Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

Stop agent turns on classified unchanged blockers

Steven Enamakelc4b1e9473cf5
diff --git a/crates/openhuman-core/src/agent/session_host/driver.rs b/crates/openhuman-core/src/agent/session_host/driver.rs
index a698e01196..cd6e41a5b5 100644
--- a/crates/openhuman-core/src/agent/session_host/driver.rs
+++ b/crates/openhuman-core/src/agent/session_host/driver.rs
@@ -303,7 +303,29 @@ impl SessionDriver<OpenHumanRunContext> for OpenHumanSessionDriver {
history.extend(appended);
let required_output = request.run_context.data.required_output.clone();
+ let classified_halt = outcome
+ .breaker_halt
+ .as_deref()
+ .is_some_and(|reason| reason.starts_with("Stopping after "));
let required_repair = match required_output.as_ref() {
+ Some(contract) if classified_halt => {
+ if !crate::agent::harness::required_output::output_satisfies_contract(
+ &output, contract,
+ ) {
+ output.push_str("\n\n");
+ output.push_str(&crate::agent::harness::required_output::synthesize_block(
+ contract,
+ ));
+ if history
+ .last()
+ .is_some_and(|message| matches!(message, Message::Assistant(_)))
+ {
+ history.pop();
+ }
+ history.push(Message::assistant(output.clone()));
+ }
+ None
+ }
Some(contract) => {
grounded_close::repair_required_output(
&self.turn_model_source,
diff --git a/crates/openhuman-core/src/agent/session_host/driver/grounded_close.rs b/crates/openhuman-core/src/agent/session_host/driver/grounded_close.rs
index 6c8536099e..acfbf9ed7f 100644
--- a/crates/openhuman-core/src/agent/session_host/driver/grounded_close.rs
+++ b/crates/openhuman-core/src/agent/session_host/driver/grounded_close.rs
@@ -51,6 +51,21 @@ pub(super) struct GroundedClose {
pub(super) usage: RepairUsage,
}
+/// A classified halt has enough evidence for a deterministic partial result.
+/// Keeping this separate from the model-driven repair path guarantees zero
+/// additional provider calls once its recovery budget is exhausted.
+fn classified_halt_close(outcome: &TinyagentsTurnOutcome) -> Option<GroundedClose> {
+ let reason = outcome.breaker_halt.as_deref()?;
+ if !reason.starts_with("Stopping after ") {
+ return None;
+ }
+ let records = results_from_tool_outcomes(&outcome.tool_outcomes);
+ Some(GroundedClose {
+ output: build_deterministic_final_summary(&records, Some(reason)),
+ usage: RepairUsage::default(),
+ })
+}
+
/// Repair an otherwise valid terminal reply which omits the host's required
/// structured-output block. This mirrors the legacy session contract while
/// keeping the repair call and its usage inside the explicit driver sidecar.
@@ -145,6 +160,9 @@ pub(super) async fn close_if_needed(
return None;
}
+ if let Some(close) = classified_halt_close(outcome) {
+ return Some(close);
+ }
let records = results_from_tool_outcomes(&outcome.tool_outcomes);
let rendered = render_tool_results(&records, turn_checkpoint::GROUNDING_TOTAL_CHARS);
let instruction = if needs_cap_close {
diff --git a/crates/openhuman-core/src/agent/session_host/driver/grounded_close_tests.rs b/crates/openhuman-core/src/agent/session_host/driver/grounded_close_tests.rs
index 70009b78c1..f935fd1ea6 100644
--- a/crates/openhuman-core/src/agent/session_host/driver/grounded_close_tests.rs
+++ b/crates/openhuman-core/src/agent/session_host/driver/grounded_close_tests.rs
@@ -7,6 +7,36 @@ const RECORDS: &str = "\n- `list_directory` — ok\n > three crates\n";
const CLEAN_REPLY: &str = "The workspace holds three crates; the build is green.";
const FALLBACK: &str = "deterministic fallback";
+#[test]
+fn classified_halt_returns_partial_work_without_provider_usage() {
+ use crate::agent::tinyagents::ToolCallOutcome;
+ let outcome = TinyagentsTurnOutcome {
+ text: String::new(),
+ resolved_route: None,
+ history: Vec::new(),
+ conversation: Vec::new(),
+ model_calls: 2,
+ tool_calls: 2,
+ input_tokens: 100,
+ output_tokens: 20,
+ cached_input_tokens: 0,
+ charged_amount_usd: 0.0,
+ early_exit_tool: None,
+ hit_cap: false,
+ wrap_up_injected: false,
+ breaker_halt: Some("Stopping after 1 attempt(s): failure class `permission` still blocks operation `search` on `catalog`. Resolve this blocker before retrying.".into()),
+ tool_outcomes: vec![
+ ToolCallOutcome { call_id: "a".into(), name: "list".into(), arguments: serde_json::json!({}), success: true, content: "three items".into(), duration_ms: 1 },
+ ToolCallOutcome { call_id: "b".into(), name: "search".into(), arguments: serde_json::json!({}), success: false, content: "403 Forbidden".into(), duration_ms: 1 },
+ ],
+ };
+ let close = classified_halt_close(&outcome).expect("classified halt");
+ assert_eq!(close.usage.model_calls, 0);
+ assert!(close.output.contains("permission"), "{}", close.output);
+ assert!(close.output.contains("three items"), "{}", close.output);
+ assert!(close.output.contains("403 Forbidden"), "{}", close.output);
+}
+
/// A candidate carrying a verbatim span of the directive it was just handed —
/// the shape this guard exists for, spliced from the constant so a reword
/// cannot leave this fixture quoting text nobody is given.
diff --git a/crates/openhuman-core/src/agent/tinyagents/README.md b/crates/openhuman-core/src/agent/tinyagents/README.md
index 60d7eacd19..22e53f7a10 100644
--- a/crates/openhuman-core/src/agent/tinyagents/README.md
+++ b/crates/openhuman-core/src/agent/tinyagents/README.md
@@ -29,7 +29,7 @@ The **adapter seam** between OpenHuman and the vendored [`tinyagents`](../../../
| `replay/` | Read-only agent-run replay/status RPC (`mod.rs`, `ops.rs`, `schemas.rs`): three `agent`-namespace controllers over `journal.rs`. |
| `journal.rs` | `TurnJournal` and `FileStatusStore`: a crate `StoreEventJournal` over a JSONL append store plus a `HarnessStatusStore` writer under `{workspace}/tinyagents_store`. Attached alongside the live `observability` bridge as an independent `EventSink` subscriber, wrapped in `RedactingSink`; best-effort and non-fatal. |
| `reaper.rs` | `reap_orphaned_runs`: startup sweep that marks non-terminal runs `Cancelled` in the durable status store. The only writer over the status seam that `replay/` reads. |
-| `middleware.rs` + `middleware/` | The named OpenHuman middleware stack. `turn_context.rs`: `TurnContextMiddleware` (bundles config and installs the enabled hooks), `TranscriptSnapshotMiddleware`/`TranscriptSnapshotSink`, `HandoffConfig`/`HandoffMiddleware` (oversized sub-agent results stashed for `extract_from_result`). `prompt_cache.rs`: `PromptCacheSegmentMiddleware`. `tool_output.rs`: `ToolOutputMiddleware` (per-result byte cap and optional payload summarizer). `approval.rs`: `ApprovalSecurityMiddleware`. `cli_rpc_only.rs`: `CliRpcOnlyMiddleware`. `tool_policy.rs`: the `ToolPolicyMiddleware` struct and impl (records blocks into `crate::tools::registry::denials`). `tool_outcome_capture.rs`: `ToolOutcomeCaptureMiddleware`. `embedder_hooks.rs`: `EmbedderToolHooksMiddleware`. `arg_recovery.rs`: `ArgRecoveryMiddleware`. `memory_protocol.rs`: `MemoryProtocolMiddleware`. `cost_budget.rs`: `CostBudgetMiddleware`. `repeated_failure.rs`: `RepeatedToolFailureMiddleware`. `loop_guards.rs`: `TerminalInferenceFailure`. `repeat_progress.rs`: `RepeatProgressMiddleware` (adjacent-repeat streaks plus a run-wide `(call, result)` recurrence ledger) and `RepeatEvictionObserver` (registered last; resets the ledger when compaction evicts a recorded result, #6275). `message_trim.rs`: `ImageAwareMessageTrimMiddleware`. `final_call_wrap_up.rs`: `FinalCallWrapUpMiddleware` (on the last permitted model call it withdraws the belt and asks for the conclusion; on the one before it, narrows the belt to `DELIVERABLE_TOOLS` so a turn whose product is a file can still write it). `artifact_index_toc.rs`: `ArtifactIndexTocMiddleware` (issue #6014). `credential_scrub.rs`: `CredentialScrubMiddleware` (issue #4453). |
+| `middleware.rs` + `middleware/` | The named OpenHuman middleware stack. `turn_context.rs`: `TurnContextMiddleware` (bundles config and installs the enabled hooks), `TranscriptSnapshotMiddleware`/`TranscriptSnapshotSink`, `HandoffConfig`/`HandoffMiddleware` (oversized sub-agent results stashed for `extract_from_result`). `prompt_cache.rs`: `PromptCacheSegmentMiddleware`. `tool_output.rs`: `ToolOutputMiddleware` (per-result byte cap and optional payload summarizer). `approval.rs`: `ApprovalSecurityMiddleware`. `cli_rpc_only.rs`: `CliRpcOnlyMiddleware`. `tool_policy.rs`: the `ToolPolicyMiddleware` struct and impl (records blocks into `crate::tools::registry::denials`). `tool_outcome_capture.rs`: `ToolOutcomeCaptureMiddleware`. `embedder_hooks.rs`: `EmbedderToolHooksMiddleware`. `arg_recovery.rs`: `ArgRecoveryMiddleware`. `memory_protocol.rs`: `MemoryProtocolMiddleware`. `cost_budget.rs`: `CostBudgetMiddleware`. `repeated_failure.rs`: `RepeatedToolFailureMiddleware` (class-specific recovery budgets before the next model call; equivalent failures share a stable resource scope even when arguments differ). `loop_guards.rs`: `TerminalInferenceFailure`. `repeat_progress.rs`: `RepeatProgressMiddleware` (adjacent-repeat streaks plus a run-wide `(call, result)` recurrence ledger) and `RepeatEvictionObserver` (registered last; resets the ledger when compaction evicts a recorded result, #6275). `message_trim.rs`: `ImageAwareMessageTrimMiddleware`. `final_call_wrap_up.rs`: `FinalCallWrapUpMiddleware` (on the last permitted model call it withdraws the belt and asks for the conclusion; on the one before it, narrows the belt to `DELIVERABLE_TOOLS` so a turn whose product is a file can still write it). `artifact_index_toc.rs`: `ArtifactIndexTocMiddleware` (issue #6014). `credential_scrub.rs`: `CredentialScrubMiddleware` (issue #4453). |
| `model.rs` | Helpers and wrappers over native crate `ChatModel` values: message/response translation, usage merging, stream-delta forwarding, `MaxTokensModel`, `ProfileOverrideModel`. |
| `tools.rs` | `CanonicalSharedToolAdapter`: resolves an OpenHuman shared tool registry and forwards the canonical `tinytools::Tool` contract; `EarlyExitHook` pauses successful `ask_user_clarification`-style calls. |
| `routes.rs` | `WORKLOAD_ROUTE_TIERS` (the tier inventory projected into the model registry), `RequiredCapabilitiesMiddleware`, `FallbackObserverMiddleware`, `UsageCarryMiddleware`, and the per-model fallback policy. |
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs
index 9da442fff8..736e3fdce3 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/repeated_failure.rs
@@ -9,7 +9,9 @@ use async_trait::async_trait;
use tinyagents_harness::context::RunContext;
use tinyagents_harness::error::Result as TaResult;
use tinyagents_harness::middleware::{Middleware, ToolInvocationIdentity};
-use tinyagents_harness::no_progress::{NoProgress, NoProgressTracker, ToolAttempt};
+use tinyagents_harness::no_progress::{
+ ClassifiedFailure, ClassifiedFailureTracker, NoProgress, NoProgressTracker, ToolAttempt,
+};
use tinyagents_harness::steering::{SteeringCommand, SteeringHandle};
use tinyinference_llm::message::Message as TaMessage;
use tinyinference_llm::tool::ToolCall as TaToolCall;
@@ -55,6 +57,7 @@ pub(crate) struct RepeatedToolFailureMiddleware {
/// Crate no-progress escalation ladder — the single source of the
/// identical-failure / varied-failure / hard-reject logic (tinyagents 1.5.0).
tracker: NoProgressTracker,
+ classified: ClassifiedFailureTracker,
/// Monotonic tool-outcome counter, used only for the crate's "no progress
/// since step X" nudge wording. Not the model-call count, but a stable,
/// increasing marker is all the wording needs.
@@ -65,6 +68,9 @@ pub(crate) struct RepeatedToolFailureMiddleware {
/// argument sets that happen to share a first error line don't count as a
/// repeat and can't pre-empt the generic no-progress backstop.
arg_sigs: std::sync::Mutex<std::collections::HashMap<String, String>>,
+ /// Call ID to stable target identity. Query strings and free-form prompts
+ /// are excluded so varying a query cannot evade a resource-level blocker.
+ target_scopes: std::sync::Mutex<std::collections::HashMap<String, String>>,
/// Recoverable-failure ladder (issue #4463): transient failures (timeouts,
/// connection resets, rate limits, 5xx) are routed here instead of the crate
/// tracker so they get the legacy extended headroom
@@ -91,8 +97,10 @@ impl RepeatedToolFailureMiddleware {
handle,
halt_summary,
tracker: NoProgressTracker::new(identical_threshold),
+ classified: ClassifiedFailureTracker::default(),
step: AtomicUsize::new(0),
arg_sigs: std::sync::Mutex::new(std::collections::HashMap::new()),
+ target_scopes: std::sync::Mutex::new(std::collections::HashMap::new()),
recoverable_sig_counts: std::sync::Mutex::new(std::collections::HashMap::new()),
recoverable_consecutive: AtomicU32::new(0),
}
@@ -195,6 +203,111 @@ fn args_fingerprint(arguments: &serde_json::Value) -> String {
format!("{:x}", hasher.finish())
}
+/// Stable resource identity supplied by the call, excluding free-form queries,
+/// prompts, credentials, and URL query parameters. An absent target remains
+/// scoped to the operation, never to the changing argument fingerprint.
+pub(super) fn failure_scope(tool: &str, arguments: &serde_json::Value) -> String {
+ let mut scope = tool.to_owned();
+ for field in [
+ "account_id",
+ "workspace_id",
+ "app",
+ "window_id",
+ "resource",
+ "endpoint",
+ "url",
+ ] {
+ let value = match arguments.get(field) {
+ Some(serde_json::Value::String(value)) if !value.is_empty() => value.clone(),
+ Some(serde_json::Value::Number(value)) => value.to_string(),
+ _ => continue,
+ };
+ scope.push(':');
+ scope.push_str(field);
+ scope.push('=');
+ scope.push_str(&crate::util::truncate_with_ellipsis(
+ value.split('?').next().unwrap_or(&value),
+ 120,
+ ));
+ }
+ scope
+}
+
+/// Explicit recovery policy. Only recognised failures enter the classified
+/// ledger; unknown prose continues through the established exact-repeat guard.
+pub(super) fn recovery_policy(
+ tool: &str,
+ error: &str,
+ body_level_failure: bool,
+) -> Option<(&'static str, usize)> {
+ use crate::tools::status::ToolFailureClass as Class;
+ if body_level_failure {
+ return Some(("validation", 1));
+ }
+ // A tool-owned JSON error contract is less ambiguous than rendered prose.
+ // Read only explicit status/code fields; arbitrary response data is not a
+ // failure signal (this function is called only for `is_error` results).
+ if let Ok(value) = serde_json::from_str::<serde_json::Value>(error) {
+ let status = value
+ .get("status_code")
+ .or_else(|| value.get("status"))
+ .or_else(|| value.pointer("/error/status_code"))
+ .and_then(serde_json::Value::as_u64);
+ match status {
+ Some(401) => return Some(("authentication", 0)),
+ Some(403) => return Some(("permission", 0)),
+ Some(400 | 422) => return Some(("validation", 1)),
+ Some(429 | 500 | 502 | 503 | 504) => return Some(("transient", 2)),
+ _ => {}
+ }
+ let code = value
+ .get("code")
+ .or_else(|| value.pointer("/error/code"))
+ .and_then(serde_json::Value::as_str);
+ match code {
+ Some("PERMISSION_DENIED") => return Some(("permission", 0)),
+ Some("UNAUTHENTICATED") => return Some(("authentication", 0)),
+ Some("INVALID_ARGUMENT") => return Some(("validation", 1)),
+ Some("WINDOW_NOT_FOUND") => return Some(("missing_window", 1)),
+ Some("APP_NOT_FOUND") => return Some(("missing_app", 1)),
+ Some("UNIMPLEMENTED") => return Some(("unsupported", 0)),
+ Some("UNAVAILABLE" | "RESOURCE_EXHAUSTED") => return Some(("transient", 2)),
+ _ => {}
+ }
+ }
+ let class = crate::tools::status::classify(error, false).class;
+ Some(match class {
+ Class::MissingPermission => ("permission", 0),
+ Class::BadCredentials => ("authentication", 0),
+ Class::BlockedByPolicy | Class::Denied | Class::ApprovalExpired => ("policy", 0),
+ Class::Unsupported | Class::MissingApp => ("unsupported", 0),
+ Class::NotFound
+ if tool.contains("desktop") && error.to_ascii_lowercase().contains("window") =>
+ {
+ ("missing_window", 1)
+ }
+ Class::NotFound => ("not_found", 1),
+ Class::ServiceUnavailable | Class::ModelConnection => ("transient", 2),
+ Class::Timeout
+ if matches!(
+ tool,
+ "web_search" | "web_fetch" | "file_read" | "list_files" | "desktop_list_windows"
+ ) =>
+ {
+ ("transient", 2)
+ }
+ Class::Timeout => ("uncertain_side_effect", 0),
+ Class::Unknown if is_recoverable_tool_failure(error) => ("transient", 2),
+ Class::Unknown
+ if error.to_ascii_lowercase().contains("schema validation")
+ || error.to_ascii_lowercase().contains("invalid arguments") =>
+ {
+ ("validation", 1)
+ }
+ Class::Unknown => return None,
+ })
+}
+
/// Detect a **body-level** failure from `validate_workflow` / `dry_run_workflow`
/// (issue: flows breaker doesn't see repeated invalid-graph loops). Both tools
/// report an invalid graph / aborted sandbox run via `ToolResult::success` with
@@ -239,6 +352,9 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>
if let Ok(mut sigs) = self.arg_sigs.lock() {
sigs.insert(call.id.clone(), args_fingerprint(&call.arguments));
}
+ if let Ok(mut scopes) = self.target_scopes.lock() {
+ scopes.insert(call.id.clone(), failure_scope(&call.name, &call.arguments));
+ }
Ok(())
}
@@ -257,6 +373,12 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>
.ok()
.and_then(|mut sigs| sigs.remove(&invocation.call_id().to_string()))
.unwrap_or_default();
+ let scope = self
+ .target_scopes
+ .lock()
+ .ok()
+ .and_then(|mut scopes| scopes.remove(&invocation.call_id().to_string()))
+ .unwrap_or_else(|| tool_name.to_owned());
let step = self.step.fetch_add(1, Ordering::SeqCst) + 1;
// Body-level failure signal: `validate_workflow` / `dry_run_workflow`
@@ -275,6 +397,64 @@ impl Middleware<(), crate::agent::tinyagents::host::OpenHumanRunContext>
false => String::new(),
};
+ if !result.is_error && !body_level_failure {
+ // Only a successful observation against this operation and scope
+ // demonstrates that its blocker changed. Unrelated successes do not.
+ for class in [
+ "permission",
+ "authentication",
+ "policy",
+ "unsupported",
+ "missing_window",
+ "missing_app",
+ "not_found",
+ "transient",
+ "uncertain_side_effect",
+ "validation",
+ ] {
+ self.classified
+ .clear(&ClassifiedFailure::new(class, tool_name, &scope));
+ }
+ } else if !is_repeat_call_exempt(tool_name) {
+ if let Some((class, budget)) =
+ recovery_policy(tool_name, &failure_text, body_level_failure)
+ {
+ let key = ClassifiedFailure::new(class, tool_name, &scope);
+ if let NoProgress::Halt(mut summary) = self.classified.record(&key, budget) {
+ tracing::warn!(
+ tool = tool_name,
+ class,
+ budget,
+ "[tinyagents::mw] classified failure budget exhausted"
+ );
+ if class == "uncertain_side_effect" {
+ summary.push_str(" The action may already have happened; reconcile its external state before any retry.");
+ }
+ if let Ok(mut slot) = self.halt_summary.lock() {
+ *slot = Some(summary);
+ }
+ self.handle.send(SteeringCommand::Pause);
+ self.tracker.reset();
+ return Ok(());
+ }
+ if matches!(class, "missing_window" | "missing_app" | "validation") {
+ let instruction = if class == "validation" {
+ "The last call failed validation. Correct its schema or arguments once before trying again."
+ } else {
+ "The desktop target was not found. Rediscover the current app and window once before trying again."
+ };
+ self.handle
+ .send(SteeringCommand::InjectMessage(TaMessage::system(
+ instruction,
+ )));
+ }
+ // The classified budget owns this known blocker. In particular,
+ // a different query must not reset its count or trigger a
+ // competing exact-repeat nudge.
+ return Ok(());
+ }
+ }
+
// ── Part 5 (#3104): terminal delegated-inference fast-halt ──────────────
// A permanent inference failure (out of budget / provider-config rejection)
// surfaced by a delegated sub-agent cannot be recovered by retrying — the
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_loop_guard_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_loop_guard_tests.rs
index 685b8249f5..36bd673a3e 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware_loop_guard_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_loop_guard_tests.rs
@@ -1,5 +1,228 @@
use super::*;
+#[tokio::test]
+async fn varied_queries_against_one_forbidden_endpoint_stop_on_first_failure() {
+ let handle = SteeringHandle::allow_all();
+ let slot = std::sync::Arc::new(std::sync::Mutex::new(None));
+ let mw = RepeatedToolFailureMiddleware::new(handle.clone(), 3, slot.clone());
+ let mut call = TaToolCall::new(
+ "forbidden-1",
+ "web_fetch",
+ serde_json::json!({
+ "url": "https://example.test/restricted?query=first"
+ }),
+ );
+ mw.before_tool(&mut ctx(), &(), &mut call).await.unwrap();
+ let mut result = failing_result("web_fetch", "403 Forbidden");
+ mw.after_tool(
+ &mut ctx(),
+ &(),
+ &invocation("forbidden-1", "web_fetch"),
+ &mut result,
+ )
+ .await
+ .unwrap();
+ assert_eq!(drain_pause_count(&handle), 1);
+ let summary = slot.lock().unwrap().clone().unwrap();
+ assert!(summary.contains("authentication"), "{summary}");
+ assert!(summary.contains("example.test/restricted"), "{summary}");
+ assert!(!summary.contains("query=first"), "{summary}");
+}
+
+#[tokio::test]
+async fn schema_repair_gets_one_attempt_even_when_arguments_change() {
+ let handle = SteeringHandle::allow_all();
+ let slot = std::sync::Arc::new(std::sync::Mutex::new(None));
+ let mw = RepeatedToolFailureMiddleware::new(handle.clone(), 3, slot.clone());
+ for (id, value) in [("schema-1", 1), ("schema-2", 2)] {
+ let mut call = TaToolCall::new(
+ id,
+ "search",
+ serde_json::json!({"query": value, "endpoint": "catalog"}),
+ );
+ mw.before_tool(&mut ctx(), &(), &mut call).await.unwrap();
+ let mut result =
+ failing_result("search", "schema validation failed: query must be a string");
+ mw.after_tool(&mut ctx(), &(), &invocation(id, "search"), &mut result)
+ .await
+ .unwrap();
+ }
+ assert_eq!(drain_pause_count(&handle), 1);
+ let summary = slot.lock().unwrap().clone().unwrap();
+ assert!(summary.contains("validation"), "{summary}");
+ assert!(summary.contains("2 attempt(s)"), "{summary}");
+}
+
+#[tokio::test]
+async fn missing_desktop_window_allows_one_rediscovery_then_stops() {
+ let handle = SteeringHandle::allow_all();
+ let slot = std::sync::Arc::new(std::sync::Mutex::new(None));
+ let mw = RepeatedToolFailureMiddleware::new(handle.clone(), 3, slot.clone());
+ for id in ["window-1", "window-2"] {
+ let mut call = TaToolCall::new(
+ id,
+ "tinydesktop_click",
+ serde_json::json!({"window_id": 17, "element": id}),
+ );
+ mw.before_tool(&mut ctx(), &(), &mut call).await.unwrap();
+ let mut result = failing_result(
+ "tinydesktop_click",
+ r#"{"error":{"code":"WINDOW_NOT_FOUND"}}"#,
+ );
+ mw.after_tool(
+ &mut ctx(),
+ &(),
+ &invocation(id, "tinydesktop_click"),
+ &mut result,
+ )
+ .await
+ .unwrap();
+ }
+ assert_eq!(drain_pause_count(&handle), 1);
+ let summary = slot.lock().unwrap().clone().unwrap();
+ assert!(summary.contains("missing_window"), "{summary}");
+ assert!(summary.contains("17"), "{summary}");
+}
+
+#[tokio::test]
+async fn transient_failures_have_two_retries_and_success_clears_only_that_scope() {
+ let handle = SteeringHandle::allow_all();
+ let slot = std::sync::Arc::new(std::sync::Mutex::new(None));
+ let mw = RepeatedToolFailureMiddleware::new(handle.clone(), 3, slot.clone());
+ for (id, endpoint) in [("a1", "alpha"), ("b1", "beta"), ("a2", "alpha")] {
+ let mut call = TaToolCall::new(
+ id,
+ "web_fetch",
+ serde_json::json!({"endpoint": endpoint, "query": id}),
+ );
+ mw.before_tool(&mut ctx(), &(), &mut call).await.unwrap();
+ let mut result = failing_result("web_fetch", "503 Service Unavailable");
+ mw.after_tool(&mut ctx(), &(), &invocation(id, "web_fetch"), &mut result)
+ .await
+ .unwrap();
+ }
+ assert_eq!(drain_pause_count(&handle), 0);
+ let mut recovered = TaToolCall::new(
+ "a-ok",
+ "web_fetch",
+ serde_json::json!({"endpoint": "alpha"}),
+ );
+ mw.before_tool(&mut ctx(), &(), &mut recovered)
+ .await
+ .unwrap();
+ let mut ok = tool_result("web_fetch", "ready");
+ mw.after_tool(&mut ctx(), &(), &invocation("a-ok", "web_fetch"), &mut ok)
+ .await
+ .unwrap();
+ for id in ["b2", "b3"] {
+ let mut call = TaToolCall::new(
+ id,
+ "web_fetch",
+ serde_json::json!({"endpoint": "beta", "query": id}),
+ );
+ mw.before_tool(&mut ctx(), &(), &mut call).await.unwrap();
+ let mut result = failing_result("web_fetch", "503 Service Unavailable");
+ mw.after_tool(&mut ctx(), &(), &invocation(id, "web_fetch"), &mut result)
+ .await
+ .unwrap();
+ }
+ assert_eq!(drain_pause_count(&handle), 1);
+ let summary = slot.lock().unwrap().clone().unwrap();
+ assert!(summary.contains("3 attempt(s)"), "{summary}");
+ assert!(summary.contains("beta"), "{summary}");
+}
+
+#[test]
+fn uncertain_timeout_requires_reconciliation() {
+ assert_eq!(
+ super::super::repeated_failure::recovery_policy("gmail_send", "timed out", false),
+ Some(("uncertain_side_effect", 0))
+ );
+ assert_eq!(
+ super::super::repeated_failure::recovery_policy("web_fetch", "timed out", false),
+ Some(("transient", 2))
+ );
+}
+
+#[test]
+fn structured_status_precedes_ambiguous_error_prose() {
+ assert_eq!(
+ super::super::repeated_failure::recovery_policy(
+ "search",
+ r#"{"status_code":403,"message":"try again later"}"#,
+ false
+ ),
+ Some(("permission", 0))
+ );
+ assert_eq!(
+ super::super::repeated_failure::recovery_policy(
+ "search",
+ r#"{"error":{"code":"INVALID_ARGUMENT"}}"#,
+ false
+ ),
+ Some(("validation", 1))
+ );
+ assert_eq!(
+ super::super::repeated_failure::recovery_policy(
+ "tinydesktop_click",
+ r#"{"error":{"code":"WINDOW_NOT_FOUND"}}"#,
+ false
+ ),
+ Some(("missing_window", 1))
+ );
+}
+
+#[test]
+fn failure_scope_keeps_resource_and_permission_context_but_ignores_query() {
+ let first = super::super::repeated_failure::failure_scope(
+ "web_fetch",
+ &serde_json::json!({"account_id": "team-a", "url": "https://example.test/restricted?q=one"}),
+ );
+ let second = super::super::repeated_failure::failure_scope(
+ "web_fetch",
+ &serde_json::json!({"account_id": "team-a", "url": "https://example.test/restricted?q=two"}),
+ );
+ let other = super::super::repeated_failure::failure_scope(
+ "web_fetch",
+ &serde_json::json!({"account_id": "team-b", "url": "https://example.test/restricted?q=two"}),
+ );
+ assert_eq!(first, second);
+ assert_ne!(first, other);
+ assert!(!first.contains("q="));
+ assert_ne!(
+ super::super::repeated_failure::failure_scope(
+ "desktop_click",
+ &serde_json::json!({"app":"Browser", "window_id": 1})
+ ),
+ super::super::repeated_failure::failure_scope(
+ "desktop_click",
+ &serde_json::json!({"app":"Browser", "window_id": 2})
+ ),
+ );
+}
+
+#[tokio::test]
+async fn legitimate_wait_polling_does_not_consume_transient_budget() {
+ let handle = SteeringHandle::allow_all();
+ let mw = RepeatedToolFailureMiddleware::new(
+ handle.clone(),
+ 3,
+ std::sync::Arc::new(std::sync::Mutex::new(None)),
+ );
+ for id in 0..5 {
+ let mut result = failing_result("wait_subagent", "timed out waiting for child");
+ mw.after_tool(
+ &mut ctx(),
+ &(),
+ &invocation(format!("wait-{id}"), "wait_subagent"),
+ &mut result,
+ )
+ .await
+ .unwrap();
+ }
+ assert_eq!(drain_pause_count(&handle), 0);
+}
+
#[tokio::test]
async fn sampling_tool_output_still_hits_the_byte_budget_backstop() {
// Unlike the proposal tools, sampling tools are deliberately NOT
diff --git a/vendor/tinyagents b/vendor/tinyagents
index 19cafdace8..30571ea37a 160000
--- a/vendor/tinyagents
+++ b/vendor/tinyagents
@@ -1 +1 @@
-Subproject commit 19cafdace8fc87a1015f49198984fd1e4c66ddae
+Subproject commit 30571ea37a17807472c33f579a1626741f001af4