| 1 | #![allow(clippy::too_many_arguments)] |
| 2 | |
| 3 | //! Codewhale account and BYOK credential commands. |
| 4 | //! |
| 5 | //! This module is deliberately separate from the provider-facing `login` and |
| 6 | //! `auth` commands in `lib.rs`: those configure the local runtime, while this |
| 7 | //! surface signs a CLI profile into the managed Codewhale account and stores |
| 8 | //! provider keys in that account's remote vault. |
| 9 | |
| 10 | use std::io::{self, IsTerminal, Read, Write}; |
| 11 | use std::net::IpAddr; |
| 12 | use std::path::{Path, PathBuf}; |
| 13 | use std::thread; |
| 14 | use std::time::Duration; |
| 15 | |
| 16 | use anyhow::{Context, Result, anyhow, bail}; |
| 17 | use clap::{Args, Subcommand, ValueEnum}; |
| 18 | use codewhale_config::device_code::DevicePollOutcome; |
| 19 | use codewhale_config::{ConfigStore, ProviderKind}; |
| 20 | use codewhale_secrets::Secrets; |
| 21 | use codewhale_secrets::account::{ |
| 22 | ACCOUNT_API_BASE_ENV as CLOUD_API_BASE_ENV, AccountAuthBundle as AuthBundle, |
| 23 | AccountSessionSnapshot, AccountSessionStore, AccountUser as CloudUser, |
| 24 | DEFAULT_ACCOUNT_API_BASE as DEFAULT_API_BASE, StoredAccountAuth as StoredCloudAuth, |
| 25 | normalize_account_profile as normalized_profile, secure_account_session_secrets, |
| 26 | validate_account_auth_bundle as validate_auth_bundle, |
| 27 | }; |
| 28 | use reqwest::Url; |
| 29 | use serde::{Deserialize, Serialize, de::DeserializeOwned}; |
| 30 | |
| 31 | mod claude_org; |
| 32 | mod computer; |
| 33 | pub mod dispatch; |
| 34 | pub mod machine; |
| 35 | mod session; |
| 36 | |
| 37 | pub use claude_org::{ |
| 38 | ClaudeOrgError, ClaudeOrgErrorKind, ClaudeOrgLinkFailure, ClaudeOrgLinkStatus, ClaudeOrgToken, |
| 39 | }; |
| 40 | pub use session::{ |
| 41 | AccountAuthLease, AccountClient, AccountLogin, AccountLoginCancellation, AccountLoginPoll, |
| 42 | AccountLoginPrompt, AccountModel, AccountModels, AccountStatus, account_api_base, |
| 43 | }; |
| 44 | mod work; |
| 45 | |
| 46 | const MAX_RESPONSE_BYTES: u64 = 256 * 1024; |
| 47 | const MAX_FILE_DOWNLOAD_BYTES: u64 = 25 * 1024 * 1024; |
| 48 | const MAX_COMPUTER_FILE_SAVE_BYTES: u64 = 16 * 1024 * 1024; |
| 49 | const MAX_COMPUTER_FILE_RESTORE_BYTES: u64 = 4 * 1024 * 1024; |
| 50 | const MAX_FILE_VERSION: u64 = 9_007_199_254_740_991; |
| 51 | const MIN_API_KEY_BYTES: usize = 8; |
| 52 | const MAX_API_KEY_BYTES: u64 = 4096; |
| 53 | const MAX_API_KEY_STDIN_BYTES: u64 = MAX_API_KEY_BYTES + 1024; |
| 54 | const MAX_KEY_LABEL_CHARS: usize = 80; |
| 55 | pub const ACCOUNT_SIGN_IN_OPEN: bool = false; |
| 56 | |
| 57 | pub fn account_sign_in_closed_message() -> String { |
| 58 | codewhale_localization::tr( |
| 59 | codewhale_localization::resolve_locale("auto"), |
| 60 | codewhale_localization::MessageId::AccountSignInClosed, |
| 61 | ) |
| 62 | .into_owned() |
| 63 | } |
| 64 | pub const DEFAULT_LOGIN_TIMEOUT_SECONDS: u64 = 600; |
| 65 | pub const MAX_LOGIN_TIMEOUT_SECONDS: u64 = 3600; |
| 66 | |
| 67 | #[derive(Debug, Args)] |
| 68 | pub struct CloudArgs { |
| 69 | /// Codewhale account API origin. HTTPS is required except for loopback HTTP. |
| 70 | #[arg(long, global = true, value_name = "URL")] |
| 71 | api_base: Option<String>, |
| 72 | #[command(subcommand)] |
| 73 | command: CloudCommand, |
| 74 | } |
| 75 | |
| 76 | #[derive(Debug, Subcommand)] |
| 77 | enum CloudCommand { |
| 78 | /// Sign this CLI profile in through the browser device flow. |
| 79 | Login(CloudLoginArgs), |
| 80 | /// Show the signed-in account for this CLI profile. |
| 81 | Status, |
| 82 | /// Remove this profile's local account session and revoke it when reachable. |
| 83 | Logout, |
| 84 | /// Manage provider API keys stored in the signed-in Codewhale account. |
| 85 | /// |
| 86 | /// These are credentials Codewhale presents *to* a model provider. For the |
| 87 | /// machine tokens a customer presents *to* Codewhale, see `api-keys`. |
| 88 | Keys(CloudKeysArgs), |
| 89 | /// Manage Computers in this signed-in Codewhale account. |
| 90 | Computers(CloudComputersArgs), |
| 91 | #[command(about = "Start or continue an account conversation on a cloud computer")] |
| 92 | Session(computer::SessionArgs), |
| 93 | /// List Projects available to this signed-in Codewhale account. |
| 94 | Projects(CloudProjectsArgs), |
| 95 | /// Inspect GitHub repositories authorized for this account. |
| 96 | Github(CloudGithubArgs), |
| 97 | /// Manage named Agents and their account conversations. |
| 98 | Agents(CloudAgentsArgs), |
| 99 | /// Manage Codewhale account API keys: machine tokens for CI. |
| 100 | #[command(name = "api-keys")] |
| 101 | ApiKeys(machine::ApiKeysArgs), |
| 102 | /// Show the account this CLI authenticates as, preferring a machine key. |
| 103 | Whoami, |
| 104 | /// Check the account's agent-model precondition for machine work. |
| 105 | Agent, |
| 106 | /// Link a Claude Platform organization so Anthropic bills it directly. |
| 107 | #[command(name = "claude-org")] |
| 108 | ClaudeOrg(claude_org::ClaudeOrgArgs), |
| 109 | /// Inspect the account document; local settings import is not available yet. |
| 110 | Pull(CloudPullArgs), |
| 111 | /// Push local settings to the account document (never automatic, --dry-run required). |
| 112 | Push(CloudPushArgs), |
| 113 | } |
| 114 | |
| 115 | #[derive(Debug, Args)] |
| 116 | struct CloudLoginArgs { |
| 117 | /// Print the verification URL without trying to open a browser. |
| 118 | #[arg(long, default_value_t = false)] |
| 119 | no_open: bool, |
| 120 | /// Maximum time to wait for browser authorization. |
| 121 | #[arg( |
| 122 | long = "timeout-seconds", |
| 123 | default_value_t = DEFAULT_LOGIN_TIMEOUT_SECONDS, |
| 124 | value_parser = clap::value_parser!(u64).range(1..=MAX_LOGIN_TIMEOUT_SECONDS) |
| 125 | )] |
| 126 | timeout_seconds: u64, |
| 127 | } |
| 128 | |
| 129 | #[derive(Debug, Args)] |
| 130 | struct CloudPullArgs { |
| 131 | /// Inspect the account document without writing local files. |
| 132 | #[arg(long, default_value_t = false)] |
| 133 | dry_run: bool, |
| 134 | } |
| 135 | |
| 136 | #[derive(Debug, Args)] |
| 137 | struct CloudPushArgs { |
| 138 | /// Show what would be pushed without writing the remote document. |
| 139 | #[arg(long, default_value_t = false)] |
| 140 | dry_run: bool, |
| 141 | } |
| 142 | |
| 143 | #[derive(Debug, Args)] |
| 144 | struct CloudKeysArgs { |
| 145 | #[command(subcommand)] |
| 146 | command: CloudKeysCommand, |
| 147 | } |
| 148 | |
| 149 | #[derive(Debug, Args)] |
| 150 | struct CloudComputersArgs { |
| 151 | #[command(subcommand)] |
| 152 | command: CloudComputersCommand, |
| 153 | } |
| 154 | |
| 155 | #[derive(Debug, Args)] |
| 156 | struct CloudAgentsArgs { |
| 157 | #[command(subcommand)] |
| 158 | command: CloudAgentsCommand, |
| 159 | } |
| 160 | |
| 161 | #[derive(Debug, Args)] |
| 162 | struct CloudProjectsArgs { |
| 163 | #[command(subcommand)] |
| 164 | command: CloudProjectsCommand, |
| 165 | } |
| 166 | |
| 167 | #[derive(Debug, Args)] |
| 168 | struct CloudGithubArgs { |
| 169 | #[command(subcommand)] |
| 170 | command: CloudGithubCommand, |
| 171 | } |
| 172 | |
| 173 | #[derive(Debug, Subcommand)] |
| 174 | enum CloudGithubCommand { |
| 175 | /// List repository bindings saved by GitHub App installation. |
| 176 | Bindings { |
| 177 | #[arg(long)] |
| 178 | json: bool, |
| 179 | }, |
| 180 | /// Connect one repository from an installed GitHub App to this account. |
| 181 | /// |
| 182 | /// The account API checks that you own the installation and can read the |
| 183 | /// repository; nothing is written to GitHub. Omit --installation-id when |
| 184 | /// every repository already connected shares one installation. |
| 185 | Bind { |
| 186 | /// Repository as OWNER/REPO. |
| 187 | repo: String, |
| 188 | /// GitHub App installation ID (see `account github bindings --json`). |
| 189 | #[arg(long)] |
| 190 | installation_id: Option<String>, |
| 191 | }, |
| 192 | } |
| 193 | |
| 194 | #[derive(Debug, Subcommand)] |
| 195 | enum CloudProjectsCommand { |
| 196 | /// List account Projects; use an ID when binding an Agent. |
| 197 | List { |
| 198 | #[arg(long)] |
| 199 | json: bool, |
| 200 | }, |
| 201 | /// Create a Project from a GitHub repository already connected to this account. |
| 202 | Create { |
| 203 | name: String, |
| 204 | #[arg(long)] |
| 205 | repo_binding_id: String, |
| 206 | #[arg(long)] |
| 207 | operation_key: String, |
| 208 | }, |
| 209 | } |
| 210 | |
| 211 | #[derive(Debug, Subcommand)] |
| 212 | enum CloudAgentsCommand { |
| 213 | /// List active Agents in this account. |
| 214 | List { |
| 215 | #[arg(long)] |
| 216 | json: bool, |
| 217 | }, |
| 218 | /// Create a named Agent. Reuse the operation key if a response is lost. |
| 219 | Create { |
| 220 | name: String, |
| 221 | /// Assign an existing account Project to this Agent. |
| 222 | #[arg(long)] |
| 223 | project_id: Option<String>, |
| 224 | /// Exact configured provider id saved in the whale's Fleet member. |
| 225 | #[arg(long, requires = "model")] |
| 226 | provider: Option<String>, |
| 227 | /// Exact model id on that provider. |
| 228 | #[arg(long, requires = "provider")] |
| 229 | model: Option<String>, |
| 230 | #[arg(long)] |
| 231 | operation_key: String, |
| 232 | }, |
| 233 | /// Assign an existing Project to an Agent, checking its saved revision. |
| 234 | BindProject { agent: String, project_id: String }, |
| 235 | /// List recent, active conversations for a named Agent or Agent ID. |
| 236 | Threads { |
| 237 | agent: String, |
| 238 | #[arg(long)] |
| 239 | json: bool, |
| 240 | }, |
| 241 | /// Create an Agent conversation with an explicit saved model route. |
| 242 | NewThread { |
| 243 | agent: String, |
| 244 | #[arg(long, default_value = "Main")] |
| 245 | title: String, |
| 246 | #[arg(long, default_value = "deepseek")] |
| 247 | provider: String, |
| 248 | #[arg(long, default_value = "deepseek-flash")] |
| 249 | model: String, |
| 250 | #[arg(long)] |
| 251 | operation_key: String, |
| 252 | }, |
| 253 | /// Send one message to a selected conversation, using its saved model. |
| 254 | Send { |
| 255 | agent: String, |
| 256 | prompt: String, |
| 257 | /// Select a specific conversation; otherwise use its only active one, or a unique Main. |
| 258 | #[arg(long)] |
| 259 | thread: Option<String>, |
| 260 | /// Explicit payer. Only byok_external is available under the current launch policy. |
| 261 | #[arg(long)] |
| 262 | billing_mode: String, |
| 263 | /// Stable message ID for safe retry after an uncertain response. |
| 264 | #[arg(long)] |
| 265 | operation_key: String, |
| 266 | }, |
| 267 | /// Read one turn's answer and status from this account's conversation events. |
| 268 | Result { |
| 269 | agent: String, |
| 270 | thread: String, |
| 271 | turn: String, |
| 272 | /// Resume from a previously printed event sequence for long conversations. |
| 273 | #[arg(long, default_value_t = 0)] |
| 274 | since_seq: u64, |
| 275 | }, |
| 276 | /// Give a named Agent durable Work. This records a request; it does not start compute. |
| 277 | /// |
| 278 | /// The Agent reads the message first: a plain instruction becomes Work, a |
| 279 | /// command such as "stop" is applied to its active Work, a correction |
| 280 | /// edits that Work's objective, and a question changes nothing. The |
| 281 | /// output states which happened. If the reply is lost, re-run the same |
| 282 | /// command with the same --message-id; that never creates a second Work for |
| 283 | /// the same instruction. If the message was a stop or a correction, check |
| 284 | /// `work-status` first. |
| 285 | Work { |
| 286 | agent: String, |
| 287 | objective: String, |
| 288 | /// Stable message ID for safe retry after an uncertain response. |
| 289 | #[arg(long)] |
| 290 | message_id: String, |
| 291 | #[arg(long, help = "UTF-8 source context file, at most 64000 UTF-16 units")] |
| 292 | context_file: Option<PathBuf>, |
| 293 | #[arg( |
| 294 | long = "file", |
| 295 | help = "Saved account file reference FILE_ID@VERSION; repeat for up to ten files" |
| 296 | )] |
| 297 | file_refs: Vec<String>, |
| 298 | }, |
| 299 | /// Record Work, review its quote, and start it on a new cloud computer. |
| 300 | /// |
| 301 | /// Without --yes and --confirm-eu-compute, a terminal asks before launching |
| 302 | /// and a script refuses; nothing starts without that consent. Reuse |
| 303 | /// --operation-key and --message-id to retry after an uncertain response. |
| 304 | Dispatch { |
| 305 | objective: String, |
| 306 | /// Agent name or ID; omitted, the account's repository-free default Agent. |
| 307 | #[arg(long)] |
| 308 | agent: Option<String>, |
| 309 | /// Task time in seconds; defaults to what the account's offer allows. |
| 310 | #[arg(long)] |
| 311 | seconds: Option<u64>, |
| 312 | #[arg(long, help = "UTF-8 source context file, at most 64000 UTF-16 units")] |
| 313 | context_file: Option<PathBuf>, |
| 314 | #[arg( |
| 315 | long = "file", |
| 316 | help = "Saved account file reference FILE_ID@VERSION; repeat for up to ten files" |
| 317 | )] |
| 318 | file_refs: Vec<String>, |
| 319 | #[arg(long)] |
| 320 | operation_key: Option<String>, |
| 321 | #[arg(long)] |
| 322 | message_id: Option<String>, |
| 323 | /// Do not ask before launching (also needs --confirm-eu-compute). |
| 324 | #[arg(long)] |
| 325 | yes: bool, |
| 326 | /// Agree that repository code and Work files run on EU compute. |
| 327 | #[arg(long)] |
| 328 | confirm_eu_compute: bool, |
| 329 | }, |
| 330 | /// Read the account-owned status of a Work request. |
| 331 | WorkStatus { id: String }, |
| 332 | /// Cancel Work and stop its computer; safe to repeat. |
| 333 | /// |
| 334 | /// If the Work still has queued prompts, choose --queue discard or --queue |
| 335 | /// park. An already-finished Work is reported and exits successfully. When |
| 336 | /// the reply is lost the outcome is unknown: run `work-status` before |
| 337 | /// retrying. |
| 338 | WorkCancel { |
| 339 | id: String, |
| 340 | /// What happens to queued prompts: discard them or park them on the Work. |
| 341 | #[arg(long, value_enum)] |
| 342 | queue: Option<WorkQueueChoice>, |
| 343 | /// Short reason recorded with the cancellation. |
| 344 | #[arg(long)] |
| 345 | reason: Option<String>, |
| 346 | }, |
| 347 | /// Read a Work's outcome: state, attempts, evidence, artifacts, draft PR, model route and usage. |
| 348 | /// |
| 349 | /// --json prints the account API's raw result and attempt records. |
| 350 | WorkResult { |
| 351 | id: String, |
| 352 | #[arg(long)] |
| 353 | json: bool, |
| 354 | }, |
| 355 | /// Quote offered computer time for Work. Nothing starts. |
| 356 | /// |
| 357 | /// Prints the funding, EU placement and time disclosure plus a short-lived |
| 358 | /// confirmation for `work-launch`. Reuse one --operation-key for the quote |
| 359 | /// and the launch. |
| 360 | WorkQuote { |
| 361 | id: String, |
| 362 | /// Stable launch ID, reused by `work-launch` so a retry cannot start two computers. |
| 363 | #[arg(long)] |
| 364 | operation_key: String, |
| 365 | #[arg( |
| 366 | long, |
| 367 | help = "Whole seconds within the served offer; defaults to its maximum" |
| 368 | )] |
| 369 | seconds: Option<u64>, |
| 370 | #[arg( |
| 371 | long, |
| 372 | help = "Failed workspace ID to recover on a fresh computer with the same Work ID" |
| 373 | )] |
| 374 | recovery_from: Option<String>, |
| 375 | }, |
| 376 | /// Start quoted Work on EU compute using the reviewed computer balance or trial. |
| 377 | /// |
| 378 | /// Requires the confirmation printed by `work-quote` and --confirm-eu-compute, |
| 379 | /// which agrees that repository code and Work files run on a cloud |
| 380 | /// computer in the EU. Re-running with the same --operation-key and --confirmation is |
| 381 | /// safe: it replays the launch instead of starting another computer. |
| 382 | WorkLaunch { |
| 383 | id: String, |
| 384 | #[arg(long)] |
| 385 | operation_key: String, |
| 386 | /// Confirmation printed by `work-quote`; use - to read bounded piped stdin. |
| 387 | #[arg(long)] |
| 388 | confirmation: String, |
| 389 | /// Agree that repository code and Work files run on EU compute. |
| 390 | #[arg(long)] |
| 391 | confirm_eu_compute: bool, |
| 392 | #[arg( |
| 393 | long, |
| 394 | help = "Exact whole seconds printed by work-quote; default is what your current offer allows" |
| 395 | )] |
| 396 | seconds: Option<u64>, |
| 397 | #[arg(long, help = "Exact failed workspace ID used for the recovery quote")] |
| 398 | recovery_from: Option<String>, |
| 399 | }, |
| 400 | } |
| 401 | |
| 402 | /// What a cancellation does with prompts still waiting behind the Work. |
| 403 | #[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)] |
| 404 | enum WorkQueueChoice { |
| 405 | Discard, |
| 406 | Park, |
| 407 | } |
| 408 | |
| 409 | #[derive(Debug, Subcommand)] |
| 410 | enum CloudComputersCommand { |
| 411 | /// List this account's Computers; --json includes allowance and entitlement data. |
| 412 | List { |
| 413 | #[arg(long)] |
| 414 | json: bool, |
| 415 | }, |
| 416 | /// Save a Computer identity; compute is allocated only when it starts. |
| 417 | Create { |
| 418 | name: String, |
| 419 | /// Try cloud compute in the EU for this Computer. |
| 420 | #[arg(long, alias = "boat-trial", requires = "eu_compute_opt_in")] |
| 421 | computer_trial: bool, |
| 422 | /// Confirm that trial code and files run on EU compute. |
| 423 | #[arg(long, requires = "computer_trial")] |
| 424 | eu_compute_opt_in: bool, |
| 425 | }, |
| 426 | /// Show one Computer; --json includes allowance and meter data. |
| 427 | Show { |
| 428 | id: String, |
| 429 | #[arg(long)] |
| 430 | json: bool, |
| 431 | }, |
| 432 | /// Read trial usage receipts for one Computer. |
| 433 | Usage { |
| 434 | id: String, |
| 435 | /// Print the full metering response. |
| 436 | #[arg(long, required = true)] |
| 437 | json: bool, |
| 438 | }, |
| 439 | /// Start a Computer, subject to the account's plan and capacity. |
| 440 | Start { id: String }, |
| 441 | /// Pause a Computer. |
| 442 | Pause { id: String }, |
| 443 | /// Permanently delete a Computer and its provider allocation. |
| 444 | Delete { |
| 445 | id: String, |
| 446 | #[arg( |
| 447 | long, |
| 448 | required = true, |
| 449 | help = "Confirm discarding files still on this computer" |
| 450 | )] |
| 451 | discard_files: bool, |
| 452 | }, |
| 453 | #[command( |
| 454 | about = "Save and restore computer files, or inspect and download account file versions" |
| 455 | )] |
| 456 | Files { |
| 457 | #[command(subcommand)] |
| 458 | command: CloudComputerFilesCommand, |
| 459 | }, |
| 460 | } |
| 461 | |
| 462 | #[derive(Debug, Subcommand)] |
| 463 | enum CloudComputerFilesCommand { |
| 464 | #[command(about = "Save a nonempty workspace file up to 16 MiB to account storage")] |
| 465 | Save { |
| 466 | computer_id: String, |
| 467 | path: String, |
| 468 | #[arg( |
| 469 | long, |
| 470 | help = "Stable save request ID; reuse it when retrying the same save" |
| 471 | )] |
| 472 | request_id: String, |
| 473 | #[arg(long, requires = "expected_version")] |
| 474 | file_id: Option<String>, |
| 475 | #[arg(long, requires = "file_id", value_parser = clap::value_parser!(u64).range(1..=MAX_FILE_VERSION))] |
| 476 | expected_version: Option<u64>, |
| 477 | #[arg(long)] |
| 478 | expected_revision: Option<String>, |
| 479 | #[arg(long)] |
| 480 | name: Option<String>, |
| 481 | }, |
| 482 | #[command( |
| 483 | about = "Restore an account file version up to 4 MiB; existing destinations need --expected-revision" |
| 484 | )] |
| 485 | Restore { |
| 486 | computer_id: String, |
| 487 | file_id: String, |
| 488 | path: String, |
| 489 | #[arg(long, value_parser = clap::value_parser!(u64).range(1..=MAX_FILE_VERSION))] |
| 490 | version: u64, |
| 491 | #[arg( |
| 492 | long, |
| 493 | help = "Current destination SHA-256, required to replace an existing file" |
| 494 | )] |
| 495 | expected_revision: Option<String>, |
| 496 | }, |
| 497 | #[command(about = "Read a computer workspace file's size and current SHA-256 revision")] |
| 498 | Revision { computer_id: String, path: String }, |
| 499 | #[command(about = "List an account file's saved versions, sizes and SHA-256 hashes")] |
| 500 | Versions { file_id: String }, |
| 501 | #[command( |
| 502 | about = "Download and verify one account file version without overwriting local files" |
| 503 | )] |
| 504 | Download { |
| 505 | file_id: String, |
| 506 | #[arg(long, value_parser = clap::value_parser!(u64).range(1..=MAX_FILE_VERSION))] |
| 507 | version: u64, |
| 508 | #[arg(long)] |
| 509 | output: PathBuf, |
| 510 | }, |
| 511 | } |
| 512 | |
| 513 | #[derive(Debug, Subcommand)] |
| 514 | enum CloudKeysCommand { |
| 515 | /// List configured providers without revealing key values. |
| 516 | List, |
| 517 | /// Save a provider key to the signed-in Codewhale account. |
| 518 | Set(CloudKeySetArgs), |
| 519 | /// Remove a provider key from the signed-in Codewhale account. |
| 520 | Remove { |
| 521 | /// Provider id from the account's catalog (`account keys list`). |
| 522 | provider: String, |
| 523 | }, |
| 524 | } |
| 525 | |
| 526 | #[derive(Debug, Args)] |
| 527 | struct CloudKeySetArgs { |
| 528 | /// Provider id from the account's catalog (`account keys list`). |
| 529 | provider: String, |
| 530 | /// Read the key from stdin. Useful for pipes and secret-manager commands. |
| 531 | #[arg(long = "api-key-stdin", conflicts_with = "from_local")] |
| 532 | api_key_stdin: bool, |
| 533 | /// Upload the locally resolved key (config, secret store, then environment). |
| 534 | #[arg(long, conflicts_with = "api_key_stdin")] |
| 535 | from_local: bool, |
| 536 | /// Non-secret label shown beside the stored credential. |
| 537 | #[arg(long, default_value = "Codewhale CLI")] |
| 538 | label: String, |
| 539 | } |
| 540 | |
| 541 | /// One row of the account control plane's public provider catalog. |
| 542 | /// |
| 543 | /// This is untrusted remote data, not a Codewhale-owned enum: the account |
| 544 | /// service adds providers without a CLI release, so the catalog is read as |
| 545 | /// data and every id is re-validated locally before it reaches a URL path. |
| 546 | /// Only the fields this surface actually uses are modeled; unknown fields are |
| 547 | /// ignored rather than being turned into behavior. |
| 548 | #[derive(Debug, Clone, Deserialize)] |
| 549 | #[serde(rename_all = "camelCase")] |
| 550 | struct CatalogProvider { |
| 551 | id: String, |
| 552 | #[serde(default)] |
| 553 | label: String, |
| 554 | /// The runtime provider id this catalog row maps onto, when one exists. |
| 555 | /// `--from-local` uses it to find the local credential; without it the |
| 556 | /// row's own id is tried. |
| 557 | #[serde(default)] |
| 558 | runtime_provider: Option<String>, |
| 559 | /// Model ids the account API lists for this provider. `new-thread` checks |
| 560 | /// its explicit route against this served list, not a compiled table. |
| 561 | #[serde(default)] |
| 562 | models: Vec<String>, |
| 563 | /// False for runtime-only rows a hosted conversation cannot use. |
| 564 | #[serde(default)] |
| 565 | connection_available: Option<bool>, |
| 566 | } |
| 567 | |
| 568 | #[derive(Debug, Deserialize)] |
| 569 | struct ProviderCatalogResponse { |
| 570 | #[serde(default)] |
| 571 | providers: Vec<CatalogProvider>, |
| 572 | } |
| 573 | |
| 574 | #[derive(Debug, Deserialize)] |
| 575 | #[serde(rename_all = "camelCase")] |
| 576 | struct AccountComputer { |
| 577 | id: String, |
| 578 | owner_id: String, |
| 579 | name: String, |
| 580 | region: String, |
| 581 | status: String, |
| 582 | #[serde(default)] |
| 583 | start_queue_reason: String, |
| 584 | } |
| 585 | |
| 586 | #[derive(Deserialize)] |
| 587 | struct ComputerListResponse { |
| 588 | computers: Vec<AccountComputer>, |
| 589 | } |
| 590 | |
| 591 | #[derive(Deserialize)] |
| 592 | struct ComputerResponse { |
| 593 | computer: AccountComputer, |
| 594 | #[serde(default)] |
| 595 | queued: bool, |
| 596 | } |
| 597 | |
| 598 | #[derive(Deserialize)] |
| 599 | #[serde(rename_all = "camelCase")] |
| 600 | struct ComputerDeleteResponse { |
| 601 | deleted: bool, |
| 602 | computer_id: String, |
| 603 | } |
| 604 | |
| 605 | #[derive(Deserialize)] |
| 606 | struct AccountFileVersion { |
| 607 | version: u64, |
| 608 | size: u64, |
| 609 | sha256: String, |
| 610 | } |
| 611 | |
| 612 | #[derive(Deserialize)] |
| 613 | struct AccountProject { |
| 614 | id: String, |
| 615 | name: String, |
| 616 | #[serde(rename = "defaultRepoProvider", default)] |
| 617 | default_repo_provider: String, |
| 618 | #[serde(rename = "defaultRepo", default)] |
| 619 | default_repo: String, |
| 620 | } |
| 621 | |
| 622 | #[derive(Deserialize)] |
| 623 | struct ProjectListResponse { |
| 624 | projects: Vec<AccountProject>, |
| 625 | } |
| 626 | |
| 627 | #[derive(Deserialize)] |
| 628 | struct ProjectResponse { |
| 629 | project: AccountProject, |
| 630 | } |
| 631 | |
| 632 | #[derive(Deserialize)] |
| 633 | #[serde(rename_all = "camelCase")] |
| 634 | struct AccountGitHubBinding { |
| 635 | id: String, |
| 636 | provider: String, |
| 637 | repo: String, |
| 638 | status: String, |
| 639 | #[serde(default)] |
| 640 | installation_id: String, |
| 641 | } |
| 642 | |
| 643 | #[derive(Deserialize)] |
| 644 | struct GitHubBindingListResponse { |
| 645 | bindings: Vec<AccountGitHubBinding>, |
| 646 | } |
| 647 | |
| 648 | #[derive(Serialize)] |
| 649 | struct ComputerCreateRequest<'a> { |
| 650 | name: &'a str, |
| 651 | #[serde(skip_serializing_if = "Option::is_none")] |
| 652 | provider: Option<&'static str>, |
| 653 | #[serde(rename = "boatEuComputeOptIn", skip_serializing_if = "Option::is_none")] |
| 654 | boat_eu_compute_opt_in: Option<bool>, |
| 655 | } |
| 656 | |
| 657 | #[derive(Clone, Deserialize)] |
| 658 | #[serde(rename_all = "camelCase")] |
| 659 | struct AccountAgent { |
| 660 | id: String, |
| 661 | name: String, |
| 662 | status: String, |
| 663 | #[serde(default)] |
| 664 | project_id: String, |
| 665 | revision: u64, |
| 666 | #[serde(default)] |
| 667 | configuration: Option<AgentConfiguration>, |
| 668 | } |
| 669 | |
| 670 | #[derive(Clone, Deserialize)] |
| 671 | #[serde(rename_all = "camelCase")] |
| 672 | struct AgentConfiguration { |
| 673 | #[serde(default)] |
| 674 | revision: u64, |
| 675 | #[serde(default)] |
| 676 | model: Option<AgentModelRoute>, |
| 677 | } |
| 678 | |
| 679 | #[derive(Clone, Deserialize)] |
| 680 | struct AgentModelRoute { |
| 681 | provider: String, |
| 682 | model: String, |
| 683 | } |
| 684 | |
| 685 | #[derive(Deserialize)] |
| 686 | struct AgentListResponse { |
| 687 | agents: Vec<AccountAgent>, |
| 688 | } |
| 689 | |
| 690 | #[derive(Deserialize)] |
| 691 | struct AgentResponse { |
| 692 | agent: AccountAgent, |
| 693 | } |
| 694 | |
| 695 | #[derive(Clone, Deserialize, Serialize)] |
| 696 | #[serde(rename_all = "camelCase")] |
| 697 | struct AgentThread { |
| 698 | id: String, |
| 699 | agent_id: String, |
| 700 | #[serde(default)] |
| 701 | project_id: String, |
| 702 | title: String, |
| 703 | model: String, |
| 704 | model_provider: String, |
| 705 | #[serde(default)] |
| 706 | model_provider_id: String, |
| 707 | #[serde(default)] |
| 708 | kind: String, |
| 709 | #[serde(default)] |
| 710 | archived_at: String, |
| 711 | } |
| 712 | |
| 713 | #[derive(Deserialize)] |
| 714 | struct ThreadResponse { |
| 715 | thread: AgentThread, |
| 716 | } |
| 717 | |
| 718 | #[derive(Deserialize)] |
| 719 | struct TurnResponse { |
| 720 | turn: TurnReceipt, |
| 721 | } |
| 722 | |
| 723 | #[derive(Deserialize)] |
| 724 | struct TurnReceipt { |
| 725 | id: String, |
| 726 | status: String, |
| 727 | } |
| 728 | |
| 729 | #[derive(Deserialize)] |
| 730 | #[serde(rename_all = "camelCase")] |
| 731 | struct AccountAgentWork { |
| 732 | id: String, |
| 733 | agent_id: String, |
| 734 | status: String, |
| 735 | #[serde(default)] |
| 736 | objective: String, |
| 737 | #[serde(default)] |
| 738 | task_context_digest: String, |
| 739 | } |
| 740 | |
| 741 | #[derive(Serialize)] |
| 742 | struct WorkTaskContext { |
| 743 | text: String, |
| 744 | #[serde(rename = "fileRefs")] |
| 745 | file_refs: Vec<WorkFileRef>, |
| 746 | } |
| 747 | |
| 748 | #[derive(Serialize)] |
| 749 | struct WorkFileRef { |
| 750 | #[serde(rename = "fileId")] |
| 751 | file_id: String, |
| 752 | version: u64, |
| 753 | } |
| 754 | |
| 755 | #[derive(Deserialize)] |
| 756 | #[serde(rename_all = "camelCase")] |
| 757 | struct AgentWorkMessageResponse { |
| 758 | intent: String, |
| 759 | /// Why the Agent read the message that way (a server-owned code). |
| 760 | #[serde(default)] |
| 761 | reason: String, |
| 762 | /// The action applied to active Work when `intent` is `control`. |
| 763 | #[serde(default)] |
| 764 | control_action: Option<String>, |
| 765 | #[serde(default)] |
| 766 | confident: Option<bool>, |
| 767 | /// What the Agent offers to do when it declined to act on an unclear message. |
| 768 | #[serde(default)] |
| 769 | suggestion: Option<String>, |
| 770 | work: Option<AccountAgentWork>, |
| 771 | #[serde(default)] |
| 772 | queued_work: Vec<AccountAgentWork>, |
| 773 | } |
| 774 | |
| 775 | #[derive(Deserialize)] |
| 776 | #[serde(rename_all = "camelCase")] |
| 777 | struct AgentTurnEvent { |
| 778 | seq: u64, |
| 779 | #[serde(rename = "type")] |
| 780 | kind: String, |
| 781 | turn_id: String, |
| 782 | payload: serde_json::Value, |
| 783 | } |
| 784 | |
| 785 | struct AgentTurnResult { |
| 786 | last_seq: u64, |
| 787 | status: String, |
| 788 | answer: String, |
| 789 | seen_turn: bool, |
| 790 | } |
| 791 | |
| 792 | impl CatalogProvider { |
| 793 | /// Non-empty display label, falling back to the id. |
| 794 | fn display_label(&self) -> String { |
| 795 | let label = printable(&self.label); |
| 796 | if label.is_empty() { |
| 797 | printable(&self.id) |
| 798 | } else { |
| 799 | label |
| 800 | } |
| 801 | } |
| 802 | |
| 803 | /// The local [`ProviderKind`] this catalog row maps onto, if any. |
| 804 | /// |
| 805 | /// The catalog states its own runtime mapping (`xiaomi` → |
| 806 | /// `xiaomi-mimo`); the row id is only a fallback for a provider whose |
| 807 | /// catalog id already equals the runtime id. |
| 808 | fn local_kind(&self) -> Option<ProviderKind> { |
| 809 | self.runtime_provider |
| 810 | .as_deref() |
| 811 | .map(str::trim) |
| 812 | .filter(|value| !value.is_empty()) |
| 813 | .and_then(ProviderKind::parse_config_identity) |
| 814 | .or_else(|| ProviderKind::parse_config_identity(&self.id)) |
| 815 | } |
| 816 | } |
| 817 | |
| 818 | /// Accept a provider id conservatively before it is ever put in a URL path. |
| 819 | /// |
| 820 | /// `^[a-z0-9][a-z0-9-]{0,63}$`. The catalog is remote data, so this guards |
| 821 | /// both directions: a hostile catalog cannot smuggle a path segment, and a |
| 822 | /// mistyped argument fails locally instead of as a confusing 404. |
| 823 | fn validate_provider_id(value: &str) -> Result<String> { |
| 824 | let trimmed = value.trim(); |
| 825 | let bytes = trimmed.as_bytes(); |
| 826 | let well_formed = (1..=64).contains(&bytes.len()) |
| 827 | && (bytes[0].is_ascii_lowercase() || bytes[0].is_ascii_digit()) |
| 828 | && bytes |
| 829 | .iter() |
| 830 | .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'-'); |
| 831 | if !well_formed { |
| 832 | bail!( |
| 833 | "`{}` is not a valid provider id. Ids are 1-64 characters of lowercase letters, digits, and `-`. Run `codewhale account keys list` to see the account's providers", |
| 834 | printable(trimmed) |
| 835 | ); |
| 836 | } |
| 837 | Ok(trimmed.to_string()) |
| 838 | } |
| 839 | |
| 840 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 841 | enum HttpMethod { |
| 842 | Get, |
| 843 | Post, |
| 844 | Patch, |
| 845 | Put, |
| 846 | Delete, |
| 847 | } |
| 848 | |
| 849 | pub(crate) struct CloudRequest { |
| 850 | method: HttpMethod, |
| 851 | path: String, |
| 852 | bearer: Option<String>, |
| 853 | body: Option<Vec<u8>>, |
| 854 | } |
| 855 | |
| 856 | pub(crate) struct CloudResponse { |
| 857 | status: u16, |
| 858 | body: Vec<u8>, |
| 859 | /// `Retry-After` in whole seconds, when the service supplied one. Kept on |
| 860 | /// the response rather than re-parsed by callers so the retry policy has a |
| 861 | /// single source for how long the server asked us to wait. |
| 862 | retry_after: Option<u64>, |
| 863 | } |
| 864 | |
| 865 | pub(crate) trait CloudTransport { |
| 866 | fn execute(&self, request: CloudRequest) -> Result<CloudResponse>; |
| 867 | } |
| 868 | |
| 869 | #[derive(Clone)] |
| 870 | struct ReqwestTransport { |
| 871 | base: Url, |
| 872 | client: reqwest::blocking::Client, |
| 873 | } |
| 874 | |
| 875 | impl ReqwestTransport { |
| 876 | fn new(base: Url) -> Result<Self> { |
| 877 | let client = codewhale_release::platform_blocking_http_client_builder() |
| 878 | .connect_timeout(Duration::from_secs(8)) |
| 879 | .timeout(Duration::from_secs(30)) |
| 880 | // Never replay bearer tokens or provider-key request bodies to a |
| 881 | // redirect target. The control-plane origin is an explicit trust |
| 882 | // boundary, so redirects are treated as ordinary non-2xx replies. |
| 883 | .redirect(reqwest::redirect::Policy::none()) |
| 884 | .user_agent(concat!("codewhale/", env!("CARGO_PKG_VERSION"))) |
| 885 | .build() |
| 886 | .context("failed to initialize the Codewhale account HTTP client")?; |
| 887 | Ok(Self { base, client }) |
| 888 | } |
| 889 | } |
| 890 | |
| 891 | impl CloudTransport for ReqwestTransport { |
| 892 | fn execute(&self, request: CloudRequest) -> Result<CloudResponse> { |
| 893 | let url = self |
| 894 | .base |
| 895 | .join(request.path.trim_start_matches('/')) |
| 896 | .context("failed to construct the Codewhale account request URL")?; |
| 897 | let file_download = request.method == HttpMethod::Get |
| 898 | && url |
| 899 | .path() |
| 900 | .strip_prefix("/v1/files/") |
| 901 | .and_then(|path| path.strip_suffix("/content")) |
| 902 | .is_some_and(|id| validate_account_file_id(id).is_ok()); |
| 903 | let max_response_bytes = if request.method == HttpMethod::Get |
| 904 | && matches!( |
| 905 | request.path.as_str(), |
| 906 | "/api/account/model-api" | "/v1/models" |
| 907 | ) { |
| 908 | 4 * 1024 * 1024 |
| 909 | } else if file_download { |
| 910 | MAX_FILE_DOWNLOAD_BYTES |
| 911 | } else if matches!(request.method, HttpMethod::Get | HttpMethod::Post) |
| 912 | && request |
| 913 | .path |
| 914 | .strip_prefix("/v1/threads/") |
| 915 | .and_then(|path| path.strip_suffix("/computer")) |
| 916 | .is_some_and(|id| validate_resource_id(id, "Conversation").is_ok()) |
| 917 | { |
| 918 | 16 * 1024 * 1024 + 64 * 1024 |
| 919 | } else { |
| 920 | MAX_RESPONSE_BYTES |
| 921 | }; |
| 922 | let method = match request.method { |
| 923 | HttpMethod::Get => reqwest::Method::GET, |
| 924 | HttpMethod::Post => reqwest::Method::POST, |
| 925 | HttpMethod::Patch => reqwest::Method::PATCH, |
| 926 | HttpMethod::Put => reqwest::Method::PUT, |
| 927 | HttpMethod::Delete => reqwest::Method::DELETE, |
| 928 | }; |
| 929 | let mut builder = self.client.request(method, url).header( |
| 930 | reqwest::header::ACCEPT, |
| 931 | if file_download { |
| 932 | "application/octet-stream" |
| 933 | } else { |
| 934 | "application/json" |
| 935 | }, |
| 936 | ); |
| 937 | // Hosted launch waits for provider creation and guest bootstrap. Its |
| 938 | // HTTP deadline is separate from the guest's bounded trial runtime. |
| 939 | if request.method == HttpMethod::Post && request.path == "/api/cloud-sessions" { |
| 940 | builder = builder.timeout(Duration::from_secs(600)); |
| 941 | } |
| 942 | if let Some(token) = request.bearer { |
| 943 | builder = builder.bearer_auth(token); |
| 944 | } |
| 945 | if let Some(body) = request.body { |
| 946 | builder = builder |
| 947 | .header(reqwest::header::CONTENT_TYPE, "application/json") |
| 948 | .body(body); |
| 949 | } |
| 950 | let response = builder.send().map_err(|source| { |
| 951 | CloudTransportError::new("could not reach the Codewhale service", source) |
| 952 | })?; |
| 953 | let status = response.status().as_u16(); |
| 954 | let retry_after = response |
| 955 | .headers() |
| 956 | .get(reqwest::header::RETRY_AFTER) |
| 957 | .and_then(|value| value.to_str().ok()) |
| 958 | .and_then(|value| value.trim().parse::<u64>().ok()); |
| 959 | let mut body = Vec::new(); |
| 960 | response |
| 961 | .take(max_response_bytes + 1) |
| 962 | .read_to_end(&mut body) |
| 963 | .map_err(|source| { |
| 964 | CloudTransportError::new("failed to read the Codewhale service response", source) |
| 965 | })?; |
| 966 | if body.len() as u64 > max_response_bytes { |
| 967 | return Err(CloudTransportError::new( |
| 968 | "The Codewhale service returned an unexpectedly large response", |
| 969 | std::io::Error::other("response exceeded the account API size limit"), |
| 970 | ) |
| 971 | .into()); |
| 972 | } |
| 973 | Ok(CloudResponse { |
| 974 | status, |
| 975 | body, |
| 976 | retry_after, |
| 977 | }) |
| 978 | } |
| 979 | } |
| 980 | |
| 981 | #[derive(Deserialize)] |
| 982 | #[serde(rename_all = "camelCase")] |
| 983 | struct DeviceStart { |
| 984 | device_code: String, |
| 985 | user_code: String, |
| 986 | verification_uri: String, |
| 987 | verification_uri_complete: String, |
| 988 | expires_in: u64, |
| 989 | interval: u64, |
| 990 | } |
| 991 | |
| 992 | #[derive(Deserialize)] |
| 993 | struct MeResponse { |
| 994 | user: CloudUser, |
| 995 | } |
| 996 | |
| 997 | #[derive(Serialize)] |
| 998 | #[serde(rename_all = "camelCase")] |
| 999 | struct DeviceTokenRequest<'a> { |
| 1000 | device_code: &'a str, |
| 1001 | } |
| 1002 | |
| 1003 | #[derive(Serialize)] |
| 1004 | #[serde(rename_all = "camelCase")] |
| 1005 | struct RefreshRequest<'a> { |
| 1006 | refresh_token: &'a str, |
| 1007 | } |
| 1008 | |
| 1009 | #[derive(Serialize)] |
| 1010 | struct ModelKeyRequest<'a> { |
| 1011 | key: &'a str, |
| 1012 | label: &'a str, |
| 1013 | } |
| 1014 | |
| 1015 | pub(crate) struct CloudClient<'a, T: CloudTransport> { |
| 1016 | transport: &'a T, |
| 1017 | account_store: AccountSessionStore, |
| 1018 | } |
| 1019 | |
| 1020 | impl<'a, T: CloudTransport> CloudClient<'a, T> { |
| 1021 | fn new(transport: &'a T, secrets: &'a Secrets, profile: &str, api_base: &'a str) -> Self { |
| 1022 | Self { |
| 1023 | transport, |
| 1024 | account_store: AccountSessionStore::new(secrets.clone(), Some(profile), api_base), |
| 1025 | } |
| 1026 | } |
| 1027 | |
| 1028 | fn start_device(&self) -> Result<DeviceStart> { |
| 1029 | let response = self.transport.execute(CloudRequest { |
| 1030 | method: HttpMethod::Post, |
| 1031 | path: "/api/cli/device/start".to_string(), |
| 1032 | bearer: None, |
| 1033 | body: Some(b"{}".to_vec()), |
| 1034 | })?; |
| 1035 | expect_json(response, &[200]) |
| 1036 | } |
| 1037 | |
| 1038 | fn poll_device( |
| 1039 | &self, |
| 1040 | device: &DeviceStart, |
| 1041 | snapshot: &AccountSessionSnapshot, |
| 1042 | timeout: Duration, |
| 1043 | sleep: &mut dyn FnMut(Duration), |
| 1044 | ) -> Result<AuthBundle> { |
| 1045 | validate_device_code(&device.device_code)?; |
| 1046 | let server_lifetime = |
| 1047 | Duration::from_secs(device.expires_in.clamp(1, MAX_LOGIN_TIMEOUT_SECONDS)); |
| 1048 | // The Codewhale account service answers HTTP 202 while the code is |
| 1049 | // still pending, so the first response is already meaningful: poll |
| 1050 | // immediately and sleep afterwards. It has no slow_down. |
| 1051 | let bundle = codewhale_config::device_code::DeviceCodePoll::new( |
| 1052 | timeout.min(server_lifetime), |
| 1053 | "Codewhale account login timed out; run `codewhale login` to try again", |
| 1054 | ) |
| 1055 | .interval_seconds(Some(device.interval)) |
| 1056 | .max_interval_seconds(10) |
| 1057 | .run(sleep, || self.poll_device_once(device))?; |
| 1058 | if self |
| 1059 | .account_store |
| 1060 | .save_if_unchanged(snapshot, bundle.clone())? |
| 1061 | .is_none() |
| 1062 | { |
| 1063 | bail!("The signed-in account changed. Refresh and try again."); |
| 1064 | } |
| 1065 | let _ = self.revoke_previous_session(snapshot, &bundle); |
| 1066 | Ok(bundle) |
| 1067 | } |
| 1068 | |
| 1069 | fn revoke_previous_session( |
| 1070 | &self, |
| 1071 | previous: &AccountSessionSnapshot, |
| 1072 | next: &AuthBundle, |
| 1073 | ) -> bool { |
| 1074 | let previous = match previous.load() { |
| 1075 | Ok(Some(previous)) => previous.bundle, |
| 1076 | Ok(None) => return true, |
| 1077 | Err(_) => return false, |
| 1078 | }; |
| 1079 | if previous |
| 1080 | .session |
| 1081 | .as_ref() |
| 1082 | .zip(next.session.as_ref()) |
| 1083 | .is_some_and(|(old, new)| old.id == new.id) |
| 1084 | { |
| 1085 | return true; |
| 1086 | } |
| 1087 | self.revoke_session_bundle(&previous) |
| 1088 | } |
| 1089 | |
| 1090 | fn revoke_session_bundle(&self, bundle: &AuthBundle) -> bool { |
| 1091 | let Ok(body) = json_body(&RefreshRequest { |
| 1092 | refresh_token: &bundle.refresh_token, |
| 1093 | }) else { |
| 1094 | return false; |
| 1095 | }; |
| 1096 | self.transport |
| 1097 | .execute(CloudRequest { |
| 1098 | method: HttpMethod::Post, |
| 1099 | path: "/api/auth/logout".into(), |
| 1100 | bearer: None, |
| 1101 | body: Some(body), |
| 1102 | }) |
| 1103 | .is_ok_and(|response| (200..300).contains(&response.status)) |
| 1104 | } |
| 1105 | |
| 1106 | fn poll_device_once(&self, device: &DeviceStart) -> Result<DevicePollOutcome<AuthBundle>> { |
| 1107 | let response = self.transport.execute(CloudRequest { |
| 1108 | method: HttpMethod::Post, |
| 1109 | path: "/api/cli/device/token".to_string(), |
| 1110 | bearer: None, |
| 1111 | body: Some(json_body(&DeviceTokenRequest { |
| 1112 | device_code: &device.device_code, |
| 1113 | })?), |
| 1114 | })?; |
| 1115 | match response.status { |
| 1116 | 200 => { |
| 1117 | let bundle: AuthBundle = parse_json_body(&response.body)?; |
| 1118 | validate_auth_bundle(&bundle)?; |
| 1119 | Ok(DevicePollOutcome::Complete(bundle)) |
| 1120 | } |
| 1121 | 202 => Ok(DevicePollOutcome::Pending), |
| 1122 | _ => Err(response_error(&response)), |
| 1123 | } |
| 1124 | } |
| 1125 | |
| 1126 | fn load_auth(&self) -> Result<Option<StoredCloudAuth>> { |
| 1127 | self.account_store.load().context( |
| 1128 | "the local Codewhale account session is unreadable; run `codewhale account logout` and sign in again", |
| 1129 | ) |
| 1130 | } |
| 1131 | |
| 1132 | #[cfg(test)] |
| 1133 | fn save_auth(&self, bundle: AuthBundle) -> Result<()> { |
| 1134 | self.account_store |
| 1135 | .save(bundle) |
| 1136 | .context("failed to save the Codewhale account session in the local secret store") |
| 1137 | } |
| 1138 | |
| 1139 | fn me(&self) -> Result<CloudUser> { |
| 1140 | let (response, snapshot) = |
| 1141 | self.execute_authenticated_snapshot(HttpMethod::Get, "/api/me", None)?; |
| 1142 | let me: MeResponse = expect_json(response, &[200])?; |
| 1143 | if me.user.id.trim().is_empty() { |
| 1144 | bail!("The Codewhale service returned an account without an ID"); |
| 1145 | } |
| 1146 | if let Some(mut stored) = snapshot.load()? { |
| 1147 | if stored |
| 1148 | .bundle |
| 1149 | .user |
| 1150 | .as_ref() |
| 1151 | .is_some_and(|user| !user.id.is_empty() && user.id != me.user.id) |
| 1152 | { |
| 1153 | bail!("The signed-in account changed. Refresh and try again."); |
| 1154 | } |
| 1155 | stored.bundle.user = Some(me.user.clone()); |
| 1156 | if self |
| 1157 | .account_store |
| 1158 | .save_if_unchanged(&snapshot, stored.bundle)? |
| 1159 | .is_none() |
| 1160 | { |
| 1161 | bail!("The signed-in account changed. Refresh and try again."); |
| 1162 | } |
| 1163 | } |
| 1164 | Ok(me.user) |
| 1165 | } |
| 1166 | |
| 1167 | fn set_key(&self, provider: &str, key: &str, label: &str) -> Result<()> { |
| 1168 | let path = format!("/api/model-keys/{provider}"); |
| 1169 | let response = self.execute_authenticated( |
| 1170 | HttpMethod::Put, |
| 1171 | &path, |
| 1172 | Some(json_body(&ModelKeyRequest { key, label })?), |
| 1173 | )?; |
| 1174 | expect_empty(response, &[200, 201]) |
| 1175 | } |
| 1176 | |
| 1177 | fn remove_key(&self, provider: &str) -> Result<()> { |
| 1178 | let path = format!("/api/model-keys/{provider}"); |
| 1179 | let response = self.execute_authenticated(HttpMethod::Delete, &path, None)?; |
| 1180 | expect_empty(response, &[200, 204]) |
| 1181 | } |
| 1182 | |
| 1183 | /// The account control plane's public provider catalog. |
| 1184 | /// |
| 1185 | /// This replaced a hardcoded eight-provider enum: the set of providers a |
| 1186 | /// customer can connect is owned by the control plane, not the CLI, so a |
| 1187 | /// newly supported provider must not need a CLI release. The route is |
| 1188 | /// public, so no session is required to *list* what could be connected — |
| 1189 | /// only to read or write this account's keys. |
| 1190 | /// |
| 1191 | /// Rows with an id this CLI would refuse to put in a URL path are dropped |
| 1192 | /// rather than trusted; duplicates collapse onto the first row. |
| 1193 | fn provider_catalog(&self) -> Result<Vec<CatalogProvider>> { |
| 1194 | let response = self.transport.execute(CloudRequest { |
| 1195 | method: HttpMethod::Get, |
| 1196 | path: "/api/model-providers".to_string(), |
| 1197 | bearer: None, |
| 1198 | body: None, |
| 1199 | })?; |
| 1200 | let listing: ProviderCatalogResponse = expect_json(response, &[200])?; |
| 1201 | let mut seen = std::collections::BTreeSet::new(); |
| 1202 | let providers: Vec<CatalogProvider> = listing |
| 1203 | .providers |
| 1204 | .into_iter() |
| 1205 | .filter(|row| validate_provider_id(&row.id).is_ok()) |
| 1206 | .filter(|row| seen.insert(row.id.trim().to_string())) |
| 1207 | .map(|mut row| { |
| 1208 | row.id = row.id.trim().to_string(); |
| 1209 | row |
| 1210 | }) |
| 1211 | .collect(); |
| 1212 | if providers.is_empty() { |
| 1213 | bail!( |
| 1214 | "The Codewhale service returned no connectable providers. Check the account API origin, or try again" |
| 1215 | ); |
| 1216 | } |
| 1217 | Ok(providers) |
| 1218 | } |
| 1219 | |
| 1220 | fn computers(&self) -> Result<serde_json::Value> { |
| 1221 | let response = self.execute_authenticated(HttpMethod::Get, "/api/computers", None)?; |
| 1222 | expect_json(response, &[200]) |
| 1223 | } |
| 1224 | |
| 1225 | fn agents(&self) -> Result<serde_json::Value> { |
| 1226 | let response = self.execute_authenticated(HttpMethod::Get, "/api/agents", None)?; |
| 1227 | expect_json(response, &[200]) |
| 1228 | } |
| 1229 | |
| 1230 | fn projects(&self) -> Result<serde_json::Value> { |
| 1231 | let response = self.execute_authenticated(HttpMethod::Get, "/api/projects", None)?; |
| 1232 | expect_json(response, &[200]) |
| 1233 | } |
| 1234 | |
| 1235 | fn github_bindings(&self) -> Result<serde_json::Value> { |
| 1236 | let response = |
| 1237 | self.execute_authenticated(HttpMethod::Get, "/api/integrations/github/bindings", None)?; |
| 1238 | if matches!(response.status, 404 | 503) { |
| 1239 | return Err(response_error(&response)).context( |
| 1240 | "GitHub repository bindings are unavailable on this Codewhale API; the account GitHub route must be attached before CLI setup", |
| 1241 | ); |
| 1242 | } |
| 1243 | expect_json(response, &[200]) |
| 1244 | } |
| 1245 | |
| 1246 | fn create_github_project( |
| 1247 | &self, |
| 1248 | name: &str, |
| 1249 | binding: &AccountGitHubBinding, |
| 1250 | operation_key: &str, |
| 1251 | ) -> Result<AccountProject> { |
| 1252 | let name = validate_named_text(name, "Project name", 80)?; |
| 1253 | let operation_key = validate_operation_key(operation_key)?; |
| 1254 | let response = self.execute_authenticated( |
| 1255 | HttpMethod::Post, |
| 1256 | "/api/projects", |
| 1257 | Some(json_body(&serde_json::json!({ |
| 1258 | "name": name, |
| 1259 | "defaultMode": "chat", |
| 1260 | "chatFilesystem": "optional_scratch", |
| 1261 | "repoBindingId": binding.id, |
| 1262 | "operationKey": operation_key, |
| 1263 | }))?), |
| 1264 | )?; |
| 1265 | let result: ProjectResponse = expect_json(response, &[200, 201])?; |
| 1266 | validate_resource_id(&result.project.id, "Project")?; |
| 1267 | if result.project.default_repo_provider != "github" |
| 1268 | || !result |
| 1269 | .project |
| 1270 | .default_repo |
| 1271 | .eq_ignore_ascii_case(&binding.repo) |
| 1272 | { |
| 1273 | bail!("The Codewhale service returned a Project for a different GitHub repository"); |
| 1274 | } |
| 1275 | Ok(result.project) |
| 1276 | } |
| 1277 | |
| 1278 | fn create_agent( |
| 1279 | &self, |
| 1280 | name: &str, |
| 1281 | project_id: Option<&str>, |
| 1282 | route: Option<(&str, &str)>, |
| 1283 | operation_key: &str, |
| 1284 | ) -> Result<AccountAgent> { |
| 1285 | let name = validate_named_text(name, "Agent name", 80)?; |
| 1286 | let operation_key = validate_operation_key(operation_key)?; |
| 1287 | let mut body = serde_json::json!({ |
| 1288 | "name": name, |
| 1289 | "operationKey": operation_key, |
| 1290 | }); |
| 1291 | if let Some((provider, model)) = route { |
| 1292 | body["model"] = serde_json::json!({ |
| 1293 | "provider": validate_named_text(provider, "Provider", 256)?, |
| 1294 | "model": validate_named_text(model, "Model", 256)?, |
| 1295 | }); |
| 1296 | } |
| 1297 | if let Some(project_id) = project_id { |
| 1298 | body["projectId"] = serde_json::json!(validate_resource_id(project_id, "Project")?); |
| 1299 | } |
| 1300 | let response = |
| 1301 | self.execute_authenticated(HttpMethod::Post, "/api/agents", Some(json_body(&body)?))?; |
| 1302 | let result: AgentResponse = expect_json(response, &[200, 201])?; |
| 1303 | Ok(result.agent) |
| 1304 | } |
| 1305 | |
| 1306 | fn bind_agent_project( |
| 1307 | &self, |
| 1308 | agent_id: &str, |
| 1309 | project_id: &str, |
| 1310 | revision: u64, |
| 1311 | ) -> Result<AccountAgent> { |
| 1312 | let agent_id = validate_resource_id(agent_id, "Agent")?; |
| 1313 | let project_id = validate_resource_id(project_id, "Project")?; |
| 1314 | if revision == 0 { |
| 1315 | bail!("The Codewhale service returned an Agent without a valid revision"); |
| 1316 | } |
| 1317 | let response = self.execute_authenticated( |
| 1318 | HttpMethod::Patch, |
| 1319 | &format!("/api/agents/{agent_id}"), |
| 1320 | Some(json_body(&serde_json::json!({ |
| 1321 | "projectId": project_id, |
| 1322 | "revision": revision, |
| 1323 | }))?), |
| 1324 | )?; |
| 1325 | let result: AgentResponse = expect_json(response, &[200])?; |
| 1326 | if result.agent.id != agent_id || result.agent.project_id != project_id { |
| 1327 | bail!("The Codewhale service returned an unexpected Agent Project binding"); |
| 1328 | } |
| 1329 | Ok(result.agent) |
| 1330 | } |
| 1331 | |
| 1332 | fn threads(&self, agent_id: &str) -> Result<Vec<AgentThread>> { |
| 1333 | let agent_id = validate_resource_id(agent_id, "Agent")?; |
| 1334 | let response = self.execute_authenticated( |
| 1335 | HttpMethod::Get, |
| 1336 | &format!("/v1/threads/summary?agentId={agent_id}&limit=100"), |
| 1337 | None, |
| 1338 | )?; |
| 1339 | expect_json(response, &[200]) |
| 1340 | } |
| 1341 | |
| 1342 | fn thread(&self, id: &str) -> Result<AgentThread> { |
| 1343 | let id = validate_resource_id(id, "Conversation")?; |
| 1344 | let response = |
| 1345 | self.execute_authenticated(HttpMethod::Get, &format!("/v1/threads/{id}"), None)?; |
| 1346 | let result: ThreadResponse = expect_json(response, &[200])?; |
| 1347 | Ok(result.thread) |
| 1348 | } |
| 1349 | |
| 1350 | fn create_agent_thread( |
| 1351 | &self, |
| 1352 | agent_id: &str, |
| 1353 | project_id: Option<&str>, |
| 1354 | title: &str, |
| 1355 | provider: &str, |
| 1356 | model: &str, |
| 1357 | operation_key: &str, |
| 1358 | ) -> Result<AgentThread> { |
| 1359 | let agent_id = validate_resource_id(agent_id, "Agent")?; |
| 1360 | let title = validate_named_text(title, "Conversation title", 120)?; |
| 1361 | let (provider, model) = validate_model_route(provider, model)?; |
| 1362 | let operation_key = validate_operation_key(operation_key)?; |
| 1363 | let mut body = serde_json::json!({ |
| 1364 | "title": title, |
| 1365 | "productMode": "chat", |
| 1366 | "mode": "chat", |
| 1367 | "agentId": agent_id, |
| 1368 | "modelProvider": provider, |
| 1369 | "model": model, |
| 1370 | "operationKey": operation_key, |
| 1371 | }); |
| 1372 | if let Some(project_id) = project_id { |
| 1373 | body["projectId"] = serde_json::json!(validate_resource_id(project_id, "Project")?); |
| 1374 | } |
| 1375 | let response = |
| 1376 | self.execute_authenticated(HttpMethod::Post, "/v1/threads", Some(json_body(&body)?))?; |
| 1377 | let result: ThreadResponse = expect_json(response, &[200, 201])?; |
| 1378 | Ok(result.thread) |
| 1379 | } |
| 1380 | |
| 1381 | fn send_agent_turn( |
| 1382 | &self, |
| 1383 | thread: &AgentThread, |
| 1384 | prompt: &str, |
| 1385 | billing_mode: &str, |
| 1386 | operation_key: &str, |
| 1387 | ) -> Result<TurnReceipt> { |
| 1388 | let thread_id = validate_resource_id(&thread.id, "Conversation")?; |
| 1389 | let prompt = prompt.trim(); |
| 1390 | if prompt.is_empty() || prompt.chars().count() > 32_000 { |
| 1391 | bail!("Message must contain 1-32000 characters"); |
| 1392 | } |
| 1393 | let billing_mode = validate_billing_mode(billing_mode)?; |
| 1394 | let (provider, model) = validate_model_route(&thread.model_provider, &thread.model)?; |
| 1395 | let operation_key = validate_operation_key(operation_key)?; |
| 1396 | let response = self.execute_authenticated( |
| 1397 | HttpMethod::Post, |
| 1398 | &format!("/v1/threads/{thread_id}/turns"), |
| 1399 | Some(json_body(&serde_json::json!({ |
| 1400 | "prompt": prompt, |
| 1401 | "billingMode": billing_mode, |
| 1402 | "modelProvider": provider, |
| 1403 | "modelProviderId": thread.model_provider_id.as_str(), |
| 1404 | "model": model, |
| 1405 | "requiresByok": billing_mode == "byok_external", |
| 1406 | "mode": "chat", |
| 1407 | "productMode": "chat", |
| 1408 | "operationKey": operation_key, |
| 1409 | "sourceMessageId": operation_key, |
| 1410 | }))?), |
| 1411 | )?; |
| 1412 | let result: TurnResponse = expect_json(response, &[200, 201, 202])?; |
| 1413 | Ok(result.turn) |
| 1414 | } |
| 1415 | |
| 1416 | fn agent_turn_result( |
| 1417 | &self, |
| 1418 | thread_id: &str, |
| 1419 | turn_id: &str, |
| 1420 | since_seq: u64, |
| 1421 | ) -> Result<AgentTurnResult> { |
| 1422 | let thread_id = validate_resource_id(thread_id, "Conversation")?; |
| 1423 | let turn_id = validate_turn_id(turn_id)?; |
| 1424 | if since_seq > i64::MAX as u64 { |
| 1425 | bail!("Event sequence is too large"); |
| 1426 | } |
| 1427 | let response = self.execute_authenticated( |
| 1428 | HttpMethod::Get, |
| 1429 | &format!("/v1/threads/{thread_id}/events?since_seq={since_seq}"), |
| 1430 | None, |
| 1431 | )?; |
| 1432 | if response.status != 200 { |
| 1433 | return Err(response_error(&response)); |
| 1434 | } |
| 1435 | parse_agent_turn_events(&response.body, turn_id, since_seq) |
| 1436 | } |
| 1437 | |
| 1438 | fn assign_agent_work( |
| 1439 | &self, |
| 1440 | agent_id: &str, |
| 1441 | objective: &str, |
| 1442 | message_id: &str, |
| 1443 | task_context: Option<&WorkTaskContext>, |
| 1444 | ) -> Result<AgentWorkMessageResponse> { |
| 1445 | let agent_id = validate_resource_id(agent_id, "Agent")?; |
| 1446 | let objective = objective.trim(); |
| 1447 | if objective.is_empty() || objective.encode_utf16().count() > 32_000 { |
| 1448 | bail!("Work objective must contain 1-32000 characters"); |
| 1449 | } |
| 1450 | let message_id = validate_operation_key(message_id)?; |
| 1451 | let mut body = serde_json::json!({ "messageId": message_id, "text": objective }); |
| 1452 | if let Some(context) = task_context { |
| 1453 | body["taskContext"] = serde_json::to_value(context)?; |
| 1454 | } |
| 1455 | let response = self.execute_authenticated( |
| 1456 | HttpMethod::Post, |
| 1457 | &format!("/api/agents/{agent_id}/messages"), |
| 1458 | Some(json_body(&body)?), |
| 1459 | )?; |
| 1460 | if ![200, 201, 202].contains(&response.status) { |
| 1461 | return Err(response_error(&response)); |
| 1462 | } |
| 1463 | // A 2xx the client cannot read means the service acted: an unknown |
| 1464 | // outcome (replay with the same message id), not a plain failure. |
| 1465 | serde_json::from_slice(&response.body).map_err(|source| { |
| 1466 | CloudTransportError::new( |
| 1467 | "The Codewhale service returned an unreadable reply to this message", |
| 1468 | source, |
| 1469 | ) |
| 1470 | .into() |
| 1471 | }) |
| 1472 | } |
| 1473 | |
| 1474 | fn agent_work_status(&self, id: &str) -> Result<serde_json::Value> { |
| 1475 | let id = validate_resource_id(id, "Work")?; |
| 1476 | let response = |
| 1477 | self.execute_authenticated(HttpMethod::Get, &format!("/api/runs/{id}"), None)?; |
| 1478 | expect_json(response, &[200]) |
| 1479 | } |
| 1480 | |
| 1481 | fn computer(&self, id: &str) -> Result<serde_json::Value> { |
| 1482 | let id = validate_computer_id(id)?; |
| 1483 | let response = |
| 1484 | self.execute_authenticated(HttpMethod::Get, &format!("/api/computers/{id}"), None)?; |
| 1485 | expect_json(response, &[200]) |
| 1486 | } |
| 1487 | |
| 1488 | fn computer_usage(&self, id: &str) -> Result<serde_json::Value> { |
| 1489 | let id = validate_computer_id(id)?; |
| 1490 | let response = self.execute_authenticated( |
| 1491 | HttpMethod::Get, |
| 1492 | &format!("/api/computers/{id}/usage"), |
| 1493 | None, |
| 1494 | )?; |
| 1495 | expect_json(response, &[200]) |
| 1496 | } |
| 1497 | |
| 1498 | fn create_computer( |
| 1499 | &self, |
| 1500 | name: &str, |
| 1501 | computer_trial: bool, |
| 1502 | eu_compute_opt_in: bool, |
| 1503 | ) -> Result<AccountComputer> { |
| 1504 | if computer_trial != eu_compute_opt_in { |
| 1505 | bail!("A computer trial requires both --computer-trial and --eu-compute-opt-in"); |
| 1506 | } |
| 1507 | let name = validate_computer_name(name)?; |
| 1508 | let response = self.execute_authenticated( |
| 1509 | HttpMethod::Post, |
| 1510 | "/api/computers", |
| 1511 | Some(json_body(&ComputerCreateRequest { |
| 1512 | name: &name, |
| 1513 | provider: computer_trial.then_some("boat"), |
| 1514 | boat_eu_compute_opt_in: computer_trial.then_some(true), |
| 1515 | })?), |
| 1516 | )?; |
| 1517 | let result: ComputerResponse = expect_json(response, &[200, 201])?; |
| 1518 | Ok(result.computer) |
| 1519 | } |
| 1520 | |
| 1521 | fn computer_action(&self, id: &str, action: &str) -> Result<ComputerResponse> { |
| 1522 | let id = validate_computer_id(id)?; |
| 1523 | let response = self.execute_authenticated( |
| 1524 | HttpMethod::Post, |
| 1525 | &format!("/api/computers/{id}/{action}"), |
| 1526 | None, |
| 1527 | )?; |
| 1528 | let status = response.status; |
| 1529 | let result: ComputerResponse = expect_json( |
| 1530 | response, |
| 1531 | if action == "start" { |
| 1532 | &[200, 202] |
| 1533 | } else { |
| 1534 | &[200] |
| 1535 | }, |
| 1536 | )?; |
| 1537 | if status == 202 && !result.queued { |
| 1538 | bail!("The Codewhale service returned a queued start without queue details"); |
| 1539 | } |
| 1540 | Ok(result) |
| 1541 | } |
| 1542 | |
| 1543 | fn delete_computer(&self, id: &str) -> Result<()> { |
| 1544 | let id = validate_computer_id(id)?; |
| 1545 | let response = self.execute_authenticated( |
| 1546 | HttpMethod::Delete, |
| 1547 | &format!("/api/computers/{id}"), |
| 1548 | Some(json_body(&serde_json::json!({ "discardFiles": true }))?), |
| 1549 | )?; |
| 1550 | let result: ComputerDeleteResponse = expect_json(response, &[200])?; |
| 1551 | if !result.deleted || result.computer_id != id { |
| 1552 | bail!("The Codewhale service did not confirm deletion of Computer {id}"); |
| 1553 | } |
| 1554 | Ok(()) |
| 1555 | } |
| 1556 | |
| 1557 | fn computer_file_revision(&self, computer_id: &str, path: &str) -> Result<serde_json::Value> { |
| 1558 | let id = validate_computer_id(computer_id)?; |
| 1559 | validate_computer_file_path(path)?; |
| 1560 | let mut url = Url::parse("https://codewhale.invalid/")?; |
| 1561 | url.set_path(&format!("/api/computers/{id}/files/revision")); |
| 1562 | url.query_pairs_mut().append_pair("path", path); |
| 1563 | let response = self.execute_authenticated( |
| 1564 | HttpMethod::Get, |
| 1565 | &format!("{}?{}", url.path(), url.query().unwrap_or_default()), |
| 1566 | None, |
| 1567 | )?; |
| 1568 | let value: serde_json::Value = expect_json(response, &[200])?; |
| 1569 | if value["computerId"].as_str() != Some(id) |
| 1570 | || value["path"].as_str() != Some(path) |
| 1571 | || value["size"].as_u64().is_none() |
| 1572 | { |
| 1573 | bail!("The Codewhale service returned an invalid file revision"); |
| 1574 | } |
| 1575 | validate_file_revision(value["revision"].as_str().unwrap_or_default())?; |
| 1576 | Ok(value) |
| 1577 | } |
| 1578 | |
| 1579 | fn computer_file_action( |
| 1580 | &self, |
| 1581 | computer_id: &str, |
| 1582 | action: &str, |
| 1583 | payload: serde_json::Value, |
| 1584 | ) -> Result<serde_json::Value> { |
| 1585 | let id = validate_computer_id(computer_id)?; |
| 1586 | let response = self.execute_authenticated( |
| 1587 | HttpMethod::Post, |
| 1588 | &format!("/api/computers/{id}/files/{action}"), |
| 1589 | Some(json_body(&payload)?), |
| 1590 | )?; |
| 1591 | expect_json(response, &[200, 201]) |
| 1592 | } |
| 1593 | |
| 1594 | fn account_file(&self, file_id: &str) -> Result<serde_json::Value> { |
| 1595 | let id = validate_account_file_id(file_id)?; |
| 1596 | let response = |
| 1597 | self.execute_authenticated(HttpMethod::Get, &format!("/v1/files/{id}"), None)?; |
| 1598 | let value: serde_json::Value = expect_json(response, &[200])?; |
| 1599 | if value["file"]["id"].as_str() != Some(id) { |
| 1600 | bail!("The Codewhale service returned a different account file"); |
| 1601 | } |
| 1602 | Ok(value) |
| 1603 | } |
| 1604 | |
| 1605 | fn download_account_file(&self, file_id: &str, version: u64, output: &Path) -> Result<()> { |
| 1606 | let id = validate_account_file_id(file_id)?; |
| 1607 | match std::fs::symlink_metadata(output) { |
| 1608 | Ok(_) => bail!("The output path already exists; choose another file name"), |
| 1609 | Err(error) if error.kind() == io::ErrorKind::NotFound => {} |
| 1610 | Err(error) => return Err(error).context("could not inspect the output path"), |
| 1611 | } |
| 1612 | let metadata = account_file_version(&self.account_file(id)?, version)?; |
| 1613 | let response = self.execute_authenticated( |
| 1614 | HttpMethod::Get, |
| 1615 | &format!("/v1/files/{id}/content?version={version}"), |
| 1616 | None, |
| 1617 | )?; |
| 1618 | if response.status != 200 { |
| 1619 | return Err(response_error(&response)); |
| 1620 | } |
| 1621 | if response.body.len() as u64 != metadata.size |
| 1622 | || codewhale_runtime::hashing::sha256_hex(&response.body) != metadata.sha256 |
| 1623 | { |
| 1624 | bail!( |
| 1625 | "The downloaded file did not match its saved size and SHA-256; nothing was written" |
| 1626 | ); |
| 1627 | } |
| 1628 | let parent = output |
| 1629 | .parent() |
| 1630 | .filter(|path| !path.as_os_str().is_empty()) |
| 1631 | .unwrap_or(Path::new(".")); |
| 1632 | let mut pending = tempfile::NamedTempFile::new_in(parent) |
| 1633 | .context("could not prepare the download beside its destination")?; |
| 1634 | pending |
| 1635 | .write_all(&response.body) |
| 1636 | .context("could not write the verified download")?; |
| 1637 | pending |
| 1638 | .as_file() |
| 1639 | .sync_all() |
| 1640 | .context("could not sync the verified download")?; |
| 1641 | pending |
| 1642 | .persist_noclobber(output) |
| 1643 | .context("could not save the download without replacing an existing file")?; |
| 1644 | Ok(()) |
| 1645 | } |
| 1646 | |
| 1647 | fn logout(&self) -> Result<bool> { |
| 1648 | let snapshot = self.account_store.snapshot()?; |
| 1649 | self.logout_from_snapshot(&snapshot) |
| 1650 | } |
| 1651 | |
| 1652 | fn logout_from_snapshot(&self, snapshot: &AccountSessionSnapshot) -> Result<bool> { |
| 1653 | self.account_store |
| 1654 | .with_transaction(|transaction| -> Result<bool> { |
| 1655 | if !transaction.matches(snapshot) { |
| 1656 | bail!("The signed-in account changed. Refresh and try again."); |
| 1657 | } |
| 1658 | let stored = match transaction.load() { |
| 1659 | Ok(Some(stored)) => stored, |
| 1660 | Ok(None) | Err(_) => { |
| 1661 | transaction.clear(); |
| 1662 | return Ok(false); |
| 1663 | } |
| 1664 | }; |
| 1665 | let body = json_body(&RefreshRequest { |
| 1666 | refresh_token: &stored.bundle.refresh_token, |
| 1667 | })?; |
| 1668 | let response = self.transport.execute(CloudRequest { |
| 1669 | method: HttpMethod::Post, |
| 1670 | path: "/api/auth/logout".into(), |
| 1671 | bearer: None, |
| 1672 | body: Some(body), |
| 1673 | })?; |
| 1674 | if (200..300).contains(&response.status) || matches!(response.status, 401 | 403) { |
| 1675 | transaction.clear(); |
| 1676 | return Ok((200..300).contains(&response.status)); |
| 1677 | } |
| 1678 | // Keep custody on transient failure so revocation can be retried. |
| 1679 | Err(response_error(&response)) |
| 1680 | }) |
| 1681 | } |
| 1682 | |
| 1683 | fn execute_authenticated( |
| 1684 | &self, |
| 1685 | method: HttpMethod, |
| 1686 | path: &str, |
| 1687 | body: Option<Vec<u8>>, |
| 1688 | ) -> Result<CloudResponse> { |
| 1689 | self.execute_authenticated_snapshot(method, path, body) |
| 1690 | .map(|(response, _)| response) |
| 1691 | } |
| 1692 | |
| 1693 | fn execute_authenticated_snapshot( |
| 1694 | &self, |
| 1695 | method: HttpMethod, |
| 1696 | path: &str, |
| 1697 | body: Option<Vec<u8>>, |
| 1698 | ) -> Result<(CloudResponse, AccountSessionSnapshot)> { |
| 1699 | let snapshot = self.account_store.snapshot()?; |
| 1700 | self.execute_from_snapshot(method, path, body, snapshot) |
| 1701 | } |
| 1702 | |
| 1703 | fn execute_from_snapshot( |
| 1704 | &self, |
| 1705 | method: HttpMethod, |
| 1706 | path: &str, |
| 1707 | body: Option<Vec<u8>>, |
| 1708 | snapshot: AccountSessionSnapshot, |
| 1709 | ) -> Result<(CloudResponse, AccountSessionSnapshot)> { |
| 1710 | let Some(stored) = snapshot.load()? else { |
| 1711 | if !ACCOUNT_SIGN_IN_OPEN { |
| 1712 | bail!(account_sign_in_closed_message()); |
| 1713 | } |
| 1714 | bail!("Not signed in. Run `codewhale login` first"); |
| 1715 | }; |
| 1716 | let first = self.transport.execute(CloudRequest { |
| 1717 | method, |
| 1718 | path: path.into(), |
| 1719 | bearer: Some(stored.bundle.access_token.clone()), |
| 1720 | body: body.clone(), |
| 1721 | })?; |
| 1722 | if first.status != 401 { |
| 1723 | return Ok((first, snapshot)); |
| 1724 | } |
| 1725 | let renewed = self.refresh_snapshot(&snapshot)?; |
| 1726 | let Some((next, next_snapshot)) = renewed else { |
| 1727 | bail!("The Codewhale account session expired. Run `codewhale login` again"); |
| 1728 | }; |
| 1729 | // The rotated token is durable before a potentially failing retry. |
| 1730 | let retried = self.transport.execute(CloudRequest { |
| 1731 | method, |
| 1732 | path: path.into(), |
| 1733 | bearer: Some(next.access_token), |
| 1734 | body, |
| 1735 | })?; |
| 1736 | if retried.status == 401 { |
| 1737 | self.account_store.clear_if_unchanged(&next_snapshot)?; |
| 1738 | bail!("The Codewhale account session expired. Run `codewhale login` again"); |
| 1739 | } |
| 1740 | Ok((retried, next_snapshot)) |
| 1741 | } |
| 1742 | |
| 1743 | fn refresh_snapshot( |
| 1744 | &self, |
| 1745 | snapshot: &AccountSessionSnapshot, |
| 1746 | ) -> Result<Option<(AuthBundle, AccountSessionSnapshot)>> { |
| 1747 | let Some(mut stored) = snapshot.load()? else { |
| 1748 | return Ok(None); |
| 1749 | }; |
| 1750 | self.account_store |
| 1751 | .with_transaction(|transaction| -> Result<_> { |
| 1752 | if !transaction.matches(snapshot) { |
| 1753 | bail!("The signed-in account changed. Refresh and try again."); |
| 1754 | } |
| 1755 | let refresh = self.transport.execute(CloudRequest { |
| 1756 | method: HttpMethod::Post, |
| 1757 | path: "/api/auth/refresh".into(), |
| 1758 | bearer: None, |
| 1759 | body: Some(json_body(&RefreshRequest { |
| 1760 | refresh_token: &stored.bundle.refresh_token, |
| 1761 | })?), |
| 1762 | })?; |
| 1763 | match refresh.status { |
| 1764 | 200 => {} |
| 1765 | 401 => { |
| 1766 | transaction.clear(); |
| 1767 | return Ok(None); |
| 1768 | } |
| 1769 | _ => return Err(response_error(&refresh)), |
| 1770 | } |
| 1771 | let mut next: AuthBundle = parse_json_body(&refresh.body)?; |
| 1772 | validate_auth_bundle(&next)?; |
| 1773 | if next |
| 1774 | .user |
| 1775 | .as_ref() |
| 1776 | .zip(stored.bundle.user.as_ref()) |
| 1777 | .is_some_and(|(next, previous)| next.id != previous.id) |
| 1778 | || next |
| 1779 | .session |
| 1780 | .as_ref() |
| 1781 | .zip(stored.bundle.session.as_ref()) |
| 1782 | .is_some_and(|(next, previous)| next.id != previous.id) |
| 1783 | { |
| 1784 | bail!("The refreshed account changed. Sign in again before retrying."); |
| 1785 | } |
| 1786 | if next.user.is_none() { |
| 1787 | next.user = stored.bundle.user.take(); |
| 1788 | } |
| 1789 | if next.session.is_none() { |
| 1790 | next.session = stored.bundle.session.take(); |
| 1791 | } |
| 1792 | transaction.replace(next.clone())?; |
| 1793 | Ok(Some((next, transaction.snapshot()))) |
| 1794 | }) |
| 1795 | } |
| 1796 | |
| 1797 | /// Whether an interactive session exists for this profile and origin. |
| 1798 | /// |
| 1799 | /// A management command asks this before it asks anything of the network, |
| 1800 | /// so "you have a machine key but no login" is answered locally instead of |
| 1801 | /// as a 403 from a route the key was never allowed to touch. |
| 1802 | fn has_session(&self) -> Result<bool> { |
| 1803 | Ok(self.load_auth()?.is_some()) |
| 1804 | } |
| 1805 | |
| 1806 | /// `execute_authenticated`, retrying only what the caller marks replayable. |
| 1807 | /// |
| 1808 | /// `machine::Retry::Never` is not a default worth having: the one POST in |
| 1809 | /// this surface mints a secret shown exactly once, so a retry that quietly |
| 1810 | /// succeeded server-side would leave an unrevocable key behind. |
| 1811 | fn execute_authenticated_with_retry( |
| 1812 | &self, |
| 1813 | method: HttpMethod, |
| 1814 | path: &str, |
| 1815 | body: Option<Vec<u8>>, |
| 1816 | retry: machine::Retry, |
| 1817 | sleeper: &mut dyn FnMut(Duration), |
| 1818 | ) -> Result<CloudResponse> { |
| 1819 | let max_attempts = if retry == machine::Retry::Idempotent { |
| 1820 | 3 |
| 1821 | } else { |
| 1822 | 1 |
| 1823 | }; |
| 1824 | let mut attempt = 1; |
| 1825 | loop { |
| 1826 | let response = self.execute_authenticated(method, path, body.clone())?; |
| 1827 | if (200..300).contains(&response.status) || attempt >= max_attempts { |
| 1828 | return Ok(response); |
| 1829 | } |
| 1830 | let retry_after = response.retry_after; |
| 1831 | if !machine::classify(&response).retryable { |
| 1832 | return Ok(response); |
| 1833 | } |
| 1834 | sleeper(machine::backoff_delay(attempt, retry_after)); |
| 1835 | attempt += 1; |
| 1836 | } |
| 1837 | } |
| 1838 | } |
| 1839 | |
| 1840 | fn validate_computer_id(value: &str) -> Result<&str> { |
| 1841 | validate_resource_id(value, "Computer") |
| 1842 | } |
| 1843 | |
| 1844 | fn validate_account_file_id(value: &str) -> Result<&str> { |
| 1845 | let suffix = value.strip_prefix("file_").unwrap_or_default(); |
| 1846 | if !(16..=64).contains(&suffix.len()) |
| 1847 | || !suffix |
| 1848 | .bytes() |
| 1849 | .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_')) |
| 1850 | { |
| 1851 | bail!("Account file ID must be file_ followed by 16-64 letters, digits, `-`, or `_`"); |
| 1852 | } |
| 1853 | Ok(value) |
| 1854 | } |
| 1855 | |
| 1856 | fn validate_computer_file_path(value: &str) -> Result<()> { |
| 1857 | let bytes = value.as_bytes(); |
| 1858 | if value.is_empty() |
| 1859 | || value.len() > 4096 |
| 1860 | || value.starts_with('/') |
| 1861 | || value.contains('\\') |
| 1862 | || value.chars().any(char::is_control) |
| 1863 | || bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' |
| 1864 | || value.split('/').any(|part| matches!(part, "" | "." | "..")) |
| 1865 | { |
| 1866 | bail!( |
| 1867 | "Choose a relative file path inside the computer workspace, without `.` or `..` segments" |
| 1868 | ); |
| 1869 | } |
| 1870 | Ok(()) |
| 1871 | } |
| 1872 | |
| 1873 | fn validate_file_revision(value: &str) -> Result<&str> { |
| 1874 | if value.len() != 64 |
| 1875 | || !value |
| 1876 | .bytes() |
| 1877 | .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f')) |
| 1878 | { |
| 1879 | bail!("File revision must be a lowercase SHA-256 hash of 64 characters"); |
| 1880 | } |
| 1881 | Ok(value) |
| 1882 | } |
| 1883 | |
| 1884 | fn account_file_version(value: &serde_json::Value, version: u64) -> Result<AccountFileVersion> { |
| 1885 | if !(1..=MAX_FILE_VERSION).contains(&version) { |
| 1886 | bail!("Choose an explicit positive saved file version"); |
| 1887 | } |
| 1888 | let versions: Vec<AccountFileVersion> = serde_json::from_value(value["versions"].clone()) |
| 1889 | .context("The Codewhale service returned invalid file versions")?; |
| 1890 | let mut matches = versions |
| 1891 | .into_iter() |
| 1892 | .filter(|entry| entry.version == version); |
| 1893 | let selected = matches |
| 1894 | .next() |
| 1895 | .ok_or_else(|| anyhow!("That saved file version is unavailable"))?; |
| 1896 | if matches.next().is_some() || selected.size == 0 || selected.size > MAX_FILE_DOWNLOAD_BYTES { |
| 1897 | bail!("The Codewhale service returned invalid saved file metadata"); |
| 1898 | } |
| 1899 | validate_file_revision(&selected.sha256)?; |
| 1900 | Ok(selected) |
| 1901 | } |
| 1902 | |
| 1903 | fn validate_resource_id<'a>(value: &'a str, kind: &str) -> Result<&'a str> { |
| 1904 | let id = value.trim(); |
| 1905 | let bytes = id.as_bytes(); |
| 1906 | if bytes.is_empty() |
| 1907 | || bytes.len() > 160 |
| 1908 | || !bytes[0].is_ascii_alphanumeric() |
| 1909 | || !bytes |
| 1910 | .iter() |
| 1911 | .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_')) |
| 1912 | { |
| 1913 | bail!("{kind} ID must be a bounded identifier of letters, digits, `-`, or `_`"); |
| 1914 | } |
| 1915 | Ok(id) |
| 1916 | } |
| 1917 | |
| 1918 | fn validate_turn_id(value: &str) -> Result<&str> { |
| 1919 | let id = value.trim(); |
| 1920 | let bytes = id.as_bytes(); |
| 1921 | if bytes.is_empty() |
| 1922 | || bytes.len() > 160 |
| 1923 | || !bytes[0].is_ascii_alphanumeric() |
| 1924 | || !bytes.iter().all(|byte| { |
| 1925 | byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':' | b'@') |
| 1926 | }) |
| 1927 | || id.contains("..") |
| 1928 | { |
| 1929 | bail!( |
| 1930 | "Turn ID must be a bounded identifier of letters, digits, `-`, `_`, `.`, `:`, or `@`" |
| 1931 | ); |
| 1932 | } |
| 1933 | Ok(id) |
| 1934 | } |
| 1935 | |
| 1936 | fn validate_computer_name(value: &str) -> Result<String> { |
| 1937 | validate_named_text(value, "Computer name", 80) |
| 1938 | } |
| 1939 | |
| 1940 | fn validate_named_text(value: &str, label: &str, maximum: usize) -> Result<String> { |
| 1941 | let text = value.trim(); |
| 1942 | if text.is_empty() || text.chars().count() > maximum || text.chars().any(char::is_control) { |
| 1943 | bail!("{label} must contain 1-{maximum} characters without control characters"); |
| 1944 | } |
| 1945 | Ok(text.to_string()) |
| 1946 | } |
| 1947 | |
| 1948 | fn validate_operation_key(value: &str) -> Result<&str> { |
| 1949 | let key = value.trim(); |
| 1950 | if key.is_empty() |
| 1951 | || key.len() > 128 |
| 1952 | || !key |
| 1953 | .bytes() |
| 1954 | .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-')) |
| 1955 | { |
| 1956 | bail!("Operation key must be 1-128 URL-safe characters"); |
| 1957 | } |
| 1958 | Ok(key) |
| 1959 | } |
| 1960 | |
| 1961 | fn validate_billing_mode(value: &str) -> Result<&str> { |
| 1962 | match value.trim() { |
| 1963 | "byok_external" => Ok("byok_external"), |
| 1964 | "membership_included" | "managed_wallet" => { |
| 1965 | bail!( |
| 1966 | "Codewhale-managed model billing is unavailable under the current launch policy. Use --billing-mode byok_external with your own provider key" |
| 1967 | ) |
| 1968 | } |
| 1969 | _ => bail!("Billing mode must be byok_external under the current launch policy"), |
| 1970 | } |
| 1971 | } |
| 1972 | |
| 1973 | fn validate_model_route<'a>(provider: &'a str, model: &'a str) -> Result<(&'a str, &'a str)> { |
| 1974 | let provider = provider.trim(); |
| 1975 | let model = model.trim(); |
| 1976 | if provider.is_empty() |
| 1977 | || provider.len() > 128 |
| 1978 | || !provider |
| 1979 | .bytes() |
| 1980 | .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-')) |
| 1981 | || model.is_empty() |
| 1982 | || model.len() > 256 |
| 1983 | || !model.bytes().all(|byte| { |
| 1984 | byte.is_ascii_alphanumeric() |
| 1985 | || matches!(byte, b'.' | b'_' | b':' | b'/' | b'@' | b'+' | b'-') |
| 1986 | }) |
| 1987 | || provider.contains("..") |
| 1988 | || model.contains("..") |
| 1989 | { |
| 1990 | bail!("Model route must contain a bounded provider and model identifier"); |
| 1991 | } |
| 1992 | Ok((provider, model)) |
| 1993 | } |
| 1994 | |
| 1995 | /// Refuse a (provider, model) the live account catalog does not list. |
| 1996 | /// |
| 1997 | /// The catalog is served data (`GET /api/model-providers`), so a new model |
| 1998 | /// needs no CLI release and a retired one stops being accepted here. The |
| 1999 | /// message names the catalog and what it does list for the provider. |
| 2000 | /// |
| 2001 | /// Returns the row's canonical id: the control plane stores that id even when |
| 2002 | /// the caller named the runtime alias (`xiaomi-mimo` for `xiaomi`), so it is |
| 2003 | /// the value to send and to compare the created conversation against. |
| 2004 | fn assert_catalog_route<'a>( |
| 2005 | catalog: &'a [CatalogProvider], |
| 2006 | provider: &str, |
| 2007 | model: &str, |
| 2008 | ) -> Result<&'a str> { |
| 2009 | let row = catalog.iter().find(|row| { |
| 2010 | row.connection_available != Some(false) |
| 2011 | && (row.id == provider || row.runtime_provider.as_deref() == Some(provider)) |
| 2012 | }); |
| 2013 | if let Some(row) = row |
| 2014 | && row.models.iter().any(|listed| listed == model) |
| 2015 | { |
| 2016 | return Ok(row.id.as_str()); |
| 2017 | } |
| 2018 | let listed = match row { |
| 2019 | Some(row) if !row.models.is_empty() => format!( |
| 2020 | "The catalog lists these models for `{}`: {}", |
| 2021 | printable(provider), |
| 2022 | row.models |
| 2023 | .iter() |
| 2024 | .take(12) |
| 2025 | .map(|model| printable(model)) |
| 2026 | .collect::<Vec<_>>() |
| 2027 | .join(", ") |
| 2028 | ), |
| 2029 | Some(_) => format!("The catalog lists no models for `{}`", printable(provider)), |
| 2030 | None => format!( |
| 2031 | "`{}` is not a hosted provider in the catalog. Known providers: {}", |
| 2032 | printable(provider), |
| 2033 | catalog |
| 2034 | .iter() |
| 2035 | .filter(|row| row.connection_available != Some(false)) |
| 2036 | .map(|row| row.id.as_str()) |
| 2037 | .collect::<Vec<_>>() |
| 2038 | .join(", ") |
| 2039 | ), |
| 2040 | }; |
| 2041 | bail!( |
| 2042 | "`{}/{}` is not listed in the live Codewhale model catalog (GET /api/model-providers), so no conversation was created. {listed}", |
| 2043 | printable(provider), |
| 2044 | printable(model) |
| 2045 | ) |
| 2046 | } |
| 2047 | |
| 2048 | fn work_objective_and_context( |
| 2049 | objective: &str, |
| 2050 | context_file: Option<&Path>, |
| 2051 | file_refs: &[String], |
| 2052 | ) -> Result<(String, Option<WorkTaskContext>)> { |
| 2053 | let objective = objective.trim(); |
| 2054 | if objective.is_empty() || objective.encode_utf16().count() > 32_000 { |
| 2055 | bail!("Work objective must contain 1-32000 UTF-16 units"); |
| 2056 | } |
| 2057 | let mut context = work::task_context(context_file, file_refs)?; |
| 2058 | if objective.encode_utf16().count() > 12_000 { |
| 2059 | let context = context.get_or_insert_with(|| WorkTaskContext { |
| 2060 | text: String::new(), |
| 2061 | file_refs: Vec::new(), |
| 2062 | }); |
| 2063 | context.text = if context.text.is_empty() { |
| 2064 | objective.to_string() |
| 2065 | } else { |
| 2066 | format!("{objective}\n\n{}", context.text) |
| 2067 | }; |
| 2068 | if context.text.encode_utf16().count() > 64_000 { |
| 2069 | bail!("Task source context exceeds 64000 UTF-16 units"); |
| 2070 | } |
| 2071 | } |
| 2072 | Ok((objective.to_string(), context)) |
| 2073 | } |
| 2074 | |
| 2075 | fn prepare_work_agent<T: CloudTransport>( |
| 2076 | client: &CloudClient<'_, T>, |
| 2077 | selector: Option<&str>, |
| 2078 | ) -> Result<AccountAgent> { |
| 2079 | let selected = match selector { |
| 2080 | Some(selector) => { |
| 2081 | let listing: AgentListResponse = serde_json::from_value(client.agents()?) |
| 2082 | .context("The Codewhale service returned an invalid Agent list")?; |
| 2083 | let agent = resolve_account_agent(&listing.agents, selector)?; |
| 2084 | if !agent.project_id.is_empty() { |
| 2085 | return Ok(agent); |
| 2086 | } |
| 2087 | Some(agent) |
| 2088 | } |
| 2089 | None => None, |
| 2090 | }; |
| 2091 | let response: AgentResponse = expect_json( |
| 2092 | client.execute_authenticated( |
| 2093 | HttpMethod::Post, |
| 2094 | "/api/work-box", |
| 2095 | Some(json_body(&serde_json::json!({}))?), |
| 2096 | )?, |
| 2097 | &[200], |
| 2098 | )?; |
| 2099 | match selected { |
| 2100 | Some(selected) |
| 2101 | if response.agent.id != selected.id || response.agent.project_id.is_empty() => |
| 2102 | { |
| 2103 | bail!( |
| 2104 | "This Agent cannot use the account's repository-free task context. Use Agent {}", |
| 2105 | printable(&response.agent.name) |
| 2106 | ) |
| 2107 | } |
| 2108 | None if response.agent.project_id.is_empty() => { |
| 2109 | bail!("The account has no default Agent for repository-free tasks") |
| 2110 | } |
| 2111 | _ => Ok(response.agent), |
| 2112 | } |
| 2113 | } |
| 2114 | |
| 2115 | fn dispatch_stamp(objective: &str) -> String { |
| 2116 | let nanos = std::time::SystemTime::now() |
| 2117 | .duration_since(std::time::UNIX_EPOCH) |
| 2118 | .map_or(0, |elapsed| elapsed.as_nanos()); |
| 2119 | let seed = format!("{nanos}:{}:{objective}", std::process::id()); |
| 2120 | codewhale_runtime::hashing::sha256_hex(seed.as_bytes())[..24].to_string() |
| 2121 | } |
| 2122 | |
| 2123 | pub(crate) enum AccountDispatch { |
| 2124 | Computer(computer::SessionArgs), |
| 2125 | Run { |
| 2126 | objective: String, |
| 2127 | agent: Option<String>, |
| 2128 | seconds: Option<u64>, |
| 2129 | context_file: Option<PathBuf>, |
| 2130 | file_refs: Vec<String>, |
| 2131 | operation_key: Option<String>, |
| 2132 | message_id: Option<String>, |
| 2133 | yes: bool, |
| 2134 | confirm_eu_compute: bool, |
| 2135 | }, |
| 2136 | Status(String), |
| 2137 | Cancel(String), |
| 2138 | } |
| 2139 | |
| 2140 | pub(crate) fn run_dispatch( |
| 2141 | call: AccountDispatch, |
| 2142 | profile: Option<&str>, |
| 2143 | config: &mut ConfigStore, |
| 2144 | ) -> Result<()> { |
| 2145 | let command = match call { |
| 2146 | AccountDispatch::Computer(args) => { |
| 2147 | return run( |
| 2148 | CloudArgs { |
| 2149 | api_base: None, |
| 2150 | command: CloudCommand::Session(args), |
| 2151 | }, |
| 2152 | profile, |
| 2153 | config, |
| 2154 | ); |
| 2155 | } |
| 2156 | AccountDispatch::Run { |
| 2157 | objective, |
| 2158 | agent, |
| 2159 | seconds, |
| 2160 | context_file, |
| 2161 | file_refs, |
| 2162 | operation_key, |
| 2163 | message_id, |
| 2164 | yes, |
| 2165 | confirm_eu_compute, |
| 2166 | } => CloudAgentsCommand::Dispatch { |
| 2167 | objective, |
| 2168 | agent, |
| 2169 | seconds, |
| 2170 | context_file, |
| 2171 | file_refs, |
| 2172 | operation_key, |
| 2173 | message_id, |
| 2174 | yes, |
| 2175 | confirm_eu_compute, |
| 2176 | }, |
| 2177 | AccountDispatch::Status(id) => CloudAgentsCommand::WorkStatus { id }, |
| 2178 | AccountDispatch::Cancel(id) => CloudAgentsCommand::WorkCancel { |
| 2179 | id, |
| 2180 | queue: None, |
| 2181 | reason: None, |
| 2182 | }, |
| 2183 | }; |
| 2184 | run( |
| 2185 | CloudArgs { |
| 2186 | api_base: None, |
| 2187 | command: CloudCommand::Agents(CloudAgentsArgs { command }), |
| 2188 | }, |
| 2189 | profile, |
| 2190 | config, |
| 2191 | ) |
| 2192 | } |
| 2193 | |
| 2194 | fn resolve_account_agent(agents: &[AccountAgent], selector: &str) -> Result<AccountAgent> { |
| 2195 | let selector = selector.trim(); |
| 2196 | if selector.is_empty() { |
| 2197 | bail!("Choose an Agent name or ID"); |
| 2198 | } |
| 2199 | let by_id = agents.iter().find(|agent| agent.id == selector); |
| 2200 | let matches = if let Some(agent) = by_id { |
| 2201 | vec![agent] |
| 2202 | } else { |
| 2203 | agents |
| 2204 | .iter() |
| 2205 | .filter(|agent| agent.name == selector) |
| 2206 | .collect::<Vec<_>>() |
| 2207 | }; |
| 2208 | if matches.len() != 1 { |
| 2209 | bail!( |
| 2210 | "Expected one Agent named `{}`; found {}. Run `codewhale account agents list` and use its ID", |
| 2211 | printable(selector), |
| 2212 | matches.len() |
| 2213 | ); |
| 2214 | } |
| 2215 | let agent = matches[0]; |
| 2216 | validate_resource_id(&agent.id, "Agent")?; |
| 2217 | if agent.status != "active" { |
| 2218 | bail!("Agent {} is not active", printable(&agent.name)); |
| 2219 | } |
| 2220 | Ok(agent.clone()) |
| 2221 | } |
| 2222 | |
| 2223 | fn active_agent_thread(thread: &AgentThread, agent_id: &str) -> bool { |
| 2224 | thread.agent_id == agent_id && thread.archived_at.is_empty() && thread.kind != "smoke" |
| 2225 | } |
| 2226 | |
| 2227 | fn parse_agent_turn_events(body: &[u8], turn_id: &str, since_seq: u64) -> Result<AgentTurnResult> { |
| 2228 | let text = std::str::from_utf8(body) |
| 2229 | .context("The Codewhale service returned invalid conversation events")?; |
| 2230 | let normalized = text.replace("\r\n", "\n"); |
| 2231 | let mut result = AgentTurnResult { |
| 2232 | last_seq: since_seq, |
| 2233 | status: "not_seen".to_string(), |
| 2234 | answer: String::new(), |
| 2235 | seen_turn: false, |
| 2236 | }; |
| 2237 | for frame in normalized.split("\n\n") { |
| 2238 | let mut data = None; |
| 2239 | for line in frame.lines() { |
| 2240 | if let Some(value) = line.strip_prefix("data:") |
| 2241 | && data.replace(value.trim_start_matches(' ')).is_some() |
| 2242 | { |
| 2243 | bail!("The Codewhale service returned a malformed conversation event"); |
| 2244 | } |
| 2245 | } |
| 2246 | let Some(data) = data else { continue }; |
| 2247 | let event: AgentTurnEvent = serde_json::from_str(data) |
| 2248 | .context("The Codewhale service returned an invalid conversation event")?; |
| 2249 | if event.seq <= result.last_seq { |
| 2250 | bail!("The Codewhale service returned an out-of-order conversation event"); |
| 2251 | } |
| 2252 | result.last_seq = event.seq; |
| 2253 | if event.turn_id != turn_id { |
| 2254 | continue; |
| 2255 | } |
| 2256 | result.seen_turn = true; |
| 2257 | if result.status == "not_seen" { |
| 2258 | result.status = "pending".to_string(); |
| 2259 | } |
| 2260 | match event.kind.as_str() { |
| 2261 | "assistant.delta" => { |
| 2262 | let delta = event |
| 2263 | .payload |
| 2264 | .get("text") |
| 2265 | .and_then(serde_json::Value::as_str) |
| 2266 | .ok_or_else(|| { |
| 2267 | anyhow!("The Codewhale service returned invalid assistant text") |
| 2268 | })?; |
| 2269 | result.answer.push_str(delta); |
| 2270 | if result.answer.len() > 128 * 1024 { |
| 2271 | bail!("The Codewhale service returned an unexpectedly long answer"); |
| 2272 | } |
| 2273 | } |
| 2274 | "turn.completed" => { |
| 2275 | let status = event |
| 2276 | .payload |
| 2277 | .get("status") |
| 2278 | .and_then(serde_json::Value::as_str) |
| 2279 | .unwrap_or("completed"); |
| 2280 | if !matches!(status, "completed" | "failed") { |
| 2281 | bail!("The Codewhale service returned an invalid turn status"); |
| 2282 | } |
| 2283 | result.status = status.to_string(); |
| 2284 | } |
| 2285 | "turn.canceled" => result.status = "canceled".to_string(), |
| 2286 | _ => {} |
| 2287 | } |
| 2288 | } |
| 2289 | Ok(result) |
| 2290 | } |
| 2291 | |
| 2292 | fn write_agent_thread<W: Write>(out: &mut W, thread: &AgentThread) -> Result<()> { |
| 2293 | validate_resource_id(&thread.id, "Conversation")?; |
| 2294 | let (provider, model) = validate_model_route(&thread.model_provider, &thread.model)?; |
| 2295 | writeln!(out, "Conversation: {}", printable(&thread.title))?; |
| 2296 | writeln!(out, "ID: {}", thread.id)?; |
| 2297 | writeln!(out, "Model: {provider}/{model}")?; |
| 2298 | Ok(()) |
| 2299 | } |
| 2300 | |
| 2301 | fn run_projects<T: CloudTransport, W: Write>( |
| 2302 | command: CloudProjectsCommand, |
| 2303 | client: &CloudClient<'_, T>, |
| 2304 | machine: &machine::MachineKeyEnv, |
| 2305 | out: &mut W, |
| 2306 | ) -> Result<()> { |
| 2307 | if machine.is_present() { |
| 2308 | bail!( |
| 2309 | "Projects require an interactive Codewhale account login; unset CODEWHALE_API_KEY and run `codewhale login`" |
| 2310 | ); |
| 2311 | } |
| 2312 | match command { |
| 2313 | CloudProjectsCommand::List { json } => { |
| 2314 | let response = client.projects()?; |
| 2315 | if json { |
| 2316 | return write_computer_json(out, &response); |
| 2317 | } |
| 2318 | let listing: ProjectListResponse = serde_json::from_value(response) |
| 2319 | .context("The Codewhale service returned an invalid Project list")?; |
| 2320 | writeln!(out, "Codewhale Projects ({})", listing.projects.len())?; |
| 2321 | for project in listing.projects { |
| 2322 | validate_resource_id(&project.id, "Project")?; |
| 2323 | writeln!(out, "{} — {}", printable(&project.name), project.id)?; |
| 2324 | } |
| 2325 | Ok(()) |
| 2326 | } |
| 2327 | CloudProjectsCommand::Create { |
| 2328 | name, |
| 2329 | repo_binding_id, |
| 2330 | operation_key, |
| 2331 | } => { |
| 2332 | let listing: GitHubBindingListResponse = |
| 2333 | serde_json::from_value(client.github_bindings()?) |
| 2334 | .context("The Codewhale service returned an invalid GitHub repository list")?; |
| 2335 | let binding = listing |
| 2336 | .bindings |
| 2337 | .iter() |
| 2338 | .find(|binding| binding.id == repo_binding_id) |
| 2339 | .ok_or_else(|| anyhow!( |
| 2340 | "GitHub binding {} is not connected to this account. Run `codewhale account github bindings`", |
| 2341 | printable(&repo_binding_id) |
| 2342 | ))?; |
| 2343 | if binding.provider != "github" |
| 2344 | || binding.installation_id.is_empty() |
| 2345 | || ["error", "revoked", "suspended", "disabled"] |
| 2346 | .contains(&binding.status.to_ascii_lowercase().as_str()) |
| 2347 | { |
| 2348 | bail!( |
| 2349 | "That GitHub binding is unavailable for a Project. Reconnect the repository, then run `codewhale account github bindings`" |
| 2350 | ); |
| 2351 | } |
| 2352 | let project = client.create_github_project(&name, binding, &operation_key)?; |
| 2353 | writeln!(out, "Project: {}", printable(&project.name))?; |
| 2354 | writeln!(out, "ID: {}", project.id)?; |
| 2355 | writeln!( |
| 2356 | out, |
| 2357 | "GitHub repository: {}", |
| 2358 | printable(&project.default_repo) |
| 2359 | )?; |
| 2360 | writeln!( |
| 2361 | out, |
| 2362 | "Assign a Whale: codewhale account agents bind-project AGENT {}", |
| 2363 | project.id |
| 2364 | )?; |
| 2365 | Ok(()) |
| 2366 | } |
| 2367 | } |
| 2368 | } |
| 2369 | |
| 2370 | fn run_github<T: CloudTransport, W: Write>( |
| 2371 | command: CloudGithubCommand, |
| 2372 | client: &CloudClient<'_, T>, |
| 2373 | machine: &machine::MachineKeyEnv, |
| 2374 | out: &mut W, |
| 2375 | ) -> Result<()> { |
| 2376 | if machine.is_present() { |
| 2377 | bail!( |
| 2378 | "GitHub bindings require an interactive Codewhale account login; unset CODEWHALE_API_KEY and run `codewhale login`" |
| 2379 | ); |
| 2380 | } |
| 2381 | match command { |
| 2382 | CloudGithubCommand::Bindings { json } => { |
| 2383 | let response = client.github_bindings()?; |
| 2384 | if json { |
| 2385 | return write_computer_json(out, &response); |
| 2386 | } |
| 2387 | let listing: GitHubBindingListResponse = serde_json::from_value(response) |
| 2388 | .context("The Codewhale service returned an invalid GitHub repository list")?; |
| 2389 | writeln!(out, "GitHub repositories ({})", listing.bindings.len())?; |
| 2390 | if listing.bindings.is_empty() { |
| 2391 | writeln!( |
| 2392 | out, |
| 2393 | "No GitHub repositories are connected to this account. Authorize one in Codewhale's GitHub setup, then retry." |
| 2394 | )?; |
| 2395 | } |
| 2396 | for binding in listing.bindings { |
| 2397 | if binding.provider != "github" || binding.id.is_empty() || binding.repo.is_empty() |
| 2398 | { |
| 2399 | bail!("The Codewhale service returned an invalid GitHub repository binding"); |
| 2400 | } |
| 2401 | writeln!( |
| 2402 | out, |
| 2403 | "{} — {} ({})", |
| 2404 | printable(&binding.repo), |
| 2405 | printable(&binding.id), |
| 2406 | printable(&binding.status) |
| 2407 | )?; |
| 2408 | } |
| 2409 | Ok(()) |
| 2410 | } |
| 2411 | CloudGithubCommand::Bind { |
| 2412 | repo, |
| 2413 | installation_id, |
| 2414 | } => work::bind_github_repo(client, out, &repo, installation_id.as_deref()), |
| 2415 | } |
| 2416 | } |
| 2417 | |
| 2418 | fn run_agents<T: CloudTransport, W: Write>( |
| 2419 | command: CloudAgentsCommand, |
| 2420 | client: &CloudClient<'_, T>, |
| 2421 | machine: &machine::MachineKeyEnv, |
| 2422 | out: &mut W, |
| 2423 | ) -> Result<()> { |
| 2424 | if machine.is_present() { |
| 2425 | bail!( |
| 2426 | "Agents require an interactive Codewhale account login; unset CODEWHALE_API_KEY and run `codewhale login`" |
| 2427 | ); |
| 2428 | } |
| 2429 | match command { |
| 2430 | CloudAgentsCommand::List { json } => { |
| 2431 | let response = client.agents()?; |
| 2432 | if json { |
| 2433 | return write_computer_json(out, &response); |
| 2434 | } |
| 2435 | let listing: AgentListResponse = serde_json::from_value(response) |
| 2436 | .context("The Codewhale service returned an invalid Agent list")?; |
| 2437 | writeln!(out, "Codewhale Agents ({})", listing.agents.len())?; |
| 2438 | for agent in listing.agents { |
| 2439 | validate_resource_id(&agent.id, "Agent")?; |
| 2440 | match agent |
| 2441 | .configuration |
| 2442 | .as_ref() |
| 2443 | .and_then(|configuration| configuration.model.as_ref()) |
| 2444 | { |
| 2445 | Some(route) => writeln!( |
| 2446 | out, |
| 2447 | "{} — {} ({}/{})", |
| 2448 | printable(&agent.name), |
| 2449 | agent.id, |
| 2450 | printable(&route.provider), |
| 2451 | printable(&route.model) |
| 2452 | )?, |
| 2453 | None => writeln!(out, "{} — {}", printable(&agent.name), agent.id)?, |
| 2454 | } |
| 2455 | } |
| 2456 | Ok(()) |
| 2457 | } |
| 2458 | CloudAgentsCommand::Create { |
| 2459 | name, |
| 2460 | project_id, |
| 2461 | provider, |
| 2462 | model, |
| 2463 | operation_key, |
| 2464 | } => { |
| 2465 | let route = provider.as_deref().zip(model.as_deref()); |
| 2466 | let agent = client.create_agent(&name, project_id.as_deref(), route, &operation_key)?; |
| 2467 | validate_resource_id(&agent.id, "Agent")?; |
| 2468 | if let Some(project_id) = project_id.as_deref() |
| 2469 | && agent.project_id != validate_resource_id(project_id, "Project")? |
| 2470 | { |
| 2471 | bail!("The Codewhale service returned an unexpected Agent Project binding"); |
| 2472 | } |
| 2473 | writeln!(out, "Agent: {}", printable(&agent.name))?; |
| 2474 | writeln!(out, "ID: {}", agent.id)?; |
| 2475 | if let Some(configuration) = agent.configuration.as_ref() |
| 2476 | && let Some(saved) = configuration.model.as_ref() |
| 2477 | { |
| 2478 | if route.is_some_and(|(provider, model)| { |
| 2479 | provider != saved.provider || model != saved.model |
| 2480 | }) { |
| 2481 | bail!("The Codewhale service saved a different model than requested"); |
| 2482 | } |
| 2483 | writeln!( |
| 2484 | out, |
| 2485 | "Model: {}/{} (Fleet revision {})", |
| 2486 | printable(&saved.provider), |
| 2487 | printable(&saved.model), |
| 2488 | configuration.revision |
| 2489 | )?; |
| 2490 | } else if route.is_some() { |
| 2491 | bail!("The Codewhale service did not save the requested model"); |
| 2492 | } |
| 2493 | if !agent.project_id.is_empty() { |
| 2494 | writeln!( |
| 2495 | out, |
| 2496 | "Project ID: {}", |
| 2497 | validate_resource_id(&agent.project_id, "Project")? |
| 2498 | )?; |
| 2499 | } |
| 2500 | writeln!( |
| 2501 | out, |
| 2502 | "Create request ID: {}", |
| 2503 | validate_operation_key(&operation_key)? |
| 2504 | )?; |
| 2505 | if agent.project_id.is_empty() { |
| 2506 | writeln!( |
| 2507 | out, |
| 2508 | "This Agent can chat now. Bind a Project for repository Work; run `codewhale account projects list` to find one." |
| 2509 | )?; |
| 2510 | } |
| 2511 | Ok(()) |
| 2512 | } |
| 2513 | CloudAgentsCommand::BindProject { agent, project_id } => { |
| 2514 | let listing: AgentListResponse = serde_json::from_value(client.agents()?) |
| 2515 | .context("The Codewhale service returned an invalid Agent list")?; |
| 2516 | let selected = resolve_account_agent(&listing.agents, &agent)?; |
| 2517 | let project_id = validate_resource_id(&project_id, "Project")?; |
| 2518 | let projects: ProjectListResponse = serde_json::from_value(client.projects()?) |
| 2519 | .context("The Codewhale service returned an invalid Project list")?; |
| 2520 | if !projects |
| 2521 | .projects |
| 2522 | .iter() |
| 2523 | .any(|project| project.id == project_id) |
| 2524 | { |
| 2525 | bail!( |
| 2526 | "Project {project_id} is not available on this account. Run `codewhale account projects list`" |
| 2527 | ); |
| 2528 | } |
| 2529 | if selected.project_id == project_id { |
| 2530 | writeln!( |
| 2531 | out, |
| 2532 | "Agent {} is already bound to Project {project_id}.", |
| 2533 | printable(&selected.name) |
| 2534 | )?; |
| 2535 | return Ok(()); |
| 2536 | } |
| 2537 | let bound = client.bind_agent_project(&selected.id, project_id, selected.revision)?; |
| 2538 | writeln!( |
| 2539 | out, |
| 2540 | "Agent {} is bound to Project {project_id}.", |
| 2541 | printable(&bound.name) |
| 2542 | )?; |
| 2543 | Ok(()) |
| 2544 | } |
| 2545 | CloudAgentsCommand::Threads { agent, json } => { |
| 2546 | let listing: AgentListResponse = serde_json::from_value(client.agents()?) |
| 2547 | .context("The Codewhale service returned an invalid Agent list")?; |
| 2548 | let selected = resolve_account_agent(&listing.agents, &agent)?; |
| 2549 | let threads = client |
| 2550 | .threads(&selected.id)? |
| 2551 | .into_iter() |
| 2552 | .filter(|thread| active_agent_thread(thread, &selected.id)) |
| 2553 | .collect::<Vec<_>>(); |
| 2554 | if json { |
| 2555 | return write_computer_json(out, &serde_json::to_value(&threads)?); |
| 2556 | } |
| 2557 | writeln!( |
| 2558 | out, |
| 2559 | "Recent conversations for {} ({})", |
| 2560 | printable(&selected.name), |
| 2561 | threads.len() |
| 2562 | )?; |
| 2563 | for thread in &threads { |
| 2564 | write_agent_thread(out, thread)?; |
| 2565 | } |
| 2566 | Ok(()) |
| 2567 | } |
| 2568 | CloudAgentsCommand::NewThread { |
| 2569 | agent, |
| 2570 | title, |
| 2571 | provider, |
| 2572 | model, |
| 2573 | operation_key, |
| 2574 | } => { |
| 2575 | let listing: AgentListResponse = serde_json::from_value(client.agents()?) |
| 2576 | .context("The Codewhale service returned an invalid Agent list")?; |
| 2577 | let selected = resolve_account_agent(&listing.agents, &agent)?; |
| 2578 | let project_id = selected.project_id.trim(); |
| 2579 | // The saved route is a promise about which model answers, so a |
| 2580 | // route the live catalog does not list is refused before anything |
| 2581 | // is created rather than accepted and discovered at first send. |
| 2582 | let (route_provider, route_model) = validate_model_route(&provider, &model)?; |
| 2583 | let catalog = client.provider_catalog()?; |
| 2584 | let route_provider = assert_catalog_route(&catalog, route_provider, route_model)?; |
| 2585 | let thread = client.create_agent_thread( |
| 2586 | &selected.id, |
| 2587 | if project_id.is_empty() { |
| 2588 | None |
| 2589 | } else { |
| 2590 | Some(project_id) |
| 2591 | }, |
| 2592 | &title, |
| 2593 | route_provider, |
| 2594 | route_model, |
| 2595 | &operation_key, |
| 2596 | )?; |
| 2597 | if !active_agent_thread(&thread, &selected.id) { |
| 2598 | bail!("The Codewhale service did not return an active conversation for this Agent"); |
| 2599 | } |
| 2600 | if thread.model_provider != route_provider || thread.model != route_model { |
| 2601 | bail!( |
| 2602 | "The Codewhale service created conversation {} on {}/{} instead of the requested {route_provider}/{route_model}. Do not send to it; create a new conversation or report this route mismatch", |
| 2603 | printable(&thread.id), |
| 2604 | printable(&thread.model_provider), |
| 2605 | printable(&thread.model) |
| 2606 | ); |
| 2607 | } |
| 2608 | if !project_id.is_empty() && thread.project_id != project_id { |
| 2609 | bail!( |
| 2610 | "The Codewhale service created this conversation in a different Project; verify the Agent's Project before sending" |
| 2611 | ); |
| 2612 | } |
| 2613 | write_agent_thread(out, &thread)?; |
| 2614 | writeln!( |
| 2615 | out, |
| 2616 | "Create request ID: {}", |
| 2617 | validate_operation_key(&operation_key)? |
| 2618 | )?; |
| 2619 | writeln!( |
| 2620 | out, |
| 2621 | "Sending requires an explicit --billing-mode and a new --operation-key for each message." |
| 2622 | )?; |
| 2623 | Ok(()) |
| 2624 | } |
| 2625 | CloudAgentsCommand::Send { |
| 2626 | agent, |
| 2627 | prompt, |
| 2628 | thread, |
| 2629 | billing_mode, |
| 2630 | operation_key, |
| 2631 | } => { |
| 2632 | let listing: AgentListResponse = serde_json::from_value(client.agents()?) |
| 2633 | .context("The Codewhale service returned an invalid Agent list")?; |
| 2634 | let selected = resolve_account_agent(&listing.agents, &agent)?; |
| 2635 | let selected_thread = if let Some(id) = thread { |
| 2636 | client.thread(&id)? |
| 2637 | } else { |
| 2638 | let threads = client.threads(&selected.id)?; |
| 2639 | if threads.len() >= 100 { |
| 2640 | bail!( |
| 2641 | "Agent {} has at least 100 recent conversations; pass --thread with an ID so an older Main conversation is not missed", |
| 2642 | printable(&selected.name) |
| 2643 | ); |
| 2644 | } |
| 2645 | let mut active = threads |
| 2646 | .into_iter() |
| 2647 | .filter(|thread| active_agent_thread(thread, &selected.id)) |
| 2648 | .collect::<Vec<_>>(); |
| 2649 | if active.len() == 1 { |
| 2650 | active.remove(0) |
| 2651 | } else { |
| 2652 | let mut main = active.into_iter().filter(|thread| thread.title == "Main"); |
| 2653 | let first = main.next().ok_or_else(|| anyhow!( |
| 2654 | "Agent {} has no unique active conversation. Run `codewhale account agents new-thread` first, or pass --thread", |
| 2655 | printable(&selected.name) |
| 2656 | ))?; |
| 2657 | if main.next().is_some() { |
| 2658 | bail!( |
| 2659 | "Agent {} has several Main conversations; pass --thread with an ID", |
| 2660 | printable(&selected.name) |
| 2661 | ); |
| 2662 | } |
| 2663 | first |
| 2664 | } |
| 2665 | }; |
| 2666 | if !active_agent_thread(&selected_thread, &selected.id) { |
| 2667 | bail!( |
| 2668 | "That conversation is not active or does not belong to Agent {}", |
| 2669 | printable(&selected.name) |
| 2670 | ); |
| 2671 | } |
| 2672 | if !selected.project_id.is_empty() && selected_thread.project_id != selected.project_id |
| 2673 | { |
| 2674 | bail!( |
| 2675 | "That conversation belongs to a different Project than Agent {} currently owns. Bind the Agent and create a new conversation in its Project before sending", |
| 2676 | printable(&selected.name) |
| 2677 | ); |
| 2678 | } |
| 2679 | let receipt = |
| 2680 | client.send_agent_turn(&selected_thread, &prompt, &billing_mode, &operation_key)?; |
| 2681 | validate_turn_id(&receipt.id)?; |
| 2682 | writeln!(out, "Conversation ID: {}", selected_thread.id)?; |
| 2683 | writeln!(out, "Turn ID: {}", receipt.id)?; |
| 2684 | writeln!(out, "Status: {}", printable(&receipt.status))?; |
| 2685 | writeln!( |
| 2686 | out, |
| 2687 | "Message request ID: {}", |
| 2688 | validate_operation_key(&operation_key)? |
| 2689 | )?; |
| 2690 | writeln!( |
| 2691 | out, |
| 2692 | "Read the answer: codewhale account agents result {} {} {}", |
| 2693 | selected.id, selected_thread.id, receipt.id |
| 2694 | )?; |
| 2695 | Ok(()) |
| 2696 | } |
| 2697 | CloudAgentsCommand::Result { |
| 2698 | agent, |
| 2699 | thread, |
| 2700 | turn, |
| 2701 | since_seq, |
| 2702 | } => { |
| 2703 | let listing: AgentListResponse = serde_json::from_value(client.agents()?) |
| 2704 | .context("The Codewhale service returned an invalid Agent list")?; |
| 2705 | let selected = resolve_account_agent(&listing.agents, &agent)?; |
| 2706 | let selected_thread = client.thread(&thread)?; |
| 2707 | if !active_agent_thread(&selected_thread, &selected.id) { |
| 2708 | bail!( |
| 2709 | "That conversation is not active or does not belong to Agent {}", |
| 2710 | printable(&selected.name) |
| 2711 | ); |
| 2712 | } |
| 2713 | let turn_id = validate_turn_id(&turn)?; |
| 2714 | let result = client.agent_turn_result(&selected_thread.id, turn_id, since_seq)?; |
| 2715 | writeln!(out, "Turn ID: {turn_id}")?; |
| 2716 | writeln!(out, "Status: {}", result.status)?; |
| 2717 | writeln!(out, "Last event sequence: {}", result.last_seq)?; |
| 2718 | if !result.seen_turn { |
| 2719 | writeln!(out, "No events for this turn after the selected sequence.")?; |
| 2720 | } else if !result.answer.is_empty() { |
| 2721 | let label = if result.status == "pending" { |
| 2722 | "Answer so far" |
| 2723 | } else { |
| 2724 | "Answer" |
| 2725 | }; |
| 2726 | writeln!(out, "{label}:")?; |
| 2727 | writeln!( |
| 2728 | out, |
| 2729 | "{}", |
| 2730 | result |
| 2731 | .answer |
| 2732 | .chars() |
| 2733 | .filter(|ch| *ch == '\n' || *ch == '\t' || !ch.is_control()) |
| 2734 | .collect::<String>() |
| 2735 | )?; |
| 2736 | } |
| 2737 | if result.status == "pending" || result.status == "not_seen" { |
| 2738 | writeln!(out, "Run this result command again to read later events.")?; |
| 2739 | } |
| 2740 | Ok(()) |
| 2741 | } |
| 2742 | CloudAgentsCommand::Work { |
| 2743 | agent, |
| 2744 | objective, |
| 2745 | message_id, |
| 2746 | context_file, |
| 2747 | file_refs, |
| 2748 | } => { |
| 2749 | let (objective, context) = |
| 2750 | work_objective_and_context(&objective, context_file.as_deref(), &file_refs)?; |
| 2751 | validate_operation_key(&message_id)?; |
| 2752 | let selected = prepare_work_agent(client, Some(&agent))?; |
| 2753 | work::assign( |
| 2754 | client, |
| 2755 | out, |
| 2756 | &selected, |
| 2757 | &objective, |
| 2758 | &message_id, |
| 2759 | context.as_ref(), |
| 2760 | ) |
| 2761 | .map(|_| ()) |
| 2762 | } |
| 2763 | CloudAgentsCommand::Dispatch { |
| 2764 | objective, |
| 2765 | agent, |
| 2766 | seconds, |
| 2767 | context_file, |
| 2768 | file_refs, |
| 2769 | operation_key, |
| 2770 | message_id, |
| 2771 | yes, |
| 2772 | confirm_eu_compute, |
| 2773 | } => { |
| 2774 | let (objective, context) = |
| 2775 | work_objective_and_context(&objective, context_file.as_deref(), &file_refs)?; |
| 2776 | let stamp = dispatch_stamp(&objective); |
| 2777 | let message_id = message_id.unwrap_or_else(|| format!("dispatch-m-{stamp}")); |
| 2778 | let operation_key = operation_key.unwrap_or_else(|| format!("dispatch-o-{stamp}")); |
| 2779 | validate_operation_key(&message_id)?; |
| 2780 | validate_operation_key(&operation_key)?; |
| 2781 | let selected = prepare_work_agent(client, agent.as_deref())?; |
| 2782 | let interactive = io::stdin().is_terminal() && io::stdout().is_terminal(); |
| 2783 | work::dispatch( |
| 2784 | client, |
| 2785 | out, |
| 2786 | &selected, |
| 2787 | &objective, |
| 2788 | context.as_ref(), |
| 2789 | work::DispatchOptions { |
| 2790 | seconds, |
| 2791 | operation_key: &operation_key, |
| 2792 | message_id: &message_id, |
| 2793 | yes, |
| 2794 | confirm_eu_compute, |
| 2795 | interactive, |
| 2796 | }, |
| 2797 | &mut || { |
| 2798 | let mut line = String::new(); |
| 2799 | io::stdin() |
| 2800 | .read_line(&mut line) |
| 2801 | .context("failed to read the answer from stdin")?; |
| 2802 | Ok(line) |
| 2803 | }, |
| 2804 | ) |
| 2805 | } |
| 2806 | CloudAgentsCommand::WorkStatus { id } => { |
| 2807 | let result = client.agent_work_status(&id)?; |
| 2808 | let run = result |
| 2809 | .get("run") |
| 2810 | .filter(|run| run.is_object()) |
| 2811 | .ok_or_else(|| anyhow!("The Codewhale service returned no Work record"))?; |
| 2812 | if run.get("id").and_then(|value| value.as_str()) |
| 2813 | != Some(validate_resource_id(&id, "Work")?) |
| 2814 | { |
| 2815 | bail!("The Codewhale service returned a different Work record"); |
| 2816 | } |
| 2817 | writeln!(out, "Work ID: {}", validate_resource_id(&id, "Work")?)?; |
| 2818 | writeln!( |
| 2819 | out, |
| 2820 | "Status: {}", |
| 2821 | printable( |
| 2822 | run.get("state") |
| 2823 | .and_then(|value| value.as_str()) |
| 2824 | .unwrap_or("unknown") |
| 2825 | ) |
| 2826 | )?; |
| 2827 | if let Some(title) = run.get("title").and_then(|value| value.as_str()) { |
| 2828 | writeln!(out, "Objective: {}", printable(title))?; |
| 2829 | } |
| 2830 | if let Some(workspace) = run |
| 2831 | .get("workspaceId") |
| 2832 | .and_then(|value| value.as_str()) |
| 2833 | .filter(|id| !id.is_empty()) |
| 2834 | { |
| 2835 | writeln!(out, "Workspace ID: {}", printable(workspace))?; |
| 2836 | } |
| 2837 | Ok(()) |
| 2838 | } |
| 2839 | CloudAgentsCommand::WorkCancel { id, queue, reason } => { |
| 2840 | work::cancel(client, out, &id, queue, reason.as_deref()) |
| 2841 | } |
| 2842 | CloudAgentsCommand::WorkResult { id, json } => work::result(client, out, &id, json), |
| 2843 | CloudAgentsCommand::WorkQuote { |
| 2844 | id, |
| 2845 | operation_key, |
| 2846 | seconds, |
| 2847 | recovery_from, |
| 2848 | } => work::quote( |
| 2849 | client, |
| 2850 | out, |
| 2851 | &id, |
| 2852 | &operation_key, |
| 2853 | seconds, |
| 2854 | recovery_from.as_deref(), |
| 2855 | true, |
| 2856 | ) |
| 2857 | .map(|_| ()), |
| 2858 | CloudAgentsCommand::WorkLaunch { |
| 2859 | id, |
| 2860 | operation_key, |
| 2861 | confirmation, |
| 2862 | confirm_eu_compute, |
| 2863 | seconds, |
| 2864 | recovery_from, |
| 2865 | } => { |
| 2866 | let confirmation = if confirmation == "-" && confirm_eu_compute { |
| 2867 | if io::stdin().is_terminal() { |
| 2868 | bail!( |
| 2869 | "Pipe the launch confirmation to stdin; it must not be typed into the terminal" |
| 2870 | ); |
| 2871 | } |
| 2872 | work::read_confirmation(io::stdin().lock())? |
| 2873 | } else { |
| 2874 | confirmation |
| 2875 | }; |
| 2876 | work::launch( |
| 2877 | client, |
| 2878 | out, |
| 2879 | &id, |
| 2880 | &operation_key, |
| 2881 | &confirmation, |
| 2882 | confirm_eu_compute, |
| 2883 | seconds, |
| 2884 | recovery_from.as_deref(), |
| 2885 | ) |
| 2886 | } |
| 2887 | } |
| 2888 | } |
| 2889 | |
| 2890 | fn write_computer<W: Write>(out: &mut W, computer: &AccountComputer) -> Result<()> { |
| 2891 | validate_computer_id(&computer.id)?; |
| 2892 | if computer.owner_id.trim().is_empty() { |
| 2893 | bail!("The Codewhale service returned a Computer without an owner"); |
| 2894 | } |
| 2895 | writeln!(out, "Computer: {}", printable(&computer.name))?; |
| 2896 | writeln!(out, "ID: {}", computer.id)?; |
| 2897 | writeln!(out, "Account ID: {}", printable(&computer.owner_id))?; |
| 2898 | writeln!(out, "Status: {}", printable(&computer.status))?; |
| 2899 | writeln!(out, "Region: {}", printable(&computer.region))?; |
| 2900 | Ok(()) |
| 2901 | } |
| 2902 | |
| 2903 | fn write_computer_json<W: Write>(out: &mut W, value: &serde_json::Value) -> Result<()> { |
| 2904 | serde_json::to_writer_pretty(&mut *out, value) |
| 2905 | .context("failed to write Codewhale Computer JSON")?; |
| 2906 | writeln!(out)?; |
| 2907 | Ok(()) |
| 2908 | } |
| 2909 | |
| 2910 | fn run_computers<T: CloudTransport, W: Write>( |
| 2911 | command: CloudComputersCommand, |
| 2912 | client: &CloudClient<'_, T>, |
| 2913 | machine: &machine::MachineKeyEnv, |
| 2914 | out: &mut W, |
| 2915 | ) -> Result<()> { |
| 2916 | // Machine keys are intentionally narrower than an interactive account |
| 2917 | // session. A present key must never silently fall back to a human login. |
| 2918 | if machine.is_present() { |
| 2919 | bail!( |
| 2920 | "Computers require an interactive Codewhale account login; unset CODEWHALE_API_KEY and run `codewhale login`" |
| 2921 | ); |
| 2922 | } |
| 2923 | match command { |
| 2924 | CloudComputersCommand::List { json } => { |
| 2925 | let response = client.computers()?; |
| 2926 | if json { |
| 2927 | return write_computer_json(out, &response); |
| 2928 | } |
| 2929 | let computers: ComputerListResponse = serde_json::from_value(response) |
| 2930 | .context("The Codewhale service returned an invalid Computer list")?; |
| 2931 | let computers = computers.computers; |
| 2932 | writeln!(out, "Codewhale Computers ({})", computers.len())?; |
| 2933 | for computer in &computers { |
| 2934 | write_computer(out, computer)?; |
| 2935 | } |
| 2936 | Ok(()) |
| 2937 | } |
| 2938 | CloudComputersCommand::Create { |
| 2939 | name, |
| 2940 | computer_trial, |
| 2941 | eu_compute_opt_in, |
| 2942 | } => { |
| 2943 | let computer = client.create_computer(&name, computer_trial, eu_compute_opt_in)?; |
| 2944 | write_computer(out, &computer)?; |
| 2945 | writeln!( |
| 2946 | out, |
| 2947 | "Saved Computer identity; compute is allocated when you start it." |
| 2948 | )?; |
| 2949 | Ok(()) |
| 2950 | } |
| 2951 | CloudComputersCommand::Show { id, json } => { |
| 2952 | let response = client.computer(&id)?; |
| 2953 | if json { |
| 2954 | write_computer_json(out, &response) |
| 2955 | } else { |
| 2956 | let result: ComputerResponse = serde_json::from_value(response) |
| 2957 | .context("The Codewhale service returned an invalid Computer")?; |
| 2958 | write_computer(out, &result.computer) |
| 2959 | } |
| 2960 | } |
| 2961 | CloudComputersCommand::Usage { id, json } => { |
| 2962 | if !json { |
| 2963 | bail!("Use --json to inspect Computer usage receipts"); |
| 2964 | } |
| 2965 | write_computer_json(out, &client.computer_usage(&id)?) |
| 2966 | } |
| 2967 | CloudComputersCommand::Start { id } => { |
| 2968 | let result = client.computer_action(&id, "start")?; |
| 2969 | if result.queued { |
| 2970 | writeln!(out, "Computer start queued.")?; |
| 2971 | if !result.computer.start_queue_reason.is_empty() { |
| 2972 | writeln!( |
| 2973 | out, |
| 2974 | "Reason: {}", |
| 2975 | printable(&result.computer.start_queue_reason) |
| 2976 | )?; |
| 2977 | } |
| 2978 | } |
| 2979 | write_computer(out, &result.computer) |
| 2980 | } |
| 2981 | CloudComputersCommand::Pause { id } => { |
| 2982 | let result = client.computer_action(&id, "pause")?; |
| 2983 | write_computer(out, &result.computer) |
| 2984 | } |
| 2985 | CloudComputersCommand::Delete { id, discard_files } => { |
| 2986 | if !discard_files { |
| 2987 | bail!( |
| 2988 | "Deleting a computer discards its remaining files; save them first, then pass --discard-files" |
| 2989 | ); |
| 2990 | } |
| 2991 | client.delete_computer(&id)?; |
| 2992 | writeln!(out, "Deleted Computer {}.", validate_computer_id(&id)?)?; |
| 2993 | Ok(()) |
| 2994 | } |
| 2995 | CloudComputersCommand::Files { command } => run_computer_files(command, client, out), |
| 2996 | } |
| 2997 | } |
| 2998 | |
| 2999 | fn run_computer_files<T: CloudTransport, W: Write>( |
| 3000 | command: CloudComputerFilesCommand, |
| 3001 | client: &CloudClient<'_, T>, |
| 3002 | out: &mut W, |
| 3003 | ) -> Result<()> { |
| 3004 | match command { |
| 3005 | CloudComputerFilesCommand::Save { |
| 3006 | computer_id, |
| 3007 | path, |
| 3008 | request_id, |
| 3009 | file_id, |
| 3010 | expected_version, |
| 3011 | expected_revision, |
| 3012 | name, |
| 3013 | } => { |
| 3014 | let id = validate_computer_id(&computer_id)?; |
| 3015 | validate_computer_file_path(&path)?; |
| 3016 | let request_id = validate_turn_id(&request_id)?; |
| 3017 | if file_id.is_some() != expected_version.is_some() |
| 3018 | || expected_version.is_some_and(|version| !(1..MAX_FILE_VERSION).contains(&version)) |
| 3019 | { |
| 3020 | bail!("Saving another version needs both --file-id and a valid --expected-version"); |
| 3021 | } |
| 3022 | if let Some(file_id) = &file_id { |
| 3023 | validate_account_file_id(file_id)?; |
| 3024 | } |
| 3025 | if let Some(revision) = &expected_revision { |
| 3026 | validate_file_revision(revision)?; |
| 3027 | } |
| 3028 | let result = client.computer_file_action(id, "save", serde_json::json!({ |
| 3029 | "path": path, "requestId": request_id, "fileId": file_id, |
| 3030 | "expectedVersion": expected_version.unwrap_or(0), "expectedRevision": expected_revision, "name": name, |
| 3031 | }))?; |
| 3032 | let saved_id = result["file"]["id"].as_str().unwrap_or_default(); |
| 3033 | validate_account_file_id(saved_id)?; |
| 3034 | let sha256 = result["file"]["sha256"].as_str().unwrap_or_default(); |
| 3035 | validate_file_revision(sha256)?; |
| 3036 | if result["saved"]["computerId"].as_str() != Some(id) |
| 3037 | || result["saved"]["path"].as_str() != Some(path.as_str()) |
| 3038 | || result["saved"]["revision"].as_str() != Some(sha256) |
| 3039 | || result["file"]["version"].as_u64() != Some(expected_version.unwrap_or(0) + 1) |
| 3040 | || !result["file"]["size"] |
| 3041 | .as_u64() |
| 3042 | .is_some_and(|size| (1..=MAX_COMPUTER_FILE_SAVE_BYTES).contains(&size)) |
| 3043 | || file_id |
| 3044 | .as_deref() |
| 3045 | .is_some_and(|expected| expected != saved_id) |
| 3046 | || expected_revision |
| 3047 | .as_deref() |
| 3048 | .is_some_and(|expected| expected != sha256) |
| 3049 | { |
| 3050 | bail!("The save receipt could not be verified; retry using the same --request-id"); |
| 3051 | } |
| 3052 | write_computer_json(out, &result) |
| 3053 | } |
| 3054 | CloudComputerFilesCommand::Restore { |
| 3055 | computer_id, |
| 3056 | file_id, |
| 3057 | path, |
| 3058 | version, |
| 3059 | expected_revision, |
| 3060 | } => { |
| 3061 | let id = validate_computer_id(&computer_id)?; |
| 3062 | validate_computer_file_path(&path)?; |
| 3063 | if let Some(revision) = &expected_revision { |
| 3064 | validate_file_revision(revision)?; |
| 3065 | } |
| 3066 | let metadata = account_file_version(&client.account_file(&file_id)?, version)?; |
| 3067 | if metadata.size > MAX_COMPUTER_FILE_RESTORE_BYTES { |
| 3068 | bail!("Restore supports files up to 4 MiB; download this version instead"); |
| 3069 | } |
| 3070 | match client.computer_file_revision(id, &path) { |
| 3071 | Ok(current) => match expected_revision.as_deref() { |
| 3072 | Some(expected) if current["revision"].as_str() == Some(expected) => {} |
| 3073 | Some(_) => { |
| 3074 | bail!("The destination revision changed; inspect it before restoring") |
| 3075 | } |
| 3076 | None => bail!( |
| 3077 | "The destination exists; inspect its revision and pass --expected-revision to replace it" |
| 3078 | ), |
| 3079 | }, |
| 3080 | Err(error) |
| 3081 | if expected_revision.is_none() |
| 3082 | && error.downcast_ref::<CloudHttpError>().is_some_and(|error| { |
| 3083 | error.status == 404 |
| 3084 | && error.code.as_deref() == Some("computer_file_not_found") |
| 3085 | }) => {} |
| 3086 | Err(error) => return Err(error), |
| 3087 | } |
| 3088 | let result = client.computer_file_action(id, "restore", serde_json::json!({ |
| 3089 | "path": path, "fileId": file_id, "version": version, "expectedRevision": expected_revision, |
| 3090 | }))?; |
| 3091 | let restored = &result["restored"]; |
| 3092 | if restored["computerId"].as_str() != Some(id) |
| 3093 | || restored["path"].as_str() != Some(path.as_str()) |
| 3094 | || restored["fileId"].as_str() != Some(file_id.as_str()) |
| 3095 | || restored["version"].as_u64() != Some(version) |
| 3096 | || restored["size"].as_u64() != Some(metadata.size) |
| 3097 | || restored["revision"].as_str() != Some(metadata.sha256.as_str()) |
| 3098 | || restored["created"].as_bool().is_none() |
| 3099 | { |
| 3100 | bail!( |
| 3101 | "The restore receipt could not be verified; inspect the destination revision before retrying" |
| 3102 | ); |
| 3103 | } |
| 3104 | write_computer_json(out, &result) |
| 3105 | } |
| 3106 | CloudComputerFilesCommand::Revision { computer_id, path } => { |
| 3107 | write_computer_json(out, &client.computer_file_revision(&computer_id, &path)?) |
| 3108 | } |
| 3109 | CloudComputerFilesCommand::Versions { file_id } => { |
| 3110 | write_computer_json(out, &client.account_file(&file_id)?) |
| 3111 | } |
| 3112 | CloudComputerFilesCommand::Download { |
| 3113 | file_id, |
| 3114 | version, |
| 3115 | output, |
| 3116 | } => { |
| 3117 | client.download_account_file(&file_id, version, &output)?; |
| 3118 | writeln!( |
| 3119 | out, |
| 3120 | "Downloaded {} version {} to {} (size and SHA-256 verified).", |
| 3121 | file_id, |
| 3122 | version, |
| 3123 | printable(&output.display().to_string()) |
| 3124 | )?; |
| 3125 | Ok(()) |
| 3126 | } |
| 3127 | } |
| 3128 | } |
| 3129 | |
| 3130 | enum KeyReadMode { |
| 3131 | Stdin, |
| 3132 | HiddenPrompt(String), |
| 3133 | } |
| 3134 | |
| 3135 | pub fn run(args: CloudArgs, profile: Option<&str>, config: &mut ConfigStore) -> Result<()> { |
| 3136 | let machine = machine::MachineKeyEnv::from_process_env(); |
| 3137 | if account_command_is_closed(ACCOUNT_SIGN_IN_OPEN, &args.command) { |
| 3138 | bail!(account_sign_in_closed_message()); |
| 3139 | } |
| 3140 | let requested_base = machine::resolve_api_base( |
| 3141 | args.api_base.as_deref(), |
| 3142 | std::env::var(machine::MACHINE_API_BASE_ENV).ok().as_deref(), |
| 3143 | std::env::var(CLOUD_API_BASE_ENV).ok().as_deref(), |
| 3144 | DEFAULT_API_BASE, |
| 3145 | ); |
| 3146 | if machine.is_present() { |
| 3147 | // A machine token is a bearer credential with no replay protection. |
| 3148 | // Refuse cleartext to a remote host before a transport exists, so |
| 3149 | // there is no code path on which the key could be written to a socket. |
| 3150 | machine::require_secure_base(&requested_base)?; |
| 3151 | } |
| 3152 | let api_base = validate_api_base(&requested_base)?; |
| 3153 | let transport = ReqwestTransport::new(api_base.url.clone())?; |
| 3154 | // Account refresh tokens require an OS credential manager. The ordinary |
| 3155 | // provider backend remains independently configurable for `--from-local`. |
| 3156 | let cloud_secrets = cloud_session_secrets()?; |
| 3157 | let provider_secrets = Secrets::auto_detect(); |
| 3158 | let profile = normalized_profile(profile); |
| 3159 | let mut stdout = io::stdout().lock(); |
| 3160 | let mut key_reader = |mode: KeyReadMode| match mode { |
| 3161 | KeyReadMode::Stdin => read_key_from_stdin(), |
| 3162 | KeyReadMode::HiddenPrompt(provider) => read_key_hidden(&provider), |
| 3163 | }; |
| 3164 | let mut opener = |url: String| webbrowser::open(&url).is_ok(); |
| 3165 | let mut sleeper = |duration| thread::sleep(duration); |
| 3166 | run_with( |
| 3167 | args.command, |
| 3168 | &profile, |
| 3169 | &api_base.display, |
| 3170 | config, |
| 3171 | &cloud_secrets, |
| 3172 | &provider_secrets, |
| 3173 | &machine, |
| 3174 | &transport, |
| 3175 | &mut stdout, |
| 3176 | &mut key_reader, |
| 3177 | &mut opener, |
| 3178 | &mut sleeper, |
| 3179 | ) |
| 3180 | } |
| 3181 | |
| 3182 | fn account_command_is_closed(sign_in_open: bool, command: &CloudCommand) -> bool { |
| 3183 | !sign_in_open && matches!(command, CloudCommand::Login(_)) |
| 3184 | } |
| 3185 | |
| 3186 | fn cloud_session_secrets() -> Result<Secrets> { |
| 3187 | // Codex-style storage contract: the OS credential manager is preferred |
| 3188 | // but never required; without one, sessions live in the private 0600 |
| 3189 | // Codewhale secrets file. Only an unresolvable store path fails here. |
| 3190 | secure_account_session_secrets().map_err(|err| anyhow!(err.to_string())) |
| 3191 | } |
| 3192 | |
| 3193 | /// `codewhale login` is a convenience entry to the account device flow — the |
| 3194 | /// same path as `codewhale account login`, without re-spelling the subcommand. |
| 3195 | pub fn run_account_login( |
| 3196 | no_open: bool, |
| 3197 | timeout_seconds: u64, |
| 3198 | profile: Option<&str>, |
| 3199 | config: &mut ConfigStore, |
| 3200 | ) -> Result<()> { |
| 3201 | run( |
| 3202 | CloudArgs { |
| 3203 | api_base: None, |
| 3204 | command: CloudCommand::Login(CloudLoginArgs { |
| 3205 | no_open, |
| 3206 | timeout_seconds, |
| 3207 | }), |
| 3208 | }, |
| 3209 | profile, |
| 3210 | config, |
| 3211 | ) |
| 3212 | } |
| 3213 | |
| 3214 | pub fn run_account_logout(profile: Option<&str>, config: &mut ConfigStore) -> Result<()> { |
| 3215 | run( |
| 3216 | CloudArgs { |
| 3217 | api_base: None, |
| 3218 | command: CloudCommand::Logout, |
| 3219 | }, |
| 3220 | profile, |
| 3221 | config, |
| 3222 | ) |
| 3223 | } |
| 3224 | |
| 3225 | pub fn reject_inline_api_key(api_key: Option<&str>) -> Result<()> { |
| 3226 | if api_key.is_some() { |
| 3227 | bail!( |
| 3228 | "`codewhale account` does not accept the global `--api-key` flag because command-line values can leak through shell history. Use `account keys set <provider>` for a hidden prompt, `--api-key-stdin`, or `--from-local`" |
| 3229 | ); |
| 3230 | } |
| 3231 | Ok(()) |
| 3232 | } |
| 3233 | |
| 3234 | #[allow(clippy::too_many_arguments)] |
| 3235 | fn run_with<T: CloudTransport, W: Write>( |
| 3236 | command: CloudCommand, |
| 3237 | profile: &str, |
| 3238 | api_base: &str, |
| 3239 | config: &mut ConfigStore, |
| 3240 | cloud_secrets: &Secrets, |
| 3241 | provider_secrets: &Secrets, |
| 3242 | machine: &machine::MachineKeyEnv, |
| 3243 | transport: &T, |
| 3244 | out: &mut W, |
| 3245 | key_reader: &mut dyn FnMut(KeyReadMode) -> Result<String>, |
| 3246 | opener: &mut dyn FnMut(String) -> bool, |
| 3247 | sleeper: &mut dyn FnMut(Duration), |
| 3248 | ) -> Result<()> { |
| 3249 | let client = CloudClient::new(transport, cloud_secrets, profile, api_base); |
| 3250 | match command { |
| 3251 | CloudCommand::Login(login) => { |
| 3252 | let snapshot = client.account_store.begin_login()?; |
| 3253 | let device = client.start_device()?; |
| 3254 | validate_user_code(&device.user_code)?; |
| 3255 | validate_verification_url( |
| 3256 | &device.verification_uri, |
| 3257 | api_base, |
| 3258 | &device.user_code, |
| 3259 | false, |
| 3260 | )?; |
| 3261 | let verification_uri_complete = validate_verification_url( |
| 3262 | &device.verification_uri_complete, |
| 3263 | api_base, |
| 3264 | &device.user_code, |
| 3265 | true, |
| 3266 | )?; |
| 3267 | writeln!(out, "Codewhale account sign-in")?; |
| 3268 | writeln!(out, "Code: {}", device.user_code)?; |
| 3269 | writeln!(out, "Open: {verification_uri_complete}")?; |
| 3270 | writeln!(out, "Profile: {}", printable(profile))?; |
| 3271 | if !login.no_open && !opener(verification_uri_complete) { |
| 3272 | writeln!( |
| 3273 | out, |
| 3274 | "Browser could not be opened; use the URL and code above." |
| 3275 | )?; |
| 3276 | } |
| 3277 | let _ = client.poll_device( |
| 3278 | &device, |
| 3279 | &snapshot, |
| 3280 | Duration::from_secs(login.timeout_seconds), |
| 3281 | sleeper, |
| 3282 | )?; |
| 3283 | let user = client.me()?; |
| 3284 | write_account(out, "Signed in to Codewhale.", profile, api_base, &user)?; |
| 3285 | writeln!( |
| 3286 | out, |
| 3287 | "Keeping your configured {} route.", |
| 3288 | config.config.provider.as_str() |
| 3289 | )?; |
| 3290 | Ok(()) |
| 3291 | } |
| 3292 | CloudCommand::ClaudeOrg(args) => { |
| 3293 | claude_org::run_claude_org(args, &client, api_base, out, opener, sleeper) |
| 3294 | } |
| 3295 | CloudCommand::Status => match client.load_auth()? { |
| 3296 | Some(_) => { |
| 3297 | let user = client.me()?; |
| 3298 | write_account(out, "Signed in to Codewhale.", profile, api_base, &user) |
| 3299 | } |
| 3300 | None => { |
| 3301 | writeln!(out, "Not signed in to Codewhale.")?; |
| 3302 | writeln!(out, "Profile: {}", printable(profile))?; |
| 3303 | writeln!(out, "API: {api_base}")?; |
| 3304 | if ACCOUNT_SIGN_IN_OPEN { |
| 3305 | writeln!(out, "Run `codewhale login` to sign in.")?; |
| 3306 | } else { |
| 3307 | writeln!(out, "{}", account_sign_in_closed_message())?; |
| 3308 | } |
| 3309 | Ok(()) |
| 3310 | } |
| 3311 | }, |
| 3312 | CloudCommand::Logout => { |
| 3313 | let remote_revoked = client.logout()?; |
| 3314 | writeln!(out, "Removed the local Codewhale account session.")?; |
| 3315 | writeln!(out, "Profile: {}", printable(profile))?; |
| 3316 | if !remote_revoked { |
| 3317 | writeln!( |
| 3318 | out, |
| 3319 | "Remote revocation was not confirmed; the local tokens are gone." |
| 3320 | )?; |
| 3321 | } |
| 3322 | Ok(()) |
| 3323 | } |
| 3324 | CloudCommand::Keys(keys) => match keys.command { |
| 3325 | CloudKeysCommand::List => { |
| 3326 | let user = client.me()?; |
| 3327 | let catalog = client.provider_catalog()?; |
| 3328 | write_account(out, "Codewhale account keys.", profile, api_base, &user)?; |
| 3329 | for row in &catalog { |
| 3330 | let stored = user.model_keys.get(&row.id); |
| 3331 | let status = match stored { |
| 3332 | Some(state) if state.configured => match state |
| 3333 | .state |
| 3334 | .as_deref() |
| 3335 | .map(printable) |
| 3336 | .filter(|value| !value.is_empty()) |
| 3337 | { |
| 3338 | Some(reported) => format!("set ({reported})"), |
| 3339 | None => "set".to_string(), |
| 3340 | }, |
| 3341 | _ => "not set".to_string(), |
| 3342 | }; |
| 3343 | writeln!(out, "{}: {status} — {}", row.id, row.display_label())?; |
| 3344 | } |
| 3345 | Ok(()) |
| 3346 | } |
| 3347 | CloudKeysCommand::Set(set) => { |
| 3348 | let provider = validate_provider_id(&set.provider)?; |
| 3349 | let user = client.me()?; |
| 3350 | let catalog = client.provider_catalog()?; |
| 3351 | let row = catalog_row(&catalog, &provider)?; |
| 3352 | let key = if set.from_local { |
| 3353 | let kind = row.local_kind().ok_or_else(|| { |
| 3354 | anyhow!( |
| 3355 | "`{provider}` has no local runtime provider, so there is no local key to copy. Use `--api-key-stdin` or the hidden prompt" |
| 3356 | ) |
| 3357 | })?; |
| 3358 | resolve_local_key(config, provider_secrets, kind)?.ok_or_else(|| { |
| 3359 | anyhow!( |
| 3360 | "No local {} API key was found in config, the secret store, or the environment", |
| 3361 | kind.as_str() |
| 3362 | ) |
| 3363 | })? |
| 3364 | } else if set.api_key_stdin { |
| 3365 | key_reader(KeyReadMode::Stdin)? |
| 3366 | } else { |
| 3367 | key_reader(KeyReadMode::HiddenPrompt(provider.clone()))? |
| 3368 | }; |
| 3369 | let key = key.trim().to_string(); |
| 3370 | validate_api_key(&key)?; |
| 3371 | let label = validate_label(&set.label)?; |
| 3372 | client.set_key(&provider, &key, &label)?; |
| 3373 | writeln!( |
| 3374 | out, |
| 3375 | "Saved {provider} for Codewhale account {} (profile {}).", |
| 3376 | printable(&user.id), |
| 3377 | printable(profile) |
| 3378 | )?; |
| 3379 | Ok(()) |
| 3380 | } |
| 3381 | CloudKeysCommand::Remove { provider } => { |
| 3382 | let provider = validate_provider_id(&provider)?; |
| 3383 | let user = client.me()?; |
| 3384 | let catalog = client.provider_catalog()?; |
| 3385 | let _ = catalog_row(&catalog, &provider)?; |
| 3386 | client.remove_key(&provider)?; |
| 3387 | writeln!( |
| 3388 | out, |
| 3389 | "Removed {provider} from Codewhale account {} (profile {}).", |
| 3390 | printable(&user.id), |
| 3391 | printable(profile) |
| 3392 | )?; |
| 3393 | Ok(()) |
| 3394 | } |
| 3395 | }, |
| 3396 | CloudCommand::Computers(computers) => { |
| 3397 | run_computers(computers.command, &client, machine, out) |
| 3398 | } |
| 3399 | CloudCommand::Session(args) => computer::run( |
| 3400 | args, |
| 3401 | &client, |
| 3402 | machine, |
| 3403 | out, |
| 3404 | key_reader, |
| 3405 | config, |
| 3406 | provider_secrets, |
| 3407 | ), |
| 3408 | CloudCommand::Projects(projects) => run_projects(projects.command, &client, machine, out), |
| 3409 | CloudCommand::Github(github) => run_github(github.command, &client, machine, out), |
| 3410 | CloudCommand::Agents(agents) => run_agents(agents.command, &client, machine, out), |
| 3411 | CloudCommand::ApiKeys(api_keys) => { |
| 3412 | machine::run_api_keys(api_keys, &client, machine, provider_secrets, out, sleeper) |
| 3413 | } |
| 3414 | CloudCommand::Whoami => match machine.resolve()? { |
| 3415 | // A present machine key wins and never falls back: silently |
| 3416 | // downgrading a machine credential to a human one is how CI ends |
| 3417 | // up running as the wrong identity. |
| 3418 | Some(key) => { |
| 3419 | let machine_client = machine::MachineClient::new(transport, key); |
| 3420 | let who = machine_client.whoami(sleeper)?; |
| 3421 | machine::write_whoami(out, &who, api_base, machine_client.key_head()) |
| 3422 | } |
| 3423 | None => { |
| 3424 | let user = client.me()?; |
| 3425 | write_account(out, "Signed in to Codewhale.", profile, api_base, &user) |
| 3426 | } |
| 3427 | }, |
| 3428 | CloudCommand::Agent => { |
| 3429 | // The agent route is machine-key-only by design, so CI and humans |
| 3430 | // never blur in an audit trail. There is no session fallback. |
| 3431 | let key = machine.require()?; |
| 3432 | let machine_client = machine::MachineClient::new(transport, key); |
| 3433 | let agent = machine_client.agent(sleeper)?.agent; |
| 3434 | machine::write_agent(out, &agent) |
| 3435 | } |
| 3436 | CloudCommand::Pull(args) => { |
| 3437 | if !args.dry_run { |
| 3438 | bail!( |
| 3439 | "Account settings import is not available yet; local config was not changed. Run `codewhale account pull --dry-run` to inspect the signed-in account." |
| 3440 | ); |
| 3441 | } |
| 3442 | let user = client.me()?; |
| 3443 | // `/api/me` currently exposes account identity and key metadata, |
| 3444 | // not a versioned settings document that can be applied locally. |
| 3445 | // Stay read-only and explicit until that import contract exists. |
| 3446 | writeln!(out, "Account settings (pull --dry-run):")?; |
| 3447 | writeln!(out, "Account ID: {}", printable(&user.id))?; |
| 3448 | writeln!(out, "Profile: {}", printable(profile))?; |
| 3449 | writeln!(out, "API: {api_base}")?; |
| 3450 | writeln!( |
| 3451 | out, |
| 3452 | "dry-run: remote settings import is not available; local config unchanged" |
| 3453 | )?; |
| 3454 | // Show the invariant: account session tokens stay in the private |
| 3455 | // Codewhale secrets file, never in config.toml. |
| 3456 | writeln!( |
| 3457 | out, |
| 3458 | "Secure custody: account session tokens stay in the private Codewhale secrets file, never in config.toml" |
| 3459 | )?; |
| 3460 | Ok(()) |
| 3461 | } |
| 3462 | CloudCommand::Push(args) => { |
| 3463 | let user = client.me()?; |
| 3464 | if !args.dry_run { |
| 3465 | bail!( |
| 3466 | "Push is never automatic; re-run with --dry-run to preview, then confirm explicitly" |
| 3467 | ); |
| 3468 | } |
| 3469 | writeln!(out, "Account settings (push --dry-run):")?; |
| 3470 | writeln!(out, "Account ID: {}", printable(&user.id))?; |
| 3471 | writeln!(out, "Profile: {}", printable(profile))?; |
| 3472 | writeln!(out, "API: {api_base}")?; |
| 3473 | writeln!( |
| 3474 | out, |
| 3475 | "dry-run: would PATCH /api/me/preferences with If-Match revision check (412 on conflict)" |
| 3476 | )?; |
| 3477 | writeln!( |
| 3478 | out, |
| 3479 | "No credentials, paths, or env are copied; only explicit fields (field-level last-writer-wins)" |
| 3480 | )?; |
| 3481 | Ok(()) |
| 3482 | } |
| 3483 | } |
| 3484 | } |
| 3485 | |
| 3486 | /// Resolve the account's configured agent route for a machine-key run. |
| 3487 | /// |
| 3488 | /// `codewhale review` hard-errors when a model resolves to several configured |
| 3489 | /// routes. When CI authenticates with a machine key, the account has already |
| 3490 | /// answered that question, so its configured provider is the disambiguator — |
| 3491 | /// no new flag, and no guess. Returns `None` when no machine key is set, which |
| 3492 | /// leaves the ordinary local resolution untouched. |
| 3493 | pub fn machine_review_provider() -> Result<Option<ProviderKind>> { |
| 3494 | let machine = machine::MachineKeyEnv::from_process_env(); |
| 3495 | let Some(key) = machine.resolve()? else { |
| 3496 | return Ok(None); |
| 3497 | }; |
| 3498 | let requested_base = machine::resolve_api_base( |
| 3499 | None, |
| 3500 | std::env::var(machine::MACHINE_API_BASE_ENV).ok().as_deref(), |
| 3501 | std::env::var(CLOUD_API_BASE_ENV).ok().as_deref(), |
| 3502 | DEFAULT_API_BASE, |
| 3503 | ); |
| 3504 | machine::require_secure_base(&requested_base)?; |
| 3505 | let api_base = validate_api_base(&requested_base)?; |
| 3506 | let transport = ReqwestTransport::new(api_base.url)?; |
| 3507 | let client = machine::MachineClient::new(&transport, key); |
| 3508 | // The call that actually needs a model is the call that refuses without |
| 3509 | // one, so this precondition runs before any review work starts. |
| 3510 | let agent = client.agent(&mut |duration| thread::sleep(duration))?.agent; |
| 3511 | machine::review_provider_from_agent(&agent).map(Some) |
| 3512 | } |
| 3513 | |
| 3514 | fn write_account<W: Write>( |
| 3515 | out: &mut W, |
| 3516 | heading: &str, |
| 3517 | profile: &str, |
| 3518 | api_base: &str, |
| 3519 | user: &CloudUser, |
| 3520 | ) -> Result<()> { |
| 3521 | writeln!(out, "{heading}")?; |
| 3522 | writeln!(out, "Account ID: {}", printable(&user.id))?; |
| 3523 | if !user.display_name.trim().is_empty() { |
| 3524 | writeln!(out, "Name: {}", printable(&user.display_name))?; |
| 3525 | } |
| 3526 | if !user.email.trim().is_empty() { |
| 3527 | writeln!(out, "Email: {}", printable(&user.email))?; |
| 3528 | } |
| 3529 | if !user.plan.trim().is_empty() { |
| 3530 | writeln!(out, "Plan: {}", printable(&user.plan))?; |
| 3531 | } |
| 3532 | writeln!(out, "Profile: {}", printable(profile))?; |
| 3533 | writeln!(out, "API: {api_base}")?; |
| 3534 | Ok(()) |
| 3535 | } |
| 3536 | |
| 3537 | struct ValidatedApiBase { |
| 3538 | url: Url, |
| 3539 | display: String, |
| 3540 | } |
| 3541 | |
| 3542 | fn validate_api_base(value: &str) -> Result<ValidatedApiBase> { |
| 3543 | let mut url = Url::parse(value.trim()).context("invalid Codewhale account API base URL")?; |
| 3544 | if !url.username().is_empty() || url.password().is_some() { |
| 3545 | bail!("Codewhale account API base URL must not contain credentials"); |
| 3546 | } |
| 3547 | if url.query().is_some() || url.fragment().is_some() { |
| 3548 | bail!("Codewhale account API base URL must not contain a query or fragment"); |
| 3549 | } |
| 3550 | if !matches!(url.path(), "" | "/") { |
| 3551 | bail!("Codewhale account API base URL must be an origin without a path"); |
| 3552 | } |
| 3553 | let host = url |
| 3554 | .host_str() |
| 3555 | .ok_or_else(|| anyhow!("Codewhale account API base URL must include a host"))?; |
| 3556 | let allowed = url.scheme() == "https" || (url.scheme() == "http" && is_loopback_host(host)); |
| 3557 | if !allowed { |
| 3558 | bail!( |
| 3559 | "Codewhale account API base URL must use HTTPS (loopback HTTP is allowed for testing)" |
| 3560 | ); |
| 3561 | } |
| 3562 | url.set_path("/"); |
| 3563 | let display = url.as_str().trim_end_matches('/').to_string(); |
| 3564 | Ok(ValidatedApiBase { url, display }) |
| 3565 | } |
| 3566 | |
| 3567 | fn validate_verification_url( |
| 3568 | value: &str, |
| 3569 | api_base: &str, |
| 3570 | user_code: &str, |
| 3571 | complete: bool, |
| 3572 | ) -> Result<String> { |
| 3573 | let url = |
| 3574 | Url::parse(value).context("The Codewhale service returned an invalid verification URL")?; |
| 3575 | if value != url.as_str() { |
| 3576 | bail!("The Codewhale service returned an unsafe verification URL"); |
| 3577 | } |
| 3578 | let host = url.host_str().ok_or_else(|| { |
| 3579 | anyhow!("The Codewhale service returned a verification URL without a host") |
| 3580 | })?; |
| 3581 | if !url.username().is_empty() || url.password().is_some() || url.fragment().is_some() { |
| 3582 | bail!("The Codewhale service returned an unsafe verification URL"); |
| 3583 | } |
| 3584 | if url.path() != "/cli/authorize" { |
| 3585 | bail!("The Codewhale service returned an unsafe verification URL"); |
| 3586 | } |
| 3587 | |
| 3588 | let api = Url::parse(api_base).context("invalid Codewhale account API base URL")?; |
| 3589 | let canonical_api = api.scheme() == "https" |
| 3590 | && api.host_str() == Some("api.codewhale.net") |
| 3591 | && api.port_or_known_default() == Some(443); |
| 3592 | let loopback_api = api.host_str().is_some_and(is_loopback_host); |
| 3593 | if canonical_api { |
| 3594 | if url.scheme() != "https" |
| 3595 | || !host.eq_ignore_ascii_case("app.codewhale.net") |
| 3596 | || url.port_or_known_default() != Some(443) |
| 3597 | { |
| 3598 | bail!("The Codewhale service returned an untrusted verification origin"); |
| 3599 | } |
| 3600 | } else if loopback_api { |
| 3601 | if !matches!(url.scheme(), "http" | "https") || !is_loopback_host(host) { |
| 3602 | bail!("The Codewhale service returned an untrusted verification origin"); |
| 3603 | } |
| 3604 | } else { |
| 3605 | bail!( |
| 3606 | "Browser login is only enabled for the canonical Codewhale account API or a loopback test API" |
| 3607 | ); |
| 3608 | } |
| 3609 | |
| 3610 | let query = url.query_pairs().collect::<Vec<_>>(); |
| 3611 | if complete { |
| 3612 | if query.len() != 1 || query[0].0 != "user_code" || query[0].1 != user_code { |
| 3613 | bail!("The Codewhale service returned an unsafe verification URL"); |
| 3614 | } |
| 3615 | } else if !query.is_empty() { |
| 3616 | bail!("The Codewhale service returned an unsafe verification URL"); |
| 3617 | } |
| 3618 | Ok(url.to_string()) |
| 3619 | } |
| 3620 | |
| 3621 | fn is_loopback_host(host: &str) -> bool { |
| 3622 | let host = host |
| 3623 | .strip_prefix('[') |
| 3624 | .and_then(|value| value.strip_suffix(']')) |
| 3625 | .unwrap_or(host); |
| 3626 | host.eq_ignore_ascii_case("localhost") |
| 3627 | || host |
| 3628 | .parse::<IpAddr>() |
| 3629 | .is_ok_and(|address| address.is_loopback()) |
| 3630 | } |
| 3631 | |
| 3632 | fn validate_user_code(code: &str) -> Result<()> { |
| 3633 | const ALPHABET: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; |
| 3634 | let bytes = code.as_bytes(); |
| 3635 | if bytes.len() != 14 |
| 3636 | || bytes[4] != b'-' |
| 3637 | || bytes[9] != b'-' |
| 3638 | || bytes |
| 3639 | .iter() |
| 3640 | .enumerate() |
| 3641 | .any(|(index, byte)| !matches!(index, 4 | 9) && !ALPHABET.contains(byte)) |
| 3642 | { |
| 3643 | bail!("The Codewhale service returned an invalid user code"); |
| 3644 | } |
| 3645 | Ok(()) |
| 3646 | } |
| 3647 | |
| 3648 | fn validate_device_code(code: &str) -> Result<()> { |
| 3649 | if code.len() != 43 |
| 3650 | || !code |
| 3651 | .bytes() |
| 3652 | .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_')) |
| 3653 | { |
| 3654 | bail!("The Codewhale service returned an invalid device authorization response"); |
| 3655 | } |
| 3656 | Ok(()) |
| 3657 | } |
| 3658 | |
| 3659 | fn validate_api_key(key: &str) -> Result<()> { |
| 3660 | let bytes = key.len(); |
| 3661 | if bytes < MIN_API_KEY_BYTES || bytes as u64 > MAX_API_KEY_BYTES { |
| 3662 | bail!("API key must be {MIN_API_KEY_BYTES}-{MAX_API_KEY_BYTES} UTF-8 bytes"); |
| 3663 | } |
| 3664 | if key.chars().any(is_ascii_control) { |
| 3665 | bail!("API key contains invalid control characters"); |
| 3666 | } |
| 3667 | Ok(()) |
| 3668 | } |
| 3669 | |
| 3670 | fn validate_label(label: &str) -> Result<String> { |
| 3671 | let label = label.split_whitespace().collect::<Vec<_>>().join(" "); |
| 3672 | if label.is_empty() |
| 3673 | || label.chars().count() > MAX_KEY_LABEL_CHARS |
| 3674 | || label.chars().any(is_ascii_control) |
| 3675 | { |
| 3676 | bail!("key label must contain 1-{MAX_KEY_LABEL_CHARS} characters"); |
| 3677 | } |
| 3678 | Ok(label) |
| 3679 | } |
| 3680 | |
| 3681 | fn is_ascii_control(character: char) -> bool { |
| 3682 | character <= '\u{001f}' || character == '\u{007f}' |
| 3683 | } |
| 3684 | |
| 3685 | /// Find one catalog row by id, or fail naming what the account does offer. |
| 3686 | /// |
| 3687 | /// A catalog miss is the common typo, so the message lists the ids rather than |
| 3688 | /// leaving the user to guess or read a 404. |
| 3689 | fn catalog_row<'a>(catalog: &'a [CatalogProvider], provider: &str) -> Result<&'a CatalogProvider> { |
| 3690 | catalog |
| 3691 | .iter() |
| 3692 | .find(|row| row.id == provider) |
| 3693 | .ok_or_else(|| { |
| 3694 | let known = catalog |
| 3695 | .iter() |
| 3696 | .map(|row| row.id.as_str()) |
| 3697 | .collect::<Vec<_>>() |
| 3698 | .join(", "); |
| 3699 | anyhow!("`{provider}` is not a provider this Codewhale account can connect. Known providers: {known}") |
| 3700 | }) |
| 3701 | } |
| 3702 | |
| 3703 | fn resolve_local_key( |
| 3704 | config: &ConfigStore, |
| 3705 | secrets: &Secrets, |
| 3706 | kind: ProviderKind, |
| 3707 | ) -> Result<Option<String>> { |
| 3708 | let provider_config = config.config.providers.for_provider(kind); |
| 3709 | let from_config = provider_config.api_key.clone(); |
| 3710 | if let Some(value) = from_config |
| 3711 | .and_then(resolve_config_key_reference) |
| 3712 | .filter(|value| !value.trim().is_empty()) |
| 3713 | { |
| 3714 | return Ok(Some(value)); |
| 3715 | } |
| 3716 | if let Some(value) = secrets |
| 3717 | .get(kind.as_str()) |
| 3718 | .context("failed to read the local provider secret store")? |
| 3719 | .filter(|value| !value.trim().is_empty()) |
| 3720 | { |
| 3721 | return Ok(Some(value)); |
| 3722 | } |
| 3723 | Ok(kind.provider().env_vars().iter().find_map(|name| { |
| 3724 | std::env::var(name) |
| 3725 | .ok() |
| 3726 | .filter(|value| !value.trim().is_empty()) |
| 3727 | })) |
| 3728 | } |
| 3729 | |
| 3730 | fn resolve_config_key_reference(value: String) -> Option<String> { |
| 3731 | let trimmed = value.trim(); |
| 3732 | let Some(variable) = trimmed.strip_prefix('$') else { |
| 3733 | return Some(value); |
| 3734 | }; |
| 3735 | if variable.is_empty() |
| 3736 | || !variable |
| 3737 | .bytes() |
| 3738 | .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_') |
| 3739 | { |
| 3740 | return None; |
| 3741 | } |
| 3742 | std::env::var(variable) |
| 3743 | .ok() |
| 3744 | .filter(|value| !value.trim().is_empty()) |
| 3745 | } |
| 3746 | |
| 3747 | fn read_key_from_stdin() -> Result<String> { |
| 3748 | let mut bytes = Vec::new(); |
| 3749 | io::stdin() |
| 3750 | .take(MAX_API_KEY_STDIN_BYTES + 1) |
| 3751 | .read_to_end(&mut bytes) |
| 3752 | .context("failed to read API key from stdin")?; |
| 3753 | parse_key_input(bytes) |
| 3754 | } |
| 3755 | |
| 3756 | fn parse_key_input(bytes: Vec<u8>) -> Result<String> { |
| 3757 | if bytes.len() as u64 > MAX_API_KEY_STDIN_BYTES { |
| 3758 | bail!("API key input is unexpectedly large"); |
| 3759 | } |
| 3760 | let value = String::from_utf8(bytes).context("API key from stdin is not valid UTF-8")?; |
| 3761 | let value = value.trim().to_string(); |
| 3762 | validate_api_key(&value)?; |
| 3763 | Ok(value) |
| 3764 | } |
| 3765 | |
| 3766 | fn read_key_hidden(provider: &str) -> Result<String> { |
| 3767 | if !io::stdin().is_terminal() { |
| 3768 | bail!("interactive key entry requires a terminal; use `--api-key-stdin` for piped input"); |
| 3769 | } |
| 3770 | let term = console::Term::stderr(); |
| 3771 | term.write_str(&format!("Enter {provider} API key: ")) |
| 3772 | .context("failed to write API key prompt")?; |
| 3773 | let value = term |
| 3774 | .read_secure_line() |
| 3775 | .context("failed to read API key securely")?; |
| 3776 | term.write_line("").ok(); |
| 3777 | let value = value.trim().to_string(); |
| 3778 | validate_api_key(&value)?; |
| 3779 | Ok(value) |
| 3780 | } |
| 3781 | |
| 3782 | fn json_body(value: &impl Serialize) -> Result<Vec<u8>> { |
| 3783 | serde_json::to_vec(value).context("failed to encode Codewhale account request") |
| 3784 | } |
| 3785 | |
| 3786 | fn expect_json<T: DeserializeOwned>(response: CloudResponse, statuses: &[u16]) -> Result<T> { |
| 3787 | if !statuses.contains(&response.status) { |
| 3788 | return Err(response_error(&response)); |
| 3789 | } |
| 3790 | parse_json_body(&response.body) |
| 3791 | } |
| 3792 | |
| 3793 | fn expect_empty(response: CloudResponse, statuses: &[u16]) -> Result<()> { |
| 3794 | if statuses.contains(&response.status) { |
| 3795 | Ok(()) |
| 3796 | } else { |
| 3797 | Err(response_error(&response)) |
| 3798 | } |
| 3799 | } |
| 3800 | |
| 3801 | fn parse_json_body<T: DeserializeOwned>(body: &[u8]) -> Result<T> { |
| 3802 | serde_json::from_slice(body).context("The Codewhale service returned an invalid JSON response") |
| 3803 | } |
| 3804 | |
| 3805 | /// A non-success reply from the account API, kept typed so a caller can tell a |
| 3806 | /// definitive refusal (4xx) from an outcome it cannot know (5xx, timeout). |
| 3807 | #[derive(Debug)] |
| 3808 | pub(crate) struct CloudHttpError { |
| 3809 | status: u16, |
| 3810 | code: Option<String>, |
| 3811 | reconciliation_required: bool, |
| 3812 | } |
| 3813 | |
| 3814 | impl CloudHttpError { |
| 3815 | fn code(&self) -> Option<&str> { |
| 3816 | self.code.as_deref() |
| 3817 | } |
| 3818 | } |
| 3819 | |
| 3820 | impl std::fmt::Display for CloudHttpError { |
| 3821 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 3822 | match self.code.as_deref().and_then(neutral_error_text) { |
| 3823 | Some(text) => write!( |
| 3824 | f, |
| 3825 | "Codewhale account request failed (HTTP {}): {text}", |
| 3826 | self.status |
| 3827 | ), |
| 3828 | None => match self.code.as_deref().filter(|code| !is_vendor_code(code)) { |
| 3829 | Some(code) => write!( |
| 3830 | f, |
| 3831 | "Codewhale account request failed (HTTP {}, code {code})", |
| 3832 | self.status |
| 3833 | ), |
| 3834 | None => write!(f, "Codewhale account request failed (HTTP {})", self.status), |
| 3835 | }, |
| 3836 | } |
| 3837 | } |
| 3838 | } |
| 3839 | |
| 3840 | pub(crate) fn vendor_safe_prose(text: String) -> String { |
| 3841 | if is_vendor_code(&text) { |
| 3842 | "The cloud service reported an unrecognised condition".to_string() |
| 3843 | } else { |
| 3844 | text |
| 3845 | } |
| 3846 | } |
| 3847 | |
| 3848 | fn is_vendor_code(code: &str) -> bool { |
| 3849 | code.split(|c: char| !c.is_ascii_alphanumeric()) |
| 3850 | .any(|token| { |
| 3851 | matches!( |
| 3852 | token.to_ascii_lowercase().as_str(), |
| 3853 | "boat" | "daytona" | "sprite" | "sprites" | "agentbay" | "alibaba" |
| 3854 | ) |
| 3855 | }) |
| 3856 | } |
| 3857 | |
| 3858 | fn neutral_error_text(code: &str) -> Option<&'static str> { |
| 3859 | Some(match code { |
| 3860 | "boat_task_replay_expired" | "work_task_replay_expired" => { |
| 3861 | "The earlier request can no longer be replayed and needs operator reconciliation" |
| 3862 | } |
| 3863 | "boat_task_create_in_progress" | "work_task_create_in_progress" => { |
| 3864 | "The cloud computer is still being created" |
| 3865 | } |
| 3866 | "boat_task_cleanup_pending" | "work_task_cleanup_pending" => { |
| 3867 | "The cloud computer is still being cleaned up" |
| 3868 | } |
| 3869 | "boat_task_receipt_invalid" | "work_task_receipt_invalid" => { |
| 3870 | "The cloud computer's receipt could not be verified" |
| 3871 | } |
| 3872 | "boat_task_authority_changed" | "work_task_authority_changed" => { |
| 3873 | "Your account authority changed while the cloud computer was starting" |
| 3874 | } |
| 3875 | "boat_task_stop_unconfirmed" | "work_task_stop_unconfirmed" => { |
| 3876 | "The cloud computer stopped but its state is unconfirmed" |
| 3877 | } |
| 3878 | "boat_task_usage_pending" | "work_task_usage_pending" => { |
| 3879 | "Usage for the cloud computer is still being finalized" |
| 3880 | } |
| 3881 | "boat_task_outcome_unknown" | "work_task_outcome_unknown" => { |
| 3882 | "The cloud computer outcome is unknown" |
| 3883 | } |
| 3884 | _ => return None, |
| 3885 | }) |
| 3886 | } |
| 3887 | |
| 3888 | pub(crate) fn display_error_code(code: &str) -> String { |
| 3889 | match neutral_error_text(code) { |
| 3890 | Some(text) => text.to_string(), |
| 3891 | None if is_vendor_code(code) => "unrecognised cloud error".to_string(), |
| 3892 | None => code.to_string(), |
| 3893 | } |
| 3894 | } |
| 3895 | |
| 3896 | impl std::error::Error for CloudHttpError {} |
| 3897 | |
| 3898 | /// The request may or may not have been processed: it never reached the |
| 3899 | /// service, or its reply was lost or unreadable. Mutating commands use this to |
| 3900 | /// say "unknown" instead of guessing "failed". |
| 3901 | #[derive(Debug)] |
| 3902 | pub(crate) struct CloudTransportError { |
| 3903 | message: &'static str, |
| 3904 | source: Box<dyn std::error::Error + Send + Sync + 'static>, |
| 3905 | } |
| 3906 | |
| 3907 | impl CloudTransportError { |
| 3908 | fn new(message: &'static str, source: impl std::error::Error + Send + Sync + 'static) -> Self { |
| 3909 | Self { |
| 3910 | message, |
| 3911 | source: Box::new(source), |
| 3912 | } |
| 3913 | } |
| 3914 | } |
| 3915 | |
| 3916 | impl std::fmt::Display for CloudTransportError { |
| 3917 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 3918 | f.write_str(self.message) |
| 3919 | } |
| 3920 | } |
| 3921 | |
| 3922 | impl std::error::Error for CloudTransportError { |
| 3923 | fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { |
| 3924 | Some(self.source.as_ref()) |
| 3925 | } |
| 3926 | } |
| 3927 | |
| 3928 | /// Whether a failed mutating request may still have taken effect. |
| 3929 | fn outcome_unknown(err: &anyhow::Error) -> bool { |
| 3930 | err.downcast_ref::<CloudTransportError>().is_some() |
| 3931 | || err.downcast_ref::<CloudHttpError>().is_some_and(|http| { |
| 3932 | http.status >= 500 |
| 3933 | || http.status == 408 |
| 3934 | || http.reconciliation_required |
| 3935 | || http.code().is_some_and(|code| { |
| 3936 | code.ends_with("_outcome_unknown") |
| 3937 | || matches!( |
| 3938 | code, |
| 3939 | "boat_task_replay_expired" |
| 3940 | | "boat_task_create_in_progress" |
| 3941 | | "boat_task_cleanup_pending" |
| 3942 | | "boat_task_receipt_invalid" |
| 3943 | | "boat_task_authority_changed" |
| 3944 | | "boat_task_stop_unconfirmed" |
| 3945 | | "boat_task_usage_pending" |
| 3946 | ) |
| 3947 | }) |
| 3948 | }) |
| 3949 | } |
| 3950 | |
| 3951 | fn response_error(response: &CloudResponse) -> anyhow::Error { |
| 3952 | let body = serde_json::from_slice::<serde_json::Value>(&response.body).ok(); |
| 3953 | let code = body.as_ref().and_then(|body| { |
| 3954 | body.get("code") |
| 3955 | .and_then(serde_json::Value::as_str) |
| 3956 | .or_else(|| { |
| 3957 | body.get("error") |
| 3958 | .and_then(|error| error.get("code")) |
| 3959 | .and_then(serde_json::Value::as_str) |
| 3960 | }) |
| 3961 | .and_then(safe_error_code) |
| 3962 | }); |
| 3963 | let reconciliation_required = body.as_ref().is_some_and(|body| { |
| 3964 | body.get("reconciliationRequired") |
| 3965 | .or_else(|| { |
| 3966 | body.get("error") |
| 3967 | .and_then(|error| error.get("reconciliationRequired")) |
| 3968 | }) |
| 3969 | .and_then(serde_json::Value::as_bool) |
| 3970 | == Some(true) |
| 3971 | }); |
| 3972 | anyhow::Error::new(CloudHttpError { |
| 3973 | status: response.status, |
| 3974 | code, |
| 3975 | reconciliation_required, |
| 3976 | }) |
| 3977 | } |
| 3978 | |
| 3979 | fn safe_error_code(code: &str) -> Option<String> { |
| 3980 | if code.is_empty() |
| 3981 | || code.len() > 80 |
| 3982 | || !code |
| 3983 | .bytes() |
| 3984 | .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.')) |
| 3985 | { |
| 3986 | return None; |
| 3987 | } |
| 3988 | Some(code.to_string()) |
| 3989 | } |
| 3990 | |
| 3991 | fn printable(value: &str) -> String { |
| 3992 | printable_max(value, 200) |
| 3993 | } |
| 3994 | |
| 3995 | /// `printable` with a caller-chosen bound, for remote prose longer than a label. |
| 3996 | fn printable_max(value: &str, max_chars: usize) -> String { |
| 3997 | value |
| 3998 | .chars() |
| 3999 | .filter(|character| !character.is_control()) |
| 4000 | .take(max_chars) |
| 4001 | .collect::<String>() |
| 4002 | .trim() |
| 4003 | .to_string() |
| 4004 | } |
| 4005 | |
| 4006 | #[cfg(test)] |
| 4007 | mod tests; |
| 4008 | |
| 4009 | #[cfg(test)] |
| 4010 | mod sign_in_gate_tests { |
| 4011 | use super::*; |
| 4012 | |
| 4013 | fn login() -> CloudCommand { |
| 4014 | CloudCommand::Login(CloudLoginArgs { |
| 4015 | no_open: true, |
| 4016 | timeout_seconds: 1, |
| 4017 | }) |
| 4018 | } |
| 4019 | |
| 4020 | #[test] |
| 4021 | fn account_sign_in_defaults_to_hidden_with_one_plain_sentence() { |
| 4022 | const { assert!(!ACCOUNT_SIGN_IN_OPEN) }; |
| 4023 | let english = codewhale_localization::tr( |
| 4024 | codewhale_localization::Locale::En, |
| 4025 | codewhale_localization::MessageId::AccountSignInClosed, |
| 4026 | ); |
| 4027 | assert!(english.contains("not open yet")); |
| 4028 | assert!(english.contains("/provider")); |
| 4029 | } |
| 4030 | |
| 4031 | #[test] |
| 4032 | fn closed_accounts_refuse_only_a_new_sign_in() { |
| 4033 | assert!(account_command_is_closed(false, &login())); |
| 4034 | for command in [ |
| 4035 | CloudCommand::Status, |
| 4036 | CloudCommand::Whoami, |
| 4037 | CloudCommand::Logout, |
| 4038 | ] { |
| 4039 | assert!(!account_command_is_closed(false, &command)); |
| 4040 | } |
| 4041 | assert!(!account_command_is_closed(true, &login())); |
| 4042 | } |
| 4043 | |
| 4044 | #[test] |
| 4045 | fn closed_login_fails_before_any_network_or_browser_work() { |
| 4046 | let dir = tempfile::tempdir().expect("tempdir"); |
| 4047 | let mut config = |
| 4048 | ConfigStore::load(Some(dir.path().join("config.toml"))).expect("config should load"); |
| 4049 | let error = run_account_login(true, 1, None, &mut config) |
| 4050 | .expect_err("sign-in is closed until accounts open"); |
| 4051 | assert_eq!(error.to_string(), account_sign_in_closed_message()); |
| 4052 | } |
| 4053 | } |
| 4054 |