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): add example-local Jev and S1 decision interface (#4057)

Francesco Bonacci605d358a48ad
diff --git a/.github/workflows/ci-jev-use.yml b/.github/workflows/ci-jev-use.yml
index 7ea76b00fc..e6f3c2d104 100644
--- a/.github/workflows/ci-jev-use.yml
+++ b/.github/workflows/ci-jev-use.yml
@@ -56,6 +56,8 @@ jobs:
run: uv run python -m unittest discover -s python/tests -v
- name: Verify bounded chooser CLI in mock mode
run: uv run --frozen python verify_choice_cli.py
+ - name: Verify closed-candidate decision CLI in mock mode
+ run: uv run --frozen python verify_decision_cli.py --model mock
unit-typescript:
name: TypeScript unit and typecheck
diff --git a/libs/cua-driver/examples/jev-use/README.md b/libs/cua-driver/examples/jev-use/README.md
index 2bfb62e8d8..061005220a 100644
--- a/libs/cua-driver/examples/jev-use/README.md
+++ b/libs/cua-driver/examples/jev-use/README.md
@@ -257,6 +257,12 @@ npm test
npm run typecheck
```
+## Other decision models
+
+For an optional Python-only closed-candidate interface spanning Jev and local
+Cua-S1-4B, see [Closed-candidate decision models](decision-models.md). It does
+not change the existing Python or TypeScript runners.
+
## Relationship to PR #3914
[PR #3914](https://github.com/trycua/cua/pull/3914) proposes an optional Jev
diff --git a/libs/cua-driver/examples/jev-use/decision-models.md b/libs/cua-driver/examples/jev-use/decision-models.md
new file mode 100644
index 0000000000..f1dc89a6c3
--- /dev/null
+++ b/libs/cua-driver/examples/jev-use/decision-models.md
@@ -0,0 +1,159 @@
+# Closed-candidate decision models
+
+The optional Python `choose_decision.py` interface lets an application choose
+between TypeSafe Jev and a local Cua-S1-4B model without giving either model
+control of Cua Driver. It is an example-local integration, not a new Driver,
+MCP, or cross-language contract. The existing Python and TypeScript `jev-use`
+runners remain unchanged.
+
+## Boundary
+
+The application observes through Driver, constructs an immutable candidate
+table, and sends only the goal, capture ID, typed visual regions, bounded
+history, and candidate IDs and descriptions to a decision model. The model
+returns a score for each supplied ID. The adapter rejects missing, extra,
+non-finite, out-of-range, or non-normalized scores, then returns one of four
+outcomes: `selected`, `reobserve`, `abstain`, or `error`.
+
+`selected` is not an action result. The application must look up the selected
+ID in its original candidate table, re-check any typed action precondition
+against the original current-capture observation, dispatch only an authorized
+action through Driver, and verify the postcondition from an independent source.
+Candidate descriptions are model input, not executable conditions; never parse
+them or treat a high model score as authorization. `reobserve`, `abstain`, and
+`error` dispatch no action.
+The decision response never contains tool names, tool arguments, coordinates,
+or screenshot bytes.
+
+For a simple capture-bound click on an exact OCR label, the Python example
+provides `action_policy.ExactRegionTextAction` and
+`authorize_exact_region_text_action`. The caller creates the policy before
+building the candidate table, uses `action.wire_candidate()` as the offered
+candidate, and passes the original `parse_visual_regions` result and current
+capture ID plus the expected source (exact window PID/window ID or primary
+desktop) to the guard after a `selected` response. This means the raw public
+Driver tool payload, not the `core.parse_visual_regions` wrapper's
+`VisualObservation` object. The guard validates its source, PNG provenance,
+coordinate mapping, and bounds before returning screenshot-pixel coordinates.
+Only a successful guard returns a point and capture ID to pass to Driver.
+Missing, duplicated, stale,
+low-confidence, or mismatched region facts refuse the action. This is one
+example caller policy, not a generic authorization engine or a Driver feature;
+other action types need their own typed checks. The helper does not dispatch a
+click or verify its effect. The caller must pass the returned screenshot-pixel
+point to the corresponding window or desktop Driver action with the same
+`capture_id`. Driver applies the capture's coordinate mapping
+once; the caller must not map the returned point again or reuse it against
+another target.
+
+The input is the existing `cua.jev_choice_request_v1` request accepted by
+`choose_action.py`. The output is a separate
+`cua.decision_choice_v1` response with `kind`, `capture_id`, `selected_id`, `model`,
+`confidence`, `probabilities`, and `reason`. This output is not a drop-in
+replacement for the older `cua.jev_choice_v1` response; callers must handle
+all four outcome kinds and match `capture_id` to the current observation.
+Tied top scores are non-actionable errors. For a `selected` outcome, callers
+should also apply their own minimum score and margin before dispatching an
+action. `confidence` preserves the provider's reported value when Jev supplies
+one; with S1 and mock it is the selected option probability. For a
+model-independent threshold, use `probabilities[selected_id]` instead.
+
+Malformed model output and lazy model-loading failures return `kind: "error"`
+with a non-secret `reason: "model_error"`. Missing local S1 paths or a failure
+to initialize the TypeSafe client stop the CLI with a generic nonzero setup
+error and no JSON response. Never treat a missing response as `selected`.
+
+## Run a bounded request
+
+The deterministic mock requires no model weights or credential:
+
+```bash
+uv run --frozen python/choose_decision.py --model mock \
+ < fixtures/jev-choice-request-v1.json
+```
+
+To verify the expected fixture choice without printing the full response, run
+`uv run --frozen verify_decision_cli.py --model mock`. The same verifier accepts
+`--model jev` or `--model s1` after configuring that provider. It checks the
+response schema, capture ID, complete candidate set, and selected ID. It does
+not dispatch a Driver action or prove live desktop behavior.
+
+The separate negative fixture has a `Save` observation but an action candidate
+that requires `Send`. To check a live provider's abstention without executing
+the candidate, run `uv run --frozen verify_decision_cli.py --model jev
+--fixture negative --expected-id abstain` in an authorized local environment.
+The mock intentionally chooses the first action candidate and is not an oracle
+for this negative case.
+
+The TypeSafe Jev path uses the example's official SDK and reads its credential
+from the local environment. Run it only with data you intend to send to that
+service. Do not put `TYPESAFE_API_KEY` in CI or GitHub Actions:
+
+```bash
+uv run --frozen python/choose_decision.py --model jev \
+ < fixtures/jev-choice-request-v1.json
+```
+
+The S1 path runs locally and needs the separately installed `cua-s1` Python
+package, PyTorch, PEFT, and a Transformers build that recognizes
+`Qwen/Qwen3.5-4B`. Install the `cua-s1[four-b]` inference extra from the
+source that includes the Transformers 5 dependency update proposed in #4060;
+the main-branch extra still pins Transformers below 5. From the repository
+root, use `uv sync --project libs/cua-s1/python --extra four-b`, then run this
+chooser with `libs/cua-s1/python/.venv/bin/python`. The isolated pinned-weight
+proof used Transformers 5.17.0. This is a local source recipe, not a published
+package or a guarantee that every allowed dependency version loads the model.
+
+The published `cua-ai/cua-s1-4b-0.2` artifact is a PEFT adapter, not a
+standalone model. Pin and locally download both the base revision
+`851bf6e806efd8d0a36b00ddf55e13ccb7b8cd0a` and adapter revision
+`16818868b0cc7813808aae4e87b417657046ab79`, then set
+`S1_BASE_MODEL_PATH` and `S1_ADAPTER_PATH` to those local directories:
+
+```bash
+S1_DEVICE=cpu S1_DTYPE=float16 \
+ /path/to/repo/libs/cua-s1/python/.venv/bin/python \
+ python/choose_decision.py --model s1 \
+ < fixtures/jev-choice-request-v1.json
+```
+
+The S1 text adapter renders OmniParser regions, including confidence and
+interactivity, as text and labels the result
+`Visual-region-derived observation`. It is not a genuine accessibility tree,
+even though the underlying S1 prompt still titles this text field
+`Accessibility tree:`. The reserved options are represented as closed-choice
+decisions; their accuracy is not established by S1's element/action training.
+S1's one-letter-per-option readout supports at most 26 candidates, including
+`reobserve` and `abstain`; a larger validated request returns `error` with
+`reason: "option_limit"` and never silently truncates the table. The Jev
+request schema permits up to 32 candidates. The S1 multimodal adapter requires
+an existing local screenshot path and an explicit screenshot capture ID equal
+to the request's `capture_id`. The caller must supply the image from that
+capture; the adapter checks identity but cannot authenticate image contents.
+The path and image are never added to a TypeSafe request. The CLI currently
+exposes only the text adapter.
+
+## Verification scope
+
+The focused fake-model tests cover the selection contract, reserved outcomes,
+malformed scores, the 26-option boundary, and absence of screenshot and action
+arguments in the TypeSafe request. A local pinned-weight S1 text inference
+selected the expected `submit-form` candidate from the synthetic fixture
+request. That is a runtime smoke, not evidence that S1 matches Jev's decision
+quality or that the S1 path has been run end to end on a desktop.
+
+In a synthetic mismatch where the observation said `Save` but the only action
+condition required `Send`, Jev selected `abstain`. Before the S1 text prompt
+included region confidence and interactivity, S1 selected non-actionable
+`reobserve`. In one pinned-weight rerun with those fields present, S1 selected
+`abstain` (probability 0.435 versus 0.384 for `reobserve`). Both earlier and
+revised outputs prevented an action; one corrected result is not a reliability
+estimate. A fresh primary-desktop negative control exposed the opposite
+polarity: packaged OmniParser observed `Send`, the sole action description
+required exact `Save`, and S1 selected that action with probability 0.777.
+The private probe dispatched no click, and the fixture stayed at zero actions.
+This is a model-quality counterexample, not a passing negative decision row.
+The typed caller policy refuses the same mismatch in deterministic tests.
+Keep an independent fixture oracle and a caller-owned score and margin policy
+for future desktop comparisons; a threshold alone cannot establish that an
+action condition is true.
diff --git a/libs/cua-driver/examples/jev-use/fixtures/jev-choice-negative-v1.json b/libs/cua-driver/examples/jev-use/fixtures/jev-choice-negative-v1.json
new file mode 100644
index 0000000000..0a063ad128
--- /dev/null
+++ b/libs/cua-driver/examples/jev-use/fixtures/jev-choice-negative-v1.json
@@ -0,0 +1,30 @@
+{
+ "schema": "cua.jev_choice_request_v1",
+ "goal": "Choose exactly one candidate by applying its condition to the supplied state. The host alone authorizes any selected action.",
+ "capture_id": "synthetic-negative-1",
+ "regions": [
+ {
+ "id": "save",
+ "kind": "text",
+ "bounds": {"x": 10, "y": 10, "width": 80, "height": 30},
+ "text": "Save",
+ "confidence": 0.98,
+ "interactive": true
+ }
+ ],
+ "history": [],
+ "candidates": [
+ {
+ "id": "region:save",
+ "description": "Select only if exactly one supplied region has id=save, kind=text, exact_text=\"Send\", confidence=0.98, and it is the sole exact Send match at or above 0.80."
+ },
+ {
+ "id": "reobserve",
+ "description": "Select only when no action candidate condition matches and no regions are supplied. Do not act; request one fresh bounded observation."
+ },
+ {
+ "id": "abstain",
+ "description": "Select only when no action candidate condition matches and one or more regions are supplied. Do not act; stop."
+ }
+ ]
+}
diff --git a/libs/cua-driver/examples/jev-use/python/action_policy.py b/libs/cua-driver/examples/jev-use/python/action_policy.py
new file mode 100644
index 0000000000..cf17dcc918
--- /dev/null
+++ b/libs/cua-driver/examples/jev-use/python/action_policy.py
@@ -0,0 +1,251 @@
+"""Caller-owned exact-text authorization for a capture-bound visual action.
+
+This is an example policy, not a decision-model guarantee or Driver API.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+import sys
+from dataclasses import dataclass
+from typing import Any, Mapping
+
+
+class ActionAuthorizationError(ValueError):
+ """The selected candidate is not authorized by the current observation."""
+
+
+@dataclass(frozen=True)
+class AuthorizedVisualClick:
+ capture_id: str
+ x: float
+ y: float
+
+
+@dataclass(frozen=True)
+class ExactRegionTextAction:
+ candidate_id: str
+ region_id: str
+ exact_text: str
+ min_confidence: float = 0.8
+
+ def __post_init__(self) -> None:
+ if not all(
+ isinstance(value, str) and value.strip()
+ for value in (self.candidate_id, self.region_id, self.exact_text)
+ ):
+ raise ValueError("action identifiers and exact text must be nonempty strings")
+ if (
+ not isinstance(self.min_confidence, (int, float))
+ or isinstance(self.min_confidence, bool)
+ or not math.isfinite(self.min_confidence)
+ or not 0 <= self.min_confidence <= 1
+ ):
+ raise ValueError("minimum confidence must be a finite value in [0, 1]")
+ if round(float(self.min_confidence), 2) != float(self.min_confidence):
+ raise ValueError("minimum confidence must use at most two decimal places")
+
+ def wire_candidate(self) -> dict[str, str]:
+ return {
+ "id": self.candidate_id,
+ "description": (
+ "Select only if exactly one supplied text region has "
+ f"id={json.dumps(self.region_id)}, "
+ f"exact_text={json.dumps(self.exact_text, ensure_ascii=False)}, "
+ f"and confidence at or above {self.min_confidence:.2f}."
+ ),
+ }
+
+
+def authorize_exact_region_text_action(
+ request: Mapping[str, Any],
+ decision: Mapping[str, Any],
+ parsed: Mapping[str, Any],
+ action: ExactRegionTextAction,
+ *,
+ current_capture_id: str,
+ expected_source: Mapping[str, Any],
+) -> AuthorizedVisualClick:
+ """Raise unless the original parse still proves the selected action condition.
+
+ The caller supplies the returned point and capture ID to Driver once, then
+ independently verifies the result. This helper does not dispatch input.
+ """
+ if not all(isinstance(value, Mapping) for value in (request, decision, parsed)):
+ raise ActionAuthorizationError("missing decision or visual observation")
+ if not isinstance(action, ExactRegionTextAction):
+ raise ActionAuthorizationError("unsupported action condition")
+ capture = parsed.get("capture")
+ capture_id = capture.get("capture_id") if isinstance(capture, Mapping) else None
+ if (
+ not isinstance(current_capture_id, str)
+ or not current_capture_id
+ or request.get("capture_id") != current_capture_id
+ or decision.get("capture_id") != current_capture_id
+ or capture_id != current_capture_id
+ ):
+ raise ActionAuthorizationError("capture identity changed")
+ if parsed.get("schema") != "cua.visual_regions_v1":
+ raise ActionAuthorizationError("unsupported visual observation")
+ source = capture.get("source")
+ if (
+ not isinstance(expected_source, Mapping)
+ or expected_source.get("kind") not in {"window", "primary_desktop"}
+ or not isinstance(source, Mapping)
+ or dict(source) != dict(expected_source)
+ ):
+ raise ActionAuthorizationError("visual capture source changed")
+ if source["kind"] == "window" and (
+ not isinstance(source.get("pid"), int)
+ or isinstance(source["pid"], bool)
+ or source["pid"] <= 0
+ or not isinstance(source.get("window_id"), int)
+ or isinstance(source["window_id"], bool)
+ or source["window_id"] <= 0
+ ):
+ raise ActionAuthorizationError("malformed window source")
+ if source["kind"] == "primary_desktop" and source.get("display_id") != "primary":
+ raise ActionAuthorizationError("malformed desktop source")
+ screenshot = capture.get("screenshot")
+ if (
+ not isinstance(screenshot, Mapping)
+ or screenshot.get("mime_type") != "image/png"
+ or not isinstance(screenshot.get("reference"), str)
+ or not screenshot["reference"]
+ or any(
+ not isinstance(screenshot.get(key), int)
+ or isinstance(screenshot[key], bool)
+ or screenshot[key] <= 0
+ for key in ("width", "height")
+ )
+ ):
+ raise ActionAuthorizationError("invalid screenshot provenance")
+ coordinate_space = capture.get("action_coordinate_space")
+ if not isinstance(coordinate_space, Mapping) or coordinate_space.get("kind") not in {
+ "screenshot_pixels",
+ "affine",
+ }:
+ raise ActionAuthorizationError("unsupported action coordinate space")
+ values = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
+ if coordinate_space["kind"] == "affine":
+ values = [coordinate_space.get(key) for key in ("m11", "m12", "m21", "m22", "tx", "ty")]
+ if (
+ any(
+ not isinstance(value, (int, float))
+ or isinstance(value, bool)
+ or not math.isfinite(value)
+ for value in values
+ )
+ or abs(values[0] * values[3] - values[1] * values[2]) <= sys.float_info.epsilon
+ ):
+ raise ActionAuthorizationError("malformed action coordinate mapping")
+ if (
+ decision.get("schema") != "cua.decision_choice_v1"
+ or decision.get("kind") != "selected"
+ or decision.get("selected_id") != action.candidate_id
+ ):
+ raise ActionAuthorizationError("decision did not select this action")
+
+ candidates = request.get("candidates")
+ if (
+ not isinstance(candidates, list)
+ or sum(
+ isinstance(candidate, Mapping) and candidate.get("id") == action.candidate_id
+ for candidate in candidates
+ )
+ != 1
+ or action.wire_candidate() not in candidates
+ ):
+ raise ActionAuthorizationError("action condition differs from the offered candidate")
+ scores = decision.get("probabilities")
+ candidate_ids = [item.get("id") for item in candidates if isinstance(item, Mapping)]
+ if (
+ len(candidate_ids) != len(candidates)
+ or any(not isinstance(candidate_id, str) for candidate_id in candidate_ids)
+ or len(set(candidate_ids)) != len(candidate_ids)
+ or not isinstance(scores, Mapping)
+ or set(scores) != set(candidate_ids)
+ or any(
+ not isinstance(score, (int, float))
+ or isinstance(score, bool)
+ or not math.isfinite(score)
+ or not 0 <= score <= 1
+ for score in scores.values()
+ )
+ or abs(sum(scores.values()) - 1) > 0.02
+ or scores[action.candidate_id] != max(scores.values())
+ or sum(score == max(scores.values()) for score in scores.values()) != 1
+ ):
+ raise ActionAuthorizationError("decision scores do not match the candidate set")
+
+ regions = parsed.get("regions")
+ offered_regions = request.get("regions")
+ if not isinstance(regions, list) or not isinstance(offered_regions, list):
+ raise ActionAuthorizationError("visual regions are unavailable")
+ offered_ids = [region.get("id") for region in offered_regions if isinstance(region, Mapping)]
+ if (
+ len(offered_ids) != len(offered_regions)
+ or any(not isinstance(region_id, str) for region_id in offered_ids)
+ or len(set(offered_ids)) != len(offered_ids)
+ ):
+ raise ActionAuthorizationError("offered visual regions are malformed")
+ matches: list[Mapping[str, Any]] = []
+ region_ids: set[str] = set()
+ for region in regions:
+ if not isinstance(region, Mapping) or not isinstance(region.get("id"), str):
+ raise ActionAuthorizationError("malformed visual region")
+ if region["id"] in region_ids:
+ raise ActionAuthorizationError("duplicate visual region ID")
+ region_ids.add(region["id"])
+ confidence = region.get("confidence")
+ if (
+ not isinstance(confidence, (int, float))
+ or isinstance(confidence, bool)
+ or not math.isfinite(confidence)
+ or not 0 <= confidence <= 1
+ ):
+ raise ActionAuthorizationError("malformed visual confidence")
+ if (
+ region.get("kind") == "text"
+ and region.get("text") == action.exact_text
+ and confidence >= action.min_confidence
+ ):
+ matches.append(region)
+ if len(matches) != 1 or matches[0]["id"] != action.region_id:
+ raise ActionAuthorizationError("exact-text condition is not uniquely satisfied")
+ offered = next(
+ (region for region in offered_regions if region.get("id") == action.region_id), None
+ )
+ region_fields = {"id", "kind", "bounds", "text", "label", "confidence", "interactive"}
+ required_fields = {"id", "kind", "bounds", "confidence", "interactive"}
+ if (
+ not isinstance(offered, Mapping)
+ or not required_fields.issubset(offered)
+ or not set(offered).issubset(region_fields)
+ or any(offered.get(key) != matches[0].get(key) for key in region_fields)
+ ):
+ raise ActionAuthorizationError("offered region differs from the original parse")
+ bounds = matches[0].get("bounds")
+ if (
+ not isinstance(bounds, Mapping)
+ or any(
+ not isinstance(bounds.get(key), int) or isinstance(bounds[key], bool)
+ for key in ("x", "y", "width", "height")
+ )
+ or bounds["x"] < 0
+ or bounds["y"] < 0
+ or bounds["width"] <= 0
+ or bounds["height"] <= 0
+ or bounds["x"] + bounds["width"] > screenshot["width"]
+ or bounds["y"] + bounds["height"] > screenshot["height"]
+ ):
+ raise ActionAuthorizationError("malformed visual bounds")
+ px = bounds["x"] + bounds["width"] / 2
+ py = bounds["y"] + bounds["height"] / 2
+ m11, m12, m21, m22, tx, ty = values
+ x = m11 * px + m12 * py + tx
+ y = m21 * px + m22 * py + ty
+ if not math.isfinite(x) or not math.isfinite(y):
+ raise ActionAuthorizationError("action coordinate mapping produced a non-finite point")
+ return AuthorizedVisualClick(current_capture_id, px, py)
diff --git a/libs/cua-driver/examples/jev-use/python/choose_decision.py b/libs/cua-driver/examples/jev-use/python/choose_decision.py
new file mode 100644
index 0000000000..d208cd95d6
--- /dev/null
+++ b/libs/cua-driver/examples/jev-use/python/choose_decision.py
@@ -0,0 +1,101 @@
+"""Choose one bounded candidate with mock, TypeSafe Jev, or local S1."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import sys
+from pathlib import Path
+from typing import Any
+
+from choose_action import MAX_INPUT_BYTES, validate_request
+from decision_models import (
+ DecisionRequest,
+ ModelScores,
+ S1DecisionModel,
+ TypeSafeDecisionModel,
+ choose,
+)
+
+
+class MockDecisionModel:
+ name = "mock"
+
+ def score(self, request: DecisionRequest) -> ModelScores:
+ selected = next(
+ (
+ item["id"]
+ for item in request.candidates
+ if item["id"] not in {"reobserve", "abstain"}
+ ),
+ "reobserve",
+ )
+ return ModelScores(
+ {item["id"]: float(item["id"] == selected) for item in request.candidates},
+ self.name,
+ )
+
+
+def local_s1_model() -> S1DecisionModel:
+ base_value = os.environ["S1_BASE_MODEL_PATH"]
+ adapter_value = os.environ["S1_ADAPTER_PATH"]
+ if not base_value.strip() or not adapter_value.strip():
+ raise ValueError("S1_BASE_MODEL_PATH and S1_ADAPTER_PATH must be local directories")
+ base = Path(base_value).expanduser()
+ adapter = Path(adapter_value).expanduser()
+ if not base.is_dir() or not adapter.is_dir():
+ raise ValueError("S1_BASE_MODEL_PATH and S1_ADAPTER_PATH must be local directories")
+ from cua_s1.four_b import FourBModel
+
+ return S1DecisionModel(
+ FourBModel(
+ base_model=str(base),
+ lora_adapter_path=adapter,
+ device=os.environ.get("S1_DEVICE", "cpu"),
+ dtype=os.environ.get("S1_DTYPE", "float16"),
+ modality="text",
+ )
+ )
+
+
+def choose_request(value: Any, model: Any) -> dict[str, Any]:
+ request = DecisionRequest.from_validated(validate_request(value))
+ return choose(model, request).to_wire()
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--model", choices=("mock", "jev", "s1"), default="mock")
+ args = parser.parse_args()
+ raw = sys.stdin.buffer.read(MAX_INPUT_BYTES + 1)
+ if len(raw) > MAX_INPUT_BYTES:
+ raise SystemExit("request exceeds input limit")
+ try:
+ request = json.loads(raw)
+ validate_request(request)
+ except (UnicodeDecodeError, json.JSONDecodeError, ValueError, KeyError, TypeError) as error:
+ raise SystemExit(f"invalid request: {error}") from None
+ if args.model == "mock":
+ model = MockDecisionModel()
+ elif args.model == "s1":
+ try:
+ model = local_s1_model()
+ except (KeyError, ValueError, ImportError) as error:
+ raise SystemExit(f"S1 setup failed: {error}") from None
+ else:
+ try:
+ from typesafe_sdk import TypeSafeClient
+
+ with TypeSafeClient() as client:
+ result = choose_request(request, TypeSafeDecisionModel(client))
+ except Exception:
+ raise SystemExit("provider setup failed") from None
+ sys.stdout.write(json.dumps(result, separators=(",", ":")) + "\n")
+ return
+ result = choose_request(request, model)
+ sys.stdout.write(json.dumps(result, separators=(",", ":")) + "\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/libs/cua-driver/examples/jev-use/python/decision_models.py b/libs/cua-driver/examples/jev-use/python/decision_models.py
new file mode 100644
index 0000000000..a41908f581
--- /dev/null
+++ b/libs/cua-driver/examples/jev-use/python/decision_models.py
@@ -0,0 +1,252 @@
+"""Closed-candidate decision models for the jev-use example.
+
+Models only select caller-supplied IDs. Candidate construction, capture
+freshness, Driver actions, and independent verification stay with the caller.
+"""
+
+from __future__ import annotations
+
+import math
+import json
+from dataclasses import dataclass
+from pathlib import Path
+from types import MappingProxyType
+from typing import Any, Literal, Mapping, Protocol
+
+from jev_adapter import choose_bounded_with_typesafe
+
+DecisionKind = Literal["selected", "reobserve", "abstain", "error"]
+
+
+@dataclass(frozen=True)
+class DecisionRequest:
+ goal: str
+ capture_id: str
+ regions: tuple[Mapping[str, Any], ...]
+ history: tuple[Mapping[str, str], ...]
+ candidates: tuple[Mapping[str, str], ...]
+
+ @classmethod
+ def from_validated(cls, request: Mapping[str, Any]) -> "DecisionRequest":
+ return cls(
+ goal=request["goal"],
+ capture_id=request["capture_id"],
+ regions=tuple(request["regions"]),
+ history=tuple(request["history"]),
+ candidates=tuple(MappingProxyType(dict(item)) for item in request["candidates"]),
+ )
+
+ @property
+ def criteria(self) -> dict[str, str]:
+ return {item["id"]: item["description"] for item in self.candidates}
+
+
+@dataclass(frozen=True)
+class ModelScores:
+ probabilities: Mapping[str, float]
+ model: str
+ selected_id: str | None = None
+ confidence: float | None = None
+
+
+@dataclass(frozen=True)
+class DecisionResult:
+ kind: DecisionKind
+ capture_id: str
+ selected_id: str | None
+ model: str
+ confidence: float | None
+ probabilities: Mapping[str, float]
+ reason: str | None = None
+
+ def to_wire(self) -> dict[str, Any]:
+ return {
+ "schema": "cua.decision_choice_v1",
+ "kind": self.kind,
+ "capture_id": self.capture_id,
+ "selected_id": self.selected_id,
+ "model": self.model,
+ "confidence": self.confidence,
+ "probabilities": dict(self.probabilities),
+ "reason": self.reason,
+ }
+
+
+class DecisionModel(Protocol):
+ name: str
+
+ def score(self, request: DecisionRequest) -> ModelScores: ...
+
+
+def choose(model: DecisionModel, request: DecisionRequest) -> DecisionResult:
+ """Reject malformed scores without converting them into an action."""
+ try:
+ allowed = request.criteria
+ scores = model.score(request)
+ if not isinstance(scores.model, str) or not 0 < len(scores.model) <= 128:
+ raise ValueError("model identity must be a bounded string")
+ if set(scores.probabilities) != set(allowed):
+ raise ValueError("probability IDs do not match the candidate IDs")
+ probabilities = dict(scores.probabilities)
+ if any(
+ not isinstance(value, (int, float))
+ or isinstance(value, bool)
+ or not math.isfinite(value)
+ or not 0 <= value <= 1
+ for value in probabilities.values()
+ ):
+ raise ValueError("probabilities must be finite numbers in [0, 1]")
+ if abs(sum(probabilities.values()) - 1) > 0.02:
+ raise ValueError("probability mass must be approximately one")
+ top = max(probabilities.values())
+ winners = [candidate_id for candidate_id in allowed if probabilities[candidate_id] == top]
+ if len(winners) != 1:
+ raise ValueError("a tied top score is not actionable")
+ selected = scores.selected_id or winners[0]
+ if selected != winners[0]:
+ raise ValueError("selection must be an allowed argmax")
+ confidence = scores.confidence if scores.confidence is not None else probabilities[selected]
+ if (
+ not isinstance(confidence, (int, float))
+ or isinstance(confidence, bool)
+ or not math.isfinite(confidence)
+ or not 0 <= confidence <= 1
+ ):
+ raise ValueError("confidence must be a finite number in [0, 1]")
+ kind: DecisionKind = (
+ "reobserve"
+ if selected == "reobserve"
+ else "abstain"
+ if selected == "abstain"
+ else "selected"
+ )
+ return DecisionResult(
+ kind=kind,
+ capture_id=request.capture_id,
+ selected_id=selected,
+ model=scores.model,
+ confidence=confidence,
+ probabilities=probabilities,
+ )
+ except Exception as error:
+ reason = "option_limit" if isinstance(error, OptionLimitError) else "model_error"
+ model_name = getattr(model, "name", "unknown")
+ if not isinstance(model_name, str) or not 0 < len(model_name) <= 128:
+ model_name = "unknown"
+ return DecisionResult("error", request.capture_id, None, model_name, None, {}, reason)
+
+
+class OptionLimitError(ValueError):
+ pass
+
+
+class TypeSafeDecisionModel:
+ name = "typesafe-jev"
+
+ def __init__(self, client: Any) -> None:
+ self.client = client
+
+ def score(self, request: DecisionRequest) -> ModelScores:
+ choice = choose_bounded_with_typesafe(
+ self.client,
+ goal=request.goal,
+ observation={
+ "capture_id": request.capture_id,
+ "regions": list(request.regions),
+ "history": list(request.history),
+ },
+ criteria=request.criteria,
+ )
+ if choice.selected_id not in request.criteria:
+ raise ValueError("Jev selected an unknown candidate")
+ if choice.probabilities.get(choice.selected_id) != max(choice.probabilities.values()):
+ raise ValueError("Jev selection disagrees with its scores")
+ return ModelScores(
+ choice.probabilities,
+ choice.model or self.name,
+ selected_id=choice.selected_id,
+ confidence=choice.confidence,
+ )
+
+
+@dataclass(frozen=True)
+class _S1Option:
+ element_id: str
+ role: str
+ label: str
+ action: str
+ entity_id: str | None = None
+
+
+def visual_regions_as_text(request: DecisionRequest) -> str:
+ """Describe OmniParser regions; this is not an accessibility tree."""
+ lines = [f"Visual-region-derived observation for capture {json.dumps(request.capture_id)}:"]
+ for region in request.regions:
+ bounds = region["bounds"]
+ label = region.get("text") or region.get("label")
+ lines.append(
+ f"{json.dumps(region['id'])}: {region['kind']} {label!r} at "
+ f"({bounds['x']},{bounds['y']},{bounds['width']},{bounds['height']}) "
+ f"confidence={json.dumps(region['confidence'])} "
+ f"interactive={json.dumps(region['interactive'])}"
+ )
+ if request.history:
+ lines.append("Prior bounded decisions:")
+ lines.extend(json.dumps(item, ensure_ascii=False) for item in request.history)
+ return "\n".join(lines)
+
+
+class S1DecisionModel:
+ name = "cua-s1-4b-local"
+
+ def __init__(
+ self,
+ scorer: Any,
+ *,
+ modality: Literal["text", "multimodal"] = "text",
+ screenshot_path: Path | None = None,
+ screenshot_capture_id: str | None = None,
+ ) -> None:
+ self.scorer = scorer
+ self.modality = modality
+ self.screenshot_path = screenshot_path
+ self.screenshot_capture_id = screenshot_capture_id
+
+ def score(self, request: DecisionRequest) -> ModelScores:
+ if len(request.candidates) > 26:
+ raise OptionLimitError("S1 uses one letter per option, at most 26")
+ if self.modality == "multimodal" and (
+ self.screenshot_path is None
+ or not self.screenshot_path.is_file()
+ or self.screenshot_capture_id != request.capture_id
+ ):
+ raise ValueError("multimodal S1 requires a screenshot bound to the request capture")
+ scorer_modality = getattr(self.scorer, "modality", self.modality)
+ if scorer_modality != self.modality:
+ raise ValueError("S1 scorer modality does not match the decision adapter")
+ options = [
+ _S1Option(
+ item["id"],
+ "Decision",
+ json.dumps(item["description"], ensure_ascii=False)[1:-1],
+ "select",
+ )
+ for item in request.candidates
+ ]
+ kwargs: dict[str, Any] = {
+ "app": "Cua Driver",
+ "task_family": "closed-candidate decision",
+ "goal": request.goal,
+ "modality": self.modality,
+ }
+ if self.modality == "text":
+ kwargs["ax_tree"] = visual_regions_as_text(request)
+ else:
+ kwargs["screenshot"] = self.screenshot_path
+ scores = self.scorer.forward(options, **kwargs)
+ probabilities: dict[str, float] = {}
+ for score in scores:
+ if score.element_id in probabilities:
+ raise ValueError("S1 returned a duplicate candidate ID")
+ probabilities[score.element_id] = score.probability
+ return ModelScores(probabilities, self.name)
diff --git a/libs/cua-driver/examples/jev-use/python/tests/test_action_policy.py b/libs/cua-driver/examples/jev-use/python/tests/test_action_policy.py
new file mode 100644
index 0000000000..1abed3a040
--- /dev/null
+++ b/libs/cua-driver/examples/jev-use/python/tests/test_action_policy.py
@@ -0,0 +1,282 @@
+from __future__ import annotations
+
+import copy
+import sys
+import unittest
+from pathlib import Path
+
+BASE = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(BASE / "python"))
+
+from action_policy import (
+ ActionAuthorizationError,
+ ExactRegionTextAction,
+ authorize_exact_region_text_action,
+)
+from choose_decision import choose_request
+from decision_models import ModelScores
+
+
+def inputs(
+ text: str = "Send", required: str = "Send"
+) -> tuple[dict, dict, dict, ExactRegionTextAction]:
+ region = {
+ "id": "text-60",
+ "kind": "text",
+ "text": text,
+ "bounds": {"x": 12, "y": 20, "width": 72, "height": 32},
+ "confidence": 0.98,
+ "interactive": False,
+ }
+ action = ExactRegionTextAction("region:text-60", "text-60", required)
+ request = {
+ "capture_id": "capture-1",
+ "regions": [copy.deepcopy(region)],
+ "candidates": [
+ action.wire_candidate(),
+ {"id": "reobserve", "description": "Observe again."},
+ {"id": "abstain", "description": "Stop."},
+ ],
+ }
+ decision = {
+ "schema": "cua.decision_choice_v1",
+ "kind": "selected",
+ "capture_id": "capture-1",
+ "selected_id": action.candidate_id,
+ "probabilities": {action.candidate_id: 0.777, "reobserve": 0.123, "abstain": 0.1},
+ }
+ parsed = {
+ "schema": "cua.visual_regions_v1",
+ "capture": {
+ "capture_id": "capture-1",
+ "source": {"kind": "window", "pid": 10, "window_id": 20},
+ "screenshot": {
+ "reference": "png-sha256:synthetic",
+ "width": 100,
+ "height": 100,
+ "mime_type": "image/png",
+ },
+ "action_coordinate_space": {"kind": "screenshot_pixels"},
+ },
+ "regions": [region],
+ }
+ return request, decision, parsed, action
+
+
+class ActionPolicyTest(unittest.TestCase):
+ def authorize(self, request, decision, parsed, action, capture_id="capture-1", source=None):
+ source = source or {"kind": "window", "pid": 10, "window_id": 20}
+ return authorize_exact_region_text_action(
+ request,
+ decision,
+ parsed,
+ action,
+ current_capture_id=capture_id,
+ expected_source=source,
+ )
+
+ def test_matching_text_authorizes(self) -> None:
+ click = self.authorize(*inputs())
+ self.assertEqual((click.capture_id, click.x, click.y), ("capture-1", 48.0, 36.0))
+
+ def test_selected_wrong_text_never_reaches_dispatch(self) -> None:
+ request, decision, parsed, action = inputs("Send", "Save")
+ request.update(
+ {"schema": "cua.jev_choice_request_v1", "goal": "Choose one.", "history": []}
+ )
+
+ class WrongSelectionModel:
+ name = "synthetic-unsafe-model"
+
+ def score(self, _request):
+ return ModelScores(
+ {action.candidate_id: 0.777, "reobserve": 0.123, "abstain": 0.1},
+ self.name,
+ )
+
+ decision = choose_request(request, WrongSelectionModel())
+ self.assertEqual(
+ (decision["kind"], decision["selected_id"]), ("selected", action.candidate_id)
+ )
+ dispatched: list[str] = []
+ with self.assertRaisesRegex(ActionAuthorizationError, "exact-text condition"):
+ self.authorize(request, decision, parsed, action)
+ dispatched.append("click")
+ self.assertEqual(dispatched, [])
+
+ def test_stale_or_changed_capture_refuses(self) -> None:
+ for field in ("request", "decision", "parse", "current"):
+ with self.subTest(field=field):
+ request, decision, parsed, action = inputs()
+ current = "capture-1"
+ if field == "request":
+ request["capture_id"] = "old"
+ elif field == "decision":
+ decision["capture_id"] = "old"
+ elif field == "parse":
+ parsed["capture"]["capture_id"] = "old"
+ else:
+ current = "new"
+ with self.assertRaisesRegex(ActionAuthorizationError, "capture identity"):
+ self.authorize(request, decision, parsed, action, current)
+
+ def test_action_and_offered_condition_must_match(self) -> None:
+ request, decision, parsed, action = inputs()
+ request["candidates"][0]["description"] = "An unrelated condition."
+ with self.assertRaisesRegex(ActionAuthorizationError, "action condition"):
+ self.authorize(request, decision, parsed, action)
+
+ request, decision, parsed, action = inputs()
+ decision["selected_id"] = "abstain"
+ with self.assertRaisesRegex(ActionAuthorizationError, "did not select"):
+ self.authorize(request, decision, parsed, action)
+
+ def test_nonunique_low_confidence_and_offered_region_refuse(self) -> None:
+ for field in ("duplicate", "low_confidence", "offered", "bounds"):
+ with self.subTest(field=field):
+ request, decision, parsed, action = inputs()
+ if field == "duplicate":
+ other = copy.deepcopy(parsed["regions"][0])
+ other["id"] = "text-61"
+ parsed["regions"].append(other)
+ elif field == "low_confidence":
+ parsed["regions"][0]["confidence"] = 0.7999
+ request["regions"][0]["confidence"] = 0.7999
+ elif field == "offered":
+ request["regions"][0]["text"] = "Save"
+ else:
+ parsed["regions"][0]["bounds"]["width"] = 0
+ request["regions"][0]["bounds"]["width"] = 0
+ with self.assertRaises(ActionAuthorizationError):
+ self.authorize(request, decision, parsed, action)
+
+ def test_case_is_exact_and_reserved_outcomes_are_not_actions(self) -> None:
+ request, decision, parsed, action = inputs("send", "Send")
+ with self.assertRaisesRegex(ActionAuthorizationError, "exact-text condition"):
+ self.authorize(request, decision, parsed, action)
+ request, decision, parsed, action = inputs()
+ decision.update({"kind": "abstain", "selected_id": "abstain"})
+ with self.assertRaisesRegex(ActionAuthorizationError, "did not select"):
+ self.authorize(request, decision, parsed, action)
+
+ def test_unsupported_action_and_malformed_confidence_refuse(self) -> None:
+ request, decision, parsed, action = inputs()
+ with self.assertRaisesRegex(ActionAuthorizationError, "unsupported action"):
+ self.authorize(request, decision, parsed, object())
+ parsed["regions"][0]["confidence"] = float("nan")
+ with self.assertRaisesRegex(ActionAuthorizationError, "malformed visual confidence"):
+ self.authorize(request, decision, parsed, action)
+
+ def test_decision_scores_must_match_offered_candidates(self) -> None:
+ for case in ("missing", "wrong_set", "non_argmax"):
+ with self.subTest(case=case):
+ request, decision, parsed, action = inputs()
+ if case == "missing":
+ del decision["probabilities"]
+ elif case == "wrong_set":
+ decision["probabilities"]["invented"] = 0.0
+ else:
+ decision["probabilities"] = {
+ action.candidate_id: 0.2,
+ "reobserve": 0.7,
+ "abstain": 0.1,
+ }
+ with self.assertRaisesRegex(ActionAuthorizationError, "decision scores"):
+ self.authorize(request, decision, parsed, action)
+
+ def test_wire_description_preserves_the_enforced_threshold(self) -> None:
+ with self.assertRaisesRegex(ValueError, "two decimal places"):
+ ExactRegionTextAction("region:one", "one", "Send", 0.805)
+
+ def test_source_geometry_and_provenance_are_checked(self) -> None:
+ for case in ("source", "screenshot", "outside", "mapping"):
+ with self.subTest(case=case):
+ request, decision, parsed, action = inputs()
+ if case == "source":
+ parsed["capture"]["source"]["window_id"] = 21
+ elif case == "screenshot":
+ parsed["capture"]["screenshot"]["mime_type"] = "image/jpeg"
+ elif case == "outside":
+ parsed["regions"][0]["bounds"]["x"] = 90
+ request["regions"][0]["bounds"]["x"] = 90
+ else:
+ parsed["capture"]["action_coordinate_space"] = {
+ "kind": "affine",
+ "m11": 0,
+ "m12": 0,
+ "m21": 0,
+ "m22": 0,
+ "tx": 0,
+ "ty": 0,
+ }
+ with self.assertRaises(ActionAuthorizationError):
+ self.authorize(request, decision, parsed, action)
+
+ def test_primary_desktop_and_affine_coordinates(self) -> None:
+ request, decision, parsed, action = inputs()
+ source = {"kind": "primary_desktop", "display_id": "primary"}
+ parsed["capture"]["source"] = source
+ parsed["capture"]["action_coordinate_space"] = {
+ "kind": "affine",
+ "m11": 2,
+ "m12": 0,
+ "m21": 0,
+ "m22": 2,
+ "tx": 10,
+ "ty": 20,
+ }
+ click = self.authorize(request, decision, parsed, action, source=source)
+ self.assertEqual((click.x, click.y), (48.0, 36.0))
+
+ def test_affine_coordinates_are_not_mapped_twice(self) -> None:
+ request, decision, parsed, action = inputs()
+ parsed["capture"]["action_coordinate_space"] = {
+ "kind": "affine",
+ "m11": 0.5,
+ "m12": 0,
+ "m21": 0,
+ "m22": 0.5,
+ "tx": 0,
+ "ty": 0,
+ }
+ click = self.authorize(request, decision, parsed, action)
+ self.assertEqual((click.x, click.y), (48.0, 36.0))
+
+ def test_affine_mapping_that_overflows_the_point_refuses(self) -> None:
+ request, decision, parsed, action = inputs()
+ parsed["capture"]["action_coordinate_space"] = {
+ "kind": "affine",
+ "m11": 1e308,
+ "m12": 0,
+ "m21": 0,
+ "m22": 1e-308,
+ "tx": 0,
+ "ty": 0,
+ }
+ with self.assertRaisesRegex(ActionAuthorizationError, "non-finite point"):
+ self.authorize(request, decision, parsed, action)
+
+ def test_tied_scores_and_duplicate_offered_regions_refuse(self) -> None:
+ request, decision, parsed, action = inputs()
+ decision["probabilities"] = {
+ action.candidate_id: 0.5,
+ "reobserve": 0.5,
+ "abstain": 0.0,
+ }
+ with self.assertRaisesRegex(ActionAuthorizationError, "decision scores"):
+ self.authorize(request, decision, parsed, action)
+ request, decision, parsed, action = inputs()
+ request["regions"].append(copy.deepcopy(request["regions"][0]))
+ with self.assertRaisesRegex(ActionAuthorizationError, "offered visual regions"):
+ self.authorize(request, decision, parsed, action)
+
+ def test_driver_optional_region_metadata_does_not_block_authorization(self) -> None:
+ request, decision, parsed, action = inputs()
+ parsed["regions"][0].update({"reading_order": 1, "parent_id": None})
+ request["regions"][0]["label"] = None
+ click = self.authorize(request, decision, parsed, action)
+ self.assertEqual((click.x, click.y), (48.0, 36.0))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/libs/cua-driver/examples/jev-use/python/tests/test_decision_models.py b/libs/cua-driver/examples/jev-use/python/tests/test_decision_models.py
new file mode 100644
index 0000000000..9e699a0cc5
--- /dev/null
+++ b/libs/cua-driver/examples/jev-use/python/tests/test_decision_models.py
@@ -0,0 +1,314 @@
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+
+BASE = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(BASE / "python"))
+
+from choose_decision import MockDecisionModel, choose_request
+from decision_models import S1DecisionModel, TypeSafeDecisionModel
+
+
+def request() -> dict:
+ return {
+ "schema": "cua.jev_choice_request_v1",
+ "goal": "Submit the verified form.",
+ "capture_id": "capture-1",
+ "regions": [
+ {
+ "id": "submit-label",
+ "kind": "text",
+ "bounds": {"x": 10, "y": 20, "width": 80, "height": 30},
+ "text": "Submit",
+ "confidence": 0.98,
+ "interactive": True,
+ }
+ ],
+ "history": [],
+ "candidates": [
+ {"id": "submit-form", "description": "Submit the form."},
+ {"id": "reobserve", "description": "Get a fresh observation."},
+ {"id": "abstain", "description": "Stop without acting."},
+ ],
+ }
+
+
+class FakeScorer:
+ def __init__(self, probabilities: dict[str, float]) -> None:
+ self.probabilities = probabilities
+ self.calls: list[tuple] = []
+
+ def forward(self, options, **kwargs):
+ self.calls.append((options, kwargs))
+ return [
+ SimpleNamespace(
+ element_id=option.element_id, probability=self.probabilities[option.element_id]
+ )
+ for option in options
+ ]
+
+
+class DecisionModelsTest(unittest.TestCase):
+ def test_mock_cli_returns_only_one_bounded_id(self) -> None:
+ result = subprocess.run(
+ [sys.executable, str(BASE / "python/choose_decision.py"), "--model", "mock"],
+ input=json.dumps(request()),
+ text=True,
+ capture_output=True,
+ check=True,
+ )
+ choice = json.loads(result.stdout)
+ self.assertEqual(choice["kind"], "selected")
+ self.assertEqual(choice["capture_id"], "capture-1")
+ self.assertEqual(choice["selected_id"], "submit-form")
+ self.assertEqual(set(choice["probabilities"]), {"submit-form", "reobserve", "abstain"})
+ self.assertNotIn("arguments", result.stdout)
+ self.assertEqual(result.stderr, "")
+
+ def test_s1_text_adapter_maps_exact_ids_and_labels_region_text_honestly(self) -> None:
+ scorer = FakeScorer({"submit-form": 0.95, "reobserve": 0.03, "abstain": 0.02})
+ choice = choose_request(request(), S1DecisionModel(scorer))
+ self.assertEqual(choice["selected_id"], "submit-form")
+ self.assertEqual(choice["model"], "cua-s1-4b-local")
+ options, kwargs = scorer.calls[0]
+ self.assertEqual([option.element_id for option in options], list(choice["probabilities"]))
+ self.assertIn("Visual-region-derived", kwargs["ax_tree"])
+ self.assertIn("confidence=0.98", kwargs["ax_tree"])
+ self.assertIn("interactive=true", kwargs["ax_tree"])
+ self.assertNotIn("screenshot", kwargs)
+
+ def test_s1_text_adapter_preserves_region_confidence_and_interactivity(self) -> None:
+ value = request()
+ value["regions"][0]["confidence"] = 0.7999
+ value["regions"][0]["interactive"] = False
+ scorer = FakeScorer({"submit-form": 1.0, "reobserve": 0.0, "abstain": 0.0})
+ choose_request(value, S1DecisionModel(scorer))
+ prompt = scorer.calls[0][1]["ax_tree"]
+ self.assertIn("confidence=0.7999", prompt)
+ self.assertIn("interactive=false", prompt)
+
+ def test_s1_reserved_decisions_do_not_become_actions(self) -> None:
+ for selected, kind in (("reobserve", "reobserve"), ("abstain", "abstain")):
+ scores = {item["id"]: float(item["id"] == selected) for item in request()["candidates"]}
+ choice = choose_request(request(), S1DecisionModel(FakeScorer(scores)))
+ self.assertEqual((choice["kind"], choice["selected_id"]), (kind, selected))
+
+ def test_s1_rejects_27_candidates_without_silent_truncation(self) -> None:
+ value = request()
+ value["candidates"] = [
+ {"id": f"choice-{index}", "description": f"Choice {index}"} for index in range(25)
+ ] + value["candidates"][-2:]
+ scorer = FakeScorer({})
+ choice = choose_request(value, S1DecisionModel(scorer))
+ self.assertEqual((choice["kind"], choice["reason"]), ("error", "option_limit"))
+ self.assertEqual(scorer.calls, [])
+
+ def test_s1_accepts_26_candidates(self) -> None:
+ value = request()
+ value["candidates"] = [
+ {"id": f"choice-{index}", "description": f"Choice {index}"} for index in range(24)
+ ] + value["candidates"][-2:]
+ scores = {item["id"]: float(item["id"] == "choice-0") for item in value["candidates"]}
+ choice = choose_request(value, S1DecisionModel(FakeScorer(scores)))
+ self.assertEqual(choice["kind"], "selected")
+ self.assertEqual(choice["selected_id"], "choice-0")
+
+ def test_invalid_s1_scores_are_non_actionable(self) -> None:
+ for scores in (
+ {"submit-form": 1.0},
+ {"submit-form": 0.5, "reobserve": 0.5, "abstain": float("nan")},
+ {"submit-form": 0.5, "reobserve": 0.3, "abstain": 0.0},
+ ):
+ with self.subTest(scores=scores):
+ choice = choose_request(request(), S1DecisionModel(FakeScorer(scores)))
+ self.assertEqual(choice["kind"], "error")
+ self.assertIsNone(choice["selected_id"])
+
+ class ExtraScorer:
+ def forward(self, options, **kwargs):
+ return [
+ *FakeScorer({"submit-form": 1.0, "reobserve": 0.0, "abstain": 0.0}).forward(
+ options, **kwargs
+ ),
+ SimpleNamespace(element_id="invented", probability=0.0),
+ ]
+
+ extra = choose_request(request(), S1DecisionModel(ExtraScorer()))
+ self.assertEqual(extra["kind"], "error")
+ self.assertIsNone(extra["selected_id"])
+
+ def test_multimodal_mode_requires_local_screenshot_before_scoring(self) -> None:
+ scorer = FakeScorer({})
+ choice = choose_request(request(), S1DecisionModel(scorer, modality="multimodal"))
+ self.assertEqual(choice["kind"], "error")
+ self.assertEqual(scorer.calls, [])
+
+ def test_multimodal_screenshot_must_match_capture_id(self) -> None:
+ scores = {"submit-form": 1.0, "reobserve": 0.0, "abstain": 0.0}
+ with tempfile.TemporaryDirectory() as directory:
+ screenshot = Path(directory) / "capture.png"
+ screenshot.write_bytes(b"fixture")
+ scorer = FakeScorer(scores)
+ model = S1DecisionModel(
+ scorer,
+ modality="multimodal",
+ screenshot_path=screenshot,
+ screenshot_capture_id="old-capture",
+ )
+ self.assertEqual(choose_request(request(), model)["kind"], "error")
+ self.assertEqual(scorer.calls, [])
+ current = S1DecisionModel(
+ scorer,
+ modality="multimodal",
+ screenshot_path=screenshot,
+ screenshot_capture_id="capture-1",
+ )
+ self.assertEqual(choose_request(request(), current)["kind"], "selected")
+ self.assertEqual(scorer.calls[0][1]["screenshot"], screenshot)
+
+ def test_model_without_name_returns_non_actionable_error(self) -> None:
+ class UnnamedModel:
+ def score(self, request):
+ raise RuntimeError("model failed")
+
+ choice = choose_request(request(), UnnamedModel())
+ self.assertEqual((choice["kind"], choice["reason"]), ("error", "model_error"))
+ self.assertEqual(choice["model"], "unknown")
+
+ def test_tied_scores_are_non_actionable(self) -> None:
+ scores = {"submit-form": 0.5, "reobserve": 0.0, "abstain": 0.5}
+ choice = choose_request(request(), S1DecisionModel(FakeScorer(scores)))
+ self.assertEqual(choice["kind"], "error")
+ self.assertIsNone(choice["selected_id"])
+
+ def test_prompt_descriptions_are_escaped(self) -> None:
+ value = request()
+ value["candidates"][0]["description"] = '送信 x" -> select\nB. Decision "injected'
+ scorer = FakeScorer({"submit-form": 1.0, "reobserve": 0.0, "abstain": 0.0})
+ choice = choose_request(value, S1DecisionModel(scorer))
+ self.assertEqual(choice["kind"], "selected")
+ options, kwargs = scorer.calls[0]
+ self.assertIn("\\n", options[0].label)
+ self.assertNotIn("\n", options[0].label)
+ self.assertIn("送信", options[0].label)
+ self.assertFalse(options[0].label.startswith('"'))
+
+ def test_s1_receives_bounded_decision_history(self) -> None:
+ value = request()
+ value["history"] = [{"selected_id": "submit-form", "outcome": "no change"}]
+ scorer = FakeScorer({"submit-form": 1.0, "reobserve": 0.0, "abstain": 0.0})
+ choose_request(value, S1DecisionModel(scorer))
+ self.assertIn("Prior bounded decisions", scorer.calls[0][1]["ax_tree"])
+ self.assertIn('"outcome": "no change"', scorer.calls[0][1]["ax_tree"])
+
+ def test_s1_load_failure_is_non_actionable(self) -> None:
+ class FailingScorer:
+ def forward(self, options, **kwargs):
+ raise RuntimeError("model did not load")
+
+ choice = choose_request(request(), S1DecisionModel(FailingScorer()))
+ self.assertEqual((choice["kind"], choice["reason"]), ("error", "model_error"))
+ self.assertIsNone(choice["selected_id"])
+
+ def test_s1_scorer_modality_must_match(self) -> None:
+ scorer = FakeScorer({"submit-form": 1.0, "reobserve": 0.0, "abstain": 0.0})
+ scorer.modality = "multimodal"
+ choice = choose_request(request(), S1DecisionModel(scorer))
+ self.assertEqual(choice["kind"], "error")
+ self.assertEqual(scorer.calls, [])
+
+ def test_s1_cli_rejects_unset_or_empty_paths(self) -> None:
+ script = str(BASE / "python/choose_decision.py")
+ for base, adapter in ((None, None), ("", "")):
+ with self.subTest(base=base, adapter=adapter):
+ env = os.environ.copy()
+ for name, value in (("S1_BASE_MODEL_PATH", base), ("S1_ADAPTER_PATH", adapter)):
+ if value is None:
+ env.pop(name, None)
+ else:
+ env[name] = value
+ result = subprocess.run(
+ [sys.executable, script, "--model", "s1"],
+ input=json.dumps(request()),
+ text=True,
+ capture_output=True,
+ env=env,
+ check=False,
+ )
+ self.assertNotEqual(result.returncode, 0)
+ self.assertEqual(result.stdout, "")
+ self.assertIn("S1 setup failed", result.stderr)
+
+ def test_typesafe_request_contains_no_screenshot_or_action_arguments(self) -> None:
+ class FakeClient:
+ sent = None
+
+ def system_one(self, **payload):
+ self.sent = payload
+ return SimpleNamespace(
+ model="jev-test",
+ choices={
+ "candidate": SimpleNamespace(
+ choice="submit-form",
+ confidence=0.9,
+ probabilities={"submit-form": 0.9, "reobserve": 0.05, "abstain": 0.05},
+ )
+ },
+ )
+
+ client = FakeClient()
+ choice = choose_request(request(), TypeSafeDecisionModel(client))
+ self.assertEqual(choice["selected_id"], "submit-form")
+ payload = json.dumps(client.sent, default=str)
+ self.assertNotIn("screenshot", payload)
+ self.assertNotIn("arguments", payload)
+ self.assertEqual(
+ set(client.sent["questions"]["candidate"].criteria), set(choice["probabilities"])
+ )
+
+ def test_typesafe_selection_can_differ_from_provider_confidence(self) -> None:
+ class FakeClient:
+ def system_one(self, **payload):
+ return SimpleNamespace(
+ model="jev-test",
+ choices={
+ "candidate": SimpleNamespace(
+ choice="submit-form",
+ confidence=0.71,
+ probabilities={"submit-form": 0.8, "reobserve": 0.1, "abstain": 0.1},
+ )
+ },
+ )
+
+ choice = choose_request(request(), TypeSafeDecisionModel(FakeClient()))
+ self.assertEqual(choice["kind"], "selected")
+ self.assertEqual(choice["confidence"], 0.71)
+
+ def test_typesafe_non_argmax_selection_is_rejected(self) -> None:
+ class FakeClient:
+ def system_one(self, **payload):
+ return SimpleNamespace(
+ model="jev-test",
+ choices={
+ "candidate": SimpleNamespace(
+ choice="abstain",
+ confidence=0.7,
+ probabilities={"submit-form": 0.8, "reobserve": 0.1, "abstain": 0.1},
+ )
+ },
+ )
+
+ choice = choose_request(request(), TypeSafeDecisionModel(FakeClient()))
+ self.assertEqual(choice["kind"], "error")
+ self.assertIsNone(choice["selected_id"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/libs/cua-driver/examples/jev-use/verify_decision_cli.py b/libs/cua-driver/examples/jev-use/verify_decision_cli.py
new file mode 100644
index 0000000000..c507c7c490
--- /dev/null
+++ b/libs/cua-driver/examples/jev-use/verify_decision_cli.py
@@ -0,0 +1,66 @@
+"""Exercise the closed-candidate CLI against a synthetic request."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import subprocess
+import sys
+from pathlib import Path
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--model", choices=("mock", "jev", "s1"), required=True)
+ parser.add_argument("--expected-id", default="submit-form")
+ parser.add_argument("--fixture", choices=("positive", "negative"), default="positive")
+ args = parser.parse_args()
+
+ root = Path(__file__).resolve().parent
+ fixture_name = (
+ "jev-choice-request-v1.json"
+ if args.fixture == "positive"
+ else "jev-choice-negative-v1.json"
+ )
+ request = json.loads((root / "fixtures" / fixture_name).read_text(encoding="utf-8"))
+ result = subprocess.run(
+ [sys.executable, str(root / "python/choose_decision.py"), "--model", args.model],
+ input=json.dumps(request),
+ text=True,
+ capture_output=True,
+ check=True,
+ )
+ response = json.loads(result.stdout)
+ expected_keys = {
+ "schema",
+ "kind",
+ "capture_id",
+ "selected_id",
+ "model",
+ "confidence",
+ "probabilities",
+ "reason",
+ }
+ if set(response) != expected_keys or response["schema"] != "cua.decision_choice_v1":
+ raise RuntimeError("decision model returned an unsupported response")
+ if response["capture_id"] != request["capture_id"]:
+ raise RuntimeError("decision model returned a different capture")
+ expected_kind = args.expected_id if args.expected_id in {"reobserve", "abstain"} else "selected"
+ if (response["kind"], response["selected_id"]) != (expected_kind, args.expected_id):
+ raise RuntimeError("decision model did not select the expected candidate")
+ candidate_ids = {candidate["id"] for candidate in request["candidates"]}
+ if set(response["probabilities"]) != candidate_ids:
+ raise RuntimeError("decision model returned a different candidate set")
+ print(
+ json.dumps(
+ {
+ "model": response["model"],
+ "kind": response["kind"],
+ "selected_id": response["selected_id"],
+ }
+ )
+ )
+
+
+if __name__ == "__main__":
+ main()