Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(cua-driver): recovery hints on refusals and unverifiable results (#5493)

Francesco Bonacciac6f7c21edc1
diff --git a/libs/cua-driver/contract/manifest.json b/libs/cua-driver/contract/manifest.json
index 2e4b8383b4..7fc22c7b29 100644
--- a/libs/cua-driver/contract/manifest.json
+++ b/libs/cua-driver/contract/manifest.json
@@ -233,6 +233,31 @@
"null"
]
},
+ "hint": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "next_call": {
+ "additionalProperties": false,
+ "properties": {
+ "arguments": {
+ "type": "object"
+ },
+ "tool": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "tool",
+ "arguments"
+ ],
+ "type": [
+ "object",
+ "null"
+ ]
+ },
"route": {
"enum": [
"accessibility",
@@ -649,6 +674,31 @@
"null"
]
},
+ "hint": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "next_call": {
+ "additionalProperties": false,
+ "properties": {
+ "arguments": {
+ "type": "object"
+ },
+ "tool": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "tool",
+ "arguments"
+ ],
+ "type": [
+ "object",
+ "null"
+ ]
+ },
"route": {
"enum": [
"accessibility",
@@ -2176,6 +2226,31 @@
"null"
]
},
+ "hint": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "next_call": {
+ "additionalProperties": false,
+ "properties": {
+ "arguments": {
+ "type": "object"
+ },
+ "tool": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "tool",
+ "arguments"
+ ],
+ "type": [
+ "object",
+ "null"
+ ]
+ },
"route": {
"enum": [
"accessibility",
@@ -2382,6 +2457,31 @@
"null"
]
},
+ "hint": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "next_call": {
+ "additionalProperties": false,
+ "properties": {
+ "arguments": {
+ "type": "object"
+ },
+ "tool": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "tool",
+ "arguments"
+ ],
+ "type": [
+ "object",
+ "null"
+ ]
+ },
"route": {
"enum": [
"accessibility",
@@ -2987,6 +3087,31 @@
"null"
]
},
+ "hint": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "next_call": {
+ "additionalProperties": false,
+ "properties": {
+ "arguments": {
+ "type": "object"
+ },
+ "tool": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "tool",
+ "arguments"
+ ],
+ "type": [
+ "object",
+ "null"
+ ]
+ },
"route": {
"enum": [
"accessibility",
@@ -3705,6 +3830,31 @@
"null"
]
},
+ "hint": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "next_call": {
+ "additionalProperties": false,
+ "properties": {
+ "arguments": {
+ "type": "object"
+ },
+ "tool": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "tool",
+ "arguments"
+ ],
+ "type": [
+ "object",
+ "null"
+ ]
+ },
"route": {
"enum": [
"accessibility",
@@ -3955,6 +4105,31 @@
"null"
]
},
+ "hint": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "next_call": {
+ "additionalProperties": false,
+ "properties": {
+ "arguments": {
+ "type": "object"
+ },
+ "tool": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "tool",
+ "arguments"
+ ],
+ "type": [
+ "object",
+ "null"
+ ]
+ },
"route": {
"enum": [
"accessibility",
@@ -4578,6 +4753,31 @@
"null"
]
},
+ "hint": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "next_call": {
+ "additionalProperties": false,
+ "properties": {
+ "arguments": {
+ "type": "object"
+ },
+ "tool": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "tool",
+ "arguments"
+ ],
+ "type": [
+ "object",
+ "null"
+ ]
+ },
"route": {
"enum": [
"accessibility",
@@ -5199,6 +5399,31 @@
"null"
]
},
+ "hint": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "next_call": {
+ "additionalProperties": false,
+ "properties": {
+ "arguments": {
+ "type": "object"
+ },
+ "tool": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "tool",
+ "arguments"
+ ],
+ "type": [
+ "object",
+ "null"
+ ]
+ },
"route": {
"enum": [
"accessibility",
diff --git a/libs/cua-driver/docs/action-result-contract.md b/libs/cua-driver/docs/action-result-contract.md
index 3acb0093c7..a1a5fc8e75 100644
--- a/libs/cua-driver/docs/action-result-contract.md
+++ b/libs/cua-driver/docs/action-result-contract.md
@@ -40,6 +40,8 @@ evidence rests on. A `refused` result adds `error: {code, hint}`.
| `evidence[].detail` | optional human readback behind the evidence |
| `summary` | optional; the result text, verbatim |
| `error.code` / `error.hint` | only with `effect: refused` |
+| `hint` | optional; one short sentence saying what to do next (see [Recovery hints](#recovery-hints)) |
+| `next_call` | optional; `{tool, arguments}`, a call that is safe to run as is (see [Recovery hints](#recovery-hints)) |
| `escalation.target` | `pixel`, `foreground`, `page`, `session` |
| `escalation.reason` | `route_unavailable`, `delivery_failed`, `effect_unconfirmed`, `suspected_noop`, `permission_required` |
@@ -66,6 +68,50 @@ The invariants are:
- `refused` has neither delivery nor evidence;
- `error` appears only on `refused`.
+## Recovery hints
+
+A refusal, or an action that ran but was not confirmed, tells the agent what
+to try next. Two optional top-level fields carry it, on every tool and
+platform:
+
+- `hint`: one short sentence (at most 240 characters) saying what to do next.
+- `next_call`: `{"tool": "...", "arguments": {...}}`, the exact call that moves
+ the task forward. It is always safe to run as is: a read such as
+ `get_window_state`, `list_windows`, `get_browser_state` or
+ `check_permissions`, or a call that keeps the user's window where it is. A
+ foreground retry, or anything that needs the user's consent, is never a
+ `next_call`. The `hint` names it with its condition, for example
+ `delivery_mode:"foreground"` "only if the user allows the window to come
+ forward".
+
+They appear on three kinds of result:
+
+| Result | Where the fields sit |
+| --- | --- |
+| An error result (`isError: true`) with a `code` | next to `code` in `structuredContent` |
+| A browser refusal (`status: "refused"`, `refusal.code`) | next to `refusal` in `structuredContent` |
+| An `ActionResult` with `effect` `unverifiable`, `suspected_noop` or `refused` | `hint` and `next_call` on the `ActionResult` |
+
+For example, a background drag that macOS cannot drop returns:
+
+```json
+{
+ "code": "background_unavailable",
+ "reason": "drag_and_drop_session",
+ "hint": "No drop landed: macOS drag-and-drop needs the real pointer. Try a route that is not a drag first (Move button, menu item, shortcut). Retry with delivery_mode:\"foreground\" only if the user allows the window to come forward.",
+ "next_call": {"tool": "get_window_state", "arguments": {"pid": 811, "window_id": 659}}
+}
+```
+
+A producer that already sets `hint` or `next_call` keeps its own value. In
+`run_steps`, a failed step's report carries the same `hint` and `next_call`; in
+`run_script`, the hint is appended to the error message of the failed call.
+In the typed SDK records, `next_call.arguments` is the same JSON object as
+JSON text.
+
+The codes with a hint are listed in the `RULES` table in
+`rust/crates/cua-driver-core/src/recovery_hint.rs`; its tests cover each one.
+
## Window target resolution
Window-scoped actions accept a PID without `window_id` only when that process
diff --git a/libs/cua-driver/python/src/cua_driver/_native_contract.py b/libs/cua-driver/python/src/cua_driver/_native_contract.py
index ce424c1cef..9f9abc657b 100644
--- a/libs/cua-driver/python/src/cua_driver/_native_contract.py
+++ b/libs/cua-driver/python/src/cua_driver/_native_contract.py
@@ -1212,6 +1212,45 @@ class _UniffiFfiConverterTypeActionEvidence(_UniffiConverterRustBuffer):
_UniffiFfiConverterTypeActionEvidenceKind.write(value.kind, buf)
_UniffiFfiConverterOptionalString.write(value.detail, buf)
+@dataclass
+class ActionNextCall:
+ """
+ A call an agent can make next: `{tool, arguments}`.
+"""
+ def __init__(self, *, tool:str, arguments:str):
+ self.tool = tool
+ self.arguments = arguments
+
+
+
+
+ def __str__(self):
+ return "ActionNextCall(tool={}, arguments={})".format(self.tool, self.arguments)
+ def __eq__(self, other):
+ if self.tool != other.tool:
+ return False
+ if self.arguments != other.arguments:
+ return False
+ return True
+
+class _UniffiFfiConverterTypeActionNextCall(_UniffiConverterRustBuffer):
+ @staticmethod
+ def read(buf):
+ return ActionNextCall(
+ tool=_UniffiFfiConverterString.read(buf),
+ arguments=_UniffiFfiConverterString.read(buf),
+ )
+
+ @staticmethod
+ def check_lower(value):
+ _UniffiFfiConverterString.check_lower(value.tool)
+ _UniffiFfiConverterString.check_lower(value.arguments)
+
+ @staticmethod
+ def write(value, buf):
+ _UniffiFfiConverterString.write(value.tool, buf)
+ _UniffiFfiConverterString.write(value.arguments, buf)
+
@@ -1471,9 +1510,34 @@ class _UniffiFfiConverterOptionalTypeActionError(_UniffiConverterRustBuffer):
else:
raise InternalError("Unexpected flag byte for optional type")
+class _UniffiFfiConverterOptionalTypeActionNextCall(_UniffiConverterRustBuffer):
+ @classmethod
+ def check_lower(cls, value):
+ if value is not None:
+ _UniffiFfiConverterTypeActionNextCall.check_lower(value)
+
+ @classmethod
+ def write(cls, value, buf):
+ if value is None:
+ buf.write_u8(0)
+ return
+
+ buf.write_u8(1)
+ _UniffiFfiConverterTypeActionNextCall.write(value, buf)
+
+ @classmethod
+ def read(cls, buf):
+ flag = buf.read_u8()
+ if flag == 0:
+ return None
+ elif flag == 1:
+ return _UniffiFfiConverterTypeActionNextCall.read(buf)
+ else:
+ raise InternalError("Unexpected flag byte for optional type")
+
@dataclass
class ActionResult:
- def __init__(self, *, effect:ActionEffect, route:ActionRoute, delivery:typing.Optional[ActionDelivery], evidence:typing.Optional[typing.List[ActionEvidence]], escalation:typing.Optional[ActionEscalation], summary:typing.Optional[str], error:typing.Optional[ActionError]):
+ def __init__(self, *, effect:ActionEffect, route:ActionRoute, delivery:typing.Optional[ActionDelivery], evidence:typing.Optional[typing.List[ActionEvidence]], escalation:typing.Optional[ActionEscalation], summary:typing.Optional[str], error:typing.Optional[ActionError], hint:typing.Optional[str], next_call:typing.Optional[ActionNextCall]):
self.effect = effect
self.route = route
self.delivery = delivery
@@ -1481,12 +1545,14 @@ class ActionResult:
self.escalation = escalation
self.summary = summary
self.error = error
+ self.hint = hint
+ self.next_call = next_call
def __str__(self):
- return "ActionResult(effect={}, route={}, delivery={}, evidence={}, escalation={}, summary={}, error={})".format(self.effect, self.route, self.delivery, self.evidence, self.escalation, self.summary, self.error)
+ return "ActionResult(effect={}, route={}, delivery={}, evidence={}, escalation={}, summary={}, error={}, hint={}, next_call={})".format(self.effect, self.route, self.delivery, self.evidence, self.escalation, self.summary, self.error, self.hint, self.next_call)
def __eq__(self, other):
if self.effect != other.effect:
return False
@@ -1502,6 +1568,10 @@ class ActionResult:
return False
if self.error != other.error:
return False
+ if self.hint != other.hint:
+ return False
+ if self.next_call != other.next_call:
+ return False
return True
class _UniffiFfiConverterTypeActionResult(_UniffiConverterRustBuffer):
@@ -1515,6 +1585,8 @@ class _UniffiFfiConverterTypeActionResult(_UniffiConverterRustBuffer):
escalation=_UniffiFfiConverterOptionalTypeActionEscalation.read(buf),
summary=_UniffiFfiConverterOptionalString.read(buf),
error=_UniffiFfiConverterOptionalTypeActionError.read(buf),
+ hint=_UniffiFfiConverterOptionalString.read(buf),
+ next_call=_UniffiFfiConverterOptionalTypeActionNextCall.read(buf),
)
@staticmethod
@@ -1526,6 +1598,8 @@ class _UniffiFfiConverterTypeActionResult(_UniffiConverterRustBuffer):
_UniffiFfiConverterOptionalTypeActionEscalation.check_lower(value.escalation)
_UniffiFfiConverterOptionalString.check_lower(value.summary)
_UniffiFfiConverterOptionalTypeActionError.check_lower(value.error)
+ _UniffiFfiConverterOptionalString.check_lower(value.hint)
+ _UniffiFfiConverterOptionalTypeActionNextCall.check_lower(value.next_call)
@staticmethod
def write(value, buf):
@@ -1536,6 +1610,8 @@ class _UniffiFfiConverterTypeActionResult(_UniffiConverterRustBuffer):
_UniffiFfiConverterOptionalTypeActionEscalation.write(value.escalation, buf)
_UniffiFfiConverterOptionalString.write(value.summary, buf)
_UniffiFfiConverterOptionalTypeActionError.write(value.error, buf)
+ _UniffiFfiConverterOptionalString.write(value.hint, buf)
+ _UniffiFfiConverterOptionalTypeActionNextCall.write(value.next_call, buf)
class _UniffiFfiConverterBoolean:
@classmethod
@@ -8637,6 +8713,7 @@ __all__ = [
"ActionError",
"ActionEscalation",
"ActionEvidence",
+ "ActionNextCall",
"ActionResult",
"AppInfo",
"BoundsExpectation",
diff --git a/libs/cua-driver/rust/Skills/cua-driver/SKILL.md b/libs/cua-driver/rust/Skills/cua-driver/SKILL.md
index f5ae15e956..0fa849b862 100644
--- a/libs/cua-driver/rust/Skills/cua-driver/SKILL.md
+++ b/libs/cua-driver/rust/Skills/cua-driver/SKILL.md
@@ -92,6 +92,7 @@ Check the installed version and advertised schema before using unfamiliar parame
| LibreOffice, Preview and other macOS editors | [macOS recipes](MACOS.md#libreoffice-numbers-and-other-editors-in-the-background) |
| Text did not visibly change | Reobserve before retrying; [text and value semantics](WORKFLOW.md#act-once) |
| Browser setup, binding, or ref refused | [Browser recovery](BROWSER.md#recovery-rules) |
+| Any refusal, `unverifiable` or `suspected_noop` | Read `hint` and make `next_call`; [Refusals and hints](WORKFLOW.md#refusals-and-hints) |
## Consult recent Cua activity only for continuation
diff --git a/libs/cua-driver/rust/Skills/cua-driver/WORKFLOW.md b/libs/cua-driver/rust/Skills/cua-driver/WORKFLOW.md
index 2876c27c1a..18a809d204 100644
--- a/libs/cua-driver/rust/Skills/cua-driver/WORKFLOW.md
+++ b/libs/cua-driver/rust/Skills/cua-driver/WORKFLOW.md
@@ -157,9 +157,22 @@ Action facts are not task outcomes:
| `refused` | The route deliberately did not deliver |
| `route` | Public actuator class: `accessibility`, `synthetic_events`, `global_input`, `dom`, or `trusted_input` |
| `escalation` | Suggested next route/reason, never authorization or an automatic retry |
+| `hint` | One sentence on what to do next; see [Refusals and hints](#refusals-and-hints) |
+| `next_call` | `{tool, arguments}` safe to run as is; see [Refusals and hints](#refusals-and-hints) |
Successful action escalation uses `target` (`pixel`, `foreground`, or `page`) and `reason` (`route_unavailable`, `delivery_failed`, `effect_unconfirmed`, `suspected_noop`, or `permission_required`). Error diagnostics may have a different shape; inspect their code and current schema. Missing action facts are not confirmation.
+### Refusals and hints
+
+A refusal, an `unverifiable` action and a `suspected_noop` carry two fields that say what to try next, on every tool:
+
+- `hint`: one short sentence. Read it before you give up or reach for pixels.
+- `next_call`: `{tool, arguments}`, a call that is safe to run as is. It is a read (`get_window_state`, `list_windows`, `get_browser_state`, `check_permissions`) or a call that keeps the user's window where it is. Make it, then decide.
+
+A foreground retry is never a `next_call`. When the `hint` names `delivery_mode:"foreground"`, it comes with a condition: only if the user allows the window to come forward. Without that, the step is blocked: say so and why; do not force it.
+
+The fields sit next to `code` on an error result, next to `refusal` on a browser refusal, and on the `ActionResult` itself. In `run_steps` a failed step's report carries them; in `run_script` the hint is appended to the failed call's error message. A tool that already set its own `hint` or `next_call` keeps it. `next_call` is advice, not an automatic retry: never replay a partial or unknown action without a fresh read.
+
When the postcondition is visibly satisfied, stop acting. For media, selection alone is not playback: check the title, playing/pause indicator, and elapsed progress after preroll/buffering. For closure, verify the requested window disappeared. State only what the evidence proves.
Never replay canceled, partial, or unknown actions automatically. An interrupted transport may have delivered input before losing its response. Report the interruption accurately and obtain fresh state before any further action.
diff --git a/libs/cua-driver/rust/crates/cua-driver-contract/src/lib.rs b/libs/cua-driver/rust/crates/cua-driver-contract/src/lib.rs
index 263916de89..d412e1a4ca 100644
--- a/libs/cua-driver/rust/crates/cua-driver-contract/src/lib.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-contract/src/lib.rs
@@ -64,7 +64,7 @@ pub use outputs::{
advertised_output_schema, conforming_error_envelope, is_refusal_envelope,
refusal_envelope_schema, ActionDelivery, ActionDeliveryMode, ActionEffect, ActionError,
ActionEscalation, ActionEscalationReason, ActionEscalationTarget, ActionEvidence,
- ActionEvidenceKind, ActionResult, ActionResultValidationError, ActionRoute,
+ ActionEvidenceKind, ActionNextCall, ActionResult, ActionResultValidationError, ActionRoute,
AgentOverlayCapture, AgentOverlayCaptureStatus, ClipboardReadOutput, ClipboardWriteOutput,
CursorMotionOutput, CursorPointOutput, CursorPositionOutput, CursorThemeOutput,
CursorVisualOutput, DesktopStateOutput, EffectiveScope, EndSessionOutput,
diff --git a/libs/cua-driver/rust/crates/cua-driver-contract/src/outputs.rs b/libs/cua-driver/rust/crates/cua-driver-contract/src/outputs.rs
index 188eb07e95..4e25c31d06 100644
--- a/libs/cua-driver/rust/crates/cua-driver-contract/src/outputs.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-contract/src/outputs.rs
@@ -696,6 +696,53 @@ pub struct ActionResult {
/// Present only with `effect: refused`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<ActionError>,
+ /// What to do next, in one short sentence. Present when the effect is
+ /// `unverifiable` or `suspected_noop`, so an unconfirmed action points at
+ /// the next step instead of leaving the agent to guess.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub hint: Option<String>,
+ /// The call that moves the task forward, always safe to run as is (a read,
+ /// or a call that keeps the user's window where it is).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub next_call: Option<ActionNextCall>,
+}
+
+/// A call an agent can make next: `{tool, arguments}`.
+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, uniffi::Record)]
+#[serde(deny_unknown_fields)]
+pub struct ActionNextCall {
+ pub tool: String,
+ /// The call's arguments. A JSON object on the wire; the SDK records carry
+ /// the same object as JSON text.
+ #[serde(with = "json_object_text")]
+ #[schemars(schema_with = "object_schema")]
+ pub arguments: String,
+}
+
+/// Serde adapter: a JSON object on the wire, JSON text in the record.
+mod json_object_text {
+ use serde::{
+ de::Error as _, ser::Error as _, Deserialize, Deserializer, Serialize, Serializer,
+ };
+ use serde_json::Value;
+
+ pub fn serialize<S: Serializer>(text: &str, serializer: S) -> Result<S::Ok, S::Error> {
+ match serde_json::from_str::<Value>(text).map_err(S::Error::custom)? {
+ value @ Value::Object(_) => value.serialize(serializer),
+ _ => Err(S::Error::custom(
+ "next_call arguments must be a JSON object",
+ )),
+ }
+ }
+
+ pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<String, D::Error> {
+ match Value::deserialize(deserializer)? {
+ value @ Value::Object(_) => Ok(value.to_string()),
+ _ => Err(D::Error::custom(
+ "next_call arguments must be a JSON object",
+ )),
+ }
+ }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -766,6 +813,10 @@ impl ToolOutput for ActionResult {
}
}
+fn object_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
+ schemars::json_schema!({ "type": "object" })
+}
+
fn string_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({ "type": "string" })
}
@@ -848,6 +899,8 @@ mod tests {
escalation: None,
summary: None,
error: None,
+ hint: None,
+ next_call: None,
}
}
@@ -908,6 +961,8 @@ mod tests {
"error",
"escalation",
"evidence",
+ "hint",
+ "next_call",
"route",
"summary"
]
@@ -1070,6 +1125,47 @@ mod tests {
assert!(serde_json::from_value::<ActionResult>(escalation_extension).is_err());
}
+ #[test]
+ fn hint_and_next_call_travel_as_a_string_and_a_json_object() {
+ let wire = json!({
+ "effect": "unverifiable",
+ "route": "synthetic_events",
+ "hint": "Read what changed before clicking again.",
+ "next_call": {
+ "tool": "get_window_state",
+ "arguments": {"pid": 7, "window_id": 3, "since": "latest"}
+ }
+ });
+ let result = serde_json::from_value::<ActionResult>(wire.clone()).expect("hint");
+ assert_eq!(result.validate_invariants(), Ok(()));
+ assert_eq!(
+ result.hint.as_deref(),
+ Some("Read what changed before clicking again.")
+ );
+ let call = result.next_call.as_ref().expect("next_call");
+ assert_eq!(call.tool, "get_window_state");
+ // The record keeps the arguments as JSON text, so every SDK language reads them.
+ assert_eq!(
+ serde_json::from_str::<Value>(&call.arguments).expect("json text"),
+ json!({"pid": 7, "window_id": 3, "since": "latest"})
+ );
+ // The wire form is the object again.
+ assert_eq!(serde_json::to_value(&result).expect("serialize"), wire);
+
+ let mut not_an_object = wire.clone();
+ not_an_object["next_call"]["arguments"] = json!("get_window_state");
+ assert!(serde_json::from_value::<ActionResult>(not_an_object).is_err());
+ let mut extra = wire;
+ extra["next_call"]["note"] = json!("x");
+ assert!(serde_json::from_value::<ActionResult>(extra).is_err());
+
+ let schema = ActionResult::output_schema();
+ let next_call = object_variant(&schema["properties"]["next_call"]);
+ assert_eq!(next_call["additionalProperties"], false);
+ assert_eq!(next_call["required"], json!(["tool", "arguments"]));
+ assert_eq!(next_call["properties"]["arguments"]["type"], "object");
+ }
+
#[test]
fn action_result_enforces_effect_invariants() {
let mut result = confirmed_result();
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/action_record.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/action_record.rs
index 4097d0857e..424a9061cd 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/action_record.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/action_record.rs
@@ -457,6 +457,9 @@ impl ActionExecutionRecord {
}
_ => None,
},
+ // The dispatch seam adds these after the record is projected.
+ hint: None,
+ next_call: None,
})
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools.rs
index 506434eebf..eec03f0971 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools.rs
@@ -1019,6 +1019,17 @@ async fn run_step(
{
report["code"] = Value::String(code.to_owned());
}
+ // The step's own recovery hint and next call, so a failed batch
+ // says what to do next without a second tool call.
+ for key in ["hint", "next_call"] {
+ if let Some(value) = result
+ .structured_content
+ .as_ref()
+ .and_then(|value| value.get(key))
+ {
+ report[key] = value.clone();
+ }
+ }
return StepOutcome {
line: format!("{}. {label} ERROR (action): {message}", index + 1),
report: with_phase(report, Phase::Action),
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs
index 5fd18d2196..5ab1462c59 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs
@@ -94,6 +94,7 @@ pub mod recording_loader;
pub mod recording_render;
pub mod recording_tools;
pub mod recording_zoom;
+pub mod recovery_hint;
#[cfg(feature = "script")]
pub mod script_tool;
pub mod server;
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/recovery_hint.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/recovery_hint.rs
new file mode 100644
index 0000000000..9b7bc262f2
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/recovery_hint.rs
@@ -0,0 +1,1063 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Recovery hints for refusals and unconfirmed actions.
+//!
+//! When an action is refused, or ran but could not be verified, an agent needs
+//! to know what to try next. Without that, many agents stop at the first
+//! refusal even when a working route exists. This module adds the same two
+//! fields to every such result, whichever tool produced it:
+//!
+//! - `hint`: one short, specific sentence saying what to do next.
+//! - `next_call`: `{tool, arguments}`, the exact call that moves the task
+//! forward. It is always safe to run as is: a read, or a call that keeps the
+//! user's window where it is. A foreground retry or anything that needs the
+//! user's consent is never a `next_call`; the `hint` names it with its
+//! condition ("only if the user allows the window to come forward").
+//!
+//! The browser tools already carry `detail.next_call` on a not-attached
+//! refusal. That stays as it is, and the same call is repeated at the top
+//! level so agents read one place.
+//!
+//! Everything lives in one table ([`RULES`]) plus the unverifiable-action
+//! rules ([`effect_hint`]). [`annotate`] runs once, at the dispatch seam in
+//! `ToolRegistry`, so every platform, every tool and every nested
+//! `run_steps`/`run_script` call is covered. A producer that already set
+//! `hint` or `next_call` keeps its own value.
+
+use serde_json::{json, Map, Value};
+
+use crate::protocol::{Content, ToolResult};
+
+/// Longest `hint`, in characters. Hints stay short so they cost few tokens and
+/// get read.
+pub const MAX_HINT_CHARS: usize = 240;
+
+/// A call the agent can make next. Serialized as `{"tool", "arguments"}`.
+#[derive(Debug, Clone, PartialEq)]
+pub struct NextCall {
+ pub tool: &'static str,
+ pub arguments: Map<String, Value>,
+}
+
+impl NextCall {
+ fn to_value(&self) -> Value {
+ json!({ "tool": self.tool, "arguments": Value::Object(self.arguments.clone()) })
+ }
+}
+
+/// What to say and, when one exists, what to call.
+#[derive(Debug, Clone, PartialEq)]
+pub struct RecoveryHint {
+ pub hint: String,
+ pub next_call: Option<NextCall>,
+}
+
+impl RecoveryHint {
+ fn new(hint: impl Into<String>) -> Self {
+ Self {
+ hint: hint.into(),
+ next_call: None,
+ }
+ }
+
+ fn call(mut self, call: Option<NextCall>) -> Self {
+ self.next_call = call;
+ self
+ }
+}
+
+/// The few request fields a hint needs. Taken from the call's public
+/// arguments before the tool runs, so the dispatch seam keeps no copy of the
+/// whole request.
+#[derive(Debug, Clone, Default)]
+pub struct Seed {
+ pid: Option<i64>,
+ window_id: Option<i64>,
+ session: Option<String>,
+ target_id: Option<String>,
+ tab_id: Option<String>,
+ desktop_target: bool,
+}
+
+impl Seed {
+ /// Read the fields a hint can use from a call's public arguments.
+ pub fn from_args(args: &Value) -> Self {
+ let text = |value: &Value, key: &str| {
+ value
+ .get(key)
+ .and_then(Value::as_str)
+ .filter(|text| !text.is_empty())
+ .map(str::to_owned)
+ };
+ let number = |value: &Value, key: &str| value.get(key).and_then(Value::as_i64);
+ let target = args.get("target");
+ let window_target =
+ target.filter(|t| t.get("kind").and_then(Value::as_str) == Some("window"));
+ Self {
+ pid: number(args, "pid").or_else(|| window_target.and_then(|t| number(t, "pid"))),
+ window_id: number(args, "window_id")
+ .or_else(|| window_target.and_then(|t| number(t, "window_id"))),
+ session: text(args, "session"),
+ target_id: text(args, "target_id"),
+ tab_id: text(args, "tab_id"),
+ desktop_target: target
+ .is_some_and(|t| t.get("kind").and_then(Value::as_str) == Some("desktop"))
+ || args.get("scope").and_then(Value::as_str) == Some("desktop"),
+ }
+ }
+}
+
+/// The structured fields a rule reads, resolved once per result.
+struct Ctx<'a> {
+ tool: &'a str,
+ seed: &'a Seed,
+ structured: &'a Map<String, Value>,
+ /// The window to act on: the call's own, else the one the refusal names.
+ pid: Option<i64>,
+ window_id: Option<i64>,
+}
+
+impl<'a> Ctx<'a> {
+ fn new(tool: &'a str, seed: &'a Seed, structured: &'a Map<String, Value>) -> Self {
+ let named = |key: &str| {
+ structured.get(key).and_then(Value::as_i64).or_else(|| {
+ structured
+ .get("window")
+ .and_then(|window| window.get(key))
+ .and_then(Value::as_i64)
+ })
+ };
+ Self {
+ tool,
+ seed,
+ structured,
+ pid: seed.pid.or_else(|| named("pid")),
+ window_id: seed.window_id.or_else(|| named("window_id")),
+ }
+ }
+
+ fn reason(&self) -> Option<&str> {
+ self.structured.get("reason").and_then(Value::as_str)
+ }
+
+ /// `detail` of a browser refusal, when there is one.
+ fn refusal_detail(&self) -> Option<&Value> {
+ self.structured
+ .get("refusal")
+ .and_then(|refusal| refusal.get("detail"))
+ }
+
+ /// The route the refusing producer itself recommends.
+ fn recommended(&self) -> Option<&str> {
+ self.structured
+ .get("escalation")
+ .and_then(|escalation| escalation.get("recommended"))
+ .and_then(Value::as_str)
+ }
+
+ fn window_args(&self) -> Option<Map<String, Value>> {
+ let (pid, window_id) = (self.pid?, self.window_id?);
+ let mut arguments = Map::new();
+ arguments.insert("pid".into(), json!(pid));
+ arguments.insert("window_id".into(), json!(window_id));
+ if let Some(session) = &self.seed.session {
+ arguments.insert("session".into(), json!(session));
+ }
+ Some(arguments)
+ }
+
+ /// `get_window_state` for a full read: fresh element tokens.
+ fn read_window(&self) -> Option<NextCall> {
+ Some(NextCall {
+ tool: "get_window_state",
+ arguments: self.window_args()?,
+ })
+ }
+
+ /// `get_window_state` for what changed since the last read.
+ fn read_changes(&self) -> Option<NextCall> {
+ let mut arguments = self.window_args()?;
+ arguments.insert("since".into(), json!("latest"));
+ Some(NextCall {
+ tool: "get_window_state",
+ arguments,
+ })
+ }
+
+ /// `get_window_state` for the screenshot only. The current snapshot's
+ /// tokens stay valid.
+ fn look_at_window(&self) -> Option<NextCall> {
+ let mut arguments = self.window_args()?;
+ arguments.insert("include_accessibility_tree".into(), json!(false));
+ Some(NextCall {
+ tool: "get_window_state",
+ arguments,
+ })
+ }
+
+ fn list_windows(&self) -> Option<NextCall> {
+ let mut arguments = Map::new();
+ arguments.insert("pid".into(), json!(self.pid?));
+ Some(NextCall {
+ tool: "list_windows",
+ arguments,
+ })
+ }
+
+ /// `get_browser_state`: the snapshot of a bound tab, else a fresh bind.
+ fn read_page(&self) -> Option<NextCall> {
+ let mut arguments = Map::new();
+ if let (Some(target_id), Some(tab_id)) = (&self.seed.target_id, &self.seed.tab_id) {
+ arguments.insert("target_id".into(), json!(target_id));
+ arguments.insert("tab_id".into(), json!(tab_id));
+ } else {
+ return self.bind_page();
+ }
+ if let Some(session) = &self.seed.session {
+ arguments.insert("session".into(), json!(session));
+ }
+ Some(NextCall {
+ tool: "get_browser_state",
+ arguments,
+ })
+ }
+
+ /// `get_browser_state` in bind mode, which needs the native window.
+ fn bind_page(&self) -> Option<NextCall> {
+ Some(NextCall {
+ tool: "get_browser_state",
+ arguments: self.window_args()?,
+ })
+ }
+
+ /// The `browser_prepare` call that attaches the user's own browser. It
+ /// refuses with nothing changed when it cannot attach.
+ fn attach_browser(&self) -> Option<NextCall> {
+ let mut arguments = self.window_args()?;
+ arguments.insert("strategy".into(), json!({ "kind": "existing_profile" }));
+ Some(NextCall {
+ tool: "browser_prepare",
+ arguments,
+ })
+ }
+
+ fn check_permissions() -> Option<NextCall> {
+ let mut arguments = Map::new();
+ arguments.insert("prompt".into(), json!(false));
+ Some(NextCall {
+ tool: "check_permissions",
+ arguments,
+ })
+ }
+}
+
+/// One table row: every code in `codes` gets the hint `build` produces.
+struct Rule {
+ codes: &'static [&'static str],
+ build: fn(&Ctx) -> RecoveryHint,
+}
+
+const FOREGROUND_CONDITION: &str = "only if the user allows the window to come forward";
+
+/// Every refusal code that carries a hint, with the hint. Add a row here to
+/// cover a new code; the coverage test checks each row.
+static RULES: &[Rule] = &[
+ // The input route is closed in the background.
+ Rule {
+ codes: &["background_unavailable", "background_occluded"],
+ build: background_unavailable,
+ },
+ Rule {
+ codes: &["foreground_unavailable"],
+ build: |c| {
+ RecoveryHint::new(
+ "The window could not be brought forward, so nothing was sent. List the app's windows, \
+ check the window still exists, then retry or act by element instead.",
+ )
+ .call(c.list_windows())
+ },
+ },
+ Rule {
+ codes: &["target_occluded"],
+ build: |c| {
+ RecoveryHint::new(format!(
+ "Another window covers that point, so a background click would land on it. Act by element \
+ (get_window_state, then element_token). Bring the window forward {FOREGROUND_CONDITION}."
+ ))
+ .call(c.read_window())
+ },
+ },
+ // Tokens, snapshots and geometry that went stale.
+ Rule {
+ codes: &["stale_element_token"],
+ build: |c| {
+ RecoveryHint::new(
+ "That element_token comes from an older read. Read the window again for fresh tokens, \
+ then act with the new one.",
+ )
+ .call(c.read_window())
+ },
+ },
+ Rule {
+ codes: &["element_not_visible", "element_bounds_unavailable"],
+ build: |c| {
+ RecoveryHint::new(
+ "The element has no on-screen bounds right now. Scroll it into view, or read the window \
+ again and pick a visible element. Use pixel x,y only if it is missing from the tree.",
+ )
+ .call(c.read_window())
+ },
+ },
+ Rule {
+ codes: &["target_changed", "stale_target", "stale_geometry"],
+ build: |c| {
+ RecoveryHint::new(
+ "The window changed since your last read, so nothing was sent. Read it again and aim from \
+ the fresh state.",
+ )
+ .call(c.read_window())
+ },
+ },
+ Rule {
+ codes: &["desktop_changed"],
+ build: |c| {
+ RecoveryHint::new(
+ "The screen changed since your last read, so nothing was sent. Read it again and aim from \
+ the fresh state.",
+ )
+ .call(c.read_window().or_else(|| {
+ c.seed.desktop_target.then(|| NextCall {
+ tool: "get_desktop_state",
+ arguments: Map::new(),
+ })
+ }))
+ },
+ },
+ Rule {
+ codes: &["point_outside_window"],
+ build: |c| {
+ RecoveryHint::new(
+ "x,y are pixels of that window's latest screenshot, and this point falls outside it. Look \
+ at the window to see its size, then aim inside it.",
+ )
+ .call(c.look_at_window())
+ },
+ },
+ Rule {
+ codes: &["px_frame_mismatch"],
+ build: |c| {
+ RecoveryHint::new(
+ "The window's screenshot does not match its on-screen size, so no pixel was sent. Read the \
+ window again, or act by element_token instead of pixels.",
+ )
+ .call(c.read_window())
+ },
+ },
+ Rule {
+ codes: &["px_capture_unavailable"],
+ build: |_| {
+ RecoveryHint::new(
+ "The window could not be captured. Check Screen Recording with check_permissions, and act \
+ by element_token while it is missing.",
+ )
+ .call(Ctx::check_permissions())
+ },
+ },
+ // Which window.
+ Rule {
+ codes: &[
+ "window_target_not_found",
+ "window_id_not_found",
+ "px_window_not_found",
+ ],
+ build: |c| {
+ RecoveryHint::new(
+ "No window matches that target now. List the app's windows and use a current window_id; \
+ launch or restore the app if it has none.",
+ )
+ .call(c.list_windows())
+ },
+ },
+ Rule {
+ codes: &["window_id_required"],
+ build: |c| {
+ RecoveryHint::new(
+ "This action is addressed to one exact window. Take its window_id from list_windows for \
+ this pid and retry with it.",
+ )
+ .call(c.list_windows())
+ },
+ },
+ Rule {
+ codes: &["ambiguous_window_target"],
+ build: |c| {
+ RecoveryHint::new(
+ "The app has several windows. Choose the window_id you mean from the candidates (or \
+ list_windows) and retry with it.",
+ )
+ .call(c.list_windows())
+ },
+ },
+ Rule {
+ codes: &["window_minimized"],
+ build: |c| {
+ RecoveryHint::new(format!(
+ "The window is minimized, so input would miss. Restore it (bring_to_front {FOREGROUND_CONDITION}), \
+ then list the windows and retry."
+ ))
+ .call(c.list_windows())
+ },
+ },
+ // Permissions and authorization.
+ Rule {
+ codes: &[
+ "permission_denied",
+ "authorization_required",
+ "authorization_declined",
+ "authorization_canceled",
+ "authorization_expired",
+ "authorization_scope_mismatch",
+ "authorization_host_failed",
+ "authorization_suspended",
+ "authorization_revoked",
+ "bounded_resource_outside_manifest",
+ "foreign_process_termination_denied",
+ "unbounded_operation_requires_unrestricted",
+ "pending_operator_approval",
+ ],
+ build: |_| {
+ RecoveryHint::new(
+ "This session's permission rules, or the user, refused the call. Do not retry it or work \
+ around it. Tell the user what was refused and ask them to allow it if the task needs it.",
+ )
+ },
+ },
+ Rule {
+ codes: &["os_permission_prompt_requires_trusted_host"],
+ build: |_| {
+ RecoveryHint::new(
+ "Operating-system permission prompts are raised by the user or the host, not by tools. \
+ Check which grants are missing with check_permissions (prompt:false) and ask the user to \
+ grant them.",
+ )
+ .call(Ctx::check_permissions())
+ },
+ },
+ Rule {
+ codes: &["permission_required"],
+ build: |_| {
+ RecoveryHint::new(
+ "A permission is still pending. Ask the user to approve it, check what is missing with \
+ check_permissions (prompt:false), then retry.",
+ )
+ .call(Ctx::check_permissions())
+ },
+ },
+ // Sessions.
+ Rule {
+ codes: &["session_ended"],
+ build: |c| {
+ let mut arguments = Map::new();
+ if let Some(session) = &c.seed.session {
+ arguments.insert("session".into(), json!(session));
+ }
+ RecoveryHint::new(
+ "That session has ended. Start it again with start_session (same label), or use a new \
+ session label.",
+ )
+ .call(Some(NextCall {
+ tool: "start_session",
+ arguments,
+ }))
+ },
+ },
+ Rule {
+ codes: &["session_not_started", "session_required"],
+ build: |c| {
+ let mut arguments = Map::new();
+ if let Some(session) = &c.seed.session {
+ arguments.insert("session".into(), json!(session));
+ }
+ RecoveryHint::new(
+ "This call needs a started session. Call start_session with a short label, then repeat \
+ that label on later calls.",
+ )
+ .call(Some(NextCall {
+ tool: "start_session",
+ arguments,
+ }))
+ },
+ },
+ // Menus.
+ Rule {
+ codes: &["menu_path_unavailable", "option_not_found"],
+ build: |c| {
+ RecoveryHint::new(
+ "That menu path or option does not exist in the app right now. Read the window to see the \
+ exact menu titles, then retry with them.",
+ )
+ .call(c.read_window())
+ },
+ },
+ // Typing and values.
+ Rule {
+ codes: &["type_text_incomplete"],
+ build: |c| {
+ let delivered = c
+ .structured
+ .get("delivered_chars")
+ .and_then(Value::as_u64)
+ .map(|n| format!("Only the first {n} characters landed. "))
+ .unwrap_or_default();
+ RecoveryHint::new(format!(
+ "{delivered}Read the field to confirm, then type only the missing rest; do not resend it all."
+ ))
+ .call(c.read_changes())
+ },
+ },
+ Rule {
+ codes: &["write_not_applied", "set_value_unavailable"],
+ build: |_| {
+ RecoveryHint::new(format!(
+ "The control did not take that value. Click it and use type_text, or use a keyboard \
+ shortcut. Bring the window forward {FOREGROUND_CONDITION}."
+ ))
+ },
+ },
+ Rule {
+ codes: &["select_menu_would_raise_window"],
+ build: |_| {
+ RecoveryHint::new(format!(
+ "Choose the option with set_value(element_token, option text); it never opens the menu. \
+ Open the menu with delivery_mode:\"foreground\" {FOREGROUND_CONDITION}."
+ ))
+ },
+ },
+ Rule {
+ codes: &["paste_target_is_browser_chrome"],
+ build: |_| {
+ RecoveryHint::new(
+ "The focused field is the browser's own address bar, not the page. Focus the page field \
+ first (click it by element_token), or use browser_type for page text.",
+ )
+ },
+ },
+ Rule {
+ codes: &["popup_keyboard_grab"],
+ build: |c| {
+ RecoveryHint::new(
+ "A popup holds the keyboard. Dismiss it (click an item in it, or outside it), then send \
+ the keys again.",
+ )
+ .call(c.read_window())
+ },
+ },
+ Rule {
+ codes: &["target_focus_unconfirmed"],
+ build: |c| {
+ RecoveryHint::new(
+ "The window did not confirm keyboard focus, so no key was sent. Read the window, click a \
+ field in it by element_token, then send the keys.",
+ )
+ .call(c.read_window())
+ },
+ },
+ Rule {
+ codes: &["delivery_failed", "foreground_partial_unknown"],
+ build: |c| {
+ RecoveryHint::new(
+ "The input may have partly landed. Read the window before repeating anything.",
+ )
+ .call(c.read_changes())
+ },
+ },
+ Rule {
+ codes: &[
+ "typed_output_mismatch",
+ "action_outcome_mismatch",
+ "tool_output_invalid",
+ ],
+ build: |c| {
+ RecoveryHint::new(
+ "The driver could not confirm its own result, so the action may have run. Read the window \
+ before repeating it.",
+ )
+ .call(c.read_changes())
+ },
+ },
+ Rule {
+ codes: &["lane_busy", "primary_target_busy"],
+ build: |_| {
+ RecoveryHint::new(
+ "Another action is using this window's input. Wait a moment and retry once; do not fire \
+ parallel actions at one window.",
+ )
+ },
+ },
+ Rule {
+ codes: &["desktop_coordinate_scope_required"],
+ build: |_| {
+ RecoveryHint::new(
+ "x,y with no pid or window_id mean screen pixels, which need scope:\"desktop\". To act in \
+ one window, pass its pid and window_id with that window's screenshot pixels.",
+ )
+ },
+ },
+ Rule {
+ codes: &["invalid_arguments"],
+ build: |_| {
+ RecoveryHint::new(
+ "An argument is missing, misspelled or the wrong type. Check the tool's input schema \
+ (tools/list, or `cua-driver describe <tool>`) and resend valid arguments.",
+ )
+ },
+ },
+ // Browser tools.
+ Rule {
+ codes: &["browser_consent_required"],
+ build: browser_consent_required,
+ },
+ Rule {
+ codes: &["browser_requires_setup"],
+ build: |c| {
+ RecoveryHint::new(
+ "No browser endpoint is attached to this window yet. Call browser_prepare with this pid \
+ and window_id; it attaches, or refuses with nothing changed and says why. Do not switch \
+ to desktop pointer tools.",
+ )
+ .call(c.attach_browser())
+ },
+ },
+ Rule {
+ codes: &["browser_ref_stale"],
+ build: |c| {
+ RecoveryHint::new(
+ "That page ref no longer matches the live page. Read the page again with get_browser_state \
+ for fresh refs, then act on a new one.",
+ )
+ .call(c.read_page())
+ },
+ },
+ Rule {
+ codes: &["browser_binding_stale"],
+ build: |c| {
+ RecoveryHint::new(
+ "The browser window or process changed since you bound it. Bind again with \
+ get_browser_state (pid and window_id from list_windows) and use the new target_id and tab_id.",
+ )
+ .call(c.bind_page())
+ },
+ },
+ Rule {
+ codes: &["browser_binding_ambiguous"],
+ build: |_| {
+ RecoveryHint::new(
+ "Several browser pages match this window, so none was chosen. Bind again with \
+ get_browser_state once the page you mean is the only match, or tell the user.",
+ )
+ },
+ },
+ Rule {
+ codes: &["browser_tab_required", "browser_tab_not_found"],
+ build: |c| {
+ RecoveryHint::new(
+ "This call needs a current tab_id. Bind the window with get_browser_state (pid and \
+ window_id); it returns target_id and tab_id.",
+ )
+ .call(c.bind_page())
+ },
+ },
+ Rule {
+ codes: &["browser_wrong_target_refused"],
+ build: |c| {
+ RecoveryHint::new(
+ "The driver could not prove this page belongs to that window, so it did nothing. Bind \
+ again with get_browser_state, using the browser's main window and pid, not a helper.",
+ )
+ .call(c.bind_page())
+ },
+ },
+ Rule {
+ codes: &["browser_route_unavailable"],
+ build: |c| {
+ RecoveryHint::new(
+ "This window has no browser-tool route. Act on it through the accessibility tree instead: \
+ get_window_state, then click or set_value by element_token.",
+ )
+ .call(c.read_window())
+ },
+ },
+ Rule {
+ codes: &["browser_input_trust_unavailable"],
+ build: browser_input_trust_unavailable,
+ },
+ Rule {
+ codes: &["browser_input_incomplete"],
+ build: |c| {
+ let counts = c.refusal_detail().and_then(|detail| {
+ Some(format!(
+ "Typing stopped after {} of {} characters. ",
+ detail.get("delivered_chars")?.as_u64()?,
+ detail.get("requested_chars")?.as_u64()?
+ ))
+ });
+ RecoveryHint::new(format!(
+ "{}Read the field with get_browser_state, then type only what is missing.",
+ counts.unwrap_or_default()
+ ))
+ .call(c.read_page())
+ },
+ },
+ Rule {
+ codes: &["browser_action_unavailable"],
+ build: |c| {
+ RecoveryHint::new(
+ "That ref does not support this action. Read the page again with get_browser_state and \
+ pick a ref that lists it, or use another browser tool such as browser_pointer.",
+ )
+ .call(c.read_page())
+ },
+ },
+ Rule {
+ codes: &["browser_reconnect_exhausted"],
+ build: |c| {
+ RecoveryHint::new(
+ "The browser connection dropped and did not come back. Bind again with get_browser_state; \
+ if it refuses, run browser_prepare from its next_call.",
+ )
+ .call(c.bind_page())
+ },
+ },
+ Rule {
+ codes: &["browser_endpoint_owner_mismatch"],
+ build: |c| {
+ RecoveryHint::new(
+ "The DevTools endpoint found is not provably this browser's, so it was refused. Act \
+ through get_window_state and the accessibility tree instead.",
+ )
+ .call(c.read_window())
+ },
+ },
+ Rule {
+ codes: &["browser_consent_revoked", "browser_origin_outside_scope"],
+ build: |_| {
+ RecoveryHint::new(
+ "Browser access was turned off or the page left the approved sites. Do not work around \
+ it. Tell the user, and continue without browser tools or ask them to allow it.",
+ )
+ },
+ },
+];
+
+/// Every refusal code that has a hint.
+pub fn covered_codes() -> impl Iterator<Item = &'static str> {
+ RULES.iter().flat_map(|rule| rule.codes.iter().copied())
+}
+
+fn background_unavailable(c: &Ctx) -> RecoveryHint {
+ // A refusal with a working background route leads with it, then names the
+ // foreground retry with its condition.
+ let foreground = format!("Retry with delivery_mode:\"foreground\" {FOREGROUND_CONDITION}.");
+ match (c.tool, c.reason()) {
+ _ if c.structured.get("window").is_some() => RecoveryHint::new(
+ "That desktop point is over a background app, so the action would use the user's pointer. \
+ Target the window instead: target {kind:\"window\", pid, window_id} with pixels from its \
+ own screenshot.",
+ )
+ .call(c.look_at_window()),
+ (_, _) if c.seed.desktop_target => RecoveryHint::new(
+ "Desktop input uses the real pointer, so it has no background mode. To stay in the background, \
+ act inside the window: target {kind:\"window\", pid, window_id} with pixels from its \
+ screenshot. Foreground only if the user allows the pointer to move.",
+ )
+ .call(c.look_at_window()),
+ (_, Some("drag_and_drop_session")) => RecoveryHint::new(format!(
+ "No drop landed: macOS drag-and-drop needs the real pointer. Try a route that is not a drag \
+ first (Move button, menu item, shortcut). {foreground}"
+ ))
+ .call(c.read_window()),
+ (_, Some("electron_main_process_unavailable")) => RecoveryHint::new(format!(
+ "This Electron window cannot take a background drag. Use the app's own controls (button, \
+ menu item or keyboard route). {foreground}"
+ ))
+ .call(c.read_window()),
+ (_, Some("pointer_reading_toolkit")) => RecoveryHint::new(format!(
+ "This app's toolkit reads the real pointer, so background pixel clicks miss. Act by element \
+ (get_window_state, then element_token) or invoke_menu. {foreground}"
+ ))
+ .call(c.read_window()),
+ (_, Some("windowserver_connection_invalid")) => RecoveryHint::new(
+ "The daemon has no valid WindowServer connection. Run the app-bundle daemon (not a bare \
+ `cua-driver serve`) and retry.",
+ ),
+ ("invoke_menu", _) => RecoveryHint::new(format!(
+ "macOS keeps this menu item disabled while the app is behind the user's window. Use the same \
+ control in the window (get_window_state, then click by element_token). bring_to_front first \
+ {FOREGROUND_CONDITION}."
+ ))
+ .call(c.read_window()),
+ ("browser_prepare", _) => RecoveryHint::new(format!(
+ "Not blocked: read the page through the window's accessibility tree with get_window_state and \
+ act by element_token. Use foreground delivery {FOREGROUND_CONDITION}."
+ ))
+ .call(c.read_window()),
+ ("scroll", _) => RecoveryHint::new(format!(
+ "This window drops background wheel events. Find the item with a get_window_state query and \
+ act on it by element_token, with no scroll. {foreground}"
+ ))
+ .call(c.read_window()),
+ _ if c.recommended() == Some("page") => RecoveryHint::new(
+ "This is a web page: use the browser tools, which leave the user's pointer alone. Read it \
+ with get_browser_state, then browser_click, browser_type or browser_pointer.",
+ )
+ .call(c.bind_page()),
+ _ if c.recommended() == Some("px") => RecoveryHint::new(
+ "Use the pixel form instead: x,y from a fresh screenshot of this window (get_window_state).",
+ )
+ .call(c.look_at_window()),
+ _ => RecoveryHint::new(format!(
+ "No background route for this action. Try an element action, invoke_menu, a shortcut or the \
+ browser tools first. {foreground} Otherwise report the step as blocked."
+ ))
+ .call(c.read_window()),
+ }
+}
+
+fn browser_consent_required(c: &Ctx) -> RecoveryHint {
+ if c.tool == "browser_prepare" {
+ return RecoveryHint::new(
+ "Attaching to this browser needs authorization from the user or the host. Retrying will not \
+ change that. Read the page through get_window_state and the accessibility tree instead, or \
+ ask the user to authorize it.",
+ )
+ .call(c.read_window());
+ }
+ // A producer that already names the attach call keeps its exact arguments.
+ let named = c
+ .refusal_detail()
+ .and_then(|detail| detail.get("next_call"))
+ .and_then(|call| {
+ let arguments = call.get("arguments")?.as_object()?.clone();
+ (call.get("tool")?.as_str()? == "browser_prepare").then_some(NextCall {
+ tool: "browser_prepare",
+ arguments,
+ })
+ });
+ RecoveryHint::new(
+ "Attach to this browser window first: make the browser_prepare call in next_call. It attaches, \
+ or refuses with nothing changed and says why. Do not switch to desktop pointer tools; they move \
+ the user's pointer.",
+ )
+ .call(named.or_else(|| c.attach_browser()))
+}
+
+fn browser_input_trust_unavailable(c: &Ctx) -> RecoveryHint {
+ let alternative = c
+ .refusal_detail()
+ .and_then(|detail| detail.get("alternative_route"))
+ .and_then(Value::as_str);
+ match alternative {
+ Some(route) => RecoveryHint::new(format!(
+ "Trusted input is not available in the background here. For a ref, retry with \
+ input_route:\"{route}\" (a synthetic click). Foreground delivery {FOREGROUND_CONDITION}."
+ )),
+ None => RecoveryHint::new(format!(
+ "Trusted browser input is not available right now. Read the page again with get_browser_state \
+ and retry once, or act through the accessibility tree. Foreground delivery {FOREGROUND_CONDITION}."
+ ))
+ .call(c.read_page()),
+ }
+}
+
+/// Tools whose successful result is an action result.
+const ACTION_TOOLS: &[&str] = &[
+ "click",
+ "double_click",
+ "right_click",
+ "scroll",
+ "drag",
+ "mouse_drag",
+ "parallel_mouse_drag",
+ "move_cursor",
+ "mouse_button_down",
+ "mouse_button_up",
+ "type_text",
+ "type_text_chars",
+ "press_key",
+ "hotkey",
+ "set_value",
+ "set_window_frame",
+ "invoke_menu",
+ "browser_click",
+ "browser_pointer",
+ "browser_type",
+ "browser_select",
+ "browser_set_input_files",
+];
+
+/// The hint for an action that ran but was not confirmed. `effect` is
+/// `unverifiable` (nothing could prove it) or `suspected_noop` (the evidence
+/// says nothing changed).
+fn effect_hint(c: &Ctx, effect: &str) -> Option<RecoveryHint> {
+ if !ACTION_TOOLS.contains(&c.tool) {
+ return None;
+ }
+ let noop = effect == "suspected_noop";
+ let browser = c.tool.starts_with("browser_");
+ if browser {
+ let text = match (c.tool, noop) {
+ ("browser_type", false) => {
+ "The text was typed but not read back. Read the field with get_browser_state before typing again."
+ }
+ (_, true) => {
+ "The page probably did not react. Read it again with get_browser_state and pick a fresh \
+ ref before retrying."
+ }
+ _ => {
+ "The action was sent but nothing confirmed it. Read the page again with get_browser_state \
+ and check the change before repeating."
+ }
+ };
+ return Some(RecoveryHint::new(text).call(c.read_page()));
+ }
+ let text = match (c.tool, noop) {
+ ("click" | "double_click" | "right_click", false) => {
+ "The click was sent but nothing confirmed it. Read what changed before clicking again; a \
+ repeat can toggle or double-fire."
+ }
+ ("click" | "double_click" | "right_click", true) => {
+ "The click probably did nothing. Read the window, then aim again from the fresh screenshot or \
+ use the element's own action (element_token)."
+ }
+ ("drag" | "mouse_drag" | "parallel_mouse_drag", _) => {
+ "The drag was posted but no drop was confirmed. Read what changed before repeating. If nothing \
+ moved, start the press inside the item (pixels of the latest screenshot) or use a Move \
+ control or menu instead."
+ }
+ ("type_text" | "type_text_chars", _) => {
+ "The text was delivered but not read back. Read the field before typing again, or it may be \
+ duplicated."
+ }
+ ("press_key" | "hotkey", _) => {
+ "The key was sent but its effect is not confirmed. Read what changed before sending it again."
+ }
+ ("scroll", _) => {
+ "The scroll was sent but not confirmed. Check that the content moved before scrolling more."
+ }
+ ("set_value", _) => {
+ "The value was written but not read back. Read the element again to confirm it before relying \
+ on it."
+ }
+ ("invoke_menu", _) => {
+ "The menu item was invoked but its effect is not confirmed. Read the window for a new dialog \
+ or change before invoking it again."
+ }
+ _ => {
+ "The action was sent but not confirmed. Read what changed, or check a postcondition with \
+ verify_state, before repeating it."
+ }
+ };
+ Some(RecoveryHint::new(text).call(c.read_changes()))
+}
+
+/// The refusal code in a structured payload: the top-level `code`, the
+/// browser refusal's `refusal.code`, or a refused action's `error.code`.
+fn code_of(structured: &Map<String, Value>) -> Option<&str> {
+ structured
+ .get("code")
+ .and_then(Value::as_str)
+ .or_else(|| {
+ structured
+ .get("refusal")
+ .and_then(|refusal| refusal.get("code"))
+ .and_then(Value::as_str)
+ })
+ .or_else(|| {
+ structured
+ .get("error")
+ .and_then(|error| error.get("code"))
+ .and_then(Value::as_str)
+ })
+}
+
+/// The hint for a structured payload, or `None` when the payload is not a
+/// refusal or an unconfirmed action, or no rule covers its code.
+pub fn recovery_for(
+ tool: &str,
+ seed: &Seed,
+ is_error: bool,
+ structured: &Map<String, Value>,
+) -> Option<RecoveryHint> {
+ let ctx = Ctx::new(tool, seed, structured);
+ let effect = structured.get("effect").and_then(Value::as_str);
+ let refused = is_error
+ || effect == Some("refused")
+ || structured.get("status").and_then(Value::as_str) == Some("refused");
+ if refused {
+ let code = code_of(structured)?;
+ let rule = RULES.iter().find(|rule| rule.codes.contains(&code))?;
+ return Some((rule.build)(&ctx));
+ }
+ match effect {
+ Some(effect @ ("unverifiable" | "suspected_noop")) => effect_hint(&ctx, effect),
+ _ => None,
+ }
+}
+
+/// The hint for an error with no structured payload, recognised from its
+/// message. Only unmistakable cases: everything else stays as it is.
+fn hint_for_plain_error(message: &str) -> Option<RecoveryHint> {
+ let lowered = message.to_ascii_lowercase();
+ if lowered.starts_with("missing required parameter") || lowered.contains(": missing required") {
+ return Some(RecoveryHint::new(
+ "A required argument is missing. Check the tool's input schema (tools/list, or `cua-driver \
+ describe <tool>`) and resend with every required argument.",
+ ));
+ }
+ None
+}
+
+fn first_text(result: &ToolResult) -> Option<&str> {
+ result.content.iter().find_map(|content| match content {
+ Content::Text { text, .. } => Some(text.as_str()),
+ _ => None,
+ })
+}
+
+/// Add `hint` and `next_call` to a refusal or an unconfirmed action. A field
+/// the producer already set stays as it is. Called once per tool call at the
+/// dispatch seam, with the arguments the caller sent.
+pub fn annotate(tool: &str, seed: &Seed, result: &mut ToolResult) {
+ let is_error = result.is_error == Some(true);
+ let recovery = match result.structured_content.as_ref() {
+ Some(Value::Object(structured)) => recovery_for(tool, seed, is_error, structured),
+ Some(_) => None,
+ None if is_error => {
+ let hint = first_text(result).and_then(hint_for_plain_error);
+ if hint.is_some() {
+ // A plain error gains a code so the hint has a payload to ride on.
+ result.structured_content = Some(json!({ "code": "invalid_arguments" }));
+ }
+ hint
+ }
+ None => None,
+ };
+ let Some(recovery) = recovery else {
+ return;
+ };
+ let Some(Value::Object(structured)) = result.structured_content.as_mut() else {
+ return;
+ };
+ structured
+ .entry("hint")
+ .or_insert_with(|| Value::String(recovery.hint));
+ if let Some(call) = recovery.next_call {
+ structured
+ .entry("next_call")
+ .or_insert_with(|| call.to_value());
+ }
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/recovery_hint/tests.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/recovery_hint/tests.rs
new file mode 100644
index 0000000000..af032110de
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/recovery_hint/tests.rs
@@ -0,0 +1,846 @@
+use super::*;
+
+const WINDOW: &Value = &Value::Null;
+
+fn seed(args: Value) -> Seed {
+ Seed::from_args(&args)
+}
+
+fn window_seed() -> Seed {
+ seed(json!({"pid": 4242, "window_id": 17, "session": "run-1"}))
+}
+
+fn structured(value: Value) -> Map<String, Value> {
+ value.as_object().expect("object").clone()
+}
+
+fn hint_for(tool: &str, seed: &Seed, is_error: bool, value: Value) -> RecoveryHint {
+ recovery_for(tool, seed, is_error, &structured(value))
+ .unwrap_or_else(|| panic!("no hint for {tool}"))
+}
+
+fn call_value(hint: &RecoveryHint) -> Value {
+ hint.next_call.as_ref().expect("next_call").to_value()
+}
+
+#[test]
+fn every_covered_code_has_a_short_non_empty_hint() {
+ let with_window = window_seed();
+ let without = Seed::default();
+ let mut count = 0;
+ let mut too_long = Vec::new();
+ for code in covered_codes() {
+ count += 1;
+ for seed in [&with_window, &without] {
+ let hint = hint_for("click", seed, true, json!({ "code": code }));
+ assert!(!hint.hint.trim().is_empty(), "{code}");
+ if hint.hint.chars().count() > MAX_HINT_CHARS {
+ too_long.push(format!("{code}: {}", hint.hint));
+ }
+ }
+ // The browser refusal shape carries the same code one level down.
+ let nested = hint_for(
+ "browser_click",
+ &with_window,
+ false,
+ json!({"status": "refused", "refusal": {"code": code, "message": "m"}}),
+ );
+ assert!(!nested.hint.is_empty(), "{code}");
+ }
+ assert!(too_long.is_empty(), "{too_long:#?}");
+ assert!(count >= 50, "table shrank to {count} codes");
+}
+
+#[test]
+fn every_hint_variant_stays_within_the_length_limit() {
+ let seed = window_seed();
+ let variants = [
+ (
+ "drag",
+ json!({"code": "background_unavailable", "reason": "drag_and_drop_session"}),
+ ),
+ (
+ "drag",
+ json!({"code": "background_unavailable", "reason": "electron_main_process_unavailable"}),
+ ),
+ (
+ "click",
+ json!({"code": "background_unavailable", "reason": "pointer_reading_toolkit"}),
+ ),
+ (
+ "click",
+ json!({"code": "background_unavailable", "reason": "windowserver_connection_invalid"}),
+ ),
+ (
+ "click",
+ json!({"code": "background_unavailable", "window": {"pid": 1, "window_id": 2}}),
+ ),
+ ("invoke_menu", json!({"code": "background_unavailable"})),
+ ("browser_prepare", json!({"code": "background_unavailable"})),
+ ("scroll", json!({"code": "background_unavailable"})),
+ (
+ "click",
+ json!({"code": "background_unavailable", "escalation": {"recommended": "page"}}),
+ ),
+ (
+ "click",
+ json!({"code": "background_unavailable", "escalation": {"recommended": "px"}}),
+ ),
+ (
+ "click",
+ json!({"code": "background_unavailable", "escalation": {"recommended": "foreground"}}),
+ ),
+ (
+ "browser_prepare",
+ json!({"code": "browser_consent_required"}),
+ ),
+ (
+ "get_browser_state",
+ json!({"code": "browser_consent_required"}),
+ ),
+ (
+ "browser_click",
+ json!({"code": "browser_input_trust_unavailable"}),
+ ),
+ (
+ "type_text",
+ json!({"code": "type_text_incomplete", "delivered_chars": 12}),
+ ),
+ ];
+ let too_long: Vec<String> = variants
+ .into_iter()
+ .filter_map(|(tool, value)| {
+ let hint = hint_for(tool, &seed, true, value.clone());
+ (hint.hint.chars().count() > MAX_HINT_CHARS).then(|| {
+ format!(
+ "{tool} {value}: {} chars: {}",
+ hint.hint.chars().count(),
+ hint.hint
+ )
+ })
+ })
+ .collect();
+ assert!(too_long.is_empty(), "{too_long:#?}");
+}
+
+#[test]
+fn the_table_covers_every_code_agents_hit_most() {
+ let covered: Vec<&str> = covered_codes().collect();
+ for code in [
+ "background_unavailable",
+ "browser_consent_required",
+ "browser_requires_setup",
+ "browser_ref_stale",
+ "browser_binding_stale",
+ "browser_tab_required",
+ "browser_tab_not_found",
+ "browser_input_trust_unavailable",
+ "browser_input_incomplete",
+ "browser_action_unavailable",
+ "browser_wrong_target_refused",
+ "browser_route_unavailable",
+ "stale_element_token",
+ "element_not_visible",
+ "element_bounds_unavailable",
+ "target_changed",
+ "stale_target",
+ "stale_geometry",
+ "desktop_changed",
+ "point_outside_window",
+ "px_frame_mismatch",
+ "window_target_not_found",
+ "ambiguous_window_target",
+ "window_id_required",
+ "window_id_not_found",
+ "window_minimized",
+ "permission_required",
+ "permission_denied",
+ "os_permission_prompt_requires_trusted_host",
+ "session_not_started",
+ "session_ended",
+ "session_required",
+ "menu_path_unavailable",
+ "option_not_found",
+ "type_text_incomplete",
+ "typed_output_mismatch",
+ "set_value_unavailable",
+ "paste_target_is_browser_chrome",
+ "popup_keyboard_grab",
+ "lane_busy",
+ "primary_target_busy",
+ "invalid_arguments",
+ ] {
+ assert!(covered.contains(&code), "no hint for {code}");
+ }
+ let mut seen = std::collections::HashSet::new();
+ for code in covered {
+ assert!(seen.insert(code), "{code} appears in two rules");
+ }
+}
+
+#[test]
+fn a_drag_refused_by_macos_drag_and_drop_names_a_non_drag_route_and_the_foreground_condition() {
+ let hint = hint_for(
+ "drag",
+ &window_seed(),
+ true,
+ json!({
+ "code": "background_unavailable",
+ "effect": "no_drop",
+ "reason": "drag_and_drop_session",
+ "event_kind": "mouse_drag",
+ }),
+ );
+ assert_eq!(
+ hint.hint,
+ "No drop landed: macOS drag-and-drop needs the real pointer. Try a route that is not a drag first \
+ (Move button, menu item, shortcut). Retry with delivery_mode:\"foreground\" \
+ only if the user allows the window to come forward."
+ );
+ assert_eq!(
+ call_value(&hint),
+ json!({
+ "tool": "get_window_state",
+ "arguments": {"pid": 4242, "window_id": 17, "session": "run-1"},
+ })
+ );
+}
+
+#[test]
+fn a_next_call_never_asks_for_the_foreground() {
+ let seed = window_seed();
+ for (tool, value) in [
+ (
+ "drag",
+ json!({"code": "background_unavailable", "reason": "drag_and_drop_session"}),
+ ),
+ ("click", json!({"code": "background_unavailable"})),
+ ("invoke_menu", json!({"code": "background_unavailable"})),
+ ("browser_prepare", json!({"code": "background_unavailable"})),
+ ("scroll", json!({"code": "background_unavailable"})),
+ ("click", json!({"code": "target_occluded"})),
+ ("click", json!({"code": "window_minimized"})),
+ ] {
+ let hint = hint_for(tool, &seed, true, value);
+ if let Some(call) = &hint.next_call {
+ let rendered = call.to_value().to_string();
+ assert!(!rendered.contains("foreground"), "{tool}: {rendered}");
+ assert!(!rendered.contains("bring_to_front"), "{tool}: {rendered}");
+ assert!(call.arguments.get("delivery_mode").is_none(), "{tool}");
+ }
+ }
+}
+
+#[test]
+fn a_desktop_point_over_a_background_app_points_at_the_window_target() {
+ let hint = hint_for(
+ "click",
+ &seed(json!({"x": 100, "y": 200, "scope": "desktop"})),
+ true,
+ json!({
+ "code": "background_unavailable",
+ "event_kind": "click",
+ "window": {"pid": 811, "window_id": 659, "app_name": "Notes"},
+ }),
+ );
+ assert!(hint
+ .hint
+ .contains("target {kind:\"window\", pid, window_id}"));
+ assert_eq!(
+ call_value(&hint),
+ json!({
+ "tool": "get_window_state",
+ "arguments": {"pid": 811, "window_id": 659, "include_accessibility_tree": false},
+ })
+ );
+}
+
+#[test]
+fn a_menu_item_disabled_in_the_background_points_at_the_control_in_the_window() {
+ let hint = hint_for(
+ "invoke_menu",
+ &window_seed(),
+ true,
+ json!({
+ "status": "refused",
+ "code": "background_unavailable",
+ "refusal": {"code": "background_unavailable", "message": "disabled"},
+ }),
+ );
+ assert!(hint
+ .hint
+ .contains("bring_to_front first only if the user allows"));
+ assert_eq!(call_value(&hint)["tool"], "get_window_state");
+}
+
+#[test]
+fn a_stale_element_token_asks_for_a_fresh_read_of_the_same_window() {
+ let hint = hint_for(
+ "click",
+ &window_seed(),
+ true,
+ json!({"code": "stale_element_token"}),
+ );
+ assert_eq!(
+ hint.hint,
+ "That element_token comes from an older read. Read the window again for fresh tokens, then act \
+ with the new one."
+ );
+ assert_eq!(
+ call_value(&hint),
+ json!({
+ "tool": "get_window_state",
+ "arguments": {"pid": 4242, "window_id": 17, "session": "run-1"},
+ })
+ );
+}
+
+#[test]
+fn a_window_target_comes_from_the_typed_target_when_the_call_has_no_top_level_ids() {
+ let hint = hint_for(
+ "click",
+ &seed(json!({"target": {"kind": "window", "pid": 9, "window_id": 4}, "x": 1, "y": 2})),
+ true,
+ json!({"code": "stale_geometry"}),
+ );
+ assert_eq!(
+ call_value(&hint),
+ json!({"tool": "get_window_state", "arguments": {"pid": 9, "window_id": 4}})
+ );
+}
+
+#[test]
+fn without_a_known_window_the_hint_stands_alone() {
+ for code in [
+ "stale_element_token",
+ "window_target_not_found",
+ "target_changed",
+ "menu_path_unavailable",
+ ] {
+ let hint = hint_for("click", &Seed::default(), true, json!({ "code": code }));
+ assert!(hint.next_call.is_none(), "{code}");
+ assert!(!hint.hint.is_empty());
+ }
+}
+
+#[test]
+fn window_lookup_refusals_list_the_app_windows() {
+ for code in [
+ "window_target_not_found",
+ "window_id_not_found",
+ "px_window_not_found",
+ "window_id_required",
+ "ambiguous_window_target",
+ "window_minimized",
+ ] {
+ let hint = hint_for("click", &window_seed(), true, json!({ "code": code }));
+ assert_eq!(
+ call_value(&hint),
+ json!({"tool": "list_windows", "arguments": {"pid": 4242}}),
+ "{code}"
+ );
+ }
+}
+
+#[test]
+fn a_point_outside_the_window_asks_for_the_screenshot_only() {
+ let hint = hint_for(
+ "click",
+ &window_seed(),
+ true,
+ json!({"code": "point_outside_window"}),
+ );
+ assert!(hint
+ .hint
+ .contains("pixels of that window's latest screenshot"));
+ assert_eq!(
+ call_value(&hint),
+ json!({
+ "tool": "get_window_state",
+ "arguments": {
+ "pid": 4242,
+ "window_id": 17,
+ "session": "run-1",
+ "include_accessibility_tree": false,
+ },
+ })
+ );
+}
+
+#[test]
+fn permission_codes_split_into_policy_refusals_and_missing_os_grants() {
+ let policy = hint_for(
+ "click",
+ &window_seed(),
+ true,
+ json!({"status": "refused", "refusal": {"code": "permission_denied", "message": "no"}}),
+ );
+ assert!(policy.hint.contains("Do not retry it or work around it"));
+ assert!(policy.next_call.is_none());
+
+ let os = hint_for(
+ "check_permissions",
+ &Seed::default(),
+ true,
+ json!({"status": "refused", "refusal": {"code": "os_permission_prompt_requires_trusted_host", "message": "m"}}),
+ );
+ assert_eq!(
+ call_value(&os),
+ json!({"tool": "check_permissions", "arguments": {"prompt": false}})
+ );
+}
+
+#[test]
+fn session_codes_name_start_session() {
+ let ended = hint_for(
+ "click",
+ &seed(json!({"session": "run-1"})),
+ true,
+ json!({"status": "refused", "refusal": {"code": "session_ended", "message": "m"}}),
+ );
+ assert_eq!(
+ call_value(&ended),
+ json!({"tool": "start_session", "arguments": {"session": "run-1"}})
+ );
+ let missing = hint_for(
+ "escalate_session",
+ &Seed::default(),
+ true,
+ json!({"code": "session_not_started"}),
+ );
+ assert_eq!(
+ call_value(&missing),
+ json!({"tool": "start_session", "arguments": {}})
+ );
+}
+
+#[test]
+fn an_incomplete_type_text_names_how_much_landed() {
+ let hint = hint_for(
+ "type_text",
+ &window_seed(),
+ true,
+ json!({"code": "type_text_incomplete", "delivered_chars": 12, "requested_chars": 40}),
+ );
+ assert_eq!(
+ hint.hint,
+ "Only the first 12 characters landed. Read the field to confirm, then type only the missing rest; \
+ do not resend it all."
+ );
+ assert_eq!(
+ call_value(&hint),
+ json!({
+ "tool": "get_window_state",
+ "arguments": {"pid": 4242, "window_id": 17, "session": "run-1", "since": "latest"},
+ })
+ );
+}
+
+#[test]
+fn an_unattached_browser_names_the_attach_call() {
+ let seed = seed(json!({"pid": 659, "window_id": 12, "session": "web"}));
+ let hint = hint_for(
+ "get_browser_state",
+ &seed,
+ false,
+ json!({"status": "refused", "refusal": {"code": "browser_consent_required", "message": "m"}}),
+ );
+ assert!(hint.hint.starts_with("Attach to this browser window first"));
+ assert_eq!(
+ call_value(&hint),
+ json!({
+ "tool": "browser_prepare",
+ "arguments": {
+ "pid": 659,
+ "window_id": 12,
+ "session": "web",
+ "strategy": {"kind": "existing_profile"},
+ },
+ })
+ );
+}
+
+#[test]
+fn the_producers_own_attach_call_wins_over_the_rebuilt_one() {
+ let hint = hint_for(
+ "get_browser_state",
+ &Seed::default(),
+ false,
+ json!({"status": "refused", "refusal": {
+ "code": "browser_consent_required",
+ "message": "m",
+ "detail": {"next_call": {"tool": "browser_prepare", "arguments": {"pid": 1, "window_id": 7}}},
+ }}),
+ );
+ assert_eq!(
+ call_value(&hint),
+ json!({"tool": "browser_prepare", "arguments": {"pid": 1, "window_id": 7}})
+ );
+}
+
+#[test]
+fn a_refused_browser_prepare_leads_to_the_accessibility_tree() {
+ let hint = hint_for(
+ "browser_prepare",
+ &window_seed(),
+ false,
+ json!({"status": "refused", "refusal": {"code": "browser_consent_required", "message": "m"}}),
+ );
+ assert!(hint.hint.contains("needs authorization"));
+ assert_eq!(call_value(&hint)["tool"], "get_window_state");
+
+ let background = hint_for(
+ "browser_prepare",
+ &window_seed(),
+ true,
+ json!({"code": "background_unavailable", "status": "refused", "refusal": {"code": "background_unavailable", "message": "m"}}),
+ );
+ assert!(background.hint.starts_with("Not blocked:"));
+ assert_eq!(call_value(&background)["tool"], "get_window_state");
+}
+
+#[test]
+fn browser_refusals_point_at_a_fresh_read_of_the_bound_tab() {
+ let seed = seed(json!({"target_id": "t1", "tab_id": "tab9", "ref": "e4", "session": "web"}));
+ for code in ["browser_ref_stale", "browser_action_unavailable"] {
+ let hint = hint_for(
+ "browser_click",
+ &seed,
+ false,
+ json!({"status": "refused", "refusal": {"code": code, "message": "m"}}),
+ );
+ assert_eq!(
+ call_value(&hint),
+ json!({
+ "tool": "get_browser_state",
+ "arguments": {"target_id": "t1", "tab_id": "tab9", "session": "web"},
+ }),
+ "{code}"
+ );
+ }
+}
+
+#[test]
+fn rebinding_a_browser_needs_the_native_window() {
+ let with_window = hint_for(
+ "browser_click",
+ &seed(json!({"pid": 5, "window_id": 6, "target_id": "t", "tab_id": "x"})),
+ false,
+ json!({"status": "refused", "refusal": {"code": "browser_binding_stale", "message": "m"}}),
+ );
+ assert_eq!(
+ call_value(&with_window),
+ json!({"tool": "get_browser_state", "arguments": {"pid": 5, "window_id": 6}})
+ );
+ let without = hint_for(
+ "browser_click",
+ &seed(json!({"target_id": "t", "tab_id": "x"})),
+ false,
+ json!({"status": "refused", "refusal": {"code": "browser_binding_stale", "message": "m"}}),
+ );
+ assert!(without.next_call.is_none());
+}
+
+#[test]
+fn trusted_input_refusals_name_the_alternative_route_the_producer_gave() {
+ let hint = hint_for(
+ "browser_click",
+ &Seed::default(),
+ false,
+ json!({"status": "refused", "refusal": {
+ "code": "browser_input_trust_unavailable",
+ "message": "m",
+ "detail": {"alternative_route": "dom_event"},
+ }}),
+ );
+ assert!(hint.hint.contains("input_route:\"dom_event\""));
+ assert!(hint
+ .hint
+ .contains("only if the user allows the window to come forward"));
+}
+
+#[test]
+fn incomplete_browser_typing_reports_the_counts() {
+ let hint = hint_for(
+ "browser_type",
+ &seed(json!({"target_id": "t", "tab_id": "x"})),
+ false,
+ json!({"status": "refused", "refusal": {
+ "code": "browser_input_incomplete",
+ "message": "m",
+ "detail": {"requested_chars": 40, "delivered_chars": 12},
+ }}),
+ );
+ assert_eq!(
+ hint.hint,
+ "Typing stopped after 12 of 40 characters. Read the field with get_browser_state, then type only what is missing."
+ );
+}
+
+#[test]
+fn unverifiable_actions_read_what_changed() {
+ let seed = window_seed();
+ let read_changes = json!({
+ "tool": "get_window_state",
+ "arguments": {"pid": 4242, "window_id": 17, "session": "run-1", "since": "latest"},
+ });
+ for tool in [
+ "click",
+ "double_click",
+ "right_click",
+ "drag",
+ "type_text",
+ "press_key",
+ "hotkey",
+ "scroll",
+ "set_value",
+ "invoke_menu",
+ "move_cursor",
+ ] {
+ for effect in ["unverifiable", "suspected_noop"] {
+ let hint = hint_for(
+ tool,
+ &seed,
+ false,
+ json!({"effect": effect, "route": "synthetic_events"}),
+ );
+ assert!(!hint.hint.is_empty(), "{tool} {effect}");
+ assert!(
+ hint.hint.chars().count() <= MAX_HINT_CHARS,
+ "{tool} {effect}"
+ );
+ assert_eq!(call_value(&hint), read_changes, "{tool} {effect}");
+ }
+ }
+ let click = hint_for("click", &seed, false, json!({"effect": "unverifiable"}));
+ assert_eq!(
+ click.hint,
+ "The click was sent but nothing confirmed it. Read what changed before clicking again; a repeat \
+ can toggle or double-fire."
+ );
+ let drag = hint_for("drag", &seed, false, json!({"effect": "unverifiable"}));
+ assert!(drag.hint.contains("start the press inside the item"));
+ let noop = hint_for("click", &seed, false, json!({"effect": "suspected_noop"}));
+ assert!(noop.hint.starts_with("The click probably did nothing."));
+}
+
+#[test]
+fn unverifiable_browser_actions_read_the_page() {
+ let seed = seed(json!({"target_id": "t1", "tab_id": "tab9"}));
+ for tool in ["browser_click", "browser_pointer", "browser_type"] {
+ let hint = hint_for(tool, &seed, false, json!({"effect": "unverifiable"}));
+ assert_eq!(
+ call_value(&hint),
+ json!({
+ "tool": "get_browser_state",
+ "arguments": {"target_id": "t1", "tab_id": "tab9"},
+ }),
+ "{tool}"
+ );
+ }
+ let typed = hint_for(
+ "browser_type",
+ &seed,
+ false,
+ json!({"effect": "unverifiable"}),
+ );
+ assert!(typed
+ .hint
+ .starts_with("The text was typed but not read back."));
+}
+
+#[test]
+fn confirmed_results_and_other_tools_get_no_hint() {
+ let seed = window_seed();
+ assert!(recovery_for(
+ "click",
+ &seed,
+ false,
+ &structured(json!({"effect": "confirmed"}))
+ )
+ .is_none());
+ assert!(recovery_for(
+ "click",
+ &seed,
+ false,
+ &structured(json!({"effect": "partial"}))
+ )
+ .is_none());
+ // Not an action tool: its `effect` field means something else.
+ assert!(recovery_for(
+ "get_window_state",
+ &seed,
+ false,
+ &structured(json!({"effect": "unverifiable"}))
+ )
+ .is_none());
+ // A success payload that happens to carry a `code` is not a refusal.
+ assert!(recovery_for(
+ "click",
+ &seed,
+ false,
+ &structured(json!({"code": "stale_element_token"}))
+ )
+ .is_none());
+ // An unknown code has no hint.
+ assert!(recovery_for(
+ "click",
+ &seed,
+ true,
+ &structured(json!({"code": "something_new"}))
+ )
+ .is_none());
+}
+
+#[test]
+fn a_refused_action_result_is_read_by_its_error_code() {
+ let hint = hint_for(
+ "click",
+ &window_seed(),
+ false,
+ json!({"effect": "refused", "route": "synthetic_events", "error": {"code": "point_outside_window"}}),
+ );
+ assert_eq!(
+ call_value(&hint)["arguments"]["include_accessibility_tree"],
+ false
+ );
+}
+
+fn error_with(structured: Value) -> ToolResult {
+ ToolResult::error("refused").with_structured(structured)
+}
+
+#[test]
+fn annotate_adds_both_fields_and_keeps_the_rest() {
+ let mut result = error_with(json!({"code": "stale_element_token", "extra": 1}));
+ annotate("click", &window_seed(), &mut result);
+ let out = result.structured_content.expect("structured");
+ assert_eq!(out["code"], "stale_element_token");
+ assert_eq!(out["extra"], 1);
+ assert!(out["hint"].as_str().unwrap().contains("fresh tokens"));
+ assert_eq!(out["next_call"]["tool"], "get_window_state");
+ assert_eq!(result.is_error, Some(true));
+}
+
+#[test]
+fn annotate_never_overwrites_a_producers_hint_or_next_call() {
+ let mut result = error_with(json!({
+ "code": "background_unavailable",
+ "hint": "producer hint",
+ "next_call": {"tool": "get_browser_state", "arguments": {"pid": 1, "window_id": 2}},
+ }));
+ annotate("click", &window_seed(), &mut result);
+ let out = result.structured_content.expect("structured");
+ assert_eq!(out["hint"], "producer hint");
+ assert_eq!(
+ out["next_call"],
+ json!({"tool": "get_browser_state", "arguments": {"pid": 1, "window_id": 2}})
+ );
+
+ // A producer hint without a next_call still gains the call.
+ let mut partial = error_with(json!({"code": "stale_element_token", "hint": "mine"}));
+ annotate("click", &window_seed(), &mut partial);
+ let out = partial.structured_content.expect("structured");
+ assert_eq!(out["hint"], "mine");
+ assert_eq!(out["next_call"]["tool"], "get_window_state");
+}
+
+#[test]
+fn annotate_covers_browser_refusals_that_are_not_errors() {
+ let mut result = ToolResult::text("refused (browser_ref_stale): m").with_structured(json!({
+ "status": "refused",
+ "refusal": {"code": "browser_ref_stale", "message": "m"},
+ }));
+ annotate(
+ "browser_click",
+ &seed(json!({"target_id": "t", "tab_id": "x"})),
+ &mut result,
+ );
+ let out = result.structured_content.expect("structured");
+ assert_eq!(out["refusal"]["code"], "browser_ref_stale");
+ assert_eq!(out["next_call"]["tool"], "get_browser_state");
+ assert!(
+ result.is_error.is_none(),
+ "a refusal stays a non-error result"
+ );
+}
+
+#[test]
+fn annotate_covers_unverifiable_action_results() {
+ let mut result = ToolResult::text("Posted drag").with_structured(json!({
+ "effect": "unverifiable",
+ "route": "synthetic_events",
+ "summary": "Posted drag",
+ }));
+ annotate("drag", &window_seed(), &mut result);
+ let out = result.structured_content.expect("structured");
+ assert_eq!(out["effect"], "unverifiable");
+ assert!(out["hint"]
+ .as_str()
+ .unwrap()
+ .starts_with("The drag was posted"));
+ assert_eq!(out["next_call"]["arguments"]["since"], "latest");
+}
+
+#[test]
+fn annotate_leaves_confirmed_results_and_plain_successes_alone() {
+ let mut confirmed = ToolResult::text("ok").with_structured(json!({"effect": "confirmed"}));
+ annotate("click", &window_seed(), &mut confirmed);
+ assert_eq!(
+ confirmed.structured_content,
+ Some(json!({"effect": "confirmed"}))
+ );
+
+ let mut plain = ToolResult::text("ok");
+ annotate("click", &window_seed(), &mut plain);
+ assert!(plain.structured_content.is_none());
+}
+
+#[test]
+fn a_missing_required_argument_gains_an_invalid_arguments_code_and_a_hint() {
+ let mut result = ToolResult::error("Missing required parameter: from_x");
+ annotate("drag", &window_seed(), &mut result);
+ let out = result.structured_content.expect("structured");
+ assert_eq!(out["code"], "invalid_arguments");
+ assert!(out["hint"]
+ .as_str()
+ .unwrap()
+ .contains("required argument is missing"));
+
+ let mut other = ToolResult::error("something else went wrong");
+ annotate("drag", &window_seed(), &mut other);
+ assert!(
+ other.structured_content.is_none(),
+ "unrecognised errors stay as they are"
+ );
+}
+
+#[test]
+fn the_seed_reads_only_public_fields() {
+ let seed = seed(json!({
+ "pid": "not a number",
+ "window_id": 5,
+ "session": "",
+ "target": {"kind": "desktop", "display_id": "primary"},
+ }));
+ assert_eq!(seed.pid, None);
+ assert_eq!(seed.window_id, Some(5));
+ assert_eq!(seed.session, None);
+ assert!(seed.desktop_target);
+ let _ = WINDOW;
+}
+
+#[test]
+fn a_desktop_scope_action_points_at_the_window_target() {
+ let hint = hint_for(
+ "click",
+ &seed(json!({"scope": "desktop", "x": 1, "y": 2})),
+ true,
+ json!({"code": "background_unavailable", "effect": "refused"}),
+ );
+ assert!(hint.hint.starts_with("Desktop input uses the real pointer"));
+ assert!(hint
+ .hint
+ .contains("Foreground only if the user allows the pointer to move."));
+ assert!(hint.next_call.is_none(), "no window is known");
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/script_tool.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/script_tool.rs
index 8542c8f6b8..3757bc9569 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/script_tool.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/script_tool.rs
@@ -508,10 +508,16 @@ impl<'a> Api<'a> {
.and_then(|value| value.get("code"))
.and_then(Value::as_str)
.unwrap_or("tool_error");
- return Err(HostError::new(
- clip(text.lines().next().unwrap_or("failed"), 500),
- code,
- ));
+ let mut message = clip(text.lines().next().unwrap_or("failed"), 500);
+ if let Some(hint) = result
+ .structured_content
+ .as_ref()
+ .and_then(|value| value.get("hint"))
+ .and_then(Value::as_str)
+ {
+ message = format!("{message} Hint: {hint}");
+ }
+ return Err(HostError::new(message, code));
}
let mut value = match result.structured_content {
Some(Value::Object(object)) => Value::Object(object),
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/script_tool/tests.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/script_tool/tests.rs
index 710ec10928..5aeb48387a 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/script_tool/tests.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/script_tool/tests.rs
@@ -50,6 +50,8 @@ impl Tool for Fake {
]
})),
"launch_app" => ToolResult::text("launched").with_structured(json!({"pid": 42})),
+ _ if args["refuse"] == true => ToolResult::error(format!("{name} refused: stale token"))
+ .with_structured(json!({"code": "stale_element_token"})),
_ if args["fail"] == true => ToolResult::error(format!("{name} refused: asked to fail")),
_ => ToolResult::text(format!("{name} done")),
}
@@ -188,6 +190,22 @@ async fn an_uncaught_driver_error_names_the_line_the_call_and_the_reason() {
assert!(harness.calls("click").is_empty());
}
+#[tokio::test]
+async fn a_refusal_in_a_script_carries_the_drivers_recovery_hint() {
+ let harness = Harness::new();
+ let result = harness
+ .run("const app = await cua.getApp('Notes');\nawait app.click('s00000009:2', {refuse: true});\nreturn 1;")
+ .await;
+ assert_eq!(result.is_error, Some(true));
+ let message = text(&result);
+ assert!(
+ message.contains(
+ "click refused: stale token Hint: That element_token comes from an older read."
+ ),
+ "{message}"
+ );
+}
+
#[tokio::test]
async fn a_script_can_catch_a_failed_call_and_carry_on() {
let harness = Harness::new();
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
index 677392578a..4ef4e462d8 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
@@ -1669,7 +1669,25 @@ impl ToolRegistry {
.await
}
+ /// The canonical native dispatch boundary. Every refusal and every
+ /// unconfirmed action leaves it with a `hint` (and a `next_call` when one
+ /// exists); see [`crate::recovery_hint`].
async fn invoke_authorized(
+ &self,
+ name: &str,
+ args: Value,
+ context: &crate::session_authorization::EffectiveAuthorizationContext,
+ evidence: &TrustedInvocationEvidence,
+ ) -> ToolResult {
+ let seed = crate::recovery_hint::Seed::from_args(&args);
+ let mut result = self
+ .invoke_authorized_unannotated(name, args, context, evidence)
+ .await;
+ crate::recovery_hint::annotate(renamed_tool(name).unwrap_or(name), &seed, &mut result);
+ result
+ }
+
+ async fn invoke_authorized_unannotated(
&self,
name: &str,
mut args: Value,
@@ -4963,9 +4981,18 @@ resources:
.invoke_with_context("click", args, standard_context())
.await;
assert_eq!(result.is_error, Some(true));
+ let mut structured = result.structured_content.expect("structured refusal");
+ // The refusal also carries a recovery hint (see `recovery_hint`).
+ let hint = structured
+ .as_object_mut()
+ .and_then(|object| object.remove("hint"))
+ .expect("a desktop background refusal carries a hint");
+ assert!(hint
+ .as_str()
+ .is_some_and(|hint| hint.contains("target {kind:\"window\"")));
assert_eq!(
- result.structured_content,
- Some(serde_json::json!({
+ structured,
+ serde_json::json!({
"code": "background_unavailable",
"effect": "refused",
"suggestion": "Retry this action with delivery_mode:\"foreground\".",
@@ -4973,7 +5000,7 @@ resources:
"recommended": "foreground",
"reason": cua_driver_contract::ClickInput::DESKTOP_BACKGROUND_MESSAGE,
},
- }))
+ })
);
assert_eq!(
hits.load(Ordering::SeqCst),
@@ -5762,9 +5789,29 @@ resources:
let object = structured.as_object().expect("ActionResult is an object");
assert_eq!(
object.keys().map(String::as_str).collect::<Vec<_>>(),
- ["delivery", "effect", "route", "summary"]
+ [
+ "delivery",
+ "effect",
+ "hint",
+ "next_call",
+ "route",
+ "summary"
+ ]
);
assert_eq!(structured["effect"], "unverifiable");
+ // An unconfirmed click says what to read next, built from the request.
+ assert_eq!(
+ structured["next_call"],
+ serde_json::json!({
+ "tool": "get_window_state",
+ "arguments": {
+ "pid": 42,
+ "window_id": 7,
+ "session": "projection",
+ "since": "latest",
+ },
+ })
+ );
assert_eq!(structured["delivery"]["mode"], "unknown");
// The producer's text travels inside the closed contract for clients
// that surface only structuredContent.
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/tests/recovery_hints_dispatch.rs b/libs/cua-driver/rust/crates/cua-driver-core/tests/recovery_hints_dispatch.rs
new file mode 100644
index 0000000000..97ac411a3e
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-core/tests/recovery_hints_dispatch.rs
@@ -0,0 +1,267 @@
+//! The dispatch seam gives every refusal and every unconfirmed action a
+//! `hint` and, where one exists, a `next_call`, whichever tool produced it.
+
+use cua_driver_core::authorization::PermissionMode;
+use cua_driver_core::protocol::ToolResult;
+use cua_driver_core::session_authorization::{
+ EffectiveAuthorizationContext, SessionAuthorizationRegistry, SessionModeCeiling,
+};
+use cua_driver_core::tool::{Tool, ToolDef, ToolRegistry};
+use serde_json::{json, Value};
+use std::sync::Arc;
+use std::time::Duration;
+
+/// A stand-in tool that returns whatever its `script` argument names.
+struct Scripted(ToolDef);
+
+#[async_trait::async_trait]
+impl Tool for Scripted {
+ fn def(&self) -> &ToolDef {
+ &self.0
+ }
+
+ async fn invoke(&self, args: Value) -> ToolResult {
+ match args.get("script").and_then(Value::as_str) {
+ Some("stale") => ToolResult::error("element_token is stale")
+ .with_structured(json!({"code": "stale_element_token"})),
+ Some("producer_hint") => ToolResult::error("refused").with_structured(json!({
+ "code": "stale_element_token",
+ "hint": "the producer's own words",
+ "next_call": {"tool": "list_windows", "arguments": {"pid": 1}},
+ })),
+ Some("browser_refusal") => ToolResult::text("refused (browser_ref_stale): gone")
+ .with_structured(json!({
+ "status": "refused",
+ "refusal": {"code": "browser_ref_stale", "message": "gone"},
+ })),
+ Some("missing") => ToolResult::error("Missing required parameter: from_x"),
+ Some("unverifiable") => ToolResult::text("Posted click").with_structured(json!({
+ "path": "cgevent",
+ "verified": false,
+ "effect": "unverifiable",
+ })),
+ _ => ToolResult::text("done"),
+ }
+ }
+}
+
+fn unrestricted_context() -> Arc<EffectiveAuthorizationContext> {
+ let ceiling = SessionModeCeiling::for_trusted_sessions(
+ [PermissionMode::Unrestricted],
+ true,
+ Duration::from_secs(60),
+ Duration::from_secs(30),
+ )
+ .unwrap();
+ SessionAuthorizationRegistry::with_ceiling(ceiling)
+ .compatibility_context(PermissionMode::Unrestricted, None)
+ .unwrap()
+}
+
+fn registry() -> Arc<ToolRegistry> {
+ let mut registry = ToolRegistry::new();
+ registry.register_session_tools();
+ for name in [
+ "click",
+ "drag",
+ "type_text",
+ "get_window_state",
+ "get_browser_state",
+ ] {
+ registry.register(Box::new(Scripted(ToolDef {
+ name: name.to_owned(),
+ description: "stub".to_owned(),
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "script": {"type": "string"},
+ "pid": {"type": "integer"},
+ "window_id": {"type": "integer"},
+ "session": {"type": "string"},
+ "x": {"type": "number"},
+ "y": {"type": "number"},
+ },
+ }),
+ read_only: false,
+ destructive: false,
+ idempotent: false,
+ open_world: false,
+ })));
+ }
+ let registry = Arc::new(registry);
+ registry.init_self_weak();
+ registry
+}
+
+async fn call(tool: &str, args: Value) -> ToolResult {
+ registry()
+ .invoke_with_context(tool, args, unrestricted_context())
+ .await
+}
+
+#[tokio::test]
+async fn a_refusal_gains_a_hint_and_a_next_call_built_from_the_request() {
+ let result = call(
+ "click",
+ json!({"script": "stale", "pid": 42, "window_id": 7, "session": "run-1"}),
+ )
+ .await;
+ assert_eq!(result.is_error, Some(true));
+ let structured = result.structured_content.expect("structured");
+ assert_eq!(structured["code"], "stale_element_token");
+ assert!(structured["hint"]
+ .as_str()
+ .unwrap()
+ .contains("fresh tokens"));
+ assert_eq!(
+ structured["next_call"],
+ json!({
+ "tool": "get_window_state",
+ "arguments": {"pid": 42, "window_id": 7, "session": "run-1"},
+ })
+ );
+}
+
+#[tokio::test]
+async fn a_producers_own_hint_and_next_call_survive_dispatch() {
+ let result = call(
+ "click",
+ json!({"script": "producer_hint", "pid": 42, "window_id": 7}),
+ )
+ .await;
+ let structured = result.structured_content.expect("structured");
+ assert_eq!(structured["hint"], "the producer's own words");
+ assert_eq!(
+ structured["next_call"],
+ json!({"tool": "list_windows", "arguments": {"pid": 1}})
+ );
+}
+
+#[tokio::test]
+async fn a_browser_style_refusal_that_is_not_an_error_is_annotated_too() {
+ // `get_browser_state` refuses without `isError`; agents branch on `status`.
+ let result = call("get_browser_state", json!({"script": "browser_refusal"})).await;
+ assert_ne!(result.is_error, Some(true));
+ let structured = result.structured_content.expect("structured");
+ assert_eq!(structured["refusal"]["code"], "browser_ref_stale");
+ assert!(structured["hint"]
+ .as_str()
+ .unwrap()
+ .contains("get_browser_state"));
+}
+
+#[tokio::test]
+async fn a_refused_action_result_keeps_its_closed_shape_and_gains_a_hint() {
+ // An action tool's refusal is published as `effect: refused` with `error.code`.
+ let result = call(
+ "type_text",
+ json!({"script": "browser_refusal", "pid": 42, "window_id": 7}),
+ )
+ .await;
+ let structured = result.structured_content.expect("structured");
+ assert_eq!(structured["effect"], "refused");
+ assert_eq!(structured["error"]["code"], "browser_ref_stale");
+ assert!(structured["hint"]
+ .as_str()
+ .unwrap()
+ .contains("get_browser_state"));
+ assert_eq!(structured["next_call"]["tool"], "get_browser_state");
+ let schema = cua_driver_contract::advertised_tool_output_schema("type_text").expect("schema");
+ let validator = jsonschema::validator_for(&schema).expect("schema compiles");
+ assert!(
+ validator.is_valid(&structured),
+ "schema rejected {structured}"
+ );
+}
+
+#[tokio::test]
+async fn an_unverifiable_action_publishes_a_hint_inside_the_closed_contract() {
+ let result = call(
+ "click",
+ json!({"script": "unverifiable", "pid": 42, "window_id": 7}),
+ )
+ .await;
+ assert_ne!(result.is_error, Some(true));
+ let structured = result.structured_content.expect("structured");
+ assert_eq!(structured["effect"], "unverifiable");
+ assert!(structured["hint"]
+ .as_str()
+ .unwrap()
+ .starts_with("The click was sent"));
+ assert_eq!(
+ structured["next_call"],
+ json!({
+ "tool": "get_window_state",
+ "arguments": {"pid": 42, "window_id": 7, "since": "latest"},
+ })
+ );
+ // The advertised output schema is closed; the hint must satisfy it.
+ let schema = cua_driver_contract::advertised_tool_output_schema("click").expect("schema");
+ let validator = jsonschema::validator_for(&schema).expect("schema compiles");
+ assert!(
+ validator.is_valid(&structured),
+ "schema rejected {structured}"
+ );
+ cua_driver_contract::validate_success_output("click", structured).expect("typed output");
+}
+
+#[tokio::test]
+async fn a_plain_missing_argument_error_gains_a_code_and_a_hint() {
+ let result = call("drag", json!({"script": "missing"})).await;
+ assert_eq!(result.is_error, Some(true));
+ let structured = result.structured_content.expect("structured");
+ assert_eq!(structured["code"], "invalid_arguments");
+ assert!(structured["hint"]
+ .as_str()
+ .unwrap()
+ .contains("required argument"));
+}
+
+#[tokio::test]
+async fn successes_and_unknown_tools_stay_as_they_were() {
+ let result = call("get_window_state", json!({"pid": 1, "window_id": 2})).await;
+ assert_ne!(result.is_error, Some(true));
+ assert!(result.structured_content.is_none());
+
+ let unknown = call("no_such_tool", json!({})).await;
+ assert_eq!(unknown.is_error, Some(true));
+ assert!(unknown.structured_content.is_none());
+}
+
+#[tokio::test]
+async fn reserved_underscore_arguments_never_reach_a_next_call() {
+ let result = call(
+ "click",
+ json!({
+ "script": "stale",
+ "pid": 42,
+ "window_id": 7,
+ "_session_id": "forged-internal-id",
+ }),
+ )
+ .await;
+ let rendered = result.structured_content.expect("structured").to_string();
+ assert!(!rendered.contains("forged-internal-id"));
+}
+
+#[tokio::test]
+async fn a_failed_batch_step_reports_the_hint_and_next_call() {
+ let result = call(
+ "run_steps",
+ json!({
+ "steps": [{
+ "tool": "click",
+ "args": {"script": "stale", "pid": 42, "window_id": 7},
+ }],
+ }),
+ )
+ .await;
+ assert_eq!(result.is_error, Some(true));
+ let structured = result.structured_content.expect("structured");
+ let step = &structured["steps"][0];
+ assert_eq!(step["ok"], false);
+ assert_eq!(step["code"], "stale_element_token");
+ assert!(step["hint"].as_str().unwrap().contains("fresh tokens"));
+ assert_eq!(step["next_call"]["tool"], "get_window_state");
+ assert_eq!(step["next_call"]["arguments"]["pid"], 42);
+}
diff --git a/libs/cua-driver/typescript/src/native/cua_driver_contract.ts b/libs/cua-driver/typescript/src/native/cua_driver_contract.ts
index 1eb94e3283..686e97bfe9 100644
--- a/libs/cua-driver/typescript/src/native/cua_driver_contract.ts
+++ b/libs/cua-driver/typescript/src/native/cua_driver_contract.ts
@@ -356,6 +356,56 @@ const FfiConverterTypeActionEvidence = (() => {
return new FFIConverter();
})();
+/**
+ * A call an agent can make next: `{tool, arguments}`.
+ */
+export type ActionNextCall = {
+ tool: string,
+ /**
+ * The call's arguments. A JSON object on the wire; the SDK records carry
+ * the same object as JSON text.
+ */
+ arguments: string
+}
+
+/**
+ * Generated factory for {@link ActionNextCall} record objects.
+ */
+export const ActionNextCall = (() => {
+ const defaults = () => ({
+ });
+ const create = (() => {
+ return uniffiCreateRecord<ActionNextCall, ReturnType<typeof defaults>>(defaults);
+ })();
+ return Object.freeze({
+ create,
+ new: create,
+ defaults: () => Object.freeze(defaults()) as Partial<ActionNextCall>,
+ });
+})();
+
+const FfiConverterTypeActionNextCall = (() => {
+ type TypeName = ActionNextCall;
+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {
+ read(from: RustBuffer): TypeName {
+ return {
+ tool: FfiConverterString.read(from),
+ arguments: FfiConverterString.read(from)
+ };
+ }
+ write(value: TypeName, into: RustBuffer): void {
+ FfiConverterString.write(value.tool, into);
+ FfiConverterString.write(value.arguments, into);
+ }
+ allocationSize(value: TypeName): number {
+ return FfiConverterString.allocationSize(value.tool) +
+ FfiConverterString.allocationSize(value.arguments);
+
+ }
+ };
+ return new FFIConverter();
+})();
+
export enum ActionEffect {
Confirmed,
Partial,
@@ -451,7 +501,18 @@ export type ActionResult = {
/**
* Present only with `effect: refused`.
*/
- error?: ActionError
+ error?: ActionError,
+ /**
+ * What to do next, in one short sentence. Present when the effect is
+ * `unverifiable` or `suspected_noop`, so an unconfirmed action points at
+ * the next step instead of leaving the agent to guess.
+ */
+ hint?: string,
+ /**
+ * The call that moves the task forward, always safe to run as is (a read,
+ * or a call that keeps the user's window where it is).
+ */
+ nextCall?: ActionNextCall
}
/**
@@ -481,7 +542,9 @@ const FfiConverterTypeActionResult = (() => {
evidence: FfiConverterOptionalSequenceTypeActionEvidence.read(from),
escalation: FfiConverterOptionalTypeActionEscalation.read(from),
summary: FfiConverterOptionalString.read(from),
- error: FfiConverterOptionalTypeActionError.read(from)
+ error: FfiConverterOptionalTypeActionError.read(from),
+ hint: FfiConverterOptionalString.read(from),
+ nextCall: FfiConverterOptionalTypeActionNextCall.read(from)
};
}
write(value: TypeName, into: RustBuffer): void {
@@ -492,6 +555,8 @@ const FfiConverterTypeActionResult = (() => {
FfiConverterOptionalTypeActionEscalation.write(value.escalation, into);
FfiConverterOptionalString.write(value.summary, into);
FfiConverterOptionalTypeActionError.write(value.error, into);
+ FfiConverterOptionalString.write(value.hint, into);
+ FfiConverterOptionalTypeActionNextCall.write(value.nextCall, into);
}
allocationSize(value: TypeName): number {
return FfiConverterTypeActionEffect.allocationSize(value.effect) +
@@ -500,7 +565,9 @@ const FfiConverterTypeActionResult = (() => {
FfiConverterOptionalSequenceTypeActionEvidence.allocationSize(value.evidence) +
FfiConverterOptionalTypeActionEscalation.allocationSize(value.escalation) +
FfiConverterOptionalString.allocationSize(value.summary) +
- FfiConverterOptionalTypeActionError.allocationSize(value.error);
+ FfiConverterOptionalTypeActionError.allocationSize(value.error) +
+ FfiConverterOptionalString.allocationSize(value.hint) +
+ FfiConverterOptionalTypeActionNextCall.allocationSize(value.nextCall);
}
};
@@ -6572,6 +6639,9 @@ const FfiConverterOptionalTypeActionEscalation = new FfiConverterOptional(FfiCon
// FfiConverter for ActionError | undefined
const FfiConverterOptionalTypeActionError = new FfiConverterOptional(FfiConverterTypeActionError);
+// FfiConverter for ActionNextCall | undefined
+const FfiConverterOptionalTypeActionNextCall = new FfiConverterOptional(FfiConverterTypeActionNextCall);
+
// FfiConverter for number | undefined
const FfiConverterOptionalFloat64 = new FfiConverterOptional(FfiConverterFloat64);
@@ -6729,6 +6799,7 @@ export default Object.freeze({
FfiConverterTypeActionEscalationTarget,
FfiConverterTypeActionEvidence,
FfiConverterTypeActionEvidenceKind,
+ FfiConverterTypeActionNextCall,
FfiConverterTypeActionResult,
FfiConverterTypeActionRoute,
FfiConverterTypeActionTarget,