1use qualia_core_db::modalities::blackboard::BlackboardBus;
19use qualia_core_db::poet_host::invoke::agent::dag_executor::{
20 execute_pipeline, NodeExecutor, PipelineResult,
21};
22use qualia_core_db::NQuin;
23use std::path::Path;
24use vibe::dag::{DagEdge, DagNode, DagPipeline, NodeEffect};
25use vibe::{DiagCode, Diagnostic, Span};
26
27use crate::agent_registry::{self, AgentBackendSpec};
28
29pub struct AgentTurnConfig {
31 pub session_id: String,
33 pub storage_path: String,
35 pub agent_slug: String,
37 pub dag_pipeline: Option<DagPipeline>,
40}
41
42impl std::fmt::Debug for AgentTurnConfig {
43 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44 f.debug_struct("AgentTurnConfig")
45 .field("session_id", &self.session_id)
46 .field("storage_path", &self.storage_path)
47 .field("agent_slug", &self.agent_slug)
48 .field("dag_pipeline", &self.dag_pipeline.is_some())
49 .finish()
50 }
51}
52
53pub fn parse_dag_pipeline(json: &str) -> Result<DagPipeline, String> {
67 let value: serde_json::Value = serde_json::from_str(json).map_err(|e| e.to_string())?;
68 let mut pipeline = DagPipeline::new();
69
70 if let Some(nodes) = value.get("nodes").and_then(|v| v.as_array()) {
71 for node_val in nodes {
72 let id = node_val.get("id").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
73 let name = node_val
74 .get("name")
75 .and_then(|v| v.as_str())
76 .unwrap_or("unnamed");
77 let effect_str = node_val
78 .get("effect")
79 .and_then(|v| v.as_str())
80 .unwrap_or("Cold");
81 let effect = match effect_str {
82 "Pure" => NodeEffect::Pure,
83 "Hot" => NodeEffect::Hot,
84 "Cold" => NodeEffect::Cold,
85 "Async" => NodeEffect::Async,
86 "External" => NodeEffect::External,
87 _ => NodeEffect::Cold,
88 };
89 let mut node = DagNode::new(id, name, effect);
90 if let Some(caps) = node_val.get("capabilities").and_then(|v| v.as_array()) {
91 node.capabilities = caps
92 .iter()
93 .filter_map(|c| c.as_str().map(String::from))
94 .collect();
95 }
96 if let Some(inputs) = node_val.get("inputs").and_then(|v| v.as_array()) {
97 node.inputs = inputs
98 .iter()
99 .filter_map(|i| i.as_str().map(String::from))
100 .collect();
101 }
102 if let Some(outputs) = node_val.get("outputs").and_then(|v| v.as_array()) {
103 node.outputs = outputs
104 .iter()
105 .filter_map(|o| o.as_str().map(String::from))
106 .collect();
107 }
108 if let Some(budget) = node_val.get("budget").and_then(|v| v.as_u64()) {
109 node.budget = budget as u32;
110 }
111 if let Some(is_cu) = node_val.get("is_control_unit").and_then(|v| v.as_bool()) {
112 node.is_control_unit = is_cu;
113 }
114 pipeline
115 .add_node(node)
116 .map_err(|e| format!("DAG node error: {e:?}"))?;
117 }
118 }
119
120 if let Some(edges) = value.get("edges").and_then(|v| v.as_array()) {
121 for edge_val in edges {
122 let from = edge_val.get("from").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
123 let to = edge_val.get("to").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
124 pipeline
125 .add_edge(DagEdge::new(from, to))
126 .map_err(|e| format!("DAG edge error: {e:?}"))?;
127 }
128 }
129
130 Ok(pipeline)
131}
132
133#[derive(Debug, Clone)]
135pub enum AgentTurnOutcome {
136 DagPipeline(PipelineResult),
138 SingleTurn,
140 AgentUnavailable(String),
142 InvalidDag(String),
144}
145
146pub struct AgentTurnExecutor {
152 session_id: String,
153 agent_slug: String,
154 diagnostics: Vec<Diagnostic>,
156}
157
158impl AgentTurnExecutor {
159 pub fn new(session_id: &str, agent_slug: &str) -> Self {
161 Self {
162 session_id: session_id.to_string(),
163 agent_slug: agent_slug.to_string(),
164 diagnostics: Vec::new(),
165 }
166 }
167
168 fn build_prompt_from_inputs(&self, node_name: &str, inputs: &[(String, Vec<NQuin>)]) -> String {
172 let mut prompt = format!("[DAG node: {node_name}]\n");
173 if inputs.is_empty() {
174 prompt.push_str("(no upstream inputs)\n");
175 } else {
176 for (channel, quins) in inputs {
177 prompt.push_str(&format!("[input: {channel}] {quins:?}\n"));
178 }
179 }
180 prompt.push_str(&format!(
181 "\nAgent @{} — process the above context and produce your output.",
182 self.agent_slug
183 ));
184 prompt
185 }
186}
187
188impl NodeExecutor for AgentTurnExecutor {
189 fn execute(
190 &mut self,
191 node_id: u32,
192 node_name: &str,
193 inputs: &[(String, Vec<NQuin>)],
194 capabilities: &[String],
195 ) -> Result<Vec<(String, Vec<NQuin>)>, Diagnostic> {
196 let prompt = self.build_prompt_from_inputs(node_name, inputs);
197
198 let result = crate::chat_inference::run_chat_inference_for_agent(
200 &self.session_id,
201 &prompt,
202 Some(&self.agent_slug),
203 None,
204 );
205
206 if let Some(reason) = &result.block_reason {
207 self.diagnostics.push(Diagnostic::new(
208 DiagCode::E600,
209 Span::point(0),
210 format!("DAG node {node_id} ({node_name}) blocked: {reason}"),
211 ));
212 return Err(Diagnostic::new(
213 DiagCode::E600,
214 Span::point(0),
215 format!("node {node_name} blocked: {reason}"),
216 ));
217 }
218
219 let output_hash = qualia_core_db::q_hash(&result.text);
222 let output_nquin = NQuin {
223 subject: output_hash,
224 predicate: qualia_core_db::q_hash("dag:output"),
225 object: output_hash,
226 context: qualia_core_db::q_hash(&format!("dag:{node_id}")),
227 metadata: 0,
228 parity: 0,
229 };
230
231 let outputs = vec![("output".to_string(), vec![output_nquin])];
233
234 let _ = capabilities;
236
237 Ok(outputs)
238 }
239}
240
241pub fn execute_agent_turn(config: &mut AgentTurnConfig) -> AgentTurnOutcome {
252 let storage = Path::new(&config.storage_path);
253
254 let agent = match agent_registry::get_agent(storage, &config.agent_slug) {
256 Some(a) => a,
257 None => {
258 return AgentTurnOutcome::AgentUnavailable(format!(
259 "Unknown agent @{}",
260 config.agent_slug
261 ));
262 }
263 };
264
265 if !agent.enabled {
266 return AgentTurnOutcome::AgentUnavailable(format!("Agent @{} is disabled", agent.slug));
267 }
268
269 if !matches!(agent.backend, AgentBackendSpec::LocalEngine { .. }) {
271 return AgentTurnOutcome::SingleTurn;
272 }
273
274 let pipeline: DagPipeline = if let Some(p) = config.dag_pipeline.take() {
276 p
277 } else if !agent.dag_pipeline_json.is_empty() {
278 match parse_dag_pipeline(&agent.dag_pipeline_json) {
279 Ok(p) => p,
280 Err(e) => {
281 return AgentTurnOutcome::InvalidDag(format!(
282 "Invalid DAG pipeline for @{}: {e}",
283 config.agent_slug
284 ));
285 }
286 }
287 } else {
288 return AgentTurnOutcome::SingleTurn;
289 };
290
291 let mut bus = BlackboardBus::new();
293
294 let mut executor = AgentTurnExecutor::new(&config.session_id, &config.agent_slug);
296
297 match execute_pipeline(&pipeline, &mut bus, None, &mut executor) {
300 Ok(result) => AgentTurnOutcome::DagPipeline(result),
301 Err(e) => AgentTurnOutcome::InvalidDag(format!("DAG execution error: {e:?}")),
302 }
303}
304
305#[cfg(test)]
306mod tests {
307 use super::*;
308
309 #[test]
310 fn agent_turn_executor_builds_prompt_from_inputs() {
311 let executor = AgentTurnExecutor::new("test-session", "researcher");
312 let inputs = vec![(
313 "context".to_string(),
314 vec![NQuin {
315 subject: 1,
316 predicate: 2,
317 object: 3,
318 context: 4,
319 metadata: 0,
320 parity: 0,
321 }],
322 )];
323 let prompt = executor.build_prompt_from_inputs("analyze", &inputs);
324 assert!(prompt.contains("[DAG node: analyze]"));
325 assert!(prompt.contains("[input: context]"));
326 assert!(prompt.contains("@researcher"));
327 }
328
329 #[test]
330 fn agent_turn_executor_empty_inputs() {
331 let executor = AgentTurnExecutor::new("test-session", "writer");
332 let prompt = executor.build_prompt_from_inputs("draft", &[]);
333 assert!(prompt.contains("(no upstream inputs)"));
334 assert!(prompt.contains("@writer"));
335 }
336
337 #[test]
338 fn agent_turn_outcome_unknown_agent() {
339 let mut config = AgentTurnConfig {
340 session_id: "test".to_string(),
341 storage_path: "/nonexistent".to_string(),
342 agent_slug: "nonexistent_agent".to_string(),
343 dag_pipeline: None,
344 };
345 let outcome = execute_agent_turn(&mut config);
346 assert!(matches!(outcome, AgentTurnOutcome::AgentUnavailable(_)));
347 }
348
349 #[test]
350 fn agent_turn_outcome_no_dag_returns_single_turn() {
351 let mut config = AgentTurnConfig {
355 session_id: "test".to_string(),
356 storage_path: "/nonexistent".to_string(),
357 agent_slug: "test".to_string(),
358 dag_pipeline: None,
359 };
360 let outcome = execute_agent_turn(&mut config);
362 assert!(matches!(outcome, AgentTurnOutcome::AgentUnavailable(_)));
363 }
364
365 #[test]
366 fn agent_turn_outcome_with_dag_unavailable_agent() {
367 use vibe::dag::{DagNode, DagPipeline, NodeEffect};
369 let mut pipeline = DagPipeline::new();
370 let _ = pipeline.add_node(DagNode::new(0, "test", NodeEffect::Hot));
371 let mut config = AgentTurnConfig {
372 session_id: "test".to_string(),
373 storage_path: "/nonexistent".to_string(),
374 agent_slug: "nonexistent".to_string(),
375 dag_pipeline: Some(pipeline),
376 };
377 let outcome = execute_agent_turn(&mut config);
378 assert!(matches!(outcome, AgentTurnOutcome::AgentUnavailable(_)));
379 }
380
381 #[test]
382 fn parse_dag_pipeline_from_valid_json() {
383 let json = r#"{
384 "nodes": [
385 {"id": 0, "name": "research", "effect": "Hot", "capabilities": ["graph.query"], "inputs": [], "outputs": ["findings"], "budget": 4096},
386 {"id": 1, "name": "synthesize", "effect": "Pure", "inputs": ["findings"], "outputs": ["report"], "budget": 2048}
387 ],
388 "edges": [
389 {"from": 0, "to": 1}
390 ]
391 }"#;
392 let pipeline = parse_dag_pipeline(json).unwrap();
393 assert_eq!(pipeline.node_count(), 2);
394 }
395
396 #[test]
397 fn parse_dag_pipeline_empty_json() {
398 let json = r#"{}"#;
399 let pipeline = parse_dag_pipeline(json).unwrap();
400 assert_eq!(pipeline.node_count(), 0);
401 }
402
403 #[test]
404 fn parse_dag_pipeline_invalid_json() {
405 let json = "not valid json";
406 let result = parse_dag_pipeline(json);
407 assert!(result.is_err());
408 }
409}