diff --git a/crates/tinycomputer-engine/src/lib.rs b/crates/tinycomputer-engine/src/lib.rs index 7a97a8fa3..b3d84bad7 100644 --- a/crates/tinycomputer-engine/src/lib.rs +++ b/crates/tinycomputer-engine/src/lib.rs @@ -65,8 +65,9 @@ pub use shape::{Harvest, RECORDS_CHARS, Shaper}; pub use task::{ BrowserRunner, CaptureFuture, ContinuePaidAtShopRequest, ContinuePaymentRequest, FailedStepRecovery, FailedStepRecoveryFuture, FailedStepRecoveryResult, FlowFuture, FlowRunner, - MAX_AWAIT_MS, MAX_TASKS, PausedTaskError, PrepareFuture, SecretHost, SecretTypeRequest, Tasks, - TextFuture, capabilities, + MAX_AWAIT_MS, MAX_TASKS, PausedTaskError, PlanRecoveryFuture, PlanRecoveryRequest, + PlanRecoveryResult, PrepareFuture, SecretHost, SecretTypeRequest, Tasks, TextFuture, + capabilities, }; pub use tinycomputer_bus::DesktopResponse; #[cfg(feature = "desktop")] diff --git a/crates/tinycomputer-engine/src/task/controller.rs b/crates/tinycomputer-engine/src/task/controller.rs index 07f403c9e..59a4da78a 100644 --- a/crates/tinycomputer-engine/src/task/controller.rs +++ b/crates/tinycomputer-engine/src/task/controller.rs @@ -225,7 +225,7 @@ impl Tasks { return self.start_planned(request, facts, task, planner.clone()); } if request.task.is_some() { - return self.register_planless(request); + return self.register_planless(request, facts); } return AgentResponse::err(AgentError::new( "INVALID_REQUEST", diff --git a/crates/tinycomputer-engine/src/task/drive.rs b/crates/tinycomputer-engine/src/task/drive.rs index 70aa7df47..bbfc84cc1 100644 --- a/crates/tinycomputer-engine/src/task/drive.rs +++ b/crates/tinycomputer-engine/src/task/drive.rs @@ -5,6 +5,7 @@ use std::collections::{BTreeMap, VecDeque}; use std::sync::Arc; use std::time::{Duration, Instant}; +use tinycomputer_bus::FLOW_GUIDE; use tinycomputer_bus::agent::{SurfaceKind, TaskConstraints, TaskId, TaskStatus}; use super::artifact::{capture, captured}; @@ -115,20 +116,7 @@ async fn plan_then_drive_with_page( let plan = match outcome { Ok(plan) => plan, Err(reason) => { - // A browser opened while planning has nothing left to do; it is - // let go before the failure is told, as a finished task's is. - runner.release(&id); - publish( - &cell, - TaskStatus::Failed { - step: None, - reason: reason.clone(), - hint: "reword the task, or pass a flow written with Describe's guide" - .to_owned(), - recoverable: true, - }, - &format!("Planning failed: {reason}"), - ); + handle_plan_failure(cell, runner, id, task, reason).await; return; } }; @@ -165,6 +153,78 @@ async fn plan_then_drive_with_page( } } +async fn handle_plan_failure( + cell: Arc, + runner: Arc, + id: TaskId, + task: String, + reason: String, +) { + if let Err(recovery) = + recover_plan_after_planner_failure(cell.clone(), runner.clone(), id.clone(), task).await + { + runner.release(&id); + let failure = format!("{reason}; host planning recovery failed: {recovery}"); + publish( + &cell, + TaskStatus::Failed { + step: None, + reason: failure.clone(), + hint: "reword the task, or pass a flow written with Describe's guide".to_owned(), + recoverable: true, + }, + &format!("Planning failed: {failure}"), + ); + } +} + +async fn recover_plan_after_planner_failure( + cell: Arc, + runner: Arc, + id: TaskId, + task: String, +) -> Result<(), String> { + let plan = super::plan_recovery::host_plan(&cell, runner.as_ref(), task, FLOW_GUIDE.to_owned()) + .await?; + let facts = cell + .state + .lock() + .map_err(|_| "task state is unavailable".to_owned())? + .facts + .clone(); + let known = super::names::known_names(&plan, &facts); + let fact_names = super::names::fact_names(&facts); + let missing = crate::agentic::missing_inputs(&plan, &known, &fact_names); + let allow = { + let mut state = cell + .state + .lock() + .map_err(|_| "task state is unavailable".to_owned())?; + state.flow = plan.clone(); + state.constraints.allow_destructive + }; + if !missing.is_empty() { + runner.release(&id); + publish( + &cell, + super::publish::needs_input(&missing), + "The recovered plan needs caller values before it can start.", + ); + return Ok(()); + } + drive( + cell, + runner, + vec![Run { + flow: plan, + allow_destructive: allow, + rescue: None, + }], + ) + .await; + Ok(()) +} + async fn prepare_page( runner: Arc, id: tinycomputer_bus::agent::TaskId, diff --git a/crates/tinycomputer-engine/src/task/mod.rs b/crates/tinycomputer-engine/src/task/mod.rs index 3881b51d4..ed0fb57a4 100644 --- a/crates/tinycomputer-engine/src/task/mod.rs +++ b/crates/tinycomputer-engine/src/task/mod.rs @@ -50,6 +50,7 @@ mod interpret; mod names; mod page; mod persistence; +mod plan_recovery; mod publish; mod recovery; mod resume; @@ -62,7 +63,7 @@ use std::pin::Pin; use tinycomputer_bus::agent::{TaskConstraints, TaskId}; use tinycomputer_bus::browser::OutputRef; -use tinycomputer_bus::{DesktopResponse, RunFlowRequest}; +use tinycomputer_bus::{DesktopResponse, Flow, RunFlowRequest}; /// Sanitizes every textual representation in a JSON report or model payload /// through the task runner's host secret filter. @@ -180,6 +181,41 @@ pub enum FailedStepRecoveryResult { /// The future returned by [`FlowRunner::recover_failed_step`]. pub type FailedStepRecoveryFuture = Pin + Send>>; +/// The task and constraints a host needs to recover an unavailable plan. +#[derive(Debug, Clone)] +pub struct PlanRecoveryRequest { + /// The task whose browser session is ready for the plan request. + pub task: TaskId, + /// The caller's task description. + pub task_text: String, + /// The guide the caller would otherwise use to supply a flow. + pub guide: String, + /// The task's original browser and payment constraints. + pub constraints: TaskConstraints, + /// Names the plan may reference; values are never included. + pub known_names: Vec, + /// Secret names the flow may reference as handles. + pub secret_names: Vec, + /// 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, +} + +/// A same-task plan the host derived, or why it could not derive one. +#[derive(Debug, Clone, PartialEq)] +pub enum PlanRecoveryResult { + /// A caller-validated flow to install on the existing task. + Plan(Flow), + /// No safe plan could be supplied. + GiveUp(String), +} + +/// The future returned by [`FlowRunner::recover_plan`]. +pub type PlanRecoveryFuture = 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 @@ -218,6 +254,21 @@ pub trait FlowRunner: Send + Sync + 'static { }) } + /// Whether the host can asynchronously write a plan for a task that has + /// no planner configured. Defaults to `false` so existing hosts keep the + /// immediate `needs_plan` behavior. + fn plan_recovery_enabled(&self) -> bool { + false + } + + /// Writes a validated flow for the existing task. The default keeps the + /// task at `needs_plan`. + fn recover_plan(&self, _request: PlanRecoveryRequest) -> PlanRecoveryFuture { + Box::pin(async { + PlanRecoveryResult::GiveUp("the host cannot write a task plan".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/plan_recovery.rs b/crates/tinycomputer-engine/src/task/plan_recovery.rs new file mode 100644 index 000000000..361d039cb --- /dev/null +++ b/crates/tinycomputer-engine/src/task/plan_recovery.rs @@ -0,0 +1,84 @@ +//! Host-supplied planning on the existing task and browser session. + +use tinycomputer_bus::Flow; + +use super::store::Cell; +use super::{ + DEFAULT_MODEL_CALLS, FlowRunner, PlanRecoveryRequest, PlanRecoveryResult, redact_task_data, +}; + +/// Asks the host for a plan, then checks it against the task's facts and +/// redacts it before any flow can run. +pub(super) async fn host_plan( + cell: &Cell, + runner: &dyn FlowRunner, + task_text: String, + guide: String, +) -> Result { + let id = { cell.view.borrow().id.clone() }; + let (constraints, budget, spent, known_names, secret_names, facts) = { + let state = cell + .state + .lock() + .map_err(|_| "task state is unavailable".to_owned())?; + ( + state.constraints.clone(), + state.budget, + state.spent, + state + .facts + .names() + .into_iter() + .map(str::to_owned) + .collect::>(), + state + .facts + .secret_names() + .into_iter() + .map(str::to_owned) + .collect::>(), + state.facts.clone(), + ) + }; + let request = PlanRecoveryRequest { + task: id.clone(), + task_text: runner.redact(&id, &task_text), + guide, + constraints, + known_names, + secret_names, + remaining_actions: budget + .max_actions + .unwrap_or(120) + .saturating_sub(spent.actions), + remaining_model_calls: budget + .max_model_calls + .unwrap_or(DEFAULT_MODEL_CALLS) + .saturating_sub(spent.model_calls), + remaining_ms: budget + .max_elapsed_ms + .map(|max| max.saturating_sub(spent.elapsed_ms)), + }; + let flow = match runner.recover_plan(request).await { + PlanRecoveryResult::Plan(flow) => flow, + PlanRecoveryResult::GiveUp(reason) => { + return Err(runner.redact(&id, &reason)); + } + }; + if flow.steps.is_empty() { + return Err("the host returned an empty plan".to_owned()); + } + let known = super::names::known_names(&flow, &facts); + let fact_names = super::names::fact_names(&facts); + let validation = crate::agentic::check_flow(&flow, &known, &fact_names); + if !validation.errors.is_empty() { + return Err(format!( + "the host plan did not pass flow validation: {}", + validation.errors.join("; ") + )); + } + let Some(flow) = redact_task_data(runner, &id, flow) else { + return Err("the host plan could not be safely redacted".to_owned()); + }; + Ok(flow) +} diff --git a/crates/tinycomputer-engine/src/task/store.rs b/crates/tinycomputer-engine/src/task/store.rs index 26528668b..77ecc8dd1 100644 --- a/crates/tinycomputer-engine/src/task/store.rs +++ b/crates/tinycomputer-engine/src/task/store.rs @@ -180,15 +180,23 @@ impl Tasks { Some(cell) } - pub(super) fn register_planless(&self, request: &StartTaskRequest) -> AgentResponse { + pub(super) fn register_planless( + &self, + request: &StartTaskRequest, + facts: Facts, + ) -> AgentResponse { let flow = Flow { app: String::new(), vars: BTreeMap::new(), steps: Vec::new(), }; - let Some(cell) = self.register(&flow, Facts::default(), request) else { + let Some(cell) = self.register(&flow, facts, request) else { return too_many(); }; + if self.runner.plan_recovery_enabled() { + self.start_planless_recovery(&cell, request.task.as_deref().unwrap_or_default()); + return AgentResponse::ok(cell.current_view()); + } publish( &cell, TaskStatus::NeedsPlan { @@ -199,6 +207,86 @@ impl Tasks { AgentResponse::ok(cell.current_view()) } + fn start_planless_recovery(&self, cell: &Arc, task: &str) { + publish( + cell, + TaskStatus::Running, + "Writing a safe plan for the task.", + ); + let (done, done_rx) = watch::channel(false); + let running_cell = cell.clone(); + let runner = self.runner.clone(); + let task = task.to_owned(); + let worker = tokio::spawn(async move { + let _completion = WorkerCompletion(done); + let id = running_cell.view.borrow().id.clone(); + let constraints = { + let Ok(state) = running_cell.state.lock() else { + return; + }; + state.constraints.clone() + }; + runner.prepare(&id, &constraints).await; + match super::plan_recovery::host_plan( + &running_cell, + runner.as_ref(), + task, + FLOW_GUIDE.to_owned(), + ) + .await + { + Ok(flow) => { + let Ok(facts) = running_cell.state.lock().map(|state| state.facts.clone()) + else { + runner.release(&id); + return; + }; + let known = super::names::known_names(&flow, &facts); + let fact_names = super::names::fact_names(&facts); + let missing = crate::agentic::missing_inputs(&flow, &known, &fact_names); + if let Ok(mut state) = running_cell.state.lock() { + state.flow = flow.clone(); + } + if !missing.is_empty() { + runner.release(&id); + publish( + &running_cell, + super::publish::needs_input(&missing), + "The recovered plan needs caller values before it can start.", + ); + return; + } + drive( + running_cell, + runner, + vec![Run { + flow, + allow_destructive: constraints.allow_destructive, + rescue: None, + }], + ) + .await; + } + Err(reason) => { + runner.release(&id); + publish( + &running_cell, + TaskStatus::NeedsPlan { + guide: FLOW_GUIDE.to_owned(), + }, + &format!("The host could not write a valid plan: {reason}"), + ); + } + } + }); + if let Ok(mut slot) = cell.worker.lock() { + *slot = Some(WorkerSlot { + abort: worker.abort_handle(), + done: done_rx, + }); + } + } + pub(super) fn start_planned( &self, request: &StartTaskRequest, diff --git a/crates/tinycomputer-engine/src/task/task_tests.rs b/crates/tinycomputer-engine/src/task/task_tests.rs index 766fb4a41..381b81ad5 100644 --- a/crates/tinycomputer-engine/src/task/task_tests.rs +++ b/crates/tinycomputer-engine/src/task/task_tests.rs @@ -40,8 +40,8 @@ use super::interpret::app_at; use super::publish::next_calls; use super::{ ContinuePaidAtShopRequest, ContinuePaymentRequest, FailedStepRecovery, - FailedStepRecoveryFuture, FailedStepRecoveryResult, FlowFuture, FlowRunner, MAX_TASKS, Tasks, - capabilities, input_kind, + FailedStepRecoveryFuture, FailedStepRecoveryResult, FlowFuture, FlowRunner, MAX_TASKS, + PlanRecoveryFuture, PlanRecoveryRequest, PlanRecoveryResult, Tasks, capabilities, input_kind, }; /// Replies queued in order; a missing reply never resolves, like a flow @@ -79,6 +79,10 @@ struct Script { recovery: Mutex>, /// Recovery requests, including their redacted task context. recoveries: Mutex>, + /// The host's planless recovery response. + plan_recovery: Mutex>, + /// Planless recovery requests, including named-only facts. + plan_requests: Mutex>, } impl FlowRunner for Script { @@ -109,6 +113,21 @@ impl FlowRunner for Script { Box::pin(async move { result }) } + fn plan_recovery_enabled(&self) -> bool { + self.plan_recovery.lock().unwrap().is_some() + } + + fn recover_plan(&self, request: PlanRecoveryRequest) -> PlanRecoveryFuture { + self.plan_requests.lock().unwrap().push(request); + let result = self + .plan_recovery + .lock() + .unwrap() + .take() + .unwrap_or_else(|| PlanRecoveryResult::GiveUp("no scripted plan 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/plan_tests.rs b/crates/tinycomputer-engine/src/task/task_tests/plan_tests.rs index 59f3f303c..e357c482e 100644 --- a/crates/tinycomputer-engine/src/task/task_tests/plan_tests.rs +++ b/crates/tinycomputer-engine/src/task/task_tests/plan_tests.rs @@ -102,6 +102,46 @@ async fn a_plain_language_task_is_planned_then_run() { assert!(plans[0].1["wall_ms"].is_u64()); } +#[tokio::test] +async fn host_recovers_a_failed_planner_without_replacing_the_task() { + let (tasks, script) = planned( + vec![finished_run( + FlowStopReason::Completed, + vec![step( + "1", + "do", + "open the shop home page", + StepOutcome::Done, + "", + )], + &[], + None, + )], + Err("the configured planner is unavailable"), + ); + *script.plan_recovery.lock().unwrap() = Some(crate::task::PlanRecoveryResult::Plan(flow( + json!({"app":"browser","steps":["open the shop home page"]}), + ))); + let started = tasks + .start(&StartTaskRequest { + task: Some("find a blue wool sweater".to_owned()), + constraints: TaskConstraints { + surfaces: vec![tinycomputer_bus::agent::SurfaceKind::Browser], + ..TaskConstraints::default() + }, + ..StartTaskRequest::default() + }) + .data + .unwrap(); + + assert!(matches!( + settle(&tasks, &started.id).await.status, + TaskStatus::Done { .. } + )); + assert_eq!(script.requests.lock().unwrap().len(), 1); + assert_eq!(script.plan_requests.lock().unwrap()[0].task, started.id); +} + #[tokio::test] async fn a_planned_task_reports_usage_from_warmup_and_run() { let script = Arc::new(Script { diff --git a/crates/tinycomputer-engine/src/task/task_tests/start_tests.rs b/crates/tinycomputer-engine/src/task/task_tests/start_tests.rs index 5dea1b9bb..a18de9c1e 100644 --- a/crates/tinycomputer-engine/src/task/task_tests/start_tests.rs +++ b/crates/tinycomputer-engine/src/task/task_tests/start_tests.rs @@ -551,6 +551,45 @@ async fn requests_that_cannot_start_are_refused_with_a_hint() { ); } +#[tokio::test] +async fn host_supplies_a_plan_on_the_same_planless_task() { + let plan = flow(json!({"app":"browser","steps":["open the shop home page"]})); + let (tasks, script) = controller(vec![finished_run( + FlowStopReason::Completed, + vec![step( + "1", + "do", + "open the shop home page", + StepOutcome::Done, + "", + )], + &[], + None, + )]); + *script.plan_recovery.lock().unwrap() = Some(crate::task::PlanRecoveryResult::Plan(plan)); + let initial = tasks + .start(&StartTaskRequest { + task: Some("find a blue wool sweater".to_owned()), + facts: BTreeMap::from([("email".to_owned(), "private@example.test".to_owned())]), + ..StartTaskRequest::default() + }) + .data + .unwrap(); + + assert!(matches!( + settle(&tasks, &initial.id).await.status, + TaskStatus::Done { .. } + )); + let requests = script.requests.lock().unwrap(); + assert_eq!(requests.len(), 1); + assert_eq!(requests[0].task_id.as_deref(), Some(initial.id.0.as_str())); + let plan_requests = script.plan_requests.lock().unwrap(); + assert_eq!(plan_requests.len(), 1); + assert_eq!(plan_requests[0].task, initial.id); + assert_eq!(plan_requests[0].known_names, ["email"]); + assert!(!plan_requests[0].task_text.contains("private@example.test")); +} + #[tokio::test] async fn extracted_rows_become_structured_records() { let (tasks, _) = controller(vec![finished_run(