diff --git a/crates/tinycomputer-engine/src/lib.rs b/crates/tinycomputer-engine/src/lib.rs index 9e38faccd..3fad30b01 100644 --- a/crates/tinycomputer-engine/src/lib.rs +++ b/crates/tinycomputer-engine/src/lib.rs @@ -63,7 +63,8 @@ pub use planner::{ pub use rescue::{Briefing, Guidance, MAX_RESCUE_STEPS, MAX_RESCUES, Rescuer, SCREEN_CHARS}; pub use shape::{Harvest, RECORDS_CHARS, Shaper}; pub use task::{ - BrowserRunner, CaptureFuture, ContinuePaymentRequest, FlowFuture, FlowRunner, MAX_AWAIT_MS, + BrowserRunner, CaptureFuture, ContinuePaymentRequest, FailedStepRecovery, + FailedStepRecoveryFuture, FailedStepRecoveryResult, FlowFuture, FlowRunner, MAX_AWAIT_MS, MAX_TASKS, PausedTaskError, PrepareFuture, SecretHost, SecretTypeRequest, Tasks, TextFuture, capabilities, }; diff --git a/crates/tinycomputer-engine/src/task/mod.rs b/crates/tinycomputer-engine/src/task/mod.rs index 3668d6066..6cd8f0fcf 100644 --- a/crates/tinycomputer-engine/src/task/mod.rs +++ b/crates/tinycomputer-engine/src/task/mod.rs @@ -140,6 +140,46 @@ pub type CaptureFuture = Pin> + Send>> /// or could not be made so; a task goes on either way. pub type PrepareFuture = Pin + Send>>; +/// The remaining work a host may try after Jev and its rescuer cannot finish +/// one top-level step. +#[derive(Debug, Clone)] +pub struct FailedStepRecovery { + /// The task whose browser session is still open. + pub task: TaskId, + /// Redacted context for the failed step. + pub briefing: crate::Briefing, + /// The task's original browser and payment constraints. + pub constraints: TaskConstraints, + /// Actions left in the task budget. + pub remaining_actions: u32, + /// Jev evaluations left in the task budget. + pub remaining_model_calls: u32, + /// Time left in the task budget, when bounded. + pub remaining_ms: Option, +} + +/// What a host's bounded failed-step recovery did. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum FailedStepRecoveryResult { + /// The host completed only the failed step; `TinyComputer` may run its tail. + Completed { + /// Why the host considers that step complete. + reason: String, + /// Browser actions spent while recovering it. + actions: u32, + /// Model calls spent while recovering it. + model_calls: u32, + }, + /// The host could not safely complete the step. + GiveUp { + /// Why recovery stopped. + reason: String, + }, +} + +/// The future returned by [`FlowRunner::recover_failed_step`]. +pub type FailedStepRecoveryFuture = Pin + Send>>; + /// Runs a task's flows, on surfaces that live as long as the task. pub trait FlowRunner: Send + Sync + 'static { /// Runs `request` for `task` within `constraints`, returning `RunFlow`'s @@ -167,6 +207,17 @@ pub trait FlowRunner: Send + Sync + 'static { self.run(task, constraints, request) } + /// Attempts a bounded recovery of one failed top-level step. The caller + /// invokes this only after its configured Jev rescuer gives up or is + /// unavailable. The default preserves the task's failure. + fn recover_failed_step(&self, _request: FailedStepRecovery) -> FailedStepRecoveryFuture { + Box::pin(async { + FailedStepRecoveryResult::GiveUp { + reason: "the host has no failed-step recovery".to_owned(), + } + }) + } + /// The visible text of the task's surface now, to spot a wall only a /// person can pass. Empty by default. fn visible_text(&self, _task: &TaskId) -> TextFuture { diff --git a/crates/tinycomputer-engine/src/task/recovery.rs b/crates/tinycomputer-engine/src/task/recovery.rs index 1bf9f07c4..8a502d5a9 100644 --- a/crates/tinycomputer-engine/src/task/recovery.rs +++ b/crates/tinycomputer-engine/src/task/recovery.rs @@ -5,7 +5,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::time::{Duration, Instant}; use tinycomputer_bus::agent::{Rescue, RescueOutcome, TaskId, TaskStatus}; -use tinycomputer_bus::{Flow, FlowStep, StepOutcome, StepReport}; +use tinycomputer_bus::{Flow, FlowAction, FlowStep, StepOutcome, StepReport}; use tinycomputer_core::Facts; use super::brief::brief; @@ -13,7 +13,9 @@ use super::names::{fact_names, known_names}; use super::publish::publish; use super::store::{Cell, Run}; use super::timing; -use super::{FlowRunner, RESCUE_TIMEOUT_MS, redact_task_data}; +use super::{ + FailedStepRecovery, FailedStepRecoveryResult, FlowRunner, RESCUE_TIMEOUT_MS, redact_task_data, +}; use crate::rescue::{Briefing, Guidance, MAX_RESCUES, Rescuer, resumed}; /// A recoverable failure of a top-level step is first rescued: `Err` holds @@ -35,19 +37,155 @@ pub(super) async fn rescued( else { return Ok(status); }; - let hint = match rescue(cell, runner, run, failed, &reason, reached).await { + let fallback_briefing = + failed_step_briefing(cell, runner, run, failed, &reason, reached.clone()).await; + let mut hint = match rescue(cell, runner, run, failed, &reason, reached).await { Rescued::Run(rescued) => return Err(rescued), Rescued::GaveUp(why) => { format!("the rescuer gave up: {why}; reword the step, split it, or take over") } Rescued::Skipped => hint, }; - Ok(TaskStatus::Failed { + if let Some(briefing) = fallback_briefing + && exact_top_level_tail(&briefing) + { + let (constraints, budget, spent) = { + let Ok(state) = cell.state.lock() else { + return Ok(failed_status(failed, reason, hint)); + }; + (state.constraints.clone(), state.budget, state.spent) + }; + let remaining_actions = budget + .max_actions + .unwrap_or(120) + .saturating_sub(spent.actions); + let remaining_model_calls = budget + .max_model_calls + .unwrap_or(super::DEFAULT_MODEL_CALLS) + .saturating_sub(spent.model_calls); + let remaining_ms = budget + .max_elapsed_ms + .map(|max| max.saturating_sub(spent.elapsed_ms)); + let request = FailedStepRecovery { + task: cell.view.borrow().id.clone(), + briefing: briefing.clone(), + constraints, + remaining_actions, + remaining_model_calls, + remaining_ms, + }; + let timeout_ms = remaining_ms + .unwrap_or(RESCUE_TIMEOUT_MS) + .min(RESCUE_TIMEOUT_MS); + let recovered = tokio::time::timeout( + Duration::from_millis(timeout_ms), + runner.recover_failed_step(request), + ) + .await; + match recovered { + Ok(FailedStepRecoveryResult::Completed { + reason: recovery_reason, + actions, + model_calls: _, + }) => { + let tail = resumed(&briefing, Vec::new(), 0); + // A final failed step has no remaining Run. Letting an empty + // flow reach RunFlow would turn completion into a false failure. + if tail.steps.is_empty() { + return Ok(failed_status( + failed, + reason, + format!( + "{hint}; host recovery completed the last step but no safe tail exists" + ), + )); + } + if let Ok(mut state) = cell.state.lock() { + state.spent.actions = state.spent.actions.saturating_add(actions); + state.rescues.push(Rescue { + step: failed, + failure: reason, + reason: recovery_reason, + steps: Vec::new(), + covers: 0, + outcome: RescueOutcome::Recovered, + }); + } + return Err(Run { + flow: tail, + allow_destructive: run.allow_destructive, + rescue: None, + }); + } + Ok(FailedStepRecoveryResult::GiveUp { reason: why }) => { + hint = format!("{hint}; host recovery gave up: {why}"); + } + Err(_) => { + hint = format!("{hint}; host recovery took too long"); + } + } + } + Ok(failed_status(failed, reason, hint)) +} + +fn failed_status(failed: usize, reason: String, hint: String) -> TaskStatus { + TaskStatus::Failed { step: Some(failed), reason, hint, recoverable: true, - }) + } +} + +/// Builds the same redacted briefing used by Jev's rescuer for the host hook. +async fn failed_step_briefing( + cell: &Cell, + runner: &dyn FlowRunner, + run: &Run, + failed: usize, + failure: &str, + reached: Vec, +) -> Option { + let id = { cell.view.borrow().id.clone() }; + let (facts, goal, earlier, rules, reads) = { + let state = cell.state.lock().ok()?; + ( + state.facts.clone(), + state.goal.clone(), + state.rescues.clone(), + brief(&state).rules, + state.reads.clone(), + ) + }; + briefing( + runner, + RescueContext { + id, + facts, + goal, + flow: run.flow.clone(), + failed, + failure: failure.to_owned(), + reached, + earlier, + rules, + reads, + }, + ) + .await +} + +/// The existing resume operation can preserve this tail exactly only when +/// failure is at a top-level atomic step. A failed branch or loop might have +/// unfinished nested siblings or iterations, so the host must give up. +fn exact_top_level_tail(briefing: &Briefing) -> bool { + let Some(step) = briefing.flow.steps.get(briefing.failed) else { + return false; + }; + !matches!( + step.action(), + FlowAction::If(_) | FlowAction::RepeatUntil(_) | FlowAction::StopBefore(_) + ) } /// What a rescue came to. diff --git a/crates/tinycomputer-engine/src/task/task_tests.rs b/crates/tinycomputer-engine/src/task/task_tests.rs index 61d655f7a..559474523 100644 --- a/crates/tinycomputer-engine/src/task/task_tests.rs +++ b/crates/tinycomputer-engine/src/task/task_tests.rs @@ -39,7 +39,8 @@ use tinycomputer_bus::{ use super::interpret::app_at; use super::publish::next_calls; use super::{ - ContinuePaymentRequest, FlowFuture, FlowRunner, MAX_TASKS, Tasks, capabilities, input_kind, + ContinuePaymentRequest, FailedStepRecovery, FailedStepRecoveryFuture, FailedStepRecoveryResult, + FlowFuture, FlowRunner, MAX_TASKS, Tasks, capabilities, input_kind, }; /// Replies queued in order; a missing reply never resolves, like a flow @@ -73,6 +74,10 @@ struct Script { host_secret: Mutex>, /// The pages loaded while tasks were planned, with their task. opened: Mutex>, + /// The host's response to a failed-step recovery request. + recovery: Mutex>, + /// Recovery requests, including their redacted task context. + recoveries: Mutex>, } impl FlowRunner for Script { @@ -93,6 +98,16 @@ impl FlowRunner for Script { }) } + fn recover_failed_step(&self, request: FailedStepRecovery) -> FailedStepRecoveryFuture { + self.recoveries.lock().unwrap().push(request); + let result = self.recovery.lock().unwrap().take().unwrap_or_else(|| { + FailedStepRecoveryResult::GiveUp { + reason: "no scripted recovery".to_owned(), + } + }); + Box::pin(async move { result }) + } + fn visible_text(&self, _task: &TaskId) -> super::TextFuture { let texts = self.screen.lock().unwrap().clone(); Box::pin(async move { texts }) diff --git a/crates/tinycomputer-engine/src/task/task_tests/rescue_tests.rs b/crates/tinycomputer-engine/src/task/task_tests/rescue_tests.rs index 5ae231799..db5b93c7b 100644 --- a/crates/tinycomputer-engine/src/task/task_tests/rescue_tests.rs +++ b/crates/tinycomputer-engine/src/task/task_tests/rescue_tests.rs @@ -12,6 +12,7 @@ use tinycomputer_bus::{DesktopResponse, FlowStep, FlowStopReason, StepOutcome}; use super::{Script, controller, failed_at_step_two, finished_run, flow, journaled, settle, step}; use crate::planner::{Completion, LanguageModel, Role, Turn}; use crate::rescue::{MAX_RESCUES, Rescuer}; +use crate::task::FailedStepRecoveryResult; use crate::task::Tasks; /// Answers from a queue and records every conversation it was shown. @@ -87,6 +88,101 @@ const TWO_STEPS: &str = r#"{"action": "retry", "reason": "try the button's label const ONE_STEP: &str = r#"{"action": "retry", "reason": "try the button's label", "steps": ["press Search Flights"]}"#; +#[tokio::test] +async fn host_recovery_runs_only_the_failed_top_level_step_tail() { + let (tasks, script) = controller(vec![ + failed_at_step_two(), + finished_run( + FlowStopReason::Completed, + vec![step( + "1", + "do", + "open the cheapest result", + StepOutcome::Done, + "", + )], + &[], + None, + ), + ]); + *script.recovery.lock().unwrap() = Some(FailedStepRecoveryResult::Completed { + reason: "the failed search step completed".to_owned(), + actions: 1, + model_calls: 1, + }); + let original = flow(flights()); + let view = tasks + .start(&StartTaskRequest { + flow: Some(original.clone()), + task: Some("find the cheapest flight".to_owned()), + budget: TaskBudget { + max_actions: Some(9), + max_model_calls: Some(8), + max_elapsed_ms: Some(90_000), + ..TaskBudget::default() + }, + ..StartTaskRequest::default() + }) + .data + .unwrap(); + + assert!(matches!( + settle(&tasks, &view.id).await.status, + TaskStatus::Done { .. } + )); + let requests = script.requests.lock().unwrap(); + assert_eq!(requests.len(), 2); + assert_eq!( + requests[1].flow.steps, + original.steps[2..].to_vec(), + "the completed prefix and recovered step do not replay" + ); + let recoveries = script.recoveries.lock().unwrap(); + assert_eq!(recoveries.len(), 1); + assert_eq!(recoveries[0].remaining_actions, 6); + assert_eq!(recoveries[0].remaining_model_calls, 8); + assert_eq!(recoveries[0].remaining_ms, Some(90_000)); +} + +#[tokio::test] +async fn host_recovery_fails_closed_for_a_nested_failed_step() { + let (tasks, script) = controller(vec![failed_at_step_two()]); + *script.recovery.lock().unwrap() = Some(FailedStepRecoveryResult::Completed { + reason: "must not skip the branch sibling".to_owned(), + actions: 1, + model_calls: 1, + }); + let nested = json!({"app":"browser","steps":[ + "open the shop home page", + {"if":{"condition":"the search form is visible", + "then":["search the shop", "confirm the result"], + "else":["open search", "search the shop"]}}, + {"stop_before":"placing the order"} + ]}); + let view = tasks + .start(&StartTaskRequest { + flow: Some(flow(nested)), + task: Some("buy the listed item".to_owned()), + ..StartTaskRequest::default() + }) + .data + .unwrap(); + + assert!(matches!( + settle(&tasks, &view.id).await.status, + TaskStatus::Failed { .. } + )); + assert_eq!( + script.requests.lock().unwrap().len(), + 1, + "completed prefix runs once" + ); + assert!( + script.recoveries.lock().unwrap().is_empty(), + "a nested sibling cannot be skipped" + ); +} + #[tokio::test] async fn a_failed_step_is_rescued_and_the_task_finishes() { let (tasks, script, model) = rescued(