Skip to main content

agentmux_mcp/tools/
work.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The shared work queue (Work*).
5
6use super::*;
7
8pub(super) async fn call(name: &str, arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
9    // A bare number with a board named is that board's: `work#12`.
10    let scoped_args;
11    let arguments = match scoped(name, arguments)? {
12        Some(a) => {
13            scoped_args = a;
14            &scoped_args
15        }
16        None => arguments,
17    };
18    match name {
19        "WorkBoards" | "WorkBoardCreate" | "WorkBoardEdit" | "WorkBoardArchive" | "WorkBoardUnarchive" | "WorkBoardDefault"
20        | "WorkBoardDelete" | "WorkBoardCancelDelete" => run_work_boards(name, arguments, cx).await,
21        "WorkEnqueue" => run_work_enqueue(arguments, cx).await,
22        "WorkClaim" => run_work_claim(arguments, cx).await,
23        "WorkUpdate" | "WorkAsk" | "WorkSubmit" => run_work_update(name, arguments, cx).await,
24        "WorkHeartbeat" | "WorkComplete" | "WorkRelease" => run_work_heartbeat(name, arguments, cx).await,
25        "WorkHold" | "WorkUnhold" => run_work_hold(name, arguments, cx).await,
26        "WorkAccept" | "WorkSendBack" => run_work_accept(name, arguments, cx).await,
27        "WorkEdit" | "WorkMove" | "WorkStart" | "WorkAnswer" | "WorkCancel" | "WorkReopen" | "WorkRetry" | "WorkTakeBack" | "WorkReassign" => run_work_edit(name, arguments, cx).await,
28        "WorkList" => run_work_list(arguments, cx).await,
29        "WorkGet" => run_work_get(arguments, cx).await,
30        "WorkTokens" => run_work_tokens(arguments, cx).await,
31        _ => Err(not_in_family()),
32    }
33}
34
35/// Enqueue a task. Every Work tool posts or gets /agentmux/work* on the local srv, with the same auth
36/// header as the cron tools.
37async fn run_work_enqueue(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
38    let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
39    require_agent_env(local_url, auth_key, block_id)?;
40    let title = arguments.get("title").and_then(|v| v.as_str()).filter(|s| !s.is_empty())
41        .ok_or_else(|| anyhow::anyhow!("missing required parameter: title"))?;
42    let payload = arguments.get("payload").and_then(|v| v.as_str()).filter(|s| !s.is_empty())
43        .ok_or_else(|| anyhow::anyhow!("missing required parameter: payload"))?;
44    let self_id = std::env::var("AGENTMUX_AGENT_ID").ok().filter(|s| !s.is_empty()).unwrap_or_default();
45    // Kanban §6.5: `for: "me"` files it in the caller's own backlog,
46    // to take after its current work.
47    let for_me = arguments.get("for").and_then(|v| v.as_str()).map(str::trim) == Some("me");
48    if for_me && self_id.is_empty() {
49        anyhow::bail!("for \"me\" needs AGENTMUX_AGENT_ID, which is not set");
50    }
51    let target_agent = if for_me {
52        self_id.as_str()
53    } else {
54        arguments.get("target_agent").and_then(|v| v.as_str()).unwrap_or("")
55    };
56    // Identity M3: resolve the typed target NOW, at the boundary, and
57    // carry its uid; an ambiguous name is handed back with candidates.
58    // The caller itself is its own UID.
59    let target_agent_uid = if target_agent.is_empty() {
60        None
61    } else if for_me {
62        std::env::var("AGENTMUX_AGENT_UID").ok().filter(|s| !s.is_empty())
63    } else {
64        match resolve_agent_target_at_boundary(&client, local_url, auth_key, target_agent).await? {
65            // A name nobody answers to would file a task no agent can
66            // claim (#1257): say so instead.
67            crate::identity::BoundaryResolution::NoSuchAgent(close) => anyhow::bail!(
68                "{}",
69                no_such_target(target_agent, &close)
70            ),
71            r => r.uid(),
72        }
73    };
74
75    let url = format!("{}/agentmux/work", local_url.trim_end_matches('/'));
76    let body = serde_json::json!({
77        "title": title,
78        "payload": payload,
79        "kind": arguments.get("kind").and_then(|v| v.as_str()).unwrap_or(""),
80        "target_agent": target_agent,
81        "target_agent_uid": target_agent_uid.unwrap_or_default(),
82        "target_group": arguments.get("target_group").and_then(|v| v.as_str()).unwrap_or(""),
83        "priority": arguments.get("priority").and_then(|v| v.as_i64()).unwrap_or(0),
84        "not_before": arguments.get("not_before").and_then(|v| v.as_i64()),
85        "max_attempts": arguments.get("max_attempts").and_then(|v| v.as_i64()).filter(|&n| n > 0),
86        "created_by": self_id,
87        "repo": arguments.get("repo").and_then(|v| v.as_str()),
88        "hold": arguments.get("hold").and_then(|v| v.as_bool()).unwrap_or(false),
89        "review": arguments.get("review").and_then(|v| v.as_bool()),
90        "after": arguments.get("after").filter(|a| a.is_array()).cloned().unwrap_or(Value::Array(vec![])),
91        "first": arguments.get("first").and_then(|v| v.as_str()),
92        "ui_change": arguments.get("ui_change").and_then(|v| v.as_bool()),
93        "board": arguments.get("board").and_then(|v| v.as_str()),
94    });
95    let resp = client.post(&url).header(AUTH_KEY_HEADER, auth_key).json(&body).send().await
96        .map_err(|e| anyhow::anyhow!("work enqueue request failed: {e}"))?;
97    let status = resp.status();
98    let text = resp.text().await.unwrap_or_default();
99    if !status.is_success() {
100        anyhow::bail!("Tasks enqueue failed: HTTP {status} — {text}");
101    }
102    let v = serde_json::from_str::<Value>(&text).unwrap_or(serde_json::json!({}));
103    let id = v.get("id").and_then(|x| x.as_str()).unwrap_or_default().to_string();
104    let name = task_name(&v, &id);
105    // srv adds a note when the target can't work now (limited or signed out): the task still waits.
106    let wait = v.get("note").and_then(|n| n.as_str()).map(|n| format!(" Note: {n}")).unwrap_or_default();
107    if let Some(build) = v.get("build_num").and_then(|n| n.as_i64()) {
108        let whose = if for_me { "your backlog" } else { "the queue" };
109        let build = v.get("build_ref").and_then(|r| r.as_str()).map(str::to_string).unwrap_or_else(|| format!("#{build}"));
110        return Ok(format!(
111            "Filed {name} (the spec) and {build} (the build, which starts after it) in {whose}: {title}. \
112             Tell the operator both numbers. Hand the spec's path in with Tasks update (links.doc); \
113             complete the spec when it is approved, and the build's agent is told it can start.{wait}"
114        ));
115    }
116    Ok(if for_me {
117        format!(
118            "Filed {name} in your backlog: {title}. Tell the operator its number. It waits for you: \
119             finish what you are doing, then take it with Tasks claim.{wait}"
120        )
121    } else {
122        format!("Enqueued {name}: {title}{wait}")
123    })
124}
125
126async fn run_work_claim(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
127    let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
128    require_agent_env(local_url, auth_key, block_id)?;
129    let self_id = std::env::var("AGENTMUX_AGENT_ID").ok().filter(|s| !s.is_empty())
130        .ok_or_else(|| anyhow::anyhow!("AGENTMUX_AGENT_ID is not set — cannot claim work without an agent identity"))?;
131
132    // Identity M1b/M3: carry this agent's UID (AGENTMUX_AGENT_UID, set
133    // by srv at spawn since M1a). It is the only way into a
134    // UID-addressed item. Empty when absent (pre-M1a spawn,
135    // continuation resume, quick-launch pane) — srv then takes the
136    // UID from this block's row, and counts the fallback.
137    let self_uid = std::env::var("AGENTMUX_AGENT_UID").ok().filter(|s| !s.is_empty()).unwrap_or_default();
138
139    // `id`: this task and no other (SPEC_KANBAN_AGENTS_HOLD_AND_UNHOLD_2026_10_22.md §3.3).
140    let named = if arguments.get("id").is_some() { Some(task_id(arguments)?) } else { None };
141    let url = format!("{}/agentmux/work/claim", local_url.trim_end_matches('/'));
142    let body = serde_json::json!({
143        "id": named,
144        "agent_id": self_id,
145        "agent_uid": self_uid,
146        // Identity M3: when no UID is carried, srv takes it from the
147        // row on this block rather than deriving one from the name.
148        "block_id": block_id,
149        "kind": arguments.get("kind").and_then(|v| v.as_str()),
150        "board": arguments.get("board").and_then(|v| v.as_str()),
151        "lease_ms": arguments.get("lease_ms").and_then(|v| v.as_i64()).filter(|&n| n > 0),
152        // Group membership is resolved server-side-of-this-call by the
153        // caller in the general design; the MCP path has no cheap way
154        // to know this agent's groups yet, so it claims only untargeted
155        // and self-targeted work. Group-targeted claiming arrives with
156        // the group lookup, not before — better to under-claim than to
157        // silently ignore a group restriction.
158        "groups": [],
159    });
160    let resp = client.post(&url).header(AUTH_KEY_HEADER, auth_key).json(&body).send().await
161        .map_err(|e| anyhow::anyhow!("work claim request failed: {e}"))?;
162    let status = resp.status();
163    let text = resp.text().await.unwrap_or_default();
164    if !status.is_success() {
165        anyhow::bail!("Tasks claim failed: HTTP {status} — {text}");
166    }
167    let v: Value = serde_json::from_str(&text).unwrap_or(serde_json::json!({}));
168    if !v.get("claimed").and_then(|x| x.as_bool()).unwrap_or(false) {
169        return Ok(match (named, v.get("why").and_then(|w| w.as_str())) {
170            (Some(_), Some(why)) => format!("Not claimed: {why}."),
171            (Some(n), None) => format!("Not claimed: task {n} isn't waiting for you."),
172            (None, _) => match v.get("reason").and_then(|r| r.as_str()) {
173                Some(reason) => format!("Not claimed: {reason}."),
174                None => "No work available on the queue right now.".to_string(),
175            },
176        });
177    }
178    let attempt = v.get("attempt").and_then(|x| x.as_i64()).unwrap_or(0);
179    let item = v.get("item").cloned().unwrap_or(serde_json::json!({}));
180    let id = item.get("id").and_then(|x| x.as_str()).unwrap_or("");
181    // An older srv ignores `id` and hands out the next task: give that
182    // one straight back rather than start on work nobody asked for.
183    if let Some(n) = named {
184        let num = v.get("num").and_then(|x| x.as_i64()).map(|x| x.to_string());
185        let task_ref = v.get("ref").and_then(|x| x.as_str());
186        // A srv that knows boards answers with the task's canonical `ref`, which may be spelled
187        // differently from the request (`main#1` for `#1`, a renamed board's old slug): it
188        // honoured the id. Only an older srv, which sends no ref, can hand out another task.
189        if task_ref.is_none() && id != n && num.as_deref() != Some(n) {
190            let release = format!("{}/agentmux/work/{}/release", local_url.trim_end_matches('/'), path_seg(id));
191            let _ = client
192                .post(&release)
193                .header(AUTH_KEY_HEADER, auth_key)
194                .json(&serde_json::json!({
195                    "agent_id": self_id,
196                    "attempt": attempt,
197                    "result": "Claimed by mistake: this AgentMux can't claim a task by id yet. Back to the queue untouched.",
198                }))
199                .send()
200                .await;
201            anyhow::bail!(
202                "This AgentMux can't claim a task by id yet: it handed out {} instead, which was released again. Claim without id, or ask the operator to start task {n} on you.",
203                task_name(&v, id)
204            );
205        }
206    }
207    Ok(claimed_text(&v, &item, id, attempt))
208}
209
210/// What a successful claim tells the agent: the task, its attempt number, and how to use them.
211fn claimed_text(v: &Value, item: &Value, id: &str, attempt: i64) -> String {
212    let name = task_name(v, id);
213    let title = item.get("title").and_then(|x| x.as_str()).unwrap_or("");
214    let payload = item.get("payload").and_then(|x| x.as_str()).unwrap_or("");
215    // Carry forward why a PREVIOUS holder handed this back (Codex P2 on
216    // PR #2902). WorkRelease's description promises the next claimant
217    // sees the reason; dropping it here broke that promise and let
218    // agents re-hit a known blocker with no warning. `attempt > 1` is
219    // exactly "someone has held this before me".
220    let prior = item.get("result").and_then(|x| x.as_str()).unwrap_or("");
221    let handback = if attempt > 1 && !prior.is_empty() {
222        format!(
223            "\n\nNOTE — a previous agent held this and handed it back \
224             (attempt {} of this item). Their reason: {prior}\n\
225             Read that before repeating their approach.",
226            attempt - 1
227        )
228    } else {
229        String::new()
230    };
231    let short = match v.get("ref").and_then(|r| r.as_str()) {
232        Some(r) => r.trim_start_matches('#').to_string(),
233        None => v.get("num").and_then(|n| n.as_i64()).map(|n| n.to_string()).unwrap_or_else(|| id.to_string()),
234    };
235    let after = starts_after_text(v.get("after"));
236    format!(
237        "Claimed {name} (attempt {attempt}): pass id={short} and attempt={attempt} to \
238         Tasks update, ask, submit, complete and release for this task.\n\n\
239         Title: {title}\n\n{payload}{after}{handback}"
240    )
241}
242
243async fn run_work_update(name: &str, arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
244    let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
245    require_agent_env(local_url, auth_key, block_id)?;
246    let self_id = std::env::var("AGENTMUX_AGENT_ID").ok().filter(|s| !s.is_empty())
247        .ok_or_else(|| anyhow::anyhow!("AGENTMUX_AGENT_ID is not set"))?;
248    let id = task_id(arguments)?;
249    let Some(attempt) = arguments.get("attempt").and_then(|v| v.as_i64()) else {
250        // A note or links on a task nobody holds need no claim. A task this agent holds still asks for its
251        // attempt: it is how srv rejects a stale holder, so it is never left out for the holder.
252        if name == "WorkUpdate" && is_only_a_note(arguments) && !holds_it(arguments, &self_id, cx).await {
253            return note_on_unheld(id, arguments, &self_id, cx).await;
254        }
255        return Err(missing_attempt(arguments, &self_id, cx).await);
256    };
257    let str_arg = |k: &str| arguments.get(k).and_then(|v| v.as_str()).map(str::trim).filter(|s| !s.is_empty());
258    let (segment, text) = match name {
259        "WorkAsk" => ("ask", str_arg("question").ok_or_else(|| anyhow::anyhow!("Tasks ask needs a question"))?),
260        "WorkSubmit" => (
261            "submit",
262            str_arg("result").ok_or_else(|| anyhow::anyhow!("Tasks submit needs a result: what was done, with links"))?,
263        ),
264        _ => ("update", ""),
265    };
266    let links = arguments.get("links").cloned().unwrap_or(Value::Null);
267    // Screenshots and recordings (SPEC_KANBAN_TASK_MEDIA_2026_10_25.md §3): checked, then uploaded,
268    // before the task changes, so a bad file fails the whole call.
269    let media = match (segment, send_files::files_arg(arguments)?) {
270        ("ask", Some(_)) => anyhow::bail!("Tasks ask takes no files: attach them with update or submit"),
271        (_, Some(paths)) => send_files::upload_task_media(&paths, arguments.get("captions"), cx).await?,
272        (_, None) => Vec::new(),
273    };
274    let url = format!("{}/agentmux/work/{}/{}", local_url.trim_end_matches('/'), path_seg(id), segment);
275    let body = serde_json::json!({
276        "agent_id": self_id,
277        "attempt": attempt,
278        "note": str_arg("note"),
279        "checklist": arguments.get("checklist").filter(|c| c.is_array()),
280        "pr_url": links.get("pr").and_then(|v| v.as_str()),
281        "branch": links.get("branch").and_then(|v| v.as_str()),
282        "doc": links.get("doc").and_then(|v| v.as_str()),
283        "text": text,
284        "media": media,
285        "ui_change": arguments.get("ui_change").and_then(|v| v.as_bool()),
286        "no_media_reason": str_arg("no_media_reason"),
287    });
288    let resp = client.post(&url).header(AUTH_KEY_HEADER, auth_key).json(&body).send().await
289        .map_err(|e| anyhow::anyhow!("work {segment} request failed: {e}"))?;
290    let status = resp.status();
291    let reply = resp.text().await.unwrap_or_default();
292    if status == reqwest::StatusCode::CONFLICT {
293        anyhow::bail!(
294            "This task is no longer yours, or that attempt number is old. Check it with \
295             Tasks list; claim again if you still want work."
296        );
297    }
298    if !status.is_success() {
299        anyhow::bail!("Tasks {segment} failed: HTTP {status} — {}", refusal_words(&reply));
300    }
301    let v: Value = serde_json::from_str(&reply).unwrap_or(serde_json::json!({}));
302    let attached = attached_text(&v);
303    Ok(match segment {
304        "ask" => format!(
305            "Asked: task {id} now waits for the operator, and stays yours. \
306             Their answer comes to you as a message."
307        ),
308        "submit" => format!("{}{attached}", finished_text(id, &v)),
309        _ => {
310            let reminder = v.get("reminder").and_then(Value::as_str).map(|r| format!(" {r}")).unwrap_or_default();
311            format!("Updated task {id}.{attached}{reminder}")
312        }
313    })
314}
315
316async fn run_work_heartbeat(name: &str, arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
317    let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
318    require_agent_env(local_url, auth_key, block_id)?;
319    let self_id = std::env::var("AGENTMUX_AGENT_ID").ok().filter(|s| !s.is_empty())
320        .ok_or_else(|| anyhow::anyhow!("AGENTMUX_AGENT_ID is not set"))?;
321    let id = task_id(arguments)?;
322    let Some(attempt) = arguments.get("attempt").and_then(|v| v.as_i64()) else {
323        return Err(missing_attempt(arguments, &self_id, cx).await);
324    };
325
326    let (segment, result_text) = match name {
327        "WorkHeartbeat" => ("heartbeat", String::new()),
328        "WorkComplete" if send_files::files_arg(arguments)?.is_some() => {
329            anyhow::bail!("Tasks complete takes no files: a task with media is handed in with submit")
330        }
331        "WorkComplete" => (
332            "complete",
333            // Enforced at runtime as well as in the schema (Codex P2 on
334            // PR #2902): completing with no result marks the item done
335            // forever while destroying the only record that the work
336            // happened. Better to reject the call than to accept a
337            // silent hole in the audit trail.
338            arguments
339                .get("result")
340                .and_then(|v| v.as_str())
341                .map(str::trim)
342                .filter(|s| !s.is_empty())
343                .ok_or_else(|| {
344                    anyhow::anyhow!(
345                        "Tasks complete requires a non-empty 'result' — it is the only \
346                         record of what this item accomplished once it is marked done"
347                    )
348                })?
349                .to_string(),
350        ),
351        _ => (
352            "release",
353            arguments.get("reason").and_then(|v| v.as_str()).unwrap_or("").to_string(),
354        ),
355    };
356
357    let url = format!("{}/agentmux/work/{}/{}", local_url.trim_end_matches('/'), path_seg(id), segment);
358    let body = serde_json::json!({
359        "agent_id": self_id,
360        "attempt": attempt,
361        "result": result_text,
362        "lease_ms": arguments.get("lease_ms").and_then(|v| v.as_i64()).filter(|&n| n > 0),
363        "handback": segment == "release" && arguments.get("handback").and_then(|v| v.as_bool()).unwrap_or(false),
364    });
365    let resp = client.post(&url).header(AUTH_KEY_HEADER, auth_key).json(&body).send().await
366        .map_err(|e| anyhow::anyhow!("work {segment} request failed: {e}"))?;
367    let status = resp.status();
368    let text = resp.text().await.unwrap_or_default();
369    if status == reqwest::StatusCode::CONFLICT {
370        // The fence rejected this call. Say so in the terms the agent
371        // can act on, rather than surfacing a raw 409 — the recovery is
372        // always the same: claim again.
373        anyhow::bail!(
374            "This claim is no longer yours — the lease expired and the item was \
375             reclaimed, or another agent holds it now. Claim again with Tasks if you \
376             still want work; do NOT retry with the old attempt number."
377        );
378    }
379    if !status.is_success() {
380        anyhow::bail!("{name} failed: HTTP {status} — {}", refusal_words(&text));
381    }
382    Ok(match segment {
383        "heartbeat" => format!("Lease extended on {id}."),
384        "complete" => finished_text(id, &serde_json::from_str::<Value>(&text).unwrap_or(serde_json::json!({}))),
385        _ => {
386            // A release on the FINAL allowed attempt parks the item as
387            // `failed` rather than reopening it, so reporting "back to
388            // the queue" unconditionally would tell the caller another
389            // agent can pick it up when nobody ever will (Codex P2 on
390            // PR #2902). The server reports the resulting state; trust
391            // it rather than re-deriving the attempts rule here.
392            if segment == "release" && arguments.get("handback").and_then(|v| v.as_bool()).unwrap_or(false) {
393                return Ok(format!(
394                    "Handed {id} back to the pool: no attempt used, and an unnamed claim won't offer it to you again."
395                ));
396            }
397            let resulting = serde_json::from_str::<Value>(&text)
398                .ok()
399                .and_then(|v| v.get("state").and_then(|s| s.as_str()).map(str::to_string))
400                .unwrap_or_default();
401            if resulting == "failed" {
402                format!(
403                    "Released {id}, and it has now used its final attempt — the item is \
404                     parked as FAILED and will not be offered to any agent again. If it \
405                     still needs doing, Tasks retry reopens it (or enqueue a fresh item, ideally \
406                     with what you learned about why it kept failing). A task that is simply \
407                     outside your area is handed back with handback: true, which never parks it."
408                )
409            } else {
410                format!("Released {id} back to the queue for another agent.")
411            }
412        }
413    })
414}
415
416async fn run_work_hold(name: &str, arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
417    let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
418    require_agent_env(local_url, auth_key, block_id)?;
419    let self_id = std::env::var("AGENTMUX_AGENT_ID").ok().filter(|s| !s.is_empty())
420        .ok_or_else(|| anyhow::anyhow!("AGENTMUX_AGENT_ID is not set"))?;
421    let id = task_id(arguments)?;
422    let segment = if name == "WorkHold" { "hold" } else { "unhold" };
423    let url = format!("{}/agentmux/work/{}/{}", local_url.trim_end_matches('/'), path_seg(id), segment);
424    let body = serde_json::json!({
425        "agent_id": self_id,
426        "attempt": arguments.get("attempt").and_then(|v| v.as_i64()),
427        "reason": arguments.get("reason").and_then(|v| v.as_str()).unwrap_or(""),
428    });
429    let resp = client.post(&url).header(AUTH_KEY_HEADER, auth_key).json(&body).send().await
430        .map_err(|e| anyhow::anyhow!("work {segment} request failed: {e}"))?;
431    let status = resp.status();
432    let reply = resp.text().await.unwrap_or_default();
433    let v: Value = serde_json::from_str(&reply).unwrap_or(serde_json::json!({}));
434    if status == reqwest::StatusCode::NOT_FOUND && v.get("error").is_none() {
435        anyhow::bail!("This AgentMux can't {segment} tasks yet; ask the operator to do it in the Kanban.");
436    }
437    if !status.is_success() {
438        let why = v.get("error").and_then(|e| e.as_str()).map(str::to_string).unwrap_or(reply);
439        anyhow::bail!("Tasks {segment}: {why}");
440    }
441    Ok(hold_text(id, segment, &v))
442}
443
444/// Any agent accepts or sends back a task in Review; srv records the agent that did it.
445async fn run_work_accept(name: &str, arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
446    let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
447    require_agent_env(local_url, auth_key, block_id)?;
448    let id = task_id(arguments)?;
449    let accept = name == "WorkAccept";
450    let segment = if accept { "accept" } else { "send_back" };
451    let url = format!("{}/agentmux/work/{}/{}", local_url.trim_end_matches('/'), path_seg(id), segment);
452    let key = if accept { "note" } else { "reason" };
453    let text = arguments.get(key).and_then(|v| v.as_str()).unwrap_or("");
454    if !accept && text.trim().is_empty() {
455        anyhow::bail!("Tasks send_back: reason is required: it goes to the task's holder.");
456    }
457    let auth = crate::identity::sign_ui_automation_auth()?;
458    let body = serde_json::json!({
459        "agent_id": auth.agent_id,
460        "ts_secs": auth.ts_secs,
461        "sig": auth.sig,
462        "text": text,
463    });
464    let resp = client.post(&url).header(AUTH_KEY_HEADER, auth_key).json(&body).send().await
465        .map_err(|e| anyhow::anyhow!("work {segment} request failed: {e}"))?;
466    let status = resp.status();
467    let reply = resp.text().await.unwrap_or_default();
468    let v: Value = serde_json::from_str(&reply).unwrap_or(serde_json::json!({}));
469    if status == reqwest::StatusCode::NOT_FOUND && v.get("error").is_none() {
470        anyhow::bail!("This AgentMux can't {segment} tasks for agents yet; ask the operator to do it in the Kanban.");
471    }
472    if !status.is_success() {
473        // srv's own words say what to do instead; they are the answer.
474        let why = v.get("error").and_then(|e| e.as_str()).map(str::to_string).unwrap_or(reply);
475        anyhow::bail!("Tasks {segment}: {why}");
476    }
477    Ok(decision_text(id, accept, &v))
478}
479
480/// The fields each of the Kanban's moves takes, as the tool's description lists them (not `board`: with a
481/// bare `id` it says which board the id is on, for every move). A field that only
482/// other moves take is refused by name: answered "done", it would be dropped and the task left as it was.
483const MOVE_FIELDS: &[(&str, &[&str])] = &[
484    ("title", &["edit"]),
485    ("payload", &["edit"]),
486    ("kind", &["edit"]),
487    ("priority", &["edit"]),
488    ("repo", &["edit"]),
489    ("review", &["edit"]),
490    ("after", &["edit"]),
491    ("target_agent", &["move", "start", "reassign"]),
492    ("hold", &["move"]),
493    ("rank", &["move"]),
494    ("drop_deps", &["move"]),
495    ("confirm", &["take_back", "reassign"]),
496    ("followers", &["cancel"]),
497];
498
499/// The tool-facing name of a move: what the agent passes as `action`.
500fn move_action_name(tool: &str) -> &'static str {
501    match tool {
502        "WorkEdit" => "edit",
503        "WorkMove" => "move",
504        "WorkStart" => "start",
505        "WorkAnswer" => "answer",
506        "WorkCancel" => "cancel",
507        "WorkReopen" => "reopen",
508        "WorkRetry" => "retry",
509        "WorkTakeBack" => "take_back",
510        _ => "reassign",
511    }
512}
513
514/// Refuse a field this move doesn't take, naming the moves that do.
515fn refuse_unused_fields(tool: &str, arguments: &Value) -> Result<()> {
516    let action = move_action_name(tool);
517    for (field, takers) in MOVE_FIELDS {
518        if takers.contains(&action) || arguments.get(*field).map_or(true, Value::is_null) {
519            continue;
520        }
521        let hint = if *field == "target_agent" { "to change who a task is for, use move with target_agent".to_string() } else { format!("{field} belongs to {}", takers.join(", ")) };
522        anyhow::bail!("Tasks {action} doesn't take {field}: {hint}. Nothing was changed.");
523    }
524    Ok(())
525}
526
527/// The Kanban's other moves, made by this agent (`POST /agentmux/work/act`).
528async fn run_work_edit(name: &str, arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
529    let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
530    require_agent_env(local_url, auth_key, block_id)?;
531    let self_id = std::env::var("AGENTMUX_AGENT_ID").ok().filter(|s| !s.is_empty())
532        .ok_or_else(|| anyhow::anyhow!("AGENTMUX_AGENT_ID is not set"))?;
533    let id = task_id(arguments)?;
534    refuse_unused_fields(name, arguments)?;
535    let action = match name {
536        "WorkEdit" => "edit",
537        "WorkMove" => "move",
538        "WorkStart" => "start",
539        "WorkAnswer" => "answer",
540        "WorkCancel" => "cancel",
541        "WorkReopen" => "reopen",
542        "WorkRetry" => "retry",
543        "WorkTakeBack" => "release",
544        _ => "reassign",
545    };
546    let text = arguments.get("text").or_else(|| arguments.get("reason")).and_then(|v| v.as_str()).unwrap_or("");
547    let mut body = serde_json::json!({ "agent_id": self_id, "action": action, "id": id, "text": text });
548    for key in ["title", "payload", "kind", "priority", "repo", "review", "after", "hold", "rank", "confirm", "followers", "board", "drop_deps"] {
549        if let Some(v) = arguments.get(key).filter(|v| !v.is_null()) {
550            body[key] = v.clone();
551        }
552    }
553    if let Some(target) = arguments.get("target_agent").and_then(|v| v.as_str()) {
554        // Empty means anyone. A typed name is resolved now, as `enqueue` does, so a stable id
555        // still finds the agent after a rename.
556        body["target"] = if target.is_empty() {
557            serde_json::json!("")
558        } else {
559            match resolve_agent_target_at_boundary(&client, local_url, auth_key, target).await? {
560                crate::identity::BoundaryResolution::NoSuchAgent(close) => anyhow::bail!("{}", no_such_target(target, &close)),
561                r => serde_json::json!(r.uid().unwrap_or_else(|| target.to_string())),
562            }
563        };
564    }
565    let url = format!("{}/agentmux/work/act", local_url.trim_end_matches('/'));
566    let resp = client.post(&url).header(AUTH_KEY_HEADER, auth_key).json(&body).send().await
567        .map_err(|e| anyhow::anyhow!("work {action} request failed: {e}"))?;
568    let status = resp.status();
569    let reply = resp.text().await.unwrap_or_default();
570    let v: Value = serde_json::from_str(&reply).unwrap_or(serde_json::json!({}));
571    if status == reqwest::StatusCode::NOT_FOUND && v.get("error").is_none() {
572        anyhow::bail!("This AgentMux can't {action} tasks for agents yet; ask the operator to do it in the Kanban.");
573    }
574    if !status.is_success() {
575        let why = v.get("error").and_then(|e| e.as_str()).map(str::to_string).unwrap_or(reply);
576        anyhow::bail!("Tasks {action}: {why}");
577    }
578    // A take back or reassign of a task with a branch or PR asks first: say what it asked.
579    if let Some(ask) = v.get("confirm").and_then(|c| c.as_str()) {
580        return Ok(format!("Task {} not changed. {ask} Call again with confirm: true to go ahead.", shown_id(id)));
581    }
582    if action == "move" && v.get("ref").is_some() {
583        let to = v.get("ref").and_then(|r| r.as_str()).unwrap_or("");
584        let from = v.get("from").and_then(|r| r.as_str()).unwrap_or("");
585        let dropped = v.get("dropped_dependencies").and_then(|d| d.as_array()).filter(|d| !d.is_empty());
586        let dropped = dropped.map(|d| format!(" Its dependencies on {} were removed.", d.iter().filter_map(|x| x.as_str()).collect::<Vec<_>>().join(", "))).unwrap_or_default();
587        let cleared = if v.get("target_cleared").and_then(|c| c.as_bool()) == Some(true) { " Its target agent is not on that board's agent list, so it is for anyone now." } else { "" };
588        return Ok(format!("Task {from} moved to {to} (the original is closed pointing to it).{dropped}{cleared}"));
589    }
590    Ok(format!("Task {}: {action} done.", shown_id(id)))
591}
592
593async fn run_work_list(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
594    let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
595    require_agent_env(local_url, auth_key, block_id)?;
596    let url = format!("{}/agentmux/work", local_url.trim_end_matches('/'));
597    let state = arguments.get("state").and_then(|v| v.as_str()).unwrap_or("");
598    let limit = arguments.get("limit").and_then(|v| v.as_i64()).unwrap_or(50);
599    let board = arguments.get("board").and_then(|v| v.as_str()).map(str::trim).unwrap_or("");
600    // Built via reqwest's own query serializer, NOT string
601    // concatenation (reagent P2 on PR #2902): `state` is a free-form
602    // string in this tool's schema, not a validated enum, so a value
603    // containing `&`, `#`, or `%` would otherwise corrupt the query
604    // rather than being sent as the literal the caller intended.
605    let mut query = vec![("state", state.to_string()), ("limit", limit.to_string())];
606    if !board.is_empty() {
607        query.push(("board", board.to_string()));
608    }
609    let resp = client
610        .get(&url)
611        .query(&query)
612        .header(AUTH_KEY_HEADER, auth_key)
613        .send()
614        .await
615        .map_err(|e| anyhow::anyhow!("work list request failed: {e}"))?;
616    let status = resp.status();
617    let text = resp.text().await.unwrap_or_default();
618    if !status.is_success() {
619        anyhow::bail!("Tasks list failed: HTTP {status} — {text}");
620    }
621    let v: Value = serde_json::from_str(&text).unwrap_or(serde_json::json!({}));
622    let items = v.get("items").and_then(|x| x.as_array()).cloned().unwrap_or_default();
623    let note = v.get("note").and_then(|n| n.as_str()).map(|n| format!("\n{n}")).unwrap_or_default();
624    if items.is_empty() {
625        let on = v.get("board").and_then(|b| b.as_str()).filter(|b| *b != "all").map(|b| format!(" on board {b}")).unwrap_or_default();
626        return Ok(format!("Queue is empty{on}.{note}"));
627    }
628    let mut out = format!("{} work item(s){}:\n", items.len(), v.get("board").and_then(|b| b.as_str()).map(|b| format!(" on {b}")).unwrap_or_default());
629    for it in &items {
630        let id = it.get("ref").and_then(|x| x.as_str()).map(str::to_string)
631            .or_else(|| it.get("num").and_then(|x| x.as_i64()).map(|n| format!("#{n}")))
632            .unwrap_or_else(|| it.get("id").and_then(|x| x.as_str()).unwrap_or("").to_string());
633        let st = it.get("state").and_then(|x| x.as_str()).unwrap_or("");
634        let title = it.get("title").and_then(|x| x.as_str()).unwrap_or("");
635        let holder = it.get("claimed_by").and_then(|x| x.as_str()).unwrap_or("");
636        let target = it.get("target_agent").and_then(|x| x.as_str()).unwrap_or("");
637        let group = it.get("target_group").and_then(|x| x.as_str()).unwrap_or("");
638        // Who it is for (a started task is for its holder: said once), and who holds it.
639        let for_who = if !target.is_empty() && target != holder {
640            format!(", for {target}")
641        } else if target.is_empty() && !group.is_empty() {
642            format!(", for group {group}")
643        } else {
644            String::new()
645        };
646        let held = if holder.is_empty() { String::new() } else { format!(", held by {holder}") };
647        out.push_str(&format!("  {id}  {st}{for_who}{held}  {title}\n"));
648        // `result` is the completion trace for a done item, and the
649        // reason for a failed/released one — the very thing
650        // WorkComplete calls "the only record". Omitting it here left
651        // that record unreachable through the only agent-facing read
652        // tool (Codex P2 on PR #2902).
653        let result = it.get("result").and_then(|x| x.as_str()).unwrap_or("");
654        if !result.is_empty() {
655            // A task with a holder (claimed, or blocked on a question) is not finished: what it carries
656            // is why a PREVIOUS holder handed it back ("agent stopped", "agent quit"), which its current
657            // holder was told when it claimed. Printed as a verdict, it reads as if this holder stopped.
658            if matches!(st, "claimed" | "blocked") {
659                out.push_str(&format!("      (handed back earlier: {result})\n"));
660            } else {
661                out.push_str(&format!("      -> {result}\n"));
662            }
663        }
664    }
665    out.push_str(note.trim_start_matches('\n'));
666    Ok(out)
667}
668
669/// One task whole (`GET /agentmux/work/:id`): the instruction it was filed with and everything the board holds about it.
670async fn run_work_get(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
671    let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
672    require_agent_env(local_url, auth_key, block_id)?;
673    let id = task_id(arguments)?;
674    let url = format!("{}/agentmux/work/{}", local_url.trim_end_matches('/'), path_seg(id));
675    let resp = client
676        .get(&url)
677        .header(AUTH_KEY_HEADER, auth_key)
678        .send()
679        .await
680        .map_err(|e| anyhow::anyhow!("work get request failed: {e}"))?;
681    let status = resp.status();
682    let text = resp.text().await.unwrap_or_default();
683    if status == reqwest::StatusCode::NOT_FOUND {
684        anyhow::bail!("Tasks get: no task {} that you can see. Tasks list shows the ones on your boards.", shown_id(id));
685    }
686    if !status.is_success() {
687        anyhow::bail!("Tasks get failed: HTTP {status} — {}", refusal_words(&text));
688    }
689    let v: Value = serde_json::from_str(&text).unwrap_or(serde_json::json!({}));
690    Ok(task_text(&v, id, agentmux_common::time::now_ms()))
691}
692
693/// A task's tokens (`GET /agentmux/work/:id/tokens`): where its tally went, as srv words it. Counts only, and only when asked.
694async fn run_work_tokens(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
695    let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
696    require_agent_env(local_url, auth_key, block_id)?;
697    let id = task_id(arguments)?;
698    let url = format!("{}/agentmux/work/{}/tokens", local_url.trim_end_matches('/'), path_seg(id));
699    let resp = client
700        .get(&url)
701        .header(AUTH_KEY_HEADER, auth_key)
702        .send()
703        .await
704        .map_err(|e| anyhow::anyhow!("work tokens request failed: {e}"))?;
705    let status = resp.status();
706    let text = resp.text().await.unwrap_or_default();
707    if status == reqwest::StatusCode::NOT_FOUND {
708        anyhow::bail!("Tasks tokens: no task {} that you can see. Tasks list shows the ones on your boards.", shown_id(id));
709    }
710    if !status.is_success() {
711        anyhow::bail!("Tasks tokens failed: HTTP {status} — {}", refusal_words(&text));
712    }
713    let v: Value = serde_json::from_str(&text).unwrap_or(serde_json::json!({}));
714    Ok(v.get("text").and_then(|t| t.as_str()).unwrap_or("No tokens counted.").to_string())
715}
716
717/// How long ago, in the words a history line uses.
718fn ago_words(ms: i64) -> String {
719    let s = ms.max(0) / 1000;
720    match s {
721        0..=89 => format!("{s} s ago"),
722        90..=5_399 => format!("{} min ago", (s + 30) / 60),
723        5_400..=129_599 => format!("{} h ago", (s + 1_800) / 3_600),
724        _ => format!("{} d ago", (s + 43_200) / 86_400),
725    }
726}
727
728/// A task as `get` shows it: who it is for and who holds it, its links, the instruction it was filed with,
729/// then the holder's note, question and checklist, what it starts after, and its last history lines.
730fn task_text(v: &Value, id: &str, now_ms: i64) -> String {
731    let s = |o: &Value, k: &str| o.get(k).and_then(|x| x.as_str()).unwrap_or("").to_string();
732    let card = v.get("card").cloned().unwrap_or(serde_json::json!({}));
733    let name = match (s(&card, "task_ref"), card.get("num").and_then(|n| n.as_i64())) {
734        (r, _) if !r.is_empty() => format!("task {r}"),
735        (_, Some(n)) => format!("task #{n}"),
736        _ => format!("work item {id}"),
737    };
738    let (target, holder) = (s(v, "target_agent"), s(v, "claimed_by"));
739    let mut head = format!("{name} ({}", s(v, "state"));
740    if !target.is_empty() && target != holder {
741        head.push_str(&format!(", for {target}"));
742    }
743    if !holder.is_empty() {
744        head.push_str(&format!(", held by {holder}"));
745    }
746    head.push(')');
747    let mut out = format!("{head}\nTitle: {}\n", s(v, "title"));
748    let mut links = Vec::new();
749    for (key, label) in [("repo", "repo"), ("branch", "branch"), ("pr_url", "PR"), ("doc", "document")] {
750        let val = s(&card, key);
751        if !val.is_empty() {
752            links.push(format!("{label}: {val}"));
753        }
754    }
755    if !links.is_empty() {
756        out.push_str(&format!("Links: {}\n", links.join("; ")));
757    }
758    let kind = s(v, "kind");
759    if !kind.is_empty() {
760        out.push_str(&format!("Kind: {kind}\n"));
761    }
762    let tokens = s(v, "token_line");
763    if !tokens.is_empty() {
764        out.push_str(&format!("{tokens}\n"));
765    }
766    for (key, label) in [("question", "Open question"), ("note", "Holder's last note")] {
767        let val = s(&card, key);
768        if !val.is_empty() {
769            out.push_str(&format!("{label}: {val}\n"));
770        }
771    }
772    if let Some(items) = card.get("checklist").and_then(|c| c.as_array()).filter(|c| !c.is_empty()) {
773        out.push_str("Checklist:\n");
774        for it in items {
775            let mark = match s(it, "status").as_str() {
776                "completed" => "x",
777                "in_progress" => "~",
778                _ => " ",
779            };
780            out.push_str(&format!("  [{mark}] {}\n", s(it, "text")));
781        }
782    }
783    out.push_str(&format!("\nThe task as it was filed (its payload):\n{}\n", s(v, "payload")));
784    let result = s(v, "result");
785    if !result.is_empty() {
786        out.push_str(&format!("\nResult recorded on it: {result}\n"));
787    }
788    out.push_str(&starts_after_text(card.get("after")));
789    if let Some(events) = v.get("history").and_then(|h| h.as_array()).filter(|h| !h.is_empty()) {
790        out.push_str(&format!("\n\nHistory (last {}):\n", events.len()));
791        for ev in events {
792            let at = ev.get("at").and_then(|a| a.as_i64()).unwrap_or(0);
793            let (from, to) = (s(ev, "from_state"), s(ev, "to_state"));
794            let moved = match (from.as_str(), to.as_str()) {
795                (f, t) if f == t => String::new(),
796                ("", t) => format!(" {t}"),
797                (f, t) => format!(" {f} -> {t}"),
798            };
799            let body = s(ev, "body");
800            let body = if body.is_empty() { String::new() } else { format!(": {body}") };
801            out.push_str(&format!("  {} {} {}{moved}{body}\n", ago_words(now_ms - at), s(ev, "actor"), s(ev, "kind")));
802        }
803    }
804    out.trim_end().to_string()
805}
806
807/// The boards, and managing them (`GET` and `POST /agentmux/work/boards`).
808async fn run_work_boards(name: &str, arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
809    let ToolCtx { local_url, auth_key, block_id, client, .. } = *cx;
810    require_agent_env(local_url, auth_key, block_id)?;
811    let url = format!("{}/agentmux/work/boards", local_url.trim_end_matches('/'));
812    let action = match name {
813        "WorkBoardCreate" => "create",
814        "WorkBoardEdit" => "edit",
815        "WorkBoardArchive" => "archive",
816        "WorkBoardUnarchive" => "unarchive",
817        "WorkBoardDefault" => "default",
818        "WorkBoardDelete" => "delete",
819        "WorkBoardCancelDelete" => "cancel_delete",
820        _ => "",
821    };
822    let resp = if action.is_empty() {
823        let archived = arguments.get("archived").and_then(|v| v.as_bool()).unwrap_or(false);
824        client.get(&url).query(&[("archived", archived.to_string())]).header(AUTH_KEY_HEADER, auth_key).send().await
825    } else {
826        let mut body = serde_json::json!({ "action": action });
827        for key in ["board", "name", "slug", "readable", "agents", "stages", "stages_reset", "stages_rev"] {
828            if let Some(v) = arguments.get(key).filter(|v| !v.is_null()) {
829                body[key] = v.clone();
830            }
831        }
832        client.post(&url).header(AUTH_KEY_HEADER, auth_key).json(&body).send().await
833    }
834    .map_err(|e| anyhow::anyhow!("boards request failed: {e}"))?;
835    let status = resp.status();
836    let text = resp.text().await.unwrap_or_default();
837    let v: Value = serde_json::from_str(&text).unwrap_or(serde_json::json!({}));
838    if !status.is_success() {
839        let why = v.get("error").and_then(|e| e.as_str()).map(str::to_string).unwrap_or(text);
840        anyhow::bail!("Tasks {}: {why}", if action.is_empty() { "boards".to_string() } else { format!("board_{action}") });
841    }
842    Ok(boards_text(action, &v))
843}
844
845/// ", stages (rev 2): Needs you [amber: needs] | Done [green: merged+released]" for a board with its own
846/// stage set; nothing for the default eight (so the list stays short). An agent reads this to know
847/// what to send back with `stages` and `stages_rev`.
848fn stages_text(b: &Value) -> String {
849    if b.get("stages_default").and_then(Value::as_bool).unwrap_or(true) {
850        return String::new();
851    }
852    let Some(list) = b.get("stages").and_then(|s| s.get("stages")).and_then(Value::as_array) else { return String::new() };
853    let one = |st: &Value| {
854        let s = |k: &str| st.get(k).and_then(Value::as_str).unwrap_or("");
855        let takes: Vec<&str> = st.get("takes").and_then(Value::as_array).map(|t| t.iter().filter_map(Value::as_str).collect()).unwrap_or_default();
856        format!("{} [{}: {}]", s("name"), s("colour"), takes.join("+"))
857    };
858    let rev = b.get("stages_rev").and_then(Value::as_i64).unwrap_or(0);
859    format!(", stages (rev {rev}): {}", list.iter().map(one).collect::<Vec<_>>().join(" | "))
860}
861
862/// What the boards answers say: the list, or the board a change left.
863fn boards_text(action: &str, v: &Value) -> String {
864    let line = |b: &Value| {
865        let s = |k: &str| b.get(k).and_then(|x| x.as_str()).unwrap_or("");
866        let n = |k: &str| b.get(k).and_then(|x| x.as_i64()).unwrap_or(0);
867        let flag = |k: &str| b.get(k).and_then(|x| x.as_bool()).unwrap_or(false);
868        let agents = b.get("agents").and_then(|a| a.as_array()).filter(|a| !a.is_empty()).map(|a| {
869            format!(", agents: {}", a.iter().filter_map(|x| x.as_str()).collect::<Vec<_>>().join(", "))
870        });
871        format!(
872            "{} ({}){}{}{}: {} open of {} task(s){}{}",
873            s("slug"),
874            s("name"),
875            if flag("default") { " [default]" } else { "" },
876            if flag("archived") { " [archived]" } else { "" },
877            if b.get("pending_delete_at").is_some_and(|p| !p.is_null()) { " [being deleted]" } else { "" },
878            n("open"),
879            n("total"),
880            agents.unwrap_or_default(),
881            stages_text(b),
882        )
883    };
884    match action {
885        "" => {
886            let boards = v.get("boards").and_then(|b| b.as_array()).cloned().unwrap_or_default();
887            let mut out = format!("{} board(s) you see:\n", boards.len());
888            for b in &boards {
889                out.push_str(&format!("  {}\n", line(b)));
890            }
891            out
892        }
893        "delete" if v.get("deleted").and_then(|d| d.as_bool()) == Some(true) => "Board deleted.".to_string(),
894        "delete" => v.get("note").and_then(|n| n.as_str()).unwrap_or("The board will be deleted shortly.").to_string(),
895        _ => match v.get("board") {
896            Some(b) => format!("Done. {}", line(b)),
897            None => "Done.".to_string(),
898        },
899    }
900}
901
902/// The task an action names, as it goes in a URL path: its id, or its number
903/// with or without the `#` the answers print (a raw `#` would start the URL's
904/// fragment). Anything else that isn't an id character is refused.
905/// What srv refused with, in words: its `error` when the answer is JSON that has one, else the answer as it came
906/// (a UI task handed in without media is told what to attach, or to say why it can't).
907fn refusal_words(reply: &str) -> String {
908    serde_json::from_str::<Value>(reply)
909        .ok()
910        .and_then(|v| v.get("error").and_then(Value::as_str).map(str::to_string))
911        .unwrap_or_else(|| reply.to_string())
912}
913
914/// " Attached: a.png (image), b.webm (recording)." for the files an update or submit carried, else "".
915fn attached_text(v: &Value) -> String {
916    let Some(list) = v.get("attached").and_then(Value::as_array).filter(|l| !l.is_empty()) else { return String::new() };
917    let names: Vec<String> = list
918        .iter()
919        .map(|m| {
920            let name = m.get("name").and_then(Value::as_str).unwrap_or("file");
921            let kind = m.get("kind").and_then(Value::as_str).unwrap_or("file");
922            format!("{name} ({kind})")
923        })
924        .collect();
925    format!(" Attached: {}.", names.join(", "))
926}
927
928/// The tasks `self_id` holds in `state` on any board, each with its attempt.
929async fn held_in(state: &str, self_id: &str, cx: &ToolCtx<'_>) -> Vec<(String, i64)> {
930    let ToolCtx { local_url, auth_key, client, .. } = *cx;
931    let url = format!("{}/agentmux/work", local_url.trim_end_matches('/'));
932    match client.get(&url).query(&[("state", state), ("limit", "200"), ("board", "all")]).header(AUTH_KEY_HEADER, auth_key).send().await {
933        Ok(resp) => resp.json::<Value>().await.ok(),
934        Err(_) => None,
935    }
936    .and_then(|v| v.get("items").and_then(Value::as_array).cloned())
937    .unwrap_or_default()
938    .iter()
939    .filter(|it| it.get("claimed_by").and_then(Value::as_str) == Some(self_id) && it.get("state").and_then(Value::as_str).is_none_or(|s| s == state))
940    .filter_map(|it| {
941        let task = it.get("ref").and_then(Value::as_str).map(|r| r.trim_start_matches('#').to_string())
942            .or_else(|| it.get("num").and_then(Value::as_i64).map(|n| n.to_string()))?;
943        Some((task, it.get("attempts").and_then(Value::as_i64)?))
944    })
945    .collect()
946}
947
948/// The refusal for a call without `attempt`: the tasks this agent holds, each with the attempt to pass. A
949/// weak model repeats a bare refusal; this one says what to send. It never fills the attempt in: the
950/// argument is how srv rejects a stale holder, and a default would defeat it.
951async fn missing_attempt(arguments: &Value, self_id: &str, cx: &ToolCtx<'_>) -> anyhow::Error {
952    let asked = arguments.get("id").and_then(|v| v.as_str()).map(|s| s.trim().trim_start_matches('#')).unwrap_or("");
953    // A task asked about with `Tasks ask` is `blocked` and still held: update and submit still take it.
954    let mut held = held_in("claimed", self_id, cx).await;
955    held.extend(held_in("blocked", self_id, cx).await);
956    let mine = held.iter().find(|(task, _)| !asked.is_empty() && task == asked);
957    anyhow::anyhow!(match (mine, held.as_slice()) {
958        (Some((task, n)), _) => format!("missing required parameter: attempt. You hold #{task} as attempt {n}: pass id={task} attempt={n}."),
959        (None, []) => "missing required parameter: attempt (from the Tasks claim answer). You hold no claimed task: claim one first, and pass the attempt it answers.".to_string(),
960        (None, held) => format!(
961            "missing required parameter: attempt (from the Tasks claim answer). You hold: {}. Pass the id and attempt of the one you mean.",
962            held.iter().map(|(task, n)| format!("#{task} (attempt {n})")).collect::<Vec<_>>().join(", ")
963        ),
964    })
965}
966
967/// An `update` that only leaves a note and/or links: the part of `update` that needs no claim. A checklist,
968/// files, or the UI flags are the holder's, and still ask for the attempt.
969fn is_only_a_note(arguments: &Value) -> bool {
970    let text = |v: Option<&Value>| v.and_then(Value::as_str).is_some_and(|s| !s.trim().is_empty());
971    let links = arguments.get("links");
972    let has_text = text(arguments.get("note")) || ["pr", "branch", "doc"].iter().any(|k| text(links.and_then(|l| l.get(*k))));
973    let holder_only = ["checklist", "files", "captions", "ui_change", "no_media_reason"].iter().any(|k| arguments.get(*k).is_some_and(|v| !v.is_null()));
974    has_text && !holder_only
975}
976
977/// Whether this agent holds the task the call names (claimed, or blocked on a question it asked).
978async fn holds_it(arguments: &Value, self_id: &str, cx: &ToolCtx<'_>) -> bool {
979    let asked = arguments.get("id").and_then(|v| v.as_str()).map(|s| s.trim().trim_start_matches('#')).unwrap_or("");
980    let mut held = held_in("claimed", self_id, cx).await;
981    held.extend(held_in("blocked", self_id, cx).await);
982    held.iter().any(|(task, _)| task == asked)
983}
984
985/// `Tasks update` with a note or links and no attempt, on a task nobody holds: srv writes it on the card as
986/// this agent's, with no claim and no attempt used. srv refuses it, saying what to do instead, if someone holds it.
987async fn note_on_unheld(id: &str, arguments: &Value, self_id: &str, cx: &ToolCtx<'_>) -> Result<String> {
988    let ToolCtx { local_url, auth_key, client, .. } = *cx;
989    let str_arg = |k: &str| arguments.get(k).and_then(|v| v.as_str()).map(str::trim).filter(|s| !s.is_empty());
990    let links = arguments.get("links").cloned().unwrap_or(Value::Null);
991    let url = format!("{}/agentmux/work/{}/update", local_url.trim_end_matches('/'), path_seg(id));
992    let body = serde_json::json!({
993        "agent_id": self_id,
994        "note": str_arg("note"),
995        "pr_url": links.get("pr").and_then(|v| v.as_str()),
996        "unpr": links.get("unpr").and_then(|v| v.as_str()),
997        "branch": links.get("branch").and_then(|v| v.as_str()),
998        "doc": links.get("doc").and_then(|v| v.as_str()),
999    });
1000    let resp = client.post(&url).header(AUTH_KEY_HEADER, auth_key).json(&body).send().await
1001        .map_err(|e| anyhow::anyhow!("work update request failed: {e}"))?;
1002    let status = resp.status();
1003    let reply = resp.text().await.unwrap_or_default();
1004    if !status.is_success() {
1005        // A 409 here is srv's own words (the task is held by someone), not "your claim is old".
1006        anyhow::bail!("Tasks update failed: HTTP {status} — {}", refusal_words(&reply));
1007    }
1008    Ok(format!(
1009        "Noted on task {id}: nobody holds it, so no claim or attempt was needed. The card shows the note as written by {self_id}."
1010    ))
1011}
1012
1013fn task_id(arguments: &Value) -> Result<&str> {
1014    let id = arguments
1015        .get("id")
1016        .and_then(|v| v.as_str())
1017        .map(|s| s.trim().trim_start_matches('#'))
1018        .filter(|s| !s.is_empty())
1019        .ok_or_else(|| anyhow::anyhow!("missing required parameter: id"))?;
1020    // `work#12`: a task number on a board; the slug is letters, digits and hyphens.
1021    let plain = |s: &str| s.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
1022    let ok = match id.split_once('#') {
1023        Some((slug, num)) => !slug.is_empty() && plain(slug) && !num.is_empty() && num.chars().all(|c| c.is_ascii_digit()),
1024        None => plain(id),
1025    };
1026    if !ok {
1027        anyhow::bail!("id {id:?} is neither a task number (12 or work#12) nor a task id");
1028    }
1029    Ok(id)
1030}
1031
1032/// A task ref as one URL path segment (a raw `#` would start the URL's fragment).
1033fn path_seg(id: &str) -> String {
1034    id.replace('#', "%23")
1035}
1036
1037/// How an answer writes the id it was given: `#12`, or `work#12` as it is.
1038fn shown_id(id: &str) -> String {
1039    if id.contains('#') { id.to_string() } else { format!("#{id}") }
1040}
1041
1042/// The arguments with a bare task number made a ref on the board they name (`board: "work"`, `id: "12"` is
1043/// `work#12`), when the board is given as a slug. Not for `move` (its board is where the task goes), nor
1044/// where the board is not about the id.
1045///
1046/// A board that is not a slug (a display name) cannot make the ref, and the number must not fall back to
1047/// the default board's task of that number: that is an error, naming the way to say it.
1048fn scoped(name: &str, arguments: &Value) -> Result<Option<Value>> {
1049    if matches!(name, "WorkMove" | "WorkEnqueue" | "WorkList") || name.starts_with("WorkBoard") {
1050        return Ok(None);
1051    }
1052    let Some(board) = arguments.get("board").and_then(|b| b.as_str()).map(str::trim).filter(|b| !b.is_empty()) else {
1053        return Ok(None);
1054    };
1055    let Some(id) = arguments.get("id").and_then(|i| i.as_str()).map(|i| i.trim().trim_start_matches('#')) else {
1056        return Ok(None);
1057    };
1058    if id.is_empty() || !id.chars().all(|c| c.is_ascii_digit()) {
1059        return Ok(None);
1060    }
1061    let slug = board.len() <= 24 && !board.starts_with('-') && board.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-');
1062    if !slug {
1063        anyhow::bail!(
1064            "Task {id} on board \"{board}\": give the board by its slug (Tasks boards lists them), or the id as slug#{id}. \
1065             A bare number alone would mean the default board's task."
1066        );
1067    }
1068    let mut a = arguments.clone();
1069    a["id"] = Value::String(format!("{board}#{id}"));
1070    Ok(Some(a))
1071}
1072
1073/// A task as an answer names it: `#12` when srv gave it a number, else its id.
1074fn task_name(v: &Value, id: &str) -> String {
1075    if let Some(r) = v.get("ref").and_then(|r| r.as_str()) {
1076        return format!("task {r}");
1077    }
1078    match v.get("num").and_then(|n| n.as_i64()) {
1079        Some(n) => format!("task #{n}"),
1080        None => format!("work item {id}"),
1081    }
1082}
1083
1084/// What a claimed task starts after, with each one's document: a build's agent
1085/// reads its spec there, however the build reached it. Empty when it starts
1086/// after nothing.
1087fn starts_after_text(after: Option<&Value>) -> String {
1088    let lines: Vec<String> = after
1089        .and_then(|a| a.as_array())
1090        .map(|a| {
1091            a.iter()
1092                .map(|t| {
1093                    let s = |k: &str| t.get(k).and_then(|x| x.as_str()).unwrap_or("");
1094                    let num = t.get("num").and_then(|n| n.as_i64()).map(|n| format!("#{n} ")).unwrap_or_default();
1095                    let doc = Some(s("doc")).filter(|d| !d.is_empty()).map(|d| format!(", document: {d}")).unwrap_or_default();
1096                    format!("- {num}\"{}\" ({}{doc})", s("title"), s("state"))
1097                })
1098                .collect()
1099        })
1100        .unwrap_or_default();
1101    if lines.is_empty() {
1102        return String::new();
1103    }
1104    format!("\n\nThis task starts after:\n{}\nThe document is what to build; read it first.", lines.join("\n"))
1105}
1106
1107/// The answer to `accept` or `send_back`: what was done, and what it set off.
1108fn decision_text(id: &str, accept: bool, v: &Value) -> String {
1109    let id = shown_id(id);
1110    if !accept {
1111        return format!("Task {id} was sent back. Its holder has the reason.");
1112    }
1113    match v.get("unlocked").and_then(|n| n.as_u64()).unwrap_or(0) {
1114        0 => format!("Task {id} is accepted."),
1115        n => format!("Task {id} is accepted. {n} waiting build{} told it can start.", if n == 1 { " was" } else { "s were" }),
1116    }
1117}
1118
1119/// The answer to `hold` or `unhold`: where the task is now.
1120fn hold_text(id: &str, segment: &str, v: &Value) -> String {
1121    let name = v.get("name").and_then(|n| n.as_str()).filter(|n| !n.is_empty()).unwrap_or(id);
1122    let changed = v.get("changed").and_then(|c| c.as_bool()).unwrap_or(true);
1123    let who = v.get("for").and_then(|f| f.as_str()).filter(|f| !f.is_empty()).unwrap_or("anyone");
1124    match (segment, changed) {
1125        ("hold", true) => format!("Task {name} is on hold: no one takes it until it is taken off hold (Tasks unhold)."),
1126        ("hold", false) => format!("Task {name} was already on hold."),
1127        (_, true) => format!("Task {name} is off hold and waiting for {who}. To take it now: Tasks claim with id {name}."),
1128        _ => format!("Task {name} wasn't on hold; it is waiting for {who}."),
1129    }
1130}
1131
1132/// The answer to finishing a task (`complete`, `submit`): where it went, and
1133/// the next task waiting for the caller, which it takes now (Kanban §6.5: an
1134/// agent goes on through its backlog).
1135fn finished_text(id: &str, v: &Value) -> String {
1136    let state = v.get("state").and_then(|s| s.as_str()).unwrap_or("done");
1137    let mut out = if state == "review" {
1138        format!("Handed in task {id}: it waits for the operator's review in the Kanban.")
1139    } else {
1140        format!("Completed task {id}.")
1141    };
1142    match v.get("next").filter(|n| !n.is_null()) {
1143        Some(next) => {
1144            let num = next.get("num").and_then(|n| n.as_i64()).map(|n| format!("#{n}")).unwrap_or_default();
1145            let title = next.get("title").and_then(|t| t.as_str()).unwrap_or("");
1146            let who = match next.get("requested_by_kind").and_then(|k| k.as_str()) {
1147                Some("operator") => " (requested by the operator)".to_string(),
1148                Some("agent") => next
1149                    .get("requested_by")
1150                    .and_then(|r| r.as_str())
1151                    .filter(|r| !r.is_empty())
1152                    .map(|r| format!(" (requested by {r})"))
1153                    .unwrap_or_default(),
1154                _ => String::new(),
1155            };
1156            let more = v.get("waiting").and_then(|w| w.as_i64()).unwrap_or(1) - 1;
1157            let after = if more > 0 { format!(" {more} more after it.") } else { String::new() };
1158            out.push_str(&format!(
1159                "\n\nNext in your backlog: {num} \"{title}\"{who}. Claim it with Tasks claim and start.{after}"
1160            ));
1161        }
1162        None => out.push_str(" Your backlog is empty."),
1163    }
1164    out
1165}
1166
1167/// Why `Tasks enqueue` refuses a target no agent answers to (#1257), and which ids it may have meant.
1168fn no_such_target(name: &str, did_you_mean: &[String]) -> String {
1169    let meant = match did_you_mean {
1170        [] => String::new(),
1171        [one] => format!(" Did you mean \"{one}\"?"),
1172        many => format!(" Did you mean one of: {}?", many.iter().map(|i| format!("\"{i}\"")).collect::<Vec<_>>().join(", ")),
1173    };
1174    format!(
1175        "No agent on this computer is called \"{name}\", so nobody could take this task.{meant} \
1176         Name it by its AGENTMUX_AGENT_ID (Agents list shows each one), its display name, the \
1177         display name's route form (\"Loap-3\" for \"Loap #3\"), or its uid; or leave \
1178         target_agent out to file it for anyone."
1179    )
1180}
1181
1182#[cfg(test)]
1183mod call_tests;
1184
1185#[cfg(test)]
1186mod tests {
1187    use super::*;
1188
1189    #[test]
1190    fn a_task_number_works_with_or_without_its_hash() {
1191        assert_eq!(task_id(&serde_json::json!({"id": "#12"})).unwrap(), "12");
1192        assert_eq!(task_id(&serde_json::json!({"id": " 12 "})).unwrap(), "12");
1193        assert_eq!(task_id(&serde_json::json!({"id": "7f3a-b2"})).unwrap(), "7f3a-b2");
1194        assert!(task_id(&serde_json::json!({"id": "12/../x"})).is_err());
1195        assert!(task_id(&serde_json::json!({"id": "#"})).is_err());
1196    }
1197
1198    #[test]
1199    fn a_task_ref_names_a_task_on_a_board() {
1200        assert_eq!(task_id(&serde_json::json!({"id": "work#12"})).unwrap(), "work#12");
1201        assert_eq!(task_id(&serde_json::json!({"id": "client-x#3"})).unwrap(), "client-x#3");
1202        assert!(task_id(&serde_json::json!({"id": "work#"})).is_err());
1203        assert!(task_id(&serde_json::json!({"id": "work#1#2"})).is_err());
1204        assert!(task_id(&serde_json::json!({"id": "#work#1"})).is_ok(), "a leading # is the hash of a number, then a ref");
1205        assert_eq!(path_seg("work#12"), "work%2312");
1206        assert_eq!(shown_id("12"), "#12");
1207        assert_eq!(shown_id("work#12"), "work#12");
1208    }
1209
1210    #[test]
1211    fn a_bare_number_with_a_board_slug_becomes_that_boards_ref() {
1212        let a = serde_json::json!({ "id": "12", "board": "work", "reason": "r" });
1213        assert_eq!(scoped("WorkHold", &a).unwrap().unwrap()["id"], "work#12");
1214        assert_eq!(scoped("WorkHold", &serde_json::json!({ "id": "#12", "board": "work" })).unwrap().unwrap()["id"], "work#12");
1215        // Not where the board is a destination, not for a ref or an id.
1216        assert!(scoped("WorkMove", &a).unwrap().is_none());
1217        assert!(scoped("WorkHold", &serde_json::json!({ "id": "work#12", "board": "work" })).unwrap().is_none());
1218        assert!(scoped("WorkHold", &serde_json::json!({ "id": "12" })).unwrap().is_none());
1219        assert!(scoped("WorkBoardEdit", &serde_json::json!({ "board": "work", "id": "12" })).unwrap().is_none());
1220        // A display name with a bare number is refused, never read as the default board's task.
1221        let e = scoped("WorkCancel", &serde_json::json!({ "id": "1", "board": "Client X" })).unwrap_err().to_string();
1222        assert!(e.contains("slug") && e.contains("Client X"), "{e}");
1223    }
1224
1225    #[test]
1226    fn a_decision_is_worded_with_what_it_unlocked() {
1227        let done = serde_json::json!({ "ok": true, "unlocked": 0 });
1228        assert_eq!(decision_text("12", true, &done), "Task #12 is accepted.");
1229        let unlocked = serde_json::json!({ "ok": true, "unlocked": 2 });
1230        assert!(decision_text("12", true, &unlocked).ends_with("2 waiting builds were told it can start."));
1231        let one = serde_json::json!({ "unlocked": 1 });
1232        assert!(decision_text("12", true, &one).ends_with("1 waiting build was told it can start."));
1233        assert!(decision_text("12", false, &done).contains("was sent back"));
1234    }
1235
1236    #[test]
1237    fn a_claimed_build_is_shown_its_specs_document() {
1238        let after = serde_json::json!([{ "id": "w1", "num": 12, "title": "Spec: Kanban", "state": "done", "kind": "spec", "doc": "C:/work/SPEC_KANBAN.md" }]);
1239        let text = starts_after_text(Some(&after));
1240        assert!(text.contains("- #12 \"Spec: Kanban\" (done, document: C:/work/SPEC_KANBAN.md)"), "{text}");
1241        let no_doc = serde_json::json!([{ "num": 3, "title": "Fix first", "state": "done" }]);
1242        assert!(starts_after_text(Some(&no_doc)).contains("- #3 \"Fix first\" (done)"));
1243        assert_eq!(starts_after_text(Some(&serde_json::json!([]))), "");
1244        assert_eq!(starts_after_text(None), "", "an older srv sends none");
1245    }
1246
1247    #[test]
1248    fn hold_and_unhold_say_where_the_task_is_now() {
1249        let v = serde_json::json!({"name": "#12", "changed": true, "for": "Loap-3"});
1250        assert!(hold_text("12", "hold", &v).starts_with("Task #12 is on hold"));
1251        let off = hold_text("12", "unhold", &v);
1252        assert!(off.contains("waiting for Loap-3") && off.contains("claim with id #12"), "{off}");
1253        let same = serde_json::json!({"name": "#12", "changed": false, "for": ""});
1254        assert_eq!(hold_text("12", "hold", &same), "Task #12 was already on hold.");
1255        assert!(hold_text("12", "unhold", &same).ends_with("waiting for anyone."));
1256    }
1257
1258    #[test]
1259    fn a_refusal_is_worded_not_shown_as_json() {
1260        assert_eq!(refusal_words(r#"{"ok":false,"error":"attach a screenshot, or say why"}"#), "attach a screenshot, or say why");
1261        assert_eq!(refusal_words("plain text"), "plain text");
1262        assert_eq!(refusal_words(r#"{"ok":false}"#), r#"{"ok":false}"#);
1263    }
1264
1265    #[test]
1266    fn a_target_nobody_answers_to_is_refused_with_how_to_name_one() {
1267        let msg = no_such_target("Naki-9", &[]);
1268        assert!(msg.contains("\"Naki-9\"") && msg.contains("AGENTMUX_AGENT_ID") && msg.contains("for anyone"), "{msg}");
1269        assert!(!msg.contains("  "), "no source indentation in the text: {msg}");
1270        assert!(!msg.contains("Did you mean"), "nothing close, nothing offered: {msg}");
1271    }
1272
1273    #[test]
1274    fn a_refusal_for_a_target_names_the_id_it_most_likely_meant() {
1275        let one = no_such_target("agent2-0630f", &["agent2".to_string()]);
1276        assert!(one.contains("Did you mean \"agent2\"?"), "{one}");
1277        let two = no_such_target("agent", &["agent2".to_string(), "agenty".to_string()]);
1278        assert!(two.contains("Did you mean one of: \"agent2\", \"agenty\"?"), "{two}");
1279        assert!(!one.contains("  "), "no source indentation in the text: {one}");
1280    }
1281}