1use std::sync::Arc;
2
3use runifold_core::{CapabilitySet, RetrySafety, RunError, RunErrorKind};
4use runifold_effect::{EffectExecutor, EffectRecoveryPolicy};
5use runifold_model::{
6 ArtifactResolvingModel, ArtifactScope, ArtifactStore, FeaturePolicy, GenerationOptions,
7 Message, Model, ModelRef, OutputFormat, ProviderToolSpec, ResponseMode,
8};
9use runifold_retrieval::{Document, RetrievalError, Retriever};
10use runifold_tool::{Tool, ToolRegistrationError};
11use schemars::JsonSchema;
12use thiserror::Error;
13
14use crate::agent::DynamicContext;
15use crate::{
16 Agent, AgentConfig, AgentDescriptor, AgentError, AgentFuture, AgentOutcome,
17 AgentRegistrationError, AgentRoute, CompletionRequirement, GatewayMiddleware, StructuredAgent,
18 ToolErrorPolicy,
19};
20
21#[derive(Clone, Debug, Error, Eq, PartialEq)]
23#[non_exhaustive]
24pub enum AgentBuildError {
25 #[error("agent Tool registration failed: {0}")]
27 Tool(#[from] ToolRegistrationError),
28 #[error("agent route registration failed: {0}")]
30 Route(#[from] AgentRegistrationError),
31 #[error("callable name `{0}` is registered as both a Tool and an Agent")]
33 CallableNameCollision(String),
34 #[error("agent name cannot be empty")]
36 EmptyName,
37 #[error("max_turns must be greater than zero")]
39 ZeroMaxTurns,
40 #[error("min_successful_tool_calls={minimum} requires at least one registered local Tool")]
42 MinimumSuccessfulToolCallsWithoutTool {
43 minimum: u32,
45 },
46 #[error("agent retrieval configuration failed: {0}")]
48 Retrieval(#[from] RetrievalError),
49}
50
51#[derive(Debug, Error)]
53#[non_exhaustive]
54pub enum AgentPromptError {
55 #[error("failed to build agent: {0}")]
57 Build(#[from] AgentBuildError),
58 #[error("agent prompt failed: {0}")]
60 Run(#[from] AgentError),
61}
62
63impl AgentPromptError {
64 pub fn run_error_kind(&self) -> RunErrorKind {
66 match self {
67 Self::Build(_) => RunErrorKind::InvalidInput,
68 Self::Run(error) => error.run_error_kind(),
69 }
70 }
71
72 pub fn retry_safety(&self) -> RetrySafety {
74 match self {
75 Self::Build(_) => RetrySafety::Safe,
76 Self::Run(error) => error.retry_safety(),
77 }
78 }
79
80 pub fn to_run_error(&self) -> RunError {
82 match self {
83 Self::Build(_) => RunError {
84 kind: RunErrorKind::InvalidInput,
85 message: self.to_string(),
86 retry_safety: RetrySafety::Safe,
87 metadata: std::collections::BTreeMap::new(),
88 },
89 Self::Run(error) => error.to_run_error(),
90 }
91 }
92}
93
94pub struct AgentBuilder {
100 agent: Agent,
101 error: Option<AgentBuildError>,
102}
103
104impl AgentBuilder {
105 pub fn new(name: impl Into<String>, model: Arc<dyn Model>, model_ref: ModelRef) -> Self {
107 Self {
108 agent: Agent::new(name, model, model_ref),
109 error: None,
110 }
111 }
112
113 #[must_use]
115 pub fn system(mut self, instruction: impl Into<String>) -> Self {
116 self.agent
117 .instructions
118 .push(Message::system(instruction.into()));
119 self
120 }
121
122 #[must_use]
127 pub fn context(self, text: impl Into<String>) -> Self {
128 let id = format!("static-context-{}", self.agent.context.len() + 1);
129 match Document::new(id, text) {
130 Ok(document) => self.context_document(document),
131 Err(error) => self.with_error(error.into()),
132 }
133 }
134
135 #[must_use]
137 pub fn context_document(mut self, document: Document) -> Self {
138 if self.error.is_none() {
139 self.agent.context.push(document);
140 }
141 self
142 }
143
144 #[must_use]
147 pub fn artifacts(mut self, scope: ArtifactScope, store: Arc<dyn ArtifactStore>) -> Self {
148 self.agent.model = Arc::new(ArtifactResolvingModel::new(
149 self.agent.model.clone(),
150 scope.clone(),
151 store.clone(),
152 ));
153 self.agent.tools = self.agent.tools.clone().with_artifact_store(scope, store);
154 self
155 }
156
157 #[must_use]
159 pub fn dynamic_context<R>(self, limit: usize, retriever: R) -> Self
160 where
161 R: Retriever + 'static,
162 {
163 self.shared_dynamic_context(limit, Arc::new(retriever))
164 }
165
166 #[must_use]
168 pub fn shared_dynamic_context(mut self, limit: usize, retriever: Arc<dyn Retriever>) -> Self {
169 if self.error.is_none() {
170 if limit == 0 {
171 self.error = Some(RetrievalError::ZeroLimit.into());
172 } else {
173 self.agent
174 .dynamic_context
175 .push(DynamicContext { limit, retriever });
176 }
177 }
178 self
179 }
180
181 #[must_use]
183 pub fn tool<T>(self, tool: T) -> Self
184 where
185 T: Tool + 'static,
186 {
187 self.shared_tool(Arc::new(tool))
188 }
189
190 #[must_use]
192 pub fn shared_tool(mut self, tool: Arc<dyn Tool>) -> Self {
193 if self.error.is_none()
194 && let Err(error) = self.agent.tools.register(tool)
195 {
196 self.error = Some(error.into());
197 }
198 self
199 }
200
201 fn with_error(mut self, error: AgentBuildError) -> Self {
202 if self.error.is_none() {
203 self.error = Some(error);
204 }
205 self
206 }
207
208 #[must_use]
210 pub fn child(
211 mut self,
212 descriptor: AgentDescriptor,
213 child: Arc<Agent>,
214 capabilities: CapabilitySet,
215 ) -> Self {
216 if self.error.is_none() {
217 let route = AgentRoute::new(descriptor, child).with_capabilities(capabilities);
218 if let Err(error) = self.agent.agents.register(route) {
219 self.error = Some(error.into());
220 }
221 }
222 self
223 }
224
225 #[must_use]
227 pub fn gateway_layer(mut self, middleware: Arc<dyn GatewayMiddleware>) -> Self {
228 self.agent.agents.push_middleware(middleware);
229 self
230 }
231
232 #[must_use]
234 pub fn max_delegation_depth(mut self, max_depth: u32) -> Self {
235 self.agent.agents = self.agent.agents.with_max_depth(max_depth);
236 self
237 }
238
239 #[must_use]
241 pub const fn max_turns(mut self, max_turns: u32) -> Self {
242 self.agent.config.max_turns = max_turns;
243 self
244 }
245
246 #[must_use]
252 pub const fn min_successful_tool_calls(mut self, minimum: u32) -> Self {
253 self.agent.min_successful_tool_calls = minimum;
254 self
255 }
256
257 #[must_use]
259 pub const fn tool_error_policy(mut self, policy: ToolErrorPolicy) -> Self {
260 self.agent.config.tool_error_policy = policy;
261 self
262 }
263
264 #[must_use]
266 pub fn completion_requirement(self, requirement: CompletionRequirement) -> Self {
267 Self {
268 agent: self.agent.completion_requirement(requirement),
269 error: self.error,
270 }
271 }
272
273 #[must_use]
275 pub const fn feature_policy(mut self, policy: FeaturePolicy) -> Self {
276 self.agent.config.feature_policy = policy;
277 self
278 }
279
280 #[must_use]
282 pub fn output_format(mut self, output_format: OutputFormat) -> Self {
283 self.agent.output_format = output_format;
284 self
285 }
286
287 #[must_use]
289 pub fn structured_output<T>(self, name: impl Into<String>) -> Self
290 where
291 T: JsonSchema,
292 {
293 self.structured_output_with_strictness::<T>(name, true)
294 }
295
296 #[must_use]
299 pub fn structured_output_with_strictness<T>(self, name: impl Into<String>, strict: bool) -> Self
300 where
301 T: JsonSchema,
302 {
303 self.output_format(OutputFormat::typed_with_strictness::<T>(name, strict))
304 }
305
306 #[must_use]
308 pub fn provider_tool(mut self, tool: ProviderToolSpec) -> Self {
309 self.agent.provider_tools.push(tool);
310 self
311 }
312
313 #[must_use]
315 pub fn generation(mut self, generation: GenerationOptions) -> Self {
316 self.agent.generation = generation;
317 self
318 }
319
320 #[must_use]
322 pub fn temperature(mut self, temperature: f64) -> Self {
323 self.agent.generation.temperature = Some(temperature);
324 self
325 }
326
327 #[must_use]
329 pub fn top_p(mut self, top_p: f64) -> Self {
330 self.agent.generation.top_p = Some(top_p);
331 self
332 }
333
334 #[must_use]
336 pub fn max_output_tokens(mut self, max_output_tokens: u64) -> Self {
337 self.agent.generation.max_output_tokens = Some(max_output_tokens);
338 self
339 }
340
341 #[must_use]
343 pub const fn response_mode(mut self, response_mode: ResponseMode) -> Self {
344 self.agent.response_mode = response_mode;
345 self
346 }
347
348 #[must_use]
350 pub fn provider_options(
351 mut self,
352 provider: impl Into<String>,
353 options: serde_json::Value,
354 ) -> Self {
355 self.agent.provider_options.insert(provider.into(), options);
356 self
357 }
358
359 #[must_use]
361 pub const fn config(mut self, config: AgentConfig) -> Self {
362 self.agent.config = config;
363 self
364 }
365
366 #[must_use]
368 pub fn effect_executor(mut self, effects: EffectExecutor) -> Self {
369 self.agent.effects = effects;
370 self
371 }
372
373 #[must_use]
375 pub const fn effect_recovery_policy(mut self, policy: EffectRecoveryPolicy) -> Self {
376 self.agent.effect_recovery = policy;
377 self
378 }
379
380 pub fn build(self) -> Result<Agent, AgentBuildError> {
387 if let Some(error) = self.error {
388 return Err(error);
389 }
390 if self.agent.name.trim().is_empty() {
391 return Err(AgentBuildError::EmptyName);
392 }
393 if self.agent.config.max_turns == 0 {
394 return Err(AgentBuildError::ZeroMaxTurns);
395 }
396 if self.agent.min_successful_tool_calls > 0 && self.agent.tools.is_empty() {
397 return Err(AgentBuildError::MinimumSuccessfulToolCallsWithoutTool {
398 minimum: self.agent.min_successful_tool_calls,
399 });
400 }
401 if let Some(collision) = self
402 .agent
403 .agents
404 .model_specs()
405 .into_iter()
406 .find(|spec| self.agent.tools.contains(&spec.name))
407 {
408 return Err(AgentBuildError::CallableNameCollision(collision.name));
409 }
410 Ok(self.agent)
411 }
412
413 pub fn prompt(
419 self,
420 input: impl Into<String> + Send + 'static,
421 ) -> AgentFuture<'static, Result<AgentOutcome, AgentPromptError>> {
422 let input = input.into();
423 Box::pin(async move {
424 let agent = self.build()?;
425 Ok(agent.prompt(input).await?)
426 })
427 }
428
429 pub fn prompt_text(
436 self,
437 input: impl Into<String> + Send + 'static,
438 ) -> AgentFuture<'static, Result<String, AgentPromptError>> {
439 let input = input.into();
440 Box::pin(async move {
441 let agent = self.build()?;
442 Ok(agent.prompt_text(input).await?)
443 })
444 }
445
446 pub fn build_structured<T>(
456 self,
457 name: impl Into<String>,
458 ) -> Result<StructuredAgent<T>, AgentBuildError>
459 where
460 T: JsonSchema + serde::de::DeserializeOwned + Send + 'static,
461 {
462 self.build_structured_with_strictness::<T>(name, true)
463 }
464
465 pub fn build_structured_with_strictness<T>(
476 self,
477 name: impl Into<String>,
478 strict: bool,
479 ) -> Result<StructuredAgent<T>, AgentBuildError>
480 where
481 T: JsonSchema + serde::de::DeserializeOwned + Send + 'static,
482 {
483 self.build()
484 .map(|agent| agent.into_structured_with_strictness::<T>(name, strict))
485 }
486}
487
488impl std::fmt::Debug for AgentBuilder {
489 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
490 formatter
491 .debug_struct("AgentBuilder")
492 .field("agent", &self.agent.name)
493 .field("error", &self.error)
494 .finish_non_exhaustive()
495 }
496}
497
498#[cfg(test)]
499mod tests {
500 use std::{collections::BTreeMap, sync::Arc};
501
502 use runifold_core::{
503 CapabilityId, CapabilitySet, EffectClass, RetrySafety, RiskLevel, RunErrorKind,
504 };
505 use runifold_model::{
506 ContentPart, FinishReason, ModelRef, ModelStreamEvent, OutputFormat, ProviderToolSpec,
507 ResponseMode,
508 };
509 use runifold_testkit::ScriptedModel;
510 use runifold_tool::{Tool, ToolContext, ToolDescriptor, ToolError, ToolFuture, ToolOutput};
511 use schemars::JsonSchema;
512 use serde::Deserialize;
513 use serde_json::json;
514
515 use crate::{Agent, AgentBuildError, AgentDescriptor, AgentPromptError};
516
517 struct TestTool {
518 descriptor: ToolDescriptor,
519 }
520
521 #[derive(Deserialize, JsonSchema)]
522 struct TypedAnswer {
523 value: u32,
524 }
525
526 impl TestTool {
527 fn named(name: &str) -> Self {
528 Self {
529 descriptor: ToolDescriptor {
530 id: CapabilityId::new(),
531 name: name.into(),
532 version: "1".into(),
533 description: "test".into(),
534 input_schema: json!({"type": "object"}),
535 output_schema: json!({"type": "object"}),
536 effect: EffectClass::Pure,
537 risk: RiskLevel::Low,
538 metadata: BTreeMap::new(),
539 },
540 }
541 }
542 }
543
544 impl Tool for TestTool {
545 fn descriptor(&self) -> &ToolDescriptor {
546 &self.descriptor
547 }
548
549 fn invoke(
550 &self,
551 input: serde_json::Value,
552 _context: ToolContext,
553 ) -> ToolFuture<'_, Result<ToolOutput, ToolError>> {
554 Box::pin(async move { Ok(ToolOutput::model_visible(input)) })
555 }
556 }
557
558 #[test]
559 fn fluent_builder_assembles_the_canonical_agent() {
560 let model = Arc::new(ScriptedModel::new());
561 let agent = Agent::builder("worker", model, ModelRef::new("test", "scripted"))
562 .system("Be precise")
563 .tool(TestTool::named("lookup"))
564 .min_successful_tool_calls(3)
565 .max_turns(4)
566 .build()
567 .unwrap();
568
569 assert_eq!(agent.name, "worker");
570 assert_eq!(agent.instructions.len(), 1);
571 assert!(agent.tools.contains("lookup"));
572 assert_eq!(agent.config.max_turns, 4);
573 assert_eq!(agent.min_successful_tool_calls, 3);
574 assert_eq!(agent.callable_capabilities().len(), 1);
575 }
576
577 #[test]
578 fn builder_rejects_a_tool_minimum_without_a_local_tool() {
579 let error = Agent::builder(
580 "worker",
581 Arc::new(ScriptedModel::new()),
582 ModelRef::new("test", "scripted"),
583 )
584 .min_successful_tool_calls(1)
585 .build()
586 .unwrap_err();
587
588 assert!(matches!(
589 error,
590 AgentBuildError::MinimumSuccessfulToolCallsWithoutTool { minimum: 1 }
591 ));
592 }
593
594 #[test]
595 fn builder_retains_generation_provider_and_delivery_controls() {
596 let provider_tool = ProviderToolSpec::new("ark", "web_search").unwrap();
597 let agent = Agent::builder(
598 "researcher",
599 Arc::new(ScriptedModel::new()),
600 ModelRef::new("ark", "doubao"),
601 )
602 .temperature(0.2)
603 .top_p(0.8)
604 .max_output_tokens(4_096)
605 .response_mode(ResponseMode::Complete)
606 .provider_tool(provider_tool)
607 .provider_options("ark", json!({"thinking": {"type": "enabled"}}))
608 .build()
609 .unwrap();
610
611 assert_eq!(agent.generation.temperature, Some(0.2));
612 assert_eq!(agent.generation.top_p, Some(0.8));
613 assert_eq!(agent.generation.max_output_tokens, Some(4_096));
614 assert_eq!(agent.response_mode, ResponseMode::Complete);
615 assert_eq!(agent.provider_tools[0].tool_type, "web_search");
616 assert_eq!(agent.provider_options["ark"]["thinking"]["type"], "enabled");
617 }
618
619 #[test]
620 fn build_rejects_tool_and_agent_name_collisions() {
621 let model = Arc::new(ScriptedModel::new());
622 let child = Arc::new(Agent::new(
623 "child",
624 model.clone(),
625 ModelRef::new("test", "child"),
626 ));
627 let error = Agent::builder("parent", model, ModelRef::new("test", "parent"))
628 .tool(TestTool::named("search"))
629 .child(
630 AgentDescriptor::new("search", "delegate search"),
631 child,
632 CapabilitySet::new(),
633 )
634 .build()
635 .unwrap_err();
636
637 assert_eq!(
638 error,
639 AgentBuildError::CallableNameCollision("search".into())
640 );
641 }
642
643 #[test]
644 fn builder_derives_a_strict_output_schema_from_a_rust_type() {
645 let example = TypedAnswer { value: 7 };
646 assert_eq!(example.value, 7);
647 let agent = Agent::builder(
648 "worker",
649 Arc::new(ScriptedModel::new()),
650 ModelRef::new("test", "scripted"),
651 )
652 .structured_output::<TypedAnswer>("typed_answer")
653 .build()
654 .unwrap();
655
656 let OutputFormat::JsonSchema {
657 name,
658 schema,
659 strict,
660 } = agent.output_format
661 else {
662 panic!("expected JSON-schema output");
663 };
664 assert_eq!(name, "typed_answer");
665 assert!(strict);
666 assert_eq!(schema["properties"]["value"]["type"], "integer");
667 }
668
669 #[test]
670 fn structured_builder_can_disable_provider_strictness_without_losing_typed_binding() {
671 let agent = Agent::builder(
672 "worker",
673 Arc::new(ScriptedModel::new()),
674 ModelRef::new("test", "scripted"),
675 )
676 .build_structured_with_strictness::<TypedAnswer>("typed_answer", false)
677 .unwrap();
678
679 let OutputFormat::JsonSchema { strict, .. } = &agent.agent().output_format else {
680 panic!("expected JSON-schema output");
681 };
682 assert!(!strict);
683 }
684
685 #[test]
686 fn builder_prompt_text_is_a_single_use_golden_path() {
687 let model = ScriptedModel::new();
688 model.enqueue([
689 ModelStreamEvent::ResponseStarted {
690 id: Some("response-1".into()),
691 model: ModelRef::new("test", "scripted"),
692 },
693 ModelStreamEvent::ContentPartCompleted {
694 index: 0,
695 part: ContentPart::text("done"),
696 },
697 ModelStreamEvent::ResponseCompleted {
698 finish_reason: FinishReason::Stop,
699 provider_metadata: BTreeMap::new(),
700 },
701 ]);
702
703 let text = futures_executor::block_on(
704 Agent::builder("worker", Arc::new(model), ModelRef::new("test", "scripted"))
705 .system("Be precise")
706 .prompt_text("start"),
707 )
708 .unwrap();
709
710 assert_eq!(text, "done");
711 }
712
713 #[test]
714 fn builder_prompt_reports_build_failures_before_model_execution() {
715 let error = futures_executor::block_on(
716 Agent::builder(
717 "",
718 Arc::new(ScriptedModel::new()),
719 ModelRef::new("test", "scripted"),
720 )
721 .prompt("start"),
722 )
723 .unwrap_err();
724
725 assert!(matches!(
726 &error,
727 AgentPromptError::Build(AgentBuildError::EmptyName)
728 ));
729 assert_eq!(error.run_error_kind(), RunErrorKind::InvalidInput);
730 assert_eq!(error.retry_safety(), RetrySafety::Safe);
731 assert_eq!(error.to_run_error().code(), "runifold.invalid_input");
732 }
733}