Skip to main content

agentmux_srv/server/
drone_handlers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! WSH RPC handlers for the Drone pane (issue #753 Phase 1).
5//!
6//! Commands:
7//!   * `listdrones`       → `Vec<DroneDefinition>`
8//!   * `getdrone`         → `Option<DroneDefinition>`
9//!   * `upsertdrone`      → `DroneDefinition` (echoed back, normalized)
10//!   * `deletedrone`      → `{ deleted: bool }`
11//!   * `rundrone`         → `{ run_id: String }` (synchronous; SSE
12//!                              streaming added in Phase 1 PR-4)
13//!   * `listdroneruns`    → `Vec<DroneRun>`
14//!
15//! Run streaming: the executor emits `RunEvent`s over an mpsc channel.
16//! Phase 1 of this PR drains the channel server-side and stores the
17//! final block-state snapshot in `db_drone_runs`. A future commit
18//! will tee the channel to the renderer via the existing `mps` event
19//! broker so `RunPanel` shows live per-block status.
20
21use std::collections::HashMap;
22use std::sync::Arc;
23
24use serde::{Deserialize, Serialize};
25
26use crate::backend::rpc_types::{
27    COMMAND_DELETE_DRONE, COMMAND_GET_DRONE, COMMAND_LIST_DRONES,
28    COMMAND_GET_DRONE_PAYLOAD_SCHEMA, COMMAND_LIST_DRONE_RUNS, COMMAND_REPLAY_DRONE_RUN, COMMAND_RESOLVE_DRONE_RUN, COMMAND_RESUME_DRONE_WAIT, COMMAND_RUN_DRONE, COMMAND_UPSERT_DRONE,
29};
30use crate::server::AppState;
31use crate::backend::rpc::actor::{actor_of, Actor};
32use crate::backend::rpc::engine::WshRpcEngine;
33use crate::backend::rpc_types::RpcContext;
34use crate::backend::drone_decision::{self, Decision};
35use crate::drone::executor::{run_drone, RunEvent};
36use crate::drone::access::DroneAccessStore;
37use crate::drone::storage::DroneStore;
38use crate::drone::types::{RunStatus, DroneDefinition, DroneRun};
39use crate::drone::checkpoint::GraphRef;
40use crate::drone::recorder::Persist;
41use crate::drone::versions::{graph_hash, DroneVersionStore, Pin};
42
43/// Request for `listdrones`, which ignores its payload.
44///
45/// Registered as `Option<Self>`: the stub sends `{}` and a client that omits
46/// `data` sends `null`, and serde accepts each of those from only one of
47/// `()` and a struct. `Option<Self>` takes both.
48#[derive(Debug, Default, Serialize, Deserialize, ts_rs::TS)]
49#[ts(export, export_to = "../../../frontend/types/rpc/")]
50pub struct ListDronesReq {}
51
52#[derive(Debug, Serialize, Deserialize, ts_rs::TS)]
53#[ts(export, export_to = "../../../frontend/types/rpc/")]
54pub struct GetDroneReq {
55    pub id: String,
56}
57
58#[derive(Debug, Serialize, Deserialize, ts_rs::TS)]
59#[ts(export, export_to = "../../../frontend/types/rpc/")]
60pub struct DeleteDroneReq {
61    pub id: String,
62}
63
64#[derive(Debug, Serialize, Deserialize, ts_rs::TS)]
65#[ts(export, export_to = "../../../frontend/types/rpc/")]
66pub struct RunDroneReq {
67    pub drone_id: String,
68    /// What the run starts with, read as `{{trigger.*}}`. At most 64 KB.
69    #[serde(default)]
70    #[ts(type = "unknown", optional)]
71    pub input: Option<serde_json::Value>,
72}
73
74#[derive(Debug, Serialize, Deserialize, ts_rs::TS)]
75#[ts(export, export_to = "../../../frontend/types/rpc/")]
76pub struct ListRunsReq {
77    pub drone_id: String,
78    /// `serde(default)`, so a caller may omit it -- which ts-rs cannot express
79    /// on a non-`Option` field. The stub derives `ListDroneRunsInput` from the
80    /// generated type to restore that; see the comment there.
81    #[serde(default = "default_limit")]
82    #[ts(type = "number")]
83    pub limit: i64,
84}
85
86fn default_limit() -> i64 {
87    50
88}
89
90/// Hard cap on `ListRunsReq.limit` — guards against a malicious or
91/// buggy client passing e.g. `i64::MAX` and pulling the entire run
92/// history (DoS / memory blow-up). 200 covers any plausible UI page
93/// size with headroom; Phase 2 pagination cursor work will move this
94/// to client-driven slicing. (kimi P1 on PR #755.)
95const MAX_LIST_LIMIT: i64 = 200;
96
97#[derive(Debug, Serialize, Deserialize, ts_rs::TS)]
98#[ts(rename = "DeleteDroneResp")]
99#[ts(export, export_to = "../../../frontend/types/rpc/")]
100pub struct DeleteResp {
101    pub deleted: bool,
102}
103
104#[derive(Debug, Serialize, Deserialize, ts_rs::TS)]
105#[ts(rename = "RunDroneResp")]
106#[ts(export, export_to = "../../../frontend/types/rpc/")]
107pub struct RunResp {
108    pub run_id: String,
109}
110
111/// `listdrones`: drone definitions live in the global shared store.
112pub(crate) fn list_drones(state: &AppState) -> Result<Vec<DroneDefinition>, String> {
113    // Drone definition CRUD — routed to id_store (global shared store).
114    let list = state
115        .id_store
116        .drone_list()
117        .map_err(|e| format!("listdrones: {e}"))?;
118    Ok(list)
119}
120
121/// `getdrone`.
122pub(crate) fn get_drone(state: &AppState, cmd: GetDroneReq) -> Result<Option<DroneDefinition>, String> {
123    let row = state
124        .id_store
125        .drone_get(&cmd.id)
126        .map_err(|e| format!("getdrone: {e}"))?;
127    Ok(row)
128}
129
130/// Who the record names for a call, taken from the connection and never from the request: the person's window
131/// is `operator`, an agent is `agent:<id>` (so no agent id can read as `operator`), and a connection that is
132/// neither says what it is.
133pub(crate) fn recorded_as(ctx: &RpcContext) -> String {
134    actor_of(ctx).label()
135}
136
137/// The starter a run's ledger row names, when it is not the person's window: that window is the ledger's own
138/// default (the operator).
139pub(crate) fn run_started_by(ctx: &RpcContext) -> Option<String> {
140    match actor_of(ctx) {
141        Actor::Operator => None,
142        other => Some(other.label()),
143    }
144}
145
146/// `upsertdrone` for a save the person's own client makes, or one no caller asked for (a template installed on
147/// the person's say): its version is the operator's.
148pub(crate) fn upsert_drone(state: &AppState, cmd: DroneDefinition) -> Result<DroneDefinition, String> {
149    upsert_drone_as(state, cmd, crate::backend::jobs::BY_OPERATOR)
150}
151
152/// `upsertdrone`: stamps the times, mints an id for a new drone, and echoes the row back. The version is saved
153/// as `saved_by`, which the registered handler takes from the connection (an agent's drone is shown as that
154/// agent's).
155pub(crate) fn upsert_drone_as(state: &AppState, mut cmd: DroneDefinition, saved_by: &str) -> Result<DroneDefinition, String> {
156    let now = now_ms();
157    if cmd.created_at == 0 {
158        cmd.created_at = now;
159    }
160    cmd.updated_at = now;
161    if cmd.id.is_empty() {
162        cmd.id = uuid::Uuid::new_v4().to_string();
163    }
164    // An agent that makes a drone owns it. A save of a drone that is there already never changes its owner.
165    let is_new = !matches!(state.id_store.drone_get(&cmd.id), Ok(Some(_)));
166    // A job that is on keeps firing the graph saved here: it must still pass where the job was turned on.
167    super::drone_turn_on::graph_allowed(state, &cmd)?;
168    // The definition and its version are one immediate transaction, so a
169    // concurrent save cannot leave the stored definition on a graph newer than
170    // the one `Latest` returns.
171    match state.id_store.drone_save_with_version(&cmd, saved_by, now) {
172        Ok(Ok(_)) => {}
173        // A failed version save must not undo the definition: a drone that
174        // cannot be edited is worse than one missing its latest version.
175        Ok(Err(e)) => tracing::warn!(
176            drone_id = %cmd.id,
177            error = %e,
178            "upsertdrone: the definition was saved but its version was not"
179        ),
180        Err(e) => return Err(format!("upsertdrone: {e}")),
181    }
182    if let (true, Some(agent)) = (is_new, saved_by.strip_prefix("agent:")) {
183        if let Err(e) = state.id_store.access_set_owner(&cmd.id, agent, now) {
184            // Without an owner the agent's own fires take the countdown: slower, never wider.
185            tracing::warn!(drone_id = %cmd.id, error = %e, "upsertdrone: the drone was saved but its owner was not");
186        }
187    }
188    state.broker.publish_event::<crate::backend::mps_events::DronesChanged>(&(), vec![], 0);
189    Ok(cmd)
190}
191
192/// `deletedrone` for a delete no connection asked for, or the person's own.
193#[cfg(test)]
194pub(crate) fn delete_drone(state: &AppState, cmd: DeleteDroneReq) -> Result<DeleteResp, String> {
195    delete_drone_as(state, cmd, crate::backend::jobs::BY_OPERATOR)
196}
197
198/// `deletedrone` with who deleted it: the log line names the connection's label (`agent:<id>` for an agent), never
199/// what the request says.
200pub(crate) fn delete_drone_as(state: &AppState, cmd: DeleteDroneReq, by: &str) -> Result<DeleteResp, String> {
201    tracing::info!(drone_id = %cmd.id, by = %by, "deletedrone");
202    let deleted = state
203        .id_store
204        .drone_delete(&cmd.id)
205        .map_err(|e| format!("deletedrone: {e}"))?;
206    // The runs are in this version's store, the definition and its
207    // versions in the shared one, so nothing cascades (m0038).
208    // Definition first, then runs and versions: a run starting
209    // meanwhile either has its row removed here or finds the
210    // definition gone and removes it itself (rundrone). Other
211    // versions keep their own runs.
212    if let Err(e) = state.mstore.drone_runs_delete_for(&cmd.id) {
213        state.broker.publish_event::<crate::backend::mps_events::DronesChanged>(&(), vec![], 0);
214        return Err(format!("deletedrone: the drone was deleted, but removing its run history failed: {e}"));
215    }
216    if let Err(e) = state.id_store.versions_delete_for(&cmd.id) {
217        state.broker.publish_event::<crate::backend::mps_events::DronesChanged>(&(), vec![], 0);
218        return Err(format!("deletedrone: the drone was deleted, but removing its versions failed: {e}"));
219    }
220    if let Err(e) = state.id_store.access_delete_for(&cmd.id) {
221        tracing::warn!(drone_id = %cmd.id, error = %e, "deletedrone: the drone's owner and grants were not removed");
222    }
223    if deleted {
224        state.broker.publish_event::<crate::backend::mps_events::DronesChanged>(&(), vec![], 0);
225    }
226    Ok(DeleteResp { deleted })
227}
228
229/// Persist a `running` placeholder row synchronously
230/// BEFORE returning. Guarantees:
231///   1. The frontend's `refreshRuns` (called right
232///      after this RPC resolves) always sees the row,
233///      no spawn-race against the drain (codex+reagent
234///      P2 from earlier rounds).
235///   2. The drain can run as a background spawn
236///      again — so drones longer than the RPC
237///      timeout (5s default) don't get their drain
238///      truncated mid-flight (codex P1 v0.33.842).
239///   3. Server-restart safety: an orphaned `running`
240///      row signals "drain was interrupted" — a
241///      future startup task can mark stale rows as
242///      `interrupted` (cleaner than the prior
243///      fire-and-forget that left no row at all).
244pub(crate) fn insert_run_placeholder(state: &AppState, run_id: &str, drone_id: &str, started_at: i64) -> Result<(), String> {
245    let placeholder = DroneRun {
246        id: run_id.to_string(),
247        drone_id: drone_id.to_string(),
248        status: RunStatus::Running.as_str().to_string(),
249        started_at,
250        ended_at: 0,
251        block_states: HashMap::new(),
252        output: String::new(),
253        error: String::new(),
254    };
255    state
256        .mstore
257        .drone_run_insert(&placeholder)
258        .map_err(|e| format!("rundrone placeholder: {e}"))?;
259    // No FK ties the run to its definition (m0038): if the drone
260    // was deleted while this run started, take the row back out
261    // rather than leave history for a drone that no longer exists.
262    match state.id_store.drone_get(drone_id) {
263        Ok(Some(_)) => {}
264        // Only this run's own row: the drone's other runs belong
265        // to the delete handler, which removes them itself.
266        Ok(None) => {
267            let _ = state.mstore.drone_run_delete(run_id);
268            return Err(format!("rundrone: drone {drone_id} was deleted while the run started"));
269        }
270        // Can't tell (a lock or I/O error): keep the run and its
271        // history rather than delete anything on a guess.
272        Err(e) => tracing::warn!(drone_id = %drone_id, "rundrone: re-checking the drone failed: {e}"),
273    }
274    Ok(())
275}
276
277/// A run's row follows its wait: `needs_attention` with the reason when a step needs an
278/// answer, `waiting` at a Wait block, `running` again once either is over. Any other event leaves the row alone.
279async fn note_attention(
280    mstore: &crate::backend::storage::store::Store,
281    (run_id, drone_id, started_at): (&str, &str, i64),
282    ev: &RunEvent,
283    final_states: &tokio::sync::Mutex<HashMap<String, crate::drone::types::BlockState>>,
284) {
285    let (status, error) = match ev {
286        RunEvent::NeedsAttention { reason, .. } => (RunStatus::NeedsAttention, reason.clone()),
287        RunEvent::AttentionAnswered { .. } | RunEvent::WaitEnded { .. } => (RunStatus::Running, String::new()),
288        RunEvent::Waiting { .. } => (RunStatus::Waiting, String::new()),
289        _ => return,
290    };
291    let row = DroneRun {
292        id: run_id.to_string(),
293        drone_id: drone_id.to_string(),
294        status: status.as_str().to_string(),
295        started_at,
296        ended_at: 0,
297        block_states: final_states.lock().await.clone(),
298        output: String::new(),
299        error,
300    };
301    if let Err(e) = mstore.drone_run_update(&row) {
302        tracing::warn!(run_id, error = %e, "drone_run_update failed");
303    }
304}
305
306/// Drain a run's events on a background task; on completion, UPDATE the
307/// placeholder row in place and close the run ledger's row.
308pub(crate) fn spawn_run_drain(
309    state: &AppState,
310    mut handle: crate::drone::executor::engine::RunHandle,
311    drone_id: String,
312    started_at: i64,
313    ledger_run: Option<(Arc<crate::backend::jobs::RunLedger>, String)>,
314) {
315    let mstore_for_drain = state.mstore.clone();
316    let broker_for_drain = state.broker.clone();
317    let run_id_for_drain = handle.run_id.clone();
318    let drone_id_for_drain = drone_id;
319    tokio::spawn(async move {
320        let mut last_status;
321        let mut output = String::new();
322        let mut error = String::new();
323        while let Some(ev) = handle.events.recv().await {
324            // For terminal events, persist the final row
325            // BEFORE publishing the event. The frontend
326            // subscription path refreshes the runs list on
327            // RunDone / RunFailed, and if the publish
328            // happens first the refresh sees a stale
329            // `running` row (codex P2 on PR #843).
330            let is_terminal = matches!(
331                ev,
332                RunEvent::RunDone { .. } | RunEvent::RunFailed { .. } | RunEvent::RunCancelled { .. }
333            );
334            if is_terminal {
335                match &ev {
336                    RunEvent::RunDone { output: o, .. } => {
337                        last_status = RunStatus::Done;
338                        // Engine already unwraps Response's
339                        // `{ "value": ... }` wrapper.
340                        output = match o {
341                            serde_json::Value::String(s) => s.clone(),
342                            other => {
343                                serde_json::to_string(other).unwrap_or_default()
344                            }
345                        };
346                    }
347                    RunEvent::RunFailed { error: e, .. } => {
348                        last_status = RunStatus::Failed;
349                        error = e.clone();
350                    }
351                    RunEvent::RunCancelled { reason, .. } => {
352                        last_status = RunStatus::Cancelled;
353                        error = reason.clone();
354                    }
355                    _ => unreachable!(),
356                }
357                let states = handle.final_states.lock().await.clone();
358                let row = DroneRun {
359                    id: run_id_for_drain.clone(),
360                    drone_id: drone_id_for_drain.clone(),
361                    status: last_status.as_str().to_string(),
362                    started_at,
363                    ended_at: now_ms(),
364                    block_states: states,
365                    output: output.clone(),
366                    error: error.clone(),
367                };
368                // The Drone run is saved before the job's row closes: whoever
369                // sees the job's row ended then finds the run's output.
370                match mstore_for_drain.drone_run_update(&row) {
371                    Ok(0) => tracing::warn!(
372                        run_id = %run_id_for_drain,
373                        "drone_run_update: placeholder row missing (race?)"
374                    ),
375                    Ok(_) => {}
376                    Err(e) => tracing::warn!(
377                        run_id = %run_id_for_drain,
378                        error = %e,
379                        "drone_run_update failed"
380                    ),
381                }
382                if let Some((ledger, ledger_id)) = &ledger_run {
383                    if last_status == RunStatus::Cancelled {
384                        ledger.drone_stopped(ledger_id, &row.block_states, &row.error);
385                    } else {
386                        ledger.drone_finished(ledger_id, last_status == RunStatus::Done, &row.block_states, &row.error);
387                    }
388                }
389            }
390            // A run that needs attention shows it in its row, and shows it is going again when answered.
391            note_attention(&mstore_for_drain, (&run_id_for_drain, &drone_id_for_drain, started_at), &ev, &handle.final_states).await;
392            broker_for_drain.publish_event_for::<crate::backend::mps_events::DroneRun>(&run_id_for_drain, &ev, vec![], 0);
393        }
394    });
395}
396
397/// What an agent's own `rundrone` call may start: the drones the Drone tool may fire (nothing that writes outside
398/// AgentMux, reads a Vault credential, runs a command or calls another drone), so approving a credential or a
399/// write stays the person's. The person's window is not asked. A drone that does not exist is left for the run
400/// to report.
401pub(crate) fn run_allowed_for(state: &AppState, ctx: &RpcContext, drone_id: &str) -> Result<(), String> {
402    if !matches!(actor_of(ctx), Actor::Agent(_)) {
403        return Ok(());
404    }
405    let Ok(Some(drone)) = state.id_store.drone_get(drone_id) else {
406        return Ok(());
407    };
408    if let Some(why) = crate::server::drone_agent::why_not_fireable(&drone) {
409        return Err(format!("FORBIDDEN: an agent can't run {:?}: {why}. A person runs it from the Drone pane", drone.name));
410    }
411    // A drone the agent made or was given runs now. Any other is the Drone tool's `fire`, which asks the person.
412    let Actor::Agent(agent) = actor_of(ctx) else { return Ok(()) };
413    match state.id_store.access_get(drone_id) {
414        Ok(access) if access.allows(&agent) => Ok(()),
415        _ => Err(format!(
416            "FORBIDDEN: {:?} is not yours and was not given to you. Use the Drone tool's fire: it asks the person, who has a few seconds to stop it",
417            drone.name
418        )),
419    }
420}
421
422/// The most a run's input may hold, as JSON. It lives in the run's memory
423/// and the ledger keeps only its hash and size (real-world jobs spec D11).
424pub(crate) const MAX_INPUT_BYTES: usize = 64 * 1024;
425
426/// `rundrone`: reads the drone definition from id_store (global), writes the
427/// run rows to mstore (per-channel).
428pub(crate) async fn start_drone_run(state: &AppState, cmd: RunDroneReq) -> Result<RunResp, String> {
429    start_drone_run_as(state, cmd, None).await
430}
431
432/// `rundrone` with the run's starter named: `by` is who the ledger row says started it, `None` for the person's
433/// window (the operator). The registered handler takes it from the connection.
434pub(crate) async fn start_drone_run_as(state: &AppState, cmd: RunDroneReq, by: Option<&str>) -> Result<RunResp, String> {
435    let run_id = launch_run(state, &cmd.drone_id, cmd.input.unwrap_or_default(), None, None, by).await?;
436    Ok(RunResp { run_id })
437}
438
439/// Start a run an agent fires with `Drone` `fire`: the ledger row says which agent did it (`by_agent`
440/// is the agent's id), as `agent:<id>` like every other path, so no agent id can read as the operator.
441///
442/// It runs `drone` as the caller loaded and checked it: the graph is not fetched again, so a drone saved in between is not
443/// the one that runs.
444pub(crate) async fn start_agent_drone_run(
445    state: &AppState,
446    drone: &DroneDefinition,
447    input: serde_json::Value,
448    by_agent: &str,
449) -> Result<String, String> {
450    let by = Actor::Agent(by_agent.to_string()).label();
451    launch_loaded(state, drone.clone(), input, None, None, Some(&by)).await
452}
453
454/// Start the run a job's `drone` action asks for. `job_run_id` is the job
455/// run's row in the ledger, which runs until the drone does; `run_cap_usd` is
456/// the job's per-run cap, which ends the run before its next block once its
457/// Agent blocks have spent it. Returns the Drone run's id.
458pub(crate) async fn start_job_drone_run(
459    state: &AppState,
460    drone_id: &str,
461    trigger: serde_json::Value,
462    (job_run_id, run_cap_usd): (&str, Option<f64>),
463) -> Result<String, String> {
464    launch_run(state, drone_id, trigger, Some(job_run_id), run_cap_usd, None).await
465}
466
467/// The graph a run starts on: its hash, and the number of the saved version
468/// that has it (the newest, when the definition has not changed since its
469/// save). A drone saved before versions existed, or one whose version could not
470/// be saved, has number 0; its hash still says which graph the run had.
471fn graph_ref_of(state: &AppState, wf: &DroneDefinition) -> GraphRef {
472    let hash = graph_hash(&wf.graph);
473    let version = match state.id_store.version_resolve(&wf.id, Pin::Latest) {
474        Ok(Some(v)) if v.hash == hash => v.version,
475        _ => 0,
476    };
477    GraphRef { version, hash }
478}
479
480/// Start a run of `drone_id` with `trigger` as its input. With a
481/// `job_run_id` the ledger row is that job run's; without one the run
482/// gets a `manual` row of its own, started by `by_agent` when an agent fired it, else the operator.
483async fn launch_run(
484    state: &AppState,
485    drone_id: &str,
486    trigger: serde_json::Value,
487    job_run_id: Option<&str>,
488    run_cap_usd: Option<f64>,
489    by_agent: Option<&str>,
490) -> Result<String, String> {
491    let wf = state
492        .id_store
493        .drone_get(drone_id)
494        .map_err(|e| format!("rundrone: {e}"))?
495        .ok_or_else(|| {
496            format!("rundrone: drone {drone_id} not found")
497        })?;
498    launch_loaded(state, wf, trigger, job_run_id, run_cap_usd, by_agent).await
499}
500
501/// [`launch_run`] for a drone already loaded: it runs exactly this definition.
502async fn launch_loaded(
503    state: &AppState,
504    wf: DroneDefinition,
505    trigger: serde_json::Value,
506    job_run_id: Option<&str>,
507    run_cap_usd: Option<f64>,
508    by_agent: Option<&str>,
509) -> Result<String, String> {
510    let size = trigger.to_string().len();
511    if size > MAX_INPUT_BYTES {
512        return Err(format!("rundrone: the input is {size} bytes; at most {MAX_INPUT_BYTES}"));
513    }
514    let ledger = state.cron_scheduler.runs().cloned();
515    let started_at = now_ms();
516    // The run keeps its checkpoints beside its row, and the graph version it started on.
517    let persist = Persist { sink: state.mstore.clone(), graph: graph_ref_of(state, &wf) };
518    let handle = run_drone(wf.id.clone(), wf.graph.clone(), trigger.clone(), (run_cap_usd, Some(persist)))
519        .await
520        .map_err(|e| format!("rundrone: {e}"))?;
521    let run_id = handle.run_id.clone();
522    let drone_id = wf.id.clone();
523
524    insert_run_placeholder(state, &run_id, &drone_id, started_at)?;
525
526    // The run ledger's row (SPEC_JOBS_AND_TEMPLATES_2026_10_24.md
527    // §3.2): the job run's own, or a manual run, linked to this one and
528    // closed by the drain.
529    let ledger_run = ledger.as_ref().and_then(|l| match job_run_id {
530        Some(job_run) => {
531            l.drone_attached(job_run, &run_id, &trigger, started_at);
532            Some((l.clone(), job_run.to_string()))
533        }
534        None => {
535            let by = by_agent.unwrap_or(crate::backend::jobs::BY_OPERATOR);
536            l.drone_started_by(&run_id, &drone_id, &wf.name, started_at, &trigger, by).map(|id| (l.clone(), id))
537        }
538    });
539
540    spawn_run_drain(state, handle, drone_id, started_at, ledger_run);
541
542    Ok(run_id)
543}
544
545/// What `resolvedronerun` is asked to do with a run that needs attention.
546#[derive(Debug, Serialize, Deserialize, ts_rs::TS)]
547#[ts(export, export_to = "../../../frontend/types/rpc/")]
548pub struct ResolveRunReq {
549    pub run_id: String,
550    /// `run_again` (the step may repeat what it did before the restart), `skip`
551    /// (carry on as if it had finished with `output`) or `cancel` (end the run).
552    pub action: String,
553    /// With `skip`: what the step is taken to have said. It is treated as
554    /// outside text (tainted) whoever sends it. At most 64 KB.
555    #[serde(default)]
556    #[ts(type = "unknown", optional)]
557    pub output: Option<serde_json::Value>,
558}
559
560#[derive(Debug, Serialize, Deserialize, ts_rs::TS)]
561#[ts(export, export_to = "../../../frontend/types/rpc/")]
562pub struct ResolveRunResp {
563    pub run_id: String,
564    pub action: String,
565}
566
567/// The answer to a step that waits for the person, as `resolvedronerun` takes it: from the person's proven
568/// window only. An agent's call, and a connection that has proved nothing, is refused whatever it carries,
569/// including the output a `skip` would give the step.
570pub(crate) fn resolve_drone_run_as(ctx: &RpcContext, cmd: ResolveRunReq) -> Result<ResolveRunResp, String> {
571    ctx.operator_only("only the person answers a run that needs attention: ask the person (a run that waits is shown in the Drone pane and the Jobs tab)")?;
572    resolve_drone_run(cmd)
573}
574
575/// `resolvedronerun`: answer a run that is waiting, `needs_attention`, for what to
576/// do with the step that was running when AgentMux stopped.
577pub(crate) fn resolve_drone_run(cmd: ResolveRunReq) -> Result<ResolveRunResp, String> {
578    let ResolveRunReq { run_id, action, output } = cmd;
579    if !drone_decision::is_waiting(&run_id) {
580        return Err(format!("resolvedronerun: run {run_id} is not waiting for an answer"));
581    }
582    match action.as_str() {
583        "run_again" => drone_decision::decide(&run_id, Decision::RunAgain),
584        "skip" => {
585            let output = output.ok_or("resolvedronerun: `skip` needs `output`, what the step is taken to have said")?;
586            let size = output.to_string().len();
587            if size > MAX_INPUT_BYTES {
588                return Err(format!("resolvedronerun: the output is {size} bytes; at most {MAX_INPUT_BYTES}"));
589            }
590            drone_decision::decide(&run_id, Decision::Skip { output })
591        }
592        "cancel" => crate::backend::drone_cancel::cancel_run(&run_id, "cancelled when asked what to do with a step that needed attention")
593            .then_some(())
594            .ok_or_else(|| format!("run {run_id} is not running")),
595        other => Err(format!("resolvedronerun: unknown action {other:?}; use run_again, skip or cancel")),
596    }
597    .map_err(|e| if e.starts_with("resolvedronerun") { e } else { format!("resolvedronerun: {e}") })?;
598    Ok(ResolveRunResp { run_id, action })
599}
600
601/// What `resumedronewait` brings to a run waiting on an event.
602#[derive(Debug, Serialize, Deserialize, ts_rs::TS)]
603#[ts(export, export_to = "../../../frontend/types/rpc/")]
604pub struct ResumeWaitReq {
605    /// The key the run's `Waiting` event gave. Whoever holds it can end the wait, once.
606    pub key: String,
607    /// What the event says, at most 64 KB. The run reads it as outside text (tainted).
608    #[serde(default)]
609    #[ts(type = "unknown", optional)]
610    pub payload: Option<serde_json::Value>,
611}
612
613#[derive(Debug, Serialize, Deserialize, ts_rs::TS)]
614#[ts(export, export_to = "../../../frontend/types/rpc/")]
615pub struct ResumeWaitResp {
616    pub resumed: bool,
617}
618
619/// `resumedronewait`: end a Wait block that waits on an event.
620#[cfg(test)]
621pub(crate) fn resume_drone_wait(cmd: ResumeWaitReq) -> Result<ResumeWaitResp, String> {
622    resume_drone_wait_as(cmd, crate::backend::jobs::BY_OPERATOR)
623}
624
625/// `resumedronewait` with the caller named as the connection says (the log line names it): the key stays what
626/// guards the wait.
627pub(crate) fn resume_drone_wait_as(cmd: ResumeWaitReq, by: &str) -> Result<ResumeWaitResp, String> {
628    tracing::info!(by = %by, "resumedronewait: a wait is being ended");
629    let payload = cmd.payload.unwrap_or(serde_json::Value::Null);
630    let size = payload.to_string().len();
631    if size > MAX_INPUT_BYTES {
632        return Err(format!("resumedronewait: the payload is {size} bytes; at most {MAX_INPUT_BYTES}"));
633    }
634    crate::backend::drone_wait::signal(&cmd.key, payload).map_err(|e| format!("resumedronewait: {e}"))?;
635    Ok(ResumeWaitResp { resumed: true })
636}
637
638/// `listdroneruns`.
639pub(crate) fn list_drone_runs(state: &AppState, cmd: ListRunsReq) -> Result<Vec<DroneRun>, String> {
640    let limit = cmd.limit.clamp(0, MAX_LIST_LIMIT);
641    let list = state
642        .mstore
643        .drone_runs_for(&cmd.drone_id, limit)
644        .map_err(|e| format!("listdroneruns: {e}"))?;
645    Ok(list)
646}
647
648pub fn register_drone_handlers(engine: &Arc<WshRpcEngine>, state: &AppState) {
649    let s = state.clone();
650    engine.register_typed(
651        COMMAND_LIST_DRONES,
652        // `Option<_>` -- see `ListDronesReq`: it is what makes both encodings
653        // of "no argument" deserialize.
654        move |_req: Option<ListDronesReq>, _ctx| {
655            let s = s.clone();
656            async move { list_drones(&s) }
657        },
658    );
659
660    let s = state.clone();
661    engine.register_typed(COMMAND_GET_DRONE, move |cmd: GetDroneReq, _ctx| {
662        let s = s.clone();
663        async move { get_drone(&s, cmd) }
664    });
665
666    let s = state.clone();
667    engine.register_typed(COMMAND_UPSERT_DRONE, move |cmd: DroneDefinition, ctx| {
668        let s = s.clone();
669        async move { upsert_drone_as(&s, cmd, &recorded_as(&ctx)) }
670    });
671
672    let s = state.clone();
673    engine.register_typed(COMMAND_DELETE_DRONE, move |cmd: DeleteDroneReq, ctx| {
674        let s = s.clone();
675        async move { delete_drone_as(&s, cmd, &recorded_as(&ctx)) }
676    });
677
678    let s = state.clone();
679    engine.register_typed(COMMAND_RUN_DRONE, move |cmd: RunDroneReq, ctx| {
680        let s = s.clone();
681        async move {
682            run_allowed_for(&s, &ctx, &cmd.drone_id)?;
683            let by = run_started_by(&ctx);
684            start_drone_run_as(&s, cmd, by.as_deref()).await
685        }
686    });
687
688    engine.register_typed(COMMAND_RESOLVE_DRONE_RUN, move |cmd: ResolveRunReq, ctx| async move { resolve_drone_run_as(&ctx, cmd) });
689    engine.register_typed(COMMAND_RESUME_DRONE_WAIT, move |cmd: ResumeWaitReq, ctx| async move { resume_drone_wait_as(cmd, &recorded_as(&ctx)) });
690    let s = state.clone();
691    engine.register_typed(COMMAND_REPLAY_DRONE_RUN, move |cmd: crate::server::drone_replay::ReplayRunReq, ctx| {
692        let s = s.clone();
693        async move {
694            let by = run_started_by(&ctx);
695            crate::server::drone_replay::replay_drone_run_as(&s, cmd, by.as_deref()).await
696        }
697    });
698
699    let s = state.clone();
700    engine.register_typed(COMMAND_GET_DRONE_PAYLOAD_SCHEMA, move |cmd: crate::server::drone_payload::PayloadSchemaReq, _ctx| {
701        let s = s.clone();
702        async move { crate::server::drone_payload::get_payload_schema(&s, cmd) }
703    });
704
705    crate::server::drone_approval_handlers::register(engine, state);
706    crate::server::drone_access_handlers::register(engine, state);
707
708    let s = state.clone();
709    engine.register_typed(COMMAND_LIST_DRONE_RUNS, move |cmd: ListRunsReq, _ctx| {
710        let s = s.clone();
711        async move { list_drone_runs(&s, cmd) }
712    });
713}
714
715use agentmux_common::time::now_ms;
716
717#[cfg(test)]
718mod tests {
719    use super::*;
720
721    /// Every drone command records its request and response type, which is the
722    /// property the generated bindings are derived from — a command that
723    /// silently falls back to `register_handler` disappears from here rather
724    /// than being recorded wrong, and that absence is what this catches.
725    // `tokio::test`, not `test`: `test_state()` builds the fs-watch pool,
726    // which spawns, so it needs a runtime.
727    #[tokio::test]
728    async fn register_typed_records_every_drone_command() {
729        let (engine, _rx) = WshRpcEngine::new();
730        let state = crate::server::tests::test_state();
731        register_drone_handlers(&engine, &state);
732        let schema = engine.schema_json();
733        let rows = schema.as_array().unwrap();
734        let find = |cmd: &str| {
735            rows.iter()
736                .find(|r| r["command"] == cmd)
737                .unwrap_or_else(|| panic!("{cmd} missing from the schema — did it fall back to register_handler?"))
738        };
739
740        for (cmd, req, resp) in [
741            (COMMAND_GET_DRONE, "GetDroneReq", "DroneDefinition"),
742            (COMMAND_UPSERT_DRONE, "DroneDefinition", "DroneDefinition"),
743            (COMMAND_DELETE_DRONE, "DeleteDroneReq", "DeleteResp"),
744            (COMMAND_RUN_DRONE, "RunDroneReq", "RunResp"),
745            (COMMAND_RESOLVE_DRONE_RUN, "ResolveRunReq", "ResolveRunResp"),
746            (COMMAND_RESUME_DRONE_WAIT, "ResumeWaitReq", "ResumeWaitResp"),
747            (COMMAND_REPLAY_DRONE_RUN, "ReplayRunReq", "ReplayRunResp"),
748            (crate::backend::rpc_types::COMMAND_GET_DRONE_ACCESS, "GetDroneAccessReq", "DroneAccess"),
749            (crate::backend::rpc_types::COMMAND_SET_DRONE_AGENTS, "SetDroneAgentsReq", "DroneAccess"),
750        ] {
751            let row = find(cmd);
752            assert_eq!(row["requestName"], req, "{cmd} request");
753            assert!(
754                row["responseName"].as_str().unwrap().contains(resp),
755                "{cmd} response should mention {resp}, got {:?}",
756                row["responseName"],
757            );
758        }
759
760        // The two list commands answer `Vec<_>`, whose recorded name keeps its
761        // full path (truncating at the last `::` would yield `DroneRun>`).
762        for (cmd, elem) in [
763            (COMMAND_LIST_DRONES, "DroneDefinition"),
764            (COMMAND_LIST_DRONE_RUNS, "DroneRun"),
765        ] {
766            let got = find(cmd)["responseName"].as_str().unwrap().to_string();
767            assert!(
768                got.starts_with("alloc::vec::Vec<") && got.contains(elem),
769                "{cmd} should answer Vec<{elem}>, got {got:?}",
770            );
771        }
772    }
773
774    /// `listdrones` takes no argument, and the two encodings of that both
775    /// reach the server: the stub sends `{}`, a client that omits `data`
776    /// sends `null`. A bare struct rejects the second, a `()` rejects the
777    /// first — `Option<ListDronesReq>` is what takes both.
778    #[test]
779    fn listdrones_request_accepts_both_encodings_of_no_argument() {
780        for payload in [serde_json::json!({}), serde_json::Value::Null] {
781            serde_json::from_value::<Option<ListDronesReq>>(payload.clone())
782                .unwrap_or_else(|e| panic!("{payload} should deserialize, got {e}"));
783        }
784        // ...and the bare struct really does reject null, so the Option is
785        // load-bearing rather than decoration.
786        assert!(serde_json::from_value::<ListDronesReq>(serde_json::Value::Null).is_err());
787    }
788
789    /// `limit` is `serde(default)`, which ts-rs cannot express on a non-Option
790    /// field — the stub's `ListDroneRunsInput` restores the optionality by
791    /// deriving from the generated type. Pin the server half: drop the default
792    /// and that derived TS type becomes a lie.
793    #[test]
794    fn listruns_request_accepts_a_missing_limit() {
795        let req: ListRunsReq =
796            serde_json::from_value(serde_json::json!({ "drone_id": "d1" }))
797                .expect("limit is serde(default) and may be omitted");
798        assert_eq!(req.drone_id, "d1");
799        assert_eq!(req.limit, default_limit(), "an omitted limit falls back to the default");
800    }
801
802    fn drone_named(name: &str) -> DroneDefinition {
803        serde_json::from_value(serde_json::json!({ "id": "", "name": name, "created_at": 0, "updated_at": 0 })).unwrap()
804    }
805
806    fn run_row(id: &str, drone_id: &str, started_at: i64) -> DroneRun {
807        DroneRun {
808            id: id.to_string(),
809            drone_id: drone_id.to_string(),
810            status: RunStatus::Done.as_str().to_string(),
811            started_at,
812            ended_at: started_at + 1,
813            block_states: HashMap::new(),
814            output: String::new(),
815            error: String::new(),
816        }
817    }
818
819    /// The handlers run without the engine: an upsert mints an id and stamps
820    /// both times, and `get` and `list` then agree with it.
821    #[tokio::test]
822    async fn upsert_get_and_list_drones_agree() {
823        let state = crate::server::tests::test_state();
824        let saved = upsert_drone(&state, drone_named("nightly")).unwrap();
825        assert!(!saved.id.is_empty(), "a new drone gets an id");
826        assert!(saved.created_at > 0 && saved.updated_at >= saved.created_at);
827
828        let got = get_drone(&state, GetDroneReq { id: saved.id.clone() }).unwrap().expect("saved drone is found");
829        assert_eq!(got.name, "nightly");
830        assert!(list_drones(&state).unwrap().iter().any(|d| d.id == saved.id));
831        assert!(get_drone(&state, GetDroneReq { id: "nope".into() }).unwrap().is_none());
832    }
833
834    /// A `created_at` the caller sends is kept; only a zero one is stamped.
835    #[tokio::test]
836    async fn upsert_drone_keeps_a_created_time_the_caller_sends() {
837        let state = crate::server::tests::test_state();
838        let mut first = drone_named("keeps-created");
839        first.created_at = 1_000;
840        let saved = upsert_drone(&state, first).unwrap();
841        assert_eq!(saved.created_at, 1_000);
842        assert!(saved.updated_at > 1_000);
843    }
844
845    /// Deleting a drone removes its run history too, nothing cascades (m0038),
846    /// and a second delete reports false rather than erroring.
847    #[tokio::test]
848    async fn delete_drone_removes_its_runs_and_reports_whether_it_existed() {
849        let state = crate::server::tests::test_state();
850        let saved = upsert_drone(&state, drone_named("doomed")).unwrap();
851        state.mstore.drone_run_insert(&run_row("run-doomed", &saved.id, 5)).unwrap();
852
853        assert!(delete_drone(&state, DeleteDroneReq { id: saved.id.clone() }).unwrap().deleted);
854        assert!(get_drone(&state, GetDroneReq { id: saved.id.clone() }).unwrap().is_none());
855        assert!(state.mstore.drone_runs_for(&saved.id, 10).unwrap().is_empty(), "the run history goes with it");
856        assert!(!delete_drone(&state, DeleteDroneReq { id: saved.id }).unwrap().deleted);
857    }
858
859    /// `limit` is clamped into 0..=MAX_LIST_LIMIT rather than trusted.
860    #[tokio::test]
861    async fn list_drone_runs_clamps_the_limit() {
862        let state = crate::server::tests::test_state();
863        for (i, id) in ["r1", "r2", "r3"].iter().enumerate() {
864            state.mstore.drone_run_insert(&run_row(id, "clamp-drone", i as i64)).unwrap();
865        }
866        let list = |limit: i64| list_drone_runs(&state, ListRunsReq { drone_id: "clamp-drone".into(), limit }).unwrap();
867        assert_eq!(list(2).len(), 2);
868        assert_eq!(list(-5).len(), 0, "a negative limit is clamped to none, not an error");
869        assert_eq!(list(i64::MAX).len(), 3, "a huge limit is capped, and still returns what exists");
870    }
871
872    /// The record names the connection's own identity: the person's window is `operator`, an agent is `agent:<id>`
873    /// (and no agent id can read as `operator`), and a connection that has proved nothing is not the operator.
874    #[test]
875    fn a_call_is_recorded_as_its_connection_and_never_as_what_it_claims() {
876        let agent = RpcContext { agent_id: "opaz".into(), ..Default::default() };
877        let named_operator = RpcContext { agent_id: "operator".into(), operator_proven: true, ..Default::default() };
878        assert_eq!(recorded_as(&RpcContext::operator_for_tests()), "operator");
879        assert_eq!(recorded_as(&agent), "agent:opaz");
880        assert_eq!(recorded_as(&named_operator), "agent:operator", "an agent called operator is still an agent, proof flag or not");
881        assert_eq!(recorded_as(&RpcContext::default()), "unproven");
882        assert_eq!(run_started_by(&RpcContext::operator_for_tests()), None, "the window is the ledger's default, the operator");
883        assert_eq!(run_started_by(&agent).as_deref(), Some("agent:opaz"));
884        assert_eq!(run_started_by(&named_operator).as_deref(), Some("agent:operator"));
885        assert_eq!(run_started_by(&RpcContext::default()).as_deref(), Some("unproven"));
886    }
887
888    /// A drone an agent saves has a version that says so, and one the window saves says `operator`.
889    #[tokio::test]
890    async fn a_drone_an_agent_saves_is_shown_as_that_agents() {
891        let state = crate::server::tests::test_state();
892        let agent = RpcContext { agent_id: "opaz".into(), ..Default::default() };
893        let by_agent = upsert_drone_as(&state, drone_named("agents drone"), &recorded_as(&agent)).unwrap();
894        let by_window = upsert_drone_as(&state, drone_named("windows drone"), &recorded_as(&RpcContext::operator_for_tests())).unwrap();
895        let saved_by = |id: &str| state.id_store.version_resolve(id, Pin::Latest).unwrap().expect("a version").saved_by;
896        assert_eq!(saved_by(&by_agent.id), "agent:opaz");
897        assert_eq!(saved_by(&by_window.id), "operator");
898        // A save with no caller behind it (a template the person installed) is the operator's, as before.
899        let plain = upsert_drone(&state, drone_named("installed")).unwrap();
900        assert_eq!(saved_by(&plain.id), "operator");
901    }
902
903    /// The agent that makes a drone owns it; a person's drone has no owner; a later save, by anyone, leaves the
904    /// owner as it was; deleting the drone forgets it.
905    #[tokio::test]
906    async fn an_agent_that_makes_a_drone_owns_it_and_a_later_save_changes_nothing() {
907        let state = crate::server::tests::test_state();
908        let owner_of = |id: &str| state.id_store.access_get(id).unwrap().owner;
909        let opaz = RpcContext { agent_id: "Opaz".into(), ..Default::default() };
910        let korp = RpcContext { agent_id: "korp".into(), ..Default::default() };
911        let made = upsert_drone_as(&state, drone_named("opaz's"), &recorded_as(&opaz)).unwrap();
912        assert_eq!(owner_of(&made.id), "opaz", "kept in lower case");
913        let mut renamed = made.clone();
914        renamed.name = "renamed by korp".into();
915        upsert_drone_as(&state, renamed, &recorded_as(&korp)).unwrap();
916        assert_eq!(owner_of(&made.id), "opaz", "another agent's edit does not take the drone");
917        let by_window = upsert_drone_as(&state, drone_named("the person's"), &recorded_as(&RpcContext::operator_for_tests())).unwrap();
918        assert_eq!(owner_of(&by_window.id), "", "a person's drone has no owner");
919        let mut taken = by_window.clone();
920        taken.name = "an agent edits it".into();
921        upsert_drone_as(&state, taken, &recorded_as(&opaz)).unwrap();
922        assert_eq!(owner_of(&by_window.id), "", "editing a person's drone does not make it the agent's");
923        delete_drone_as(&state, DeleteDroneReq { id: made.id.clone() }, "operator").unwrap();
924        assert_eq!(state.id_store.access_get(&made.id).unwrap(), crate::drone::access::DroneAccess::default());
925    }
926
927    #[tokio::test]
928    async fn start_drone_run_of_an_unknown_drone_is_an_error() {
929        let state = crate::server::tests::test_state();
930        let err = start_drone_run(&state, RunDroneReq { drone_id: "ghost".into(), input: None }).await.unwrap_err();
931        assert_eq!(err, "rundrone: drone ghost not found");
932    }
933
934    /// A run leaves its row behind before the call returns, so the pane's
935    /// refresh right after sees it.
936    #[tokio::test]
937    async fn start_drone_run_leaves_a_run_row_before_it_returns() {
938        let state = crate::server::tests::test_state();
939        let saved = upsert_drone(&state, drone_named("runs")).unwrap();
940        let resp = start_drone_run(&state, RunDroneReq { drone_id: saved.id.clone(), input: None }).await.unwrap();
941        let runs = state.mstore.drone_runs_for(&saved.id, 10).unwrap();
942        assert!(runs.iter().any(|r| r.id == resp.run_id), "the run row exists: {runs:?}");
943    }
944}