Skip to main content

tirea_contract/
lib.rs

1//! Shared agent contracts for conversation state, runtime protocol, extension SPI, and storage.
2#![allow(missing_docs)]
3
4/// Builder methods for pure-data fields shared by both BaseAgent and AgentDefinition.
5///
6/// Covers: id, model, system_prompt, max_rounds, chat_options, fallback_models,
7/// llm_retry_policy.
8#[macro_export]
9macro_rules! impl_shared_agent_builder_methods {
10    () => {
11        /// Create a new instance with the given model id.
12        pub fn new(model: impl Into<String>) -> Self {
13            Self {
14                model: model.into(),
15                ..Default::default()
16            }
17        }
18
19        /// Create a new instance with explicit id and model.
20        pub fn with_id(id: impl Into<String>, model: impl Into<String>) -> Self {
21            Self {
22                id: id.into(),
23                model: model.into(),
24                ..Default::default()
25            }
26        }
27
28        /// Set system prompt.
29        #[must_use]
30        pub fn with_system_prompt(mut self, prompt: impl Into<String>) -> Self {
31            self.system_prompt = prompt.into();
32            self
33        }
34
35        /// Set max rounds.
36        #[must_use]
37        pub fn with_max_rounds(mut self, max_rounds: usize) -> Self {
38            self.max_rounds = max_rounds;
39            self
40        }
41
42        /// Set chat options.
43        #[must_use]
44        pub fn with_chat_options(mut self, options: ChatOptions) -> Self {
45            self.chat_options = Some(options);
46            self
47        }
48
49        /// Set fallback model ids to try after the primary model.
50        #[must_use]
51        pub fn with_fallback_models(mut self, models: Vec<String>) -> Self {
52            self.fallback_models = models;
53            self
54        }
55
56        /// Add a single fallback model id.
57        #[must_use]
58        pub fn with_fallback_model(mut self, model: impl Into<String>) -> Self {
59            self.fallback_models.push(model.into());
60            self
61        }
62
63        /// Set LLM retry policy.
64        #[must_use]
65        pub fn with_llm_retry_policy(mut self, policy: LlmRetryPolicy) -> Self {
66            self.llm_retry_policy = policy;
67            self
68        }
69    };
70}
71
72/// Declares the [`StateSpec`] types managed by a plugin behavior.
73///
74/// Generates `register_lattice_paths` and `register_state_scopes`
75/// implementations for [`AgentBehavior`], so plugin authors only need to
76/// list their state types once instead of implementing two methods.
77///
78/// # Example
79///
80/// ```ignore
81/// #[async_trait]
82/// impl AgentBehavior for MyPlugin {
83///     fn id(&self) -> &str { "my_plugin" }
84///     tirea_contract::declare_plugin_states!(MyState, MyOtherState);
85/// }
86/// ```
87#[macro_export]
88macro_rules! declare_plugin_states {
89    ($($state:ty),+ $(,)?) => {
90        fn register_lattice_paths(&self, registry: &mut ::tirea_state::LatticeRegistry) {
91            $(<$state as ::tirea_state::State>::register_lattice(registry);)+
92        }
93
94        fn register_state_scopes(
95            &self,
96            registry: &mut $crate::runtime::state::StateScopeRegistry,
97        ) {
98            $(registry.register::<$state>(<$state as ::tirea_state::StateSpec>::SCOPE);)+
99        }
100
101        fn register_state_action_deserializers(
102            &self,
103            registry: &mut $crate::runtime::state::StateActionDeserializerRegistry,
104        ) {
105            $(registry.register::<$state>();)+
106        }
107    };
108}
109
110#[cfg(any(test, feature = "test-support"))]
111pub mod testing;
112
113pub mod io;
114pub mod runtime;
115pub mod scope;
116pub mod storage;
117pub mod thread;
118pub mod transport;
119
120/// Per-run scope and execution policy.
121pub type RunPolicy = runtime::RunPolicy;
122
123// thread
124pub use thread::{
125    gen_message_id, CheckpointReason, Message, MessageMetadata, Role, RunMeta, Thread,
126    ThreadChangeSet, ThreadMetadata, ToolCall, Version, Visibility,
127};
128
129// io
130pub use io::{
131    AgentEvent, ResumeDecisionAction, RunRequest, RuntimeInput, RuntimeOutput, ToolCallDecision,
132};
133
134// runtime plugin/tool-call/lifecycle
135pub use runtime::{
136    build_read_only_context_from_step, reduce_state_actions, Action, ActivityContext,
137    ActivityManager, AfterInferenceContext, AfterToolExecuteContext, AgentBehavior, AnyStateAction,
138    BeforeInferenceContext, BeforeToolExecuteContext, DecisionReplayPolicy, Extensions,
139    NoOpBehavior, Phase, PhaseContext, PhasePolicy, ReadOnlyContext, RunAction, RunContext,
140    RunDelta, RunEndContext, RunStartContext, ScopeContext, SerializedStateAction,
141    StateActionDecodeError, StateActionDeserializerRegistry, StateScope, StateScopeRegistry,
142    StateSpec, StepContext, StepEndContext, StepOutcome, StepStartContext, StoppedReason,
143    StreamResult, SuspendTicket, Suspension, SuspensionResponse, TerminationReason, TokenUsage,
144    ToolCallAction, ToolCallContext, ToolCallOutcome, ToolCallProgressSink, ToolCallProgressState,
145    ToolCallProgressStatus, ToolCallProgressUpdate, ToolExecution, ToolExecutionEffect,
146    ToolExecutionRequest, ToolExecutionResult, ToolExecutor, ToolExecutorError, ToolGate,
147    ToolProgressState, TOOL_CALL_PROGRESS_ACTIVITY_TYPE, TOOL_CALL_PROGRESS_SCHEMA,
148    TOOL_CALL_PROGRESS_TYPE, TOOL_PROGRESS_ACTIVITY_TYPE, TOOL_PROGRESS_ACTIVITY_TYPE_LEGACY,
149};
150
151// storage
152pub use storage::{
153    paginate_in_memory, paginate_runs_in_memory, Committed, MessagePage, MessageQuery,
154    MessageWithCursor, RunOrigin, RunPage, RunQuery, RunReader, RunRecord, RunStore, RunStoreError,
155    RunWriter, SortOrder, ThreadHead, ThreadListPage, ThreadListQuery, ThreadReader, ThreadStore,
156    ThreadStoreError, ThreadSync, ThreadWriter, VersionPrecondition,
157};
158
159// transport
160pub use transport::{Identity, Transcoder};