1use crate::agent::Agent;
2use crate::built::{detached, Cancel, Discard};
3use crate::error::KitError;
4use crate::laws::Laws;
5use crate::storage::Storage;
6use crate::tool::AsTool;
7use crate::trace::root_span;
8use async_trait::async_trait;
9use serde_json::{Map, Value};
10use std::collections::HashMap;
11use std::fmt;
12use std::future::Future;
13use std::path::{Path, PathBuf};
14use std::sync::Arc;
15use std::time::Duration;
16use toml::Value as Toml;
17use troupekit_agent::{
18 AgentIo, EvalFn, InMemoryLedger, Limits, MemorySource, PersonaLoader, SimpleIo, UsageLedger,
19};
20use troupekit_core::clock::Clock;
21use troupekit_core::event::Usage;
22use troupekit_core::ids::RunId;
23use troupekit_core::inmem::InMemCheckpoints;
24use troupekit_core::secret::Secret;
25use troupekit_core::store::CheckpointStore;
26use troupekit_graph::{GraphIo, GraphOutcome, GraphRun, SimpleGraphIo, Workflow};
27use troupekit_tools::{Tool, ToolContext, ToolError, ToolOutput, ToolRegistry, ToolSpec};
28use troupekit_trace::Trace;
29
30mod run_api;
31
32const MAX_NODES: usize = 64;
33const MAX_GRAPH_RETRIES: u32 = 50;
34const DEFAULT_GRAPH_RETRIES: u32 = 3;
35const RETRY_WAIT_CHUNK_MS: i64 = 300_000;
36const INPUT: &str = "input";
37const END: &str = "end";
38
39#[derive(Clone)]
40enum Node {
41 Agent(Box<Agent>),
42 Step(Arc<dyn Tool>),
43}
44
45#[derive(Clone)]
50pub struct Graph {
51 name: String,
52 nodes: Vec<(String, Node)>,
53 edges: Vec<(String, String)>,
54 storage: Storage,
55 limits: Limits,
56 ledger: Option<Arc<dyn UsageLedger>>,
57 max_steps: Option<u32>,
58 retries: u32,
59 law_paths: Vec<PathBuf>,
60 inline_laws: Vec<String>,
61 auto_laws: bool,
62 events: Option<Arc<dyn troupekit_agent::EventSink>>,
63 pub(crate) trace: crate::trace::TraceConfig,
64 pub(crate) private: bool,
65}
66
67impl Graph {
68 pub fn new(name: impl Into<String>) -> Self {
72 Graph {
73 name: name.into(),
74 nodes: Vec::new(),
75 edges: Vec::new(),
76 storage: Storage::memory(),
77 limits: Limits::default(),
78 ledger: None,
79 max_steps: None,
80 retries: DEFAULT_GRAPH_RETRIES,
81 law_paths: Vec::new(),
82 inline_laws: Vec::new(),
83 auto_laws: true,
84 events: None,
85 trace: crate::trace::TraceConfig::default(),
86 private: false,
87 }
88 }
89
90 pub fn agent(mut self, id: impl Into<String>, agent: Agent) -> Self {
96 self.nodes.push((id.into(), Node::Agent(Box::new(agent))));
97 self
98 }
99
100 pub fn step(mut self, id: impl Into<String>, step: impl AsTool) -> Self {
104 self.nodes.push((id.into(), Node::Step(step.into_arc())));
105 self
106 }
107
108 pub fn edge(mut self, from: impl Into<String>, to: impl Into<String>) -> Self {
112 self.edges.push((from.into(), to.into()));
113 self
114 }
115
116 pub fn checkpoints(mut self, storage: Storage) -> Self {
120 self.storage = storage;
121 self
122 }
123
124 pub fn limits(mut self, limits: Limits) -> Self {
128 self.limits = limits;
129 self
130 }
131
132 pub fn ledger(mut self, ledger: Arc<dyn UsageLedger>) -> Self {
137 self.ledger = Some(ledger);
138 self
139 }
140
141 pub fn max_steps(mut self, steps: u32) -> Self {
145 self.max_steps = Some(steps);
146 self
147 }
148
149 pub fn retries(mut self, retries: u32) -> Self {
153 self.retries = retries;
154 self
155 }
156
157 pub fn laws(mut self, path: impl AsRef<Path>) -> Self {
161 self.law_paths.push(path.as_ref().to_path_buf());
162 self
163 }
164
165 pub fn law(mut self, law: impl Into<String>) -> Self {
169 self.inline_laws.push(law.into());
170 self
171 }
172
173 pub fn auto_laws(mut self, on: bool) -> Self {
177 self.auto_laws = on;
178 self
179 }
180
181 pub async fn build(self) -> Result<BuiltGraph, KitError> {
185 let owner = format!("graph:{}", self.name);
186 let secrets: Vec<Secret> = self
187 .nodes
188 .iter()
189 .filter_map(|(_, node)| match node {
190 Node::Agent(agent) => agent.trace_secret(),
191 Node::Step(_) => None,
192 })
193 .collect();
194 let traced = self.trace.open(&owner, &self.name, &secrets)?;
195 match traced {
196 Some(t) => {
197 let tracer = t.tracer.clone();
198 tracer.in_scope(self.build_in(owner, Some(t))).await
199 }
200 None => self.build_in(owner, None).await,
201 }
202 }
203
204 async fn build_in(
205 mut self,
206 owner: String,
207 traced: Option<crate::trace::Traced>,
208 ) -> Result<BuiltGraph, KitError> {
209 if self.private {
210 for (_, node) in &mut self.nodes {
211 if let Node::Agent(agent) = node {
212 agent.route.private = true;
213 }
214 }
215 }
216 #[cfg(feature = "local")]
217 {
218 let mut loads = crate::local::Loads::new();
219 for (_, node) in &mut self.nodes {
220 if let Node::Agent(agent) = node {
221 let loaded = agent.as_ref().clone().load_local(&mut loads).await?;
222 **agent = loaded;
223 }
224 }
225 }
226 let fail = |m: String| KitError::config(&owner, m);
227 if self.retries > MAX_GRAPH_RETRIES {
228 return Err(fail(format!(
229 "retries must be at most {MAX_GRAPH_RETRIES}, got {}",
230 self.retries
231 )));
232 }
233 let order = self.chain().map_err(fail)?;
234 let laws = Laws::check(&owner, &self.law_paths, &self.inline_laws, self.auto_laws)?;
235 let (names, outputs) = self.persona_names(&order)?;
236 let workflow = self.workflow(&order, &names, &outputs)?;
237 let mut registry = ToolRegistry::new();
238 let mut agent_io = SimpleIo::new(ToolRegistry::new());
239 let mut files: HashMap<String, String> = HashMap::new();
240 let mut keys: HashMap<String, (String, &Agent)> = HashMap::new();
241 let mut evals: HashMap<String, EvalFn> = HashMap::new();
242 let (store, durable) = self.storage.open().await?;
243 let ledger: Arc<dyn UsageLedger> = self
244 .ledger
245 .clone()
246 .unwrap_or_else(|| Arc::new(InMemoryLedger::default()));
247 let route_ledger = self
248 .ledger
249 .clone()
250 .or(durable)
251 .unwrap_or_else(|| ledger.clone());
252 for (i, id) in order.iter().enumerate() {
253 let feeder = feeder(&order, i);
254 match self.node(id) {
255 Node::Agent(agent) => {
256 if let Some(what) = agent.graph_conflict() {
257 return Err(fail(format!("agent node `{id}` sets its own {what}")));
258 }
259 let name = &names[id];
260 let key = match keys.get(name) {
261 Some((key, first)) if first.same_model(agent) => key.clone(),
262 Some(_) => {
263 return Err(fail(format!("two different agents are named `{name}`")));
264 }
265 None => {
266 let key = format!("agent-{}", keys.len());
267 keys.insert(name.clone(), (key.clone(), agent));
268 key
269 }
270 };
271 let prepared = agent.prepare(Some(&key), &route_ledger)?;
272 if prepared.persona.name != *name {
273 return Err(fail(format!(
274 "agent node `{id}` persona name changed from `{name}` to `{}` during build",
275 prepared.persona.name
276 )));
277 }
278 for tool in &prepared.tools {
279 share(&mut registry, tool.clone()).map_err(fail)?;
280 }
281 agent_io.models.entry(key).or_insert(prepared.handle);
282 for (eval, f) in prepared.eval_fns {
283 match evals.get(&eval) {
284 Some(first) if Arc::ptr_eq(first, &f) => {}
285 Some(_) => {
286 return Err(fail(format!(
287 "eval `{eval}` has two different callbacks; pass one shared EvalFn"
288 )));
289 }
290 None => {
291 agent_io.evals.register(&eval, f.clone())?;
292 evals.insert(eval, f);
293 }
294 }
295 }
296 let file = format!("{}.toml", prepared.persona.name);
297 match files.get(&file) {
298 Some(text) if *text != prepared.persona_text => {
299 return Err(fail(format!(
300 "two different agents are named `{}`",
301 prepared.persona.name
302 )));
303 }
304 Some(_) => {}
305 None => {
306 files.insert(file, prepared.persona_text);
307 }
308 }
309 }
310 Node::Step(tool) => {
311 if outputs.contains_key(feeder) {
312 return Err(fail(format!(
313 "step `{id}` is fed by agent node `{feeder}`, which has typed \
314 output; steps take text, so feed it from an agent without [output]"
315 )));
316 }
317 let args = arg_names(tool.spec());
318 if args != [feeder] {
319 return Err(fail(format!(
320 "step `{id}` takes ({}) but is fed by ({feeder}); name its arguments after the nodes that feed it",
321 args.join(", ")
322 )));
323 }
324 if !takes_text(&tool.spec().schema["properties"][feeder]) {
325 return Err(fail(format!(
326 "step `{id}` argument `{feeder}` must accept a string; every graph node is fed text"
327 )));
328 }
329 registry.register(Arc::new(StepTool::new(id, tool.clone())))?;
330 }
331 }
332 }
333 agent_io.tools = registry;
334 agent_io.events = self.events.clone().unwrap_or_else(|| Arc::new(Discard));
335 agent_io.ledger = ledger;
336 let agent_io: Arc<dyn AgentIo> = Arc::new(agent_io);
337 let loader = PersonaLoader::new(vec![Arc::new(MemorySource::new("graph", files))]);
338 let io = SimpleGraphIo::new(agent_io, loader);
339 GraphRun::new(
340 workflow.clone(),
341 input_state("build check"),
342 self.limits.clone(),
343 &io,
344 )
345 .await?;
346 let last = order.last().expect("chain has a node").clone();
347 Ok(BuiltGraph {
348 inner: Arc::new(Inner {
349 owner,
350 workflow,
351 io,
352 limits: self.limits,
353 store,
354 last,
355 laws,
356 trace: traced,
357 }),
358 })
359 }
360
361 pub async fn run(self, input: impl Into<String>) -> Result<Value, KitError> {
365 self.build().await?.run(input).await
366 }
367
368 pub async fn run_with(self, input: impl Into<String>) -> Result<GraphReport, KitError> {
372 self.build().await?.run_with(input).await
373 }
374
375 fn node(&self, id: &str) -> &Node {
376 let found = self.nodes.iter().find(|(n, _)| n == id);
377 &found.expect("chain ids come from the nodes").1
378 }
379
380 fn chain(&self) -> Result<Vec<String>, String> {
381 if self.nodes.is_empty() {
382 return Err("needs at least one node".into());
383 }
384 if self.nodes.len() > MAX_NODES {
385 return Err(format!(
386 "takes at most {MAX_NODES} nodes, got {}",
387 self.nodes.len()
388 ));
389 }
390 let mut ids: Vec<&str> = Vec::with_capacity(self.nodes.len());
391 for (id, _) in &self.nodes {
392 if id == INPUT || id == END {
393 return Err(format!("node id `{id}` is reserved"));
394 }
395 if ids.contains(&id.as_str()) {
396 return Err(format!("duplicate node id `{id}`"));
397 }
398 ids.push(id);
399 }
400 if self.edges.is_empty() {
401 return Ok(ids.iter().map(|s| s.to_string()).collect());
402 }
403 for (from, to) in &self.edges {
404 if let Some(unknown) = [from, to].into_iter().find(|n| !ids.contains(&n.as_str())) {
405 return Err(format!("edge names unknown node `{unknown}`"));
406 }
407 }
408 let count = |pick: &dyn Fn(&(String, String)) -> &str, id: &str| {
409 self.edges.iter().filter(|e| pick(e) == id).count()
410 };
411 for id in &ids {
412 if count(&|e| e.0.as_str(), id) > 1 {
413 return Err(format!(
414 "node `{id}` has two outgoing edges; fan-out needs workflow TOML"
415 ));
416 }
417 if count(&|e| e.1.as_str(), id) > 1 {
418 return Err(format!(
419 "node `{id}` has two incoming edges; joins need workflow TOML"
420 ));
421 }
422 }
423 let Some(start) = ids.iter().find(|id| count(&|e| e.1.as_str(), id) == 0) else {
424 return Err("edges form a cycle".into());
425 };
426 let mut order = vec![start.to_string()];
427 while order.len() <= ids.len() {
428 let last = order.last().expect("order starts non-empty");
429 let Some((_, next)) = self.edges.iter().find(|(from, _)| from == last) else {
430 break;
431 };
432 if order.contains(next) {
433 return Err("edges form a cycle".into());
434 }
435 order.push(next.clone());
436 }
437 if let Some(lone) = ids.iter().find(|id| !order.iter().any(|o| o == *id)) {
438 return Err(format!("node `{lone}` is not on the chain"));
439 }
440 assert_eq!(order.len(), ids.len());
441 Ok(order)
442 }
443
444 fn persona_names(&self, order: &[String]) -> Result<(Names, Outputs), KitError> {
445 let mut names = HashMap::with_capacity(order.len());
446 let mut outputs = HashMap::new();
447 for id in order {
448 if let Node::Agent(agent) = self.node(id) {
449 let (name, output) = agent.persona_identity()?;
450 names.insert(id.clone(), name);
451 if let Some(output) = output.as_ref().and_then(object_type) {
452 outputs.insert(id.clone(), output);
453 }
454 }
455 }
456 assert!(names.len() <= order.len());
457 assert!(outputs.keys().all(|id| names.contains_key(id)));
458 Ok((names, outputs))
459 }
460
461 fn workflow(
462 &self,
463 order: &[String],
464 names: &Names,
465 outputs: &Outputs,
466 ) -> Result<Workflow, KitError> {
467 let mut state = toml::Table::new();
468 state.insert(INPUT.into(), Toml::String("string".into()));
469 let mut nodes = Vec::with_capacity(order.len() + 1);
470 for (i, id) in order.iter().enumerate() {
471 let kind = outputs.get(id).map_or("string", String::as_str);
472 state.insert(id.clone(), Toml::String(kind.into()));
473 let mut node = toml::Table::new();
474 node.insert("id".into(), Toml::String(id.clone()));
475 match self.node(id) {
476 Node::Agent(_) => {
477 node.insert("kind".into(), Toml::String("agent".into()));
478 let name = names.get(id).expect("every agent node has a persona name");
479 node.insert("persona".into(), Toml::String(name.clone()));
480 }
481 Node::Step(_) => {
482 node.insert("kind".into(), Toml::String("tool".into()));
483 node.insert("tool".into(), Toml::String(step_name(id)));
484 }
485 }
486 let reads = vec![Toml::String(feeder(order, i).to_string())];
487 node.insert("reads".into(), Toml::Array(reads));
488 node.insert("writes".into(), Toml::String(id.clone()));
489 nodes.push(Toml::Table(node));
490 }
491 let mut end = toml::Table::new();
492 end.insert("id".into(), Toml::String(END.into()));
493 end.insert("kind".into(), Toml::String("end".into()));
494 nodes.push(Toml::Table(end));
495 let mut edges = Vec::with_capacity(order.len());
496 for (i, from) in order.iter().enumerate() {
497 let to = order.get(i + 1).map_or(END, String::as_str);
498 let mut edge = toml::Table::new();
499 edge.insert("from".into(), Toml::String(from.clone()));
500 edge.insert("to".into(), Toml::String(to.to_string()));
501 edges.push(Toml::Table(edge));
502 }
503 let mut table = toml::Table::new();
504 table.insert("name".into(), Toml::String(self.name.clone()));
505 table.insert("start".into(), Toml::String(order[0].clone()));
506 if let Some(steps) = self.max_steps {
507 table.insert("max_steps".into(), Toml::Integer(i64::from(steps)));
508 }
509 table.insert("max_retries".into(), Toml::Integer(i64::from(self.retries)));
510 table.insert("state".into(), Toml::Table(state));
511 table.insert("nodes".into(), Toml::Array(nodes));
512 table.insert("edges".into(), Toml::Array(edges));
513 let text = toml::to_string(&table).map_err(|e| {
514 KitError::config(
515 &format!("graph:{}", self.name),
516 format!("workflow does not serialize: {e}"),
517 )
518 })?;
519 Ok(Workflow::parse(&format!("graph:{}", self.name), &text)?)
520 }
521}
522
523impl fmt::Debug for Graph {
524 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
525 let ids: Vec<&str> = self.nodes.iter().map(|(id, _)| id.as_str()).collect();
526 f.debug_struct("Graph")
527 .field("name", &self.name)
528 .field("nodes", &ids)
529 .field("edges", &self.edges)
530 .field("storage", &self.storage)
531 .field("retries", &self.retries)
532 .field("ledger", &self.ledger.is_some())
533 .field("private", &self.private)
534 .finish_non_exhaustive()
535 }
536}
537
538#[derive(Debug, Clone, PartialEq)]
542#[non_exhaustive]
543pub struct GraphReport {
544 output: Value,
545 state: Map<String, Value>,
546 usage: Usage,
547 steps: u64,
548 run_id: RunId,
549 trace_path: Option<PathBuf>,
550}
551
552impl GraphReport {
553 pub fn output(&self) -> &Value {
557 &self.output
558 }
559
560 pub fn state(&self) -> &Map<String, Value> {
564 &self.state
565 }
566
567 pub fn usage(&self) -> Usage {
571 self.usage
572 }
573
574 pub fn steps(&self) -> u64 {
578 self.steps
579 }
580
581 pub fn run_id(&self) -> RunId {
585 self.run_id
586 }
587
588 pub fn trace_path(&self) -> Option<&Path> {
592 self.trace_path.as_deref()
593 }
594}
595
596#[derive(Clone)]
600pub struct BuiltGraph {
601 inner: Arc<Inner>,
602}
603
604struct Inner {
605 owner: String,
606 workflow: Workflow,
607 io: SimpleGraphIo,
608 limits: Limits,
609 store: Option<Arc<dyn CheckpointStore>>,
610 last: String,
611 laws: Laws,
612 trace: Option<crate::trace::Traced>,
613}
614
615impl BuiltGraph {
616 pub fn trace_path(&self) -> Option<&Path> {
620 crate::trace::path_of(&self.inner.trace)
621 }
622
623 async fn traced<T>(
624 &self,
625 run_id: Option<RunId>,
626 work: impl Future<Output = Result<T, KitError>>,
627 id_of: impl Fn(&T) -> RunId,
628 ) -> Result<T, KitError> {
629 let owner = self.inner.workflow.name.as_str();
630 let traced = self.inner.trace.as_ref();
631 root_span(
632 traced,
633 Trace::Graphs,
634 "graph.run",
635 owner,
636 run_id,
637 work,
638 id_of,
639 )
640 .await
641 }
642
643 pub async fn run(&self, input: impl Into<String>) -> Result<Value, KitError> {
647 Ok(self.run_with(input).await?.output)
648 }
649
650 pub async fn run_with(&self, input: impl Into<String>) -> Result<GraphReport, KitError> {
654 let input = input.into();
655 self.traced(None, self.run_untraced(input), GraphReport::run_id)
656 .await
657 }
658
659 async fn run_untraced(&self, input: String) -> Result<GraphReport, KitError> {
660 let inner = &self.inner;
661 let run = GraphRun::new(
662 inner.workflow.clone(),
663 input_state(&input),
664 inner.limits.clone(),
665 &inner.io,
666 )
667 .await?;
668 let store: Arc<dyn CheckpointStore> = match &inner.store {
669 Some(store) => store.clone(),
670 None => Arc::new(InMemCheckpoints::default()),
671 };
672 let graph = self.clone();
673 detached(run.run_id(), move |stop| async move {
674 let mut run = run;
675 graph.finish(&graph.inner.io, &mut run, store.as_ref(), &stop).await
676 })
677 .await
678 }
679
680 pub async fn resume(&self, run_id: RunId) -> Result<Value, KitError> {
685 self.traced(Some(run_id), self.resume_untraced(run_id), |_| run_id)
686 .await
687 }
688
689 async fn resume_untraced(&self, run_id: RunId) -> Result<Value, KitError> {
690 let inner = &self.inner;
691 let Some(store) = &inner.store else {
692 return Err(KitError::config(
693 &inner.owner,
694 "resume needs Storage::sqlite(..) or Storage::custom(..) checkpoints",
695 ));
696 };
697 let Some(checkpoint) = store.latest(run_id).await? else {
698 return Err(KitError::config(
699 &inner.owner,
700 format!("no checkpoint for run {run_id}"),
701 ));
702 };
703 let mut run = GraphRun::from_checkpoint(&checkpoint)?;
704 if run.workflow() != &inner.workflow {
705 return Err(KitError::config(
706 &inner.owner,
707 format!(
708 "run {run_id} was started by a different workflow; resume it with the graph that started it"
709 ),
710 ));
711 }
712 run.tighten(&inner.limits);
713 let graph = self.clone();
714 let store = store.clone();
715 let report = detached(run_id, move |stop| async move {
716 let mut run = run;
717 graph.finish(&graph.inner.io, &mut run, store.as_ref(), &stop).await
718 })
719 .await?;
720 Ok(report.output)
721 }
722
723 pub fn workflow(&self) -> &Workflow {
727 &self.inner.workflow
728 }
729
730 pub fn laws(&self) -> &Laws {
734 &self.inner.laws
735 }
736
737 async fn finish(
738 &self,
739 io: &dyn GraphIo,
740 run: &mut GraphRun,
741 store: &dyn CheckpointStore,
742 cancel: &Cancel,
743 ) -> Result<GraphReport, KitError> {
744 let inner = &self.inner;
745 let run_id = run.run_id();
746 let in_run = |e: troupekit_core::error::CoreError| KitError::in_run(run_id, e.into());
747 if store.latest(run_id).await.map_err(in_run)?.is_none() {
748 store.save(run.checkpoint()).await.map_err(in_run)?;
749 }
750 let cap =
751 2 * u64::from(inner.workflow.max_steps) + u64::from(inner.workflow.max_retries) + 8;
752 for _ in 0..cap {
753 if cancel.is_set() {
754 return Err(KitError::Cancelled { run_id });
755 }
756 let before = run.steps();
757 let outcome = run.step(io).await;
758 if run.steps() != before {
759 store.save(run.checkpoint()).await.map_err(in_run)?;
760 }
761 if cancel.is_set() {
762 return Err(KitError::Cancelled { run_id });
763 }
764 match outcome {
765 GraphOutcome::Continue => {}
766 GraphOutcome::RetryAt { at_ms, .. } => {
767 if wait_until(io.agent().clock(), at_ms, RETRY_WAIT_CHUNK_MS, cancel).await {
768 return Err(KitError::Cancelled { run_id });
769 }
770 }
771 GraphOutcome::Waiting(reason) => {
772 return Err(KitError::Paused {
773 run_id: run.run_id(),
774 reason,
775 })
776 }
777 GraphOutcome::Failed(reason) => {
778 return Err(KitError::failed(run.run_id(), reason, run.host_failed()))
779 }
780 GraphOutcome::Done(state) => {
781 let output = state
782 .get(&inner.last)
783 .cloned()
784 .expect("a finished chain run wrote its last node");
785 return Ok(GraphReport {
786 output,
787 state,
788 usage: run.usage(),
789 steps: run.steps(),
790 run_id: run.run_id(),
791 trace_path: self.trace_path().map(Path::to_path_buf),
792 });
793 }
794 }
795 }
796 Err(KitError::Failed {
797 run_id: run.run_id(),
798 reason: format!("did not finish within {cap} steps"),
799 })
800 }
801}
802
803impl fmt::Debug for BuiltGraph {
804 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
805 let inner = &self.inner;
806 f.debug_struct("BuiltGraph")
807 .field("name", &inner.workflow.name)
808 .field("nodes", &inner.workflow.nodes.len())
809 .field("durable", &inner.store.is_some())
810 .field("laws", &inner.laws)
811 .finish_non_exhaustive()
812 }
813}
814
815struct StepTool {
816 spec: ToolSpec,
817 inner: Arc<dyn Tool>,
818}
819
820impl StepTool {
821 fn new(id: &str, inner: Arc<dyn Tool>) -> Self {
822 let spec = ToolSpec {
823 name: step_name(id),
824 ..inner.spec().clone()
825 };
826 StepTool { spec, inner }
827 }
828}
829
830#[async_trait]
831impl Tool for StepTool {
832 fn spec(&self) -> &ToolSpec {
833 &self.spec
834 }
835
836 async fn call(&self, args: Value, ctx: &ToolContext) -> Result<ToolOutput, ToolError> {
837 let out = self.inner.call(args, ctx).await?;
838 if out.is_error {
839 return Ok(out);
840 }
841 Ok(ToolOutput::text(Value::String(out.content).to_string()))
842 }
843}
844
845async fn wait_until(clock: &dyn Clock, at_ms: i64, chunk_ms: i64, cancel: &Cancel) -> bool {
846 assert!(chunk_ms > 0, "a wait chunk lasts some time");
847 let first = at_ms.saturating_sub(clock.now_ms());
848 let rounds = first.max(0) / chunk_ms + 2;
849 for _ in 0..rounds {
850 let left = at_ms.saturating_sub(clock.now_ms());
851 if left <= 0 {
852 return false;
853 }
854 let ms = u64::try_from(left.min(chunk_ms)).expect("left is positive");
855 if cancel.sleep(Duration::from_millis(ms)).await {
856 return true;
857 }
858 }
859 false
860}
861
862fn step_name(id: &str) -> String {
863 format!("step__{id}")
864}
865
866fn feeder(order: &[String], i: usize) -> &str {
867 if i == 0 {
868 INPUT
869 } else {
870 &order[i - 1]
871 }
872}
873
874fn input_state(text: &str) -> Map<String, Value> {
875 let mut state = Map::new();
876 state.insert(INPUT.into(), Value::String(text.to_string()));
877 state
878}
879
880type Names = HashMap<String, String>;
881type Outputs = HashMap<String, String>;
882
883fn object_type(output: &toml::Table) -> Option<String> {
887 let mut fields = Vec::with_capacity(output.len());
888 for (field, kind) in output {
889 fields.push(format!("{field}: {}", kind.as_str()?));
890 }
891 assert_eq!(fields.len(), output.len());
892 Some(format!("{{{}}}", fields.join(", ")))
893}
894
895fn takes_text(schema: &Value) -> bool {
896 match schema {
897 Value::Bool(any) => *any,
898 Value::Object(map) => match map.get("type") {
899 Some(Value::String(t)) => t == "string",
900 Some(Value::Array(types)) => types.iter().any(|t| t == "string"),
901 Some(_) => false,
902 None => !["$ref", "anyOf", "oneOf", "allOf", "enum", "const", "not"]
903 .iter()
904 .any(|k| map.contains_key(*k)),
905 },
906 _ => false,
907 }
908}
909
910fn arg_names(spec: &ToolSpec) -> Vec<String> {
911 let mut names: Vec<String> = spec.schema["properties"]
912 .as_object()
913 .map(|p| p.keys().cloned().collect())
914 .unwrap_or_default();
915 names.sort();
916 names
917}
918
919fn share(registry: &mut ToolRegistry, tool: Arc<dyn Tool>) -> Result<(), String> {
920 let name = tool.spec().name.clone();
921 match registry.get(&name) {
922 Some(existing) if Arc::ptr_eq(&existing, &tool) => Ok(()),
923 Some(existing) if existing.spec() == tool.spec() => Err(format!(
924 "tool `{name}` has two different implementations; pass one shared tool to both agents"
925 )),
926 Some(_) => Err(format!(
927 "tool `{name}` is registered twice with different specs"
928 )),
929 None => registry.register(tool).map_err(|e| e.to_string()),
930 }
931}
932
933#[cfg(test)]
934mod tests {
935 use super::wait_until;
936 use troupekit_core::clock::{Clock, SystemClock};
937
938 #[tokio::test]
939 async fn retry_wait_reaches_a_deadline_past_one_chunk() {
940 let clock = SystemClock;
941 let at = clock.now_ms() + 25;
942 wait_until(&clock, at, 10, &crate::built::Cancel::default()).await;
943 assert!(clock.now_ms() >= at);
944 let before = clock.now_ms();
945 wait_until(&clock, before - 1_000, 10, &crate::built::Cancel::default()).await;
946 assert!(clock.now_ms() - before < 10);
947 }
948}