1use serde::{Deserialize, Serialize};
2use tokio_util::sync::CancellationToken;
3use tracing::{error, info, warn};
4
5use crate::agents::default_agent_spec_id;
6use crate::app::conversation::{Message, UserContent};
7use crate::app::domain::event::SessionEvent;
8use crate::app::domain::runtime::{RuntimeError, RuntimeHandle};
9use crate::app::domain::types::SessionId;
10use crate::config::model::ModelId;
11use crate::error::{Error, Result};
12use crate::session::ToolApprovalPolicy;
13use crate::session::state::SessionConfig;
14use crate::tools::{DISPATCH_AGENT_TOOL_NAME, DispatchAgentParams, DispatchAgentTarget};
15use steer_tools::ToolCall;
16use steer_tools::tools::BASH_TOOL_NAME;
17use steer_tools::tools::bash::BashParams;
18
19#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct RunOnceResult {
21 pub final_message: Message,
22 pub session_id: SessionId,
23}
24
25pub struct OneShotRunner;
26
27impl Default for OneShotRunner {
28 fn default() -> Self {
29 Self::new()
30 }
31}
32
33impl OneShotRunner {
34 pub fn new() -> Self {
35 Self
36 }
37
38 pub async fn run_in_session(
39 runtime: &RuntimeHandle,
40 session_id: SessionId,
41 message: String,
42 model: ModelId,
43 ) -> Result<RunOnceResult> {
44 Self::run_in_session_with_cancel(
45 runtime,
46 session_id,
47 message,
48 model,
49 CancellationToken::new(),
50 )
51 .await
52 }
53
54 pub async fn run_in_session_with_cancel(
55 runtime: &RuntimeHandle,
56 session_id: SessionId,
57 message: String,
58 model: ModelId,
59 cancel_token: CancellationToken,
60 ) -> Result<RunOnceResult> {
61 runtime.resume_session(session_id).await.map_err(|e| {
62 Error::InvalidOperation(format!("Failed to resume session {session_id}: {e}"))
63 })?;
64
65 let subscription = runtime.subscribe_events(session_id).await.map_err(|e| {
66 Error::InvalidOperation(format!(
67 "Failed to subscribe to session {session_id} events: {e}"
68 ))
69 })?;
70
71 let approval_policy = match runtime.get_session_state(session_id).await {
72 Ok(state) => state
73 .session_config
74 .map(|config| config.tool_config.approval_policy)
75 .unwrap_or_default(),
76 Err(err) => {
77 warn!(
78 session_id = %session_id,
79 error = %err,
80 "Failed to load session approval policy; defaulting to deny"
81 );
82 ToolApprovalPolicy::default()
83 }
84 };
85
86 info!(session_id = %session_id, message = %message, "Sending message to session");
87
88 let op_id = runtime
89 .submit_user_input(
90 session_id,
91 vec![UserContent::Text {
92 text: message.clone(),
93 }],
94 model,
95 )
96 .await
97 .map_err(|e| {
98 Error::InvalidOperation(format!(
99 "Failed to send message to session {session_id}: {e}"
100 ))
101 })?;
102
103 let cancel_task = {
104 let runtime = runtime.clone();
105 let cancel_token = cancel_token.clone();
106 tokio::spawn(async move {
107 cancel_token.cancelled().await;
108 if let Err(err) = runtime.cancel_operation(session_id, Some(op_id)).await {
109 warn!(
110 session_id = %session_id,
111 error = %err,
112 "Failed to cancel one-shot operation"
113 );
114 }
115 })
116 };
117
118 let result =
119 Self::process_events(runtime, subscription, session_id, op_id, approval_policy).await;
120
121 cancel_task.abort();
122
123 if let Err(e) = runtime.suspend_session(session_id).await {
124 error!(session_id = %session_id, error = %e, "Failed to suspend session");
125 } else {
126 info!(session_id = %session_id, "Session suspended successfully");
127 }
128
129 result
130 }
131
132 pub async fn run_new_session(
133 runtime: &RuntimeHandle,
134 config: SessionConfig,
135 message: String,
136 model: ModelId,
137 ) -> Result<RunOnceResult> {
138 Self::run_new_session_with_cancel(runtime, config, message, model, CancellationToken::new())
139 .await
140 }
141
142 pub async fn run_new_session_with_cancel(
143 runtime: &RuntimeHandle,
144 config: SessionConfig,
145 message: String,
146 model: ModelId,
147 cancel_token: CancellationToken,
148 ) -> Result<RunOnceResult> {
149 let session_id = runtime
150 .create_session(config)
151 .await
152 .map_err(|e| Error::InvalidOperation(format!("Failed to create session: {e}")))?;
153
154 info!(session_id = %session_id, "Created new session for one-shot run");
155
156 Self::run_in_session_with_cancel(runtime, session_id, message, model, cancel_token).await
157 }
158
159 async fn process_events(
160 runtime: &RuntimeHandle,
161 mut subscription: crate::app::domain::runtime::SessionEventSubscription,
162 session_id: SessionId,
163 op_id: crate::app::domain::types::OpId,
164 approval_policy: ToolApprovalPolicy,
165 ) -> Result<RunOnceResult> {
166 let mut messages = Vec::new();
167 info!(session_id = %session_id, "Starting event processing loop");
168
169 while let Some(envelope) = subscription.recv().await {
170 match envelope.event {
171 SessionEvent::AssistantMessageAdded { message, model: _ } => {
172 info!(
173 session_id = %session_id,
174 role = ?message.role(),
175 id = %message.id(),
176 "AssistantMessageAdded event"
177 );
178 messages.push(message);
179 }
180
181 SessionEvent::MessageUpdated { message } => {
182 info!(
183 session_id = %session_id,
184 id = %message.id(),
185 "MessageUpdated event"
186 );
187 }
188
189 SessionEvent::OperationCompleted {
190 op_id: completed_op,
191 } => {
192 if completed_op != op_id {
193 continue;
194 }
195 info!(
196 session_id = %session_id,
197 op_id = %completed_op,
198 "OperationCompleted event received"
199 );
200 if !messages.is_empty() {
201 info!(session_id = %session_id, "Final message received, exiting event loop");
202 break;
203 }
204 }
205
206 SessionEvent::OperationCancelled {
207 op_id: cancelled_op,
208 ..
209 } => {
210 if cancelled_op != op_id {
211 continue;
212 }
213 warn!(
214 session_id = %session_id,
215 op_id = %cancelled_op,
216 "OperationCancelled event received"
217 );
218 return Err(Error::Cancelled);
219 }
220
221 SessionEvent::Error { message } => {
222 error!(session_id = %session_id, error = %message, "Error event");
223 return Err(Error::InvalidOperation(format!(
224 "Error during processing: {message}"
225 )));
226 }
227
228 SessionEvent::ApprovalRequested {
229 request_id,
230 tool_call,
231 } => {
232 let approved = tool_is_preapproved(&tool_call, &approval_policy);
233 if approved {
234 info!(
235 session_id = %session_id,
236 request_id = %request_id,
237 tool = %tool_call.name,
238 "Auto-approving preapproved tool"
239 );
240 } else {
241 warn!(
242 session_id = %session_id,
243 request_id = %request_id,
244 tool = %tool_call.name,
245 "Auto-denying unapproved tool"
246 );
247 }
248
249 runtime
250 .submit_tool_approval(session_id, request_id, approved, None)
251 .await
252 .map_err(|e| {
253 Error::InvalidOperation(format!(
254 "Failed to submit tool approval decision: {e}"
255 ))
256 })?;
257 }
258
259 _ => {}
260 }
261 }
262
263 match messages.last() {
264 Some(final_message) => {
265 info!(
266 session_id = %session_id,
267 message_count = messages.len(),
268 "Returning final result"
269 );
270 Ok(RunOnceResult {
271 final_message: final_message.clone(),
272 session_id,
273 })
274 }
275 None => Err(Error::InvalidOperation("No message received".to_string())),
276 }
277 }
278}
279
280fn tool_is_preapproved(tool_call: &ToolCall, policy: &ToolApprovalPolicy) -> bool {
281 if policy.preapproved.tools.contains(&tool_call.name) {
282 return true;
283 }
284
285 if tool_call.name == DISPATCH_AGENT_TOOL_NAME {
286 let params = serde_json::from_value::<DispatchAgentParams>(tool_call.parameters.clone());
287 if let Ok(params) = params {
288 return match params.target {
289 DispatchAgentTarget::Resume { .. } => true,
290 DispatchAgentTarget::New { agent, .. } => {
291 let agent_id = agent
292 .as_deref()
293 .filter(|value| !value.trim().is_empty())
294 .map_or_else(|| default_agent_spec_id().to_string(), str::to_string);
295 policy.is_dispatch_agent_pattern_preapproved(&agent_id)
296 }
297 };
298 }
299 }
300
301 if tool_call.name == BASH_TOOL_NAME {
302 let params = serde_json::from_value::<BashParams>(tool_call.parameters.clone());
303 if let Ok(params) = params {
304 return policy.is_bash_pattern_preapproved(¶ms.command);
305 }
306 }
307
308 false
309}
310
311impl From<RuntimeError> for Error {
312 fn from(e: RuntimeError) -> Self {
313 match e {
314 RuntimeError::SessionNotFound { session_id } => {
315 Error::InvalidOperation(format!("Session not found: {session_id}"))
316 }
317 RuntimeError::SessionAlreadyExists { session_id } => {
318 Error::InvalidOperation(format!("Session already exists: {session_id}"))
319 }
320 RuntimeError::InvalidInput { message } => Error::InvalidOperation(message),
321 RuntimeError::ChannelClosed => {
322 Error::InvalidOperation("Runtime channel closed".to_string())
323 }
324 RuntimeError::ShuttingDown => {
325 Error::InvalidOperation("Runtime is shutting down".to_string())
326 }
327 RuntimeError::Session(e) => Error::InvalidOperation(format!("Session error: {e}")),
328 RuntimeError::EventStore(e) => {
329 Error::InvalidOperation(format!("Event store error: {e}"))
330 }
331 }
332 }
333}
334
335#[cfg(test)]
336mod tests {
337 use super::*;
338 use crate::api::Client as ApiClient;
339 use crate::api::{ApiError, CompletionResponse, Provider};
340 use crate::app::conversation::{AssistantContent, Message, MessageData};
341 use crate::app::domain::action::ApprovalDecision;
342 use crate::app::domain::runtime::RuntimeService;
343 use crate::app::domain::session::event_store::InMemoryEventStore;
344 use crate::app::validation::ValidatorRegistry;
345 use crate::config::model::builtin;
346 use crate::session::SessionPolicyOverrides;
347 use crate::session::ToolApprovalPolicy;
348 use crate::session::state::{
349 ApprovalRules, SessionToolConfig, UnapprovedBehavior, WorkspaceConfig,
350 };
351 use crate::tools::static_tools::READ_ONLY_TOOL_NAMES;
352 use crate::tools::{BackendRegistry, ToolExecutor};
353 use dotenvy::dotenv;
354 use serde_json::json;
355 use std::collections::{HashMap, HashSet};
356 use std::sync::Arc;
357 use std::sync::Mutex as StdMutex;
358 use steer_tools::ToolCall;
359 use steer_tools::tools::BASH_TOOL_NAME;
360 use tokio_util::sync::CancellationToken;
361
362 #[derive(Clone)]
363 struct ToolCallThenTextProvider {
364 tool_call: ToolCall,
365 final_text: String,
366 call_count: Arc<StdMutex<usize>>,
367 }
368
369 impl ToolCallThenTextProvider {
370 fn new(tool_call: ToolCall, final_text: impl Into<String>) -> Self {
371 Self {
372 tool_call,
373 final_text: final_text.into(),
374 call_count: Arc::new(StdMutex::new(0)),
375 }
376 }
377 }
378
379 #[async_trait::async_trait]
380 impl Provider for ToolCallThenTextProvider {
381 fn name(&self) -> &'static str {
382 "stub-tool-call"
383 }
384
385 async fn complete(
386 &self,
387 _model_id: &crate::config::model::ModelId,
388 _messages: Vec<Message>,
389 _system: Option<crate::app::SystemContext>,
390 _tools: Option<Vec<steer_tools::ToolSchema>>,
391 _call_options: Option<crate::config::model::ModelParameters>,
392 _token: CancellationToken,
393 ) -> std::result::Result<CompletionResponse, ApiError> {
394 let mut count = self
395 .call_count
396 .lock()
397 .expect("tool call counter lock poisoned");
398 let response = if *count == 0 {
399 CompletionResponse {
400 content: vec![AssistantContent::ToolCall {
401 tool_call: self.tool_call.clone(),
402 thought_signature: None,
403 }],
404 }
405 } else {
406 CompletionResponse {
407 content: vec![AssistantContent::Text {
408 text: self.final_text.clone(),
409 }],
410 }
411 };
412 *count += 1;
413 Ok(response)
414 }
415 }
416
417 async fn create_test_runtime() -> RuntimeService {
418 let event_store = Arc::new(InMemoryEventStore::new());
419 let model_registry = Arc::new(crate::model_registry::ModelRegistry::load(&[]).unwrap());
420 let provider_registry = Arc::new(crate::auth::ProviderRegistry::load(&[]).unwrap());
421 let api_client = Arc::new(ApiClient::new_with_deps(
422 crate::test_utils::test_llm_config_provider().unwrap(),
423 provider_registry,
424 model_registry,
425 ));
426
427 let tool_executor = Arc::new(ToolExecutor::with_components(
428 Arc::new(BackendRegistry::new()),
429 Arc::new(ValidatorRegistry::new()),
430 ));
431
432 RuntimeService::spawn(event_store, api_client, tool_executor)
433 }
434
435 fn create_test_session_config() -> SessionConfig {
436 SessionConfig {
437 default_model: builtin::claude_sonnet_4_5(),
438 workspace: WorkspaceConfig::default(),
439 workspace_ref: None,
440 workspace_id: None,
441 repo_ref: None,
442 parent_session_id: None,
443 workspace_name: None,
444 tool_config: SessionToolConfig::default(),
445 system_prompt: None,
446 primary_agent_id: None,
447 policy_overrides: SessionPolicyOverrides::empty(),
448 metadata: std::collections::HashMap::new(),
449 }
450 }
451
452 fn create_test_tool_approval_policy() -> ToolApprovalPolicy {
453 let tool_names = READ_ONLY_TOOL_NAMES
454 .iter()
455 .map(|name| (*name).to_string())
456 .collect();
457 ToolApprovalPolicy {
458 default_behavior: UnapprovedBehavior::Prompt,
459 preapproved: ApprovalRules {
460 tools: tool_names,
461 per_tool: std::collections::HashMap::new(),
462 },
463 }
464 }
465
466 #[test]
467 fn tool_is_preapproved_allows_whitelisted_tool() {
468 let policy = create_test_tool_approval_policy();
469 let tool_call = ToolCall {
470 id: "tc_read".to_string(),
471 name: READ_ONLY_TOOL_NAMES[0].to_string(),
472 parameters: json!({}),
473 };
474
475 assert!(tool_is_preapproved(&tool_call, &policy));
476 }
477
478 #[test]
479 fn tool_is_preapproved_allows_bash_pattern() {
480 use crate::session::state::{ApprovalRules, ToolRule, UnapprovedBehavior};
481
482 let mut per_tool = HashMap::new();
483 per_tool.insert(
484 "bash".to_string(),
485 ToolRule::Bash {
486 patterns: vec!["echo *".to_string()],
487 },
488 );
489
490 let policy = ToolApprovalPolicy {
491 default_behavior: UnapprovedBehavior::Prompt,
492 preapproved: ApprovalRules {
493 tools: HashSet::new(),
494 per_tool,
495 },
496 };
497
498 let tool_call = ToolCall {
499 id: "tc_bash".to_string(),
500 name: BASH_TOOL_NAME.to_string(),
501 parameters: json!({ "command": "echo hello" }),
502 };
503
504 assert!(tool_is_preapproved(&tool_call, &policy));
505 }
506
507 #[test]
508 fn tool_is_preapproved_allows_dispatch_agent_pattern() {
509 use crate::session::state::{ApprovalRules, ToolRule, UnapprovedBehavior};
510
511 let mut per_tool = HashMap::new();
512 per_tool.insert(
513 "dispatch_agent".to_string(),
514 ToolRule::DispatchAgent {
515 agent_patterns: vec!["explore".to_string()],
516 },
517 );
518
519 let policy = ToolApprovalPolicy {
520 default_behavior: UnapprovedBehavior::Prompt,
521 preapproved: ApprovalRules {
522 tools: HashSet::new(),
523 per_tool,
524 },
525 };
526
527 let tool_call = ToolCall {
528 id: "tc_dispatch".to_string(),
529 name: DISPATCH_AGENT_TOOL_NAME.to_string(),
530 parameters: json!({
531 "prompt": "find files",
532 "target": {
533 "session": "new",
534 "workspace": {
535 "location": "current"
536 },
537 "agent": "explore"
538 }
539 }),
540 };
541
542 assert!(tool_is_preapproved(&tool_call, &policy));
543 }
544
545 #[test]
546 fn tool_is_preapproved_denies_unlisted_tool() {
547 let policy = create_test_tool_approval_policy();
548 let tool_call = ToolCall {
549 id: "tc_other".to_string(),
550 name: "bash".to_string(),
551 parameters: json!({ "command": "rm -rf /" }),
552 };
553
554 assert!(!tool_is_preapproved(&tool_call, &policy));
555 }
556
557 #[tokio::test]
558 async fn run_new_session_denies_unapproved_tool_requests() {
559 let event_store = Arc::new(InMemoryEventStore::new());
560 let model_registry = Arc::new(crate::model_registry::ModelRegistry::load(&[]).unwrap());
561 let provider_registry = Arc::new(crate::auth::ProviderRegistry::load(&[]).unwrap());
562 let api_client = Arc::new(ApiClient::new_with_deps(
563 crate::test_utils::test_llm_config_provider().unwrap(),
564 provider_registry,
565 model_registry.clone(),
566 ));
567
568 let tool_call = ToolCall {
569 id: "tc_1".to_string(),
570 name: "bash".to_string(),
571 parameters: json!({ "command": "echo denied" }),
572 };
573 api_client.insert_test_provider(
574 builtin::claude_sonnet_4_5().provider.clone(),
575 Arc::new(ToolCallThenTextProvider::new(tool_call, "done")),
576 );
577
578 let tool_executor = Arc::new(ToolExecutor::with_components(
579 Arc::new(BackendRegistry::new()),
580 Arc::new(ValidatorRegistry::new()),
581 ));
582 let runtime = RuntimeService::spawn(event_store, api_client, tool_executor);
583
584 let mut config = create_test_session_config();
585 config.tool_config.approval_policy = ToolApprovalPolicy {
586 default_behavior: UnapprovedBehavior::Prompt,
587 preapproved: ApprovalRules {
588 tools: HashSet::new(),
589 per_tool: HashMap::new(),
590 },
591 };
592
593 let model = builtin::claude_sonnet_4_5();
594 let result = OneShotRunner::run_new_session(
595 &runtime.handle,
596 config,
597 "Trigger tool call".to_string(),
598 model,
599 )
600 .await
601 .expect("run_new_session should complete");
602
603 let events = runtime
604 .handle
605 .load_events_after(result.session_id, 0)
606 .await
607 .expect("load events");
608
609 let mut saw_request = false;
610 let mut saw_decision = false;
611 let mut saw_denied = false;
612
613 for (_, event) in events {
614 match event {
615 SessionEvent::ApprovalRequested { .. } => saw_request = true,
616 SessionEvent::ApprovalDecided { decision, .. } => {
617 saw_decision = true;
618 if decision == ApprovalDecision::Denied {
619 saw_denied = true;
620 }
621 }
622 _ => {}
623 }
624 }
625
626 assert!(saw_request, "expected ApprovalRequested event");
627 assert!(saw_decision, "expected ApprovalDecided event");
628 assert!(saw_denied, "expected denied decision");
629
630 runtime.shutdown().await;
631 }
632
633 #[tokio::test]
634 #[ignore = "Requires API keys and network access"]
635 async fn test_run_new_session_basic() {
636 dotenv().ok();
637 let runtime = create_test_runtime().await;
638
639 let mut config = create_test_session_config();
640 config.tool_config = SessionToolConfig::read_only();
641 config.tool_config.approval_policy = create_test_tool_approval_policy();
642 config
643 .metadata
644 .insert("mode".to_string(), "headless".to_string());
645
646 let model = builtin::claude_sonnet_4_5();
647 let result = OneShotRunner::run_new_session(
648 &runtime.handle,
649 config,
650 "What is 2 + 2?".to_string(),
651 model,
652 )
653 .await;
654
655 let result = tokio::time::timeout(std::time::Duration::from_secs(30), async { result })
656 .await
657 .expect("Timed out waiting for response")
658 .expect("run_new_session failed");
659
660 assert!(!result.final_message.id().is_empty());
661 println!("New session run succeeded: {:?}", result.final_message);
662
663 let content = match &result.final_message.data {
664 MessageData::Assistant { content, .. } => content,
665 _ => panic!("expected assistant message, got {:?}", result.final_message),
666 };
667 let text_content = content.iter().find_map(|c| match c {
668 AssistantContent::Text { text } => Some(text),
669 _ => None,
670 });
671 let content = text_content.expect("No text content found in assistant message");
672 assert!(!content.is_empty(), "Response should not be empty");
673 assert!(
674 content.contains('4'),
675 "Expected response to contain '4', got: {content}"
676 );
677
678 runtime.shutdown().await;
679 }
680
681 #[tokio::test]
682 async fn test_session_creation() {
683 let runtime = create_test_runtime().await;
684
685 let mut config = create_test_session_config();
686 config.tool_config.approval_policy = create_test_tool_approval_policy();
687 config
688 .metadata
689 .insert("test".to_string(), "value".to_string());
690
691 let session_id = runtime.handle.create_session(config).await.unwrap();
692
693 assert!(runtime.handle.is_session_active(session_id).await.unwrap());
694
695 let state = runtime.handle.get_session_state(session_id).await.unwrap();
696 assert_eq!(
697 state.session_config.as_ref().unwrap().metadata.get("test"),
698 Some(&"value".to_string())
699 );
700
701 runtime.shutdown().await;
702 }
703
704 #[tokio::test]
705 async fn test_run_in_session_nonexistent_session() {
706 let runtime = create_test_runtime().await;
707
708 let fake_session_id = SessionId::new();
709 let model = builtin::claude_sonnet_4_5();
710 let result = OneShotRunner::run_in_session(
711 &runtime.handle,
712 fake_session_id,
713 "Test message".to_string(),
714 model,
715 )
716 .await;
717
718 assert!(result.is_err());
719 let err = result.err().unwrap().to_string();
720 assert!(
721 err.contains("not found") || err.contains("Session"),
722 "Expected session not found error, got: {err}"
723 );
724
725 runtime.shutdown().await;
726 }
727
728 #[tokio::test]
729 #[ignore = "Requires API keys and network access"]
730 async fn test_run_in_session_with_real_api() {
731 dotenv().ok();
732 let runtime = create_test_runtime().await;
733
734 let mut config = create_test_session_config();
735 config.tool_config = SessionToolConfig::read_only();
736 config.tool_config.approval_policy = create_test_tool_approval_policy();
737 config
738 .metadata
739 .insert("test".to_string(), "api_test".to_string());
740
741 let session_id = runtime.handle.create_session(config).await.unwrap();
742 let model = builtin::claude_sonnet_4_5();
743
744 let result = OneShotRunner::run_in_session(
745 &runtime.handle,
746 session_id,
747 "What is the capital of France?".to_string(),
748 model,
749 )
750 .await;
751
752 match result {
753 Ok(run_result) => {
754 println!("Session run succeeded: {:?}", run_result.final_message);
755
756 let content = match &run_result.final_message.data {
757 MessageData::Assistant { content, .. } => content.clone(),
758 _ => panic!(
759 "expected assistant message, got {:?}",
760 run_result.final_message
761 ),
762 };
763 let text_content = content.iter().find_map(|c| match c {
764 AssistantContent::Text { text } => Some(text),
765 _ => None,
766 });
767 let content = text_content.expect("expected text response in assistant message");
768 assert!(!content.is_empty(), "Response should not be empty");
769 assert!(
770 content.to_lowercase().contains("paris"),
771 "Expected response to contain 'Paris', got: {content}"
772 );
773 }
774 Err(e) => {
775 println!("Session run failed (expected if no API key): {e}");
776 assert!(
777 e.to_string().contains("API key")
778 || e.to_string().contains("authentication")
779 || e.to_string().contains("timed out"),
780 "Unexpected error: {e}"
781 );
782 }
783 }
784
785 runtime.shutdown().await;
786 }
787
788 #[tokio::test]
789 #[ignore = "Requires API keys and network access"]
790 async fn test_run_in_session_preserves_context() {
791 dotenv().ok();
792 let runtime = create_test_runtime().await;
793
794 let mut config = create_test_session_config();
795 config.tool_config = SessionToolConfig::read_only();
796 config.tool_config.approval_policy = create_test_tool_approval_policy();
797 config
798 .metadata
799 .insert("test".to_string(), "context_test".to_string());
800
801 let session_id = runtime.handle.create_session(config).await.unwrap();
802 let model = builtin::claude_sonnet_4_5();
803
804 let result1 = OneShotRunner::run_in_session(
805 &runtime.handle,
806 session_id,
807 "My name is Alice and I like pizza.".to_string(),
808 model.clone(),
809 )
810 .await
811 .expect("First session run should succeed");
812
813 println!("First interaction: {:?}", result1.final_message);
814
815 runtime.handle.resume_session(session_id).await.unwrap();
816
817 let result2 = OneShotRunner::run_in_session(
818 &runtime.handle,
819 session_id,
820 "What is my name and what do I like?".to_string(),
821 model,
822 )
823 .await
824 .expect("Second session run should succeed");
825
826 println!("Second interaction: {:?}", result2.final_message);
827
828 match &result2.final_message.data {
829 MessageData::Assistant { content, .. } => {
830 let text_content = content.iter().find_map(|c| match c {
831 AssistantContent::Text { text } => Some(text),
832 _ => None,
833 });
834
835 match text_content {
836 Some(content) => {
837 assert!(!content.is_empty(), "Response should not be empty");
838 let content_lower = content.to_lowercase();
839
840 assert!(
841 content_lower.contains("alice") || content_lower.contains("name"),
842 "Expected response to reference the name or context, got: {content}"
843 );
844 }
845 None => {
846 panic!("expected text response in assistant message");
847 }
848 }
849 }
850 _ => {
851 panic!(
852 "expected assistant message, got {:?}",
853 result2.final_message
854 );
855 }
856 }
857
858 runtime.shutdown().await;
859 }
860
861 #[tokio::test]
862 #[ignore = "Requires API keys and network access"]
863 async fn test_run_new_session_with_tool_usage() {
864 dotenv().ok();
865 let runtime = create_test_runtime().await;
866
867 let mut config = create_test_session_config();
868 config.tool_config = SessionToolConfig::read_only();
869 config.tool_config.approval_policy = create_test_tool_approval_policy();
870 let model = builtin::claude_sonnet_4_5();
871
872 let result = OneShotRunner::run_new_session(
873 &runtime.handle,
874 config,
875 "List the files in the current directory".to_string(),
876 model,
877 )
878 .await
879 .expect("New session run with tools should succeed with valid API key");
880
881 assert!(!result.final_message.id().is_empty());
882 println!(
883 "New session run with tools succeeded: {:?}",
884 result.final_message
885 );
886
887 let has_content = match &result.final_message.data {
888 MessageData::Assistant { content, .. } => content.iter().any(|c| match c {
889 AssistantContent::Text { text } => !text.is_empty(),
890 _ => true,
891 }),
892 _ => false,
893 };
894 assert!(has_content, "Response should have some content");
895
896 runtime.shutdown().await;
897 }
898}