1use std::sync::Arc;
6
7use crate::backend::rpc::engine::WshRpcEngine;
8use crate::backend::rpc_types::{
9 COMMAND_LIST_AGENT_INSTANCES, COMMAND_GET_AGENT_INSTANCE,
10 COMMAND_CREATE_AGENT_INSTANCE, COMMAND_UPDATE_AGENT_INSTANCE,
11 COMMAND_DELETE_AGENT_INSTANCE, COMMAND_AGENT_LAST_RUNTIME,
12 AgentLastRuntime, CommandAgentLastRuntimeData,
13 CommandListAgentInstancesData, CommandGetAgentInstanceData,
14 CommandCreateAgentInstanceData, CommandUpdateAgentInstanceData,
15 CommandDeleteAgentInstanceData, DeleteAgentInstanceResult,
16};
17use crate::backend::storage::store::{
18 AgentInstance, InstanceStatus,
19};
20
21use super::super::AppState;
22
23pub(crate) fn list_agent_instances(
33 state: &AppState,
34 cmd: Option<CommandListAgentInstancesData>,
35) -> Result<Vec<AgentInstance>, String> {
36 let cmd = cmd.unwrap_or_default();
37 let rows = state
38 .mstore
39 .instance_list(cmd.definition_id.as_deref(), cmd.status.as_deref())
40 .map_err(|e| format!("listagentinstances: {e}"))?;
41 Ok(rows)
42}
43
44pub(crate) fn get_agent_instance(
46 state: &AppState,
47 cmd: CommandGetAgentInstanceData,
48) -> Result<AgentInstance, String> {
49 state
53 .mstore
54 .instance_get(&cmd.id)
55 .map_err(|e| format!("getagentinstance: {e}"))?
56 .ok_or_else(|| format!("getagentinstance: not found id={}", cmd.id))
57}
58
59fn stamp_session_zone(state: &AppState, inst: &AgentInstance) {
66 if !inst.block_id.is_empty()
67 && crate::backend::agent_session::is_valid_definition_id(&inst.definition_id)
68 {
69 let zone = crate::backend::agent_session::agent_current_zone(
70 &inst.definition_id,
71 );
72 let mut meta_update = crate::backend::obj::MetaMapType::new();
73 meta_update.insert(
74 "agent:sessionZone".to_string(),
75 serde_json::json!(zone),
76 );
77 let oref_str = format!("block:{}", inst.block_id);
78 if let Err(e) = crate::server::service::update_object_meta(
79 &state.mstore, &oref_str, &meta_update,
80 ) {
81 tracing::warn!(
86 block_id = %inst.block_id,
87 definition_id = %inst.definition_id,
88 error = %e,
89 "createagentinstance: failed to stamp agent:sessionZone"
90 );
91 }
92 }
93}
94
95pub(crate) fn create_agent_instance(
97 state: &AppState,
98 cmd: CommandCreateAgentInstanceData,
99) -> Result<AgentInstance, String> {
100 let mstore = &state.mstore;
101 if cmd.parent_instance_id.is_empty()
107 && mstore.agent_def_get(&cmd.definition_id).ok().flatten().is_some_and(|d| d.is_seeded == 1)
108 {
109 return Err(format!(
110 "TEMPLATE_NOT_LAUNCHABLE: '{}' is a template; create an agent from it first",
111 cmd.definition_id
112 ));
113 }
114 let now = agentmux_common::time::now_ms();
115 let inst = AgentInstance {
116 id: uuid::Uuid::new_v4().to_string(),
117 definition_id: cmd.definition_id,
118 parent_instance_id: cmd.parent_instance_id,
119 block_id: cmd.block_id,
120 session_id: String::new(),
121 status: InstanceStatus::Running.as_str().to_string(),
122 github_context: String::new(),
123 started_at: now,
124 ended_at: 0,
125 created_at: now,
126 identity_id: cmd.identity_id,
131 memory_id: cmd.memory_id,
132 instance_name: cmd.instance_name.clone(),
138 working_directory: cmd.working_directory.clone(),
139 display_hidden: false,
140 };
141 let created = mstore
152 .instance_create(&inst)
153 .map_err(|e| format!("createagentinstance: {e}"))?;
154
155 stamp_session_zone(state, &inst);
156
157 state.broker.publish_event_for::<crate::backend::mps_events::AgentInstancesChanged>(&inst.definition_id, &(), vec![], 0);
158 Ok(created)
159}
160
161pub(crate) fn update_agent_instance(
163 state: &AppState,
164 cmd: CommandUpdateAgentInstanceData,
165) -> Result<AgentInstance, String> {
166 let upd = crate::backend::storage::InstanceUpdate {
175 block_id: cmd.block_id,
176 session_id: cmd.session_id,
177 status: cmd.status,
178 github_context: cmd.github_context,
179 ended_at: cmd.ended_at,
180 };
181 let fresh = state
182 .mstore
183 .instance_update_partial(&cmd.id, &upd)
184 .map_err(|e| format!("updateagentinstance: {e}"))?
185 .ok_or_else(|| format!("updateagentinstance: not found id={}", cmd.id))?;
186 state.broker.publish_event_for::<crate::backend::mps_events::AgentInstancesChanged>(&fresh.definition_id, &(), vec![], 0);
187 Ok(fresh)
188}
189
190pub(crate) fn agent_last_runtime(
192 state: &AppState,
193 cmd: CommandAgentLastRuntimeData,
194) -> Result<AgentLastRuntime, String> {
195 if let Some(raw) = &cmd.runtime {
196 let normalized = crate::backend::storage::agents::normalize_last_runtime(raw)
197 .map_err(|e| format!("agentlastruntime: {e}"))?;
198 state
199 .mstore
200 .agent_last_runtime_set(&cmd.id, &normalized)
201 .map_err(|e| format!("agentlastruntime: {e}"))?;
202 }
203 let runtime = state
204 .mstore
205 .agent_last_runtime_get(&cmd.id)
206 .map_err(|e| format!("agentlastruntime: {e}"))?;
207 Ok(AgentLastRuntime { runtime })
208}
209
210pub(crate) async fn delete_agent_instance(
212 state: &AppState,
213 cmd: CommandDeleteAgentInstanceData,
214) -> Result<DeleteAgentInstanceResult, String> {
215 crate::sagas::park_agents::delete_parked_blocks_of(state, &cmd.id).await;
217 let definition_id = state
219 .mstore
220 .instance_get(&cmd.id)
221 .map_err(|e| format!("deleteagentinstance: {e}"))?
222 .map(|i| i.definition_id);
223 let deleted = state
224 .mstore
225 .instance_delete(&cmd.id)
226 .map_err(|e| format!("deleteagentinstance: {e}"))?;
227 super::purge_identity_store_rows(&state.identity_store, &state.id_store, &cmd.id, "deleteagentinstance");
237 if let Some(def_id) = definition_id.filter(|_| deleted) {
238 state.broker.publish_event_for::<crate::backend::mps_events::AgentInstancesChanged>(&def_id, &(), vec![], 0);
239 }
240 Ok(DeleteAgentInstanceResult { deleted })
241}
242
243pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
244 let s = state.clone();
245 engine.register_typed(
246 COMMAND_LIST_AGENT_INSTANCES,
247 move |cmd: Option<CommandListAgentInstancesData>, _ctx| {
248 let s = s.clone();
249 async move { list_agent_instances(&s, cmd) }
250 },
251 );
252
253 let s = state.clone();
254 engine.register_typed(COMMAND_GET_AGENT_INSTANCE, move |cmd: CommandGetAgentInstanceData, _ctx| {
255 let s = s.clone();
256 async move { get_agent_instance(&s, cmd) }
257 });
258
259 let s = state.clone();
260 engine.register_typed(COMMAND_CREATE_AGENT_INSTANCE, move |cmd: CommandCreateAgentInstanceData, _ctx| {
261 let s = s.clone();
262 async move { create_agent_instance(&s, cmd) }
263 });
264
265 let s = state.clone();
266 engine.register_typed(COMMAND_UPDATE_AGENT_INSTANCE, move |cmd: CommandUpdateAgentInstanceData, _ctx| {
267 let s = s.clone();
268 async move { update_agent_instance(&s, cmd) }
269 });
270
271 let s = state.clone();
272 engine.register_typed(COMMAND_AGENT_LAST_RUNTIME, move |cmd: CommandAgentLastRuntimeData, _ctx| {
273 let s = s.clone();
274 async move { agent_last_runtime(&s, cmd) }
275 });
276
277 let s = state.clone();
278 engine.register_typed(COMMAND_DELETE_AGENT_INSTANCE, move |cmd: CommandDeleteAgentInstanceData, _ctx| {
279 let s = s.clone();
280 async move { delete_agent_instance(&s, cmd).await }
281 });
282}
283
284#[cfg(test)]
285mod tests {
286 use super::*;
287 use crate::backend::rpc::engine::WshRpcEngine;
288 use crate::server::tests::test_state;
289
290 #[tokio::test]
298 async fn register_typed_records_the_four_instance_crud_commands() {
299 let state = crate::server::tests::test_state();
300 let (engine, _rx) = WshRpcEngine::new();
301 register(&engine, &state);
302 let schema = engine.schema_json();
303 let rows = schema.as_array().unwrap();
304 let find = |cmd: &str| {
305 rows.iter()
306 .find(|r| r["command"] == cmd)
307 .unwrap_or_else(|| panic!("{cmd} missing from the schema"))
308 };
309
310 for (cmd, resp) in [
311 (crate::backend::rpc_types::COMMAND_GET_AGENT_INSTANCE, "AgentInstance"),
312 (crate::backend::rpc_types::COMMAND_CREATE_AGENT_INSTANCE, "AgentInstance"),
313 (crate::backend::rpc_types::COMMAND_UPDATE_AGENT_INSTANCE, "AgentInstance"),
314 ] {
315 assert_eq!(find(cmd)["responseName"], resp, "{cmd} response");
316 }
317 let list = find(crate::backend::rpc_types::COMMAND_LIST_AGENT_INSTANCES);
318 let list_resp = list["responseName"].as_str().unwrap();
319 assert!(
320 list_resp.starts_with("alloc::vec::Vec<") && list_resp.contains("AgentInstance"),
321 "listagentinstances should answer Vec<AgentInstance>, got {list_resp:?}",
322 );
323 }
324
325 #[tokio::test]
338 async fn listagentinstances_accepts_no_filter_but_rejects_a_malformed_one() {
339 let state = crate::server::tests::test_state();
340 let (engine, mut rx) = WshRpcEngine::new();
341 register(&engine, &state);
342
343 let call = |payload: serde_json::Value, reqid: &str| {
344 engine.handle_message(crate::backend::rpc_types::RpcMessage {
345 command: crate::backend::rpc_types::COMMAND_LIST_AGENT_INSTANCES.to_string(),
346 reqid: reqid.to_string(),
347 data: Some(payload),
348 ..Default::default()
349 });
350 };
351
352 for (i, payload) in [serde_json::json!({}), serde_json::Value::Null]
353 .into_iter()
354 .enumerate()
355 {
356 call(payload.clone(), &format!("ok-{i}"));
357 let resp = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
358 .await
359 .unwrap()
360 .unwrap();
361 assert!(
362 resp.error.is_empty(),
363 "{payload} means no filter and must be accepted, got {:?}",
364 resp.error,
365 );
366 }
367
368 call(serde_json::json!({ "status": 5 }), "bad");
369 let resp = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
370 .await
371 .unwrap()
372 .unwrap();
373 assert!(
374 !resp.error.is_empty(),
375 "a malformed filter must not be silently answered with the unfiltered list",
376 );
377 }
378
379 #[tokio::test]
381 async fn register_typed_records_deleteagentinstance() {
382 let state = test_state();
383 let (engine, _rx) = WshRpcEngine::new();
384 register(&engine, &state);
385 let schema = engine.schema_json();
386 let rows = schema.as_array().unwrap();
387 let row = rows
388 .iter()
389 .find(|r| r["command"] == COMMAND_DELETE_AGENT_INSTANCE)
390 .expect("deleteagentinstance missing from the schema");
391 assert_eq!(row["requestName"], "CommandDeleteAgentInstanceData");
392 assert_eq!(row["responseName"], "DeleteAgentInstanceResult");
393 for cmd in [
401 COMMAND_LIST_AGENT_INSTANCES,
402 COMMAND_GET_AGENT_INSTANCE,
403 COMMAND_CREATE_AGENT_INSTANCE,
404 COMMAND_UPDATE_AGENT_INSTANCE,
405 ] {
406 assert!(
407 rows.iter().any(|r| r["command"] == cmd),
408 "{cmd} is migrated and must appear in the schema",
409 );
410 }
411 }
412
413 #[tokio::test]
416 async fn createagentinstance_refuses_a_fresh_template_launch() {
417 let state = crate::server::tests::test_state();
418 for (id, seeded) in [("tpl-x", 1), ("mine-x", 0)] {
419 let mut def: crate::backend::storage::AgentDefinition = serde_json::from_value(serde_json::json!({
420 "id": id, "name": id, "icon": "wand-magic-sparkles", "provider": "claude",
421 "description": "", "created_at": 1, "is_seeded": seeded,
422 }))
423 .unwrap();
424 state.mstore.agent_def_insert(&mut def).unwrap();
425 }
426 let (engine, mut rx) = WshRpcEngine::new();
427 register(&engine, &state);
428 let mut call = |n: u32, id: &str| {
429 engine.handle_message(crate::backend::rpc_types::RpcMessage {
430 command: COMMAND_CREATE_AGENT_INSTANCE.to_string(),
431 reqid: format!("r{n}"),
432 data: Some(serde_json::json!({ "definition_id": id })),
433 ..Default::default()
434 });
435 };
436
437 call(1, "tpl-x");
438 let r = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv()).await.unwrap().unwrap();
439 assert!(r.error.starts_with("TEMPLATE_NOT_LAUNCHABLE"), "{:?}", r.error);
440 assert!(state.mstore.instance_list(Some("tpl-x"), None).unwrap().is_empty(), "no row was made");
441
442 call(2, "mine-x");
443 let r = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv()).await.unwrap().unwrap();
444 assert!(r.error.is_empty(), "{:?}", r.error);
445 }
446
447 #[tokio::test]
450 async fn agentlastruntime_reads_replaces_forgets_and_refuses_bad_values() {
451 let state = crate::server::tests::test_state();
452 let mut agent: crate::backend::storage::AgentDefinition = serde_json::from_value(serde_json::json!({
453 "id": "rt-agent",
454 "name": "rt-agent",
455 "icon": "wand-magic-sparkles",
456 "provider": "claude",
457 "description": "",
458 "created_at": 1,
459 }))
460 .unwrap();
461 state.mstore.agent_def_insert(&mut agent).unwrap();
462 let (engine, mut rx) = WshRpcEngine::new();
463 register(&engine, &state);
464
465 let mut n = 0;
466 let mut call = |payload: serde_json::Value| {
467 n += 1;
468 engine.handle_message(crate::backend::rpc_types::RpcMessage {
469 command: COMMAND_AGENT_LAST_RUNTIME.to_string(),
470 reqid: format!("r{n}"),
471 data: Some(payload),
472 ..Default::default()
473 });
474 };
475 macro_rules! next {
476 () => {
477 tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
478 .await
479 .unwrap()
480 .unwrap()
481 };
482 }
483
484 call(serde_json::json!({ "id": "rt-agent" }));
485 let r = next!();
486 assert!(r.error.is_empty(), "{:?}", r.error);
487 assert_eq!(r.data.unwrap()["runtime"], "");
488
489 call(serde_json::json!({ "id": "rt-agent", "runtime": r#"{"model":"opus","effort":"high"}"# }));
490 let r = next!();
491 assert!(r.error.is_empty(), "{:?}", r.error);
492 assert_eq!(r.data.unwrap()["runtime"], r#"{"effort":"high","model":"opus"}"#);
493
494 call(serde_json::json!({ "id": "rt-agent", "runtime": r#"{"colour":"red"}"# }));
495 let r = next!();
496 assert!(!r.error.is_empty(), "an unknown key is refused");
497
498 call(serde_json::json!({ "id": "rt-agent" }));
499 assert_eq!(next!().data.unwrap()["runtime"], r#"{"effort":"high","model":"opus"}"#, "a refused write changes nothing");
500
501 call(serde_json::json!({ "id": "rt-agent", "runtime": "" }));
502 assert_eq!(next!().data.unwrap()["runtime"], "");
503 }
504
505 fn insert_agent(state: &AppState, id: &str, seeded: i64) {
506 let mut def: crate::backend::storage::AgentDefinition = serde_json::from_value(serde_json::json!({
507 "id": id, "name": id, "icon": "wand-magic-sparkles", "provider": "claude",
508 "description": "", "created_at": 1, "is_seeded": seeded,
509 }))
510 .unwrap();
511 state.mstore.agent_def_insert(&mut def).unwrap();
512 }
513
514 fn launch(state: &AppState, def: &str) -> AgentInstance {
515 create_agent_instance(state, serde_json::from_value(serde_json::json!({ "definition_id": def })).unwrap()).unwrap()
516 }
517
518 #[tokio::test]
521 async fn create_get_and_list_agent_instances_agree() {
522 let state = test_state();
523 insert_agent(&state, "inst-a", 0);
524 insert_agent(&state, "inst-b", 0);
525 let a = launch(&state, "inst-a");
526 launch(&state, "inst-b");
527 assert_eq!(a.status, "running");
528
529 let got = get_agent_instance(&state, serde_json::from_value(serde_json::json!({ "id": a.id })).unwrap()).unwrap();
530 assert_eq!(got.definition_id, "inst-a");
531
532 let only_a = list_agent_instances(
533 &state,
534 Some(serde_json::from_value(serde_json::json!({ "definition_id": "inst-a" })).unwrap()),
535 )
536 .unwrap();
537 assert_eq!(only_a.len(), 1);
538 assert_eq!(list_agent_instances(&state, None).unwrap().len(), 2);
539 }
540
541 #[tokio::test]
542 async fn get_agent_instance_errors_when_the_row_is_missing() {
543 let state = test_state();
544 let err = get_agent_instance(&state, serde_json::from_value(serde_json::json!({ "id": "nope" })).unwrap()).unwrap_err();
545 assert_eq!(err, "getagentinstance: not found id=nope");
546 }
547
548 #[tokio::test]
550 async fn create_agent_instance_refuses_a_template_but_not_a_continuation() {
551 let state = test_state();
552 insert_agent(&state, "tpl-direct", 1);
553 let fresh = serde_json::from_value(serde_json::json!({ "definition_id": "tpl-direct" })).unwrap();
554 let err = create_agent_instance(&state, fresh).unwrap_err();
555 assert!(err.starts_with("TEMPLATE_NOT_LAUNCHABLE"), "{err}");
556 assert!(state.mstore.instance_list(Some("tpl-direct"), None).unwrap().is_empty());
557
558 let cont = serde_json::from_value(serde_json::json!({
559 "definition_id": "tpl-direct", "parent_instance_id": "earlier",
560 }))
561 .unwrap();
562 assert!(create_agent_instance(&state, cont).is_ok());
563 }
564
565 #[tokio::test]
567 async fn update_agent_instance_writes_only_the_named_fields() {
568 let state = test_state();
569 insert_agent(&state, "inst-u", 0);
570 let inst = launch(&state, "inst-u");
571
572 let upd = serde_json::from_value(serde_json::json!({ "id": inst.id, "status": "ended", "ended_at": 42 })).unwrap();
573 let fresh = update_agent_instance(&state, upd).unwrap();
574 assert_eq!(fresh.status, "ended");
575 assert_eq!(fresh.ended_at, 42);
576 assert_eq!(fresh.definition_id, "inst-u");
577
578 let missing = serde_json::from_value(serde_json::json!({ "id": "nope", "status": "ended" })).unwrap();
579 assert_eq!(update_agent_instance(&state, missing).unwrap_err(), "updateagentinstance: not found id=nope");
580 }
581
582 #[tokio::test]
583 async fn agent_last_runtime_handler_reads_replaces_and_refuses_bad_values() {
584 let state = test_state();
585 insert_agent(&state, "rt-direct", 0);
586 let call = |v: serde_json::Value| agent_last_runtime(&state, serde_json::from_value(v).unwrap());
587
588 assert_eq!(call(serde_json::json!({ "id": "rt-direct" })).unwrap().runtime, "");
589 let set = call(serde_json::json!({ "id": "rt-direct", "runtime": r#"{"model":"opus"}"# })).unwrap();
590 assert_eq!(set.runtime, r#"{"model":"opus"}"#);
591 assert!(call(serde_json::json!({ "id": "rt-direct", "runtime": r#"{"colour":"red"}"# })).is_err());
592 assert_eq!(call(serde_json::json!({ "id": "rt-direct" })).unwrap().runtime, r#"{"model":"opus"}"#);
593 }
594
595 #[tokio::test]
598 async fn delete_agent_instance_reports_whether_a_row_was_removed() {
599 let state = test_state();
600 insert_agent(&state, "inst-d", 0);
601 let inst = launch(&state, "inst-d");
602 let del = |id: &str| delete_agent_instance(&state, serde_json::from_value(serde_json::json!({ "id": id })).unwrap());
603
604 assert!(del(&inst.id).await.unwrap().deleted);
605 assert!(state.mstore.instance_get(&inst.id).unwrap().is_none());
606 assert!(!del(&inst.id).await.unwrap().deleted);
607 }
608}