Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions crates/tinycomputer-engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
Expand Down
2 changes: 1 addition & 1 deletion crates/tinycomputer-engine/src/task/controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
88 changes: 74 additions & 14 deletions crates/tinycomputer-engine/src/task/drive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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;
}
};
Expand Down Expand Up @@ -165,6 +153,78 @@ async fn plan_then_drive_with_page(
}
}

async fn handle_plan_failure(
cell: Arc<Cell>,
runner: Arc<dyn FlowRunner>,
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<Cell>,
runner: Arc<dyn FlowRunner>,
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<dyn FlowRunner>,
id: tinycomputer_bus::agent::TaskId,
Expand Down
53 changes: 52 additions & 1 deletion crates/tinycomputer-engine/src/task/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ mod interpret;
mod names;
mod page;
mod persistence;
mod plan_recovery;
mod publish;
mod recovery;
mod resume;
Expand All @@ -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.
Expand Down Expand Up @@ -180,6 +181,41 @@ pub enum FailedStepRecoveryResult {
/// The future returned by [`FlowRunner::recover_failed_step`].
pub type FailedStepRecoveryFuture = Pin<Box<dyn Future<Output = FailedStepRecoveryResult> + 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<String>,
/// Secret names the flow may reference as handles.
pub secret_names: Vec<String>,
/// 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<u64>,
}

/// 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<Box<dyn Future<Output = PlanRecoveryResult> + 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
Expand Down Expand Up @@ -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 {
Expand Down
84 changes: 84 additions & 0 deletions crates/tinycomputer-engine/src/task/plan_recovery.rs
Original file line number Diff line number Diff line change
@@ -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<Flow, String> {
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::<Vec<_>>(),
state
.facts
.secret_names()
.into_iter()
.map(str::to_owned)
.collect::<Vec<_>>(),
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)
}
Loading
Loading