1use crate::error::GraphError;
2use crate::io::{Emitter, GraphIo, NodeIo};
3use crate::workflow::{Ask, Node, NodeKind, Workflow};
4use futures_util::future::join_all;
5use serde::{Deserialize, Serialize};
6use serde_json::{Map, Value};
7use std::sync::atomic::{AtomicU64, Ordering};
8use troupekit_agent::{AgentRun, Budget, Limits, RunState, StepOutcome};
9use troupekit_core::event::{EventBody, PauseReason, Usage};
10use troupekit_core::ids::RunId;
11use troupekit_core::message::{Message, Role};
12use troupekit_core::store::Checkpoint;
13use troupekit_tools::{fence_untrusted, ToolContext, ToolError};
14use troupekit_agent::persona::{open_trace, SavedTrace};
15use troupekit_trace::{content, trace, trace_span, Span, Trace, TraceSpec};
16
17pub const GRAPH_FORMAT: u32 = 1;
21
22const MAX_RETRY_DELAY_MS: u64 = 300_000;
23const BASE_RETRY_DELAY_MS: u64 = 1_000;
24
25#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
29#[serde(tag = "status", rename_all = "snake_case", deny_unknown_fields)]
30pub enum GraphStatus {
31 Queued,
32 Running,
33 Checkpointed,
34 WaitingHuman { reason: PauseReason },
35 WaitingBudget { reason: PauseReason },
36 Done,
37 Failed { error: String },
38}
39
40#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
45pub enum Stop {
46 TimeLimit { limit_ms: u64 },
47 Cancelled,
48}
49
50impl Stop {
51 fn error(&self) -> String {
52 match self {
53 Stop::TimeLimit { limit_ms } => format!("time limit of {limit_ms} ms of active work reached"),
54 Stop::Cancelled => "cancelled".into(),
55 }
56 }
57}
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
64#[serde(rename_all = "snake_case")]
65enum Failure {
66 Final,
67 Tool,
68 Transient,
69 Host,
70}
71
72impl Failure {
73 fn of_error(error: &str) -> Failure {
74 let after_node = error
75 .strip_prefix("node `")
76 .and_then(|rest| rest.split_once("`: tool `"))
77 .and_then(|(_, rest)| rest.split_once("`: "))
78 .map(|(_, rest)| rest);
79 let retries = error
80 .strip_prefix("error after ")
81 .is_some_and(|rest| rest.contains(" retries: "));
82 match after_node {
83 Some(rest) if rest.starts_with("failed: ") || rest.starts_with("http: ") => Failure::Tool,
84 _ if retries => Failure::Transient,
85 _ => Failure::Final,
86 }
87 }
88}
89
90#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
93#[serde(deny_unknown_fields)]
94struct CallKey {
95 step: u64,
96 index: usize,
97}
98
99struct ToolFailure {
102 message: String,
103 transient: bool,
104}
105
106#[derive(Debug, Clone, PartialEq)]
110pub enum GraphOutcome {
111 Continue,
112 RetryAt { at_ms: i64, error: String },
113 Waiting(PauseReason),
114 Done(Map<String, Value>),
115 Failed(String),
116}
117
118#[derive(Debug, Clone, PartialEq)]
122pub struct HumanAsk {
123 pub node: String,
124 pub ask: Ask,
125 pub prompt: Option<String>,
126 pub data: Map<String, Value>,
127}
128
129#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
130#[serde(tag = "at", rename_all = "snake_case", deny_unknown_fields)]
131enum At {
132 Enter,
133 Agent {
134 run: Box<AgentRun>,
135 call_cap: Option<u64>,
136 run_cap: Option<u64>,
137 },
138 Human {
139 data: Map<String, Value>,
140 },
141 Joined,
142 Left,
143}
144
145#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
146#[serde(deny_unknown_fields)]
147struct Branch {
148 node: String,
149 at: At,
150 #[serde(default, skip_serializing_if = "Option::is_none")]
151 call: Option<CallKey>,
152}
153
154impl Branch {
155 fn enter(node: &str) -> Branch {
156 Branch {
157 node: node.to_string(),
158 at: At::Enter,
159 call: None,
160 }
161 }
162
163 fn budget_paused(&self) -> Option<&PauseReason> {
164 match &self.at {
165 At::Agent { run, .. } => match run.state() {
166 RunState::Paused { reason, .. } => Some(reason),
167 _ => None,
168 },
169 _ => None,
170 }
171 }
172}
173
174enum Work {
175 Idle,
176 Agent(StepOutcome),
177 Tool(Result<Value, ToolFailure>),
178}
179
180#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
185#[serde(deny_unknown_fields)]
186pub struct GraphRun {
187 format: u32,
188 run_id: RunId,
189 workflow: Workflow,
190 limits: Limits,
191 state: Map<String, Value>,
192 branches: Vec<Branch>,
193 status: GraphStatus,
194 usage: Usage,
195 retries: u32,
196 seq: u64,
197 steps: u64,
198 #[serde(default, skip_serializing_if = "Option::is_none")]
199 time_limit_ms: Option<u64>,
200 #[serde(default)]
201 active_ms: u64,
202 #[serde(default, skip_serializing_if = "Option::is_none")]
203 stopped: Option<Stop>,
204 #[serde(default, skip_serializing_if = "Option::is_none")]
205 failure: Option<Failure>,
206 #[serde(default, skip_serializing_if = "Option::is_none")]
207 trace: Option<SavedTrace>,
208}
209
210impl GraphRun {
211 pub async fn new(
215 workflow: Workflow,
216 input: Map<String, Value>,
217 limits: Limits,
218 io: &dyn GraphIo,
219 ) -> Result<GraphRun, GraphError> {
220 let setup = |id: &str, m: String| GraphError::Setup(format!("node `{id}`: {m}"));
221 for n in &workflow.nodes {
222 match &n.kind {
223 NodeKind::Agent { persona, .. } => {
224 let p = io
225 .persona(persona)
226 .await
227 .map_err(|e| setup(&n.id, e.to_string()))?;
228 let probe = vec![Message::text(Role::User, "setup check")];
229 AgentRun::new(&p, probe, Limits::default(), io.agent())
230 .await
231 .map_err(|e| setup(&n.id, e.to_string()))?;
232 }
233 NodeKind::Tool { tool } if io.agent().tools().get(tool).is_none() => {
234 return Err(setup(&n.id, format!("tool `{tool}` is not registered")));
235 }
236 NodeKind::Router { condition }
237 if io.conditions().get(&condition.name).is_none() =>
238 {
239 return Err(setup(
240 &n.id,
241 format!("condition `{}` is not registered", condition.name),
242 ));
243 }
244 _ => {}
245 }
246 }
247 for (k, v) in &input {
248 if !workflow.state.contains_key(k) {
249 return Err(GraphError::Setup(format!(
250 "input `{k}` is not declared in [state]"
251 )));
252 }
253 let errs = workflow.check_value(k, v);
254 if !errs.is_empty() {
255 return Err(GraphError::Setup(format!(
256 "input `{k}`: {}",
257 errs.join("; ")
258 )));
259 }
260 }
261 let start = Branch::enter(&workflow.start);
262 Ok(GraphRun {
263 format: GRAPH_FORMAT,
264 run_id: RunId::new(),
265 workflow,
266 limits,
267 state: input,
268 branches: vec![start],
269 status: GraphStatus::Queued,
270 usage: Usage::default(),
271 retries: 0,
272 seq: 0,
273 steps: 0,
274 time_limit_ms: None,
275 active_ms: 0,
276 stopped: None,
277 failure: None,
278 trace: None,
279 })
280 }
281
282 pub fn set_trace(&mut self, spec: TraceSpec) {
286 self.trace = Some(SavedTrace::from_spec(&spec));
287 assert_eq!(self.trace(), Some(spec));
288 }
289
290 pub fn trace(&self) -> Option<TraceSpec> {
293 self.trace
294 .as_ref()
295 .map(|saved| saved.spec().expect("trace spec checked when set or loaded"))
296 }
297
298 pub fn with_time_limit(mut self, limit_ms: u64) -> GraphRun {
302 assert!(limit_ms > 0, "a time limit allows some work");
303 self.time_limit_ms = Some(limit_ms);
304 self
305 }
306
307 pub fn add_active_ms(&mut self, ms: u64) {
311 self.active_ms = self.active_ms.saturating_add(ms);
312 }
313
314 pub fn active_ms(&self) -> u64 {
318 self.active_ms
319 }
320
321 pub fn time_limit_ms(&self) -> Option<u64> {
325 self.time_limit_ms
326 }
327
328 pub fn over_time(&self) -> bool {
332 self.time_limit_ms.is_some_and(|limit| self.active_ms >= limit)
333 }
334
335 pub fn stopped(&self) -> Option<&Stop> {
339 self.stopped.as_ref()
340 }
341
342 pub fn stop(&mut self, why: Stop) -> Result<(), GraphError> {
346 if matches!(self.status, GraphStatus::Done | GraphStatus::Failed { .. }) {
347 return Err(GraphError::Resume("the run is finished".into()));
348 }
349 self.status = GraphStatus::Failed { error: why.error() };
350 self.stopped = Some(why);
351 self.steps += 1;
352 Ok(())
353 }
354
355 pub fn retryable(&self) -> bool {
359 self.stopped.is_some() || matches!(self.failure, Some(Failure::Tool | Failure::Transient))
360 }
361
362 pub fn retry(&mut self, time_limit_ms: Option<u64>) -> Result<(), GraphError> {
367 if !self.retryable() {
368 return Err(GraphError::Resume(
369 "only a stopped run or one failed on a transient error can be retried".into(),
370 ));
371 }
372 assert!(matches!(self.status, GraphStatus::Failed { .. }), "a retryable run is failed");
373 if self.stopped.is_none() && self.failure == Some(Failure::Tool) {
374 let step = self.steps;
375 let tools: Vec<bool> = self
376 .branches
377 .iter()
378 .map(|b| b.at == At::Enter && matches!(self.node(&b.node).kind, NodeKind::Tool { .. }))
379 .collect();
380 assert!(tools.iter().any(|t| *t), "a tool failure leaves its branch at the tool");
381 for (index, (b, tool)) in self.branches.iter_mut().zip(tools).enumerate() {
382 if tool {
383 b.call.get_or_insert(CallKey { step, index });
384 }
385 }
386 }
387 self.stopped = None;
388 self.failure = None;
389 self.retries = 0;
390 self.active_ms = 0;
391 self.time_limit_ms = time_limit_ms;
392 self.queue();
393 Ok(())
394 }
395
396 pub fn from_checkpoint(cp: &Checkpoint) -> Result<GraphRun, GraphError> {
400 let bad = |m: String| GraphError::Checkpoint(m);
401 let mut run: GraphRun =
402 serde_json::from_value(cp.state.clone()).map_err(|e| bad(e.to_string()))?;
403 if run.format != GRAPH_FORMAT {
404 return Err(bad(format!(
405 "graph format {} is not {GRAPH_FORMAT}",
406 run.format
407 )));
408 }
409 if run.run_id != cp.run_id || run.steps != cp.step {
410 return Err(bad("checkpoint header does not match its state".into()));
411 }
412 if run.status == GraphStatus::Running {
413 return Err(bad("a checkpoint never holds a running step".into()));
414 }
415 if let Some(saved) = &run.trace {
416 saved.check_loaded().map_err(bad)?;
417 }
418 for b in &run.branches {
419 if let At::Agent { run: agent, .. } = &b.at {
420 AgentRun::from_checkpoint(&agent.checkpoint())
421 .map_err(|e| bad(format!("node `{}`: {e}", b.node)))?;
422 }
423 }
424 if let (GraphStatus::Failed { error }, None, None) = (&run.status, &run.stopped, run.failure) {
425 run.failure = Some(Failure::of_error(error));
426 }
427 Ok(run)
428 }
429
430 pub fn checkpoint(&self) -> Checkpoint {
434 assert_ne!(
435 self.status,
436 GraphStatus::Running,
437 "checkpoints are taken between steps"
438 );
439 Checkpoint {
440 run_id: self.run_id,
441 step: self.steps,
442 state: serde_json::to_value(self).expect("graph run serializes"),
443 }
444 }
445
446 pub fn host_failed(&self) -> bool {
450 self.failure == Some(Failure::Host)
451 }
452
453 pub fn run_id(&self) -> RunId {
457 self.run_id
458 }
459
460 pub fn status(&self) -> &GraphStatus {
464 &self.status
465 }
466
467 pub fn state(&self) -> &Map<String, Value> {
471 &self.state
472 }
473
474 pub fn usage(&self) -> Usage {
478 self.branches.iter().fold(self.usage, |acc, b| match &b.at {
479 At::Agent { run, .. } => acc + run.usage(),
480 _ => acc,
481 })
482 }
483
484 pub fn steps(&self) -> u64 {
488 self.steps
489 }
490
491 pub fn workflow(&self) -> &Workflow {
495 &self.workflow
496 }
497
498 pub fn pending_human(&self) -> Vec<HumanAsk> {
502 self.branches
503 .iter()
504 .filter_map(|b| {
505 let At::Human { data } = &b.at else {
506 return None;
507 };
508 let NodeKind::Human { ask, prompt } = &self.node(&b.node).kind else {
509 unreachable!("human branches sit at human nodes");
510 };
511 Some(HumanAsk {
512 node: b.node.clone(),
513 ask: *ask,
514 prompt: prompt.clone(),
515 data: data.clone(),
516 })
517 })
518 .collect()
519 }
520
521 pub fn resume(&mut self, node: &str, answer: Value) -> Result<(), GraphError> {
525 let bad = |m: String| GraphError::Resume(m);
526 if matches!(self.status, GraphStatus::Done | GraphStatus::Failed { .. }) {
527 return Err(bad("the run is finished".into()));
528 }
529 let i = self
530 .branches
531 .iter()
532 .position(|b| b.node == node && matches!(b.at, At::Human { .. }))
533 .ok_or_else(|| bad(format!("no branch waits at human node `{node}`")))?;
534 let key = self
535 .node(node)
536 .writes
537 .clone()
538 .expect("human nodes write their answer");
539 let errs = self.workflow.check_value(&key, &answer);
540 if !errs.is_empty() {
541 return Err(bad(format!(
542 "answer does not match `{key}`: {}",
543 errs.join("; ")
544 )));
545 }
546 self.state.insert(key, answer);
547 self.branches[i].at = At::Left;
548 self.queue();
549 Ok(())
550 }
551
552 pub fn tighten(&mut self, limits: &Limits) {
557 self.limits = self.limits.clone().stricter(limits);
558 let spent = self.usage().cost_usd_micros;
559 let base = self.limits.clone();
560 for b in &mut self.branches {
561 if let At::Agent { run, call_cap, run_cap } = &mut b.at {
562 let own = run.usage().cost_usd_micros;
563 run.tighten(&node_limits(&base, spent.saturating_sub(own), *call_cap, *run_cap));
564 }
565 }
566 }
567
568 pub fn raise_budget(&mut self, limits: Limits) -> Result<(), GraphError> {
572 if matches!(self.status, GraphStatus::Done | GraphStatus::Failed { .. }) {
573 return Err(GraphError::Resume("the run is finished".into()));
574 }
575 self.limits = limits;
576 let spent = self.usage().cost_usd_micros;
577 let base = self.limits.clone();
578 for b in &mut self.branches {
579 if b.budget_paused().is_none() {
580 continue;
581 }
582 let At::Agent {
583 run,
584 call_cap,
585 run_cap,
586 } = &mut b.at
587 else {
588 unreachable!("budget pauses happen in agent branches");
589 };
590 let own = run.usage().cost_usd_micros;
591 run.resume(node_limits(&base, spent - own, *call_cap, *run_cap))?;
592 }
593 self.queue();
594 Ok(())
595 }
596
597 pub async fn step(&mut self, io: &dyn GraphIo) -> GraphOutcome {
603 let working = matches!(self.status, GraphStatus::Queued | GraphStatus::Checkpointed);
604 let Some(spec) = self.trace().filter(|_| working) else {
605 return self.step_once(io).await;
606 };
607 if let Some(scope) = troupekit_trace::current() {
608 let content = scope.content() && spec.content();
609 let nested = scope.nest(spec.categories(), Some(content));
610 assert!(!nested.content() || scope.content());
611 return nested.in_scope(self.step_once(io)).await;
612 }
613 match open_trace(&spec, &self.workflow.name, self.run_id) {
614 Ok(tracer) => tracer.in_scope(self.step_once(io)).await,
615 Err(_) => self.step_once(io).await,
616 }
617 }
618
619 async fn step_once(&mut self, io: &dyn GraphIo) -> GraphOutcome {
620 match &self.status {
621 GraphStatus::Done => return GraphOutcome::Done(self.state.clone()),
622 GraphStatus::Failed { error } => return GraphOutcome::Failed(error.clone()),
623 GraphStatus::WaitingHuman { reason } | GraphStatus::WaitingBudget { reason } => {
624 return GraphOutcome::Waiting(reason.clone())
625 }
626 GraphStatus::Running => unreachable!("a step never starts inside another"),
627 GraphStatus::Queued | GraphStatus::Checkpointed => {}
628 }
629 self.steps += 1;
630 self.status = GraphStatus::Running;
631 let seq = AtomicU64::new(self.seq);
632 let em = Emitter {
633 run_id: self.run_id,
634 seq: &seq,
635 io: io.agent(),
636 };
637 if self.seq == 0 {
638 em.emit(EventBody::RunStarted {
639 workflow: self.workflow.name.clone(),
640 });
641 }
642 self.failure = None;
643 let outcome = self.work(io, &em).await;
644 match &outcome {
645 GraphOutcome::Continue | GraphOutcome::RetryAt { .. } => {
646 self.status = GraphStatus::Checkpointed
647 }
648 GraphOutcome::Waiting(reason) => {
649 self.status = match reason {
650 PauseReason::Budget { .. } => GraphStatus::WaitingBudget {
651 reason: reason.clone(),
652 },
653 _ => GraphStatus::WaitingHuman {
654 reason: reason.clone(),
655 },
656 };
657 em.emit(EventBody::RunPaused {
658 reason: reason.clone(),
659 });
660 }
661 GraphOutcome::Done(_) => {
662 self.status = GraphStatus::Done;
663 em.emit(EventBody::RunFinished {
664 usage: self.usage(),
665 });
666 }
667 GraphOutcome::Failed(error) => {
668 self.failure.get_or_insert(Failure::Final);
669 self.status = GraphStatus::Failed {
670 error: error.clone(),
671 };
672 em.emit(EventBody::RunFailed {
673 error: error.clone(),
674 });
675 }
676 }
677 self.seq = seq.load(Ordering::SeqCst);
678 outcome
679 }
680
681 fn queue(&mut self) {
682 self.steps += 1;
683 self.status = GraphStatus::Queued;
684 }
685
686 fn node(&self, id: &str) -> &Node {
687 self.workflow
688 .node(id)
689 .expect("branches sit at workflow nodes")
690 }
691
692 async fn work(&mut self, io: &dyn GraphIo, em: &Emitter<'_>) -> GraphOutcome {
693 let held = self.steps <= u64::from(self.workflow.max_steps);
694 trace!(
695 Trace::Laws,
696 "law.check",
697 law = "step_stays_within_max_steps",
698 held = held,
699 steps = self.steps,
700 max_steps = self.workflow.max_steps,
701 );
702 if !held {
703 return GraphOutcome::Failed(format!("max_steps {} reached", self.workflow.max_steps));
704 }
705 match self.settle(io).await {
706 Err(e) => return GraphOutcome::Failed(e),
707 Ok(true) => return GraphOutcome::Done(self.state.clone()),
708 Ok(false) => {}
709 }
710 let results = self.run_branches(io, em).await;
711 let mut retry: Option<(String, Option<u64>)> = None;
712 for (i, w) in results.into_iter().enumerate() {
713 let node = self.node(&self.branches[i].node).clone();
714 match w {
715 Work::Idle | Work::Agent(StepOutcome::Continue | StepOutcome::Paused(_)) => {}
716 Work::Agent(StepOutcome::Retry {
717 error,
718 retry_after_ms,
719 }) => {
720 retry.get_or_insert((error, retry_after_ms));
721 }
722 Work::Agent(StepOutcome::Failed(e)) => {
723 let At::Agent { run, .. } = &self.branches[i].at else {
724 unreachable!("agent work comes from agent branches");
725 };
726 if run.host_failed() {
727 self.failure = Some(Failure::Host);
728 }
729 return GraphOutcome::Failed(format!("node `{}`: {e}", node.id));
730 }
731 Work::Tool(Err(f)) => {
732 if f.transient {
733 self.failure = Some(Failure::Tool);
734 }
735 return GraphOutcome::Failed(format!("node `{}`: {}", node.id, f.message));
736 }
737 Work::Agent(StepOutcome::Done(output)) => {
738 let At::Agent { run, .. } = &self.branches[i].at else {
739 unreachable!("agent work comes from agent branches");
740 };
741 self.usage += run.usage();
742 self.branches[i].at = At::Left;
743 if let Err(e) = self.write(&node, output) {
744 return GraphOutcome::Failed(e);
745 }
746 }
747 Work::Tool(Ok(output)) => {
748 self.branches[i].at = At::Left;
749 if let Err(e) = self.write(&node, output) {
750 return GraphOutcome::Failed(e);
751 }
752 }
753 }
754 }
755 match self.settle(io).await {
756 Err(e) => return GraphOutcome::Failed(e),
757 Ok(true) => return GraphOutcome::Done(self.state.clone()),
758 Ok(false) => {}
759 }
760 if let Some((error, after)) = retry {
761 self.retries += 1;
762 if self.retries > self.workflow.max_retries {
763 self.failure = Some(Failure::Transient);
764 return GraphOutcome::Failed(format!(
765 "error after {} retries: {error}",
766 self.workflow.max_retries
767 ));
768 }
769 let backoff = BASE_RETRY_DELAY_MS.saturating_mul(1 << (self.retries - 1).min(20));
770 let delay = after.unwrap_or(backoff.min(MAX_RETRY_DELAY_MS));
771 let at_ms = io.agent().clock().now_ms() + i64::try_from(delay).unwrap_or(i64::MAX / 2);
772 return GraphOutcome::RetryAt { at_ms, error };
773 }
774 self.retries = 0;
775 self.wait_or_continue()
776 }
777
778 fn wait_or_continue(&self) -> GraphOutcome {
779 if self.branches.iter().any(|b| self.can_work(b)) {
780 return GraphOutcome::Continue;
781 }
782 if let Some(b) = self
783 .branches
784 .iter()
785 .find(|b| matches!(b.at, At::Human { .. }))
786 {
787 let NodeKind::Human { ask, .. } = &self.node(&b.node).kind else {
788 unreachable!("human branches sit at human nodes");
789 };
790 let node = b.node.clone();
791 return GraphOutcome::Waiting(match ask {
792 Ask::Approval => PauseReason::Approval { node },
793 Ask::Question => PauseReason::Question { node },
794 });
795 }
796 let reason = self
797 .branches
798 .iter()
799 .find_map(Branch::budget_paused)
800 .expect("a run that cannot work waits for a human or a budget");
801 GraphOutcome::Waiting(reason.clone())
802 }
803
804 fn can_work(&self, b: &Branch) -> bool {
805 match &b.at {
806 At::Agent { .. } => b.budget_paused().is_none(),
807 At::Enter => matches!(self.node(&b.node).kind, NodeKind::Tool { .. }),
808 At::Human { .. } | At::Joined | At::Left => false,
809 }
810 }
811
812 async fn run_branches(&mut self, io: &dyn GraphIo, em: &Emitter<'_>) -> Vec<Work> {
813 let workers: Vec<bool> = self.branches.iter().map(|b| self.can_work(b)).collect();
814 let (wf, state, run_id, step) = (&self.workflow, &self.state, self.run_id, self.steps);
815 let futures =
816 self.branches
817 .iter_mut()
818 .zip(workers)
819 .enumerate()
820 .map(|(i, (b, works))| async move {
821 if !works {
822 return Work::Idle;
823 }
824 let node = wf.node(&b.node).expect("branches sit at workflow nodes");
825 match (&mut b.at, &node.kind) {
826 (At::Agent { run, .. }, NodeKind::Agent { persona, .. }) => {
827 let nio = NodeIo::new(em, &node.id, persona);
828 let span = graph_step_span(&node.id, "agent", step);
829 Work::Agent(span.instrument(run.step(&nio)).await)
830 }
831 (At::Enter, NodeKind::Tool { tool }) => {
832 let key = b.call.unwrap_or(CallKey { step, index: i });
833 let ctx = ToolContext::for_call(run_id, key.step, key.index);
834 let span = graph_step_span(&node.id, "tool", step);
835 let call = call_tool(io, em, node, tool, state, ctx);
836 Work::Tool(span.instrument(call).await)
837 }
838 _ => unreachable!("only agent and tool branches work"),
839 }
840 });
841 join_all(futures).await
842 }
843
844 fn write(&mut self, node: &Node, value: Value) -> Result<(), String> {
845 let Some(key) = &node.writes else {
846 return Ok(());
847 };
848 let errs = self.workflow.check_value(key, &value);
849 if !errs.is_empty() {
850 return Err(format!(
851 "node `{}`: output does not match `{key}`: {}",
852 node.id,
853 errs.join("; ")
854 ));
855 }
856 self.state.insert(key.clone(), value);
857 Ok(())
858 }
859
860 async fn settle(&mut self, io: &dyn GraphIo) -> Result<bool, String> {
861 let passes = 2 * self.workflow.nodes.len() + 4;
862 for _ in 0..passes {
863 let mut changed = false;
864 let mut next = Vec::with_capacity(self.branches.len());
865 for b in std::mem::take(&mut self.branches) {
866 if b.at != At::Left {
867 next.push(b);
868 continue;
869 }
870 changed = true;
871 let out = self.workflow.next(&b.node);
872 assert!(!out.is_empty(), "only end nodes have no out-edges");
873 for e in &out {
874 graph_edge(&b.node, &e.to, e.when.as_deref());
875 }
876 next.extend(out.into_iter().map(|e| Branch::enter(&e.to)));
877 }
878 self.branches = next;
879 for i in 0..self.branches.len() {
880 if self.branches[i].at != At::Enter {
881 continue;
882 }
883 let node = self.node(&self.branches[i].node).clone();
884 let fail = |m: String| format!("node `{}`: {m}", node.id);
885 match &node.kind {
886 NodeKind::Tool { .. } => continue,
887 NodeKind::End => {
888 assert_eq!(self.branches.len(), 1, "branches join before an end");
889 return Ok(true);
890 }
891 NodeKind::Join => self.branches[i].at = At::Joined,
892 NodeKind::Router { condition } => {
893 let f = io.conditions().get(&condition.name).ok_or_else(|| {
894 fail(format!("condition `{}` is not registered", condition.name))
895 })?;
896 let label = f(&self.state, &condition.args).map_err(fail)?;
897 let edge = self
898 .workflow
899 .next(&node.id)
900 .into_iter()
901 .find(|e| e.when.as_deref() == Some(label.as_str()))
902 .ok_or_else(|| fail(format!("no edge for label `{label}`")))?;
903 graph_edge(&node.id, &edge.to, Some(label.as_str()));
904 self.branches[i] = Branch::enter(&edge.to);
905 }
906 NodeKind::Human { .. } => {
907 let data = reads(&self.state, &node.reads).map_err(fail)?;
908 self.branches[i].at = At::Human { data };
909 }
910 NodeKind::Agent { persona, prompt } => {
911 let data = reads(&self.state, &node.reads).map_err(fail)?;
912 let p = io.persona(persona).await.map_err(|e| fail(e.to_string()))?;
913 let (call_cap, run_cap) =
914 (p.budget.call_usd_micros, p.budget.run_usd_micros);
915 let limits = node_limits(
916 &self.limits,
917 self.usage().cost_usd_micros,
918 call_cap,
919 run_cap,
920 );
921 let input = vec![agent_input(prompt.as_deref(), data)];
922 let mut run = AgentRun::new(&p, input, limits, io.agent())
923 .await
924 .map_err(|e| fail(e.to_string()))?;
925 if let Some(spec) = io.persona_trace(persona).await {
926 run.set_trace(spec);
927 }
928 self.branches[i].at = At::Agent {
929 run: Box::new(run),
930 call_cap,
931 run_cap,
932 };
933 }
934 }
935 changed = true;
936 }
937 changed |= self.close_joins();
938 if !changed {
939 return Ok(false);
940 }
941 }
942 Err(format!(
943 "routing passed {passes} control nodes without work; check router loops"
944 ))
945 }
946
947 fn close_joins(&mut self) -> bool {
948 let ready = self.branches.iter().find_map(|b| {
949 let parked = self
950 .branches
951 .iter()
952 .filter(|o| o.node == b.node && o.at == At::Joined)
953 .count();
954 (b.at == At::Joined && parked == self.workflow.in_degree(&b.node))
955 .then(|| b.node.clone())
956 });
957 let Some(join) = ready else {
958 return false;
959 };
960 let first = self
961 .branches
962 .iter()
963 .position(|b| b.node == join)
964 .expect("the join has parked branches");
965 self.branches.retain(|b| b.node != join);
966 self.branches.insert(
967 first.min(self.branches.len()),
968 Branch {
969 node: join,
970 at: At::Left,
971 call: None,
972 },
973 );
974 true
975 }
976}
977
978fn graph_step_span(node: &str, kind: &'static str, step: u64) -> Span {
982 trace_span!(Trace::Graphs, "graph.step", node = node, kind = kind, step = step)
983}
984
985fn graph_edge(from: &str, to: &str, label: Option<&str>) {
988 trace!(Trace::Graphs, "graph.edge", from = from, to = to, label = label.unwrap_or(""));
989}
990
991fn node_limits(
992 base: &Limits,
993 spent_by_others: u64,
994 call_cap: Option<u64>,
995 run_cap: Option<u64>,
996) -> Limits {
997 let mut limits = base.clone();
998 limits.run = limits.run.map(|r| r.saturating_sub(spent_by_others));
999 limits.with_budget(&Budget {
1000 call_usd_micros: call_cap,
1001 run_usd_micros: run_cap,
1002 })
1003}
1004
1005fn reads(state: &Map<String, Value>, keys: &[String]) -> Result<Map<String, Value>, String> {
1006 keys.iter()
1007 .map(|k| {
1008 state
1009 .get(k)
1010 .map(|v| (k.clone(), v.clone()))
1011 .ok_or_else(|| format!("reads `{k}`, which is not set"))
1012 })
1013 .collect()
1014}
1015
1016fn agent_input(prompt: Option<&str>, data: Map<String, Value>) -> Message {
1017 let mut parts: Vec<String> = prompt.map(str::to_string).into_iter().collect();
1018 if !data.is_empty() {
1019 let json = serde_json::to_string(&Value::Object(data)).expect("state serializes");
1020 parts.push(fence_untrusted("workflow state", &json, false));
1021 }
1022 assert!(!parts.is_empty(), "agent nodes have a prompt or reads");
1023 Message::text(Role::User, parts.join("\n\n"))
1024}
1025
1026async fn call_tool(
1027 io: &dyn GraphIo,
1028 em: &Emitter<'_>,
1029 node: &Node,
1030 tool: &str,
1031 state: &Map<String, Value>,
1032 ctx: ToolContext,
1033) -> Result<Value, ToolFailure> {
1034 let args = reads(state, &node.reads).map_err(|message| ToolFailure {
1035 message,
1036 transient: false,
1037 })?;
1038 let key = ctx.idempotency_key.clone().expect("for_call sets the key");
1039 let step = format!("{}/tool", node.id);
1040 em.emit(EventBody::StepStarted { step: step.clone(), persona: None });
1041 em.emit(EventBody::ToolCallStarted {
1042 call_id: key.clone(),
1043 name: tool.to_string(),
1044 });
1045 let mut span = trace_span!(
1046 Trace::Tools,
1047 "tool.call",
1048 name = tool,
1049 call_id = key.as_str(),
1050 node = node.id.as_str(),
1051 args = content(serde_json::to_string(&args).expect("tool arguments serialize")),
1052 );
1053 let call = io.agent().tools().call(tool, Value::Object(args), &ctx);
1054 let result = span.instrument(call).await;
1055 match &result {
1056 Ok(out) if span.is_enabled() => {
1057 if out.is_error {
1058 span.fail("tool returned an error");
1059 }
1060 span.record("is_error", out.is_error);
1061 span.record("output", content(out.content.as_str()));
1062 }
1063 Ok(_) => {}
1064 Err(e) => {
1065 span.fail("tool call failed");
1066 span.record("error", content(e.to_string()));
1067 }
1068 }
1069 drop(span);
1070 em.emit(EventBody::ToolCallFinished {
1071 call_id: key,
1072 is_error: !matches!(&result, Ok(o) if !o.is_error),
1073 });
1074 em.emit(EventBody::StepFinished {
1075 step,
1076 usage: Usage::default(),
1077 });
1078 match result {
1079 Ok(out) if !out.is_error => {
1080 Ok(serde_json::from_str(&out.content).unwrap_or(Value::String(out.content)))
1081 }
1082 Ok(out) => Err(ToolFailure {
1083 message: format!("tool `{tool}` failed: {}", out.content),
1084 transient: false,
1085 }),
1086 Err(e) => Err(ToolFailure {
1087 message: format!("tool `{tool}`: {e}"),
1088 transient: matches!(e, ToolError::Failed(_) | ToolError::Http(_)),
1089 }),
1090 }
1091}