Skip to main content

qualia_client_core/
agent_turn_handler.rs

1//! Agent-turn handler — bridges the DAG executor to the chat/inference layer.
2//!
3//! This is the final piece of the critical path:
4//! `R1 → R5 → R3 → R6 → R7 → agent_turn_handler`
5//!
6//! When a user sends `@researcher analyze this data`, the chat layer:
7//! 1. Parses the @mention (R7) → resolves to a roster agent.
8//! 2. If the agent has a DAG pipeline definition, the agent-turn handler
9//!    executes the pipeline using the DAG executor (R3), with each node
10//!    dispatched as a local LLM agent turn.
11//! 3. If no DAG is defined, falls through to the standard single-agent
12//!    inference path (`run_chat_inference_for_agent`).
13//!
14//! The handler implements `NodeExecutor` so the DAG executor can call it
15//! for each node. Each node execution is a local LLM inference turn with
16//! the node's inputs (from the blackboard) injected into the prompt context.
17
18use 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
29/// Configuration for an agent-turn handler invocation.
30pub struct AgentTurnConfig {
31    /// The session ID for chat context.
32    pub session_id: String,
33    /// The storage path for agent definitions.
34    pub storage_path: String,
35    /// The roster agent to execute.
36    pub agent_slug: String,
37    /// Optional DAG pipeline to execute.
38    /// If None, the agent runs as a single-turn inference.
39    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
53/// Parse a DAG pipeline from a JSON definition.
54///
55/// Expected format:
56/// ```json
57/// {
58///   "nodes": [
59///     {"id": 0, "name": "step1", "effect": "Hot", "capabilities": [], "inputs": [], "outputs": ["out"], "budget": 4096}
60///   ],
61///   "edges": [
62///     {"from": 0, "to": 1}
63///   ]
64/// }
65/// ```
66pub 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/// Result of an agent-turn handler invocation.
134#[derive(Debug, Clone)]
135pub enum AgentTurnOutcome {
136    /// The agent has a DAG pipeline — it was executed.
137    DagPipeline(PipelineResult),
138    /// The agent has no DAG pipeline — single-turn inference was used.
139    SingleTurn,
140    /// The agent could not be found or is disabled.
141    AgentUnavailable(String),
142    /// The DAG pipeline definition was invalid.
143    InvalidDag(String),
144}
145
146/// A node executor that dispatches each DAG node as a local LLM agent turn.
147///
148/// The executor collects the prompt context from the blackboard inputs,
149/// constructs a prompt, and calls the local inference path. The outputs
150/// are written back to the blackboard as NQuin records.
151pub struct AgentTurnExecutor {
152    session_id: String,
153    agent_slug: String,
154    /// Accumulated diagnostics from node executions.
155    diagnostics: Vec<Diagnostic>,
156}
157
158impl AgentTurnExecutor {
159    /// Creates a new instance.
160    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    /// Build a prompt string from the blackboard inputs for a DAG node.
169    /// The inputs are (channel_name, quins) pairs. Each channel's quins
170    /// are rendered as a context block.
171    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        // Run the local inference turn for this node.
199        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        // Convert the inference output to NQuin records for the blackboard.
220        // The output text is hashed into an NQuin for provenance tracking.
221        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        // The output channel name is "output" by convention.
232        let outputs = vec![("output".to_string(), vec![output_nquin])];
233
234        // Track capabilities used (for audit).
235        let _ = capabilities;
236
237        Ok(outputs)
238    }
239}
240
241/// Execute an agent turn, optionally through a DAG pipeline.
242///
243/// This is the entry point called by the chat layer when an @mention
244/// resolves to a roster agent. If the agent has a DAG pipeline definition
245/// (in `dag_pipeline_json`), the pipeline is executed with the agent-turn
246/// executor. Otherwise, the function returns `SingleTurn` and the caller
247/// should fall through to `run_chat_inference_for_agent`.
248///
249/// If `config.dag_pipeline` is provided, it overrides the agent's stored
250/// pipeline definition.
251pub fn execute_agent_turn(config: &mut AgentTurnConfig) -> AgentTurnOutcome {
252    let storage = Path::new(&config.storage_path);
253
254    // Resolve the agent.
255    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    // Only local agents can use DAG pipelines.
270    if !matches!(agent.backend, AgentBackendSpec::LocalEngine { .. }) {
271        return AgentTurnOutcome::SingleTurn;
272    }
273
274    // Use explicit pipeline if provided, otherwise parse from agent definition.
275    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    // Create a blackboard bus for the pipeline.
292    let mut bus = BlackboardBus::new();
293
294    // Create the agent-turn executor.
295    let mut executor = AgentTurnExecutor::new(&config.session_id, &config.agent_slug);
296
297    // Execute the pipeline (no phase leaser for now — the chat layer
298    // doesn't manage deontic phases; that's the host's responsibility).
299    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        // Without a real agent registry, we can't test the full path,
352        // but we can verify the config logic: no DAG → SingleTurn.
353        // This test would need a mock agent registry to be fully end-to-end.
354        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        // With a nonexistent path, get_agent returns None → AgentUnavailable.
361        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        // A DAG pipeline is provided but the agent doesn't exist.
368        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}