Skip to main content

atman_runtime/tools/
stdlib.rs

1use crate::approval::{ApprovalOutcome, request_approval};
2use crate::error::RuntimeError;
3use crate::tool::{BoxFut, Tier, Tool, ToolArgs, ToolCtx, ToolResult};
4use crate::value::Value;
5
6pub struct ShellQuote;
7
8impl Tool for ShellQuote {
9    fn name(&self) -> &str {
10        "shell_quote"
11    }
12
13    fn tier(&self) -> Tier {
14        Tier::Zero
15    }
16
17    fn call<'a>(&'a self, args: ToolArgs, _ctx: &'a ToolCtx) -> BoxFut<'a, ToolResult> {
18        Box::pin(async move {
19            let s = extract_string(&args, "s", 0)?;
20            Ok(Value::Str(shell_quote(&s)))
21        })
22    }
23}
24
25pub fn shell_quote(s: &str) -> String {
26    // POSIX-safe: wrap in single quotes, escape any internal ' as '\''.
27    let mut out = String::with_capacity(s.len() + 2);
28    out.push('\'');
29    for c in s.chars() {
30        if c == '\'' {
31            out.push_str("'\\''");
32        } else {
33            out.push(c);
34        }
35    }
36    out.push('\'');
37    out
38}
39
40pub struct Len;
41
42impl Tool for Len {
43    fn name(&self) -> &str {
44        "len"
45    }
46
47    fn tier(&self) -> Tier {
48        Tier::Zero
49    }
50
51    fn call<'a>(&'a self, args: ToolArgs, _ctx: &'a ToolCtx) -> BoxFut<'a, ToolResult> {
52        Box::pin(async move {
53            let v = args.positional(0)?;
54            match v {
55                Value::List(items) => Ok(Value::Int(items.len() as i64)),
56                Value::Str(s) => Ok(Value::Int(s.chars().count() as i64)),
57                other => Err(RuntimeError::TypeMismatch {
58                    expected: "list or string".into(),
59                    actual: other.kind_name().into(),
60                }),
61            }
62        })
63    }
64}
65
66pub struct Head;
67
68impl Tool for Head {
69    fn name(&self) -> &str {
70        "head"
71    }
72
73    fn tier(&self) -> Tier {
74        Tier::Zero
75    }
76
77    fn call<'a>(&'a self, args: ToolArgs, _ctx: &'a ToolCtx) -> BoxFut<'a, ToolResult> {
78        Box::pin(async move {
79            match args.positional(0)? {
80                Value::List(items) => items
81                    .first()
82                    .cloned()
83                    .ok_or_else(|| RuntimeError::ToolFailed("head: empty list".into())),
84                other => Err(RuntimeError::TypeMismatch {
85                    expected: "list".into(),
86                    actual: other.kind_name().into(),
87                }),
88            }
89        })
90    }
91}
92
93pub struct Tail;
94
95impl Tool for Tail {
96    fn name(&self) -> &str {
97        "tail"
98    }
99
100    fn tier(&self) -> Tier {
101        Tier::Zero
102    }
103
104    fn call<'a>(&'a self, args: ToolArgs, _ctx: &'a ToolCtx) -> BoxFut<'a, ToolResult> {
105        Box::pin(async move {
106            match args.positional(0)? {
107                Value::List(items) if !items.is_empty() => Ok(Value::List(items[1..].to_vec())),
108                Value::List(_) => Err(RuntimeError::ToolFailed("tail: empty list".into())),
109                other => Err(RuntimeError::TypeMismatch {
110                    expected: "list".into(),
111                    actual: other.kind_name().into(),
112                }),
113            }
114        })
115    }
116}
117
118pub struct IsEmpty;
119
120impl Tool for IsEmpty {
121    fn name(&self) -> &str {
122        "is_empty"
123    }
124
125    fn tier(&self) -> Tier {
126        Tier::Zero
127    }
128
129    fn call<'a>(&'a self, args: ToolArgs, _ctx: &'a ToolCtx) -> BoxFut<'a, ToolResult> {
130        Box::pin(async move {
131            let v = args.positional(0)?;
132            match v {
133                Value::List(items) => Ok(Value::Bool(items.is_empty())),
134                Value::Str(s) => Ok(Value::Bool(s.is_empty())),
135                other => Err(RuntimeError::TypeMismatch {
136                    expected: "list or string".into(),
137                    actual: other.kind_name().into(),
138                }),
139            }
140        })
141    }
142}
143
144pub struct EstimateTokens;
145
146impl Tool for EstimateTokens {
147    fn name(&self) -> &str {
148        "estimate_tokens"
149    }
150    fn tier(&self) -> Tier {
151        Tier::Zero
152    }
153    fn call<'a>(&'a self, args: ToolArgs, _ctx: &'a ToolCtx) -> BoxFut<'a, ToolResult> {
154        Box::pin(async move {
155            let v = args.positional(0)?;
156            match v {
157                Value::List(items) => {
158                    let mut msgs = Vec::with_capacity(items.len());
159                    for it in items {
160                        match it {
161                            Value::Message(m) => msgs.push(m.clone()),
162                            other => {
163                                return Err(RuntimeError::TypeMismatch {
164                                    expected: "list of message".into(),
165                                    actual: other.kind_name().into(),
166                                });
167                            }
168                        }
169                    }
170                    let n = crate::compaction::estimate_tokens_for_messages(&msgs);
171                    Ok(Value::Int(n as i64))
172                }
173                Value::Message(m) => Ok(Value::Int(
174                    crate::compaction::estimate_tokens_for_message(m) as i64,
175                )),
176                Value::Str(s) => {
177                    let approx = ((s.len() as f64) / 3.5).ceil() as i64;
178                    Ok(Value::Int(approx))
179                }
180                other => Err(RuntimeError::TypeMismatch {
181                    expected: "message | list of message | string".into(),
182                    actual: other.kind_name().into(),
183                }),
184            }
185        })
186    }
187}
188
189pub struct FindCompactRange;
190
191impl Tool for FindCompactRange {
192    fn name(&self) -> &str {
193        "find_compact_range"
194    }
195    fn tier(&self) -> Tier {
196        Tier::Zero
197    }
198    fn call<'a>(&'a self, args: ToolArgs, _ctx: &'a ToolCtx) -> BoxFut<'a, ToolResult> {
199        Box::pin(async move {
200            let messages = extract_message_list(&args, "messages", 0)?;
201            let budget = extract_int(&args, "budget", 1)? as u64;
202            match crate::compaction::find_compact_range(&messages, budget) {
203                Some(range) => Ok(Value::Struct(vec![
204                    ("start".into(), Value::Int(range.start as i64)),
205                    ("end".into(), Value::Int(range.end as i64)),
206                    (
207                        "tokens_saved".into(),
208                        Value::Int(range.tokens_saved_estimate as i64),
209                    ),
210                    ("found".into(), Value::Bool(true)),
211                ])),
212                None => Ok(Value::Struct(vec![
213                    ("start".into(), Value::Int(0)),
214                    ("end".into(), Value::Int(0)),
215                    ("tokens_saved".into(), Value::Int(0)),
216                    ("found".into(), Value::Bool(false)),
217                ])),
218            }
219        })
220    }
221}
222
223pub struct ReplaceMessagesRange;
224
225impl Tool for ReplaceMessagesRange {
226    fn name(&self) -> &str {
227        "replace_messages_range"
228    }
229    fn tier(&self) -> Tier {
230        Tier::Zero
231    }
232    fn call<'a>(&'a self, args: ToolArgs, ctx: &'a ToolCtx) -> BoxFut<'a, ToolResult> {
233        Box::pin(async move {
234            let messages = extract_message_list(&args, "messages", 0)?;
235            let start = extract_int(&args, "start", 1)? as usize;
236            let end = extract_int(&args, "end", 2)? as usize;
237            let summary = extract_string_arg(&args, "summary", 3)?;
238            if start > end || end > messages.len() {
239                return Err(RuntimeError::ToolFailed(format!(
240                    "replace_messages_range: invalid range start={start} end={end} len={}",
241                    messages.len()
242                )));
243            }
244            let before_tokens = crate::compaction::estimate_tokens_for_messages(&messages);
245            let seq_span = messages
246                .get(start..end.min(messages.len()))
247                .and_then(|slice| {
248                    Some((
249                        slice.first().map(|_| start as u64)?,
250                        slice.last().map(|_| end.saturating_sub(1) as u64)?,
251                    ))
252                })
253                .unwrap_or((start as u64, end.saturating_sub(1) as u64));
254            let range = crate::compaction::CompactRange {
255                start,
256                end,
257                tokens_saved_estimate: 0,
258            };
259            let turn_id = messages
260                .first()
261                .map(|m| m.turn_id.clone())
262                .unwrap_or_else(crate::event::TurnId::now);
263            let out =
264                crate::compaction::replace_range_with_summary(&messages, &range, summary, turn_id);
265            let after_tokens = crate::compaction::estimate_tokens_for_messages(&out);
266            if let Some(sink) = &ctx.events {
267                sink.mark_compacted();
268                sink.emit(crate::event::Event::ContextCompact {
269                    session_id: ctx
270                        .turn_id
271                        .as_ref()
272                        .map(|t| t.0.to_string())
273                        .unwrap_or_default(),
274                    before_tokens,
275                    after_tokens,
276                    compacted_range_start: seq_span.0,
277                    compacted_range_end: seq_span.1,
278                    summary_text: None,
279                    replacement_msg_seq: None,
280                });
281            }
282            if let Some(tx) = &ctx.lifecycle_fire_tx {
283                let _ = tx.send(atman_dsl::ast::LifecycleEvent::ContextCompact);
284            }
285            let list: Vec<Value> = out.into_iter().map(Value::Message).collect();
286            Ok(Value::List(list))
287        })
288    }
289}
290
291fn extract_message_list(
292    args: &ToolArgs,
293    name: &str,
294    pos: usize,
295) -> Result<Vec<crate::message::Message>, RuntimeError> {
296    let value = match args.named(name) {
297        Some(v) => v,
298        None => args.positional(pos)?,
299    };
300    match value {
301        Value::List(items) => {
302            let mut out = Vec::with_capacity(items.len());
303            for it in items {
304                match it {
305                    Value::Message(m) => out.push(m.clone()),
306                    other => {
307                        return Err(RuntimeError::TypeMismatch {
308                            expected: "list of message".into(),
309                            actual: other.kind_name().into(),
310                        });
311                    }
312                }
313            }
314            Ok(out)
315        }
316        other => Err(RuntimeError::TypeMismatch {
317            expected: "list of message".into(),
318            actual: other.kind_name().into(),
319        }),
320    }
321}
322
323fn extract_int(args: &ToolArgs, name: &str, pos: usize) -> Result<i64, RuntimeError> {
324    let value = match args.named(name) {
325        Some(v) => v,
326        None => args.positional(pos)?,
327    };
328    match value {
329        Value::Int(n) => Ok(*n),
330        other => Err(RuntimeError::TypeMismatch {
331            expected: "int".into(),
332            actual: other.kind_name().into(),
333        }),
334    }
335}
336
337fn extract_string_arg(args: &ToolArgs, name: &str, pos: usize) -> Result<String, RuntimeError> {
338    let value = match args.named(name) {
339        Some(v) => v,
340        None => args.positional(pos)?,
341    };
342    match value {
343        Value::Str(s) => Ok(s.clone()),
344        other => Err(RuntimeError::TypeMismatch {
345            expected: "string".into(),
346            actual: other.kind_name().into(),
347        }),
348    }
349}
350
351pub struct RenderPromptXml;
352pub struct RenderPromptMarkdown;
353pub struct RenderPromptTerse;
354
355fn extract_prompt_spec(v: &Value) -> Result<PromptSpec<'_>, RuntimeError> {
356    let Value::Struct(fields) = v else {
357        return Err(RuntimeError::TypeMismatch {
358            expected: "struct { role?, context?, task, examples?, schema? }".into(),
359            actual: v.kind_name().into(),
360        });
361    };
362    let get = |k: &str| fields.iter().find(|(n, _)| n == k).map(|(_, v)| v);
363    let task = match get("task") {
364        Some(Value::Str(s)) => s.clone(),
365        Some(other) => {
366            return Err(RuntimeError::TypeMismatch {
367                expected: "string (task)".into(),
368                actual: other.kind_name().into(),
369            });
370        }
371        None => return Err(RuntimeError::MissingArg("prompt.task".into())),
372    };
373    let role = match get("role") {
374        Some(Value::Str(s)) => Some(s.clone()),
375        Some(Value::Unit) | None => None,
376        Some(other) => {
377            return Err(RuntimeError::TypeMismatch {
378                expected: "string (role)".into(),
379                actual: other.kind_name().into(),
380            });
381        }
382    };
383    let context = get("context");
384    let schema = match get("schema") {
385        Some(Value::Str(s)) => Some(s.clone()),
386        _ => None,
387    };
388    let examples = match get("examples") {
389        Some(Value::List(items)) => items.iter().collect(),
390        _ => Vec::new(),
391    };
392    Ok(PromptSpec {
393        role,
394        context,
395        task,
396        examples,
397        schema,
398    })
399}
400
401struct PromptSpec<'a> {
402    role: Option<String>,
403    context: Option<&'a Value>,
404    task: String,
405    examples: Vec<&'a Value>,
406    schema: Option<String>,
407}
408
409fn json_str(v: &Value) -> String {
410    serde_json::to_string_pretty(&v.to_json()).unwrap_or_default()
411}
412
413fn render_xml(spec: &PromptSpec<'_>) -> String {
414    let mut out = String::new();
415    if let Some(role) = &spec.role {
416        out.push_str(&format!("<role>{}</role>\n", role));
417    }
418    if let Some(ctx) = spec.context {
419        out.push_str(&format!("<context>\n{}\n</context>\n", json_str(ctx)));
420    }
421    if !spec.examples.is_empty() {
422        out.push_str("<examples>\n");
423        for (i, ex) in spec.examples.iter().enumerate() {
424            out.push_str(&format!(
425                "  <example n=\"{}\">\n{}\n  </example>\n",
426                i + 1,
427                json_str(ex)
428            ));
429        }
430        out.push_str("</examples>\n");
431    }
432    out.push_str(&format!("<task>{}</task>\n", spec.task));
433    if let Some(schema) = &spec.schema {
434        out.push_str(&format!("<schema>{}</schema>\n", schema));
435    }
436    out
437}
438
439fn render_markdown(spec: &PromptSpec<'_>) -> String {
440    let mut out = String::new();
441    if let Some(role) = &spec.role {
442        out.push_str(&format!("# Role\n{}\n\n", role));
443    }
444    if let Some(ctx) = spec.context {
445        out.push_str(&format!("# Context\n```json\n{}\n```\n\n", json_str(ctx)));
446    }
447    if !spec.examples.is_empty() {
448        out.push_str("# Examples\n");
449        for (i, ex) in spec.examples.iter().enumerate() {
450            out.push_str(&format!(
451                "{}. `{}`\n",
452                i + 1,
453                json_str(ex).replace('\n', " ")
454            ));
455        }
456        out.push('\n');
457    }
458    out.push_str(&format!("# Task\n{}\n", spec.task));
459    if let Some(schema) = &spec.schema {
460        out.push_str(&format!("\n# Schema\n{}\n", schema));
461    }
462    out
463}
464
465fn render_terse(spec: &PromptSpec<'_>) -> String {
466    let mut out = String::new();
467    if let Some(role) = &spec.role {
468        out.push_str(&format!("Role: {}\n", role));
469    }
470    if let Some(ctx) = spec.context {
471        out.push_str(&format!("Context: {}\n", json_str(ctx).replace('\n', " ")));
472    }
473    out.push_str(&format!("Task: {}\n", spec.task));
474    if let Some(schema) = &spec.schema {
475        out.push_str(&format!("Schema: {}\n", schema));
476    }
477    for (i, ex) in spec.examples.iter().enumerate() {
478        out.push_str(&format!(
479            "Example {}: {}\n",
480            i + 1,
481            json_str(ex).replace('\n', " ")
482        ));
483    }
484    out
485}
486
487impl Tool for RenderPromptXml {
488    fn name(&self) -> &str {
489        "render_prompt_xml"
490    }
491    fn tier(&self) -> Tier {
492        Tier::Zero
493    }
494    fn call<'a>(&'a self, args: ToolArgs, _ctx: &'a ToolCtx) -> BoxFut<'a, ToolResult> {
495        Box::pin(async move {
496            let v = args.positional(0)?;
497            let spec = extract_prompt_spec(v)?;
498            Ok(Value::Str(render_xml(&spec)))
499        })
500    }
501}
502
503impl Tool for RenderPromptMarkdown {
504    fn name(&self) -> &str {
505        "render_prompt_markdown"
506    }
507    fn tier(&self) -> Tier {
508        Tier::Zero
509    }
510    fn call<'a>(&'a self, args: ToolArgs, _ctx: &'a ToolCtx) -> BoxFut<'a, ToolResult> {
511        Box::pin(async move {
512            let v = args.positional(0)?;
513            let spec = extract_prompt_spec(v)?;
514            Ok(Value::Str(render_markdown(&spec)))
515        })
516    }
517}
518
519impl Tool for RenderPromptTerse {
520    fn name(&self) -> &str {
521        "render_prompt_terse"
522    }
523    fn tier(&self) -> Tier {
524        Tier::Zero
525    }
526    fn call<'a>(&'a self, args: ToolArgs, _ctx: &'a ToolCtx) -> BoxFut<'a, ToolResult> {
527        Box::pin(async move {
528            let v = args.positional(0)?;
529            let spec = extract_prompt_spec(v)?;
530            Ok(Value::Str(render_terse(&spec)))
531        })
532    }
533}
534
535pub struct ToJsonString;
536
537impl Tool for ToJsonString {
538    fn name(&self) -> &str {
539        "to_json_string"
540    }
541
542    fn tier(&self) -> Tier {
543        Tier::Zero
544    }
545
546    fn call<'a>(&'a self, args: ToolArgs, _ctx: &'a ToolCtx) -> BoxFut<'a, ToolResult> {
547        Box::pin(async move {
548            let v = args.positional(0)?.clone();
549            let json = v.to_json();
550            let s = serde_json::to_string_pretty(&json)
551                .map_err(|e| RuntimeError::ToolFailed(format!("to_json_string: {e}")))?;
552            Ok(Value::Str(s))
553        })
554    }
555}
556
557pub struct TextConcat;
558
559impl Tool for TextConcat {
560    fn name(&self) -> &str {
561        "text_concat"
562    }
563
564    fn tier(&self) -> Tier {
565        Tier::Zero
566    }
567
568    fn description(&self) -> Option<&str> {
569        Some("Flatten the text parts of a Message into a single string.")
570    }
571
572    fn input_schema(&self) -> serde_json::Value {
573        serde_json::json!({
574            "type": "object",
575            "properties": {"message": {"description": "A Message value from an llm call."}},
576            "required": ["message"]
577        })
578    }
579
580    fn call<'a>(&'a self, args: ToolArgs, _ctx: &'a ToolCtx) -> BoxFut<'a, ToolResult> {
581        Box::pin(async move {
582            let v = match args.named("message") {
583                Some(v) => v,
584                None => args.positional(0)?,
585            };
586            match v {
587                Value::Message(m) => Ok(Value::Str(m.text_concat())),
588                Value::Str(s) => Ok(Value::Str(s.clone())),
589                other => Err(RuntimeError::TypeMismatch {
590                    expected: "message or string".into(),
591                    actual: other.kind_name().into(),
592                }),
593            }
594        })
595    }
596}
597
598pub struct Concat;
599
600impl Tool for Concat {
601    fn name(&self) -> &str {
602        "concat"
603    }
604
605    fn tier(&self) -> Tier {
606        Tier::Zero
607    }
608
609    fn description(&self) -> Option<&str> {
610        Some("Concatenate two lists into a single new list.")
611    }
612
613    fn input_schema(&self) -> serde_json::Value {
614        serde_json::json!({
615            "type": "object",
616            "properties": {
617                "left": {"type": "array"},
618                "right": {"type": "array"}
619            },
620            "required": ["left", "right"]
621        })
622    }
623
624    fn call<'a>(&'a self, args: ToolArgs, _ctx: &'a ToolCtx) -> BoxFut<'a, ToolResult> {
625        Box::pin(async move {
626            let left = extract_list(&args, "left", 0)?;
627            let right = extract_list(&args, "right", 1)?;
628            let mut out = Vec::with_capacity(left.len() + right.len());
629            out.extend(left);
630            out.extend(right);
631            Ok(Value::List(out))
632        })
633    }
634}
635
636pub struct MessageUser;
637
638impl Tool for MessageUser {
639    fn name(&self) -> &str {
640        "message.user"
641    }
642    fn tier(&self) -> Tier {
643        Tier::Zero
644    }
645    fn description(&self) -> Option<&str> {
646        Some(
647            "Construct a user-role Message from a text string. Use with session.push to inject user instructions into the session history before an llm.call(context: session) call.",
648        )
649    }
650    fn input_schema(&self) -> serde_json::Value {
651        serde_json::json!({
652            "type": "object",
653            "properties": {"text": {"type": "string"}},
654            "required": ["text"]
655        })
656    }
657    fn call<'a>(&'a self, args: ToolArgs, ctx: &'a ToolCtx) -> BoxFut<'a, ToolResult> {
658        Box::pin(async move {
659            let text = extract_string(&args, "text", 0)?;
660            let turn_id = ctx
661                .turn_id
662                .clone()
663                .unwrap_or_else(crate::event::TurnId::now);
664            Ok(Value::Message(crate::message::Message::user_text(
665                turn_id, text,
666            )))
667        })
668    }
669}
670
671pub struct MessageAssistant;
672
673impl Tool for MessageAssistant {
674    fn name(&self) -> &str {
675        "message.assistant"
676    }
677    fn tier(&self) -> Tier {
678        Tier::Zero
679    }
680    fn description(&self) -> Option<&str> {
681        Some("Construct an assistant-role Message from a text string.")
682    }
683    fn input_schema(&self) -> serde_json::Value {
684        serde_json::json!({
685            "type": "object",
686            "properties": {"text": {"type": "string"}},
687            "required": ["text"]
688        })
689    }
690    fn call<'a>(&'a self, args: ToolArgs, ctx: &'a ToolCtx) -> BoxFut<'a, ToolResult> {
691        Box::pin(async move {
692            let text = extract_string(&args, "text", 0)?;
693            let turn_id = ctx
694                .turn_id
695                .clone()
696                .unwrap_or_else(crate::event::TurnId::now);
697            Ok(Value::Message(crate::message::Message::assistant_text(
698                turn_id, text,
699            )))
700        })
701    }
702}
703
704pub struct MessageSystem;
705
706impl Tool for MessageSystem {
707    fn name(&self) -> &str {
708        "message.system"
709    }
710    fn tier(&self) -> Tier {
711        Tier::Zero
712    }
713    fn description(&self) -> Option<&str> {
714        Some("Construct a system-role Message from a text string.")
715    }
716    fn input_schema(&self) -> serde_json::Value {
717        serde_json::json!({
718            "type": "object",
719            "properties": {"text": {"type": "string"}},
720            "required": ["text"]
721        })
722    }
723    fn call<'a>(&'a self, args: ToolArgs, ctx: &'a ToolCtx) -> BoxFut<'a, ToolResult> {
724        Box::pin(async move {
725            let text = extract_string(&args, "text", 0)?;
726            let turn_id = ctx
727                .turn_id
728                .clone()
729                .unwrap_or_else(crate::event::TurnId::now);
730            Ok(Value::Message(crate::message::Message::system_text(
731                turn_id, text,
732            )))
733        })
734    }
735}
736
737pub struct MessageTool;
738
739impl Tool for MessageTool {
740    fn name(&self) -> &str {
741        "message.tool"
742    }
743    fn tier(&self) -> Tier {
744        Tier::Zero
745    }
746    fn description(&self) -> Option<&str> {
747        Some(
748            "Construct a tool-role Message from a text string. Rarely needed directly — dispatch_all already returns tool-role Messages.",
749        )
750    }
751    fn input_schema(&self) -> serde_json::Value {
752        serde_json::json!({
753            "type": "object",
754            "properties": {"text": {"type": "string"}},
755            "required": ["text"]
756        })
757    }
758    fn call<'a>(&'a self, args: ToolArgs, ctx: &'a ToolCtx) -> BoxFut<'a, ToolResult> {
759        Box::pin(async move {
760            let text = extract_string(&args, "text", 0)?;
761            let turn_id = ctx
762                .turn_id
763                .clone()
764                .unwrap_or_else(crate::event::TurnId::now);
765            Ok(Value::Message(crate::message::Message {
766                turn_id,
767                role: crate::message::MessageRole::Tool,
768                parts: vec![crate::message::MessagePart::Text { text }],
769                origin: crate::message::MessageOrigin::User,
770            }))
771        })
772    }
773}
774
775pub struct ExtractToolUses;
776
777impl Tool for ExtractToolUses {
778    fn name(&self) -> &str {
779        "extract_tool_uses"
780    }
781
782    fn tier(&self) -> Tier {
783        Tier::Zero
784    }
785
786    fn description(&self) -> Option<&str> {
787        Some(
788            "Pull the tool_use parts out of an assistant Message. Returns a list of \
789             {id, name, input} structs suitable for dispatch_all.",
790        )
791    }
792
793    fn input_schema(&self) -> serde_json::Value {
794        serde_json::json!({
795            "type": "object",
796            "properties": {"message": {"description": "Assistant Message value."}},
797            "required": ["message"]
798        })
799    }
800
801    fn call<'a>(&'a self, args: ToolArgs, _ctx: &'a ToolCtx) -> BoxFut<'a, ToolResult> {
802        Box::pin(async move {
803            let v = match args.named("message") {
804                Some(v) => v,
805                None => args.positional(0)?,
806            };
807            let m = match v {
808                Value::Message(m) => m,
809                Value::Str(_) => return Ok(Value::List(Vec::new())),
810                other => {
811                    return Err(RuntimeError::TypeMismatch {
812                        expected: "message or string".into(),
813                        actual: other.kind_name().into(),
814                    });
815                }
816            };
817            let mut out = Vec::new();
818            for part in &m.parts {
819                if let crate::message::MessagePart::ToolUse { id, name, input } = part {
820                    out.push(Value::Struct(vec![
821                        ("id".into(), Value::Str(id.clone())),
822                        ("name".into(), Value::Str(name.clone())),
823                        ("input".into(), Value::from_json(input.clone())),
824                    ]));
825                }
826            }
827            Ok(Value::List(out))
828        })
829    }
830}
831
832pub struct DispatchAll;
833
834impl Tool for DispatchAll {
835    fn name(&self) -> &str {
836        "dispatch_all"
837    }
838
839    fn tier(&self) -> Tier {
840        Tier::Zero
841    }
842
843    fn description(&self) -> Option<&str> {
844        Some(
845            "Dispatch each tool_use in the list against the current tool registry and \
846             return a list of tool_result Message values.",
847        )
848    }
849
850    fn input_schema(&self) -> serde_json::Value {
851        serde_json::json!({
852            "type": "object",
853            "properties": {"tool_uses": {"type": "array"}},
854            "required": ["tool_uses"]
855        })
856    }
857
858    fn call<'a>(&'a self, args: ToolArgs, ctx: &'a ToolCtx) -> BoxFut<'a, ToolResult> {
859        Box::pin(async move {
860            let uses = extract_list(&args, "tool_uses", 0)?;
861            let Some(registry) = ctx.registry.as_ref() else {
862                return Err(RuntimeError::ToolFailed(
863                    "dispatch_all: no tool registry available on ctx".into(),
864                ));
865            };
866            let prepared = prepare_dispatch(&uses, registry.as_ref(), ctx)?;
867            let (auto_batch, serial_batch, mut out_slots) = partition_and_gate(prepared, ctx).await;
868            run_auto_parallel(auto_batch, ctx, &mut out_slots).await;
869            run_serial(serial_batch, ctx, &mut out_slots).await;
870            let out: Vec<Value> = out_slots.into_iter().flatten().collect();
871            Ok(Value::List(out))
872        })
873    }
874}
875
876enum PreparedEntry {
877    Ready {
878        index: usize,
879        id: String,
880        name: String,
881        tool: std::sync::Arc<dyn Tool>,
882        call_args: ToolArgs,
883    },
884    Failed {
885        index: usize,
886        msg: crate::message::Message,
887    },
888}
889
890fn prepare_dispatch(
891    uses: &[Value],
892    registry: &crate::tool::ToolRegistry,
893    ctx: &ToolCtx,
894) -> Result<Vec<PreparedEntry>, RuntimeError> {
895    let parsed = uses
896        .iter()
897        .enumerate()
898        .map(|(index, entry)| {
899            let Value::Struct(fields) = entry else {
900                return Err(RuntimeError::TypeMismatch {
901                    expected: "struct {id, name, input}".into(),
902                    actual: entry.kind_name().into(),
903                });
904            };
905            let get = |key: &str| {
906                fields
907                    .iter()
908                    .find(|(name, _)| name == key)
909                    .map(|(_, value)| value.clone())
910            };
911            let id = match get("id") {
912                Some(Value::Str(id)) => id,
913                _ => {
914                    return Err(RuntimeError::ToolFailed(
915                        "dispatch_all: tool_use missing `id` string".into(),
916                    ));
917                }
918            };
919            let name = match get("name") {
920                Some(Value::Str(name)) => name,
921                _ => {
922                    return Err(RuntimeError::ToolFailed(
923                        "dispatch_all: tool_use missing `name` string".into(),
924                    ));
925                }
926            };
927            Ok((index, id, name, get("input").unwrap_or(Value::Unit)))
928        })
929        .collect::<Result<Vec<_>, RuntimeError>>()?;
930
931    let mut prepared = Vec::with_capacity(parsed.len());
932    for (index, id, name, input) in parsed {
933        emit_tool_node(ctx, &id, &name, &input);
934        let Some(tool) = registry.get(&name) else {
935            prepared.push(PreparedEntry::Failed {
936                index,
937                msg: build_error_result(ctx, &id, &format!("dispatch_all: unknown tool `{name}`")),
938            });
939            continue;
940        };
941        let named = match &input {
942            Value::Struct(fields) => fields.clone(),
943            Value::Unit => Vec::new(),
944            other => {
945                prepared.push(PreparedEntry::Failed {
946                    index,
947                    msg: build_error_result(
948                        ctx,
949                        &id,
950                        &format!(
951                            "tool `{name}` expected struct or unit input, got {}",
952                            other.kind_name()
953                        ),
954                    ),
955                });
956                continue;
957            }
958        };
959        let missing = missing_required_fields(&tool.input_schema(), &named);
960        if !missing.is_empty() {
961            let content = format!(
962                "tool `{name}` received empty/incomplete input. Missing required fields: {}. Retry with a complete argument object like {{{}}} — do NOT reuse an empty {{}} input.",
963                missing.join(", "),
964                missing
965                    .iter()
966                    .map(|f| format!("\"{f}\":\"...\""))
967                    .collect::<Vec<_>>()
968                    .join(", ")
969            );
970            prepared.push(PreparedEntry::Failed {
971                index,
972                msg: build_error_result(ctx, &id, &content),
973            });
974            continue;
975        }
976        prepared.push(PreparedEntry::Ready {
977            index,
978            id,
979            name,
980            tool,
981            call_args: ToolArgs {
982                positional: Vec::new(),
983                named,
984            },
985        });
986    }
987    Ok(prepared)
988}
989
990struct Approved {
991    index: usize,
992    id: String,
993    name: String,
994    tool: std::sync::Arc<dyn Tool>,
995    call_args: ToolArgs,
996}
997
998async fn partition_and_gate(
999    prepared: Vec<PreparedEntry>,
1000    ctx: &ToolCtx,
1001) -> (Vec<Approved>, Vec<Approved>, Vec<Option<Value>>) {
1002    let total = prepared.len();
1003    let mut out_slots: Vec<Option<Value>> = vec![None; total];
1004    struct ReadyEntry {
1005        index: usize,
1006        id: String,
1007        name: String,
1008        tool: std::sync::Arc<dyn Tool>,
1009        call_args: ToolArgs,
1010    }
1011    let mut ready: Vec<ReadyEntry> = Vec::new();
1012    for entry in prepared {
1013        match entry {
1014            PreparedEntry::Failed { index, msg } => {
1015                emit_tool_result(ctx, &msg);
1016                out_slots[index] = Some(Value::Message(msg));
1017            }
1018            PreparedEntry::Ready {
1019                index,
1020                id,
1021                name,
1022                tool,
1023                call_args,
1024            } => {
1025                ready.push(ReadyEntry {
1026                    index,
1027                    id,
1028                    name,
1029                    tool,
1030                    call_args,
1031                });
1032            }
1033        }
1034    }
1035    // Parallel: serial awaits hid all but the first pending node from the UI.
1036    let gates = ready.iter().map(|r| {
1037        let level = r.tool.approval_level(&r.call_args, ctx);
1038        request_approval(
1039            ctx,
1040            &r.id,
1041            &r.name,
1042            &r.call_args,
1043            level,
1044            Some(r.tool.as_ref()),
1045        )
1046    });
1047    let outcomes = futures::future::join_all(gates).await;
1048    let mut auto_batch = Vec::new();
1049    let mut serial_batch = Vec::new();
1050    for (r, outcome) in ready.into_iter().zip(outcomes) {
1051        let level = r.tool.approval_level(&r.call_args, ctx);
1052        match outcome {
1053            ApprovalOutcome::Approve => {
1054                let a = Approved {
1055                    index: r.index,
1056                    id: r.id,
1057                    name: r.name.clone(),
1058                    tool: r.tool,
1059                    call_args: r.call_args,
1060                };
1061                if level == crate::tool::ApprovalLevel::Auto {
1062                    auto_batch.push(a);
1063                } else {
1064                    serial_batch.push(a);
1065                }
1066            }
1067            ApprovalOutcome::Deny { reason } => {
1068                let msg = build_error_result(
1069                    ctx,
1070                    &r.id,
1071                    &format!("tool `{}` denied by user: {reason}", r.name),
1072                );
1073                emit_tool_result(ctx, &msg);
1074                out_slots[r.index] = Some(Value::Message(msg));
1075            }
1076        }
1077    }
1078    (auto_batch, serial_batch, out_slots)
1079}
1080
1081async fn run_auto_parallel(batch: Vec<Approved>, ctx: &ToolCtx, out_slots: &mut [Option<Value>]) {
1082    use futures::StreamExt;
1083
1084    let mut pending = futures::stream::FuturesUnordered::new();
1085    for a in batch {
1086        pending.push(async move {
1087            let result = a.tool.call(a.call_args, ctx).await;
1088            (a.index, a.id, a.name, result)
1089        });
1090    }
1091    while let Some((index, id, name, result)) = pending.next().await {
1092        out_slots[index] = Some(finish_dispatch(ctx, &id, &name, result));
1093    }
1094}
1095
1096async fn run_serial(batch: Vec<Approved>, ctx: &ToolCtx, out_slots: &mut [Option<Value>]) {
1097    for a in batch {
1098        let result = a.tool.call(a.call_args, ctx).await;
1099        out_slots[a.index] = Some(finish_dispatch(ctx, &a.id, &a.name, result));
1100    }
1101}
1102
1103fn finish_dispatch(ctx: &ToolCtx, id: &str, name: &str, result: ToolResult) -> Value {
1104    let (content, is_error) = match &result {
1105        Ok(v) => (render_tool_result_text(v), false),
1106        Err(e) => (format!("{e}"), true),
1107    };
1108    if let Ok(v) = &result {
1109        emit_diff_preview_if_relevant(ctx, name, v);
1110    }
1111    let msg = crate::message::Message {
1112        role: crate::message::MessageRole::Tool,
1113        parts: vec![crate::message::MessagePart::ToolResult {
1114            tool_use_id: id.to_string(),
1115            content,
1116            is_error,
1117        }],
1118        turn_id: ctx
1119            .turn_id
1120            .clone()
1121            .unwrap_or_else(crate::event::TurnId::now),
1122        origin: crate::message::MessageOrigin::User,
1123    };
1124    emit_tool_result(ctx, &msg);
1125    Value::Message(msg)
1126}
1127
1128type DiffPreviewData = (String, Option<String>, Option<String>, Option<String>);
1129
1130fn emit_diff_preview_if_relevant(ctx: &ToolCtx, tool_name: &str, value: &Value) {
1131    let Some(sink) = ctx.events.as_ref() else {
1132        return;
1133    };
1134    let data: Option<DiffPreviewData> = match tool_name {
1135        "fs.edit" => {
1136            let path = value_struct_string(value, "summary").and_then(|s| {
1137                s.strip_prefix("[fs.edit(")
1138                    .and_then(|s| s.split(':').next())
1139                    .map(|s| s.trim_end_matches(')').to_string())
1140            });
1141            let diff = value_struct_string(value, "diff");
1142            diff.map(|d| (path.unwrap_or_default(), None, None, Some(d)))
1143        }
1144        "fs.write" => {
1145            let path = value_struct_string(value, "path").unwrap_or_default();
1146            let diff = value_struct_string(value, "diff");
1147            diff.map(|d| (path, None, None, Some(d)))
1148        }
1149        "git.diff" => {
1150            let Some(diff) = value_struct_string(value, "diff") else {
1151                return;
1152            };
1153            Some(("git diff".into(), None, None, Some(diff)))
1154        }
1155        "git.show" => {
1156            let sha = value_struct_string(value, "sha").unwrap_or_default();
1157            let Some(diff) = value_struct_string(value, "diff") else {
1158                return;
1159            };
1160            Some((format!("git show {sha}"), None, None, Some(diff)))
1161        }
1162        "git.log" => {
1163            let Some(diff) = value_struct_string(value, "diff") else {
1164                return;
1165            };
1166            Some(("git log HEAD".into(), None, None, Some(diff)))
1167        }
1168        _ => None,
1169    };
1170    if let Some((title, old_content, new_content, unified_diff)) = data {
1171        sink.emit(crate::event::Event::DiffPreview {
1172            turn_id: ctx.turn_id.clone(),
1173            flow_run_id: ctx.flow_run_id.clone(),
1174            title,
1175            old_content,
1176            new_content,
1177            unified_diff,
1178        });
1179    }
1180}
1181
1182fn value_struct_string(value: &Value, field: &str) -> Option<String> {
1183    if let Value::Struct(fields) = value {
1184        fields
1185            .iter()
1186            .find(|(k, _)| k == field)
1187            .and_then(|(_, v)| match v {
1188                Value::Str(s) => Some(s.clone()),
1189                _ => None,
1190            })
1191    } else {
1192        None
1193    }
1194}
1195
1196fn emit_tool_node(ctx: &ToolCtx, id: &str, name: &str, input: &Value) {
1197    let (Some(run_id), Some(parent_node)) = (&ctx.flow_run_id, &ctx.current_node_id) else {
1198        return;
1199    };
1200    let args_preview = format!("{:?}", input)
1201        .chars()
1202        .take(4000)
1203        .collect::<String>();
1204    if let Some(sink) = &ctx.events {
1205        sink.emit(crate::event::Event::ToolNode {
1206            run_id: run_id.clone(),
1207            parent_node_id: parent_node.clone(),
1208            tool_use_id: id.to_string(),
1209            tool_name: name.to_string(),
1210            args_preview: args_preview.clone(),
1211        });
1212    }
1213    if let Some(tx) = &ctx.stream_tx {
1214        let _ = tx.send(crate::stream::StreamFrame::ToolNode {
1215            run_id: run_id.0.to_string(),
1216            parent_node_id: parent_node.clone(),
1217            tool_use_id: id.to_string(),
1218            tool: name.to_string(),
1219            args_preview,
1220        });
1221    }
1222}
1223
1224fn build_error_result(ctx: &ToolCtx, tool_use_id: &str, content: &str) -> crate::message::Message {
1225    crate::message::Message {
1226        role: crate::message::MessageRole::Tool,
1227        parts: vec![crate::message::MessagePart::ToolResult {
1228            tool_use_id: tool_use_id.to_string(),
1229            content: content.to_string(),
1230            is_error: true,
1231        }],
1232        turn_id: ctx
1233            .turn_id
1234            .clone()
1235            .unwrap_or_else(crate::event::TurnId::now),
1236        origin: crate::message::MessageOrigin::User,
1237    }
1238}
1239
1240fn missing_required_fields(schema: &serde_json::Value, named: &[(String, Value)]) -> Vec<String> {
1241    let Some(required) = schema.get("required").and_then(|v| v.as_array()) else {
1242        return Vec::new();
1243    };
1244    let have: std::collections::HashSet<&str> = named.iter().map(|(k, _)| k.as_str()).collect();
1245    required
1246        .iter()
1247        .filter_map(|v| v.as_str())
1248        .filter(|k| !have.contains(k))
1249        .map(String::from)
1250        .collect()
1251}
1252
1253fn emit_tool_result(ctx: &ToolCtx, msg: &crate::message::Message) {
1254    let msg =
1255        crate::tools::tool_output::maybe_truncate_tool_message(msg, ctx.session_dir.as_deref());
1256    if let Some(tx) = &ctx.stream_tx {
1257        let _ = tx.send(crate::stream::StreamFrame::ToolResultMsg {
1258            flow_run_id: ctx.flow_run_id.as_ref().map(|r| r.0.to_string()),
1259            message: msg,
1260        });
1261    } else if let Some(sink) = &ctx.events {
1262        sink.emit(crate::event::Event::ToolResultMsg {
1263            turn_id: msg.turn_id.clone(),
1264            flow_run_id: ctx.flow_run_id.clone(),
1265            message: msg,
1266        });
1267    }
1268}
1269
1270fn render_tool_result_text(v: &Value) -> String {
1271    match v {
1272        Value::Str(s) => s.clone(),
1273        Value::Message(m) => m.text_concat(),
1274        other => other.to_json().to_string(),
1275    }
1276}
1277
1278fn extract_list(args: &ToolArgs, name: &str, pos: usize) -> Result<Vec<Value>, RuntimeError> {
1279    let value = match args.named(name) {
1280        Some(v) => v,
1281        None => args.positional(pos)?,
1282    };
1283    match value {
1284        Value::List(items) => Ok(items.clone()),
1285        other => Err(RuntimeError::TypeMismatch {
1286            expected: "list".into(),
1287            actual: other.kind_name().into(),
1288        }),
1289    }
1290}
1291
1292pub struct ComposeEmailPreview;
1293
1294impl Tool for ComposeEmailPreview {
1295    fn name(&self) -> &str {
1296        "compose_email_preview"
1297    }
1298
1299    fn tier(&self) -> Tier {
1300        Tier::Zero
1301    }
1302
1303    fn call<'a>(&'a self, args: ToolArgs, _ctx: &'a ToolCtx) -> BoxFut<'a, ToolResult> {
1304        Box::pin(async move {
1305            let subject = extract_string(&args, "subject", 0)?;
1306            let body = extract_string(&args, "body", 1)?;
1307            let to = extract_string_list(&args, "to", 2)?;
1308            Ok(Value::Str(compose_email_preview(&subject, &body, &to)))
1309        })
1310    }
1311}
1312
1313pub fn compose_email_preview(subject: &str, body: &str, to: &[String]) -> String {
1314    format!(
1315        "To: {}
1316Subject: {subject}
1317---
1318{body}",
1319        to.join(", ")
1320    )
1321}
1322
1323fn extract_string(args: &ToolArgs, name: &str, pos: usize) -> Result<String, RuntimeError> {
1324    let value = match args.named(name) {
1325        Some(v) => v,
1326        None => args.positional(pos)?,
1327    };
1328    match value {
1329        Value::Str(s) => Ok(s.clone()),
1330        other => Err(RuntimeError::TypeMismatch {
1331            expected: "string".into(),
1332            actual: other.kind_name().into(),
1333        }),
1334    }
1335}
1336
1337fn extract_string_list(
1338    args: &ToolArgs,
1339    name: &str,
1340    pos: usize,
1341) -> Result<Vec<String>, RuntimeError> {
1342    let value = match args.named(name) {
1343        Some(v) => v,
1344        None => args.positional(pos)?,
1345    };
1346    match value {
1347        Value::List(items) => items
1348            .iter()
1349            .map(|v| match v {
1350                Value::Str(s) => Ok(s.clone()),
1351                other => Err(RuntimeError::TypeMismatch {
1352                    expected: "list of string".into(),
1353                    actual: other.kind_name().into(),
1354                }),
1355            })
1356            .collect(),
1357        other => Err(RuntimeError::TypeMismatch {
1358            expected: "list".into(),
1359            actual: other.kind_name().into(),
1360        }),
1361    }
1362}
1363
1364#[cfg(test)]
1365mod tests {
1366    use super::*;
1367
1368    #[test]
1369    fn shell_quote_wraps_and_escapes() {
1370        assert_eq!(shell_quote("hello"), "'hello'");
1371        assert_eq!(shell_quote("It's fine"), "'It'\\''s fine'");
1372        assert_eq!(shell_quote(""), "''");
1373        assert_eq!(shell_quote("a'b'c"), "'a'\\''b'\\''c'");
1374    }
1375
1376    struct ControlledTool {
1377        name: &'static str,
1378        release: std::sync::Arc<tokio::sync::Semaphore>,
1379    }
1380
1381    impl Tool for ControlledTool {
1382        fn name(&self) -> &str {
1383            self.name
1384        }
1385
1386        fn tier(&self) -> Tier {
1387            Tier::Zero
1388        }
1389
1390        fn call<'a>(&'a self, _args: ToolArgs, _ctx: &'a ToolCtx) -> BoxFut<'a, ToolResult> {
1391            Box::pin(async move {
1392                let _permit = self.release.acquire().await.unwrap();
1393                Ok(Value::Str(self.name.to_string()))
1394            })
1395        }
1396    }
1397
1398    #[tokio::test]
1399    async fn dispatch_all_emits_each_scoped_result_as_its_tool_finishes() {
1400        let fast_release = std::sync::Arc::new(tokio::sync::Semaphore::new(0));
1401        let slow_release = std::sync::Arc::new(tokio::sync::Semaphore::new(0));
1402        let registry = crate::tool::ToolRegistry::new();
1403        registry.register(std::sync::Arc::new(ControlledTool {
1404            name: "fast",
1405            release: fast_release.clone(),
1406        }));
1407        registry.register(std::sync::Arc::new(ControlledTool {
1408            name: "slow",
1409            release: slow_release.clone(),
1410        }));
1411        let run_id = crate::event::FlowRunId::now();
1412        let (stream_tx, mut stream_rx) = tokio::sync::broadcast::channel(32);
1413        let ctx = ToolCtx::new()
1414            .with_anchors(None, Some(run_id.clone()), None)
1415            .with_current_node(Some("dispatch_all".into()))
1416            .with_registry(std::sync::Arc::new(registry))
1417            .with_stream_tx(stream_tx);
1418        let uses = Value::List(vec![
1419            Value::Struct(vec![
1420                ("id".into(), Value::Str("slow_id".into())),
1421                ("name".into(), Value::Str("slow".into())),
1422                ("input".into(), Value::Struct(Vec::new())),
1423            ]),
1424            Value::Struct(vec![
1425                ("id".into(), Value::Str("fast_id".into())),
1426                ("name".into(), Value::Str("fast".into())),
1427                ("input".into(), Value::Struct(Vec::new())),
1428            ]),
1429        ]);
1430        let task = tokio::spawn(async move {
1431            DispatchAll
1432                .call(
1433                    ToolArgs {
1434                        positional: vec![uses],
1435                        named: Vec::new(),
1436                    },
1437                    &ctx,
1438                )
1439                .await
1440                .unwrap()
1441        });
1442
1443        fast_release.add_permits(1);
1444        let fast_result = tokio::time::timeout(std::time::Duration::from_secs(1), async {
1445            loop {
1446                if let crate::stream::StreamFrame::ToolResultMsg {
1447                    flow_run_id,
1448                    message,
1449                } = stream_rx.recv().await.unwrap()
1450                    && message.parts.iter().any(|part| {
1451                        matches!(
1452                            part,
1453                            crate::message::MessagePart::ToolResult { tool_use_id, .. }
1454                                if tool_use_id == "fast_id"
1455                        )
1456                    })
1457                {
1458                    break flow_run_id;
1459                }
1460            }
1461        })
1462        .await
1463        .expect("fast result before slow release");
1464        assert_eq!(fast_result.as_deref(), Some(run_id.0.to_string().as_str()));
1465        assert!(!task.is_finished());
1466
1467        slow_release.add_permits(1);
1468        let Value::List(results) = task.await.unwrap() else {
1469            panic!("dispatch result list");
1470        };
1471        let ids: Vec<&str> = results
1472            .iter()
1473            .map(|value| match value {
1474                Value::Message(message) => match &message.parts[0] {
1475                    crate::message::MessagePart::ToolResult { tool_use_id, .. } => {
1476                        tool_use_id.as_str()
1477                    }
1478                    _ => panic!("tool result part"),
1479                },
1480                _ => panic!("tool result message"),
1481            })
1482            .collect();
1483        assert_eq!(ids, vec!["slow_id", "fast_id"]);
1484    }
1485
1486    #[tokio::test]
1487    async fn dispatch_all_unknown_tool_finishes_its_workflow_node_with_error() {
1488        use crate::workflow::{NodeStatus, WorkflowGraph};
1489
1490        let registry = crate::tool::ToolRegistry::new();
1491        let run_id = crate::event::FlowRunId::now();
1492        let run = run_id.0.to_string();
1493        let (stream_tx, mut stream_rx) = tokio::sync::broadcast::channel(8);
1494        let ctx = ToolCtx::new()
1495            .with_anchors(None, Some(run_id), None)
1496            .with_current_node(Some("dispatch_all".into()))
1497            .with_registry(std::sync::Arc::new(registry))
1498            .with_stream_tx(stream_tx);
1499        let uses = Value::List(vec![Value::Struct(vec![
1500            ("id".into(), Value::Str("unknown_id".into())),
1501            ("name".into(), Value::Str("missing.tool".into())),
1502            ("input".into(), Value::Struct(Vec::new())),
1503        ])]);
1504
1505        DispatchAll
1506            .call(
1507                ToolArgs {
1508                    positional: vec![uses],
1509                    named: Vec::new(),
1510                },
1511                &ctx,
1512            )
1513            .await
1514            .unwrap();
1515
1516        let mut graph = WorkflowGraph::new(crate::event::TurnId::now());
1517        graph.apply_stream_frame(&crate::stream::StreamFrame::FlowStart {
1518            run_id: run.clone(),
1519            flow_name: "agent_loop".into(),
1520            parent_run_id: None,
1521            parent_node_id: None,
1522        });
1523        graph.apply_stream_frame(&crate::stream::StreamFrame::FlowNodeStart {
1524            run_id: run.clone(),
1525            node_id: "dispatch_all".into(),
1526            kind: crate::nodegraph::NodeKind::ToolCall {
1527                path: "dispatch_all".into(),
1528            },
1529            label: "dispatch_all".into(),
1530            parent_node_id: None,
1531        });
1532        while let Ok(frame) = stream_rx.try_recv() {
1533            graph.apply_stream_frame(&frame);
1534        }
1535
1536        let node = graph
1537            .find_node(&format!("tool:{run}:unknown_id"))
1538            .expect("unknown tool node");
1539        assert_eq!(node.status, NodeStatus::Err);
1540        assert!(matches!(
1541            &node.kind,
1542            crate::workflow::WorkflowNodeKind::ToolCall {
1543                result_preview: Some(preview),
1544                ..
1545            } if preview.contains("unknown tool")
1546        ));
1547        let result = node.output_preview.as_deref().unwrap();
1548        assert!(result.contains("unknown tool"));
1549        assert!(
1550            graph
1551                .root
1552                .iter()
1553                .flat_map(|root| &root.children)
1554                .all(|child| {
1555                    !matches!(
1556                        &child.kind,
1557                        crate::workflow::WorkflowNodeKind::ToolCall { tool_use_id, .. }
1558                            if tool_use_id == "unknown_id"
1559                    )
1560                })
1561        );
1562    }
1563
1564    #[test]
1565    fn prepare_dispatch_does_not_emit_partial_nodes_for_malformed_batch() {
1566        let registry = crate::tool::ToolRegistry::new();
1567        let run_id = crate::event::FlowRunId::now();
1568        let (stream_tx, mut stream_rx) = tokio::sync::broadcast::channel(8);
1569        let ctx = ToolCtx::new()
1570            .with_anchors(None, Some(run_id), None)
1571            .with_current_node(Some("dispatch_all".into()))
1572            .with_stream_tx(stream_tx);
1573        let uses = vec![
1574            Value::Struct(vec![
1575                ("id".into(), Value::Str("valid_id".into())),
1576                ("name".into(), Value::Str("missing.tool".into())),
1577            ]),
1578            Value::Struct(vec![("name".into(), Value::Str("missing.tool".into()))]),
1579        ];
1580
1581        assert!(prepare_dispatch(&uses, &registry, &ctx).is_err());
1582        assert!(matches!(
1583            stream_rx.try_recv(),
1584            Err(tokio::sync::broadcast::error::TryRecvError::Empty)
1585        ));
1586    }
1587
1588    #[test]
1589    fn compose_email_preview_formats_headers() {
1590        let preview = compose_email_preview(
1591            "Deploy status",
1592            "See attached",
1593            &["a@x.com".into(), "b@x.com".into()],
1594        );
1595        assert_eq!(
1596            preview,
1597            "To: a@x.com, b@x.com\nSubject: Deploy status\n---\nSee attached"
1598        );
1599    }
1600}