Skip to main content

aion_integrations/
contract.rs

1//! The harness-integration seam: the [`AgentHarness`] trait an integrator implements and the
2//! live [`AgentSession`] it produces.
3//!
4//! This is the SDK's published extension seam, mirroring `aion-client`'s `WorkflowTransport`
5//! (a dedicated `#[async_trait]` contract module). It is **harness-blind by construction**: no
6//! signature names a concrete harness, a transport, or a wire protocol. A harness is integrated
7//! by implementing these traits in a separate adapter crate; the seam speaks only neutral run
8//! identity, the neutral [`ActivityEvent`] / [`InterventionCommand`] types, the neutral
9//! [`InterventionCapabilities`] advertisement, and a neutral terminal [`Payload`].
10//!
11//! # Designed from two cases so it is provably general
12//!
13//! The seam is designed against two deliberately different integrations at once, so it cannot be
14//! shaped by any one harness:
15//!
16//! - a full rich-path harness (a bidirectional channel, streamed events out, acknowledged
17//!   commands in, a structured terminal result), and
18//! - a plain-stdout, **observability-only** CLI agent (no command channel at all): it demuxes
19//!   interleaved stdout into [`ActivityEvent`]s (mostly [`aion_core::ActivityEventKind::Raw`]),
20//!   advertises an **empty** [`InterventionCapabilities`] set, and yields its final output as the
21//!   result.
22//!
23//! The empty-capability case is what forces [`AgentSession::intervene`] to be
24//! optional-by-capability: an empty advertisement is a valid, first-class tier, and a session
25//! that advertises it rejects every command with [`HarnessError::CapabilityNotSupported`].
26
27use aion_core::{ActivityEvent, InterventionCapabilities, InterventionCommand, Payload};
28use async_trait::async_trait;
29use futures::stream::BoxStream;
30
31use crate::error::HarnessError;
32use crate::spec::AgentRunSpec;
33
34/// How to run one agent harness — the SDK's published extension seam.
35///
36/// An integrator implements this (in a separate adapter crate) to teach Aion how to spawn or
37/// connect their harness for a single activity attempt. It is harness-blind: [`Self::start`]
38/// takes only the neutral [`AgentRunSpec`] and returns a live [`AgentSession`].
39#[async_trait]
40pub trait AgentHarness: Send + Sync {
41    /// The live session type this harness produces for one attempt.
42    type Session: AgentSession;
43
44    /// Spawns or connects the harness for one activity attempt, negotiates capabilities, and
45    /// returns a live session.
46    ///
47    /// `spec` carries the neutral run identity (`workflow_id`, `activity_id`, `attempt`) and the
48    /// input [`Payload`] — never any harness-specific configuration.
49    ///
50    /// # Errors
51    ///
52    /// Returns a [`HarnessError`] when the harness cannot be spawned/connected or when the
53    /// capability handshake fails ([`HarnessError::Transport`] / [`HarnessError::Protocol`]).
54    async fn start(&self, spec: AgentRunSpec) -> Result<Self::Session, HarnessError>;
55}
56
57/// A live agent run for one activity attempt.
58///
59/// Produced by [`AgentHarness::start`]. Exposes the negotiated capability set, a stream of
60/// neutral events OUT, a neutral command sink IN, and a single terminal result.
61#[async_trait]
62pub trait AgentSession: Send {
63    /// The capability set negotiated at start.
64    ///
65    /// The server and ops console gate on THIS, never on harness identity. An **empty** set is a
66    /// first-class advertisement — an observability-only harness supports no interventions.
67    fn capabilities(&self) -> &InterventionCapabilities;
68
69    /// The stream of neutral events produced by this run.
70    ///
71    /// Every item is an [`ActivityEvent`]; how the adapter derives them (mapping a structured
72    /// notification, or demuxing interleaved stdout into mostly
73    /// [`aion_core::ActivityEventKind::Raw`]) is an adapter-internal detail invisible here.
74    fn events(&mut self) -> BoxStream<'static, ActivityEvent>;
75
76    /// Delivers a neutral intervention command into the running agent.
77    ///
78    /// A session whose advertised [`Self::capabilities`] set does not contain the command's
79    /// primitive rejects it with [`HarnessError::CapabilityNotSupported`]. An observability-only
80    /// session (empty set) rejects **every** command this way; the server never routes one to it
81    /// because the advertised set is empty.
82    ///
83    /// # Errors
84    ///
85    /// Returns [`HarnessError::CapabilityNotSupported`] when the command's primitive is not
86    /// advertised, [`HarnessError::StaleTarget`] when the command targets a superseded attempt,
87    /// or a transport/protocol error when delivery fails.
88    async fn intervene(&self, cmd: InterventionCommand) -> Result<(), HarnessError>;
89
90    /// Awaits the single terminal result of the run.
91    ///
92    /// Consumes the session: exactly one terminal result is produced per attempt, and it is the
93    /// replay-authoritative activity output the worker captures.
94    ///
95    /// **The completed result is the canonical agent-outcome record.** A completed run's payload
96    /// is the JSON serialization of [`aion_core::AgentOutcome`] —
97    /// `{"text": <the whole accumulated output>, "final_message": <the last completed answer>,
98    /// "stop_reason": <canonical snake_case reason>,
99    /// "session_id": <the handle of the conversation that produced the outcome>}` —
100    /// from EVERY harness. The adapter maps its native terminal outcome onto the record at this
101    /// boundary (`stop_reason` spelled through the one
102    /// [`StopKind::canonical_stop_reason`](aion_core::StopKind::canonical_stop_reason) mapping);
103    /// a native outcome that cannot fill the record (e.g. a structured, non-text output) is a
104    /// typed [`HarnessError::Contract`] naming this contract and what was found — a deterministic
105    /// refusal the worker maps to a terminal activity failure — never a payload a workflow's
106    /// decoder then chokes on.
107    ///
108    /// # Errors
109    ///
110    /// Returns [`HarnessError::Harness`] when the run reported an application-level failure,
111    /// [`HarnessError::Contract`] when the completed run's native outcome cannot satisfy the
112    /// agent-outcome contract, or a transport/protocol error when the terminal result could not
113    /// be received.
114    async fn wait_result(self) -> Result<Payload, HarnessError>;
115}
116
117/// An object-safe erased [`AgentSession`], so a worker can drive a session behind a
118/// `Box<dyn ..>` without being generic over the concrete harness.
119///
120/// It mirrors [`AgentSession`] exactly EXCEPT that the terminal [`Self::wait_result`]
121/// takes `self: Box<Self>` (rather than `self` by value), which is what makes the
122/// trait object-safe — an owned-`self` method is not dispatchable through `dyn`. A
123/// blanket impl over every [`AgentSession`] means an integrator implements only the
124/// ergonomic typed trait and gets the erased form for free.
125///
126/// The async methods are `?Send`-dispatched. [`AgentSession`] is `Send` but not
127/// `Sync`, so a `&session` cannot cross threads; the worker holds an erased session
128/// inside ONE task and drives it (plus its event drain) there — never `tokio::spawn`-ing
129/// a borrow of it — so requiring `Sync` would over-constrain every adapter for no gain.
130#[async_trait(?Send)]
131pub trait DynAgentSession: Send {
132    /// The negotiated capability set — see [`AgentSession::capabilities`].
133    fn capabilities(&self) -> &InterventionCapabilities;
134
135    /// The neutral event stream OUT — see [`AgentSession::events`].
136    fn events(&mut self) -> BoxStream<'static, ActivityEvent>;
137
138    /// Deliver a neutral command IN — see [`AgentSession::intervene`].
139    ///
140    /// # Errors
141    ///
142    /// Propagates [`AgentSession::intervene`]'s errors unchanged.
143    async fn intervene(&self, cmd: InterventionCommand) -> Result<(), HarnessError>;
144
145    /// Await the single terminal result — see [`AgentSession::wait_result`]. Takes
146    /// `Box<Self>` (not `self`) so the trait stays object-safe.
147    ///
148    /// # Errors
149    ///
150    /// Propagates [`AgentSession::wait_result`]'s errors unchanged.
151    async fn wait_result(self: Box<Self>) -> Result<Payload, HarnessError>;
152}
153
154#[async_trait(?Send)]
155impl<S: AgentSession + 'static> DynAgentSession for S {
156    fn capabilities(&self) -> &InterventionCapabilities {
157        AgentSession::capabilities(self)
158    }
159
160    fn events(&mut self) -> BoxStream<'static, ActivityEvent> {
161        AgentSession::events(self)
162    }
163
164    async fn intervene(&self, cmd: InterventionCommand) -> Result<(), HarnessError> {
165        AgentSession::intervene(self, cmd).await
166    }
167
168    async fn wait_result(self: Box<Self>) -> Result<Payload, HarnessError> {
169        AgentSession::wait_result(*self).await
170    }
171}
172
173/// An object-safe erased [`AgentHarness`], so a worker can HOLD a harness behind a
174/// `Arc<dyn DynAgentHarness>` (the typed [`AgentHarness`] is not object-safe — it has
175/// an associated `Session` type).
176///
177/// A blanket impl over every [`AgentHarness`] erases the session type into a
178/// `Box<dyn DynAgentSession>`, so a composition root passes any typed harness and the
179/// worker drives it without naming the concrete type.
180#[async_trait]
181pub trait DynAgentHarness: Send + Sync {
182    /// Spawn/connect the harness for one attempt, returning an erased session.
183    ///
184    /// # Errors
185    ///
186    /// Propagates [`AgentHarness::start`]'s errors unchanged.
187    async fn start_dyn(&self, spec: AgentRunSpec)
188    -> Result<Box<dyn DynAgentSession>, HarnessError>;
189}
190
191#[async_trait]
192impl<H: AgentHarness> DynAgentHarness for H
193where
194    H::Session: 'static,
195{
196    async fn start_dyn(
197        &self,
198        spec: AgentRunSpec,
199    ) -> Result<Box<dyn DynAgentSession>, HarnessError> {
200        let session = AgentHarness::start(self, spec).await?;
201        Ok(Box::new(session))
202    }
203}