Skip to main content

troupekit_kit/
graph.rs

1use crate::agent::Agent;
2use crate::built::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::{GraphOutcome, GraphRun, SimpleGraphIo, Workflow};
27use troupekit_tools::{Tool, ToolContext, ToolError, ToolOutput, ToolRegistry, ToolSpec};
28use troupekit_trace::Trace;
29
30const MAX_NODES: usize = 64;
31const MAX_GRAPH_RETRIES: u32 = 50;
32const DEFAULT_GRAPH_RETRIES: u32 = 3;
33const RETRY_WAIT_CHUNK_MS: i64 = 300_000;
34const INPUT: &str = "input";
35const END: &str = "end";
36
37#[derive(Clone)]
38enum Node {
39    Agent(Box<Agent>),
40    Step(Arc<dyn Tool>),
41}
42
43/// Builds a pipeline of agents and tool fns that run one after another.
44/// Each node reads the output of the node before it, the first reads the
45/// input; the last node's output is the answer. Fan-out, routers and
46/// human nodes stay in workflow TOML.
47#[derive(Clone)]
48pub struct Graph {
49    name: String,
50    nodes: Vec<(String, Node)>,
51    edges: Vec<(String, String)>,
52    storage: Storage,
53    limits: Limits,
54    ledger: Option<Arc<dyn UsageLedger>>,
55    max_steps: Option<u32>,
56    retries: u32,
57    law_paths: Vec<PathBuf>,
58    inline_laws: Vec<String>,
59    auto_laws: bool,
60    pub(crate) trace: crate::trace::TraceConfig,
61    pub(crate) private: bool,
62}
63
64impl Graph {
65    /// Starts a graph builder called `name`, 1 to 64 of `[a-z0-9-]`.
66    /// `build` checks the name with the workflow rules.
67    /// Every setting starts at its documented default.
68    pub fn new(name: impl Into<String>) -> Self {
69        Graph {
70            name: name.into(),
71            nodes: Vec::new(),
72            edges: Vec::new(),
73            storage: Storage::memory(),
74            limits: Limits::default(),
75            ledger: None,
76            max_steps: None,
77            retries: DEFAULT_GRAPH_RETRIES,
78            law_paths: Vec::new(),
79            inline_laws: Vec::new(),
80            auto_laws: true,
81            trace: crate::trace::TraceConfig::default(),
82            private: false,
83        }
84    }
85
86    /// Adds agent node `id` running `agent` on the previous node's output.
87    /// The agent keeps its own model binding; its tools and evals join the
88    /// graph, and its storage, retries and events are the graph's. An agent
89    /// with its own limits, laws or ledger fails `build`: set them on the
90    /// graph, so no spend cap or counter is dropped.
91    pub fn agent(mut self, id: impl Into<String>, agent: Agent) -> Self {
92        self.nodes.push((id.into(), Node::Agent(Box::new(agent))));
93        self
94    }
95
96    /// Adds fn node `id` calling `step`, a `#[tool]` fn or `tool(..)`.
97    /// Its argument names must equal the ids of the nodes that feed it
98    /// (`input` for the first node); `build` checks this.
99    pub fn step(mut self, id: impl Into<String>, step: impl AsTool) -> Self {
100        self.nodes.push((id.into(), Node::Step(step.into_arc())));
101        self
102    }
103
104    /// Adds an edge from node `from` to node `to`.
105    /// Edges must form one chain; with no edges the nodes run in the
106    /// order they were added.
107    pub fn edge(mut self, from: impl Into<String>, to: impl Into<String>) -> Self {
108        self.edges.push((from.into(), to.into()));
109        self
110    }
111
112    /// Sets where graph checkpoints live.
113    /// Defaults to `Storage::memory()`, fresh per run.
114    /// Returns the builder.
115    pub fn checkpoints(mut self, storage: Storage) -> Self {
116        self.storage = storage;
117        self
118    }
119
120    /// Sets the spend limits for the whole graph run.
121    /// Defaults to `Limits::default()`, no limit.
122    /// Returns the builder.
123    pub fn limits(mut self, limits: Limits) -> Self {
124        self.limits = limits;
125        self
126    }
127
128    /// Sets the usage ledger that period limits (`scope`, `user`) and the
129    /// agent nodes' route daily cloud spend count in. Defaults to a fresh
130    /// in-memory ledger per build; pass a durable one so caps survive
131    /// rebuilds and restarts.
132    pub fn ledger(mut self, ledger: Arc<dyn UsageLedger>) -> Self {
133        self.ledger = Some(ledger);
134        self
135    }
136
137    /// Caps graph steps per run; 1 to 10000, checked at `build`.
138    /// Defaults to the workflow default.
139    /// Returns the builder.
140    pub fn max_steps(mut self, steps: u32) -> Self {
141        self.max_steps = Some(steps);
142        self
143    }
144
145    /// Sets how often a transient failure is retried per run.
146    /// At most 50, checked at `build`; defaults to 3.
147    /// Returns the builder.
148    pub fn retries(mut self, retries: u32) -> Self {
149        self.retries = retries;
150        self
151    }
152
153    /// Adds a `.bend` law file, checked at `build`.
154    /// 0.2 stores laws; no run proves them yet.
155    /// Returns the builder.
156    pub fn laws(mut self, path: impl AsRef<Path>) -> Self {
157        self.law_paths.push(path.as_ref().to_path_buf());
158        self
159    }
160
161    /// Adds one inline law, checked at `build`.
162    /// 0.2 stores laws; no run proves them yet.
163    /// Returns the builder.
164    pub fn law(mut self, law: impl Into<String>) -> Self {
165        self.inline_laws.push(law.into());
166        self
167    }
168
169    /// Asks for laws derived from the code as well. Defaults to `true`.
170    /// 0.2 records the choice only.
171    /// Returns the builder.
172    pub fn auto_laws(mut self, on: bool) -> Self {
173        self.auto_laws = on;
174        self
175    }
176
177    /// Checks the nodes, edges, workflow, every agent and tool, and the
178    /// storage, then returns a ready graph. Makes no model call.
179    /// Fails with the first problem found.
180    pub async fn build(self) -> Result<BuiltGraph, KitError> {
181        let owner = format!("graph:{}", self.name);
182        let secrets: Vec<Secret> = self
183            .nodes
184            .iter()
185            .filter_map(|(_, node)| match node {
186                Node::Agent(agent) => agent.trace_secret(),
187                Node::Step(_) => None,
188            })
189            .collect();
190        let traced = self.trace.open(&owner, &self.name, &secrets)?;
191        match traced {
192            Some(t) => {
193                let tracer = t.tracer.clone();
194                tracer.in_scope(self.build_in(owner, Some(t))).await
195            }
196            None => self.build_in(owner, None).await,
197        }
198    }
199
200    async fn build_in(
201        mut self,
202        owner: String,
203        traced: Option<crate::trace::Traced>,
204    ) -> Result<BuiltGraph, KitError> {
205        if self.private {
206            for (_, node) in &mut self.nodes {
207                if let Node::Agent(agent) = node {
208                    agent.route.private = true;
209                }
210            }
211        }
212        #[cfg(feature = "local")]
213        {
214            let mut loads = crate::local::Loads::new();
215            for (_, node) in &mut self.nodes {
216                if let Node::Agent(agent) = node {
217                    let loaded = agent.as_ref().clone().load_local(&mut loads).await?;
218                    **agent = loaded;
219                }
220            }
221        }
222        let fail = |m: String| KitError::config(&owner, m);
223        if self.retries > MAX_GRAPH_RETRIES {
224            return Err(fail(format!(
225                "retries must be at most {MAX_GRAPH_RETRIES}, got {}",
226                self.retries
227            )));
228        }
229        let order = self.chain().map_err(fail)?;
230        let laws = Laws::check(&owner, &self.law_paths, &self.inline_laws, self.auto_laws)?;
231        let workflow = self.workflow(&order)?;
232        let mut registry = ToolRegistry::new();
233        let mut agent_io = SimpleIo::new(ToolRegistry::new());
234        let mut files: HashMap<String, String> = HashMap::new();
235        let mut keys: HashMap<String, (String, &Agent)> = HashMap::new();
236        let mut evals: HashMap<String, EvalFn> = HashMap::new();
237        let ledger: Arc<dyn UsageLedger> = self
238            .ledger
239            .clone()
240            .unwrap_or_else(|| Arc::new(InMemoryLedger::default()));
241        for (i, id) in order.iter().enumerate() {
242            let feeder = feeder(&order, i);
243            match self.node(id) {
244                Node::Agent(agent) => {
245                    if let Some(what) = agent.graph_conflict() {
246                        return Err(fail(format!("agent node `{id}` sets its own {what}")));
247                    }
248                    let key = match keys.get(agent.name()) {
249                        Some((key, first)) if first.same_model(agent) => key.clone(),
250                        Some(_) => {
251                            return Err(fail(format!(
252                                "two different agents are named `{}`",
253                                agent.name()
254                            )));
255                        }
256                        None => {
257                            let key = format!("agent-{}", keys.len());
258                            keys.insert(agent.name().to_string(), (key.clone(), agent));
259                            key
260                        }
261                    };
262                    let prepared = agent.prepare(Some(&key), &ledger)?;
263                    for tool in &prepared.tools {
264                        share(&mut registry, tool.clone()).map_err(fail)?;
265                    }
266                    agent_io.models.entry(key).or_insert(prepared.handle);
267                    for (eval, f) in prepared.eval_fns {
268                        match evals.get(&eval) {
269                            Some(first) if Arc::ptr_eq(first, &f) => {}
270                            Some(_) => {
271                                return Err(fail(format!(
272                                    "eval `{eval}` has two different callbacks; pass one shared EvalFn"
273                                )));
274                            }
275                            None => {
276                                agent_io.evals.register(&eval, f.clone())?;
277                                evals.insert(eval, f);
278                            }
279                        }
280                    }
281                    let file = format!("{}.toml", prepared.persona.name);
282                    match files.get(&file) {
283                        Some(text) if *text != prepared.persona_text => {
284                            return Err(fail(format!(
285                                "two different agents are named `{}`",
286                                prepared.persona.name
287                            )));
288                        }
289                        Some(_) => {}
290                        None => {
291                            files.insert(file, prepared.persona_text);
292                        }
293                    }
294                }
295                Node::Step(tool) => {
296                    let args = arg_names(tool.spec());
297                    if args != [feeder] {
298                        return Err(fail(format!(
299                            "step `{id}` takes ({}) but is fed by ({feeder}); name its arguments after the nodes that feed it",
300                            args.join(", ")
301                        )));
302                    }
303                    if !takes_text(&tool.spec().schema["properties"][feeder]) {
304                        return Err(fail(format!(
305                            "step `{id}` argument `{feeder}` must accept a string; every graph node is fed text"
306                        )));
307                    }
308                    registry.register(Arc::new(StepTool::new(id, tool.clone())))?;
309                }
310            }
311        }
312        agent_io.tools = registry;
313        agent_io.events = Arc::new(Discard);
314        agent_io.ledger = ledger;
315        let agent_io: Arc<dyn AgentIo> = Arc::new(agent_io);
316        let loader = PersonaLoader::new(vec![Arc::new(MemorySource::new("graph", files))]);
317        let io = SimpleGraphIo::new(agent_io, loader);
318        GraphRun::new(
319            workflow.clone(),
320            input_state("build check"),
321            self.limits.clone(),
322            &io,
323        )
324        .await?;
325        let store = self.storage.open().await?;
326        let last = order.last().expect("chain has a node").clone();
327        Ok(BuiltGraph {
328            inner: Arc::new(Inner {
329                owner,
330                workflow,
331                io,
332                limits: self.limits,
333                store,
334                last,
335                laws,
336                trace: traced,
337            }),
338        })
339    }
340
341    /// Builds the graph and runs it once on `input`.
342    /// Returns the last node's output.
343    /// Fails like `build`, then like `BuiltGraph::run`.
344    pub async fn run(self, input: impl Into<String>) -> Result<Value, KitError> {
345        self.build().await?.run(input).await
346    }
347
348    /// Builds the graph and runs it once on `input`.
349    /// Returns the full report.
350    /// Fails like `build`, then like `BuiltGraph::run_with`.
351    pub async fn run_with(self, input: impl Into<String>) -> Result<GraphReport, KitError> {
352        self.build().await?.run_with(input).await
353    }
354
355    fn node(&self, id: &str) -> &Node {
356        let found = self.nodes.iter().find(|(n, _)| n == id);
357        &found.expect("chain ids come from the nodes").1
358    }
359
360    fn chain(&self) -> Result<Vec<String>, String> {
361        if self.nodes.is_empty() {
362            return Err("needs at least one node".into());
363        }
364        if self.nodes.len() > MAX_NODES {
365            return Err(format!(
366                "takes at most {MAX_NODES} nodes, got {}",
367                self.nodes.len()
368            ));
369        }
370        let mut ids: Vec<&str> = Vec::with_capacity(self.nodes.len());
371        for (id, _) in &self.nodes {
372            if id == INPUT || id == END {
373                return Err(format!("node id `{id}` is reserved"));
374            }
375            if ids.contains(&id.as_str()) {
376                return Err(format!("duplicate node id `{id}`"));
377            }
378            ids.push(id);
379        }
380        if self.edges.is_empty() {
381            return Ok(ids.iter().map(|s| s.to_string()).collect());
382        }
383        for (from, to) in &self.edges {
384            if let Some(unknown) = [from, to].into_iter().find(|n| !ids.contains(&n.as_str())) {
385                return Err(format!("edge names unknown node `{unknown}`"));
386            }
387        }
388        let count = |pick: &dyn Fn(&(String, String)) -> &str, id: &str| {
389            self.edges.iter().filter(|e| pick(e) == id).count()
390        };
391        for id in &ids {
392            if count(&|e| e.0.as_str(), id) > 1 {
393                return Err(format!(
394                    "node `{id}` has two outgoing edges; fan-out needs workflow TOML"
395                ));
396            }
397            if count(&|e| e.1.as_str(), id) > 1 {
398                return Err(format!(
399                    "node `{id}` has two incoming edges; joins need workflow TOML"
400                ));
401            }
402        }
403        let Some(start) = ids.iter().find(|id| count(&|e| e.1.as_str(), id) == 0) else {
404            return Err("edges form a cycle".into());
405        };
406        let mut order = vec![start.to_string()];
407        while order.len() <= ids.len() {
408            let last = order.last().expect("order starts non-empty");
409            let Some((_, next)) = self.edges.iter().find(|(from, _)| from == last) else {
410                break;
411            };
412            if order.contains(next) {
413                return Err("edges form a cycle".into());
414            }
415            order.push(next.clone());
416        }
417        if let Some(lone) = ids.iter().find(|id| !order.iter().any(|o| o == *id)) {
418            return Err(format!("node `{lone}` is not on the chain"));
419        }
420        assert_eq!(order.len(), ids.len());
421        Ok(order)
422    }
423
424    fn workflow(&self, order: &[String]) -> Result<Workflow, KitError> {
425        let mut state = toml::Table::new();
426        state.insert(INPUT.into(), Toml::String("string".into()));
427        let mut nodes = Vec::with_capacity(order.len() + 1);
428        for (i, id) in order.iter().enumerate() {
429            state.insert(id.clone(), Toml::String("string".into()));
430            let mut node = toml::Table::new();
431            node.insert("id".into(), Toml::String(id.clone()));
432            match self.node(id) {
433                Node::Agent(agent) => {
434                    node.insert("kind".into(), Toml::String("agent".into()));
435                    node.insert("persona".into(), Toml::String(agent.name().to_string()));
436                }
437                Node::Step(_) => {
438                    node.insert("kind".into(), Toml::String("tool".into()));
439                    node.insert("tool".into(), Toml::String(step_name(id)));
440                }
441            }
442            let reads = vec![Toml::String(feeder(order, i).to_string())];
443            node.insert("reads".into(), Toml::Array(reads));
444            node.insert("writes".into(), Toml::String(id.clone()));
445            nodes.push(Toml::Table(node));
446        }
447        let mut end = toml::Table::new();
448        end.insert("id".into(), Toml::String(END.into()));
449        end.insert("kind".into(), Toml::String("end".into()));
450        nodes.push(Toml::Table(end));
451        let mut edges = Vec::with_capacity(order.len());
452        for (i, from) in order.iter().enumerate() {
453            let to = order.get(i + 1).map_or(END, String::as_str);
454            let mut edge = toml::Table::new();
455            edge.insert("from".into(), Toml::String(from.clone()));
456            edge.insert("to".into(), Toml::String(to.to_string()));
457            edges.push(Toml::Table(edge));
458        }
459        let mut table = toml::Table::new();
460        table.insert("name".into(), Toml::String(self.name.clone()));
461        table.insert("start".into(), Toml::String(order[0].clone()));
462        if let Some(steps) = self.max_steps {
463            table.insert("max_steps".into(), Toml::Integer(i64::from(steps)));
464        }
465        table.insert("max_retries".into(), Toml::Integer(i64::from(self.retries)));
466        table.insert("state".into(), Toml::Table(state));
467        table.insert("nodes".into(), Toml::Array(nodes));
468        table.insert("edges".into(), Toml::Array(edges));
469        let text = toml::to_string(&table).map_err(|e| {
470            KitError::config(
471                &format!("graph:{}", self.name),
472                format!("workflow does not serialize: {e}"),
473            )
474        })?;
475        Ok(Workflow::parse(&format!("graph:{}", self.name), &text)?)
476    }
477}
478
479impl fmt::Debug for Graph {
480    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
481        let ids: Vec<&str> = self.nodes.iter().map(|(id, _)| id.as_str()).collect();
482        f.debug_struct("Graph")
483            .field("name", &self.name)
484            .field("nodes", &ids)
485            .field("edges", &self.edges)
486            .field("storage", &self.storage)
487            .field("retries", &self.retries)
488            .field("ledger", &self.ledger.is_some())
489            .field("private", &self.private)
490            .finish_non_exhaustive()
491    }
492}
493
494/// The result of one finished graph run: the last node's output, the
495/// whole state, usage, steps and the run id.
496/// Read it through the getters.
497#[derive(Debug, Clone, PartialEq)]
498#[non_exhaustive]
499pub struct GraphReport {
500    output: Value,
501    state: Map<String, Value>,
502    usage: Usage,
503    steps: u64,
504    run_id: RunId,
505    trace_path: Option<PathBuf>,
506}
507
508impl GraphReport {
509    /// Returns the last node's output, the answer of the graph.
510    /// A string for text nodes.
511    /// The same value `run` returns.
512    pub fn output(&self) -> &Value {
513        &self.output
514    }
515
516    /// Returns the final state: `input` plus one entry per node id.
517    /// Each value is that node's output.
518    /// Read only.
519    pub fn state(&self) -> &Map<String, Value> {
520        &self.state
521    }
522
523    /// Returns the tokens and cost every agent node used, summed.
524    /// Cost is in millionths of a US dollar.
525    /// Tool nodes add nothing.
526    pub fn usage(&self) -> Usage {
527        self.usage
528    }
529
530    /// Returns how many graph steps the run took.
531    /// Bounded by the workflow's `max_steps`.
532    /// At least one.
533    pub fn steps(&self) -> u64 {
534        self.steps
535    }
536
537    /// Returns the id of the run, for `resume` and logs.
538    /// Unique per run.
539    /// Stable across checkpoints.
540    pub fn run_id(&self) -> RunId {
541        self.run_id
542    }
543
544    /// Returns the trace file this run was written to.
545    /// `None` when tracing is off or goes to a custom sink.
546    /// Every run of one built graph shares the file.
547    pub fn trace_path(&self) -> Option<&Path> {
548        self.trace_path.as_deref()
549    }
550}
551
552/// A graph that passed every `build` check, ready to run many times.
553/// Cheap to clone and safe to share across tasks; in-memory checkpoints
554/// are dropped after each run.
555#[derive(Clone)]
556pub struct BuiltGraph {
557    inner: Arc<Inner>,
558}
559
560struct Inner {
561    owner: String,
562    workflow: Workflow,
563    io: SimpleGraphIo,
564    limits: Limits,
565    store: Option<Arc<dyn CheckpointStore>>,
566    last: String,
567    laws: Laws,
568    trace: Option<crate::trace::Traced>,
569}
570
571impl BuiltGraph {
572    /// Returns the trace file this graph writes, one root span per run.
573    /// `None` when tracing is off or goes to a custom sink.
574    /// The file is created at `build`.
575    pub fn trace_path(&self) -> Option<&Path> {
576        crate::trace::path_of(&self.inner.trace)
577    }
578
579    async fn traced<T>(
580        &self,
581        run_id: Option<RunId>,
582        work: impl Future<Output = Result<T, KitError>>,
583        id_of: impl Fn(&T) -> RunId,
584    ) -> Result<T, KitError> {
585        let owner = self.inner.workflow.name.as_str();
586        let traced = self.inner.trace.as_ref();
587        root_span(
588            traced,
589            Trace::Graphs,
590            "graph.run",
591            owner,
592            run_id,
593            work,
594            id_of,
595        )
596        .await
597    }
598
599    /// Runs the graph once on `input` and returns the last node's output.
600    /// Fails with `Failed` or `Paused` when the run ends without one.
601    /// Transient failures are retried by the graph engine.
602    pub async fn run(&self, input: impl Into<String>) -> Result<Value, KitError> {
603        Ok(self.run_with(input).await?.output)
604    }
605
606    /// Runs the graph once on `input` and returns the full report.
607    /// Same failures as `run`.
608    /// The run id in the report works with `resume`.
609    pub async fn run_with(&self, input: impl Into<String>) -> Result<GraphReport, KitError> {
610        let input = input.into();
611        self.traced(None, self.run_untraced(input), GraphReport::run_id)
612            .await
613    }
614
615    async fn run_untraced(&self, input: String) -> Result<GraphReport, KitError> {
616        let inner = &self.inner;
617        let mut run = GraphRun::new(
618            inner.workflow.clone(),
619            input_state(&input),
620            inner.limits.clone(),
621            &inner.io,
622        )
623        .await?;
624        let store: Arc<dyn CheckpointStore> = match &inner.store {
625            Some(store) => store.clone(),
626            None => Arc::new(InMemCheckpoints::default()),
627        };
628        self.finish(&mut run, store.as_ref()).await
629    }
630
631    /// Continues graph run `run_id` from its latest checkpoint and returns
632    /// the last node's output; a finished run returns it again. Needs
633    /// durable storage and a run this same workflow started.
634    pub async fn resume(&self, run_id: RunId) -> Result<Value, KitError> {
635        self.traced(Some(run_id), self.resume_untraced(run_id), |_| run_id)
636            .await
637    }
638
639    async fn resume_untraced(&self, run_id: RunId) -> Result<Value, KitError> {
640        let inner = &self.inner;
641        let Some(store) = &inner.store else {
642            return Err(KitError::config(
643                &inner.owner,
644                "resume needs Storage::sqlite(..) or Storage::custom(..) checkpoints",
645            ));
646        };
647        let Some(checkpoint) = store.latest(run_id).await? else {
648            return Err(KitError::config(
649                &inner.owner,
650                format!("no checkpoint for run {run_id}"),
651            ));
652        };
653        let mut run = GraphRun::from_checkpoint(&checkpoint)?;
654        if run.workflow() != &inner.workflow {
655            return Err(KitError::config(
656                &inner.owner,
657                format!(
658                    "run {run_id} was started by a different workflow; resume it with the graph that started it"
659                ),
660            ));
661        }
662        Ok(self.finish(&mut run, store.as_ref()).await?.output)
663    }
664
665    /// Returns the validated workflow this graph runs.
666    /// Built from the builder by `Workflow::parse`.
667    /// Read only.
668    pub fn workflow(&self) -> &Workflow {
669        &self.inner.workflow
670    }
671
672    /// Returns the laws checked at `build`.
673    /// 0.2 stores them; runs do not prove them yet.
674    /// Read only.
675    pub fn laws(&self) -> &Laws {
676        &self.inner.laws
677    }
678
679    async fn finish(
680        &self,
681        run: &mut GraphRun,
682        store: &dyn CheckpointStore,
683    ) -> Result<GraphReport, KitError> {
684        let inner = &self.inner;
685        if store.latest(run.run_id()).await?.is_none() {
686            store.save(run.checkpoint()).await?;
687        }
688        let cap =
689            2 * u64::from(inner.workflow.max_steps) + u64::from(inner.workflow.max_retries) + 8;
690        for _ in 0..cap {
691            let before = run.steps();
692            let outcome = run.step(&inner.io).await;
693            if run.steps() != before {
694                store.save(run.checkpoint()).await?;
695            }
696            match outcome {
697                GraphOutcome::Continue => {}
698                GraphOutcome::RetryAt { at_ms, .. } => {
699                    wait_until(inner.io.agent.clock(), at_ms, RETRY_WAIT_CHUNK_MS).await;
700                }
701                GraphOutcome::Waiting(reason) => {
702                    return Err(KitError::Paused {
703                        run_id: run.run_id(),
704                        reason,
705                    })
706                }
707                GraphOutcome::Failed(reason) => {
708                    return Err(KitError::Failed {
709                        run_id: run.run_id(),
710                        reason,
711                    })
712                }
713                GraphOutcome::Done(state) => {
714                    let output = state
715                        .get(&inner.last)
716                        .cloned()
717                        .expect("a finished chain run wrote its last node");
718                    return Ok(GraphReport {
719                        output,
720                        state,
721                        usage: run.usage(),
722                        steps: run.steps(),
723                        run_id: run.run_id(),
724                        trace_path: self.trace_path().map(Path::to_path_buf),
725                    });
726                }
727            }
728        }
729        Err(KitError::Failed {
730            run_id: run.run_id(),
731            reason: format!("did not finish within {cap} steps"),
732        })
733    }
734}
735
736impl fmt::Debug for BuiltGraph {
737    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
738        let inner = &self.inner;
739        f.debug_struct("BuiltGraph")
740            .field("name", &inner.workflow.name)
741            .field("nodes", &inner.workflow.nodes.len())
742            .field("durable", &inner.store.is_some())
743            .field("laws", &inner.laws)
744            .finish_non_exhaustive()
745    }
746}
747
748struct StepTool {
749    spec: ToolSpec,
750    inner: Arc<dyn Tool>,
751}
752
753impl StepTool {
754    fn new(id: &str, inner: Arc<dyn Tool>) -> Self {
755        let spec = ToolSpec {
756            name: step_name(id),
757            ..inner.spec().clone()
758        };
759        StepTool { spec, inner }
760    }
761}
762
763#[async_trait]
764impl Tool for StepTool {
765    fn spec(&self) -> &ToolSpec {
766        &self.spec
767    }
768
769    async fn call(&self, args: Value, ctx: &ToolContext) -> Result<ToolOutput, ToolError> {
770        let out = self.inner.call(args, ctx).await?;
771        if out.is_error {
772            return Ok(out);
773        }
774        Ok(ToolOutput::text(Value::String(out.content).to_string()))
775    }
776}
777
778async fn wait_until(clock: &dyn Clock, at_ms: i64, chunk_ms: i64) {
779    assert!(chunk_ms > 0, "a wait chunk lasts some time");
780    let first = at_ms.saturating_sub(clock.now_ms());
781    let rounds = first.max(0) / chunk_ms + 2;
782    for _ in 0..rounds {
783        let left = at_ms.saturating_sub(clock.now_ms());
784        if left <= 0 {
785            return;
786        }
787        let ms = u64::try_from(left.min(chunk_ms)).expect("left is positive");
788        tokio::time::sleep(Duration::from_millis(ms)).await;
789    }
790}
791
792fn step_name(id: &str) -> String {
793    format!("step__{id}")
794}
795
796fn feeder(order: &[String], i: usize) -> &str {
797    if i == 0 {
798        INPUT
799    } else {
800        &order[i - 1]
801    }
802}
803
804fn input_state(text: &str) -> Map<String, Value> {
805    let mut state = Map::new();
806    state.insert(INPUT.into(), Value::String(text.to_string()));
807    state
808}
809
810fn takes_text(schema: &Value) -> bool {
811    match schema {
812        Value::Bool(any) => *any,
813        Value::Object(map) => match map.get("type") {
814            Some(Value::String(t)) => t == "string",
815            Some(Value::Array(types)) => types.iter().any(|t| t == "string"),
816            Some(_) => false,
817            None => !["$ref", "anyOf", "oneOf", "allOf", "enum", "const", "not"]
818                .iter()
819                .any(|k| map.contains_key(*k)),
820        },
821        _ => false,
822    }
823}
824
825fn arg_names(spec: &ToolSpec) -> Vec<String> {
826    let mut names: Vec<String> = spec.schema["properties"]
827        .as_object()
828        .map(|p| p.keys().cloned().collect())
829        .unwrap_or_default();
830    names.sort();
831    names
832}
833
834fn share(registry: &mut ToolRegistry, tool: Arc<dyn Tool>) -> Result<(), String> {
835    let name = tool.spec().name.clone();
836    match registry.get(&name) {
837        Some(existing) if Arc::ptr_eq(&existing, &tool) => Ok(()),
838        Some(existing) if existing.spec() == tool.spec() => Err(format!(
839            "tool `{name}` has two different implementations; pass one shared tool to both agents"
840        )),
841        Some(_) => Err(format!(
842            "tool `{name}` is registered twice with different specs"
843        )),
844        None => registry.register(tool).map_err(|e| e.to_string()),
845    }
846}
847
848#[cfg(test)]
849mod tests {
850    use super::wait_until;
851    use troupekit_core::clock::{Clock, SystemClock};
852
853    #[tokio::test]
854    async fn retry_wait_reaches_a_deadline_past_one_chunk() {
855        let clock = SystemClock;
856        let at = clock.now_ms() + 25;
857        wait_until(&clock, at, 10).await;
858        assert!(clock.now_ms() >= at);
859        let before = clock.now_ms();
860        wait_until(&clock, before - 1_000, 10).await;
861        assert!(clock.now_ms() - before < 10);
862    }
863}