Skip to main content

agent_runtime/runtime/
agent_runtime.rs

1//! Coordinates model turns, tool calls, authorization, cancellation, and run results.
2
3use std::sync::Arc;
4
5use agent_metering::{InvocationOutcome, MeteredValue, ReportedCost, UsageDimensions, UsageRecord};
6use agent_models::TokenUsage;
7use std::time::Duration;
8use uuid::Uuid;
9
10use super::{
11    CancellationToken, EventSink, NoopEventSink, RunEvent, RunEventKind, RunFailure, RunResult,
12    RunStatus, StopReason,
13};
14use crate::{
15    Agent, AgentModel, Authorization, ErrorCategory, FixedModelRouter, Message, ModelError,
16    ModelRequest, ModelRouter, ModelRoutingEvent, ModelRoutingEventSink, PolicyEngine,
17    RoutedModelTurn, RuntimeError, ToolContext, ToolDispatcher, ToolError,
18};
19use tokio::sync::mpsc;
20
21const DEFAULT_TOOL_TIMEOUT: Duration = Duration::from_secs(30);
22const DEFAULT_MAX_TOOL_OUTPUT_BYTES: usize = 16 * 1024;
23const TOOL_OUTPUT_TRUNCATED: &str = "\n[tool output truncated]";
24struct ModelRoutingEventChannel(mpsc::UnboundedSender<ModelRoutingEvent>);
25
26impl ModelRoutingEventSink for ModelRoutingEventChannel {
27    fn emit(&self, event: ModelRoutingEvent) {
28        let _ = self.0.send(event);
29    }
30}
31
32struct CompositeEventSink {
33    sinks: Vec<Arc<dyn EventSink>>,
34}
35
36impl EventSink for CompositeEventSink {
37    fn emit(&self, event: &RunEvent) {
38        for sink in &self.sinks {
39            sink.emit(event);
40        }
41    }
42}
43
44enum ModelTurnError {
45    Model(ModelError),
46    TimedOut,
47}
48
49fn usage_dimensions(usage: Option<&TokenUsage>) -> UsageDimensions {
50    let Some(usage) = usage else {
51        return UsageDimensions::new();
52    };
53    let mut dimensions = UsageDimensions::new()
54        .with(
55            UsageDimensions::INPUT_TOKENS,
56            MeteredValue::Reported(u64::from(usage.input_tokens)),
57        )
58        .with(
59            UsageDimensions::OUTPUT_TOKENS,
60            MeteredValue::Reported(u64::from(usage.output_tokens)),
61        );
62    if let Some(value) = usage.cached_input_tokens {
63        dimensions = dimensions.with(
64            UsageDimensions::CACHED_INPUT_TOKENS,
65            MeteredValue::Reported(u64::from(value)),
66        );
67    }
68    if let Some(value) = usage.reasoning_tokens {
69        dimensions = dimensions.with(
70            UsageDimensions::REASONING_TOKENS,
71            MeteredValue::Reported(u64::from(value)),
72        );
73    }
74    dimensions
75}
76
77fn usage_record(
78    run_id: Uuid,
79    iteration: usize,
80    agent: &str,
81    principal_id: Option<String>,
82    model_id: &str,
83    outcome: InvocationOutcome,
84    usage: UsageDimensions,
85) -> UsageRecord {
86    let (provider, model) = model_id.split_once('/').unwrap_or(("unknown", model_id));
87    UsageRecord::new(
88        Uuid::new_v4(),
89        run_id,
90        u32::try_from(iteration).unwrap_or(u32::MAX),
91        agent,
92        principal_id,
93        provider,
94        model,
95        outcome,
96        usage,
97        chrono::Utc::now(),
98    )
99    .expect("runtime attribution is non-empty")
100}
101
102fn limit_tool_output(mut output: String, max_bytes: usize) -> String {
103    if output.len() <= max_bytes {
104        return output;
105    }
106
107    let marker = if max_bytes >= TOOL_OUTPUT_TRUNCATED.len() {
108        TOOL_OUTPUT_TRUNCATED
109    } else {
110        ""
111    };
112    let mut end = max_bytes.saturating_sub(marker.len()).min(output.len());
113    while !output.is_char_boundary(end) {
114        end -= 1;
115    }
116    output.truncate(end);
117    output.push_str(marker);
118    output
119}
120
121#[derive(Clone)]
122pub struct AgentRuntime {
123    model_router: Arc<dyn ModelRouter>,
124    tools: Arc<dyn ToolDispatcher>,
125    policy: Arc<dyn PolicyEngine>,
126    event_sink: Arc<dyn EventSink>,
127    timeout: Option<Duration>,
128    tool_timeout: Duration,
129    max_tool_output_bytes: usize,
130}
131
132impl AgentRuntime {
133    /// Creates a runtime using a fixed model (useful for tests and embedding).
134    pub fn new(
135        model: Arc<dyn AgentModel>,
136        tools: Arc<dyn ToolDispatcher>,
137        policy: Arc<dyn PolicyEngine>,
138    ) -> Self {
139        Self::new_with_router(Arc::new(FixedModelRouter::new(model)), tools, policy)
140    }
141
142    /// Creates a runtime whose model is selected independently for each turn.
143    pub fn new_with_router(
144        model_router: Arc<dyn ModelRouter>,
145        tools: Arc<dyn ToolDispatcher>,
146        policy: Arc<dyn PolicyEngine>,
147    ) -> Self {
148        Self {
149            model_router,
150            tools,
151            policy,
152            event_sink: Arc::new(NoopEventSink),
153            timeout: None,
154            tool_timeout: DEFAULT_TOOL_TIMEOUT,
155            max_tool_output_bytes: DEFAULT_MAX_TOOL_OUTPUT_BYTES,
156        }
157    }
158
159    pub fn with_event_sink(mut self, event_sink: Arc<dyn EventSink>) -> Self {
160        self.event_sink = event_sink;
161        self
162    }
163
164    pub fn with_timeout(mut self, timeout: Duration) -> Self {
165        self.timeout = Some(timeout);
166        self
167    }
168
169    /// Sets the maximum duration of an individual tool invocation.
170    ///
171    /// A timed-out tool future is dropped and its timeout is returned to the
172    /// model as a tool error. This does not undo external side effects.
173    pub fn with_tool_timeout(mut self, timeout: Duration) -> Self {
174        self.tool_timeout = timeout;
175        self
176    }
177
178    /// Sets the maximum number of UTF-8 bytes retained from each tool result.
179    pub fn with_max_tool_output_bytes(mut self, max_bytes: usize) -> Self {
180        self.max_tool_output_bytes = max_bytes;
181        self
182    }
183
184    async fn complete_model_turn(
185        &self,
186        run_id: Uuid,
187        iteration: usize,
188        agent: &str,
189        principal_id: Option<String>,
190        required: &[agent_models::ModelCapability],
191        request: ModelRequest,
192        cancellation: CancellationToken,
193        deadline: Option<tokio::time::Instant>,
194        events: &mut Vec<RunEvent>,
195    ) -> Result<RoutedModelTurn, ModelTurnError> {
196        let (sender, mut receiver) = mpsc::unbounded_channel();
197        let event_sink = Arc::new(ModelRoutingEventChannel(sender));
198        let completion = self
199            .model_router
200            .complete(required, request, cancellation, event_sink);
201        let result = match deadline {
202            Some(deadline) => match tokio::time::timeout_at(deadline, completion).await {
203                Ok(result) => Ok(result),
204                Err(_) => Err(ModelTurnError::TimedOut),
205            },
206            None => Ok(completion.await),
207        };
208
209        let mut pending_attempts = Vec::new();
210        while let Ok(event) = receiver.try_recv() {
211            let kind = match event {
212                ModelRoutingEvent::CandidatesDiscovered { model_ids } => {
213                    RunEventKind::ModelCandidatesDiscovered { model_ids }
214                }
215                ModelRoutingEvent::CandidateAttemptStarted { model_id } => {
216                    pending_attempts.push(model_id.clone());
217                    RunEventKind::ModelCandidateAttemptStarted { model_id }
218                }
219                ModelRoutingEvent::CandidateAttemptFailed { model_id, category } => {
220                    pending_attempts.retain(|candidate| candidate != &model_id);
221                    let record = usage_record(
222                        run_id,
223                        iteration,
224                        agent,
225                        principal_id.clone(),
226                        &model_id,
227                        InvocationOutcome::Failed,
228                        UsageDimensions::new(),
229                    );
230                    self.emit_event(
231                        events,
232                        RunEvent {
233                            run_id,
234                            iteration,
235                            kind: RunEventKind::ModelUsageRecorded { record },
236                        },
237                    );
238                    RunEventKind::ModelCandidateAttemptFailed { model_id, category }
239                }
240                ModelRoutingEvent::Fallback {
241                    from_model_id,
242                    to_model_id,
243                    category,
244                } => RunEventKind::ModelFallback {
245                    from_model_id,
246                    to_model_id,
247                    category,
248                },
249                ModelRoutingEvent::ModelSelected { model_id } => {
250                    RunEventKind::ModelSelected { model_id }
251                }
252                ModelRoutingEvent::RoutingFailed {
253                    attempted_candidates,
254                } => RunEventKind::ModelRoutingFailed {
255                    attempted_candidates,
256                },
257            };
258            self.emit_event(
259                events,
260                RunEvent {
261                    run_id,
262                    iteration,
263                    kind,
264                },
265            );
266        }
267
268        match result {
269            Ok(Ok(routed)) => {
270                let mut record = usage_record(
271                    run_id,
272                    iteration,
273                    agent,
274                    principal_id,
275                    &routed.model_id,
276                    InvocationOutcome::Succeeded,
277                    usage_dimensions(routed.turn.usage.as_ref()),
278                );
279                if let Some(provider_cost) = routed
280                    .turn
281                    .usage
282                    .as_ref()
283                    .and_then(|usage| usage.reported_cost.as_ref())
284                {
285                    if let Ok(cost) = ReportedCost::new(
286                        provider_cost.amount_micros,
287                        provider_cost.currency.clone(),
288                    ) {
289                        record = record.with_reported_cost(cost);
290                    }
291                }
292                self.emit_event(
293                    events,
294                    RunEvent {
295                        run_id,
296                        iteration,
297                        kind: RunEventKind::ModelUsageRecorded { record },
298                    },
299                );
300                Ok(routed)
301            }
302            Ok(Err(error)) => {
303                let outcome = if matches!(error, ModelError::Cancelled) {
304                    InvocationOutcome::Cancelled
305                } else {
306                    InvocationOutcome::Failed
307                };
308                for model_id in pending_attempts {
309                    let record = usage_record(
310                        run_id,
311                        iteration,
312                        agent,
313                        principal_id.clone(),
314                        &model_id,
315                        outcome,
316                        UsageDimensions::new(),
317                    );
318                    self.emit_event(
319                        events,
320                        RunEvent {
321                            run_id,
322                            iteration,
323                            kind: RunEventKind::ModelUsageRecorded { record },
324                        },
325                    );
326                }
327                Err(ModelTurnError::Model(error))
328            }
329            Err(error) => {
330                for model_id in pending_attempts {
331                    let record = usage_record(
332                        run_id,
333                        iteration,
334                        agent,
335                        principal_id.clone(),
336                        &model_id,
337                        InvocationOutcome::TimedOut,
338                        UsageDimensions::new(),
339                    );
340                    self.emit_event(
341                        events,
342                        RunEvent {
343                            run_id,
344                            iteration,
345                            kind: RunEventKind::ModelUsageRecorded { record },
346                        },
347                    );
348                }
349                Err(error)
350            }
351        }
352    }
353
354    fn emit_event(&self, events: &mut Vec<RunEvent>, event: RunEvent) {
355        self.event_sink.emit(&event);
356        events.push(event);
357    }
358
359    fn stop_reason(
360        &self,
361        cancellation: &CancellationToken,
362        deadline: Option<tokio::time::Instant>,
363    ) -> Option<StopReason> {
364        if cancellation.is_cancelled() {
365            return Some(StopReason::Cancelled);
366        }
367
368        if deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline) {
369            return Some(StopReason::TimedOut);
370        }
371
372        None
373    }
374
375    fn stopped_result(
376        &self,
377        run_id: Uuid,
378        iteration: usize,
379        reason: StopReason,
380        messages: Vec<Message>,
381        events: &mut Vec<RunEvent>,
382    ) -> RunResult {
383        let (status, kind) = match reason {
384            StopReason::Cancelled => (RunStatus::Cancelled, RunEventKind::Cancelled),
385            StopReason::TimedOut => (RunStatus::TimedOut, RunEventKind::TimedOut),
386        };
387
388        self.emit_event(
389            events,
390            RunEvent {
391                run_id,
392                iteration,
393                kind,
394            },
395        );
396
397        RunResult {
398            run_id,
399            status,
400            response: None,
401            messages,
402            iterations: iteration,
403            events: events.clone(),
404        }
405    }
406
407    /// Runs an agent while forwarding each emitted runtime event to an additional sink.
408    ///
409    /// The runtime's configured sink remains active; the supplied sink is composed
410    /// with it so existing observers continue to receive events.
411    pub async fn run_with_event_sink(
412        &self,
413        run_id: Uuid,
414        agent: &Agent,
415        context: ToolContext,
416        messages: Vec<Message>,
417        input: impl Into<String>,
418        cancellation: CancellationToken,
419        event_sink: Arc<dyn EventSink>,
420    ) -> Result<RunResult, RunFailure> {
421        let runtime = Self {
422            event_sink: Arc::new(CompositeEventSink {
423                sinks: vec![Arc::clone(&self.event_sink), event_sink],
424            }),
425            ..self.clone()
426        };
427        runtime
428            .run(run_id, agent, context, messages, input, cancellation)
429            .await
430    }
431
432    /// Runs an agent with trusted platform context and optional conversation history.
433    pub async fn run(
434        &self,
435        run_id: Uuid,
436        agent: &Agent,
437        mut context: ToolContext,
438        mut messages: Vec<Message>,
439        input: impl Into<String>,
440        cancellation: CancellationToken,
441    ) -> Result<RunResult, RunFailure> {
442        context.run_id = Some(run_id);
443        let deadline = self
444            .timeout
445            .map(|timeout| tokio::time::Instant::now() + timeout);
446
447        let mut events = Vec::new();
448        messages.push(Message::User {
449            content: input.into(),
450        });
451
452        // Time is trusted host context, not model-authored conversation content.
453        // Compute it for every run so every model turn receives the current date.
454        let now = chrono::Utc::now();
455        let date_context = format!(
456            "Current date and time: {} (UTC). Current date: {} (UTC). Treat this as the authoritative current date and time; do not guess or infer it from conversation history.",
457            now.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
458            now.date_naive(),
459        );
460        let base_prompt = agent.system_prompt.as_deref().unwrap_or_default();
461        let timezone_context = context.timezone.as_deref().map(|timezone| {
462            format!(
463                "User timezone: {timezone}. This timezone comes from the authenticated user's profile and is authoritative. Use it when interpreting local dates, times, schedules, and relative time expressions; do not infer or override it from conversation content."
464            )
465        });
466        // Give the model the internal recipient IDs for every family the host
467        // has verified the user belongs to. Provider-specific Telegram IDs are
468        // intentionally omitted by FamilyMemberContext serialization.
469        let mut trusted_families = context.families.clone();
470        if let Some(selected_family) = context.family.as_ref() {
471            if !trusted_families
472                .iter()
473                .any(|family| family.family_id == selected_family.family_id)
474            {
475                trusted_families.push(selected_family.clone());
476            }
477        }
478        let family_context = if trusted_families.is_empty() {
479            None
480        } else {
481            let family_json = serde_json::to_string_pretty(&trusted_families)
482                .expect("family contexts are serializable");
483            Some(format!(
484                "Trusted family context available to this run:\n{}\nUse these names, relationships, and recipient IDs as authoritative. Do not infer additional family members or relationships. If a name is unavailable, say so.",
485                family_json,
486            ))
487        };
488        let system_prompt = match (family_context.as_deref(), timezone_context.as_deref()) {
489            (Some(family_context), Some(timezone_context)) => Some(format!(
490                "{}\n\n{}\n\n{}\n\n{}",
491                base_prompt, date_context, timezone_context, family_context
492            )),
493            (Some(family_context), None) => Some(format!(
494                "{}\n\n{}\n\n{}",
495                base_prompt, date_context, family_context
496            )),
497            (None, Some(timezone_context)) => Some(format!(
498                "{}\n\n{}\n\n{}",
499                base_prompt, date_context, timezone_context
500            )),
501            (None, None) => Some(format!("{}\n\n{}", base_prompt, date_context)),
502        };
503
504        let tools = match agent
505            .tool_names
506            .iter()
507            .map(|name| {
508                self.tools
509                    .definition(name)
510                    .ok_or_else(|| RuntimeError::Tool(ToolError::UnknownTool(name.clone())))
511            })
512            .collect::<Result<Vec<_>, _>>()
513        {
514            Ok(tools) => tools,
515            Err(error) => {
516                return Err(RunFailure {
517                    run_id,
518                    error,
519                    messages,
520                    events,
521                    iterations: 0,
522                });
523            }
524        };
525
526        for iteration in 1..=agent.max_iterations {
527            let request = ModelRequest {
528                system_prompt: system_prompt.clone(),
529                messages: messages.clone(),
530                tools: tools.clone(),
531            };
532
533            if let Some(reason) = self.stop_reason(&cancellation, deadline) {
534                return Ok(self.stopped_result(
535                    run_id,
536                    iteration - 1,
537                    reason,
538                    messages,
539                    &mut events,
540                ));
541            }
542
543            self.emit_event(
544                &mut events,
545                RunEvent {
546                    run_id,
547                    iteration,
548                    kind: RunEventKind::ModelRequested,
549                },
550            );
551
552            let routed = match self
553                .complete_model_turn(
554                    run_id,
555                    iteration,
556                    &agent.id,
557                    context.user_id.clone(),
558                    &agent.capabilities,
559                    request,
560                    cancellation.clone(),
561                    deadline,
562                    &mut events,
563                )
564                .await
565            {
566                Ok(routed) => routed,
567                Err(ModelTurnError::TimedOut) => {
568                    return Ok(self.stopped_result(
569                        run_id,
570                        iteration - 1,
571                        StopReason::TimedOut,
572                        messages,
573                        &mut events,
574                    ));
575                }
576                Err(ModelTurnError::Model(ModelError::Cancelled)) => {
577                    return Ok(self.stopped_result(
578                        run_id,
579                        iteration - 1,
580                        StopReason::Cancelled,
581                        messages,
582                        &mut events,
583                    ));
584                }
585                Err(ModelTurnError::Model(error)) => {
586                    let error = RuntimeError::Model(error);
587                    self.emit_event(
588                        &mut events,
589                        RunEvent {
590                            run_id,
591                            iteration,
592                            kind: RunEventKind::ModelFailed {
593                                category: ErrorCategory::Model,
594                            },
595                        },
596                    );
597                    return Err(RunFailure {
598                        run_id,
599                        error,
600                        messages,
601                        events,
602                        iterations: iteration - 1,
603                    });
604                }
605            };
606            let model_id = routed.model_id;
607            let turn = routed.turn;
608            self.emit_event(
609                &mut events,
610                RunEvent {
611                    run_id,
612                    iteration,
613                    kind: RunEventKind::ModelResponded {
614                        model_id: model_id.clone(),
615                        tool_calls: turn.tool_calls.len(),
616                    },
617                },
618            );
619
620            messages.push(Message::Assistant {
621                content: turn.content.clone(),
622                tool_calls: turn.tool_calls.clone(),
623                model_id: Some(model_id),
624                generated_at: Some(chrono::Utc::now()),
625            });
626
627            // Preserve the completed model turn, but do not start any requested tools.
628            if cancellation.is_cancelled() {
629                return Ok(self.stopped_result(
630                    run_id,
631                    iteration,
632                    StopReason::Cancelled,
633                    messages,
634                    &mut events,
635                ));
636            }
637
638            if turn.tool_calls.is_empty() {
639                return Ok(RunResult {
640                    run_id,
641                    status: RunStatus::Completed,
642                    response: turn.content,
643                    messages,
644                    iterations: iteration,
645                    events,
646                });
647            }
648
649            for call in turn.tool_calls {
650                if let Some(reason) = self.stop_reason(&cancellation, deadline) {
651                    return Ok(self.stopped_result(
652                        run_id,
653                        iteration,
654                        reason,
655                        messages,
656                        &mut events,
657                    ));
658                }
659
660                self.emit_event(
661                    &mut events,
662                    RunEvent {
663                        run_id,
664                        iteration,
665                        kind: RunEventKind::ToolExecutionStarted {
666                            tool_call_id: call.id.clone(),
667                            name: call.name.clone(),
668                        },
669                    },
670                );
671
672                let tool_name = call.name.clone();
673                let arguments = call.arguments.clone();
674
675                let execution = async {
676                    match self.policy.authorize(agent, &call) {
677                        Authorization::Allowed => self
678                            .tools
679                            .execute(&context, &tool_name, arguments)
680                            .await
681                            .map_err(RuntimeError::Tool),
682                        Authorization::Denied(error) => Err(RuntimeError::Authorization(error)),
683                    }
684                };
685
686                let tool_deadline = tokio::time::Instant::now() + self.tool_timeout;
687                let operation_deadline = deadline.map_or(tool_deadline, |run_deadline| {
688                    run_deadline.min(tool_deadline)
689                });
690
691                let result = match tokio::time::timeout_at(operation_deadline, execution).await {
692                    Ok(result) => result,
693                    Err(_)
694                        if deadline.is_some_and(|run_deadline| run_deadline <= tool_deadline) =>
695                    {
696                        return Ok(self.stopped_result(
697                            run_id,
698                            iteration,
699                            StopReason::TimedOut,
700                            messages,
701                            &mut events,
702                        ));
703                    }
704                    Err(_) => Err(RuntimeError::Timeout(self.tool_timeout)),
705                };
706
707                self.emit_event(
708                    &mut events,
709                    RunEvent {
710                        run_id,
711                        iteration,
712                        kind: RunEventKind::ToolExecutionFinished {
713                            tool_call_id: call.id.clone(),
714                            name: call.name.clone(),
715                            error_category: result.as_ref().err().map(RuntimeError::category),
716                        },
717                    },
718                );
719
720                let (content, is_error) = match result {
721                    Ok(output) => (output, false),
722                    Err(error) => (error.to_string(), true),
723                };
724                let content = limit_tool_output(content, self.max_tool_output_bytes);
725
726                messages.push(Message::Tool {
727                    tool_call_id: call.id,
728                    name: call.name,
729                    content,
730                    is_error,
731                    provider_metadata: call.provider_metadata.clone(),
732                });
733
734                // The in-flight tool completed and its result is now part of the
735                // conversation. Stop before starting another tool or model request.
736                if cancellation.is_cancelled() {
737                    return Ok(self.stopped_result(
738                        run_id,
739                        iteration,
740                        StopReason::Cancelled,
741                        messages,
742                        &mut events,
743                    ));
744                }
745            }
746        }
747
748        Ok(RunResult {
749            run_id,
750            status: RunStatus::MaxIterationsReached,
751            response: None,
752            messages,
753            iterations: agent.max_iterations,
754            events,
755        })
756    }
757}
758
759#[cfg(test)]
760mod external_run_id_tests {
761    use std::sync::Arc;
762
763    use agent_models::ModelError;
764    use async_trait::async_trait;
765    use uuid::Uuid;
766
767    use super::{AgentRuntime, CancellationToken, RunStatus};
768    use crate::{
769        Agent, AgentModel, AllowListPolicy, ModelRequest, ModelTurn, ToolContext, ToolRegistry,
770    };
771
772    struct FixedModel;
773
774    #[async_trait]
775    impl AgentModel for FixedModel {
776        async fn complete(&self, _request: ModelRequest) -> Result<ModelTurn, ModelError> {
777            Ok(ModelTurn {
778                usage: None,
779                content: Some("completed".into()),
780                tool_calls: Vec::new(),
781            })
782        }
783    }
784
785    #[tokio::test]
786    async fn run_with_history_keeps_previous_messages_and_appends_new_input() {
787        let runtime = AgentRuntime::new(
788            Arc::new(FixedModel),
789            Arc::new(ToolRegistry::new()),
790            Arc::new(AllowListPolicy::new(Vec::<String>::new())),
791        );
792        let agent = Agent {
793            id: "test-agent".into(),
794            capabilities: Vec::new(),
795            system_prompt: None,
796            tool_names: Vec::new(),
797            max_iterations: 2,
798        };
799        let history = vec![crate::Message::User {
800            content: "previous turn".into(),
801        }];
802
803        let result = runtime
804            .run(
805                Uuid::new_v4(),
806                &agent,
807                ToolContext::default(),
808                history,
809                "current turn",
810                CancellationToken::new(),
811            )
812            .await
813            .unwrap();
814
815        assert!(matches!(
816            &result.messages[0],
817            crate::Message::User { content } if content == "previous turn"
818        ));
819        assert!(matches!(
820            &result.messages[1],
821            crate::Message::User { content } if content == "current turn"
822        ));
823        assert!(matches!(
824            &result.messages[2],
825            crate::Message::Assistant { content: Some(content), .. } if content == "completed"
826        ));
827    }
828
829    #[tokio::test]
830    async fn run_with_id_preserves_the_callers_identifier_in_result_and_events() {
831        let runtime = AgentRuntime::new(
832            Arc::new(FixedModel),
833            Arc::new(ToolRegistry::new()),
834            Arc::new(AllowListPolicy::new(Vec::<String>::new())),
835        );
836        let agent = Agent {
837            id: "test-agent".into(),
838            capabilities: Vec::new(),
839            system_prompt: None,
840            tool_names: Vec::new(),
841            max_iterations: 2,
842        };
843        let run_id = Uuid::new_v4();
844
845        let result = runtime
846            .run(
847                run_id,
848                &agent,
849                ToolContext::default(),
850                Vec::new(),
851                "hello",
852                CancellationToken::new(),
853            )
854            .await
855            .unwrap();
856
857        assert_eq!(result.run_id, run_id);
858        assert_eq!(result.status, RunStatus::Completed);
859        assert!(result.events.iter().all(|event| event.run_id == run_id));
860    }
861}
862
863#[cfg(test)]
864mod family_context_tests {
865    use std::sync::{Arc, Mutex};
866
867    use agent_models::ModelError;
868    use async_trait::async_trait;
869    use uuid::Uuid;
870
871    use crate::{
872        Agent, AgentModel, AgentRuntime, AllowListPolicy, CancellationToken, FamilyContext,
873        FamilyMemberContext, ModelRequest, ModelTurn, ToolContext, ToolRegistry,
874    };
875
876    struct CapturingModel(Mutex<Option<ModelRequest>>);
877
878    #[async_trait]
879    impl AgentModel for CapturingModel {
880        async fn complete(&self, request: ModelRequest) -> Result<ModelTurn, ModelError> {
881            *self.0.lock().unwrap() = Some(request);
882            Ok(ModelTurn {
883                usage: None,
884                content: Some("done".into()),
885                tool_calls: Vec::new(),
886            })
887        }
888    }
889
890    #[tokio::test]
891    async fn all_trusted_family_rosters_are_injected_into_model_system_prompt() {
892        let model = Arc::new(CapturingModel(Mutex::new(None)));
893        let runtime = AgentRuntime::new(
894            model.clone(),
895            Arc::new(ToolRegistry::new()),
896            Arc::new(AllowListPolicy::new(Vec::<String>::new())),
897        );
898        let agent = Agent {
899            id: "assistant".into(),
900            capabilities: Vec::new(),
901            system_prompt: Some("You are a helpful assistant.".into()),
902            tool_names: Vec::new(),
903            max_iterations: 1,
904        };
905        let context = ToolContext {
906            family: Some(FamilyContext {
907                family_id: "family-1".into(),
908                family_name: "Home".into(),
909                family_role: "owner".into(),
910                relationship: "father".into(),
911                members: vec![
912                    FamilyMemberContext {
913                        user_id: "user-1".into(),
914                        name: Some("Javier".into()),
915                        birthday: None,
916                        telegram_id: None,
917                        role: "owner".into(),
918                        relationship: "father".into(),
919                    },
920                    FamilyMemberContext {
921                        user_id: "user-2".into(),
922                        name: Some("Lucas".into()),
923                        birthday: None,
924                        telegram_id: None,
925                        role: "member".into(),
926                        relationship: "son".into(),
927                    },
928                ],
929            }),
930            families: vec![FamilyContext {
931                family_id: "family-2".into(),
932                family_name: "Other home".into(),
933                family_role: "member".into(),
934                relationship: "son".into(),
935                members: vec![FamilyMemberContext {
936                    user_id: "user-3".into(),
937                    name: Some("Alex".into()),
938                    birthday: None,
939                    telegram_id: Some("987654321".into()),
940                    role: "owner".into(),
941                    relationship: "father".into(),
942                }],
943            }],
944            ..ToolContext::default()
945        };
946
947        runtime
948            .run(
949                Uuid::new_v4(),
950                &agent,
951                context,
952                Vec::new(),
953                "Who is in my family?",
954                CancellationToken::new(),
955            )
956            .await
957            .unwrap();
958
959        let request = model.0.lock().unwrap().take().unwrap();
960        let prompt = request.system_prompt.unwrap();
961        assert!(prompt.contains("Home"));
962        assert!(prompt.contains("Javier"));
963        assert!(prompt.contains("Lucas"));
964        assert!(prompt.contains("Other home"));
965        assert!(prompt.contains("Alex"));
966        assert!(prompt.contains("user-3"));
967        assert!(prompt.contains("father"));
968        assert!(prompt.contains("son"));
969        assert!(prompt.contains("Do not infer additional family members"));
970        assert!(prompt.contains("Current date and time:"));
971        assert!(prompt.contains(&chrono::Utc::now().date_naive().to_string()));
972        assert!(prompt.contains("recipient_id"));
973        assert!(prompt.contains("user-1"));
974        assert!(!prompt.contains("telegram_id"));
975        assert!(!prompt.contains("987654321"));
976    }
977    #[tokio::test]
978    async fn user_timezone_is_injected_as_authoritative_system_context() {
979        let model = Arc::new(CapturingModel(Mutex::new(None)));
980        let runtime = AgentRuntime::new(
981            model.clone(),
982            Arc::new(ToolRegistry::new()),
983            Arc::new(AllowListPolicy::new(Vec::<String>::new())),
984        );
985        let agent = Agent {
986            id: "assistant".into(),
987            capabilities: Vec::new(),
988            system_prompt: Some("You are a helpful assistant.".into()),
989            tool_names: Vec::new(),
990            max_iterations: 1,
991        };
992
993        runtime
994            .run(
995                Uuid::new_v4(),
996                &agent,
997                ToolContext {
998                    timezone: Some("Europe/Madrid".into()),
999                    ..ToolContext::default()
1000                },
1001                Vec::new(),
1002                "What time is it?",
1003                CancellationToken::new(),
1004            )
1005            .await
1006            .unwrap();
1007
1008        let request = model.0.lock().unwrap().take().unwrap();
1009        let prompt = request.system_prompt.unwrap();
1010        assert!(prompt.contains("User timezone: Europe/Madrid"));
1011        assert!(
1012            prompt.contains("comes from the authenticated user's profile and is authoritative")
1013        );
1014    }
1015}