Skip to main content

agentmux_srv/server/
job_actions.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! The job actions that need the server: `task` files a task on the Kanban
5//! as `kanban.act` does, `spawn` opens a worker through the spawn path
6//! (docs/specs/SPEC_JOBS_AND_TEMPLATES_2026_10_24.md ยง5.1 "Actions").
7//! `drone` starts a Drone run. `message` is the scheduler's own delivery.
8
9use std::sync::Arc;
10
11use agentmux_common::time::now_ms;
12
13use crate::backend::cron::ActionOutcome;
14use crate::backend::jobs;
15use crate::backend::jobs::definition::Action;
16use crate::backend::reactive::sanitize::{neutralize_markers, sanitize_message};
17use crate::backend::storage::cron::CronJob;
18use crate::backend::storage::store::Store;
19use crate::backend::storage::work_board::{requested, NewCard, WorkEvent};
20use crate::backend::storage::work_queue::{work_state, WorkItem};
21
22use super::AppState;
23
24/// Who files a job's task and who its history says did.
25const FILED_BY: &str = "jobs";
26
27/// The task's `kind`.
28const TASK_KIND: &str = "job";
29
30/// Run `task`, `spawn` and `drone` actions in this server from now on.
31pub(crate) fn install(state: &AppState) {
32    let st = state.clone();
33    state.cron_scheduler.install_actions(Arc::new(move |job, run_id| {
34        let st = st.clone();
35        Box::pin(async move { run_action(&st, job, &run_id).await })
36    }));
37}
38
39/// Carry out `job`'s action for run `run_id`.
40pub(crate) async fn run_action(state: &AppState, job: CronJob, run_id: &str) -> ActionOutcome {
41    match serde_json::from_value::<Action>(job.action.clone()) {
42        Ok(Action::Task { title, payload, target }) => {
43            let store = super::cron::work_store(state);
44            let target = target_of(state, &target);
45            match file_task(&store, &job, run_id, &title, &payload, target) {
46                Ok((work_id, num)) => ActionOutcome::Filed { work_id, num },
47                Err(e) => ActionOutcome::Failed(format!("couldn't file the task: {e}")),
48            }
49        }
50        Ok(Action::Spawn { leader, brief, model, account, keep_worker }) => {
51            // A spawn spends until someone stops it: it runs only for a job
52            // the operator created (their creating it is the approval).
53            if !operator_made(&job) {
54                return ActionOutcome::Failed("a spawn job runs only when the operator created it".to_string());
55            }
56            let (model, account) = (Some(model).filter(|m| !m.is_empty()), Some(account).filter(|a| !a.is_empty()));
57            let leader_name = state.mstore.agent_def_get(&leader).ok().flatten().map(|d| d.name).unwrap_or_default();
58            let brief_text = worker_brief(&leader_name, &brief);
59            match super::app_api::agent_spawn::spawn_for_job(state, &leader, &brief_text, model, account).await {
60                Ok(w) => ActionOutcome::Spawned { block_id: w.block_id, def_id: w.agent_id, slug: w.message_to, brief: brief_text, keep: keep_worker },
61                Err(e) => ActionOutcome::Failed(e),
62            }
63        }
64        Ok(Action::Drone { drone_id }) => {
65            // A drone run can spend (its Agent blocks) and a timer repeats it. Until
66            // an agent's drone job gets a notice with a veto window and run limits,
67            // only the person's runs (a temporary gate, not a rule).
68            if !operator_made(&job) {
69                return ActionOutcome::Failed("a drone job made by an agent doesn't run yet (temporary: its Agent blocks spend, and agent-made drone jobs get a notice with a veto window and run limits in the next change). Ask the person to create it in the Jobs tab".to_string());
70            }
71            if run_id.is_empty() {
72                return ActionOutcome::Failed("a drone job runs only with a ledger row to follow it".to_string());
73            }
74            let trigger = match drone_trigger(state, &job, run_id) {
75                Ok(trigger) => trigger,
76                Err(e) => return ActionOutcome::Failed(e),
77            };
78            let cap = state.cron_scheduler.runs().map(|l| l.run_cap_usd(&job));
79            match super::drone_handlers::start_job_drone_run(state, &drone_id, trigger, (run_id, cap)).await {
80                Ok(_) => ActionOutcome::Drone,
81                Err(e) => ActionOutcome::Failed(e),
82            }
83        }
84        Ok(other) => ActionOutcome::Failed(format!("action kind {} has nothing to run here", other.kind())),
85        Err(e) => ActionOutcome::Failed(format!("the job's action doesn't read: {e}")),
86    }
87}
88
89/// What a job hands the drone it runs, read as `{{trigger.*}}`: how the run
90/// started (`schedule`, `manual`, `retry`, `event`), the job, and the slot it was due.
91///
92/// For an event's run it is the event's own fields (`jobs::RunLedger::event_input`) with those keys set on top, so a
93/// source's field never stands in for `kind`, `job`, `run_id` or `fired_at_ms`. The event's data is kept with the run
94/// (`db_job_event_inputs`) from the fire to here, through a delay, a wait for its turn, a retry and a restart. A run
95/// whose data is no longer there (it aged out, or could not be read) fails saying so, not running on an empty input.
96fn drone_trigger(state: &AppState, job: &CronJob, run_id: &str) -> Result<serde_json::Value, String> {
97    let ledger = state.cron_scheduler.runs();
98    let run = ledger.and_then(|l| l.store().job_run_get(run_id).ok().flatten());
99    let kind = run.as_ref().map_or(jobs::TRIGGER_MANUAL, |r| r.trigger.as_str());
100    let mut fields = serde_json::Map::new();
101    // An event's run, and a retry of it, read the event: never start one on an empty input.
102    let of_event = kind == jobs::TRIGGER_EVENT || run.as_ref().is_some_and(|r| r.links["from_event"] == serde_json::json!(true));
103    if of_event {
104        match ledger.and_then(|l| l.event_input(run_id)) {
105            Some(serde_json::Value::Object(input)) => fields = input,
106            Some(other) => {
107                fields.insert("value".to_string(), other);
108            }
109            None => return Err("the event's data is no longer available, so this run didn't start".to_string()),
110        }
111    }
112    fields.insert("kind".to_string(), serde_json::json!(kind));
113    fields.insert("job".to_string(), serde_json::json!({ "id": job.id, "name": job.name }));
114    fields.insert("run_id".to_string(), serde_json::json!(run_id));
115    fields.insert("scheduled_for_ms".to_string(), serde_json::json!(run.as_ref().and_then(|r| r.scheduled_for_ms)));
116    fields.insert("fired_at_ms".to_string(), serde_json::json!(now_ms()));
117    Ok(serde_json::Value::Object(fields))
118}
119
120/// Whether the operator created `job`: it carries no agent's UID.
121pub(crate) fn operator_made(job: &CronJob) -> bool {
122    job.created_by == jobs::BY_OPERATOR && job.created_by_uid.is_empty()
123}
124
125/// The agent a task is for, `(name, uid)`; none for the backlog.
126pub(crate) fn target_of(state: &AppState, target: &str) -> (String, String) {
127    let target = target.trim();
128    if target.is_empty() {
129        return (String::new(), String::new());
130    }
131    match state.mstore.agent_def_get(target) {
132        Ok(Some(def)) => (def.slug, target.to_string()),
133        _ => (target.to_string(), String::new()),
134    }
135}
136
137/// The worker's first message: who it reports to, then the brief. As the
138/// `Agents` tool sends it, naming the tool exactly.
139pub(crate) fn worker_brief(leader: &str, brief: &str) -> String {
140    let brief = neutralize_markers(&sanitize_message(brief));
141    format!(
142        "You are a worker of {leader}, started to do the task below. Report to {leader} with the agentmux \
143         MCP server's Message tool (mcp__agentmux__Message in Claude Code; action \"send\", to \"{leader}\"), \
144         never a built-in SendMessage, when you finish, get stuck, or need a decision.\n\n{brief}"
145    )
146}
147
148/// File the job's task, as `kanban.act` `create` does: the queue row, its
149/// card (no review: the task isn't the operator's to accept), and its first
150/// history line, which names the job and the run. Returns its id and number.
151pub(crate) fn file_task(
152    store: &Store,
153    job: &CronJob,
154    run_id: &str,
155    title: &str,
156    payload: &str,
157    target: (String, String),
158) -> Result<(String, i64), crate::backend::storage::StoreError> {
159    let first_line = format!("Filed by the job \"{}\" (job {}, run {run_id}).", crate::server::work_tasks::clean(&job.name), job.id);
160    file_task_as(store, FILED_BY, TASK_KIND, title, payload, target, &first_line)
161}
162
163/// File a task for an automation, as `kanban.act` `create` does: the queue
164/// row, its card (no review: the task isn't the operator's to accept) and its
165/// first history line. `filed_by` is who the history says did it, `kind` the
166/// task's tag, and `first_line` the history's first line. Returns its id and number.
167pub(crate) fn file_task_as(
168    store: &Store,
169    filed_by: &str,
170    kind: &str,
171    title: &str,
172    payload: &str,
173    target: (String, String),
174    first_line: &str,
175) -> Result<(String, i64), crate::backend::storage::StoreError> {
176    file_task_by(store, filed_by, "", kind, title, payload, target, first_line)
177}
178
179/// [`file_task_as`], with the task's `created_by_uid` set to `filed_by_uid`: a tag the code that filed it can find it
180/// by later (a drone's Task block, to add a note only to a task that drone filed). Nothing authorises on it.
181#[allow(clippy::too_many_arguments)]
182pub(crate) fn file_task_by(
183    store: &Store,
184    filed_by: &str,
185    filed_by_uid: &str,
186    kind: &str,
187    title: &str,
188    payload: &str,
189    (target, target_uid): (String, String),
190    first_line: &str,
191) -> Result<(String, i64), crate::backend::storage::StoreError> {
192    let now = now_ms();
193    let item = WorkItem {
194        id: uuid::Uuid::new_v4().to_string(),
195        title: crate::server::work_tasks::clean(title),
196        payload: crate::server::work_tasks::payload_text(payload).unwrap_or_else(|_| {
197            crate::backend::reactive::sanitize::sanitize_text(&payload.chars().take(crate::server::work_tasks::MAX_PAYLOAD).collect::<String>())
198        }),
199        kind: kind.to_string(),
200        target_agent: target,
201        target_group: String::new(),
202        priority: 0,
203        state: String::new(),
204        claimed_by: String::new(),
205        target_agent_uid: target_uid,
206        claimed_by_uid: String::new(),
207        claim_expires: None,
208        attempts: 0,
209        max_attempts: 3,
210        created_by: filed_by.to_string(),
211        created_by_uid: filed_by_uid.to_string(),
212        created_at: now,
213        updated_at: now,
214        not_before: None,
215        result: String::new(),
216    };
217    store.work_queue_enqueue(&item)?;
218    let card = NewCard {
219        review_required: false,
220        requested_by: filed_by.to_string(),
221        requested_by_kind: requested::OTHER.to_string(),
222        filed_by: filed_by.to_string(),
223        ..Default::default()
224    };
225    let num = store.work_card_create(&item.id, &card, now)?;
226    let event = WorkEvent {
227        work_id: item.id.clone(),
228        at: now,
229        actor: filed_by.to_string(),
230        actor_kind: "system".to_string(),
231        kind: "created".to_string(),
232        to_state: work_state::OPEN.to_string(),
233        body: first_line.to_string(),
234        ..Default::default()
235    };
236    store.work_event_add(&event)?;
237    Ok((item.id, num))
238}