Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
feat(cua-driver): let the jev-use native runners choose with Cua-S1 (#4295)
Francesco Bonacci705749639948
diff --git a/libs/cua-driver/examples/jev-use/README.md b/libs/cua-driver/examples/jev-use/README.mdindex 79f790ad0f..226a358010 100644--- a/libs/cua-driver/examples/jev-use/README.md+++ b/libs/cua-driver/examples/jev-use/README.md@@ -128,6 +128,30 @@ no `value` for a named text field`gtk3-save-note` cannot observe its own write, so it keeps offering the writeuntil the step budget runs out.+#### Choose with Cua-S1++The native runners also accept `--provider s1`, and `verify_native.py` accepts+`--s1`. Loading Cua-S1 takes 10 to 35 seconds, so a per-step model load would+not fit inside Driver's 60-second capture lifetime. The runners therefore send+each validated `cua.jev_choice_request_v2` request to an already loaded model+behind a loopback HTTP endpoint, and read one `cua.decision_choice_v1`+response. `CUA_S1_DECISION_URL` names that endpoint. It must be a plain+`http://` URL on `127.0.0.1`, `localhost`, or `::1`; a model on another host is+reached through an SSH tunnel. The runner rejects a response whose schema,+`capture_id`, kind, selected ID, or probabilities do not match the request, and+it resolves the selected ID to its own candidate as with every other provider.++The service is not part of this example. Any server that loads the pinned+checkpoint from [`libs/cua-s1`](../../../cua-s1/README.md), validates the+request with `python/choose_action.py`, and answers with+`decision_models.choose(S1DecisionModel(...), request).to_wire()` fits the+contract. For example, to verify the native tasks with it:++```bash+export CUA_S1_DECISION_URL=http://127.0.0.1:8791/decide+uv run --frozen python verify_native.py --harness appkit --typescript --s1 --output-dir /tmp/jev-native-s1+```+The MCP connection stays open across the entire loop. This preserves theexplicit named Cua Driver session and avoids rebuilding tool state for everystep.diff --git a/libs/cua-driver/examples/jev-use/python/run_native.py b/libs/cua-driver/examples/jev-use/python/run_native.pyindex 8dbdca5c9f..df213676c7 100644--- a/libs/cua-driver/examples/jev-use/python/run_native.py+++ b/libs/cua-driver/examples/jev-use/python/run_native.py@@ -43,6 +43,7 @@ from native_tasks import (native_choice_request,visual_fallback_reason,)+from s1_service import choose_s1_service, s1_service_urlfrom run import Driver, DriverToolError, background_refusal_code, supports_capture_bound_clickfrom sources import NativeAccessibilitySource, VisualRegionSourcefrom tasks import TaskSources@@ -274,6 +275,8 @@ async def run_task(args: argparse.Namespace, task: NativeTask) -> str:choice, confidence, probabilities = choose_mock_for_task(task, sources, plan.candidates, history)+ elif args.provider == "s1":+ choice, confidence, probabilities = await asyncio.to_thread(choose_s1_service, request)else:choice, confidence, probabilities = await asyncio.to_thread(choose_live, request)decide_ms = round((time.perf_counter() - decide_started) * 1000, 2)@@ -352,7 +355,10 @@ async def run_task(args: argparse.Namespace, task: NativeTask) -> str:def parse_args(argv: list[str] | None = None) -> argparse.Namespace:parser = argparse.ArgumentParser(description=__doc__)parser.add_argument("--task", choices=NATIVE_TASK_IDS, required=True)- parser.add_argument("--provider", choices=("mock", "live"), default="mock")+ parser.add_argument(+ "--provider", choices=("mock", "live", "s1"), default="mock",+ help="s1 reads the loopback decide URL from CUA_S1_DECISION_URL",+ )parser.add_argument("--pid", type=int, required=True, help="the running harness process")parser.add_argument("--state-file", required=True, help="the harness task-state file path")parser.add_argument("--note-text", help="note text for the save-note tasks")@@ -371,6 +377,8 @@ def task_from_args(args: argparse.Namespace) -> NativeTask:def main() -> None:args = parse_args()+ if args.provider == "s1":+ s1_service_url() # fail before touching the app when the service is not configuredtry:outcome = asyncio.run(run_task(args, task_from_args(args)))except (OracleError, NativeObservationError) as error:diff --git a/libs/cua-driver/examples/jev-use/python/s1_service.py b/libs/cua-driver/examples/jev-use/python/s1_service.pynew file mode 100644index 0000000000..b61fd94a21--- /dev/null+++ b/libs/cua-driver/examples/jev-use/python/s1_service.py@@ -0,0 +1,119 @@+"""Choose one supplied candidate through a warm, loopback S1 decision service.++Loading Cua-S1 costs 10 to 35 seconds, which does not fit inside Driver's+60-second capture lifetime when every step starts a new process. The native+runners therefore reach an already loaded model through a small HTTP service+on the loopback interface. ``CUA_S1_DECISION_URL`` names its decide endpoint,+for example ``http://127.0.0.1:8791/decide``.++The service receives the same validated ``cua.jev_choice_request_v1`` or+``_v2`` request that every other provider sees and returns one+``cua.decision_choice_v1`` response. This module checks that response strictly+before the runner resolves the selected ID to its own immutable candidate. The+request never contains element tokens, values, secrets, or pixels.+"""++from __future__ import annotations++import ipaddress+import json+import math+import os+import urllib.error+import urllib.request+from typing import Any, Mapping+from urllib.parse import urlsplit++from choose_action import validate_request++DECISION_SCHEMA = "cua.decision_choice_v1"+DECISION_KINDS = frozenset({"selected", "reobserve", "abstain", "error"})+URL_ENV = "CUA_S1_DECISION_URL"+DEFAULT_TIMEOUT_S = 30.0+MAX_RESPONSE_BYTES = 256 * 1024+++class S1ServiceError(RuntimeError):+ """The service was unreachable or returned an unusable decision."""+++def s1_service_url(value: str | None = None) -> str:+ """Return the configured decide URL; it must be plain HTTP on loopback."""+ url = (value if value is not None else os.environ.get(URL_ENV, "")).strip()+ if not url:+ raise S1ServiceError(f"{URL_ENV} is not set")+ parts = urlsplit(url)+ host = parts.hostname or ""+ try:+ loopback = host == "localhost" or ipaddress.ip_address(host).is_loopback+ except ValueError:+ loopback = False+ if parts.scheme != "http" or not loopback or parts.username or parts.password:+ raise S1ServiceError(f"{URL_ENV} must be an http:// URL on the loopback interface")+ return url+++def _finite_unit(value: Any) -> bool:+ return (+ isinstance(value, (int, float))+ and not isinstance(value, bool)+ and math.isfinite(value)+ and 0 <= value <= 1+ )+++def validate_decision(decision: Any, request: Mapping[str, Any]) -> dict[str, Any]:+ """Check a ``cua.decision_choice_v1`` response against the request it answers."""+ if not isinstance(decision, dict) or decision.get("schema") != DECISION_SCHEMA:+ raise S1ServiceError("response is not a cua.decision_choice_v1 decision")+ kind = decision.get("kind")+ if kind not in DECISION_KINDS:+ raise S1ServiceError("response kind is not supported")+ if decision.get("capture_id") != request.get("capture_id"):+ raise S1ServiceError("response capture_id does not match the request")+ if kind == "error":+ raise S1ServiceError(f"S1 decision failed: {decision.get('reason') or 'unknown'}")+ ids = [candidate["id"] for candidate in request["candidates"]]+ selected = decision.get("selected_id")+ if selected not in ids:+ raise S1ServiceError("S1 selected an ID that was not supplied")+ expected_kind = selected if selected in {"reobserve", "abstain"} else "selected"+ if kind != expected_kind:+ raise S1ServiceError("response kind does not match the selected ID")+ probabilities = decision.get("probabilities")+ if (+ not isinstance(probabilities, dict)+ or set(probabilities) != set(ids)+ or not all(_finite_unit(value) for value in probabilities.values())+ ):+ raise S1ServiceError("response probabilities do not match the candidate set")+ confidence = decision.get("confidence")+ if not _finite_unit(confidence):+ raise S1ServiceError("response confidence must be a finite number in [0, 1]")+ return decision+++def choose_s1_service(+ request: Mapping[str, Any], url: str | None = None, timeout: float = DEFAULT_TIMEOUT_S+) -> tuple[str | None, float, dict[str, float]]:+ """POST one validated request and return ``(selected_id, confidence, probabilities)``."""+ validated = validate_request(request)+ body = json.dumps(request, separators=(",", ":")).encode()+ http_request = urllib.request.Request(+ s1_service_url(url), data=body, method="POST", headers={"Content-Type": "application/json"}+ )+ try:+ with urllib.request.urlopen(http_request, timeout=timeout) as response: # noqa: S310+ payload = response.read(MAX_RESPONSE_BYTES + 1)+ except urllib.error.HTTPError as error:+ raise S1ServiceError(f"S1 service returned HTTP {error.code}") from None+ except (urllib.error.URLError, TimeoutError, OSError) as error:+ raise S1ServiceError(f"S1 service is unreachable: {type(error).__name__}") from None+ if len(payload) > MAX_RESPONSE_BYTES:+ raise S1ServiceError("S1 response is too large")+ try:+ decision = json.loads(payload)+ except json.JSONDecodeError:+ raise S1ServiceError("S1 response is not JSON") from None+ decision = validate_decision(decision, validated)+ return decision["selected_id"], float(decision["confidence"]), dict(decision["probabilities"])diff --git a/libs/cua-driver/examples/jev-use/python/tests/test_s1_service.py b/libs/cua-driver/examples/jev-use/python/tests/test_s1_service.pynew file mode 100644index 0000000000..2475a2c844--- /dev/null+++ b/libs/cua-driver/examples/jev-use/python/tests/test_s1_service.py@@ -0,0 +1,155 @@+"""Loopback S1 decision-service provider tests (RFC #4268 Phase 3)."""++from __future__ import annotations++import json+import sys+import threading+import unittest+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from run_native import parse_args+from s1_service import S1ServiceError, choose_s1_service, s1_service_url, validate_decision++REQUEST = {+ "schema": "cua.jev_choice_request_v2",+ "goal": "Set the counter to 3.",+ "capture_id": "cap-1",+ "regions": [],+ "history": [],+ "candidates": [+ {"id": "ax:button:increment", "description": "Click Increment", "source": "ax"},+ {"id": "reobserve", "description": "Observe again"},+ {"id": "abstain", "description": "Stop"},+ ],+}+++def decision(**overrides):+ value = {+ "schema": "cua.decision_choice_v1",+ "kind": "selected",+ "capture_id": "cap-1",+ "selected_id": "ax:button:increment",+ "model": "cua-s1-4b-0.2",+ "confidence": 0.9,+ "probabilities": {"ax:button:increment": 0.9, "reobserve": 0.06, "abstain": 0.04},+ "reason": None,+ }+ value.update(overrides)+ return value+++class Service:+ """A one-endpoint loopback server that records requests and replays a response."""++ def __init__(self, status: int, body: bytes):+ self.received: list[dict] = []+ outer = self++ class Handler(BaseHTTPRequestHandler):+ def log_message(self, *_args):+ pass++ def do_POST(self):+ length = int(self.headers.get("Content-Length") or 0)+ outer.received.append(json.loads(self.rfile.read(length)))+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ self.url = f"http://127.0.0.1:{self.server.server_address[1]}/decide"+ threading.Thread(target=self.server.serve_forever, daemon=True).start()++ def close(self):+ self.server.shutdown()+ self.server.server_close()+++class S1ServiceUrlTest(unittest.TestCase):+ def test_accepts_loopback_http(self):+ for url in ("http://127.0.0.1:8791/decide", "http://localhost:8791/decide", "http://[::1]:8791/decide"):+ self.assertEqual(s1_service_url(url), url)++ def test_rejects_remote_tls_credentials_and_missing(self):+ for url in (+ "http://10.0.0.5:8791/decide",+ "http://example.com/decide",+ "https://127.0.0.1:8791/decide",+ "http://user:[email protected]:8791/decide",+ "",+ ):+ with self.assertRaises(S1ServiceError):+ s1_service_url(url)+++class ValidateDecisionTest(unittest.TestCase):+ def test_accepts_selected_reobserve_and_abstain(self):+ self.assertEqual(validate_decision(decision(), REQUEST)["selected_id"], "ax:button:increment")+ for choice in ("reobserve", "abstain"):+ probabilities = {"ax:button:increment": 0.1, "reobserve": 0.1, "abstain": 0.1, choice: 0.8}+ value = decision(kind=choice, selected_id=choice, confidence=0.8, probabilities=probabilities)+ self.assertEqual(validate_decision(value, REQUEST)["kind"], choice)++ def test_rejects_malformed_decisions(self):+ bad = [+ decision(schema="cua.decision_choice_v0"),+ decision(kind="act"),+ decision(capture_id="cap-2"),+ decision(kind="error", selected_id=None, reason="model_error"),+ decision(selected_id="ax:button:reset"),+ decision(kind="reobserve"),+ decision(probabilities={"ax:button:increment": 1.0}),+ decision(probabilities={"ax:button:increment": 1.5, "reobserve": 0, "abstain": 0}),+ decision(confidence=float("nan")),+ decision(confidence=True),+ [],+ ]+ for value in bad:+ with self.assertRaises(S1ServiceError, msg=json.dumps(value, default=str)):+ validate_decision(value, REQUEST)+++class ChooseS1ServiceTest(unittest.TestCase):+ def test_posts_the_request_and_returns_the_choice(self):+ service = Service(200, json.dumps(decision()).encode())+ try:+ choice, confidence, probabilities = choose_s1_service(REQUEST, url=service.url)+ finally:+ service.close()+ self.assertEqual(service.received, [REQUEST])+ self.assertEqual(choice, "ax:button:increment")+ self.assertEqual(confidence, 0.9)+ self.assertEqual(set(probabilities), {"ax:button:increment", "reobserve", "abstain"})++ def test_http_errors_and_invalid_json_raise(self):+ for status, body in ((400, b'{"error":"invalid_request"}'), (200, b"not json")):+ service = Service(status, body)+ try:+ with self.assertRaises(S1ServiceError):+ choose_s1_service(REQUEST, url=service.url)+ finally:+ service.close()++ def test_unreachable_service_raises(self):+ service = Service(200, b"{}")+ url = service.url+ service.close()+ with self.assertRaises(S1ServiceError):+ choose_s1_service(REQUEST, url=url, timeout=2)+++class RunnerArgumentsTest(unittest.TestCase):+ def test_runner_accepts_the_s1_provider(self):+ args = parse_args(["--task", "appkit-counter", "--provider", "s1", "--pid", "1", "--state-file", "s"])+ self.assertEqual(args.provider, "s1")+++if __name__ == "__main__":+ unittest.main()diff --git a/libs/cua-driver/examples/jev-use/typescript/run_native.ts b/libs/cua-driver/examples/jev-use/typescript/run_native.tsindex 25a91cf670..d88128522e 100644--- a/libs/cua-driver/examples/jev-use/typescript/run_native.ts+++ b/libs/cua-driver/examples/jev-use/typescript/run_native.ts@@ -28,6 +28,7 @@ import {windowStateArguments,type NativeTask,} from './native_tasks.js';+import { chooseS1Service, s1ServiceUrl } from './s1_service.js';import { backgroundRefusalCode, Driver, DriverToolError, supportsCaptureBoundClick } from './run.js';import { NativeAccessibilitySource, VisualRegionSource } from './sources.js';import type { HistoryEntry, Outcome, TaskSources } from './tasks.js';@@ -37,7 +38,7 @@ const REOBSERVE_TIMEOUT_MS = 5_000;type Arguments = {task: string;- provider: 'mock' | 'live';+ provider: 'mock' | 'live' | 's1';pid: number;stateFile: string;noteText?: string;@@ -69,7 +70,9 @@ export function parseArgs(argv: string[]): Arguments {if (!result.task || !NATIVE_TASK_IDS.includes(result.task)) {throw new Error(`--task must be one of ${NATIVE_TASK_IDS.join(', ')}`);}- if (result.provider !== 'mock' && result.provider !== 'live') throw new Error('--provider must be mock or live');+ if (result.provider !== 'mock' && result.provider !== 'live' && result.provider !== 's1') {+ throw new Error('--provider must be mock, live, or s1');+ }if (!Number.isInteger(result.pid) || (result.pid as number) <= 0) throw new Error('--pid is required');if (!result.stateFile) throw new Error('--state-file is required');if (result.platform && !['macos', 'windows', 'linux'].includes(result.platform)) {@@ -264,7 +267,9 @@ export async function runTask(args: Arguments, task: NativeTask): Promise<Outcomconst decision =args.provider === 'mock'? chooseMockForTask(task, sources, plan.candidates, history)- : await chooseLive(request);+ : args.provider === 's1'+ ? await chooseS1Service(request)+ : await chooseLive(request);const baseEvent: Record<string, unknown> = {event: 'step',step,@@ -343,6 +348,8 @@ export async function runTask(args: Arguments, task: NativeTask): Promise<Outcomif (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {const args = parseArgs(process.argv.slice(2));+ // Fail before touching the app when the S1 service is not configured.+ if (args.provider === 's1') s1ServiceUrl();const task = nativeTask(args.task, args.stateFile, {pid: args.pid,noteText: args.noteText,diff --git a/libs/cua-driver/examples/jev-use/typescript/s1_service.test.ts b/libs/cua-driver/examples/jev-use/typescript/s1_service.test.tsnew file mode 100644index 0000000000..e1282d234b--- /dev/null+++ b/libs/cua-driver/examples/jev-use/typescript/s1_service.test.ts@@ -0,0 +1,125 @@+import assert from 'node:assert/strict';+import { createServer, type Server } from 'node:http';+import type { AddressInfo } from 'node:net';+import test from 'node:test';++import { parseArgs } from './run_native.js';+import { chooseS1Service, S1ServiceError, s1ServiceUrl, validateDecision } from './s1_service.js';++const REQUEST = {+ schema: 'cua.jev_choice_request_v2',+ goal: 'Set the counter to 3.',+ capture_id: 'cap-1',+ regions: [],+ history: [],+ candidates: [+ { id: 'ax:button:increment', description: 'Click Increment', source: 'ax' },+ { id: 'reobserve', description: 'Observe again' },+ { id: 'abstain', description: 'Stop' },+ ],+};++function decision(overrides: Record<string, unknown> = {}): Record<string, unknown> {+ return {+ schema: 'cua.decision_choice_v1',+ kind: 'selected',+ capture_id: 'cap-1',+ selected_id: 'ax:button:increment',+ model: 'cua-s1-4b-0.2',+ confidence: 0.9,+ probabilities: { 'ax:button:increment': 0.9, reobserve: 0.06, abstain: 0.04 },+ reason: null,+ ...overrides,+ };+}++async function serve(status: number, body: string, received: unknown[]): Promise<{ server: Server; url: string }> {+ const server = createServer((request, response) => {+ let data = '';+ request.on('data', (chunk) => { data += chunk; });+ request.on('end', () => {+ received.push(JSON.parse(data));+ response.writeHead(status, { 'Content-Type': 'application/json' });+ response.end(body);+ });+ });+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));+ const { port } = server.address() as AddressInfo;+ return { server, url: `http://127.0.0.1:${port}/decide` };+}++test('s1ServiceUrl accepts only loopback http', () => {+ for (const url of ['http://127.0.0.1:8791/decide', 'http://localhost:8791/decide', 'http://[::1]:8791/decide']) {+ assert.equal(s1ServiceUrl(url), url);+ }+ for (const url of [+ 'http://10.0.0.5:8791/decide',+ 'http://example.com/decide',+ 'https://127.0.0.1:8791/decide',+ 'http://user:[email protected]:8791/decide',+ '',+ ]) {+ assert.throws(() => s1ServiceUrl(url), S1ServiceError, url);+ }+});++test('validateDecision accepts selected, reobserve, and abstain', () => {+ assert.equal(validateDecision(decision(), REQUEST).selected_id, 'ax:button:increment');+ for (const choice of ['reobserve', 'abstain']) {+ const probabilities = { 'ax:button:increment': 0.1, reobserve: 0.1, abstain: 0.1, [choice]: 0.8 };+ assert.equal(+ validateDecision(decision({ kind: choice, selected_id: choice, confidence: 0.8, probabilities }), REQUEST).kind,+ choice,+ );+ }+});++test('validateDecision rejects malformed decisions', () => {+ const bad: unknown[] = [+ decision({ schema: 'cua.decision_choice_v0' }),+ decision({ kind: 'act' }),+ decision({ capture_id: 'cap-2' }),+ decision({ kind: 'error', selected_id: null, reason: 'model_error' }),+ decision({ selected_id: 'ax:button:reset' }),+ decision({ kind: 'reobserve' }),+ decision({ probabilities: { 'ax:button:increment': 1 } }),+ decision({ probabilities: { 'ax:button:increment': 1.5, reobserve: 0, abstain: 0 } }),+ decision({ confidence: Number.NaN }),+ decision({ confidence: true }),+ [],+ ];+ for (const value of bad) assert.throws(() => validateDecision(value, REQUEST), S1ServiceError);+});++test('chooseS1Service posts the request and returns the choice', async () => {+ const received: unknown[] = [];+ const { server, url } = await serve(200, JSON.stringify(decision()), received);+ try {+ const result = await chooseS1Service(REQUEST, url);+ assert.deepEqual(received, [REQUEST]);+ assert.equal(result.choice, 'ax:button:increment');+ assert.equal(result.confidence, 0.9);+ assert.deepEqual(Object.keys(result.probabilities).sort(), ['abstain', 'ax:button:increment', 'reobserve']);+ } finally {+ server.close();+ }+});++test('chooseS1Service rejects HTTP errors, invalid JSON, and an unreachable service', async () => {+ for (const [status, body] of [[400, '{"error":"invalid_request"}'], [200, 'not json']] as const) {+ const { server, url } = await serve(status, body, []);+ try {+ await assert.rejects(chooseS1Service(REQUEST, url), S1ServiceError);+ } finally {+ server.close();+ }+ }+ const { server, url } = await serve(200, '{}', []);+ await new Promise<void>((resolve) => server.close(() => resolve()));+ await assert.rejects(chooseS1Service(REQUEST, url, 2_000), S1ServiceError);+});++test('the native runner accepts the s1 provider', () => {+ const args = parseArgs(['--task', 'appkit-counter', '--provider', 's1', '--pid', '1', '--state-file', 's']);+ assert.equal(args.provider, 's1');+});diff --git a/libs/cua-driver/examples/jev-use/typescript/s1_service.ts b/libs/cua-driver/examples/jev-use/typescript/s1_service.tsnew file mode 100644index 0000000000..d567da90e8--- /dev/null+++ b/libs/cua-driver/examples/jev-use/typescript/s1_service.ts@@ -0,0 +1,122 @@+/**+ * Choose one supplied candidate through a warm, loopback S1 decision service.+ *+ * Mirrors python/s1_service.py. `CUA_S1_DECISION_URL` names the decide+ * endpoint (for example `http://127.0.0.1:8791/decide`). The service receives+ * the validated `cua.jev_choice_request_v1` or `_v2` request and returns one+ * `cua.decision_choice_v1` response, which is checked strictly here before the+ * runner resolves the selected ID to its own immutable candidate.+ */+import { isIP } from 'node:net';++import { validateRequest } from './choose_action.js';++export const DECISION_SCHEMA = 'cua.decision_choice_v1';+export const URL_ENV = 'CUA_S1_DECISION_URL';+const DECISION_KINDS = new Set(['selected', 'reobserve', 'abstain', 'error']);+const DEFAULT_TIMEOUT_MS = 30_000;+const MAX_RESPONSE_BYTES = 256 * 1024;++export class S1ServiceError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'S1ServiceError';+ }+}++type RequestLike = { capture_id?: unknown; candidates: Array<{ id: string }> };+export type S1Choice = { choice: string | null; confidence: number; probabilities: Record<string, number> };++function isLoopback(host: string): boolean {+ const bare = host.replace(/^\[|\]$/g, '');+ if (bare === 'localhost') return true;+ if (isIP(bare) === 4) return bare.split('.')[0] === '127';+ if (isIP(bare) === 6) return bare === '::1' || /^(0{0,4}:){7}0{0,3}1$/.test(bare);+ return false;+}++/** Return the configured decide URL; it must be plain HTTP on loopback. */+export function s1ServiceUrl(value?: string): string {+ const url = (value ?? process.env[URL_ENV] ?? '').trim();+ if (!url) throw new S1ServiceError(`${URL_ENV} is not set`);+ let parsed: URL;+ try {+ parsed = new URL(url);+ } catch {+ throw new S1ServiceError(`${URL_ENV} must be an http:// URL on the loopback interface`);+ }+ if (parsed.protocol !== 'http:' || !isLoopback(parsed.hostname) || parsed.username || parsed.password) {+ throw new S1ServiceError(`${URL_ENV} must be an http:// URL on the loopback interface`);+ }+ return url;+}++function finiteUnit(value: unknown): value is number {+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 1;+}++/** Check a `cua.decision_choice_v1` response against the request it answers. */+export function validateDecision(decision: unknown, request: RequestLike): Record<string, unknown> {+ if (typeof decision !== 'object' || decision === null || Array.isArray(decision)) {+ throw new S1ServiceError('response is not a cua.decision_choice_v1 decision');+ }+ const value = decision as Record<string, unknown>;+ if (value.schema !== DECISION_SCHEMA) throw new S1ServiceError('response is not a cua.decision_choice_v1 decision');+ const kind = value.kind;+ if (typeof kind !== 'string' || !DECISION_KINDS.has(kind)) throw new S1ServiceError('response kind is not supported');+ if (value.capture_id !== request.capture_id) throw new S1ServiceError('response capture_id does not match the request');+ if (kind === 'error') throw new S1ServiceError(`S1 decision failed: ${String(value.reason ?? 'unknown')}`);+ const ids = request.candidates.map(({ id }) => id);+ const selected = value.selected_id;+ if (typeof selected !== 'string' || !ids.includes(selected)) {+ throw new S1ServiceError('S1 selected an ID that was not supplied');+ }+ const expectedKind = selected === 'reobserve' || selected === 'abstain' ? selected : 'selected';+ if (kind !== expectedKind) throw new S1ServiceError('response kind does not match the selected ID');+ const probabilities = value.probabilities;+ if (+ typeof probabilities !== 'object' || probabilities === null || Array.isArray(probabilities)+ || Object.keys(probabilities).length !== ids.length+ || !ids.every((id) => finiteUnit((probabilities as Record<string, unknown>)[id]))+ ) {+ throw new S1ServiceError('response probabilities do not match the candidate set');+ }+ if (!finiteUnit(value.confidence)) throw new S1ServiceError('response confidence must be a finite number in [0, 1]');+ return value;+}++/** POST one validated request and return the chosen ID, confidence, and probabilities. */+export async function chooseS1Service(+ request: Record<string, unknown>,+ url?: string,+ timeoutMs: number = DEFAULT_TIMEOUT_MS,+): Promise<S1Choice> {+ const validated = validateRequest(request);+ let response: Response;+ try {+ response = await fetch(s1ServiceUrl(url), {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(request),+ signal: AbortSignal.timeout(timeoutMs),+ });+ } catch (error) {+ if (error instanceof S1ServiceError) throw error;+ throw new S1ServiceError(`S1 service is unreachable: ${(error as Error).name}`);+ }+ if (!response.ok) throw new S1ServiceError(`S1 service returned HTTP ${response.status}`);+ const text = await response.text();+ if (Buffer.byteLength(text) > MAX_RESPONSE_BYTES) throw new S1ServiceError('S1 response is too large');+ let decision: unknown;+ try {+ decision = JSON.parse(text);+ } catch {+ throw new S1ServiceError('S1 response is not JSON');+ }+ const value = validateDecision(decision, validated);+ return {+ choice: value.selected_id as string,+ confidence: value.confidence as number,+ probabilities: { ...(value.probabilities as Record<string, number>) },+ };+}diff --git a/libs/cua-driver/examples/jev-use/verify_native.py b/libs/cua-driver/examples/jev-use/verify_native.pyindex 8b07b26428..366541afb0 100644--- a/libs/cua-driver/examples/jev-use/verify_native.py+++ b/libs/cua-driver/examples/jev-use/verify_native.py@@ -195,6 +195,10 @@ def main() -> None:parser.add_argument("--app", type=Path, help="harness app or executable (default: the fixture build output)")parser.add_argument("--typescript", action="store_true", help="also verify the TypeScript runner")parser.add_argument("--live", action="store_true", help="also verify live Jev; needs a TypeSafe key")+ parser.add_argument(+ "--s1", action="store_true",+ help="also verify Cua-S1 through the loopback decision service named by CUA_S1_DECISION_URL",+ )parser.add_argument("--task", action="append", choices=sorted(EXPECTED), help="limit to task kinds")parser.add_argument("--capture-dir", type=Path, help="also record sanitized window-state fixtures")parser.add_argument("--output-dir", type=Path, required=True, help="new evidence directory")@@ -203,6 +207,14 @@ def main() -> None:if not sys.stdin.isatty():raise SystemExit("Human prerequisite: provision TYPESAFE_API_KEY before a live run")os.environ["TYPESAFE_API_KEY"] = getpass.getpass("TypeSafe API key: ").strip()+ if args.s1:+ sys.path.insert(0, str(BASE / "python"))+ from s1_service import S1ServiceError, s1_service_url++ try:+ s1_service_url()+ except S1ServiceError as error:+ raise SystemExit(f"Prerequisite: {error}; start the S1 decision service first") from Noneoutput = args.output_dir.resolve()output.mkdir(mode=0o700, parents=True, exist_ok=False)app = args.app or HARNESSES[args.harness].app@@ -213,13 +225,15 @@ def main() -> None:"complete": False,"harness": args.harness,"live_requested": args.live,+ "s1_requested": args.s1,"typescript_requested": args.typescript,"checks": [],}try:with tempfile.TemporaryDirectory(prefix="jev-native-") as work:for language in ["python", "typescript"] if args.typescript else ["python"]:- for provider in ["mock", "live"] if args.live else ["mock"]:+ providers = ["mock"] + (["live"] if args.live else []) + (["s1"] if args.s1 else [])+ for provider in providers:for kind in args.task or sorted(EXPECTED):result = verify(language, provider, args.harness, kind, app, output, Path(work), capture_dir