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