Skip to main content

everruns_core/
traits.rs

1// Core traits for pluggable backends
2//
3// These traits allow the agent loop to be used with different backends:
4// - In-memory implementations for examples and testing
5// - Database implementations for production
6// - Channel-based implementations for streaming
7
8use crate::agent::Agent;
9use crate::harness::Harness;
10use crate::provider::DriverId;
11use crate::session_file::{FileInfo, FileStat, GrepMatch, InitialFile, SessionFile};
12use crate::tool_types::{ToolCall, ToolDefinition, ToolResult};
13use crate::typed_id::{AgentId, HarnessId, ImageId, ModelId, SessionId, WorkspaceId};
14use async_trait::async_trait;
15use chrono::{DateTime, Utc};
16use std::any::{Any, TypeId};
17use std::collections::{HashMap, HashSet};
18use std::sync::Arc;
19use uuid::Uuid;
20
21/// Build a map of tool names to definitions for efficient lookup
22fn build_tool_map(tool_defs: &[ToolDefinition]) -> HashMap<&str, &ToolDefinition> {
23    tool_defs.iter().map(|def| (def.name(), def)).collect()
24}
25
26use crate::error::Result;
27
28// ============================================================================
29// ReasoningEffortHandle - live, turn-scoped reasoning-effort override
30// ============================================================================
31
32/// A live, shared handle to the reasoning effort for the current turn (EVE-595).
33///
34/// Each internal LLM step within a single `run_turn` re-reads this handle when
35/// building its provider request. A tool (or any in-turn actor) can call
36/// [`ReasoningEffortHandle::set`] mid-turn so that *subsequent* LLM steps in the
37/// same turn use the new effort, without waiting for the next turn.
38///
39/// When the handle holds `None`, the [`crate::atoms::ReasonAtom`] falls back to
40/// the effort resolved from the latest user message's `controls` — so callers
41/// that never set an override see no behavior change.
42#[derive(Clone, Default)]
43pub struct ReasoningEffortHandle {
44    inner: Arc<std::sync::RwLock<Option<String>>>,
45}
46
47impl ReasoningEffortHandle {
48    /// Create an empty handle (no override).
49    pub fn new() -> Self {
50        Self::default()
51    }
52
53    /// Create a handle pre-seeded with an effort override.
54    pub fn with_effort(effort: impl Into<String>) -> Self {
55        Self {
56            inner: Arc::new(std::sync::RwLock::new(Some(effort.into()))),
57        }
58    }
59
60    /// Set (or replace) the override effort. Subsequent LLM steps in the same
61    /// turn pick this up. Pass `None` to clear the override and fall back to the
62    /// message-derived effort.
63    pub fn set(&self, effort: Option<String>) {
64        // Recover from a poisoned lock so a panic elsewhere never silently
65        // disables mid-turn overrides; the stored value is a plain Option<String>
66        // with no broken invariant to worry about.
67        let mut guard = self.inner.write().unwrap_or_else(|e| e.into_inner());
68        *guard = effort;
69    }
70
71    /// Read the current override effort, if any.
72    pub fn get(&self) -> Option<String> {
73        // Recover from a poisoned lock rather than silently reverting to the
74        // message-derived effort mid-turn (see `set`).
75        let guard = self.inner.read().unwrap_or_else(|e| e.into_inner());
76        guard.clone()
77    }
78}
79
80impl std::fmt::Debug for ReasoningEffortHandle {
81    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82        f.debug_struct("ReasoningEffortHandle")
83            .field("effort", &self.get())
84            .finish()
85    }
86}
87
88// ============================================================================
89// AgentStore - For retrieving agent configurations
90// ============================================================================
91
92/// Trait for retrieving agent configurations
93///
94/// Implementations can:
95/// - Load agents from a database
96/// - Keep agents in memory for testing
97/// - Load agents from a configuration file
98#[async_trait]
99pub trait AgentStore: Send + Sync {
100    /// Get an agent by ID
101    async fn get_agent(&self, agent_id: AgentId) -> Result<Option<Agent>>;
102}
103
104#[async_trait]
105impl<T: AgentStore + ?Sized> AgentStore for std::sync::Arc<T> {
106    async fn get_agent(&self, agent_id: AgentId) -> Result<Option<Agent>> {
107        (**self).get_agent(agent_id).await
108    }
109}
110
111// ============================================================================
112// HarnessStore - For retrieving harness configurations
113// ============================================================================
114
115/// Trait for retrieving harness configurations
116///
117/// Implementations can:
118/// - Load harnesses from a database
119/// - Keep harnesses in memory for testing
120///
121/// Returns the harness inheritance chain (root-to-leaf) so the caller
122/// can fold each harness as an `AgentConfigOverlay`. DB-backed stores
123/// return the raw chain; gRPC-backed stores may return a single
124/// pre-merged harness (functionally equivalent when folded).
125#[async_trait]
126pub trait HarnessStore: Send + Sync {
127    /// Get the harness inheritance chain, root-to-leaf.
128    ///
129    /// Returns `Ok(vec![])` if the harness does not exist.
130    /// A harness with no parent returns a single-element vec.
131    async fn get_harness_chain(&self, harness_id: HarnessId) -> Result<Vec<Harness>>;
132}
133
134#[async_trait]
135impl<T: HarnessStore + ?Sized> HarnessStore for std::sync::Arc<T> {
136    async fn get_harness_chain(&self, harness_id: HarnessId) -> Result<Vec<Harness>> {
137        (**self).get_harness_chain(harness_id).await
138    }
139}
140
141// ============================================================================
142// SessionStore - For retrieving session information
143// ============================================================================
144
145use crate::leased_resource::{LeasedResource, UpsertLeasedResource};
146use crate::session::Session;
147
148/// Trait for retrieving session configurations
149///
150/// Implementations can:
151/// - Load sessions from a database
152/// - Keep sessions in memory for testing
153#[async_trait]
154pub trait SessionStore: Send + Sync {
155    /// Get a session by ID
156    async fn get_session(&self, session_id: SessionId) -> Result<Option<Session>>;
157}
158
159#[async_trait]
160impl<T: SessionStore + ?Sized> SessionStore for std::sync::Arc<T> {
161    async fn get_session(&self, session_id: SessionId) -> Result<Option<Session>> {
162        (**self).get_session(session_id).await
163    }
164}
165
166/// Trait for updating mutable session metadata.
167#[async_trait]
168pub trait SessionMutator: Send + Sync {
169    /// Update a session's human-readable title.
170    async fn update_session_title(&self, session_id: SessionId, title: String) -> Result<Session>;
171}
172
173#[async_trait]
174impl<T: SessionMutator + ?Sized> SessionMutator for std::sync::Arc<T> {
175    async fn update_session_title(&self, session_id: SessionId, title: String) -> Result<Session> {
176        (**self).update_session_title(session_id, title).await
177    }
178}
179
180// ============================================================================
181// ProviderStore - For retrieving LLM provider configurations
182// ============================================================================
183
184/// Model information with provider details needed for LLM calls
185#[derive(Debug, Clone)]
186pub struct ResolvedModel {
187    /// The model ID string to pass to the LLM API (e.g., "gpt-4o", "claude-3-opus")
188    pub model: String,
189    /// Provider type for factory selection
190    pub provider_type: DriverId,
191    /// Decrypted API key (if configured)
192    pub api_key: Option<String>,
193    /// Optional base URL override
194    pub base_url: Option<String>,
195    /// Extra provider-specific metadata (OAuth tokens, account ids, etc.).
196    /// Used by embedder-defined providers that authenticate without an API key.
197    pub provider_metadata: Option<crate::driver_registry::ProviderMetadata>,
198}
199
200/// Trait for retrieving LLM provider and model configurations
201///
202/// This trait abstracts the database lookup and API key decryption needed
203/// to create LLM providers at runtime.
204///
205/// Implementations can:
206/// - Load from a database with encrypted API keys
207/// - Use in-memory configurations for testing
208/// - Load from environment variables for development
209#[async_trait]
210pub trait ProviderStore: Send + Sync {
211    /// Get model with provider info by model ID
212    ///
213    /// Returns the model string ID, provider type, decrypted API key, and base URL
214    /// needed to create an LLM provider via the factory.
215    async fn get_resolved_model(&self, model_id: ModelId) -> Result<Option<ResolvedModel>>;
216
217    /// Get the default model with provider info
218    ///
219    /// Returns the system default model when an agent has no default_model_id set.
220    async fn get_default_model(&self) -> Result<Option<ResolvedModel>>;
221}
222
223#[async_trait]
224impl<T: ProviderStore + ?Sized> ProviderStore for std::sync::Arc<T> {
225    async fn get_resolved_model(&self, model_id: ModelId) -> Result<Option<ResolvedModel>> {
226        (**self).get_resolved_model(model_id).await
227    }
228
229    async fn get_default_model(&self) -> Result<Option<ResolvedModel>> {
230        (**self).get_default_model().await
231    }
232}
233
234// ============================================================================
235// ImageArtifactStore - For durable image persistence from tools
236// ============================================================================
237
238/// Metadata for a stored image artifact.
239#[derive(Debug, Clone)]
240pub struct StoredImageInfo {
241    pub id: ImageId,
242    pub filename: String,
243    pub content_type: String,
244    pub size_bytes: i64,
245    pub metadata: serde_json::Value,
246    pub created_at: DateTime<Utc>,
247}
248
249/// Stored image artifact with binary data.
250#[derive(Debug, Clone)]
251pub struct StoredImage {
252    pub info: StoredImageInfo,
253    pub data: Vec<u8>,
254}
255
256/// Input for creating a stored image artifact.
257#[derive(Debug, Clone)]
258pub struct CreateStoredImage {
259    pub filename: String,
260    pub content_type: String,
261    pub data: Vec<u8>,
262    pub metadata: serde_json::Value,
263}
264
265#[async_trait]
266pub trait ImageArtifactStore: Send + Sync {
267    /// Persist an image artifact and return its durable metadata.
268    async fn create_image(&self, input: CreateStoredImage) -> Result<StoredImageInfo>;
269
270    /// Load a stored image artifact including bytes.
271    async fn get_image(&self, image_id: ImageId) -> Result<Option<StoredImage>>;
272
273    /// Load stored image metadata without binary data.
274    async fn get_image_info(&self, image_id: ImageId) -> Result<Option<StoredImageInfo>>;
275}
276
277// ============================================================================
278// ProviderCredentialStore - For tool-side provider credential resolution
279// ============================================================================
280
281/// Provider credentials resolved for tool-side API clients.
282#[derive(Debug, Clone)]
283pub struct ProviderCredentials {
284    pub api_key: String,
285    pub base_url: Option<String>,
286}
287
288#[async_trait]
289pub trait ProviderCredentialStore: Send + Sync {
290    /// Resolve default credentials for a provider type (for example `openai`).
291    ///
292    /// Implementations may apply environment fallbacks internally, but tools
293    /// should never read provider env vars directly.
294    async fn get_default_provider_credentials(
295        &self,
296        provider_type: &str,
297    ) -> Result<Option<ProviderCredentials>>;
298}
299
300// ============================================================================
301// ToolExecutor - For executing tool calls
302// ============================================================================
303
304/// Trait for executing tool calls
305///
306/// Implementations handle the actual tool execution:
307/// - Webhook calls
308/// - Built-in function execution
309/// - Mock execution for testing
310#[async_trait]
311pub trait ToolExecutor: Send + Sync {
312    /// Execute a single tool call (without context)
313    ///
314    /// This is the legacy method that doesn't provide context to tools.
315    /// Use `execute_with_context` when context is available.
316    async fn execute(&self, tool_call: &ToolCall, tool_def: &ToolDefinition) -> Result<ToolResult>;
317
318    /// Execute a single tool call with context
319    ///
320    /// This method provides runtime context to tools that need it (like filesystem tools).
321    /// The default implementation delegates to `execute()`.
322    async fn execute_with_context(
323        &self,
324        tool_call: &ToolCall,
325        tool_def: &ToolDefinition,
326        _context: &ToolContext,
327    ) -> Result<ToolResult> {
328        // Default: delegate to execute(), ignoring context
329        self.execute(tool_call, tool_def).await
330    }
331
332    /// Execute multiple tool calls (default: sequential)
333    async fn execute_batch(
334        &self,
335        tool_calls: &[ToolCall],
336        tool_defs: &[ToolDefinition],
337    ) -> Result<Vec<ToolResult>> {
338        let mut results = Vec::with_capacity(tool_calls.len());
339
340        let tool_map = build_tool_map(tool_defs);
341
342        for tool_call in tool_calls {
343            let tool_def = tool_map.get(tool_call.name.as_str()).ok_or_else(|| {
344                crate::error::AgentLoopError::tool(format!(
345                    "Tool definition not found: {}",
346                    tool_call.name
347                ))
348            })?;
349
350            results.push(self.execute(tool_call, tool_def).await?);
351        }
352
353        Ok(results)
354    }
355
356    /// Execute multiple tool calls in parallel
357    async fn execute_parallel(
358        &self,
359        tool_calls: &[ToolCall],
360        tool_defs: &[ToolDefinition],
361    ) -> Result<Vec<ToolResult>>
362    where
363        Self: Sized,
364    {
365        use futures::future::join_all;
366
367        let tool_map = build_tool_map(tool_defs);
368
369        let futures: Vec<_> = tool_calls
370            .iter()
371            .map(|tool_call| async {
372                let tool_def = tool_map.get(tool_call.name.as_str()).ok_or_else(|| {
373                    crate::error::AgentLoopError::tool(format!(
374                        "Tool definition not found: {}",
375                        tool_call.name
376                    ))
377                })?;
378                self.execute(tool_call, tool_def).await
379            })
380            .collect();
381
382        let results = join_all(futures).await;
383        results.into_iter().collect()
384    }
385}
386
387/// Delegating impl so callers can hold a `ToolExecutor` as a trait object
388/// (e.g. to choose between a plain registry and an MCP-routing composite at
389/// runtime without monomorphizing the consumer).
390#[async_trait]
391impl ToolExecutor for std::sync::Arc<dyn ToolExecutor> {
392    async fn execute(&self, tool_call: &ToolCall, tool_def: &ToolDefinition) -> Result<ToolResult> {
393        (**self).execute(tool_call, tool_def).await
394    }
395
396    async fn execute_with_context(
397        &self,
398        tool_call: &ToolCall,
399        tool_def: &ToolDefinition,
400        context: &ToolContext,
401    ) -> Result<ToolResult> {
402        (**self)
403            .execute_with_context(tool_call, tool_def, context)
404            .await
405    }
406
407    async fn execute_batch(
408        &self,
409        tool_calls: &[ToolCall],
410        tool_defs: &[ToolDefinition],
411    ) -> Result<Vec<ToolResult>> {
412        (**self).execute_batch(tool_calls, tool_defs).await
413    }
414}
415
416// ============================================================================
417// SessionFileSystem - For session filesystem operations
418// ============================================================================
419
420/// Trait for session filesystem operations
421///
422/// This trait abstracts the session filesystem contract for tools and hosts.
423/// Implementations can:
424/// - Store files in a database (production)
425/// - Use an in-memory filesystem for testing
426/// - Project files onto real disk or object storage
427#[async_trait]
428pub trait SessionFileSystem: Send + Sync {
429    /// Human-facing root path for this filesystem.
430    ///
431    /// `/workspace` is the stable agent namespace and the default. Embedded
432    /// runtimes backed by a host directory override this to expose the real
433    /// root, so shared capabilities avoid misleading users about where files
434    /// live.
435    fn display_root(&self) -> String {
436        crate::session_path::WORKSPACE_PREFIX.to_string()
437    }
438
439    /// Convert a canonical session path into a human-facing path.
440    ///
441    /// The default renders the `/workspace` alias. Host-backed stores override
442    /// it, and decorators such as [`MountFs`](crate::mount_fs::MountFs) must
443    /// preserve the primary backend's path identity.
444    fn display_path(&self, path: &str) -> String {
445        crate::session_path::to_display_path(path)
446    }
447
448    /// Resolve an input path (any accepted spelling, relative or absolute) to an
449    /// absolute path within this filesystem's namespace. Relative inputs resolve
450    /// against the filesystem's current directory.
451    ///
452    /// This is how a shell seeds its working directory: a resolver like
453    /// [`MountFs`] returns a path in the primary backend's visible namespace, so
454    /// the shell and file tools share the same identity. The default is the flat
455    /// VFS session form.
456    ///
457    /// [`MountFs`]: crate::mount_fs::MountFs
458    fn resolve_path(&self, input: &str) -> String {
459        crate::session_path::to_session_path(input)
460    }
461
462    /// Whether this store is already a mount-based resolver ([`MountFs`]).
463    ///
464    /// Used to avoid re-wrapping nested mount tables when building tool context.
465    fn is_mount_resolver(&self) -> bool;
466
467    /// Read a file by path
468    async fn read_file(&self, session_id: SessionId, path: &str) -> Result<Option<SessionFile>>;
469
470    /// Write/create a file
471    async fn write_file(
472        &self,
473        session_id: SessionId,
474        path: &str,
475        content: &str,
476        encoding: &str,
477    ) -> Result<SessionFile>;
478
479    /// Write a file only if its current content snapshot still matches.
480    ///
481    /// Implementations backed by transactional storage should override this
482    /// with an atomic compare-and-set update.
483    async fn write_file_if_content_matches(
484        &self,
485        session_id: SessionId,
486        path: &str,
487        expected_content: &str,
488        expected_encoding: &str,
489        content: &str,
490        encoding: &str,
491    ) -> Result<Option<SessionFile>> {
492        let Some(existing) = self.read_file(session_id, path).await? else {
493            return Ok(None);
494        };
495
496        if existing.is_directory {
497            return Ok(None);
498        }
499
500        let current_content = existing.content.unwrap_or_default();
501        if current_content != expected_content || existing.encoding != expected_encoding {
502            return Ok(None);
503        }
504
505        self.write_file(session_id, path, content, encoding)
506            .await
507            .map(Some)
508    }
509
510    /// Delete a file or directory
511    async fn delete_file(&self, session_id: SessionId, path: &str, recursive: bool)
512    -> Result<bool>;
513
514    /// List files in a directory
515    async fn list_directory(&self, session_id: SessionId, path: &str) -> Result<Vec<FileInfo>>;
516
517    /// Get file metadata
518    async fn stat_file(&self, session_id: SessionId, path: &str) -> Result<Option<FileStat>>;
519
520    /// Search files by pattern (grep)
521    async fn grep_files(
522        &self,
523        session_id: SessionId,
524        pattern: &str,
525        path_pattern: Option<&str>,
526    ) -> Result<Vec<GrepMatch>>;
527
528    /// Create a directory
529    async fn create_directory(&self, session_id: SessionId, path: &str) -> Result<FileInfo>;
530
531    /// Seed a starter file into a session workspace.
532    async fn seed_initial_file(&self, session_id: SessionId, file: &InitialFile) -> Result<()> {
533        if file.is_readonly {
534            return Err(crate::error::AgentLoopError::store(
535                "read-only initial files require a SessionFileSystem-specific seed implementation",
536            ));
537        }
538        self.write_file(session_id, &file.path, &file.content, &file.encoding)
539            .await?;
540        Ok(())
541    }
542}
543
544/// A [`SessionFileSystem`] decorator that pins every operation to a fixed
545/// workspace key, ignoring the per-call `session_id`.
546///
547/// Used to re-key file I/O for a session attached to a shared workspace (where
548/// `workspace.id != session.id`): wrap the session's file store once with the
549/// session's `workspace_id`, and all downstream capability/tool access then
550/// addresses the attached workspace rather than the session's own keyspace. For
551/// the default 1:1 session the key equals the session id, so the wrapper is a
552/// transparent pass-through. See `specs/workspace.md`.
553pub struct WorkspaceScopedFileSystem {
554    inner: Arc<dyn SessionFileSystem>,
555    key: SessionId,
556}
557
558impl WorkspaceScopedFileSystem {
559    /// Wrap `inner`, pinning all operations to `workspace_id`'s key.
560    pub fn wrap(
561        inner: Arc<dyn SessionFileSystem>,
562        workspace_id: WorkspaceId,
563    ) -> Arc<dyn SessionFileSystem> {
564        Arc::new(Self {
565            inner,
566            key: SessionId::from_uuid(workspace_id.uuid()),
567        })
568    }
569}
570
571#[async_trait]
572impl SessionFileSystem for WorkspaceScopedFileSystem {
573    async fn read_file(&self, _session_id: SessionId, path: &str) -> Result<Option<SessionFile>> {
574        self.inner.read_file(self.key, path).await
575    }
576    async fn write_file(
577        &self,
578        _session_id: SessionId,
579        path: &str,
580        content: &str,
581        encoding: &str,
582    ) -> Result<SessionFile> {
583        self.inner
584            .write_file(self.key, path, content, encoding)
585            .await
586    }
587    async fn write_file_if_content_matches(
588        &self,
589        _session_id: SessionId,
590        path: &str,
591        expected_content: &str,
592        expected_encoding: &str,
593        content: &str,
594        encoding: &str,
595    ) -> Result<Option<SessionFile>> {
596        self.inner
597            .write_file_if_content_matches(
598                self.key,
599                path,
600                expected_content,
601                expected_encoding,
602                content,
603                encoding,
604            )
605            .await
606    }
607    async fn delete_file(
608        &self,
609        _session_id: SessionId,
610        path: &str,
611        recursive: bool,
612    ) -> Result<bool> {
613        self.inner.delete_file(self.key, path, recursive).await
614    }
615    async fn list_directory(&self, _session_id: SessionId, path: &str) -> Result<Vec<FileInfo>> {
616        self.inner.list_directory(self.key, path).await
617    }
618    async fn stat_file(&self, _session_id: SessionId, path: &str) -> Result<Option<FileStat>> {
619        self.inner.stat_file(self.key, path).await
620    }
621    async fn grep_files(
622        &self,
623        _session_id: SessionId,
624        pattern: &str,
625        path_pattern: Option<&str>,
626    ) -> Result<Vec<GrepMatch>> {
627        self.inner.grep_files(self.key, pattern, path_pattern).await
628    }
629    async fn create_directory(&self, _session_id: SessionId, path: &str) -> Result<FileInfo> {
630        self.inner.create_directory(self.key, path).await
631    }
632    async fn seed_initial_file(&self, _session_id: SessionId, file: &InitialFile) -> Result<()> {
633        self.inner.seed_initial_file(self.key, file).await
634    }
635
636    fn display_root(&self) -> String {
637        self.inner.display_root()
638    }
639
640    fn display_path(&self, path: &str) -> String {
641        self.inner.display_path(path)
642    }
643
644    fn resolve_path(&self, input: &str) -> String {
645        self.inner.resolve_path(input)
646    }
647
648    fn is_mount_resolver(&self) -> bool {
649        self.inner.is_mount_resolver()
650    }
651}
652
653#[async_trait]
654impl<T: SessionFileSystem + ?Sized> SessionFileSystem for std::sync::Arc<T> {
655    fn display_root(&self) -> String {
656        (**self).display_root()
657    }
658
659    fn display_path(&self, path: &str) -> String {
660        (**self).display_path(path)
661    }
662
663    fn resolve_path(&self, input: &str) -> String {
664        (**self).resolve_path(input)
665    }
666
667    fn is_mount_resolver(&self) -> bool {
668        (**self).is_mount_resolver()
669    }
670
671    async fn read_file(&self, session_id: SessionId, path: &str) -> Result<Option<SessionFile>> {
672        (**self).read_file(session_id, path).await
673    }
674
675    async fn write_file(
676        &self,
677        session_id: SessionId,
678        path: &str,
679        content: &str,
680        encoding: &str,
681    ) -> Result<SessionFile> {
682        (**self)
683            .write_file(session_id, path, content, encoding)
684            .await
685    }
686
687    async fn write_file_if_content_matches(
688        &self,
689        session_id: SessionId,
690        path: &str,
691        expected_content: &str,
692        expected_encoding: &str,
693        content: &str,
694        encoding: &str,
695    ) -> Result<Option<SessionFile>> {
696        (**self)
697            .write_file_if_content_matches(
698                session_id,
699                path,
700                expected_content,
701                expected_encoding,
702                content,
703                encoding,
704            )
705            .await
706    }
707
708    async fn delete_file(
709        &self,
710        session_id: SessionId,
711        path: &str,
712        recursive: bool,
713    ) -> Result<bool> {
714        (**self).delete_file(session_id, path, recursive).await
715    }
716
717    async fn list_directory(&self, session_id: SessionId, path: &str) -> Result<Vec<FileInfo>> {
718        (**self).list_directory(session_id, path).await
719    }
720
721    async fn stat_file(&self, session_id: SessionId, path: &str) -> Result<Option<FileStat>> {
722        (**self).stat_file(session_id, path).await
723    }
724
725    async fn grep_files(
726        &self,
727        session_id: SessionId,
728        pattern: &str,
729        path_pattern: Option<&str>,
730    ) -> Result<Vec<GrepMatch>> {
731        (**self).grep_files(session_id, pattern, path_pattern).await
732    }
733
734    async fn create_directory(&self, session_id: SessionId, path: &str) -> Result<FileInfo> {
735        (**self).create_directory(session_id, path).await
736    }
737
738    async fn seed_initial_file(&self, session_id: SessionId, file: &InitialFile) -> Result<()> {
739        (**self).seed_initial_file(session_id, file).await
740    }
741}
742
743/// Backward-compatible alias for the old session filesystem trait name.
744pub use SessionFileSystem as SessionFileStore;
745
746/// Host-supplied values used by platform file-system factories.
747///
748/// The context is intentionally type-erased so `everruns-core` can own the
749/// platform contract without depending on server-only types such as
750/// `StorageBackend` or future object-storage clients.
751#[derive(Clone, Default)]
752pub struct SessionFileSystemFactoryContext {
753    values: Arc<HashMap<TypeId, Arc<dyn Any + Send + Sync>>>,
754}
755
756impl SessionFileSystemFactoryContext {
757    pub fn new() -> Self {
758        Self::default()
759    }
760
761    pub fn with<T: Any + Send + Sync>(mut self, value: Arc<T>) -> Self {
762        let values = Arc::make_mut(&mut self.values);
763        values.insert(TypeId::of::<T>(), value);
764        self
765    }
766
767    pub fn get<T: Any + Send + Sync>(&self) -> Option<Arc<T>> {
768        self.values
769            .get(&TypeId::of::<T>())
770            .and_then(|value| value.clone().downcast::<T>().ok())
771    }
772
773    pub fn with_workspace_roots(self, roots: Arc<crate::WorkspaceRootSet>) -> Self {
774        self.with(roots)
775    }
776
777    pub fn workspace_roots(&self) -> Option<Arc<crate::WorkspaceRootSet>> {
778        self.get::<crate::WorkspaceRootSet>()
779    }
780}
781
782/// Factory for deployment-selected session filesystem implementations.
783#[async_trait]
784pub trait SessionFileSystemFactory: Send + Sync {
785    /// Human-readable factory name for diagnostics.
786    fn name(&self) -> &'static str {
787        "SessionFileSystemFactory"
788    }
789
790    /// Whether this factory intentionally leaves filesystem selection to the
791    /// runtime default.
792    fn is_disabled(&self) -> bool {
793        false
794    }
795
796    /// Resolve a live filesystem from host-provided dependencies.
797    async fn create_session_file_system(
798        &self,
799        context: SessionFileSystemFactoryContext,
800    ) -> Result<Arc<dyn SessionFileSystem>>;
801}
802
803/// Default factory used when a platform does not configure session files.
804#[derive(Debug, Clone, Default)]
805pub struct DisabledSessionFileSystemFactory;
806
807#[async_trait]
808impl SessionFileSystemFactory for DisabledSessionFileSystemFactory {
809    fn name(&self) -> &'static str {
810        "DisabledSessionFileSystemFactory"
811    }
812
813    fn is_disabled(&self) -> bool {
814        true
815    }
816
817    async fn create_session_file_system(
818        &self,
819        _context: SessionFileSystemFactoryContext,
820    ) -> Result<Arc<dyn SessionFileSystem>> {
821        Err(crate::error::AgentLoopError::config(
822            "session filesystem is disabled",
823        ))
824    }
825}
826
827// ============================================================================
828// SessionStorageStore - For session key/value and secret storage
829// ============================================================================
830
831/// Info about a stored key (without its value)
832#[derive(Debug, Clone)]
833pub struct KeyInfo {
834    pub key: String,
835    pub created_at: chrono::DateTime<chrono::Utc>,
836    pub updated_at: chrono::DateTime<chrono::Utc>,
837}
838
839/// Info about a stored secret (without its value)
840#[derive(Debug, Clone)]
841pub struct SecretInfo {
842    pub name: String,
843    pub created_at: chrono::DateTime<chrono::Utc>,
844    pub updated_at: chrono::DateTime<chrono::Utc>,
845}
846
847/// Trait for session key/value and secret storage operations
848///
849/// This trait abstracts storage operations for tools that need to persist
850/// data within a session. Implementations can:
851/// - Store data in a database (production)
852/// - Use in-memory storage for testing
853///
854/// A single ranked hit from a Knowledge Base search. Public-id surface only;
855/// no internal UUIDs. See specs/knowledge-bases.md and specs/okf-adoption.md.
856#[derive(Debug, Clone, serde::Serialize)]
857pub struct KnowledgeSearchHit {
858    /// Entry public id (`kbe_…`).
859    pub id: String,
860    /// Owning Knowledge Base public id (`kb_…`).
861    pub kb_id: String,
862    pub title: String,
863    pub kind: String,
864    pub tags: Vec<String>,
865    /// Short body excerpt for the LLM.
866    pub snippet: String,
867    /// Optional OKF resource URI, when set on the entry.
868    pub resource: Option<String>,
869}
870
871/// Org-scoped search over curated Knowledge Bases, backing the agent-facing
872/// `search_knowledge` tool. Implementations MUST scope to `org_id` and silently
873/// ignore KB ids not owned by that org (no existence leak across tenants).
874#[async_trait]
875pub trait KnowledgeStore: Send + Sync {
876    async fn search_knowledge(
877        &self,
878        org_id: crate::typed_id::OrgId,
879        kb_public_ids: &[String],
880        query: &str,
881        kind: Option<&str>,
882        tags: &[String],
883        limit: usize,
884    ) -> Result<Vec<KnowledgeSearchHit>>;
885}
886
887/// Storage for session-scoped key/value pairs and secrets.
888///
889/// Key/value storage is for general data that doesn't need encryption.
890/// Secret storage is for sensitive data that is encrypted at rest.
891#[async_trait]
892pub trait SessionStorageStore: Send + Sync {
893    // Key/Value operations (plain text)
894
895    /// Set a key/value pair (creates or updates)
896    async fn set_value(&self, session_id: SessionId, key: &str, value: &str) -> Result<()>;
897
898    /// Get a value by key
899    async fn get_value(&self, session_id: SessionId, key: &str) -> Result<Option<String>>;
900
901    /// Delete a key/value pair
902    async fn delete_value(&self, session_id: SessionId, key: &str) -> Result<bool>;
903
904    /// List all keys in a session
905    async fn list_keys(&self, session_id: SessionId) -> Result<Vec<KeyInfo>>;
906
907    // Secret operations (encrypted)
908
909    /// Set a secret (creates or updates, value is encrypted before storage)
910    async fn set_secret(&self, session_id: SessionId, name: &str, value: &str) -> Result<()>;
911
912    /// Get a secret by name (value is decrypted before returning)
913    async fn get_secret(&self, session_id: SessionId, name: &str) -> Result<Option<String>>;
914
915    /// Delete a secret
916    async fn delete_secret(&self, session_id: SessionId, name: &str) -> Result<bool>;
917
918    /// List all secret names in a session (without values)
919    async fn list_secrets(&self, session_id: SessionId) -> Result<Vec<SecretInfo>>;
920}
921
922// ============================================================================
923// SessionScheduleStore - For session-scoped schedule operations
924// ============================================================================
925
926use crate::session_schedule::SessionSchedule;
927use crate::typed_id::ScheduleId;
928
929/// Trait for session schedule CRUD operations.
930///
931/// Used by scheduling tools to create, cancel, and list schedules.
932#[async_trait]
933pub trait SessionScheduleStore: Send + Sync {
934    /// Create a new schedule for a session.
935    async fn create_schedule(
936        &self,
937        session_id: SessionId,
938        description: String,
939        cron_expression: Option<String>,
940        scheduled_at: Option<chrono::DateTime<chrono::Utc>>,
941        timezone: String,
942    ) -> Result<SessionSchedule>;
943
944    /// Create a new schedule after enforcing create-time limits in the same
945    /// store operation. Backends with shared mutable state must override this
946    /// to make the check-and-create sequence atomic.
947    async fn create_schedule_enforcing_limits(
948        &self,
949        session_id: SessionId,
950        description: String,
951        cron_expression: Option<String>,
952        scheduled_at: Option<chrono::DateTime<chrono::Utc>>,
953        timezone: String,
954    ) -> std::result::Result<SessionSchedule, crate::session_schedule::ScheduleLimitError> {
955        let per_session = self
956            .count_active_schedules(session_id)
957            .await
958            .map_err(crate::session_schedule::ScheduleLimitError::Store)?;
959        if per_session >= crate::session_schedule::MAX_ACTIVE_SCHEDULES_PER_SESSION {
960            return Err(crate::session_schedule::ScheduleLimitError::Rejected(
961                format!(
962                    "Maximum {} active schedules per session. Cancel an existing schedule first.",
963                    crate::session_schedule::MAX_ACTIVE_SCHEDULES_PER_SESSION
964                ),
965            ));
966        }
967
968        let max_per_org = crate::session_schedule::max_active_schedules_per_org();
969        let per_org = self
970            .count_active_org_schedules()
971            .await
972            .map_err(crate::session_schedule::ScheduleLimitError::Store)?;
973        if i64::from(per_org) >= max_per_org {
974            return Err(crate::session_schedule::ScheduleLimitError::Rejected(
975                format!(
976                    "Maximum {max_per_org} active schedules per org reached. Cancel an existing schedule first."
977                ),
978            ));
979        }
980
981        if let Some(cron) = cron_expression.as_deref() {
982            crate::session_schedule::validate_cron_min_interval(cron)
983                .map_err(crate::session_schedule::ScheduleLimitError::Rejected)?;
984        }
985
986        self.create_schedule(
987            session_id,
988            description,
989            cron_expression,
990            scheduled_at,
991            timezone,
992        )
993        .await
994        .map_err(crate::session_schedule::ScheduleLimitError::Store)
995    }
996
997    /// Cancel (disable) a schedule.
998    async fn cancel_schedule(
999        &self,
1000        session_id: SessionId,
1001        schedule_id: ScheduleId,
1002    ) -> Result<SessionSchedule>;
1003
1004    /// List schedules for a session.
1005    async fn list_schedules(&self, session_id: SessionId) -> Result<Vec<SessionSchedule>>;
1006
1007    /// Count active (enabled) schedules for a session.
1008    async fn count_active_schedules(&self, session_id: SessionId) -> Result<u32>;
1009
1010    /// Count active (enabled) schedules across the whole org this store is
1011    /// scoped to. Used to enforce a per-org cap independent of session count:
1012    /// `count_active_schedules` only bounds one session, so unlimited sessions
1013    /// would otherwise imply unlimited active schedules per org.
1014    async fn count_active_org_schedules(&self) -> Result<u32>;
1015}
1016
1017// ============================================================================
1018// SessionResourceRegistry - Generic session-scoped resource registry
1019// ============================================================================
1020
1021/// Generic registry of resources active alongside a session.
1022///
1023/// Capabilities register resources here (sandboxes, subagents, browser sessions).
1024/// Agents query it ("what's running?"), infrastructure scans it for cleanup.
1025/// See `specs/session-resources.md`.
1026#[async_trait]
1027pub trait SessionResourceRegistry: Send + Sync {
1028    /// Register a resource (or update if resource_id already exists for this session).
1029    async fn register(
1030        &self,
1031        entry: crate::session_resource::RegisterSessionResource,
1032    ) -> Result<crate::session_resource::SessionResourceEntry>;
1033
1034    /// Update the status of a registered resource.
1035    async fn update_status(
1036        &self,
1037        session_id: SessionId,
1038        resource_id: &str,
1039        status: crate::session_resource::SessionResourceStatus,
1040    ) -> Result<Option<crate::session_resource::SessionResourceEntry>>;
1041
1042    /// Get a specific resource by ID.
1043    async fn get(
1044        &self,
1045        session_id: SessionId,
1046        resource_id: &str,
1047    ) -> Result<Option<crate::session_resource::SessionResourceEntry>>;
1048
1049    /// List resources for a session, optionally filtered.
1050    async fn list(
1051        &self,
1052        session_id: SessionId,
1053        filter: Option<&crate::session_resource::SessionResourceFilter>,
1054    ) -> Result<Vec<crate::session_resource::SessionResourceEntry>>;
1055
1056    /// Remove a resource from the registry.
1057    async fn deregister(&self, session_id: SessionId, resource_id: &str) -> Result<bool>;
1058}
1059
1060// ============================================================================
1061// LeasedResourceStore - For lifecycle-managed external resources
1062// ============================================================================
1063
1064/// Trait for session-scoped leased resource operations.
1065///
1066/// Tools use this store to register or refresh leases when they create or use
1067/// external provider resources. Cleanup workers operate through control-plane
1068/// storage APIs directly so they can claim work across organizations.
1069#[async_trait]
1070pub trait LeasedResourceStore: Send + Sync {
1071    /// Create or refresh a leased resource for a session.
1072    ///
1073    /// Implementations must treat this as an idempotent upsert keyed by the
1074    /// provider-specific resource identity so repeated tool usage extends the
1075    /// same lease instead of creating duplicate rows.
1076    async fn upsert_resource(&self, input: UpsertLeasedResource) -> Result<LeasedResource>;
1077
1078    /// Mark a leased resource as explicitly released.
1079    ///
1080    /// This is the fast path for explicit user intent such as "close browser"
1081    /// or "delete sandbox". It should transition the resource to `released`
1082    /// without waiting for the durable cleanup worker to observe lease expiry.
1083    async fn release_resource(
1084        &self,
1085        session_id: SessionId,
1086        provider: &str,
1087        resource_type: &str,
1088        external_id: &str,
1089    ) -> Result<Option<LeasedResource>>;
1090
1091    /// List leased resources currently associated with a session.
1092    ///
1093    /// Session surfaces use this for visibility. Released resources remain
1094    /// visible so operators can inspect cleanup outcomes and failure history.
1095    async fn list_resources(&self, session_id: SessionId) -> Result<Vec<LeasedResource>>;
1096}
1097
1098// ============================================================================
1099// ToolContext - Runtime context for tool execution
1100// ============================================================================
1101
1102/// Default maximum child depth for subagent delegation. Top-level sessions are
1103/// depth 0, their children are depth 1, and grandchildren are depth 2.
1104pub const DEFAULT_MAX_SUBAGENT_DEPTH: u32 = 2;
1105pub const DEFAULT_MAX_ACTIVE_DESCENDANT_SUBAGENT_TASKS: u32 = 16;
1106pub const DEFAULT_MAX_TOTAL_DESCENDANT_SUBAGENT_TASKS: u32 = 200;
1107
1108/// Resolved subagent spawn governance policy for a tool execution context.
1109#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1110pub struct SubagentNestingPolicy {
1111    pub platform_default: u32,
1112    pub org_override: Option<u32>,
1113    pub agent_override: Option<u32>,
1114    pub platform_default_max_active_descendant_tasks: u32,
1115    pub org_override_max_active_descendant_tasks: Option<u32>,
1116    pub agent_override_max_active_descendant_tasks: Option<u32>,
1117    pub platform_default_max_total_descendant_tasks: u32,
1118    pub org_override_max_total_descendant_tasks: Option<u32>,
1119    pub agent_override_max_total_descendant_tasks: Option<u32>,
1120}
1121
1122impl Default for SubagentNestingPolicy {
1123    fn default() -> Self {
1124        Self {
1125            platform_default: DEFAULT_MAX_SUBAGENT_DEPTH,
1126            org_override: None,
1127            agent_override: None,
1128            platform_default_max_active_descendant_tasks:
1129                DEFAULT_MAX_ACTIVE_DESCENDANT_SUBAGENT_TASKS,
1130            org_override_max_active_descendant_tasks: None,
1131            agent_override_max_active_descendant_tasks: None,
1132            platform_default_max_total_descendant_tasks:
1133                DEFAULT_MAX_TOTAL_DESCENDANT_SUBAGENT_TASKS,
1134            org_override_max_total_descendant_tasks: None,
1135            agent_override_max_total_descendant_tasks: None,
1136        }
1137    }
1138}
1139
1140impl SubagentNestingPolicy {
1141    pub fn max_subagent_depth(self) -> u32 {
1142        self.agent_override
1143            .or(self.org_override)
1144            .unwrap_or(self.platform_default)
1145    }
1146
1147    pub fn max_active_descendant_tasks(self) -> u32 {
1148        self.agent_override_max_active_descendant_tasks
1149            .or(self.org_override_max_active_descendant_tasks)
1150            .unwrap_or(self.platform_default_max_active_descendant_tasks)
1151    }
1152
1153    pub fn max_total_descendant_tasks(self) -> u32 {
1154        self.agent_override_max_total_descendant_tasks
1155            .or(self.org_override_max_total_descendant_tasks)
1156            .unwrap_or(self.platform_default_max_total_descendant_tasks)
1157    }
1158
1159    pub fn with_platform_default(mut self, depth: u32) -> Self {
1160        self.platform_default = depth;
1161        self
1162    }
1163
1164    pub fn with_org_override(mut self, depth: Option<u32>) -> Self {
1165        self.org_override = depth;
1166        self
1167    }
1168
1169    pub fn with_agent_override(mut self, depth: Option<u32>) -> Self {
1170        self.agent_override = depth;
1171        self
1172    }
1173
1174    pub fn with_agent_task_caps_override(
1175        mut self,
1176        max_active: Option<u32>,
1177        max_total: Option<u32>,
1178    ) -> Self {
1179        self.agent_override_max_active_descendant_tasks = max_active;
1180        self.agent_override_max_total_descendant_tasks = max_total;
1181        self
1182    }
1183}
1184
1185/// Type alias for the session SQL DB store trait object.
1186pub type SessionSqlDbStoreRef = Arc<dyn crate::session_sqldb::SessionSqlDbStore>;
1187
1188/// Resolves user connection tokens (e.g. GitHub) lazily at tool execution time.
1189///
1190/// Instead of eagerly injecting tokens at session creation, tools call this
1191/// resolver when they need a token. If the user hasn't connected, returns None.
1192#[async_trait]
1193pub trait UserConnectionResolver: Send + Sync {
1194    /// Get a decrypted connection token for the given provider.
1195    /// Returns None if the user has no connection for this provider.
1196    async fn get_connection_token(
1197        &self,
1198        session_id: SessionId,
1199        provider: &str,
1200    ) -> Result<Option<String>>;
1201
1202    /// Resolve the user ID of the connection used for a session/provider pair.
1203    ///
1204    /// This is used by leased resources to bind cleanup to the same provider
1205    /// identity that created the remote resource.
1206    async fn get_connection_user(
1207        &self,
1208        _session_id: SessionId,
1209        _provider: &str,
1210    ) -> Result<Option<Uuid>> {
1211        Ok(None)
1212    }
1213
1214    /// Resolve a provider token for a specific user.
1215    ///
1216    /// Cleanup workers use this to avoid "first org member wins" behavior when
1217    /// cleaning resources created by a specific provider connection owner.
1218    async fn get_connection_token_for_user(
1219        &self,
1220        _user_id: Uuid,
1221        _provider: &str,
1222    ) -> Result<Option<String>> {
1223        Ok(None)
1224    }
1225
1226    /// Get provider-specific metadata stored alongside the connection.
1227    /// Returns None if no metadata is stored or no connection exists.
1228    async fn get_connection_metadata(
1229        &self,
1230        _session_id: SessionId,
1231        _provider: &str,
1232    ) -> Result<Option<serde_json::Value>> {
1233        Ok(None)
1234    }
1235}
1236
1237// ============================================================================
1238// BudgetChecker - For querying budget status from tools
1239// ============================================================================
1240
1241/// Trait for checking budget status from within tool execution.
1242///
1243/// Implemented by gRPC adapters (worker → server) and direct adapters (in-process).
1244/// Used by the `check_budget` tool to return real budget data to agents.
1245/// The org_id is captured at construction time by the implementing adapter.
1246#[async_trait]
1247pub trait BudgetChecker: Send + Sync {
1248    /// Check all budgets for a session and return a tool-friendly response.
1249    async fn check_budgets(&self, session_id: &str) -> Result<crate::budget::BudgetToolResponse>;
1250}
1251
1252// ============================================================================
1253// PaymentAuthority - For capability-internal machine payments
1254// ============================================================================
1255
1256/// Internal authority for paid capability operations.
1257///
1258/// Capabilities call this with fixed, typed requests. The model never receives a
1259/// generic paid HTTP tool, wallet credentials, or payment payloads.
1260#[async_trait]
1261pub trait PaymentAuthority: Send + Sync {
1262    async fn execute_machine_payment(
1263        &self,
1264        session_id: SessionId,
1265        request: crate::payment::MachinePaymentRequest,
1266    ) -> Result<crate::payment::MachinePaymentResponse>;
1267}
1268
1269// OutboundToolRateLimiter - Per-org outbound tool-call rate limiting (TM-TOOL-009)
1270// ============================================================================
1271
1272/// Per-org gate on outbound tool execution.
1273///
1274/// Returns `true` if the call is within the per-org budget, `false` if the
1275/// org has exceeded its outbound tool rate limit for this window.
1276/// Implementations must be fail-open: Valkey/backend errors should return `true`
1277/// rather than blocking legitimate tool calls.
1278#[async_trait]
1279pub trait OutboundToolRateLimiter: Send + Sync {
1280    /// Key by the public org UUID (keyed string representation).
1281    async fn check_org(&self, org_id: &crate::typed_id::OrgId) -> bool;
1282}
1283
1284// ============================================================================
1285// DurableToolResultStore — per-tool-call idempotency (EVE-530)
1286// ============================================================================
1287
1288/// Result of a claim attempt on the per-tool-call idempotency store.
1289#[derive(Debug)]
1290pub enum ToolCallClaimResult {
1291    /// First claim for this (turn_id, tool_call_id); caller should execute the tool.
1292    /// `claim_token` must be passed to `settle_tool_call` to verify ownership.
1293    Claimed { claim_token: uuid::Uuid },
1294    /// A prior run already settled this call; replay the stored result.
1295    AlreadySettled {
1296        result_json: serde_json::Value,
1297        args_fingerprint: String,
1298    },
1299    /// A prior run started but never settled. For `AtMostOnce` tools the
1300    /// caller should NOT re-execute; for `Pure`/`Idempotent` tools the caller
1301    /// may re-execute and then try to settle (the settle CAS will be a no-op if
1302    /// a different claimer wins first).
1303    AlreadyRunning { args_fingerprint: String },
1304    /// A settled row exists but its `args_fingerprint` does not match the
1305    /// current call — this is a determinism violation (workflow replay with
1306    /// different inputs). The workflow should be failed loudly.
1307    DeterminismViolation {
1308        stored_fingerprint: String,
1309        current_fingerprint: String,
1310    },
1311}
1312
1313/// Read-only status of a tool call in durable storage (EVE-533).
1314#[derive(Debug, Clone)]
1315pub enum DurableToolCallStatus {
1316    /// Tool completed successfully or with an error; result is stored.
1317    Settled { result_json: serde_json::Value },
1318    /// Tool was settled with `interrupted` status; result may contain error details.
1319    Interrupted {
1320        result_json: Option<serde_json::Value>,
1321    },
1322    /// A claim exists but the tool never finished.
1323    Running,
1324}
1325
1326/// Durable per-tool-call idempotency store (EVE-530).
1327///
1328/// Implements the claim/settle CAS that prevents double-execution of
1329/// `AtMostOnce` tools on worker reclaim/replay.
1330#[async_trait]
1331pub trait DurableToolResultStore: Send + Sync + 'static {
1332    /// Atomically claim `(turn_id, tool_call_id)` before tool dispatch.
1333    ///
1334    /// - Inserts a `running` row if none exists → `Claimed`.
1335    /// - Finds an existing `settled` row → `AlreadySettled`.
1336    /// - Finds an existing `running` row → `AlreadyRunning`.
1337    /// - Finds a `settled` row with a mismatched `args_fingerprint`
1338    ///   (determinism violation) → `DeterminismViolation`.
1339    async fn try_claim_tool_call(
1340        &self,
1341        turn_id: &str,
1342        tool_call_id: &str,
1343        tool_name: &str,
1344        args_fingerprint: &str,
1345    ) -> Result<ToolCallClaimResult>;
1346
1347    /// Settle a previously claimed tool call with its result.
1348    ///
1349    /// `claim_token` must match the token returned by `try_claim_tool_call`.
1350    /// Returns `Ok(true)` if the row was updated, `Ok(false)` if the claim
1351    /// token no longer matches (ownership lost — treat as a warning).
1352    async fn settle_tool_call(
1353        &self,
1354        turn_id: &str,
1355        tool_call_id: &str,
1356        result_json: serde_json::Value,
1357        status: &str,
1358        claim_token: uuid::Uuid,
1359    ) -> Result<bool>;
1360
1361    /// Read-only lookup of a tool call's current status in durable storage (EVE-533).
1362    ///
1363    /// Used by transcript repair to decide whether to replay a stored result or
1364    /// synthesize an interrupted placeholder. Returns `None` if no row exists.
1365    async fn get_tool_call_status(
1366        &self,
1367        turn_id: &str,
1368        tool_call_id: &str,
1369    ) -> Result<Option<DurableToolCallStatus>>;
1370}
1371
1372/// No-op implementation — used when no durable store is configured (dev/test).
1373/// Every call is treated as a fresh first execution; no replay or ownership checks.
1374pub struct NoopDurableToolResultStore;
1375
1376#[async_trait]
1377impl DurableToolResultStore for NoopDurableToolResultStore {
1378    async fn try_claim_tool_call(
1379        &self,
1380        _turn_id: &str,
1381        _tool_call_id: &str,
1382        _tool_name: &str,
1383        _args_fingerprint: &str,
1384    ) -> Result<ToolCallClaimResult> {
1385        Ok(ToolCallClaimResult::Claimed {
1386            claim_token: uuid::Uuid::new_v4(),
1387        })
1388    }
1389
1390    async fn settle_tool_call(
1391        &self,
1392        _turn_id: &str,
1393        _tool_call_id: &str,
1394        _result_json: serde_json::Value,
1395        _status: &str,
1396        _claim_token: uuid::Uuid,
1397    ) -> Result<bool> {
1398        Ok(true)
1399    }
1400
1401    async fn get_tool_call_status(
1402        &self,
1403        _turn_id: &str,
1404        _tool_call_id: &str,
1405    ) -> Result<Option<DurableToolCallStatus>> {
1406        Ok(None)
1407    }
1408}
1409
1410// ============================================================================
1411// StreamHeartbeater — per-stream liveness signal for Reason activity (EVE-531)
1412// ============================================================================
1413
1414/// Progress snapshot carried in each stream heartbeat.
1415#[derive(Debug, Clone)]
1416pub struct StreamProgress {
1417    /// Accumulated text + thinking length (characters) at the time of heartbeat.
1418    pub accumulated_len: usize,
1419    /// Wall-clock time of the most recent received token (Unix seconds).
1420    pub last_delta_at: u64,
1421}
1422
1423/// Heartbeater the Reason streaming loop calls on delta batches and a keepalive
1424/// timer, signalling that the provider connection is alive.
1425///
1426/// Implementations bridge to the durable-execution layer (e.g. gRPC).
1427/// The no-op is used in dev/test where no durable store is present.
1428#[async_trait]
1429pub trait StreamHeartbeater: Send + Sync {
1430    /// Signal stream liveness with current progress.
1431    ///
1432    /// Must be best-effort: errors must not propagate to the caller.
1433    /// Cancel-safety is critical — if the worker dies the heartbeat stops
1434    /// and the existing task-level reclaim takes over.
1435    async fn heartbeat(&self, progress: StreamProgress);
1436}
1437
1438/// No-op heartbeater — treats every stream as perpetually alive (dev/test).
1439pub struct NoopStreamHeartbeater;
1440
1441#[async_trait]
1442impl StreamHeartbeater for NoopStreamHeartbeater {
1443    async fn heartbeat(&self, _progress: StreamProgress) {}
1444}
1445
1446// ============================================================================
1447// PartialStreamStore — partial-stream recovery for Reason activity (EVE-532)
1448// ============================================================================
1449
1450/// State of a partially-streamed assistant message detected in the event log.
1451#[derive(Debug, Clone)]
1452pub struct PartialStreamState {
1453    /// Accumulated text from the last `output.message.delta` for the turn.
1454    /// Empty when `output.message.started` was emitted but no delta arrived.
1455    pub accumulated: String,
1456}
1457
1458/// Consults the persisted event log to detect whether a `reason` activity
1459/// was interrupted after `output.message.started` but before
1460/// `output.message.completed` or `output.message.replaced`.
1461///
1462/// Used by `ReasonAtom` on re-entry to apply the ContinuePartial recovery
1463/// policy (EVE-532): finalize the partial text without a second provider call,
1464/// or restart clean if the partial is unusable.
1465#[async_trait]
1466pub trait PartialStreamStore: Send + Sync {
1467    /// Return the partial-stream state for `(session_id, turn_id)` if an
1468    /// in-flight assistant message exists (started but not completed).
1469    async fn get_partial_stream(
1470        &self,
1471        session_id: SessionId,
1472        turn_id: &str,
1473    ) -> Result<Option<PartialStreamState>>;
1474}
1475
1476/// No-op — always reports no partial stream (dev/test / in-memory mode).
1477pub struct NoopPartialStreamStore;
1478
1479#[async_trait]
1480impl PartialStreamStore for NoopPartialStreamStore {
1481    async fn get_partial_stream(
1482        &self,
1483        _session_id: SessionId,
1484        _turn_id: &str,
1485    ) -> Result<Option<PartialStreamState>> {
1486        Ok(None)
1487    }
1488}
1489
1490/// Runtime context provided to tools during execution.
1491///
1492/// This context contains:
1493/// - Session ID for scoping operations
1494/// - Optional stores for tools that need external access
1495///
1496/// Tools that need context-aware execution (like filesystem tools) can use
1497/// the `execute_with_context` method on the Tool trait.
1498#[derive(Clone)]
1499pub struct ToolContext {
1500    /// The session ID for the current execution
1501    pub session_id: SessionId,
1502    /// The workspace this session is attached to — the key for the virtual
1503    /// file store. For the default 1:1 session this equals
1504    /// `WorkspaceId::from_uuid(session_id.uuid())`; for a shared workspace it
1505    /// differs. File-system tools MUST key by this (via `workspace_fs_key`)
1506    /// rather than `session_id` so shared-workspace sessions read/write the
1507    /// attached workspace's files. See specs/workspace.md.
1508    pub workspace_id: WorkspaceId,
1509
1510    /// Optional file store for filesystem operations
1511    pub file_store: Option<Arc<dyn SessionFileSystem>>,
1512
1513    /// Optional storage store for key/value and secret storage
1514    pub storage_store: Option<Arc<dyn SessionStorageStore>>,
1515
1516    /// Optional durable image artifact store for tool-side media persistence.
1517    pub image_store: Option<Arc<dyn ImageArtifactStore>>,
1518
1519    /// Optional provider credential store for tool-side API clients.
1520    pub provider_credential_store: Option<Arc<dyn ProviderCredentialStore>>,
1521
1522    /// Optional system utility LLM service for capability internals.
1523    pub utility_llm_service: Option<Arc<dyn crate::UtilityLlmService>>,
1524
1525    /// Optional scoped-MCP tool invoker for capability internals that need to
1526    /// call an MCP server out-of-band (e.g. the guardrails `mcp` check
1527    /// delegating a decision to an external guardrail endpoint). The invoker
1528    /// resolves connections and credentials per the current session/org, so
1529    /// tenant scoping is enforced by the host that supplies it.
1530    pub mcp_invoker: Option<Arc<dyn crate::McpToolInvoker>>,
1531
1532    /// Optional outbound egress service for HTTP/API traffic.
1533    pub egress_service: Option<Arc<dyn crate::EgressService>>,
1534
1535    /// Optional session SQL database store
1536    pub sqldb_store: Option<SessionSqlDbStoreRef>,
1537
1538    /// Optional message retriever for tools that need conversation history access
1539    pub message_retriever: Option<Arc<dyn crate::message_retriever::MessageRetriever>>,
1540
1541    /// Optional session store for tools that need session metadata access.
1542    pub session_store: Option<Arc<dyn SessionStore>>,
1543
1544    /// Optional session mutator for tools that need to update session metadata.
1545    pub session_mutator: Option<Arc<dyn SessionMutator>>,
1546
1547    /// Optional agent store for tools that need agent metadata access.
1548    pub agent_store: Option<Arc<dyn AgentStore>>,
1549
1550    /// Optional resolver for user connection tokens (lazy GitHub token lookup, etc.)
1551    pub connection_resolver: Option<Arc<dyn UserConnectionResolver>>,
1552
1553    /// Optional session schedule store for scheduling tools.
1554    pub schedule_store: Option<Arc<dyn SessionScheduleStore>>,
1555
1556    /// Optional platform store for org-level management tools.
1557    pub platform_store: Option<Arc<dyn crate::platform_store::PlatformStore>>,
1558    /// Optional knowledge store backing the `search_knowledge` tool.
1559    pub knowledge_store: Option<Arc<dyn KnowledgeStore>>,
1560
1561    /// Optional hybrid retrieval over bound Knowledge Indexes for the
1562    /// `search_index` tool. Server-implemented; populated only on the server
1563    /// act path alongside `platform_store` / `connection_resolver`.
1564    pub knowledge_index_search: Option<Arc<dyn crate::vector_store::KnowledgeIndexSearch>>,
1565
1566    /// Optional leased resource store for lifecycle-managed provider resources.
1567    pub leased_resource_store: Option<Arc<dyn LeasedResourceStore>>,
1568
1569    /// Optional session resource registry — generic registry of active resources.
1570    pub session_resource_registry: Option<Arc<dyn SessionResourceRegistry>>,
1571
1572    /// Optional session task registry — background work owned by the session
1573    /// (specs/session-tasks.md).
1574    pub session_task_registry: Option<Arc<dyn crate::session_task::SessionTaskRegistry>>,
1575
1576    /// Optional event emitter for tools that need to stream progress updates.
1577    /// When set, tools can emit `tool.progress` events during execution.
1578    pub event_emitter: Option<Arc<dyn EventEmitter>>,
1579
1580    /// Event context for correlating progress events with the current tool call.
1581    /// Set by ActAtom when constructing the ToolContext.
1582    pub event_context: Option<crate::events::EventContext>,
1583
1584    /// The tool call ID for the current execution (set by ActAtom).
1585    /// Used by tools to emit correlated progress events.
1586    pub tool_call_id: Option<String>,
1587    /// Optional capability registry for blueprint lookups.
1588    pub capability_registry: Option<crate::capabilities::CapabilityRegistry>,
1589
1590    /// Optional registry of active built-in tools for meta-tools such as
1591    /// `spawn_background` that need to inspect or delegate to sibling tools.
1592    pub tool_registry: Option<Arc<crate::tools::ToolRegistry>>,
1593
1594    /// Optional allowlist of tools visible to the model for this turn.
1595    /// Registry-introspecting tools must filter through this before returning
1596    /// sibling tool metadata, because the execution registry can be a superset.
1597    pub visible_tool_names: Option<Arc<HashSet<String>>>,
1598
1599    /// Optional org ID for org-scoped operations.
1600    pub org_id: Option<crate::typed_id::OrgId>,
1601
1602    /// Merged network access list (harness ∩ agent ∩ session).
1603    /// When set, tools that make HTTP requests must check URLs against this list.
1604    pub network_access: Option<crate::network_access::NetworkAccessList>,
1605
1606    /// Resolved locale for localized tool behavior (BCP 47, e.g. `uk-UA`).
1607    /// When set, tools that support localization use this to produce
1608    /// locale-appropriate descriptions, error messages, and prompts.
1609    pub locale: Option<String>,
1610
1611    /// Optional budget checker for the check_budget tool.
1612    pub budget_checker: Option<Arc<dyn BudgetChecker>>,
1613
1614    /// Optional internal payment authority for paid capability tools.
1615    pub payment_authority: Option<Arc<dyn PaymentAuthority>>,
1616
1617    /// Optional durable spawn handle store for subagent reattach (EVE-535).
1618    /// When set, subagent delegation uses claim/settle to prevent duplicate spawning
1619    /// on parent worker reclaim.
1620    pub subagent_spawn_store: Option<Arc<dyn SubagentSpawnStore>>,
1621
1622    /// Resolved subagent nesting policy for this turn.
1623    pub subagent_nesting_policy: SubagentNestingPolicy,
1624
1625    /// Optional live reasoning-effort handle (EVE-595). When set, a tool can
1626    /// change the reasoning effort mid-turn; subsequent LLM steps in the same
1627    /// `run_turn` re-read it and use the new effort.
1628    pub reasoning_effort_handle: Option<ReasoningEffortHandle>,
1629}
1630
1631impl ToolContext {
1632    /// The virtual-file-store key for this execution, derived from the attached
1633    /// workspace. Carried through the `SessionFileSystem` trait's `SessionId`
1634    /// parameter (the store keys by `.uuid()`), so a shared-workspace session
1635    /// addresses the workspace's files rather than its own session-id keyspace.
1636    pub fn workspace_fs_key(&self) -> SessionId {
1637        SessionId::from_uuid(self.workspace_id.uuid())
1638    }
1639
1640    /// Override the attached workspace (default is the 1:1 session-derived id).
1641    pub fn with_workspace_id(mut self, workspace_id: WorkspaceId) -> Self {
1642        self.workspace_id = workspace_id;
1643        self
1644    }
1645
1646    /// Create a new tool context with just a session ID
1647    pub fn new(session_id: SessionId) -> Self {
1648        Self {
1649            session_id,
1650            workspace_id: WorkspaceId::from_uuid(session_id.uuid()),
1651            file_store: None,
1652            storage_store: None,
1653            image_store: None,
1654            provider_credential_store: None,
1655            utility_llm_service: None,
1656            mcp_invoker: None,
1657            egress_service: None,
1658            sqldb_store: None,
1659            message_retriever: None,
1660            session_store: None,
1661            session_mutator: None,
1662            agent_store: None,
1663            connection_resolver: None,
1664            schedule_store: None,
1665            platform_store: None,
1666            knowledge_store: None,
1667            knowledge_index_search: None,
1668            leased_resource_store: None,
1669            session_resource_registry: None,
1670            session_task_registry: None,
1671            event_emitter: None,
1672            event_context: None,
1673            tool_call_id: None,
1674            capability_registry: None,
1675            tool_registry: None,
1676            visible_tool_names: None,
1677            org_id: None,
1678            network_access: None,
1679            locale: None,
1680            budget_checker: None,
1681            payment_authority: None,
1682            subagent_spawn_store: None,
1683            subagent_nesting_policy: SubagentNestingPolicy::default(),
1684            reasoning_effort_handle: None,
1685        }
1686    }
1687
1688    /// Create a context with a file store
1689    pub fn with_file_store(session_id: SessionId, file_store: Arc<dyn SessionFileSystem>) -> Self {
1690        Self {
1691            session_id,
1692            workspace_id: WorkspaceId::from_uuid(session_id.uuid()),
1693            file_store: Some(file_store),
1694            storage_store: None,
1695            image_store: None,
1696            provider_credential_store: None,
1697            utility_llm_service: None,
1698            mcp_invoker: None,
1699            egress_service: None,
1700            sqldb_store: None,
1701            message_retriever: None,
1702            session_store: None,
1703            session_mutator: None,
1704            agent_store: None,
1705            connection_resolver: None,
1706            schedule_store: None,
1707            platform_store: None,
1708            knowledge_store: None,
1709            knowledge_index_search: None,
1710            leased_resource_store: None,
1711            session_resource_registry: None,
1712            session_task_registry: None,
1713            event_emitter: None,
1714            event_context: None,
1715            tool_call_id: None,
1716            capability_registry: None,
1717            tool_registry: None,
1718            visible_tool_names: None,
1719            org_id: None,
1720            network_access: None,
1721            locale: None,
1722            budget_checker: None,
1723            payment_authority: None,
1724            subagent_spawn_store: None,
1725            subagent_nesting_policy: SubagentNestingPolicy::default(),
1726            reasoning_effort_handle: None,
1727        }
1728    }
1729
1730    /// Create a context with a storage store
1731    pub fn with_storage_store(
1732        session_id: SessionId,
1733        storage_store: Arc<dyn SessionStorageStore>,
1734    ) -> Self {
1735        Self {
1736            session_id,
1737            workspace_id: WorkspaceId::from_uuid(session_id.uuid()),
1738            file_store: None,
1739            storage_store: Some(storage_store),
1740            image_store: None,
1741            provider_credential_store: None,
1742            utility_llm_service: None,
1743            mcp_invoker: None,
1744            egress_service: None,
1745            sqldb_store: None,
1746            message_retriever: None,
1747            session_store: None,
1748            session_mutator: None,
1749            agent_store: None,
1750            connection_resolver: None,
1751            schedule_store: None,
1752            platform_store: None,
1753            knowledge_store: None,
1754            knowledge_index_search: None,
1755            leased_resource_store: None,
1756            session_resource_registry: None,
1757            session_task_registry: None,
1758            event_emitter: None,
1759            event_context: None,
1760            tool_call_id: None,
1761            capability_registry: None,
1762            tool_registry: None,
1763            visible_tool_names: None,
1764            org_id: None,
1765            network_access: None,
1766            locale: None,
1767            budget_checker: None,
1768            payment_authority: None,
1769            subagent_spawn_store: None,
1770            subagent_nesting_policy: SubagentNestingPolicy::default(),
1771            reasoning_effort_handle: None,
1772        }
1773    }
1774
1775    /// Create a context with both file store and storage store
1776    pub fn with_stores(
1777        session_id: SessionId,
1778        file_store: Arc<dyn SessionFileSystem>,
1779        storage_store: Arc<dyn SessionStorageStore>,
1780    ) -> Self {
1781        Self {
1782            session_id,
1783            workspace_id: WorkspaceId::from_uuid(session_id.uuid()),
1784            file_store: Some(file_store),
1785            storage_store: Some(storage_store),
1786            sqldb_store: None,
1787            image_store: None,
1788            provider_credential_store: None,
1789            utility_llm_service: None,
1790            mcp_invoker: None,
1791            egress_service: None,
1792            message_retriever: None,
1793            session_store: None,
1794            session_mutator: None,
1795            agent_store: None,
1796            connection_resolver: None,
1797            schedule_store: None,
1798            platform_store: None,
1799            knowledge_store: None,
1800            knowledge_index_search: None,
1801            leased_resource_store: None,
1802            session_resource_registry: None,
1803            session_task_registry: None,
1804            event_emitter: None,
1805            event_context: None,
1806            tool_call_id: None,
1807            capability_registry: None,
1808            tool_registry: None,
1809            visible_tool_names: None,
1810            org_id: None,
1811            network_access: None,
1812            locale: None,
1813            budget_checker: None,
1814            payment_authority: None,
1815            subagent_spawn_store: None,
1816            subagent_nesting_policy: SubagentNestingPolicy::default(),
1817            reasoning_effort_handle: None,
1818        }
1819    }
1820
1821    /// Add a SQL database store to this context
1822    pub fn with_sqldb_store(mut self, sqldb_store: SessionSqlDbStoreRef) -> Self {
1823        self.sqldb_store = Some(sqldb_store);
1824        self
1825    }
1826
1827    /// Add a message retriever to this context
1828    pub fn with_message_retriever(
1829        mut self,
1830        retriever: Arc<dyn crate::message_retriever::MessageRetriever>,
1831    ) -> Self {
1832        self.message_retriever = Some(retriever);
1833        self
1834    }
1835
1836    /// Add a session store to this context.
1837    pub fn with_session_store(mut self, store: Arc<dyn SessionStore>) -> Self {
1838        self.session_store = Some(store);
1839        self
1840    }
1841
1842    /// Add a session mutator to this context.
1843    pub fn with_session_mutator(mut self, mutator: Arc<dyn SessionMutator>) -> Self {
1844        self.session_mutator = Some(mutator);
1845        self
1846    }
1847
1848    /// Add a live reasoning-effort handle (EVE-595). Tools can call
1849    /// [`ReasoningEffortHandle::set`] on it to change the effort used by
1850    /// subsequent LLM steps within the same turn.
1851    pub fn with_reasoning_effort_handle(mut self, handle: ReasoningEffortHandle) -> Self {
1852        self.reasoning_effort_handle = Some(handle);
1853        self
1854    }
1855
1856    /// Add an agent store to this context.
1857    pub fn with_agent_store(mut self, store: Arc<dyn AgentStore>) -> Self {
1858        self.agent_store = Some(store);
1859        self
1860    }
1861
1862    /// Add a connection resolver to this context
1863    pub fn with_connection_resolver(mut self, resolver: Arc<dyn UserConnectionResolver>) -> Self {
1864        self.connection_resolver = Some(resolver);
1865        self
1866    }
1867
1868    /// Create a context with an image artifact store.
1869    pub fn with_image_store(
1870        session_id: SessionId,
1871        image_store: Arc<dyn ImageArtifactStore>,
1872    ) -> Self {
1873        Self {
1874            session_id,
1875            workspace_id: WorkspaceId::from_uuid(session_id.uuid()),
1876            file_store: None,
1877            storage_store: None,
1878            image_store: Some(image_store),
1879            provider_credential_store: None,
1880            utility_llm_service: None,
1881            mcp_invoker: None,
1882            egress_service: None,
1883            sqldb_store: None,
1884            message_retriever: None,
1885            session_store: None,
1886            session_mutator: None,
1887            agent_store: None,
1888            connection_resolver: None,
1889            schedule_store: None,
1890            platform_store: None,
1891            knowledge_store: None,
1892            knowledge_index_search: None,
1893            leased_resource_store: None,
1894            session_resource_registry: None,
1895            session_task_registry: None,
1896            event_emitter: None,
1897            event_context: None,
1898            tool_call_id: None,
1899            capability_registry: None,
1900            tool_registry: None,
1901            visible_tool_names: None,
1902            org_id: None,
1903            network_access: None,
1904            locale: None,
1905            budget_checker: None,
1906            payment_authority: None,
1907            subagent_spawn_store: None,
1908            subagent_nesting_policy: SubagentNestingPolicy::default(),
1909            reasoning_effort_handle: None,
1910        }
1911    }
1912
1913    /// Set the provider credential store on this context.
1914    pub fn with_provider_credential_store(
1915        mut self,
1916        store: Arc<dyn ProviderCredentialStore>,
1917    ) -> Self {
1918        self.provider_credential_store = Some(store);
1919        self
1920    }
1921
1922    /// Set the utility LLM service on this context.
1923    pub fn with_utility_llm_service(mut self, service: Arc<dyn crate::UtilityLlmService>) -> Self {
1924        self.utility_llm_service = Some(service);
1925        self
1926    }
1927
1928    /// Set the scoped-MCP tool invoker on this context.
1929    pub fn with_mcp_invoker(mut self, invoker: Arc<dyn crate::McpToolInvoker>) -> Self {
1930        self.mcp_invoker = Some(invoker);
1931        self
1932    }
1933
1934    /// Set the outbound egress service on this context.
1935    pub fn with_egress_service(mut self, service: Arc<dyn crate::EgressService>) -> Self {
1936        self.egress_service = Some(service);
1937        self
1938    }
1939
1940    /// Set the outbound egress service on this context when available.
1941    /// Preserves any already-set service when `service` is `None`.
1942    pub fn with_egress_service_opt(
1943        mut self,
1944        service: Option<Arc<dyn crate::EgressService>>,
1945    ) -> Self {
1946        if let Some(service) = service {
1947            self.egress_service = Some(service);
1948        }
1949        self
1950    }
1951
1952    /// Set the session storage store on this context (builder method).
1953    pub fn with_storage_store_arc(mut self, store: Arc<dyn SessionStorageStore>) -> Self {
1954        self.storage_store = Some(store);
1955        self
1956    }
1957
1958    /// Add a session schedule store to this context.
1959    pub fn with_schedule_store(mut self, store: Arc<dyn SessionScheduleStore>) -> Self {
1960        self.schedule_store = Some(store);
1961        self
1962    }
1963
1964    /// Add a platform store to this context.
1965    pub fn with_platform_store(
1966        mut self,
1967        store: Arc<dyn crate::platform_store::PlatformStore>,
1968    ) -> Self {
1969        self.platform_store = Some(store);
1970        self
1971    }
1972
1973    /// Add a Knowledge Index search service to this context (for `search_index`).
1974    pub fn with_knowledge_index_search(
1975        mut self,
1976        search: Arc<dyn crate::vector_store::KnowledgeIndexSearch>,
1977    ) -> Self {
1978        self.knowledge_index_search = Some(search);
1979        self
1980    }
1981
1982    /// Add a leased resource store to this context.
1983    pub fn with_leased_resource_store(mut self, store: Arc<dyn LeasedResourceStore>) -> Self {
1984        self.leased_resource_store = Some(store);
1985        self
1986    }
1987
1988    /// Add a session resource registry to this context.
1989    pub fn with_session_resource_registry(
1990        mut self,
1991        registry: Arc<dyn SessionResourceRegistry>,
1992    ) -> Self {
1993        self.session_resource_registry = Some(registry);
1994        self
1995    }
1996
1997    /// Add a session task registry to this context.
1998    pub fn with_session_task_registry(
1999        mut self,
2000        registry: Arc<dyn crate::session_task::SessionTaskRegistry>,
2001    ) -> Self {
2002        self.session_task_registry = Some(registry);
2003        self
2004    }
2005
2006    /// Set org ID for org-scoped operations.
2007    pub fn with_org_id(mut self, org_id: crate::typed_id::OrgId) -> Self {
2008        self.org_id = Some(org_id);
2009        self
2010    }
2011
2012    /// Set the active built-in tool registry on this context.
2013    pub fn with_tool_registry(mut self, registry: Arc<crate::tools::ToolRegistry>) -> Self {
2014        self.tool_registry = Some(registry);
2015        self
2016    }
2017
2018    /// Set the tool names visible to the model in this turn.
2019    pub fn with_visible_tool_names(mut self, names: Arc<HashSet<String>>) -> Self {
2020        self.visible_tool_names = Some(names);
2021        self
2022    }
2023
2024    /// Set the merged network access list for URL filtering.
2025    pub fn with_network_access(
2026        mut self,
2027        network_access: Option<crate::network_access::NetworkAccessList>,
2028    ) -> Self {
2029        self.network_access = network_access;
2030        self
2031    }
2032
2033    /// Set the internal payment authority for paid capability operations.
2034    pub fn with_payment_authority(mut self, authority: Arc<dyn PaymentAuthority>) -> Self {
2035        self.payment_authority = Some(authority);
2036        self
2037    }
2038
2039    /// Set the durable subagent spawn handle store (EVE-535).
2040    pub fn with_subagent_spawn_store(mut self, store: Arc<dyn SubagentSpawnStore>) -> Self {
2041        self.subagent_spawn_store = Some(store);
2042        self
2043    }
2044
2045    /// Set the resolved subagent nesting policy.
2046    pub fn with_subagent_nesting_policy(mut self, policy: SubagentNestingPolicy) -> Self {
2047        self.subagent_nesting_policy = policy;
2048        self
2049    }
2050
2051    /// Emit a `tool.progress` event if an event emitter and context are available.
2052    ///
2053    /// This is a best-effort helper: failures are logged but not propagated,
2054    /// so tools never fail just because a progress event couldn't be sent.
2055    pub async fn emit_progress(&self, tool_name: &str, message: &str) {
2056        let (Some(emitter), Some(ctx), Some(call_id)) =
2057            (&self.event_emitter, &self.event_context, &self.tool_call_id)
2058        else {
2059            return;
2060        };
2061        if let Err(e) = emitter
2062            .emit(EventRequest::new(
2063                self.session_id,
2064                ctx.clone(),
2065                crate::events::ToolProgressData {
2066                    tool_call_id: call_id.clone(),
2067                    tool_name: tool_name.to_string(),
2068                    message: message.to_string(),
2069                    display_name: None,
2070                },
2071            ))
2072            .await
2073        {
2074            tracing::debug!(
2075                tool_call_id = call_id,
2076                tool_name,
2077                error = %e,
2078                "Failed to emit tool.progress event"
2079            );
2080        }
2081    }
2082
2083    /// Emit a `tool.output.delta` event if an event emitter and context are available.
2084    ///
2085    /// Streams incremental output chunks (e.g., stdout/stderr lines) for live
2086    /// rendering in UI and CLI. Best-effort: failures are logged, not propagated.
2087    pub async fn emit_tool_output(&self, tool_name: &str, delta: &str, stream: &str) {
2088        let (Some(emitter), Some(ctx), Some(call_id)) =
2089            (&self.event_emitter, &self.event_context, &self.tool_call_id)
2090        else {
2091            return;
2092        };
2093        if let Err(e) = emitter
2094            .emit(EventRequest::new(
2095                self.session_id,
2096                ctx.clone(),
2097                crate::events::ToolOutputDeltaData {
2098                    tool_call_id: call_id.clone(),
2099                    tool_name: tool_name.to_string(),
2100                    delta: delta.to_string(),
2101                    stream: stream.to_string(),
2102                },
2103            ))
2104            .await
2105        {
2106            tracing::debug!(
2107                tool_call_id = call_id,
2108                tool_name,
2109                error = %e,
2110                "Failed to emit tool.output.delta event"
2111            );
2112        }
2113    }
2114}
2115
2116impl std::fmt::Debug for ToolContext {
2117    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2118        f.debug_struct("ToolContext")
2119            .field("session_id", &self.session_id)
2120            .field("file_store", &self.file_store.is_some())
2121            .field("storage_store", &self.storage_store.is_some())
2122            .field("image_store", &self.image_store.is_some())
2123            .field(
2124                "provider_credential_store",
2125                &self.provider_credential_store.is_some(),
2126            )
2127            .field("utility_llm_service", &self.utility_llm_service.is_some())
2128            .field("egress_service", &self.egress_service.is_some())
2129            .field("sqldb_store", &self.sqldb_store.is_some())
2130            .field("message_retriever", &self.message_retriever.is_some())
2131            .field("session_store", &self.session_store.is_some())
2132            .field("session_mutator", &self.session_mutator.is_some())
2133            .field("agent_store", &self.agent_store.is_some())
2134            .field("connection_resolver", &self.connection_resolver.is_some())
2135            .field("schedule_store", &self.schedule_store.is_some())
2136            .field("platform_store", &self.platform_store.is_some())
2137            .field(
2138                "knowledge_index_search",
2139                &self.knowledge_index_search.is_some(),
2140            )
2141            .field(
2142                "leased_resource_store",
2143                &self.leased_resource_store.is_some(),
2144            )
2145            .field("event_emitter", &self.event_emitter.is_some())
2146            .field("tool_registry", &self.tool_registry.is_some())
2147            .field("payment_authority", &self.payment_authority.is_some())
2148            .field("subagent_spawn_store", &self.subagent_spawn_store.is_some())
2149            .field("subagent_nesting_policy", &self.subagent_nesting_policy)
2150            .field("org_id", &self.org_id)
2151            .finish()
2152    }
2153}
2154
2155// ============================================================================
2156// EventEmitter - For emitting events
2157// ============================================================================
2158
2159use crate::events::{Event, EventRequest};
2160
2161/// Trait for emitting events following the standard event protocol
2162///
2163/// Implementations can:
2164/// - Store events in a database
2165/// - Keep events in memory for testing
2166/// - Stream events via SSE/WebSocket
2167/// - Log events for debugging
2168///
2169/// Events follow a consistent schema: id, type, ts, context, data.
2170/// See specs/events.md for the full event protocol specification.
2171#[async_trait]
2172pub trait EventEmitter: Send + Sync {
2173    /// Emit an event request
2174    ///
2175    /// Takes an EventRequest (without id/sequence) and returns the stored Event
2176    /// with id and sequence assigned by the storage layer.
2177    async fn emit(&self, request: EventRequest) -> Result<Event>;
2178}
2179
2180/// Blanket impl: `Arc<E>` delegates to the inner emitter.
2181#[async_trait]
2182impl<E: EventEmitter + ?Sized> EventEmitter for Arc<E> {
2183    async fn emit(&self, request: EventRequest) -> Result<Event> {
2184        (**self).emit(request).await
2185    }
2186}
2187
2188/// No-op event emitter for when event emission is not needed
2189///
2190/// This is useful for testing or when event observability is disabled.
2191#[derive(Debug, Clone, Default)]
2192pub struct NoopEventEmitter;
2193
2194#[async_trait]
2195impl EventEmitter for NoopEventEmitter {
2196    async fn emit(&self, request: EventRequest) -> Result<Event> {
2197        // Return a dummy event with sequence 0
2198        Ok(request.into_event(crate::typed_id::EventId::new(), 0))
2199    }
2200}
2201
2202// Note: EventListener trait has been moved to event_listeners.rs module.
2203// Use `everruns_core::EventListener` or `everruns_core::event_listeners::EventListener`.
2204
2205// ============================================================================
2206// ImageResolver - For resolving image_file content to actual image data
2207// ============================================================================
2208
2209/// Resolved image data for LLM consumption
2210///
2211/// This struct contains the actual image data in a format suitable for
2212/// sending to LLM providers. Both OpenAI and Anthropic accept base64-encoded
2213/// images with media type information.
2214#[derive(Debug, Clone)]
2215pub struct ResolvedImage {
2216    /// Base64-encoded image data (without data URL prefix)
2217    pub base64: String,
2218    /// MIME type (e.g., "image/png", "image/jpeg")
2219    pub media_type: String,
2220}
2221
2222impl ResolvedImage {
2223    /// Create a new resolved image
2224    pub fn new(base64: impl Into<String>, media_type: impl Into<String>) -> Self {
2225        Self {
2226            base64: base64.into(),
2227            media_type: media_type.into(),
2228        }
2229    }
2230
2231    /// Convert to a data URL suitable for OpenAI Vision API
2232    ///
2233    /// Format: `data:{media_type};base64,{base64_data}`
2234    pub fn to_data_url(&self) -> String {
2235        format!("data:{};base64,{}", self.media_type, self.base64)
2236    }
2237}
2238
2239/// Trait for resolving image_file content parts to actual image data
2240///
2241/// When building LLM messages, `image_file` content parts contain only
2242/// a reference (UUID) to an uploaded image. This trait allows resolving
2243/// those references to actual image data.
2244///
2245/// # Provider-specific formatting
2246///
2247/// The resolved image data is then converted to provider-specific formats:
2248///
2249/// **OpenAI Vision:**
2250/// ```json
2251/// {
2252///   "type": "image_url",
2253///   "image_url": { "url": "data:image/png;base64,..." }
2254/// }
2255/// ```
2256///
2257/// **Anthropic Vision:**
2258/// ```json
2259/// {
2260///   "type": "image",
2261///   "source": { "type": "base64", "media_type": "image/png", "data": "..." }
2262/// }
2263/// ```
2264///
2265/// # Implementation notes
2266///
2267/// Implementations should:
2268/// - Fetch image data from storage (database, S3, etc.)
2269/// - Return base64-encoded data with media type
2270/// - Handle missing images gracefully (return None)
2271#[async_trait]
2272pub trait ImageResolver: Send + Sync {
2273    /// Resolve an image_file reference to actual image data
2274    ///
2275    /// Returns `None` if the image is not found.
2276    async fn resolve_image(&self, image_id: Uuid) -> Result<Option<ResolvedImage>>;
2277}
2278
2279// ============================================================================
2280// SubagentSpawnStore — durable spawn handles for subagent reattach (EVE-535)
2281// ============================================================================
2282
2283/// Result of attempting to claim a subagent spawn slot.
2284#[derive(Debug)]
2285pub enum SpawnClaimResult {
2286    /// First claim — child session does not yet exist.
2287    /// Proceed to create the child, then call `register_child_session`.
2288    Claimed {
2289        spawn_handle_id: uuid::Uuid,
2290        claim_token: uuid::Uuid,
2291    },
2292    /// Row exists but `child_session_id` was never registered (crash between
2293    /// claim and `register_child_session`). Re-create the child and call
2294    /// `register_child_session` — same flow as `Claimed`.
2295    ClaimedPendingChild {
2296        spawn_handle_id: uuid::Uuid,
2297        claim_token: uuid::Uuid,
2298    },
2299    /// Child session was created and is still running.
2300    /// Reattach: wait for the existing child and settle with the stored claim_token.
2301    AlreadyRunning {
2302        child_session_id: crate::typed_id::SessionId,
2303        /// Stored claim token — must be used for `settle_spawn` on this replay.
2304        claim_token: uuid::Uuid,
2305    },
2306    /// Child already finished on a previous execution.
2307    /// Fast-path: return the stored result immediately without waiting.
2308    AlreadySettled {
2309        child_session_id: crate::typed_id::SessionId,
2310        /// The `wait_for_idle` return value from the original execution.
2311        terminal_status: String,
2312        terminal_result: String,
2313    },
2314}
2315
2316/// Durable spawn handle store for subagent idempotency (EVE-535).
2317///
2318/// Maps `(parent_session_id, tool_call_id) → child_session_id` so that when
2319/// a parent's `act` is reclaimed mid-`wait_for_idle`, the tool can reattach
2320/// to the existing child instead of spawning a duplicate.
2321///
2322/// Lifecycle: claim → register_child_session → settle_spawn.
2323#[async_trait]
2324pub trait SubagentSpawnStore: Send + Sync + 'static {
2325    /// Attempt to claim a spawn slot for `(parent_session_id, tool_call_id)`.
2326    ///
2327    /// Does NOT accept `child_session_id` — the child session does not exist yet.
2328    /// Call `register_child_session` with the actual child ID after creating it.
2329    async fn try_claim_spawn(
2330        &self,
2331        parent_session_id: crate::typed_id::SessionId,
2332        tool_call_id: &str,
2333        claim_token: uuid::Uuid,
2334    ) -> Result<SpawnClaimResult>;
2335
2336    /// Register the actual child session ID after it has been created.
2337    ///
2338    /// Must be called after `try_claim_spawn` returns `Claimed` or
2339    /// `ClaimedPendingChild`, before waiting for the child to complete.
2340    async fn register_child_session(
2341        &self,
2342        spawn_handle_id: uuid::Uuid,
2343        claim_token: uuid::Uuid,
2344        child_session_id: crate::typed_id::SessionId,
2345    ) -> Result<()>;
2346
2347    /// Record the terminal result once the child has completed.
2348    ///
2349    /// `claim_token` must match the stored token. `terminal_status` is the
2350    /// `wait_for_idle` return value ("idle", "error", "timeout", etc.) and
2351    /// `terminal_result` is the last agent message.
2352    async fn settle_spawn(
2353        &self,
2354        parent_session_id: crate::typed_id::SessionId,
2355        tool_call_id: &str,
2356        claim_token: uuid::Uuid,
2357        terminal_status: &str,
2358        terminal_result: &str,
2359    ) -> Result<()>;
2360}
2361
2362/// Blanket impl: `Arc<S>` delegates to the inner store.
2363#[async_trait]
2364impl<S: SubagentSpawnStore + ?Sized> SubagentSpawnStore for Arc<S> {
2365    async fn try_claim_spawn(
2366        &self,
2367        parent_session_id: crate::typed_id::SessionId,
2368        tool_call_id: &str,
2369        claim_token: uuid::Uuid,
2370    ) -> Result<SpawnClaimResult> {
2371        (**self)
2372            .try_claim_spawn(parent_session_id, tool_call_id, claim_token)
2373            .await
2374    }
2375
2376    async fn register_child_session(
2377        &self,
2378        spawn_handle_id: uuid::Uuid,
2379        claim_token: uuid::Uuid,
2380        child_session_id: crate::typed_id::SessionId,
2381    ) -> Result<()> {
2382        (**self)
2383            .register_child_session(spawn_handle_id, claim_token, child_session_id)
2384            .await
2385    }
2386
2387    async fn settle_spawn(
2388        &self,
2389        parent_session_id: crate::typed_id::SessionId,
2390        tool_call_id: &str,
2391        claim_token: uuid::Uuid,
2392        terminal_status: &str,
2393        terminal_result: &str,
2394    ) -> Result<()> {
2395        (**self)
2396            .settle_spawn(
2397                parent_session_id,
2398                tool_call_id,
2399                claim_token,
2400                terminal_status,
2401                terminal_result,
2402            )
2403            .await
2404    }
2405}
2406
2407/// No-op spawn store — used when no durable store is configured (dev/test).
2408///
2409/// Always claims (no dedup); settle and register are no-ops.
2410pub struct NoopSubagentSpawnStore;
2411
2412#[async_trait]
2413impl SubagentSpawnStore for NoopSubagentSpawnStore {
2414    async fn try_claim_spawn(
2415        &self,
2416        _parent_session_id: crate::typed_id::SessionId,
2417        _tool_call_id: &str,
2418        claim_token: uuid::Uuid,
2419    ) -> Result<SpawnClaimResult> {
2420        Ok(SpawnClaimResult::Claimed {
2421            spawn_handle_id: uuid::Uuid::new_v4(),
2422            claim_token,
2423        })
2424    }
2425
2426    async fn register_child_session(
2427        &self,
2428        _spawn_handle_id: uuid::Uuid,
2429        _claim_token: uuid::Uuid,
2430        _child_session_id: crate::typed_id::SessionId,
2431    ) -> Result<()> {
2432        Ok(())
2433    }
2434
2435    async fn settle_spawn(
2436        &self,
2437        _parent_session_id: crate::typed_id::SessionId,
2438        _tool_call_id: &str,
2439        _claim_token: uuid::Uuid,
2440        _terminal_status: &str,
2441        _terminal_result: &str,
2442    ) -> Result<()> {
2443        Ok(())
2444    }
2445}
2446
2447// ============================================================================
2448// Tests
2449// ============================================================================
2450
2451#[cfg(test)]
2452mod tests {
2453    use super::*;
2454
2455    #[test]
2456    fn test_resolved_image_new() {
2457        let image = ResolvedImage::new("SGVsbG8=", "image/png");
2458        assert_eq!(image.base64, "SGVsbG8=");
2459        assert_eq!(image.media_type, "image/png");
2460    }
2461
2462    #[test]
2463    fn test_resolved_image_to_data_url() {
2464        let image = ResolvedImage::new("SGVsbG8=", "image/png");
2465        let data_url = image.to_data_url();
2466        assert_eq!(data_url, "data:image/png;base64,SGVsbG8=");
2467    }
2468
2469    #[test]
2470    fn test_resolved_image_jpeg() {
2471        let image = ResolvedImage::new("base64data", "image/jpeg");
2472        let data_url = image.to_data_url();
2473        assert!(data_url.starts_with("data:image/jpeg;base64,"));
2474    }
2475}