Skip to main content

qualia_client_core/api/
qapp_vault.rs

1//! QApp vault, config, wallet status
2
3#![allow(non_snake_case)]
4
5use super::*;
6
7use crate::qapp_paths::qapps_dir;
8use crate::qapp_registry;
9use crate::state::*;
10use serde::Serialize;
11use std::path::PathBuf;
12use std::sync::atomic::Ordering;
13use sysinfo::Disks;
14
15/// Lists installed qapps.
16pub fn list_installed_qapps() -> Vec<String> {
17    let state = crate::state::APP_STATE.get().unwrap();
18    let data_dir = state.config.lock().unwrap().storage_path.clone();
19    let qapps_dir = qapps_dir(&data_dir);
20    let mut qapps = Vec::new();
21    if let Ok(entries) = std::fs::read_dir(qapps_dir) {
22        for entry in entries.filter_map(Result::ok) {
23            if entry.path().is_dir() {
24                qapps.push(entry.file_name().to_string_lossy().to_string());
25            }
26        }
27    }
28    qapps
29}
30
31/// MCP: lists qapps.
32pub fn mcp_list_qapps() -> Result<String, String> {
33    crate::qapp_mcp::list_qapp_catalogue_json()
34}
35
36/// MCP: gets a qapp manifest.
37pub fn mcp_get_qapp_manifest(qapp_name: String) -> Result<String, String> {
38    crate::qapp_mcp::get_qapp_manifest_json(&qapp_name)
39}
40
41/// MCP: inspects qapp readiness.
42pub fn mcp_inspect_qapp_readiness(qapp_name: String) -> Result<String, String> {
43    crate::qapp_mcp::inspect_qapp_readiness_json(&qapp_name)
44}
45
46/// MCP: lists qapp updates.
47pub fn mcp_list_qapp_updates() -> Result<String, String> {
48    crate::qapp_mcp::list_qapp_updates_json()
49}
50
51/// MCP: describes the qapp surface schema.
52pub fn mcp_describe_qapp_surface_schema() -> Result<String, String> {
53    crate::qapp_mcp::describe_qapp_surface_schema_json()
54}
55
56/// Generates a qapp credential.
57pub fn generate_qapp_credential(qapp_name: String) -> String {
58    format!("did:qualia:qapp:{}:signed_vc", qapp_name)
59}
60
61/// Verifies and installs a qapp.
62pub fn verify_and_install_qapp(target_path: String) -> Result<String, String> {
63    let state = crate::state::APP_STATE.get().unwrap();
64    let storage = state.config.lock().unwrap().storage_path.clone();
65    let storage_path = std::path::PathBuf::from(&storage);
66
67    if let Ok(port) = target_path.parse::<u16>() {
68        return Err(format!(
69            "Dev proxy port registration ({port}) requires a package directory path, not a bare port"
70        ));
71    }
72
73    let source_dir = std::path::PathBuf::from(&target_path);
74    if !source_dir.is_dir() {
75        return Err(format!("Qapp source directory not found: {target_path}"));
76    }
77
78    let entry = crate::qapp_install::install_package_atomic(
79        &storage_path,
80        &source_dir,
81        crate::qapp_install::InstallPolicy::Development,
82        None,
83    )
84    .map_err(|e| e.to_string())?;
85
86    let package_dir =
87        crate::qapp_paths::resolve_active_package_dir(&storage_path, &entry.package_id);
88    let manifest = load_qapp_package_from_dir(&package_dir)?;
89    let qapp_did = format!(
90        "did:qualia:qapp:{}",
91        manifest.name.to_lowercase().replace(" ", "-")
92    );
93
94    let registered_qapp = qapp_registry::RegisteredQapp {
95        did: qapp_did.clone(),
96        manifest: manifest.clone(),
97        target: qapp_registry::QappTarget::IsolatedVault(entry.package_id.clone()),
98    };
99
100    let qapp_id_hash = crate::qapp_manifest::install_qapp_capabilities(&manifest)
101        .map_err(|e| format!("Qapp capability compile failed: {e:?}"))?;
102
103    {
104        let mut installed = state.installed_qapps.lock().unwrap();
105        installed.retain(|q| q.manifest.name != entry.package_id && q.did != qapp_did);
106        installed.push(registered_qapp);
107    }
108    save_directory_state();
109
110    Ok(format!(
111        "{qapp_did} v{} hash={} content={}",
112        entry.active_version, qapp_id_hash, entry.content_hash
113    ))
114}
115
116#[derive(Serialize)]
117pub struct WalletStatus {
118    /// XEC balance in satoshis (live from Chronik when identity is set).
119    pub xec_sats: i64,
120    /// Total ILP micro-cents dispatched (from persistent ledger).
121    pub ilp_dispatched_microcents: u64,
122    /// Whether the Nym mixnet relay is active.
123    pub nym_connected: bool,
124    /// Sync status: "synced" | "offline" | "no_identity".
125    pub sync_status: String,
126}
127
128/// Gets wallet-status.
129pub fn get_wallet_status() -> WalletStatus {
130    let nym_connected = crate::state::APP_STATE
131        .get()
132        .map(|s| s.nym_relay_active.load(Ordering::Relaxed))
133        .unwrap_or(false);
134
135    let state = crate::state::APP_STATE.get();
136    let storage_path = state
137        .map(|s| s.config.lock().unwrap().storage_path.clone())
138        .unwrap_or_default();
139
140    // Read ILP dispatched total from persistent ledger
141    let ilp_dispatched =
142        crate::wallet::ledger::total_ilp_sent_micro_cents(&std::path::Path::new(&storage_path));
143
144    // Query live XEC balance from Chronik if identity is set
145    let id = read_identity();
146    let (xec_sats, sync_status) = match id
147        .as_ref()
148        .and_then(|v| v.get("ecash_hash160"))
149        .and_then(|v| v.as_str())
150    {
151        Some(hash160) => {
152            let client = crate::wallet::chronik::ChronikClient::new("https://chronik.be.cash");
153            match client.fetch_utxos_p2pkh(hash160) {
154                Ok(utxos) => {
155                    let sats: i64 = utxos
156                        .iter()
157                        .filter(|u| u.slp_meta.is_none())
158                        .map(|u| u.value)
159                        .sum();
160                    (sats, "synced".to_string())
161                }
162                Err(_) => (0, "offline".to_string()),
163            }
164        }
165        None => (0, "no_identity".to_string()),
166    };
167
168    WalletStatus {
169        xec_sats,
170        ilp_dispatched_microcents: ilp_dispatched,
171        nym_connected,
172        sync_status,
173    }
174}
175
176/// `true` when Nym mixnet is opted in.
177pub fn nym_mixnet_opted_in() -> bool {
178    crate::state::APP_STATE
179        .get()
180        .map(|s| s.nym_relay_active.load(Ordering::Relaxed))
181        .unwrap_or(false)
182}
183
184/// Gets config.
185pub fn get_config() -> AgentConfig {
186    let state = crate::state::APP_STATE.get().unwrap();
187    state.config.lock().unwrap().clone()
188}
189
190/// Saves config.
191pub fn save_config(new_config: AgentConfig) -> Result<(), String> {
192    let state = crate::state::APP_STATE.get().unwrap();
193    let disks = Disks::new_with_refreshed_list();
194    let path = PathBuf::from(&new_config.storage_path);
195    let mut available = u64::MAX;
196    for disk in disks.list() {
197        if path.starts_with(disk.mount_point()) {
198            available = disk.available_space();
199            break;
200        }
201    }
202    let margin: u64 = 15 * 1024 * 1024 * 1024;
203    let requested = new_config.storage_quota_gb * 1024 * 1024 * 1024;
204    if available.saturating_sub(requested) < margin {
205        return Err(
206            "OS_SAFETY_VIOLATION: Would leave the host OS with less than the 15 GB safety margin."
207                .to_string(),
208        );
209    }
210    // Persist config to disk
211    let meta = app_meta_dir();
212    std::fs::create_dir_all(&meta).map_err(|e| e.to_string())?;
213    let json = serde_json::to_string_pretty(&new_config).map_err(|e| e.to_string())?;
214    std::fs::write(config_file_path(), json).map_err(|e| e.to_string())?;
215    // Ensure data directories exist under the new path
216    init_data_directories(&new_config.storage_path);
217    // Mirror inference_backend string into structured settings (Local/Remote/Hybrid/Ollama).
218    let mut ib = crate::inference_backend::load_inference_backend_settings();
219    ib.apply_agent_config_backend_string(&new_config.inference_backend);
220    let _ = crate::inference_backend::save_inference_backend_settings(&ib);
221    *state.config.lock().unwrap() = new_config;
222    Ok(())
223}