Skip to main content

trusty_code/serve/
http.rs

1//! HTTP JSON-RPC 2.0 transport for `tcode serve --http` (#2053, #2054).
2//!
3//! Why: matches how `trusty-memory` (`web::router` + `run_http_on`) and
4//! `trusty-search` (`service::server::build_router`) stand up their axum
5//! daemons: a pure `axum::Router` builder — testable via `oneshot`, no real
6//! socket — wrapped in the shared guarded middleware stack
7//! (`trusty_common::server::with_guarded_middleware_same_origin_cors`, #6003),
8//! plus a bind+serve entry point that installs the
9//! shared `trusty_common::shutdown_signal()` graceful-shutdown watcher
10//! (SIGTERM + SIGINT), exactly like `trusty-memory`'s `run_http_on`. `POST
11//! /rpc` and `GET /health` dispatch through the SAME [`crate::jsonrpc::Router`]
12//! the STDIO transport (`crate::serve::transport`) uses via
13//! [`Router::dispatch_json`] — there is exactly one implementation of each
14//! method (`ping`, `health`, `session.*`, …), not one per transport.
15//!
16//! #2054 adds `GET /sessions/{id}/events`: an SSE route that is HTTP's real
17//! live-streaming mechanism for `session.attach`. HTTP `POST /rpc` is
18//! fundamentally one request/one response, so `session.attach` over HTTP
19//! acknowledges immediately (replay burst + this endpoint's URL in
20//! `stream_url`) rather than holding the connection open — a browser or CLI
21//! client then opens this endpoint to receive the ring-buffer replay
22//! followed by live events, and simply closing that connection IS "detach"
23//! for HTTP (there is nothing further to call). See
24//! `crate::jsonrpc::ConnectionContext`'s docs and `session::protocol::attach`
25//! for the full STDIO-vs-HTTP rationale. Multi-client attach falls out for
26//! free here: every `GET` gets its own `crate::events::subscribe()`
27//! receiver.
28//!
29//! What: [`build_axum_router`] (pure, unit-testable) and [`run_http`] (binds
30//! a `TcpListener` — port `0` yields an OS-assigned ephemeral port — logs
31//! the bound address to stderr, never stdout, and serves until graceful
32//! shutdown).
33//!
34//! Deferred: batch JSON-RPC requests (a JSON array body) are not supported —
35//! `POST /rpc` accepts a single request object per call, matching what the
36//! ticket asked for ("single-request is fine for now").
37//!
38//! Test: `http::tests::*` drive [`build_axum_router`] via
39//! `tower::util::ServiceExt::oneshot` (no real socket): `POST /rpc` ping
40//! success, `POST /rpc` malformed JSON -> `-32700`, `GET /health`,
41//! `session.create` + `GET /sessions/{id}/events` SSE replay + live event.
42
43use std::convert::Infallible;
44use std::net::SocketAddr;
45use std::sync::Arc;
46
47use anyhow::{Context, Result};
48use axum::{
49    Json, Router as AxumRouter,
50    body::Bytes,
51    extract::{Path, State},
52    response::sse::{Event as SseEvent, KeepAlive, Sse},
53    routing::{get, post},
54};
55use futures_util::{Stream, StreamExt, stream};
56use tokio::net::TcpListener;
57use tokio::sync::mpsc;
58use tokio_stream::wrappers::BroadcastStream;
59use tracing::info;
60use trusty_common::server::SelfOrigins;
61use trusty_mcp::Response;
62
63use crate::binding::ProjectBinding;
64use crate::jsonrpc::{ConnectionContext, Router};
65use crate::serve::methods::health_payload;
66use crate::serve::rest;
67use crate::session::SessionRegistry;
68use crate::workstreams::SharedWorkstreamStore;
69
70/// Shared axum state: the JSON-RPC router (for `POST /rpc`), the session
71/// registry (for the SSE route, which reads it directly rather than going
72/// through the router), and the daemon's project binding (for `GET /health`).
73///
74/// Why: every field is an `Arc` so cloning per-request (axum requires
75/// `State` to be `Clone`) is cheap and every route sees the same daemon-wide
76/// instances. `binding` is here rather than resolved per request because a
77/// daemon binds exactly ONE project for its whole life — that immutability
78/// is precisely what makes it worth publishing on `/health` (#4512).
79#[derive(Clone)]
80struct HttpState {
81    router: Arc<Router>,
82    sessions: Arc<SessionRegistry>,
83    binding: Arc<ProjectBinding>,
84}
85
86/// Build the pure axum router (no listener bound) exposing `POST /rpc`,
87/// `GET /health`, `GET /sessions/{id}/events`, and (#2983 Slice 2 + Slice 3)
88/// the full `/sessions*` REST resource group.
89///
90/// Why: kept separate from [`run_http`] so unit tests exercise routing and
91/// dispatch via `tower::util::ServiceExt::oneshot` without opening a real
92/// socket, and so the shared guarded middleware stack wraps it identically to
93/// trusty-agents/trusty-memory/trusty-search.
94///
95/// #6003: the stack is
96/// `trusty_common::server::with_guarded_middleware_same_origin_cors`, not the
97/// permissive `with_standard_middleware` this router used to call. Two things
98/// change. `guard_write_origin` runs router-wide and innermost, so a browser
99/// POST/PUT/PATCH/DELETE carrying a foreign `Origin` is `403`ed before any
100/// handler runs — `POST /rpc` (the whole JSON-RPC method surface), `/tasks`,
101/// `/sessions`, `/sessions/{id}/messages`, `/agents`, and the `workstream.*`
102/// write routes. And the CORS policy reflects only same-machine origins
103/// instead of `Any`, so a page on a foreign origin cannot READ
104/// `GET /sessions/{id}/transcript` or either SSE stream either — those are
105/// `GET`, which the method-gated guard deliberately lets through, and they
106/// carry conversation content. Callers that send no `Origin` at all (the
107/// `tcode tui` client, the console reverse proxy, `curl`) are untouched: the
108/// guard passes an absent `Origin` through, and CORS is browser-enforced.
109/// What: `POST /rpc` dispatches the request body through
110/// `Router::dispatch_json` (shared with the STDIO transport); `GET /health`
111/// returns [`health_payload`]; `GET /sessions/{id}/events` streams that
112/// session's ring-buffer replay then live events as SSE; `crate::serve::rest`
113/// merges in the `session.*` REST read routes (`GET /sessions`,
114/// `GET /sessions/{id}`, `.../transcript`, `.../readiness`, `.../goals`,
115/// (issue #3015) `.../budget`),
116/// (Slice 3) the write routes (`POST /sessions`,
117/// `POST /sessions/{id}/messages`, `POST /sessions/{id}/cancel`,
118/// `PUT`/`DELETE /sessions/{id}/goal`), (Slice 4) `POST /tasks`, (Slice 5)
119/// `GET /fs`, (Slice 6) `GET /sessions/{id}/agents`, (Slice 7, issue #3072)
120/// `GET /sessions/{id}/search-audit`, and the full `workstream.*` REST
121/// surface: `POST /workstreams`, `GET /workstreams/{id}`, `GET /workstreams`,
122/// `POST /workstreams/{id}/close` (issue #3295) plus
123/// `POST /workstreams/{id}/activate`/`.../deactivate` (DOC-48 §5.2, issue
124/// #3294) — plus (issue #3297) `GET /workstreams/{id}/events` (the
125/// workstream-level SSE aggregation route, `crate::workstreams::sse::routes`)
126/// — plus (issue #3449) `GET`/`POST /agents`, `DELETE /agents/{name}` and the
127/// `skills` twin (the Foundry GUI's Agents/Skills management tabs,
128/// `rest::agent_catalog`/`rest::skill_catalog`) — none of which collide with
129/// the paths registered directly on this router or with each other.
130/// Test: `http_rpc_ping_returns_pong`,
131/// `http_rpc_malformed_json_returns_parse_error`,
132/// `http_health_matches_jsonrpc_health_payload`,
133/// `http_session_events_sse_streams_replay_then_live_event`,
134/// `http_rest_sessions_route_is_merged_in`,
135/// `http_rest_post_sessions_route_is_merged_in`,
136/// `http_rest_post_tasks_route_is_merged_in`,
137/// `http_rest_get_fs_route_is_merged_in`,
138/// `http_rest_get_session_agents_route_is_merged_in`,
139/// `http_rest_get_session_budget_route_is_merged_in`,
140/// `http_rest_get_session_search_audit_route_is_merged_in`,
141/// `http_rest_get_workstreams_route_is_merged_in` (also pins the
142/// `GET /workstreams/{id}/events` merge),
143/// `http_rest_get_projects_route_is_merged_in`,
144/// `http_rest_get_agent_and_skill_catalog_routes_are_merged_in`;
145/// the #6003 guard arms live in `http_origin_guard_tests`.
146pub fn build_axum_router(
147    router: Arc<Router>,
148    sessions: Arc<SessionRegistry>,
149    workstreams: SharedWorkstreamStore,
150    binding: Arc<ProjectBinding>,
151) -> AxumRouter {
152    let state = HttpState {
153        router: router.clone(),
154        sessions,
155        binding,
156    };
157    let core = AxumRouter::new()
158        .route("/rpc", post(rpc_handler))
159        .route("/health", get(health_handler))
160        .route("/sessions/{id}/events", get(session_events_sse))
161        .with_state(state);
162    let app = core
163        .merge(rest::sessions::routes(router.clone()))
164        .merge(rest::sessions_write::routes(router.clone()))
165        .merge(rest::tasks::routes(router.clone()))
166        .merge(rest::fs::routes(router.clone()))
167        .merge(rest::projects::routes(router.clone()))
168        .merge(rest::agents::routes(router.clone()))
169        .merge(rest::agent_catalog::routes(router.clone()))
170        .merge(rest::skill_catalog::routes(router.clone()))
171        .merge(rest::search_audit::routes(router.clone()))
172        .merge(rest::workstreams::routes(router))
173        .merge(crate::workstreams::sse::routes(workstreams));
174    // #6003: the daemon binds loopback only (`run_http`), so the guard needs no
175    // bind-derived allowlist — `SelfOrigins::default()` trusts loopback and
176    // nothing else.
177    trusty_common::server::with_guarded_middleware_same_origin_cors(app, SelfOrigins::default())
178}
179
180/// `POST /rpc` — JSON-RPC 2.0 dispatch endpoint.
181///
182/// Why: lets browser clients, curl, and any HTTP-only caller reach the same
183/// method surface the STDIO transport exposes, without learning a REST
184/// vocabulary per method.
185/// What: builds a throwaway [`ConnectionContext`] for this one call (its
186/// `notify` receiver is dropped once this function returns, so any handler
187/// that queued a notification via it — e.g. `session.attach`'s forwarder —
188/// simply stops on its next send; the real HTTP live-streaming path is
189/// `GET /sessions/{id}/events`, not this channel), then dispatches the raw
190/// request body through `Router::dispatch_json` (single request per call —
191/// batch/array bodies are not supported, see module docs). Always returns
192/// HTTP 200; JSON-RPC errors, including malformed JSON (mapped to
193/// `-32700`), are carried in the response envelope's `error` field rather
194/// than the HTTP status.
195/// Test: `http_rpc_ping_returns_pong`, `http_rpc_malformed_json_returns_parse_error`.
196async fn rpc_handler(State(state): State<HttpState>, body: Bytes) -> Json<Response> {
197    let (notify_tx, _notify_rx) = mpsc::unbounded_channel();
198    let ctx = ConnectionContext::new(notify_tx);
199    Json(state.router.dispatch_json(&body, &ctx).await)
200}
201
202/// `GET /health` — liveness probe matching the `health` JSON-RPC method.
203///
204/// Why: the ecosystem convention (trusty-search, trusty-memory) is an
205/// unauthenticated `GET /health`; trusty-console's gateway polls it to
206/// confirm a daemon is alive. Reusing [`health_payload`] — the exact
207/// function the `health` JSON-RPC method calls — keeps the two transports
208/// from drifting into two different health shapes.
209///
210/// #4512: this is also the route `tcode tui`'s auto-attach reads the
211/// daemon's `binding` from before deciding whether attaching would put it on
212/// the wrong project, which is why the handler now needs `State`.
213/// What: always returns HTTP 200 with
214/// `{"server","version","status","pid","binding"}`.
215/// Test: `http_health_matches_jsonrpc_health_payload`,
216/// `http_health_reports_the_daemons_project_binding`.
217async fn health_handler(State(state): State<HttpState>) -> Json<serde_json::Value> {
218    Json(health_payload(&state.binding))
219}
220
221/// `GET /sessions/{id}/events` — Server-Sent Events stream of a session's
222/// ring-buffer replay followed by its live events.
223///
224/// Why: HTTP's real live-streaming mechanism for `session.attach` (see
225/// module docs for why `POST /rpc` itself can't hold the stream open).
226/// Multiple concurrent `GET`s against the same session id each get their
227/// own subscription (multi-client attach, vision spec Axiom 4) — no extra
228/// bookkeeping needed because `crate::events::subscribe()` already hands
229/// out an independent `broadcast::Receiver` per call.
230/// What: 404 with a JSON-RPC error envelope if the session id is unknown
231/// (`SessionRegistry::replay` -> `session_not_found`, spec-mapped HTTP
232/// status per §13.2). Otherwise: an SSE stream that first emits the
233/// ring-buffer replay (oldest-first) then chains the live bus, filtered to
234/// this `session_id`, forever (until the client disconnects — which is
235/// "detach" for HTTP).
236/// Test: `http_session_events_sse_streams_replay_then_live_event`,
237/// `http_session_events_sse_unknown_session_returns_404`.
238async fn session_events_sse(
239    State(state): State<HttpState>,
240    Path(session_id): Path<String>,
241) -> Result<
242    Sse<impl Stream<Item = Result<SseEvent, Infallible>>>,
243    (axum::http::StatusCode, Json<Response>),
244> {
245    let replay = state.sessions.replay(&session_id).map_err(|e| {
246        let body = Response::err(None, e.code, e.message);
247        (axum::http::StatusCode::NOT_FOUND, Json(body))
248    })?;
249
250    let replay_stream = stream::iter(
251        replay
252            .into_iter()
253            .map(|envelope| Ok(sse_event_for(&envelope))),
254    );
255
256    let filter_id = session_id.clone();
257    let live_stream = BroadcastStream::new(crate::events::subscribe()).filter_map(move |item| {
258        let filter_id = filter_id.clone();
259        async move {
260            match item {
261                Ok(envelope) if envelope.session_id == filter_id => {
262                    Some(Ok(sse_event_for(&envelope)))
263                }
264                _ => None,
265            }
266        }
267    });
268
269    Ok(Sse::new(replay_stream.chain(live_stream)).keep_alive(KeepAlive::default()))
270}
271
272/// Serialise one `crate::events::SessionEventEnvelope` as an SSE `data:`
273/// frame.
274///
275/// Why: centralises the (practically infallible — the envelope has no
276/// untagged maps or non-string keys) JSON encoding so `session_events_sse`
277/// doesn't repeat the fallback logic at two call sites. Sending the full
278/// envelope (not just the bare `event`) means the HTTP SSE transport carries
279/// exactly the same `session_id`/`seq`/`at`/`kind`/`event` shape the STDIO
280/// `session.event` notification does (#2055 requirement: both transports
281/// carry the full taxonomy with the envelope).
282/// What: `SseEvent::default().json_data(envelope)`, falling back to an empty
283/// JSON object on the (unreachable in practice) serialisation error rather
284/// than `unwrap`ing.
285fn sse_event_for(envelope: &crate::events::SessionEventEnvelope) -> SseEvent {
286    SseEvent::default()
287        .json_data(envelope)
288        .unwrap_or_else(|_| SseEvent::default().data("{}"))
289}
290
291/// Bind a `TcpListener` and serve `POST /rpc` + `GET /health` +
292/// `GET /sessions/{id}/events` until SIGTERM/SIGINT (graceful) or an
293/// internal axum error.
294///
295/// Why: the top-level entry point `crate::serve::run_http` delegates to this
296/// once the router and session registry are assembled.
297/// What: binds `127.0.0.1:port` (`port = 0` lets the OS assign an ephemeral
298/// port), logs the real bound address to stderr — mirroring
299/// `trusty-memory`'s `run_http_on`, and never touching stdout — then serves
300/// with `trusty_common::shutdown_signal()` installed via
301/// `with_graceful_shutdown`: SIGTERM/SIGINT stop new connections and drain
302/// in-flight requests before this function returns (issue #534 convention).
303/// Test: not directly unit-tested (would require a real socket + a real
304/// signal); [`build_axum_router`]'s tests cover the routing/dispatch logic
305/// this serves.
306pub async fn run_http(
307    router: Router,
308    sessions: Arc<SessionRegistry>,
309    workstreams: SharedWorkstreamStore,
310    port: u16,
311    // #4512: published on `GET /health` so an auto-attaching client can tell
312    // WHICH project this daemon serves before it starts driving it.
313    binding: Arc<ProjectBinding>,
314) -> Result<()> {
315    let addr = SocketAddr::from(([127, 0, 0, 1], port));
316    let listener = TcpListener::bind(addr)
317        .await
318        .with_context(|| format!("tcode serve --http: bind {addr}"))?;
319    let bound = listener
320        .local_addr()
321        .context("tcode serve --http: read bound local address")?;
322    info!("tcode serve --http: listening on http://{bound}");
323    eprintln!("tcode serve --http: listening on http://{bound}");
324
325    // Issue #3415 (DOC-50 §3.4): write the discovery file `CodeEngine` reads
326    // to find this daemon without a hardcoded port. Best-effort — a write
327    // failure only means discovery degrades to the `TCODE_DAEMON_URL` env
328    // var; it must never block the daemon from serving.
329    let discovery_path = crate::serve::discovery::http_addr_path();
330    if let Some(path) = &discovery_path
331        && let Err(e) = crate::serve::discovery::write_http_addr_file(path, &bound)
332    {
333        tracing::warn!(
334            error = %e,
335            path = %path.display(),
336            "tcode serve --http: failed to write daemon discovery file"
337        );
338    }
339
340    let app = build_axum_router(Arc::new(router), sessions, workstreams, binding);
341    axum::serve(listener, app)
342        .with_graceful_shutdown(trusty_common::shutdown_signal())
343        .await
344        .context("tcode serve --http: axum serve failed")?;
345
346    if let Some(path) = &discovery_path {
347        crate::serve::discovery::remove_http_addr_file(path);
348    }
349    info!("tcode serve --http: stopped");
350    Ok(())
351}
352
353#[cfg(test)]
354#[path = "http_tests.rs"]
355mod tests;
356
357#[cfg(test)]
358#[path = "http_origin_guard_tests.rs"]
359mod origin_guard_tests;