返回 CodeWhale
external_agent_options.rs
根目录 / crates / app-server / src / runtime_api / external_agent_options.rs
1 use std::path::PathBuf;
2
3 use axum::Json;
4 use axum::extract::{Path, Query, State};
5 use serde::Deserialize;
6
7 use codewhale_engine::external_agents::acp::AgentOptions;
8 use codewhale_engine::fleet::agents::ExecutorUnavailable;
9
10 use super::{ApiError, RuntimeApiState, external_agent_refusal};
11
12 use codewhale_engine::external_agents::valid_agent_id;
13 const MAX_CWD_BYTES: usize = 4096;
14 const MAX_MODEL_BYTES: usize = 128;
15
16 #[derive(Debug, Deserialize)]
17 pub(super) struct OptionsQuery {
18 cwd: Option<PathBuf>,
19 model: Option<String>,
20 }
21
22 pub(super) async fn get_external_agent_options(
23 State(state): State<RuntimeApiState>,
24 Path(id): Path<String>,
25 Query(query): Query<OptionsQuery>,
26 ) -> Result<Json<AgentOptions>, ApiError> {
27 if !valid_agent_id(&id) {
28 return Err(ApiError::bad_request(
29 "the agent id must name an agent from GET /v1/agents/external",
30 ));
31 }
32 let cwd = query
33 .cwd
34 .ok_or_else(|| ApiError::bad_request("cwd is required"))?;
35 let text = cwd.to_string_lossy();
36 if text.len() > MAX_CWD_BYTES || text.chars().any(char::is_control) || !cwd.is_absolute() {
37 return Err(ApiError::bad_request(
38 "cwd must be an absolute directory path",
39 ));
40 }
41 let probe = cwd.clone();
42 let is_dir = tokio::task::spawn_blocking(move || probe.is_dir())
43 .await
44 .map_err(|_| ApiError::internal("cwd check failed"))?;
45 if !is_dir {
46 return Err(ApiError::not_found(
47 "cwd is not a directory on this computer",
48 ));
49 }
50 let requested_model = match query.model.as_deref().map(str::trim) {
51 Some("") | None => None,
52 Some(model) if model.len() <= MAX_MODEL_BYTES && !model.chars().any(char::is_control) => {
53 Some(model)
54 }
55 Some(_) => {
56 return Err(ApiError::bad_request(
57 "model must be the agent's own option value",
58 ));
59 }
60 };
61 match state
62 .runtime_threads
63 .external_agent_options_for_model(&id, &cwd, requested_model)
64 .await
65 {
66 Ok(options) => Ok(Json(options)),
67 Err(error) => {
68 let mut refusal = external_agent_refusal(&error);
69 if let Some(refusal) = refusal.as_mut()
70 && refusal.code == Some(ExecutorUnavailable::UNKNOWN_AGENT)
71 {
72 refusal.status = axum::http::StatusCode::NOT_FOUND;
73 }
74 Err(refusal.unwrap_or_else(|| ApiError::internal(error.to_string())))
75 }
76 }
77 }
78
78 lines RUST