Skip to main content

agentmux_srv/server/
name_resolution.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `POST /agentmux/agents/resolve` — the HTTP face of the one place a typed
5//! agent name is interpreted (identity M3, spec §5). Called by `agentmux-mcp`
6//! before `WorkEnqueue` and `CronCreate` so those tools can store a UID at
7//! authoring time (§5.4) and hand an ambiguous name back to the model with
8//! the candidates (§5.2) instead of enqueueing something that can never be
9//! delivered unambiguously.
10//!
11//! Auth-gated like every other loopback route. The body names a *target*; it
12//! never asserts the caller's own identity.
13
14use axum::extract::State;
15use axum::http::StatusCode;
16use axum::response::Json;
17use serde::Deserialize;
18use serde_json::{json, Value};
19
20use super::AppState;
21
22#[derive(Debug, Deserialize)]
23pub(super) struct ResolveRequest {
24    pub name: String,
25}
26
27pub(super) async fn handle_resolve_agent_name(
28    State(state): State<AppState>,
29    Json(req): Json<ResolveRequest>,
30) -> (StatusCode, Json<Value>) {
31    if req.name.trim().is_empty() {
32        return (
33            StatusCode::BAD_REQUEST,
34            Json(json!({ "error": "name is required" })),
35        );
36    }
37    // A synchronous store read, so off the async worker (incident #1782).
38    let mstore = state.mstore.clone();
39    let registry = state.reactive_handler;
40    let name = req.name.clone();
41    match tokio::task::spawn_blocking(move || {
42        crate::backend::name_resolution::resolve_name_to_uid(&mstore, registry, &name)
43    })
44    .await
45    {
46        // The store could not be read: refuse (503), so the MCP fails the
47        // tool call instead of sending a bare name that a same-named live
48        // agent could take (Codex P1 on #3563).
49        Ok(Err(e)) => (StatusCode::SERVICE_UNAVAILABLE, Json(json!({ "error": e }))),
50        Ok(Ok(resolution)) => {
51            let mut body = serde_json::to_value(&resolution).unwrap_or_else(|_| json!({ "resolution": "none" }));
52            // A name nobody answers to: the ids it most likely meant, so the refusal can offer them.
53            if matches!(resolution, crate::backend::name_resolution::NameResolution::None) {
54                body["did_you_mean"] = json!(did_you_mean(&state, &req.name).await);
55            }
56            (StatusCode::OK, Json(body))
57        }
58        Err(e) => (
59            StatusCode::INTERNAL_SERVER_ERROR,
60            Json(json!({ "error": format!("resolve task failed: {e}") })),
61        ),
62    }
63}
64
65/// The ids of the agents on this computer that a typed name nobody answers to most likely meant, best first.
66async fn did_you_mean(state: &AppState, typed: &str) -> Vec<String> {
67    let (mstore, registry, typed) = (state.mstore.clone(), state.reactive_handler, typed.to_string());
68    // A synchronous store read, so off the async worker (incident #1782).
69    tokio::task::spawn_blocking(move || {
70        let ids = crate::backend::name_resolution::known_agent_ids(&mstore, registry);
71        crate::backend::name_resolution::closest_ids(&typed, &ids)
72    })
73    .await
74    .unwrap_or_default()
75}
76
77/// A message `body` queued at the relay for `typed`, with the ids `typed` most likely meant when it is a name
78/// that answers to no agent here (a typo, a workspace folder's form), for the sender to send it again to.
79pub(crate) async fn with_did_you_mean(state: &AppState, typed: &str, mut body: Value) -> Value {
80    let close = did_you_mean(state, typed).await;
81    if !close.is_empty() {
82        body["did_you_mean"] = json!(close);
83    }
84    body
85}
86
87/// The same resolution for a name typed by an agent of another machine in a remote operation
88/// (`remote_ops`), which is as much a boundary as the MCP tool argument: that agent can't know a uid
89/// here. Internal code still never calls `resolve_name_to_uid` itself (`check-name-resolver-callers.sh`).
90pub(crate) async fn resolve_typed_name(
91    state: &AppState,
92    name: &str,
93) -> Result<crate::backend::name_resolution::NameResolution, String> {
94    let mstore = state.mstore.clone();
95    let registry = state.reactive_handler;
96    let name = name.to_string();
97    // A synchronous store read, so off the async worker (incident #1782).
98    tokio::task::spawn_blocking(move || crate::backend::name_resolution::resolve_name_to_uid(&mstore, registry, &name))
99        .await
100        .map_err(|e| format!("resolve task failed: {e}"))?
101}