1use serde::{Deserialize, Serialize};
6
7use crate::activity::Activity;
8
9#[derive(Debug, Deserialize)]
11#[serde(rename_all = "camelCase")]
12pub struct AgentChatRequest {
13 pub text: String,
14 #[serde(default)]
15 pub tenant: Option<String>,
16 #[serde(default)]
17 pub conversation_id: Option<String>,
18 #[serde(default)]
19 pub user_id: Option<String>,
20 #[serde(default)]
21 pub flow_id: Option<String>,
22 #[serde(default, rename = "resume_payload", alias = "resumePayload")]
30 pub resume_payload: Option<serde_json::Map<String, serde_json::Value>>,
31}
32
33pub(crate) fn turn_payload(
37 text: String,
38 resume_payload: Option<serde_json::Map<String, serde_json::Value>>,
39) -> serde_json::Value {
40 match resume_payload {
41 None => serde_json::json!({ "text": text }),
42 Some(mut submit) => {
43 if !text.trim().is_empty() {
44 submit
45 .entry("text")
46 .or_insert(serde_json::Value::String(text));
47 }
48 serde_json::Value::Object(submit)
49 }
50 }
51}
52
53pub(crate) fn pending_card(
57 node_outputs: &std::collections::HashMap<String, serde_json::Value>,
58) -> Option<serde_json::Value> {
59 node_outputs
60 .values()
61 .find_map(crate::runner::engine::tool_presentation)
62 .cloned()
63}
64
65fn side_turn_reply(
68 node_outputs: &std::collections::HashMap<String, serde_json::Value>,
69) -> Option<String> {
70 node_outputs.values().find_map(|output| {
71 let is_side_turn = output.get("side_turn").and_then(|v| v.as_bool()) == Some(true);
72 let reply = output.get("reply").and_then(|v| v.as_str())?;
73 (is_side_turn && !reply.trim().is_empty()).then(|| reply.to_string())
74 })
75}
76
77#[derive(Debug, Serialize)]
79#[serde(rename_all = "camelCase")]
80pub struct ReplyView {
81 pub text: String,
82}
83
84#[derive(Debug, Serialize)]
86#[serde(rename_all = "camelCase")]
87pub struct AgentChatResponse {
88 pub replies: Vec<ReplyView>,
89 #[serde(rename = "pending_card", skip_serializing_if = "Option::is_none")]
92 pub pending_card: Option<serde_json::Value>,
93}
94
95fn reply_text(activity: &Activity) -> String {
102 let payload = activity.payload();
103 if let Some(t) = payload.get("text").and_then(|v| v.as_str()) {
104 return t.to_string();
105 }
106 if let Some(t) = payload
107 .get("messages")
108 .and_then(|m| m.get(0))
109 .and_then(|m0| m0.get("text"))
110 .and_then(|v| v.as_str())
111 {
112 return t.to_string();
113 }
114 serde_json::to_string(payload).unwrap_or_default()
115}
116
117pub fn replies_to_response(activities: Vec<Activity>) -> AgentChatResponse {
119 let replies = activities
120 .iter()
121 .map(reply_text)
122 .filter(|t| !t.trim().is_empty())
123 .map(|text| ReplyView { text })
124 .collect();
125 AgentChatResponse {
126 replies,
127 pending_card: None,
128 }
129}
130
131pub fn trace_to_response(trace: crate::host::TurnTrace) -> AgentChatResponse {
137 match pending_card(&trace.node_outputs) {
138 Some(card) => AgentChatResponse {
139 replies: side_turn_reply(&trace.node_outputs)
140 .map(|text| vec![ReplyView { text }])
141 .unwrap_or_default(),
142 pending_card: Some(card),
143 },
144 None => replies_to_response(trace.replies),
145 }
146}
147
148use axum::http::StatusCode;
149use axum::response::IntoResponse;
150use axum::{Json, extract::State};
151
152use crate::host::RunnerHost;
153use crate::http::auth::AdminGuard;
154use crate::runner::ServerState;
155
156const DEFAULT_CONVERSATION: &str = "test-chat";
159const DEFAULT_USER: &str = "test-chat-user";
160
161async fn execute_chat(
164 host: &RunnerHost,
165 default_tenant: &str,
166 req: AgentChatRequest,
167) -> Result<AgentChatResponse, (StatusCode, serde_json::Value)> {
168 let tenant = req
169 .tenant
170 .as_deref()
171 .map(str::to_string)
172 .unwrap_or_else(|| default_tenant.to_string());
173
174 let mut activity = Activity::text("")
175 .with_payload(turn_payload(req.text, req.resume_payload))
176 .in_conversation(
177 req.conversation_id
178 .unwrap_or_else(|| DEFAULT_CONVERSATION.to_string()),
179 )
180 .from_user(req.user_id.unwrap_or_else(|| DEFAULT_USER.to_string()));
181 if let Some(flow) = req.flow_id {
182 activity = activity.with_flow(flow);
183 }
184
185 if host.active_packs().load_pack(&tenant).is_none() {
187 return Err(ChatError::TenantNotLoaded.into_response_parts());
188 }
189
190 match host.handle_activity_traced(&tenant, activity).await {
191 Ok(trace) => Ok(trace_to_response(trace)),
192 Err(e) => {
193 tracing::error!(tenant = %tenant, error = %format!("{e:#}"), "agent chat turn failed");
195 Err(ChatError::Internal.into_response_parts())
196 }
197 }
198}
199
200pub(crate) async fn run_detached<T, F>(fut: F) -> Result<T, tokio::task::JoinError>
205where
206 F: std::future::Future<Output = T> + Send + 'static,
207 T: Send + 'static,
208{
209 tokio::spawn(fut).await
210}
211
212#[derive(Debug, Clone, Copy, PartialEq, Eq)]
214enum ChatError {
215 TenantNotLoaded,
216 Internal,
217}
218
219impl ChatError {
220 fn into_response_parts(self) -> (StatusCode, serde_json::Value) {
221 match self {
222 Self::TenantNotLoaded => (
223 StatusCode::NOT_FOUND,
224 serde_json::json!({ "error": "tenant_not_loaded", "message": "tenant not loaded" }),
225 ),
226 Self::Internal => (
227 StatusCode::INTERNAL_SERVER_ERROR,
228 serde_json::json!({ "error": "agent_chat_failed", "message": "agent chat failed" }),
229 ),
230 }
231 }
232}
233
234pub async fn agent_chat(
237 _guard: AdminGuard,
238 State(state): State<ServerState>,
239 Json(req): Json<AgentChatRequest>,
240) -> impl IntoResponse {
241 let host = state.host.clone();
242 let default_tenant = state.routing.default_tenant().to_string();
243 let outcome = run_detached(async move { execute_chat(&host, &default_tenant, req).await })
244 .await
245 .unwrap_or_else(|e| {
246 tracing::error!(error = %e, "agent chat turn task panicked or was cancelled");
247 Err(ChatError::Internal.into_response_parts())
248 });
249 match outcome {
250 Ok(response) => (StatusCode::OK, Json(response)).into_response(),
251 Err((code, body)) => (code, Json(body)).into_response(),
252 }
253}
254
255#[cfg(feature = "agentic-worker")]
256use axum::response::sse::{Event, KeepAlive, Sse};
257#[cfg(feature = "agentic-worker")]
258use futures::{Stream, StreamExt};
259#[cfg(feature = "agentic-worker")]
260use std::convert::Infallible;
261#[cfg(feature = "agentic-worker")]
262use std::sync::Arc;
263
264#[cfg(feature = "agentic-worker")]
265use crate::http::agent_stream::{SseForwardObserver, StreamFrame, StreamObserverRegistry};
266
267#[cfg(feature = "agentic-worker")]
271fn first_nonempty_reply(activities: &[Activity]) -> Option<String> {
272 activities
273 .iter()
274 .map(reply_text)
275 .find(|t| !t.trim().is_empty())
276}
277
278#[cfg(feature = "agentic-worker")]
285struct Cleanup {
286 registry: StreamObserverRegistry,
287 conversation_id: String,
288 observer: Arc<dyn greentic_aw_runtime::StepObserver>,
289}
290
291#[cfg(feature = "agentic-worker")]
292impl Cleanup {
293 fn remove_stale(
296 registry: &StreamObserverRegistry,
297 conversation_id: &str,
298 observer: &Arc<dyn greentic_aw_runtime::StepObserver>,
299 ) {
300 registry.remove_if(conversation_id, |_k, stored| Arc::ptr_eq(stored, observer));
301 }
302}
303
304#[cfg(feature = "agentic-worker")]
305impl Drop for Cleanup {
306 fn drop(&mut self) {
307 Self::remove_stale(&self.registry, &self.conversation_id, &self.observer);
308 }
309}
310
311#[cfg(feature = "agentic-worker")]
322fn completed_turn_frames(trace: crate::host::TurnTrace, streamed: bool) -> Vec<StreamFrame> {
323 let mut frames = Vec::new();
324 match pending_card(&trace.node_outputs) {
325 Some(card) => {
326 if !streamed && let Some(text) = side_turn_reply(&trace.node_outputs) {
329 frames.push(StreamFrame::TextChunk { text });
330 }
331 frames.push(StreamFrame::PendingCard { card });
332 }
333 None => {
334 if !streamed && let Some(reply) = first_nonempty_reply(&trace.replies) {
335 frames.push(StreamFrame::TextChunk { text: reply });
336 }
337 }
338 }
339 frames.push(StreamFrame::Done);
340 frames
341}
342
343#[cfg(feature = "agentic-worker")]
357fn build_stream_turn_activity(
358 payload: serde_json::Value,
359 conversation_id: String,
360 user_id: Option<String>,
361 flow_id: Option<String>,
362) -> Activity {
363 let mut activity = Activity::text("")
364 .with_payload(payload)
365 .with_session(conversation_id.clone())
366 .in_conversation(conversation_id)
367 .from_user(user_id.unwrap_or_else(|| DEFAULT_USER.to_string()));
368 if let Some(flow) = flow_id {
369 activity = activity.with_flow(flow);
370 }
371 activity
372}
373
374#[cfg(feature = "agentic-worker")]
384pub fn agent_chat_stream_core(
385 state: &ServerState,
386 req: AgentChatRequest,
387) -> impl Stream<Item = StreamFrame> + use<> {
388 let (frame_tx, frame_rx) = tokio::sync::mpsc::unbounded_channel::<StreamFrame>();
389 let conversation_id = req
390 .conversation_id
391 .clone()
392 .unwrap_or_else(|| DEFAULT_CONVERSATION.to_string());
393
394 let observer = Arc::new(SseForwardObserver::new(frame_tx.clone()));
395 let observer_dyn: Arc<dyn greentic_aw_runtime::StepObserver> = observer.clone();
396 state
397 .stream_observers
398 .insert(conversation_id.clone(), observer_dyn.clone());
399
400 let host = state.host.clone();
401 let default_tenant = state.routing.default_tenant().to_string();
402 let registry: StreamObserverRegistry = state.stream_observers.clone();
403
404 let panic_tx = frame_tx.clone();
405 let turn = tokio::spawn(async move {
406 let _cleanup = Cleanup {
408 registry,
409 conversation_id: conversation_id.clone(),
410 observer: observer_dyn,
411 };
412
413 let tenant = req.tenant.unwrap_or(default_tenant);
414 let activity = build_stream_turn_activity(
415 turn_payload(req.text, req.resume_payload),
416 conversation_id,
417 req.user_id,
418 req.flow_id,
419 );
420
421 match host.handle_activity_traced(&tenant, activity).await {
422 Ok(trace) => {
423 for frame in completed_turn_frames(trace, observer.streamed()) {
424 let _ = frame_tx.send(frame);
425 }
426 }
427 Err(e) => {
428 tracing::error!(error = %format!("{e:#}"), "agent chat stream turn failed");
429 let _ = frame_tx.send(StreamFrame::Error {
430 message: "agent chat failed".to_string(),
431 });
432 }
433 }
434 });
435 tokio::spawn(async move {
438 if let Err(e) = turn.await {
439 tracing::error!(error = %e, "agent chat stream turn task panicked");
440 let _ = panic_tx.send(StreamFrame::Error {
441 message: "agent chat failed".to_string(),
442 });
443 }
444 });
445
446 futures::stream::unfold(frame_rx, |mut rx| async move {
447 rx.recv().await.map(|frame| (frame, rx))
448 })
449}
450
451#[cfg(feature = "agentic-worker")]
457pub async fn agent_chat_stream(
458 _guard: AdminGuard,
459 State(state): State<ServerState>,
460 Json(req): Json<AgentChatRequest>,
461) -> impl IntoResponse {
462 let stream = agent_chat_stream_core(&state, req).map(|frame| {
463 let data = serde_json::to_string(&frame).unwrap_or_else(|_| "null".into());
464 Ok::<Event, Infallible>(Event::default().event("frame").data(data))
465 });
466 Sse::new(stream).keep_alive(
467 KeepAlive::new()
468 .interval(std::time::Duration::from_secs(15))
469 .text("keepalive"),
470 )
471}
472
473#[cfg(test)]
474mod tests {
475 use super::*;
476 use crate::activity::Activity;
477 use serde_json::json;
478
479 fn reply_with(payload: serde_json::Value) -> Activity {
480 Activity::from_output(payload, "demo")
484 }
485
486 #[test]
487 fn maps_text_payload_to_reply() {
488 let out = replies_to_response(vec![reply_with(json!({"text": "hello there"}))]);
489 assert_eq!(out.replies.len(), 1);
490 assert_eq!(out.replies[0].text, "hello there");
491 }
492
493 #[test]
494 fn maps_nested_messages_text() {
495 let out = replies_to_response(vec![reply_with(
496 json!({"messages": [{"text": "nested hi"}]}),
497 )]);
498 assert_eq!(out.replies[0].text, "nested hi");
499 }
500
501 #[test]
502 fn skips_empty_and_keeps_order() {
503 let out = replies_to_response(vec![
504 reply_with(json!({"text": ""})),
505 reply_with(json!({"text": "second"})),
506 ]);
507 assert_eq!(out.replies.len(), 1);
508 assert_eq!(out.replies[0].text, "second");
509 }
510
511 #[test]
512 fn request_deserializes_camel_case() {
513 let r: AgentChatRequest = serde_json::from_value(json!({
514 "text": "hi", "conversationId": "c1", "userId": "u1"
515 }))
516 .unwrap();
517 assert_eq!(r.text, "hi");
518 assert_eq!(r.conversation_id.as_deref(), Some("c1"));
519 assert_eq!(r.user_id.as_deref(), Some("u1"));
520 }
521
522 #[tokio::test]
527 async fn agent_chat_unknown_tenant_maps_to_not_found() {
528 let host = crate::host::RunnerHost::for_test();
529 let req = AgentChatRequest {
530 text: "hello".into(),
531 tenant: Some("nope".into()),
532 conversation_id: None,
533 user_id: None,
534 flow_id: None,
535 resume_payload: None,
536 };
537 let err = execute_chat(&host, "test", req)
538 .await
539 .expect_err("unknown tenant should fail");
540 assert_eq!(err.0, StatusCode::NOT_FOUND);
541 assert_eq!(err.1["error"], "tenant_not_loaded");
542 }
543
544 #[tokio::test]
545 async fn run_detached_survives_dropped_caller() {
546 let (done_tx, done_rx) = tokio::sync::oneshot::channel::<()>();
547 let (go_tx, go_rx) = tokio::sync::oneshot::channel::<()>();
548 let caller = run_detached(async move {
549 let _ = go_rx.await;
550 let _ = done_tx.send(());
551 });
552 let _ = tokio::time::timeout(std::time::Duration::from_millis(20), caller).await;
554 let _ = go_tx.send(());
555 let finished = tokio::time::timeout(std::time::Duration::from_secs(2), done_rx).await;
556 assert!(matches!(finished, Ok(Ok(()))), "task must outlive caller");
557 }
558
559 #[tokio::test]
560 async fn run_detached_reports_panics_as_join_error() {
561 let res = run_detached(async { panic!("boom") }).await;
562 assert!(res.is_err_and(|e| e.is_panic()));
563 }
564
565 #[test]
566 fn internal_chat_error_is_generic() {
567 let (code, body) = ChatError::Internal.into_response_parts();
568 assert_eq!(code, StatusCode::INTERNAL_SERVER_ERROR);
569 assert_eq!(body["message"], "agent chat failed");
570 }
571
572 #[cfg(feature = "agentic-worker")]
576 #[tokio::test]
577 async fn agent_chat_stream_unknown_tenant_emits_error_frame_not_500() {
578 let state = crate::runner::ServerState::for_test();
579 let req = AgentChatRequest {
580 text: "hi".into(),
581 tenant: Some("nope".into()),
582 conversation_id: Some("c1".into()),
583 user_id: None,
584 flow_id: None,
585 resume_payload: None,
586 };
587 let frames = drive_stream_to_vec(agent_chat_stream_core(&state, req)).await;
588 assert!(
589 matches!(frames.last(), Some(StreamFrame::Error { .. })),
590 "got {frames:?}"
591 );
592 assert!(state.stream_observers.get("c1").is_none());
594 }
595
596 #[cfg(feature = "agentic-worker")]
607 #[test]
608 fn stream_turn_activity_stamps_session_with_conversation_id() {
609 let activity = build_stream_turn_activity(
610 turn_payload("hi".into(), None),
611 "conv-uuid-1".into(),
612 None,
613 None,
614 );
615 assert_eq!(
616 activity.session_id(),
617 Some("conv-uuid-1"),
618 "stream turn must stamp session = conversationId so the canonical \
619 hint matches the observer registry key"
620 );
621 assert_eq!(activity.conversation(), Some("conv-uuid-1"));
622 }
623
624 #[cfg(feature = "agentic-worker")]
625 async fn drive_stream_to_vec(
626 stream: impl futures::Stream<Item = StreamFrame>,
627 ) -> Vec<StreamFrame> {
628 use futures::StreamExt;
629 stream.collect().await
630 }
631
632 #[cfg(feature = "agentic-worker")]
637 #[test]
638 fn cleanup_remove_stale_does_not_evict_a_replaced_observer() {
639 let registry: StreamObserverRegistry = Arc::new(dashmap::DashMap::new());
640 let (tx_a, _rx_a) = tokio::sync::mpsc::unbounded_channel();
641 let (tx_b, _rx_b) = tokio::sync::mpsc::unbounded_channel();
642 let observer_a: Arc<dyn greentic_aw_runtime::StepObserver> =
643 Arc::new(SseForwardObserver::new(tx_a));
644 let observer_b: Arc<dyn greentic_aw_runtime::StepObserver> =
645 Arc::new(SseForwardObserver::new(tx_b));
646
647 registry.insert("c1".to_string(), observer_a.clone());
648 registry.insert("c1".to_string(), observer_b.clone());
650
651 Cleanup::remove_stale(®istry, "c1", &observer_a);
653 assert!(
654 registry
655 .get("c1")
656 .is_some_and(|e| Arc::ptr_eq(e.value(), &observer_b)),
657 "stale cleanup for A must not evict B's observer"
658 );
659
660 Cleanup::remove_stale(®istry, "c1", &observer_b);
662 assert!(registry.get("c1").is_none());
663 }
664
665 #[test]
666 fn request_carries_an_optional_resume_payload() {
667 let r: AgentChatRequest = serde_json::from_value(json!({
668 "text": "", "resume_payload": { "room": "101", "metadata": { "action": "submit" } }
669 }))
670 .unwrap();
671 let submit = r.resume_payload.expect("resume_payload parsed");
672 assert_eq!(submit["room"], "101");
673
674 let absent: AgentChatRequest = serde_json::from_value(json!({ "text": "hi" })).unwrap();
675 assert!(absent.resume_payload.is_none());
676 }
677
678 #[test]
679 fn turn_payload_is_the_text_or_the_submit() {
680 assert_eq!(turn_payload("hi".into(), None), json!({ "text": "hi" }));
681
682 let submit = json!({ "room": "101", "metadata": { "action": "submit" } });
683 let map = submit.as_object().cloned();
684 assert_eq!(
685 turn_payload(String::new(), map.clone()),
686 submit,
687 "an empty text adds nothing to the submit"
688 );
689 let with_text = turn_payload("done".into(), map);
690 assert_eq!(with_text["text"], "done");
691 assert_eq!(with_text["room"], "101");
692 }
693
694 fn parked_trace() -> crate::host::TurnTrace {
695 let mut node_outputs = std::collections::HashMap::new();
696 node_outputs.insert(
697 "agent".to_string(),
698 json!({
699 "reply": "",
700 "terminated_by": "awaiting_tool_input",
701 "pending_presentation": { "type": "AdaptiveCard", "body": [] }
702 }),
703 );
704 crate::host::TurnTrace {
705 replies: vec![reply_with(json!({ "status": "pending", "response": {} }))],
706 node_outputs,
707 }
708 }
709
710 #[test]
711 fn a_parked_flow_tool_surfaces_as_pending_card_and_no_replies() {
712 let response = trace_to_response(parked_trace());
713 assert!(
714 response.replies.is_empty(),
715 "the pending envelope is not a reply"
716 );
717 let body = serde_json::to_value(&response).unwrap();
718 assert_eq!(body["pending_card"]["type"], "AdaptiveCard");
719
720 let mut done = std::collections::HashMap::new();
721 done.insert(
722 "agent".to_string(),
723 json!({ "reply": "booked", "terminated_by": "final_reply" }),
724 );
725 let plain = trace_to_response(crate::host::TurnTrace {
726 replies: vec![reply_with(json!({ "text": "booked" }))],
727 node_outputs: done,
728 });
729 let body = serde_json::to_value(&plain).unwrap();
730 assert!(
731 body.get("pending_card").is_none(),
732 "omitted when None: {body}"
733 );
734 assert_eq!(body["replies"][0]["text"], "booked");
735 }
736
737 #[test]
738 fn a_side_turn_carries_its_reply_and_the_card() {
739 let mut outputs = std::collections::HashMap::new();
740 outputs.insert(
741 "agent".to_string(),
742 json!({
743 "reply": "the signature is in Settings",
744 "terminated_by": "awaiting_tool_input",
745 "side_turn": true,
746 "pending_presentation": { "type": "AdaptiveCard", "body": [] }
747 }),
748 );
749 let response = trace_to_response(crate::host::TurnTrace {
750 replies: vec![],
751 node_outputs: outputs,
752 });
753 let body = serde_json::to_value(&response).unwrap();
754 assert_eq!(body["replies"][0]["text"], "the signature is in Settings");
755 assert_eq!(body["pending_card"]["type"], "AdaptiveCard");
756 }
757
758 #[cfg(feature = "agentic-worker")]
759 #[test]
760 fn a_side_turn_that_was_not_streamed_sends_its_reply_before_the_card() {
761 let mut outputs = std::collections::HashMap::new();
762 outputs.insert(
763 "agent".to_string(),
764 json!({
765 "reply": "the signature is in Settings",
766 "terminated_by": "awaiting_tool_input",
767 "side_turn": true,
768 "pending_presentation": { "type": "AdaptiveCard", "body": [] }
769 }),
770 );
771 let trace = || crate::host::TurnTrace {
772 replies: vec![],
773 node_outputs: outputs.clone(),
774 };
775 let frames = completed_turn_frames(trace(), false);
776 assert!(
777 matches!(frames.as_slice(),
778 [StreamFrame::TextChunk { text }, StreamFrame::PendingCard { .. }, StreamFrame::Done]
779 if text == "the signature is in Settings"),
780 "{frames:?}"
781 );
782 let frames = completed_turn_frames(trace(), true);
784 assert!(
785 matches!(
786 frames.as_slice(),
787 [StreamFrame::PendingCard { .. }, StreamFrame::Done]
788 ),
789 "{frames:?}"
790 );
791 }
792
793 #[cfg(feature = "agentic-worker")]
794 #[test]
795 fn a_parked_flow_tool_streams_pending_card_then_done() {
796 let frames = completed_turn_frames(parked_trace(), false);
797 assert!(
798 matches!(
799 frames.as_slice(),
800 [StreamFrame::PendingCard { card }, StreamFrame::Done]
801 if card["type"] == "AdaptiveCard"
802 ),
803 "got {frames:?}"
804 );
805
806 let plain = completed_turn_frames(
807 crate::host::TurnTrace {
808 replies: vec![reply_with(json!({ "text": "booked" }))],
809 node_outputs: std::collections::HashMap::new(),
810 },
811 false,
812 );
813 assert!(
814 matches!(
815 plain.as_slice(),
816 [StreamFrame::TextChunk { text }, StreamFrame::Done] if text == "booked"
817 ),
818 "got {plain:?}"
819 );
820 }
821}