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