diff --git a/crates/orbit-api/src/background.rs b/crates/orbit-api/src/background.rs index f54c8462..6b227072 100644 --- a/crates/orbit-api/src/background.rs +++ b/crates/orbit-api/src/background.rs @@ -43,7 +43,7 @@ pub fn spawn(state: AppState) -> Vec> { loop { ticker.tick().await; let tick = Tick::start(&output_state, "outputs"); - crate::handlers::outputs::deliver_pending(&output_state).await; + crate::output_delivery::deliver_pending(&output_state).await; tick.done(true); } })); @@ -90,7 +90,7 @@ pub fn spawn(state: AppState) -> Vec> { loop { ticker.tick().await; let tick = Tick::start(&launch_state, "launches"); - let ok = crate::handlers::worker_launches::refresh_active_launches(&launch_state).await; + let ok = crate::launches::refresh_active_launches(&launch_state).await; tick.done(ok); } })); @@ -111,7 +111,7 @@ pub fn spawn(state: AppState) -> Vec> { Ok(runs) => { after = runs.last().map(|run| run.id); for run in runs { - match crate::handlers::teams::advance(&team_state, run).await { + match crate::team_runs::advance(&team_state, run).await { Ok(_) => team_state.metrics.team_run_advanced(), Err(error) => { ok = false; @@ -127,7 +127,7 @@ pub fn spawn(state: AppState) -> Vec> { } } } - if let Err(error) = crate::handlers::teams::reconcile_team_outcomes(&team_state).await { + if let Err(error) = crate::team_runs::reconcile_team_outcomes(&team_state).await { ok = false; tracing::warn!(%error, "team outcome reconciliation failed"); } @@ -518,15 +518,20 @@ async fn fire_trigger_inner(state: &AppState, trigger: Trigger) -> anyhow::Resul // error and counts towards the trigger's consecutive-failure auto-disable. Harness // unavailability and the hourly quota skip this tick instead of failing the trigger. let identity_user = trigger.owner_user_id.or(agent.owner_user_id); - let identity = crate::preflight::background_access( + let verdict = crate::preflight::evaluate_background(&crate::preflight::BackgroundPreflight { state, - trigger.org_id, - &[trigger.owner_user_id, agent.owner_user_id], - ) + org_id: trigger.org_id, + owners: &[trigger.owner_user_id, agent.owner_user_id], + agent: &agent, + spec: &spec, + harness: harness_kind, + extra_connection_ids: &[], + team: None, + }) .await; - let access = match identity { - Ok(access) => access, - Err(error) => { + match verdict { + crate::preflight::BackgroundVerdict::Allowed => {} + crate::preflight::BackgroundVerdict::Denied(error) => { crate::preflight::audit_denied_run( state, trigger.org_id, @@ -539,42 +544,20 @@ async fn fire_trigger_inner(state: &AppState, trigger: Trigger) -> anyhow::Resul .await; anyhow::bail!("scheduled run refused: {}", error.message); } - }; - if let Some(access) = &access { - let preflight = crate::preflight::Preflight { - state, - org_id: trigger.org_id, - access, - agent: &agent, - spec: &spec, - harness: harness_kind, - extra_connection_ids: &[], - }; - if let Err(error) = preflight.authorize_access().await { - crate::preflight::audit_denied_run( - state, - trigger.org_id, - "trigger.fire_denied", - "trigger", - trigger.id, - &error, - identity_user, - ) - .await; - anyhow::bail!("scheduled run refused: {}", error.message); + crate::preflight::BackgroundVerdict::Delayed( + crate::preflight::DelayReason::HarnessUnavailable, + error, + ) => { + tracing::warn!(trigger_id = %trigger.id, error = %error.message, "scheduled trigger skipped: harness unavailable"); + return Ok(()); + } + crate::preflight::BackgroundVerdict::Delayed( + crate::preflight::DelayReason::HourlyQuota, + error, + ) => { + tracing::info!(trigger_id = %trigger.id, error = %error.message, "scheduled trigger skipped: hourly quota reached"); + return Ok(()); } - } - if let Err(error) = - crate::preflight::require_harness_available(state, trigger.org_id, harness_kind).await - { - tracing::warn!(trigger_id = %trigger.id, error = %error.message, "scheduled trigger skipped: harness unavailable"); - return Ok(()); - } - if let Err(error) = - crate::preflight::require_hourly_quota(state, trigger.org_id, agent.id, &spec).await - { - tracing::info!(trigger_id = %trigger.id, error = %error.message, "scheduled trigger skipped: hourly quota reached"); - return Ok(()); } let idempotency_key = format!("trigger:{}:{}", trigger.id, fired_at.timestamp_millis()); let execution = match state @@ -881,9 +864,7 @@ pub(crate) async fn report_ended_execution( let worker_terminated = code.is_some_and(|code| orbit_contracts::WorkerTerminationReason::parse(code).is_some()); if worker_terminated || matches!(code, Some("harness_unresponsive")) { - if let Err(error) = - crate::handlers::teams::fail_team_run_for_execution(state, execution).await - { + if let Err(error) = crate::team_runs::fail_team_run_for_execution(state, execution).await { tracing::warn!(%error, execution_id = %execution.id, "failed to fail team run for ended execution"); } } @@ -945,19 +926,14 @@ async fn reconcile_worker_tags(state: &AppState) -> anyhow::Result<()> { } } let old_image = launch.image.clone(); - match crate::handlers::worker_launches::stop_launch_internal(state, &auth, launch).await - { + match crate::launches::stop_launch_internal(state, &auth, launch).await { Ok(_) => {} Err(error) => { tracing::warn!(profile = %profile.name, %error, "could not stop old worker"); continue; } } - match crate::handlers::worker_launches::launch_profile_internal( - state, &auth, profile.id, None, - ) - .await - { + match crate::launches::launch_profile_internal(state, &auth, profile.id, None).await { Ok(new_launch) => { tracing::info!( profile = %profile.name, @@ -1200,68 +1176,48 @@ async fn advance_runtime( // Shared execution preflight (#140) for the runtime creator (falling back to the // agent owner). Lost access stops the runtime with a recorded error; an unavailable // harness or exhausted hourly quota delays the next tick. - let access = crate::preflight::background_access( + let verdict = crate::preflight::evaluate_background(&crate::preflight::BackgroundPreflight { state, - runtime.org_id, - &[runtime.created_by, agent.owner_user_id], - ) + org_id: runtime.org_id, + owners: &[runtime.created_by, agent.owner_user_id], + agent: &agent, + spec: &spec, + harness: harness_kind, + extra_connection_ids: &[], + team: None, + }) .await; - let denied = match &access { - Err(error) => Some(error.clone()), - Ok(Some(access)) => crate::preflight::Preflight { - state, - org_id: runtime.org_id, - access, - agent: &agent, - spec: &spec, - harness: harness_kind, - extra_connection_ids: &[], - } - .authorize_access() - .await - .err(), - Ok(None) => None, - }; - if let Some(error) = denied { - crate::preflight::audit_denied_run( - state, - runtime.org_id, - "runtime.run_denied", - "agent", - agent.id, - &error, - runtime.created_by.or(agent.owner_user_id), - ) - .await; - let _ = state - .store - .halt_agent_runtime(runtime.id, &format!("run refused: {}", error.message)) - .await; - return Ok(()); - } - let delayed = match crate::preflight::require_harness_available( - state, - runtime.org_id, - harness_kind, - ) - .await - { - Ok(()) => { - crate::preflight::require_hourly_quota(state, runtime.org_id, agent.id, &spec).await - } - Err(error) => Err(error), - }; - if let Err(error) = delayed { - let _ = state - .store - .advance_agent_runtime( - runtime.id, - Some(&format!("run delayed: {}", error.message)), - chrono::Utc::now() - + chrono::Duration::seconds(runtime.interval_seconds.max(30) as i64), + match verdict { + crate::preflight::BackgroundVerdict::Allowed => {} + crate::preflight::BackgroundVerdict::Denied(error) => { + crate::preflight::audit_denied_run( + state, + runtime.org_id, + "runtime.run_denied", + "agent", + agent.id, + &error, + runtime.created_by.or(agent.owner_user_id), ) .await; - return Ok(()); + let _ = state + .store + .halt_agent_runtime(runtime.id, &format!("run refused: {}", error.message)) + .await; + return Ok(()); + } + crate::preflight::BackgroundVerdict::Delayed(_, error) => { + let _ = state + .store + .advance_agent_runtime( + runtime.id, + Some(&format!("run delayed: {}", error.message)), + chrono::Utc::now() + + chrono::Duration::seconds(runtime.interval_seconds.max(30) as i64), + ) + .await; + return Ok(()); + } } let input = serde_json::json!({ "task": runtime.task, diff --git a/crates/orbit-api/src/dispatcher.rs b/crates/orbit-api/src/dispatcher.rs index 249f38f4..86f23b3e 100644 --- a/crates/orbit-api/src/dispatcher.rs +++ b/crates/orbit-api/src/dispatcher.rs @@ -13,8 +13,8 @@ use orbit_security::AuthContext; use orbit_store::team_queue::TeamQueueItem; use orbit_store::AgentTeam; -use crate::handlers::teams::parse_definition; use crate::state::AppState; +use crate::team_runs::parse_definition; use crate::work_sources::{self, WorkSourceDefinition}; pub async fn dispatch_tick(state: &AppState) -> anyhow::Result<()> { @@ -311,8 +311,8 @@ async fn start_queue_item( auth: &AuthContext, team: &AgentTeam, item: &TeamQueueItem, -) -> Result { - crate::handlers::team_queue::start_queue_item(state, auth, team, item).await +) -> Result { + crate::team_runs::start_queue_item(state, auth, team, item).await } struct WorkSourceConnection { diff --git a/crates/orbit-api/src/handlers/export.rs b/crates/orbit-api/src/handlers/export.rs index 1f2dfbb4..cb1fb26e 100644 --- a/crates/orbit-api/src/handlers/export.rs +++ b/crates/orbit-api/src/handlers/export.rs @@ -329,7 +329,7 @@ pub(crate) async fn build_document( } PortableKind::AgentTeam => { let team = store.get_agent_team(org_id, id).await?; - let definition = super::teams::parse_definition(&team)?; + let definition = crate::team_runs::parse_definition(&team)?; let worker_profile = match definition.worker_profile_id { Some(profile_id) => names .worker_profile(profile_id) diff --git a/crates/orbit-api/src/handlers/import_portable.rs b/crates/orbit-api/src/handlers/import_portable.rs index 807aa80e..019058c4 100644 --- a/crates/orbit-api/src/handlers/import_portable.rs +++ b/crates/orbit-api/src/handlers/import_portable.rs @@ -46,10 +46,11 @@ use crate::dto::{ use crate::error::ApiError; use crate::extract::ApiJson; use crate::handlers::skills::{CreateSkillRequest, UpdateSkillRequest}; -use crate::handlers::teams::{CreateTeamRequest, TeamModelOverride, TeamStepInput}; +use crate::handlers::teams::{CreateTeamRequest, TeamStepInput}; use crate::handlers::tool_policies::ToolPolicyRequest; use crate::handlers::worker_profiles::CreateWorkerProfileRequest; use crate::state::AppState; +use crate::team_runs::TeamModelOverride; use crate::work_sources::{RepositorySpec, WorkSourceDefinition}; #[derive(Debug, Clone, Deserialize, utoipa::IntoParams)] diff --git a/crates/orbit-api/src/handlers/outputs.rs b/crates/orbit-api/src/handlers/outputs.rs index 8c36b0ce..073d18b8 100644 --- a/crates/orbit-api/src/handlers/outputs.rs +++ b/crates/orbit-api/src/handlers/outputs.rs @@ -7,25 +7,16 @@ use axum::Json; use serde::{Deserialize, Serialize}; use uuid::Uuid; -use orbit_contracts::{ - redact_secret, telegram_error, telegram_message_parts, OutputEvent, OutputKind, TelegramTarget, -}; +use orbit_contracts::{OutputEvent, OutputKind, TelegramTarget}; use orbit_domain::ValidationIssue; -use orbit_security::{new_secret_ref, AuthContext, OutboundPolicy, Permission, SecretValue}; -use orbit_store::outputs::DeliveryOutcome; -use orbit_store::{ - ExecutionRecord, Output, OutputDelivery, OutputDeliveryJob, Store, StoreError, TeamRun, -}; +use orbit_security::{new_secret_ref, AuthContext, Permission, SecretValue}; +use orbit_store::{Output, OutputDelivery}; use crate::audit; use crate::error::ApiError; +use crate::output_delivery::{deliver, guard_credential, redact_urls, with_note}; use crate::state::AppState; -/// Default Bot API host. Override with `ORBIT_TELEGRAM_API_BASE_URL` only for an explicit -/// admin-controlled proxy or test server; the override is still passed through the outbound -/// URL guard on every request. -const TELEGRAM_API_BASE_URL: &str = "https://api.telegram.org"; - #[derive(Debug, Clone, Deserialize, utoipa::ToSchema)] #[serde(rename_all = "camelCase")] pub struct OutputRequest { @@ -139,28 +130,6 @@ impl OutputDeliveryView { } } -/// Replace every http(s) URL in an error with ``. Send errors already drop the -/// webhook URL; this also covers rows recorded before that, since the URL is a secret. -fn redact_urls(text: &str) -> String { - let mut out = String::with_capacity(text.len()); - let mut rest = text; - while let Some(start) = ["http://", "https://"] - .iter() - .filter_map(|scheme| rest.find(scheme)) - .min() - { - out.push_str(&rest[..start]); - let tail = &rest[start..]; - let end = tail - .find(|c: char| c.is_whitespace() || matches!(c, ')' | '"' | '\'' | '>' | ',')) - .unwrap_or(tail.len()); - out.push_str(""); - rest = &tail[end..]; - } - out.push_str(rest); - out -} - impl From for OutputView { fn from(output: Output) -> Self { Self { @@ -202,39 +171,6 @@ fn credential(body: &OutputRequest, kind: OutputKind) -> Option<&str> { .filter(|value| !value.is_empty()) } -async fn guard_credential(kind: OutputKind, value: &str) -> Result<(), ApiError> { - match kind { - OutputKind::Telegram => { - // Telegram tokens are `:`; rejecting URL metacharacters here - // prevents the token from altering the assembled Bot API request path. - let mut parts = value.split(':'); - let id = parts.next().unwrap_or_default(); - let secret = parts.next().unwrap_or_default(); - let valid = !id.is_empty() - && id.bytes().all(|byte| byte.is_ascii_digit()) - && !secret.is_empty() - && secret - .bytes() - .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-') - && parts.next().is_none(); - if !valid { - return Err(ApiError::validation(vec![ValidationIssue::new( - "botToken", - "botToken must be a Telegram bot token (numeric id:secret)", - )])); - } - Ok(()) - } - OutputKind::S3 => { - orbit_s3::S3Credentials::from_secret(value).map_err(|message| { - ApiError::validation(vec![ValidationIssue::new("s3Credential", message)]) - })?; - Ok(()) - } - _ => guard_webhook_url(value).await, - } -} - async fn store_credential( state: &AppState, org_id: Uuid, @@ -699,571 +635,3 @@ pub async fn test_output( deliver(&state, &output, &text, None, None).await?; Ok(StatusCode::NO_CONTENT) } - -/// Why a delivery attempt failed, and whether retrying can help. -#[derive(Debug)] -pub struct SendError { - pub status: Option, - pub message: String, - pub retryable: bool, -} - -/// HTTP statuses worth retrying: server errors, timeouts and rate limits. Other 4xx -/// (bad URL, revoked webhook, rejected payload) will not succeed on retry. -fn status_is_retryable(status: u16) -> bool { - status >= 500 || status == 408 || status == 429 -} - -/// Delivery used by the test endpoint. -pub async fn deliver( - state: &AppState, - output: &Output, - text: &str, - execution: Option<&ExecutionRecord>, - team_run: Option<&TeamRun>, -) -> Result<(), ApiError> { - send(state, output, text, execution, team_run, None, None) - .await - .map_err(|error| { - ApiError::new( - StatusCode::BAD_GATEWAY, - "output_delivery_failed", - error.message, - ) - }) -} - -/// POST one notification. When `delivery_id` is set it is sent as `Idempotency-Key` and -/// `X-Orbit-Delivery-Id` (and `deliveryId` in generic webhook bodies) so receivers can -/// de-duplicate the at-least-once delivery. Telegram/Slack/Mattermost ignore the headers. -pub async fn send( - state: &AppState, - output: &Output, - text: &str, - execution: Option<&ExecutionRecord>, - team_run: Option<&TeamRun>, - delivery_id: Option, - progress: Option>, -) -> Result<(), SendError> { - let kind = OutputKind::parse(&output.kind).ok_or_else(|| SendError { - status: None, - message: format!("unsupported output kind '{}'", output.kind), - retryable: false, - })?; - let secret = match state.store.get_secret_value(&output.secret_ref).await { - Ok(Some(value)) => value.expose().to_string(), - Ok(None) => { - return Err(SendError { - status: None, - message: "output credential is missing".into(), - retryable: false, - }) - } - Err(error) => { - return Err(SendError { - status: None, - message: error.to_string(), - retryable: true, - }) - } - }; - if kind == OutputKind::S3 { - let (config, credentials) = orbit_s3::S3Config::for_output(&output.config, Some(&secret)) - .map_err(|message| SendError { - status: None, - message, - retryable: false, - })?; - let client = orbit_s3::S3Client::new(config, credentials).map_err(|message| SendError { - status: None, - message, - retryable: false, - })?; - let key = format!( - "{}{}.txt", - client.config().key_prefix, - delivery_id.unwrap_or_else(Uuid::now_v7) - ); - client - .put_object(None, &key, text.as_bytes(), "text/plain; charset=utf-8") - .await - .map_err(|error| SendError { - status: error.status, - message: error.message, - retryable: error.retryable, - })?; - return Ok(()); - } - if kind == OutputKind::Telegram { - let target = TelegramTarget::parse( - output.telegram_chat_id.as_deref().unwrap_or(""), - output.telegram_message_thread_id.as_deref(), - ) - .map_err(|message| SendError { - status: None, - message: message.to_string(), - retryable: false, - })?; - return send_telegram_with_progress( - &TelegramEndpoint::from_env(), - &secret, - &target, - text, - delivery_id, - progress, - ) - .await; - } - guard_webhook_url(&secret) - .await - .map_err(|error| SendError { - status: None, - message: error.message, - retryable: false, - })?; - let client = orbit_security::guarded_client(std::time::Duration::from_secs(15)); - let payload = if kind == OutputKind::Webhook { - serde_json::json!({ - "event": execution - .map(|e| format!("execution.{}", e.status)) - .or_else(|| team_run.map(|run| format!("team_run.{}", run.status))) - .unwrap_or_else(|| "test".into()), - "deliveryId": delivery_id, - "text": text, - "execution": execution.map(|e| serde_json::json!({ - "id": e.id, "agentName": e.agent_name, "status": e.status, - "output": e.output, "error": e.error, - })), - "teamRun": team_run.map(|run| serde_json::json!({ - "id": run.id, "teamId": run.team_id, "status": run.status, - "output": run.output, "error": run.error, - })), - }) - } else { - serde_json::json!({ "text": text }) - }; - let mut request = client.post(&secret).json(&payload); - if let Some(id) = delivery_id { - request = request - .header("Idempotency-Key", id.to_string()) - .header("X-Orbit-Delivery-Id", id.to_string()); - } - let response = request.send().await.map_err(|error| SendError { - status: None, - // reqwest errors embed the (secret) webhook URL; strip it. - message: error.without_url().to_string(), - retryable: true, - })?; - let status = response.status(); - if !status.is_success() { - return Err(SendError { - status: Some(status.as_u16()), - message: format!("webhook returned HTTP {status}"), - retryable: status_is_retryable(status.as_u16()), - }); - } - Ok(()) -} - -/// Operator-controlled Telegram endpoint. The base URL defaults to the official Bot API; -/// an admin may set `ORBIT_TELEGRAM_API_BASE_URL` (for a proxy or mock server), but the -/// fully assembled URL is always checked against the outbound policy before any request. -#[derive(Debug, Clone)] -pub struct TelegramEndpoint { - pub base_url: String, - policy: OutboundPolicy, -} - -impl TelegramEndpoint { - pub fn from_env() -> Self { - let base_url = std::env::var("ORBIT_TELEGRAM_API_BASE_URL") - .ok() - .map(|value| value.trim().to_string()) - .filter(|value| !value.is_empty()) - .unwrap_or_else(|| TELEGRAM_API_BASE_URL.to_string()); - Self::new(base_url, OutboundPolicy::from_env()) - } - - pub fn new(base_url: impl Into, policy: OutboundPolicy) -> Self { - Self { - base_url: base_url.into().trim_end_matches('/').to_string(), - policy, - } - } -} - -/// Resume state for a claimed multi-part Telegram delivery. `store` is `None` for direct -/// sends (tests and the test endpoint), which then always start at part zero. -#[derive(Clone, Copy)] -pub struct TelegramProgress<'a> { - pub store: Option<&'a Store>, - pub delivery_id: Uuid, - pub claim_token: Uuid, - pub parts_sent: i32, -} - -/// Send one Telegram notification, splitting long text into multiple `sendMessage` calls. -/// The bot token is only ever used in the request URL, never in errors or diagnostics. -pub async fn send_telegram( - endpoint: &TelegramEndpoint, - bot_token: &str, - target: &TelegramTarget, - text: &str, - delivery_id: Option, -) -> Result<(), SendError> { - send_telegram_with_progress(endpoint, bot_token, target, text, delivery_id, None).await -} - -/// Send a Telegram notification, resuming after the parts already accepted on a previous -/// attempt and durably counting each newly accepted part as it goes. -pub async fn send_telegram_with_progress( - endpoint: &TelegramEndpoint, - bot_token: &str, - target: &TelegramTarget, - text: &str, - delivery_id: Option, - progress: Option>, -) -> Result<(), SendError> { - let url = format!("{}/bot{}/sendMessage", endpoint.base_url, bot_token); - orbit_security::check_outbound_url(&url, &endpoint.policy) - .await - .map_err(|error| SendError { - status: None, - message: format!( - "telegram endpoint refused by outbound policy ({})", - error.category() - ), - retryable: false, - })?; - let client = orbit_security::guarded_client_with_policy( - std::time::Duration::from_secs(15), - endpoint.policy.clone(), - ); - let parts = telegram_message_parts(text, delivery_id); - let resume_after = progress - .as_ref() - .map_or(0, |progress| progress.parts_sent.max(0) as usize); - for (index, part) in parts.iter().enumerate() { - if index < resume_after { - continue; - } - let mut payload = serde_json::json!({ - "chat_id": target.chat_id, - "text": part, - "disable_web_page_preview": true, - }); - if let Some(thread_id) = &target.message_thread_id { - payload["message_thread_id"] = serde_json::Value::String(thread_id.clone()); - } - let mut request = client.post(&url).json(&payload); - if let Some(id) = delivery_id { - request = request - .header("Idempotency-Key", format!("{id}-{index}")) - .header("X-Orbit-Delivery-Id", id.to_string()); - } - let response = request.send().await.map_err(|error| SendError { - status: None, - message: redact_secret(&orbit_security::describe_request_error(&error), bot_token), - retryable: true, - })?; - let status = response.status(); - if !status.is_success() { - let body = response.text().await.unwrap_or_default(); - let description = serde_json::from_str::(&body) - .ok() - .and_then(|value| { - value - .get("description") - .and_then(|description| description.as_str()) - .map(str::to_string) - }); - let mapped = telegram_error(status.as_u16(), description.as_deref(), bot_token); - return Err(SendError { - status: Some(status.as_u16()), - message: mapped.message, - retryable: mapped.retryable, - }); - } - if let Some(progress) = &progress { - let Some(store) = progress.store else { - continue; - }; - match store - .record_output_delivery_part(progress.delivery_id, progress.claim_token) - .await - { - Ok(true) => {} - Ok(false) => { - return Err(SendError { - status: None, - message: "delivery claim lost while sending Telegram part".into(), - retryable: false, - }) - } - Err(error) => { - return Err(SendError { - status: None, - message: format!("could not record Telegram part: {error}"), - retryable: true, - }) - } - } - } - } - Ok(()) -} - -const DELIVERY_LEASE: chrono::Duration = chrono::Duration::seconds(120); -const MAX_DELIVERIES_PER_TICK: usize = 25; - -/// Background outbox loop: enqueue finished runs, then claim and deliver due rows. -/// -/// Safe to run on every replica and concurrently: rows are claimed one at a time with a -/// lease (`FOR UPDATE SKIP LOCKED`), so each delivery is sent by one worker at a time and a -/// crashed sender's rows are reclaimed after the lease expires (at-least-once). -pub async fn deliver_pending(state: &AppState) { - if let Err(error) = state.store.enqueue_output_deliveries().await { - tracing::error!(%error, "output delivery enqueue failed"); - } - if let Err(error) = state.store.enqueue_team_output_deliveries().await { - tracing::error!(%error, "team output delivery enqueue failed"); - } - for _ in 0..MAX_DELIVERIES_PER_TICK { - let job = match state.store.claim_output_deliveries(1, DELIVERY_LEASE).await { - Ok(mut jobs) => match jobs.pop() { - Some(job) => job, - None => break, - }, - Err(error) => { - tracing::error!(%error, "output delivery claim failed"); - break; - } - }; - process_delivery(state, job).await; - } -} - -async fn process_delivery(state: &AppState, job: OutputDeliveryJob) { - let (outcome, status, error) = attempt_delivery(state, &job).await; - match state - .store - .finish_output_delivery( - job.id, - job.claim_token, - outcome, - status, - error.as_deref(), - job.attempts, - ) - .await - { - Ok(true) => {} - Ok(false) => { - tracing::warn!(delivery_id = %job.id, "output delivery claim lost before finish"); - } - Err(error) => { - // The lease will expire and the row is reclaimed. - tracing::error!(delivery_id = %job.id, %error, "recording output delivery result failed"); - } - } -} - -type AttemptResult = (DeliveryOutcome, Option, Option); - -async fn attempt_delivery(state: &AppState, job: &OutputDeliveryJob) -> AttemptResult { - let skipped = |reason: &str| (DeliveryOutcome::Skipped, None, Some(reason.to_string())); - let retry = |error: StoreError| (DeliveryOutcome::Retry, None, Some(error.to_string())); - let output = match state.store.get_output(job.org_id, job.output_id).await { - Ok(output) if output.enabled => output, - Ok(_) => return skipped("output is disabled"), - Err(StoreError::NotFound(_)) => return skipped("output was deleted"), - Err(error) => return retry(error), - }; - let execution = match job.execution_id { - Some(id) => match state.store.get_execution_by_id_any_org(id).await { - Ok(execution) => Some(execution), - Err(StoreError::NotFound(_)) => return skipped("execution was deleted"), - Err(error) => return retry(error), - }, - None => None, - }; - let team_run = match job.team_run_id { - Some(id) => match state.store.get_team_run_any_org(id).await { - Ok(run) => Some(run), - Err(StoreError::NotFound(_)) => return skipped("team run was deleted"), - Err(error) => return retry(error), - }, - None => None, - }; - let text = execution - .as_ref() - .map(summary) - .or_else(|| team_run.as_ref().map(team_summary)) - .unwrap_or_else(|| "ORBIT run finished".into()); - let text = with_note(text, output.template.as_deref()); - let progress = TelegramProgress { - store: Some(&state.store), - delivery_id: job.id, - claim_token: job.claim_token, - parts_sent: job.parts_sent, - }; - match send( - state, - &output, - &text, - execution.as_ref(), - team_run.as_ref(), - Some(job.id), - Some(progress), - ) - .await - { - Ok(()) => (DeliveryOutcome::Succeeded, None, None), - Err(error) => { - let outcome = if error.retryable { - DeliveryOutcome::Retry - } else { - DeliveryOutcome::Failed - }; - (outcome, error.status.map(i32::from), Some(error.message)) - } - } -} - -/// Append the output's note (stored as `template`) after the run summary, as the UI -/// promises. A blank note adds nothing. -fn with_note(text: String, note: Option<&str>) -> String { - match note.map(str::trim).filter(|note| !note.is_empty()) { - Some(note) => format!("{text}\n\n{note}"), - None => text, - } -} - -fn team_summary(run: &TeamRun) -> String { - let output = run - .output - .as_ref() - .map(|value| { - value - .get("text") - .or_else(|| value.get("summary")) - .and_then(|v| v.as_str()) - .map(str::to_string) - .unwrap_or_else(|| value.to_string()) - }) - .or_else(|| run.error.clone()) - .unwrap_or_else(|| "completed".into()); - let output: String = output.chars().take(3000).collect(); - format!( - "Agent team run {} — {}\n{}", - run.status, - run.input - .get("task") - .and_then(|v| v.as_str()) - .unwrap_or("task"), - output - ) -} - -fn summary(execution: &ExecutionRecord) -> String { - let output = execution - .output - .as_ref() - .map(|value| { - value - .get("text") - .or_else(|| value.get("summary")) - .and_then(|v| v.as_str()) - .map(str::to_string) - .unwrap_or_else(|| value.to_string()) - }) - .or_else(|| execution.error.as_ref().map(|error| error.to_string())) - .unwrap_or_else(|| "completed".into()); - let output: String = output.chars().take(3000).collect(); - format!( - "{} {} — {}\n{}", - execution.agent_name, - execution.status, - execution - .input - .get("task") - .and_then(|v| v.as_str()) - .unwrap_or("task"), - output - ) -} - -/// Refuse webhook targets in loopback, link-local/metadata or other blocked ranges -/// (see `ORBIT_OUTBOUND_*`). Private ranges are allowed by default. -async fn guard_webhook_url(url: &str) -> Result<(), ApiError> { - orbit_security::check_outbound_url(url, &orbit_security::OutboundPolicy::from_env()) - .await - .map_err(|error| { - ApiError::validation(vec![ValidationIssue::new("webhookUrl", error.to_string())]) - }) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn note_is_appended_after_the_summary() { - assert_eq!( - with_note( - "Agent succeeded — task\nDone".into(), - Some(" Ping #release ") - ), - "Agent succeeded — task\nDone\n\nPing #release" - ); - } - - #[test] - fn urls_are_redacted_from_errors() { - assert_eq!( - super::redact_urls( - "error sending request for url (https://hooks.slack.com/services/T/B/secret): timed out" - ), - "error sending request for url (): timed out" - ); - assert_eq!( - super::redact_urls("a http://x/1 and https://y/2"), - "a and " - ); - assert_eq!( - super::redact_urls("webhook returned HTTP 404"), - "webhook returned HTTP 404" - ); - } - - #[test] - fn blank_note_adds_nothing() { - assert_eq!(with_note("summary".into(), None), "summary"); - assert_eq!(with_note("summary".into(), Some(" ")), "summary"); - } - - #[test] - fn telegram_endpoint_defaults_to_the_official_host() { - let endpoint = TelegramEndpoint::new("https://proxy.example/", OutboundPolicy::default()); - assert_eq!(endpoint.base_url, "https://proxy.example"); - } - - #[tokio::test] - async fn telegram_tokens_cannot_alter_the_request_path() { - assert!(guard_credential(OutputKind::Telegram, "123456:ABC_def-1") - .await - .is_ok()); - for token in [ - "123:abc/../../evil", - "123:abc?x=1", - "abc:secret", - "123:", - ":secret", - ] { - assert!( - guard_credential(OutputKind::Telegram, token).await.is_err(), - "{token} must be rejected" - ); - } - } -} diff --git a/crates/orbit-api/src/handlers/team_queue.rs b/crates/orbit-api/src/handlers/team_queue.rs index 36d9da85..136cc660 100644 --- a/crates/orbit-api/src/handlers/team_queue.rs +++ b/crates/orbit-api/src/handlers/team_queue.rs @@ -10,10 +10,10 @@ use uuid::Uuid; use orbit_domain::ValidationIssue; use orbit_security::{AuthContext, Permission}; use orbit_store::team_queue::TeamQueueItem; -use orbit_store::AgentTeam; use crate::error::ApiError; use crate::state::AppState; +use crate::team_runs::{effective_payload, start_queue_item}; #[derive(Debug, Clone, Deserialize, utoipa::ToSchema)] #[serde(rename_all = "camelCase")] @@ -61,7 +61,7 @@ pub async fn enqueue( ) -> Result<(StatusCode, Json>), ApiError> { auth.require(Permission::ExecutionsCreate)?; let team = crate::handlers::teams::require_team_use(&state, &auth, team_id).await?; - let definition = crate::handlers::teams::parse_definition(&team)?; + let definition = crate::team_runs::parse_definition(&team)?; if body.items.is_empty() || body.items.len() > MAX_ENQUEUE_ITEMS { return Err(ApiError::validation(vec![ValidationIssue::new( "items", @@ -78,7 +78,7 @@ pub async fn enqueue( } // The run uses the team's connection credentials, so an item may only target the // team's configured repositories, the same rule as `create_run` (#384). - crate::handlers::teams::validate_queue_repositories( + crate::team_runs::validate_queue_repositories( &definition, &effective_payload(&item.payload, item.repository.as_deref()), false, @@ -165,12 +165,12 @@ pub async fn list( )) } -#[utoipa::path(post, path = "/api/v1/agent-teams/{team_id}/queue/{item_id}/run", tag = "agent-teams", responses((status = 201, body = crate::handlers::teams::TeamRunDetail)))] +#[utoipa::path(post, path = "/api/v1/agent-teams/{team_id}/queue/{item_id}/run", tag = "agent-teams", responses((status = 201, body = crate::team_runs::TeamRunDetail)))] pub async fn run_item( State(state): State, Extension(auth): Extension, Path((team_id, item_id)): Path<(Uuid, Uuid)>, -) -> Result<(StatusCode, Json), ApiError> { +) -> Result<(StatusCode, Json), ApiError> { auth.require(Permission::ExecutionsCreate)?; // The limit is checked atomically in start_step, which also serves dispatcher auto-run. let team = crate::handlers::teams::require_team_use(&state, &auth, team_id).await?; @@ -196,202 +196,6 @@ pub async fn run_item( Ok((StatusCode::CREATED, Json(detail))) } -/// Claim a queue item, then create and start its TeamRun. -/// -/// The claim (`pending|failed -> running`) is a single conditional UPDATE, so concurrent -/// callers (double click, manual run vs auto-run, two replicas) cannot both start a run. -/// Anything that fails after the claim cancels the run it created (and its queued -/// execution) and puts the item back into `failed`, which is retryable. -pub(crate) async fn start_queue_item( - state: &AppState, - auth: &AuthContext, - team: &AgentTeam, - item: &TeamQueueItem, -) -> Result { - let definition = crate::handlers::teams::parse_definition(team)?; - let Some(item) = state - .store - .claim_team_queue_item(auth.org_id, item.id) - .await? - else { - return Err(ApiError::conflict( - "queue item is not startable (already running, succeeded or cancelled)", - )); - }; - let task = item - .payload - .get("task") - .and_then(|value| value.as_str()) - .map(str::to_string) - .unwrap_or_else(|| definition.instructions.clone()); - let mut payload = item.payload.clone(); - if !payload.is_object() { - payload = serde_json::json!({}); - } - if let Some(repository) = &item.repository { - payload["repository"] = serde_json::json!(repository); - } - if payload - .get("repository") - .and_then(|value| value.as_str()) - .filter(|value| !value.trim().is_empty()) - .is_none() - { - if let Some(repository) = &definition.repository { - payload["repository"] = serde_json::json!(repository); - } - } - if !definition.repositories.is_empty() && payload.get("repositories").is_none() { - payload["repositories"] = serde_json::json!(definition.repositories); - } - // Items stored before enqueue validated their repository (#384), or written by hand, - // are checked again before the team's credentials are used for them. - if let Err(error) = - crate::handlers::teams::validate_queue_repositories(&definition, &payload, true) - { - release_failed_claim(state, auth, &item, None, &error.message).await; - return Err(error); - } - let input = serde_json::json!({ - "task": task, - "instructions": definition.instructions, - "payload": payload, - "definition": definition, - "autoApprove": false, - "queueItemId": item.id, - "externalKey": item.external_key, - }); - // Shared execution preflight (#140) before any run row is created. A refusal ends the - // claim with the reason instead of leaving the item `running` without a run (#383). - let authorized = async { - let access = crate::access::AccessScope::load(state, auth).await?; - let step_agent_ids: Vec = definition.steps.iter().map(|step| step.agent_id).collect(); - crate::preflight::authorize_team_run( - state, - auth.org_id, - &access, - team, - &step_agent_ids, - &crate::handlers::teams::team_connection_ids(&definition), - ) - .await - } - .await; - if let Err(error) = authorized { - release_failed_claim(state, auth, &item, None, &error.message).await; - return Err(error); - } - let run = match state - .store - .create_team_run(auth.org_id, team.id, &input, Some(auth.user_id)) - .await - { - Ok(run) => run, - Err(error) => { - let error = ApiError::from(error); - release_failed_claim(state, auth, &item, None, &error.message).await; - return Err(error); - } - }; - match start_claimed_run(state, auth, &item, &run, &definition).await { - Ok(steps) => Ok(crate::handlers::teams::TeamRunDetail { run, steps }), - Err(error) => { - release_failed_claim(state, auth, &item, Some(&run), &error.message).await; - Err(error) - } - } -} - -/// The payload a queue item runs with: its `repository` overrides `payload.repository`. -fn effective_payload(payload: &serde_json::Value, repository: Option<&str>) -> serde_json::Value { - let mut effective = if payload.is_object() { - payload.clone() - } else { - serde_json::json!({}) - }; - if let Some(repository) = repository.map(str::trim).filter(|value| !value.is_empty()) { - effective["repository"] = serde_json::json!(repository); - } - effective -} - -async fn start_claimed_run( - state: &AppState, - auth: &AuthContext, - item: &TeamQueueItem, - run: &orbit_store::TeamRun, - definition: &crate::handlers::teams::TeamDefinition, -) -> Result, ApiError> { - if !state - .store - .attach_team_run_to_queue_item(auth.org_id, item.id, run.id) - .await? - { - return Err(ApiError::conflict( - "queue item was cancelled or claimed elsewhere while starting", - )); - } - let first = crate::handlers::teams::start_first_steps(state, run, definition).await?; - for step in &first.started { - crate::handlers::teams::auto_launch_step(state, run, definition, step, Some(auth)).await?; - } - Ok(first.steps) -} - -/// Undo a failed start: cancel the run and its not-yet-running execution so nothing -/// executes for an item that is reported as failed, then mark the item retryable. -async fn release_failed_claim( - state: &AppState, - auth: &AuthContext, - item: &TeamQueueItem, - run: Option<&orbit_store::TeamRun>, - message: &str, -) { - if let Some(run) = run { - // A workflow run may have started several steps; stop them all. - match state - .store - .request_team_run_cancel(run.org_id, run.id) - .await - { - Ok(cancelled) => { - crate::handlers::teams::announce_cancel(state, run.org_id, &cancelled).await - } - Err(error) => { - tracing::warn!(%error, run_id = %run.id, "failed to cancel executions of aborted team run") - } - } - let key = format!("team:{}:0", run.id); - if let Ok(Some(execution)) = state - .store - .get_execution_by_idempotency_key(run.org_id, &key) - .await - { - if let Err(error) = state - .store - .request_execution_cancel(run.org_id, execution.id) - .await - { - tracing::warn!(%error, execution_id = %execution.id, "failed to cancel execution of aborted team run"); - } - } - if let Err(error) = state - .store - .finish_team_run(run.id, "cancelled", None, Some(message)) - .await - { - tracing::warn!(%error, run_id = %run.id, "failed to cancel aborted team run"); - } - } - if let Err(error) = state - .store - .fail_claimed_team_queue_item(auth.org_id, item.id, message) - .await - { - tracing::warn!(%error, queue_item = %item.id, "failed to release queue item claim"); - } -} - /// A cancelled item keeps its run link until it is retried or requeued, so a second run is /// never started while the first one's execution is still stopping (#299). async fn reject_while_previous_run_is_live( @@ -494,7 +298,7 @@ pub async fn cancel( .store .request_team_run_cancel(auth.org_id, run_id) .await?; - crate::handlers::teams::announce_cancel(&state, auth.org_id, &cancelled).await; + crate::team_runs::announce_cancel(&state, auth.org_id, &cancelled).await; let _ = state .store .finish_team_run(run_id, "cancelled", None, Some("queue item cancelled")) diff --git a/crates/orbit-api/src/handlers/teams.rs b/crates/orbit-api/src/handlers/teams.rs index ae2cfd07..49ce64b1 100644 --- a/crates/orbit-api/src/handlers/teams.rs +++ b/crates/orbit-api/src/handlers/teams.rs @@ -4,40 +4,27 @@ use axum::extract::{Path, Query, State}; use axum::http::StatusCode; use axum::Extension; use axum::Json; -use serde::{Deserialize, Serialize}; +use serde::Deserialize; use uuid::Uuid; use orbit_domain::{ - HarnessKind, TeamAutonomy, TeamAutonomyMode, TriggerSource, ValidationIssue, - WorkflowDefinition, WorkflowNode, WORKFLOW_MODE, + HarnessKind, TeamAutonomy, TeamAutonomyMode, ValidationIssue, WorkflowDefinition, WORKFLOW_MODE, }; use orbit_security::{AuthContext, Permission}; -use orbit_store::{AgentTeam, ExecutionRecord, TeamRun, TeamStep}; +use orbit_store::AgentTeam; use crate::dto::{TeamRunListQuery, TeamRunPage}; use crate::error::ApiError; use crate::state::AppState; +use crate::team_runs::{ + announce_cancel, approval_mode_label, auto_launch_step, default_mode, parse_definition, + start_first_steps, team_connection_ids, validate_requested_repositories, TeamModelOverride, + TeamRunDetail, +}; use crate::work_sources::{ validate_repositories, validate_work_source, RepositorySpec, WorkSourceDefinition, }; -/// The explicit run instruction is the only text presented as the task to the harness. -fn run_instruction(run_input: &serde_json::Value) -> &str { - run_input - .get("task") - .and_then(serde_json::Value::as_str) - .unwrap_or("Team run") -} - -/// Team goal/instructions are configuration. They travel as trusted system context, -/// never as part of the run instruction. -fn configured_goal(run_input: &serde_json::Value) -> &str { - run_input - .get("instructions") - .and_then(serde_json::Value::as_str) - .unwrap_or("") -} - #[derive(Debug, Clone, Deserialize, utoipa::ToSchema)] #[serde(rename_all = "camelCase")] pub struct TeamStepInput { @@ -129,116 +116,6 @@ pub struct CreateTeamRunRequest { pub harness_override: Option, } -#[derive(Debug, Clone, Serialize, utoipa::ToSchema)] -#[serde(rename_all = "camelCase")] -pub struct TeamRunDetail { - pub run: TeamRun, - pub steps: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct TeamDefinition { - #[serde(default = "default_mode")] - pub mode: String, - #[serde(default)] - pub instructions: String, - #[serde(default)] - pub repository: Option, - #[serde(default)] - pub branch: Option, - #[serde(default)] - pub work_source: Option, - #[serde(default)] - pub repositories: Vec, - #[serde(default)] - pub worker_profile_id: Option, - #[serde(default)] - pub auto_launch: bool, - #[serde(default)] - pub skills: Vec, - #[serde(default)] - pub harness: Option, - #[serde(default)] - pub connection_ids: Vec, - #[serde(default)] - pub env_mapping_ids: Vec, - #[serde(default)] - pub model: Option, - /// Wall-clock timeout for each step. Defaults to 1 hour for team runs. - #[serde(default)] - pub timeout_seconds: Option, - /// Explicit team autonomy. Missing means follow each step agent's level. - #[serde(default)] - pub autonomy: Option, - /// The agents in order. For a workflow: every agent it uses, once. - #[serde(default)] - pub steps: Vec, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub workflow: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)] -#[serde(rename_all = "camelCase")] -pub struct TeamModelOverride { - #[serde(default)] - pub provider: Option, - #[serde(default)] - pub model: Option, - #[serde(default)] - pub management: Option, -} - -impl TeamModelOverride { - /// Apply the override to an agent's model settings. Fields the override leaves out - /// keep the agent's own value. - pub(crate) fn apply(&self, model: &mut orbit_domain::ModelSpec) { - if let Some(provider) = &self.provider { - model.provider = Some(provider.clone()); - } - if let Some(value) = &self.model { - model.model = Some(value.clone()); - } - if let Some(management) = &self.management { - model.management = match management.as_str() { - "platform" => orbit_domain::ModelManagement::Platform, - _ => orbit_domain::ModelManagement::Harness, - }; - } - } -} - -impl TeamDefinition { - /// The graph, when this team runs as a workflow. - pub(crate) fn workflow(&self) -> Option<&WorkflowDefinition> { - if self.mode == WORKFLOW_MODE { - self.workflow.as_ref() - } else { - None - } - } - - /// The model override for a step: the step's own, else the team's. - pub(crate) fn model_override(&self, step_index: usize) -> Option<&TeamModelOverride> { - self.steps - .get(step_index) - .and_then(|step| step.model.as_ref()) - .or(self.model.as_ref()) - } -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct TeamStepDefinition { - pub agent_id: Uuid, - #[serde(default)] - pub model: Option, -} - -fn default_mode() -> String { - "pipeline".into() -} - /// Check the mode and, for a workflow, the graph; then derive `steps` from it so access /// checks, autonomy elevation, the queue and exports see every agent the workflow uses. fn prepare_mode(body: &mut CreateTeamRequest) -> Result<(), ApiError> { @@ -308,99 +185,6 @@ fn step_agent_paths(body: &CreateTeamRequest, index: usize, agent_id: Uuid) -> V vec![format!("steps[{index}].agentId")] } -pub(crate) fn parse_definition(team: &AgentTeam) -> Result { - serde_json::from_value(team.definition.clone()) - .map_err(|error| ApiError::internal(format!("team definition is invalid: {error}"))) -} - -/// Connections a team run injects beyond the agent specs: the team's shared connections -/// and an enabled work source connection. -pub(crate) fn team_connection_ids(definition: &TeamDefinition) -> Vec { - let mut ids = definition.connection_ids.clone(); - if let Some(source) = &definition.work_source { - if source.enabled { - ids.extend(source.connection_id); - } - } - ids -} - -/// A caller-supplied repository must be one of the team's configured repositories; the -/// run injects the team's connection credentials, so it must not retarget them. -fn validate_requested_repositories( - definition: &TeamDefinition, - payload: &serde_json::Value, -) -> Result<(), ApiError> { - check_requested_repositories(definition, payload, |_| false) -} - -/// The repository rule for queue items (#384): the same targets as a run, plus the -/// projects of a GitLab group work source. `stored` relaxes the group rule for items that -/// are already in the queue (the dispatcher records projects of a group given by numeric -/// id, which cannot be matched by path); callers enqueuing new items get the strict rule. -pub(crate) fn validate_queue_repositories( - definition: &TeamDefinition, - payload: &serde_json::Value, - stored: bool, -) -> Result<(), ApiError> { - check_requested_repositories(definition, payload, |value| { - definition.work_source.as_ref().is_some_and(|source| { - crate::work_sources::group_includes_project(source, value, stored) - }) - }) -} - -fn check_requested_repositories( - definition: &TeamDefinition, - payload: &serde_json::Value, - also_allowed: impl Fn(&str) -> bool, -) -> Result<(), ApiError> { - let mut allowed: Vec = Vec::new(); - allowed.extend(definition.repository.iter().cloned()); - allowed.extend( - definition - .repositories - .iter() - .map(|repository| repository.repository.clone()), - ); - if let Some(source) = &definition.work_source { - allowed.extend(source.repository.iter().cloned()); - allowed.extend(source.project.iter().cloned()); - } - let is_allowed = |value: &str| { - allowed - .iter() - .any(|candidate| candidate.trim().eq_ignore_ascii_case(value.trim())) - || also_allowed(value) - }; - if let Some(repository) = payload.get("repository").and_then(|value| value.as_str()) { - if !is_allowed(repository) { - return Err(ApiError::validation(vec![ValidationIssue::new( - "payload.repository", - "repository is not one of the team's configured repositories", - )])); - } - } - if let Some(items) = payload - .get("repositories") - .and_then(|value| value.as_array()) - { - for (idx, item) in items.iter().enumerate() { - let repository = item - .get("repository") - .and_then(|value| value.as_str()) - .unwrap_or_default(); - if !is_allowed(repository) { - return Err(ApiError::validation(vec![ValidationIssue::new( - format!("payload.repositories[{idx}].repository"), - "repository is not one of the team's configured repositories", - )])); - } - } - } - Ok(()) -} - async fn validate_work_source_connection( state: &AppState, org_id: Uuid, @@ -623,14 +407,6 @@ async fn validate_team_autonomy( (elevated, Some(stored)) } -fn approval_mode_label(mode: orbit_domain::ApprovalMode) -> &'static str { - match mode { - orbit_domain::ApprovalMode::Auto => "auto", - orbit_domain::ApprovalMode::Writes => "writes", - orbit_domain::ApprovalMode::Always => "always", - } -} - async fn audit_team_autonomy_elevations( state: &AppState, auth: &AuthContext, @@ -714,14 +490,21 @@ pub(crate) async fn require_team_use( Ok(team) } -#[utoipa::path(post, path = "/api/v1/agent-teams", tag = "agent-teams", request_body = CreateTeamRequest, responses((status = 201, body = orbit_store::AgentTeam)))] -pub async fn create_team( - State(state): State, - Extension(auth): Extension, - crate::extract::ApiJson(mut body): crate::extract::ApiJson, -) -> Result<(StatusCode, Json), ApiError> { - auth.require(Permission::SettingsWrite)?; - prepare_mode(&mut body)?; +/// What a validated team request stores, plus the autonomy elevations to audit. +struct ValidatedTeam { + definition: serde_json::Value, + elevations: Vec, + autonomy: Option, +} + +/// Validation shared by team create and update: normalise the mode, check the request and +/// everything it references for the caller, and build the definition to store. +async fn validate_team_request( + state: &AppState, + auth: &AuthContext, + body: &mut CreateTeamRequest, +) -> Result { + prepare_mode(body)?; // Only the fields that are actually wrong (#438): a team with a name but no steps used // to be told "name: name is required" as well. let mut required = Vec::new(); @@ -766,11 +549,11 @@ pub async fn create_team( if !body.repositories.is_empty() { issues.extend(validate_repositories(&body.repositories)); } - let access = crate::access::AccessScope::load(&state, &auth).await?; + let access = crate::access::AccessScope::load(state, auth).await?; let mut agent_ids = std::collections::BTreeSet::new(); for (index, step) in body.steps.iter().enumerate() { if !agent_ids.insert(step.agent_id) { - for path in step_agent_paths(&body, index, step.agent_id) { + for path in step_agent_paths(body, index, step.agent_id) { issues.push(ValidationIssue::new( path, "the same agent cannot appear twice in one team", @@ -785,7 +568,7 @@ pub async fn create_team( Err(_) => false, }; if !viewable { - for path in step_agent_paths(&body, index, step.agent_id) { + for path in step_agent_paths(body, index, step.agent_id) { issues.push(ValidationIssue::new( path, format!("unknown agent '{}'", step.agent_id), @@ -794,7 +577,7 @@ pub async fn create_team( } } if let Some(source) = &body.work_source { - validate_work_source_connection(&state, auth.org_id, &access, source, &mut issues).await; + validate_work_source_connection(state, auth.org_id, &access, source, &mut issues).await; } if let Some(profile_id) = body.worker_profile_id { let viewable = match state @@ -818,7 +601,7 @@ pub async fn create_team( } issues.extend( crate::preflight::unusable_skill_issues( - &state, + state, auth.org_id, &access, &body.skills, @@ -865,10 +648,10 @@ pub async fn create_team( )); } } - validate_native_primary(&state, auth.org_id, &body.mode, &body.steps, &mut issues).await; + validate_native_primary(state, auth.org_id, &body.mode, &body.steps, &mut issues).await; let (elevations, autonomy) = validate_team_autonomy( - &state, - &auth, + state, + auth, &access, body.autonomy.as_ref(), &body.steps, @@ -900,6 +683,25 @@ pub async fn create_team( })).collect::>(), "workflow": body.workflow, }); + Ok(ValidatedTeam { + definition, + elevations, + autonomy, + }) +} + +#[utoipa::path(post, path = "/api/v1/agent-teams", tag = "agent-teams", request_body = CreateTeamRequest, responses((status = 201, body = orbit_store::AgentTeam)))] +pub async fn create_team( + State(state): State, + Extension(auth): Extension, + crate::extract::ApiJson(mut body): crate::extract::ApiJson, +) -> Result<(StatusCode, Json), ApiError> { + auth.require(Permission::SettingsWrite)?; + let ValidatedTeam { + definition, + elevations, + autonomy, + } = validate_team_request(&state, &auth, &mut body).await?; let team = state .store .create_agent_team( @@ -964,263 +766,89 @@ pub(crate) async fn replace_team( auth.require(Permission::SettingsWrite)?; let stored = require_team_manage(state, auth, team_id).await?; let expected_updated_at = expected_updated_at.or(body.expected_updated_at); - prepare_mode(&mut body)?; - // Only the fields that are actually wrong (#438): a team with a name but no steps used - // to be told "name: name is required" as well. - let mut required = Vec::new(); - if body.name.trim().is_empty() { - required.push(ValidationIssue::new("name", "name is required")); - } - if body.steps.is_empty() { - required.push(ValidationIssue::new( - "steps", - "at least one step is required", - )); - } - if !required.is_empty() { - return Err(ApiError::validation(required)); - } - if body - .timeout_seconds - .is_some_and(|seconds| !(1..=86_400).contains(&seconds)) - { + let ValidatedTeam { + definition, + elevations, + autonomy, + } = validate_team_request(state, auth, &mut body).await?; + let team = state + .store + .update_agent_team( + auth.org_id, + team_id, + body.name.trim(), + body.description.trim(), + &definition, + expected_updated_at, + ) + .await?; + audit_team_autonomy_elevations(state, auth, team.id, &elevations, autonomy.as_ref()).await; + crate::audit::record( + state, + auth, + "team.updated", + Some("agent_team"), + Some(team.id), + serde_json::json!({ "name": team.name, "changed": changed_keys(&stored, &team) }), + ) + .await; + Ok(team) +} + +/// The stored team as a request, with the fields of `patch` laid over it (#432). Before, +/// PATCH replaced the whole team, so a client that left out `autonomy`, +/// `connectionIds` or `workSource` silently cleared them. +fn merge_team_patch( + stored: &AgentTeam, + patch: serde_json::Value, +) -> Result<(CreateTeamRequest, Option>), ApiError> { + let serde_json::Value::Object(mut patch) = patch else { return Err(ApiError::validation(vec![ValidationIssue::new( - "timeoutSeconds", - "must be 1..=86400", + "body", + "the request body must be a JSON object", )])); + }; + let expected_updated_at = match patch.remove("expectedUpdatedAt") { + None | Some(serde_json::Value::Null) => None, + Some(value) => Some(serde_json::from_value(value).map_err(|_| { + ApiError::validation(vec![ValidationIssue::new( + "expectedUpdatedAt", + "must be an RFC 3339 timestamp, the team's updatedAt", + )]) + })?), + }; + let mut merged = match &stored.definition { + serde_json::Value::Object(map) => map.clone(), + _ => serde_json::Map::new(), + }; + merged.insert("name".into(), serde_json::json!(stored.name)); + merged.insert("description".into(), serde_json::json!(stored.description)); + for (key, value) in patch { + merged.insert(key, value); } - if let Some(repository) = body - .repository - .as_deref() - .map(str::trim) - .filter(|r| !r.is_empty()) - { - if !repository.contains('/') || repository.chars().any(char::is_whitespace) { - return Err(ApiError::validation(vec![ValidationIssue::new( - "repository", - "repository must be owner/repo", - )])); - } - } - let mut issues = Vec::new(); - if let Some(source) = &body.work_source { - issues.extend(validate_work_source(source)); + let body = serde_json::from_value(serde_json::Value::Object(merged)).map_err(|error| { + ApiError::validation(vec![ValidationIssue::new("body", error.to_string())]) + })?; + Ok((body, expected_updated_at)) +} + +/// Top-level team fields whose stored value changed, for the audit entry. +fn changed_keys(before: &AgentTeam, after: &AgentTeam) -> Vec { + let mut keys = Vec::new(); + if before.name != after.name { + keys.push("name".to_string()); } - if !body.repositories.is_empty() { - issues.extend(validate_repositories(&body.repositories)); + if before.description != after.description { + keys.push("description".to_string()); } - let access = crate::access::AccessScope::load(state, auth).await?; - let mut agent_ids = std::collections::BTreeSet::new(); - for (index, step) in body.steps.iter().enumerate() { - if !agent_ids.insert(step.agent_id) { - for path in step_agent_paths(&body, index, step.agent_id) { - issues.push(ValidationIssue::new( - path, - "the same agent cannot appear twice in one team", - )); - } - } - // An agent the caller cannot view is reported exactly like a missing one. - let viewable = match state.store.get_agent(auth.org_id, step.agent_id).await { - Ok(agent) => { - access.can_view(agent.owner_user_id, agent.owner_team_id, &agent.visibility) - } - Err(_) => false, - }; - if !viewable { - for path in step_agent_paths(&body, index, step.agent_id) { - issues.push(ValidationIssue::new( - path, - format!("unknown agent '{}'", step.agent_id), - )); - } - } - } - if let Some(source) = &body.work_source { - validate_work_source_connection(state, auth.org_id, &access, source, &mut issues).await; - } - if let Some(profile_id) = body.worker_profile_id { - let viewable = match state - .store - .get_worker_profile(auth.org_id, profile_id) - .await - { - Ok(profile) => access.can_view( - profile.owner_user_id, - profile.owner_team_id, - &profile.visibility, - ), - Err(_) => false, - }; - if !viewable { - issues.push(ValidationIssue::new( - "workerProfileId", - format!("unknown worker profile '{profile_id}'"), - )); - } - } - issues.extend( - crate::preflight::unusable_skill_issues( - state, - auth.org_id, - &access, - &body.skills, - "skills", - false, - ) - .await?, - ); - for connection_id in &body.connection_ids { - match state - .store - .get_connection(auth.org_id, *connection_id) - .await - { - Ok(connection) - if access.can_view( - connection.owner_user_id, - connection.owner_team_id, - &connection.visibility, - ) => {} - Ok(_) => issues.push(ValidationIssue::new( - "connectionIds", - format!("connection '{connection_id}' is not visible to you"), - )), - Err(_) => issues.push(ValidationIssue::new( - "connectionIds", - format!("unknown connection '{connection_id}'"), - )), - } - } - for mapping_id in &body.env_mapping_ids { - let viewable = match state.store.get_env_mapping(auth.org_id, *mapping_id).await { - Ok(mapping) => access.can_view( - mapping.owner_user_id, - mapping.owner_team_id, - &mapping.visibility, - ), - Err(_) => false, - }; - if !viewable { - issues.push(ValidationIssue::new( - "envMappingIds", - format!("unknown environment mapping '{mapping_id}'"), - )); - } - } - validate_native_primary(state, auth.org_id, &body.mode, &body.steps, &mut issues).await; - let (elevations, autonomy) = validate_team_autonomy( - state, - auth, - &access, - body.autonomy.as_ref(), - &body.steps, - &mut issues, - ) - .await; - if !issues.is_empty() { - return Err(ApiError::validation(issues)); - } - let definition = serde_json::json!({ - "mode": body.mode, - "instructions": body.instructions.trim(), - "repository": body.repository.as_deref().map(str::trim).filter(|value| !value.is_empty()), - "branch": body.branch.as_deref().map(str::trim).filter(|value| !value.is_empty()), - "workSource": body.work_source.as_ref().map(work_source_to_json), - "repositories": repositories_to_json(&body.repositories), - "model": body.model, - "workerProfileId": body.worker_profile_id, - "autoLaunch": body.auto_launch, - "skills": body.skills, - "harness": body.harness, - "connectionIds": body.connection_ids, - "envMappingIds": body.env_mapping_ids, - "timeoutSeconds": body.timeout_seconds, - "autonomy": autonomy, - "steps": body.steps.iter().map(|step| serde_json::json!({ - "agentId": step.agent_id, - "model": step.model, - })).collect::>(), - "workflow": body.workflow, - }); - let team = state - .store - .update_agent_team( - auth.org_id, - team_id, - body.name.trim(), - body.description.trim(), - &definition, - expected_updated_at, - ) - .await?; - audit_team_autonomy_elevations(state, auth, team.id, &elevations, autonomy.as_ref()).await; - crate::audit::record( - state, - auth, - "team.updated", - Some("agent_team"), - Some(team.id), - serde_json::json!({ "name": team.name, "changed": changed_keys(&stored, &team) }), - ) - .await; - Ok(team) -} - -/// The stored team as a request, with the fields of `patch` laid over it (#432). Before, -/// PATCH replaced the whole team, so a client that left out `autonomy`, -/// `connectionIds` or `workSource` silently cleared them. -fn merge_team_patch( - stored: &AgentTeam, - patch: serde_json::Value, -) -> Result<(CreateTeamRequest, Option>), ApiError> { - let serde_json::Value::Object(mut patch) = patch else { - return Err(ApiError::validation(vec![ValidationIssue::new( - "body", - "the request body must be a JSON object", - )])); - }; - let expected_updated_at = match patch.remove("expectedUpdatedAt") { - None | Some(serde_json::Value::Null) => None, - Some(value) => Some(serde_json::from_value(value).map_err(|_| { - ApiError::validation(vec![ValidationIssue::new( - "expectedUpdatedAt", - "must be an RFC 3339 timestamp, the team's updatedAt", - )]) - })?), - }; - let mut merged = match &stored.definition { - serde_json::Value::Object(map) => map.clone(), - _ => serde_json::Map::new(), - }; - merged.insert("name".into(), serde_json::json!(stored.name)); - merged.insert("description".into(), serde_json::json!(stored.description)); - for (key, value) in patch { - merged.insert(key, value); - } - let body = serde_json::from_value(serde_json::Value::Object(merged)).map_err(|error| { - ApiError::validation(vec![ValidationIssue::new("body", error.to_string())]) - })?; - Ok((body, expected_updated_at)) -} - -/// Top-level team fields whose stored value changed, for the audit entry. -fn changed_keys(before: &AgentTeam, after: &AgentTeam) -> Vec { - let mut keys = Vec::new(); - if before.name != after.name { - keys.push("name".to_string()); - } - if before.description != after.description { - keys.push("description".to_string()); - } - let empty = serde_json::Map::new(); - let old = before.definition.as_object().unwrap_or(&empty); - let new = after.definition.as_object().unwrap_or(&empty); - let mut names: std::collections::BTreeSet<&String> = old.keys().collect(); - names.extend(new.keys()); - for name in names { - if old.get(name) != new.get(name) { - keys.push(name.clone()); + let empty = serde_json::Map::new(); + let old = before.definition.as_object().unwrap_or(&empty); + let new = after.definition.as_object().unwrap_or(&empty); + let mut names: std::collections::BTreeSet<&String> = old.keys().collect(); + names.extend(new.keys()); + for name in names { + if old.get(name) != new.get(name) { + keys.push(name.clone()); } } keys @@ -1280,26 +908,6 @@ pub async fn delete_team( Ok(StatusCode::NO_CONTENT) } -/// Tell workers about executions whose cancellation was just requested. Workers also -/// poll the cancel flag, so a lost bus message only delays the stop. -pub(crate) async fn announce_cancel( - state: &AppState, - org_id: Uuid, - executions: &[orbit_store::ExecutionRecord], -) { - for execution in executions { - let event = orbit_contracts::OrbitEvent::new( - orbit_contracts::subjects::EXECUTION_CANCEL, - "orbit-api", - serde_json::json!({ "executionId": execution.id }), - ) - .with_org(org_id); - if let Err(error) = state.bus.publish(event).await { - tracing::warn!(%error, execution_id = %execution.id, "cancel event publish failed; worker polls the cancel flag"); - } - } -} - /// Stop a team run: request cancellation of its live executions, mark the run /// `cancelled` and cancel the queue item it was started for, if any. #[utoipa::path(post, path = "/api/v1/team-runs/{run_id}/cancel", tag = "agent-teams", responses((status = 200, body = TeamRunDetail), (status = 409, description = "the run already ended")))] @@ -1350,588 +958,6 @@ pub async fn cancel_run( Ok(Json(TeamRunDetail { run, steps })) } -/// A subagent's system prompt: its instructions followed by its constraints. Never stored -/// in the run: execution and step input are readable by anyone who can view the team or -/// the primary agent, and a subagent may be private (#429). The worker context adds it -/// when a worker claims the step. -pub(crate) fn subagent_instructions(spec: &orbit_domain::AgentSpec) -> String { - let mut instructions = spec.instructions.system.clone(); - if !spec.instructions.constraints.is_empty() { - instructions.push_str("\n\nConstraints:\n"); - for constraint in &spec.instructions.constraints { - instructions.push_str(&format!("- {constraint}\n")); - } - } - instructions -} - -/// The native subagents of a team, as references: id, name, description and model, but -/// no instructions (see [`subagent_instructions`]). -async fn native_subagents( - state: &AppState, - org_id: Uuid, - definition: &TeamDefinition, -) -> Result, ApiError> { - let mut subagents = Vec::new(); - for (index, step) in definition.steps.iter().enumerate().skip(1) { - let agent = state.store.get_agent(org_id, step.agent_id).await?; - let version = state.store.get_current_version(org_id, &agent).await?; - let mut spec: orbit_domain::AgentSpec = serde_json::from_value(version.spec.clone()) - .map_err(|error| { - ApiError::internal(format!("stored agent spec is invalid: {error}")) - })?; - let model_override = definition.model_override(index).cloned(); - if let Some(override_model) = &model_override { - override_model.apply(&mut spec.model); - } - let model = match (&spec.model.provider, &spec.model.model) { - (Some(provider), Some(model)) if !model.contains('/') => { - Some(format!("{provider}/{model}")) - } - (_, Some(model)) => Some(model.clone()), - _ => None, - }; - subagents.push(serde_json::json!({ - "agentId": agent.id, - "name": agent.name, - "slug": agent.slug, - "description": agent.description, - "model": model, - "modelOverride": model_override, - })); - } - Ok(subagents) -} - -/// The workflow step a team step runs, for [`start_step_with`]. -pub(crate) struct WorkflowStepStart<'a> { - pub node: &'a WorkflowNode, - /// 1 for the first time this workflow step runs in the run. - pub attempt: u32, - /// The deliveries this start takes (`[{ edge, step }]`). - pub activated_by: serde_json::Value, -} - -pub(crate) struct StepStart<'a> { - pub step_index: usize, - pub agent_id: Uuid, - pub model_override: Option, - pub previous_output: Option<&'a serde_json::Value>, - pub workflow: Option>, -} - -/// Start step `step_index` of a pipeline or native run. -/// A step agent whose current policy is stricter than the team's authorised elevation, so -/// the step runs with the stricter policy (#385). -struct AutonomyClamp { - agent_id: Uuid, - agent_name: String, - requested: orbit_domain::AutonomyPolicy, - agent: orbit_domain::AutonomyPolicy, - applied: orbit_domain::AutonomyPolicy, -} - -impl AutonomyClamp { - fn message(&self) -> String { - format!( - "team autonomy limited for agent '{}': the team asks for level {} with approval mode {}, \ - but the agent's own policy (level {}, approval mode {}) is stricter than when the team was \ - authorised; running at level {} with approval mode {}. Re-save the team with manage \ - access to the agent to authorise it again.", - self.agent_name, - self.requested.level, - approval_mode_label(self.requested.approval_mode), - self.agent.level, - approval_mode_label(self.agent.approval_mode), - self.applied.level, - approval_mode_label(self.applied.approval_mode), - ) - } - - fn to_json(&self) -> serde_json::Value { - serde_json::json!({ - "agentId": self.agent_id, - "agentName": self.agent_name, - "requested": self.requested, - "agent": self.agent, - "applied": self.applied, - }) - } -} - -/// The fixed team policy a step execution carries, resolved against the **current** policy -/// of every agent it governs: the step agent, and for a native team every subagent too, -/// because subagents inherit the primary execution's policy. `None` when the team does not -/// fix autonomy. An agent whose policy cannot be read fails the step. -async fn effective_team_autonomy( - state: &AppState, - run: &TeamRun, - definition: &TeamDefinition, - agent_id: Uuid, - spec: &orbit_domain::AgentSpec, - native: bool, -) -> Result)>, ApiError> { - let Some(autonomy) = definition.autonomy.as_ref() else { - return Ok(None); - }; - if autonomy.mode != TeamAutonomyMode::Fixed { - return Ok(None); - } - let mut governed = vec![( - agent_id, - None, - orbit_domain::AutonomyPolicy::of(&spec.autonomy), - )]; - if native { - for step in &definition.steps { - if governed.iter().any(|(id, _, _)| *id == step.agent_id) { - continue; - } - let agent = state.store.get_agent(run.org_id, step.agent_id).await?; - let version = state.store.get_current_version(run.org_id, &agent).await?; - let sub: orbit_domain::AgentSpec = - serde_json::from_value(version.spec).map_err(|error| { - ApiError::internal(format!("stored agent spec is invalid: {error}")) - })?; - governed.push(( - agent.id, - Some(agent.name), - orbit_domain::AutonomyPolicy::of(&sub.autonomy), - )); - } - } - let mut clamps = Vec::new(); - let mut combined: Option = None; - for (id, name, own) in governed { - let applied = match orbit_domain::resolve_team_autonomy(autonomy, id, own) { - orbit_domain::TeamAutonomyResolution::NotFixed => return Ok(None), - orbit_domain::TeamAutonomyResolution::Applies(team) => { - team.policy_for(own).unwrap_or(own) - } - orbit_domain::TeamAutonomyResolution::Clamped { - autonomy: clamped, - requested, - agent, - } => { - let applied = clamped.policy_for(agent).unwrap_or(agent); - clamps.push(AutonomyClamp { - agent_id: id, - agent_name: match name { - Some(name) => name, - None => state.store.get_agent(run.org_id, id).await?.name, - }, - requested, - agent, - applied, - }); - applied - } - }; - combined = Some(match combined { - Some(policy) => policy.stricter_of(&applied), - None => applied, - }); - } - if clamps.is_empty() { - return Ok(Some((autonomy.snapshot(), clamps))); - } - let policy = combined.expect("at least the step agent is governed"); - Ok(Some(( - TeamAutonomy { - mode: TeamAutonomyMode::Fixed, - level: Some(policy.level), - approval_mode: Some(policy.approval_mode), - elevations: Vec::new(), - }, - clamps, - ))) -} - -pub(crate) async fn start_step( - state: &AppState, - run: &TeamRun, - definition: &TeamDefinition, - step_index: usize, - previous_output: Option<&serde_json::Value>, -) -> Result { - let step = definition - .steps - .get(step_index) - .ok_or_else(|| ApiError::internal("team step index out of range"))?; - start_step_with( - state, - run, - definition, - StepStart { - step_index, - agent_id: step.agent_id, - model_override: definition.model_override(step_index).cloned(), - previous_output, - workflow: None, - }, - ) - .await -} - -/// The first steps of a new run. -pub(crate) struct FirstSteps { - /// Every step the run has now. - pub steps: Vec, - /// The steps this call created. The caller launches workers for these only; steps - /// the background loop created were launched by the loop. - pub started: Vec, -} - -/// Start the first step of a new run: step 0 of a pipeline or native team, or the -/// starting steps of a workflow. -pub(crate) async fn start_first_steps( - state: &AppState, - run: &TeamRun, - definition: &TeamDefinition, -) -> Result { - if let Some(workflow) = definition.workflow() { - return crate::team_workflow::start_run(state, run, definition, workflow).await; - } - let step = start_step(state, run, definition, 0, None).await?; - Ok(FirstSteps { - steps: vec![step.clone()], - started: vec![step], - }) -} - -/// Launch the team's worker profile for a step that was just created, when the team asks -/// for that. `auth` is the caller; background starts pass `None`. -pub(crate) async fn auto_launch_step( - state: &AppState, - run: &TeamRun, - definition: &TeamDefinition, - step: &TeamStep, - auth: Option<&AuthContext>, -) -> Result<(), ApiError> { - if !definition.auto_launch { - return Ok(()); - } - let (Some(profile_id), Some(execution_id)) = (definition.worker_profile_id, step.execution_id) - else { - return Ok(()); - }; - let background; - let auth = match auth { - Some(auth) => auth, - None => { - // Later steps start in the background: launch as the run's requester, or the - // team owner when the requester was deleted (`requested_by` is then NULL). - // Never a nil user id: `worker_launches.created_by` is a foreign key (#383). - let team = state.store.get_agent_team(run.org_id, run.team_id).await?; - background = crate::preflight::background_identity( - state, - run.org_id, - &[run.requested_by, team.owner_user_id], - ) - .await? - .ok_or_else(|| { - ApiError::validation(vec![ValidationIssue::new( - "autoLaunch", - "auto-launch needs the run's requester or a team owner", - )]) - })?; - &background - } - }; - crate::handlers::worker_launches::launch_profile_internal( - state, - auth, - profile_id, - Some(execution_id), - ) - .await?; - Ok(()) -} - -pub(crate) async fn start_step_with( - state: &AppState, - run: &TeamRun, - definition: &TeamDefinition, - start: StepStart<'_>, -) -> Result { - // Every team step creates an execution through `create_execution_with_limit`, so - // manual runs, scheduled/queue starts and dispatcher auto-run share the same guard. - let StepStart { - step_index, - agent_id, - model_override, - previous_output, - workflow, - } = start; - let agent = state.store.get_agent(run.org_id, agent_id).await?; - let version = state.store.get_current_version(run.org_id, &agent).await?; - let mut spec: orbit_domain::AgentSpec = serde_json::from_value(version.spec.clone()) - .map_err(|error| ApiError::internal(format!("stored agent spec is invalid: {error}")))?; - - // Apply the step's (or the team's) model override. Preflight checks the provider of - // the overridden model, and the override travels with the execution so the worker - // runs that same model (#305). - if let Some(override_model) = &model_override { - override_model.apply(&mut spec.model); - } - // #259: the run instruction is the single task for every step. The team goal is - // configured system context and the previous step output is delegated context; - // neither is copied into the task the harness presents as user input. - let task = run_instruction(&run.input).to_string(); - // A workflow step adds its own instructions and, when it has outcomes, how to report - // one. Both are configuration, so they travel with the goal as system context. - let instructions = match &workflow { - Some(step) => crate::team_workflow::step_goal(configured_goal(&run.input), step.node), - None => configured_goal(&run.input).to_string(), - }; - let previous = previous_output - .map(|value| value.to_string()) - .unwrap_or_else(|| "null".into()); - let requested_harness = run - .input - .get("payload") - .and_then(|value| value.get("harnessOverride")) - .and_then(|value| value.as_str()) - .or(definition.harness.as_deref()); - let harness_kind = match requested_harness { - Some(value) => value.parse::().map_err(|_| { - ApiError::validation(vec![ValidationIssue::new("harness", "unknown harness")]) - })?, - None => match spec.harness.as_ref().map(|harness| harness.kind) { - Some(kind) => kind, - None => state.default_harness().await.ok_or_else(|| { - ApiError::validation(vec![ValidationIssue::new( - "harness", - "no team harness, legacy agent harness or default harness is configured", - )]) - })?, - }, - }; - // Shared execution preflight (#140), re-evaluated for every step with the identity - // that requested the run (falling back to the team owner). - let team = state.store.get_agent_team(run.org_id, run.team_id).await?; - let team_connections = team_connection_ids(definition); - match crate::preflight::background_access( - state, - run.org_id, - &[run.requested_by, team.owner_user_id], - ) - .await? - { - Some(access) => { - access.require_use( - "agent team", - team.owner_user_id, - team.owner_team_id, - &team.visibility, - )?; - crate::preflight::Preflight { - state, - org_id: run.org_id, - access: &access, - agent: &agent, - spec: &spec, - harness: harness_kind, - extra_connection_ids: &team_connections, - } - .run() - .await?; - } - None => { - crate::preflight::require_harness_available(state, run.org_id, harness_kind).await?; - crate::preflight::require_hourly_quota(state, run.org_id, agent.id, &spec).await?; - } - } - let native = definition.mode == "native"; - if native && harness_kind != HarnessKind::OpenCode { - return Err(ApiError::conflict( - "native Agent Teams currently require an OpenCode primary agent", - )); - } - let mut team_payload = serde_json::json!({ - "runId": run.id, - "mode": definition.mode, - // Configured team instructions, consumed by the worker as system context. - "goal": instructions, - "agent": agent.name, - "stepIndex": step_index, - // Delegated context for later steps; never part of the run instruction. - "previous": previous, - "connectionIds": definition.connection_ids, - // Set server-side like connectionIds; the worker context applies it (#305). - "modelOverride": model_override, - "envMappingIds": definition.env_mapping_ids, - }); - if definition.repositories.len() > 1 { - let manifest = definition - .repositories - .iter() - .map(|repository| { - format!( - "- {} (workspace path: {})", - repository.repository, - if repository.path.is_empty() { - "." - } else { - &repository.path - } - ) - }) - .collect::>() - .join("\n"); - team_payload["workspaceRepositories"] = serde_json::json!(manifest); - } - if let Some(step) = &workflow { - team_payload["step"] = serde_json::json!({ - "id": step.node.id, - "name": step.node.name, - "attempt": step.attempt, - }); - } - if native { - team_payload["subagents"] = - serde_json::Value::Array(native_subagents(state, run.org_id, definition).await?); - } - let mut input = serde_json::json!({ - "task": task, - "payload": { - "teamRunId": run.id, - "stepIndex": step_index, - "agentName": agent.name, - "stepName": workflow.as_ref().map(|step| step.node.name.as_str()), - // Tells the agent (and the mock harness) which run of the step this is. - "stepAttempt": workflow.as_ref().map(|step| step.attempt), - "previous": previous_output, - "repository": run.input.get("payload").and_then(|value| value.get("repository")).cloned(), - "branch": run.input.get("payload").and_then(|value| value.get("branch")).cloned(), - "repositories": run.input.get("payload").and_then(|value| value.get("repositories")).cloned(), - "harnessOverride": run.input.get("payload").and_then(|value| value.get("harnessOverride")).cloned(), - }, - "provenance": { - "source": "team", - "trusted": true, - "subject": run.id, - "receivedAt": chrono::Utc::now(), - }, - "team": team_payload, - }); - // #385: the fixed team policy is resolved against the step agents' current policies, - // so an agent made stricter after the team was saved is never run less strictly. - let mut autonomy_clamps = Vec::new(); - if let Some((autonomy, clamps)) = - effective_team_autonomy(state, run, definition, agent.id, &spec, native).await? - { - input[orbit_domain::TEAM_AUTONOMY_KEY] = - serde_json::to_value(&autonomy).unwrap_or(serde_json::Value::Null); - if !clamps.is_empty() { - input["teamAutonomyClamped"] = - serde_json::Value::Array(clamps.iter().map(AutonomyClamp::to_json).collect()); - } - autonomy_clamps = clamps; - } - // #194: set only here, server-side, after the run was authorised with approvals:decide. - // The worker applies this before the fixed team policy, so a fixed team policy wins. - if run - .input - .get("autoApprove") - .and_then(|value| value.as_bool()) - == Some(true) - { - input[orbit_domain::APPROVAL_OVERRIDE_KEY] = - serde_json::json!(orbit_domain::APPROVAL_OVERRIDE_AUTO); - } - // A workflow step is identified by what it runs, not by the order it was created in: - // a retried start must find the same execution again. - let idempotency_key = match &workflow { - Some(step) => format!("team:{}:{}:{}", run.id, step.node.id, step.attempt), - None => format!("team:{}:{}", run.id, step_index), - }; - let replayed = !autonomy_clamps.is_empty() - && state - .store - .get_execution_by_idempotency_key(run.org_id, &idempotency_key) - .await? - .is_some(); - let execution = state - .create_execution_with_limit(orbit_store::executions::NewExecution { - org_id: run.org_id, - agent_id: agent.id, - agent_version_id: version.id, - agent_name: &agent.name, - harness_kind, - trigger_source: TriggerSource::Manual, - placement: spec - .harness - .as_ref() - .map(|harness| harness.placement.as_str()) - .unwrap_or("auto"), - trigger_id: None, - input, - session_ref: None, - skills: &definition.skills, - timeout_seconds: definition - .timeout_seconds - .unwrap_or_else(|| spec.resources.timeout_seconds.max(3600)), - requested_by: run.requested_by, - idempotency_key: Some(&idempotency_key), - team_run_id: Some(run.id), - team_step_index: Some(step_index as i32), - }) - .await?; - if !replayed { - for clamp in &autonomy_clamps { - if let Err(error) = state - .store - .append_execution_event( - run.org_id, - execution.id, - "log", - orbit_domain::LogLevel::Warn, - &clamp.message(), - &clamp.to_json(), - ) - .await - { - tracing::warn!(%error, execution_id = %execution.id, "could not record the team autonomy clamp"); - } - } - } - if let Some(step) = &workflow { - return Ok(state - .store - .create_workflow_step(orbit_store::agent_teams::NewWorkflowStep { - run_id: run.id, - org_id: run.org_id, - step_index: step_index as i32, - name: &step.node.name, - agent_id: agent.id, - agent_version_id: version.id, - skills: &definition.skills, - input: &execution.input, - execution_id: Some(execution.id), - node_id: &step.node.id, - attempt: step.attempt as i32, - activated_by: &step.activated_by, - }) - .await?); - } - let created = state - .store - .create_team_step( - run.id, - run.org_id, - step_index as i32, - &agent.name, - agent.id, - version.id, - &definition.skills, - &execution.input, - Some(execution.id), - ) - .await?; - Ok(created) -} - #[utoipa::path(post, path = "/api/v1/agent-teams/{team_id}/runs", tag = "agent-teams", request_body = CreateTeamRunRequest, responses((status = 201, body = TeamRunDetail)))] pub async fn create_run( State(state): State, @@ -2109,425 +1135,3 @@ pub async fn get_run( let steps = state.store.list_team_steps(run.id).await?; Ok(Json(TeamRunDetail { run, steps })) } - -/// How long a replica may hold the per-run advance lease before another may take over. -pub(crate) const ADVANCE_LEASE_SECS: i64 = 120; -/// How long a run whose next step cannot be started is retried before it is failed. -pub(crate) const START_STEP_RETRY_WINDOW_SECS: i64 = 300; -/// How long a step held back by an hourly quota or the licence's daily execution limit is -/// retried. Long enough for an hourly quota to clear (#305). -pub(crate) const LIMITED_STEP_RETRY_WINDOW_SECS: i64 = 3_900; - -/// Limits that clear by themselves: the agent's `maxExecutionsPerHour` (429) and the -/// licence's rolling daily execution limit (402). -pub(crate) fn is_temporary_limit(error: &ApiError) -> bool { - matches!(error.code, "rate_limited" | "license_limit") -} - -/// Advance a running team after its current execution reaches a terminal state. -/// -/// Safe to call concurrently from every API replica: a per-run lease makes all but one -/// caller a no-op, step transitions are conditional (`WHERE status = 'running'`) and -/// `team_steps` is unique on `(run_id, step_index)`. -/// -/// The state machine is resumable. If a tick dies after finishing a step but before the -/// next one exists, the next tick sees "last step succeeded, run still running" and -/// continues from there; a run is never stranded in that state. -pub async fn advance(state: &AppState, run: TeamRun) -> anyhow::Result<()> { - // Most ticks find the current step still working. Check that with two reads before - // taking the lease, which costs two writes per run per tick on every replica (#305). - // The claimed path re-reads everything, so a stale answer here only delays a tick. - if !has_work(state, &run).await? { - return Ok(()); - } - let Some((run, lease)) = state - .store - .claim_team_run_advance(run.id, ADVANCE_LEASE_SECS) - .await? - else { - return Ok(()); - }; - let result = advance_claimed(state, run.clone()).await; - if let Err(error) = state.store.release_team_run_advance(run.id, lease).await { - tracing::warn!(%error, run_id = %run.id, "failed to release team run advance lease"); - } - result -} - -/// Whether advancing `run` can change anything: false while its current step's execution -/// is still running (or there is no step yet). -async fn has_work(state: &AppState, run: &TeamRun) -> anyhow::Result { - if let Some(definition) = run_definition(run) { - if let Some(workflow) = definition.workflow() { - return crate::team_workflow::has_work(state, run, workflow).await; - } - } - let Some(current) = state.store.current_team_step(run.id).await? else { - return Ok(false); - }; - if current.status != "running" { - return Ok(true); - } - let Some(execution_id) = current.execution_id else { - return Ok(false); - }; - let execution = state.store.get_execution_by_id(execution_id).await?; - Ok(matches!( - orbit_domain::ExecutionStatus::parse(&execution.status), - Some(status) if status.is_terminal() - )) -} - -/// The definition a run was started with, when the run carries a readable snapshot. -fn run_definition(run: &TeamRun) -> Option { - serde_json::from_value(run.input.get("definition")?.clone()).ok() -} - -async fn advance_claimed(state: &AppState, run: TeamRun) -> anyhow::Result<()> { - if let Some(definition) = run_definition(&run) { - if let Some(workflow) = definition.workflow() { - return crate::team_workflow::advance(state, &run, &definition, workflow).await; - } - } - let Some(current) = state.store.current_team_step(run.id).await? else { - return Ok(()); - }; - let definition = match run.input.get("definition").cloned() { - Some(value) => serde_json::from_value::(value) - .map_err(|error| anyhow::anyhow!("team run definition is invalid: {error}"))?, - None => { - let team = state.store.get_agent_team(run.org_id, run.team_id).await?; - parse_definition(&team).map_err(|error| anyhow::anyhow!(error.message))? - } - }; - match current.status.as_str() { - "running" => { - let Some(execution_id) = current.execution_id else { - return Ok(()); - }; - let execution = state.store.get_execution_by_id(execution_id).await?; - if !matches!( - orbit_domain::ExecutionStatus::parse(&execution.status), - Some(status) if status.is_terminal() - ) { - return Ok(()); - } - if execution.status == "succeeded" { - let Some(finished) = state - .store - .finish_team_step(current.id, "succeeded", execution.output.as_ref(), None) - .await? - else { - return Ok(()); - }; - continue_after_success(state, &run, &definition, &finished).await - } else { - let Some(finished) = state - .store - .finish_team_step( - current.id, - "failed", - execution.output.as_ref(), - Some(&execution_error_message(&execution)), - ) - .await? - else { - return Ok(()); - }; - fail_run_for_step(state, &run, &finished).await - } - } - // Resume: the previous tick finished the step but did not get further. - "succeeded" => continue_after_success(state, &run, &definition, ¤t).await, - "failed" => fail_run_for_step(state, &run, ¤t).await, - _ => Ok(()), - } -} - -async fn fail_run_for_step(state: &AppState, run: &TeamRun, step: &TeamStep) -> anyhow::Result<()> { - let message = format!( - "step '{}' finished with {}", - step.name, - step.error.as_deref().unwrap_or("failure") - ); - finalize_run(state, run, "failed", step.output.as_ref(), Some(&message)).await -} - -/// Human-readable reason recorded on a step whose execution ended outside the harness. -pub(crate) fn execution_error_message(execution: &ExecutionRecord) -> String { - execution - .error - .as_ref() - .and_then(|error| error.get("message").and_then(serde_json::Value::as_str)) - .filter(|message| !message.is_empty()) - .map(str::to_string) - .unwrap_or_else(|| "worker failed".into()) -} - -/// Fail the team run whose current step owns an execution ended by the platform (worker -/// restart, lost heartbeat or expired lease). Both writes are conditional, so repeated -/// calls from the heartbeat and reaper paths are safe. -pub(crate) async fn fail_team_run_for_execution( - state: &AppState, - execution: &ExecutionRecord, -) -> anyhow::Result<()> { - let Some(run_id) = execution.team_run_id else { - return Ok(()); - }; - let run = state.store.get_team_run(execution.org_id, run_id).await?; - // A workflow has several steps at once, so find the step by its execution. The run - // fails as a whole and its other executions are asked to stop. - // - // This holds even when a "failed" line leaves the step: the lost worker may have had - // side effects, so nothing is run after it automatically (the same reason a queue - // item is not retried). - if let Some(step) = state.store.team_step_by_execution(execution.id).await? { - if step.run_id == run_id && step.node_id.is_some() { - if !matches!(step.status.as_str(), "running" | "failed") { - return Ok(()); - } - let message = execution_error_message(execution); - let _ = state - .store - .finish_team_step(step.id, "failed", execution.output.as_ref(), Some(&message)) - .await?; - let cancelled = state - .store - .request_team_run_cancel(run.org_id, run.id) - .await?; - announce_cancel(state, run.org_id, &cancelled).await; - state - .store - .close_running_team_steps( - run.id, - "cancelled", - Some("stopped because the run ended"), - ) - .await?; - let error = format!("step '{}' finished with {}", step.name, message); - return finalize_run_no_retry( - state, - &run, - "failed", - execution.output.as_ref(), - Some(&error), - ) - .await; - } - } - let Some(step) = state.store.current_team_step(run_id).await? else { - return Ok(()); - }; - if step.execution_id != Some(execution.id) - || !matches!(step.status.as_str(), "running" | "failed") - { - return Ok(()); - } - let message = execution_error_message(execution); - if step.status == "running" { - // `None` means another caller already finished this step; still finalize the run. - let _ = state - .store - .finish_team_step(step.id, "failed", execution.output.as_ref(), Some(&message)) - .await?; - } - let error = format!("step '{}' finished with {}", step.name, message); - finalize_run_no_retry( - state, - &run, - "failed", - execution.output.as_ref(), - Some(&error), - ) - .await -} - -/// Move a run to a terminal status (conditionally) and close the queue loop. If closing -/// the loop fails the queue item stays `running` with a terminal run; the outcome -/// reconciler (`reconcile_team_outcomes`) retries it on later ticks. -pub(crate) async fn finalize_run( - state: &AppState, - run: &TeamRun, - status: &str, - output: Option<&serde_json::Value>, - error: Option<&str>, -) -> anyhow::Result<()> { - let Some(updated) = state - .store - .finish_team_run(run.id, status, output, error) - .await? - else { - return Ok(()); - }; - crate::team_outcomes::close_queue_loop( - state, - &updated, - status, - updated.output.as_ref(), - updated.error.as_deref(), - ) - .await -} - -/// Same terminal transition as `finalize_run`, but closes the queue item terminal without -/// offering a retry. Used when the platform - not the harness - ended the execution. -async fn finalize_run_no_retry( - state: &AppState, - run: &TeamRun, - status: &str, - output: Option<&serde_json::Value>, - error: Option<&str>, -) -> anyhow::Result<()> { - let Some(updated) = state - .store - .finish_team_run(run.id, status, output, error) - .await? - else { - return Ok(()); - }; - crate::team_outcomes::close_queue_loop_without_retry( - state, - &updated, - status, - updated.output.as_ref(), - updated.error.as_deref(), - ) - .await -} - -async fn continue_after_success( - state: &AppState, - run: &TeamRun, - definition: &TeamDefinition, - finished: &TeamStep, -) -> anyhow::Result<()> { - let next = (finished.step_index as usize) + 1; - if definition.mode == "native" || next >= definition.steps.len() { - return finalize_run(state, run, "succeeded", finished.output.as_ref(), None).await; - } - let created = match start_step(state, run, definition, next, finished.output.as_ref()).await { - Ok(created) => created, - // Refused by the preflight (access lost, unknown harness): fail the run instead of - // retrying the same step every poll. A limit that clears by itself is not a refusal. - Err(error) if error.status.is_client_error() && !is_temporary_limit(&error) => { - return crate::preflight::fail_team_run(state, run, &error).await; - } - Err(error) => { - // The finished step stays `succeeded` and no next step exists, so the next tick - // retries. Give up (fail the run visibly) once the retry window has passed so a - // permanent error (e.g. the agent was deleted) does not retry forever. - let waited = finished - .finished_at - .map(|at| (chrono::Utc::now() - at).num_seconds()) - .unwrap_or(0); - let limited = is_temporary_limit(&error); - let window = if limited { - LIMITED_STEP_RETRY_WINDOW_SECS - } else { - START_STEP_RETRY_WINDOW_SECS - }; - if limited && waited < window { - // Waiting for an hourly quota or the daily licence limit is expected, not - // an error to log on every tick. - tracing::debug!(run_id = %run.id, step = next + 1, reason = %error.message, "team step waits for a limit"); - return Ok(()); - } - if waited >= window { - let message = format!("could not start step {}: {}", next + 1, error.message); - return finalize_run( - state, - run, - "failed", - finished.output.as_ref(), - Some(&message), - ) - .await; - } - return Err(anyhow::anyhow!(error.message)); - } - }; - if let Err(error) = auto_launch_step(state, run, definition, &created, None).await { - fail_run_after_launch_error(state, run, &created, &error).await; - } - Ok(()) -} - -/// A step was created but its worker could not be launched. Nothing would ever claim the -/// queued execution and the next tick sees a step that is already running, so the run is -/// failed now with the launch error instead of waiting for ever (#431). -pub(crate) async fn fail_run_after_launch_error( - state: &AppState, - run: &TeamRun, - step: &TeamStep, - error: &ApiError, -) { - tracing::warn!(run_id = %run.id, step = %step.name, error = %error.message, "team step worker launch failed"); - match state - .store - .request_team_run_cancel(run.org_id, run.id) - .await - { - Ok(cancelled) => announce_cancel(state, run.org_id, &cancelled).await, - Err(cancel_error) => { - tracing::warn!(error = %cancel_error, run_id = %run.id, "failed to cancel executions after a launch error") - } - } - let message = format!( - "could not launch a worker for step '{}': {}", - step.name, error.message - ); - // `finalize_run` also closes the queue item of a queued run, offering a retry. - if let Err(finish_error) = finalize_run(state, run, "failed", None, Some(&message)).await { - tracing::warn!(error = %finish_error, run_id = %run.id, "failed to fail a team run after a launch error"); - } -} - -/// Retry queue outcomes that were never applied (terminal run, item still `running`) and -/// release queue claims that never got a run attached. Called from the team-run loop. -pub async fn reconcile_team_outcomes(state: &AppState) -> anyhow::Result<()> { - for run in state.store.list_team_runs_pending_outcome(50).await? { - if let Err(error) = crate::team_outcomes::close_queue_loop( - state, - &run, - &run.status, - run.output.as_ref(), - run.error.as_deref(), - ) - .await - { - tracing::warn!(%error, run_id = %run.id, "retrying queue outcome failed"); - } - } - let released = state.store.release_stale_team_queue_claims(600).await?; - if released > 0 { - tracing::warn!(released, "released stale team queue claims"); - } - Ok(()) -} - -#[cfg(test)] -mod prompt_separation_tests { - use super::{configured_goal, run_instruction}; - use serde_json::json; - - #[test] - fn run_instruction_is_only_the_explicit_task() { - let unique = "AURORA-259-TEAM-UNIQUE-RUN-INSTRUCTION"; - let configured = "AURORA-259-TEAM-CONFIGURED-GOAL"; - let input = json!({ - "task": unique, - "instructions": configured, - "definition": { "instructions": configured }, - }); - assert_eq!(run_instruction(&input), unique); - assert_eq!(configured_goal(&input), configured); - assert!(!run_instruction(&input).contains(configured)); - } - - #[test] - fn missing_task_does_not_default_to_configured_goal_text() { - let input = json!({ "instructions": "goal" }); - assert_eq!(run_instruction(&input), "Team run"); - assert_eq!(configured_goal(&input), "goal"); - } -} diff --git a/crates/orbit-api/src/handlers/worker_api.rs b/crates/orbit-api/src/handlers/worker_api.rs index 2e22d88f..55c880a0 100644 --- a/crates/orbit-api/src/handlers/worker_api.rs +++ b/crates/orbit-api/src/handlers/worker_api.rs @@ -550,10 +550,7 @@ async fn build_context( let mut sub_spec: AgentSpec = serde_json::from_value(version.spec).map_err(|error| { ApiError::internal(format!("subagent '{name}' spec is invalid: {error}")) })?; - subagent_instructions.insert( - agent_id, - crate::handlers::teams::subagent_instructions(&sub_spec), - ); + subagent_instructions.insert(agent_id, crate::team_runs::subagent_instructions(&sub_spec)); if let Some(override_model) = &subagent_override { override_model.apply(&mut sub_spec.model); } @@ -660,11 +657,7 @@ fn with_subagent_instructions( execution } -type SubagentRef = ( - Uuid, - String, - Option, -); +type SubagentRef = (Uuid, String, Option); fn team_subagents(execution: &ExecutionRecord) -> Vec { execution @@ -690,9 +683,7 @@ fn team_subagents(execution: &ExecutionRecord) -> Vec { } /// The team or step model override the API recorded with a team execution (#305). -fn model_override_in( - value: &serde_json::Value, -) -> Option { +fn model_override_in(value: &serde_json::Value) -> Option { value .get("modelOverride") .filter(|value| !value.is_null()) diff --git a/crates/orbit-api/src/handlers/worker_launches.rs b/crates/orbit-api/src/handlers/worker_launches.rs index 247e8b9c..7655ec05 100644 --- a/crates/orbit-api/src/handlers/worker_launches.rs +++ b/crates/orbit-api/src/handlers/worker_launches.rs @@ -3,8 +3,6 @@ //! The API stores launch intent and status, but never receives Docker socket or //! Kubernetes privileges. The launcher exposes a small internal HTTP surface. -use std::time::Duration; - use axum::extract::{Path, Query, State}; use axum::http::StatusCode; use axum::Extension; @@ -16,293 +14,15 @@ use orbit_security::{AuthContext, Permission}; use orbit_store::WorkerLaunch; use crate::error::ApiError; +use crate::launches::{call_launcher, launch_profile_internal, refresh, stop_launch_internal}; use crate::state::AppState; -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -struct LauncherRequest { - launch_id: Uuid, - profile_id: Uuid, - name: String, - harness_kind: String, - target: String, - execution_driver: String, - image: String, - image_tag: String, - auth_secret_name: Option, - env: serde_json::Value, - resources: serde_json::Value, - api_url: String, - worker_token: String, - worker_id: String, - #[serde(skip_serializing_if = "Option::is_none")] - ca_secret_name: Option, - ca_secret_key: String, - #[serde(skip_serializing_if = "Option::is_none")] - single_execution_id: Option, - /// Execution timeout; the launcher derives the Job `activeDeadlineSeconds` from it. - #[serde(skip_serializing_if = "Option::is_none")] - timeout_seconds: Option, -} - -#[derive(Debug, Deserialize)] -#[serde(rename_all = "camelCase")] -struct LauncherStatus { - status: String, - #[serde(default)] - runtime_id: Option, - #[serde(default)] - worker_id: Option, - #[serde(default)] - error: Option, - #[serde(default)] - termination: Option, -} - #[derive(Debug, Serialize, Deserialize, utoipa::ToSchema)] #[serde(rename_all = "camelCase")] pub struct LaunchLogs { pub logs: String, } -fn launcher(state: &AppState) -> Result<(&str, &str), ApiError> { - match (&state.launcher_url, &state.launcher_token) { - (Some(url), Some(token)) => Ok((url.trim_end_matches('/'), token)), - _ => Err(ApiError::new( - StatusCode::SERVICE_UNAVAILABLE, - "launcher_unavailable", - "no worker launcher is configured for this deployment", - )), - } -} - -async fn call_launcher Deserialize<'de>>( - state: &AppState, - method: reqwest::Method, - path: &str, - body: Option, -) -> Result { - let (url, token) = launcher(state)?; - let client = reqwest::Client::builder() - .timeout(Duration::from_secs(20)) - .build() - .map_err(|error| ApiError::internal(error.to_string()))?; - let mut request = client - .request(method, format!("{url}{path}")) - .bearer_auth(token); - if let Some(body) = body { - request = request.json(&body); - } - let response = request.send().await.map_err(|error| { - ApiError::new( - StatusCode::BAD_GATEWAY, - "launcher_error", - format!("worker launcher request failed: {error}"), - ) - })?; - if !response.status().is_success() { - let status = response.status(); - let body = response.text().await.unwrap_or_default(); - return Err(ApiError::new( - StatusCode::BAD_GATEWAY, - "launcher_error", - format!("worker launcher returned {status}: {body}"), - )); - } - response.json().await.map_err(|error| { - ApiError::new(StatusCode::BAD_GATEWAY, "launcher_error", error.to_string()) - }) -} - -pub(crate) async fn refresh(state: &AppState, launch: WorkerLaunch) -> WorkerLaunch { - if !matches!(launch.status.as_str(), "pending" | "starting" | "running") { - return launch; - } - let (url, token) = match (&state.launcher_url, &state.launcher_token) { - (Some(url), Some(token)) => (url.trim_end_matches('/'), token), - _ => return launch, - }; - let client = match reqwest::Client::builder() - .timeout(Duration::from_secs(4)) - .build() - { - Ok(client) => client, - Err(_) => return launch, - }; - let response = client - .get(format!( - "{url}/launches/{}?target={}", - launch.id, launch.target - )) - .bearer_auth(token) - .send() - .await; - let Ok(response) = response else { - return launch; - }; - let Ok(status) = response.json::().await else { - return launch; - }; - let stopped = matches!(status.status.as_str(), "stopped" | "failed"); - let updated = state - .store - .update_worker_launch( - launch.org_id, - launch.id, - &status.status, - status.runtime_id.as_deref(), - status.worker_id.as_deref(), - status.error.as_deref(), - status.status == "running", - stopped, - ) - .await - .unwrap_or(launch); - if updated.status == "failed" { - if let Some(termination) = launch_termination(&status, &updated) { - fail_worker_executions(state, &updated, &termination).await; - } - } - updated -} - -/// Structured termination from the launcher, with a legacy OOM-message fallback for older -/// launchers that only report a human-readable error. -fn launch_termination( - status: &LauncherStatus, - launch: &WorkerLaunch, -) -> Option { - if let Some(termination) = status.termination.clone() { - return Some(termination); - } - let oom = status - .error - .as_deref() - .is_some_and(|error| error.to_lowercase().contains("oom")); - if !oom { - return None; - } - let name = status - .runtime_id - .clone() - .or_else(|| launch.runtime_id.clone()) - .or_else(|| launch.worker_id.clone()) - .unwrap_or_else(|| "unknown-worker".into()); - Some(orbit_contracts::WorkerTermination::new( - orbit_contracts::WorkerTerminationReason::WorkerOom, - name, - )) -} - -/// A worker terminated by the runtime (OOM, eviction, exit or node loss) cannot report its -/// own execution failure. Fail every in-flight execution on that worker with the structured -/// reason, terminate the team step/run/queue without auto-retry, and audit the cause. -async fn fail_worker_executions( - state: &AppState, - launch: &WorkerLaunch, - termination: &orbit_contracts::WorkerTermination, -) { - let Some(worker_id) = launch.worker_id.as_deref() else { - return; - }; - let executions = match state - .store - .active_executions_for_worker(launch.org_id, worker_id) - .await - { - Ok(executions) => executions, - Err(error) => { - tracing::warn!(%error, launch_id = %launch.id, "could not load executions for terminated launch"); - return; - } - }; - let message = launch - .error - .clone() - .unwrap_or_else(|| termination.message()); - let mut data = serde_json::to_value(termination).unwrap_or_else(|_| serde_json::json!({})); - if let Some(object) = data.as_object_mut() { - object.insert( - "code".into(), - serde_json::json!(termination.reason.as_str()), - ); - object.insert("message".into(), serde_json::json!(message)); - object.insert("workerId".into(), serde_json::json!(worker_id)); - object.insert("profileId".into(), serde_json::json!(launch.profile_id)); - object.insert("launchId".into(), serde_json::json!(launch.id)); - // Side effects may already have happened; an operator must decide to rerun. - object.insert("retryable".into(), serde_json::json!(false)); - } - for execution in executions { - let finished = state - .store - .finish_execution( - execution.id, - orbit_domain::ExecutionStatus::Failed, - None, - Some(&data), - None, - execution.session_ref.as_deref(), - ) - .await; - let ended = match finished { - Ok(Some(ended)) => ended, - Ok(None) => { - // Another path already ended it; still make sure the team run is closed. - let mut ended = execution.clone(); - ended.status = orbit_domain::ExecutionStatus::Failed.as_str().into(); - ended.error = Some(data.clone()); - ended - } - Err(error) => { - tracing::warn!(execution_id = %execution.id, %error, "could not fail execution for terminated worker"); - continue; - } - }; - crate::background::report_ended_execution(state, &ended, &message, &data).await; - if let Err(error) = state - .store - .append_audit_log( - launch.org_id, - "system", - None, - None, - termination.reason.audit_action(), - Some("execution"), - Some(execution.id), - data.clone(), - None, - None, - ) - .await - { - tracing::warn!(execution_id = %execution.id, %error, "failed to audit worker termination"); - } - } -} - -/// Background termination poller: refresh live launches so an OOM/eviction/exit is surfaced -/// even when nobody has the Workers page open. Returns false only when the store read fails. -pub async fn refresh_active_launches(state: &AppState) -> bool { - if state.launcher_url.is_none() { - return true; - } - let launches = match state - .store - .list_active_worker_launches_installation(200) - .await - { - Ok(launches) => launches, - Err(error) => { - tracing::warn!(%error, "could not list live worker launches for termination polling"); - return false; - } - }; - let _ = - futures::future::join_all(launches.into_iter().map(|launch| refresh(state, launch))).await; - true -} - /// A launch is exactly as visible as the worker profile it was launched from. Launches /// whose profile no longer exists are visible to owners/admins only. fn launch_visible( @@ -419,216 +139,6 @@ pub async fn get_launch( Ok(Json(refresh(&state, launch).await)) } -#[utoipa::path(post, path = "/api/v1/worker-profiles/{profile_id}/launch", tag = "workers", responses((status = 201, body = WorkerLaunch)))] -pub(crate) async fn launch_profile_internal( - state: &AppState, - auth: &AuthContext, - profile_id: Uuid, - single_execution_id: Option, -) -> Result { - launcher(state)?; - let profile = state - .store - .get_worker_profile(auth.org_id, profile_id) - .await?; - let access = crate::access::AccessScope::load(state, auth).await?; - access.require_view( - "worker profile", - profile.owner_user_id, - profile.owner_team_id, - &profile.visibility, - )?; - if !profile.enabled { - return Err(ApiError::conflict( - "enable the worker profile before launching it", - )); - } - // Reuse an existing live launch for this profile instead of creating a new worker - // for every TeamRun. Single-execution launches are always isolated. - if single_execution_id.is_none() { - if let Some(existing) = state - .store - .find_live_launch_for_profile(auth.org_id, profile.id) - .await? - { - return Ok(existing); - } - } - // Count running workers installation-wide. Held through the launch insert so two - // concurrent launches (manual, team run or dispatcher) cannot exceed the seat count. - let _worker_limit = state.worker_limit_guard().await?; - let issued = - crate::handlers::worker_profiles::issue_profile_token(state, auth.org_id, &profile, false) - .await?; - let image_tag = if profile.image_tag.trim().is_empty() { - crate::images::image_tag() - } else { - profile.image_tag.clone() - }; - let image = format!("{}:{}", profile.image, image_tag); - let launch = match state - .store - .create_worker_launch( - auth.org_id, - profile.id, - &profile.name, - &profile.target, - &image, - Some(issued.token_id), - Some(auth.user_id), - single_execution_id.is_some(), - ) - .await - { - Ok(launch) => launch, - Err(error) => { - let _ = state - .store - .revoke_worker_token(auth.org_id, issued.token_id) - .await; - // Lost the race against a concurrent launch of the same profile: reuse the winner. - if error.is_unique_violation() && single_execution_id.is_none() { - if let Some(existing) = state - .store - .find_live_launch_for_profile(auth.org_id, profile.id) - .await? - { - return Ok(existing); - } - } - return Err(error.into()); - } - }; - let worker_id = launch_worker_id(launch.id); - let mut timeout_seconds = None; - if let Some(execution_id) = single_execution_id { - // Lets the background reaper revoke this launch's token when the execution ends. - state - .store - .set_worker_launch_single_execution(launch.id, execution_id) - .await?; - // Claim and token binding are one statement: a failure between them would leave a - // dispatched execution with a NULL token, which `ensure_execution` treats as a - // legacy claim that any profile-scoped token can access. - let claimed = state - .store - .claim_execution_for_launch(execution_id, &worker_id, issued.token_id) - .await; - let claimed = match claimed { - Ok(Some(claimed)) => claimed, - other => { - // Do not leave a phantom pending launch or an active token behind. - let _ = state - .store - .revoke_worker_token(auth.org_id, issued.token_id) - .await; - let _ = state - .store - .update_worker_launch( - auth.org_id, - launch.id, - "failed", - None, - None, - Some("execution was no longer queued for this launch"), - false, - true, - ) - .await; - other?; - return Err(ApiError::conflict( - "execution is no longer queued for this launch", - )); - } - }; - timeout_seconds = Some(claimed.timeout_seconds.max(1) as u64); - } - let request = LauncherRequest { - launch_id: launch.id, - profile_id: profile.id, - name: profile.name.clone(), - harness_kind: profile.harness_kind.clone(), - target: profile.target.clone(), - execution_driver: profile.execution_driver.clone(), - image: profile.image.clone(), - image_tag, - auth_secret_name: profile.auth_secret_name.clone(), - env: profile.env.clone(), - resources: profile.resources.clone(), - api_url: state.worker_api_url.clone(), - worker_token: issued.token, - worker_id: worker_id.clone(), - ca_secret_name: state.ca_secret_name.clone(), - ca_secret_key: state.ca_secret_key.clone(), - single_execution_id, - timeout_seconds, - }; - let launch_started = std::time::Instant::now(); - let launched = call_launcher( - state, - reqwest::Method::POST, - "/launches", - Some(serde_json::to_value(&request).unwrap_or_default()), - ) - .await; - state - .metrics - .worker_launch_request(launched.is_ok(), launch_started.elapsed()); - let result: LauncherStatus = match launched { - Ok(result) => result, - Err(error) => { - let _ = state - .store - .revoke_worker_token(auth.org_id, issued.token_id) - .await; - let _ = state - .store - .update_worker_launch( - auth.org_id, - launch.id, - "failed", - None, - None, - Some(&error.message), - false, - true, - ) - .await; - if let Some(execution_id) = single_execution_id { - let _ = state - .store - .finish_execution( - execution_id, - orbit_domain::ExecutionStatus::Failed, - None, - Some(&serde_json::json!({ - "code": "launch_failed", - "message": error.message - })), - None, - None, - ) - .await; - } - return Err(error); - } - }; - state - .store - .update_worker_launch( - auth.org_id, - launch.id, - &result.status, - result.runtime_id.as_deref(), - Some(result.worker_id.as_deref().unwrap_or(&worker_id)), - result.error.as_deref(), - true, - false, - ) - .await - .map_err(Into::into) -} - #[utoipa::path(post, path = "/api/v1/worker-profiles/{profile_id}/launch", tag = "workers", responses((status = 201, body = WorkerLaunch)))] pub async fn launch_profile( State(state): State, @@ -653,36 +163,6 @@ pub async fn stop_launch( Ok(Json(stop_launch_internal(&state, &auth, launch).await?)) } -pub(crate) async fn stop_launch_internal( - state: &AppState, - auth: &AuthContext, - launch: WorkerLaunch, -) -> Result { - let _: serde_json::Value = call_launcher( - state, - reqwest::Method::POST, - &format!("/launches/{}/stop?target={}", launch.id, launch.target), - Some(serde_json::json!({})), - ) - .await?; - if let Some(token_id) = launch.worker_token_id { - let _ = state.store.revoke_worker_token(auth.org_id, token_id).await; - } - Ok(state - .store - .update_worker_launch( - auth.org_id, - launch.id, - "stopped", - None, - None, - None, - false, - true, - ) - .await?) -} - #[utoipa::path(get, path = "/api/v1/worker-launches/{launch_id}/logs", tag = "workers", responses((status = 200, body = LaunchLogs)))] pub async fn launch_logs( State(state): State, @@ -731,22 +211,3 @@ pub async fn archive_launch( .await?, )) } - -/// Worker id for a launch: `worker-` plus the full UUID without hyphens. The first 8 hex -/// chars of a UUIDv7 are timestamp bits shared by every launch within ~65 s (issue #106). -pub(crate) fn launch_worker_id(launch_id: uuid::Uuid) -> String { - format!("worker-{}", launch_id.simple()) -} - -#[cfg(test)] -mod worker_id_tests { - use super::launch_worker_id; - - #[test] - fn back_to_back_launches_get_distinct_worker_ids() { - let a = uuid::Uuid::now_v7(); - let b = uuid::Uuid::now_v7(); - assert_ne!(launch_worker_id(a), launch_worker_id(b)); - assert!(launch_worker_id(a).len() <= 63); - } -} diff --git a/crates/orbit-api/src/handlers/worker_profiles.rs b/crates/orbit-api/src/handlers/worker_profiles.rs index 3ddec5bb..fee449b7 100644 --- a/crates/orbit-api/src/handlers/worker_profiles.rs +++ b/crates/orbit-api/src/handlers/worker_profiles.rs @@ -12,6 +12,7 @@ use orbit_store::WorkerProfile; use crate::audit; use crate::error::ApiError; use crate::state::AppState; +use crate::worker_tokens::{issue_profile_token, IssuedWorkerToken}; #[derive(Debug, Clone, Deserialize, utoipa::ToSchema)] #[serde(rename_all = "camelCase")] @@ -351,16 +352,6 @@ pub struct CreateWorkerTokenRequest { pub profile_id: Option, } -#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)] -#[serde(rename_all = "camelCase")] -pub struct IssuedWorkerToken { - pub token: String, - pub token_id: Uuid, - pub profile_id: Option, - pub harnesses: Vec, - pub name: String, -} - #[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)] #[serde(rename_all = "camelCase")] pub struct WorkerTokenView { @@ -374,39 +365,6 @@ pub struct WorkerTokenView { pub created_at: chrono::DateTime, } -pub(crate) async fn issue_profile_token( - state: &AppState, - org_id: Uuid, - profile: &WorkerProfile, - rotate: bool, -) -> Result { - if rotate { - state - .store - .revoke_profile_worker_tokens(org_id, profile.id) - .await?; - } - let issued = issue_worker_token(); - let record = state - .store - .create_worker_token( - org_id, - Some(profile.id), - &format!("profile:{}", profile.name), - &issued.prefix, - &issued.hash, - std::slice::from_ref(&profile.harness_kind), - ) - .await?; - Ok(IssuedWorkerToken { - token: issued.token, - token_id: record.id, - profile_id: record.profile_id, - harnesses: record.harnesses, - name: record.name, - }) -} - #[utoipa::path(post, path = "/api/v1/worker-profiles/{profile_id}/token", tag = "workers", responses((status = 200, body = IssuedWorkerToken)))] pub async fn rotate_token( State(state): State, diff --git a/crates/orbit-api/src/launches.rs b/crates/orbit-api/src/launches.rs new file mode 100644 index 00000000..5a778c25 --- /dev/null +++ b/crates/orbit-api/src/launches.rs @@ -0,0 +1,551 @@ +//! Worker launch lifecycle: calls to the optional `orb-launcher` service, launch status +//! refresh and the executions a terminated launch leaves behind. +//! +//! The API stores launch intent and status, but never receives Docker socket or +//! Kubernetes privileges. The launcher exposes a small internal HTTP surface. + +use crate::error::ApiError; +use crate::state::AppState; +use axum::http::StatusCode; +use orbit_security::AuthContext; +use orbit_store::WorkerLaunch; +use serde::{Deserialize, Serialize}; +use std::time::Duration; +use uuid::Uuid; + +#[derive(Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct LauncherRequest { + launch_id: Uuid, + profile_id: Uuid, + name: String, + harness_kind: String, + target: String, + execution_driver: String, + image: String, + image_tag: String, + auth_secret_name: Option, + env: serde_json::Value, + resources: serde_json::Value, + api_url: String, + worker_token: String, + worker_id: String, + #[serde(skip_serializing_if = "Option::is_none")] + ca_secret_name: Option, + ca_secret_key: String, + #[serde(skip_serializing_if = "Option::is_none")] + single_execution_id: Option, + /// Execution timeout; the launcher derives the Job `activeDeadlineSeconds` from it. + #[serde(skip_serializing_if = "Option::is_none")] + timeout_seconds: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +struct LauncherStatus { + status: String, + #[serde(default)] + runtime_id: Option, + #[serde(default)] + worker_id: Option, + #[serde(default)] + error: Option, + #[serde(default)] + termination: Option, +} + +fn launcher(state: &AppState) -> Result<(&str, &str), ApiError> { + match (&state.launcher_url, &state.launcher_token) { + (Some(url), Some(token)) => Ok((url.trim_end_matches('/'), token)), + _ => Err(ApiError::new( + StatusCode::SERVICE_UNAVAILABLE, + "launcher_unavailable", + "no worker launcher is configured for this deployment", + )), + } +} + +pub(crate) async fn call_launcher Deserialize<'de>>( + state: &AppState, + method: reqwest::Method, + path: &str, + body: Option, +) -> Result { + let (url, token) = launcher(state)?; + let client = reqwest::Client::builder() + .timeout(Duration::from_secs(20)) + .build() + .map_err(|error| ApiError::internal(error.to_string()))?; + let mut request = client + .request(method, format!("{url}{path}")) + .bearer_auth(token); + if let Some(body) = body { + request = request.json(&body); + } + let response = request.send().await.map_err(|error| { + ApiError::new( + StatusCode::BAD_GATEWAY, + "launcher_error", + format!("worker launcher request failed: {error}"), + ) + })?; + if !response.status().is_success() { + let status = response.status(); + let body = response.text().await.unwrap_or_default(); + return Err(ApiError::new( + StatusCode::BAD_GATEWAY, + "launcher_error", + format!("worker launcher returned {status}: {body}"), + )); + } + response.json().await.map_err(|error| { + ApiError::new(StatusCode::BAD_GATEWAY, "launcher_error", error.to_string()) + }) +} + +pub(crate) async fn refresh(state: &AppState, launch: WorkerLaunch) -> WorkerLaunch { + if !matches!(launch.status.as_str(), "pending" | "starting" | "running") { + return launch; + } + let (url, token) = match (&state.launcher_url, &state.launcher_token) { + (Some(url), Some(token)) => (url.trim_end_matches('/'), token), + _ => return launch, + }; + let client = match reqwest::Client::builder() + .timeout(Duration::from_secs(4)) + .build() + { + Ok(client) => client, + Err(_) => return launch, + }; + let response = client + .get(format!( + "{url}/launches/{}?target={}", + launch.id, launch.target + )) + .bearer_auth(token) + .send() + .await; + let Ok(response) = response else { + return launch; + }; + let Ok(status) = response.json::().await else { + return launch; + }; + let stopped = matches!(status.status.as_str(), "stopped" | "failed"); + let updated = state + .store + .update_worker_launch( + launch.org_id, + launch.id, + &status.status, + status.runtime_id.as_deref(), + status.worker_id.as_deref(), + status.error.as_deref(), + status.status == "running", + stopped, + ) + .await + .unwrap_or(launch); + if updated.status == "failed" { + if let Some(termination) = launch_termination(&status, &updated) { + fail_worker_executions(state, &updated, &termination).await; + } + } + updated +} + +/// Structured termination from the launcher, with a legacy OOM-message fallback for older +/// launchers that only report a human-readable error. +fn launch_termination( + status: &LauncherStatus, + launch: &WorkerLaunch, +) -> Option { + if let Some(termination) = status.termination.clone() { + return Some(termination); + } + let oom = status + .error + .as_deref() + .is_some_and(|error| error.to_lowercase().contains("oom")); + if !oom { + return None; + } + let name = status + .runtime_id + .clone() + .or_else(|| launch.runtime_id.clone()) + .or_else(|| launch.worker_id.clone()) + .unwrap_or_else(|| "unknown-worker".into()); + Some(orbit_contracts::WorkerTermination::new( + orbit_contracts::WorkerTerminationReason::WorkerOom, + name, + )) +} + +/// A worker terminated by the runtime (OOM, eviction, exit or node loss) cannot report its +/// own execution failure. Fail every in-flight execution on that worker with the structured +/// reason, terminate the team step/run/queue without auto-retry, and audit the cause. +async fn fail_worker_executions( + state: &AppState, + launch: &WorkerLaunch, + termination: &orbit_contracts::WorkerTermination, +) { + let Some(worker_id) = launch.worker_id.as_deref() else { + return; + }; + let executions = match state + .store + .active_executions_for_worker(launch.org_id, worker_id) + .await + { + Ok(executions) => executions, + Err(error) => { + tracing::warn!(%error, launch_id = %launch.id, "could not load executions for terminated launch"); + return; + } + }; + let message = launch + .error + .clone() + .unwrap_or_else(|| termination.message()); + let mut data = serde_json::to_value(termination).unwrap_or_else(|_| serde_json::json!({})); + if let Some(object) = data.as_object_mut() { + object.insert( + "code".into(), + serde_json::json!(termination.reason.as_str()), + ); + object.insert("message".into(), serde_json::json!(message)); + object.insert("workerId".into(), serde_json::json!(worker_id)); + object.insert("profileId".into(), serde_json::json!(launch.profile_id)); + object.insert("launchId".into(), serde_json::json!(launch.id)); + // Side effects may already have happened; an operator must decide to rerun. + object.insert("retryable".into(), serde_json::json!(false)); + } + for execution in executions { + let finished = state + .store + .finish_execution( + execution.id, + orbit_domain::ExecutionStatus::Failed, + None, + Some(&data), + None, + execution.session_ref.as_deref(), + ) + .await; + let ended = match finished { + Ok(Some(ended)) => ended, + Ok(None) => { + // Another path already ended it; still make sure the team run is closed. + let mut ended = execution.clone(); + ended.status = orbit_domain::ExecutionStatus::Failed.as_str().into(); + ended.error = Some(data.clone()); + ended + } + Err(error) => { + tracing::warn!(execution_id = %execution.id, %error, "could not fail execution for terminated worker"); + continue; + } + }; + crate::background::report_ended_execution(state, &ended, &message, &data).await; + if let Err(error) = state + .store + .append_audit_log( + launch.org_id, + "system", + None, + None, + termination.reason.audit_action(), + Some("execution"), + Some(execution.id), + data.clone(), + None, + None, + ) + .await + { + tracing::warn!(execution_id = %execution.id, %error, "failed to audit worker termination"); + } + } +} + +/// Background termination poller: refresh live launches so an OOM/eviction/exit is surfaced +/// even when nobody has the Workers page open. Returns false only when the store read fails. +pub async fn refresh_active_launches(state: &AppState) -> bool { + if state.launcher_url.is_none() { + return true; + } + let launches = match state + .store + .list_active_worker_launches_installation(200) + .await + { + Ok(launches) => launches, + Err(error) => { + tracing::warn!(%error, "could not list live worker launches for termination polling"); + return false; + } + }; + let _ = + futures::future::join_all(launches.into_iter().map(|launch| refresh(state, launch))).await; + true +} + +#[utoipa::path(post, path = "/api/v1/worker-profiles/{profile_id}/launch", tag = "workers", responses((status = 201, body = WorkerLaunch)))] +pub(crate) async fn launch_profile_internal( + state: &AppState, + auth: &AuthContext, + profile_id: Uuid, + single_execution_id: Option, +) -> Result { + launcher(state)?; + let profile = state + .store + .get_worker_profile(auth.org_id, profile_id) + .await?; + let access = crate::access::AccessScope::load(state, auth).await?; + access.require_view( + "worker profile", + profile.owner_user_id, + profile.owner_team_id, + &profile.visibility, + )?; + if !profile.enabled { + return Err(ApiError::conflict( + "enable the worker profile before launching it", + )); + } + // Reuse an existing live launch for this profile instead of creating a new worker + // for every TeamRun. Single-execution launches are always isolated. + if single_execution_id.is_none() { + if let Some(existing) = state + .store + .find_live_launch_for_profile(auth.org_id, profile.id) + .await? + { + return Ok(existing); + } + } + // Count running workers installation-wide. Held through the launch insert so two + // concurrent launches (manual, team run or dispatcher) cannot exceed the seat count. + let _worker_limit = state.worker_limit_guard().await?; + let issued = + crate::worker_tokens::issue_profile_token(state, auth.org_id, &profile, false).await?; + let image_tag = if profile.image_tag.trim().is_empty() { + crate::images::image_tag() + } else { + profile.image_tag.clone() + }; + let image = format!("{}:{}", profile.image, image_tag); + let launch = match state + .store + .create_worker_launch( + auth.org_id, + profile.id, + &profile.name, + &profile.target, + &image, + Some(issued.token_id), + Some(auth.user_id), + single_execution_id.is_some(), + ) + .await + { + Ok(launch) => launch, + Err(error) => { + let _ = state + .store + .revoke_worker_token(auth.org_id, issued.token_id) + .await; + // Lost the race against a concurrent launch of the same profile: reuse the winner. + if error.is_unique_violation() && single_execution_id.is_none() { + if let Some(existing) = state + .store + .find_live_launch_for_profile(auth.org_id, profile.id) + .await? + { + return Ok(existing); + } + } + return Err(error.into()); + } + }; + let worker_id = launch_worker_id(launch.id); + let mut timeout_seconds = None; + if let Some(execution_id) = single_execution_id { + // Lets the background reaper revoke this launch's token when the execution ends. + state + .store + .set_worker_launch_single_execution(launch.id, execution_id) + .await?; + // Claim and token binding are one statement: a failure between them would leave a + // dispatched execution with a NULL token, which `ensure_execution` treats as a + // legacy claim that any profile-scoped token can access. + let claimed = state + .store + .claim_execution_for_launch(execution_id, &worker_id, issued.token_id) + .await; + let claimed = match claimed { + Ok(Some(claimed)) => claimed, + other => { + // Do not leave a phantom pending launch or an active token behind. + let _ = state + .store + .revoke_worker_token(auth.org_id, issued.token_id) + .await; + let _ = state + .store + .update_worker_launch( + auth.org_id, + launch.id, + "failed", + None, + None, + Some("execution was no longer queued for this launch"), + false, + true, + ) + .await; + other?; + return Err(ApiError::conflict( + "execution is no longer queued for this launch", + )); + } + }; + timeout_seconds = Some(claimed.timeout_seconds.max(1) as u64); + } + let request = LauncherRequest { + launch_id: launch.id, + profile_id: profile.id, + name: profile.name.clone(), + harness_kind: profile.harness_kind.clone(), + target: profile.target.clone(), + execution_driver: profile.execution_driver.clone(), + image: profile.image.clone(), + image_tag, + auth_secret_name: profile.auth_secret_name.clone(), + env: profile.env.clone(), + resources: profile.resources.clone(), + api_url: state.worker_api_url.clone(), + worker_token: issued.token, + worker_id: worker_id.clone(), + ca_secret_name: state.ca_secret_name.clone(), + ca_secret_key: state.ca_secret_key.clone(), + single_execution_id, + timeout_seconds, + }; + let launch_started = std::time::Instant::now(); + let launched = call_launcher( + state, + reqwest::Method::POST, + "/launches", + Some(serde_json::to_value(&request).unwrap_or_default()), + ) + .await; + state + .metrics + .worker_launch_request(launched.is_ok(), launch_started.elapsed()); + let result: LauncherStatus = match launched { + Ok(result) => result, + Err(error) => { + let _ = state + .store + .revoke_worker_token(auth.org_id, issued.token_id) + .await; + let _ = state + .store + .update_worker_launch( + auth.org_id, + launch.id, + "failed", + None, + None, + Some(&error.message), + false, + true, + ) + .await; + if let Some(execution_id) = single_execution_id { + let _ = state + .store + .finish_execution( + execution_id, + orbit_domain::ExecutionStatus::Failed, + None, + Some(&serde_json::json!({ + "code": "launch_failed", + "message": error.message + })), + None, + None, + ) + .await; + } + return Err(error); + } + }; + state + .store + .update_worker_launch( + auth.org_id, + launch.id, + &result.status, + result.runtime_id.as_deref(), + Some(result.worker_id.as_deref().unwrap_or(&worker_id)), + result.error.as_deref(), + true, + false, + ) + .await + .map_err(Into::into) +} + +pub(crate) async fn stop_launch_internal( + state: &AppState, + auth: &AuthContext, + launch: WorkerLaunch, +) -> Result { + let _: serde_json::Value = call_launcher( + state, + reqwest::Method::POST, + &format!("/launches/{}/stop?target={}", launch.id, launch.target), + Some(serde_json::json!({})), + ) + .await?; + if let Some(token_id) = launch.worker_token_id { + let _ = state.store.revoke_worker_token(auth.org_id, token_id).await; + } + Ok(state + .store + .update_worker_launch( + auth.org_id, + launch.id, + "stopped", + None, + None, + None, + false, + true, + ) + .await?) +} + +/// Worker id for a launch: `worker-` plus the full UUID without hyphens. The first 8 hex +/// chars of a UUIDv7 are timestamp bits shared by every launch within ~65 s (issue #106). +pub(crate) fn launch_worker_id(launch_id: uuid::Uuid) -> String { + format!("worker-{}", launch_id.simple()) +} + +#[cfg(test)] +mod worker_id_tests { + use super::launch_worker_id; + + #[test] + fn back_to_back_launches_get_distinct_worker_ids() { + let a = uuid::Uuid::now_v7(); + let b = uuid::Uuid::now_v7(); + assert_ne!(launch_worker_id(a), launch_worker_id(b)); + assert!(launch_worker_id(a).len() <= 63); + } +} diff --git a/crates/orbit-api/src/lib.rs b/crates/orbit-api/src/lib.rs index e3ce3a62..1b942dd4 100644 --- a/crates/orbit-api/src/lib.rs +++ b/crates/orbit-api/src/lib.rs @@ -17,8 +17,10 @@ pub mod error; pub mod extract; pub mod handlers; pub mod images; +pub mod launches; pub mod metrics; pub mod openapi; +pub mod output_delivery; pub mod preflight; pub mod rate_limit; pub mod request_id; @@ -26,10 +28,12 @@ pub mod routes; pub mod state; pub mod supervisor; pub mod team_outcomes; +pub mod team_runs; pub mod team_workflow; pub mod telemetry; pub mod work_sources; pub mod worker_auth; +pub mod worker_tokens; pub use bootstrap::{initialize, Initialized}; pub use config::ApiConfig; diff --git a/crates/orbit-api/src/openapi.rs b/crates/orbit-api/src/openapi.rs index 52660d20..f7369318 100644 --- a/crates/orbit-api/src/openapi.rs +++ b/crates/orbit-api/src/openapi.rs @@ -183,7 +183,7 @@ use crate::handlers; handlers::bulk_lifecycle::BulkLifecycleFailure, handlers::worker_profiles::CreateWorkerProfileRequest, handlers::worker_profiles::CreateWorkerTokenRequest, - handlers::worker_profiles::IssuedWorkerToken, + crate::worker_tokens::IssuedWorkerToken, handlers::worker_profiles::WorkerTokenView, handlers::worker_profiles::WorkerBootstrap, orbit_store::Skill, @@ -211,8 +211,8 @@ use crate::handlers; handlers::teams::CreateTeamRequest, handlers::teams::TeamStepInput, handlers::teams::CreateTeamRunRequest, - handlers::teams::TeamRunDetail, - handlers::teams::TeamModelOverride, + crate::team_runs::TeamRunDetail, + crate::team_runs::TeamModelOverride, orbit_domain::WorkflowDefinition, orbit_domain::WorkflowNode, orbit_domain::WorkflowEdge, diff --git a/crates/orbit-api/src/output_delivery.rs b/crates/orbit-api/src/output_delivery.rs new file mode 100644 index 00000000..df413fe5 --- /dev/null +++ b/crates/orbit-api/src/output_delivery.rs @@ -0,0 +1,643 @@ +//! Output delivery: sending execution and team-run results to Slack, Mattermost, +//! webhooks and Telegram, and the background loop that drains the delivery queue. + +use crate::error::ApiError; +use crate::state::AppState; +use axum::http::StatusCode; +use orbit_contracts::{ + redact_secret, telegram_error, telegram_message_parts, OutputKind, TelegramTarget, +}; +use orbit_domain::ValidationIssue; +use orbit_security::OutboundPolicy; +use orbit_store::outputs::DeliveryOutcome; +use orbit_store::{ExecutionRecord, Output, OutputDeliveryJob, Store, StoreError, TeamRun}; +use uuid::Uuid; + +/// Default Bot API host. Override with `ORBIT_TELEGRAM_API_BASE_URL` only for an explicit +/// admin-controlled proxy or test server; the override is still passed through the outbound +/// URL guard on every request. +const TELEGRAM_API_BASE_URL: &str = "https://api.telegram.org"; + +/// Replace every http(s) URL in an error with ``. Send errors already drop the +/// webhook URL; this also covers rows recorded before that, since the URL is a secret. +pub(crate) fn redact_urls(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + let mut rest = text; + while let Some(start) = ["http://", "https://"] + .iter() + .filter_map(|scheme| rest.find(scheme)) + .min() + { + out.push_str(&rest[..start]); + let tail = &rest[start..]; + let end = tail + .find(|c: char| c.is_whitespace() || matches!(c, ')' | '"' | '\'' | '>' | ',')) + .unwrap_or(tail.len()); + out.push_str(""); + rest = &tail[end..]; + } + out.push_str(rest); + out +} + +/// Why a delivery attempt failed, and whether retrying can help. +#[derive(Debug)] +pub struct SendError { + pub status: Option, + pub message: String, + pub retryable: bool, +} + +/// HTTP statuses worth retrying: server errors, timeouts and rate limits. Other 4xx +/// (bad URL, revoked webhook, rejected payload) will not succeed on retry. +fn status_is_retryable(status: u16) -> bool { + status >= 500 || status == 408 || status == 429 +} + +/// Delivery used by the test endpoint. +pub async fn deliver( + state: &AppState, + output: &Output, + text: &str, + execution: Option<&ExecutionRecord>, + team_run: Option<&TeamRun>, +) -> Result<(), ApiError> { + send(state, output, text, execution, team_run, None, None) + .await + .map_err(|error| { + ApiError::new( + StatusCode::BAD_GATEWAY, + "output_delivery_failed", + error.message, + ) + }) +} + +/// POST one notification. When `delivery_id` is set it is sent as `Idempotency-Key` and +/// `X-Orbit-Delivery-Id` (and `deliveryId` in generic webhook bodies) so receivers can +/// de-duplicate the at-least-once delivery. Telegram/Slack/Mattermost ignore the headers. +pub async fn send( + state: &AppState, + output: &Output, + text: &str, + execution: Option<&ExecutionRecord>, + team_run: Option<&TeamRun>, + delivery_id: Option, + progress: Option>, +) -> Result<(), SendError> { + let kind = OutputKind::parse(&output.kind).ok_or_else(|| SendError { + status: None, + message: format!("unsupported output kind '{}'", output.kind), + retryable: false, + })?; + let secret = match state.store.get_secret_value(&output.secret_ref).await { + Ok(Some(value)) => value.expose().to_string(), + Ok(None) => { + return Err(SendError { + status: None, + message: "output credential is missing".into(), + retryable: false, + }) + } + Err(error) => { + return Err(SendError { + status: None, + message: error.to_string(), + retryable: true, + }) + } + }; + if kind == OutputKind::S3 { + let (config, credentials) = orbit_s3::S3Config::for_output(&output.config, Some(&secret)) + .map_err(|message| SendError { + status: None, + message, + retryable: false, + })?; + let client = orbit_s3::S3Client::new(config, credentials).map_err(|message| SendError { + status: None, + message, + retryable: false, + })?; + let key = format!( + "{}{}.txt", + client.config().key_prefix, + delivery_id.unwrap_or_else(Uuid::now_v7) + ); + client + .put_object(None, &key, text.as_bytes(), "text/plain; charset=utf-8") + .await + .map_err(|error| SendError { + status: error.status, + message: error.message, + retryable: error.retryable, + })?; + return Ok(()); + } + if kind == OutputKind::Telegram { + let target = TelegramTarget::parse( + output.telegram_chat_id.as_deref().unwrap_or(""), + output.telegram_message_thread_id.as_deref(), + ) + .map_err(|message| SendError { + status: None, + message: message.to_string(), + retryable: false, + })?; + return send_telegram_with_progress( + &TelegramEndpoint::from_env(), + &secret, + &target, + text, + delivery_id, + progress, + ) + .await; + } + guard_webhook_url(&secret) + .await + .map_err(|error| SendError { + status: None, + message: error.message, + retryable: false, + })?; + let client = orbit_security::guarded_client(std::time::Duration::from_secs(15)); + let payload = if kind == OutputKind::Webhook { + serde_json::json!({ + "event": execution + .map(|e| format!("execution.{}", e.status)) + .or_else(|| team_run.map(|run| format!("team_run.{}", run.status))) + .unwrap_or_else(|| "test".into()), + "deliveryId": delivery_id, + "text": text, + "execution": execution.map(|e| serde_json::json!({ + "id": e.id, "agentName": e.agent_name, "status": e.status, + "output": e.output, "error": e.error, + })), + "teamRun": team_run.map(|run| serde_json::json!({ + "id": run.id, "teamId": run.team_id, "status": run.status, + "output": run.output, "error": run.error, + })), + }) + } else { + serde_json::json!({ "text": text }) + }; + let mut request = client.post(&secret).json(&payload); + if let Some(id) = delivery_id { + request = request + .header("Idempotency-Key", id.to_string()) + .header("X-Orbit-Delivery-Id", id.to_string()); + } + let response = request.send().await.map_err(|error| SendError { + status: None, + // reqwest errors embed the (secret) webhook URL; strip it. + message: error.without_url().to_string(), + retryable: true, + })?; + let status = response.status(); + if !status.is_success() { + return Err(SendError { + status: Some(status.as_u16()), + message: format!("webhook returned HTTP {status}"), + retryable: status_is_retryable(status.as_u16()), + }); + } + Ok(()) +} + +/// Operator-controlled Telegram endpoint. The base URL defaults to the official Bot API; +/// an admin may set `ORBIT_TELEGRAM_API_BASE_URL` (for a proxy or mock server), but the +/// fully assembled URL is always checked against the outbound policy before any request. +#[derive(Debug, Clone)] +pub struct TelegramEndpoint { + pub base_url: String, + policy: OutboundPolicy, +} + +impl TelegramEndpoint { + pub fn from_env() -> Self { + let base_url = std::env::var("ORBIT_TELEGRAM_API_BASE_URL") + .ok() + .map(|value| value.trim().to_string()) + .filter(|value| !value.is_empty()) + .unwrap_or_else(|| TELEGRAM_API_BASE_URL.to_string()); + Self::new(base_url, OutboundPolicy::from_env()) + } + + pub fn new(base_url: impl Into, policy: OutboundPolicy) -> Self { + Self { + base_url: base_url.into().trim_end_matches('/').to_string(), + policy, + } + } +} + +/// Resume state for a claimed multi-part Telegram delivery. `store` is `None` for direct +/// sends (tests and the test endpoint), which then always start at part zero. +#[derive(Clone, Copy)] +pub struct TelegramProgress<'a> { + pub store: Option<&'a Store>, + pub delivery_id: Uuid, + pub claim_token: Uuid, + pub parts_sent: i32, +} + +/// Send one Telegram notification, splitting long text into multiple `sendMessage` calls. +/// The bot token is only ever used in the request URL, never in errors or diagnostics. +pub async fn send_telegram( + endpoint: &TelegramEndpoint, + bot_token: &str, + target: &TelegramTarget, + text: &str, + delivery_id: Option, +) -> Result<(), SendError> { + send_telegram_with_progress(endpoint, bot_token, target, text, delivery_id, None).await +} + +/// Send a Telegram notification, resuming after the parts already accepted on a previous +/// attempt and durably counting each newly accepted part as it goes. +pub async fn send_telegram_with_progress( + endpoint: &TelegramEndpoint, + bot_token: &str, + target: &TelegramTarget, + text: &str, + delivery_id: Option, + progress: Option>, +) -> Result<(), SendError> { + let url = format!("{}/bot{}/sendMessage", endpoint.base_url, bot_token); + orbit_security::check_outbound_url(&url, &endpoint.policy) + .await + .map_err(|error| SendError { + status: None, + message: format!( + "telegram endpoint refused by outbound policy ({})", + error.category() + ), + retryable: false, + })?; + let client = orbit_security::guarded_client_with_policy( + std::time::Duration::from_secs(15), + endpoint.policy.clone(), + ); + let parts = telegram_message_parts(text, delivery_id); + let resume_after = progress + .as_ref() + .map_or(0, |progress| progress.parts_sent.max(0) as usize); + for (index, part) in parts.iter().enumerate() { + if index < resume_after { + continue; + } + let mut payload = serde_json::json!({ + "chat_id": target.chat_id, + "text": part, + "disable_web_page_preview": true, + }); + if let Some(thread_id) = &target.message_thread_id { + payload["message_thread_id"] = serde_json::Value::String(thread_id.clone()); + } + let mut request = client.post(&url).json(&payload); + if let Some(id) = delivery_id { + request = request + .header("Idempotency-Key", format!("{id}-{index}")) + .header("X-Orbit-Delivery-Id", id.to_string()); + } + let response = request.send().await.map_err(|error| SendError { + status: None, + message: redact_secret(&orbit_security::describe_request_error(&error), bot_token), + retryable: true, + })?; + let status = response.status(); + if !status.is_success() { + let body = response.text().await.unwrap_or_default(); + let description = serde_json::from_str::(&body) + .ok() + .and_then(|value| { + value + .get("description") + .and_then(|description| description.as_str()) + .map(str::to_string) + }); + let mapped = telegram_error(status.as_u16(), description.as_deref(), bot_token); + return Err(SendError { + status: Some(status.as_u16()), + message: mapped.message, + retryable: mapped.retryable, + }); + } + if let Some(progress) = &progress { + let Some(store) = progress.store else { + continue; + }; + match store + .record_output_delivery_part(progress.delivery_id, progress.claim_token) + .await + { + Ok(true) => {} + Ok(false) => { + return Err(SendError { + status: None, + message: "delivery claim lost while sending Telegram part".into(), + retryable: false, + }) + } + Err(error) => { + return Err(SendError { + status: None, + message: format!("could not record Telegram part: {error}"), + retryable: true, + }) + } + } + } + } + Ok(()) +} + +const DELIVERY_LEASE: chrono::Duration = chrono::Duration::seconds(120); + +const MAX_DELIVERIES_PER_TICK: usize = 25; + +/// Background outbox loop: enqueue finished runs, then claim and deliver due rows. +/// +/// Safe to run on every replica and concurrently: rows are claimed one at a time with a +/// lease (`FOR UPDATE SKIP LOCKED`), so each delivery is sent by one worker at a time and a +/// crashed sender's rows are reclaimed after the lease expires (at-least-once). +pub async fn deliver_pending(state: &AppState) { + if let Err(error) = state.store.enqueue_output_deliveries().await { + tracing::error!(%error, "output delivery enqueue failed"); + } + if let Err(error) = state.store.enqueue_team_output_deliveries().await { + tracing::error!(%error, "team output delivery enqueue failed"); + } + for _ in 0..MAX_DELIVERIES_PER_TICK { + let job = match state.store.claim_output_deliveries(1, DELIVERY_LEASE).await { + Ok(mut jobs) => match jobs.pop() { + Some(job) => job, + None => break, + }, + Err(error) => { + tracing::error!(%error, "output delivery claim failed"); + break; + } + }; + process_delivery(state, job).await; + } +} + +async fn process_delivery(state: &AppState, job: OutputDeliveryJob) { + let (outcome, status, error) = attempt_delivery(state, &job).await; + match state + .store + .finish_output_delivery( + job.id, + job.claim_token, + outcome, + status, + error.as_deref(), + job.attempts, + ) + .await + { + Ok(true) => {} + Ok(false) => { + tracing::warn!(delivery_id = %job.id, "output delivery claim lost before finish"); + } + Err(error) => { + // The lease will expire and the row is reclaimed. + tracing::error!(delivery_id = %job.id, %error, "recording output delivery result failed"); + } + } +} + +type AttemptResult = (DeliveryOutcome, Option, Option); + +async fn attempt_delivery(state: &AppState, job: &OutputDeliveryJob) -> AttemptResult { + let skipped = |reason: &str| (DeliveryOutcome::Skipped, None, Some(reason.to_string())); + let retry = |error: StoreError| (DeliveryOutcome::Retry, None, Some(error.to_string())); + let output = match state.store.get_output(job.org_id, job.output_id).await { + Ok(output) if output.enabled => output, + Ok(_) => return skipped("output is disabled"), + Err(StoreError::NotFound(_)) => return skipped("output was deleted"), + Err(error) => return retry(error), + }; + let execution = match job.execution_id { + Some(id) => match state.store.get_execution_by_id_any_org(id).await { + Ok(execution) => Some(execution), + Err(StoreError::NotFound(_)) => return skipped("execution was deleted"), + Err(error) => return retry(error), + }, + None => None, + }; + let team_run = match job.team_run_id { + Some(id) => match state.store.get_team_run_any_org(id).await { + Ok(run) => Some(run), + Err(StoreError::NotFound(_)) => return skipped("team run was deleted"), + Err(error) => return retry(error), + }, + None => None, + }; + let text = execution + .as_ref() + .map(summary) + .or_else(|| team_run.as_ref().map(team_summary)) + .unwrap_or_else(|| "ORBIT run finished".into()); + let text = with_note(text, output.template.as_deref()); + let progress = TelegramProgress { + store: Some(&state.store), + delivery_id: job.id, + claim_token: job.claim_token, + parts_sent: job.parts_sent, + }; + match send( + state, + &output, + &text, + execution.as_ref(), + team_run.as_ref(), + Some(job.id), + Some(progress), + ) + .await + { + Ok(()) => (DeliveryOutcome::Succeeded, None, None), + Err(error) => { + let outcome = if error.retryable { + DeliveryOutcome::Retry + } else { + DeliveryOutcome::Failed + }; + (outcome, error.status.map(i32::from), Some(error.message)) + } + } +} + +/// Append the output's note (stored as `template`) after the run summary, as the UI +/// promises. A blank note adds nothing. +pub(crate) fn with_note(text: String, note: Option<&str>) -> String { + match note.map(str::trim).filter(|note| !note.is_empty()) { + Some(note) => format!("{text}\n\n{note}"), + None => text, + } +} + +fn team_summary(run: &TeamRun) -> String { + let output = run + .output + .as_ref() + .map(|value| { + value + .get("text") + .or_else(|| value.get("summary")) + .and_then(|v| v.as_str()) + .map(str::to_string) + .unwrap_or_else(|| value.to_string()) + }) + .or_else(|| run.error.clone()) + .unwrap_or_else(|| "completed".into()); + let output: String = output.chars().take(3000).collect(); + format!( + "Agent team run {} — {}\n{}", + run.status, + run.input + .get("task") + .and_then(|v| v.as_str()) + .unwrap_or("task"), + output + ) +} + +fn summary(execution: &ExecutionRecord) -> String { + let output = execution + .output + .as_ref() + .map(|value| { + value + .get("text") + .or_else(|| value.get("summary")) + .and_then(|v| v.as_str()) + .map(str::to_string) + .unwrap_or_else(|| value.to_string()) + }) + .or_else(|| execution.error.as_ref().map(|error| error.to_string())) + .unwrap_or_else(|| "completed".into()); + let output: String = output.chars().take(3000).collect(); + format!( + "{} {} — {}\n{}", + execution.agent_name, + execution.status, + execution + .input + .get("task") + .and_then(|v| v.as_str()) + .unwrap_or("task"), + output + ) +} + +/// Refuse webhook targets in loopback, link-local/metadata or other blocked ranges +/// (see `ORBIT_OUTBOUND_*`). Private ranges are allowed by default. +pub(crate) async fn guard_webhook_url(url: &str) -> Result<(), ApiError> { + orbit_security::check_outbound_url(url, &orbit_security::OutboundPolicy::from_env()) + .await + .map_err(|error| { + ApiError::validation(vec![ValidationIssue::new("webhookUrl", error.to_string())]) + }) +} + +pub(crate) async fn guard_credential(kind: OutputKind, value: &str) -> Result<(), ApiError> { + match kind { + OutputKind::Telegram => { + // Telegram tokens are `:`; rejecting URL metacharacters here + // prevents the token from altering the assembled Bot API request path. + let mut parts = value.split(':'); + let id = parts.next().unwrap_or_default(); + let secret = parts.next().unwrap_or_default(); + let valid = !id.is_empty() + && id.bytes().all(|byte| byte.is_ascii_digit()) + && !secret.is_empty() + && secret + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-') + && parts.next().is_none(); + if !valid { + return Err(ApiError::validation(vec![ValidationIssue::new( + "botToken", + "botToken must be a Telegram bot token (numeric id:secret)", + )])); + } + Ok(()) + } + OutputKind::S3 => { + orbit_s3::S3Credentials::from_secret(value).map_err(|message| { + ApiError::validation(vec![ValidationIssue::new("s3Credential", message)]) + })?; + Ok(()) + } + _ => guard_webhook_url(value).await, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn note_is_appended_after_the_summary() { + assert_eq!( + with_note( + "Agent succeeded — task\nDone".into(), + Some(" Ping #release ") + ), + "Agent succeeded — task\nDone\n\nPing #release" + ); + } + + #[test] + fn urls_are_redacted_from_errors() { + assert_eq!( + super::redact_urls( + "error sending request for url (https://hooks.slack.com/services/T/B/secret): timed out" + ), + "error sending request for url (): timed out" + ); + assert_eq!( + super::redact_urls("a http://x/1 and https://y/2"), + "a and " + ); + assert_eq!( + super::redact_urls("webhook returned HTTP 404"), + "webhook returned HTTP 404" + ); + } + + #[test] + fn blank_note_adds_nothing() { + assert_eq!(with_note("summary".into(), None), "summary"); + assert_eq!(with_note("summary".into(), Some(" ")), "summary"); + } + + #[test] + fn telegram_endpoint_defaults_to_the_official_host() { + let endpoint = TelegramEndpoint::new("https://proxy.example/", OutboundPolicy::default()); + assert_eq!(endpoint.base_url, "https://proxy.example"); + } + + #[tokio::test] + async fn telegram_tokens_cannot_alter_the_request_path() { + assert!(guard_credential(OutputKind::Telegram, "123456:ABC_def-1") + .await + .is_ok()); + for token in [ + "123:abc/../../evil", + "123:abc?x=1", + "abc:secret", + "123:", + ":secret", + ] { + assert!( + guard_credential(OutputKind::Telegram, token).await.is_err(), + "{token} must be rejected" + ); + } + } +} diff --git a/crates/orbit-api/src/preflight.rs b/crates/orbit-api/src/preflight.rs index 98bfd7c3..9071031a 100644 --- a/crates/orbit-api/src/preflight.rs +++ b/crates/orbit-api/src/preflight.rs @@ -12,9 +12,11 @@ //! 4. the agent's `autonomy.maxExecutionsPerHour` quota has headroom. //! //! Callers with an HTTP request build the [`AccessScope`] from the request identity. -//! Background callers have no request, so they resolve a stored identity with -//! [`background_access`] (trigger owner, runtime creator, team-run requester) and load -//! its scope with `AccessScope::load_for_user`, i.e. access is re-evaluated at run time. +//! Background callers have no request: trigger fires, runtime ticks and team steps all go +//! through [`evaluate_background`], which resolves a stored identity with +//! [`background_access`] (trigger owner, runtime creator, team-run requester), loads its +//! scope with `AccessScope::load_for_user` (access is re-evaluated at run time) and returns +//! a [`BackgroundVerdict`] the caller maps to its own action. //! //! Other entry points that need the same rules (for example the trigger-create and queue //! visibility fixes in #135 / #132) can call [`Preflight::authorize_access`] or @@ -351,6 +353,86 @@ pub async fn background_access( } } +/// Why a background start should wait instead of being refused. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DelayReason { + /// The harness is disabled or not yet available. + HarnessUnavailable, + /// The agent's `autonomy.maxExecutionsPerHour` quota is used up. + HourlyQuota, +} + +/// The outcome of [`evaluate_background`]. Callers decide what each verdict means for +/// them (fail and audit, halt, skip the tick, retry later). +#[derive(Debug)] +pub enum BackgroundVerdict { + Allowed, + /// The identity could not be loaded or may not run this (access, connections, + /// provider, team use). The error is what the caller reports. + Denied(ApiError), + /// The run is allowed but cannot start now. + Delayed(DelayReason, ApiError), +} + +/// Inputs for [`evaluate_background`]. +pub struct BackgroundPreflight<'a> { + pub state: &'a AppState, + pub org_id: Uuid, + /// Candidate identities, most specific first (see [`background_access`]). + pub owners: &'a [Option], + pub agent: &'a Agent, + pub spec: &'a AgentSpec, + pub harness: HarnessKind, + /// Connections used outside the agent spec (team shared connections, work source). + pub extra_connection_ids: &'a [Uuid], + /// For team steps: the identity must also be able to use the team. + pub team: Option<&'a orbit_store::AgentTeam>, +} + +/// The single preflight for starts without an HTTP caller (trigger fire, runtime tick, +/// team step): load the stored identity, check team use and [`Preflight::authorize_access`] +/// for it, then harness availability and the hourly quota. Unowned (legacy) resources skip +/// the identity checks and run under platform authority. +pub async fn evaluate_background(input: &BackgroundPreflight<'_>) -> BackgroundVerdict { + let access = match background_access(input.state, input.org_id, input.owners).await { + Ok(access) => access, + Err(error) => return BackgroundVerdict::Denied(error), + }; + if let Some(access) = &access { + if let Some(team) = input.team { + if let Err(error) = access.require_use( + "agent team", + team.owner_user_id, + team.owner_team_id, + &team.visibility, + ) { + return BackgroundVerdict::Denied(error); + } + } + let preflight = Preflight { + state: input.state, + org_id: input.org_id, + access, + agent: input.agent, + spec: input.spec, + harness: input.harness, + extra_connection_ids: input.extra_connection_ids, + }; + if let Err(error) = preflight.authorize_access().await { + return BackgroundVerdict::Denied(error); + } + } + if let Err(error) = require_harness_available(input.state, input.org_id, input.harness).await { + return BackgroundVerdict::Delayed(DelayReason::HarnessUnavailable, error); + } + if let Err(error) = + require_hourly_quota(input.state, input.org_id, input.agent.id, input.spec).await + { + return BackgroundVerdict::Delayed(DelayReason::HourlyQuota, error); + } + BackgroundVerdict::Allowed +} + /// The identity a background start acts as when it needs a full [`AuthContext`] (queue /// auto-run, team-step auto-launch): the first of `owners` that is set, loaded from the /// store so the user's current role and status apply. `None` when no owner is set. diff --git a/crates/orbit-api/src/team_outcomes.rs b/crates/orbit-api/src/team_outcomes.rs index c9d8a0f9..31486f8b 100644 --- a/crates/orbit-api/src/team_outcomes.rs +++ b/crates/orbit-api/src/team_outcomes.rs @@ -9,8 +9,8 @@ use serde_json::Value; use orbit_store::team_queue::TeamQueueItem; use orbit_store::TeamRun; -use crate::handlers::teams::{parse_definition, TeamDefinition}; use crate::state::AppState; +use crate::team_runs::{parse_definition, TeamDefinition}; use crate::work_sources::{self, WorkSourceDefinition}; struct WorkSourceConnector { diff --git a/crates/orbit-api/src/team_runs.rs b/crates/orbit-api/src/team_runs.rs new file mode 100644 index 00000000..78a5df98 --- /dev/null +++ b/crates/orbit-api/src/team_runs.rs @@ -0,0 +1,1446 @@ +//! Team runs: the run definition, the step lifecycle and the run state machine. +//! +//! Background loops (`background.rs`, `dispatcher.rs`, `team_outcomes.rs`) and the HTTP +//! handlers (the `teams` and `team_queue` handler modules) both drive runs through this module, +//! so orchestration does not depend on the HTTP layer. + +use crate::error::ApiError; +use crate::state::AppState; +use crate::work_sources::{RepositorySpec, WorkSourceDefinition}; +use orbit_domain::{ + HarnessKind, TeamAutonomy, TeamAutonomyMode, TriggerSource, ValidationIssue, + WorkflowDefinition, WorkflowNode, WORKFLOW_MODE, +}; +use orbit_security::AuthContext; +use orbit_store::team_queue::TeamQueueItem; +use orbit_store::{AgentTeam, ExecutionRecord, TeamRun, TeamStep}; +use serde::{Deserialize, Serialize}; +use uuid::Uuid; + +/// The explicit run instruction is the only text presented as the task to the harness. +fn run_instruction(run_input: &serde_json::Value) -> &str { + run_input + .get("task") + .and_then(serde_json::Value::as_str) + .unwrap_or("Team run") +} + +/// Team goal/instructions are configuration. They travel as trusted system context, +/// never as part of the run instruction. +fn configured_goal(run_input: &serde_json::Value) -> &str { + run_input + .get("instructions") + .and_then(serde_json::Value::as_str) + .unwrap_or("") +} + +#[derive(Debug, Clone, Serialize, utoipa::ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct TeamRunDetail { + pub run: TeamRun, + pub steps: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TeamDefinition { + #[serde(default = "default_mode")] + pub mode: String, + #[serde(default)] + pub instructions: String, + #[serde(default)] + pub repository: Option, + #[serde(default)] + pub branch: Option, + #[serde(default)] + pub work_source: Option, + #[serde(default)] + pub repositories: Vec, + #[serde(default)] + pub worker_profile_id: Option, + #[serde(default)] + pub auto_launch: bool, + #[serde(default)] + pub skills: Vec, + #[serde(default)] + pub harness: Option, + #[serde(default)] + pub connection_ids: Vec, + #[serde(default)] + pub env_mapping_ids: Vec, + #[serde(default)] + pub model: Option, + /// Wall-clock timeout for each step. Defaults to 1 hour for team runs. + #[serde(default)] + pub timeout_seconds: Option, + /// Explicit team autonomy. Missing means follow each step agent's level. + #[serde(default)] + pub autonomy: Option, + /// The agents in order. For a workflow: every agent it uses, once. + #[serde(default)] + pub steps: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub workflow: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct TeamModelOverride { + #[serde(default)] + pub provider: Option, + #[serde(default)] + pub model: Option, + #[serde(default)] + pub management: Option, +} + +impl TeamModelOverride { + /// Apply the override to an agent's model settings. Fields the override leaves out + /// keep the agent's own value. + pub(crate) fn apply(&self, model: &mut orbit_domain::ModelSpec) { + if let Some(provider) = &self.provider { + model.provider = Some(provider.clone()); + } + if let Some(value) = &self.model { + model.model = Some(value.clone()); + } + if let Some(management) = &self.management { + model.management = match management.as_str() { + "platform" => orbit_domain::ModelManagement::Platform, + _ => orbit_domain::ModelManagement::Harness, + }; + } + } +} + +impl TeamDefinition { + /// The graph, when this team runs as a workflow. + pub(crate) fn workflow(&self) -> Option<&WorkflowDefinition> { + if self.mode == WORKFLOW_MODE { + self.workflow.as_ref() + } else { + None + } + } + + /// The model override for a step: the step's own, else the team's. + pub(crate) fn model_override(&self, step_index: usize) -> Option<&TeamModelOverride> { + self.steps + .get(step_index) + .and_then(|step| step.model.as_ref()) + .or(self.model.as_ref()) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TeamStepDefinition { + pub agent_id: Uuid, + #[serde(default)] + pub model: Option, +} + +pub(crate) fn default_mode() -> String { + "pipeline".into() +} + +pub(crate) fn parse_definition(team: &AgentTeam) -> Result { + serde_json::from_value(team.definition.clone()) + .map_err(|error| ApiError::internal(format!("team definition is invalid: {error}"))) +} + +/// Connections a team run injects beyond the agent specs: the team's shared connections +/// and an enabled work source connection. +pub(crate) fn team_connection_ids(definition: &TeamDefinition) -> Vec { + let mut ids = definition.connection_ids.clone(); + if let Some(source) = &definition.work_source { + if source.enabled { + ids.extend(source.connection_id); + } + } + ids +} + +/// A caller-supplied repository must be one of the team's configured repositories; the +/// run injects the team's connection credentials, so it must not retarget them. +pub(crate) fn validate_requested_repositories( + definition: &TeamDefinition, + payload: &serde_json::Value, +) -> Result<(), ApiError> { + check_requested_repositories(definition, payload, |_| false) +} + +/// The repository rule for queue items (#384): the same targets as a run, plus the +/// projects of a GitLab group work source. `stored` relaxes the group rule for items that +/// are already in the queue (the dispatcher records projects of a group given by numeric +/// id, which cannot be matched by path); callers enqueuing new items get the strict rule. +pub(crate) fn validate_queue_repositories( + definition: &TeamDefinition, + payload: &serde_json::Value, + stored: bool, +) -> Result<(), ApiError> { + check_requested_repositories(definition, payload, |value| { + definition.work_source.as_ref().is_some_and(|source| { + crate::work_sources::group_includes_project(source, value, stored) + }) + }) +} + +fn check_requested_repositories( + definition: &TeamDefinition, + payload: &serde_json::Value, + also_allowed: impl Fn(&str) -> bool, +) -> Result<(), ApiError> { + let mut allowed: Vec = Vec::new(); + allowed.extend(definition.repository.iter().cloned()); + allowed.extend( + definition + .repositories + .iter() + .map(|repository| repository.repository.clone()), + ); + if let Some(source) = &definition.work_source { + allowed.extend(source.repository.iter().cloned()); + allowed.extend(source.project.iter().cloned()); + } + let is_allowed = |value: &str| { + allowed + .iter() + .any(|candidate| candidate.trim().eq_ignore_ascii_case(value.trim())) + || also_allowed(value) + }; + if let Some(repository) = payload.get("repository").and_then(|value| value.as_str()) { + if !is_allowed(repository) { + return Err(ApiError::validation(vec![ValidationIssue::new( + "payload.repository", + "repository is not one of the team's configured repositories", + )])); + } + } + if let Some(items) = payload + .get("repositories") + .and_then(|value| value.as_array()) + { + for (idx, item) in items.iter().enumerate() { + let repository = item + .get("repository") + .and_then(|value| value.as_str()) + .unwrap_or_default(); + if !is_allowed(repository) { + return Err(ApiError::validation(vec![ValidationIssue::new( + format!("payload.repositories[{idx}].repository"), + "repository is not one of the team's configured repositories", + )])); + } + } + } + Ok(()) +} + +/// Tell workers about executions whose cancellation was just requested. Workers also +/// poll the cancel flag, so a lost bus message only delays the stop. +pub(crate) async fn announce_cancel( + state: &AppState, + org_id: Uuid, + executions: &[orbit_store::ExecutionRecord], +) { + for execution in executions { + let event = orbit_contracts::OrbitEvent::new( + orbit_contracts::subjects::EXECUTION_CANCEL, + "orbit-api", + serde_json::json!({ "executionId": execution.id }), + ) + .with_org(org_id); + if let Err(error) = state.bus.publish(event).await { + tracing::warn!(%error, execution_id = %execution.id, "cancel event publish failed; worker polls the cancel flag"); + } + } +} + +/// A subagent's system prompt: its instructions followed by its constraints. Never stored +/// in the run: execution and step input are readable by anyone who can view the team or +/// the primary agent, and a subagent may be private (#429). The worker context adds it +/// when a worker claims the step. +pub(crate) fn subagent_instructions(spec: &orbit_domain::AgentSpec) -> String { + let mut instructions = spec.instructions.system.clone(); + if !spec.instructions.constraints.is_empty() { + instructions.push_str("\n\nConstraints:\n"); + for constraint in &spec.instructions.constraints { + instructions.push_str(&format!("- {constraint}\n")); + } + } + instructions +} + +/// The native subagents of a team, as references: id, name, description and model, but +/// no instructions (see [`subagent_instructions`]). +async fn native_subagents( + state: &AppState, + org_id: Uuid, + definition: &TeamDefinition, +) -> Result, ApiError> { + let mut subagents = Vec::new(); + for (index, step) in definition.steps.iter().enumerate().skip(1) { + let agent = state.store.get_agent(org_id, step.agent_id).await?; + let version = state.store.get_current_version(org_id, &agent).await?; + let mut spec: orbit_domain::AgentSpec = serde_json::from_value(version.spec.clone()) + .map_err(|error| { + ApiError::internal(format!("stored agent spec is invalid: {error}")) + })?; + let model_override = definition.model_override(index).cloned(); + if let Some(override_model) = &model_override { + override_model.apply(&mut spec.model); + } + let model = match (&spec.model.provider, &spec.model.model) { + (Some(provider), Some(model)) if !model.contains('/') => { + Some(format!("{provider}/{model}")) + } + (_, Some(model)) => Some(model.clone()), + _ => None, + }; + subagents.push(serde_json::json!({ + "agentId": agent.id, + "name": agent.name, + "slug": agent.slug, + "description": agent.description, + "model": model, + "modelOverride": model_override, + })); + } + Ok(subagents) +} + +/// The workflow step a team step runs, for [`start_step_with`]. +pub(crate) struct WorkflowStepStart<'a> { + pub node: &'a WorkflowNode, + /// 1 for the first time this workflow step runs in the run. + pub attempt: u32, + /// The deliveries this start takes (`[{ edge, step }]`). + pub activated_by: serde_json::Value, +} + +pub(crate) struct StepStart<'a> { + pub step_index: usize, + pub agent_id: Uuid, + pub model_override: Option, + pub previous_output: Option<&'a serde_json::Value>, + pub workflow: Option>, +} + +/// Start step `step_index` of a pipeline or native run. +/// A step agent whose current policy is stricter than the team's authorised elevation, so +/// the step runs with the stricter policy (#385). +struct AutonomyClamp { + agent_id: Uuid, + agent_name: String, + requested: orbit_domain::AutonomyPolicy, + agent: orbit_domain::AutonomyPolicy, + applied: orbit_domain::AutonomyPolicy, +} + +impl AutonomyClamp { + fn message(&self) -> String { + format!( + "team autonomy limited for agent '{}': the team asks for level {} with approval mode {}, \ + but the agent's own policy (level {}, approval mode {}) is stricter than when the team was \ + authorised; running at level {} with approval mode {}. Re-save the team with manage \ + access to the agent to authorise it again.", + self.agent_name, + self.requested.level, + approval_mode_label(self.requested.approval_mode), + self.agent.level, + approval_mode_label(self.agent.approval_mode), + self.applied.level, + approval_mode_label(self.applied.approval_mode), + ) + } + + fn to_json(&self) -> serde_json::Value { + serde_json::json!({ + "agentId": self.agent_id, + "agentName": self.agent_name, + "requested": self.requested, + "agent": self.agent, + "applied": self.applied, + }) + } +} + +/// The fixed team policy a step execution carries, resolved against the **current** policy +/// of every agent it governs: the step agent, and for a native team every subagent too, +/// because subagents inherit the primary execution's policy. `None` when the team does not +/// fix autonomy. An agent whose policy cannot be read fails the step. +async fn effective_team_autonomy( + state: &AppState, + run: &TeamRun, + definition: &TeamDefinition, + agent_id: Uuid, + spec: &orbit_domain::AgentSpec, + native: bool, +) -> Result)>, ApiError> { + let Some(autonomy) = definition.autonomy.as_ref() else { + return Ok(None); + }; + if autonomy.mode != TeamAutonomyMode::Fixed { + return Ok(None); + } + let mut governed = vec![( + agent_id, + None, + orbit_domain::AutonomyPolicy::of(&spec.autonomy), + )]; + if native { + for step in &definition.steps { + if governed.iter().any(|(id, _, _)| *id == step.agent_id) { + continue; + } + let agent = state.store.get_agent(run.org_id, step.agent_id).await?; + let version = state.store.get_current_version(run.org_id, &agent).await?; + let sub: orbit_domain::AgentSpec = + serde_json::from_value(version.spec).map_err(|error| { + ApiError::internal(format!("stored agent spec is invalid: {error}")) + })?; + governed.push(( + agent.id, + Some(agent.name), + orbit_domain::AutonomyPolicy::of(&sub.autonomy), + )); + } + } + let mut clamps = Vec::new(); + let mut combined: Option = None; + for (id, name, own) in governed { + let applied = match orbit_domain::resolve_team_autonomy(autonomy, id, own) { + orbit_domain::TeamAutonomyResolution::NotFixed => return Ok(None), + orbit_domain::TeamAutonomyResolution::Applies(team) => { + team.policy_for(own).unwrap_or(own) + } + orbit_domain::TeamAutonomyResolution::Clamped { + autonomy: clamped, + requested, + agent, + } => { + let applied = clamped.policy_for(agent).unwrap_or(agent); + clamps.push(AutonomyClamp { + agent_id: id, + agent_name: match name { + Some(name) => name, + None => state.store.get_agent(run.org_id, id).await?.name, + }, + requested, + agent, + applied, + }); + applied + } + }; + combined = Some(match combined { + Some(policy) => policy.stricter_of(&applied), + None => applied, + }); + } + if clamps.is_empty() { + return Ok(Some((autonomy.snapshot(), clamps))); + } + let policy = combined.expect("at least the step agent is governed"); + Ok(Some(( + TeamAutonomy { + mode: TeamAutonomyMode::Fixed, + level: Some(policy.level), + approval_mode: Some(policy.approval_mode), + elevations: Vec::new(), + }, + clamps, + ))) +} + +pub(crate) async fn start_step( + state: &AppState, + run: &TeamRun, + definition: &TeamDefinition, + step_index: usize, + previous_output: Option<&serde_json::Value>, +) -> Result { + let step = definition + .steps + .get(step_index) + .ok_or_else(|| ApiError::internal("team step index out of range"))?; + start_step_with( + state, + run, + definition, + StepStart { + step_index, + agent_id: step.agent_id, + model_override: definition.model_override(step_index).cloned(), + previous_output, + workflow: None, + }, + ) + .await +} + +/// The first steps of a new run. +pub(crate) struct FirstSteps { + /// Every step the run has now. + pub steps: Vec, + /// The steps this call created. The caller launches workers for these only; steps + /// the background loop created were launched by the loop. + pub started: Vec, +} + +/// Start the first step of a new run: step 0 of a pipeline or native team, or the +/// starting steps of a workflow. +pub(crate) async fn start_first_steps( + state: &AppState, + run: &TeamRun, + definition: &TeamDefinition, +) -> Result { + if let Some(workflow) = definition.workflow() { + return crate::team_workflow::start_run(state, run, definition, workflow).await; + } + let step = start_step(state, run, definition, 0, None).await?; + Ok(FirstSteps { + steps: vec![step.clone()], + started: vec![step], + }) +} + +/// Launch the team's worker profile for a step that was just created, when the team asks +/// for that. `auth` is the caller; background starts pass `None`. +pub(crate) async fn auto_launch_step( + state: &AppState, + run: &TeamRun, + definition: &TeamDefinition, + step: &TeamStep, + auth: Option<&AuthContext>, +) -> Result<(), ApiError> { + if !definition.auto_launch { + return Ok(()); + } + let (Some(profile_id), Some(execution_id)) = (definition.worker_profile_id, step.execution_id) + else { + return Ok(()); + }; + let background; + let auth = match auth { + Some(auth) => auth, + None => { + // Later steps start in the background: launch as the run's requester, or the + // team owner when the requester was deleted (`requested_by` is then NULL). + // Never a nil user id: `worker_launches.created_by` is a foreign key (#383). + let team = state.store.get_agent_team(run.org_id, run.team_id).await?; + background = crate::preflight::background_identity( + state, + run.org_id, + &[run.requested_by, team.owner_user_id], + ) + .await? + .ok_or_else(|| { + ApiError::validation(vec![ValidationIssue::new( + "autoLaunch", + "auto-launch needs the run's requester or a team owner", + )]) + })?; + &background + } + }; + crate::launches::launch_profile_internal(state, auth, profile_id, Some(execution_id)).await?; + Ok(()) +} + +pub(crate) async fn start_step_with( + state: &AppState, + run: &TeamRun, + definition: &TeamDefinition, + start: StepStart<'_>, +) -> Result { + // Every team step creates an execution through `create_execution_with_limit`, so + // manual runs, scheduled/queue starts and dispatcher auto-run share the same guard. + let StepStart { + step_index, + agent_id, + model_override, + previous_output, + workflow, + } = start; + let agent = state.store.get_agent(run.org_id, agent_id).await?; + let version = state.store.get_current_version(run.org_id, &agent).await?; + let mut spec: orbit_domain::AgentSpec = serde_json::from_value(version.spec.clone()) + .map_err(|error| ApiError::internal(format!("stored agent spec is invalid: {error}")))?; + + // Apply the step's (or the team's) model override. Preflight checks the provider of + // the overridden model, and the override travels with the execution so the worker + // runs that same model (#305). + if let Some(override_model) = &model_override { + override_model.apply(&mut spec.model); + } + // #259: the run instruction is the single task for every step. The team goal is + // configured system context and the previous step output is delegated context; + // neither is copied into the task the harness presents as user input. + let task = run_instruction(&run.input).to_string(); + // A workflow step adds its own instructions and, when it has outcomes, how to report + // one. Both are configuration, so they travel with the goal as system context. + let instructions = match &workflow { + Some(step) => crate::team_workflow::step_goal(configured_goal(&run.input), step.node), + None => configured_goal(&run.input).to_string(), + }; + let previous = previous_output + .map(|value| value.to_string()) + .unwrap_or_else(|| "null".into()); + let requested_harness = run + .input + .get("payload") + .and_then(|value| value.get("harnessOverride")) + .and_then(|value| value.as_str()) + .or(definition.harness.as_deref()); + let harness_kind = match requested_harness { + Some(value) => value.parse::().map_err(|_| { + ApiError::validation(vec![ValidationIssue::new("harness", "unknown harness")]) + })?, + None => match spec.harness.as_ref().map(|harness| harness.kind) { + Some(kind) => kind, + None => state.default_harness().await.ok_or_else(|| { + ApiError::validation(vec![ValidationIssue::new( + "harness", + "no team harness, legacy agent harness or default harness is configured", + )]) + })?, + }, + }; + // Shared execution preflight (#140), re-evaluated for every step with the identity + // that requested the run (falling back to the team owner). + let team = state.store.get_agent_team(run.org_id, run.team_id).await?; + let team_connections = team_connection_ids(definition); + match crate::preflight::evaluate_background(&crate::preflight::BackgroundPreflight { + state, + org_id: run.org_id, + owners: &[run.requested_by, team.owner_user_id], + agent: &agent, + spec: &spec, + harness: harness_kind, + extra_connection_ids: &team_connections, + team: Some(&team), + }) + .await + { + crate::preflight::BackgroundVerdict::Allowed => {} + crate::preflight::BackgroundVerdict::Denied(error) + | crate::preflight::BackgroundVerdict::Delayed(_, error) => return Err(error), + } + let native = definition.mode == "native"; + if native && harness_kind != HarnessKind::OpenCode { + return Err(ApiError::conflict( + "native Agent Teams currently require an OpenCode primary agent", + )); + } + let mut team_payload = serde_json::json!({ + "runId": run.id, + "mode": definition.mode, + // Configured team instructions, consumed by the worker as system context. + "goal": instructions, + "agent": agent.name, + "stepIndex": step_index, + // Delegated context for later steps; never part of the run instruction. + "previous": previous, + "connectionIds": definition.connection_ids, + // Set server-side like connectionIds; the worker context applies it (#305). + "modelOverride": model_override, + "envMappingIds": definition.env_mapping_ids, + }); + if definition.repositories.len() > 1 { + let manifest = definition + .repositories + .iter() + .map(|repository| { + format!( + "- {} (workspace path: {})", + repository.repository, + if repository.path.is_empty() { + "." + } else { + &repository.path + } + ) + }) + .collect::>() + .join("\n"); + team_payload["workspaceRepositories"] = serde_json::json!(manifest); + } + if let Some(step) = &workflow { + team_payload["step"] = serde_json::json!({ + "id": step.node.id, + "name": step.node.name, + "attempt": step.attempt, + }); + } + if native { + team_payload["subagents"] = + serde_json::Value::Array(native_subagents(state, run.org_id, definition).await?); + } + let mut input = serde_json::json!({ + "task": task, + "payload": { + "teamRunId": run.id, + "stepIndex": step_index, + "agentName": agent.name, + "stepName": workflow.as_ref().map(|step| step.node.name.as_str()), + // Tells the agent (and the mock harness) which run of the step this is. + "stepAttempt": workflow.as_ref().map(|step| step.attempt), + "previous": previous_output, + "repository": run.input.get("payload").and_then(|value| value.get("repository")).cloned(), + "branch": run.input.get("payload").and_then(|value| value.get("branch")).cloned(), + "repositories": run.input.get("payload").and_then(|value| value.get("repositories")).cloned(), + "harnessOverride": run.input.get("payload").and_then(|value| value.get("harnessOverride")).cloned(), + }, + "provenance": { + "source": "team", + "trusted": true, + "subject": run.id, + "receivedAt": chrono::Utc::now(), + }, + "team": team_payload, + }); + // #385: the fixed team policy is resolved against the step agents' current policies, + // so an agent made stricter after the team was saved is never run less strictly. + let mut autonomy_clamps = Vec::new(); + if let Some((autonomy, clamps)) = + effective_team_autonomy(state, run, definition, agent.id, &spec, native).await? + { + input[orbit_domain::TEAM_AUTONOMY_KEY] = + serde_json::to_value(&autonomy).unwrap_or(serde_json::Value::Null); + if !clamps.is_empty() { + input["teamAutonomyClamped"] = + serde_json::Value::Array(clamps.iter().map(AutonomyClamp::to_json).collect()); + } + autonomy_clamps = clamps; + } + // #194: set only here, server-side, after the run was authorised with approvals:decide. + // The worker applies this before the fixed team policy, so a fixed team policy wins. + if run + .input + .get("autoApprove") + .and_then(|value| value.as_bool()) + == Some(true) + { + input[orbit_domain::APPROVAL_OVERRIDE_KEY] = + serde_json::json!(orbit_domain::APPROVAL_OVERRIDE_AUTO); + } + // A workflow step is identified by what it runs, not by the order it was created in: + // a retried start must find the same execution again. + let idempotency_key = match &workflow { + Some(step) => format!("team:{}:{}:{}", run.id, step.node.id, step.attempt), + None => format!("team:{}:{}", run.id, step_index), + }; + let replayed = !autonomy_clamps.is_empty() + && state + .store + .get_execution_by_idempotency_key(run.org_id, &idempotency_key) + .await? + .is_some(); + let execution = state + .create_execution_with_limit(orbit_store::executions::NewExecution { + org_id: run.org_id, + agent_id: agent.id, + agent_version_id: version.id, + agent_name: &agent.name, + harness_kind, + trigger_source: TriggerSource::Manual, + placement: spec + .harness + .as_ref() + .map(|harness| harness.placement.as_str()) + .unwrap_or("auto"), + trigger_id: None, + input, + session_ref: None, + skills: &definition.skills, + timeout_seconds: definition + .timeout_seconds + .unwrap_or_else(|| spec.resources.timeout_seconds.max(3600)), + requested_by: run.requested_by, + idempotency_key: Some(&idempotency_key), + team_run_id: Some(run.id), + team_step_index: Some(step_index as i32), + }) + .await?; + if !replayed { + for clamp in &autonomy_clamps { + if let Err(error) = state + .store + .append_execution_event( + run.org_id, + execution.id, + "log", + orbit_domain::LogLevel::Warn, + &clamp.message(), + &clamp.to_json(), + ) + .await + { + tracing::warn!(%error, execution_id = %execution.id, "could not record the team autonomy clamp"); + } + } + } + if let Some(step) = &workflow { + return Ok(state + .store + .create_workflow_step(orbit_store::agent_teams::NewWorkflowStep { + run_id: run.id, + org_id: run.org_id, + step_index: step_index as i32, + name: &step.node.name, + agent_id: agent.id, + agent_version_id: version.id, + skills: &definition.skills, + input: &execution.input, + execution_id: Some(execution.id), + node_id: &step.node.id, + attempt: step.attempt as i32, + activated_by: &step.activated_by, + }) + .await?); + } + let created = state + .store + .create_team_step( + run.id, + run.org_id, + step_index as i32, + &agent.name, + agent.id, + version.id, + &definition.skills, + &execution.input, + Some(execution.id), + ) + .await?; + Ok(created) +} + +/// How long a replica may hold the per-run advance lease before another may take over. +pub(crate) const ADVANCE_LEASE_SECS: i64 = 120; + +/// How long a run whose next step cannot be started is retried before it is failed. +pub(crate) const START_STEP_RETRY_WINDOW_SECS: i64 = 300; + +/// How long a step held back by an hourly quota or the licence's daily execution limit is +/// retried. Long enough for an hourly quota to clear (#305). +pub(crate) const LIMITED_STEP_RETRY_WINDOW_SECS: i64 = 3_900; + +/// Limits that clear by themselves: the agent's `maxExecutionsPerHour` (429) and the +/// licence's rolling daily execution limit (402). +pub(crate) fn is_temporary_limit(error: &ApiError) -> bool { + matches!(error.code, "rate_limited" | "license_limit") +} + +/// Advance a running team after its current execution reaches a terminal state. +/// +/// Safe to call concurrently from every API replica: a per-run lease makes all but one +/// caller a no-op, step transitions are conditional (`WHERE status = 'running'`) and +/// `team_steps` is unique on `(run_id, step_index)`. +/// +/// The state machine is resumable. If a tick dies after finishing a step but before the +/// next one exists, the next tick sees "last step succeeded, run still running" and +/// continues from there; a run is never stranded in that state. +pub async fn advance(state: &AppState, run: TeamRun) -> anyhow::Result<()> { + // Most ticks find the current step still working. Check that with two reads before + // taking the lease, which costs two writes per run per tick on every replica (#305). + // The claimed path re-reads everything, so a stale answer here only delays a tick. + if !has_work(state, &run).await? { + return Ok(()); + } + let Some((run, lease)) = state + .store + .claim_team_run_advance(run.id, ADVANCE_LEASE_SECS) + .await? + else { + return Ok(()); + }; + let result = advance_claimed(state, run.clone()).await; + if let Err(error) = state.store.release_team_run_advance(run.id, lease).await { + tracing::warn!(%error, run_id = %run.id, "failed to release team run advance lease"); + } + result +} + +/// Whether advancing `run` can change anything: false while its current step's execution +/// is still running (or there is no step yet). +async fn has_work(state: &AppState, run: &TeamRun) -> anyhow::Result { + if let Some(definition) = run_definition(run) { + if let Some(workflow) = definition.workflow() { + return crate::team_workflow::has_work(state, run, workflow).await; + } + } + let Some(current) = state.store.current_team_step(run.id).await? else { + return Ok(false); + }; + if current.status != "running" { + return Ok(true); + } + let Some(execution_id) = current.execution_id else { + return Ok(false); + }; + let execution = state.store.get_execution_by_id(execution_id).await?; + Ok(matches!( + orbit_domain::ExecutionStatus::parse(&execution.status), + Some(status) if status.is_terminal() + )) +} + +/// The definition a run was started with, when the run carries a readable snapshot. +fn run_definition(run: &TeamRun) -> Option { + serde_json::from_value(run.input.get("definition")?.clone()).ok() +} + +async fn advance_claimed(state: &AppState, run: TeamRun) -> anyhow::Result<()> { + if let Some(definition) = run_definition(&run) { + if let Some(workflow) = definition.workflow() { + return crate::team_workflow::advance(state, &run, &definition, workflow).await; + } + } + let Some(current) = state.store.current_team_step(run.id).await? else { + return Ok(()); + }; + let definition = match run.input.get("definition").cloned() { + Some(value) => serde_json::from_value::(value) + .map_err(|error| anyhow::anyhow!("team run definition is invalid: {error}"))?, + None => { + let team = state.store.get_agent_team(run.org_id, run.team_id).await?; + parse_definition(&team).map_err(|error| anyhow::anyhow!(error.message))? + } + }; + match current.status.as_str() { + "running" => { + let Some(execution_id) = current.execution_id else { + return Ok(()); + }; + let execution = state.store.get_execution_by_id(execution_id).await?; + if !matches!( + orbit_domain::ExecutionStatus::parse(&execution.status), + Some(status) if status.is_terminal() + ) { + return Ok(()); + } + if execution.status == "succeeded" { + let Some(finished) = state + .store + .finish_team_step(current.id, "succeeded", execution.output.as_ref(), None) + .await? + else { + return Ok(()); + }; + continue_after_success(state, &run, &definition, &finished).await + } else { + let Some(finished) = state + .store + .finish_team_step( + current.id, + "failed", + execution.output.as_ref(), + Some(&execution_error_message(&execution)), + ) + .await? + else { + return Ok(()); + }; + fail_run_for_step(state, &run, &finished).await + } + } + // Resume: the previous tick finished the step but did not get further. + "succeeded" => continue_after_success(state, &run, &definition, ¤t).await, + "failed" => fail_run_for_step(state, &run, ¤t).await, + _ => Ok(()), + } +} + +async fn fail_run_for_step(state: &AppState, run: &TeamRun, step: &TeamStep) -> anyhow::Result<()> { + let message = format!( + "step '{}' finished with {}", + step.name, + step.error.as_deref().unwrap_or("failure") + ); + finalize_run(state, run, "failed", step.output.as_ref(), Some(&message)).await +} + +/// Human-readable reason recorded on a step whose execution ended outside the harness. +pub(crate) fn execution_error_message(execution: &ExecutionRecord) -> String { + execution + .error + .as_ref() + .and_then(|error| error.get("message").and_then(serde_json::Value::as_str)) + .filter(|message| !message.is_empty()) + .map(str::to_string) + .unwrap_or_else(|| "worker failed".into()) +} + +/// Fail the team run whose current step owns an execution ended by the platform (worker +/// restart, lost heartbeat or expired lease). Both writes are conditional, so repeated +/// calls from the heartbeat and reaper paths are safe. +pub(crate) async fn fail_team_run_for_execution( + state: &AppState, + execution: &ExecutionRecord, +) -> anyhow::Result<()> { + let Some(run_id) = execution.team_run_id else { + return Ok(()); + }; + let run = state.store.get_team_run(execution.org_id, run_id).await?; + // A workflow has several steps at once, so find the step by its execution. The run + // fails as a whole and its other executions are asked to stop. + // + // This holds even when a "failed" line leaves the step: the lost worker may have had + // side effects, so nothing is run after it automatically (the same reason a queue + // item is not retried). + if let Some(step) = state.store.team_step_by_execution(execution.id).await? { + if step.run_id == run_id && step.node_id.is_some() { + if !matches!(step.status.as_str(), "running" | "failed") { + return Ok(()); + } + let message = execution_error_message(execution); + let _ = state + .store + .finish_team_step(step.id, "failed", execution.output.as_ref(), Some(&message)) + .await?; + let cancelled = state + .store + .request_team_run_cancel(run.org_id, run.id) + .await?; + announce_cancel(state, run.org_id, &cancelled).await; + state + .store + .close_running_team_steps( + run.id, + "cancelled", + Some("stopped because the run ended"), + ) + .await?; + let error = format!("step '{}' finished with {}", step.name, message); + return finalize_run_no_retry( + state, + &run, + "failed", + execution.output.as_ref(), + Some(&error), + ) + .await; + } + } + let Some(step) = state.store.current_team_step(run_id).await? else { + return Ok(()); + }; + if step.execution_id != Some(execution.id) + || !matches!(step.status.as_str(), "running" | "failed") + { + return Ok(()); + } + let message = execution_error_message(execution); + if step.status == "running" { + // `None` means another caller already finished this step; still finalize the run. + let _ = state + .store + .finish_team_step(step.id, "failed", execution.output.as_ref(), Some(&message)) + .await?; + } + let error = format!("step '{}' finished with {}", step.name, message); + finalize_run_no_retry( + state, + &run, + "failed", + execution.output.as_ref(), + Some(&error), + ) + .await +} + +/// Move a run to a terminal status (conditionally) and close the queue loop. If closing +/// the loop fails the queue item stays `running` with a terminal run; the outcome +/// reconciler (`reconcile_team_outcomes`) retries it on later ticks. +pub(crate) async fn finalize_run( + state: &AppState, + run: &TeamRun, + status: &str, + output: Option<&serde_json::Value>, + error: Option<&str>, +) -> anyhow::Result<()> { + let Some(updated) = state + .store + .finish_team_run(run.id, status, output, error) + .await? + else { + return Ok(()); + }; + crate::team_outcomes::close_queue_loop( + state, + &updated, + status, + updated.output.as_ref(), + updated.error.as_deref(), + ) + .await +} + +/// Same terminal transition as `finalize_run`, but closes the queue item terminal without +/// offering a retry. Used when the platform - not the harness - ended the execution. +async fn finalize_run_no_retry( + state: &AppState, + run: &TeamRun, + status: &str, + output: Option<&serde_json::Value>, + error: Option<&str>, +) -> anyhow::Result<()> { + let Some(updated) = state + .store + .finish_team_run(run.id, status, output, error) + .await? + else { + return Ok(()); + }; + crate::team_outcomes::close_queue_loop_without_retry( + state, + &updated, + status, + updated.output.as_ref(), + updated.error.as_deref(), + ) + .await +} + +async fn continue_after_success( + state: &AppState, + run: &TeamRun, + definition: &TeamDefinition, + finished: &TeamStep, +) -> anyhow::Result<()> { + let next = (finished.step_index as usize) + 1; + if definition.mode == "native" || next >= definition.steps.len() { + return finalize_run(state, run, "succeeded", finished.output.as_ref(), None).await; + } + let created = match start_step(state, run, definition, next, finished.output.as_ref()).await { + Ok(created) => created, + // Refused by the preflight (access lost, unknown harness): fail the run instead of + // retrying the same step every poll. A limit that clears by itself is not a refusal. + Err(error) if error.status.is_client_error() && !is_temporary_limit(&error) => { + return crate::preflight::fail_team_run(state, run, &error).await; + } + Err(error) => { + // The finished step stays `succeeded` and no next step exists, so the next tick + // retries. Give up (fail the run visibly) once the retry window has passed so a + // permanent error (e.g. the agent was deleted) does not retry forever. + let waited = finished + .finished_at + .map(|at| (chrono::Utc::now() - at).num_seconds()) + .unwrap_or(0); + let limited = is_temporary_limit(&error); + let window = if limited { + LIMITED_STEP_RETRY_WINDOW_SECS + } else { + START_STEP_RETRY_WINDOW_SECS + }; + if limited && waited < window { + // Waiting for an hourly quota or the daily licence limit is expected, not + // an error to log on every tick. + tracing::debug!(run_id = %run.id, step = next + 1, reason = %error.message, "team step waits for a limit"); + return Ok(()); + } + if waited >= window { + let message = format!("could not start step {}: {}", next + 1, error.message); + return finalize_run( + state, + run, + "failed", + finished.output.as_ref(), + Some(&message), + ) + .await; + } + return Err(anyhow::anyhow!(error.message)); + } + }; + if let Err(error) = auto_launch_step(state, run, definition, &created, None).await { + fail_run_after_launch_error(state, run, &created, &error).await; + } + Ok(()) +} + +/// A step was created but its worker could not be launched. Nothing would ever claim the +/// queued execution and the next tick sees a step that is already running, so the run is +/// failed now with the launch error instead of waiting for ever (#431). +pub(crate) async fn fail_run_after_launch_error( + state: &AppState, + run: &TeamRun, + step: &TeamStep, + error: &ApiError, +) { + tracing::warn!(run_id = %run.id, step = %step.name, error = %error.message, "team step worker launch failed"); + match state + .store + .request_team_run_cancel(run.org_id, run.id) + .await + { + Ok(cancelled) => announce_cancel(state, run.org_id, &cancelled).await, + Err(cancel_error) => { + tracing::warn!(error = %cancel_error, run_id = %run.id, "failed to cancel executions after a launch error") + } + } + let message = format!( + "could not launch a worker for step '{}': {}", + step.name, error.message + ); + // `finalize_run` also closes the queue item of a queued run, offering a retry. + if let Err(finish_error) = finalize_run(state, run, "failed", None, Some(&message)).await { + tracing::warn!(error = %finish_error, run_id = %run.id, "failed to fail a team run after a launch error"); + } +} + +/// Retry queue outcomes that were never applied (terminal run, item still `running`) and +/// release queue claims that never got a run attached. Called from the team-run loop. +pub async fn reconcile_team_outcomes(state: &AppState) -> anyhow::Result<()> { + for run in state.store.list_team_runs_pending_outcome(50).await? { + if let Err(error) = crate::team_outcomes::close_queue_loop( + state, + &run, + &run.status, + run.output.as_ref(), + run.error.as_deref(), + ) + .await + { + tracing::warn!(%error, run_id = %run.id, "retrying queue outcome failed"); + } + } + let released = state.store.release_stale_team_queue_claims(600).await?; + if released > 0 { + tracing::warn!(released, "released stale team queue claims"); + } + Ok(()) +} + +/// Claim a queue item, then create and start its TeamRun. +/// +/// The claim (`pending|failed -> running`) is a single conditional UPDATE, so concurrent +/// callers (double click, manual run vs auto-run, two replicas) cannot both start a run. +/// Anything that fails after the claim cancels the run it created (and its queued +/// execution) and puts the item back into `failed`, which is retryable. +pub(crate) async fn start_queue_item( + state: &AppState, + auth: &AuthContext, + team: &AgentTeam, + item: &TeamQueueItem, +) -> Result { + let definition = crate::team_runs::parse_definition(team)?; + let Some(item) = state + .store + .claim_team_queue_item(auth.org_id, item.id) + .await? + else { + return Err(ApiError::conflict( + "queue item is not startable (already running, succeeded or cancelled)", + )); + }; + let task = item + .payload + .get("task") + .and_then(|value| value.as_str()) + .map(str::to_string) + .unwrap_or_else(|| definition.instructions.clone()); + let mut payload = item.payload.clone(); + if !payload.is_object() { + payload = serde_json::json!({}); + } + if let Some(repository) = &item.repository { + payload["repository"] = serde_json::json!(repository); + } + if payload + .get("repository") + .and_then(|value| value.as_str()) + .filter(|value| !value.trim().is_empty()) + .is_none() + { + if let Some(repository) = &definition.repository { + payload["repository"] = serde_json::json!(repository); + } + } + if !definition.repositories.is_empty() && payload.get("repositories").is_none() { + payload["repositories"] = serde_json::json!(definition.repositories); + } + // Items stored before enqueue validated their repository (#384), or written by hand, + // are checked again before the team's credentials are used for them. + if let Err(error) = crate::team_runs::validate_queue_repositories(&definition, &payload, true) { + release_failed_claim(state, auth, &item, None, &error.message).await; + return Err(error); + } + let input = serde_json::json!({ + "task": task, + "instructions": definition.instructions, + "payload": payload, + "definition": definition, + "autoApprove": false, + "queueItemId": item.id, + "externalKey": item.external_key, + }); + // Shared execution preflight (#140) before any run row is created. A refusal ends the + // claim with the reason instead of leaving the item `running` without a run (#383). + let authorized = async { + let access = crate::access::AccessScope::load(state, auth).await?; + let step_agent_ids: Vec = definition.steps.iter().map(|step| step.agent_id).collect(); + crate::preflight::authorize_team_run( + state, + auth.org_id, + &access, + team, + &step_agent_ids, + &crate::team_runs::team_connection_ids(&definition), + ) + .await + } + .await; + if let Err(error) = authorized { + release_failed_claim(state, auth, &item, None, &error.message).await; + return Err(error); + } + let run = match state + .store + .create_team_run(auth.org_id, team.id, &input, Some(auth.user_id)) + .await + { + Ok(run) => run, + Err(error) => { + let error = ApiError::from(error); + release_failed_claim(state, auth, &item, None, &error.message).await; + return Err(error); + } + }; + match start_claimed_run(state, auth, &item, &run, &definition).await { + Ok(steps) => Ok(crate::team_runs::TeamRunDetail { run, steps }), + Err(error) => { + release_failed_claim(state, auth, &item, Some(&run), &error.message).await; + Err(error) + } + } +} + +/// The payload a queue item runs with: its `repository` overrides `payload.repository`. +pub(crate) fn effective_payload( + payload: &serde_json::Value, + repository: Option<&str>, +) -> serde_json::Value { + let mut effective = if payload.is_object() { + payload.clone() + } else { + serde_json::json!({}) + }; + if let Some(repository) = repository.map(str::trim).filter(|value| !value.is_empty()) { + effective["repository"] = serde_json::json!(repository); + } + effective +} + +async fn start_claimed_run( + state: &AppState, + auth: &AuthContext, + item: &TeamQueueItem, + run: &orbit_store::TeamRun, + definition: &crate::team_runs::TeamDefinition, +) -> Result, ApiError> { + if !state + .store + .attach_team_run_to_queue_item(auth.org_id, item.id, run.id) + .await? + { + return Err(ApiError::conflict( + "queue item was cancelled or claimed elsewhere while starting", + )); + } + let first = crate::team_runs::start_first_steps(state, run, definition).await?; + for step in &first.started { + crate::team_runs::auto_launch_step(state, run, definition, step, Some(auth)).await?; + } + Ok(first.steps) +} + +/// Undo a failed start: cancel the run and its not-yet-running execution so nothing +/// executes for an item that is reported as failed, then mark the item retryable. +async fn release_failed_claim( + state: &AppState, + auth: &AuthContext, + item: &TeamQueueItem, + run: Option<&orbit_store::TeamRun>, + message: &str, +) { + if let Some(run) = run { + // A workflow run may have started several steps; stop them all. + match state + .store + .request_team_run_cancel(run.org_id, run.id) + .await + { + Ok(cancelled) => crate::team_runs::announce_cancel(state, run.org_id, &cancelled).await, + Err(error) => { + tracing::warn!(%error, run_id = %run.id, "failed to cancel executions of aborted team run") + } + } + let key = format!("team:{}:0", run.id); + if let Ok(Some(execution)) = state + .store + .get_execution_by_idempotency_key(run.org_id, &key) + .await + { + if let Err(error) = state + .store + .request_execution_cancel(run.org_id, execution.id) + .await + { + tracing::warn!(%error, execution_id = %execution.id, "failed to cancel execution of aborted team run"); + } + } + if let Err(error) = state + .store + .finish_team_run(run.id, "cancelled", None, Some(message)) + .await + { + tracing::warn!(%error, run_id = %run.id, "failed to cancel aborted team run"); + } + } + if let Err(error) = state + .store + .fail_claimed_team_queue_item(auth.org_id, item.id, message) + .await + { + tracing::warn!(%error, queue_item = %item.id, "failed to release queue item claim"); + } +} + +pub(crate) fn approval_mode_label(mode: orbit_domain::ApprovalMode) -> &'static str { + match mode { + orbit_domain::ApprovalMode::Auto => "auto", + orbit_domain::ApprovalMode::Writes => "writes", + orbit_domain::ApprovalMode::Always => "always", + } +} + +#[cfg(test)] +mod prompt_separation_tests { + use super::{configured_goal, run_instruction}; + use serde_json::json; + + #[test] + fn run_instruction_is_only_the_explicit_task() { + let unique = "AURORA-259-TEAM-UNIQUE-RUN-INSTRUCTION"; + let configured = "AURORA-259-TEAM-CONFIGURED-GOAL"; + let input = json!({ + "task": unique, + "instructions": configured, + "definition": { "instructions": configured }, + }); + assert_eq!(run_instruction(&input), unique); + assert_eq!(configured_goal(&input), configured); + assert!(!run_instruction(&input).contains(configured)); + } + + #[test] + fn missing_task_does_not_default_to_configured_goal_text() { + let input = json!({ "instructions": "goal" }); + assert_eq!(run_instruction(&input), "Team run"); + assert_eq!(configured_goal(&input), "goal"); + } +} diff --git a/crates/orbit-api/src/team_workflow.rs b/crates/orbit-api/src/team_workflow.rs index 328c09d7..7a8ec783 100644 --- a/crates/orbit-api/src/team_workflow.rs +++ b/crates/orbit-api/src/team_workflow.rs @@ -6,7 +6,7 @@ //! plan asks for and finishes the run. It never looks at the work itself; the only thing //! it reads from a step's answer is the `OUTCOME:` line the step was told to end with. //! -//! Everything here runs under the per-run advance lease (see `handlers::teams::advance`), +//! Everything here runs under the per-run advance lease (see `team_runs::advance`), //! and every write is conditional or idempotent, so a tick that dies half-way is simply //! repeated: the plan is recomputed from the steps that exist. @@ -19,13 +19,13 @@ use orbit_domain::{ use orbit_store::{TeamRun, TeamStep}; use crate::error::ApiError; -use crate::handlers::teams::{ +use crate::state::AppState; +use crate::team_runs::{ announce_cancel, auto_launch_step, execution_error_message, fail_run_after_launch_error, finalize_run, is_temporary_limit, start_step_with, FirstSteps, StepStart, TeamDefinition, TeamModelOverride, WorkflowStepStart, ADVANCE_LEASE_SECS, LIMITED_STEP_RETRY_WINDOW_SECS, START_STEP_RETRY_WINDOW_SECS, }; -use crate::state::AppState; /// The configured context for one workflow step: the team goal, what this step is for /// and, when the step has outcomes, how to report one. diff --git a/crates/orbit-api/src/worker_tokens.rs b/crates/orbit-api/src/worker_tokens.rs new file mode 100644 index 00000000..e2d16bb2 --- /dev/null +++ b/crates/orbit-api/src/worker_tokens.rs @@ -0,0 +1,50 @@ +//! Issuing worker tokens for worker profiles (bootstrap, rotation and launches). + +use crate::error::ApiError; +use crate::state::AppState; +use orbit_security::issue_worker_token; +use orbit_store::WorkerProfile; +use uuid::Uuid; + +#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)] +#[serde(rename_all = "camelCase")] +pub struct IssuedWorkerToken { + pub token: String, + pub token_id: Uuid, + pub profile_id: Option, + pub harnesses: Vec, + pub name: String, +} + +pub(crate) async fn issue_profile_token( + state: &AppState, + org_id: Uuid, + profile: &WorkerProfile, + rotate: bool, +) -> Result { + if rotate { + state + .store + .revoke_profile_worker_tokens(org_id, profile.id) + .await?; + } + let issued = issue_worker_token(); + let record = state + .store + .create_worker_token( + org_id, + Some(profile.id), + &format!("profile:{}", profile.name), + &issued.prefix, + &issued.hash, + std::slice::from_ref(&profile.harness_kind), + ) + .await?; + Ok(IssuedWorkerToken { + token: issued.token, + token_id: record.id, + profile_id: record.profile_id, + harnesses: record.harnesses, + name: record.name, + }) +} diff --git a/crates/orbit-api/tests/api_integration.rs b/crates/orbit-api/tests/api_integration.rs index 8cd27309..cb0b797a 100644 --- a/crates/orbit-api/tests/api_integration.rs +++ b/crates/orbit-api/tests/api_integration.rs @@ -4396,7 +4396,7 @@ async fn advance_concurrently( let state = state.clone(); let run = run.clone(); tasks.push(tokio::spawn(async move { - orbit_api::handlers::teams::advance(&state, run).await + orbit_api::team_runs::advance(&state, run).await })); } let mut out = Vec::new(); @@ -4458,7 +4458,7 @@ async fn advance_resumes_after_step_finished_without_next_step() { .unwrap() .is_none()); let run = app.store.get_team_run(app.org_id, run_id).await.unwrap(); - orbit_api::handlers::teams::advance(&app.state, run) + orbit_api::team_runs::advance(&app.state, run) .await .unwrap(); assert_eq!(app.store.list_team_steps(run_id).await.unwrap().len(), 2); @@ -4488,7 +4488,7 @@ async fn a_temporary_limit_at_a_later_step_does_not_fail_the_run() { let run_id = start_run(&app, team).await; succeed_current_step(&app, run_id).await; let run = app.store.get_team_run(app.org_id, run_id).await.unwrap(); - orbit_api::handlers::teams::advance(&app.state, run.clone()) + orbit_api::team_runs::advance(&app.state, run.clone()) .await .unwrap(); assert_eq!( @@ -4509,7 +4509,7 @@ async fn a_temporary_limit_at_a_later_step_does_not_fail_the_run() { .execute(&raw_pool().await) .await .unwrap(); - orbit_api::handlers::teams::advance(&app.state, run) + orbit_api::team_runs::advance(&app.state, run) .await .unwrap(); assert_eq!( @@ -4532,7 +4532,7 @@ async fn advancing_a_busy_run_takes_no_lease() { let team = make_team(&app, vec![app.agent_id], json!({})).await; let run_id = start_run(&app, team).await; let run = app.store.get_team_run(app.org_id, run_id).await.unwrap(); - orbit_api::handlers::teams::advance(&app.state, run) + orbit_api::team_runs::advance(&app.state, run) .await .unwrap(); let claimed: Option> = @@ -4566,7 +4566,7 @@ async fn failed_next_step_start_is_retried_then_fails_the_run() { let run = app.store.get_team_run(app.org_id, run_id).await.unwrap(); // Within the retry window: error, run stays running, step stays succeeded (retryable). - assert!(orbit_api::handlers::teams::advance(&app.state, run.clone()) + assert!(orbit_api::team_runs::advance(&app.state, run.clone()) .await .is_err()); let run_now = app.store.get_team_run(app.org_id, run_id).await.unwrap(); @@ -4574,7 +4574,7 @@ async fn failed_next_step_start_is_retried_then_fails_the_run() { let step = app.store.current_team_step(run_id).await.unwrap().unwrap(); assert_eq!(step.status, "succeeded"); // The lease was released, so the next tick retries. - assert!(orbit_api::handlers::teams::advance(&app.state, run.clone()) + assert!(orbit_api::team_runs::advance(&app.state, run.clone()) .await .is_err()); @@ -4584,7 +4584,7 @@ async fn failed_next_step_start_is_retried_then_fails_the_run() { .execute(&raw_pool().await) .await .unwrap(); - orbit_api::handlers::teams::advance(&app.state, run) + orbit_api::team_runs::advance(&app.state, run) .await .unwrap(); let run_now = app.store.get_team_run(app.org_id, run_id).await.unwrap(); @@ -5227,7 +5227,7 @@ async fn terminal_run_with_unclosed_queue_item_is_reconciled() { .status, "running" ); - orbit_api::handlers::teams::reconcile_team_outcomes(&app.state) + orbit_api::team_runs::reconcile_team_outcomes(&app.state) .await .unwrap(); let stored = app @@ -5415,7 +5415,7 @@ async fn outcome_writer_never_contacts_a_foreign_repository() { .await .unwrap() .unwrap(); - orbit_api::handlers::teams::reconcile_team_outcomes(&app.state) + orbit_api::team_runs::reconcile_team_outcomes(&app.state) .await .unwrap(); let stored = app @@ -5512,7 +5512,7 @@ mod output_delivery { use axum::extract::State; use axum::http::HeaderMap; use axum::routing::{post as route_post, put as route_put}; - use orbit_api::handlers::outputs::deliver_pending; + use orbit_api::output_delivery::deliver_pending; use orbit_security::SecretValue; use orbit_store::Output; use std::sync::atomic::{AtomicU16, AtomicU64, Ordering}; @@ -7294,7 +7294,7 @@ async fn termination_poller_ends_dispatched_work_without_the_workers_page() { state.launcher_url = Some(url); state.launcher_token = Some("launcher-token".into()); - assert!(orbit_api::handlers::worker_launches::refresh_active_launches(&state).await); + assert!(orbit_api::launches::refresh_active_launches(&state).await); let execution = app .store @@ -7346,7 +7346,7 @@ async fn a_clean_stop_does_not_fail_the_workers_executions() { let mut state = app.state.clone(); state.launcher_url = Some(url); state.launcher_token = Some("launcher-token".into()); - assert!(orbit_api::handlers::worker_launches::refresh_active_launches(&state).await); + assert!(orbit_api::launches::refresh_active_launches(&state).await); let execution = app .store @@ -12740,9 +12740,7 @@ async fn later_auto_launch_uses_the_team_owner_when_the_requester_is_gone() { .unwrap(); succeed_current_step(&app, run_id).await; let run = app.store.get_team_run(app.org_id, run_id).await.unwrap(); - orbit_api::handlers::teams::advance(&state, run) - .await - .unwrap(); + orbit_api::team_runs::advance(&state, run).await.unwrap(); let run = app.store.get_team_run(app.org_id, run_id).await.unwrap(); assert_eq!(run.status, "running", "{:?}", run.error); @@ -14773,7 +14771,7 @@ async fn finish_workflow_step( .await .unwrap(); let run = app.store.get_team_run(app.org_id, run_id).await.unwrap(); - orbit_api::handlers::teams::advance(&app.state, run) + orbit_api::team_runs::advance(&app.state, run) .await .unwrap(); } @@ -15104,7 +15102,7 @@ async fn a_workflow_run_is_started_once_by_whoever_gets_there_first() { assert!(results.iter().all(|result| result.is_ok()), "{results:?}"); assert_eq!(workflow_trace(&app, run.id).await, ["a#1", "b#1"]); // Planning again changes nothing while both steps work. - orbit_api::handlers::teams::advance(&app.state, run.clone()) + orbit_api::team_runs::advance(&app.state, run.clone()) .await .unwrap(); assert_eq!(app.store.list_team_steps(run.id).await.unwrap().len(), 2); diff --git a/crates/orbit-api/tests/telegram_output.rs b/crates/orbit-api/tests/telegram_output.rs index f03cb866..78012156 100644 --- a/crates/orbit-api/tests/telegram_output.rs +++ b/crates/orbit-api/tests/telegram_output.rs @@ -7,7 +7,7 @@ use std::sync::{Arc, Mutex}; use axum::extract::State; use axum::http::{HeaderMap, StatusCode, Uri}; use axum::Json; -use orbit_api::handlers::outputs::{ +use orbit_api::output_delivery::{ send_telegram, send_telegram_with_progress, TelegramEndpoint, TelegramProgress, }; use orbit_contracts::{TelegramTarget, TELEGRAM_TEXT_LIMIT}; diff --git a/docs/architecture/agent-teams.md b/docs/architecture/agent-teams.md index 8682d0bd..da7451af 100644 --- a/docs/architecture/agent-teams.md +++ b/docs/architecture/agent-teams.md @@ -36,6 +36,11 @@ Agent Team ──ordered agents───────────────┘ `crates/orbit-domain/src/workflow.rs`, the run-time part in `crates/orbit-api/src/team_workflow.rs`; see [decision 0015](../decisions/0015-team-workflows.md). +- **Where the code lives**: the run definition, step starts and the run state machine + are in `crates/orbit-api/src/team_runs.rs`. The HTTP handlers + (`handlers/teams.rs`, `handlers/team_queue.rs`) and the background loops + (`background.rs`, `dispatcher.rs`, `team_outcomes.rs`) both call into it; the loops + never import a handler. - **Per-agent models**: each step already uses its own agent's model. A team-level `model` override applies to all steps, and a step-level `model` override wins over it: `{ "provider": "...", "model": "...", "management": "platform|harness" }`. @@ -48,7 +53,7 @@ Agent Team ──ordered agents───────────────┘ ## Team definition fields -The team `definition` (`TeamDefinition` in `crates/orbit-api/src/handlers/teams.rs`): +The team `definition` (`TeamDefinition` in `crates/orbit-api/src/team_runs.rs`): | Field | Meaning | |---|---| diff --git a/docs/security/threat-analysis.md b/docs/security/threat-analysis.md index 54014589..318c13ab 100644 --- a/docs/security/threat-analysis.md +++ b/docs/security/threat-analysis.md @@ -159,8 +159,8 @@ user-supplied config is covered: |---|---|---| | `probe_endpoint` (`crates/orbit-api/src/handlers/catalog.rs`) | provider `baseUrl` and its models endpoint | Yes, on each probe | | `probe_connection` / `probe_supported_connection` (`crates/orbit-api/src/handlers/catalog.rs`) | connection `baseUrl` or `url` | Yes, on each test; URL fields are also checked when saved | -| Webhook delivery (`crates/orbit-api/src/handlers/outputs.rs`) | write-only webhook URL | Yes, on save and on each delivery | -| `send_telegram` (`crates/orbit-api/src/handlers/outputs.rs`) | `api.telegram.org`, or `ORBIT_TELEGRAM_API_BASE_URL` set by an operator | Yes, on each send; the token is confined to the URL path | +| Webhook delivery (`crates/orbit-api/src/handlers/outputs.rs` on save, `crates/orbit-api/src/output_delivery.rs` on delivery) | write-only webhook URL | Yes, on save and on each delivery | +| `send_telegram` (`crates/orbit-api/src/output_delivery.rs`) | `api.telegram.org`, or `ORBIT_TELEGRAM_API_BASE_URL` set by an operator | Yes, on each send; the token is confined to the URL path | | Work-source dispatcher (`crates/orbit-api/src/dispatcher.rs`, `crates/orbit-api/src/work_sources.rs`) | connection `baseUrl` | Yes, before each dispatch | | Team outcome delivery (`crates/orbit-api/src/team_outcomes.rs`) | connection `baseUrl` | Yes, on each delivery | | Kubernetes client (`crates/orbit-kubernetes/src/lib.rs`) | API server / kubeconfig `server` | Yes, before each request; only Kubernetes `Status` messages are forwarded, never other response bodies | @@ -174,7 +174,7 @@ config, and are deliberately outside the outbound policy: - OIDC discovery (`crates/orbit-api/src/handlers/auth_oidc.rs`) and JWKS fetches (`crates/orbit-security/src/auth.rs`) use `client_with_custom_ca` with the issuer/JWKS URL from `ORBIT_OIDC_ISSUER` / `ORBIT_OIDC_JWKS_URL`; both are cached and rate-bounded. -- Launcher calls (`crates/orbit-api/src/handlers/worker_launches.rs`) use +- Launcher calls (`crates/orbit-api/src/launches.rs`) use `ORBIT_LAUNCHER_URL`; worker → API calls (`services/worker/src/client.rs`) use `ORBIT_API_URL`. - The MCP bridge (`services/worker/src/mcp_broker.rs`)