1use std::{
7 fmt,
8 io::{self, Write},
9 marker::PhantomData,
10 sync::Arc,
11};
12
13use schemars::{JsonSchema, generate::SchemaSettings};
14use serde::{Serialize, de::DeserializeOwned};
15use serde_json::Value;
16use stateknot_core::{
17 AgentDescriptor, AgentDescriptorError, AgentExecutionConfig, AgentInstructions, AgentRequest,
18 AgentResult, AgentResultProvenance, AgentResultValidationError, AgentStructuredOutputStrategy,
19 AgentTools, BoundedJson, BudgetLimits, Digest, GraphSchemaValidationError, JsonLimits,
20 ModelDescriptor, SchemaId, SchemaReference,
21};
22use thiserror::Error;
23
24use crate::{JsonSchemaRegistry, JsonSchemaRegistryBuilder, JsonSchemaRegistryError};
25
26#[derive(Clone, Copy, Debug, Eq, PartialEq)]
28#[non_exhaustive]
29pub enum AgentSchemaRole {
30 Input,
32 Output,
34}
35
36impl fmt::Display for AgentSchemaRole {
37 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
38 formatter.write_str(match self {
39 Self::Input => "input",
40 Self::Output => "output",
41 })
42 }
43}
44
45pub struct AgentBuilder<I, O> {
52 metadata: stateknot_core::CapabilityMetadata,
53 input_schema_id: SchemaId,
54 output_schema_id: SchemaId,
55 model: ModelDescriptor,
56 instructions: AgentInstructions,
57 tools: AgentTools,
58 execution: AgentExecutionConfig,
59 budget_limits: BudgetLimits,
60 input_json_limits: JsonLimits,
61 marker: PhantomData<fn(I) -> O>,
62}
63
64impl<I, O> AgentBuilder<I, O> {
65 #[must_use]
68 #[allow(clippy::too_many_arguments)]
69 pub fn new(
70 metadata: stateknot_core::CapabilityMetadata,
71 input_schema_id: SchemaId,
72 output_schema_id: SchemaId,
73 model: ModelDescriptor,
74 instructions: AgentInstructions,
75 execution: AgentExecutionConfig,
76 ) -> Self {
77 Self {
78 metadata,
79 input_schema_id,
80 output_schema_id,
81 model,
82 instructions,
83 tools: AgentTools::empty(),
84 execution,
85 budget_limits: BudgetLimits::empty(),
86 input_json_limits: JsonLimits::DEFAULT,
87 marker: PhantomData,
88 }
89 }
90
91 #[must_use]
93 pub fn with_tools(mut self, tools: AgentTools) -> Self {
94 self.tools = tools;
95 self
96 }
97
98 #[must_use]
100 pub fn with_budget_limits(mut self, budget_limits: BudgetLimits) -> Self {
101 self.budget_limits = budget_limits;
102 self
103 }
104
105 #[must_use]
107 pub const fn with_input_json_limits(mut self, limits: JsonLimits) -> Self {
108 self.input_json_limits = limits;
109 self
110 }
111}
112
113impl<I, O> AgentBuilder<I, O>
114where
115 I: JsonSchema,
116 O: JsonSchema,
117{
118 pub fn build(self) -> Result<TypedAgentDefinition<I, O>, AgentBuilderError> {
126 if self.input_schema_id == self.output_schema_id {
127 return Err(AgentBuilderError::DuplicateSchemaId);
128 }
129
130 let version = self.metadata.identity().version();
131 let (input_schema, input_document) = generate_schema::<I>(
132 self.input_schema_id,
133 version,
134 AgentSchemaRole::Input,
135 SchemaContract::Serialize,
136 )?;
137 let (output_schema, output_document) = generate_schema::<O>(
138 self.output_schema_id,
139 version,
140 AgentSchemaRole::Output,
141 SchemaContract::Deserialize,
142 )?;
143 let descriptor = AgentDescriptor::new(
144 self.metadata,
145 input_schema,
146 output_schema,
147 self.model,
148 self.instructions,
149 self.tools,
150 self.execution,
151 self.budget_limits,
152 )
153 .map_err(AgentBuilderError::descriptor)?;
154
155 Ok(TypedAgentDefinition {
156 descriptor,
157 input_document,
158 output_document,
159 input_json_limits: self.input_json_limits,
160 marker: PhantomData,
161 })
162 }
163}
164
165impl<I, O> fmt::Debug for AgentBuilder<I, O> {
166 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
167 formatter
168 .debug_struct("AgentBuilder")
169 .field("agent", self.metadata.identity())
170 .field("input_schema_id", &self.input_schema_id)
171 .field("output_schema_id", &self.output_schema_id)
172 .field("model", self.model.metadata().identity())
173 .field("tool_count", &self.tools.len())
174 .field("has_budget_limits", &!self.budget_limits.is_empty())
175 .finish_non_exhaustive()
176 }
177}
178
179pub struct TypedAgentDefinition<I, O> {
182 descriptor: AgentDescriptor,
183 input_document: Value,
184 output_document: Value,
185 input_json_limits: JsonLimits,
186 marker: PhantomData<fn(I) -> O>,
187}
188
189impl<I, O> TypedAgentDefinition<I, O> {
190 #[must_use]
192 pub const fn descriptor(&self) -> &AgentDescriptor {
193 &self.descriptor
194 }
195
196 #[must_use]
198 pub const fn input_schema_document(&self) -> &Value {
199 &self.input_document
200 }
201
202 #[must_use]
204 pub const fn output_schema_document(&self) -> &Value {
205 &self.output_document
206 }
207
208 pub fn register_schemas(
218 &self,
219 mut registry: JsonSchemaRegistryBuilder,
220 ) -> Result<JsonSchemaRegistryBuilder, AgentSchemaRegistrationError> {
221 registry
222 .register(
223 self.descriptor.input_schema().clone(),
224 self.input_document.clone(),
225 )
226 .map_err(|source| AgentSchemaRegistrationError::new(AgentSchemaRole::Input, source))?;
227 registry
228 .register(
229 self.descriptor.output_schema().clone(),
230 self.output_document.clone(),
231 )
232 .map_err(|source| AgentSchemaRegistrationError::new(AgentSchemaRole::Output, source))?;
233 Ok(registry)
234 }
235
236 pub fn bind(
244 self,
245 registry: Arc<JsonSchemaRegistry>,
246 ) -> Result<TypedAgent<I, O>, TypedAgentBindError> {
247 validate_definition_schemas(&self.descriptor, ®istry)?;
248 Ok(TypedAgent {
249 descriptor: self.descriptor,
250 schemas: registry,
251 input_json_limits: self.input_json_limits,
252 marker: PhantomData,
253 })
254 }
255}
256
257impl<I, O> fmt::Debug for TypedAgentDefinition<I, O> {
258 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
259 formatter
260 .debug_struct("TypedAgentDefinition")
261 .field("descriptor", &self.descriptor)
262 .field("input_schema_bytes", &canonical_len(&self.input_document))
263 .field("output_schema_bytes", &canonical_len(&self.output_document))
264 .finish_non_exhaustive()
265 }
266}
267
268pub struct TypedAgent<I, O> {
274 descriptor: AgentDescriptor,
275 schemas: Arc<JsonSchemaRegistry>,
276 input_json_limits: JsonLimits,
277 marker: PhantomData<fn(I) -> O>,
278}
279
280impl<I, O> TypedAgent<I, O> {
281 #[must_use]
283 pub const fn descriptor(&self) -> &AgentDescriptor {
284 &self.descriptor
285 }
286
287 #[must_use]
289 pub const fn schema_registry(&self) -> &Arc<JsonSchemaRegistry> {
290 &self.schemas
291 }
292}
293
294impl<I, O> TypedAgent<I, O>
295where
296 I: Serialize,
297{
298 pub fn prepare_request(
307 &self,
308 input: &I,
309 budget_limits: BudgetLimits,
310 ) -> Result<AgentRequest, TypedAgentInputError> {
311 let mut writer = BoundedBuffer::new(self.input_json_limits.max_bytes());
312 if serde_json::to_writer(&mut writer, input).is_err() {
313 return Err(if writer.overflowed {
314 TypedAgentInputError::ResourceLimit
315 } else {
316 TypedAgentInputError::Serialization
317 });
318 }
319 let input = BoundedJson::from_slice_with_limits(&writer.bytes, self.input_json_limits)
320 .map_err(|_| TypedAgentInputError::ResourceLimit)?;
321 match self
322 .schemas
323 .validate_bounded(self.descriptor.input_schema(), &input)
324 {
325 Ok(()) => Ok(AgentRequest::new(
326 self.descriptor.input_schema().clone(),
327 input,
328 budget_limits,
329 )),
330 Err(GraphSchemaValidationError::Rejected) => Err(TypedAgentInputError::SchemaRejected),
331 Err(GraphSchemaValidationError::Unavailable) => {
332 Err(TypedAgentInputError::RegistryInvariant)
333 }
334 Err(_) => Err(TypedAgentInputError::RegistryInvariant),
335 }
336 }
337}
338
339impl<I, O> TypedAgent<I, O>
340where
341 O: DeserializeOwned,
342{
343 pub fn decode_result(
351 &self,
352 result: &AgentResult,
353 expected_provenance: &AgentResultProvenance,
354 request: &AgentRequest,
355 budget: &stateknot_core::ResolvedBudget,
356 ) -> Result<O, TypedAgentOutputError> {
357 result
358 .validate_for(expected_provenance, request, &self.descriptor, budget)
359 .map_err(TypedAgentOutputError::validation)?;
360 match self
361 .schemas
362 .validate_bounded(self.descriptor.output_schema(), result.output())
363 {
364 Ok(()) => {}
365 Err(GraphSchemaValidationError::Rejected) => {
366 return Err(TypedAgentOutputError::SchemaRejected);
367 }
368 Err(GraphSchemaValidationError::Unavailable) => {
369 return Err(TypedAgentOutputError::RegistryInvariant);
370 }
371 Err(_) => return Err(TypedAgentOutputError::RegistryInvariant),
372 }
373 serde::Deserialize::deserialize(result.output().as_value())
374 .map_err(|_| TypedAgentOutputError::Deserialization)
375 }
376}
377
378impl<I, O> Clone for TypedAgent<I, O> {
379 fn clone(&self) -> Self {
380 Self {
381 descriptor: self.descriptor.clone(),
382 schemas: Arc::clone(&self.schemas),
383 input_json_limits: self.input_json_limits,
384 marker: PhantomData,
385 }
386 }
387}
388
389impl<I, O> fmt::Debug for TypedAgent<I, O> {
390 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
391 formatter
392 .debug_struct("TypedAgent")
393 .field("descriptor", &self.descriptor)
394 .field("schemas", &self.schemas)
395 .field("input_json_limits", &self.input_json_limits)
396 .finish_non_exhaustive()
397 }
398}
399
400#[derive(Clone, Debug, Eq, Error, PartialEq)]
402#[non_exhaustive]
403pub enum AgentBuilderError {
404 #[error("typed agent input and output schema identifiers must be distinct")]
406 DuplicateSchemaId,
407 #[error("generated {role} schema could not be represented as JSON")]
409 SchemaSerialization {
410 role: AgentSchemaRole,
412 },
413 #[error("generated {role} schema exceeds the bounded schema envelope")]
415 SchemaResourceLimit {
416 role: AgentSchemaRole,
418 },
419 #[error("typed agent descriptor is invalid: {source}")]
421 Descriptor {
422 #[source]
424 source: AgentDescriptorError,
425 },
426}
427
428impl AgentBuilderError {
429 const fn descriptor(source: AgentDescriptorError) -> Self {
430 Self::Descriptor { source }
431 }
432}
433
434#[derive(Clone, Debug, Eq, Error, PartialEq)]
436#[error("generated {role} schema registration failed: {source}")]
437pub struct AgentSchemaRegistrationError {
438 role: AgentSchemaRole,
439 #[source]
440 source: JsonSchemaRegistryError,
441}
442
443impl AgentSchemaRegistrationError {
444 const fn new(role: AgentSchemaRole, source: JsonSchemaRegistryError) -> Self {
445 Self { role, source }
446 }
447
448 #[must_use]
450 pub const fn role(&self) -> AgentSchemaRole {
451 self.role
452 }
453
454 #[must_use]
456 pub const fn source_error(&self) -> &JsonSchemaRegistryError {
457 &self.source
458 }
459}
460
461#[derive(Clone, Debug, Eq, Error, PartialEq)]
463#[non_exhaustive]
464pub enum TypedAgentBindError {
465 #[error("typed agent referenced a schema that is absent from the offline registry")]
467 SchemaUnavailable {
468 schema: Box<SchemaReference>,
470 },
471 #[error("typed agent schema document exceeds the bounded profile-validation envelope")]
473 InvalidSchemaDocument {
474 schema: Box<SchemaReference>,
476 },
477 #[error("typed agent schema is incompatible with its pinned provider profile")]
479 ProfileRejected {
480 schema: Box<SchemaReference>,
482 profile: Box<SchemaReference>,
484 },
485}
486
487#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
489#[non_exhaustive]
490pub enum TypedAgentInputError {
491 #[error("typed agent input serialization failed")]
493 Serialization,
494 #[error("typed agent input exceeds its bounded JSON limits")]
496 ResourceLimit,
497 #[error("typed agent input was rejected by its pinned schema")]
499 SchemaRejected,
500 #[error("typed agent schema registry invariant was violated")]
502 RegistryInvariant,
503}
504
505#[derive(Clone, Debug, Eq, Error, PartialEq)]
507#[non_exhaustive]
508pub enum TypedAgentOutputError {
509 #[error("typed agent result validation failed: {source}")]
511 ResultValidation {
512 #[source]
514 source: AgentResultValidationError,
515 },
516 #[error("typed agent output was rejected by its pinned schema")]
518 SchemaRejected,
519 #[error("typed agent schema registry invariant was violated")]
521 RegistryInvariant,
522 #[error("typed agent output deserialization failed")]
524 Deserialization,
525}
526
527impl TypedAgentOutputError {
528 const fn validation(source: AgentResultValidationError) -> Self {
529 Self::ResultValidation { source }
530 }
531}
532
533#[derive(Clone, Copy)]
534enum SchemaContract {
535 Serialize,
536 Deserialize,
537}
538
539fn generate_schema<T: JsonSchema>(
540 id: SchemaId,
541 version: stateknot_core::Version,
542 role: AgentSchemaRole,
543 contract: SchemaContract,
544) -> Result<(SchemaReference, Value), AgentBuilderError> {
545 let settings = match contract {
546 SchemaContract::Serialize => SchemaSettings::draft2020_12().for_serialize(),
547 SchemaContract::Deserialize => SchemaSettings::draft2020_12().for_deserialize(),
548 };
549 let schema = settings.into_generator().into_root_schema_for::<T>();
550 let mut document = serde_json::to_value(schema)
551 .map_err(|_| AgentBuilderError::SchemaSerialization { role })?;
552 let object = document
553 .as_object_mut()
554 .ok_or(AgentBuilderError::SchemaSerialization { role })?;
555 object.insert("$id".to_owned(), Value::String(id.as_str().to_owned()));
556 let canonical = serde_json_canonicalizer::to_vec(&document)
557 .map_err(|_| AgentBuilderError::SchemaSerialization { role })?;
558 BoundedJson::from_slice_with_limits(&canonical, JsonLimits::MAXIMUM)
559 .map_err(|_| AgentBuilderError::SchemaResourceLimit { role })?;
560 let reference = SchemaReference::new(id, version, Digest::sha256(&canonical));
561 Ok((reference, document))
562}
563
564fn validate_definition_schemas(
565 descriptor: &AgentDescriptor,
566 registry: &JsonSchemaRegistry,
567) -> Result<(), TypedAgentBindError> {
568 require_schema(registry, descriptor.input_schema())?;
569 require_schema(registry, descriptor.output_schema())?;
570
571 for profile in [
572 descriptor.model().capabilities().tools().schema_profile(),
573 descriptor
574 .model()
575 .capabilities()
576 .structured_output()
577 .schema_profile(),
578 ]
579 .into_iter()
580 .flatten()
581 {
582 require_schema(registry, profile)?;
583 }
584
585 let output_profile = match descriptor.execution().structured_output() {
586 AgentStructuredOutputStrategy::ModelNative => descriptor
587 .model()
588 .capabilities()
589 .structured_output()
590 .schema_profile(),
591 AgentStructuredOutputStrategy::ToolCall => {
592 descriptor.model().capabilities().tools().schema_profile()
593 }
594 }
595 .expect("AgentDescriptor guarantees a profile for its structured-output strategy");
596 validate_profile(registry, output_profile, descriptor.output_schema())?;
597
598 if !descriptor.tools().is_empty() {
599 let tool_profile = descriptor
600 .model()
601 .capabilities()
602 .tools()
603 .schema_profile()
604 .expect("AgentDescriptor guarantees a tool profile for ordinary tools");
605 for tool in descriptor.tools() {
606 require_schema(registry, tool.input_schema())?;
607 require_schema(registry, tool.output_schema())?;
608 validate_profile(registry, tool_profile, tool.input_schema())?;
609 }
610 }
611 Ok(())
612}
613
614fn require_schema(
615 registry: &JsonSchemaRegistry,
616 schema: &SchemaReference,
617) -> Result<(), TypedAgentBindError> {
618 if registry.contains(schema) {
619 Ok(())
620 } else {
621 Err(TypedAgentBindError::SchemaUnavailable {
622 schema: Box::new(schema.clone()),
623 })
624 }
625}
626
627fn validate_profile(
628 registry: &JsonSchemaRegistry,
629 profile: &SchemaReference,
630 schema: &SchemaReference,
631) -> Result<(), TypedAgentBindError> {
632 let bytes =
633 registry
634 .canonical_bytes(schema)
635 .ok_or_else(|| TypedAgentBindError::SchemaUnavailable {
636 schema: Box::new(schema.clone()),
637 })?;
638 let document =
639 BoundedJson::from_slice_with_limits(bytes, JsonLimits::MAXIMUM).map_err(|_| {
640 TypedAgentBindError::InvalidSchemaDocument {
641 schema: Box::new(schema.clone()),
642 }
643 })?;
644 match registry.validate_bounded(profile, &document) {
645 Ok(()) => Ok(()),
646 Err(GraphSchemaValidationError::Unavailable) => {
647 Err(TypedAgentBindError::SchemaUnavailable {
648 schema: Box::new(profile.clone()),
649 })
650 }
651 Err(_) => Err(TypedAgentBindError::ProfileRejected {
652 schema: Box::new(schema.clone()),
653 profile: Box::new(profile.clone()),
654 }),
655 }
656}
657
658fn canonical_len(document: &Value) -> usize {
659 serde_json_canonicalizer::to_vec(document).map_or(0, |bytes| bytes.len())
660}
661
662struct BoundedBuffer {
663 bytes: Vec<u8>,
664 maximum: usize,
665 overflowed: bool,
666}
667
668impl BoundedBuffer {
669 fn new(maximum: usize) -> Self {
670 Self {
671 bytes: Vec::with_capacity(maximum.min(4096)),
672 maximum,
673 overflowed: false,
674 }
675 }
676}
677
678impl Write for BoundedBuffer {
679 fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
680 let Some(length) = self.bytes.len().checked_add(buffer.len()) else {
681 self.overflowed = true;
682 return Err(io::Error::other("typed JSON byte limit exceeded"));
683 };
684 if length > self.maximum {
685 self.overflowed = true;
686 return Err(io::Error::other("typed JSON byte limit exceeded"));
687 }
688 self.bytes.extend_from_slice(buffer);
689 Ok(buffer.len())
690 }
691
692 fn flush(&mut self) -> io::Result<()> {
693 Ok(())
694 }
695}