Skip to main content

infinity_agent_core/
traits.rs

1use async_trait::async_trait;
2use infinity_provider_protocol::message::AssistantContent;
3
4use rap_protocol::ThreadId;
5
6use crate::message::{InfinityMessage, InputMessage};
7use crate::system::UserChoice;
8
9/// Persistent conversation history storage (DSQL in Lambda, in-memory for CLI).
10#[async_trait]
11pub trait ConversationStore: Send + Sync + Clone {
12    type Error: std::error::Error + Send + Sync + 'static;
13
14    async fn ensure_root_thread(&self, thread_id: &ThreadId<str>) -> Result<(), Self::Error>;
15
16    /// Return whether an exact root or child thread record exists without
17    /// creating it.
18    async fn thread_exists(&self, thread_id: &ThreadId<str>) -> Result<bool, Self::Error>;
19
20    /// Load history for a session. `start_from` (exclusive) and `up_to`
21    /// (inclusive) are optional bounds on message order. `None` means unbounded.
22    async fn load_history_up_to(
23        &self,
24        session_id: &ThreadId<str>,
25        start_from: Option<i64>,
26        up_to: Option<i64>,
27    ) -> Result<Vec<InfinityMessage>, Self::Error>;
28
29    /// Load full history for a thread including ancestor context and compaction.
30    /// Walks backwards through ancestors to find the most recent compaction
31    /// summary, skipping all earlier ancestors (their content is in the summary).
32    /// Returns `(history, leaf_compacted_up_to, ancestor_prefix_len)` where the
33    /// second element is the absolute store index the leaf thread's compaction
34    /// covers (if any), and the third is how many messages at the front of the
35    /// history come from ancestors (not this thread's own store).
36    async fn load_history_with_ancestors(
37        &self,
38        thread_id: &ThreadId<str>,
39    ) -> Result<(Vec<InfinityMessage>, Option<i64>, usize), Self::Error> {
40        // Check the thread itself first
41        if let Ok(Some((summary, compacted_up_to))) = self
42            .load_latest_compaction_summary_up_to(thread_id, None)
43            .await
44        {
45            let mut combined = vec![InfinityMessage::Assistant {
46                content: AssistantContent::text(format!(
47                    "[Compacted conversation summary]\n{}",
48                    summary
49                )),
50            }];
51            combined.extend(
52                self.load_history_up_to(thread_id, Some(compacted_up_to), None)
53                    .await?,
54            );
55            return Ok((combined, Some(compacted_up_to), 0));
56        }
57
58        let ancestors = self.get_ancestor_chain(thread_id).await?;
59
60        // Walk backwards to find the first ancestor with a compaction summary
61        let mut compaction_idx = None;
62        let mut compaction_summary = None;
63        for i in (0..ancestors.len()).rev() {
64            let (ref tid, cutoff) = ancestors[i];
65            if let Ok(Some((summary, compacted_up_to))) = self
66                .load_latest_compaction_summary_up_to(tid, Some(cutoff))
67                .await
68            {
69                compaction_idx = Some(i);
70                compaction_summary = Some((summary, compacted_up_to));
71                break;
72            }
73        }
74
75        let mut combined = Vec::new();
76
77        if let (Some(idx), Some((summary, compacted_up_to))) = (compaction_idx, compaction_summary)
78        {
79            // Prepend the compaction summary (covers all ancestors before idx + ancestor idx's messages up to compacted_up_to)
80            combined.push(InfinityMessage::Assistant {
81                content: AssistantContent::text(format!(
82                    "[Compacted conversation summary]\n{}",
83                    summary
84                )),
85            });
86            // Load remaining messages from the compacted ancestor (after summary, up to cutoff)
87            let (_, cutoff) = &ancestors[idx];
88            combined.extend(
89                self.load_history_up_to(&ancestors[idx].0, Some(compacted_up_to), Some(*cutoff))
90                    .await?,
91            );
92            // Load subsequent ancestors normally
93            for (tid, cutoff) in &ancestors[idx + 1..] {
94                combined.extend(self.load_history_up_to(tid, None, Some(*cutoff)).await?);
95            }
96        } else {
97            // No compaction anywhere — load all ancestors
98            for (tid, cutoff) in &ancestors {
99                combined.extend(self.load_history_up_to(tid, None, Some(*cutoff)).await?);
100            }
101        }
102
103        let ancestor_prefix_len = combined.len();
104        combined.extend(self.load_history_up_to(thread_id, None, None).await?);
105        Ok((combined, None, ancestor_prefix_len))
106    }
107
108    async fn append_messages(
109        &self,
110        session_id: &ThreadId<str>,
111        messages: Vec<(InfinityMessage, String)>,
112    ) -> Result<(), Self::Error>;
113
114    async fn spawn_thread(
115        &self,
116        parent_thread_id: &ThreadId<str>,
117        spawn_tool_call_id: &str,
118        is_for_subscription_event: bool,
119        spawn_order_override: Option<usize>,
120    ) -> Result<ThreadId, Self::Error>;
121
122    async fn is_thread_closed(&self, thread_id: &ThreadId<str>) -> Result<bool, Self::Error>;
123
124    async fn close_thread(&self, thread_id: &ThreadId<str>) -> Result<(), Self::Error>;
125
126    async fn is_subscription_event_thread(
127        &self,
128        thread_id: &ThreadId<str>,
129    ) -> Result<bool, Self::Error>;
130
131    async fn get_thread_parent_info(
132        &self,
133        thread_id: &ThreadId<str>,
134    ) -> Result<Option<(ThreadId, String)>, Self::Error>;
135
136    async fn get_ancestor_chain(
137        &self,
138        thread_id: &ThreadId<str>,
139    ) -> Result<Vec<(ThreadId, i64)>, Self::Error>;
140
141    // ── Compaction support ──
142
143    async fn mark_thread_as_compaction(&self, thread_id: &ThreadId<str>)
144    -> Result<(), Self::Error>;
145
146    async fn is_compaction_thread(&self, thread_id: &ThreadId<str>) -> Result<bool, Self::Error>;
147
148    async fn get_thread_spawn_order(
149        &self,
150        thread_id: &ThreadId<str>,
151    ) -> Result<Option<i64>, Self::Error>;
152
153    async fn save_compaction_summary(
154        &self,
155        thread_id: &ThreadId<str>,
156        summary: &str,
157        up_to_order: i64,
158    ) -> Result<(), Self::Error>;
159
160    /// Load the latest compaction summary. When `up_to_order` is `Some(n)`,
161    /// only return summaries whose `up_to_order` is <= n.
162    async fn load_latest_compaction_summary_up_to(
163        &self,
164        thread_id: &ThreadId<str>,
165        up_to_order: Option<i64>,
166    ) -> Result<Option<(String, i64)>, Self::Error>;
167}
168
169/// Key-value state store for processed message IDs, metadata, toolset caches
170/// (DynamoDB in Lambda, in-memory HashMap for CLI).
171#[async_trait]
172pub trait StateStore: Send + Sync + Clone {
173    type Error: std::error::Error + Send + Sync + 'static;
174
175    /// Durably deduplicated message IDs for this thread. Only inputs that are
176    /// not naturally idempotent are tracked (user text and subscription
177    /// events); tool results are deduplicated against history itself.
178    async fn get_processed_ids(
179        &self,
180        thread_id: &ThreadId<str>,
181    ) -> Result<std::collections::HashSet<String>, Self::Error>;
182
183    async fn add_processed_message_ids(
184        &self,
185        thread_id: &ThreadId<str>,
186        message_ids: Vec<String>,
187    ) -> Result<(), Self::Error>;
188
189    async fn get_metadata(
190        &self,
191        root_thread_id: &ThreadId<str>,
192    ) -> Result<Option<serde_json::Value>, Self::Error>;
193
194    async fn set_metadata(
195        &self,
196        root_thread_id: &ThreadId<str>,
197        metadata: serde_json::Value,
198    ) -> Result<(), Self::Error>;
199
200    /// Return the list of active subscription tool_call_ids for a specific thread.
201    async fn get_active_subscriptions(
202        &self,
203        thread_id: &ThreadId<str>,
204    ) -> Result<Vec<String>, Self::Error>;
205
206    /// Record a new active subscription (tool_call_id) for a specific thread.
207    async fn add_active_subscription(
208        &self,
209        thread_id: &ThreadId<str>,
210        tool_call_id: &str,
211    ) -> Result<(), Self::Error>;
212
213    /// Remove an active subscription (tool_call_id) from a specific thread.
214    async fn remove_active_subscription(
215        &self,
216        thread_id: &ThreadId<str>,
217        tool_call_id: &str,
218    ) -> Result<(), Self::Error>;
219
220    /// Add or replace a pending user choice for one thread.
221    async fn add_pending_user_choice(
222        &self,
223        thread_id: &ThreadId<str>,
224        choice: UserChoice,
225    ) -> Result<(), Self::Error>;
226
227    /// Remove a pending user choice after it is answered or interrupted.
228    async fn remove_pending_user_choice(
229        &self,
230        thread_id: &ThreadId<str>,
231        choice_id: &str,
232    ) -> Result<(), Self::Error>;
233
234    /// List choices awaiting a response for one thread.
235    async fn get_pending_user_choices(
236        &self,
237        thread_id: &ThreadId<str>,
238    ) -> Result<Vec<UserChoice>, Self::Error>;
239
240    /// Whether an existing thread has been explicitly stopped.
241    ///
242    /// The local router consults this before spawning a driver for input that
243    /// cannot legitimately resume a stopped thread: synthetic subscription
244    /// events and thread reports, tool results, OAuth completions, and user
245    /// choices. Returning `true` drops such input before a driver is spawned.
246    /// Plain user text is never gated by this method because sending new text
247    /// is how a user resumes a stopped thread.
248    ///
249    /// `thread_id` is the target thread itself, not necessarily its root.
250    /// Implementations that track stopped state per conversation may resolve
251    /// the root themselves. Stores without stopped-thread policy inherit the
252    /// default `false` response.
253    async fn is_thread_stopped(&self, _thread_id: &ThreadId<str>) -> Result<bool, Self::Error> {
254        Ok(false)
255    }
256}
257
258/// Abstraction over input message delivery (SQS in Lambda, channel/direct in CLI).
259#[async_trait]
260pub trait InputSender: Send + Sync + Clone {
261    type Error: std::error::Error + Send + Sync + 'static;
262
263    /// Send a message to the input queue for processing.
264    async fn send_to_input_queue(
265        &self,
266        message: InputMessage,
267        dedup_id: &str,
268    ) -> Result<(), Self::Error>;
269}