Skip to main content

agentmux_srv/server/app_api/
jobs_edit.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! The Jobs tab's editor RPCs (docs/specs/SPEC_JOBS_AND_TEMPLATES_2026_10_24.md
5//! §3.3, §5.1 "Dry run", §5.2, §5.4):
6//!
7//! - `jobs.get`: one job's definition, for Edit and Clone.
8//! - `jobs.save`: create a job, or edit one, from a definition. The
9//!   operator's own window only (`operator_only`): it may start workers
10//!   (`spawn`), raise a cap and confirm a job on a provider that reports no
11//!   cost, which nothing else can. It goes through the same create and edit
12//!   code as the Schedule routes, as the operator.
13//! - `jobs.dryrun`: what a definition (or a stored job) would do, without
14//!   starting an agent.
15//! - `jobs.templates.update_diff`: what accepting a template's newer version
16//!   would change in a job. Accepting is a `jobs.save` that names it.
17
18use std::sync::Arc;
19
20use axum::http::StatusCode;
21use chrono::TimeZone;
22use serde::{Deserialize, Serialize};
23use serde_json::{Map, Value};
24
25use agentmux_common::time::now_ms;
26
27use crate::backend::cron::schedule::{parse_tz, JobSchedule};
28use crate::backend::jobs::definition::{Action, Check, JobDefinition};
29use crate::backend::jobs::from_template::{self, TemplateUpdateDiff};
30use crate::backend::jobs::{caps, policy};
31use crate::backend::rpc::engine::WshRpcEngine;
32use crate::backend::rpc_types::*;
33use crate::backend::storage::cron::CronJob;
34use crate::server::cron::{create_job, jobs_store, patch_job, runnable_yet};
35use crate::server::job_caps::{self, Origin, NO_COST_TIMEOUT_MINUTES};
36
37use super::AppState;
38
39/// How many fire times a dry run lists.
40const DRY_RUN_FIRES: usize = 5;
41/// A definition's fields an edit can't change: srv sets them.
42const FIXED_FIELDS: [&str; 3] = ["id", "jobVersion", "created_by"];
43
44#[derive(Debug, Clone, Deserialize, ts_rs::TS)]
45#[ts(export, export_to = "../../../frontend/types/rpc/")]
46pub struct JobsGetRequest {
47    pub job_id: String,
48}
49
50#[derive(Debug, Clone, Serialize, ts_rs::TS)]
51#[ts(export, export_to = "../../../frontend/types/rpc/")]
52pub struct JobsGetResult {
53    /// The job's definition (`schema/agentmux-job.v1.schema.json`), as stored.
54    #[ts(type = "Record<string, unknown>")]
55    pub definition: Value,
56}
57
58#[derive(Debug, Clone, Deserialize, ts_rs::TS)]
59#[ts(export, export_to = "../../../frontend/types/rpc/")]
60pub struct JobsSaveRequest {
61    /// The job to edit; a new job when absent.
62    #[serde(default)]
63    #[ts(optional)]
64    pub job_id: Option<String>,
65    /// The job definition. On an edit, only the fields that differ from the
66    /// stored job count, so a job kept as it was isn't refused for a rule
67    /// newer than it. One that names a template is made from it.
68    #[ts(type = "Record<string, unknown>")]
69    pub definition: Value,
70    /// Confirms a job whose agent's provider reports no cost (§5.3).
71    #[serde(default)]
72    #[ts(optional)]
73    pub confirm_no_cost: Option<bool>,
74    /// Confirms turning on a drone job after its prompt (what it changes outside AgentMux, the credentials it uses).
75    #[serde(default)]
76    #[ts(optional)]
77    pub confirm_turn_on: Option<bool>,
78}
79
80#[derive(Debug, Clone, Default, Serialize, ts_rs::TS)]
81#[ts(export, export_to = "../../../frontend/types/rpc/")]
82pub struct JobsSaveResult {
83    pub ok: bool,
84    /// The job created or edited.
85    pub job_id: String,
86    /// What srv changed or filled in, in words.
87    pub notes: Vec<String>,
88    /// The job needs the operator's confirmation first: `no_cost`.
89    pub needs_confirmation: Option<String>,
90    /// The provider that reports no cost, with `needs_confirmation`.
91    pub provider: Option<String>,
92    /// Why the confirmation is needed, in words.
93    pub error: Option<String>,
94    /// With `needs_confirmation: turn_on`: what turning the drone on lets it do, one line each.
95    pub lines: Vec<String>,
96}
97
98#[derive(Debug, Clone, Deserialize, ts_rs::TS)]
99#[ts(export, export_to = "../../../frontend/types/rpc/")]
100pub struct JobsDryRunRequest {
101    /// A stored job, alone or with the edits `definition` makes to it.
102    #[serde(default)]
103    #[ts(optional)]
104    pub job_id: Option<String>,
105    #[serde(default)]
106    #[ts(optional, type = "Record<string, unknown>")]
107    pub definition: Option<Value>,
108}
109
110#[derive(Debug, Clone, Serialize, ts_rs::TS)]
111#[ts(export, export_to = "../../../frontend/types/rpc/")]
112pub struct DryRunFire {
113    #[ts(type = "number")]
114    pub at_ms: i64,
115    /// In the job's time zone: `Mon 2026-10-26 06:00 EDT`.
116    pub local: String,
117}
118
119/// The figures that would apply (§5.3), in dollars.
120#[derive(Debug, Clone, Serialize, ts_rs::TS)]
121#[ts(export, export_to = "../../../frontend/types/rpc/")]
122pub struct DryRunCaps {
123    pub run_usd: f64,
124    pub day_usd: f64,
125    pub account_day_usd: f64,
126    pub messages_per_day: u32,
127    /// An agent's higher figures would be held to the defaults.
128    pub clamped: bool,
129}
130
131#[derive(Debug, Clone, Serialize, ts_rs::TS)]
132#[ts(export, export_to = "../../../frontend/types/rpc/")]
133pub struct DryRunSecret {
134    pub name: String,
135    /// The Vault entry it names (never a value).
136    pub vault: String,
137}
138
139#[derive(Debug, Clone, Default, Serialize, ts_rs::TS)]
140#[ts(export, export_to = "../../../frontend/types/rpc/")]
141pub struct JobsDryRunResult {
142    /// The definition is one a save would accept.
143    pub ok: bool,
144    /// Why it isn't, in words.
145    pub error: Option<String>,
146    pub name: String,
147    /// `message`, `task` or `spawn`.
148    pub action_kind: String,
149    /// Who it goes to: the message's target, the task's, the spawn's leader.
150    pub target: String,
151    /// The brief as the agent would get it (a task's payload).
152    pub brief: String,
153    /// The trigger's time zone.
154    pub tz: String,
155    pub fires: Vec<DryRunFire>,
156    pub caps: Option<DryRunCaps>,
157    pub outputs: Vec<String>,
158    /// What it declares. A dry run can't see the Vault's grants for a run:
159    /// each is made, or refused, when the run first uses it.
160    pub secrets: Vec<DryRunSecret>,
161    /// The concurrency group its runs would wait in.
162    pub group: Option<String>,
163    /// Things to know before saving, in words.
164    pub notes: Vec<String>,
165}
166
167#[derive(Debug, Clone, Deserialize, ts_rs::TS)]
168#[ts(export, export_to = "../../../frontend/types/rpc/")]
169pub struct JobsUpdateDiffRequest {
170    pub job_id: String,
171}
172
173pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
174    let s = state.clone();
175    engine.register_typed(COMMAND_JOBS_GET, move |req: JobsGetRequest, _ctx| {
176        let s = s.clone();
177        async move { get(&s, &req.job_id).map(|d| JobsGetResult { definition: d }) }
178    });
179    let s = state.clone();
180    engine.register_typed(COMMAND_JOBS_SAVE, move |req: JobsSaveRequest, ctx| {
181        let s = s.clone();
182        async move { save(&s, req, &ctx) }
183    });
184    let s = state.clone();
185    engine.register_typed(COMMAND_JOBS_DRYRUN, move |req: JobsDryRunRequest, ctx| {
186        let s = s.clone();
187        async move { dry_run(&s, req, &ctx) }
188    });
189    let s = state.clone();
190    engine.register_typed(COMMAND_JOBS_TEMPLATES_UPDATE_DIFF, move |req: JobsUpdateDiffRequest, _ctx| {
191        let s = s.clone();
192        async move { update_diff(&s, &req.job_id) }
193    });
194}
195
196fn stored_job(state: &AppState, id: &str) -> Result<CronJob, String> {
197    let store = jobs_store(state).ok_or("the shared store isn't available")?;
198    store.cron_get(id).map_err(|e| e.to_string())?.ok_or_else(|| "job not found".to_string())
199}
200
201fn stored(state: &AppState, id: &str) -> Result<JobDefinition, String> {
202    stored_job(state, id).map(|job| JobDefinition::from_job(&job))
203}
204
205fn get(state: &AppState, id: &str) -> Result<Value, String> {
206    serde_json::to_value(stored(state, id)?).map_err(|e| e.to_string())
207}
208
209/// The fields of `sent` that differ from the stored `before`, without the
210/// ones srv sets.
211fn changed_fields(before: &JobDefinition, sent: &Value) -> Result<Map<String, Value>, String> {
212    let sent = sent.as_object().ok_or("a job definition is a JSON object")?;
213    let current = serde_json::to_value(before).map_err(|e| e.to_string())?;
214    Ok(sent
215        .iter()
216        .filter(|(k, v)| !FIXED_FIELDS.contains(&k.as_str()) && current.get(k.as_str()) != Some(*v))
217        .map(|(k, v)| (k.clone(), v.clone()))
218        .collect())
219}
220
221fn save(state: &AppState, req: JobsSaveRequest, ctx: &RpcContext) -> Result<JobsSaveResult, String> {
222    ctx.operator_only("only the operator creates or edits a job here")?;
223    let origin = Origin { from_host: true, confirm_no_cost: req.confirm_no_cost == Some(true), confirm_turn_on: req.confirm_turn_on == Some(true) };
224    let (status, axum::Json(body)) = match req.job_id.as_deref().filter(|id| !id.is_empty()) {
225        None => create_job(state, None, req.definition, origin),
226        Some(id) => {
227            let fields = changed_fields(&stored(state, id)?, &req.definition)?;
228            patch_job(state, None, id, Value::Object(fields), origin)
229        }
230    };
231    saved(status, &body)
232}
233
234/// A create's or edit's answer as the RPC's: the job it made, or why not.
235fn saved(status: StatusCode, body: &Value) -> Result<JobsSaveResult, String> {
236    let error = body.get("error").and_then(Value::as_str).map(str::to_string);
237    if let Some(kind) = body.get("needs_confirmation").and_then(Value::as_str) {
238        let provider = body.get("provider").and_then(Value::as_str).map(str::to_string);
239        let lines = body.get("lines").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();
240        return Ok(JobsSaveResult { needs_confirmation: Some(kind.to_string()), provider, error, lines, ..Default::default() });
241    }
242    if !status.is_success() {
243        return Err(error.unwrap_or_else(|| format!("refused ({status})")));
244    }
245    let job_id = body.pointer("/job/id").and_then(Value::as_str).unwrap_or("").to_string();
246    let notes = body.get("notes").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();
247    Ok(JobsSaveResult { ok: true, job_id, notes, ..Default::default() })
248}
249
250fn update_diff(state: &AppState, job_id: &str) -> Result<TemplateUpdateDiff, String> {
251    Ok(from_template::update_diff(&stored(state, job_id)?))
252}
253
254// ── Dry run ─────────────────────────────────────────────────────────────────
255
256/// The definition a dry run reads and whether its trigger or action is being
257/// set (the rules a save would check), from the stored job and/or the sent
258/// definition, with its template applied.
259fn dry_run_input(state: &AppState, req: &JobsDryRunRequest) -> Result<(Value, bool, Option<JobDefinition>), String> {
260    let before = req.job_id.as_deref().filter(|id| !id.is_empty()).map(|id| stored(state, id)).transpose()?;
261    match (&before, &req.definition) {
262        (None, None) => Err("which job? give job_id or a definition".to_string()),
263        (None, Some(sent)) => {
264            let mut value = sent.clone();
265            from_template::apply(&mut value, None)?;
266            Ok((value, true, None))
267        }
268        (Some(b), None) => Ok((serde_json::to_value(b).map_err(|e| e.to_string())?, false, before)),
269        (Some(b), Some(sent)) => {
270            let fields = changed_fields(b, sent)?;
271            let mut merged = serde_json::to_value(b).map_err(|e| e.to_string())?;
272            for (k, v) in &fields {
273                merged[k.as_str()] = v.clone();
274            }
275            if from_template::edit_needs_render(&fields, b) {
276                from_template::apply(&mut merged, b.template.as_ref())?;
277            }
278            let fresh = fields.contains_key("trigger") || fields.contains_key("action");
279            Ok((merged, fresh, before))
280        }
281    }
282}
283
284fn target_of(action: &Action) -> String {
285    match action {
286        Action::Message { to, .. } => to.clone(),
287        Action::Task { target, .. } => target.clone(),
288        Action::Spawn { leader, .. } => leader.clone(),
289        Action::Drone { .. } => String::new(),
290    }
291}
292
293fn brief_of(action: &Action) -> String {
294    match action {
295        Action::Message { brief, .. } | Action::Spawn { brief, .. } => brief.clone(),
296        Action::Task { payload, .. } => payload.clone(),
297        Action::Drone { .. } => String::new(),
298    }
299}
300
301/// `at_ms` as the zone `tz` reads it: `Mon 2026-10-26 06:00 EDT`.
302fn local_time(tz: &chrono_tz::Tz, at_ms: i64) -> String {
303    tz.timestamp_millis_opt(at_ms).single().map(|t| t.format("%a %Y-%m-%d %H:%M %Z").to_string()).unwrap_or_default()
304}
305
306fn dry_run(state: &AppState, req: JobsDryRunRequest, ctx: &RpcContext) -> Result<JobsDryRunResult, String> {
307    let refused = |error: String| JobsDryRunResult { error: Some(error), ..Default::default() };
308    let (value, fresh, before) = match dry_run_input(state, &req) {
309        Ok(input) => input,
310        Err(e) => return Ok(refused(e)),
311    };
312    let now = now_ms();
313    let def = match JobDefinition::parse(&value, Check { fresh, now_ms: now }).and_then(|d| runnable_yet(&d).map(|()| d)) {
314        Ok(def) => def,
315        Err(e) => return Ok(refused(e)),
316    };
317    let mut notes = Vec::new();
318    let mut job = CronJob {
319        id: before.as_ref().map(|b| b.id.clone()).filter(|id| !id.is_empty()).unwrap_or_else(|| "dry-run".to_string()),
320        created_at: now / 1000,
321        ..Default::default()
322    };
323    def.apply_to(&mut job, &|to| (to.to_string(), String::new()));
324    let tz = parse_tz(&job.tz).unwrap_or(chrono_tz::Tz::UTC);
325    let fires: Vec<DryRunFire> = match JobSchedule::of(&job) {
326        Ok(schedule) => schedule.after(now).take(DRY_RUN_FIRES).map(|at_ms| DryRunFire { at_ms, local: local_time(&tz, at_ms) }).collect(),
327        Err(e) => return Ok(refused(e)),
328    };
329    if fires.is_empty() && !matches!(def.trigger, crate::backend::jobs::definition::Trigger::Manual) {
330        notes.push("this trigger has no time ahead: it won't fire".to_string());
331    }
332
333    // The caps that would apply: an agent's higher figures are held to the
334    // defaults (the operator's window keeps them).
335    let limits = job_caps::limits(state);
336    let mut policy_caps = def.policy.caps.clone();
337    let mut clamped = false;
338    if !ctx.agent_id.is_empty() {
339        let (kept, clamp_notes) = caps::clamp_to_defaults(policy_caps, &limits, before.as_ref().and_then(|b| b.policy.caps.as_ref()));
340        clamped = !clamp_notes.is_empty();
341        notes.extend(clamp_notes);
342        policy_caps = kept;
343    }
344    let eff = caps::effective(policy_caps.as_ref(), &limits);
345    if let Some(provider) = job_caps::action_provider(state, &def.action).filter(|p| !p.is_empty() && !caps::reports_cost(p)) {
346        let timeout = def.policy.timeout_minutes.unwrap_or(NO_COST_TIMEOUT_MINUTES);
347        notes.push(format!(
348            "its agent runs on {provider}, which doesn't report what a run costs: the spending caps can't stop it, only its {timeout}-minute timeout does"
349        ));
350    }
351    if matches!(def.action, Action::Spawn { .. }) {
352        notes.push("it starts a worker for each run; a dry run starts none".to_string());
353    }
354    Ok(JobsDryRunResult {
355        ok: true,
356        error: None,
357        name: def.name.trim().to_string(),
358        action_kind: def.action.kind().to_string(),
359        target: target_of(&def.action),
360        brief: brief_of(&def.action),
361        tz: tz.name().to_string(),
362        fires,
363        caps: Some(DryRunCaps {
364            run_usd: eff.run_usd,
365            day_usd: eff.day_usd,
366            account_day_usd: limits.account_day_usd,
367            messages_per_day: eff.messages_per_day,
368            clamped,
369        }),
370        outputs: def.outputs.clone(),
371        secrets: def.secrets.iter().map(|s| DryRunSecret { name: s.name.clone(), vault: s.vault.clone() }).collect(),
372        group: policy::group_of(&job),
373        notes,
374    })
375}
376
377#[cfg(test)]
378#[path = "jobs_edit_tests.rs"]
379mod tests;