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::{
8    InfinityMessage, InputMessage, InputMessageContent, SyntheticKind, TaggedSyntheticKind,
9};
10use crate::traits::{ConversationStore, InputSender, SpawnContext};
11use rap_client::http::HttpClient;
12use rap_client::notifier::RapNotifier;
13
14/// Tool that spawns a new child thread and returns its ID.
15pub struct SpawnThreadTool<C: ConversationStore> {
16    pub conversation_store: C,
17}
18
19#[async_trait]
20impl<M: InputSender + 'static, C: ConversationStore + 'static> Tool<M> for SpawnThreadTool<C> {
21    fn name(&self) -> &str {
22        "spawn_thread"
23    }
24
25    fn description(&self) -> &str {
26        "Spawn a new child thread for a sub-task. By default the new thread inherits the conversation context of the current thread and will see its tasks automatically. Pass fresh_context: true to spawn a subagent WITHOUT the inherited context. Returns the new thread ID."
27    }
28
29    fn parameters(&self) -> serde_json::Value {
30        serde_json::json!({
31            "type": "object",
32            "properties": {
33                "instructions": {
34                    "type": "string",
35                    "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."
36                },
37                "child_of": {
38                    "type": "array",
39                    "items": { "type": "string" },
40                    "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\"]."
41                },
42                "fresh_context": {
43                    "type": "boolean",
44                    "description": "If true, the child thread starts with a FRESH (empty) context: it does NOT inherit the conversation history of this thread or its ancestors. Use this for independent sub-tasks where the accumulated context would be irrelevant or distracting. The instructions must then be fully self-contained: include all relevant file paths, IDs, requirements, and background the child needs. Defaults to false (full context inheritance)."
45                }
46            },
47            "required": ["instructions", "child_of"]
48        })
49    }
50
51    async fn execute(
52        &self,
53        _args: serde_json::Value,
54        _id: rap_protocol::ToolCallId,
55        _call_id: Option<rap_protocol::ProviderCallId>,
56        _context: &ToolContext<M>,
57    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
58        Ok(())
59    }
60
61    fn supports_sync(&self) -> bool {
62        true
63    }
64
65    async fn execute_synchronous(
66        &self,
67        args: &serde_json::Value,
68        id: &rap_protocol::ToolCallId<str>,
69        call_id: Option<&rap_protocol::ProviderCallId<str>>,
70        context: &ToolContext<M>,
71    ) -> Option<ToolResult> {
72        // Validate child_of matches the actual thread stack
73        let child_of: Vec<ThreadId> = args
74            .get("child_of")
75            .and_then(|v| serde_json::from_value(v.clone()).ok())
76            .unwrap_or_default();
77
78        if child_of != context.thread_stack {
79            return Some(ToolResult {
80                id: id.as_str().to_owned(),
81                call_id: call_id.map(|c| c.as_str().to_owned()),
82                content: vec![ToolResultContent::Text(Text {
83                    text: format!(
84                        "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.",
85                        child_of, context.thread_stack, context.group_id
86                    ),
87                })],
88            });
89        }
90
91        let error_result = |text: String| {
92            Some(ToolResult {
93                id: id.as_str().to_owned(),
94                call_id: call_id.map(|c| c.as_str().to_owned()),
95                content: vec![ToolResultContent::Text(Text { text })],
96            })
97        };
98
99        let fresh_context = args
100            .get("fresh_context")
101            .and_then(|v| v.as_bool())
102            .unwrap_or(false);
103        // Spawn the child right *before* the spawn call and give the child
104        // its own copy of the call (seeded below), instead of letting the
105        // child see the parent's copy through its inherited slice. The child
106        // then owns the call its seed instructions (and later parent
107        // messages) resolve against, even after the parent's copy — or the
108        // child's inherited prefix — is folded into a compaction summary.
109        let spawn_context = if fresh_context {
110            SpawnContext::Fresh
111        } else {
112            // spawn_thread only executes synchronously, and the runtime
113            // always provides the safe spawn point on that path.
114            SpawnContext::InheritUpTo(context.safe_spawn_point.expect(
115                "bug: spawn_thread executed without a safe spawn point in the tool context",
116            ))
117        };
118
119        let new_thread_id = match self
120            .conversation_store
121            .spawn_thread(&context.group_id, id, false, spawn_context)
122            .await
123        {
124            Ok(id) => id,
125            Err(e) => {
126                tracing::error!("failed to spawn thread in conversation store: {e}");
127                return error_result(format!("Error: failed to spawn thread: {e}"));
128            }
129        };
130
131        tracing::info!(
132            "Spawned new thread {} from parent {} (fresh_context: {})",
133            new_thread_id,
134            context.group_id,
135            fresh_context
136        );
137
138        let instructions = args
139            .get("instructions")
140            .expect("bug: missing 'instructions' arg")
141            .as_str()
142            .expect("bug: 'instructions' arg is not a string");
143
144        // Write the child's own copy of the spawn call into its (so far
145        // empty) store, pairing with the instruction tool result sent below.
146        // Fresh threads need it because they inherit nothing; inherit
147        // threads because their cutoff excludes the parent's copy (see
148        // `spawn_context` above). The call is duplicated verbatim — same
149        // provider call_id and arguments — so the child's model-facing
150        // history is exactly what the provider originally emitted.
151        let spawn_tool_call = InfinityMessage::ToolCall {
152            call: infinity_provider_protocol::message::ToolCall {
153                id: id.as_str().to_owned(),
154                call_id: call_id.map(|c| c.as_str().to_owned()),
155                function: infinity_provider_protocol::message::ToolFunction {
156                    name: "spawn_thread".to_owned(),
157                    arguments: args.clone(),
158                },
159            },
160            display_as: None,
161        };
162        if let Err(e) = self
163            .conversation_store
164            .append_messages(
165                &new_thread_id,
166                vec![(spawn_tool_call, format!("{}-spawn-call", id))],
167            )
168            .await
169        {
170            tracing::error!("failed to seed child thread with spawn call: {e}");
171            return error_result(format!("Error: failed to seed child thread: {e}"));
172        }
173
174        let child_instructions = if fresh_context {
175            format!(
176                "You are now INSIDE a newly created thread with a FRESH context. Your thread ID is {}. You do NOT inherit any conversation history from your parent thread: the instructions above are your ONLY context, so do not assume any other background. Follow the instructions exactly. Use report_to_parent to send results to the parent, and call close_thread with your thread ID when you are done.",
177                new_thread_id
178            )
179        } else {
180            format!(
181                "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.",
182                new_thread_id, instructions
183            )
184        };
185
186        let child_result = InputMessage {
187            content: InputMessageContent::User(UserContent::ToolResult(ToolResult {
188                id: id.as_str().to_owned(),
189                // Must match the seeded call's call_id (preserved above).
190                call_id: call_id.map(|c| c.as_str().to_owned()),
191                content: vec![ToolResultContent::Text(Text {
192                    text: child_instructions,
193                })],
194            })),
195            group_id: new_thread_id.clone(),
196            metadata: None,
197            synthetic: None,
198            display_as: None,
199            subscription: false,
200        };
201
202        context
203            .message_sender
204            .send_to_input_queue(child_result, id.as_str())
205            .await
206            .expect("failed to send child thread message to input queue");
207
208        Some(ToolResult {
209            id: id.as_str().to_owned(),
210            call_id: call_id.map(|c| c.as_str().to_owned()),
211            content: vec![ToolResultContent::Text(Text {
212                text: format!(
213                    "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.",
214                    new_thread_id
215                ),
216            })],
217        })
218    }
219}
220
221/// Tool that sends a report to the parent thread without closing the current thread.
222pub struct ReportToParentTool<C: ConversationStore> {
223    pub conversation_store: C,
224}
225
226#[async_trait]
227impl<M: InputSender + 'static, C: ConversationStore + 'static> Tool<M> for ReportToParentTool<C> {
228    fn name(&self) -> &str {
229        "report_to_parent"
230    }
231
232    fn description(&self) -> &str {
233        "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."
234    }
235
236    fn parameters(&self) -> serde_json::Value {
237        serde_json::json!({
238            "type": "object",
239            "properties": {
240                "report": {
241                    "type": "string",
242                    "description": "The report content to send to the parent thread."
243                }
244            },
245            "required": ["report"]
246        })
247    }
248
249    async fn execute(
250        &self,
251        args: serde_json::Value,
252        id: rap_protocol::ToolCallId,
253        call_id: Option<rap_protocol::ProviderCallId>,
254        context: &ToolContext<M>,
255    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
256        let Some(report_text) = args["report"].as_str() else {
257            return send_tool_error(context, &id, call_id, "report is required").await;
258        };
259
260        let Some((parent_id, spawn_tool_call_id)) = self
261            .conversation_store
262            .get_thread_parent_info(&context.group_id)
263            .await
264            .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?
265        else {
266            return send_tool_error(
267                context,
268                &id,
269                call_id,
270                "No parent thread found — this is a root thread",
271            )
272            .await;
273        };
274
275        let is_subscription = self
276            .conversation_store
277            .is_subscription_event_thread(&context.group_id)
278            .await
279            .unwrap_or(false);
280
281        tracing::info!(
282            "Sending report from thread {} to parent {} via tool call {}",
283            context.group_id,
284            parent_id,
285            spawn_tool_call_id
286        );
287
288        let formatted_report = if is_subscription {
289            format!(
290                "Report from temporary child thread created to process a subscription event:\n{}",
291                report_text
292            )
293        } else {
294            format!("Report from child thread: {}", report_text)
295        };
296
297        let report_message = InputMessage {
298            content: InputMessageContent::User(UserContent::ToolResult(ToolResult {
299                id: String::new(),
300                call_id: None,
301                content: vec![ToolResultContent::Text(Text {
302                    text: formatted_report,
303                })],
304            })),
305            group_id: parent_id,
306            metadata: None,
307            synthetic: Some(SyntheticKind::Tagged(TaggedSyntheticKind::ThreadReport {
308                tool_call_id: spawn_tool_call_id,
309                child_thread_id: context.group_id.clone(),
310            })),
311            display_as: None,
312            subscription: false,
313        };
314
315        context
316            .message_sender
317            .send_to_input_queue(report_message, id.as_str())
318            .await?;
319
320        let tool_result = InputMessage {
321            content: InputMessageContent::User(UserContent::ToolResult(ToolResult {
322                id: id.clone().into_inner(),
323                call_id: call_id.map(|c| c.into_inner()),
324                content: vec![ToolResultContent::Text(Text {
325                    text: "Report sent to parent thread.".to_owned(),
326                })],
327            })),
328            group_id: context.group_id.clone(),
329            metadata: None,
330            synthetic: None,
331            display_as: None,
332            subscription: false,
333        };
334
335        context
336            .message_sender
337            .send_to_input_queue(tool_result, id.as_str())
338            .await?;
339
340        Ok(())
341    }
342}
343
344/// Tool that closes a thread, returning control to the parent.
345pub struct CloseThreadTool<C: ConversationStore, H: HttpClient> {
346    pub conversation_store: C,
347    /// Optional notifier that informs RAP tool servers about the thread closure.
348    /// Best-effort: failures are logged but do not prevent the thread from closing.
349    pub rap_notifier: Option<RapNotifier<H>>,
350}
351
352#[async_trait]
353impl<M: InputSender + 'static, C: ConversationStore + 'static, H: HttpClient + 'static> Tool<M>
354    for CloseThreadTool<C, H>
355{
356    fn name(&self) -> &str {
357        "close_thread"
358    }
359
360    fn description(&self) -> &str {
361        "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."
362    }
363
364    fn parameters(&self) -> serde_json::Value {
365        serde_json::json!({
366            "type": "object",
367            "properties": {
368                "thread_id": {
369                    "type": "string",
370                    "description": "The ID of the thread to close."
371                },
372                "report_to_parent": {
373                    "type": "string",
374                    "description": "Optional report to send to the parent thread."
375                }
376            },
377            "required": ["thread_id"]
378        })
379    }
380
381    async fn execute(
382        &self,
383        args: serde_json::Value,
384        id: rap_protocol::ToolCallId,
385        call_id: Option<rap_protocol::ProviderCallId>,
386        context: &ToolContext<M>,
387    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
388        let Some(thread_id) = args["thread_id"].as_str() else {
389            return send_tool_error(context, &id, call_id, "thread_id is required").await;
390        };
391        let thread_id = ThreadId::from(thread_id);
392
393        if thread_id != context.group_id {
394            return send_tool_error(
395                context,
396                &id,
397                call_id,
398                format!(
399                    "the provided thread ID to close {} does not match the current thread ID {}",
400                    thread_id, context.group_id
401                ),
402            )
403            .await;
404        }
405
406        // Prevent closing the root thread
407        let Some((parent_id, spawn_tool_call_id)) = self
408            .conversation_store
409            .get_thread_parent_info(&thread_id)
410            .await
411            .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?
412        else {
413            return send_tool_error(
414                context,
415                &id,
416                call_id,
417                "cannot close the root thread. Only child threads can be closed.",
418            )
419            .await;
420        };
421
422        let report = args.get("report_to_parent").and_then(|v| v.as_str());
423
424        self.conversation_store
425            .close_thread(&thread_id)
426            .await
427            .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?;
428
429        tracing::info!("Closed thread {}", thread_id);
430
431        // Handle compaction threads: store summary and skip normal parent reporting
432        let is_compaction = self
433            .conversation_store
434            .is_compaction_thread(&thread_id)
435            .await
436            .unwrap_or(false);
437
438        if is_compaction {
439            if let Some(report_text) = report {
440                let up_to_order = self
441                    .conversation_store
442                    .get_thread_spawn_order(&thread_id)
443                    .await
444                    .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?
445                    .unwrap_or(0);
446                self.conversation_store
447                    .save_compaction_summary(&parent_id, report_text, up_to_order)
448                    .await
449                    .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?;
450                tracing::info!(
451                    "Stored compaction summary for thread {} up to order {}",
452                    parent_id,
453                    up_to_order
454                );
455            }
456
457            // Notify the parent thread to apply the compaction
458            let notify_msg = InputMessage {
459                content: InputMessageContent::User(UserContent::ToolResult(ToolResult {
460                    id: String::new(),
461                    call_id: None,
462                    content: vec![ToolResultContent::Text(Text {
463                        text: "Compaction complete".to_owned(),
464                    })],
465                })),
466                group_id: parent_id,
467                metadata: None,
468                synthetic: Some(SyntheticKind::Tagged(
469                    TaggedSyntheticKind::CompactionComplete,
470                )),
471                display_as: None,
472                subscription: false,
473            };
474            context
475                .message_sender
476                .send_to_input_queue(notify_msg, id.as_str())
477                .await?;
478            if let Some(ref notifier) = self.rap_notifier {
479                notifier.notify_thread_closed(&thread_id).await;
480            }
481            return Ok(());
482        }
483
484        let is_subscription = self
485            .conversation_store
486            .is_subscription_event_thread(&thread_id)
487            .await
488            .unwrap_or(false);
489
490        let report_text = if is_subscription {
491            report.map(|report_text| format!(
492                    "An event from your subscription {} was processed by a child thread {}. The subscription remains active. Report from the child:\n{}",
493                    spawn_tool_call_id, thread_id, report_text
494                ))
495        } else if let Some(report_text) = report {
496            Some(format!(
497                "Child thread with ID {} has shut down. Report from child thread: {}",
498                thread_id, report_text
499            ))
500        } else {
501            Some(format!("Child thread with ID {} has shut down", thread_id))
502        };
503
504        if let Some(report_text) = report_text {
505            tracing::info!(
506                "Sending report from thread {} to parent {} via tool call {}",
507                thread_id,
508                parent_id,
509                spawn_tool_call_id
510            );
511
512            let report_message = InputMessage {
513                content: InputMessageContent::User(UserContent::ToolResult(ToolResult {
514                    id: String::new(),
515                    call_id: None,
516                    content: vec![ToolResultContent::Text(Text { text: report_text })],
517                })),
518                group_id: parent_id,
519                metadata: None,
520                synthetic: Some(SyntheticKind::Tagged(TaggedSyntheticKind::ThreadReport {
521                    tool_call_id: spawn_tool_call_id,
522                    child_thread_id: thread_id.clone(),
523                })),
524                display_as: None,
525                subscription: false,
526            };
527
528            context
529                .message_sender
530                .send_to_input_queue(report_message, id.as_str())
531                .await?;
532        }
533
534        // Best-effort: notify RAP tool servers that this thread has been closed
535        // so they can clean up thread-specific resources (e.g. sandboxes).
536        if let Some(ref notifier) = self.rap_notifier {
537            notifier.notify_thread_closed(&thread_id).await;
538        }
539
540        Ok(())
541    }
542}
543
544/// Tool that sends a message to a child thread, injected inline into its history.
545pub struct SendMessageToChildTool<C: ConversationStore> {
546    pub conversation_store: C,
547}
548
549#[async_trait]
550impl<M: InputSender + 'static, C: ConversationStore + 'static> Tool<M>
551    for SendMessageToChildTool<C>
552{
553    fn name(&self) -> &str {
554        "send_message_to_child"
555    }
556
557    fn description(&self) -> &str {
558        "Send a message to a child thread. The message will be injected inline into the child's conversation history."
559    }
560
561    fn parameters(&self) -> serde_json::Value {
562        serde_json::json!({
563            "type": "object",
564            "properties": {
565                "thread_id": {
566                    "type": "string",
567                    "description": "The ID of the child thread to send the message to."
568                },
569                "message": {
570                    "type": "string",
571                    "description": "The message content to send to the child thread."
572                }
573            },
574            "required": ["thread_id", "message"]
575        })
576    }
577
578    async fn execute(
579        &self,
580        args: serde_json::Value,
581        id: rap_protocol::ToolCallId,
582        call_id: Option<rap_protocol::ProviderCallId>,
583        context: &ToolContext<M>,
584    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
585        let Some(child_thread_id) = args["thread_id"].as_str().map(ThreadId::from) else {
586            return send_tool_error(context, &id, call_id, "thread_id is required").await;
587        };
588        let Some(message_text) = args["message"].as_str() else {
589            return send_tool_error(context, &id, call_id, "message is required").await;
590        };
591
592        let Some((parent_id, spawn_tool_call_id)) = self
593            .conversation_store
594            .get_thread_parent_info(&child_thread_id)
595            .await
596            .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?
597        else {
598            return send_tool_error(
599                context,
600                &id,
601                call_id,
602                "Child thread not found or has no parent",
603            )
604            .await;
605        };
606
607        if parent_id != context.group_id {
608            return send_tool_error(
609                context,
610                &id,
611                call_id,
612                format!(
613                    "thread {} is not a child of the current thread {}",
614                    child_thread_id, context.group_id
615                ),
616            )
617            .await;
618        }
619
620        tracing::info!(
621            "Sending message from parent {} to child thread {} via tool call {}",
622            context.group_id,
623            child_thread_id,
624            spawn_tool_call_id
625        );
626
627        let child_message = InputMessage {
628            content: InputMessageContent::User(UserContent::ToolResult(ToolResult {
629                id: String::new(),
630                call_id: None,
631                content: vec![ToolResultContent::Text(Text {
632                    text: format!("Message from parent thread: {}", message_text),
633                })],
634            })),
635            group_id: child_thread_id.clone(),
636            metadata: None,
637            synthetic: Some(SyntheticKind::Tagged(TaggedSyntheticKind::ParentMessage {
638                tool_call_id: spawn_tool_call_id,
639            })),
640            display_as: None,
641            subscription: false,
642        };
643
644        context
645            .message_sender
646            .send_to_input_queue(child_message, id.as_str())
647            .await?;
648
649        let tool_result = InputMessage {
650            content: InputMessageContent::User(UserContent::ToolResult(ToolResult {
651                id: id.clone().into_inner(),
652                call_id: call_id.map(|c| c.into_inner()),
653                content: vec![ToolResultContent::Text(Text {
654                    text: "Message sent to child thread.".to_owned(),
655                })],
656            })),
657            group_id: context.group_id.clone(),
658            metadata: None,
659            synthetic: None,
660            display_as: None,
661            subscription: false,
662        };
663
664        context
665            .message_sender
666            .send_to_input_queue(tool_result, id.as_str())
667            .await?;
668
669        Ok(())
670    }
671}