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    /// Digest of the immutable declaration-only `BoundAgent` snapshot this
58    /// binding was resolved from (`sha256:<hex>`). Carried into the spawn
59    /// frame so a non-strict Operator can correlate the request and self-check
60    /// its own environment against it. Like `tools`, this is informational —
61    /// a self-check input for the Operator, not a Server-enforced gate. `None`
62    /// on construction sites that have no snapshot (compile-time / test paths).
63    #[serde(default, skip_serializing_if = "Option::is_none")]
64    pub request_digest: Option<crate::blueprint::BindingDigest>,
65    /// Model name or tier declared in `AgentDef.profile.model`, forwarded so
66    /// the Operator can compare the requested model against what its
67    /// environment actually runs. Informational (self-check input), not an
68    /// enforcement field. `None` when the profile declares no model.
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub requested_model: Option<String>,
71}
72
73/// The `Operator` trait: takes a spawn request and returns a
74/// `WorkerResult`. The backend for `OperatorSpawner`. Implementations
75/// are free to differ per kind; the spawner just calls `execute` and
76/// stays out of the internals.
77///
78/// Arguments — a two-slot payload plus `worker_token` (the thin path
79/// was added later) plus `worker` (the Blueprint-baked binding, added
80/// later still):
81///
82/// - `system`: the agent persona — the rendered value of
83///   `AgentDef.profile.system_prompt` after template expansion. `None`
84///   means no profile. Expected to map straight onto the LLM API's
85///   system message; direct-LLM operators consume this.
86/// - `prompt`: task-specific intent — `TaskSpec.initial_directive`,
87///   pulled server-side via `engine.fetch_prompt`. Expected to map
88///   straight onto the LLM API's user message.
89/// - `worker`: the compile-time-baked [`WorkerBinding`] (subagent type +
90///   declared tools) resolved from `AgentDef.profile.worker_binding`.
91///   `None` for agents whose profile has no `worker_binding` set.
92///   Backends that require one (see [`Operator::requires_worker_binding`])
93///   must fail loud rather than silently degrade when this is `None`.
94/// - `worker_token`: a capability token (`Role::Worker`, 1800s TTL,
95///   `scopes = ["*"]`). Thin-path operators (a `a WebSocket-backed operator session`,
96///   for instance) `encode()` this token and hand it to the MainAI
97///   WebSocket client, so the SubAgent can hit `/v1/worker/prompt` +
98///   `/v1/worker/result` with `Authorization: Bearer <encoded>`.
99///   Direct-LLM operators may ignore it.
100///
101/// The trait passes both slots so the same signature works for the
102/// thin path and the direct path; the implementation picks which one
103/// it takes (consume the server-rendered `system` directly, or forward
104/// the token and let the client fetch).
105#[async_trait]
106pub trait Operator: Send + Sync {
107    /// Executes one spawn request against this operator's backend and
108    /// returns the resulting `WorkerResult` (or a `WorkerError` if the
109    /// backend failed). See the trait doc above for the meaning of each
110    /// argument.
111    async fn execute(
112        &self,
113        ctx: &Ctx,
114        system: Option<String>,
115        prompt: Value,
116        worker: Option<WorkerBinding>,
117        worker_token: CapToken,
118    ) -> Result<WorkerResult, WorkerError>;
119
120    /// Whether this operator backend requires a non-`None` `worker`
121    /// binding to execute at all. `false` by default (direct-LLM
122    /// operators consume `system` / `prompt` directly and have no
123    /// SubAgent to dispatch). WS thin-path operators override this to
124    /// `true` — the compiler uses it to fail loud at `compile()` time
125    /// when `AgentDef.profile.worker_binding` is absent, rather than
126    /// silently degrading at dispatch time.
127    fn requires_worker_binding(&self) -> bool {
128        false
129    }
130}
131
132/// A `SpawnerAdapter` implementation that hands the dispatch off to an
133/// `Arc<dyn Operator>`.
134///
135/// `OperatorSpawner` itself does not inspect the operator's `kind` —
136/// `MainAi` / `Human` / `Automate` / `Composite` all go through the same
137/// path, and the operator implementation absorbs the differences.
138///
139/// # Position — the AgentSpec-axis Operator path
140///
141/// Use this type on the path that **bakes a separate Operator backend
142/// into every `AgentDef`**. For an `AgentKind::Operator` `AgentDef`, the
143/// `OperatorSpawnerFactory` produces one with
144/// `OperatorSpawner::new(op, system_prompt, worker_binding)` and places it
145/// in `routes[agent_name]`. Agents flowing in through the `agent.md`
146/// loader default to `kind = Operator`, so they land here.
147///
148/// The paired **Blueprint-global (session) axis** is
149/// `crate::middleware::OperatorDelegateMiddleware` — a single operator
150/// backend registered on the session and applied uniformly across every
151/// agent. When both are effective, the delegate middleware sits at the
152/// outer end of the stack and bypasses `inner.spawn`; this type is inert
153/// and no double fire can occur. See the `OperatorSpawnerFactory` doc
154/// for the exclusivity narrative.
155pub struct OperatorSpawner {
156    operator: Arc<dyn Operator>,
157    /// The compile-time-baked `AgentDef.profile.system_prompt` — the
158    /// agent's persona. If `Some`, it takes priority at spawn time; if
159    /// `None`, we fall back to `fetch_prompt` (`initial_directive`).
160    system_prompt: Option<String>,
161    /// The compile-time-baked worker binding — resolved from
162    /// `AgentDef.profile.worker_binding` by `OperatorSpawnerFactory`.
163    /// Passed straight through to `Operator::execute` on every spawn.
164    worker_binding: Option<WorkerBinding>,
165}
166
167impl OperatorSpawner {
168    /// Binds an operator backend plus an optional compile-time
169    /// `system_prompt` template (rendered per-spawn via `render_system`)
170    /// and an optional compile-time-baked `worker_binding`.
171    pub fn new(
172        operator: Arc<dyn Operator>,
173        system_prompt: Option<String>,
174        worker_binding: Option<WorkerBinding>,
175    ) -> Self {
176        Self {
177            operator,
178            system_prompt,
179            worker_binding,
180        }
181    }
182}
183
184#[async_trait]
185impl SpawnerAdapter for OperatorSpawner {
186    async fn spawn(
187        &self,
188        engine: &Engine,
189        ctx: &Ctx,
190        task_id: StepId,
191        attempt: u32,
192        token: CapToken,
193    ) -> Result<Box<dyn Worker>, SpawnError> {
194        // By convention the spawner pulls `prompt`
195        // through `fetch_prompt`. The `system_prompt` (from
196        // `AgentDef.profile`) travels on the other slot — sibling to the
197        // AgentBlock path's `BlockConfig.context` / `.prompt` split.
198        let prompt = engine
199            .fetch_prompt(&token, &task_id)
200            .await
201            .map_err(|e| SpawnError::Internal(format!("fetch_prompt: {e}")))?;
202
203        // Render the `system_prompt` template.
204        // Expand the prompt into a slot map and hand the template to
205        // minijinja. The syntax used inside the agent.md body is
206        // Jinja2-compatible (`{{ directive }}` / `{% if intent %}` /
207        // `{{ x | upper }}`), with strict undefined variables and
208        // auto-escape disabled.
209        let system = match self.system_prompt.as_deref() {
210            Some(tmpl) => {
211                let slots = render::slots_from_prompt(&prompt);
212                let rendered = render::render_system(tmpl, &slots)
213                    .map_err(|e| SpawnError::Internal(format!("render system_prompt: {e}")))?;
214                Some(rendered)
215            }
216            None => None,
217        };
218
219        // Bake the rendered `system`
220        // into engine state so the SubAgent can fetch it alongside
221        // `prompt` on the `HTTP /v1/worker/prompt` path. Failures are
222        // fail-loud via `SpawnError::Internal` — no silent fallback.
223        engine
224            .bake_worker_system_prompt(&task_id, attempt, system.clone())
225            .await
226            .map_err(|e| SpawnError::Internal(format!("bake system_prompt: {e}")))?;
227
228        let op = self.operator.clone();
229        let engine_clone = engine.clone();
230        let token_clone = token.clone();
231        let token_for_op = token.clone();
232        let task_id_clone = task_id.clone();
233        let ctx_clone = ctx.clone();
234        let worker_binding = self.worker_binding.clone();
235        let (tx, rx) = oneshot::channel();
236        let cancel = CancellationToken::new();
237        let cancel_inner = cancel.clone();
238        let worker_id = WorkerId::new();
239        // issue #11: surface the minted WorkerId in the trace log.
240        tracing::debug!(worker_id = %worker_id, step_id = %task_id, "worker spawned (operator spawner)");
241
242        tokio::spawn(async move {
243            let result: Result<WorkerResult, WorkerError> = tokio::select! {
244                r = op.execute(&ctx_clone, system, prompt, worker_binding, token_for_op) => r,
245                _ = cancel_inner.cancelled() => Err(WorkerError::Cancelled),
246            };
247            // Per-step run stats: the WS operator ack may attach
248            // harness-reported SubAgent usage — forward it to the
249            // engine so the dispatcher's outcome fold lands it on the
250            // terminal StepEntry. Even without stats attached,
251            // `ensure_worker_kind` guarantees the `worker_kind:
252            // "operator"` label always rides (mirrors the sibling
253            // `OperatorDelegateMiddleware` fold site).
254            let result = result.map(|wr| wr.ensure_worker_kind("operator"));
255            if let Ok(wr) = &result {
256                if let Some(stats) = wr.stats.clone() {
257                    engine_clone
258                        .record_worker_stats(&task_id_clone, attempt, stats)
259                        .await;
260                }
261            }
262            // Emit `WorkerResult` → `OutputEvent::Final` in
263            // parallel. If the SubAgent already
264            // pushed a `Final` via HTTP (`/v1/worker/result` or
265            // `/v1/worker/submit`), skip. The POSTed value is canonical
266            // — protocol.rs L107-110 design intent. Only operator
267            // implementations that do not POST (tests, inline
268            // operators) need this fallback emit.
269            if let Ok(wr) = &result {
270                let tail = engine_clone.output_tail(&task_id_clone, attempt).await;
271                let has_final = tail
272                    .iter()
273                    .any(|ev| matches!(ev, OutputEvent::Final { .. }));
274                if !has_final {
275                    let ev = OutputEvent::Final {
276                        content: ContentRef::Inline {
277                            value: wr.value.clone(),
278                        },
279                        ok: wr.ok,
280                    };
281                    // GH #51: `submit_output` now embeds the
282                    // completion-time verdict-contract check (see
283                    // `Engine::verdict_contract_completion_check`'s doc)
284                    // — this fallback emit is gated by it exactly like
285                    // the HTTP routes are, with zero new WS protocol
286                    // surface. On rejection the `Final` is simply never
287                    // written: `output_tail` stays without one, and the
288                    // downstream `dispatch_attempt_with` Final-pull
289                    // naturally treats the attempt as incomplete — no new
290                    // reject-back-to-client message is synthesized (the
291                    // deliberate "Zero flow-ir changes" design choice, not
292                    // a gap to fill).
293                    if let Err(e) = engine_clone
294                        .submit_output(&token_clone, &task_id_clone, attempt, ev)
295                        .await
296                    {
297                        tracing::warn!(
298                            step_id = %task_id_clone,
299                            attempt,
300                            error = %e,
301                            "operator fallback Final rejected by verdict-contract completion gate"
302                        );
303                    }
304                }
305            }
306            let signal: Result<(), WorkerError> = result.map(|_| ());
307            let _ = tx.send(signal);
308        });
309
310        Ok(Box::new(OperatorWorker {
311            handler: WorkerJoinHandler {
312                worker_id,
313                cancel,
314                completion: rx,
315            },
316        }))
317    }
318}
319
320/// Concrete Worker type for the Operator kind — wraps the async
321/// `Operator::execute` call. This represents the handle for a task
322/// backed by an operator (SDK, WebSocket bridge, direct LLM call, etc.)
323/// and embeds a `WorkerJoinHandler` that carries the async signal.
324pub struct OperatorWorker {
325    /// The completion-signal handle for this operator call's spawned
326    /// task.
327    pub handler: WorkerJoinHandler,
328}
329
330#[async_trait]
331impl Worker for OperatorWorker {
332    fn id(&self) -> &WorkerId {
333        &self.handler.worker_id
334    }
335    fn cancel_token(&self) -> CancellationToken {
336        self.handler.cancel.clone()
337    }
338    async fn join(self: Box<Self>) -> Result<(), WorkerError> {
339        self.handler.await_completion().await
340    }
341}