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