Skip to main content

tea_kernel/
config.rs

1use std::time::Duration;
2
3use tea_policy::{ActorId, PolicyEnvironment, WorkspaceId};
4use tea_protocol::ProtocolMetadata;
5
6use crate::compaction::{CompactionPolicy, CompactionSummarizer, NeverCompactPolicy};
7use crate::retry::ModelRetryPolicy;
8use crate::{KernelError, KernelErrorCode};
9
10/// Hard deterministic limits applied to one kernel run.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12#[allow(clippy::struct_field_names)] // `max_*` expresses the stable limit vocabulary.
13pub struct RunLimits {
14    max_tool_iterations: u32,
15    max_elapsed: Duration,
16    max_assistant_output_bytes: usize,
17    max_events: u64,
18    max_queued_messages: usize,
19}
20
21impl RunLimits {
22    /// Creates validated non-zero run limits.
23    ///
24    /// # Errors
25    ///
26    /// Returns an error for zero or unsupported values.
27    pub fn new(
28        max_tool_iterations: u32,
29        max_elapsed: Duration,
30        max_assistant_output_bytes: usize,
31        max_events: u64,
32        max_queued_messages: usize,
33    ) -> Result<Self, KernelError> {
34        if max_tool_iterations == 0
35            || max_elapsed.is_zero()
36            || max_elapsed > Duration::from_hours(24)
37            || max_assistant_output_bytes == 0
38            || max_assistant_output_bytes > 16 * 1024 * 1024
39            || max_events == 0
40            || max_events > 1_000_000
41            || max_queued_messages == 0
42            || max_queued_messages > 1024
43        {
44            return Err(KernelError::new(
45                KernelErrorCode::InvalidRequest,
46                "run limits are invalid",
47            ));
48        }
49        Ok(Self {
50            max_tool_iterations,
51            max_elapsed,
52            max_assistant_output_bytes,
53            max_events,
54            max_queued_messages,
55        })
56    }
57
58    /// Returns the maximum model responses containing tools.
59    #[must_use]
60    pub const fn max_tool_iterations(self) -> u32 {
61        self.max_tool_iterations
62    }
63    /// Returns maximum elapsed run time.
64    #[must_use]
65    pub const fn max_elapsed(self) -> Duration {
66        self.max_elapsed
67    }
68    /// Returns maximum accumulated assistant output bytes.
69    #[must_use]
70    pub const fn max_assistant_output_bytes(self) -> usize {
71        self.max_assistant_output_bytes
72    }
73    /// Returns maximum emitted observations.
74    #[must_use]
75    pub const fn max_events(self) -> u64 {
76        self.max_events
77    }
78    /// Returns maximum accepted queued messages.
79    #[must_use]
80    pub const fn max_queued_messages(self) -> usize {
81        self.max_queued_messages
82    }
83}
84
85impl Default for RunLimits {
86    fn default() -> Self {
87        Self {
88            max_tool_iterations: 16,
89            max_elapsed: Duration::from_mins(5),
90            max_assistant_output_bytes: 4 * 1024 * 1024,
91            max_events: 100_000,
92            max_queued_messages: 64,
93        }
94    }
95}
96
97/// Immutable product-independent context frozen for one run.
98#[derive(Debug, Clone)]
99pub struct KernelRunConfig {
100    actor_id: ActorId,
101    workspace_id: Option<WorkspaceId>,
102    environment: PolicyEnvironment,
103    system_prompt: Option<String>,
104    compiled_prompt: Option<tea_context::CompiledPrompt>,
105    request_metadata: ProtocolMetadata,
106    approval_ttl: Duration,
107    retry_policy: ModelRetryPolicy,
108    compaction_policy: std::sync::Arc<dyn CompactionPolicy>,
109    compaction_summarizer: Option<std::sync::Arc<dyn CompactionSummarizer>>,
110    limits: RunLimits,
111}
112
113impl KernelRunConfig {
114    /// Creates a run snapshot with default hard limits.
115    #[must_use]
116    pub fn new(actor_id: ActorId, environment: PolicyEnvironment) -> Self {
117        Self {
118            actor_id,
119            workspace_id: None,
120            environment,
121            system_prompt: None,
122            compiled_prompt: None,
123            request_metadata: ProtocolMetadata::default(),
124            approval_ttl: Duration::from_mins(10),
125            retry_policy: ModelRetryPolicy::default(),
126            compaction_policy: std::sync::Arc::new(NeverCompactPolicy),
127            compaction_summarizer: None,
128            limits: RunLimits {
129                max_tool_iterations: 16,
130                max_elapsed: Duration::from_mins(5),
131                max_assistant_output_bytes: 4 * 1024 * 1024,
132                max_events: 100_000,
133                max_queued_messages: 64,
134            },
135        }
136    }
137
138    /// Adds a workspace identity.
139    #[must_use]
140    pub fn with_workspace(mut self, workspace_id: WorkspaceId) -> Self {
141        self.workspace_id = Some(workspace_id);
142        self
143    }
144
145    /// Adds a bounded non-empty system prompt.
146    ///
147    /// # Errors
148    ///
149    /// Returns an error when the prompt is empty, oversized, or contains null.
150    pub fn with_system_prompt(mut self, prompt: impl Into<String>) -> Result<Self, KernelError> {
151        let prompt = prompt.into();
152        if self.compiled_prompt.is_some()
153            || prompt.is_empty()
154            || prompt.len() > 1024 * 1024
155            || prompt.contains('\0')
156        {
157            return Err(KernelError::new(
158                KernelErrorCode::InvalidRequest,
159                "system prompt is invalid",
160            ));
161        }
162        self.system_prompt = Some(prompt);
163        Ok(self)
164    }
165
166    /// Attaches one immutable provenance-preserving compiled prompt snapshot.
167    ///
168    /// # Errors
169    ///
170    /// Returns an error when a legacy system prompt is already configured.
171    pub fn with_compiled_prompt(
172        mut self,
173        prompt: tea_context::CompiledPrompt,
174    ) -> Result<Self, KernelError> {
175        if self.system_prompt.is_some() {
176            return Err(KernelError::new(
177                KernelErrorCode::InvalidRequest,
178                "compiled and legacy system prompts are mutually exclusive",
179            ));
180        }
181        self.compiled_prompt = Some(prompt);
182        Ok(self)
183    }
184
185    /// Adds bounded model request metadata.
186    #[must_use]
187    pub fn with_request_metadata(mut self, metadata: ProtocolMetadata) -> Self {
188        self.request_metadata = metadata;
189        self
190    }
191
192    /// Replaces the approval lifetime used for newly persisted requests.
193    ///
194    /// # Errors
195    ///
196    /// Returns an error for zero or values above 24 hours.
197    pub fn with_approval_ttl(mut self, ttl: Duration) -> Result<Self, KernelError> {
198        if ttl.is_zero() || ttl > Duration::from_hours(24) {
199            return Err(KernelError::new(
200                KernelErrorCode::InvalidRequest,
201                "approval lifetime is invalid",
202            ));
203        }
204        self.approval_ttl = ttl;
205        Ok(self)
206    }
207
208    /// Replaces default run limits.
209    #[must_use]
210    pub const fn with_limits(mut self, limits: RunLimits) -> Self {
211        self.limits = limits;
212        self
213    }
214
215    /// Replaces the default model retry policy.
216    #[must_use]
217    pub const fn with_retry_policy(mut self, policy: ModelRetryPolicy) -> Self {
218        self.retry_policy = policy;
219        self
220    }
221
222    /// Replaces the default automatic compaction policy.
223    #[must_use]
224    pub fn with_compaction_policy(mut self, policy: std::sync::Arc<dyn CompactionPolicy>) -> Self {
225        self.compaction_policy = policy;
226        self
227    }
228
229    /// Attaches a product-supplied compaction summarizer.
230    #[must_use]
231    pub fn with_compaction_summarizer(
232        mut self,
233        summarizer: std::sync::Arc<dyn CompactionSummarizer>,
234    ) -> Self {
235        self.compaction_summarizer = Some(summarizer);
236        self
237    }
238
239    /// Returns the actor snapshot.
240    #[must_use]
241    pub const fn actor_id(&self) -> &ActorId {
242        &self.actor_id
243    }
244    /// Returns optional workspace identity.
245    #[must_use]
246    pub const fn workspace_id(&self) -> Option<&WorkspaceId> {
247        self.workspace_id.as_ref()
248    }
249    /// Returns the policy environment snapshot.
250    #[must_use]
251    pub const fn environment(&self) -> &PolicyEnvironment {
252        &self.environment
253    }
254    /// Returns optional product-supplied system prompt.
255    #[must_use]
256    pub fn system_prompt(&self) -> Option<&str> {
257        self.compiled_prompt.as_ref().map_or_else(
258            || self.system_prompt.as_deref(),
259            |prompt| (!prompt.text().is_empty()).then_some(prompt.text()),
260        )
261    }
262    /// Returns the immutable compiled prompt and inspection snapshot.
263    #[must_use]
264    pub const fn compiled_prompt(&self) -> Option<&tea_context::CompiledPrompt> {
265        self.compiled_prompt.as_ref()
266    }
267    /// Returns model request metadata.
268    #[must_use]
269    pub const fn request_metadata(&self) -> &ProtocolMetadata {
270        &self.request_metadata
271    }
272    /// Returns the lifetime assigned to new approval requests.
273    #[must_use]
274    pub const fn approval_ttl(&self) -> Duration {
275        self.approval_ttl
276    }
277    /// Returns hard run limits.
278    #[must_use]
279    pub const fn limits(&self) -> RunLimits {
280        self.limits
281    }
282    /// Returns the model retry policy.
283    #[must_use]
284    pub const fn retry_policy(&self) -> ModelRetryPolicy {
285        self.retry_policy
286    }
287    /// Returns the automatic compaction policy.
288    #[must_use]
289    pub fn compaction_policy(&self) -> &std::sync::Arc<dyn CompactionPolicy> {
290        &self.compaction_policy
291    }
292    /// Returns the product-supplied compaction summarizer when configured.
293    #[must_use]
294    pub fn compaction_summarizer(&self) -> Option<&std::sync::Arc<dyn CompactionSummarizer>> {
295        self.compaction_summarizer.as_ref()
296    }
297}