1use anyhow::Result;
2use serde_json::Value;
3
4#[async_trait::async_trait]
11pub trait GraphNodeHandler: Send + Sync {
12 async fn execute(
16 &self,
17 tenant_id: &str,
18 env_id: &str,
19 graph_id: &str,
20 session_id: &str,
21 flow_input: &Value,
22 ) -> Result<Value>;
23}
24
25#[cfg(feature = "agentic-worker")]
30mod aw {
31 use std::collections::HashMap;
32 use std::sync::Arc;
33 use std::time::Duration;
34
35 use anyhow::Result;
36 use greentic_aw_runtime::CachingGraphProvider;
37 use greentic_aw_runtime::HttpGraphProvider;
38 use greentic_aw_runtime::ToolLedger;
39 use greentic_aw_runtime::config_provider::InMemoryConfigProvider;
40 use greentic_aw_runtime::error::{AgentError, ConfigError};
41 use greentic_aw_runtime::graph::{
42 AgentTurnFn, AgentTurnRequest, AgentTurnResult, ApprovalFn, ApprovalOutcome,
43 ApprovalRequest, BoxFut, CheckpointError, CheckpointStore, GraphConfig, GraphExecError,
44 GraphExecutor, GraphRole, GraphRunState, RunStatus, SupervisorFn, SupervisorRequest,
45 SupervisorResult, ToolCallRequest, ToolFn,
46 };
47 use greentic_aw_runtime::state::{AgentStateStore, ChatMessage, ConversationState};
48 use greentic_aw_runtime::tools::dispatch_tool_call;
49 use greentic_aw_runtime::{
50 AgentConfig, AgentInput, AgentLimits, AgentOutput, AgentRuntime, LlmBackend,
51 LlmProviderRef, StepObserver, Telemetry, TenantContext, TokenMeter, ToolRef,
52 };
53 use greentic_ext_runtime::ExtensionRuntime;
54 use serde_json::{Value, json};
55
56 use crate::runner::knowledge_index::IndexMount;
57 use crate::trace::agent_audit::AgentAuditObserver;
58 use crate::trace::audit_sink::AuditSink;
59
60 use super::GraphNodeHandler;
61
62 use super::super::agent_node::tenant_ctx_for_audit;
63
64 const SANITISED_ERROR_REPLY: &str = "Something went wrong. Please try again.";
69
70 const GRAPH_UNAVAILABLE_REPLY: &str =
73 "This worker isn't available right now. Please try again later.";
74
75 const RESOLVED_SENTINEL: &str = "[[RESOLVED]]";
80
81 const MAX_RUN_ID_SUFFIX: u32 = 100;
84
85 #[derive(Debug, thiserror::Error)]
91 enum RunIdError {
92 #[error(transparent)]
99 Checkpoint(#[from] CheckpointError),
100 #[error("all run-id slots exhausted for base run `{base_run_id}`")]
104 SuffixExhausted { base_run_id: String },
105 }
106
107 fn detect_resolved(reply: &str) -> bool {
109 reply
110 .to_ascii_lowercase()
111 .contains(&RESOLVED_SENTINEL.to_ascii_lowercase())
112 }
113
114 fn strip_sentinel(reply: &str) -> String {
117 let lower = reply.to_ascii_lowercase();
118 if let Some(idx) = lower.find(&RESOLVED_SENTINEL.to_ascii_lowercase()) {
119 let mut out = reply.to_string();
120 out.replace_range(idx..idx + RESOLVED_SENTINEL.len(), "");
121 return out.trim().to_string();
122 }
123 reply.trim().to_string()
124 }
125
126 pub trait GraphConfigSource: Send + Sync {
136 fn graph_config<'a>(
137 &'a self,
138 tenant: &'a TenantContext,
139 graph_id: &'a str,
140 ) -> BoxFut<'a, Result<GraphConfig, ConfigError>>;
141 }
142
143 pub struct InMemoryGraphProvider {
149 graphs: HashMap<String, GraphConfig>,
150 }
151
152 impl InMemoryGraphProvider {
153 pub fn new(graphs: HashMap<String, GraphConfig>) -> Self {
155 Self { graphs }
156 }
157 }
158
159 impl GraphConfigSource for InMemoryGraphProvider {
160 fn graph_config<'a>(
161 &'a self,
162 _tenant: &'a TenantContext,
163 graph_id: &'a str,
164 ) -> BoxFut<'a, Result<GraphConfig, ConfigError>> {
165 let found = self.graphs.get(graph_id).cloned();
166 let graph_id_owned = graph_id.to_string();
167 Box::pin(async move { found.ok_or(ConfigError::AgentNotFound(graph_id_owned)) })
168 }
169 }
170
171 impl GraphConfigSource for CachingGraphProvider<HttpGraphProvider> {
183 fn graph_config<'a>(
184 &'a self,
185 tenant: &'a TenantContext,
186 graph_id: &'a str,
187 ) -> BoxFut<'a, Result<GraphConfig, ConfigError>> {
188 Box::pin(async move { self.graph_config(tenant, graph_id).await })
189 }
190 }
191
192 pub struct LayeredGraphProvider<P: GraphConfigSource, F: GraphConfigSource> {
213 primary: P,
214 fallback: F,
215 }
216
217 impl<P: GraphConfigSource, F: GraphConfigSource> LayeredGraphProvider<P, F> {
218 pub fn new(primary: P, fallback: F) -> Self {
219 Self { primary, fallback }
220 }
221 }
222
223 impl<P: GraphConfigSource, F: GraphConfigSource> GraphConfigSource for LayeredGraphProvider<P, F> {
224 fn graph_config<'a>(
225 &'a self,
226 tenant: &'a TenantContext,
227 graph_id: &'a str,
228 ) -> BoxFut<'a, Result<GraphConfig, ConfigError>> {
229 Box::pin(async move {
230 match self.primary.graph_config(tenant, graph_id).await {
231 Ok(cfg) => Ok(cfg),
232 Err(ConfigError::AgentNotFound(_)) | Err(ConfigError::Internal(_)) => {
233 self.fallback.graph_config(tenant, graph_id).await
234 }
235 Err(other) => Err(other),
239 }
240 })
241 }
242 }
243
244 fn graph_registry_from_env() -> Option<CachingGraphProvider<HttpGraphProvider>> {
255 let endpoint = std::env::var("GREENTIC_AW_ADMIN_ENDPOINT")
256 .ok()
257 .filter(|s| !s.is_empty())?;
258 let token = std::env::var("GREENTIC_AW_ADMIN_TOKEN")
259 .ok()
260 .filter(|s| !s.is_empty())?;
261 Some(CachingGraphProvider::new(HttpGraphProvider::new(
262 endpoint, token,
263 )))
264 }
265
266 pub fn graph_config_from_sidecar(pack_id: &str, bytes: &[u8]) -> Option<GraphConfig> {
280 let raw = match std::str::from_utf8(bytes) {
281 Ok(raw) => raw,
282 Err(error) => {
283 tracing::warn!(
284 pack_id,
285 error = %error,
286 "skipping agent-graph sidecar: not valid UTF-8"
287 );
288 return None;
289 }
290 };
291 match GraphConfig::from_json(raw) {
292 Ok(config) => Some(config),
293 Err(error) => {
294 tracing::warn!(
295 pack_id,
296 error = %error,
297 "skipping malformed agent-graph sidecar in pack"
298 );
299 None
300 }
301 }
302 }
303
304 #[allow(clippy::too_many_arguments)]
333 pub async fn build_graph_node_handler(
334 graphs: HashMap<String, GraphConfig>,
335 audit_sink: Option<AuditSink>,
336 packs: Arc<Vec<Arc<crate::pack::PackRuntime>>>,
337 merged_agents: HashMap<String, AgentConfig>,
338 tenant: String,
339 secrets: crate::secrets::DynSecretsManager,
340 unit: Option<String>,
341 ) -> Option<Arc<dyn GraphNodeHandler>> {
342 build_graph_node_handler_metered(
343 graphs,
344 audit_sink,
345 packs,
346 merged_agents,
347 tenant,
348 secrets,
349 unit,
350 super::super::agent_node::resolve_billing_meter(None),
351 )
352 .await
353 }
354
355 #[allow(clippy::too_many_arguments)]
359 pub(crate) async fn build_graph_node_handler_metered(
360 graphs: HashMap<String, GraphConfig>,
361 audit_sink: Option<AuditSink>,
362 packs: Arc<Vec<Arc<crate::pack::PackRuntime>>>,
363 merged_agents: HashMap<String, AgentConfig>,
364 tenant: String,
365 secrets: crate::secrets::DynSecretsManager,
366 unit: Option<String>,
367 billing_meter: Option<Arc<dyn greentic_aw_runtime::billing::BillingMeter>>,
368 ) -> Option<Arc<dyn GraphNodeHandler>> {
369 use crate::runner::aw_backends::{AwBackends, build_aw_backends};
370 use greentic_aw_runtime::OtelTelemetry;
371
372 if graphs.is_empty() {
373 return None; }
375
376 let AwBackends {
377 state_store,
378 token_meter,
379 tool_ledger: ledger,
380 checkpoint_store: checkpoint,
381 } = build_aw_backends().await?;
382
383 let ext_runtime = super::super::agent_node::build_ext_runtime(
387 std::sync::Arc::new(super::super::agent_node::EnvSecretsBackend),
388 None,
389 None,
390 None,
392 &packs,
393 )?;
394 let llm = super::super::agent_node::build_llm_backend(&ext_runtime);
395 let telemetry = Arc::new(OtelTelemetry);
396
397 let graph_count = graphs.len();
398 let local = InMemoryGraphProvider::new(graphs);
413 let provider: Arc<dyn GraphConfigSource> = match graph_registry_from_env() {
414 Some(http) => Arc::new(LayeredGraphProvider::new(http, local)),
415 None => Arc::new(local),
416 };
417
418 let a2a_source = graph_a2a_source(&packs, &tenant, &secrets, unit.as_deref());
419 let index_mount = IndexMount {
423 secrets: Some(super::super::agent_node::mcp_secrets_manager(&secrets)),
424 secret_tenant: Some(tenant.clone()),
425 };
426 let handler = RuntimeGraphNodeHandler::from_parts(
427 provider,
428 checkpoint,
429 state_store,
430 ext_runtime,
431 llm,
432 telemetry,
433 token_meter,
434 ledger,
435 audit_sink,
436 packs,
437 Arc::new(merged_agents),
438 a2a_source,
439 index_mount,
440 )
441 .with_billing(billing_meter, unit);
442
443 tracing::info!(graph_count, "AW graph runtime constructed");
444 Some(Arc::new(handler))
445 }
446
447 pub(crate) fn graph_a2a_source(
462 packs: &[Arc<crate::pack::PackRuntime>],
463 tenant: &str,
464 secrets: &crate::secrets::DynSecretsManager,
465 unit: Option<&str>,
466 ) -> Option<Arc<greentic_aw_runtime::A2aToolSource>> {
467 crate::runner::a2a_pack_source::a2a_source_from_packs(
468 packs,
469 tenant,
470 Some(super::super::agent_node::mcp_secrets_manager(secrets)),
471 unit,
472 )
473 }
474
475 trait TurnEffectSource: Send + Sync {
501 fn agent_turn(
502 &self,
503 audit_sink: Option<AuditSink>,
504 real_tenant: greentic_types::TenantCtx,
505 billing: TurnBilling,
506 ) -> AgentTurnFn;
507 fn supervisor(
508 &self,
509 audit_sink: Option<AuditSink>,
510 real_tenant: greentic_types::TenantCtx,
511 billing: TurnBilling,
512 ) -> SupervisorFn;
513 }
514
515 #[derive(Clone, Default)]
524 pub(crate) struct TurnBilling {
525 pub(crate) meter: Option<Arc<dyn greentic_aw_runtime::billing::BillingMeter>>,
526 pub(crate) project_id: Option<String>,
527 pub(crate) state_scope: Option<String>,
530 }
531
532 impl TurnBilling {
533 fn scoped_session(&self, base: &str) -> String {
535 match &self.state_scope {
536 Some(scope) => format!("{scope}__{base}"),
537 None => base.to_string(),
538 }
539 }
540
541 fn turn_tenant(&self, real_tenant: &greentic_types::TenantCtx) -> TenantContext {
544 TenantContext::new(real_tenant.tenant_id.as_str(), real_tenant.env.as_str())
545 .with_project_id(self.project_id.clone())
546 }
547
548 fn install(&self, runtime: AgentRuntime) -> AgentRuntime {
551 match &self.meter {
552 Some(meter) => runtime.with_billing_meter(Arc::clone(meter)),
553 None => runtime,
554 }
555 }
556 }
557
558 struct RuntimeTurnSource {
565 state_store: Arc<dyn AgentStateStore>,
566 ext_runtime: Arc<ExtensionRuntime>,
567 llm: Arc<dyn LlmBackend>,
568 telemetry: Arc<dyn Telemetry>,
569 token_meter: Arc<dyn TokenMeter>,
570 ledger: Arc<dyn ToolLedger>,
571 mcp_source: Option<Arc<greentic_aw_runtime::McpToolSource>>,
575 a2a_source: Option<Arc<greentic_aw_runtime::A2aToolSource>>,
579 packs: Arc<Vec<Arc<crate::pack::PackRuntime>>>,
585 merged_agents: Arc<HashMap<String, AgentConfig>>,
589 index_mount: IndexMount,
592 }
593
594 impl TurnEffectSource for RuntimeTurnSource {
595 fn agent_turn(
596 &self,
597 audit_sink: Option<AuditSink>,
598 real_tenant: greentic_types::TenantCtx,
599 billing: TurnBilling,
600 ) -> AgentTurnFn {
601 build_agent_turn(
602 self.state_store.clone(),
603 self.ext_runtime.clone(),
604 self.llm.clone(),
605 self.telemetry.clone(),
606 self.token_meter.clone(),
607 self.ledger.clone(),
608 self.mcp_source.clone(),
609 self.a2a_source.clone(),
610 self.packs.clone(),
611 self.merged_agents.clone(),
612 self.index_mount.clone(),
613 audit_sink,
614 real_tenant,
615 billing,
616 )
617 }
618
619 fn supervisor(
620 &self,
621 audit_sink: Option<AuditSink>,
622 real_tenant: greentic_types::TenantCtx,
623 billing: TurnBilling,
624 ) -> SupervisorFn {
625 build_supervisor(
626 self.state_store.clone(),
627 self.ext_runtime.clone(),
628 self.llm.clone(),
629 self.telemetry.clone(),
630 self.token_meter.clone(),
631 self.ledger.clone(),
632 self.merged_agents.clone(),
633 audit_sink,
634 real_tenant,
635 billing,
636 )
637 }
638 }
639
640 #[cfg(test)]
645 struct FixedTurnSource {
646 agent_turn: AgentTurnFn,
647 supervisor: SupervisorFn,
648 }
649
650 #[cfg(test)]
651 impl TurnEffectSource for FixedTurnSource {
652 fn agent_turn(
653 &self,
654 _audit_sink: Option<AuditSink>,
655 _real_tenant: greentic_types::TenantCtx,
656 _billing: TurnBilling,
657 ) -> AgentTurnFn {
658 self.agent_turn.clone()
659 }
660
661 fn supervisor(
662 &self,
663 _audit_sink: Option<AuditSink>,
664 _real_tenant: greentic_types::TenantCtx,
665 _billing: TurnBilling,
666 ) -> SupervisorFn {
667 self.supervisor.clone()
668 }
669 }
670
671 pub struct RuntimeGraphNodeHandler {
677 graphs: Arc<dyn GraphConfigSource>,
678 checkpoint: Arc<dyn CheckpointStore>,
679 state_store: Arc<dyn AgentStateStore>,
680 turn_source: Arc<dyn TurnEffectSource>,
681 tool: ToolFn,
682 approval: ApprovalFn,
683 audit_sink: Option<AuditSink>,
689 billing: TurnBilling,
693 }
694
695 impl RuntimeGraphNodeHandler {
696 #[must_use]
700 pub fn with_billing(
701 mut self,
702 meter: Option<Arc<dyn greentic_aw_runtime::billing::BillingMeter>>,
703 project_id: Option<String>,
704 ) -> Self {
705 self.billing = TurnBilling {
706 meter,
707 project_id,
708 state_scope: None,
709 };
710 self
711 }
712
713 #[allow(clippy::too_many_arguments)]
725 pub fn from_parts(
726 graphs: Arc<dyn GraphConfigSource>,
727 checkpoint: Arc<dyn CheckpointStore>,
728 state_store: Arc<dyn AgentStateStore>,
729 ext_runtime: Arc<ExtensionRuntime>,
730 llm: Arc<dyn LlmBackend>,
731 telemetry: Arc<dyn Telemetry>,
732 token_meter: Arc<dyn TokenMeter>,
733 ledger: Arc<dyn ToolLedger>,
734 audit_sink: Option<AuditSink>,
735 packs: Arc<Vec<Arc<crate::pack::PackRuntime>>>,
736 merged_agents: Arc<HashMap<String, AgentConfig>>,
737 a2a_source: Option<Arc<greentic_aw_runtime::A2aToolSource>>,
738 index_mount: IndexMount,
739 ) -> Self {
740 let tool = build_tool(ext_runtime.clone(), a2a_source.clone());
743 let mcp_source = super::super::agent_node::mcp_source_from_env(None);
749 let turn_source: Arc<dyn TurnEffectSource> = Arc::new(RuntimeTurnSource {
750 state_store: state_store.clone(),
751 ext_runtime,
752 llm,
753 telemetry,
754 token_meter,
755 ledger,
756 mcp_source,
757 a2a_source,
758 packs,
759 merged_agents,
760 index_mount,
761 });
762 let approval = default_approval_awaiting();
772 Self {
773 graphs,
774 checkpoint,
775 state_store,
776 turn_source,
777 tool,
778 approval,
779 audit_sink,
780 billing: TurnBilling::default(),
781 }
782 }
783
784 #[cfg(test)]
790 #[allow(clippy::too_many_arguments)]
791 pub(crate) fn with_effects(
792 graphs: Arc<dyn GraphConfigSource>,
793 checkpoint: Arc<dyn CheckpointStore>,
794 state_store: Arc<dyn AgentStateStore>,
795 agent_turn: AgentTurnFn,
796 tool: ToolFn,
797 supervisor: SupervisorFn,
798 approval: ApprovalFn,
799 ) -> Self {
800 Self {
801 graphs,
802 checkpoint,
803 state_store,
804 turn_source: Arc::new(FixedTurnSource {
805 agent_turn,
806 supervisor,
807 }),
808 tool,
809 approval,
810 audit_sink: None,
811 billing: TurnBilling::default(),
812 }
813 }
814
815 async fn derive_run_id(
838 &self,
839 tenant: &TenantContext,
840 graph_id: &str,
841 session_id: &str,
842 ) -> Result<RunSlot, RunIdError> {
843 let safe_session = session_id.replace(':', "_");
846 let base = format!("{safe_session}__{graph_id}");
847 match self.checkpoint.load(tenant, &base).await? {
848 None => return Ok(RunSlot::start(base)),
849 Some(rec)
857 if matches!(rec.status, RunStatus::Running | RunStatus::AwaitingInput) =>
858 {
859 return Ok(RunSlot::resume(base));
860 }
861 Some(_) => {}
862 }
863 for n in 2..=MAX_RUN_ID_SUFFIX {
864 let candidate = format!("{safe_session}__{graph_id}__{n}");
865 match self.checkpoint.load(tenant, &candidate).await? {
866 None => return Ok(RunSlot::start(candidate)),
867 Some(rec)
868 if matches!(rec.status, RunStatus::Running | RunStatus::AwaitingInput) =>
869 {
870 return Ok(RunSlot::resume(candidate));
871 }
872 Some(_) => continue,
873 }
874 }
875 Err(RunIdError::SuffixExhausted { base_run_id: base })
879 }
880 }
881
882 struct RunSlot {
885 run_id: String,
886 resume: bool,
887 }
888
889 impl RunSlot {
890 fn start(run_id: String) -> Self {
891 Self {
892 run_id,
893 resume: false,
894 }
895 }
896 fn resume(run_id: String) -> Self {
897 Self {
898 run_id,
899 resume: true,
900 }
901 }
902 }
903
904 #[async_trait::async_trait]
905 impl GraphNodeHandler for RuntimeGraphNodeHandler {
906 async fn execute(
907 &self,
908 tenant_id: &str,
909 env_id: &str,
910 graph_id: &str,
911 session_id: &str,
912 flow_input: &Value,
913 ) -> Result<Value> {
914 let user_text = flow_input
918 .get("user_text")
919 .and_then(Value::as_str)
920 .unwrap_or("")
921 .to_string();
922 let parsed = crate::runner::agent_node::attachments_from_flow_input(flow_input);
929 let mut user_text = crate::runner::agent_node::text_with_skipped_notices(
930 user_text,
931 &parsed.skipped_codes,
932 );
933 if !parsed.refs.is_empty() {
934 user_text.push_str(
935 &greentic_aw_runtime::attachments_materialize::unreadable_note(
936 parsed.refs.len(),
937 ),
938 );
939 }
940
941 let tenant = TenantContext::new(tenant_id, env_id);
942
943 let cfg = match self.graphs.graph_config(&tenant, graph_id).await {
946 Ok(cfg) => cfg,
947 Err(error) => {
948 tracing::warn!(error = %error, graph_id, "graph config not found");
949 return Ok(error_envelope(GRAPH_UNAVAILABLE_REPLY));
950 }
951 };
952
953 let _lock = match self
956 .state_store
957 .acquire_lock(&tenant, session_id, Duration::from_secs(5))
958 .await
959 {
960 Ok(guard) => guard,
961 Err(error) => {
962 tracing::warn!(error = %error, graph_id, session_id, "session lock failed");
963 return Ok(error_envelope(SANITISED_ERROR_REPLY));
964 }
965 };
966
967 let slot = match self.derive_run_id(&tenant, graph_id, session_id).await {
968 Ok(slot) => slot,
969 Err(RunIdError::SuffixExhausted { .. }) => {
970 tracing::warn!(
971 graph_id,
972 session_id,
973 "all run-id slots exhausted for session"
974 );
975 return Ok(error_envelope(
976 "Too many runs for this session. Please start a new conversation.",
977 ));
978 }
979 Err(RunIdError::Checkpoint(error)) => {
980 tracing::warn!(error = %error, graph_id, session_id, "run-id derivation failed");
981 return Ok(error_envelope(SANITISED_ERROR_REPLY));
982 }
983 };
984
985 let real_tenant = tenant_ctx_for_audit(tenant_id, env_id)
994 .map_err(crate::runner::engine::pre_effect)?;
995 let billing = TurnBilling {
999 state_scope: Some(format!("{session_id}__{graph_id}")),
1000 ..self.billing.clone()
1001 };
1002 let agent_turn = self.turn_source.agent_turn(
1003 self.audit_sink.clone(),
1004 real_tenant.clone(),
1005 billing.clone(),
1006 );
1007 let supervisor =
1008 self.turn_source
1009 .supervisor(self.audit_sink.clone(), real_tenant, billing);
1010
1011 let executor = GraphExecutor::new(
1012 self.checkpoint.clone(),
1013 agent_turn,
1014 self.tool.clone(),
1015 supervisor,
1016 self.approval.clone(),
1017 );
1018
1019 let result = if slot.resume {
1020 executor.resume(&tenant, &slot.run_id).await
1021 } else {
1022 executor
1023 .start(&tenant, &slot.run_id, &cfg, &user_text)
1024 .await
1025 };
1026
1027 match result {
1028 Ok(outcome) if outcome.status == RunStatus::AwaitingInput => {
1042 tracing::warn!(
1043 graph_id,
1044 session_id,
1045 run_id = %slot.run_id,
1046 "graph run parked awaiting human approval; no approval \
1047 transport is wired on this in-process runner-host path, \
1048 so the run stays AwaitingInput until an external decision \
1049 resolves it"
1050 );
1051 Ok(json!({
1052 "reply": outcome.reply,
1053 "trail": outcome.trail,
1054 "terminated_by": "awaiting_approval",
1055 }))
1056 }
1057 Ok(outcome) => Ok(json!({
1058 "reply": outcome.reply,
1059 "trail": outcome.trail,
1060 "terminated_by": "respond",
1061 })),
1062 Err(error) => {
1063 tracing::warn!(error = %error, graph_id, session_id, "graph run failed");
1064 let reply = match error {
1069 GraphExecError::IterationCap { .. } => {
1070 "This is taking longer than expected. Please try again."
1071 }
1072 _ => SANITISED_ERROR_REPLY,
1073 };
1074 Ok(error_envelope(reply))
1075 }
1076 }
1077 }
1078 }
1079
1080 fn error_envelope(reply: &str) -> Value {
1084 json!({
1085 "reply": reply,
1086 "trail": Vec::<Value>::new(),
1087 "terminated_by": "error",
1088 })
1089 }
1090
1091 fn seed_state_from_graph(
1099 tenant: &TenantContext,
1100 session_id: &str,
1101 state: &GraphRunState,
1102 ) -> ConversationState {
1103 let mut seeded = ConversationState::empty(tenant, session_id);
1104 for m in &state.messages {
1105 match m.role {
1106 GraphRole::User => seeded.messages.push(ChatMessage::User {
1107 content: m.content.clone(),
1108 attachments: Vec::new(),
1109 }),
1110 GraphRole::Assistant => seeded.messages.push(ChatMessage::Assistant {
1111 content: m.content.clone(),
1112 tool_calls: vec![],
1113 }),
1114 GraphRole::Tool => seeded.messages.push(ChatMessage::User {
1115 content: format!("Tool result: {}", m.content),
1116 attachments: Vec::new(),
1117 }),
1118 }
1119 }
1120 seeded
1121 }
1122
1123 #[allow(clippy::too_many_arguments)]
1132 fn build_agent_turn(
1133 state_store: Arc<dyn AgentStateStore>,
1134 ext_runtime: Arc<ExtensionRuntime>,
1135 llm: Arc<dyn LlmBackend>,
1136 telemetry: Arc<dyn Telemetry>,
1137 token_meter: Arc<dyn TokenMeter>,
1138 ledger: Arc<dyn ToolLedger>,
1139 mcp_source: Option<Arc<greentic_aw_runtime::McpToolSource>>,
1140 a2a_source: Option<Arc<greentic_aw_runtime::A2aToolSource>>,
1141 packs: Arc<Vec<Arc<crate::pack::PackRuntime>>>,
1142 merged_agents: Arc<HashMap<String, AgentConfig>>,
1143 index_mount: IndexMount,
1144 audit_sink: Option<AuditSink>,
1145 real_tenant: greentic_types::TenantCtx,
1146 billing: TurnBilling,
1147 ) -> AgentTurnFn {
1148 Arc::new(move |req: AgentTurnRequest| {
1149 let state_store = state_store.clone();
1150 let ext_runtime = ext_runtime.clone();
1151 let llm = llm.clone();
1152 let telemetry = telemetry.clone();
1153 let token_meter = token_meter.clone();
1154 let ledger = ledger.clone();
1155 let mcp_source = mcp_source.clone();
1156 let a2a_source = a2a_source.clone();
1157 let packs = packs.clone();
1158 let merged_agents = merged_agents.clone();
1159 let audit_sink = audit_sink.clone();
1160 let real_tenant = real_tenant.clone();
1161 let index_mount = index_mount.clone();
1162 let billing = billing.clone();
1163 Box::pin(async move {
1164 run_one_agent_turn(
1165 req,
1166 state_store,
1167 ext_runtime,
1168 llm,
1169 telemetry,
1170 token_meter,
1171 ledger,
1172 mcp_source,
1173 a2a_source,
1174 packs,
1175 merged_agents,
1176 audit_sink.as_ref(),
1177 &real_tenant,
1178 &index_mount,
1179 &billing,
1180 )
1181 .await
1182 }) as BoxFut<'static, Result<AgentTurnResult, GraphExecError>>
1183 })
1184 }
1185
1186 async fn run_agent_step(
1202 runtime: &AgentRuntime,
1203 tenant: TenantContext,
1204 session_id: &str,
1205 agent_id: &str,
1206 input: AgentInput,
1207 audit_sink: Option<&AuditSink>,
1208 real_tenant: &greentic_types::TenantCtx,
1209 ) -> std::result::Result<AgentOutput, AgentError> {
1210 match audit_sink {
1211 Some(sink) => {
1212 let observer: Arc<dyn StepObserver> = Arc::new(AgentAuditObserver::new(
1213 sink.clone(),
1214 real_tenant.clone(),
1215 agent_id.to_string(),
1216 session_id.to_string(),
1217 ));
1218 runtime
1219 .step_with_observer(tenant, session_id, agent_id, input, observer)
1220 .await
1221 }
1222 None => runtime.step(tenant, session_id, agent_id, input).await,
1223 }
1224 }
1225
1226 fn parse_tool_ref(s: &str) -> Option<ToolRef> {
1235 match s.rsplit_once('/') {
1236 Some((extension_id, tool_name))
1237 if !extension_id.is_empty() && !tool_name.is_empty() =>
1238 {
1239 Some(ToolRef {
1240 extension_id: extension_id.to_string(),
1241 tool_name: tool_name.to_string(),
1242 description: None,
1243 input_schema: None,
1244 usage_note: None,
1245 })
1246 }
1247 _ => {
1248 tracing::warn!(tool_ref = %s, "skipping malformed graph-node tool ref (expected \"<extension_id>/<tool_name>\")");
1249 None
1250 }
1251 }
1252 }
1253
1254 fn map_tool_refs(tools: &[String]) -> Vec<ToolRef> {
1259 tools.iter().filter_map(|t| parse_tool_ref(t)).collect()
1260 }
1261
1262 fn resolve_turn_config(
1271 req: &AgentTurnRequest,
1272 merged: &HashMap<String, AgentConfig>,
1273 agent_id: &str,
1274 ) -> Result<AgentConfig, GraphExecError> {
1275 if let Some(id) = req.agent_ref.as_deref() {
1276 return merged.get(id).cloned().ok_or_else(|| {
1277 GraphExecError::AgentTurn(format!("referenced agent '{id}' not found"))
1278 });
1279 }
1280 if let Some(id) = req.inherit_from.as_deref() {
1291 let parent = merged.get(id).ok_or_else(|| {
1292 GraphExecError::AgentTurn(format!(
1293 "node '{}': inherit_from '{}' not found in merged agents; \
1294 refusing to run without its tools and guardrails",
1295 req.node_id, id
1296 ))
1297 })?;
1298 return Ok(AgentConfig {
1299 agent_id: agent_id.to_string(),
1300 system_prompt: req.system_prompt.clone(),
1301 llm: LlmProviderRef {
1302 provider: req.provider.clone().unwrap_or_else(|| "openai".into()),
1303 model: req.model.clone(),
1304 credential_ref: None,
1305 },
1306 tools: parent.tools.clone(),
1308 guardrails: parent.guardrails.clone(),
1309 memory: parent.memory.clone(),
1310 knowledge: parent.knowledge.clone(),
1311 limits: parent.limits.clone(),
1312 conversational: false,
1313 opening_message: None,
1314 on_text_while_parked: Default::default(),
1315 });
1316 }
1317 Ok(AgentConfig {
1318 agent_id: agent_id.to_string(),
1319 system_prompt: req.system_prompt.clone(),
1320 tools: map_tool_refs(&req.tools),
1321 guardrails: vec![],
1322 llm: LlmProviderRef {
1323 provider: req.provider.clone().unwrap_or_else(|| "openai".into()),
1324 model: req.model.clone(),
1325 credential_ref: None,
1326 },
1327 limits: AgentLimits::default(),
1328 memory: None,
1329 knowledge: None,
1330 conversational: false,
1331 opening_message: None,
1332 on_text_while_parked: Default::default(),
1333 })
1334 }
1335
1336 #[allow(clippy::too_many_arguments)]
1351 async fn run_one_agent_turn(
1352 req: AgentTurnRequest,
1353 state_store: Arc<dyn AgentStateStore>,
1354 ext_runtime: Arc<ExtensionRuntime>,
1355 llm: Arc<dyn LlmBackend>,
1356 telemetry: Arc<dyn Telemetry>,
1357 token_meter: Arc<dyn TokenMeter>,
1358 ledger: Arc<dyn ToolLedger>,
1359 mcp_source: Option<Arc<greentic_aw_runtime::McpToolSource>>,
1360 a2a_source: Option<Arc<greentic_aw_runtime::A2aToolSource>>,
1361 packs: Arc<Vec<Arc<crate::pack::PackRuntime>>>,
1362 merged_agents: Arc<HashMap<String, AgentConfig>>,
1363 audit_sink: Option<&AuditSink>,
1364 real_tenant: &greentic_types::TenantCtx,
1365 index_mount: &IndexMount,
1366 billing: &TurnBilling,
1367 ) -> Result<AgentTurnResult, GraphExecError> {
1368 let tenant = billing.turn_tenant(real_tenant);
1378 let session_id = billing.scoped_session(&format!("graph__{}", req.node_id));
1379 let agent_id = format!("graph.{}", req.node_id);
1380
1381 let seeded = seed_state_from_graph(&tenant, &session_id, &req.state);
1382 if let Err(error) = state_store.save(&tenant, &session_id, &seeded).await {
1383 return Err(GraphExecError::AgentTurn(format!(
1384 "seeding conversation state: {error}"
1385 )));
1386 }
1387
1388 let cfg = resolve_turn_config(&req, &merged_agents, &agent_id)?;
1389 let step_agent_id = req.agent_ref.clone().unwrap_or_else(|| agent_id.clone());
1395 let mut provider = InMemoryConfigProvider::new();
1396 provider.insert(&tenant, &step_agent_id, cfg.clone());
1397
1398 let component_source = super::super::agent_node::component_source_from_packs(
1410 &packs,
1411 real_tenant.tenant_id.as_str(),
1412 );
1413 let mut runtime = AgentRuntime::new(
1414 Arc::new(provider),
1415 state_store,
1416 ext_runtime.clone(),
1417 llm,
1418 telemetry,
1419 token_meter,
1420 ledger,
1421 mcp_source,
1422 )
1423 .with_component_source(component_source)
1424 .with_a2a_source(a2a_source);
1428 runtime = billing.install(runtime);
1429 runtime =
1439 super::super::agent_node::attach_guardrails(runtime, ext_runtime.clone(), Vec::new());
1440
1441 if req.agent_ref.is_some() {
1447 runtime = runtime.with_short_term_memory(Arc::new(
1448 greentic_aw_runtime::memory::InMemoryMemoryProvider::new(),
1449 ));
1450 runtime = crate::runner::runtime_ext::attach_all(runtime).await;
1453 runtime = index_mount.attach(runtime);
1461 runtime = crate::runner::knowledge_ext::attach(runtime, ext_runtime.clone());
1462 }
1463
1464 let input = AgentInput {
1469 text: String::new(),
1470 ..Default::default()
1471 };
1472
1473 let out = run_agent_step(
1474 &runtime,
1475 tenant.clone(),
1476 &session_id,
1477 &step_agent_id,
1478 input,
1479 audit_sink,
1480 real_tenant,
1481 )
1482 .await
1483 .map_err(|e| GraphExecError::AgentTurn(format!("agent step failed: {e}")))?;
1484
1485 Ok(AgentTurnResult {
1486 resolved: detect_resolved(&out.reply),
1487 reply: strip_sentinel(&out.reply),
1488 })
1489 }
1490
1491 const ROUTE_SENTINEL_PREFIX: &str = "[[ROUTE:";
1494 const ROUTE_SENTINEL_SUFFIX: &str = "]]";
1495
1496 #[allow(clippy::too_many_arguments)]
1504 fn build_supervisor(
1505 state_store: Arc<dyn AgentStateStore>,
1506 ext_runtime: Arc<ExtensionRuntime>,
1507 llm: Arc<dyn LlmBackend>,
1508 telemetry: Arc<dyn Telemetry>,
1509 token_meter: Arc<dyn TokenMeter>,
1510 ledger: Arc<dyn ToolLedger>,
1511 merged_agents: Arc<HashMap<String, AgentConfig>>,
1512 audit_sink: Option<AuditSink>,
1513 real_tenant: greentic_types::TenantCtx,
1514 billing: TurnBilling,
1515 ) -> SupervisorFn {
1516 Arc::new(move |req: SupervisorRequest| {
1517 let merged_agents = merged_agents.clone();
1518 let state_store = state_store.clone();
1519 let ext_runtime = ext_runtime.clone();
1520 let llm = llm.clone();
1521 let telemetry = telemetry.clone();
1522 let token_meter = token_meter.clone();
1523 let ledger = ledger.clone();
1524 let audit_sink = audit_sink.clone();
1525 let real_tenant = real_tenant.clone();
1526 let billing = billing.clone();
1527 Box::pin(async move {
1528 run_one_supervisor_turn(
1529 req,
1530 state_store,
1531 ext_runtime,
1532 llm,
1533 telemetry,
1534 token_meter,
1535 ledger,
1536 merged_agents,
1537 audit_sink.as_ref(),
1538 &real_tenant,
1539 &billing,
1540 )
1541 .await
1542 }) as BoxFut<'static, Result<SupervisorResult, GraphExecError>>
1543 })
1544 }
1545
1546 fn resolve_supervisor_guardrails(
1558 agent_ref: Option<&str>,
1559 merged: &HashMap<String, AgentConfig>,
1560 node_id: &str,
1561 ) -> Result<Vec<greentic_aw_runtime::config::GuardrailRef>, GraphExecError> {
1562 let Some(id) = agent_ref else {
1563 return Ok(vec![]);
1564 };
1565 merged
1566 .get(id)
1567 .map(|parent| parent.guardrails.clone())
1568 .ok_or_else(|| {
1569 GraphExecError::Supervisor(format!(
1570 "node '{node_id}': agent_ref '{id}' not found in merged agents; \
1571 refusing to route without its guardrails"
1572 ))
1573 })
1574 }
1575
1576 #[allow(clippy::too_many_arguments)]
1598 async fn run_one_supervisor_turn(
1599 req: SupervisorRequest,
1600 state_store: Arc<dyn AgentStateStore>,
1601 ext_runtime: Arc<ExtensionRuntime>,
1602 llm: Arc<dyn LlmBackend>,
1603 telemetry: Arc<dyn Telemetry>,
1604 token_meter: Arc<dyn TokenMeter>,
1605 ledger: Arc<dyn ToolLedger>,
1606 merged_agents: Arc<HashMap<String, AgentConfig>>,
1607 audit_sink: Option<&AuditSink>,
1608 real_tenant: &greentic_types::TenantCtx,
1609 billing: &TurnBilling,
1610 ) -> Result<SupervisorResult, GraphExecError> {
1611 let tenant = billing.turn_tenant(real_tenant);
1613 let session_id = billing.scoped_session(&format!("graph__{}_sup", req.node_id));
1614 let agent_id = format!("graph.{}.supervisor", req.node_id);
1615
1616 let mut route_menu = String::from("\n\nAvailable routes:\n");
1618 for r in &req.routes {
1619 route_menu.push_str(&format!("- {}: {}\n", r.branch, r.description));
1620 }
1621 route_menu.push_str("\nReply with [[ROUTE:<branch>]] to select a route.");
1622
1623 let routing_system_prompt = format!("{}{}", req.system_prompt, route_menu);
1624
1625 let seeded = seed_state_from_graph(&tenant, &session_id, &req.state);
1626 if let Err(error) = state_store.save(&tenant, &session_id, &seeded).await {
1627 return Err(GraphExecError::Supervisor(format!(
1628 "seeding conversation state: {error}"
1629 )));
1630 }
1631
1632 let guardrails =
1633 resolve_supervisor_guardrails(req.agent_ref.as_deref(), &merged_agents, &req.node_id)?;
1634
1635 let cfg = AgentConfig {
1636 agent_id: agent_id.clone(),
1637 system_prompt: routing_system_prompt,
1638 tools: vec![],
1639 guardrails,
1640 llm: LlmProviderRef {
1641 provider: req.provider.clone().unwrap_or_else(|| "openai".into()),
1642 model: req.model.clone(),
1643 credential_ref: None,
1644 },
1645 limits: AgentLimits::default(),
1646 memory: None,
1647 knowledge: None,
1648 conversational: false,
1649 opening_message: None,
1650 on_text_while_parked: Default::default(),
1651 };
1652 let mut provider = InMemoryConfigProvider::new();
1653 provider.insert(&tenant, &agent_id, cfg);
1654
1655 let runtime = billing.install(AgentRuntime::new(
1656 Arc::new(provider),
1657 state_store,
1658 ext_runtime.clone(),
1659 llm,
1660 telemetry,
1661 token_meter,
1662 ledger,
1663 None,
1666 ));
1667 let runtime = super::super::agent_node::attach_guardrails(runtime, ext_runtime, Vec::new());
1670
1671 let input = AgentInput {
1672 text: String::new(),
1673 ..Default::default()
1674 };
1675
1676 let out = run_agent_step(
1677 &runtime,
1678 tenant.clone(),
1679 &session_id,
1680 &agent_id,
1681 input,
1682 audit_sink,
1683 real_tenant,
1684 )
1685 .await
1686 .map_err(|e| GraphExecError::Supervisor(format!("supervisor step failed: {e}")))?;
1687
1688 let branch = parse_route_branch(&out.reply, &req.routes).unwrap_or_else(|| {
1691 let fallback = req
1692 .routes
1693 .first()
1694 .map(|r| r.branch.clone())
1695 .unwrap_or_default();
1696 tracing::warn!(
1697 node_id = req.node_id,
1698 reply = %out.reply,
1699 fallback = %fallback,
1700 "supervisor reply missing or unknown [[ROUTE:]] sentinel; falling back to first route"
1701 );
1702 fallback
1703 });
1704
1705 let raw_reply = strip_route_sentinel(&out.reply);
1708
1709 Ok(SupervisorResult { branch, raw_reply })
1710 }
1711
1712 fn parse_route_branch(
1716 reply: &str,
1717 routes: &[greentic_aw_runtime::graph::SupervisorRoute],
1718 ) -> Option<String> {
1719 let lower = reply.to_ascii_lowercase();
1720 let prefix_lower = ROUTE_SENTINEL_PREFIX.to_ascii_lowercase();
1721 let suffix_lower = ROUTE_SENTINEL_SUFFIX.to_ascii_lowercase();
1722 let start = lower.find(&prefix_lower)?;
1723 let after_prefix = start + prefix_lower.len();
1724 let end = lower[after_prefix..].find(&suffix_lower)?;
1725 let branch = reply[after_prefix..after_prefix + end].trim().to_string();
1726 if routes.iter().any(|r| r.branch == branch) {
1728 Some(branch)
1729 } else {
1730 None
1731 }
1732 }
1733
1734 fn strip_route_sentinel(reply: &str) -> String {
1741 let lower = reply.to_ascii_lowercase();
1742 let prefix_lower = ROUTE_SENTINEL_PREFIX.to_ascii_lowercase();
1743 let suffix_lower = ROUTE_SENTINEL_SUFFIX.to_ascii_lowercase();
1744 if let Some(start) = lower.find(&prefix_lower) {
1745 let after_prefix = start + prefix_lower.len();
1746 if let Some(end) = lower[after_prefix..].find(&suffix_lower) {
1747 let sentinel_end = after_prefix + end + suffix_lower.len();
1748 let mut out = reply.to_string();
1749 out.replace_range(start..sentinel_end, "");
1750 return out.trim().to_string();
1751 }
1752 }
1753 reply.trim().to_string()
1754 }
1755
1756 fn build_tool(
1764 ext_runtime: Arc<ExtensionRuntime>,
1765 a2a_source: Option<Arc<greentic_aw_runtime::A2aToolSource>>,
1766 ) -> ToolFn {
1767 Arc::new(move |req: ToolCallRequest| {
1768 let ext_runtime = ext_runtime.clone();
1769 let a2a_source = a2a_source.clone();
1770 Box::pin(async move { run_one_tool(req, ext_runtime, a2a_source).await })
1771 as BoxFut<'static, Result<Value, GraphExecError>>
1772 })
1773 }
1774
1775 fn default_approval_awaiting() -> ApprovalFn {
1789 Arc::new(|_req: ApprovalRequest| Box::pin(async move { Ok(ApprovalOutcome::Awaiting) }))
1790 }
1791
1792 async fn run_one_tool(
1794 req: ToolCallRequest,
1795 ext_runtime: Arc<ExtensionRuntime>,
1796 a2a_source: Option<Arc<greentic_aw_runtime::A2aToolSource>>,
1797 ) -> Result<Value, GraphExecError> {
1798 let (extension_id, tool_name) = req.tool_name.split_once('/').ok_or_else(|| {
1799 GraphExecError::Tool(format!(
1800 "tool name '{}' must be 'extension_id/tool_name'",
1801 req.tool_name
1802 ))
1803 })?;
1804 if extension_id.is_empty() || tool_name.is_empty() {
1805 return Err(GraphExecError::Tool(format!(
1806 "tool name '{}' must be 'extension_id/tool_name' (non-empty parts)",
1807 req.tool_name
1808 )));
1809 }
1810
1811 let call = greentic_aw_runtime::state::ToolCallRecord {
1814 call_id: format!("{}__{}", req.node_id, tool_name),
1815 extension_id: extension_id.to_string(),
1816 tool_name: tool_name.to_string(),
1817 args: json!({}),
1818 };
1819
1820 let a2a = match a2a_source.as_ref() {
1832 Some(source) => Some(source.catalog().await),
1833 None => None,
1834 };
1835 let tenant = TenantContext::new("", "");
1836 dispatch_tool_call(ext_runtime, None, None, None, None, a2a, call, &tenant)
1844 .await
1845 .map_err(|e| GraphExecError::Tool(format!("dispatch '{}': {e}", req.tool_name)))
1846 }
1847
1848 #[cfg(all(test, feature = "agentic-worker"))]
1849 mod tests {
1850 use std::collections::HashMap;
1851 use std::sync::Arc;
1852 use std::sync::atomic::{AtomicU32, Ordering};
1853
1854 use greentic_aw_runtime::graph::model::SupervisorRoute;
1855 use greentic_aw_runtime::graph::{
1856 AgentTurnFn, AgentTurnRequest, AgentTurnResult, ApprovalFn, ApprovalOutcome,
1857 ApprovalRequest, GraphConfig, InMemoryCheckpointStore, SupervisorFn, SupervisorRequest,
1858 SupervisorResult, ToolCallRequest, ToolFn,
1859 };
1860 use greentic_aw_runtime::mock::MockAgentStateStore;
1861 use serde_json::json;
1862
1863 use super::*;
1864
1865 fn triage_graph_json(max_iterations: u32) -> String {
1873 json!({
1874 "schemaVersion": 1,
1875 "entry": "agent",
1876 "nodes": [
1877 {"id": "agent", "kind": "agent", "systemPrompt": "You triage.", "model": "gpt-4o-mini", "tools": []},
1878 {"id": "lookup", "kind": "tool", "toolName": "kb/search"},
1879 {"id": "router", "kind": "router", "maxIterations": max_iterations},
1880 {"id": "respond", "kind": "respond"}
1881 ],
1882 "edges": [
1883 {"from": "agent", "to": "lookup"},
1884 {"from": "lookup", "to": "router"},
1885 {"from": "router", "to": "agent", "branch": "loop"},
1886 {"from": "router", "to": "respond", "branch": "resolved"}
1887 ]
1888 })
1889 .to_string()
1890 }
1891
1892 fn triage_cfg(max_iterations: u32) -> GraphConfig {
1893 GraphConfig::from_json(&triage_graph_json(max_iterations)).expect("fixture valid")
1894 }
1895
1896 fn approval_graph_json() -> String {
1902 json!({
1903 "schemaVersion": 2,
1904 "entry": "start",
1905 "nodes": [
1906 {"id": "start", "kind": "agent", "systemPrompt": "greet the user", "model": "gpt-4o-mini", "tools": []},
1907 {"id": "approval", "kind": "approval", "title": "Approve refund?", "mode": "always"},
1908 {"id": "respond", "kind": "respond"}
1909 ],
1910 "edges": [
1911 {"from": "start", "to": "approval"},
1912 {"from": "approval", "to": "respond", "branch": "approved"}
1913 ]
1914 })
1915 .to_string()
1916 }
1917
1918 fn approval_cfg() -> GraphConfig {
1919 GraphConfig::from_json(&approval_graph_json()).expect("approval fixture valid")
1920 }
1921
1922 fn approval_fn_toggle(decide: Arc<std::sync::atomic::AtomicBool>) -> ApprovalFn {
1927 Arc::new(move |_req: ApprovalRequest| {
1928 let decide = decide.clone();
1929 Box::pin(async move {
1930 if decide.load(Ordering::SeqCst) {
1931 Ok(ApprovalOutcome::Decided {
1932 branch: "approved".to_string(),
1933 })
1934 } else {
1935 Ok(ApprovalOutcome::Awaiting)
1936 }
1937 })
1938 })
1939 }
1940
1941 fn provider_with(graph_id: &str, cfg: GraphConfig) -> Arc<InMemoryGraphProvider> {
1942 let mut graphs = HashMap::new();
1943 graphs.insert(graph_id.to_string(), cfg);
1944 Arc::new(InMemoryGraphProvider::new(graphs))
1945 }
1946
1947 fn agent_fn_resolves_on(counter: Arc<AtomicU32>, resolve_on_call: u32) -> AgentTurnFn {
1949 Arc::new(move |req: AgentTurnRequest| {
1950 let n = counter.fetch_add(1, Ordering::SeqCst) + 1;
1951 let resolved = n >= resolve_on_call;
1952 let reply = format!("reply-{n} from {}", req.node_id);
1953 Box::pin(async move { Ok(AgentTurnResult { reply, resolved }) })
1954 })
1955 }
1956
1957 fn tool_fn_ok() -> ToolFn {
1958 Arc::new(move |_req: ToolCallRequest| {
1959 Box::pin(async move { Ok(json!({"found": true})) })
1960 })
1961 }
1962
1963 fn supervisor_fn_noop() -> SupervisorFn {
1965 Arc::new(|_req: SupervisorRequest| {
1966 Box::pin(async move {
1967 Err(greentic_aw_runtime::graph::GraphExecError::Supervisor(
1968 "supervisor fn should not be called in this test".into(),
1969 ))
1970 })
1971 })
1972 }
1973
1974 fn approval_fn_awaiting() -> ApprovalFn {
1977 Arc::new(|_req: ApprovalRequest| Box::pin(async move { Ok(ApprovalOutcome::Awaiting) }))
1978 }
1979
1980 fn handler_with(
1981 graphs: Arc<dyn GraphConfigSource>,
1982 agent_turn: AgentTurnFn,
1983 tool: ToolFn,
1984 ) -> RuntimeGraphNodeHandler {
1985 RuntimeGraphNodeHandler::with_effects(
1986 graphs,
1987 Arc::new(InMemoryCheckpointStore::default()),
1988 Arc::new(MockAgentStateStore::new()),
1989 agent_turn,
1990 tool,
1991 supervisor_fn_noop(),
1992 approval_fn_awaiting(),
1993 )
1994 }
1995
1996 #[test]
2001 fn parse_tool_ref_splits_on_last_slash() {
2002 assert_eq!(
2003 super::parse_tool_ref("myext/dothing"),
2004 Some(ToolRef {
2005 extension_id: "myext".into(),
2006 tool_name: "dothing".into(),
2007 description: None,
2008 input_schema: None,
2009 usage_note: None,
2010 })
2011 );
2012 assert_eq!(
2013 super::parse_tool_ref("component:owner/repo/list"),
2014 Some(ToolRef {
2015 extension_id: "component:owner/repo".into(),
2016 tool_name: "list".into(),
2017 description: None,
2018 input_schema: None,
2019 usage_note: None,
2020 })
2021 );
2022 assert_eq!(super::parse_tool_ref("noslash"), None);
2023 assert_eq!(super::parse_tool_ref("trailing/"), None);
2024 }
2025
2026 #[test]
2027 fn parse_tool_ref_rejects_leading_slash() {
2028 assert_eq!(super::parse_tool_ref("/dothing"), None);
2030 }
2031
2032 #[test]
2033 fn map_tool_refs_drops_malformed_entries_and_keeps_valid_ones() {
2034 let tools = vec![
2035 "myext/dothing".to_string(),
2036 "noslash".to_string(),
2037 "other/thing".to_string(),
2038 ];
2039 let refs = super::map_tool_refs(&tools);
2040 assert_eq!(
2041 refs,
2042 vec![
2043 ToolRef {
2044 extension_id: "myext".into(),
2045 tool_name: "dothing".into(),
2046 description: None,
2047 input_schema: None,
2048 usage_note: None,
2049 },
2050 ToolRef {
2051 extension_id: "other".into(),
2052 tool_name: "thing".into(),
2053 description: None,
2054 input_schema: None,
2055 usage_note: None,
2056 },
2057 ]
2058 );
2059 }
2060
2061 #[test]
2066 fn sidecar_valid_triage_parses() {
2067 let bytes = triage_graph_json(3).into_bytes();
2068 let cfg = super::graph_config_from_sidecar("test-pack", &bytes);
2069 assert!(cfg.is_some(), "valid triage sidecar must parse");
2070 }
2071
2072 #[test]
2073 fn sidecar_malformed_json_returns_none() {
2074 let bytes = b"{ this is not valid json";
2075 let cfg = super::graph_config_from_sidecar("test-pack", bytes);
2077 assert!(cfg.is_none(), "malformed JSON sidecar must yield None");
2078 }
2079
2080 #[test]
2081 fn sidecar_unsupported_schema_version_returns_none() {
2082 let bytes = json!({
2083 "schemaVersion": 99,
2084 "entry": "agent",
2085 "nodes": [
2086 {"id": "agent", "kind": "agent", "systemPrompt": "x", "model": "gpt-4o-mini", "tools": []},
2087 {"id": "respond", "kind": "respond"}
2088 ],
2089 "edges": [{"from": "agent", "to": "respond"}]
2090 })
2091 .to_string()
2092 .into_bytes();
2093 let cfg = super::graph_config_from_sidecar("test-pack", &bytes);
2094 assert!(
2095 cfg.is_none(),
2096 "unsupported schemaVersion must be rejected (None)"
2097 );
2098 }
2099
2100 #[tokio::test]
2105 async fn executes_graph_and_returns_dw_agent_envelope() {
2106 let handler = handler_with(
2107 provider_with("triage", triage_cfg(3)),
2108 agent_fn_resolves_on(Arc::new(AtomicU32::new(0)), 1),
2109 tool_fn_ok(),
2110 );
2111
2112 let out = handler
2113 .execute("t", "e", "triage", "sess-1", &json!({"user_text": "help"}))
2114 .await
2115 .expect("execute should succeed");
2116
2117 assert_eq!(out["terminated_by"].as_str(), Some("respond"));
2118 assert!(
2119 out["reply"].as_str().unwrap_or("").contains("reply-1"),
2120 "reply should carry agent output: {:?}",
2121 out["reply"]
2122 );
2123 assert!(
2124 out["trail"]
2125 .as_array()
2126 .map(|a| !a.is_empty())
2127 .unwrap_or(false),
2128 "trail should be a non-empty array: {:?}",
2129 out["trail"]
2130 );
2131 }
2132
2133 #[tokio::test]
2137 async fn attachments_on_a_graph_turn_are_announced_with_the_fixed_notice() {
2138 let seen = Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
2139 let seen_by_agent = seen.clone();
2140 let agent: AgentTurnFn = Arc::new(move |req: AgentTurnRequest| {
2141 seen_by_agent.lock().unwrap().extend(
2142 req.state
2143 .messages
2144 .iter()
2145 .map(|m| m.content.clone())
2146 .collect::<Vec<_>>(),
2147 );
2148 Box::pin(async move {
2149 Ok(AgentTurnResult {
2150 reply: "done".into(),
2151 resolved: true,
2152 })
2153 })
2154 });
2155 let handler = handler_with(provider_with("triage", triage_cfg(3)), agent, tool_fn_ok());
2156 handler
2157 .execute(
2158 "t",
2159 "e",
2160 "triage",
2161 "sess-1",
2162 &json!({
2163 "user_text": "look",
2164 "attachments": [
2165 {"mime_type": "image/png", "url": format!("artifact://{}", "a".repeat(64)), "name": "secret.png"},
2166 {"mime_type": "application/pdf", "url": null, "name": "b.pdf"}
2167 ]
2168 }),
2169 )
2170 .await
2171 .expect("execute should succeed");
2172 let seen = seen.lock().unwrap().join("\n");
2173 let note = greentic_aw_runtime::attachments_materialize::unreadable_note(1);
2177 assert!(
2178 seen.contains(&format!(
2179 "look\n[attachment not used: a file was not stored for the agent]{note}"
2180 )),
2181 "{seen}"
2182 );
2183 assert!(!seen.contains("secret.png"), "{seen}");
2184 assert!(!seen.contains("b.pdf"), "{seen}");
2185 }
2186
2187 #[tokio::test]
2188 async fn same_session_resumes_completed_run_with_fresh_run() {
2189 let graphs = provider_with("triage", triage_cfg(3));
2192 let checkpoint = Arc::new(InMemoryCheckpointStore::default());
2193 let state_store = Arc::new(MockAgentStateStore::new());
2194 let counter = Arc::new(AtomicU32::new(0));
2195
2196 let handler = RuntimeGraphNodeHandler::with_effects(
2197 graphs,
2198 checkpoint.clone(),
2199 state_store,
2200 agent_fn_resolves_on(counter, 1),
2201 tool_fn_ok(),
2202 supervisor_fn_noop(),
2203 approval_fn_awaiting(),
2204 );
2205
2206 let first = handler
2207 .execute("t", "e", "triage", "sess-1", &json!({"user_text": "one"}))
2208 .await
2209 .expect("first call succeeds");
2210 assert_eq!(first["terminated_by"].as_str(), Some("respond"));
2211
2212 let second = handler
2213 .execute("t", "e", "triage", "sess-1", &json!({"user_text": "two"}))
2214 .await
2215 .expect("second call succeeds with fresh run id");
2216 assert_eq!(second["terminated_by"].as_str(), Some("respond"));
2217
2218 let tenant = TenantContext::new("t", "e");
2220 let fresh = checkpoint
2221 .load(&tenant, "sess-1__triage__2")
2222 .await
2223 .expect("store ok");
2224 assert!(fresh.is_some(), "fresh __2 run id should be recorded");
2225 }
2226
2227 #[tokio::test]
2235 async fn awaiting_input_parks_without_orphaning_and_resumes_on_decision() {
2236 let graphs = provider_with("approval-graph", approval_cfg());
2237 let checkpoint = Arc::new(InMemoryCheckpointStore::default());
2238 let state_store = Arc::new(MockAgentStateStore::new());
2239 let decide = Arc::new(std::sync::atomic::AtomicBool::new(false));
2240
2241 let handler = RuntimeGraphNodeHandler::with_effects(
2242 graphs,
2243 checkpoint.clone(),
2244 state_store,
2245 agent_fn_resolves_on(Arc::new(AtomicU32::new(0)), 1),
2246 tool_fn_ok(),
2247 supervisor_fn_noop(),
2248 approval_fn_toggle(decide.clone()),
2249 );
2250 let tenant = TenantContext::new("t", "e");
2251
2252 let first = handler
2254 .execute(
2255 "t",
2256 "e",
2257 "approval-graph",
2258 "sess-approve",
2259 &json!({"user_text": "please refund"}),
2260 )
2261 .await
2262 .expect("a parked run must be Ok, not an Err");
2263 assert_ne!(
2264 first["terminated_by"].as_str(),
2265 Some("respond"),
2266 "a parked run must not be reported as a completed respond: {first:?}"
2267 );
2268 assert_ne!(
2269 first["terminated_by"].as_str(),
2270 Some("error"),
2271 "a parked run must not be reported as an error: {first:?}"
2272 );
2273
2274 let rec = checkpoint
2275 .load(&tenant, "sess-approve__approval-graph")
2276 .await
2277 .expect("store accessible")
2278 .expect("base run id must be recorded");
2279 assert_eq!(
2280 rec.status,
2281 RunStatus::AwaitingInput,
2282 "persisted record must reflect the park"
2283 );
2284
2285 let second = handler
2288 .execute(
2289 "t",
2290 "e",
2291 "approval-graph",
2292 "sess-approve",
2293 &json!({"user_text": "still waiting"}),
2294 )
2295 .await
2296 .expect("a re-parked run must be Ok, not an Err");
2297 assert_ne!(second["terminated_by"].as_str(), Some("respond"));
2298
2299 let forked = checkpoint
2300 .load(&tenant, "sess-approve__approval-graph__2")
2301 .await
2302 .expect("store accessible");
2303 assert!(
2304 forked.is_none(),
2305 "an AwaitingInput run must resume in place, not fork a fresh run id"
2306 );
2307
2308 decide.store(true, Ordering::SeqCst);
2311 let third = handler
2312 .execute(
2313 "t",
2314 "e",
2315 "approval-graph",
2316 "sess-approve",
2317 &json!({"user_text": "resolve"}),
2318 )
2319 .await
2320 .expect("execute should succeed once decided");
2321 assert_eq!(third["terminated_by"].as_str(), Some("respond"));
2322
2323 let rec = checkpoint
2324 .load(&tenant, "sess-approve__approval-graph")
2325 .await
2326 .expect("store accessible")
2327 .expect("base run id must still be recorded");
2328 assert_eq!(
2329 rec.status,
2330 RunStatus::Succeeded,
2331 "the base run id must resolve once decided, not a forked one"
2332 );
2333 }
2334
2335 #[tokio::test]
2336 async fn missing_graph_returns_structured_error_reply() {
2337 let handler = handler_with(
2338 provider_with("triage", triage_cfg(3)),
2339 agent_fn_resolves_on(Arc::new(AtomicU32::new(0)), 1),
2340 tool_fn_ok(),
2341 );
2342
2343 let out = handler
2344 .execute("t", "e", "unknown", "sess-1", &json!({"user_text": "hi"}))
2345 .await
2346 .expect("missing graph must NOT return Err");
2347
2348 assert_eq!(out["terminated_by"].as_str(), Some("error"));
2349 assert!(
2350 out["reply"]
2351 .as_str()
2352 .unwrap_or("")
2353 .to_ascii_lowercase()
2354 .contains("available"),
2355 "reply should mention availability: {:?}",
2356 out["reply"]
2357 );
2358 }
2359
2360 #[tokio::test]
2361 async fn missing_user_text_matches_agent_node_contract() {
2362 let handler = handler_with(
2365 provider_with("triage", triage_cfg(3)),
2366 agent_fn_resolves_on(Arc::new(AtomicU32::new(0)), 1),
2367 tool_fn_ok(),
2368 );
2369
2370 let out = handler
2371 .execute("t", "e", "triage", "sess-1", &json!({}))
2372 .await
2373 .expect("missing user_text must NOT return Err (matches agent_node)");
2374
2375 assert_eq!(out["terminated_by"].as_str(), Some("respond"));
2376 }
2377
2378 #[tokio::test]
2379 async fn iteration_cap_maps_to_error_envelope() {
2380 let handler = handler_with(
2383 provider_with("triage", triage_cfg(1000)),
2384 agent_fn_resolves_on(Arc::new(AtomicU32::new(0)), u32::MAX),
2386 tool_fn_ok(),
2387 );
2388
2389 let out = handler
2390 .execute("t", "e", "triage", "sess-1", &json!({"user_text": "loop"}))
2391 .await
2392 .expect("iteration cap must NOT return Err");
2393
2394 assert_eq!(out["terminated_by"].as_str(), Some("error"));
2395 assert_ne!(
2396 out["reply"].as_str(),
2397 Some(SANITISED_ERROR_REPLY),
2398 "iteration cap should use a distinct reply"
2399 );
2400 }
2401
2402 #[tokio::test]
2408 async fn colon_bearing_session_id_executes_successfully() {
2409 let handler = handler_with(
2410 provider_with("triage", triage_cfg(3)),
2411 agent_fn_resolves_on(Arc::new(AtomicU32::new(0)), 1),
2412 tool_fn_ok(),
2413 );
2414
2415 let out = handler
2417 .execute(
2418 "t",
2419 "e",
2420 "triage",
2421 "msteams:thread:19xyz",
2422 &json!({"user_text": "hello"}),
2423 )
2424 .await
2425 .expect("colon-bearing session id must NOT return Err");
2426
2427 assert_eq!(
2428 out["terminated_by"].as_str(),
2429 Some("respond"),
2430 "colon-bearing session id should complete successfully: {:?}",
2431 out
2432 );
2433 }
2434
2435 struct ErrGraphProvider(fn() -> ConfigError);
2441
2442 impl GraphConfigSource for ErrGraphProvider {
2443 fn graph_config<'a>(
2444 &'a self,
2445 _tenant: &'a TenantContext,
2446 _graph_id: &'a str,
2447 ) -> BoxFut<'a, Result<GraphConfig, ConfigError>> {
2448 let e = (self.0)();
2449 Box::pin(async move { Err(e) })
2450 }
2451 }
2452
2453 struct PanicGraphProvider;
2455
2456 impl GraphConfigSource for PanicGraphProvider {
2457 fn graph_config<'a>(
2458 &'a self,
2459 _tenant: &'a TenantContext,
2460 _graph_id: &'a str,
2461 ) -> BoxFut<'a, Result<GraphConfig, ConfigError>> {
2462 Box::pin(
2463 async move { panic!("fallback must not be consulted when primary returns Ok") },
2464 )
2465 }
2466 }
2467
2468 #[tokio::test]
2469 async fn layered_primary_ok_short_circuits_fallback() {
2470 let mut graphs = HashMap::new();
2471 graphs.insert("g".to_string(), triage_cfg(3));
2472 let primary = InMemoryGraphProvider::new(graphs);
2473 let layered = LayeredGraphProvider::new(primary, PanicGraphProvider);
2474 let tc = TenantContext::new("t", "e");
2475 let cfg = layered.graph_config(&tc, "g").await.unwrap();
2477 assert_eq!(cfg.graph.entry, "agent");
2478 }
2479
2480 #[tokio::test]
2481 async fn layered_falls_back_on_not_found() {
2482 let mut graphs = HashMap::new();
2483 graphs.insert("g".to_string(), triage_cfg(3));
2484 let fb = InMemoryGraphProvider::new(graphs);
2485 let layered = LayeredGraphProvider::new(
2486 ErrGraphProvider(|| ConfigError::AgentNotFound("g".into())),
2487 fb,
2488 );
2489 let tc = TenantContext::new("t", "e");
2490 let cfg = layered.graph_config(&tc, "g").await.unwrap();
2491 assert_eq!(cfg.graph.entry, "agent");
2492 }
2493
2494 #[tokio::test]
2495 async fn layered_falls_back_on_internal() {
2496 let mut graphs = HashMap::new();
2497 graphs.insert("g".to_string(), triage_cfg(3));
2498 let fb = InMemoryGraphProvider::new(graphs);
2499 let layered = LayeredGraphProvider::new(
2500 ErrGraphProvider(|| ConfigError::Internal("down".into())),
2501 fb,
2502 );
2503 let tc = TenantContext::new("t", "e");
2504 let cfg = layered.graph_config(&tc, "g").await.unwrap();
2505 assert_eq!(cfg.graph.entry, "agent");
2506 }
2507
2508 #[tokio::test]
2509 async fn layered_propagates_misconfigured_without_fallback() {
2510 let fb = InMemoryGraphProvider::new(HashMap::new());
2511 let layered = LayeredGraphProvider::new(
2512 ErrGraphProvider(|| ConfigError::Misconfigured("bad schema".into())),
2513 fb,
2514 );
2515 let tc = TenantContext::new("t", "e");
2516 let result = layered.graph_config(&tc, "g").await;
2517 assert!(
2518 matches!(result, Err(ConfigError::Misconfigured(_))),
2519 "Misconfigured must NOT fall back: {result:?}"
2520 );
2521 }
2522
2523 #[test]
2528 #[serial_test::serial]
2529 #[allow(unsafe_code)]
2530 fn graph_registry_from_env_requires_both_vars() {
2531 unsafe {
2533 std::env::remove_var("GREENTIC_AW_ADMIN_ENDPOINT");
2534 std::env::remove_var("GREENTIC_AW_ADMIN_TOKEN");
2535 }
2536 assert!(super::graph_registry_from_env().is_none());
2537
2538 unsafe {
2539 std::env::set_var("GREENTIC_AW_ADMIN_ENDPOINT", "http://localhost:9999");
2540 }
2541 assert!(
2542 super::graph_registry_from_env().is_none(),
2543 "endpoint alone is not enough"
2544 );
2545
2546 unsafe {
2547 std::env::set_var("GREENTIC_AW_ADMIN_TOKEN", "gtc_live_x");
2548 }
2549 assert!(super::graph_registry_from_env().is_some());
2550
2551 unsafe {
2553 std::env::remove_var("GREENTIC_AW_ADMIN_ENDPOINT");
2554 }
2555 assert!(
2556 super::graph_registry_from_env().is_none(),
2557 "token alone is not enough"
2558 );
2559
2560 unsafe {
2561 std::env::remove_var("GREENTIC_AW_ADMIN_TOKEN");
2562 }
2563 }
2564
2565 fn supervisor_graph_json() -> String {
2580 json!({
2581 "schemaVersion": 2,
2582 "entry": "sup",
2583 "nodes": [
2584 {
2585 "id": "sup",
2586 "kind": "supervisor",
2587 "systemPrompt": "Route the request to the correct specialist.",
2588 "model": "gpt-4o-mini",
2589 "routes": [
2590 {"branch": "billing", "description": "Billing and payment questions"},
2591 {"branch": "tech", "description": "Technical support issues"}
2592 ]
2593 },
2594 {"id": "agent_billing", "kind": "agent", "systemPrompt": "Billing.", "model": "gpt-4o-mini", "tools": []},
2595 {"id": "router_billing", "kind": "router", "maxIterations": 2},
2596 {"id": "agent_tech", "kind": "agent", "systemPrompt": "Tech.", "model": "gpt-4o-mini", "tools": []},
2597 {"id": "router_tech", "kind": "router", "maxIterations": 2},
2598 {"id": "respond", "kind": "respond"}
2599 ],
2600 "edges": [
2601 {"from": "sup", "to": "agent_billing", "branch": "billing"},
2602 {"from": "sup", "to": "agent_tech", "branch": "tech"},
2603 {"from": "agent_billing", "to": "router_billing"},
2604 {"from": "router_billing","to": "agent_billing", "branch": "loop"},
2605 {"from": "router_billing","to": "respond", "branch": "resolved"},
2606 {"from": "agent_tech", "to": "router_tech"},
2607 {"from": "router_tech", "to": "agent_tech", "branch": "loop"},
2608 {"from": "router_tech", "to": "respond", "branch": "resolved"}
2609 ]
2610 })
2611 .to_string()
2612 }
2613
2614 fn supervisor_cfg() -> GraphConfig {
2615 GraphConfig::from_json(&supervisor_graph_json()).expect("supervisor fixture valid")
2616 }
2617
2618 fn route(branch: &str, description: &str) -> SupervisorRoute {
2620 SupervisorRoute {
2621 branch: branch.to_string(),
2622 description: description.to_string(),
2623 }
2624 }
2625
2626 fn supervisor_fn_routes_to(fixed_branch: &str) -> SupervisorFn {
2628 let branch = fixed_branch.to_string();
2629 Arc::new(move |_req: SupervisorRequest| {
2630 let branch = branch.clone();
2631 Box::pin(async move {
2632 Ok(SupervisorResult {
2633 branch: branch.clone(),
2634 raw_reply: format!("I'll route this. [[ROUTE:{branch}]] Done."),
2635 })
2636 })
2637 })
2638 }
2639
2640 fn supervisor_handler(
2643 graphs: Arc<dyn GraphConfigSource>,
2644 supervisor: SupervisorFn,
2645 ) -> RuntimeGraphNodeHandler {
2646 let agent: AgentTurnFn = agent_fn_resolves_on(Arc::new(AtomicU32::new(0)), 1);
2647 RuntimeGraphNodeHandler::with_effects(
2648 graphs,
2649 Arc::new(InMemoryCheckpointStore::default()),
2650 Arc::new(MockAgentStateStore::new()),
2651 agent,
2652 tool_fn_ok(),
2653 supervisor,
2654 approval_fn_awaiting(),
2655 )
2656 }
2657
2658 fn billing_tech_routes() -> Vec<SupervisorRoute> {
2664 vec![
2665 route("billing", "Billing and payment questions"),
2666 route("tech", "Technical support issues"),
2667 ]
2668 }
2669
2670 #[test]
2671 fn parse_route_extracts_billing_from_reply() {
2672 let reply = "I analysed the message. [[ROUTE:billing]] Go ahead.";
2674 let result = parse_route_branch(reply, &billing_tech_routes());
2675 assert_eq!(result, Some("billing".to_string()));
2676 }
2677
2678 #[test]
2679 fn parse_route_case_insensitive_prefix() {
2680 let reply = "[[route:tech]] is the answer";
2684 let result = parse_route_branch(reply, &billing_tech_routes());
2685 assert_eq!(result, Some("tech".to_string()));
2686 }
2687
2688 #[test]
2689 fn parse_route_missing_sentinel_returns_none() {
2690 let reply = "I think billing would be best here.";
2692 let result = parse_route_branch(reply, &billing_tech_routes());
2693 assert_eq!(result, None);
2694 }
2695
2696 #[test]
2697 fn parse_route_unknown_branch_returns_none() {
2698 let reply = "[[ROUTE:unknown_branch]] routing";
2700 let result = parse_route_branch(reply, &billing_tech_routes());
2701 assert_eq!(result, None);
2702 }
2703
2704 #[test]
2705 fn parse_route_multiple_sentinels_uses_first() {
2706 let reply = "[[ROUTE:billing]] or [[ROUTE:tech]]";
2709 let result = parse_route_branch(reply, &billing_tech_routes());
2710 assert_eq!(
2711 result,
2712 Some("billing".to_string()),
2713 "multiple sentinels: first occurrence wins"
2714 );
2715 }
2716
2717 #[test]
2718 fn parse_route_branch_label_whitespace_trimmed() {
2719 let reply = "[[ROUTE: billing ]]";
2721 let result = parse_route_branch(reply, &billing_tech_routes());
2722 assert_eq!(result, Some("billing".to_string()));
2723 }
2724
2725 #[test]
2730 fn strip_sentinel_removes_token_leaves_rest() {
2731 let reply = "I'll route this. [[ROUTE:billing]] Proceeding.";
2732 let stripped = strip_route_sentinel(reply);
2733 assert!(
2734 !stripped.contains("[[ROUTE:billing]]"),
2735 "sentinel must be removed: {stripped:?}"
2736 );
2737 assert!(
2738 stripped.contains("Proceeding"),
2739 "text after sentinel must survive: {stripped:?}"
2740 );
2741 }
2742
2743 #[test]
2744 fn strip_sentinel_no_sentinel_returns_trimmed() {
2745 let reply = " No routing needed here. ";
2746 let stripped = strip_route_sentinel(reply);
2747 assert_eq!(stripped, "No routing needed here.");
2748 }
2749
2750 #[test]
2751 fn strip_sentinel_case_insensitive_removal() {
2752 let reply = "Decision: [[route:tech]] done.";
2753 let stripped = strip_route_sentinel(reply);
2754 assert!(
2755 !stripped.to_ascii_lowercase().contains("[[route:"),
2756 "sentinel must be stripped case-insensitively: {stripped:?}"
2757 );
2758 }
2759
2760 #[test]
2761 fn strip_sentinel_only_first_occurrence_removed() {
2762 let reply = "[[ROUTE:billing]] first [[ROUTE:tech]] second";
2764 let stripped = strip_route_sentinel(reply);
2765 assert!(
2766 !stripped.contains("[[ROUTE:billing]]"),
2767 "first sentinel must be gone: {stripped:?}"
2768 );
2769 assert!(
2771 stripped.contains("[[ROUTE:tech]]"),
2772 "second sentinel must remain: {stripped:?}"
2773 );
2774 }
2775
2776 #[test]
2781 fn parse_route_none_documents_fallback_to_first_route() {
2782 let routes = billing_tech_routes();
2787 let garbage = "absolutely no routing sentinel here";
2788 let parsed = parse_route_branch(garbage, &routes);
2789 assert_eq!(parsed, None, "no sentinel → None from parser");
2790
2791 let fallback = parsed
2793 .unwrap_or_else(|| routes.first().map(|r| r.branch.clone()).unwrap_or_default());
2794 assert_eq!(
2795 fallback, "billing",
2796 "None → first route 'billing' as fallback"
2797 );
2798 }
2799
2800 #[tokio::test]
2805 async fn supervisor_routes_to_billing_returns_respond_envelope() {
2806 let handler = supervisor_handler(
2810 provider_with("sup_graph", supervisor_cfg()),
2811 supervisor_fn_routes_to("billing"),
2812 );
2813
2814 let out = handler
2815 .execute(
2816 "t",
2817 "e",
2818 "sup_graph",
2819 "sess-sup-1",
2820 &json!({"user_text": "I need billing help"}),
2821 )
2822 .await
2823 .expect("supervisor execute must not Err");
2824
2825 assert_eq!(
2826 out["terminated_by"].as_str(),
2827 Some("respond"),
2828 "billing path must terminate at respond: {out:?}"
2829 );
2830 assert!(
2831 out["reply"].as_str().is_some_and(|r| !r.is_empty()),
2832 "reply must be non-empty: {out:?}"
2833 );
2834 assert!(
2835 out["trail"].as_array().is_some_and(|t| !t.is_empty()),
2836 "trail must be non-empty: {out:?}"
2837 );
2838 }
2839
2840 #[tokio::test]
2841 async fn supervisor_routes_to_tech_returns_respond_envelope() {
2842 let handler = supervisor_handler(
2844 provider_with("sup_graph", supervisor_cfg()),
2845 supervisor_fn_routes_to("tech"),
2846 );
2847
2848 let out = handler
2849 .execute(
2850 "t",
2851 "e",
2852 "sup_graph",
2853 "sess-sup-2",
2854 &json!({"user_text": "my device is broken"}),
2855 )
2856 .await
2857 .expect("supervisor tech-route execute must not Err");
2858
2859 assert_eq!(
2860 out["terminated_by"].as_str(),
2861 Some("respond"),
2862 "tech path must terminate at respond: {out:?}"
2863 );
2864 }
2865
2866 #[tokio::test]
2867 async fn supervisor_fallback_on_missing_sentinel_still_completes() {
2868 let supervisor: SupervisorFn = Arc::new(|_req: SupervisorRequest| {
2880 Box::pin(async move {
2883 Ok(SupervisorResult {
2884 branch: "billing".to_string(),
2885 raw_reply: "I think billing is right.".to_string(),
2886 })
2887 })
2888 });
2889
2890 let handler =
2891 supervisor_handler(provider_with("sup_graph", supervisor_cfg()), supervisor);
2892
2893 let out = handler
2894 .execute(
2895 "t",
2896 "e",
2897 "sup_graph",
2898 "sess-sup-3",
2899 &json!({"user_text": "help me"}),
2900 )
2901 .await
2902 .expect("fallback supervisor must not Err");
2903
2904 assert_eq!(
2905 out["terminated_by"].as_str(),
2906 Some("respond"),
2907 "fallback path must still reach respond: {out:?}"
2908 );
2909 }
2910
2911 fn real_tenant_ctx(tenant: &str, env: &str) -> greentic_types::TenantCtx {
2918 greentic_types::TenantCtx::new(
2919 greentic_types::EnvId::try_from(env).expect("valid env id"),
2920 greentic_types::TenantId::try_from(tenant).expect("valid tenant id"),
2921 )
2922 }
2923
2924 fn agent_runtime_with_scripted_remember_call(
2944 tenant: &TenantContext,
2945 agent_id: &str,
2946 ) -> AgentRuntime {
2947 use greentic_aw_runtime::cost::MockTokenMeter;
2948 use greentic_aw_runtime::llm::LlmResponse;
2949 use greentic_aw_runtime::mock::{MockLlmBackend, MockTelemetry, NoopToolLedger};
2950 use greentic_aw_runtime::state::ToolCallRecord;
2951 use greentic_aw_runtime::{InMemoryMemoryProvider, MemoryProviderRef, MemorySettings};
2952
2953 let llm = Arc::new(MockLlmBackend::new(vec![
2954 Ok(LlmResponse {
2955 content: None,
2956 tool_calls: vec![ToolCallRecord {
2957 call_id: "c1".into(),
2958 extension_id: "host".into(),
2959 tool_name: "remember".into(),
2960 args: json!({"key": "k", "value": "v"}),
2961 }],
2962 tokens_in: 1,
2963 tokens_out: 1,
2964 }),
2965 Ok(LlmResponse {
2966 content: Some("done".into()),
2967 tool_calls: vec![],
2968 tokens_in: 1,
2969 tokens_out: 1,
2970 }),
2971 ]));
2972
2973 let cfg = AgentConfig {
2974 agent_id: agent_id.to_string(),
2975 system_prompt: "test".into(),
2976 tools: vec![],
2977 guardrails: vec![],
2978 llm: LlmProviderRef {
2979 provider: "openai".into(),
2980 model: "gpt-4o-mini".into(),
2981 credential_ref: None,
2982 },
2983 limits: AgentLimits::default(),
2984 memory: Some(MemorySettings {
2985 short_term: Some(MemoryProviderRef {
2986 provider: "inmemory".into(),
2987 capability: "cap://memory/short-term".into(),
2988 params: Default::default(),
2989 credential_ref: None,
2990 }),
2991 long_term: None,
2992 }),
2993 knowledge: None,
2994 conversational: false,
2995 opening_message: None,
2996 on_text_while_parked: Default::default(),
2997 };
2998 let mut provider = InMemoryConfigProvider::new();
2999 provider.insert(tenant, agent_id, cfg);
3000
3001 AgentRuntime::new(
3002 Arc::new(provider),
3003 Arc::new(MockAgentStateStore::new()),
3004 Arc::new(ExtensionRuntime::for_test().unwrap()),
3005 llm,
3006 Arc::new(MockTelemetry::new()),
3007 Arc::new(MockTokenMeter::new(0)),
3008 Arc::new(NoopToolLedger),
3009 None,
3010 )
3011 .with_short_term_memory(Arc::new(InMemoryMemoryProvider::new()))
3012 }
3013
3014 #[tokio::test]
3015 async fn run_agent_step_with_audit_sink_enqueues_events_under_real_tenant_not_state_tenant()
3016 {
3017 let state_tenant = TenantContext::new("graph", "run");
3020 let agent_id = "graph.agent-1";
3021 let session_id = "graph__agent-1";
3022 let runtime = agent_runtime_with_scripted_remember_call(&state_tenant, agent_id);
3023
3024 let (tx, mut rx) = tokio::sync::mpsc::channel(16);
3025 let sink = AuditSink::from_sender(tx);
3026 let real_tenant = real_tenant_ctx("acme", "prod");
3027
3028 let input = AgentInput {
3029 text: String::new(),
3030 ..Default::default()
3031 };
3032 let out = run_agent_step(
3033 &runtime,
3034 state_tenant.clone(),
3035 session_id,
3036 agent_id,
3037 input,
3038 Some(&sink),
3039 &real_tenant,
3040 )
3041 .await
3042 .expect("step should succeed");
3043 assert_eq!(out.reply, "done");
3044
3045 let (subject, bytes) = rx.try_recv().expect("tool_call audit event enqueued");
3046 assert_eq!(
3047 subject, "audit.acme.agent.tool_call",
3048 "audit subject must carry the REAL tenant (\"acme\"), not the synthetic state tenant (\"graph\")"
3049 );
3050 let value: Value = serde_json::from_slice(&bytes).expect("valid JSON");
3051 assert_eq!(value["payload"]["tool"], json!("remember"));
3052 assert_eq!(value["payload"]["agent_id"], json!(agent_id));
3053
3054 let (subject, bytes) = rx.try_recv().expect("tool_result audit event enqueued");
3055 assert_eq!(subject, "audit.acme.agent.tool_result");
3056 let value: Value = serde_json::from_slice(&bytes).expect("valid JSON");
3057 assert_eq!(value["payload"]["tool"], json!("remember"));
3058
3059 assert!(
3060 rx.try_recv().is_err(),
3061 "exactly two audit events enqueued (one tool_call, one tool_result)"
3062 );
3063 }
3064
3065 #[tokio::test]
3066 async fn run_agent_step_without_audit_sink_uses_plain_step_path_unchanged() {
3067 let state_tenant = TenantContext::new("graph", "run");
3073 let agent_id = "graph.agent-1";
3074 let session_id = "graph__agent-1";
3075 let runtime = agent_runtime_with_scripted_remember_call(&state_tenant, agent_id);
3076 let real_tenant = real_tenant_ctx("acme", "prod");
3077
3078 let input = AgentInput {
3079 text: String::new(),
3080 ..Default::default()
3081 };
3082 let out = run_agent_step(
3083 &runtime,
3084 state_tenant.clone(),
3085 session_id,
3086 agent_id,
3087 input,
3088 None,
3089 &real_tenant,
3090 )
3091 .await
3092 .expect("step should succeed");
3093
3094 assert_eq!(out.reply, "done");
3095 }
3096
3097 fn plain_reply_llm(reply: &str) -> Arc<dyn LlmBackend> {
3102 use greentic_aw_runtime::llm::LlmResponse;
3103 use greentic_aw_runtime::mock::MockLlmBackend;
3104
3105 Arc::new(MockLlmBackend::new(vec![Ok(LlmResponse {
3106 content: Some(reply.to_string()),
3107 tool_calls: vec![],
3108 tokens_in: 1,
3109 tokens_out: 1,
3110 })]))
3111 }
3112
3113 fn agent_turn_request(node_id: &str, system_prompt: &str) -> AgentTurnRequest {
3114 AgentTurnRequest {
3115 node_id: node_id.to_string(),
3116 system_prompt: system_prompt.to_string(),
3117 model: "gpt-4o-mini".to_string(),
3118 state: GraphRunState::default(),
3119 provider: None,
3120 tools: vec![],
3121 agent_ref: None,
3122 inherit_from: None,
3123 }
3124 }
3125
3126 type AgentTurnEffects = (
3129 Arc<dyn AgentStateStore>,
3130 Arc<ExtensionRuntime>,
3131 Arc<dyn Telemetry>,
3132 Arc<dyn TokenMeter>,
3133 Arc<dyn ToolLedger>,
3134 );
3135
3136 fn agent_turn_effects() -> AgentTurnEffects {
3137 use greentic_aw_runtime::cost::MockTokenMeter;
3138 use greentic_aw_runtime::mock::{MockTelemetry, NoopToolLedger};
3139
3140 (
3141 Arc::new(MockAgentStateStore::new()),
3142 Arc::new(ExtensionRuntime::for_test().unwrap()),
3143 Arc::new(MockTelemetry::new()),
3144 Arc::new(MockTokenMeter::new(0)),
3145 Arc::new(NoopToolLedger),
3146 )
3147 }
3148
3149 #[tokio::test]
3150 async fn run_one_agent_turn_without_audit_sink_completes_unchanged() {
3151 let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
3152 let real_tenant = real_tenant_ctx("acme", "prod");
3153
3154 let result = run_one_agent_turn(
3155 agent_turn_request("agent", "You triage."),
3156 state_store,
3157 ext_runtime,
3158 plain_reply_llm("all good [[RESOLVED]]"),
3159 telemetry,
3160 token_meter,
3161 ledger,
3162 None,
3163 None,
3164 Arc::new(vec![]),
3165 Arc::new(HashMap::new()),
3166 None,
3167 &real_tenant,
3168 &crate::runner::knowledge_index::IndexMount::default(),
3169 &TurnBilling::default(),
3170 )
3171 .await
3172 .expect("turn should succeed");
3173
3174 assert!(result.resolved);
3175 assert_eq!(result.reply, "all good");
3176 }
3177
3178 #[tokio::test]
3179 async fn run_one_agent_turn_with_audit_sink_completes_same_reply_as_without() {
3180 let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
3187 let (tx, mut rx) = tokio::sync::mpsc::channel(16);
3188 let sink = AuditSink::from_sender(tx);
3189 let real_tenant = real_tenant_ctx("acme", "prod");
3190
3191 let result = run_one_agent_turn(
3192 agent_turn_request("agent", "You triage."),
3193 state_store,
3194 ext_runtime,
3195 plain_reply_llm("all good [[RESOLVED]]"),
3196 telemetry,
3197 token_meter,
3198 ledger,
3199 None,
3200 None,
3201 Arc::new(vec![]),
3202 Arc::new(HashMap::new()),
3203 Some(&sink),
3204 &real_tenant,
3205 &crate::runner::knowledge_index::IndexMount::default(),
3206 &TurnBilling::default(),
3207 )
3208 .await
3209 .expect("turn should succeed");
3210
3211 assert!(result.resolved);
3212 assert_eq!(result.reply, "all good");
3213 assert!(
3214 rx.try_recv().is_err(),
3215 "no tool call happens on this path, so no audit event is expected"
3216 );
3217 }
3218
3219 #[tokio::test]
3228 async fn run_one_agent_turn_with_declared_tools_still_completes() {
3229 let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
3230 let real_tenant = real_tenant_ctx("acme", "prod");
3231
3232 let mut req = agent_turn_request("agent", "You triage.");
3233 req.tools = vec!["myext/dothing".to_string()];
3234
3235 let result = run_one_agent_turn(
3236 req,
3237 state_store,
3238 ext_runtime,
3239 plain_reply_llm("all good [[RESOLVED]]"),
3240 telemetry,
3241 token_meter,
3242 ledger,
3243 None,
3244 None,
3245 Arc::new(vec![]),
3246 Arc::new(HashMap::new()),
3247 None,
3248 &real_tenant,
3249 &crate::runner::knowledge_index::IndexMount::default(),
3250 &TurnBilling::default(),
3251 )
3252 .await
3253 .expect("turn should succeed even with a declared-but-unregistered tool");
3254
3255 assert!(result.resolved);
3256 assert_eq!(result.reply, "all good");
3257 }
3258
3259 fn faq_bot_agent_config() -> AgentConfig {
3267 use greentic_aw_runtime::config::KnowledgeSettings;
3268 use greentic_aw_runtime::{MemoryProviderRef, MemorySettings};
3269
3270 AgentConfig {
3271 agent_id: "faq".to_string(),
3272 system_prompt: "You are FAQ-BOT. Answer only from the knowledge base.".to_string(),
3273 tools: vec![],
3274 guardrails: vec![],
3275 llm: LlmProviderRef {
3276 provider: "openai".to_string(),
3277 model: "gpt-4o-mini".to_string(),
3278 credential_ref: None,
3279 },
3280 limits: AgentLimits::default(),
3281 memory: Some(MemorySettings {
3282 short_term: Some(MemoryProviderRef {
3283 provider: "inmemory".to_string(),
3284 capability: "cap://memory/short-term".to_string(),
3285 params: Default::default(),
3286 credential_ref: None,
3287 }),
3288 long_term: None,
3289 }),
3290 knowledge: Some(KnowledgeSettings {
3291 knowledge: Some(MemoryProviderRef {
3292 provider: "chronicle".to_string(),
3293 capability: "cap://dw.knowledge".to_string(),
3294 params: Default::default(),
3295 credential_ref: None,
3296 }),
3297 embedding: None,
3298 top_k: 5,
3299 }),
3300 conversational: false,
3301 opening_message: None,
3302 on_text_while_parked: Default::default(),
3303 }
3304 }
3305
3306 fn recording_llm(reply: &str) -> Arc<greentic_aw_runtime::mock::MockLlmBackend> {
3311 use greentic_aw_runtime::llm::LlmResponse;
3312 use greentic_aw_runtime::mock::MockLlmBackend;
3313
3314 Arc::new(MockLlmBackend::new(vec![Ok(LlmResponse {
3315 content: Some(reply.to_string()),
3316 tool_calls: vec![],
3317 tokens_in: 1,
3318 tokens_out: 1,
3319 })]))
3320 }
3321
3322 #[test]
3323 fn resolve_turn_config_agent_ref_present_returns_full_config_from_map() {
3324 let mut merged = HashMap::new();
3325 merged.insert("faq".to_string(), faq_bot_agent_config());
3326
3327 let mut req = agent_turn_request("s", "inline prompt, should be ignored");
3328 req.agent_ref = Some("faq".to_string());
3329
3330 let cfg = resolve_turn_config(&req, &merged, "graph.s").expect("resolves");
3331
3332 assert!(cfg.system_prompt.contains("FAQ-BOT"));
3333 assert!(cfg.memory.is_some(), "memory carried through unstripped");
3334 assert!(
3335 cfg.knowledge.is_some(),
3336 "knowledge carried through unstripped"
3337 );
3338 }
3339
3340 #[test]
3341 fn resolve_turn_config_agent_ref_none_returns_stripped_inline_config() {
3342 let merged = HashMap::new();
3343 let req = agent_turn_request("s", "You triage.");
3344
3345 let cfg = resolve_turn_config(&req, &merged, "graph.s").expect("resolves");
3346
3347 assert_eq!(cfg.system_prompt, "You triage.");
3348 assert_eq!(cfg.agent_id, "graph.s");
3349 assert!(cfg.memory.is_none());
3350 assert!(cfg.knowledge.is_none());
3351 assert!(cfg.guardrails.is_empty());
3352 }
3353
3354 #[test]
3355 fn resolve_turn_config_agent_ref_missing_returns_err() {
3356 let merged = HashMap::new();
3357 let mut req = agent_turn_request("s", "inline prompt");
3358 req.agent_ref = Some("missing".to_string());
3359
3360 let err = resolve_turn_config(&req, &merged, "graph.s").expect_err("must error");
3361
3362 assert!(
3363 err.to_string()
3364 .contains("referenced agent 'missing' not found"),
3365 "unexpected error message: {err}"
3366 );
3367 }
3368
3369 #[tokio::test]
3370 async fn run_one_agent_turn_with_agent_ref_uses_referenced_config_system_prompt() {
3371 let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
3372 let real_tenant = real_tenant_ctx("acme", "prod");
3373
3374 let mut merged = HashMap::new();
3375 merged.insert("faq".to_string(), faq_bot_agent_config());
3376
3377 let mut req = agent_turn_request("s", "inline prompt, should NOT be used");
3378 req.agent_ref = Some("faq".to_string());
3379
3380 let llm = recording_llm("all good [[RESOLVED]]");
3381
3382 let result = run_one_agent_turn(
3383 req,
3384 state_store,
3385 ext_runtime,
3386 llm.clone(),
3387 telemetry,
3388 token_meter,
3389 ledger,
3390 None,
3391 None,
3392 Arc::new(vec![]),
3393 Arc::new(merged),
3394 None,
3395 &real_tenant,
3396 &crate::runner::knowledge_index::IndexMount::default(),
3397 &TurnBilling::default(),
3398 )
3399 .await
3400 .expect("turn should succeed");
3401
3402 assert!(result.resolved);
3403 assert_eq!(result.reply, "all good");
3404
3405 let seen = llm.seen_system_prompts.lock().expect("lock poisoned");
3406 assert_eq!(seen.len(), 1);
3407 assert!(
3408 seen[0].contains("FAQ-BOT"),
3409 "expected the referenced agent's system prompt, got: {}",
3410 seen[0]
3411 );
3412 assert!(
3413 !seen[0].contains("should NOT be used"),
3414 "the node's inline system prompt must not be used when agent_ref is set"
3415 );
3416 }
3417
3418 #[tokio::test]
3419 async fn run_one_agent_turn_without_agent_ref_uses_inline_system_prompt() {
3420 let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
3424 let real_tenant = real_tenant_ctx("acme", "prod");
3425
3426 let mut merged = HashMap::new();
3427 merged.insert("faq".to_string(), faq_bot_agent_config());
3428
3429 let req = agent_turn_request("s", "You triage inline.");
3430 let llm = recording_llm("all good [[RESOLVED]]");
3431
3432 let result = run_one_agent_turn(
3433 req,
3434 state_store,
3435 ext_runtime,
3436 llm.clone(),
3437 telemetry,
3438 token_meter,
3439 ledger,
3440 None,
3441 None,
3442 Arc::new(vec![]),
3443 Arc::new(merged),
3444 None,
3445 &real_tenant,
3446 &crate::runner::knowledge_index::IndexMount::default(),
3447 &TurnBilling::default(),
3448 )
3449 .await
3450 .expect("turn should succeed");
3451
3452 assert!(result.resolved);
3453
3454 let seen = llm.seen_system_prompts.lock().expect("lock poisoned");
3455 assert_eq!(seen.len(), 1);
3456 assert!(seen[0].contains("You triage inline."));
3457 assert!(!seen[0].contains("FAQ-BOT"));
3458 }
3459
3460 #[tokio::test]
3461 async fn run_one_agent_turn_with_missing_agent_ref_errors() {
3462 let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
3463 let real_tenant = real_tenant_ctx("acme", "prod");
3464
3465 let mut req = agent_turn_request("s", "inline prompt");
3466 req.agent_ref = Some("missing".to_string());
3467
3468 let err = run_one_agent_turn(
3469 req,
3470 state_store,
3471 ext_runtime,
3472 plain_reply_llm("unused"),
3473 telemetry,
3474 token_meter,
3475 ledger,
3476 None,
3477 None,
3478 Arc::new(vec![]),
3479 Arc::new(HashMap::new()),
3480 None,
3481 &real_tenant,
3482 &crate::runner::knowledge_index::IndexMount::default(),
3483 &TurnBilling::default(),
3484 )
3485 .await
3486 .expect_err("must error when agent_ref doesn't resolve");
3487
3488 assert!(
3489 err.to_string()
3490 .contains("referenced agent 'missing' not found"),
3491 "unexpected error message: {err}"
3492 );
3493 }
3494
3495 #[test]
3500 fn inherit_from_keeps_the_node_prompt_and_adopts_the_capability_surface() {
3501 use greentic_aw_runtime::config::GuardrailRef;
3502
3503 let mut parent = faq_bot_agent_config();
3504 parent.guardrails = vec![GuardrailRef {
3505 cap_id: "greentic:guardrail/pii".to_string(),
3506 offer_id: None,
3507 config: serde_json::json!({}),
3508 mode: Default::default(),
3509 }];
3510 let mut merged = HashMap::new();
3511 merged.insert("faq".to_string(), parent);
3512
3513 let mut req = agent_turn_request("spec-billing", "You handle billing only.");
3514 req.inherit_from = Some("faq".to_string());
3515
3516 let cfg = resolve_turn_config(&req, &merged, "graph.spec-billing")
3517 .expect("a resolvable inherit_from must succeed");
3518
3519 assert_eq!(
3520 cfg.system_prompt, "You handle billing only.",
3521 "the specialist keeps its OWN prompt — this is the whole point"
3522 );
3523 assert_eq!(cfg.guardrails.len(), 1, "guardrails are inherited");
3524 assert!(cfg.memory.is_some(), "memory is inherited");
3525 assert!(cfg.knowledge.is_some(), "knowledge is inherited");
3526 }
3527
3528 #[test]
3530 fn inherit_from_unresolvable_fails_rather_than_running_stripped() {
3531 let merged = HashMap::new();
3532 let mut req = agent_turn_request("spec", "Specialist prompt.");
3533 req.inherit_from = Some("ghost".to_string());
3534
3535 let err = resolve_turn_config(&req, &merged, "graph.spec")
3536 .expect_err("an unknown inherit_from must not silently succeed");
3537 let msg = err.to_string();
3538 assert!(
3539 msg.contains("ghost") && msg.contains("refusing to run"),
3540 "error should name the id and say it refused: {msg}"
3541 );
3542 }
3543
3544 #[test]
3547 fn agent_ref_takes_precedence_over_inherit_from() {
3548 let mut merged = HashMap::new();
3549 merged.insert("faq".to_string(), faq_bot_agent_config());
3550
3551 let mut req = agent_turn_request("spec", "Specialist prompt.");
3552 req.agent_ref = Some("faq".to_string());
3553 req.inherit_from = Some("faq".to_string());
3554
3555 let cfg = resolve_turn_config(&req, &merged, "graph.spec").expect("resolvable");
3556 assert_eq!(
3557 cfg.system_prompt, "You are FAQ-BOT. Answer only from the knowledge base.",
3558 "agent_ref adopts the referenced prompt wholesale"
3559 );
3560 }
3561
3562 #[test]
3565 fn supervisor_without_agent_ref_resolves_no_guardrails() {
3566 let merged = HashMap::new();
3567 let got = resolve_supervisor_guardrails(None, &merged, "router")
3568 .expect("absent agent_ref is not an error");
3569 assert!(got.is_empty());
3570 }
3571
3572 #[test]
3575 fn supervisor_with_agent_ref_inherits_the_parent_guardrails() {
3576 use greentic_aw_runtime::config::GuardrailRef;
3577
3578 let mut parent = faq_bot_agent_config();
3579 parent.guardrails = vec![GuardrailRef {
3580 cap_id: "greentic:guardrail/pii".to_string(),
3581 offer_id: None,
3582 config: serde_json::json!({}),
3583 mode: Default::default(),
3584 }];
3585 let mut merged = HashMap::new();
3586 merged.insert("faq".to_string(), parent);
3587
3588 let got = resolve_supervisor_guardrails(Some("faq"), &merged, "router")
3589 .expect("a resolvable agent_ref must succeed");
3590 assert_eq!(got.len(), 1);
3591 assert_eq!(got[0].cap_id, "greentic:guardrail/pii");
3592 }
3593
3594 #[test]
3598 fn supervisor_with_unresolvable_agent_ref_fails_rather_than_routing_bare() {
3599 let merged = HashMap::new();
3600 let err = resolve_supervisor_guardrails(Some("ghost"), &merged, "router")
3601 .expect_err("an unknown agent_ref must not silently succeed");
3602 let msg = err.to_string();
3603 assert!(
3604 msg.contains("ghost") && msg.contains("refusing to route"),
3605 "error should name the id and say it refused: {msg}"
3606 );
3607 }
3608
3609 #[test]
3613 fn supervisor_inherits_guardrails_but_not_memory_or_knowledge() {
3614 use greentic_aw_runtime::config::GuardrailRef;
3615
3616 let mut parent = faq_bot_agent_config();
3617 parent.guardrails = vec![GuardrailRef {
3618 cap_id: "greentic:guardrail/pii".to_string(),
3619 offer_id: None,
3620 config: serde_json::json!({}),
3621 mode: Default::default(),
3622 }];
3623 assert!(parent.memory.is_some(), "fixture should carry memory");
3624 assert!(parent.knowledge.is_some(), "fixture should carry knowledge");
3625
3626 let mut merged = HashMap::new();
3627 merged.insert("faq".to_string(), parent);
3628
3629 let got =
3630 resolve_supervisor_guardrails(Some("faq"), &merged, "router").expect("resolvable");
3631 assert_eq!(got.len(), 1, "guardrails come across");
3632 }
3633
3634 #[tokio::test]
3635 async fn run_one_supervisor_turn_without_audit_sink_completes_unchanged() {
3636 let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
3637 let real_tenant = real_tenant_ctx("acme", "prod");
3638 let routes = vec![
3639 SupervisorRoute {
3640 branch: "billing".into(),
3641 description: "Billing questions".into(),
3642 },
3643 SupervisorRoute {
3644 branch: "tech".into(),
3645 description: "Technical support".into(),
3646 },
3647 ];
3648 let req = SupervisorRequest {
3649 node_id: "router".to_string(),
3650 system_prompt: "Route the user.".to_string(),
3651 model: "gpt-4o-mini".to_string(),
3652 routes,
3653 state: GraphRunState::default(),
3654 provider: None,
3655 agent_ref: None,
3656 };
3657
3658 let result = run_one_supervisor_turn(
3661 req,
3662 state_store,
3663 ext_runtime,
3664 plain_reply_llm("I'm not sure, let me think."),
3665 telemetry,
3666 token_meter,
3667 ledger,
3668 Arc::new(HashMap::new()),
3669 None,
3670 &real_tenant,
3671 &TurnBilling::default(),
3672 )
3673 .await
3674 .expect("supervisor turn should succeed");
3675
3676 assert_eq!(result.branch, "billing");
3677 }
3678
3679 #[tokio::test]
3680 async fn run_one_supervisor_turn_with_audit_sink_completes_same_branch_as_without() {
3681 let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
3682 let (tx, mut rx) = tokio::sync::mpsc::channel(16);
3683 let sink = AuditSink::from_sender(tx);
3684 let real_tenant = real_tenant_ctx("acme", "prod");
3685 let routes = vec![
3686 SupervisorRoute {
3687 branch: "billing".into(),
3688 description: "Billing questions".into(),
3689 },
3690 SupervisorRoute {
3691 branch: "tech".into(),
3692 description: "Technical support".into(),
3693 },
3694 ];
3695 let req = SupervisorRequest {
3696 node_id: "router".to_string(),
3697 system_prompt: "Route the user.".to_string(),
3698 model: "gpt-4o-mini".to_string(),
3699 routes,
3700 state: GraphRunState::default(),
3701 provider: None,
3702 agent_ref: None,
3703 };
3704
3705 let result = run_one_supervisor_turn(
3706 req,
3707 state_store,
3708 ext_runtime,
3709 plain_reply_llm("I'm not sure, let me think."),
3710 telemetry,
3711 token_meter,
3712 ledger,
3713 Arc::new(HashMap::new()),
3714 Some(&sink),
3715 &real_tenant,
3716 &TurnBilling::default(),
3717 )
3718 .await
3719 .expect("supervisor turn should succeed");
3720
3721 assert_eq!(result.branch, "billing");
3722 assert!(
3723 rx.try_recv().is_err(),
3724 "no tool call happens on this path, so no audit event is expected"
3725 );
3726 }
3727
3728 type GraphEmit = (String, String, Option<String>, String, String);
3734
3735 #[derive(Default)]
3736 struct RecordingGraphMeter {
3737 calls: std::sync::Mutex<Vec<GraphEmit>>,
3738 }
3739
3740 impl greentic_aw_runtime::billing::BillingMeter for RecordingGraphMeter {
3741 fn emit<'a>(
3742 &'a self,
3743 tenant: &'a TenantContext,
3744 _input_tokens: u64,
3745 _output_tokens: u64,
3746 agent_id: &'a str,
3747 model: &'a str,
3748 ) -> std::pin::Pin<
3749 Box<
3750 dyn std::future::Future<
3751 Output = Result<(), greentic_aw_runtime::billing::BillingError>,
3752 > + Send
3753 + 'a,
3754 >,
3755 > {
3756 self.calls.lock().expect("lock").push((
3757 tenant.tenant_id.clone(),
3758 tenant.env_id.clone(),
3759 tenant.project_id.clone(),
3760 agent_id.to_string(),
3761 model.to_string(),
3762 ));
3763 Box::pin(async { Ok(()) })
3764 }
3765
3766 fn over_budget<'a>(
3767 &'a self,
3768 _tenant: &'a TenantContext,
3769 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = bool> + Send + 'a>>
3770 {
3771 Box::pin(std::future::ready(false))
3772 }
3773 }
3774
3775 fn unit_billing(meter: &Arc<RecordingGraphMeter>) -> TurnBilling {
3776 TurnBilling {
3777 meter: Some(
3778 Arc::clone(meter) as Arc<dyn greentic_aw_runtime::billing::BillingMeter>
3779 ),
3780 project_id: Some("support-bot".to_string()),
3781 state_scope: None,
3782 }
3783 }
3784
3785 #[test]
3788 fn per_visit_session_ids_are_scoped_to_session_and_graph() {
3789 let scoped = |session: &str, graph: &str| TurnBilling {
3790 state_scope: Some(format!("{session}__{graph}")),
3791 ..TurnBilling::default()
3792 };
3793 let a = scoped("sess-a", "triage").scoped_session("graph__n1");
3794 let b = scoped("sess-b", "triage").scoped_session("graph__n1");
3795 let c = scoped("sess-a", "other").scoped_session("graph__n1");
3796 assert_ne!(a, b);
3797 assert_ne!(a, c);
3798 assert_eq!(a, "sess-a__triage__graph__n1");
3799 assert_eq!(
3800 TurnBilling::default().scoped_session("graph__n1"),
3801 "graph__n1"
3802 );
3803 }
3804
3805 #[tokio::test]
3810 async fn a_graph_agent_turn_bills_the_real_tenant_and_the_unit() {
3811 let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
3812 let real_tenant = real_tenant_ctx("acme", "prod");
3813 let meter = Arc::new(RecordingGraphMeter::default());
3814
3815 run_one_agent_turn(
3816 agent_turn_request("triage", "You triage."),
3817 state_store,
3818 ext_runtime,
3819 plain_reply_llm("routed [[RESOLVED]]"),
3820 telemetry,
3821 token_meter,
3822 ledger,
3823 None,
3824 None,
3825 Arc::new(vec![]),
3826 Arc::new(HashMap::new()),
3827 None,
3828 &real_tenant,
3829 &crate::runner::knowledge_index::IndexMount::default(),
3830 &unit_billing(&meter),
3831 )
3832 .await
3833 .expect("turn succeeds");
3834
3835 let calls = meter.calls.lock().expect("lock");
3836 assert_eq!(calls.len(), 1, "one LLM iteration → one billing emit");
3837 assert_eq!(
3838 calls[0],
3839 (
3840 "acme".to_string(),
3841 "prod".to_string(),
3842 Some("support-bot".to_string()),
3843 "graph.triage".to_string(),
3844 "gpt-4o-mini".to_string(),
3845 )
3846 );
3847 }
3848
3849 #[tokio::test]
3851 async fn a_supervisor_routing_turn_is_billed() {
3852 let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
3853 let real_tenant = real_tenant_ctx("acme", "prod");
3854 let meter = Arc::new(RecordingGraphMeter::default());
3855 let req = SupervisorRequest {
3856 node_id: "router".to_string(),
3857 system_prompt: "Route the user.".to_string(),
3858 model: "claude-3-haiku".to_string(),
3859 routes: vec![SupervisorRoute {
3860 branch: "billing".into(),
3861 description: "Billing questions".into(),
3862 }],
3863 state: GraphRunState::default(),
3864 provider: None,
3865 agent_ref: None,
3866 };
3867
3868 run_one_supervisor_turn(
3869 req,
3870 state_store,
3871 ext_runtime,
3872 plain_reply_llm("[[ROUTE:billing]]"),
3873 telemetry,
3874 token_meter,
3875 ledger,
3876 Arc::new(HashMap::new()),
3877 None,
3878 &real_tenant,
3879 &unit_billing(&meter),
3880 )
3881 .await
3882 .expect("supervisor turn succeeds");
3883
3884 let calls = meter.calls.lock().expect("lock");
3885 assert_eq!(calls.len(), 1);
3886 assert_eq!(calls[0].0, "acme");
3887 assert_eq!(calls[0].1, "prod");
3888 assert_eq!(calls[0].2.as_deref(), Some("support-bot"));
3889 assert_eq!(calls[0].3, "graph.router.supervisor");
3890 assert_eq!(calls[0].4, "claude-3-haiku");
3891 }
3892
3893 #[tokio::test]
3896 async fn a_graph_turn_without_a_sink_still_runs() {
3897 let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
3898 let real_tenant = real_tenant_ctx("acme", "prod");
3899 let result = run_one_agent_turn(
3900 agent_turn_request("triage", "You triage."),
3901 state_store,
3902 ext_runtime,
3903 plain_reply_llm("hello"),
3904 telemetry,
3905 token_meter,
3906 ledger,
3907 None,
3908 None,
3909 Arc::new(vec![]),
3910 Arc::new(HashMap::new()),
3911 None,
3912 &real_tenant,
3913 &crate::runner::knowledge_index::IndexMount::default(),
3914 &TurnBilling::default(),
3915 )
3916 .await
3917 .expect("turn succeeds with no sink");
3918 assert_eq!(result.reply, "hello");
3919 }
3920
3921 #[test]
3922 fn with_billing_sets_the_sink_and_unit_on_the_handler() {
3923 let handler = handler_with(
3924 Arc::new(InMemoryGraphProvider::new(HashMap::new())),
3925 agent_fn_resolves_on(Arc::new(AtomicU32::new(0)), 1),
3926 tool_fn_ok(),
3927 );
3928 assert!(handler.billing.meter.is_none());
3929 let meter = Arc::new(RecordingGraphMeter::default());
3930 let handler = handler.with_billing(
3931 Some(meter as Arc<dyn greentic_aw_runtime::billing::BillingMeter>),
3932 Some("support-bot".to_string()),
3933 );
3934 assert!(handler.billing.meter.is_some());
3935 assert_eq!(handler.billing.project_id.as_deref(), Some("support-bot"));
3936 }
3937 }
3938
3939 #[cfg(all(test, feature = "agentic-worker"))]
3944 #[allow(clippy::unwrap_used, clippy::expect_used)]
3945 mod a2a_tests {
3946 use std::collections::HashMap;
3947 use std::future::Future;
3948 use std::pin::Pin;
3949 use std::sync::{Arc, Mutex};
3950
3951 use greentic_aw_runtime::cost::MockTokenMeter;
3952 use greentic_aw_runtime::error::LlmError;
3953 use greentic_aw_runtime::graph::{AgentTurnRequest, GraphRunState, ToolCallRequest};
3954 use greentic_aw_runtime::llm::{LlmBackend, LlmRequest, LlmResponse};
3955 use greentic_aw_runtime::mock::{MockAgentStateStore, MockTelemetry, NoopToolLedger};
3956 use greentic_aw_runtime::state::ToolCallRecord;
3957 use greentic_aw_runtime::{AgentConfig, AgentLimits, LlmProviderRef, ToolRef};
3958 use greentic_ext_runtime::ExtensionRuntime;
3959 use serde_json::json;
3960 use wiremock::matchers::{method, path};
3961 use wiremock::{Mock, MockServer, ResponseTemplate};
3962
3963 use super::{RuntimeTurnSource, TurnEffectSource, build_tool, graph_a2a_source};
3964
3965 const AGENT_ID: &str = "8d2f0c1e-recipe";
3967 const TENANT: &str = "acme";
3968 const UNIT: &str = "unit-1";
3969
3970 async fn serve_agent(server: &MockServer, reply: &str) {
3971 let card = json!({
3972 "name": "Recipe Agent",
3973 "description": "Suggests dishes.",
3974 "version": "1.0.0",
3975 "supportedInterfaces": [{
3976 "url": format!("{}/a2a", server.uri()),
3977 "protocolBinding": "JSONRPC",
3978 "protocolVersion": "1.0"
3979 }],
3980 "capabilities": {"streaming": false, "pushNotifications": false},
3981 "defaultInputModes": ["text/plain"],
3982 "defaultOutputModes": ["text/plain"],
3983 "skills": []
3984 });
3985 Mock::given(method("GET"))
3986 .and(path("/.well-known/agent-card.json"))
3987 .respond_with(ResponseTemplate::new(200).set_body_json(card))
3988 .mount(server)
3989 .await;
3990 Mock::given(method("POST"))
3991 .and(path("/a2a"))
3992 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
3993 "jsonrpc": "2.0", "id": 1,
3994 "result": {"message": {"messageId": "m-2", "role": "ROLE_AGENT",
3995 "parts": [{"text": reply}]}}
3996 })))
3997 .mount(server)
3998 .await;
3999 }
4000
4001 fn pack_for(server: &MockServer) -> (tempfile::TempDir, Arc<crate::pack::PackRuntime>) {
4004 let dir = tempfile::tempdir().unwrap();
4005 std::fs::create_dir_all(dir.path().join("assets")).unwrap();
4006 let sidecar = json!([{
4007 "agent_id": AGENT_ID,
4008 "name": "Recipe agent",
4009 "base_url": server.uri(),
4010 "auth_header_name": null,
4011 "auth_team": "sales",
4012 "requires_auth": true
4013 }]);
4014 std::fs::write(
4015 dir.path().join("assets/a2a-routes.json"),
4016 sidecar.to_string(),
4017 )
4018 .unwrap();
4019 let pack = Arc::new(crate::pack::tests::pack_runtime_for_dir(dir.path()));
4020 (dir, pack)
4021 }
4022
4023 struct MapSecrets(HashMap<String, Vec<u8>>);
4024
4025 #[async_trait::async_trait]
4026 impl greentic_secrets_lib::SecretsManager for MapSecrets {
4027 async fn read(&self, path: &str) -> greentic_secrets_lib::Result<Vec<u8>> {
4028 self.0
4029 .get(path)
4030 .cloned()
4031 .ok_or_else(|| greentic_secrets_lib::SecretError::NotFound(path.to_string()))
4032 }
4033 async fn write(&self, _: &str, _: &[u8]) -> greentic_secrets_lib::Result<()> {
4034 Ok(())
4035 }
4036 async fn delete(&self, _: &str) -> greentic_secrets_lib::Result<()> {
4037 Ok(())
4038 }
4039 }
4040
4041 fn unit_scoped_store() -> crate::secrets::DynSecretsManager {
4045 let uri = greentic_aw_runtime::scoped_secrets::secret_uri_candidates(
4046 "a2a",
4047 TENANT,
4048 Some("sales"),
4049 Some(UNIT),
4050 AGENT_ID,
4051 )
4052 .unwrap()
4053 .remove(0);
4054 assert!(uri.contains(".unit-"), "first candidate is the unit scope");
4055 Arc::new(MapSecrets(HashMap::from([(uri, b"tok-1".to_vec())])))
4056 }
4057
4058 #[allow(unsafe_code)]
4059 fn set_gate(value: Option<&str>) {
4060 unsafe {
4062 match value {
4063 Some(v) => std::env::set_var("GREENTIC_AW_A2A", v),
4064 None => std::env::remove_var("GREENTIC_AW_A2A"),
4065 }
4066 }
4067 }
4068
4069 struct RecordingLlm {
4072 responses: Mutex<Vec<LlmResponse>>,
4073 offered: Mutex<Vec<Vec<(String, String)>>>,
4074 }
4075
4076 impl LlmBackend for RecordingLlm {
4077 fn complete<'a>(
4078 &'a self,
4079 req: LlmRequest,
4080 ) -> Pin<Box<dyn Future<Output = Result<LlmResponse, LlmError>> + Send + 'a>>
4081 {
4082 self.offered.lock().unwrap().push(
4083 req.tools
4084 .iter()
4085 .map(|t| (t.extension_id.clone(), t.tool_name.clone()))
4086 .collect(),
4087 );
4088 let next = {
4089 let mut queue = self.responses.lock().unwrap();
4090 if queue.is_empty() {
4091 Err(LlmError::Transport("script exhausted".into()))
4092 } else {
4093 Ok(queue.remove(0))
4094 }
4095 };
4096 Box::pin(async move { next })
4097 }
4098 }
4099
4100 fn tool_ref() -> String {
4101 format!("a2a:{AGENT_ID}")
4102 }
4103
4104 fn worker_with_a2a_tool() -> AgentConfig {
4107 AgentConfig {
4108 agent_id: "worker".into(),
4109 system_prompt: "sys".into(),
4110 tools: vec![ToolRef {
4111 extension_id: tool_ref(),
4112 tool_name: "ask".into(),
4113 description: Some("Ask the Recipe agent agent.".into()),
4114 input_schema: Some(json!({
4115 "type": "object",
4116 "properties": {"message": {"type": "string"}},
4117 "required": ["message"]
4118 })),
4119 usage_note: None,
4120 }],
4121 llm: LlmProviderRef {
4122 provider: "mock".into(),
4123 model: "m".into(),
4124 credential_ref: None,
4125 },
4126 limits: AgentLimits::default(),
4127 memory: None,
4128 knowledge: None,
4129 guardrails: vec![],
4130 conversational: false,
4131 opening_message: None,
4132 on_text_while_parked: Default::default(),
4133 }
4134 }
4135
4136 async fn run_specialist_turn(
4141 a2a_source: Option<Arc<greentic_aw_runtime::A2aToolSource>>,
4142 calls_tool: bool,
4143 ) -> (String, Vec<(String, String)>) {
4144 let mut script = Vec::new();
4145 if calls_tool {
4146 script.push(LlmResponse {
4147 content: None,
4148 tool_calls: vec![ToolCallRecord {
4149 call_id: "c1".into(),
4150 extension_id: tool_ref(),
4151 tool_name: "ask".into(),
4152 args: json!({"message": "eggs?"}),
4153 }],
4154 tokens_in: 5,
4155 tokens_out: 5,
4156 });
4157 }
4158 script.push(LlmResponse {
4159 content: Some("Try an omelette. [[RESOLVED]]".into()),
4160 tool_calls: vec![],
4161 tokens_in: 5,
4162 tokens_out: 5,
4163 });
4164 let llm = Arc::new(RecordingLlm {
4165 responses: Mutex::new(script),
4166 offered: Mutex::new(Vec::new()),
4167 });
4168 let source = RuntimeTurnSource {
4169 state_store: Arc::new(MockAgentStateStore::new()),
4170 ext_runtime: Arc::new(ExtensionRuntime::for_test().unwrap()),
4171 llm: llm.clone(),
4172 telemetry: Arc::new(MockTelemetry::new()),
4173 token_meter: Arc::new(MockTokenMeter::new(0)),
4174 ledger: Arc::new(NoopToolLedger),
4175 mcp_source: None,
4176 a2a_source,
4177 packs: Arc::new(vec![]),
4178 merged_agents: Arc::new(HashMap::from([(
4179 "worker".to_string(),
4180 worker_with_a2a_tool(),
4181 )])),
4182 index_mount: crate::runner::knowledge_index::IndexMount::default(),
4183 };
4184 let real_tenant = greentic_types::TenantCtx::new(
4185 greentic_types::EnvId::try_from("prod").unwrap(),
4186 greentic_types::TenantId::try_from(TENANT).unwrap(),
4187 );
4188 let turn = source.agent_turn(None, real_tenant, super::TurnBilling::default());
4189 let result = turn(AgentTurnRequest {
4190 node_id: "specialist".into(),
4191 system_prompt: "You suggest recipes.".into(),
4192 model: "m".into(),
4193 state: GraphRunState::default(),
4194 provider: Some("mock".into()),
4195 tools: vec![],
4196 agent_ref: None,
4197 inherit_from: Some("worker".into()),
4198 })
4199 .await
4200 .expect("the turn completes");
4201 let offered = llm
4202 .offered
4203 .lock()
4204 .unwrap()
4205 .first()
4206 .cloned()
4207 .unwrap_or_default();
4208 (result.reply, offered)
4209 }
4210
4211 #[tokio::test]
4215 #[serial_test::serial]
4216 async fn a_graph_agent_turn_is_offered_and_calls_a_pack_carried_a2a_tool() {
4217 set_gate(None);
4218 let server = MockServer::start().await;
4219 serve_agent(&server, "an omelette").await;
4220 let (_dir, pack) = pack_for(&server);
4221 let source = graph_a2a_source(&[pack], TENANT, &unit_scoped_store(), Some(UNIT));
4222 assert!(source.is_some(), "the sidecar must yield a source");
4223
4224 let (reply, offered) = run_specialist_turn(source, true).await;
4225
4226 assert!(
4227 offered.contains(&(tool_ref(), "ask".to_string())),
4228 "the a2a tool must be offered to a graph agent turn; offered: {offered:?}"
4229 );
4230 assert_eq!(reply, "Try an omelette.");
4231 let requests = server.received_requests().await.unwrap();
4232 let post = requests
4233 .iter()
4234 .find(|r| r.method.as_str() == "POST")
4235 .expect("the agent must have been called");
4236 assert_eq!(
4237 post.headers
4238 .get("authorization")
4239 .and_then(|v| v.to_str().ok()),
4240 Some("Bearer tok-1"),
4241 "the credential is read at the unit scope the handler was built for"
4242 );
4243 }
4244
4245 #[tokio::test]
4248 #[serial_test::serial]
4249 async fn the_env_gate_disables_a2a_for_graph_turns() {
4250 let server = MockServer::start().await;
4251 serve_agent(&server, "unused").await;
4252 let (_dir, pack) = pack_for(&server);
4253 set_gate(Some("0"));
4254 let gated = graph_a2a_source(
4255 std::slice::from_ref(&pack),
4256 TENANT,
4257 &unit_scoped_store(),
4258 Some(UNIT),
4259 );
4260 set_gate(None);
4261 assert!(gated.is_none(), "the operator's kill switch must hold");
4262
4263 let (_, offered) = run_specialist_turn(gated, false).await;
4264 assert!(
4265 !offered.iter().any(|(ext, _)| ext.starts_with("a2a:")),
4266 "a disabled A2A source must offer no a2a: tool; offered: {offered:?}"
4267 );
4268 assert!(
4269 server.received_requests().await.unwrap().is_empty(),
4270 "a disabled source must never dial the agent"
4271 );
4272 assert!(
4273 graph_a2a_source(&[pack], TENANT, &unit_scoped_store(), Some(UNIT)).is_some(),
4274 "control: the same pack builds a source with the gate unset"
4275 );
4276 }
4277
4278 #[tokio::test]
4281 #[serial_test::serial]
4282 async fn a_graph_tool_node_dispatches_an_a2a_ref() {
4283 set_gate(None);
4284 let server = MockServer::start().await;
4285 serve_agent(&server, "an omelette").await;
4286 let (_dir, pack) = pack_for(&server);
4287 let source = graph_a2a_source(&[pack], TENANT, &unit_scoped_store(), Some(UNIT));
4288 let tool = build_tool(Arc::new(ExtensionRuntime::for_test().unwrap()), source);
4289
4290 let value = tool(ToolCallRequest {
4291 node_id: "lookup".into(),
4292 tool_name: format!("{}/ask", tool_ref()),
4293 state: GraphRunState::default(),
4294 })
4295 .await
4296 .expect("dispatch succeeds");
4297
4298 assert_eq!(
4299 value,
4300 json!({"status": "completed", "agent": AGENT_ID, "reply": "an omelette"})
4301 );
4302 let requests = server.received_requests().await.unwrap();
4303 let post = requests
4304 .iter()
4305 .find(|r| r.method.as_str() == "POST")
4306 .expect("the agent must have been called");
4307 assert_eq!(
4308 post.headers
4309 .get("authorization")
4310 .and_then(|v| v.to_str().ok()),
4311 Some("Bearer tok-1")
4312 );
4313 }
4314 }
4315}
4316
4317#[cfg(feature = "agentic-worker")]
4318pub use aw::{
4319 GraphConfigSource, InMemoryGraphProvider, LayeredGraphProvider, RuntimeGraphNodeHandler,
4320 build_graph_node_handler, graph_config_from_sidecar,
4321};
4322
4323#[cfg(feature = "agentic-worker")]
4324pub(crate) use aw::build_graph_node_handler_metered;