1use std::sync::Arc;
20use std::sync::Mutex;
21
22use aion_core::{
23 ActivityEvent, ActivityEventKind, ContentType, InterventionCapabilities, InterventionCommand,
24 InterventionKind, InterventionPrimitive, MessageRole, Payload, StopKind,
25};
26use aion_integrations::contract::{AgentHarness, AgentSession};
27use aion_integrations::error::HarnessError;
28use aion_integrations::spec::AgentRunSpec;
29use async_trait::async_trait;
30use chrono::Utc;
31use futures::stream::BoxStream;
32use tokio::sync::mpsc;
33use uuid::Uuid;
34
35pub type AppliedLog = Arc<Mutex<Vec<InterventionKind>>>;
37
38pub struct RunHandle {
46 keep_alive: mpsc::UnboundedSender<ActivityEvent>,
47}
48
49impl RunHandle {
50 pub fn end_run(self) {
52 drop(self.keep_alive);
53 }
54}
55
56#[derive(Clone)]
63pub struct MockAgentHarness {
64 applied: AppliedLog,
65 run_handle: Arc<Mutex<Option<RunHandle>>>,
66}
67
68impl Default for MockAgentHarness {
69 fn default() -> Self {
70 Self::new()
71 }
72}
73
74impl MockAgentHarness {
75 #[must_use]
77 pub fn new() -> Self {
78 Self {
79 applied: Arc::new(Mutex::new(Vec::new())),
80 run_handle: Arc::new(Mutex::new(None)),
81 }
82 }
83
84 #[must_use]
86 pub fn applied(&self) -> AppliedLog {
87 Arc::clone(&self.applied)
88 }
89
90 #[must_use]
96 pub fn take_run_handle(&self) -> Option<RunHandle> {
97 self.run_handle
98 .lock()
99 .ok()
100 .and_then(|mut guard| guard.take())
101 }
102
103 #[must_use]
107 pub fn advertised_capabilities() -> InterventionCapabilities {
108 InterventionCapabilities::from_primitives([
109 InterventionPrimitive::InjectMessage,
110 InterventionPrimitive::Cancel,
111 ])
112 }
113}
114
115pub struct MockAgentSession {
119 capabilities: InterventionCapabilities,
120 applied: AppliedLog,
121 events: Option<mpsc::UnboundedReceiver<ActivityEvent>>,
125 result: Payload,
126}
127
128#[async_trait]
129impl AgentHarness for MockAgentHarness {
130 type Session = MockAgentSession;
131
132 async fn start(&self, spec: AgentRunSpec) -> Result<Self::Session, HarnessError> {
133 let (tx, rx) = mpsc::unbounded_channel();
134 for event in fixed_transcript(&spec) {
137 let _ = tx.send(event);
138 }
139 if let Ok(mut guard) = self.run_handle.lock() {
140 *guard = Some(RunHandle { keep_alive: tx });
141 }
142 Ok(MockAgentSession {
143 capabilities: MockAgentHarness::advertised_capabilities(),
144 applied: Arc::clone(&self.applied),
145 events: Some(rx),
146 result: Payload::new(ContentType::Json, b"{\"result\":\"completed\"}".to_vec()),
147 })
148 }
149}
150
151fn fixed_transcript(spec: &AgentRunSpec) -> Vec<ActivityEvent> {
153 let base = ActivityEvent {
154 workflow_id: spec.workflow_id.clone(),
155 run_id: spec.run_id.clone(),
156 activity_id: spec.activity_id.clone(),
157 attempt: spec.attempt,
158 agent_id: Uuid::nil(),
159 agent_role: "mock".to_owned(),
160 emitted_at: Utc::now(),
161 worker_seq: 0,
162 store_seq: None,
163 ephemeral: false,
164 kind: ActivityEventKind::Message {
165 role: MessageRole::Assistant,
166 text: "working".to_owned(),
167 },
168 };
169 let stop = ActivityEvent {
170 worker_seq: 1,
171 kind: ActivityEventKind::Stop {
172 reason: StopKind::EndTurn,
173 },
174 ..base.clone()
175 };
176 vec![base, stop]
177}
178
179#[async_trait]
180impl AgentSession for MockAgentSession {
181 fn capabilities(&self) -> &InterventionCapabilities {
182 &self.capabilities
183 }
184
185 fn events(&mut self) -> BoxStream<'static, ActivityEvent> {
186 match self.events.take() {
187 Some(receiver) => Box::pin(tokio_stream::wrappers::UnboundedReceiverStream::new(
188 receiver,
189 )),
190 None => Box::pin(futures::stream::empty()),
191 }
192 }
193
194 async fn intervene(&self, cmd: InterventionCommand) -> Result<(), HarnessError> {
195 if !self.capabilities.supports(&cmd.kind) {
199 return Err(HarnessError::capability_not_supported(format!(
200 "{:?}",
201 cmd.kind.primitive()
202 )));
203 }
204 self.applied
205 .lock()
206 .map_err(|_poison| HarnessError::harness("applied-command lock poisoned"))?
207 .push(cmd.kind);
208 Ok(())
209 }
210
211 async fn wait_result(self) -> Result<Payload, HarnessError> {
212 Ok(self.result)
215 }
216}
217
218#[cfg(test)]
219#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
220mod tests {
221 use super::*;
222 use aion_core::{ActivityId, ApprovalDecision, InjectPriority, RunId, WorkflowId};
223 use futures::StreamExt;
224
225 fn spec() -> AgentRunSpec {
226 AgentRunSpec::new(
227 WorkflowId::new(Uuid::nil()),
228 RunId::new_v4(),
229 ActivityId::from_sequence_position(4),
230 2,
231 "mock-activity",
232 Payload::new(ContentType::Json, b"\"in\"".to_vec()),
233 )
234 }
235
236 fn command(kind: InterventionKind) -> InterventionCommand {
237 InterventionCommand {
238 workflow_id: WorkflowId::new(Uuid::nil()),
239 run_id: RunId::new_v4(),
240 activity_id: ActivityId::from_sequence_position(4),
241 attempt: 2,
242 issued_by: Some("operator".to_owned()),
243 issued_at: Utc::now(),
244 kind,
245 }
246 }
247
248 #[tokio::test]
249 async fn advertises_inject_message_and_cancel_only() {
250 let harness = MockAgentHarness::new();
251 let session = harness.start(spec()).await.unwrap();
252 let caps = session.capabilities();
253 assert!(caps.supports_primitive(InterventionPrimitive::InjectMessage));
254 assert!(caps.supports_primitive(InterventionPrimitive::Cancel));
255 assert!(!caps.supports_primitive(InterventionPrimitive::PauseResume));
256 assert!(!caps.supports_primitive(InterventionPrimitive::UpdateBudget));
257 assert!(!caps.supports_primitive(InterventionPrimitive::RespondToApproval));
258 }
259
260 #[tokio::test]
261 async fn accepts_an_advertised_command_and_records_it() {
262 let harness = MockAgentHarness::new();
263 let applied = harness.applied();
264 let session = harness.start(spec()).await.unwrap();
265
266 session
267 .intervene(command(InterventionKind::InjectMessage {
268 text: "steer".to_owned(),
269 priority: InjectPriority::Interrupt,
270 }))
271 .await
272 .unwrap();
273 session
274 .intervene(command(InterventionKind::Cancel {
275 reason: "stop".to_owned(),
276 }))
277 .await
278 .unwrap();
279
280 assert_eq!(applied.lock().unwrap().len(), 2);
281 }
282
283 #[tokio::test]
284 async fn rejects_respond_to_approval_as_capability_not_supported() {
285 let harness = MockAgentHarness::new();
286 let applied = harness.applied();
287 let session = harness.start(spec()).await.unwrap();
288
289 let error = session
290 .intervene(command(InterventionKind::RespondToApproval {
291 call_id: "c1".to_owned(),
292 decision: ApprovalDecision::Approve,
293 note: None,
294 }))
295 .await
296 .unwrap_err();
297 assert!(
298 matches!(error, HarnessError::CapabilityNotSupported { .. }),
299 "an advertised-unsupported primitive is cleanly NACKed, got {error:?}"
300 );
301 assert!(
302 applied.lock().unwrap().is_empty(),
303 "a gated command is never recorded as applied"
304 );
305 }
306
307 #[tokio::test]
308 async fn streams_a_transcript_and_returns_a_result() {
309 let harness = MockAgentHarness::new();
310 let mut session = harness.start(spec()).await.unwrap();
311 harness.take_run_handle().expect("a run handle").end_run();
313 let events: Vec<ActivityEvent> = session.events().collect().await;
314 assert_eq!(events.len(), 2, "the fixed transcript streams");
315 assert!(matches!(events[0].kind, ActivityEventKind::Message { .. }));
316 assert!(matches!(events[1].kind, ActivityEventKind::Stop { .. }));
317 let payload = session.wait_result().await.unwrap();
318 assert_eq!(payload.content_type(), &ContentType::Json);
319 }
320}