| 1 | //! The account Work journey: assign Work, cancel it, read its outcome, quote |
| 2 | //! and launch offered cloud compute, and connect a GitHub repository. |
| 3 | //! |
| 4 | //! Everything here is a thin, honest client of the account control plane. |
| 5 | //! Remote text is untrusted: it only reaches the terminal through `printable`, |
| 6 | //! ids are re-validated before they enter a URL path, and a mutating request |
| 7 | //! whose reply is lost is reported as an *unknown* outcome with the exact |
| 8 | //! command that is safe to run next, never as a failure or a success. |
| 9 | |
| 10 | use serde_json::{Value, json}; |
| 11 | |
| 12 | use super::*; |
| 13 | |
| 14 | /// The cloud Work profile this CLI can start. These are the contract values |
| 15 | /// the control plane admits; anything else is refused by the server, so the |
| 16 | /// CLI states them instead of exposing knobs that could only fail. |
| 17 | const WORK_SKU: &str = "task-small"; |
| 18 | const WORK_MODEL_PROVIDER: &str = "deepseek"; |
| 19 | const WORK_MODEL: &str = "deepseek-flash"; |
| 20 | const MAX_CONFIRMATION_BYTES: usize = 4096; |
| 21 | const MAX_CANCEL_REASON_CHARS: usize = 500; |
| 22 | |
| 23 | pub(super) fn task_context( |
| 24 | path: Option<&Path>, |
| 25 | refs: &[String], |
| 26 | ) -> Result<Option<WorkTaskContext>> { |
| 27 | if refs.len() > 10 { |
| 28 | bail!("Reference at most ten saved files per task"); |
| 29 | } |
| 30 | let text = match path { |
| 31 | Some(path) => { |
| 32 | let mut bytes = Vec::new(); |
| 33 | std::fs::File::open(path) |
| 34 | .context("Could not open the task source context file")? |
| 35 | .take(256_001) |
| 36 | .read_to_end(&mut bytes)?; |
| 37 | if bytes.len() > 256_000 { |
| 38 | bail!("Task source context exceeds 64000 UTF-16 units"); |
| 39 | } |
| 40 | let text = String::from_utf8(bytes).context("Task source context must be UTF-8")?; |
| 41 | if text.encode_utf16().count() > 64_000 { |
| 42 | bail!("Task source context exceeds 64000 UTF-16 units"); |
| 43 | } |
| 44 | text |
| 45 | } |
| 46 | None => String::new(), |
| 47 | }; |
| 48 | let mut file_refs: Vec<WorkFileRef> = Vec::new(); |
| 49 | for value in refs { |
| 50 | let (id, version) = value |
| 51 | .rsplit_once('@') |
| 52 | .ok_or_else(|| anyhow!("Saved file references must be FILE_ID@VERSION"))?; |
| 53 | let file_id = validate_account_file_id(id)?.to_string(); |
| 54 | let version: u64 = version |
| 55 | .parse() |
| 56 | .context("Saved file version must be a positive integer")?; |
| 57 | if version == 0 |
| 58 | || version > 9_007_199_254_740_991 |
| 59 | || file_refs.iter().any(|ref_| ref_.file_id == file_id) |
| 60 | { |
| 61 | bail!( |
| 62 | "Saved file references need distinct file IDs and positive safe-integer versions" |
| 63 | ); |
| 64 | } |
| 65 | file_refs.push(WorkFileRef { file_id, version }); |
| 66 | } |
| 67 | Ok((!text.is_empty() || !file_refs.is_empty()).then_some(WorkTaskContext { text, file_refs })) |
| 68 | } |
| 69 | |
| 70 | fn valid_confirmation(token: &str) -> bool { |
| 71 | !token.is_empty() |
| 72 | && token.len() <= MAX_CONFIRMATION_BYTES |
| 73 | && token |
| 74 | .bytes() |
| 75 | .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-')) |
| 76 | } |
| 77 | |
| 78 | /// Consume a pipe rather than placing signed consent proof in process argv. |
| 79 | /// Bound the read before decoding and allow only one terminal line ending. |
| 80 | pub(super) fn read_confirmation(reader: impl Read) -> Result<String> { |
| 81 | let mut bytes = Vec::new(); |
| 82 | reader |
| 83 | .take(MAX_CONFIRMATION_BYTES as u64 + 3) |
| 84 | .read_to_end(&mut bytes) |
| 85 | .context("Could not read the launch confirmation from stdin")?; |
| 86 | if bytes.len() > MAX_CONFIRMATION_BYTES + 2 { |
| 87 | bail!("Launch confirmation from stdin is too long"); |
| 88 | } |
| 89 | let value = String::from_utf8(bytes).context("Launch confirmation from stdin must be UTF-8")?; |
| 90 | let token = value |
| 91 | .strip_suffix("\r\n") |
| 92 | .or_else(|| value.strip_suffix('\n')) |
| 93 | .unwrap_or(&value); |
| 94 | if !valid_confirmation(token) { |
| 95 | bail!("Launch confirmation from stdin must be one non-empty confirmation token"); |
| 96 | } |
| 97 | Ok(token.to_string()) |
| 98 | } |
| 99 | |
| 100 | fn at<'a>(value: &'a Value, path: &[&str]) -> Option<&'a Value> { |
| 101 | path.iter().try_fold(value, |cursor, key| cursor.get(*key)) |
| 102 | } |
| 103 | |
| 104 | fn str_at<'a>(value: &'a Value, path: &[&str]) -> Option<&'a str> { |
| 105 | at(value, path).and_then(Value::as_str) |
| 106 | } |
| 107 | |
| 108 | /// A sanitized, non-empty string from a remote document. |
| 109 | fn text_at(value: &Value, path: &[&str]) -> Option<String> { |
| 110 | str_at(value, path) |
| 111 | .map(printable) |
| 112 | .filter(|text| !text.is_empty()) |
| 113 | } |
| 114 | |
| 115 | fn count_at(value: &Value, path: &[&str]) -> Option<u64> { |
| 116 | at(value, path).and_then(Value::as_u64) |
| 117 | } |
| 118 | |
| 119 | fn http_code(err: &anyhow::Error) -> Option<&str> { |
| 120 | err.downcast_ref::<CloudHttpError>() |
| 121 | .and_then(CloudHttpError::code) |
| 122 | } |
| 123 | |
| 124 | /// A 2xx reply whose body cannot be read: the service acted, but the client |
| 125 | /// cannot say how, so it is an unknown outcome rather than a failure. |
| 126 | fn parse_reply(body: &[u8], what: &'static str) -> Result<Value> { |
| 127 | serde_json::from_slice(body).map_err(|source| CloudTransportError::new(what, source).into()) |
| 128 | } |
| 129 | |
| 130 | fn validate_work_uuid(value: &str) -> Result<&str> { |
| 131 | let id = value.trim(); |
| 132 | let groups = id.split('-').map(str::len).collect::<Vec<_>>(); |
| 133 | if groups != [8, 4, 4, 4, 12] |
| 134 | || !id |
| 135 | .bytes() |
| 136 | .all(|byte| byte == b'-' || byte.is_ascii_hexdigit()) |
| 137 | { |
| 138 | bail!( |
| 139 | "Work ID must be the UUID printed when the Work was created (see `codewhale account agents work-status`)" |
| 140 | ); |
| 141 | } |
| 142 | Ok(id) |
| 143 | } |
| 144 | |
| 145 | fn github_owner_ok(owner: &str) -> bool { |
| 146 | (1..=39).contains(&owner.len()) |
| 147 | && owner |
| 148 | .bytes() |
| 149 | .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-') |
| 150 | && !owner.starts_with('-') |
| 151 | && !owner.ends_with('-') |
| 152 | } |
| 153 | |
| 154 | fn github_name_ok(name: &str) -> bool { |
| 155 | (1..=100).contains(&name.len()) |
| 156 | && name |
| 157 | .bytes() |
| 158 | .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-')) |
| 159 | && !matches!(name, "." | "..") |
| 160 | } |
| 161 | |
| 162 | fn validate_github_repo(value: &str) -> Result<String> { |
| 163 | let value = value.trim(); |
| 164 | match value.split_once('/') { |
| 165 | Some((owner, name)) if github_owner_ok(owner) && github_name_ok(name) => { |
| 166 | Ok(value.to_string()) |
| 167 | } |
| 168 | _ => bail!("Repository must be written OWNER/REPO, for example `octo-org/app`"), |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | /// A draft-PR link is shown only when it is exactly a GitHub pull-request URL |
| 173 | /// (and, when the result names its repository, points into that repository). |
| 174 | /// A remote string that merely looks like a link is never echoed. |
| 175 | fn github_pull_request_url(url: &str, repository: &str) -> Option<String> { |
| 176 | let rest = url.strip_prefix("https://github.com/")?; |
| 177 | let mut parts = rest.split('/'); |
| 178 | let (owner, name, kind, number) = (parts.next()?, parts.next()?, parts.next()?, parts.next()?); |
| 179 | if parts.next().is_some() |
| 180 | || kind != "pull" |
| 181 | || !github_owner_ok(owner) |
| 182 | || !github_name_ok(name) |
| 183 | || number.is_empty() |
| 184 | || number.len() > 10 |
| 185 | || number.starts_with('0') |
| 186 | || !number.bytes().all(|byte| byte.is_ascii_digit()) |
| 187 | { |
| 188 | return None; |
| 189 | } |
| 190 | if !repository.is_empty() && !repository.eq_ignore_ascii_case(&format!("{owner}/{name}")) { |
| 191 | return None; |
| 192 | } |
| 193 | Some(url.to_string()) |
| 194 | } |
| 195 | |
| 196 | fn write_work_item<W: Write>(out: &mut W, item: &AccountAgentWork) -> Result<()> { |
| 197 | writeln!(out, "Work ID: {}", item.id)?; |
| 198 | writeln!(out, "Status: {}", printable(&item.status))?; |
| 199 | if !item.objective.is_empty() { |
| 200 | writeln!(out, "Objective: {}", printable(&item.objective))?; |
| 201 | } |
| 202 | Ok(()) |
| 203 | } |
| 204 | |
| 205 | /// `codewhale account agents work`: say what the Agent actually did with the |
| 206 | /// message. Only an actionable or queued reading creates Work; a control verb |
| 207 | /// or correction acts on Work that already exists, and a question changes |
| 208 | /// nothing, so those must never read as "Work is recorded". |
| 209 | pub(super) fn assign<T: CloudTransport, W: Write>( |
| 210 | client: &CloudClient<'_, T>, |
| 211 | out: &mut W, |
| 212 | agent: &AccountAgent, |
| 213 | objective: &str, |
| 214 | message_id: &str, |
| 215 | task_context: Option<&WorkTaskContext>, |
| 216 | ) -> Result<Vec<String>> { |
| 217 | let message_id = validate_operation_key(message_id)?; |
| 218 | let receipt = client |
| 219 | .assign_agent_work(&agent.id, objective, message_id, task_context) |
| 220 | .map_err(|err| { |
| 221 | if outcome_unknown(&err) { |
| 222 | err.context(format!( |
| 223 | "The request may or may not have reached Codewhale. Re-run this exact command with --message-id {message_id}; replaying the same --message-id never creates a second Work for the same instruction. If the message was a stop or a correction, check `work-status` first" |
| 224 | )) |
| 225 | } else { |
| 226 | err |
| 227 | } |
| 228 | })?; |
| 229 | let mut items = Vec::new(); |
| 230 | for item in receipt.work.iter().chain(receipt.queued_work.iter()) { |
| 231 | validate_resource_id(&item.id, "Work")?; |
| 232 | if item.agent_id != agent.id { |
| 233 | bail!("The Codewhale service returned Work for a different Agent"); |
| 234 | } |
| 235 | if let Some(context) = task_context { |
| 236 | let digest = codewhale_runtime::hashing::sha256_hex(&serde_json::to_vec(context)?); |
| 237 | if item.task_context_digest != digest { |
| 238 | return Err(CloudTransportError::new("The Work reply does not confirm the requested source context; replay the same message and context", std::io::Error::other("task context mismatch")).into()); |
| 239 | } |
| 240 | } |
| 241 | items.push(item); |
| 242 | } |
| 243 | let intent = receipt.intent.as_str(); |
| 244 | if items.is_empty() { |
| 245 | match intent { |
| 246 | "actionable" | "queued" => bail!( |
| 247 | "The Codewhale service read this message as {} but returned no Work record, so nothing is confirmed. Re-run this exact command with --message-id {message_id} to replay it", |
| 248 | printable(intent) |
| 249 | ), |
| 250 | "control" | "correction" => bail!( |
| 251 | "The Codewhale service reported a {} but returned no Work record, so nothing is confirmed. Run `codewhale account agents work-status` on the Work you meant", |
| 252 | printable(intent) |
| 253 | ), |
| 254 | _ => {} |
| 255 | } |
| 256 | } |
| 257 | writeln!(out, "Intent: {}", printable(intent))?; |
| 258 | if !receipt.reason.is_empty() { |
| 259 | writeln!(out, "Reason: {}", printable(&receipt.reason))?; |
| 260 | } |
| 261 | if receipt.confident == Some(false) { |
| 262 | writeln!(out, "The Agent was not confident in this reading.")?; |
| 263 | } |
| 264 | match intent { |
| 265 | "control" => { |
| 266 | let action = receipt |
| 267 | .control_action |
| 268 | .as_deref() |
| 269 | .map(printable) |
| 270 | .filter(|action| !action.is_empty()) |
| 271 | .unwrap_or_else(|| "unspecified".to_string()); |
| 272 | writeln!(out, "Applied control action: {action}")?; |
| 273 | } |
| 274 | "correction" => writeln!( |
| 275 | out, |
| 276 | "Applied: this message edited the objective of active Work. No new Work was created." |
| 277 | )?, |
| 278 | "queued" => writeln!(out, "This Work was queued behind active Work.")?, |
| 279 | "actionable" => {} |
| 280 | "informational" => { |
| 281 | writeln!(out, "No Work was created and nothing was changed.")?; |
| 282 | if let Some(suggestion) = receipt |
| 283 | .suggestion |
| 284 | .as_deref() |
| 285 | .map(printable) |
| 286 | .filter(|suggestion| !suggestion.is_empty()) |
| 287 | { |
| 288 | writeln!(out, "Suggestion: {suggestion}")?; |
| 289 | writeln!( |
| 290 | out, |
| 291 | "To have the Agent do it, send it as an instruction that starts with a verb such as fix, add or update." |
| 292 | )?; |
| 293 | } |
| 294 | } |
| 295 | _ => writeln!( |
| 296 | out, |
| 297 | "The Agent reported an intent this CLI does not recognize; verify with `codewhale account agents work-status`." |
| 298 | )?, |
| 299 | } |
| 300 | for item in &items { |
| 301 | write_work_item(out, item)?; |
| 302 | } |
| 303 | match (intent, items.first()) { |
| 304 | ("actionable" | "queued", Some(first)) => { |
| 305 | writeln!( |
| 306 | out, |
| 307 | "Work is recorded, not started. To run it on a cloud computer, review a quote first:" |
| 308 | )?; |
| 309 | writeln!( |
| 310 | out, |
| 311 | " codewhale account agents work-quote {} --operation-key <new-key>", |
| 312 | first.id |
| 313 | )?; |
| 314 | } |
| 315 | ("control" | "correction", _) => writeln!( |
| 316 | out, |
| 317 | "Status above is the Work's state after this message; `work-status` confirms it." |
| 318 | )?, |
| 319 | _ => {} |
| 320 | } |
| 321 | writeln!(out, "Message ID: {message_id}")?; |
| 322 | Ok(items.iter().map(|item| item.id.clone()).collect()) |
| 323 | } |
| 324 | |
| 325 | /// `codewhale account agents work-cancel`. |
| 326 | pub(super) fn cancel<T: CloudTransport, W: Write>( |
| 327 | client: &CloudClient<'_, T>, |
| 328 | out: &mut W, |
| 329 | id: &str, |
| 330 | queue: Option<WorkQueueChoice>, |
| 331 | reason: Option<&str>, |
| 332 | ) -> Result<()> { |
| 333 | let id = validate_resource_id(id, "Work")?; |
| 334 | let mut body = json!({}); |
| 335 | if let Some(reason) = reason { |
| 336 | body["reason"] = json!(validate_named_text( |
| 337 | reason, |
| 338 | "Cancel reason", |
| 339 | MAX_CANCEL_REASON_CHARS |
| 340 | )?); |
| 341 | } |
| 342 | if let Some(queue) = queue { |
| 343 | body["queue"] = json!(match queue { |
| 344 | WorkQueueChoice::Discard => "discard", |
| 345 | WorkQueueChoice::Park => "park", |
| 346 | }); |
| 347 | } |
| 348 | let unknown = |err: anyhow::Error| { |
| 349 | err.context(format!( |
| 350 | "The cancel outcome is unknown: the request may or may not have been applied. Run `codewhale account agents work-status {id}` before retrying; cancelling is safe to repeat" |
| 351 | )) |
| 352 | }; |
| 353 | let response = client |
| 354 | .execute_authenticated( |
| 355 | HttpMethod::Post, |
| 356 | &format!("/api/runs/{id}/cancel"), |
| 357 | Some(json_body(&body)?), |
| 358 | ) |
| 359 | .map_err(|err| { |
| 360 | if outcome_unknown(&err) { |
| 361 | unknown(err) |
| 362 | } else { |
| 363 | err |
| 364 | } |
| 365 | })?; |
| 366 | if !(200..300).contains(&response.status) { |
| 367 | let err = response_error(&response); |
| 368 | return match (response.status, http_code(&err)) { |
| 369 | (409, Some("run_control_terminal")) => { |
| 370 | writeln!(out, "Work ID: {id}")?; |
| 371 | writeln!(out, "Work is already final; there is nothing to cancel.")?; |
| 372 | writeln!( |
| 373 | out, |
| 374 | "Read its outcome: codewhale account agents work-result {id}" |
| 375 | )?; |
| 376 | Ok(()) |
| 377 | } |
| 378 | (422, Some("run_prompt_queue_choice_required")) => Err(err.context( |
| 379 | "This Work still has queued prompts and was not cancelled. Re-run with --queue discard or --queue park to choose what happens to them", |
| 380 | )), |
| 381 | (404, _) => Err(err.context(format!("Work {id} was not found on this account"))), |
| 382 | _ if outcome_unknown(&err) => Err(unknown(err)), |
| 383 | _ => Err(err.context("The cancel request was refused")), |
| 384 | }; |
| 385 | } |
| 386 | let reply = parse_reply( |
| 387 | &response.body, |
| 388 | "The Codewhale service returned an unreadable cancel reply", |
| 389 | ) |
| 390 | .map_err(unknown)?; |
| 391 | if let Some(run_id) = str_at(&reply, &["run", "id"]) |
| 392 | && run_id != id |
| 393 | { |
| 394 | bail!("The Codewhale service returned a different Work record"); |
| 395 | } |
| 396 | writeln!(out, "Work ID: {id}")?; |
| 397 | let state = text_at(&reply, &["run", "state"]); |
| 398 | if reply.get("queued").is_some() && state.is_none() { |
| 399 | writeln!( |
| 400 | out, |
| 401 | "Cancel requested. The runtime has not confirmed the stop yet." |
| 402 | )?; |
| 403 | if reply.get("replayed").and_then(Value::as_bool) == Some(true) { |
| 404 | writeln!(out, "This cancellation was already pending.")?; |
| 405 | } |
| 406 | writeln!( |
| 407 | out, |
| 408 | "Check `codewhale account agents work-status {id}` until its status is canceled." |
| 409 | )?; |
| 410 | } else if let Some(state) = state { |
| 411 | writeln!(out, "Status: {state}")?; |
| 412 | if state == "canceled" { |
| 413 | writeln!(out, "Work canceled.")?; |
| 414 | } else { |
| 415 | writeln!( |
| 416 | out, |
| 417 | "Cancel accepted; run `codewhale account agents work-status {id}` to confirm the final state." |
| 418 | )?; |
| 419 | } |
| 420 | } else { |
| 421 | writeln!( |
| 422 | out, |
| 423 | "Cancel accepted; run `codewhale account agents work-status {id}` to confirm the final state." |
| 424 | )?; |
| 425 | } |
| 426 | if reply.get("promptQueue").is_some_and(Value::is_object) |
| 427 | && let Some(queue) = queue |
| 428 | { |
| 429 | writeln!( |
| 430 | out, |
| 431 | "Queued prompts: {} (recorded).", |
| 432 | match queue { |
| 433 | WorkQueueChoice::Discard => "discarded", |
| 434 | WorkQueueChoice::Park => "parked", |
| 435 | } |
| 436 | )?; |
| 437 | } |
| 438 | writeln!( |
| 439 | out, |
| 440 | "Compute stop and provider usage are final only in `codewhale account agents work-result {id}`." |
| 441 | )?; |
| 442 | Ok(()) |
| 443 | } |
| 444 | |
| 445 | /// The model route recorded for a Work, wherever the account API reports it. |
| 446 | fn recorded_model_route(envelope: &Value, result: &Value) -> Option<(String, String)> { |
| 447 | let candidates = [ |
| 448 | at(result, &["modelRoute"]), |
| 449 | at(result, &["modelAuthority"]), |
| 450 | at(result, &["model"]), |
| 451 | at(result, &["run", "modelAuthority"]), |
| 452 | at(envelope, &["modelAuthority"]), |
| 453 | at(result, &["run"]), |
| 454 | ]; |
| 455 | candidates.into_iter().flatten().find_map(|candidate| { |
| 456 | let provider = |
| 457 | str_at(candidate, &["provider"]).or_else(|| str_at(candidate, &["modelProvider"]))?; |
| 458 | let model = str_at(candidate, &["model"])?; |
| 459 | validate_model_route(provider, model) |
| 460 | .ok() |
| 461 | .map(|(provider, model)| (provider.to_string(), model.to_string())) |
| 462 | }) |
| 463 | } |
| 464 | |
| 465 | fn usd(value: f64) -> String { |
| 466 | if value == 0.0 { |
| 467 | "$0".to_string() |
| 468 | } else { |
| 469 | format!("${value:.4}") |
| 470 | } |
| 471 | } |
| 472 | |
| 473 | fn write_compute_usage<W: Write>(out: &mut W, envelope: &Value, result: &Value) -> Result<()> { |
| 474 | let block = [ |
| 475 | at(result, &["computeUsage"]), |
| 476 | at(result, &["boatUsage"]), |
| 477 | at(result, &["providerUsage"]), |
| 478 | at(result, &["usage"]), |
| 479 | at(envelope, &["computeUsage"]), |
| 480 | at(envelope, &["boatUsage"]), |
| 481 | at(envelope, &["providerUsage"]), |
| 482 | at(envelope, &["usage"]), |
| 483 | ] |
| 484 | .into_iter() |
| 485 | .flatten() |
| 486 | .find(|block| block.is_object()); |
| 487 | let Some(block) = block else { |
| 488 | return Ok(()); |
| 489 | }; |
| 490 | writeln!(out, "Computer usage:")?; |
| 491 | let number = |keys: &[&str]| { |
| 492 | keys.iter() |
| 493 | .find_map(|key| block.get(*key).and_then(Value::as_f64)) |
| 494 | }; |
| 495 | if let Some(seconds) = number(&["providerSeconds", "seconds", "usedSeconds"]) { |
| 496 | writeln!(out, " Provider seconds: {seconds}")?; |
| 497 | } |
| 498 | if let Some(dollars) = number(&["providerListPriceDollars", "dollars"]) { |
| 499 | writeln!(out, " Provider list price: {}", usd(dollars))?; |
| 500 | } |
| 501 | if let Some(charged) = number(&["customerCreditsChargedUsd", "customerChargeDollars"]) { |
| 502 | writeln!(out, " Codewhale credits charged: {}", usd(charged))?; |
| 503 | } |
| 504 | if let Some(funding) = text_at(block, &["funding"]) { |
| 505 | writeln!(out, " Funding: {funding}")?; |
| 506 | } |
| 507 | if let Some(running) = block.get("running").and_then(Value::as_bool) { |
| 508 | writeln!( |
| 509 | out, |
| 510 | " Provider VM: {}", |
| 511 | if running { "still running" } else { "stopped" } |
| 512 | )?; |
| 513 | } |
| 514 | if let Some(confirmed) = block.get("cleanupConfirmed").and_then(Value::as_bool) { |
| 515 | writeln!( |
| 516 | out, |
| 517 | " Provider cleanup: {}", |
| 518 | if confirmed { "confirmed" } else { "pending" } |
| 519 | )?; |
| 520 | } |
| 521 | Ok(()) |
| 522 | } |
| 523 | |
| 524 | fn write_work_result<W: Write>( |
| 525 | out: &mut W, |
| 526 | id: &str, |
| 527 | envelope: &Value, |
| 528 | attempts: Option<&Value>, |
| 529 | ) -> Result<()> { |
| 530 | let result = envelope |
| 531 | .get("result") |
| 532 | .filter(|result| result.is_object()) |
| 533 | .ok_or_else(|| anyhow!("The Codewhale service returned no Work result"))?; |
| 534 | if str_at(result, &["run", "id"]) != Some(id) { |
| 535 | bail!("The Codewhale service returned a different Work result"); |
| 536 | } |
| 537 | writeln!(out, "Work ID: {id}")?; |
| 538 | writeln!( |
| 539 | out, |
| 540 | "State: {}", |
| 541 | text_at(result, &["run", "state"]).unwrap_or_else(|| "unknown".to_string()) |
| 542 | )?; |
| 543 | let status = text_at(result, &["status"]); |
| 544 | if let Some(status) = &status { |
| 545 | writeln!(out, "Result: {status}")?; |
| 546 | } |
| 547 | if let Some(title) = text_at(result, &["run", "title"]) { |
| 548 | writeln!(out, "Objective: {title}")?; |
| 549 | } |
| 550 | if status.as_deref() == Some("in_progress") { |
| 551 | writeln!(out, "This Work is still running; nothing below is final.")?; |
| 552 | } |
| 553 | if let Some(summary) = str_at(result, &["summary", "text"]) |
| 554 | .map(|text| printable_max(text, 600)) |
| 555 | .filter(|text| !text.is_empty()) |
| 556 | { |
| 557 | writeln!(out, "Summary: {summary}")?; |
| 558 | } |
| 559 | |
| 560 | let files = count_at(result, &["changes", "fileCount"]).unwrap_or(0); |
| 561 | match text_at(result, &["changes", "evidence"]).as_deref() { |
| 562 | Some("recorded") => writeln!( |
| 563 | out, |
| 564 | "Changes: {files} file(s), +{} -{} (recorded)", |
| 565 | count_at(result, &["changes", "additions"]).unwrap_or(0), |
| 566 | count_at(result, &["changes", "deletions"]).unwrap_or(0) |
| 567 | )?, |
| 568 | Some(other) => writeln!(out, "Changes: not verified (evidence: {other})")?, |
| 569 | None => writeln!(out, "Changes: not reported")?, |
| 570 | } |
| 571 | if let Some(checks) = at(result, &["checks"]).and_then(Value::as_array) { |
| 572 | if checks.is_empty() { |
| 573 | writeln!(out, "Checks: none recorded")?; |
| 574 | } else { |
| 575 | let passed = checks |
| 576 | .iter() |
| 577 | .filter(|check| check.get("passed").and_then(Value::as_bool) == Some(true)) |
| 578 | .count(); |
| 579 | writeln!(out, "Checks: {passed} passed of {}", checks.len())?; |
| 580 | for check in checks |
| 581 | .iter() |
| 582 | .filter(|check| check.get("passed").and_then(Value::as_bool) != Some(true)) |
| 583 | .take(10) |
| 584 | { |
| 585 | writeln!( |
| 586 | out, |
| 587 | " not passed: {} ({})", |
| 588 | text_at(check, &["name"]).unwrap_or_else(|| "check".to_string()), |
| 589 | text_at(check, &["status"]).unwrap_or_else(|| "unverified".to_string()) |
| 590 | )?; |
| 591 | } |
| 592 | } |
| 593 | } |
| 594 | if let Some(findings) = at(result, &["findings"]).and_then(Value::as_array) |
| 595 | && !findings.is_empty() |
| 596 | { |
| 597 | writeln!(out, "Findings: {}", findings.len())?; |
| 598 | for finding in findings.iter().take(5) { |
| 599 | writeln!( |
| 600 | out, |
| 601 | " {}: {}", |
| 602 | text_at(finding, &["severity"]).unwrap_or_else(|| "info".to_string()), |
| 603 | text_at(finding, &["title"]).unwrap_or_else(|| "finding".to_string()) |
| 604 | )?; |
| 605 | } |
| 606 | } |
| 607 | if let Some(approvals) = at(result, &["pendingApprovals"]).and_then(Value::as_array) |
| 608 | && !approvals.is_empty() |
| 609 | { |
| 610 | writeln!(out, "Waiting on {} approval(s).", approvals.len())?; |
| 611 | } |
| 612 | let artifacts = at(result, &["artifacts"]) |
| 613 | .and_then(Value::as_array) |
| 614 | .map(Vec::as_slice) |
| 615 | .unwrap_or_default(); |
| 616 | if artifacts.is_empty() { |
| 617 | writeln!(out, "Artifacts: none")?; |
| 618 | } else { |
| 619 | writeln!(out, "Artifacts ({}):", artifacts.len())?; |
| 620 | for artifact in artifacts.iter().take(20) { |
| 621 | writeln!( |
| 622 | out, |
| 623 | " {} ({}, {}, {} bytes)", |
| 624 | text_at(artifact, &["name"]).unwrap_or_else(|| "artifact".to_string()), |
| 625 | text_at(artifact, &["status"]).unwrap_or_else(|| "unknown".to_string()), |
| 626 | text_at(artifact, &["contentType"]).unwrap_or_else(|| "unknown type".to_string()), |
| 627 | count_at(artifact, &["size"]).unwrap_or(0) |
| 628 | )?; |
| 629 | } |
| 630 | } |
| 631 | |
| 632 | let repository = str_at(result, &["repository", "name"]).unwrap_or_default(); |
| 633 | if let Some(branch) = text_at(result, &["repository", "branch"]) { |
| 634 | writeln!(out, "Branch: {branch}")?; |
| 635 | } |
| 636 | if let Some(revision) = text_at(result, &["repository", "revision"]) { |
| 637 | writeln!(out, "Revision: {revision}")?; |
| 638 | } |
| 639 | match str_at(result, &["repository", "pullRequest", "url"]) { |
| 640 | Some(url) => match github_pull_request_url(url, repository) { |
| 641 | Some(url) => { |
| 642 | let draft = |
| 643 | str_at(result, &["repository", "pullRequest", "state"]) == Some("draft"); |
| 644 | writeln!( |
| 645 | out, |
| 646 | "{}: {url}", |
| 647 | if draft { "Draft PR" } else { "Pull request" } |
| 648 | )?; |
| 649 | } |
| 650 | None => writeln!( |
| 651 | out, |
| 652 | "Pull request: the service reported a link that is not a GitHub pull request for this repository, so it is not shown" |
| 653 | )?, |
| 654 | }, |
| 655 | None => writeln!(out, "Draft PR: none")?, |
| 656 | } |
| 657 | if let Some(blockers) = at(result, &["readiness", "blockers"]).and_then(Value::as_array) |
| 658 | && !blockers.is_empty() |
| 659 | { |
| 660 | writeln!( |
| 661 | out, |
| 662 | "Blockers: {}", |
| 663 | blockers |
| 664 | .iter() |
| 665 | .filter_map(Value::as_str) |
| 666 | .map(printable) |
| 667 | .collect::<Vec<_>>() |
| 668 | .join(", ") |
| 669 | )?; |
| 670 | } |
| 671 | if let Some(next) = text_at(result, &["nextAction", "label"]) { |
| 672 | writeln!(out, "Next: {next}")?; |
| 673 | } |
| 674 | match recorded_model_route(envelope, result) { |
| 675 | Some((provider, model)) => writeln!(out, "Model route: {provider}/{model}")?, |
| 676 | None => writeln!(out, "Model route: not reported by the account API")?, |
| 677 | } |
| 678 | write_compute_usage(out, envelope, result)?; |
| 679 | match attempts { |
| 680 | Some(attempts) => { |
| 681 | let rows = at(attempts, &["attempts"]) |
| 682 | .and_then(Value::as_array) |
| 683 | .map(Vec::as_slice) |
| 684 | .unwrap_or_default(); |
| 685 | writeln!( |
| 686 | out, |
| 687 | "Attempts: {}", |
| 688 | count_at(attempts, &["attemptCount"]).unwrap_or(rows.len() as u64) |
| 689 | )?; |
| 690 | for attempt in rows.iter().take(10) { |
| 691 | let mut line = format!( |
| 692 | " #{} {} {}", |
| 693 | count_at(attempt, &["sequence"]).unwrap_or(0), |
| 694 | text_at(attempt, &["kind"]).unwrap_or_else(|| "attempt".to_string()), |
| 695 | text_at(attempt, &["status"]).unwrap_or_else(|| "unknown".to_string()) |
| 696 | ); |
| 697 | if let Some(code) = text_at(attempt, &["errorCode"]) { |
| 698 | line.push_str(&format!(" (error: {})", display_error_code(&code))); |
| 699 | } |
| 700 | writeln!(out, "{line}")?; |
| 701 | } |
| 702 | } |
| 703 | None => writeln!(out, "Attempts: unavailable")?, |
| 704 | } |
| 705 | if let Some(seq) = count_at(result, &["receipt", "eventsThroughSeq"]) { |
| 706 | writeln!(out, "Evidence through event {seq}")?; |
| 707 | } |
| 708 | Ok(()) |
| 709 | } |
| 710 | |
| 711 | /// `codewhale account agents work-result`. |
| 712 | pub(super) fn result<T: CloudTransport, W: Write>( |
| 713 | client: &CloudClient<'_, T>, |
| 714 | out: &mut W, |
| 715 | id: &str, |
| 716 | json: bool, |
| 717 | ) -> Result<()> { |
| 718 | let id = validate_resource_id(id, "Work")?; |
| 719 | let envelope: Value = expect_json( |
| 720 | client.execute_authenticated(HttpMethod::Get, &format!("/api/runs/{id}/result"), None)?, |
| 721 | &[200], |
| 722 | )?; |
| 723 | // Attempt lineage is supporting evidence: without it the result is still |
| 724 | // worth showing, so its failure is reported instead of hiding the result. |
| 725 | let attempts = client |
| 726 | .execute_authenticated(HttpMethod::Get, &format!("/api/runs/{id}/attempts"), None) |
| 727 | .and_then(|response| expect_json::<Value>(response, &[200])) |
| 728 | .ok(); |
| 729 | if json { |
| 730 | return write_computer_json( |
| 731 | out, |
| 732 | &json!({ "result": envelope, "attempts": attempts.unwrap_or(Value::Null) }), |
| 733 | ); |
| 734 | } |
| 735 | write_work_result(out, id, &envelope, attempts.as_ref()) |
| 736 | } |
| 737 | |
| 738 | struct LaunchTarget { |
| 739 | run_id: String, |
| 740 | agent_id: String, |
| 741 | project_id: String, |
| 742 | repo: String, |
| 743 | prompt: String, |
| 744 | state: String, |
| 745 | workspace_id: String, |
| 746 | } |
| 747 | |
| 748 | struct WorkOffer { |
| 749 | funding: String, |
| 750 | min_seconds: u64, |
| 751 | max_seconds: u64, |
| 752 | remaining_seconds: Option<u64>, |
| 753 | empty_workspace: bool, |
| 754 | } |
| 755 | |
| 756 | fn default_seconds(offer: &WorkOffer) -> u64 { |
| 757 | offer |
| 758 | .remaining_seconds |
| 759 | .map_or(offer.max_seconds, |remaining| { |
| 760 | remaining.min(offer.max_seconds) |
| 761 | }) |
| 762 | } |
| 763 | |
| 764 | fn load_work_offer<T: CloudTransport>(client: &CloudClient<'_, T>) -> Result<WorkOffer> { |
| 765 | let value: Value = expect_json( |
| 766 | client.execute_authenticated(HttpMethod::Get, "/api/sandbox/work-offer", None)?, |
| 767 | &[200], |
| 768 | )?; |
| 769 | let offer = value.get("offer").unwrap_or(&value); |
| 770 | let min_seconds = count_at(offer, &["minSeconds"]).unwrap_or(0); |
| 771 | let max_seconds = count_at(offer, &["maxSeconds"]).unwrap_or(0); |
| 772 | let funding = str_at(offer, &["funding"]).unwrap_or_default(); |
| 773 | let mode_matches = matches!( |
| 774 | (str_at(offer, &["mode"]), funding), |
| 775 | (Some("trial"), "trial_credit") | (Some("open"), "compute_cu") |
| 776 | ); |
| 777 | if !mode_matches |
| 778 | || min_seconds == 0 |
| 779 | || max_seconds < min_seconds |
| 780 | || max_seconds > 9_007_199_254_740_991 |
| 781 | || str_at(offer, &["sku"]) != Some(WORK_SKU) |
| 782 | || str_at(offer, &["region"]) != Some("eu") |
| 783 | || str_at(offer, &["model", "provider"]) != Some(WORK_MODEL_PROVIDER) |
| 784 | || str_at(offer, &["model", "model"]) != Some(WORK_MODEL) |
| 785 | { |
| 786 | bail!("The account did not serve a supported cloud Work offer; nothing started"); |
| 787 | } |
| 788 | let remaining_seconds = match offer.get("computeRemainingSeconds") { |
| 789 | None | Some(Value::Null) => None, |
| 790 | Some(value) => Some( |
| 791 | value |
| 792 | .as_u64() |
| 793 | .filter(|seconds| *seconds <= 9_007_199_254_740_991) |
| 794 | .ok_or_else(|| anyhow!("The computer balance in the Work offer is invalid"))?, |
| 795 | ), |
| 796 | }; |
| 797 | Ok(WorkOffer { |
| 798 | funding: funding.to_string(), |
| 799 | min_seconds, |
| 800 | max_seconds, |
| 801 | remaining_seconds, |
| 802 | empty_workspace: offer.get("emptyWorkspace").and_then(Value::as_bool) == Some(true), |
| 803 | }) |
| 804 | } |
| 805 | |
| 806 | /// The Work as the account serves it: the launch acts on this record, not on |
| 807 | /// anything the caller types, so the reviewed quote and the launch agree. |
| 808 | fn load_launch_target<T: CloudTransport>( |
| 809 | client: &CloudClient<'_, T>, |
| 810 | id: &str, |
| 811 | ) -> Result<LaunchTarget> { |
| 812 | let envelope: Value = expect_json( |
| 813 | client.execute_authenticated(HttpMethod::Get, &format!("/api/runs/{id}"), None)?, |
| 814 | &[200], |
| 815 | )?; |
| 816 | let run = envelope |
| 817 | .get("run") |
| 818 | .filter(|run| run.is_object()) |
| 819 | .ok_or_else(|| anyhow!("The Codewhale service returned no Work record"))?; |
| 820 | if str_at(run, &["id"]) != Some(id) { |
| 821 | bail!("The Codewhale service returned a different Work record"); |
| 822 | } |
| 823 | let field = |name: &str| str_at(run, &[name]).unwrap_or_default().trim().to_string(); |
| 824 | let provider = field("repoProvider").to_ascii_lowercase(); |
| 825 | if !provider.is_empty() && provider != "github" { |
| 826 | bail!( |
| 827 | "Cloud Work supports GitHub repositories only; this Work uses {}", |
| 828 | printable(&provider) |
| 829 | ); |
| 830 | } |
| 831 | let agent_id = field("agentId"); |
| 832 | let project_id = field("projectId"); |
| 833 | if agent_id.is_empty() || project_id.is_empty() { |
| 834 | bail!( |
| 835 | "This Work is not attached to an Agent and Project, so it cannot be launched; create it with `codewhale account agents work`" |
| 836 | ); |
| 837 | } |
| 838 | validate_resource_id(&agent_id, "Agent")?; |
| 839 | validate_resource_id(&project_id, "Project")?; |
| 840 | let prompt = field("title"); |
| 841 | if prompt.is_empty() || prompt.chars().count() > 32_000 { |
| 842 | bail!("Work objective must contain 1-32000 characters"); |
| 843 | } |
| 844 | Ok(LaunchTarget { |
| 845 | run_id: id.to_string(), |
| 846 | agent_id, |
| 847 | project_id, |
| 848 | repo: field("repo"), |
| 849 | prompt, |
| 850 | state: field("state"), |
| 851 | workspace_id: field("workspaceId"), |
| 852 | }) |
| 853 | } |
| 854 | |
| 855 | /// Cross-check the Work against the Agent and Project the account serves now. |
| 856 | fn verify_launch_authority<T: CloudTransport>( |
| 857 | client: &CloudClient<'_, T>, |
| 858 | target: &mut LaunchTarget, |
| 859 | ) -> Result<()> { |
| 860 | let agents: AgentListResponse = serde_json::from_value(client.agents()?) |
| 861 | .context("The Codewhale service returned an invalid Agent list")?; |
| 862 | let agent = resolve_account_agent(&agents.agents, &target.agent_id)?; |
| 863 | if agent.project_id != target.project_id { |
| 864 | bail!( |
| 865 | "Agent {} is no longer bound to this Work's Project; bind it again or create new Work", |
| 866 | printable(&agent.name) |
| 867 | ); |
| 868 | } |
| 869 | let projects: ProjectListResponse = serde_json::from_value(client.projects()?) |
| 870 | .context("The Codewhale service returned an invalid Project list")?; |
| 871 | let project = projects |
| 872 | .projects |
| 873 | .into_iter() |
| 874 | .find(|project| project.id == target.project_id); |
| 875 | let project = match project { |
| 876 | Some(project) => project, |
| 877 | None => { |
| 878 | let id = validate_resource_id(&target.project_id, "Project")?; |
| 879 | let reply: ProjectResponse = expect_json( |
| 880 | client.execute_authenticated( |
| 881 | HttpMethod::Get, |
| 882 | &format!("/api/projects/{id}"), |
| 883 | None, |
| 884 | )?, |
| 885 | &[200], |
| 886 | )?; |
| 887 | if reply.project.id != target.project_id { |
| 888 | bail!("The Codewhale service returned a different Work Project"); |
| 889 | } |
| 890 | reply.project |
| 891 | } |
| 892 | }; |
| 893 | if target.repo.is_empty() |
| 894 | && project.default_repo.is_empty() |
| 895 | && project.default_repo_provider.is_empty() |
| 896 | { |
| 897 | return Ok(()); |
| 898 | } |
| 899 | if project.default_repo_provider != "github" || project.default_repo.trim().is_empty() { |
| 900 | bail!( |
| 901 | "Project {} has no GitHub repository, so its Work cannot be launched", |
| 902 | printable(&project.name) |
| 903 | ); |
| 904 | } |
| 905 | if target.repo.is_empty() { |
| 906 | target.repo = project.default_repo.trim().to_string(); |
| 907 | } else if !target |
| 908 | .repo |
| 909 | .eq_ignore_ascii_case(project.default_repo.trim()) |
| 910 | { |
| 911 | bail!("This Work's repository differs from its Project's repository; create new Work"); |
| 912 | } |
| 913 | Ok(()) |
| 914 | } |
| 915 | |
| 916 | /// Contract C5: the launch-quote and cloud-sessions request for one bounded |
| 917 | /// cloud task. The quote and the launch send the same fields so the signed |
| 918 | /// confirmation binds to exactly what starts. |
| 919 | fn launch_body( |
| 920 | target: &LaunchTarget, |
| 921 | operation_key: &str, |
| 922 | seconds: u64, |
| 923 | recovery_from: Option<&str>, |
| 924 | ) -> Result<Value> { |
| 925 | if seconds == 0 || seconds > 9_007_199_254_740_991 { |
| 926 | bail!("Task time must be a positive safe-integer number of seconds"); |
| 927 | } |
| 928 | let mut body = json!({ |
| 929 | "workRunId": target.run_id, |
| 930 | "agentId": target.agent_id, |
| 931 | "projectId": target.project_id, |
| 932 | "prompt": target.prompt, |
| 933 | "runnerKind": "hosted", |
| 934 | "sandboxSku": WORK_SKU, |
| 935 | "estimatedSeconds": seconds, |
| 936 | "modelProvider": WORK_MODEL_PROVIDER, |
| 937 | "model": WORK_MODEL, |
| 938 | "billingMode": "byok_external", |
| 939 | "computeRegion": "eu", |
| 940 | "sandboxTargetRegion": "eu", |
| 941 | "crossRegionSandboxOptIn": true, |
| 942 | "operationKey": operation_key, |
| 943 | }); |
| 944 | if target.repo.is_empty() { |
| 945 | body["workspaceSource"] = json!("empty"); |
| 946 | } else { |
| 947 | body["repo"] = json!(validate_github_repo(&target.repo)?); |
| 948 | body["provider"] = json!("github"); |
| 949 | } |
| 950 | if let Some(previous) = recovery_from { |
| 951 | body["recovery"] = json!(true); |
| 952 | body["expectedPreviousWorkspaceId"] = json!(validate_resource_id(previous, "Workspace")?); |
| 953 | } |
| 954 | Ok(body) |
| 955 | } |
| 956 | |
| 957 | /// What to do next for a control-plane code the launch flow knows about. |
| 958 | fn launch_hint(code: &str) -> Option<&'static str> { |
| 959 | Some(match code { |
| 960 | "work_vm_trial_unavailable" => "Cloud Work is not available for this account", |
| 961 | "work_vm_provider_unavailable" => { |
| 962 | "Cloud computers are not configured on this Codewhale API" |
| 963 | } |
| 964 | "hosted_launch_quote_required" |
| 965 | | "hosted_launch_quote_invalid" |
| 966 | | "hosted_launch_quote_expired" |
| 967 | | "hosted_launch_quote_mismatch" => { |
| 968 | "The confirmation is not valid for this launch. Run `work-quote` again with the same --operation-key and use the new confirmation" |
| 969 | } |
| 970 | "launch_operation_mismatch" => { |
| 971 | "This --operation-key belongs to different launch inputs. Check `work-status` and `work-result` before starting again; never replace the key to retry an unknown launch" |
| 972 | } |
| 973 | "work_run_not_queued" => { |
| 974 | "Only queued Work can be launched. Run `work-status` to see what happened to it" |
| 975 | } |
| 976 | "repo_access_required" => { |
| 977 | "Connect the repository first with `codewhale account github bind OWNER/REPO`" |
| 978 | } |
| 979 | "hosted_byok_required" => { |
| 980 | "Save your DeepSeek key first with `codewhale account keys set deepseek`" |
| 981 | } |
| 982 | _ => return None, |
| 983 | }) |
| 984 | } |
| 985 | |
| 986 | /// `codewhale account agents work-quote`. |
| 987 | pub(super) fn quote<T: CloudTransport, W: Write>( |
| 988 | client: &CloudClient<'_, T>, |
| 989 | out: &mut W, |
| 990 | id: &str, |
| 991 | operation_key: &str, |
| 992 | seconds: Option<u64>, |
| 993 | recovery_from: Option<&str>, |
| 994 | reveal: bool, |
| 995 | ) -> Result<QuotedLaunch> { |
| 996 | let id = validate_work_uuid(id)?; |
| 997 | let operation_key = validate_operation_key(operation_key)?; |
| 998 | let mut target = load_launch_target(client, id)?; |
| 999 | let recovery_from = recovery_from |
| 1000 | .map(|id| validate_resource_id(id, "Workspace")) |
| 1001 | .transpose()?; |
| 1002 | if recovery_from.is_some() { |
| 1003 | if target.state != "failed" || recovery_from != Some(target.workspace_id.as_str()) { |
| 1004 | bail!( |
| 1005 | "Recovery needs the exact failed Work workspace; refresh work-status before reviewing a replacement" |
| 1006 | ); |
| 1007 | } |
| 1008 | } else if target.state != "queued" { |
| 1009 | bail!( |
| 1010 | "Work is {}, and only queued Work can be quoted for launch. Run `codewhale account agents work-status {id}`", |
| 1011 | printable(&target.state) |
| 1012 | ); |
| 1013 | } |
| 1014 | if recovery_from.is_none() { |
| 1015 | verify_launch_authority(client, &mut target)?; |
| 1016 | } |
| 1017 | let offer = load_work_offer(client)?; |
| 1018 | let seconds = seconds.unwrap_or_else(|| default_seconds(&offer)); |
| 1019 | if seconds < offer.min_seconds || seconds > offer.max_seconds { |
| 1020 | bail!( |
| 1021 | "Task time must be within the served offer: {}-{} seconds", |
| 1022 | offer.min_seconds, |
| 1023 | offer.max_seconds |
| 1024 | ); |
| 1025 | } |
| 1026 | if target.repo.is_empty() && !offer.empty_workspace { |
| 1027 | bail!("The account's Work offer does not support an empty workspace"); |
| 1028 | } |
| 1029 | if offer.funding == "compute_cu" |
| 1030 | && offer |
| 1031 | .remaining_seconds |
| 1032 | .is_some_and(|remaining| remaining < seconds) |
| 1033 | { |
| 1034 | bail!("The computer balance does not cover the reviewed task time"); |
| 1035 | } |
| 1036 | let body = launch_body(&target, operation_key, seconds, recovery_from)?; |
| 1037 | let response = client.execute_authenticated( |
| 1038 | HttpMethod::Post, |
| 1039 | "/api/sandbox/launch-quote", |
| 1040 | Some(json_body(&body)?), |
| 1041 | )?; |
| 1042 | if response.status != 200 { |
| 1043 | let err = response_error(&response); |
| 1044 | return Err(match http_code(&err).and_then(launch_hint) { |
| 1045 | Some(hint) => err.context(hint), |
| 1046 | None => err, |
| 1047 | }); |
| 1048 | } |
| 1049 | let quote: Value = parse_json_body(&response.body)?; |
| 1050 | |
| 1051 | let quoted_seconds = count_at("e, &["disclosure", "computerTime", "estimatedSeconds"]); |
| 1052 | let expected = at("e, &["disclosure", "funding"]).and_then(Value::as_str) |
| 1053 | == Some(offer.funding.as_str()) |
| 1054 | && at("e, &["disclosure", "customerCreditsChargedUsd"]).and_then(Value::as_f64) |
| 1055 | == Some(0.0) |
| 1056 | && str_at("e, &["quote", "sku"]) == Some(WORK_SKU) |
| 1057 | && str_at("e, &["disclosure", "sandboxTargetRegion"]) == Some("eu") |
| 1058 | && str_at("e, &["disclosure", "modelInference", "billing"]) == Some("byok_external") |
| 1059 | && quoted_seconds == Some(seconds) |
| 1060 | && (offer.funding != "compute_cu" |
| 1061 | || (at( |
| 1062 | "e, |
| 1063 | &["disclosure", "computerTime", "coveredByComputeBalance"], |
| 1064 | ) |
| 1065 | .and_then(Value::as_bool) |
| 1066 | == Some(true) |
| 1067 | && count_at( |
| 1068 | "e, |
| 1069 | &["disclosure", "computerTime", "remainingAfterSeconds"], |
| 1070 | ) |
| 1071 | .is_some())) |
| 1072 | && (if target.repo.is_empty() { |
| 1073 | str_at("e, &["workspace", "source"]) == Some("empty") |
| 1074 | && at("e, &["workspace", "clone"]).and_then(Value::as_bool) == Some(false) |
| 1075 | && at("e, &["workspace", "repository"]).is_none_or(Value::is_null) |
| 1076 | } else { |
| 1077 | str_at("e, &["workspace", "source"]) != Some("empty") |
| 1078 | }); |
| 1079 | if !expected { |
| 1080 | bail!( |
| 1081 | "The Codewhale service quoted different terms from the reviewed Work offer. Refusing to print a confirmation for it; nothing started" |
| 1082 | ); |
| 1083 | } |
| 1084 | let token = str_at("e, &["confirmation", "token"]).unwrap_or_default(); |
| 1085 | if !valid_confirmation(token) |
| 1086 | || str_at("e, &["confirmation", "workRunId"]).is_some_and(|quoted| quoted != id) |
| 1087 | || recovery_from.is_some_and(|previous| { |
| 1088 | str_at("e, &["confirmation", "workRunId"]) != Some(id) |
| 1089 | || at("e, &["confirmation", "recovery"]).and_then(Value::as_bool) != Some(true) |
| 1090 | || str_at("e, &["confirmation", "expectedPreviousWorkspaceId"]) |
| 1091 | != Some(previous) |
| 1092 | }) |
| 1093 | { |
| 1094 | bail!("The Codewhale service returned an unusable launch confirmation"); |
| 1095 | } |
| 1096 | writeln!( |
| 1097 | out, |
| 1098 | "Cloud Work quote. Nothing has started and nothing is charged." |
| 1099 | )?; |
| 1100 | writeln!(out, "Work ID: {id}")?; |
| 1101 | if target.repo.is_empty() { |
| 1102 | writeln!(out, "Workspace: empty; no repository will be cloned")?; |
| 1103 | } else { |
| 1104 | writeln!(out, "Repository: {}", printable(&target.repo))?; |
| 1105 | } |
| 1106 | if let Some(previous) = recovery_from { |
| 1107 | writeln!( |
| 1108 | out, |
| 1109 | "Recovery: fresh computer; Work ID retained; previous workspace {}", |
| 1110 | printable(previous) |
| 1111 | )?; |
| 1112 | } |
| 1113 | writeln!( |
| 1114 | out, |
| 1115 | "Model: {WORK_MODEL_PROVIDER}/{WORK_MODEL} with your own DeepSeek key; DeepSeek bills your BYOK usage directly" |
| 1116 | )?; |
| 1117 | writeln!( |
| 1118 | out, |
| 1119 | "Computer: small cloud computer in the EU, up to {seconds} seconds" |
| 1120 | )?; |
| 1121 | if offer.funding == "compute_cu" { |
| 1122 | writeln!( |
| 1123 | out, |
| 1124 | "Funding: account computer balance; up to {seconds} seconds; Codewhale credits charged: $0" |
| 1125 | )?; |
| 1126 | if let Some(remaining) = offer.remaining_seconds { |
| 1127 | writeln!(out, "Computer balance at review: {remaining} seconds")?; |
| 1128 | } |
| 1129 | } else { |
| 1130 | writeln!(out, "Funding: trial credit; Codewhale credits charged: $0")?; |
| 1131 | } |
| 1132 | if let Some(estimate) = |
| 1133 | at("e, &["disclosure", "providerCostEstimateUsd"]).and_then(Value::as_f64) |
| 1134 | { |
| 1135 | writeln!(out, "Provider cost estimate: {}", usd(estimate))?; |
| 1136 | } |
| 1137 | writeln!( |
| 1138 | out, |
| 1139 | "EU placement: Codewhale admission attestation. Repository code and Work files are admitted to EU compute." |
| 1140 | )?; |
| 1141 | if let Some(title) = text_at("e, &["confirmCopy", "title"]) { |
| 1142 | writeln!(out, "{title}")?; |
| 1143 | } |
| 1144 | if let Some(copy) = str_at("e, &["confirmCopy", "body"]) |
| 1145 | .map(|body| vendor_safe_prose(printable_max(body, 800))) |
| 1146 | .filter(|body| !body.is_empty()) |
| 1147 | { |
| 1148 | writeln!(out, "{copy}")?; |
| 1149 | } |
| 1150 | if let Some(expires) = text_at("e, &["confirmation", "expiresAt"]) { |
| 1151 | writeln!(out, "Confirmation expires: {expires}")?; |
| 1152 | } |
| 1153 | writeln!(out, "Operation key: {operation_key}")?; |
| 1154 | if reveal { |
| 1155 | writeln!(out, "Confirmation: {token}")?; |
| 1156 | let recovery_args = recovery_from |
| 1157 | .map(|previous| format!(" --recovery-from {previous}")) |
| 1158 | .unwrap_or_default(); |
| 1159 | writeln!( |
| 1160 | out, |
| 1161 | "To start: codewhale account agents work-launch {id} --operation-key {operation_key} --confirmation {token} --confirm-eu-compute --seconds {seconds}{recovery_args}" |
| 1162 | )?; |
| 1163 | } |
| 1164 | Ok(QuotedLaunch { |
| 1165 | token: token.to_string(), |
| 1166 | seconds, |
| 1167 | }) |
| 1168 | } |
| 1169 | |
| 1170 | pub(super) struct QuotedLaunch { |
| 1171 | token: String, |
| 1172 | seconds: u64, |
| 1173 | } |
| 1174 | |
| 1175 | pub(super) struct DispatchOptions<'a> { |
| 1176 | pub seconds: Option<u64>, |
| 1177 | pub operation_key: &'a str, |
| 1178 | pub message_id: &'a str, |
| 1179 | pub yes: bool, |
| 1180 | pub confirm_eu_compute: bool, |
| 1181 | pub interactive: bool, |
| 1182 | } |
| 1183 | |
| 1184 | /// `codewhale dispatch`: record Work, review its quote, then launch it once |
| 1185 | /// the member has consented to EU compute for this launch. |
| 1186 | pub(super) fn dispatch<T: CloudTransport, W: Write>( |
| 1187 | client: &CloudClient<'_, T>, |
| 1188 | out: &mut W, |
| 1189 | agent: &AccountAgent, |
| 1190 | objective: &str, |
| 1191 | context: Option<&WorkTaskContext>, |
| 1192 | options: DispatchOptions<'_>, |
| 1193 | read_answer: &mut dyn FnMut() -> Result<String>, |
| 1194 | ) -> Result<()> { |
| 1195 | let mut recorded = Vec::new(); |
| 1196 | let ids = assign( |
| 1197 | client, |
| 1198 | &mut recorded, |
| 1199 | agent, |
| 1200 | objective, |
| 1201 | options.message_id, |
| 1202 | context, |
| 1203 | )?; |
| 1204 | let [id] = ids.as_slice() else { |
| 1205 | out.write_all(&recorded)?; |
| 1206 | bail!("This message did not create exactly one new Work, so nothing was quoted or started"); |
| 1207 | }; |
| 1208 | let recorded_text = String::from_utf8_lossy(&recorded); |
| 1209 | if !recorded_text |
| 1210 | .lines() |
| 1211 | .any(|line| matches!(line.trim(), "Intent: actionable" | "Intent: queued")) |
| 1212 | { |
| 1213 | out.write_all(&recorded)?; |
| 1214 | bail!("This message was not read as new Work, so nothing was quoted or started"); |
| 1215 | } |
| 1216 | writeln!(out, "Message ID: {}", options.message_id)?; |
| 1217 | writeln!(out, "Work ID: {id}")?; |
| 1218 | let quoted = quote( |
| 1219 | client, |
| 1220 | out, |
| 1221 | id, |
| 1222 | options.operation_key, |
| 1223 | options.seconds, |
| 1224 | None, |
| 1225 | false, |
| 1226 | )?; |
| 1227 | let consented = if options.yes && options.confirm_eu_compute { |
| 1228 | true |
| 1229 | } else if options.interactive { |
| 1230 | write!( |
| 1231 | out, |
| 1232 | "Start this on a new cloud computer in the EU? Your repository code and Work files run there. [y/N] " |
| 1233 | )?; |
| 1234 | out.flush()?; |
| 1235 | matches!( |
| 1236 | read_answer()?.trim().to_ascii_lowercase().as_str(), |
| 1237 | "y" | "yes" |
| 1238 | ) |
| 1239 | } else { |
| 1240 | false |
| 1241 | }; |
| 1242 | if !consented { |
| 1243 | bail!( |
| 1244 | "Nothing started. Work {id} is recorded; to start it re-run with --yes --confirm-eu-compute --message-id {} --operation-key {}", |
| 1245 | options.message_id, |
| 1246 | options.operation_key |
| 1247 | ); |
| 1248 | } |
| 1249 | launch( |
| 1250 | client, |
| 1251 | out, |
| 1252 | id, |
| 1253 | options.operation_key, |
| 1254 | "ed.token, |
| 1255 | true, |
| 1256 | Some(quoted.seconds), |
| 1257 | None, |
| 1258 | )?; |
| 1259 | writeln!( |
| 1260 | out, |
| 1261 | "Status: codewhale dispatch --show {id} Stop: codewhale dispatch --cancel {id}" |
| 1262 | )?; |
| 1263 | Ok(()) |
| 1264 | } |
| 1265 | |
| 1266 | /// `codewhale account agents work-launch`. |
| 1267 | pub(super) fn launch<T: CloudTransport, W: Write>( |
| 1268 | client: &CloudClient<'_, T>, |
| 1269 | out: &mut W, |
| 1270 | id: &str, |
| 1271 | operation_key: &str, |
| 1272 | confirmation: &str, |
| 1273 | confirm_eu_compute: bool, |
| 1274 | seconds: Option<u64>, |
| 1275 | recovery_from: Option<&str>, |
| 1276 | ) -> Result<()> { |
| 1277 | if !confirm_eu_compute { |
| 1278 | bail!( |
| 1279 | "Cloud Work runs your source context and Work files on a cloud computer in the EU. Nothing was sent; re-run with --confirm-eu-compute to agree" |
| 1280 | ); |
| 1281 | } |
| 1282 | let id = validate_work_uuid(id)?; |
| 1283 | let operation_key = validate_operation_key(operation_key)?; |
| 1284 | let confirmation = confirmation.trim(); |
| 1285 | if !valid_confirmation(confirmation) { |
| 1286 | bail!("Confirmation must be the value printed by `codewhale account agents work-quote`"); |
| 1287 | } |
| 1288 | let mut target = load_launch_target(client, id)?; |
| 1289 | // A queued Work is checked against the Agent and Project as they are now. |
| 1290 | // Any other state is a replay of a launch that already ran (or a Work that |
| 1291 | // cannot launch); the control plane's operation ledger decides which, so |
| 1292 | // the same command stays safe to repeat after a lost reply. |
| 1293 | if target.state == "queued" && recovery_from.is_none() { |
| 1294 | verify_launch_authority(client, &mut target)?; |
| 1295 | } |
| 1296 | let seconds = match seconds { |
| 1297 | Some(seconds) => seconds, |
| 1298 | None => default_seconds(&load_work_offer(client)?), |
| 1299 | }; |
| 1300 | let mut body = launch_body(&target, operation_key, seconds, recovery_from)?; |
| 1301 | body["launchQuoteConfirmation"] = json!(confirmation); |
| 1302 | body["customerEuPlacementConsent"] = json!(true); |
| 1303 | |
| 1304 | let refused = |err: anyhow::Error| -> anyhow::Error { |
| 1305 | if http_code(&err) == Some("boat_task_replay_expired") { |
| 1306 | return err.context(format!( |
| 1307 | "The launch outcome is unknown and the provider's safe replay window expired. Run `codewhale account agents work-status {id}` and `work-result {id}`; operator reconciliation is required. Do not submit a new operation key or retry the provider allocation" |
| 1308 | )); |
| 1309 | } |
| 1310 | if outcome_unknown(&err) { |
| 1311 | return err.context(format!( |
| 1312 | "The launch outcome is unknown, and a computer may already be running. Run `codewhale account agents work-status {id}` (and `work-cancel {id}` to stop it). To retry, re-run this exact command with the same --operation-key and --confirmation; it replays the launch and cannot start a second computer" |
| 1313 | )); |
| 1314 | } |
| 1315 | match http_code(&err) { |
| 1316 | Some("launch_in_progress" | "launch_idempotency_commit_failed") => err.context( |
| 1317 | "This launch is still being recorded. Re-run this exact command with the same --operation-key and --confirmation", |
| 1318 | ), |
| 1319 | Some(code) => match launch_hint(code) { |
| 1320 | Some(hint) => err.context(hint), |
| 1321 | None => err.context("The launch was refused"), |
| 1322 | }, |
| 1323 | None => err, |
| 1324 | } |
| 1325 | }; |
| 1326 | let response = client |
| 1327 | .execute_authenticated( |
| 1328 | HttpMethod::Post, |
| 1329 | "/api/cloud-sessions", |
| 1330 | Some(json_body(&body)?), |
| 1331 | ) |
| 1332 | .map_err(refused)?; |
| 1333 | if !matches!(response.status, 200..=202) { |
| 1334 | return Err(refused(response_error(&response))); |
| 1335 | } |
| 1336 | let reply = parse_reply( |
| 1337 | &response.body, |
| 1338 | "The Codewhale service returned an unreadable launch reply", |
| 1339 | ) |
| 1340 | .map_err(refused)?; |
| 1341 | // The service acted, so a reply without its `session` document is an |
| 1342 | // unknown outcome, not a success and not a different Work. |
| 1343 | let Some(session) = reply.get("session").filter(|value| value.is_object()) else { |
| 1344 | return Err(refused( |
| 1345 | CloudTransportError::new( |
| 1346 | "The Codewhale service returned a launch reply without a session", |
| 1347 | std::io::Error::other("missing session"), |
| 1348 | ) |
| 1349 | .into(), |
| 1350 | )); |
| 1351 | }; |
| 1352 | let Some(returned_run_id) = str_at(session, &["run", "id"]) else { |
| 1353 | return Err(refused( |
| 1354 | CloudTransportError::new( |
| 1355 | "The Codewhale service returned a launch reply without a Work ID", |
| 1356 | std::io::Error::other("missing Work ID"), |
| 1357 | ) |
| 1358 | .into(), |
| 1359 | )); |
| 1360 | }; |
| 1361 | if returned_run_id != id { |
| 1362 | bail!( |
| 1363 | "The Codewhale service launched a different Work than requested. Run `codewhale account agents work-status {id}` before doing anything else" |
| 1364 | ); |
| 1365 | } |
| 1366 | if let Some(previous) = recovery_from { |
| 1367 | let workspace = str_at(session, &["workspace", "id"]); |
| 1368 | let matches = workspace.is_some_and(|workspace| { |
| 1369 | workspace != previous |
| 1370 | && validate_resource_id(workspace, "Workspace").is_ok() |
| 1371 | && str_at(session, &["attempt", "kind"]) == Some("recovery") |
| 1372 | && str_at(session, &["attempt", "workRunId"]) == Some(id) |
| 1373 | && str_at(session, &["attempt", "workspaceId"]) == Some(workspace) |
| 1374 | && str_at(session, &["attempt", "previousWorkspaceId"]) == Some(previous) |
| 1375 | && str_at(session, &["recovery", "workId"]) == Some(id) |
| 1376 | && str_at(session, &["recovery", "workspaceId"]) == Some(workspace) |
| 1377 | && str_at(session, &["recovery", "previousWorkspaceId"]) == Some(previous) |
| 1378 | }); |
| 1379 | if !matches { |
| 1380 | return Err(refused( |
| 1381 | CloudTransportError::new( |
| 1382 | "The reply does not confirm the reviewed replacement attempt", |
| 1383 | std::io::Error::other("recovery identity mismatch"), |
| 1384 | ) |
| 1385 | .into(), |
| 1386 | )); |
| 1387 | } |
| 1388 | writeln!( |
| 1389 | out, |
| 1390 | "Work recovered on a fresh cloud computer; the original Work ID is retained." |
| 1391 | )?; |
| 1392 | } else { |
| 1393 | writeln!(out, "Work launched on a cloud computer.")?; |
| 1394 | } |
| 1395 | writeln!(out, "Work ID: {id}")?; |
| 1396 | writeln!( |
| 1397 | out, |
| 1398 | "Status: {}", |
| 1399 | text_at(session, &["run", "state"]).unwrap_or_else(|| "unknown".to_string()) |
| 1400 | )?; |
| 1401 | if let Some(session_id) = text_at(session, &["id"]) { |
| 1402 | writeln!(out, "Session: {session_id}")?; |
| 1403 | } |
| 1404 | if let Some(status) = text_at(session, &["sandbox", "status"]) { |
| 1405 | writeln!(out, "Computer: {status}")?; |
| 1406 | } |
| 1407 | if let Some(region) = text_at(session, &["sandboxTargetRegion"]) { |
| 1408 | writeln!(out, "Compute region: {region}")?; |
| 1409 | } |
| 1410 | if let Some(charged) = |
| 1411 | at(session, &["quote", "customerCreditsChargedUsd"]).and_then(Value::as_f64) |
| 1412 | { |
| 1413 | writeln!(out, "Codewhale credits charged: {}", usd(charged))?; |
| 1414 | } |
| 1415 | if let Some(attempt) = text_at(session, &["attempt", "status"]) { |
| 1416 | writeln!(out, "Attempt: {attempt}")?; |
| 1417 | } |
| 1418 | if let Some(turn) = text_at(session, &["initialTurn", "status"]) { |
| 1419 | writeln!(out, "First turn: {turn} (not complete yet)")?; |
| 1420 | } |
| 1421 | writeln!(out, "Operation key: {operation_key}")?; |
| 1422 | writeln!( |
| 1423 | out, |
| 1424 | "Follow it: codewhale account agents work-status {id}, then work-result {id}. Stop it: work-cancel {id}" |
| 1425 | )?; |
| 1426 | Ok(()) |
| 1427 | } |
| 1428 | |
| 1429 | /// `codewhale account github bind`. |
| 1430 | pub(super) fn bind_github_repo<T: CloudTransport, W: Write>( |
| 1431 | client: &CloudClient<'_, T>, |
| 1432 | out: &mut W, |
| 1433 | repo: &str, |
| 1434 | installation_id: Option<&str>, |
| 1435 | ) -> Result<()> { |
| 1436 | let repo = validate_github_repo(repo)?; |
| 1437 | let installation_id = installation_id |
| 1438 | .map(|value| { |
| 1439 | let value = value.trim(); |
| 1440 | if value.is_empty() |
| 1441 | || value.len() > 20 |
| 1442 | || !value.bytes().all(|byte| byte.is_ascii_digit()) |
| 1443 | { |
| 1444 | bail!("GitHub installation ID must be the numeric ID of the installed app"); |
| 1445 | } |
| 1446 | Ok(value.to_string()) |
| 1447 | }) |
| 1448 | .transpose()?; |
| 1449 | let listing: GitHubBindingListResponse = serde_json::from_value(client.github_bindings()?) |
| 1450 | .context("The Codewhale service returned an invalid GitHub repository list")?; |
| 1451 | let usable = |status: &str| { |
| 1452 | !["error", "revoked", "suspended", "disabled"] |
| 1453 | .contains(&status.to_ascii_lowercase().as_str()) |
| 1454 | }; |
| 1455 | if let Some(existing) = listing.bindings.iter().find(|binding| { |
| 1456 | binding.provider == "github" |
| 1457 | && binding.repo.eq_ignore_ascii_case(&repo) |
| 1458 | && !binding.installation_id.is_empty() |
| 1459 | && usable(&binding.status) |
| 1460 | && installation_id |
| 1461 | .as_deref() |
| 1462 | .is_none_or(|requested| requested == binding.installation_id) |
| 1463 | }) { |
| 1464 | writeln!( |
| 1465 | out, |
| 1466 | "{} is already connected: {} ({})", |
| 1467 | printable(&existing.repo), |
| 1468 | printable(&existing.id), |
| 1469 | printable(&existing.status) |
| 1470 | )?; |
| 1471 | writeln!( |
| 1472 | out, |
| 1473 | "Create a Project: codewhale account projects create NAME --repo-binding-id {} --operation-key <new-key>", |
| 1474 | printable(&existing.id) |
| 1475 | )?; |
| 1476 | return Ok(()); |
| 1477 | } |
| 1478 | let installation_id = match installation_id { |
| 1479 | Some(id) => id, |
| 1480 | None => { |
| 1481 | let mut known = listing |
| 1482 | .bindings |
| 1483 | .iter() |
| 1484 | .filter(|binding| binding.provider == "github") |
| 1485 | .map(|binding| binding.installation_id.as_str()) |
| 1486 | .filter(|id| !id.is_empty()) |
| 1487 | .collect::<Vec<_>>(); |
| 1488 | known.sort_unstable(); |
| 1489 | known.dedup(); |
| 1490 | match known.as_slice() { |
| 1491 | [only] => (*only).to_string(), |
| 1492 | [] => bail!( |
| 1493 | "No GitHub App installation is known for this account yet. Install the Codewhale GitHub App, then pass its numeric ID with --installation-id" |
| 1494 | ), |
| 1495 | many => bail!( |
| 1496 | "This account has several GitHub App installations ({}); choose one with --installation-id", |
| 1497 | many.iter() |
| 1498 | .map(|id| printable(id)) |
| 1499 | .collect::<Vec<_>>() |
| 1500 | .join(", ") |
| 1501 | ), |
| 1502 | } |
| 1503 | } |
| 1504 | }; |
| 1505 | let response = client |
| 1506 | .execute_authenticated( |
| 1507 | HttpMethod::Post, |
| 1508 | "/api/integrations/github/bindings", |
| 1509 | Some(json_body(&json!({ |
| 1510 | "installationId": installation_id, |
| 1511 | "repo": repo, |
| 1512 | }))?), |
| 1513 | ) |
| 1514 | .map_err(|err| { |
| 1515 | if outcome_unknown(&err) { |
| 1516 | err.context( |
| 1517 | "The bind outcome is unknown. Run `codewhale account github bindings` to see whether it was saved; binding is safe to repeat", |
| 1518 | ) |
| 1519 | } else { |
| 1520 | err |
| 1521 | } |
| 1522 | })?; |
| 1523 | if response.status == 404 { |
| 1524 | return Err(response_error(&response)).context( |
| 1525 | "GitHub repository bindings are unavailable on this Codewhale API, or this repository is not reachable through that installation", |
| 1526 | ); |
| 1527 | } |
| 1528 | if !matches!(response.status, 200 | 201) { |
| 1529 | let err = response_error(&response); |
| 1530 | return Err(if outcome_unknown(&err) { |
| 1531 | err.context( |
| 1532 | "The bind outcome is unknown. Run `codewhale account github bindings` to see whether it was saved; binding is safe to repeat", |
| 1533 | ) |
| 1534 | } else { |
| 1535 | err |
| 1536 | }); |
| 1537 | } |
| 1538 | let reply = parse_reply(&response.body, "The Codewhale service returned an unreadable bind reply") |
| 1539 | .map_err(|err| { |
| 1540 | err.context( |
| 1541 | "The bind outcome is unknown. Run `codewhale account github bindings` to see whether it was saved", |
| 1542 | ) |
| 1543 | })?; |
| 1544 | let binding: AccountGitHubBinding = |
| 1545 | serde_json::from_value(reply.get("binding").cloned().unwrap_or(Value::Null)) |
| 1546 | .context("The Codewhale service returned an invalid GitHub repository binding")?; |
| 1547 | if binding.provider != "github" |
| 1548 | || binding.id.is_empty() |
| 1549 | || !binding.repo.eq_ignore_ascii_case(&repo) |
| 1550 | { |
| 1551 | bail!("The Codewhale service returned a binding for a different repository"); |
| 1552 | } |
| 1553 | writeln!( |
| 1554 | out, |
| 1555 | "Connected {}: {} ({})", |
| 1556 | printable(&binding.repo), |
| 1557 | printable(&binding.id), |
| 1558 | printable(&binding.status) |
| 1559 | )?; |
| 1560 | writeln!( |
| 1561 | out, |
| 1562 | "Create a Project: codewhale account projects create NAME --repo-binding-id {} --operation-key <new-key>", |
| 1563 | printable(&binding.id) |
| 1564 | )?; |
| 1565 | Ok(()) |
| 1566 | } |
| 1567 |