Skip to main content

mlua_swarm_server/
lib.rs

1//! the server lib: axum Router + handler set. Split out as a library so it can
2//! be used from both `main.rs` (CLI) and integration tests.
3//!
4//! # Endpoints
5//!
6//! - `GET /v1/healthz`
7//! - `POST /v1/sessions` / `DELETE /v1/sessions` (= operator attach / detach, Bearer sid)
8//! - `POST /v1/tasks` (= unified Flow-form entry, Operator inject supported;
9//!   `operator_sid` explicitly pins the task to a registered Operator session, S2).
10//!   Also creates a `TaskRecord` + `RunRecord` (issue #13 ID-hierarchy persistence)
11//!   and echoes their ids in the response; see the `tasks` module doc.
12//! - `GET /v1/tasks` — list every persisted `TaskRecord` (newest first).
13//! - `GET /v1/tasks/:id` — a `TaskRecord` plus every `RunRecord` kicked from it.
14//! - `POST /v1/tasks/:id/runs` — re-kick an existing Task (new `RunId`, same
15//!   `blueprint_ref` / `input_ctx`).
16//! - `GET /v1/runs/:id` — a single `RunRecord` (its `step_entries` trace included).
17//! - `POST /v1/operators` / `GET /v1/operators/:sid` / `DELETE /v1/operators/:sid` /
18//!   `GET /v1/operators/:sid/ws` (WS upgrade) — REST-like Operator login flow,
19//!   Bearer-mandatory; the sole WS Operator session route. See `operator_ws::login`
20//!   module doc.
21//!
22//! The Enhance issue axis (`/issues`) lives in the `issues` module; callers merge
23//! `build_issues_router` to integrate it into the same server.
24//!
25//! # The 3 faces of the Operator role (= registered directly on the engine SoT)
26//!
27//! The engine stateless-executor refactor removed the three
28//! `AppState` registries (former `HookRegistry` / `BridgeRegistry` / `OperatorRegistry`);
29//! all registration now goes directly to the engine SoT via
30//! `engine.register_spawn_hook` / `register_senior_bridge` / `register_operator`.
31//! `WSOperatorSession` (in the `operator_ws` module) registers all three traits
32//! simultaneously under a single sid — one WS connection covers all 3 faces of
33//! the Operator role, the canonical pattern.
34//!
35//! # `build_*` family
36//!
37//! - [`build_router`] — minimal entry (= `default_registry()`)
38//! - [`build_router_with`] — caller provides a `SpawnerRegistry` and optional `BlueprintStore`
39//!
40//! The engine should be started with [`default_layer_registry`] (= `Engine::new_with_layers`);
41//! otherwise `Blueprint.spawner_hints` is ignored.
42
43#![warn(missing_docs)]
44
45/// HTTP surface for inspecting/registering Blueprint state (`/v1/blueprints/*`).
46pub mod blueprints;
47/// Server config file support (`~/.mse/config.toml`, CLI > file > default merge).
48pub mod config;
49/// `/v1/data/*` endpoints (v9 Big Response handling, Store-owner direct path).
50pub mod data;
51/// `GET /v1/doctor` — read-only startup config / Store snapshot.
52pub mod doctor;
53/// HTTP surface for the `/v1/enhance/log` axis.
54pub mod enhance_log;
55/// `EnhanceSetting` HTTP CRUD (`/v1/enhance-settings*`).
56pub mod enhance_settings;
57/// HTTP surface for the Enhance issue axis (`/v1/issues*`).
58pub mod issues;
59/// WebSocket Operator Callback IF (`/v1/operators*`).
60pub mod operator_ws;
61/// HTTP surface for the Task/Run persistence axis (issue #13 ID hierarchy;
62/// `GET /v1/tasks`, `GET /v1/tasks/:id`, `POST /v1/tasks/:id/runs`,
63/// `GET /v1/runs/:id`). `POST /v1/tasks` itself stays in this module (it is
64/// the entry point `tasks_start` shares with the flow-eval path) — see the
65/// `tasks` module doc for the split rationale.
66pub mod tasks;
67/// `/v1/worker/*` endpoints (SubAgent self-fetch path).
68pub mod worker;
69pub use blueprints::{build_blueprints_router, build_blueprints_router_with_refs};
70pub use enhance_log::build_enhance_log_router;
71pub use enhance_settings::build_enhance_settings_router;
72pub use issues::{build_issues_router, GetIssueResponse, PostIssueRequest, PostIssueResponse};
73pub use operator_ws::{
74    operators_create, operators_delete, operators_info, operators_ws_connect, ClientMsg,
75    OperatorSessionEntry, ServerMsg, WSOperatorSession,
76};
77pub use tasks::{RunKickResponse, TaskDetailResponse};
78pub use worker::{worker_prompt, worker_result, PromptQuery, WorkerResultReq};
79
80use axum::{
81    extract::State,
82    http::{header::AUTHORIZATION, HeaderMap, StatusCode},
83    response::{IntoResponse, Response},
84    routing::{get, post},
85    Json, Router,
86};
87use mlua_swarm::application::{BlueprintRef, TaskApplication};
88use mlua_swarm::blueprint::store::BlueprintStore;
89use mlua_swarm::service::TaskLaunchService;
90use mlua_swarm::store::run::{RunContext, RunRecord, RunStatus, RunStore};
91use mlua_swarm::store::task::{TaskRecord, TaskRecordStatus, TaskStore};
92use mlua_swarm::{
93    CapToken, Compiler, Engine, LayerRegistry, LuaInProcessSpawnerFactory, MainAIMiddleware,
94    OperatorDelegateMiddleware, OperatorSpawnerFactory, Role, RunId, RustFnInProcessSpawnerFactory,
95    SeniorEscalationMiddleware, SessionId, SpawnerRegistry, SubprocessProcessSpawnerFactory,
96    TaskId,
97};
98use serde::{Deserialize, Serialize};
99use serde_json::{json, Value};
100use std::collections::HashMap;
101use std::sync::Arc;
102use std::time::Duration;
103use tokio::sync::Mutex;
104
105/// In-memory session map backing `/v1/sessions` attach/detach.
106///
107/// The `sid` handed to the client on this REST path is the token nonce
108/// itself (a bearer secret), so the server never uses it as a map key —
109/// entries are keyed by its fingerprint
110/// (`mlua_swarm::types::token_fingerprint`; issue #14).
111#[derive(Default)]
112pub struct SessionStore {
113    /// Live session tokens keyed by the sid's fingerprint.
114    pub map: HashMap<String, CapToken>,
115}
116
117/// Shared axum handler state for the whole router. Cloned per-request (all
118/// fields are `Arc`/cheap-clone), constructed once in [`build_router_with_ws_factory`].
119#[derive(Clone)]
120pub struct AppState {
121    /// The engine SoT (attach/detach, dispatch, registries).
122    pub engine: Engine,
123    /// Live `/v1/sessions` attach records (Operator/Worker/etc session tokens).
124    pub sessions: Arc<Mutex<SessionStore>>,
125    /// Application used at the task entry to resolve `BlueprintRef`. Without a Store, runs in Inline-only mode.
126    pub task_app: Arc<TaskApplication>,
127    /// When `Some`, on WS connect a new `WSOperatorSession` is automatically registered
128    /// with this factory under the sid name (= a `kind=operator` + `operator_ref=<sid>` AgentDef
129    /// binds to the `WSOperatorSession` backend).
130    /// When `None`, no auto-registration happens; the session is only registered on
131    /// `engine.OperatorRegistry` (= only the `OperatorDelegateMiddleware` path is effective;
132    /// the `OperatorSpawnerFactory` path is dead).
133    pub ws_operator_factory: Option<Arc<OperatorSpawnerFactory>>,
134    /// Owner of the Store on the Data path (Big Response handling). Added in v9.
135    /// Independent layer — the Engine core and the Domain path (`/v1/worker/result`)
136    /// are not involved.
137    /// Default = `InMemoryOutputStore` (constructed inside `build_router_with_ws_factory`);
138    /// callers can swap in an sqlite/fs backend later (future carry).
139    pub data_store: Arc<dyn mlua_swarm::store::output::OutputStore>,
140    /// Login-flow session store (`POST /v1/operators` mint records). `sid` →
141    /// `OperatorSessionEntry`. This is the sole session store for the WS
142    /// Operator role. See `operator_ws::login` module doc.
143    pub operator_sessions:
144        Arc<Mutex<HashMap<SessionId, Arc<crate::operator_ws::login::OperatorSessionEntry>>>>,
145    /// S1 login-flow roles-exclusivity map. Role name → owning `sid`. Checked
146    /// (and updated) atomically under a single lock in
147    /// `operator_ws::login::operators_create` — a role already present here
148    /// causes `POST /v1/operators` to return `409 CONFLICT`. Entries are
149    /// released on `DELETE /v1/operators/:sid`.
150    pub roles_to_sid: Arc<Mutex<HashMap<String, SessionId>>>,
151    /// Persistence for `Task` records (issue #13 ID-hierarchy work-item
152    /// identity; see `mlua_swarm::store::task` module doc). Default =
153    /// `InMemoryTaskStore` (constructed inside `build_router_full`); callers
154    /// can swap in a `SqliteTaskStore` via the `task_store` argument.
155    pub task_store: Arc<dyn TaskStore>,
156    /// Persistence for `Run` records (one kick of a Task; see
157    /// `mlua_swarm::store::run` module doc). Default = `InMemoryRunStore`;
158    /// callers can swap in a `SqliteRunStore` via the `run_store` argument.
159    pub run_store: Arc<dyn RunStore>,
160    /// Public HTTP base URL the server is reachable at (e.g.
161    /// `"http://127.0.0.1:7777"`), sourced from the binary at boot time.
162    /// When `Some`, `WSOperatorSession` renders it literally into the
163    /// Spawn `directive`'s `base_url` line so the receiving operator can
164    /// paste the frame into a SubAgent prompt without a `mse_doctor`
165    /// detour (issue #8). `None` preserves the historical fallback
166    /// (a placeholder that points at `mse_doctor`).
167    pub base_url: Option<Arc<str>>,
168}
169
170/// Minimal entry point: builds a router with [`default_registry`] and no
171/// `BlueprintStore` (Inline-only mode) or `ws_operator_factory`.
172pub fn build_router(engine: Engine) -> Router {
173    build_router_with(engine, default_registry(), None)
174}
175
176/// Default `LayerRegistry` for the server. Hint keys:
177/// - `"main_ai"` → `MainAIMiddleware` (= fires SpawnHook before/after)
178/// - `"senior_escalation"` → `SeniorEscalationMiddleware` (= on `ok=false`, escalates via `SeniorBridge.ask`)
179/// - `"operator_delegate"` → `OperatorDelegateMiddleware` (= when an operator backend is registered, delegates the entire spawn)
180///
181/// Including any of these keys in `Blueprint.spawner_hints.layers` causes them to
182/// be wrapped into a `SpawnerStack` at `service::linker::link` time (= per-launch;
183/// the old `engine.bind` global-state path is retired).
184/// Callers (the engine builder side) receive it via
185/// `Engine::new_with_layers(cfg, mse_server::default_layer_registry())`.
186pub fn default_layer_registry() -> LayerRegistry {
187    LayerRegistry::new()
188        .with_hint("main_ai", |_engine| Arc::new(MainAIMiddleware::new()))
189        .with_hint("senior_escalation", |_engine| {
190            Arc::new(SeniorEscalationMiddleware::new())
191        })
192        .with_hint("operator_delegate", |_engine| {
193            Arc::new(OperatorDelegateMiddleware::new())
194        })
195}
196
197/// Build form where the caller supplies a registry and an optional `BlueprintStore`.
198/// The Operator callback path (= external HTTP / WS callers acting as an Operator)
199/// must be pre-registered via `engine.register_*` (= the engine is the SoT).
200/// See the `operator_ws` module doc and `OperatorInfo` (engine-side `ctx.rs`) for details.
201pub fn build_router_with(
202    engine: Engine,
203    registry: SpawnerRegistry,
204    store: Option<Arc<dyn BlueprintStore>>,
205) -> Router {
206    build_router_with_ws_factory(engine, registry, store, None)
207}
208
209/// 4-argument variant of `build_router_with`. Passing `ws_operator_factory = Some(arc)`
210/// causes each WS connect to auto-register a new `WSOperatorSession` under its sid
211/// name with the factory (= a `kind=operator` AgentDef with `operator_ref: <sid>`
212/// can then bind to the WS client backend). Callers are expected to also install
213/// the same `Arc` into the `SpawnerRegistry` via
214/// `reg.register::<OperatorSpawnerFactory>(arc.clone())`.
215pub fn build_router_with_ws_factory(
216    engine: Engine,
217    registry: SpawnerRegistry,
218    store: Option<Arc<dyn BlueprintStore>>,
219    ws_operator_factory: Option<Arc<OperatorSpawnerFactory>>,
220) -> Router {
221    build_router_with_ws_factory_and_output(engine, registry, store, ws_operator_factory, None)
222}
223
224/// 5-argument variant of [`build_router_with_ws_factory`]. Passing
225/// `output_store = Some(arc)` swaps the default `InMemoryOutputStore` for a
226/// caller-supplied backend (a `SqliteOutputStore`, for instance). `None`
227/// preserves the historical behaviour (fresh in-memory store per call).
228pub fn build_router_with_ws_factory_and_output(
229    engine: Engine,
230    registry: SpawnerRegistry,
231    store: Option<Arc<dyn BlueprintStore>>,
232    ws_operator_factory: Option<Arc<OperatorSpawnerFactory>>,
233    output_store: Option<Arc<dyn mlua_swarm::store::output::OutputStore>>,
234) -> Router {
235    build_router_full(
236        engine,
237        registry,
238        store,
239        ws_operator_factory,
240        output_store,
241        None,
242        None,
243        None,
244    )
245}
246
247/// 8-argument variant of [`build_router_with_ws_factory_and_output`].
248/// Passing `base_url = Some(...)` (e.g. `"http://127.0.0.1:7777"`) makes
249/// `WSOperatorSession` render the actual server bind into the Spawn
250/// directive's `base_url` line, so the receiving operator can copy the
251/// frame straight into a SubAgent prompt (issue #8). `None` preserves
252/// the historical fallback (`<check with mse_doctor>` placeholder).
253/// `task_store` / `run_store` swap the default `InMemoryTaskStore` /
254/// `InMemoryRunStore` (issue #13 ID-hierarchy persistence) for a
255/// caller-supplied backend (`SqliteTaskStore` / `SqliteRunStore`, for
256/// instance); `None` preserves the process-volatile default.
257// This is the terminal builder in the `build_router*` delegation chain
258// (each variant adds one more caller-overridable store/factory); the
259// argument count grows with the number of pluggable backends, not with
260// unrelated responsibilities, so a plain allow is preferable to bundling
261// them into a config struct only this one function would consume.
262#[allow(clippy::too_many_arguments)]
263pub fn build_router_full(
264    engine: Engine,
265    registry: SpawnerRegistry,
266    store: Option<Arc<dyn BlueprintStore>>,
267    ws_operator_factory: Option<Arc<OperatorSpawnerFactory>>,
268    output_store: Option<Arc<dyn mlua_swarm::store::output::OutputStore>>,
269    base_url: Option<Arc<str>>,
270    task_store: Option<Arc<dyn TaskStore>>,
271    run_store: Option<Arc<dyn RunStore>>,
272) -> Router {
273    let compiler = Compiler::new(registry);
274    let launch = Arc::new(TaskLaunchService::new(engine.clone(), compiler));
275    let task_app = Arc::new(match store {
276        Some(s) => TaskApplication::new(launch, s),
277        None => TaskApplication::new_inline_only(launch),
278    });
279    let data_store: Arc<dyn mlua_swarm::store::output::OutputStore> = match output_store {
280        Some(s) => s,
281        None => Arc::new(mlua_swarm::store::output::InMemoryOutputStore::new()),
282    };
283    let task_store: Arc<dyn TaskStore> = match task_store {
284        Some(s) => s,
285        None => Arc::new(mlua_swarm::store::task::InMemoryTaskStore::new()),
286    };
287    let run_store: Arc<dyn RunStore> = match run_store {
288        Some(s) => s,
289        None => Arc::new(mlua_swarm::store::run::InMemoryRunStore::new()),
290    };
291    let state = AppState {
292        engine,
293        sessions: Arc::new(Mutex::new(SessionStore::default())),
294        task_app,
295        ws_operator_factory,
296        data_store,
297        operator_sessions: Arc::new(Mutex::new(HashMap::new())),
298        roles_to_sid: Arc::new(Mutex::new(HashMap::new())),
299        task_store,
300        run_store,
301        base_url,
302    };
303    Router::new()
304        .route("/v1/healthz", get(healthz))
305        // session = collection (POST = attach, DELETE = detach, sid via Authorization)
306        .route(
307            "/v1/sessions",
308            post(sessions_attach).delete(sessions_detach),
309        )
310        // task = flat, single level; authz resolved via Authorization: Bearer <sid>
311        .route("/v1/tasks", post(tasks_start).get(tasks::tasks_list))
312        .route("/v1/tasks/:id", get(tasks::task_get))
313        .route("/v1/tasks/:id/runs", post(tasks::task_rekick))
314        .route("/v1/runs/:id", get(tasks::run_get))
315        // REST-like Operator login flow (Bearer-mandatory, roles exclusivity).
316        // Sole WS Operator session route; see `operator_ws::login` module doc.
317        .route("/v1/operators", post(operators_create))
318        .route("/v1/operators/:sid/ws", get(operators_ws_connect))
319        .route(
320            "/v1/operators/:sid",
321            get(operators_info).delete(operators_delete),
322        )
323        // SubAgent self-fetch path (the SubAgent self-fetch design). The SubAgent puts the
324        // CapToken handed over via WS Spawn into Bearer and hits the prompt / result
325        // endpoints directly over HTTP. See the `worker` module doc for details.
326        .route("/v1/worker/prompt", get(worker::worker_prompt))
327        .route("/v1/worker/result", post(worker::worker_result))
328        // Simplified endpoint (= worker POSTs with just token + raw body; task_id is auto-looked-up)
329        .route("/v1/worker/submit", post(worker::worker_submit))
330        // Data path (v9 Big Response handling, independent from Domain / verdict flow)
331        .route("/v1/data/emit", post(data::data_emit))
332        .route(
333            "/v1/data/:key",
334            get(data::data_get).post(data::data_emit_named),
335        )
336        .with_state(state)
337}
338
339/// Default registry = Subprocess + RustFn (baseline `identity` worker pre-baked) + empty Operator factory.
340///
341/// `RustFnInProcessSpawnerFactory` gets one baseline entry (`fn_id = "identity"`)
342/// baked in via [`mlua_swarm::worker::baseline::extend_with_baseline`]. This
343/// is the shared bootstrap / smoke worker SoT across each binary (the server / MCP adapter /
344/// one-shot runner) — it structurally replaces the old per-binary inline echo injection.
345///
346/// Usage: default Task path at server startup. If production needs additional
347/// backends, callers bring in a different registry via
348/// `build_router_with(engine, custom_registry)`. The enhance flow
349/// (= patch-spawner / patch-applier / verifier-router / committer axes) uses
350/// [`default_registry_with_enhance_flow`].
351///
352/// The Operator factory is an empty shell with zero registrations (= sids are
353/// dynamically registered per WS connect; see the `operator_ws` module).
354pub fn default_registry() -> SpawnerRegistry {
355    let rustfn_factory =
356        mlua_swarm::worker::baseline::extend_with_baseline(RustFnInProcessSpawnerFactory::new());
357
358    let mut reg = SpawnerRegistry::new();
359    reg.register::<SubprocessProcessSpawnerFactory>(Arc::new(SubprocessProcessSpawnerFactory));
360    reg.register::<RustFnInProcessSpawnerFactory>(Arc::new(rustfn_factory));
361    reg.register::<OperatorSpawnerFactory>(Arc::new(OperatorSpawnerFactory::new()));
362    reg
363}
364
365/// Opt-in registry that merges [`default_registry`] with the enhance flow
366/// (Lua factory + AgentBlock factory).
367///
368/// Selected via the `the server` CLI flag `--enable-enhance-flow`. The enhance
369/// flow is a separate-axis wrapper: the Lua factory (= 3 Lua workers + 3 primitive
370/// bridges) and the AgentBlock factory (= patch-spawner path, expects
371/// `assets/operator_scripts/blueprint_patch_spawner.lua` + `ANTHROPIC_API_KEY`)
372/// are baked in as pipeline defaults. The baseline RustFn (`identity`) is pre-baked
373/// the same way as in `default_registry`.
374pub fn default_registry_with_enhance_flow() -> SpawnerRegistry {
375    let lua_factory =
376        mlua_swarm::enhance::blueprint::extend_factory(LuaInProcessSpawnerFactory::new());
377    // The Factory is stateless (= 1 process → 1 factory shared by all AgentDefs).
378    // Per-agent specialization (script_path / project_root, etc.) goes through AgentDef.spec.
379    // The enhance-flow patch-spawner is declared literally in agents[].spec of `default_blueprint.yaml`.
380    let agent_block_factory =
381        mlua_swarm::worker::agent_block::AgentBlockInProcessSpawnerFactory::new();
382    let rustfn_factory =
383        mlua_swarm::worker::baseline::extend_with_baseline(RustFnInProcessSpawnerFactory::new());
384
385    let mut reg = SpawnerRegistry::new();
386    reg.register::<SubprocessProcessSpawnerFactory>(Arc::new(SubprocessProcessSpawnerFactory));
387    reg.register::<RustFnInProcessSpawnerFactory>(Arc::new(rustfn_factory));
388    reg.register::<LuaInProcessSpawnerFactory>(Arc::new(lua_factory));
389    reg.register::<mlua_swarm::worker::agent_block::AgentBlockInProcessSpawnerFactory>(Arc::new(
390        agent_block_factory,
391    ));
392    reg.register::<OperatorSpawnerFactory>(Arc::new(OperatorSpawnerFactory::new()));
393    reg
394}
395
396// ─── handlers ────────────────────────────────────────────────────────────
397
398async fn healthz() -> &'static str {
399    "ok"
400}
401
402#[derive(Deserialize)]
403struct AttachReq {
404    agent_id: String,
405    role: String,
406    ttl_secs: u64,
407}
408
409#[derive(Serialize)]
410struct AttachResp {
411    session_id: String,
412    role: String,
413}
414
415async fn sessions_attach(
416    State(state): State<AppState>,
417    Json(req): Json<AttachReq>,
418) -> Result<Json<AttachResp>, ApiError> {
419    let role = parse_role(&req.role)?;
420    let token = state
421        .engine
422        .attach(req.agent_id, role, Duration::from_secs(req.ttl_secs))
423        .await
424        .map_err(ApiError::engine)?;
425    // The wire `session_id` stays the nonce (Bearer credential contract);
426    // the server-side map key is its fingerprint (issue #14).
427    let sid = token.nonce.clone();
428    let key = token.fingerprint();
429    state.sessions.lock().await.map.insert(key, token);
430    Ok(Json(AttachResp {
431        session_id: sid,
432        role: req.role,
433    }))
434}
435
436async fn sessions_detach(
437    State(state): State<AppState>,
438    headers: HeaderMap,
439) -> Result<StatusCode, ApiError> {
440    let sid = extract_bearer(&headers)?;
441    let token = take_session_token(&state, &sid).await?;
442    state
443        .engine
444        .detach(&token)
445        .await
446        .map_err(ApiError::engine)?;
447    Ok(StatusCode::NO_CONTENT)
448}
449
450// ─── Unified /v1/tasks schema (= flow-eval path, Operator inject supported) ───────
451
452/// `/v1/tasks` POST schema. Uses the flow-eval path and supports Operator inject
453/// (kind / spawn_hook / senior_bridge). Expressing a one-shot task as a 1-Step
454/// Blueprint is the only correct model.
455#[derive(Deserialize)]
456struct FlowTasksReq {
457    blueprint: BlueprintRef,
458    init_ctx: Value,
459    /// TTL in seconds. When unspecified (`None`), falls back in this order:
460    /// (1) `metadata.default_run_ttl_secs` from the resolved BP,
461    /// (2) if absent, the server global `default_run_ttl()` (1800s).
462    #[serde(default)]
463    ttl_secs: Option<u64>,
464    #[serde(default)]
465    operator: Option<OperatorReq>,
466    /// Explicit Operator session sid (or role alias) this task's entire Spawn
467    /// stream should be routed to (runtime Operator match stage 1).
468    ///
469    /// When `Some`, it is validated at request time against
470    /// `state.engine.list_operator_ids()` (the live `engine.operators`
471    /// registry key set): an unknown/never-registered id returns `400`
472    /// immediately — this is a deliberate hard-fail, in contrast to
473    /// `OperatorDelegateWrapped::spawn`, which silently falls through to
474    /// `inner.spawn` on a registry miss. A sid that *was* registered but has
475    /// since disconnected (WS `tx` cleared, session entry retained for
476    /// reconnect) passes this check and surfaces as an explicit dispatch-time
477    /// error instead (`WSOperatorSession::send_and_await` returns `Err` when
478    /// `tx` is `None`), which also propagates as a request failure rather
479    /// than a silent fallback.
480    ///
481    /// On success this value **overrides** `operator.operator_backend_id`
482    /// (last-write-wins, `operator_sid` takes priority) before the flow is
483    /// dispatched — see `run_flow_form`. Dispatch still only delegates if the
484    /// Blueprint opts into `spawner_hints.layers = ["operator_delegate"]`
485    /// (unchanged precondition, same as the existing `operator_backend_id`
486    /// field).
487    ///
488    /// When unset, behavior is unchanged: whatever
489    /// `operator.operator_backend_id` / BP-level `operator_ref` alias
490    /// resolution already does still applies.
491    #[serde(default)]
492    operator_sid: Option<String>,
493    /// Human-facing description of the work item (e.g. "resolve issue #10"),
494    /// stashed verbatim into the minted `TaskRecord.goal`. Omitted / `None`
495    /// stores an empty string — the flow-eval path itself never reads it.
496    #[serde(default)]
497    goal: Option<String>,
498}
499
500#[derive(Deserialize, Default)]
501struct OperatorReq {
502    /// `main_ai` / `automate` / `composite`. This is the "Runtime Global"
503    /// tier of the 4-tier `OperatorKind` cascade (see `mlua_swarm
504    /// ::ctx::collapse_operator_kind`); when unspecified, falls through to
505    /// the BP-level tiers (`OperatorDef.kind` / `Blueprint
506    /// .default_operator_kind`) instead of eagerly defaulting to `automate`.
507    #[serde(default)]
508    kind: Option<String>,
509    /// Operator id at attach time (= sessions tracking key in the EventLog); unspecified defaults to `"http-run"`.
510    #[serde(default)]
511    id: Option<String>,
512    /// Name of a hook pre-registered via `engine.register_spawn_hook`; `None` if unspecified.
513    #[serde(default)]
514    spawn_hook_id: Option<String>,
515    /// Name of a bridge pre-registered via `engine.register_senior_bridge`; `None` if unspecified.
516    #[serde(default)]
517    senior_bridge_id: Option<String>,
518    /// Name of an Operator backend pre-registered via `engine.register_operator`
519    /// (= the path that delegates the entire spawn to an external Operator);
520    /// `None` if unspecified. When `kind == MainAi/Composite` and this id is `Some`,
521    /// `OperatorDelegateMiddleware` bypasses `inner.spawn` and calls `operator.execute` instead.
522    /// This is a different axis from `operator.id` (= session tracking label);
523    /// `operator_backend_id` is the registry lookup key.
524    #[serde(default)]
525    operator_backend_id: Option<String>,
526    /// "Runtime Agent-level" tier (highest priority) of the `OperatorKind`
527    /// cascade — per-agent override, keyed by `AgentDef.name`, value is
528    /// `main_ai` / `automate` / `composite` (same parsing as `kind`).
529    /// `None` / absent means no per-agent override.
530    #[serde(default)]
531    per_agent_kinds: Option<HashMap<String, String>>,
532}
533
534/// Parse a wire-level kind string (`"main_ai"` / `"automate"` / `"composite"`)
535/// into `OperatorKind`. Shared by `OperatorReq.kind` and
536/// `OperatorReq.per_agent_kinds` values.
537fn parse_operator_kind_str(s: &str) -> Result<mlua_swarm::OperatorKind, ApiError> {
538    use mlua_swarm::OperatorKind;
539    match s {
540        "main_ai" => Ok(OperatorKind::MainAi),
541        "composite" => Ok(OperatorKind::Composite),
542        "automate" => Ok(OperatorKind::Automate),
543        other => Err(ApiError::bad_request(format!(
544            "operator kind: unknown value '{other}' (expected main_ai|automate|composite)"
545        ))),
546    }
547}
548
549#[derive(Serialize)]
550struct FlowTasksResp {
551    final_ctx: Value,
552    bound_version: Option<String>,
553    /// Resolved TTL (seconds) actually applied to the run. Exposes the
554    /// 3-layer cascade (request body → BP metadata → server default) so
555    /// clients can verify which value took effect without re-deriving it.
556    effective_ttl_secs: u64,
557    ttl_source: TtlSource,
558    /// The `TaskRecord` minted for this request (issue #13 ID-hierarchy
559    /// persistence). `GET /v1/tasks/:id` re-fetches it; `POST
560    /// /v1/tasks/:id/runs` re-kicks it under a fresh `RunId`.
561    task_id: TaskId,
562    /// The `RunRecord` minted for this specific kick. `GET /v1/runs/:id`
563    /// re-fetches it (`step_entries` included).
564    run_id: RunId,
565}
566
567#[derive(Serialize, Clone, Copy, Debug, PartialEq, Eq)]
568#[serde(rename_all = "snake_case")]
569enum TtlSource {
570    RequestBody,
571    BpMetadata,
572    ServerDefault,
573}
574
575/// Unified `/v1/tasks` POST entry (= Flow form only).
576/// Runs `Blueprint.flow` to completion via flow eval in a single round-trip.
577/// One-shot tasks are also expressed as a 1-Step Blueprint. Operator
578/// (kind / spawn_hook / senior_bridge) can be injected per request body.
579/// `operator_sid` (S2, runtime Operator match stage 1) additionally
580/// lets the caller pin the task to a specific already-registered Operator
581/// session sid, bypassing BP-level alias lookup — see `FlowTasksReq` doc.
582async fn tasks_start(
583    State(state): State<AppState>,
584    Json(req): Json<FlowTasksReq>,
585) -> Result<Json<FlowTasksResp>, ApiError> {
586    let resp = run_flow_form(&state, req).await?;
587    Ok(Json(resp))
588}
589
590/// Flow-form path (= via `TaskApplication::handle_with_run`).
591/// Core handler behind the `/v1/tasks` entry (`tasks_start`).
592///
593/// Engine stateless-executor refactor: the per-request
594/// sub_engine + 3-registry propagate loop is retired; the startup-built
595/// `state.task_app` (= a `TaskLaunchService` wrap around `state.engine`) is
596/// used directly. The Operator callback IF (`spawn_hook_id` /
597/// `senior_bridge_id` / `operator_backend_id`) is registered on
598/// `state.engine.register_*` at WS connect time — the engine is the SoT.
599/// See the `operator_ws` module doc for details.
600async fn run_flow_form(state: &AppState, req: FlowTasksReq) -> Result<FlowTasksResp, ApiError> {
601    use mlua_swarm::application::{BlueprintRef as AppBlueprintRef, TaskApplicationInput};
602    use mlua_swarm::OperatorKind;
603
604    // Snapshot everything the TaskRecord needs before `req.blueprint` /
605    // `req.init_ctx` are moved into the dispatch path below.
606    let blueprint_ref_json = serde_json::to_value(&req.blueprint)
607        .map_err(|e| ApiError::bad_request(format!("blueprint snapshot: {e}")))?;
608    let input_ctx_snapshot = req.init_ctx.clone();
609    let goal = req.goal.clone().unwrap_or_default();
610
611    let mut op_req = req.operator.unwrap_or_default();
612
613    // S2: explicit `operator_sid` override (runtime Operator match stage 1).
614    // Resolved *before* building `operator_kind` / dispatching so an
615    // unknown sid fails fast with a 400, never silently falling back to the
616    // BP-level alias lookup. See `FlowTasksReq::operator_sid` doc for the
617    // disconnected-vs-unknown distinction.
618    if let Some(sid) = &req.operator_sid {
619        let known_ids = state.engine.list_operator_ids().await;
620        if !known_ids.iter().any(|id| id == sid) {
621            return Err(ApiError::bad_request(format!(
622                "operator_sid: no such registered operator session '{sid}'"
623            )));
624        }
625        op_req.operator_backend_id = Some(sid.clone());
626    }
627
628    // "Runtime Global" tier: `Some(_)` — including `Some(Automate)` — is
629    // always an explicit request that outranks the BP-level tiers; an
630    // absent/unset `kind` in the request body stays `None`, leaving the
631    // BP-level tiers (`OperatorDef.kind` / `Blueprint.default_operator_kind`)
632    // to decide instead of eagerly defaulting to `Automate`.
633    let operator_kind = op_req
634        .kind
635        .as_deref()
636        .map(parse_operator_kind_str)
637        .transpose()?;
638    let operator_id = op_req.id.unwrap_or_else(|| "http-run".to_string());
639    // "Runtime Agent-level" tier: per-agent overrides. Absent/empty = no
640    // override for any agent, letting the BP-level tiers decide per agent.
641    let mut operator_kind_overrides: HashMap<String, OperatorKind> = HashMap::new();
642    for (agent, kind_str) in op_req.per_agent_kinds.take().unwrap_or_default() {
643        operator_kind_overrides.insert(agent, parse_operator_kind_str(&kind_str)?);
644    }
645
646    let blueprint: AppBlueprintRef = match req.blueprint {
647        AppBlueprintRef::Inline { value } => AppBlueprintRef::Inline { value },
648        AppBlueprintRef::Id { id, version } => AppBlueprintRef::Id { id, version },
649    };
650
651    // TTL resolution cascade: (1) request body value, (2) BP metadata `default_run_ttl_secs`,
652    // (3) server global default (`default_run_ttl()`, 1800s).
653    let (ttl_secs, ttl_source) = match req.ttl_secs {
654        Some(v) => (v, TtlSource::RequestBody),
655        None => {
656            let (resolved_bp, _ver) = state
657                .task_app
658                .resolve(&blueprint)
659                .await
660                .map_err(|e| ApiError::bad_request(format!("bp resolve: {e}")))?;
661            match resolved_bp.metadata.default_run_ttl_secs {
662                Some(v) => (v, TtlSource::BpMetadata),
663                None => (default_run_ttl(), TtlSource::ServerDefault),
664            }
665        }
666    };
667
668    // issue #13 ID-hierarchy persistence: mint the work-item identity (Task)
669    // and this kick's identity (Run) *before* dispatching, so a Task/Run
670    // pair always exists even if the flow itself fails mid-way (the
671    // Failed-status paths below still have a row to update).
672    let task_id = TaskId::new();
673    let run_id = RunId::new();
674    let now = tasks::now_secs();
675    state
676        .task_store
677        .create(TaskRecord {
678            id: task_id.clone(),
679            goal,
680            blueprint_ref: blueprint_ref_json,
681            input_ctx: input_ctx_snapshot,
682            status: TaskRecordStatus::Running,
683            created_at: now,
684            updated_at: now,
685        })
686        .await
687        .map_err(ApiError::engine)?;
688    state
689        .run_store
690        .create(RunRecord {
691            id: run_id.clone(),
692            task_id: task_id.clone(),
693            status: RunStatus::Running,
694            step_entries: Vec::new(),
695            operator_sid: req.operator_sid.clone(),
696            result_ref: None,
697            created_at: now,
698            updated_at: now,
699        })
700        .await
701        .map_err(ApiError::engine)?;
702
703    let run_ctx = RunContext {
704        run_id: run_id.clone(),
705        run_store: state.run_store.clone(),
706    };
707    let outcome = state
708        .task_app
709        .handle_with_run(
710            TaskApplicationInput {
711                blueprint,
712                operator_id: operator_id.clone(),
713                role: Role::Operator,
714                ttl: Duration::from_secs(ttl_secs),
715                init_ctx: req.init_ctx,
716                operator_kind,
717                bridge_id: op_req.senior_bridge_id,
718                hook_id: op_req.spawn_hook_id,
719                operator_backend_id: op_req.operator_backend_id,
720                operator_kind_overrides,
721            },
722            Some(run_ctx),
723        )
724        .await;
725
726    let out = tasks::finalize_run(state, &task_id, &run_id, outcome)
727        .await
728        .map_err(|e| ApiError::bad_request(format!("run: {e}")))?;
729
730    Ok(FlowTasksResp {
731        final_ctx: out.final_ctx,
732        bound_version: out.bound_version.map(|v| format!("{:?}", v)),
733        effective_ttl_secs: ttl_secs,
734        ttl_source,
735        task_id,
736        run_id,
737    })
738}
739
740// ─── helpers ─────────────────────────────────────────────────────────────
741
742async fn take_session_token(state: &AppState, sid: &str) -> Result<CapToken, ApiError> {
743    // `sid` on this path is the token nonce itself (a bearer secret), so
744    // both the map key and the not-found diagnostic use its fingerprint
745    // (issue #14 — never echo the nonce back in an error body).
746    let key = mlua_swarm::types::token_fingerprint(sid);
747    state
748        .sessions
749        .lock()
750        .await
751        .map
752        .remove(&key)
753        .ok_or_else(|| ApiError::not_found(format!("session: fp={key}")))
754}
755
756/// Extracts sid from `Authorization: Bearer <sid>`. Strict — does not accept any other scheme prefix.
757fn extract_bearer(headers: &HeaderMap) -> Result<String, ApiError> {
758    let v = headers
759        .get(AUTHORIZATION)
760        .ok_or_else(|| ApiError::bad_request("missing Authorization header".into()))?
761        .to_str()
762        .map_err(|_| ApiError::bad_request("invalid Authorization header encoding".into()))?;
763    let sid = v
764        .strip_prefix("Bearer ")
765        .ok_or_else(|| ApiError::bad_request("Authorization must be 'Bearer <sid>'".into()))?
766        .trim();
767    if sid.is_empty() {
768        return Err(ApiError::bad_request("Bearer sid is empty".into()));
769    }
770    Ok(sid.to_string())
771}
772
773fn parse_role(s: &str) -> Result<Role, ApiError> {
774    match s.to_ascii_lowercase().as_str() {
775        "operator" => Ok(Role::Operator),
776        "worker" => Ok(Role::Worker),
777        "observer" => Ok(Role::Observer),
778        "senior" => Ok(Role::Senior),
779        other => Err(ApiError::bad_request(format!("unknown role: {other}"))),
780    }
781}
782
783// ─── error type ──────────────────────────────────────────────────────────
784
785/// Uniform error response type for the handlers in this module. Converts to
786/// a JSON `{"error": message}` body with the given status via [`IntoResponse`].
787#[derive(Debug)]
788pub struct ApiError {
789    status: StatusCode,
790    message: String,
791}
792
793impl ApiError {
794    /// Wraps an engine-side error as `500 Internal Server Error`.
795    pub fn engine(e: impl std::fmt::Display) -> Self {
796        Self {
797            status: StatusCode::INTERNAL_SERVER_ERROR,
798            message: format!("engine: {e}"),
799        }
800    }
801    /// Builds a `404 Not Found` with the given message.
802    pub fn not_found(m: String) -> Self {
803        Self {
804            status: StatusCode::NOT_FOUND,
805            message: m,
806        }
807    }
808    /// Builds a `400 Bad Request` with the given message.
809    pub fn bad_request(m: String) -> Self {
810        Self {
811            status: StatusCode::BAD_REQUEST,
812            message: m,
813        }
814    }
815}
816
817impl IntoResponse for ApiError {
818    fn into_response(self) -> Response {
819        (self.status, Json(json!({"error": self.message}))).into_response()
820    }
821}
822
823fn default_run_ttl() -> u64 {
824    // 1800s (= 30 min). Prevents op_token expiry across a flow.ir multi-step chain
825    // (= 5+ SubAgent dispatches at 30–60s each). Origin: the observed fvloop smoke
826    // where a post-gate mock-commit dispatch blew past 300s and expired — sibling of worker_token TTL.
827    1800
828}
829
830/// TTL cascade resolve helper (Blueprint metadata → server default fallback).
831/// Second-stage fallback, called when the POST `/v1/tasks` body does not set `ttl_secs`.
832/// (1) If BP metadata `default_run_ttl_secs` is `Some`, use it.
833/// (2) If `None`, fall back to the server global `default_run_ttl()` (1800s).
834///
835/// # Full cascade (combined in `run_flow_form`)
836///
837/// - request body `ttl_secs=Some(v)` → v (this helper is not called)
838/// - request body `None` + metadata `Some(v)` → v
839/// - request body `None` + metadata `None` → `default_run_ttl()` = 1800s
840#[cfg(test)]
841fn resolve_ttl_from_metadata(metadata_ttl: Option<u64>) -> u64 {
842    metadata_ttl.unwrap_or_else(default_run_ttl)
843}
844
845#[cfg(test)]
846mod tests {
847    use super::*;
848
849    /// TTL cascade case 1: when the request body sets it, that value is used as-is
850    /// (upper branch that does not go through the helper; semantic verify of the
851    /// `Some(v) => v` direct-return path in `run_flow_form`).
852    #[test]
853    fn ttl_cascade_request_body_wins_over_metadata() {
854        let req_ttl: Option<u64> = Some(100);
855        let metadata_ttl: Option<u64> = Some(3600);
856        let effective = match req_ttl {
857            Some(v) => v,
858            None => resolve_ttl_from_metadata(metadata_ttl),
859        };
860        assert_eq!(
861            effective, 100,
862            "request body ttl_secs=100 must win over metadata=3600 (cascade priority (1) > (2))"
863        );
864    }
865
866    /// TTL cascade case 2: request body omitted + BP metadata `Some(N)` → `N` is effective.
867    #[test]
868    fn ttl_cascade_metadata_used_when_body_missing() {
869        let req_ttl: Option<u64> = None;
870        let metadata_ttl: Option<u64> = Some(3600);
871        let effective = match req_ttl {
872            Some(v) => v,
873            None => resolve_ttl_from_metadata(metadata_ttl),
874        };
875        assert_eq!(
876            effective, 3600,
877            "body None + metadata=3600 must resolve to 3600 (cascade (2))"
878        );
879    }
880
881    /// TTL cascade case 3: request body omitted + BP metadata `None` → server default (1800s).
882    #[test]
883    fn ttl_cascade_server_default_when_both_missing() {
884        let req_ttl: Option<u64> = None;
885        let metadata_ttl: Option<u64> = None;
886        let effective = match req_ttl {
887            Some(v) => v,
888            None => resolve_ttl_from_metadata(metadata_ttl),
889        };
890        assert_eq!(
891            effective,
892            default_run_ttl(),
893            "body None + metadata None must fall back to default_run_ttl() = 1800s"
894        );
895        assert_eq!(effective, 1800, "default_run_ttl() literal = 1800s");
896    }
897
898    /// Helper unit: metadata `None` → 1800 (server default expansion).
899    #[test]
900    fn resolve_ttl_from_metadata_none_returns_server_default() {
901        assert_eq!(resolve_ttl_from_metadata(None), 1800);
902    }
903
904    /// Helper unit: metadata `Some(N)` → `N` (server default ignored).
905    #[test]
906    fn resolve_ttl_from_metadata_some_returns_value() {
907        assert_eq!(resolve_ttl_from_metadata(Some(7200)), 7200);
908        assert_eq!(resolve_ttl_from_metadata(Some(60)), 60);
909    }
910}