| 1 | use super::*; |
| 2 | use codewhale_config::private_directory::PrivateDirectory; |
| 3 | use codewhale_runtime::hashing::sha256_hex; |
| 4 | use std::sync::Arc; |
| 5 | |
| 6 | #[derive(Deserialize)] |
| 7 | #[serde(deny_unknown_fields)] |
| 8 | pub(in crate::runtime_api) struct Recycle { |
| 9 | workspace: Option<PathBuf>, |
| 10 | } |
| 11 | |
| 12 | #[derive(Serialize, Deserialize)] |
| 13 | struct HomeAction { |
| 14 | key: String, |
| 15 | store: String, |
| 16 | prior_home: Option<String>, |
| 17 | instance: Option<uuid::Uuid>, |
| 18 | request: CreateThreadRequest, |
| 19 | } |
| 20 | |
| 21 | #[derive(Serialize, Deserialize)] |
| 22 | struct HomeReceipt { |
| 23 | workspace: PathBuf, |
| 24 | home_thread_id: String, |
| 25 | instance: Option<uuid::Uuid>, |
| 26 | unavailable: bool, |
| 27 | } |
| 28 | |
| 29 | struct Journal { |
| 30 | dir: PrivateDirectory, |
| 31 | _lock: std::fs::File, |
| 32 | } |
| 33 | |
| 34 | impl Journal { |
| 35 | fn open(id: &str) -> anyhow::Result<Self> { |
| 36 | anyhow::ensure!( |
| 37 | id == "default" || saved_whales::valid_id(id), |
| 38 | "Invalid whale ID" |
| 39 | ); |
| 40 | let whale = codewhale_config::codewhale_home()?.join("whales").join(id); |
| 41 | PrivateDirectory::admit(&whale)?; |
| 42 | let dir = PrivateDirectory::admit(&whale.join("home-operations"))?; |
| 43 | let lock = dir.open_internal_file("lock")?; |
| 44 | anyhow::ensure!( |
| 45 | codewhale_util::lock::try_lock_file_exclusive(&lock)?, |
| 46 | "Whale home operation in progress. Retry the same action." |
| 47 | ); |
| 48 | anyhow::ensure!(dir.is_at_selected_path()?, "Whale home directory changed"); |
| 49 | Ok(Self { dir, _lock: lock }) |
| 50 | } |
| 51 | |
| 52 | fn read<T: serde::de::DeserializeOwned>(&self, name: &str) -> anyhow::Result<Option<T>> { |
| 53 | self.dir |
| 54 | .read_private_receipt(name, 2 * 1024 * 1024)? |
| 55 | .map(|(bytes, _)| serde_json::from_slice(&bytes).map_err(Into::into)) |
| 56 | .transpose() |
| 57 | } |
| 58 | |
| 59 | fn write(&self, name: &str, value: &impl Serialize) -> anyhow::Result<()> { |
| 60 | anyhow::ensure!( |
| 61 | self.dir.is_at_selected_path()?, |
| 62 | "Whale home directory changed" |
| 63 | ); |
| 64 | self.dir |
| 65 | .write_owned_file(name, &serde_json::to_vec(value)?, true) |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | pub(super) fn with_home_edit<T>( |
| 70 | id: &str, |
| 71 | edit: impl FnOnce() -> anyhow::Result<T>, |
| 72 | ) -> anyhow::Result<T> { |
| 73 | let journal = Journal::open(id)?; |
| 74 | anyhow::ensure!( |
| 75 | journal.read::<HomeAction>("pending")?.is_none(), |
| 76 | "Finish the pending recycle action before changing the home" |
| 77 | ); |
| 78 | edit() |
| 79 | } |
| 80 | |
| 81 | fn prepare( |
| 82 | id: &str, |
| 83 | store: &str, |
| 84 | key: &str, |
| 85 | workspace: PathBuf, |
| 86 | default_posture: &str, |
| 87 | ) -> anyhow::Result<HomeAction> { |
| 88 | let mut request = CreateThreadRequest { |
| 89 | workspace: Some(workspace), |
| 90 | whale_id: Some(id.to_owned()), |
| 91 | operation_key: Some(format!("whale-home-{key}")), |
| 92 | permission_posture: Some(default_posture.to_owned()), |
| 93 | ..Default::default() |
| 94 | }; |
| 95 | let (prior_home, instance) = if id == "default" { |
| 96 | let soul = codewhale_engine::whale_soul::load()?; |
| 97 | anyhow::ensure!(soul.writable, "The account owns this whale"); |
| 98 | if !soul.text.is_empty() { |
| 99 | request.system_prompt = Some(soul.text); |
| 100 | } |
| 101 | (None, None) |
| 102 | } else { |
| 103 | let whale = saved_whales::get(id)?; |
| 104 | request.system_prompt = whale.soul; |
| 105 | if let Some(posture) = whale.settings.permission_posture { |
| 106 | request.permission_posture = Some(posture); |
| 107 | } |
| 108 | request.child_posture = whale.settings.child_posture; |
| 109 | if let Some(agent_id) = whale.settings.external_agent_id { |
| 110 | request.executor = Some(CreateThreadExecutor { |
| 111 | kind: "acp".into(), |
| 112 | agent_id, |
| 113 | config: CreateThreadExecutorConfig { |
| 114 | model: whale.model, |
| 115 | ..Default::default() |
| 116 | }, |
| 117 | ..Default::default() |
| 118 | }); |
| 119 | } else { |
| 120 | request.model = whale.model; |
| 121 | request.model_provider_id = whale.model_provider_id; |
| 122 | } |
| 123 | (whale.settings.home_thread_id, whale.settings.instance_id) |
| 124 | }; |
| 125 | if let Some(child) = request.child_posture.as_deref() { |
| 126 | let parse = |value| { |
| 127 | codewhale_runtime::runtime_policy::RuntimePolicyProjection::from_request( |
| 128 | "agent", value, None, |
| 129 | ) |
| 130 | }; |
| 131 | let parent = parse(request.permission_posture.as_deref())?.permission; |
| 132 | let effective = parse(Some(child))?.permission.capped_at(parent); |
| 133 | request.child_posture = |
| 134 | Some(codewhale_runtime::runtime_policy::approval_wire(effective).into()); |
| 135 | } |
| 136 | Ok(HomeAction { |
| 137 | store: store.to_owned(), |
| 138 | key: key.to_owned(), |
| 139 | prior_home, |
| 140 | instance, |
| 141 | request, |
| 142 | }) |
| 143 | } |
| 144 | |
| 145 | fn finish( |
| 146 | journal: &Journal, |
| 147 | action: &HomeAction, |
| 148 | home: &str, |
| 149 | thread: Option<&ThreadRecord>, |
| 150 | ) -> anyhow::Result<bool> { |
| 151 | let id = action |
| 152 | .request |
| 153 | .whale_id |
| 154 | .as_deref() |
| 155 | .context("Missing whale identity")?; |
| 156 | let workspace = action |
| 157 | .request |
| 158 | .workspace |
| 159 | .as_ref() |
| 160 | .context("Missing whale workspace")?; |
| 161 | if let Some(thread) = thread { |
| 162 | anyhow::ensure!( |
| 163 | thread.id == home |
| 164 | && thread.whale_id.as_deref() == Some(id) |
| 165 | && &thread.workspace == workspace, |
| 166 | "Whale home identity changed" |
| 167 | ); |
| 168 | } |
| 169 | let mut unavailable = thread.is_none_or(|thread| thread.archived); |
| 170 | if id != "default" { |
| 171 | match saved_whales::get(id) { |
| 172 | Ok(whale) => { |
| 173 | let already_linked = whale.settings.home_thread_id.as_deref() == Some(home); |
| 174 | unavailable |= whale.settings.instance_id != action.instance |
| 175 | || (!already_linked && whale.settings.home_thread_id != action.prior_home); |
| 176 | if !unavailable && !already_linked { |
| 177 | saved_whales::save( |
| 178 | id, |
| 179 | Map::from_iter([("home_thread_id".into(), Value::String(home.to_owned()))]), |
| 180 | Some(&whale.revision), |
| 181 | )?; |
| 182 | } |
| 183 | } |
| 184 | Err(err) if err.is::<saved_whales::Missing>() => unavailable = true, |
| 185 | Err(err) => return Err(err), |
| 186 | } |
| 187 | } |
| 188 | journal.write( |
| 189 | &action.key, |
| 190 | &HomeReceipt { |
| 191 | workspace: workspace.clone(), |
| 192 | home_thread_id: home.to_owned(), |
| 193 | instance: action.instance, |
| 194 | unavailable, |
| 195 | }, |
| 196 | )?; |
| 197 | journal.dir.remove_raw("pending")?; |
| 198 | Ok(!unavailable) |
| 199 | } |
| 200 | |
| 201 | pub(in crate::runtime_api) async fn recycle( |
| 202 | State(state): State<RuntimeApiState>, |
| 203 | Path(id): Path<String>, |
| 204 | headers: HeaderMap, |
| 205 | Json(input): Json<Recycle>, |
| 206 | ) -> Result<Json<Value>, ApiError> { |
| 207 | let operation = automation_idempotency_key(&headers)? |
| 208 | .ok_or_else(|| ApiError::bad_request("Send an Idempotency-Key for the recycle action"))?; |
| 209 | let store = state |
| 210 | .runtime_threads |
| 211 | .session_store_binding() |
| 212 | .execution_scope; |
| 213 | let key = sha256_hex( |
| 214 | serde_json::to_vec(&(&store, &id, &operation)) |
| 215 | .map_err(|_| ApiError::internal("Cannot encode whale operation"))?, |
| 216 | ); |
| 217 | let workspace = input.workspace.unwrap_or_else(|| state.workspace.clone()); |
| 218 | let task = tokio::spawn(async move { |
| 219 | let lookup = id.clone(); |
| 220 | let journal = Arc::new( |
| 221 | owner_work(move || Journal::open(&lookup)) |
| 222 | .await |
| 223 | .map_err(|_| { |
| 224 | ApiError::conflict("Cannot acquire the whale home. Retry the same action.") |
| 225 | })?, |
| 226 | ); |
| 227 | let posture = state |
| 228 | .config |
| 229 | .read() |
| 230 | .approval_policy |
| 231 | .clone() |
| 232 | .unwrap_or_else(|| "ask".into()); |
| 233 | loop { |
| 234 | let read = Arc::clone(&journal); |
| 235 | let action_key = key.clone(); |
| 236 | let specialist = id.clone(); |
| 237 | let path = workspace.clone(); |
| 238 | let posture = posture.clone(); |
| 239 | let owner = store.clone(); |
| 240 | let next = owner_work(move || { |
| 241 | if let Some(receipt) = read.read::<HomeReceipt>(&action_key)? { |
| 242 | let current_instance = if specialist == "default" { |
| 243 | None |
| 244 | } else { |
| 245 | saved_whales::get(&specialist)?.settings.instance_id |
| 246 | }; |
| 247 | anyhow::ensure!( |
| 248 | !receipt.unavailable && receipt.instance == current_instance, |
| 249 | "The recycled whale home is no longer available" |
| 250 | ); |
| 251 | anyhow::ensure!( |
| 252 | receipt.workspace == path, |
| 253 | "Operation key already used for a different workspace" |
| 254 | ); |
| 255 | return Ok(Ok(receipt)); |
| 256 | } |
| 257 | if let Some(pending) = read.read::<HomeAction>("pending")? { |
| 258 | anyhow::ensure!( |
| 259 | pending.store == owner, |
| 260 | "Another runtime owns the pending whale home" |
| 261 | ); |
| 262 | anyhow::ensure!( |
| 263 | pending.key != action_key |
| 264 | || pending.request.workspace.as_ref() == Some(&path), |
| 265 | "Operation key already used for a different workspace" |
| 266 | ); |
| 267 | return Ok(Err(pending)); |
| 268 | } |
| 269 | let action = prepare(&specialist, &owner, &action_key, path, &posture)?; |
| 270 | read.write("pending", &action)?; |
| 271 | Ok(Err(action)) |
| 272 | }) |
| 273 | .await |
| 274 | .map_err(failure)?; |
| 275 | let action = match next { |
| 276 | Ok(receipt) => { |
| 277 | let thread = state |
| 278 | .runtime_threads |
| 279 | .get_thread(&receipt.home_thread_id) |
| 280 | .await |
| 281 | .map_err(map_thread_err)?; |
| 282 | if thread.whale_id.as_deref() != Some(id.as_str()) |
| 283 | || thread.workspace != workspace |
| 284 | || thread.archived |
| 285 | { |
| 286 | return Err(ApiError::conflict( |
| 287 | "The recycled home is no longer available", |
| 288 | )); |
| 289 | } |
| 290 | return Ok(Json(json!({"home_thread_id": thread.id}))); |
| 291 | } |
| 292 | Err(action) => action, |
| 293 | }; |
| 294 | let op = action |
| 295 | .request |
| 296 | .operation_key |
| 297 | .as_deref() |
| 298 | .ok_or_else(|| ApiError::internal("Missing whale operation key"))?; |
| 299 | let manager = &state.runtime_threads; |
| 300 | let (home, thread) = match manager |
| 301 | .thread_create_reservation(op) |
| 302 | .await |
| 303 | .map_err(failure)? |
| 304 | { |
| 305 | Some((home, false)) if action.key != key => (home, None), |
| 306 | Some((home, true)) => { |
| 307 | let runtime = Arc::clone(manager); |
| 308 | let lookup = home.clone(); |
| 309 | let thread = owner_work(move || runtime.history_operation_thread(&lookup)) |
| 310 | .await |
| 311 | .map_err(failure)?; |
| 312 | (home, thread) |
| 313 | } |
| 314 | _ => match create_prepared_thread(state.clone(), action.request.clone()).await { |
| 315 | Ok((_, Json(thread))) => (thread.id.clone(), Some(thread)), |
| 316 | Err(error) => match manager |
| 317 | .thread_create_reservation(op) |
| 318 | .await |
| 319 | .map_err(failure)? |
| 320 | { |
| 321 | Some((home, false)) if error.code == Some("thread_create_conflict") => { |
| 322 | (home, None) |
| 323 | } |
| 324 | None => { |
| 325 | let cleanup = Arc::clone(&journal); |
| 326 | owner_work(move || cleanup.dir.remove_raw("pending")) |
| 327 | .await |
| 328 | .map_err(failure)?; |
| 329 | return Err(error); |
| 330 | } |
| 331 | _ => return Err(error), |
| 332 | }, |
| 333 | }, |
| 334 | }; |
| 335 | let completed = action.key == key; |
| 336 | let reserved = home.clone(); |
| 337 | let write = Arc::clone(&journal); |
| 338 | let available = owner_work(move || finish(&write, &action, &reserved, thread.as_ref())) |
| 339 | .await |
| 340 | .map_err(failure)?; |
| 341 | if completed { |
| 342 | if !available { |
| 343 | return Err(ApiError::conflict( |
| 344 | "The recycled whale home is no longer available", |
| 345 | )); |
| 346 | } |
| 347 | return Ok(Json(json!({"home_thread_id":home}))); |
| 348 | } |
| 349 | } |
| 350 | }); |
| 351 | task.await |
| 352 | .map_err(|_| ApiError::internal("Retry the whale home action with its original key"))? |
| 353 | } |
| 354 | |
| 355 | #[cfg(test)] |
| 356 | mod tests { |
| 357 | use super::*; |
| 358 | |
| 359 | #[test] |
| 360 | fn unavailable_reservations_leave_a_terminal_receipt_and_release_the_pending_slot() |
| 361 | -> anyhow::Result<()> { |
| 362 | let _env = codewhale_engine::test_support::lock_test_env(); |
| 363 | let root = tempfile::tempdir()?; |
| 364 | let _home = codewhale_engine::test_support::EnvVarGuard::set( |
| 365 | "CODEWHALE_HOME", |
| 366 | root.path().join("home"), |
| 367 | ); |
| 368 | let journal = Journal::open("default")?; |
| 369 | let action = prepare("default", "runtime", "action", root.path().into(), "ask")?; |
| 370 | journal.write("pending", &action)?; |
| 371 | assert!(!finish(&journal, &action, "thr_missing", None)?); |
| 372 | assert!(journal.read::<HomeAction>("pending")?.is_none()); |
| 373 | let receipt = journal.read::<HomeReceipt>("action")?.unwrap(); |
| 374 | assert!(receipt.unavailable); |
| 375 | assert_eq!(receipt.home_thread_id, "thr_missing"); |
| 376 | drop(journal); |
| 377 | with_home_edit("default", || Ok(())) |
| 378 | } |
| 379 | } |
| 380 |