返回 CodeWhale
http.rs
根目录 / crates / app-server / src / http.rs
1 use crate::config_rpc::{CONFIG_LOAD_ERROR, CONFIG_SAVE_ERROR, process_app_request};
2 use crate::turns::{handle_thread_request, run_http_thread_message, run_prompt_turn};
3 use crate::{
4 AppServerOptions, AppState, AppTransport, DEFAULT_CORS_ORIGINS, DispatchError,
5 MAX_HTTP_BODY_BYTES, RUNTIME_UNAVAILABLE_CODE, THREAD_NOT_FOUND_CODE, chat_completions,
6 legacy_deepseek_compat,
7 };
8 use anyhow::{Result, bail};
9 use axum::extract::{DefaultBodyLimit, Request, State};
10 use axum::http::{HeaderValue, Method, StatusCode, header};
11 use axum::middleware::Next;
12 use axum::response::{IntoResponse as _, Response};
13 use axum::routing::{get, post};
14 use axum::{Json, Router, middleware};
15 use codewhale_app_server_protocol::runtime::MAX_RUNTIME_IMAGE_BODY_BYTES;
16 use codewhale_protocol::{AppRequest, AppResponse, PromptRequest, ThreadRequest};
17 use serde_json::{Value, json};
18 use std::path::PathBuf;
19 use tower_http::cors::CorsLayer;
20 use uuid::Uuid;
21
22 /// Protected routes the `Capabilities` response advertises. A test sends a
23 /// request to each one through [`app_router`], so an entry here without a
24 /// handler fails the tests instead of shipping a dead route.
25 ///
26 /// There is no `/tool`: a direct tool call outside a turn would need its own
27 /// tool catalog and approval decision, and the Engine behind the runtime
28 /// bridge is the only tool and approval authority. Tools run inside turns
29 /// (`/prompt`, `/thread` messages). Compatibility turns require an explicit
30 /// empty `allowed_tools` list; interactive execution is refused before turn
31 /// admission. Tool-enabled work belongs on `app-server --http` and `/v1/*`.
32 pub(crate) const ADVERTISED_ROUTES: &[&str] = &["/thread", "/app", "/prompt"];
33
34 /// Existing compatibility routes adopted by the canonical host listener.
35 /// Both callers share the exact existing dispatcher/auth/body-limit routes.
36 pub fn runtime_compatibility_router(
37 mut state: AppState,
38 cors_origins: &[String],
39 auth_token: Option<String>,
40 workspace: Option<PathBuf>,
41 ) -> Router {
42 // Only the listener's gate changes. The captured bridge keeps the original
43 // owner's in-memory credential and all shared dispatcher state.
44 state.auth_token = auth_token;
45 state.frontend_workspace = workspace;
46 app_router(state, cors_origins)
47 }
48
49 pub(crate) fn app_router(state: AppState, cors_origins: &[String]) -> Router {
50 let protected_routes = Router::new()
51 .route(
52 "/thread",
53 post(thread_handler).layer(axum::extract::DefaultBodyLimit::max(
54 MAX_RUNTIME_IMAGE_BODY_BYTES,
55 )),
56 )
57 .route("/app", post(app_handler))
58 .route(
59 "/prompt",
60 post(prompt_handler).layer(axum::extract::DefaultBodyLimit::max(
61 MAX_RUNTIME_IMAGE_BODY_BYTES,
62 )),
63 )
64 .route(
65 "/v1/chat/completions",
66 post(chat_completions::chat_completions_handler),
67 )
68 .route_layer(middleware::from_fn_with_state(
69 state.clone(),
70 require_app_server_token,
71 ));
72
73 Router::new()
74 .route("/healthz", get(healthz))
75 .merge(protected_routes)
76 .layer(DefaultBodyLimit::max(MAX_HTTP_BODY_BYTES))
77 .layer(cors_layer(cors_origins))
78 .with_state(state)
79 }
80
81 pub(crate) async fn healthz() -> Json<Value> {
82 Json(json!({
83 "status": "ok",
84 "protocol": "v2",
85 "service": legacy_deepseek_compat::SERVICE_NAME
86 }))
87 }
88
89 /// Render a routing failure as a typed HTTP error body.
90 ///
91 /// Deliberately *not* a success-shaped payload with the error stuffed into a
92 /// content field: a client must be able to tell "the model said this" from
93 /// "nothing ran".
94 pub(crate) fn http_error_from_jsonrpc(err: DispatchError) -> (StatusCode, Json<Value>) {
95 let (status, code) = match err.wire.code {
96 -32600 | -32602 => (StatusCode::BAD_REQUEST, "invalid_request"),
97 THREAD_NOT_FOUND_CODE => (StatusCode::NOT_FOUND, "thread_not_found"),
98 RUNTIME_UNAVAILABLE_CODE => (StatusCode::SERVICE_UNAVAILABLE, "runtime_unavailable"),
99 _ => (StatusCode::INTERNAL_SERVER_ERROR, "internal_error"),
100 };
101 (
102 status,
103 Json(json!({
104 "error": {
105 "code": code,
106 "jsonrpc_code": err.wire.code,
107 "message": err.wire.message,
108 "data": err.wire.data,
109 }
110 })),
111 )
112 }
113
114 pub(crate) async fn thread_handler(
115 State(state): State<AppState>,
116 Json(req): Json<ThreadRequest>,
117 ) -> Response {
118 // A message is a turn, and turns belong to the runtime — not to the
119 // bookkeeping `Runtime` behind the other thread operations. This mirrors
120 // the interception stdio `thread/message` has always done.
121 if let ThreadRequest::Message {
122 thread_id,
123 input,
124 allowed_tools,
125 images,
126 max_output_tokens,
127 } = req
128 {
129 return match run_http_thread_message(
130 &state,
131 thread_id,
132 input,
133 allowed_tools,
134 images,
135 max_output_tokens,
136 )
137 .await
138 {
139 Ok(res) => (StatusCode::OK, Json(res)).into_response(),
140 Err(err) => http_error_from_jsonrpc(err).into_response(),
141 };
142 }
143 match handle_thread_request(&state, req).await {
144 Ok(res) => (StatusCode::OK, Json(res)).into_response(),
145 Err(err) => http_error_from_jsonrpc(err).into_response(),
146 }
147 }
148
149 /// `POST /prompt` — runs a genuine model turn through the runtime bridge.
150 ///
151 /// Note what this handler does *not* do: it never takes the `Runtime` write
152 /// lock. The old implementation held it across the whole request while doing
153 /// no model work at all.
154 pub(crate) async fn prompt_handler(
155 State(state): State<AppState>,
156 Json(req): Json<PromptRequest>,
157 ) -> Response {
158 let mut sink = tokio::io::sink();
159 match run_prompt_turn(&state, &mut sink, req, None).await {
160 Ok(res) => (StatusCode::OK, Json(res)).into_response(),
161 Err(err) => http_error_from_jsonrpc(err).into_response(),
162 }
163 }
164
165 pub(crate) async fn app_handler(
166 State(state): State<AppState>,
167 Json(req): Json<AppRequest>,
168 ) -> (StatusCode, Json<AppResponse>) {
169 let response = process_app_request(&state, req, AppTransport::Http).await;
170 (app_response_status(&response), Json(response))
171 }
172
173 pub(crate) fn app_response_status(response: &AppResponse) -> StatusCode {
174 if response.ok {
175 return StatusCode::OK;
176 }
177 if response.data.get("request_id").is_some() {
178 StatusCode::CONFLICT
179 } else if response
180 .data
181 .get("error")
182 .and_then(Value::as_str)
183 .is_some_and(|err| err.starts_with(CONFIG_LOAD_ERROR) || err.starts_with(CONFIG_SAVE_ERROR))
184 {
185 StatusCode::INTERNAL_SERVER_ERROR
186 } else {
187 StatusCode::BAD_REQUEST
188 }
189 }
190
191 pub(crate) fn resolve_auth_token(options: &AppServerOptions) -> Result<Option<String>> {
192 let configured = options.auth_token.as_ref().map(|token| token.trim());
193 if let Some(token) = configured
194 && token.is_empty()
195 {
196 bail!("app-server auth token cannot be empty");
197 }
198 let has_explicit_token = configured.is_some();
199
200 if options.insecure_no_auth {
201 if !options.listen.ip().is_loopback() {
202 bail!("refusing unauthenticated app-server bind on non-loopback address");
203 }
204 eprintln!("warning: app-server HTTP auth disabled by --insecure-no-auth");
205 return Ok(None);
206 }
207
208 if !has_explicit_token && !options.listen.ip().is_loopback() {
209 bail!(
210 "refusing non-loopback app-server bind without explicit auth token; pass --auth-token or set CODEWHALE_APP_SERVER_TOKEN"
211 );
212 }
213
214 let token = configured
215 .map(str::to_string)
216 .unwrap_or_else(|| format!("cwapp_{}", Uuid::new_v4().simple()));
217 for line in app_server_auth_status_lines(has_explicit_token) {
218 eprintln!("{line}");
219 }
220 Ok(Some(token))
221 }
222
223 pub(crate) fn app_server_auth_status_lines(has_explicit_token: bool) -> Vec<&'static str> {
224 if has_explicit_token {
225 return vec!["app-server auth: bearer token required for HTTP routes."];
226 }
227 vec![
228 "app-server auth: generated bearer token for this process (not printed).",
229 " Pass --auth-token or set CODEWHALE_APP_SERVER_TOKEN when another client needs to connect.",
230 ]
231 }
232
233 pub(crate) fn cors_layer(extra_origins: &[String]) -> CorsLayer {
234 let mut origins: Vec<HeaderValue> = DEFAULT_CORS_ORIGINS
235 .iter()
236 .filter_map(|origin| HeaderValue::from_str(origin).ok())
237 .collect();
238 for raw in extra_origins {
239 let trimmed = raw.trim();
240 if trimmed.is_empty() {
241 continue;
242 }
243 match HeaderValue::from_str(trimmed) {
244 Ok(value) if !origins.contains(&value) => origins.push(value),
245 Ok(_) => {}
246 Err(err) => {
247 eprintln!("warning: ignoring invalid app-server CORS origin `{trimmed}`: {err}")
248 }
249 }
250 }
251
252 CorsLayer::new()
253 .allow_origin(origins)
254 .allow_methods([Method::GET, Method::POST, Method::OPTIONS])
255 .allow_headers([header::AUTHORIZATION, header::CONTENT_TYPE])
256 }
257
258 pub(crate) async fn require_app_server_token(
259 State(state): State<AppState>,
260 req: Request,
261 next: Next,
262 ) -> Response {
263 let Some(expected) = state.auth_token.as_deref() else {
264 return next.run(req).await;
265 };
266 let authorized = req
267 .headers()
268 .get(header::AUTHORIZATION)
269 .and_then(|value| value.to_str().ok())
270 .and_then(|raw| raw.strip_prefix("Bearer "))
271 .is_some_and(|token| {
272 codewhale_core::secret_eq::constant_time_eq(token.as_bytes(), expected.as_bytes())
273 });
274
275 if authorized {
276 next.run(req).await
277 } else {
278 (
279 StatusCode::UNAUTHORIZED,
280 Json(json!({
281 "error": {
282 "message": "app-server bearer token required",
283 "status": StatusCode::UNAUTHORIZED.as_u16(),
284 }
285 })),
286 )
287 .into_response()
288 }
289 }
290
290 lines RUST