Skip to main content

lex_api/
lib.rs

1//! M8: agent API server. Spec §12.3.
2//!
3//! HTTP/JSON server exposing the same operations as the CLI. The server
4//! is stateful (it owns a `Store` instance) so agents don't pay sandbox
5//! startup cost per request.
6//!
7//! Endpoints:
8//!   POST /v1/parse           { source } → CanonicalAst | [SyntaxError]
9//!   POST /v1/check           { source } → { ok: true } | [TypeError]
10//!   POST /v1/publish         { source, activate? } → [{ stage_id, sig_id, status }]
11//!   GET  /v1/stage/<id>      → { metadata, ast, status }
12//!   GET  /v1/stage/<id>/attestations → { attestations: [Attestation] }
13//!   POST /v1/run             { source, fn, args, policy } → { run_id, output | error }
14//!   GET  /v1/trace/<run_id>  → TraceTree
15//!   POST /v1/replay          { source, fn, args, policy, overrides } → { run_id, output | error }
16//!   GET  /v1/diff?a=&b=      → Divergence | { divergence: null }
17//!   POST /v1/merge/start              { src_branch, dst_branch } → { merge_id, conflicts, ... }
18//!   POST /v1/merge/<id>/resolve       { resolutions: [...] } → { verdicts, remaining_conflicts }
19//!   POST /v1/merge/<id>/commit        → { new_head_op, dst_branch } | 422 conflicts remaining
20//!   POST /v1/ops/batch                [OperationRecord] → { received, added, skipped, added_ids }
21//!   POST /v1/attestations/batch       [Attestation] → { received, added, skipped, added_ids }
22//!   GET  /v1/branches/<name>/head     → { branch, head_op } (probe for `lex op push`)
23//!   GET  /v1/health          → { ok: true }
24//!
25//! Web (lex-tea v2, read-only HTML; human-only audit + triage):
26//!   GET  /                      → activity stream (recent attestations)
27//!   GET  /web/attention         → exceptions queue (Failed / Inconclusive,
28//!                                 stale merge sessions)
29//!   GET  /web/trust             → per-producer rollup (pass rate, latest
30//!                                 failure)
31//!   GET  /web/branches          → branch list
32//!   GET  /web/branch/<name>     → fns on a branch (detail)
33//!   GET  /web/stage/<id>        → stage info + attestation trail (detail)
34
35pub mod handlers;
36mod web;
37pub mod mcp;
38
39/// Re-exported so embedders can build a [`handlers::State::policy_ceiling`]
40/// without taking a direct dependency on `lex-runtime`.
41pub use lex_runtime::Policy;
42
43use std::path::PathBuf;
44use std::sync::Arc;
45
46pub fn serve(port: u16, store_root: PathBuf) -> anyhow::Result<()> {
47    let server = tiny_http::Server::http(("127.0.0.1", port))
48        .map_err(|e| anyhow::anyhow!("bind failed: {e}"))?;
49    let state = Arc::new(handlers::State::open(store_root)?);
50    serve_on(server, state);
51    Ok(())
52}
53
54/// MCP server (#171). Same `State` shape as the HTTP server,
55/// stdio transport instead of TCP. Designed for hosts that
56/// spawn `lex serve --mcp` as a subprocess and pipe JSON-RPC
57/// over stdin/stdout.
58pub fn serve_mcp_stdio(store_root: PathBuf) -> anyhow::Result<()> {
59    let state = Arc::new(handlers::State::open(store_root)?);
60    mcp::serve_mcp(state)?;
61    Ok(())
62}
63
64/// Test/embedded entry: takes an already-bound `Server` and runs until it
65/// stops accepting requests. Returns immediately when the `Server` is
66/// dropped on another thread.
67pub fn serve_on(server: tiny_http::Server, state: Arc<handlers::State>) {
68    for request in server.incoming_requests() {
69        let state = Arc::clone(&state);
70        let _ = handlers::handle(state, request);
71    }
72}