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 agent's terminal text>, "stop_reason": <canonical snake_case reason>}` —
98    /// from EVERY harness. The adapter maps its native terminal outcome onto the record at this
99    /// boundary (`stop_reason` spelled through the one
100    /// [`StopKind::canonical_stop_reason`](aion_core::StopKind::canonical_stop_reason) mapping);
101    /// a native outcome that cannot fill the record (e.g. a structured, non-text output) is a
102    /// typed [`HarnessError::Contract`] naming this contract and what was found — a deterministic
103    /// refusal the worker maps to a terminal activity failure — never a payload a workflow's
104    /// decoder then chokes on.
105    ///
106    /// # Errors
107    ///
108    /// Returns [`HarnessError::Harness`] when the run reported an application-level failure,
109    /// [`HarnessError::Contract`] when the completed run's native outcome cannot satisfy the
110    /// agent-outcome contract, or a transport/protocol error when the terminal result could not
111    /// be received.
112    async fn wait_result(self) -> Result<Payload, HarnessError>;
113}
114
115/// An object-safe erased [`AgentSession`], so a worker can drive a session behind a
116/// `Box<dyn ..>` without being generic over the concrete harness.
117///
118/// It mirrors [`AgentSession`] exactly EXCEPT that the terminal [`Self::wait_result`]
119/// takes `self: Box<Self>` (rather than `self` by value), which is what makes the
120/// trait object-safe — an owned-`self` method is not dispatchable through `dyn`. A
121/// blanket impl over every [`AgentSession`] means an integrator implements only the
122/// ergonomic typed trait and gets the erased form for free.
123///
124/// The async methods are `?Send`-dispatched. [`AgentSession`] is `Send` but not
125/// `Sync`, so a `&session` cannot cross threads; the worker holds an erased session
126/// inside ONE task and drives it (plus its event drain) there — never `tokio::spawn`-ing
127/// a borrow of it — so requiring `Sync` would over-constrain every adapter for no gain.
128#[async_trait(?Send)]
129pub trait DynAgentSession: Send {
130    /// The negotiated capability set — see [`AgentSession::capabilities`].
131    fn capabilities(&self) -> &InterventionCapabilities;
132
133    /// The neutral event stream OUT — see [`AgentSession::events`].
134    fn events(&mut self) -> BoxStream<'static, ActivityEvent>;
135
136    /// Deliver a neutral command IN — see [`AgentSession::intervene`].
137    ///
138    /// # Errors
139    ///
140    /// Propagates [`AgentSession::intervene`]'s errors unchanged.
141    async fn intervene(&self, cmd: InterventionCommand) -> Result<(), HarnessError>;
142
143    /// Await the single terminal result — see [`AgentSession::wait_result`]. Takes
144    /// `Box<Self>` (not `self`) so the trait stays object-safe.
145    ///
146    /// # Errors
147    ///
148    /// Propagates [`AgentSession::wait_result`]'s errors unchanged.
149    async fn wait_result(self: Box<Self>) -> Result<Payload, HarnessError>;
150}
151
152#[async_trait(?Send)]
153impl<S: AgentSession + 'static> DynAgentSession for S {
154    fn capabilities(&self) -> &InterventionCapabilities {
155        AgentSession::capabilities(self)
156    }
157
158    fn events(&mut self) -> BoxStream<'static, ActivityEvent> {
159        AgentSession::events(self)
160    }
161
162    async fn intervene(&self, cmd: InterventionCommand) -> Result<(), HarnessError> {
163        AgentSession::intervene(self, cmd).await
164    }
165
166    async fn wait_result(self: Box<Self>) -> Result<Payload, HarnessError> {
167        AgentSession::wait_result(*self).await
168    }
169}
170
171/// An object-safe erased [`AgentHarness`], so a worker can HOLD a harness behind a
172/// `Arc<dyn DynAgentHarness>` (the typed [`AgentHarness`] is not object-safe — it has
173/// an associated `Session` type).
174///
175/// A blanket impl over every [`AgentHarness`] erases the session type into a
176/// `Box<dyn DynAgentSession>`, so a composition root passes any typed harness and the
177/// worker drives it without naming the concrete type.
178#[async_trait]
179pub trait DynAgentHarness: Send + Sync {
180    /// Spawn/connect the harness for one attempt, returning an erased session.
181    ///
182    /// # Errors
183    ///
184    /// Propagates [`AgentHarness::start`]'s errors unchanged.
185    async fn start_dyn(&self, spec: AgentRunSpec)
186    -> Result<Box<dyn DynAgentSession>, HarnessError>;
187}
188
189#[async_trait]
190impl<H: AgentHarness> DynAgentHarness for H
191where
192    H::Session: 'static,
193{
194    async fn start_dyn(
195        &self,
196        spec: AgentRunSpec,
197    ) -> Result<Box<dyn DynAgentSession>, HarnessError> {
198        let session = AgentHarness::start(self, spec).await?;
199        Ok(Box::new(session))
200    }
201}