Skip to main content

agentmux_srv/server/
work_delegate.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! An agent accepts or sends back a task in Review:
5//!
6//!   POST /agentmux/work/:id/accept     { auth, text? }
7//!   POST /agentmux/work/:id/send_back  { auth, text }
8//!
9//! Any agent may. The history carries the agent as the one who decided, and
10//! says so plainly when the task was its own work; it is never recorded as the
11//! operator. The caller is the agent whose signed identity (or token) verifies,
12//! never one the body names.
13
14use axum::extract::{Path, State};
15use axum::http::StatusCode;
16use axum::response::{IntoResponse, Response};
17use axum::Json;
18use serde::Deserialize;
19use serde_json::json;
20
21use agentmux_common::api_types::UiAutomationAuth;
22use agentmux_common::time::now_ms;
23
24use super::app_api::kanban::{accept_task, send_back_task, Decider};
25use super::caller::Caller;
26use super::work_tasks::resolve_id;
27use super::AppState;
28use crate::backend::kanban_delegate::{self as delegate, Refusal};
29use crate::backend::reactive::sanitize::is_sensitive_message;
30use crate::backend::reactive::types::AgentRegistration;
31use crate::backend::storage::work_board::BoardTask;
32use crate::backend::storage::work_queue::work_state;
33
34#[derive(Debug, Deserialize)]
35pub(crate) struct DecisionRequest {
36    #[serde(flatten)]
37    auth: UiAutomationAuth,
38    /// `accept`: an optional note. `send_back`: the reason, which goes to the holder.
39    #[serde(default)]
40    text: String,
41}
42
43#[derive(Clone, Copy, PartialEq, Eq)]
44enum Verb {
45    Accept,
46    SendBack,
47}
48
49impl Verb {
50    fn audit_action(self) -> &'static str {
51        match self {
52            Verb::Accept => "kanban.accept",
53            Verb::SendBack => "kanban.send_back",
54        }
55    }
56}
57
58pub(crate) async fn handle_work_accept(
59    State(state): State<AppState>,
60    Path(id): Path<String>,
61    caller: Option<axum::Extension<Caller>>,
62    Json(req): Json<DecisionRequest>,
63) -> Response {
64    decide(&state, caller.as_deref(), &id, req, Verb::Accept).await
65}
66
67pub(crate) async fn handle_work_send_back(
68    State(state): State<AppState>,
69    Path(id): Path<String>,
70    caller: Option<axum::Extension<Caller>>,
71    Json(req): Json<DecisionRequest>,
72) -> Response {
73    decide(&state, caller.as_deref(), &id, req, Verb::SendBack).await
74}
75
76fn refused(r: &Refusal) -> Response {
77    (StatusCode::FORBIDDEN, Json(json!({ "error": r.words, "code": r.code }))).into_response()
78}
79
80/// The task is the caller's own: it holds it, or handed it in.
81fn is_own_work(t: &BoardTask, reg: &AgentRegistration, events: &[crate::backend::storage::work_board::WorkEvent]) -> bool {
82    let uid = reg.uid.as_deref().unwrap_or("");
83    let holds = if t.item.claimed_by_uid.is_empty() {
84        t.item.claimed_by.eq_ignore_ascii_case(&reg.agent_id)
85    } else {
86        !uid.is_empty() && t.item.claimed_by_uid == uid
87    };
88    holds || events.iter().any(|e| e.kind == "submitted" && e.actor.eq_ignore_ascii_case(&reg.agent_id))
89}
90
91async fn decide(state: &AppState, caller: Option<&Caller>, id: &str, req: DecisionRequest, verb: Verb) -> Response {
92    let block_id = match super::ui_handlers::verified_block_id(state, caller, &req.auth) {
93        Ok(b) => b,
94        Err(e) => return (StatusCode::UNAUTHORIZED, Json(json!({ "error": e }))).into_response(),
95    };
96    let regs = state.reactive_handler.list_agents();
97    let Some(reg) = regs.iter().find(|r| r.block_id == block_id).cloned() else {
98        return (StatusCode::UNAUTHORIZED, Json(json!({ "error": "your pane isn't registered with AgentMux" }))).into_response();
99    };
100    let task_id = resolve_id(state, id);
101    let task = match state.work_store.work_board_get(&task_id) {
102        Ok(Some(t)) => t,
103        Ok(None) => return (StatusCode::NOT_FOUND, Json(json!({ "error": "no such task" }))).into_response(),
104        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": e.to_string() }))).into_response(),
105    };
106    // A task on a board whose agent list leaves this agent out looks like one that doesn't exist.
107    if let Ok(Some((board, _))) = state.work_store.work_task_board(&task.item.id) {
108        if !board.visible_to(&reg.agent_id, reg.uid.as_deref().unwrap_or("")) {
109            return (StatusCode::NOT_FOUND, Json(json!({ "error": "no such task" }))).into_response();
110        }
111    }
112    let num = task.card.num;
113    let events = state.work_store.work_events(&task.item.id, 200).unwrap_or_default();
114    let own_work = is_own_work(&task, &reg, &events);
115
116    let outcome = check(&task, &req.text, verb);
117    // One audit line per call, a refusal too: who, which task and why not.
118    let request_id = uuid::Uuid::new_v4().to_string();
119    let note = format!("{}{}", task.card.name(), if own_work { " (its own work)" } else { "" });
120    match &outcome {
121        Err(r) => {
122            tracing::info!(agent = %reg.agent_id, task = num, why = r.code, "kanban: an agent's decision was refused");
123            state.reactive_handler.log_fleet_action_audit(
124                Some(&reg.agent_id),
125                &reg.agent_id,
126                &block_id,
127                verb.audit_action(),
128                false,
129                Some(r.code),
130                &request_id,
131                Some(&note),
132            );
133            refused(r)
134        }
135        Ok(()) => {
136            // The history names the agent by its slug, as the other Kanban moves do.
137            let slug = reg.uid.as_deref().and_then(|u| state.mstore.agent_names_by_id(u).ok().flatten()).map(|r| r.slug);
138            let by = Decider::agent(slug.as_deref().unwrap_or(&reg.agent_id), own_work);
139            let text = super::work_tasks::clean(&req.text);
140            let now = now_ms();
141            let done = match verb {
142                Verb::Accept => accept_task(state, &task, &by, &text, now),
143                Verb::SendBack => send_back_task(state, &regs, &task, &by, &text, now).await,
144            };
145            state.reactive_handler.log_fleet_action_audit(
146                Some(&reg.agent_id),
147                &reg.agent_id,
148                &block_id,
149                verb.audit_action(),
150                done.is_ok(),
151                done.as_ref().err().map(String::as_str),
152                &request_id,
153                Some(&note),
154            );
155            tracing::info!(agent = %reg.agent_id, task = num, action = verb.audit_action(), ok = done.is_ok(), "kanban: an agent decided");
156            super::work_queue::publish_changed(state);
157            match done {
158                Ok(v) => Json(v).into_response(),
159                Err(e) => (StatusCode::CONFLICT, Json(json!({ "error": e }))).into_response(),
160            }
161        }
162    }
163}
164
165/// The checks, in order; the first that fails answers.
166fn check(task: &BoardTask, text: &str, verb: Verb) -> Result<(), Refusal> {
167    if task.item.state != work_state::REVIEW {
168        return Err(delegate::not_in_review(&task.card.name(), &task.item.state));
169    }
170    if verb == Verb::SendBack && text.trim().is_empty() {
171        return Err(Refusal { code: "reason_required", words: "send_back needs a reason: it goes to the task's holder.".to_string() });
172    }
173    // A credential in the text is refused, not stored.
174    if is_sensitive_message(text) {
175        return Err(delegate::sensitive_quote());
176    }
177    Ok(())
178}
179
180#[cfg(test)]
181#[path = "work_delegate_tests.rs"]
182mod tests;