infinity-agent-core 0.2.0

Core time-sliced agent runtime for Infinity: event processing, threads, and tool dispatch.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
use async_trait::async_trait;
use infinity_provider_protocol::message::{Text, ToolResult, ToolResultContent, UserContent};
use rap_protocol::ThreadId;
use tracing;

use super::{Tool, ToolContext, send_tool_error};
use crate::message::{
    InfinityMessage, InputMessage, InputMessageContent, SyntheticKind, TaggedSyntheticKind,
};
use crate::traits::{ConversationStore, InputSender, SpawnContext};
use rap_client::http::HttpClient;
use rap_client::notifier::RapNotifier;

/// Tool that spawns a new child thread and returns its ID.
pub struct SpawnThreadTool<C: ConversationStore> {
    pub conversation_store: C,
}

#[async_trait]
impl<M: InputSender + 'static, C: ConversationStore + 'static> Tool<M> for SpawnThreadTool<C> {
    fn name(&self) -> &str {
        "spawn_thread"
    }

    fn description(&self) -> &str {
        "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."
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "instructions": {
                    "type": "string",
                    "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."
                },
                "child_of": {
                    "type": "array",
                    "items": { "type": "string" },
                    "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\"]."
                },
                "fresh_context": {
                    "type": "boolean",
                    "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)."
                }
            },
            "required": ["instructions", "child_of"]
        })
    }

    async fn execute(
        &self,
        _args: serde_json::Value,
        _id: rap_protocol::ToolCallId,
        _call_id: Option<rap_protocol::ProviderCallId>,
        _context: &ToolContext<M>,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        Ok(())
    }

    fn supports_sync(&self) -> bool {
        true
    }

    async fn execute_synchronous(
        &self,
        args: &serde_json::Value,
        id: &rap_protocol::ToolCallId<str>,
        call_id: Option<&rap_protocol::ProviderCallId<str>>,
        context: &ToolContext<M>,
    ) -> Option<ToolResult> {
        // Validate child_of matches the actual thread stack
        let child_of: Vec<ThreadId> = args
            .get("child_of")
            .and_then(|v| serde_json::from_value(v.clone()).ok())
            .unwrap_or_default();

        if child_of != context.thread_stack {
            return Some(ToolResult {
                id: id.as_str().to_owned(),
                call_id: call_id.map(|c| c.as_str().to_owned()),
                content: vec![ToolResultContent::Text(Text {
                    text: format!(
                        "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.",
                        child_of, context.thread_stack, context.group_id
                    ),
                })],
            });
        }

        let error_result = |text: String| {
            Some(ToolResult {
                id: id.as_str().to_owned(),
                call_id: call_id.map(|c| c.as_str().to_owned()),
                content: vec![ToolResultContent::Text(Text { text })],
            })
        };

        let fresh_context = args
            .get("fresh_context")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        // Spawn the child right *before* the spawn call and give the child
        // its own copy of the call (seeded below), instead of letting the
        // child see the parent's copy through its inherited slice. The child
        // then owns the call its seed instructions (and later parent
        // messages) resolve against, even after the parent's copy — or the
        // child's inherited prefix — is folded into a compaction summary.
        let spawn_context = if fresh_context {
            SpawnContext::Fresh
        } else {
            // spawn_thread only executes synchronously, and the runtime
            // always provides the safe spawn point on that path.
            SpawnContext::InheritUpTo(context.safe_spawn_point.expect(
                "bug: spawn_thread executed without a safe spawn point in the tool context",
            ))
        };

        let new_thread_id = match self
            .conversation_store
            .spawn_thread(&context.group_id, id, false, spawn_context)
            .await
        {
            Ok(id) => id,
            Err(e) => {
                tracing::error!("failed to spawn thread in conversation store: {e}");
                return error_result(format!("Error: failed to spawn thread: {e}"));
            }
        };

        tracing::info!(
            "Spawned new thread {} from parent {} (fresh_context: {})",
            new_thread_id,
            context.group_id,
            fresh_context
        );

        let instructions = args
            .get("instructions")
            .expect("bug: missing 'instructions' arg")
            .as_str()
            .expect("bug: 'instructions' arg is not a string");

        // Write the child's own copy of the spawn call into its (so far
        // empty) store, pairing with the instruction tool result sent below.
        // Fresh threads need it because they inherit nothing; inherit
        // threads because their cutoff excludes the parent's copy (see
        // `spawn_context` above). The call is duplicated verbatim — same
        // provider call_id and arguments — so the child's model-facing
        // history is exactly what the provider originally emitted.
        let spawn_tool_call = InfinityMessage::ToolCall {
            call: infinity_provider_protocol::message::ToolCall {
                id: id.as_str().to_owned(),
                call_id: call_id.map(|c| c.as_str().to_owned()),
                function: infinity_provider_protocol::message::ToolFunction {
                    name: "spawn_thread".to_owned(),
                    arguments: args.clone(),
                },
            },
            display_as: None,
        };
        if let Err(e) = self
            .conversation_store
            .append_messages(
                &new_thread_id,
                vec![(spawn_tool_call, format!("{}-spawn-call", id))],
            )
            .await
        {
            tracing::error!("failed to seed child thread with spawn call: {e}");
            return error_result(format!("Error: failed to seed child thread: {e}"));
        }

        let child_instructions = if fresh_context {
            format!(
                "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.",
                new_thread_id
            )
        } else {
            format!(
                "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.",
                new_thread_id, instructions
            )
        };

        let child_result = InputMessage {
            content: InputMessageContent::User(UserContent::ToolResult(ToolResult {
                id: id.as_str().to_owned(),
                // Must match the seeded call's call_id (preserved above).
                call_id: call_id.map(|c| c.as_str().to_owned()),
                content: vec![ToolResultContent::Text(Text {
                    text: child_instructions,
                })],
            })),
            group_id: new_thread_id.clone(),
            metadata: None,
            synthetic: None,
            display_as: None,
            subscription: false,
        };

        context
            .message_sender
            .send_to_input_queue(child_result, id.as_str())
            .await
            .expect("failed to send child thread message to input queue");

        Some(ToolResult {
            id: id.as_str().to_owned(),
            call_id: call_id.map(|c| c.as_str().to_owned()),
            content: vec![ToolResultContent::Text(Text {
                text: format!(
                    "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.",
                    new_thread_id
                ),
            })],
        })
    }
}

/// Tool that sends a report to the parent thread without closing the current thread.
pub struct ReportToParentTool<C: ConversationStore> {
    pub conversation_store: C,
}

#[async_trait]
impl<M: InputSender + 'static, C: ConversationStore + 'static> Tool<M> for ReportToParentTool<C> {
    fn name(&self) -> &str {
        "report_to_parent"
    }

    fn description(&self) -> &str {
        "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."
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "report": {
                    "type": "string",
                    "description": "The report content to send to the parent thread."
                }
            },
            "required": ["report"]
        })
    }

    async fn execute(
        &self,
        args: serde_json::Value,
        id: rap_protocol::ToolCallId,
        call_id: Option<rap_protocol::ProviderCallId>,
        context: &ToolContext<M>,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let Some(report_text) = args["report"].as_str() else {
            return send_tool_error(context, &id, call_id, "report is required").await;
        };

        let Some((parent_id, spawn_tool_call_id)) = self
            .conversation_store
            .get_thread_parent_info(&context.group_id)
            .await
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?
        else {
            return send_tool_error(
                context,
                &id,
                call_id,
                "No parent thread found — this is a root thread",
            )
            .await;
        };

        let is_subscription = self
            .conversation_store
            .is_subscription_event_thread(&context.group_id)
            .await
            .unwrap_or(false);

        tracing::info!(
            "Sending report from thread {} to parent {} via tool call {}",
            context.group_id,
            parent_id,
            spawn_tool_call_id
        );

        let formatted_report = if is_subscription {
            format!(
                "Report from temporary child thread created to process a subscription event:\n{}",
                report_text
            )
        } else {
            format!("Report from child thread: {}", report_text)
        };

        let report_message = InputMessage {
            content: InputMessageContent::User(UserContent::ToolResult(ToolResult {
                id: String::new(),
                call_id: None,
                content: vec![ToolResultContent::Text(Text {
                    text: formatted_report,
                })],
            })),
            group_id: parent_id,
            metadata: None,
            synthetic: Some(SyntheticKind::Tagged(TaggedSyntheticKind::ThreadReport {
                tool_call_id: spawn_tool_call_id,
                child_thread_id: context.group_id.clone(),
            })),
            display_as: None,
            subscription: false,
        };

        context
            .message_sender
            .send_to_input_queue(report_message, id.as_str())
            .await?;

        let tool_result = InputMessage {
            content: InputMessageContent::User(UserContent::ToolResult(ToolResult {
                id: id.clone().into_inner(),
                call_id: call_id.map(|c| c.into_inner()),
                content: vec![ToolResultContent::Text(Text {
                    text: "Report sent to parent thread.".to_owned(),
                })],
            })),
            group_id: context.group_id.clone(),
            metadata: None,
            synthetic: None,
            display_as: None,
            subscription: false,
        };

        context
            .message_sender
            .send_to_input_queue(tool_result, id.as_str())
            .await?;

        Ok(())
    }
}

/// Tool that closes a thread, returning control to the parent.
pub struct CloseThreadTool<C: ConversationStore, H: HttpClient> {
    pub conversation_store: C,
    /// Optional notifier that informs RAP tool servers about the thread closure.
    /// Best-effort: failures are logged but do not prevent the thread from closing.
    pub rap_notifier: Option<RapNotifier<H>>,
}

#[async_trait]
impl<M: InputSender + 'static, C: ConversationStore + 'static, H: HttpClient + 'static> Tool<M>
    for CloseThreadTool<C, H>
{
    fn name(&self) -> &str {
        "close_thread"
    }

    fn description(&self) -> &str {
        "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."
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "thread_id": {
                    "type": "string",
                    "description": "The ID of the thread to close."
                },
                "report_to_parent": {
                    "type": "string",
                    "description": "Optional report to send to the parent thread."
                }
            },
            "required": ["thread_id"]
        })
    }

    async fn execute(
        &self,
        args: serde_json::Value,
        id: rap_protocol::ToolCallId,
        call_id: Option<rap_protocol::ProviderCallId>,
        context: &ToolContext<M>,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let Some(thread_id) = args["thread_id"].as_str() else {
            return send_tool_error(context, &id, call_id, "thread_id is required").await;
        };
        let thread_id = ThreadId::from(thread_id);

        if thread_id != context.group_id {
            return send_tool_error(
                context,
                &id,
                call_id,
                format!(
                    "the provided thread ID to close {} does not match the current thread ID {}",
                    thread_id, context.group_id
                ),
            )
            .await;
        }

        // Prevent closing the root thread
        let Some((parent_id, spawn_tool_call_id)) = self
            .conversation_store
            .get_thread_parent_info(&thread_id)
            .await
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?
        else {
            return send_tool_error(
                context,
                &id,
                call_id,
                "cannot close the root thread. Only child threads can be closed.",
            )
            .await;
        };

        let report = args.get("report_to_parent").and_then(|v| v.as_str());

        self.conversation_store
            .close_thread(&thread_id)
            .await
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?;

        tracing::info!("Closed thread {}", thread_id);

        // Handle compaction threads: store summary and skip normal parent reporting
        let is_compaction = self
            .conversation_store
            .is_compaction_thread(&thread_id)
            .await
            .unwrap_or(false);

        if is_compaction {
            if let Some(report_text) = report {
                let up_to_order = self
                    .conversation_store
                    .get_thread_spawn_order(&thread_id)
                    .await
                    .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?
                    .unwrap_or(0);
                self.conversation_store
                    .save_compaction_summary(&parent_id, report_text, up_to_order)
                    .await
                    .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?;
                tracing::info!(
                    "Stored compaction summary for thread {} up to order {}",
                    parent_id,
                    up_to_order
                );
            }

            // Notify the parent thread to apply the compaction
            let notify_msg = InputMessage {
                content: InputMessageContent::User(UserContent::ToolResult(ToolResult {
                    id: String::new(),
                    call_id: None,
                    content: vec![ToolResultContent::Text(Text {
                        text: "Compaction complete".to_owned(),
                    })],
                })),
                group_id: parent_id,
                metadata: None,
                synthetic: Some(SyntheticKind::Tagged(
                    TaggedSyntheticKind::CompactionComplete,
                )),
                display_as: None,
                subscription: false,
            };
            context
                .message_sender
                .send_to_input_queue(notify_msg, id.as_str())
                .await?;
            if let Some(ref notifier) = self.rap_notifier {
                notifier.notify_thread_closed(&thread_id).await;
            }
            return Ok(());
        }

        let is_subscription = self
            .conversation_store
            .is_subscription_event_thread(&thread_id)
            .await
            .unwrap_or(false);

        let report_text = if is_subscription {
            report.map(|report_text| format!(
                    "An event from your subscription {} was processed by a child thread {}. The subscription remains active. Report from the child:\n{}",
                    spawn_tool_call_id, thread_id, report_text
                ))
        } else if let Some(report_text) = report {
            Some(format!(
                "Child thread with ID {} has shut down. Report from child thread: {}",
                thread_id, report_text
            ))
        } else {
            Some(format!("Child thread with ID {} has shut down", thread_id))
        };

        if let Some(report_text) = report_text {
            tracing::info!(
                "Sending report from thread {} to parent {} via tool call {}",
                thread_id,
                parent_id,
                spawn_tool_call_id
            );

            let report_message = InputMessage {
                content: InputMessageContent::User(UserContent::ToolResult(ToolResult {
                    id: String::new(),
                    call_id: None,
                    content: vec![ToolResultContent::Text(Text { text: report_text })],
                })),
                group_id: parent_id,
                metadata: None,
                synthetic: Some(SyntheticKind::Tagged(TaggedSyntheticKind::ThreadReport {
                    tool_call_id: spawn_tool_call_id,
                    child_thread_id: thread_id.clone(),
                })),
                display_as: None,
                subscription: false,
            };

            context
                .message_sender
                .send_to_input_queue(report_message, id.as_str())
                .await?;
        }

        // Best-effort: notify RAP tool servers that this thread has been closed
        // so they can clean up thread-specific resources (e.g. sandboxes).
        if let Some(ref notifier) = self.rap_notifier {
            notifier.notify_thread_closed(&thread_id).await;
        }

        Ok(())
    }
}

/// Tool that sends a message to a child thread, injected inline into its history.
pub struct SendMessageToChildTool<C: ConversationStore> {
    pub conversation_store: C,
}

#[async_trait]
impl<M: InputSender + 'static, C: ConversationStore + 'static> Tool<M>
    for SendMessageToChildTool<C>
{
    fn name(&self) -> &str {
        "send_message_to_child"
    }

    fn description(&self) -> &str {
        "Send a message to a child thread. The message will be injected inline into the child's conversation history."
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "thread_id": {
                    "type": "string",
                    "description": "The ID of the child thread to send the message to."
                },
                "message": {
                    "type": "string",
                    "description": "The message content to send to the child thread."
                }
            },
            "required": ["thread_id", "message"]
        })
    }

    async fn execute(
        &self,
        args: serde_json::Value,
        id: rap_protocol::ToolCallId,
        call_id: Option<rap_protocol::ProviderCallId>,
        context: &ToolContext<M>,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let Some(child_thread_id) = args["thread_id"].as_str().map(ThreadId::from) else {
            return send_tool_error(context, &id, call_id, "thread_id is required").await;
        };
        let Some(message_text) = args["message"].as_str() else {
            return send_tool_error(context, &id, call_id, "message is required").await;
        };

        let Some((parent_id, spawn_tool_call_id)) = self
            .conversation_store
            .get_thread_parent_info(&child_thread_id)
            .await
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?
        else {
            return send_tool_error(
                context,
                &id,
                call_id,
                "Child thread not found or has no parent",
            )
            .await;
        };

        if parent_id != context.group_id {
            return send_tool_error(
                context,
                &id,
                call_id,
                format!(
                    "thread {} is not a child of the current thread {}",
                    child_thread_id, context.group_id
                ),
            )
            .await;
        }

        tracing::info!(
            "Sending message from parent {} to child thread {} via tool call {}",
            context.group_id,
            child_thread_id,
            spawn_tool_call_id
        );

        let child_message = InputMessage {
            content: InputMessageContent::User(UserContent::ToolResult(ToolResult {
                id: String::new(),
                call_id: None,
                content: vec![ToolResultContent::Text(Text {
                    text: format!("Message from parent thread: {}", message_text),
                })],
            })),
            group_id: child_thread_id.clone(),
            metadata: None,
            synthetic: Some(SyntheticKind::Tagged(TaggedSyntheticKind::ParentMessage {
                tool_call_id: spawn_tool_call_id,
            })),
            display_as: None,
            subscription: false,
        };

        context
            .message_sender
            .send_to_input_queue(child_message, id.as_str())
            .await?;

        let tool_result = InputMessage {
            content: InputMessageContent::User(UserContent::ToolResult(ToolResult {
                id: id.clone().into_inner(),
                call_id: call_id.map(|c| c.into_inner()),
                content: vec![ToolResultContent::Text(Text {
                    text: "Message sent to child thread.".to_owned(),
                })],
            })),
            group_id: context.group_id.clone(),
            metadata: None,
            synthetic: None,
            display_as: None,
            subscription: false,
        };

        context
            .message_sender
            .send_to_input_queue(tool_result, id.as_str())
            .await?;

        Ok(())
    }
}