Skip to main content

runifold_tool/
context.rs

1use std::time::{Duration, Instant};
2
3use runifold_core::{CancellationToken, InvocationId, RunContext, RunId};
4
5/// Execution scope for one tool invocation.
6#[derive(Clone, Debug)]
7pub struct ToolContext {
8    invocation_id: InvocationId,
9    run_id: RunId,
10    deadline: Option<Instant>,
11    cancellation: CancellationToken,
12}
13
14impl ToolContext {
15    pub(crate) fn for_run(run: &RunContext) -> Self {
16        Self {
17            invocation_id: InvocationId::new(),
18            run_id: run.run_id(),
19            deadline: run.deadline(),
20            cancellation: run.cancellation().child_token(),
21        }
22    }
23
24    /// Returns the invocation identity.
25    pub const fn invocation_id(&self) -> InvocationId {
26        self.invocation_id
27    }
28
29    /// Returns the owning run identity.
30    pub const fn run_id(&self) -> RunId {
31        self.run_id
32    }
33
34    /// Returns the effective deadline.
35    pub const fn deadline(&self) -> Option<Instant> {
36        self.deadline
37    }
38
39    /// Returns the remaining time before the deadline.
40    pub fn remaining(&self) -> Option<Duration> {
41        self.deadline
42            .map(|deadline| deadline.saturating_duration_since(Instant::now()))
43    }
44
45    /// Returns the hierarchical cancellation token.
46    pub const fn cancellation(&self) -> &CancellationToken {
47        &self.cancellation
48    }
49}