Skip to main content

mj_controller/server/api/
routes.rs

1use super::*;
2
3pub(in crate::server) fn router(state: ServerState) -> Router<ServerState> {
4    Router::new()
5        .route(
6            "/sessions/{session_id}/native-agents/{child_id}/history",
7            get(native_agent_history),
8        )
9        .route("/events", get(events::events))
10        .route("/github-token", get(github_token))
11        .route("/profiles/{profile_id}/config", get(profile_config))
12        .route(
13            "/profiles/{profile_id}/subagent-options",
14            get(subagent_options),
15        )
16        .route("/options", get(options))
17        .route(
18            "/sessions/{session_id}/config",
19            axum::routing::patch(set_config),
20        )
21        .route("/workspaces", get(list_workspaces).post(create_workspace))
22        .route("/sessions", get(list_sessions).post(start_session))
23        .route("/sessions/{session_id}", get(get_session))
24        .route(
25            "/sessions/{session_id}/subagents",
26            get(list_subagents).post(spawn_subagent),
27        )
28        .route("/sessions/{session_id}/prompt", post(prompt))
29        .route(
30            "/sessions/{session_id}/message",
31            post(mailbox::send_message),
32        )
33        .route(
34            "/sessions/{session_id}/queued-prompts/clear",
35            post(clear_queue),
36        )
37        .route(
38            "/sessions/{session_id}/events",
39            post(mailbox::enqueue_event),
40        )
41        .route("/sessions/{session_id}/transcript", get(transcript))
42        .route("/sessions/{session_id}/history", get(transcript_history))
43        .route("/sessions/{session_id}/usage", get(usage))
44        .route("/sessions/{session_id}/usage/tree", get(usage_tree))
45        .route("/sessions/{session_id}/wait", post(wait))
46        .route("/sessions/{session_id}/suspend", post(suspend))
47        .route("/sessions/{session_id}/destroy", post(destroy))
48        .route("/sessions/{session_id}/resume", post(resume))
49        .route(
50            "/sessions/{session_id}/background-tasks/stop",
51            post(stop_background_task),
52        )
53        .route(
54            "/sessions/{session_id}/interrupt-turn",
55            post(interrupt_turn),
56        )
57        .route(
58            "/sessions/{session_id}/review",
59            get(review_status).post(start_review),
60        )
61        .route(
62            "/sessions/{session_id}/review/{resolution}",
63            post(resolve_review),
64        )
65        .route("/sessions/{session_id}/diff", get(diff))
66        .route(
67            "/sessions/{session_id}/files",
68            get(read_file)
69                .put(write_file)
70                .layer(axum::extract::DefaultBodyLimit::max(
71                    mj_checkpoint::archive::MAX_SESSION_FILE_BYTES as usize,
72                )),
73        )
74        .route("/sessions/{session_id}/elicitations", get(elicitations))
75        .route(
76            "/sessions/{session_id}/elicitations/{elicitation_id}",
77            post(respond_elicitation),
78        )
79        .route("/sessions/{session_id}/export", post(export))
80        .route("/wiki/search", get(wiki_search))
81        .route("/wiki/sessions/{wiki_id}", get(wiki_session))
82        .route("/wiki/sessions/{wiki_id}/brief", get(wiki_brief))
83        .route("/wiki/sessions/{wiki_id}/hits", get(wiki_hits))
84        .route("/wiki/sessions/{wiki_id}/restore", post(wiki_restore))
85        .route_layer(axum::middleware::from_fn_with_state(
86            state,
87            require_api_auth,
88        ))
89        // Outside the auth layer so a 401 carries the version header too: a
90        // client must be able to tell "wrong token" from "wrong server".
91        .layer(axum::middleware::from_fn(api_response_headers))
92}
93
94/// Accept either the bearer token or the viewer's own session cookie.
95///
96/// The cookie is accepted because a browser already signed in to the viewer is
97/// the same user, and it makes the API reachable from the viewer page without
98/// handing the page a second secret.
99pub(super) async fn require_api_auth(
100    State(state): State<ServerState>,
101    request: HttpRequest<axum::body::Body>,
102    next: Next,
103) -> Result<Response, ApiFailure> {
104    let bearer = request
105        .headers()
106        .get(AUTHORIZATION)
107        .and_then(|value| value.to_str().ok())
108        .and_then(|value| value.strip_prefix("Bearer "))
109        .map(str::trim);
110    if bearer.is_some_and(|token| {
111        constant_time_eq(state.api_token.as_bytes(), token.as_bytes()) && !token.is_empty()
112    }) {
113        return Ok(next.run(request).await);
114    }
115    let cookie =
116        super::super::authenticated_viewer(&state, request.headers()).map_err(|error| {
117            if error.status == StatusCode::UNAUTHORIZED {
118                ApiFailure::new(
119                    StatusCode::UNAUTHORIZED,
120                    "supply the API token from the api-token file as a bearer token",
121                )
122            } else {
123                ApiFailure::from(error)
124            }
125        })?;
126    let mut response = next.run(request).await;
127    super::super::renew_viewer_response(&state, &cookie, &mut response)?;
128    Ok(response)
129}
130
131/// Stamp the contract version and forbid caching on every API response,
132/// including failures.
133pub(super) async fn api_response_headers(
134    request: HttpRequest<axum::body::Body>,
135    next: Next,
136) -> Response {
137    let mut response = next.run(request).await;
138    let headers = response.headers_mut();
139    headers.insert(API_VERSION_HEADER, HeaderValue::from_static(API_VERSION));
140    headers.insert(CACHE_CONTROL, HeaderValue::from_static("no-store"));
141    response
142}
143
144// ---------------------------------------------------------------------------
145// Handlers
146// ---------------------------------------------------------------------------
147
148#[derive(Debug, Clone, Serialize, Deserialize)]
149#[serde(deny_unknown_fields)]
150pub struct SessionListQuery {
151    pub workspace_id: Option<String>,
152    /// Older API clients omit this and retain the historical all-sessions list.
153    #[serde(default = "default_all_sessions")]
154    pub all: bool,
155}
156
157fn default_all_sessions() -> bool {
158    true
159}
160
161impl Default for SessionListQuery {
162    fn default() -> Self {
163        Self {
164            workspace_id: None,
165            all: true,
166        }
167    }
168}
169
170#[derive(Debug, Default, Deserialize)]
171#[serde(deny_unknown_fields)]
172pub(super) struct ProfileConfigQuery {
173    pub(super) model: Option<String>,
174}
175
176#[derive(Debug, Clone, Serialize, Deserialize)]
177#[serde(deny_unknown_fields)]
178pub struct SetConfigRequest {
179    pub key: String,
180    pub value: String,
181}