Skip to main content

stateknot_core/
agent.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Immutable, runtime-neutral agent definition contracts.
5
6use std::{
7    collections::{BTreeMap, btree_map},
8    fmt, slice,
9};
10
11use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
12use serde::{
13    Deserialize, Deserializer, Serialize, Serializer,
14    de::{self},
15};
16use thiserror::Error;
17
18use crate::{
19    ArtifactModality, BudgetLimits, ByteCount, CapabilityIdentity, CapabilityKind,
20    CapabilityLifecycleState, CapabilityMetadata, CapabilityName, ExecutionCount, Instruction,
21    InstructionContent, InstructionIdentity, ModelDescriptor, ModelRequest,
22    ModelStructuredOutputLevel, SchemaReference, ToolDescriptor,
23};
24
25const MEBIBYTE: u64 = 1024 * 1024;
26
27/// Ordered, non-empty trusted instructions pinned into one agent definition.
28///
29/// Serialized instruction claims are not authority. A trusted registry must
30/// authenticate every owner and resolve artifact bytes before making an agent
31/// selectable. The collection itself prevents identity ambiguity and unbounded
32/// prompt material.
33#[derive(Clone, Eq, PartialEq)]
34pub struct AgentInstructions {
35    values: Box<[Instruction]>,
36    content_bytes: ByteCount,
37}
38
39impl AgentInstructions {
40    /// Maximum number of instructions in one agent definition.
41    pub const MAX_LEN: usize = 32;
42
43    /// Maximum aggregate resolved instruction content.
44    pub const MAX_CONTENT_BYTES: ByteCount = ByteCount::new(8 * MEBIBYTE);
45
46    /// Validates and constructs an ordered non-empty instruction collection.
47    ///
48    /// # Errors
49    ///
50    /// Returns [`AgentInstructionsError`] for an empty, duplicate, unsupported,
51    /// oversized, or arithmetically unrepresentable collection.
52    pub fn try_new<I>(values: I) -> Result<Self, AgentInstructionsError>
53    where
54        I: IntoIterator<Item = Instruction>,
55    {
56        let mut normalized = Vec::new();
57        let mut content_bytes = ByteCount::ZERO;
58        for value in values {
59            push_instruction(&mut normalized, &mut content_bytes, value)?;
60        }
61        if normalized.is_empty() {
62            return Err(AgentInstructionsError::Empty);
63        }
64        Ok(Self {
65            values: normalized.into_boxed_slice(),
66            content_bytes,
67        })
68    }
69
70    /// Returns the ordered instruction slice.
71    #[must_use]
72    pub const fn as_slice(&self) -> &[Instruction] {
73        &self.values
74    }
75
76    /// Iterates in declared precedence order.
77    pub fn iter(&self) -> slice::Iter<'_, Instruction> {
78        self.values.iter()
79    }
80
81    /// Returns the number of instructions.
82    #[must_use]
83    pub const fn len(&self) -> usize {
84        self.values.len()
85    }
86
87    /// Returns whether this collection is empty.
88    ///
89    /// Valid constructed values always return `false`.
90    #[must_use]
91    pub const fn is_empty(&self) -> bool {
92        self.values.is_empty()
93    }
94
95    /// Returns aggregate resolved text or artifact bytes.
96    #[must_use]
97    pub const fn content_bytes(&self) -> ByteCount {
98        self.content_bytes
99    }
100}
101
102impl<'a> IntoIterator for &'a AgentInstructions {
103    type Item = &'a Instruction;
104    type IntoIter = slice::Iter<'a, Instruction>;
105
106    fn into_iter(self) -> Self::IntoIter {
107        self.iter()
108    }
109}
110
111impl TryFrom<Vec<Instruction>> for AgentInstructions {
112    type Error = AgentInstructionsError;
113
114    fn try_from(value: Vec<Instruction>) -> Result<Self, Self::Error> {
115        Self::try_new(value)
116    }
117}
118
119impl fmt::Debug for AgentInstructions {
120    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
121        formatter
122            .debug_struct("AgentInstructions")
123            .field("count", &self.len())
124            .field("content_bytes", &self.content_bytes)
125            .finish_non_exhaustive()
126    }
127}
128
129impl Serialize for AgentInstructions {
130    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
131    where
132        S: Serializer,
133    {
134        self.values.serialize(serializer)
135    }
136}
137
138impl<'de> Deserialize<'de> for AgentInstructions {
139    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
140    where
141        D: Deserializer<'de>,
142    {
143        deserializer.deserialize_seq(AgentInstructionsVisitor)
144    }
145}
146
147struct AgentInstructionsVisitor;
148
149impl<'de> de::Visitor<'de> for AgentInstructionsVisitor {
150    type Value = AgentInstructions;
151
152    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
153        write!(
154            formatter,
155            "an array containing 1 to {} unique trusted instructions",
156            AgentInstructions::MAX_LEN
157        )
158    }
159
160    fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
161    where
162        A: de::SeqAccess<'de>,
163    {
164        let mut values = Vec::with_capacity(
165            sequence
166                .size_hint()
167                .unwrap_or_default()
168                .min(AgentInstructions::MAX_LEN),
169        );
170        let mut content_bytes = ByteCount::ZERO;
171        while let Some(value) = sequence.next_element::<Instruction>()? {
172            push_instruction(&mut values, &mut content_bytes, value).map_err(de::Error::custom)?;
173        }
174        if values.is_empty() {
175            return Err(de::Error::custom(AgentInstructionsError::Empty));
176        }
177        Ok(AgentInstructions {
178            values: values.into_boxed_slice(),
179            content_bytes,
180        })
181    }
182}
183
184impl JsonSchema for AgentInstructions {
185    fn schema_name() -> std::borrow::Cow<'static, str> {
186        "AgentInstructions".into()
187    }
188
189    fn schema_id() -> std::borrow::Cow<'static, str> {
190        concat!(module_path!(), "::AgentInstructions").into()
191    }
192
193    fn json_schema(generator: &mut SchemaGenerator) -> Schema {
194        json_schema!({
195            "type": "array",
196            "items": generator.subschema_for::<Instruction>(),
197            "minItems": 1,
198            "maxItems": 32,
199            "uniqueItems": true,
200            "description": "Ordered application-controlled instructions. Runtime additionally rejects duplicate identities, non-text instruction artifacts, and more than 8388608 resolved content bytes."
201        })
202    }
203}
204
205fn push_instruction(
206    values: &mut Vec<Instruction>,
207    content_bytes: &mut ByteCount,
208    value: Instruction,
209) -> Result<(), AgentInstructionsError> {
210    if values.len() == AgentInstructions::MAX_LEN {
211        return Err(AgentInstructionsError::TooMany {
212            max: AgentInstructions::MAX_LEN,
213            observed: AgentInstructions::MAX_LEN + 1,
214        });
215    }
216    if values
217        .iter()
218        .any(|existing| existing.identity() == value.identity())
219    {
220        return Err(AgentInstructionsError::Duplicate {
221            identity: value.identity().clone(),
222        });
223    }
224
225    let additional = match value.content() {
226        InstructionContent::Text(text) => ByteCount::new(text.text().len() as u64),
227        InstructionContent::Artifact(artifact) => {
228            let modality = artifact.representation().modality();
229            if modality != ArtifactModality::Text {
230                return Err(AgentInstructionsError::UnsupportedArtifact {
231                    index: values.len(),
232                    modality,
233                });
234            }
235            artifact.representation().byte_length()
236        }
237    };
238    let actual = content_bytes
239        .checked_add(additional)
240        .ok_or(AgentInstructionsError::ContentBytesOverflow)?;
241    if actual > AgentInstructions::MAX_CONTENT_BYTES {
242        return Err(AgentInstructionsError::ContentTooLarge {
243            maximum: AgentInstructions::MAX_CONTENT_BYTES,
244            actual,
245        });
246    }
247    *content_bytes = actual;
248    values.push(value);
249    Ok(())
250}
251
252/// Invalid agent instruction collection.
253#[derive(Clone, Debug, Eq, Error, PartialEq)]
254#[non_exhaustive]
255pub enum AgentInstructionsError {
256    /// An agent had no trusted instruction.
257    #[error("agent instructions must not be empty")]
258    Empty,
259    /// The hard instruction-count ceiling was exceeded.
260    #[error("agent instructions contain at least {observed} values; maximum is {max}")]
261    TooMany {
262        /// Maximum accepted instruction count.
263        max: usize,
264        /// Minimum count observed before validation stopped.
265        observed: usize,
266    },
267    /// One versioned instruction identity appeared more than once.
268    #[error("agent instructions contain duplicate identity {identity:?}")]
269    Duplicate {
270        /// Repeated instruction identity.
271        identity: InstructionIdentity,
272    },
273    /// An instruction artifact was not text material.
274    #[error("agent instruction {index} uses unsupported artifact modality {modality:?}")]
275    UnsupportedArtifact {
276        /// Zero-based instruction position.
277        index: usize,
278        /// Rejected artifact modality.
279        modality: ArtifactModality,
280    },
281    /// Aggregate content-byte accounting overflowed.
282    #[error("agent instruction content byte count overflowed")]
283    ContentBytesOverflow,
284    /// Aggregate resolved content exceeded the hard ceiling.
285    #[error("agent instruction content is {actual}; maximum is {maximum}")]
286    ContentTooLarge {
287        /// Immutable aggregate limit.
288        maximum: ByteCount,
289        /// Rejected aggregate size.
290        actual: ByteCount,
291    },
292}
293
294/// Canonically ordered, registry-resolved tools exposed by one agent.
295///
296/// Model tool names are registry-local. This collection rejects collisions
297/// across owners and versions because a model request cannot disambiguate them.
298#[derive(Clone, Eq, PartialEq)]
299pub struct AgentTools(BTreeMap<CapabilityName, ToolDescriptor>);
300
301impl AgentTools {
302    /// Maximum number of ordinary tools exposed by one agent.
303    pub const MAX_LEN: usize = 128;
304
305    /// Constructs an empty tool collection.
306    #[must_use]
307    pub const fn empty() -> Self {
308        Self(BTreeMap::new())
309    }
310
311    /// Validates and constructs a canonical tool collection.
312    ///
313    /// # Errors
314    ///
315    /// Returns [`AgentToolsError`] for a duplicate model-visible name, retired
316    /// dependency, or count above the hard ceiling.
317    pub fn try_new<I>(values: I) -> Result<Self, AgentToolsError>
318    where
319        I: IntoIterator<Item = ToolDescriptor>,
320    {
321        let mut normalized = BTreeMap::new();
322        for value in values {
323            insert_tool(&mut normalized, value)?;
324        }
325        Ok(Self(normalized))
326    }
327
328    /// Returns the number of tools.
329    #[must_use]
330    pub fn len(&self) -> usize {
331        self.0.len()
332    }
333
334    /// Returns whether no ordinary tool is exposed.
335    #[must_use]
336    pub fn is_empty(&self) -> bool {
337        self.0.is_empty()
338    }
339
340    /// Returns one tool by its model-visible registry-local name.
341    #[must_use]
342    pub fn get(&self, name: &CapabilityName) -> Option<&ToolDescriptor> {
343        self.0.get(name)
344    }
345
346    /// Iterates descriptors in canonical name order.
347    pub fn iter(&self) -> btree_map::Values<'_, CapabilityName, ToolDescriptor> {
348        self.0.values()
349    }
350
351    fn contains_name(&self, name: &str) -> bool {
352        self.0.keys().any(|candidate| candidate.as_str() == name)
353    }
354}
355
356impl Default for AgentTools {
357    fn default() -> Self {
358        Self::empty()
359    }
360}
361
362impl<'a> IntoIterator for &'a AgentTools {
363    type Item = &'a ToolDescriptor;
364    type IntoIter = btree_map::Values<'a, CapabilityName, ToolDescriptor>;
365
366    fn into_iter(self) -> Self::IntoIter {
367        self.iter()
368    }
369}
370
371impl TryFrom<Vec<ToolDescriptor>> for AgentTools {
372    type Error = AgentToolsError;
373
374    fn try_from(value: Vec<ToolDescriptor>) -> Result<Self, Self::Error> {
375        Self::try_new(value)
376    }
377}
378
379impl fmt::Debug for AgentTools {
380    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
381        formatter
382            .debug_struct("AgentTools")
383            .field("count", &self.len())
384            .finish_non_exhaustive()
385    }
386}
387
388impl Serialize for AgentTools {
389    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
390    where
391        S: Serializer,
392    {
393        serializer.collect_seq(self.iter())
394    }
395}
396
397impl<'de> Deserialize<'de> for AgentTools {
398    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
399    where
400        D: Deserializer<'de>,
401    {
402        deserializer.deserialize_seq(AgentToolsVisitor)
403    }
404}
405
406struct AgentToolsVisitor;
407
408impl<'de> de::Visitor<'de> for AgentToolsVisitor {
409    type Value = AgentTools;
410
411    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
412        write!(
413            formatter,
414            "an array containing at most {} active or deprecated tools with unique names",
415            AgentTools::MAX_LEN
416        )
417    }
418
419    fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
420    where
421        A: de::SeqAccess<'de>,
422    {
423        let mut values = BTreeMap::new();
424        while let Some(value) = sequence.next_element::<ToolDescriptor>()? {
425            insert_tool(&mut values, value).map_err(de::Error::custom)?;
426        }
427        Ok(AgentTools(values))
428    }
429}
430
431impl JsonSchema for AgentTools {
432    fn schema_name() -> std::borrow::Cow<'static, str> {
433        "AgentTools".into()
434    }
435
436    fn schema_id() -> std::borrow::Cow<'static, str> {
437        concat!(module_path!(), "::AgentTools").into()
438    }
439
440    fn json_schema(generator: &mut SchemaGenerator) -> Schema {
441        json_schema!({
442            "type": "array",
443            "items": generator.subschema_for::<ToolDescriptor>(),
444            "maxItems": 128,
445            "uniqueItems": true,
446            "description": "Tools serialize in model-visible name order. Runtime rejects duplicate names across owners or versions and retired descriptors."
447        })
448    }
449}
450
451fn insert_tool(
452    values: &mut BTreeMap<CapabilityName, ToolDescriptor>,
453    value: ToolDescriptor,
454) -> Result<(), AgentToolsError> {
455    let name = value.metadata().identity().capability().name().clone();
456    if values.contains_key(&name) {
457        return Err(AgentToolsError::DuplicateName { name });
458    }
459    if values.len() == AgentTools::MAX_LEN {
460        return Err(AgentToolsError::TooMany {
461            max: AgentTools::MAX_LEN,
462            observed: AgentTools::MAX_LEN + 1,
463        });
464    }
465    if value.metadata().lifecycle().state() == CapabilityLifecycleState::Retired {
466        return Err(AgentToolsError::Retired { name });
467    }
468    values.insert(name, value);
469    Ok(())
470}
471
472/// Invalid agent tool collection.
473#[derive(Clone, Debug, Eq, Error, PartialEq)]
474#[non_exhaustive]
475pub enum AgentToolsError {
476    /// Two descriptors would expose the same name to the model.
477    #[error("agent tools contain duplicate model-visible name {name}")]
478    DuplicateName {
479        /// Colliding registry-local name.
480        name: CapabilityName,
481    },
482    /// The collection exceeded its hard count ceiling.
483    #[error("agent tools contain at least {observed} values; maximum is {max}")]
484    TooMany {
485        /// Maximum accepted tool count.
486        max: usize,
487        /// Minimum count observed before validation stopped.
488        observed: usize,
489    },
490    /// A retired tool cannot enter a new executable definition.
491    #[error("agent tool {name} is retired")]
492    Retired {
493        /// Retired model-visible name.
494        name: CapabilityName,
495    },
496}
497
498/// Resolved mechanism used to obtain a typed final output.
499///
500/// Builders may negotiate a strategy, but durable descriptors store only the
501/// resolved value so recovery cannot change behavior after a model upgrade.
502#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, PartialEq, Serialize)]
503#[serde(rename_all = "snake_case")]
504pub enum AgentStructuredOutputStrategy {
505    /// Use the model binding's native JSON Schema response format.
506    ModelNative,
507    /// Use one framework-owned synthetic final-output tool definition.
508    ToolCall,
509}
510
511/// Deterministic scheduling mode for ordinary tool calls from one response.
512#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, PartialEq, Serialize)]
513#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
514pub enum AgentToolConcurrency {
515    /// Execute every accepted tool call in model proposal order.
516    Sequential {},
517    /// Parallelize read-only calls up to a finite bound; serialize all writes.
518    ParallelReadOnly {
519        /// Maximum concurrently executing read-only calls.
520        max_concurrency: ExecutionCount,
521    },
522}
523
524impl AgentToolConcurrency {
525    /// Constructs deterministic sequential execution.
526    #[must_use]
527    pub const fn sequential() -> Self {
528        Self::Sequential {}
529    }
530
531    /// Constructs bounded parallel execution for read-only calls.
532    #[must_use]
533    pub const fn parallel_read_only(max_concurrency: ExecutionCount) -> Self {
534        Self::ParallelReadOnly { max_concurrency }
535    }
536
537    /// Returns the maximum ordinary tool concurrency.
538    #[must_use]
539    pub const fn maximum(self) -> ExecutionCount {
540        match self {
541            Self::Sequential {} => ExecutionCount::new(1),
542            Self::ParallelReadOnly { max_concurrency } => max_concurrency,
543        }
544    }
545}
546
547/// Finite, deterministic controls for the prebuilt model/tool agent loop.
548#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
549#[serde(deny_unknown_fields)]
550pub struct AgentExecutionConfig {
551    structured_output: AgentStructuredOutputStrategy,
552    max_model_turns: ExecutionCount,
553    max_output_repair_turns: ExecutionCount,
554    max_tool_calls_per_turn: ExecutionCount,
555    tool_concurrency: AgentToolConcurrency,
556}
557
558impl AgentExecutionConfig {
559    /// Immutable hard model-turn ceiling for one agent run.
560    pub const HARD_MAX_MODEL_TURNS: ExecutionCount = ExecutionCount::new(1024);
561
562    /// Immutable hard output-repair ceiling for one agent run.
563    pub const HARD_MAX_OUTPUT_REPAIR_TURNS: ExecutionCount = ExecutionCount::new(64);
564
565    /// Immutable hard ordinary tool-call ceiling for one model response.
566    pub const HARD_MAX_TOOL_CALLS_PER_TURN: ExecutionCount = ExecutionCount::new(1024);
567
568    /// Constructs cross-field validated loop controls.
569    ///
570    /// # Errors
571    ///
572    /// Returns [`AgentExecutionConfigError`] for zero or excessive model
573    /// turns, excessive repairs/calls, impossible repair capacity, or invalid
574    /// read-only concurrency.
575    pub const fn new(
576        structured_output: AgentStructuredOutputStrategy,
577        max_model_turns: ExecutionCount,
578        max_output_repair_turns: ExecutionCount,
579        max_tool_calls_per_turn: ExecutionCount,
580        tool_concurrency: AgentToolConcurrency,
581    ) -> Result<Self, AgentExecutionConfigError> {
582        if max_model_turns.get() == 0 {
583            return Err(AgentExecutionConfigError::ZeroModelTurns);
584        }
585        if max_model_turns.get() > Self::HARD_MAX_MODEL_TURNS.get() {
586            return Err(AgentExecutionConfigError::ModelTurnsAboveHardMaximum {
587                maximum: Self::HARD_MAX_MODEL_TURNS,
588                actual: max_model_turns,
589            });
590        }
591        if max_output_repair_turns.get() > Self::HARD_MAX_OUTPUT_REPAIR_TURNS.get() {
592            return Err(AgentExecutionConfigError::OutputRepairsAboveHardMaximum {
593                maximum: Self::HARD_MAX_OUTPUT_REPAIR_TURNS,
594                actual: max_output_repair_turns,
595            });
596        }
597        if max_output_repair_turns.get() >= max_model_turns.get() {
598            return Err(AgentExecutionConfigError::OutputRepairsConsumeAllTurns {
599                repairs: max_output_repair_turns,
600                turns: max_model_turns,
601            });
602        }
603        if max_tool_calls_per_turn.get() > Self::HARD_MAX_TOOL_CALLS_PER_TURN.get() {
604            return Err(AgentExecutionConfigError::ToolCallsAboveHardMaximum {
605                maximum: Self::HARD_MAX_TOOL_CALLS_PER_TURN,
606                actual: max_tool_calls_per_turn,
607            });
608        }
609        if let AgentToolConcurrency::ParallelReadOnly { max_concurrency } = tool_concurrency {
610            if max_concurrency.get() < 2 {
611                return Err(AgentExecutionConfigError::ParallelConcurrencyBelowTwo {
612                    actual: max_concurrency,
613                });
614            }
615            if max_concurrency.get() > max_tool_calls_per_turn.get() {
616                return Err(AgentExecutionConfigError::ConcurrencyExceedsToolCalls {
617                    concurrency: max_concurrency,
618                    tool_calls: max_tool_calls_per_turn,
619                });
620            }
621        }
622        Ok(Self {
623            structured_output,
624            max_model_turns,
625            max_output_repair_turns,
626            max_tool_calls_per_turn,
627            tool_concurrency,
628        })
629    }
630
631    /// Returns the resolved structured-output mechanism.
632    #[must_use]
633    pub const fn structured_output(&self) -> AgentStructuredOutputStrategy {
634        self.structured_output
635    }
636
637    /// Returns the inclusive logical model-turn ceiling.
638    #[must_use]
639    pub const fn max_model_turns(&self) -> ExecutionCount {
640        self.max_model_turns
641    }
642
643    /// Returns the number of invalid final-output repair turns permitted.
644    #[must_use]
645    pub const fn max_output_repair_turns(&self) -> ExecutionCount {
646        self.max_output_repair_turns
647    }
648
649    /// Returns the ordinary tool-call ceiling for one model response.
650    #[must_use]
651    pub const fn max_tool_calls_per_turn(&self) -> ExecutionCount {
652        self.max_tool_calls_per_turn
653    }
654
655    /// Returns deterministic ordinary-tool scheduling behavior.
656    #[must_use]
657    pub const fn tool_concurrency(&self) -> AgentToolConcurrency {
658        self.tool_concurrency
659    }
660}
661
662#[derive(Deserialize)]
663#[serde(deny_unknown_fields)]
664struct AgentExecutionConfigWire {
665    structured_output: AgentStructuredOutputStrategy,
666    max_model_turns: ExecutionCount,
667    max_output_repair_turns: ExecutionCount,
668    max_tool_calls_per_turn: ExecutionCount,
669    tool_concurrency: AgentToolConcurrency,
670}
671
672impl<'de> Deserialize<'de> for AgentExecutionConfig {
673    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
674    where
675        D: Deserializer<'de>,
676    {
677        let wire = AgentExecutionConfigWire::deserialize(deserializer)?;
678        Self::new(
679            wire.structured_output,
680            wire.max_model_turns,
681            wire.max_output_repair_turns,
682            wire.max_tool_calls_per_turn,
683            wire.tool_concurrency,
684        )
685        .map_err(de::Error::custom)
686    }
687}
688
689/// Invalid prebuilt agent-loop controls.
690#[derive(Clone, Debug, Eq, Error, PartialEq)]
691#[non_exhaustive]
692pub enum AgentExecutionConfigError {
693    /// A loop allowed no model invocation.
694    #[error("agent max model turns must be greater than zero")]
695    ZeroModelTurns,
696    /// Model-turn capacity exceeded the immutable resource bound.
697    #[error("agent max model turns {actual} exceeds hard maximum {maximum}")]
698    ModelTurnsAboveHardMaximum {
699        /// Immutable ceiling.
700        maximum: ExecutionCount,
701        /// Rejected capacity.
702        actual: ExecutionCount,
703    },
704    /// Output-repair capacity exceeded the immutable resource bound.
705    #[error("agent max output repair turns {actual} exceeds hard maximum {maximum}")]
706    OutputRepairsAboveHardMaximum {
707        /// Immutable ceiling.
708        maximum: ExecutionCount,
709        /// Rejected capacity.
710        actual: ExecutionCount,
711    },
712    /// Repair turns left no capacity for an initial model result.
713    #[error("agent output repair turns {repairs} must be less than model turns {turns}")]
714    OutputRepairsConsumeAllTurns {
715        /// Rejected repair capacity.
716        repairs: ExecutionCount,
717        /// Total model-turn capacity.
718        turns: ExecutionCount,
719    },
720    /// Per-turn tool calls exceeded the immutable resource bound.
721    #[error("agent max tool calls per turn {actual} exceeds hard maximum {maximum}")]
722    ToolCallsAboveHardMaximum {
723        /// Immutable ceiling.
724        maximum: ExecutionCount,
725        /// Rejected capacity.
726        actual: ExecutionCount,
727    },
728    /// Parallel mode was selected with sequential capacity.
729    #[error("parallel read-only tool concurrency {actual} must be at least 2")]
730    ParallelConcurrencyBelowTwo {
731        /// Rejected concurrency.
732        actual: ExecutionCount,
733    },
734    /// Parallel concurrency exceeded possible calls in one response.
735    #[error(
736        "parallel read-only concurrency {concurrency} exceeds tool calls per turn {tool_calls}"
737    )]
738    ConcurrencyExceedsToolCalls {
739        /// Rejected concurrency.
740        concurrency: ExecutionCount,
741        /// Per-response call ceiling.
742        tool_calls: ExecutionCount,
743    },
744}
745
746/// Immutable, registry-resolved definition of one typed agent version.
747///
748/// This value is a definition snapshot, not a mutable runtime object. The
749/// durable runtime compiles it onto journaled graph semantics and records model
750/// attempts, tool invocations, approvals, and checkpoints independently.
751#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
752#[serde(deny_unknown_fields)]
753pub struct AgentDescriptor {
754    metadata: CapabilityMetadata,
755    input_schema: SchemaReference,
756    output_schema: SchemaReference,
757    model: ModelDescriptor,
758    instructions: AgentInstructions,
759    tools: AgentTools,
760    execution: AgentExecutionConfig,
761    budget_limits: BudgetLimits,
762}
763
764impl AgentDescriptor {
765    /// Framework-owned model-visible name used by tool-call structured output.
766    pub const FINAL_OUTPUT_TOOL_NAME: &'static str = "stateknot_final_output";
767
768    /// Constructs and validates one executable agent definition snapshot.
769    ///
770    /// Schema documents and provider compatibility profiles must additionally
771    /// be resolved and validated by the trusted local registry before this
772    /// descriptor becomes selectable.
773    ///
774    /// # Errors
775    ///
776    /// Returns [`AgentDescriptorError`] for invalid classification, retired
777    /// model binding, incoherent ordinary-tool controls, reserved-name
778    /// shadowing, or a model capability mismatch.
779    #[allow(clippy::too_many_arguments)]
780    pub fn new(
781        metadata: CapabilityMetadata,
782        input_schema: SchemaReference,
783        output_schema: SchemaReference,
784        model: ModelDescriptor,
785        instructions: AgentInstructions,
786        tools: AgentTools,
787        execution: AgentExecutionConfig,
788        budget_limits: BudgetLimits,
789    ) -> Result<Self, AgentDescriptorError> {
790        if metadata.kind() != CapabilityKind::Agent {
791            return Err(AgentDescriptorError::WrongCapabilityKind {
792                actual: metadata.kind(),
793            });
794        }
795        if model.metadata().lifecycle().state() == CapabilityLifecycleState::Retired {
796            return Err(AgentDescriptorError::RetiredModel {
797                identity: Box::new(model.metadata().identity().clone()),
798            });
799        }
800
801        let ordinary_calls = execution.max_tool_calls_per_turn();
802        match (tools.is_empty(), ordinary_calls.get() == 0) {
803            (true, false) => {
804                return Err(AgentDescriptorError::ToolCallsWithoutTools {
805                    actual: ordinary_calls,
806                });
807            }
808            (false, true) => return Err(AgentDescriptorError::ToolsWithoutToolCalls),
809            _ => {}
810        }
811
812        let synthetic_output =
813            execution.structured_output() == AgentStructuredOutputStrategy::ToolCall;
814        if synthetic_output && tools.contains_name(Self::FINAL_OUTPUT_TOOL_NAME) {
815            return Err(AgentDescriptorError::ReservedOutputToolName);
816        }
817
818        let required_definitions = tools.len() + usize::from(synthetic_output);
819        let hard_definition_maximum = ModelRequest::MAX_TOOL_DEFINITIONS;
820        if required_definitions as u64 > hard_definition_maximum.get() {
821            return Err(
822                AgentDescriptorError::ModelRequestToolDefinitionsAboveHardMaximum {
823                    maximum: hard_definition_maximum,
824                    actual: ExecutionCount::new(required_definitions as u64),
825                },
826            );
827        }
828        if required_definitions > 0 {
829            let capabilities = model.capabilities().tools();
830            if !capabilities.supports_tool_calling() {
831                return Err(AgentDescriptorError::ModelToolCallingUnsupported);
832            }
833            let required = ExecutionCount::new(required_definitions as u64);
834            if capabilities.max_definitions() < required {
835                return Err(AgentDescriptorError::ModelToolDefinitionsInsufficient {
836                    required,
837                    available: capabilities.max_definitions(),
838                });
839            }
840            let required_calls = if synthetic_output {
841                ordinary_calls.max(ExecutionCount::new(1))
842            } else {
843                ordinary_calls
844            };
845            if capabilities.max_calls_per_response() < required_calls {
846                return Err(AgentDescriptorError::ModelToolCallsInsufficient {
847                    required: required_calls,
848                    available: capabilities.max_calls_per_response(),
849                });
850            }
851        }
852
853        if execution.structured_output() == AgentStructuredOutputStrategy::ModelNative {
854            let available = model.capabilities().structured_output().level();
855            if available < ModelStructuredOutputLevel::JsonSchema {
856                return Err(
857                    AgentDescriptorError::ModelNativeStructuredOutputUnsupported { available },
858                );
859            }
860        }
861        if let Some(deadline) = budget_limits.deadline() {
862            return Err(AgentDescriptorError::AbsoluteDeadlineIsNotReusable { deadline });
863        }
864
865        Ok(Self {
866            metadata,
867            input_schema,
868            output_schema,
869            model,
870            instructions,
871            tools,
872            execution,
873            budget_limits,
874        })
875    }
876
877    /// Returns common identity, discovery, lifecycle, scope, and extension data.
878    #[must_use]
879    pub const fn metadata(&self) -> &CapabilityMetadata {
880        &self.metadata
881    }
882
883    /// Returns the immutable typed input schema identity.
884    #[must_use]
885    pub const fn input_schema(&self) -> &SchemaReference {
886        &self.input_schema
887    }
888
889    /// Returns the immutable typed final-output schema identity.
890    #[must_use]
891    pub const fn output_schema(&self) -> &SchemaReference {
892        &self.output_schema
893    }
894
895    /// Returns the exact resolved model binding snapshot.
896    #[must_use]
897    pub const fn model(&self) -> &ModelDescriptor {
898        &self.model
899    }
900
901    /// Returns ordered trusted instructions.
902    #[must_use]
903    pub const fn instructions(&self) -> &AgentInstructions {
904        &self.instructions
905    }
906
907    /// Returns canonically ordered ordinary tools.
908    #[must_use]
909    pub const fn tools(&self) -> &AgentTools {
910        &self.tools
911    }
912
913    /// Returns finite deterministic loop controls.
914    #[must_use]
915    pub const fn execution(&self) -> &AgentExecutionConfig {
916        &self.execution
917    }
918
919    /// Returns the optional agent-level run-budget layer.
920    #[must_use]
921    pub const fn budget_limits(&self) -> &BudgetLimits {
922        &self.budget_limits
923    }
924}
925
926impl fmt::Debug for AgentDescriptor {
927    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
928        formatter
929            .debug_struct("AgentDescriptor")
930            .field("metadata", &self.metadata)
931            .field("input_schema", &self.input_schema)
932            .field("output_schema", &self.output_schema)
933            .field("model", self.model.metadata().identity())
934            .field("instructions", &self.instructions)
935            .field("tools", &self.tools)
936            .field("execution", &self.execution)
937            .field("has_budget_limits", &!self.budget_limits.is_empty())
938            .finish_non_exhaustive()
939    }
940}
941
942#[derive(Deserialize)]
943#[serde(deny_unknown_fields)]
944struct AgentDescriptorWire {
945    metadata: CapabilityMetadata,
946    input_schema: SchemaReference,
947    output_schema: SchemaReference,
948    model: ModelDescriptor,
949    instructions: AgentInstructions,
950    tools: AgentTools,
951    execution: AgentExecutionConfig,
952    budget_limits: BudgetLimits,
953}
954
955impl<'de> Deserialize<'de> for AgentDescriptor {
956    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
957    where
958        D: Deserializer<'de>,
959    {
960        let wire = AgentDescriptorWire::deserialize(deserializer)?;
961        Self::new(
962            wire.metadata,
963            wire.input_schema,
964            wire.output_schema,
965            wire.model,
966            wire.instructions,
967            wire.tools,
968            wire.execution,
969            wire.budget_limits,
970        )
971        .map_err(de::Error::custom)
972    }
973}
974
975/// Invalid cross-component agent definition snapshot.
976#[derive(Clone, Debug, Eq, Error, PartialEq)]
977#[non_exhaustive]
978pub enum AgentDescriptorError {
979    /// Common metadata classified the capability as something other than an agent.
980    #[error("agent descriptor requires kind=agent, received {actual:?}")]
981    WrongCapabilityKind {
982        /// Conflicting capability kind.
983        actual: CapabilityKind,
984    },
985    /// The resolved model binding is unavailable for a new definition.
986    #[error("agent model binding {identity:?} is retired")]
987    RetiredModel {
988        /// Retired owner-qualified model identity.
989        identity: Box<CapabilityIdentity>,
990    },
991    /// Ordinary call capacity was declared without an ordinary tool.
992    #[error("agent has no ordinary tools but allows {actual} tool calls per turn")]
993    ToolCallsWithoutTools {
994        /// Rejected nonzero capacity.
995        actual: ExecutionCount,
996    },
997    /// Ordinary tools were present but the loop could never invoke one.
998    #[error("agent ordinary tools require a positive tool-call ceiling")]
999    ToolsWithoutToolCalls,
1000    /// A user tool shadowed the framework-owned final-output marker.
1001    #[error("agent tool name stateknot_final_output is reserved for structured output")]
1002    ReservedOutputToolName,
1003    /// The pinned model cannot accept any tool definition.
1004    #[error("agent definition requires model tool calling, but the model does not support it")]
1005    ModelToolCallingUnsupported,
1006    /// The pinned model cannot accept all ordinary and synthetic definitions.
1007    #[error("agent requires {required} tool definitions, model accepts {available}")]
1008    ModelToolDefinitionsInsufficient {
1009        /// Required ordinary plus synthetic definition count.
1010        required: ExecutionCount,
1011        /// Pinned model capacity.
1012        available: ExecutionCount,
1013    },
1014    /// Ordinary plus synthetic definitions exceeded the core request boundary.
1015    #[error("agent requires {actual} tool definitions; core request maximum is {maximum}")]
1016    ModelRequestToolDefinitionsAboveHardMaximum {
1017        /// Immutable core request ceiling.
1018        maximum: ExecutionCount,
1019        /// Rejected ordinary plus synthetic definition count.
1020        actual: ExecutionCount,
1021    },
1022    /// The pinned model cannot emit the configured per-response calls.
1023    #[error("agent requires {required} tool calls per response, model allows {available}")]
1024    ModelToolCallsInsufficient {
1025        /// Required model response call capacity.
1026        required: ExecutionCount,
1027        /// Pinned model capacity.
1028        available: ExecutionCount,
1029    },
1030    /// Native strategy was selected for a weaker model binding.
1031    #[error("model-native agent output requires JSON Schema support, model provides {available:?}")]
1032    ModelNativeStructuredOutputUnsupported {
1033        /// Pinned model capability level.
1034        available: ModelStructuredOutputLevel,
1035    },
1036    /// A reusable definition attempted to embed a one-run absolute deadline.
1037    #[error("agent budget cannot embed absolute deadline {deadline}")]
1038    AbsoluteDeadlineIsNotReusable {
1039        /// Rejected absolute instant.
1040        deadline: crate::Timestamp,
1041    },
1042}
1043
1044#[cfg(test)]
1045mod tests {
1046    use super::*;
1047    use proptest::prelude::*;
1048    use serde_json::{from_value, json, to_value};
1049
1050    use crate::{
1051        CapabilityDescription, CapabilityLifecycle, CapabilityReference, ContentMetadata,
1052        ContentSource, ContentTrust, Digest, DurationMillis, Extensions, InstructionName,
1053        InstructionProvenance, IssuerId, ModelCapabilities, ModelModalities, ModelModality,
1054        ModelStructuredOutputCapabilities, ModelTokenLimits, ModelToolCapabilities,
1055        ModelToolChoice, ModelToolChoices, PrincipalIdentity, RedactionState, SchemaId, ScopeSet,
1056        SecurityLabel, SubjectId, TextContent, Timestamp, TokenCount, ToolCancellationSupport,
1057        ToolExecutionLimits, ToolExecutionSemantics, ToolIdempotency, ToolInvocationCapabilities,
1058        ToolResourceRequirements, ToolRisk, Version,
1059    };
1060
1061    fn principal(subject: &str) -> PrincipalIdentity {
1062        PrincipalIdentity::new(
1063            "https://issuer.example.com/tenant"
1064                .parse::<IssuerId>()
1065                .unwrap(),
1066            subject.parse::<SubjectId>().unwrap(),
1067        )
1068    }
1069
1070    fn lifecycle(retired: bool) -> CapabilityLifecycle {
1071        if retired {
1072            CapabilityLifecycle::retired(
1073                "2026-08-29T00:00:00.000000Z".parse::<Timestamp>().unwrap(),
1074                CapabilityDescription::new("Retired test binding").unwrap(),
1075                None,
1076            )
1077        } else {
1078            CapabilityLifecycle::active()
1079        }
1080    }
1081
1082    fn metadata(
1083        kind: CapabilityKind,
1084        name: &str,
1085        owner: &str,
1086        retired: bool,
1087        description: &str,
1088    ) -> CapabilityMetadata {
1089        CapabilityMetadata::new(
1090            CapabilityIdentity::new(
1091                principal(owner),
1092                CapabilityReference::new(
1093                    name.parse::<CapabilityName>().unwrap(),
1094                    Version::new(1, 0, 0),
1095                ),
1096            ),
1097            kind,
1098            None,
1099            CapabilityDescription::new(description).unwrap(),
1100            lifecycle(retired),
1101            ScopeSet::empty(),
1102            Extensions::default(),
1103        )
1104        .unwrap()
1105    }
1106
1107    fn schema(name: &str) -> SchemaReference {
1108        SchemaReference::new(
1109            format!("https://schemas.example.com/{name}/1.0.0")
1110                .parse::<SchemaId>()
1111                .unwrap(),
1112            Version::new(1, 0, 0),
1113            Digest::sha256(name),
1114        )
1115    }
1116
1117    fn instruction(name: &str, content: &str) -> Instruction {
1118        let metadata = ContentMetadata::new(
1119            ContentSource::Application,
1120            ContentTrust::ApplicationControlled,
1121            "internal".parse::<SecurityLabel>().unwrap(),
1122            RedactionState::NotApplied,
1123        );
1124        Instruction::new(
1125            crate::InstructionIdentity::new(
1126                name.parse::<InstructionName>().unwrap(),
1127                Version::new(1, 0, 0),
1128            ),
1129            TextContent::new(content, None, metadata).unwrap().into(),
1130            InstructionProvenance::new(principal("instruction-owner")),
1131        )
1132        .unwrap()
1133    }
1134
1135    fn model(
1136        max_definitions: u64,
1137        max_calls: u64,
1138        structured_output: ModelStructuredOutputLevel,
1139        retired: bool,
1140    ) -> ModelDescriptor {
1141        let tool_capabilities = if max_definitions == 0 {
1142            ModelToolCapabilities::unsupported()
1143        } else {
1144            ModelToolCapabilities::new(
1145                Some(schema("model-tool-profile")),
1146                ExecutionCount::new(max_definitions),
1147                ExecutionCount::new(max_calls),
1148                ModelToolChoices::try_new([ModelToolChoice::Auto]).unwrap(),
1149                true,
1150            )
1151            .unwrap()
1152        };
1153        let structured_output = match structured_output {
1154            ModelStructuredOutputLevel::Unsupported => {
1155                ModelStructuredOutputCapabilities::unsupported()
1156            }
1157            ModelStructuredOutputLevel::Json => ModelStructuredOutputCapabilities::json(),
1158            ModelStructuredOutputLevel::JsonSchema => {
1159                ModelStructuredOutputCapabilities::json_schema(schema("model-output-profile"))
1160            }
1161        };
1162        ModelDescriptor::new(
1163            metadata(
1164                CapabilityKind::Model,
1165                "models.primary",
1166                "model-owner",
1167                retired,
1168                "Pinned model binding",
1169            ),
1170            ModelCapabilities::new(
1171                ModelModalities::try_new([ModelModality::Text]).unwrap(),
1172                ModelModalities::try_new([ModelModality::Text]).unwrap(),
1173                true,
1174                tool_capabilities,
1175                structured_output,
1176                false,
1177                ModelTokenLimits::new(
1178                    Some(TokenCount::new(128_000)),
1179                    Some(TokenCount::new(120_000)),
1180                    Some(TokenCount::new(16_384)),
1181                )
1182                .unwrap(),
1183            )
1184            .unwrap(),
1185        )
1186        .unwrap()
1187    }
1188
1189    fn tool(name: &str, retired: bool) -> ToolDescriptor {
1190        ToolDescriptor::new(
1191            metadata(
1192                CapabilityKind::Tool,
1193                name,
1194                "tool-owner",
1195                retired,
1196                "Read-only test tool",
1197            ),
1198            schema(&format!("{name}-input")),
1199            schema(&format!("{name}-output")),
1200            ToolExecutionSemantics::new(
1201                ToolRisk::ReadOnly,
1202                ToolIdempotency::NotApplicable,
1203                false,
1204                false,
1205            )
1206            .unwrap(),
1207            ToolResourceRequirements::none(),
1208            ToolInvocationCapabilities::new(
1209                ToolCancellationSupport::Cooperative,
1210                ExecutionCount::new(32),
1211            ),
1212            ToolExecutionLimits::new(
1213                DurationMillis::new(30_000).unwrap(),
1214                ExecutionCount::new(16),
1215                ByteCount::new(64 * 1024),
1216                ByteCount::new(256 * 1024),
1217                ExecutionCount::new(4),
1218                ByteCount::new(25 * 1024 * 1024),
1219            )
1220            .unwrap(),
1221        )
1222        .unwrap()
1223    }
1224
1225    fn execution(strategy: AgentStructuredOutputStrategy, tool_calls: u64) -> AgentExecutionConfig {
1226        AgentExecutionConfig::new(
1227            strategy,
1228            ExecutionCount::new(12),
1229            ExecutionCount::new(2),
1230            ExecutionCount::new(tool_calls),
1231            AgentToolConcurrency::sequential(),
1232        )
1233        .unwrap()
1234    }
1235
1236    fn descriptor(
1237        model: ModelDescriptor,
1238        tools: AgentTools,
1239        execution: AgentExecutionConfig,
1240        secret: &str,
1241    ) -> Result<AgentDescriptor, AgentDescriptorError> {
1242        AgentDescriptor::new(
1243            metadata(
1244                CapabilityKind::Agent,
1245                "agents.incident",
1246                "agent-owner",
1247                false,
1248                secret,
1249            ),
1250            schema("incident-request"),
1251            schema("incident-report"),
1252            model,
1253            AgentInstructions::try_new([instruction("incident.base", secret)]).unwrap(),
1254            tools,
1255            execution,
1256            BudgetLimits::empty()
1257                .with_model_turns(ExecutionCount::new(12))
1258                .with_tool_calls(ExecutionCount::new(24))
1259                .with_write_calls(ExecutionCount::new(1)),
1260        )
1261    }
1262
1263    #[test]
1264    fn execution_config_is_finite_closed_and_revalidated() {
1265        let config = AgentExecutionConfig::new(
1266            AgentStructuredOutputStrategy::ToolCall,
1267            ExecutionCount::new(10),
1268            ExecutionCount::new(2),
1269            ExecutionCount::new(4),
1270            AgentToolConcurrency::parallel_read_only(ExecutionCount::new(3)),
1271        )
1272        .unwrap();
1273        assert_eq!(config.max_model_turns(), ExecutionCount::new(10));
1274        assert_eq!(config.max_output_repair_turns(), ExecutionCount::new(2));
1275        assert_eq!(config.max_tool_calls_per_turn(), ExecutionCount::new(4));
1276        assert_eq!(config.tool_concurrency().maximum(), ExecutionCount::new(3));
1277        assert_eq!(
1278            from_value::<AgentExecutionConfig>(to_value(&config).unwrap()).unwrap(),
1279            config
1280        );
1281
1282        assert_eq!(
1283            AgentExecutionConfig::new(
1284                AgentStructuredOutputStrategy::ModelNative,
1285                ExecutionCount::ZERO,
1286                ExecutionCount::ZERO,
1287                ExecutionCount::ZERO,
1288                AgentToolConcurrency::sequential(),
1289            ),
1290            Err(AgentExecutionConfigError::ZeroModelTurns)
1291        );
1292        assert!(matches!(
1293            AgentExecutionConfig::new(
1294                AgentStructuredOutputStrategy::ModelNative,
1295                ExecutionCount::new(1025),
1296                ExecutionCount::ZERO,
1297                ExecutionCount::ZERO,
1298                AgentToolConcurrency::sequential(),
1299            ),
1300            Err(AgentExecutionConfigError::ModelTurnsAboveHardMaximum { .. })
1301        ));
1302        assert!(matches!(
1303            AgentExecutionConfig::new(
1304                AgentStructuredOutputStrategy::ModelNative,
1305                ExecutionCount::new(3),
1306                ExecutionCount::new(3),
1307                ExecutionCount::ZERO,
1308                AgentToolConcurrency::sequential(),
1309            ),
1310            Err(AgentExecutionConfigError::OutputRepairsConsumeAllTurns { .. })
1311        ));
1312        assert!(matches!(
1313            AgentExecutionConfig::new(
1314                AgentStructuredOutputStrategy::ToolCall,
1315                ExecutionCount::new(10),
1316                ExecutionCount::ZERO,
1317                ExecutionCount::new(4),
1318                AgentToolConcurrency::parallel_read_only(ExecutionCount::new(1)),
1319            ),
1320            Err(AgentExecutionConfigError::ParallelConcurrencyBelowTwo { .. })
1321        ));
1322        assert!(matches!(
1323            AgentExecutionConfig::new(
1324                AgentStructuredOutputStrategy::ToolCall,
1325                ExecutionCount::new(10),
1326                ExecutionCount::ZERO,
1327                ExecutionCount::new(2),
1328                AgentToolConcurrency::parallel_read_only(ExecutionCount::new(3)),
1329            ),
1330            Err(AgentExecutionConfigError::ConcurrencyExceedsToolCalls { .. })
1331        ));
1332
1333        let mut unknown = to_value(config).unwrap();
1334        unknown["unlimited"] = json!(true);
1335        assert!(from_value::<AgentExecutionConfig>(unknown).is_err());
1336        assert!(from_value::<AgentStructuredOutputStrategy>(json!("auto")).is_err());
1337        assert!(from_value::<AgentToolConcurrency>(json!({ "mode": "parallel" })).is_err());
1338    }
1339
1340    #[test]
1341    fn instructions_are_nonempty_ordered_unique_bounded_and_redacted() {
1342        assert_eq!(
1343            AgentInstructions::try_new([]),
1344            Err(AgentInstructionsError::Empty)
1345        );
1346        let first = instruction("base.first", "secret-first");
1347        let second = instruction("base.second", "secret-second");
1348        let instructions = AgentInstructions::try_new([first.clone(), second.clone()]).unwrap();
1349        assert_eq!(instructions.len(), 2);
1350        assert!(!instructions.is_empty());
1351        assert_eq!(instructions.as_slice()[0].identity(), first.identity());
1352        assert_eq!(instructions.as_slice()[1].identity(), second.identity());
1353        assert_eq!(
1354            AgentInstructions::try_new([first.clone(), first]),
1355            Err(AgentInstructionsError::Duplicate {
1356                identity: instruction("base.first", "replacement").identity().clone(),
1357            })
1358        );
1359        let encoded = to_value(&instructions).unwrap();
1360        assert_eq!(
1361            from_value::<AgentInstructions>(encoded).unwrap(),
1362            instructions
1363        );
1364        let debug = format!("{instructions:?}");
1365        assert!(!debug.contains("secret-first"));
1366        assert!(!debug.contains("secret-second"));
1367
1368        let too_many = (0..=AgentInstructions::MAX_LEN)
1369            .map(|index| instruction(&format!("instruction.{index}"), "bounded"));
1370        assert!(matches!(
1371            AgentInstructions::try_new(too_many),
1372            Err(AgentInstructionsError::TooMany { .. })
1373        ));
1374
1375        let schema = to_value(schemars::schema_for!(AgentInstructions)).unwrap();
1376        assert_eq!(schema["minItems"], 1);
1377        assert_eq!(schema["maxItems"], AgentInstructions::MAX_LEN);
1378    }
1379
1380    #[test]
1381    fn tools_are_canonical_unique_bounded_and_active() {
1382        let tools =
1383            AgentTools::try_new([tool("tools.zeta", false), tool("tools.alpha", false)]).unwrap();
1384        assert_eq!(tools.len(), 2);
1385        assert_eq!(
1386            tools
1387                .iter()
1388                .map(|tool| tool.metadata().identity().capability().name().as_str())
1389                .collect::<Vec<_>>(),
1390            ["tools.alpha", "tools.zeta"]
1391        );
1392        assert!(tools.get(&"tools.alpha".parse().unwrap()).is_some());
1393        assert_eq!(
1394            from_value::<AgentTools>(to_value(&tools).unwrap()).unwrap(),
1395            tools
1396        );
1397        assert!(matches!(
1398            AgentTools::try_new([tool("tools.same", false), tool("tools.same", false)]),
1399            Err(AgentToolsError::DuplicateName { .. })
1400        ));
1401        assert!(matches!(
1402            AgentTools::try_new([tool("tools.retired", true)]),
1403            Err(AgentToolsError::Retired { .. })
1404        ));
1405
1406        let too_many =
1407            (0..=AgentTools::MAX_LEN).map(|index| tool(&format!("tools.t{index}"), false));
1408        assert!(matches!(
1409            AgentTools::try_new(too_many),
1410            Err(AgentToolsError::TooMany { .. })
1411        ));
1412
1413        let schema = to_value(schemars::schema_for!(AgentTools)).unwrap();
1414        assert_eq!(schema["maxItems"], AgentTools::MAX_LEN);
1415    }
1416
1417    #[test]
1418    fn descriptor_binds_every_dependency_and_redacts_instruction_content() {
1419        let descriptor = descriptor(
1420            model(8, 4, ModelStructuredOutputLevel::JsonSchema, false),
1421            AgentTools::try_new([tool("tools.lookup", false)]).unwrap(),
1422            execution(AgentStructuredOutputStrategy::ModelNative, 4),
1423            "never-log-this-instruction",
1424        )
1425        .unwrap();
1426        assert_eq!(descriptor.metadata().kind(), CapabilityKind::Agent);
1427        assert_eq!(descriptor.input_schema(), &schema("incident-request"));
1428        assert_eq!(descriptor.output_schema(), &schema("incident-report"));
1429        assert_eq!(descriptor.instructions().len(), 1);
1430        assert_eq!(descriptor.tools().len(), 1);
1431        assert_eq!(
1432            descriptor.execution().structured_output(),
1433            AgentStructuredOutputStrategy::ModelNative
1434        );
1435        assert_eq!(
1436            descriptor.budget_limits().tool_calls(),
1437            Some(ExecutionCount::new(24))
1438        );
1439
1440        let encoded = to_value(&descriptor).unwrap();
1441        assert_eq!(from_value::<AgentDescriptor>(encoded).unwrap(), descriptor);
1442        let debug = format!("{descriptor:?}");
1443        assert!(!debug.contains("never-log-this-instruction"));
1444        assert!(!debug.contains("instruction-owner"));
1445    }
1446
1447    #[test]
1448    fn descriptor_rejects_incoherent_tool_and_output_capabilities() {
1449        let native_model = || model(8, 4, ModelStructuredOutputLevel::JsonSchema, false);
1450        let no_tools = AgentTools::empty();
1451        assert!(matches!(
1452            descriptor(
1453                native_model(),
1454                no_tools.clone(),
1455                execution(AgentStructuredOutputStrategy::ModelNative, 1),
1456                "agent"
1457            ),
1458            Err(AgentDescriptorError::ToolCallsWithoutTools { .. })
1459        ));
1460        assert_eq!(
1461            descriptor(
1462                native_model(),
1463                AgentTools::try_new([tool("tools.lookup", false)]).unwrap(),
1464                execution(AgentStructuredOutputStrategy::ModelNative, 0),
1465                "agent"
1466            ),
1467            Err(AgentDescriptorError::ToolsWithoutToolCalls)
1468        );
1469        assert_eq!(
1470            descriptor(
1471                model(0, 0, ModelStructuredOutputLevel::JsonSchema, false),
1472                AgentTools::try_new([tool("tools.lookup", false)]).unwrap(),
1473                execution(AgentStructuredOutputStrategy::ModelNative, 1),
1474                "agent"
1475            ),
1476            Err(AgentDescriptorError::ModelToolCallingUnsupported)
1477        );
1478        assert!(matches!(
1479            descriptor(
1480                model(1, 4, ModelStructuredOutputLevel::Unsupported, false),
1481                AgentTools::try_new([tool("tools.lookup", false)]).unwrap(),
1482                execution(AgentStructuredOutputStrategy::ToolCall, 1),
1483                "agent"
1484            ),
1485            Err(AgentDescriptorError::ModelToolDefinitionsInsufficient { .. })
1486        ));
1487        assert!(matches!(
1488            descriptor(
1489                model(8, 1, ModelStructuredOutputLevel::JsonSchema, false),
1490                AgentTools::try_new([tool("tools.lookup", false)]).unwrap(),
1491                execution(AgentStructuredOutputStrategy::ModelNative, 2),
1492                "agent"
1493            ),
1494            Err(AgentDescriptorError::ModelToolCallsInsufficient { .. })
1495        ));
1496        assert!(matches!(
1497            descriptor(
1498                model(8, 4, ModelStructuredOutputLevel::Json, false),
1499                AgentTools::empty(),
1500                execution(AgentStructuredOutputStrategy::ModelNative, 0),
1501                "agent"
1502            ),
1503            Err(
1504                AgentDescriptorError::ModelNativeStructuredOutputUnsupported {
1505                    available: ModelStructuredOutputLevel::Json
1506                }
1507            )
1508        ));
1509
1510        descriptor(
1511            model(2, 1, ModelStructuredOutputLevel::Unsupported, false),
1512            AgentTools::try_new([tool("tools.lookup", false)]).unwrap(),
1513            execution(AgentStructuredOutputStrategy::ToolCall, 1),
1514            "tool-output-agent",
1515        )
1516        .unwrap();
1517        assert_eq!(
1518            descriptor(
1519                model(1, 1, ModelStructuredOutputLevel::Unsupported, false),
1520                AgentTools::try_new([tool(AgentDescriptor::FINAL_OUTPUT_TOOL_NAME, false)])
1521                    .unwrap(),
1522                execution(AgentStructuredOutputStrategy::ToolCall, 1),
1523                "agent"
1524            ),
1525            Err(AgentDescriptorError::ReservedOutputToolName)
1526        );
1527    }
1528
1529    #[test]
1530    fn descriptor_rejects_wrong_kind_and_retired_model() {
1531        let instructions = AgentInstructions::try_new([instruction("base", "trusted")]).unwrap();
1532        let config = execution(AgentStructuredOutputStrategy::ModelNative, 0);
1533        assert!(matches!(
1534            AgentDescriptor::new(
1535                metadata(
1536                    CapabilityKind::Workflow,
1537                    "agents.invalid",
1538                    "agent-owner",
1539                    false,
1540                    "Wrong kind"
1541                ),
1542                schema("input"),
1543                schema("output"),
1544                model(0, 0, ModelStructuredOutputLevel::JsonSchema, false),
1545                instructions.clone(),
1546                AgentTools::empty(),
1547                config.clone(),
1548                BudgetLimits::empty(),
1549            ),
1550            Err(AgentDescriptorError::WrongCapabilityKind {
1551                actual: CapabilityKind::Workflow
1552            })
1553        ));
1554        assert!(matches!(
1555            AgentDescriptor::new(
1556                metadata(
1557                    CapabilityKind::Agent,
1558                    "agents.invalid",
1559                    "agent-owner",
1560                    false,
1561                    "Retired model"
1562                ),
1563                schema("input"),
1564                schema("output"),
1565                model(0, 0, ModelStructuredOutputLevel::JsonSchema, true),
1566                instructions,
1567                AgentTools::empty(),
1568                config,
1569                BudgetLimits::empty(),
1570            ),
1571            Err(AgentDescriptorError::RetiredModel { .. })
1572        ));
1573    }
1574
1575    #[test]
1576    fn descriptor_rejects_nonreusable_deadlines_and_request_definition_overflow() {
1577        let instructions =
1578            || AgentInstructions::try_new([instruction("base", "trusted definition")]).unwrap();
1579        let deadline = "2027-01-01T00:00:00.000000Z".parse::<Timestamp>().unwrap();
1580        assert_eq!(
1581            AgentDescriptor::new(
1582                metadata(
1583                    CapabilityKind::Agent,
1584                    "agents.deadline",
1585                    "agent-owner",
1586                    false,
1587                    "Absolute deadline"
1588                ),
1589                schema("input"),
1590                schema("output"),
1591                model(0, 0, ModelStructuredOutputLevel::JsonSchema, false),
1592                instructions(),
1593                AgentTools::empty(),
1594                execution(AgentStructuredOutputStrategy::ModelNative, 0),
1595                BudgetLimits::empty().with_deadline(deadline),
1596            ),
1597            Err(AgentDescriptorError::AbsoluteDeadlineIsNotReusable { deadline })
1598        );
1599
1600        let tools = AgentTools::try_new(
1601            (0..AgentTools::MAX_LEN).map(|index| tool(&format!("tools.t{index}"), false)),
1602        )
1603        .unwrap();
1604        assert!(matches!(
1605            AgentDescriptor::new(
1606                metadata(
1607                    CapabilityKind::Agent,
1608                    "agents.capacity",
1609                    "agent-owner",
1610                    false,
1611                    "Definition capacity"
1612                ),
1613                schema("input"),
1614                schema("output"),
1615                model(129, 1, ModelStructuredOutputLevel::Unsupported, false),
1616                instructions(),
1617                tools,
1618                execution(AgentStructuredOutputStrategy::ToolCall, 1),
1619                BudgetLimits::empty(),
1620            ),
1621            Err(AgentDescriptorError::ModelRequestToolDefinitionsAboveHardMaximum {
1622                maximum: ModelRequest::MAX_TOOL_DEFINITIONS,
1623                actual
1624            }) if actual == ExecutionCount::new(129)
1625        ));
1626    }
1627
1628    #[test]
1629    fn agent_schemas_close_objects_and_publish_collection_bounds() {
1630        let descriptor_schema = to_value(schemars::schema_for!(AgentDescriptor)).unwrap();
1631        assert_eq!(descriptor_schema["additionalProperties"], false);
1632        let execution_schema = to_value(schemars::schema_for!(AgentExecutionConfig)).unwrap();
1633        assert_eq!(execution_schema["additionalProperties"], false);
1634
1635        let descriptor = descriptor(
1636            model(0, 0, ModelStructuredOutputLevel::JsonSchema, false),
1637            AgentTools::empty(),
1638            execution(AgentStructuredOutputStrategy::ModelNative, 0),
1639            "closed-wire",
1640        )
1641        .unwrap();
1642        let mut wire = to_value(descriptor).unwrap();
1643        wire["dynamic_tools"] = json!(true);
1644        assert!(from_value::<AgentDescriptor>(wire).is_err());
1645    }
1646
1647    proptest! {
1648        #[test]
1649        fn valid_sequential_execution_configs_round_trip(
1650            turns in 1_u64..=1024,
1651            repairs in 0_u64..=64,
1652            tool_calls in 0_u64..=1024,
1653            tool_output in any::<bool>(),
1654        ) {
1655            prop_assume!(repairs < turns);
1656            let strategy = if tool_output {
1657                AgentStructuredOutputStrategy::ToolCall
1658            } else {
1659                AgentStructuredOutputStrategy::ModelNative
1660            };
1661            let config = AgentExecutionConfig::new(
1662                strategy,
1663                ExecutionCount::new(turns),
1664                ExecutionCount::new(repairs),
1665                ExecutionCount::new(tool_calls),
1666                AgentToolConcurrency::sequential(),
1667            ).unwrap();
1668            let wire = to_value(&config).unwrap();
1669            prop_assert_eq!(from_value::<AgentExecutionConfig>(wire).unwrap(), config);
1670        }
1671    }
1672}