| 1 | use super::*; |
| 2 | use codewhale_engine::fleet::profile::{AgentProfileIdentityConflict, AgentProfileWriteConflict}; |
| 3 | use codewhale_engine::runtime_threads::manager::{ |
| 4 | CreateThreadExecutor, CreateThreadExecutorConfig, |
| 5 | }; |
| 6 | use codewhale_engine::saved_whales::{self, SavedWhale}; |
| 7 | use codewhale_runtime::runtime_control::owner_work; |
| 8 | use serde_json::Map; |
| 9 | |
| 10 | fn failure(error: anyhow::Error) -> ApiError { |
| 11 | if error.is::<saved_whales::Missing>() { |
| 12 | ApiError::not_found("Saved whale not found").with_code("saved_whale_not_found") |
| 13 | } else if error.is::<saved_whales::Stale>() || error.is::<AgentProfileWriteConflict>() { |
| 14 | ApiError { |
| 15 | status: StatusCode::PRECONDITION_FAILED, |
| 16 | code: None, |
| 17 | message: "Saved whale changed. Reopen it and retry.".into(), |
| 18 | } |
| 19 | } else if error.is::<AgentProfileIdentityConflict>() { |
| 20 | ApiError::conflict("A profile with this ID already exists") |
| 21 | } else if error.is::<std::io::Error>() { |
| 22 | ApiError::conflict("Cannot access the saved profile") |
| 23 | } else { |
| 24 | ApiError::bad_request(error.to_string()) |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | fn revision(headers: &HeaderMap) -> Result<Option<String>, ApiError> { |
| 29 | let Some(header) = headers.get("if-match") else { |
| 30 | return Ok(None); |
| 31 | }; |
| 32 | let raw = header |
| 33 | .to_str() |
| 34 | .ok() |
| 35 | .and_then(|v| v.strip_prefix('"')?.strip_suffix('"')) |
| 36 | .ok_or_else(|| ApiError::bad_request("Expected a quoted profile revision in If-Match"))?; |
| 37 | if raw != "new" |
| 38 | && !(raw.len() == 64 |
| 39 | && raw |
| 40 | .bytes() |
| 41 | .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))) |
| 42 | { |
| 43 | return Err(ApiError::bad_request("Invalid profile revision")); |
| 44 | } |
| 45 | Ok(Some(raw.to_owned())) |
| 46 | } |
| 47 | |
| 48 | async fn scope_home(state: &RuntimeApiState, whale: &mut SavedWhale) { |
| 49 | if let Some(home) = whale.settings.home_thread_id.as_deref() { |
| 50 | let local = state.runtime_threads.get_thread(home).await; |
| 51 | if !local.is_ok_and(|thread| { |
| 52 | !thread.archived && thread.whale_id.as_deref() == Some(whale.id.as_str()) |
| 53 | }) { |
| 54 | whale.settings.home_thread_id = None; |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | pub(super) async fn list( |
| 60 | State(state): State<RuntimeApiState>, |
| 61 | ) -> Result<Json<saved_whales::SavedWhaleList>, ApiError> { |
| 62 | let mut rows = owner_work(saved_whales::list).await.map_err(failure)?; |
| 63 | for row in &mut rows.whales { |
| 64 | scope_home(&state, row).await; |
| 65 | } |
| 66 | Ok(Json(rows)) |
| 67 | } |
| 68 | |
| 69 | pub(super) async fn detail( |
| 70 | State(state): State<RuntimeApiState>, |
| 71 | Path(id): Path<String>, |
| 72 | ) -> Result<Json<SavedWhale>, ApiError> { |
| 73 | let mut row = owner_work(move || saved_whales::get(&id)) |
| 74 | .await |
| 75 | .map_err(failure)?; |
| 76 | scope_home(&state, &mut row).await; |
| 77 | Ok(Json(row)) |
| 78 | } |
| 79 | |
| 80 | async fn validate_home( |
| 81 | state: &RuntimeApiState, |
| 82 | id: &str, |
| 83 | fields: &Map<String, Value>, |
| 84 | ) -> Result<(), ApiError> { |
| 85 | if let Some(Value::String(home)) = fields.get("home_thread_id") { |
| 86 | let thread = state |
| 87 | .runtime_threads |
| 88 | .get_thread(home) |
| 89 | .await |
| 90 | .map_err(|_| ApiError::bad_request("Unknown local whale home thread"))?; |
| 91 | if thread.archived || thread.whale_id.as_deref() != Some(id) { |
| 92 | return Err(ApiError::bad_request( |
| 93 | "Choose an active local thread created for this whale", |
| 94 | )); |
| 95 | } |
| 96 | } |
| 97 | Ok(()) |
| 98 | } |
| 99 | |
| 100 | pub(super) async fn apply_profile(req: &mut CreateThreadRequest) -> Result<(), ApiError> { |
| 101 | let Some(id) = req.whale_id.clone().filter(|id| id != "default") else { |
| 102 | return Ok(()); |
| 103 | }; |
| 104 | match owner_work(move || saved_whales::get(&id)).await { |
| 105 | Ok(whale) => { |
| 106 | if req.permission_posture.is_none() { |
| 107 | req.permission_posture = whale.settings.permission_posture; |
| 108 | } |
| 109 | if let Some(saved) = whale.settings.child_posture { |
| 110 | let parse = |v: &str| { |
| 111 | codewhale_runtime::runtime_policy::RuntimePolicyProjection::from_request( |
| 112 | "agent", |
| 113 | Some(v), |
| 114 | None, |
| 115 | ) |
| 116 | .map(|p| p.permission) |
| 117 | .map_err(failure) |
| 118 | }; |
| 119 | let ceiling = parse(&saved)?; |
| 120 | let limit = req |
| 121 | .child_posture |
| 122 | .as_deref() |
| 123 | .map(parse) |
| 124 | .transpose()? |
| 125 | .map_or(ceiling, |value| value.capped_at(ceiling)); |
| 126 | let parent = |
| 127 | codewhale_runtime::runtime_policy::RuntimePolicyProjection::from_request( |
| 128 | req.mode.as_deref().unwrap_or("agent"), |
| 129 | req.permission_posture.as_deref(), |
| 130 | req.auto_approve, |
| 131 | ) |
| 132 | .map_err(failure)?; |
| 133 | req.child_posture = Some( |
| 134 | codewhale_runtime::runtime_policy::approval_wire( |
| 135 | limit.capped_at(parent.permission), |
| 136 | ) |
| 137 | .into(), |
| 138 | ); |
| 139 | } |
| 140 | } |
| 141 | Err(err) if err.is::<saved_whales::Missing>() => {} |
| 142 | Err(err) => return Err(failure(err)), |
| 143 | } |
| 144 | Ok(()) |
| 145 | } |
| 146 | |
| 147 | pub(super) async fn create( |
| 148 | State(state): State<RuntimeApiState>, |
| 149 | Json(mut fields): Json<Map<String, Value>>, |
| 150 | ) -> Result<(StatusCode, Json<SavedWhale>), ApiError> { |
| 151 | let Some(Value::String(id)) = fields.remove("id") else { |
| 152 | return Err(ApiError::bad_request("A specialist ID is required")); |
| 153 | }; |
| 154 | validate_home(&state, &id, &fields).await?; |
| 155 | let mut row = |
| 156 | owner_work(move || recycle::with_home_edit(&id, || saved_whales::save(&id, fields, None))) |
| 157 | .await |
| 158 | .map_err(failure)?; |
| 159 | scope_home(&state, &mut row).await; |
| 160 | Ok((StatusCode::CREATED, Json(row))) |
| 161 | } |
| 162 | |
| 163 | pub(super) async fn edit( |
| 164 | State(state): State<RuntimeApiState>, |
| 165 | Path(id): Path<String>, |
| 166 | headers: HeaderMap, |
| 167 | Json(fields): Json<Map<String, Value>>, |
| 168 | ) -> Result<Json<SavedWhale>, ApiError> { |
| 169 | let rev = revision(&headers)?.ok_or_else(|| { |
| 170 | ApiError::bad_request("Read the saved whale and send its revision in If-Match") |
| 171 | })?; |
| 172 | validate_home(&state, &id, &fields).await?; |
| 173 | let mut row = owner_work(move || { |
| 174 | if fields.contains_key("home_thread_id") { |
| 175 | recycle::with_home_edit(&id, || saved_whales::save(&id, fields, Some(&rev))) |
| 176 | } else { |
| 177 | saved_whales::save(&id, fields, Some(&rev)) |
| 178 | } |
| 179 | }) |
| 180 | .await |
| 181 | .map_err(failure)?; |
| 182 | scope_home(&state, &mut row).await; |
| 183 | Ok(Json(row)) |
| 184 | } |
| 185 | |
| 186 | pub(super) async fn remove( |
| 187 | Path(id): Path<String>, |
| 188 | headers: HeaderMap, |
| 189 | ) -> Result<StatusCode, ApiError> { |
| 190 | let rev = revision(&headers)?; |
| 191 | owner_work(move || recycle::with_home_edit(&id, || saved_whales::remove(&id, rev.as_deref()))) |
| 192 | .await |
| 193 | .map_err(failure)?; |
| 194 | Ok(StatusCode::NO_CONTENT) |
| 195 | } |
| 196 | |
| 197 | mod recycle; |
| 198 | pub(super) use recycle::recycle; |
| 199 |