Skip to main content

agentmux_srv/server/
work_remote.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! The Kanban's remote operations: `tasks.enqueue` and `tasks.list` on this machine's board, for an
5//! agent of another machine (SPEC_AGENTS_OPERATE_OTHER_MACHINES_2026_10_30.md ยง4.3, phase P3).
6//!
7//! The transport (`remote_ops`) has already proven the requesting machine and the request; these
8//! functions take the verified requester's name (`slug@machine`) and the typed params, and do what the
9//! same call does locally, through the same code (`work_queue::enqueue_core`, `list_items`). They never
10//! see the envelope and write no audit row; the transport does both.
11//!
12//! What differs from a local call, on purpose:
13//! - The task is asked for by that agent (`slug@machine`, kind `agent`), never by the operator, and is
14//!   not held for the operator's Accept unless the request says `review: true`.
15//! - The target is named by its slug or name and resolved here, on the machine that owns it; a name that
16//!   matches nobody, or several agents, is refused with the candidates, never guessed.
17//! - The request's `reason` isn't a parameter: it never reaches an agent (the transport keeps it for the audit).
18//! - There is no `target_group`: a group is a local idea.
19
20use serde::de::DeserializeOwned;
21use serde::Deserialize;
22use serde_json::{json, Value};
23
24use super::work_queue::{enqueue_core, list_items, EnqueueRequest, Filer};
25use super::AppState;
26
27/// Why an operation didn't run: a short snake_case `code` (the transport's `refused_reason`) and words.
28#[derive(Debug, PartialEq, Eq)]
29pub(crate) struct Failure {
30    pub code: &'static str,
31    pub message: String,
32}
33
34fn fail(code: &'static str, message: impl Into<String>) -> Failure {
35    Failure { code, message: message.into() }
36}
37
38/// The params as `T`, naming the field that is wrong or unknown.
39fn params_of<T: DeserializeOwned>(params: Value) -> Result<T, Failure> {
40    serde_json::from_value(params).map_err(|e| fail("bad_params", e.to_string()))
41}
42
43/// What `tasks.enqueue` takes: the local tool's fields, less `target_group`, `created_by` and the carried uid.
44#[derive(Debug, Deserialize)]
45#[serde(deny_unknown_fields)]
46struct EnqueueParams {
47    title: String,
48    payload: String,
49    #[serde(default)]
50    kind: String,
51    /// The agent it is for, by slug, name or uid on THIS machine. Empty: for anyone.
52    #[serde(default)]
53    target_agent: String,
54    #[serde(default)]
55    priority: i64,
56    #[serde(default)]
57    max_attempts: Option<i64>,
58    #[serde(default)]
59    not_before: Option<i64>,
60    #[serde(default)]
61    repo: Option<String>,
62    #[serde(default)]
63    hold: bool,
64    #[serde(default)]
65    review: Option<bool>,
66    /// Tasks on this machine's board it starts after, by number or id.
67    #[serde(default)]
68    after: Vec<Value>,
69    #[serde(default)]
70    first: Option<String>,
71    #[serde(default)]
72    ui_change: Option<bool>,
73    /// The board to file on, by name or slug; the default board when absent.
74    #[serde(default)]
75    board: Option<String>,
76}
77
78/// The uid of the agent here that `typed` names, or why none can be named.
79async fn target_uid(state: &AppState, typed: &str) -> Result<String, Failure> {
80    use crate::backend::name_resolution::NameResolution;
81    // The typed name is interpreted at the boundary layer, never here.
82    let resolved = super::name_resolution::resolve_typed_name(state, typed).await.map_err(|e| fail("failed", e))?;
83    match resolved {
84        NameResolution::One { uid, .. } => Ok(uid),
85        NameResolution::Ambiguous { candidates } => {
86            let names: Vec<String> = candidates.iter().map(|c| if c.slug.is_empty() { c.name.clone() } else { c.slug.clone() }).collect();
87            Err(fail("ambiguous_target", format!("\"{typed}\" names more than one agent here: {}. Name one by its slug", names.join(", "))))
88        }
89        // An agent with no stored identity can't be given a task that only it may claim.
90        NameResolution::Unidentified { .. } | NameResolution::None => Err(fail("no_such_agent", format!("no agent named \"{typed}\" on this machine"))),
91    }
92}
93
94/// `tasks.enqueue`: file a task (or, with `first`, a spec and its build) on this machine's board for one of
95/// its agents. The answer is the local call's: `{id, num}`, and `build_id`/`build_num` for a pair, with a
96/// note when the target can't work now.
97pub(crate) async fn tasks_enqueue(state: &AppState, actor: &str, params: Value) -> Result<Value, Failure> {
98    let p: EnqueueParams = params_of(params)?;
99    let target = p.target_agent.trim().to_string();
100    let target_agent_uid = if target.is_empty() { String::new() } else { target_uid(state, &target).await? };
101    let req = EnqueueRequest {
102        title: p.title,
103        payload: p.payload,
104        kind: p.kind,
105        target_agent: target,
106        target_agent_uid,
107        target_group: String::new(),
108        priority: p.priority,
109        created_by: actor.to_string(),
110        max_attempts: p.max_attempts,
111        not_before: p.not_before,
112        repo: p.repo,
113        hold: p.hold,
114        review: p.review,
115        after: p.after,
116        first: p.first,
117        ui_change: p.ui_change,
118        board: p.board,
119    };
120    let (status, axum::response::Json(body)) = enqueue_core(state, req, Filer::Remote(actor)).await;
121    if status.is_success() {
122        return Ok(body);
123    }
124    let why = body.get("error").and_then(Value::as_str).unwrap_or("the task was not filed").to_string();
125    Err(if status == axum::http::StatusCode::BAD_REQUEST { fail("bad_params", why) } else { fail("failed", why) })
126}
127
128/// What `tasks.list` takes.
129#[derive(Debug, Default, Deserialize)]
130#[serde(deny_unknown_fields)]
131struct ListParams {
132    /// open, held, claimed, blocked, review, done, failed or cancelled; all when absent.
133    #[serde(default)]
134    state: String,
135    #[serde(default)]
136    limit: Option<usize>,
137    /// A board by name or slug, or `all`; the default board when absent.
138    #[serde(default)]
139    board: Option<String>,
140}
141
142/// `tasks.list`: this machine's board, read-only: `{items: [...]}`, each with its number.
143pub(crate) fn tasks_list(state: &AppState, params: Value) -> Result<Value, Failure> {
144    tasks_list_for(state, None, params)
145}
146
147/// [`tasks_list`] for the agent `actor` (`slug@machine`), which sees only the boards whose agent list
148/// has it.
149pub(crate) fn tasks_list_for(state: &AppState, actor: Option<&str>, params: Value) -> Result<Value, Failure> {
150    // No params at all is a plain "list".
151    let p: ListParams = if params.is_null() { ListParams::default() } else { params_of(params)? };
152    let who = actor.map(|a| (a, ""));
153    let items = list_items(state, &p.state, p.limit, p.board.as_deref(), who)
154        .map_err(|e| fail(if e.starts_with("no board") { "bad_params" } else { "failed" }, e))?;
155    Ok(json!({ "items": items }))
156}
157
158#[cfg(test)]
159#[path = "work_remote_tests.rs"]
160mod tests;