quorum-rs 0.7.0-rc.6

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.
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
//! Agent registration REST handlers — add, remove, update, and bulk-register agents.
//!
//! These endpoints validate requests and update in-memory configuration.
//! Full worker lifecycle (spawn/stop/persist) requires AgentManager integration.

use super::MultiAppState;
use crate::agents::AgentConfig;
use axum::extract::{Json, Path, Query, State};
use axum::http::StatusCode;
use axum::response::IntoResponse;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;

// ---------------------------------------------------------------------------
// Request / Response types
// ---------------------------------------------------------------------------

/// Request body for registering a new agent.
#[derive(Debug, Deserialize, ToSchema)]
pub struct RegisterAgentRequest {
    /// Unique agent name (alphanumeric + underscore, max 64 chars).
    pub name: String,
    /// Provider ID — must reference a configured provider.
    pub provider_id: String,
    /// Model name (optional for stub provider).
    #[serde(default)]
    pub model_name: Option<String>,
    /// Agent persona / system prompt.
    #[serde(default)]
    pub persona: Option<String>,
    /// Response SLA in seconds.
    #[serde(default)]
    pub response_sla_secs: Option<u64>,
    /// Capability tags for directory filtering.
    #[serde(default)]
    pub capability_tags: Vec<String>,
    /// Agent description.
    #[serde(default)]
    pub description: Option<String>,
    /// Signing schemes supported.
    #[serde(default)]
    pub signing_schemes: Vec<String>,
}

/// Response after registering an agent.
#[derive(Debug, Serialize, ToSchema)]
pub struct RegisterAgentResponse {
    pub name: String,
    pub status: String,
}

/// Request for bulk agent registration.
#[derive(Debug, Deserialize, ToSchema)]
pub struct BulkRegisterRequest {
    pub agents: Vec<RegisterAgentRequest>,
}

/// Response for bulk registration.
#[derive(Debug, Serialize, ToSchema)]
pub struct BulkRegisterResponse {
    pub registered: Vec<String>,
    pub failed: u32,
    pub errors: Vec<String>,
}

/// Query params for force-delete.
#[derive(Debug, Deserialize)]
pub struct DeleteQuery {
    #[serde(default)]
    pub force: bool,
}

// ---------------------------------------------------------------------------
// Validation
// ---------------------------------------------------------------------------

fn validate_agent_name(name: &str) -> Result<(), String> {
    if name.is_empty() || name.len() > 64 {
        return Err("Agent name must be 1-64 characters".to_string());
    }
    if !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
        return Err("Agent name must be alphanumeric + underscore only".to_string());
    }
    Ok(())
}

fn request_to_config(req: &RegisterAgentRequest) -> Result<AgentConfig, String> {
    let model_name = match &req.model_name {
        Some(m) => m.clone(),
        None if req.provider_id.contains("stub") => "stub".to_string(),
        None => {
            return Err(format!(
                "model_name is required for provider '{}'",
                req.provider_id
            ));
        }
    };
    Ok(AgentConfig {
        name: req.name.clone(),
        provider_id: req.provider_id.clone(),
        model_name,
        persona: req.persona.clone(),
        response_sla_secs: req.response_sla_secs.unwrap_or(300),
        capability_tags: req.capability_tags.clone(),
        description: req.description.clone(),
        signing_schemes: req.signing_schemes.clone(),
        ..Default::default()
    })
}

// ---------------------------------------------------------------------------
// Handlers
// ---------------------------------------------------------------------------

/// `POST /api/agents/register` — Register a new agent.
#[utoipa::path(
    post,
    path = "/api/agents/register",
    tag = "Agent Management",
    summary = "Register new agent",
    description = "Add a new agent to the config and start it. Returns 409 if the agent already exists.",
    request_body = RegisterAgentRequest,
    responses(
        (status = 202, description = "Agent registration accepted (pending hot-reload)", body = RegisterAgentResponse),
        (status = 400, description = "Invalid agent name or config"),
        (status = 409, description = "Agent already exists"),
    )
)]
pub(super) async fn register_agent(
    State(state): State<MultiAppState>,
    Json(req): Json<RegisterAgentRequest>,
) -> impl IntoResponse {
    if let Err(msg) = validate_agent_name(&req.name) {
        return (
            StatusCode::BAD_REQUEST,
            Json(serde_json::json!({"error": msg})),
        )
            .into_response();
    }

    // Check for duplicate
    if state.configs.contains_key(&req.name) {
        return (
            StatusCode::CONFLICT,
            Json(serde_json::json!({"error": format!("Agent '{}' already exists", req.name)})),
        )
            .into_response();
    }

    // Validate the config can be built (catches bad field combos early)
    if let Err(msg) = request_to_config(&req) {
        return (
            StatusCode::BAD_REQUEST,
            Json(serde_json::json!({"error": msg})),
        )
            .into_response();
    }

    // AgentManager is not yet wired into MultiAppState — config validated
    // but worker lifecycle (spawn/stop/persist) requires full integration.
    (
        StatusCode::NOT_IMPLEMENTED,
        Json(serde_json::json!({
            "error": "Agent registration validated but not yet executable — AgentManager integration pending",
            "name": req.name,
            "validated": true
        })),
    )
        .into_response()
}

/// `DELETE /api/agents/{id}/manage` — Remove an agent.
#[utoipa::path(
    delete,
    path = "/api/agents/{id}/manage",
    tag = "Agent Management",
    summary = "Remove agent",
    description = "Stop and remove an agent. Use ?force=true to remove agents with pending tasks.",
    params(
        ("id" = String, Path, description = "Agent ID (currently name; future: pubkey fingerprint)"),
        ("force" = Option<bool>, Query, description = "Set to true to force removal of agents with pending tasks"),
    ),
    responses(
        (status = 202, description = "Agent removal accepted (pending hot-reload)"),
        (status = 404, description = "Agent not found"),
        (status = 409, description = "Agent has pending tasks (use ?force=true)"),
    )
)]
pub(super) async fn delete_agent(
    State(state): State<MultiAppState>,
    Path(id): Path<String>,
    Query(query): Query<DeleteQuery>,
) -> impl IntoResponse {
    if !state.configs.contains_key(&id) {
        return (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({"error": format!("Agent '{}' not found", id)})),
        )
            .into_response();
    }

    // Check for pending tasks (buffered entries)
    if !query.force {
        if let Some(buf) = state.buffers.get(&id) {
            let pending = buf.list().await;
            if !pending.is_empty() {
                return (
                    StatusCode::CONFLICT,
                    Json(serde_json::json!({
                        "error": format!("Agent '{}' has {} pending buffer entries. Use ?force=true to remove.", id, pending.len())
                    })),
                )
                    .into_response();
            }
        }
    }

    // AgentManager not wired — can't stop worker or persist removal
    (
        StatusCode::NOT_IMPLEMENTED,
        Json(serde_json::json!({
            "error": "Agent removal validated but not yet executable — AgentManager integration pending",
            "id": id,
            "validated": true
        })),
    )
        .into_response()
}

/// `PUT /api/agents/{id}/manage` — Full replace of agent config.
#[utoipa::path(
    put,
    path = "/api/agents/{id}/manage",
    tag = "Agent Management",
    summary = "Replace agent config",
    description = "Full replace of agent configuration in memory. Config changes take effect on the worker's next task cycle. Full restart requires AgentManager integration.",
    params(
        ("id" = String, Path, description = "Agent ID (currently name; future: pubkey fingerprint)"),
    ),
    request_body = RegisterAgentRequest,
    responses(
        (status = 200, description = "Agent updated", body = RegisterAgentResponse),
        (status = 404, description = "Agent not found"),
        (status = 400, description = "Invalid config"),
    )
)]
pub(super) async fn replace_agent(
    State(state): State<MultiAppState>,
    Path(id): Path<String>,
    Json(req): Json<RegisterAgentRequest>,
) -> impl IntoResponse {
    // Body name must match path ID (or be omitted — use path ID)
    if req.name != id {
        return (
            StatusCode::BAD_REQUEST,
            Json(serde_json::json!({"error": format!("Body name '{}' does not match path id '{}'", req.name, id)})),
        )
            .into_response();
    }

    let Some(config_lock) = state.configs.get(&id) else {
        return (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({"error": format!("Agent '{}' not found", id)})),
        )
            .into_response();
    };

    let new_config = match request_to_config(&req) {
        Ok(c) => c,
        Err(msg) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(serde_json::json!({"error": msg})),
            )
                .into_response();
        }
    };

    // Update the in-memory config
    {
        let mut config = config_lock.write().await;
        config.provider_id = new_config.provider_id;
        config.model_name = new_config.model_name;
        config.persona = new_config.persona;
        config.response_sla_secs = new_config.response_sla_secs;
        config.capability_tags = new_config.capability_tags;
        config.description = new_config.description;
        config.signing_schemes = new_config.signing_schemes;
    }

    let response = RegisterAgentResponse {
        name: id.clone(),
        status: "config_updated".to_string(),
    };

    tracing::info!(agent = %id, "Agent config replaced in-memory (worker restart requires AgentManager)");
    (StatusCode::OK, Json(response)).into_response()
}

/// `PATCH /api/agents/{id}/manage` — Partial update of agent config.
#[utoipa::path(
    patch,
    path = "/api/agents/{id}/manage",
    tag = "Agent Management",
    summary = "Patch agent config",
    description = "Partial update — only provided fields are changed.",
    params(
        ("id" = String, Path, description = "Agent ID (currently name; future: pubkey fingerprint)"),
    ),
    request_body = PatchAgentRequest,
    responses(
        (status = 200, description = "Agent patched", body = RegisterAgentResponse),
        (status = 404, description = "Agent not found"),
    )
)]
pub(super) async fn patch_agent(
    State(state): State<MultiAppState>,
    Path(id): Path<String>,
    Json(patch): Json<PatchAgentRequest>,
) -> impl IntoResponse {
    let Some(config_lock) = state.configs.get(&id) else {
        return (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({"error": format!("Agent '{}' not found", id)})),
        )
            .into_response();
    };

    {
        let mut config = config_lock.write().await;
        if let Some(ref provider_id) = patch.provider_id {
            config.provider_id = provider_id.clone();
        }
        if let Some(ref model_name) = patch.model_name {
            config.model_name = model_name.clone();
        }
        if let Some(ref persona) = patch.persona {
            config.persona = Some(persona.clone());
        }
        if let Some(sla) = patch.response_sla_secs {
            config.response_sla_secs = sla;
        }
        if let Some(ref tags) = patch.capability_tags {
            config.capability_tags = tags.clone();
        }
        if let Some(ref desc) = patch.description {
            config.description = Some(desc.clone());
        }
        if let Some(ref schemes) = patch.signing_schemes {
            config.signing_schemes = schemes.clone();
        }
    }

    let response = RegisterAgentResponse {
        name: id.clone(),
        status: "patched".to_string(),
    };

    tracing::info!(agent = %id, "Agent config patched via API");
    (StatusCode::OK, Json(response)).into_response()
}

/// Partial update fields for PATCH.
#[derive(Debug, Deserialize, ToSchema)]
pub struct PatchAgentRequest {
    #[serde(default)]
    pub provider_id: Option<String>,
    #[serde(default)]
    pub model_name: Option<String>,
    #[serde(default)]
    pub persona: Option<String>,
    #[serde(default)]
    pub response_sla_secs: Option<u64>,
    #[serde(default)]
    pub capability_tags: Option<Vec<String>>,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub signing_schemes: Option<Vec<String>>,
}

/// `POST /api/agents/bulk` — Register multiple agents at once.
#[utoipa::path(
    post,
    path = "/api/agents/bulk",
    tag = "Agent Management",
    summary = "Bulk register agents",
    description = "Register multiple agents in one request.",
    request_body = BulkRegisterRequest,
    responses(
        (status = 202, description = "Agent registrations accepted (pending hot-reload)", body = BulkRegisterResponse),
    )
)]
pub(super) async fn bulk_register(
    State(state): State<MultiAppState>,
    Json(req): Json<BulkRegisterRequest>,
) -> impl IntoResponse {
    let mut registered = Vec::new();
    let mut errors = Vec::new();
    let mut seen = std::collections::HashSet::new();

    for agent_req in &req.agents {
        if let Err(msg) = validate_agent_name(&agent_req.name) {
            errors.push(format!("{}: {}", agent_req.name, msg));
            continue;
        }
        if state.configs.contains_key(&agent_req.name) {
            errors.push(format!("{}: already exists", agent_req.name));
            continue;
        }
        if !seen.insert(agent_req.name.clone()) {
            errors.push(format!("{}: duplicate in request", agent_req.name));
            continue;
        }
        // Validate config can be built
        if let Err(msg) = request_to_config(agent_req) {
            errors.push(format!("{}: {}", agent_req.name, msg));
            continue;
        }
        registered.push(agent_req.name.clone());
        tracing::info!(agent = %agent_req.name, "Agent bulk-registered via API (pending hot-reload)");
    }

    // Return validation results but indicate that actual registration
    // (worker spawn + persistence) is not yet executable.
    (
        StatusCode::NOT_IMPLEMENTED,
        Json(serde_json::json!({
            "error": "Bulk registration validated but not yet executable — AgentManager integration pending",
            "validated": registered,
            "validation_errors": errors,
        })),
    )
        .into_response()
}