From 2ba21dc608ea1085a9e0ce96417238f657857536 Mon Sep 17 00:00:00 2001 From: Abhijay Jain Date: Wed, 13 May 2026 01:54:06 +0530 Subject: [PATCH 01/25] =?UTF-8?q?wip:=20goose=20copilot=20=E2=80=94=20PR?= =?UTF-8?q?=20review=20bot=20via=20GitHub=20App=20webhooks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Abhijay Jain --- .gitignore | 3 + crates/goose-server/src/openapi.rs | 5 + crates/goose-server/src/routes/copilot.rs | 380 ++++ crates/goose-server/src/routes/mod.rs | 2 + crates/goose/src/config/mod.rs | 1 + crates/goose/src/config/signup_copilot/mod.rs | 96 + .../goose/src/config/signup_copilot/server.rs | 130 ++ .../signup_copilot/templates/error.html | 19 + .../signup_copilot/templates/success.html | 17 + services/copilot-switchboard/.gitignore | 7 + services/copilot-switchboard/README.md | 120 + services/copilot-switchboard/package.json | 20 + services/copilot-switchboard/pnpm-lock.yaml | 2015 +++++++++++++++++ services/copilot-switchboard/src/index.ts | 105 + .../copilot-switchboard/src/lib/github.ts | 173 ++ .../copilot-switchboard/src/lib/handlers.ts | 218 ++ services/copilot-switchboard/src/lib/oauth.ts | 75 + .../copilot-switchboard/src/lib/registry.ts | 26 + .../copilot-switchboard/src/lib/tunnel.ts | 55 + services/copilot-switchboard/src/lib/types.ts | 61 + services/copilot-switchboard/tsconfig.json | 22 + .../copilot-switchboard/wrangler.toml.example | 21 + ui/desktop/.env.example | 13 + ui/desktop/openapi.json | 123 + ui/desktop/src/App.tsx | 21 +- ui/desktop/src/api/types.gen.ts | 77 + .../src/components/copilot/CopilotView.tsx | 288 +++ ui/desktop/src/hooks/useNavigationItems.ts | 6 + ui/desktop/src/i18n/messages/en.json | 60 + 29 files changed, 4154 insertions(+), 5 deletions(-) create mode 100644 crates/goose-server/src/routes/copilot.rs create mode 100644 crates/goose/src/config/signup_copilot/mod.rs create mode 100644 crates/goose/src/config/signup_copilot/server.rs create mode 100644 crates/goose/src/config/signup_copilot/templates/error.html create mode 100644 crates/goose/src/config/signup_copilot/templates/success.html create mode 100644 services/copilot-switchboard/.gitignore create mode 100644 services/copilot-switchboard/README.md create mode 100644 services/copilot-switchboard/package.json create mode 100644 services/copilot-switchboard/pnpm-lock.yaml create mode 100644 services/copilot-switchboard/src/index.ts create mode 100644 services/copilot-switchboard/src/lib/github.ts create mode 100644 services/copilot-switchboard/src/lib/handlers.ts create mode 100644 services/copilot-switchboard/src/lib/oauth.ts create mode 100644 services/copilot-switchboard/src/lib/registry.ts create mode 100644 services/copilot-switchboard/src/lib/tunnel.ts create mode 100644 services/copilot-switchboard/src/lib/types.ts create mode 100644 services/copilot-switchboard/tsconfig.json create mode 100644 services/copilot-switchboard/wrangler.toml.example create mode 100644 ui/desktop/.env.example create mode 100644 ui/desktop/src/components/copilot/CopilotView.tsx 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-server/src/openapi.rs b/crates/goose-server/src/openapi.rs index f2b4d832afc6..f13e3384db7b 100644 --- a/crates/goose-server/src/openapi.rs +++ b/crates/goose-server/src/openapi.rs @@ -479,6 +479,8 @@ derive_utoipa!(IconTheme as IconThemeSchema); super::routes::tunnel::start_tunnel, super::routes::tunnel::stop_tunnel, super::routes::tunnel::get_tunnel_status, + super::routes::copilot::review, + super::routes::copilot::setup, super::routes::telemetry::send_telemetry_event, super::routes::dictation::transcribe_dictation, super::routes::dictation::get_dictation_config, @@ -658,6 +660,9 @@ derive_utoipa!(IconTheme as IconThemeSchema); super::routes::setup::SetupResponse, super::tunnel::TunnelInfo, super::tunnel::TunnelState, + super::routes::copilot::CopilotReviewRequest, + super::routes::copilot::CopilotReviewResponse, + super::routes::copilot::CopilotSetupResponse, super::routes::telemetry::TelemetryEventRequest, goose::goose_apps::GooseApp, goose::goose_apps::WindowProps, diff --git a/crates/goose-server/src/routes/copilot.rs b/crates/goose-server/src/routes/copilot.rs new file mode 100644 index 000000000000..caf45ac84867 --- /dev/null +++ b/crates/goose-server/src/routes/copilot.rs @@ -0,0 +1,380 @@ +//! Renders the `goose-copilot-review` recipe with per-PR params and spawns +//! an agent session in the background. Returns the session id immediately. + +use std::collections::HashMap; +use std::env; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use anyhow::Result; +use axum::{extract::State, response::Json, routing::post, Router}; +use goose::agents::{Agent, SessionConfig}; +use goose::config::paths::Paths; +use goose::config::signup_copilot::CopilotInstallFlow; +use goose::config::{resolve_extensions_for_new_session, Config}; +use goose::conversation::message::Message; +use goose::providers::create; +use goose::recipe::template_recipe::render_recipe_content_with_params; +use goose::recipe::Recipe; +use goose::session::session_manager::SessionType; +use serde::{Deserialize, Serialize}; +use tokio_util::sync::CancellationToken; +use utoipa::ToSchema; + +use crate::routes::errors::ErrorResponse; +use crate::state::AppState; + +const DEFAULT_RECIPE_FILENAME: &str = "goose-copilot-review.yaml"; +const RECIPE_PATH_ENV: &str = "GOOSE_COPILOT_RECIPE_PATH"; +const SWITCHBOARD_URL: &str = "https://goose-copilot-switchboard.example.workers.dev"; +const SWITCHBOARD_URL_ENV: &str = "GOOSE_COPILOT_SWITCHBOARD_URL"; + +#[derive(Debug, Deserialize, ToSchema)] +pub struct CopilotReviewRequest { + pub github_token: String, + /// `owner/repo` form, e.g. `block/goose`. + pub repo: String, + pub pr_number: u64, + pub head_sha: String, + pub pr_url: String, + /// The recipe updates this Check Run on completion. + #[serde(default)] + pub check_run_id: Option, +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct CopilotReviewResponse { + pub session_id: String, +} + +#[utoipa::path( + post, + path = "/copilot/review", + request_body = CopilotReviewRequest, + responses( + (status = 200, description = "Review session spawned", body = CopilotReviewResponse), + (status = 400, description = "Recipe missing or invalid"), + (status = 500, description = "Internal error"), + ), + tag = "copilot" +)] +#[axum::debug_handler] +async fn review( + State(_state): State>, + Json(req): Json, +) -> Result, ErrorResponse> { + let recipe_path = locate_recipe()?; + let raw = tokio::fs::read_to_string(&recipe_path).await.map_err(|e| { + ErrorResponse::bad_request(format!( + "Recipe not found at {}: {e}. Set {RECIPE_PATH_ENV} or place the recipe at the default path.", + recipe_path.display(), + )) + })?; + + let params = build_params(&req, &recipe_path); + let rendered = render_recipe_content_with_params(&raw, ¶ms)?; + let recipe: Recipe = serde_yaml::from_str(&rendered)?; + + let prompt_text = recipe_prompt(&recipe)?; + let session_id = spawn_review(recipe, prompt_text, req).await?; + + Ok(Json(CopilotReviewResponse { session_id })) +} + +fn locate_recipe() -> Result { + if let Ok(custom) = env::var(RECIPE_PATH_ENV) { + let p = PathBuf::from(custom); + if p.exists() { + return Ok(p); + } + return Err(ErrorResponse::bad_request(format!( + "{RECIPE_PATH_ENV} points to {} which does not exist", + p.display() + ))); + } + Ok(Paths::config_dir() + .join("recipes") + .join(DEFAULT_RECIPE_FILENAME)) +} + +fn build_params(req: &CopilotReviewRequest, recipe_path: &Path) -> HashMap { + let mut params = HashMap::new(); + params.insert("github_token".to_string(), req.github_token.clone()); + params.insert("repo".to_string(), req.repo.clone()); + params.insert("pr_number".to_string(), req.pr_number.to_string()); + params.insert("head_sha".to_string(), req.head_sha.clone()); + params.insert("pr_url".to_string(), req.pr_url.clone()); + params.insert( + "check_run_id".to_string(), + req.check_run_id.map(|n| n.to_string()).unwrap_or_default(), + ); + if let Some(parent) = recipe_path.parent() { + params.insert( + "recipe_dir".to_string(), + parent.to_string_lossy().into_owned(), + ); + } + params +} + +fn recipe_prompt(recipe: &Recipe) -> Result { + recipe + .prompt + .as_deref() + .filter(|s| !s.trim().is_empty()) + .or_else(|| { + recipe + .instructions + .as_deref() + .filter(|s| !s.trim().is_empty()) + }) + .map(|s| s.to_string()) + .ok_or_else(|| { + ErrorResponse::bad_request( + "Recipe must define either `prompt` or `instructions`".to_string(), + ) + }) +} + +async fn spawn_review( + recipe: Recipe, + prompt_text: String, + req: CopilotReviewRequest, +) -> Result { + let agent = Agent::new(); + + let config = Config::global(); + let provider_name = config.get_goose_provider()?; + let model_name = config.get_goose_model()?; + let model_config = + goose::model::ModelConfig::new(&model_name)?.with_canonical_limits(&provider_name); + + let session = agent + .config + .session_manager + .create_session( + std::env::current_dir()?, + format!("Copilot review {} #{}", req.repo, req.pr_number), + SessionType::Scheduled, + agent.config.goose_mode, + ) + .await?; + + let extensions = resolve_extensions_for_new_session(recipe.extensions.as_deref(), None); + for ext in &extensions { + agent.add_extension(ext.clone(), &session.id).await?; + } + + let agent_provider = create(&provider_name, model_config, extensions).await?; + agent.update_provider(agent_provider, &session.id).await?; + + let session_id = session.id.clone(); + + tokio::spawn(async move { + let user_message = Message::user().with_text(&prompt_text); + + let session_config = SessionConfig { + id: session_id.clone(), + schedule_id: None, + max_turns: None, + retry_config: None, + }; + + let cancel_token = CancellationToken::new(); + match agent + .reply(user_message, session_config, Some(cancel_token)) + .await + { + Ok(stream) => { + use futures::StreamExt; + let mut stream = std::pin::pin!(stream); + while stream.next().await.is_some() {} + } + Err(e) => { + tracing::error!("[copilot] review session {} failed: {}", session_id, e); + } + } + + if let Err(e) = agent + .config + .session_manager + .update(&session_id) + .recipe(Some(recipe)) + .apply() + .await + { + tracing::warn!("[copilot] failed to persist recipe on session: {}", e); + } + }); + + Ok(session.id) +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct CopilotSetupResponse { + pub installation_id: u64, +} + +#[utoipa::path( + post, + path = "/copilot/setup", + responses( + (status = 200, description = "Goose Copilot connected", body = CopilotSetupResponse), + (status = 408, description = "Install timed out"), + (status = 500, description = "Internal error"), + ), + tag = "copilot" +)] +#[axum::debug_handler] +async fn setup( + State(state): State>, +) -> Result, ErrorResponse> { + let mut flow = CopilotInstallFlow::new(); + 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 switchboard = switchboard_url(); + let body = serde_json::json!({ + "installation_id": callback.installation_id, + "oauth_code": callback.oauth_code, + "agent_id": agent_id, + "tunnel_secret": tunnel_info.secret, + "tunnel_url": tunnel_info.url, + }); + let client = reqwest::Client::new(); + let res = client + .post(format!("{}/copilot/register", switchboard)) + .json(&body) + .send() + .await + .map_err(|e| ErrorResponse::internal(format!("switchboard unreachable: {e}")))?; + if !res.status().is_success() { + let status = res.status(); + let detail = res.text().await.unwrap_or_default(); + return Err(ErrorResponse::internal(format!( + "switchboard rejected registration: {status} {detail}" + ))); + } + + Ok(Json(CopilotSetupResponse { + installation_id: callback.installation_id, + })) +} + +fn switchboard_url() -> String { + env::var(SWITCHBOARD_URL_ENV).unwrap_or_else(|_| SWITCHBOARD_URL.to_string()) +} + +fn extract_agent_id(tunnel_url: &str) -> Option { + tunnel_url + .rsplit_once("/tunnel/") + .map(|(_, rest)| rest.split(['/', '?', '#']).next().unwrap_or("").to_string()) +} + +pub fn routes(state: Arc) -> Router { + Router::new() + .route("/copilot/review", post(review)) + .route("/copilot/setup", post(setup)) + .with_state(state) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample_req() -> CopilotReviewRequest { + CopilotReviewRequest { + github_token: "ghs_test".to_string(), + repo: "block/goose".to_string(), + pr_number: 42, + head_sha: "abc123".to_string(), + pr_url: "https://github.com/block/goose/pull/42".to_string(), + check_run_id: Some(99), + } + } + + #[test] + fn build_params_maps_required_fields() { + let path = PathBuf::from("/tmp/recipes/r.yaml"); + let params = build_params(&sample_req(), &path); + + assert_eq!(params.get("github_token").unwrap(), "ghs_test"); + assert_eq!(params.get("repo").unwrap(), "block/goose"); + assert_eq!(params.get("pr_number").unwrap(), "42"); + assert_eq!(params.get("head_sha").unwrap(), "abc123"); + assert_eq!( + params.get("pr_url").unwrap(), + "https://github.com/block/goose/pull/42" + ); + assert_eq!(params.get("check_run_id").unwrap(), "99"); + assert_eq!(params.get("recipe_dir").unwrap(), "/tmp/recipes"); + } + + #[test] + fn build_params_handles_missing_check_run_id() { + let mut req = sample_req(); + req.check_run_id = None; + let params = build_params(&req, Path::new("/tmp/r.yaml")); + assert_eq!(params.get("check_run_id").unwrap(), ""); + } + + #[test] + fn recipe_prompt_prefers_prompt_over_instructions() { + let recipe: Recipe = serde_yaml::from_str( + "version: '1.0.0'\ntitle: t\ndescription: d\nprompt: from prompt\ninstructions: from instructions\n", + ) + .unwrap(); + assert_eq!(recipe_prompt(&recipe).unwrap(), "from prompt"); + } + + #[test] + fn recipe_prompt_falls_back_to_instructions() { + let recipe: Recipe = serde_yaml::from_str( + "version: '1.0.0'\ntitle: t\ndescription: d\ninstructions: from instructions\n", + ) + .unwrap(); + assert_eq!(recipe_prompt(&recipe).unwrap(), "from instructions"); + } + + #[test] + fn recipe_prompt_rejects_when_both_missing() { + let recipe: Recipe = + serde_yaml::from_str("version: '1.0.0'\ntitle: t\ndescription: d\n").unwrap(); + assert!(recipe_prompt(&recipe).is_err()); + } + + #[test] + fn locate_recipe_uses_env_override_when_present() { + let tmp = std::env::temp_dir().join("goose-copilot-locate-test.yaml"); + std::fs::write(&tmp, "stub").unwrap(); + std::env::set_var(RECIPE_PATH_ENV, &tmp); + + let located = locate_recipe().unwrap(); + assert_eq!(located, tmp); + + std::env::remove_var(RECIPE_PATH_ENV); + std::fs::remove_file(&tmp).ok(); + } + + #[test] + fn locate_recipe_errors_when_env_path_missing() { + std::env::set_var(RECIPE_PATH_ENV, "/nonexistent/path/recipe.yaml"); + let result = locate_recipe(); + std::env::remove_var(RECIPE_PATH_ENV); + assert!(result.is_err()); + } +} diff --git a/crates/goose-server/src/routes/mod.rs b/crates/goose-server/src/routes/mod.rs index 00777d80acc4..23bc85a87af2 100644 --- a/crates/goose-server/src/routes/mod.rs +++ b/crates/goose-server/src/routes/mod.rs @@ -1,6 +1,7 @@ pub mod action_required; pub mod agent; pub mod config_management; +pub mod copilot; pub mod dictation; pub mod errors; pub mod features; @@ -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(copilot::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/src/config/mod.rs b/crates/goose/src/config/mod.rs index 402c835f8783..cf14c142150a 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_copilot; pub mod signup_nanogpt; pub mod signup_openrouter; pub mod signup_tetrate; diff --git a/crates/goose/src/config/signup_copilot/mod.rs b/crates/goose/src/config/signup_copilot/mod.rs new file mode 100644 index 000000000000..41c477fd45e7 --- /dev/null +++ b/crates/goose/src/config/signup_copilot/mod.rs @@ -0,0 +1,96 @@ +pub mod server; + +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 = "goose-copilot"; +const CALLBACK_PORT: u16 = 3458; +const INSTALL_TIMEOUT: Duration = Duration::from_secs(600); + +#[derive(Debug, Deserialize)] +pub struct InstallCallback { + pub installation_id: u64, + pub oauth_code: String, +} + +pub struct CopilotInstallFlow { + state: String, + server_shutdown_tx: Option>, +} + +impl CopilotInstallFlow { + 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, + } + } + + pub fn install_url(&self) -> String { + format!( + "https://github.com/apps/{}/installations/new?state={}", + APP_SLUG, self.state + ) + } + + pub fn callback_url() -> String { + format!("http://localhost:{}/", CALLBACK_PORT) + } + + pub async fn complete_flow(&mut self) -> Result { + let url = self.install_url(); + tracing::info!("[copilot-install] opening browser to {}", url); + if let Err(e) = webbrowser::open(&url) { + tracing::warn!("[copilot-install] failed to open browser: {}", e); + } + self.await_callback().await + } + + pub async fn await_callback(&mut self) -> Result { + let (cb_tx, cb_rx) = oneshot::channel::(); + let (shutdown_tx, shutdown_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, expected_state, CALLBACK_PORT).await + { + tracing::error!("[copilot-install] callback server error: {}", e); + } + }); + + match timeout(INSTALL_TIMEOUT, cb_rx).await { + Ok(Ok(cb)) => Ok(cb), + 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 CopilotInstallFlow { + fn default() -> Self { + Self::new() + } +} + +impl Drop for CopilotInstallFlow { + fn drop(&mut self) { + self.shutdown(); + } +} diff --git a/crates/goose/src/config/signup_copilot/server.rs b/crates/goose/src/config/signup_copilot/server.rs new file mode 100644 index 000000000000..443974afbd5e --- /dev/null +++ b/crates/goose/src/config/signup_copilot/server.rs @@ -0,0 +1,130 @@ +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; + +static TEMPLATES_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/src/config/signup_copilot/templates"); + +#[derive(Debug, Deserialize)] +struct CallbackQuery { + installation_id: Option, + code: Option, + state: Option, + setup_action: 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<()>, + 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?; + + 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 { + return render( + &TEMPLATES_DIR, + "error.html", + StatusCode::BAD_REQUEST, + &error, + ); + } + + let installation_id = match params.installation_id.and_then(|s| s.parse::().ok()) { + Some(id) => id, + None => { + return render( + &TEMPLATES_DIR, + "error.html", + StatusCode::BAD_REQUEST, + "missing installation_id", + ) + } + }; + let code = match params.code { + Some(c) => c, + None => { + return render( + &TEMPLATES_DIR, + "error.html", + StatusCode::BAD_REQUEST, + "missing oauth code", + ) + } + }; + let state = params.state.unwrap_or_default(); + if state != inner.expected_state { + return render( + &TEMPLATES_DIR, + "error.html", + StatusCode::BAD_REQUEST, + "state mismatch", + ); + } + if params.setup_action.as_deref() != Some("install") { + return render( + &TEMPLATES_DIR, + "error.html", + StatusCode::BAD_REQUEST, + "unexpected setup_action", + ); + } + + let mut tx_guard = inner.tx.lock().await; + if let Some(tx) = tx_guard.take() { + let _ = tx.send(InstallCallback { + installation_id, + oauth_code: code, + }); + } + + render(&TEMPLATES_DIR, "success.html", StatusCode::OK, "") +} + +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 Copilot

{}

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

Could not connect Goose Copilot

+

{{ message }}

+

Return to Goose Desktop and try again.

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

✅ Goose Copilot connected

+

You can close this tab and return to Goose Desktop.

+ + diff --git a/services/copilot-switchboard/.gitignore b/services/copilot-switchboard/.gitignore new file mode 100644 index 000000000000..666258c9a5ed --- /dev/null +++ b/services/copilot-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/copilot-switchboard/README.md b/services/copilot-switchboard/README.md new file mode 100644 index 000000000000..eb2239293e67 --- /dev/null +++ b/services/copilot-switchboard/README.md @@ -0,0 +1,120 @@ +# Goose Copilot — Switchboard + +A small Cloudflare Worker that bridges GitHub webhooks → the user's local +`goosed` instance via the existing lapstone tunnel. + +The switchboard is the **only** Block-hosted component of Goose Copilot. +It deliberately holds no API keys and never sees user code. + +## Architecture + +``` +github.com ──webhook──▶ [switchboard Worker] + │ verify HMAC + │ mint App installation token + │ look up installation_id → tunnel routing + ▼ + [lapstone tunnel proxy] ──WS──▶ user's local goosed + │ goose run + │ --recipe goose-copilot-review + │ --params pr=... + ▼ + inline review on PR +``` + +What the switchboard sees: +- Webhook payloads (HMAC-validated) +- Opaque routing data: `installation_id → {agent_id, tunnel_secret, tunnel_url}` + +What the switchboard does **not** see: +- User model API keys (live in the user's keyring) +- User source code (the diff is fetched by the user's local goosed) +- Review content (generated locally, posted to GitHub from the user's machine) + +## GitHub App configuration + +Permissions: +- Contents: Read +- Pull requests: Read & write +- Issues: Read & write (for the `@goose-copilot review` mention) +- Checks: Read & write +- Metadata: Read + +Webhook subscriptions: +- `installation` +- `pull_request` +- `issue_comment` + +Webhook URL: `https://.workers.dev/webhook` +Webhook secret: same string set as `GITHUB_WEBHOOK_SECRET`. + +## Local development + +```bash +pnpm install +pnpm dev # wrangler dev, hot reload +pnpm test # vitest +pnpm typecheck # tsc --noEmit +``` + +## Deploy + +1. **Create the KV namespace.** + ```bash + wrangler kv namespace create INSTALL_REGISTRY + ``` + Paste the returned id into `wrangler.toml` (`kv_namespaces[0].id`). + +2. **Set secrets.** + ```bash + wrangler secret put GITHUB_APP_ID + wrangler secret put GITHUB_APP_PRIVATE_KEY # paste the full PEM + wrangler secret put GITHUB_WEBHOOK_SECRET + wrangler secret put REGISTER_SHARED_SECRET # any high-entropy string + ``` + +3. **Deploy.** + ```bash + pnpm deploy + ``` + +4. **Set the webhook URL** in the GitHub App settings to + `https://.workers.dev/webhook`. + +5. **Wire Desktop** to the same `REGISTER_SHARED_SECRET` and Worker base URL + so the Copilot tab can POST `/register`. + +## Endpoints + +### `POST /webhook` +HMAC-validated GitHub webhook. Returns 200 immediately and processes events +in the background. + +### `POST /register` +Called by Goose Desktop when the user enables Copilot reviews. + +```http +POST /register +Authorization: Bearer +Content-Type: application/json + +{ + "installationId": 12345678, + "agentId": "0123abcd...", + "tunnelSecret": "abcdef0123...", + "tunnelUrl": "https://tunnel-proxy.example/tunnel/0123abcd..." +} +``` + +Stores the routing record in KV. The Worker uses it on the next webhook +to dispatch the review to the user's tunnel. + +### `DELETE /register` +Same auth, body `{ "installationId": 12345678 }`. Removes the KV record so +future PRs no longer attempt to reach the user's goosed. + +## Transferring out of this monorepo + +Everything in `services/copilot-switchboard/` is self-contained: zero +imports from `crates/` or `ui/`. Move the directory to its own repo and +nothing inside needs editing. diff --git a/services/copilot-switchboard/package.json b/services/copilot-switchboard/package.json new file mode 100644 index 000000000000..0e83f75e500f --- /dev/null +++ b/services/copilot-switchboard/package.json @@ -0,0 +1,20 @@ +{ + "name": "goose-copilot-switchboard", + "version": "0.1.0", + "private": true, + "description": "Webhook switchboard for the Goose Copilot 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/copilot-switchboard/pnpm-lock.yaml b/services/copilot-switchboard/pnpm-lock.yaml new file mode 100644 index 000000000000..cf28d3995e9d --- /dev/null +++ b/services/copilot-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/copilot-switchboard/src/index.ts b/services/copilot-switchboard/src/index.ts new file mode 100644 index 000000000000..237930a00f6b --- /dev/null +++ b/services/copilot-switchboard/src/index.ts @@ -0,0 +1,105 @@ +/** + * Trust model: the Worker holds zero user API keys and never sees user + * code. Reviews run in the user's local goosed via the lapstone tunnel + * using a per-install secret; KV stores opaque routing data only. + * + * Registration is authenticated by exchanging a GitHub OAuth code (issued + * to the user during App install) and verifying via the GitHub API that + * the user owns the claimed installation_id. + */ + +import { verifyWebhookSignature } from './lib/github'; +import { + handleInstallation, + handleIssueComment, + handlePullRequest, + handleRegister, +} 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 Copilot 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 === '/copilot/register') { + return handleRegisterRoute(request, env); + } + + 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/copilot-switchboard/src/lib/github.ts b/services/copilot-switchboard/src/lib/github.ts new file mode 100644 index 000000000000..196c03c352d6 --- /dev/null +++ b/services/copilot-switchboard/src/lib/github.ts @@ -0,0 +1,173 @@ +// No third-party deps — Web Crypto + fetch only, portable to any +// Web-Platform runtime, not just Cloudflare Workers. + +const API = 'https://api.github.com'; +const UA = 'goose-copilot-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): ArrayBuffer { + 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); + return buf.buffer; +} + +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; +} + +export async function getPullRequestHead( + fullName: string, + prNumber: number, + token: string +): Promise<{ sha: 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 }; html_url: string }; + return { sha: data.head.sha, 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 Copilot', + head_sha: headSha, + status: 'in_progress', + output: { + title: 'Goose 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'); +} + +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/copilot-switchboard/src/lib/handlers.ts b/services/copilot-switchboard/src/lib/handlers.ts new file mode 100644 index 000000000000..2b9d8e4147ee --- /dev/null +++ b/services/copilot-switchboard/src/lib/handlers.ts @@ -0,0 +1,218 @@ +// 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, + getInstallationToken, + getPullRequestHead, +} from './github'; +import { exchangeCodeAndVerify } from './oauth'; +import { deleteInstall, loadInstall, saveInstall } from './registry'; +import { runReviewViaTunnel } from './tunnel'; +import type { + Env, + InstallationEvent, + IssueCommentEvent, + PullRequestEvent, + RegisterRequest, +} from './types'; + +const REVIEW_TRIGGER_RE = /(^|\s)@goose-copilot\s+review\b/i; + +export async function handleRegister(req: RegisterRequest, env: Env): Promise { + if ( + !req || + typeof req.installation_id !== 'number' || + 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 verification = await exchangeCodeAndVerify({ + clientId: env.GITHUB_OAUTH_CLIENT_ID, + clientSecret: env.GITHUB_OAUTH_CLIENT_SECRET, + code: req.oauth_code, + installationId: req.installation_id, + }); + if (!verification.ok) { + return jsonError(verification.status, verification.error); + } + + await saveInstall(env, { + installationId: req.installation_id, + agentId: req.agent_id, + tunnelSecret: req.tunnel_secret, + tunnelUrl: req.tunnel_url, + registeredAt: new Date().toISOString(), + }); + + return new Response(JSON.stringify({ ok: true }), { + 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' }, + }); +} + +// `created`/`added`/suspend/unsuspend are no-ops here — Desktop owns +// /register once the user enables Copilot. 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); + } +} + +export async function handlePullRequest(payload: PullRequestEvent, env: Env): Promise { + if (!['opened', 'synchronize', 'reopened'].includes(payload.action)) return; + if (payload.pull_request.draft) 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; + if (!payload.issue.pull_request) return; + if (!REVIEW_TRIGGER_RE.test(payload.comment.body)) return; + + const jwt = await generateAppJwt(env.GITHUB_APP_ID, env.GITHUB_APP_PRIVATE_KEY); + const token = await getInstallationToken(payload.installation.id, jwt); + const pr = await getPullRequestHead(payload.repository.full_name, payload.issue.number, token); + + await triggerReview({ + fullName: payload.repository.full_name, + prNumber: payload.issue.number, + headSha: pr.sha, + prUrl: pr.htmlUrl, + installationId: payload.installation.id, + env, + token, + }); +} + +async function triggerReview(opts: { + fullName: string; + prNumber: number; + headSha: string; + prUrl: string; + installationId: number; + env: Env; + /** Reuse a freshly-minted token from the caller if we already have one. */ + token?: string; +}): 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 Copilot not enabled', + summary: + 'No local goosed is registered for this installation. Open Goose Desktop → Copilot tab → enable code review to start receiving reviews.', + token: opts.token, + }).catch(() => {}); + 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 (err) { + console.warn( + `[trigger] ${fullName} #${prNumber}: check run creation failed (continuing): ${ + err instanceof Error ? err.message : err + }` + ); + } + + try { + const result = await runReviewViaTunnel(install, { + githubToken: token, + repo: fullName, + prNumber, + headSha, + prUrl, + checkRunId, + }); + + 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 Copilot offline', + summary: `Could not reach your local goosed via the tunnel:\n\n${msg}\n\nMake sure Goose Desktop is running and try \`@goose-copilot 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, + }); +} diff --git a/services/copilot-switchboard/src/lib/oauth.ts b/services/copilot-switchboard/src/lib/oauth.ts new file mode 100644 index 000000000000..b53f345ce04b --- /dev/null +++ b/services/copilot-switchboard/src/lib/oauth.ts @@ -0,0 +1,75 @@ +// Exchanges a GitHub App OAuth code for a user access token and verifies +// the user actually has access to the claimed installation_id. + +const UA = 'goose-copilot-switchboard/0.1'; + +interface OAuthTokenResponse { + access_token?: string; + error?: string; + error_description?: string; +} + +interface InstallationListResponse { + total_count: number; + installations: Array<{ id: number }>; +} + +export async function exchangeCodeAndVerify(opts: { + clientId: string; + clientSecret: string; + code: string; + installationId: number; +}): Promise<{ ok: true } | { ok: false; status: number; error: string }> { + 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 owned = installs.installations.some((i) => i.id === opts.installationId); + if (!owned) { + return { + ok: false, + status: 403, + error: 'authenticated user does not own the requested installation', + }; + } + return { ok: true }; +} diff --git a/services/copilot-switchboard/src/lib/registry.ts b/services/copilot-switchboard/src/lib/registry.ts new file mode 100644 index 000000000000..a16dafea9b8e --- /dev/null +++ b/services/copilot-switchboard/src/lib/registry.ts @@ -0,0 +1,26 @@ +import type { Env, InstallRecord } from './types'; + +function key(installationId: number): string { + return `install:${installationId}`; +} + +export async function loadInstall( + env: Env, + installationId: number +): Promise { + const raw = await env.INSTALL_REGISTRY.get(key(installationId)); + if (!raw) return null; + try { + return JSON.parse(raw) as InstallRecord; + } catch { + return null; + } +} + +export async function saveInstall(env: Env, record: InstallRecord): Promise { + await env.INSTALL_REGISTRY.put(key(record.installationId), JSON.stringify(record)); +} + +export async function deleteInstall(env: Env, installationId: number): Promise { + await env.INSTALL_REGISTRY.delete(key(installationId)); +} diff --git a/services/copilot-switchboard/src/lib/tunnel.ts b/services/copilot-switchboard/src/lib/tunnel.ts new file mode 100644 index 000000000000..2006569c2591 --- /dev/null +++ b/services/copilot-switchboard/src/lib/tunnel.ts @@ -0,0 +1,55 @@ +// lapstone forwards any request hitting `/tunnel//*` to +// `127.0.0.1:/*` after validating `X-Secret-Key`. So we just +// POST `/copilot/review` 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; +} + +export interface TunnelRunResult { + ok: boolean; + status: number; + body: string; +} + +const TUNNEL_TIMEOUT_MS = 20_000; + +export async function runReviewViaTunnel( + install: InstallRecord, + params: TunnelRunParams +): Promise { + const target = `${install.tunnelUrl}/copilot/review`; + + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), TUNNEL_TIMEOUT_MS); + + try { + const res = await fetch(target, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Secret-Key': install.tunnelSecret, + }, + signal: controller.signal, + body: JSON.stringify({ + github_token: params.githubToken, + repo: params.repo, + pr_number: params.prNumber, + head_sha: params.headSha, + pr_url: params.prUrl, + check_run_id: params.checkRunId, + }), + }); + const body = await res.text(); + return { ok: res.ok, status: res.status, body }; + } finally { + clearTimeout(timeout); + } +} diff --git a/services/copilot-switchboard/src/lib/types.ts b/services/copilot-switchboard/src/lib/types.ts new file mode 100644 index 000000000000..26a4236bc655 --- /dev/null +++ b/services/copilot-switchboard/src/lib/types.ts @@ -0,0 +1,61 @@ +// Kept dependency-free so the switchboard lifts cleanly into its own repo. + +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; + /** Stores routing records only — never API keys. */ + INSTALL_REGISTRY: KVNamespace; +} + +// Stored under key `install:`. Routing only; nothing +// that could compromise the user if leaked. +export interface InstallRecord { + installationId: number; + agentId: string; + tunnelSecret: string; + tunnelUrl: string; + registeredAt: string; +} + +export interface RegisterRequest { + installation_id: number; + 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: { body: string; user: { login: string } }; + issue: { + number: number; + pull_request?: { url: string } | null; + }; + repository: { full_name: string }; + installation: { id: number }; +} diff --git a/services/copilot-switchboard/tsconfig.json b/services/copilot-switchboard/tsconfig.json new file mode 100644 index 000000000000..804ac74794a1 --- /dev/null +++ b/services/copilot-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/copilot-switchboard/wrangler.toml.example b/services/copilot-switchboard/wrangler.toml.example new file mode 100644 index 000000000000..421d0e872a24 --- /dev/null +++ b/services/copilot-switchboard/wrangler.toml.example @@ -0,0 +1,21 @@ +name = "goose-copilot-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/.env.example b/ui/desktop/.env.example new file mode 100644 index 000000000000..45593cb7e3fe --- /dev/null +++ b/ui/desktop/.env.example @@ -0,0 +1,13 @@ +VITE_START_EMBEDDED_SERVER=yes +GOOSE_PROVIDER__TYPE=openai +GOOSE_PROVIDER__HOST=https://api.openai.com +GOOSE_PROVIDER__MODEL=gpt-4o + +# Goose Copilot — GitHub App credentials (kept local, never committed) +GITHUB_APP_ID= +GITHUB_APP_PRIVATE_KEY_PATH= + +# Goose Copilot — Desktop ↔ switchboard wiring +VITE_GOOSE_COPILOT_APP_SLUG= +VITE_GOOSE_COPILOT_SWITCHBOARD_URL= +VITE_GOOSE_COPILOT_REGISTER_TOKEN= diff --git a/ui/desktop/openapi.json b/ui/desktop/openapi.json index 3bd3b51992e8..01cfce1c4fe7 100644 --- a/ui/desktop/openapi.json +++ b/ui/desktop/openapi.json @@ -1723,6 +1723,68 @@ } } }, + "/copilot/review": { + "post": { + "tags": [ + "copilot" + ], + "operationId": "review", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CopilotReviewRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Review session spawned", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CopilotReviewResponse" + } + } + } + }, + "400": { + "description": "Recipe missing or invalid" + }, + "500": { + "description": "Internal error" + } + } + } + }, + "/copilot/setup": { + "post": { + "tags": [ + "copilot" + ], + "operationId": "setup", + "responses": { + "200": { + "description": "Goose Copilot connected", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CopilotSetupResponse" + } + } + } + }, + "408": { + "description": "Install timed out" + }, + "500": { + "description": "Internal error" + } + } + } + }, "/diagnostics/{session_id}": { "get": { "tags": [ @@ -4734,6 +4796,67 @@ "$ref": "#/components/schemas/Message" } }, + "CopilotReviewRequest": { + "type": "object", + "required": [ + "github_token", + "repo", + "pr_number", + "head_sha", + "pr_url" + ], + "properties": { + "check_run_id": { + "type": "integer", + "format": "int64", + "description": "The recipe updates this Check Run on completion.", + "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", + "description": "`owner/repo` form, e.g. `block/goose`." + } + } + }, + "CopilotReviewResponse": { + "type": "object", + "required": [ + "session_id" + ], + "properties": { + "session_id": { + "type": "string" + } + } + }, + "CopilotSetupResponse": { + "type": "object", + "required": [ + "installation_id" + ], + "properties": { + "installation_id": { + "type": "integer", + "format": "int64", + "minimum": 0 + } + } + }, "CreateCustomProviderResponse": { "type": "object", "required": [ diff --git a/ui/desktop/src/App.tsx b/ui/desktop/src/App.tsx index e53dcde476ac..bb8cf465c0f1 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 CopilotView from './components/copilot/CopilotView'; 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 CopilotRoute = () => { + 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() { } /> } /> } /> + } /> ; +export type CopilotReviewRequest = { + /** + * The recipe updates this Check Run on completion. + */ + check_run_id?: number | null; + github_token: string; + head_sha: string; + pr_number: number; + pr_url: string; + /** + * `owner/repo` form, e.g. `block/goose`. + */ + repo: string; +}; + +export type CopilotReviewResponse = { + session_id: string; +}; + +export type CopilotSetupResponse = { + installation_id: number; +}; + export type CreateCustomProviderResponse = { provider_name: string; }; @@ -3060,6 +3083,60 @@ export type ValidateConfigResponses = { export type ValidateConfigResponse = ValidateConfigResponses[keyof ValidateConfigResponses]; +export type ReviewData = { + body: CopilotReviewRequest; + path?: never; + query?: never; + url: '/copilot/review'; +}; + +export type ReviewErrors = { + /** + * Recipe missing or invalid + */ + 400: unknown; + /** + * Internal error + */ + 500: unknown; +}; + +export type ReviewResponses = { + /** + * Review session spawned + */ + 200: CopilotReviewResponse; +}; + +export type ReviewResponse = ReviewResponses[keyof ReviewResponses]; + +export type SetupData = { + body?: never; + path?: never; + query?: never; + url: '/copilot/setup'; +}; + +export type SetupErrors = { + /** + * Install timed out + */ + 408: unknown; + /** + * Internal error + */ + 500: unknown; +}; + +export type SetupResponses = { + /** + * Goose Copilot connected + */ + 200: CopilotSetupResponse; +}; + +export type SetupResponse2 = SetupResponses[keyof SetupResponses]; + export type DiagnosticsData = { body?: never; path: { diff --git a/ui/desktop/src/components/copilot/CopilotView.tsx b/ui/desktop/src/components/copilot/CopilotView.tsx new file mode 100644 index 000000000000..ac57befb3e8f --- /dev/null +++ b/ui/desktop/src/components/copilot/CopilotView.tsx @@ -0,0 +1,288 @@ +import { useCallback, useEffect, useState } from 'react'; +import { AlertCircle, Bot, CheckCircle2, ExternalLink, Loader2 } from 'lucide-react'; +import { MainPanelLayout } from '../Layout/MainPanelLayout'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../ui/card'; +import { Button } from '../ui/button'; +import { getTunnelStatus } from '../../api/sdk.gen'; +import type { TunnelInfo } from '../../api/types.gen'; +import { errorMessage } from '../../utils/conversionUtils'; +import { defineMessages, useIntl } from '../../i18n'; + +const STORAGE_KEY = 'goose-copilot:installation'; + +const i18n = defineMessages({ + pageTitle: { + id: 'copilotView.pageTitle', + defaultMessage: 'Goose Copilot', + }, + pageDescription: { + id: 'copilotView.pageDescription', + defaultMessage: + 'Auto-review pull requests using your local goose. Your code and API keys never leave your machine.', + }, + cardTitle: { + id: 'copilotView.cardTitle', + defaultMessage: 'Code review on pull requests', + }, + cardDescription: { + id: 'copilotView.cardDescription', + defaultMessage: + 'When enabled, every PR opened on a connected repository triggers a review on your local goose. The review is posted as inline comments on the PR.', + }, + statusLocalTunnel: { + id: 'copilotView.statusLocalTunnel', + defaultMessage: 'Local tunnel', + }, + statusGithubApp: { + id: 'copilotView.statusGithubApp', + defaultMessage: 'GitHub App', + }, + tunnelRunning: { + id: 'copilotView.tunnelRunning', + defaultMessage: 'Running', + }, + tunnelStarting: { + id: 'copilotView.tunnelStarting', + defaultMessage: 'Starting…', + }, + tunnelError: { + id: 'copilotView.tunnelError', + defaultMessage: 'Error', + }, + tunnelIdle: { + id: 'copilotView.tunnelIdle', + defaultMessage: 'Idle', + }, + installationLabel: { + id: 'copilotView.installationLabel', + defaultMessage: 'Installation {id}', + }, + notConnected: { + id: 'copilotView.notConnected', + defaultMessage: 'Not connected', + }, + awaitingInstall: { + id: 'copilotView.awaitingInstall', + defaultMessage: 'Finish installing on GitHub in your browser…', + }, + awaitingInstallHint: { + id: 'copilotView.awaitingInstallHint', + defaultMessage: + 'A browser tab just opened to GitHub. Pick the repos you want reviewed and click Install & Authorize. This page will pick it up automatically.', + }, + installAction: { + id: 'copilotView.installAction', + defaultMessage: 'Connect GitHub', + }, + activeMessage: { + id: 'copilotView.activeMessage', + defaultMessage: 'Goose Copilot is active. Open a PR to try it.', + }, + setupFailed: { + id: 'copilotView.setupFailed', + defaultMessage: 'Failed to connect Goose Copilot', + }, + disconnectAction: { + id: 'copilotView.disconnectAction', + defaultMessage: 'Disconnect', + }, + disconnectHint: { + id: 'copilotView.disconnectHint', + defaultMessage: + 'Opens the GitHub App settings so you can uninstall. After you uninstall on GitHub, this side disconnects automatically.', + }, +}); + +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; + } +} + +export default function CopilotView() { + const intl = useIntl(); + const [tunnelInfo, setTunnelInfo] = useState({ + state: 'idle', + url: '', + hostname: '', + secret: '', + }); + const [stored, setStored] = useState(loadStoredInstall); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + 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]); + + const isEnabled = stored !== null && tunnelInfo.state === 'running'; + + const handleDisconnect = () => { + if (!stored) return; + const url = `https://github.com/settings/installations/${stored.installationId}`; + window.electron.openExternal(url); + localStorage.removeItem(STORAGE_KEY); + setStored(null); + }; + + const handleConnect = async () => { + setError(null); + setBusy(true); + try { + const host = await window.electron.getGoosedHostPort(); + const secret = await window.electron.getSecretKey(); + if (!host) throw new Error('goosed is not running'); + + const res = await fetch(`${host}/copilot/setup`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Secret-Key': secret, + }, + }); + if (!res.ok) { + const detail = await res.text(); + throw new Error(`${res.status}: ${detail}`); + } + const body = (await res.json()) as { installation_id: number }; + const record: StoredInstall = { + installationId: body.installation_id, + enabledAt: new Date().toISOString(), + }; + localStorage.setItem(STORAGE_KEY, JSON.stringify(record)); + setStored(record); + await refreshTunnel(); + } catch (err) { + setError(errorMessage(err, intl.formatMessage(i18n.setupFailed))); + } finally { + setBusy(false); + } + }; + + const tunnelStatusLabel = (): string => { + switch (tunnelInfo.state) { + case 'running': + return intl.formatMessage(i18n.tunnelRunning); + case 'starting': + return intl.formatMessage(i18n.tunnelStarting); + case 'error': + return intl.formatMessage(i18n.tunnelError); + default: + return intl.formatMessage(i18n.tunnelIdle); + } + }; + + return ( + +
+
+
+ +
+

{intl.formatMessage(i18n.pageTitle)}

+

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

+
+
+ + + + {intl.formatMessage(i18n.cardTitle)} + {intl.formatMessage(i18n.cardDescription)} + + + + + + {error && ( +
+ {error} +
+ )} + + {isEnabled ? ( +
+
+

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

+ +
+

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

+
+ ) : busy ? ( +
+
+ + {intl.formatMessage(i18n.awaitingInstall)} +
+

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

+
+ ) : ( +
+ +
+ )} +
+
+
+
+
+ ); +} + +function StatusRow({ label, ok, detail }: { label: string; ok: boolean; detail: string }) { + return ( +
+ {label} + + {ok ? ( + + ) : ( + + )} + {detail} + +
+ ); +} diff --git a/ui/desktop/src/hooks/useNavigationItems.ts b/ui/desktop/src/hooks/useNavigationItems.ts index e6283baead90..a03b2a04bccc 100644 --- a/ui/desktop/src/hooks/useNavigationItems.ts +++ b/ui/desktop/src/hooks/useNavigationItems.ts @@ -1,5 +1,6 @@ import { AppWindow, + Bot, Clock, FileText, History, @@ -28,6 +29,7 @@ export const NAV_ITEMS: NavItem[] = [ { id: 'apps', path: '/apps', label: 'Apps', icon: AppWindow }, { id: 'scheduler', path: '/schedules', label: 'Scheduler', icon: Clock }, { id: 'extensions', path: '/extensions', label: 'Extensions', icon: Puzzle }, + { id: 'copilot', path: '/copilot', label: 'Copilot', icon: Bot }, { id: 'sessions', path: '/sessions', label: 'Session History', icon: History }, ]; @@ -66,6 +68,10 @@ const navItemMessages = defineMessages({ id: 'navigation.itemExtensions', defaultMessage: 'Extensions', }, + copilot: { + id: 'navigation.itemCopilot', + defaultMessage: 'Copilot', + }, sessions: { id: 'navigation.itemSessions', defaultMessage: 'Session History', diff --git a/ui/desktop/src/i18n/messages/en.json b/ui/desktop/src/i18n/messages/en.json index 9ba65c279d98..a3d2b4d5acb5 100644 --- a/ui/desktop/src/i18n/messages/en.json +++ b/ui/desktop/src/i18n/messages/en.json @@ -335,6 +335,63 @@ "conversationLimitsDropdown.maxTurnsDescription": { "defaultMessage": "Maximum agent turns before Goose asks for user input" }, + "copilotView.activeMessage": { + "defaultMessage": "Goose Copilot is active. Open a PR to try it." + }, + "copilotView.awaitingInstall": { + "defaultMessage": "Finish installing on GitHub in your browser…" + }, + "copilotView.awaitingInstallHint": { + "defaultMessage": "A browser tab just opened to GitHub. Pick the repos you want reviewed and click Install & Authorize. This page will pick it up automatically." + }, + "copilotView.cardDescription": { + "defaultMessage": "When enabled, every PR opened on a connected repository triggers a review on your local goose. The review is posted as inline comments on the PR." + }, + "copilotView.cardTitle": { + "defaultMessage": "Code review on pull requests" + }, + "copilotView.disconnectAction": { + "defaultMessage": "Disconnect" + }, + "copilotView.disconnectHint": { + "defaultMessage": "Opens the GitHub App settings so you can uninstall. After you uninstall on GitHub, this side disconnects automatically." + }, + "copilotView.installAction": { + "defaultMessage": "Connect GitHub" + }, + "copilotView.installationLabel": { + "defaultMessage": "Installation {id}" + }, + "copilotView.notConnected": { + "defaultMessage": "Not connected" + }, + "copilotView.pageDescription": { + "defaultMessage": "Auto-review pull requests using your local goose. Your code and API keys never leave your machine." + }, + "copilotView.pageTitle": { + "defaultMessage": "Goose Copilot" + }, + "copilotView.setupFailed": { + "defaultMessage": "Failed to connect Goose Copilot" + }, + "copilotView.statusGithubApp": { + "defaultMessage": "GitHub App" + }, + "copilotView.statusLocalTunnel": { + "defaultMessage": "Local tunnel" + }, + "copilotView.tunnelError": { + "defaultMessage": "Error" + }, + "copilotView.tunnelIdle": { + "defaultMessage": "Idle" + }, + "copilotView.tunnelRunning": { + "defaultMessage": "Running" + }, + "copilotView.tunnelStarting": { + "defaultMessage": "Starting…" + }, "costTracker.costUnavailable": { "defaultMessage": "Cost data not available for {model} ({inputTokens} input, {outputTokens} output tokens)" }, @@ -2441,6 +2498,9 @@ "navigation.itemExtensions": { "defaultMessage": "Extensions" }, + "navigation.itemCopilot": { + "defaultMessage": "Copilot" + }, "navigation.itemHome": { "defaultMessage": "New Chat" }, From e1818e3f7515871421e7c108b94886fc907ebb63 Mon Sep 17 00:00:00 2001 From: Abhijay Jain Date: Thu, 14 May 2026 13:32:48 +0530 Subject: [PATCH 02/25] feat(copilot): replace recipe with direct-Rust handler on goose review Signed-off-by: Abhijay Jain --- Cargo.lock | 1 + crates/goose-server/Cargo.toml | 1 + crates/goose-server/src/routes/copilot.rs | 696 ++++++++++++++-------- ui/desktop/openapi.json | 16 +- ui/desktop/src/api/types.gen.ts | 13 +- 5 files changed, 447 insertions(+), 280 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fd7f5d235be1..1101f0b31a24 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4818,6 +4818,7 @@ dependencies = [ "serde_yaml", "socket2", "subtle", + "tempfile", "thiserror 1.0.69", "tokio", "tokio-stream", diff --git a/crates/goose-server/Cargo.toml b/crates/goose-server/Cargo.toml index c1f04fc6dddf..105423067d04 100644 --- a/crates/goose-server/Cargo.toml +++ b/crates/goose-server/Cargo.toml @@ -90,6 +90,7 @@ axum-server = { version = "0.8", default-features = false } aws-lc-rs = { version = "1.17", default-features = false, optional = true } openssl = { version = "0.10.66", default-features = false, optional = true } pem = { version = "3.0.2", default-features = false, features = ["std"] } +tempfile.workspace = true [target.'cfg(windows)'.dependencies] winreg = { version = "0.56", default-features = false } diff --git a/crates/goose-server/src/routes/copilot.rs b/crates/goose-server/src/routes/copilot.rs index caf45ac84867..3d6811875a0a 100644 --- a/crates/goose-server/src/routes/copilot.rs +++ b/crates/goose-server/src/routes/copilot.rs @@ -1,214 +1,34 @@ -//! Renders the `goose-copilot-review` recipe with per-PR params and spawns -//! an agent session in the background. Returns the session id immediately. +//! Goose Copilot review endpoint. +//! +//! Receives a per-PR review request from the switchboard, clones the user's +//! repo to a temp directory using the GitHub App installation token, invokes +//! `goose review --range BASE...HEAD` as a subprocess (parallel orchestrator +//! lives in goose-cli), parses the JSONL findings, and posts them back to +//! GitHub as inline review comments + a check-run conclusion. -use std::collections::HashMap; use std::env; use std::path::{Path, PathBuf}; +use std::process::Stdio; use std::sync::Arc; -use anyhow::Result; +use anyhow::{anyhow, bail, Context, Result}; use axum::{extract::State, response::Json, routing::post, Router}; -use goose::agents::{Agent, SessionConfig}; -use goose::config::paths::Paths; use goose::config::signup_copilot::CopilotInstallFlow; -use goose::config::{resolve_extensions_for_new_session, Config}; -use goose::conversation::message::Message; -use goose::providers::create; -use goose::recipe::template_recipe::render_recipe_content_with_params; -use goose::recipe::Recipe; -use goose::session::session_manager::SessionType; +use reqwest::Client; use serde::{Deserialize, Serialize}; -use tokio_util::sync::CancellationToken; +use tokio::process::Command; use utoipa::ToSchema; use crate::routes::errors::ErrorResponse; use crate::state::AppState; -const DEFAULT_RECIPE_FILENAME: &str = "goose-copilot-review.yaml"; -const RECIPE_PATH_ENV: &str = "GOOSE_COPILOT_RECIPE_PATH"; const SWITCHBOARD_URL: &str = "https://goose-copilot-switchboard.example.workers.dev"; const SWITCHBOARD_URL_ENV: &str = "GOOSE_COPILOT_SWITCHBOARD_URL"; +const USER_AGENT: &str = "goose-copilot/0.1"; -#[derive(Debug, Deserialize, ToSchema)] -pub struct CopilotReviewRequest { - pub github_token: String, - /// `owner/repo` form, e.g. `block/goose`. - pub repo: String, - pub pr_number: u64, - pub head_sha: String, - pub pr_url: String, - /// The recipe updates this Check Run on completion. - #[serde(default)] - pub check_run_id: Option, -} - -#[derive(Debug, Serialize, ToSchema)] -pub struct CopilotReviewResponse { - pub session_id: String, -} - -#[utoipa::path( - post, - path = "/copilot/review", - request_body = CopilotReviewRequest, - responses( - (status = 200, description = "Review session spawned", body = CopilotReviewResponse), - (status = 400, description = "Recipe missing or invalid"), - (status = 500, description = "Internal error"), - ), - tag = "copilot" -)] -#[axum::debug_handler] -async fn review( - State(_state): State>, - Json(req): Json, -) -> Result, ErrorResponse> { - let recipe_path = locate_recipe()?; - let raw = tokio::fs::read_to_string(&recipe_path).await.map_err(|e| { - ErrorResponse::bad_request(format!( - "Recipe not found at {}: {e}. Set {RECIPE_PATH_ENV} or place the recipe at the default path.", - recipe_path.display(), - )) - })?; - - let params = build_params(&req, &recipe_path); - let rendered = render_recipe_content_with_params(&raw, ¶ms)?; - let recipe: Recipe = serde_yaml::from_str(&rendered)?; - - let prompt_text = recipe_prompt(&recipe)?; - let session_id = spawn_review(recipe, prompt_text, req).await?; - - Ok(Json(CopilotReviewResponse { session_id })) -} - -fn locate_recipe() -> Result { - if let Ok(custom) = env::var(RECIPE_PATH_ENV) { - let p = PathBuf::from(custom); - if p.exists() { - return Ok(p); - } - return Err(ErrorResponse::bad_request(format!( - "{RECIPE_PATH_ENV} points to {} which does not exist", - p.display() - ))); - } - Ok(Paths::config_dir() - .join("recipes") - .join(DEFAULT_RECIPE_FILENAME)) -} - -fn build_params(req: &CopilotReviewRequest, recipe_path: &Path) -> HashMap { - let mut params = HashMap::new(); - params.insert("github_token".to_string(), req.github_token.clone()); - params.insert("repo".to_string(), req.repo.clone()); - params.insert("pr_number".to_string(), req.pr_number.to_string()); - params.insert("head_sha".to_string(), req.head_sha.clone()); - params.insert("pr_url".to_string(), req.pr_url.clone()); - params.insert( - "check_run_id".to_string(), - req.check_run_id.map(|n| n.to_string()).unwrap_or_default(), - ); - if let Some(parent) = recipe_path.parent() { - params.insert( - "recipe_dir".to_string(), - parent.to_string_lossy().into_owned(), - ); - } - params -} - -fn recipe_prompt(recipe: &Recipe) -> Result { - recipe - .prompt - .as_deref() - .filter(|s| !s.trim().is_empty()) - .or_else(|| { - recipe - .instructions - .as_deref() - .filter(|s| !s.trim().is_empty()) - }) - .map(|s| s.to_string()) - .ok_or_else(|| { - ErrorResponse::bad_request( - "Recipe must define either `prompt` or `instructions`".to_string(), - ) - }) -} - -async fn spawn_review( - recipe: Recipe, - prompt_text: String, - req: CopilotReviewRequest, -) -> Result { - let agent = Agent::new(); - - let config = Config::global(); - let provider_name = config.get_goose_provider()?; - let model_name = config.get_goose_model()?; - let model_config = - goose::model::ModelConfig::new(&model_name)?.with_canonical_limits(&provider_name); - - let session = agent - .config - .session_manager - .create_session( - std::env::current_dir()?, - format!("Copilot review {} #{}", req.repo, req.pr_number), - SessionType::Scheduled, - agent.config.goose_mode, - ) - .await?; - - let extensions = resolve_extensions_for_new_session(recipe.extensions.as_deref(), None); - for ext in &extensions { - agent.add_extension(ext.clone(), &session.id).await?; - } - - let agent_provider = create(&provider_name, model_config, extensions).await?; - agent.update_provider(agent_provider, &session.id).await?; - - let session_id = session.id.clone(); - - tokio::spawn(async move { - let user_message = Message::user().with_text(&prompt_text); - - let session_config = SessionConfig { - id: session_id.clone(), - schedule_id: None, - max_turns: None, - retry_config: None, - }; - - let cancel_token = CancellationToken::new(); - match agent - .reply(user_message, session_config, Some(cancel_token)) - .await - { - Ok(stream) => { - use futures::StreamExt; - let mut stream = std::pin::pin!(stream); - while stream.next().await.is_some() {} - } - Err(e) => { - tracing::error!("[copilot] review session {} failed: {}", session_id, e); - } - } - - if let Err(e) = agent - .config - .session_manager - .update(&session_id) - .recipe(Some(recipe)) - .apply() - .await - { - tracing::warn!("[copilot] failed to persist recipe on session: {}", e); - } - }); - - Ok(session.id) -} +// --------------------------------------------------------------------------- +// POST /copilot/setup — local OAuth install flow +// --------------------------------------------------------------------------- #[derive(Debug, Serialize, ToSchema)] pub struct CopilotSetupResponse { @@ -247,7 +67,6 @@ async fn setup( let agent_id = extract_agent_id(&tunnel_info.url) .ok_or_else(|| ErrorResponse::internal("tunnel URL is missing the agent id".to_string()))?; - let switchboard = switchboard_url(); let body = serde_json::json!({ "installation_id": callback.installation_id, "oauth_code": callback.oauth_code, @@ -255,9 +74,8 @@ async fn setup( "tunnel_secret": tunnel_info.secret, "tunnel_url": tunnel_info.url, }); - let client = reqwest::Client::new(); - let res = client - .post(format!("{}/copilot/register", switchboard)) + let res = Client::new() + .post(format!("{}/copilot/register", switchboard_url())) .json(&body) .send() .await @@ -285,6 +103,356 @@ fn extract_agent_id(tunnel_url: &str) -> Option { .map(|(_, rest)| rest.split(['/', '?', '#']).next().unwrap_or("").to_string()) } +// --------------------------------------------------------------------------- +// POST /copilot/review — webhook-triggered PR review +// --------------------------------------------------------------------------- + +#[derive(Debug, Deserialize, Clone, ToSchema)] +pub struct CopilotReviewRequest { + /// Short-lived GitHub App installation token, scoped to the user's repos. + pub github_token: String, + /// `owner/repo` form, e.g. `block/goose`. + pub repo: String, + pub pr_number: u64, + pub head_sha: String, + pub pr_url: String, + /// The endpoint updates this Check Run on completion. + #[serde(default)] + pub check_run_id: Option, +} + +#[derive(Debug, Serialize, ToSchema)] +pub struct CopilotReviewResponse { + pub accepted: bool, +} + +#[utoipa::path( + post, + path = "/copilot/review", + request_body = CopilotReviewRequest, + responses( + (status = 200, description = "Review accepted, running in background", body = CopilotReviewResponse), + (status = 500, description = "Internal error"), + ), + tag = "copilot" +)] +#[axum::debug_handler] +async fn review( + State(_state): State>, + Json(req): Json, +) -> Result, ErrorResponse> { + let pr_label = format!("{} #{}", req.repo, req.pr_number); + tokio::spawn(async move { + if let Err(e) = run_review(req).await { + tracing::error!("[copilot] review {} failed: {:#}", pr_label, e); + } + }); + Ok(Json(CopilotReviewResponse { accepted: true })) +} + +/// One review finding emitted by `goose review` as JSONL. Matches the shape +/// of `goose_cli::commands::review::orchestrator::Finding`. +#[derive(Debug, Clone, Deserialize)] +struct Finding { + severity: String, + path: String, + #[serde(default)] + line_start: i64, + #[serde(default)] + line_end: i64, + summary: String, + #[serde(default)] + check: String, +} + +async fn run_review(req: CopilotReviewRequest) -> Result<()> { + let pr = fetch_pr_metadata(&req).await?; + let workdir = tempfile::tempdir().context("create temp workdir")?; + git_clone_and_checkout(&req, workdir.path()).await?; + let findings = run_goose_review(workdir.path(), &pr.base_sha, &req.head_sha).await?; + post_review(&req, &findings).await?; + if let Some(crid) = req.check_run_id { + complete_check_run(&req, crid, &findings).await?; + } + Ok(()) +} + +struct PrMetadata { + base_sha: String, +} + +async fn fetch_pr_metadata(req: &CopilotReviewRequest) -> 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 = github_client() + .get(&url) + .header("Authorization", format!("token {}", req.github_token)) + .send() + .await + .context("fetch PR metadata")?; + if !res.status().is_success() { + bail!( + "fetch PR metadata: {} — {}", + res.status(), + res.text().await.unwrap_or_default() + ); + } + let pr: PrResponse = res.json().await.context("parse PR metadata")?; + Ok(PrMetadata { + base_sha: pr.base.sha, + }) +} + +async fn git_clone_and_checkout(req: &CopilotReviewRequest, dest: &Path) -> Result<()> { + let url = format!( + "https://x-access-token:{}@github.com/{}", + req.github_token, req.repo + ); + git_run(dest, &["clone", "--quiet", "--no-tags", &url, "."]).await?; + let refspec = format!("+refs/pull/{}/head:refs/copilot/pr", req.pr_number); + git_run(dest, &["fetch", "--quiet", "origin", &refspec]).await?; + git_run(dest, &["checkout", "--quiet", "refs/copilot/pr"]).await?; + Ok(()) +} + +async fn git_run(cwd: &Path, args: &[&str]) -> Result<()> { + let output = Command::new("git") + .current_dir(cwd) + .args(args) + .stdin(Stdio::null()) + .output() + .await + .context(format!("invoke git {}", args.join(" ")))?; + if !output.status.success() { + bail!( + "git {} failed: {}", + args.join(" "), + String::from_utf8_lossy(&output.stderr).trim() + ); + } + Ok(()) +} + +async fn run_goose_review(workdir: &Path, base: &str, head: &str) -> Result> { + let bin = locate_goose_binary()?; + let range = format!("{base}...{head}"); + + let output = Command::new(&bin) + .current_dir(workdir) + .args(["review", &range, "--severity", "medium", "--quiet"]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .await + .context(format!("invoke {} review", bin.display()))?; + + 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) +} + +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) +} + +/// Resolve the `goose` binary path. Prefer the binary co-located with the +/// running `goosed` (typical Desktop install layout), then fall back to a +/// `PATH` lookup so dev environments without a co-located binary still work. +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")) +} + +async fn post_review(req: &CopilotReviewRequest, findings: &[Finding]) -> Result<()> { + let url = format!( + "https://api.github.com/repos/{}/pulls/{}/reviews", + req.repo, req.pr_number + ); + let payload = build_review_payload(req, findings, false); + + let res = github_client() + .post(&url) + .header("Authorization", format!("token {}", req.github_token)) + .json(&payload) + .send() + .await + .context("POST PR review")?; + + if res.status().is_success() { + return Ok(()); + } + + // 422 typically means an inline comment targeted a line not in the diff. + // Fall back to summary-only so the review still lands. + let status = res.status(); + let detail = res.text().await.unwrap_or_default(); + tracing::warn!( + "[copilot] inline review rejected ({status}): {} — falling back to summary-only", + detail.chars().take(300).collect::() + ); + + let fallback = build_review_payload(req, findings, true); + github_client() + .post(&url) + .header("Authorization", format!("token {}", req.github_token)) + .json(&fallback) + .send() + .await + .context("POST fallback summary-only review")? + .error_for_status() + .context("fallback summary-only review rejected")?; + Ok(()) +} + +fn build_review_payload( + req: &CopilotReviewRequest, + findings: &[Finding], + summary_only: bool, +) -> serde_json::Value { + let comments: Vec = if summary_only { + Vec::new() + } else { + findings + .iter() + .filter(|f| !f.path.is_empty()) + .map(|f| { + let line = if f.line_end > 0 { + f.line_end + } else { + f.line_start + }; + let line = line.max(1); + let body = format!( + "**{}** ({}) — {}", + f.severity.to_ascii_uppercase(), + if f.check.is_empty() { "main" } else { &f.check }, + f.summary + ); + serde_json::json!({ + "path": f.path, + "line": line, + "side": "RIGHT", + "body": body, + }) + }) + .collect() + }; + + let mut summary = format!( + "**[goose Copilot]({})** — {} finding(s)", + req.pr_url, + findings.len() + ); + if !findings.is_empty() { + summary.push_str(":\n\n"); + for f in findings.iter().take(10) { + summary.push_str(&format!( + "- **{}** in `{}`: {}\n", + f.severity, f.path, f.summary + )); + } + if findings.len() > 10 { + summary.push_str(&format!("…and {} more.\n", findings.len() - 10)); + } + } + if summary_only { + summary.push_str("\n_(inline comments were rejected by GitHub; posted summary only.)_"); + } + + serde_json::json!({ + "commit_id": req.head_sha, + "body": summary, + "event": "COMMENT", + "comments": comments, + }) +} + +async fn complete_check_run( + req: &CopilotReviewRequest, + 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 + ); + github_client() + .patch(&url) + .header("Authorization", format!("token {}", req.github_token)) + .json(&serde_json::json!({ + "status": "completed", + "conclusion": "success", + "output": { + "title": title, + "summary": "goose Copilot review complete.", + }, + })) + .send() + .await + .context("PATCH check run")? + .error_for_status() + .context("PATCH check run rejected")?; + Ok(()) +} + +fn github_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 fn routes(state: Arc) -> Router { Router::new() .route("/copilot/review", post(review)) @@ -296,85 +464,85 @@ pub fn routes(state: Arc) -> Router { mod tests { use super::*; - fn sample_req() -> CopilotReviewRequest { - CopilotReviewRequest { - github_token: "ghs_test".to_string(), - repo: "block/goose".to_string(), - pr_number: 42, - head_sha: "abc123".to_string(), - pr_url: "https://github.com/block/goose/pull/42".to_string(), - check_run_id: Some(99), - } - } - #[test] - fn build_params_maps_required_fields() { - let path = PathBuf::from("/tmp/recipes/r.yaml"); - let params = build_params(&sample_req(), &path); - - assert_eq!(params.get("github_token").unwrap(), "ghs_test"); - assert_eq!(params.get("repo").unwrap(), "block/goose"); - assert_eq!(params.get("pr_number").unwrap(), "42"); - assert_eq!(params.get("head_sha").unwrap(), "abc123"); + fn extract_agent_id_parses_tunnel_url() { assert_eq!( - params.get("pr_url").unwrap(), - "https://github.com/block/goose/pull/42" + extract_agent_id("https://tunnel-proxy.example/tunnel/abc123"), + Some("abc123".to_string()) ); - assert_eq!(params.get("check_run_id").unwrap(), "99"); - assert_eq!(params.get("recipe_dir").unwrap(), "/tmp/recipes"); - } - - #[test] - fn build_params_handles_missing_check_run_id() { - let mut req = sample_req(); - req.check_run_id = None; - let params = build_params(&req, Path::new("/tmp/r.yaml")); - assert_eq!(params.get("check_run_id").unwrap(), ""); - } - - #[test] - fn recipe_prompt_prefers_prompt_over_instructions() { - let recipe: Recipe = serde_yaml::from_str( - "version: '1.0.0'\ntitle: t\ndescription: d\nprompt: from prompt\ninstructions: from instructions\n", - ) - .unwrap(); - assert_eq!(recipe_prompt(&recipe).unwrap(), "from prompt"); + 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 recipe_prompt_falls_back_to_instructions() { - let recipe: Recipe = serde_yaml::from_str( - "version: '1.0.0'\ntitle: t\ndescription: d\ninstructions: from instructions\n", - ) - .unwrap(); - assert_eq!(recipe_prompt(&recipe).unwrap(), "from instructions"); + 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 recipe_prompt_rejects_when_both_missing() { - let recipe: Recipe = - serde_yaml::from_str("version: '1.0.0'\ntitle: t\ndescription: d\n").unwrap(); - assert!(recipe_prompt(&recipe).is_err()); + fn parse_findings_rejects_malformed_line() { + let stdout = "{\"severity\":\"high\"}\nnot-json\n"; + assert!(parse_findings(stdout).is_err()); } #[test] - fn locate_recipe_uses_env_override_when_present() { - let tmp = std::env::temp_dir().join("goose-copilot-locate-test.yaml"); - std::fs::write(&tmp, "stub").unwrap(); - std::env::set_var(RECIPE_PATH_ENV, &tmp); - - let located = locate_recipe().unwrap(); - assert_eq!(located, tmp); - - std::env::remove_var(RECIPE_PATH_ENV); - std::fs::remove_file(&tmp).ok(); + fn build_review_payload_inline_includes_comments() { + let req = CopilotReviewRequest { + github_token: "t".into(), + repo: "o/r".into(), + pr_number: 1, + head_sha: "h".into(), + pr_url: "u".into(), + check_run_id: None, + }; + let findings = vec![Finding { + severity: "high".into(), + path: "a.rs".into(), + line_start: 1, + line_end: 2, + summary: "bug".into(), + check: "main".into(), + }]; + let payload = build_review_payload(&req, &findings, false); + let comments = payload["comments"].as_array().unwrap(); + assert_eq!(comments.len(), 1); + assert_eq!(comments[0]["path"], "a.rs"); + assert_eq!(comments[0]["line"], 2); } #[test] - fn locate_recipe_errors_when_env_path_missing() { - std::env::set_var(RECIPE_PATH_ENV, "/nonexistent/path/recipe.yaml"); - let result = locate_recipe(); - std::env::remove_var(RECIPE_PATH_ENV); - assert!(result.is_err()); + fn build_review_payload_summary_only_drops_comments() { + let req = CopilotReviewRequest { + github_token: "t".into(), + repo: "o/r".into(), + pr_number: 1, + head_sha: "h".into(), + pr_url: "u".into(), + check_run_id: None, + }; + let findings = vec![Finding { + severity: "high".into(), + path: "a.rs".into(), + line_start: 1, + line_end: 2, + summary: "bug".into(), + check: "main".into(), + }]; + let payload = build_review_payload(&req, &findings, true); + assert!(payload["comments"].as_array().unwrap().is_empty()); + assert!(payload["body"] + .as_str() + .unwrap() + .contains("rejected by GitHub")); } } diff --git a/ui/desktop/openapi.json b/ui/desktop/openapi.json index 01cfce1c4fe7..0e49bd8bd448 100644 --- a/ui/desktop/openapi.json +++ b/ui/desktop/openapi.json @@ -1741,7 +1741,7 @@ }, "responses": { "200": { - "description": "Review session spawned", + "description": "Review accepted, running in background", "content": { "application/json": { "schema": { @@ -1750,9 +1750,6 @@ } } }, - "400": { - "description": "Recipe missing or invalid" - }, "500": { "description": "Internal error" } @@ -4809,12 +4806,13 @@ "check_run_id": { "type": "integer", "format": "int64", - "description": "The recipe updates this Check Run on completion.", + "description": "The endpoint updates this Check Run on completion.", "nullable": true, "minimum": 0 }, "github_token": { - "type": "string" + "type": "string", + "description": "Short-lived GitHub App installation token, scoped to the user's repos." }, "head_sha": { "type": "string" @@ -4836,11 +4834,11 @@ "CopilotReviewResponse": { "type": "object", "required": [ - "session_id" + "accepted" ], "properties": { - "session_id": { - "type": "string" + "accepted": { + "type": "boolean" } } }, diff --git a/ui/desktop/src/api/types.gen.ts b/ui/desktop/src/api/types.gen.ts index e732dc4013cf..c409238bd711 100644 --- a/ui/desktop/src/api/types.gen.ts +++ b/ui/desktop/src/api/types.gen.ts @@ -175,9 +175,12 @@ export type Conversation = Array; export type CopilotReviewRequest = { /** - * The recipe updates this Check Run on completion. + * The endpoint updates this Check Run on completion. */ check_run_id?: number | null; + /** + * Short-lived GitHub App installation token, scoped to the user's repos. + */ github_token: string; head_sha: string; pr_number: number; @@ -189,7 +192,7 @@ export type CopilotReviewRequest = { }; export type CopilotReviewResponse = { - session_id: string; + accepted: boolean; }; export type CopilotSetupResponse = { @@ -3091,10 +3094,6 @@ export type ReviewData = { }; export type ReviewErrors = { - /** - * Recipe missing or invalid - */ - 400: unknown; /** * Internal error */ @@ -3103,7 +3102,7 @@ export type ReviewErrors = { export type ReviewResponses = { /** - * Review session spawned + * Review accepted, running in background */ 200: CopilotReviewResponse; }; From e9f8071cea9450a535ce9327f6f89b4320c33d8b Mon Sep 17 00:00:00 2001 From: Abhijay Jain Date: Fri, 15 May 2026 18:56:02 +0530 Subject: [PATCH 03/25] feat(copilot): @goose-copilot mention replies with optional commit+push Signed-off-by: Abhijay Jain --- .../src/commands/review/orchestrator.rs | 13 +- crates/goose-server/src/openapi.rs | 2 + crates/goose-server/src/routes/copilot.rs | 321 +++++++++++++++++- .../copilot-switchboard/src/lib/github.ts | 23 +- .../copilot-switchboard/src/lib/handlers.ts | 93 ++++- .../copilot-switchboard/src/lib/tunnel.ts | 66 +++- services/copilot-switchboard/src/lib/types.ts | 5 +- ui/desktop/openapi.json | 70 ++++ ui/desktop/src/api/types.gen.ts | 37 ++ 9 files changed, 594 insertions(+), 36 deletions(-) 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 f13e3384db7b..95240f0d9801 100644 --- a/crates/goose-server/src/openapi.rs +++ b/crates/goose-server/src/openapi.rs @@ -481,6 +481,7 @@ derive_utoipa!(IconTheme as IconThemeSchema); super::routes::tunnel::get_tunnel_status, super::routes::copilot::review, super::routes::copilot::setup, + super::routes::copilot::comment, super::routes::telemetry::send_telemetry_event, super::routes::dictation::transcribe_dictation, super::routes::dictation::get_dictation_config, @@ -663,6 +664,7 @@ derive_utoipa!(IconTheme as IconThemeSchema); super::routes::copilot::CopilotReviewRequest, super::routes::copilot::CopilotReviewResponse, super::routes::copilot::CopilotSetupResponse, + super::routes::copilot::CopilotCommentRequest, super::routes::telemetry::TelemetryEventRequest, goose::goose_apps::GooseApp, goose::goose_apps::WindowProps, diff --git a/crates/goose-server/src/routes/copilot.rs b/crates/goose-server/src/routes/copilot.rs index 3d6811875a0a..0ba648953b69 100644 --- a/crates/goose-server/src/routes/copilot.rs +++ b/crates/goose-server/src/routes/copilot.rs @@ -26,10 +26,6 @@ const SWITCHBOARD_URL: &str = "https://goose-copilot-switchboard.example.workers const SWITCHBOARD_URL_ENV: &str = "GOOSE_COPILOT_SWITCHBOARD_URL"; const USER_AGENT: &str = "goose-copilot/0.1"; -// --------------------------------------------------------------------------- -// POST /copilot/setup — local OAuth install flow -// --------------------------------------------------------------------------- - #[derive(Debug, Serialize, ToSchema)] pub struct CopilotSetupResponse { pub installation_id: u64, @@ -103,10 +99,6 @@ fn extract_agent_id(tunnel_url: &str) -> Option { .map(|(_, rest)| rest.split(['/', '?', '#']).next().unwrap_or("").to_string()) } -// --------------------------------------------------------------------------- -// POST /copilot/review — webhook-triggered PR review -// --------------------------------------------------------------------------- - #[derive(Debug, Deserialize, Clone, ToSchema)] pub struct CopilotReviewRequest { /// Short-lived GitHub App installation token, scoped to the user's repos. @@ -163,6 +155,10 @@ struct Finding { summary: String, #[serde(default)] check: String, + /// Optional concrete fix the orchestrator captured. Rendered as a + /// GitHub ```suggestion block in the posted review comment. + #[serde(default)] + suggestion: Option, } async fn run_review(req: CopilotReviewRequest) -> Result<()> { @@ -359,12 +355,22 @@ fn build_review_payload( f.line_start }; let line = line.max(1); - let body = format!( + 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```"); + } serde_json::json!({ "path": f.path, "line": line, @@ -453,10 +459,256 @@ fn github_client() -> Client { .expect("build reqwest client") } +#[derive(Debug, Deserialize, Clone, ToSchema)] +pub struct CopilotCommentRequest { + pub github_token: String, + pub repo: String, + pub pr_number: u64, + pub pr_url: String, + pub comment_body: String, + pub commenter: String, + /// The PR's head branch name (e.g. `feature/foo`). Used to push any + /// edits the agent makes back to the PR. + #[serde(default)] + pub head_ref: String, +} + +#[utoipa::path( + post, + path = "/copilot/comment", + request_body = CopilotCommentRequest, + responses( + (status = 200, description = "Comment accepted, replying in background", body = CopilotReviewResponse), + (status = 500, description = "Internal error"), + ), + tag = "copilot" +)] +#[axum::debug_handler] +async fn comment( + State(_state): State>, + Json(req): Json, +) -> Result, ErrorResponse> { + let pr_label = format!("{} #{}", req.repo, req.pr_number); + tokio::spawn(async move { + if let Err(e) = run_comment_reply(req).await { + tracing::error!("[copilot] comment {} failed: {:#}", pr_label, e); + } + }); + Ok(Json(CopilotReviewResponse { accepted: true })) +} + +async fn run_comment_reply(req: CopilotCommentRequest) -> Result<()> { + let workdir = tempfile::tempdir().context("create temp workdir")?; + git_clone_and_checkout_for_comment(&req, workdir.path()).await?; + let prompt = build_comment_prompt(&req); + let reply = run_goose_for_reply(workdir.path(), &prompt).await?; + let pushed = commit_and_push_if_changed(&req, workdir.path()).await?; + let final_reply = match pushed { + Some(n) => format!( + "{reply}\n\n_Pushed {n} file change(s) to `{}`._", + req.head_ref + ), + None => reply, + }; + post_pr_comment(&req, &final_reply).await?; + Ok(()) +} + +async fn git_clone_and_checkout_for_comment( + req: &CopilotCommentRequest, + dest: &Path, +) -> Result<()> { + let url = format!( + "https://x-access-token:{}@github.com/{}", + req.github_token, req.repo + ); + git_run(dest, &["clone", "--quiet", "--no-tags", &url, "."]).await?; + let refspec = format!("+refs/pull/{}/head:refs/copilot/pr", req.pr_number); + git_run(dest, &["fetch", "--quiet", "origin", &refspec]).await?; + git_run(dest, &["checkout", "--quiet", "refs/copilot/pr"]).await?; + Ok(()) +} + +fn build_comment_prompt(req: &CopilotCommentRequest) -> String { + // Strip the @goose-copilot mention so the model sees the user's actual ask. + let cleaned = req + .comment_body + .replace("@goose-copilot", "") + .trim() + .to_string(); + format!( + "You are responding to a comment on a GitHub pull request.\n\ +\n\ +Repository: {}\n\ +Pull request: #{} ({})\n\ +Commenter: @{}\n\ +\n\ +The repository is checked out at the current working directory at the\n\ +PR's head commit. 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\ +- 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.\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\ +\n\ +The commenter's message (with @goose-copilot stripped):\n\ +---\n\ +{}\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", + req.repo, req.pr_number, req.pr_url, req.commenter, cleaned, + ) +} + +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 + .context(format!("invoke {} run", bin.display()))?; + 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) +} + +/// Pull the last assistant message's plain text out of `goose run --output-format json`. +/// The shape is `{ "messages": [{ "role": "user|assistant|...", "content": [...] }, ...] }`; +/// each content entry is `{ "type": "text", "text": "..." }` or a tool-call variant we ignore. +fn extract_final_assistant_text(stdout: &str) -> Result { + #[derive(serde::Deserialize)] + struct RunOutput { + messages: Vec, + } + #[derive(serde::Deserialize)] + struct RunMessage { + role: String, + #[serde(default)] + content: Vec, + } + + let parsed: RunOutput = + serde_json::from_str(stdout).context("parse goose run --output-format json")?; + 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()) +} + +async fn post_pr_comment(req: &CopilotCommentRequest, reply: &str) -> Result<()> { + let url = format!( + "https://api.github.com/repos/{}/issues/{}/comments", + req.repo, req.pr_number + ); + let body = format!("@{} {}", req.commenter, reply); + github_client() + .post(&url) + .header("Authorization", format!("token {}", req.github_token)) + .json(&serde_json::json!({ "body": body })) + .send() + .await + .context("POST issue comment")? + .error_for_status() + .context("POST issue comment rejected")?; + Ok(()) +} + +/// If the agent left dirty files in the working tree, commit them with the +/// goose-copilot[bot] identity and push to the PR branch. Returns the number +/// of files changed (None if the tree is clean). +/// +/// Uses the same installation token the rest of the flow uses — push lands +/// in `git log` attributed to goose-copilot[bot] via GitHub App routing. +async fn commit_and_push_if_changed( + req: &CopilotCommentRequest, + 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 + .context("git status")?; + 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); + } + + git_run( + workdir, + &[ + "config", + "user.email", + "goose-copilot[bot]@users.noreply.github.com", + ], + ) + .await?; + git_run(workdir, &["config", "user.name", "goose-copilot[bot]"]).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 refspec = format!("HEAD:refs/heads/{}", req.head_ref); + git_run(workdir, &["push", "--quiet", "origin", &refspec]).await?; + Ok(Some(changed)) +} + pub fn routes(state: Arc) -> Router { Router::new() .route("/copilot/review", post(review)) .route("/copilot/setup", post(setup)) + .route("/copilot/comment", post(comment)) .with_state(state) } @@ -512,12 +764,62 @@ mod tests { line_end: 2, summary: "bug".into(), check: "main".into(), + suggestion: None, }]; let payload = build_review_payload(&req, &findings, false); let comments = payload["comments"].as_array().unwrap(); assert_eq!(comments.len(), 1); assert_eq!(comments[0]["path"], "a.rs"); assert_eq!(comments[0]["line"], 2); + assert!(!comments[0]["body"] + .as_str() + .unwrap() + .contains("```suggestion")); + } + + #[test] + fn build_review_payload_inline_emits_suggestion_block() { + let req = CopilotReviewRequest { + github_token: "t".into(), + repo: "o/r".into(), + pr_number: 1, + head_sha: "h".into(), + pr_url: "u".into(), + check_run_id: None, + }; + 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(&req, &findings, false); + let body = payload["comments"][0]["body"].as_str().unwrap(); + assert!(body.contains("```suggestion\ndef add_tag(tag, tags=None):\n```")); + } + + #[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"); + } + + #[test] + fn extract_final_assistant_text_errors_when_no_assistant() { + let stdout = + r#"{"messages": [{"role": "user", "content": [{"type": "text", "text": "hi"}]}]}"#; + assert!(extract_final_assistant_text(stdout).is_err()); } #[test] @@ -537,6 +839,7 @@ mod tests { line_end: 2, summary: "bug".into(), check: "main".into(), + suggestion: None, }]; let payload = build_review_payload(&req, &findings, true); assert!(payload["comments"].as_array().unwrap().is_empty()); diff --git a/services/copilot-switchboard/src/lib/github.ts b/services/copilot-switchboard/src/lib/github.ts index 196c03c352d6..21a2873bf94b 100644 --- a/services/copilot-switchboard/src/lib/github.ts +++ b/services/copilot-switchboard/src/lib/github.ts @@ -105,13 +105,16 @@ export async function getPullRequestHead( fullName: string, prNumber: number, token: string -): Promise<{ sha: string; htmlUrl: string }> { +): Promise<{ sha: string; ref: 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 }; html_url: string }; - return { sha: data.head.sha, htmlUrl: data.html_url }; + const data = (await res.json()) as { + head: { sha: string; ref: string }; + html_url: string; + }; + return { sha: data.head.sha, ref: data.head.ref, htmlUrl: data.html_url }; } export async function createCheckRun( @@ -158,6 +161,20 @@ export async function completeCheckRun(opts: { 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'); +} + function ghHeaders(token: string): HeadersInit { return { Authorization: `Bearer ${token}`, diff --git a/services/copilot-switchboard/src/lib/handlers.ts b/services/copilot-switchboard/src/lib/handlers.ts index 2b9d8e4147ee..9e82b59f83f0 100644 --- a/services/copilot-switchboard/src/lib/handlers.ts +++ b/services/copilot-switchboard/src/lib/handlers.ts @@ -7,10 +7,11 @@ import { generateAppJwt, getInstallationToken, getPullRequestHead, + postIssueComment, } from './github'; import { exchangeCodeAndVerify } from './oauth'; import { deleteInstall, loadInstall, saveInstall } from './registry'; -import { runReviewViaTunnel } from './tunnel'; +import { runCommentViaTunnel, runReviewViaTunnel } from './tunnel'; import type { Env, InstallationEvent, @@ -19,7 +20,8 @@ import type { RegisterRequest, } from './types'; -const REVIEW_TRIGGER_RE = /(^|\s)@goose-copilot\s+review\b/i; +const MENTION_RE = /(^|\s)@goose-copilot\b/i; +const REVIEW_TRIGGER_RE = /(^|\s)@goose-copilot\s+review\s*$/im; export async function handleRegister(req: RegisterRequest, env: Env): Promise { if ( @@ -92,23 +94,106 @@ export async function handlePullRequest(payload: PullRequestEvent, env: Env): Pr export async function handleIssueComment(payload: IssueCommentEvent, env: Env): Promise { if (payload.action !== 'created') return; if (!payload.issue.pull_request) return; - if (!REVIEW_TRIGGER_RE.test(payload.comment.body)) return; + // Bot accounts trigger nothing — prevents goose-copilot[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 jwt = await generateAppJwt(env.GITHUB_APP_ID, env.GITHUB_APP_PRIVATE_KEY); const token = await getInstallationToken(payload.installation.id, jwt); const pr = await getPullRequestHead(payload.repository.full_name, payload.issue.number, token); - await triggerReview({ + if (REVIEW_TRIGGER_RE.test(payload.comment.body)) { + await triggerReview({ + fullName: payload.repository.full_name, + prNumber: payload.issue.number, + headSha: pr.sha, + prUrl: pr.htmlUrl, + installationId: payload.installation.id, + env, + token, + }); + return; + } + + await triggerComment({ fullName: payload.repository.full_name, prNumber: payload.issue.number, headSha: pr.sha, + headRef: pr.ref, prUrl: pr.htmlUrl, + commentBody: payload.comment.body, + commenter: payload.comment.user.login, installationId: payload.installation.id, env, token, }); } +async function triggerComment(opts: { + fullName: string; + prNumber: number; + headSha: string; + headRef: string; + prUrl: string; + commentBody: string; + commenter: string; + 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 Copilot is installed on this repo but no local goose is connected. ` + + `Open Goose Desktop → Copilot tab → Connect GitHub 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, + prUrl: opts.prUrl, + commentBody, + commenter, + }); + 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 Copilot 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; diff --git a/services/copilot-switchboard/src/lib/tunnel.ts b/services/copilot-switchboard/src/lib/tunnel.ts index 2006569c2591..80753f09643d 100644 --- a/services/copilot-switchboard/src/lib/tunnel.ts +++ b/services/copilot-switchboard/src/lib/tunnel.ts @@ -1,6 +1,6 @@ // lapstone forwards any request hitting `/tunnel//*` to // `127.0.0.1:/*` after validating `X-Secret-Key`. So we just -// POST `/copilot/review` with the per-install secret. +// POST `/copilot/` with the per-install secret. import type { InstallRecord } from './types'; @@ -13,6 +13,17 @@ export interface TunnelRunParams { checkRunId?: number; } +export interface TunnelCommentParams { + githubToken: string; + repo: string; + prNumber: number; + headSha: string; + headRef: string; + prUrl: string; + commentBody: string; + commenter: string; +} + export interface TunnelRunResult { ok: boolean; status: number; @@ -21,35 +32,56 @@ export interface TunnelRunResult { const TUNNEL_TIMEOUT_MS = 20_000; -export async function runReviewViaTunnel( +async function postJson( install: InstallRecord, - params: TunnelRunParams + path: string, + body: unknown ): Promise { - const target = `${install.tunnelUrl}/copilot/review`; - const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), TUNNEL_TIMEOUT_MS); - try { - const res = await fetch(target, { + 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({ - github_token: params.githubToken, - repo: params.repo, - pr_number: params.prNumber, - head_sha: params.headSha, - pr_url: params.prUrl, - check_run_id: params.checkRunId, - }), + body: JSON.stringify(body), }); - const body = await res.text(); - return { ok: res.ok, status: res.status, 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, '/copilot/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, + }); +} + +export async function runCommentViaTunnel( + install: InstallRecord, + params: TunnelCommentParams +): Promise { + return postJson(install, '/copilot/comment', { + github_token: params.githubToken, + repo: params.repo, + pr_number: params.prNumber, + head_sha: params.headSha, + head_ref: params.headRef, + pr_url: params.prUrl, + comment_body: params.commentBody, + commenter: params.commenter, + }); +} diff --git a/services/copilot-switchboard/src/lib/types.ts b/services/copilot-switchboard/src/lib/types.ts index 26a4236bc655..48bb31470124 100644 --- a/services/copilot-switchboard/src/lib/types.ts +++ b/services/copilot-switchboard/src/lib/types.ts @@ -51,7 +51,10 @@ export interface PullRequestEvent { export interface IssueCommentEvent { action: 'created' | 'edited' | 'deleted'; - comment: { body: string; user: { login: string } }; + comment: { + body: string; + user: { login: string; type: 'User' | 'Bot' | 'Organization' }; + }; issue: { number: number; pull_request?: { url: string } | null; diff --git a/ui/desktop/openapi.json b/ui/desktop/openapi.json index 0e49bd8bd448..c00b28166406 100644 --- a/ui/desktop/openapi.json +++ b/ui/desktop/openapi.json @@ -1723,6 +1723,39 @@ } } }, + "/copilot/comment": { + "post": { + "tags": [ + "copilot" + ], + "operationId": "comment", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CopilotCommentRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Comment accepted, replying in background", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CopilotReviewResponse" + } + } + } + }, + "500": { + "description": "Internal error" + } + } + } + }, "/copilot/review": { "post": { "tags": [ @@ -4793,6 +4826,43 @@ "$ref": "#/components/schemas/Message" } }, + "CopilotCommentRequest": { + "type": "object", + "required": [ + "github_token", + "repo", + "pr_number", + "pr_url", + "comment_body", + "commenter" + ], + "properties": { + "comment_body": { + "type": "string" + }, + "commenter": { + "type": "string" + }, + "github_token": { + "type": "string" + }, + "head_ref": { + "type": "string", + "description": "The PR's head branch name (e.g. `feature/foo`). Used to push any\nedits the agent makes back to the PR." + }, + "pr_number": { + "type": "integer", + "format": "int64", + "minimum": 0 + }, + "pr_url": { + "type": "string" + }, + "repo": { + "type": "string" + } + } + }, "CopilotReviewRequest": { "type": "object", "required": [ diff --git a/ui/desktop/src/api/types.gen.ts b/ui/desktop/src/api/types.gen.ts index c409238bd711..292480d50e2e 100644 --- a/ui/desktop/src/api/types.gen.ts +++ b/ui/desktop/src/api/types.gen.ts @@ -173,6 +173,20 @@ export type ContentBlock = ({ export type Conversation = Array; +export type CopilotCommentRequest = { + comment_body: string; + commenter: string; + github_token: string; + /** + * The PR's head branch name (e.g. `feature/foo`). Used to push any + * edits the agent makes back to the PR. + */ + head_ref?: string; + pr_number: number; + pr_url: string; + repo: string; +}; + export type CopilotReviewRequest = { /** * The endpoint updates this Check Run on completion. @@ -3086,6 +3100,29 @@ export type ValidateConfigResponses = { export type ValidateConfigResponse = ValidateConfigResponses[keyof ValidateConfigResponses]; +export type CommentData = { + body: CopilotCommentRequest; + path?: never; + query?: never; + url: '/copilot/comment'; +}; + +export type CommentErrors = { + /** + * Internal error + */ + 500: unknown; +}; + +export type CommentResponses = { + /** + * Comment accepted, replying in background + */ + 200: CopilotReviewResponse; +}; + +export type CommentResponse = CommentResponses[keyof CommentResponses]; + export type ReviewData = { body: CopilotReviewRequest; path?: never; From d94275bac0a6aa8bbac4f14d7bbc6e43c2c963b0 Mon Sep 17 00:00:00 2001 From: Abhijay Jain Date: Sat, 16 May 2026 23:01:13 +0530 Subject: [PATCH 04/25] feat(copilot): emoji reactions, OAuth reconnect, tabbed Desktop UI Signed-off-by: Abhijay Jain --- crates/goose-server/src/routes/copilot.rs | 92 ++++- crates/goose/src/config/signup_copilot/mod.rs | 22 +- .../goose/src/config/signup_copilot/server.rs | 27 +- services/copilot-switchboard/src/index.ts | 10 + .../copilot-switchboard/src/lib/github.ts | 20 + .../copilot-switchboard/src/lib/handlers.ts | 49 ++- services/copilot-switchboard/src/lib/oauth.ts | 34 +- .../copilot-switchboard/src/lib/tunnel.ts | 5 + services/copilot-switchboard/src/lib/types.ts | 2 +- ui/desktop/openapi.json | 14 + ui/desktop/src/api/types.gen.ts | 10 + .../src/components/copilot/CopilotView.tsx | 377 +++++++----------- .../copilot/sections/CopilotAnalytics.tsx | 113 ++++++ .../copilot/sections/CopilotCodeReview.tsx | 148 +++++++ .../copilot/sections/CopilotConnectors.tsx | 268 +++++++++++++ .../copilot/sections/CopilotGeneral.tsx | 76 ++++ 16 files changed, 990 insertions(+), 277 deletions(-) create mode 100644 ui/desktop/src/components/copilot/sections/CopilotAnalytics.tsx create mode 100644 ui/desktop/src/components/copilot/sections/CopilotCodeReview.tsx create mode 100644 ui/desktop/src/components/copilot/sections/CopilotConnectors.tsx create mode 100644 ui/desktop/src/components/copilot/sections/CopilotGeneral.tsx diff --git a/crates/goose-server/src/routes/copilot.rs b/crates/goose-server/src/routes/copilot.rs index 0ba648953b69..59afa8384ec1 100644 --- a/crates/goose-server/src/routes/copilot.rs +++ b/crates/goose-server/src/routes/copilot.rs @@ -45,7 +45,11 @@ pub struct CopilotSetupResponse { async fn setup( State(state): State>, ) -> Result, ErrorResponse> { - let mut flow = CopilotInstallFlow::new(); + let oauth_client_id = fetch_oauth_client_id() + .await + .map_err(|e| ErrorResponse::internal(format!("oauth-config lookup failed: {e}")))?; + + let mut flow = CopilotInstallFlow::new().with_oauth_client_id(oauth_client_id); let callback = flow .complete_flow() .await @@ -64,7 +68,6 @@ async fn setup( .ok_or_else(|| ErrorResponse::internal("tunnel URL is missing the agent id".to_string()))?; let body = serde_json::json!({ - "installation_id": callback.installation_id, "oauth_code": callback.oauth_code, "agent_id": agent_id, "tunnel_secret": tunnel_info.secret, @@ -84,8 +87,17 @@ async fn setup( ))); } + #[derive(Deserialize)] + struct RegisterResponse { + installation_id: u64, + } + let register: RegisterResponse = res + .json() + .await + .map_err(|e| ErrorResponse::internal(format!("parse register response: {e}")))?; + Ok(Json(CopilotSetupResponse { - installation_id: callback.installation_id, + installation_id: register.installation_id, })) } @@ -93,6 +105,28 @@ fn switchboard_url() -> String { env::var(SWITCHBOARD_URL_ENV).unwrap_or_else(|_| SWITCHBOARD_URL.to_string()) } +/// Fetch the public OAuth client ID from the switchboard. The client *id* is +/// public — only the client *secret* stays on the worker. +async fn fetch_oauth_client_id() -> Result { + #[derive(Deserialize)] + struct OAuthConfig { + oauth_client_id: String, + } + let res = Client::new() + .get(format!("{}/copilot/oauth-config", switchboard_url())) + .send() + .await + .context("switchboard unreachable")?; + if !res.status().is_success() { + bail!("switchboard returned {}", res.status()); + } + let cfg: OAuthConfig = res.json().await.context("parse oauth-config")?; + if cfg.oauth_client_id.trim().is_empty() { + bail!("switchboard returned an empty oauth_client_id"); + } + Ok(cfg.oauth_client_id) +} + fn extract_agent_id(tunnel_url: &str) -> Option { tunnel_url .rsplit_once("/tunnel/") @@ -111,6 +145,10 @@ pub struct CopilotReviewRequest { /// The endpoint updates this Check Run on completion. #[serde(default)] pub check_run_id: Option, + /// Issue-comment id when the review was triggered via `@goose-copilot review`. + /// goosed reacts on this comment when done. + #[serde(default)] + pub comment_id: Option, } #[derive(Debug, Serialize, ToSchema)] @@ -135,9 +173,17 @@ async fn review( ) -> Result, ErrorResponse> { let pr_label = format!("{} #{}", req.repo, req.pr_number); tokio::spawn(async move { - if let Err(e) = run_review(req).await { + let result = run_review(req.clone()).await; + if let Err(e) = &result { tracing::error!("[copilot] review {} failed: {:#}", pr_label, e); } + if let Some(id) = req.comment_id { + let reaction = if result.is_ok() { "+1" } else { "confused" }; + if let Err(e) = post_comment_reaction(&req.repo, id, reaction, &req.github_token).await + { + tracing::warn!("[copilot] review reaction failed: {:#}", e); + } + } }); Ok(Json(CopilotReviewResponse { accepted: true })) } @@ -471,6 +517,10 @@ pub struct CopilotCommentRequest { /// edits the agent makes back to the PR. #[serde(default)] pub head_ref: String, + /// Issue-comment id we're replying to. goosed reacts on this comment + /// (`+1` on success, `confused` on failure) when done. + #[serde(default)] + pub comment_id: Option, } #[utoipa::path( @@ -490,9 +540,17 @@ async fn comment( ) -> Result, ErrorResponse> { let pr_label = format!("{} #{}", req.repo, req.pr_number); tokio::spawn(async move { - if let Err(e) = run_comment_reply(req).await { + let result = run_comment_reply(req.clone()).await; + if let Err(e) = &result { tracing::error!("[copilot] comment {} failed: {:#}", pr_label, e); } + if let Some(id) = req.comment_id { + let reaction = if result.is_ok() { "+1" } else { "confused" }; + if let Err(e) = post_comment_reaction(&req.repo, id, reaction, &req.github_token).await + { + tracing::warn!("[copilot] comment reaction failed: {:#}", e); + } + } }); Ok(Json(CopilotReviewResponse { accepted: true })) } @@ -635,6 +693,27 @@ fn extract_final_assistant_text(stdout: &str) -> Result { Ok(text.trim().to_string()) } +/// React on an issue comment (`eyes`, `+1`, `-1`, `confused`, …). 200 means +/// the bot already had that reaction; 201 means new — both are success. +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"); + github_client() + .post(&url) + .header("Authorization", format!("token {github_token}")) + .json(&serde_json::json!({ "content": content })) + .send() + .await + .context("POST comment reaction")? + .error_for_status() + .context("POST comment reaction rejected")?; + Ok(()) +} + async fn post_pr_comment(req: &CopilotCommentRequest, reply: &str) -> Result<()> { let url = format!( "https://api.github.com/repos/{}/issues/{}/comments", @@ -756,6 +835,7 @@ mod tests { head_sha: "h".into(), pr_url: "u".into(), check_run_id: None, + comment_id: None, }; let findings = vec![Finding { severity: "high".into(), @@ -786,6 +866,7 @@ mod tests { head_sha: "h".into(), pr_url: "u".into(), check_run_id: None, + comment_id: None, }; let findings = vec![Finding { severity: "medium".into(), @@ -831,6 +912,7 @@ mod tests { head_sha: "h".into(), pr_url: "u".into(), check_run_id: None, + comment_id: None, }; let findings = vec![Finding { severity: "high".into(), diff --git a/crates/goose/src/config/signup_copilot/mod.rs b/crates/goose/src/config/signup_copilot/mod.rs index 41c477fd45e7..106de90e1644 100644 --- a/crates/goose/src/config/signup_copilot/mod.rs +++ b/crates/goose/src/config/signup_copilot/mod.rs @@ -13,13 +13,16 @@ const INSTALL_TIMEOUT: Duration = Duration::from_secs(600); #[derive(Debug, Deserialize)] pub struct InstallCallback { - pub installation_id: u64, pub oauth_code: String, } pub struct CopilotInstallFlow { state: String, server_shutdown_tx: Option>, + /// Public GitHub OAuth client ID. When set, the flow uses the + /// /login/oauth/authorize endpoint instead of /apps/.../installations/new, + /// which works whether the app is already installed for the user or not. + oauth_client_id: Option, } impl CopilotInstallFlow { @@ -32,10 +35,27 @@ impl CopilotInstallFlow { 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 install_url(&self) -> String { + // OAuth authorize URL: always redirects to redirect_uri with + // (code, state, installation_id) regardless of install state. + 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()) + ); + } + // Fallback: legacy install URL — only works on first install. format!( "https://github.com/apps/{}/installations/new?state={}", APP_SLUG, self.state diff --git a/crates/goose/src/config/signup_copilot/server.rs b/crates/goose/src/config/signup_copilot/server.rs index 443974afbd5e..9df465d03a52 100644 --- a/crates/goose/src/config/signup_copilot/server.rs +++ b/crates/goose/src/config/signup_copilot/server.rs @@ -17,10 +17,8 @@ static TEMPLATES_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/src/config/signup_ #[derive(Debug, Deserialize)] struct CallbackQuery { - installation_id: Option, code: Option, state: Option, - setup_action: Option, error: Option, } @@ -69,17 +67,6 @@ async fn handle_callback( ); } - let installation_id = match params.installation_id.and_then(|s| s.parse::().ok()) { - Some(id) => id, - None => { - return render( - &TEMPLATES_DIR, - "error.html", - StatusCode::BAD_REQUEST, - "missing installation_id", - ) - } - }; let code = match params.code { Some(c) => c, None => { @@ -100,21 +87,9 @@ async fn handle_callback( "state mismatch", ); } - if params.setup_action.as_deref() != Some("install") { - return render( - &TEMPLATES_DIR, - "error.html", - StatusCode::BAD_REQUEST, - "unexpected setup_action", - ); - } - let mut tx_guard = inner.tx.lock().await; if let Some(tx) = tx_guard.take() { - let _ = tx.send(InstallCallback { - installation_id, - oauth_code: code, - }); + let _ = tx.send(InstallCallback { oauth_code: code }); } render(&TEMPLATES_DIR, "success.html", StatusCode::OK, "") diff --git a/services/copilot-switchboard/src/index.ts b/services/copilot-switchboard/src/index.ts index 237930a00f6b..c06a81368ab3 100644 --- a/services/copilot-switchboard/src/index.ts +++ b/services/copilot-switchboard/src/index.ts @@ -42,6 +42,16 @@ export default { return handleRegisterRoute(request, env); } + // Public OAuth client ID for goosed to build the /login/oauth/authorize URL. + // The OAuth *secret* never leaves the Worker — only the client_id does, and + // GitHub treats client_ids as public values. + if (request.method === 'GET' && url.pathname === '/copilot/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 }); }, }; diff --git a/services/copilot-switchboard/src/lib/github.ts b/services/copilot-switchboard/src/lib/github.ts index 21a2873bf94b..3bb903f0ab3a 100644 --- a/services/copilot-switchboard/src/lib/github.ts +++ b/services/copilot-switchboard/src/lib/github.ts @@ -175,6 +175,26 @@ export async function postIssueComment( 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}`, diff --git a/services/copilot-switchboard/src/lib/handlers.ts b/services/copilot-switchboard/src/lib/handlers.ts index 9e82b59f83f0..45308042a585 100644 --- a/services/copilot-switchboard/src/lib/handlers.ts +++ b/services/copilot-switchboard/src/lib/handlers.ts @@ -7,9 +7,10 @@ import { generateAppJwt, getInstallationToken, getPullRequestHead, + postCommentReaction, postIssueComment, } from './github'; -import { exchangeCodeAndVerify } from './oauth'; +import { exchangeCodeAndResolve } from './oauth'; import { deleteInstall, loadInstall, saveInstall } from './registry'; import { runCommentViaTunnel, runReviewViaTunnel } from './tunnel'; import type { @@ -26,7 +27,6 @@ const REVIEW_TRIGGER_RE = /(^|\s)@goose-copilot\s+review\s*$/im; export async function handleRegister(req: RegisterRequest, env: Env): Promise { if ( !req || - typeof req.installation_id !== 'number' || typeof req.oauth_code !== 'string' || typeof req.agent_id !== 'string' || typeof req.tunnel_secret !== 'string' || @@ -38,28 +38,35 @@ export async function handleRegister(req: RegisterRequest, env: Env): Promise + console.warn( + `[comment] ${payload.repository.full_name} #${payload.issue.number}: :eyes: reaction failed: ${err}` + ) + ); + if (REVIEW_TRIGGER_RE.test(payload.comment.body)) { await triggerReview({ fullName: payload.repository.full_name, @@ -112,6 +132,7 @@ export async function handleIssueComment(payload: IssueCommentEvent, env: Env): installationId: payload.installation.id, env, token, + commentId: payload.comment.id, }); return; } @@ -124,6 +145,7 @@ export async function handleIssueComment(payload: IssueCommentEvent, env: Env): prUrl: pr.htmlUrl, commentBody: payload.comment.body, commenter: payload.comment.user.login, + commentId: payload.comment.id, installationId: payload.installation.id, env, token, @@ -138,6 +160,7 @@ async function triggerComment(opts: { prUrl: string; commentBody: string; commenter: string; + commentId: number; installationId: number; env: Env; token: string; @@ -169,6 +192,7 @@ async function triggerComment(opts: { prUrl: opts.prUrl, commentBody, commenter, + commentId: opts.commentId, }); if (!result.ok) { throw new Error(`tunnel responded ${result.status}: ${result.body.slice(0, 200)}`); @@ -203,6 +227,8 @@ async function triggerReview(opts: { env: Env; /** Reuse a freshly-minted token from the caller if we already have one. */ token?: string; + /** When the review was triggered via `@goose-copilot review`, goosed reacts on this comment when done. */ + commentId?: number; }): Promise { const { fullName, prNumber, headSha, prUrl, installationId, env } = opts; @@ -247,6 +273,7 @@ async function triggerReview(opts: { headSha, prUrl, checkRunId, + commentId: opts.commentId, }); if (!result.ok) { diff --git a/services/copilot-switchboard/src/lib/oauth.ts b/services/copilot-switchboard/src/lib/oauth.ts index b53f345ce04b..5cf906c35dee 100644 --- a/services/copilot-switchboard/src/lib/oauth.ts +++ b/services/copilot-switchboard/src/lib/oauth.ts @@ -1,5 +1,5 @@ -// Exchanges a GitHub App OAuth code for a user access token and verifies -// the user actually has access to the claimed installation_id. +// Exchanges a GitHub App OAuth code for a user access token and resolves +// which installation of *our* app the authenticated user owns. const UA = 'goose-copilot-switchboard/0.1'; @@ -11,15 +11,19 @@ interface OAuthTokenResponse { interface InstallationListResponse { total_count: number; - installations: Array<{ id: number }>; + installations: Array<{ id: number; app_id: number; account: { login: string } | null }>; } -export async function exchangeCodeAndVerify(opts: { +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; - installationId: number; -}): Promise<{ ok: true } | { ok: false; status: number; error: string }> { +}): Promise { const tokenRes = await fetch('https://github.com/login/oauth/access_token', { method: 'POST', headers: { @@ -63,13 +67,21 @@ export async function exchangeCodeAndVerify(opts: { }; } const installs = (await installRes.json()) as InstallationListResponse; - const owned = installs.installations.some((i) => i.id === opts.installationId); - if (!owned) { + const mine = installs.installations.filter((i) => i.app_id === opts.appId); + if (mine.length === 0) { return { ok: false, - status: 403, - error: 'authenticated user does not own the requested installation', + status: 409, + error: + 'Goose Copilot is not installed on any account this user can access. Install the GitHub App first.', }; } - return { ok: true }; + // Pick the first matching installation. Most users have exactly one + // (their personal account). Multi-org users will be revisited later. + const chosen = mine[0]; + return { + ok: true, + installationId: chosen.id, + accountLogin: chosen.account?.login ?? null, + }; } diff --git a/services/copilot-switchboard/src/lib/tunnel.ts b/services/copilot-switchboard/src/lib/tunnel.ts index 80753f09643d..0a595bf31d95 100644 --- a/services/copilot-switchboard/src/lib/tunnel.ts +++ b/services/copilot-switchboard/src/lib/tunnel.ts @@ -11,6 +11,8 @@ export interface TunnelRunParams { headSha: string; prUrl: string; checkRunId?: number; + /** Comment that triggered this review (when invoked via `@goose-copilot review`). */ + commentId?: number; } export interface TunnelCommentParams { @@ -22,6 +24,7 @@ export interface TunnelCommentParams { prUrl: string; commentBody: string; commenter: string; + commentId: number; } export interface TunnelRunResult { @@ -67,6 +70,7 @@ export async function runReviewViaTunnel( head_sha: params.headSha, pr_url: params.prUrl, check_run_id: params.checkRunId, + comment_id: params.commentId, }); } @@ -83,5 +87,6 @@ export async function runCommentViaTunnel( pr_url: params.prUrl, comment_body: params.commentBody, commenter: params.commenter, + comment_id: params.commentId, }); } diff --git a/services/copilot-switchboard/src/lib/types.ts b/services/copilot-switchboard/src/lib/types.ts index 48bb31470124..630ac2566aa1 100644 --- a/services/copilot-switchboard/src/lib/types.ts +++ b/services/copilot-switchboard/src/lib/types.ts @@ -21,7 +21,6 @@ export interface InstallRecord { } export interface RegisterRequest { - installation_id: number; oauth_code: string; agent_id: string; tunnel_secret: string; @@ -52,6 +51,7 @@ export interface PullRequestEvent { export interface IssueCommentEvent { action: 'created' | 'edited' | 'deleted'; comment: { + id: number; body: string; user: { login: string; type: 'User' | 'Bot' | 'Organization' }; }; diff --git a/ui/desktop/openapi.json b/ui/desktop/openapi.json index c00b28166406..f92d6da98b3a 100644 --- a/ui/desktop/openapi.json +++ b/ui/desktop/openapi.json @@ -4840,6 +4840,13 @@ "comment_body": { "type": "string" }, + "comment_id": { + "type": "integer", + "format": "int64", + "description": "Issue-comment id we're replying to. goosed reacts on this comment\n(`+1` on success, `confused` on failure) when done.", + "nullable": true, + "minimum": 0 + }, "commenter": { "type": "string" }, @@ -4880,6 +4887,13 @@ "nullable": true, "minimum": 0 }, + "comment_id": { + "type": "integer", + "format": "int64", + "description": "Issue-comment id when the review was triggered via `@goose-copilot review`.\ngoosed reacts on this comment when done.", + "nullable": true, + "minimum": 0 + }, "github_token": { "type": "string", "description": "Short-lived GitHub App installation token, scoped to the user's repos." diff --git a/ui/desktop/src/api/types.gen.ts b/ui/desktop/src/api/types.gen.ts index 292480d50e2e..fe64c4e48b4b 100644 --- a/ui/desktop/src/api/types.gen.ts +++ b/ui/desktop/src/api/types.gen.ts @@ -175,6 +175,11 @@ export type Conversation = Array; export type CopilotCommentRequest = { comment_body: string; + /** + * Issue-comment id we're replying to. goosed reacts on this comment + * (`+1` on success, `confused` on failure) when done. + */ + comment_id?: number | null; commenter: string; github_token: string; /** @@ -192,6 +197,11 @@ export type CopilotReviewRequest = { * The endpoint updates this Check Run on completion. */ check_run_id?: number | null; + /** + * Issue-comment id when the review was triggered via `@goose-copilot review`. + * goosed reacts on this comment when done. + */ + comment_id?: number | null; /** * Short-lived GitHub App installation token, scoped to the user's repos. */ diff --git a/ui/desktop/src/components/copilot/CopilotView.tsx b/ui/desktop/src/components/copilot/CopilotView.tsx index ac57befb3e8f..45007cacbb10 100644 --- a/ui/desktop/src/components/copilot/CopilotView.tsx +++ b/ui/desktop/src/components/copilot/CopilotView.tsx @@ -1,115 +1,80 @@ import { useCallback, useEffect, useState } from 'react'; -import { AlertCircle, Bot, CheckCircle2, ExternalLink, Loader2 } from 'lucide-react'; +import { + AlertCircle, + BarChart3, + ListChecks, + Plug, + Settings as SettingsIcon, +} from 'lucide-react'; import { MainPanelLayout } from '../Layout/MainPanelLayout'; -import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../ui/card'; +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 { errorMessage } from '../../utils/conversionUtils'; import { defineMessages, useIntl } from '../../i18n'; +import CopilotGeneral from './sections/CopilotGeneral'; +import CopilotCodeReview from './sections/CopilotCodeReview'; +import CopilotAnalytics from './sections/CopilotAnalytics'; +import CopilotConnectors from './sections/CopilotConnectors'; const STORAGE_KEY = 'goose-copilot: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: 'copilotView.pageTitle', defaultMessage: 'Goose Copilot', }, - pageDescription: { - id: 'copilotView.pageDescription', - defaultMessage: - 'Auto-review pull requests using your local goose. Your code and API keys never leave your machine.', - }, - cardTitle: { - id: 'copilotView.cardTitle', - defaultMessage: 'Code review on pull requests', + tabGeneral: { + id: 'copilotView.tabGeneral', + defaultMessage: 'General', }, - cardDescription: { - id: 'copilotView.cardDescription', - defaultMessage: - 'When enabled, every PR opened on a connected repository triggers a review on your local goose. The review is posted as inline comments on the PR.', - }, - statusLocalTunnel: { - id: 'copilotView.statusLocalTunnel', - defaultMessage: 'Local tunnel', - }, - statusGithubApp: { - id: 'copilotView.statusGithubApp', - defaultMessage: 'GitHub App', - }, - tunnelRunning: { - id: 'copilotView.tunnelRunning', - defaultMessage: 'Running', + tabCodeReview: { + id: 'copilotView.tabCodeReview', + defaultMessage: 'Code review', }, - tunnelStarting: { - id: 'copilotView.tunnelStarting', - defaultMessage: 'Starting…', + tabAnalytics: { + id: 'copilotView.tabAnalytics', + defaultMessage: 'Analytics', }, - tunnelError: { - id: 'copilotView.tunnelError', - defaultMessage: 'Error', + tabConnectors: { + id: 'copilotView.tabConnectors', + defaultMessage: 'Connectors', }, - tunnelIdle: { - id: 'copilotView.tunnelIdle', - defaultMessage: 'Idle', + notConnectedBannerTitle: { + id: 'copilotView.notConnectedBannerTitle', + defaultMessage: 'Goose Copilot is not connected yet', }, - installationLabel: { - id: 'copilotView.installationLabel', - defaultMessage: 'Installation {id}', - }, - notConnected: { - id: 'copilotView.notConnected', - defaultMessage: 'Not connected', - }, - awaitingInstall: { - id: 'copilotView.awaitingInstall', - defaultMessage: 'Finish installing on GitHub in your browser…', - }, - awaitingInstallHint: { - id: 'copilotView.awaitingInstallHint', + notConnectedBannerBody: { + id: 'copilotView.notConnectedBannerBody', defaultMessage: - 'A browser tab just opened to GitHub. Pick the repos you want reviewed and click Install & Authorize. This page will pick it up automatically.', - }, - installAction: { - id: 'copilotView.installAction', - defaultMessage: 'Connect GitHub', + 'Connect the GitHub App in the Connectors tab to start receiving automated PR reviews.', }, - activeMessage: { - id: 'copilotView.activeMessage', - defaultMessage: 'Goose Copilot is active. Open a PR to try it.', - }, - setupFailed: { - id: 'copilotView.setupFailed', - defaultMessage: 'Failed to connect Goose Copilot', - }, - disconnectAction: { - id: 'copilotView.disconnectAction', - defaultMessage: 'Disconnect', - }, - disconnectHint: { - id: 'copilotView.disconnectHint', - defaultMessage: - 'Opens the GitHub App settings so you can uninstall. After you uninstall on GitHub, this side disconnects automatically.', + notConnectedBannerCta: { + id: 'copilotView.notConnectedBannerCta', + defaultMessage: 'Go to Connectors', }, }); -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; - } -} - export default function CopilotView() { const intl = useIntl(); + const [activeTab, setActiveTab] = useState('general'); const [tunnelInfo, setTunnelInfo] = useState({ state: 'idle', url: '', @@ -117,8 +82,6 @@ export default function CopilotView() { secret: '', }); const [stored, setStored] = useState(loadStoredInstall); - const [busy, setBusy] = useState(false); - const [error, setError] = useState(null); const refreshTunnel = useCallback(async () => { try { @@ -133,156 +96,126 @@ export default function CopilotView() { refreshTunnel(); }, [refreshTunnel]); - const isEnabled = stored !== null && tunnelInfo.state === 'running'; + const handleInstallSaved = (record: StoredInstall) => { + localStorage.setItem(STORAGE_KEY, JSON.stringify(record)); + setStored(record); + refreshTunnel(); + }; - const handleDisconnect = () => { - if (!stored) return; - const url = `https://github.com/settings/installations/${stored.installationId}`; - window.electron.openExternal(url); + const handleInstallCleared = () => { localStorage.removeItem(STORAGE_KEY); setStored(null); }; - const handleConnect = async () => { - setError(null); - setBusy(true); - try { - const host = await window.electron.getGoosedHostPort(); - const secret = await window.electron.getSecretKey(); - if (!host) throw new Error('goosed is not running'); - - const res = await fetch(`${host}/copilot/setup`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'X-Secret-Key': secret, - }, - }); - if (!res.ok) { - const detail = await res.text(); - throw new Error(`${res.status}: ${detail}`); - } - const body = (await res.json()) as { installation_id: number }; - const record: StoredInstall = { - installationId: body.installation_id, - enabledAt: new Date().toISOString(), - }; - localStorage.setItem(STORAGE_KEY, JSON.stringify(record)); - setStored(record); - await refreshTunnel(); - } catch (err) { - setError(errorMessage(err, intl.formatMessage(i18n.setupFailed))); - } finally { - setBusy(false); - } - }; - - const tunnelStatusLabel = (): string => { - switch (tunnelInfo.state) { - case 'running': - return intl.formatMessage(i18n.tunnelRunning); - case 'starting': - return intl.formatMessage(i18n.tunnelStarting); - case 'error': - return intl.formatMessage(i18n.tunnelError); - default: - return intl.formatMessage(i18n.tunnelIdle); - } - }; + const isConnected = stored !== null && tunnelInfo.state === 'running'; return ( -
-
-
- -
-

{intl.formatMessage(i18n.pageTitle)}

-

- {intl.formatMessage(i18n.pageDescription)} -

+
+
+
+
+

{intl.formatMessage(i18n.pageTitle)}

+
- - - {intl.formatMessage(i18n.cardTitle)} - {intl.formatMessage(i18n.cardDescription)} - - - - - - {error && ( -
- {error} -
- )} - - {isEnabled ? ( -
-
-

- {intl.formatMessage(i18n.activeMessage)} -

- -
-

- {intl.formatMessage(i18n.disconnectHint)} +

+ {!isConnected && activeTab !== 'connectors' && ( + + + +
+

+ {intl.formatMessage(i18n.notConnectedBannerTitle)}

-
- ) : busy ? ( -
-
- - {intl.formatMessage(i18n.awaitingInstall)} -
-

- {intl.formatMessage(i18n.awaitingInstallHint)} +

+ {intl.formatMessage(i18n.notConnectedBannerBody)}

- ) : ( -
- -
- )} -
-
+ + + + )} + + +
+ + + + {intl.formatMessage(i18n.tabGeneral)} + + + + {intl.formatMessage(i18n.tabCodeReview)} + + + + {intl.formatMessage(i18n.tabAnalytics)} + + + + {intl.formatMessage(i18n.tabConnectors)} + + +
+ + + + + + + + + + + + + + + + + + +
); } - -function StatusRow({ label, ok, detail }: { label: string; ok: boolean; detail: string }) { - return ( -
- {label} - - {ok ? ( - - ) : ( - - )} - {detail} - -
- ); -} diff --git a/ui/desktop/src/components/copilot/sections/CopilotAnalytics.tsx b/ui/desktop/src/components/copilot/sections/CopilotAnalytics.tsx new file mode 100644 index 000000000000..5a9f2da241d2 --- /dev/null +++ b/ui/desktop/src/components/copilot/sections/CopilotAnalytics.tsx @@ -0,0 +1,113 @@ +import { BarChart3, Info } from 'lucide-react'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../../ui/card'; +import { defineMessages, useIntl } from '../../../i18n'; + +const i18n = defineMessages({ + comingSoonTitle: { + id: 'copilotAnalytics.comingSoonTitle', + defaultMessage: 'Analytics is wiring up', + }, + comingSoonBody: { + id: 'copilotAnalytics.comingSoonBody', + defaultMessage: + 'Goose Copilot does not record review metrics yet. These cards show the shape of what is coming — reviews delivered, issues found by severity, and reaction sentiment from PR authors.', + }, + issuesRaised: { + id: 'copilotAnalytics.issuesRaised', + defaultMessage: 'Issues raised', + }, + prsReviewed: { + id: 'copilotAnalytics.prsReviewed', + defaultMessage: 'PRs reviewed', + }, + commitsPushed: { + id: 'copilotAnalytics.commitsPushed', + defaultMessage: 'Commits pushed', + }, + issuesBySeverity: { + id: 'copilotAnalytics.issuesBySeverity', + defaultMessage: 'Issues found by severity', + }, + reactionSentiment: { + id: 'copilotAnalytics.reactionSentiment', + defaultMessage: 'Reviewer reactions', + }, + reactionSentimentDescription: { + id: 'copilotAnalytics.reactionSentimentDescription', + defaultMessage: '👍 / 👎 reactions left on Goose Copilot review comments.', + }, + noData: { + id: 'copilotAnalytics.noData', + defaultMessage: 'No data for this period', + }, +}); + +export default function CopilotAnalytics() { + const intl = useIntl(); + + return ( +
+ + + +
+

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

+

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

+
+
+
+ +
+ + + +
+ +
+ + + {intl.formatMessage(i18n.issuesBySeverity)} + + + + + + + + {intl.formatMessage(i18n.reactionSentiment)} + + {intl.formatMessage(i18n.reactionSentimentDescription)} + + + + + + +
+
+ ); +} + +function StatCard({ label, value }: { label: string; value: string }) { + return ( + + +

{label}

+

{value}

+
+
+ ); +} + +function EmptyChart({ label }: { label: string }) { + return ( +
+ + {label} +
+ ); +} diff --git a/ui/desktop/src/components/copilot/sections/CopilotCodeReview.tsx b/ui/desktop/src/components/copilot/sections/CopilotCodeReview.tsx new file mode 100644 index 000000000000..6593bacd39e6 --- /dev/null +++ b/ui/desktop/src/components/copilot/sections/CopilotCodeReview.tsx @@ -0,0 +1,148 @@ +import { useEffect, useState } from 'react'; +import { Info } from 'lucide-react'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../../ui/card'; +import { Switch } from '../../ui/switch'; +import { defineMessages, useIntl } from '../../../i18n'; + +const PREFS_STORAGE_KEY = 'goose-copilot:preferences'; + +interface CopilotPrefs { + autoReviewOnPrOpen: boolean; + allowCommitOnFix: boolean; + exhaustiveReview: boolean; +} + +const DEFAULT_PREFS: CopilotPrefs = { + autoReviewOnPrOpen: true, + allowCommitOnFix: false, + exhaustiveReview: false, +}; + +function loadPrefs(): CopilotPrefs { + const raw = localStorage.getItem(PREFS_STORAGE_KEY); + if (!raw) return DEFAULT_PREFS; + try { + return { ...DEFAULT_PREFS, ...(JSON.parse(raw) as Partial) }; + } catch { + return DEFAULT_PREFS; + } +} + +function savePrefs(prefs: CopilotPrefs) { + localStorage.setItem(PREFS_STORAGE_KEY, JSON.stringify(prefs)); +} + +const i18n = defineMessages({ + reviewTitle: { + id: 'copilotCodeReview.reviewTitle', + defaultMessage: 'Code review', + }, + reviewDescription: { + id: 'copilotCodeReview.reviewDescription', + defaultMessage: 'Configure when and how Goose Copilot reviews pull requests.', + }, + autoReviewLabel: { + id: 'copilotCodeReview.autoReviewLabel', + defaultMessage: 'Auto-review on PR open', + }, + autoReviewHelper: { + id: 'copilotCodeReview.autoReviewHelper', + defaultMessage: + 'Run a review automatically when a pull request is opened on a connected repo.', + }, + exhaustiveLabel: { + id: 'copilotCodeReview.exhaustiveLabel', + defaultMessage: 'Exhaustive review', + }, + exhaustiveHelper: { + id: 'copilotCodeReview.exhaustiveHelper', + defaultMessage: + 'Keep looking for additional findings until the model stops finding new issues. Uses more tokens.', + }, + allowCommitLabel: { + id: 'copilotCodeReview.allowCommitLabel', + defaultMessage: 'Let @goose-copilot push commits', + }, + allowCommitHelper: { + id: 'copilotCodeReview.allowCommitHelper', + defaultMessage: + 'When someone asks @goose-copilot to fix issues, push the resulting changes to the PR branch as goose-copilot[bot].', + }, + notWiredYet: { + id: 'copilotCodeReview.notWiredYet', + defaultMessage: + 'These preferences are stored locally — the bot still runs with permissive defaults. Backend wiring is in progress.', + }, +}); + +export default function CopilotCodeReview() { + const intl = useIntl(); + const [prefs, setPrefs] = useState(loadPrefs); + + useEffect(() => { + savePrefs(prefs); + }, [prefs]); + + const togglePref = (key: keyof CopilotPrefs) => (checked: boolean) => + setPrefs((p) => ({ ...p, [key]: checked })); + + return ( +
+ + + {intl.formatMessage(i18n.reviewTitle)} + {intl.formatMessage(i18n.reviewDescription)} + + + + + + +
+ + {intl.formatMessage(i18n.notWiredYet)} +
+
+
+
+ ); +} + +function PreferenceRow({ + label, + helper, + checked, + onCheckedChange, +}: { + label: string; + helper: string; + checked: boolean; + onCheckedChange: (checked: boolean) => void; +}) { + return ( +
+
+

{label}

+

{helper}

+
+
+ +
+
+ ); +} diff --git a/ui/desktop/src/components/copilot/sections/CopilotConnectors.tsx b/ui/desktop/src/components/copilot/sections/CopilotConnectors.tsx new file mode 100644 index 000000000000..61c6ae23d6ef --- /dev/null +++ b/ui/desktop/src/components/copilot/sections/CopilotConnectors.tsx @@ -0,0 +1,268 @@ +import { useState } from 'react'; +import { + AlertCircle, + CheckCircle2, + ExternalLink, + Github, + Loader2, + MessageSquare, + Plug, + Workflow, +} from 'lucide-react'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../../ui/card'; +import { Button } from '../../ui/button'; +import type { TunnelInfo } from '../../../api/types.gen'; +import { errorMessage } from '../../../utils/conversionUtils'; +import { defineMessages, useIntl } from '../../../i18n'; +import type { StoredInstall } from '../CopilotView'; + +const i18n = defineMessages({ + githubTitle: { + id: 'copilotConnectors.githubTitle', + defaultMessage: 'GitHub', + }, + githubDescription: { + id: 'copilotConnectors.githubDescription', + defaultMessage: 'Install the Goose Copilot GitHub App on the repos you want auto-reviewed.', + }, + installAction: { + id: 'copilotConnectors.installAction', + defaultMessage: 'Connect GitHub', + }, + disconnectAction: { + id: 'copilotConnectors.disconnectAction', + defaultMessage: 'Disconnect', + }, + manageAction: { + id: 'copilotConnectors.manageAction', + defaultMessage: 'Manage on GitHub', + }, + connectedLabel: { + id: 'copilotConnectors.connectedLabel', + defaultMessage: 'Connected — installation {id}', + }, + notConnected: { + id: 'copilotConnectors.notConnected', + defaultMessage: 'Not connected', + }, + awaitingInstall: { + id: 'copilotConnectors.awaitingInstall', + defaultMessage: 'Finish installing on GitHub in your browser…', + }, + awaitingInstallHint: { + id: 'copilotConnectors.awaitingInstallHint', + defaultMessage: + 'A browser tab just opened to GitHub. Pick the repos you want reviewed and click Install & Authorize.', + }, + setupFailed: { + id: 'copilotConnectors.setupFailed', + defaultMessage: 'Failed to connect Goose Copilot', + }, + disconnectHint: { + id: 'copilotConnectors.disconnectHint', + defaultMessage: + 'Opens the GitHub App settings so you can uninstall. After you uninstall on GitHub, this side disconnects automatically.', + }, + slackTitle: { + id: 'copilotConnectors.slackTitle', + defaultMessage: 'Slack', + }, + slackDescription: { + id: 'copilotConnectors.slackDescription', + defaultMessage: 'Ask @goose-copilot questions or trigger reviews from a Slack channel.', + }, + linearTitle: { + id: 'copilotConnectors.linearTitle', + defaultMessage: 'Linear', + }, + linearDescription: { + id: 'copilotConnectors.linearDescription', + defaultMessage: 'Mention @goose-copilot on issues and let it open PRs to address them.', + }, + comingSoon: { + id: 'copilotConnectors.comingSoon', + defaultMessage: 'Coming soon', + }, +}); + +interface Props { + tunnelInfo: TunnelInfo; + stored: StoredInstall | null; + onInstallSaved: (record: StoredInstall) => void; + onInstallCleared: () => void; + onRefreshTunnel: () => Promise; +} + +export default function CopilotConnectors({ + tunnelInfo, + stored, + onInstallSaved, + onInstallCleared, + onRefreshTunnel, +}: Props) { + const intl = useIntl(); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + const isConnected = stored !== null && tunnelInfo.state === 'running'; + + const handleConnect = async () => { + setError(null); + setBusy(true); + try { + const host = await window.electron.getGoosedHostPort(); + const secret = await window.electron.getSecretKey(); + if (!host) throw new Error('goosed is not running'); + + const res = await fetch(`${host}/copilot/setup`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Secret-Key': secret, + }, + }); + if (!res.ok) { + const detail = await res.text(); + throw new Error(`${res.status}: ${detail}`); + } + const body = (await res.json()) as { installation_id: number }; + onInstallSaved({ + installationId: body.installation_id, + enabledAt: new Date().toISOString(), + }); + await onRefreshTunnel(); + } catch (err) { + setError(errorMessage(err, intl.formatMessage(i18n.setupFailed))); + } finally { + setBusy(false); + } + }; + + const handleDisconnect = () => { + if (!stored) return; + window.electron.openExternal( + `https://github.com/settings/installations/${stored.installationId}` + ); + onInstallCleared(); + }; + + return ( +
+ + +
+ +
+ {intl.formatMessage(i18n.githubTitle)} + {intl.formatMessage(i18n.githubDescription)} +
+
+
+ +
+

+ {isConnected + ? intl.formatMessage(i18n.connectedLabel, { id: stored?.installationId ?? '' }) + : intl.formatMessage(i18n.notConnected)} +

+ {isConnected ? ( + + ) : ( + + )} +
+ + {error && ( +
+ {error} +
+ )} + + {isConnected ? ( +
+
+ + +
+

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

+
+ ) : busy ? ( +
+
+ + {intl.formatMessage(i18n.awaitingInstall)} +
+

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

+
+ ) : ( + + )} +
+
+ + } + title={intl.formatMessage(i18n.slackTitle)} + description={intl.formatMessage(i18n.slackDescription)} + comingSoon={intl.formatMessage(i18n.comingSoon)} + /> + } + title={intl.formatMessage(i18n.linearTitle)} + description={intl.formatMessage(i18n.linearDescription)} + comingSoon={intl.formatMessage(i18n.comingSoon)} + /> +
+ ); +} + +function ConnectorPlaceholder({ + title, + description, + comingSoon, + icon, +}: { + title: string; + description: string; + comingSoon: string; + icon?: React.ReactNode; +}) { + return ( + + +
+ {icon ?? } +
+ + {title} + + {comingSoon} + + + {description} +
+
+
+
+ ); +} diff --git a/ui/desktop/src/components/copilot/sections/CopilotGeneral.tsx b/ui/desktop/src/components/copilot/sections/CopilotGeneral.tsx new file mode 100644 index 000000000000..e1a64e1c8dfe --- /dev/null +++ b/ui/desktop/src/components/copilot/sections/CopilotGeneral.tsx @@ -0,0 +1,76 @@ +import { useEffect, useState } from 'react'; +import { Info } from 'lucide-react'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../../ui/card'; +import { defineMessages, useIntl } from '../../../i18n'; + +const INSTRUCTIONS_STORAGE_KEY = 'goose-copilot:custom-instructions'; + +const i18n = defineMessages({ + customInstructionsTitle: { + id: 'copilotGeneral.customInstructionsTitle', + defaultMessage: 'Custom instructions', + }, + customInstructionsDescription: { + id: 'copilotGeneral.customInstructionsDescription', + defaultMessage: + 'Free-form rules appended to every review prompt. Use them to nudge the bot toward what your team actually cares about.', + }, + customInstructionsPlaceholder: { + id: 'copilotGeneral.customInstructionsPlaceholder', + defaultMessage: + 'Example: Don\'t flag TODO comments. Be strict on missing tests. Treat any change under crates/goose/src/security/ as critical.', + }, + customInstructionsHelper: { + id: 'copilotGeneral.customInstructionsHelper', + defaultMessage: + 'These instructions are appended verbatim to the system prompt the review orchestrator sends to the model.', + }, + notWiredYet: { + id: 'copilotGeneral.notWiredYet', + defaultMessage: + 'Saved locally. Backend wiring to feed this into the review prompt is in progress.', + }, +}); + +export default function CopilotGeneral() { + const intl = useIntl(); + const [instructions, setInstructions] = useState( + () => localStorage.getItem(INSTRUCTIONS_STORAGE_KEY) ?? '' + ); + + useEffect(() => { + localStorage.setItem(INSTRUCTIONS_STORAGE_KEY, instructions); + }, [instructions]); + + return ( +
+ + + + {intl.formatMessage(i18n.customInstructionsTitle)} + + + {intl.formatMessage(i18n.customInstructionsDescription)} + + + +