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
3 changes: 2 additions & 1 deletion crates/tinycomputer-engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
Expand Down
51 changes: 51 additions & 0 deletions crates/tinycomputer-engine/src/task/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,46 @@ pub type CaptureFuture = Pin<Box<dyn Future<Output = Option<OutputRef>> + Send>>
/// or could not be made so; a task goes on either way.
pub type PrepareFuture = Pin<Box<dyn Future<Output = ()> + 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<u64>,
}

/// 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<Box<dyn Future<Output = FailedStepRecoveryResult> + 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 @@ -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 {
Expand Down
148 changes: 143 additions & 5 deletions crates/tinycomputer-engine/src/task/recovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,17 @@ 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;
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
Expand All @@ -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<StepReport>,
) -> Option<Briefing> {
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.
Expand Down
17 changes: 16 additions & 1 deletion crates/tinycomputer-engine/src/task/task_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -73,6 +74,10 @@ struct Script {
host_secret: Mutex<Option<String>>,
/// The pages loaded while tasks were planned, with their task.
opened: Mutex<Vec<(TaskId, String)>>,
/// The host's response to a failed-step recovery request.
recovery: Mutex<Option<FailedStepRecoveryResult>>,
/// Recovery requests, including their redacted task context.
recoveries: Mutex<Vec<FailedStepRecovery>>,
}

impl FlowRunner for Script {
Expand All @@ -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 })
Expand Down
Loading
Loading