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 publish_examples;
37mod web;
38pub mod mcp;
39
40/// Re-exported so embedders can build a [`handlers::State::policy_ceiling`]
41/// without taking a direct dependency on `lex-runtime`.
42pub use lex_runtime::Policy;
43
44use std::path::PathBuf;
45use std::sync::Arc;
46
47pub fn serve(port: u16, store_root: PathBuf) -> anyhow::Result<()> {
48    let server = tiny_http::Server::http(("127.0.0.1", port))
49        .map_err(|e| anyhow::anyhow!("bind failed: {e}"))?;
50    let state = Arc::new(handlers::State::open(store_root)?);
51    serve_on(server, state);
52    Ok(())
53}
54
55/// MCP server (#171). Same `State` shape as the HTTP server,
56/// stdio transport instead of TCP. Designed for hosts that
57/// spawn `lex serve --mcp` as a subprocess and pipe JSON-RPC
58/// over stdin/stdout.
59pub fn serve_mcp_stdio(store_root: PathBuf) -> anyhow::Result<()> {
60    let state = Arc::new(handlers::State::open(store_root)?);
61    mcp::serve_mcp(state)?;
62    Ok(())
63}
64
65/// Test/embedded entry: takes an already-bound `Server` and runs until it
66/// stops accepting requests. Returns immediately when the `Server` is
67/// dropped on another thread.
68pub fn serve_on(server: tiny_http::Server, state: Arc<handlers::State>) {
69    for request in server.incoming_requests() {
70        let state = Arc::clone(&state);
71        let _ = handlers::handle(state, request);
72    }
73}