diff --git a/.github/workflows/goose-bot-switchboard.yml b/.github/workflows/goose-bot-switchboard.yml new file mode 100644 index 000000000000..f84a15e9d029 --- /dev/null +++ b/.github/workflows/goose-bot-switchboard.yml @@ -0,0 +1,44 @@ +name: GooseBot Switchboard CI + +on: + push: + branches: [main] + paths: + - "services/goose-bot-switchboard/**" + - ".github/workflows/goose-bot-switchboard.yml" + pull_request: + branches: [main] + paths: + - "services/goose-bot-switchboard/**" + - ".github/workflows/goose-bot-switchboard.yml" + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +defaults: + run: + working-directory: services/goose-bot-switchboard + +jobs: + test: + name: Typecheck & test + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - uses: pnpm/action-setup@8912a9102ac27614460f54aedde9e1e7f9aec20d # v6.0.5 + with: + version: 10.30.3 + + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version: 24 + cache: pnpm + cache-dependency-path: services/goose-bot-switchboard/pnpm-lock.yaml + + - run: pnpm install --frozen-lockfile + - run: pnpm typecheck + - run: pnpm test diff --git a/.gitignore b/.gitignore index b82cf5c75309..899890963075 100644 --- a/.gitignore +++ b/.gitignore @@ -61,6 +61,9 @@ do_not_version/ /ui/desktop/src/bin/goose-scheduler-executor /ui/desktop/src/bin/goose /.env +**/.env +!**/.env.example +**/*.pem /working_dir diff --git a/crates/goose-cli/src/commands/review/orchestrator.rs b/crates/goose-cli/src/commands/review/orchestrator.rs index 151bd181f33a..f8025acf532f 100644 --- a/crates/goose-cli/src/commands/review/orchestrator.rs +++ b/crates/goose-cli/src/commands/review/orchestrator.rs @@ -55,6 +55,11 @@ pub struct Finding { pub line_end: i64, pub summary: String, pub check: String, + /// Optional concrete fix: the exact line(s) that should replace + /// `path:line_start..line_end`. Consumers (e.g. PR-review bots) can + /// render this as a GitHub ```suggestion block. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub suggestion: Option, } /// Schema the check subprocess is required to emit. @@ -75,6 +80,8 @@ struct RawFinding { line_end: Option, #[serde(default)] summary: Option, + #[serde(default)] + suggestion: Option, } /// Run all discovered checks concurrently as `goose run` subprocesses. @@ -217,6 +224,7 @@ async fn run_single_check_subprocess( line_end: r.line_end.unwrap_or(0), summary: r.summary.unwrap_or_default(), check: check.name.clone(), + suggestion: r.suggestion.filter(|s| !s.trim().is_empty()), }) .collect()) } @@ -370,6 +378,7 @@ pub async fn run_main_pass_in_parallel( line_end: r.line_end.unwrap_or(0), summary: r.summary.unwrap_or_default(), check: "main".to_string(), + suggestion: r.suggestion.filter(|s| !s.trim().is_empty()), }) .collect(); if !quiet { @@ -617,7 +626,7 @@ fn build_main_pass_prompt( ); s.push_str( "## Output\n\nReturn ONLY valid JSON with this exact schema:\n\n\ -{\n \"findings\": [\n {\n \"severity\": \"low|medium|high|critical\",\n \"path\": \"relative/path/to/file\",\n \"line_start\": 10,\n \"line_end\": 12,\n \"summary\": \"One-paragraph actionable explanation of the issue and the fix\"\n }\n ]\n}\n\nIf there are no real issues, return:\n{\"findings\":[]}\n\nDo NOT include any text before or after the JSON. Do NOT wrap the JSON in code fences.\n\n", +{\n \"findings\": [\n {\n \"severity\": \"low|medium|high|critical\",\n \"path\": \"relative/path/to/file\",\n \"line_start\": 10,\n \"line_end\": 12,\n \"summary\": \"One-paragraph actionable explanation of the issue and the fix\",\n \"suggestion\": \"the exact line(s) that should replace path:line_start..line_end — no leading +/-, no surrounding context. Omit this field when you don't have a single concrete replacement (e.g. the fix spans multiple non-contiguous locations or requires structural changes).\"\n }\n ]\n}\n\nIf there are no real issues, return:\n{\"findings\":[]}\n\nDo NOT include any text before or after the JSON. Do NOT wrap the JSON in code fences.\n\n", ); s.push_str("## Diff\n\n```diff\n"); s.push_str(file_diff.trim_end_matches('\n')); @@ -674,7 +683,7 @@ fn build_check_prompt( s.push_str("Do NOT report issues for unchanged/pre-existing code shown for context.\n\n"); s.push_str( "Return ONLY valid JSON with this exact schema:\n\ -{\n \"findings\": [\n {\n \"severity\": \"low|medium|high|critical\",\n \"path\": \"relative/path/to/file\",\n \"line_start\": 10,\n \"line_end\": 12,\n \"summary\": \"One-sentence actionable issue\"\n }\n ]\n}\n\nIf there are no issues, return:\n{\"findings\":[]}\n\nDo NOT include any text before or after the JSON. Do NOT wrap the JSON in code fences.\n\n", +{\n \"findings\": [\n {\n \"severity\": \"low|medium|high|critical\",\n \"path\": \"relative/path/to/file\",\n \"line_start\": 10,\n \"line_end\": 12,\n \"summary\": \"One-sentence actionable issue\",\n \"suggestion\": \"the exact line(s) that should replace path:line_start..line_end — no leading +/-, no surrounding context. Omit when no single concrete replacement applies.\"\n }\n ]\n}\n\nIf there are no issues, return:\n{\"findings\":[]}\n\nDo NOT include any text before or after the JSON. Do NOT wrap the JSON in code fences.\n\n", ); s.push_str("Check instructions:\n\n"); s.push_str(check.body.trim()); diff --git a/crates/goose-server/src/openapi.rs b/crates/goose-server/src/openapi.rs index f2b4d832afc6..931ea843ada0 100644 --- a/crates/goose-server/src/openapi.rs +++ b/crates/goose-server/src/openapi.rs @@ -479,6 +479,15 @@ derive_utoipa!(IconTheme as IconThemeSchema); super::routes::tunnel::start_tunnel, super::routes::tunnel::stop_tunnel, super::routes::tunnel::get_tunnel_status, + super::routes::goose_bot::review, + super::routes::goose_bot::setup, + super::routes::goose_bot::disconnect, + super::routes::goose_bot::get_status, + super::routes::goose_bot::comment, + super::routes::goose_bot::get_prefs, + super::routes::goose_bot::put_prefs, + super::routes::goose_bot::get_repos, + super::routes::goose_bot::get_analytics, super::routes::telemetry::send_telemetry_event, super::routes::dictation::transcribe_dictation, super::routes::dictation::get_dictation_config, @@ -658,6 +667,25 @@ derive_utoipa!(IconTheme as IconThemeSchema); super::routes::setup::SetupResponse, super::tunnel::TunnelInfo, super::tunnel::TunnelState, + goose::goose_bot::GooseBotReviewRequest, + goose::goose_bot::GooseBotReviewResponse, + goose::goose_bot::GooseBotSetupResponse, + goose::goose_bot::GooseBotStatusResponse, + goose::goose_bot::GooseBotDisconnectResponse, + goose::goose_bot::GooseBotCommentRequest, + goose::goose_bot::GooseBotPrefsRequest, + goose::goose_bot::GooseBotPrefsResponse, + goose::goose_bot::GooseBotPrefs, + goose::goose_bot::RoutingPrefs, + goose::goose_bot::TriggerPreference, + goose::goose_bot::TriggerPermission, + goose::goose_bot::ReviewOutputStyle, + goose::goose_bot::ReviewModelChoice, + goose::goose_bot::ReviewSeverity, + goose::goose_bot::GooseBotRepo, + goose::goose_bot::GooseBotReposResponse, + goose::goose_bot::RepoVisibility, + goose::goose_bot::GooseBotAnalytics, super::routes::telemetry::TelemetryEventRequest, goose::goose_apps::GooseApp, goose::goose_apps::WindowProps, diff --git a/crates/goose-server/src/routes/goose_bot.rs b/crates/goose-server/src/routes/goose_bot.rs new file mode 100644 index 000000000000..daeba7826423 --- /dev/null +++ b/crates/goose-server/src/routes/goose_bot.rs @@ -0,0 +1,365 @@ +//! GooseBot HTTP routes - thin handlers over `goose::goose_bot`. + +use std::{sync::Arc, time::Duration}; + +use axum::{ + extract::State, + http::StatusCode, + response::Json, + routing::{get, post}, + Router, +}; +use goose::config::signup_goose_bot::GooseBotInstallFlow; +use goose::config::Config; +use goose::goose_bot::{ + cached_installation_id, disconnect_install, extract_agent_id, fetch_analytics, + fetch_oauth_client_id, fetch_repos, forward_routing_prefs, load_prefs, register_installation, + replace_comment_reaction, report_analytics_event, resolve_install_credentials, + run_comment_reply, run_review, save_prefs, AnalyticsEvent, GooseBotAnalytics, + GooseBotCommentRequest, GooseBotDisconnectResponse, GooseBotPrefs, GooseBotPrefsRequest, + GooseBotPrefsResponse, GooseBotReposResponse, GooseBotReviewRequest, GooseBotReviewResponse, + GooseBotSetupResponse, GooseBotStatusResponse, InstallCredentials, RegisterInstallRequest, + TunnelSnapshot, INSTALLATION_ID_CONFIG_KEY, +}; +use tokio::time::sleep; + +use crate::routes::errors::ErrorResponse; +use crate::state::AppState; + +const TUNNEL_READY_ATTEMPTS: usize = 20; +const TUNNEL_READY_DELAY: Duration = Duration::from_millis(500); + +async fn tunnel_snapshot(state: &AppState) -> TunnelSnapshot { + let info = state.tunnel_manager.get_info().await; + TunnelSnapshot { + url: info.url, + secret: info.secret, + } +} + +async fn wait_for_tunnel_ready(url: &str, secret: &str) -> Result<(), ErrorResponse> { + let endpoint = format!("{}/goose-bot/status", url.trim_end_matches('/')); + let client = reqwest::Client::new(); + let mut last_error = "tunnel status probe did not run".to_string(); + + for attempt in 0..TUNNEL_READY_ATTEMPTS { + match client + .get(&endpoint) + .header("X-Secret-Key", secret) + .send() + .await + { + Ok(res) if res.status().is_success() => return Ok(()), + Ok(res) => { + last_error = format!("tunnel status returned {}", res.status()); + } + Err(e) => { + last_error = format!("tunnel status probe failed: {e}"); + } + } + + if attempt + 1 < TUNNEL_READY_ATTEMPTS { + sleep(TUNNEL_READY_DELAY).await; + } + } + + Err(ErrorResponse::internal(format!( + "tunnel did not become reachable: {last_error}" + ))) +} + +fn app_not_installed_error(message: &str) -> bool { + message.contains("not installed on any account") +} + +#[utoipa::path( + post, + path = "/goose-bot/setup", + responses( + (status = 200, description = "Goose Bot connected", body = GooseBotSetupResponse), + (status = 409, description = "GitHub App is not installed"), + (status = 408, description = "Install timed out"), + (status = 500, description = "Internal error"), + ), + tag = "goose_bot" +)] +#[axum::debug_handler] +async fn setup( + State(state): State>, +) -> Result, ErrorResponse> { + let oauth_client_id = fetch_oauth_client_id() + .await + .map_err(|e| ErrorResponse::internal(format!("oauth-config lookup failed: {e}")))?; + + let mut flow = GooseBotInstallFlow::new().with_oauth_client_id(oauth_client_id); + let callback = flow + .complete_flow() + .await + .map_err(|e| ErrorResponse::internal(e.to_string()))?; + + let tunnel_info = state.tunnel_manager.get_info().await; + if tunnel_info.state != crate::tunnel::TunnelState::Running { + state + .tunnel_manager + .start() + .await + .map_err(|e| ErrorResponse::internal(format!("tunnel start failed: {e}")))?; + } + let tunnel_info = state.tunnel_manager.get_info().await; + let agent_id = extract_agent_id(&tunnel_info.url) + .ok_or_else(|| ErrorResponse::internal("tunnel URL is missing the agent id".to_string()))?; + let tunnel_secret = tunnel_info.secret.clone(); + + wait_for_tunnel_ready(&tunnel_info.url, &tunnel_secret).await?; + + let installation_id = register_installation(RegisterInstallRequest { + oauth_code: callback.oauth_code, + agent_id, + tunnel_secret: tunnel_secret.clone(), + tunnel_url: tunnel_info.url.clone(), + }) + .await + .map_err(|e| { + let message = e.to_string(); + if app_not_installed_error(&message) { + flow.open_app_install_url(); + ErrorResponse { + message: "Goose Bot GitHub App is not installed yet. Install it in the browser window that just opened, then retry Connect GitHub.".to_string(), + status: StatusCode::CONFLICT, + } + } else { + ErrorResponse::internal(message) + } + })?; + + let _ = Config::global().set_param( + INSTALLATION_ID_CONFIG_KEY, + serde_json::json!(installation_id), + ); + let creds = InstallCredentials { + installation_id, + tunnel_secret, + }; + let _ = forward_routing_prefs(&creds, &load_prefs().routing_subset()).await; + + Ok(Json(GooseBotSetupResponse { installation_id })) +} + +#[utoipa::path( + get, + path = "/goose-bot/status", + responses( + (status = 200, description = "Cached GitHub App installation id", body = GooseBotStatusResponse), + ), + tag = "goose_bot" +)] +#[axum::debug_handler] +async fn get_status() -> Json { + Json(GooseBotStatusResponse { + installation_id: cached_installation_id(Config::global()), + }) +} + +#[utoipa::path( + delete, + path = "/goose-bot/setup", + responses( + (status = 200, description = "Local install cleared and switchboard registration removed", body = GooseBotDisconnectResponse), + (status = 500, description = "Internal error"), + ), + tag = "goose_bot" +)] +#[axum::debug_handler] +async fn disconnect( + State(state): State>, +) -> Result, ErrorResponse> { + disconnect_install(tunnel_snapshot(&state).await) + .await + .map_err(|e| ErrorResponse::internal(e.to_string()))?; + Ok(Json(GooseBotDisconnectResponse { disconnected: true })) +} + +#[utoipa::path( + post, + path = "/goose-bot/review", + request_body = GooseBotReviewRequest, + responses( + (status = 200, description = "Review accepted, running in background", body = GooseBotReviewResponse), + (status = 500, description = "Internal error"), + ), + tag = "goose_bot" +)] +#[axum::debug_handler] +async fn review( + State(state): State>, + Json(req): Json, +) -> Result, ErrorResponse> { + let pr_label = format!("{} #{}", req.repo, req.pr_number); + let tunnel = tunnel_snapshot(&state).await; + tokio::spawn(async move { + let result = run_review(req.clone()).await; + match &result { + Ok(_) => report_analytics_event(tunnel, AnalyticsEvent::PrReviewed).await, + Err(e) => tracing::error!("[goose_bot] review {} failed: {:#}", pr_label, e), + } + if let Some(id) = req.comment_id { + let reaction = if result.is_ok() { "+1" } else { "confused" }; + let _ = replace_comment_reaction(&req.repo, id, reaction, &req.github_token).await; + } + }); + Ok(Json(GooseBotReviewResponse { accepted: true })) +} + +#[utoipa::path( + post, + path = "/goose-bot/comment", + request_body = GooseBotCommentRequest, + responses( + (status = 200, description = "Comment accepted, replying in background", body = GooseBotReviewResponse), + (status = 500, description = "Internal error"), + ), + tag = "goose_bot" +)] +#[axum::debug_handler] +async fn comment( + State(state): State>, + Json(req): Json, +) -> Result, ErrorResponse> { + let pr_label = format!("{} #{}", req.repo, req.pr_number); + let tunnel = tunnel_snapshot(&state).await; + tokio::spawn(async move { + let result = run_comment_reply(req.clone()).await; + match &result { + Ok(commit_pushed) => { + if !req.is_pr { + report_analytics_event(tunnel.clone(), AnalyticsEvent::IssueHandled).await; + } + if *commit_pushed { + report_analytics_event(tunnel, AnalyticsEvent::CommitPushed).await; + } + } + Err(e) => tracing::error!("[goose_bot] comment {} failed: {:#}", pr_label, e), + } + if let Some(id) = req.comment_id { + let reaction = if result.is_ok() { "+1" } else { "confused" }; + let _ = replace_comment_reaction(&req.repo, id, reaction, &req.github_token).await; + } + }); + Ok(Json(GooseBotReviewResponse { accepted: true })) +} + +#[utoipa::path( + get, + path = "/goose-bot/prefs", + responses( + (status = 200, description = "Current Goose Bot preferences", body = GooseBotPrefs), + (status = 500, description = "Internal error"), + ), + tag = "goose_bot" +)] +#[axum::debug_handler] +async fn get_prefs() -> Result, ErrorResponse> { + Ok(Json(load_prefs())) +} + +#[utoipa::path( + put, + path = "/goose-bot/prefs", + request_body = GooseBotPrefsRequest, + responses( + (status = 200, description = "Preferences saved", body = GooseBotPrefsResponse), + (status = 400, description = "Validation error"), + (status = 500, description = "Internal error"), + ), + tag = "goose_bot" +)] +#[axum::debug_handler] +async fn put_prefs( + State(state): State>, + Json(req): Json, +) -> Result, ErrorResponse> { + req.prefs + .validate() + .map_err(|e| ErrorResponse::bad_request(e.to_string()))?; + + save_prefs(&req.prefs).map_err(|e| ErrorResponse::internal(e.to_string()))?; + + let (switchboard_synced, switchboard_error) = + match resolve_install_credentials(tunnel_snapshot(&state).await).await { + Ok(creds) => match forward_routing_prefs(&creds, &req.prefs.routing_subset()).await { + Ok(()) => (true, None), + Err(e) => (false, Some(e.to_string())), + }, + Err(e) => (false, Some(e.to_string())), + }; + + Ok(Json(GooseBotPrefsResponse { + prefs: req.prefs, + switchboard_synced, + switchboard_error, + })) +} + +#[utoipa::path( + get, + path = "/goose-bot/repos", + responses( + (status = 200, description = "Repos accessible to the installation", body = GooseBotReposResponse), + (status = 412, description = "Setup not completed"), + (status = 502, description = "Switchboard / GitHub error"), + ), + tag = "goose_bot" +)] +#[axum::debug_handler] +async fn get_repos( + State(state): State>, +) -> Result, ErrorResponse> { + let creds = resolve_install_credentials(tunnel_snapshot(&state).await) + .await + .map_err(|e| ErrorResponse { + message: e.to_string(), + status: axum::http::StatusCode::PRECONDITION_FAILED, + })?; + + let body = fetch_repos(&creds) + .await + .map_err(|e| ErrorResponse::internal(e.to_string()))?; + Ok(Json(body)) +} + +#[utoipa::path( + get, + path = "/goose-bot/analytics", + responses( + (status = 200, description = "Per-install analytics rollups", body = GooseBotAnalytics), + (status = 412, description = "Setup not completed"), + ), + tag = "goose_bot" +)] +#[axum::debug_handler] +async fn get_analytics( + State(state): State>, +) -> Result, ErrorResponse> { + let creds = resolve_install_credentials(tunnel_snapshot(&state).await) + .await + .map_err(|e| ErrorResponse { + message: e.to_string(), + status: axum::http::StatusCode::PRECONDITION_FAILED, + })?; + let body = fetch_analytics(&creds) + .await + .map_err(|e| ErrorResponse::internal(e.to_string()))?; + Ok(Json(body)) +} + +pub fn routes(state: Arc) -> Router { + Router::new() + .route("/goose-bot/review", post(review)) + .route("/goose-bot/setup", post(setup).delete(disconnect)) + .route("/goose-bot/status", get(get_status)) + .route("/goose-bot/comment", post(comment)) + .route("/goose-bot/prefs", get(get_prefs).put(put_prefs)) + .route("/goose-bot/repos", get(get_repos)) + .route("/goose-bot/analytics", get(get_analytics)) + .with_state(state) +} diff --git a/crates/goose-server/src/routes/mod.rs b/crates/goose-server/src/routes/mod.rs index 00777d80acc4..a72e6c10cc6a 100644 --- a/crates/goose-server/src/routes/mod.rs +++ b/crates/goose-server/src/routes/mod.rs @@ -5,6 +5,7 @@ pub mod dictation; pub mod errors; pub mod features; pub mod gateway; +pub mod goose_bot; #[cfg(feature = "local-inference")] pub mod local_inference; pub mod mcp_app_proxy; @@ -42,6 +43,7 @@ pub fn configure(state: Arc, secret_key: String) -> Rout .merge(setup::routes(state.clone())) .merge(telemetry::routes(state.clone())) .merge(tunnel::routes(state.clone())) + .merge(goose_bot::routes(state.clone())) .merge(gateway::routes(state.clone())) .merge(mcp_ui_proxy::routes(secret_key.clone())) .merge(mcp_app_proxy::routes(secret_key)) diff --git a/crates/goose-server/src/tunnel/lapstone.rs b/crates/goose-server/src/tunnel/lapstone.rs index 9b55afbf306b..953a266713fd 100644 --- a/crates/goose-server/src/tunnel/lapstone.rs +++ b/crates/goose-server/src/tunnel/lapstone.rs @@ -22,20 +22,21 @@ struct ProxyContext { http_client: reqwest::Client, } -/// Constant-time comparison using hash to prevent timing attacks fn secure_compare(a: &str, b: &str) -> bool { - use std::collections::hash_map::DefaultHasher; - use std::hash::{Hash, Hasher}; - - let mut hasher_a = DefaultHasher::new(); - a.hash(&mut hasher_a); - let hash_a = hasher_a.finish(); - - let mut hasher_b = DefaultHasher::new(); - b.hash(&mut hasher_b); - let hash_b = hasher_b.finish(); + use subtle::ConstantTimeEq; + a.as_bytes().ct_eq(b.as_bytes()).into() +} - hash_a == hash_b +/// Only Goose Bot endpoints may be reached through the public tunnel. +fn tunnel_path_allowed(path: &str) -> bool { + let path = path.split('?').next().unwrap_or(path); + if path.contains("..") { + return false; + } + matches!( + path, + "/goose-bot/review" | "/goose-bot/comment" | "/goose-bot/status" + ) } const WORKER_URL: &str = "https://cloudflare-tunnel-proxy.michael-neale.workers.dev"; @@ -269,6 +270,25 @@ async fn handle_request( let request_id = message.request_id.clone(); let client = &ctx.http_client; + if !tunnel_path_allowed(&message.path) { + warn!("✗ Blocked tunnel path [{}]: {}", request_id, message.path); + let error_response = TunnelResponse { + request_id, + status: 403, + headers: None, + body: None, + error: Some("tunnel path not allowed".to_string()), + chunk_index: None, + total_chunks: None, + is_chunked: false, + is_streaming: false, + is_first_chunk: false, + is_last_chunk: false, + }; + send_response(ws_tx, error_response).await?; + return Ok(()); + } + let url = format!("{}://127.0.0.1:{}{}", scheme, ctx.port, message.path); let request_builder = match validate_and_build_request( @@ -633,3 +653,30 @@ pub async fn stop(handle: Arc>>>) { info!("Lapstone tunnel stopped"); } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tunnel_path_allowed_accepts_goose_bot_routes() { + assert!(tunnel_path_allowed("/goose-bot/review")); + assert!(tunnel_path_allowed("/goose-bot/comment")); + assert!(tunnel_path_allowed("/goose-bot/status")); + assert!(tunnel_path_allowed("/goose-bot/status?x=1")); + } + + #[test] + fn tunnel_path_allowed_rejects_other_paths() { + assert!(!tunnel_path_allowed("/config")); + assert!(!tunnel_path_allowed("/agent/start")); + assert!(!tunnel_path_allowed("/goose-bot/../config")); + assert!(!tunnel_path_allowed("/goose-bot/setup")); + } + + #[test] + fn secure_compare_matches_equal_secrets() { + assert!(secure_compare("abc", "abc")); + assert!(!secure_compare("abc", "abd")); + } +} diff --git a/crates/goose-server/tests/goose_bot_routes_test.rs b/crates/goose-server/tests/goose_bot_routes_test.rs new file mode 100644 index 000000000000..5185f620cae6 --- /dev/null +++ b/crates/goose-server/tests/goose_bot_routes_test.rs @@ -0,0 +1,106 @@ +use axum::body::Body; +use axum::http::{Request, StatusCode}; +use goose::config::Config; +use goose::goose_bot::{cached_installation_id, GooseBotPrefs, INSTALLATION_ID_CONFIG_KEY}; +use goose_server::routes::goose_bot::routes; +use goose_server::state::AppState; +use tower::ServiceExt; + +fn secret_header() -> (&'static str, &'static str) { + ("x-secret-key", "test-secret") +} + +#[tokio::test(flavor = "multi_thread")] +async fn goose_bot_prefs_get_put_roundtrip() { + let state = AppState::new(true).await.unwrap(); + let app = routes(state); + + let get = Request::builder() + .uri("/goose-bot/prefs") + .method("GET") + .header(secret_header().0, secret_header().1) + .body(Body::empty()) + .unwrap(); + let response = app.clone().oneshot(get).await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + + let put = Request::builder() + .uri("/goose-bot/prefs") + .method("PUT") + .header(secret_header().0, secret_header().1) + .header("content-type", "application/json") + .body(Body::from( + serde_json::to_string(&serde_json::json!({ + "prefs": { + "schema_version": 1, + "auto_review_on_pr_open": false, + "trigger_preference": "manual-only", + "trigger_permission": "anyone", + "allow_act_on_issues": false, + "specific_users_allowlist": [], + "allow_commit_on_fix": false, + "allow_open_new_prs": false, + "review_severity": "medium", + "custom_instructions": "route-test", + "review_output_style": "both", + "review_model_choice": "default" + } + })) + .unwrap(), + )) + .unwrap(); + let response = app.clone().oneshot(put).await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + + let get = Request::builder() + .uri("/goose-bot/prefs") + .method("GET") + .header(secret_header().0, secret_header().1) + .body(Body::empty()) + .unwrap(); + let response = app.oneshot(get).await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + let prefs: GooseBotPrefs = serde_json::from_slice(&body).unwrap(); + assert_eq!(prefs.custom_instructions, "route-test"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn goose_bot_status_and_disconnect_clear_install_id() { + let state = AppState::new(true).await.unwrap(); + let app = routes(state); + let config = Config::global(); + + config + .set_param(INSTALLATION_ID_CONFIG_KEY, serde_json::json!(42_u64)) + .unwrap(); + + let status = Request::builder() + .uri("/goose-bot/status") + .method("GET") + .header(secret_header().0, secret_header().1) + .body(Body::empty()) + .unwrap(); + let response = app.clone().oneshot(status).await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + let body = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); + assert_eq!(json["installation_id"], 42); + + assert_eq!(cached_installation_id(config), Some(42)); + + let disconnect = Request::builder() + .uri("/goose-bot/setup") + .method("DELETE") + .header(secret_header().0, secret_header().1) + .body(Body::empty()) + .unwrap(); + let response = app.oneshot(disconnect).await.unwrap(); + assert_eq!(response.status(), StatusCode::OK); + + assert_eq!(cached_installation_id(config), None); +} diff --git a/crates/goose/src/config/mod.rs b/crates/goose/src/config/mod.rs index 402c835f8783..59aa209f9a79 100644 --- a/crates/goose/src/config/mod.rs +++ b/crates/goose/src/config/mod.rs @@ -8,6 +8,7 @@ pub mod paths; pub mod permission; pub mod providers; pub mod search_path; +pub mod signup_goose_bot; pub mod signup_nanogpt; pub mod signup_openrouter; pub mod signup_tetrate; diff --git a/crates/goose/src/config/signup_goose_bot/mod.rs b/crates/goose/src/config/signup_goose_bot/mod.rs new file mode 100644 index 000000000000..7cb517dfc2de --- /dev/null +++ b/crates/goose/src/config/signup_goose_bot/mod.rs @@ -0,0 +1,141 @@ +pub mod server; + +#[cfg(test)] +mod tests; + +use anyhow::{anyhow, Result}; +use rand::{distributions::Alphanumeric, Rng}; +use serde::Deserialize; +use std::time::Duration; +use tokio::sync::oneshot; +use tokio::time::timeout; + +const APP_SLUG: &str = "aaif-goose-bot"; +const CALLBACK_PORT: u16 = 3458; +const INSTALL_TIMEOUT: Duration = Duration::from_secs(600); + +#[derive(Debug, Deserialize)] +pub struct InstallCallback { + pub oauth_code: String, +} + +pub type InstallCallbackResult = std::result::Result; + +pub struct GooseBotInstallFlow { + state: String, + server_shutdown_tx: Option>, + oauth_client_id: Option, +} + +impl GooseBotInstallFlow { + pub fn new() -> Self { + let state: String = rand::thread_rng() + .sample_iter(&Alphanumeric) + .take(64) + .map(char::from) + .collect(); + Self { + state, + server_shutdown_tx: None, + oauth_client_id: None, + } + } + + pub fn with_oauth_client_id(mut self, oauth_client_id: String) -> Self { + self.oauth_client_id = Some(oauth_client_id); + self + } + + pub fn app_install_url(&self) -> String { + format!( + "https://github.com/apps/{}/installations/new?state={}", + APP_SLUG, self.state + ) + } + + pub fn open_app_install_url(&self) { + let _ = webbrowser::open(&self.app_install_url()); + } + + pub fn install_url(&self) -> String { + if let Some(client_id) = &self.oauth_client_id { + return format!( + "https://github.com/login/oauth/authorize?client_id={}&state={}&redirect_uri={}", + client_id, + self.state, + urlencoding::encode(&Self::callback_url()) + ); + } + self.app_install_url() + } + + pub fn callback_url() -> String { + format!("http://localhost:{}/", CALLBACK_PORT) + } + + pub async fn complete_flow(&mut self) -> Result { + let cb_rx = self.start_callback_server().await?; + let _ = webbrowser::open(&self.install_url()); + Self::wait_for_callback(cb_rx).await + } + + pub async fn await_callback(&mut self) -> Result { + let cb_rx = self.start_callback_server().await?; + Self::wait_for_callback(cb_rx).await + } + + async fn start_callback_server(&mut self) -> Result> { + let (cb_tx, cb_rx) = oneshot::channel::(); + let (shutdown_tx, shutdown_rx) = oneshot::channel::<()>(); + let (ready_tx, ready_rx) = oneshot::channel::>(); + self.server_shutdown_tx = Some(shutdown_tx); + + let expected_state = self.state.clone(); + tokio::spawn(async move { + if let Err(e) = server::run_callback_server( + cb_tx, + shutdown_rx, + ready_tx, + expected_state, + CALLBACK_PORT, + ) + .await + { + tracing::error!("[goose-bot-install] callback server error: {}", e); + } + }); + ready_rx + .await + .map_err(|_| anyhow!("install callback server failed to start"))??; + Ok(cb_rx) + } + + async fn wait_for_callback( + cb_rx: oneshot::Receiver, + ) -> Result { + match timeout(INSTALL_TIMEOUT, cb_rx).await { + Ok(Ok(Ok(cb))) => Ok(cb), + Ok(Ok(Err(e))) => Err(anyhow!(e)), + Ok(Err(_)) => Err(anyhow!("install callback channel closed unexpectedly")), + Err(_) => Err(anyhow!("install timeout - please try again")), + } + } + + pub fn shutdown(&mut self) { + if let Some(tx) = self.server_shutdown_tx.take() { + let _ = tx.send(()); + } + } +} + +impl Default for GooseBotInstallFlow { + fn default() -> Self { + Self::new() + } +} + +impl Drop for GooseBotInstallFlow { + fn drop(&mut self) { + self.shutdown(); + } +} diff --git a/crates/goose/src/config/signup_goose_bot/server.rs b/crates/goose/src/config/signup_goose_bot/server.rs new file mode 100644 index 000000000000..85ac5c73cb3c --- /dev/null +++ b/crates/goose/src/config/signup_goose_bot/server.rs @@ -0,0 +1,115 @@ +use anyhow::Result; +use axum::{ + extract::Query, + http::StatusCode, + response::{Html, IntoResponse}, + routing::get, + Router, +}; +use include_dir::{include_dir, Dir}; +use serde::Deserialize; +use std::net::SocketAddr; +use tokio::sync::oneshot; + +use super::{InstallCallback, InstallCallbackResult}; + +static TEMPLATES_DIR: Dir = + include_dir!("$CARGO_MANIFEST_DIR/src/config/signup_goose_bot/templates"); + +#[derive(Debug, Deserialize)] +struct CallbackQuery { + code: Option, + state: Option, + error: Option, +} + +#[derive(Clone)] +struct Inner { + tx: std::sync::Arc>>>, + expected_state: String, +} + +pub async fn run_callback_server( + cb_tx: oneshot::Sender, + shutdown_rx: oneshot::Receiver<()>, + ready_tx: oneshot::Sender>, + expected_state: String, + port: u16, +) -> Result<()> { + let inner = Inner { + tx: std::sync::Arc::new(tokio::sync::Mutex::new(Some(cb_tx))), + expected_state, + }; + + let app = Router::new() + .route("/", get(handle_callback)) + .with_state(inner); + let addr = SocketAddr::from(([127, 0, 0, 1], port)); + let listener = tokio::net::TcpListener::bind(addr).await?; + let _ = ready_tx.send(Ok(())); + + axum::serve(listener, app.into_make_service()) + .with_graceful_shutdown(async move { + let _ = shutdown_rx.await; + }) + .await?; + + Ok(()) +} + +async fn handle_callback( + Query(params): Query, + axum::extract::State(inner): axum::extract::State, +) -> impl IntoResponse { + if let Some(error) = params.error { + send_callback(&inner, Err(error.clone())).await; + return render( + &TEMPLATES_DIR, + "error.html", + StatusCode::BAD_REQUEST, + &error, + ); + } + + let code = match params.code { + Some(c) => c, + None => { + send_callback(&inner, Err("missing oauth code".to_string())).await; + return render( + &TEMPLATES_DIR, + "error.html", + StatusCode::BAD_REQUEST, + "missing oauth code", + ); + } + }; + let state = params.state.unwrap_or_default(); + if state != inner.expected_state { + send_callback(&inner, Err("state mismatch".to_string())).await; + return render( + &TEMPLATES_DIR, + "error.html", + StatusCode::BAD_REQUEST, + "state mismatch", + ); + } + send_callback(&inner, Ok(InstallCallback { oauth_code: code })).await; + + render(&TEMPLATES_DIR, "success.html", StatusCode::OK, "") +} + +async fn send_callback(inner: &Inner, result: InstallCallbackResult) { + let mut tx_guard = inner.tx.lock().await; + if let Some(tx) = tx_guard.take() { + let _ = tx.send(result); + } +} + +fn render(dir: &Dir, name: &str, status: StatusCode, message: &str) -> (StatusCode, Html) { + let body = dir + .get_file(name) + .and_then(|f| f.contents_utf8()) + .map(|s| s.replace("{{ message }}", message)) + .unwrap_or_else(|| format!("

Goose Bot

{}

", message)); + (status, Html(body)) +} diff --git a/crates/goose/src/config/signup_goose_bot/templates/error.html b/crates/goose/src/config/signup_goose_bot/templates/error.html new file mode 100644 index 000000000000..548b6aa5c2ba --- /dev/null +++ b/crates/goose/src/config/signup_goose_bot/templates/error.html @@ -0,0 +1,19 @@ + + + + +Goose Bot - install failed + + + +

Could not connect Goose Bot

+

{{ message }}

+

Return to Goose Desktop and try again.

+ + diff --git a/crates/goose/src/config/signup_goose_bot/templates/success.html b/crates/goose/src/config/signup_goose_bot/templates/success.html new file mode 100644 index 000000000000..25e0aa747010 --- /dev/null +++ b/crates/goose/src/config/signup_goose_bot/templates/success.html @@ -0,0 +1,17 @@ + + + + +Goose Bot connected + + + +

Goose Bot connected

+

You can close this tab and return to Goose Desktop.

+ + diff --git a/crates/goose/src/config/signup_goose_bot/tests.rs b/crates/goose/src/config/signup_goose_bot/tests.rs new file mode 100644 index 000000000000..1d189fbbb50f --- /dev/null +++ b/crates/goose/src/config/signup_goose_bot/tests.rs @@ -0,0 +1,42 @@ +use super::GooseBotInstallFlow; + +#[test] +fn install_url_includes_oauth_client_and_state() { + let flow = GooseBotInstallFlow::new().with_oauth_client_id("Iv1.test-client".into()); + let url = flow.install_url(); + assert!(url.starts_with("https://github.com/login/oauth/authorize")); + assert!(url.contains("client_id=Iv1.test-client")); + assert!(url.contains("state=")); + assert!(url.contains("redirect_uri=")); +} + +#[test] +fn install_url_legacy_slug_when_no_oauth_client() { + let flow = GooseBotInstallFlow::new(); + let url = flow.install_url(); + assert!(url.contains("github.com/apps/aaif-goose-bot/installations/new")); + assert!(url.contains("state=")); +} + +#[test] +fn app_install_url_uses_github_app_slug() { + let flow = GooseBotInstallFlow::new().with_oauth_client_id("Iv1.test-client".into()); + let url = flow.app_install_url(); + assert!(url.contains("github.com/apps/aaif-goose-bot/installations/new")); + assert!(url.contains("state=")); +} + +#[test] +fn distinct_flows_have_distinct_state() { + let a = GooseBotInstallFlow::new(); + let b = GooseBotInstallFlow::new(); + assert_ne!(a.install_url(), b.install_url()); +} + +#[test] +fn callback_url_is_localhost() { + assert_eq!( + GooseBotInstallFlow::callback_url(), + "http://localhost:3458/" + ); +} diff --git a/crates/goose/src/goose_bot/analytics.rs b/crates/goose/src/goose_bot/analytics.rs new file mode 100644 index 000000000000..de1bb461df6b --- /dev/null +++ b/crates/goose/src/goose_bot/analytics.rs @@ -0,0 +1,20 @@ +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; + +#[derive(Debug, Clone, Default, Serialize, Deserialize, ToSchema, PartialEq, Eq)] +pub struct GooseBotAnalytics { + #[serde(default)] + pub prs_reviewed: u64, + #[serde(default)] + pub issues_handled: u64, + #[serde(default)] + pub commits_pushed: u64, +} + +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)] +#[serde(rename_all = "snake_case", tag = "kind")] +pub enum AnalyticsEvent { + PrReviewed, + IssueHandled, + CommitPushed, +} diff --git a/crates/goose/src/goose_bot/comment.rs b/crates/goose/src/goose_bot/comment.rs new file mode 100644 index 000000000000..997073d67b50 --- /dev/null +++ b/crates/goose/src/goose_bot/comment.rs @@ -0,0 +1,602 @@ +use std::path::Path; +use std::process::Stdio; +use std::time::{SystemTime, UNIX_EPOCH}; + +use anyhow::{bail, Result}; +use serde::Deserialize; +use tokio::process::Command; + +use super::github::{ + authenticated_repo_url, client, configure_bot_git_identity, git_run, scrub_remote_credentials, +}; +use super::runner::run_goose_for_reply; +use super::store::load_prefs; +use super::types::GooseBotCommentRequest; +use super::GooseBotPrefs; + +pub async fn run_comment_reply(req: GooseBotCommentRequest) -> Result { + let prefs = load_prefs(); + let workdir = tempfile::tempdir()?; + git_clone_and_checkout_for_comment(&req, workdir.path()).await?; + let context = fetch_comment_context(&req).await.ok(); + let prompt = build_comment_prompt(&req, &prefs, context.as_ref()); + let reply = run_goose_for_reply(workdir.path(), &prompt).await?; + + let outcome = decide_push_path(&req, &prefs, workdir.path()).await?; + let final_reply = match &outcome { + PushOutcome::CommittedToPr { files, branch } => { + format!("{reply}\n\n_Pushed {files} file change(s) to `{branch}`._") + } + PushOutcome::OpenedPr { url, files } => { + format!("{reply}\n\n_Opened a new pull request with {files} file change(s): {url}_") + } + PushOutcome::NoChanges | PushOutcome::Disabled => reply, + }; + post_pr_comment(&req, &final_reply).await?; + Ok(matches!( + outcome, + PushOutcome::CommittedToPr { .. } | PushOutcome::OpenedPr { .. } + )) +} + +enum PushOutcome { + NoChanges, + Disabled, + CommittedToPr { files: usize, branch: String }, + OpenedPr { url: String, files: usize }, +} + +fn can_push_to_pr_head(req: &GooseBotCommentRequest) -> bool { + req.head_repo.is_empty() || req.head_repo == req.repo +} + +async fn decide_push_path( + req: &GooseBotCommentRequest, + prefs: &GooseBotPrefs, + workdir: &Path, +) -> Result { + if req.is_pr { + if !prefs.allow_commit_on_fix || !can_push_to_pr_head(req) { + return Ok(PushOutcome::Disabled); + } + return match commit_and_push_if_changed(req, workdir).await? { + Some(files) => Ok(PushOutcome::CommittedToPr { + files, + branch: req.head_ref.clone(), + }), + None => Ok(PushOutcome::NoChanges), + }; + } + if !prefs.allow_open_new_prs { + return Ok(PushOutcome::Disabled); + } + create_branch_and_open_pr_if_changed(req, workdir).await +} + +async fn git_clone_and_checkout_for_comment( + req: &GooseBotCommentRequest, + dest: &Path, +) -> Result<()> { + let url = authenticated_repo_url(&req.github_token, &req.repo); + git_run(dest, &["clone", "--quiet", "--no-tags", &url, "."]).await?; + if req.is_pr { + let refspec = format!("+refs/pull/{}/head:refs/goose-bot/pr", req.pr_number); + git_run(dest, &["fetch", "--quiet", "origin", &refspec]).await?; + git_run(dest, &["checkout", "--quiet", "refs/goose-bot/pr"]).await?; + } + scrub_remote_credentials(dest, &req.repo).await?; + Ok(()) +} + +struct CommentContext { + title: String, + body: String, + state: String, + base_ref: Option, + prior_comments: Vec, +} + +struct PriorComment { + author: String, + location: Option, + body: String, +} + +const MAX_CONTEXT_BODY_BYTES: usize = 8 * 1024; +const MAX_PRIOR_COMMENTS: usize = 20; +const MAX_PRIOR_COMMENT_BYTES: usize = 1500; + +fn truncate_bytes(s: &str, max_bytes: usize) -> String { + if s.len() <= max_bytes { + return s.to_string(); + } + let mut end = max_bytes; + while end > 0 && !s.is_char_boundary(end) { + end -= 1; + } + let prefix = s.get(..end).unwrap_or(""); + format!("{prefix}\n...[truncated]") +} + +async fn fetch_comment_context(req: &GooseBotCommentRequest) -> Result { + #[derive(Deserialize)] + struct IssueResponse { + title: Option, + body: Option, + state: Option, + #[serde(default)] + pull_request: Option, + } + let url = format!( + "https://api.github.com/repos/{}/issues/{}", + req.repo, req.pr_number + ); + let res = client() + .get(&url) + .header("Authorization", format!("token {}", req.github_token)) + .send() + .await?; + if !res.status().is_success() { + bail!( + "fetch issue context: {} - {}", + res.status(), + res.text().await.unwrap_or_default() + ); + } + let issue: IssueResponse = res.json().await?; + + let mut body = issue.body.unwrap_or_default(); + if body.len() > MAX_CONTEXT_BODY_BYTES { + body = truncate_bytes(&body, MAX_CONTEXT_BODY_BYTES); + } + + let is_pr = issue.pull_request.is_some(); + let base_ref = if is_pr { + fetch_pr_base_ref(req).await.ok() + } else { + None + }; + let prior_comments = fetch_prior_comments(req, is_pr).await.unwrap_or_default(); + + Ok(CommentContext { + title: issue.title.unwrap_or_default(), + body, + state: issue.state.unwrap_or_default(), + base_ref, + prior_comments, + }) +} + +async fn fetch_prior_comments( + req: &GooseBotCommentRequest, + is_pr: bool, +) -> Result> { + #[derive(Deserialize)] + struct UserRef { + login: Option, + } + #[derive(Deserialize)] + struct RawComment { + id: u64, + user: Option, + body: Option, + #[serde(default)] + created_at: String, + #[serde(default)] + path: Option, + #[serde(default)] + line: Option, + } + async fn get_pages(url: &str, token: &str) -> Result> { + let mut out = Vec::new(); + let mut page = 1; + loop { + let separator = if url.contains('?') { '&' } else { '?' }; + let page_url = format!("{url}{separator}page={page}"); + let res = client() + .get(&page_url) + .header("Authorization", format!("token {token}")) + .send() + .await?; + if !res.status().is_success() { + bail!("GET {page_url} -> {}", res.status()); + } + let mut comments: Vec = res.json().await?; + let count = comments.len(); + out.append(&mut comments); + if count < 100 { + break; + } + page += 1; + } + Ok(out) + } + + let issue_url = format!( + "https://api.github.com/repos/{}/issues/{}/comments?per_page=100", + req.repo, req.pr_number + ); + let mut raw = get_pages(&issue_url, &req.github_token) + .await + .unwrap_or_default(); + if is_pr { + let pr_url = format!( + "https://api.github.com/repos/{}/pulls/{}/comments?per_page=100", + req.repo, req.pr_number + ); + if let Ok(mut more) = get_pages(&pr_url, &req.github_token).await { + raw.append(&mut more); + } + } + + if let Some(cur) = req.comment_id { + raw.retain(|c| c.id != cur); + } + raw.sort_by(|a, b| a.created_at.cmp(&b.created_at)); + if raw.len() > MAX_PRIOR_COMMENTS { + let skip = raw.len() - MAX_PRIOR_COMMENTS; + raw.drain(0..skip); + } + + Ok(raw + .into_iter() + .map(|c| { + let body = c.body.unwrap_or_default(); + let body = if body.len() > MAX_PRIOR_COMMENT_BYTES { + truncate_bytes(&body, MAX_PRIOR_COMMENT_BYTES) + } else { + body + }; + let location = match (c.path, c.line) { + (Some(p), Some(l)) => Some(format!("{p}:{l}")), + (Some(p), None) => Some(p), + _ => None, + }; + PriorComment { + author: c.user.and_then(|u| u.login).unwrap_or_default(), + location, + body, + } + }) + .collect()) +} + +async fn fetch_pr_base_ref(req: &GooseBotCommentRequest) -> Result { + #[derive(Deserialize)] + struct PrResponse { + base: BaseRef, + } + #[derive(Deserialize)] + struct BaseRef { + #[serde(rename = "ref")] + ref_name: String, + } + let url = format!( + "https://api.github.com/repos/{}/pulls/{}", + req.repo, req.pr_number + ); + let res = client() + .get(&url) + .header("Authorization", format!("token {}", req.github_token)) + .send() + .await?; + if !res.status().is_success() { + bail!("fetch PR base: {}", res.status()); + } + let pr: PrResponse = res.json().await?; + Ok(pr.base.ref_name) +} + +fn build_comment_prompt( + req: &GooseBotCommentRequest, + prefs: &GooseBotPrefs, + context: Option<&CommentContext>, +) -> String { + let cleaned = req + .comment_body + .replace("@aaif-goose-bot", "") + .trim() + .to_string(); + let (context_kind, context_label) = if req.is_pr { + ("pull request", "Pull request") + } else { + ("issue", "Issue") + }; + let checkout_clause = if req.is_pr { + "PR's head commit" + } else { + "repository's default branch" + }; + let commit_clause = if req.is_pr && prefs.allow_commit_on_fix && can_push_to_pr_head(req) { + "- Any files you change will be automatically committed and pushed to\n \ + the PR branch after you finish - do NOT run `git commit` or `git push`\n \ + yourself." + } else if req.is_pr { + "- The repo owner has DISABLED commit push for this bot. Tell the commenter\n \ + what you would change, but don't expect your edits to land on the PR.\n \ + Fork-based PRs are treated as commit-push-disabled." + } else if prefs.allow_open_new_prs { + "- This is an issue, not a PR. Make edits in the working directory; your\n \ + changes will be committed on a new branch and opened as a pull request\n \ + after you finish - do NOT run `git commit` or `git push` yourself." + } else { + "- This is an issue, not a PR - there is no branch to push to. Reply with\n \ + analysis, suggestions, or code samples in the comment itself." + }; + let custom = if prefs.custom_instructions.trim().is_empty() { + String::new() + } else { + format!( + "\nThe repo owner added these custom instructions - apply them:\n---\n{}\n---\n", + prefs.custom_instructions.trim() + ) + }; + let context_block = match context { + Some(c) => { + let mut block = format!( + "\n{label} title: {title}\n{label} state: {state}\n", + label = context_label, + title = if c.title.is_empty() { + "(no title)" + } else { + c.title.as_str() + }, + state = c.state, + ); + if let Some(base) = &c.base_ref { + block.push_str(&format!( + "PR base branch: {base} (you can run `git diff {base}...HEAD` to see what changed)\n" + )); + } + if !c.body.trim().is_empty() { + block.push_str(&format!( + "\n{label} body:\n---\n{body}\n---\n", + label = context_label, + body = c.body.trim() + )); + } + if !c.prior_comments.is_empty() { + block.push_str( + "\nPrior comments on this thread (oldest first). When the user\n\ + says \"address the suggested changes\" or \"fix what you flagged,\"\n\ + they are referring to these - look here, then apply the changes\n\ + in the working directory:\n", + ); + for c in &c.prior_comments { + let loc = c + .location + .as_deref() + .map(|l| format!(" @ {l}")) + .unwrap_or_default(); + block.push_str(&format!( + "---\n@{author}{loc}:\n{body}\n", + author = c.author, + loc = loc, + body = c.body + )); + } + block.push_str("---\n"); + } + block + } + None => String::new(), + }; + format!( + "You are responding to a comment on a GitHub {kind}.\n\ +\n\ +Repository: {repo}\n\ +{label}: #{num} ({url})\n\ +Commenter: @{user}\n\ +{context}\n\ +The repository is checked out at the current working directory at the\n\ +{checkout}. You can read AND modify files, run shell commands,\n\ +and use any available tools.\n\ +\n\ +If the commenter asks you to fix, address, or apply changes:\n\ +- Make the edits directly with your file-editing tools.\n\ +{commit}\n\ +- Then reply with a short summary of what you changed.\n\ +\n\ +If the commenter is asking a question or for analysis only:\n\ +- Don't modify any files.\n\ +- Reply with a concise answer, referencing files/lines when relevant.\n\ +- If the commenter is asking whether something is resolved or addressed,\n \ + read the {kind} body above for what they want, then check the working\n \ + directory to see if the code addresses it.\n\ +{custom}\n\ +The commenter's message (with @aaif-goose-bot stripped):\n\ +---\n\ +{body}\n\ +---\n\ +\n\ +Reply with a single concise GitHub-flavored markdown response. Do NOT\n\ +include a preamble like \"Sure, here's my response.\" Just answer.\n", + kind = context_kind, + repo = req.repo, + label = context_label, + num = req.pr_number, + url = req.pr_url, + user = req.commenter, + context = context_block, + checkout = checkout_clause, + commit = commit_clause, + custom = custom, + body = cleaned, + ) +} + +async fn post_pr_comment(req: &GooseBotCommentRequest, reply: &str) -> Result<()> { + let url = format!( + "https://api.github.com/repos/{}/issues/{}/comments", + req.repo, req.pr_number + ); + let body = format!("@{} {}", req.commenter, reply); + client() + .post(&url) + .header("Authorization", format!("token {}", req.github_token)) + .json(&serde_json::json!({ "body": body })) + .send() + .await? + .error_for_status()?; + Ok(()) +} + +async fn commit_and_push_if_changed( + req: &GooseBotCommentRequest, + workdir: &Path, +) -> Result> { + if req.head_ref.is_empty() { + return Ok(None); + } + + let status = Command::new("git") + .current_dir(workdir) + .args(["status", "--porcelain"]) + .stdin(Stdio::null()) + .output() + .await?; + if !status.status.success() { + bail!( + "git status failed: {}", + String::from_utf8_lossy(&status.stderr).trim() + ); + } + let stdout = String::from_utf8_lossy(&status.stdout); + let changed = stdout.lines().filter(|l| !l.trim().is_empty()).count(); + if changed == 0 { + return Ok(None); + } + + configure_bot_git_identity(workdir).await?; + git_run(workdir, &["add", "-A"]).await?; + let commit_msg = format!("Apply changes requested by @{}", req.commenter); + git_run(workdir, &["commit", "--quiet", "-m", &commit_msg]).await?; + let push_url = authenticated_repo_url(&req.github_token, &req.repo); + let refspec = format!("HEAD:refs/heads/{}", req.head_ref); + git_run(workdir, &["push", "--quiet", &push_url, &refspec]).await?; + Ok(Some(changed)) +} + +async fn create_branch_and_open_pr_if_changed( + req: &GooseBotCommentRequest, + workdir: &Path, +) -> Result { + let status = Command::new("git") + .current_dir(workdir) + .args(["status", "--porcelain"]) + .stdin(Stdio::null()) + .output() + .await?; + if !status.status.success() { + bail!( + "git status failed: {}", + String::from_utf8_lossy(&status.stderr).trim() + ); + } + let stdout = String::from_utf8_lossy(&status.stdout); + let changed = stdout.lines().filter(|l| !l.trim().is_empty()).count(); + if changed == 0 { + return Ok(PushOutcome::NoChanges); + } + + configure_bot_git_identity(workdir).await?; + + let head_out = Command::new("git") + .current_dir(workdir) + .args(["symbolic-ref", "--short", "HEAD"]) + .stdin(Stdio::null()) + .output() + .await?; + let default_branch = String::from_utf8_lossy(&head_out.stdout).trim().to_string(); + if default_branch.is_empty() { + bail!("could not determine default branch from clone"); + } + + let suffix = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + let branch = format!("goose-bot/issue-{}-{suffix}", req.pr_number); + git_run(workdir, &["checkout", "--quiet", "-b", &branch]).await?; + git_run(workdir, &["add", "-A"]).await?; + let commit_msg = format!( + "Address issue #{} requested by @{}", + req.pr_number, req.commenter + ); + git_run(workdir, &["commit", "--quiet", "-m", &commit_msg]).await?; + let push_url = authenticated_repo_url(&req.github_token, &req.repo); + let refspec = format!("HEAD:refs/heads/{branch}"); + git_run(workdir, &["push", "--quiet", &push_url, &refspec]).await?; + + let title = format!("Address issue #{}", req.pr_number); + let body = format!( + "Closes #{issue}.\n\nRequested by @{user} via Goose Bot.", + issue = req.pr_number, + user = req.commenter, + ); + let url = format!("https://api.github.com/repos/{}/pulls", req.repo); + let res = client() + .post(&url) + .header("Authorization", format!("token {}", req.github_token)) + .json(&serde_json::json!({ + "title": title, + "head": branch, + "base": default_branch, + "body": body, + })) + .send() + .await?; + if !res.status().is_success() { + let status = res.status(); + let detail = res.text().await.unwrap_or_default(); + bail!("create PR failed ({status}): {detail}"); + } + let pr: serde_json::Value = res.json().await?; + let html_url = pr + .get("html_url") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + Ok(PushOutcome::OpenedPr { + url: html_url, + files: changed, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn truncate_bytes_splits_on_char_boundary() { + let s = "あ".repeat(600); + let out = truncate_bytes(&s, 1500); + assert!(out.ends_with("...[truncated]")); + assert!(std::str::from_utf8(out.as_bytes()).is_ok()); + } + + #[test] + fn pr_head_push_requires_same_repo_when_head_repo_is_known() { + let mut req: GooseBotCommentRequest = serde_json::from_str( + r#"{ + "github_token": "t", + "repo": "owner/repo", + "pr_number": 1, + "pr_url": "https://github.com/owner/repo/pull/1", + "comment_body": "fix it", + "commenter": "u", + "head_ref": "feature", + "head_repo": "owner/repo", + "is_pr": true + }"#, + ) + .unwrap(); + assert!(can_push_to_pr_head(&req)); + + req.head_repo = "contributor/repo".into(); + assert!(!can_push_to_pr_head(&req)); + + req.head_repo.clear(); + assert!(can_push_to_pr_head(&req)); + } +} diff --git a/crates/goose/src/goose_bot/github.rs b/crates/goose/src/goose_bot/github.rs new file mode 100644 index 000000000000..ad723be531d8 --- /dev/null +++ b/crates/goose/src/goose_bot/github.rs @@ -0,0 +1,294 @@ +use std::path::Path; +use std::process::Stdio; + +use anyhow::{bail, Result}; +use reqwest::Client; +use serde::Deserialize; +use tokio::process::Command; + +use super::review::{build_review_payload, Finding, ReviewPublishContext}; +use super::types::GooseBotReviewRequest; +use super::{GooseBotPrefs, ReviewOutputStyle}; + +const USER_AGENT: &str = concat!("goose-bot/", env!("CARGO_PKG_VERSION")); + +pub fn client() -> Client { + Client::builder() + .user_agent(USER_AGENT) + .default_headers({ + let mut h = reqwest::header::HeaderMap::new(); + h.insert( + reqwest::header::ACCEPT, + "application/vnd.github+json".parse().unwrap(), + ); + h.insert("X-GitHub-Api-Version", "2022-11-28".parse().unwrap()); + h + }) + .build() + .expect("build reqwest client") +} + +pub async fn git_run(cwd: &Path, args: &[&str]) -> Result<()> { + let output = Command::new("git") + .current_dir(cwd) + .args(args) + .stdin(Stdio::null()) + .output() + .await?; + if !output.status.success() { + bail!( + "git {} failed: {}", + args.join(" "), + String::from_utf8_lossy(&output.stderr).trim() + ); + } + Ok(()) +} + +pub async fn fetch_pr_base_sha(req: &GooseBotReviewRequest) -> Result { + #[derive(Deserialize)] + struct PrResponse { + base: BaseRef, + } + #[derive(Deserialize)] + struct BaseRef { + sha: String, + } + + let url = format!( + "https://api.github.com/repos/{}/pulls/{}", + req.repo, req.pr_number + ); + let res = client() + .get(&url) + .header("Authorization", format!("token {}", req.github_token)) + .send() + .await?; + if !res.status().is_success() { + bail!( + "fetch PR metadata: {} - {}", + res.status(), + res.text().await.unwrap_or_default() + ); + } + let pr: PrResponse = res.json().await?; + Ok(pr.base.sha) +} + +pub fn authenticated_repo_url(github_token: &str, repo: &str) -> String { + format!("https://x-access-token:{github_token}@github.com/{repo}") +} + +pub async fn scrub_remote_credentials(dest: &Path, repo: &str) -> Result<()> { + let clean = format!("https://github.com/{repo}"); + git_run(dest, &["remote", "set-url", "origin", &clean]).await +} + +pub async fn git_clone_and_checkout_pr(req: &GooseBotReviewRequest, dest: &Path) -> Result<()> { + let url = authenticated_repo_url(&req.github_token, &req.repo); + git_run(dest, &["clone", "--quiet", "--no-tags", &url, "."]).await?; + let refspec = format!("+refs/pull/{}/head:refs/goose-bot/pr", req.pr_number); + git_run(dest, &["fetch", "--quiet", "origin", &refspec]).await?; + git_run(dest, &["fetch", "--quiet", "origin", &req.head_sha]).await?; + scrub_remote_credentials(dest, &req.repo).await?; + git_run(dest, &["checkout", "--quiet", "--detach", &req.head_sha]).await?; + Ok(()) +} + +pub async fn post_review( + req: &GooseBotReviewRequest, + findings: &[Finding], + prefs: &GooseBotPrefs, +) -> Result<()> { + let url = format!( + "https://api.github.com/repos/{}/pulls/{}/reviews", + req.repo, req.pr_number + ); + let style = &prefs.review_output_style; + let ctx = ReviewPublishContext { + pr_url: &req.pr_url, + head_sha: &req.head_sha, + }; + let payload = build_review_payload(ctx, findings, style); + + let res = client() + .post(&url) + .header("Authorization", format!("token {}", req.github_token)) + .json(&payload) + .send() + .await?; + + if res.status().is_success() { + return Ok(()); + } + + let status = res.status(); + let detail = res.text().await.unwrap_or_default(); + let detail_short: String = detail.chars().take(300).collect(); + + if matches!(style, ReviewOutputStyle::Summary) { + bail!("post review ({status}): {detail_short}"); + } + + tracing::warn!( + "[goose_bot] inline review rejected ({status}): {detail_short} - falling back to summary-only" + ); + + let mut fallback = build_review_payload(ctx, findings, &ReviewOutputStyle::Summary); + if let Some(body) = fallback + .get_mut("body") + .and_then(|v| v.as_str()) + .map(String::from) + { + let note = format!( + "\n\n_Inline annotations were rejected by GitHub ({status}). Showing summary only._\n_GitHub said:_ `{}`", + detail_short.replace('`', "'") + ); + fallback["body"] = serde_json::Value::String(format!("{body}{note}")); + } + client() + .post(&url) + .header("Authorization", format!("token {}", req.github_token)) + .json(&fallback) + .send() + .await? + .error_for_status()?; + Ok(()) +} + +pub async fn complete_check_run( + req: &GooseBotReviewRequest, + check_run_id: u64, + findings: &[Finding], +) -> Result<()> { + let title = if findings.is_empty() { + "No blocking issues".to_string() + } else { + format!("Reviewed - {} finding(s)", findings.len()) + }; + let url = format!( + "https://api.github.com/repos/{}/check-runs/{}", + req.repo, check_run_id + ); + client() + .patch(&url) + .header("Authorization", format!("token {}", req.github_token)) + .json(&serde_json::json!({ + "status": "completed", + "conclusion": "success", + "output": { + "title": title, + "summary": "Goose Bot review complete.", + }, + })) + .send() + .await? + .error_for_status()?; + Ok(()) +} + +pub async fn complete_check_run_failure( + req: &GooseBotReviewRequest, + check_run_id: u64, + detail: &str, +) -> Result<()> { + let detail_short: String = detail.chars().take(500).collect(); + let url = format!( + "https://api.github.com/repos/{}/check-runs/{}", + req.repo, check_run_id + ); + client() + .patch(&url) + .header("Authorization", format!("token {}", req.github_token)) + .json(&serde_json::json!({ + "status": "completed", + "conclusion": "neutral", + "output": { + "title": "Goose Bot review failed", + "summary": detail_short, + }, + })) + .send() + .await? + .error_for_status()?; + Ok(()) +} + +pub async fn post_comment_reaction( + repo: &str, + comment_id: u64, + content: &str, + github_token: &str, +) -> Result<()> { + let url = format!("https://api.github.com/repos/{repo}/issues/comments/{comment_id}/reactions"); + client() + .post(&url) + .header("Authorization", format!("token {github_token}")) + .json(&serde_json::json!({ "content": content })) + .send() + .await? + .error_for_status()?; + Ok(()) +} + +pub async fn replace_comment_reaction( + repo: &str, + comment_id: u64, + new_content: &str, + github_token: &str, +) -> Result<()> { + #[derive(Deserialize)] + struct ReactionUser { + login: String, + } + #[derive(Deserialize)] + struct Reaction { + id: u64, + content: String, + user: Option, + } + let list_url = + format!("https://api.github.com/repos/{repo}/issues/comments/{comment_id}/reactions"); + let existing: Vec = client() + .get(&list_url) + .header("Authorization", format!("token {github_token}")) + .send() + .await? + .error_for_status()? + .json() + .await?; + for r in existing { + let is_ours = r + .user + .as_ref() + .map(|u| u.login.starts_with("aaif-goose-bot")) + .unwrap_or(false); + if !is_ours || r.content == new_content { + continue; + } + let delete_url = format!( + "https://api.github.com/repos/{repo}/issues/comments/{comment_id}/reactions/{id}", + id = r.id + ); + let _ = client() + .delete(&delete_url) + .header("Authorization", format!("token {github_token}")) + .send() + .await + .and_then(|res| res.error_for_status()); + } + post_comment_reaction(repo, comment_id, new_content, github_token).await +} + +pub async fn configure_bot_git_identity(workdir: &Path) -> Result<()> { + git_run( + workdir, + &[ + "config", + "user.email", + "aaif-goose-bot[bot]@users.noreply.github.com", + ], + ) + .await?; + git_run(workdir, &["config", "user.name", "aaif-goose-bot[bot]"]).await +} diff --git a/crates/goose/src/goose_bot/mod.rs b/crates/goose/src/goose_bot/mod.rs new file mode 100644 index 000000000000..4785045beee7 --- /dev/null +++ b/crates/goose/src/goose_bot/mod.rs @@ -0,0 +1,42 @@ +//! GooseBot preferences schema for goosed, Desktop (OpenAPI), and the switchboard routing cache. + +pub mod analytics; +pub mod comment; +pub mod github; +pub mod prefs; +pub mod repos; +pub mod review; +pub mod review_run; +pub mod runner; +pub mod store; +pub mod switchboard; +pub mod types; + +pub use analytics::{AnalyticsEvent, GooseBotAnalytics}; +pub use comment::run_comment_reply; +pub use github::replace_comment_reaction; +pub use prefs::{ + GooseBotPrefs, ReviewModelChoice, ReviewOutputStyle, ReviewSeverity, RoutingPrefs, + TriggerPermission, TriggerPreference, SCHEMA_VERSION, +}; +pub use repos::{GooseBotRepo, GooseBotReposResponse, RepoVisibility}; +pub use review::{ + build_goose_review_args, build_review_payload, extract_final_assistant_text, parse_findings, + Finding, ReviewPublishContext, +}; +pub use review_run::run_review; +pub use store::{ + cached_installation_id, clear_install, load_prefs, load_prefs_from, save_prefs, save_prefs_to, + PREFS_CONFIG_KEY, +}; +pub use switchboard::{ + disconnect_install, extract_agent_id, fetch_analytics, fetch_oauth_client_id, fetch_repos, + forward_routing_prefs, register_installation, report_analytics_event, + resolve_install_credentials, unregister_installation, InstallCredentials, + RegisterInstallRequest, TunnelSnapshot, INSTALLATION_ID_CONFIG_KEY, SWITCHBOARD_URL_ENV, +}; +pub use types::{ + GooseBotCommentRequest, GooseBotDisconnectResponse, GooseBotPrefsRequest, + GooseBotPrefsResponse, GooseBotReviewRequest, GooseBotReviewResponse, GooseBotSetupResponse, + GooseBotStatusResponse, +}; diff --git a/crates/goose/src/goose_bot/prefs.rs b/crates/goose/src/goose_bot/prefs.rs new file mode 100644 index 000000000000..4a4ed1a129ec --- /dev/null +++ b/crates/goose/src/goose_bot/prefs.rs @@ -0,0 +1,374 @@ +use anyhow::{bail, Result}; +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; + +// Bump when the schema changes; reject client versions above SCHEMA_VERSION. +pub const SCHEMA_VERSION: u32 = 1; + +pub const MAX_CUSTOM_INSTRUCTIONS_BYTES: usize = 16 * 1024; +pub const MAX_ALLOWLIST_ENTRIES: usize = 256; +pub const MAX_GITHUB_USERNAME_LEN: usize = 39; + +#[derive(Debug, Clone, Default, Serialize, Deserialize, ToSchema, PartialEq, Eq)] +#[serde(rename_all = "kebab-case")] +pub enum TriggerPreference { + #[default] + PrOpen, + OnEveryPush, + ManualOnly, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize, ToSchema, PartialEq, Eq)] +#[serde(rename_all = "kebab-case")] +pub enum TriggerPermission { + #[default] + Anyone, + WriteAccess, + SpecificUsers, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize, ToSchema, PartialEq, Eq)] +#[serde(rename_all = "kebab-case")] +pub enum ReviewOutputStyle { + Inline, + Summary, + #[default] + Both, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize, ToSchema, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub enum ReviewSeverity { + Low, + #[default] + Medium, + High, + Critical, +} + +impl ReviewSeverity { + pub fn as_cli_flag(&self) -> &'static str { + match self { + Self::Low => "low", + Self::Medium => "medium", + Self::High => "high", + Self::Critical => "critical", + } + } +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize, ToSchema, PartialEq, Eq)] +#[serde(rename_all = "kebab-case")] +pub enum ReviewModelChoice { + #[default] + Default, + Custom, +} + +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub struct GooseBotPrefs { + #[serde(default = "default_schema_version")] + pub schema_version: u32, + + #[serde(default)] + pub auto_review_on_pr_open: bool, + #[serde(default)] + pub trigger_preference: TriggerPreference, + #[serde(default)] + pub trigger_permission: TriggerPermission, + #[serde(default)] + pub allow_act_on_issues: bool, + #[serde(default)] + pub specific_users_allowlist: Vec, + + #[serde(default)] + pub allow_commit_on_fix: bool, + #[serde(default)] + pub allow_open_new_prs: bool, + #[serde(default)] + pub review_severity: ReviewSeverity, + #[serde(default)] + pub custom_instructions: String, + #[serde(default)] + pub review_output_style: ReviewOutputStyle, + #[serde(default)] + pub review_model_choice: ReviewModelChoice, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub review_provider: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub review_model: Option, +} + +fn default_schema_version() -> u32 { + SCHEMA_VERSION +} + +impl Default for GooseBotPrefs { + fn default() -> Self { + Self { + schema_version: SCHEMA_VERSION, + auto_review_on_pr_open: false, + trigger_preference: TriggerPreference::default(), + trigger_permission: TriggerPermission::default(), + allow_act_on_issues: false, + specific_users_allowlist: Vec::new(), + allow_commit_on_fix: false, + allow_open_new_prs: false, + review_severity: ReviewSeverity::default(), + custom_instructions: String::new(), + review_output_style: ReviewOutputStyle::default(), + review_model_choice: ReviewModelChoice::default(), + review_provider: None, + review_model: None, + } + } +} + +impl GooseBotPrefs { + pub fn validate(&self) -> Result<()> { + if self.schema_version > SCHEMA_VERSION { + bail!( + "schema_version {} is newer than this server understands ({})", + self.schema_version, + SCHEMA_VERSION + ); + } + if self.custom_instructions.len() > MAX_CUSTOM_INSTRUCTIONS_BYTES { + bail!( + "custom_instructions exceeds {} bytes", + MAX_CUSTOM_INSTRUCTIONS_BYTES + ); + } + if self + .custom_instructions + .chars() + .any(|c| c.is_control() && c != '\n' && c != '\r' && c != '\t') + { + bail!("custom_instructions contains disallowed control characters"); + } + if self.specific_users_allowlist.len() > MAX_ALLOWLIST_ENTRIES { + bail!( + "specific_users_allowlist exceeds {} entries", + MAX_ALLOWLIST_ENTRIES + ); + } + for entry in &self.specific_users_allowlist { + let trimmed = entry.trim(); + if trimmed.is_empty() { + bail!("specific_users_allowlist contains a blank entry"); + } + if trimmed.len() > MAX_GITHUB_USERNAME_LEN { + bail!("allowlist entry `{trimmed}` exceeds {MAX_GITHUB_USERNAME_LEN} chars",); + } + if !is_valid_github_username(trimmed) { + bail!("allowlist entry `{trimmed}` is not a valid GitHub username"); + } + } + Ok(()) + } + + pub fn routing_subset(&self) -> RoutingPrefs { + RoutingPrefs { + schema_version: self.schema_version, + auto_review_on_pr_open: self.auto_review_on_pr_open, + trigger_preference: self.trigger_preference.clone(), + trigger_permission: self.trigger_permission.clone(), + allow_act_on_issues: self.allow_act_on_issues, + specific_users_allowlist: self.specific_users_allowlist.clone(), + } + } +} + +fn is_valid_github_username(s: &str) -> bool { + if s.is_empty() || s.starts_with('-') || s.ends_with('-') { + return false; + } + if s.contains("--") { + return false; + } + s.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') +} + +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub struct RoutingPrefs { + pub schema_version: u32, + pub auto_review_on_pr_open: bool, + pub trigger_preference: TriggerPreference, + pub trigger_permission: TriggerPermission, + pub allow_act_on_issues: bool, + #[serde(default)] + pub specific_users_allowlist: Vec, +} + +impl Default for RoutingPrefs { + fn default() -> Self { + GooseBotPrefs::default().routing_subset() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn defaults_roundtrip() { + let p = GooseBotPrefs::default(); + let json = serde_json::to_string(&p).unwrap(); + let p2: GooseBotPrefs = serde_json::from_str(&json).unwrap(); + assert_eq!(p, p2); + } + + #[test] + fn missing_fields_get_defaults() { + let p: GooseBotPrefs = serde_json::from_str("{}").unwrap(); + assert_eq!(p, GooseBotPrefs::default()); + } + + #[test] + fn partial_payload_merges_defaults() { + let p: GooseBotPrefs = serde_json::from_str( + r#"{"auto_review_on_pr_open": false, "custom_instructions": "be nice"}"#, + ) + .unwrap(); + assert!(!p.auto_review_on_pr_open); + assert_eq!(p.custom_instructions, "be nice"); + assert_eq!(p.trigger_preference, TriggerPreference::PrOpen); + assert_eq!(p.review_output_style, ReviewOutputStyle::Both); + } + + #[test] + fn kebab_case_enum_serialization() { + let p = GooseBotPrefs { + trigger_preference: TriggerPreference::OnEveryPush, + ..Default::default() + }; + let json = serde_json::to_string(&p).unwrap(); + assert!( + json.contains("\"trigger_preference\":\"on-every-push\""), + "got {json}" + ); + } + + #[test] + fn validate_accepts_default() { + GooseBotPrefs::default().validate().unwrap(); + } + + #[test] + fn validate_rejects_future_schema_version() { + let p = GooseBotPrefs { + schema_version: SCHEMA_VERSION + 1, + ..Default::default() + }; + assert!(p.validate().is_err()); + } + + #[test] + fn validate_rejects_oversized_instructions() { + let p = GooseBotPrefs { + custom_instructions: "x".repeat(MAX_CUSTOM_INSTRUCTIONS_BYTES + 1), + ..Default::default() + }; + assert!(p.validate().is_err()); + } + + #[test] + fn validate_rejects_control_chars() { + let p = GooseBotPrefs { + custom_instructions: "evil \x07 bell".to_string(), + ..Default::default() + }; + assert!(p.validate().is_err()); + } + + #[test] + fn validate_allows_newlines_and_tabs() { + let p = GooseBotPrefs { + custom_instructions: "line one\nline two\twith tab\r\nend".to_string(), + ..Default::default() + }; + p.validate().unwrap(); + } + + #[test] + fn routing_subset_drops_execution_prefs() { + let p = GooseBotPrefs { + custom_instructions: "secret prompt".to_string(), + review_model_choice: ReviewModelChoice::Custom, + ..Default::default() + }; + let routing = p.routing_subset(); + let json = serde_json::to_string(&routing).unwrap(); + assert!(!json.contains("custom_instructions")); + assert!(!json.contains("review_model_choice")); + } + + #[test] + fn review_severity_cli_flag_strings() { + assert_eq!(ReviewSeverity::Low.as_cli_flag(), "low"); + assert_eq!(ReviewSeverity::Medium.as_cli_flag(), "medium"); + assert_eq!(ReviewSeverity::High.as_cli_flag(), "high"); + assert_eq!(ReviewSeverity::Critical.as_cli_flag(), "critical"); + } + + #[test] + fn validate_accepts_well_formed_allowlist() { + let p = GooseBotPrefs { + specific_users_allowlist: vec!["octocat".into(), "abhi-jay".into(), "user123".into()], + ..Default::default() + }; + p.validate().unwrap(); + } + + #[test] + fn validate_rejects_blank_allowlist_entry() { + let p = GooseBotPrefs { + specific_users_allowlist: vec!["octocat".into(), " ".into()], + ..Default::default() + }; + assert!(p.validate().is_err()); + } + + #[test] + fn validate_rejects_malformed_username() { + for bad in [ + "-leading", + "trailing-", + "double--hyphen", + "has space", + "has_underscore", + ] { + let p = GooseBotPrefs { + specific_users_allowlist: vec![bad.into()], + ..Default::default() + }; + assert!(p.validate().is_err(), "expected reject for `{bad}`"); + } + } + + #[test] + fn validate_rejects_oversize_allowlist() { + let p = GooseBotPrefs { + specific_users_allowlist: (0..(MAX_ALLOWLIST_ENTRIES + 1)) + .map(|i| format!("user{i}")) + .collect(), + ..Default::default() + }; + assert!(p.validate().is_err()); + } + + #[test] + fn routing_subset_carries_allowlist() { + let p = GooseBotPrefs { + specific_users_allowlist: vec!["octocat".into()], + ..Default::default() + }; + let routing = p.routing_subset(); + assert_eq!( + routing.specific_users_allowlist, + vec!["octocat".to_string()] + ); + } +} diff --git a/crates/goose/src/goose_bot/repos.rs b/crates/goose/src/goose_bot/repos.rs new file mode 100644 index 000000000000..e597fef94637 --- /dev/null +++ b/crates/goose/src/goose_bot/repos.rs @@ -0,0 +1,36 @@ +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; + +#[derive(Debug, Clone, Default, Serialize, Deserialize, ToSchema, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub enum RepoVisibility { + Public, + Private, + Internal, + #[default] + Unknown, +} + +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)] +pub struct GooseBotRepo { + pub id: u64, + pub full_name: String, + pub name: String, + pub owner: String, + #[serde(default)] + pub visibility: RepoVisibility, + #[serde(default)] + pub archived: bool, + #[serde(default)] + pub default_branch: String, + #[serde(default)] + pub html_url: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, PartialEq, Eq)] +pub struct GooseBotReposResponse { + pub total_count: u64, + pub repos: Vec, + #[serde(default)] + pub truncated: bool, +} diff --git a/crates/goose/src/goose_bot/review.rs b/crates/goose/src/goose_bot/review.rs new file mode 100644 index 000000000000..fd9ca4ecd04c --- /dev/null +++ b/crates/goose/src/goose_bot/review.rs @@ -0,0 +1,376 @@ +use anyhow::{anyhow, bail, Context, Result}; +use serde::Deserialize; + +use super::{GooseBotPrefs, ReviewModelChoice, ReviewOutputStyle}; + +#[derive(Debug, Deserialize, Clone)] +pub struct Finding { + pub severity: String, + pub path: String, + #[serde(default)] + pub line_start: i64, + #[serde(default)] + pub line_end: i64, + pub summary: String, + #[serde(default)] + pub check: String, + #[serde(default)] + pub suggestion: Option, +} + +#[derive(Clone, Copy)] +pub struct ReviewPublishContext<'a> { + pub pr_url: &'a str, + pub head_sha: &'a str, +} + +pub fn parse_findings(stdout: &str) -> Result> { + let mut out = Vec::new(); + for (idx, line) in stdout.lines().enumerate() { + let trimmed = line.trim(); + if trimmed.is_empty() { + continue; + } + let f: Finding = serde_json::from_str(trimmed) + .with_context(|| format!("parse finding on line {}", idx + 1))?; + out.push(f); + } + Ok(out) +} + +pub fn build_goose_review_args(base: &str, head: &str, prefs: &GooseBotPrefs) -> Vec { + let mut args: Vec = vec![ + "review".into(), + format!("{base}...{head}"), + "--severity".into(), + prefs.review_severity.as_cli_flag().into(), + "--quiet".into(), + ]; + if matches!(prefs.review_model_choice, ReviewModelChoice::Custom) { + if let Some(provider) = prefs.review_provider.as_deref().filter(|s| !s.is_empty()) { + args.push("--provider".into()); + args.push(provider.to_string()); + } + if let Some(model) = prefs.review_model.as_deref().filter(|s| !s.is_empty()) { + args.push("--model".into()); + args.push(model.to_string()); + } + } + let instructions = prefs.custom_instructions.trim(); + if !instructions.is_empty() { + args.push("--instructions".into()); + args.push(instructions.to_string()); + } + args +} + +pub fn build_review_payload( + ctx: ReviewPublishContext<'_>, + findings: &[Finding], + style: &ReviewOutputStyle, +) -> serde_json::Value { + let include_inline = matches!(style, ReviewOutputStyle::Inline | ReviewOutputStyle::Both); + let include_summary = matches!(style, ReviewOutputStyle::Summary | ReviewOutputStyle::Both); + + let comments: Vec = if include_inline { + findings + .iter() + .filter(|f| !f.path.is_empty() && f.line_start > 0) + .map(|f| { + let line = if f.line_end > 0 { + f.line_end + } else { + f.line_start + }; + let mut body = format!( + "**{}** ({}) - {}", + f.severity.to_ascii_uppercase(), + if f.check.is_empty() { "main" } else { &f.check }, + f.summary + ); + if let Some(code) = f + .suggestion + .as_deref() + .map(str::trim) + .filter(|s| !s.is_empty()) + { + body.push_str("\n\n```suggestion\n"); + body.push_str(code); + body.push_str("\n```"); + } + let mut comment = serde_json::json!({ + "path": f.path, + "line": line, + "side": "RIGHT", + "body": body, + }); + if f.line_end > f.line_start { + comment["start_line"] = serde_json::json!(f.line_start); + comment["start_side"] = serde_json::json!("RIGHT"); + } + comment + }) + .collect() + } else { + Vec::new() + }; + + let summary = if include_summary { + let mut s = format!( + "**[Goose Bot]({})** - {} finding(s)", + ctx.pr_url, + findings.len() + ); + if !findings.is_empty() { + s.push_str(":\n\n"); + for f in findings.iter().take(10) { + s.push_str(&format!( + "- **{}** in `{}`: {}\n", + f.severity, f.path, f.summary + )); + } + if findings.len() > 10 { + s.push_str(&format!("...and {} more.\n", findings.len() - 10)); + } + } + if !include_inline { + s.push_str("\n_(summary-only mode; inline annotations disabled.)_"); + } + s + } else { + format!( + "[Goose Bot]({}) - {} inline finding(s).", + ctx.pr_url, + findings.len() + ) + }; + + serde_json::json!({ + "commit_id": ctx.head_sha, + "body": summary, + "event": "COMMENT", + "comments": comments, + }) +} + +pub fn extract_final_assistant_text(stdout: &str) -> Result { + #[derive(Deserialize)] + struct RunOutput { + messages: Vec, + } + #[derive(Deserialize)] + struct RunMessage { + role: String, + #[serde(default)] + content: Vec, + } + + let parsed: RunOutput = serde_json::from_str(stdout)?; + let last = parsed + .messages + .iter() + .rev() + .find(|m| m.role.eq_ignore_ascii_case("assistant")) + .ok_or_else(|| anyhow!("no assistant message in goose run output"))?; + let text: String = last + .content + .iter() + .filter_map(|c| c.get("text").and_then(|t| t.as_str()).map(str::to_string)) + .collect::>() + .join("\n\n"); + if text.trim().is_empty() { + bail!("assistant message had no text content"); + } + Ok(text.trim().to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample_ctx() -> ReviewPublishContext<'static> { + ReviewPublishContext { + pr_url: "https://github.com/o/r/pull/1", + head_sha: "h", + } + } + + #[test] + fn parse_findings_drops_blank_lines() { + let stdout = r#"{"severity":"high","path":"src/foo.rs","line_start":10,"line_end":12,"summary":"oops","check":"main"} + +{"severity":"low","path":"src/bar.rs","line_start":5,"line_end":5,"summary":"nit","check":"perf"} +"#; + let findings = parse_findings(stdout).unwrap(); + assert_eq!(findings.len(), 2); + assert_eq!(findings[0].severity, "high"); + assert_eq!(findings[1].check, "perf"); + } + + #[test] + fn parse_findings_rejects_malformed_line() { + let stdout = "{\"severity\":\"high\"}\nnot-json\n"; + assert!(parse_findings(stdout).is_err()); + } + + #[test] + fn build_review_payload_inline_includes_comments() { + let findings = vec![Finding { + severity: "high".into(), + path: "a.rs".into(), + line_start: 1, + line_end: 2, + summary: "bug".into(), + check: "main".into(), + suggestion: None, + }]; + let payload = build_review_payload(sample_ctx(), &findings, &ReviewOutputStyle::Both); + let comments = payload["comments"].as_array().unwrap(); + assert_eq!(comments.len(), 1); + assert_eq!(comments[0]["path"], "a.rs"); + assert!(!comments[0]["body"] + .as_str() + .unwrap() + .contains("```suggestion")); + } + + #[test] + fn build_review_payload_inline_emits_suggestion_block() { + let findings = vec![Finding { + severity: "medium".into(), + path: "a.py".into(), + line_start: 4, + line_end: 4, + summary: "mutable default arg".into(), + check: "main".into(), + suggestion: Some("def add_tag(tag, tags=None):".into()), + }]; + let payload = build_review_payload(sample_ctx(), &findings, &ReviewOutputStyle::Both); + let body = payload["comments"][0]["body"].as_str().unwrap(); + assert!(body.contains("```suggestion\ndef add_tag(tag, tags=None):\n```")); + } + + #[test] + fn build_review_payload_inline_drops_unmapped_lines() { + let findings = vec![Finding { + severity: "medium".into(), + path: "a.py".into(), + line_start: 0, + line_end: 0, + summary: "repo-level issue".into(), + check: "main".into(), + suggestion: None, + }]; + let payload = build_review_payload(sample_ctx(), &findings, &ReviewOutputStyle::Both); + assert!(payload["comments"].as_array().unwrap().is_empty()); + assert!(payload["body"] + .as_str() + .unwrap() + .contains("repo-level issue")); + } + + #[test] + fn build_review_payload_inline_marks_multiline_ranges() { + let findings = vec![Finding { + severity: "medium".into(), + path: "a.py".into(), + line_start: 4, + line_end: 6, + summary: "replace range".into(), + check: "main".into(), + suggestion: Some("line_a()\nline_b()\nline_c()".into()), + }]; + let payload = build_review_payload(sample_ctx(), &findings, &ReviewOutputStyle::Both); + let comment = &payload["comments"][0]; + assert_eq!(comment["line"], 6); + assert_eq!(comment["start_line"], 4); + assert_eq!(comment["start_side"], "RIGHT"); + assert!(comment["body"] + .as_str() + .unwrap() + .contains("```suggestion\nline_a()\nline_b()\nline_c()\n```")); + } + + #[test] + fn build_review_payload_summary_only_drops_comments() { + let findings = vec![Finding { + severity: "high".into(), + path: "a.rs".into(), + line_start: 1, + line_end: 2, + summary: "bug".into(), + check: "main".into(), + suggestion: None, + }]; + let payload = build_review_payload(sample_ctx(), &findings, &ReviewOutputStyle::Summary); + assert!(payload["comments"].as_array().unwrap().is_empty()); + assert!(payload["body"] + .as_str() + .unwrap() + .contains("summary-only mode")); + } + + #[test] + fn build_review_payload_inline_only_drops_summary_body() { + let findings = vec![Finding { + severity: "high".into(), + path: "a.rs".into(), + line_start: 1, + line_end: 2, + summary: "bug".into(), + check: "main".into(), + suggestion: None, + }]; + let payload = build_review_payload(sample_ctx(), &findings, &ReviewOutputStyle::Inline); + assert_eq!(payload["comments"].as_array().unwrap().len(), 1); + let body = payload["body"].as_str().unwrap(); + assert!(body.contains("1 inline finding(s)"), "got body: {body}"); + assert!(!body.contains("- **high**")); + } + + #[test] + fn review_args_defaults() { + let args = build_goose_review_args("base", "head", &GooseBotPrefs::default()); + assert_eq!( + args, + vec!["review", "base...head", "--severity", "medium", "--quiet"] + ); + } + + #[test] + fn review_args_severity_reflects_pref() { + use crate::goose_bot::ReviewSeverity; + let prefs = GooseBotPrefs { + review_severity: ReviewSeverity::High, + ..Default::default() + }; + let args = build_goose_review_args("base", "head", &prefs); + let pos = args.iter().position(|a| a == "--severity").unwrap(); + assert_eq!(args[pos + 1], "high"); + } + + #[test] + fn review_args_threads_custom_instructions() { + let prefs = GooseBotPrefs { + custom_instructions: "Be strict on missing tests.".into(), + ..Default::default() + }; + let args = build_goose_review_args("base", "head", &prefs); + let pos = args.iter().position(|a| a == "--instructions").unwrap(); + assert_eq!(args[pos + 1], "Be strict on missing tests."); + } + + #[test] + fn extract_final_assistant_text_picks_last_assistant() { + let stdout = r#"{ + "messages": [ + {"role": "user", "content": [{"type": "text", "text": "hi"}]}, + {"role": "assistant", "content": [{"type": "tool_use", "name": "shell"}]}, + {"role": "tool", "content": [{"type": "text", "text": "tool output"}]}, + {"role": "assistant", "content": [{"type": "text", "text": "final reply"}]} + ] + }"#; + let text = extract_final_assistant_text(stdout).unwrap(); + assert_eq!(text, "final reply"); + } +} diff --git a/crates/goose/src/goose_bot/review_run.rs b/crates/goose/src/goose_bot/review_run.rs new file mode 100644 index 000000000000..e595a10389c5 --- /dev/null +++ b/crates/goose/src/goose_bot/review_run.rs @@ -0,0 +1,36 @@ +use anyhow::Result; + +use super::github::{ + complete_check_run, complete_check_run_failure, fetch_pr_base_sha, git_clone_and_checkout_pr, + post_review, +}; +use super::review::Finding; +use super::runner::run_goose_review; +use super::store::load_prefs; +use super::types::GooseBotReviewRequest; + +pub async fn run_review(req: GooseBotReviewRequest) -> Result> { + let result = run_review_inner(&req).await; + if let Err(e) = &result { + if let Some(crid) = req.check_run_id { + if let Err(complete_err) = complete_check_run_failure(&req, crid, &e.to_string()).await + { + tracing::warn!("[goose_bot] complete failed review check run: {complete_err}"); + } + } + } + result +} + +async fn run_review_inner(req: &GooseBotReviewRequest) -> Result> { + let prefs = load_prefs(); + let base_sha = fetch_pr_base_sha(req).await?; + let workdir = tempfile::tempdir()?; + git_clone_and_checkout_pr(req, workdir.path()).await?; + let findings = run_goose_review(workdir.path(), &base_sha, &req.head_sha, &prefs).await?; + post_review(req, &findings, &prefs).await?; + if let Some(crid) = req.check_run_id { + complete_check_run(req, crid, &findings).await?; + } + Ok(findings) +} diff --git a/crates/goose/src/goose_bot/runner.rs b/crates/goose/src/goose_bot/runner.rs new file mode 100644 index 000000000000..648c3b64ef90 --- /dev/null +++ b/crates/goose/src/goose_bot/runner.rs @@ -0,0 +1,82 @@ +use std::env; +use std::path::{Path, PathBuf}; +use std::process::Stdio; + +use anyhow::{anyhow, bail, Result}; +use tokio::process::Command; + +use super::review::{build_goose_review_args, extract_final_assistant_text, parse_findings}; +use super::GooseBotPrefs; + +pub fn locate_goose_binary() -> Result { + if let Ok(current) = env::current_exe() { + if let Some(parent) = current.parent() { + let candidate = parent.join("goose"); + if candidate.exists() { + return Ok(candidate); + } + } + } + Ok(PathBuf::from("goose")) +} + +pub async fn run_goose_review( + workdir: &Path, + base: &str, + head: &str, + prefs: &GooseBotPrefs, +) -> Result> { + let bin = locate_goose_binary()?; + let args = build_goose_review_args(base, head, prefs); + + let output = Command::new(&bin) + .current_dir(workdir) + .args(&args) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .await?; + + if !output.status.success() { + bail!( + "goose review exited with {}: {}", + output.status, + String::from_utf8_lossy(&output.stderr).trim() + ); + } + + let stdout = String::from_utf8(output.stdout) + .map_err(|e| anyhow!("goose review stdout was not UTF-8: {e}"))?; + parse_findings(&stdout) +} + +pub async fn run_goose_for_reply(workdir: &Path, prompt: &str) -> Result { + let bin = locate_goose_binary()?; + let output = Command::new(&bin) + .current_dir(workdir) + .args([ + "run", + "--no-session", + "--quiet", + "--output-format", + "json", + "-t", + prompt, + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .await?; + if !output.status.success() { + bail!( + "goose run exited with {}: {}", + output.status, + String::from_utf8_lossy(&output.stderr).trim() + ); + } + let stdout = String::from_utf8(output.stdout) + .map_err(|e| anyhow!("goose run stdout was not UTF-8: {e}"))?; + extract_final_assistant_text(&stdout) +} diff --git a/crates/goose/src/goose_bot/store.rs b/crates/goose/src/goose_bot/store.rs new file mode 100644 index 000000000000..c263ab99592c --- /dev/null +++ b/crates/goose/src/goose_bot/store.rs @@ -0,0 +1,39 @@ +use anyhow::{anyhow, Result}; + +use crate::config::Config; + +use super::GooseBotPrefs; + +pub const PREFS_CONFIG_KEY: &str = "goose_bot_prefs"; + +pub fn load_prefs_from(config: &Config) -> GooseBotPrefs { + match config.get_param::(PREFS_CONFIG_KEY) { + Ok(v) => serde_json::from_value(v).unwrap_or_default(), + Err(_) => GooseBotPrefs::default(), + } +} + +pub fn save_prefs_to(config: &Config, prefs: &GooseBotPrefs) -> Result<()> { + config + .set_param(PREFS_CONFIG_KEY, serde_json::to_value(prefs)?) + .map_err(|e| anyhow!("persist goose_bot prefs: {e}")) +} + +pub fn load_prefs() -> GooseBotPrefs { + load_prefs_from(Config::global()) +} + +pub fn save_prefs(prefs: &GooseBotPrefs) -> Result<()> { + save_prefs_to(Config::global(), prefs) +} + +pub fn cached_installation_id(config: &Config) -> Option { + config + .get_param::(super::switchboard::INSTALLATION_ID_CONFIG_KEY) + .ok() +} + +pub fn clear_install(config: &Config) { + let _ = config.delete(super::switchboard::INSTALLATION_ID_CONFIG_KEY); + let _ = config.delete(PREFS_CONFIG_KEY); +} diff --git a/crates/goose/src/goose_bot/switchboard.rs b/crates/goose/src/goose_bot/switchboard.rs new file mode 100644 index 000000000000..24b0bf3b26f1 --- /dev/null +++ b/crates/goose/src/goose_bot/switchboard.rs @@ -0,0 +1,238 @@ +use std::env; + +use anyhow::{anyhow, bail, Context, Result}; +use reqwest::Client; +use serde::Deserialize; + +use crate::config::Config; + +use super::{AnalyticsEvent, GooseBotAnalytics, GooseBotReposResponse, RoutingPrefs}; + +pub const SWITCHBOARD_URL_ENV: &str = "GOOSE_BOT_SWITCHBOARD_URL"; +pub const INSTALLATION_ID_CONFIG_KEY: &str = "goose_bot_installation_id"; + +pub fn switchboard_url() -> Result { + env::var(SWITCHBOARD_URL_ENV).map_err(|_| { + anyhow!( + "{SWITCHBOARD_URL_ENV} must be set to your Cloudflare switchboard URL (see ui/desktop/.env.example)" + ) + }) +} + +pub fn extract_agent_id(tunnel_url: &str) -> Option { + tunnel_url + .rsplit_once("/tunnel/") + .map(|(_, rest)| rest.split(['/', '?', '#']).next().unwrap_or("").to_string()) +} + +pub async fn fetch_oauth_client_id() -> Result { + #[derive(Deserialize)] + struct OAuthConfig { + oauth_client_id: String, + } + let switchboard = switchboard_url()?; + let res = Client::new() + .get(format!("{switchboard}/goose-bot/oauth-config")) + .send() + .await?; + if !res.status().is_success() { + bail!("switchboard returned {}", res.status()); + } + let cfg: OAuthConfig = res.json().await?; + if cfg.oauth_client_id.trim().is_empty() { + bail!("switchboard returned an empty oauth_client_id"); + } + Ok(cfg.oauth_client_id) +} + +#[derive(Debug, Clone)] +pub struct TunnelSnapshot { + pub url: String, + pub secret: String, +} + +#[derive(Debug, Clone)] +pub struct InstallCredentials { + pub installation_id: u64, + pub tunnel_secret: String, +} + +pub async fn resolve_install_credentials(tunnel: TunnelSnapshot) -> Result { + let tunnel_secret = if tunnel.secret.is_empty() { + Config::global() + .get_secret::("tunnel_secret") + .context("tunnel_secret unavailable; complete setup first")? + } else { + tunnel.secret + }; + let cached = Config::global() + .get_param::(INSTALLATION_ID_CONFIG_KEY) + .ok(); + let agent_id = extract_agent_id(&tunnel.url); + + let resolved = match agent_id { + Some(agent_id) => { + let resolved = resolve_install_id(&agent_id, &tunnel_secret).await?; + if cached != Some(resolved) { + let _ = Config::global() + .set_param(INSTALLATION_ID_CONFIG_KEY, serde_json::json!(resolved)); + } + resolved + } + None => cached.context("tunnel URL is missing the agent id; complete setup first")?, + }; + + Ok(InstallCredentials { + installation_id: resolved, + tunnel_secret, + }) +} + +async fn resolve_install_id(agent_id: &str, tunnel_secret: &str) -> Result { + #[derive(Deserialize)] + struct WhoamiResponse { + installation_id: u64, + } + let switchboard = switchboard_url()?; + let res = Client::new() + .post(format!("{switchboard}/goose-bot/whoami")) + .json(&serde_json::json!({ + "agent_id": agent_id, + "tunnel_secret": tunnel_secret, + })) + .send() + .await?; + if !res.status().is_success() { + let status = res.status(); + let detail = res.text().await.unwrap_or_default(); + bail!("switchboard whoami rejected: {status} {detail}"); + } + let body: WhoamiResponse = res.json().await?; + Ok(body.installation_id) +} + +#[derive(Debug)] +pub struct RegisterInstallRequest { + pub oauth_code: String, + pub agent_id: String, + pub tunnel_secret: String, + pub tunnel_url: String, +} + +pub async fn register_installation(req: RegisterInstallRequest) -> Result { + #[derive(Deserialize)] + struct RegisterResponse { + installation_id: u64, + } + let switchboard = switchboard_url()?; + let body = serde_json::json!({ + "oauth_code": req.oauth_code, + "agent_id": req.agent_id, + "tunnel_secret": req.tunnel_secret, + "tunnel_url": req.tunnel_url, + }); + let res = Client::new() + .post(format!("{switchboard}/goose-bot/register")) + .json(&body) + .send() + .await?; + if !res.status().is_success() { + let status = res.status(); + let detail = res.text().await.unwrap_or_default(); + bail!("switchboard rejected registration: {status} {detail}"); + } + let register: RegisterResponse = res.json().await?; + Ok(register.installation_id) +} + +pub async fn forward_routing_prefs( + creds: &InstallCredentials, + routing: &RoutingPrefs, +) -> Result<()> { + let switchboard = switchboard_url()?; + let res = Client::new() + .put(format!("{switchboard}/goose-bot/routing-prefs")) + .header("X-Install-Id", creds.installation_id.to_string()) + .header("X-Install-Secret", &creds.tunnel_secret) + .json(routing) + .send() + .await?; + if !res.status().is_success() { + let status = res.status(); + let detail = res.text().await.unwrap_or_default(); + bail!("switchboard rejected routing prefs: {status} {detail}"); + } + Ok(()) +} + +pub async fn fetch_repos(creds: &InstallCredentials) -> Result { + let switchboard = switchboard_url()?; + let res = Client::new() + .get(format!("{switchboard}/goose-bot/repos")) + .header("X-Install-Id", creds.installation_id.to_string()) + .header("X-Install-Secret", &creds.tunnel_secret) + .send() + .await?; + if !res.status().is_success() { + let status = res.status(); + let detail = res.text().await.unwrap_or_default(); + bail!("switchboard returned {status}: {detail}"); + } + res.json().await.map_err(Into::into) +} + +pub async fn fetch_analytics(creds: &InstallCredentials) -> Result { + let switchboard = switchboard_url()?; + let res = Client::new() + .get(format!("{switchboard}/goose-bot/analytics")) + .header("X-Install-Id", creds.installation_id.to_string()) + .header("X-Install-Secret", &creds.tunnel_secret) + .send() + .await?; + if !res.status().is_success() { + let status = res.status(); + let detail = res.text().await.unwrap_or_default(); + bail!("switchboard returned {status}: {detail}"); + } + res.json().await.map_err(Into::into) +} + +pub async fn unregister_installation(creds: &InstallCredentials) -> Result<()> { + let switchboard = switchboard_url()?; + let res = Client::new() + .delete(format!("{switchboard}/goose-bot/install")) + .header("X-Install-Id", creds.installation_id.to_string()) + .header("X-Install-Secret", &creds.tunnel_secret) + .send() + .await?; + if !res.status().is_success() { + let status = res.status(); + let detail = res.text().await.unwrap_or_default(); + bail!("switchboard rejected unregister: {status} {detail}"); + } + Ok(()) +} + +pub async fn disconnect_install(tunnel: TunnelSnapshot) -> Result<()> { + if let Ok(creds) = resolve_install_credentials(tunnel).await { + let _ = unregister_installation(&creds).await; + } + super::store::clear_install(Config::global()); + Ok(()) +} + +pub async fn report_analytics_event(tunnel: TunnelSnapshot, event: AnalyticsEvent) { + let Ok(creds) = resolve_install_credentials(tunnel).await else { + return; + }; + let Ok(switchboard) = switchboard_url() else { + return; + }; + let _ = Client::new() + .post(format!("{switchboard}/goose-bot/analytics/event")) + .header("X-Install-Id", creds.installation_id.to_string()) + .header("X-Install-Secret", &creds.tunnel_secret) + .json(&event) + .send() + .await; +} diff --git a/crates/goose/src/goose_bot/types.rs b/crates/goose/src/goose_bot/types.rs new file mode 100644 index 000000000000..1784e8792638 --- /dev/null +++ b/crates/goose/src/goose_bot/types.rs @@ -0,0 +1,73 @@ +use serde::{Deserialize, Serialize}; +use utoipa::ToSchema; + +use super::GooseBotPrefs; + +#[derive(Debug, Deserialize, Clone, ToSchema)] +pub struct GooseBotReviewRequest { + pub github_token: String, + pub repo: String, + pub pr_number: u64, + pub head_sha: String, + pub pr_url: String, + #[serde(default)] + pub check_run_id: Option, + #[serde(default)] + pub comment_id: Option, +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct GooseBotReviewResponse { + pub accepted: bool, +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct GooseBotSetupResponse { + pub installation_id: u64, +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct GooseBotStatusResponse { + pub installation_id: Option, +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct GooseBotDisconnectResponse { + pub disconnected: bool, +} + +#[derive(Debug, Deserialize, Clone, ToSchema)] +pub struct GooseBotCommentRequest { + pub github_token: String, + pub repo: String, + pub pr_number: u64, + pub pr_url: String, + pub comment_body: String, + pub commenter: String, + #[serde(default)] + pub head_ref: String, + #[serde(default)] + pub head_repo: String, + #[serde(default)] + pub comment_id: Option, + /// Omitted in older switchboard payloads (treated as PR); current switchboard always sends this. + #[serde(default = "is_pr_absent_legacy_default")] + pub is_pr: bool, +} + +fn is_pr_absent_legacy_default() -> bool { + true +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct GooseBotPrefsResponse { + pub prefs: GooseBotPrefs, + pub switchboard_synced: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub switchboard_error: Option, +} + +#[derive(Debug, Deserialize, ToSchema)] +pub struct GooseBotPrefsRequest { + pub prefs: GooseBotPrefs, +} diff --git a/crates/goose/src/lib.rs b/crates/goose/src/lib.rs index 4b19247d8239..5c8463677763 100644 --- a/crates/goose/src/lib.rs +++ b/crates/goose/src/lib.rs @@ -16,6 +16,7 @@ pub mod download_manager; pub mod execution; pub mod gateway; pub mod goose_apps; +pub mod goose_bot; pub mod hints; pub mod hooks; pub mod instance_id; diff --git a/crates/goose/tests/goose_bot_integration_test.rs b/crates/goose/tests/goose_bot_integration_test.rs new file mode 100644 index 000000000000..9f0129fe5384 --- /dev/null +++ b/crates/goose/tests/goose_bot_integration_test.rs @@ -0,0 +1,123 @@ +use goose::config::Config; +use goose::goose_bot::{ + cached_installation_id, clear_install, extract_agent_id, load_prefs_from, save_prefs_to, + GooseBotCommentRequest, GooseBotPrefs, ReviewSeverity, RoutingPrefs, TriggerPreference, + INSTALLATION_ID_CONFIG_KEY, +}; +use tempfile::NamedTempFile; + +fn isolated_config() -> Config { + let config_file = NamedTempFile::new().unwrap(); + let secrets_file = NamedTempFile::new().unwrap(); + Config::new_with_file_secrets(config_file.path(), secrets_file.path()).unwrap() +} + +#[test] +fn prefs_roundtrip_through_isolated_config() { + let config = isolated_config(); + let prefs = GooseBotPrefs { + auto_review_on_pr_open: false, + trigger_preference: TriggerPreference::ManualOnly, + review_severity: ReviewSeverity::High, + custom_instructions: "be thorough".into(), + ..Default::default() + }; + prefs.validate().unwrap(); + save_prefs_to(&config, &prefs).unwrap(); + assert_eq!(load_prefs_from(&config), prefs); +} + +#[test] +fn clear_install_removes_id_and_prefs() { + let config = isolated_config(); + config + .set_param(INSTALLATION_ID_CONFIG_KEY, serde_json::json!(99_u64)) + .unwrap(); + save_prefs_to( + &config, + &GooseBotPrefs { + custom_instructions: "gone".into(), + ..Default::default() + }, + ) + .unwrap(); + clear_install(&config); + assert_eq!(cached_installation_id(&config), None); + assert_eq!(load_prefs_from(&config), GooseBotPrefs::default()); +} + +#[test] +fn routing_default_matches_switchboard_fixture() { + let routing = RoutingPrefs::default(); + let actual = serde_json::to_string(&routing).unwrap(); + let expected = + include_str!("../../../services/goose-bot-switchboard/fixtures/routing_prefs_default.json") + .trim(); + assert_eq!(actual, expected); +} + +#[test] +fn routing_subset_strips_non_routing_fields() { + let prefs = GooseBotPrefs { + custom_instructions: "full prefs".into(), + review_severity: ReviewSeverity::Critical, + specific_users_allowlist: vec!["octocat".into()], + ..Default::default() + }; + prefs.validate().unwrap(); + let routing = prefs.routing_subset(); + assert_eq!( + routing.specific_users_allowlist, + vec!["octocat".to_string()] + ); + assert_eq!(routing.auto_review_on_pr_open, prefs.auto_review_on_pr_open); + let json = serde_json::to_value(&routing).unwrap(); + assert!(json.get("custom_instructions").is_none()); + assert!(json.get("review_severity").is_none()); +} + +#[test] +fn extract_agent_id_parses_tunnel_url() { + assert_eq!( + extract_agent_id("https://tunnel-proxy.example/tunnel/abc123"), + Some("abc123".to_string()) + ); + assert_eq!( + extract_agent_id("https://tunnel-proxy.example/tunnel/abc123/extra?q=1"), + Some("abc123".to_string()) + ); + assert_eq!(extract_agent_id("https://example.com/no-tunnel-path"), None); +} + +#[test] +fn comment_request_is_pr_explicit_false() { + let req: GooseBotCommentRequest = serde_json::from_str( + r#"{ + "github_token": "t", + "repo": "o/r", + "pr_number": 1, + "pr_url": "https://github.com/o/r/issues/1", + "comment_body": "hi", + "commenter": "u", + "is_pr": false + }"#, + ) + .unwrap(); + assert!(!req.is_pr); +} + +#[test] +fn comment_request_is_pr_omitted_defaults_legacy_true() { + let req: GooseBotCommentRequest = serde_json::from_str( + r#"{ + "github_token": "t", + "repo": "o/r", + "pr_number": 1, + "pr_url": "https://github.com/o/r/pull/1", + "comment_body": "hi", + "commenter": "u" + }"#, + ) + .unwrap(); + assert!(req.is_pr); +} diff --git a/goose-self-test.yaml b/goose-self-test.yaml index 96e713201b85..ff06c8a74d56 100644 --- a/goose-self-test.yaml +++ b/goose-self-test.yaml @@ -13,6 +13,7 @@ activities: - Test load tool for knowledge injection and discovery - Test delegate tool for task delegation (sync and async) - Test error boundaries including nested delegation prevention + - Test Goose Bot prefs persistence (when goosed is reachable) - Generate comprehensive test report parameters: @@ -369,6 +370,20 @@ prompt: | Log results to: {{ workspace_dir }}/phase4_advanced.md {% endif %} + {% if test_phases == "all" or "goose_bot" in test_phases %} + ## 🤖 PHASE: Goose Bot prefs (optional) + + Skip if `GOOSE_BOT_SWITCHBOARD_URL` is unset or goosed is not running. + + With the goosed base URL and `X-Secret-Key`: + 1. `GET /goose-bot/prefs` — expect 200 and `schema_version` in the body. + 2. `PUT /goose-bot/prefs` with `custom_instructions` set to `self-test ping` (keep other fields valid). + 3. `GET /goose-bot/prefs` again — confirm `custom_instructions` persisted. + 4. Restore any prefs you changed for production use. + + Log results to: {{ workspace_dir }}/phase_goose_bot_prefs.md + {% endif %} + ## 📊 PHASE 5: Final Report Generation Create TWO reports: diff --git a/services/goose-bot-switchboard/.gitignore b/services/goose-bot-switchboard/.gitignore new file mode 100644 index 000000000000..666258c9a5ed --- /dev/null +++ b/services/goose-bot-switchboard/.gitignore @@ -0,0 +1,7 @@ +# Operator-specific Worker config (KV namespace ID, account, etc.). +# Copy from wrangler.toml.example and fill in your values. +wrangler.toml + +# Wrangler local state +.wrangler/ +.dev.vars diff --git a/services/goose-bot-switchboard/fixtures/routing_prefs_default.json b/services/goose-bot-switchboard/fixtures/routing_prefs_default.json new file mode 100644 index 000000000000..c05f989db8d7 --- /dev/null +++ b/services/goose-bot-switchboard/fixtures/routing_prefs_default.json @@ -0,0 +1 @@ +{"schema_version":1,"auto_review_on_pr_open":false,"trigger_preference":"pr-open","trigger_permission":"anyone","allow_act_on_issues":false,"specific_users_allowlist":[]} diff --git a/services/goose-bot-switchboard/package.json b/services/goose-bot-switchboard/package.json new file mode 100644 index 000000000000..bc4eaae4b1c4 --- /dev/null +++ b/services/goose-bot-switchboard/package.json @@ -0,0 +1,20 @@ +{ + "name": "goose-bot-switchboard", + "version": "0.1.0", + "private": true, + "description": "Webhook switchboard for the Goose Bot GitHub App. Verifies GitHub webhooks and routes PR reviews into the user's local goosed via the lapstone tunnel. Stores no API keys, no user code.", + "scripts": { + "dev": "wrangler dev", + "deploy": "wrangler deploy", + "test": "vitest run", + "typecheck": "tsc --noEmit", + "cf-typegen": "wrangler types" + }, + "devDependencies": { + "@cloudflare/vitest-pool-workers": "^0.12.4", + "@cloudflare/workers-types": "^4.20251101.0", + "typescript": "^5.5.2", + "vitest": "~3.2.0", + "wrangler": "^4.84.1" + } +} diff --git a/services/goose-bot-switchboard/pnpm-lock.yaml b/services/goose-bot-switchboard/pnpm-lock.yaml new file mode 100644 index 000000000000..cf28d3995e9d --- /dev/null +++ b/services/goose-bot-switchboard/pnpm-lock.yaml @@ -0,0 +1,2015 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + devDependencies: + '@cloudflare/vitest-pool-workers': + specifier: ^0.12.4 + version: 0.12.21(@cloudflare/workers-types@4.20260510.1)(@vitest/runner@3.2.4)(@vitest/snapshot@3.2.4)(vitest@3.2.4) + '@cloudflare/workers-types': + specifier: ^4.20251101.0 + version: 4.20260510.1 + typescript: + specifier: ^5.5.2 + version: 5.9.3 + vitest: + specifier: ~3.2.0 + version: 3.2.4 + wrangler: + specifier: ^4.84.1 + version: 4.90.0(@cloudflare/workers-types@4.20260510.1) + +packages: + + '@cloudflare/kv-asset-handler@0.4.2': + resolution: {integrity: sha512-SIOD2DxrRRwQ+jgzlXCqoEFiKOFqaPjhnNTGKXSRLvp1HiOvapLaFG2kEr9dYQTYe8rKrd9uvDUzmAITeNyaHQ==} + engines: {node: '>=18.0.0'} + + '@cloudflare/kv-asset-handler@0.5.0': + resolution: {integrity: sha512-jxQYkj8dSIzc0cD6cMMNdOc1UVjqSqu8BZdor5s8cGjW2I8BjODt/kWPVdY+u9zj3ms75Q5qaZgnxUad83+eAg==} + engines: {node: '>=22.0.0'} + + '@cloudflare/unenv-preset@2.15.0': + resolution: {integrity: sha512-EGYmJaGZKWl+X8tXxcnx4v2bOZSjQeNI5dWFeXivgX9+YCT69AkzHHwlNbVpqtEUTbew8eQurpyOpeN8fg00nw==} + peerDependencies: + unenv: 2.0.0-rc.24 + workerd: 1.20260301.1 || ~1.20260302.1 || ~1.20260303.1 || ~1.20260304.1 || >1.20260305.0 <2.0.0-0 + peerDependenciesMeta: + workerd: + optional: true + + '@cloudflare/unenv-preset@2.16.1': + resolution: {integrity: sha512-ECxObrMfyTl5bhQf/lZCXwo5G6xX9IAUo+nDMKK4SZ8m4Jvvxp52vilxyySSWh2YTZz8+HQ07qGH/2rEom1vDw==} + peerDependencies: + unenv: 2.0.0-rc.24 + workerd: '>1.20260305.0 <2.0.0-0' + peerDependenciesMeta: + workerd: + optional: true + + '@cloudflare/vitest-pool-workers@0.12.21': + resolution: {integrity: sha512-xqvqVR+qAhekXWaTNY36UtFFmHrz13yGUoWVGOu6LDC2ABiQqI1E1lQ3eUZY8KVB+1FXY/mP5dB6oD07XUGnPg==} + peerDependencies: + '@vitest/runner': 2.0.x - 3.2.x + '@vitest/snapshot': 2.0.x - 3.2.x + vitest: 2.0.x - 3.2.x + + '@cloudflare/workerd-darwin-64@1.20260310.1': + resolution: {integrity: sha512-hF2VpoWaMb1fiGCQJqCY6M8I+2QQqjkyY4LiDYdTL5D/w6C1l5v1zhc0/jrjdD1DXfpJtpcSMSmEPjHse4p9Ig==} + engines: {node: '>=16'} + cpu: [x64] + os: [darwin] + + '@cloudflare/workerd-darwin-64@1.20260507.1': + resolution: {integrity: sha512-S85aMwcaPJUjKWDiG6iMMnioKWtPLACa6m0j/EhHR1GYfVpnxb974cBc6d25L+sf7jHWHJI2u5hGp0UTJ7MtXQ==} + engines: {node: '>=16'} + cpu: [x64] + os: [darwin] + + '@cloudflare/workerd-darwin-arm64@1.20260310.1': + resolution: {integrity: sha512-h/Vl3XrYYPI6yFDE27XO1QPq/1G1lKIM8tzZGIWYpntK3IN5XtH3Ee/sLaegpJ49aIJoqhF2mVAZ6Yw+Vk2gJw==} + engines: {node: '>=16'} + cpu: [arm64] + os: [darwin] + + '@cloudflare/workerd-darwin-arm64@1.20260507.1': + resolution: {integrity: sha512-GMEBu8Zp9Q97HLnf7bWJN4KjWpN5MxpeqdvHjBGWNl8UYprJI0k+Jkp89+Wh5S8vIon+HoVbDfOzPa7VwgL6Eg==} + engines: {node: '>=16'} + cpu: [arm64] + os: [darwin] + + '@cloudflare/workerd-linux-64@1.20260310.1': + resolution: {integrity: sha512-XzQ0GZ8G5P4d74bQYOIP2Su4CLdNPpYidrInaSOuSxMw+HamsHaFrjVsrV2mPy/yk2hi6SY2yMbgKFK9YjA7vw==} + engines: {node: '>=16'} + cpu: [x64] + os: [linux] + + '@cloudflare/workerd-linux-64@1.20260507.1': + resolution: {integrity: sha512-QlrKEBdgA3uVc0Ok0Q3+0/CW0CTjgj5ySir1i1YY5FXVv0X6GpwtnB5umjunjF2MFprss+L+iFGZzxcSvMC1nA==} + engines: {node: '>=16'} + cpu: [x64] + os: [linux] + + '@cloudflare/workerd-linux-arm64@1.20260310.1': + resolution: {integrity: sha512-sxv4CxnN4ZR0uQGTFVGa0V4KTqwdej/czpIc5tYS86G8FQQoGIBiAIs2VvU7b8EROPcandxYHDBPTb+D9HIMPw==} + engines: {node: '>=16'} + cpu: [arm64] + os: [linux] + + '@cloudflare/workerd-linux-arm64@1.20260507.1': + resolution: {integrity: sha512-eGbbupEtK2nh9V9Dhcx3vv3GTKeXqSVNgAEYVCCN0NGS9tl9HbMoHRX/4JL181FKXROMigWBCQVL//qPhsAzBQ==} + engines: {node: '>=16'} + cpu: [arm64] + os: [linux] + + '@cloudflare/workerd-windows-64@1.20260310.1': + resolution: {integrity: sha512-+1ZTViWKJypLfgH/luAHCqkent0DEBjAjvO40iAhOMHRLYP/SPphLvr4Jpi6lb+sIocS8Q1QZL4uM5Etg1Wskg==} + engines: {node: '>=16'} + cpu: [x64] + os: [win32] + + '@cloudflare/workerd-windows-64@1.20260507.1': + resolution: {integrity: sha512-dmClJ/E0BAcuDetQIZFqbeAXejWrG5pysGRMQ6T83Y0IW/7IAamY2zFEkAJ10I5xwZsdHuYsZtzlOxpEXpJs7A==} + engines: {node: '>=16'} + cpu: [x64] + os: [win32] + + '@cloudflare/workers-types@4.20260510.1': + resolution: {integrity: sha512-Wcmb56nJMHw1BLpArV3RSmWb/z0Zx3S8OJ5mVUTb+AVTbyopU9iJzZrFGlYX18Ju9hXxqak2mhFMq6sCaFssag==} + + '@cspotcode/source-map-support@0.8.1': + resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==} + engines: {node: '>=12'} + + '@emnapi/runtime@1.10.0': + resolution: {integrity: sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==} + + '@esbuild/aix-ppc64@0.27.3': + resolution: {integrity: sha512-9fJMTNFTWZMh5qwrBItuziu834eOCUcEqymSH7pY+zoMVEZg3gcPuBNxH1EvfVYe9h0x/Ptw8KBzv7qxb7l8dg==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] + + '@esbuild/aix-ppc64@0.27.7': + resolution: {integrity: sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] + + '@esbuild/android-arm64@0.27.3': + resolution: {integrity: sha512-YdghPYUmj/FX2SYKJ0OZxf+iaKgMsKHVPF1MAq/P8WirnSpCStzKJFjOjzsW0QQ7oIAiccHdcqjbHmJxRb/dmg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm64@0.27.7': + resolution: {integrity: sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm@0.27.3': + resolution: {integrity: sha512-i5D1hPY7GIQmXlXhs2w8AWHhenb00+GxjxRncS2ZM7YNVGNfaMxgzSGuO8o8SJzRc/oZwU2bcScvVERk03QhzA==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] + + '@esbuild/android-arm@0.27.7': + resolution: {integrity: sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] + + '@esbuild/android-x64@0.27.3': + resolution: {integrity: sha512-IN/0BNTkHtk8lkOM8JWAYFg4ORxBkZQf9zXiEOfERX/CzxW3Vg1ewAhU7QSWQpVIzTW+b8Xy+lGzdYXV6UZObQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] + + '@esbuild/android-x64@0.27.7': + resolution: {integrity: sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] + + '@esbuild/darwin-arm64@0.27.3': + resolution: {integrity: sha512-Re491k7ByTVRy0t3EKWajdLIr0gz2kKKfzafkth4Q8A5n1xTHrkqZgLLjFEHVD+AXdUGgQMq+Godfq45mGpCKg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-arm64@0.27.7': + resolution: {integrity: sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-x64@0.27.3': + resolution: {integrity: sha512-vHk/hA7/1AckjGzRqi6wbo+jaShzRowYip6rt6q7VYEDX4LEy1pZfDpdxCBnGtl+A5zq8iXDcyuxwtv3hNtHFg==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + + '@esbuild/darwin-x64@0.27.7': + resolution: {integrity: sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + + '@esbuild/freebsd-arm64@0.27.3': + resolution: {integrity: sha512-ipTYM2fjt3kQAYOvo6vcxJx3nBYAzPjgTCk7QEgZG8AUO3ydUhvelmhrbOheMnGOlaSFUoHXB6un+A7q4ygY9w==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-arm64@0.27.7': + resolution: {integrity: sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.27.3': + resolution: {integrity: sha512-dDk0X87T7mI6U3K9VjWtHOXqwAMJBNN2r7bejDsc+j03SEjtD9HrOl8gVFByeM0aJksoUuUVU9TBaZa2rgj0oA==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.27.7': + resolution: {integrity: sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + + '@esbuild/linux-arm64@0.27.3': + resolution: {integrity: sha512-sZOuFz/xWnZ4KH3YfFrKCf1WyPZHakVzTiqji3WDc0BCl2kBwiJLCXpzLzUBLgmp4veFZdvN5ChW4Eq/8Fc2Fg==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm64@0.27.7': + resolution: {integrity: sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm@0.27.3': + resolution: {integrity: sha512-s6nPv2QkSupJwLYyfS+gwdirm0ukyTFNl3KTgZEAiJDd+iHZcbTPPcWCcRYH+WlNbwChgH2QkE9NSlNrMT8Gfw==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-arm@0.27.7': + resolution: {integrity: sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-ia32@0.27.3': + resolution: {integrity: sha512-yGlQYjdxtLdh0a3jHjuwOrxQjOZYD/C9PfdbgJJF3TIZWnm/tMd/RcNiLngiu4iwcBAOezdnSLAwQDPqTmtTYg==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-ia32@0.27.7': + resolution: {integrity: sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-loong64@0.27.3': + resolution: {integrity: sha512-WO60Sn8ly3gtzhyjATDgieJNet/KqsDlX5nRC5Y3oTFcS1l0KWba+SEa9Ja1GfDqSF1z6hif/SkpQJbL63cgOA==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-loong64@0.27.7': + resolution: {integrity: sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-mips64el@0.27.3': + resolution: {integrity: sha512-APsymYA6sGcZ4pD6k+UxbDjOFSvPWyZhjaiPyl/f79xKxwTnrn5QUnXR5prvetuaSMsb4jgeHewIDCIWljrSxw==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-mips64el@0.27.7': + resolution: {integrity: sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-ppc64@0.27.3': + resolution: {integrity: sha512-eizBnTeBefojtDb9nSh4vvVQ3V9Qf9Df01PfawPcRzJH4gFSgrObw+LveUyDoKU3kxi5+9RJTCWlj4FjYXVPEA==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-ppc64@0.27.7': + resolution: {integrity: sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-riscv64@0.27.3': + resolution: {integrity: sha512-3Emwh0r5wmfm3ssTWRQSyVhbOHvqegUDRd0WhmXKX2mkHJe1SFCMJhagUleMq+Uci34wLSipf8Lagt4LlpRFWQ==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-riscv64@0.27.7': + resolution: {integrity: sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-s390x@0.27.3': + resolution: {integrity: sha512-pBHUx9LzXWBc7MFIEEL0yD/ZVtNgLytvx60gES28GcWMqil8ElCYR4kvbV2BDqsHOvVDRrOxGySBM9Fcv744hw==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-s390x@0.27.7': + resolution: {integrity: sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-x64@0.27.3': + resolution: {integrity: sha512-Czi8yzXUWIQYAtL/2y6vogER8pvcsOsk5cpwL4Gk5nJqH5UZiVByIY8Eorm5R13gq+DQKYg0+JyQoytLQas4dA==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + + '@esbuild/linux-x64@0.27.7': + resolution: {integrity: sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + + '@esbuild/netbsd-arm64@0.27.3': + resolution: {integrity: sha512-sDpk0RgmTCR/5HguIZa9n9u+HVKf40fbEUt+iTzSnCaGvY9kFP0YKBWZtJaraonFnqef5SlJ8/TiPAxzyS+UoA==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + + '@esbuild/netbsd-arm64@0.27.7': + resolution: {integrity: sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.27.3': + resolution: {integrity: sha512-P14lFKJl/DdaE00LItAukUdZO5iqNH7+PjoBm+fLQjtxfcfFE20Xf5CrLsmZdq5LFFZzb5JMZ9grUwvtVYzjiA==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.27.7': + resolution: {integrity: sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + + '@esbuild/openbsd-arm64@0.27.3': + resolution: {integrity: sha512-AIcMP77AvirGbRl/UZFTq5hjXK+2wC7qFRGoHSDrZ5v5b8DK/GYpXW3CPRL53NkvDqb9D+alBiC/dV0Fb7eJcw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + + '@esbuild/openbsd-arm64@0.27.7': + resolution: {integrity: sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.27.3': + resolution: {integrity: sha512-DnW2sRrBzA+YnE70LKqnM3P+z8vehfJWHXECbwBmH/CU51z6FiqTQTHFenPlHmo3a8UgpLyH3PT+87OViOh1AQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.27.7': + resolution: {integrity: sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openharmony-arm64@0.27.3': + resolution: {integrity: sha512-NinAEgr/etERPTsZJ7aEZQvvg/A6IsZG/LgZy+81wON2huV7SrK3e63dU0XhyZP4RKGyTm7aOgmQk0bGp0fy2g==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openharmony] + + '@esbuild/openharmony-arm64@0.27.7': + resolution: {integrity: sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openharmony] + + '@esbuild/sunos-x64@0.27.3': + resolution: {integrity: sha512-PanZ+nEz+eWoBJ8/f8HKxTTD172SKwdXebZ0ndd953gt1HRBbhMsaNqjTyYLGLPdoWHy4zLU7bDVJztF5f3BHA==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + + '@esbuild/sunos-x64@0.27.7': + resolution: {integrity: sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + + '@esbuild/win32-arm64@0.27.3': + resolution: {integrity: sha512-B2t59lWWYrbRDw/tjiWOuzSsFh1Y/E95ofKz7rIVYSQkUYBjfSgf6oeYPNWHToFRr2zx52JKApIcAS/D5TUBnA==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-arm64@0.27.7': + resolution: {integrity: sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-ia32@0.27.3': + resolution: {integrity: sha512-QLKSFeXNS8+tHW7tZpMtjlNb7HKau0QDpwm49u0vUp9y1WOF+PEzkU84y9GqYaAVW8aH8f3GcBck26jh54cX4Q==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-ia32@0.27.7': + resolution: {integrity: sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-x64@0.27.3': + resolution: {integrity: sha512-4uJGhsxuptu3OcpVAzli+/gWusVGwZZHTlS63hh++ehExkVT8SgiEf7/uC/PclrPPkLhZqGgCTjd0VWLo6xMqA==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + + '@esbuild/win32-x64@0.27.7': + resolution: {integrity: sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + + '@img/colour@1.1.0': + resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==} + engines: {node: '>=18'} + + '@img/sharp-darwin-arm64@0.34.5': + resolution: {integrity: sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + cpu: [arm64] + os: [darwin] + + '@img/sharp-darwin-x64@0.34.5': + resolution: {integrity: sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + cpu: [x64] + os: [darwin] + + '@img/sharp-libvips-darwin-arm64@1.2.4': + resolution: {integrity: sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==} + cpu: [arm64] + os: [darwin] + + '@img/sharp-libvips-darwin-x64@1.2.4': + resolution: {integrity: sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==} + cpu: [x64] + os: [darwin] + + '@img/sharp-libvips-linux-arm64@1.2.4': + resolution: {integrity: sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-arm@1.2.4': + resolution: {integrity: sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==} + cpu: [arm] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-ppc64@1.2.4': + resolution: {integrity: sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-riscv64@1.2.4': + resolution: {integrity: sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-s390x@1.2.4': + resolution: {integrity: sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-x64@1.2.4': + resolution: {integrity: sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linuxmusl-arm64@1.2.4': + resolution: {integrity: sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@img/sharp-libvips-linuxmusl-x64@1.2.4': + resolution: {integrity: sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@img/sharp-linux-arm64@0.34.5': + resolution: {integrity: sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-arm@0.34.5': + resolution: {integrity: sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + cpu: [arm] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-ppc64@0.34.5': + resolution: {integrity: sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-riscv64@0.34.5': + resolution: {integrity: sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-s390x@0.34.5': + resolution: {integrity: sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-x64@0.34.5': + resolution: {integrity: sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@img/sharp-linuxmusl-arm64@0.34.5': + resolution: {integrity: sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@img/sharp-linuxmusl-x64@0.34.5': + resolution: {integrity: sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@img/sharp-wasm32@0.34.5': + resolution: {integrity: sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + cpu: [wasm32] + + '@img/sharp-win32-arm64@0.34.5': + resolution: {integrity: sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + cpu: [arm64] + os: [win32] + + '@img/sharp-win32-ia32@0.34.5': + resolution: {integrity: sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + cpu: [ia32] + os: [win32] + + '@img/sharp-win32-x64@0.34.5': + resolution: {integrity: sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + cpu: [x64] + os: [win32] + + '@jridgewell/resolve-uri@3.1.2': + resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} + engines: {node: '>=6.0.0'} + + '@jridgewell/sourcemap-codec@1.5.5': + resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==} + + '@jridgewell/trace-mapping@0.3.9': + resolution: {integrity: sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==} + + '@poppinss/colors@4.1.6': + resolution: {integrity: sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==} + + '@poppinss/dumper@0.6.5': + resolution: {integrity: sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==} + + '@poppinss/exception@1.2.3': + resolution: {integrity: sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==} + + '@rollup/rollup-android-arm-eabi@4.60.3': + resolution: {integrity: sha512-x35CNW/ANXG3hE/EZpRU8MXX1JDN86hBb2wMGAtltkz7pc6cxgjpy1OMMfDosOQ+2hWqIkag/fGok1Yady9nGw==} + cpu: [arm] + os: [android] + + '@rollup/rollup-android-arm64@4.60.3': + resolution: {integrity: sha512-xw3xtkDApIOGayehp2+Rz4zimfkaX65r4t47iy+ymQB2G4iJCBBfj0ogVg5jpvjpn8UWn/+q9tprxleYeNp3Hw==} + cpu: [arm64] + os: [android] + + '@rollup/rollup-darwin-arm64@4.60.3': + resolution: {integrity: sha512-vo6Y5Qfpx7/5EaamIwi0WqW2+zfiusVihKatLvtN1VFVy3D13uERk/6gZLU1UiHRL6fDXqj/ELIeVRGnvcTE1g==} + cpu: [arm64] + os: [darwin] + + '@rollup/rollup-darwin-x64@4.60.3': + resolution: {integrity: sha512-D+0QGcZhBzTN82weOnsSlY7V7+RMmPuF1CkbxyMAGE8+ZHeUjyb76ZiWmBlCu//AQQONvxcqRbwZTajZKqjuOw==} + cpu: [x64] + os: [darwin] + + '@rollup/rollup-freebsd-arm64@4.60.3': + resolution: {integrity: sha512-6HnvHCT7fDyj6R0Ph7A6x8dQS/S38MClRWeDLqc0MdfWkxjiu1HSDYrdPhqSILzjTIC/pnXbbJbo+ft+gy/9hQ==} + cpu: [arm64] + os: [freebsd] + + '@rollup/rollup-freebsd-x64@4.60.3': + resolution: {integrity: sha512-KHLgC3WKlUYW3ShFKnnosZDOJ0xjg9zp7au3sIm2bs/tGBeC2ipmvRh/N7JKi0t9Ue20C0dpEshi8WUubg+cnA==} + cpu: [x64] + os: [freebsd] + + '@rollup/rollup-linux-arm-gnueabihf@4.60.3': + resolution: {integrity: sha512-DV6fJoxEYWJOvaZIsok7KrYl0tPvga5OZ2yvKHNNYyk/2roMLqQAbGhr78EQ5YhHpnhLKJD3S1WFusAkmUuV5g==} + cpu: [arm] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-arm-musleabihf@4.60.3': + resolution: {integrity: sha512-mQKoJAzvuOs6F+TZybQO4GOTSMUu7v0WdxEk24krQ/uUxXoPTtHjuaUuPmFhtBcM4K0ons8nrE3JyhTuCFtT/w==} + cpu: [arm] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-arm64-gnu@4.60.3': + resolution: {integrity: sha512-Whjj2qoiJ6+OOJMGptTYazaJvjOJm+iKHpXQM1P3LzGjt7Ff++Tp7nH4N8J/BUA7R9IHfDyx4DJIflifwnbmIA==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-arm64-musl@4.60.3': + resolution: {integrity: sha512-4YTNHKqGng5+yiZt3mg77nmyuCfmNfX4fPmyUapBcIk+BdwSwmCWGXOUxhXbBEkFHtoN5boLj/5NON+u5QC9tg==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-loong64-gnu@4.60.3': + resolution: {integrity: sha512-SU3kNlhkpI4UqlUc2VXPGK9o886ZsSeGfMAX2ba2b8DKmMXq4AL7KUrkSWVbb7koVqx41Yczx6dx5PNargIrEA==} + cpu: [loong64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-loong64-musl@4.60.3': + resolution: {integrity: sha512-6lDLl5h4TXpB1mTf2rQWnAk/LcXrx9vBfu/DT5TIPhvMhRWaZ5MxkIc8u4lJAmBo6klTe1ywXIUHFjylW505sg==} + cpu: [loong64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-ppc64-gnu@4.60.3': + resolution: {integrity: sha512-BMo8bOw8evlup/8G+cj5xWtPyp93xPdyoSN16Zy90Q2QZ0ZYRhCt6ZJSwbrRzG9HApFabjwj2p25TUPDWrhzqQ==} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-ppc64-musl@4.60.3': + resolution: {integrity: sha512-E0L8X1dZN1/Rph+5VPF6Xj2G7JJvMACVXtamTJIDrVI44Y3K+G8gQaMEAavbqCGTa16InptiVrX6eM6pmJ+7qA==} + cpu: [ppc64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-riscv64-gnu@4.60.3': + resolution: {integrity: sha512-oZJ/WHaVfHUiRAtmTAeo3DcevNsVvH8mbvodjZy7D5QKvCefO371SiKRpxoDcCxB3PTRTLayWBkvmDQKTcX/sw==} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-riscv64-musl@4.60.3': + resolution: {integrity: sha512-Dhbyh7j9FybM3YaTgaHmVALwA8AkUwTPccyCQ79TG9AJUsMQqgN1DDEZNr4+QUfwiWvLDumW5vdwzoeUF+TNxQ==} + cpu: [riscv64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-s390x-gnu@4.60.3': + resolution: {integrity: sha512-cJd1X5XhHHlltkaypz1UcWLA8AcoIi1aWhsvaWDskD1oz2eKCypnqvTQ8ykMNI0RSmm7NkTdSqSSD7zM0xa6Ig==} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-x64-gnu@4.60.3': + resolution: {integrity: sha512-DAZDBHQfG2oQuhY7mc6I3/qB4LU2fQCjRvxbDwd/Jdvb9fypP4IJ4qmtu6lNjes6B531AI8cg1aKC2di97bUxA==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-x64-musl@4.60.3': + resolution: {integrity: sha512-cRxsE8c13mZOh3vP+wLDxpQBRrOHDIGOWyDL93Sy0Ga8y515fBcC2pjUfFwUe5T7tqvTvWbCpg1URM/AXdWIXA==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rollup/rollup-openbsd-x64@4.60.3': + resolution: {integrity: sha512-QaWcIgRxqEdQdhJqW4DJctsH6HCmo5vHxY0krHSX4jMtOqfzC+dqDGuHM87bu4H8JBeibWx7jFz+h6/4C8wA5Q==} + cpu: [x64] + os: [openbsd] + + '@rollup/rollup-openharmony-arm64@4.60.3': + resolution: {integrity: sha512-AaXwSvUi3QIPtroAUw1t5yHGIyqKEXwH54WUocFolZhpGDruJcs8c+xPNDRn4XiQsS7MEwnYsHW2l0MBLDMkWg==} + cpu: [arm64] + os: [openharmony] + + '@rollup/rollup-win32-arm64-msvc@4.60.3': + resolution: {integrity: sha512-65LAKM/bAWDqKNEelHlcHvm2V+Vfb8C6INFxQXRHCvaVN1rJfwr4NvdP4FyzUaLqWfaCGaadf6UbTm8xJeYfEg==} + cpu: [arm64] + os: [win32] + + '@rollup/rollup-win32-ia32-msvc@4.60.3': + resolution: {integrity: sha512-EEM2gyhBF5MFnI6vMKdX1LAosE627RGBzIoGMdLloPZkXrUN0Ckqgr2Qi8+J3zip/8NVVro3/FjB+tjhZUgUHA==} + cpu: [ia32] + os: [win32] + + '@rollup/rollup-win32-x64-gnu@4.60.3': + resolution: {integrity: sha512-E5Eb5H/DpxaoXH++Qkv28RcUJboMopmdDUALBczvHMf7hNIxaDZqwY5lK12UK1BHacSmvupoEWGu+n993Z0y1A==} + cpu: [x64] + os: [win32] + + '@rollup/rollup-win32-x64-msvc@4.60.3': + resolution: {integrity: sha512-hPt/bgL5cE+Qp+/TPHBqptcAgPzgj46mPcg/16zNUmbQk0j+mOEQV/+Lqu8QRtDV3Ek95Q6FeFITpuhl6OTsAA==} + cpu: [x64] + os: [win32] + + '@sindresorhus/is@7.2.0': + resolution: {integrity: sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==} + engines: {node: '>=18'} + + '@speed-highlight/core@1.2.15': + resolution: {integrity: sha512-BMq1K3DsElxDWawkX6eLg9+CKJrTVGCBAWVuHXVUV2u0s2711qiChLSId6ikYPfxhdYocLNt3wWwSvDiTvFabw==} + + '@types/chai@5.2.3': + resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} + + '@types/deep-eql@4.0.2': + resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} + + '@types/estree@1.0.8': + resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==} + + '@types/estree@1.0.9': + resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + + '@vitest/expect@3.2.4': + resolution: {integrity: sha512-Io0yyORnB6sikFlt8QW5K7slY4OjqNX9jmJQ02QDda8lyM6B5oNgVWoSoKPac8/kgnCUzuHQKrSLtu/uOqqrig==} + + '@vitest/mocker@3.2.4': + resolution: {integrity: sha512-46ryTE9RZO/rfDd7pEqFl7etuyzekzEhUbTW3BvmeO/BcCMEgq59BKhek3dXDWgAj4oMK6OZi+vRr1wPW6qjEQ==} + peerDependencies: + msw: ^2.4.9 + vite: ^5.0.0 || ^6.0.0 || ^7.0.0-0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/pretty-format@3.2.4': + resolution: {integrity: sha512-IVNZik8IVRJRTr9fxlitMKeJeXFFFN0JaB9PHPGQ8NKQbGpfjlTx9zO4RefN8gp7eqjNy8nyK3NZmBzOPeIxtA==} + + '@vitest/runner@3.2.4': + resolution: {integrity: sha512-oukfKT9Mk41LreEW09vt45f8wx7DordoWUZMYdY/cyAk7w5TWkTRCNZYF7sX7n2wB7jyGAl74OxgwhPgKaqDMQ==} + + '@vitest/snapshot@3.2.4': + resolution: {integrity: sha512-dEYtS7qQP2CjU27QBC5oUOxLE/v5eLkGqPE0ZKEIDGMs4vKWe7IjgLOeauHsR0D5YuuycGRO5oSRXnwnmA78fQ==} + + '@vitest/spy@3.2.4': + resolution: {integrity: sha512-vAfasCOe6AIK70iP5UD11Ac4siNUNJ9i/9PZ3NKx07sG6sUxeag1LWdNrMWeKKYBLlzuK+Gn65Yd5nyL6ds+nw==} + + '@vitest/utils@3.2.4': + resolution: {integrity: sha512-fB2V0JFrQSMsCo9HiSq3Ezpdv4iYaXRG1Sx8edX3MwxfyNn83mKiGzOcH+Fkxt4MHxr3y42fQi1oeAInqgX2QA==} + + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + + blake3-wasm@2.1.5: + resolution: {integrity: sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==} + + cac@6.7.14: + resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==} + engines: {node: '>=8'} + + chai@5.3.3: + resolution: {integrity: sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==} + engines: {node: '>=18'} + + check-error@2.1.3: + resolution: {integrity: sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==} + engines: {node: '>= 16'} + + cjs-module-lexer@1.4.3: + resolution: {integrity: sha512-9z8TZaGM1pfswYeXrUpzPrkx8UnWYdhJclsiYMm6x/w5+nN+8Tf/LnAgfLGQCm59qAOxU8WwHEq2vNwF6i4j+Q==} + + cookie@1.1.1: + resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==} + engines: {node: '>=18'} + + debug@4.4.3: + resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} + engines: {node: '>=6.0'} + peerDependencies: + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + + deep-eql@5.0.2: + resolution: {integrity: sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==} + engines: {node: '>=6'} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + error-stack-parser-es@1.0.5: + resolution: {integrity: sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==} + + es-module-lexer@1.7.0: + resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==} + + esbuild@0.27.3: + resolution: {integrity: sha512-8VwMnyGCONIs6cWue2IdpHxHnAjzxnw2Zr7MkVxB2vjmQ2ivqGFb4LEG3SMnv0Gb2F/G/2yA8zUaiL1gywDCCg==} + engines: {node: '>=18'} + hasBin: true + + esbuild@0.27.7: + resolution: {integrity: sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==} + engines: {node: '>=18'} + hasBin: true + + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + + expect-type@1.3.0: + resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==} + engines: {node: '>=12.0.0'} + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + js-tokens@9.0.1: + resolution: {integrity: sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==} + + kleur@4.1.5: + resolution: {integrity: sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==} + engines: {node: '>=6'} + + loupe@3.2.1: + resolution: {integrity: sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==} + + magic-string@0.30.21: + resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + + miniflare@4.20260310.0: + resolution: {integrity: sha512-uC5vNPenFpDSj5aUU3wGSABG6UUqMr+Xs1m4AkCrTHo37F4Z6xcQw5BXqViTfPDVT/zcYH1UgTVoXhr1l6ZMXw==} + engines: {node: '>=18.0.0'} + hasBin: true + + miniflare@4.20260507.1: + resolution: {integrity: sha512-PSXBiLExTdZ4UGO/raKCHQauUpYL7F880ZRB7j0+78Rv8h7TsdN2E/iEDK9sK2Y+SPQ5wJSeAa+rDeVKoZZoEw==} + engines: {node: '>=22.0.0'} + hasBin: true + + ms@2.1.3: + resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + + nanoid@3.3.12: + resolution: {integrity: sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + path-to-regexp@6.3.0: + resolution: {integrity: sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==} + + pathe@2.0.3: + resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} + + pathval@2.0.1: + resolution: {integrity: sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==} + engines: {node: '>= 14.16'} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@4.0.4: + resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==} + engines: {node: '>=12'} + + postcss@8.5.14: + resolution: {integrity: sha512-SoSL4+OSEtR99LHFZQiJLkT59C5B1amGO1NzTwj7TT1qCUgUO6hxOvzkOYxD+vMrXBM3XJIKzokoERdqQq/Zmg==} + engines: {node: ^10 || ^12 || >=14} + + rollup@4.60.3: + resolution: {integrity: sha512-pAQK9HalE84QSm4Po3EmWIZPd3FnjkShVkiMlz1iligWYkWQ7wHYd1PF/T7QZ5TVSD6uSTon5gBVMSM4JfBV+A==} + engines: {node: '>=18.0.0', npm: '>=8.0.0'} + hasBin: true + + semver@7.8.0: + resolution: {integrity: sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==} + engines: {node: '>=10'} + hasBin: true + + sharp@0.34.5: + resolution: {integrity: sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==} + engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} + + siginfo@2.0.0: + resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} + + source-map-js@1.2.1: + resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} + engines: {node: '>=0.10.0'} + + stackback@0.0.2: + resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + + std-env@3.10.0: + resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==} + + strip-literal@3.1.0: + resolution: {integrity: sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==} + + supports-color@10.2.2: + resolution: {integrity: sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==} + engines: {node: '>=18'} + + tinybench@2.9.0: + resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} + + tinyexec@0.3.2: + resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==} + + tinyglobby@0.2.16: + resolution: {integrity: sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==} + engines: {node: '>=12.0.0'} + + tinypool@1.1.1: + resolution: {integrity: sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==} + engines: {node: ^18.0.0 || >=20.0.0} + + tinyrainbow@2.0.0: + resolution: {integrity: sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==} + engines: {node: '>=14.0.0'} + + tinyspy@4.0.4: + resolution: {integrity: sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q==} + engines: {node: '>=14.0.0'} + + tslib@2.8.1: + resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + + typescript@5.9.3: + resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==} + engines: {node: '>=14.17'} + hasBin: true + + undici@7.18.2: + resolution: {integrity: sha512-y+8YjDFzWdQlSE9N5nzKMT3g4a5UBX1HKowfdXh0uvAnTaqqwqB92Jt4UXBAeKekDs5IaDKyJFR4X1gYVCgXcw==} + engines: {node: '>=20.18.1'} + + undici@7.24.8: + resolution: {integrity: sha512-6KQ/+QxK49Z/p3HO6E5ZCZWNnCasyZLa5ExaVYyvPxUwKtbCPMKELJOqh7EqOle0t9cH/7d2TaaTRRa6Nhs4YQ==} + engines: {node: '>=20.18.1'} + + unenv@2.0.0-rc.24: + resolution: {integrity: sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==} + + vite-node@3.2.4: + resolution: {integrity: sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==} + engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0} + hasBin: true + + vite@7.3.3: + resolution: {integrity: sha512-/4XH147Ui7OGTjg3HbdWe5arnZQSbfuRzdr9Ec7TQi5I7R+ir0Rlc9GIvD4v0XZurELqA035KVXJXpR61xhiTA==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + '@types/node': ^20.19.0 || >=22.12.0 + jiti: '>=1.21.0' + less: ^4.0.0 + lightningcss: ^1.21.0 + sass: ^1.70.0 + sass-embedded: ^1.70.0 + stylus: '>=0.54.8' + sugarss: ^5.0.0 + terser: ^5.16.0 + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + '@types/node': + optional: true + jiti: + optional: true + less: + optional: true + lightningcss: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + + vitest@3.2.4: + resolution: {integrity: sha512-LUCP5ev3GURDysTWiP47wRRUpLKMOfPh+yKTx3kVIEiu5KOMeqzpnYNsKyOoVrULivR8tLcks4+lga33Whn90A==} + engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@types/debug': ^4.1.12 + '@types/node': ^18.0.0 || ^20.0.0 || >=22.0.0 + '@vitest/browser': 3.2.4 + '@vitest/ui': 3.2.4 + happy-dom: '*' + jsdom: '*' + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@types/debug': + optional: true + '@types/node': + optional: true + '@vitest/browser': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + + why-is-node-running@2.3.0: + resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} + engines: {node: '>=8'} + hasBin: true + + workerd@1.20260310.1: + resolution: {integrity: sha512-yawXhypXXHtArikJj15HOMknNGikpBbSg2ZDe6lddUbqZnJXuCVSkgc/0ArUeVMG1jbbGvpst+REFtKwILvRTQ==} + engines: {node: '>=16'} + hasBin: true + + workerd@1.20260507.1: + resolution: {integrity: sha512-z7JhsFSe6+X1b5fUHaVpo15VM1IRMJiLofEkq8iKdCo+Veqc+FUg5lIsuz8NwePxuSKrXtO4ZQpGkQLbPVXFhg==} + engines: {node: '>=16'} + hasBin: true + + wrangler@4.72.0: + resolution: {integrity: sha512-bKkb8150JGzJZJWiNB2nu/33smVfawmfYiecA6rW4XH7xS23/jqMbgpdelM34W/7a1IhR66qeQGVqTRXROtAZg==} + engines: {node: '>=20.0.0'} + hasBin: true + peerDependencies: + '@cloudflare/workers-types': ^4.20260310.1 + peerDependenciesMeta: + '@cloudflare/workers-types': + optional: true + + wrangler@4.90.0: + resolution: {integrity: sha512-bmNIykl59TfCUn5xQgU7IWylSsPx3LQaPLMSAq2VQHt89CBrcj9qXQ0eYfjBCWA5XTBVgten391evt7xxtXwcA==} + engines: {node: '>=22.0.0'} + hasBin: true + peerDependencies: + '@cloudflare/workers-types': ^4.20260507.1 + peerDependenciesMeta: + '@cloudflare/workers-types': + optional: true + + ws@8.18.0: + resolution: {integrity: sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==} + engines: {node: '>=10.0.0'} + peerDependencies: + bufferutil: ^4.0.1 + utf-8-validate: '>=5.0.2' + peerDependenciesMeta: + bufferutil: + optional: true + utf-8-validate: + optional: true + + youch-core@0.3.3: + resolution: {integrity: sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==} + + youch@4.1.0-beta.10: + resolution: {integrity: sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==} + +snapshots: + + '@cloudflare/kv-asset-handler@0.4.2': {} + + '@cloudflare/kv-asset-handler@0.5.0': {} + + '@cloudflare/unenv-preset@2.15.0(unenv@2.0.0-rc.24)(workerd@1.20260310.1)': + dependencies: + unenv: 2.0.0-rc.24 + optionalDependencies: + workerd: 1.20260310.1 + + '@cloudflare/unenv-preset@2.16.1(unenv@2.0.0-rc.24)(workerd@1.20260507.1)': + dependencies: + unenv: 2.0.0-rc.24 + optionalDependencies: + workerd: 1.20260507.1 + + '@cloudflare/vitest-pool-workers@0.12.21(@cloudflare/workers-types@4.20260510.1)(@vitest/runner@3.2.4)(@vitest/snapshot@3.2.4)(vitest@3.2.4)': + dependencies: + '@vitest/runner': 3.2.4 + '@vitest/snapshot': 3.2.4 + cjs-module-lexer: 1.4.3 + esbuild: 0.27.3 + miniflare: 4.20260310.0 + vitest: 3.2.4 + wrangler: 4.72.0(@cloudflare/workers-types@4.20260510.1) + transitivePeerDependencies: + - '@cloudflare/workers-types' + - bufferutil + - utf-8-validate + + '@cloudflare/workerd-darwin-64@1.20260310.1': + optional: true + + '@cloudflare/workerd-darwin-64@1.20260507.1': + optional: true + + '@cloudflare/workerd-darwin-arm64@1.20260310.1': + optional: true + + '@cloudflare/workerd-darwin-arm64@1.20260507.1': + optional: true + + '@cloudflare/workerd-linux-64@1.20260310.1': + optional: true + + '@cloudflare/workerd-linux-64@1.20260507.1': + optional: true + + '@cloudflare/workerd-linux-arm64@1.20260310.1': + optional: true + + '@cloudflare/workerd-linux-arm64@1.20260507.1': + optional: true + + '@cloudflare/workerd-windows-64@1.20260310.1': + optional: true + + '@cloudflare/workerd-windows-64@1.20260507.1': + optional: true + + '@cloudflare/workers-types@4.20260510.1': {} + + '@cspotcode/source-map-support@0.8.1': + dependencies: + '@jridgewell/trace-mapping': 0.3.9 + + '@emnapi/runtime@1.10.0': + dependencies: + tslib: 2.8.1 + optional: true + + '@esbuild/aix-ppc64@0.27.3': + optional: true + + '@esbuild/aix-ppc64@0.27.7': + optional: true + + '@esbuild/android-arm64@0.27.3': + optional: true + + '@esbuild/android-arm64@0.27.7': + optional: true + + '@esbuild/android-arm@0.27.3': + optional: true + + '@esbuild/android-arm@0.27.7': + optional: true + + '@esbuild/android-x64@0.27.3': + optional: true + + '@esbuild/android-x64@0.27.7': + optional: true + + '@esbuild/darwin-arm64@0.27.3': + optional: true + + '@esbuild/darwin-arm64@0.27.7': + optional: true + + '@esbuild/darwin-x64@0.27.3': + optional: true + + '@esbuild/darwin-x64@0.27.7': + optional: true + + '@esbuild/freebsd-arm64@0.27.3': + optional: true + + '@esbuild/freebsd-arm64@0.27.7': + optional: true + + '@esbuild/freebsd-x64@0.27.3': + optional: true + + '@esbuild/freebsd-x64@0.27.7': + optional: true + + '@esbuild/linux-arm64@0.27.3': + optional: true + + '@esbuild/linux-arm64@0.27.7': + optional: true + + '@esbuild/linux-arm@0.27.3': + optional: true + + '@esbuild/linux-arm@0.27.7': + optional: true + + '@esbuild/linux-ia32@0.27.3': + optional: true + + '@esbuild/linux-ia32@0.27.7': + optional: true + + '@esbuild/linux-loong64@0.27.3': + optional: true + + '@esbuild/linux-loong64@0.27.7': + optional: true + + '@esbuild/linux-mips64el@0.27.3': + optional: true + + '@esbuild/linux-mips64el@0.27.7': + optional: true + + '@esbuild/linux-ppc64@0.27.3': + optional: true + + '@esbuild/linux-ppc64@0.27.7': + optional: true + + '@esbuild/linux-riscv64@0.27.3': + optional: true + + '@esbuild/linux-riscv64@0.27.7': + optional: true + + '@esbuild/linux-s390x@0.27.3': + optional: true + + '@esbuild/linux-s390x@0.27.7': + optional: true + + '@esbuild/linux-x64@0.27.3': + optional: true + + '@esbuild/linux-x64@0.27.7': + optional: true + + '@esbuild/netbsd-arm64@0.27.3': + optional: true + + '@esbuild/netbsd-arm64@0.27.7': + optional: true + + '@esbuild/netbsd-x64@0.27.3': + optional: true + + '@esbuild/netbsd-x64@0.27.7': + optional: true + + '@esbuild/openbsd-arm64@0.27.3': + optional: true + + '@esbuild/openbsd-arm64@0.27.7': + optional: true + + '@esbuild/openbsd-x64@0.27.3': + optional: true + + '@esbuild/openbsd-x64@0.27.7': + optional: true + + '@esbuild/openharmony-arm64@0.27.3': + optional: true + + '@esbuild/openharmony-arm64@0.27.7': + optional: true + + '@esbuild/sunos-x64@0.27.3': + optional: true + + '@esbuild/sunos-x64@0.27.7': + optional: true + + '@esbuild/win32-arm64@0.27.3': + optional: true + + '@esbuild/win32-arm64@0.27.7': + optional: true + + '@esbuild/win32-ia32@0.27.3': + optional: true + + '@esbuild/win32-ia32@0.27.7': + optional: true + + '@esbuild/win32-x64@0.27.3': + optional: true + + '@esbuild/win32-x64@0.27.7': + optional: true + + '@img/colour@1.1.0': {} + + '@img/sharp-darwin-arm64@0.34.5': + optionalDependencies: + '@img/sharp-libvips-darwin-arm64': 1.2.4 + optional: true + + '@img/sharp-darwin-x64@0.34.5': + optionalDependencies: + '@img/sharp-libvips-darwin-x64': 1.2.4 + optional: true + + '@img/sharp-libvips-darwin-arm64@1.2.4': + optional: true + + '@img/sharp-libvips-darwin-x64@1.2.4': + optional: true + + '@img/sharp-libvips-linux-arm64@1.2.4': + optional: true + + '@img/sharp-libvips-linux-arm@1.2.4': + optional: true + + '@img/sharp-libvips-linux-ppc64@1.2.4': + optional: true + + '@img/sharp-libvips-linux-riscv64@1.2.4': + optional: true + + '@img/sharp-libvips-linux-s390x@1.2.4': + optional: true + + '@img/sharp-libvips-linux-x64@1.2.4': + optional: true + + '@img/sharp-libvips-linuxmusl-arm64@1.2.4': + optional: true + + '@img/sharp-libvips-linuxmusl-x64@1.2.4': + optional: true + + '@img/sharp-linux-arm64@0.34.5': + optionalDependencies: + '@img/sharp-libvips-linux-arm64': 1.2.4 + optional: true + + '@img/sharp-linux-arm@0.34.5': + optionalDependencies: + '@img/sharp-libvips-linux-arm': 1.2.4 + optional: true + + '@img/sharp-linux-ppc64@0.34.5': + optionalDependencies: + '@img/sharp-libvips-linux-ppc64': 1.2.4 + optional: true + + '@img/sharp-linux-riscv64@0.34.5': + optionalDependencies: + '@img/sharp-libvips-linux-riscv64': 1.2.4 + optional: true + + '@img/sharp-linux-s390x@0.34.5': + optionalDependencies: + '@img/sharp-libvips-linux-s390x': 1.2.4 + optional: true + + '@img/sharp-linux-x64@0.34.5': + optionalDependencies: + '@img/sharp-libvips-linux-x64': 1.2.4 + optional: true + + '@img/sharp-linuxmusl-arm64@0.34.5': + optionalDependencies: + '@img/sharp-libvips-linuxmusl-arm64': 1.2.4 + optional: true + + '@img/sharp-linuxmusl-x64@0.34.5': + optionalDependencies: + '@img/sharp-libvips-linuxmusl-x64': 1.2.4 + optional: true + + '@img/sharp-wasm32@0.34.5': + dependencies: + '@emnapi/runtime': 1.10.0 + optional: true + + '@img/sharp-win32-arm64@0.34.5': + optional: true + + '@img/sharp-win32-ia32@0.34.5': + optional: true + + '@img/sharp-win32-x64@0.34.5': + optional: true + + '@jridgewell/resolve-uri@3.1.2': {} + + '@jridgewell/sourcemap-codec@1.5.5': {} + + '@jridgewell/trace-mapping@0.3.9': + dependencies: + '@jridgewell/resolve-uri': 3.1.2 + '@jridgewell/sourcemap-codec': 1.5.5 + + '@poppinss/colors@4.1.6': + dependencies: + kleur: 4.1.5 + + '@poppinss/dumper@0.6.5': + dependencies: + '@poppinss/colors': 4.1.6 + '@sindresorhus/is': 7.2.0 + supports-color: 10.2.2 + + '@poppinss/exception@1.2.3': {} + + '@rollup/rollup-android-arm-eabi@4.60.3': + optional: true + + '@rollup/rollup-android-arm64@4.60.3': + optional: true + + '@rollup/rollup-darwin-arm64@4.60.3': + optional: true + + '@rollup/rollup-darwin-x64@4.60.3': + optional: true + + '@rollup/rollup-freebsd-arm64@4.60.3': + optional: true + + '@rollup/rollup-freebsd-x64@4.60.3': + optional: true + + '@rollup/rollup-linux-arm-gnueabihf@4.60.3': + optional: true + + '@rollup/rollup-linux-arm-musleabihf@4.60.3': + optional: true + + '@rollup/rollup-linux-arm64-gnu@4.60.3': + optional: true + + '@rollup/rollup-linux-arm64-musl@4.60.3': + optional: true + + '@rollup/rollup-linux-loong64-gnu@4.60.3': + optional: true + + '@rollup/rollup-linux-loong64-musl@4.60.3': + optional: true + + '@rollup/rollup-linux-ppc64-gnu@4.60.3': + optional: true + + '@rollup/rollup-linux-ppc64-musl@4.60.3': + optional: true + + '@rollup/rollup-linux-riscv64-gnu@4.60.3': + optional: true + + '@rollup/rollup-linux-riscv64-musl@4.60.3': + optional: true + + '@rollup/rollup-linux-s390x-gnu@4.60.3': + optional: true + + '@rollup/rollup-linux-x64-gnu@4.60.3': + optional: true + + '@rollup/rollup-linux-x64-musl@4.60.3': + optional: true + + '@rollup/rollup-openbsd-x64@4.60.3': + optional: true + + '@rollup/rollup-openharmony-arm64@4.60.3': + optional: true + + '@rollup/rollup-win32-arm64-msvc@4.60.3': + optional: true + + '@rollup/rollup-win32-ia32-msvc@4.60.3': + optional: true + + '@rollup/rollup-win32-x64-gnu@4.60.3': + optional: true + + '@rollup/rollup-win32-x64-msvc@4.60.3': + optional: true + + '@sindresorhus/is@7.2.0': {} + + '@speed-highlight/core@1.2.15': {} + + '@types/chai@5.2.3': + dependencies: + '@types/deep-eql': 4.0.2 + assertion-error: 2.0.1 + + '@types/deep-eql@4.0.2': {} + + '@types/estree@1.0.8': {} + + '@types/estree@1.0.9': {} + + '@vitest/expect@3.2.4': + dependencies: + '@types/chai': 5.2.3 + '@vitest/spy': 3.2.4 + '@vitest/utils': 3.2.4 + chai: 5.3.3 + tinyrainbow: 2.0.0 + + '@vitest/mocker@3.2.4(vite@7.3.3)': + dependencies: + '@vitest/spy': 3.2.4 + estree-walker: 3.0.3 + magic-string: 0.30.21 + optionalDependencies: + vite: 7.3.3 + + '@vitest/pretty-format@3.2.4': + dependencies: + tinyrainbow: 2.0.0 + + '@vitest/runner@3.2.4': + dependencies: + '@vitest/utils': 3.2.4 + pathe: 2.0.3 + strip-literal: 3.1.0 + + '@vitest/snapshot@3.2.4': + dependencies: + '@vitest/pretty-format': 3.2.4 + magic-string: 0.30.21 + pathe: 2.0.3 + + '@vitest/spy@3.2.4': + dependencies: + tinyspy: 4.0.4 + + '@vitest/utils@3.2.4': + dependencies: + '@vitest/pretty-format': 3.2.4 + loupe: 3.2.1 + tinyrainbow: 2.0.0 + + assertion-error@2.0.1: {} + + blake3-wasm@2.1.5: {} + + cac@6.7.14: {} + + chai@5.3.3: + dependencies: + assertion-error: 2.0.1 + check-error: 2.1.3 + deep-eql: 5.0.2 + loupe: 3.2.1 + pathval: 2.0.1 + + check-error@2.1.3: {} + + cjs-module-lexer@1.4.3: {} + + cookie@1.1.1: {} + + debug@4.4.3: + dependencies: + ms: 2.1.3 + + deep-eql@5.0.2: {} + + detect-libc@2.1.2: {} + + error-stack-parser-es@1.0.5: {} + + es-module-lexer@1.7.0: {} + + esbuild@0.27.3: + optionalDependencies: + '@esbuild/aix-ppc64': 0.27.3 + '@esbuild/android-arm': 0.27.3 + '@esbuild/android-arm64': 0.27.3 + '@esbuild/android-x64': 0.27.3 + '@esbuild/darwin-arm64': 0.27.3 + '@esbuild/darwin-x64': 0.27.3 + '@esbuild/freebsd-arm64': 0.27.3 + '@esbuild/freebsd-x64': 0.27.3 + '@esbuild/linux-arm': 0.27.3 + '@esbuild/linux-arm64': 0.27.3 + '@esbuild/linux-ia32': 0.27.3 + '@esbuild/linux-loong64': 0.27.3 + '@esbuild/linux-mips64el': 0.27.3 + '@esbuild/linux-ppc64': 0.27.3 + '@esbuild/linux-riscv64': 0.27.3 + '@esbuild/linux-s390x': 0.27.3 + '@esbuild/linux-x64': 0.27.3 + '@esbuild/netbsd-arm64': 0.27.3 + '@esbuild/netbsd-x64': 0.27.3 + '@esbuild/openbsd-arm64': 0.27.3 + '@esbuild/openbsd-x64': 0.27.3 + '@esbuild/openharmony-arm64': 0.27.3 + '@esbuild/sunos-x64': 0.27.3 + '@esbuild/win32-arm64': 0.27.3 + '@esbuild/win32-ia32': 0.27.3 + '@esbuild/win32-x64': 0.27.3 + + esbuild@0.27.7: + optionalDependencies: + '@esbuild/aix-ppc64': 0.27.7 + '@esbuild/android-arm': 0.27.7 + '@esbuild/android-arm64': 0.27.7 + '@esbuild/android-x64': 0.27.7 + '@esbuild/darwin-arm64': 0.27.7 + '@esbuild/darwin-x64': 0.27.7 + '@esbuild/freebsd-arm64': 0.27.7 + '@esbuild/freebsd-x64': 0.27.7 + '@esbuild/linux-arm': 0.27.7 + '@esbuild/linux-arm64': 0.27.7 + '@esbuild/linux-ia32': 0.27.7 + '@esbuild/linux-loong64': 0.27.7 + '@esbuild/linux-mips64el': 0.27.7 + '@esbuild/linux-ppc64': 0.27.7 + '@esbuild/linux-riscv64': 0.27.7 + '@esbuild/linux-s390x': 0.27.7 + '@esbuild/linux-x64': 0.27.7 + '@esbuild/netbsd-arm64': 0.27.7 + '@esbuild/netbsd-x64': 0.27.7 + '@esbuild/openbsd-arm64': 0.27.7 + '@esbuild/openbsd-x64': 0.27.7 + '@esbuild/openharmony-arm64': 0.27.7 + '@esbuild/sunos-x64': 0.27.7 + '@esbuild/win32-arm64': 0.27.7 + '@esbuild/win32-ia32': 0.27.7 + '@esbuild/win32-x64': 0.27.7 + + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.9 + + expect-type@1.3.0: {} + + fdir@6.5.0(picomatch@4.0.4): + optionalDependencies: + picomatch: 4.0.4 + + fsevents@2.3.3: + optional: true + + js-tokens@9.0.1: {} + + kleur@4.1.5: {} + + loupe@3.2.1: {} + + magic-string@0.30.21: + dependencies: + '@jridgewell/sourcemap-codec': 1.5.5 + + miniflare@4.20260310.0: + dependencies: + '@cspotcode/source-map-support': 0.8.1 + sharp: 0.34.5 + undici: 7.18.2 + workerd: 1.20260310.1 + ws: 8.18.0 + youch: 4.1.0-beta.10 + transitivePeerDependencies: + - bufferutil + - utf-8-validate + + miniflare@4.20260507.1: + dependencies: + '@cspotcode/source-map-support': 0.8.1 + sharp: 0.34.5 + undici: 7.24.8 + workerd: 1.20260507.1 + ws: 8.18.0 + youch: 4.1.0-beta.10 + transitivePeerDependencies: + - bufferutil + - utf-8-validate + + ms@2.1.3: {} + + nanoid@3.3.12: {} + + path-to-regexp@6.3.0: {} + + pathe@2.0.3: {} + + pathval@2.0.1: {} + + picocolors@1.1.1: {} + + picomatch@4.0.4: {} + + postcss@8.5.14: + dependencies: + nanoid: 3.3.12 + picocolors: 1.1.1 + source-map-js: 1.2.1 + + rollup@4.60.3: + dependencies: + '@types/estree': 1.0.8 + optionalDependencies: + '@rollup/rollup-android-arm-eabi': 4.60.3 + '@rollup/rollup-android-arm64': 4.60.3 + '@rollup/rollup-darwin-arm64': 4.60.3 + '@rollup/rollup-darwin-x64': 4.60.3 + '@rollup/rollup-freebsd-arm64': 4.60.3 + '@rollup/rollup-freebsd-x64': 4.60.3 + '@rollup/rollup-linux-arm-gnueabihf': 4.60.3 + '@rollup/rollup-linux-arm-musleabihf': 4.60.3 + '@rollup/rollup-linux-arm64-gnu': 4.60.3 + '@rollup/rollup-linux-arm64-musl': 4.60.3 + '@rollup/rollup-linux-loong64-gnu': 4.60.3 + '@rollup/rollup-linux-loong64-musl': 4.60.3 + '@rollup/rollup-linux-ppc64-gnu': 4.60.3 + '@rollup/rollup-linux-ppc64-musl': 4.60.3 + '@rollup/rollup-linux-riscv64-gnu': 4.60.3 + '@rollup/rollup-linux-riscv64-musl': 4.60.3 + '@rollup/rollup-linux-s390x-gnu': 4.60.3 + '@rollup/rollup-linux-x64-gnu': 4.60.3 + '@rollup/rollup-linux-x64-musl': 4.60.3 + '@rollup/rollup-openbsd-x64': 4.60.3 + '@rollup/rollup-openharmony-arm64': 4.60.3 + '@rollup/rollup-win32-arm64-msvc': 4.60.3 + '@rollup/rollup-win32-ia32-msvc': 4.60.3 + '@rollup/rollup-win32-x64-gnu': 4.60.3 + '@rollup/rollup-win32-x64-msvc': 4.60.3 + fsevents: 2.3.3 + + semver@7.8.0: {} + + sharp@0.34.5: + dependencies: + '@img/colour': 1.1.0 + detect-libc: 2.1.2 + semver: 7.8.0 + optionalDependencies: + '@img/sharp-darwin-arm64': 0.34.5 + '@img/sharp-darwin-x64': 0.34.5 + '@img/sharp-libvips-darwin-arm64': 1.2.4 + '@img/sharp-libvips-darwin-x64': 1.2.4 + '@img/sharp-libvips-linux-arm': 1.2.4 + '@img/sharp-libvips-linux-arm64': 1.2.4 + '@img/sharp-libvips-linux-ppc64': 1.2.4 + '@img/sharp-libvips-linux-riscv64': 1.2.4 + '@img/sharp-libvips-linux-s390x': 1.2.4 + '@img/sharp-libvips-linux-x64': 1.2.4 + '@img/sharp-libvips-linuxmusl-arm64': 1.2.4 + '@img/sharp-libvips-linuxmusl-x64': 1.2.4 + '@img/sharp-linux-arm': 0.34.5 + '@img/sharp-linux-arm64': 0.34.5 + '@img/sharp-linux-ppc64': 0.34.5 + '@img/sharp-linux-riscv64': 0.34.5 + '@img/sharp-linux-s390x': 0.34.5 + '@img/sharp-linux-x64': 0.34.5 + '@img/sharp-linuxmusl-arm64': 0.34.5 + '@img/sharp-linuxmusl-x64': 0.34.5 + '@img/sharp-wasm32': 0.34.5 + '@img/sharp-win32-arm64': 0.34.5 + '@img/sharp-win32-ia32': 0.34.5 + '@img/sharp-win32-x64': 0.34.5 + + siginfo@2.0.0: {} + + source-map-js@1.2.1: {} + + stackback@0.0.2: {} + + std-env@3.10.0: {} + + strip-literal@3.1.0: + dependencies: + js-tokens: 9.0.1 + + supports-color@10.2.2: {} + + tinybench@2.9.0: {} + + tinyexec@0.3.2: {} + + tinyglobby@0.2.16: + dependencies: + fdir: 6.5.0(picomatch@4.0.4) + picomatch: 4.0.4 + + tinypool@1.1.1: {} + + tinyrainbow@2.0.0: {} + + tinyspy@4.0.4: {} + + tslib@2.8.1: + optional: true + + typescript@5.9.3: {} + + undici@7.18.2: {} + + undici@7.24.8: {} + + unenv@2.0.0-rc.24: + dependencies: + pathe: 2.0.3 + + vite-node@3.2.4: + dependencies: + cac: 6.7.14 + debug: 4.4.3 + es-module-lexer: 1.7.0 + pathe: 2.0.3 + vite: 7.3.3 + transitivePeerDependencies: + - '@types/node' + - jiti + - less + - lightningcss + - sass + - sass-embedded + - stylus + - sugarss + - supports-color + - terser + - tsx + - yaml + + vite@7.3.3: + dependencies: + esbuild: 0.27.7 + fdir: 6.5.0(picomatch@4.0.4) + picomatch: 4.0.4 + postcss: 8.5.14 + rollup: 4.60.3 + tinyglobby: 0.2.16 + optionalDependencies: + fsevents: 2.3.3 + + vitest@3.2.4: + dependencies: + '@types/chai': 5.2.3 + '@vitest/expect': 3.2.4 + '@vitest/mocker': 3.2.4(vite@7.3.3) + '@vitest/pretty-format': 3.2.4 + '@vitest/runner': 3.2.4 + '@vitest/snapshot': 3.2.4 + '@vitest/spy': 3.2.4 + '@vitest/utils': 3.2.4 + chai: 5.3.3 + debug: 4.4.3 + expect-type: 1.3.0 + magic-string: 0.30.21 + pathe: 2.0.3 + picomatch: 4.0.4 + std-env: 3.10.0 + tinybench: 2.9.0 + tinyexec: 0.3.2 + tinyglobby: 0.2.16 + tinypool: 1.1.1 + tinyrainbow: 2.0.0 + vite: 7.3.3 + vite-node: 3.2.4 + why-is-node-running: 2.3.0 + transitivePeerDependencies: + - jiti + - less + - lightningcss + - msw + - sass + - sass-embedded + - stylus + - sugarss + - supports-color + - terser + - tsx + - yaml + + why-is-node-running@2.3.0: + dependencies: + siginfo: 2.0.0 + stackback: 0.0.2 + + workerd@1.20260310.1: + optionalDependencies: + '@cloudflare/workerd-darwin-64': 1.20260310.1 + '@cloudflare/workerd-darwin-arm64': 1.20260310.1 + '@cloudflare/workerd-linux-64': 1.20260310.1 + '@cloudflare/workerd-linux-arm64': 1.20260310.1 + '@cloudflare/workerd-windows-64': 1.20260310.1 + + workerd@1.20260507.1: + optionalDependencies: + '@cloudflare/workerd-darwin-64': 1.20260507.1 + '@cloudflare/workerd-darwin-arm64': 1.20260507.1 + '@cloudflare/workerd-linux-64': 1.20260507.1 + '@cloudflare/workerd-linux-arm64': 1.20260507.1 + '@cloudflare/workerd-windows-64': 1.20260507.1 + + wrangler@4.72.0(@cloudflare/workers-types@4.20260510.1): + dependencies: + '@cloudflare/kv-asset-handler': 0.4.2 + '@cloudflare/unenv-preset': 2.15.0(unenv@2.0.0-rc.24)(workerd@1.20260310.1) + blake3-wasm: 2.1.5 + esbuild: 0.27.3 + miniflare: 4.20260310.0 + path-to-regexp: 6.3.0 + unenv: 2.0.0-rc.24 + workerd: 1.20260310.1 + optionalDependencies: + '@cloudflare/workers-types': 4.20260510.1 + fsevents: 2.3.3 + transitivePeerDependencies: + - bufferutil + - utf-8-validate + + wrangler@4.90.0(@cloudflare/workers-types@4.20260510.1): + dependencies: + '@cloudflare/kv-asset-handler': 0.5.0 + '@cloudflare/unenv-preset': 2.16.1(unenv@2.0.0-rc.24)(workerd@1.20260507.1) + blake3-wasm: 2.1.5 + esbuild: 0.27.3 + miniflare: 4.20260507.1 + path-to-regexp: 6.3.0 + unenv: 2.0.0-rc.24 + workerd: 1.20260507.1 + optionalDependencies: + '@cloudflare/workers-types': 4.20260510.1 + fsevents: 2.3.3 + transitivePeerDependencies: + - bufferutil + - utf-8-validate + + ws@8.18.0: {} + + youch-core@0.3.3: + dependencies: + '@poppinss/exception': 1.2.3 + error-stack-parser-es: 1.0.5 + + youch@4.1.0-beta.10: + dependencies: + '@poppinss/colors': 4.1.6 + '@poppinss/dumper': 0.6.5 + '@speed-highlight/core': 1.2.15 + cookie: 1.1.1 + youch-core: 0.3.3 diff --git a/services/goose-bot-switchboard/src/index.ts b/services/goose-bot-switchboard/src/index.ts new file mode 100644 index 000000000000..6205337f6402 --- /dev/null +++ b/services/goose-bot-switchboard/src/index.ts @@ -0,0 +1,134 @@ +// Reviews run on the user's goosed via lapstone; KV holds routing metadata only. + +import { verifyWebhookSignature } from './lib/github'; +import { + handleAnalyticsEvent, + handleAnalyticsGet, + handleInstallation, + handleIssueComment, + handleListRepos, + handlePullRequest, + handleRegister, + handleRoutingPrefs, + handleUnregister, + handleWhoami, +} from './lib/handlers'; +import type { + Env, + InstallationEvent, + IssueCommentEvent, + PullRequestEvent, + RegisterRequest, +} from './lib/types'; + +export default { + async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { + const url = new URL(request.url); + + if (request.method === 'GET' && url.pathname === '/') { + return new Response('Goose Bot switchboard\n', { + status: 200, + headers: { 'content-type': 'text/plain' }, + }); + } + + if (request.method === 'POST' && url.pathname === '/webhook') { + return handleWebhook(request, env, ctx); + } + + if (request.method === 'POST' && url.pathname === '/goose-bot/register') { + return handleRegisterRoute(request, env); + } + + if (request.method === 'PUT' && url.pathname === '/goose-bot/routing-prefs') { + return handleRoutingPrefs(request, env); + } + + if (request.method === 'POST' && url.pathname === '/goose-bot/whoami') { + return handleWhoami(request, env); + } + + if (request.method === 'DELETE' && url.pathname === '/goose-bot/install') { + return handleUnregister(request, env); + } + + if (request.method === 'GET' && url.pathname === '/goose-bot/repos') { + return handleListRepos(request, env); + } + + if (request.method === 'GET' && url.pathname === '/goose-bot/analytics') { + return handleAnalyticsGet(request, env); + } + + if (request.method === 'POST' && url.pathname === '/goose-bot/analytics/event') { + return handleAnalyticsEvent(request, env); + } + + if (request.method === 'GET' && url.pathname === '/goose-bot/oauth-config') { + return new Response( + JSON.stringify({ oauth_client_id: env.GITHUB_OAUTH_CLIENT_ID }), + { status: 200, headers: { 'content-type': 'application/json' } } + ); + } + + return new Response('Not Found', { status: 404 }); + }, +}; + +async function handleWebhook( + request: Request, + env: Env, + ctx: ExecutionContext +): Promise { + const body = await request.text(); + const signature = request.headers.get('x-hub-signature-256') ?? ''; + + if (!(await verifyWebhookSignature(body, signature, env.GITHUB_WEBHOOK_SECRET))) { + return new Response('Unauthorized', { status: 401 }); + } + + const event = request.headers.get('x-github-event') ?? ''; + const deliveryId = request.headers.get('x-github-delivery') ?? ''; + + let payload: unknown; + try { + payload = JSON.parse(body); + } catch { + return new Response('Invalid JSON', { status: 400 }); + } + + // GitHub gives us a 5s budget to ack the webhook. + switch (event) { + case 'installation': + ctx.waitUntil(guard(deliveryId, handleInstallation(payload as InstallationEvent, env))); + break; + case 'pull_request': + ctx.waitUntil(guard(deliveryId, handlePullRequest(payload as PullRequestEvent, env))); + break; + case 'issue_comment': + ctx.waitUntil(guard(deliveryId, handleIssueComment(payload as IssueCommentEvent, env))); + break; + case 'ping': + break; + } + + return new Response('OK', { status: 200 }); +} + +async function handleRegisterRoute(request: Request, env: Env): Promise { + let body: RegisterRequest; + try { + body = (await request.json()) as RegisterRequest; + } catch { + return new Response('Invalid JSON', { status: 400 }); + } + return handleRegister(body, env); +} + +async function guard(deliveryId: string, p: Promise): Promise { + try { + await p; + } catch (err) { + console.error(`[handler] delivery=${deliveryId}: ${err instanceof Error ? err.stack : err}`); + } +} diff --git a/services/goose-bot-switchboard/src/lib/analytics.ts b/services/goose-bot-switchboard/src/lib/analytics.ts new file mode 100644 index 000000000000..6859c0c4f078 --- /dev/null +++ b/services/goose-bot-switchboard/src/lib/analytics.ts @@ -0,0 +1,64 @@ +import type { Env } from './types'; + +const KV_PREFIX = 'analytics'; + +export interface GooseBotAnalytics { + prs_reviewed: number; + issues_handled: number; + commits_pushed: number; +} + +const EMPTY: GooseBotAnalytics = { + prs_reviewed: 0, + issues_handled: 0, + commits_pushed: 0, +}; + +export type AnalyticsEvent = + | { kind: 'pr_reviewed' } + | { kind: 'issue_handled' } + | { kind: 'commit_pushed' }; + +function key(installationId: number): string { + return `${KV_PREFIX}:${installationId}`; +} + +export async function loadAnalytics( + env: Env, + installationId: number +): Promise { + const raw = await env.INSTALL_REGISTRY.get(key(installationId)); + if (!raw) return { ...EMPTY }; + try { + const parsed = JSON.parse(raw) as Partial; + return { ...EMPTY, ...parsed }; + } catch { + return { ...EMPTY }; + } +} + +export async function recordEvent( + env: Env, + installationId: number, + event: AnalyticsEvent +): Promise { + // KV has no atomic increments; for a single-user-per-install bot this + // read-modify-write is fine. Multi-org rollouts will want a Durable Object. + const current = await loadAnalytics(env, installationId); + switch (event.kind) { + case 'pr_reviewed': + current.prs_reviewed += 1; + break; + case 'issue_handled': + current.issues_handled += 1; + break; + case 'commit_pushed': + current.commits_pushed += 1; + break; + } + await env.INSTALL_REGISTRY.put(key(installationId), JSON.stringify(current)); +} + +export async function deleteAnalytics(env: Env, installationId: number): Promise { + await env.INSTALL_REGISTRY.delete(key(installationId)); +} diff --git a/services/goose-bot-switchboard/src/lib/github.ts b/services/goose-bot-switchboard/src/lib/github.ts new file mode 100644 index 000000000000..fa124b3481d3 --- /dev/null +++ b/services/goose-bot-switchboard/src/lib/github.ts @@ -0,0 +1,370 @@ +const API = 'https://api.github.com'; +const UA = 'goose-bot-switchboard/0.1'; + +export async function verifyWebhookSignature( + body: string, + signatureHeader: string, + secret: string +): Promise { + if (!signatureHeader.startsWith('sha256=')) return false; + const provided = signatureHeader.slice('sha256='.length); + + const key = await crypto.subtle.importKey( + 'raw', + new TextEncoder().encode(secret), + { name: 'HMAC', hash: 'SHA-256' }, + false, + ['sign'] + ); + const sigBuf = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(body)); + const expected = bufToHex(sigBuf); + + return timingSafeEqual(provided, expected); +} + +function bufToHex(buf: ArrayBuffer): string { + return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join(''); +} + +export function timingSafeEqual(a: string, b: string): boolean { + if (a.length !== b.length) return false; + let mismatch = 0; + for (let i = 0; i < a.length; i++) mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i); + return mismatch === 0; +} + +export async function generateAppJwt(appId: string, privateKeyPem: string): Promise { + const now = Math.floor(Date.now() / 1000); + const header = b64url(JSON.stringify({ alg: 'RS256', typ: 'JWT' })); + // iat is 60s in the past to tolerate clock skew; exp must be ≤ 10 min per GitHub. + const payload = b64url(JSON.stringify({ iat: now - 60, exp: now + 540, iss: parseInt(appId, 10) })); + const signingInput = `${header}.${payload}`; + + const key = await crypto.subtle.importKey( + 'pkcs8', + pemToPkcs8(privateKeyPem), + { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, + false, + ['sign'] + ); + const sig = await crypto.subtle.sign( + { name: 'RSASSA-PKCS1-v1_5' }, + key, + new TextEncoder().encode(signingInput) + ); + return `${signingInput}.${b64urlBytes(new Uint8Array(sig))}`; +} + +function b64url(s: string): string { + return b64urlBytes(new TextEncoder().encode(s)); +} + +function b64urlBytes(bytes: Uint8Array): string { + let bin = ''; + for (const b of bytes) bin += String.fromCharCode(b); + return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); +} + +function pemToPkcs8(pem: string): Uint8Array { + const label = pem.match(/-----BEGIN ([A-Z ]+)-----/)?.[1]; + const stripped = pem + .replace(/-----BEGIN [A-Z ]+-----/, '') + .replace(/-----END [A-Z ]+-----/, '') + .replace(/\s+/g, ''); + const bin = atob(stripped); + const buf = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i); + if (label === 'PRIVATE KEY') { + return buf; + } + if (label === 'RSA PRIVATE KEY') { + return wrapPkcs1AsPkcs8(buf); + } + throw new Error('GITHUB_APP_PRIVATE_KEY must be a PEM private key'); +} + +function wrapPkcs1AsPkcs8(pkcs1: Uint8Array): Uint8Array { + const version = new Uint8Array([0x02, 0x01, 0x00]); + const rsaEncryption = new Uint8Array([ + 0x30, 0x0d, + 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, + 0x05, 0x00, + ]); + const privateKey = der(0x04, pkcs1); + return der(0x30, concat(version, rsaEncryption, privateKey)); +} + +function der(tag: number, value: Uint8Array): Uint8Array { + return concat(new Uint8Array([tag]), derLength(value.length), value); +} + +function derLength(length: number): Uint8Array { + if (length < 0x80) return new Uint8Array([length]); + const bytes: number[] = []; + let remaining = length; + while (remaining > 0) { + bytes.unshift(remaining & 0xff); + remaining >>= 8; + } + return new Uint8Array([0x80 | bytes.length, ...bytes]); +} + +function concat(...parts: Uint8Array[]): Uint8Array { + const total = parts.reduce((sum, part) => sum + part.length, 0); + const out = new Uint8Array(total); + let offset = 0; + for (const part of parts) { + out.set(part, offset); + offset += part.length; + } + return out; +} + +const installationTokenCache = new Map(); + +export async function getInstallationToken( + installationId: number, + appJwt: string +): Promise { + const cached = installationTokenCache.get(installationId); + if (cached && cached.expiresAt > Date.now() + 60_000) return cached.token; + + const res = await fetch(`${API}/app/installations/${installationId}/access_tokens`, { + method: 'POST', + headers: ghHeaders(appJwt), + }); + if (!res.ok) throw await ghError(res, 'Failed to mint installation token'); + const data = (await res.json()) as { token: string; expires_at: string }; + installationTokenCache.set(installationId, { + token: data.token, + expiresAt: new Date(data.expires_at).getTime(), + }); + return data.token; +} + +interface InstallationReposPage { + total_count: number; + repositories: Array<{ + id: number; + name: string; + full_name: string; + owner: { login: string } | null; + visibility?: string; + archived?: boolean; + default_branch?: string; + html_url?: string; + }>; +} + +const MAX_REPO_PAGES = 5; +const REPOS_PER_PAGE = 100; + +export interface RepoSummary { + id: number; + full_name: string; + name: string; + owner: string; + visibility: 'public' | 'private' | 'internal' | 'unknown'; + archived: boolean; + default_branch: string; + html_url: string; +} + +export interface ListReposResult { + total_count: number; + repos: RepoSummary[]; + truncated: boolean; +} + +export async function listInstallationRepos(token: string): Promise { + const collected: RepoSummary[] = []; + let totalCount = 0; + let truncated = false; + + for (let page = 1; page <= MAX_REPO_PAGES; page++) { + const res = await fetch( + `${API}/installation/repositories?per_page=${REPOS_PER_PAGE}&page=${page}`, + { headers: ghHeaders(token) } + ); + if (!res.ok) throw await ghError(res, 'Failed to list installation repositories'); + const data = (await res.json()) as InstallationReposPage; + totalCount = data.total_count ?? collected.length; + for (const r of data.repositories) { + collected.push({ + id: r.id, + full_name: r.full_name, + name: r.name, + owner: r.owner?.login ?? '', + visibility: normalizeVisibility(r.visibility), + archived: r.archived ?? false, + default_branch: r.default_branch ?? '', + html_url: r.html_url ?? '', + }); + } + if (data.repositories.length < REPOS_PER_PAGE) break; + if (page === MAX_REPO_PAGES && collected.length < totalCount) { + truncated = true; + } + } + + return { total_count: totalCount, repos: collected, truncated }; +} + +function normalizeVisibility(v: string | undefined): RepoSummary['visibility'] { + if (v === 'public' || v === 'private' || v === 'internal') return v; + return 'unknown'; +} + +export async function getCommenterPermission( + fullName: string, + username: string, + token: string +): Promise<'admin' | 'maintain' | 'write' | 'triage' | 'read' | 'none' | null> { + const res = await fetch( + `${API}/repos/${fullName}/collaborators/${encodeURIComponent(username)}/permission`, + { headers: ghHeaders(token) } + ); + if (!res.ok) return null; + const data = (await res.json()) as { permission?: string }; + const p = data.permission; + if ( + p === 'admin' || + p === 'maintain' || + p === 'write' || + p === 'triage' || + p === 'read' || + p === 'none' + ) { + return p; + } + return null; +} + +export async function getBranchHeadSha( + fullName: string, + branch: string, + token: string +): Promise { + const res = await fetch( + `${API}/repos/${fullName}/git/refs/heads/${encodeURIComponent(branch)}`, + { headers: ghHeaders(token) } + ); + if (!res.ok) throw await ghError(res, `Failed to resolve branch ${branch}`); + const data = (await res.json()) as { object?: { sha?: string } }; + const sha = data.object?.sha; + if (!sha) throw new Error(`branch ${branch} resolved with no SHA`); + return sha; +} + +export async function getPullRequestHead( + fullName: string, + prNumber: number, + token: string +): Promise<{ sha: string; ref: string; repoFullName: string; htmlUrl: string }> { + const res = await fetch(`${API}/repos/${fullName}/pulls/${prNumber}`, { + headers: ghHeaders(token), + }); + if (!res.ok) throw await ghError(res, `Failed to load PR #${prNumber}`); + const data = (await res.json()) as { + head: { sha: string; ref: string; repo: { full_name: string } | null }; + html_url: string; + }; + return { + sha: data.head.sha, + ref: data.head.ref, + repoFullName: data.head.repo?.full_name ?? '', + htmlUrl: data.html_url, + }; +} + +export async function createCheckRun( + fullName: string, + headSha: string, + token: string +): Promise { + const res = await fetch(`${API}/repos/${fullName}/check-runs`, { + method: 'POST', + headers: { ...ghHeaders(token), 'Content-Type': 'application/json' }, + body: JSON.stringify({ + name: 'Goose Bot', + head_sha: headSha, + status: 'in_progress', + output: { + title: 'Goose Bot is reviewing this PR...', + summary: 'Routing this review to your local goosed. Usually takes 30-90 seconds.', + }, + }), + }); + if (!res.ok) throw await ghError(res, 'Failed to create check run'); + const data = (await res.json()) as { id: number }; + return data.id; +} + +export async function completeCheckRun(opts: { + fullName: string; + checkRunId: number; + conclusion: 'success' | 'failure' | 'neutral' | 'cancelled'; + title: string; + summary: string; + token: string; +}): Promise { + const { fullName, checkRunId, conclusion, title, summary, token } = opts; + const res = await fetch(`${API}/repos/${fullName}/check-runs/${checkRunId}`, { + method: 'PATCH', + headers: { ...ghHeaders(token), 'Content-Type': 'application/json' }, + body: JSON.stringify({ + status: 'completed', + conclusion, + output: { title, summary: summary.slice(0, 65_000) }, + }), + }); + if (!res.ok) throw await ghError(res, 'Failed to complete check run'); +} + +export async function postIssueComment( + fullName: string, + issueNumber: number, + body: string, + token: string +): Promise { + const res = await fetch(`${API}/repos/${fullName}/issues/${issueNumber}/comments`, { + method: 'POST', + headers: { ...ghHeaders(token), 'Content-Type': 'application/json' }, + body: JSON.stringify({ body }), + }); + if (!res.ok) throw await ghError(res, 'Failed to post issue comment'); +} + +export type Reaction = '+1' | '-1' | 'laugh' | 'confused' | 'heart' | 'hooray' | 'rocket' | 'eyes'; + +export async function postCommentReaction( + fullName: string, + commentId: number, + content: Reaction, + token: string +): Promise { + const res = await fetch( + `${API}/repos/${fullName}/issues/comments/${commentId}/reactions`, + { + method: 'POST', + headers: { ...ghHeaders(token), 'Content-Type': 'application/json' }, + body: JSON.stringify({ content }), + } + ); + // 200 = already reacted, 201 = newly reacted; both are fine. + if (!res.ok) throw await ghError(res, `Failed to react ${content}`); +} + +function ghHeaders(token: string): HeadersInit { + return { + Authorization: `Bearer ${token}`, + Accept: 'application/vnd.github+json', + 'X-GitHub-Api-Version': '2022-11-28', + 'User-Agent': UA, + }; +} + +async function ghError(res: Response, prefix: string): Promise { + const detail = (await res.json().catch(() => ({}))) as { message?: string }; + return new Error(`${prefix}: ${res.status} ${detail.message ?? res.statusText}`); +} diff --git a/services/goose-bot-switchboard/src/lib/handlers.ts b/services/goose-bot-switchboard/src/lib/handlers.ts new file mode 100644 index 000000000000..8323a699931b --- /dev/null +++ b/services/goose-bot-switchboard/src/lib/handlers.ts @@ -0,0 +1,615 @@ +// Webhook handlers run inside `ctx.waitUntil()`; we've already returned 200 +// to GitHub by the time they execute. Failures are logged, not rethrown. + +import { + completeCheckRun, + createCheckRun, + generateAppJwt, + getBranchHeadSha, + getCommenterPermission, + getInstallationToken, + getPullRequestHead, + listInstallationRepos, + postCommentReaction, + postIssueComment, +} from './github'; +import { + type AnalyticsEvent, + deleteAnalytics, + loadAnalytics, + recordEvent, +} from './analytics'; +import { exchangeCodeAndResolve } from './oauth'; +import { + deleteRoutingPrefs, + loadRoutingPrefs, + parseRoutingPrefs, + saveRoutingPrefs, + type TriggerPermission, +} from './prefs'; +import { deleteInstall, loadInstall, loadInstallByAgent, saveInstall } from './registry'; +import { + agentIdFromTunnelUrl, + runCommentViaTunnel, + runReviewViaTunnel, + verifyTunnelReachable, +} from './tunnel'; +import type { + Env, + InstallationEvent, + IssueCommentEvent, + PullRequestEvent, + RegisterRequest, +} from './types'; + +const MENTION_RE = /(^|\s)@aaif-goose-bot\b/i; +const REVIEW_TRIGGER_RE = /(^|\s)@aaif-goose-bot\s+review\s*$/im; + +export async function handleRegister(req: RegisterRequest, env: Env): Promise { + if ( + !req || + typeof req.oauth_code !== 'string' || + typeof req.agent_id !== 'string' || + typeof req.tunnel_secret !== 'string' || + typeof req.tunnel_url !== 'string' + ) { + return jsonError(400, 'Missing or invalid registration fields'); + } + if (!/^https:\/\//.test(req.tunnel_url)) { + return jsonError(400, 'tunnel_url must be an https URL'); + } + const urlAgentId = agentIdFromTunnelUrl(req.tunnel_url); + if (!urlAgentId || urlAgentId !== req.agent_id) { + return jsonError(400, 'tunnel_url does not match agent_id'); + } + + const tunnel = await verifyTunnelReachable(req.tunnel_url, req.tunnel_secret); + if (!tunnel.ok) { + return jsonError(400, tunnel.error); + } + + const resolution = await exchangeCodeAndResolve({ + clientId: env.GITHUB_OAUTH_CLIENT_ID, + clientSecret: env.GITHUB_OAUTH_CLIENT_SECRET, + appId: Number(env.GITHUB_APP_ID), + code: req.oauth_code, + }); + if (!resolution.ok) { + return jsonError(resolution.status, resolution.error); + } + + const existing = await loadInstall(env, resolution.installationId); + if ( + existing && + (existing.agentId !== req.agent_id || existing.tunnelSecret !== req.tunnel_secret) + ) { + return jsonError( + 409, + 'installation is already registered; disconnect the existing Goose before reconnecting' + ); + } + + await saveInstall(env, { + installationId: resolution.installationId, + agentId: req.agent_id, + tunnelSecret: req.tunnel_secret, + tunnelUrl: req.tunnel_url, + registeredAt: new Date().toISOString(), + }); + + return new Response( + JSON.stringify({ + ok: true, + installation_id: resolution.installationId, + account_login: resolution.accountLogin, + }), + { + status: 200, + headers: { 'content-type': 'application/json' }, + } + ); +} + +function jsonError(status: number, message: string): Response { + return new Response(JSON.stringify({ error: message }), { + status, + headers: { 'content-type': 'application/json' }, + }); +} + +export async function handleRoutingPrefs(request: Request, env: Env): Promise { + const installIdRaw = request.headers.get('x-install-id'); + const installSecret = request.headers.get('x-install-secret'); + if (!installIdRaw || !installSecret) { + return jsonError(401, 'missing install credentials'); + } + const installId = Number.parseInt(installIdRaw, 10); + if (!Number.isFinite(installId)) { + return jsonError(400, 'invalid install id'); + } + + const install = await loadInstall(env, installId); + if (!install || install.tunnelSecret !== installSecret) { + return jsonError(401, 'install credentials rejected'); + } + + let body: unknown; + try { + body = await request.json(); + } catch { + return jsonError(400, 'invalid JSON body'); + } + + let prefs; + try { + prefs = parseRoutingPrefs(body); + } catch (e) { + return jsonError(400, e instanceof Error ? e.message : 'invalid routing prefs'); + } + + await saveRoutingPrefs(env, installId, prefs); + return new Response(JSON.stringify({ ok: true, prefs }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); +} + +export async function handleUnregister(request: Request, env: Env): Promise { + const installIdRaw = request.headers.get('x-install-id'); + const installSecret = request.headers.get('x-install-secret'); + if (!installIdRaw || !installSecret) { + return jsonError(401, 'missing install credentials'); + } + const installId = Number.parseInt(installIdRaw, 10); + if (!Number.isFinite(installId)) { + return jsonError(400, 'invalid install id'); + } + + const install = await loadInstall(env, installId); + if (!install || install.tunnelSecret !== installSecret) { + return jsonError(401, 'install credentials rejected'); + } + + await deleteInstall(env, installId); + await deleteRoutingPrefs(env, installId); + await deleteAnalytics(env, installId); + + return new Response(JSON.stringify({ ok: true }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); +} + +export async function handleWhoami(request: Request, env: Env): Promise { + let body: { agent_id?: unknown; tunnel_secret?: unknown }; + try { + body = (await request.json()) as typeof body; + } catch { + return jsonError(400, 'invalid JSON body'); + } + const agentId = typeof body.agent_id === 'string' ? body.agent_id : ''; + const tunnelSecret = typeof body.tunnel_secret === 'string' ? body.tunnel_secret : ''; + if (!agentId || !tunnelSecret) { + return jsonError(400, 'agent_id and tunnel_secret are required'); + } + + const install = await loadInstallByAgent(env, agentId); + if (!install || install.tunnelSecret !== tunnelSecret) { + // Don't differentiate "no such agent" from "wrong secret" - same surface + // either way, no oracle for attackers. + return jsonError(401, 'unrecognized credentials'); + } + + return new Response( + JSON.stringify({ installation_id: install.installationId }), + { status: 200, headers: { 'content-type': 'application/json' } } + ); +} + +export async function handleListRepos(request: Request, env: Env): Promise { + const installIdRaw = request.headers.get('x-install-id'); + const installSecret = request.headers.get('x-install-secret'); + if (!installIdRaw || !installSecret) { + return jsonError(401, 'missing install credentials'); + } + const installId = Number.parseInt(installIdRaw, 10); + if (!Number.isFinite(installId)) { + return jsonError(400, 'invalid install id'); + } + + const install = await loadInstall(env, installId); + if (!install || install.tunnelSecret !== installSecret) { + return jsonError(401, 'install credentials rejected'); + } + + try { + const jwt = await generateAppJwt(env.GITHUB_APP_ID, env.GITHUB_APP_PRIVATE_KEY); + const token = await getInstallationToken(installId, jwt); + const result = await listInstallationRepos(token); + return new Response(JSON.stringify(result), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + console.error(`[repos] install=${installId}: ${msg}`); + return jsonError(502, msg); + } +} + +export async function handleAnalyticsGet(request: Request, env: Env): Promise { + const auth = authenticateInstall(request); + if (!auth.ok) return jsonError(auth.status, auth.message); + const install = await loadInstall(env, auth.installId); + if (!install || install.tunnelSecret !== auth.secret) { + return jsonError(401, 'install credentials rejected'); + } + const data = await loadAnalytics(env, auth.installId); + return new Response(JSON.stringify(data), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); +} + +export async function handleAnalyticsEvent(request: Request, env: Env): Promise { + const auth = authenticateInstall(request); + if (!auth.ok) return jsonError(auth.status, auth.message); + const install = await loadInstall(env, auth.installId); + if (!install || install.tunnelSecret !== auth.secret) { + return jsonError(401, 'install credentials rejected'); + } + let body: unknown; + try { + body = await request.json(); + } catch { + return jsonError(400, 'invalid JSON body'); + } + const event = parseAnalyticsEvent(body); + if (!event) return jsonError(400, 'invalid analytics event'); + await recordEvent(env, auth.installId, event); + return new Response(JSON.stringify({ ok: true }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); +} + +type AuthOk = { ok: true; installId: number; secret: string }; +type AuthErr = { ok: false; status: number; message: string }; + +function authenticateInstall(request: Request): AuthOk | AuthErr { + const idRaw = request.headers.get('x-install-id'); + const secret = request.headers.get('x-install-secret'); + if (!idRaw || !secret) { + return { ok: false, status: 401, message: 'missing install credentials' }; + } + const installId = Number.parseInt(idRaw, 10); + if (!Number.isFinite(installId)) { + return { ok: false, status: 400, message: 'invalid install id' }; + } + return { ok: true, installId, secret }; +} + +function parseAnalyticsEvent(body: unknown): AnalyticsEvent | null { + if (!body || typeof body !== 'object') return null; + const kind = (body as { kind?: string }).kind; + if (kind === 'pr_reviewed' || kind === 'issue_handled' || kind === 'commit_pushed') { + return { kind }; + } + return null; +} + +// `created`/`added`/suspend/unsuspend are no-ops here - Desktop owns +// /register once the user enables Goose Bot. We only need to clean up KV on uninstall. +export async function handleInstallation(payload: InstallationEvent, env: Env): Promise { + if (payload.action === 'deleted') { + await deleteInstall(env, payload.installation.id); + await deleteRoutingPrefs(env, payload.installation.id); + await deleteAnalytics(env, payload.installation.id); + } +} + +export async function handlePullRequest(payload: PullRequestEvent, env: Env): Promise { + if (!['opened', 'synchronize', 'reopened', 'ready_for_review'].includes(payload.action)) return; + if (payload.pull_request.draft) return; + + const routing = await loadRoutingPrefs(env, payload.installation.id); + if (!routing.auto_review_on_pr_open) return; + if (routing.trigger_preference === 'manual-only') return; + if (payload.action === 'synchronize' && routing.trigger_preference === 'pr-open') return; + + await triggerReview({ + fullName: payload.repository.full_name, + prNumber: payload.number, + headSha: payload.pull_request.head.sha, + prUrl: payload.pull_request.html_url, + installationId: payload.installation.id, + env, + }); +} + +export async function handleIssueComment(payload: IssueCommentEvent, env: Env): Promise { + if (payload.action !== 'created') return; + // Bot accounts trigger nothing - prevents aaif-goose-bot[bot] from replying + // to its own comments and other bots (Dependabot, CodeRabbit, etc). + if (payload.comment.user.type === 'Bot') return; + if (!MENTION_RE.test(payload.comment.body)) return; + + const routing = await loadRoutingPrefs(env, payload.installation.id); + const isPr = Boolean(payload.issue.pull_request); + if (!isPr && !routing.allow_act_on_issues) return; + + const jwt = await generateAppJwt(env.GITHUB_APP_ID, env.GITHUB_APP_PRIVATE_KEY); + const token = await getInstallationToken(payload.installation.id, jwt); + + // Trigger-permission gate. We check BEFORE reacting, so an unauthorized + // commenter sees nothing (silent drop, no :eyes:). + if ( + !(await commenterMayTrigger( + routing.trigger_permission, + routing.specific_users_allowlist, + payload, + token + )) + ) { + return; + } + + let headSha: string; + let headRef: string; + let headRepo: string; + let contextUrl: string; + if (isPr) { + const pr = await getPullRequestHead( + payload.repository.full_name, + payload.issue.number, + token + ); + headSha = pr.sha; + headRef = pr.ref; + headRepo = pr.repoFullName; + contextUrl = pr.htmlUrl; + } else { + const branch = payload.repository.default_branch; + headSha = await getBranchHeadSha(payload.repository.full_name, branch, token); + headRef = ''; + headRepo = payload.repository.full_name; + contextUrl = payload.issue.html_url; + } + + // Ack the mention right away so the user knows the webhook fired. goosed + // will react with :+1: / :confused: once it's done. + await postCommentReaction( + payload.repository.full_name, + payload.comment.id, + 'eyes', + token + ).catch(() => {}); + + if (isPr && REVIEW_TRIGGER_RE.test(payload.comment.body)) { + await triggerReview({ + fullName: payload.repository.full_name, + prNumber: payload.issue.number, + headSha, + prUrl: contextUrl, + installationId: payload.installation.id, + env, + token, + commentId: payload.comment.id, + }); + return; + } + + await triggerComment({ + fullName: payload.repository.full_name, + prNumber: payload.issue.number, + headSha, + headRef, + headRepo, + prUrl: contextUrl, + commentBody: payload.comment.body, + commenter: payload.comment.user.login, + commentId: payload.comment.id, + isPr, + installationId: payload.installation.id, + env, + token, + }); +} + +async function triggerComment(opts: { + fullName: string; + prNumber: number; + headSha: string; + headRef: string; + headRepo: string; + prUrl: string; + commentBody: string; + commenter: string; + commentId: number; + isPr: boolean; + installationId: number; + env: Env; + token: string; +}): Promise { + const { fullName, prNumber, commentBody, commenter, installationId, env, token } = opts; + + const install = await loadInstall(env, installationId); + if (!install) { + // No registered goosed - surface that as a polite reply rather than silence. + await postIssueComment( + fullName, + prNumber, + `@${commenter} Goose Bot is installed on this repo but no local goose is connected. ` + + `Open Goose Desktop > Code Review > Connectors to enable.`, + token + ).catch((err) => + console.error(`[comment] ${fullName} #${prNumber}: post no-install reply failed: ${err}`) + ); + return; + } + + try { + const result = await runCommentViaTunnel(install, { + githubToken: token, + repo: fullName, + prNumber: opts.prNumber, + headSha: opts.headSha, + headRef: opts.headRef, + headRepo: opts.headRepo, + prUrl: opts.prUrl, + commentBody, + commenter, + commentId: opts.commentId, + isPr: opts.isPr, + }); + if (!result.ok) { + throw new Error(`tunnel responded ${result.status}: ${result.body.slice(0, 200)}`); + } + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + console.error(`[comment] ${fullName} #${prNumber}: ${msg}`); + try { + await postIssueComment( + fullName, + prNumber, + `@${commenter} Goose Bot couldn't reach your local goose. ` + + `Make sure Goose Desktop is running, then try again.`, + token + ); + } catch (postErr) { + console.error( + `[comment] ${fullName} #${prNumber}: also failed to post error reply: ${ + postErr instanceof Error ? postErr.message : postErr + }` + ); + } + } +} + +async function triggerReview(opts: { + fullName: string; + prNumber: number; + headSha: string; + prUrl: string; + installationId: number; + env: Env; + token?: string; + commentId?: number; +}): Promise { + const { fullName, prNumber, headSha, prUrl, installationId, env } = opts; + + const install = await loadInstall(env, installationId); + if (!install) { + await postNeutralCheck({ + fullName, + headSha, + installationId, + env, + title: 'Goose Bot not enabled', + summary: + 'No local goosed is registered for this installation. Open Goose Desktop > Code Review > Connectors to start receiving reviews.', + token: opts.token, + }).catch((err) => + console.error( + `[trigger] ${fullName} #${prNumber}: failed to post no-install neutral check: ${ + err instanceof Error ? err.message : err + }` + ) + ); + return; + } + + const token = + opts.token ?? + (await getInstallationToken( + installationId, + await generateAppJwt(env.GITHUB_APP_ID, env.GITHUB_APP_PRIVATE_KEY) + )); + + let checkRunId: number | undefined; + try { + checkRunId = await createCheckRun(fullName, headSha, token); + } catch {} + + try { + const result = await runReviewViaTunnel(install, { + githubToken: token, + repo: fullName, + prNumber, + headSha, + prUrl, + checkRunId, + commentId: opts.commentId, + }); + + if (!result.ok) { + throw new Error(`tunnel responded ${result.status}: ${result.body.slice(0, 200)}`); + } + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + console.error(`[trigger] ${fullName} #${prNumber}: ${msg}`); + if (checkRunId !== undefined) { + try { + await completeCheckRun({ + fullName, + checkRunId, + conclusion: 'neutral', + title: 'Goose Bot offline', + summary: `Could not reach your local goosed via the tunnel:\n\n${msg}\n\nMake sure Goose Desktop is running and try \`@aaif-goose-bot review\` to retry.`, + token, + }); + } catch (completeErr) { + console.error( + `[trigger] ${fullName} #${prNumber}: also failed to complete check run: ${ + completeErr instanceof Error ? completeErr.message : completeErr + }` + ); + } + } + } +} + +async function postNeutralCheck(opts: { + fullName: string; + headSha: string; + installationId: number; + env: Env; + title: string; + summary: string; + token?: string; +}): Promise { + const token = + opts.token ?? + (await getInstallationToken( + opts.installationId, + await generateAppJwt(opts.env.GITHUB_APP_ID, opts.env.GITHUB_APP_PRIVATE_KEY) + )); + const checkRunId = await createCheckRun(opts.fullName, opts.headSha, token); + await completeCheckRun({ + fullName: opts.fullName, + checkRunId, + conclusion: 'neutral', + title: opts.title, + summary: opts.summary, + token, + }); +} + +async function commenterMayTrigger( + permission: TriggerPermission, + allowlist: string[], + payload: IssueCommentEvent, + token: string +): Promise { + if (permission === 'anyone') return true; + if (permission === 'specific-users') { + const commenter = payload.comment.user.login.toLowerCase(); + return allowlist.some((u) => u.trim().toLowerCase() === commenter); + } + const level = await getCommenterPermission( + payload.repository.full_name, + payload.comment.user.login, + token + ); + return level === 'admin' || level === 'maintain' || level === 'write'; +} diff --git a/services/goose-bot-switchboard/src/lib/oauth.ts b/services/goose-bot-switchboard/src/lib/oauth.ts new file mode 100644 index 000000000000..eed9de457780 --- /dev/null +++ b/services/goose-bot-switchboard/src/lib/oauth.ts @@ -0,0 +1,92 @@ +const UA = 'goose-bot-switchboard/0.1'; + +interface OAuthTokenResponse { + access_token?: string; + error?: string; + error_description?: string; +} + +interface InstallationListResponse { + total_count: number; + installations: Array<{ id: number; app_id: number; account: { login: string } | null }>; +} + +export type ResolveResult = + | { ok: true; installationId: number; accountLogin: string | null } + | { ok: false; status: number; error: string }; + +export async function exchangeCodeAndResolve(opts: { + clientId: string; + clientSecret: string; + appId: number; + code: string; +}): Promise { + const tokenRes = await fetch('https://github.com/login/oauth/access_token', { + method: 'POST', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + 'User-Agent': UA, + }, + body: JSON.stringify({ + client_id: opts.clientId, + client_secret: opts.clientSecret, + code: opts.code, + }), + }); + + if (!tokenRes.ok) { + return { ok: false, status: 502, error: `code exchange failed: ${tokenRes.status}` }; + } + const tokenBody = (await tokenRes.json()) as OAuthTokenResponse; + if (tokenBody.error || !tokenBody.access_token) { + return { + ok: false, + status: 400, + error: `oauth error: ${tokenBody.error ?? 'no access_token returned'}`, + }; + } + + const userToken = tokenBody.access_token; + const installRes = await fetch('https://api.github.com/user/installations?per_page=100', { + headers: { + Authorization: `Bearer ${userToken}`, + Accept: 'application/vnd.github+json', + 'X-GitHub-Api-Version': '2022-11-28', + 'User-Agent': UA, + }, + }); + if (!installRes.ok) { + return { + ok: false, + status: 502, + error: `installations lookup failed: ${installRes.status}`, + }; + } + const installs = (await installRes.json()) as InstallationListResponse; + const mine = installs.installations.filter((i) => i.app_id === opts.appId); + if (mine.length === 0) { + return { + ok: false, + status: 409, + error: + 'Goose Bot is not installed on any account this user can access. Install the GitHub App first.', + }; + } + if (mine.length > 1) { + const accounts = mine + .map((i) => i.account?.login) + .filter((login): login is string => Boolean(login)); + return { + ok: false, + status: 409, + error: `Goose Bot is installed on multiple accounts (${accounts.join(', ')}). Install it on one account or reconnect after narrowing installation access.`, + }; + } + const chosen = mine[0]; + return { + ok: true, + installationId: chosen.id, + accountLogin: chosen.account?.login ?? null, + }; +} diff --git a/services/goose-bot-switchboard/src/lib/prefs.test.ts b/services/goose-bot-switchboard/src/lib/prefs.test.ts new file mode 100644 index 000000000000..b31a72f10fd5 --- /dev/null +++ b/services/goose-bot-switchboard/src/lib/prefs.test.ts @@ -0,0 +1,13 @@ +import { describe, expect, it } from 'vitest'; +import defaultFixture from '../../fixtures/routing_prefs_default.json'; +import { DEFAULT_ROUTING_PREFS, parseRoutingPrefs } from './prefs'; + +describe('routing prefs schema sync', () => { + it('default matches Rust fixture', () => { + expect(DEFAULT_ROUTING_PREFS).toEqual(defaultFixture); + }); + + it('parseRoutingPrefs accepts fixture', () => { + expect(parseRoutingPrefs(defaultFixture)).toEqual(defaultFixture); + }); +}); diff --git a/services/goose-bot-switchboard/src/lib/prefs.ts b/services/goose-bot-switchboard/src/lib/prefs.ts new file mode 100644 index 000000000000..f8aadb69a030 --- /dev/null +++ b/services/goose-bot-switchboard/src/lib/prefs.ts @@ -0,0 +1,136 @@ +// Routing prefs cache - authoritative copy lives in goosed (see crates/goose/src/goose-bot/prefs.rs). +// DEFAULT_ROUTING_PREFS must match fixtures/routing_prefs_default.json (checked by Rust + vitest). + +import type { Env } from './types'; + +export const CURRENT_SCHEMA_VERSION = 1; + +const KV_PREFIX = 'routing'; +const KV_TTL_SECONDS = 365 * 24 * 60 * 60; + +export type TriggerPreference = 'pr-open' | 'on-every-push' | 'manual-only'; +export type TriggerPermission = 'anyone' | 'write-access' | 'specific-users'; + +export interface RoutingPrefs { + schema_version: number; + auto_review_on_pr_open: boolean; + trigger_preference: TriggerPreference; + trigger_permission: TriggerPermission; + allow_act_on_issues: boolean; + specific_users_allowlist: string[]; +} + +export const DEFAULT_ROUTING_PREFS: RoutingPrefs = { + schema_version: CURRENT_SCHEMA_VERSION, + auto_review_on_pr_open: false, + trigger_preference: 'pr-open', + trigger_permission: 'anyone', + allow_act_on_issues: false, + specific_users_allowlist: [], +}; + +function key(installationId: number): string { + return `${KV_PREFIX}:${installationId}`; +} + +export async function loadRoutingPrefs( + env: Env, + installationId: number +): Promise { + const raw = await env.INSTALL_REGISTRY.get(key(installationId)); + if (!raw) return DEFAULT_ROUTING_PREFS; + try { + const parsed = JSON.parse(raw) as RoutingPrefs; + if (typeof parsed?.schema_version !== 'number') return DEFAULT_ROUTING_PREFS; + if (parsed.schema_version > CURRENT_SCHEMA_VERSION) { + return DEFAULT_ROUTING_PREFS; + } + // Merge so partial older payloads still produce a complete object. + return { ...DEFAULT_ROUTING_PREFS, ...parsed }; + } catch { + return DEFAULT_ROUTING_PREFS; + } +} + +export async function saveRoutingPrefs( + env: Env, + installationId: number, + prefs: RoutingPrefs +): Promise { + await env.INSTALL_REGISTRY.put(key(installationId), JSON.stringify(prefs), { + expirationTtl: KV_TTL_SECONDS, + }); +} + +export async function deleteRoutingPrefs( + env: Env, + installationId: number +): Promise { + await env.INSTALL_REGISTRY.delete(key(installationId)); +} + +export function parseRoutingPrefs(body: unknown): RoutingPrefs { + if (!body || typeof body !== 'object') { + throw new Error('body must be a JSON object'); + } + const b = body as Partial; + + const sv = b.schema_version; + if (typeof sv !== 'number' || sv < 1) { + throw new Error('schema_version must be a positive integer'); + } + if (sv > CURRENT_SCHEMA_VERSION) { + throw new Error( + `schema_version ${sv} is newer than this switchboard understands (${CURRENT_SCHEMA_VERSION})` + ); + } + + const triggerPref = b.trigger_preference; + if ( + triggerPref !== 'pr-open' && + triggerPref !== 'on-every-push' && + triggerPref !== 'manual-only' + ) { + throw new Error('trigger_preference must be one of pr-open|on-every-push|manual-only'); + } + + const triggerPerm = b.trigger_permission; + if ( + triggerPerm !== 'anyone' && + triggerPerm !== 'write-access' && + triggerPerm !== 'specific-users' + ) { + throw new Error( + 'trigger_permission must be one of anyone|write-access|specific-users' + ); + } + + if (typeof b.auto_review_on_pr_open !== 'boolean') { + throw new Error('auto_review_on_pr_open must be a boolean'); + } + if (typeof b.allow_act_on_issues !== 'boolean') { + throw new Error('allow_act_on_issues must be a boolean'); + } + + const rawAllowlist = b.specific_users_allowlist ?? []; + if (!Array.isArray(rawAllowlist)) { + throw new Error('specific_users_allowlist must be an array of strings'); + } + const allowlist: string[] = []; + for (const entry of rawAllowlist) { + if (typeof entry !== 'string') { + throw new Error('specific_users_allowlist entries must be strings'); + } + const trimmed = entry.trim(); + if (trimmed.length > 0) allowlist.push(trimmed); + } + + return { + schema_version: sv, + auto_review_on_pr_open: b.auto_review_on_pr_open, + trigger_preference: triggerPref, + trigger_permission: triggerPerm, + allow_act_on_issues: b.allow_act_on_issues, + specific_users_allowlist: allowlist, + }; +} diff --git a/services/goose-bot-switchboard/src/lib/registry.ts b/services/goose-bot-switchboard/src/lib/registry.ts new file mode 100644 index 000000000000..d374dcab4b18 --- /dev/null +++ b/services/goose-bot-switchboard/src/lib/registry.ts @@ -0,0 +1,77 @@ +import type { Env, InstallRecord } from './types'; + +function installKey(installationId: number): string { + return `install:${installationId}`; +} + +function agentKey(agentId: string): string { + return `agent:${agentId}`; +} + +export async function loadInstall( + env: Env, + installationId: number +): Promise { + const raw = await env.INSTALL_REGISTRY.get(installKey(installationId)); + if (!raw) return null; + try { + return JSON.parse(raw) as InstallRecord; + } catch { + return null; + } +} + +export async function loadInstallByAgent( + env: Env, + agentId: string +): Promise { + const idRaw = await env.INSTALL_REGISTRY.get(agentKey(agentId)); + if (idRaw) { + const id = Number.parseInt(idRaw, 10); + if (Number.isFinite(id)) { + const direct = await loadInstall(env, id); + if (direct?.agentId === agentId) return direct; + } + } + + // Pre-reverse-index installs: scan primary keys and backfill agent:. + let cursor: string | undefined; + do { + const list = await env.INSTALL_REGISTRY.list({ + prefix: 'install:', + limit: 1000, + cursor, + }); + for (const item of list.keys) { + const raw = await env.INSTALL_REGISTRY.get(item.name); + if (!raw) continue; + let record: InstallRecord; + try { + record = JSON.parse(raw) as InstallRecord; + } catch { + continue; + } + if (record.agentId !== agentId) continue; + await env.INSTALL_REGISTRY.put(agentKey(agentId), String(record.installationId)); + return record; + } + cursor = list.list_complete ? undefined : list.cursor; + } while (cursor); + return null; +} + +export async function saveInstall(env: Env, record: InstallRecord): Promise { + await Promise.all([ + env.INSTALL_REGISTRY.put(installKey(record.installationId), JSON.stringify(record)), + env.INSTALL_REGISTRY.put(agentKey(record.agentId), String(record.installationId)), + ]); +} + +export async function deleteInstall(env: Env, installationId: number): Promise { + const existing = await loadInstall(env, installationId); + const tasks: Promise[] = [env.INSTALL_REGISTRY.delete(installKey(installationId))]; + if (existing) { + tasks.push(env.INSTALL_REGISTRY.delete(agentKey(existing.agentId))); + } + await Promise.all(tasks); +} diff --git a/services/goose-bot-switchboard/src/lib/tunnel.test.ts b/services/goose-bot-switchboard/src/lib/tunnel.test.ts new file mode 100644 index 000000000000..374843cad364 --- /dev/null +++ b/services/goose-bot-switchboard/src/lib/tunnel.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, it } from 'vitest'; +import { agentIdFromTunnelUrl } from './tunnel'; + +describe('agentIdFromTunnelUrl', () => { + it('parses agent id from lapstone tunnel url', () => { + expect( + agentIdFromTunnelUrl('https://proxy.example/tunnel/abc123') + ).toBe('abc123'); + }); + + it('rejects urls without tunnel segment', () => { + expect(agentIdFromTunnelUrl('https://proxy.example/nope')).toBeNull(); + }); +}); diff --git a/services/goose-bot-switchboard/src/lib/tunnel.ts b/services/goose-bot-switchboard/src/lib/tunnel.ts new file mode 100644 index 000000000000..bc76544b131b --- /dev/null +++ b/services/goose-bot-switchboard/src/lib/tunnel.ts @@ -0,0 +1,130 @@ +// lapstone forwards any request hitting `/tunnel//*` to +// `127.0.0.1:/*` after validating `X-Secret-Key`. So we just +// POST `/goose-bot/` with the per-install secret. + +import type { InstallRecord } from './types'; + +export interface TunnelRunParams { + githubToken: string; + repo: string; + prNumber: number; + headSha: string; + prUrl: string; + checkRunId?: number; + commentId?: number; +} + +export interface TunnelCommentParams { + githubToken: string; + repo: string; + prNumber: number; + headSha: string; + headRef: string; + prUrl: string; + commentBody: string; + commenter: string; + commentId: number; + isPr: boolean; + headRepo: string; +} + +export interface TunnelRunResult { + ok: boolean; + status: number; + body: string; +} + +const TUNNEL_TIMEOUT_MS = 20_000; +const REGISTER_PROBE_TIMEOUT_MS = 10_000; + +export function agentIdFromTunnelUrl(tunnelUrl: string): string | null { + const match = tunnelUrl.match(/\/tunnel\/([^/?#]+)/); + return match?.[1] ?? null; +} + +/** Proves the registrant controls tunnel_url + tunnel_secret before we write KV. */ +export async function verifyTunnelReachable( + tunnelUrl: string, + tunnelSecret: string +): Promise<{ ok: true } | { ok: false; error: string }> { + const base = tunnelUrl.replace(/\/$/, ''); + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), REGISTER_PROBE_TIMEOUT_MS); + try { + const res = await fetch(`${base}/goose-bot/status`, { + method: 'GET', + headers: { 'X-Secret-Key': tunnelSecret }, + signal: controller.signal, + }); + if (!res.ok) { + return { + ok: false, + error: `tunnel probe returned ${res.status}`, + }; + } + return { ok: true }; + } catch (e) { + const msg = e instanceof Error ? e.message : String(e); + return { ok: false, error: `tunnel probe failed: ${msg}` }; + } finally { + clearTimeout(timeout); + } +} + +async function postJson( + install: InstallRecord, + path: string, + body: unknown +): Promise { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), TUNNEL_TIMEOUT_MS); + try { + const res = await fetch(`${install.tunnelUrl}${path}`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Secret-Key': install.tunnelSecret, + }, + signal: controller.signal, + body: JSON.stringify(body), + }); + const text = await res.text(); + return { ok: res.ok, status: res.status, body: text }; + } finally { + clearTimeout(timeout); + } +} + +export async function runReviewViaTunnel( + install: InstallRecord, + params: TunnelRunParams +): Promise { + return postJson(install, '/goose-bot/review', { + github_token: params.githubToken, + repo: params.repo, + pr_number: params.prNumber, + head_sha: params.headSha, + pr_url: params.prUrl, + check_run_id: params.checkRunId, + comment_id: params.commentId, + }); +} + +export async function runCommentViaTunnel( + install: InstallRecord, + params: TunnelCommentParams +): Promise { + return postJson(install, '/goose-bot/comment', { + github_token: params.githubToken, + repo: params.repo, + pr_number: params.prNumber, + head_sha: params.headSha, + head_ref: params.headRef, + head_repo: params.headRepo, + pr_url: params.prUrl, + comment_body: params.commentBody, + commenter: params.commenter, + comment_id: params.commentId, + is_pr: params.isPr, + }); +} diff --git a/services/goose-bot-switchboard/src/lib/types.ts b/services/goose-bot-switchboard/src/lib/types.ts new file mode 100644 index 000000000000..4cc93192231b --- /dev/null +++ b/services/goose-bot-switchboard/src/lib/types.ts @@ -0,0 +1,60 @@ +export interface Env { + GITHUB_APP_ID: string; + GITHUB_APP_PRIVATE_KEY: string; + GITHUB_WEBHOOK_SECRET: string; + GITHUB_OAUTH_CLIENT_ID: string; + GITHUB_OAUTH_CLIENT_SECRET: string; + INSTALL_REGISTRY: KVNamespace; +} + +export interface InstallRecord { + installationId: number; + agentId: string; + tunnelSecret: string; + tunnelUrl: string; + registeredAt: string; +} + +export interface RegisterRequest { + oauth_code: string; + agent_id: string; + tunnel_secret: string; + tunnel_url: string; +} + +export interface InstallationEvent { + action: 'created' | 'deleted' | 'suspend' | 'unsuspend' | 'new_permissions_accepted'; + installation: { id: number; account: { login: string } | null }; + repositories?: Array<{ full_name: string; default_branch?: string }>; +} + +export interface PullRequestEvent { + action: string; + number: number; + pull_request: { + head: { ref: string; sha: string }; + base: { ref: string }; + title: string; + body: string | null; + html_url: string; + draft?: boolean; + }; + repository: { full_name: string; default_branch: string }; + installation: { id: number }; +} + +export interface IssueCommentEvent { + action: 'created' | 'edited' | 'deleted'; + comment: { + id: number; + body: string; + user: { login: string; type: 'User' | 'Bot' | 'Organization' }; + }; + issue: { + number: number; + html_url: string; + pull_request?: { url: string } | null; + }; + repository: { full_name: string; default_branch: string }; + installation: { id: number }; +} diff --git a/services/goose-bot-switchboard/tsconfig.json b/services/goose-bot-switchboard/tsconfig.json new file mode 100644 index 000000000000..804ac74794a1 --- /dev/null +++ b/services/goose-bot-switchboard/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ES2022", + "moduleResolution": "bundler", + "lib": ["ES2022"], + "types": ["@cloudflare/workers-types"], + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "isolatedModules": true, + "resolveJsonModule": true, + "allowJs": false, + "noEmit": true + }, + "include": ["src/**/*"] +} diff --git a/services/goose-bot-switchboard/wrangler.toml.example b/services/goose-bot-switchboard/wrangler.toml.example new file mode 100644 index 000000000000..6fbc1cb96c31 --- /dev/null +++ b/services/goose-bot-switchboard/wrangler.toml.example @@ -0,0 +1,21 @@ +name = "goose-bot-switchboard" +main = "src/index.ts" +compatibility_date = "2025-01-01" +compatibility_flags = ["nodejs_compat"] + +# Copy to `wrangler.toml` (gitignored), create the KV namespace, and set secrets below. +# +# Secrets (set via `wrangler secret put`, NOT here): +# GITHUB_APP_ID - numeric App ID +# GITHUB_APP_PRIVATE_KEY - PEM contents (full PRIVATE KEY block, newlines preserved) +# GITHUB_WEBHOOK_SECRET - HMAC shared secret configured on the App's webhook +# GITHUB_OAUTH_CLIENT_ID - public OAuth client ID from the App settings +# GITHUB_OAUTH_CLIENT_SECRET - OAuth client secret from the App settings + +[[kv_namespaces]] +binding = "INSTALL_REGISTRY" +# Run `wrangler kv namespace create INSTALL_REGISTRY` and paste the id here. +id = "" + +[observability] +enabled = true diff --git a/ui/desktop/openapi.json b/ui/desktop/openapi.json index 3bd3b51992e8..1cefac336bd1 100644 --- a/ui/desktop/openapi.json +++ b/ui/desktop/openapi.json @@ -1993,6 +1993,248 @@ } } }, + "/goose-bot/analytics": { + "get": { + "tags": [ + "goose_bot" + ], + "operationId": "get_analytics", + "responses": { + "200": { + "description": "Per-install analytics rollups", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GooseBotAnalytics" + } + } + } + }, + "412": { + "description": "Setup not completed" + } + } + } + }, + "/goose-bot/comment": { + "post": { + "tags": [ + "goose_bot" + ], + "operationId": "comment", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GooseBotCommentRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Comment accepted, replying in background", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GooseBotReviewResponse" + } + } + } + }, + "500": { + "description": "Internal error" + } + } + } + }, + "/goose-bot/prefs": { + "get": { + "tags": [ + "goose_bot" + ], + "operationId": "get_prefs", + "responses": { + "200": { + "description": "Current Goose Bot preferences", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GooseBotPrefs" + } + } + } + }, + "500": { + "description": "Internal error" + } + } + }, + "put": { + "tags": [ + "goose_bot" + ], + "operationId": "put_prefs", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GooseBotPrefsRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Preferences saved", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GooseBotPrefsResponse" + } + } + } + }, + "400": { + "description": "Validation error" + }, + "500": { + "description": "Internal error" + } + } + } + }, + "/goose-bot/repos": { + "get": { + "tags": [ + "goose_bot" + ], + "operationId": "get_repos", + "responses": { + "200": { + "description": "Repos accessible to the installation", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GooseBotReposResponse" + } + } + } + }, + "412": { + "description": "Setup not completed" + }, + "502": { + "description": "Switchboard / GitHub error" + } + } + } + }, + "/goose-bot/review": { + "post": { + "tags": [ + "goose_bot" + ], + "operationId": "review", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GooseBotReviewRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Review accepted, running in background", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GooseBotReviewResponse" + } + } + } + }, + "500": { + "description": "Internal error" + } + } + } + }, + "/goose-bot/setup": { + "post": { + "tags": [ + "goose_bot" + ], + "operationId": "setup", + "responses": { + "200": { + "description": "Goose Bot connected", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GooseBotSetupResponse" + } + } + } + }, + "408": { + "description": "Install timed out" + }, + "409": { + "description": "GitHub App is not installed" + }, + "500": { + "description": "Internal error" + } + } + }, + "delete": { + "tags": [ + "goose_bot" + ], + "operationId": "disconnect", + "responses": { + "200": { + "description": "Local install cleared and switchboard registration removed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GooseBotDisconnectResponse" + } + } + } + }, + "500": { + "description": "Internal error" + } + } + } + }, + "/goose-bot/status": { + "get": { + "tags": [ + "goose_bot" + ], + "operationId": "get_status", + "responses": { + "200": { + "description": "Cached GitHub App installation id", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GooseBotStatusResponse" + } + } + } + } + } + } + }, "/handle_nanogpt": { "post": { "tags": [ @@ -5710,6 +5952,306 @@ } ] }, + "GooseBotAnalytics": { + "type": "object", + "properties": { + "commits_pushed": { + "type": "integer", + "format": "int64", + "minimum": 0 + }, + "issues_handled": { + "type": "integer", + "format": "int64", + "minimum": 0 + }, + "prs_reviewed": { + "type": "integer", + "format": "int64", + "minimum": 0 + } + } + }, + "GooseBotCommentRequest": { + "type": "object", + "required": [ + "github_token", + "repo", + "pr_number", + "pr_url", + "comment_body", + "commenter" + ], + "properties": { + "comment_body": { + "type": "string" + }, + "comment_id": { + "type": "integer", + "format": "int64", + "nullable": true, + "minimum": 0 + }, + "commenter": { + "type": "string" + }, + "github_token": { + "type": "string" + }, + "head_ref": { + "type": "string" + }, + "head_repo": { + "type": "string" + }, + "is_pr": { + "type": "boolean", + "description": "Omitted in older switchboard payloads (treated as PR); current switchboard always sends this." + }, + "pr_number": { + "type": "integer", + "format": "int64", + "minimum": 0 + }, + "pr_url": { + "type": "string" + }, + "repo": { + "type": "string" + } + } + }, + "GooseBotDisconnectResponse": { + "type": "object", + "required": [ + "disconnected" + ], + "properties": { + "disconnected": { + "type": "boolean" + } + } + }, + "GooseBotPrefs": { + "type": "object", + "properties": { + "allow_act_on_issues": { + "type": "boolean" + }, + "allow_commit_on_fix": { + "type": "boolean" + }, + "allow_open_new_prs": { + "type": "boolean" + }, + "auto_review_on_pr_open": { + "type": "boolean" + }, + "custom_instructions": { + "type": "string" + }, + "review_model": { + "type": "string", + "nullable": true + }, + "review_model_choice": { + "$ref": "#/components/schemas/ReviewModelChoice" + }, + "review_output_style": { + "$ref": "#/components/schemas/ReviewOutputStyle" + }, + "review_provider": { + "type": "string", + "nullable": true + }, + "review_severity": { + "$ref": "#/components/schemas/ReviewSeverity" + }, + "schema_version": { + "type": "integer", + "format": "int32", + "minimum": 0 + }, + "specific_users_allowlist": { + "type": "array", + "items": { + "type": "string" + } + }, + "trigger_permission": { + "$ref": "#/components/schemas/TriggerPermission" + }, + "trigger_preference": { + "$ref": "#/components/schemas/TriggerPreference" + } + } + }, + "GooseBotPrefsRequest": { + "type": "object", + "required": [ + "prefs" + ], + "properties": { + "prefs": { + "$ref": "#/components/schemas/GooseBotPrefs" + } + } + }, + "GooseBotPrefsResponse": { + "type": "object", + "required": [ + "prefs", + "switchboard_synced" + ], + "properties": { + "prefs": { + "$ref": "#/components/schemas/GooseBotPrefs" + }, + "switchboard_error": { + "type": "string", + "nullable": true + }, + "switchboard_synced": { + "type": "boolean" + } + } + }, + "GooseBotRepo": { + "type": "object", + "required": [ + "id", + "full_name", + "name", + "owner" + ], + "properties": { + "archived": { + "type": "boolean" + }, + "default_branch": { + "type": "string" + }, + "full_name": { + "type": "string" + }, + "html_url": { + "type": "string" + }, + "id": { + "type": "integer", + "format": "int64", + "minimum": 0 + }, + "name": { + "type": "string" + }, + "owner": { + "type": "string" + }, + "visibility": { + "$ref": "#/components/schemas/RepoVisibility" + } + } + }, + "GooseBotReposResponse": { + "type": "object", + "required": [ + "total_count", + "repos" + ], + "properties": { + "repos": { + "type": "array", + "items": { + "$ref": "#/components/schemas/GooseBotRepo" + } + }, + "total_count": { + "type": "integer", + "format": "int64", + "minimum": 0 + }, + "truncated": { + "type": "boolean" + } + } + }, + "GooseBotReviewRequest": { + "type": "object", + "required": [ + "github_token", + "repo", + "pr_number", + "head_sha", + "pr_url" + ], + "properties": { + "check_run_id": { + "type": "integer", + "format": "int64", + "nullable": true, + "minimum": 0 + }, + "comment_id": { + "type": "integer", + "format": "int64", + "nullable": true, + "minimum": 0 + }, + "github_token": { + "type": "string" + }, + "head_sha": { + "type": "string" + }, + "pr_number": { + "type": "integer", + "format": "int64", + "minimum": 0 + }, + "pr_url": { + "type": "string" + }, + "repo": { + "type": "string" + } + } + }, + "GooseBotReviewResponse": { + "type": "object", + "required": [ + "accepted" + ], + "properties": { + "accepted": { + "type": "boolean" + } + } + }, + "GooseBotSetupResponse": { + "type": "object", + "required": [ + "installation_id" + ], + "properties": { + "installation_id": { + "type": "integer", + "format": "int64", + "minimum": 0 + } + } + }, + "GooseBotStatusResponse": { + "type": "object", + "properties": { + "installation_id": { + "type": "integer", + "format": "int64", + "nullable": true, + "minimum": 0 + } + } + }, "GooseMode": { "type": "string", "enum": [ @@ -7759,6 +8301,15 @@ } } }, + "RepoVisibility": { + "type": "string", + "enum": [ + "public", + "private", + "internal", + "unknown" + ] + }, "ResourceContents": { "anyOf": [ { @@ -7929,6 +8480,30 @@ } } }, + "ReviewModelChoice": { + "type": "string", + "enum": [ + "default", + "custom" + ] + }, + "ReviewOutputStyle": { + "type": "string", + "enum": [ + "inline", + "summary", + "both" + ] + }, + "ReviewSeverity": { + "type": "string", + "enum": [ + "low", + "medium", + "high", + "critical" + ] + }, "Role": { "oneOf": [ { @@ -7945,6 +8520,41 @@ } ] }, + "RoutingPrefs": { + "type": "object", + "required": [ + "schema_version", + "auto_review_on_pr_open", + "trigger_preference", + "trigger_permission", + "allow_act_on_issues" + ], + "properties": { + "allow_act_on_issues": { + "type": "boolean" + }, + "auto_review_on_pr_open": { + "type": "boolean" + }, + "schema_version": { + "type": "integer", + "format": "int32", + "minimum": 0 + }, + "specific_users_allowlist": { + "type": "array", + "items": { + "type": "string" + } + }, + "trigger_permission": { + "$ref": "#/components/schemas/TriggerPermission" + }, + "trigger_preference": { + "$ref": "#/components/schemas/TriggerPreference" + } + } + }, "RunNowResponse": { "type": "object", "required": [ @@ -9189,6 +9799,22 @@ } } }, + "TriggerPermission": { + "type": "string", + "enum": [ + "anyone", + "write-access", + "specific-users" + ] + }, + "TriggerPreference": { + "type": "string", + "enum": [ + "pr-open", + "on-every-push", + "manual-only" + ] + }, "TunnelInfo": { "type": "object", "required": [ diff --git a/ui/desktop/src/App.tsx b/ui/desktop/src/App.tsx index e53dcde476ac..58251f9f8671 100644 --- a/ui/desktop/src/App.tsx +++ b/ui/desktop/src/App.tsx @@ -45,6 +45,7 @@ import PermissionSettingsView from './components/settings/permission/PermissionS import ExtensionsView, { ExtensionsViewOptions } from './components/extensions/ExtensionsView'; import RecipesView from './components/recipes/RecipesView'; import SkillsView from './components/skills/SkillsView'; +import GooseBotView from './components/goose_bot/GooseBotView'; import AppsView from './components/apps/AppsView'; import StandaloneAppView from './components/apps/StandaloneAppView'; import { View, ViewOptions } from './utils/navigationUtils'; @@ -213,6 +214,10 @@ const SkillsRoute = () => { return ; }; +const GooseBotRoute = () => { + return ; +}; + const PermissionRoute = () => { const location = useLocation(); const navigate = useNavigate(); @@ -486,13 +491,18 @@ export function AppInner() { // Show a toast if mesh is the configured provider but isn't running. useEffect(() => { const handler = () => { - toast.warn('Inference Mesh is set as your provider but isn\'t running. Open Settings → Mesh to start it. Keep goose running to stay connected.', { - autoClose: false, - toastId: 'mesh-not-running', - }); + toast.warn( + "Inference Mesh is set as your provider but isn't running. Open Settings → Mesh to start it. Keep goose running to stay connected.", + { + autoClose: false, + toastId: 'mesh-not-running', + } + ); }; window.electron.on('mesh-not-running', handler); - return () => { window.electron.off('mesh-not-running', handler); }; + return () => { + window.electron.off('mesh-not-running', handler); + }; }, []); // Prevent default drag and drop behavior globally to avoid opening files in new windows @@ -691,6 +701,7 @@ export function AppInner() { } /> } /> } /> + } /> = Options2 & { /** @@ -319,6 +319,45 @@ export const transcribeDictation = (option export const getFeatures = (options?: Options) => (options?.client ?? client).get({ url: '/features', ...options }); +export const getAnalytics = (options?: Options) => (options?.client ?? client).get({ url: '/goose-bot/analytics', ...options }); + +export const comment = (options: Options) => (options.client ?? client).post({ + url: '/goose-bot/comment', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const getPrefs = (options?: Options) => (options?.client ?? client).get({ url: '/goose-bot/prefs', ...options }); + +export const putPrefs = (options: Options) => (options.client ?? client).put({ + url: '/goose-bot/prefs', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const getRepos = (options?: Options) => (options?.client ?? client).get({ url: '/goose-bot/repos', ...options }); + +export const review = (options: Options) => (options.client ?? client).post({ + url: '/goose-bot/review', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +export const disconnect = (options?: Options) => (options?.client ?? client).delete({ url: '/goose-bot/setup', ...options }); + +export const setup = (options?: Options) => (options?.client ?? client).post({ url: '/goose-bot/setup', ...options }); + +export const getStatus = (options?: Options) => (options?.client ?? client).get({ url: '/goose-bot/status', ...options }); + export const startNanogptSetup = (options?: Options) => (options?.client ?? client).post({ url: '/handle_nanogpt', ...options }); export const startOpenrouterSetup = (options?: Options) => (options?.client ?? client).post({ url: '/handle_openrouter', ...options }); diff --git a/ui/desktop/src/api/types.gen.ts b/ui/desktop/src/api/types.gen.ts index fda990138938..aea0fd2e68d0 100644 --- a/ui/desktop/src/api/types.gen.ts +++ b/ui/desktop/src/api/types.gen.ts @@ -540,6 +540,98 @@ export type GooseApp = McpAppResource & (WindowProps | null) & { prd?: string | null; }; +export type GooseBotAnalytics = { + commits_pushed?: number; + issues_handled?: number; + prs_reviewed?: number; +}; + +export type GooseBotCommentRequest = { + comment_body: string; + comment_id?: number | null; + commenter: string; + github_token: string; + head_ref?: string; + head_repo?: string; + /** + * Omitted in older switchboard payloads (treated as PR); current switchboard always sends this. + */ + is_pr?: boolean; + pr_number: number; + pr_url: string; + repo: string; +}; + +export type GooseBotDisconnectResponse = { + disconnected: boolean; +}; + +export type GooseBotPrefs = { + allow_act_on_issues?: boolean; + allow_commit_on_fix?: boolean; + allow_open_new_prs?: boolean; + auto_review_on_pr_open?: boolean; + custom_instructions?: string; + review_model?: string | null; + review_model_choice?: ReviewModelChoice; + review_output_style?: ReviewOutputStyle; + review_provider?: string | null; + review_severity?: ReviewSeverity; + schema_version?: number; + specific_users_allowlist?: Array; + trigger_permission?: TriggerPermission; + trigger_preference?: TriggerPreference; +}; + +export type GooseBotPrefsRequest = { + prefs: GooseBotPrefs; +}; + +export type GooseBotPrefsResponse = { + prefs: GooseBotPrefs; + switchboard_error?: string | null; + switchboard_synced: boolean; +}; + +export type GooseBotRepo = { + archived?: boolean; + default_branch?: string; + full_name: string; + html_url?: string; + id: number; + name: string; + owner: string; + visibility?: RepoVisibility; +}; + +export type GooseBotReposResponse = { + repos: Array; + total_count: number; + truncated?: boolean; +}; + +export type GooseBotReviewRequest = { + check_run_id?: number | null; + comment_id?: number | null; + github_token: string; + head_sha: string; + pr_number: number; + pr_url: string; + repo: string; +}; + +export type GooseBotReviewResponse = { + accepted: boolean; +}; + +export type GooseBotSetupResponse = { + installation_id: number; +}; + +export type GooseBotStatusResponse = { + installation_id?: number | null; +}; + export type GooseMode = 'auto' | 'approve' | 'smart_approve' | 'chat'; /** @@ -1187,6 +1279,8 @@ export type RepoVariantsResponse = { variants: Array; }; +export type RepoVisibility = 'public' | 'private' | 'internal' | 'unknown'; + export type ResourceContents = { _meta?: { [key: string]: unknown; @@ -1258,8 +1352,23 @@ export type RetryConfig = { timeout_seconds?: number | null; }; +export type ReviewModelChoice = 'default' | 'custom'; + +export type ReviewOutputStyle = 'inline' | 'summary' | 'both'; + +export type ReviewSeverity = 'low' | 'medium' | 'high' | 'critical'; + export type Role = 'user' | 'assistant'; +export type RoutingPrefs = { + allow_act_on_issues: boolean; + auto_review_on_pr_open: boolean; + schema_version: number; + specific_users_allowlist?: Array; + trigger_permission: TriggerPermission; + trigger_preference: TriggerPreference; +}; + export type RunNowResponse = { session_id: string; }; @@ -1652,6 +1761,10 @@ export type TranscribeResponse = { text: string; }; +export type TriggerPermission = 'anyone' | 'write-access' | 'specific-users'; + +export type TriggerPreference = 'pr-open' | 'on-every-push' | 'manual-only'; + export type TunnelInfo = { hostname: string; secret: string; @@ -3292,6 +3405,222 @@ export type GetFeaturesResponses = { export type GetFeaturesResponse = GetFeaturesResponses[keyof GetFeaturesResponses]; +export type GetAnalyticsData = { + body?: never; + path?: never; + query?: never; + url: '/goose-bot/analytics'; +}; + +export type GetAnalyticsErrors = { + /** + * Setup not completed + */ + 412: unknown; +}; + +export type GetAnalyticsResponses = { + /** + * Per-install analytics rollups + */ + 200: GooseBotAnalytics; +}; + +export type GetAnalyticsResponse = GetAnalyticsResponses[keyof GetAnalyticsResponses]; + +export type CommentData = { + body: GooseBotCommentRequest; + path?: never; + query?: never; + url: '/goose-bot/comment'; +}; + +export type CommentErrors = { + /** + * Internal error + */ + 500: unknown; +}; + +export type CommentResponses = { + /** + * Comment accepted, replying in background + */ + 200: GooseBotReviewResponse; +}; + +export type CommentResponse = CommentResponses[keyof CommentResponses]; + +export type GetPrefsData = { + body?: never; + path?: never; + query?: never; + url: '/goose-bot/prefs'; +}; + +export type GetPrefsErrors = { + /** + * Internal error + */ + 500: unknown; +}; + +export type GetPrefsResponses = { + /** + * Current Goose Bot preferences + */ + 200: GooseBotPrefs; +}; + +export type GetPrefsResponse = GetPrefsResponses[keyof GetPrefsResponses]; + +export type PutPrefsData = { + body: GooseBotPrefsRequest; + path?: never; + query?: never; + url: '/goose-bot/prefs'; +}; + +export type PutPrefsErrors = { + /** + * Validation error + */ + 400: unknown; + /** + * Internal error + */ + 500: unknown; +}; + +export type PutPrefsResponses = { + /** + * Preferences saved + */ + 200: GooseBotPrefsResponse; +}; + +export type PutPrefsResponse = PutPrefsResponses[keyof PutPrefsResponses]; + +export type GetReposData = { + body?: never; + path?: never; + query?: never; + url: '/goose-bot/repos'; +}; + +export type GetReposErrors = { + /** + * Setup not completed + */ + 412: unknown; + /** + * Switchboard / GitHub error + */ + 502: unknown; +}; + +export type GetReposResponses = { + /** + * Repos accessible to the installation + */ + 200: GooseBotReposResponse; +}; + +export type GetReposResponse = GetReposResponses[keyof GetReposResponses]; + +export type ReviewData = { + body: GooseBotReviewRequest; + path?: never; + query?: never; + url: '/goose-bot/review'; +}; + +export type ReviewErrors = { + /** + * Internal error + */ + 500: unknown; +}; + +export type ReviewResponses = { + /** + * Review accepted, running in background + */ + 200: GooseBotReviewResponse; +}; + +export type ReviewResponse = ReviewResponses[keyof ReviewResponses]; + +export type DisconnectData = { + body?: never; + path?: never; + query?: never; + url: '/goose-bot/setup'; +}; + +export type DisconnectErrors = { + /** + * Internal error + */ + 500: unknown; +}; + +export type DisconnectResponses = { + /** + * Local install cleared and switchboard registration removed + */ + 200: GooseBotDisconnectResponse; +}; + +export type DisconnectResponse = DisconnectResponses[keyof DisconnectResponses]; + +export type SetupData = { + body?: never; + path?: never; + query?: never; + url: '/goose-bot/setup'; +}; + +export type SetupErrors = { + /** + * Install timed out + */ + 408: unknown; + /** + * GitHub App is not installed + */ + 409: unknown; + /** + * Internal error + */ + 500: unknown; +}; + +export type SetupResponses = { + /** + * Goose Bot connected + */ + 200: GooseBotSetupResponse; +}; + +export type SetupResponse2 = SetupResponses[keyof SetupResponses]; + +export type GetStatusData = { + body?: never; + path?: never; + query?: never; + url: '/goose-bot/status'; +}; + +export type GetStatusResponses = { + /** + * Cached GitHub App installation id + */ + 200: GooseBotStatusResponse; +}; + +export type GetStatusResponse = GetStatusResponses[keyof GetStatusResponses]; + export type StartNanogptSetupData = { body?: never; path?: never; diff --git a/ui/desktop/src/components/goose_bot/GooseBotView.tsx b/ui/desktop/src/components/goose_bot/GooseBotView.tsx new file mode 100644 index 000000000000..ade7fb600fcf --- /dev/null +++ b/ui/desktop/src/components/goose_bot/GooseBotView.tsx @@ -0,0 +1,311 @@ +import { useCallback, useEffect, useState } from 'react'; +import { + AlertCircle, + BarChart3, + ExternalLink, + Info, + ListChecks, + Plug, + Settings as SettingsIcon, +} from 'lucide-react'; +import { MainPanelLayout } from '../Layout/MainPanelLayout'; +import { ScrollArea } from '../ui/scroll-area'; +import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs'; +import { Card, CardContent } from '../ui/card'; +import { Button } from '../ui/button'; +import { getTunnelStatus } from '../../api/sdk.gen'; +import type { TunnelInfo } from '../../api/types.gen'; +import { defineMessages, useIntl } from '../../i18n'; +import GooseBotGeneral from './sections/GooseBotGeneral'; +import GooseBotCodeReview from './sections/GooseBotCodeReview'; +import GooseBotAnalytics from './sections/GooseBotAnalytics'; +import GooseBotConnectors from './sections/GooseBotConnectors'; +import { SaveIndicator } from './SaveIndicator'; +import { useGooseBotPrefs } from './useGooseBotPrefs'; +import { fetchGooseBotInstallId } from '../../utils/gooseBotSetup'; + +const STORAGE_KEY = 'goose-bot:installation'; + +export interface StoredInstall { + installationId: number; + enabledAt: string; +} + +function loadStoredInstall(): StoredInstall | null { + const raw = localStorage.getItem(STORAGE_KEY); + if (!raw) return null; + try { + return JSON.parse(raw) as StoredInstall; + } catch { + return null; + } +} + +const i18n = defineMessages({ + pageTitle: { + id: 'gooseBotView.pageTitle', + defaultMessage: 'Goose Bot', + }, + tabGeneral: { + id: 'gooseBotView.tabGeneral', + defaultMessage: 'General', + }, + tabCodeReview: { + id: 'gooseBotView.tabCodeReview', + defaultMessage: 'Configure', + }, + tabAnalytics: { + id: 'gooseBotView.tabAnalytics', + defaultMessage: 'Analytics', + }, + tabConnectors: { + id: 'gooseBotView.tabConnectors', + defaultMessage: 'Connectors', + }, + notConnectedBannerTitle: { + id: 'gooseBotView.notConnectedBannerTitle', + defaultMessage: 'Goose Bot is not connected yet', + }, + notConnectedBannerBody: { + id: 'gooseBotView.notConnectedBannerBody', + defaultMessage: + 'Connect the GitHub App in the Connectors tab to start receiving automated PR reviews.', + }, + notConnectedBannerCta: { + id: 'gooseBotView.notConnectedBannerCta', + defaultMessage: 'Go to Connectors', + }, + experimentalBannerTitle: { + id: 'gooseBotView.experimentalBannerTitle', + defaultMessage: 'Experimental feature', + }, + experimentalBannerBody: { + id: 'gooseBotView.experimentalBannerBody', + defaultMessage: + "Goose Bot is in early access - we're gathering feedback. Share bug reports and ideas on", + }, + experimentalBannerIssues: { + id: 'gooseBotView.experimentalBannerIssues', + defaultMessage: 'GitHub Issues', + }, + experimentalBannerOr: { + id: 'gooseBotView.experimentalBannerOr', + defaultMessage: 'or', + }, + experimentalBannerDiscord: { + id: 'gooseBotView.experimentalBannerDiscord', + defaultMessage: 'Discord', + }, +}); + +export default function GooseBotView() { + const intl = useIntl(); + const [activeTab, setActiveTab] = useState('general'); + const [tunnelInfo, setTunnelInfo] = useState({ + state: 'idle', + url: '', + hostname: '', + secret: '', + }); + const [stored, setStored] = useState(loadStoredInstall); + const { + prefs, + update: updatePrefs, + retry: retryPrefs, + clearInstall: clearGooseBotInstall, + syncState, + } = useGooseBotPrefs(); + + const refreshTunnel = useCallback(async () => { + try { + const { data } = await getTunnelStatus(); + if (data) setTunnelInfo(data); + } catch (err) { + console.error('Failed to read tunnel status:', err); + } + }, []); + + useEffect(() => { + refreshTunnel(); + }, [refreshTunnel]); + + useEffect(() => { + let cancelled = false; + (async () => { + try { + const installationId = await fetchGooseBotInstallId(); + if (cancelled) return; + if (installationId != null) { + const record: StoredInstall = { + installationId, + enabledAt: stored?.enabledAt ?? new Date().toISOString(), + }; + localStorage.setItem(STORAGE_KEY, JSON.stringify(record)); + setStored(record); + } else { + localStorage.removeItem(STORAGE_KEY); + setStored(null); + } + } catch { + // goosed unreachable - keep existing localStorage hint + } + })(); + return () => { + cancelled = true; + }; + // eslint-disable-next-line react-hooks/exhaustive-deps -- sync once on mount + }, []); + + const handleInstallSaved = (record: StoredInstall) => { + localStorage.setItem(STORAGE_KEY, JSON.stringify(record)); + setStored(record); + refreshTunnel(); + }; + + const handleInstallCleared = () => { + localStorage.removeItem(STORAGE_KEY); + clearGooseBotInstall(); + setStored(null); + }; + + const isConnected = stored !== null && tunnelInfo.state === 'running'; + + return ( + +
+
+
+
+

{intl.formatMessage(i18n.pageTitle)}

+ +
+
+
+ +
+
+ +
+ {intl.formatMessage(i18n.experimentalBannerTitle)}:{' '} + {intl.formatMessage(i18n.experimentalBannerBody)}{' '} + {' '} + {intl.formatMessage(i18n.experimentalBannerOr)}{' '} + + . +
+
+ + {!isConnected && activeTab !== 'connectors' && ( + + + +
+

+ {intl.formatMessage(i18n.notConnectedBannerTitle)} +

+

+ {intl.formatMessage(i18n.notConnectedBannerBody)} +

+
+ +
+
+ )} + + +
+ + + + {intl.formatMessage(i18n.tabGeneral)} + + + + {intl.formatMessage(i18n.tabCodeReview)} + + + + {intl.formatMessage(i18n.tabAnalytics)} + + + + {intl.formatMessage(i18n.tabConnectors)} + + +
+ + + + + + + + + + + + + + + + + + +
+
+
+
+ ); +} diff --git a/ui/desktop/src/components/goose_bot/SaveIndicator.tsx b/ui/desktop/src/components/goose_bot/SaveIndicator.tsx new file mode 100644 index 000000000000..8cd88755da7d --- /dev/null +++ b/ui/desktop/src/components/goose_bot/SaveIndicator.tsx @@ -0,0 +1,91 @@ +import { AlertCircle, CheckCircle2, Loader2 } from 'lucide-react'; +import { Button } from '../ui/button'; +import { defineMessages, useIntl } from '../../i18n'; +import type { SyncState } from './useGooseBotPrefs'; + +const i18n = defineMessages({ + loading: { + id: 'gooseBotSaveIndicator.loading', + defaultMessage: 'Loading...', + }, + syncing: { + id: 'gooseBotSaveIndicator.syncing', + defaultMessage: 'Saving...', + }, + saved: { + id: 'gooseBotSaveIndicator.saved', + defaultMessage: 'Saved', + }, + savedPending: { + id: 'gooseBotSaveIndicator.savedPending', + defaultMessage: 'Saved locally - webhook sync pending', + }, + failed: { + id: 'gooseBotSaveIndicator.failed', + defaultMessage: "Couldn't save", + }, + retry: { + id: 'gooseBotSaveIndicator.retry', + defaultMessage: 'Retry', + }, +}); + +export function SaveIndicator({ + syncState, + onRetry, +}: { + syncState: SyncState; + onRetry: () => void; +}) { + const intl = useIntl(); + + if (syncState.kind === 'idle') return null; + + if (syncState.kind === 'loading') { + return ( + + + {intl.formatMessage(i18n.loading)} + + ); + } + + if (syncState.kind === 'syncing') { + return ( + + + {intl.formatMessage(i18n.syncing)} + + ); + } + + if (syncState.kind === 'synced') { + if (syncState.switchboardSynced) { + return ( + + + {intl.formatMessage(i18n.saved)} + + ); + } + return ( + + + {intl.formatMessage(i18n.savedPending)} + + + ); + } + + return ( + + + {intl.formatMessage(i18n.failed)}: {syncState.error} + + + ); +} diff --git a/ui/desktop/src/components/goose_bot/sections/GooseBotAnalytics.tsx b/ui/desktop/src/components/goose_bot/sections/GooseBotAnalytics.tsx new file mode 100644 index 000000000000..a3e5fd537eed --- /dev/null +++ b/ui/desktop/src/components/goose_bot/sections/GooseBotAnalytics.tsx @@ -0,0 +1,96 @@ +import { AlertCircle, Loader2, RefreshCw } from 'lucide-react'; +import { Card, CardContent } from '../../ui/card'; +import { Button } from '../../ui/button'; +import { useGooseBotAnalytics } from '../useGooseBotAnalytics'; +import { defineMessages, useIntl } from '../../../i18n'; + +interface Props { + enabled: boolean; +} + +const i18n = defineMessages({ + prsReviewed: { + id: 'gooseBotAnalytics.prsReviewed', + defaultMessage: 'PRs reviewed', + }, + issuesHandled: { + id: 'gooseBotAnalytics.issuesHandled', + defaultMessage: 'Issues handled', + }, + commitsPushed: { + id: 'gooseBotAnalytics.commitsPushed', + defaultMessage: 'Commits pushed', + }, + loadFailed: { + id: 'gooseBotAnalytics.loadFailed', + defaultMessage: 'Could not load analytics', + }, + retry: { + id: 'gooseBotAnalytics.retry', + defaultMessage: 'Retry', + }, +}); + +export default function GooseBotAnalyticsSection({ enabled }: Props) { + const intl = useIntl(); + const { state, refresh } = useGooseBotAnalytics(enabled); + + if (state.kind === 'idle' || state.kind === 'loading') { + return ( +
+
+ + Loading... +
+
+ ); + } + + if (state.kind === 'error') { + return ( +
+
+ + + {intl.formatMessage(i18n.loadFailed)}: {state.error} + + +
+
+ ); + } + + const data = state.data; + return ( +
+
+ + + +
+
+ ); +} + +function StatCard({ label, value }: { label: string; value: string }) { + return ( + + +

{label}

+

{value}

+
+
+ ); +} diff --git a/ui/desktop/src/components/goose_bot/sections/GooseBotCodeReview.tsx b/ui/desktop/src/components/goose_bot/sections/GooseBotCodeReview.tsx new file mode 100644 index 000000000000..fa579fb4e8c4 --- /dev/null +++ b/ui/desktop/src/components/goose_bot/sections/GooseBotCodeReview.tsx @@ -0,0 +1,726 @@ +import { useMemo, useState } from 'react'; +import { + AlertCircle, + ChevronDown, + ExternalLink, + Lightbulb, + Loader2, + Lock, + RefreshCw, + Search, +} from 'lucide-react'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../../ui/card'; +import { Switch } from '../../ui/switch'; +import { Input } from '../../ui/input'; +import { Button } from '../../ui/button'; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuRadioGroup, + DropdownMenuRadioItem, + DropdownMenuTrigger, +} from '../../ui/dropdown-menu'; +import type { + GooseBotPrefs, + GooseBotRepo, + ReviewModelChoice, + ReviewOutputStyle, + ReviewSeverity, + TriggerPermission, + TriggerPreference, +} from '../../../api/types.gen'; +import { defineMessages, useIntl } from '../../../i18n'; +import { useGooseBotRepos } from '../useGooseBotRepos'; +import { RecipeModelSelector } from '../../recipes/shared/RecipeModelSelector'; + +const i18n = defineMessages({ + setupBlurb: { + id: 'gooseBotCodeReview.setupBlurb', + defaultMessage: + 'When code review is on, Goose Bot automatically reviews pull requests and leaves inline suggestions. Mention @aaif-goose-bot in any PR comment to ask a question, request a manual review, or apply fixes.', + }, + reviewTitle: { + id: 'gooseBotCodeReview.reviewTitle', + defaultMessage: 'Code review', + }, + reviewDescription: { + id: 'gooseBotCodeReview.reviewDescription', + defaultMessage: 'Configure when and how Goose Bot reviews pull requests.', + }, + autoReviewLabel: { + id: 'gooseBotCodeReview.autoReviewLabel', + defaultMessage: 'Personal auto review preferences', + }, + autoReviewHelper: { + id: 'gooseBotCodeReview.autoReviewHelper', + defaultMessage: + 'All your pull requests in a Goose Bot-enabled repository will be automatically reviewed.', + }, + triggerLabel: { + id: 'gooseBotCodeReview.triggerLabel', + defaultMessage: 'Personal review trigger preference', + }, + triggerHelper: { + id: 'gooseBotCodeReview.triggerHelper', + defaultMessage: 'Choose when Goose Bot should automatically review your pull requests.', + }, + outputStyleLabel: { + id: 'gooseBotCodeReview.outputStyleLabel', + defaultMessage: 'Review output style', + }, + outputStyleHelper: { + id: 'gooseBotCodeReview.outputStyleHelper', + defaultMessage: 'How findings are posted back to the pull request.', + }, + severityLabel: { + id: 'gooseBotCodeReview.severityLabel', + defaultMessage: 'Minimum severity to surface', + }, + severityHelper: { + id: 'gooseBotCodeReview.severityHelper', + defaultMessage: + 'Findings below this rank are dropped from the review. Higher = quieter.', + }, + reviewModelLabel: { + id: 'gooseBotCodeReview.reviewModelLabel', + defaultMessage: 'Review model', + }, + reviewModelHelper: { + id: 'gooseBotCodeReview.reviewModelHelper', + defaultMessage: + 'Which model the review orchestrator uses. Defaults to the model goose is configured with.', + }, + permissionsTitle: { + id: 'gooseBotCodeReview.permissionsTitle', + defaultMessage: 'Permissions', + }, + permissionsDescription: { + id: 'gooseBotCodeReview.permissionsDescription', + defaultMessage: 'Control who can interact with @aaif-goose-bot and what it is allowed to do.', + }, + triggerPermissionLabel: { + id: 'gooseBotCodeReview.triggerPermissionLabel', + defaultMessage: 'Who can trigger Goose Bot', + }, + triggerPermissionHelper: { + id: 'gooseBotCodeReview.triggerPermissionHelper', + defaultMessage: + 'Restrict who can @mention the bot to request reviews, fixes, or replies.', + }, + allowCommitLabel: { + id: 'gooseBotCodeReview.allowCommitLabel', + defaultMessage: 'Allow pushing commits to PR branches', + }, + allowCommitHelper: { + id: 'gooseBotCodeReview.allowCommitHelper', + defaultMessage: + 'When someone asks @aaif-goose-bot to fix issues, push the resulting changes to the PR branch as aaif-goose-bot[bot].', + }, + allowIssuesLabel: { + id: 'gooseBotCodeReview.allowIssuesLabel', + defaultMessage: 'Respond to mentions on issues', + }, + allowIssuesHelper: { + id: 'gooseBotCodeReview.allowIssuesHelper', + defaultMessage: + 'Let @aaif-goose-bot answer questions and draft PRs from issue comments, not just from inside pull requests.', + }, + allowNewPrsLabel: { + id: 'gooseBotCodeReview.allowNewPrsLabel', + defaultMessage: 'Open new pull requests for issue fixes', + }, + allowNewPrsHelper: { + id: 'gooseBotCodeReview.allowNewPrsHelper', + defaultMessage: + 'When someone @-mentions the bot on a plain issue and asks for a fix, push the changes on a fresh branch and open a PR linked back to the issue.', + }, + allowlistLabel: { + id: 'gooseBotCodeReview.allowlistLabel', + defaultMessage: 'Allowlist', + }, + allowlistHelper: { + id: 'gooseBotCodeReview.allowlistHelper', + defaultMessage: + 'One GitHub username per line. Only listed users can mention the bot.', + }, + allowlistPlaceholder: { + id: 'gooseBotCodeReview.allowlistPlaceholder', + defaultMessage: 'octocat', + }, + repoPrefsTitle: { + id: 'gooseBotCodeReview.repoPrefsTitle', + defaultMessage: 'Repository preferences', + }, + repoSearchPlaceholder: { + id: 'gooseBotCodeReview.repoSearchPlaceholder', + defaultMessage: 'Search repos or enter a GitHub org/repo', + }, + hideArchived: { + id: 'gooseBotCodeReview.hideArchived', + defaultMessage: 'Hide archived repositories', + }, + repoEmptyConnected: { + id: 'gooseBotCodeReview.repoEmptyConnected', + defaultMessage: + 'Per-repo overrides are coming soon - the bot uses your personal defaults for every connected repo for now.', + }, + repoLoading: { + id: 'gooseBotCodeReview.repoLoading', + defaultMessage: 'Loading repositories...', + }, + repoError: { + id: 'gooseBotCodeReview.repoError', + defaultMessage: 'Could not load repositories', + }, + repoRetry: { + id: 'gooseBotCodeReview.repoRetry', + defaultMessage: 'Retry', + }, + repoCount: { + id: 'gooseBotCodeReview.repoCount', + defaultMessage: '{shown, plural, one {# repository} other {# repositories}} accessible', + }, + repoTruncated: { + id: 'gooseBotCodeReview.repoTruncated', + defaultMessage: 'Showing first {shown} of {total} - others omitted.', + }, + repoNoMatch: { + id: 'gooseBotCodeReview.repoNoMatch', + defaultMessage: 'No repositories match your search.', + }, + repoColRepo: { + id: 'gooseBotCodeReview.repoColRepo', + defaultMessage: 'Repository', + }, + repoColVisibility: { + id: 'gooseBotCodeReview.repoColVisibility', + defaultMessage: 'Visibility', + }, + repoColBranch: { + id: 'gooseBotCodeReview.repoColBranch', + defaultMessage: 'Default branch', + }, +}); + +interface RichOption { + value: T; + label: string; + description: string; +} + +interface Props { + prefs: GooseBotPrefs | null; + onUpdate: (patch: Partial) => void; +} + +export default function GooseBotCodeReview({ prefs, onUpdate }: Props) { + const intl = useIntl(); + const [repoQuery, setRepoQuery] = useState(''); + const [hideArchivedRepos, setHideArchivedRepos] = useState(true); + const { state: reposState, refresh: refreshRepos } = useGooseBotRepos(prefs !== null); + + const triggerOptions = useMemo[]>( + () => [ + { + value: 'pr-open', + label: 'On PR open', + description: 'Review when a pull request is opened.', + }, + { + value: 'on-every-push', + label: 'On every push', + description: 'Review again whenever new commits are pushed to the pull request.', + }, + { + value: 'manual-only', + label: 'Manual only', + description: 'Only review when someone mentions @aaif-goose-bot review.', + }, + ], + [] + ); + + const severityOptions = useMemo[]>( + () => [ + { + value: 'low', + label: 'Low - surface everything', + description: 'Every finding the model produces. Highest signal *and* noise.', + }, + { + value: 'medium', + label: 'Medium (default)', + description: 'Drop low-severity nits; show medium and above.', + }, + { + value: 'high', + label: 'High - only important issues', + description: 'Only high- and critical-severity findings.', + }, + { + value: 'critical', + label: 'Critical - blocking issues only', + description: 'Only the most severe issues that should block the PR.', + }, + ], + [] + ); + + const outputOptions = useMemo[]>( + () => [ + { + value: 'inline', + label: 'Inline suggestions', + description: + 'Post findings as inline review comments with GitHub suggestion blocks where possible.', + }, + { + value: 'summary', + label: 'Summary comment only', + description: + 'Post a single review comment listing all findings - no inline annotations.', + }, + { + value: 'both', + label: 'Inline + summary', + description: + 'Inline annotations on each finding, plus a one-comment summary at the top of the review.', + }, + ], + [] + ); + + const modelOptions = useMemo[]>( + () => [ + { + value: 'default', + label: "Use Goose's default model", + description: 'Whatever model goose is configured with in Settings > Models.', + }, + { + value: 'custom', + label: 'Use a different model for reviews', + description: 'Pick a separate provider + model for code review.', + }, + ], + [] + ); + + const triggerPermissionOptions = useMemo[]>( + () => [ + { + value: 'anyone', + label: 'Anyone', + description: + 'Any GitHub user who can see the PR can mention @aaif-goose-bot. Best for open-source.', + }, + { + value: 'write-access', + label: 'Collaborators with write access', + description: + 'Only repo collaborators with write permission or higher can trigger the bot.', + }, + { + value: 'specific-users', + label: 'Specific users', + description: + 'Only usernames listed below can mention the bot. Add one GitHub login per line in the allowlist field.', + }, + ], + [] + ); + + const disabled = prefs === null; + + return ( +
+ + + {intl.formatMessage(i18n.reviewTitle)} + {intl.formatMessage(i18n.reviewDescription)} + + +
+ +

+ {intl.formatMessage(i18n.setupBlurb)} +

+
+ + onUpdate({ auto_review_on_pr_open: checked })} + variant="mono" + /> + } + /> + + onUpdate({ trigger_preference: v })} + /> + } + /> + + onUpdate({ review_output_style: v })} + /> + } + /> + + onUpdate({ review_severity: v })} + /> + } + /> + + onUpdate({ review_model_choice: v })} + /> + } + /> + {prefs?.review_model_choice === 'custom' && ( +
+ + onUpdate({ review_provider: provider ?? undefined }) + } + onModelChange={(model) => onUpdate({ review_model: model ?? undefined })} + /> +
+ )} +
+
+ + + + {intl.formatMessage(i18n.permissionsTitle)} + {intl.formatMessage(i18n.permissionsDescription)} + + + onUpdate({ trigger_permission: v })} + /> + } + /> + + {prefs?.trigger_permission === 'specific-users' && ( +
+

+ {intl.formatMessage(i18n.allowlistLabel)} +

+

+ {intl.formatMessage(i18n.allowlistHelper)} +

+