| 1 | use super::*; |
| 2 | use serde_json::{Value, json}; |
| 3 | |
| 4 | #[derive(Debug, Default, Args)] |
| 5 | pub(crate) struct ComputerOptions { |
| 6 | #[arg( |
| 7 | long, |
| 8 | value_name = "ID", |
| 9 | help = "Run on this account cloud computer (preview)" |
| 10 | )] |
| 11 | pub computer: Option<String>, |
| 12 | #[arg( |
| 13 | long, |
| 14 | value_name = "ID", |
| 15 | help = "Continue or inspect a desktop/CLI cloud conversation" |
| 16 | )] |
| 17 | pub thread: Option<String>, |
| 18 | #[arg( |
| 19 | long, |
| 20 | requires = "cloud_model", |
| 21 | help = "Provider on the cloud computer" |
| 22 | )] |
| 23 | pub cloud_provider: Option<String>, |
| 24 | #[arg( |
| 25 | long, |
| 26 | requires = "cloud_provider", |
| 27 | help = "Model on the cloud computer" |
| 28 | )] |
| 29 | pub cloud_model: Option<String>, |
| 30 | #[arg( |
| 31 | long, |
| 32 | help = "Read a provider key from stdin into VM memory for this running computer" |
| 33 | )] |
| 34 | pub key_stdin: bool, |
| 35 | #[arg(long, help = "Stop the current turn of --thread")] |
| 36 | pub stop: bool, |
| 37 | #[arg( |
| 38 | long, |
| 39 | value_name = "ID", |
| 40 | conflicts_with = "deny", |
| 41 | help = "Allow one pending tool request in --thread" |
| 42 | )] |
| 43 | pub approve: Option<String>, |
| 44 | #[arg( |
| 45 | long, |
| 46 | value_name = "ID", |
| 47 | help = "Deny one pending tool request in --thread" |
| 48 | )] |
| 49 | pub deny: Option<String>, |
| 50 | #[arg(long, help = "Print the session receipt as JSON")] |
| 51 | pub json: bool, |
| 52 | #[arg(long, help = "Show the configured model available to cloud dispatch")] |
| 53 | pub configured_model: bool, |
| 54 | #[arg( |
| 55 | long, |
| 56 | help = "Connect the configured model to --thread without sending a message" |
| 57 | )] |
| 58 | pub prepare_model: bool, |
| 59 | #[arg(long, hide = true)] |
| 60 | pub expected_account: Option<String>, |
| 61 | #[arg( |
| 62 | long, |
| 63 | value_name = "AGENT_ID", |
| 64 | conflicts_with_all = ["thread", "cloud_provider", "cloud_model"], |
| 65 | help = "Start a cloud conversation with this whale, using its saved model" |
| 66 | )] |
| 67 | pub whale: Option<String>, |
| 68 | } |
| 69 | |
| 70 | impl ComputerOptions { |
| 71 | pub fn selected(&self) -> bool { |
| 72 | self.computer.is_some() |
| 73 | || self.thread.is_some() |
| 74 | || self.cloud_provider.is_some() |
| 75 | || self.cloud_model.is_some() |
| 76 | || self.key_stdin |
| 77 | || self.stop |
| 78 | || self.approve.is_some() |
| 79 | || self.deny.is_some() |
| 80 | || self.json |
| 81 | || self.configured_model |
| 82 | || self.prepare_model |
| 83 | || self.whale.is_some() |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | #[derive(Debug, Args)] |
| 88 | pub(crate) struct SessionArgs { |
| 89 | #[arg(value_name = "PROMPT")] |
| 90 | pub prompt: Vec<String>, |
| 91 | #[command(flatten)] |
| 92 | pub options: ComputerOptions, |
| 93 | #[arg( |
| 94 | long, |
| 95 | help = "Reuse this key and the same prompt after an uncertain send" |
| 96 | )] |
| 97 | pub operation_key: Option<String>, |
| 98 | } |
| 99 | |
| 100 | struct SessionClient<'a, 'b, T: CloudTransport> { |
| 101 | client: &'a CloudClient<'b, T>, |
| 102 | account: String, |
| 103 | session: String, |
| 104 | } |
| 105 | |
| 106 | impl<T: CloudTransport> SessionClient<'_, '_, T> { |
| 107 | fn snapshot(&self) -> Result<AccountSessionSnapshot> { |
| 108 | let snapshot = self.client.account_store.snapshot()?; |
| 109 | let stored = snapshot |
| 110 | .load()? |
| 111 | .context("Sign in with `codewhale login` first")?; |
| 112 | if stored.bundle.user.as_ref().map(|user| &user.id) != Some(&self.account) |
| 113 | || stored.bundle.session.as_ref().map(|session| &session.id) != Some(&self.session) |
| 114 | { |
| 115 | bail!("The signed-in account changed. Recover the original session before retrying."); |
| 116 | } |
| 117 | Ok(snapshot) |
| 118 | } |
| 119 | |
| 120 | fn request(&self, method: HttpMethod, path: &str, body: Option<Value>) -> Result<Value> { |
| 121 | let snapshot = self.snapshot()?; |
| 122 | let (response, _) = self.client.execute_from_snapshot( |
| 123 | method, |
| 124 | path, |
| 125 | body.as_ref().map(json_body).transpose()?, |
| 126 | snapshot, |
| 127 | )?; |
| 128 | self.snapshot()?; |
| 129 | expect_json(response, &[200, 201, 202]) |
| 130 | } |
| 131 | |
| 132 | fn operation( |
| 133 | &self, |
| 134 | thread: &str, |
| 135 | computer: &str, |
| 136 | runtime: &str, |
| 137 | kind: &str, |
| 138 | input: Value, |
| 139 | ) -> Result<Value> { |
| 140 | let value = self.request( |
| 141 | HttpMethod::Post, |
| 142 | &format!("/v1/threads/{thread}/computer"), |
| 143 | Some( |
| 144 | json!({ "computerId": computer, "operation": { "kind": kind, "request": input } }), |
| 145 | ), |
| 146 | )?; |
| 147 | check_binding(&value, thread, computer)?; |
| 148 | if value["runtimeThreadId"].as_str() != Some(runtime) |
| 149 | || !value.get("result").is_some_and(Value::is_object) |
| 150 | { |
| 151 | bail!("The computer returned a different session. Refresh before continuing."); |
| 152 | } |
| 153 | Ok(value["result"].clone()) |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | fn check_binding(value: &Value, thread: &str, computer: &str) -> Result<String> { |
| 158 | if value["threadId"].as_str() != Some(thread) |
| 159 | || value["computerId"].as_str() != Some(computer) |
| 160 | || value["state"] != "bound" |
| 161 | { |
| 162 | bail!("The cloud conversation is not bound to the selected computer."); |
| 163 | } |
| 164 | let runtime = value["runtimeThreadId"] |
| 165 | .as_str() |
| 166 | .context("The computer did not return its session ID")?; |
| 167 | validate_turn_id(runtime)?; |
| 168 | Ok(runtime.to_string()) |
| 169 | } |
| 170 | |
| 171 | pub(super) fn run<T: CloudTransport, W: Write>( |
| 172 | args: SessionArgs, |
| 173 | client: &CloudClient<'_, T>, |
| 174 | machine: &machine::MachineKeyEnv, |
| 175 | out: &mut W, |
| 176 | key_reader: &mut dyn FnMut(KeyReadMode) -> Result<String>, |
| 177 | config: &ConfigStore, |
| 178 | secrets: &Secrets, |
| 179 | ) -> Result<()> { |
| 180 | let mut local = config.config.resolve_runtime_options_with_secrets( |
| 181 | &codewhale_config::CliRuntimeOverrides::default(), |
| 182 | secrets, |
| 183 | ); |
| 184 | if args.options.configured_model { |
| 185 | if !args.prompt.is_empty() |
| 186 | || args.options.prepare_model |
| 187 | || args.options.key_stdin |
| 188 | || args.options.stop |
| 189 | || args.options.approve.is_some() |
| 190 | || args.options.deny.is_some() |
| 191 | { |
| 192 | bail!("Use --configured-model without a session action."); |
| 193 | } |
| 194 | let available = portable_model(&local, config).is_ok(); |
| 195 | let reason = portable_model(&local, config) |
| 196 | .err() |
| 197 | .map(|error| error.to_string()); |
| 198 | writeln!( |
| 199 | out, |
| 200 | "{}", |
| 201 | serde_json::to_string( |
| 202 | &json!({ "provider": local.provider.as_str(), "model": local.model, |
| 203 | "configured": available, "reason": reason }) |
| 204 | )? |
| 205 | )?; |
| 206 | return Ok(()); |
| 207 | } |
| 208 | if machine.is_present() { |
| 209 | bail!( |
| 210 | "Cloud conversations require an account login; unset CODEWHALE_API_KEY and run `codewhale login`." |
| 211 | ); |
| 212 | } |
| 213 | let mut options = args.options; |
| 214 | let mut prompt = args.prompt.join(" ").trim().to_string(); |
| 215 | if prompt.is_empty() |
| 216 | && !io::stdin().is_terminal() |
| 217 | && !options.key_stdin |
| 218 | && !options.prepare_model |
| 219 | && !options.stop |
| 220 | && options.approve.is_none() |
| 221 | && options.deny.is_none() |
| 222 | { |
| 223 | let mut piped = String::new(); |
| 224 | io::stdin() |
| 225 | .take(512_001) |
| 226 | .read_to_string(&mut piped) |
| 227 | .context("Read the task from standard input")?; |
| 228 | if piped.len() > 512_000 { |
| 229 | bail!("The piped task is too large."); |
| 230 | } |
| 231 | prompt = piped.trim().to_string(); |
| 232 | } |
| 233 | if [ |
| 234 | !prompt.is_empty(), |
| 235 | options.stop, |
| 236 | options.approve.is_some(), |
| 237 | options.deny.is_some(), |
| 238 | options.prepare_model, |
| 239 | ] |
| 240 | .into_iter() |
| 241 | .filter(|x| *x) |
| 242 | .count() |
| 243 | > 1 |
| 244 | { |
| 245 | bail!("Choose a prompt, --stop, --approve, or --deny."); |
| 246 | } |
| 247 | if prompt.chars().count() > 128_000 { |
| 248 | bail!("The cloud prompt is too long; keep it under 128,000 characters."); |
| 249 | } |
| 250 | if options.thread.is_none() && prompt.is_empty() { |
| 251 | bail!("Give a task to dispatch, or continue with --thread <id>."); |
| 252 | } |
| 253 | if let Some(value) = &options.whale { |
| 254 | validate_resource_id(value, "Whale")?; |
| 255 | } |
| 256 | let use_local_model = options.cloud_provider.is_none() |
| 257 | && !options.key_stdin |
| 258 | && (!prompt.is_empty() || options.prepare_model); |
| 259 | if options.thread.is_none() && options.cloud_provider.is_none() && options.whale.is_none() { |
| 260 | options.cloud_provider = Some(local.provider.as_str().to_string()); |
| 261 | options.cloud_model = Some(local.model.clone()); |
| 262 | } |
| 263 | if let Some(value) = &options.thread { |
| 264 | validate_resource_id(value, "Conversation")?; |
| 265 | } |
| 266 | if let Some(value) = &options.computer { |
| 267 | validate_resource_id(value, "Computer")?; |
| 268 | } |
| 269 | if let (Some(provider), Some(model)) = (&options.cloud_provider, &options.cloud_model) { |
| 270 | validate_model_route(provider, model)?; |
| 271 | if model.len() > 200 { |
| 272 | bail!("Cloud model names must be at most 200 bytes."); |
| 273 | } |
| 274 | } |
| 275 | let operation_key = args |
| 276 | .operation_key |
| 277 | .unwrap_or_else(|| format!("dispatch-{}", dispatch_stamp(&prompt))); |
| 278 | validate_operation_key(&operation_key)?; |
| 279 | if !operation_key.starts_with(|value: char| value.is_ascii_alphanumeric()) { |
| 280 | bail!("The operation key must start with a letter or number."); |
| 281 | } |
| 282 | let user = client.me()?; |
| 283 | if options |
| 284 | .expected_account |
| 285 | .as_deref() |
| 286 | .is_some_and(|id| id != user.id) |
| 287 | { |
| 288 | bail!("The signed-in account changed. Reopen the original cloud conversation."); |
| 289 | } |
| 290 | let stored = client |
| 291 | .load_auth()? |
| 292 | .context("Sign in with `codewhale login` first")?; |
| 293 | let session = stored |
| 294 | .bundle |
| 295 | .session |
| 296 | .as_ref() |
| 297 | .filter(|session| !session.id.is_empty()) |
| 298 | .context("Sign in again to establish a durable account session")? |
| 299 | .id |
| 300 | .clone(); |
| 301 | let account = SessionClient { |
| 302 | client, |
| 303 | account: user.id, |
| 304 | session, |
| 305 | }; |
| 306 | account.snapshot()?; |
| 307 | let key = if options.key_stdin { |
| 308 | Some(zeroize::Zeroizing::new(key_reader(KeyReadMode::Stdin)?)) |
| 309 | } else { |
| 310 | None |
| 311 | }; |
| 312 | let mut thread = if let Some(id) = &options.thread { |
| 313 | account.request(HttpMethod::Get, &format!("/v1/threads/{id}"), None)?["thread"].clone() |
| 314 | } else { |
| 315 | Value::Null |
| 316 | }; |
| 317 | if let Some(id) = &options.thread |
| 318 | && (thread["id"].as_str() != Some(id) |
| 319 | || thread["userId"].as_str() != Some(&account.account) |
| 320 | || thread["archivedAt"] |
| 321 | .as_str() |
| 322 | .is_some_and(|value| !value.is_empty())) |
| 323 | { |
| 324 | bail!("This account conversation is unavailable."); |
| 325 | } |
| 326 | let whale_id = options.whale.clone().or_else(|| { |
| 327 | thread["agentId"] |
| 328 | .as_str() |
| 329 | .filter(|id| !id.is_empty() && thread["agentFleetRevision"].as_u64().is_some()) |
| 330 | .map(str::to_string) |
| 331 | }); |
| 332 | let whale_route = match &whale_id { |
| 333 | Some(id) => { |
| 334 | validate_resource_id(id, "Whale")?; |
| 335 | let agent = account.request(HttpMethod::Get, &format!("/api/agents/{id}"), None)?; |
| 336 | let route = &agent["agent"]["configuration"]["model"]; |
| 337 | match (route["provider"].as_str(), route["model"].as_str()) { |
| 338 | (Some(provider), Some(model)) if agent["agent"]["id"].as_str() == Some(id) => { |
| 339 | validate_model_route(provider, model)?; |
| 340 | Some((provider.to_string(), model.to_string())) |
| 341 | } |
| 342 | _ => bail!( |
| 343 | "This whale has no saved model. Give it a configured model in Codewhale before dispatching." |
| 344 | ), |
| 345 | } |
| 346 | } |
| 347 | None => None, |
| 348 | }; |
| 349 | if let Some((provider, model)) = &whale_route |
| 350 | && (use_local_model || options.prepare_model) |
| 351 | { |
| 352 | let kind = codewhale_config::ProviderKind::parse(provider).with_context(|| { |
| 353 | format!( |
| 354 | "Configure the {provider} provider in Codewhale before dispatching to this whale." |
| 355 | ) |
| 356 | })?; |
| 357 | local = config.config.resolve_runtime_options_with_secrets( |
| 358 | &codewhale_config::CliRuntimeOverrides { |
| 359 | provider: Some(kind), |
| 360 | model: Some(model.clone()), |
| 361 | ..Default::default() |
| 362 | }, |
| 363 | secrets, |
| 364 | ); |
| 365 | portable_model(&local, config)?; |
| 366 | } else if use_local_model { |
| 367 | portable_model(&local, config)?; |
| 368 | } |
| 369 | let selected = if options.computer.is_none() && options.thread.is_none() { |
| 370 | let list = account.request(HttpMethod::Get, "/api/computers", None)?; |
| 371 | let machines = list["computers"] |
| 372 | .as_array() |
| 373 | .context("The account computer list is unavailable")?; |
| 374 | let running: Vec<_> = machines |
| 375 | .iter() |
| 376 | .filter(|computer| { |
| 377 | computer["ownerId"].as_str() == Some(&account.account) |
| 378 | && computer["status"] == "running" |
| 379 | }) |
| 380 | .collect(); |
| 381 | match running.as_slice() { |
| 382 | [computer] => computer["id"].as_str().map(str::to_string), |
| 383 | [] => bail!( |
| 384 | "No Boat computer is running. Start one in Codewhale Computers, then dispatch your task." |
| 385 | ), |
| 386 | _ => bail!( |
| 387 | "More than one computer is running. Choose --computer <id>; `codewhale account computers list` shows their IDs." |
| 388 | ), |
| 389 | } |
| 390 | } else { |
| 391 | None |
| 392 | }; |
| 393 | let computer = options |
| 394 | .computer |
| 395 | .as_deref() |
| 396 | .or_else(|| thread["computerId"].as_str()) |
| 397 | .or(selected.as_deref()) |
| 398 | .context("This conversation has no cloud computer")? |
| 399 | .to_string(); |
| 400 | validate_resource_id(&computer, "Computer")?; |
| 401 | if options.thread.is_some() && thread["computerId"].as_str() != Some(&computer) { |
| 402 | bail!("The conversation belongs to a different computer."); |
| 403 | } |
| 404 | let machine = account.request(HttpMethod::Get, &format!("/api/computers/{computer}"), None)?; |
| 405 | if machine["computer"]["id"].as_str() != Some(&computer) |
| 406 | || machine["computer"]["ownerId"].as_str() != Some(&account.account) |
| 407 | { |
| 408 | bail!("This computer does not belong to the signed-in account."); |
| 409 | } |
| 410 | if machine["computer"]["status"] != "running" { |
| 411 | bail!( |
| 412 | "Start this computer with `codewhale account computers start {computer}`, then retry the same session." |
| 413 | ); |
| 414 | } |
| 415 | if !prompt.is_empty() { |
| 416 | eprintln!( |
| 417 | "Replay key: {operation_key}. Keep the same target, prompt, and --operation-key when retrying an uncertain send." |
| 418 | ); |
| 419 | } |
| 420 | if options.thread.is_none() { |
| 421 | let value = account.request(HttpMethod::Post, "/v1/threads", Some(json!({ |
| 422 | "title": prompt.chars().take(120).collect::<String>(), "agentId": whale_id.as_deref().unwrap_or(""), "computerId": computer, |
| 423 | "productMode": "chat", "mode": "chat", "billingMode": "byok_external", "requiresByok": true, |
| 424 | "modelProvider": options.cloud_provider, "model": options.cloud_model, "operationKey": operation_key, |
| 425 | })))?; |
| 426 | thread = value.get("thread").unwrap_or(&value).clone(); |
| 427 | if thread["computerId"].as_str() != Some(&computer) |
| 428 | || thread["userId"].as_str() != Some(&account.account) |
| 429 | { |
| 430 | bail!("Conversation creation is unconfirmed. Retry with the same operation key."); |
| 431 | } |
| 432 | } |
| 433 | let thread_id = thread["id"] |
| 434 | .as_str() |
| 435 | .context("Conversation creation did not return an ID")?; |
| 436 | validate_resource_id(thread_id, "Conversation")?; |
| 437 | let binding_path = format!("/v1/threads/{thread_id}/computer"); |
| 438 | let existing_binding = if options.thread.is_some() { |
| 439 | account.request(HttpMethod::Get, &binding_path, None)? |
| 440 | } else { |
| 441 | Value::Null |
| 442 | }; |
| 443 | let binding = if existing_binding["state"] == "bound" { |
| 444 | existing_binding |
| 445 | } else if options.stop { |
| 446 | bail!("This conversation has no connected task to stop."); |
| 447 | } else { |
| 448 | account.request( |
| 449 | HttpMethod::Post, |
| 450 | &binding_path, |
| 451 | Some(json!({ "computerId": computer })), |
| 452 | )? |
| 453 | }; |
| 454 | let runtime = check_binding(&binding, thread_id, &computer)?; |
| 455 | let detail = account.operation(thread_id, &computer, &runtime, "read", json!({}))?; |
| 456 | if detail["thread"]["id"].as_str() != Some(&runtime) |
| 457 | || !detail["turns"].is_array() |
| 458 | || !detail["items"].is_array() |
| 459 | { |
| 460 | bail!("The computer did not confirm this conversation's task history."); |
| 461 | } |
| 462 | let turns = detail["turns"].as_array().unwrap(); |
| 463 | if turns |
| 464 | .iter() |
| 465 | .any(|turn| turn["thread_id"].as_str() != Some(&runtime)) |
| 466 | { |
| 467 | bail!("The computer returned a task from a different conversation."); |
| 468 | } |
| 469 | let latest_id = detail["thread"]["latest_turn_id"] |
| 470 | .as_str() |
| 471 | .filter(|id| !id.is_empty()); |
| 472 | let latest = latest_id.and_then(|id| { |
| 473 | turns |
| 474 | .iter() |
| 475 | .find(|turn| turn["id"] == id && turn["routing_settlement"] != true) |
| 476 | }); |
| 477 | let provider = options |
| 478 | .cloud_provider |
| 479 | .as_deref() |
| 480 | .or(whale_route.as_ref().map(|(provider, _)| provider.as_str())) |
| 481 | .or_else(|| latest.and_then(|turn| turn["effective_provider"].as_str())) |
| 482 | .or_else(|| { |
| 483 | latest_id |
| 484 | .is_none() |
| 485 | .then(|| detail["thread"]["model_provider"].as_str()) |
| 486 | .flatten() |
| 487 | }) |
| 488 | .unwrap_or(""); |
| 489 | let model = options |
| 490 | .cloud_model |
| 491 | .as_deref() |
| 492 | .or(whale_route.as_ref().map(|(_, model)| model.as_str())) |
| 493 | .or_else(|| latest.and_then(|turn| turn["effective_model"].as_str())) |
| 494 | .or_else(|| { |
| 495 | latest_id |
| 496 | .is_none() |
| 497 | .then(|| detail["thread"]["model"].as_str()) |
| 498 | .flatten() |
| 499 | }) |
| 500 | .unwrap_or(""); |
| 501 | let provider_id = if options.cloud_provider.is_some() || whale_route.is_some() { |
| 502 | None |
| 503 | } else { |
| 504 | latest |
| 505 | .and_then(|turn| turn["effective_provider_id"].as_str()) |
| 506 | .filter(|id| !id.is_empty()) |
| 507 | .or_else(|| { |
| 508 | latest_id |
| 509 | .is_none() |
| 510 | .then(|| { |
| 511 | detail["thread"]["model_provider_id"] |
| 512 | .as_str() |
| 513 | .filter(|id| !id.is_empty()) |
| 514 | }) |
| 515 | .flatten() |
| 516 | }) |
| 517 | }; |
| 518 | if !prompt.is_empty() || key.is_some() { |
| 519 | validate_model_route(provider, model).context("The last model route is unconfirmed. Choose --cloud-provider and --cloud-model explicitly")?; |
| 520 | } |
| 521 | if use_local_model { |
| 522 | if provider != local.provider.as_str() |
| 523 | || model != local.model |
| 524 | || provider_id.is_some_and(|id| id != provider) |
| 525 | { |
| 526 | bail!( |
| 527 | "This conversation uses a different model from your configured model. Select its model locally or explicitly choose --cloud-provider and --cloud-model to use the computer's existing connection." |
| 528 | ); |
| 529 | } |
| 530 | account.operation( |
| 531 | thread_id, |
| 532 | &computer, |
| 533 | &runtime, |
| 534 | "key", |
| 535 | json!({ "provider": provider, |
| 536 | "key": local.api_key.as_deref(), "expectedBaseUrl": local.base_url }), |
| 537 | ).context("The computer could not confirm your model connection. Check that its provider endpoint matches your configured model")?; |
| 538 | } |
| 539 | let mut member_connections = Vec::new(); |
| 540 | if use_local_model { |
| 541 | let lead = thread["agentId"].as_str().unwrap_or(""); |
| 542 | let mut connected = vec![provider.to_string()]; |
| 543 | for participant in thread["group"]["participants"] |
| 544 | .as_array() |
| 545 | .into_iter() |
| 546 | .flatten() |
| 547 | .filter(|row| row["state"] == "active" && row["agentId"].as_str() != Some(lead)) |
| 548 | { |
| 549 | let id = participant["agentId"] |
| 550 | .as_str() |
| 551 | .context("A group member has no whale ID. Refresh the group.")?; |
| 552 | validate_resource_id(id, "Whale")?; |
| 553 | let name = printable(participant["name"].as_str().unwrap_or("A member")); |
| 554 | let agent = account.request(HttpMethod::Get, &format!("/api/agents/{id}"), None)?; |
| 555 | let route = &agent["agent"]["configuration"]["model"]; |
| 556 | let (Some(member_provider), Some(member_model)) = |
| 557 | (route["provider"].as_str(), route["model"].as_str()) |
| 558 | else { |
| 559 | bail!("{name} has no saved model. Give it a configured model in Codewhale."); |
| 560 | }; |
| 561 | if agent["agent"]["id"].as_str() != Some(id) { |
| 562 | bail!("The account returned a different whale for {name}."); |
| 563 | } |
| 564 | validate_model_route(member_provider, member_model)?; |
| 565 | if connected.iter().any(|done| done == member_provider) { |
| 566 | continue; |
| 567 | } |
| 568 | let kind = |
| 569 | codewhale_config::ProviderKind::parse(member_provider).with_context(|| { |
| 570 | format!("Configure the {member_provider} provider in Codewhale for {name}.") |
| 571 | })?; |
| 572 | let member_local = config.config.resolve_runtime_options_with_secrets( |
| 573 | &codewhale_config::CliRuntimeOverrides { |
| 574 | provider: Some(kind), |
| 575 | model: Some(member_model.to_string()), |
| 576 | ..Default::default() |
| 577 | }, |
| 578 | secrets, |
| 579 | ); |
| 580 | portable_model(&member_local, config) |
| 581 | .with_context(|| format!("{name} uses {member_provider}"))?; |
| 582 | account |
| 583 | .operation( |
| 584 | thread_id, |
| 585 | &computer, |
| 586 | &runtime, |
| 587 | "key", |
| 588 | json!({ "provider": member_provider, |
| 589 | "key": member_local.api_key.as_deref(), "expectedBaseUrl": member_local.base_url }), |
| 590 | ) |
| 591 | .with_context(|| { |
| 592 | format!("The computer could not confirm the {member_provider} connection for {name}") |
| 593 | })?; |
| 594 | connected.push(member_provider.to_string()); |
| 595 | member_connections.push(json!({ "agentId": id, "provider": member_provider })); |
| 596 | } |
| 597 | } |
| 598 | if let Some(key) = key { |
| 599 | validate_api_key(&key)?; |
| 600 | account.operation( |
| 601 | thread_id, |
| 602 | &computer, |
| 603 | &runtime, |
| 604 | "key", |
| 605 | json!({ "provider": provider_id.unwrap_or(provider), "key": key.as_str() }), |
| 606 | )?; |
| 607 | } |
| 608 | let result = if !prompt.is_empty() { |
| 609 | account.operation(thread_id, &computer, &runtime, "turn", json!({ |
| 610 | "prompt": prompt, "operation_key": operation_key, "model": model, |
| 611 | "model_provider": provider, "model_provider_id": provider_id, |
| 612 | })).with_context(|| format!("Session {thread_id}: retry the original request with --operation-key {operation_key}"))? |
| 613 | } else if options.stop { |
| 614 | if let Some(turn) = turns |
| 615 | .iter() |
| 616 | .rev() |
| 617 | .find(|turn| matches!(turn["status"].as_str(), Some("queued" | "in_progress"))) |
| 618 | { |
| 619 | let stopped = account.operation( |
| 620 | thread_id, |
| 621 | &computer, |
| 622 | &runtime, |
| 623 | "stop", |
| 624 | json!({ "turnId": turn["id"] }), |
| 625 | )?; |
| 626 | if stopped["id"] != turn["id"] || stopped["thread_id"].as_str() != Some(&runtime) { |
| 627 | bail!("The computer did not confirm which task received the stop request."); |
| 628 | } |
| 629 | json!({ "turn": stopped, "message": "Stop requested. Inspect the conversation to confirm it has stopped." }) |
| 630 | } else { |
| 631 | json!({ "status": "idle", "message": "No running turn" }) |
| 632 | } |
| 633 | } else if let Some(id) = options.approve.as_ref().or(options.deny.as_ref()) { |
| 634 | let reply = account.operation(thread_id, &computer, &runtime, "approve", json!({ "id": id, "decision": if options.approve.is_some() { "allow" } else { "deny" } }))?; |
| 635 | if reply["delivered"] != true { |
| 636 | bail!("This approval is no longer waiting. Refresh the conversation."); |
| 637 | } |
| 638 | reply |
| 639 | } else if options.prepare_model { |
| 640 | json!({ "prepared": true, "provider": provider, "model": model, "backend": "memory", |
| 641 | "members": member_connections }) |
| 642 | } else { |
| 643 | detail |
| 644 | }; |
| 645 | if let Some(turn) = result.get("turn") |
| 646 | && turn["thread_id"].as_str() != Some(&runtime) |
| 647 | { |
| 648 | bail!("The computer returned a different task"); |
| 649 | } |
| 650 | if options.json { |
| 651 | writeln!( |
| 652 | out, |
| 653 | "{}", |
| 654 | serde_json::to_string_pretty(&json!({ "threadId": thread_id, "computerId": computer, |
| 655 | "runtimeThreadId": runtime, "operationKey": (!prompt.is_empty()).then_some(&operation_key), "result": result }))? |
| 656 | )?; |
| 657 | } else { |
| 658 | writeln!(out, "Cloud conversation: {thread_id}\nComputer: {computer}")?; |
| 659 | if let Some(turn) = result.get("turn") { |
| 660 | writeln!( |
| 661 | out, |
| 662 | "Task: {} ({})", |
| 663 | printable(turn["id"].as_str().unwrap_or("")), |
| 664 | printable(turn["status"].as_str().unwrap_or("unconfirmed")) |
| 665 | )?; |
| 666 | } |
| 667 | if let Some(message) = result["message"].as_str() { |
| 668 | writeln!(out, "{}", printable(message))?; |
| 669 | } |
| 670 | if result["delivered"] == true { |
| 671 | writeln!(out, "Decision delivered to the running task.")?; |
| 672 | } |
| 673 | if let Some(items) = result["items"].as_array() { |
| 674 | for item in items { |
| 675 | let text = item["detail"] |
| 676 | .as_str() |
| 677 | .filter(|text| !text.is_empty()) |
| 678 | .or_else(|| item["summary"].as_str()) |
| 679 | .unwrap_or(""); |
| 680 | writeln!( |
| 681 | out, |
| 682 | "{}: {}", |
| 683 | printable(item["kind"].as_str().unwrap_or("status")), |
| 684 | printable(text) |
| 685 | )?; |
| 686 | } |
| 687 | } |
| 688 | if let Some(approvals) = result["pending_approvals"].as_array() { |
| 689 | for approval in approvals { |
| 690 | writeln!( |
| 691 | out, |
| 692 | "Approval {}: {}", |
| 693 | printable(approval["id"].as_str().unwrap_or("")), |
| 694 | printable(&serde_json::to_string(approval)?) |
| 695 | )?; |
| 696 | } |
| 697 | } |
| 698 | if result["pending_user_inputs"] |
| 699 | .as_array() |
| 700 | .is_some_and(|rows| !rows.is_empty()) |
| 701 | { |
| 702 | writeln!( |
| 703 | out, |
| 704 | "A question is waiting. Open this conversation in desktop to answer it." |
| 705 | )?; |
| 706 | } |
| 707 | writeln!( |
| 708 | out, |
| 709 | "Inspect: codewhale dispatch --thread {thread_id}\nContinue: codewhale dispatch --thread {thread_id} \"your next task\"\nStop: codewhale dispatch --thread {thread_id} --stop" |
| 710 | )?; |
| 711 | } |
| 712 | Ok(()) |
| 713 | } |
| 714 | |
| 715 | fn portable_model( |
| 716 | local: &codewhale_config::ResolvedRuntimeOptions, |
| 717 | config: &ConfigStore, |
| 718 | ) -> Result<()> { |
| 719 | local |
| 720 | .route |
| 721 | .as_ref() |
| 722 | .map_err(|_| anyhow!("Choose a valid model in Codewhale before dispatching."))?; |
| 723 | let endpoint = |
| 724 | Url::parse(&local.base_url).context("The configured model endpoint is invalid")?; |
| 725 | let local_host = endpoint.host_str().is_some_and(|host| { |
| 726 | host.eq_ignore_ascii_case("localhost") |
| 727 | || host.ends_with(".localhost") |
| 728 | || host |
| 729 | .trim_matches(['[', ']']) |
| 730 | .parse::<IpAddr>() |
| 731 | .is_ok_and(|address| address.is_loopback() || address.is_unspecified()) |
| 732 | }); |
| 733 | if endpoint.scheme() != "https" |
| 734 | || local_host |
| 735 | || endpoint.host_str().is_none() |
| 736 | || !endpoint.username().is_empty() |
| 737 | || endpoint.password().is_some() |
| 738 | || endpoint.query().is_some() |
| 739 | || endpoint.fragment().is_some() |
| 740 | || local.insecure_skip_tls_verify |
| 741 | { |
| 742 | bail!( |
| 743 | "Cloud dispatch needs a model endpoint reachable over HTTPS from Boat. A model running only on this computer cannot continue after it disconnects." |
| 744 | ); |
| 745 | } |
| 746 | if codewhale_config::auth_mode_disables_api_key(local.auth_mode.as_deref()) |
| 747 | || config |
| 748 | .config |
| 749 | .providers |
| 750 | .for_provider(local.provider) |
| 751 | .external_credentials |
| 752 | .is_some() |
| 753 | || config |
| 754 | .config |
| 755 | .providers |
| 756 | .for_provider(local.provider) |
| 757 | .oauth_credential_generation |
| 758 | .is_some() |
| 759 | || !local.http_headers.is_empty() |
| 760 | || matches!( |
| 761 | local.provider, |
| 762 | codewhale_config::ProviderKind::OpenaiCodex | codewhale_config::ProviderKind::Custom |
| 763 | ) |
| 764 | || local |
| 765 | .auth_mode |
| 766 | .as_deref() |
| 767 | .is_some_and(|mode| !matches!(mode, "api_key" | "auto")) |
| 768 | { |
| 769 | bail!( |
| 770 | "This configured connection cannot be copied to Boat. Use a portable API-key model connection; device-bound sign-ins stay on their credential owner." |
| 771 | ); |
| 772 | } |
| 773 | validate_api_key(local.api_key.as_deref().context("Configure a model API key in Codewhale before dispatching. Boat provides the computer, not model credentials.")?)?; |
| 774 | Ok(()) |
| 775 | } |
| 776 |