Skip to main content

agentmux_srv/server/reactive/
register.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `POST /agentmux/reactive/register`: a pane says which agent it runs.
5
6use axum::{
7    extract::State,
8    http::StatusCode,
9    response::{IntoResponse, Json, Response},
10};
11use serde_json::json;
12
13use crate::backend::blockcontroller;
14use crate::backend::reactive::registry as agent_registry;
15use crate::backend::{base, subagent_watcher};
16use crate::server::AppState;
17
18#[derive(serde::Deserialize)]
19pub(in crate::server) struct RegisterRequest {
20    agent_id: String,
21    block_id: String,
22    tab_id: Option<String>,
23}
24
25pub(in crate::server) async fn handle_reactive_register(
26    State(state): State<AppState>,
27    caller: Option<axum::Extension<crate::server::caller::Caller>>,
28    Json(mut req): Json<RegisterRequest>,
29) -> Response {
30    let sent_name = req.agent_id.clone();
31    req.agent_id = crate::backend::reactive::sanitize::route_name(&sent_name).unwrap_or_default();
32    tracing::info!(agent_id = %req.agent_id, block_id = %req.block_id, "reactive register request");
33    let uid = block_uid(&state, &req.block_id).await;
34    if let Some(refusal) = crate::server::pane_binding::register_refusal(&state, caller.as_deref(), &req.block_id, uid.as_deref(), &sent_name, &req.agent_id).await {
35        return refusal;
36    }
37    if let Some(refusal) = live_in_another_instance(&state, &req, uid.as_deref()).await {
38        return refusal;
39    }
40    match state.reactive_handler.register_agent_full(
41        &req.agent_id,
42        &req.block_id,
43        req.tab_id.as_deref(),
44        0,
45        None,
46        uid.as_deref(),
47        "registration.no_uid.http_register",
48    ) {
49        Ok(()) => {
50            announce_registration(&state, &req);
51            Json(json!({"success": true})).into_response()
52        }
53        Err(e) => (
54            StatusCode::BAD_REQUEST,
55            Json(json!({"error": e})),
56        )
57            .into_response(),
58    }
59}
60
61/// Identity M2 (spec §4.4.1 row 3): a presence signal keyed by block. The sent name, as its
62/// route name, becomes the display binding and the cross-instance registries' name, but
63/// identity is NOT taken from it (it may be a stale meta value or an id the agent emitted over
64/// OSC). The UID comes from the row the server made for this block, read on `spawn_blocking`
65/// like every async-handler store read (#1782).
66async fn block_uid(state: &AppState, block_id: &str) -> Option<String> {
67    let mstore = state.mstore.clone();
68    let block_id = block_id.to_string();
69    tokio::task::spawn_blocking(move || crate::backend::agent_resolve::uid_for_block(&mstore, &block_id))
70        .await
71        .unwrap_or_else(|e| {
72            tracing::warn!(error = %e, "reactive register: uid lookup task failed — registering by name");
73            None
74        })
75}
76
77/// One live instance per agent (SPEC_AGENT_SINGLE_LIVE_INSTANCE_2026_09_24 Phase 1, I9): a pane
78/// whose agent runs in another instance on this host must not register it. The cross-instance
79/// registries written below send this agent's jekts to the freshest entry, so registering here
80/// would pull the live instance's messages to a pane refused its turns. The frontend only logs a
81/// failed registration; it doesn't retry.
82async fn live_in_another_instance(state: &AppState, req: &RegisterRequest, uid: Option<&str>) -> Option<Response> {
83    let uid = uid?;
84    let refusal = crate::backend::agent_admission::check_before_spawn(
85        crate::backend::agent_admission::lease_store_for(state.mstore.shared_agent_registry()),
86        uid,
87        &req.agent_id,
88        &state.boot_id,
89    )
90    .await
91    .err()?;
92    tracing::warn!(
93        agent_id = %req.agent_id,
94        block_id = %req.block_id,
95        uid,
96        "reactive register refused: agent is live in another AgentMux instance on this host"
97    );
98    Some((StatusCode::CONFLICT, Json(json!({ "success": false, "error": refusal }))).into_response())
99}
100
101/// What a registration that went through sets going: the block's controller, the registries other
102/// instances read, the subagent watch, the cloud subscription and the Swarm's event.
103fn announce_registration(state: &AppState, req: &RegisterRequest) {
104    // Refresh the block's own captured identity too (#2697): this path can re-register a
105    // block_id under a different agent_id (a rename, a changed cmd:env), and a stale
106    // controller `agent_id()` would make `inject_message_inner`'s recipient check (#2695)
107    // reject the agent's own correctly-addressed messages. `None` (untracked block, or a
108    // controller without `agent_id()`/`set_agent_id()`) is a no-op.
109    if let Some(ctrl) = blockcontroller::get_controller(&req.block_id) {
110        ctrl.set_agent_id(Some(req.agent_id.clone()));
111    }
112
113    // Also write to the cross-instance file registry so other AgentMux instances can
114    // forward inject requests here.
115    let data_dir = base::get_mux_data_dir();
116    agent_registry::write(&data_dir, &req.agent_id, &state.local_web_url, &req.block_id);
117
118    // And to the host-global shared registry (Tier 2b), so instances in OTHER channels
119    // reach this agent too (#1916).
120    agent_registry::write_shared_from_env(&req.agent_id, &state.local_web_url, &req.block_id);
121
122    watch_subagents(state, req);
123
124    // Subscribe the display and stable names; cloud senders address the stable one.
125    if let Some(sub) = crate::muxbus::cloud_subscriber::get_global_subscriber() {
126        state.reactive_handler.names_for_block(&req.block_id).iter().for_each(|n| sub.add_agent(n));
127    }
128
129    // Notify the Swarm view so it calls AgentTrackedBlocksCommand and shows this pane. A
130    // dedicated event name, because `useProcessCount` (on agent:process-added/-exited)
131    // would take this for a phantom OS process and show a spurious ⚙ N badge or the
132    // kill-tree modal on pane close.
133    state.broker.publish_event::<crate::backend::mps_events::AgentReactiveRegistered>(&crate::backend::mps_events::BlockRefEvent { block_id: req.block_id.clone() }, vec![format!("block:{}", req.block_id)], 0);
134}
135
136/// Auto-watch this agent's Claude Code config dir for subagent JSONL files. `block_id`
137/// stamps subagent events with the owning pane so the frontend routes ⚡ panels to it
138/// only. The dir comes from the block's own `cmd:env` (see `resolve_claude_config_dir`).
139fn watch_subagents(state: &AppState, req: &RegisterRequest) {
140    let block = state.mstore.get::<crate::backend::obj::Block>(&req.block_id).ok().flatten();
141    let empty_meta = crate::backend::obj::MetaMapType::new();
142    let meta = || block.as_ref().map(|b| &b.meta).unwrap_or(&empty_meta);
143    let bound_dir_now = || {
144        crate::identity::resolver::resolve_bound_oauth_config_dir(&state.mstore, &state.id_store, &state.identity_store, &req.block_id)
145    };
146    // An identity-bound agent's real CLAUDE_CONFIG_DIR is never the stale `cmd:env`
147    // snapshot (`resolve_claude_config_dir`,
148    // SPEC_SUBAGENT_WATCHER_IDENTITY_BOUND_CONFIG_DIR_2026_08_22.md).
149    let bound_dir = bound_dir_now();
150    crate::identity::foreign_dir::heal_block_config_dir_env(&state.mstore, block.as_ref(), bound_dir.as_deref());
151    let Some(config_dir) = subagent_watcher::resolve_claude_config_dir(meta(), &req.agent_id, bound_dir) else { return };
152    state.subagent_watcher.watch_agent(&req.agent_id, &req.block_id, config_dir.clone());
153
154    // Re-resolve now that the watch is installed (#2980): an `agent_identity_link`
155    // write on another thread can commit between resolving `config_dir` and
156    // `watch_agent`, and the bind's own `recheck_all_watched_agents` then finds nothing
157    // to correct, with no later bind guaranteed to retrigger it. `recheck_config_dir`
158    // is a no-op when nothing changed. Here, not in `watch_agent`, because this is the
159    // one site that derives `config_dir` from identity binding (baking it into
160    // `watch_agent` broke its other callers).
161    if let Some(fresh_dir) = subagent_watcher::resolve_claude_config_dir(meta(), &req.agent_id, bound_dir_now()) {
162        state.subagent_watcher.recheck_config_dir(&req.agent_id, fresh_dir);
163    }
164
165    // A block with a persisted session id is resuming: backfill only THAT session's
166    // subagents, so a reopened pane shows what it had without flooding in every other
167    // session of this identity. A new session has nothing to backfill; the live watcher
168    // picks up subagents as the Task tool spawns them.
169    let session_id = block
170        .as_ref()
171        .map(|b| crate::backend::obj::meta_get_string(&b.meta, crate::backend::blockcontroller::core::META_SESSION_ID, ""))
172        .unwrap_or_default();
173    if !session_id.is_empty() {
174        state.subagent_watcher.scan_session_subagents(&req.agent_id, &req.block_id, &config_dir, &session_id);
175    }
176}