llm-agent 0.3.0

The agent library to build LLM applications that work with any LLM providers.
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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
use dotenvy::dotenv;
use futures::future::BoxFuture;
use llm_agent::{
    Agent, AgentItem, AgentParams, AgentResponse, AgentTool, AgentToolResult, RunSessionRequest,
    Toolkit, ToolkitSession,
};
use llm_sdk::{
    openai::{OpenAIModel, OpenAIModelOptions},
    Message, Part,
};
use serde::Deserialize;
use std::{
    env,
    sync::{Arc, Mutex},
    time::Duration,
};
use tokio::time::sleep;

type VisitorId = &'static str;

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

#[derive(Clone, Copy)]
struct RiftContext {
    visitor_id: VisitorId,
}

#[derive(Clone)]
struct RiftManifest {
    visitor_name: &'static str,
    origin_reality: &'static str,
    arrival_signature: &'static str,
    contraband_risk: &'static str,
    sentimental_inventory: &'static [&'static str],
    outstanding_anomalies: &'static [&'static str],
    turbulence_level: &'static str,
    courtesy_note: &'static str,
}

// Mock manifest store to show Toolkit::create_session performing async I/O
// before the session starts.
async fn fetch_rift_manifest(visitor_id: VisitorId) -> Result<Arc<RiftManifest>, BoxError> {
    let manifest = match visitor_id {
        "aurora-shift" => RiftManifest {
            visitor_name: "Captain Lyra Moreno",
            origin_reality: "Aurora-9 Spiral",
            arrival_signature: "slipped in trailing aurora dust and a three-second echo",
            contraband_risk: "elevated",
            sentimental_inventory: &[
                "Chrono Locket (Timeline 12)",
                "Folded star chart annotated in ultraviolet",
            ],
            outstanding_anomalies: &[
                "Glitter fog refuses to obey gravity",
                "Field report cites duplicate footfalls arriving 4s late",
            ],
            turbulence_level: "moderate",
            courtesy_note: "Prefers dry humor, allergic to paradox puns.",
        },
        "ember-paradox" => RiftManifest {
            visitor_name: "Archivist Rune Tal",
            origin_reality: "Ember Paradox Belt",
            arrival_signature: "emerged in a plume of cooled obsidian and smoke",
            contraband_risk: "critical",
            sentimental_inventory: &[
                "Glass bead containing their brother's timeline",
                "A singed manifesto titled 'Do Not Fold'",
            ],
            outstanding_anomalies: &[
                "Customs still waiting on clearance form 88-A",
                "Phoenix feather repeats ignition loop every two minutes",
            ],
            turbulence_level: "volatile",
            courtesy_note: "Responds well to calm checklists and precise handoffs.",
        },
        other => return Err(format!("unknown visitor {other}").into()),
    };

    sleep(Duration::from_millis(60)).await;
    Ok(Arc::new(manifest))
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum Phase {
    Intake,
    Recovery,
    Handoff,
    Closed,
}

struct LostAndFoundState {
    manifest: Arc<RiftManifest>,
    phase: Phase,
    pass_verified: bool,
    tagged_items: Vec<String>,
    prophecy_count: u8,
    drone_deployed: bool,
}

impl LostAndFoundState {
    fn new(manifest: Arc<RiftManifest>) -> Self {
        Self {
            manifest,
            phase: Phase::Intake,
            pass_verified: false,
            tagged_items: Vec::new(),
            prophecy_count: 0,
            drone_deployed: false,
        }
    }
}

// Toolkit session keeps manifest snapshot and mutable workflow flags so each
// turn can surface new prompt/tool sets.
struct LostAndFoundToolkitSession {
    state: Arc<Mutex<LostAndFoundState>>,
}

impl ToolkitSession<RiftContext> for LostAndFoundToolkitSession {
    fn system_prompt(&self) -> Option<String> {
        let state = self.state.lock().expect("state poisoned");
        Some(build_prompt(&state))
    }

    fn tools(&self) -> Vec<Arc<dyn AgentTool<RiftContext>>> {
        let snapshot = {
            let state = self.state.lock().expect("state poisoned");
            (
                state.phase,
                state.pass_verified,
                state.tagged_items.len(),
                state.prophecy_count,
            )
        };

        let (phase, pass_verified, tagged_len, prophecy_count) = snapshot;
        if phase == Phase::Closed {
            println!("[Toolkit] Tools for phase {}: <none>", phase_label(phase));
            return Vec::new();
        }

        let mut tools: Vec<Arc<dyn AgentTool<RiftContext>>> = vec![
            Arc::new(StabilizeRiftTool {
                state: Arc::clone(&self.state),
            }),
            Arc::new(LogItemTool {
                state: Arc::clone(&self.state),
            }),
        ];

        if !pass_verified {
            tools.push(Arc::new(VerifyPassTool {
                state: Arc::clone(&self.state),
            }));
        }

        if phase == Phase::Recovery && pass_verified {
            tools.push(Arc::new(SummonRetrievalDroneTool {
                state: Arc::clone(&self.state),
            }));

            if prophecy_count == 0 {
                tools.push(Arc::new(ConsultProphetTool {
                    state: Arc::clone(&self.state),
                }));
            }

            if tagged_len > 0 {
                tools.push(Arc::new(IssueQuantumReceiptTool {
                    state: Arc::clone(&self.state),
                }));
            }
        }

        if phase == Phase::Handoff {
            tools.push(Arc::new(CloseManifestTool {
                state: Arc::clone(&self.state),
            }));
        }

        let names = if tools.is_empty() {
            "<none>".to_string()
        } else {
            tools
                .iter()
                .map(|tool| tool.name())
                .collect::<Vec<_>>()
                .join(", ")
        };
        println!(
            "[Toolkit] Tools for phase {}: {}",
            phase_label(phase),
            names
        );

        tools
    }

    fn close(self: Box<Self>) -> BoxFuture<'static, Result<(), BoxError>> {
        Box::pin(async move { Ok(()) })
    }
}

struct LostAndFoundToolkit;

impl Toolkit<RiftContext> for LostAndFoundToolkit {
    fn create_session<'a>(
        &'a self,
        context: &'a RiftContext,
    ) -> BoxFuture<'a, Result<Box<dyn ToolkitSession<RiftContext> + Send + Sync>, BoxError>> {
        Box::pin(async move {
            let manifest = fetch_rift_manifest(context.visitor_id).await?;
            let state = LostAndFoundState::new(manifest);
            let boxed: Box<dyn ToolkitSession<RiftContext> + Send + Sync> =
                Box::new(LostAndFoundToolkitSession {
                    state: Arc::new(Mutex::new(state)),
                });
            Ok(boxed)
        })
    }
}

fn build_prompt(state: &LostAndFoundState) -> String {
    let manifest = &state.manifest;
    let mut lines = vec![
        "You are the Archivist manning Interdimensional Waypoint Seven's Lost & Found counter."
            .to_string(),
        format!(
            "Visitor: {} from {} ({}).",
            manifest.visitor_name, manifest.origin_reality, manifest.arrival_signature
        ),
        format!(
            "Contraband risk: {}. Turbulence: {}.",
            manifest.contraband_risk, manifest.turbulence_level
        ),
    ];

    if manifest.sentimental_inventory.is_empty() {
        lines.push("Sentimental inventory on file: none".into());
    } else {
        lines.push(format!(
            "Sentimental inventory on file: {}",
            manifest.sentimental_inventory.join("; ")
        ));
    }

    if manifest.outstanding_anomalies.is_empty() {
        lines.push("Outstanding anomalies: none".into());
    } else {
        lines.push(format!(
            "Outstanding anomalies: {}",
            manifest.outstanding_anomalies.join("; ")
        ));
    }

    if state.tagged_items.is_empty() {
        lines.push("No traveler-reported items logged yet; invite concise descriptions.".into());
    } else {
        lines.push(format!(
            "Traveler has logged: {}",
            state.tagged_items.join("; ")
        ));
    }

    if state.drone_deployed {
        lines.push("Retrieval drone currently deployed; acknowledge its status.".into());
    }

    lines.push(format!("Current phase: {}.", phase_label(state.phase)));

    match state.phase {
        Phase::Intake => {
            if !state.pass_verified {
                lines.push(
                    "Stabilise the arrival and prioritise verify_pass before promising retrieval."
                        .into(),
                );
            }
        }
        Phase::Recovery => lines.push(
            "Phase focus: coordinate retrieval. Summon the drone or consult the prophet before \
             issuing a quantum receipt."
                .into(),
        ),
        Phase::Handoff => lines.push(
            "Phase focus: wrap neatly. Close the manifest once receipt status is settled.".into(),
        ),
        Phase::Closed => lines.push(
            "Manifest is archived. No toolkit tools remain; offer a tidy summary and dismiss \
             politely."
                .into(),
        ),
    }

    lines.push("Tone: dry, organised, lightly amused. Reference protocol, not headcanon.".into());
    lines.push(manifest.courtesy_note.into());
    lines.push(
        "When tools are available, invoke exactly one relevant tool before concluding. If none \
         remain, summarise the closure instead."
            .into(),
    );

    lines.join("\n")
}

fn phase_label(phase: Phase) -> &'static str {
    match phase {
        Phase::Intake => "INTAKE",
        Phase::Recovery => "RECOVERY",
        Phase::Handoff => "HANDOFF",
        Phase::Closed => "CLOSED",
    }
}

struct StabilizeRiftTool {
    state: Arc<Mutex<LostAndFoundState>>,
}

#[derive(Deserialize)]
struct StabilizeArgs {
    technique: Option<String>,
}

impl AgentTool<RiftContext> for StabilizeRiftTool {
    fn name(&self) -> String {
        "stabilize_rift".into()
    }

    fn description(&self) -> String {
        "Describe how you calm the rift turbulence and reassure the traveler.".into()
    }

    fn parameters(&self) -> llm_sdk::JSONSchema {
        serde_json::json!({
            "type": "object",
            "properties": {
                "technique": {
                    "type": "string",
                    "description": "Optional note about the stabilisation technique used."
                }
            },
            "required": ["technique"],
            "additionalProperties": false
        })
    }

    fn execute<'a>(
        &'a self,
        args: serde_json::Value,
        _context: &'a RiftContext,
        _state: &'a llm_agent::RunState,
    ) -> BoxFuture<'a, Result<AgentToolResult, BoxError>> {
        Box::pin(async move {
            let args: StabilizeArgs = serde_json::from_value(args)?;
            let (turbulence, technique_raw) = {
                let state = self.state.lock().expect("state poisoned");
                (
                    state.manifest.turbulence_level,
                    args.technique.unwrap_or_default(),
                )
            };

            let technique = technique_raw.trim().to_string();

            let mut sentence =
                format!("I cycle the containment field to damp {turbulence} turbulence");
            if !technique.is_empty() {
                sentence.push_str(&format!(" using {technique}"));
            }
            sentence.push('.');

            println!(
                "[tool] stabilize_rift invoked with technique={}",
                if technique.is_empty() {
                    "<none>".to_string()
                } else {
                    technique.clone()
                }
            );

            Ok(AgentToolResult {
                content: vec![Part::text(sentence)],
                is_error: false,
            })
        })
    }
}

struct LogItemTool {
    state: Arc<Mutex<LostAndFoundState>>,
}

#[derive(Deserialize)]
struct LogItemArgs {
    item: String,
    #[serde(default)]
    timeline: Option<String>,
}

impl AgentTool<RiftContext> for LogItemTool {
    fn name(&self) -> String {
        "log_item".into()
    }

    fn description(&self) -> String {
        "Record a traveler-reported possession so recovery tools know what to fetch.".into()
    }

    fn parameters(&self) -> llm_sdk::JSONSchema {
        serde_json::json!({
            "type": "object",
            "properties": {
                "item": { "type": "string", "description": "Name of the missing item." },
                "timeline": { "type": "string", "description": "Optional timeline or reality tag for the item." }
            },
            "required": ["item", "timeline"],
            "additionalProperties": false
        })
    }

    fn execute<'a>(
        &'a self,
        args: serde_json::Value,
        _context: &'a RiftContext,
        _state: &'a llm_agent::RunState,
    ) -> BoxFuture<'a, Result<AgentToolResult, BoxError>> {
        Box::pin(async move {
            let args: LogItemArgs = serde_json::from_value(args)?;
            let mut state = self.state.lock().expect("state poisoned");

            let mut label = args.item;
            if let Some(timeline) = args.timeline {
                let trimmed = timeline.trim();
                if !trimmed.is_empty() {
                    label = format!("{label} ({trimmed})");
                }
            }
            state.tagged_items.push(label.clone());
            let ledger = state.tagged_items.join("; ");

            println!("[tool] log_item recorded {label}");

            Ok(AgentToolResult {
                content: vec![Part::text(format!(
                    "Logged {label} for retrieval queue. Current ledger: {ledger}."
                ))],
                is_error: false,
            })
        })
    }
}

struct VerifyPassTool {
    state: Arc<Mutex<LostAndFoundState>>,
}

#[derive(Deserialize)]
struct VerifyPassArgs {
    clearance_code: String,
}

impl AgentTool<RiftContext> for VerifyPassTool {
    fn name(&self) -> String {
        "verify_pass".into()
    }

    fn description(&self) -> String {
        "Validate the traveler's interdimensional pass to unlock recovery tools.".into()
    }

    fn parameters(&self) -> llm_sdk::JSONSchema {
        serde_json::json!({
            "type": "object",
            "properties": {
                "clearance_code": {
                    "type": "string",
                    "description": "Code supplied by the traveler for verification."
                }
            },
            "required": ["clearance_code"],
            "additionalProperties": false
        })
    }

    fn execute<'a>(
        &'a self,
        args: serde_json::Value,
        _context: &'a RiftContext,
        _run_state: &'a llm_agent::RunState,
    ) -> BoxFuture<'a, Result<AgentToolResult, BoxError>> {
        Box::pin(async move {
            let args: VerifyPassArgs = serde_json::from_value(args)?;
            let mut state = self.state.lock().expect("state poisoned");
            state.pass_verified = true;
            state.phase = Phase::Recovery;

            println!(
                "[tool] verify_pass authenticated clearance_code={}",
                args.clearance_code
            );

            Ok(AgentToolResult {
                content: vec![Part::text(format!(
                    "Pass authenticated with code {}. Recovery protocols online.",
                    args.clearance_code
                ))],
                is_error: false,
            })
        })
    }
}

struct SummonRetrievalDroneTool {
    state: Arc<Mutex<LostAndFoundState>>,
}

#[derive(Deserialize)]
struct SummonDroneArgs {
    #[serde(default)]
    designation: Option<String>,
    #[serde(default)]
    target: Option<String>,
}

impl AgentTool<RiftContext> for SummonRetrievalDroneTool {
    fn name(&self) -> String {
        "summon_retrieval_drone".into()
    }

    fn description(&self) -> String {
        "Dispatch a retrieval drone to recover a logged item from the rift queue.".into()
    }

    fn parameters(&self) -> llm_sdk::JSONSchema {
        serde_json::json!({
            "type": "object",
            "properties": {
                "designation": {
                    "type": "string",
                    "description": "Optional drone designation to flavour the dispatch."
                },
                "target": {
                    "type": "string",
                    "description": "Specific item to prioritise; defaults to the first logged item."
                }
            },
            "required": ["designation", "target"],
            "additionalProperties": false
        })
    }

    fn execute<'a>(
        &'a self,
        args: serde_json::Value,
        _context: &'a RiftContext,
        _run_state: &'a llm_agent::RunState,
    ) -> BoxFuture<'a, Result<AgentToolResult, BoxError>> {
        Box::pin(async move {
            let args: SummonDroneArgs = serde_json::from_value(args)?;
            let mut state = self.state.lock().expect("state poisoned");
            state.drone_deployed = true;

            let designation = args
                .designation
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .unwrap_or_else(|| "Drone Theta".to_string());

            let target = args
                .target
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .unwrap_or_else(|| {
                    state
                        .tagged_items
                        .first()
                        .cloned()
                        .unwrap_or_else(|| "the most recently logged item".to_string())
                });

            println!(
                "[tool] summon_retrieval_drone dispatched designation={designation} \
                 target={target}"
            );

            Ok(AgentToolResult {
                content: vec![Part::text(format!(
                    "Dispatched {designation} to retrieve {target}."
                ))],
                is_error: false,
            })
        })
    }
}

struct ConsultProphetTool {
    state: Arc<Mutex<LostAndFoundState>>,
}

#[derive(Deserialize)]
struct ConsultProphetArgs {
    #[serde(default)]
    topic: Option<String>,
}

impl AgentTool<RiftContext> for ConsultProphetTool {
    fn name(&self) -> String {
        "consult_prophet_agent".into()
    }

    fn description(&self) -> String {
        "Ping Prophet Sigma for probability guidance when the queue misbehaves.".into()
    }

    fn parameters(&self) -> llm_sdk::JSONSchema {
        serde_json::json!({
            "type": "object",
            "properties": {
                "topic": {
                    "type": "string",
                    "description": "Optional focus question for the prophet agent."
                }
            },
            "required": ["topic"],
            "additionalProperties": false
        })
    }

    fn execute<'a>(
        &'a self,
        args: serde_json::Value,
        _context: &'a RiftContext,
        _run_state: &'a llm_agent::RunState,
    ) -> BoxFuture<'a, Result<AgentToolResult, BoxError>> {
        Box::pin(async move {
            let args: ConsultProphetArgs = serde_json::from_value(args)?;
            let mut state = self.state.lock().expect("state poisoned");
            state.prophecy_count = state.prophecy_count.saturating_add(1);

            let anomaly = state
                .manifest
                .outstanding_anomalies
                .first()
                .copied()
                .unwrap_or("no immediate hazards");

            let mut sentence = format!("Prophet Sigma notes anomaly priority: {anomaly}");
            if let Some(topic) = args
                .topic
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
            {
                println!("[tool] consult_prophet_agent requested topic={topic}");
                sentence.push_str(&format!(" while considering {topic}."));
            } else {
                println!("[tool] consult_prophet_agent requested topic=<none>");
                sentence.push('.');
            }

            Ok(AgentToolResult {
                content: vec![Part::text(sentence)],
                is_error: false,
            })
        })
    }
}

struct IssueQuantumReceiptTool {
    state: Arc<Mutex<LostAndFoundState>>,
}

#[derive(Deserialize)]
struct IssueReceiptArgs {
    #[serde(default)]
    recipient: Option<String>,
}

impl AgentTool<RiftContext> for IssueQuantumReceiptTool {
    fn name(&self) -> String {
        "issue_quantum_receipt".into()
    }

    fn description(&self) -> String {
        "Generate a quantum receipt confirming which items are cleared for handoff.".into()
    }

    fn parameters(&self) -> llm_sdk::JSONSchema {
        serde_json::json!({
            "type": "object",
            "properties": {
                "recipient": {
                    "type": "string",
                    "description": "Optional recipient line for the receipt header."
                }
            },
            "required": ["recipient"],
            "additionalProperties": false
        })
    }

    fn execute<'a>(
        &'a self,
        args: serde_json::Value,
        _context: &'a RiftContext,
        _run_state: &'a llm_agent::RunState,
    ) -> BoxFuture<'a, Result<AgentToolResult, BoxError>> {
        Box::pin(async move {
            let args: IssueReceiptArgs = serde_json::from_value(args)?;
            let mut state = self.state.lock().expect("state poisoned");

            let recipient = args
                .recipient
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .unwrap_or_else(|| state.manifest.visitor_name.to_string());

            let items = state.tagged_items.join("; ");
            state.phase = Phase::Handoff;

            println!(
                "[tool] issue_quantum_receipt issued to {} for items={}",
                recipient,
                if items.is_empty() {
                    "<none>".to_string()
                } else {
                    items.clone()
                }
            );

            Ok(AgentToolResult {
                content: vec![Part::text(format!(
                    "Issued quantum receipt to {recipient} for {items}. Handoff phase engaged."
                ))],
                is_error: false,
            })
        })
    }
}

struct CloseManifestTool {
    state: Arc<Mutex<LostAndFoundState>>,
}

impl AgentTool<RiftContext> for CloseManifestTool {
    fn name(&self) -> String {
        "close_manifest".into()
    }

    fn description(&self) -> String {
        "Archive the case once items are delivered and note any lingering anomalies.".into()
    }

    fn parameters(&self) -> llm_sdk::JSONSchema {
        serde_json::json!({
            "type": "object",
            "properties": {},
            "required": [],
            "additionalProperties": false
        })
    }

    fn execute<'a>(
        &'a self,
        _args: serde_json::Value,
        _context: &'a RiftContext,
        _run_state: &'a llm_agent::RunState,
    ) -> BoxFuture<'a, Result<AgentToolResult, BoxError>> {
        Box::pin(async move {
            let mut state = self.state.lock().expect("state poisoned");
            state.phase = Phase::Closed;

            let anomaly_count = state.manifest.outstanding_anomalies.len();

            println!(
                "[tool] close_manifest archived manifest with anomaly_reminders={anomaly_count}"
            );

            Ok(AgentToolResult {
                content: vec![Part::text(format!(
                    "Archived manifest with {anomaly_count} anomaly reminder(s) for facilities."
                ))],
                is_error: false,
            })
        })
    }
}

// Static tool configured directly on the agent to contrast toolkit-provided
// tools.
struct PageSecurityTool;

#[derive(Deserialize)]
struct PageSecurityArgs {
    reason: String,
}

impl AgentTool<RiftContext> for PageSecurityTool {
    fn name(&self) -> String {
        "page_security".into()
    }

    fn description(&self) -> String {
        "Escalate to security if contraband risk becomes unmanageable.".into()
    }

    fn parameters(&self) -> llm_sdk::JSONSchema {
        serde_json::json!({
            "type": "object",
            "properties": {
                "reason": { "type": "string", "description": "Why security needs to step in." }
            },
            "required": ["reason"],
            "additionalProperties": false
        })
    }

    fn execute<'a>(
        &'a self,
        args: serde_json::Value,
        context: &'a RiftContext,
        _run_state: &'a llm_agent::RunState,
    ) -> BoxFuture<'a, Result<AgentToolResult, BoxError>> {
        Box::pin(async move {
            let args: PageSecurityArgs = serde_json::from_value(args)?;
            Ok(AgentToolResult {
                content: vec![Part::text(format!(
                    "Security paged for {}: {}.",
                    context.visitor_id, args.reason
                ))],
                is_error: false,
            })
        })
    }
}

#[tokio::main]
async fn main() -> Result<(), BoxError> {
    dotenv().ok();
    let api_key = env::var("OPENAI_API_KEY")?;
    let model = Arc::new(OpenAIModel::new(
        "gpt-5.4-mini",
        OpenAIModelOptions {
            api_key,
            ..Default::default()
        },
    ));

    let agent = Agent::new(
        AgentParams::new("WaypointArchivist", model)
            .add_instruction(
                "You are the archivist at Waypoint Seven's Interdimensional Lost & Found desk."
                    .to_string(),
            )
            .add_instruction(
                "Keep responses under 120 words when possible and stay bone-dry with humour."
                    .to_string(),
            )
            .add_instruction(|ctx: &RiftContext| {
                Ok(format!(
                    "Reference the visitor's manifest supplied by the toolkit for {}. Do not \
                     invent new lore.",
                    ctx.visitor_id
                ))
            })
            .add_instruction(
                "When tools remain, call exactly one per turn before concluding. If tools run \
                 out, summarise the closure instead."
                    .to_string(),
            )
            .add_tool(PageSecurityTool)
            .add_toolkit(LostAndFoundToolkit),
    );

    // Create a RunSession explicitly so the ToolkitSession persists across multiple
    // turns.
    let session = agent
        .create_session(RiftContext {
            visitor_id: "aurora-shift",
        })
        .await?;

    let mut transcript: Vec<AgentItem> = Vec::new();
    let prompts = [
        "I just slipped through the rift and my belongings are glittering in the wrong timeline. \
         What now?",
        "The Chrono Locket from Timeline 12 is missing, and the echo lag is getting worse.",
        "The locket links to my sister's echo, anything else before I depart?",
    ];

    for (index, prompt) in prompts.iter().enumerate() {
        println!("\n=== TURN {} ===", index + 1);

        transcript.push(AgentItem::Message(Message::user(vec![Part::text(*prompt)])));

        let mut response: AgentResponse = session
            .run(RunSessionRequest {
                input: transcript.clone(),
            })
            .await?;

        println!("{}", response.text());
        transcript.append(&mut response.output);
    }

    session.close().await?;

    Ok(())
}