1use 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
91pub const SUB_SEGMENT: &str = "/sub/";
93
94pub const DEFAULT_MAX_RESULT_CHARS: usize = 4_000;
96
97pub const DEFAULT_MAX_DEPTH: usize = 3;
99
100pub fn child_session_id(parent_session: &str, call_id: &str) -> String {
102 format!("{parent_session}{SUB_SEGMENT}{call_id}")
103}
104
105pub 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
120pub fn session_depth(session_id: &str) -> usize {
123 session_id.matches(SUB_SEGMENT).count()
124}
125
126pub 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
142pub type ForkSource = Arc<dyn Fn(&ToolContext) -> Option<String> + Send + Sync>;
146
147#[derive(Clone, Default)]
149pub enum ContextMode {
150 #[default]
152 Brief,
153 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#[derive(Debug, Clone, PartialEq)]
171pub struct ChildBudget {
172 pub max_turns: u32,
173 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 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 pub fn limits(&self) -> Limits {
202 self.apply(Limits::default())
203 }
204}
205
206#[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 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 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 pub fn fork_from(self, source: ForkSource) -> Self {
291 self.context_mode(ContextMode::Fork(source))
292 }
293
294 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 pub fn read_only(self) -> Self {
309 self.with_annotations(ToolAnnotations::READ_ONLY)
310 }
311
312 pub fn max_depth(mut self, depth: usize) -> Self {
315 self.max_depth = depth;
316 self
317 }
318
319 pub fn interrupt_resolver(mut self, resolver: Arc<dyn InterruptResolver>) -> Self {
323 self.resolver = Some(resolver);
324 self
325 }
326
327 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 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 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 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 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
481pub 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 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 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 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
627struct 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
643pub 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#[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 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 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 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}