Skip to main content

agentmux_srv/server/app_api/
agent_spawn.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `POST /api/v1/agent/spawn`, the `Agents` tool's `spawn`
5//! (docs/specs/SPEC_AGENT_WORKERS_2026_10_15.md §3.1, Phase A): the calling
6//! agent, the leader, opens a worker: a new agent built from its own
7//! definition, on the model it names, in a pane to the right of its own.
8//! A worker is not a fork (the pane's Fork, an exact copy that carries the
9//! conversation): it isn't among the leader's forks, and starts without the
10//! leader's conversation or Personal Memory, with the leader's definition
11//! (instructions, skills), Global Memory and, from the MCP server, the brief
12//! it is sent as the leader's own message.
13//!
14//! Launching an agent spends tokens until someone stops it, so (§3.5): only
15//! a verified agent spawns, host or container (a container leader gets container workers: same image,
16//! each with its own container and workspace), a worker doesn't, a leader has at most
17//! [`MAX_LIVE_WORKERS`], and unless the user's own turn asked for it the user is told first, in the
18//! leader's pane, by a card with a countdown that goes ahead on its own (`announce_start`).
19
20use axum::extract::State;
21use axum::http::StatusCode;
22use axum::response::{IntoResponse, Response};
23use axum::Json;
24
25use agentmux_common::api_types::SpawnAgentRequest;
26
27use super::*;
28
29mod container;
30mod create;
31pub(crate) mod import;
32mod many;
33pub(crate) mod route;
34pub(super) mod team;
35pub(crate) use create::handle_agent_create;
36pub(crate) use import::handle_agent_import;
37pub(crate) use many::handle_agent_spawn_many;
38
39/// The worker pane's leader, `{agent, id, block_id}`: the leader's name, its
40/// definition id and its pane. srv writes it when it opens the worker; no
41/// client can (`browser_owner::srv_only_keys`).
42pub(crate) const COACHED_BY_META_KEY: &str = "agent:coached_by";
43
44/// Live workers a leader may have at once (§3.5).
45pub(crate) const MAX_LIVE_WORKERS: usize = 12;
46
47/// The agent that made this one with `Agents create`, `{agent, id}`, kept on the new agent's definition (agent
48/// content) so that agent can delete it again (`Agents delete`). srv writes it; a client may not, and a fork does
49/// not inherit it.
50pub(crate) const CREATED_BY_CONTENT: &str = "agent:created_by";
51
52/// Content only srv writes, and that a fork of the agent does not take along.
53pub(crate) fn written_only_by_srv(content_type: &str) -> bool {
54    content_type == WORKER_OF_CONTENT || content_type == CREATED_BY_CONTENT || content_type == crate::backend::model_gateway::launch::CONTENT_TYPE || content_type == crate::backend::model_gateway::switch::PREVIOUS_TYPE
55        || content_type == crate::backend::model_gateway::launch::LEAVING_TYPE
56}
57
58/// The agent that made `def_id`: the one that created it, or the leader it is a worker of.
59pub(crate) fn creator_of(mstore: &Store, def_id: &str) -> Option<String> {
60    let id_in = |content_type: &str| -> Option<String> {
61        let content = mstore.agent_content_get(def_id, content_type).ok()??;
62        let value: serde_json::Value = serde_json::from_str(&content.content).ok()?;
63        value.get("id")?.as_str().map(str::to_string)
64    };
65    id_in(CREATED_BY_CONTENT).or_else(|| id_in(WORKER_OF_CONTENT))
66}
67
68/// `setagentcontent`'s check (a client's write): which agent a worker reports
69/// to, and which agent made another, are srv's to write: clearing the first would let a worker spawn and free
70/// its leader's place, and writing the second would let an agent delete one it did not make.
71pub(crate) fn client_may_write_content(content_type: &str) -> Result<(), String> {
72    if written_only_by_srv(content_type) {
73        return Err(format!("{content_type} is written only by AgentMux itself"));
74    }
75    Ok(())
76}
77
78const MAX_NAME_CHARS: usize = 64;
79
80#[derive(Debug, serde::Serialize)]
81pub(crate) struct SpawnAgentResult {
82    /// The worker's definition id.
83    pub agent_id: String,
84    pub name: String,
85    /// What `Message` `send` addresses it by (its AGENTMUX_AGENT_ID).
86    pub message_to: String,
87    pub block_id: String,
88    pub tab_id: String,
89    pub provider: String,
90    pub model: Option<String>,
91    /// The model route it runs on (`Agents routes`); absent when it runs on its harness's own sign-in.
92    #[serde(skip_serializing_if = "Option::is_none")]
93    pub route: Option<String>,
94    pub effort: Option<String>,
95    /// The account it runs on: its name, and its id.
96    pub account: String,
97    pub account_id: String,
98    /// Why it isn't on the account asked for or the leader's, when it isn't.
99    pub account_note: Option<String>,
100    /// Whether the user was shown a card with a countdown (the turn wasn't the user's own, and neither
101    /// "Always" nor the "Agents may start agents" setting applied).
102    pub asked_user: bool,
103    /// `native` or `container`, and the image of a container agent.
104    pub runtime: String,
105    pub container_image: Option<String>,
106}
107
108/// `native` / `container` for a definition's `agent_type`, and its image when it has one.
109fn runtime_of(def: &AgentDefinition) -> (String, Option<String>) {
110    if def.runtime().is_container() {
111        ("container".to_string(), Some(def.container_image.clone()).filter(|i| !i.is_empty()))
112    } else {
113        ("native".to_string(), None)
114    }
115}
116
117#[derive(Debug)]
118pub(crate) struct SpawnError {
119    status: StatusCode,
120    message: String,
121}
122
123fn refuse(status: StatusCode, message: impl Into<String>) -> SpawnError {
124    SpawnError { status, message: message.into() }
125}
126
127pub(crate) async fn handle_agent_spawn(
128    State(state): State<AppState>,
129    caller: Option<axum::Extension<crate::server::caller::Caller>>,
130    Json(req): Json<SpawnAgentRequest>,
131) -> Response {
132    match spawn_worker(&state, caller.as_deref(), req).await {
133        Ok(result) => Json(json!(result)).into_response(),
134        Err(e) => (e.status, Json(json!({ "error": e.message }))).into_response(),
135    }
136}
137
138/// The leader as srv knows it: its pane and its definition.
139struct Leader {
140    block_id: String,
141    def: AgentDefinition,
142}
143
144async fn spawn_worker(
145    state: &AppState,
146    caller: Option<&crate::server::caller::Caller>,
147    req: SpawnAgentRequest,
148) -> Result<SpawnAgentResult, SpawnError> {
149    let leader = leader_of(state, caller, &req.auth)?;
150    spawn_with(state, leader, &req, false).await
151}
152
153/// Open a worker for `leader` as `req` asks. `operator_approved`: the
154/// operator made the decision beforehand (a job they created), so the user
155/// isn't asked; the limits and the leader's checks still apply.
156async fn spawn_with(
157    state: &AppState,
158    leader: Leader,
159    req: &SpawnAgentRequest,
160    operator_approved: bool,
161) -> Result<SpawnAgentResult, SpawnError> {
162    let brief = req.brief.trim();
163    if brief.is_empty() {
164        return Err(refuse(StatusCode::BAD_REQUEST, "INVALID_ARG: a brief is required: the worker's task, its first message"));
165    }
166    let name = req.name.as_deref().map(str::trim).filter(|n| !n.is_empty());
167    if let Some(n) = name {
168        if n.chars().count() > MAX_NAME_CHARS || n.chars().any(char::is_control) {
169            return Err(refuse(StatusCode::BAD_REQUEST, format!("INVALID_ARG: a name is at most {MAX_NAME_CHARS} characters, on one line")));
170        }
171        if let Err(e) = crate::backend::reserved_names::check_all(&[n]) {
172            return Err(refuse(StatusCode::BAD_REQUEST, format!("INVALID_ARG: {e}")));
173        }
174    }
175    let (provider, mut runtime) = route::choose(state, &leader, &req.route, req.model.as_deref(), req.effort.as_deref())?;
176    runtime.placement = container::decide_here(state, &req.container, &leader.def, &leader.def, &provider).await?;
177    let tab_id = super::agent_block::resolve_tab_id_or_active(&state.mstore, &leader.block_id)
178        .map_err(|e| refuse(StatusCode::CONFLICT, format!("NO_TAB: your pane isn't in a tab: {e}")))?;
179    // Held until the worker's pane exists (or nothing was made), so a second
180    // call counts it: parallel spawns can't each see room for one more.
181    let lock = leader_lock(&leader.def.id);
182    let _one_at_a_time = lock.lock().await;
183    let live = live_workers_of(&state.mstore, &leader.def.id);
184    if live >= MAX_LIVE_WORKERS {
185        return Err(refuse(
186            StatusCode::CONFLICT,
187            format!(
188                "TOO_MANY_WORKERS: you have {live} workers open, the most at once is {MAX_LIVE_WORKERS}; close one \
189                 (Stop pane) when its work is done, then spawn again"
190            ),
191        ));
192    }
193
194    let account = route::account(state, &leader, &provider, &runtime, req.account.as_deref())?;
195
196    let asked_user = if operator_approved {
197        false
198    } else {
199        consent(state, &leader, name, runtime.model.as_deref(), &runtime, &account, brief, &req.user_instruction).await?
200    };
201
202    let name = match name {
203        Some(n) => n.to_string(),
204        None => next_worker_name(&state.mstore, &leader.def.name, &std::collections::HashSet::new()),
205    };
206    let tab_id = team::team_tab(state, &leader, &tab_id).await;
207    let (worker, opened) = launch(state, &leader, &name, &tab_id, &runtime, &account, None).await?;
208    tracing::info!(
209        leader = %leader.def.name,
210        worker = %worker.name,
211        block_id = %opened.block_id,
212        model = ?runtime.model,
213        account = %account.label,
214        switched = account.note.is_some(),
215        asked_user,
216        "agent.spawn: a worker was launched"
217    );
218    let (kind, container_image) = runtime_of(&worker);
219    Ok(SpawnAgentResult {
220        agent_id: worker.id,
221        name: worker.name,
222        message_to: worker.slug,
223        block_id: opened.block_id,
224        tab_id: opened.tab_id,
225        provider: opened.provider,
226        route: runtime.route.as_ref().map(|c| c.route.clone()),
227        model: runtime.route.map(|c| c.model).or(runtime.model),
228        effort: runtime.effort,
229        account: account.label,
230        account_id: account.id,
231        account_note: account.note,
232        asked_user,
233        runtime: kind,
234        container_image,
235    })
236}
237
238/// Build the worker from the leader's definition and open it. A worker that
239/// doesn't open is removed again, with any pane the open made before it
240/// failed: the user didn't get a worker, so there is no definition of one in
241/// My Agents and no marked pane taking up one of the leader's places.
242async fn launch(
243    state: &AppState,
244    leader: &Leader,
245    name: &str,
246    tab_id: &str,
247    runtime: &WorkerRuntime,
248    account: &WorkerAccount,
249    // The stand-in key a batch holds this worker's room under: it becomes the worker's own as soon as
250    // the worker exists, so its start is the one that room is for.
251    reserved: Option<&str>,
252) -> Result<(AgentDefinition, AgentOpenResult), SpawnError> {
253    let mut worker = crate::server::agent_handlers::copy_definition(
254        &state.mstore,
255        &state.id_store,
256        &state.identity_store,
257        &leader.def.id,
258        name,
259        false,
260    )
261    .map_err(|e| {
262        let status = if e.contains("already exists") { StatusCode::CONFLICT } else { StatusCode::INTERNAL_SERVER_ERROR };
263        refuse(status, e)
264    })?;
265    state.broker.publish_event::<crate::backend::mps_events::AgentsChanged>(&(), vec![], 0);
266    if let Some(stand_in) = reserved {
267        crate::server::agent_lifecycle::rekey_reservation(state, stand_in, &worker.id);
268    }
269    let placed = container::apply(state, &mut worker, &runtime.placement).and_then(|()| route::apply(state, &mut worker, runtime));
270    let marked = placed.and_then(|()| {
271        state
272            .mstore
273            .agent_content_set(&crate::backend::storage::store::AgentContent {
274                agent_id: worker.id.clone(),
275                content_type: WORKER_OF_CONTENT.to_string(),
276                content: json!({ "agent": leader.def.name, "id": leader.def.id }).to_string(),
277                updated_at: agentmux_common::time::now_ms(),
278            })
279            .map_err(|e| format!("mark it as a worker: {e}"))
280    });
281    let linked = marked.and_then(|()| {
282        if account.id.is_empty() {
283            return Ok(());
284        }
285        state
286            .identity_store
287            .agent_identity_link(&worker.id, &account.id, &account.provider)
288            .map_err(|e| format!("link its account: {e}"))
289    });
290    let opened = match linked {
291        Ok(()) => open_worker(state, leader, &worker, tab_id, runtime).await,
292        Err(e) => Err(e),
293    };
294    match opened {
295        Ok(opened) => Ok((worker, opened)),
296        Err(e) => {
297            discard_worker(state, tab_id, &worker.id).await;
298            crate::server::agent_lifecycle::release_start(state, &worker.id);
299            Err(refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("the worker couldn't be opened, and was removed: {e}")))
300        }
301    }
302}
303
304/// The verified caller, if it may spawn: an agent's own pane, host or container, not a
305/// worker's.
306fn leader_of(
307    state: &AppState,
308    caller: Option<&crate::server::caller::Caller>,
309    auth: &agentmux_common::api_types::UiAutomationAuth,
310) -> Result<Leader, SpawnError> {
311    let block_id = crate::server::ui_handlers::verified_block_id(state, caller, auth)
312        .map_err(|e| refuse(StatusCode::UNAUTHORIZED, format!("could not verify which agent is asking: {e}")))?;
313    leader_at(state, block_id)
314}
315
316/// The leader whose pane is `block_id`, if it may spawn: an agent of any kind, host or container, not a
317/// worker. A container leader's worker is a container worker (`copy_definition` keeps the type and the image).
318fn leader_at(state: &AppState, block_id: String) -> Result<Leader, SpawnError> {
319    let block = state
320        .mstore
321        .get::<Block>(&block_id)
322        .ok()
323        .flatten()
324        .ok_or_else(|| refuse(StatusCode::CONFLICT, "NOT_AN_AGENT_PANE: your pane is gone"))?;
325    let def_id = obj::meta_get_string(&block.meta, "agentId", "");
326    // Its pane's mark, or its definition's: a worker reopened from My Agents
327    // has only the latter.
328    if block.meta.get(COACHED_BY_META_KEY).is_some_and(|v| !v.is_null()) || worker_of(&state.mstore, &def_id).is_some() {
329        return Err(refuse(
330            StatusCode::FORBIDDEN,
331            "WORKER_CANNOT_SPAWN: you are a worker; only the agent that coaches you can start workers",
332        ));
333    }
334    let def = state
335        .mstore
336        .agent_def_list()
337        .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("agent.spawn: {e}")))?
338        .into_iter()
339        .find(|d| !def_id.is_empty() && d.id == def_id)
340        .ok_or_else(|| refuse(StatusCode::CONFLICT, "NOT_AN_AGENT_PANE: your pane isn't an agent from My Agents"))?;
341    Ok(Leader { block_id, def })
342}
343
344/// Open a worker for the job whose leader is `leader_uid`, from its running
345/// pane: the same path as an agent's `spawn`, without asking the user, since
346/// the operator created the job. `MAX_LIVE_WORKERS` and "workers can't
347/// spawn" apply.
348pub(crate) async fn spawn_for_job(
349    state: &AppState,
350    leader_uid: &str,
351    brief: &str,
352    model: Option<String>,
353    account: Option<String>,
354) -> Result<SpawnAgentResult, String> {
355    spawn_beside_leader(state, leader_uid, brief, model, account, true).await
356}
357
358/// Open a worker for a drone's Spawn block: the path of [`spawn_for_job`], but the person is told first,
359/// by the card with a countdown that goes ahead on its own, unless their settings already allow agents to start
360/// agents. A drone run isn't known to be one the operator started, so the block doesn't count as their approval.
361pub(crate) async fn spawn_for_drone(
362    state: &AppState,
363    leader_uid: &str,
364    brief: &str,
365    model: Option<String>,
366    account: Option<String>,
367) -> Result<SpawnAgentResult, String> {
368    spawn_beside_leader(state, leader_uid, brief, model, account, false).await
369}
370
371async fn spawn_beside_leader(
372    state: &AppState,
373    leader_uid: &str,
374    brief: &str,
375    model: Option<String>,
376    account: Option<String>,
377    operator_approved: bool,
378) -> Result<SpawnAgentResult, String> {
379    let block_id = state
380        .reactive_handler
381        .block_for_uid(leader_uid)
382        .ok_or_else(|| "the leader isn't running: start it, or the worker has no pane to open beside".to_string())?;
383    let leader = leader_at(state, block_id).map_err(|e| e.message)?;
384    let req = SpawnAgentRequest {
385        auth: agentmux_common::api_types::UiAutomationAuth { agent_id: leader.def.name.clone(), ts_secs: 0, sig: String::new() },
386        name: None,
387        model,
388        effort: None,
389        account,
390        brief: brief.to_string(),
391        container: Default::default(),
392        route: Default::default(),
393        user_instruction: String::new(),
394    };
395    spawn_with(state, leader, &req, operator_approved).await.map_err(|e| e.message)
396}
397
398/// The account and provider the next worker of a `spawn` job led by
399/// `leader_uid` would run on (`choose_account`), without opening it: what the
400/// spending caps weigh before the run starts (jobs spec §5.3). `None` when
401/// the leader isn't running or no account can take a worker.
402pub(crate) fn account_for_job(state: &AppState, leader_uid: &str, requested: Option<&str>) -> Option<(String, String)> {
403    let block_id = state.reactive_handler.block_for_uid(leader_uid)?;
404    let leader = leader_at(state, block_id).ok()?;
405    let provider = state.id_store.resolve_effective_provider_id(&leader.def);
406    let account = choose_account(state, &leader, &provider, requested).ok()?;
407    Some((account.id, account.provider))
408}
409
410/// The worker's remembered runtime (`agentlastruntime`): the leader's, with
411/// the requested model and effort over it.
412#[derive(Debug, Default, PartialEq, Eq)]
413pub(crate) struct WorkerRuntime {
414    /// The normalized JSON to store; empty when there is nothing to remember.
415    stored: String,
416    model: Option<String>,
417    effort: Option<String>,
418    /// Where it runs, when it was asked for (`runtime`, `container_image`, `memory_mb`, `cpus`).
419    placement: container::Placement,
420    /// The model route and model it runs on, when it has one (`Agents routes`).
421    route: Option<crate::backend::model_gateway::launch::Choice>,
422    /// What the approval says about that route and who pays.
423    route_line: String,
424    /// The route was named, or differs from the leader's: the person is asked even when their own turn asked for the
425    /// worker, because their words asked for a worker and not for spending their key.
426    route_asked: bool,
427    /// Its harness, when that is not its leader's.
428    harness: Option<String>,
429}
430
431pub(crate) fn worker_runtime(
432    provider: &str,
433    leader_runtime: &str,
434    model: Option<&str>,
435    effort: Option<&str>,
436) -> Result<WorkerRuntime, String> {
437    use crate::backend::agent_runtime::Remembered;
438    let model = model.map(str::trim).filter(|m| !m.is_empty());
439    let effort = effort.map(str::trim).filter(|e| !e.is_empty());
440    let leader = Remembered::parse(provider, leader_runtime);
441    if provider != "claude" {
442        if model.is_some() || effort.is_some() {
443            return Err(format!("a model and effort can be chosen only for a Claude worker for now; this agent runs {provider}"));
444        }
445        return Ok(WorkerRuntime::default());
446    }
447    let mut obj = serde_json::Map::new();
448    if let Some(mode) = &leader.permission_mode {
449        obj.insert("permissionMode".into(), json!(mode));
450    }
451    if let Some(m) = model.map(str::to_string).or(leader.model.clone()) {
452        obj.insert("model".into(), json!(m));
453    }
454    if let Some(e) = effort.map(str::to_string).or(leader.effort.clone()) {
455        obj.insert("effort".into(), json!(e));
456    }
457    let raw = serde_json::Value::Object(obj).to_string();
458    // What a launch will read back: a value it would drop is refused here.
459    let parsed = Remembered::parse(provider, &raw);
460    if model.is_some() && parsed.model.as_deref() != model {
461        return Err(format!("unknown model {:?}: use opus, sonnet, haiku or a claude-… model id", model.unwrap_or("")));
462    }
463    if effort.is_some() && parsed.effort.as_deref() != effort {
464        return Err(format!("unknown effort {:?}: use low, medium, high, xhigh or max", effort.unwrap_or("")));
465    }
466    let stored = crate::backend::storage::agents::normalize_last_runtime(&raw)?;
467    Ok(WorkerRuntime { stored, model: parsed.model, effort: parsed.effort, ..Default::default() })
468}
469
470/// One spawn at a time per leader, from counting its workers to opening the
471/// new one, including the wait for the user. Like `agent_open`'s locks, it
472/// serializes only this process's calls.
473static LEADER_LOCKS: std::sync::LazyLock<
474    std::sync::Mutex<std::collections::HashMap<String, std::sync::Arc<tokio::sync::Mutex<()>>>>,
475> = std::sync::LazyLock::new(Default::default);
476
477pub(crate) fn leader_lock(leader_def_id: &str) -> std::sync::Arc<tokio::sync::Mutex<()>> {
478    let mut locks = LEADER_LOCKS.lock().unwrap_or_else(|e| e.into_inner());
479    locks.entry(leader_def_id.to_string()).or_default().clone()
480}
481
482/// The account a worker runs on.
483#[derive(Debug, Clone, PartialEq, Eq)]
484pub(crate) struct WorkerAccount {
485    pub id: String,
486    /// Its name as the user sees it (display name, email, else name).
487    pub label: String,
488    /// The link's provider, the leader's.
489    pub provider: String,
490    /// Why it isn't the account asked for or the leader's, when it isn't.
491    pub note: Option<String>,
492}
493
494/// The account to run the worker on (§3.5): the one asked for, else the
495/// leader's, else, when the leader's can't run (`account_blocks`), the first
496/// of the user's other accounts for the provider that can, with a note
497/// saying why. Refused when the one asked for can't run, or none can.
498fn choose_account(state: &AppState, leader: &Leader, provider: &str, requested: Option<&str>) -> Result<WorkerAccount, SpawnError> {
499    use crate::backend::providers::resolve_provider_alias;
500    let provider = resolve_provider_alias(provider).to_string();
501    // The channel's own accounts and their sign-in state: what a spawn can
502    // launch with (`resolve_account_for_spawn` reads `id_store` only). The
503    // global mirror can list an account signed in only in another channel.
504    let accounts: Vec<IdentityAccount> = state
505        .id_store
506        .identity_list(None)
507        .map_err(|e| refuse(StatusCode::INTERNAL_SERVER_ERROR, format!("agent.spawn: accounts: {e}")))?
508        .into_iter()
509        .filter(|a| resolve_provider_alias(&a.provider) == provider)
510        .collect();
511    let blocked = account_blocks(state, &accounts);
512    let pick = |a: &IdentityAccount, note: Option<String>| WorkerAccount {
513        id: a.id.clone(),
514        label: account_label_in(a, &accounts),
515        provider: provider.clone(),
516        note,
517    };
518    let usable = || accounts.iter().find(|o| !blocked.contains_key(&o.id));
519    if let Some(wanted) = requested.map(str::trim).filter(|w| !w.is_empty()) {
520        let Some(a) = accounts.iter().find(|a| account_matches(a, wanted, &accounts)) else {
521            let known: Vec<String> = accounts.iter().map(|a| account_label_in(a, &accounts)).collect();
522            return Err(refuse(
523                StatusCode::BAD_REQUEST,
524                format!("UNKNOWN_ACCOUNT: no {provider} account {wanted:?}; the user's are: {}", known.join(", ")),
525            ));
526        };
527        if let Some(why) = blocked.get(&a.id) {
528            return Err(refuse(
529                StatusCode::CONFLICT,
530                format!("ACCOUNT_CANT_RUN: {} {why}; name another account, or leave account out", account_label_in(a, &accounts)),
531            ));
532        }
533        return Ok(pick(a, None));
534    }
535    let leader_account = crate::identity::resolver::effective_identity_links(&state.mstore, &state.identity_store, &leader.def)
536        .unwrap_or_default()
537        .into_iter()
538        .filter(|l| resolve_provider_alias(&l.provider) == provider)
539        .find_map(|l| accounts.iter().find(|a| a.id == l.account_id));
540    match (leader_account, usable()) {
541        (Some(a), _) if !blocked.contains_key(&a.id) => Ok(pick(a, None)),
542        (Some(a), Some(other)) => {
543            let note = format!("Your account {} {}, so it runs on {} instead.", account_label_in(a, &accounts), blocked[&a.id], account_label_in(other, &accounts));
544            Ok(pick(other, Some(note)))
545        }
546        (Some(a), None) => Err(refuse(
547            StatusCode::CONFLICT,
548            format!("NO_ACCOUNT: your account {} {}, and none of the user's other {provider} accounts can run", account_label_in(a, &accounts), blocked[&a.id]),
549        )),
550        (None, Some(other)) => Ok(pick(other, Some(format!("You have no {provider} account linked, so it runs on {}.", account_label_in(other, &accounts))))),
551        (None, None) => Err(refuse(StatusCode::CONFLICT, format!("NO_ACCOUNT: none of the user's {provider} accounts can run"))),
552    }
553}
554
555/// The accounts that can't take a worker now, and why: signed out (its
556/// status), or a pane on it whose last run ended on the plan's usage limit or
557/// a refused sign-in (`agent:last_failure`, which its next clean turn clears).
558/// A usage limit counts until its reset, when one is known, even with the
559/// pane still open (SPEC_UNRESPONSIVE_AGENTS_2026_10_23.md §6.3).
560pub(crate) fn account_blocks(state: &AppState, accounts: &[IdentityAccount]) -> std::collections::HashMap<String, String> {
561    account_blocks_at(state, accounts, agentmux_common::time::now_ms_u64())
562}
563
564/// [`account_blocks`] at `now_ms`.
565pub(crate) fn account_blocks_at(state: &AppState, accounts: &[IdentityAccount], now_ms: u64) -> std::collections::HashMap<String, String> {
566    use crate::agents::failure::FailureClass;
567    let mut blocked = std::collections::HashMap::new();
568    for a in accounts {
569        if matches!(a.status.as_str(), "expired" | "needs_reauth" | "invalid") {
570            blocked.insert(a.id.clone(), "needs the user to sign in again".to_string());
571        }
572    }
573    let Ok(blocks) = super::agent_block::blocks_in_tabs_or_parked(&state.mstore) else {
574        return blocked;
575    };
576    for (block, _) in blocks {
577        let failure = crate::backend::agent_state::failure_of_block(&block);
578        let why = match failure.map(|f| (f.code, f.resets_at_ms)) {
579            Some((FailureClass::UsageLimit, reset)) if reset.is_none_or(|r| r > now_ms) => {
580                "is out of quota (a pane on it hit the plan's usage limit)"
581            }
582            Some((FailureClass::Auth, _)) => "had its sign-in refused",
583            _ => continue,
584        };
585        // The account that run was on (the rule `unavailable_of_block` shares).
586        for account in crate::backend::agent_state::run_accounts_of_block(&state.identity_store, &block) {
587            if accounts.iter().any(|a| a.id == account) {
588                blocked.entry(account).or_insert_with(|| why.to_string());
589            }
590        }
591    }
592    blocked
593}
594
595/// `agent:last_failure` (`blockcontroller::core::META_LAST_FAILURE`).
596#[cfg(test)]
597const LAST_FAILURE_META_KEY: &str = "agent:last_failure";
598
599/// The leader a worker belongs to, and the content type that records it. They live in
600/// `backend::agent_seat`, which reads them without naming `server/`.
601pub(crate) use crate::backend::agent_seat::{worker_of, WORKER_OF_CONTENT};
602/// The account a pane's run launched on (`agent_state::RUN_ACCOUNT_META_KEY`).
603pub(crate) use crate::backend::agent_state::RUN_ACCOUNT_META_KEY;
604
605/// [`account_label`] with the number that tells it from the other accounts of
606/// its provider and email (`all`).
607pub(crate) fn account_label_in(a: &IdentityAccount, all: &[IdentityAccount]) -> String {
608    crate::identity::account_numbering::numbered_label(a, &account_label(a), all)
609}
610
611pub(crate) fn account_label(a: &IdentityAccount) -> String {
612    let email = a.context.get("email").and_then(|e| e.as_str()).unwrap_or("");
613    [a.display_name.as_str(), email, a.name.as_str()]
614        .into_iter()
615        .find(|s| !s.trim().is_empty())
616        .unwrap_or(&a.id)
617        .to_string()
618}
619
620/// `wanted` names `a`: its id, name, display name or email, ignoring case.
621fn account_matches(a: &IdentityAccount, wanted: &str, all: &[IdentityAccount]) -> bool {
622    crate::identity::account_numbering::names(a, wanted, all)
623}
624
625/// "<Leader> worker N", the first N no agent is named.
626fn next_worker_name(mstore: &Store, leader: &str, also_taken: &std::collections::HashSet<String>) -> String {
627    let mut taken: std::collections::HashSet<String> =
628        mstore.agent_def_list().unwrap_or_default().into_iter().map(|d| d.name.to_lowercase()).collect();
629    taken.extend(also_taken.iter().cloned());
630    (1..)
631        .map(|n| format!("{leader} worker {n}"))
632        .find(|n| !taken.contains(&n.to_lowercase()))
633        .unwrap_or_default()
634}
635
636/// One of a leader's workers, for `Agents` `workers` (§3.4).
637#[derive(Debug, serde::Serialize, PartialEq)]
638pub(crate) struct WorkerSummary {
639    pub name: String,
640    /// What `Message` `send` addresses it by.
641    pub message_to: String,
642    pub agent_id: String,
643    pub block_id: String,
644    /// working | waiting | idle | stopped | error | limited | signed_out, and
645    /// since when (unix ms); absent while srv has no controller for the pane.
646    pub state: Option<crate::backend::agent_state::AgentState>,
647    pub since_ms: Option<u64>,
648    /// Why it can't work while `limited` or `signed_out`: `{state, code,
649    /// title, resets_at_ms, since_ms}`, never the account; otherwise null.
650    pub unavailable: Option<crate::backend::agent_state::Unavailable>,
651    /// When it last messaged the leader (unix ms), since srv started.
652    pub last_report_ms: Option<u64>,
653}
654
655/// `POST /api/v1/agent/workers`: the caller's own open workers. A caller that
656/// isn't a leader gets an empty list.
657pub(crate) async fn handle_agent_workers(
658    State(state): State<AppState>,
659    caller: Option<axum::Extension<crate::server::caller::Caller>>,
660    Json(req): Json<agentmux_common::api_types::AgentWorkersRequest>,
661) -> Response {
662    let block_id = match crate::server::ui_handlers::verified_block_id(&state, caller.as_deref(), &req.auth) {
663        Ok(b) => b,
664        Err(e) => {
665            let error = format!("could not verify which agent is asking: {e}");
666            return (StatusCode::UNAUTHORIZED, Json(json!({ "error": error }))).into_response();
667        }
668    };
669    let mstore = state.mstore.clone();
670    let listed = tokio::task::spawn_blocking(move || {
671        let leader = mstore
672            .get::<Block>(&block_id)
673            .ok()
674            .flatten()
675            .map(|b| obj::meta_get_string(&b.meta, "agentId", ""))
676            .unwrap_or_default();
677        crate::backend::worker_notes::absorb(&crate::backend::reactive::get_global_handler().get_audit_log(usize::MAX));
678        workers_of(&mstore, &leader)
679    })
680    .await
681    .unwrap_or_default();
682    Json(json!({ "workers": listed })).into_response()
683}
684
685/// `leader_def_id`'s workers open in a tab or parked: panes marked as its (on the pane
686/// or on their definition), with their state and last report.
687pub(crate) fn workers_of(mstore: &Store, leader_def_id: &str) -> Vec<WorkerSummary> {
688    if leader_def_id.is_empty() {
689        return Vec::new();
690    }
691    let Ok(in_tabs_or_parked) = super::agent_block::blocks_in_tabs_or_parked(mstore) else {
692        return Vec::new();
693    };
694    let defs = mstore.agent_def_list().unwrap_or_default();
695    let blocks: Vec<Block> = in_tabs_or_parked.into_iter().map(|(b, _)| b).collect();
696    let leader_panes: Vec<String> = blocks
697        .iter()
698        .filter(|b| obj::meta_get_string(&b.meta, "agentId", "") == leader_def_id)
699        .map(|b| b.oid.clone())
700        .collect();
701    blocks
702        .iter()
703        .filter_map(|b| {
704            let def_id = obj::meta_get_string(&b.meta, "agentId", "");
705            let marked = coached_by_id(&b.meta) == Some(leader_def_id) || worker_of(mstore, &def_id).as_deref() == Some(leader_def_id);
706            if def_id.is_empty() || !marked {
707                return None;
708            }
709            let def = defs.iter().find(|d| d.id == def_id)?;
710            let status = crate::backend::agent_state::agent_status_of_block(mstore, &b.oid);
711            let unavailable = crate::backend::agent_state::unavailable_of_block(mstore, None, &b.oid, agentmux_common::time::now_ms_u64());
712            let last_report_ms = crate::backend::worker_notes::last_report(&def.slug, &leader_panes);
713            Some(WorkerSummary {
714                name: def.name.clone(),
715                message_to: def.slug.clone(),
716                agent_id: def.id.clone(),
717                block_id: b.oid.clone(),
718                state: status.map(|s| s.state),
719                since_ms: status.map(|s| s.since_ms),
720                unavailable,
721                last_report_ms,
722            })
723        })
724        .collect()
725}
726
727/// How many open panes `leader_def_id` coaches: workers in some tab, or parked (still running).
728pub(crate) fn live_workers_of(mstore: &Store, leader_def_id: &str) -> usize {
729    let Ok(blocks) = super::agent_block::blocks_in_tabs_or_parked(mstore) else {
730        return 0;
731    };
732    // A pane is the leader's worker by its mark, or by its definition's (a
733    // worker reopened from My Agents).
734    let mut leader_of_def: std::collections::HashMap<String, Option<String>> = std::collections::HashMap::new();
735    blocks
736        .iter()
737        .map(|(b, _)| b)
738        .filter(|b| {
739            if coached_by_id(&b.meta) == Some(leader_def_id) {
740                return true;
741            }
742            let def = obj::meta_get_string(&b.meta, "agentId", "");
743            !def.is_empty() && leader_of_def.entry(def.clone()).or_insert_with(|| worker_of(mstore, &def)).as_deref() == Some(leader_def_id)
744        })
745        .count()
746}
747
748fn coached_by_id(meta: &MetaMapType) -> Option<&str> {
749    meta.get(COACHED_BY_META_KEY)?.get("id")?.as_str()
750}
751
752/// Tell the person in the leader's pane that it starts agents, and whether it may go ahead
753/// (docs/specs/SPEC_AGENT_SPAWN_NOTICE_IN_THE_PANE_2026_11_08.md). Nothing waits for a click:
754/// - the person's own turn asked for it and the agent chose no route (the `QuitSelf` rule,
755///   `self_quit::gate`), the "Agents may start agents" setting is on, or the person said Always to
756///   this leader: a one-line notice, and it goes ahead;
757/// - otherwise a card with a countdown (Stop it, Start now, Always allow), and it goes ahead when
758///   the countdown ends. With no window connected there is no one to stop it, so it goes ahead.
759///
760/// `Err` when the person stopped it, or the leader is gone. Returns whether a card was shown.
761pub(super) async fn announce_start(
762    state: &AppState,
763    leader: &Leader,
764    user_instruction: &str,
765    route_asked: bool,
766    headline: String,
767    body: String,
768    quote: &str,
769) -> Result<bool, SpawnError> {
770    use crate::sagas::agent_notice::{self, Go, Kind, Notice, Outcome, Waiver};
771    let provenance = blockcontroller::get_controller(&leader.block_id).and_then(|c| c.turn_provenance());
772    let gate = crate::sagas::self_quit::gate(provenance.as_ref(), user_instruction);
773    let waived = if gate.is_ok() && !route_asked {
774        Some(Waiver::UserTurn)
775    } else if agents_may_start_agents(state) {
776        Some(Waiver::Setting)
777    } else {
778        None
779    };
780    let notice = Notice {
781        kind: Kind::Spawn,
782        block_id: leader.block_id.clone(),
783        agent_id: leader.def.id.clone(),
784        agent: leader.def.name.clone(),
785        connection: String::new(),
786        headline,
787        body,
788        quote: if quote.trim().is_empty() { String::new() } else { one_line(quote, 400) },
789        always_label: format!("Always allow {} to start agents", one_line(&leader.def.name, 40)),
790        waived,
791    };
792    match agent_notice::announce(state, notice, || requester_here(state, &leader.block_id)).await {
793        Outcome::Go(Go::Waived(_) | Go::Granted | Go::Headless) => Ok(false),
794        Outcome::Go(_) => Ok(true),
795        Outcome::Stopped => Err(refuse(StatusCode::FORBIDDEN, "NOT_ALLOWED: the user stopped it, so nothing was started")),
796        Outcome::Gone => Err(refuse(StatusCode::CONFLICT, "NOT_AN_AGENT_PANE: your pane was closed before the start, so nothing was started")),
797    }
798}
799
800/// `agent:maystartagents`: the person turned on "Agents may start agents" in Settings, so no
801/// agent's start shows a card.
802pub(crate) const SETTING_MAY_START_AGENTS: &str = "agent:maystartagents";
803
804fn agents_may_start_agents(state: &AppState) -> bool {
805    state.config_watcher.get_settings().extra.get(SETTING_MAY_START_AGENTS).and_then(serde_json::Value::as_bool).unwrap_or(false)
806}
807
808/// Whether the requester is still there to start things for: its pane exists and its agent was not
809/// stopped since (an explicit stop keeps the pane). A parked agent's pane exists and it still runs.
810pub(crate) fn requester_here(state: &AppState, block_id: &str) -> bool {
811    state.mstore.get::<Block>(block_id).ok().flatten().is_some() && !super::agent_attach::stopped_this_run(block_id)
812}
813
814/// What the person is shown about one worker.
815async fn consent(
816    state: &AppState,
817    leader: &Leader,
818    name: Option<&str>,
819    model: Option<&str>,
820    runtime: &WorkerRuntime,
821    account: &WorkerAccount,
822    brief: &str,
823    user_instruction: &str,
824) -> Result<bool, SpawnError> {
825    let who = match name {
826        Some(n) => format!("a new agent, {}", one_line(n, 60)),
827        None => "a new agent".to_string(),
828    };
829    let headline = format!("{} is starting {who}", one_line(&leader.def.name, 60));
830    announce_start(state, leader, user_instruction, runtime.route_asked, headline, consent_message(name, model, runtime, account), brief).await
831}
832
833/// The facts of a start, from srv's record: its model, placement, who pays.
834fn consent_message(name: Option<&str>, model: Option<&str>, runtime: &WorkerRuntime, account: &WorkerAccount) -> String {
835    let who = match name {
836        Some(n) => one_line(n, 60),
837        None => "A new agent".to_string(),
838    };
839    let on = model.map(|m| format!(" on {}", one_line(m, 40))).unwrap_or_default();
840    let on = format!("{on}{}", runtime.placement.describe());
841    let note = account.note.as_deref().map(|n| format!(" {}", one_line(n, 200))).unwrap_or_default();
842    let paid_by = if account.id.is_empty() { runtime.route_line.clone() } else { format!(" It runs on the account {}.{note}", one_line(&account.label, 80)) };
843    format!("{who}{on}, from its leader's instructions, in the leader's team tab.{} It spends tokens until it is stopped.", if paid_by.trim().is_empty() { String::new() } else { format!(" {}", paid_by.trim()) })
844}
845
846/// `s` on one line, at most `max` characters.
847fn one_line(s: &str, max: usize) -> String {
848    let flat = s.split_whitespace().collect::<Vec<_>>().join(" ");
849    if flat.chars().count() <= max {
850        flat
851    } else {
852        format!("{}…", flat.chars().take(max).collect::<String>())
853    }
854}
855
856/// Remember the worker's runtime, then open it in `tab_id` (right of the leader's pane when that pane
857/// is in the tab), marked as the leader's worker from the moment its block exists.
858async fn open_worker(
859    state: &AppState,
860    leader: &Leader,
861    worker: &AgentDefinition,
862    tab_id: &str,
863    runtime: &WorkerRuntime,
864) -> Result<AgentOpenResult, String> {
865    if !runtime.stored.is_empty() {
866        state
867            .mstore
868            .agent_last_runtime_set(&worker.id, &runtime.stored)
869            .map_err(|e| format!("remember its model: {e}"))?;
870    }
871    let mut meta = MetaMapType::new();
872    meta.insert(
873        COACHED_BY_META_KEY.to_string(),
874        json!({ "agent": leader.def.name, "id": leader.def.id, "block_id": leader.block_id }),
875    );
876    let beside = resolve_tab_id_for_block(&state.mstore, &leader.block_id).is_ok_and(|t| t == tab_id);
877    super::agent_open::open_agent_inner(
878        state,
879        CommandAgentOpenData {
880            agent_id: worker.id.clone(),
881            tab_id: Some(tab_id.to_string()),
882            // Beside the leader's pane only when it is in the tab: a team tab has its own layout.
883            split_direction: beside.then(|| "right".to_string()),
884            split_reference_block_id: beside.then(|| leader.block_id.clone()),
885            focus: Some(false),
886            into_block_id: None,
887        },
888        None,
889        meta,
890    )
891    .await
892}
893
894/// Remove a worker whose open failed: the pane the open may have made in
895/// `tab_id` before failing (closed as any pane is, `delete_block`), then its
896/// definition, as the `deleteagent` RPC deletes one.
897async fn discard_worker(state: &AppState, tab_id: &str, def_id: &str) {
898    if let Ok(Some(block)) = super::find_agent_block(&state.mstore, tab_id, def_id) {
899        if let Err(e) = crate::sagas::delete_block::run(state, tab_id.to_string(), block.oid.clone()).await {
900            tracing::warn!(def_id, block_id = %block.oid, error = %e, "agent.spawn: the unopened worker's pane is left behind");
901        }
902    }
903    if let Err(e) = state.mstore.agent_def_delete(def_id) {
904        tracing::warn!(def_id, error = %e, "agent.spawn: the unopened worker's definition is left behind");
905        return;
906    }
907    crate::server::agent_handlers::purge_identity_store_rows(&state.identity_store, &state.id_store, def_id, "agent.spawn");
908    state.broker.publish_event::<crate::backend::mps_events::AgentsChanged>(&(), vec![], 0);
909}
910
911#[cfg(test)]
912#[path = "tests/agent_spawn_tests.rs"]
913mod tests;