| 1 | //! Compatibility control projection onto the already held canonical owner. |
| 2 | //! SQLite supplies immutable migration input and committed alias receipts only. |
| 3 | use super::*; |
| 4 | use crate::owner_calls; |
| 5 | use anyhow::{Context as _, bail}; |
| 6 | #[cfg(test)] |
| 7 | use axum::Router; |
| 8 | use codewhale_protocol::{ |
| 9 | CanonicalHistoryImportRequest, CanonicalHistoryOptions, CanonicalHistorySource, |
| 10 | CanonicalThreadMutation, CanonicalThreadMutationRequest, CanonicalThreadOperationKind, |
| 11 | CanonicalThreadOperationLookup, CanonicalThreadOperationRecovery, |
| 12 | CanonicalThreadOperationStatus, CanonicalThreadReceipt, CanonicalThreadSnapshot, |
| 13 | LegacyThreadHistory, MAX_CANONICAL_HISTORY_BYTES, MAX_CANONICAL_HISTORY_ENTRIES, |
| 14 | RuntimeOwnerReceipt, SessionSource, Thread, ThreadStatus, |
| 15 | }; |
| 16 | |
| 17 | #[cfg(test)] |
| 18 | #[derive(Debug, thiserror::Error)] |
| 19 | #[error("runtime API returned {status}: {detail}")] |
| 20 | struct HttpFailure { |
| 21 | status: StatusCode, |
| 22 | detail: String, |
| 23 | } |
| 24 | |
| 25 | #[derive(Debug, thiserror::Error)] |
| 26 | #[error( |
| 27 | "canonical operation {operation} completed as thread {thread} / session {session}; inspect this result without replay: {source}" |
| 28 | )] |
| 29 | struct CommittedControlFailure { |
| 30 | operation: String, |
| 31 | thread: String, |
| 32 | session: String, |
| 33 | #[source] |
| 34 | source: anyhow::Error, |
| 35 | } |
| 36 | |
| 37 | fn committed_failure(receipt: &CanonicalThreadReceipt, source: anyhow::Error) -> anyhow::Error { |
| 38 | CommittedControlFailure { |
| 39 | operation: receipt.operation_key.clone(), |
| 40 | thread: receipt.runtime_thread_id.clone(), |
| 41 | session: receipt.session_id.clone(), |
| 42 | source, |
| 43 | } |
| 44 | .into() |
| 45 | } |
| 46 | |
| 47 | fn owner(state: &AppState) -> Result<RuntimeOwnerReceipt> { |
| 48 | state.captured_owner.clone().context( |
| 49 | "thread controls require the authenticated canonical owner; no standalone history writer", |
| 50 | ) |
| 51 | } |
| 52 | |
| 53 | /// declared length and actual streamed bytes must both fit; nothing is cut. |
| 54 | #[cfg(test)] |
| 55 | pub(super) async fn read_json_response(mut response: reqwest::Response) -> Result<Value> { |
| 56 | let status = response.status(); |
| 57 | if response |
| 58 | .content_length() |
| 59 | .is_some_and(|len| len > MAX_CANONICAL_HISTORY_BYTES as u64) |
| 60 | { |
| 61 | bail!("canonical response exceeds complete-document bound"); |
| 62 | } |
| 63 | let mut bytes = Vec::new(); |
| 64 | while let Some(chunk) = response.chunk().await? { |
| 65 | if bytes |
| 66 | .len() |
| 67 | .checked_add(chunk.len()) |
| 68 | .is_none_or(|len| len > MAX_CANONICAL_HISTORY_BYTES) |
| 69 | { |
| 70 | bail!("canonical response exceeds complete-document bound"); |
| 71 | } |
| 72 | bytes.extend_from_slice(&chunk); |
| 73 | } |
| 74 | if !status.is_success() { |
| 75 | let detail = String::from_utf8_lossy(&bytes); |
| 76 | return Err(HttpFailure { |
| 77 | status, |
| 78 | detail: detail.trim().to_owned(), |
| 79 | } |
| 80 | .into()); |
| 81 | } |
| 82 | if bytes.is_empty() && status == StatusCode::NO_CONTENT { |
| 83 | return Ok(Value::Null); |
| 84 | } |
| 85 | serde_json::from_slice(&bytes).context("invalid canonical Runtime JSON") |
| 86 | } |
| 87 | |
| 88 | async fn request( |
| 89 | owner: &Arc<dyn RuntimeOwnerFrontend>, |
| 90 | operation: RuntimeOwnerRequest, |
| 91 | ) -> Result<Value> { |
| 92 | let encoded = match &operation { |
| 93 | RuntimeOwnerRequest::CreateThread(body) |
| 94 | | RuntimeOwnerRequest::UpdateThread { body, .. } |
| 95 | | RuntimeOwnerRequest::StartTurn { body, .. } => Some(serde_json::to_vec(body)?.len()), |
| 96 | RuntimeOwnerRequest::HistoryImport(body) => Some(serde_json::to_vec(body)?.len()), |
| 97 | RuntimeOwnerRequest::HistoryMutate(body) => Some(serde_json::to_vec(body)?.len()), |
| 98 | RuntimeOwnerRequest::HistoryLookup(body) => Some(serde_json::to_vec(body)?.len()), |
| 99 | RuntimeOwnerRequest::HistoryRecover(body) => Some(serde_json::to_vec(body)?.len()), |
| 100 | _ => None, |
| 101 | }; |
| 102 | anyhow::ensure!( |
| 103 | encoded.is_none_or(|len| len <= MAX_CANONICAL_HISTORY_BYTES), |
| 104 | "encoded canonical control exceeds bound" |
| 105 | ); |
| 106 | owner_calls::execute(owner, operation).await |
| 107 | } |
| 108 | |
| 109 | #[cfg(any(unix, windows))] |
| 110 | async fn store_work<T, F>(work: F) -> Result<T> |
| 111 | where |
| 112 | T: Send + 'static, |
| 113 | F: FnOnce() -> Result<T> + Send + 'static, |
| 114 | { |
| 115 | codewhale_runtime::runtime_control::owner_work(work).await |
| 116 | } |
| 117 | #[cfg(not(any(unix, windows)))] |
| 118 | async fn store_work<T, F>(_work: F) -> Result<T> |
| 119 | where |
| 120 | T: Send + 'static, |
| 121 | F: FnOnce() -> Result<T> + Send + 'static, |
| 122 | { |
| 123 | bail!("canonical owner attachment is unsupported on this platform") |
| 124 | } |
| 125 | |
| 126 | struct LegacySource { |
| 127 | metadata: codewhale_state::ThreadMetadata, |
| 128 | previous: Option<String>, |
| 129 | receipt: Option<CanonicalThreadReceipt>, |
| 130 | history: Option<LegacyThreadHistory>, |
| 131 | } |
| 132 | |
| 133 | async fn legacy_source( |
| 134 | state: &AppState, |
| 135 | key: &str, |
| 136 | owner: &RuntimeOwnerReceipt, |
| 137 | ) -> Result<Option<(StateStore, LegacySource)>> { |
| 138 | let store = state.runtime.read().await.state_store().clone(); |
| 139 | let read_store = store.clone(); |
| 140 | let key = key.to_owned(); |
| 141 | let owner = owner.clone(); |
| 142 | let source = store_work(move || { |
| 143 | let Some(metadata) = read_store.get_thread(&key)? else { |
| 144 | return Ok(None); |
| 145 | }; |
| 146 | let previous = read_store.get_runtime_thread_link(&key)?; |
| 147 | let receipt = read_store.get_canonical_runtime_link(&key, &owner)?; |
| 148 | let history = if receipt.is_none() { |
| 149 | Some(read_store.snapshot_legacy_thread_history(&key)?) |
| 150 | } else { |
| 151 | None |
| 152 | }; |
| 153 | Ok(Some(LegacySource { |
| 154 | metadata, |
| 155 | previous, |
| 156 | receipt, |
| 157 | history, |
| 158 | })) |
| 159 | }) |
| 160 | .await?; |
| 161 | Ok(source.map(|source| (store, source))) |
| 162 | } |
| 163 | |
| 164 | fn migration_key(history: &LegacyThreadHistory) -> Result<String> { |
| 165 | // JSON tuple delimiters make this an exact source identity even when a |
| 166 | // legacy ID contains punctuation. Overlong identities visibly refuse. |
| 167 | let key = format!( |
| 168 | "legacy-import:{}", |
| 169 | serde_json::to_string(&(&history.state_store_id, &history.thread_id))? |
| 170 | ); |
| 171 | anyhow::ensure!( |
| 172 | key.len() <= 128 && !key.chars().any(char::is_control), |
| 173 | "legacy operation identity exceeds the owner's bound; source retained for recovery" |
| 174 | ); |
| 175 | Ok(key) |
| 176 | } |
| 177 | |
| 178 | fn verify_receipt( |
| 179 | receipt: &CanonicalThreadReceipt, |
| 180 | owner: &RuntimeOwnerReceipt, |
| 181 | operation: &str, |
| 182 | ) -> Result<()> { |
| 183 | anyhow::ensure!( |
| 184 | receipt.version == 1 |
| 185 | && receipt.data_dir == owner.data_dir |
| 186 | && receipt.execution_scope == owner.execution_scope |
| 187 | && receipt.operation_key == operation, |
| 188 | "canonical import receipt does not match the selected owner operation" |
| 189 | ); |
| 190 | Ok(()) |
| 191 | } |
| 192 | |
| 193 | fn check_workspace(state: &AppState, workspace: &Path) -> Result<()> { |
| 194 | if let Some(selected) = &state.frontend_workspace { |
| 195 | anyhow::ensure!( |
| 196 | workspace == selected, |
| 197 | "thread belongs to another selected frontend workspace; attach its owner scope" |
| 198 | ); |
| 199 | } |
| 200 | Ok(()) |
| 201 | } |
| 202 | |
| 203 | /// CAS. A cancelled waiter does not cancel publication of a committed result. |
| 204 | pub(super) async fn resolve( |
| 205 | state: &AppState, |
| 206 | key: &str, |
| 207 | execution: bool, |
| 208 | ) -> Result<(String, PathBuf)> { |
| 209 | let state = state.clone(); |
| 210 | let key = key.to_owned(); |
| 211 | anyhow::ensure!( |
| 212 | !key.is_empty() && key.len() <= 1024 && !key.chars().any(char::is_control), |
| 213 | "invalid thread identity" |
| 214 | ); |
| 215 | tokio::spawn(async move { resolve_owned(&state, &key, execution).await }) |
| 216 | .await |
| 217 | .context("canonical resolution task failed")? |
| 218 | } |
| 219 | |
| 220 | async fn resolve_owned(state: &AppState, key: &str, execution: bool) -> Result<(String, PathBuf)> { |
| 221 | let owner = owner(state)?; |
| 222 | let source = legacy_source(state, key, &owner).await?; |
| 223 | let native = owner_calls::captured(state)?; |
| 224 | let id = if let Some((store, source)) = source { |
| 225 | if execution || source.receipt.is_none() { |
| 226 | check_workspace(state, &source.metadata.cwd)?; |
| 227 | } |
| 228 | if let Some(receipt) = source.receipt { |
| 229 | receipt.runtime_thread_id |
| 230 | } else { |
| 231 | // Existing targets retain their canonical active branch; the |
| 232 | // owner admits complete legacy branches without replacing work. |
| 233 | let history = source.history.context("legacy source snapshot missing")?; |
| 234 | let operation = migration_key(&history)?; |
| 235 | let request_body = CanonicalHistoryImportRequest { |
| 236 | version: 1, |
| 237 | target_runtime_thread_id: source.previous.clone(), |
| 238 | operation_key: operation.clone(), |
| 239 | expected_data_dir: owner.data_dir.clone(), |
| 240 | expected_execution_scope: owner.execution_scope.clone(), |
| 241 | workspace: source.metadata.cwd, |
| 242 | model: None, |
| 243 | history: history.clone(), |
| 244 | }; |
| 245 | let value = request(&native, RuntimeOwnerRequest::HistoryImport(request_body)).await |
| 246 | .with_context(|| format!("canonical import {operation} may have committed; inspect or retry the same operation, never remint"))?; |
| 247 | let receipt: CanonicalThreadReceipt = serde_json::from_value(value)?; |
| 248 | verify_receipt(&receipt, &owner, &operation)?; |
| 249 | let publication = receipt.clone(); |
| 250 | let thread_key = key.to_owned(); |
| 251 | let previous = source.previous; |
| 252 | store_work(move || store.publish_canonical_runtime_link(&thread_key, previous.as_deref(), &history, &owner, &publication)).await |
| 253 | .context("canonical result committed but compatibility publication failed; result and source retained for recovery")?; |
| 254 | receipt.runtime_thread_id |
| 255 | } |
| 256 | } else { |
| 257 | key.to_owned() |
| 258 | }; |
| 259 | let value = request( |
| 260 | &native, |
| 261 | RuntimeOwnerRequest::GetThread { |
| 262 | thread_id: id.clone(), |
| 263 | }, |
| 264 | ) |
| 265 | .await |
| 266 | .context( |
| 267 | "canonical target is unavailable; existing identity retained, no replacement thread", |
| 268 | )?; |
| 269 | let record = value.get("thread").unwrap_or(&value); |
| 270 | anyhow::ensure!( |
| 271 | record.get("id").and_then(Value::as_str) == Some(id.as_str()), |
| 272 | "canonical resolution returned another target identity" |
| 273 | ); |
| 274 | let thread = project_thread(record, key)?; |
| 275 | if execution { |
| 276 | check_workspace(state, &thread.cwd)?; |
| 277 | } |
| 278 | Ok((id, thread.cwd)) |
| 279 | } |
| 280 | |
| 281 | fn timestamp(record: &Value, key: &str) -> Result<i64> { |
| 282 | Ok(chrono::DateTime::parse_from_rfc3339( |
| 283 | record |
| 284 | .get(key) |
| 285 | .and_then(Value::as_str) |
| 286 | .context("canonical timestamp missing")?, |
| 287 | )? |
| 288 | .timestamp()) |
| 289 | } |
| 290 | |
| 291 | fn project_thread(record: &Value, public_id: &str) -> Result<Thread> { |
| 292 | let id = record |
| 293 | .get("id") |
| 294 | .and_then(Value::as_str) |
| 295 | .context("canonical thread identity missing")?; |
| 296 | anyhow::ensure!(!id.is_empty(), "canonical thread identity missing"); |
| 297 | Ok(Thread { |
| 298 | id: public_id.to_owned(), |
| 299 | preview: String::new(), |
| 300 | ephemeral: false, |
| 301 | model_provider: record |
| 302 | .get("model_provider_id") |
| 303 | .or_else(|| record.get("model_provider")) |
| 304 | .and_then(Value::as_str) |
| 305 | .context("canonical provider identity missing")? |
| 306 | .to_owned(), |
| 307 | created_at: timestamp(record, "created_at")?, |
| 308 | updated_at: timestamp(record, "updated_at")?, |
| 309 | status: if record.get("archived").and_then(Value::as_bool) == Some(true) { |
| 310 | ThreadStatus::Archived |
| 311 | } else { |
| 312 | ThreadStatus::Idle |
| 313 | }, |
| 314 | path: None, |
| 315 | cwd: serde_json::from_value( |
| 316 | record |
| 317 | .get("workspace") |
| 318 | .cloned() |
| 319 | .context("canonical workspace missing")?, |
| 320 | )?, |
| 321 | cli_version: env!("CARGO_PKG_VERSION").to_owned(), |
| 322 | source: SessionSource::Api, |
| 323 | name: record |
| 324 | .get("title") |
| 325 | .and_then(Value::as_str) |
| 326 | .map(str::to_owned), |
| 327 | }) |
| 328 | } |
| 329 | |
| 330 | fn response(id: String) -> ThreadResponse { |
| 331 | ThreadResponse { |
| 332 | thread_id: id, |
| 333 | status: "ok".into(), |
| 334 | thread: None, |
| 335 | threads: Vec::new(), |
| 336 | goal: None, |
| 337 | model: None, |
| 338 | model_provider: None, |
| 339 | cwd: None, |
| 340 | approval_policy: None, |
| 341 | sandbox: None, |
| 342 | events: Vec::new(), |
| 343 | data: json!({}), |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | pub(super) async fn loaded(state: &AppState) -> Result<ThreadResponse> { |
| 348 | let native = owner_calls::captured(state)?; |
| 349 | let rows = request(&native, RuntimeOwnerRequest::LoadedThreads).await?; |
| 350 | let rows = rows |
| 351 | .as_array() |
| 352 | .context("loaded thread snapshot is not an array")?; |
| 353 | anyhow::ensure!( |
| 354 | rows.len() <= MAX_CANONICAL_HISTORY_ENTRIES, |
| 355 | "loaded thread snapshot exceeds bound" |
| 356 | ); |
| 357 | let active = running_ids(&native).await?; |
| 358 | let mut result = response("loaded".into()); |
| 359 | let mut ids = std::collections::HashSet::new(); |
| 360 | for row in rows { |
| 361 | let id = row |
| 362 | .get("id") |
| 363 | .and_then(Value::as_str) |
| 364 | .context("loaded thread identity missing")?; |
| 365 | anyhow::ensure!( |
| 366 | !id.is_empty() |
| 367 | && id.len() <= 1024 |
| 368 | && !id.chars().any(char::is_control) |
| 369 | && ids.insert(id.to_owned()), |
| 370 | "loaded thread identity invalid or repeated" |
| 371 | ); |
| 372 | let mut thread = project_thread(row, id)?; |
| 373 | if active.contains(id) && thread.status != ThreadStatus::Archived { |
| 374 | thread.status = ThreadStatus::Running; |
| 375 | } |
| 376 | result.threads.push(thread); |
| 377 | } |
| 378 | result.threads.sort_by(|left, right| left.id.cmp(&right.id)); |
| 379 | Ok(result) |
| 380 | } |
| 381 | |
| 382 | fn wire_thread(thread: Thread) -> codewhale_app_server_protocol::rpc::ThreadListItem { |
| 383 | use codewhale_app_server_protocol::rpc::{ThreadListItem, ThreadListSource, ThreadListStatus}; |
| 384 | ThreadListItem { |
| 385 | session_id: thread.id.clone(), |
| 386 | id: thread.id, |
| 387 | preview: thread.preview, |
| 388 | ephemeral: thread.ephemeral, |
| 389 | model_provider: thread.model_provider, |
| 390 | created_at: thread.created_at, |
| 391 | updated_at: thread.updated_at, |
| 392 | status: match thread.status { |
| 393 | ThreadStatus::Running => ThreadListStatus::Active { |
| 394 | active_flags: Vec::new(), |
| 395 | }, |
| 396 | ThreadStatus::Idle | ThreadStatus::Completed | ThreadStatus::Paused => { |
| 397 | ThreadListStatus::Idle |
| 398 | } |
| 399 | ThreadStatus::Archived => ThreadListStatus::NotLoaded, |
| 400 | ThreadStatus::Failed => ThreadListStatus::SystemError, |
| 401 | }, |
| 402 | cwd: thread.cwd.to_string_lossy().into_owned(), |
| 403 | cli_version: thread.cli_version, |
| 404 | source: match thread.source { |
| 405 | SessionSource::Interactive => ThreadListSource::Cli, |
| 406 | SessionSource::Api => ThreadListSource::AppServer, |
| 407 | SessionSource::Resume | SessionSource::Fork | SessionSource::Unknown => { |
| 408 | ThreadListSource::Unknown |
| 409 | } |
| 410 | }, |
| 411 | project_id: None, |
| 412 | turns: Vec::new(), |
| 413 | name: thread.name, |
| 414 | executor: None, |
| 415 | environment: None, |
| 416 | } |
| 417 | } |
| 418 | |
| 419 | pub(super) fn list_wire( |
| 420 | response: ThreadResponse, |
| 421 | ) -> codewhale_app_server_protocol::rpc::ThreadListResponse { |
| 422 | codewhale_app_server_protocol::rpc::ThreadListResponse { |
| 423 | data: response.threads.into_iter().map(wire_thread).collect(), |
| 424 | next_cursor: None, |
| 425 | backwards_cursor: None, |
| 426 | } |
| 427 | } |
| 428 | |
| 429 | #[derive(serde::Deserialize)] |
| 430 | struct WireTurnRow { |
| 431 | id: String, |
| 432 | status: String, |
| 433 | started_at: Option<chrono::DateTime<chrono::Utc>>, |
| 434 | ended_at: Option<chrono::DateTime<chrono::Utc>>, |
| 435 | duration_ms: Option<u64>, |
| 436 | error: Option<String>, |
| 437 | #[serde(default)] |
| 438 | item_ids: Vec<String>, |
| 439 | } |
| 440 | |
| 441 | #[derive(serde::Deserialize)] |
| 442 | struct WireItemRow { |
| 443 | id: String, |
| 444 | turn_id: String, |
| 445 | kind: String, |
| 446 | summary: String, |
| 447 | detail: Option<String>, |
| 448 | } |
| 449 | |
| 450 | fn wire_turns(data: &Value) -> Result<Vec<codewhale_app_server_protocol::rpc::ThreadTurn>> { |
| 451 | use codewhale_app_server_protocol::rpc::{ |
| 452 | ThreadTurn, ThreadTurnError, ThreadTurnItem, ThreadTurnItemsView, ThreadTurnStatus, |
| 453 | ThreadUserInput, |
| 454 | }; |
| 455 | let turns: Vec<WireTurnRow> = |
| 456 | serde_json::from_value(data.get("turns").cloned().unwrap_or(Value::Null)) |
| 457 | .context("canonical turn records are malformed")?; |
| 458 | let items: Vec<WireItemRow> = |
| 459 | serde_json::from_value(data.get("items").cloned().unwrap_or(Value::Null)) |
| 460 | .context("canonical item records are malformed")?; |
| 461 | anyhow::ensure!( |
| 462 | turns.len() <= MAX_CANONICAL_HISTORY_ENTRIES |
| 463 | && items.len() <= MAX_CANONICAL_HISTORY_ENTRIES, |
| 464 | "canonical turn history exceeds bound" |
| 465 | ); |
| 466 | turns |
| 467 | .into_iter() |
| 468 | .map(|turn| { |
| 469 | let mut own: Vec<&WireItemRow> = items |
| 470 | .iter() |
| 471 | .filter(|item| item.turn_id == turn.id) |
| 472 | .collect(); |
| 473 | own.sort_by_key(|item| { |
| 474 | turn.item_ids |
| 475 | .iter() |
| 476 | .position(|id| *id == item.id) |
| 477 | .unwrap_or(usize::MAX) |
| 478 | }); |
| 479 | let mut complete = true; |
| 480 | let mut mapped = Vec::with_capacity(own.len()); |
| 481 | for item in own { |
| 482 | let text = item.detail.clone().unwrap_or_else(|| item.summary.clone()); |
| 483 | let id = item.id.clone(); |
| 484 | match item.kind.as_str() { |
| 485 | "user_message" => mapped.push(ThreadTurnItem::UserMessage { |
| 486 | id, |
| 487 | content: if text.is_empty() { |
| 488 | Vec::new() |
| 489 | } else { |
| 490 | vec![ThreadUserInput::Text { text }] |
| 491 | }, |
| 492 | }), |
| 493 | "agent_message" => mapped.push(ThreadTurnItem::AgentMessage { id, text }), |
| 494 | "agent_reasoning" => mapped.push(ThreadTurnItem::Reasoning { |
| 495 | id, |
| 496 | content: item.detail.iter().cloned().collect(), |
| 497 | }), |
| 498 | "context_compaction" => mapped.push(ThreadTurnItem::ContextCompaction { id }), |
| 499 | _ => complete = false, |
| 500 | } |
| 501 | } |
| 502 | Ok(ThreadTurn { |
| 503 | id: turn.id, |
| 504 | items: mapped, |
| 505 | items_view: if complete { |
| 506 | ThreadTurnItemsView::Full |
| 507 | } else { |
| 508 | ThreadTurnItemsView::Summary |
| 509 | }, |
| 510 | status: match turn.status.as_str() { |
| 511 | "completed" => ThreadTurnStatus::Completed, |
| 512 | "failed" => ThreadTurnStatus::Failed, |
| 513 | "interrupted" | "canceled" => ThreadTurnStatus::Interrupted, |
| 514 | "queued" | "in_progress" => ThreadTurnStatus::InProgress, |
| 515 | other => bail!("unknown canonical turn status {other}"), |
| 516 | }, |
| 517 | error: turn.error.map(|message| ThreadTurnError { message }), |
| 518 | started_at: turn.started_at.map(|at| at.timestamp()), |
| 519 | completed_at: turn.ended_at.map(|at| at.timestamp()), |
| 520 | duration_ms: turn.duration_ms.and_then(|ms| i64::try_from(ms).ok()), |
| 521 | }) |
| 522 | }) |
| 523 | .collect() |
| 524 | } |
| 525 | |
| 526 | pub(super) fn start_params( |
| 527 | params: codewhale_app_server_protocol::rpc::ThreadStartParams, |
| 528 | ) -> std::result::Result<codewhale_protocol::ThreadStartParams, DispatchError> { |
| 529 | let refused: Vec<&str> = [ |
| 530 | ("ephemeral", params.ephemeral == Some(true)), |
| 531 | ("approvalPolicy", params.approval_policy.is_some()), |
| 532 | ("approvalsReviewer", params.approvals_reviewer.is_some()), |
| 533 | ("sandbox", params.sandbox.is_some()), |
| 534 | ("config", params.config.is_some()), |
| 535 | ("baseInstructions", params.base_instructions.is_some()), |
| 536 | ( |
| 537 | "developerInstructions", |
| 538 | params.developer_instructions.is_some(), |
| 539 | ), |
| 540 | ("serviceName", params.service_name.is_some()), |
| 541 | ("serviceTier", params.service_tier.is_some()), |
| 542 | ("sessionStartSource", params.session_start_source.is_some()), |
| 543 | ] |
| 544 | .into_iter() |
| 545 | .filter_map(|(name, set)| set.then_some(name)) |
| 546 | .collect(); |
| 547 | if !refused.is_empty() { |
| 548 | return Err(DispatchError { |
| 549 | wire: RpcErrorDetails { |
| 550 | code: -32602, |
| 551 | message: format!( |
| 552 | "thread/start cannot honor {}: threads are durable and tool-free with a fixed read-only sandbox, and these settings are not applied", |
| 553 | refused.join(", ") |
| 554 | ), |
| 555 | data: Some(json!({ |
| 556 | "error": "unsupported_thread_start_parameter", |
| 557 | "parameters": refused, |
| 558 | })), |
| 559 | }, |
| 560 | transport_error: None, |
| 561 | }); |
| 562 | } |
| 563 | Ok(codewhale_protocol::ThreadStartParams { |
| 564 | operation_key: Some( |
| 565 | params |
| 566 | .operation_key |
| 567 | .unwrap_or_else(|| Uuid::new_v4().to_string()), |
| 568 | ), |
| 569 | model: params.model, |
| 570 | model_provider: params.model_provider, |
| 571 | cwd: params.cwd.map(PathBuf::from), |
| 572 | persist_extended_history: false, |
| 573 | }) |
| 574 | } |
| 575 | |
| 576 | pub(super) fn start_wire( |
| 577 | response: ThreadResponse, |
| 578 | ) -> Result<codewhale_app_server_protocol::rpc::ThreadStartResponse> { |
| 579 | let thread = wire_thread( |
| 580 | response |
| 581 | .thread |
| 582 | .context("canonical start returned no thread")?, |
| 583 | ); |
| 584 | Ok(codewhale_app_server_protocol::rpc::ThreadStartResponse { |
| 585 | model: response |
| 586 | .model |
| 587 | .context("canonical start returned no model")?, |
| 588 | model_provider: thread.model_provider.clone(), |
| 589 | cwd: thread.cwd.clone(), |
| 590 | approval_policy: "never".to_owned(), |
| 591 | approvals_reviewer: "user".to_owned(), |
| 592 | sandbox: codewhale_app_server_protocol::rpc::ThreadSandboxPolicy::ReadOnly, |
| 593 | thread, |
| 594 | }) |
| 595 | } |
| 596 | |
| 597 | pub(super) fn read_wire( |
| 598 | response: ThreadResponse, |
| 599 | include_turns: bool, |
| 600 | ) -> Result<codewhale_app_server_protocol::rpc::ThreadReadResponse> { |
| 601 | let thread = response |
| 602 | .thread |
| 603 | .context("canonical read returned no thread")?; |
| 604 | let mut thread = wire_thread(thread); |
| 605 | if include_turns { |
| 606 | thread.turns = wire_turns(&response.data)? |
| 607 | .into_iter() |
| 608 | .map(serde_json::to_value) |
| 609 | .collect::<std::result::Result<_, _>>()?; |
| 610 | } |
| 611 | Ok(codewhale_app_server_protocol::rpc::ThreadReadResponse { thread }) |
| 612 | } |
| 613 | |
| 614 | async fn list( |
| 615 | state: &AppState, |
| 616 | params: codewhale_protocol::ThreadListParams, |
| 617 | ) -> Result<ThreadResponse> { |
| 618 | let owner = owner(state)?; |
| 619 | let store = state.runtime.read().await.state_store().clone(); |
| 620 | let legacy = store_work(move || { |
| 621 | let rows = store.list_threads(codewhale_state::ThreadListFilters { |
| 622 | include_archived: true, |
| 623 | limit: Some(MAX_CANONICAL_HISTORY_ENTRIES + 1), |
| 624 | })?; |
| 625 | anyhow::ensure!( |
| 626 | rows.len() <= MAX_CANONICAL_HISTORY_ENTRIES, |
| 627 | "legacy metadata list exceeds bound" |
| 628 | ); |
| 629 | rows.into_iter() |
| 630 | .map(|row| { |
| 631 | let receipt = store.get_canonical_runtime_link(&row.id, &owner)?; |
| 632 | Ok((row, receipt)) |
| 633 | }) |
| 634 | .collect::<Result<Vec<_>>>() |
| 635 | }) |
| 636 | .await?; |
| 637 | let limit = params.limit.unwrap_or(50); |
| 638 | anyhow::ensure!( |
| 639 | limit <= MAX_CANONICAL_HISTORY_ENTRIES, |
| 640 | "thread list exceeds bound" |
| 641 | ); |
| 642 | let native = owner_calls::captured(state)?; |
| 643 | let rows = request( |
| 644 | &native, |
| 645 | RuntimeOwnerRequest::ListThreads { |
| 646 | include_archived: true, |
| 647 | limit: MAX_CANONICAL_HISTORY_ENTRIES + 1, |
| 648 | }, |
| 649 | ) |
| 650 | .await?; |
| 651 | let rows = rows |
| 652 | .as_array() |
| 653 | .context("canonical thread list is not an array")?; |
| 654 | anyhow::ensure!( |
| 655 | rows.len() <= MAX_CANONICAL_HISTORY_ENTRIES, |
| 656 | "canonical thread list exceeds bound" |
| 657 | ); |
| 658 | let mut canonical = HashMap::new(); |
| 659 | let active = running_ids(&native).await?; |
| 660 | for row in rows { |
| 661 | let id = row |
| 662 | .get("id") |
| 663 | .and_then(Value::as_str) |
| 664 | .context("canonical list identity missing")?; |
| 665 | anyhow::ensure!( |
| 666 | canonical.insert(id.to_owned(), row).is_none(), |
| 667 | "duplicate canonical list identity" |
| 668 | ); |
| 669 | } |
| 670 | let mut result = response("list".into()); |
| 671 | let mut aliased = std::collections::HashSet::new(); |
| 672 | for (metadata, receipt) in legacy { |
| 673 | if let Some(receipt) = receipt { |
| 674 | let row = canonical |
| 675 | .get(&receipt.runtime_thread_id) |
| 676 | .context("bound compatibility alias has no canonical record; recovery required")?; |
| 677 | let mut thread = project_thread(row, &metadata.id)?; |
| 678 | if active.contains(&receipt.runtime_thread_id) |
| 679 | && thread.status != ThreadStatus::Archived |
| 680 | { |
| 681 | thread.status = ThreadStatus::Running; |
| 682 | } |
| 683 | thread.preview = metadata.preview; |
| 684 | thread.source = serde_json::from_value(serde_json::to_value(metadata.source)?)?; |
| 685 | if params.include_archived || thread.status != ThreadStatus::Archived { |
| 686 | result.threads.push(thread); |
| 687 | } |
| 688 | aliased.insert(receipt.runtime_thread_id); |
| 689 | } else { |
| 690 | // Read projection only: listing never imports or mutates history. |
| 691 | if params.include_archived || !metadata.archived { |
| 692 | result |
| 693 | .threads |
| 694 | .push(serde_json::from_value(serde_json::to_value(metadata)?)?); |
| 695 | } |
| 696 | } |
| 697 | } |
| 698 | for (id, row) in canonical { |
| 699 | if !aliased.contains(&id) { |
| 700 | let mut thread = project_thread(row, &id)?; |
| 701 | if active.contains(&id) && thread.status != ThreadStatus::Archived { |
| 702 | thread.status = ThreadStatus::Running; |
| 703 | } |
| 704 | if params.include_archived || thread.status != ThreadStatus::Archived { |
| 705 | result.threads.push(thread); |
| 706 | } |
| 707 | } |
| 708 | } |
| 709 | anyhow::ensure!( |
| 710 | result.threads.len() <= MAX_CANONICAL_HISTORY_ENTRIES, |
| 711 | "combined thread list exceeds bound" |
| 712 | ); |
| 713 | result.threads.sort_by(|a, b| { |
| 714 | b.updated_at |
| 715 | .cmp(&a.updated_at) |
| 716 | .then_with(|| a.id.cmp(&b.id)) |
| 717 | }); |
| 718 | result.threads.truncate(limit); // Explicit caller list limit; history is never truncated. |
| 719 | Ok(result) |
| 720 | } |
| 721 | |
| 722 | pub(super) async fn handle( |
| 723 | state: &AppState, |
| 724 | request_value: ThreadRequest, |
| 725 | ) -> std::result::Result<ThreadResponse, DispatchError> { |
| 726 | let key = match &request_value { |
| 727 | ThreadRequest::Read(p) => Some(p.thread_id.as_str()), |
| 728 | ThreadRequest::SetName(p) => Some(p.thread_id.as_str()), |
| 729 | ThreadRequest::Archive { thread_id } | ThreadRequest::Unarchive { thread_id } => { |
| 730 | Some(thread_id.as_str()) |
| 731 | } |
| 732 | ThreadRequest::GoalGet(p) => Some(p.thread_id.as_str()), |
| 733 | ThreadRequest::GoalSet(p) => Some(p.thread_id.as_str()), |
| 734 | ThreadRequest::GoalClear(p) => Some(p.thread_id.as_str()), |
| 735 | ThreadRequest::Resume(p) => Some(p.thread_id.as_str()), |
| 736 | ThreadRequest::Fork(p) => Some(p.thread_id.as_str()), |
| 737 | ThreadRequest::GoalRecordProgress(p) => Some(p.thread_id.as_str()), |
| 738 | ThreadRequest::Message { thread_id, .. } => Some(thread_id.as_str()), |
| 739 | ThreadRequest::Create { .. } | ThreadRequest::Start(_) | ThreadRequest::List(_) => None, |
| 740 | } |
| 741 | .map(str::to_owned); |
| 742 | let result = handle_owned(state, request_value) |
| 743 | .await |
| 744 | .map_err(|error| rpc_error(error, key.as_deref()))?; |
| 745 | if serde_json::to_vec(&result) |
| 746 | .map_err(|e| DispatchError::internal(e.to_string()))? |
| 747 | .len() |
| 748 | > MAX_CANONICAL_HISTORY_BYTES |
| 749 | { |
| 750 | let message = "complete thread response exceeds transport bound; no truncation"; |
| 751 | let error = result |
| 752 | .data |
| 753 | .get("receipt") |
| 754 | .and_then(|value| serde_json::from_value::<CanonicalThreadReceipt>(value.clone()).ok()) |
| 755 | .map(|receipt| committed_failure(&receipt, anyhow!(message))) |
| 756 | .unwrap_or_else(|| anyhow!(message)); |
| 757 | return Err(DispatchError::runtime_unavailable(format!("{error:#}"))); |
| 758 | } |
| 759 | Ok(result) |
| 760 | } |
| 761 | |
| 762 | pub(super) fn rpc_error(error: anyhow::Error, key: Option<&str>) -> DispatchError { |
| 763 | if error.downcast_ref::<CommittedControlFailure>().is_some() { |
| 764 | DispatchError::runtime_unavailable(format!("{error:#}")) |
| 765 | } else if error |
| 766 | .downcast_ref::<RuntimeOwnerFailure>() |
| 767 | .is_some_and(|error| error.status == StatusCode::NOT_FOUND.as_u16()) |
| 768 | { |
| 769 | DispatchError::thread_not_found(key.unwrap_or("unknown")) |
| 770 | } else { |
| 771 | DispatchError::runtime_unavailable(format!("{error:#}")) |
| 772 | } |
| 773 | } |
| 774 | |
| 775 | async fn running_ids( |
| 776 | native: &Arc<dyn RuntimeOwnerFrontend>, |
| 777 | ) -> Result<std::collections::HashSet<String>> { |
| 778 | let value = request(native, RuntimeOwnerRequest::RunningThreads).await?; |
| 779 | let rows = value |
| 780 | .as_array() |
| 781 | .context("canonical running list is not an array")?; |
| 782 | anyhow::ensure!( |
| 783 | rows.len() <= MAX_CANONICAL_HISTORY_ENTRIES, |
| 784 | "canonical running list exceeds bound" |
| 785 | ); |
| 786 | rows.iter() |
| 787 | .map(|row| { |
| 788 | row.get("thread_id") |
| 789 | .and_then(Value::as_str) |
| 790 | .map(str::to_owned) |
| 791 | .context("canonical running identity missing") |
| 792 | }) |
| 793 | .collect() |
| 794 | } |
| 795 | |
| 796 | fn operation_key(key: Option<String>) -> Result<String> { |
| 797 | let key = key.context("canonical mutation requires a client-captured operation_key; retain it when retrying an uncertain outcome")?; |
| 798 | anyhow::ensure!( |
| 799 | !key.is_empty() && key.len() <= 128 && !key.chars().any(char::is_control), |
| 800 | "invalid canonical operation_key" |
| 801 | ); |
| 802 | Ok(key) |
| 803 | } |
| 804 | |
| 805 | fn selected_workspace(state: &AppState, explicit: Option<PathBuf>) -> Result<PathBuf> { |
| 806 | let workspace = explicit.or_else(|| state.frontend_workspace.clone()).context( |
| 807 | "canonical mutation needs the owner's acknowledged workspace or an explicit checked selection", |
| 808 | )?; |
| 809 | check_workspace(state, &workspace)?; |
| 810 | Ok(workspace) |
| 811 | } |
| 812 | |
| 813 | async fn full_snapshot( |
| 814 | state: &AppState, |
| 815 | native: &Arc<dyn RuntimeOwnerFrontend>, |
| 816 | id: &str, |
| 817 | ) -> Result<CanonicalThreadSnapshot> { |
| 818 | let snapshot: CanonicalThreadSnapshot = serde_json::from_value( |
| 819 | request( |
| 820 | native, |
| 821 | RuntimeOwnerRequest::HistorySnapshot { |
| 822 | thread_id: id.to_owned(), |
| 823 | }, |
| 824 | ) |
| 825 | .await?, |
| 826 | )?; |
| 827 | let selected = owner(state)?; |
| 828 | anyhow::ensure!( |
| 829 | snapshot.version == 1 |
| 830 | && snapshot.data_dir == selected.data_dir |
| 831 | && snapshot.execution_scope == selected.execution_scope |
| 832 | && snapshot.runtime_thread_id == id, |
| 833 | "canonical full history response has another owner/thread binding" |
| 834 | ); |
| 835 | Ok(snapshot) |
| 836 | } |
| 837 | |
| 838 | async fn mutate( |
| 839 | state: &AppState, |
| 840 | operation: String, |
| 841 | workspace: PathBuf, |
| 842 | mutation: CanonicalThreadMutation, |
| 843 | status: &str, |
| 844 | public_alias: Option<&str>, |
| 845 | ) -> Result<ThreadResponse> { |
| 846 | let owner = owner(state)?; |
| 847 | check_workspace(state, &workspace)?; |
| 848 | let native = owner_calls::captured(state)?; |
| 849 | let body = CanonicalThreadMutationRequest { |
| 850 | version: 1, |
| 851 | operation_key: operation.clone(), |
| 852 | expected_data_dir: owner.data_dir.clone(), |
| 853 | expected_execution_scope: owner.execution_scope.clone(), |
| 854 | workspace, |
| 855 | mutation, |
| 856 | }; |
| 857 | let value = request(&native, RuntimeOwnerRequest::HistoryMutate(body)) |
| 858 | .await |
| 859 | .with_context(|| format!("canonical operation {operation} may have committed; retain this key, no automatic replay or replacement"))?; |
| 860 | let receipt: CanonicalThreadReceipt = serde_json::from_value(value).with_context(|| { |
| 861 | format!("canonical operation {operation} returned an invalid result; retain this key, no replacement") |
| 862 | })?; |
| 863 | verify_receipt(&receipt, &owner, &operation).with_context(|| { |
| 864 | format!("canonical operation {operation} returned an unbound receipt; retain this key without replay or replacement") |
| 865 | })?; |
| 866 | present_receipt(&native, receipt, status, public_alias).await |
| 867 | } |
| 868 | |
| 869 | async fn present_receipt( |
| 870 | native: &Arc<dyn RuntimeOwnerFrontend>, |
| 871 | receipt: CanonicalThreadReceipt, |
| 872 | status: &str, |
| 873 | public_alias: Option<&str>, |
| 874 | ) -> Result<ThreadResponse> { |
| 875 | let public_id = public_alias.unwrap_or(&receipt.runtime_thread_id); |
| 876 | let value = request( |
| 877 | native, |
| 878 | RuntimeOwnerRequest::GetThread { |
| 879 | thread_id: receipt.runtime_thread_id.clone(), |
| 880 | }, |
| 881 | ) |
| 882 | .await |
| 883 | .map_err(|error| committed_failure(&receipt, error.context("metadata is unavailable")))?; |
| 884 | let record = value.get("thread").unwrap_or(&value); |
| 885 | if record.get("id").and_then(Value::as_str) != Some(receipt.runtime_thread_id.as_str()) { |
| 886 | return Err(committed_failure( |
| 887 | &receipt, |
| 888 | anyhow!("another metadata identity was returned"), |
| 889 | )); |
| 890 | } |
| 891 | let mut result = response(public_id.to_owned()); |
| 892 | result.status = status.to_owned(); |
| 893 | result.thread = Some(project_thread(record, public_id).map_err(|error| { |
| 894 | committed_failure(&receipt, error.context("metadata projection failed")) |
| 895 | })?); |
| 896 | result.model = record |
| 897 | .get("model") |
| 898 | .and_then(Value::as_str) |
| 899 | .map(str::to_owned); |
| 900 | result.model_provider = result |
| 901 | .thread |
| 902 | .as_ref() |
| 903 | .map(|thread| thread.model_provider.clone()); |
| 904 | result.cwd = result.thread.as_ref().map(|thread| thread.cwd.clone()); |
| 905 | result.data = json!({"receipt":receipt,"thread":record}); |
| 906 | Ok(result) |
| 907 | } |
| 908 | |
| 909 | async fn source_identity(state: &AppState, key: &str) -> Result<String> { |
| 910 | let selected = owner(state)?; |
| 911 | let store = state.runtime.read().await.state_store().clone(); |
| 912 | let key = key.to_owned(); |
| 913 | store_work(move || { |
| 914 | if let Some(receipt) = store.get_canonical_runtime_link(&key, &selected)? { |
| 915 | Ok(receipt.runtime_thread_id) |
| 916 | } else { |
| 917 | Ok(store.get_runtime_thread_link(&key)?.unwrap_or(key)) |
| 918 | } |
| 919 | }) |
| 920 | .await |
| 921 | } |
| 922 | |
| 923 | async fn recover_operation( |
| 924 | state: &AppState, |
| 925 | operation: &str, |
| 926 | workspace: &Path, |
| 927 | kind: CanonicalThreadOperationKind, |
| 928 | source: Option<&str>, |
| 929 | status: &str, |
| 930 | public_alias: Option<&str>, |
| 931 | ) -> Result<Option<ThreadResponse>> { |
| 932 | let selected = owner(state)?; |
| 933 | let native = owner_calls::captured(state)?; |
| 934 | let body = CanonicalThreadOperationLookup { |
| 935 | version: 1, |
| 936 | operation_key: operation.to_owned(), |
| 937 | expected_data_dir: selected.data_dir.clone(), |
| 938 | expected_execution_scope: selected.execution_scope.clone(), |
| 939 | workspace: workspace.to_owned(), |
| 940 | }; |
| 941 | let outcome: CanonicalThreadOperationStatus = serde_json::from_value(request( |
| 942 | &native, RuntimeOwnerRequest::HistoryLookup(body.clone()), |
| 943 | ).await.with_context(|| format!("canonical key lookup {operation} is unavailable; retain key, no absence inference or replacement"))?) |
| 944 | .with_context(|| format!("canonical key lookup {operation} returned an invalid result; retain key, no absence inference or replacement"))?; |
| 945 | let (receipt, association, committed) = match outcome { |
| 946 | CanonicalThreadOperationStatus::Absent => return Ok(None), |
| 947 | CanonicalThreadOperationStatus::Pending { |
| 948 | receipt, |
| 949 | association, |
| 950 | } => (receipt, association, false), |
| 951 | CanonicalThreadOperationStatus::Committed { |
| 952 | receipt, |
| 953 | association, |
| 954 | } => (receipt, association, true), |
| 955 | }; |
| 956 | verify_receipt(&receipt, &selected, operation)?; |
| 957 | if association.kind != kind || association.source_runtime_thread_id.as_deref() != source { |
| 958 | let error = anyhow!("retained key belongs to another action or source; no new operation"); |
| 959 | return Err(if committed { |
| 960 | committed_failure(&receipt, error) |
| 961 | } else { |
| 962 | error.context(format!( |
| 963 | "canonical operation {operation} is pending; inspect reserved thread {}, no replay", |
| 964 | receipt.runtime_thread_id |
| 965 | )) |
| 966 | }); |
| 967 | } |
| 968 | if !committed { |
| 969 | // Lookup is read-only. Explicit retained-key recovery can settle only |
| 970 | // the owner's already prepared target, never reconstruct this source. |
| 971 | let recovery = CanonicalThreadOperationRecovery { |
| 972 | operation: body, |
| 973 | association: association.clone(), |
| 974 | }; |
| 975 | let recovered: CanonicalThreadOperationStatus = serde_json::from_value( |
| 976 | request( |
| 977 | &native, RuntimeOwnerRequest::HistoryRecover(recovery), |
| 978 | ) |
| 979 | .await |
| 980 | .with_context(|| format!( |
| 981 | "canonical operation {operation} remains uncertain as thread {} / session {}; retain key, no resume, replay or replacement", |
| 982 | receipt.runtime_thread_id, receipt.session_id |
| 983 | ))?, |
| 984 | ).with_context(|| format!( |
| 985 | "canonical operation {operation} returned an invalid recovery result for reserved thread {} / session {}; retain key, no replacement", |
| 986 | receipt.runtime_thread_id, receipt.session_id |
| 987 | ))?; |
| 988 | match recovered { |
| 989 | CanonicalThreadOperationStatus::Committed { |
| 990 | receipt: recovered_receipt, |
| 991 | association: recovered_association, |
| 992 | } => { |
| 993 | anyhow::ensure!( |
| 994 | recovered_receipt == receipt && recovered_association == association, |
| 995 | "canonical recovery changed retained operation {operation}; reserved thread {} / session {}, no replay", |
| 996 | receipt.runtime_thread_id, |
| 997 | receipt.session_id |
| 998 | ); |
| 999 | } |
| 1000 | CanonicalThreadOperationStatus::Pending { |
| 1001 | receipt: pending_receipt, |
| 1002 | association: pending_association, |
| 1003 | } => { |
| 1004 | anyhow::ensure!( |
| 1005 | pending_receipt == receipt && pending_association == association, |
| 1006 | "canonical recovery changed retained operation {operation}; no replay" |
| 1007 | ); |
| 1008 | bail!( |
| 1009 | "canonical operation {operation} is pending as thread {} / session {}; no resume, replay or replacement", |
| 1010 | receipt.runtime_thread_id, |
| 1011 | receipt.session_id |
| 1012 | ); |
| 1013 | } |
| 1014 | CanonicalThreadOperationStatus::Absent => bail!( |
| 1015 | "canonical retained operation {operation} disappeared as thread {} / session {}; no resume, replay or replacement", |
| 1016 | receipt.runtime_thread_id, |
| 1017 | receipt.session_id |
| 1018 | ), |
| 1019 | } |
| 1020 | } |
| 1021 | present_receipt(&native, receipt, status, public_alias) |
| 1022 | .await |
| 1023 | .map(Some) |
| 1024 | } |
| 1025 | |
| 1026 | async fn resume_or_fork( |
| 1027 | state: &AppState, |
| 1028 | key: &str, |
| 1029 | operation: String, |
| 1030 | cwd: Option<PathBuf>, |
| 1031 | fork: bool, |
| 1032 | options: CanonicalHistoryOptions, |
| 1033 | ) -> Result<ThreadResponse> { |
| 1034 | let selected_workspace = selected_workspace(state, cwd.clone())?; |
| 1035 | let expected_source = source_identity(state, key).await?; |
| 1036 | if let Some(result) = recover_operation( |
| 1037 | state, |
| 1038 | &operation, |
| 1039 | &selected_workspace, |
| 1040 | if fork { |
| 1041 | CanonicalThreadOperationKind::Fork |
| 1042 | } else { |
| 1043 | CanonicalThreadOperationKind::Resume |
| 1044 | }, |
| 1045 | Some(&expected_source), |
| 1046 | if fork { "forked" } else { "resumed" }, |
| 1047 | (!fork).then_some(key), |
| 1048 | ) |
| 1049 | .await? |
| 1050 | { |
| 1051 | return Ok(result); |
| 1052 | } |
| 1053 | let (id, workspace) = resolve(state, key, !fork).await?; |
| 1054 | if let Some(cwd) = cwd { |
| 1055 | anyhow::ensure!( |
| 1056 | fork || cwd == workspace, |
| 1057 | "moving a history source to another workspace requires the canonical owner's explicit admission" |
| 1058 | ); |
| 1059 | } |
| 1060 | let native = owner_calls::captured(state)?; |
| 1061 | let snapshot = full_snapshot(state, &native, &id).await?; |
| 1062 | let source = CanonicalHistorySource::Thread { |
| 1063 | runtime_thread_id: id, |
| 1064 | expected_document_digest: snapshot.document_digest, |
| 1065 | }; |
| 1066 | let mutation = if fork { |
| 1067 | CanonicalThreadMutation::Fork { |
| 1068 | source, |
| 1069 | options, |
| 1070 | selected_entry_id: None, |
| 1071 | } |
| 1072 | } else { |
| 1073 | CanonicalThreadMutation::Resume { source, options } |
| 1074 | }; |
| 1075 | // Only resume preserves the old public alias. Fork returns its new actual |
| 1076 | // canonical identity and never creates another SQLite transcript writer. |
| 1077 | mutate( |
| 1078 | state, |
| 1079 | operation, |
| 1080 | if fork { selected_workspace } else { workspace }, |
| 1081 | mutation, |
| 1082 | if fork { "forked" } else { "resumed" }, |
| 1083 | (!fork).then_some(key), |
| 1084 | ) |
| 1085 | .await |
| 1086 | } |
| 1087 | |
| 1088 | fn history_parameters( |
| 1089 | params: Value, |
| 1090 | ) -> Result<(String, String, Option<PathBuf>, CanonicalHistoryOptions)> { |
| 1091 | let mut fields = params |
| 1092 | .as_object() |
| 1093 | .cloned() |
| 1094 | .context("invalid typed history control")?; |
| 1095 | let key = serde_json::from_value( |
| 1096 | fields |
| 1097 | .remove("thread_id") |
| 1098 | .context("thread identity missing")?, |
| 1099 | )?; |
| 1100 | let operation = operation_key( |
| 1101 | fields |
| 1102 | .remove("operation_key") |
| 1103 | .map(serde_json::from_value) |
| 1104 | .transpose()?, |
| 1105 | )?; |
| 1106 | let cwd = fields |
| 1107 | .get("cwd") |
| 1108 | .cloned() |
| 1109 | .map(serde_json::from_value) |
| 1110 | .transpose()?; |
| 1111 | let source_path = fields |
| 1112 | .remove("path") |
| 1113 | .map(serde_json::from_value) |
| 1114 | .transpose()?; |
| 1115 | let offered_history = fields |
| 1116 | .remove("history") |
| 1117 | .map(serde_json::from_value) |
| 1118 | .transpose()? |
| 1119 | .unwrap_or_default(); |
| 1120 | // Complete canonical history is durable for both values of the old flag. |
| 1121 | fields.remove("persist_extended_history"); |
| 1122 | Ok(( |
| 1123 | key, |
| 1124 | operation, |
| 1125 | cwd, |
| 1126 | CanonicalHistoryOptions { |
| 1127 | offered_history, |
| 1128 | overrides: Value::Object(fields), |
| 1129 | source_path, |
| 1130 | expected_session_goal_digest: None, |
| 1131 | }, |
| 1132 | )) |
| 1133 | } |
| 1134 | |
| 1135 | async fn creation(state: &AppState, request_value: ThreadRequest) -> Result<ThreadResponse> { |
| 1136 | match request_value { |
| 1137 | ThreadRequest::Create { metadata } => { |
| 1138 | let mut config = metadata.as_object().cloned().context( |
| 1139 | "thread/create metadata must carry an operation_key and existing create-thread fields", |
| 1140 | )?; |
| 1141 | let operation = operation_key( |
| 1142 | config |
| 1143 | .remove("operation_key") |
| 1144 | .map(serde_json::from_value) |
| 1145 | .transpose()?, |
| 1146 | )?; |
| 1147 | let explicit = config |
| 1148 | .get("workspace") |
| 1149 | .cloned() |
| 1150 | .map(serde_json::from_value) |
| 1151 | .transpose()?; |
| 1152 | let workspace = selected_workspace(state, explicit)?; |
| 1153 | if let Some(result) = recover_operation( |
| 1154 | state, |
| 1155 | &operation, |
| 1156 | &workspace, |
| 1157 | CanonicalThreadOperationKind::Create, |
| 1158 | None, |
| 1159 | "created", |
| 1160 | None, |
| 1161 | ) |
| 1162 | .await? |
| 1163 | { |
| 1164 | return Ok(result); |
| 1165 | } |
| 1166 | config.insert("workspace".into(), serde_json::to_value(&workspace)?); |
| 1167 | mutate( |
| 1168 | state, |
| 1169 | operation, |
| 1170 | workspace, |
| 1171 | CanonicalThreadMutation::Create { |
| 1172 | config: Value::Object(config), |
| 1173 | }, |
| 1174 | "created", |
| 1175 | None, |
| 1176 | ) |
| 1177 | .await |
| 1178 | } |
| 1179 | ThreadRequest::Start(params) => { |
| 1180 | let operation = operation_key(params.operation_key)?; |
| 1181 | let workspace = selected_workspace(state, params.cwd)?; |
| 1182 | if let Some(result) = recover_operation( |
| 1183 | state, |
| 1184 | &operation, |
| 1185 | &workspace, |
| 1186 | CanonicalThreadOperationKind::Create, |
| 1187 | None, |
| 1188 | "started", |
| 1189 | None, |
| 1190 | ) |
| 1191 | .await? |
| 1192 | { |
| 1193 | return Ok(result); |
| 1194 | } |
| 1195 | let mut config = json!({"workspace":workspace}); |
| 1196 | if let Some(model) = params.model { |
| 1197 | config["model"] = json!(model); |
| 1198 | } |
| 1199 | if let Some(provider) = params.model_provider { |
| 1200 | config["model_provider"] = json!(provider); |
| 1201 | } |
| 1202 | // Canonical history is always complete and durable; the legacy |
| 1203 | // extended-history flag cannot turn off branches or receipts. |
| 1204 | mutate( |
| 1205 | state, |
| 1206 | operation, |
| 1207 | workspace, |
| 1208 | CanonicalThreadMutation::Create { config }, |
| 1209 | "started", |
| 1210 | None, |
| 1211 | ) |
| 1212 | .await |
| 1213 | } |
| 1214 | ThreadRequest::Resume(params) => { |
| 1215 | let (key, operation, cwd, options) = history_parameters(serde_json::to_value(params)?)?; |
| 1216 | resume_or_fork(state, &key, operation, cwd, false, options).await |
| 1217 | } |
| 1218 | ThreadRequest::Fork(params) => { |
| 1219 | let (key, operation, cwd, options) = history_parameters(serde_json::to_value(params)?)?; |
| 1220 | resume_or_fork(state, &key, operation, cwd, true, options).await |
| 1221 | } |
| 1222 | _ => unreachable!("closed creation request dispatch"), |
| 1223 | } |
| 1224 | } |
| 1225 | |
| 1226 | async fn handle_owned(state: &AppState, request_value: ThreadRequest) -> Result<ThreadResponse> { |
| 1227 | if let ThreadRequest::List(params) = request_value { |
| 1228 | return list(state, params).await; |
| 1229 | } |
| 1230 | if matches!( |
| 1231 | &request_value, |
| 1232 | ThreadRequest::Create { .. } |
| 1233 | | ThreadRequest::Start(_) |
| 1234 | | ThreadRequest::Resume(_) |
| 1235 | | ThreadRequest::Fork(_) |
| 1236 | ) { |
| 1237 | return creation(state, request_value).await; |
| 1238 | } |
| 1239 | let (key, method, action, body) = match request_value { |
| 1240 | ThreadRequest::Read(p) => (p.thread_id, Method::GET, None, None), |
| 1241 | ThreadRequest::SetName(p) => ( |
| 1242 | p.thread_id, |
| 1243 | Method::PATCH, |
| 1244 | None, |
| 1245 | Some(json!({"title":p.name})), |
| 1246 | ), |
| 1247 | ThreadRequest::Archive { thread_id } => ( |
| 1248 | thread_id, |
| 1249 | Method::PATCH, |
| 1250 | None, |
| 1251 | Some(json!({"archived":true})), |
| 1252 | ), |
| 1253 | ThreadRequest::Unarchive { thread_id } => ( |
| 1254 | thread_id, |
| 1255 | Method::PATCH, |
| 1256 | None, |
| 1257 | Some(json!({"archived":false})), |
| 1258 | ), |
| 1259 | ThreadRequest::GoalGet(p) => (p.thread_id, Method::GET, Some("goal"), None), |
| 1260 | ThreadRequest::GoalSet(_) => { |
| 1261 | bail!("goal execution requires the canonical Runtime interaction API") |
| 1262 | } |
| 1263 | ThreadRequest::GoalClear(p) => (p.thread_id, Method::DELETE, Some("goal"), None), |
| 1264 | ThreadRequest::GoalRecordProgress(_) => bail!( |
| 1265 | "goal progress requires producing Engine usage/time receipts; client deltas are not accounting authority" |
| 1266 | ), |
| 1267 | ThreadRequest::Create { .. } |
| 1268 | | ThreadRequest::Start(_) |
| 1269 | | ThreadRequest::Resume(_) |
| 1270 | | ThreadRequest::Fork(_) => unreachable!("creation handled above"), |
| 1271 | ThreadRequest::Message { .. } => { |
| 1272 | bail!("thread messages use the existing canonical turn transport") |
| 1273 | } |
| 1274 | ThreadRequest::List(_) => unreachable!("list handled above"), |
| 1275 | }; |
| 1276 | let (id, _) = resolve(state, &key, false).await?; |
| 1277 | let native = owner_calls::captured(state)?; |
| 1278 | let mut result = response(key.clone()); |
| 1279 | let operation = match (method.as_str(), action) { |
| 1280 | ("GET", None) => RuntimeOwnerRequest::GetThread { |
| 1281 | thread_id: id.clone(), |
| 1282 | }, |
| 1283 | ("PATCH", None) => RuntimeOwnerRequest::UpdateThread { |
| 1284 | thread_id: id.clone(), |
| 1285 | body: body.clone().context("missing update")?, |
| 1286 | }, |
| 1287 | ("GET", Some("goal")) => RuntimeOwnerRequest::GetGoal { |
| 1288 | thread_id: id.clone(), |
| 1289 | }, |
| 1290 | ("DELETE", Some("goal")) => RuntimeOwnerRequest::ClearGoal { |
| 1291 | thread_id: id.clone(), |
| 1292 | }, |
| 1293 | _ => bail!("unsupported native thread operation"), |
| 1294 | }; |
| 1295 | let value = match request(&native, operation).await { |
| 1296 | Ok(value) => value, |
| 1297 | Err(error) |
| 1298 | if action == Some("goal") |
| 1299 | && (method == Method::GET || method == Method::DELETE) |
| 1300 | && error |
| 1301 | .downcast_ref::<RuntimeOwnerFailure>() |
| 1302 | .is_some_and(|e| e.status == StatusCode::NOT_FOUND.as_u16()) => |
| 1303 | { |
| 1304 | // Distinguish an absent goal from a concurrently removed thread. |
| 1305 | request( |
| 1306 | &native, |
| 1307 | RuntimeOwnerRequest::GetThread { |
| 1308 | thread_id: id.clone(), |
| 1309 | }, |
| 1310 | ) |
| 1311 | .await?; |
| 1312 | if method == Method::DELETE { |
| 1313 | result.status = "empty".into(); |
| 1314 | } |
| 1315 | Value::Null |
| 1316 | } |
| 1317 | Err(error) => return Err(error), |
| 1318 | }; |
| 1319 | if action == Some("goal") { |
| 1320 | if method == Method::DELETE && result.status != "empty" { |
| 1321 | result.status = "cleared".into(); |
| 1322 | } |
| 1323 | if !value.is_null() { |
| 1324 | let mut goal: codewhale_protocol::ThreadGoal = serde_json::from_value(value.clone())?; |
| 1325 | anyhow::ensure!( |
| 1326 | goal.thread_id == id, |
| 1327 | "canonical goal response belongs to another thread" |
| 1328 | ); |
| 1329 | goal.thread_id = key; |
| 1330 | result.goal = Some(goal); |
| 1331 | } |
| 1332 | result.data = |
| 1333 | json!({"goal":result.goal,"cleared":method==Method::DELETE && result.status!="empty"}); |
| 1334 | } else { |
| 1335 | let record = value.get("thread").unwrap_or(&value); |
| 1336 | anyhow::ensure!( |
| 1337 | record.get("id").and_then(Value::as_str) == Some(id.as_str()), |
| 1338 | "canonical control returned another target identity" |
| 1339 | ); |
| 1340 | let mut thread = project_thread(record, &key)?; |
| 1341 | if running_ids(&native).await?.contains(&id) && thread.status != ThreadStatus::Archived { |
| 1342 | thread.status = ThreadStatus::Running; |
| 1343 | } |
| 1344 | result.thread = Some(thread); |
| 1345 | result.model = record |
| 1346 | .get("model") |
| 1347 | .and_then(Value::as_str) |
| 1348 | .map(str::to_owned); |
| 1349 | result.model_provider = result.thread.as_ref().map(|t| t.model_provider.clone()); |
| 1350 | result.cwd = result.thread.as_ref().map(|t| t.cwd.clone()); |
| 1351 | result.data = value; |
| 1352 | if method == Method::GET { |
| 1353 | let snapshot = full_snapshot(state, &native, &id).await?; |
| 1354 | result.data["history"] = serde_json::to_value(snapshot)?; |
| 1355 | } |
| 1356 | } |
| 1357 | Ok(result) |
| 1358 | } |
| 1359 | |
| 1360 | /// Explicit CLI startup facts. The helper fills scheduler facts only from |
| 1361 | /// the authenticated owner's routing, never from a guessed local Config. |
| 1362 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 1363 | pub struct ThreadControlSelection { |
| 1364 | pub workspace: Option<PathBuf>, |
| 1365 | pub config_profile: Option<String>, |
| 1366 | pub config_source: Option<PathBuf>, |
| 1367 | } |
| 1368 | |
| 1369 | #[cfg(any(unix, windows))] |
| 1370 | pub async fn request_thread_control( |
| 1371 | config_path: Option<PathBuf>, |
| 1372 | selected: Option<PathBuf>, |
| 1373 | selection: Option<ThreadControlSelection>, |
| 1374 | request: ThreadRequest, |
| 1375 | ) -> Result<ThreadResponse> { |
| 1376 | let mut client = daemon_client::connect(config_path.clone(), selected).await?; |
| 1377 | if let Some(selection) = selection { |
| 1378 | let routing = client |
| 1379 | .routing() |
| 1380 | .context("selected owner has no acknowledged control scope")?; |
| 1381 | let scope = RuntimeFrontendScope { |
| 1382 | workers: routing |
| 1383 | .workers |
| 1384 | .context("selected owner has no captured worker setting")?, |
| 1385 | workspace: selection |
| 1386 | .workspace |
| 1387 | .or_else(|| routing.workspace.clone()) |
| 1388 | .context("selected owner has no acknowledged workspace")?, |
| 1389 | config_profile: selection.config_profile, |
| 1390 | config_source: selection.config_source, |
| 1391 | }; |
| 1392 | scope.validate_bounds()?; |
| 1393 | let owner = client.receipt().clone(); |
| 1394 | let socket = owner.socket_path.clone(); |
| 1395 | drop(client); |
| 1396 | client = daemon_client::connect_scoped_control_if_published( |
| 1397 | config_path, |
| 1398 | Some(socket), |
| 1399 | scope, |
| 1400 | owner, |
| 1401 | ) |
| 1402 | .await? |
| 1403 | .context("captured owner disappeared during scope admission; no replacement")?; |
| 1404 | } |
| 1405 | let request_id = json!(format!("thread-control-{}", Uuid::new_v4())); |
| 1406 | client |
| 1407 | .send( |
| 1408 | request_id.clone(), |
| 1409 | "thread/request", |
| 1410 | serde_json::to_value(request)?, |
| 1411 | ) |
| 1412 | .await?; |
| 1413 | tokio::time::timeout(Duration::from_secs(30), async { |
| 1414 | let mut notifications = 0usize; |
| 1415 | loop { |
| 1416 | let frame = client |
| 1417 | .recv() |
| 1418 | .await? |
| 1419 | .context("selected owner closed; outcome uncertain, not replayed")?; |
| 1420 | if frame.get("id") == Some(&request_id) { |
| 1421 | if let Some(error) = frame.get("error") { |
| 1422 | bail!("canonical owner refused thread control: {error}") |
| 1423 | } |
| 1424 | return serde_json::from_value( |
| 1425 | frame |
| 1426 | .get("result") |
| 1427 | .cloned() |
| 1428 | .context("canonical control result missing")?, |
| 1429 | ) |
| 1430 | .context("invalid canonical control response"); |
| 1431 | } |
| 1432 | anyhow::ensure!( |
| 1433 | frame.get("id").is_none(), |
| 1434 | "canonical owner returned another request identity" |
| 1435 | ); |
| 1436 | notifications += 1; |
| 1437 | anyhow::ensure!( |
| 1438 | notifications <= MAX_CANONICAL_HISTORY_ENTRIES, |
| 1439 | "canonical owner notification bound exceeded" |
| 1440 | ); |
| 1441 | } |
| 1442 | }) |
| 1443 | .await |
| 1444 | .context("canonical control deadline expired; outcome uncertain, not replayed")? |
| 1445 | } |
| 1446 | #[cfg(not(any(unix, windows)))] |
| 1447 | pub async fn request_thread_control( |
| 1448 | _config_path: Option<PathBuf>, |
| 1449 | _selected: Option<PathBuf>, |
| 1450 | _selection: Option<ThreadControlSelection>, |
| 1451 | _request: ThreadRequest, |
| 1452 | ) -> Result<ThreadResponse> { |
| 1453 | bail!("canonical owner attachment is unsupported on this platform") |
| 1454 | } |
| 1455 | |
| 1456 | #[cfg(test)] |
| 1457 | mod tests; |
| 1458 | |
| 1459 | #[cfg(test)] |
| 1460 | pub(super) async fn compatibility_fixture() |
| 1461 | -> (AppState, tempfile::TempDir, tokio::task::JoinHandle<()>) { |
| 1462 | tests::compatibility_fixture().await |
| 1463 | } |
| 1464 | |
| 1465 | #[cfg(test)] |
| 1466 | pub(super) fn compatibility_router() -> (AppState, tempfile::TempDir, Router) { |
| 1467 | tests::compatibility_router() |
| 1468 | } |
| 1469 |