Skip to main content

mlua_swarm/
operator.rs

1//! Operator abstraction.
2//!
3//! ## Roles
4//!
5//! - **Spawners** (`SpawnerAdapter`) do not know about `Operator` `kind`s.
6//!   Ordinary dispatches are handled by `ProcessSpawner` /
7//!   `InProcSpawner` / etc.
8//! - `OperatorSpawner` is the `SpawnerAdapter` that routes dispatches
9//!   through an operator. It holds an `Arc<dyn Operator>` and does one
10//!   thing: hand every spawn request to that operator's `execute`. It
11//!   still does not know the operator's `kind` (`MainAi` / `Human` /
12//!   `Automate` / `Composite`).
13//! - The `Operator` trait itself returns a `WorkerResult`, as a
14//!   synchronous backend. Implementations are free per kind — a `MainAi`
15//!   operator might round-trip through Claude via an HTTP callback, a
16//!   `Human` operator might prompt on a CLI, an `Automate` operator
17//!   might delegate to a different spawner, and so on.
18//!
19//! Which dispatches go through the `OperatorSpawner` is decided at the
20//! flow.ir layer (designer + hints + Swarm compiler). The algocline
21//! strategy side never says "hand this to the operator" — a firm
22//! separation of concerns.
23
24pub mod render;
25
26pub use render::{render_system, slots_from_prompt, RenderError};
27
28use crate::core::ctx::Ctx;
29use crate::core::engine::Engine;
30use crate::types::{CapToken, TaskId, WorkerId};
31use crate::worker::adapter::{SpawnError, SpawnerAdapter, WorkerError, WorkerResult};
32use crate::worker::output::{ContentRef, OutputEvent};
33use crate::worker::{Worker, WorkerJoinHandler};
34use async_trait::async_trait;
35use std::sync::Arc;
36use tokio::sync::oneshot;
37use tokio_util::sync::CancellationToken;
38
39/// Worker binding baked from `AgentDef.profile` at compile time — which
40/// Claude Code SubAgent definition the MainAI must dispatch, plus the
41/// tool surface the Blueprint declared for this agent.
42#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
43pub struct WorkerBinding {
44    /// SubAgent definition name (Agent tool `subagent_type`).
45    pub subagent_type: String,
46    /// Tool list declared in `AgentDef.profile.tools` (informational
47    /// for the MainAI / observability; the SubAgent's own frontmatter
48    /// is what actually grants tools).
49    pub tools: Vec<String>,
50}
51
52/// The `Operator` trait: takes a spawn request and returns a
53/// `WorkerResult`. The backend for `OperatorSpawner`. Implementations
54/// are free to differ per kind; the spawner just calls `execute` and
55/// stays out of the internals.
56///
57/// Arguments — a two-slot payload plus `worker_token` (the thin path
58/// was added later) plus `worker` (the Blueprint-baked binding, added
59/// later still):
60///
61/// - `system`: the agent persona — the rendered value of
62///   `AgentDef.profile.system_prompt` after template expansion. `None`
63///   means no profile. Expected to map straight onto the LLM API's
64///   system message; direct-LLM operators consume this.
65/// - `prompt`: task-specific intent — `TaskSpec.initial_directive`,
66///   pulled server-side via `engine.fetch_prompt`. Expected to map
67///   straight onto the LLM API's user message.
68/// - `worker`: the compile-time-baked [`WorkerBinding`] (subagent type +
69///   declared tools) resolved from `AgentDef.profile.worker_binding`.
70///   `None` for agents whose profile has no `worker_binding` set.
71///   Backends that require one (see [`Operator::requires_worker_binding`])
72///   must fail loud rather than silently degrade when this is `None`.
73/// - `worker_token`: a capability token (`Role::Worker`, 600s TTL,
74///   `scopes = ["*"]`). Thin-path operators (a `a WebSocket-backed operator session`,
75///   for instance) `encode()` this token and hand it to the MainAI
76///   WebSocket client, so the SubAgent can hit `/v1/worker/prompt` +
77///   `/v1/worker/result` with `Authorization: Bearer <encoded>`.
78///   Direct-LLM operators may ignore it.
79///
80/// The trait passes both slots so the same signature works for the
81/// thin path and the direct path; the implementation picks which one
82/// it takes (consume the server-rendered `system` directly, or forward
83/// the token and let the client fetch).
84#[async_trait]
85pub trait Operator: Send + Sync {
86    /// Executes one spawn request against this operator's backend and
87    /// returns the resulting `WorkerResult` (or a `WorkerError` if the
88    /// backend failed). See the trait doc above for the meaning of each
89    /// argument.
90    async fn execute(
91        &self,
92        ctx: &Ctx,
93        system: Option<String>,
94        prompt: String,
95        worker: Option<WorkerBinding>,
96        worker_token: CapToken,
97    ) -> Result<WorkerResult, WorkerError>;
98
99    /// Whether this operator backend requires a non-`None` `worker`
100    /// binding to execute at all. `false` by default (direct-LLM
101    /// operators consume `system` / `prompt` directly and have no
102    /// SubAgent to dispatch). WS thin-path operators override this to
103    /// `true` — the compiler uses it to fail loud at `compile()` time
104    /// when `AgentDef.profile.worker_binding` is absent, rather than
105    /// silently degrading at dispatch time.
106    fn requires_worker_binding(&self) -> bool {
107        false
108    }
109}
110
111/// A `SpawnerAdapter` implementation that hands the dispatch off to an
112/// `Arc<dyn Operator>`.
113///
114/// `OperatorSpawner` itself does not inspect the operator's `kind` —
115/// `MainAi` / `Human` / `Automate` / `Composite` all go through the same
116/// path, and the operator implementation absorbs the differences.
117///
118/// # Position — the AgentSpec-axis Operator path
119///
120/// Use this type on the path that **bakes a separate Operator backend
121/// into every `AgentDef`**. For an `AgentKind::Operator` `AgentDef`, the
122/// `OperatorSpawnerFactory` produces one with
123/// `OperatorSpawner::new(op, system_prompt, worker_binding)` and places it
124/// in `routes[agent_name]`. Agents flowing in through the `agent.md`
125/// loader default to `kind = Operator`, so they land here.
126///
127/// The paired **Blueprint-global (session) axis** is
128/// `crate::middleware::OperatorDelegateMiddleware` — a single operator
129/// backend registered on the session and applied uniformly across every
130/// agent. When both are effective, the delegate middleware sits at the
131/// outer end of the stack and bypasses `inner.spawn`; this type is inert
132/// and no double fire can occur. See the `OperatorSpawnerFactory` doc
133/// for the exclusivity narrative.
134pub struct OperatorSpawner {
135    operator: Arc<dyn Operator>,
136    /// The compile-time-baked `AgentDef.profile.system_prompt` — the
137    /// agent's persona. If `Some`, it takes priority at spawn time; if
138    /// `None`, we fall back to `fetch_prompt` (`initial_directive`).
139    system_prompt: Option<String>,
140    /// The compile-time-baked worker binding — resolved from
141    /// `AgentDef.profile.worker_binding` by `OperatorSpawnerFactory`.
142    /// Passed straight through to `Operator::execute` on every spawn.
143    worker_binding: Option<WorkerBinding>,
144}
145
146impl OperatorSpawner {
147    /// Binds an operator backend plus an optional compile-time
148    /// `system_prompt` template (rendered per-spawn via `render_system`)
149    /// and an optional compile-time-baked `worker_binding`.
150    pub fn new(
151        operator: Arc<dyn Operator>,
152        system_prompt: Option<String>,
153        worker_binding: Option<WorkerBinding>,
154    ) -> Self {
155        Self {
156            operator,
157            system_prompt,
158            worker_binding,
159        }
160    }
161}
162
163#[async_trait]
164impl SpawnerAdapter for OperatorSpawner {
165    async fn spawn(
166        &self,
167        engine: &Engine,
168        ctx: &Ctx,
169        task_id: TaskId,
170        attempt: u32,
171        token: CapToken,
172    ) -> Result<Box<dyn Worker>, SpawnError> {
173        // By convention the spawner pulls `prompt`
174        // through `fetch_prompt`. The `system_prompt` (from
175        // `AgentDef.profile`) travels on the other slot — sibling to the
176        // AgentBlock path's `BlockConfig.context` / `.prompt` split.
177        let prompt = engine
178            .fetch_prompt(&token, &task_id)
179            .await
180            .map_err(|e| SpawnError::Internal(format!("fetch_prompt: {e}")))?;
181
182        // Render the `system_prompt` template.
183        // Expand the prompt into a slot map and hand the template to
184        // minijinja. The syntax used inside the agent.md body is
185        // Jinja2-compatible (`{{ directive }}` / `{% if intent %}` /
186        // `{{ x | upper }}`), with strict undefined variables and
187        // auto-escape disabled.
188        let system = match self.system_prompt.as_deref() {
189            Some(tmpl) => {
190                let slots = render::slots_from_prompt(&prompt);
191                let rendered = render::render_system(tmpl, &slots)
192                    .map_err(|e| SpawnError::Internal(format!("render system_prompt: {e}")))?;
193                Some(rendered)
194            }
195            None => None,
196        };
197
198        // Bake the rendered `system`
199        // into engine state so the SubAgent can fetch it alongside
200        // `prompt` on the `HTTP /v1/worker/prompt` path. Failures are
201        // fail-loud via `SpawnError::Internal` — no silent fallback.
202        engine
203            .bake_worker_system_prompt(&task_id, attempt, system.clone())
204            .await
205            .map_err(|e| SpawnError::Internal(format!("bake system_prompt: {e}")))?;
206
207        let op = self.operator.clone();
208        let engine_clone = engine.clone();
209        let token_clone = token.clone();
210        let token_for_op = token.clone();
211        let task_id_clone = task_id.clone();
212        let ctx_clone = ctx.clone();
213        let worker_binding = self.worker_binding.clone();
214        let (tx, rx) = oneshot::channel();
215        let cancel = CancellationToken::new();
216        let cancel_inner = cancel.clone();
217        let worker_id = WorkerId::new();
218
219        tokio::spawn(async move {
220            let result: Result<WorkerResult, WorkerError> = tokio::select! {
221                r = op.execute(&ctx_clone, system, prompt, worker_binding, token_for_op) => r,
222                _ = cancel_inner.cancelled() => Err(WorkerError::Cancelled),
223            };
224            // Emit `WorkerResult` → `OutputEvent::Final` in
225            // parallel. If the SubAgent already
226            // pushed a `Final` via HTTP (`/v1/worker/result` or
227            // `/v1/worker/submit`), skip. The POSTed value is canonical
228            // — protocol.rs L107-110 design intent. Only operator
229            // implementations that do not POST (tests, inline
230            // operators) need this fallback emit.
231            if let Ok(wr) = &result {
232                let tail = engine_clone.output_tail(&task_id_clone, attempt).await;
233                let has_final = tail
234                    .iter()
235                    .any(|ev| matches!(ev, OutputEvent::Final { .. }));
236                if !has_final {
237                    let ev = OutputEvent::Final {
238                        content: ContentRef::Inline {
239                            value: wr.value.clone(),
240                        },
241                        ok: wr.ok,
242                    };
243                    let _ = engine_clone
244                        .submit_output(&token_clone, &task_id_clone, attempt, ev)
245                        .await;
246                }
247            }
248            let signal: Result<(), WorkerError> = result.map(|_| ());
249            let _ = tx.send(signal);
250        });
251
252        Ok(Box::new(OperatorWorker {
253            handler: WorkerJoinHandler {
254                worker_id,
255                cancel,
256                completion: rx,
257            },
258        }))
259    }
260}
261
262/// Concrete Worker type for the Operator kind — wraps the async
263/// `Operator::execute` call. This represents the handle for a task
264/// backed by an operator (SDK, WebSocket bridge, direct LLM call, etc.)
265/// and embeds a `WorkerJoinHandler` that carries the async signal.
266pub struct OperatorWorker {
267    /// The completion-signal handle for this operator call's spawned
268    /// task.
269    pub handler: WorkerJoinHandler,
270}
271
272#[async_trait]
273impl Worker for OperatorWorker {
274    fn id(&self) -> &WorkerId {
275        &self.handler.worker_id
276    }
277    fn cancel_token(&self) -> CancellationToken {
278        self.handler.cancel.clone()
279    }
280    async fn join(self: Box<Self>) -> Result<(), WorkerError> {
281        self.handler.await_completion().await
282    }
283}