1use std::collections::HashMap;
2use std::sync::Arc;
3
4use async_trait::async_trait;
5use tokio_util::sync::CancellationToken;
6
7use crate::error::{BuildError, CoreError};
8use crate::event::EventSink;
9use crate::hook::Hook;
10use crate::limits::{Limits, StopCondition};
11use crate::message::Message;
12use crate::outcome::{RunOutcome, RunStatus};
13use crate::provider::{Provider, ToolSpec};
14use crate::run_loop::Driver;
15use crate::safeguard::Safeguard;
16use crate::state::{Interruption, RUN_STATE_SCHEMA, RunState};
17use crate::store::RunStore;
18use crate::stuck::StuckConfig;
19use crate::tool::{Extensions, Tool};
20
21#[async_trait]
28pub trait InterruptResolver: Send + Sync {
29 async fn resolve(&self, state: &RunState, interruption: &Interruption) -> Option<Resolution>;
30}
31
32#[derive(Debug, Clone, PartialEq)]
34pub enum Resolution {
35 Approve,
38 Deny { reason: String },
40 OwnerDeclined {
44 request: crate::approval::OwnerApprovalRequest,
45 reason: String,
46 },
47 Unanswered { reason: String },
52}
53
54#[derive(Clone)]
55pub(crate) struct AgentInner {
56 pub id: String,
57 pub model: String,
58 pub instructions: String,
59 pub provider: Arc<dyn Provider>,
60 pub tools: HashMap<String, Arc<dyn Tool>>,
61 pub specs: Vec<ToolSpec>,
65 pub deferred: std::collections::HashSet<String>,
68 pub retired: HashMap<String, String>,
71 pub loaded: crate::tool_loading::LoadedTools,
72 pub hooks: Vec<Arc<dyn Hook>>,
73 pub limits: Limits,
74 pub stuck: StuckConfig,
75 pub stop_conditions: Vec<Arc<dyn StopCondition>>,
76 pub sinks: Vec<Arc<dyn EventSink>>,
77 pub store: Option<Arc<dyn RunStore>>,
78 pub max_output_tokens: Option<u32>,
79 pub extensions: Extensions,
81 pub approval_key: Option<[u8; 32]>,
83 pub redaction: crate::redaction::RedactionScope,
85}
86
87#[derive(Clone)]
91pub struct Agent {
92 inner: Arc<AgentInner>,
93}
94
95impl Agent {
96 pub fn builder(id: impl Into<String>) -> AgentBuilder {
97 AgentBuilder::new(id)
98 }
99
100 pub fn id(&self) -> &str {
101 &self.inner.id
102 }
103
104 pub fn tool_specs(&self) -> &[ToolSpec] {
105 &self.inner.specs
106 }
107
108 pub fn limits(&self) -> &Limits {
109 &self.inner.limits
110 }
111
112 pub fn redaction_scope(&self) -> &crate::redaction::RedactionScope {
115 &self.inner.redaction
116 }
117
118 pub fn with_limits(&self, limits: Limits) -> Agent {
121 let mut inner = (*self.inner).clone();
122 inner.limits = limits;
123 Agent {
124 inner: Arc::new(inner),
125 }
126 }
127
128 pub fn with_hook(&self, hook: impl Hook + 'static) -> Agent {
130 let mut inner = (*self.inner).clone();
131 inner.hooks.push(Arc::new(hook));
132 Agent {
133 inner: Arc::new(inner),
134 }
135 }
136
137 pub async fn run(
140 &self,
141 session_id: &str,
142 input: impl Into<Message>,
143 ) -> Result<RunOutcome, CoreError> {
144 self.run_with_cancel(session_id, input, CancellationToken::new())
145 .await
146 }
147
148 pub async fn run_with_cancel(
149 &self,
150 session_id: &str,
151 input: impl Into<Message>,
152 cancel: CancellationToken,
153 ) -> Result<RunOutcome, CoreError> {
154 let state = RunState::new(&self.inner.id, session_id, input);
155 Driver::new(&self.inner, state, cancel).drive(None).await
156 }
157
158 pub async fn run_from(
161 &self,
162 state: RunState,
163 cancel: CancellationToken,
164 ) -> Result<RunOutcome, CoreError> {
165 self.check_owner(&state)?;
166 if state.pending.is_some() {
167 return Err(CoreError::PendingInterruption);
168 }
169 Driver::new(&self.inner, state, cancel).drive(None).await
170 }
171
172 pub async fn run_resolving(
181 &self,
182 state: RunState,
183 cancel: CancellationToken,
184 resolver: &dyn InterruptResolver,
185 ) -> Result<RunOutcome, CoreError> {
186 self.check_owner(&state)?;
187 if state.pending.is_some() {
188 return Err(CoreError::PendingInterruption);
189 }
190 let outcome = Driver::new(&self.inner, state, cancel.clone())
191 .without_run_end()
192 .with_resolver(resolver)
193 .drive(None)
194 .await?;
195 self.settle_interruptions(outcome, cancel, resolver).await
196 }
197
198 pub async fn end_in_flight(&self, state: RunState) -> Result<RunOutcome, CoreError> {
205 self.check_owner(&state)?;
206 if state.pending.is_some() {
207 return Err(CoreError::PendingInterruption);
208 }
209 Driver::new(&self.inner, state, CancellationToken::new())
210 .end_in_flight()
211 .await
212 }
213
214 pub async fn resume_resolving(
217 &self,
218 state: RunState,
219 resolution: Resolution,
220 cancel: CancellationToken,
221 resolver: &dyn InterruptResolver,
222 ) -> Result<RunOutcome, CoreError> {
223 self.check_owner(&state)?;
224 if state.pending.is_none() {
225 return Err(CoreError::NotInterrupted);
226 }
227 let outcome = Driver::new(&self.inner, state, cancel.clone())
228 .without_run_end()
229 .with_resolver(resolver)
230 .drive(Some(resolution))
231 .await?;
232 self.settle_interruptions(outcome, cancel, resolver).await
233 }
234
235 async fn settle_interruptions(
236 &self,
237 mut outcome: RunOutcome,
238 cancel: CancellationToken,
239 resolver: &dyn InterruptResolver,
240 ) -> Result<RunOutcome, CoreError> {
241 while let RunStatus::Interrupted { interruption } = &outcome.status {
242 let Some(resolution) = resolver.resolve(&outcome.state, interruption).await else {
243 break;
244 };
245 self.check_owner(&outcome.state)?;
246 outcome = Driver::new(&self.inner, outcome.state, cancel.clone())
247 .without_run_end()
248 .with_resolver(resolver)
249 .drive(Some(resolution))
250 .await?;
251 }
252 crate::run_loop::report_run_end(&self.inner, &outcome).await;
253 Ok(outcome)
254 }
255
256 pub async fn resume(
261 &self,
262 state: RunState,
263 resolution: Resolution,
264 ) -> Result<RunOutcome, CoreError> {
265 self.resume_with_cancel(state, resolution, CancellationToken::new())
266 .await
267 }
268
269 pub async fn resume_with_cancel(
270 &self,
271 state: RunState,
272 resolution: Resolution,
273 cancel: CancellationToken,
274 ) -> Result<RunOutcome, CoreError> {
275 self.check_owner(&state)?;
276 if state.pending.is_none() {
277 return Err(CoreError::NotInterrupted);
278 }
279 Driver::new(&self.inner, state, cancel)
280 .drive(Some(resolution))
281 .await
282 }
283
284 fn check_owner(&self, state: &RunState) -> Result<(), CoreError> {
285 let mut run = Some(state);
286 while let Some(current) = run {
287 if current.schema > RUN_STATE_SCHEMA {
288 return Err(CoreError::UnsupportedRunState {
289 found: current.schema,
290 supported: RUN_STATE_SCHEMA,
291 });
292 }
293 run = current.pending.as_ref().and_then(|p| p.child.as_deref());
294 }
295 if state.agent_id != self.inner.id {
296 return Err(CoreError::AgentMismatch {
297 expected: self.inner.id.clone(),
298 found: state.agent_id.clone(),
299 });
300 }
301 Ok(())
302 }
303}
304
305pub struct AgentBuilder {
309 id: String,
310 model: Option<String>,
311 instructions: String,
312 provider: Option<Arc<dyn Provider>>,
313 tools: Vec<Arc<dyn Tool>>,
314 deferred_tools: Vec<Arc<dyn Tool>>,
315 retired: HashMap<String, String>,
316 loaded: crate::tool_loading::LoadedTools,
317 hooks: Vec<Arc<dyn Hook>>,
318 attested: Vec<Safeguard>,
319 unguarded: bool,
320 limits: Limits,
321 stuck: StuckConfig,
322 stop_conditions: Vec<Arc<dyn StopCondition>>,
323 sinks: Vec<Arc<dyn EventSink>>,
324 store: Option<Arc<dyn RunStore>>,
325 max_output_tokens: Option<u32>,
326 extensions: Extensions,
327 approval_key: Option<[u8; 32]>,
328 redaction: crate::redaction::RedactionScope,
329}
330
331impl AgentBuilder {
332 pub fn new(id: impl Into<String>) -> Self {
333 Self {
334 id: id.into(),
335 model: None,
336 instructions: String::new(),
337 provider: None,
338 tools: Vec::new(),
339 deferred_tools: Vec::new(),
340 retired: HashMap::new(),
341 loaded: crate::tool_loading::LoadedTools::default(),
342 hooks: Vec::new(),
343 attested: Vec::new(),
344 unguarded: false,
345 limits: Limits::default(),
346 stuck: StuckConfig::default(),
347 stop_conditions: Vec::new(),
348 sinks: Vec::new(),
349 store: None,
350 max_output_tokens: None,
351 extensions: Extensions::default(),
352 approval_key: None,
353 redaction: crate::redaction::RedactionScope::process(),
354 }
355 }
356
357 pub fn model(mut self, model: impl Into<String>) -> Self {
361 self.model = Some(model.into());
362 self
363 }
364
365 pub fn instructions(mut self, instructions: impl Into<String>) -> Self {
367 self.instructions = instructions.into();
368 self
369 }
370
371 pub fn provider(mut self, provider: impl Provider + 'static) -> Self {
372 self.provider = Some(Arc::new(provider));
373 self
374 }
375
376 pub fn tool(mut self, tool: impl Tool + 'static) -> Self {
377 self.tools.push(Arc::new(tool));
378 self
379 }
380
381 pub fn tool_arc(mut self, tool: Arc<dyn Tool>) -> Self {
382 self.tools.push(tool);
383 self
384 }
385
386 pub fn deferred_tool_arc(mut self, tool: Arc<dyn Tool>) -> Self {
391 self.deferred_tools.push(tool);
392 self
393 }
394
395 pub fn retired_tool(mut self, name: impl Into<String>, note: impl Into<String>) -> Self {
398 self.retired.insert(name.into(), note.into());
399 self
400 }
401
402 pub fn loaded_tools(mut self, loaded: crate::tool_loading::LoadedTools) -> Self {
405 self.loaded = loaded;
406 self
407 }
408
409 pub fn hook(mut self, hook: impl Hook + 'static) -> Self {
413 self.hooks.push(Arc::new(hook));
414 self
415 }
416
417 pub fn hook_arc(mut self, hook: Arc<dyn Hook>) -> Self {
418 self.hooks.push(hook);
419 self
420 }
421
422 pub fn attest(mut self, safeguard: Safeguard) -> Self {
426 self.attested.push(safeguard);
427 self
428 }
429
430 pub fn allow_unguarded(mut self) -> Self {
433 self.unguarded = true;
434 self
435 }
436
437 pub fn limits(mut self, limits: Limits) -> Self {
438 self.limits = limits;
439 self
440 }
441
442 pub fn stuck_detection(mut self, config: StuckConfig) -> Self {
443 self.stuck = config;
444 self
445 }
446
447 pub fn stop_when(mut self, condition: impl StopCondition + 'static) -> Self {
448 self.stop_conditions.push(Arc::new(condition));
449 self
450 }
451
452 pub fn event_sink(mut self, sink: impl EventSink + 'static) -> Self {
453 self.sinks.push(Arc::new(sink));
454 self
455 }
456
457 pub fn event_sink_arc(mut self, sink: Arc<dyn EventSink>) -> Self {
459 self.sinks.push(sink);
460 self
461 }
462
463 pub fn store(mut self, store: Arc<dyn RunStore>) -> Self {
464 self.store = Some(store);
465 self
466 }
467
468 pub fn max_output_tokens(mut self, tokens: u32) -> Self {
469 self.max_output_tokens = Some(tokens);
470 self
471 }
472
473 pub fn approval_key(mut self, key: [u8; 32]) -> Self {
482 self.approval_key = Some(key);
483 self
484 }
485
486 pub fn redaction_scope(mut self, scope: crate::redaction::RedactionScope) -> Self {
495 self.redaction = scope;
496 self
497 }
498
499 pub fn tool_extensions(mut self, extensions: Extensions) -> Self {
500 self.extensions = extensions;
501 self
502 }
503
504 pub fn build(self) -> Result<Agent, BuildError> {
505 if self.id.trim().is_empty() {
506 return Err(BuildError::EmptyAgentId);
507 }
508 let provider = self.provider.ok_or(BuildError::MissingProvider)?;
509 let model = match self.model {
510 Some(model) => model,
511 None => provider
512 .default_model()
513 .map(str::to_string)
514 .ok_or(BuildError::MissingModel)?,
515 };
516
517 let mut tools = HashMap::new();
518 let mut specs = Vec::with_capacity(self.tools.len() + self.deferred_tools.len() + 1);
519 let mut deferred = std::collections::HashSet::new();
520 let mut deferred_specs = Vec::new();
521 for tool in self.deferred_tools {
522 let spec = tool.spec();
523 if !valid_tool_name(&spec.name) {
524 return Err(BuildError::InvalidToolName(spec.name));
525 }
526 if tools.insert(spec.name.clone(), tool).is_some() {
527 return Err(BuildError::DuplicateTool(spec.name));
528 }
529 deferred.insert(spec.name.clone());
530 deferred_specs.push(spec);
531 }
532 let mut core_tools = self.tools;
533 if !deferred_specs.is_empty() {
534 let entries = deferred_specs
535 .iter()
536 .map(|spec| crate::tool_loading::DeferredEntry {
537 name: spec.name.clone(),
538 summary: crate::tool_loading::one_line(&spec.description),
539 })
540 .collect();
541 core_tools.push(Arc::new(crate::tool_loading::LoadToolsTool::new(
542 entries,
543 self.loaded.clone(),
544 )));
545 }
546 for tool in core_tools {
547 let spec = tool.spec();
548 if !valid_tool_name(&spec.name) {
549 return Err(BuildError::InvalidToolName(spec.name));
550 }
551 if tools.insert(spec.name.clone(), tool).is_some() {
552 return Err(BuildError::DuplicateTool(spec.name));
553 }
554 specs.push(spec);
555 }
556 deferred_specs.sort_by(|a, b| a.name.cmp(&b.name));
557 specs.extend(deferred_specs);
558 if !specs.is_empty() && !self.unguarded {
559 for required in Safeguard::REQUIRED {
560 let covered = self.attested.contains(&required)
561 || self
562 .hooks
563 .iter()
564 .any(|h| h.safeguards().contains(&required));
565 if !covered {
566 return Err(BuildError::MissingSafeguard(required));
567 }
568 }
569 }
570
571 Ok(Agent {
572 inner: Arc::new(AgentInner {
573 id: self.id,
574 model,
575 instructions: self.instructions,
576 provider,
577 tools,
578 specs,
579 deferred,
580 retired: self.retired,
581 loaded: self.loaded,
582 hooks: self.hooks,
583 limits: self.limits,
584 stuck: self.stuck,
585 stop_conditions: self.stop_conditions,
586 sinks: self.sinks,
587 store: self.store,
588 max_output_tokens: self.max_output_tokens,
589 extensions: self.extensions,
590 approval_key: self.approval_key,
591 redaction: self.redaction,
592 }),
593 })
594 }
595}
596
597fn valid_tool_name(name: &str) -> bool {
598 (1..=64).contains(&name.len())
599 && name
600 .bytes()
601 .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
602}