agentmux_srv/server/prep/
handlers.rs1use std::sync::Arc;
8
9use axum::extract::State;
10use axum::http::StatusCode;
11use axum::response::{IntoResponse, Response};
12use axum::{Extension, Json};
13use serde::{Deserialize, Serialize};
14use serde_json::json;
15
16use crate::backend::rpc::engine::WshRpcEngine;
17use crate::backend::rpc_types::COMMAND_AGENT_PREP_NOW;
18use crate::server::caller::Caller;
19use crate::server::AppState;
20
21use super::ledger::{self, Answer};
22
23#[derive(Debug, Deserialize)]
24pub struct ReadyRequest {
25 agent: String,
27 #[serde(default)]
28 handoff: Option<String>,
29 #[serde(default)]
30 more_time: bool,
31 #[serde(default)]
32 why: Option<String>,
33}
34
35fn refused(status: StatusCode, why: &str) -> Response {
36 (status, Json(json!({ "error": why }))).into_response()
37}
38
39pub async fn handle_ready_self(State(state): State<AppState>, caller: Option<Extension<Caller>>, Json(req): Json<ReadyRequest>) -> Response {
42 let Some(block_id) = crate::server::actor::own_pane_by_token(&state.mstore, caller.as_deref(), req.agent.trim()) else {
43 return refused(StatusCode::UNAUTHORIZED, "no pane for this agent token: Agents ready answers only the calling agent's own change");
44 };
45 let def_id = match state.mstore.get::<crate::backend::obj::Block>(&block_id) {
46 Ok(Some(b)) => crate::backend::obj::meta_get_string(&b.meta, "agentId", ""),
47 _ => String::new(),
48 };
49 if def_id.is_empty() {
50 return refused(StatusCode::BAD_REQUEST, "the pane is not an agent's");
51 }
52 let slug = req.agent.trim().to_string();
53 let answer = Answer { handoff: req.handoff, more_time: req.more_time, why: req.why };
54 let result = tokio::task::spawn_blocking(move || ledger::answer(&state, &def_id, &slug, answer)).await;
55 match result {
56 Ok(Ok(body)) => Json(body).into_response(),
57 Ok(Err(why)) => refused(StatusCode::CONFLICT, &why),
58 Err(e) => refused(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
59 }
60}
61
62#[derive(Debug, Clone, Deserialize, ts_rs::TS)]
64#[ts(export, export_to = "../../../frontend/types/rpc/")]
65pub struct AgentPrepNowReq {
66 pub agent_id: String,
67}
68
69#[derive(Debug, Clone, Serialize, ts_rs::TS)]
70#[ts(export, export_to = "../../../frontend/types/rpc/")]
71pub struct AgentPrepNowResult {
72 pub ended: bool,
74}
75
76pub fn register(engine: &Arc<WshRpcEngine>, _state: &AppState) {
79 engine.register_typed(COMMAND_AGENT_PREP_NOW, move |req: AgentPrepNowReq, ctx| async move {
80 if ctx.agent_id.is_empty() {
81 ctx.operator_only("only the AgentMux window or an agent ends a change's window")?;
82 }
83 Ok(AgentPrepNowResult { ended: ledger::person_says_now(req.agent_id.trim(), &ctx.agent_id).is_ok() })
84 });
85}