Skip to main content

infinity_agent_core/tools/
thread.rs

1use async_trait::async_trait;
2use infinity_provider_protocol::message::{Text, ToolResult, ToolResultContent, UserContent};
3use rap_protocol::ThreadId;
4use tracing;
5
6use super::{Tool, ToolContext, send_tool_error};
7use crate::message::{InputMessage, InputMessageContent, SyntheticKind, TaggedSyntheticKind};
8use crate::traits::{ConversationStore, InputSender};
9use rap_client::http::HttpClient;
10use rap_client::notifier::RapNotifier;
11
12/// Tool that spawns a new child thread and returns its ID.
13pub struct SpawnThreadTool<C: ConversationStore> {
14    pub conversation_store: C,
15}
16
17#[async_trait]
18impl<M: InputSender + 'static, C: ConversationStore + 'static> Tool<M> for SpawnThreadTool<C> {
19    fn name(&self) -> &str {
20        "spawn_thread"
21    }
22
23    fn description(&self) -> &str {
24        "Spawn a new child thread for a sub-task. The new thread inherits the conversation context of the current thread and will see its tasks automatically. Returns the new thread ID."
25    }
26
27    fn parameters(&self) -> serde_json::Value {
28        serde_json::json!({
29            "type": "object",
30            "properties": {
31                "instructions": {
32                    "type": "string",
33                    "description": "Instructions for the spawned thread describing what it should do. Make sure to include in the instructions what **you plan to do while the thread runs** to make sure the child thread doesn't accidentally duplicate your work."
34                },
35                "child_of": {
36                    "type": "array",
37                    "items": { "type": "string" },
38                    "description": "The thread stack that you are spawning from, used for validation. Pass the full thread stack from root to current thread. For example, if you are the root thread 'R', pass [\"R\"]. If you are child 'A' of root 'R', pass [\"R\", \"A\"]."
39                }
40            },
41            "required": ["instructions", "child_of"]
42        })
43    }
44
45    async fn execute(
46        &self,
47        _args: serde_json::Value,
48        _id: String,
49        _call_id: Option<String>,
50        _context: &ToolContext<M>,
51    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
52        Ok(())
53    }
54
55    fn supports_sync(&self) -> bool {
56        true
57    }
58
59    async fn execute_synchronous(
60        &self,
61        args: &serde_json::Value,
62        id: &str,
63        call_id: Option<&str>,
64        context: &ToolContext<M>,
65    ) -> Option<ToolResult> {
66        // Validate child_of matches the actual thread stack
67        let child_of: Vec<ThreadId> = args
68            .get("child_of")
69            .and_then(|v| serde_json::from_value(v.clone()).ok())
70            .unwrap_or_default();
71
72        if child_of != context.thread_stack {
73            return Some(ToolResult {
74                id: id.to_owned(),
75                call_id: call_id.map(|c| c.to_owned()),
76                content: vec![ToolResultContent::Text(Text {
77                    text: format!(
78                        "Error: child_of {:?} does not match the actual thread stack {:?}. You may be confused and think you are in the parent thread, but you are not. You are in thread {}. Do NOT spawn threads — focus on your assigned task.",
79                        child_of, context.thread_stack, context.group_id
80                    ),
81                })],
82            });
83        }
84
85        let new_thread_id = match self
86            .conversation_store
87            .spawn_thread(&context.group_id, id, false, None)
88            .await
89        {
90            Ok(id) => id,
91            Err(e) => {
92                tracing::error!("failed to spawn thread in conversation store: {e}");
93                return Some(ToolResult {
94                    id: id.to_owned(),
95                    call_id: call_id.map(|c| c.to_owned()),
96                    content: vec![ToolResultContent::Text(Text {
97                        text: format!("Error: failed to spawn thread: {e}"),
98                    })],
99                });
100            }
101        };
102
103        tracing::info!(
104            "Spawned new thread {} from parent {}",
105            new_thread_id,
106            context.group_id
107        );
108
109        let parent_result = ToolResult {
110            id: id.to_owned(),
111            call_id: call_id.map(|c| c.to_owned()),
112            content: vec![ToolResultContent::Text(Text {
113                text: format!(
114                    "Child thread is successfully spawned and has ID: {}. You will be notified automatically when the child has anything to report. Make sure that you **do not** do the task assigned to the child thread.",
115                    new_thread_id
116                ),
117            })],
118        };
119
120        let instructions = args
121            .get("instructions")
122            .expect("bug: missing 'instructions' arg")
123            .as_str()
124            .expect("bug: 'instructions' arg is not a string");
125
126        let child_result = InputMessage {
127            content: InputMessageContent::User(UserContent::ToolResult(ToolResult {
128                id: id.to_owned(),
129                call_id: call_id.map(|c| c.to_owned()),
130                content: vec![ToolResultContent::Text(Text {
131                    text: format!(
132                        "You are now INSIDE the thread that you requested to create. Your thread ID is {}. Your next task is to exactly follow these instructions: {}\n. Start by repeating to yourself the instructions, ignoring thinking from the parent context. Make sure to not be confused by the parent context. If the parent was planning to spawn more threads, you should not.",
133                        new_thread_id, instructions
134                    ),
135                })],
136            })),
137            group_id: new_thread_id,
138            metadata: None,
139            synthetic: None,
140            display_as: None,
141            subscription: false,
142        };
143
144        context
145            .message_sender
146            .send_to_input_queue(child_result, id)
147            .await
148            .expect("failed to send child thread message to input queue");
149
150        Some(parent_result)
151    }
152}
153
154/// Tool that sends a report to the parent thread without closing the current thread.
155pub struct ReportToParentTool<C: ConversationStore> {
156    pub conversation_store: C,
157}
158
159#[async_trait]
160impl<M: InputSender + 'static, C: ConversationStore + 'static> Tool<M> for ReportToParentTool<C> {
161    fn name(&self) -> &str {
162        "report_to_parent"
163    }
164
165    fn description(&self) -> &str {
166        "Send a report to the parent thread. Use this when you have intermediate results, updates, or information the parent should know about while you continue working."
167    }
168
169    fn parameters(&self) -> serde_json::Value {
170        serde_json::json!({
171            "type": "object",
172            "properties": {
173                "report": {
174                    "type": "string",
175                    "description": "The report content to send to the parent thread."
176                }
177            },
178            "required": ["report"]
179        })
180    }
181
182    async fn execute(
183        &self,
184        args: serde_json::Value,
185        id: String,
186        call_id: Option<String>,
187        context: &ToolContext<M>,
188    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
189        let Some(report_text) = args["report"].as_str() else {
190            return send_tool_error(context, &id, call_id, "report is required").await;
191        };
192
193        let Some((parent_id, spawn_tool_call_id)) = self
194            .conversation_store
195            .get_thread_parent_info(&context.group_id)
196            .await
197            .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?
198        else {
199            return send_tool_error(
200                context,
201                &id,
202                call_id,
203                "No parent thread found — this is a root thread",
204            )
205            .await;
206        };
207
208        let is_subscription = self
209            .conversation_store
210            .is_subscription_event_thread(&context.group_id)
211            .await
212            .unwrap_or(false);
213
214        tracing::info!(
215            "Sending report from thread {} to parent {} via tool call {}",
216            context.group_id,
217            parent_id,
218            spawn_tool_call_id
219        );
220
221        let formatted_report = if is_subscription {
222            format!(
223                "Report from temporary child thread created to process a subscription event:\n{}",
224                report_text
225            )
226        } else {
227            format!("Report from child thread: {}", report_text)
228        };
229
230        let report_message = InputMessage {
231            content: InputMessageContent::User(UserContent::ToolResult(ToolResult {
232                id: String::new(),
233                call_id: None,
234                content: vec![ToolResultContent::Text(Text {
235                    text: formatted_report,
236                })],
237            })),
238            group_id: parent_id,
239            metadata: None,
240            synthetic: Some(SyntheticKind::Tagged(TaggedSyntheticKind::ThreadReport {
241                tool_call_id: spawn_tool_call_id,
242                child_thread_id: context.group_id.clone(),
243            })),
244            display_as: None,
245            subscription: false,
246        };
247
248        context
249            .message_sender
250            .send_to_input_queue(report_message, &id)
251            .await?;
252
253        let tool_result = InputMessage {
254            content: InputMessageContent::User(UserContent::ToolResult(ToolResult {
255                id: id.clone(),
256                call_id,
257                content: vec![ToolResultContent::Text(Text {
258                    text: "Report sent to parent thread.".to_owned(),
259                })],
260            })),
261            group_id: context.group_id.clone(),
262            metadata: None,
263            synthetic: None,
264            display_as: None,
265            subscription: false,
266        };
267
268        context
269            .message_sender
270            .send_to_input_queue(tool_result, &id)
271            .await?;
272
273        Ok(())
274    }
275}
276
277/// Tool that closes a thread, returning control to the parent.
278pub struct CloseThreadTool<C: ConversationStore, H: HttpClient> {
279    pub conversation_store: C,
280    /// Optional notifier that informs RAP tool servers about the thread closure.
281    /// Best-effort: failures are logged but do not prevent the thread from closing.
282    pub rap_notifier: Option<RapNotifier<H>>,
283}
284
285#[async_trait]
286impl<M: InputSender + 'static, C: ConversationStore + 'static, H: HttpClient + 'static> Tool<M>
287    for CloseThreadTool<C, H>
288{
289    fn name(&self) -> &str {
290        "close_thread"
291    }
292
293    fn description(&self) -> &str {
294        "Permanently shuts down the specified thread, marking it as complete. Use this from a thread that wants to close itself. Make sure to cancel any subscriptions you created before calling this. If the thread has additional information has not already been reported to the parent, include it in report_to_parent. Omit report_to_parent if there is nothing worth reporting."
295    }
296
297    fn parameters(&self) -> serde_json::Value {
298        serde_json::json!({
299            "type": "object",
300            "properties": {
301                "thread_id": {
302                    "type": "string",
303                    "description": "The ID of the thread to close."
304                },
305                "report_to_parent": {
306                    "type": "string",
307                    "description": "Optional report to send to the parent thread."
308                }
309            },
310            "required": ["thread_id"]
311        })
312    }
313
314    async fn execute(
315        &self,
316        args: serde_json::Value,
317        id: String,
318        call_id: Option<String>,
319        context: &ToolContext<M>,
320    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
321        let Some(thread_id) = args["thread_id"].as_str() else {
322            return send_tool_error(context, &id, call_id, "thread_id is required").await;
323        };
324        let thread_id = ThreadId::from(thread_id);
325
326        if thread_id != context.group_id {
327            return send_tool_error(
328                context,
329                &id,
330                call_id,
331                format!(
332                    "the provided thread ID to close {} does not match the current thread ID {}",
333                    thread_id, context.group_id
334                ),
335            )
336            .await;
337        }
338
339        // Prevent closing the root thread
340        let Some((parent_id, spawn_tool_call_id)) = self
341            .conversation_store
342            .get_thread_parent_info(&thread_id)
343            .await
344            .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?
345        else {
346            return send_tool_error(
347                context,
348                &id,
349                call_id,
350                "cannot close the root thread. Only child threads can be closed.",
351            )
352            .await;
353        };
354
355        let report = args.get("report_to_parent").and_then(|v| v.as_str());
356
357        self.conversation_store
358            .close_thread(&thread_id)
359            .await
360            .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?;
361
362        tracing::info!("Closed thread {}", thread_id);
363
364        // Handle compaction threads: store summary and skip normal parent reporting
365        let is_compaction = self
366            .conversation_store
367            .is_compaction_thread(&thread_id)
368            .await
369            .unwrap_or(false);
370
371        if is_compaction {
372            if let Some(report_text) = report {
373                let up_to_order = self
374                    .conversation_store
375                    .get_thread_spawn_order(&thread_id)
376                    .await
377                    .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?
378                    .unwrap_or(0);
379                self.conversation_store
380                    .save_compaction_summary(&parent_id, report_text, up_to_order)
381                    .await
382                    .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?;
383                tracing::info!(
384                    "Stored compaction summary for thread {} up to order {}",
385                    parent_id,
386                    up_to_order
387                );
388            }
389
390            // Notify the parent thread to apply the compaction
391            let notify_msg = InputMessage {
392                content: InputMessageContent::User(UserContent::ToolResult(ToolResult {
393                    id: String::new(),
394                    call_id: None,
395                    content: vec![ToolResultContent::Text(Text {
396                        text: "Compaction complete".to_owned(),
397                    })],
398                })),
399                group_id: parent_id,
400                metadata: None,
401                synthetic: Some(SyntheticKind::Tagged(
402                    TaggedSyntheticKind::CompactionComplete,
403                )),
404                display_as: None,
405                subscription: false,
406            };
407            context
408                .message_sender
409                .send_to_input_queue(notify_msg, &id)
410                .await?;
411            if let Some(ref notifier) = self.rap_notifier {
412                notifier.notify_thread_closed(&thread_id).await;
413            }
414            return Ok(());
415        }
416
417        let is_subscription = self
418            .conversation_store
419            .is_subscription_event_thread(&thread_id)
420            .await
421            .unwrap_or(false);
422
423        let report_text = if is_subscription {
424            report.map(|report_text| format!(
425                    "An event from your subscription {} was processed by a child thread {}. The subscription remains active. Report from the child:\n{}",
426                    spawn_tool_call_id, thread_id, report_text
427                ))
428        } else if let Some(report_text) = report {
429            Some(format!(
430                "Child thread with ID {} has shut down. Report from child thread: {}",
431                thread_id, report_text
432            ))
433        } else {
434            Some(format!("Child thread with ID {} has shut down", thread_id))
435        };
436
437        if let Some(report_text) = report_text {
438            tracing::info!(
439                "Sending report from thread {} to parent {} via tool call {}",
440                thread_id,
441                parent_id,
442                spawn_tool_call_id
443            );
444
445            let report_message = InputMessage {
446                content: InputMessageContent::User(UserContent::ToolResult(ToolResult {
447                    id: String::new(),
448                    call_id: None,
449                    content: vec![ToolResultContent::Text(Text { text: report_text })],
450                })),
451                group_id: parent_id,
452                metadata: None,
453                synthetic: Some(SyntheticKind::Tagged(TaggedSyntheticKind::ThreadReport {
454                    tool_call_id: spawn_tool_call_id,
455                    child_thread_id: thread_id.clone(),
456                })),
457                display_as: None,
458                subscription: false,
459            };
460
461            context
462                .message_sender
463                .send_to_input_queue(report_message, &id)
464                .await?;
465        }
466
467        // Best-effort: notify RAP tool servers that this thread has been closed
468        // so they can clean up thread-specific resources (e.g. sandboxes).
469        if let Some(ref notifier) = self.rap_notifier {
470            notifier.notify_thread_closed(&thread_id).await;
471        }
472
473        Ok(())
474    }
475}
476
477/// Tool that sends a message to a child thread, injected inline into its history.
478pub struct SendMessageToChildTool<C: ConversationStore> {
479    pub conversation_store: C,
480}
481
482#[async_trait]
483impl<M: InputSender + 'static, C: ConversationStore + 'static> Tool<M>
484    for SendMessageToChildTool<C>
485{
486    fn name(&self) -> &str {
487        "send_message_to_child"
488    }
489
490    fn description(&self) -> &str {
491        "Send a message to a child thread. The message will be injected inline into the child's conversation history."
492    }
493
494    fn parameters(&self) -> serde_json::Value {
495        serde_json::json!({
496            "type": "object",
497            "properties": {
498                "thread_id": {
499                    "type": "string",
500                    "description": "The ID of the child thread to send the message to."
501                },
502                "message": {
503                    "type": "string",
504                    "description": "The message content to send to the child thread."
505                }
506            },
507            "required": ["thread_id", "message"]
508        })
509    }
510
511    async fn execute(
512        &self,
513        args: serde_json::Value,
514        id: String,
515        call_id: Option<String>,
516        context: &ToolContext<M>,
517    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
518        let Some(child_thread_id) = args["thread_id"].as_str().map(ThreadId::from) else {
519            return send_tool_error(context, &id, call_id, "thread_id is required").await;
520        };
521        let Some(message_text) = args["message"].as_str() else {
522            return send_tool_error(context, &id, call_id, "message is required").await;
523        };
524
525        let Some((parent_id, spawn_tool_call_id)) = self
526            .conversation_store
527            .get_thread_parent_info(&child_thread_id)
528            .await
529            .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?
530        else {
531            return send_tool_error(
532                context,
533                &id,
534                call_id,
535                "Child thread not found or has no parent",
536            )
537            .await;
538        };
539
540        if parent_id != context.group_id {
541            return send_tool_error(
542                context,
543                &id,
544                call_id,
545                format!(
546                    "thread {} is not a child of the current thread {}",
547                    child_thread_id, context.group_id
548                ),
549            )
550            .await;
551        }
552
553        tracing::info!(
554            "Sending message from parent {} to child thread {} via tool call {}",
555            context.group_id,
556            child_thread_id,
557            spawn_tool_call_id
558        );
559
560        let child_message = InputMessage {
561            content: InputMessageContent::User(UserContent::ToolResult(ToolResult {
562                id: String::new(),
563                call_id: None,
564                content: vec![ToolResultContent::Text(Text {
565                    text: format!("Message from parent thread: {}", message_text),
566                })],
567            })),
568            group_id: child_thread_id.clone(),
569            metadata: None,
570            synthetic: Some(SyntheticKind::Tagged(TaggedSyntheticKind::ParentMessage {
571                tool_call_id: spawn_tool_call_id,
572            })),
573            display_as: None,
574            subscription: false,
575        };
576
577        context
578            .message_sender
579            .send_to_input_queue(child_message, &id)
580            .await?;
581
582        let tool_result = InputMessage {
583            content: InputMessageContent::User(UserContent::ToolResult(ToolResult {
584                id: id.clone(),
585                call_id,
586                content: vec![ToolResultContent::Text(Text {
587                    text: "Message sent to child thread.".to_owned(),
588                })],
589            })),
590            group_id: context.group_id.clone(),
591            metadata: None,
592            synthetic: None,
593            display_as: None,
594            subscription: false,
595        };
596
597        context
598            .message_sender
599            .send_to_input_queue(tool_result, &id)
600            .await?;
601
602        Ok(())
603    }
604}