1use crate::agent::{parse_run_id, refuse_law, AgentBuilder};
2use crate::error::{ErrorCode, FfiError};
3use crate::host::{guarded, host_tool, trace_categories, trace_sink, HostTool, TraceListener};
4use crate::records::{GraphResult, Progress};
5use crate::runtime::{check_input, spawn};
6use crate::stream::RunStream;
7use std::sync::{Arc, Mutex, PoisonError};
8use std::time::Duration;
9use troupekit_kit::{BuiltGraph, Graph, GraphReport, StreamSettings};
10
11#[derive(Debug)]
15pub struct GraphBuilder {
16 state: Mutex<State>,
17}
18
19#[derive(Debug)]
20enum State {
21 Open(Box<Graph>),
22 Broken(FfiError),
23 Built,
24}
25
26impl GraphBuilder {
27 pub fn new(name: String) -> Arc<Self> {
31 let state = match check_input("name", &name) {
32 Ok(()) => State::Open(Box::new(Graph::new(name))),
33 Err(err) => State::Broken(err),
34 };
35 Arc::new(GraphBuilder {
36 state: Mutex::new(state),
37 })
38 }
39
40 fn is_open(&self) -> bool {
44 let state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
45 matches!(*state, State::Open(_))
46 }
47
48 fn update(
49 self: &Arc<Self>,
50 change: impl FnOnce(Graph) -> Result<Graph, FfiError>,
51 ) -> Arc<Self> {
52 let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
53 let next = match std::mem::replace(&mut *state, State::Built) {
54 State::Open(graph) => match change(*graph) {
55 Ok(graph) => State::Open(Box::new(graph)),
56 Err(err) => State::Broken(err),
57 },
58 other => other,
59 };
60 *state = next;
61 self.clone()
62 }
63
64 pub fn agent(self: &Arc<Self>, id: String, agent: Arc<AgentBuilder>) -> Arc<Self> {
68 let taken = agent.take();
69 self.update(|graph| {
70 check_input("node id", &id)?;
71 Ok(graph.agent(id, taken?))
72 })
73 }
74
75 pub fn step(self: &Arc<Self>, id: String, tool: Arc<dyn HostTool>) -> Arc<Self> {
79 if !self.is_open() {
80 return self.clone();
81 }
82 let wrapped = guarded("tool", || host_tool(tool));
83 self.update(|graph| {
84 check_input("node id", &id)?;
85 Ok(graph.step(id, wrapped?))
86 })
87 }
88
89 pub fn edge(self: &Arc<Self>, from: String, to: String) -> Arc<Self> {
93 self.update(|graph| {
94 check_input("edge from", &from)?;
95 check_input("edge to", &to)?;
96 Ok(graph.edge(from, to))
97 })
98 }
99
100 pub fn sqlite(self: &Arc<Self>, path: String) -> Arc<Self> {
104 self.update(|graph| {
105 check_input("sqlite", &path)?;
106 sqlite_storage(graph, path)
107 })
108 }
109
110 pub fn max_steps(self: &Arc<Self>, steps: u32) -> Arc<Self> {
114 self.update(|graph| Ok(graph.max_steps(steps)))
115 }
116
117 pub fn retries(self: &Arc<Self>, retries: u32) -> Arc<Self> {
121 self.update(|graph| Ok(graph.retries(retries)))
122 }
123
124 pub fn laws(self: &Arc<Self>, path: String) -> Arc<Self> {
129 self.update(|_| Err(refuse_law("laws", &path, true)))
130 }
131
132 pub fn law(self: &Arc<Self>, text: String) -> Arc<Self> {
137 self.update(|_| Err(refuse_law("law", &text, false)))
138 }
139
140 pub fn auto_laws(self: &Arc<Self>, on: bool) -> Arc<Self> {
144 self.update(|graph| Ok(graph.auto_laws(on)))
145 }
146
147 pub fn tracing(self: &Arc<Self>, on: bool) -> Arc<Self> {
151 self.update(|graph| Ok(graph.tracing(on)))
152 }
153
154 pub fn trace(self: &Arc<Self>, categories: Vec<String>) -> Arc<Self> {
158 self.update(|graph| Ok(graph.trace(trace_categories(&categories)?)))
159 }
160
161 pub fn trace_content(self: &Arc<Self>, on: bool) -> Arc<Self> {
165 self.update(|graph| Ok(graph.trace_content(on)))
166 }
167
168 pub fn trace_jsonl(self: &Arc<Self>, path: String) -> Arc<Self> {
172 self.update(|graph| {
173 check_input("trace_jsonl", &path)?;
174 Ok(graph.trace_file(path))
175 })
176 }
177
178 pub fn trace_listener(self: &Arc<Self>, listener: Arc<dyn TraceListener>) -> Arc<Self> {
182 self.update(|graph| Ok(graph.trace_to(trace_sink(listener))))
183 }
184
185 pub async fn build(self: &Arc<Self>) -> Result<Arc<GraphHandle>, FfiError> {
189 let graph = {
190 let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
191 match std::mem::replace(&mut *state, State::Built) {
192 State::Open(graph) => *graph,
193 State::Broken(err) => return Err(err),
194 State::Built => {
195 return Err(FfiError::new(
196 ErrorCode::InvalidArgument,
197 "builder already built",
198 ))
199 }
200 }
201 };
202 let built = spawn(async move { graph.build().await.map_err(FfiError::from) }).await?;
203 Ok(Arc::new(GraphHandle { graph: built }))
204 }
205}
206
207#[cfg(feature = "sqlite")]
208fn sqlite_storage(graph: Graph, path: String) -> Result<Graph, FfiError> {
209 Ok(graph.checkpoints(troupekit_kit::Storage::sqlite(path)))
210}
211
212#[cfg(not(feature = "sqlite"))]
213fn sqlite_storage(_graph: Graph, _path: String) -> Result<Graph, FfiError> {
214 Err(FfiError::new(
215 ErrorCode::Unsupported,
216 "sqlite needs troupekit built with the sqlite feature",
217 ))
218}
219
220#[derive(Debug)]
224pub struct GraphHandle {
225 graph: BuiltGraph,
226}
227
228impl GraphHandle {
229 pub async fn run(&self, input: String) -> Result<String, FfiError> {
233 check_input("input", &input)?;
234 let graph = self.graph.clone();
235 let output = spawn(async move { graph.run(input).await.map_err(FfiError::from) }).await?;
236 Ok(output.to_string())
237 }
238
239 pub async fn run_result(&self, input: String) -> Result<GraphResult, FfiError> {
243 check_input("input", &input)?;
244 let graph = self.graph.clone();
245 let report =
246 spawn(async move { graph.run_with(input).await.map_err(FfiError::from) }).await?;
247 Ok(GraphResult::from_report(&report))
248 }
249
250 pub async fn start(&self, input: String) -> Result<String, FfiError> {
254 check_input("input", &input)?;
255 let graph = self.graph.clone();
256 let run_id = spawn(async move { graph.start(input).await.map_err(FfiError::from) }).await?;
257 Ok(run_id.to_string())
258 }
259
260 pub async fn resume(&self, run_id: String) -> Result<String, FfiError> {
264 let run_id = parse_run_id(&run_id)?;
265 let graph = self.graph.clone();
266 let output =
267 spawn(async move { graph.resume(run_id).await.map_err(FfiError::from) }).await?;
268 Ok(output.to_string())
269 }
270
271 pub async fn resume_for(&self, run_id: String, budget_ms: u64) -> Result<Progress, FfiError> {
275 let run_id = parse_run_id(&run_id)?;
276 let graph = self.graph.clone();
277 let budget = Duration::from_millis(budget_ms);
278 let progress = spawn(async move {
279 graph
280 .resume_for(run_id, budget)
281 .await
282 .map_err(FfiError::from)
283 })
284 .await?;
285 Progress::from_kit(progress)
286 }
287
288 pub async fn stream(&self, input: String) -> Result<Arc<RunStream>, FfiError> {
292 check_input("input", &input)?;
293 let graph = self.graph.clone();
294 let mut settings = StreamSettings::default();
295 settings.capacity = crate::runtime::settings().event_buffer;
296 let stream = spawn(async move {
297 graph
298 .stream_with(input, settings)
299 .await
300 .map_err(FfiError::from)
301 })
302 .await?;
303 Ok(RunStream::graph(stream))
304 }
305}
306
307impl GraphResult {
308 pub(crate) fn from_report(report: &GraphReport) -> GraphResult {
309 let state = serde_json::Value::Object(report.state().clone());
310 GraphResult {
311 output_json: report.output().to_string(),
312 state_json: state.to_string(),
313 usage: crate::stream::usage_of(report.usage()),
314 steps: report.steps(),
315 run_id: report.run_id().to_string(),
316 }
317 }
318}