Skip to main content

qualia_client_core/api/
jobs.rs

1//! Local job scheduler
2
3#![allow(non_snake_case)]
4
5use super::*;
6
7use std::path::Path;
8
9/// Schedule one agent turn as a background job (queued, off the chat thread). Routed local-first; a
10/// remote-MCP agent's turn is sent out over MCP. Returns the created job as JSON.
11pub fn schedule_agent_job(
12    session_id: String,
13    agent_slug: Option<String>,
14    prompt: String,
15) -> Result<serde_json::Value, String> {
16    let agent_updated_at_unix = if let Some(slug) = agent_slug.as_deref() {
17        let state = crate::state::APP_STATE
18            .get()
19            .ok_or("Application not initialized")?;
20        let storage = state
21            .config
22            .lock()
23            .map_err(|error| error.to_string())?
24            .storage_path
25            .clone();
26        Some(
27            crate::agent_registry::get_agent(Path::new(&storage), slug)
28                .ok_or_else(|| format!("unknown agent @{slug}"))?
29                .updated_at_unix,
30        )
31    } else {
32        None
33    };
34    let job = crate::local_job_scheduler::LocalJobScheduler::global().enqueue(
35        crate::local_job_scheduler::LocalJobKind::AgentTurn {
36            session_id,
37            agent_slug,
38            agent_updated_at_unix,
39            prompt,
40            context_snapshot: Vec::new(),
41        },
42    )?;
43    serde_json::to_value(job).map_err(|e| e.to_string())
44}
45
46/// Snapshot of the local job queue (jobs + status counts).
47pub fn list_local_jobs() -> Result<serde_json::Value, String> {
48    let snap = crate::local_job_scheduler::LocalJobScheduler::global().snapshot()?;
49    serde_json::to_value(snap).map_err(|e| e.to_string())
50}
51
52/// Cancel a job by id (queued → cancelled; running → cooperative cancel).
53pub fn cancel_local_job(id: String) -> Result<bool, String> {
54    crate::local_job_scheduler::LocalJobScheduler::global().cancel(&id)
55}
56
57/// Re-run a finished job with the same bounded inputs.
58pub fn retry_local_job(id: String) -> Result<serde_json::Value, String> {
59    let job = crate::local_job_scheduler::LocalJobScheduler::global().retry(&id)?;
60    serde_json::to_value(job).map_err(|e| e.to_string())
61}
62
63/// Clear completed/failed/cancelled history without affecting active work.
64pub fn clear_finished_local_jobs() -> Result<usize, String> {
65    crate::local_job_scheduler::LocalJobScheduler::global().clear_finished()
66}
67
68/// Schedules a model download.
69pub fn schedule_model_download(
70    url: String,
71    filename: String,
72    model_id: String,
73) -> Result<serde_json::Value, String> {
74    let job = crate::local_job_scheduler::LocalJobScheduler::global().enqueue(
75        crate::local_job_scheduler::LocalJobKind::ModelDownload {
76            url,
77            filename,
78            model_id,
79        },
80    )?;
81    serde_json::to_value(job).map_err(|e| e.to_string())
82}
83
84/// Schedules model activation.
85pub fn schedule_model_activation(model_name: String) -> Result<serde_json::Value, String> {
86    let job = crate::local_job_scheduler::LocalJobScheduler::global()
87        .enqueue(crate::local_job_scheduler::LocalJobKind::ModelActivation { model_name })?;
88    serde_json::to_value(job).map_err(|e| e.to_string())
89}
90
91/// Schedules an anatomy-asset acquire.
92pub fn schedule_anatomy_asset_acquire(model: String) -> Result<serde_json::Value, String> {
93    // Validate before queueing so typo failures are immediate and visible at the initiating control.
94    crate::wellfair::api::parse_anatomy_model(&model)?;
95    let job = crate::local_job_scheduler::LocalJobScheduler::global()
96        .enqueue(crate::local_job_scheduler::LocalJobKind::AnatomyAssetAcquire { model })?;
97    serde_json::to_value(job).map_err(|e| e.to_string())
98}
99
100/// Enqueue a job for a specific apparatus (`did:q42:device:…`). Empty target → this install.
101/// Remote devices fail closed until multi-device dispatch is live.
102pub fn schedule_job_on_device(
103    kind_json: String,
104    target_device_id: Option<String>,
105) -> Result<serde_json::Value, String> {
106    let kind: crate::local_job_scheduler::LocalJobKind =
107        serde_json::from_str(&kind_json).map_err(|e| format!("invalid job kind: {e}"))?;
108    let job = crate::local_job_scheduler::LocalJobScheduler::global()
109        .enqueue_for_device(kind, target_device_id)?;
110    serde_json::to_value(job).map_err(|e| e.to_string())
111}
112
113/// Ensures chat-session.
114pub fn ensure_chat_session() -> Result<String, String> {
115    if let Some(id) = get_last_chat_session_id() {
116        let state = crate::state::APP_STATE.get().unwrap();
117        let storage = state.config.lock().unwrap().storage_path.clone();
118        if crate::chat_session::load_session(Path::new(&storage), &id).is_ok() {
119            return Ok(id);
120        }
121    }
122    create_chat_session(None)
123}
124
125/// Creates group-chat-session.
126pub fn create_group_chat_session(
127    title: Option<String>,
128    participant_dids: Vec<String>,
129) -> Result<String, String> {
130    let state = crate::state::APP_STATE.get().unwrap();
131    let storage = state.config.lock().unwrap().storage_path.clone();
132    crate::chat_session::create_group_session(Path::new(&storage), title, &participant_dids)
133        .map_err(|e| e.to_string())
134}
135
136/// Adds chat-participant.
137pub fn add_chat_participant(
138    session_id: String,
139    participant_did: String,
140) -> Result<serde_json::Value, String> {
141    let state = crate::state::APP_STATE.get().unwrap();
142    let storage = state.config.lock().unwrap().storage_path.clone();
143    let participants =
144        crate::chat_session::add_participant(Path::new(&storage), &session_id, &participant_did)
145            .map_err(|e| e.to_string())?;
146    serde_json::to_value(participants).map_err(|e| e.to_string())
147}
148
149/// Removes chat-participant.
150pub fn remove_chat_participant(
151    session_id: String,
152    participant_did: String,
153) -> Result<serde_json::Value, String> {
154    let state = crate::state::APP_STATE.get().unwrap();
155    let storage = state.config.lock().unwrap().storage_path.clone();
156    let participants =
157        crate::chat_session::remove_participant(Path::new(&storage), &session_id, &participant_did)
158            .map_err(|e| e.to_string())?;
159    serde_json::to_value(participants).map_err(|e| e.to_string())
160}
161
162/// Gets chat-participants.
163pub fn get_chat_participants(session_id: String) -> Result<serde_json::Value, String> {
164    let state = crate::state::APP_STATE.get().unwrap();
165    let storage = state.config.lock().unwrap().storage_path.clone();
166    let participants = crate::chat_session::get_participants(Path::new(&storage), &session_id)
167        .map_err(|e| e.to_string())?;
168    serde_json::to_value(participants).map_err(|e| e.to_string())
169}
170
171/// Gets local-agent-config.
172pub fn get_local_agent_config(session_id: String) -> Result<serde_json::Value, String> {
173    let state = crate::state::APP_STATE.get().unwrap();
174    let storage = state.config.lock().unwrap().storage_path.clone();
175    let cfg = crate::chat_agents::load_local_agent_config(Path::new(&storage), &session_id)?;
176    serde_json::to_value(cfg).map_err(|e| e.to_string())
177}
178
179/// Updates agent outcome sharing.
180pub fn update_agent_outcome_sharing(
181    session_id: String,
182    policy_json: String,
183) -> Result<serde_json::Value, String> {
184    let policy: crate::chat_agents::OutcomeSharingPolicy =
185        serde_json::from_str(&policy_json).map_err(|e| e.to_string())?;
186    let state = crate::state::APP_STATE.get().unwrap();
187    let storage = state.config.lock().unwrap().storage_path.clone();
188    let cfg = crate::chat_agents::update_outcome_sharing(Path::new(&storage), &session_id, policy)?;
189    serde_json::to_value(cfg).map_err(|e| e.to_string())
190}
191
192/// Gets default-outcome-sharing.
193pub fn get_default_outcome_sharing(session_id: String) -> Result<serde_json::Value, String> {
194    let state = crate::state::APP_STATE.get().unwrap();
195    let storage = state.config.lock().unwrap().storage_path.clone();
196    let session = crate::chat_session::load_session(Path::new(&storage), &session_id)
197        .map_err(|e| e.to_string())?;
198    let policy = crate::chat_agents::default_outcome_sharing(session.meta.session_kind);
199    serde_json::to_value(policy).map_err(|e| e.to_string())
200}