greentic-runner-host 1.2.2

Host runtime shim for Greentic runner: config, pack loading, activity handling
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
pub mod a2a_node;
pub mod a2a_pack_routes;
#[cfg(feature = "agentic-worker")]
pub(crate) mod a2a_pack_source;
pub mod adapt_events_email;
pub mod adapt_timer;
pub mod agent_node;
pub mod approval_http;
pub(crate) mod approval_token;
// Uses `GreenticLlmBackend`, which exists only with `greentic-llm-backend`.
#[cfg(all(feature = "agentic-worker", feature = "greentic-llm-backend"))]
pub(crate) mod artifact_reader_wiring;
#[cfg(feature = "agentic-worker")]
pub(crate) mod aw_backends;
pub mod card_nav;
pub mod component_invoker;
pub mod contract_cache;
pub mod contract_introspection;
pub mod dispatch_listener;
pub mod engine;
#[cfg(feature = "agentic-worker")]
pub(crate) mod run_context_policy;
pub mod run_context_routes;
#[cfg(feature = "agentic-worker")]
pub(crate) mod user_ledger_policy;
pub mod user_ledger_routes;
// `ext_llm_port` uses `greentic_llm::ProviderKind` directly (not just the
// agentic-worker types), and `greentic-llm` is an optional dependency pulled
// in only by the `greentic-llm-backend` feature — mirroring the gate on
// `agent_node::EnvLlmPort`, which this module wraps as tier 2.
#[cfg(all(feature = "agentic-worker", feature = "greentic-llm-backend"))]
pub(crate) mod ext_llm_port;
// Stores files an extension creates (`host.artifact.put`); public because
// greentic-start may construct `HttpArtifactPort` for a unit.
#[cfg(feature = "agentic-worker")]
pub mod ext_artifact_port;
pub mod flow_adapter;
#[cfg(feature = "agentic-worker")]
pub mod flow_invoker;
pub mod graph_node;
pub mod i18n;
pub mod invocation;
#[cfg(feature = "agentic-worker")]
pub mod knowledge_corpus;
#[cfg(feature = "agentic-worker")]
pub mod knowledge_ext;
#[cfg(feature = "agentic-worker")]
pub mod knowledge_index;
pub mod mcp_node;
pub mod mcp_pack_routes;
#[cfg(feature = "agentic-worker")]
pub mod mcp_warm_listener;
#[cfg(feature = "agentic-worker")]
pub mod media_node;
#[cfg(feature = "agentic-worker")]
pub mod media_render;
pub mod mocks;
pub mod nested_flow;
pub mod operala_node;
#[cfg(feature = "operala-in-process")]
pub mod operala_tools;
pub mod playbook_invoker;
pub mod playbook_turn;
// Bills an in-process deep worker's own reasoning-loop LLM calls.
#[cfg(feature = "operala-in-process")]
pub(crate) mod metered_llm;
pub mod operator;
#[cfg(feature = "agentic-worker")]
pub mod pack_extensions;
pub mod remote_dispatch;
#[cfg(feature = "agentic-worker")]
pub mod runtime_ext;
pub mod runtime_session_resumer;
pub mod schema_validator;
#[cfg(feature = "agentic-worker")]
pub(crate) mod sorla_node;
pub mod sorla_pack_routes;
#[cfg(feature = "agentic-worker")]
pub(crate) mod sorla_pack_source;
#[cfg(feature = "agentic-worker")]
pub mod sorla_route;
#[cfg(feature = "agentic-worker")]
pub mod sorx_invoker;
pub mod templating;

use std::net::SocketAddr;
use std::sync::Arc;

use anyhow::Result;
use axum::response::IntoResponse as _;
use axum::routing::{get, post};
use axum::{Router, serve};
use tokio::net::TcpListener;

use crate::host::RunnerHost;
use crate::http::{self, admin, auth::AdminAuth, health::HealthState};
use crate::routing::TenantRouting;
use crate::runtime::ActivePacks;
use crate::sql::SqlGateway;
use crate::watcher::PackReloadHandle;

pub struct HostServer {
    addr: SocketAddr,
    router: Router,
    _state: ServerState,
}

impl HostServer {
    pub fn new(
        port: u16,
        active: Arc<ActivePacks>,
        routing: TenantRouting,
        health: Arc<HealthState>,
        reload: Option<PackReloadHandle>,
        admin: AdminAuth,
        host: Arc<RunnerHost>,
    ) -> Result<Self> {
        Self::with_sql(port, active, routing, health, reload, admin, host, None)
    }

    /// Like [`HostServer::new`] but wires an optional [`SqlGateway`] into the
    /// server state.  When `sql_gateway` is `None` the server uses an empty
    /// gateway that returns 404/401 for all `/sql` routes — safe by default.
    // Builder param set mirrors the existing fields plus `host`; a config-struct
    // refactor is deferred. See B0 plan.
    #[allow(clippy::too_many_arguments)]
    pub fn with_sql(
        port: u16,
        active: Arc<ActivePacks>,
        routing: TenantRouting,
        health: Arc<HealthState>,
        reload: Option<PackReloadHandle>,
        admin: AdminAuth,
        host: Arc<RunnerHost>,
        sql_gateway: Option<SqlGateway>,
    ) -> Result<Self> {
        let addr = SocketAddr::from(([0, 0, 0, 0], port));
        let sql = sql_gateway
            .unwrap_or_else(|| SqlGateway::new(std::collections::HashMap::new(), String::new()));
        let state = ServerState {
            active,
            routing,
            health,
            reload,
            admin,
            // Clone off `host` (not a fresh registry): the SSE stream
            // handler (writer) and `RuntimeAgentNodeHandler::execute`
            // (reader, wired in at `TenantRuntime` construction) must share
            // the exact same `Arc<DashMap<..>>` or a registration here would
            // never be seen by the agent step.
            #[cfg(feature = "agentic-worker")]
            stream_observers: host.stream_observers(),
            // Built here rather than reused from `host`: the per-tenant runtimes
            // are constructed later, inside `TenantRuntime`, with per-tenant
            // secrets. This blocks boot on a full extra set of WASM loads,
            // landing entirely in the pre-bind window — `/healthz` cannot answer
            // at all until this returns. Measured: ~80s to readiness with 81
            // extensions installed, on top of whatever the per-tenant load
            // already costs. A deployment health-gate must tolerate that delay.
            //
            // No packs are passed: pack-carried extensions are per-tenant, so
            // there is no process-wide answer for them (see the field's doc
            // comment).
            #[cfg(feature = "agentic-worker")]
            ext_runtime: crate::runner::agent_node::build_ext_runtime(
                std::sync::Arc::new(crate::runner::agent_node::EnvSecretsBackend),
                None,
                None,
                // Process-level path: no embedding host, so no artifact port.
                None,
                &[],
            ),
            host,
            sql,
        };
        let router = router(state.clone());
        Ok(Self {
            addr,
            router,
            _state: state,
        })
    }

    pub async fn serve(self) -> Result<()> {
        self.serve_with_shutdown(std::future::pending::<()>()).await
    }

    /// Like [`serve`](Self::serve), but stops accepting connections and lets
    /// in-flight requests finish once `shutdown` resolves.
    pub async fn serve_with_shutdown<F>(self, shutdown: F) -> Result<()>
    where
        F: std::future::Future<Output = ()> + Send + 'static,
    {
        tracing::info!(addr = %self.addr, "starting host server");
        if !self._state.admin.operator_protected() {
            tracing::warn!(
                addr = %self.addr,
                "POST /operator/op/invoke is UNAUTHENTICATED and bound to {}: set OPERATOR_TOKEN \
                 (or ADMIN_TOKEN) to require a bearer token",
                self.addr
            );
        }
        let listener = TcpListener::bind(self.addr).await?;
        serve(
            listener,
            self.router
                .into_make_service_with_connect_info::<SocketAddr>(),
        )
        .with_graceful_shutdown(shutdown)
        .await?;
        Ok(())
    }
}

/// Assemble the full host router for `state`.
///
/// Extracted from [`HostServer::with_sql`] so tests can drive the *assembled*
/// router — route registration included — without binding a socket. Mirrors the
/// `sql::routes::router` precedent.
pub(crate) fn router(state: ServerState) -> Router {
    with_request_timeout(
        base_router(state),
        request_timeout_from_raw(std::env::var(REQUEST_TIMEOUT_ENV).ok().as_deref()),
    )
}

/// Per-request wall-clock limit in seconds for every route except the
/// [`LONG_RUNNING_PATHS`]. `0` disables.
pub(crate) const REQUEST_TIMEOUT_ENV: &str = "GREENTIC_HTTP_REQUEST_TIMEOUT_SECS";
const DEFAULT_REQUEST_TIMEOUT_SECS: u64 = 60;
/// Routes that legitimately stay open longer than the request timeout because
/// their work has its own deadline: the agent loop (graceful termination, state
/// save, lock release must not be pre-empted by a 408) and the component
/// invocation (`GREENTIC_WASM_MAX_EXEC_SECS`; a 408 plus a client retry could
/// repeat a side effect).
const LONG_RUNNING_PATHS: &[&str] = &["/agent/chat", "/agent/chat/stream", "/operator/op/invoke"];

/// Whether `path` is exempt from the request timeout.
pub(crate) fn is_long_running_path(path: &str) -> bool {
    LONG_RUNNING_PATHS.contains(&path)
}

/// `None` = disabled. Absent or unparseable falls back to the default: a
/// malformed knob must not silently remove the limit.
pub(crate) fn request_timeout_from_raw(raw: Option<&str>) -> Option<std::time::Duration> {
    let secs = raw
        .and_then(|v| v.trim().parse::<u64>().ok())
        .unwrap_or(DEFAULT_REQUEST_TIMEOUT_SECS);
    (secs > 0).then(|| std::time::Duration::from_secs(secs))
}

/// Wrap `router` so a request not answered within `timeout` gets a 408.
/// (`tower-http` is not a dependency; this is the same behaviour as its
/// `TimeoutLayer`, with the long-running routes exempt.)
pub(crate) fn with_request_timeout(router: Router, timeout: Option<std::time::Duration>) -> Router {
    let Some(timeout) = timeout else {
        return router;
    };
    router.layer(axum::middleware::from_fn(
        move |req: axum::extract::Request, next: axum::middleware::Next| async move {
            if is_long_running_path(req.uri().path()) {
                return next.run(req).await;
            }
            match tokio::time::timeout(timeout, next.run(req)).await {
                Ok(response) => response,
                Err(_) => axum::http::StatusCode::REQUEST_TIMEOUT.into_response(),
            }
        },
    ))
}

fn base_router(state: ServerState) -> Router {
    // `/operator/op/invoke` is guarded by the operator/admin bearer token when
    // one is configured; with none it stays open (see `warn_if_operator_open`).
    let operator_routes = Router::new()
        .route("/operator/op/invoke", post(operator::invoke))
        .route_layer(axum::middleware::from_fn_with_state(
            state.clone(),
            crate::http::auth::require_operator,
        ));
    let router = Router::new()
        .merge(operator_routes)
        .route("/healthz", get(http::health::handler))
        .route("/admin/packs/status", get(admin::status))
        .route("/admin/packs/reload", post(admin::reload))
        .route("/agent/chat", post(crate::http::agent_chat::agent_chat));
    #[cfg(feature = "agentic-worker")]
    let router = router
        .route(
            "/agent/chat/stream",
            post(crate::http::agent_chat::agent_chat_stream),
        )
        .route("/admin/capabilities", get(admin::capabilities));
    router
        .route(
            "/sql/{conn}/schema",
            get(crate::sql::routes::schema_handler),
        )
        .route("/sql/{conn}/query", post(crate::sql::routes::query_handler))
        .with_state(state)
}

#[derive(Clone)]
pub struct ServerState {
    pub active: Arc<ActivePacks>,
    pub routing: TenantRouting,
    pub health: Arc<HealthState>,
    pub reload: Option<PackReloadHandle>,
    pub admin: AdminAuth,
    /// The runner host instance used by the `POST /agent/chat` handler to
    /// dispatch activity turns to loaded worker packs.
    pub host: Arc<RunnerHost>,
    /// SQL gateway for `/sql/{conn}/schema` and `/sql/{conn}/query`.
    /// Defaults to an empty gateway (returns 404/401 for all connections)
    /// when no SQL connections are configured.
    pub sql: SqlGateway,
    /// Session-id → active streaming observer (R2). Cloned from
    /// `host.stream_observers()` at server-build time so it is the exact
    /// same registry `RuntimeAgentNodeHandler::execute` reads from — a
    /// `POST /agent/chat/stream` handler inserts an observer here before
    /// dispatching a turn.
    #[cfg(feature = "agentic-worker")]
    pub stream_observers: crate::http::agent_stream::StreamObserverRegistry,
    /// Extension runtime backing `GET /admin/capabilities`, so an operator
    /// console can see which capabilities this runner actually has installed.
    ///
    /// Built once at server-build time. This is a *separate* instance from the
    /// per-tenant runtimes in `agent_node::build_ext_runtime`, which need
    /// per-tenant secrets backends — so it costs one extra set of WASM loads at
    /// boot. All tenants scan the same `GREENTIC_EXTENSIONS_DIR/design/`, so a
    /// process-level answer is correct for the ON-DISK half.
    ///
    /// It is NOT correct for the pack-carried half: extensions travelling inside
    /// a `.gtpack` (`crate::runner::pack_extensions`) belong to the tenant whose
    /// pack carries them, so this instance is built with no packs and reports
    /// only what the host has installed. An operator reading
    /// `GET /admin/capabilities` sees the host's floor, not any one tenant's
    /// total.
    ///
    /// `None` only when `ExtensionRuntime::new` itself fails. A missing/absent
    /// extension directory does NOT produce `None`: `scan_kind_dir` errors,
    /// logs a warning, and the runtime still comes back `Some` with an empty
    /// registry (`agent_node.rs:918-948`). Either way the handler reports an
    /// empty list rather than failing.
    #[cfg(feature = "agentic-worker")]
    pub ext_runtime: Option<std::sync::Arc<greentic_ext_runtime::ExtensionRuntime>>,
}

impl ServerState {
    /// Test-only builder: an empty host (`RunnerHost::for_test`, no loaded
    /// packs), default routing, and — when `agentic-worker` is enabled — an
    /// empty streaming-observer registry cloned from the same host. Mirrors
    /// the inline `state()` test helpers in `http/admin.rs` / `http/auth.rs`
    /// / `http/health.rs`, but lives here (next to the struct) so it's
    /// reusable from `http/agent_chat.rs`'s SSE core test.
    // Consumed by the `agentic-worker`-gated SSE core test in
    // `http/agent_chat.rs` and by `router_tests` in this file — gating on both
    // keeps a lean (no `agentic-worker`) test build free of dead-code warnings.
    #[cfg(all(test, feature = "agentic-worker"))]
    pub(crate) fn for_test() -> Self {
        let host = RunnerHost::for_test();
        Self {
            active: Arc::new(ActivePacks::new()),
            routing: TenantRouting::new(crate::routing::RoutingConfig::default()),
            health: Arc::new(HealthState::new()),
            reload: None,
            admin: AdminAuth::default(),
            #[cfg(feature = "agentic-worker")]
            stream_observers: host.stream_observers(),
            #[cfg(feature = "agentic-worker")]
            ext_runtime: None,
            host,
            sql: SqlGateway::new(std::collections::HashMap::new(), String::new()),
        }
    }
}

impl axum::extract::FromRef<ServerState> for SqlGateway {
    fn from_ref(state: &ServerState) -> Self {
        state.sql.clone()
    }
}

#[cfg(test)]
mod request_timeout_tests {
    use super::*;
    use axum::body::Body;
    use axum::http::{Request, StatusCode};
    use std::time::Duration;
    use tower::ServiceExt as _;

    #[test]
    fn timeout_env_resolution() {
        assert_eq!(
            request_timeout_from_raw(None),
            Some(Duration::from_secs(60))
        );
        assert_eq!(
            request_timeout_from_raw(Some("5")),
            Some(Duration::from_secs(5))
        );
        assert_eq!(request_timeout_from_raw(Some("0")), None);
        assert_eq!(
            request_timeout_from_raw(Some("junk")),
            Some(Duration::from_secs(60))
        );
    }

    fn slow_app(timeout: Option<Duration>) -> Router {
        let slow = || async {
            tokio::time::sleep(Duration::from_millis(400)).await;
            "done"
        };
        let app = Router::new()
            .route("/slow", get(slow))
            .route("/agent/chat", get(slow))
            .route("/agent/chat/stream", get(slow))
            .route("/operator/op/invoke", get(slow))
            .route("/admin/packs/status", get(slow));
        with_request_timeout(app, timeout)
    }

    async fn status(app: Router, path: &str) -> Result<StatusCode> {
        let req = Request::builder().uri(path).body(Body::empty())?;
        Ok(app.oneshot(req).await?.status())
    }

    #[tokio::test]
    async fn slow_handler_times_out_with_408() -> Result<()> {
        let app = slow_app(Some(Duration::from_millis(50)));
        assert_eq!(status(app, "/slow").await?, StatusCode::REQUEST_TIMEOUT);
        Ok(())
    }

    #[tokio::test]
    async fn long_running_routes_are_exempt() -> Result<()> {
        for path in ["/agent/chat", "/agent/chat/stream", "/operator/op/invoke"] {
            let app = slow_app(Some(Duration::from_millis(50)));
            assert_eq!(status(app, path).await?, StatusCode::OK, "{path}");
            assert!(is_long_running_path(path));
        }
        Ok(())
    }

    #[tokio::test]
    async fn admin_route_is_not_exempt() -> Result<()> {
        let app = slow_app(Some(Duration::from_millis(50)));
        assert_eq!(
            status(app, "/admin/packs/status").await?,
            StatusCode::REQUEST_TIMEOUT
        );
        assert!(!is_long_running_path("/admin/packs/status"));
        assert!(!is_long_running_path("/healthz"));
        Ok(())
    }

    #[tokio::test]
    async fn disabled_timeout_lets_slow_handlers_finish() -> Result<()> {
        assert_eq!(status(slow_app(None), "/slow").await?, StatusCode::OK);
        Ok(())
    }
}

#[cfg(all(test, feature = "agentic-worker"))]
mod router_tests {
    use super::*;
    use axum::body::Body;
    use axum::extract::ConnectInfo;
    use axum::http::{Request, StatusCode};
    use tower::ServiceExt as _;

    /// `AdminGuard` 500s without `ConnectInfo`; `oneshot` does not supply it.
    fn loopback() -> ConnectInfo<SocketAddr> {
        ConnectInfo("127.0.0.1:8080".parse::<SocketAddr>().unwrap())
    }

    async fn operator_status(
        admin: crate::http::auth::AdminAuth,
        bearer: Option<&str>,
    ) -> StatusCode {
        let mut state = ServerState::for_test();
        state.admin = admin;
        let mut req = Request::builder()
            .method("POST")
            .uri("/operator/op/invoke")
            .extension(loopback());
        if let Some(b) = bearer {
            req = req.header("authorization", format!("Bearer {b}"));
        }
        router(state)
            .oneshot(req.body(Body::empty()).unwrap())
            .await
            .unwrap()
            .status()
    }

    #[tokio::test]
    async fn operator_invoke_requires_token_when_configured() {
        let admin =
            crate::http::auth::AdminAuth::default().with_operator_token(Some("op-secret".into()));
        assert_eq!(
            operator_status(admin.clone(), None).await,
            StatusCode::UNAUTHORIZED
        );
        assert_eq!(
            operator_status(admin.clone(), Some("wrong")).await,
            StatusCode::UNAUTHORIZED
        );
        // Right token passes the layer; the handler then answers (not 401).
        assert_ne!(
            operator_status(admin, Some("op-secret")).await,
            StatusCode::UNAUTHORIZED
        );
    }

    #[tokio::test]
    async fn operator_invoke_open_without_token() {
        assert_ne!(
            operator_status(crate::http::auth::AdminAuth::default(), None).await,
            StatusCode::UNAUTHORIZED
        );
    }

    #[tokio::test]
    async fn assembled_router_serves_admin_packs_status() {
        let app = router(ServerState::for_test());
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/admin/packs/status")
                    .extension(loopback())
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
    }

    /// Anti-regression for the greentic-designer #796 class of bug: a handler
    /// that exists but is never registered. Without the `.route(...)` line this
    /// returns 404.
    #[tokio::test]
    async fn assembled_router_serves_admin_capabilities() {
        let app = router(ServerState::for_test());
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/admin/capabilities")
                    .extension(loopback())
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);

        let body = http_body_util::BodyExt::collect(response.into_body())
            .await
            .unwrap()
            .to_bytes();
        let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
        // `ServerState::for_test()` has no ext_runtime, so the list is empty —
        // but the envelope key must still be present and an array.
        assert_eq!(body, serde_json::json!({ "capabilities": [] }));
    }
}