quorum-rs 0.8.0

Rust SDK and CLI for multi-agent deliberation systems — ships the `quorum` binary (run / status / trace / tui / init) plus the underlying agent, LLM, tool, prompt, and worker library.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
//! Middleware configuration — YAML deserialization and pipeline builder.
//!
//! ```yaml
//! middleware:
//!   before_release:
//!     - builtin: rule_based
//!       stages: [edit, release]
//!       config:
//!         max_content_length: 50000
//!     - binary: ./middleware/moderate
//!       timeout_secs: 30
//!       stages: [release]
//!   on_provider_response:
//!     - binary: ./middleware/transform
//!       timeout_secs: 10
//! ```

use super::BinaryMiddleware;
use crate::llms::AiModel;
use crate::middleware::{AgentMiddleware, MiddlewareStage, pipeline::MiddlewarePipeline};
use serde::Deserialize;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

/// Default binary middleware timeout (30 seconds).
fn default_timeout() -> u64 {
    30
}

/// Top-level middleware configuration from agent YAML config.
#[derive(Debug, Clone, Deserialize, Default)]
pub struct MiddlewareConfig {
    /// Middleware that runs before buffer release (edit + release stages).
    #[serde(default)]
    pub before_release: Vec<MiddlewareEntry>,
    /// Middleware that runs after LLM provider returns.
    #[serde(default)]
    pub on_provider_response: Vec<MiddlewareEntry>,
    /// Middleware that runs before constructing the LLM prompt.
    #[serde(default)]
    pub before_prompt: Vec<MiddlewareEntry>,
    /// Middleware that runs after deliberation completes (per round).
    #[serde(default)]
    pub on_completion: Vec<MiddlewareEntry>,
    /// Middleware that runs once at job-final (terminal winner known).
    #[serde(default)]
    pub on_job_complete: Vec<MiddlewareEntry>,
    /// Optional AiModel instance for LLM moderation middleware.
    /// Set at runtime (not from YAML) — call [`Self::with_moderation_model()`].
    #[serde(skip)]
    pub moderation_model: Option<Arc<dyn AiModel>>,
}

impl MiddlewareConfig {
    /// Set the LLM model for moderation middleware.
    /// Called at agent startup after constructing the provider.
    pub fn with_moderation_model(mut self, model: Arc<dyn AiModel>) -> Self {
        self.moderation_model = Some(model);
        self
    }
}

/// A single middleware entry — builtin, external binary, or dynamic library.
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum MiddlewareEntry {
    /// Builtin middleware (compiled into the binary).
    Builtin {
        /// Builtin type identifier.
        builtin: BuiltinMiddlewareType,
        /// Which stages this middleware runs at (default: all for the hook point).
        #[serde(default)]
        stages: Option<Vec<MiddlewareStage>>,
        /// Builtin-specific configuration.
        #[serde(default)]
        config: serde_json::Value,
    },
    /// Dynamic library middleware (.so / .dylib / .dll via FFI).
    Dylib {
        /// Path to the shared library.
        dylib: PathBuf,
        /// Which stages this middleware runs at (default: all for the hook point).
        #[serde(default)]
        stages: Option<Vec<MiddlewareStage>>,
        /// Opaque config passed to the dylib. Merged into `MiddlewareContext.metadata`
        /// before each FFI call, so a dylib self-configures from the yml without env
        /// vars (feature-parity with builtin `config`). The dylib defines its own
        /// schema under whatever key it reads.
        #[serde(default)]
        config: serde_json::Value,
    },
    /// External binary middleware (stdin/stdout JSON protocol).
    Binary {
        /// Path to the executable.
        binary: PathBuf,
        /// Extra command-line arguments.
        #[serde(default)]
        args: Vec<String>,
        /// Timeout in seconds (default: 30).
        #[serde(default = "default_timeout")]
        timeout_secs: u64,
        /// Which stages this middleware runs at (default: all for the hook point).
        #[serde(default)]
        stages: Option<Vec<MiddlewareStage>>,
    },
}

/// Built-in middleware types. Implementations live in Issue #110.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BuiltinMiddlewareType {
    /// Signature verification (check cryptographic signatures on content).
    SignatureVerification,
    /// Rule-based validation (blocklist, content length, PII patterns).
    RuleBased,
    /// LLM-based content moderation (uses a separate LLM to classify content).
    LlmModeration,
    /// Blocks LLM output that leaks the agent's own system prompt (XML tags,
    /// protocol phrases) or the canonical tool registry.
    PromptExposure,
}

impl MiddlewareConfig {
    /// Build a pipeline for the `before_release` hook point. `Err` if any
    /// configured middleware fails to build (fail-closed — see `build_pipeline`).
    pub fn build_before_release_pipeline(&self) -> Result<MiddlewarePipeline, String> {
        self.build_pipeline(
            &self.before_release,
            &[MiddlewareStage::Edit, MiddlewareStage::Release],
        )
    }

    /// Build a pipeline for the `on_provider_response` hook point.
    pub fn build_provider_response_pipeline(&self) -> Result<MiddlewarePipeline, String> {
        self.build_pipeline(
            &self.on_provider_response,
            &[MiddlewareStage::ProviderResponse],
        )
    }

    /// Build a pipeline for the `before_prompt` hook point.
    pub fn build_before_prompt_pipeline(&self) -> Result<MiddlewarePipeline, String> {
        self.build_pipeline(&self.before_prompt, &[MiddlewareStage::BeforePrompt])
    }

    /// Build a pipeline for the `on_completion` hook point.
    pub fn build_completion_pipeline(&self) -> Result<MiddlewarePipeline, String> {
        self.build_pipeline(&self.on_completion, &[MiddlewareStage::Completion])
    }

    /// Build a pipeline for the `on_job_complete` hook point.
    pub fn build_job_complete_pipeline(&self) -> Result<MiddlewarePipeline, String> {
        self.build_pipeline(&self.on_job_complete, &[MiddlewareStage::JobComplete])
    }

    /// Returns true if no middleware is configured at any hook point.
    pub fn is_empty(&self) -> bool {
        self.before_release.is_empty()
            && self.on_provider_response.is_empty()
            && self.before_prompt.is_empty()
            && self.on_completion.is_empty()
            && self.on_job_complete.is_empty()
    }

    fn build_pipeline(
        &self,
        entries: &[MiddlewareEntry],
        default_stages: &[MiddlewareStage],
    ) -> Result<MiddlewarePipeline, String> {
        // Fail CLOSED: a middleware that can't be built (missing/corrupt dylib,
        // builtin create error) is a broken security guard — propagate the error so
        // the agent refuses to start, rather than silently dropping the guard and
        // running the pipeline without it (fail-open).
        let middleware = entries
            .iter()
            .map(|entry| self.build_entry(entry, default_stages))
            .collect::<Result<Vec<_>, _>>()?;
        Ok(MiddlewarePipeline::new(middleware))
    }

    fn build_entry(
        &self,
        entry: &MiddlewareEntry,
        default_stages: &[MiddlewareStage],
    ) -> Result<Box<dyn AgentMiddleware>, String> {
        match entry {
            MiddlewareEntry::Builtin {
                builtin,
                stages,
                config,
            } => {
                let active_stages = stages
                    .as_ref()
                    .cloned()
                    .unwrap_or_else(|| default_stages.to_vec());

                match super::builtin::create_builtin_middleware(
                    builtin,
                    config,
                    active_stages,
                    self.moderation_model.clone(),
                ) {
                    Ok(mw) => {
                        tracing::info!(
                            builtin_type = ?builtin,
                            "Loaded builtin middleware"
                        );
                        Ok(mw)
                    }
                    Err(e) => Err(format!(
                        "failed to create builtin middleware {builtin:?}: {e}"
                    )),
                }
            }
            MiddlewareEntry::Dylib {
                dylib,
                stages,
                config,
            } => {
                let active_stages = stages
                    .as_ref()
                    .cloned()
                    .unwrap_or_else(|| default_stages.to_vec());

                // Safety: we trust the operator's config to point at a valid dylib.
                // The FFI contract is documented in dylib.rs.
                match unsafe { super::DylibMiddleware::load(dylib, active_stages, config.clone()) }
                {
                    Ok(mw) => {
                        tracing::info!(
                            dylib = ?dylib,
                            "Loaded dynamic library middleware"
                        );
                        Ok(Box::new(mw))
                    }
                    // Fail CLOSED: propagate so the agent refuses to start (matching
                    // the operator-facing contract) instead of running without this
                    // guard. Fix the dylib path or remove it from config.
                    Err(e) => Err(format!(
                        "failed to load dynamic library middleware {dylib:?}: {e} \
                         — fix the dylib path or remove it from config"
                    )),
                }
            }
            MiddlewareEntry::Binary {
                binary,
                args,
                timeout_secs,
                stages,
            } => {
                let active_stages = stages
                    .as_ref()
                    .cloned()
                    .unwrap_or_else(|| default_stages.to_vec());

                let name = binary
                    .file_name()
                    .and_then(|n| n.to_str())
                    .unwrap_or("binary")
                    .to_string();

                Ok(Box::new(BinaryMiddleware {
                    display_name: name,
                    path: binary.clone(),
                    args: args.clone(),
                    timeout: Duration::from_secs(*timeout_secs),
                    active_stages,
                }))
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn config_deserialize_empty() {
        let yaml = "{}";
        let config: MiddlewareConfig = serde_yaml::from_str(yaml).unwrap();
        assert!(config.is_empty());
    }

    #[test]
    fn config_deserialize_binary_entry() {
        let yaml = r#"
before_release:
  - binary: ./hooks/moderate
    timeout_secs: 15
    stages: [release]
"#;
        let config: MiddlewareConfig = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(config.before_release.len(), 1);
        match &config.before_release[0] {
            MiddlewareEntry::Binary {
                binary,
                timeout_secs,
                stages,
                ..
            } => {
                assert_eq!(binary, &PathBuf::from("./hooks/moderate"));
                assert_eq!(*timeout_secs, 15);
                assert_eq!(stages.as_ref().unwrap(), &[MiddlewareStage::Release]);
            }
            _ => panic!("Expected Binary entry"),
        }
    }

    #[test]
    fn config_deserialize_builtin_entry() {
        let yaml = r#"
before_release:
  - builtin: rule_based
    stages: [edit, release]
    config:
      max_content_length: 50000
      pii_patterns: true
"#;
        let config: MiddlewareConfig = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(config.before_release.len(), 1);
        match &config.before_release[0] {
            MiddlewareEntry::Builtin {
                builtin,
                stages,
                config,
            } => {
                assert!(matches!(builtin, BuiltinMiddlewareType::RuleBased));
                assert_eq!(
                    stages.as_ref().unwrap(),
                    &[MiddlewareStage::Edit, MiddlewareStage::Release]
                );
                assert_eq!(config["max_content_length"], 50000);
                assert_eq!(config["pii_patterns"], true);
            }
            _ => panic!("Expected Builtin entry"),
        }
    }

    #[test]
    fn config_deserialize_mixed() {
        let yaml = r#"
before_release:
  - builtin: signature_verification
    stages: [release]
  - binary: ./hooks/moderate
    timeout_secs: 30
    stages: [release]
on_provider_response:
  - binary: ./hooks/transform
    timeout_secs: 10
"#;
        let config: MiddlewareConfig = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(config.before_release.len(), 2);
        assert_eq!(config.on_provider_response.len(), 1);
        assert!(!config.is_empty());
    }

    #[test]
    fn config_default_timeout() {
        let yaml = r#"
before_release:
  - binary: ./hooks/check
"#;
        let config: MiddlewareConfig = serde_yaml::from_str(yaml).unwrap();
        match &config.before_release[0] {
            MiddlewareEntry::Binary { timeout_secs, .. } => {
                assert_eq!(*timeout_secs, 30); // default
            }
            _ => panic!("Expected Binary entry"),
        }
    }

    #[test]
    fn build_binary_pipeline() {
        let yaml = r#"
before_release:
  - binary: /bin/true
    timeout_secs: 5
"#;
        let config: MiddlewareConfig = serde_yaml::from_str(yaml).unwrap();
        let pipeline = config.build_before_release_pipeline().unwrap();
        assert_eq!(pipeline.len(), 1);
        assert!(!pipeline.is_empty());
    }

    #[test]
    fn build_builtin_pipeline_creates_rule_based() {
        let yaml = r#"
before_release:
  - builtin: rule_based
    config: {}
"#;
        let config: MiddlewareConfig = serde_yaml::from_str(yaml).unwrap();
        let pipeline = config.build_before_release_pipeline().unwrap();
        // rule_based is implemented — should create 1 middleware
        assert_eq!(pipeline.len(), 1);
    }

    #[test]
    fn unloadable_dylib_fails_closed_not_dropped() {
        // A dylib that can't load must make pipeline-build ERROR (→ agent refuses to
        // start), not silently drop the guard and run the pipeline without it.
        let yaml = r#"
before_prompt:
  - dylib: /nonexistent/path/to/guard.so
"#;
        let config: MiddlewareConfig = serde_yaml::from_str(yaml).unwrap();
        let result = config.build_before_prompt_pipeline();
        assert!(
            result.is_err(),
            "an unloadable dylib guard must fail closed (Err), got Ok"
        );
        assert!(result.unwrap_err().contains("dynamic library"));
    }

    #[test]
    fn dylib_entry_parses_config() {
        let yaml = r#"
before_prompt:
  - dylib: /nonexistent.dylib
    config:
      patch_deliberation:
        upstream: epic
        downstream_root: ./downstreams
"#;
        let config: MiddlewareConfig = serde_yaml::from_str(yaml).unwrap();
        match &config.before_prompt[0] {
            MiddlewareEntry::Dylib { dylib, config, .. } => {
                assert_eq!(dylib.to_str(), Some("/nonexistent.dylib"));
                assert_eq!(
                    config["patch_deliberation"]["upstream"],
                    serde_json::json!("epic")
                );
                assert_eq!(
                    config["patch_deliberation"]["downstream_root"],
                    serde_json::json!("./downstreams")
                );
            }
            other => panic!("expected Dylib entry, got {other:?}"),
        }
    }
}