Skip to main content

qualia_client_core/api/
agents.rs

1//! Agent roster, MCP tool loop
2
3#![allow(non_snake_case)]
4
5use super::*;
6
7use std::path::Path;
8
9fn agent_roster_storage() -> Result<String, String> {
10    let state = crate::state::APP_STATE
11        .get()
12        .ok_or("Application not initialized")?;
13    let storage = state
14        .config
15        .lock()
16        .map_err(|e| e.to_string())?
17        .storage_path
18        .clone();
19    Ok(storage)
20}
21
22/// Lists the agent roster.
23pub fn agent_roster_list() -> Result<serde_json::Value, String> {
24    let storage = agent_roster_storage()?;
25    let roster = crate::agent_registry::load_roster(Path::new(&storage));
26    serde_json::to_value(roster).map_err(|e| e.to_string())
27}
28
29/// Gets an agent-roster entry.
30pub fn agent_roster_get(slug: String) -> Result<serde_json::Value, String> {
31    let storage = agent_roster_storage()?;
32    match crate::agent_registry::get_agent(Path::new(&storage), &slug) {
33        Some(a) => serde_json::to_value(a).map_err(|e| e.to_string()),
34        None => Ok(serde_json::Value::Null),
35    }
36}
37
38/// Upserts an agent-roster entry.
39pub fn agent_roster_upsert(agent_json: String) -> Result<(), String> {
40    let storage = agent_roster_storage()?;
41    let agent: crate::agent_registry::AgentDefinition =
42        serde_json::from_str(&agent_json).map_err(|e| format!("invalid agent JSON: {e}"))?;
43    crate::agent_registry::upsert_agent(Path::new(&storage), agent)
44}
45
46/// Removes an agent-roster entry.
47pub fn agent_roster_remove(slug: String) -> Result<(), String> {
48    let storage = agent_roster_storage()?;
49    crate::agent_registry::remove_agent(Path::new(&storage), &slug)
50}
51
52/// Truthful runtime projection for one roster agent.  Definitions are durable;
53/// this response describes only the currently effective local-model residency
54/// and recent decode measurement, so callers do not mistake "configured" for
55/// "loaded on GPU".
56pub fn agent_runtime_status(slug: String) -> Result<serde_json::Value, String> {
57    let storage = agent_roster_storage()?;
58    let agent = crate::agent_registry::get_agent(Path::new(&storage), &slug)
59        .ok_or_else(|| format!("unknown agent @{slug}"))?;
60    let active = crate::api::load_active_model_record_from_disk();
61    let (backend, configured_model, resident) = match &agent.backend {
62        crate::agent_registry::AgentBackendSpec::LocalEngine { model_id } => {
63            let resident = active.as_ref().is_some_and(|active| {
64                model_id
65                    .as_deref()
66                    .map_or(true, |configured| configured == active.model_id)
67            });
68            ("local", model_id.clone(), resident)
69        }
70        crate::agent_registry::AgentBackendSpec::RemoteMcp { model, .. } => {
71            ("remote_mcp", model.clone(), false)
72        }
73    };
74    Ok(serde_json::json!({
75        "slug": agent.slug,
76        "enabled": agent.enabled,
77        "backend": backend,
78        "configured_model_id": configured_model,
79        "resident": resident,
80        "active_model_id": active.as_ref().map(|record| record.model_id.clone()),
81        "lifecycle_state": crate::model_lifecycle::lifecycle_label(
82            crate::model_lifecycle::get_model_lifecycle_state()
83        ),
84        "last_decode_tokens_per_sec": crate::model_lifecycle::get_last_decode_tok_s(),
85        "last_decode_at_unix": crate::model_lifecycle::get_last_decode_tok_s_at_unix(),
86    }))
87}
88
89// ── Principal-gated MCP tool loop (U3-A / U3-B) ────────────────────────────────
90// Propose → Permit/Deny → execute. Deny never dispatches. Allowlist from roster.
91
92/// List local in-process MCP tools (`tools/list`) for Talk / allowlist UI.
93pub fn mcp_list_local_tools() -> Result<serde_json::Value, String> {
94    let tools = crate::mcp_tool_loop::mcp_list_local_tools()?;
95    serde_json::to_value(tools).map_err(|e| e.to_string())
96}
97
98/// Principal-gated MCP tool call. `principal_permitted = false` → Err without MCP.
99/// Tool must be on the agent's `allowed_mcp_tools` (or `*`); empty allowlist denies all.
100pub fn mcp_call_tool_gated(
101    agent_slug: String,
102    tool_name: String,
103    arguments_json: String,
104    principal_permitted: bool,
105) -> Result<String, String> {
106    let storage = agent_roster_storage()?;
107    crate::mcp_tool_loop::mcp_call_tool_gated(
108        Path::new(&storage),
109        &agent_slug,
110        &tool_name,
111        &arguments_json,
112        principal_permitted,
113    )
114}
115
116/// Convenience: set `allowed_mcp_tools` on a roster agent (persist via upsert).
117pub fn agent_set_allowed_mcp_tools(slug: String, tools: Vec<String>) -> Result<(), String> {
118    let storage = agent_roster_storage()?;
119    crate::mcp_tool_loop::agent_set_allowed_mcp_tools(Path::new(&storage), &slug, tools)
120}
121
122/// If allowlist is empty, seed `list_capabilities` + `computer_vision` (dogfood-safe).
123/// Does not Permit any call — only widens the roster allowlist.
124pub fn mcp_ensure_safe_tool_allowlist(slug: String) -> Result<serde_json::Value, String> {
125    let storage = agent_roster_storage()?;
126    let tools = crate::mcp_tool_loop::ensure_safe_tool_allowlist(Path::new(&storage), &slug)?;
127    serde_json::to_value(tools).map_err(|e| e.to_string())
128}
129
130/// Convenience: create/update a REMOTE-MCP agent from primitives so the UI never hand-builds the
131/// backend enum. `transport_kind` ∈ `"tcp"` | `"http"` | `"stdio"`; `endpoint` is `host:port` / a URL /
132/// a command line respectively.
133pub fn agent_roster_add_remote(
134    slug: String,
135    display_name: String,
136    transport_kind: String,
137    endpoint: String,
138    infer_tool: Option<String>,
139    model: Option<String>,
140    system_prompt: Option<String>,
141) -> Result<(), String> {
142    use crate::agent_registry::{AgentBackendSpec, McpTransport};
143    if slug.trim().is_empty() {
144        return Err("agent slug is required".to_string());
145    }
146    let transport = match transport_kind.to_lowercase().as_str() {
147        "tcp" => {
148            let (host, port) = endpoint
149                .rsplit_once(':')
150                .ok_or_else(|| "TCP endpoint must be host:port".to_string())?;
151            let port: u16 = port
152                .trim()
153                .parse()
154                .map_err(|_| "invalid TCP port".to_string())?;
155            McpTransport::Tcp {
156                host: host.trim().to_string(),
157                port,
158            }
159        }
160        "http" => McpTransport::Http {
161            url: endpoint.trim().to_string(),
162            credential_id: None,
163        },
164        "stdio" => {
165            let mut parts = endpoint.split_whitespace().map(|s| s.to_string());
166            let command = parts
167                .next()
168                .ok_or_else(|| "stdio endpoint needs a command".to_string())?;
169            McpTransport::Stdio {
170                command,
171                args: parts.collect(),
172            }
173        }
174        other => return Err(format!("unknown transport '{other}' (use tcp|http|stdio)")),
175    };
176    let backend = AgentBackendSpec::RemoteMcp {
177        endpoint: endpoint.trim().to_string(),
178        transport,
179        infer_tool: infer_tool.filter(|s| !s.trim().is_empty()),
180        model: model.filter(|s| !s.trim().is_empty()),
181        supports_system_role: None,
182    };
183    let mut agent = crate::agent_registry::AgentDefinition::new(
184        slug,
185        display_name,
186        "Remote agent reached over MCP.".to_string(),
187        backend,
188        system_prompt.unwrap_or_default(),
189    );
190    agent.enabled = true;
191    let storage = agent_roster_storage()?;
192    crate::agent_registry::upsert_agent(Path::new(&storage), agent)
193}
194
195/// Store a bearer credential for a user-owned connection in the operating
196/// system keychain. The secret is intentionally write-only at this API boundary.
197#[cfg(not(target_arch = "wasm32"))]
198pub fn provider_credential_store(connection_id: String, bearer: String) -> Result<(), String> {
199    crate::provider_credentials::store_bearer_credential(&connection_id, &bearer)
200}
201
202/// Remove a user-owned connection credential from the operating-system keychain.
203#[cfg(not(target_arch = "wasm32"))]
204pub fn provider_credential_remove(connection_id: String) -> Result<(), String> {
205    crate::provider_credentials::remove_bearer_credential(&connection_id)
206}
207
208/// Verify that a configured remote-MCP agent can answer the non-generative
209/// `tools/list` handshake.  This never sends a chat prompt.
210#[cfg(not(target_arch = "wasm32"))]
211pub fn agent_remote_connection_test(slug: String) -> Result<serde_json::Value, String> {
212    let storage = agent_roster_storage()?;
213    let agent = crate::agent_registry::get_agent(Path::new(&storage), &slug)
214        .ok_or_else(|| format!("no agent '{slug}' in roster"))?;
215    let transport = match &agent.backend {
216        crate::agent_registry::AgentBackendSpec::RemoteMcp { transport, .. } => transport,
217        crate::agent_registry::AgentBackendSpec::LocalEngine { .. } => {
218            return Err("only remote MCP agents have a connection to test".into());
219        }
220    };
221    let tool_count = crate::remote_mcp::remote_mcp_probe(transport)?;
222    Ok(serde_json::json!({
223        "ok": true,
224        "agent_slug": agent.slug,
225        "tool_count": tool_count,
226    }))
227}
228
229/// Backend kind of a roster agent: `"local"` | `"remote"` (unknown/empty slug → `"local"`).
230pub fn agent_backend_kind(slug: Option<String>) -> Result<String, String> {
231    let slug = match slug {
232        Some(s) if !s.is_empty() => s,
233        _ => return Ok("local".to_string()),
234    };
235    let storage = agent_roster_storage()?;
236    match crate::agent_registry::get_agent(Path::new(&storage), &slug) {
237        Some(a) => Ok(match a.backend {
238            crate::agent_registry::AgentBackendSpec::LocalEngine { .. } => "local".to_string(),
239            crate::agent_registry::AgentBackendSpec::RemoteMcp { .. } => "remote".to_string(),
240        }),
241        None => Ok("local".to_string()),
242    }
243}
244
245/// Run one turn against a REMOTE-MCP agent from the roster (native-only). Privacy-gated via the job
246/// router (Classified/sanctuary never leaves the device), then issues an MCP `tools/call` to the
247/// provider and appends the reply as an agent message. Returns a ChatInferenceResult-shaped JSON.
248#[cfg(not(target_arch = "wasm32"))]
249pub fn run_remote_agent_turn(
250    session_id: String,
251    slug: String,
252    prompt: String,
253    per_turn_consent: bool,
254) -> Result<serde_json::Value, String> {
255    use crate::agent_registry::AgentBackendSpec;
256    let storage = agent_roster_storage()?;
257    let agent = crate::agent_registry::get_agent(Path::new(&storage), &slug)
258        .ok_or_else(|| format!("no agent '{slug}' in roster"))?;
259    if !agent.enabled {
260        return Ok(remote_turn_blocked(&format!(
261            "agent '{}' is disabled",
262            agent.display_name
263        )));
264    }
265    match agent.execution_policy.remote_consent {
266        crate::agent_registry::RemoteConsentPolicy::Never => {
267            return Ok(remote_turn_blocked(
268                "this agent's remote connection is disabled by its policy",
269            ));
270        }
271        crate::agent_registry::RemoteConsentPolicy::PerTurn if !per_turn_consent => {
272            return Ok(remote_turn_blocked(
273                "remote dispatch requires this turn's explicit confirmation",
274            ));
275        }
276        crate::agent_registry::RemoteConsentPolicy::PerTurn
277        | crate::agent_registry::RemoteConsentPolicy::Preapproved => {}
278    }
279    let (transport, infer_tool, model, declared_system_role) = match &agent.backend {
280        AgentBackendSpec::RemoteMcp {
281            transport,
282            infer_tool,
283            model,
284            supports_system_role,
285            ..
286        } => (
287            transport.clone(),
288            infer_tool.clone(),
289            model.clone(),
290            *supports_system_role,
291        ),
292        AgentBackendSpec::LocalEngine { .. } => {
293            return Err("agent is local — use the local inference path".to_string());
294        }
295    };
296
297    // Privacy-first placement: a configured remote agent implies consent, but sanctuary/Classified
298    // context must never leave the device.
299    let local_active = crate::model_lifecycle::lifecycle_label(
300        crate::model_lifecycle::get_model_lifecycle_state(),
301    ) == "Active";
302    let inputs = crate::job_router::RoutingInputs {
303        sensitivity: wellfare_core::record::SensitivityClass::Restricted,
304        local_available: local_active,
305        external_consented: per_turn_consent
306            || matches!(
307                agent.execution_policy.remote_consent,
308                crate::agent_registry::RemoteConsentPolicy::Preapproved
309            ),
310        requires_capability: None,
311        local_has_capability: false,
312        estimated_cost_microcents: 0,
313    };
314    match crate::job_router::route_job(&inputs, &crate::job_router::RoutingPolicy::default()) {
315        crate::job_router::RoutingDecision::Blocked { reason }
316        | crate::job_router::RoutingDecision::NeedsConsent { reason } => {
317            return Ok(remote_turn_blocked(&reason));
318        }
319        _ => {}
320    }
321
322    // Prompt Precision: the same persisted profile that conditions local chat
323    // is compiled for this turn and carried as system text. Compile failures
324    // fail closed — enforced requirements are never silently dropped before a
325    // remote dispatch leaves the device.
326    let principal = crate::user_profile::load_profile().public_did;
327    let prepared = crate::conditioning::prepare_active_semantic_request(
328        Path::new(&storage),
329        &prompt,
330        &principal,
331        &format!("webizen:session:{session_id}"),
332        1024,
333    )?;
334
335    // System text = the agent's declared persona + the prepared request.
336    let system_owned = {
337        let mut parts: Vec<&str> = Vec::with_capacity(2);
338        if !agent.system_prompt.trim().is_empty() {
339            parts.push(agent.system_prompt.trim());
340        }
341        if let Some(request) = &prepared {
342            parts.push(request.text.as_str());
343        }
344        if parts.is_empty() {
345            None
346        } else {
347            Some(parts.join("\n\n"))
348        }
349    };
350
351    // Capability precedence: roster-declared flag, then `tools/list`
352    // discovery; unknown capability flattens with a degradation receipt.
353    let supports_system_role = declared_system_role.or_else(|| {
354        let tool = infer_tool
355            .as_deref()
356            .unwrap_or(crate::remote_mcp::DEFAULT_INFER_TOOL);
357        crate::remote_mcp::remote_mcp_tool_supports_system_role(&transport, tool)
358    });
359
360    let started = std::time::Instant::now();
361    let outcome = crate::remote_mcp::remote_mcp_infer(
362        &transport,
363        infer_tool.as_deref(),
364        model.as_deref(),
365        system_owned.as_deref(),
366        &prompt,
367        supports_system_role,
368    )?;
369    let duration_ms = started.elapsed().as_millis() as u64;
370
371    // `committed` reports whether the reply was actually persisted to the
372    // session log — a remote response alone commits nothing to the graph.
373    let appended = if !outcome.text.trim().is_empty() {
374        append_chat_message(session_id, "agent".to_string(), outcome.text.clone()).is_ok()
375    } else {
376        false
377    };
378    let role_mode = match outcome.lowering.mode {
379        crate::conditioning::McpLoweringMode::Structured => "structured",
380        crate::conditioning::McpLoweringMode::Flattened => "flattened",
381    };
382    let conditioning = prepared.as_ref().map(|request| {
383        request.receipt(
384            "remote_mcp",
385            role_mode,
386            outcome.lowering.role_degraded,
387            outcome.lowering.degradation_reason.map(str::to_string),
388        )
389    });
390    Ok(serde_json::json!({
391        "text": outcome.text,
392        "committed": appended,
393        "session_appended": appended,
394        "wal_committed": false,
395        "block_reason": serde_json::Value::Null,
396        "agent_backend": "remote",
397        "model_id": model,
398        "provenance_hashes": [],
399        "citations": [],
400        "tokens_generated": serde_json::Value::Null,
401        "token_measurement": "unknown",
402        "inference_duration_ms": duration_ms,
403        "latency_measurement": "measured",
404        "conditioning": conditioning,
405        "mcp_lowering": outcome.lowering,
406    }))
407}
408
409#[cfg(not(target_arch = "wasm32"))]
410fn remote_turn_blocked(reason: &str) -> serde_json::Value {
411    serde_json::json!({
412        "text": "",
413        "committed": false,
414        "block_reason": reason,
415        "agent_backend": "remote",
416    })
417}
418
419/// Store a chat turn's inline CML context (`#project:` / `#topic:` / `#task:` / `[[concept]]`) into the
420/// person's inforg (their private library). No-op if the message has no tags. Returns concepts stored.
421pub fn ingest_chat_cml(session_id: String, text: String) -> Result<usize, String> {
422    let storage = agent_roster_storage()?;
423    crate::cml_context::ingest_turn(Path::new(&storage), &session_id, &text).map(|v| v.len())
424}