Skip to main content

aidaemon_agents/
lib.rs

1//! # aidaemon-agents (experimental)
2//!
3//! Multi-agent composition for `aidaemon-core`, built only on its public API.
4//!
5//! The one pattern supported here is **agent-as-tool**: a parent agent calls a
6//! child agent the way it calls any other tool, the child runs to completion
7//! in its own session, and the parent receives a *condensed* result plus
8//! structured evidence (status, turns, per-receipt summary, child run id).
9//! Reports from Anthropic (orchestrator + condensed sub-agent results) and
10//! Cognition (parallel writers and persona crews diverge) point the same way:
11//! delegate bounded tasks, keep one writer, return summaries.
12//!
13//! Design points:
14//!
15//! - **Fresh session per call.** The child runs in
16//!   `{parent_session}/sub/{call_id}` ([`child_session_id`]), so stores and
17//!   traces can relate it to the parent without sharing a transcript.
18//! - **Explicit context.** [`ContextMode::Brief`] (default) gives the child
19//!   only the task and the optional `context` argument.
20//!   [`ContextMode::Fork`] also prepends a parent-transcript summary, which
21//!   is *caller-supplied*: a tool cannot read the parent's transcript from
22//!   [`ToolContext`], so the summary comes from a construction-time closure
23//!   ([`ForkSource`]). [`TranscriptTap`] is a ready-made hook that captures
24//!   one for you.
25//! - **Budgets roll up.** The child's usage is returned through
26//!   [`ToolOutput::with_usage`], which the kernel adds to the parent run, so
27//!   parent token limits cover delegated work. Per-child caps come from
28//!   [`ChildBudget`] (default `max_turns` 20).
29//! - **Failures are visible, and the parent decides.** A child that ends
30//!   with anything other than `Completed` becomes an error result (failed
31//!   receipt) naming the status. The parent's run does not fail with it:
32//!   the parent's model sees the error and carries on. Read each child's
33//!   answer and how it ended with `RunOutcome::tool_results` on the
34//!   parent's outcome.
35//! - **Sequential by default.** The tool is annotated
36//!   [`ToolAnnotations::WRITE`], so two children never run concurrently
37//!   unless the caller marks them read-only (e.g. research children). A
38//!   suspending child always runs alone. To run several tasks at once
39//!   without a model choosing them, use [`run_all`].
40//! - **No file access of its own.** A delegation declares
41//!   [`CallEffects::none`]: the call itself changes no file; each of the
42//!   child's own calls is judged by the child's hooks. So a parent's scope
43//!   guard and approval policy (the SDK preset's included) neither refuse
44//!   it nor ask the owner for not declaring paths; an approval mode that
45//!   asks before every write (`ApprovalMode::AllWrites`) still asks before
46//!   a delegation that is not read-only.
47//! - **Depth guard.** Nesting depth is the number of `/sub/` segments in the
48//!   session id; calls beyond `max_depth` are refused.
49//!
50//! ## Synchronous mode and approvals
51//!
52//! A child that pauses on a `before_tool` interrupt is settled inside the
53//! parent's tool call by the resolver given to
54//! [`AgentTool::interrupt_resolver`], and keeps going. The parent's tool call
55//! stays open meanwhile, so `Limits::tool_timeout` on the parent bounds the
56//! wait, and a cancelled parent stops waiting. With no resolver, or when it
57//! leaves the interruption unsettled, the child is reported as an error,
58//! unless the tool suspends.
59//!
60//! ## Durable mode
61//!
62//! With [`AgentTool::suspend_on_interrupt`], a child left interrupted pauses
63//! the parent instead: the parent's `RunStatus::Interrupted` carries the
64//! child's interruption, the child's whole state is saved in the parent's
65//! `Pending`, and the process may exit. `Agent::resume` on the parent, even
66//! in another process, passes the answer down to the child, and the parent's
67//! call ends with what the child ends with. A crash after the answer was
68//! given and before the child finished is the crash of any running call: the
69//! delegation is re-run if annotated idempotent and marked indeterminate
70//! otherwise, and nothing the child did is repeated.
71
72// Feature unification only (cargo-hakari); keeps the unused-dependency lint quiet.
73use workspace_hack as _;
74
75pub mod specialist;
76
77use std::collections::HashMap;
78use std::fmt;
79use std::sync::{Arc, Mutex};
80use std::time::Duration;
81
82use aidaemon_core::{
83    Agent, AgentBuilder, AuthorityHook, BuildError, CallEffects, CancellationToken, CoreError,
84    FinishOutcome, Hook, HookContext, InterruptResolver, Interruption, Limits, Message,
85    ModelRequest, Resolution, Role, RunOutcome, RunState, RunStatus, Tool, ToolAnnotations,
86    ToolContext, ToolError, ToolOutput, ToolResult, ToolSpec,
87};
88use async_trait::async_trait;
89use serde_json::{Value, json};
90
91/// The segment that separates a parent session from a child session.
92pub const SUB_SEGMENT: &str = "/sub/";
93
94/// Default cap on the condensed child result handed back to the parent.
95pub const DEFAULT_MAX_RESULT_CHARS: usize = 4_000;
96
97/// Default maximum nesting depth (a child of a child of a child).
98pub const DEFAULT_MAX_DEPTH: usize = 3;
99
100/// Session id for the child spawned by `call_id` inside `parent_session`.
101pub fn child_session_id(parent_session: &str, call_id: &str) -> String {
102    format!("{parent_session}{SUB_SEGMENT}{call_id}")
103}
104
105/// Run each `(agent, task)` at the same time, each in its own child session
106/// of `session` (`{session}/sub/job-{n}`), and return their outcomes in the
107/// order given. For fan-out the application decides, not the model: the
108/// runs share nothing and a failed one does not stop the others.
109pub async fn run_all<'a>(
110    session: &str,
111    jobs: impl IntoIterator<Item = (&'a Agent, String)>,
112) -> Vec<Result<RunOutcome, CoreError>> {
113    let runs = jobs.into_iter().enumerate().map(|(n, (agent, task))| {
114        let session = child_session_id(session, &format!("job-{n}"));
115        async move { agent.run(&session, task).await }
116    });
117    futures::future::join_all(runs).await
118}
119
120/// Nesting depth encoded in a session id: the number of `/sub/` segments.
121/// A top-level session has depth 0.
122pub fn session_depth(session_id: &str) -> usize {
123    session_id.matches(SUB_SEGMENT).count()
124}
125
126/// Keep the head and tail of `text` within `max_chars` characters (plus a
127/// one-line notice). The conclusion of a report is usually at the end and
128/// the framing at the start, so both survive.
129pub fn condense(text: &str, max_chars: usize) -> String {
130    let total = text.chars().count();
131    if max_chars == 0 || total <= max_chars {
132        return text.to_string();
133    }
134    let head = max_chars * 2 / 3;
135    let tail = max_chars - head;
136    let omitted = total - head - tail;
137    let head_text: String = text.chars().take(head).collect();
138    let tail_text: String = text.chars().skip(total - tail).collect();
139    format!("{head_text}\n[... {omitted} characters of sub-agent output omitted ...]\n{tail_text}")
140}
141
142/// Produces a summary of the parent's transcript for [`ContextMode::Fork`].
143/// It receives the trusted context of the delegating call (session, run and
144/// call ids) and returns `None` when no summary is available.
145pub type ForkSource = Arc<dyn Fn(&ToolContext) -> Option<String> + Send + Sync>;
146
147/// What the child sees besides the task.
148#[derive(Clone, Default)]
149pub enum ContextMode {
150    /// Only the task and the optional `context` argument.
151    #[default]
152    Brief,
153    /// The task, the optional `context` argument, and a parent-transcript
154    /// summary from the given source. If the source returns `None`, this
155    /// behaves like `Brief`.
156    Fork(ForkSource),
157}
158
159impl fmt::Debug for ContextMode {
160    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161        match self {
162            Self::Brief => f.write_str("Brief"),
163            Self::Fork(_) => f.write_str("Fork(..)"),
164        }
165    }
166}
167
168/// Per-child hard caps, applied when the child agent is built through
169/// [`AgentTool::from_builder`].
170#[derive(Debug, Clone, PartialEq)]
171pub struct ChildBudget {
172    pub max_turns: u32,
173    /// Billable-token cap for one child run.
174    pub max_tokens: Option<u64>,
175    pub max_tool_calls: Option<u32>,
176    pub timeout: Option<Duration>,
177}
178
179impl Default for ChildBudget {
180    fn default() -> Self {
181        Self {
182            max_turns: 20,
183            max_tokens: None,
184            max_tool_calls: None,
185            timeout: None,
186        }
187    }
188}
189
190impl ChildBudget {
191    /// Overlay this budget on `base` (tool timeout and output caps are kept).
192    pub fn apply(&self, mut base: Limits) -> Limits {
193        base.max_turns = self.max_turns;
194        base.max_tokens = self.max_tokens;
195        base.max_tool_calls = self.max_tool_calls;
196        base.timeout = self.timeout;
197        base
198    }
199
200    /// The budget as a complete [`Limits`], for building a child by hand.
201    pub fn limits(&self) -> Limits {
202        self.apply(Limits::default())
203    }
204}
205
206/// A child [`Agent`] exposed as a [`Tool`]. Arguments: `{task, context?}`.
207///
208/// Note that the parent's `Limits::tool_timeout` (default 120 s) bounds the
209/// whole child run; raise it on parents that delegate long tasks.
210#[derive(Clone)]
211pub struct AgentTool {
212    agent: Agent,
213    name: String,
214    description: String,
215    mode: ContextMode,
216    max_result_chars: usize,
217    annotations: ToolAnnotations,
218    max_depth: usize,
219    resolver: Option<Arc<dyn InterruptResolver>>,
220    suspend_on_interrupt: bool,
221}
222
223impl fmt::Debug for AgentTool {
224    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225        f.debug_struct("AgentTool")
226            .field("agent", &self.agent.id())
227            .field("name", &self.name)
228            .field("mode", &self.mode)
229            .field("max_result_chars", &self.max_result_chars)
230            .field("annotations", &self.annotations)
231            .field("max_depth", &self.max_depth)
232            .finish()
233    }
234}
235
236impl AgentTool {
237    /// Wrap an already-built agent. The child keeps the limits it was built
238    /// with; call [`AgentTool::budget`] (or use [`AgentTool::from_builder`])
239    /// to give it child-sized caps.
240    pub fn new(agent: Agent) -> Self {
241        let name = sanitize_tool_name(agent.id());
242        let description = format!(
243            "Delegate a self-contained task to the `{}` sub-agent. It starts with no \
244             memory of this conversation: put everything it needs in `task` and \
245             `context`. Returns its final answer.",
246            agent.id()
247        );
248        Self {
249            agent,
250            name,
251            description,
252            mode: ContextMode::Brief,
253            max_result_chars: DEFAULT_MAX_RESULT_CHARS,
254            annotations: ToolAnnotations::WRITE,
255            max_depth: DEFAULT_MAX_DEPTH,
256            resolver: None,
257            suspend_on_interrupt: false,
258        }
259    }
260
261    /// Build the child from `builder` with `budget` applied. This replaces
262    /// any limits already set on the builder.
263    /// Give the wrapped agent child-sized caps, replacing its own limits.
264    pub fn budget(mut self, budget: ChildBudget) -> Self {
265        self.agent = self.agent.with_limits(budget.limits());
266        self
267    }
268
269    pub fn from_builder(builder: AgentBuilder, budget: ChildBudget) -> Result<Self, BuildError> {
270        let agent = builder.limits(budget.limits()).build()?;
271        Ok(Self::new(agent))
272    }
273
274    pub fn name(mut self, name: impl Into<String>) -> Self {
275        self.name = name.into();
276        self
277    }
278
279    pub fn description(mut self, description: impl Into<String>) -> Self {
280        self.description = description.into();
281        self
282    }
283
284    pub fn context_mode(mut self, mode: ContextMode) -> Self {
285        self.mode = mode;
286        self
287    }
288
289    /// Shorthand for `context_mode(ContextMode::Fork(source))`.
290    pub fn fork_from(self, source: ForkSource) -> Self {
291        self.context_mode(ContextMode::Fork(source))
292    }
293
294    /// Cap on the condensed result (head + tail). 0 disables condensing.
295    pub fn max_result_chars(mut self, chars: usize) -> Self {
296        self.max_result_chars = chars;
297        self
298    }
299
300    pub fn with_annotations(mut self, annotations: ToolAnnotations) -> Self {
301        self.annotations = annotations;
302        self
303    }
304
305    /// Mark the child read-only so several calls in one turn run
306    /// concurrently. Only do this for children whose tools are all
307    /// read-only (research, search, review).
308    pub fn read_only(self) -> Self {
309        self.with_annotations(ToolAnnotations::READ_ONLY)
310    }
311
312    /// Maximum session depth a child may run at (top level is 0, its child
313    /// is 1). Calls that would exceed it are refused.
314    pub fn max_depth(mut self, depth: usize) -> Self {
315        self.max_depth = depth;
316        self
317    }
318
319    /// Settle the child's interruptions with `resolver` instead of ending
320    /// the delegation with an error. It sees the child's state, whose
321    /// `session_id` and `parent_run` name where the child came from.
322    pub fn interrupt_resolver(mut self, resolver: Arc<dyn InterruptResolver>) -> Self {
323        self.resolver = Some(resolver);
324        self
325    }
326
327    /// Pause the parent durably for a child left interrupted, instead of
328    /// ending the delegation with an error (see the crate docs). A resolver
329    /// set with [`AgentTool::interrupt_resolver`] is asked first; only what
330    /// it leaves unsettled pauses the parent. A call of this tool runs alone,
331    /// even when the tool is marked read-only.
332    pub fn suspend_on_interrupt(mut self) -> Self {
333        self.suspend_on_interrupt = true;
334        self
335    }
336
337    pub fn agent(&self) -> &Agent {
338        &self.agent
339    }
340
341    /// The child agent, answering to everything the parent does: its
342    /// authority stacks on the child's own. Applied afresh on every resume,
343    /// so a resumed child can never do more than the parent may now.
344    fn child_for(&self, ctx: &ToolContext) -> Agent {
345        match &ctx.authority {
346            Some(authority) => self.agent.with_hook(AuthorityHook::new(authority.clone())),
347            None => self.agent.clone(),
348        }
349    }
350
351    /// The tool result for a child run that ended or paused.
352    fn conclude(&self, outcome: RunOutcome, session: &str) -> ToolResult {
353        if self.suspend_on_interrupt && matches!(outcome.status, RunStatus::Interrupted { .. }) {
354            return Ok(ToolOutput::suspended(outcome.state));
355        }
356        let details = self.details(&outcome, session);
357        let usage = outcome.usage();
358        let output = match &outcome.status {
359            // Completed means the child stopped, not that it did the work:
360            // unmet requirements are passed up so the caller cannot mistake
361            // a stop for a success.
362            RunStatus::Completed if !outcome.unmet().is_empty() => {
363                let text = condense(
364                    outcome.final_text.as_deref().unwrap_or_default(),
365                    self.max_result_chars,
366                );
367                let mut message = format!(
368                    "sub-agent `{}` stopped without finishing; still unmet:",
369                    self.name
370                );
371                for line in outcome.unmet() {
372                    message.push_str("\n- ");
373                    message.push_str(line);
374                }
375                message.push_str("\n\nIts reply:\n");
376                message.push_str(&text);
377                ToolOutput::text(message)
378            }
379            RunStatus::Completed => {
380                let text = outcome.final_text.as_deref().unwrap_or_default();
381                ToolOutput::text(condense(text, self.max_result_chars))
382            }
383            // A tool in the sub-agent ended its run: the finish reply is the
384            // answer. Partial work says so; a blocked one is a failure the
385            // caller should react to.
386            RunStatus::Finished {
387                outcome: finish, ..
388            } => {
389                let text = condense(
390                    outcome.final_text.as_deref().unwrap_or_default(),
391                    self.max_result_chars,
392                );
393                match finish {
394                    FinishOutcome::Succeeded => ToolOutput::text(text),
395                    FinishOutcome::Partial => ToolOutput::text(format!(
396                        "sub-agent `{}` finished part of the task:\n{text}",
397                        self.name
398                    )),
399                    _ => {
400                        ToolOutput::error(format!("sub-agent `{}` is blocked:\n{text}", self.name))
401                    }
402                }
403            }
404            RunStatus::Interrupted { interruption } if self.resolver.is_some() => {
405                ToolOutput::error(format!(
406                    "sub-agent `{}` paused waiting for approval of `{}` ({}) and it was not \
407                     settled, so the call did not run. Do it yourself (your own approval policy \
408                     applies) or ask the user.",
409                    self.name, interruption.call.name, interruption.reason
410                ))
411            }
412            RunStatus::Interrupted { interruption } => ToolOutput::error(format!(
413                "sub-agent `{}` paused waiting for approval of `{}` ({}). Sub-agents that need \
414                 approval are not supported in synchronous agent-as-tool mode, so the call did \
415                 not run. Do it yourself (your own approval policy applies) or ask the user.",
416                self.name, interruption.call.name, interruption.reason
417            )),
418            status => {
419                let mut message = format!(
420                    "sub-agent `{}` did not complete: {}.",
421                    self.name,
422                    status_label(status)
423                );
424                if let Some(partial) = last_assistant_text(&outcome.state.messages) {
425                    message.push_str("\nLast message from the sub-agent:\n");
426                    message.push_str(&condense(partial, self.max_result_chars));
427                }
428                ToolOutput::error(message)
429            }
430        };
431        Ok(output.with_details(details).with_usage(usage))
432    }
433
434    fn could_not_run(&self, error: CoreError) -> ToolError {
435        ToolError(format!("sub-agent `{}` could not run: {error}", self.name))
436    }
437
438    fn compose_input(&self, task: &str, context: Option<&str>, ctx: &ToolContext) -> String {
439        let summary = match &self.mode {
440            ContextMode::Brief => None,
441            ContextMode::Fork(source) => source(ctx).filter(|s| !s.trim().is_empty()),
442        };
443        let context = context.filter(|c| !c.trim().is_empty());
444        match summary {
445            None => match context {
446                None => task.to_string(),
447                Some(context) => format!("{task}\n\nContext:\n{context}"),
448            },
449            Some(summary) => {
450                let mut input = format!(
451                    "[Summary of the delegating agent's conversation]\n{summary}\n\n[Task]\n{task}"
452                );
453                if let Some(context) = context {
454                    input.push_str(&format!("\n\n[Context]\n{context}"));
455                }
456                input
457            }
458        }
459    }
460
461    fn details(&self, outcome: &RunOutcome, session: &str) -> Value {
462        let receipts: Vec<Value> = outcome
463            .receipts()
464            .iter()
465            .map(|r| json!({"tool": r.tool, "status": r.status}))
466            .collect();
467        json!({
468            "sub_agent": self.agent.id(),
469            "child_run_id": outcome.state.run_id,
470            "child_session_id": session,
471            "status": outcome.status,
472            "succeeded": outcome.is_succeeded(),
473            "unmet": outcome.unmet(),
474            "turns": outcome.turns(),
475            "receipts": receipts,
476            "usage": outcome.usage(),
477        })
478    }
479}
480
481/// `agent.as_tool(name, description)`.
482pub trait AgentExt {
483    fn as_tool(&self, name: impl Into<String>, description: impl Into<String>) -> AgentTool;
484}
485
486impl AgentExt for Agent {
487    fn as_tool(&self, name: impl Into<String>, description: impl Into<String>) -> AgentTool {
488        AgentTool::new(self.clone())
489            .name(name)
490            .description(description)
491    }
492}
493
494#[async_trait]
495impl Tool for AgentTool {
496    fn spec(&self) -> ToolSpec {
497        ToolSpec {
498            name: self.name.clone(),
499            description: self.description.clone(),
500            parameters: json!({
501                "type": "object",
502                "properties": {
503                    "task": {
504                        "type": "string",
505                        "description": "The complete, self-contained task for the sub-agent."
506                    },
507                    "context": {
508                        "type": "string",
509                        "description": "Optional facts, constraints or prior findings the sub-agent needs."
510                    }
511                },
512                "required": ["task"],
513                "additionalProperties": false
514            }),
515        }
516    }
517
518    fn annotations(&self) -> ToolAnnotations {
519        self.annotations
520    }
521
522    /// The delegation itself changes nothing: the child's own calls carry
523    /// their effects, judged by the child's hooks.
524    fn effects(&self, _arguments: &Value) -> CallEffects {
525        CallEffects::none()
526    }
527
528    fn validate(&self, arguments: &Value) -> Result<(), String> {
529        let Some(object) = arguments.as_object() else {
530            return Err("arguments must be a JSON object".into());
531        };
532        match object.get("task").and_then(Value::as_str) {
533            Some(task) if !task.trim().is_empty() => {}
534            Some(_) => return Err("`task` must not be empty".into()),
535            None => return Err("missing required string argument: task".into()),
536        }
537        match object.get("context") {
538            None | Some(Value::Null) | Some(Value::String(_)) => {}
539            Some(_) => return Err("`context` must be a string".into()),
540        }
541        if let Some(extra) = object.keys().find(|k| *k != "task" && *k != "context") {
542            return Err(format!("unexpected argument `{extra}`"));
543        }
544        Ok(())
545    }
546
547    async fn call(&self, arguments: Value, ctx: &ToolContext) -> ToolResult {
548        let depth = session_depth(&ctx.session_id) + 1;
549        if depth > self.max_depth {
550            return Ok(ToolOutput::error(format!(
551                "Refused: delegating to `{}` would run a sub-agent at depth {depth}, beyond the \
552                 maximum of {}. Do this part of the work yourself.",
553                self.name, self.max_depth
554            ))
555            .with_details(json!({
556                "refused": "max_depth",
557                "depth": depth,
558                "max_depth": self.max_depth,
559            })));
560        }
561
562        let task = arguments["task"].as_str().unwrap_or_default();
563        let context = arguments.get("context").and_then(Value::as_str);
564        let input = self.compose_input(task, context, ctx);
565        let session = child_session_id(&ctx.session_id, &ctx.call_id);
566
567        // A decline in the child binds the parent, and the other way round.
568        let agent = self.child_for(ctx);
569        let mut state = RunState::new(agent.id(), &session, &input).with_parent(ctx.run_id);
570        if let Some(declines) = &ctx.declines {
571            state = state.share_declines(declines.clone());
572        }
573        let outcome = match &self.resolver {
574            Some(resolver) => {
575                let resolver = UntilCancelled {
576                    inner: resolver.as_ref(),
577                    cancel: ctx.cancel.clone(),
578                };
579                agent
580                    .run_resolving(state, ctx.cancel.clone(), &resolver)
581                    .await
582            }
583            None => agent.run_from(state, ctx.cancel.clone()).await,
584        }
585        .map_err(|e| self.could_not_run(e))?;
586        self.conclude(outcome, &session)
587    }
588
589    fn suspends(&self) -> bool {
590        self.suspend_on_interrupt
591    }
592
593    async fn resume_child(
594        &self,
595        mut child: RunState,
596        resolution: Resolution,
597        ctx: &ToolContext,
598    ) -> ToolResult {
599        // Declines are runtime handles, not saved state: join the set in
600        // force now, so the child and the parent bind each other again.
601        if let Some(declines) = &ctx.declines {
602            child = child.share_declines(declines.clone());
603        }
604        let session = child.session_id.clone();
605        let agent = self.child_for(ctx);
606        let outcome = match &self.resolver {
607            Some(resolver) => {
608                let resolver = UntilCancelled {
609                    inner: resolver.as_ref(),
610                    cancel: ctx.cancel.clone(),
611                };
612                agent
613                    .resume_resolving(child, resolution, ctx.cancel.clone(), &resolver)
614                    .await
615            }
616            None => {
617                agent
618                    .resume_with_cancel(child, resolution, ctx.cancel.clone())
619                    .await
620            }
621        }
622        .map_err(|e| self.could_not_run(e))?;
623        self.conclude(outcome, &session)
624    }
625}
626
627/// Stops waiting for an answer once the parent is cancelled.
628struct UntilCancelled<'a> {
629    inner: &'a dyn InterruptResolver,
630    cancel: CancellationToken,
631}
632
633#[async_trait]
634impl InterruptResolver for UntilCancelled<'_> {
635    async fn resolve(&self, state: &RunState, interruption: &Interruption) -> Option<Resolution> {
636        self.cancel
637            .run_until_cancelled(self.inner.resolve(state, interruption))
638            .await
639            .flatten()
640    }
641}
642
643/// A short machine-derived label for a terminal status.
644pub fn status_label(status: &RunStatus) -> String {
645    match status {
646        RunStatus::Completed => "completed".into(),
647        RunStatus::Interrupted { interruption } => {
648            format!("interrupted before `{}`", interruption.call.name)
649        }
650        RunStatus::LimitReached { limit } => {
651            let kind = serde_json::to_value(limit)
652                .ok()
653                .and_then(|v| v.as_str().map(str::to_string))
654                .unwrap_or_else(|| format!("{limit:?}"));
655            format!("limit reached ({kind})")
656        }
657        RunStatus::Stopped { reason } => format!("stopped ({reason})"),
658        RunStatus::Stuck { signal } => format!("stuck ({signal:?})"),
659        RunStatus::Cancelled => "cancelled".into(),
660        RunStatus::ProviderFailed { error } => format!("provider failed ({error})"),
661        RunStatus::Finished { outcome, tool } => {
662            let how = match outcome {
663                FinishOutcome::Succeeded => "succeeded",
664                FinishOutcome::Partial => "partial",
665                FinishOutcome::Blocked => "blocked",
666                _ => "ended",
667            };
668            format!("finished by `{tool}` ({how})")
669        }
670        other => format!("{other:?}"),
671    }
672}
673
674fn last_assistant_text(messages: &[Message]) -> Option<&str> {
675    messages
676        .iter()
677        .rev()
678        .filter(|m| m.role == Role::Assistant)
679        .map(|m| m.content.as_str())
680        .find(|c| !c.trim().is_empty())
681}
682
683fn sanitize_tool_name(id: &str) -> String {
684    let mut name: String = id
685        .chars()
686        .map(|c| {
687            if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
688                c
689            } else {
690                '_'
691            }
692        })
693        .take(64)
694        .collect();
695    if name.is_empty() {
696        name.push_str("sub_agent");
697    }
698    name
699}
700
701/// A hook that records a compact summary of each session's transcript so a
702/// [`ContextMode::Fork`] child can see what the parent has been doing.
703///
704/// Register it on the **parent** and pass [`TranscriptTap::source`] to
705/// [`AgentTool::fork_from`]. The summary is taken in `before_model`, so it
706/// reflects the transcript up to (not including) the turn that delegates.
707#[derive(Clone)]
708pub struct TranscriptTap {
709    summaries: Arc<Mutex<HashMap<String, String>>>,
710    max_messages: usize,
711    max_chars_per_message: usize,
712}
713
714impl Default for TranscriptTap {
715    fn default() -> Self {
716        Self::new(12, 400)
717    }
718}
719
720impl TranscriptTap {
721    pub fn new(max_messages: usize, max_chars_per_message: usize) -> Self {
722        Self {
723            summaries: Arc::new(Mutex::new(HashMap::new())),
724            max_messages,
725            max_chars_per_message,
726        }
727    }
728
729    /// The latest summary captured for `session_id`.
730    pub fn summary(&self, session_id: &str) -> Option<String> {
731        self.summaries
732            .lock()
733            .ok()
734            .and_then(|m| m.get(session_id).cloned())
735    }
736
737    /// Forget a session (call when it ends to bound memory).
738    pub fn clear(&self, session_id: &str) {
739        if let Ok(mut map) = self.summaries.lock() {
740            map.remove(session_id);
741        }
742    }
743
744    /// A [`ForkSource`] reading this tap by the delegating call's session.
745    pub fn source(&self) -> ForkSource {
746        let tap = self.clone();
747        Arc::new(move |ctx: &ToolContext| tap.summary(&ctx.session_id))
748    }
749
750    fn summarize(&self, messages: &[Message]) -> String {
751        let start = messages.len().saturating_sub(self.max_messages);
752        let mut lines = Vec::new();
753        for message in &messages[start..] {
754            let role = match message.role {
755                Role::System => "system",
756                Role::User => "user",
757                Role::Assistant => "assistant",
758                Role::Tool => "tool result",
759            };
760            let content = condense(message.content.trim(), self.max_chars_per_message);
761            if !content.is_empty() {
762                lines.push(format!("{role}: {content}"));
763            }
764            for call in &message.tool_calls {
765                lines.push(format!("assistant called `{}`", call.name));
766            }
767        }
768        lines.join("\n")
769    }
770}
771
772#[async_trait]
773impl Hook for TranscriptTap {
774    async fn before_model(&self, ctx: &HookContext<'_>, _request: &mut ModelRequest) {
775        let summary = self.summarize(ctx.messages);
776        if let Ok(mut map) = self.summaries.lock() {
777            map.insert(ctx.session_id.to_string(), summary);
778        }
779    }
780}
781
782#[cfg(test)]
783mod tests {
784    use super::*;
785
786    #[test]
787    fn depth_counts_sub_segments() {
788        assert_eq!(session_depth("telegram:synthetic-user-1"), 0);
789        let child = child_session_id("telegram:synthetic-user-1", "c1");
790        assert_eq!(child, "telegram:synthetic-user-1/sub/c1");
791        assert_eq!(session_depth(&child), 1);
792        assert_eq!(session_depth(&child_session_id(&child, "c2")), 2);
793    }
794
795    #[test]
796    fn condense_keeps_head_and_tail() {
797        let text: String = (0..1000)
798            .map(|i| char::from(b'a' + (i % 26) as u8))
799            .collect();
800        let out = condense(&text, 90);
801        assert!(out.starts_with(&text[..60]));
802        assert!(out.ends_with(&text[970..]));
803        assert!(out.contains("910 characters"));
804        assert_eq!(condense("short", 90), "short");
805        assert_eq!(condense(&text, 0), text);
806    }
807
808    #[test]
809    fn tool_names_are_sanitized() {
810        assert_eq!(sanitize_tool_name("research agent.v2"), "research_agent_v2");
811        assert_eq!(sanitize_tool_name(""), "sub_agent");
812    }
813
814    #[test]
815    fn budget_overlays_limits() {
816        let limits = ChildBudget {
817            max_tokens: Some(500),
818            ..ChildBudget::default()
819        }
820        .limits();
821        assert_eq!(limits.max_turns, 20);
822        assert_eq!(limits.max_tokens, Some(500));
823    }
824}