Skip to main content

troupekit_graph/
io.rs

1use crate::condition::Conditions;
2use async_trait::async_trait;
3use std::sync::atomic::{AtomicU64, Ordering};
4use std::sync::Arc;
5use troupekit_agent::budget::UsageLedger;
6use troupekit_agent::eval::EvalRegistry;
7use troupekit_agent::{AgentError, AgentIo, EventSink, ModelHandle, Persona, PersonaLoader};
8use troupekit_core::clock::Clock;
9use troupekit_core::event::{Event, EventBody};
10use troupekit_core::ids::RunId;
11use troupekit_tools::ToolRegistry;
12use troupekit_trace::TraceSpec;
13
14/// Everything live a graph run needs, supplied by the host on every step:
15/// the `AgentIo` its agent and tool nodes use, persona loading by name
16/// and the router conditions.
17#[async_trait]
18pub trait GraphIo: Send + Sync {
19    fn agent(&self) -> &dyn AgentIo;
20    async fn persona(&self, name: &str) -> Result<Persona, AgentError>;
21    fn conditions(&self) -> &Conditions;
22
23    /// Returns the trace settings of persona `name`, applied to the agent
24    /// run of every node using it. The default is `None`, no tracing.
25    /// Input: the persona name. Output: the spec.
26    async fn persona_trace(&self, _name: &str) -> Option<TraceSpec> {
27        None
28    }
29}
30
31/// A `GraphIo` built from plain fields: an agent io, a persona loader and
32/// conditions. Good for tests, examples and single-user hosts.
33/// `new` starts with the built-in conditions.
34pub struct SimpleGraphIo {
35    pub agent: Arc<dyn AgentIo>,
36    pub personas: PersonaLoader,
37    pub conditions: Conditions,
38}
39
40impl SimpleGraphIo {
41    /// Builds an io over `agent` and `personas` with only the built-in
42    /// `flag` condition; add more through the `conditions` field.
43    /// Returns the io.
44    pub fn new(agent: Arc<dyn AgentIo>, personas: PersonaLoader) -> Self {
45        Self {
46            agent,
47            personas,
48            conditions: Conditions::new(),
49        }
50    }
51}
52
53#[async_trait]
54impl GraphIo for SimpleGraphIo {
55    fn agent(&self) -> &dyn AgentIo {
56        self.agent.as_ref()
57    }
58
59    async fn persona(&self, name: &str) -> Result<Persona, AgentError> {
60        self.personas.load(name).await
61    }
62
63    fn conditions(&self) -> &Conditions {
64        &self.conditions
65    }
66
67    async fn persona_trace(&self, name: &str) -> Option<TraceSpec> {
68        self.personas.trace_spec(name).await.ok().flatten()
69    }
70}
71
72/// Numbers and sends the events of one graph step under the graph run id.
73/// Branches emit concurrently, so the next `seq` is an atomic seeded from
74/// the run and read back when the step ends.
75pub(crate) struct Emitter<'a> {
76    pub run_id: RunId,
77    pub seq: &'a AtomicU64,
78    pub io: &'a dyn AgentIo,
79}
80
81impl Emitter<'_> {
82    /// Sends `body` as the run's next event, stamped with the io clock.
83    /// Takes the next `seq` atomically, so concurrent branches never
84    /// share or skip a number.
85    pub fn emit(&self, body: EventBody) {
86        self.io.events().emit(Event {
87            run_id: self.run_id,
88            seq: self.seq.fetch_add(1, Ordering::SeqCst),
89            at_ms: self.io.clock().now_ms(),
90            body,
91        });
92    }
93}
94
95struct NodeSink<'a> {
96    emitter: &'a Emitter<'a>,
97    node: &'a str,
98    persona: &'a str,
99}
100
101impl EventSink for NodeSink<'_> {
102    fn emit(&self, event: Event) {
103        let body = match event.body {
104            EventBody::RunStarted { .. }
105            | EventBody::RunFinished { .. }
106            | EventBody::RunPaused { .. }
107            | EventBody::RunFailed { .. } => return,
108            EventBody::StepStarted { step, .. } => EventBody::StepStarted {
109                step: format!("{}/{step}", self.node),
110                persona: Some(self.persona.to_string()),
111            },
112            EventBody::StepFinished { step, usage } => EventBody::StepFinished {
113                step: format!("{}/{step}", self.node),
114                usage,
115            },
116            other => other,
117        };
118        self.emitter.emit(body);
119    }
120}
121
122/// The `AgentIo` an agent node steps with: the graph's agent io, except
123/// that events go out under the graph run id and `seq`, step names gain a
124/// `node/` prefix, step starts name the node's persona slug and the
125/// agent's own run lifecycle events are dropped.
126pub(crate) struct NodeIo<'a> {
127    inner: &'a dyn AgentIo,
128    sink: NodeSink<'a>,
129}
130
131impl<'a> NodeIo<'a> {
132    /// Builds the io for agent node `node` running persona slug `persona`,
133    /// emitting through `emitter`. Everything else delegates to the
134    /// emitter's agent io. Returns the io.
135    pub fn new(emitter: &'a Emitter<'a>, node: &'a str, persona: &'a str) -> Self {
136        Self {
137            inner: emitter.io,
138            sink: NodeSink {
139                emitter,
140                node,
141                persona,
142            },
143        }
144    }
145}
146
147#[async_trait]
148impl AgentIo for NodeIo<'_> {
149    async fn model(&self, selector: &str) -> Result<ModelHandle, AgentError> {
150        self.inner.model(selector).await
151    }
152
153    fn tools(&self) -> &ToolRegistry {
154        self.inner.tools()
155    }
156
157    fn evals(&self) -> &EvalRegistry {
158        self.inner.evals()
159    }
160
161    fn ledger(&self) -> &dyn UsageLedger {
162        self.inner.ledger()
163    }
164
165    fn events(&self) -> &dyn EventSink {
166        &self.sink
167    }
168
169    fn clock(&self) -> &dyn Clock {
170        self.inner.clock()
171    }
172}