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
//! Launching threads with their own tools and prompt.
//!
//! Build a local system, start it, and launch configured threads through
//! [`LaunchingSystem::thread_builder`]. Each launched thread gets a generated
//! ID and runs with the union of the system-wide configuration and the tools
//! and prompt registered at launch.

use rap_protocol::ThreadId;
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;

use async_trait::async_trait;

use crate::tools::Tool;
use crate::traits::{ConversationStore, InputSender, StateStore};
use rap_client::http::HttpClient;

use super::driver::ThreadLifecycleEvent;
use super::handle::{HandleSubscribeRequest, ThreadHandle, attach, handle_observer_factory};
use super::router::RunningSystem;
use super::sender::ChannelSender;
use crate::system::builder::{AgentSystem, LocalAgentSystem};
use crate::system::config::{ThreadConfig, ThreadConfigSource};
use crate::system::model::{ModelSource, ResolvedModel};

type BoxError = Box<dyn std::error::Error + Send + Sync>;

/// The tools, prompt, and model a thread was launched with.
struct LaunchConfig<M: InputSender> {
    tools: Vec<Rc<dyn Tool<M>>>,
    extra_system_prompt: Option<String>,
    model: Option<Rc<dyn ModelSource>>,
}

/// Per-thread launch configurations, shared between the running system's
/// [`UnionConfigSource`] and the [`LaunchingSystem`] that registers entries.
/// Lives (and dies) with the process: launch configurations are not
/// persisted, so a thread resumed after a restart runs with the system-wide
/// configuration only.
#[derive(Clone)]
pub(crate) struct LaunchRegistry<M: InputSender> {
    threads: Rc<RefCell<HashMap<ThreadId, LaunchConfig<M>>>>,
}

impl<M: InputSender> Default for LaunchRegistry<M> {
    fn default() -> Self {
        Self {
            threads: Rc::new(RefCell::new(HashMap::new())),
        }
    }
}

/// Resolve the root thread of `thread_id`. Launch configurations attach to
/// the launched thread, which is always a root; subagent threads resolve to
/// their root so they inherit its entry.
async fn root_thread_id<C: ConversationStore>(
    store: &C,
    thread_id: &ThreadId<str>,
) -> Result<ThreadId, BoxError> {
    Ok(store
        .get_ancestor_chain(thread_id)
        .await
        .map_err(|e| Box::new(e) as BoxError)?
        .first()
        .map(|(id, _)| id.clone())
        .unwrap_or_else(|| thread_id.to_owned()))
}

/// Wraps the system-wide [`ModelSource`]: threads launched with their own
/// model (and the subagent threads they spawn, via root resolution) resolve
/// through it; all other threads fall through to the inner source.
pub(crate) struct UnionModelSource<C: ConversationStore, M: InputSender> {
    pub(crate) inner: Box<dyn ModelSource>,
    pub(crate) registry: LaunchRegistry<M>,
    pub(crate) conversation_store: C,
}

#[async_trait(?Send)]
impl<C, M> ModelSource for UnionModelSource<C, M>
where
    C: ConversationStore + 'static,
    M: InputSender + 'static,
{
    async fn resolve(&self, thread_id: &ThreadId<str>) -> Result<ResolvedModel, BoxError> {
        let root_id = root_thread_id(&self.conversation_store, thread_id).await?;
        let launched = self
            .registry
            .threads
            .borrow()
            .get(&root_id)
            .and_then(|config| config.model.clone());
        match launched {
            Some(model) => model.resolve(thread_id).await,
            None => self.inner.resolve(thread_id).await,
        }
    }
}

/// Wraps the system-wide [`ThreadConfigSource`], unioning each launched
/// thread's registered tools and prompt on top of whatever the inner source
/// resolves. Launch configurations attach to the launched (root) thread, so
/// threads a launched thread spawns resolve their root's entry and inherit
/// its tools and prompt. Threads whose root has no registry entry see the
/// inner configuration unchanged.
pub(crate) struct UnionConfigSource<C: ConversationStore, M: InputSender, H: HttpClient> {
    pub(crate) inner: Box<dyn ThreadConfigSource<M, H>>,
    pub(crate) registry: LaunchRegistry<M>,
    pub(crate) conversation_store: C,
}

#[async_trait(?Send)]
impl<C, M, H> ThreadConfigSource<M, H> for UnionConfigSource<C, M, H>
where
    C: ConversationStore + 'static,
    M: InputSender + 'static,
    H: HttpClient + 'static,
{
    async fn resolve(&self, thread_id: &ThreadId<str>) -> Result<ThreadConfig<M, H>, BoxError> {
        let mut config = self.inner.resolve(thread_id).await?;
        let root_id = root_thread_id(&self.conversation_store, thread_id).await?;
        if let Some(local) = self.registry.threads.borrow().get(&root_id) {
            config.tools.extend(local.tools.iter().cloned());
            config.extra_system_prompt = match (
                config.extra_system_prompt.take(),
                local.extra_system_prompt.clone(),
            ) {
                (Some(system_wide), Some(local)) => Some(format!("{system_wide}\n\n{local}")),
                (system_wide, local) => system_wide.or(local),
            };
        }
        Ok(config)
    }
}

impl<C, S, H> LocalAgentSystem<C, S, H>
where
    C: ConversationStore + 'static,
    S: StateStore + 'static,
    H: HttpClient + 'static,
{
    /// Run the system with the built-in thread-builder API: create threads
    /// through [`LaunchingSystem::thread_builder`], and reattach to existing
    /// threads with [`LaunchingSystem::thread_handle`].
    pub fn start(self) -> LaunchingSystem<C, S, H> {
        let registry = self.registry.clone();
        let system = AgentSystem {
            inner: self.system.inner.clone(),
        };
        let running = self.start_inner(handle_observer_factory());
        LaunchingSystem {
            system,
            running,
            registry,
        }
    }
}

/// A running local system whose threads are created through
/// [`thread_builder`](Self::thread_builder), each with its own tools and
/// prompt unioned onto the system-wide configuration. New threads cannot be
/// created by attaching a handle: [`thread_handle`](Self::thread_handle) only
/// reattaches to a thread that was launched or already exists in the store.
pub struct LaunchingSystem<C, S, H>
where
    C: ConversationStore,
    S: StateStore,
    H: HttpClient,
{
    pub(crate) system: AgentSystem<C, S, ChannelSender, H>,
    pub(crate) running: RunningSystem<HandleSubscribeRequest>,
    pub(crate) registry: LaunchRegistry<ChannelSender>,
}

impl<C, S, H> LaunchingSystem<C, S, H>
where
    C: ConversationStore + 'static,
    S: StateStore + 'static,
    H: HttpClient + 'static,
{
    /// Start configuring a new thread. Finish with
    /// [`ThreadBuilder::launch`].
    pub fn thread_builder(&self) -> ThreadBuilder<'_, C, S, H> {
        ThreadBuilder {
            system: self,
            tools: Vec::new(),
            extra_system_prompt: None,
            model: None,
        }
    }

    /// Attach to an existing thread. Returns `Ok(None)` if the thread was not
    /// launched in this process and does not exist in the conversation store.
    /// New threads are created with [`thread_builder`](Self::thread_builder).
    pub async fn thread_handle(
        &self,
        thread_id: &ThreadId<str>,
    ) -> Result<Option<ThreadHandle>, C::Error> {
        if !self.thread_exists(thread_id).await? {
            return Ok(None);
        }
        Ok(Some(attach(&self.running, thread_id).await))
    }

    async fn thread_exists(&self, thread_id: &ThreadId<str>) -> Result<bool, C::Error> {
        if self.registry.threads.borrow().contains_key(thread_id) {
            return Ok(true);
        }
        self.system
            .inner
            .conversation_store
            .thread_exists(thread_id)
            .await
    }

    /// The system's [`InputSender`](crate::traits::InputSender), for callback
    /// servers and any other external message injectors.
    pub fn sender(&self) -> ChannelSender {
        self.running.sender()
    }

    /// Wait for the next thread-driver lifecycle transition. See
    /// [`RunningSystem::next_lifecycle_event`].
    pub async fn next_lifecycle_event(&mut self) -> Option<ThreadLifecycleEvent> {
        self.running.next_lifecycle_event().await
    }

    /// Whether no thread driver is currently live. Threads with active
    /// subscriptions but no pending work do not count as live; their events
    /// respawn a driver when they arrive.
    pub fn is_idle(&self) -> bool {
        self.running.is_idle()
    }

    /// Wind the whole system down (process exit): every driver flushes its
    /// in-flight turn and exits; resolves when the wind-down is complete.
    pub async fn shutdown(self) {
        self.running.shutdown().await;
    }
}

/// Configures and launches one new thread on a [`LaunchingSystem`]. The
/// thread's ID is generated at [`launch`](Self::launch); the registered tools
/// and prompt are unioned onto the system-wide configuration for every
/// completion the thread runs.
pub struct ThreadBuilder<'a, C, S, H>
where
    C: ConversationStore,
    S: StateStore,
    H: HttpClient,
{
    system: &'a LaunchingSystem<C, S, H>,
    tools: Vec<Box<dyn Tool<ChannelSender>>>,
    extra_system_prompt: Option<String>,
    model: Option<Rc<dyn ModelSource>>,
}

impl<C, S, H> ThreadBuilder<'_, C, S, H>
where
    C: ConversationStore + 'static,
    S: StateStore + 'static,
    H: HttpClient + 'static,
{
    /// Give the thread an additional tool (on top of the system-wide tools).
    pub fn tool(mut self, tool: Box<dyn Tool<ChannelSender>>) -> Self {
        self.tools.push(tool);
        self
    }

    /// Give the thread additional tools (on top of the system-wide tools).
    pub fn tools(mut self, tools: impl IntoIterator<Item = Box<dyn Tool<ChannelSender>>>) -> Self {
        self.tools.extend(tools);
        self
    }

    /// Append thread-specific text to the system prompt (after any
    /// system-wide extra prompt).
    pub fn extra_system_prompt(mut self, prompt: impl Into<String>) -> Self {
        self.extra_system_prompt = Some(prompt.into());
        self
    }

    /// Give the thread its own [`ModelSource`] in place of the system-wide
    /// one. Like the system-wide source, it resolves at the start of every
    /// completion round, and threads this thread spawns inherit it.
    pub fn model(mut self, model: impl ModelSource + 'static) -> Self {
        self.model = Some(Rc::new(model));
        self
    }

    /// Create the thread: generate its ID, register the launch
    /// configuration, and attach. Returns the thread's [`ThreadHandle`]
    /// (its ID is [`ThreadHandle::thread_id`]).
    ///
    /// The launch configuration lives for the lifetime of the process; a
    /// thread resumed after a restart runs with the system-wide
    /// configuration only.
    pub async fn launch(self) -> ThreadHandle {
        let thread_id = ThreadId::from(uuid::Uuid::new_v4().to_string());
        self.system.registry.threads.borrow_mut().insert(
            thread_id.clone(),
            LaunchConfig {
                tools: self.tools.into_iter().map(Rc::from).collect(),
                extra_system_prompt: self.extra_system_prompt,
                model: self.model,
            },
        );
        attach(&self.system.running, &thread_id).await
    }
}
#[cfg(test)]
mod tests {
    use crate::system::test_support::*;

    #[tokio::test(flavor = "current_thread")]
    async fn launched_threads_union_their_own_tools_and_prompt() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (system, mut ctrl) = start_launcher_system(
                    vec![Box::new(NamedTool("global_tool"))],
                    "Global prompt.",
                );

                let mut alpha = system
                    .thread_builder()
                    .tool(Box::new(NamedTool("alpha_tool")))
                    .extra_system_prompt("You are alpha.")
                    .launch()
                    .await;
                let mut beta = system
                    .thread_builder()
                    .tool(Box::new(NamedTool("beta_tool")))
                    .launch()
                    .await;
                assert_ne!(alpha.thread_id(), beta.thread_id());

                alpha.send_user_text("hi").await.expect("send input");
                let req = ctrl.next_request().await;
                let names = tool_names(&req);
                assert!(names.contains(&"global_tool".to_owned()));
                assert!(names.contains(&"alpha_tool".to_owned()));
                assert!(!names.contains(&"beta_tool".to_owned()));
                let preamble = req.preamble.clone().expect("system prompt present");
                assert!(preamble.contains("Global prompt."));
                assert!(preamble.contains("You are alpha."));
                ctrl.send_text("hello alpha");
                ctrl.finish();
                assert_eq!(
                    handle_texts_until_finished(&mut alpha).await,
                    ["hello alpha"]
                );

                beta.send_user_text("hi").await.expect("send input");
                let req = ctrl.next_request().await;
                let names = tool_names(&req);
                assert!(names.contains(&"global_tool".to_owned()));
                assert!(names.contains(&"beta_tool".to_owned()));
                assert!(!names.contains(&"alpha_tool".to_owned()));
                let preamble = req.preamble.clone().expect("system prompt present");
                assert!(preamble.contains("Global prompt."));
                assert!(!preamble.contains("You are alpha."));
                ctrl.send_text("hello beta");
                ctrl.finish();
                assert_eq!(handle_texts_until_finished(&mut beta).await, ["hello beta"]);
            })
            .await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn launcher_thread_handle_attaches_to_existing_threads_only() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (mut system, mut ctrl) = start_launcher_system(vec![], "");

                // Unknown threads cannot be attached to.
                assert!(
                    system
                        .thread_handle(rap_protocol::ThreadId::from_ref("no-such-thread"))
                        .await
                        .expect("check unknown thread")
                        .is_none()
                );

                // Launched threads can, even before their first message.
                let launched = system.thread_builder().launch().await;
                let launched_id = launched.thread_id().to_owned();
                assert!(
                    system
                        .thread_handle(&launched_id)
                        .await
                        .expect("check launched thread")
                        .is_some()
                );

                let history_thread = system.thread_builder().launch().await;
                let history_thread_id = history_thread.thread_id().to_owned();
                history_thread
                    .send_user_text("hello")
                    .await
                    .expect("send input");
                let _req = ctrl.next_request().await;
                ctrl.send_text("hi");
                ctrl.finish();
                // Wait for the round to settle (drivers idle out).
                while !system.is_idle() {
                    tokio::time::timeout(
                        std::time::Duration::from_secs(5),
                        system.next_lifecycle_event(),
                    )
                    .await
                    .expect("timed out waiting for a driver exit")
                    .expect("thread lifecycle channel closed");
                }
                drop(history_thread);
                let mut attached = system
                    .thread_handle(&history_thread_id)
                    .await
                    .expect("load existing thread")
                    .expect("thread has history");
                assert!(
                    !attached.replay().history.is_empty(),
                    "replay includes the thread's history"
                );
                attached.send_user_text("again").await.expect("send input");
                let _req = ctrl.next_request().await;
                ctrl.send_text("still here");
                ctrl.finish();
                assert_eq!(
                    handle_texts_until_finished(&mut attached).await,
                    ["still here"]
                );
            })
            .await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn launched_thread_children_inherit_launch_config() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (system, mut ctrl) = start_launcher_system(
                    vec![Box::new(NamedTool("global_tool"))],
                    "Global prompt.",
                );

                let alpha = system
                    .thread_builder()
                    .tool(Box::new(NamedTool("alpha_tool")))
                    .extra_system_prompt("You are alpha.")
                    .launch()
                    .await;
                let alpha_id = alpha.thread_id().to_owned();

                alpha
                    .send_user_text("spawn a child")
                    .await
                    .expect("send input");
                let _req = ctrl.next_request().await;
                ctrl.send_tool_call(
                    "tc-spawn",
                    "spawn_thread",
                    serde_json::json!({
                        "instructions": "do child work",
                        "child_of": [alpha_id],
                    }),
                );
                ctrl.finish();

                // The spawn is synchronous: the parent loops back with the
                // spawn result first.
                let parent_followup = ctrl.next_request().await;
                assert!(tool_names(&parent_followup).contains(&"alpha_tool".to_owned()));
                ctrl.send_text("spawned");
                ctrl.finish();

                // The child's seed message produces its first completion. Launch
                // configurations attach to the launched (root) thread, so the
                // child runs with alpha's tools and prompt.
                let child_req = ctrl.next_request().await;
                let names = tool_names(&child_req);
                assert!(names.contains(&"global_tool".to_owned()));
                assert!(
                    names.contains(&"alpha_tool".to_owned()),
                    "child threads inherit the launched root's tools"
                );
                let preamble = child_req.preamble.expect("system prompt present");
                assert!(
                    preamble.contains("You are alpha."),
                    "child threads inherit the launched root's prompt"
                );
                ctrl.send_text("child done");
                ctrl.finish();
            })
            .await;
    }

    #[tokio::test(flavor = "current_thread")]
    async fn launched_threads_use_their_own_model_and_children_inherit_it() {
        let local = tokio::task::LocalSet::new();
        local
            .run_until(async {
                let (system, mut system_ctrl) = start_launcher_system(vec![], "");
                let (alpha_model, mut alpha_ctrl) = model_source(None);

                let alpha = system.thread_builder().model(alpha_model).launch().await;
                let alpha_id = alpha.thread_id().to_owned();
                let other = system.thread_builder().launch().await;

                // The launched model serves alpha's rounds; the system-wide
                // model serves everyone else.
                alpha.send_user_text("hi").await.expect("send input");
                let _req = alpha_ctrl.next_request().await;
                alpha_ctrl.send_text("from alpha model");
                alpha_ctrl.finish();

                other.send_user_text("hi").await.expect("send input");
                let _req = system_ctrl.next_request().await;
                system_ctrl.send_text("from system model");
                system_ctrl.finish();

                // A child spawned by alpha inherits alpha's model.
                alpha
                    .send_user_text("spawn a child")
                    .await
                    .expect("send input");
                let _req = alpha_ctrl.next_request().await;
                alpha_ctrl.send_tool_call(
                    "tc-spawn",
                    "spawn_thread",
                    serde_json::json!({
                        "instructions": "do child work",
                        "child_of": [alpha_id],
                    }),
                );
                alpha_ctrl.finish();

                // Parent follow-up (spawn is synchronous), then the child's
                // seed completion: both on alpha's model.
                let _parent_followup = alpha_ctrl.next_request().await;
                alpha_ctrl.send_text("spawned");
                alpha_ctrl.finish();
                let child_req = alpha_ctrl.next_request().await;
                assert!(
                    tool_result_texts(&child_req)
                        .iter()
                        .any(|t| t.contains("do child work")),
                    "the request on alpha's model is the child's seed"
                );
                alpha_ctrl.send_text("child done");
                alpha_ctrl.finish();
            })
            .await;
    }
}