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): add optional visual perception extension
Francesco Bonacci681bc44807d1
diff --git a/.github/releases/README.md b/.github/releases/README.mdindex 064875f560..4d151244b1 100644--- a/.github/releases/README.md+++ b/.github/releases/README.md@@ -6,6 +6,46 @@ tag namespaces, build-time version sites, builder workflow, and change paths.It intentionally does not describe signing, packaging, or registry publishing;those remain owned by each component workflow.+## cua-perception candidates++`cua-perception` has an independent version and changelog beside its Rust crate+in `libs/cua-driver/rust/crates/cua-perception`. Keeping the Release Please root+at that crate scopes its commits without unsupported path traversal. The+`.github/releases/cua-perception` directory remains the authority for schemas,+trust, and candidate controls. Release Please may open version PRs for the+component, while `skip-github-release` keeps the stream candidate-only and does+not create GitHub releases. The workflow creates an idempotent lightweight+`cua-perception-v<semver>` git tag on the exact main commit carrying each version+so later candidate changelogs have an immutable range anchor.++The candidate workflow accepts prebuilt payloads. It does not download model+weights or compile product code. Every supplied worker, runtime, model, notice,+and source file must be declared with its exact size, SHA-256, license source,+target, and protocol version as applicable. Models and bundled source also need+complete ledgers. The workflow emits a deterministic archive, SPDX SBOM, signed+catalog, redacted provenance, and checksums as retained CI artifacts only.++Candidate catalogs use the same Ed25519 envelope consumed by Cua Driver's+extension manager: `{ "payload": <compact catalog payload>,+"signature_algorithm": "ed25519", "signature": <base64> }`. The active public+key and rotation window are recorded in `cua-perception/trust-root.json`; the+matching private key is never generated,+stored, or uploaded by this repository. Candidate jobs receive it from an+external reviewed secret as base64-encoded PKCS#8 PEM and refuse keys whose+derived public key differs from the active trust root.++Candidate evidence is artifact-scoped. A passing metadata check is not a claim+that a future hosted or Fleet distribution satisfies a source-offer obligation.+Those distribution paths need their own review of the exact archive, durable+corresponding-source location, notices, and delivery behavior before any+compliance claim is made.++Cua Driver continues to exclude Perception paths from release attribution and+change detection. Shared Cargo manifest and lockfile changes are treated as+companions only when a commit otherwise contains Perception-owned changes. The+candidate tests also reject Driver archives containing Perception binaries,+model directories, or common model-weight formats.+To add a component, add one descriptor, keep its stable prefix identical to itsRelease Please component tag, choose a unique `nightly-` prefix, declare onlyversion sites that affect built nightly artifacts, and add focused tests todiff --git a/.github/releases/component.schema.json b/.github/releases/component.schema.jsonindex cef696c9b3..c882359979 100644--- a/.github/releases/component.schema.json+++ b/.github/releases/component.schema.json@@ -54,17 +54,28 @@"items": { "$ref": "#/$defs/repositoryPath" },"uniqueItems": true},+ "changeDetectionExcludePaths": {+ "type": "array",+ "items": { "$ref": "#/$defs/repositoryPath" },+ "uniqueItems": true+ },+ "changeDetectionCompanionPaths": {+ "type": "array",+ "items": { "$ref": "#/$defs/repositoryPath" },+ "uniqueItems": true+ },"buildVersionSites": {"type": "array","minItems": 1,"items": { "$ref": "#/$defs/versionSite" }},+ "candidateOnly": { "type": "boolean" },"channels": {"type": "object","additionalProperties": false,"required": ["nightly", "registries"],"properties": {- "nightly": { "const": true },+ "nightly": { "type": "boolean" },"registries": {"type": "array","maxItems": 0diff --git a/.github/releases/components.json b/.github/releases/components.jsonindex 2894657636..1fd20b1d98 100644--- a/.github/releases/components.json+++ b/.github/releases/components.json@@ -9,6 +9,32 @@".github/workflows/nightly-component-plan.yml"],"components": {+ "cua-perception": {+ "releasePleasePath": "libs/cua-driver/rust/crates/cua-perception",+ "displayName": "Cua Perception",+ "stableTagPrefix": "cua-perception-v",+ "nightlyTagPrefix": "nightly-cua-perception-v",+ "versionAuthorityFile": "libs/cua-driver/rust/crates/cua-perception/VERSION",+ "changelog": "libs/cua-driver/rust/crates/cua-perception/CHANGELOG.md",+ "builderWorkflow": ".github/workflows/cd-cua-perception-candidate.yml",+ "changeDetectionPaths": [+ "libs/cua-driver/rust/crates/cua-perception",+ ".github/releases/cua-perception",+ ".github/scripts/perception_release.py",+ ".github/workflows/cd-cua-perception-candidate.yml"+ ],+ "buildVersionSites": [+ {+ "kind": "plain",+ "path": "libs/cua-driver/rust/crates/cua-perception/VERSION"+ }+ ],+ "candidateOnly": true,+ "channels": {+ "nightly": false,+ "registries": []+ }+ },"cua-driver-rs": {"releasePleasePath": "libs/cua-driver","displayName": "Cua Driver",@@ -23,6 +49,15 @@".github/workflows/cd-rust-cua-driver.yml",".github/workflows/nightly-cua-driver.yml"],+ "changeDetectionExcludePaths": [+ "libs/cua-driver/examples",+ "libs/cua-driver/rust/crates/cua-perception",+ "libs/cua-driver/experiments/cua-perception-inference"+ ],+ "changeDetectionCompanionPaths": [+ "libs/cua-driver/rust/Cargo.toml",+ "libs/cua-driver/rust/Cargo.lock"+ ],"buildVersionSites": [{"kind": "plain",diff --git a/.github/releases/cua-perception/artifact-manifest.schema.json b/.github/releases/cua-perception/artifact-manifest.schema.jsonnew file mode 100644index 0000000000..0b0f7fbb67--- /dev/null+++ b/.github/releases/cua-perception/artifact-manifest.schema.json@@ -0,0 +1,86 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://github.com/trycua/cua/.github/releases/cua-perception/artifact-manifest.schema.json",+ "title": "Cua Perception candidate input manifest",+ "type": "object",+ "additionalProperties": false,+ "required": ["schemaVersion", "component", "version", "driverVersion", "sourceSha", "target", "protocol", "artifacts", "modelLedger", "sourceLedger", "suppliedVerification"],+ "properties": {+ "$schema": { "type": "string" },+ "schemaVersion": { "const": 1 },+ "component": { "const": "cua-perception" },+ "version": { "$ref": "#/$defs/semver" },+ "driverVersion": { "type": "string", "minLength": 1 },+ "sourceSha": { "type": "string", "pattern": "^[0-9a-f]{40}$" },+ "target": { "$ref": "#/$defs/target" },+ "protocol": { "$ref": "#/$defs/protocol" },+ "artifacts": {+ "type": "array",+ "minItems": 1,+ "items": { "$ref": "#/$defs/artifact" }+ },+ "modelLedger": { "$ref": "#/$defs/relativePath" },+ "sourceLedger": { "$ref": "#/$defs/relativePath" },+ "suppliedVerification": {+ "type": "object",+ "additionalProperties": false,+ "required": ["health", "selfTest", "realParse"],+ "properties": {+ "health": { "$ref": "#/$defs/relativePath" },+ "selfTest": { "$ref": "#/$defs/relativePath" },+ "realParse": { "$ref": "#/$defs/relativePath" }+ }+ }+ },+ "$defs": {+ "semver": { "type": "string", "pattern": "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)$" },+ "relativePath": { "type": "string", "minLength": 1, "pattern": "^(?!/)(?!.*(?:^|/)\\.\\.(?:/|$)).+$" },+ "target": {+ "type": "object",+ "additionalProperties": false,+ "required": ["triple", "os", "arch"],+ "properties": {+ "triple": { "type": "string", "pattern": "^[a-z0-9_+.]+(?:-[a-z0-9_+.]+)+$" },+ "os": { "enum": ["linux", "macos", "windows"] },+ "arch": { "enum": ["x86_64", "aarch64", "universal"] }+ }+ },+ "protocol": {+ "type": "object",+ "additionalProperties": false,+ "required": ["name", "version"],+ "properties": {+ "name": { "const": "cua-perception-worker" },+ "version": { "type": "integer", "minimum": 1 }+ }+ },+ "license": {+ "type": "object",+ "additionalProperties": false,+ "required": ["spdx", "source"],+ "properties": {+ "spdx": { "type": "string", "minLength": 1, "pattern": "^[A-Za-z0-9.+() -]+$" },+ "source": { "type": "string", "minLength": 1 },+ "notice": { "$ref": "#/$defs/relativePath" }+ }+ },+ "artifact": {+ "type": "object",+ "additionalProperties": false,+ "required": ["kind", "name", "path", "sha256", "size", "license"],+ "properties": {+ "kind": { "enum": ["worker", "runtime", "model", "dictionary", "model-manifest", "notice", "source", "supplied-verification-report", "review-recording"] },+ "role": {+ "enum": ["icon-detect", "ocr-detect", "ocr-recognize", "ocr-dictionary", "health", "self-test", "real-parse"]+ },+ "name": { "type": "string", "pattern": "^[A-Za-z0-9][A-Za-z0-9._-]*$" },+ "path": { "$ref": "#/$defs/relativePath" },+ "sha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" },+ "size": { "type": "integer", "minimum": 1 },+ "target": { "$ref": "#/$defs/target" },+ "protocolVersion": { "type": "integer", "minimum": 1 },+ "license": { "$ref": "#/$defs/license" }+ }+ }+ }+}diff --git a/.github/releases/cua-perception/catalog-input.schema.json b/.github/releases/cua-perception/catalog-input.schema.jsonnew file mode 100644index 0000000000..48b938d49a--- /dev/null+++ b/.github/releases/cua-perception/catalog-input.schema.json@@ -0,0 +1,136 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://github.com/trycua/cua/.github/releases/cua-perception/catalog-input.schema.json",+ "title": "Cua extension-manager Ed25519 catalog payload",+ "type": "object",+ "additionalProperties": false,+ "required": [+ "schema_version",+ "catalog_version",+ "expires_unix",+ "publisher_id",+ "publisher_name",+ "key_id",+ "extension_id",+ "version",+ "target",+ "archive",+ "archive_size",+ "archive_sha256",+ "manifest_sha256",+ "license",+ "source",+ "corresponding_source_uri",+ "corresponding_source_revision",+ "provenance",+ "next_key"+ ],+ "properties": {+ "schema_version": {+ "const": 1+ },+ "catalog_version": {+ "type": "integer",+ "minimum": 1+ },+ "expires_unix": {+ "type": "integer",+ "minimum": 1+ },+ "publisher_id": {+ "const": "cua"+ },+ "publisher_name": {+ "const": "Cua"+ },+ "key_id": {+ "type": "string",+ "minLength": 1+ },+ "extension_id": {+ "const": "cua-perception"+ },+ "version": {+ "type": "string"+ },+ "target": {+ "type": "string"+ },+ "archive": {+ "type": "string",+ "pattern": "^[A-Za-z0-9._-]+\\.tar\\.gz$"+ },+ "archive_size": {+ "type": "integer",+ "minimum": 1+ },+ "archive_sha256": {+ "type": "string",+ "pattern": "^[0-9a-f]{64}$"+ },+ "manifest_sha256": {+ "type": "string",+ "pattern": "^[0-9a-f]{64}$"+ },+ "license": {+ "type": "string",+ "minLength": 1+ },+ "source": {+ "type": "string",+ "minLength": 1+ },+ "corresponding_source_uri": {+ "type": "string",+ "minLength": 1+ },+ "corresponding_source_revision": {+ "type": "string",+ "minLength": 1+ },+ "provenance": {+ "type": "string",+ "minLength": 1+ },+ "next_key": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/$defs/publisherKey"+ }+ ]+ }+ },+ "$defs": {+ "publisherKey": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "key_id",+ "public_key_base64",+ "valid_from_unix",+ "valid_until_unix"+ ],+ "properties": {+ "key_id": {+ "type": "string",+ "minLength": 1+ },+ "public_key_base64": {+ "type": "string",+ "pattern": "^[A-Za-z0-9+/]{43}=$"+ },+ "valid_from_unix": {+ "type": "integer",+ "minimum": 1+ },+ "valid_until_unix": {+ "type": "integer",+ "minimum": 1+ }+ }+ }+ }+}diff --git a/.github/releases/cua-perception/ed25519-test-vector.json b/.github/releases/cua-perception/ed25519-test-vector.jsonnew file mode 100644index 0000000000..3ab56337b2--- /dev/null+++ b/.github/releases/cua-perception/ed25519-test-vector.json@@ -0,0 +1,7 @@+{+ "source": "RFC 8032 section 7.1 test 1",+ "algorithm": "Ed25519",+ "messageHex": "",+ "publicKeyHex": "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a",+ "signatureBase64": "5VZDAMNgrHKQhuLMgG6CioSHfx645dl02HPgZSJJAVVfuIIVkKM7rMYeOXAc+bRr0lv18FlbviRlUUFDjnoQCw=="+}diff --git a/.github/releases/cua-perception/executed-verification.schema.json b/.github/releases/cua-perception/executed-verification.schema.jsonnew file mode 100644index 0000000000..fd9db88da9--- /dev/null+++ b/.github/releases/cua-perception/executed-verification.schema.json@@ -0,0 +1,36 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://github.com/trycua/cua/.github/releases/cua-perception/executed-verification.schema.json",+ "title": "Cua Perception executed candidate verification",+ "type": "object",+ "additionalProperties": false,+ "required": ["schemaVersion", "evidenceKind", "sourceSha", "target", "protocolVersion", "workerSha256", "runtimeSha256", "gates"],+ "properties": {+ "$schema": { "type": "string" },+ "schemaVersion": { "const": 1 },+ "evidenceKind": { "const": "executed" },+ "sourceSha": { "type": "string", "pattern": "^[0-9a-f]{40}$" },+ "target": { "type": "string", "minLength": 1 },+ "protocolVersion": { "type": "integer", "minimum": 1 },+ "workerSha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" },+ "runtimeSha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" },+ "gates": {+ "type": "array",+ "minItems": 4,+ "maxItems": 4,+ "items": {+ "type": "object",+ "additionalProperties": false,+ "required": ["gate", "arguments", "status", "exitCode", "stdoutSha256", "stderrSha256"],+ "properties": {+ "gate": { "enum": ["health", "self-test", "real-parse", "mismatch-rejection"] },+ "arguments": { "type": "array", "minItems": 1, "items": { "type": "string", "minLength": 1 } },+ "status": { "const": "passed" },+ "exitCode": { "const": 0 },+ "stdoutSha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" },+ "stderrSha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" }+ }+ }+ }+ }+}diff --git a/.github/releases/cua-perception/model-ledger.schema.json b/.github/releases/cua-perception/model-ledger.schema.jsonnew file mode 100644index 0000000000..a8804236fb--- /dev/null+++ b/.github/releases/cua-perception/model-ledger.schema.json@@ -0,0 +1,45 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://github.com/trycua/cua/.github/releases/cua-perception/model-ledger.schema.json",+ "title": "Cua Perception model ledger",+ "type": "object",+ "additionalProperties": false,+ "required": ["schemaVersion", "models"],+ "properties": {+ "$schema": { "type": "string" },+ "schemaVersion": { "const": 1 },+ "models": {+ "type": "array",+ "items": {+ "type": "object",+ "additionalProperties": false,+ "required": ["artifact", "artifactSha256", "origin", "revision", "license", "redistributionAllowed", "verificationStatus", "exportSource"],+ "properties": {+ "artifact": { "type": "string", "minLength": 1 },+ "artifactSha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" },+ "artifactSize": { "type": "integer", "minimum": 1 },+ "origin": { "type": "string", "minLength": 1 },+ "revision": { "type": "string", "minLength": 1 },+ "license": { "type": "string", "minLength": 1 },+ "redistributionAllowed": { "const": true },+ "verificationStatus": {+ "enum": ["release-verified", "license-review-required", "conversion-review-required"]+ },+ "exportSource": { "type": "string", "minLength": 1 },+ "sourceArtifact": {+ "type": "object",+ "additionalProperties": false,+ "required": ["artifact", "path", "sha256", "size"],+ "properties": {+ "artifact": { "type": "string", "minLength": 1 },+ "path": { "type": "string", "minLength": 1 },+ "sha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" },+ "size": { "type": "integer", "minimum": 1 }+ }+ },+ "usageRestrictions": { "type": "array", "items": { "type": "string" } }+ }+ }+ }+ }+}diff --git a/.github/releases/cua-perception/model-ledger.template.json b/.github/releases/cua-perception/model-ledger.template.jsonnew file mode 100644index 0000000000..6d5f7f05b9--- /dev/null+++ b/.github/releases/cua-perception/model-ledger.template.json@@ -0,0 +1,44 @@+{+ "$schema": "./model-ledger.schema.json",+ "schemaVersion": 1,+ "models": [+ {+ "artifact": "omniparser-icon-detect-fixed-1280-opset17.onnx",+ "artifactSha256": "d8a876bf7f9fb73d7da9432904ade7fa78e092e9a91674e5a2806b45562a9ab2",+ "artifactSize": 80933219,+ "origin": "Hugging Face repository microsoft/OmniParser-v2.0",+ "revision": "6600256cb0f1b07651e3bc86166196307bad7e2d",+ "license": "AGPL-3.0-only",+ "redistributionAllowed": true,+ "verificationStatus": "license-review-required",+ "exportSource": "models/conversion-recipe.json and models/export_omniparser_detector.py in the Cua source archive, with principal exporter sources listed in source-ledger.json",+ "sourceArtifact": {+ "artifact": "omniparser-icon-detect-model.pt",+ "path": "source/upstream/omniparser-icon-detect-model.pt",+ "sha256": "dab3d4351ad00b035db829909a4db98354d5a90f6990e4ac00222a9a95d4bf57",+ "size": 40623819+ },+ "usageRestrictions": ["Do not publish until AGPL release review is complete"]+ },+ {+ "artifact": "pp-ocrv5-mobile-det.onnx",+ "artifactSha256": "a431985659dc921974177a95adcfbb90fd9e51989a5e04d70d0b75f597b6e61d",+ "origin": "Hugging Face repository PaddlePaddle/PP-OCRv5_mobile_det",+ "revision": "e6f4fa85f00e168c862bc462aebca69eef9b3d3d",+ "license": "Apache-2.0",+ "redistributionAllowed": true,+ "verificationStatus": "release-verified",+ "exportSource": "Pinned conversion recipe and exporter source must be bundled in the source ledger"+ },+ {+ "artifact": "pp-ocrv5-mobile-rec-en.onnx",+ "artifactSha256": "b5f833dfc5d0eb71da397b4efa06ebeee9b431b690a47d6af40d77d8eabc557f",+ "origin": "Hugging Face repository PaddlePaddle/PP-OCRv5_mobile_rec",+ "revision": "3fafbc3b5dcf93dd72add9f48368be8a3a2cd33b",+ "license": "Apache-2.0",+ "redistributionAllowed": true,+ "verificationStatus": "release-verified",+ "exportSource": "Pinned conversion recipe and exporter source must be bundled in the source ledger"+ }+ ]+}diff --git a/.github/releases/cua-perception/platform-inputs.json b/.github/releases/cua-perception/platform-inputs.jsonnew file mode 100644index 0000000000..9baca97d91--- /dev/null+++ b/.github/releases/cua-perception/platform-inputs.json@@ -0,0 +1,8 @@+{+ "schemaVersion": 1,+ "platforms": [+ { "os": "linux", "arch": "x86_64", "triple": "x86_64-unknown-linux-gnu", "runner": "ubuntu-latest", "bundleArtifact": "cua-perception-input-linux-x86_64", "worker": "cua-perception", "runtime": "libonnxruntime.so", "modelManifest": "model-manifest.json" },+ { "os": "macos", "arch": "aarch64", "triple": "aarch64-apple-darwin", "runner": "macos-15", "bundleArtifact": "cua-perception-input-macos-aarch64", "worker": "cua-perception", "runtime": "libonnxruntime.dylib", "modelManifest": "model-manifest.json" },+ { "os": "windows", "arch": "x86_64", "triple": "x86_64-pc-windows-msvc", "runner": "windows-latest", "bundleArtifact": "cua-perception-input-windows-x86_64", "worker": "cua-perception.exe", "runtime": "onnxruntime.dll", "modelManifest": "model-manifest.json" }+ ]+}diff --git a/.github/releases/cua-perception/platform-inputs.schema.json b/.github/releases/cua-perception/platform-inputs.schema.jsonnew file mode 100644index 0000000000..bf3f77e5c7--- /dev/null+++ b/.github/releases/cua-perception/platform-inputs.schema.json@@ -0,0 +1,48 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://github.com/trycua/cua/.github/releases/cua-perception/platform-inputs.schema.json",+ "type": "object",+ "additionalProperties": false,+ "required": ["schemaVersion", "platforms"],+ "properties": {+ "schemaVersion": { "const": 1 },+ "platforms": {+ "type": "array",+ "minItems": 3,+ "maxItems": 3,+ "items": {+ "type": "object",+ "additionalProperties": false,+ "allOf": [+ {+ "if": {+ "properties": { "os": { "const": "macos" } },+ "required": ["os"]+ },+ "then": {+ "properties": {+ "arch": { "const": "aarch64" },+ "triple": { "const": "aarch64-apple-darwin" },+ "runner": { "const": "macos-15" }+ }+ },+ "else": {+ "properties": { "arch": { "const": "x86_64" } }+ }+ }+ ],+ "required": ["os", "arch", "triple", "runner", "bundleArtifact", "worker", "runtime", "modelManifest"],+ "properties": {+ "os": { "enum": ["linux", "macos", "windows"] },+ "arch": { "enum": ["aarch64", "x86_64"] },+ "triple": { "type": "string", "minLength": 1 },+ "runner": { "type": "string", "minLength": 1 },+ "bundleArtifact": { "type": "string", "pattern": "^cua-perception-input-[A-Za-z0-9_-]+$" },+ "worker": { "type": "string", "minLength": 1 },+ "runtime": { "type": "string", "pattern": "^(libonnxruntime\\.(so|dylib)|onnxruntime\\.dll)$" },+ "modelManifest": { "const": "model-manifest.json" }+ }+ }+ }+ }+}diff --git a/.github/releases/cua-perception/provenance.schema.json b/.github/releases/cua-perception/provenance.schema.jsonnew file mode 100644index 0000000000..75465394d9--- /dev/null+++ b/.github/releases/cua-perception/provenance.schema.json@@ -0,0 +1,29 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://github.com/trycua/cua/.github/releases/cua-perception/provenance.schema.json",+ "title": "Cua Perception redacted candidate provenance",+ "type": "object",+ "additionalProperties": false,+ "required": ["schemaVersion", "component", "candidate", "releaseStatus", "source", "build", "evidence", "subjects", "redactions"],+ "properties": {+ "$schema": { "type": "string" },+ "schemaVersion": { "const": 1 },+ "component": { "const": "cua-perception" },+ "candidate": { "const": true },+ "releaseStatus": { "const": "staging-candidate" },+ "source": { "type": "object", "required": ["repository", "commit"] },+ "build": { "type": "object", "required": ["workflow", "runId", "target"] },+ "evidence": {+ "type": "object",+ "additionalProperties": false,+ "required": ["supplied", "executed", "executedSha256"],+ "properties": {+ "supplied": { "type": "array", "minItems": 3, "maxItems": 3, "items": { "type": "string", "minLength": 1 } },+ "executed": { "const": "metadata/executed-verification.json" },+ "executedSha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" }+ }+ },+ "subjects": { "type": "array", "minItems": 1 },+ "redactions": { "type": "array", "contains": { "const": "absolutePaths" } }+ }+}diff --git a/.github/releases/cua-perception/release-input.template.json b/.github/releases/cua-perception/release-input.template.jsonnew file mode 100644index 0000000000..096982ef13--- /dev/null+++ b/.github/releases/cua-perception/release-input.template.json@@ -0,0 +1,45 @@+{+ "$schema": "./artifact-manifest.schema.json",+ "schemaVersion": 1,+ "component": "cua-perception",+ "version": "0.1.0",+ "driverVersion": ">=0.28.2",+ "sourceSha": "0000000000000000000000000000000000000000",+ "target": { "triple": "x86_64-unknown-linux-gnu", "os": "linux", "arch": "x86_64" },+ "protocol": { "name": "cua-perception-worker", "version": 1 },+ "artifacts": [+ {+ "kind": "worker",+ "name": "cua-perception-worker",+ "path": "payload/cua-perception-worker",+ "sha256": "0000000000000000000000000000000000000000000000000000000000000000",+ "size": 1,+ "target": { "triple": "x86_64-unknown-linux-gnu", "os": "linux", "arch": "x86_64" },+ "protocolVersion": 1,+ "license": { "spdx": "Apache-2.0", "source": "https://github.com/trycua/cua", "notice": "payload/NOTICE" }+ },+ {+ "kind": "notice",+ "name": "NOTICE",+ "path": "payload/NOTICE",+ "sha256": "0000000000000000000000000000000000000000000000000000000000000000",+ "size": 1,+ "license": { "spdx": "Apache-2.0", "source": "https://github.com/trycua/cua" }+ },+ {+ "kind": "model-manifest",+ "name": "model-manifest.json",+ "path": "payload/model-manifest.json",+ "sha256": "0000000000000000000000000000000000000000000000000000000000000000",+ "size": 1,+ "license": { "spdx": "Apache-2.0", "source": "https://github.com/trycua/cua", "notice": "payload/NOTICE" }+ }+ ],+ "modelLedger": "model-ledger.json",+ "sourceLedger": "source-ledger.json",+ "suppliedVerification": {+ "health": "verification/health.json",+ "selfTest": "verification/self-test.json",+ "realParse": "verification/real-parse.json"+ }+}diff --git a/.github/releases/cua-perception/runtime-contract.schema.json b/.github/releases/cua-perception/runtime-contract.schema.jsonnew file mode 100644index 0000000000..f132516ac6--- /dev/null+++ b/.github/releases/cua-perception/runtime-contract.schema.json@@ -0,0 +1,32 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://github.com/trycua/cua/.github/releases/cua-perception/runtime-contract.schema.json",+ "title": "Cua Perception runtime binding contract",+ "type": "object",+ "additionalProperties": false,+ "required": ["schemaVersion", "target", "protocolVersion", "worker", "runtime", "modelManifest", "models", "dictionary", "rejectMismatch"],+ "properties": {+ "$schema": { "type": "string" },+ "schemaVersion": { "const": 1 },+ "target": { "type": "string", "minLength": 1 },+ "protocolVersion": { "type": "integer", "minimum": 1 },+ "worker": { "$ref": "#/$defs/binding" },+ "runtime": { "$ref": "#/$defs/binding" },+ "modelManifest": { "$ref": "#/$defs/binding" },+ "models": { "type": "array", "minItems": 3, "maxItems": 3, "items": { "$ref": "#/$defs/binding" } },+ "dictionary": { "$ref": "#/$defs/binding" },+ "rejectMismatch": { "const": true }+ },+ "$defs": {+ "binding": {+ "type": "object",+ "additionalProperties": false,+ "required": ["name", "sha256"],+ "properties": {+ "name": { "type": "string", "minLength": 1 },+ "role": { "type": "string" },+ "sha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" }+ }+ }+ }+}diff --git a/.github/releases/cua-perception/sbom.schema.json b/.github/releases/cua-perception/sbom.schema.jsonnew file mode 100644index 0000000000..fdd3a9ea50--- /dev/null+++ b/.github/releases/cua-perception/sbom.schema.json@@ -0,0 +1,15 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://github.com/trycua/cua/.github/releases/cua-perception/sbom.schema.json",+ "title": "Cua Perception candidate SPDX SBOM",+ "type": "object",+ "required": ["spdxVersion", "dataLicense", "SPDXID", "name", "documentNamespace", "packages", "files", "relationships"],+ "properties": {+ "spdxVersion": { "const": "SPDX-2.3" },+ "dataLicense": { "const": "CC0-1.0" },+ "SPDXID": { "const": "SPDXRef-DOCUMENT" },+ "packages": { "type": "array", "minItems": 1 },+ "files": { "type": "array", "minItems": 1 },+ "relationships": { "type": "array", "minItems": 1 }+ }+}diff --git a/.github/releases/cua-perception/signed-catalog.schema.json b/.github/releases/cua-perception/signed-catalog.schema.jsonnew file mode 100644index 0000000000..7c676fbd63--- /dev/null+++ b/.github/releases/cua-perception/signed-catalog.schema.json@@ -0,0 +1,13 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://github.com/trycua/cua/.github/releases/cua-perception/signed-catalog.schema.json",+ "title": "Cua extension-manager signed catalog",+ "type": "object",+ "additionalProperties": false,+ "required": ["payload", "signature_algorithm", "signature"],+ "properties": {+ "payload": { "$ref": "./catalog-input.schema.json" },+ "signature_algorithm": { "const": "ed25519" },+ "signature": { "type": "string", "pattern": "^[A-Za-z0-9+/]{86}==$" }+ }+}diff --git a/.github/releases/cua-perception/source-ledger.schema.json b/.github/releases/cua-perception/source-ledger.schema.jsonnew file mode 100644index 0000000000..b510e4ea06--- /dev/null+++ b/.github/releases/cua-perception/source-ledger.schema.json@@ -0,0 +1,34 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://github.com/trycua/cua/.github/releases/cua-perception/source-ledger.schema.json",+ "title": "Cua Perception bundled-source ledger",+ "type": "object",+ "additionalProperties": false,+ "required": ["schemaVersion", "sources"],+ "properties": {+ "$schema": { "type": "string" },+ "schemaVersion": { "const": 1 },+ "sources": {+ "type": "array",+ "items": {+ "type": "object",+ "additionalProperties": false,+ "required": ["artifact", "artifactSha256", "artifactSize", "repository", "revision", "license", "durableLocation", "sourceOfferStatus", "contentKind", "format"],+ "properties": {+ "artifact": { "type": "string", "minLength": 1 },+ "artifactSha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" },+ "artifactSize": { "type": "integer", "minimum": 1 },+ "repository": { "type": "string", "minLength": 1 },+ "revision": { "type": "string", "minLength": 1 },+ "license": { "type": "string", "minLength": 1 },+ "durableLocation": { "type": "string", "minLength": 1 },+ "sourceOfferStatus": { "enum": ["bundled", "bundled-review-only", "external-review-required"] },+ "contentKind": { "enum": ["cua-source", "model-source-input", "exporter-source"] },+ "format": { "enum": ["file", "tar.gz"] },+ "requiredPaths": { "type": "array", "items": { "type": "string", "minLength": 1 } },+ "patches": { "type": "array", "items": { "type": "string" } }+ }+ }+ }+ }+}diff --git a/.github/releases/cua-perception/source-ledger.template.json b/.github/releases/cua-perception/source-ledger.template.jsonnew file mode 100644index 0000000000..762e9d624b--- /dev/null+++ b/.github/releases/cua-perception/source-ledger.template.json@@ -0,0 +1,107 @@+{+ "$schema": "./source-ledger.schema.json",+ "schemaVersion": 1,+ "sources": [+ {+ "artifact": "cua-perception-source.tar.gz",+ "artifactSha256": "0000000000000000000000000000000000000000000000000000000000000000",+ "artifactSize": 1,+ "repository": "https://github.com/trycua/cua",+ "revision": "0000000000000000000000000000000000000000",+ "license": "MIT",+ "durableLocation": "Candidate archive source/cua-perception-source.tar.gz",+ "sourceOfferStatus": "bundled-review-only",+ "contentKind": "cua-source",+ "format": "tar.gz",+ "requiredPaths": [+ "libs/cua-driver/rust/crates/cua-perception/models/conversion-recipe.json",+ "libs/cua-driver/rust/crates/cua-perception/models/export_omniparser_detector.py",+ "libs/cua-driver/rust/crates/cua-perception/scripts/artifacts.lock.json"+ ],+ "patches": []+ },+ {+ "artifact": "omniparser-icon-detect-model.pt",+ "artifactSha256": "dab3d4351ad00b035db829909a4db98354d5a90f6990e4ac00222a9a95d4bf57",+ "artifactSize": 40623819,+ "repository": "https://huggingface.co/microsoft/OmniParser-v2.0",+ "revision": "6600256cb0f1b07651e3bc86166196307bad7e2d",+ "license": "AGPL-3.0-only",+ "durableLocation": "Candidate archive source/upstream/omniparser-icon-detect-model.pt",+ "sourceOfferStatus": "bundled-review-only",+ "contentKind": "model-source-input",+ "format": "file",+ "patches": []+ },+ {+ "artifact": "ultralytics-8f7fe171f0db13e5c2eff55eee3443f8903e5068.tar.gz",+ "artifactSha256": "6c289215a5ce593a872111b87e58ffff6949d235c2af720e8f01704375f7bf44",+ "artifactSize": 1872606,+ "repository": "https://github.com/ultralytics/ultralytics",+ "revision": "8f7fe171f0db13e5c2eff55eee3443f8903e5068",+ "license": "AGPL-3.0-only",+ "durableLocation": "Candidate archive source/exporter/ultralytics-8f7fe171f0db13e5c2eff55eee3443f8903e5068.tar.gz",+ "sourceOfferStatus": "bundled-review-only",+ "contentKind": "exporter-source",+ "format": "tar.gz",+ "requiredPaths": ["ultralytics/engine/exporter.py", "pyproject.toml"],+ "patches": []+ },+ {+ "artifact": "pytorch-ba56102387ef21a3b04b357e5b183d48f0afefc7.tar.gz",+ "artifactSha256": "a9623012b046e9cc87c919f178782860bcee9fbf014ad5c24a2655b517d0881b",+ "artifactSize": 56595340,+ "repository": "https://github.com/pytorch/pytorch",+ "revision": "ba56102387ef21a3b04b357e5b183d48f0afefc7",+ "license": "BSD-3-Clause",+ "durableLocation": "Candidate archive source/exporter/pytorch-ba56102387ef21a3b04b357e5b183d48f0afefc7.tar.gz",+ "sourceOfferStatus": "bundled-review-only",+ "contentKind": "exporter-source",+ "format": "tar.gz",+ "requiredPaths": ["torch/onnx", "torch/_dynamo", "setup.py"],+ "patches": []+ },+ {+ "artifact": "torchvision-824e8c8726b65fd9d5abdc9702f81c2b0c4c0dc8.tar.gz",+ "artifactSha256": "8e44b7705c901b9af76113393fe675b02ceeb43b1c688db50e0d8ff8a9dcef03",+ "artifactSize": 14499056,+ "repository": "https://github.com/pytorch/vision",+ "revision": "824e8c8726b65fd9d5abdc9702f81c2b0c4c0dc8",+ "license": "BSD-3-Clause",+ "durableLocation": "Candidate archive source/exporter/torchvision-824e8c8726b65fd9d5abdc9702f81c2b0c4c0dc8.tar.gz",+ "sourceOfferStatus": "bundled-review-only",+ "contentKind": "exporter-source",+ "format": "tar.gz",+ "requiredPaths": ["torchvision", "setup.py"],+ "patches": []+ },+ {+ "artifact": "onnx-57b9c6a4f6eebb09ae1b34cfb632078518f72832.tar.gz",+ "artifactSha256": "a1a9c44e20ea1f9cf0c094e0f82001113b36e0867e04c06966475c46e3c75739",+ "artifactSize": 13109973,+ "repository": "https://github.com/onnx/onnx",+ "revision": "57b9c6a4f6eebb09ae1b34cfb632078518f72832",+ "license": "Apache-2.0",+ "durableLocation": "Candidate archive source/exporter/onnx-57b9c6a4f6eebb09ae1b34cfb632078518f72832.tar.gz",+ "sourceOfferStatus": "bundled-review-only",+ "contentKind": "exporter-source",+ "format": "tar.gz",+ "requiredPaths": ["onnx", "pyproject.toml"],+ "patches": []+ },+ {+ "artifact": "onnxslim-0.1.68.tar.gz",+ "artifactSha256": "ff1ec2bf61ff10b75e33990b2046c446dec522ba7f0a12b2f984547ff43f9138",+ "artifactSize": 141502,+ "repository": "https://github.com/inisis/OnnxSlim",+ "revision": "0.1.68",+ "license": "Apache-2.0",+ "durableLocation": "Candidate archive source/exporter/onnxslim-0.1.68.tar.gz",+ "sourceOfferStatus": "bundled-review-only",+ "contentKind": "exporter-source",+ "format": "tar.gz",+ "requiredPaths": ["onnxslim", "VERSION"],+ "patches": []+ }+ ]+}diff --git a/.github/releases/cua-perception/test-requirements.in b/.github/releases/cua-perception/test-requirements.innew file mode 100644index 0000000000..33796f0f3f--- /dev/null+++ b/.github/releases/cua-perception/test-requirements.in@@ -0,0 +1,4 @@+cryptography==46.0.7+jsonschema==4.23.0+pytest==8.3.5+pyyaml==6.0.2diff --git a/.github/releases/cua-perception/test-requirements.lock b/.github/releases/cua-perception/test-requirements.locknew file mode 100644index 0000000000..c650d3c159--- /dev/null+++ b/.github/releases/cua-perception/test-requirements.lock@@ -0,0 +1,378 @@+# This file was autogenerated by uv via the following command:+# uv pip compile --config-file /dev/null --python-version 3.11 --universal .github/releases/cua-perception/test-requirements.in --generate-hashes --output-file .github/releases/cua-perception/test-requirements.lock+attrs==26.1.0 \+ --hash=sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309 \+ --hash=sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32+ # via+ # jsonschema+ # referencing+cffi==2.1.1 ; platform_python_implementation != 'PyPy' \+ --hash=sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e \+ --hash=sha256:06c72bb76605a4b0cd0aad6930b69d4baf7dd5d806cfc409b824191099700e66 \+ --hash=sha256:0beceaabe56af686895136a2de78db54ecd8e4046b236b8fd6d6cb61389e9bf2 \+ --hash=sha256:154852545011f779917b11c78db2358d095da62a9a172b78ad0a583ee5adc0d0 \+ --hash=sha256:194cffa889098ced9976c3fc6340305e43f6303657d298da55366907c05c22d6 \+ --hash=sha256:19ee6127ee34de7d83ce3d371ebc5ed91addbdcc39f9ab15ce4eb35a4e534971 \+ --hash=sha256:1a18a57b58cfb21fc28d72e876acf10eaed67a1ed96226f92af4df681d571c4c \+ --hash=sha256:1aa5645c30469b09530c4ebca77ebf8f17618293c58f8549cb1a543a50236e7d \+ --hash=sha256:1dea0e4d7d4f11f619fe8c1d76caf49e24405b4b5743c0e3be16a500ecd930c9 \+ --hash=sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517 \+ --hash=sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735 \+ --hash=sha256:246fa40ce8645a614ff682e0b70f37134e460eaf93a775e0cbe3cca585a67a80 \+ --hash=sha256:25792eac27877609e7bb06d42ff88278a6624fff2ba9bbb523c09616b117e80f \+ --hash=sha256:27350daa11d4f10c540e6e89dada4c54feb7256ad03e9a4dc075ebad7ba360d1 \+ --hash=sha256:28907ab9bfb6aa13184cfc17c6b8e1023c5ab6fd7076d8c20a35e59fe04f8f29 \+ --hash=sha256:2ae64be792b8966f2c69538199728b290e34726562896df1e5dc8ffd8d8188e8 \+ --hash=sha256:31348097ff5bbe827ccc41795d4dd099d9f0625e7def00ee653c137a490c2a6c \+ --hash=sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e \+ --hash=sha256:3222ba5d678f80a030e6afbcc33dc1ae5cb45facabb61cee2c7016b8432fde48 \+ --hash=sha256:3311ed60d36f83378794e1009ac6258bafbf81f7888b4caa7b35a521e3f95813 \+ --hash=sha256:334644fbac4eff73d985a17a91226df55d0f394160c4cfb880e084c8f7161cac \+ --hash=sha256:34e261f78cb6ceaaa36f42f2613f4380d94d9c759a9c73c769ee6e0247364632 \+ --hash=sha256:363e05fa78e15116c3c32c210ee36884fd6b9afa6d440e47112c3bd511d64cb6 \+ --hash=sha256:398aff33cee2767e3e781d2554c54bd0dff386bb437581e0d8011fde1a942ec1 \+ --hash=sha256:3d22a20b1fb1632cc72c22f95f7b0d2961c3e1c235f245ba4c606c4771035659 \+ --hash=sha256:42a494cee34437f05546455144f2b5d9ac09b1face62bcfce597d2e521066688 \+ --hash=sha256:42e2f76b9455f5a9a844f770bf3e200ed3da0e15f5df3db9c31fe80b04b3d004 \+ --hash=sha256:42f6930c31dc7f50732c9ae793c2786c7b6b044195967bbdde40bb9be81c4cc0 \+ --hash=sha256:456a61fa52d579ebf9df2e9552ead5129855dbaff6c1e5a9b1bc408809bdc062 \+ --hash=sha256:471cee653ae88de62096552e6d24ccb4a5adb8c8c9f10b5054d0122c15bf2779 \+ --hash=sha256:49cbc70e6542d4ccccb936558d1064a8012541e78f821f955cff24e357776c94 \+ --hash=sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50 \+ --hash=sha256:4be96343e422f2dfcd12ab5c9f5aebe03f82f737c6bffeca6830b3875cb44aab \+ --hash=sha256:4f42141fc14250de6dde5ee7ea4432be017252d91f19c5ad043c084cea629cac \+ --hash=sha256:507a24c282e0f42f8ed737cf048572cbf580468da5555764a8331735e9c736b6 \+ --hash=sha256:51b31d1c98274844cfd7838ce00bfc27c7423a4dc00fc0772fc3331c2cc90676 \+ --hash=sha256:58acb8ab8e295e6c5ea12f888cbb13cf21511ef2a3303a23f4325c29d17fe5c1 \+ --hash=sha256:5a59cc1c4442bc3d5c703bf720b51138d0bfc173618807c9ee2490a7541dd3d9 \+ --hash=sha256:5bb4e7ea95dcd6a014a6fef62e62467d67d8e582326443f3d68e71d6320a9fcf \+ --hash=sha256:5c58fe613dc5e5336357eff555824a314d8e43282600435c8d1cb6a7a2fedd13 \+ --hash=sha256:5e7cecbaadb83884793e05828cee59b210b24583b9c7425d0ba6a754fe22eb4e \+ --hash=sha256:616f097f2fe415bc92a247f02e11f634e1f9e9a83d327e3c915c15089c87869e \+ --hash=sha256:63bbfd5ded17c4840ac07cd8f1c21ba9d9708141f840b324f422f41b207e3973 \+ --hash=sha256:64faea20f4e2613363a1a9b9c7dd73058f3ecd00133a511e72ad7c511658f527 \+ --hash=sha256:661c298b4821edebead0c91edd2b00374d67ad7c5a1f7a91d4442633b79d6a72 \+ --hash=sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890 \+ --hash=sha256:6a8dddef476fab96d066d578fc88526767b836ab5ab21754e1d5bf3879c31c7c \+ --hash=sha256:6e192623c49c94421616a5778fba35cf0d5a8d000650c1967ef4448ee5cdd990 \+ --hash=sha256:7225e4514edb64eb6740324353e0da0711954fd8d7da4576755b1c6e09b697cd \+ --hash=sha256:75f80557d1389eddbd0de2681f6a390a0c5338c31ddaa821381c203fc3fd50d9 \+ --hash=sha256:770de9db11e84213beec501cfcaa013b019820ca881e03344dea5844f7876d94 \+ --hash=sha256:7750c6449dff7864bb9bb27ddfb0267756189201a3afc911d82b3caacd70dfc3 \+ --hash=sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80 \+ --hash=sha256:7ce713ace7c0e4520535b42b77eaa742c16dab813978064913e5a3cf82973b41 \+ --hash=sha256:7da0c5eff80f0197f3b3d1232ec5a682a9325f4ae9016a78f5f5ca35f9ced1f5 \+ --hash=sha256:7dbb61fe3a7699468030f71bbe5f8a0e326a151daa91beb11a6fc1f980c55e1c \+ --hash=sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a \+ --hash=sha256:8ef53b2de9bcb9197d31854256575d59dbac0cba72ac627bb291ef5eceb74be4 \+ --hash=sha256:937c0052c05a31ca1daf18de3158eed4dbfcb9cc107adbea227728d647be701e \+ --hash=sha256:9d2055050ea716bd38b7f7f1579c275386646b4894c155a3e2f3cd62ed41b7c6 \+ --hash=sha256:9f8d177621de5cb38ee3e731eda45d421db093ec0739f46a5594babda7987a98 \+ --hash=sha256:a2d7755bef5a12ed488f4ef1f1b69ee9191d7396083b755a5d2295f6edb4768b \+ --hash=sha256:a48d62ab9d6f4f98c983223a547af44be6ca3691074c31cecced6facd3ba2dc1 \+ --hash=sha256:a4f00aa42f75d6e4595e8866e748cc1705adc0cddfeb2ca86d0d03993d63ba03 \+ --hash=sha256:a6e721d4b0e45d5b65e87534470e67b18dcd092c83f68fba09f152b9cbc061af \+ --hash=sha256:a730a083190634c65cca36ba5f489531576ebd79bcd5c8e172130f6453127231 \+ --hash=sha256:a931079504ecc49efed7744c476a5c343a92fabf66dec2db95edb1b2fdc770e2 \+ --hash=sha256:aa9511c62d14da7aacc9b4bf51f3f697a621e83b2d6919008243c3aad168eea3 \+ --hash=sha256:ab36d55f9ed2d067327667c2fea18dda018eb628dd6347aa01dda6cf1f5d3836 \+ --hash=sha256:ad2c86c495b899d862ea0f4b42891b8713a3bd45dd4105c7fd51c2a72f39f3a5 \+ --hash=sha256:aeae0e330c9f6acd681f647d46cefd30c29f93e3392882e792e82080c9691399 \+ --hash=sha256:b0431303acaea1089ad4b3e9ce4e6518193def1118d4073ca848635ee4ea2e96 \+ --hash=sha256:b5bdfd1c873d4e093aabc0ca84c4ca6dbc4f752afb5c86f146d9742580c9da2e \+ --hash=sha256:baed1e86cc735622097354b9d1281406caf42ff42a886d29faa8e8d1630333be \+ --hash=sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf \+ --hash=sha256:c26608d2222fb1e94487e4a387d85f13eb55d5ed725cb25a0c589ac4ee60e7bc \+ --hash=sha256:c7659f22557c5a0bc4855cd635f55edec690cc008a40768527762cb9fb263455 \+ --hash=sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0 \+ --hash=sha256:c8d2c9fd1f2d16f780d15127abb050d13d1a76c03a4bd87d7e4980e45e511e12 \+ --hash=sha256:ca82be1a1d406ecfe1d25dc16cb33488e5a16bf4438c9fb590484ea29d92478b \+ --hash=sha256:cc572dace3f60ef98d7b12ff411d20f5362feb31a0439eab0085bbfd349982d7 \+ --hash=sha256:d18e5ac0f2f03f4f518d3e23db0f0cad7faa1da8620e9c09461d443bbf6e6692 \+ --hash=sha256:d28630f5854ab07ab1fd4aba756de52326c82e6be15d414b12793f1975048b54 \+ --hash=sha256:d9c275eaacd24aa73f94ffd6de08fc3f932424d8b6c376f4bed7cde376fe7bc3 \+ --hash=sha256:da0e573f9f97159390c89d9f1a9e41908b66d408cc5b58d08cf3847d844c531b \+ --hash=sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be \+ --hash=sha256:dddad92b554513a31f272570678ba307fb9f618f05e3d4a5eacafff9eae03e1d \+ --hash=sha256:df423d40ee8654634421812bc3b196da3f9bd7d32929da813f8394c4348a5358 \+ --hash=sha256:df913725b79db7bcf03448f36b7bf8815363417d5b58deecf9305e3e30f0f21a \+ --hash=sha256:e0bcb7e0f677f543555d2adff3bf19c05f66cdb4796e5ff602442ab2fe3c4ef7 \+ --hash=sha256:e2d65b31f36619cda3999b78b2aa9632e76b78448e7a56fc4240824200e7c4fc \+ --hash=sha256:e6e8cff14d6fb0be70a09c0bdc58096f501952d04624ebf867e0e56da2df8960 \+ --hash=sha256:f16c709686a78c727bbbf059f92b0bf41c6fc60deec706d2dc19f529175a6125 \+ --hash=sha256:f24fb43132a4c6b4cb4eb029492919b2db645be6808d738f244fd146c03c32cb \+ --hash=sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a \+ --hash=sha256:f5cfbc5fe74540d335175b656c725d74d90e3730c626d92575eea35029d9afaa \+ --hash=sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf \+ --hash=sha256:f8ec5e643a9a937f64e1999eb9f75d072263751912dc5cd06d3c85f8f44be7c3 \+ --hash=sha256:fb92203a88b3d3053034db775110081c49d28be6551923805e039924093761e4 \+ --hash=sha256:fcd22650c908d7b7da162bbfaab594a1227a15d1643a98c68b122ac642fa2264+ # via cryptography+colorama==0.4.6 ; sys_platform == 'win32' \+ --hash=sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44 \+ --hash=sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6+ # via pytest+cryptography==46.0.7 \+ --hash=sha256:04959522f938493042d595a736e7dbdff6eb6cc2339c11465b3ff89343b65f65 \+ --hash=sha256:128c5edfe5e5938b86b03941e94fac9ee793a94452ad1365c9fc3f4f62216832 \+ --hash=sha256:1d25aee46d0c6f1a501adcddb2d2fee4b979381346a78558ed13e50aa8a59067 \+ --hash=sha256:24402210aa54baae71d99441d15bb5a1919c195398a87b563df84468160a65de \+ --hash=sha256:258514877e15963bd43b558917bc9f54cf7cf866c38aa576ebf47a77ddbc43a4 \+ --hash=sha256:35719dc79d4730d30f1c2b6474bd6acda36ae2dfae1e3c16f2051f215df33ce0 \+ --hash=sha256:397655da831414d165029da9bc483bed2fe0e75dde6a1523ec2fe63f3c46046b \+ --hash=sha256:3986ac1dee6def53797289999eabe84798ad7817f3e97779b5061a95b0ee4968 \+ --hash=sha256:420b1e4109cc95f0e5700eed79908cef9268265c773d3a66f7af1eef53d409ef \+ --hash=sha256:42a1e5f98abb6391717978baf9f90dc28a743b7d9be7f0751a6f56a75d14065b \+ --hash=sha256:462ad5cb1c148a22b2e3bcc5ad52504dff325d17daf5df8d88c17dda1f75f2a4 \+ --hash=sha256:506c4ff91eff4f82bdac7633318a526b1d1309fc07ca76a3ad182cb5b686d6d3 \+ --hash=sha256:5ad9ef796328c5e3c4ceed237a183f5d41d21150f972455a9d926593a1dcb308 \+ --hash=sha256:5d1c02a14ceb9148cc7816249f64f623fbfee39e8c03b3650d842ad3f34d637e \+ --hash=sha256:5e51be372b26ef4ba3de3c167cd3d1022934bc838ae9eaad7e644986d2a3d163 \+ --hash=sha256:60627cf07e0d9274338521205899337c5d18249db56865f943cbe753aa96f40f \+ --hash=sha256:65814c60f8cc400c63131584e3e1fad01235edba2614b61fbfbfa954082db0ee \+ --hash=sha256:73510b83623e080a2c35c62c15298096e2a5dc8d51c3b4e1740211839d0dea77 \+ --hash=sha256:7bbc6ccf49d05ac8f7d7b5e2e2c33830d4fe2061def88210a126d130d7f71a85 \+ --hash=sha256:80406c3065e2c55d7f49a9550fe0c49b3f12e5bfff5dedb727e319e1afb9bf99 \+ --hash=sha256:84d4cced91f0f159a7ddacad249cc077e63195c36aac40b4150e7a57e84fffe7 \+ --hash=sha256:8a469028a86f12eb7d2fe97162d0634026d92a21f3ae0ac87ed1c4a447886c83 \+ --hash=sha256:91bbcb08347344f810cbe49065914fe048949648f6bd5c2519f34619142bbe85 \+ --hash=sha256:935ce7e3cfdb53e3536119a542b839bb94ec1ad081013e9ab9b7cfd478b05006 \+ --hash=sha256:9694078c5d44c157ef3162e3bf3946510b857df5a3955458381d1c7cfc143ddb \+ --hash=sha256:a1529d614f44b863a7b480c6d000fe93b59acee9c82ffa027cfadc77521a9f5e \+ --hash=sha256:abad9dac36cbf55de6eb49badd4016806b3165d396f64925bf2999bcb67837ba \+ --hash=sha256:b36a4695e29fe69215d75960b22577197aca3f7a25b9cf9d165dcfe9d80bc325 \+ --hash=sha256:b7b412817be92117ec5ed95f880defe9cf18a832e8cafacf0a22337dc1981b4d \+ --hash=sha256:c5b1ccd1239f48b7151a65bc6dd54bcfcc15e028c8ac126d3fada09db0e07ef1 \+ --hash=sha256:cbd5fb06b62bd0721e1170273d3f4d5a277044c47ca27ee257025146c34cbdd1 \+ --hash=sha256:cdf1a610ef82abb396451862739e3fc93b071c844399e15b90726ef7470eeaf2 \+ --hash=sha256:cdfbe22376065ffcf8be74dc9a909f032df19bc58a699456a21712d6e5eabfd0 \+ --hash=sha256:d02c738dacda7dc2a74d1b2b3177042009d5cab7c7079db74afc19e56ca1b455 \+ --hash=sha256:d151173275e1728cf7839aaa80c34fe550c04ddb27b34f48c232193df8db5842 \+ --hash=sha256:d23c8ca48e44ee015cd0a54aeccdf9f09004eba9fc96f38c911011d9ff1bd457 \+ --hash=sha256:d3b99c535a9de0adced13d159c5a9cf65c325601aa30f4be08afd680643e9c15 \+ --hash=sha256:d5f7520159cd9c2154eb61eb67548ca05c5774d39e9c2c4339fd793fe7d097b2 \+ --hash=sha256:db0f493b9181c7820c8134437eb8b0b4792085d37dbb24da050476ccb664e59c \+ --hash=sha256:e06acf3c99be55aa3b516397fe42f5855597f430add9c17fa46bf2e0fb34c9bb \+ --hash=sha256:e4cfd68c5f3e0bfdad0d38e023239b96a2fe84146481852dffbcca442c245aa5 \+ --hash=sha256:ea42cbe97209df307fdc3b155f1b6fa2577c0defa8f1f7d3be7d31d189108ad4 \+ --hash=sha256:ebd6daf519b9f189f85c479427bbd6e9c9037862cf8fe89ee35503bd209ed902 \+ --hash=sha256:f247c8c1a1fb45e12586afbb436ef21ff1e80670b2861a90353d9b025583d246 \+ --hash=sha256:fbfd0e5f273877695cb93baf14b185f4878128b250cc9f8e617ea0c025dfb022 \+ --hash=sha256:fc9ab8856ae6cf7c9358430e49b368f3108f050031442eaeb6b9d87e4dcf4e4f \+ --hash=sha256:fcd8eac50d9138c1d7fc53a653ba60a2bee81a505f9f8850b6b2888555a45d0e \+ --hash=sha256:fdd1736fed309b4300346f88f74cd120c27c56852c3838cab416e7a166f67298 \+ --hash=sha256:ffca7aa1d00cf7d6469b988c581598f2259e46215e0140af408966a24cf086ce+ # via -r .github/releases/cua-perception/test-requirements.in+iniconfig==2.3.0 \+ --hash=sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730 \+ --hash=sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12+ # via pytest+jsonschema==4.23.0 \+ --hash=sha256:d71497fef26351a33265337fa77ffeb82423f3ea21283cd9467bb03999266bc4 \+ --hash=sha256:fbadb6f8b144a8f8cf9f0b89ba94501d143e50411a1278633f56a7acf7fd5566+ # via -r .github/releases/cua-perception/test-requirements.in+jsonschema-specifications==2025.9.1 \+ --hash=sha256:98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe \+ --hash=sha256:b540987f239e745613c7a9176f3edb72b832a4ac465cf02712288397832b5e8d+ # via jsonschema+packaging==26.3 \+ --hash=sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79 \+ --hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c+ # via pytest+pluggy==1.6.0 \+ --hash=sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3 \+ --hash=sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746+ # via pytest+pycparser==3.0 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' \+ --hash=sha256:600f49d217304a5902ac3c37e1281c9fe94e4d0489de643a9504c5cdfdfc6b29 \+ --hash=sha256:b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992+ # via cffi+pytest==8.3.5 \+ --hash=sha256:c69214aa47deac29fad6c2a4f590b9c4a9fdb16a403176fe154b79c0b4d4d820 \+ --hash=sha256:f4efe70cc14e511565ac476b57c279e12a855b11f48f212af1080ef2263d3845+ # via -r .github/releases/cua-perception/test-requirements.in+pyyaml==6.0.2 \+ --hash=sha256:01179a4a8559ab5de078078f37e5c1a30d76bb88519906844fd7bdea1b7729ff \+ --hash=sha256:0833f8694549e586547b576dcfaba4a6b55b9e96098b36cdc7ebefe667dfed48 \+ --hash=sha256:0a9a2848a5b7feac301353437eb7d5957887edbf81d56e903999a75a3d743086 \+ --hash=sha256:0b69e4ce7a131fe56b7e4d770c67429700908fc0752af059838b1cfb41960e4e \+ --hash=sha256:0ffe8360bab4910ef1b9e87fb812d8bc0a308b0d0eef8c8f44e0254ab3b07133 \+ --hash=sha256:11d8f3dd2b9c1207dcaf2ee0bbbfd5991f571186ec9cc78427ba5bd32afae4b5 \+ --hash=sha256:17e311b6c678207928d649faa7cb0d7b4c26a0ba73d41e99c4fff6b6c3276484 \+ --hash=sha256:1e2120ef853f59c7419231f3bf4e7021f1b936f6ebd222406c3b60212205d2ee \+ --hash=sha256:1f71ea527786de97d1a0cc0eacd1defc0985dcf6b3f17bb77dcfc8c34bec4dc5 \+ --hash=sha256:23502f431948090f597378482b4812b0caae32c22213aecf3b55325e049a6c68 \+ --hash=sha256:24471b829b3bf607e04e88d79542a9d48bb037c2267d7927a874e6c205ca7e9a \+ --hash=sha256:29717114e51c84ddfba879543fb232a6ed60086602313ca38cce623c1d62cfbf \+ --hash=sha256:2e99c6826ffa974fe6e27cdb5ed0021786b03fc98e5ee3c5bfe1fd5015f42b99 \+ --hash=sha256:39693e1f8320ae4f43943590b49779ffb98acb81f788220ea932a6b6c51004d8 \+ --hash=sha256:3ad2a3decf9aaba3d29c8f537ac4b243e36bef957511b4766cb0057d32b0be85 \+ --hash=sha256:3b1fdb9dc17f5a7677423d508ab4f243a726dea51fa5e70992e59a7411c89d19 \+ --hash=sha256:41e4e3953a79407c794916fa277a82531dd93aad34e29c2a514c2c0c5fe971cc \+ --hash=sha256:43fa96a3ca0d6b1812e01ced1044a003533c47f6ee8aca31724f78e93ccc089a \+ --hash=sha256:50187695423ffe49e2deacb8cd10510bc361faac997de9efef88badc3bb9e2d1 \+ --hash=sha256:5ac9328ec4831237bec75defaf839f7d4564be1e6b25ac710bd1a96321cc8317 \+ --hash=sha256:5d225db5a45f21e78dd9358e58a98702a0302f2659a3c6cd320564b75b86f47c \+ --hash=sha256:6395c297d42274772abc367baaa79683958044e5d3835486c16da75d2a694631 \+ --hash=sha256:688ba32a1cffef67fd2e9398a2efebaea461578b0923624778664cc1c914db5d \+ --hash=sha256:68ccc6023a3400877818152ad9a1033e3db8625d899c72eacb5a668902e4d652 \+ --hash=sha256:70b189594dbe54f75ab3a1acec5f1e3faa7e8cf2f1e08d9b561cb41b845f69d5 \+ --hash=sha256:797b4f722ffa07cc8d62053e4cff1486fa6dc094105d13fea7b1de7d8bf71c9e \+ --hash=sha256:7c36280e6fb8385e520936c3cb3b8042851904eba0e58d277dca80a5cfed590b \+ --hash=sha256:7e7401d0de89a9a855c839bc697c079a4af81cf878373abd7dc625847d25cbd8 \+ --hash=sha256:80bab7bfc629882493af4aa31a4cfa43a4c57c83813253626916b8c7ada83476 \+ --hash=sha256:82d09873e40955485746739bcb8b4586983670466c23382c19cffecbf1fd8706 \+ --hash=sha256:8388ee1976c416731879ac16da0aff3f63b286ffdd57cdeb95f3f2e085687563 \+ --hash=sha256:8824b5a04a04a047e72eea5cec3bc266db09e35de6bdfe34c9436ac5ee27d237 \+ --hash=sha256:8b9c7197f7cb2738065c481a0461e50ad02f18c78cd75775628afb4d7137fb3b \+ --hash=sha256:9056c1ecd25795207ad294bcf39f2db3d845767be0ea6e6a34d856f006006083 \+ --hash=sha256:936d68689298c36b53b29f23c6dbb74de12b4ac12ca6cfe0e047bedceea56180 \+ --hash=sha256:9b22676e8097e9e22e36d6b7bda33190d0d400f345f23d4065d48f4ca7ae0425 \+ --hash=sha256:a4d3091415f010369ae4ed1fc6b79def9416358877534caf6a0fdd2146c87a3e \+ --hash=sha256:a8786accb172bd8afb8be14490a16625cbc387036876ab6ba70912730faf8e1f \+ --hash=sha256:a9f8c2e67970f13b16084e04f134610fd1d374bf477b17ec1599185cf611d725 \+ --hash=sha256:bc2fa7c6b47d6bc618dd7fb02ef6fdedb1090ec036abab80d4681424b84c1183 \+ --hash=sha256:c70c95198c015b85feafc136515252a261a84561b7b1d51e3384e0655ddf25ab \+ --hash=sha256:cc1c1159b3d456576af7a3e4d1ba7e6924cb39de8f67111c735f6fc832082774 \+ --hash=sha256:ce826d6ef20b1bc864f0a68340c8b3287705cae2f8b4b1d932177dcc76721725 \+ --hash=sha256:d584d9ec91ad65861cc08d42e834324ef890a082e591037abe114850ff7bbc3e \+ --hash=sha256:d7fded462629cfa4b685c5416b949ebad6cec74af5e2d42905d41e257e0869f5 \+ --hash=sha256:d84a1718ee396f54f3a086ea0a66d8e552b2ab2017ef8b420e92edbc841c352d \+ --hash=sha256:d8e03406cac8513435335dbab54c0d385e4a49e4945d2909a581c83647ca0290 \+ --hash=sha256:e10ce637b18caea04431ce14fabcf5c64a1c61ec9c56b071a4b7ca131ca52d44 \+ --hash=sha256:ec031d5d2feb36d1d1a24380e4db6d43695f3748343d99434e6f5f9156aaa2ed \+ --hash=sha256:ef6107725bd54b262d6dedcc2af448a266975032bc85ef0172c5f059da6325b4 \+ --hash=sha256:efdca5630322a10774e8e98e1af481aad470dd62c3170801852d752aa7a783ba \+ --hash=sha256:f753120cb8181e736c57ef7636e83f31b9c0d1722c516f7e86cf15b7aa57ff12 \+ --hash=sha256:ff3824dc5261f50c9b0dfb3be22b4567a6f938ccce4587b38952d85fd9e9afe4+ # via -r .github/releases/cua-perception/test-requirements.in+referencing==0.37.0 \+ --hash=sha256:381329a9f99628c9069361716891d34ad94af76e461dcb0335825aecc7692231 \+ --hash=sha256:44aefc3142c5b842538163acb373e24cce6632bd54bdb01b21ad5863489f50d8+ # via+ # jsonschema+ # jsonschema-specifications+rpds-py==2026.6.3 \+ --hash=sha256:0be972be84cfcaf46c8c6edf690ca0f154ac17babf1f6a955a51579b34ad2dc5 \+ --hash=sha256:127565fead0a10943b282957bd5447804ff3160ad79f2ad2635e6d249e380680 \+ --hash=sha256:127e08c0642d880cf32ca47ec2a4a77b901f7e2dd1ad9762adb13955d72ffcc9 \+ --hash=sha256:166cf54d9f44fc6ceb53c7860258dde44a81406646de79f8ed3234fca3b6e538 \+ --hash=sha256:168c733a7112e071bb7a66460e667edfcff06c017a3c523f7a8a8e08d0140804 \+ --hash=sha256:1967debc37f64f2c4dc90a7f563aec558b471966e12adcac4e1c4240496b6ebf \+ --hash=sha256:1cebd1337c242e4ec2293e541f712b2da849b29f48f0c293684b71c0632625d4 \+ --hash=sha256:1cf01971c4f2c5553b772a542e4aaf191789cd331bc2cd4ff0e6e65ba49e1e97 \+ --hash=sha256:1e5822dfc2f0d4ab7e745eaa6d85945069329beeccef965af3f3bb26058fcab6 \+ --hash=sha256:22bffe6042b9bcb0822bcd1955ec00e245daf17b4344e4ed8e9551b976b63e96 \+ --hash=sha256:23a439f31ccbeff1574e24889128821d1f7917470e830cf6544dced1c662262a \+ --hash=sha256:24e9c5386e16669b674a69c156c8eeefcb578f3b3397b713b08e6d60f3c7b187 \+ --hash=sha256:270b293dae9058fc9fcedab50f13cebf46fb8ed1d1d54e0521a9da5d6b211975 \+ --hash=sha256:29dfa0533a5d4c94d4dfa1b694fcb56c9c63aad8330ffdd816fd225d0a7a162f \+ --hash=sha256:2a9c6f195058cb45335e8cc3802745c603d716eb96bc9625950c1aac71c0c703 \+ --hash=sha256:2bfd04c19ddbd6640de0b51894d764bd2758854d5b75bd102d2ef10cb9c293a9 \+ --hash=sha256:2c54a076ca4d370980ab57bc0e31df57bbe8d41340436a90ef8b1219a3cbb127 \+ --hash=sha256:2c958bf94822e9290a40aaf2a822d4bc5c88099093e3948ad6c571eca9272e5f \+ --hash=sha256:2c99f7e8ccb3dd6e3e4bfeac657a7b208c9bac8075f4b078c02d7404c34107fa \+ --hash=sha256:2f7c26fbc5acd2522b95d4177fe4710ffd8e9b20529e703ffbf8db4d93903f05 \+ --hash=sha256:30c6dc199b24a5e3e81d50da0f00858c5bbdb2617a750395687f4339c5818171 \+ --hash=sha256:38a2fea2787428f811719ceb9114cb78964a3138838320c29ac39526c79c16ba \+ --hash=sha256:3a83ae6c67b7676b9878378547ca8e93ed77a580037bcbcd1d32f739e1e6089c \+ --hash=sha256:3cfe765c1da0072636ca06628261e0ea05688e160d5c8a03e0217c3854037223 \+ --hash=sha256:421aba32367055614287a4292b6a17f1939c9452299f7a0209c117e990b646d4 \+ --hash=sha256:425560c6fa0415f27261727bb20bd097568485e5eb0c121f1949417d1c516885 \+ --hash=sha256:4470ce197d4090875cf6affbf1f853338387428df97c4fb7b7106317b8214698 \+ --hash=sha256:4cf2d36a2357e4d07bb5a4f98801265327b48256867816cfd2ceb001e9754a8f \+ --hash=sha256:4f4bca01b63096f606e095734dd56e74e175f94cfbf24ff3d63281cec61f7bb7 \+ --hash=sha256:501f9f04a588d6a09179368c57071301445191767c64e4b52a6aa9871f1ef5ed \+ --hash=sha256:536bceea4fa4acf7e1c61da2b5786304367c816c8895be71b8f537c480b0ea1f \+ --hash=sha256:538949e262e46caa31ac01bdb3c1e8f642622922cacbabbae6a8445d9dc33eaf \+ --hash=sha256:539d75de9e0d536c84ff18dfeb805398e58227001ce09231a26a08b9aed1ee0e \+ --hash=sha256:54f45a148e28767bf343d33a684693c70e451c6f4c0e9904709a723fafbdfc1f \+ --hash=sha256:55927d532399c2c646100ff7feb48eaa940ad70f42cd68e1328f3ded9f81ca24 \+ --hash=sha256:58eadac9cd119677b60e1cf8ac4052f35949d71b8a9e5556efccbe82533cf22a \+ --hash=sha256:5e8d07bddee435a2ff6f1920e18feff28d0bc4533e42f4bf6927fbd073312c41 \+ --hash=sha256:62698275682bf121181861295c9181e789030a2d516071f5b8f3c23c170cd0fc \+ --hash=sha256:639c8929aa0afe81be836b04de888460d6bed38b9c54cfc18da8f6bfabf5af5d \+ --hash=sha256:67e3a721ffc5d8d2210d3671872298c4a84e4b8035cfe42ffd7cde35d772b146 \+ --hash=sha256:6de4744d05bd1aa1be4ed7ea1189e3979196808008113bbbf899a460966b925e \+ --hash=sha256:6e84adbcf4bf841aed8116a8264b9f50b4cb3e7bd89b516122e616ac56ca269e \+ --hash=sha256:7491ee23305ac3eb59e492b6945881f5cd77a6f731061a3f25b77fd40f9e99a4 \+ --hash=sha256:79486287de1730dbaff3dbd124d0ca4d2ef7f9d29bf2544f1f93c09b5bcbbd12 \+ --hash=sha256:7b689145a1485c335569bd056464f3243a29af7ed3871c7be31ad624ba239bc7 \+ --hash=sha256:7f88d653e7b3b779d71ae7454e20dcc9b6bae903f33c269db9f2be41bda3f261 \+ --hash=sha256:8020133a74bd81b4572dd8e4be028a6b1ebcd70e6726edc3918008c08bee6ee6 \+ --hash=sha256:808345f53cb952433ca2816f1604ff3515608a81784954f38d4452acfe8e61d5 \+ --hash=sha256:83e35b57523816c8613fd0776b40cd8bb9f596b37ddd2692eb4a6bb5ab2f8c93 \+ --hash=sha256:842e7b070435622248c7a2c44ae53fa1440e073cc3023bc919fed570884097a7 \+ --hash=sha256:847927daf4cffbd4e90e42bc890069897101edd015f956cb8721b3473372edda \+ --hash=sha256:882076c00c0a608b131187055ddc5ae29f2e7eaf870d6168980420d58528a5c8 \+ --hash=sha256:8b95977e7211527ab0ba576e286d023389fbeeb32a6b7b771665d333c60e5342 \+ --hash=sha256:8bb68f03f395eb793220b45c097bd4d8c32944393da0fad8b999efac0868fc8c \+ --hash=sha256:8c2642a7603ec0b16ed77da4555db3b4b472341904873788327c0b0d7b95f1bb \+ --hash=sha256:8c3d1e9c15b9d51ca0391e13da1a25a0a4df3c58a37c9dc368e0736cf7f69df0 \+ --hash=sha256:8c6e5a2f750cc71c3e3b11d71661f21d6f9bc6cebc6564b1466417a1ec03ec77 \+ --hash=sha256:8d2294a31386bfa251d8c8a39472beee17db67d4f1a6eabea665d35c9a4461c3 \+ --hash=sha256:8e4320744c1ffdd95a603def63344bfab2d33edeab301c5007e7de9f9f5b3885 \+ --hash=sha256:8e65860d238379ed982fd9ba690579b5e95af2f4840f99c772816dbe573cb826 \+ --hash=sha256:8f2e5c5ee828d42cb11760761c0af6507927bec42d0ad5458f97c9203b054617 \+ --hash=sha256:900a67df3fd1660b035a4761c4ce73c382ea6b35f90f9863c36c6fd8bf8b09bb \+ --hash=sha256:913ca42ccad3f8cc6e292b587ae8ae49c8c823e5dce51a736252fc7c7cdfa577 \+ --hash=sha256:9250a9a0a6fd4648b3f868da8d91a4c52b5811a62df58e753d50ae4454a36f80 \+ --hash=sha256:931908d9fc855d8f74783377822be318edb6dcb19e47169dc038f9a1bf60b06e \+ --hash=sha256:9826217f048f620d9a712672818bf231442c1b35d96b227a07eabd11b4bb6945 \+ --hash=sha256:9891e594296ab9dada6551c8e7b387b2721f27a67eecd528412e8906247a7b90 \+ --hash=sha256:9c1255b302953c86a486b81d330d5ee1d5bd937691ce271b6be0ef0e299eaab7 \+ --hash=sha256:a0811d33247c3d6128a3001d763f2aa056bb3425204335400ac54f89eec3a0d0 \+ --hash=sha256:a136d453475ac0fcbda502ef1e6504bd28d6d904700915d278deeab0d00fe140 \+ --hash=sha256:a214c993455f99a89aaeadc9b21241900037adc9d97203e374d75513c5911822 \+ --hash=sha256:a3086b538543802f84c843911242db20447de00d8752dd0efc936dbcf02218ba \+ --hash=sha256:a3450b693fde92133e9f51060568a4c31fcca76d5e53bbd611e689ca446517e9 \+ --hash=sha256:a550fb4950a06dde3beb4721f5ad4b25bf4513784665b0a8522c792e2bd822a4 \+ --hash=sha256:a9f4645593036b81bbdb36b9c8e0ea0d1c3fee968c4d59db0344c14087ef143a \+ --hash=sha256:aca6c1ef08a82bfe327cc156da694660f599923e2e6665b6d81c9c2d0ac9ffc8 \+ --hash=sha256:acac386b453c2516111b50985d60ce46e7fadb5ea71ae7b25f4c946935bf27cf \+ --hash=sha256:acc992ab27b15f852c76755eb2ab7dce86585ddadba6fa5946e58556088845b4 \+ --hash=sha256:ae3d4fe8c0b9213624fdce7279d70e3b148b682ca20719ebd193a23ebfa47324 \+ --hash=sha256:ae50181a047c871561212bb97f7932a2d45fb53e947bd9b57ebad85b529cbc53 \+ --hash=sha256:ae6dd8f10bd17aad820876d24caec9efdafd80a318d16c0a48edb5e136902c6b \+ --hash=sha256:af05d726809bff6b141be124d4c7ce998f9c9c7f30edb1f46c07aa103d540b41 \+ --hash=sha256:afd70d95892096cdb26f15a00c45907b17817577aa8d1c76b2dcc2788391f9e9 \+ --hash=sha256:b5c2dc92304aa48a4a60443b548bb12f12e119d4b72f314015e67b9e1be97fca \+ --hash=sha256:bc0011654b91cc4fb2ae701bec0a0ba1e552c0714247fa7af6c59e0ccfa3a4e1 \+ --hash=sha256:bcfbcf66006befb9fd2aeaa9e01feaf881b4dc330a02ba07d2322b1c11be7b5d \+ --hash=sha256:bdbd97738551fca3917c1bd7188bec1920bb520104f28e7e1007f9ceb17b7690 \+ --hash=sha256:c60924535c75f1566b6eb75b5c31a48a43fef04fa2d0d201acbad8a9969c6107 \+ --hash=sha256:c7b9a2f8f4d8e90af72571d3d495deebdd7e3c75451f5b41719aee166e940fc2 \+ --hash=sha256:ca6546b66be9dc4738b1b043d5ebd5488c66c578c5ff0fd0e8065313fe3afb76 \+ --hash=sha256:ccffae9a092a00deb7efd545fe5e2c33c33b88e7c054337e9a74c179347d0b7d \+ --hash=sha256:cdc7e35386f3847df728fbcb5e887e2d79c19e2fa1eba9e51b6621d23e3243af \+ --hash=sha256:d15fde0e6fb0d88a60d221204873743e5d9f0b7d29165e62cd86d0413ad74ba6 \+ --hash=sha256:d34c20167764fbcf927194d532dd7e0c56772f0a5f943fa5ef9e9afbba8fb9db \+ --hash=sha256:d483fe17f01ad64b7bf7cc38fcefff1ca9fb83f8c2b2542b68f97ffe0611b369 \+ --hash=sha256:d7469697dce35be237db177d42e2a2ee26e6dcc5fc052078a6fefabd288c6edd \+ --hash=sha256:db08f45aecde626498fb3df07bcf6d2ec040af42e859a4f5040d79c200342911 \+ --hash=sha256:dc319e5a1de4b6913aac94bf6a2f9e847371e0a140a43dd4991db1a09bc2d504 \+ --hash=sha256:de3eceba0b683bcbb1ab93da016d0270df1f9ae7be716b40214c5dafac6ea45a \+ --hash=sha256:dfcc8b909769d19db55c7cc9541eb64b9b774b1057ffffb4f1048070475bb9f9 \+ --hash=sha256:e059c5dde6452b44424bd1834557556c226b57781dee1227af23518459722b13 \+ --hash=sha256:e4316bf32babbed84e691e352faf967ce2f0f024174a8643c37c94a1080374fc \+ --hash=sha256:e52655eaf81e32593abedaa4bfe33170c8cfedf3365ed9be6e11e07f148f0278 \+ --hash=sha256:e55d236be29255554da47abe5c577637db7c24a02b8b46f0ca9524c855801868 \+ --hash=sha256:ea7bb13b7c9a29791f87a0387ba7d3ad3a6d783d827e4d3f27b40a0ff44495e2 \+ --hash=sha256:ea964164cc9afa72d4d9b23cc28dafae93693c0a53e0b42acbff15b22c3f9ddd \+ --hash=sha256:ec829541c45bca16e61c7ae50c20501f213605beb75d1aba91a6ee37fbbb56a4 \+ --hash=sha256:ecabd69db66de867690f9797f2f8fa27ba501bbc24540cbdbdc649cd15888ba6 \+ --hash=sha256:ed0c1e5d10cdc7135537988c74a0188da68e2f3c30813ba3744ab1e42e0480f9 \+ --hash=sha256:f0840b5b17057f7fd918b76183a4b5a0635f43e14eb2ce60dce1d4ee4707ea00 \+ --hash=sha256:f4d78253f6996be4901669ad25319f842f740eccf4d58e3c7f3dd39e6dde1d8f \+ --hash=sha256:f56f1695bc5c0871cbc33dc0130fcf503aab0c57dcc5a6700a4f49eba4f2652e \+ --hash=sha256:f826877d462181e5eb1c26a0026b8d0cab05d99844ecb6d8bf3627a2ca0c0442 \+ --hash=sha256:f8f23ead891a3b762f35ab3b04623da7056545b48aa60d59957e6789914545da \+ --hash=sha256:f90938e92afda60266da758ee7d363447f7f0138c9559f9e1811629580582d90 \+ --hash=sha256:faa679d19a6696fd54259ad321251ad77a13e70e03dd834daa762a44fb6196ef+ # via+ # jsonschema+ # referencing+typing-extensions==4.16.0 ; python_full_version < '3.13' \+ --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8 \+ --hash=sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5+ # via referencingdiff --git a/.github/releases/cua-perception/trust-root.json b/.github/releases/cua-perception/trust-root.jsonnew file mode 100644index 0000000000..667396db33--- /dev/null+++ b/.github/releases/cua-perception/trust-root.json@@ -0,0 +1,22 @@+{+ "$schema": "./trust-root.schema.json",+ "schemaVersion": 1,+ "publisherId": "cua",+ "activeKeyId": "cua-extension-ed25519-2026-01",+ "keys": [+ {+ "keyId": "cua-extension-ed25519-2026-01",+ "algorithm": "Ed25519",+ "publicKeyBase64": "dB7E/36fTXLiHPfr8ya4i4TFbssU/jpO9zrS8gl4bsQ=",+ "status": "active",+ "validFromUnix": 1735689600,+ "validUntilUnix": 2082758400,+ "replaces": null+ }+ ],+ "rotation": {+ "minimumOverlapDays": 30,+ "nextKeyId": null,+ "privateKeysStoredInRepository": false+ }+}diff --git a/.github/releases/cua-perception/trust-root.schema.json b/.github/releases/cua-perception/trust-root.schema.jsonnew file mode 100644index 0000000000..75b9603e8a--- /dev/null+++ b/.github/releases/cua-perception/trust-root.schema.json@@ -0,0 +1,109 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://github.com/trycua/cua/.github/releases/cua-perception/trust-root.schema.json",+ "title": "Cua extension signing trust root",+ "type": "object",+ "additionalProperties": false,+ "required": [+ "schemaVersion",+ "publisherId",+ "activeKeyId",+ "keys",+ "rotation"+ ],+ "properties": {+ "$schema": {+ "type": "string"+ },+ "schemaVersion": {+ "const": 1+ },+ "publisherId": {+ "const": "cua"+ },+ "activeKeyId": {+ "type": "string",+ "minLength": 1+ },+ "keys": {+ "type": "array",+ "minItems": 1,+ "items": {+ "$ref": "#/$defs/key"+ }+ },+ "rotation": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "minimumOverlapDays",+ "nextKeyId",+ "privateKeysStoredInRepository"+ ],+ "properties": {+ "minimumOverlapDays": {+ "type": "integer",+ "minimum": 1+ },+ "nextKeyId": {+ "type": [+ "string",+ "null"+ ]+ },+ "privateKeysStoredInRepository": {+ "const": false+ }+ }+ }+ },+ "$defs": {+ "key": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "keyId",+ "algorithm",+ "publicKeyBase64",+ "status",+ "validFromUnix",+ "validUntilUnix",+ "replaces"+ ],+ "properties": {+ "keyId": {+ "type": "string",+ "minLength": 1+ },+ "algorithm": {+ "const": "Ed25519"+ },+ "publicKeyBase64": {+ "type": "string",+ "pattern": "^[A-Za-z0-9+/]{43}=$"+ },+ "status": {+ "enum": [+ "active",+ "pending",+ "retired"+ ]+ },+ "validFromUnix": {+ "type": "integer",+ "minimum": 1+ },+ "validUntilUnix": {+ "type": "integer",+ "minimum": 1+ },+ "replaces": {+ "type": [+ "string",+ "null"+ ]+ }+ }+ }+ }+}diff --git a/.github/releases/cua-perception/verification-report.schema.json b/.github/releases/cua-perception/verification-report.schema.jsonnew file mode 100644index 0000000000..bc4a707f77--- /dev/null+++ b/.github/releases/cua-perception/verification-report.schema.json@@ -0,0 +1,24 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://github.com/trycua/cua/.github/releases/cua-perception/verification-report.schema.json",+ "title": "Cua Perception target verification report",+ "type": "object",+ "additionalProperties": false,+ "required": ["schemaVersion", "evidenceKind", "gate", "status", "target", "protocolVersion", "extensionId", "extensionVersion", "workerSha256", "runtimeSha256"],+ "properties": {+ "$schema": { "type": "string" },+ "schemaVersion": { "const": 1 },+ "evidenceKind": { "const": "supplied" },+ "gate": { "enum": ["health", "self-test", "real-parse"] },+ "status": { "const": "passed" },+ "target": { "type": "string", "minLength": 1 },+ "protocolVersion": { "type": "integer", "minimum": 1 },+ "extensionId": { "const": "cua-perception" },+ "extensionVersion": { "type": "string", "pattern": "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)$" },+ "workerSha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" },+ "runtimeSha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" },+ "fixtureSha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" },+ "observations": { "type": "integer", "minimum": 1 },+ "mismatchRejectionPassed": { "const": true }+ }+}diff --git a/.github/scripts/cua-driver-mcp-compat/expected-tools.json b/.github/scripts/cua-driver-mcp-compat/expected-tools.jsonindex 7d80cc8db8..dc795bed82 100644--- a/.github/scripts/cua-driver-mcp-compat/expected-tools.json+++ b/.github/scripts/cua-driver-mcp-compat/expected-tools.json@@ -1,9 +1,9 @@{"serverName": "cua-driver","outputSchemaCountByPlatform": {- "darwin": 34,- "linux": 38,- "win32": 34+ "darwin": 35,+ "linux": 39,+ "win32": 35},"baseTools": ["bring_to_front",@@ -37,6 +37,7 @@"get_window_state","health_report","hotkey",+ "install_extension","install_ffmpeg","invoke_menu","kill_app",@@ -46,6 +47,7 @@"list_windows","move_cursor","page",+ "parse_visual_regions","press_key","replay_trajectory","right_click",diff --git a/.github/scripts/cua-driver-mcp-compat/verify-modern.mjs b/.github/scripts/cua-driver-mcp-compat/verify-modern.mjsindex b2af4186ec..87cb7a1da4 100644--- a/.github/scripts/cua-driver-mcp-compat/verify-modern.mjs+++ b/.github/scripts/cua-driver-mcp-compat/verify-modern.mjs@@ -45,6 +45,7 @@ const expectedFiles = ['RECORDING.md','RUNTIME.md','SKILL.md',+ 'VISUAL.md','WINDOWS.md','WORKFLOW.md',];diff --git a/.github/scripts/macos-review-codesign.sh b/.github/scripts/macos-review-codesign.shnew file mode 100755index 0000000000..47c6cd4048--- /dev/null+++ b/.github/scripts/macos-review-codesign.sh@@ -0,0 +1,279 @@+#!/usr/bin/env bash++set -euo pipefail++if [[ $# -ne 2 ]]; then+ echo "usage: $0 DRIVER_PATH MEASUREMENT_PATH" >&2+ exit 2+fi+if [[ "$(uname -s)" != Darwin ]]; then+ echo "macOS review signing must run on Darwin" >&2+ exit 2+fi++driver_path="$1"+measurement_path="$2"+[[ -f "$driver_path" ]] || { echo "review Driver is missing: $driver_path" >&2; exit 2; }+[[ ! -e "$measurement_path" ]] || { echo "measurement output already exists: $measurement_path" >&2; exit 2; }++work_root="$(mktemp -d "${RUNNER_TEMP:-/tmp}/cua-review-codesign.XXXXXX")"+keychain_path="$work_root/review-signing.keychain-db"+private_key_path="$work_root/review-signing.key"+certificate_path="$work_root/review-signing.crt"+certificate_der_path="$work_root/review-signing.der"+identity_path="$work_root/review-signing.p12"+keychain_password="$(openssl rand -hex 32)"+identity_password="$(openssl rand -hex 32)"+identity_name="Cua Review Candidate ${GITHUB_RUN_ID:-local}"+keychain_created=false+search_list_snapshotted=false+default_keychain_snapshotted=false+previous_keychains=()+previous_keychain_count=0+previous_default_keychain=""+trusted_identity=""+admin_trust_cleanup_needed=false+log_dir="$work_root/logs"+signing_probe="$work_root/signing-probe"++run_bounded() {+ /usr/bin/perl -e 'alarm shift; exec @ARGV' 60 "$@"+}++emit_log() {+ sed -E 's/[[:xdigit:]]{64}/<redacted>/g' "$1" >&2+}++run_step() {+ local label="$1"+ shift+ if ! run_bounded "$@" >"$log_dir/$label.log" 2>&1; then+ echo "review signing step failed: $label" >&2+ emit_log "$log_dir/$label.log"+ exit 1+ fi+}++cleanup() {+ local status=$?+ local cleanup_status="$status"+ local cleanup_failed=false+ trap - EXIT INT TERM+ set +e+ if [[ "$admin_trust_cleanup_needed" == true \+ && "$trusted_identity" =~ ^[0-9A-Fa-f]{40}$ ]]; then+ run_bounded sudo -n security remove-trusted-cert -d "$certificate_path" \+ >/dev/null 2>&1 || true+ run_bounded sudo -n security delete-certificate -Z "$trusted_identity" \+ /Library/Keychains/System.keychain >/dev/null 2>&1 || true+ system_certificates="$(run_bounded security find-certificate -Z -a \+ /Library/Keychains/System.keychain 2>&1)"+ system_certificates_status=$?+ if [[ "$system_certificates_status" != 0 ]]; then+ echo "cannot verify removal of the temporary system certificate" >&2+ cleanup_failed=true+ elif [[ "$system_certificates" == *"$trusted_identity"* ]]; then+ echo "temporary review certificate remained in the system keychain" >&2+ cleanup_failed=true+ fi+ admin_trust_dump="$(run_bounded security dump-trust-settings -d 2>&1)"+ admin_trust_status=$?+ if [[ "$admin_trust_status" != 0 \+ && "$admin_trust_dump" != *"No Trust Settings were found."* ]]; then+ echo "cannot verify removal of temporary admin trust settings" >&2+ cleanup_failed=true+ fi+ if [[ "$admin_trust_dump" == *"Cua Review Candidate ${GITHUB_RUN_ID:-local}"* ]]; then+ echo "temporary review trust setting remained configured" >&2+ cleanup_failed=true+ fi+ fi+ if [[ "$default_keychain_snapshotted" == true && -n "$previous_default_keychain" ]]; then+ security default-keychain -d user -s "$previous_default_keychain" \+ >/dev/null 2>&1 || true+ fi+ if [[ "$search_list_snapshotted" == true ]]; then+ if (( previous_keychain_count > 0 )); then+ security list-keychains -d user -s "${previous_keychains[@]}" >/dev/null 2>&1 || true+ else+ security list-keychains -d user -s >/dev/null 2>&1 || true+ fi+ fi+ if [[ "$keychain_created" == true ]]; then+ security delete-keychain "$keychain_path" >/dev/null 2>&1 || true+ fi+ rm -f "$signing_probe" \+ "$log_dir/import.log" "$log_dir/partition.log" \+ "$log_dir/pkcs12-legacy.log" "$log_dir/pkcs12-fallback.log" \+ "$log_dir/identity.log" "$log_dir/valid-identity.log" \+ "$log_dir/sudo-preflight.log" "$log_dir/add-trust.log" \+ "$log_dir/trusted-cert-present.log" "$log_dir/probe-sign-name.log" \+ "$log_dir/probe-sign-hash.log" "$log_dir/probe-verify.log" \+ "$log_dir/driver-sign.log" \+ "$log_dir/driver-verify.log"+ rmdir "$log_dir" >/dev/null 2>&1 || true+ rm -f "$private_key_path" "$certificate_path" "$certificate_der_path" \+ "$identity_path" "$keychain_path"+ rmdir "$work_root" >/dev/null 2>&1 || true+ keychain_password=""+ identity_password=""+ if [[ "$cleanup_failed" == true && "$status" == 0 ]]; then+ cleanup_status=1+ fi+ exit "$cleanup_status"+}+trap cleanup EXIT INT TERM++mkdir -p "$log_dir"++previous_default_keychain="$(security default-keychain -d user |+ sed -E 's/^[[:space:]]*"//; s/"[[:space:]]*$//')"+[[ -n "$previous_default_keychain" ]] || {+ echo "cannot determine the current user default keychain" >&2+ exit 1+}+default_keychain_snapshotted=true++previous_keychains_output="$(security list-keychains -d user)"+while IFS= read -r listed_keychain; do+ listed_keychain="${listed_keychain#*\"}"+ listed_keychain="${listed_keychain%\"*}"+ if [[ -n "$listed_keychain" ]]; then+ previous_keychains+=("$listed_keychain")+ previous_keychain_count=$((previous_keychain_count + 1))+ fi+done <<< "$previous_keychains_output"+unset previous_keychains_output+search_list_snapshotted=true++openssl req -new -newkey rsa:2048 -nodes -x509 -sha256 -days 2 \+ -subj "/CN=$identity_name/O=Cua Review Only" \+ -addext "basicConstraints=critical,CA:FALSE" \+ -addext "keyUsage=critical,digitalSignature" \+ -addext "extendedKeyUsage=codeSigning" \+ -keyout "$private_key_path" -out "$certificate_path"+openssl x509 -in "$certificate_path" -outform der -out "$certificate_der_path"+if ! openssl pkcs12 -export -legacy \+ -inkey "$private_key_path" -in "$certificate_path" \+ -name "$identity_name" -passout "pass:$identity_password" \+ -out "$identity_path" >"$log_dir/pkcs12-legacy.log" 2>&1; then+ if ! openssl pkcs12 -export \+ -inkey "$private_key_path" -in "$certificate_path" \+ -name "$identity_name" -passout "pass:$identity_password" \+ -out "$identity_path" >"$log_dir/pkcs12-fallback.log" 2>&1; then+ echo "review signing step failed: pkcs12-export" >&2+ emit_log "$log_dir/pkcs12-legacy.log"+ emit_log "$log_dir/pkcs12-fallback.log"+ exit 1+ fi+fi++security create-keychain -p "$keychain_password" "$keychain_path"+keychain_created=true+security set-keychain-settings -lut 900 "$keychain_path"+security unlock-keychain -p "$keychain_password" "$keychain_path"+if (( previous_keychain_count > 0 )); then+ security list-keychains -d user -s "$keychain_path" "${previous_keychains[@]}"+else+ security list-keychains -d user -s "$keychain_path"+fi+security default-keychain -d user -s "$keychain_path"++# This allow-all ACL is confined to a generated key in an ephemeral keychain on+# a single-tenant runner. The EXIT trap deletes both the key and its keychain.+run_step import security import "$identity_path" -k "$keychain_path" \+ -P "$identity_password" -A -T /usr/bin/codesign++run_step identity security find-identity -p codesigning "$keychain_path"+identities="$(sed -nE 's/^[[:space:]]*[0-9]+\) ([0-9A-F]{40}) .*/\1/p' \+ "$log_dir/identity.log")"+[[ "$(printf '%s\n' "$identities" | sed '/^$/d' | wc -l | tr -d ' ')" == 1 ]] || {+ echo "temporary keychain must contain exactly one code-signing identity" >&2+ emit_log "$log_dir/identity.log"+ exit 1+}+identity_hash="$identities"+trusted_identity="$identity_hash"++if [[ "${GITHUB_ACTIONS:-}" == true \+ && "${RUNNER_ENVIRONMENT:-}" == github-hosted \+ && "${RUNNER_OS:-}" == macOS ]]; then+ # The hosted runner resolves the imported key for codesign only after the+ # self-signed certificate has a temporary code-signing trust setting.+ run_step sudo-preflight sudo -n -v+ admin_trust_cleanup_needed=true+ run_step add-trust sudo -n security add-trusted-cert -d -r trustRoot \+ -p codeSign -k /Library/Keychains/System.keychain "$certificate_path"+ run_step trusted-cert-present security find-certificate -Z -a \+ /Library/Keychains/System.keychain+ grep -Fqi "$identity_hash" "$log_dir/trusted-cert-present.log" || {+ echo "temporary review certificate was not found in the system keychain" >&2+ emit_log "$log_dir/trusted-cert-present.log"+ exit 1+ }+ run_step valid-identity security find-identity -v -p codesigning "$keychain_path"+ grep -Fqi "$identity_hash" "$log_dir/valid-identity.log" || {+ echo "temporary code-signing identity did not become valid" >&2+ emit_log "$log_dir/valid-identity.log"+ exit 1+ }+fi++# Some hosted runners cannot update partitions on a freshly imported key.+# The signing probe below is the authoritative noninteractive usability check.+if ! run_bounded security set-key-partition-list \+ -S apple-tool:,apple:,codesign: -s -k "$keychain_password" "$keychain_path" \+ >"$log_dir/partition.log" 2>&1; then+ echo "note: set-key-partition-list did not apply; relying on the import ACL" >&2+ emit_log "$log_dir/partition.log"+fi++# Identity discovery proves presence; this probe proves the private key can sign+# the same unsigned Mach-O bytes without modifying the candidate first. Prefer+# the unique certificate name and default keychain path used by release signing;+# retain the exact certificate hash as a compatibility fallback.+cp "$driver_path" "$signing_probe"+identity_selector="$identity_name"+if ! run_bounded codesign --force --sign "$identity_selector" "$signing_probe" \+ >"$log_dir/probe-sign-name.log" 2>&1; then+ identity_selector="$identity_hash"+ if ! run_bounded codesign --force --sign "$identity_selector" "$signing_probe" \+ >"$log_dir/probe-sign-hash.log" 2>&1; then+ echo "review signing step failed: probe-sign" >&2+ emit_log "$log_dir/probe-sign-name.log"+ emit_log "$log_dir/probe-sign-hash.log"+ exit 1+ fi+fi+run_step probe-verify codesign --verify --strict "$signing_probe"++run_step driver-sign codesign --force --sign "$identity_selector" "$driver_path"+run_step driver-verify codesign --verify --strict --verbose=2 "$driver_path"++requirement_output="$({ codesign -d -r- "$driver_path"; } 2>&1)"+requirement="$(printf '%s\n' "$requirement_output" | sed -n 's/^designated => //p')"+printf '%s\n' "$requirement" |+ grep -Eqi "certificate (leaf|root) = H\"$identity_hash\"" || {+ echo "review Driver designated requirement does not bind the selected certificate" >&2+ exit 1+}+certificate_sha256="$(shasum -a 256 "$certificate_der_path" | awk '{print $1}')"++CODE_SIGNING_REQUIREMENT="$requirement" \+CODE_SIGNING_CERTIFICATE_SHA256="$certificate_sha256" \+python3 - "$measurement_path" <<'PY'+import json+import os+import pathlib+import sys++path = pathlib.Path(sys.argv[1])+value = {+ "status": "verified",+ "format": "apple-codesign",+ "identity": "ephemeral-self-signed-review-only",+ "certificate_sha256": os.environ["CODE_SIGNING_CERTIFICATE_SHA256"],+ "designated_requirement": os.environ["CODE_SIGNING_REQUIREMENT"],+}+path.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n")+PYdiff --git a/.github/scripts/merge_release_please_manifests.py b/.github/scripts/merge_release_please_manifests.pyindex 8b3bc5ab7f..dd8b7c1c45 100644--- a/.github/scripts/merge_release_please_manifests.py+++ b/.github/scripts/merge_release_please_manifests.py@@ -10,6 +10,7 @@ from typing import AnyCOMPONENT_PATHS = {+ "cua-perception": "libs/cua-driver/rust/crates/cua-perception","cua-driver-rs": "libs/cua-driver","lume": "libs/lume","sandbox": "libs/python/cua-sandbox",diff --git a/.github/scripts/perception_release.py b/.github/scripts/perception_release.pynew file mode 100644index 0000000000..2be4775ec7--- /dev/null+++ b/.github/scripts/perception_release.py@@ -0,0 +1,1053 @@+#!/usr/bin/env python3+"""Validate and package non-publishing Cua Perception release candidates."""++from __future__ import annotations++import argparse+import gzip+from hashlib import sha256+import json+import os+from pathlib import Path, PurePosixPath+import re+import shutil+import stat+import subprocess+import tarfile+import tempfile+import time+from typing import Any, Mapping, Sequence+import zipfile++try:+ from jsonschema import Draft202012Validator+except ImportError: # Release packaging intentionally has no network-installed dependencies.+ Draft202012Validator = None # type: ignore[assignment]+++ROOT = Path(__file__).resolve().parents[2]+CONTROL = ROOT / ".github/releases/cua-perception"+VERSION_AUTHORITY = ROOT / "libs/cua-driver/rust/crates/cua-perception/VERSION"+SEMVER_RE = re.compile(r"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$")+TARGET_RE = re.compile(r"^[a-z0-9_+.]+(?:-[a-z0-9_+.]+)+$")+SHA256_RE = re.compile(r"^[0-9a-f]{64}$")+KIND_DIRECTORIES = {+ "worker": "bin",+ "runtime": "runtime",+ "model": "models",+ "dictionary": "models",+ "model-manifest": "",+ "notice": "notices",+ "source": "source",+ "supplied-verification-report": "verification/supplied",+ "review-recording": "review-recordings",+}+++class CandidateError(RuntimeError):+ """A candidate release invariant failed."""+++def read_json(path: Path) -> Any:+ try:+ return json.loads(path.read_text(encoding="utf-8"))+ except (OSError, UnicodeError, json.JSONDecodeError) as error:+ raise CandidateError(f"cannot read JSON from {path}: {error}") from error+++def validate_schema(document: Any, schema_path: Path) -> None:+ if Draft202012Validator is None:+ return+ schema = read_json(schema_path)+ errors = sorted(Draft202012Validator(schema).iter_errors(document), key=lambda item: list(item.path))+ if errors:+ details = "; ".join(+ f"{'/'.join(str(part) for part in error.path) or '<root>'}: {error.message}"+ for error in errors+ )+ raise CandidateError(f"{schema_path.name} validation failed: {details}")+++def confined_file(root: Path, relative: str) -> Path:+ pure = PurePosixPath(relative)+ if pure.is_absolute() or ".." in pure.parts:+ raise CandidateError(f"input path must be relative and confined: {relative!r}")+ candidate = root / pure+ if candidate.is_symlink():+ raise CandidateError(f"input must not be a symlink: {relative!r}")+ resolved = candidate.resolve()+ try:+ resolved.relative_to(root.resolve())+ except ValueError as error:+ raise CandidateError(f"input path escapes payload root: {relative!r}") from error+ if not resolved.is_file():+ raise CandidateError(f"input must be a regular non-symlink file: {relative!r}")+ return resolved+++def file_digest(path: Path) -> str:+ digest = sha256()+ with path.open("rb") as stream:+ for block in iter(lambda: stream.read(1024 * 1024), b""):+ digest.update(block)+ return digest.hexdigest()+++def load_and_validate_manifest(manifest_path: Path, payload_root: Path) -> dict[str, Any]:+ manifest = read_json(manifest_path)+ validate_schema(manifest, CONTROL / "artifact-manifest.schema.json")+ required = {+ "schemaVersion", "component", "version", "driverVersion", "sourceSha",+ "target", "protocol", "artifacts", "modelLedger", "sourceLedger",+ "suppliedVerification",+ }+ missing = required - set(manifest) if isinstance(manifest, dict) else required+ if missing:+ raise CandidateError(f"candidate manifest is missing: {', '.join(sorted(missing))}")+ if manifest["schemaVersion"] != 1 or manifest["component"] != "cua-perception":+ raise CandidateError("candidate manifest identity or schema version is invalid")+ if not re.fullmatch(r"[0-9a-f]{40}", str(manifest["sourceSha"])):+ raise CandidateError("candidate sourceSha must be an exact lowercase commit SHA")+ authority = VERSION_AUTHORITY.read_text(encoding="utf-8").strip()+ if manifest["version"] != authority:+ raise CandidateError(+ f"candidate version {manifest['version']} differs from release authority {authority}"+ )+ if not SEMVER_RE.fullmatch(authority):+ raise CandidateError(f"release authority is not stable SemVer: {authority!r}")+ target = manifest["target"]+ if not TARGET_RE.fullmatch(target["triple"]):+ raise CandidateError(f"invalid target triple: {target['triple']!r}")++ names: set[str] = set()+ paths: set[str] = set()+ kinds: dict[str, list[Mapping[str, Any]]] = {}+ for artifact in manifest["artifacts"]:+ name = artifact["name"]+ relative = artifact["path"]+ if name in names or relative in paths:+ raise CandidateError(f"duplicate artifact name or path: {name!r}, {relative!r}")+ names.add(name)+ paths.add(relative)+ source = confined_file(payload_root, relative)+ actual_size = source.stat().st_size+ actual_digest = file_digest(source)+ if actual_size != artifact["size"]:+ raise CandidateError(+ f"size mismatch for {name}: expected {artifact['size']}, got {actual_size}"+ )+ if actual_digest != artifact["sha256"]:+ raise CandidateError(+ f"SHA-256 mismatch for {name}: expected {artifact['sha256']}, got {actual_digest}"+ )+ if not artifact.get("license", {}).get("spdx") or not artifact["license"].get("source"):+ raise CandidateError(f"artifact {name} has incomplete license provenance")+ if artifact["kind"] in {"worker", "runtime"}:+ if artifact.get("target") != target:+ raise CandidateError(f"{artifact['kind']} {name} does not match candidate target")+ if artifact.get("protocolVersion") != manifest["protocol"]["version"]:+ raise CandidateError(f"{artifact['kind']} {name} has a different protocol version")+ kinds.setdefault(artifact["kind"], []).append(artifact)+ if len(kinds.get("worker", [])) != 1:+ raise CandidateError("candidate must contain exactly one worker artifact")+ if len(kinds.get("runtime", [])) != 1:+ raise CandidateError("candidate must contain exactly one target-specific runtime")+ model_roles = {item.get("role") for item in kinds.get("model", [])}+ if model_roles != {"icon-detect", "ocr-detect", "ocr-recognize"}:+ raise CandidateError("candidate must contain exactly the three required model roles")+ dictionaries = kinds.get("dictionary", [])+ if len(dictionaries) != 1 or dictionaries[0].get("role") != "ocr-dictionary":+ raise CandidateError("candidate must contain exactly one OCR dictionary")+ model_manifests = kinds.get("model-manifest", [])+ if len(model_manifests) != 1 or model_manifests[0]["name"] != "model-manifest.json":+ raise CandidateError("candidate must contain exactly one model-manifest.json artifact")+ runtime = kinds["runtime"][0]+ expected_runtime_suffix = {"linux": ".so", "macos": ".dylib", "windows": ".dll"}[+ target["os"]+ ]+ if not runtime["name"].lower().endswith(expected_runtime_suffix):+ raise CandidateError(+ f"runtime {runtime['name']} does not match target OS {target['os']}"+ )+ notice_paths = {item["path"] for item in kinds.get("notice", [])}+ for artifact in manifest["artifacts"]:+ if artifact["kind"] == "notice":+ continue+ notice = artifact["license"].get("notice")+ if not notice or notice not in notice_paths:+ raise CandidateError(+ f"{artifact['kind']} {artifact['name']} must reference a declared notice artifact"+ )++ _validate_ledger(manifest, payload_root, "modelLedger", "model", "model-ledger.schema.json")+ _validate_ledger(manifest, payload_root, "sourceLedger", "source", "source-ledger.schema.json")+ _validate_model_source_binding(manifest, payload_root)+ _validate_model_manifest(manifest, payload_root, kinds)+ _validate_verification_reports(manifest, payload_root, kinds)+ return manifest+++def _validate_model_manifest(+ manifest: Mapping[str, Any], payload_root: Path, kinds: Mapping[str, list[Mapping[str, Any]]]+) -> None:+ artifact = kinds["model-manifest"][0]+ document = read_json(confined_file(payload_root, artifact["path"]))+ if not isinstance(document, dict) or document.get("schema_version") != 1:+ raise CandidateError("model-manifest.json has an invalid schema version")+ runtime = kinds["runtime"][0]+ if document.get("onnx_runtime", {}).get("library_sha256") != runtime["sha256"]:+ raise CandidateError("model-manifest.json binds a different ONNX Runtime")+ expected = {+ "detector.model": next(item for item in kinds["model"] if item.get("role") == "icon-detect"),+ "ocr.detector.model": next(item for item in kinds["model"] if item.get("role") == "ocr-detect"),+ "ocr.recognizer.model": next(item for item in kinds["model"] if item.get("role") == "ocr-recognize"),+ "ocr.dictionary": kinds["dictionary"][0],+ }+ actual = {+ "detector.model": document.get("detector", {}).get("model"),+ "ocr.detector.model": document.get("ocr", {}).get("detector", {}).get("model"),+ "ocr.recognizer.model": document.get("ocr", {}).get("recognizer", {}).get("model"),+ "ocr.dictionary": document.get("ocr", {}).get("dictionary"),+ }+ for field, release_artifact in expected.items():+ binding = actual[field]+ wanted = {+ "path": f"models/{release_artifact['name']}",+ "sha256": release_artifact["sha256"],+ }+ if binding != wanted:+ raise CandidateError(f"model-manifest.json {field} differs from release artifacts")+++def _validate_verification_reports(+ manifest: Mapping[str, Any], payload_root: Path, kinds: Mapping[str, list[Mapping[str, Any]]]+) -> None:+ declared = {+ item["path"]: item for item in kinds.get("supplied-verification-report", [])+ }+ worker = kinds["worker"][0]+ runtime = kinds["runtime"][0]+ for field, gate in (("health", "health"), ("selfTest", "self-test"), ("realParse", "real-parse")):+ relative = manifest["suppliedVerification"][field]+ artifact = declared.get(relative)+ if not artifact or artifact.get("role") != gate:+ raise CandidateError(f"verification gate {gate} is not a declared report artifact")+ report = read_json(confined_file(payload_root, relative))+ validate_schema(report, CONTROL / "verification-report.schema.json")+ if report.get("evidenceKind") != "supplied":+ raise CandidateError(f"verification gate {gate} is not marked as supplied evidence")+ if report["gate"] != gate or report["target"] != manifest["target"]["triple"]:+ raise CandidateError(f"verification gate {gate} targets a different platform")+ if report["protocolVersion"] != manifest["protocol"]["version"]:+ raise CandidateError(f"verification gate {gate} uses a different protocol")+ expected_identity = (manifest["component"], manifest["version"])+ report_identity = (report["extensionId"], report["extensionVersion"])+ if report_identity != expected_identity:+ raise CandidateError(+ f"verification gate {gate} reports extension identity {report_identity!r}; "+ f"expected {expected_identity!r}"+ )+ if report["workerSha256"] != worker["sha256"] or report["runtimeSha256"] != runtime["sha256"]:+ raise CandidateError(f"verification gate {gate} hashes a different worker or runtime")+ if gate == "real-parse" and (not report.get("fixtureSha256") or not report.get("observations")):+ raise CandidateError("real-parse verification must record a fixture and observations")+ if gate == "self-test" and report.get("mismatchRejectionPassed") is not True:+ raise CandidateError("self-test must prove cross-platform runtime/hash mismatch rejection")+++def _validate_ledger(+ manifest: Mapping[str, Any],+ payload_root: Path,+ field: str,+ kind: str,+ schema_name: str,+) -> None:+ artifacts = {item["name"]: item for item in manifest["artifacts"] if item["kind"] == kind}+ artifact_names = set(artifacts)+ ledger_path = manifest.get(field)+ if artifact_names and not ledger_path:+ raise CandidateError(f"{field} is required when {kind} artifacts are supplied")+ if not ledger_path:+ return+ ledger = read_json(confined_file(payload_root, str(ledger_path)))+ validate_schema(ledger, CONTROL / schema_name)+ key = "models" if kind == "model" else "sources"+ if kind == "source" and not ledger[key]:+ raise CandidateError("sourceLedger must contain bundled corresponding source")+ ledger_names = {item["artifact"] for item in ledger[key]}+ if artifact_names != ledger_names:+ raise CandidateError(+ f"{field} entries differ from {kind} artifacts: "+ f"artifacts={sorted(artifact_names)}, ledger={sorted(ledger_names)}"+ )+ entries = {item["artifact"]: item for item in ledger[key]}+ for name, artifact in artifacts.items():+ entry = entries[name]+ if entry["license"] != artifact["license"]["spdx"]:+ raise CandidateError(f"{field} license differs from manifest for {name}")+ if kind == "model" and entry["artifactSha256"] != artifact["sha256"]:+ raise CandidateError(f"{field} SHA-256 differs from manifest for {name}")+ if kind == "model" and entry.get("artifactSize", artifact["size"]) != artifact["size"]:+ raise CandidateError(f"{field} size differs from manifest for {name}")+ if kind == "model" and (+ entry.get("redistributionAllowed") is not True or not entry.get("exportSource")+ ):+ raise CandidateError(f"{field} lacks redistribution or exporter-source proof for {name}")+ if kind == "source":+ if entry.get("artifactSha256") != artifact["sha256"]:+ raise CandidateError(f"{field} SHA-256 differs from manifest for {name}")+ if entry.get("artifactSize") != artifact["size"]:+ raise CandidateError(f"{field} size differs from manifest for {name}")+ if entry.get("contentKind") == "cua-source" and entry.get("revision") != manifest["sourceSha"]:+ raise CandidateError(f"{field} Cua revision differs from manifest sourceSha")+ if entry.get("sourceOfferStatus") not in {"bundled", "bundled-review-only"}:+ raise CandidateError("candidate catalog requires bundled corresponding source")+ source_path = confined_file(payload_root, artifact["path"])+ if entry.get("format") == "tar.gz":+ _validate_source_archive(source_path, entry.get("requiredPaths", []))+ elif entry.get("format") != "file":+ raise CandidateError(f"{field} has an unsupported source format for {name}")+++def _validate_source_archive(path: Path, required_paths: Sequence[str]) -> None:+ try:+ with tarfile.open(path, "r:gz") as archive:+ members = archive.getmembers()+ except tarfile.TarError as error:+ raise CandidateError(f"invalid source archive {path}: {error}") from error+ if not members:+ raise CandidateError(f"source archive is empty: {path}")+ names = []+ for member in members:+ pure = PurePosixPath(member.name)+ if pure.is_absolute() or ".." in pure.parts:+ raise CandidateError(f"source archive contains an unsafe member: {member.name}")+ if member.issym() or member.islnk():+ target = PurePosixPath(member.linkname)+ parts = list(pure.parent.parts)+ if target.is_absolute():+ raise CandidateError(f"source archive contains an unsafe link: {member.name}")+ for part in target.parts:+ if part in {"", "."}:+ continue+ if part == "..":+ if len(parts) <= 1:+ raise CandidateError(f"source archive link escapes its root: {member.name}")+ parts.pop()+ else:+ parts.append(part)+ names.append(pure.as_posix().rstrip("/"))+ for required in required_paths:+ wanted = required.rstrip("/")+ if not any(name == wanted or name.endswith("/" + wanted) or f"/{wanted}/" in f"/{name}/" for name in names):+ raise CandidateError(f"source archive {path.name} lacks required path: {required}")+++def _validate_model_source_binding(manifest: Mapping[str, Any], payload_root: Path) -> None:+ model_ledger = read_json(confined_file(payload_root, str(manifest["modelLedger"])))+ source_ledger = read_json(confined_file(payload_root, str(manifest["sourceLedger"])))+ source_entries = {entry["artifact"]: entry for entry in source_ledger["sources"]}+ for model in model_ledger["models"]:+ if model.get("verificationStatus") != "license-review-required":+ continue+ binding = model.get("sourceArtifact")+ if not binding:+ raise CandidateError(f"license-review-required model lacks a bundled source input: {model['artifact']}")+ source = source_entries.get(binding.get("artifact"))+ artifact = next(+ (item for item in manifest["artifacts"] if item["kind"] == "source" and item["name"] == binding.get("artifact")),+ None,+ )+ if not source or not artifact or source.get("contentKind") != "model-source-input":+ raise CandidateError(f"model source input is absent from the source ledger: {model['artifact']}")+ if binding.get("path") != artifact["path"] or binding.get("sha256") != artifact["sha256"] or binding.get("size") != artifact["size"]:+ raise CandidateError(f"model source input binding differs from the candidate manifest: {model['artifact']}")+++def canonical_json(path: Path, value: Mapping[str, Any]) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n", encoding="utf-8")+++def bind_corresponding_source(+ manifest_path: Path, payload_root: Path, repository_root: Path+) -> Path:+ manifest = read_json(manifest_path)+ if not isinstance(manifest, dict) or not re.fullmatch(+ r"[0-9a-f]{40}", str(manifest.get("sourceSha", ""))+ ):+ raise CandidateError("candidate sourceSha must be an exact lowercase commit SHA")+ source_sha = manifest["sourceSha"]+ head = subprocess.run(+ ["git", "-C", str(repository_root), "rev-parse", "HEAD"],+ check=True,+ stdout=subprocess.PIPE,+ text=True,+ ).stdout.strip()+ if head != source_sha:+ raise CandidateError(f"checked-out source {head} differs from manifest {source_sha}")+ ledger_path = confined_file(payload_root, str(manifest.get("sourceLedger", "")))+ ledger = read_json(ledger_path)+ cua_entries = [entry for entry in ledger.get("sources", []) if entry.get("contentKind") == "cua-source"]+ if len(cua_entries) != 1:+ raise CandidateError("candidate must declare exactly one Cua corresponding-source artifact")+ source_artifacts = [item for item in manifest.get("artifacts", []) if item.get("kind") == "source"]+ matching_artifacts = [item for item in source_artifacts if item.get("name") == cua_entries[0].get("artifact")]+ if len(matching_artifacts) != 1:+ raise CandidateError("Cua corresponding-source ledger entry does not match the manifest")+ source = matching_artifacts[0]+ pure = PurePosixPath(str(source.get("path", "")))+ if pure.is_absolute() or ".." in pure.parts or not pure.parts:+ raise CandidateError("corresponding-source path must be relative and confined")+ destination = (payload_root / pure).resolve()+ try:+ destination.relative_to(payload_root.resolve())+ except ValueError as error:+ raise CandidateError("corresponding-source path escapes payload root") from error+ if destination.suffixes[-2:] != [".tar", ".gz"]:+ raise CandidateError("corresponding-source artifact must use .tar.gz")+ if (payload_root / pure).is_symlink():+ raise CandidateError("corresponding-source artifact must not be a symlink")+ destination.parent.mkdir(parents=True, exist_ok=True)+ with tempfile.TemporaryDirectory(prefix="cua-perception-source-") as temporary:+ raw_tar = Path(temporary) / "source.tar"+ subprocess.run(+ [+ "git", "-C", str(repository_root), "archive", "--format=tar",+ f"--prefix=cua-source-{source_sha}/", "-o", str(raw_tar), source_sha,+ ],+ check=True,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ )+ with raw_tar.open("rb") as source_stream, destination.open("wb") as output_stream:+ with gzip.GzipFile(filename="", mode="wb", fileobj=output_stream, mtime=0) as compressed:+ shutil.copyfileobj(source_stream, compressed)+ if destination.stat().st_size == 0:+ raise CandidateError("generated corresponding-source artifact is empty")+ source["sha256"] = file_digest(destination)+ source["size"] = destination.stat().st_size+ entries = ledger.get("sources", []) if isinstance(ledger, dict) else []+ matching = [entry for entry in entries if entry.get("artifact") == source.get("name")]+ if len(matching) != 1:+ raise CandidateError("source ledger must contain the declared Cua source artifact")+ matching[0].update({+ "artifactSha256": source["sha256"],+ "artifactSize": source["size"],+ "revision": source_sha,+ "sourceOfferStatus": "bundled",+ })+ canonical_json(ledger_path, ledger)+ canonical_json(manifest_path, manifest)+ load_and_validate_manifest(manifest_path, payload_root)+ return destination+++def load_executed_evidence(+ evidence_path: Path, manifest: Mapping[str, Any]+) -> dict[str, Any]:+ evidence = read_json(evidence_path)+ validate_schema(evidence, CONTROL / "executed-verification.schema.json")+ worker = next(item for item in manifest["artifacts"] if item["kind"] == "worker")+ runtime = next(item for item in manifest["artifacts"] if item["kind"] == "runtime")+ expected = {+ "schemaVersion": 1,+ "evidenceKind": "executed",+ "sourceSha": manifest["sourceSha"],+ "target": manifest["target"]["triple"],+ "protocolVersion": manifest["protocol"]["version"],+ "workerSha256": worker["sha256"],+ "runtimeSha256": runtime["sha256"],+ }+ for field, value in expected.items():+ if evidence.get(field) != value:+ raise CandidateError(f"executed evidence {field} differs from candidate")+ gates = evidence.get("gates", [])+ if [item.get("gate") for item in gates] != [+ "health", "self-test", "real-parse", "mismatch-rejection"+ ] or any(item.get("status") != "passed" or item.get("exitCode") != 0 for item in gates):+ raise CandidateError("executed evidence does not contain all passing release gates")+ return evidence+++def spdx_id(value: str) -> str:+ return "SPDXRef-" + re.sub(r"[^A-Za-z0-9.-]", "-", value)+++def generated_documents(+ manifest: Mapping[str, Any], executed_evidence: Mapping[str, Any]+) -> tuple[dict[str, Any], dict[str, Any]]:+ artifacts = sorted(manifest["artifacts"], key=lambda item: (item["kind"], item["name"]))+ namespace_seed = sha256(+ f"{manifest['sourceSha']}:{manifest['target']['triple']}:{manifest['version']}".encode()+ ).hexdigest()+ sbom = {+ "spdxVersion": "SPDX-2.3",+ "dataLicense": "CC0-1.0",+ "SPDXID": "SPDXRef-DOCUMENT",+ "name": f"cua-perception-{manifest['version']}-{manifest['target']['triple']}",+ "documentNamespace": f"https://cua.ai/spdx/cua-perception/{namespace_seed}",+ "creationInfo": {"creators": ["Organization: Cua"], "created": "1970-01-01T00:00:00Z"},+ "packages": [+ {+ "name": "cua-perception",+ "SPDXID": "SPDXRef-Package-cua-perception",+ "versionInfo": manifest["version"],+ "downloadLocation": "NOASSERTION",+ "filesAnalyzed": True,+ "licenseConcluded": "NOASSERTION",+ "licenseDeclared": "NOASSERTION",+ "copyrightText": "NOASSERTION",+ }+ ],+ "files": [+ {+ "fileName": f"./{KIND_DIRECTORIES[item['kind']]}/{item['name']}",+ "SPDXID": spdx_id(f"File-{item['kind']}-{item['name']}"),+ "checksums": [{"algorithm": "SHA256", "checksumValue": item["sha256"]}],+ "licenseConcluded": item["license"]["spdx"],+ "licenseInfoInFiles": [item["license"]["spdx"]],+ "copyrightText": "NOASSERTION",+ }+ for item in artifacts+ ],+ "relationships": [+ {+ "spdxElementId": "SPDXRef-Package-cua-perception",+ "relationshipType": "CONTAINS",+ "relatedSpdxElement": spdx_id(f"File-{item['kind']}-{item['name']}"),+ }+ for item in artifacts+ ],+ }+ provenance = {+ "$schema": "provenance.schema.json",+ "schemaVersion": 1,+ "component": "cua-perception",+ "candidate": True,+ "releaseStatus": "staging-candidate",+ "source": {+ "repository": os.environ.get("GITHUB_REPOSITORY", "trycua/cua"),+ "commit": manifest["sourceSha"],+ },+ "build": {+ "workflow": os.environ.get("GITHUB_WORKFLOW_REF", "local-candidate"),+ "runId": os.environ.get("GITHUB_RUN_ID", "local"),+ "target": manifest["target"]["triple"],+ },+ "evidence": {+ "supplied": [manifest["suppliedVerification"][field] for field in ("health", "selfTest", "realParse")],+ "executed": "metadata/executed-verification.json",+ "executedSha256": sha256(+ (json.dumps(executed_evidence, indent=2, sort_keys=True) + "\n").encode()+ ).hexdigest(),+ },+ "subjects": [+ {"name": item["name"], "digest": {"sha256": item["sha256"]}}+ for item in artifacts+ ],+ "redactions": ["absolutePaths", "environment", "credentials", "runnerIdentity"],+ }+ return sbom, provenance+++def extension_manifest(stage: Path, manifest: Mapping[str, Any], payload_root: Path) -> dict[str, Any]:+ model_ledger = read_json(confined_file(payload_root, manifest["modelLedger"]))+ model_entries = {item["artifact"]: item for item in model_ledger["models"]}+ artifacts = manifest["artifacts"]+ files = []+ for path in sorted(stage.rglob("*"), key=lambda item: item.as_posix()):+ if path.is_file():+ relative = path.relative_to(stage).as_posix()+ files.append({+ "path": relative,+ "sha256": file_digest(path),+ "executable": relative.startswith("bin/"),+ })+ models = []+ notice_bindings = {+ item["path"]: {+ "path": staged_artifact_path(item).as_posix(),+ "sha256": item["sha256"],+ }+ for item in artifacts+ if item["kind"] == "notice"+ }+ for item in artifacts:+ if item["kind"] != "model":+ continue+ ledger = model_entries[item["name"]]+ original = ledger.get("sourceArtifact", {}).get("sha256", item["sha256"])+ models.append({+ "path": f"models/{item['name']}",+ "revision": ledger["revision"],+ "original_sha256": original,+ "conversion_sha256": item["sha256"],+ "license_file": notice_bindings[item["license"]["notice"]],+ })+ components = [+ {+ "name": item["name"],+ "version": manifest["version"],+ "license": item["license"]["spdx"],+ "notice": f"notices/{Path(item['license']['notice']).name}",+ "source_uri": item["license"]["source"],+ "source_revision": manifest["sourceSha"],+ "notice_file": notice_bindings[item["license"]["notice"]],+ }+ for item in artifacts+ if item["kind"] != "notice"+ ]+ source = corresponding_source_artifact(manifest)+ worker = next(item for item in artifacts if item["kind"] == "worker")+ return {+ "schema_version": 1,+ "id": "cua-perception",+ "version": manifest["version"],+ "driver_version": manifest["driverVersion"],+ "protocol_version": manifest["protocol"]["version"],+ "target": manifest["target"]["triple"],+ "entrypoint": f"bin/{worker['name']}",+ "files": files,+ "models": models,+ "components": components,+ "corresponding_source_file": {+ "path": staged_artifact_path(source).as_posix(),+ "sha256": source["sha256"],+ },+ "license": "LicenseRef-Mixed",+ "source": "https://github.com/trycua/cua",+ "corresponding_source_uri": f"source/{source['name']}",+ "corresponding_source_revision": manifest["sourceSha"],+ "provenance": "metadata/provenance.redacted.json",+ "health_args": [+ "--health", "--extension-id", "cua-perception",+ "--extension-version", manifest["version"],+ ],+ "self_test_args": [+ "--self-test", "--extension-id", "cua-perception",+ "--extension-version", manifest["version"],+ ],+ }+++def validate_extension_manifest_bindings(extension: Mapping[str, Any]) -> None:+ declared = {item["path"]: item["sha256"] for item in extension["files"]}++ def validate_binding(label: str, binding: Any) -> None:+ if not isinstance(binding, dict):+ raise CandidateError(f"{label} binding is missing")+ path = binding.get("path")+ digest = binding.get("sha256")+ if declared.get(path) != digest:+ raise CandidateError(f"{label} binding does not match a declared staged file")++ for component in extension["components"]:+ validate_binding(+ f"component {component['name']} notice_file", component.get("notice_file")+ )+ for model in extension["models"]:+ validate_binding(f"model {model['path']} license_file", model.get("license_file"))+ validate_binding("corresponding_source_file", extension.get("corresponding_source_file"))+++def corresponding_source_artifact(manifest: Mapping[str, Any]) -> Mapping[str, Any]:+ matches = [+ item for item in manifest["artifacts"]+ if item["kind"] == "source" and item["name"] == "cua-perception-source.tar.gz"+ ]+ if len(matches) != 1:+ raise CandidateError("candidate must contain one named Cua corresponding-source archive")+ return matches[0]+++def catalog_payload(+ manifest: Mapping[str, Any], archive: Path, manifest_file: Path, key_id: str,+ catalog_version: int, expires_unix: int, next_key: Any,+) -> dict[str, Any]:+ source = corresponding_source_artifact(manifest)+ return {+ "schema_version": 1,+ "catalog_version": catalog_version,+ "expires_unix": expires_unix,+ "publisher_id": "cua",+ "publisher_name": "Cua",+ "key_id": key_id,+ "extension_id": "cua-perception",+ "version": manifest["version"],+ "target": manifest["target"]["triple"],+ "archive": archive.name,+ "archive_size": archive.stat().st_size,+ "archive_sha256": file_digest(archive),+ "manifest_sha256": file_digest(manifest_file),+ "license": "LicenseRef-Mixed",+ "source": "https://github.com/trycua/cua",+ "corresponding_source_uri": f"source/{source['name']}",+ "corresponding_source_revision": manifest["sourceSha"],+ "provenance": "metadata/provenance.redacted.json",+ "next_key": next_key,+ }+++def runtime_contract(manifest: Mapping[str, Any]) -> dict[str, Any]:+ artifacts = manifest["artifacts"]+ binding = lambda item: {+ "name": item["name"],+ **({"role": item["role"]} if item.get("role") else {}),+ "sha256": item["sha256"],+ }+ return {+ "$schema": "runtime-contract.schema.json",+ "schemaVersion": 1,+ "target": manifest["target"]["triple"],+ "protocolVersion": manifest["protocol"]["version"],+ "worker": binding(next(item for item in artifacts if item["kind"] == "worker")),+ "runtime": binding(next(item for item in artifacts if item["kind"] == "runtime")),+ "modelManifest": binding(+ next(item for item in artifacts if item["kind"] == "model-manifest")+ ),+ "models": [binding(item) for item in artifacts if item["kind"] == "model"],+ "dictionary": binding(next(item for item in artifacts if item["kind"] == "dictionary")),+ "rejectMismatch": True,+ }+++def create_archive(stage: Path, destination: Path) -> None:+ with destination.open("wb") as raw:+ with gzip.GzipFile(filename="", mode="wb", fileobj=raw, mtime=0) as compressed:+ with tarfile.open(fileobj=compressed, mode="w") as archive:+ for path in sorted(stage.rglob("*"), key=lambda item: item.as_posix()):+ relative = path.relative_to(stage).as_posix()+ info = archive.gettarinfo(str(path), arcname=relative)+ info.uid = info.gid = 0+ info.uname = info.gname = "root"+ info.mtime = 0+ if info.isfile():+ with path.open("rb") as source:+ archive.addfile(info, source)+ else:+ archive.addfile(info)+++def staged_artifact_path(item: Mapping[str, Any]) -> Path:+ if item["kind"] != "source":+ return Path(KIND_DIRECTORIES[item["kind"]]) / item["name"]+ parts = PurePosixPath(item["path"]).parts+ if "source" in parts:+ tail = parts[parts.index("source") + 1:]+ if tail:+ return Path("source", *tail)+ return Path("source") / item["name"]+++def package_candidate(+ manifest_path: Path, payload_root: Path, output: Path, *,+ executed_evidence_path: Path,+ key_id: str = "cua-extension-ed25519-2026-01",+ catalog_version: int = 1,+ expires_unix: int = 2000000000,+) -> Path:+ trust = read_json(CONTROL / "trust-root.json")+ if key_id != trust.get("activeKeyId"):+ raise CandidateError(f"catalog key id is not the active trust root: {key_id}")+ active_keys = [+ key for key in trust.get("keys", [])+ if key.get("keyId") == key_id and key.get("algorithm") == "Ed25519" and key.get("status") == "active"+ ]+ if len(active_keys) != 1:+ raise CandidateError("active Ed25519 trust root is missing or ambiguous")+ active_key = active_keys[0]+ now = int(time.time())+ if not active_key["validFromUnix"] <= now < active_key["validUntilUnix"]:+ raise CandidateError("active Ed25519 trust root is outside its validity window")+ if catalog_version < 1:+ raise CandidateError("catalog version must be greater than zero")+ if expires_unix <= now:+ raise CandidateError("catalog expiration must be in the future")+ if expires_unix > active_key["validUntilUnix"]:+ raise CandidateError("catalog expiration exceeds the signing key validity window")+ next_key = None+ next_key_id = trust.get("rotation", {}).get("nextKeyId")+ if next_key_id is not None:+ pending = [key for key in trust["keys"] if key.get("keyId") == next_key_id]+ if len(pending) != 1 or pending[0].get("status") != "pending":+ raise CandidateError("pending Ed25519 trust root is missing or ambiguous")+ pending_key = pending[0]+ overlap_seconds = active_key["validUntilUnix"] - pending_key["validFromUnix"]+ minimum_overlap = trust["rotation"]["minimumOverlapDays"] * 86_400+ if overlap_seconds < minimum_overlap:+ raise CandidateError("pending Ed25519 trust root has insufficient overlap")+ next_key = {+ "key_id": pending_key["keyId"],+ "public_key_base64": pending_key["publicKeyBase64"],+ "valid_from_unix": pending_key["validFromUnix"],+ "valid_until_unix": pending_key["validUntilUnix"],+ }+ manifest = load_and_validate_manifest(manifest_path, payload_root)+ executed_evidence = load_executed_evidence(executed_evidence_path, manifest)+ if output.exists() and any(output.iterdir()):+ raise CandidateError(f"candidate output directory must be empty: {output}")+ output.mkdir(parents=True, exist_ok=True)+ with tempfile.TemporaryDirectory(prefix="cua-perception-candidate-") as temporary:+ stage = Path(temporary) / "candidate"+ stage.mkdir()+ for item in manifest["artifacts"]:+ destination = stage / staged_artifact_path(item)+ destination.parent.mkdir(parents=True, exist_ok=True)+ shutil.copyfile(confined_file(payload_root, item["path"]), destination)+ destination.chmod(0o755 if item["kind"] in {"worker", "runtime"} else 0o644)+ for field in ("modelLedger", "sourceLedger"):+ if field in manifest:+ shutil.copyfile(confined_file(payload_root, manifest[field]), stage / f"{field}.json")++ sbom, provenance = generated_documents(manifest, executed_evidence)+ runtime = runtime_contract(manifest)+ canonical_json(stage / "metadata/artifact-manifest.json", manifest)+ canonical_json(stage / "metadata/sbom.spdx.json", sbom)+ canonical_json(stage / "metadata/provenance.redacted.json", provenance)+ canonical_json(stage / "metadata/runtime-contract.json", runtime)+ canonical_json(stage / "metadata/executed-verification.json", executed_evidence)+ validate_schema(sbom, CONTROL / "sbom.schema.json")+ validate_schema(provenance, CONTROL / "provenance.schema.json")+ validate_schema(runtime, CONTROL / "runtime-contract.schema.json")+ extension = extension_manifest(stage, manifest, payload_root)+ validate_extension_manifest_bindings(extension)+ canonical_json(stage / "extension.json", extension)++ archive = output / (+ f"cua-perception-{manifest['version']}-{manifest['target']['triple']}.tar.gz"+ )+ create_archive(stage, archive)+ payload = catalog_payload(+ manifest, archive, stage / "extension.json", key_id, catalog_version, expires_unix,+ next_key,+ )+ validate_schema(payload, CONTROL / "catalog-input.schema.json")+ (output / "catalog-payload.json").write_text(+ json.dumps(payload, separators=(",", ":"), ensure_ascii=False), encoding="utf-8"+ )+ canonical_json(output / "sbom.spdx.json", sbom)+ canonical_json(output / "provenance.redacted.json", provenance)+ canonical_json(output / "runtime-contract.json", runtime)+ checksum_paths = [+ archive,+ output / "catalog-payload.json",+ output / "sbom.spdx.json",+ output / "provenance.redacted.json",+ output / "runtime-contract.json",+ ]+ (output / "checksums.txt").write_text(+ "".join(f"{file_digest(path)} {path.name}\n" for path in checksum_paths),+ encoding="utf-8",+ )+ return archive+++def archive_names(path: Path) -> list[str]:+ if tarfile.is_tarfile(path):+ with tarfile.open(path, "r:*") as archive:+ return archive.getnames()+ if zipfile.is_zipfile(path):+ with zipfile.ZipFile(path) as archive:+ return archive.namelist()+ raise CandidateError(f"unsupported Driver archive: {path}")+++def verify_driver_exclusion(paths: Sequence[Path]) -> None:+ forbidden_suffixes = (".onnx", ".ort", ".gguf", ".safetensors")+ for path in paths:+ for name in archive_names(path):+ lowered = name.lower()+ if (+ "cua-perception" in lowered+ or "/models/" in f"/{lowered.strip('/')}"+ or lowered.endswith(forbidden_suffixes)+ ):+ raise CandidateError(f"Driver archive {path.name} contains Perception payload: {name}")+++def run_candidate_gates(+ manifest_path: Path, payload_root: Path, evidence_path: Path | None = None+) -> dict[str, Any]:+ manifest = load_and_validate_manifest(manifest_path, payload_root)+ worker_item = next(item for item in manifest["artifacts"] if item["kind"] == "worker")+ runtime_item = next(item for item in manifest["artifacts"] if item["kind"] == "runtime")+ worker = confined_file(payload_root, worker_item["path"])+ runtime = confined_file(payload_root, runtime_item["path"])+ worker.chmod(worker.stat().st_mode | stat.S_IXUSR)+ environment = {+ "PATH": os.environ.get("PATH", ""),+ "CUA_PERCEPTION_RUNTIME": str(runtime),+ "CUA_PERCEPTION_RUNTIME_SHA256": runtime_item["sha256"],+ "CUA_PERCEPTION_TARGET": manifest["target"]["triple"],+ }+ executed = []+ identity_arguments = [+ "--extension-id", manifest["component"], "--extension-version", manifest["version"]+ ]+ for gate, arguments in (+ ("health", ["--health"]),+ ("self-test", ["--self-test"]),+ ("real-parse", ["--real-parse-self-test"]),+ ("mismatch-rejection", ["--mismatch-rejection-self-test"]),+ ):+ arguments = [*arguments, *identity_arguments]+ result = subprocess.run(+ [str(worker), *arguments],+ cwd=payload_root,+ env=environment,+ check=False,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ timeout=120,+ )+ if result.returncode != 0:+ raise CandidateError(+ f"executed {gate} gate failed with exit {result.returncode}: "+ f"{result.stderr.decode(errors='replace')[:500]}"+ )+ validate_candidate_gate_output(+ gate, result.stdout, manifest["component"], manifest["version"]+ )+ executed.append({+ "gate": gate,+ "arguments": arguments,+ "status": "passed",+ "exitCode": result.returncode,+ "stdoutSha256": sha256(result.stdout).hexdigest(),+ "stderrSha256": sha256(result.stderr).hexdigest(),+ })+ evidence = {+ "$schema": "executed-verification.schema.json",+ "schemaVersion": 1,+ "evidenceKind": "executed",+ "sourceSha": manifest["sourceSha"],+ "target": manifest["target"]["triple"],+ "protocolVersion": manifest["protocol"]["version"],+ "workerSha256": worker_item["sha256"],+ "runtimeSha256": runtime_item["sha256"],+ "gates": executed,+ }+ validate_schema(evidence, CONTROL / "executed-verification.schema.json")+ if evidence_path is not None:+ canonical_json(evidence_path, evidence)+ return evidence+++def validate_candidate_gate_output(+ gate: str, stdout: bytes, extension_id: str, extension_version: str+) -> None:+ try:+ output = json.loads(stdout)+ except (UnicodeDecodeError, json.JSONDecodeError) as error:+ raise CandidateError(f"executed {gate} gate returned invalid JSON: {error}") from error+ if not isinstance(output, dict):+ raise CandidateError(f"executed {gate} gate returned a non-object response")+ if gate == "mismatch-rejection":+ if output != {"mismatch_rejection": True}:+ raise CandidateError("executed mismatch-rejection gate did not prove hash rejection")+ return+ if output.get("protocol") != "cua-perception/1" or output.get("status") != "ok":+ raise CandidateError(f"executed {gate} gate returned an unsuccessful protocol response")+ result = output.get("result")+ if not isinstance(result, dict):+ raise CandidateError(f"executed {gate} gate omitted its result object")+ identity = result.get("identity")+ extension = identity.get("extension") if isinstance(identity, dict) else None+ expected_identity = {"id": extension_id, "version": extension_version}+ if extension != expected_identity:+ raise CandidateError(+ f"executed {gate} gate reported extension identity {extension!r}; "+ f"expected {expected_identity!r}"+ )+ if gate == "health" and result.get("ready") is not True:+ raise CandidateError("executed health gate did not report ready=true")+ if gate == "self-test" and result.get("passed") is not True:+ raise CandidateError("executed self-test gate did not report passed=true")+ if gate == "real-parse":+ regions = result.get("regions")+ if not isinstance(regions, list) or not regions:+ raise CandidateError("executed real-parse gate did not return any real regions")+++def verify_checksums(checksum_path: Path) -> None:+ seen: set[str] = set()+ for line in checksum_path.read_text(encoding="utf-8").splitlines():+ match = re.fullmatch(r"([0-9a-f]{64}) ([A-Za-z0-9._-]+)", line)+ if not match:+ raise CandidateError("checksum manifest has an invalid entry")+ expected, name = match.groups()+ if name in seen:+ raise CandidateError(f"checksum manifest repeats {name}")+ seen.add(name)+ path = checksum_path.parent / name+ if not path.is_file() or file_digest(path) != expected:+ raise CandidateError(f"checksum verification failed for {name}")+ if not seen:+ raise CandidateError("checksum manifest is empty")+++def main(argv: Sequence[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ subparsers = parser.add_subparsers(dest="command", required=True)+ validate = subparsers.add_parser("validate")+ validate.add_argument("--manifest", type=Path, required=True)+ validate.add_argument("--payload-root", type=Path, required=True)+ package = subparsers.add_parser("package")+ package.add_argument("--manifest", type=Path, required=True)+ package.add_argument("--payload-root", type=Path, required=True)+ package.add_argument("--output", type=Path, required=True)+ package.add_argument("--executed-evidence", type=Path, required=True)+ package.add_argument("--key-id", required=True)+ package.add_argument("--catalog-version", type=int, required=True)+ package.add_argument("--expires-unix", type=int, required=True)+ driver = subparsers.add_parser("verify-driver-exclusion")+ driver.add_argument("archives", nargs="+", type=Path)+ gates = subparsers.add_parser("run-gates")+ gates.add_argument("--manifest", type=Path, required=True)+ gates.add_argument("--payload-root", type=Path, required=True)+ gates.add_argument("--evidence", type=Path, required=True)+ source = subparsers.add_parser("bind-source")+ source.add_argument("--manifest", type=Path, required=True)+ source.add_argument("--payload-root", type=Path, required=True)+ source.add_argument("--repository-root", type=Path, required=True)+ checksums = subparsers.add_parser("verify-checksums")+ checksums.add_argument("checksum_path", type=Path)+ args = parser.parse_args(argv)+ try:+ if args.command == "validate":+ load_and_validate_manifest(args.manifest, args.payload_root)+ print("Cua Perception candidate inputs are valid")+ elif args.command == "package":+ archive = package_candidate(+ args.manifest,+ args.payload_root,+ args.output,+ executed_evidence_path=args.executed_evidence,+ key_id=args.key_id,+ catalog_version=args.catalog_version,+ expires_unix=args.expires_unix,+ )+ print(archive)+ elif args.command == "verify-driver-exclusion":+ verify_driver_exclusion(args.archives)+ print("Driver archives exclude Cua Perception payloads")+ elif args.command == "run-gates":+ run_candidate_gates(args.manifest, args.payload_root, args.evidence)+ print("Executed health, self-test, real-parse, and mismatch-rejection gates")+ elif args.command == "bind-source":+ archive = bind_corresponding_source(+ args.manifest, args.payload_root, args.repository_root+ )+ print(archive)+ else:+ verify_checksums(args.checksum_path)+ print("Candidate checksums are valid")+ except (CandidateError, OSError, ValueError) as error:+ print(f"Cua Perception release error: {error}", file=os.sys.stderr)+ return 1+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/.github/scripts/release_attribution.py b/.github/scripts/release_attribution.pyindex 18dde9820e..41184ae21a 100644--- a/.github/scripts/release_attribution.py+++ b/.github/scripts/release_attribution.py@@ -70,6 +70,16 @@ NOREPLY_RE = re.compile(re.IGNORECASE,)RELEASING_TYPES = {"feat", "fix", "perf", "revert"}+PERCEPTION_OWNED_PATHS = (+ ".github/releases/cua-perception",+ "libs/cua-driver/rust/crates/cua-perception",+ "libs/cua-driver/experiments/cua-perception-inference",+)+PERCEPTION_EXACT_PATHS = ("libs/cua-driver/docs/cua-perception-rust-inference-spike.md",)+PERCEPTION_COMPANION_PATHS = (+ "libs/cua-driver/rust/Cargo.toml",+ "libs/cua-driver/rust/Cargo.lock",+)ALLOWED_TITLE_TYPES = RELEASING_TYPES | {"build","chore",@@ -201,6 +211,7 @@ def commits_in_range(current_tag: str,paths: Sequence[str],exclude_paths: Sequence[str] = (),+ exclude_companion_paths: Sequence[str] = (),) -> list[CommitRecord]:range_spec = f"{previous_tag}..{current_tag}" if previous_tag else current_tagpathspecs = [*paths, *(f":(exclude){path}" for path in exclude_paths)]@@ -209,6 +220,29 @@ def commits_in_range(for commit_sha in shas.splitlines():if not commit_sha:continue+ if exclude_companion_paths:+ changed_files = run_git(+ repo_root,+ "show",+ "--format=",+ "--name-only",+ commit_sha,+ ).splitlines()+ owns_excluded_path = any(+ file == excluded or file.startswith(f"{excluded}/")+ for file in changed_files+ for excluded in exclude_paths+ )+ only_excluded_or_companion = all(+ file in exclude_companion_paths+ or any(+ file == excluded or file.startswith(f"{excluded}/")+ for excluded in exclude_paths+ )+ for file in changed_files+ )+ if owns_excluded_path and only_excluded_or_companion:+ continueraw = run_git(repo_root, "show", "-s", "--format=%s%x00%B", commit_sha)subject, _, body = raw.partition("\x00")records.append(CommitRecord(commit_sha, subject.strip(), body.strip()))@@ -251,6 +285,8 @@ def validate_pr_title(*,require_release: bool = False,allow_non_release: bool = False,+ forbid_any_releasing_title: bool = False,+ pull_body: str = "",) -> None:entry = parse_conventional_line(title)if not entry:@@ -263,6 +299,27 @@ def validate_pr_title(raise ReleaseError(f"unsupported pull request type '{entry.change_type}'; use one of: {allowed}")+ override = OVERRIDE_RE.search(pull_body or "")+ override_entries = (+ [+ parsed+ for line in override.group("body").splitlines()+ if (parsed := parse_conventional_line(line))+ ]+ if override+ else []+ )+ forbidden_entries = [entry, *override_entries]+ if forbid_any_releasing_title and any(+ candidate.change_type in RELEASING_TYPES or candidate.breaking+ for candidate in forbidden_entries+ ):+ raise ReleaseError(+ "Perception changes that also modify shared Cargo metadata cannot use a "+ "releasing or breaking title or commit override because Release Please would "+ "also classify the commit as a Driver release; use an accurate non-releasing "+ "type with the 'no-release' label"+ )if require_release and entry.change_type not in RELEASING_TYPES and not allow_non_release:raise ReleaseError(f"pull request type '{entry.change_type}' makes Release Please skip changes to "@@ -273,6 +330,21 @@ def validate_pr_title()+def is_perception_only_diff(paths: Sequence[str]) -> bool:+ """Return whether the complete diff is Perception-owned plus allowed companions."""+ perception_owned = False+ for path in paths:+ if path in PERCEPTION_EXACT_PATHS or any(+ path == root or path.startswith(f"{root}/") for root in PERCEPTION_OWNED_PATHS+ ):+ perception_owned = True+ continue+ if path in PERCEPTION_COMPANION_PATHS:+ continue+ return False+ return perception_owned++def login_from_email(email: str, overrides: Mapping[str, str]) -> str | None:normalized = email.strip().lower()if normalized in overrides:@@ -871,6 +943,7 @@ def build_manifest(github: GitHubClient,release_ref: str | None = None,exclude_paths: Sequence[str] = (),+ exclude_companion_paths: Sequence[str] = (),asset_dir: Path | None = None,channel: str = "stable",) -> dict[str, Any]:@@ -889,7 +962,14 @@ def build_manifest(all_contributors: list[dict[str, Any]] = []visual_requested = False- for commit in commits_in_range(repo_root, previous_tag, current_ref, paths, exclude_paths):+ for commit in commits_in_range(+ repo_root,+ previous_tag,+ current_ref,+ paths,+ exclude_paths,+ exclude_companion_paths,+ ):if (re.match(r"^chore(?:\([^)]+\))?: release\b", commit.subject, re.IGNORECASE)or LEGACY_RELEASE_BUMP_RE.match(commit.subject)@@ -1183,6 +1263,7 @@ def collect_command(args: argparse.Namespace) -> None:github=client,release_ref=args.ref,exclude_paths=args.exclude_path,+ exclude_companion_paths=args.exclude_companion_path,asset_dir=args.asset_dir.resolve() if args.asset_dir else None,channel=args.channel,)@@ -1271,6 +1352,11 @@ def build_parser() -> argparse.ArgumentParser:validate.add_argument("--title", required=True)validate.add_argument("--require-release", action="store_true")validate.add_argument("--allow-non-release", action="store_true")+ validate.add_argument("--forbid-any-releasing-title", action="store_true")+ validate.add_argument("--pull-body", default="")++ classify = subparsers.add_parser("classify-perception-diff")+ classify.add_argument("--path", action="append", default=[])validate_pr = subparsers.add_parser("validate-pr")validate_pr.add_argument("--event", type=Path, required=True)@@ -1291,6 +1377,7 @@ def build_parser() -> argparse.ArgumentParser:collect.add_argument("--sha", required=True)collect.add_argument("--path", action="append", required=True)collect.add_argument("--exclude-path", action="append", default=[])+ collect.add_argument("--exclude-companion-path", action="append", default=[])collect.add_argument("--changelog", type=Path, required=True)collect.add_argument("--config", type=Path, default=Path(".github/release-attribution-config.json")@@ -1318,8 +1405,12 @@ def main(argv: Sequence[str] | None = None) -> int:args.title,require_release=args.require_release,allow_non_release=args.allow_non_release,+ forbid_any_releasing_title=args.forbid_any_releasing_title,+ pull_body=args.pull_body,)print("release title is valid")+ elif args.command == "classify-perception-diff":+ print("true" if is_perception_only_diff(args.path) else "false")elif args.command == "validate-pr":validate_pr_command(args)elif args.command == "collect":diff --git a/.github/scripts/release_channels.py b/.github/scripts/release_channels.pyindex 74eda7d020..38507dc86e 100644--- a/.github/scripts/release_channels.py+++ b/.github/scripts/release_channels.py@@ -105,10 +105,30 @@ def load_registry(for site in sites:if not repository_path(root, str(site["path"])).is_file():raise ChannelError(f"component {name} version site does not exist: {site['path']}")+ exclude_paths = component.get("changeDetectionExcludePaths", [])+ if not isinstance(exclude_paths, list) or not all(+ isinstance(value, str) for value in exclude_paths+ ):+ raise ChannelError(+ f"component {name} changeDetectionExcludePaths must be a list of paths"+ )+ for excluded_path in exclude_paths:+ repository_path(root, excluded_path)+ companion_paths = component.get("changeDetectionCompanionPaths", [])+ if not isinstance(companion_paths, list) or not all(+ isinstance(value, str) for value in companion_paths+ ):+ raise ChannelError(+ f"component {name} changeDetectionCompanionPaths must be a list of paths"+ )+ for companion_path in companion_paths:+ repository_path(root, companion_path)channels = component["channels"]- if channels != {"nightly": True, "registries": []}:+ expected_nightly = not bool(component.get("candidateOnly", False))+ if channels != {"nightly": expected_nightly, "registries": []}:raise ChannelError(- f"component {name} v1 channels must enable nightly and declare no registries"+ f"component {name} channels must set nightly={expected_nightly} "+ "and declare no registries")release_config = read_json(root / "release-please-config.json")@@ -412,12 +432,21 @@ def nightly_attribution_preflight(previous_tag: str | None,source_ref: str,paths: Sequence[str],+ exclude_paths: Sequence[str],+ exclude_companion_paths: Sequence[str],config_path: Path,) -> list[dict[str, str]]:"""Find unresolved squash-generated coauthors before an expensive build."""try:config = read_json(config_path)- commits = release_attribution.commits_in_range(root, previous_tag, source_ref, paths)+ commits = release_attribution.commits_in_range(+ root,+ previous_tag,+ source_ref,+ paths,+ exclude_paths,+ exclude_companion_paths,+ )return release_attribution.unresolved_coauthor_identities(commits, config)except release_attribution.ReleaseError as error:raise ChannelError(f"nightly attribution preflight failed: {error}") from error@@ -438,6 +467,8 @@ def plan_nightly(if not SHA_RE.fullmatch(source_sha):raise ChannelError(f"source SHA must be 40 lowercase hex characters: {source_sha!r}")component = component_descriptor(name, registry_path, root=root)+ if not component["channels"]["nightly"]:+ raise ChannelError(f"component {name} does not enable nightly publication")base = (repository_path(root, component["versionAuthorityFile"]).read_text(encoding="utf-8").strip())@@ -466,14 +497,43 @@ def plan_nightly(paths = list(component["changeDetectionPaths"])paths.extend(load_registry(registry_path, root=root)["sharedChangePaths"])paths = sorted(set(str(path) for path in paths))+ exclude_paths = sorted(+ set(str(path) for path in component.get("changeDetectionExcludePaths", []))+ )+ exclude_companion_paths = sorted(+ set(str(path) for path in component.get("changeDetectionCompanionPaths", []))+ )if force:should_build, reason = True, "forced"+ elif previous_sha is None and exclude_companion_paths:+ commits = release_attribution.commits_in_range(+ root,+ attribution_base_tag,+ source_sha,+ paths,+ exclude_paths,+ exclude_companion_paths,+ )+ should_build = bool(commits)+ reason = "first-nightly" if should_build else "component-unchanged"elif previous_sha is None:should_build, reason = True, "first-nightly"elif previous_sha == source_sha:should_build, reason = False, "source-unchanged"+ elif exclude_companion_paths:+ commits = release_attribution.commits_in_range(+ root,+ previous_tag,+ source_sha,+ paths,+ exclude_paths,+ exclude_companion_paths,+ )+ should_build = bool(commits)+ reason = "relevant-changes" if should_build else "component-unchanged"else:- changed = _git(root, "diff", "--name-only", previous_sha, source_sha, "--", *paths)+ pathspecs = [*paths, *(f":(exclude){path}" for path in exclude_paths)]+ changed = _git(root, "diff", "--name-only", previous_sha, source_sha, "--", *pathspecs)should_build = bool(changed)reason = "relevant-changes" if should_build else "component-unchanged"attribution_issues: list[dict[str, str]] = []@@ -483,6 +543,8 @@ def plan_nightly(previous_tag=attribution_base_tag,source_ref=source_sha,paths=paths,+ exclude_paths=exclude_paths,+ exclude_companion_paths=exclude_companion_paths,config_path=attribution_config_path,)if attribution_issues:@@ -541,6 +603,12 @@ def build_manifest(*(str(path) for path in registry["sharedChangePaths"]),})+ exclude_paths = sorted(+ set(str(path) for path in component.get("changeDetectionExcludePaths", []))+ )+ exclude_companion_paths = sorted(+ set(str(path) for path in component.get("changeDetectionCompanionPaths", []))+ )config_path = attribution_config_path or root / ".github/release-attribution-config.json"client = github or release_attribution.GitHubClient(os.environ.get("GH_TOKEN", ""),@@ -557,6 +625,8 @@ def build_manifest(previous_tag=previous_tag,expected_sha=source_sha,paths=paths,+ exclude_paths=exclude_paths,+ exclude_companion_paths=exclude_companion_paths,changelog_path=repository_path(root, component["changelog"]),attribution_config=read_json(config_path),github=client,diff --git a/.github/scripts/resolve_release_please_request.py b/.github/scripts/resolve_release_please_request.pyindex 397dd204ea..003c9a3b2f 100644--- a/.github/scripts/resolve_release_please_request.py+++ b/.github/scripts/resolve_release_please_request.py@@ -11,6 +11,7 @@ from typing import AnyCOMPONENT_PATHS = {+ "cua-perception": "libs/cua-driver/rust/crates/cua-perception","cua-driver-rs": "libs/cua-driver","lume": "libs/lume","sandbox": "libs/python/cua-sandbox",diff --git a/.github/scripts/tests/release_please_perception_preview.cjs b/.github/scripts/tests/release_please_perception_preview.cjsnew file mode 100644index 0000000000..abfa150302--- /dev/null+++ b/.github/scripts/tests/release_please_perception_preview.cjs@@ -0,0 +1,106 @@+// Offline: exercise the candidate-only Perception stream with pinned Release Please.+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const { buildStrategy } = require('release-please/build/src/factory');+const { parseConventionalCommits } = require('release-please/build/src/commit');+const { CommitExclude } = require('release-please/build/src/util/commit-exclude');+const { CommitSplit } = require('release-please/build/src/util/commit-split');+const { TagName } = require('release-please/build/src/util/tag-name');++const root = path.resolve(__dirname, '../../..');+const config = JSON.parse(fs.readFileSync(path.join(root, 'release-please-config.json')));+const manifest = JSON.parse(fs.readFileSync(path.join(root, '.release-please-manifest.json')));+const perceptionPath = 'libs/cua-driver/rust/crates/cua-perception';+const driverPath = 'libs/cua-driver';+const perceptionConfig = config.packages[perceptionPath];+const releaseConfigs = Object.fromEntries(Object.entries(config.packages).map(+ ([packagePath, packageConfig]) => [packagePath, {+ excludePaths: packageConfig['exclude-paths'],+ }],+));+const commitSplit = new CommitSplit({packagePaths: Object.keys(config.packages)});+const commitExclude = new CommitExclude(releaseConfigs);++function commit(message, files, shaByte) {+ return { sha: shaByte.repeat(40), message, files };+}++async function main() {+ const workerCommit = commit('feat(cua-perception): add offline visual parsing', [+ 'libs/cua-driver/rust/crates/cua-perception/src/main.rs',+ ], 'a');+ const lumeCommit = commit('feat(lume): add guest support', [+ 'libs/lume/Sources/LumeCLI/main.swift',+ ], 'b');+ const driverCommit = commit('feat(cua-driver): add input support', [+ 'libs/cua-driver/rust/crates/cua-driver/src/main.rs',+ ], 'c');+ const topLevelCommit = commit('docs: refresh repository readme', ['README.md'], 'd');+ const filtered = commitExclude.excludeCommits(commitSplit.split([+ workerCommit,+ lumeCommit,+ driverCommit,+ topLevelCommit,+ ]));+ assert.deepEqual(filtered[perceptionPath], [workerCommit]);+ assert.deepEqual(filtered[driverPath], [driverCommit]);+ assert.equal(filtered[perceptionPath].includes(lumeCommit), false);+ assert.equal(filtered[perceptionPath].includes(driverCommit), false);+ assert.equal(filtered[perceptionPath].includes(topLevelCommit), false);++ const exampleOnly = commit('docs(cua-driver): update example', [+ 'libs/cua-driver/examples/agent-sdks/README.md',+ ], 'e');+ assert.deepEqual(+ commitExclude.excludeCommits(commitSplit.split([exampleOnly]))[driverPath],+ [],+ );++ const options = Object.fromEntries(+ Object.entries({ ...config, ...perceptionConfig })+ .map(([key, value]) => [key.replace(/-([a-z])/g, (_, c) => c.toUpperCase()), value])+ );+ const strategy = await buildStrategy({+ ...options,+ path: perceptionPath,+ targetBranch: 'main',+ github: { repository: { owner: 'example', repo: 'repo', defaultBranch: 'main' } },+ });+ const release = await strategy.buildReleasePullRequest(+ parseConventionalCommits(filtered[perceptionPath]),+ {+ tag: TagName.parse(`cua-perception-v${manifest[perceptionPath]}`),+ sha: 'f'.repeat(40),+ notes: '',+ },+ );+ assert.notEqual(release, undefined);+ assert.equal(release.version.toString(), '0.2.0');+ assert.equal(perceptionConfig['skip-github-release'], true);+ assert.equal(perceptionConfig.component, 'cua-perception');+ assert.equal(perceptionConfig['version-file'], 'VERSION');+ assert.equal(perceptionConfig['changelog-path'], 'CHANGELOG.md');+ assert.deepEqual(+ release.updates.map(update => update.path).sort(),+ [+ 'libs/cua-driver/rust/crates/cua-perception/CHANGELOG.md',+ 'libs/cua-driver/rust/crates/cua-perception/Cargo.toml',+ 'libs/cua-driver/rust/crates/cua-perception/VERSION',+ ].sort(),+ );+ assert.equal(release.updates.some(update => update.path.includes('..')), false);++ const sharedCargoCommit = commit('feat(cua-perception): update protocol', [+ 'libs/cua-driver/rust/crates/cua-perception/src/main.rs',+ 'libs/cua-driver/rust/Cargo.toml',+ 'libs/cua-driver/rust/Cargo.lock',+ ], '1');+ const shared = commitExclude.excludeCommits(commitSplit.split([sharedCargoCommit]));+ assert.equal(shared[driverPath].length, 1);+ assert.equal(shared[perceptionPath].length, 1);++ console.log('release-please 17.3.0 scopes Perception and stages only crate-local updates');+}++main().catch(error => { console.error(error); process.exitCode = 1; });diff --git a/.github/scripts/tests/test_authorized_live_jev_macos_evidence.py b/.github/scripts/tests/test_authorized_live_jev_macos_evidence.pynew file mode 100644index 0000000000..503295da84--- /dev/null+++ b/.github/scripts/tests/test_authorized_live_jev_macos_evidence.py@@ -0,0 +1,11 @@+from pathlib import Path+++ROOT = Path(__file__).resolve().parents[3]+MACOS_ENTRY = ROOT / ".github/workflows/e2e-rust-macos.yml"+++def test_direct_lume_certification_stays_outside_actions() -> None:+ text = MACOS_ENTRY.read_text(encoding="utf-8")+ assert "run-all.sh --standalone-browser" not in text+ assert "authorized-live-jev-macos-evidence.yml" not in textdiff --git a/.github/scripts/tests/test_authorized_live_jev_use_demo.py b/.github/scripts/tests/test_authorized_live_jev_use_demo.pynew file mode 100644index 0000000000..7788b9e5f3--- /dev/null+++ b/.github/scripts/tests/test_authorized_live_jev_use_demo.py@@ -0,0 +1,529 @@+"""Static security contracts for the review-gated live Jev visual demo."""++from pathlib import Path+import re+import unittest++import yaml+++ROOT = Path(__file__).resolve().parents[3]+WORKFLOW = ROOT / ".github/workflows/authorized-live-jev-use-demo.yml"+ORCHESTRATOR = (+ ROOT / "libs/cua-driver/rust/crates/cua-driver/tests/authorized_live_jev_use_demo_test.rs"+)+EVIDENCE_README = ROOT / "libs/cua-driver/tests/perception-demo/README.md"+++class AuthorizedLiveDemoWorkflowTests(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.text = WORKFLOW.read_text()+ cls.orchestrator = ORCHESTRATOR.read_text()+ cls.evidence_readme = EVIDENCE_README.read_text()+ cls.workflow = yaml.safe_load(cls.text)+ cls.triggers = cls.workflow.get("on", cls.workflow.get(True))+ cls.jobs = cls.workflow["jobs"]++ def test_is_manual_or_callable_with_open_source_head_and_merged_jev_commit(self):+ self.assertEqual(set(self.triggers), {"workflow_dispatch", "workflow_call"})+ dispatch_inputs = self.triggers["workflow_dispatch"]["inputs"]+ callable_inputs = self.triggers["workflow_call"]["inputs"]+ self.assertEqual(dispatch_inputs, callable_inputs)+ self.assertNotRegex(self.text, r"(?m)^\s*inputs:\s*[&*]")+ for trigger in self.triggers.values():+ self.assertEqual(+ set(trigger["inputs"]),+ {+ "run_live",+ "source_pr_number",+ "source_sha",+ "jev_pr_number",+ "jev_source_sha",+ "signed_candidate_artifact_id",+ "signed_candidate_run_id",+ "windows_e2e_run_id",+ "linux_e2e_run_id",+ },+ )+ self.assertTrue(all(value["required"] for value in trigger["inputs"].values()))+ self.assertEqual(trigger["inputs"]["run_live"]["type"], "boolean")+ source = self.jobs["source"]["steps"][0]["run"]+ self.assertIn('[[ "$RUN_LIVE_ACKNOWLEDGED" == true ]]', source)+ self.assertEqual(+ self.jobs["source"]["steps"][0]["env"]["RUN_LIVE_ACKNOWLEDGED"],+ "${{ inputs.run_live }}",+ )+ self.assertIn('validate_pr_head "$SOURCE_PR_NUMBER"', source)+ self.assertIn('validate_merged_pr "$JEV_PR_NUMBER"', source)+ self.assertNotIn("CANONICAL_JEV_MERGE_SHA", self.text)+ self.assertIn('[[ "$requested" == "$head_sha" ]]', source)+ self.assertIn('"$head_repo" == "$GITHUB_REPOSITORY"', source)+ self.assertIn('[[ "$state" == closed && "$merged" == true', source)+ self.assertIn('"$requested" == "$merge_sha"', source)+ self.assertNotIn("merge-base --is-ancestor", source)+ self.assertNotIn("pull_request_target", self.text)+ self.assertIn('[[ "$run_id" == "$CANDIDATE_RUN_ID" ]]', source)+ self.assertIn("STAGING-cua-perception-review-candidates-$REQUESTED_SHA", source)+ self.assertIn(".github/workflows/review-cua-perception-candidates.yml", source)+ self.assertIn('.event <<<"$run_json")" == pull_request', source)+ self.assertIn('[[ "$EVENT_ACTION" == labeled', source)+ self.assertIn('"$EVENT_PR_NUMBER" == "$SOURCE_PR_NUMBER"', source)+ self.assertIn('"$EVENT_HEAD_SHA" == "$REQUESTED_SHA"', source)+ self.assertIn('"$EVENT_LABEL" == cua-perception-live-review', source)+ self.assertIn('"$run_id" == "$GITHUB_RUN_ID"', source)+ self.assertIn('"$GITHUB_EVENT_NAME" == workflow_dispatch', source)+ self.assertIn('.status <<<"$run_json")" == in_progress', source)+ self.assertIn('.status <<<"$run_json")" == completed', source)+ download = next(+ step+ for step in self.jobs["live"]["steps"]+ if "download-artifact" in step.get("uses", "")+ )+ self.assertEqual(download["with"]["run-id"], "${{ needs.source.outputs.candidate_run_id }}")+ self.assertIn("d3f86a106a0bac45b974a628896c90dbdf5c8093", download["uses"])++ def test_artifact_is_source_bound_and_verified_by_actual_driver_trust(self):+ source = self.jobs["source"]["steps"][0]["run"]+ for contract in (+ "actions/artifacts/$CANDIDATE_ARTIFACT_ID",+ ".workflow_run.head_sha",+ "candidate artifact is expired",+ ".conclusion",+ ):+ self.assertIn(contract, source)+ live_text = "\n".join(step.get("run", "") for step in self.jobs["live"]["steps"])+ self.assertIn("extension inspect cua-perception --catalog", live_text)+ self.assertIn("extension install cua-perception --catalog", live_text)+ self.assertIn("extension status cua-perception --self-test --json", live_text)+ self.assertIn(+ 'catalog["signature_algorithm"] == measured["signature_algorithm"] == "ed25519"',+ live_text,+ )+ self.assertIn('status["trust"] == "review-only-publisher-verified"', live_text)+ self.assertIn('digest == files[model["path"]] == model["conversion_sha256"]', live_text)+ self.assertNotIn("--allow-unsigned-local", live_text)+ self.assertNotRegex(live_text, r"--archive\s+[^\n]+--catalog")++ def test_canonical_runs_are_attested_before_protected_live_job(self):+ self.assertEqual(+ set(self.jobs),+ {"source", "mock-preflight", "live"},+ )+ preflights = "\n".join(str(self.jobs[name]) for name in ("source", "mock-preflight"))+ self.assertNotIn("environment", preflights)+ self.assertNotIn("TYPESAFE_API_KEY", preflights)+ self.assertEqual(self.jobs["live"]["environment"], "authorized-live-jev-use-demo")+ self.assertEqual(self.jobs["live"]["env"]["CUA_E2E_UNRESTRICTED_GUI"], "1")+ self.assertEqual(+ set(self.jobs["live"]["needs"]),+ {"source", "mock-preflight"},+ )+ source = self.jobs["source"]["steps"][0]["run"]+ mock = "\n".join(step.get("run", "") for step in self.jobs["mock-preflight"]["steps"])+ self.assertIn("python3-tk", mock)+ self.assertIn("libx11-dev", mock)+ self.assertIn("libwebkit2gtk-4.1-dev", mock)+ self.assertLess(mock.index("python3-tk"), mock.index("test_fixture.py"))+ self.assertIn(".github/workflows/e2e-rust-windows.yml", source)+ self.assertIn("rust-windows-e2e-certification", source)+ self.assertIn(".github/workflows/e2e-rust-linux.yml", source)+ self.assertIn("rust-linux-e2e-certification", source)+ self.assertNotIn("run-rust-e2e", self.text)++ def test_live_matrix_uses_review_candidates_and_orchestrator_supports_macos(self):+ matrix = self.jobs["live"]["strategy"]["matrix"]["include"]+ self.assertEqual(+ {item["platform"]: item["runner"] for item in matrix},+ {+ "windows": "windows-latest",+ "linux-x11": "ubuntu-latest",+ },+ )+ self.assertEqual(+ {item["platform"]: item["driver"] for item in matrix},+ {"windows": "review-cua-driver.exe", "linux-x11": "review-cua-driver"},+ )+ self.assertIn('target_os = "macos"', self.orchestrator)+ self.assertIn('#[cfg(any(target_os = "linux", target_os = "macos"))]', self.orchestrator)+ shared = self.orchestrator.index(".arg(fixture_path())")+ self.assertGreater(shared, self.orchestrator.index('Command::new("py")'))+ self.assertGreater(shared, self.orchestrator.index('Command::new("python3")'))++ def test_live_paths_use_private_windows_extension_home_and_runner_temp_evidence(self):+ live_env = self.jobs["live"]["env"]+ self.assertNotIn("CUA_PERCEPTION_EXTENSION_HOME", live_env)+ self.assertNotIn("CUA_PERCEPTION_EVIDENCE_DIR", live_env)+ self.assertNotIn("CUA_E2E_RECORDINGS_ROOT", live_env)+ steps = self.jobs["live"]["steps"]+ configure = next(+ step for step in steps if step.get("name") == "Configure temporary evidence paths"+ )+ self.assertIn(+ '$extensionHomeName = "cua-perception-extension-home-$($env:GITHUB_RUN_ID)-$($env:GITHUB_RUN_ATTEMPT)"',+ configure["run"],+ )+ self.assertIn("$userProfile = [IO.Path]::GetFullPath($env:USERPROFILE)", configure["run"])+ self.assertIn(+ "$userProfileItem.Attributes -band [IO.FileAttributes]::ReparsePoint", configure["run"]+ )+ self.assertIn(+ "[IO.Path]::GetDirectoryName($extensionHome) -ne $userProfile", configure["run"]+ )+ self.assertIn(+ "if (Test-Path -LiteralPath $extensionHome) { throw 'Windows extension home must be fresh' }",+ configure["run"],+ )+ self.assertIn("New-Item -ItemType Directory -Path $extensionHome", configure["run"])+ self.assertIn(+ "$extensionHomeItem.Attributes -band [IO.FileAttributes]::ReparsePoint",+ configure["run"],+ )+ self.assertNotIn("LOCALAPPDATA", configure["run"])+ self.assertIn(+ "$extensionHome = Join-Path $env:RUNNER_TEMP 'cua-perception-extension-home/live'",+ configure["run"],+ )+ self.assertIn(+ '"CUA_PERCEPTION_EXTENSION_HOME=$extensionHome" >> $env:GITHUB_ENV', configure["run"]+ )+ self.assertIn('"CUA_DRIVER_RS_HOME=$extensionHome" >> $env:GITHUB_ENV', configure["run"])+ self.assertIn(+ "CUA_E2E_RECORDINGS_ROOT=$(Join-Path $env:RUNNER_TEMP 'cua-perception-recordings')",+ configure["run"],+ )+ self.assertIn(+ "CUA_PERCEPTION_EVIDENCE_DIR=$(Join-Path $env:RUNNER_TEMP 'cua-perception-evidence/live')",+ configure["run"],+ )+ self.assertNotIn("if", configure)+ mock = next(step for step in steps if "deterministic mock" in step.get("name", ""))+ live = next(step for step in steps if "bounded live Jev chooser" in step.get("name", ""))+ self.assertLess(steps.index(configure), steps.index(mock))+ self.assertLess(steps.index(configure), steps.index(live))+ self.assertEqual(+ {item["platform"] for item in self.jobs["live"]["strategy"]["matrix"]["include"]},+ {"windows", "linux-x11"},+ )+ self.assertNotRegex(+ self.text,+ r"CUA_PERCEPTION_EXTENSION_HOME[^\n]*github\.workspace",+ )+ self.assertNotRegex(+ self.text,+ r"CUA_E2E_RECORDINGS_ROOT[^\n]*github\.workspace",+ )+ self.assertNotIn("github.workspace", configure["run"])+ self.assertFalse(any("${{ runner." in value for value in live_env.values()))++ def test_live_linux_desktop_persists_and_is_rechecked_before_demos(self):+ steps = self.jobs["live"]["steps"]+ prepare = next(step for step in steps if step.get("name") == "Prepare Linux X11 desktop")+ self.assertEqual(prepare["if"], "runner.os == 'Linux'")+ self.assertRegex(prepare["run"], r"apt-get install[^\n]*\bx11-utils\b")+ self.assertLess(prepare["run"].index("x11-utils"), prepare["run"].index("xdpyinfo"))+ for daemon in ("Xvfb", "dbus-daemon", "openbox", "picom"):+ self.assertRegex(+ prepare["run"],+ rf"nohup env -u RUNNER_TRACKING_ID[^\n]*(?:\n[^\n]*)?\b{re.escape(daemon)}\b",+ )+ self.assertIn("cua-linux-desktop.pids", prepare["run"])+ self.assertIn("xprop -root _NET_SUPPORTING_WM_CHECK _NET_CLIENT_LIST", prepare["run"])+ self.assertIn("^_NET_SUPPORTING_WM_CHECK(WINDOW): window id # 0x", prepare["run"])+ self.assertIn("^_NET_CLIENT_LIST(WINDOW):", prepare["run"])+ self.assertIn("dbus-send --session", prepare["run"])+ self.assertIn("dump_desktop_state", prepare["run"])+ for name in ("xvfb", "dbus", "openbox", "picom"):+ self.assertIn(f"$RUNNER_TEMP/{name}.log", prepare["run"])++ verify = next(+ step+ for step in steps+ if step.get("name") == "Verify Linux X11 desktop survived setup steps"+ )+ mock = next(step for step in steps if "deterministic mock" in step.get("name", ""))+ self.assertEqual(verify["if"], "runner.os == 'Linux'")+ self.assertLess(steps.index(verify), steps.index(mock))+ self.assertIn("kill -0", verify["run"])+ self.assertIn("xprop -root _NET_SUPPORTING_WM_CHECK _NET_CLIENT_LIST", verify["run"])+ self.assertIn("^_NET_SUPPORTING_WM_CHECK(WINDOW): window id # 0x", verify["run"])+ self.assertIn("^_NET_CLIENT_LIST(WINDOW):", verify["run"])+ self.assertIn("dbus-send --session", verify["run"])+ self.assertIn("dump_desktop_state", verify["run"])++ stop = next(step for step in steps if step.get("name") == "Stop Linux X11 desktop")+ cleanup = next(+ step+ for step in steps+ if step.get("name") == "Remove plaintext evidence from the runner"+ )+ self.assertEqual(stop["if"], "always() && runner.os == 'Linux'")+ self.assertLess(steps.index(stop), steps.index(cleanup))+ self.assertIn("/proc/$pid/comm", stop["run"])+ self.assertIn('kill "$pid"', stop["run"])++ def test_external_chooser_receives_only_the_key_and_windows_system_root(self):+ start = self.orchestrator.index("fn external_choice(")+ end = self.orchestrator.index("fn choose(", start)+ external = self.orchestrator[start:end]+ self.assertIn(".env_clear()", external)+ self.assertIn('.env("TYPESAFE_API_KEY", required("TYPESAFE_API_KEY"))', external)+ self.assertIn('command.env("SYSTEMROOT", system_root)', external)+ self.assertEqual(external.count(".env("), 2)++ def test_review_driver_is_consumed_from_hash_bound_aggregate(self):+ live_text = "\n".join(step.get("run", "") for step in self.jobs["live"]["steps"])+ self.assertIn("review-measurements.json", live_text)+ self.assertIn('measured["review_driver_sha256"]', live_text)+ self.assertIn(+ 'measured["review_driver_build_profile"] == "debug-review-trust-root"', live_text+ )+ self.assertIn("CUA_TEST_DRIVER_BIN", live_text)+ self.assertIn("signed-candidate-checksums.txt", live_text)+ self.assertIn('measured["code_signing"] == {"status": "not-applicable"', live_text)+ self.assertNotIn("cargo build --manifest-path", live_text)+ self.assertNotIn("target/release/cua-driver", live_text)+ self.assertNotIn("RSA-SHA256", self.evidence_readme)+ self.assertIn("Ed25519", self.evidence_readme)+ self.assertIn("debug review-trust-root", self.evidence_readme)++ def test_only_measured_binary_receives_typesafe_secret_in_one_bounded_step(self):+ secret = next(+ step for step in self.jobs["live"]["steps"] if "secrets.TYPESAFE_API_KEY" in str(step)+ )+ self.assertEqual(+ sum("secrets.TYPESAFE_API_KEY" in str(step) for step in self.jobs["live"]["steps"]),+ 1,+ )+ self.assertEqual(secret["timeout-minutes"], 15)+ self.assertEqual(+ secret["env"],+ {+ "GH_TOKEN": "${{ github.token }}",+ "LIVE_TYPESAFE_API_KEY": "${{ secrets.TYPESAFE_API_KEY }}",+ },+ )+ self.assertNotIn("cargo ", secret["run"])+ self.assertIn("CUA_LIVE_TEST_BINARY_SHA256", secret["run"])+ self.assertIn("Remove-Item Env:LIVE_TYPESAFE_API_KEY", secret["run"])+ self.assertIn("Remove-Item Env:TYPESAFE_API_KEY", secret["run"])+ self.assertIn("pulls/$sourcePrNumber", secret["run"])+ self.assertIn("pulls/$jevPrNumber", secret["run"])+ self.assertIn("$jevReview.state -ne 'closed'", secret["run"])+ self.assertIn("$jevReview.merged -ne $true", secret["run"])+ self.assertIn("$jevReview.head.repo.full_name -ne $env:GITHUB_REPOSITORY", secret["run"])+ self.assertIn(+ "$jevReview.merge_commit_sha -ne '${{ needs.source.outputs.jev_sha }}'", secret["run"]+ )+ self.assertNotIn("$jevReview.head.sha", secret["run"])+ self.assertIn("cua-perception-live-review", secret["run"])+ self.assertIn("Remove-Item Env:GH_TOKEN", secret["run"])+ self.assertIn(+ "& $env:CUA_LIVE_TEST_BINARY --ignored --exact $env:CUA_LIVE_WINDOW_TEST",+ secret["run"],+ )+ self.assertIn(+ "& $env:CUA_LIVE_TEST_BINARY --ignored --exact $env:CUA_LIVE_DESKTOP_TEST",+ secret["run"],+ )+ compile_step = next(+ step+ for step in self.jobs["live"]["steps"]+ if step.get("name", "").startswith("Compile and measure")+ )+ self.assertIn("--no-run --message-format=json", compile_step["run"])+ self.assertIn('name.endswith(f"::{short_name}")', compile_step["run"])+ self.assertIn("assert len(matches) == 1", compile_step["run"])+ self.assertIn("re.fullmatch", compile_step["run"])+ self.assertIn('resolve("authorized_visual_only_window_demo")', compile_step["run"])+ self.assertIn('resolve("authorized_visual_only_primary_desktop_demo")', compile_step["run"])+ self.assertIn("CUA_LIVE_WINDOW_TEST={window_test}", compile_step["run"])+ self.assertIn("CUA_LIVE_DESKTOP_TEST={desktop_test}", compile_step["run"])++ def test_chooser_is_exact_fixed_and_fails_closed_when_absent(self):+ live = self.jobs["live"]+ checkout = next(+ step+ for step in live["steps"]+ if step.get("name") == "Check out the exact reviewed Jev chooser"+ )+ self.assertEqual(checkout["with"]["ref"], "${{ needs.source.outputs.jev_sha }}")+ setup = next(+ step+ for step in live["steps"]+ if step.get("name", "").startswith("Install the locked reviewed chooser")+ )+ self.assertIn("python/choose_action.py", setup["run"])+ self.assertIn("uv sync --frozen --project", setup["run"])+ self.assertIn("reviewed live chooser contract is unavailable", setup["run"])+ secret = next(step for step in live["steps"] if "secrets.TYPESAFE_API_KEY" in str(step))+ self.assertIn("CUA_JEV_CHOOSER_PROGRAM", secret["run"])+ self.assertIn("CUA_JEV_CHOOSER_SCRIPT", secret["run"])+ self.assertNotIn("Invoke-Expression", self.text)+ self.assertNotIn("bash -c", secret["run"])++ def test_mock_has_no_chooser_or_key(self):+ mock = next(+ step+ for step in self.jobs["live"]["steps"]+ if "deterministic mock" in step.get("name", "")+ )+ self.assertEqual(+ mock["env"],+ {+ "CUA_JEV_MOCK_DEMO": "1",+ "CUA_PERCEPTION_EVIDENCE_DIR": "${{ runner.temp }}/perception-evidence/mock",+ "CUA_TEST_DRIVER_STDERR": "1",+ },+ )+ self.assertNotIn("CHOOSER", str(mock))+ self.assertNotIn("TYPESAFE", str(mock))+ self.assertIn("--exact $env:CUA_LIVE_WINDOW_TEST", mock["run"])+ self.assertIn("--exact $env:CUA_LIVE_DESKTOP_TEST", mock["run"])++ def test_only_encrypted_schema_validated_evidence_is_uploaded(self):+ uploads = [+ step for step in self.jobs["live"]["steps"] if "upload-artifact" in step.get("uses", "")+ ]+ self.assertEqual(len(uploads), 1)+ upload = uploads[0]+ self.assertEqual(upload["with"]["path"], "${{ runner.temp }}/encrypted-evidence/")+ validate_step = next(+ step+ for step in self.jobs["live"]["steps"]+ if step.get("name", "").startswith("Fully decode")+ )+ validate = validate_step["run"]+ self.assertIn("ffmpeg -v error -xerror", validate)+ self.assertIn("Draft202012Validator(schema).validate(manifest)", validate)+ self.assertIn(+ 'assert sorted(path.name for path in destination.iterdir()) == ["manifest.json", "recording.mp4"]',+ validate,+ )+ self.assertIn('"window": (evidence, "window", "get_window_state", "background")', validate)+ self.assertIn(+ '"primary-desktop": (evidence / "primary-desktop", "desktop", "get_desktop_state", "foreground")',+ validate,+ )+ self.assertIn("destination = output / scope", validate)+ self.assertIn(+ 'assert sorted(path.name for path in output.iterdir()) == ["primary-desktop", "window"]',+ validate,+ )+ self.assertIn(+ 'perception["signed_extension_archive_sha256"] == measured["archive_sha256"]', validate+ )+ self.assertIn('driver = runtime["driver"]', validate)+ self.assertIn('observation = manifest["observation"]', validate)+ self.assertIn('manifest["environment"] ==', validate)+ self.assertIn('perception["models"] == measured["models"]', validate)+ self.assertIn('chooser["model_id"]', validate)+ self.assertIn('chooser["mode"] == "live"', validate)+ self.assertIn('chooser["provider"] == "typesafe"', validate)+ self.assertIn('recording_value["frame_rate"]', validate)+ self.assertIn('recording_value["edit_operations"]', validate)+ encrypt_step = next(+ step+ for step in self.jobs["live"]["steps"]+ if step.get("name") == "Encrypt the validated evidence bundles"+ )+ self.assertEqual(+ encrypt_step["env"],+ {+ "CUA_PERCEPTION_EVIDENCE_RECIPIENT": (+ "${{ vars.EVIDENCE_ARCHIVE_RECIPIENT_PUBLIC_KEY }}"+ )+ },+ )+ self.assertEqual(+ sum(+ "vars.EVIDENCE_ARCHIVE_RECIPIENT_PUBLIC_KEY" in str(step)+ for step in self.jobs["live"]["steps"]+ ),+ 1,+ )+ self.assertNotIn("EVIDENCE_ARCHIVE_KEY", self.text)+ self.assertNotIn("private-key", self.text)+ self.assertIn("evidence_envelope.py encrypt", encrypt_step["run"])+ self.assertIn("--recipient-env CUA_PERCEPTION_EVIDENCE_RECIPIENT", encrypt_step["run"])+ self.assertIn("^recipient_public_key_sha256=[0-9a-f]{64}$", encrypt_step["run"])+ self.assertIn('Write-Host "$scope $fingerprint"', encrypt_step["run"])+ self.assertIn("Remove-Item Env:CUA_PERCEPTION_EVIDENCE_RECIPIENT", encrypt_step["run"])+ self.assertIn('== ["primary-desktop.cuae", "window.cuae"]', encrypt_step["run"])+ self.assertNotIn("CUA_PERCEPTION_EVIDENCE_RECIPIENT", validate)+ steps = self.jobs["live"]["steps"]+ cleanup = next(+ step+ for step in steps+ if step.get("name") == "Remove plaintext evidence from the runner"+ )+ self.assertLess(steps.index(validate_step), steps.index(encrypt_step))+ self.assertLess(steps.index(encrypt_step), steps.index(upload))+ self.assertLess(steps.index(upload), steps.index(cleanup))+ self.assertEqual(cleanup["if"], "always()")+ for directory in (+ "cua-perception-recordings",+ "cua-perception-evidence",+ "perception-evidence",+ "publish-evidence",+ ):+ self.assertIn(f"'{directory}'", cleanup["run"])+ self.assertIn(+ "-not [string]::IsNullOrWhiteSpace($env:CUA_PERCEPTION_EXTENSION_HOME)", cleanup["run"]+ )+ self.assertIn(+ "$expectedExtensionHome = [IO.Path]::GetFullPath((Join-Path $userProfile $extensionHomeName))",+ cleanup["run"],+ )+ self.assertIn("$extensionHome -ne $expectedExtensionHome", cleanup["run"])+ self.assertIn(+ "[IO.Path]::GetDirectoryName($extensionHome) -ne $userProfile", cleanup["run"]+ )+ self.assertIn("try {", cleanup["run"])+ self.assertIn("} finally {", cleanup["run"])+ self.assertLess(cleanup["run"].index("try {"), cleanup["run"].index("} finally {"))+ self.assertLess(+ cleanup["run"].index("} finally {"),+ cleanup["run"].index("$runnerTemp = [IO.Path]::GetFullPath"),+ )+ self.assertIn(+ "$extensionHomeItem.Attributes -band [IO.FileAttributes]::ReparsePoint", cleanup["run"]+ )+ self.assertIn("Remove-Item -LiteralPath $expectedExtensionHome -Force", cleanup["run"])+ self.assertIn(+ "Remove-Item -LiteralPath $expectedExtensionHome -Recurse -Force", cleanup["run"]+ )+ reparse = cleanup["run"].index(+ "$extensionHomeItem.Attributes -band [IO.FileAttributes]::ReparsePoint"+ )+ unlink = cleanup["run"].index("Remove-Item -LiteralPath $expectedExtensionHome -Force")+ recursive = cleanup["run"].index(+ "Remove-Item -LiteralPath $expectedExtensionHome -Recurse -Force"+ )+ self.assertLess(reparse, unlink)+ self.assertLess(unlink, recursive)+ self.assertNotIn("Remove-Item -Path $env:CUA_PERCEPTION_EXTENSION_HOME", cleanup["run"])+ self.assertNotIn("@'", cleanup["run"])+ self.assertNotIn("python - $env:RUNNER_TEMP", cleanup["run"])+ self.assertIn("$runnerTemp = [IO.Path]::GetFullPath($env:RUNNER_TEMP)", cleanup["run"])+ self.assertIn(+ "$runnerTempItem.Attributes -band [IO.FileAttributes]::ReparsePoint", cleanup["run"]+ )+ self.assertIn("[IO.Path]::GetDirectoryName($target) -ne $runnerTemp", cleanup["run"])+ self.assertIn("Remove-Item -LiteralPath $target -Force", cleanup["run"])+ self.assertIn("Remove-Item -LiteralPath $target -Recurse -Force", cleanup["run"])+ self.assertNotIn("publish-evidence", str(upload))+ self.assertNotIn("manifest.json", str(upload))+ self.assertNotIn("recording.mp4", str(upload))+ self.assertNotIn("raw-manifest.json", str(upload))+ self.assertNotIn("timeline.json", str(upload))++ def test_all_actions_are_full_sha_pinned(self):+ uses = re.findall(r"^\s*-?\s*uses:\s*([^\s#]+)", self.text, re.MULTILINE)+ self.assertTrue(uses)+ for action in uses:+ self.assertRegex(action, r"^[^@]+@[0-9a-f]{40}$")+++if __name__ == "__main__":+ unittest.main()diff --git a/.github/scripts/tests/test_cua_driver_default_distribution.py b/.github/scripts/tests/test_cua_driver_default_distribution.pynew file mode 100644index 0000000000..bac4d9b310--- /dev/null+++ b/.github/scripts/tests/test_cua_driver_default_distribution.py@@ -0,0 +1,80 @@+from pathlib import Path+import re+++ROOT = Path(__file__).resolve().parents[3]+WORKFLOW = ROOT / ".github/workflows/cd-rust-cua-driver.yml"+PERCEPTION_WORKFLOW = ROOT / ".github/workflows/ci-cua-perception-release.yml"+UNIX_INSTALLER = ROOT / "libs/cua-driver/scripts/_install-rust.sh"+WINDOWS_INSTALLER = ROOT / "libs/cua-driver/scripts/install.ps1"++FORBIDDEN_DISTRIBUTION_TOKENS = (+ "cua-perception",+ "onnxruntime",+ ".onnx",+ ".ort",+ "signed-catalog",+ "catalog-payload",+ "agpl",+)++REQUIRED_DRIVER_PACKAGES = frozenset(+ ("cua-driver", "cursor-theme-cli", "cua-driver-sdk")+)+ALLOWED_BUILD_PACKAGE_SETS = (+ REQUIRED_DRIVER_PACKAGES,+ REQUIRED_DRIVER_PACKAGES | {"cua-driver-uia"},+)+++def _cargo_build_packages(command: str) -> frozenset[str]:+ return frozenset(+ match.group(1)+ for match in re.finditer(r"(?:^|\s)(?:-p|--package)(?:\s+|=)([\w-]+)", command)+ )+++def test_driver_package_commands_only_stage_driver_runtime() -> None:+ source = WORKFLOW.read_text()+ build_commands = [line for line in source.splitlines() if "cargo build" in line]+ package_commands = [+ line+ for line in source.splitlines()+ if re.search(r"\b(cp|tar|Copy-Item|Compress-Archive)\b", line)+ ]++ assert build_commands+ assert package_commands+ for command in build_commands:+ assert not re.search(r"(?:^|\s)(?:--workspace|--all)(?:\s|$)", command)+ packages = _cargo_build_packages(command)+ assert REQUIRED_DRIVER_PACKAGES <= packages+ assert packages in ALLOWED_BUILD_PACKAGE_SETS+ assert all(+ token not in line.lower()+ for line in package_commands+ for token in FORBIDDEN_DISTRIBUTION_TOKENS+ )+++def test_dependency_graph_gate_runs_for_driver_manifest_changes() -> None:+ source = PERCEPTION_WORKFLOW.read_text()++ assert source.count(' - "libs/cua-driver/rust/**/Cargo.toml"') == 2+ assert source.count(' - "libs/cua-driver/rust/Cargo.lock"') == 2+ assert "cargo tree --locked -p cua-driver --edges normal,build --prefix none" in source+ assert "grep -q '^cua-perception v'" in source+ assert ".github/scripts/tests/test_cua_driver_default_distribution.py" in source+ assert ".github/scripts/tests/test_verify_cua_driver_release_archives.py" in source+++def test_ordinary_installers_have_no_optional_perception_download_path() -> None:+ for installer in (UNIX_INSTALLER, WINDOWS_INSTALLER):+ source = installer.read_text(encoding="utf-8-sig").lower()+ assert all(token not in source for token in FORBIDDEN_DISTRIBUTION_TOKENS), installer++ unix = UNIX_INSTALLER.read_text()+ windows = WINDOWS_INSTALLER.read_text(encoding="utf-8-sig")+ assert "releases/download/${TAG}/$tarball" in unix+ assert '"cua-driver-rs-$version-$archLabel.zip"' in windows+ assert "releases/download/$Script:CuaDriverRsReleaseTag/$zipName" in windowsdiff --git a/.github/scripts/tests/test_cua_driver_release_wiring.py b/.github/scripts/tests/test_cua_driver_release_wiring.pyindex 1aba4ad564..2169e144aa 100644--- a/.github/scripts/tests/test_cua_driver_release_wiring.py+++ b/.github/scripts/tests/test_cua_driver_release_wiring.py@@ -837,6 +837,33 @@ fiworkflow,)+ def test_full_archive_packaging_requires_repository_license(self) -> None:+ workflow = self.read(".github/workflows/cd-rust-cua-driver.yml")+ self.assertTrue((REPO_ROOT / "LICENSE.md").is_file())++ job_boundaries = (+ ("build-linux", "build-windows"),+ ("build-windows", "verify-windows-node-runtime"),+ ("build-macos-universal", "build-hyprland-plugin-source"),+ )+ expected_copies = (+ 'cp ../../../LICENSE.md "release/${STAGE}/LICENSE"',+ 'Copy-Item "../../../LICENSE.md" "release/$stage/LICENSE" -ErrorAction Stop',+ 'cp ../../../LICENSE.md "release/${STAGE}/LICENSE"',+ )+ for (job, next_job), expected_copy in zip(job_boundaries, expected_copies):+ with self.subTest(job=job):+ job_block = workflow.split(f" {job}:\n", 1)[1].split(+ f"\n {next_job}:\n", 1+ )[0]+ package_block = job_block.split(" - name: Package\n", 1)[1].split(+ "\n - uses: actions/upload-artifact", 1+ )[0]+ self.assertIn(expected_copy, package_block)+ self.assertNotIn("2>/dev/null", package_block)+ self.assertNotIn("|| true", package_block)+ self.assertNotIn("Test-Path", package_block)+def test_driver_release_blocks_on_packaged_mcp_client_discovery(self) -> None:workflow = self.read(".github/workflows/cd-rust-cua-driver.yml")ci_workflow = self.read(@@ -887,10 +914,10 @@ fiself.assertEqual(len(expected["baseTools"]), len(set(expected["baseTools"])))- self.assertEqual(len(expected["baseTools"]), 56)+ self.assertEqual(len(expected["baseTools"]), 58)self.assertEqual(expected["outputSchemaCountByPlatform"],- {"darwin": 34, "linux": 38, "win32": 34},+ {"darwin": 35, "linux": 39, "win32": 35},)self.assertEqual(expected["platformTools"],diff --git a/.github/scripts/tests/test_cua_perception_pr_review_trigger.py b/.github/scripts/tests/test_cua_perception_pr_review_trigger.pynew file mode 100644index 0000000000..c908e997d2--- /dev/null+++ b/.github/scripts/tests/test_cua_perception_pr_review_trigger.py@@ -0,0 +1,177 @@+"""Static security contracts for the labeled candidate live review chain."""++from pathlib import Path+import re++import yaml+++ROOT = Path(__file__).resolve().parents[3]+TRIGGER = ROOT / ".github/workflows/review-cua-perception-candidates.yml"+CANDIDATE = ROOT / ".github/workflows/cd-cua-perception-review-supplied-inputs.yml"+LIVE = ROOT / ".github/workflows/authorized-live-jev-use-demo.yml"+MACOS_ENTRY = ROOT / ".github/workflows/e2e-rust-macos.yml"+++def load_workflow(path: Path) -> tuple[str, dict]:+ text = path.read_text(encoding="utf-8")+ workflow = yaml.safe_load(text)+ assert isinstance(workflow, dict)+ return text, workflow+++def triggers(workflow: dict) -> dict:+ return workflow.get("on", workflow.get(True))+++def test_trigger_is_only_labeled_pull_request() -> None:+ text, workflow = load_workflow(TRIGGER)+ assert triggers(workflow) == {+ "pull_request": {"types": ["labeled"]},+ }+ assert "workflow_dispatch" not in text+ assert "pull_request_target" not in text+ assert "push:" not in text+++def test_unlabelled_and_unrelated_pull_requests_skip_before_any_runner() -> None:+ _, workflow = load_workflow(TRIGGER)+ condition = workflow["jobs"]["resolve"]["if"]+ assert "github.event.pull_request.number == 3943" not in condition+ assert "github.event.pull_request.draft == true" not in condition+ assert "github.event.pull_request.head.repo.full_name == github.repository" in condition+ assert "github.event.pull_request.state == 'open'" in condition+ assert "github.event.label.name == 'cua-perception-live-review'" in condition+ assert "synchronize" not in condition+ assert workflow["concurrency"]["cancel-in-progress"] is True+ assert workflow["concurrency"]["group"] == (+ "cua-perception-live-review-${{ github.event.pull_request.number }}"+ )+++def test_gate_revalidates_the_current_labeled_head_for_any_pull_request() -> None:+ text, workflow = load_workflow(TRIGGER)+ gate = workflow["jobs"]["resolve"]["steps"][0]["run"]+ for contract in (+ '[[ "$GITHUB_REPOSITORY" == "trycua/cua" ]]',+ '[[ "$EVENT_PR_NUMBER" =~ ^[1-9][0-9]*$ ]]',+ '[[ "$(jq -r .state <<<"$pr_json")" == "open" ]]',+ '[[ "$(jq -r .head.repo.full_name <<<"$pr_json")" == "$GITHUB_REPOSITORY" ]]',+ '[[ "$(jq -r .head.sha <<<"$pr_json")" == "$EVENT_HEAD_SHA" ]]',+ '.labels | any(.name == "cua-perception-live-review")',+ 'echo "source_pr_number=$EVENT_PR_NUMBER" >> "$GITHUB_OUTPUT"',+ ):+ assert contract in gate+ assert "3943" not in gate+ assert "3916" not in gate+ assert "jev" not in gate.lower()+ assert '[[ "$(jq -r .draft <<<"$pr_json")" == "true" ]]' not in gate+ assert "secrets." not in text+ assert workflow["permissions"] == {+ "actions": "read",+ "contents": "read",+ "pull-requests": "read",+ }+ assert workflow["jobs"]["candidate"]["permissions"] == {+ "actions": "read",+ "contents": "read",+ "pull-requests": "read",+ }+ assert workflow["jobs"]["resolve"]["outputs"]["source_pr_number"] == (+ "${{ steps.resolve.outputs.source_pr_number }}"+ )+ assert "jev_source_sha" not in text+++def test_review_candidate_executes_release_gates_instead_of_synthesizing_evidence() -> None:+ text, _ = load_workflow(CANDIDATE)+ assert "perception_release.py run-gates" in text+ assert "--evidence executed-verification.json" in text+ assert "assembler:worker-protocol:" not in text+++def test_candidate_is_callable_uses_pinned_reviewed_artifact_and_returns_artifact_id() -> None:+ text, workflow = load_workflow(CANDIDATE)+ candidate_triggers = triggers(workflow)+ assert set(candidate_triggers) == {"workflow_dispatch", "workflow_call"}+ assert "reviewed_model_asset_id" not in candidate_triggers["workflow_call"]["inputs"]+ assert 'REVIEWED_ARTIFACT_ID: "10582583541"' in text+ assert 'REVIEWED_RUN_ID: "35438356263"' in text+ assert 'REVIEWED_SOURCE_ASSET_ID: "571471639"' in text+ assert "expected exactly one reviewed model in producer artifact" in text+ assert "CUA_REVIEWED_MODEL_ASSET_ID" in text+ assert "Number(process.env.CUA_REVIEWED_MODEL_ASSET_ID)" in text+ assert "${{ env.CUA_REVIEWED_MODEL_ASSET_ID }}" not in text+ assert "PERCEPTION_ED25519_PRIVATE_KEY_BASE64" not in text+ assert "${{ secrets." not in text+ assert not any("environment" in job for job in workflow["jobs"].values())+ output = candidate_triggers["workflow_call"]["outputs"]["signed_candidate_artifact_id"]+ assert output["value"] == "${{ jobs.aggregate.outputs.signed_candidate_artifact_id }}"+ run_output = candidate_triggers["workflow_call"]["outputs"]["producer_run_id"]+ assert run_output["value"] == "${{ jobs.aggregate.outputs.producer_run_id }}"+ aggregate = workflow["jobs"]["aggregate"]+ assert aggregate["outputs"]["signed_candidate_artifact_id"] == (+ "${{ steps.upload.outputs.artifact-id }}"+ )+++def test_pr_review_produces_candidates_without_entering_the_protected_environment() -> None:+ trigger_text, workflow = load_workflow(TRIGGER)+ assert set(workflow["jobs"]) == {"resolve", "candidate"}+ candidate = workflow["jobs"]["candidate"]+ assert candidate["uses"] == ("./.github/workflows/cd-cua-perception-review-supplied-inputs.yml")+ assert candidate["permissions"]["contents"] == "read"+ assert candidate["with"] == {+ "source_pr_number": "${{ needs.resolve.outputs.source_pr_number }}",+ "source_sha": "${{ needs.resolve.outputs.source_sha }}",+ "catalog_version": "${{ needs.resolve.outputs.catalog_version }}",+ "expires_unix": "${{ needs.resolve.outputs.expires_unix }}",+ }+ assert "secrets" not in candidate+ assert "authorized-live-jev-use-demo.yml" not in trigger_text+ assert "secrets: inherit" not in trigger_text+ assert "${{ secrets." not in trigger_text+ assert not re.findall(r"^\s*([\w-]+):\s*write\s*$", trigger_text, re.MULTILINE)+ assert not re.findall(r"^\s*environment:", trigger_text, re.MULTILINE)+++def test_protected_live_workflow_owns_secrets_and_environment() -> None:+ live_text, live_workflow = load_workflow(LIVE)+ live_job = live_workflow["jobs"]["live"]+ assert live_job["environment"] == "authorized-live-jev-use-demo"+ secret_steps = [step for step in live_job["steps"] if "${{ secrets." in str(step)]+ assert len(secret_steps) == 1+ typesafe_step = next(+ step for step in secret_steps if "LIVE_TYPESAFE_API_KEY" in step.get("env", {})+ )+ assert typesafe_step["env"] == {+ "GH_TOKEN": "${{ github.token }}",+ "LIVE_TYPESAFE_API_KEY": "${{ secrets.TYPESAFE_API_KEY }}",+ }+ evidence_step = next(+ step+ for step in live_job["steps"]+ if "CUA_PERCEPTION_EVIDENCE_RECIPIENT" in step.get("env", {})+ )+ assert evidence_step["env"] == {+ "CUA_PERCEPTION_EVIDENCE_RECIPIENT": ("${{ vars.EVIDENCE_ARCHIVE_RECIPIENT_PUBLIC_KEY }}"),+ }+ assert "EVIDENCE_ARCHIVE_KEY" not in live_text+ assert "TYPESAFE_API_KEY" not in "\n".join(+ str(job) for name, job in live_workflow["jobs"].items() if name != "live"+ )+ validation = next(+ step["run"] for step in live_job["steps"] if step.get("name", "").startswith("Fully decode")+ )+ assert 'chooser["mode"] == "live"' in validation+ assert 'chooser["provider"] == "typesafe"' in validation+++def test_macos_direct_lume_registration_is_manual_and_not_pr_event_chained() -> None:+ _, workflow = load_workflow(TRIGGER)+ assert "macos" not in workflow["jobs"]+ entry_text, entry_workflow = load_workflow(MACOS_ENTRY)+ assert set(triggers(entry_workflow)) == {"workflow_dispatch"}+ assert "pull_request:" not in entry_text and "pull_request_target" not in entry_text+ assert "live-jev-perception" not in entry_workflow["jobs"]+ assert "authorized-live-jev-macos-evidence.yml" not in entry_textdiff --git a/.github/scripts/tests/test_cua_perception_release_topology.py b/.github/scripts/tests/test_cua_perception_release_topology.pynew file mode 100644index 0000000000..af99b3ea60--- /dev/null+++ b/.github/scripts/tests/test_cua_perception_release_topology.py@@ -0,0 +1,800 @@+from __future__ import annotations++from hashlib import sha256+import importlib.util+import io+import json+from pathlib import Path+import subprocess+import tarfile++import pytest+from jsonschema import Draft202012Validator, ValidationError+import yaml+++ROOT = Path(__file__).resolve().parents[3]+CONTROL = ROOT / ".github/releases/cua-perception"+VERSION_AUTHORITY = ROOT / "libs/cua-driver/rust/crates/cua-perception/VERSION"+SPEC = importlib.util.spec_from_file_location(+ "perception_release", ROOT / ".github/scripts/perception_release.py"+)+assert SPEC and SPEC.loader+release = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(release)+++def digest(data: bytes) -> str:+ return sha256(data).hexdigest()+++def fixture(tmp_path: Path) -> tuple[Path, Path]:+ payload = tmp_path / "payload-root"+ values = {+ "payload/worker": b"""#!/bin/sh+[ -f fail-gates ] && exit 7+version="$5"+[ -f wrong-identity ] && version="9.9.9"+case "$1" in+ --health) printf '{"protocol":"cua-perception/1","status":"ok","result":{"ready":true,"identity":{"extension":{"id":"cua-perception","version":"%s"}}}}\n' "$version";;+ --self-test) printf '{"protocol":"cua-perception/1","status":"ok","result":{"passed":true,"identity":{"extension":{"id":"cua-perception","version":"%s"}}}}\n' "$version";;+ --real-parse-self-test) printf '{"protocol":"cua-perception/1","status":"ok","result":{"regions":[{"id":"fixture-region"}],"identity":{"extension":{"id":"cua-perception","version":"%s"}}}}\n' "$version";;+ --mismatch-rejection-self-test) printf '{"mismatch_rejection":true}\n';;+ *) exit 2;;+esac+""",+ "payload/libonnxruntime.so": b"runtime-v1\n",+ "payload/NOTICE": b"Apache-2.0 notice\n",+ "payload/model.onnx": b"model\n",+ "payload/ocr-det.onnx": b"ocr-det\n",+ "payload/ocr-rec.onnx": b"ocr-rec\n",+ "payload/ocr-dictionary.txt": b"a\nb\n",+ "payload/review.mp4": b"review-recording\n",+ }+ source_buffer = io.BytesIO()+ with tarfile.open(fileobj=source_buffer, mode="w:gz") as source_archive:+ source_bytes = b"fixture source\n"+ source_info = tarfile.TarInfo("fixture/AGENTS.md")+ source_info.size = len(source_bytes)+ source_archive.addfile(source_info, io.BytesIO(source_bytes))+ values["payload/source.tar.gz"] = source_buffer.getvalue()+ model_manifest = {+ "schema_version": 1,+ "identity": {+ "name": "fixture",+ "version": "1",+ "source_url": "fixture",+ "source_revision": "fixture",+ "license": "Apache-2.0",+ },+ "onnx_runtime": {+ "version": "1",+ "library_sha256": digest(values["payload/libonnxruntime.so"]),+ "intra_threads": 1,+ },+ "detector": {+ "model": {+ "path": "models/fixture-model.onnx",+ "sha256": digest(values["payload/model.onnx"]),+ },+ "input_name": "images",+ "output_name": "output0",+ "input_width": 32,+ "input_height": 32,+ "confidence_threshold": 0.3,+ "iou_threshold": 0.1,+ "output_layout": "yolo_v8_cxcywh_class_scores",+ },+ "ocr": {+ "detector": {+ "model": {+ "path": "models/ocr-det.onnx",+ "sha256": digest(values["payload/ocr-det.onnx"]),+ },+ "input_name": "x",+ "output_name": "out",+ "input_width": 32,+ "input_height": 32,+ "pixel_threshold": 0.3,+ "box_threshold": 0.6,+ "unclip_ratio": 1.5,+ "minimum_area": 1,+ "max_candidates": 10,+ },+ "recognizer": {+ "model": {+ "path": "models/ocr-rec.onnx",+ "sha256": digest(values["payload/ocr-rec.onnx"]),+ },+ "input_name": "x",+ "output_name": "out",+ "input_width": 32,+ "input_height": 16,+ "blank_index": 0,+ },+ "dictionary": {+ "path": "models/ocr-dictionary.txt",+ "sha256": digest(values["payload/ocr-dictionary.txt"]),+ },+ "dictionary_format": "plain_lines",+ },+ }+ values["payload/model-manifest.json"] = (json.dumps(model_manifest) + "\n").encode()+ for relative, content in values.items():+ path = payload / relative+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(content)+ target = {"triple": "x86_64-unknown-linux-gnu", "os": "linux", "arch": "x86_64"}+ artifacts = []+ for kind, name, relative in (+ ("worker", "cua-perception-worker", "payload/worker"),+ ("runtime", "libonnxruntime.so", "payload/libonnxruntime.so"),+ ("notice", "NOTICE", "payload/NOTICE"),+ ("model", "fixture-model.onnx", "payload/model.onnx"),+ ("model", "ocr-det.onnx", "payload/ocr-det.onnx"),+ ("model", "ocr-rec.onnx", "payload/ocr-rec.onnx"),+ ("dictionary", "ocr-dictionary.txt", "payload/ocr-dictionary.txt"),+ ("model-manifest", "model-manifest.json", "payload/model-manifest.json"),+ ("source", "cua-perception-source.tar.gz", "payload/source.tar.gz"),+ ("review-recording", "linux-review.mp4", "payload/review.mp4"),+ ):+ content = values[relative]+ item = {+ "kind": kind,+ "name": name,+ "path": relative,+ "sha256": digest(content),+ "size": len(content),+ "license": {+ "spdx": "Apache-2.0",+ "source": "https://github.com/trycua/cua",+ "notice": "payload/NOTICE",+ },+ }+ if kind in {"worker", "runtime"}:+ item.update({"target": target, "protocolVersion": 1})+ roles = {+ "fixture-model.onnx": "icon-detect",+ "ocr-det.onnx": "ocr-detect",+ "ocr-rec.onnx": "ocr-recognize",+ "ocr-dictionary.txt": "ocr-dictionary",+ }+ if name in roles:+ item["role"] = roles[name]+ artifacts.append(item)+ worker_hash = digest(values["payload/worker"])+ runtime_hash = digest(values["payload/libonnxruntime.so"])+ verification = {}+ for gate, field in (+ ("health", "health"),+ ("self-test", "selfTest"),+ ("real-parse", "realParse"),+ ):+ relative = f"verification/{gate}.json"+ report = {+ "$schema": "verification-report.schema.json",+ "schemaVersion": 1,+ "evidenceKind": "supplied",+ "gate": gate,+ "status": "passed",+ "target": target["triple"],+ "protocolVersion": 1,+ "extensionId": "cua-perception",+ "extensionVersion": VERSION_AUTHORITY.read_text().strip(),+ "workerSha256": worker_hash,+ "runtimeSha256": runtime_hash,+ }+ if gate == "real-parse":+ report.update({"fixtureSha256": "f" * 64, "observations": 1})+ if gate == "self-test":+ report["mismatchRejectionPassed"] = True+ report_bytes = (json.dumps(report) + "\n").encode()+ report_path = payload / relative+ report_path.parent.mkdir(parents=True, exist_ok=True)+ report_path.write_bytes(report_bytes)+ artifacts.append(+ {+ "kind": "supplied-verification-report",+ "role": gate,+ "name": f"{gate}.json",+ "path": relative,+ "sha256": digest(report_bytes),+ "size": len(report_bytes),+ "license": {+ "spdx": "CC0-1.0",+ "source": "generated test evidence",+ "notice": "payload/NOTICE",+ },+ }+ )+ verification[field] = relative+ ledgers = {+ "model-ledger.json": {+ "$schema": "model-ledger.schema.json",+ "schemaVersion": 1,+ "models": [+ {+ "artifact": name,+ "artifactSha256": digest(values[relative]),+ "artifactSize": len(values[relative]),+ "origin": "fixture",+ "revision": "model-v1",+ "license": "Apache-2.0",+ "redistributionAllowed": True,+ "verificationStatus": "release-verified",+ "exportSource": "fixture exporter",+ }+ for name, relative in (+ ("fixture-model.onnx", "payload/model.onnx"),+ ("ocr-det.onnx", "payload/ocr-det.onnx"),+ ("ocr-rec.onnx", "payload/ocr-rec.onnx"),+ )+ ],+ },+ "source-ledger.json": {+ "$schema": "source-ledger.schema.json",+ "schemaVersion": 1,+ "sources": [+ {+ "artifact": "cua-perception-source.tar.gz",+ "artifactSha256": digest(values["payload/source.tar.gz"]),+ "artifactSize": len(values["payload/source.tar.gz"]),+ "repository": "https://github.com/trycua/cua",+ "revision": "a" * 40,+ "license": "Apache-2.0",+ "durableLocation": "candidate archive source/",+ "sourceOfferStatus": "bundled",+ "contentKind": "cua-source",+ "format": "tar.gz",+ "requiredPaths": ["AGENTS.md"],+ }+ ],+ },+ }+ for name, ledger in ledgers.items():+ (payload / name).write_text(json.dumps(ledger))+ manifest = {+ "$schema": "artifact-manifest.schema.json",+ "schemaVersion": 1,+ "component": "cua-perception",+ "version": VERSION_AUTHORITY.read_text().strip(),+ "driverVersion": ">=0.28.2",+ "sourceSha": "a" * 40,+ "target": target,+ "protocol": {"name": "cua-perception-worker", "version": 1},+ "artifacts": artifacts,+ "modelLedger": "model-ledger.json",+ "sourceLedger": "source-ledger.json",+ "suppliedVerification": verification,+ }+ manifest_path = payload / "release-input.json"+ manifest_path.write_text(json.dumps(manifest))+ return payload, manifest_path+++def test_templates_and_schemas_are_valid_and_pin_known_models() -> None:+ for document_name, schema_name in (+ ("release-input.template.json", "artifact-manifest.schema.json"),+ ("model-ledger.template.json", "model-ledger.schema.json"),+ ("source-ledger.template.json", "source-ledger.schema.json"),+ ):+ document = json.loads((CONTROL / document_name).read_text())+ schema = json.loads((CONTROL / schema_name).read_text())+ Draft202012Validator(schema).validate(document)+ models = json.loads((CONTROL / "model-ledger.template.json").read_text())["models"]+ serialized = json.dumps(models)+ for expected in (+ "6600256cb0f1b07651e3bc86166196307bad7e2d",+ "dab3d4351ad00b035db829909a4db98354d5a90f6990e4ac00222a9a95d4bf57",+ "d8a876bf7f9fb73d7da9432904ade7fa78e092e9a91674e5a2806b45562a9ab2",+ "e6f4fa85f00e168c862bc462aebca69eef9b3d3d",+ "a431985659dc921974177a95adcfbb90fd9e51989a5e04d70d0b75f597b6e61d",+ "3fafbc3b5dcf93dd72add9f48368be8a3a2cd33b",+ "b5f833dfc5d0eb71da397b4efa06ebeee9b431b690a47d6af40d77d8eabc557f",+ ):+ assert expected in serialized+ assert models[0]["license"] == "AGPL-3.0-only"+ assert models[0]["verificationStatus"] == "license-review-required"+ platforms = json.loads((CONTROL / "platform-inputs.json").read_text())+ platform_validator = Draft202012Validator(+ json.loads((CONTROL / "platform-inputs.schema.json").read_text())+ )+ platform_validator.validate(platforms)+ assert [item["triple"] for item in platforms["platforms"]] == [+ "x86_64-unknown-linux-gnu",+ "aarch64-apple-darwin",+ "x86_64-pc-windows-msvc",+ ]+ assert all(item["modelManifest"] == "model-manifest.json" for item in platforms["platforms"])+ artifact_lock = json.loads(+ (+ ROOT / "libs/cua-driver/rust/crates/cua-perception/scripts/artifacts.lock.json"+ ).read_text()+ )+ locked_targets = artifact_lock["onnx_runtime"]["targets"]+ assert all(item["triple"] in locked_targets for item in platforms["platforms"])+ macos = next(item for item in platforms["platforms"] if item["os"] == "macos")+ assert (macos["arch"], macos["runner"], macos["bundleArtifact"]) == (+ "aarch64",+ "macos-15",+ "cua-perception-input-macos-aarch64",+ )+ stale_intel_platforms = json.loads(json.dumps(platforms))+ stale_intel_macos = next(+ item for item in stale_intel_platforms["platforms"] if item["os"] == "macos"+ )+ stale_intel_macos.update(+ {+ "arch": "x86_64",+ "triple": "x86_64-apple-darwin",+ "runner": "macos-15-intel",+ }+ )+ with pytest.raises(ValidationError):+ platform_validator.validate(stale_intel_platforms)+++def test_packages_deterministically_with_catalog_sbom_and_redacted_provenance(+ tmp_path: Path,+) -> None:+ payload, manifest = fixture(tmp_path)+ first, second = tmp_path / "first", tmp_path / "second"+ evidence = tmp_path / "executed.json"+ release.run_candidate_gates(manifest, payload, evidence)+ archive = release.package_candidate(manifest, payload, first, executed_evidence_path=evidence)+ repeated = release.package_candidate(manifest, payload, second, executed_evidence_path=evidence)+ assert archive.read_bytes() == repeated.read_bytes()+ assert (first / "checksums.txt").read_text().startswith(release.file_digest(archive))+ catalog = json.loads((first / "catalog-payload.json").read_text())+ assert (first / "catalog-payload.json").read_bytes() == json.dumps(+ catalog, separators=(",", ":"), ensure_ascii=False+ ).encode()+ provenance = json.loads((first / "provenance.redacted.json").read_text())+ assert catalog["publisher_id"] == "cua"+ assert catalog["key_id"] == "cua-extension-ed25519-2026-01"+ assert catalog["archive_sha256"] == release.file_digest(archive)+ assert catalog["next_key"] is None+ assert list(catalog) == [+ "schema_version",+ "catalog_version",+ "expires_unix",+ "publisher_id",+ "publisher_name",+ "key_id",+ "extension_id",+ "version",+ "target",+ "archive",+ "archive_size",+ "archive_sha256",+ "manifest_sha256",+ "license",+ "source",+ "corresponding_source_uri",+ "corresponding_source_revision",+ "provenance",+ "next_key",+ ]+ assert "absolutePaths" in provenance["redactions"]+ assert str(tmp_path) not in json.dumps(provenance)+ with tarfile.open(archive) as candidate:+ names = candidate.getnames()+ assert {+ "bin/cua-perception-worker",+ "models/fixture-model.onnx",+ "review-recordings/linux-review.mp4",+ "metadata/sbom.spdx.json",+ "metadata/runtime-contract.json",+ "metadata/executed-verification.json",+ "model-manifest.json",+ "source/cua-perception-source.tar.gz",+ "extension.json",+ } <= set(names)+ with tarfile.open(archive) as candidate:+ extension_bytes = candidate.extractfile("extension.json").read()+ extension = json.loads(extension_bytes)+ archived_files = {+ member.name: digest(candidate.extractfile(member).read())+ for member in candidate.getmembers()+ if member.isfile() and member.name != "extension.json"+ }+ assert {item["path"] for item in extension["files"]} == set(archived_files)+ expected_notice = {+ "path": "notices/NOTICE",+ "sha256": archived_files["notices/NOTICE"],+ }+ assert all(component["notice_file"] == expected_notice for component in extension["components"])+ assert all(model["license_file"] == expected_notice for model in extension["models"])+ assert extension["corresponding_source_file"] == {+ "path": "source/cua-perception-source.tar.gz",+ "sha256": archived_files["source/cua-perception-source.tar.gz"],+ }+ assert catalog["manifest_sha256"] == digest(extension_bytes)+ assert catalog["extension_id"] == "cua-perception"+ runtime_contract = json.loads((first / "runtime-contract.json").read_text())+ assert runtime_contract["rejectMismatch"] is True+ assert len(runtime_contract["models"]) == 3+ assert runtime_contract["modelManifest"]["name"] == "model-manifest.json"+ assert provenance["evidence"]["supplied"] == [+ "verification/health.json",+ "verification/self-test.json",+ "verification/real-parse.json",+ ]+ assert provenance["evidence"]["executed"] == "metadata/executed-verification.json"+ release.verify_checksums(first / "checksums.txt")+ (first / "runtime-contract.json").write_text("tampered\n")+ with pytest.raises(release.CandidateError, match="checksum verification failed"):+ release.verify_checksums(first / "checksums.txt")+++ ("binding_owner", "binding_field"),+ [+ ("component", "notice_file"),+ ("model", "license_file"),+ ("extension", "corresponding_source_file"),+ ],+)+def test_rejects_missing_digest_bound_extension_files(+ tmp_path: Path, binding_owner: str, binding_field: str+) -> None:+ payload, manifest_path = fixture(tmp_path)+ manifest = release.load_and_validate_manifest(manifest_path, payload)+ stage = tmp_path / "stage"+ stage.mkdir()+ for item in manifest["artifacts"]:+ destination = stage / release.staged_artifact_path(item)+ destination.parent.mkdir(parents=True, exist_ok=True)+ destination.write_bytes((payload / item["path"]).read_bytes())+ extension = release.extension_manifest(stage, manifest, payload)+ if binding_owner == "component":+ del extension["components"][0][binding_field]+ elif binding_owner == "model":+ del extension["models"][0][binding_field]+ else:+ extension[binding_field]["sha256"] = "0" * 64++ with pytest.raises(release.CandidateError, match="binding"):+ release.validate_extension_manifest_bindings(extension)++[email protected]("field", ["sha256", "size", "protocolVersion", "target"])+def test_rejects_mismatched_payload_contract(tmp_path: Path, field: str) -> None:+ payload, manifest_path = fixture(tmp_path)+ manifest = json.loads(manifest_path.read_text())+ worker = manifest["artifacts"][0]+ if field == "sha256":+ worker[field] = "0" * 64+ elif field == "size":+ worker[field] += 1+ elif field == "protocolVersion":+ worker[field] += 1+ else:+ worker[field] = {"triple": "aarch64-unknown-linux-gnu", "os": "linux", "arch": "aarch64"}+ manifest_path.write_text(json.dumps(manifest))+ with pytest.raises(release.CandidateError):+ release.load_and_validate_manifest(manifest_path, payload)+++def test_model_requires_redistributable_ledger(tmp_path: Path) -> None:+ payload, manifest_path = fixture(tmp_path)+ ledger = json.loads((payload / "model-ledger.json").read_text())+ ledger["models"][0]["redistributionAllowed"] = False+ (payload / "model-ledger.json").write_text(json.dumps(ledger))+ with pytest.raises(release.CandidateError, match="model-ledger.schema.json"):+ release.load_and_validate_manifest(manifest_path, payload)+++def test_license_review_model_requires_exact_bundled_source_input(tmp_path: Path) -> None:+ payload, manifest_path = fixture(tmp_path)+ source_path = payload / "payload/source/upstream/omniparser-icon-detect-model.pt"+ source_path.parent.mkdir(parents=True, exist_ok=True)+ source_path.write_bytes(b"exact detector source input\n")+ manifest = json.loads(manifest_path.read_text())+ manifest["artifacts"].append(+ {+ "kind": "source",+ "name": "omniparser-icon-detect-model.pt",+ "path": "payload/source/upstream/omniparser-icon-detect-model.pt",+ "sha256": release.file_digest(source_path),+ "size": source_path.stat().st_size,+ "license": {+ "spdx": "AGPL-3.0-only",+ "source": "fixture source",+ "notice": "payload/NOTICE",+ },+ }+ )+ manifest_path.write_text(json.dumps(manifest))+ source_ledger_path = payload / "source-ledger.json"+ source_ledger = json.loads(source_ledger_path.read_text())+ source_ledger["sources"].append(+ {+ "artifact": "omniparser-icon-detect-model.pt",+ "artifactSha256": release.file_digest(source_path),+ "artifactSize": source_path.stat().st_size,+ "repository": "fixture source",+ "revision": "b" * 40,+ "license": "AGPL-3.0-only",+ "durableLocation": "candidate archive source/upstream/omniparser-icon-detect-model.pt",+ "sourceOfferStatus": "bundled-review-only",+ "contentKind": "model-source-input",+ "format": "file",+ }+ )+ source_ledger_path.write_text(json.dumps(source_ledger))+ model_ledger_path = payload / "model-ledger.json"+ model_ledger = json.loads(model_ledger_path.read_text())+ model_ledger["models"][0]["verificationStatus"] = "license-review-required"+ model_ledger["models"][0]["sourceArtifact"] = {+ "artifact": "omniparser-icon-detect-model.pt",+ "path": "payload/source/upstream/omniparser-icon-detect-model.pt",+ "sha256": release.file_digest(source_path),+ "size": source_path.stat().st_size,+ }+ model_ledger_path.write_text(json.dumps(model_ledger))+ release.load_and_validate_manifest(manifest_path, payload)+ model_ledger["models"][0]["sourceArtifact"]["sha256"] = "0" * 64+ model_ledger_path.write_text(json.dumps(model_ledger))+ with pytest.raises(release.CandidateError, match="source input binding differs"):+ release.load_and_validate_manifest(manifest_path, payload)+++def test_source_ledger_must_bind_hash_size_revision_and_bundled_offer(tmp_path: Path) -> None:+ payload, manifest_path = fixture(tmp_path)+ ledger_path = payload / "source-ledger.json"+ original = json.loads(ledger_path.read_text())+ for field, value in (+ ("artifactSha256", "0" * 64),+ ("artifactSize", 999),+ ("revision", "b" * 40),+ ("sourceOfferStatus", "external-review-required"),+ ):+ ledger = json.loads(json.dumps(original))+ ledger["sources"][0][field] = value+ ledger_path.write_text(json.dumps(ledger))+ with pytest.raises(release.CandidateError):+ release.load_and_validate_manifest(manifest_path, payload)+ ledger_path.write_text(json.dumps(original))+++def test_bind_source_builds_nonempty_archive_from_exact_checked_out_sha(tmp_path: Path) -> None:+ payload, manifest_path = fixture(tmp_path)+ source_sha = subprocess.run(+ ["git", "rev-parse", "HEAD"], cwd=ROOT, check=True, text=True, stdout=subprocess.PIPE+ ).stdout.strip()+ manifest = json.loads(manifest_path.read_text())+ manifest["sourceSha"] = source_sha+ manifest_path.write_text(json.dumps(manifest))+ ledger = json.loads((payload / "source-ledger.json").read_text())+ ledger["sources"][0]["revision"] = source_sha+ (payload / "source-ledger.json").write_text(json.dumps(ledger))+ archive = release.bind_corresponding_source(manifest_path, payload, ROOT)+ assert archive.stat().st_size > 0+ first_bytes = archive.read_bytes()+ assert (+ release.bind_corresponding_source(manifest_path, payload, ROOT).read_bytes() == first_bytes+ )+ with tarfile.open(archive) as source:+ assert source.getnames()[0].rstrip("/") == f"cua-source-{source_sha}"+ rebound = json.loads(manifest_path.read_text())+ source_artifact = next(item for item in rebound["artifacts"] if item["kind"] == "source")+ assert source_artifact["sha256"] == release.file_digest(archive)+ assert source_artifact["size"] == archive.stat().st_size+++def test_release_gates_execute_worker_instead_of_trusting_reports(tmp_path: Path) -> None:+ payload, manifest_path = fixture(tmp_path)+ evidence_path = tmp_path / "executed.json"+ evidence = release.run_candidate_gates(manifest_path, payload, evidence_path)+ assert evidence["evidenceKind"] == "executed"+ assert [gate["gate"] for gate in evidence["gates"]] == [+ "health",+ "self-test",+ "real-parse",+ "mismatch-rejection",+ ]+ assert json.loads(evidence_path.read_text()) == evidence+ (payload / "fail-gates").write_text("fail\n")+ with pytest.raises(release.CandidateError, match="executed health gate failed"):+ release.run_candidate_gates(manifest_path, payload)+++def test_release_gates_reject_worker_identity_outside_signed_manifest(tmp_path: Path) -> None:+ payload, manifest_path = fixture(tmp_path)+ (payload / "wrong-identity").write_text("wrong\n")+ with pytest.raises(release.CandidateError, match="reported extension identity"):+ release.run_candidate_gates(manifest_path, payload)+++ ("field", "value"),+ [("extensionId", "wrong"), ("extensionVersion", "9.9.9")],+)+def test_supplied_verification_requires_signed_manifest_identity(+ tmp_path: Path, field: str, value: str+) -> None:+ payload, manifest_path = fixture(tmp_path)+ manifest = json.loads(manifest_path.read_text())+ report_path = payload / manifest["suppliedVerification"]["health"]+ report = json.loads(report_path.read_text())+ report[field] = value+ report_bytes = (json.dumps(report) + "\n").encode()+ report_path.write_bytes(report_bytes)+ report_artifact = next(item for item in manifest["artifacts"] if item.get("role") == "health")+ report_artifact["sha256"] = digest(report_bytes)+ report_artifact["size"] = len(report_bytes)+ manifest_path.write_text(json.dumps(manifest))+ with pytest.raises((release.CandidateError, ValidationError)):+ release.load_and_validate_manifest(manifest_path, payload)+++def test_packaging_rejects_executed_evidence_for_another_candidate(tmp_path: Path) -> None:+ payload, manifest_path = fixture(tmp_path)+ evidence_path = tmp_path / "executed.json"+ release.run_candidate_gates(manifest_path, payload, evidence_path)+ evidence = json.loads(evidence_path.read_text())+ evidence["sourceSha"] = "b" * 40+ evidence_path.write_text(json.dumps(evidence))+ with pytest.raises(release.CandidateError, match="sourceSha differs"):+ release.package_candidate(+ manifest_path, payload, tmp_path / "candidate", executed_evidence_path=evidence_path+ )+++def test_requires_one_exact_model_manifest_bound_to_runtime_and_models(tmp_path: Path) -> None:+ payload, manifest_path = fixture(tmp_path)+ manifest = json.loads(manifest_path.read_text())+ model_manifest = next(+ item for item in manifest["artifacts"] if item["kind"] == "model-manifest"+ )+ manifest["artifacts"].remove(model_manifest)+ manifest_path.write_text(json.dumps(manifest))+ with pytest.raises(release.CandidateError, match="exactly one model-manifest.json"):+ release.load_and_validate_manifest(manifest_path, payload)++ manifest["artifacts"].extend(+ [+ model_manifest,+ {**model_manifest, "name": "other.json", "path": "payload/model-manifest-copy.json"},+ ]+ )+ (payload / "payload/model-manifest-copy.json").write_bytes(+ (payload / model_manifest["path"]).read_bytes()+ )+ manifest_path.write_text(json.dumps(manifest))+ with pytest.raises(release.CandidateError, match="exactly one model-manifest.json"):+ release.load_and_validate_manifest(manifest_path, payload)++ manifest["artifacts"] = [+ item for item in manifest["artifacts"] if item["path"] != "payload/model-manifest-copy.json"+ ]+ document = json.loads((payload / model_manifest["path"]).read_text())+ document["onnx_runtime"]["library_sha256"] = "0" * 64+ changed = (json.dumps(document) + "\n").encode()+ (payload / model_manifest["path"]).write_bytes(changed)+ model_manifest.update({"sha256": digest(changed), "size": len(changed)})+ manifest_path.write_text(json.dumps(manifest))+ with pytest.raises(release.CandidateError, match="different ONNX Runtime"):+ release.load_and_validate_manifest(manifest_path, payload)+++def test_driver_archive_exclusion_is_enforced(tmp_path: Path) -> None:+ clean, dirty = tmp_path / "driver.tar.gz", tmp_path / "dirty.tar.gz"+ driver, model = tmp_path / "cua-driver", tmp_path / "model.onnx"+ driver.write_bytes(b"driver")+ model.write_bytes(b"model")+ with tarfile.open(clean, "w:gz") as archive:+ archive.add(driver, arcname="cua-driver")+ with tarfile.open(dirty, "w:gz") as archive:+ archive.add(model, arcname="models/model.onnx")+ release.verify_driver_exclusion([clean])+ with pytest.raises(release.CandidateError, match="Perception payload"):+ release.verify_driver_exclusion([dirty])+++def test_release_stream_is_candidate_only_and_driver_remains_excluded() -> None:+ config = json.loads((ROOT / "release-please-config.json").read_text())+ manifest = json.loads((ROOT / ".release-please-manifest.json").read_text())+ registry = json.loads((ROOT / ".github/releases/components.json").read_text())+ path = "libs/cua-driver/rust/crates/cua-perception"+ assert config["packages"][path]["skip-github-release"] is True+ assert config["packages"][path]["component"] == "cua-perception"+ assert config["packages"][path]["version-file"] == "VERSION"+ assert config["packages"][path]["changelog-path"] == "CHANGELOG.md"+ assert config["packages"][path]["extra-files"] == [+ {+ "type": "toml",+ "path": "Cargo.toml",+ "jsonpath": "$.package.version",+ }+ ]+ assert "include-paths" not in config["packages"][path]+ assert manifest[path] == (ROOT / path / "VERSION").read_text().strip()+ assert registry["components"]["cua-perception"]["releasePleasePath"] == path+ assert registry["components"]["cua-perception"]["candidateOnly"] is True+ assert (+ "libs/cua-driver/rust/crates/cua-perception"+ in registry["components"]["cua-driver-rs"]["changeDetectionExcludePaths"]+ )+ assert registry["components"]["cua-perception"]["versionAuthorityFile"] == (+ "libs/cua-driver/rust/crates/cua-perception/VERSION"+ )+ assert registry["components"]["cua-perception"]["changelog"] == (+ "libs/cua-driver/rust/crates/cua-perception/CHANGELOG.md"+ )+ assert not (CONTROL / "VERSION").exists()+ assert not (CONTROL / "CHANGELOG.md").exists()+++def test_workflows_are_valid_and_candidate_workflow_cannot_publish() -> None:+ candidate_path = ROOT / ".github/workflows/cd-cua-perception-candidate.yml"+ manual_path = ROOT / ".github/workflows/cd-cua-perception-candidate-manual.yml"+ ci_path = ROOT / ".github/workflows/ci-cua-perception-release.yml"+ for path in (candidate_path, manual_path, ci_path):+ assert isinstance(yaml.safe_load(path.read_text()), dict)+ candidate = candidate_path.read_text()+ assert "actions/upload-artifact" in candidate and "actions/download-artifact" in candidate+ assert "github_release.py" not in candidate and "gh release" not in candidate+ assert "contents: write" not in candidate+ assert "STAGING-cua-perception-candidate" in candidate+ assert "crypto.verify(null, payloadBytes, publicKey, signature)" in candidate+ assert "PERCEPTION_ED25519_PRIVATE_KEY_BASE64" in candidate+ assert "openssl genpkey" not in candidate+ assert "verify-checksums" in candidate+ assert "bind-source" in candidate and "--executed-evidence" in candidate+ assert "refs/cua-reviewed/source" in candidate+ assert "macos:aarch64-apple-darwin" in candidate+ assert "macos-15-intel" not in candidate+ assert "refs/pull/3943/head" not in manual_path.read_text()+ parsed = yaml.safe_load(candidate)+ assert "PRIVATE_KEY_BASE64" not in json.dumps(parsed["jobs"]["package"])+ assert "PRIVATE_KEY_BASE64" in json.dumps(parsed["jobs"]["sign"])+ assert parsed["jobs"]["sign"]["environment"] == "cua-perception-candidate-signing"+ manual = manual_path.read_text()+ for value in ("x86_64-unknown-linux-gnu", "aarch64-apple-darwin", "x86_64-pc-windows-msvc"):+ assert value in manual+ assert "cua-perception-input-macos-aarch64" in manual+ assert "x86_64-apple-darwin" not in manual+++def test_trust_root_and_rfc8032_vector_match_extension_manager_contract() -> None:+ trust = json.loads((CONTROL / "trust-root.json").read_text())+ vector = json.loads((CONTROL / "ed25519-test-vector.json").read_text())+ Draft202012Validator(json.loads((CONTROL / "trust-root.schema.json").read_text())).validate(+ trust+ )+ assert trust["activeKeyId"] == "cua-extension-ed25519-2026-01"+ assert trust["keys"][0]["publicKeyBase64"] == "dB7E/36fTXLiHPfr8ya4i4TFbssU/jpO9zrS8gl4bsQ="+ assert trust["rotation"]["privateKeysStoredInRepository"] is False+ assert trust["keys"][0]["validFromUnix"] == 1735689600+ assert trust["keys"][0]["validUntilUnix"] == 2082758400+ assert (+ vector["publicKeyHex"] == "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a"+ )+ assert len(vector["signatureBase64"]) == 88+ subprocess.run(+ [+ "node",+ "-e",+ "const c=require('node:crypto');"+ "const key=Buffer.from('302a300506032b6570032100'+process.argv[1],'hex');"+ "if(!c.verify(null,Buffer.from(process.argv[2],'hex'),"+ "{key,format:'der',type:'spki'},Buffer.from(process.argv[3],'base64')))process.exit(1)",+ vector["publicKeyHex"],+ vector["messageHex"],+ vector["signatureBase64"],+ ],+ check=True,+ )+++def test_driver_workflow_never_packages_perception() -> None:+ driver = (ROOT / ".github/workflows/cd-rust-cua-driver.yml").read_text()+ assert driver.count("--exclude-path libs/cua-driver/rust/crates/cua-perception") == 2+ assert driver.count("--exclude-path libs/cua-driver/examples") == 2+ assert all(+ "cua-perception" not in line+ for line in driver.splitlines()+ if line.strip().startswith("cp ")+ )diff --git a/.github/scripts/tests/test_cua_perception_release_workflows.py b/.github/scripts/tests/test_cua_perception_release_workflows.pynew file mode 100644index 0000000000..d74bfbfcf7--- /dev/null+++ b/.github/scripts/tests/test_cua_perception_release_workflows.py@@ -0,0 +1,96 @@+"""Contract tests for Perception metadata sync and first-release tag anchoring."""++from pathlib import Path++import yaml+++ROOT = Path(__file__).resolve().parents[3]+RELEASE_WORKFLOW = ROOT / ".github/workflows/release-please.yml"+CI_WORKFLOW = ROOT / ".github/workflows/ci-release-metadata.yml"+VERSION_PATH = "libs/cua-driver/rust/crates/cua-perception/VERSION"+CHANGELOG_PATH = "libs/cua-driver/rust/crates/cua-perception/CHANGELOG.md"+++def load_workflow(path: Path) -> tuple[str, dict]:+ source = path.read_text()+ workflow = yaml.safe_load(source)+ assert isinstance(workflow, dict)+ return source, workflow+++def step(workflow: dict, name: str) -> dict:+ steps = workflow["jobs"]["release-please"]["steps"]+ return next(item for item in steps if item.get("name") == name)+++def test_release_pr_sync_uses_crate_metadata_and_updates_the_lockfile() -> None:+ source, workflow = load_workflow(RELEASE_WORKFLOW)+ sync = step(workflow, "Synchronize generated files on release pull requests")["run"]++ assert VERSION_PATH in sync+ assert "-p cua-perception --precise \"$PERCEPTION_VERSION\"" in sync+ assert "validate_release_versions.py --product perception" in sync+ assert "git add libs/cua-driver/rust/Cargo.lock" in sync+ assert ".github/releases/cua-perception/VERSION" not in source+ assert "jq -r '.[\\\".\\\"]'" not in source+++def test_candidate_tag_is_exact_lightweight_main_anchor_without_a_release() -> None:+ _, workflow = load_workflow(RELEASE_WORKFLOW)+ steps = workflow["jobs"]["release-please"]["steps"]+ tag_step = step(+ workflow, "Anchor a merged Perception version with a lightweight tag"+ )+ script = tag_step["run"]++ tag_index = steps.index(tag_step)+ for release_step in (+ "Open or update automatic release pull requests",+ "Open or update the targeted release pull request",+ "Synchronize generated files on release pull requests",+ ):+ assert tag_index < next(+ index+ for index, item in enumerate(steps)+ if item.get("name") == release_step+ )+ assert tag_step["if"] == (+ "github.event_name == 'push' && github.ref == 'refs/heads/main'"+ )+ assert tag_step["env"]["GH_TOKEN"] == "${{ steps.app-token.outputs.token }}"+ assert tag_step["env"]["VERSION_PATH"] == VERSION_PATH+ assert "validate_release_versions.py --product perception" in script+ assert 'git merge-base --is-ancestor "$BEFORE_SHA" "$GITHUB_SHA"' in script+ assert 'git merge-base --is-ancestor "$GITHUB_SHA" origin/main' in script+ assert "Perception version must increase" in script+ assert 'TAG="cua-perception-v$VERSION"' in script+ assert 'tag_type" != "commit"' in script+ assert 'tag_sha" != "$GITHUB_SHA"' in script+ assert '-f ref="refs/tags/$TAG"' in script+ assert '-f sha="$GITHUB_SHA"' in script+ assert "--method PATCH" not in script+ assert "gh release" not in script+ assert "/releases" not in script+++def test_ci_uses_crate_root_metadata_and_central_version_validation() -> None:+ source, workflow = load_workflow(CI_WORKFLOW)+ steps = workflow["jobs"]["validate"]["steps"]+ validation = next(+ item for item in steps if item.get("name") == "Validate checked-in release versions"+ )+ preflight = next(+ item+ for item in steps+ if item.get("name") == "Preflight trusted Release Please attribution"+ )["run"]++ assert validation["run"] == (+ "python3 .github/scripts/validate_release_versions.py --product all"+ )+ assert VERSION_PATH in preflight+ assert f"--changelog {CHANGELOG_PATH}" in preflight+ assert ".github/releases/cua-perception/VERSION" not in source+ assert ".github/releases/cua-perception/*" in source+ assert "jq -r '.[\\\".\\\"]'" not in sourcediff --git a/.github/scripts/tests/test_cua_perception_review_pipeline.py b/.github/scripts/tests/test_cua_perception_review_pipeline.pynew file mode 100644index 0000000000..63279d7b83--- /dev/null+++ b/.github/scripts/tests/test_cua_perception_review_pipeline.py@@ -0,0 +1,462 @@+from __future__ import annotations++import json+from pathlib import Path+import re++import yaml+++ROOT = Path(__file__).resolve().parents[3]+WORKFLOW = ROOT / ".github/workflows/cd-cua-perception-review-supplied-inputs.yml"+LOCK = ROOT / "libs/cua-driver/rust/crates/cua-perception/scripts/artifacts.lock.json"+++def workflow_text() -> str:+ return WORKFLOW.read_text(encoding="utf-8")+++def workflow_triggers(parsed: dict) -> dict:+ return parsed.get("on", parsed.get(True))+++def test_review_pipeline_declares_equal_literal_trigger_inputs() -> None:+ text = workflow_text()+ parsed = yaml.safe_load(text)+ triggers = workflow_triggers(parsed)+ assert triggers["workflow_dispatch"]["inputs"] == triggers["workflow_call"]["inputs"]+ assert "&review_inputs" not in text+ assert "*review_inputs" not in text+++def test_review_pipeline_is_valid_pinned_and_nonpublishing() -> None:+ text = workflow_text()+ parsed = yaml.safe_load(text)+ assert isinstance(parsed, dict)+ assert parsed["permissions"] == {+ "actions": "read",+ "contents": "read",+ "pull-requests": "read",+ }+ assert all(access != "write" for access in parsed["permissions"].values())+ assert "contents: write" not in text+ uses = re.findall(r"^\s*uses:\s*([^\s#]+)", text, flags=re.MULTILINE)+ assert uses+ assert all(re.fullmatch(r"[^@]+@[0-9a-f]{40}", use) for use in uses)+ lowered = text.lower()+ assert "gh release" not in lowered+ assert "--method" not in lowered+ assert "method=" not in lowered+ assert "data=" not in lowered+ assert "softprops/action-gh-release" not in lowered+ assert "actions/create-release" not in lowered+ assert "actions/upload-release-asset" not in lowered+ assert "perception_ed25519_private_key_base64" not in lowered+ assert "review_only: true" in lowered+ assert "environment:" not in text+ assert "secrets." not in text+ assert parsed["jobs"]["reviewed-model"]["permissions"] == {+ "actions": "read",+ "contents": "read",+ "pull-requests": "read",+ }+ assert parsed["jobs"]["supplied-input"]["permissions"] == {+ "actions": "read",+ "contents": "read",+ "pull-requests": "read",+ }+ assert parsed["jobs"]["aggregate"]["permissions"] == {+ "actions": "read",+ "contents": "read",+ }+++def test_reviewed_model_broker_is_read_only_pinned_and_immutable() -> None:+ text = workflow_text()+ parsed = yaml.safe_load(text)+ broker = parsed["jobs"]["reviewed-model"]+ broker_text = str(broker)+ assert "actions/checkout" not in broker_text+ assert "libs/cua-driver" not in broker_text+ assert broker["outputs"] == {"source_asset_id": "${{ steps.verify.outputs.source_asset_id }}"}+ assert broker["permissions"] == {+ "actions": "read",+ "contents": "read",+ "pull-requests": "read",+ }+ assert "35438356263" in broker_text+ assert "10582583541" in broker_text+ assert "571471639" in broker_text+ assert "289372dea8b2b11f572f0f6a15824315bc74026b" in broker_text+ assert ".github/workflows/review-cua-perception-pr3943.yml" in broker_text+ assert '"$workflow_path" == "$expected_workflow"@*' in broker_text+ assert '[[ "$(jq -r .conclusion <<<"$run_json")" == "success" ]]' in broker_text+ assert '[[ "$(jq -r .expired <<<"$artifact_json")" == "false" ]]' in broker_text+ assert (+ '[[ "$(jq -r .workflow_run.id <<<"$artifact_json")" == "$REVIEWED_RUN_ID" ]]' in broker_text+ )+ assert (+ '[[ "$(jq -r .workflow_run.head_sha <<<"$artifact_json")" == "$REVIEWED_SOURCE_SHA" ]]'+ in broker_text+ )+ assert "omniparser-icon-detect-1280-opset17.onnx" in broker_text+ assert "d8a876bf7f9fb73d7da9432904ade7fa78e092e9a91674e5a2806b45562a9ab2" in broker_text+ assert "80_933_219" in broker_text+ producer_download = next(+ step+ for step in broker["steps"]+ if step.get("name") == "Download the exact reviewed producer artifact"+ )+ assert producer_download["with"] == {+ "artifact-ids": "10582583541",+ "github-token": "${{ github.token }}",+ "path": "reviewed-producer-input",+ "repository": "trycua/cua",+ "run-id": "35438356263",+ }+ assert "actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08" in broker_text++ supplied = parsed["jobs"]["supplied-input"]+ assert supplied["needs"] == "reviewed-model"+ assert any(+ step.get("uses", "").startswith("actions/download-artifact@")+ and step["with"]+ == {+ "name": "reviewed-cua-perception-model",+ "path": "reviewed-inputs",+ }+ for step in supplied["steps"]+ )+ assert "${{ needs.reviewed-model.outputs.source_asset_id }}" in text+ assert "${{ needs.reviewed-model.outputs.asset_id }}" not in text+ for job in parsed["jobs"].values():+ if "actions/checkout@" in str(job):+ assert job["permissions"]["contents"] == "read"+++def test_review_pipeline_binds_current_pr_head_and_authenticated_supplied_model() -> None:+ text = workflow_text()+ lock = json.loads(LOCK.read_text(encoding="utf-8"))+ detector = next(item for item in lock["artifacts"] if item["role"] == "icon-detect")+ assert detector["url"] is None+ assert detector["size"] == 80_933_219+ assert detector["sha256"] == "d8a876bf7f9fb73d7da9432904ade7fa78e092e9a91674e5a2806b45562a9ab2"+ assert "digest != expected_sha256" in text+ assert "refs/pull/$REQUESTED_PR_NUMBER/head" in text+ assert "pulls/$REQUESTED_PR_NUMBER" in text+ assert "actions/runs/$REVIEWED_RUN_ID" in text+ assert "actions/artifacts/$REVIEWED_ARTIFACT_ID" in text+ assert "browser_download_url" not in text+ assert text.index("differ from the reviewed size or SHA-256") < text.index(+ "Generate an ephemeral review trust root"+ )+ assert 'test "$EVENT_HEAD_SHA" = "$REQUESTED_SHA"' in text+ assert 'test "$GITHUB_SHA" = "$REQUESTED_SHA"' in text+ assert 'test "$EVENT_PR_NUMBER" = "$REQUESTED_PR_NUMBER"' in text+ assert 'test "$EVENT_LABEL" = cua-perception-live-review' in text+ assert '"$GITHUB_EVENT_NAME" == pull_request' in text+ assert '"$REQUESTED_PR_NUMBER" =~ ^[1-9][0-9]*$' in text+++def test_review_pipeline_builds_pending_trust_override_and_exact_artifact_contracts() -> None:+ text = workflow_text()+ parsed = yaml.safe_load(text)+ supplied_input = parsed["jobs"]["supplied-input"]+ assert supplied_input["env"] == {+ "MSYS2_ENV_CONV_EXCL": "CUA_DRIVER_REVIEW_EXTENSION_PUBLIC_KEY_BASE64"+ }+ for value in (+ "CUA_DRIVER_REVIEW_EXTENSION_PUBLIC_KEY_BASE64",+ "--features review-trust-root",+ 'publisher_id = "cua-review-only"',+ 'publisher_name = "Cua REVIEW ONLY"',+ 'key_id = "review-only-build-override"',+ 'signature_algorithm: "ed25519"',+ "cua-perception-input-linux-x86_64",+ "cua-perception-input-windows-x86_64",+ "cua-perception-input-macos-aarch64",+ '("windows", "x86_64-pc-windows-msvc")',+ '("linux-x11", "x86_64-unknown-linux-gnu")',+ '("macos", "aarch64-apple-darwin")',+ "STAGING-cua-perception-review-candidates-",+ "review_driver_relative_path: driverName",+ 'review_driver_build_profile: "debug-review-trust-root"',+ ):+ assert value in text+ driver_build = re.search(+ r"cargo build --manifest-path libs/cua-driver/rust/Cargo.toml \\\n+\s+-p cua-driver[^\n]+",+ text,+ )+ assert driver_build and "--release" not in driver_build.group(0)+ assert "const payloadBytes = Buffer.from(JSON.stringify(payload));" in text+ assert "crypto.sign(null, payloadBytes, privateKey)" in text+ assert "crypto.verify(null, payloadBytes, key" in text+ assert "fs.unlinkSync(privatePath)" in text+ aggregate = parsed["jobs"]["aggregate"]+ assert aggregate["outputs"] == {+ "signed_candidate_artifact_id": "${{ steps.upload.outputs.artifact-id }}",+ "producer_run_id": "${{ steps.producer.outputs.run_id }}",+ }+ download = next(+ step+ for step in aggregate["steps"]+ if step.get("name") == "Download all signed target layouts"+ )+ assert download["with"] == {+ "pattern": "review-cua-perception-*-${{ inputs.source_sha }}",+ "path": "staged",+ "merge-multiple": True,+ }+ upload = next(step for step in aggregate["steps"] if step.get("id") == "upload")+ assert upload["with"]["name"] == (+ "STAGING-cua-perception-review-candidates-${{ inputs.source_sha }}"+ )+ assert upload["with"]["path"] == "staged/"+++def test_review_pipeline_preserves_the_assembler_candidate_manifest() -> None:+ parsed = yaml.safe_load(workflow_text())+ conversion = next(+ step["run"]+ for step in parsed["jobs"]["supplied-input"]["steps"]+ if step.get("name") == "Convert sealed assembler evidence to candidate input"+ )+ assert 'manifest = json.loads((root / "artifact-manifest.json").read_text())' in conversion+ assert '(root / "release-input.json").write_text(' in conversion+ assert '"verification-report"' not in conversion+ assert 'artifact["kind"] = "supplied-verification-report"' not in conversion+ assert 'report["evidenceKind"] = "supplied"' not in conversion+ assert 'manifest.pop("verification", None)' not in conversion+ assert 'manifest["artifacts"].append' not in conversion+ assert '"kind": "model-manifest"' not in conversion+ assert '"model-manifest.json"' not in conversion+ assert "perception_release.py bind-source" in conversion+ assert "perception_release.py validate" in conversion+ assert 'for stale in ("artifact-manifest.json", "SHA256SUMS")' in conversion+++def test_macos_review_candidate_uses_ephemeral_certificate_signing() -> None:+ text = workflow_text()+ script = (ROOT / ".github/scripts/macos-review-codesign.sh").read_text()+ assert "runner: macos-26" in text+ assert "runner: macos-15" not in text+ assert "Match the production Driver build and hosted desktop E2E image" in text+ assert "bash .github/scripts/macos-review-codesign.sh" in text+ assert "code_signing: codeSigning" in text+ for contract in (+ "mktemp -d",+ "security create-keychain",+ "extendedKeyUsage=codeSigning",+ "openssl pkcs12 -export -legacy",+ '-P "$identity_password" -A -T /usr/bin/codesign',+ 'cp "$driver_path" "$signing_probe"',+ 'identity_selector="$identity_name"',+ 'codesign --force --sign "$identity_selector" "$signing_probe"',+ 'run_step driver-sign codesign --force --sign "$identity_selector"',+ "run_step driver-verify codesign --verify --strict",+ "security delete-keychain",+ "trap cleanup EXIT INT TERM",+ 'requirement_output="$({ codesign -d -r- "$driver_path"; } 2>&1)"',+ '"identity": "ephemeral-self-signed-review-only"',+ ):+ assert contract in script+ assert "Developer ID" not in script++ snapshot = script.index('previous_keychains_output="$(security list-keychains -d user)"')+ default_snapshot = script.index(+ 'previous_default_keychain="$(security default-keychain -d user |'+ )+ create = script.index('security create-keychain -p "$keychain_password"')+ unlock = script.index('security unlock-keychain -p "$keychain_password"')+ prepend = script.index(+ 'security list-keychains -d user -s "$keychain_path" "${previous_keychains[@]}"',+ unlock,+ )+ default_set = script.index('security default-keychain -d user -s "$keychain_path"', prepend)+ identity_import = script.index('security import "$identity_path"')+ identity_lookup = script.index("run_step identity security find-identity")+ sudo_preflight = script.index("run_step sudo-preflight sudo -n -v")+ cleanup_flag = script.index("admin_trust_cleanup_needed=true", sudo_preflight)+ add_trust = script.index("run_step add-trust sudo -n security add-trusted-cert")+ trusted_cert_present = script.index("run_step trusted-cert-present security find-certificate")+ valid_identity = script.index("run_step valid-identity security find-identity -v")+ partition_list = script.index("security set-key-partition-list")+ probe_sign = script.index('identity_selector="$identity_name"')+ driver_sign = script.index("run_step driver-sign codesign")+ assert (+ default_snapshot+ < snapshot+ < create+ < unlock+ < prepend+ < default_set+ < identity_import+ < identity_lookup+ < sudo_preflight+ < cleanup_flag+ < add_trust+ < trusted_cert_present+ < valid_identity+ < partition_list+ < probe_sign+ < driver_sign+ )+ assert script.count('previous_keychains_output="$(security list-keychains -d user)"') == 1+ assert script.count('previous_default_keychain="$(security default-keychain -d user |') == 1+ assert 'done <<< "$previous_keychains_output"' in script[snapshot:create]+ assert "search_list_snapshotted=true" in script[snapshot:create]+ assert 'if [[ "$search_list_snapshotted" == true ]]; then' in script+ assert (+ 'security list-keychains -d user -s "${previous_keychains[@]}" >/dev/null 2>&1 || true'+ ) in script+ assert (+ 'security default-keychain -d user -s "$previous_default_keychain" '+ "\\\n >/dev/null 2>&1 || true"+ ) in script+ assert "set -x" not in script+ assert '--keychain "$keychain_path"' not in script[probe_sign:]+ assert '--keychain "$keychain_path" "$signing_probe"' not in script+ assert '--keychain "$keychain_path" "$driver_path"' not in script+ assert 'cp /bin/echo "$signing_probe"' not in script+ assert script.count("openssl pkcs12 -export") == 2+ assert '"$log_dir/pkcs12-legacy.log" "$log_dir/pkcs12-fallback.log"' in script+ assert 'emit_log "$log_dir/pkcs12-legacy.log"' in script+ assert 'emit_log "$log_dir/pkcs12-fallback.log"' in script+ assert "-keypbe PBE-SHA1-3DES" not in script+ assert "-certpbe PBE-SHA1-3DES" not in script+ assert "[[:xdigit:]]{64}" in script+ assert '"${RUNNER_ENVIRONMENT:-}" == github-hosted' in script+ assert '"${RUNNER_OS:-}" == macOS' in script+ assert '"${GITHUB_ACTIONS:-}" == true' in script+ assert 'security remove-trusted-cert -d "$certificate_path"' in script+ assert 'security delete-certificate -Z "$trusted_identity"' in script+ assert "security dump-trust-settings -d" in script+ assert "run_bounded security find-certificate -Z -a" in script+ assert 'exit "$cleanup_status"' in script+ assert 'exit "$status"' not in script+ trust_removal = script.index('security remove-trusted-cert -d "$certificate_path"')+ certificate_cleanup = script.index('rm -f "$private_key_path"')+ assert trust_removal < certificate_cleanup+ assert 'grep -Eqi "certificate (leaf|root) = H\\"$identity_hash\\""' in script+ assert 'rmdir "$work_root"' in script+ assert 'rm -rf "$work_root"' not in script++ for production_workflow in ("cd-rust-cua-driver.yml", "cd-swift-lume.yml"):+ production = (ROOT / ".github/workflows" / production_workflow).read_text()+ assert " -A " not in production+++def test_review_measurements_are_extracted_from_the_sealed_archive() -> None:+ text = workflow_text()+ for member in (+ 'member_bytes("metadata/artifact-manifest.json")',+ 'member_bytes("extension.json")',+ 'member_json("metadata/runtime-contract.json")',+ 'member_json("model-manifest.json")',+ 'member_json("modelLedger.json")',+ 'member_bytes("metadata/executed-verification.json")',+ ):+ assert member in text+ assert 'for role in ("icon-detect", "ocr-detect", "ocr-recognize")' in text+ assert "digest(sealed_bytes)" in text+ assert 'gates.get("self-test", {}).get("status") != "passed"' in text+ assert '"sealed_artifact_manifest_sha256": digest(artifact_bytes)' in text+ assert '"sealed_extension_manifest_sha256": digest(extension_bytes)' in text+ assert '"review_driver_version": match.group(0)' in text+ assert (+ "modelLock.artifacts.find" in text+ ) # download identity only; sealed values replace it below+ assert text.index("measurements.update({") < text.rindex("signed-candidate-checksums.txt")+++def test_review_pipeline_native_driver_inspects_the_final_candidate_without_installing() -> None:+ parsed = yaml.safe_load(workflow_text())+ steps = parsed["jobs"]["supplied-input"]["steps"]+ package_index = next(+ index+ for index, step in enumerate(steps)+ if step.get("name") == "Package, review-sign, and measure the candidate"+ )+ inspect_index = next(+ index+ for index, step in enumerate(steps)+ if step.get("name") == "Inspect the signed candidate with the native review Driver"+ )+ upload_index = next(+ index+ for index, step in enumerate(steps)+ if step.get("name") == "Preserve signed review-only target without publishing"+ )+ assert package_index < inspect_index < upload_index++ inspection = steps[inspect_index]["run"]+ assert 'CUA_DRIVER_RS_HOME="$inspect_home"' in inspection+ assert 'test ! -e "$inspect_home"' in inspection+ assert 'extension inspect cua-perception --catalog "$catalog" --json' in inspection+ assert "extension install" not in inspection+ assert "extension update" not in inspection+ assert 'preview["trust"] == "review-only-publisher-verified"' in inspection+ assert 'preview["publisher_signature_verified"] is True' in inspection+ assert 'preview["archive_sha256"] == measurements["archive_sha256"]' in inspection+ assert (+ 'hashlib.sha256(archive.read_bytes()).hexdigest() == preview["archive_sha256"]'+ in inspection+ )+ assert 'model["license_file"]' in inspection+ assert 'component["notice_file"]' in inspection+ assert 'source = preview["corresponding_source"]' in inspection+ assert 'preview["mutation_performed"] is False' in inspection+ assert 'preview["installed"] is False' in inspection+++def test_review_pipeline_installs_and_self_tests_each_packaged_candidate() -> None:+ parsed = yaml.safe_load(workflow_text())+ steps = parsed["jobs"]["supplied-input"]["steps"]+ inspect_index = next(+ index+ for index, step in enumerate(steps)+ if step.get("name") == "Inspect the signed candidate with the native review Driver"+ )+ install_index = next(+ index+ for index, step in enumerate(steps)+ if step.get("name")+ == "Install and self-test the packaged candidate with the native review Driver"+ )+ cleanup_index = next(+ index+ for index, step in enumerate(steps)+ if step.get("name") == "Destroy any remaining ephemeral private key"+ )+ upload_index = next(+ index+ for index, step in enumerate(steps)+ if step.get("name") == "Preserve signed review-only target without publishing"+ )+ assert inspect_index < install_index < cleanup_index < upload_index++ self_test = steps[install_index]+ assert self_test["shell"] == "bash"+ assert self_test["env"] == {"PLATFORM": "${{ matrix.platform }}"}+ run = self_test["run"]+ assert 'driver="$root/review-${{ matrix.driver }}"' in run+ assert 'catalog="$root/signed-catalog.json"' in run+ assert 'test ! -e "$install_home"' in run+ absent_check = run.index('test ! -e "$install_home"')+ first_driver_call = run.index('CUA_DRIVER_RS_HOME="$install_home"', absent_check)+ assert run[absent_check:first_driver_call].strip() == 'test ! -e "$install_home"'+ assert 'mkdir "$install_home"' not in run+ assert run.count('CUA_DRIVER_RS_HOME="$install_home"') == 2+ assert 'extension install cua-perception --catalog "$catalog"' in run+ assert 'extension status cua-perception --self-test --json > "$status"' in run+ for contract in (+ 'installed["installed"] is True',+ 'installed["healthy"] is True',+ 'installed["trust"] == "review-only-publisher-verified"',+ 'installed["evidence_class"] == "review-only-not-release-evidence"',+ 'installed["publisher_id"] == measurements["publisher_id"] == "cua-review-only"',+ 'installed["publisher_key_id"] == measurements["key_id"] == "review-only-build-override"',+ 'installed["active_version"] == measurements["extension_version"]',+ 'installed["protocol_version"] == measurements["protocol_version"]',+ ):+ assert contract in rundiff --git a/.github/scripts/tests/test_e2e_rust_linux_workflow.py b/.github/scripts/tests/test_e2e_rust_linux_workflow.pynew file mode 100644index 0000000000..3a2debcb43--- /dev/null+++ b/.github/scripts/tests/test_e2e_rust_linux_workflow.py@@ -0,0 +1,21 @@+from pathlib import Path+++ROOT = Path(__file__).resolve().parents[3]+WORKFLOW = ROOT / ".github/workflows/e2e-rust-linux.yml"+++def test_canonical_certification_is_fail_closed_and_complete() -> None:+ workflow = WORKFLOW.read_text(encoding="utf-8")+ certification = workflow.split("\n certify:\n", 1)[1]++ assert (+ "if: success() && github.event_name == 'workflow_dispatch' && inputs.lane == 'all'"+ in certification+ )+ assert "needs: [source, shared, native, capture, installer]" in certification+ assert 'schema "cua-driver/e2e-certification/v1"' in certification+ assert 'platform "linux"' in certification+ for job in ("shared", "native", "capture", "installer"):+ assert f'{job}: "success"' in certification+ assert "name: rust-linux-e2e-certification" in certificationdiff --git a/.github/scripts/tests/test_e2e_rust_windows_workflow.py b/.github/scripts/tests/test_e2e_rust_windows_workflow.pynew file mode 100644index 0000000000..0c969b6233--- /dev/null+++ b/.github/scripts/tests/test_e2e_rust_windows_workflow.py@@ -0,0 +1,98 @@+import json+import os+from pathlib import Path+import subprocess++import yaml+++ROOT = Path(__file__).resolve().parents[3]+WORKFLOW = ROOT / ".github/workflows/e2e-rust-windows.yml"+++def matrix_summary_script() -> str:+ workflow = yaml.safe_load(WORKFLOW.read_text(encoding="utf-8"))+ steps = workflow["jobs"]["summary"]["steps"]+ return next(step["run"] for step in steps if step.get("name") == "Publish matrix summary")+++def test_canonical_certification_is_fail_closed_and_github_hosted() -> None:+ workflow = WORKFLOW.read_text(encoding="utf-8")+ certification = workflow.split("\n certify:\n", 1)[1]++ assert (+ "if: success() && github.event_name == 'workflow_dispatch' && inputs.lane == 'all'"+ in certification+ )+ assert "needs: [source, shared, native, capture, installer]" in certification+ assert "windows-latest|windows-2022|windows-2025" in certification+ assert "class=github-hosted" in certification+ assert 'schema "cua-driver/e2e-certification/v1"' in certification+ assert 'platform "windows"' in certification+ assert "runner_policy_class: $runner_policy_class" in certification+ assert "name: rust-windows-e2e-certification" in certification+++def test_matrix_summary_recovers_results_when_lane_summary_is_missing(tmp_path: Path) -> None:+ artifact = tmp_path / "artifacts/rust-windows-native"+ artifact.mkdir(parents=True)+ records = [+ {+ "cell_id": "windows-wpf-click",+ "test_status": "fail",+ "observed_behavior": "error",+ "message": "fixture stopped | unexpectedly",+ "evidence": {"video": "recordings/windows-wpf-click/recording.mp4"},+ },+ {+ "cell_id": "windows-winui3-snapshot",+ "test_status": "pass",+ "observed_behavior": "delivered",+ "message": "",+ "evidence": {},+ },+ ]+ (artifact / "results.jsonl").write_text(+ "".join(json.dumps(record) + "\n" for record in records), encoding="utf-8"+ )++ bin_dir = tmp_path / "bin"+ bin_dir.mkdir()+ gh = bin_dir / "gh"+ gh.write_text(+ "#!/usr/bin/env bash\n"+ 'printf \'%s\\n\' \'{"artifacts":[{"name":"rust-windows-native","id":1234}]}\'\n',+ encoding="utf-8",+ )+ gh.chmod(0o755)++ step_summary = tmp_path / "step-summary.md"+ env = os.environ.copy()+ env.update(+ {+ "PATH": f"{bin_dir}:{env['PATH']}",+ "GITHUB_REPOSITORY": "cua/example",+ "GITHUB_RUN_ID": "77",+ "GITHUB_SERVER_URL": "https://github.example",+ "GITHUB_STEP_SUMMARY": str(step_summary),+ "SOURCE_SHA": "0123456789abcdef0123456789abcdef01234567",+ }+ )+ subprocess.run(+ ["bash", "-euo", "pipefail", "-c", matrix_summary_script()],+ cwd=tmp_path,+ env=env,+ check=True,+ )++ summary = (tmp_path / "matrix-summary.md").read_text(encoding="utf-8")+ assert "Source commit: `0123456789abcdef0123456789abcdef01234567`" in summary+ assert "## rust-windows-native" in summary+ assert "The lane did not produce `summary.md`." in summary+ assert "Records: 2; pass: 1; fail: 1; other: 0." in summary+ artifact_url = "https://github.example/cua/example/actions/runs/77/artifacts/1234"+ assert f"[Download rust-windows-native]({artifact_url})" in summary+ assert "| windows-wpf-click | fail | error | fixture stopped \\| unexpectedly |" in summary+ assert f"[recordings/windows-wpf-click/recording.mp4]({artifact_url})" in summary+ assert "No lane summary artifact was produced." not in summary+ assert step_summary.read_text(encoding="utf-8") == summarydiff --git a/.github/scripts/tests/test_macos_hosted_e2e_workflow.py b/.github/scripts/tests/test_macos_hosted_e2e_workflow.pyindex 3feb48b6fb..d6366738e8 100644--- a/.github/scripts/tests/test_macos_hosted_e2e_workflow.py+++ b/.github/scripts/tests/test_macos_hosted_e2e_workflow.py@@ -18,7 +18,7 @@ def test_hosted_macos_probe_is_manual_exact_sha_and_least_privilege() -> None:assert "pull_request:" not in triggerassert "push:" not in triggerassert "source_sha:" in trigger- assert "permissions:\n contents: read\n" in workflow+ assert "permissions:\n actions: read\n contents: read\n pull-requests: read\n" in workflowassert "id-token: write" not in workflowassert "secrets." not in workflowassert "runs-on: macos-26" in workflow@@ -39,6 +39,9 @@ def test_hosted_macos_probe_is_manual_exact_sha_and_least_privilege() -> None:assert "cua-driver/macos-hosted-certification@v1" in workflowassert "workflow_ref: $workflow_ref" in workflowassert "workflow_sha: $workflow_sha" in workflow+ assert "live_jev_perception" not in workflow+ assert "authorized-live-jev-macos-evidence.yml" not in workflow+ assert "secrets: inherit" not in workflowfor action in ("actions/checkout", "actions/upload-artifact"):line = next(line for line in workflow.splitlines() if f"uses: {action}@" in line)@@ -47,6 +50,37 @@ def test_hosted_macos_probe_is_manual_exact_sha_and_least_privilege() -> None:assert all(character in "0123456789abcdef" for character in revision)+def test_lume_certification_registers_a_direct_console_run_without_a_self_hosted_runner() -> None:+ workflow = read(".github/workflows/e2e-rust-macos.yml")+ runner = read("libs/cua-driver/tests/runners/macos-lume/run-all.sh")++ assert "workflow_dispatch:" in workflow+ assert "source_sha:" in workflow+ assert "direct_lume_run_id:" in workflow+ assert "direct_lume_evidence_sha256:" in workflow+ assert "direct_lume_result_base64:" in workflow+ assert "name: Register direct Lume certification" in workflow+ assert "runs-on: [self-hosted, macOS, ARM64, cua-lume-maintainer]" not in workflow+ assert "runs-on: ubuntu-latest" in workflow+ assert "environment: authorized-live-jev-use-demo" in workflow+ assert "source_sha must match the selected workflow ref tip" in workflow+ assert "cua-driver/macos-lume-direct-result@v1" in workflow+ assert 'schema "cua-driver/macos-lume-certification@v2"' in workflow+ assert 'workflow_path ".github/workflows/e2e-rust-macos.yml"' in workflow+ assert 'kind: "direct-lume-console"' in workflow+ assert "direct-result.json" in workflow+ assert "libs/cua-driver/tests/runners/macos-lume/run-all.sh --standalone-browser" not in workflow+ assert "jq -e '.passed == true' certification.json" in workflow+ assert '"${ARTIFACT_DIR}/run-id.txt"' in runner+ assert "cua-driver/macos-lume-direct-result@v1" in runner+ assert '"${ARTIFACT_DIR}/direct-result.json"' in runner+ assert runner.index("BROWSER_STATUS") < runner.index("macos-lume-direct-result@v1")+ assert (+ "name: rust-macos-lume-certification-${{ github.run_id }}-${{ github.run_attempt }}"+ in workflow+ )++def test_hosted_macos_probe_fails_closed_before_gui_capture() -> None:probe = read("scripts/ci/macos/probe-hosted-runner.sh")@@ -66,9 +100,7 @@ def test_hosted_macos_probe_fails_closed_before_gui_capture() -> None:assert "trap write_environment EXIT" in probeassert "AXIsProcessTrusted" in read("scripts/ci/macos/verify-hosted-window.swift")- assert "CGPreflightScreenCaptureAccess" in read(- "scripts/ci/macos/verify-hosted-window.swift"- )+ assert "CGPreflightScreenCaptureAccess" in read("scripts/ci/macos/verify-hosted-window.swift")def test_hosted_macos_probe_proves_textedit_window_content() -> None:@@ -90,7 +122,7 @@ def test_hosted_macos_probe_proves_textedit_window_content() -> None:assert "textedit-window.png" in probeassert "display.png" in probeassert "run_with_deadline 30 /usr/bin/killall TextEdit" in probe- assert 'pgrep -x TextEdit' in probe+ assert "pgrep -x TextEdit" in probedef test_script_ci_runs_when_hosted_macos_contract_changes() -> None:@@ -103,6 +135,8 @@ def test_script_ci_runs_when_hosted_macos_contract_changes() -> None:assert "e2e-rust-macos.yml" in guideassert "temporary certificate-backed identity" in " ".join(guide.split())assert "supplemental" in guide+ assert "do not install or register a GitHub Actions runner" in guide+ assert "direct result" in guidedef test_hosted_macos_runner_is_strict_and_uses_the_canonical_matrix() -> None:@@ -139,7 +173,7 @@ def test_hosted_macos_runner_is_strict_and_uses_the_canonical_matrix() -> None:assert "security verify-cert" not in runnerassert "security set-key-partition-list" in runnerassert "set-keychain-settings -lut 21600" in runner- assert 'security list-keychains -d user -s' in runner+ assert "security list-keychains -d user -s" in runnerassert '"${ORIGINAL_KEYCHAINS[@]}"' in runnerassert "run_bounded 30 codesign" in runnerassert "phase.txt" in runner@@ -154,13 +188,13 @@ def test_hosted_macos_runner_is_strict_and_uses_the_canonical_matrix() -> None:assert "seed-tcc-guest.sh" in runnerassert "--expected-client com.trycua.driver.local" in runnerassert "--dangerously-bypass-approvals" in runner- assert ".direct_capture_status == \"not_checked\"" in runner+ assert '.direct_capture_status == "not_checked"' in runnerassert '.source.attribution == "driver-daemon"' in runnerassert 'bash "${SCRIPT_DIR}/run-rust-e2e.sh"' in runnerassert 'CUA_E2E_MACOS_DAEMON_SOCKET="${DAEMON_SOCKET}"' in runnerassert '--socket "${DAEMON_SOCKET}"' in runner- assert 'trap \'exit 130\' INT' in runner- assert 'trap \'exit 143\' TERM' in runner+ assert "trap 'exit 130' INT" in runner+ assert "trap 'exit 143' TERM" in runnerassert 'bash "${SCRIPT_DIR}/probe-hosted-runner.sh"' in runnerassert "watch_daemon" in runnerassert "daemon status probe failed; confirming before restart" in runnerdiff --git a/.github/scripts/tests/test_merge_release_please_manifests.py b/.github/scripts/tests/test_merge_release_please_manifests.pyindex 72e1b97df1..3ace4e23dd 100644--- a/.github/scripts/tests/test_merge_release_please_manifests.py+++ b/.github/scripts/tests/test_merge_release_please_manifests.py@@ -90,6 +90,25 @@ class TestMergeReleasePleaseManifests(unittest.TestCase):["lume"],)+ def test_perception_release_preserves_product_versions(self) -> None:+ current = {+ "libs/cua-driver/rust/crates/cua-perception": "0.1.0",+ "libs/cua-driver": "0.28.2",+ "libs/lume": "0.5.3",+ }+ release = {+ "libs/cua-driver/rust/crates/cua-perception": "0.2.0",+ "libs/cua-driver": "0.27.0",+ "libs/lume": "0.5.2",+ }+ self.assertEqual(+ MODULE.merge_component_versions(current, release, ["cua-perception"]),+ {+ **current,+ "libs/cua-driver/rust/crates/cua-perception": "0.2.0",+ },+ )+if __name__ == "__main__":unittest.main()diff --git a/.github/scripts/tests/test_perception_release.py b/.github/scripts/tests/test_perception_release.pynew file mode 100644index 0000000000..b75ba0c029--- /dev/null+++ b/.github/scripts/tests/test_perception_release.py@@ -0,0 +1,49 @@+from __future__ import annotations++import importlib.util+import json+from pathlib import Path++import pytest+++ROOT = Path(__file__).resolve().parents[3]+SPEC = importlib.util.spec_from_file_location(+ "perception_release", ROOT / ".github/scripts/perception_release.py"+)+assert SPEC and SPEC.loader+release = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(release)+++def test_manifest_version_uses_crate_authority(monkeypatch, tmp_path: Path):+ version_authority = tmp_path / "crate/VERSION"+ version_authority.parent.mkdir(parents=True)+ version_authority.write_text("1.2.3\n", encoding="utf-8")+ manifest_path = tmp_path / "manifest.json"+ manifest_path.write_text(+ json.dumps(+ {+ "schemaVersion": 1,+ "component": "cua-perception",+ "version": "9.9.9",+ "driverVersion": "1.0.0",+ "sourceSha": "a" * 40,+ "target": {},+ "protocol": {},+ "artifacts": [],+ "modelLedger": {},+ "sourceLedger": {},+ "suppliedVerification": {},+ }+ ),+ encoding="utf-8",+ )+ monkeypatch.setattr(release, "VERSION_AUTHORITY", version_authority)+ monkeypatch.setattr(release, "validate_schema", lambda *_args: None)++ with pytest.raises(+ release.CandidateError,+ match=r"candidate version 9\.9\.9 differs from release authority 1\.2\.3",+ ):+ release.load_and_validate_manifest(manifest_path, tmp_path)diff --git a/.github/scripts/tests/test_release_attribution.py b/.github/scripts/tests/test_release_attribution.pyindex 8c6f8223b0..344a442c76 100644--- a/.github/scripts/tests/test_release_attribution.py+++ b/.github/scripts/tests/test_release_attribution.py@@ -15,6 +15,7 @@ from release_attribution import (_change_contributors,build_manifest,changelog_references_change,+ is_perception_only_diff,linked_issue_numbers,login_from_email,merge_contributors,@@ -118,6 +119,22 @@ def test_release_tracked_changes_require_a_releasing_title_or_explicit_opt_out())+def test_perception_diff_scope_includes_crate_and_release_controls():+ assert is_perception_only_diff(+ [+ "libs/cua-driver/rust/crates/cua-perception/VERSION",+ "libs/cua-driver/rust/crates/cua-perception/CHANGELOG.md",+ ".github/releases/cua-perception/artifact-manifest.schema.json",+ ]+ )+ assert not is_perception_only_diff(+ [+ "libs/cua-driver/rust/crates/cua-perception/VERSION",+ ".github/releases/components.json",+ ]+ )++def test_login_from_noreply_and_override():assert login_from_email("[email protected]", {}) == "octo-user"assert (diff --git a/.github/scripts/tests/test_release_channels.py b/.github/scripts/tests/test_release_channels.pyindex 1866efb60f..90c73a7a3e 100644--- a/.github/scripts/tests/test_release_channels.py+++ b/.github/scripts/tests/test_release_channels.py@@ -60,13 +60,28 @@ def test_registry_matches_release_please_and_channel_prefixes_are_disjoint():schema = json.loads((ROOT / ".github/releases/component.schema.json").read_text())Draft202012Validator(schema).validate(json.loads(REGISTRY.read_text()))registry = load_registry(REGISTRY, root=ROOT)- assert set(registry["components"]) == {"cua-driver-rs", "lume"}+ assert set(registry["components"]) == {"cua-driver-rs", "cua-perception", "lume"}+ assert registry["components"]["cua-perception"]["candidateOnly"] is True+ assert registry["components"]["cua-perception"]["channels"]["nightly"] is Falseall_prefixes = {component[key]for component in registry["components"].values()for key in ("stableTagPrefix", "nightlyTagPrefix")}- assert len(all_prefixes) == 4+ assert len(all_prefixes) == 2 * len(registry["components"])+++def test_candidate_only_component_rejects_nightly_planning():+ with pytest.raises(ChannelError, match="does not enable nightly publication"):+ plan_nightly(+ "cua-perception",+ "a" * 40,+ "20260812",+ "1",+ [],+ registry_path=REGISTRY,+ root=ROOT,+ )@pytest.mark.parametrize(@@ -245,11 +260,24 @@ def test_plan_builds_only_for_declared_relevant_changes(monkeypatch: pytest.Monkif command == "merge-base":assert args == ("--is-ancestor", previous_sha, source_sha)return ""- assert command == "diff"- assert "libs/cua-driver" in args- return "libs/cua-driver/rust/crates/cua-driver/src/main.rs"+ raise AssertionError((command, args))monkeypatch.setattr(release_channels, "_git", fake_git)+ monkeypatch.setattr(+ release_channels.release_attribution,+ "commits_in_range",+ lambda _root, _previous, _source, paths, excluded, companions: (+ [+ release_channels.release_attribution.CommitRecord(+ "deadbeef", "fix(cua-driver): preserve input", ""+ )+ ]+ if "libs/cua-driver" in paths+ and "libs/cua-driver/rust/crates/cua-perception" in excluded+ and "libs/cua-driver/rust/Cargo.toml" in companions+ else []+ ),+ )plan = plan_nightly("cua-driver-rs",source_sha,@@ -271,6 +299,82 @@ def test_plan_builds_only_for_declared_relevant_changes(monkeypatch: pytest.Monkassert plan["attributionBaseTag"] == plan["previousNightlyTag"]+def test_driver_plan_ignores_perception_only_changes(monkeypatch: pytest.MonkeyPatch):+ previous_sha = "b" * 40+ source_sha = "c" * 40++ def fake_git(_root, command, *args):+ if command == "rev-list":+ return previous_sha+ if command == "merge-base":+ return ""+ raise AssertionError((command, args))++ monkeypatch.setattr(release_channels, "_git", fake_git)+ monkeypatch.setattr(+ release_channels.release_attribution,+ "commits_in_range",+ lambda _root, _previous, _source, paths, excluded, companions: (+ []+ if "libs/cua-driver" in paths+ and "libs/cua-driver/rust/crates/cua-perception" in excluded+ and "libs/cua-driver/rust/Cargo.toml" in companions+ else [object()]+ ),+ )+ plan = plan_nightly(+ "cua-driver-rs",+ source_sha,+ "20260812",+ "45",+ [+ {+ "tag_name": "nightly-cua-driver-rs-v0.19.4-nightly.20260811.41",+ "draft": False,+ "published_at": "2026-08-11T04:17:00Z",+ }+ ],+ registry_path=REGISTRY,+ root=ROOT,+ )+ assert plan["shouldBuild"] is False+ assert plan["reason"] == "component-unchanged"+++def test_first_driver_nightly_ignores_perception_only_changes(+ monkeypatch: pytest.MonkeyPatch,+):+ source_sha = "c" * 40++ def fake_git(_root, command, *args):+ if command == "rev-list":+ assert args == ("-n", "1", "cua-driver-rs-v0.28.2")+ return "b" * 40+ if command == "merge-base":+ return ""+ raise AssertionError((command, args))++ monkeypatch.setattr(release_channels, "_git", fake_git)+ monkeypatch.setattr(+ release_channels.release_attribution,+ "commits_in_range",+ lambda _root, previous, _source, _paths, _excluded, _companions: (+ [] if previous == "cua-driver-rs-v0.28.2" else [object()]+ ),+ )+ plan = plan_nightly(+ "cua-driver-rs",+ source_sha,+ "20260812",+ "46",+ [],+ registry_path=REGISTRY,+ root=ROOT,+ )+ assert plan["shouldBuild"] is False+ assert plan["reason"] == "component-unchanged"++def test_plan_holds_before_build_for_unresolved_attribution(monkeypatch: pytest.MonkeyPatch, tmp_path: Path):@@ -366,6 +470,15 @@ def test_manifest_uses_stable_authority_with_a_separately_versioned_asset_tree((assets / "cua-driver.tar.gz").write_bytes(b"nightly")def fake_build_manifest(**kwargs):+ assert kwargs["exclude_paths"] == [+ "libs/cua-driver/examples",+ "libs/cua-driver/experiments/cua-perception-inference",+ "libs/cua-driver/rust/crates/cua-perception",+ ]+ assert kwargs["exclude_companion_paths"] == [+ "libs/cua-driver/rust/Cargo.lock",+ "libs/cua-driver/rust/Cargo.toml",+ ]return {"version": kwargs["version"], "tag": kwargs["tag"]}monkeypatch.setattr(release_channels.release_attribution, "build_manifest", fake_build_manifest)diff --git a/.github/scripts/tests/test_resolve_release_please_request.py b/.github/scripts/tests/test_resolve_release_please_request.pyindex fd45eeb422..264b3f784f 100644--- a/.github/scripts/tests/test_resolve_release_please_request.py+++ b/.github/scripts/tests/test_resolve_release_please_request.py@@ -15,6 +15,7 @@ SPEC.loader.exec_module(MODULE)class TestResolveReleasePleaseRequest(unittest.TestCase):def setUp(self) -> None:self.manifest = {+ "libs/cua-driver/rust/crates/cua-perception": "0.1.0","libs/cua-driver": "0.9.0","libs/lume": "0.4.7","libs/python/cua-sandbox": "0.4.3",@@ -24,10 +25,14 @@ class TestResolveReleasePleaseRequest(unittest.TestCase):driver = MODULE.resolve_request(self.manifest, "cua-driver-rs", "automatic")lume = MODULE.resolve_request(self.manifest, "lume", "automatic")sandbox = MODULE.resolve_request(self.manifest, "sandbox", "automatic")+ perception = MODULE.resolve_request(self.manifest, "cua-perception", "automatic")self.assertEqual(driver["path"], "libs/cua-driver")self.assertEqual(lume["path"], "libs/lume")self.assertEqual(sandbox["path"], "libs/python/cua-sandbox")+ self.assertEqual(+ perception["path"], "libs/cua-driver/rust/crates/cua-perception"+ )self.assertEqual(sandbox["current_version"], "0.4.3")self.assertIsNone(sandbox["release_as"])self.assertIsNone(driver["release_as"])diff --git a/.github/scripts/tests/test_validate_release_versions.py b/.github/scripts/tests/test_validate_release_versions.pyindex e56dc1aca4..19b9d39e19 100644--- a/.github/scripts/tests/test_validate_release_versions.py+++ b/.github/scripts/tests/test_validate_release_versions.py@@ -45,6 +45,58 @@ def test_sandbox_product_cli_accepts_current_versions():assert main(["--repo-root", str(REPO_ROOT), "--product", "sandbox"]) == 0+def test_perception_product_cli_accepts_current_versions():+ assert main(["--repo-root", str(REPO_ROOT), "--product", "perception"]) == 0++[email protected]("product", ["perception", "all"])+def test_perception_versions_use_independent_authority(tmp_path: Path, product: str):+ copy_release_sources(tmp_path)+ base = tmp_path / "libs/cua-driver/rust/crates/cua-perception"+ (base / "VERSION").write_text("0.1.0\n")++ validate(tmp_path, product)++[email protected]("product", ["perception", "all"])+ ("source", "expected"),+ [+ ("VERSION", "Cua Perception expects 9.9.9"),+ ("Cargo.toml", "Cargo.toml=9.9.9"),+ ("Cargo.lock", "Cargo.lock:cua-perception=9.9.9"),+ (".release-please-manifest.json", ".release-please-manifest.json=9.9.9"),+ ],+)+def test_perception_version_drift_fails(+ tmp_path: Path, product: str, source: str, expected: str+):+ copy_release_sources(tmp_path)+ base = tmp_path / "libs/cua-driver/rust/crates/cua-perception"+ (base / "VERSION").write_text("0.1.0\n")+ if source == ".release-please-manifest.json":+ path = tmp_path / source+ manifest = json.loads(path.read_text())+ manifest["libs/cua-driver/rust/crates/cua-perception"] = "9.9.9"+ path.write_text(json.dumps(manifest))+ elif source == "Cargo.lock":+ path = tmp_path / "libs/cua-driver/rust/Cargo.lock"+ path.write_text(+ re.sub(+ r'(\[\[package\]\]\nname = "cua-perception"\nversion = ")0\.1\.0("\n)',+ r"\g<1>9.9.9\2",+ path.read_text(),+ count=1,+ )+ )+ else:+ path = base / source+ path.write_text(path.read_text().replace("0.1.0", "9.9.9", 1))++ with pytest.raises(VersionError, match=re.escape(expected)):+ validate(tmp_path, product)++@pytest.mark.parametrize("product", ["sandbox", "all"])@pytest.mark.parametrize("source",diff --git a/.github/scripts/tests/test_verify_cua_driver_release_archives.py b/.github/scripts/tests/test_verify_cua_driver_release_archives.pyindex f1dec3b0db..f73473cf76 100644--- a/.github/scripts/tests/test_verify_cua_driver_release_archives.py+++ b/.github/scripts/tests/test_verify_cua_driver_release_archives.py@@ -6,6 +6,7 @@ import tarfileimport zipfileimport pytest+import verify_cua_driver_release_archives as archive_verifierfrom verify_cua_driver_release_archives import (ArchiveContract,@@ -18,10 +19,21 @@ from verify_cua_driver_release_archives import (VERSION = "9.8.7"+def _payload(contract: ArchiveContract, name: str) -> bytes:+ if name in contract.binary_members:+ magic = {+ "elf": b"\x7fELF",+ "pe": b"MZ",+ "mach-o": b"\xca\xfe\xba\xbe",+ }[contract.binary_format]+ return magic + f" binary payload for {name}".encode()+ return f"payload for {name}".encode()++def _write_tar(path: Path, contract: ArchiveContract) -> None:with tarfile.open(path, "w:gz") as archive:for name in contract.members:- payload = f"payload for {name}".encode()+ payload = _payload(contract, name)info = tarfile.TarInfo(name)info.size = len(payload)info.mode = 0o755 if name in contract.executable_members else 0o644@@ -31,7 +43,29 @@ def _write_tar(path: Path, contract: ArchiveContract) -> None:def _write_zip(path: Path, contract: ArchiveContract) -> None:with zipfile.ZipFile(path, "w") as archive:for name in contract.members:- archive.writestr(name, f"payload for {name}")+ archive.writestr(name, _payload(contract, name))+++def _rewrite_with_extra_member(+ path: Path, contract: ArchiveContract, name: str, payload: bytes = b"optional payload"+) -> None:+ if path.name.endswith(".tar.gz"):+ with tarfile.open(path, "w:gz") as archive:+ for member_name in dict.fromkeys((*contract.members, name)):+ member_payload = (+ payload if member_name == name else _payload(contract, member_name)+ )+ info = tarfile.TarInfo(member_name)+ info.size = len(member_payload)+ info.mode = 0o755 if member_name in contract.executable_members else 0o644+ archive.addfile(info, BytesIO(member_payload))+ else:+ with zipfile.ZipFile(path, "w") as archive:+ for member_name in dict.fromkeys((*contract.members, name)):+ member_payload = (+ payload if member_name == name else _payload(contract, member_name)+ )+ archive.writestr(member_name, member_payload)def _write_valid_release(root: Path) -> tuple[ArchiveContract, ...]:@@ -67,6 +101,9 @@ def test_missing_cursor_theme_fails_with_archive_and_member(target.filename,tuple(member for member in target.members if member != missing),tuple(member for member in target.executable_members if member != missing),+ target.optional_members,+ tuple(member for member in target.binary_members if member != missing),+ target.binary_format,)_write_tar(tmp_path / target.filename, broken)@@ -90,7 +127,13 @@ def test_non_executable_unix_binary_fails_closed(tmp_path: Path) -> None:for contract in contractsif contract.filename.endswith("linux-x86_64-binary.tar.gz"))- broken = ArchiveContract(target.filename, target.members)+ broken = ArchiveContract(+ target.filename,+ target.members,+ optional_members=target.optional_members,+ binary_members=target.binary_members,+ binary_format=target.binary_format,+ )_write_tar(tmp_path / target.filename, broken)with pytest.raises(@@ -98,3 +141,125 @@ def test_non_executable_unix_binary_fails_closed(tmp_path: Path) -> None:match=rf"{target.filename} contains non-executable member cua-driver",):verify_release_archives(tmp_path, VERSION)+++ ("archive_suffix", "member"),+ (+ ("linux-x86_64-binary.tar.gz", "cua-perception"),+ ("darwin-universal.tar.gz", "models/detector.onnx"),+ ("windows-x86_64.zip", "onnxruntime.dll"),+ ("windows-arm64-binary.zip", "signed-catalog.json"),+ ),+)+def test_optional_perception_payload_fails_closed(+ tmp_path: Path, archive_suffix: str, member: str+) -> None:+ contracts = _write_valid_release(tmp_path)+ target = next(contract for contract in contracts if contract.filename.endswith(archive_suffix))+ _rewrite_with_extra_member(tmp_path / target.filename, target, member)++ with pytest.raises(+ ContractError,+ match=rf"{target.filename} contains (?:forbidden optional perception payload .*|unexpected member)",+ ):+ verify_release_archives(tmp_path, VERSION)+++def test_agpl_notice_content_fails_closed(tmp_path: Path) -> None:+ contracts = _write_valid_release(tmp_path)+ target = next(+ contract for contract in contracts if contract.filename.endswith("linux-arm64.tar.gz")+ )+ member = f"cua-driver-rs-{VERSION}-linux-arm64/LICENSE"+ _rewrite_with_extra_member(+ tmp_path / target.filename,+ target,+ member,+ b"GNU AFFERO GENERAL PUBLIC LICENSE Version 3",+ )++ with pytest.raises(ContractError, match=rf"\(AGPL notice\): {member}"):+ verify_release_archives(tmp_path, VERSION)+++def test_unrecognized_member_fails_closed(tmp_path: Path) -> None:+ contracts = _write_valid_release(tmp_path)+ target = next(+ contract for contract in contracts if contract.filename.endswith("darwin-universal-binary.tar.gz")+ )+ _rewrite_with_extra_member(+ tmp_path / target.filename,+ target,+ "debug-symbols.txt",+ )++ with pytest.raises(ContractError, match="contains unexpected member debug-symbols.txt"):+ verify_release_archives(tmp_path, VERSION)+++def test_binary_linkage_marker_fails_closed(tmp_path: Path) -> None:+ contracts = _write_valid_release(tmp_path)+ target = next(+ contract for contract in contracts if contract.filename.endswith("linux-x86_64-binary.tar.gz")+ )+ _rewrite_with_extra_member(+ tmp_path / target.filename,+ ArchiveContract(+ target.filename,+ tuple(member for member in target.members if member != "cua-driver"),+ target.executable_members,+ binary_members=tuple(+ member for member in target.binary_members if member != "cua-driver"+ ),+ binary_format=target.binary_format,+ ),+ "cua-driver",+ b"\x7fELF linked libonnxruntime.so",+ )++ with pytest.raises(ContractError, match="binary links or vendors optional perception runtime"):+ verify_release_archives(tmp_path, VERSION)+++def test_binary_format_fails_closed(tmp_path: Path) -> None:+ contracts = _write_valid_release(tmp_path)+ target = next(+ contract for contract in contracts if contract.filename.endswith("windows-x86_64-binary.zip")+ )+ _rewrite_with_extra_member(+ tmp_path / target.filename,+ ArchiveContract(+ target.filename,+ tuple(member for member in target.members if member != "cua-driver.exe"),+ binary_members=tuple(+ member for member in target.binary_members if member != "cua-driver.exe"+ ),+ binary_format=target.binary_format,+ ),+ "cua-driver.exe",+ b"not a PE binary",+ )++ with pytest.raises(ContractError, match="member is not pe binary"):+ verify_release_archives(tmp_path, VERSION)+++def test_oversized_binary_fails_closed(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ contracts = _write_valid_release(tmp_path)+ target = next(+ contract for contract in contracts if contract.filename.endswith("linux-x86_64-binary.tar.gz")+ )+ monkeypatch.setattr(archive_verifier, "MAX_BINARY_SIZE", 8)++ with pytest.raises(ContractError, match="binary exceeds 8 bytes"):+ verify_release_archives(tmp_path, VERSION)+++def test_oversized_archive_fails_closed(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ contracts = _write_valid_release(tmp_path)+ target = contracts[0]+ monkeypatch.setattr(archive_verifier, "MAX_ARCHIVE_UNCOMPRESSED_SIZE", 8)++ with pytest.raises(ContractError, match=rf"{target.filename} uncompressed payload is too large"):+ verify_release_archives(tmp_path, VERSION)diff --git a/.github/scripts/validate_release_versions.py b/.github/scripts/validate_release_versions.pyindex cb8f0e22dc..5e9f363ac4 100644--- a/.github/scripts/validate_release_versions.py+++ b/.github/scripts/validate_release_versions.py@@ -1,5 +1,5 @@#!/usr/bin/env python3-"""Verify that checked-in Driver, Lume, and Sandbox release versions agree."""+"""Verify that checked-in product release versions agree."""from __future__ import annotations@@ -99,6 +99,7 @@ def driver_versions(root: Path) -> tuple[str, dict[str, str]]:local_names = {tomllib.loads((member / "Cargo.toml").read_text())["package"]["name"] for member in members}+ local_names.discard("cua-perception")lock = tomllib.loads((base / "rust/Cargo.lock").read_text())for package in lock["package"]:if package["name"] in local_names:@@ -111,6 +112,21 @@ def driver_versions(root: Path) -> tuple[str, dict[str, str]]:return expected, values+def perception_versions(root: Path) -> tuple[str, dict[str, str]]:+ base = root / "libs/cua-driver/rust/crates/cua-perception"+ expected = (base / "VERSION").read_text().strip()+ project = tomllib.loads((base / "Cargo.toml").read_text())+ lock = tomllib.loads((root / "libs/cua-driver/rust/Cargo.lock").read_text())+ packages = [entry for entry in lock["package"] if entry["name"] == "cua-perception"]+ if len(packages) != 1:+ raise VersionError("Cargo.lock must contain exactly one cua-perception package")+ stable_version_tuple(expected)+ return expected, {+ "Cargo.toml": str(project["package"]["version"]),+ "Cargo.lock:cua-perception": str(packages[0]["version"]),+ }++def lume_versions(root: Path) -> tuple[str, dict[str, str]]:base = root / "libs/lume"docs = root / "docs/content/docs/reference/lume"@@ -167,6 +183,12 @@ def validate(root: Path, product: str) -> None:f"Cua Driver baked installers advertise {installer_version}, "f"ahead of source release {expected}")+ if product in {"all", "perception"}:+ expected, values = perception_versions(root)+ values[".release-please-manifest.json"] = str(+ manifest["libs/cua-driver/rust/crates/cua-perception"]+ )+ require_equal("Cua Perception", expected, values)if product in {"all", "lume"}:expected, values = lume_versions(root)values[".release-please-manifest.json"] = str(manifest["libs/lume"])@@ -180,7 +202,11 @@ def validate(root: Path, product: str) -> None:def main(argv: Sequence[str] | None = None) -> int:parser = argparse.ArgumentParser(description=__doc__)parser.add_argument("--repo-root", type=Path, default=Path.cwd())- parser.add_argument("--product", choices=("all", "driver", "lume", "sandbox"), default="all")+ parser.add_argument(+ "--product",+ choices=("all", "driver", "perception", "lume", "sandbox"),+ default="all",+ )args = parser.parse_args(argv)try:validate(args.repo_root.resolve(), args.product)diff --git a/.github/scripts/verify_cua_driver_release_archives.py b/.github/scripts/verify_cua_driver_release_archives.pyindex fe65bc4338..b65e048954 100644--- a/.github/scripts/verify_cua_driver_release_archives.py+++ b/.github/scripts/verify_cua_driver_release_archives.py@@ -10,6 +10,31 @@ import tarfileimport zipfile+FORBIDDEN_MODEL_SUFFIXES = (".onnx", ".ort", ".gguf", ".safetensors")+AGPL_MARKERS = (b"agpl-", b"agpl ", b"gnu affero general public license")+NOTICE_NAMES = ("license", "notice", "copying")+FORBIDDEN_BINARY_MARKERS = (+ b"onnxruntime",+ b"OrtGetApiBase",+ b"onnxruntime_providers",+)+MAX_BINARY_SIZE = 128 * 1024 * 1024+MAX_ARCHIVE_UNCOMPRESSED_SIZE = 512 * 1024 * 1024++BINARY_MAGIC = {+ "elf": (b"\x7fELF",),+ "pe": (b"MZ",),+ "mach-o": (+ b"\xca\xfe\xba\xbe",+ b"\xca\xfe\xba\xbf",+ b"\xce\xfa\xed\xfe",+ b"\xcf\xfa\xed\xfe",+ b"\xfe\xed\xfa\xce",+ b"\xfe\xed\xfa\xcf",+ ),+}++class ContractError(RuntimeError):"""Raised when a release archive is missing or malformed."""@@ -19,6 +44,9 @@ class ArchiveContract:filename: strmembers: tuple[str, ...]executable_members: tuple[str, ...] = ()+ optional_members: tuple[str, ...] = ()+ binary_members: tuple[str, ...] = ()+ binary_format: str = ""def release_contracts(version: str) -> tuple[ArchiveContract, ...]:@@ -26,29 +54,43 @@ def release_contracts(version: str) -> tuple[ArchiveContract, ...]:contracts: list[ArchiveContract] = []- linux_payload = (+ linux_runtime = ("cua-driver","cua-cursor-theme","libcua_driver_sdk.so","cua_driver_node_runtime.node","cua_driver_abi.h",)+ linux_helper = (+ "wayland-helper/README.md",+ "wayland-helper/install.sh",+ "wayland-helper/winrects@cua/extension.js",+ "wayland-helper/winrects@cua/metadata.json",+ )+ linux_payload = linux_runtime + linux_helper+ linux_binaries = linux_runtime[:-1]for arch in ("x86_64", "arm64"):stage = f"cua-driver-rs-{version}-linux-{arch}"contracts.extend((ArchiveContract(f"{stage}.tar.gz",- tuple(f"{stage}/{member}" for member in linux_payload),+ tuple(f"{stage}/{member}" for member in (*linux_payload, "LICENSE")),(f"{stage}/cua-driver",f"{stage}/cua-cursor-theme",),+ binary_members=tuple(+ f"{stage}/{member}" for member in linux_binaries+ ),+ binary_format="elf",),ArchiveContract(f"{stage}-binary.tar.gz",linux_payload,("cua-driver", "cua-cursor-theme"),+ binary_members=linux_binaries,+ binary_format="elf",),))@@ -67,9 +109,18 @@ def release_contracts(version: str) -> tuple[ArchiveContract, ...]:(ArchiveContract(f"{stage}.zip",- tuple(f"{stage}/{member}" for member in windows_payload),+ tuple(f"{stage}/{member}" for member in (*windows_payload, "LICENSE")),+ binary_members=tuple(+ f"{stage}/{member}" for member in windows_payload[:-1]+ ),+ binary_format="pe",+ ),+ ArchiveContract(+ f"{stage}-binary.zip",+ windows_payload,+ binary_members=windows_payload[:-1],+ binary_format="pe",),- ArchiveContract(f"{stage}-binary.zip", windows_payload),))@@ -82,19 +133,36 @@ def release_contracts(version: str) -> tuple[ArchiveContract, ...]:"CuaDriver.app/Contents/Info.plist","CuaDriver.app/Contents/MacOS/cua-driver","CuaDriver.app/Contents/MacOS/cua-cursor-theme",+ "CuaDriver.app/Contents/Resources/AppIcon.icns",+ )+ macos_optional = (+ "CuaDriver.app/Contents/_CodeSignature/CodeResources",+ "CuaDriver.app/Contents/CodeResources",+ "CuaDriver.app/Contents/embedded.provisionprofile",+ )+ macos_binaries = (+ "cua-driver",+ "cua-cursor-theme",+ "libcua_driver_sdk.dylib",+ "cua_driver_node_runtime.node",+ "CuaDriver.app/Contents/MacOS/cua-driver",+ "CuaDriver.app/Contents/MacOS/cua-cursor-theme",)for label in ("darwin-arm64", "darwin-x86_64", "darwin-universal"):stage = f"cua-driver-rs-{version}-{label}"contracts.append(ArchiveContract(f"{stage}.tar.gz",- tuple(f"{stage}/{member}" for member in macos_payload),+ tuple(f"{stage}/{member}" for member in (*macos_payload, "LICENSE")),(f"{stage}/cua-driver",f"{stage}/cua-cursor-theme",f"{stage}/CuaDriver.app/Contents/MacOS/cua-driver",f"{stage}/CuaDriver.app/Contents/MacOS/cua-cursor-theme",),+ tuple(f"{stage}/{member}" for member in macos_optional),+ tuple(f"{stage}/{member}" for member in macos_binaries),+ "mach-o",))@@ -109,6 +177,13 @@ def release_contracts(version: str) -> tuple[ArchiveContract, ...]:"cua_driver_abi.h",),("cua-driver", "cua-cursor-theme"),+ binary_members=(+ "cua-driver",+ "cua-cursor-theme",+ "libcua_driver_sdk.dylib",+ "cua_driver_node_runtime.node",+ ),+ binary_format="mach-o",))return tuple(contracts)@@ -129,41 +204,179 @@ def _find_archive(root: Path, filename: str) -> Path:return matches[0]+def _forbidden_member_reason(name: str) -> str | None:+ normalized = _normalize_member(name).lower()+ path = f"/{normalized.strip('/')}"+ basename = PurePosixPath(normalized).name+ if "cua-perception" in normalized:+ return "cua-perception worker"+ if "/models/" in f"{path}/" or basename == "models":+ return "model directory"+ if basename.endswith(FORBIDDEN_MODEL_SUFFIXES):+ return "model payload"+ if "onnxruntime" in normalized:+ return "ONNX Runtime"+ if "catalog" in basename:+ return "extension catalog"+ if "agpl" in normalized:+ return "AGPL notice"+ return None+++def _verify_member_names(path: Path, names: tuple[str, ...]) -> None:+ for name in names:+ if reason := _forbidden_member_reason(name):+ raise ContractError(+ f"{path.name} contains forbidden optional perception payload "+ f"({reason}): {_normalize_member(name)}"+ )+++def _verify_notice_content(path: Path, name: str, payload: bytes) -> None:+ basename = PurePosixPath(_normalize_member(name)).name.lower()+ if not any(token in basename for token in NOTICE_NAMES):+ return+ lowered = payload.lower()+ if any(marker in lowered for marker in AGPL_MARKERS):+ raise ContractError(+ f"{path.name} contains forbidden optional perception payload "+ f"(AGPL notice): {_normalize_member(name)}"+ )+++def _allowed_directories(names: set[str]) -> set[str]:+ directories: set[str] = set()+ for name in names:+ parent = PurePosixPath(name).parent+ while str(parent) != ".":+ directories.add(str(parent))+ parent = parent.parent+ return directories+++def _verify_exact_members(+ path: Path,+ contract: ArchiveContract,+ file_names: tuple[str, ...],+ directory_names: tuple[str, ...],+) -> None:+ required = set(contract.members)+ allowed = required | set(contract.optional_members)+ actual = set(file_names)+ missing = sorted(required - actual)+ if missing:+ raise ContractError(f"{path.name} is missing {missing[0]}")+ unexpected = sorted(actual - allowed)+ if unexpected:+ raise ContractError(f"{path.name} contains unexpected member {unexpected[0]}")+ unexpected_directories = sorted(set(directory_names) - _allowed_directories(allowed))+ if unexpected_directories:+ raise ContractError(+ f"{path.name} contains unexpected directory {unexpected_directories[0]}"+ )+ if len(file_names) != len(actual):+ raise ContractError(f"{path.name} contains duplicate file members")+++def _verify_binary(path: Path, contract: ArchiveContract, name: str, payload: bytes) -> None:+ if len(payload) > MAX_BINARY_SIZE:+ raise ContractError(+ f"{path.name} binary exceeds {MAX_BINARY_SIZE} bytes: {name}"+ )+ magic = BINARY_MAGIC[contract.binary_format]+ if not payload.startswith(magic):+ raise ContractError(+ f"{path.name} member is not {contract.binary_format} binary: {name}"+ )+ lowered = payload.lower()+ for marker in FORBIDDEN_BINARY_MARKERS:+ if marker.lower() in lowered:+ raise ContractError(+ f"{path.name} binary links or vendors optional perception runtime "+ f"({marker.decode()}): {name}"+ )++def _verify_tar(path: Path, contract: ArchiveContract) -> None:with tarfile.open(path, "r:gz") as archive:+ archive_members = archive.getmembers()+ _verify_member_names(path, tuple(member.name for member in archive_members))members = {- _normalize_member(member.name): member- for member in archive.getmembers()- if member.isfile()+ _normalize_member(member.name): member for member in archive_members if member.isfile()}+ files = tuple(_normalize_member(member.name) for member in archive_members if member.isfile())+ directories = tuple(+ _normalize_member(member.name) for member in archive_members if member.isdir()+ )+ unsupported = next(+ (member for member in archive_members if not member.isfile() and not member.isdir()),+ None,+ )+ if unsupported is not None:+ raise ContractError(+ f"{path.name} contains unsupported archive member "+ f"{_normalize_member(unsupported.name)}"+ )+ _verify_exact_members(path, contract, files, directories)+ total_size = sum(member.size for member in members.values())+ if total_size > MAX_ARCHIVE_UNCOMPRESSED_SIZE:+ raise ContractError(f"{path.name} uncompressed payload is too large: {total_size}")++ for name, member in members.items():+ if member.size <= 0:+ raise ContractError(f"{path.name} contains empty member {name}")+ if any(token in PurePosixPath(name).name.lower() for token in NOTICE_NAMES):+ extracted = archive.extractfile(member)+ if extracted is not None:+ _verify_notice_content(path, name, extracted.read())+for expected in contract.members:member = members.get(expected)if member is None:raise ContractError(f"{path.name} is missing {expected}")- if member.size <= 0:- raise ContractError(f"{path.name} contains empty member {expected}")for expected in contract.executable_members:member = members.get(expected)if member is None or member.mode & 0o111 == 0:raise ContractError(f"{path.name} contains non-executable member {expected}")+ for expected in contract.binary_members:+ extracted = archive.extractfile(members[expected])+ if extracted is None: # pragma: no cover - member is already a regular file.+ raise ContractError(f"{path.name} cannot read binary member {expected}")+ _verify_binary(path, contract, expected, extracted.read())+def _verify_zip(path: Path, contract: ArchiveContract) -> None:with zipfile.ZipFile(path) as archive:+ archive_members = archive.infolist()+ _verify_member_names(path, tuple(info.filename for info in archive_members))members = {- _normalize_member(info.filename): info- for info in archive.infolist()- if not info.is_dir()+ _normalize_member(info.filename): info for info in archive_members if not info.is_dir()}+ files = tuple(_normalize_member(info.filename) for info in archive_members if not info.is_dir())+ directories = tuple(+ _normalize_member(info.filename) for info in archive_members if info.is_dir()+ )+ _verify_exact_members(path, contract, files, directories)+ total_size = sum(member.file_size for member in members.values())+ if total_size > MAX_ARCHIVE_UNCOMPRESSED_SIZE:+ raise ContractError(f"{path.name} uncompressed payload is too large: {total_size}")++ for name, member in members.items():+ if member.file_size <= 0:+ raise ContractError(f"{path.name} contains empty member {name}")+ if any(token in PurePosixPath(name).name.lower() for token in NOTICE_NAMES):+ _verify_notice_content(path, name, archive.read(member))for expected in contract.members:member = members.get(expected)if member is None:raise ContractError(f"{path.name} is missing {expected}")- if member.file_size <= 0:- raise ContractError(f"{path.name} contains empty member {expected}")++ for expected in contract.binary_members:+ _verify_binary(path, contract, expected, archive.read(members[expected]))def verify_release_archives(root: Path, version: str) -> tuple[Path, ...]:diff --git a/.github/workflows/authorized-live-jev-use-demo.yml b/.github/workflows/authorized-live-jev-use-demo.ymlnew file mode 100644index 0000000000..93461e0063--- /dev/null+++ b/.github/workflows/authorized-live-jev-use-demo.yml@@ -0,0 +1,777 @@+name: "Authorized: live Jev visual demo"++on:+ workflow_dispatch:+ inputs:+ run_live:+ description: "Explicit acknowledgement that this invocation may use protected live credentials"+ required: true+ type: boolean+ source_pr_number:+ description: "Pull request number under live review; must be open with the fixed cua-perception-live-review label"+ required: true+ type: string+ source_sha:+ description: "Exact reviewed head SHA of source_pr_number"+ required: true+ type: string+ jev_pr_number:+ description: "Merged pull request number supplying the canonical Jev chooser recipe"+ required: true+ type: string+ jev_source_sha:+ description: "Exact canonical merge commit SHA of jev_pr_number"+ required: true+ type: string+ signed_candidate_artifact_id:+ description: "Immutable Actions artifact ID containing signed Windows and Linux review candidates"+ required: true+ type: string+ signed_candidate_run_id:+ description: "Producer Actions run ID containing the signed review candidates"+ required: true+ type: string+ windows_e2e_run_id:+ description: "Actions run ID of an independent, already-completed canonical e2e-rust-windows.yml run at source_sha"+ required: true+ type: string+ linux_e2e_run_id:+ description: "Actions run ID of an independent, already-completed canonical e2e-rust-linux.yml run at source_sha"+ required: true+ type: string+ workflow_call:+ inputs:+ run_live:+ description: "Explicit acknowledgement that this invocation may use protected live credentials"+ required: true+ type: boolean+ source_pr_number:+ description: "Pull request number under live review; must be open with the fixed cua-perception-live-review label"+ required: true+ type: string+ source_sha:+ description: "Exact reviewed head SHA of source_pr_number"+ required: true+ type: string+ jev_pr_number:+ description: "Merged pull request number supplying the canonical Jev chooser recipe"+ required: true+ type: string+ jev_source_sha:+ description: "Exact canonical merge commit SHA of jev_pr_number"+ required: true+ type: string+ signed_candidate_artifact_id:+ description: "Immutable Actions artifact ID containing signed Windows and Linux review candidates"+ required: true+ type: string+ signed_candidate_run_id:+ description: "Producer Actions run ID containing the signed review candidates"+ required: true+ type: string+ windows_e2e_run_id:+ description: "Actions run ID of an independent, already-completed canonical e2e-rust-windows.yml run at source_sha"+ required: true+ type: string+ linux_e2e_run_id:+ description: "Actions run ID of an independent, already-completed canonical e2e-rust-linux.yml run at source_sha"+ required: true+ type: string++permissions:+ actions: read+ contents: read+ pull-requests: read++concurrency:+ group: authorized-live-jev-demo-${{ inputs.source_sha }}-${{ inputs.jev_source_sha }}+ cancel-in-progress: false++jobs:+ source:+ name: Resolve reviewed candidates and signed artifact+ runs-on: ubuntu-latest+ outputs:+ sha: ${{ steps.validate.outputs.sha }}+ jev_sha: ${{ steps.validate.outputs.jev_sha }}+ candidate_run_id: ${{ steps.validate.outputs.candidate_run_id }}+ steps:+ - id: validate+ name: Require exact current PR heads and candidate artifact+ shell: bash+ env:+ GH_TOKEN: ${{ github.token }}+ RUN_LIVE_ACKNOWLEDGED: ${{ inputs.run_live }}+ SOURCE_PR_NUMBER: ${{ inputs.source_pr_number }}+ REQUESTED_SHA: ${{ inputs.source_sha }}+ JEV_PR_NUMBER: ${{ inputs.jev_pr_number }}+ REQUESTED_JEV_SHA: ${{ inputs.jev_source_sha }}+ CANDIDATE_ARTIFACT_ID: ${{ inputs.signed_candidate_artifact_id }}+ CANDIDATE_RUN_ID: ${{ inputs.signed_candidate_run_id }}+ WINDOWS_E2E_RUN_ID: ${{ inputs.windows_e2e_run_id }}+ LINUX_E2E_RUN_ID: ${{ inputs.linux_e2e_run_id }}+ EVENT_ACTION: ${{ github.event.action }}+ EVENT_HEAD_REPOSITORY: ${{ github.event.pull_request.head.repo.full_name }}+ EVENT_HEAD_SHA: ${{ github.event.pull_request.head.sha }}+ EVENT_LABEL: ${{ github.event.label.name }}+ EVENT_PR_NUMBER: ${{ github.event.pull_request.number }}+ run: |+ set -euo pipefail+ [[ "$GITHUB_REPOSITORY" == "trycua/cua" ]] || { echo "live demo runs only in trycua/cua" >&2; exit 2; }+ [[ "$RUN_LIVE_ACKNOWLEDGED" == true ]] || { echo "run_live must be explicitly acknowledged" >&2; exit 2; }+ [[ "$SOURCE_PR_NUMBER" =~ ^[1-9][0-9]*$ ]] || { echo "source_pr_number must be numeric" >&2; exit 2; }+ [[ "$REQUESTED_SHA" =~ ^[0-9a-f]{40}$ ]] || { echo "source_sha must be exactly 40 lowercase hexadecimal characters" >&2; exit 2; }+ [[ "$JEV_PR_NUMBER" =~ ^[1-9][0-9]*$ ]] || { echo "jev_pr_number must be numeric" >&2; exit 2; }+ [[ "$REQUESTED_JEV_SHA" =~ ^[0-9a-f]{40}$ ]] || { echo "jev_source_sha must be exactly 40 lowercase hexadecimal characters" >&2; exit 2; }+ [[ "$CANDIDATE_ARTIFACT_ID" =~ ^[1-9][0-9]*$ ]] || { echo "signed_candidate_artifact_id must be numeric" >&2; exit 2; }+ [[ "$CANDIDATE_RUN_ID" =~ ^[1-9][0-9]*$ ]] || { echo "signed_candidate_run_id must be numeric" >&2; exit 2; }+ [[ "$WINDOWS_E2E_RUN_ID" =~ ^[1-9][0-9]*$ ]] || { echo "windows_e2e_run_id must be numeric" >&2; exit 2; }+ [[ "$LINUX_E2E_RUN_ID" =~ ^[1-9][0-9]*$ ]] || { echo "linux_e2e_run_id must be numeric" >&2; exit 2; }+ validate_pr_head() {+ local number="$1" requested="$2" label="$3" state head_sha head_repo+ IFS=$'\t' read -r state head_sha head_repo < <(+ gh api "repos/$GITHUB_REPOSITORY/pulls/$number" \+ --jq '[.state, .head.sha, .head.repo.full_name] | @tsv'+ )+ [[ "$state" == open && "$head_repo" == "$GITHUB_REPOSITORY" ]] || {+ echo "PR $number must be open with a head in $GITHUB_REPOSITORY" >&2; exit 2;+ }+ [[ "$requested" == "$head_sha" ]] || {+ echo "$label is not the exact current reviewed head of PR $number" >&2; exit 2;+ }+ }+ validate_merged_pr() {+ local number="$1" requested="$2" label="$3" state merged head_repo merge_sha+ IFS=$'\t' read -r state merged head_repo merge_sha < <(+ gh api "repos/$GITHUB_REPOSITORY/pulls/$number" \+ --jq '[.state, .merged, .head.repo.full_name, .merge_commit_sha] | @tsv'+ )+ [[ "$state" == closed && "$merged" == true && "$head_repo" == "$GITHUB_REPOSITORY" ]] || {+ echo "PR $number must be merged and closed with a head in $GITHUB_REPOSITORY" >&2; exit 2;+ }+ [[ -n "$merge_sha" && "$requested" == "$merge_sha" ]] || {+ echo "$label is not the exact canonical merge commit of PR $number" >&2; exit 2;+ }+ }+ validate_e2e_run() {+ local run_id="$1" expected_path="$2" expected_artifact="$3" expected_platform="$4" label="$5" run_json repo path event head_sha status conclusion artifacts_json artifact_id cert_dir cert_json+ run_json="$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$run_id")"+ repo="$(jq -r .repository.full_name <<<"$run_json")"+ path="$(jq -r .path <<<"$run_json")"+ event="$(jq -r .event <<<"$run_json")"+ head_sha="$(jq -r .head_sha <<<"$run_json")"+ status="$(jq -r .status <<<"$run_json")"+ conclusion="$(jq -r .conclusion <<<"$run_json")"+ [[ "$repo" == "$GITHUB_REPOSITORY" ]] || { echo "$label run is not in $GITHUB_REPOSITORY" >&2; exit 2; }+ [[ "$path" == "$expected_path" ]] || { echo "$label run is not the canonical $expected_path workflow" >&2; exit 2; }+ [[ "$event" == workflow_dispatch ]] || { echo "$label run is not a trusted workflow_dispatch run" >&2; exit 2; }+ [[ "$head_sha" == "$REQUESTED_SHA" ]] || { echo "$label run head_sha does not match source_sha" >&2; exit 2; }+ [[ "$status" == completed && "$conclusion" == success ]] || { echo "$label run did not complete successfully" >&2; exit 2; }+ artifacts_json="$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$run_id/artifacts?per_page=100")"+ jq -e --arg name "$expected_artifact" \+ '.artifacts[]? | select(.name == $name and (.expired | not))' <<<"$artifacts_json" >/dev/null || {+ echo "$label run is missing the $expected_artifact certification artifact" >&2; exit 2;+ }+ artifact_id="$(jq -r --arg name "$expected_artifact" '.artifacts[] | select(.name == $name and (.expired | not)) | .id' <<<"$artifacts_json")"+ [[ "$artifact_id" =~ ^[1-9][0-9]*$ ]] || { echo "$label certification artifact ID is invalid" >&2; exit 2; }+ cert_dir="$(mktemp -d)"+ gh api "repos/$GITHUB_REPOSITORY/actions/artifacts/$artifact_id/zip" > "$cert_dir/certification.zip"+ unzip -q "$cert_dir/certification.zip" -d "$cert_dir/unpacked"+ [[ -f "$cert_dir/unpacked/certification.json" ]] || { echo "$label certification.json is missing" >&2; exit 2; }+ cert_json="$(cat "$cert_dir/unpacked/certification.json")"+ [[ "$(jq -r .schema <<<"$cert_json")" == "cua-driver/e2e-certification/v1" ]]+ [[ "$(jq -r .repository <<<"$cert_json")" == "$GITHUB_REPOSITORY" ]]+ [[ "$(jq -r .run_id <<<"$cert_json")" == "$run_id" ]]+ [[ "$(jq -r .event_name <<<"$cert_json")" == workflow_dispatch ]]+ [[ "$(jq -r .platform <<<"$cert_json")" == "$expected_platform" ]]+ [[ "$(jq -r .lane <<<"$cert_json")" == all ]]+ [[ "$(jq -r .canonical <<<"$cert_json")" == true ]]+ [[ "$(jq -r .source_sha <<<"$cert_json")" == "$REQUESTED_SHA" ]]+ [[ "$(jq -r '.required_jobs | all(.[]; . == "success")' <<<"$cert_json")" == true ]]+ if [[ "$expected_platform" == windows ]]; then+ [[ "$(jq -r .runner_policy_class <<<"$cert_json")" == github-hosted ]]+ fi+ }+ validate_pr_head "$SOURCE_PR_NUMBER" "$REQUESTED_SHA" source_sha+ validate_merged_pr "$JEV_PR_NUMBER" "$REQUESTED_JEV_SHA" jev_source_sha+ validate_e2e_run "$WINDOWS_E2E_RUN_ID" ".github/workflows/e2e-rust-windows.yml" rust-windows-e2e-certification windows windows_e2e_run_id+ validate_e2e_run "$LINUX_E2E_RUN_ID" ".github/workflows/e2e-rust-linux.yml" rust-linux-e2e-certification linux linux_e2e_run_id+ artifact_json="$(gh api "repos/$GITHUB_REPOSITORY/actions/artifacts/$CANDIDATE_ARTIFACT_ID")"+ [[ "$(jq -r .name <<<"$artifact_json")" == "STAGING-cua-perception-review-candidates-$REQUESTED_SHA" ]] || { echo "candidate artifact has the wrong aggregate name" >&2; exit 2; }+ [[ "$(jq -r .expired <<<"$artifact_json")" == false ]] || { echo "candidate artifact is expired" >&2; exit 2; }+ [[ "$(jq -r .workflow_run.head_sha <<<"$artifact_json")" == "$REQUESTED_SHA" ]] || {+ echo "candidate artifact was not produced from source_sha" >&2; exit 2;+ }+ run_id="$(jq -r .workflow_run.id <<<"$artifact_json")"+ [[ "$run_id" == "$CANDIDATE_RUN_ID" ]] || { echo "candidate artifact does not belong to signed_candidate_run_id" >&2; exit 2; }+ run_json="$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$run_id")"+ [[ "$(jq -r .head_sha <<<"$run_json")" == "$REQUESTED_SHA" ]] || {+ echo "candidate artifact workflow run is not bound to source_sha" >&2; exit 2;+ }+ [[ "$(jq -r .path <<<"$run_json")" == ".github/workflows/review-cua-perception-candidates.yml" ]] || { echo "candidate artifact was not produced by the PR review workflow" >&2; exit 2; }+ [[ "$(jq -r .event <<<"$run_json")" == pull_request ]] || { echo "candidate artifact producer was not a pull-request review run" >&2; exit 2; }+ if [[ "$GITHUB_EVENT_NAME" == pull_request ]]; then+ [[ "$EVENT_ACTION" == labeled && "$EVENT_PR_NUMBER" == "$SOURCE_PR_NUMBER" ]] || { echo "same-run use requires the labeled source_pr_number caller" >&2; exit 2; }+ [[ "$EVENT_HEAD_REPOSITORY" == "$GITHUB_REPOSITORY" && "$EVENT_HEAD_SHA" == "$REQUESTED_SHA" ]] || { echo "same-run caller is not the exact same-repository source head" >&2; exit 2; }+ [[ "$EVENT_LABEL" == cua-perception-live-review && "$run_id" == "$GITHUB_RUN_ID" ]] || { echo "same-run caller lacks the exact review label or run ID" >&2; exit 2; }+ [[ "$(jq -r .status <<<"$run_json")" == in_progress && "$(jq -r .conclusion <<<"$run_json")" == null ]] || { echo "same-run candidate artifact is not from the active review run" >&2; exit 2; }+ else+ [[ "$GITHUB_EVENT_NAME" == workflow_dispatch ]] || { echo "unsupported live demo invocation" >&2; exit 2; }+ [[ "$(jq -r .status <<<"$run_json")" == completed && "$(jq -r .conclusion <<<"$run_json")" == success ]] || { echo "candidate artifact workflow run did not complete successfully" >&2; exit 2; }+ fi+ echo "sha=$REQUESTED_SHA" >> "$GITHUB_OUTPUT"+ echo "jev_sha=$REQUESTED_JEV_SHA" >> "$GITHUB_OUTPUT"+ echo "candidate_run_id=$CANDIDATE_RUN_ID" >> "$GITHUB_OUTPUT"++ mock-preflight:+ name: Secret-free mock and static contracts+ needs: source+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4+ with:+ ref: ${{ needs.source.outputs.sha }}+ persist-credentials: false+ - uses: dtolnay/rust-toolchain@4716b85f2fac3e324e64fa2810f6b5c3905760a5 # 1.97.1+ - name: Install visual fixture and native Rust dependencies+ run: |+ sudo apt-get update+ sudo apt-get install -y --no-install-recommends \+ python3-tk clang pkg-config libdbus-1-dev libpipewire-0.3-dev \+ libspa-0.2-dev libei-dev libxkbcommon-dev libx11-dev libxi-dev \+ libxtst-dev libxext-dev libwebkit2gtk-4.1-dev libssl-dev libxdo-dev \+ libayatana-appindicator3-dev librsvg2-dev+ - name: Verify exact checkout+ shell: bash+ env:+ EXPECTED_SHA: ${{ needs.source.outputs.sha }}+ run: test "$(git rev-parse HEAD)" = "$EXPECTED_SHA"+ - name: Run fixture, evidence, workflow, and mock-choice contracts+ env:+ CUA_JEV_MOCK_DEMO: "1"+ run: |+ python -m pip install --require-hashes -r .github/releases/cua-perception/test-requirements.lock+ python libs/cua-driver/tests/fixtures/apps/cross-platform/visual-only-canvas/test_fixture.py -v+ python libs/cua-driver/tests/perception-demo/test_sanitize_evidence.py -v+ python libs/cua-driver/tests/perception-demo/test_evidence_envelope.py -v+ python .github/scripts/tests/test_authorized_live_jev_use_demo.py -v+ cargo test --manifest-path libs/cua-driver/rust/Cargo.toml -p cua-driver --test authorized_live_jev_use_demo_test --locked+ cargo test --manifest-path libs/cua-driver/rust/Cargo.toml -p cua-perception --locked++ live:+ name: Live Jev (${{ matrix.platform }})+ needs: [source, mock-preflight]+ strategy:+ fail-fast: false+ matrix:+ include:+ - {platform: windows, runner: windows-latest, target: x86_64-pc-windows-msvc, driver: review-cua-driver.exe, desktop_session: windows-interactive}+ - {platform: linux-x11, runner: ubuntu-latest, target: x86_64-unknown-linux-gnu, driver: review-cua-driver, desktop_session: x11-openbox}+ runs-on: ${{ matrix.runner }}+ timeout-minutes: 60+ environment: authorized-live-jev-use-demo+ env:+ CUA_E2E_SOURCE_SHA: ${{ needs.source.outputs.sha }}+ CUA_JEV_SOURCE_SHA: ${{ needs.source.outputs.jev_sha }}+ CUA_E2E_UNRESTRICTED_GUI: "1"+ CUA_SESSION_LABEL: authorized-jev-choice-demo-${{ matrix.platform }}+ CUA_DESKTOP_SESSION_TYPE: ${{ matrix.desktop_session }}+ CUA_RUNNER_IDENTITY_CLASS: github-hosted+ steps:+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4+ with:+ ref: ${{ needs.source.outputs.sha }}+ persist-credentials: false+ - name: Configure temporary evidence paths+ shell: pwsh+ run: |+ $ErrorActionPreference = 'Stop'+ if ($IsWindows) {+ if ([string]::IsNullOrWhiteSpace($env:USERPROFILE)) { throw 'USERPROFILE is required for the Windows extension home' }+ if ($env:GITHUB_RUN_ID -notmatch '^[1-9][0-9]*$' -or $env:GITHUB_RUN_ATTEMPT -notmatch '^[1-9][0-9]*$') { throw 'GitHub run identity is invalid' }+ $extensionHomeName = "cua-perception-extension-home-$($env:GITHUB_RUN_ID)-$($env:GITHUB_RUN_ATTEMPT)"+ $userProfile = [IO.Path]::GetFullPath($env:USERPROFILE)+ $userProfileItem = Get-Item -LiteralPath $userProfile -Force+ if (-not $userProfileItem.PSIsContainer -or $userProfileItem.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Windows user profile must be a real directory' }+ $extensionHome = [IO.Path]::GetFullPath((Join-Path $userProfile $extensionHomeName))+ if ([IO.Path]::GetDirectoryName($extensionHome) -ne $userProfile -or [IO.Path]::GetFileName($extensionHome) -ne $extensionHomeName) { throw 'Windows extension home is not the expected USERPROFILE child' }+ if (Test-Path -LiteralPath $extensionHome) { throw 'Windows extension home must be fresh' }+ New-Item -ItemType Directory -Path $extensionHome | Out-Null+ $extensionHomeItem = Get-Item -LiteralPath $extensionHome -Force+ if (-not $extensionHomeItem.PSIsContainer -or $extensionHomeItem.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Windows extension home must be a real directory' }+ } else {+ $extensionHome = Join-Path $env:RUNNER_TEMP 'cua-perception-extension-home/live'+ }+ "CUA_PERCEPTION_EXTENSION_HOME=$extensionHome" >> $env:GITHUB_ENV+ "CUA_DRIVER_RS_HOME=$extensionHome" >> $env:GITHUB_ENV+ "CUA_E2E_RECORDINGS_ROOT=$(Join-Path $env:RUNNER_TEMP 'cua-perception-recordings')" >> $env:GITHUB_ENV+ "CUA_PERCEPTION_EVIDENCE_DIR=$(Join-Path $env:RUNNER_TEMP 'cua-perception-evidence/live')" >> $env:GITHUB_ENV+ - name: Check out the exact reviewed Jev chooser+ uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4+ with:+ repository: trycua/cua+ ref: ${{ needs.source.outputs.jev_sha }}+ path: jev-use-source+ persist-credentials: false+ - uses: dtolnay/rust-toolchain@4716b85f2fac3e324e64fa2810f6b5c3905760a5 # 1.97.1+ - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5+ with:+ python-version: "3.12"+ - uses: astral-sh/setup-uv@d0cc045d04ccac9d8b7881df0226f9e82c39688e # v6+ with:+ version: "0.8.15"+ - name: Download immutable signed candidate+ uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0+ with:+ artifact-ids: ${{ inputs.signed_candidate_artifact_id }}+ run-id: ${{ needs.source.outputs.candidate_run_id }}+ path: ${{ runner.temp }}/perception-candidate+ github-token: ${{ github.token }}+ merge-multiple: true+ - name: Prepare Windows recording support+ if: runner.os == 'Windows'+ shell: pwsh+ run: .\scripts\ci\windows\setup-ffmpeg.ps1+ - name: Prepare Linux X11 desktop+ if: runner.os == 'Linux'+ shell: bash+ run: |+ set -euo pipefail+ sudo apt-get update+ sudo apt-get install -y --no-install-recommends xvfb x11-utils dbus-x11 at-spi2-core openbox picom python3-gi gir1.2-gtk-3.0 libgtk-3-dev clang pkg-config libdbus-1-dev libpipewire-0.3-dev libspa-0.2-dev libei-dev libx11-dev libxi-dev libxtst-dev libxext-dev libwebkit2gtk-4.1-dev libssl-dev libxdo-dev libayatana-appindicator3-dev librsvg2-dev ffmpeg jq+ xvfb_pid="" dbus_pid="" openbox_pid="" picom_pid=""+ dump_desktop_state() {+ echo "Linux X11 desktop failed to become ready" >&2+ for entry in "xvfb:$xvfb_pid" "dbus:$dbus_pid" "openbox:$openbox_pid" "picom:$picom_pid"; do+ name="${entry%%:*}"; pid="${entry#*:}"+ if [[ -n "$pid" ]]; then+ echo "--- $name process ($pid) ---" >&2+ ps -o pid=,ppid=,sid=,stat=,comm=,args= -p "$pid" >&2 || true+ fi+ echo "--- $name log ---" >&2+ sed -n '1,200p' "$RUNNER_TEMP/$name.log" >&2 2>/dev/null || true+ done+ DISPLAY=:99 xprop -root _NET_SUPPORTED _NET_SUPPORTING_WM_CHECK _NET_CLIENT_LIST >&2 2>&1 || true+ }+ ewmh_ready() {+ local state+ state="$(DISPLAY=:99 xprop -root _NET_SUPPORTING_WM_CHECK _NET_CLIENT_LIST 2>/dev/null)" || return 1+ grep -q '^_NET_SUPPORTING_WM_CHECK(WINDOW): window id # 0x' <<< "$state" &&+ grep -q '^_NET_CLIENT_LIST(WINDOW):' <<< "$state"+ }+ handle_desktop_failure() {+ local status=$?+ dump_desktop_state+ exit "$status"+ }+ trap handle_desktop_failure ERR++ pid_file="$RUNNER_TEMP/cua-linux-desktop.pids"+ : > "$pid_file"+ nohup env -u RUNNER_TRACKING_ID setsid Xvfb :99 -screen 0 1920x1080x24 -nolisten tcp \+ >"$RUNNER_TEMP/xvfb.log" 2>&1 </dev/null &+ xvfb_pid=$!+ echo "xvfb=$xvfb_pid" >> "$pid_file"+ for _ in {1..50}; do+ kill -0 "$xvfb_pid" 2>/dev/null+ if DISPLAY=:99 xdpyinfo >/dev/null 2>&1; then break; fi+ sleep 0.2+ done+ DISPLAY=:99 xdpyinfo >/dev/null++ nohup env -u RUNNER_TRACKING_ID setsid dbus-daemon --session --nofork --print-address=1 \+ >"$RUNNER_TEMP/dbus.log" 2>&1 </dev/null &+ dbus_pid=$!+ echo "dbus=$dbus_pid" >> "$pid_file"+ dbus_address=""+ for _ in {1..50}; do+ kill -0 "$dbus_pid" 2>/dev/null+ dbus_address="$(sed -n '1p' "$RUNNER_TEMP/dbus.log")"+ if [[ "$dbus_address" == unix:* ]]; then break; fi+ sleep 0.2+ done+ [[ "$dbus_address" == unix:* ]]++ nohup env -u RUNNER_TRACKING_ID DISPLAY=:99 DBUS_SESSION_BUS_ADDRESS="$dbus_address" \+ setsid openbox >"$RUNNER_TEMP/openbox.log" 2>&1 </dev/null &+ openbox_pid=$!+ echo "openbox=$openbox_pid" >> "$pid_file"+ nohup env -u RUNNER_TRACKING_ID DISPLAY=:99 DBUS_SESSION_BUS_ADDRESS="$dbus_address" \+ setsid picom --backend xrender --config /dev/null >"$RUNNER_TEMP/picom.log" 2>&1 </dev/null &+ picom_pid=$!+ echo "picom=$picom_pid" >> "$pid_file"+ for _ in {1..50}; do+ kill -0 "$openbox_pid" 2>/dev/null+ kill -0 "$picom_pid" 2>/dev/null+ if ewmh_ready; then break; fi+ sleep 0.2+ done+ ewmh_ready+ DBUS_SESSION_BUS_ADDRESS="$dbus_address" dbus-send --session --dest=org.freedesktop.DBus \+ --type=method_call --print-reply / org.freedesktop.DBus.ListNames >/dev/null+ echo "DISPLAY=:99" >> "$GITHUB_ENV"+ echo "DBUS_SESSION_BUS_ADDRESS=$dbus_address" >> "$GITHUB_ENV"+ trap - ERR+ - name: Resolve the measured review Driver and verify the signed candidate+ shell: pwsh+ env:+ PLATFORM: ${{ matrix.platform }}+ EXPECTED_TARGET: ${{ matrix.target }}+ EXPECTED_DRIVER: ${{ matrix.driver }}+ EXPECTED_SHA: ${{ needs.source.outputs.sha }}+ run: |+ $ErrorActionPreference = 'Stop'+ if ((git rev-parse HEAD).Trim() -ne $env:EXPECTED_SHA) { throw 'checkout does not match source_sha' }+ $candidate = Join-Path $env:RUNNER_TEMP "perception-candidate/$($env:PLATFORM)"+ $catalog = Join-Path $candidate 'signed-catalog.json'+ $measurements = Join-Path $candidate 'review-measurements.json'+ @'+ import base64, hashlib, json, os, pathlib, sys+ root, measurements_path, env_path = map(pathlib.Path, sys.argv[1:4]); expected_sha, expected_target, expected_driver = sys.argv[4:]+ measured = json.loads(measurements_path.read_text()); assert measured["review_only"] is True and measured["source_sha"] == expected_sha and measured["target"] == expected_target+ assert measured["review_driver_build_profile"] == "debug-review-trust-root" and measured["review_driver_relative_path"] == expected_driver+ assert measured["review_driver_version"] and measured["extension_version"] and measured["protocol_version"] > 0+ assert measured["self_test"]["status"] == "passed" and measured["self_test"]["mismatch_rejection"] is True+ assert [item["role"] for item in measured["models"]] == ["icon-detect", "ocr-detect", "ocr-recognize"]+ assert measured["onnx_runtime"]["revision"] and len(measured["onnx_runtime"]["sha256"]) == 64+ assert measured["key_id"] == "review-only-build-override" and measured["publisher_id"] == "cua-review-only" and measured["signature_algorithm"] == "ed25519"+ assert measured["code_signing"] == {"status": "not-applicable", "format": "none", "identity": "none", "certificate_sha256": None, "designated_requirement": None}+ public_key = base64.b64decode(measured["public_key_base64"], validate=True); assert len(public_key) == 32 and hashlib.sha256(public_key).hexdigest() == measured["public_key_sha256"]+ driver = (root / expected_driver).resolve(); driver.relative_to(root.resolve()); assert driver.is_file() and hashlib.sha256(driver.read_bytes()).hexdigest() == measured["review_driver_sha256"]+ catalog = (root / "signed-catalog.json").resolve(); assert catalog.is_file() and hashlib.sha256(catalog.read_bytes()).hexdigest() == measured["catalog_sha256"]+ catalog_value = json.loads(catalog.read_text()); payload = catalog_value["payload"]; archive_relative = pathlib.PurePosixPath(payload["archive"]); assert not archive_relative.is_absolute() and ".." not in archive_relative.parts+ archive = root.joinpath(*archive_relative.parts).resolve(); archive.relative_to(root.resolve()); assert archive.is_file() and hashlib.sha256(archive.read_bytes()).hexdigest() == measured["archive_sha256"] == payload["archive_sha256"]+ checksums = root / "signed-candidate-checksums.txt"; entries = {}+ for line in checksums.read_text().splitlines():+ digest, relative_text = line.split(None, 1); relative = pathlib.PurePosixPath(relative_text.strip()); assert len(digest) == 64 and not relative.is_absolute() and ".." not in relative.parts+ path = root.joinpath(*relative.parts).resolve(); path.relative_to(root.resolve()); assert path.is_file() and hashlib.sha256(path.read_bytes()).hexdigest() == digest; entries[relative.as_posix()] = digest+ assert {expected_driver, "review-measurements.json", "signed-catalog.json", archive_relative.as_posix()} <= set(entries)+ if os.name != "nt": driver.chmod(driver.stat().st_mode | 0o100)+ with env_path.open("a") as stream: stream.write(f"CUA_DRIVER_BIN={driver}\nCUA_TEST_DRIVER_BIN={driver}\nCUA_CANDIDATE_MEASUREMENTS={measurements_path}\nCUA_PERCEPTION_CATALOG={catalog}\nCUA_PERCEPTION_EXTENSION_ARCHIVE={archive}\n")+ '@ | python - $candidate $measurements $env:GITHUB_ENV $env:EXPECTED_SHA $env:EXPECTED_TARGET $env:EXPECTED_DRIVER+ if ($LASTEXITCODE -ne 0) { throw 'review candidate measurement verification failed' }+ $driver = (Resolve-Path -LiteralPath (Join-Path $candidate $env:EXPECTED_DRIVER)).Path+ $inspect = Join-Path $env:RUNNER_TEMP 'perception-inspect.json'+ $env:CUA_DRIVER_RS_HOME = $env:CUA_PERCEPTION_EXTENSION_HOME+ & $driver extension inspect cua-perception --catalog $catalog --json | Set-Content $inspect -Encoding utf8+ if ($LASTEXITCODE -ne 0) { throw 'signed catalog inspection failed' }+ & $driver extension install cua-perception --catalog $catalog+ if ($LASTEXITCODE -ne 0) { throw 'signed extension install failed' }+ $status = Join-Path $env:RUNNER_TEMP 'perception-status.json'+ & $driver extension status cua-perception --self-test --json | Set-Content $status -Encoding utf8+ if ($LASTEXITCODE -ne 0) { throw 'installed extension self-test failed' }+ $installed = (& $driver extension path cua-perception).Trim()+ @'+ import hashlib, json, os, pathlib, sys+ inspect_path, status_path, catalog_path, installed_path, env_path, driver, measurements_path = sys.argv[1:]+ inspect_path, status_path, catalog_path, installed_path, env_path = map(pathlib.Path, (inspect_path, status_path, catalog_path, installed_path, env_path))+ preview = json.loads(inspect_path.read_text(encoding="utf-8-sig")); status = json.loads(status_path.read_text(encoding="utf-8-sig")); catalog = json.loads(catalog_path.read_text()); measured = json.loads(pathlib.Path(measurements_path).read_text())+ assert preview["publisher_signature_verified"] is True and preview["trust"] == "review-only-publisher-verified"+ assert status["installed"] is True and status["healthy"] is True and status["trust"] == "review-only-publisher-verified"+ assert status["publisher_id"] == measured["publisher_id"] and status["publisher_key_id"] == measured["key_id"]+ assert status["active_version"] == measured["extension_version"] and status["protocol_version"] == measured["protocol_version"]+ assert catalog["signature_algorithm"] == measured["signature_algorithm"] == "ed25519" and preview["archive_sha256"] == measured["archive_sha256"] == catalog["payload"]["archive_sha256"]+ archive_rel = pathlib.PurePosixPath(catalog["payload"]["archive"]); assert not archive_rel.is_absolute() and ".." not in archive_rel.parts+ archive = catalog_path.parent.joinpath(*archive_rel.parts).resolve(); assert archive.is_file() and hashlib.sha256(archive.read_bytes()).hexdigest() == preview["archive_sha256"]+ root = installed_path.resolve(); files = {item["path"]: item["sha256"] for item in preview["files"]}; model_paths, model_hashes = [], []+ assert preview["models"]+ for model in preview["models"]:+ relative = pathlib.PurePosixPath(model["path"]); assert not relative.is_absolute() and ".." not in relative.parts+ path = root.joinpath(*relative.parts).resolve(); path.relative_to(root); digest = hashlib.sha256(path.read_bytes()).hexdigest()+ assert digest == files[model["path"]] == model["conversion_sha256"]+ model_paths.append(str(path)); model_hashes.append(digest)+ assert hashlib.sha256(catalog_path.read_bytes()).hexdigest() == measured["catalog_sha256"]+ assert len(model_hashes) == 3 and measured["supplied_model_sha256"] in model_hashes+ assert model_hashes == [item["converted_sha256"] for item in measured["models"]]+ supplied_model_path = model_paths[model_hashes.index(measured["supplied_model_sha256"])]+ runner_identity = {"name": os.environ.get("ImageOS", ""), "version": os.environ.get("ImageVersion", ""), "arch": os.environ.get("RUNNER_ARCH", "")}+ assert all(runner_identity.values()), runner_identity+ with env_path.open("a") as stream:+ stream.write(f"CUA_PERCEPTION_MODEL={supplied_model_path}\nCUA_RUNNER_OS_NAME={runner_identity['name']}\nCUA_RUNNER_OS_VERSION={runner_identity['version']}\nCUA_RUNNER_OS_ARCH={runner_identity['arch']}\n")+ '@ | python - $inspect $status $catalog $installed $env:GITHUB_ENV $driver $measurements+ if ($LASTEXITCODE -ne 0) { throw 'candidate measurement failed' }+ - name: Install the locked reviewed chooser with the source-reviewed adapter+ shell: pwsh+ env:+ EXPECTED_JEV_SHA: ${{ needs.source.outputs.jev_sha }}+ run: |+ $ErrorActionPreference = 'Stop'+ $chooserRepo = Join-Path $env:GITHUB_WORKSPACE 'jev-use-source'+ $chooserRoot = Join-Path $chooserRepo 'libs/cua-driver/examples/jev-use'+ if ((git -C $chooserRepo rev-parse HEAD).Trim() -ne $env:EXPECTED_JEV_SHA) { throw 'chooser checkout does not match jev_source_sha' }+ $script = Join-Path $chooserRoot 'python/choose_action.py'+ $adapter = Join-Path $env:GITHUB_WORKSPACE 'libs/cua-driver/examples/jev-use/python/jev_adapter.py'+ $installedAdapter = Join-Path $chooserRoot 'python/jev_adapter.py'+ if (-not (Test-Path $script -PathType Leaf)) { throw 'reviewed live chooser contract is unavailable' }+ if (-not (Test-Path $adapter -PathType Leaf) -or -not (Test-Path $installedAdapter -PathType Leaf)) { throw 'reviewed live chooser adapter is unavailable' }+ Copy-Item -LiteralPath $adapter -Destination $installedAdapter -Force+ $adapterSha256 = (Get-FileHash $adapter -Algorithm SHA256).Hash.ToLowerInvariant()+ if ((Get-FileHash $installedAdapter -Algorithm SHA256).Hash.ToLowerInvariant() -ne $adapterSha256) { throw 'source-reviewed chooser adapter copy does not match' }+ uv sync --frozen --project $chooserRoot+ if ($LASTEXITCODE -ne 0) { throw 'locked chooser install failed' }+ $program = if ($IsWindows) { Join-Path $chooserRoot '.venv/Scripts/python.exe' } else { Join-Path $chooserRoot '.venv/bin/python' }+ if (-not (Test-Path $program -PathType Leaf)) { throw 'chooser interpreter is unavailable' }+ "CUA_FIXED_CHOOSER_PROGRAM=$program" >> $env:GITHUB_ENV+ "CUA_FIXED_CHOOSER_SCRIPT=$script" >> $env:GITHUB_ENV+ "CUA_FIXED_CHOOSER_ADAPTER=$installedAdapter" >> $env:GITHUB_ENV+ "CUA_FIXED_CHOOSER_ADAPTER_SHA256=$adapterSha256" >> $env:GITHUB_ENV+ - name: Compile and measure the exact live test binary without credentials+ shell: pwsh+ run: |+ $ErrorActionPreference = 'Stop'+ $messages = Join-Path $env:RUNNER_TEMP 'live-test-build.jsonl'+ cargo test --manifest-path libs/cua-driver/rust/Cargo.toml -p cua-driver --test authorized_live_jev_use_demo_test --locked --no-run --message-format=json-render-diagnostics | Set-Content $messages -Encoding utf8+ if ($LASTEXITCODE -ne 0) { throw 'live test build failed' }+ @'+ import hashlib, json, os, pathlib, re, subprocess, sys+ records = []+ for line in pathlib.Path(sys.argv[1]).read_text(encoding="utf-8-sig").splitlines():+ try: value = json.loads(line)+ except json.JSONDecodeError: continue+ if value.get("reason") == "compiler-artifact" and value.get("target", {}).get("name") == "authorized_live_jev_use_demo_test" and value.get("executable"): records.append(pathlib.Path(value["executable"]).resolve())+ assert len(records) == 1 and records[0].is_file(), records+ binary = records[0]+ listing = subprocess.run([str(binary), "--list"], check=True, capture_output=True, text=True).stdout.splitlines()+ available = [line.removesuffix(": test") for line in listing if line.endswith(": test")]+ def resolve(short_name):+ matches = [name for name in available if name == short_name or name.endswith(f"::{short_name}")]+ assert len(matches) == 1, f"required live test {short_name!r} resolved to {matches!r}"+ assert re.fullmatch(r"[A-Za-z0-9_]+(?:::[A-Za-z0-9_]+)*", matches[0]), matches[0]+ return matches[0]+ window_test = resolve("authorized_visual_only_window_demo")+ desktop_test = resolve("authorized_visual_only_primary_desktop_demo")+ negative_test = resolve("authorized_live_jev_no_matching_action_control")+ with pathlib.Path(os.environ["GITHUB_ENV"]).open("a") as stream:+ stream.write(f"CUA_LIVE_TEST_BINARY={binary}\nCUA_LIVE_TEST_BINARY_SHA256={hashlib.sha256(binary.read_bytes()).hexdigest()}\nCUA_LIVE_WINDOW_TEST={window_test}\nCUA_LIVE_DESKTOP_TEST={desktop_test}\nCUA_LIVE_NEGATIVE_TEST={negative_test}\n")+ '@ | python - $messages+ if ($LASTEXITCODE -ne 0) { throw 'live test binary measurement failed' }+ - name: Verify Linux X11 desktop survived setup steps+ if: runner.os == 'Linux'+ shell: bash+ run: |+ set -euo pipefail+ dump_desktop_state() {+ echo "Linux X11 desktop is unavailable before the live demos" >&2+ pgrep -a -f 'Xvfb|dbus-daemon|openbox|picom' >&2 || true+ DISPLAY="$DISPLAY" xprop -root _NET_SUPPORTED _NET_SUPPORTING_WM_CHECK _NET_CLIENT_LIST >&2 2>&1 || true+ for name in xvfb dbus openbox picom; do+ echo "--- $name log ---" >&2+ sed -n '1,200p' "$RUNNER_TEMP/$name.log" >&2 2>/dev/null || true+ done+ }+ handle_desktop_failure() {+ local status=$?+ dump_desktop_state+ exit "$status"+ }+ trap handle_desktop_failure ERR+ declare -A desktop_pids=()+ while IFS='=' read -r name pid; do+ [[ "$name" =~ ^(xvfb|dbus|openbox|picom)$ && "$pid" =~ ^[1-9][0-9]*$ ]]+ desktop_pids["$name"]="$pid"+ done < "$RUNNER_TEMP/cua-linux-desktop.pids"+ for name in xvfb dbus openbox picom; do+ [[ -n "${desktop_pids[$name]:-}" ]]+ kill -0 "${desktop_pids[$name]}"+ done+ xdpyinfo >/dev/null+ ewmh_state="$(xprop -root _NET_SUPPORTING_WM_CHECK _NET_CLIENT_LIST)"+ grep -q '^_NET_SUPPORTING_WM_CHECK(WINDOW): window id # 0x' <<< "$ewmh_state"+ grep -q '^_NET_CLIENT_LIST(WINDOW):' <<< "$ewmh_state"+ dbus-send --session --dest=org.freedesktop.DBus --type=method_call --print-reply / \+ org.freedesktop.DBus.ListNames >/dev/null+ trap - ERR+ - name: Run installed candidate with deterministic mock chooser+ shell: pwsh+ env:+ CUA_JEV_MOCK_DEMO: "1"+ CUA_PERCEPTION_EVIDENCE_DIR: ${{ runner.temp }}/perception-evidence/mock+ CUA_TEST_DRIVER_STDERR: "1"+ run: |+ & $env:CUA_LIVE_TEST_BINARY --ignored --exact $env:CUA_LIVE_WINDOW_TEST --nocapture+ if ($LASTEXITCODE -ne 0) { throw 'artifact-gated mock window demo failed' }+ & $env:CUA_LIVE_TEST_BINARY --ignored --exact $env:CUA_LIVE_DESKTOP_TEST --nocapture+ if ($LASTEXITCODE -ne 0) { throw 'artifact-gated mock primary-desktop demo failed' }+ - name: Run bounded live Jev chooser against the measured binary+ shell: pwsh+ timeout-minutes: 15+ env:+ GH_TOKEN: ${{ github.token }}+ LIVE_TYPESAFE_API_KEY: ${{ secrets.TYPESAFE_API_KEY }}+ run: |+ $ErrorActionPreference = 'Stop'+ $key = $env:LIVE_TYPESAFE_API_KEY; Remove-Item Env:LIVE_TYPESAFE_API_KEY+ if ([string]::IsNullOrWhiteSpace($key)) { throw 'TYPESAFE_API_KEY environment secret is required' }+ $sourcePrNumber = '${{ inputs.source_pr_number }}'+ $jevPrNumber = '${{ inputs.jev_pr_number }}'+ $review = gh api "repos/$env:GITHUB_REPOSITORY/pulls/$sourcePrNumber" | ConvertFrom-Json+ if ($review.state -ne 'open' -or $review.head.repo.full_name -ne $env:GITHUB_REPOSITORY -or $review.head.sha -ne '${{ needs.source.outputs.sha }}' -or 'cua-perception-live-review' -notin $review.labels.name) { throw "PR #$sourcePrNumber is no longer the exact labeled source under review" }+ $jevReview = gh api "repos/$env:GITHUB_REPOSITORY/pulls/$jevPrNumber" | ConvertFrom-Json+ if ($jevReview.state -ne 'closed' -or $jevReview.merged -ne $true -or $jevReview.head.repo.full_name -ne $env:GITHUB_REPOSITORY -or $jevReview.merge_commit_sha -ne '${{ needs.source.outputs.jev_sha }}') { throw "PR #$jevPrNumber is no longer the exact canonical merged Jev recipe" }+ Remove-Item Env:GH_TOKEN+ if ((git rev-parse HEAD).Trim() -ne '${{ needs.source.outputs.sha }}') { throw 'source changed after build' }+ if ((git -C (Join-Path $env:GITHUB_WORKSPACE 'jev-use-source') rev-parse HEAD).Trim() -ne '${{ needs.source.outputs.jev_sha }}') { throw 'chooser source changed after setup' }+ if ((Get-FileHash $env:CUA_LIVE_TEST_BINARY -Algorithm SHA256).Hash.ToLowerInvariant() -ne $env:CUA_LIVE_TEST_BINARY_SHA256) { throw 'live test binary changed after measurement' }+ if (-not (Test-Path $env:CUA_FIXED_CHOOSER_SCRIPT -PathType Leaf)) { throw 'chooser script disappeared after setup' }+ if ((Get-FileHash $env:CUA_FIXED_CHOOSER_ADAPTER -Algorithm SHA256).Hash.ToLowerInvariant() -ne $env:CUA_FIXED_CHOOSER_ADAPTER_SHA256) { throw 'source-reviewed chooser adapter changed after setup' }+ $env:CUA_JEV_LIVE = '1'; $env:CUA_JEV_CHOOSER_PROGRAM = $env:CUA_FIXED_CHOOSER_PROGRAM; $env:CUA_JEV_CHOOSER_SCRIPT = $env:CUA_FIXED_CHOOSER_SCRIPT; $env:TYPESAFE_API_KEY = $key+ try {+ & $env:CUA_LIVE_TEST_BINARY --ignored --exact $env:CUA_LIVE_NEGATIVE_TEST --nocapture+ if ($LASTEXITCODE -ne 0) { throw 'live Jev no-matching-action control failed' }+ & $env:CUA_LIVE_TEST_BINARY --ignored --exact $env:CUA_LIVE_WINDOW_TEST --nocapture+ if ($LASTEXITCODE -ne 0) { throw 'live Jev window demo failed' }+ & $env:CUA_LIVE_TEST_BINARY --ignored --exact $env:CUA_LIVE_DESKTOP_TEST --nocapture+ if ($LASTEXITCODE -ne 0) { throw 'live Jev primary-desktop demo failed' }+ } finally {+ Remove-Item Env:TYPESAFE_API_KEY -ErrorAction SilentlyContinue; Remove-Item Env:CUA_JEV_LIVE -ErrorAction SilentlyContinue; Remove-Item Env:CUA_JEV_CHOOSER_PROGRAM -ErrorAction SilentlyContinue; Remove-Item Env:CUA_JEV_CHOOSER_SCRIPT -ErrorAction SilentlyContinue; $key = $null+ }+ - name: Fully decode and validate redacted evidence+ shell: pwsh+ env:+ EXPECTED_SHA: ${{ needs.source.outputs.sha }}+ EXPECTED_PLATFORM: ${{ matrix.platform }}+ run: |+ $ErrorActionPreference = 'Stop'+ $evidence = $env:CUA_PERCEPTION_EVIDENCE_DIR+ foreach ($scope in @('window', 'primary-desktop')) {+ $scopeEvidence = if ($scope -eq 'window') { $evidence } else { Join-Path $evidence $scope }+ $recording = Join-Path $scopeEvidence 'recording.mp4'+ $manifest = Join-Path $scopeEvidence 'manifest.json'+ if (-not (Test-Path $recording -PathType Leaf) -or -not (Test-Path $manifest -PathType Leaf)) { throw "complete $scope live evidence was not produced" }+ ffmpeg -v error -xerror -i $recording -map 0:v:0 -f null -+ if ($LASTEXITCODE -ne 0) { throw "$scope recording.mp4 did not fully decode" }+ }+ uv pip install --no-config --system --require-hashes -r .github/releases/cua-perception/test-requirements.lock+ @'+ import hashlib, json, os, pathlib, shutil, subprocess, sys+ from jsonschema import Draft202012Validator+ evidence, output, schema_path, measurements_path = map(pathlib.Path, sys.argv[1:])+ schema = json.loads(schema_path.read_text()); Draft202012Validator.check_schema(schema); measured = json.loads(measurements_path.read_text())+ routes = {+ "window": (evidence, "window", "get_window_state", "background"),+ "primary-desktop": (evidence / "primary-desktop", "desktop", "get_desktop_state", "foreground"),+ }+ output.mkdir(mode=0o700, parents=True, exist_ok=False)+ for scope, (source, input_scope, capture_kind, delivery_mode) in routes.items():+ manifest_path, recording = source / "manifest.json", source / "recording.mp4"+ manifest = json.loads(manifest_path.read_text()); Draft202012Validator(schema).validate(manifest)+ assert manifest["platform"] == os.environ["EXPECTED_PLATFORM"]+ assert manifest["fixture"] == {"id": "visual-only-canvas/v1", "oracle": {"source": "fixture-journal", "initial_ready": True, "selected": "send", "action_count": 1, "result": "passed"}}+ runtime = manifest["runtime"]; driver = runtime["driver"]; perception = runtime["perception"]; chooser = runtime["chooser"]+ assert driver["source_sha"] == measured["source_sha"] == os.environ["EXPECTED_SHA"] and driver["version"] == measured["review_driver_version"] and driver["binary_sha256"] == measured["review_driver_sha256"]+ assert driver["build"] == {"profile": measured["review_driver_build_profile"], "target": measured["target"], "sealed_artifact_manifest_sha256": measured["sealed_artifact_manifest_sha256"], "sealed_extension_manifest_sha256": measured["sealed_extension_manifest_sha256"]}+ assert perception["signature_algorithm"] == measured["signature_algorithm"] == "ed25519"; assert perception["signed_extension_archive_sha256"] == measured["archive_sha256"]; assert perception["signing_key_sha256"] == measured["public_key_sha256"]; assert perception["signed_catalog_sha256"] == measured["catalog_sha256"]+ assert perception["protocol_version"] == measured["protocol_version"] and perception["worker_sha256"] == measured["worker_sha256"] and perception["self_test"] == measured["self_test"] and perception["models"] == measured["models"] and perception["onnx_runtime"] == measured["onnx_runtime"]+ assert chooser["mode"] == "live" and chooser["provider"] == "typesafe" and chooser["model_id"]+ assert chooser["adapter_source_sha"] == os.environ["EXPECTED_SHA"] and chooser["source_sha"] == os.environ["CUA_JEV_SOURCE_SHA"]+ result = manifest["result"]; observation = manifest["observation"]+ assert observation["session_label"] == f'{os.environ["CUA_SESSION_LABEL"]}-{scope}'+ assert (observation["input_scope"], observation["capture_kind"], manifest["environment"]["delivery_mode"]) == (input_scope, capture_kind, delivery_mode)+ assert observation["capture_source"] == "driver-screenshot" and len(observation["acted_capture_id_sha256"]) == len(observation["fresh_capture_id_sha256"]) == len(observation["capture_trace_sha256"]) == 64+ assert 2 <= len(observation["candidates"]) <= 18 and result["selected_candidate"] in {item["id"] for item in observation["candidates"]}+ assert manifest["environment"] == {"os": {"name": os.environ["CUA_RUNNER_OS_NAME"], "version": os.environ["CUA_RUNNER_OS_VERSION"], "arch": os.environ["CUA_RUNNER_OS_ARCH"]}, "desktop_session": os.environ["CUA_DESKTOP_SESSION_TYPE"], "runner_identity_class": os.environ["CUA_RUNNER_IDENTITY_CLASS"], "delivery_mode": delivery_mode}+ assert result["status"] == "passed" and result["stale_capture_refused"] is True+ content = recording.read_bytes(); video_sha = hashlib.sha256(content).hexdigest(); assert manifest["artifacts"] == [{"kind": "video", "path": "recording.mp4", "sha256": video_sha, "size_bytes": len(content)}]+ probe = json.loads(subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height,avg_frame_rate:format=duration", "-of", "json", recording], check=True, capture_output=True, text=True).stdout); stream = probe["streams"][0]; numerator, denominator = map(int, stream["avg_frame_rate"].split("/")); duration_ms = round(float(probe["format"]["duration"]) * 1000)+ recording_value = manifest["recording"]; dimensions = {"width": stream["width"], "height": stream["height"]}; assert recording_value["original_dimensions"] == recording_value["delivered_dimensions"] == dimensions; assert recording_value["frame_rate"] == {"numerator": numerator, "denominator": denominator}; assert recording_value["cursor"] == {"agent_overlay": False, "system_cursor": "recorder-default"}; assert recording_value["edit_operations"] == [{"operation": "none", "speed": "1x"}]; assert recording_value["shots"] == [{"source_sha256": video_sha, "start_ms": 0, "end_ms": duration_ms}]; assert recording_value["final_sha256"] == video_sha and recording_value["size_bytes"] == len(content)+ destination = output / scope; destination.mkdir(mode=0o700); shutil.copyfile(recording, destination / "recording.mp4"); shutil.copyfile(manifest_path, destination / "manifest.json"); assert sorted(path.name for path in destination.iterdir()) == ["manifest.json", "recording.mp4"]+ assert sorted(path.name for path in output.iterdir()) == ["primary-desktop", "window"]+ '@ | python - $evidence (Join-Path $env:RUNNER_TEMP 'publish-evidence') 'libs/cua-driver/tests/perception-demo/evidence-manifest.schema.json' $env:CUA_CANDIDATE_MEASUREMENTS+ if ($LASTEXITCODE -ne 0) { throw 'redacted evidence validation failed' }+ - name: Encrypt the validated evidence bundles+ shell: pwsh+ env:+ CUA_PERCEPTION_EVIDENCE_RECIPIENT: ${{ vars.EVIDENCE_ARCHIVE_RECIPIENT_PUBLIC_KEY }}+ run: |+ $ErrorActionPreference = 'Stop'+ $plaintext = Join-Path $env:RUNNER_TEMP 'publish-evidence'+ $ciphertext = Join-Path $env:RUNNER_TEMP 'encrypted-evidence'+ try {+ if ([string]::IsNullOrWhiteSpace($env:CUA_PERCEPTION_EVIDENCE_RECIPIENT)) { throw 'EVIDENCE_ARCHIVE_RECIPIENT_PUBLIC_KEY environment variable is required' }+ if (Test-Path -LiteralPath $ciphertext) { throw 'encrypted evidence output must be fresh' }+ New-Item -ItemType Directory -Path $ciphertext | Out-Null+ foreach ($scope in @('window', 'primary-desktop')) {+ $fingerprint = python libs/cua-driver/tests/perception-demo/evidence_envelope.py encrypt --input (Join-Path $plaintext $scope) --output (Join-Path $ciphertext "$scope.cuae") --recipient-env CUA_PERCEPTION_EVIDENCE_RECIPIENT+ if ($LASTEXITCODE -ne 0) { throw "$scope evidence encryption failed" }+ if ($fingerprint -notmatch '^recipient_public_key_sha256=[0-9a-f]{64}$') { throw "$scope evidence encryption did not report a valid recipient fingerprint" }+ Write-Host "$scope $fingerprint"+ }+ @'+ import pathlib, sys+ root = pathlib.Path(sys.argv[1])+ assert sorted(path.name for path in root.iterdir()) == ["primary-desktop.cuae", "window.cuae"]+ assert all(path.is_file() and not path.is_symlink() for path in root.iterdir())+ '@ | python - $ciphertext+ if ($LASTEXITCODE -ne 0) { throw 'encrypted evidence directory contract failed' }+ } finally {+ Remove-Item Env:CUA_PERCEPTION_EVIDENCE_RECIPIENT -ErrorAction SilentlyContinue+ }+ - name: Upload only encrypted evidence envelopes+ uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4.6.2+ with:+ name: live-jev-visual-${{ matrix.platform }}-${{ needs.source.outputs.sha }}+ path: ${{ runner.temp }}/encrypted-evidence/+ if-no-files-found: error+ retention-days: 14+ - name: Stop Linux X11 desktop+ if: always() && runner.os == 'Linux'+ shell: bash+ run: |+ set -euo pipefail+ pid_file="$RUNNER_TEMP/cua-linux-desktop.pids"+ [[ -f "$pid_file" ]] || exit 0+ declare -A expected=(+ [xvfb]=Xvfb+ [dbus]=dbus-daemon+ [openbox]=openbox+ [picom]=picom+ )+ while IFS='=' read -r name pid; do+ [[ -n "${expected[$name]:-}" && "$pid" =~ ^[1-9][0-9]*$ ]] || continue+ if [[ -r "/proc/$pid/comm" && "$(<"/proc/$pid/comm")" == "${expected[$name]}" ]]; then+ kill "$pid" 2>/dev/null || true+ fi+ done < "$pid_file"+ - name: Remove plaintext evidence from the runner+ if: always()+ shell: pwsh+ run: |+ $ErrorActionPreference = 'Stop'+ try {+ if ($IsWindows -and -not [string]::IsNullOrWhiteSpace($env:CUA_PERCEPTION_EXTENSION_HOME)) {+ if ([string]::IsNullOrWhiteSpace($env:USERPROFILE)) { throw 'USERPROFILE is required for Windows extension cleanup' }+ if ($env:GITHUB_RUN_ID -notmatch '^[1-9][0-9]*$' -or $env:GITHUB_RUN_ATTEMPT -notmatch '^[1-9][0-9]*$') { throw 'GitHub run identity is invalid' }+ $extensionHomeName = "cua-perception-extension-home-$($env:GITHUB_RUN_ID)-$($env:GITHUB_RUN_ATTEMPT)"+ $userProfile = [IO.Path]::GetFullPath($env:USERPROFILE)+ $userProfileItem = Get-Item -LiteralPath $userProfile -Force+ if (-not $userProfileItem.PSIsContainer -or $userProfileItem.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Windows user profile must be a real directory' }+ $extensionHome = [IO.Path]::GetFullPath($env:CUA_PERCEPTION_EXTENSION_HOME)+ $expectedExtensionHome = [IO.Path]::GetFullPath((Join-Path $userProfile $extensionHomeName))+ if ($extensionHome -ne $expectedExtensionHome -or [IO.Path]::GetDirectoryName($extensionHome) -ne $userProfile -or [IO.Path]::GetFileName($extensionHome) -ne $extensionHomeName) { throw 'refusing to clean an unexpected Windows extension home' }+ if (Test-Path -LiteralPath $expectedExtensionHome) {+ $extensionHomeItem = Get-Item -LiteralPath $expectedExtensionHome -Force+ if ($extensionHomeItem.Attributes -band [IO.FileAttributes]::ReparsePoint) {+ Remove-Item -LiteralPath $expectedExtensionHome -Force+ } else {+ Remove-Item -LiteralPath $expectedExtensionHome -Recurse -Force+ }+ }+ }+ } finally {+ if ([string]::IsNullOrWhiteSpace($env:RUNNER_TEMP)) { throw 'RUNNER_TEMP is required for plaintext evidence cleanup' }+ $runnerTemp = [IO.Path]::GetFullPath($env:RUNNER_TEMP)+ $runnerTempItem = Get-Item -LiteralPath $runnerTemp -Force+ if (-not $runnerTempItem.PSIsContainer -or $runnerTempItem.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'RUNNER_TEMP must be a real directory' }+ foreach ($name in @('cua-perception-recordings', 'cua-perception-evidence', 'perception-evidence', 'publish-evidence')) {+ $target = [IO.Path]::GetFullPath((Join-Path $runnerTemp $name))+ if ([IO.Path]::GetDirectoryName($target) -ne $runnerTemp -or [IO.Path]::GetFileName($target) -ne $name) { throw 'refusing to clean an unexpected plaintext evidence path' }+ if (Test-Path -LiteralPath $target) {+ $targetItem = Get-Item -LiteralPath $target -Force+ if ($targetItem.Attributes -band [IO.FileAttributes]::ReparsePoint) {+ Remove-Item -LiteralPath $target -Force+ } else {+ Remove-Item -LiteralPath $target -Recurse -Force+ }+ }+ }+ }diff --git a/.github/workflows/cd-cua-perception-candidate-manual.yml b/.github/workflows/cd-cua-perception-candidate-manual.ymlnew file mode 100644index 0000000000..1037a37ccf--- /dev/null+++ b/.github/workflows/cd-cua-perception-candidate-manual.yml@@ -0,0 +1,73 @@+name: "CD: Cua Perception exact-SHA candidates"++on:+ workflow_dispatch:+ inputs:+ source_sha:+ description: "Exact 40-character SHA at the reviewed ref tip"+ required: true+ type: string+ reviewed_ref:+ description: "Reviewed PR head or immutable candidate tag"+ required: true+ type: string+ payload_run_id:+ description: "Run ID containing all three platform bundle inputs"+ required: true+ type: string+ linux_payload_artifact:+ description: "Linux x86_64 release-input bundle artifact"+ required: true+ default: "cua-perception-input-linux-x86_64"+ type: string+ macos_payload_artifact:+ description: "macOS aarch64 release-input bundle artifact"+ required: true+ default: "cua-perception-input-macos-aarch64"+ type: string+ windows_payload_artifact:+ description: "Windows x86_64 release-input bundle artifact"+ required: true+ default: "cua-perception-input-windows-x86_64"+ type: string+ catalog_version:+ description: "Monotonic catalog version"+ required: true+ type: string+ expires_unix:+ description: "Catalog expiry before the active key expires"+ required: true+ type: string++permissions:+ actions: read+ contents: read++jobs:+ candidate:+ name: candidate ${{ matrix.target_triple }}+ strategy:+ fail-fast: false+ matrix:+ include:+ - target_os: linux+ target_triple: x86_64-unknown-linux-gnu+ payload_artifact: ${{ inputs.linux_payload_artifact }}+ - target_os: macos+ target_triple: aarch64-apple-darwin+ payload_artifact: ${{ inputs.macos_payload_artifact }}+ - target_os: windows+ target_triple: x86_64-pc-windows-msvc+ payload_artifact: ${{ inputs.windows_payload_artifact }}+ uses: ./.github/workflows/cd-cua-perception-candidate.yml+ with:+ payload_artifact: ${{ matrix.payload_artifact }}+ payload_run_id: ${{ fromJSON(inputs.payload_run_id) }}+ source_ref: ${{ inputs.source_sha }}+ reviewed_ref: ${{ inputs.reviewed_ref }}+ target_os: ${{ matrix.target_os }}+ target_triple: ${{ matrix.target_triple }}+ catalog_version: ${{ fromJSON(inputs.catalog_version) }}+ expires_unix: ${{ fromJSON(inputs.expires_unix) }}+ secrets:+ PERCEPTION_ED25519_PRIVATE_KEY_BASE64: ${{ secrets.PERCEPTION_ED25519_PRIVATE_KEY_BASE64 }}diff --git a/.github/workflows/cd-cua-perception-candidate.yml b/.github/workflows/cd-cua-perception-candidate.ymlnew file mode 100644index 0000000000..5f4753f9cd--- /dev/null+++ b/.github/workflows/cd-cua-perception-candidate.yml@@ -0,0 +1,235 @@+name: "CD: Cua Perception candidate"++on:+ workflow_call:+ inputs:+ payload_artifact:+ description: "Platform input artifact containing release-input.json and payload files"+ required: true+ type: string+ payload_run_id:+ description: "Run ID that produced the platform input artifact"+ required: true+ type: number+ source_ref:+ description: "Exact trusted source commit represented by the candidate"+ required: true+ type: string+ reviewed_ref:+ description: "Explicitly reviewed ref whose current tip must equal source_ref"+ required: true+ type: string+ target_os:+ description: "linux, macos, or windows"+ required: true+ type: string+ target_triple:+ description: "Exact target triple expected in release-input.json"+ required: true+ type: string+ catalog_version:+ description: "Monotonic extension catalog version"+ required: true+ type: number+ expires_unix:+ description: "Catalog expiration as Unix seconds"+ required: true+ type: number+ secrets:+ PERCEPTION_ED25519_PRIVATE_KEY_BASE64:+ required: true++permissions:+ actions: read+ contents: read++concurrency:+ group: cua-perception-candidate-${{ inputs.source_ref }}-${{ inputs.target_triple }}+ cancel-in-progress: false++jobs:+ package:+ name: verify and package ${{ inputs.target_triple }}+ runs-on: ${{ inputs.target_os == 'windows' && 'windows-latest' || inputs.target_os == 'macos' && 'macos-15' || inputs.target_os == 'linux' && 'ubuntu-latest' || 'invalid-runner' }}+ steps:+ - name: Check out exact candidate source+ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683+ with:+ fetch-depth: 0+ ref: ${{ inputs.source_ref }}+ path: source+ persist-credentials: false+ - name: Check out trusted release tooling+ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683+ with:+ ref: ${{ github.workflow_sha }}+ path: release-control+ persist-credentials: false+ - name: Verify immutable trusted source input+ shell: bash+ env:+ SOURCE_REF: ${{ inputs.source_ref }}+ REVIEWED_REF: ${{ inputs.reviewed_ref }}+ TARGET_OS: ${{ inputs.target_os }}+ TARGET_TRIPLE: ${{ inputs.target_triple }}+ run: |+ set -euo pipefail+ test "$GITHUB_REPOSITORY" = "trycua/cua"+ [[ "$SOURCE_REF" =~ ^[0-9a-f]{40}$ ]]+ [[ "$REVIEWED_REF" =~ ^refs/(pull/[0-9]+/head|tags/[A-Za-z0-9._/-]+)$ ]]+ test "$SOURCE_REF" = "$(git -C source rev-parse HEAD)"+ git -C source fetch --no-tags origin "+$REVIEWED_REF:refs/cua-reviewed/source"+ test "$SOURCE_REF" = "$(git -C source rev-parse refs/cua-reviewed/source)"+ case "$TARGET_OS:$TARGET_TRIPLE" in+ linux:x86_64-unknown-linux-gnu|macos:aarch64-apple-darwin|windows:x86_64-pc-windows-msvc) ;;+ *) echo "unsupported target mapping: $TARGET_OS:$TARGET_TRIPLE" >&2; exit 1 ;;+ esac+ - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065+ with:+ python-version: "3.11"+ - name: Download platform bundle input+ uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093+ with:+ github-token: ${{ github.token }}+ run-id: ${{ inputs.payload_run_id }}+ name: ${{ inputs.payload_artifact }}+ path: perception-input+ - name: Bind corresponding source to the exact revision+ shell: bash+ run: |+ python3 release-control/.github/scripts/perception_release.py bind-source \+ --manifest perception-input/release-input.json \+ --payload-root perception-input \+ --repository-root source+ - name: Verify hashes, licenses, target, protocol, and model manifest+ shell: bash+ env:+ SOURCE_REF: ${{ inputs.source_ref }}+ TARGET_OS: ${{ inputs.target_os }}+ TARGET_TRIPLE: ${{ inputs.target_triple }}+ run: |+ set -euo pipefail+ python3 - "$SOURCE_REF" "$TARGET_OS" "$TARGET_TRIPLE" <<'PY'+ import json, pathlib, sys+ value = json.loads(pathlib.Path("perception-input/release-input.json").read_text())+ assert value["sourceSha"] == sys.argv[1]+ assert value["target"]["os"] == sys.argv[2]+ assert value["target"]["triple"] == sys.argv[3]+ PY+ python3 release-control/.github/scripts/perception_release.py validate \+ --manifest perception-input/release-input.json \+ --payload-root perception-input+ - name: Execute target worker release gates+ shell: bash+ run: |+ python3 release-control/.github/scripts/perception_release.py run-gates \+ --manifest perception-input/release-input.json \+ --payload-root perception-input \+ --evidence executed-verification.json+ - name: Build deterministic unsigned candidate+ shell: bash+ env:+ CATALOG_VERSION: ${{ inputs.catalog_version }}+ EXPIRES_UNIX: ${{ inputs.expires_unix }}+ run: |+ python3 release-control/.github/scripts/perception_release.py package \+ --manifest perception-input/release-input.json \+ --payload-root perception-input \+ --executed-evidence executed-verification.json \+ --output perception-candidate \+ --key-id cua-extension-ed25519-2026-01 \+ --catalog-version "$CATALOG_VERSION" \+ --expires-unix "$EXPIRES_UNIX"+ python3 release-control/.github/scripts/perception_release.py \+ verify-checksums perception-candidate/checksums.txt+ - name: Preserve unsigned input for isolated signing+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02+ with:+ name: UNSIGNED-cua-perception-${{ inputs.target_triple }}-${{ inputs.source_ref }}+ path: perception-candidate/+ if-no-files-found: error+ retention-days: 1++ sign:+ name: sign verified ${{ inputs.target_triple }} catalog+ needs: package+ runs-on: ubuntu-latest+ environment: cua-perception-candidate-signing+ steps:+ - name: Check out trusted release tooling+ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683+ with:+ ref: ${{ github.workflow_sha }}+ path: release-control+ persist-credentials: false+ - name: Download verified unsigned candidate+ uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093+ with:+ name: UNSIGNED-cua-perception-${{ inputs.target_triple }}-${{ inputs.source_ref }}+ path: perception-candidate+ - name: Verify package checksums before exposing the signing key+ run: python3 release-control/.github/scripts/perception_release.py verify-checksums perception-candidate/checksums.txt+ - name: Sign extension-manager catalog with trusted Ed25519 key+ env:+ PRIVATE_KEY_BASE64: ${{ secrets.PERCEPTION_ED25519_PRIVATE_KEY_BASE64 }}+ SOURCE_REF: ${{ inputs.source_ref }}+ TARGET_TRIPLE: ${{ inputs.target_triple }}+ working-directory: perception-candidate+ run: |+ node <<'JS'+ const crypto = require("node:crypto");+ const fs = require("node:fs");+ const path = require("node:path");+ const encodedKey = process.env.PRIVATE_KEY_BASE64;+ if (!encodedKey || Buffer.from(encodedKey, "base64").toString("base64") !== encodedKey) {+ throw new Error("private signing key is not canonical base64");+ }+ const privateKey = crypto.createPrivateKey(Buffer.from(encodedKey, "base64"));+ if (privateKey.asymmetricKeyType !== "ed25519") throw new Error("signing key is not Ed25519");+ const publicKey = crypto.createPublicKey(privateKey);+ const publicDer = publicKey.export({format: "der", type: "spki"});+ const trust = JSON.parse(fs.readFileSync(path.join(+ process.env.GITHUB_WORKSPACE,+ "release-control/.github/releases/cua-perception/trust-root.json",+ )));+ const active = trust.keys.filter((key) =>+ key.keyId === trust.activeKeyId && key.algorithm === "Ed25519" && key.status === "active"+ );+ if (active.length !== 1 || publicDer.subarray(-32).toString("base64") !== active[0].publicKeyBase64) {+ throw new Error("private signing key does not match the active trust root");+ }+ const payloadBytes = fs.readFileSync("catalog-payload.json");+ const payload = JSON.parse(payloadBytes);+ if (payload.corresponding_source_revision !== process.env.SOURCE_REF ||+ payload.target !== process.env.TARGET_TRIPLE || payload.key_id !== trust.activeKeyId) {+ throw new Error("catalog identity differs from trusted workflow inputs");+ }+ const archive = path.basename(payload.archive);+ if (archive !== payload.archive) throw new Error("catalog archive path is not canonical");+ const archiveBytes = fs.readFileSync(archive);+ if (archiveBytes.length !== payload.archive_size ||+ crypto.createHash("sha256").update(archiveBytes).digest("hex") !== payload.archive_sha256) {+ throw new Error("catalog archive binding is invalid");+ }+ const signature = crypto.sign(null, payloadBytes, privateKey);+ if (signature.length !== 64 || !crypto.verify(null, payloadBytes, publicKey, signature)) {+ throw new Error("Ed25519 catalog signature verification failed");+ }+ fs.writeFileSync("catalog.signature", signature);+ fs.writeFileSync("signed-catalog.json", JSON.stringify({+ payload,+ signature_algorithm: "ed25519",+ signature: signature.toString("base64"),+ }) + "\n");+ const signed = ["signed-catalog.json", "catalog-payload.json", "catalog.signature"];+ fs.writeFileSync("signed-candidate-checksums.txt", signed.map((name) =>+ `${crypto.createHash("sha256").update(fs.readFileSync(name)).digest("hex")} ${name}\n`+ ).join(""));+ JS+ - name: Preserve signed candidate without publishing+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02+ with:+ name: STAGING-cua-perception-candidate-${{ inputs.target_triple }}-${{ inputs.source_ref }}+ path: perception-candidate/+ if-no-files-found: error+ retention-days: 30diff --git a/.github/workflows/cd-cua-perception-review-supplied-inputs.yml b/.github/workflows/cd-cua-perception-review-supplied-inputs.ymlnew file mode 100644index 0000000000..6cd6bbc917--- /dev/null+++ b/.github/workflows/cd-cua-perception-review-supplied-inputs.yml@@ -0,0 +1,804 @@+name: "Review: Cua Perception supplied-input candidates"++on:+ workflow_dispatch:+ inputs:+ source_pr_number:+ description: "Pull request number carrying the cua-perception-live-review label"+ required: true+ type: string+ source_sha:+ description: "Exact current head SHA of the source pull request"+ required: true+ type: string+ catalog_version:+ description: "Positive review catalog version"+ required: true+ type: string+ expires_unix:+ description: "Review catalog expiry as Unix seconds"+ required: true+ type: string+ workflow_call:+ inputs:+ source_pr_number:+ description: "Pull request number carrying the cua-perception-live-review label"+ required: true+ type: string+ source_sha:+ description: "Exact current head SHA of the source pull request"+ required: true+ type: string+ catalog_version:+ description: "Positive review catalog version"+ required: true+ type: string+ expires_unix:+ description: "Review catalog expiry as Unix seconds"+ required: true+ type: string+ outputs:+ signed_candidate_artifact_id:+ description: "Artifact ID containing all signed review candidates"+ value: ${{ jobs.aggregate.outputs.signed_candidate_artifact_id }}+ producer_run_id:+ description: "Actions run ID that produced the signed review candidates"+ value: ${{ jobs.aggregate.outputs.producer_run_id }}++permissions:+ actions: read+ contents: read+ pull-requests: read++concurrency:+ group: cua-perception-review-inputs-${{ inputs.source_sha }}+ cancel-in-progress: false++jobs:+ reviewed-model:+ name: Broker the pinned reviewed model artifact+ runs-on: ubuntu-latest+ permissions:+ actions: read+ contents: read+ pull-requests: read+ outputs:+ source_asset_id: ${{ steps.verify.outputs.source_asset_id }}+ steps:+ - id: verify+ name: Verify the immutable producer run and artifact+ shell: bash+ env:+ GH_TOKEN: ${{ github.token }}+ # PR #3943 bootstrap input from a successful exact-head producer run.+ REVIEWED_ARTIFACT_ID: "10582583541"+ REVIEWED_ARTIFACT_NAME: cua-perception-input-linux-x86_64+ REVIEWED_RUN_ID: "35438356263"+ REVIEWED_SOURCE_ASSET_ID: "571471639"+ REVIEWED_SOURCE_SHA: 289372dea8b2b11f572f0f6a15824315bc74026b+ run: |+ set -euo pipefail+ [[ "$GITHUB_REPOSITORY" == "trycua/cua" ]]+ run_json="$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$REVIEWED_RUN_ID")"+ [[ "$(jq -r .id <<<"$run_json")" == "$REVIEWED_RUN_ID" ]]+ [[ "$(jq -r .status <<<"$run_json")" == "completed" ]]+ [[ "$(jq -r .conclusion <<<"$run_json")" == "success" ]]+ [[ "$(jq -r .event <<<"$run_json")" == "pull_request" ]]+ [[ "$(jq -r .head_sha <<<"$run_json")" == "$REVIEWED_SOURCE_SHA" ]]+ [[ "$(jq -r .head_repository.full_name <<<"$run_json")" == "$GITHUB_REPOSITORY" ]]+ workflow_path="$(jq -r .path <<<"$run_json")"+ expected_workflow=.github/workflows/review-cua-perception-pr3943.yml+ [[ "$workflow_path" == "$expected_workflow" || "$workflow_path" == "$expected_workflow"@* ]]++ artifact_json="$(gh api "repos/$GITHUB_REPOSITORY/actions/artifacts/$REVIEWED_ARTIFACT_ID")"+ [[ "$(jq -r .id <<<"$artifact_json")" == "$REVIEWED_ARTIFACT_ID" ]]+ [[ "$(jq -r .name <<<"$artifact_json")" == "$REVIEWED_ARTIFACT_NAME" ]]+ [[ "$(jq -r .expired <<<"$artifact_json")" == "false" ]]+ [[ "$(jq -r .workflow_run.id <<<"$artifact_json")" == "$REVIEWED_RUN_ID" ]]+ [[ "$(jq -r .workflow_run.head_sha <<<"$artifact_json")" == "$REVIEWED_SOURCE_SHA" ]]+ echo "source_asset_id=$REVIEWED_SOURCE_ASSET_ID" >> "$GITHUB_OUTPUT"+ - name: Download the exact reviewed producer artifact+ uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0+ with:+ artifact-ids: "10582583541"+ github-token: ${{ github.token }}+ path: reviewed-producer-input+ repository: trycua/cua+ run-id: "35438356263"+ - name: Extract and verify the reviewed model+ shell: bash+ run: |+ set -euo pipefail+ python3 - <<'PY'+ import hashlib, pathlib, shutil++ root = pathlib.Path("reviewed-producer-input")+ filename = "omniparser-icon-detect-1280-opset17.onnx"+ expected_sha256 = "d8a876bf7f9fb73d7da9432904ade7fa78e092e9a91674e5a2806b45562a9ab2"+ expected_size = 80_933_219+ matches = [path for path in root.rglob(filename) if path.is_file()]+ if len(matches) != 1:+ raise SystemExit(f"expected exactly one reviewed model in producer artifact; found {len(matches)}")+ source = matches[0]+ size = source.stat().st_size+ digest = hashlib.sha256(source.read_bytes()).hexdigest()+ if size != expected_size or digest != expected_sha256:+ raise SystemExit("producer artifact model differs from the reviewed size or SHA-256")+ destination = pathlib.Path("reviewed-inputs") / filename+ destination.parent.mkdir()+ shutil.copyfile(source, destination)+ print({"sha256": digest, "size": size})+ PY+ - name: Upload the immutable reviewed model handoff+ uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4.6.2+ with:+ name: reviewed-cua-perception-model+ path: reviewed-inputs/+ if-no-files-found: error+ retention-days: 1++ supplied-input:+ name: native review input (${{ matrix.target }})+ needs: reviewed-model+ env:+ MSYS2_ENV_CONV_EXCL: CUA_DRIVER_REVIEW_EXTENSION_PUBLIC_KEY_BASE64+ permissions:+ actions: read+ contents: read+ pull-requests: read+ strategy:+ fail-fast: false+ matrix:+ include:+ - runner: ubuntu-latest+ target: x86_64-unknown-linux-gnu+ platform: linux-x11+ input_artifact: cua-perception-input-linux-x86_64+ worker: cua-perception+ driver: cua-driver+ - runner: windows-latest+ target: x86_64-pc-windows-msvc+ platform: windows+ input_artifact: cua-perception-input-windows-x86_64+ worker: cua-perception.exe+ driver: cua-driver.exe+ # Match the production Driver build and hosted desktop E2E image.+ # The macOS 15 image cannot use the ephemeral self-signed review key.+ - runner: macos-26+ target: aarch64-apple-darwin+ platform: macos+ input_artifact: cua-perception-input-macos-aarch64+ worker: cua-perception+ driver: cua-driver+ runs-on: ${{ matrix.runner }}+ timeout-minutes: 90+ steps:+ - name: Check out the exact workflow and candidate source+ uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4+ with:+ ref: ${{ inputs.source_sha }}+ fetch-depth: 0+ persist-credentials: false+ - uses: dtolnay/rust-toolchain@4716b85f2fac3e324e64fa2810f6b5c3905760a5 # 1.97.1+ - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5+ with:+ python-version: "3.12"+ - name: Install native Linux build dependencies+ if: runner.os == 'Linux'+ shell: bash+ run: |+ set -euo pipefail+ sudo apt-get update+ sudo apt-get install -y --no-install-recommends \+ clang pkg-config libdbus-1-dev libpipewire-0.3-dev libspa-0.2-dev \+ libei-dev libx11-dev libxi-dev libxtst-dev libxext-dev \+ libwebkit2gtk-4.1-dev libssl-dev libxdo-dev \+ libayatana-appindicator3-dev librsvg2-dev+ - name: Require the exact current pull request head+ shell: bash+ env:+ GH_TOKEN: ${{ github.token }}+ REQUESTED_PR_NUMBER: ${{ inputs.source_pr_number }}+ REQUESTED_SHA: ${{ inputs.source_sha }}+ EVENT_HEAD_REPOSITORY: ${{ github.event.pull_request.head.repo.full_name }}+ EVENT_HEAD_SHA: ${{ github.event.pull_request.head.sha }}+ EVENT_LABEL: ${{ github.event.label.name }}+ EVENT_PR_NUMBER: ${{ github.event.pull_request.number }}+ run: |+ set -euo pipefail+ test "$GITHUB_REPOSITORY" = "trycua/cua"+ [[ "$REQUESTED_PR_NUMBER" =~ ^[1-9][0-9]*$ ]]+ [[ "$REQUESTED_SHA" =~ ^[0-9a-f]{40}$ ]]+ test "$(git rev-parse HEAD)" = "$REQUESTED_SHA"+ if [[ "$GITHUB_EVENT_NAME" == pull_request ]]; then+ test "$EVENT_PR_NUMBER" = "$REQUESTED_PR_NUMBER"+ test "$EVENT_HEAD_REPOSITORY" = "$GITHUB_REPOSITORY"+ test "$EVENT_HEAD_SHA" = "$REQUESTED_SHA"+ test "$EVENT_LABEL" = cua-perception-live-review+ else+ test "$GITHUB_EVENT_NAME" = workflow_dispatch+ test "$GITHUB_SHA" = "$REQUESTED_SHA"+ fi+ IFS=$'\t' read -r state head_sha head_repo < <(+ gh api "repos/$GITHUB_REPOSITORY/pulls/$REQUESTED_PR_NUMBER" \+ --jq '[.state, .head.sha, .head.repo.full_name] | @tsv'+ )+ test "$state" = open+ test "$head_repo" = "$GITHUB_REPOSITORY"+ test "$head_sha" = "$REQUESTED_SHA"+ git fetch --no-tags origin "+refs/pull/$REQUESTED_PR_NUMBER/head:refs/cua-reviewed/pr-$REQUESTED_PR_NUMBER"+ test "$(git rev-parse "refs/cua-reviewed/pr-$REQUESTED_PR_NUMBER")" = "$REQUESTED_SHA"+ - name: Download the immutable reviewed model handoff+ uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0+ with:+ name: reviewed-cua-perception-model+ path: reviewed-inputs+ - name: Verify the supplied model handoff+ shell: bash+ env:+ CUA_REVIEWED_MODEL_ASSET_ID: ${{ needs.reviewed-model.outputs.source_asset_id }}+ run: |+ set -euo pipefail+ python3 - <<'PY'+ import hashlib, json, os, pathlib++ asset_id = os.environ["CUA_REVIEWED_MODEL_ASSET_ID"]+ if not asset_id.isdigit() or asset_id.startswith("0"):+ raise SystemExit("broker returned an invalid reviewed model asset ID")+ expected = next(item for item in json.loads(pathlib.Path(+ "libs/cua-driver/rust/crates/cua-perception/scripts/artifacts.lock.json"+ ).read_text())["artifacts"] if item["role"] == "icon-detect")+ if expected.get("url") is not None or expected["size"] != 80_933_219:+ raise SystemExit("reviewed detector lock must remain supplied-only at the reviewed size")+ destination = pathlib.Path("reviewed-inputs") / expected["filename"]+ size = destination.stat().st_size+ digest = hashlib.sha256(destination.read_bytes()).hexdigest()+ if size != expected["size"] or digest != expected["sha256"]:+ raise SystemExit("supplied model bytes differ from the reviewed size or SHA-256")+ print(json.dumps({"asset_id": int(asset_id), "review_only": True,+ "sha256": digest, "size": size}, sort_keys=True))+ PY+ - name: Generate an ephemeral review trust root+ shell: bash+ run: |+ set -euo pipefail+ node <<'JS'+ const crypto = require("node:crypto");+ const fs = require("node:fs");+ const path = require("node:path");+ const {privateKey, publicKey} = crypto.generateKeyPairSync("ed25519");+ const privateDer = privateKey.export({format: "der", type: "pkcs8"});+ const publicDer = publicKey.export({format: "der", type: "spki"});+ const rawPublicKey = publicDer.subarray(-32);+ if (rawPublicKey.length !== 32) throw new Error("unexpected Ed25519 public key length");+ fs.writeFileSync(path.join(process.env.RUNNER_TEMP, "review-private-key.der"), privateDer, {mode: 0o600});+ fs.appendFileSync(process.env.GITHUB_ENV,+ `CUA_DRIVER_REVIEW_EXTENSION_PUBLIC_KEY_BASE64=${rawPublicKey.toString("base64")}\n`);+ JS+ - name: Build the native worker and measured review Driver+ shell: bash+ env:+ TARGET: ${{ matrix.target }}+ run: |+ set -euo pipefail+ cargo build --manifest-path libs/cua-driver/rust/Cargo.toml \+ -p cua-perception --release --locked+ cargo build --manifest-path libs/cua-driver/rust/Cargo.toml \+ -p cua-driver --features review-trust-root --locked+ - name: Assemble and execute native health, self-test, and real parse+ shell: bash+ env:+ SOURCE_SHA: ${{ inputs.source_sha }}+ TARGET: ${{ matrix.target }}+ WORKER: ${{ matrix.worker }}+ run: |+ set -euo pipefail+ version="$(tr -d '[:space:]' < libs/cua-driver/rust/crates/cua-perception/VERSION)"+ python3 libs/cua-driver/rust/crates/cua-perception/scripts/assemble_bundle.py \+ --target "$TARGET" \+ --worker "libs/cua-driver/rust/target/release/$WORKER" \+ --inputs reviewed-inputs \+ --cache "$RUNNER_TEMP/cua-perception-cache" \+ --real-parse-fixture libs/cua-driver/tests/fixtures/apps/cross-platform/tauri/src-tauri/icons/icon.png \+ --source-sha "$SOURCE_SHA" \+ --version "$version" \+ --output perception-input+ - name: Convert sealed assembler evidence to candidate input+ shell: bash+ run: |+ set -euo pipefail+ python3 - <<'PY'+ import json, pathlib++ root = pathlib.Path("perception-input")+ manifest = json.loads((root / "artifact-manifest.json").read_text())+ (root / "release-input.json").write_text(+ json.dumps(manifest, indent=2, sort_keys=True) + "\n"+ )+ PY+ python3 .github/scripts/perception_release.py bind-source \+ --manifest perception-input/release-input.json \+ --payload-root perception-input \+ --repository-root .+ python3 .github/scripts/perception_release.py validate \+ --manifest perception-input/release-input.json \+ --payload-root perception-input+ python3 - <<'PY'+ import pathlib+ for stale in ("artifact-manifest.json", "SHA256SUMS"):+ (pathlib.Path("perception-input") / stale).unlink()+ PY+ - name: Preserve exact candidate packaging input+ uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4.6.2+ with:+ name: ${{ matrix.input_artifact }}+ path: perception-input/+ if-no-files-found: error+ retention-days: 7+ - name: Package, review-sign, and measure the candidate+ shell: bash+ env:+ CATALOG_VERSION: ${{ inputs.catalog_version }}+ DRIVER: ${{ matrix.driver }}+ EXPIRES_UNIX: ${{ inputs.expires_unix }}+ PLATFORM: ${{ matrix.platform }}+ SOURCE_SHA: ${{ inputs.source_sha }}+ TARGET: ${{ matrix.target }}+ CUA_REVIEWED_MODEL_ASSET_ID: ${{ needs.reviewed-model.outputs.source_asset_id }}+ run: |+ set -euo pipefail+ [[ "$CATALOG_VERSION" =~ ^[1-9][0-9]*$ ]]+ [[ "$EXPIRES_UNIX" =~ ^[1-9][0-9]*$ ]]+ python3 .github/scripts/perception_release.py run-gates \+ --manifest perception-input/release-input.json \+ --payload-root perception-input \+ --evidence executed-verification.json+ python3 .github/scripts/perception_release.py package \+ --manifest perception-input/release-input.json \+ --payload-root perception-input \+ --executed-evidence executed-verification.json \+ --output perception-candidate \+ --key-id cua-extension-ed25519-2026-01 \+ --catalog-version "$CATALOG_VERSION" \+ --expires-unix "$EXPIRES_UNIX"+ python3 .github/scripts/perception_release.py \+ verify-checksums perception-candidate/checksums.txt+ mkdir -p "review-staging/$PLATFORM"+ cp perception-candidate/* "review-staging/$PLATFORM/"+ cp "libs/cua-driver/rust/target/debug/$DRIVER" "review-staging/$PLATFORM/review-$DRIVER"+ if [[ "$PLATFORM" == macos ]]; then+ bash .github/scripts/macos-review-codesign.sh \+ "review-staging/$PLATFORM/review-$DRIVER" \+ "review-staging/$PLATFORM/code-signing.json"+ else+ python3 - "review-staging/$PLATFORM/code-signing.json" <<'PY'+ import json, pathlib, sys+ pathlib.Path(sys.argv[1]).write_text(json.dumps({+ "status": "not-applicable",+ "format": "none",+ "identity": "none",+ "certificate_sha256": None,+ "designated_requirement": None,+ }, indent=2, sort_keys=True) + "\n")+ PY+ fi+ node <<'JS'+ const crypto = require("node:crypto");+ const fs = require("node:fs");+ const path = require("node:path");+ const platform = process.env.PLATFORM;+ const root = path.join("review-staging", platform);+ const privatePath = path.join(process.env.RUNNER_TEMP, "review-private-key.der");+ const privateBytes = fs.readFileSync(privatePath);+ const privateKey = crypto.createPrivateKey({key: privateBytes, format: "der", type: "pkcs8"});+ const publicKey = crypto.createPublicKey(privateKey);+ const publicRaw = publicKey.export({format: "der", type: "spki"}).subarray(-32);+ const publicBase64 = publicRaw.toString("base64");+ if (publicBase64 !== process.env.CUA_DRIVER_REVIEW_EXTENSION_PUBLIC_KEY_BASE64) {+ throw new Error("review Driver trust root differs from the signing key");+ }+ const payloadPath = path.join(root, "catalog-payload.json");+ const payload = JSON.parse(fs.readFileSync(payloadPath));+ payload.publisher_id = "cua-review-only";+ payload.publisher_name = "Cua REVIEW ONLY";+ payload.key_id = "review-only-build-override";+ payload.next_key = null;+ const payloadBytes = Buffer.from(JSON.stringify(payload));+ fs.writeFileSync(payloadPath, payloadBytes);+ const signature = crypto.sign(null, payloadBytes, privateKey);+ if (!crypto.verify(null, payloadBytes, publicKey, signature)) {+ throw new Error("review Ed25519 signature verification failed");+ }+ fs.writeFileSync(path.join(root, "catalog.signature"), signature);+ fs.writeFileSync(path.join(root, "signed-catalog.json"), JSON.stringify({+ payload,+ signature_algorithm: "ed25519",+ signature: signature.toString("base64"),+ }) + "\n");+ const digest = name => crypto.createHash("sha256").update(fs.readFileSync(path.join(root, name))).digest("hex");+ const driverName = `review-${process.env.DRIVER}`;+ const archiveName = payload.archive;+ const modelLock = JSON.parse(fs.readFileSync(+ "libs/cua-driver/rust/crates/cua-perception/scripts/artifacts.lock.json"));+ const model = modelLock.artifacts.find(item => item.role === "icon-detect");+ const codeSigning = JSON.parse(fs.readFileSync(path.join(root, "code-signing.json")));+ const measurements = {+ review_only: true,+ source_sha: process.env.SOURCE_SHA,+ target: process.env.TARGET,+ supplied_model_asset_id: Number(process.env.CUA_REVIEWED_MODEL_ASSET_ID),+ supplied_model_sha256: model.sha256,+ supplied_model_size: model.size,+ public_key_base64: publicBase64,+ public_key_sha256: crypto.createHash("sha256").update(publicRaw).digest("hex"),+ key_id: payload.key_id,+ publisher_id: payload.publisher_id,+ signature_algorithm: "ed25519",+ catalog_sha256: digest("signed-catalog.json"),+ archive_sha256: digest(archiveName),+ review_driver_relative_path: driverName,+ review_driver_build_profile: "debug-review-trust-root",+ review_driver_sha256: digest(driverName),+ code_signing: codeSigning,+ };+ fs.writeFileSync(path.join(root, "review-measurements.json"),+ JSON.stringify(measurements, null, 2) + "\n");+ const signedFiles = [archiveName, "catalog-payload.json", "catalog.signature", "code-signing.json",+ "signed-catalog.json", "sbom.spdx.json", "provenance.redacted.json",+ "runtime-contract.json", driverName, "review-measurements.json"];+ fs.writeFileSync(path.join(root, "signed-candidate-checksums.txt"),+ signedFiles.sort().map(name => `${digest(name)} ${name}\n`).join(""));+ fs.unlinkSync(path.join(root, "checksums.txt"));+ fs.writeFileSync(privatePath, Buffer.alloc(privateBytes.length), {flag: "r+"});+ fs.unlinkSync(privatePath);+ JS+ python3 - <<'PY'+ import hashlib, json, os, pathlib, re, subprocess, tarfile++ root = pathlib.Path("review-staging") / os.environ["PLATFORM"]+ measurements_path = root / "review-measurements.json"+ measurements = json.loads(measurements_path.read_text())+ archive = root / json.loads((root / "catalog-payload.json").read_text())["archive"]++ def digest(data):+ return hashlib.sha256(data).hexdigest()++ with tarfile.open(archive, "r:gz") as package:+ members = package.getmembers()+ names = [member.name for member in members]+ if len(names) != len(set(names)) or any(+ member.issym() or member.islnk() or pathlib.PurePosixPath(member.name).is_absolute()+ or ".." in pathlib.PurePosixPath(member.name).parts for member in members+ ):+ raise SystemExit("signed archive contains an unsafe or duplicate member")++ def member_bytes(name):+ matches = [member for member in members if member.name == name and member.isfile()]+ if len(matches) != 1:+ raise SystemExit(f"signed archive must contain one regular {name}")+ stream = package.extractfile(matches[0])+ if stream is None:+ raise SystemExit(f"signed archive member cannot be read: {name}")+ return stream.read()++ def member_json(name):+ return json.loads(member_bytes(name))++ artifact_bytes = member_bytes("metadata/artifact-manifest.json")+ artifact_manifest = json.loads(artifact_bytes)+ extension_bytes = member_bytes("extension.json")+ extension = json.loads(extension_bytes)+ runtime_contract = member_json("metadata/runtime-contract.json")+ model_manifest = member_json("model-manifest.json")+ model_ledger = member_json("modelLedger.json")+ verification_bytes = member_bytes("metadata/executed-verification.json")+ verification = json.loads(verification_bytes)++ if artifact_manifest["sourceSha"] != measurements["source_sha"]:+ raise SystemExit("sealed artifact manifest source differs from candidate")+ if artifact_manifest["target"]["triple"] != measurements["target"]:+ raise SystemExit("sealed artifact manifest target differs from candidate")+ if extension["version"] != artifact_manifest["version"]:+ raise SystemExit("sealed extension and artifact manifest versions differ")+ if runtime_contract["protocolVersion"] != artifact_manifest["protocol"]["version"]:+ raise SystemExit("sealed runtime contract protocol differs from artifact manifest")++ artifacts = artifact_manifest["artifacts"]+ worker = next(item for item in artifacts if item["kind"] == "worker")+ runtime = next(item for item in artifacts if item["kind"] == "runtime")+ models = []+ for role in ("icon-detect", "ocr-detect", "ocr-recognize"):+ artifact = next(item for item in artifacts if item.get("role") == role)+ ledger = next(item for item in model_ledger["models"] if item["artifact"] == artifact["name"])+ sealed_bytes = member_bytes(f"models/{artifact['name']}")+ if digest(sealed_bytes) != artifact["sha256"]:+ raise SystemExit(f"sealed {role} bytes differ from artifact manifest")+ original = ledger.get("sourceArtifact", {}).get("sha256", artifact["sha256"])+ models.append({+ "role": role,+ "id": artifact["name"],+ "revision": ledger["revision"],+ "original_sha256": original,+ "converted_sha256": artifact["sha256"],+ "license": ledger["license"],+ })++ runtime_bytes = member_bytes(f"runtime/{runtime['name']}")+ worker_bytes = member_bytes(f"bin/{worker['name']}")+ if digest(runtime_bytes) != runtime["sha256"] or digest(worker_bytes) != worker["sha256"]:+ raise SystemExit("sealed worker or runtime bytes differ from artifact manifest")+ gates = {gate["gate"]: gate for gate in verification["gates"]}+ if gates.get("self-test", {}).get("status") != "passed" or gates.get("mismatch-rejection", {}).get("status") != "passed":+ raise SystemExit("sealed executed evidence does not prove self-test and mismatch rejection")++ driver = root / measurements["review_driver_relative_path"]+ version_output = subprocess.run(+ [str(driver), "--version"], check=True, capture_output=True, text=True+ ).stdout.strip()+ match = re.search(r"\b[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?\b", version_output)+ if not match:+ raise SystemExit("review Driver did not report a bounded semantic version")+ measurements.update({+ "review_driver_version": match.group(0),+ "extension_version": artifact_manifest["version"],+ "protocol_version": artifact_manifest["protocol"]["version"],+ "worker_sha256": worker["sha256"],+ "models": models,+ "onnx_runtime": {+ "revision": model_manifest["onnx_runtime"]["version"],+ "sha256": runtime["sha256"],+ "license": runtime["license"]["spdx"],+ },+ "self_test": {+ "status": "passed",+ "mismatch_rejection": True,+ "evidence_sha256": digest(verification_bytes),+ },+ "sealed_artifact_manifest_sha256": digest(artifact_bytes),+ "sealed_extension_manifest_sha256": digest(extension_bytes),+ })+ icon = next(item for item in models if item["role"] == "icon-detect")+ if measurements["supplied_model_sha256"] != icon["converted_sha256"]:+ raise SystemExit("supplied model measurement differs from sealed archive")+ measurements_path.write_text(json.dumps(measurements, indent=2, sort_keys=True) + "\n")++ signed_files = [+ archive.name, "catalog-payload.json", "catalog.signature", "code-signing.json", "signed-catalog.json",+ "sbom.spdx.json", "provenance.redacted.json", "runtime-contract.json",+ measurements["review_driver_relative_path"], "review-measurements.json",+ ]+ (root / "signed-candidate-checksums.txt").write_text("".join(+ f"{hashlib.sha256((root / name).read_bytes()).hexdigest()} {name}\n"+ for name in sorted(signed_files)+ ))+ PY+ - name: Inspect the signed candidate with the native review Driver+ shell: bash+ env:+ PLATFORM: ${{ matrix.platform }}+ run: |+ set -euo pipefail+ root="review-staging/$PLATFORM"+ driver="$root/review-${{ matrix.driver }}"+ catalog="$root/signed-catalog.json"+ preview="$RUNNER_TEMP/cua-perception-producer-inspect.json"+ inspect_home="$RUNNER_TEMP/cua-perception-producer-inspect-home"+ test ! -e "$inspect_home"+ mkdir "$inspect_home"+ CUA_DRIVER_RS_HOME="$inspect_home" \+ "$driver" extension inspect cua-perception --catalog "$catalog" --json > "$preview"+ python3 - "$preview" "$catalog" "$root/review-measurements.json" <<'PY'+ import hashlib, json, pathlib, re, sys++ preview_path, catalog_path, measurements_path = map(pathlib.Path, sys.argv[1:])+ preview = json.loads(preview_path.read_text())+ catalog = json.loads(catalog_path.read_text())+ measurements = json.loads(measurements_path.read_text())+ payload = catalog["payload"]++ assert preview["trust"] == "review-only-publisher-verified"+ assert preview["evidence_class"] == "review-only-not-release-evidence"+ assert preview["publisher_signature_verified"] is True+ assert preview["publisher_id"] == measurements["publisher_id"] == "cua-review-only"+ assert preview["publisher_key_id"] == measurements["key_id"] == "review-only-build-override"+ assert preview["signing_key_algorithm"] == measurements["signature_algorithm"] == "ed25519"+ assert preview["archive_sha256"] == measurements["archive_sha256"] == payload["archive_sha256"]+ archive_relative = pathlib.PurePosixPath(payload["archive"])+ assert not archive_relative.is_absolute() and ".." not in archive_relative.parts+ archive = catalog_path.parent.joinpath(*archive_relative.parts).resolve()+ archive.relative_to(catalog_path.parent.resolve())+ assert hashlib.sha256(archive.read_bytes()).hexdigest() == preview["archive_sha256"]+ assert preview["authorization"] == {+ "request": "cli-inspect",+ "confirmation_required": False,+ "confirmation_received": False,+ "mutation_authorized": False,+ "mutation_performed": False,+ }+ assert preview["mutation_performed"] is False+ assert preview["installed"] is False+ assert preview["ran"] is False++ files = {item["path"]: item["sha256"] for item in preview["files"]}+ assert len(files) == len(preview["files"])++ def assert_binding(label, binding):+ assert set(binding) == {"path", "sha256"}, label+ assert re.fullmatch(r"[0-9a-f]{64}", binding["sha256"]), label+ assert files.get(binding["path"]) == binding["sha256"], label++ model_licenses = {item["model"]: item["file"] for item in preview["model_licenses"]}+ assert len(model_licenses) == len(preview["models"]) == 3+ for model in preview["models"]:+ assert files.get(model["path"]) == model["conversion_sha256"]+ assert_binding(f"model license {model['path']}", model["license_file"])+ assert model_licenses[model["path"]] == model["license_file"]++ notices = {item["component"]: item["file"] for item in preview["license_notices"]}+ assert len(notices) == len(preview["components"]) > 0+ for component in preview["components"]:+ assert_binding(f"component notice {component['name']}", component["notice_file"])+ assert notices[component["name"]] == component["notice_file"]++ source = preview["corresponding_source"]+ assert_binding("corresponding source", source["file"])+ assert source["uri"] == preview["corresponding_source_uri"] == payload["corresponding_source_uri"]+ assert source["revision"] == preview["corresponding_source_revision"] == payload["corresponding_source_revision"]+ PY+ - name: Install and self-test the packaged candidate with the native review Driver+ shell: bash+ env:+ PLATFORM: ${{ matrix.platform }}+ run: |+ set -euo pipefail+ root="review-staging/$PLATFORM"+ driver="$root/review-${{ matrix.driver }}"+ catalog="$root/signed-catalog.json"+ measurements="$root/review-measurements.json"+ status="$RUNNER_TEMP/cua-perception-producer-status.json"+ install_home="$RUNNER_TEMP/cua-perception-producer-install-home"+ test ! -e "$install_home"+ CUA_DRIVER_RS_HOME="$install_home" \+ "$driver" extension install cua-perception --catalog "$catalog"+ CUA_DRIVER_RS_HOME="$install_home" \+ "$driver" extension status cua-perception --self-test --json > "$status"+ python3 - "$status" "$measurements" <<'PY'+ import json, pathlib, sys++ status_path, measurements_path = map(pathlib.Path, sys.argv[1:])+ installed = json.loads(status_path.read_text())+ measurements = json.loads(measurements_path.read_text())++ assert installed["id"] == "cua-perception"+ assert installed["installed"] is True+ assert installed["healthy"] is True+ assert installed["trust"] == "review-only-publisher-verified"+ assert installed["evidence_class"] == "review-only-not-release-evidence"+ assert installed["publisher_id"] == measurements["publisher_id"] == "cua-review-only"+ assert installed["publisher_key_id"] == measurements["key_id"] == "review-only-build-override"+ assert installed["active_version"] == measurements["extension_version"]+ assert installed["protocol_version"] == measurements["protocol_version"]+ PY+ - name: Destroy any remaining ephemeral private key+ if: always()+ shell: bash+ run: |+ node <<'JS'+ const fs = require("node:fs");+ const path = require("node:path");+ const privatePath = path.join(process.env.RUNNER_TEMP, "review-private-key.der");+ if (fs.existsSync(privatePath)) {+ const size = fs.statSync(privatePath).size;+ fs.writeFileSync(privatePath, Buffer.alloc(size), {flag: "r+"});+ fs.unlinkSync(privatePath);+ }+ JS+ - name: Preserve signed review-only target without publishing+ uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4.6.2+ with:+ name: review-cua-perception-${{ matrix.platform }}-${{ inputs.source_sha }}+ path: review-staging/+ if-no-files-found: error+ retention-days: 7++ aggregate:+ name: aggregate signed review candidates+ needs: supplied-input+ runs-on: ubuntu-latest+ permissions:+ actions: read+ contents: read+ outputs:+ signed_candidate_artifact_id: ${{ steps.upload.outputs.artifact-id }}+ producer_run_id: ${{ steps.producer.outputs.run_id }}+ steps:+ - id: producer+ name: Bind the aggregate to this producer run+ shell: bash+ run: echo "run_id=$GITHUB_RUN_ID" >> "$GITHUB_OUTPUT"+ - name: Download all signed target layouts+ uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0+ with:+ pattern: review-cua-perception-*-${{ inputs.source_sha }}+ path: staged+ merge-multiple: true+ - name: Verify the live workflow catalog layout+ shell: bash+ env:+ SOURCE_SHA: ${{ inputs.source_sha }}+ run: |+ set -euo pipefail+ python3 - <<'PY'+ import hashlib, json, os, pathlib+ root = pathlib.Path("staged")+ for platform, target in (("windows", "x86_64-pc-windows-msvc"),+ ("linux-x11", "x86_64-unknown-linux-gnu"),+ ("macos", "aarch64-apple-darwin")):+ directory = root / platform+ catalog_path = directory / "signed-catalog.json"+ measurements_path = directory / "review-measurements.json"+ catalog = json.loads(catalog_path.read_text())+ measurements = json.loads(measurements_path.read_text())+ payload = catalog["payload"]+ assert measurements["review_only"] is True+ assert measurements["source_sha"] == os.environ["SOURCE_SHA"]+ assert measurements["target"] == target == payload["target"]+ assert measurements["review_driver_version"]+ assert measurements["extension_version"] == payload["version"]+ assert measurements["protocol_version"] > 0 and len(measurements["worker_sha256"]) == 64+ assert [item["role"] for item in measurements["models"]] == ["icon-detect", "ocr-detect", "ocr-recognize"]+ assert all(len(item["original_sha256"]) == len(item["converted_sha256"]) == 64 and item["revision"] and item["license"] for item in measurements["models"])+ assert measurements["onnx_runtime"]["revision"] and len(measurements["onnx_runtime"]["sha256"]) == 64+ assert measurements["self_test"]["status"] == "passed" and measurements["self_test"]["mismatch_rejection"] is True+ assert len(measurements["sealed_artifact_manifest_sha256"]) == len(measurements["sealed_extension_manifest_sha256"]) == 64+ assert payload["publisher_id"] == "cua-review-only"+ assert payload["publisher_name"] == "Cua REVIEW ONLY"+ assert payload["key_id"] == "review-only-build-override"+ assert catalog["signature_algorithm"] == "ed25519"+ archive = directory / payload["archive"]+ assert archive.is_file()+ assert hashlib.sha256(archive.read_bytes()).hexdigest() == payload["archive_sha256"]+ driver_relative = pathlib.PurePosixPath(measurements["review_driver_relative_path"])+ assert not driver_relative.is_absolute() and ".." not in driver_relative.parts+ driver = directory.joinpath(*driver_relative.parts)+ assert driver.is_file()+ assert measurements["review_driver_build_profile"] == "debug-review-trust-root"+ assert hashlib.sha256(driver.read_bytes()).hexdigest() == measurements["review_driver_sha256"]+ signing = measurements["code_signing"]+ assert set(signing) == {"status", "format", "identity", "certificate_sha256", "designated_requirement"}+ if platform == "macos":+ assert signing["status"] == "verified"+ assert signing["format"] == "apple-codesign"+ assert signing["identity"] == "ephemeral-self-signed-review-only"+ assert len(signing["certificate_sha256"]) == 64+ assert any(marker in signing["designated_requirement"] for marker in ("certificate leaf", "certificate root"))+ else:+ assert signing == {"status": "not-applicable", "format": "none", "identity": "none", "certificate_sha256": None, "designated_requirement": None}+ PY+ node <<'JS'+ const crypto = require("node:crypto");+ const fs = require("node:fs");+ for (const platform of ["windows", "linux-x11", "macos"]) {+ const root = `staged/${platform}`;+ const catalog = JSON.parse(fs.readFileSync(`${root}/signed-catalog.json`));+ const metadata = JSON.parse(fs.readFileSync(`${root}/review-measurements.json`));+ const payloadBytes = fs.readFileSync(`${root}/catalog-payload.json`);+ if (JSON.stringify(catalog.payload) !== payloadBytes.toString()) {+ throw new Error(`${platform} signed payload bytes are not exact`);+ }+ const raw = Buffer.from(metadata.public_key_base64, "base64");+ const spki = Buffer.concat([Buffer.from("302a300506032b6570032100", "hex"), raw]);+ const key = crypto.createPublicKey({key: spki, format: "der", type: "spki"});+ if (!crypto.verify(null, payloadBytes, key, Buffer.from(catalog.signature, "base64"))) {+ throw new Error(`${platform} review signature is invalid`);+ }+ }+ JS+ - id: upload+ name: Upload one immutable staged artifact for the authorized live workflow+ uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4.6.2+ with:+ name: STAGING-cua-perception-review-candidates-${{ inputs.source_sha }}+ path: staged/+ if-no-files-found: error+ retention-days: 7diff --git a/.github/workflows/cd-rust-cua-driver.yml b/.github/workflows/cd-rust-cua-driver.ymlindex cb74953ae9..ed8f638aa4 100644--- a/.github/workflows/cd-rust-cua-driver.yml+++ b/.github/workflows/cd-rust-cua-driver.yml@@ -127,8 +127,13 @@ jobs:--sha "$SHA" \--path libs/cua-driver \--exclude-path libs/cua-driver/docs \+ --exclude-path libs/cua-driver/examples \--exclude-path libs/cua-driver/python \--exclude-path libs/cua-driver/tests \+ --exclude-path libs/cua-driver/rust/crates/cua-perception \+ --exclude-path libs/cua-driver/experiments/cua-perception-inference \+ --exclude-companion-path libs/cua-driver/rust/Cargo.toml \+ --exclude-companion-path libs/cua-driver/rust/Cargo.lock \--changelog libs/cua-driver/rust/CHANGELOG.md \--output "$RUNNER_TEMP/cua-driver-release-manifest.json"@@ -253,7 +258,7 @@ jobs:cp "target/${TARGET}/release/cua_driver_node_runtime.node" "release/${STAGE}/"cp include/cua_driver_abi.h "release/${STAGE}/"cp -R ../wayland-helper "release/${STAGE}/wayland-helper"- cp ../../LICENSE.md "release/${STAGE}/LICENSE" 2>/dev/null || true+ cp ../../../LICENSE.md "release/${STAGE}/LICENSE"(cd release && tar -czf "${STAGE}.tar.gz" "${STAGE}")# Bare runtime tarball: CLI plus the UniFFI library consumed by the# Python and Node imported-SDK packages.@@ -431,7 +436,7 @@ jobs:Copy-Item "target/$target/release/cua_driver_sdk.dll" "release/$stage/"Copy-Item "target/$target/release/cua_driver_node_runtime.node" "release/$stage/"Copy-Item "include/cua_driver_abi.h" "release/$stage/"- if (Test-Path "../../LICENSE.md") { Copy-Item "../../LICENSE.md" "release/$stage/LICENSE" }+ Copy-Item "../../../LICENSE.md" "release/$stage/LICENSE" -ErrorAction Stop# Zip the directory itself (no trailing /*) so the archive contains# the top-level "$stage" wrapper dir — install.ps1 walks into# extracted/cua-driver-rs-<v>-<arch>/cua-driver.exe to find the@@ -901,7 +906,7 @@ jobs:# attribution (issue #1525). Tarball callers that want only# the bare binary can grab the *-binary.tar.gz below.cp -R release/CuaDriver.app "release/${STAGE}/CuaDriver.app"- cp ../../LICENSE.md "release/${STAGE}/LICENSE" 2>/dev/null || true+ cp ../../../LICENSE.md "release/${STAGE}/LICENSE"(cd release && tar -czf "${STAGE}.tar.gz" "${STAGE}")done# Bare runtime tarball: universal CLI plus universal UniFFI library.@@ -1245,8 +1250,13 @@ jobs:--sha "${{ steps.version.outputs.sha }}" \--path libs/cua-driver \--exclude-path libs/cua-driver/docs \+ --exclude-path libs/cua-driver/examples \--exclude-path libs/cua-driver/python \--exclude-path libs/cua-driver/tests \+ --exclude-path libs/cua-driver/rust/crates/cua-perception \+ --exclude-path libs/cua-driver/experiments/cua-perception-inference \+ --exclude-companion-path libs/cua-driver/rust/Cargo.toml \+ --exclude-companion-path libs/cua-driver/rust/Cargo.lock \--changelog libs/cua-driver/rust/CHANGELOG.md \--asset-dir release-upload \--output release-metadata/release-manifest.jsondiff --git a/.github/workflows/ci-cua-perception-release.yml b/.github/workflows/ci-cua-perception-release.ymlnew file mode 100644index 0000000000..5ac31a1b99--- /dev/null+++ b/.github/workflows/ci-cua-perception-release.yml@@ -0,0 +1,95 @@+name: "CI: Cua Perception release contract"++on:+ pull_request:+ paths:+ - ".github/releases/**"+ - ".github/scripts/perception_release.py"+ - ".github/scripts/verify_cua_driver_release_archives.py"+ - ".github/scripts/tests/test_cua_driver_default_distribution.py"+ - ".github/scripts/tests/test_cua_perception_release_topology.py"+ - ".github/scripts/tests/test_verify_cua_driver_release_archives.py"+ - ".github/workflows/cd-cua-perception-candidate.yml"+ - ".github/workflows/cd-rust-cua-driver.yml"+ - ".github/workflows/ci-cua-perception-release.yml"+ - ".github/workflows/release-please.yml"+ - "libs/cua-driver/rust/crates/cua-perception/**"+ - "libs/cua-driver/rust/**/Cargo.toml"+ - "libs/cua-driver/rust/Cargo.lock"+ - ".release-please-manifest.json"+ - "release-please-config.json"+ push:+ branches: [main]+ paths:+ - ".github/releases/**"+ - ".github/scripts/perception_release.py"+ - ".github/scripts/verify_cua_driver_release_archives.py"+ - ".github/scripts/tests/test_cua_driver_default_distribution.py"+ - ".github/scripts/tests/test_verify_cua_driver_release_archives.py"+ - ".github/workflows/cd-cua-perception-candidate.yml"+ - ".github/workflows/cd-rust-cua-driver.yml"+ - ".github/workflows/ci-cua-perception-release.yml"+ - "libs/cua-driver/rust/crates/cua-perception/**"+ - "libs/cua-driver/rust/**/Cargo.toml"+ - "libs/cua-driver/rust/Cargo.lock"+ - ".release-please-manifest.json"+ - "release-please-config.json"++permissions:+ contents: read++jobs:+ crate:+ name: crate (${{ matrix.target }})+ strategy:+ fail-fast: false+ matrix:+ include:+ - target: linux-x64+ os: ubuntu-latest+ - target: macos-x64+ os: macos-15-intel+ - target: windows-x64+ os: windows-latest+ runs-on: ${{ matrix.os }}+ steps:+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683+ with:+ persist-credentials: false+ - name: Compile and test Cua Perception+ working-directory: libs/cua-driver/rust+ run: cargo test --locked -p cua-perception++ contract:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683+ with:+ persist-credentials: false+ - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065+ with:+ python-version: "3.11"+ - name: Install validators+ run: python -m pip install --disable-pip-version-check --require-hashes -r .github/releases/cua-perception/test-requirements.lock+ - name: Validate registry and focused release tests+ run: |+ python3 .github/scripts/release_channels.py validate+ python3 libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/generate.py --check+ python3 -m pytest \+ .github/scripts/tests/test_cua_driver_default_distribution.py \+ .github/scripts/tests/test_cua_perception_release_topology.py \+ .github/scripts/tests/test_verify_cua_driver_release_archives.py \+ .github/scripts/tests/test_release_channels.py \+ .github/scripts/tests/test_resolve_release_please_request.py \+ .github/scripts/tests/test_merge_release_please_manifests.py \+ libs/cua-driver/rust/crates/cua-perception/scripts/tests/test_measure_quality.py \+ libs/cua-driver/rust/crates/cua-perception/scripts/tests/test_quality_runner.py+ - name: Prove Driver dependency graph excludes Perception+ working-directory: libs/cua-driver/rust+ run: |+ set -euo pipefail+ if cargo tree --locked -p cua-driver --edges normal,build --prefix none | \+ grep -q '^cua-perception v'; then+ echo "::error::Default Cua Driver dependency graph includes cua-perception"+ exit 1+ fidiff --git a/.github/workflows/ci-release-metadata.yml b/.github/workflows/ci-release-metadata.ymlindex 2eb49159b2..a87922a4c9 100644--- a/.github/workflows/ci-release-metadata.yml+++ b/.github/workflows/ci-release-metadata.yml@@ -47,19 +47,32 @@ jobs:run: |set -euo pipefailPRODUCT_CHANGED=false- while IFS= read -r path; do+ COMPANION_CHANGED=false+ mapfile -t CHANGED_PATHS < <(git diff --name-only "$BASE_SHA...$HEAD_SHA")+ CLASSIFY_ARGS=(classify-perception-diff)+ for path in "${CHANGED_PATHS[@]}"; do+ CLASSIFY_ARGS+=(--path "$path")case "$path" in+ libs/cua-driver/rust/crates/cua-perception/*|.github/releases/cua-perception/*)+ PRODUCT_CHANGED=true+ ;;libs/lume/*|libs/python/cua-sandbox/*)PRODUCT_CHANGED=true;;- libs/cua-driver/docs/*|libs/cua-driver/python/*|libs/cua-driver/tests/*)+ libs/cua-driver/docs/*|libs/cua-driver/examples/*|libs/cua-driver/python/*|libs/cua-driver/tests/*)+ ;;+ libs/cua-driver/rust/Cargo.toml|libs/cua-driver/rust/Cargo.lock)+ PRODUCT_CHANGED=true+ COMPANION_CHANGED=true;;libs/cua-driver/*)PRODUCT_CHANGED=true;;esac- done < <(git diff --name-only "$BASE_SHA...$HEAD_SHA")+ done+ PERCEPTION_ONLY=$(python3 .github/scripts/release_attribution.py "${CLASSIFY_ARGS[@]}")echo "product_changed=$PRODUCT_CHANGED" >> "$GITHUB_OUTPUT"+ echo "perception_companion_only=$([[ "$PERCEPTION_ONLY" == true && "$COMPANION_CHANGED" == true ]] && echo true || echo false)" >> "$GITHUB_OUTPUT"- name: Validate squash-release titleif: steps.scope.outputs.product_changed == 'true'@@ -67,11 +80,20 @@ jobs:HEAD_REF: ${{ github.event.pull_request.head.ref }}HEAD_REPOSITORY: ${{ github.event.pull_request.head.repo.full_name }}PR_LABELS: ${{ toJSON(github.event.pull_request.labels.*.name) }}+ PR_BODY: ${{ github.event.pull_request.body }}PR_TITLE: ${{ github.event.pull_request.title }}+ PERCEPTION_COMPANION_ONLY: ${{ steps.scope.outputs.perception_companion_only }}REPOSITORY: ${{ github.repository }}run: |set -euo pipefail- ARGS=(validate-title --title "$PR_TITLE" --require-release)+ ARGS=(+ validate-title+ --title "$PR_TITLE"+ --require-release+ )+ if [[ "$PERCEPTION_COMPANION_ONLY" == "true" ]]; then+ ARGS+=(--forbid-any-releasing-title --pull-body "$PR_BODY")+ fiif jq -e 'index("no-release") != null' <<<"$PR_LABELS" >/dev/null; thenARGS+=(--allow-non-release)fi@@ -96,6 +118,21 @@ jobs:run: |set -euo pipefailCHANGED=$(git diff --name-only "$BASE_SHA...$HEAD_SHA")+ if grep -qx 'libs/cua-driver/rust/crates/cua-perception/VERSION' <<<"$CHANGED"; then+ VERSION=$(tr -d '[:space:]' < libs/cua-driver/rust/crates/cua-perception/VERSION)+ python3 .github/scripts/release_attribution.py collect \+ --repository "${{ github.repository }}" \+ --product cua-perception \+ --display-name "Cua Perception" \+ --version "$VERSION" \+ --tag "cua-perception-v$VERSION" \+ --tag-prefix cua-perception-v \+ --ref "$HEAD_SHA" \+ --sha "$HEAD_SHA" \+ --path libs/cua-driver/rust/crates/cua-perception \+ --changelog libs/cua-driver/rust/crates/cua-perception/CHANGELOG.md \+ --output /tmp/cua-perception-release-manifest.json+ fiif grep -qx 'libs/cua-driver/rust/VERSION' <<<"$CHANGED"; thenVERSION=$(tr -d '[:space:]' < libs/cua-driver/rust/VERSION)python3 .github/scripts/release_attribution.py collect \@@ -109,8 +146,13 @@ jobs:--sha "$HEAD_SHA" \--path libs/cua-driver \--exclude-path libs/cua-driver/docs \+ --exclude-path libs/cua-driver/examples \--exclude-path libs/cua-driver/python \--exclude-path libs/cua-driver/tests \+ --exclude-path libs/cua-driver/rust/crates/cua-perception \+ --exclude-path libs/cua-driver/experiments/cua-perception-inference \+ --exclude-companion-path libs/cua-driver/rust/Cargo.toml \+ --exclude-companion-path libs/cua-driver/rust/Cargo.lock \--changelog libs/cua-driver/rust/CHANGELOG.md \--output /tmp/cua-driver-release-manifest.jsonfidiff --git a/.github/workflows/ci-rust-windows.yml b/.github/workflows/ci-rust-windows.ymlindex 1da21532f8..53009e10a2 100644--- a/.github/workflows/ci-rust-windows.yml+++ b/.github/workflows/ci-rust-windows.yml@@ -72,6 +72,24 @@ jobs:- name: Run complete desktop-independent core testsworking-directory: libs/cua-driver/rustrun: cargo test -p cua-driver-core --lib --test recording_shutdown_errors --locked+ - name: Run extension manager security regressions+ working-directory: libs/cua-driver/rust+ run: |+ $tests = @(+ "extension_manager::tests::hardens_a_precreated_extension_root_with_a_broad_acl",+ "extension_manager::tests::acl_hardening_reopens_directory_and_file_handles",+ "extension_manager::tests::recursive_acl_hardening_removes_package_access_from_staged_tree",+ "extension_manager::tests::recursive_acl_hardening_reasserts_root_after_descendant_walk",+ "extension_manager::tests::staged_install_verification_survives_acl_drift_during_recursive_hardening",+ "extension_manager::tests::post_hook_acl_grant_is_removed_before_staged_version_is_placed",+ "extension_manager::tests::health_hook_acl_grant_is_removed_before_status_returns_healthy",+ "extension_manager::tests::acl_identity_check_rejects_a_different_object",+ "extension_manager::tests::rejects_windows_junctions_and_broad_acl_entries"+ )+ foreach ($test in $tests) {+ cargo test -p cua-driver --bin cua-driver $test --locked -- --exact+ if ($LASTEXITCODE -ne 0) { throw "Extension manager security regression $test failed with exit $LASTEXITCODE" }+ }- name: Run deferred text publication regressionsworking-directory: libs/cua-driver/rustrun: |diff --git a/.github/workflows/ci-test-scripts.yml b/.github/workflows/ci-test-scripts.ymlindex cb5e970283..1108e350d6 100644--- a/.github/workflows/ci-test-scripts.yml+++ b/.github/workflows/ci-test-scripts.yml@@ -37,6 +37,11 @@ on:- ".github/workflows/periodic-cua-sandbox-live.yml"- ".github/workflows/ci-contributor-attribution.yml"- ".github/workflows/e2e-rust-macos.yml"+ - ".github/workflows/e2e-rust-linux.yml"+ - ".github/workflows/e2e-rust-windows.yml"+ - ".github/workflows/cd-cua-perception-review-supplied-inputs.yml"+ - ".github/workflows/authorized-live-jev-use-demo.yml"+ - ".github/workflows/review-cua-perception-candidates.yml"- "docs/release-backfill-runbook.md"- "libs/cua-driver/scripts/**"- "libs/cua-driver/tests/fixtures/apps/cross-platform/electron/build.sh"@@ -44,6 +49,7 @@ on:- "libs/cua-driver/tests/fixtures/apps/cross-platform/tauri/build.sh"- "libs/cua-driver/tests/runners/macos-lume/**"- "scripts/ci/macos/**"+ - "libs/cua-driver/tests/perception-demo/**"jobs:windows-uninstall:@@ -88,7 +94,7 @@ jobs:with:node-version: "22"- - name: Preview Sandbox releases offline+ - name: Preview component release behavior offlineenv:NPM_CONFIG_IGNORE_SCRIPTS: "true"run: |@@ -99,6 +105,8 @@ jobs:--ignore-scripts --no-audit --no-fund [email protected]NODE_PATH="$RUNNER_TEMP/sandbox-release-preview/node_modules" \node .github/scripts/tests/release_please_sandbox_preview.cjs+ NODE_PATH="$RUNNER_TEMP/sandbox-release-preview/node_modules" \+ node .github/scripts/tests/release_please_perception_preview.cjs- name: Validate historical release backfillrun: python3 .github/scripts/release_backfill.py validatediff --git a/.github/workflows/e2e-rust-linux.yml b/.github/workflows/e2e-rust-linux.ymlindex 20c0581c24..2e35310ede 100644--- a/.github/workflows/e2e-rust-linux.yml+++ b/.github/workflows/e2e-rust-linux.yml@@ -314,3 +314,67 @@ jobs:name: rust-linux-matrix-summarypath: matrix-summary.mdif-no-files-found: error++ certify:+ # success() requires every job this one depends on to have succeeded;+ # combined with the lane=='all' check this keeps certification fail-closed+ # against both lane failures and diagnostic-lane dispatches.+ if: success() && github.event_name == 'workflow_dispatch' && inputs.lane == 'all'+ needs: [source, shared, native, capture, installer]+ name: "Linux / canonical certification"+ runs-on: ubuntu-latest+ timeout-minutes: 10+ steps:+ - name: Emit canonical certification record+ shell: bash+ env:+ CUA_E2E_REQUESTED_REF: ${{ inputs.ref }}+ CUA_E2E_SOURCE_SHA: ${{ needs.source.outputs.sha }}+ CUA_E2E_HEAD_SHA: ${{ github.sha }}+ run: |+ set -euo pipefail+ certified_at="$(date -u +%Y-%m-%dT%H:%M:%SZ)"+ jq -n \+ --arg schema "cua-driver/e2e-certification/v1" \+ --arg repository "$GITHUB_REPOSITORY" \+ --arg workflow "$GITHUB_WORKFLOW" \+ --arg workflow_ref "$GITHUB_WORKFLOW_REF" \+ --arg run_id "$GITHUB_RUN_ID" \+ --arg run_attempt "$GITHUB_RUN_ATTEMPT" \+ --arg event_name "$GITHUB_EVENT_NAME" \+ --arg platform "linux" \+ --arg lane "all" \+ --argjson canonical true \+ --arg requested_ref "$CUA_E2E_REQUESTED_REF" \+ --arg source_sha "$CUA_E2E_SOURCE_SHA" \+ --arg head_sha "$CUA_E2E_HEAD_SHA" \+ --arg certified_at "$certified_at" \+ '{+ schema: $schema,+ repository: $repository,+ workflow: $workflow,+ workflow_ref: $workflow_ref,+ run_id: $run_id,+ run_attempt: $run_attempt,+ event_name: $event_name,+ platform: $platform,+ lane: $lane,+ canonical: $canonical,+ requested_ref: $requested_ref,+ source_sha: $source_sha,+ head_sha: $head_sha,+ required_jobs: {+ shared: "success",+ native: "success",+ capture: "success",+ installer: "success"+ },+ certified_at: $certified_at+ }' | tee certification.json+ - name: Upload canonical certification+ uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4+ with:+ name: rust-linux-e2e-certification+ path: certification.json+ if-no-files-found: error+ retention-days: 90diff --git a/.github/workflows/e2e-rust-macos.yml b/.github/workflows/e2e-rust-macos.ymlindex f1e975a73d..db84a09bd2 100644--- a/.github/workflows/e2e-rust-macos.yml+++ b/.github/workflows/e2e-rust-macos.yml@@ -7,9 +7,31 @@ on:description: "Full 40-character commit SHA to certify"required: truetype: string+ mode:+ description: "Supplemental GitHub-hosted matrix or registration of a direct Lume console run"+ required: false+ type: choice+ default: hosted+ options:+ - hosted+ - lume+ direct_lume_run_id:+ description: "Run ID printed by the direct Lume console harness (required for mode=lume)"+ required: false+ type: string+ direct_lume_evidence_sha256:+ description: "SHA-256 of the private direct Lume evidence bundle (required for mode=lume)"+ required: false+ type: string+ direct_lume_result_base64:+ description: "Base64-encoded direct-result.json from the Lume harness (required for mode=lume)"+ required: false+ type: stringpermissions:+ actions: readcontents: read+ pull-requests: readconcurrency:group: e2e-rust-macos-hosted-${{ inputs.source_sha }}@@ -17,6 +39,7 @@ concurrency:jobs:probe:+ if: inputs.mode == 'hosted'name: hosted environment proberuns-on: macos-26timeout-minutes: 20@@ -85,6 +108,7 @@ jobs:retention-days: 14matrix:+ if: inputs.mode == 'hosted'needs: probename: hosted ${{ matrix.lane }} laneruns-on: macos-26@@ -164,7 +188,7 @@ jobs:retention-days: 14certify:- if: always()+ if: ${{ always() && inputs.mode == 'hosted' }}needs: [probe, matrix]name: hosted certification resultruns-on: ubuntu-latest@@ -205,3 +229,83 @@ jobs:path: certification.jsonif-no-files-found: errorretention-days: 14++ register-lume:+ if: inputs.mode == 'lume'+ name: Register direct Lume certification+ runs-on: ubuntu-latest+ environment: authorized-live-jev-use-demo+ timeout-minutes: 10+ env:+ CUA_E2E_SOURCE_SHA: ${{ inputs.source_sha }}+ CUA_E2E_WORKFLOW_SHA: ${{ github.sha }}+ DIRECT_LUME_RUN_ID: ${{ inputs.direct_lume_run_id }}+ DIRECT_LUME_EVIDENCE_SHA256: ${{ inputs.direct_lume_evidence_sha256 }}+ DIRECT_LUME_RESULT_BASE64: ${{ inputs.direct_lume_result_base64 }}+ steps:+ - name: Register the exact direct Lume console result+ shell: bash+ run: |+ set -euo pipefail+ if [[ ! "${CUA_E2E_SOURCE_SHA}" =~ ^[0-9a-fA-F]{40}$ ]]; then+ echo "source_sha must be a full 40-character commit SHA" >&2+ exit 2+ fi+ source_sha_lower="$(printf '%s' "${CUA_E2E_SOURCE_SHA}" | tr '[:upper:]' '[:lower:]')"+ workflow_sha_lower="$(printf '%s' "${CUA_E2E_WORKFLOW_SHA}" | tr '[:upper:]' '[:lower:]')"+ if [[ "${source_sha_lower}" != "${workflow_sha_lower}" ]]; then+ echo "source_sha must match the selected workflow ref tip (${CUA_E2E_WORKFLOW_SHA})" >&2+ exit 2+ fi+ [[ "$DIRECT_LUME_RUN_ID" =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$ ]] || {+ echo "direct_lume_run_id is missing or invalid" >&2+ exit 2+ }+ [[ "$DIRECT_LUME_EVIDENCE_SHA256" =~ ^[0-9a-f]{64}$ ]] || {+ echo "direct_lume_evidence_sha256 must be a lowercase SHA-256 digest" >&2+ exit 2+ }+ [[ -n "$DIRECT_LUME_RESULT_BASE64" ]] || {+ echo "direct_lume_result_base64 is required" >&2+ exit 2+ }+ printf '%s' "$DIRECT_LUME_RESULT_BASE64" | base64 --decode > direct-result.json+ jq -e \+ --arg source_sha "$source_sha_lower" \+ --arg run_id "$DIRECT_LUME_RUN_ID" \+ '.schema == "cua-driver/macos-lume-direct-result@v1"+ and .source_sha == $source_sha+ and .run_id == $run_id+ and .standalone_browser == true+ and .passed == true' direct-result.json >/dev/null+ jq -n \+ --arg schema "cua-driver/macos-lume-certification@v2" \+ --arg source_sha "${CUA_E2E_SOURCE_SHA}" \+ --arg run_id "${GITHUB_RUN_ID}" \+ --arg run_attempt "${GITHUB_RUN_ATTEMPT}" \+ --arg repository "${GITHUB_REPOSITORY}" \+ --arg workflow_path ".github/workflows/e2e-rust-macos.yml" \+ --arg workflow_ref "${GITHUB_WORKFLOW_REF}" \+ --arg workflow_sha "${CUA_E2E_WORKFLOW_SHA}" \+ --arg event "${GITHUB_EVENT_NAME}" \+ --arg direct_run_id "${DIRECT_LUME_RUN_ID}" \+ --arg evidence_sha256 "${DIRECT_LUME_EVIDENCE_SHA256}" \+ --slurpfile direct_result direct-result.json \+ '{schema: $schema, source_sha: $source_sha,+ github: {repository: $repository, run_id: $run_id, run_attempt: $run_attempt,+ workflow_path: $workflow_path, workflow_ref: $workflow_ref, workflow_sha: $workflow_sha,+ event: $event},+ execution: {kind: "direct-lume-console", run_id: $direct_run_id,+ evidence_sha256: $evidence_sha256, result: $direct_result[0]},+ passed: true}' \+ | tee certification.json+ jq -e '.passed == true' certification.json >/dev/null++ - name: Upload certification result+ if: always()+ uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4.6.2+ with:+ name: rust-macos-lume-certification-${{ github.run_id }}-${{ github.run_attempt }}+ path: certification.json+ if-no-files-found: error+ retention-days: 14diff --git a/.github/workflows/e2e-rust-windows.yml b/.github/workflows/e2e-rust-windows.ymlindex dfa9c445f4..d36783af1e 100644--- a/.github/workflows/e2e-rust-windows.yml+++ b/.github/workflows/e2e-rust-windows.yml@@ -285,11 +285,14 @@ jobs:shell: bashenv:GH_TOKEN: ${{ github.token }}+ SOURCE_SHA: ${{ needs.source.outputs.sha }}run: |summary_path=matrix-summary.md{echo "# CUA Rust Windows E2E matrix"echo+ echo "Source commit: \`$SOURCE_SHA\`"+ echoecho "The lane jobs above are independent; a failure in one lane does not hide the others."echo} > "$summary_path"@@ -310,6 +313,59 @@ jobs:fiecho >> "$summary_path"done < <(find artifacts -type f -name summary.md -print | sort)++ while IFS= read -r results; do+ artifact_dir=$(dirname "$results")+ if [[ -f "$artifact_dir/summary.md" ]]; then+ continue+ fi+ found=1+ artifact=$(basename "$artifact_dir")+ artifact_id=$(jq -r --arg name "$artifact" \+ '.artifacts[] | select(.name == $name) | .id' <<< "$artifacts_json" | head -n 1)+ if [[ -n "$artifact_id" && "$artifact_id" != "null" ]]; then+ artifact_url="$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID/artifacts/$artifact_id"+ artifact_link="[Download $artifact]($artifact_url)"+ else+ artifact_url=""+ artifact_link="Artifact link unavailable"+ fi++ echo "## $artifact" >> "$summary_path"+ echo >> "$summary_path"+ echo "The lane did not produce \`summary.md\`. Results recovered from \`results.jsonl\`: $artifact_link." >> "$summary_path"+ echo >> "$summary_path"+ result_count=$(jq -s 'length' "$results")+ pass_count=$(jq -s '[.[] | select(.test_status == "pass")] | length' "$results")+ fail_count=$(jq -s '[.[] | select(.test_status == "fail")] | length' "$results")+ other_count=$((result_count - pass_count - fail_count))+ echo "Records: $result_count; pass: $pass_count; fail: $fail_count; other: $other_count." >> "$summary_path"+ if ((result_count == 0)); then+ echo >> "$summary_path"+ echo "No behavioral result records were written before the lane stopped." >> "$summary_path"+ elif ((fail_count + other_count > 0)); then+ {+ echo+ echo "| Non-passing cell | Status | Observed | Message | Evidence |"+ echo "| --- | --- | --- | --- | --- |"+ } >> "$summary_path"+ while IFS=$'\t' read -r cell status observed message evidence; do+ cell=${cell//|/\\|}+ status=${status//|/\\|}+ observed=${observed//|/\\|}+ message=${message//|/\\|}+ evidence=${evidence//|/\\|}+ if [[ -n "$artifact_url" && "$evidence" != "-" ]]; then+ evidence="[$evidence]($artifact_url)"+ fi+ echo "| $cell | $status | $observed | $message | $evidence |" >> "$summary_path"+ done < <(jq -r 'select(.test_status != "pass") | [.cell_id // "(missing cell_id)", .test_status // "unknown", .observed_behavior // "unknown", ((.message // "-") | if . == "" then "-" else . end), (.evidence.video // "-")] | @tsv' "$results")+ else+ echo >> "$summary_path"+ echo "All recovered behavioral records passed; the lane failed before its Markdown report was produced." >> "$summary_path"+ fi+ echo >> "$summary_path"+ done < <(find artifacts -type f -name results.jsonl -print | sort)if [[ "$found" == 0 ]]; thenecho "No lane summary artifact was produced." >> "$summary_path"fi@@ -356,3 +412,92 @@ jobs:name: rust-windows-matrix-summarypath: matrix-summary.mdif-no-files-found: error++ certify:+ # success() requires every job this one depends on to have succeeded;+ # combined with the lane=='all' check this keeps certification fail-closed+ # against both lane failures and diagnostic-lane dispatches. The runner+ # policy check below additionally refuses to certify an Azure RDP parity+ # replay: per scripts/ci/README.md that replay is not itself a source of+ # behavioral truth, only the GitHub-hosted preflighted-interactive lane is.+ if: success() && github.event_name == 'workflow_dispatch' && inputs.lane == 'all'+ needs: [source, shared, native, capture, installer]+ name: "Windows / canonical certification"+ runs-on: ubuntu-latest+ timeout-minutes: 10+ steps:+ - name: Determine approved runner policy class+ id: runner_policy+ shell: bash+ env:+ CUA_E2E_RUNNER_INPUT: ${{ inputs.runner }}+ run: |+ set -euo pipefail+ case "$CUA_E2E_RUNNER_INPUT" in+ windows-latest|windows-2022|windows-2025)+ echo "class=github-hosted" >> "$GITHUB_OUTPUT"+ ;;+ *)+ echo "Runner '$CUA_E2E_RUNNER_INPUT' is not on the approved canonical runner policy (github-hosted: windows-latest, windows-2022, windows-2025); an Azure RDP parity replay is not certifiable evidence, refusing to certify." >&2+ exit 1+ ;;+ esac+ - name: Emit canonical certification record+ shell: bash+ env:+ CUA_E2E_REQUESTED_REF: ${{ inputs.ref }}+ CUA_E2E_SOURCE_SHA: ${{ needs.source.outputs.sha }}+ CUA_E2E_HEAD_SHA: ${{ github.sha }}+ CUA_E2E_RUNNER_INPUT: ${{ inputs.runner }}+ CUA_E2E_RUNNER_POLICY_CLASS: ${{ steps.runner_policy.outputs.class }}+ run: |+ set -euo pipefail+ certified_at="$(date -u +%Y-%m-%dT%H:%M:%SZ)"+ jq -n \+ --arg schema "cua-driver/e2e-certification/v1" \+ --arg repository "$GITHUB_REPOSITORY" \+ --arg workflow "$GITHUB_WORKFLOW" \+ --arg workflow_ref "$GITHUB_WORKFLOW_REF" \+ --arg run_id "$GITHUB_RUN_ID" \+ --arg run_attempt "$GITHUB_RUN_ATTEMPT" \+ --arg event_name "$GITHUB_EVENT_NAME" \+ --arg platform "windows" \+ --arg lane "all" \+ --argjson canonical true \+ --arg requested_ref "$CUA_E2E_REQUESTED_REF" \+ --arg source_sha "$CUA_E2E_SOURCE_SHA" \+ --arg head_sha "$CUA_E2E_HEAD_SHA" \+ --arg runner_input "$CUA_E2E_RUNNER_INPUT" \+ --arg runner_policy_class "$CUA_E2E_RUNNER_POLICY_CLASS" \+ --arg certified_at "$certified_at" \+ '{+ schema: $schema,+ repository: $repository,+ workflow: $workflow,+ workflow_ref: $workflow_ref,+ run_id: $run_id,+ run_attempt: $run_attempt,+ event_name: $event_name,+ platform: $platform,+ lane: $lane,+ canonical: $canonical,+ requested_ref: $requested_ref,+ source_sha: $source_sha,+ head_sha: $head_sha,+ runner_input: $runner_input,+ runner_policy_class: $runner_policy_class,+ required_jobs: {+ shared: "success",+ native: "success",+ capture: "success",+ installer: "success"+ },+ certified_at: $certified_at+ }' | tee certification.json+ - name: Upload canonical certification+ uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4+ with:+ name: rust-windows-e2e-certification+ path: certification.json+ if-no-files-found: error+ retention-days: 90diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.ymlindex ef9e6ea9cd..14b174835b 100644--- a/.github/workflows/release-please.yml+++ b/.github/workflows/release-please.yml@@ -13,6 +13,7 @@ on:default: automaticoptions:- automatic+ - cua-perception- cua-driver-rs- lume- sandbox@@ -59,7 +60,7 @@ jobs:inputs.component == 'automatic' &&inputs.bump != 'automatic'run: |- echo "::error::Select cua-driver-rs, lume, or sandbox when forcing a bump type."+ echo "::error::Select cua-perception, cua-driver-rs, lume, or sandbox when forcing a bump type."exit 1- name: Reject manifest tags outside main history@@ -79,6 +80,94 @@ jobs:echo "current_version=$(jq -r .current_version <<<"$REQUEST")" >> "$GITHUB_OUTPUT"echo "release_as=$(jq -r '.release_as // ""' <<<"$REQUEST")" >> "$GITHUB_OUTPUT"+ - name: Anchor a merged Perception version with a lightweight tag+ if: github.event_name == 'push' && github.ref == 'refs/heads/main'+ env:+ GH_TOKEN: ${{ steps.app-token.outputs.token }}+ BEFORE_SHA: ${{ github.event.before }}+ VERSION_PATH: libs/cua-driver/rust/crates/cua-perception/VERSION+ run: |+ set -euo pipefail+ git checkout --detach "$GITHUB_SHA"++ if [[ "$BEFORE_SHA" =~ ^0+$ ]]; then+ echo "Skipping Perception tag creation for the initial branch push"+ exit 0+ fi+ if ! git merge-base --is-ancestor "$BEFORE_SHA" "$GITHUB_SHA"; then+ echo "::error::Refusing to create a release tag for a non-fast-forward main push"+ exit 1+ fi+ BEFORE_VERSION=$(git show "$BEFORE_SHA:$VERSION_PATH" 2>/dev/null | tr -d '[:space:]' || true)+ VERSION=$(tr -d '[:space:]' < "$VERSION_PATH")+ if [[ "$BEFORE_VERSION" == "$VERSION" ]]; then+ echo "Perception version did not change in this main push"+ exit 0+ fi++ python3 .github/scripts/validate_release_versions.py --product perception+ if [[ ! "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then+ echo "::error::Refusing to tag invalid Perception version: $VERSION"+ exit 1+ fi+ if [[ -n "$BEFORE_VERSION" ]]; then+ python3 - "$BEFORE_VERSION" "$VERSION" <<'PY'+ import re+ import sys++ semver = re.compile(r"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$")+ previous, current = sys.argv[1:]+ previous_match = semver.fullmatch(previous)+ current_match = semver.fullmatch(current)+ if not previous_match or not current_match:+ raise SystemExit("Perception versions must be stable SemVer")+ if tuple(map(int, current_match.groups())) <= tuple(map(int, previous_match.groups())):+ raise SystemExit(+ f"Perception version must increase: previous={previous}, current={current}"+ )+ PY+ fi+ git fetch origin "+refs/heads/main:refs/remotes/origin/main"+ if ! git merge-base --is-ancestor "$GITHUB_SHA" origin/main; then+ echo "::error::Refusing to tag a commit outside main"+ exit 1+ fi++ TAG="cua-perception-v$VERSION"+ read_remote_tag() {+ gh api "repos/$GITHUB_REPOSITORY/git/ref/tags/$TAG" \+ --jq '[.object.type, .object.sha] | @tsv' 2>/dev/null || true+ }+ require_exact_lightweight_tag() {+ local tag_record="$1"+ local tag_type tag_sha+ IFS=$'\t' read -r tag_type tag_sha <<<"$tag_record"+ if [[ "$tag_type" != "commit" || "$tag_sha" != "$GITHUB_SHA" ]]; then+ echo "::error::$TAG already exists but is not a lightweight tag at $GITHUB_SHA"+ exit 1+ fi+ }++ EXISTING=$(read_remote_tag)+ if [[ -n "$EXISTING" ]]; then+ require_exact_lightweight_tag "$EXISTING"+ echo "$TAG already points to the merged Perception version"+ exit 0+ fi++ if ! gh api --method POST "repos/$GITHUB_REPOSITORY/git/refs" \+ -f ref="refs/tags/$TAG" \+ -f sha="$GITHUB_SHA" >/dev/null; then+ # A concurrent run may have created the same immutable anchor.+ EXISTING=$(read_remote_tag)+ if [[ -z "$EXISTING" ]]; then+ echo "::error::Failed to create $TAG"+ exit 1+ fi+ require_exact_lightweight_tag "$EXISTING"+ fi+ require_exact_lightweight_tag "$(read_remote_tag)"+# release-please-action v4.4.1, embedding release-please 17.3.0.- name: Open or update automatic release pull requestsid: release-auto@@ -132,11 +221,13 @@ jobs:PR=$(gh pr view "$number" --json headRefName,headRepositoryOwner,files)DRIVER=$(echo "$PR" | jq -r \'.files | any(.path == "libs/cua-driver/rust/VERSION")')+ PERCEPTION=$(echo "$PR" | jq -r \+ '.files | any(.path == "libs/cua-driver/rust/crates/cua-perception/VERSION")')LUME=$(echo "$PR" | jq -r \'.files | any(.path == "libs/lume/VERSION")')SANDBOX=$(echo "$PR" | jq -r \'.files | any(.path == "libs/python/cua-sandbox/VERSION")')- if [[ "$DRIVER" != "true" && "$LUME" != "true" && "$SANDBOX" != "true" ]]; then+ if [[ "$DRIVER" != "true" && "$PERCEPTION" != "true" && "$LUME" != "true" && "$SANDBOX" != "true" ]]; thencontinuefi@@ -176,6 +267,9 @@ jobs:if [[ "$DRIVER" == "true" ]]; thenCOMPONENT_ARGS+=(--component cua-driver-rs)fi+ if [[ "$PERCEPTION" == "true" ]]; then+ COMPONENT_ARGS+=(--component cua-perception)+ fiif [[ "$LUME" == "true" ]]; thenCOMPONENT_ARGS+=(--component lume)fi@@ -194,7 +288,15 @@ jobs:exit 1fifi- if [[ "$DRIVER" == "true" ]]; then+ if [[ "$PERCEPTION" == "true" ]]; then+ PERCEPTION_VERSION=$(tr -d '[:space:]' < \+ libs/cua-driver/rust/crates/cua-perception/VERSION)+ cargo update --manifest-path libs/cua-driver/rust/Cargo.toml \+ -p cua-perception --precise "$PERCEPTION_VERSION"+ python3 .github/scripts/validate_release_versions.py --product perception+ git add libs/cua-driver/rust/Cargo.lock+ COMMIT_MESSAGE="chore(cua-perception): synchronize release lockfile"+ elif [[ "$DRIVER" == "true" ]]; thenDRIVER_VERSION=$(tr -d '[:space:]' < libs/cua-driver/rust/VERSION)cargo update --manifest-path libs/cua-driver/rust/Cargo.toml \-p cua-driver --precise "$DRIVER_VERSION"diff --git a/.github/workflows/review-cua-perception-candidates.yml b/.github/workflows/review-cua-perception-candidates.ymlnew file mode 100644index 0000000000..2e8060649a--- /dev/null+++ b/.github/workflows/review-cua-perception-candidates.yml@@ -0,0 +1,74 @@+name: "Review: labeled Cua Perception candidates"++on:+ pull_request:+ types: [labeled]++permissions:+ actions: read+ contents: read+ pull-requests: read++concurrency:+ group: cua-perception-live-review-${{ github.event.pull_request.number }}+ cancel-in-progress: true++jobs:+ resolve:+ name: Require the labeled same-repository review heads+ if: >-+ github.event_name == 'pull_request' &&+ github.event.pull_request.head.repo.full_name == github.repository &&+ github.event.pull_request.state == 'open' &&+ github.event.action == 'labeled' &&+ github.event.label.name == 'cua-perception-live-review'+ runs-on: ubuntu-latest+ outputs:+ source_pr_number: ${{ steps.resolve.outputs.source_pr_number }}+ source_sha: ${{ steps.resolve.outputs.source_sha }}+ catalog_version: ${{ steps.resolve.outputs.catalog_version }}+ expires_unix: ${{ steps.resolve.outputs.expires_unix }}+ steps:+ - id: resolve+ name: Revalidate current head and label+ shell: bash+ env:+ GH_TOKEN: ${{ github.token }}+ EVENT_ACTION: ${{ github.event.action }}+ EVENT_HEAD_REPOSITORY: ${{ github.event.pull_request.head.repo.full_name }}+ EVENT_HEAD_SHA: ${{ github.event.pull_request.head.sha }}+ EVENT_LABEL: ${{ github.event.label.name }}+ EVENT_PR_NUMBER: ${{ github.event.pull_request.number }}+ run: |+ set -euo pipefail+ [[ "$GITHUB_REPOSITORY" == "trycua/cua" ]]+ [[ "$EVENT_PR_NUMBER" =~ ^[1-9][0-9]*$ ]]+ [[ "$EVENT_HEAD_REPOSITORY" == "$GITHUB_REPOSITORY" ]]+ [[ "$EVENT_HEAD_SHA" =~ ^[0-9a-f]{40}$ ]]+ [[ "$EVENT_ACTION" == "labeled" ]]+ [[ "$EVENT_LABEL" == "cua-perception-live-review" ]]++ pr_json="$(gh api "repos/$GITHUB_REPOSITORY/pulls/$EVENT_PR_NUMBER")"+ [[ "$(jq -r .state <<<"$pr_json")" == "open" ]]+ [[ "$(jq -r .head.repo.full_name <<<"$pr_json")" == "$GITHUB_REPOSITORY" ]]+ [[ "$(jq -r .head.sha <<<"$pr_json")" == "$EVENT_HEAD_SHA" ]]+ jq -e '.labels | any(.name == "cua-perception-live-review")' <<<"$pr_json" >/dev/null++ echo "source_pr_number=$EVENT_PR_NUMBER" >> "$GITHUB_OUTPUT"+ echo "source_sha=$EVENT_HEAD_SHA" >> "$GITHUB_OUTPUT"+ echo "catalog_version=$GITHUB_RUN_ID" >> "$GITHUB_OUTPUT"+ echo "expires_unix=$(( $(date +%s) + 604800 ))" >> "$GITHUB_OUTPUT"++ candidate:+ name: Build ephemeral signed review candidates+ needs: resolve+ permissions:+ actions: read+ contents: read+ pull-requests: read+ uses: ./.github/workflows/cd-cua-perception-review-supplied-inputs.yml+ with:+ source_pr_number: ${{ needs.resolve.outputs.source_pr_number }}+ source_sha: ${{ needs.resolve.outputs.source_sha }}+ catalog_version: ${{ needs.resolve.outputs.catalog_version }}+ expires_unix: ${{ needs.resolve.outputs.expires_unix }}diff --git a/.release-please-manifest.json b/.release-please-manifest.jsonindex 10340b7675..1d28947d16 100644--- a/.release-please-manifest.json+++ b/.release-please-manifest.json@@ -1,4 +1,5 @@{+ "libs/cua-driver/rust/crates/cua-perception": "0.1.0","libs/cua-driver": "0.28.2","libs/lume": "0.5.3","libs/python/cua-sandbox": "0.8.0"diff --git a/README.md b/README.mdindex 10a6dea81e..a952753f8d 100644--- a/README.md+++ b/README.md@@ -190,8 +190,19 @@ MIT License — see [LICENSE](LICENSE.md) for details.Third-party components have their own licenses:- [Kasm](libs/kasm/LICENSE) (MIT)-- [OmniParser](https://github.com/microsoft/OmniParser/blob/master/LICENSE) (CC-BY-4.0)-- Optional `cua-agent[omni]` includes ultralytics (AGPL-3.0)+- [`cua-som`](libs/python/som) is an optional package licensed under+ AGPL-3.0-or-later. Its Ultralytics dependency retains its own license; inspect+ the resolved dependency version and its notices before redistribution.+- The Microsoft OmniParser repository [states+ CC-BY-4.0](https://github.com/microsoft/OmniParser/blob/master/LICENSE) for its+ repository content. Model files downloaded from the separate OmniParser model+ repository are distinct artifacts; verify the terms published with the exact+ model revision before redistributing them.+- The optional `cua-perception` extension is installed separately from the MIT+ Cua Driver. Its reviewed candidate combines an AGPL-3.0-only OmniParser model+ artifact, Apache-2.0 PP-OCR model artifacts, and a separately packaged ONNX+ Runtime. See the [perception third-party notices](libs/cua-driver/docs/perception-third-party-notices.md)+ before using or redistributing an extension artifact.## Trademarksdiff --git a/docs/content/docs/how-to-guides/driver/meta.json b/docs/content/docs/how-to-guides/driver/meta.jsonindex ee2dc4609c..d87c0fdc84 100644--- a/docs/content/docs/how-to-guides/driver/meta.json+++ b/docs/content/docs/how-to-guides/driver/meta.json@@ -13,6 +13,8 @@"run-tests-in-macos-lume-vm","connect-your-agent","run-with-local-model",+ "parse-visual-regions",+ "use-jev-use-with-visual-regions","drive-a-web-page","record-and-render-a-trajectory","keep-running",diff --git a/docs/content/docs/how-to-guides/driver/parse-visual-regions.mdx b/docs/content/docs/how-to-guides/driver/parse-visual-regions.mdxnew file mode 100644index 0000000000..eec0139715--- /dev/null+++ b/docs/content/docs/how-to-guides/driver/parse-visual-regions.mdx@@ -0,0 +1,187 @@+---+title: 'Parse visual regions with Cua Driver'+description: 'Install the optional perception preview, parse one retained screenshot, take one bounded action, and reobserve.'+---++import { Callout } from 'fumadocs-ui/components/callout';++Use this workflow when a window contains useful text or icons but its+accessibility tree or typed browser state does not identify the target. Cua+Driver keeps capture and action authority; the optional perception extension+turns one retained screenshot into model-neutral regions.++<Callout type="warning" title="Developer preview">+ The `cua-perception` extension is separate from the default Cua Driver install. Verified-catalog+ publication and the exact initial OCR/model artifact are still pending release verification. This+ page does not identify an artifact URL or claim that a stable release is available.+</Callout>++## Before you start++Install Cua Driver and confirm that the exact build advertises both the+extension lifecycle and `parse_visual_regions`:++```bash+cua-driver --version+cua-driver extension list+cua-driver describe parse_visual_regions+```++The default local Driver remains MIT licensed and works without this extension.+The candidate records its OmniParser detector artifact as AGPL-3.0-only and its+PP-OCR detector and recognizer artifacts as Apache-2.0. The packaged CPU ONNX+Runtime must identify its exact version, hash, license, and notices. Inspect the+catalog, manifest, SBOM, model ledger, source ledger, and built artifact rather+than applying the Driver license to them. Publication remains blocked while the+OmniParser ledger says `license-review-required`; distribution and remote+service require the applicable notices, corresponding source and conversion+material, and AGPL network source path. See the repository's [perception+third-party notices](https://github.com/trycua/cua/blob/18259fc2ee5d37a133edd91f762057daf9d9f791/libs/cua-driver/docs/perception-third-party-notices.md).+Installing the preview does not add Python, and neither Driver nor the extension+requires a Jev credential.++## Inspect the extension++Use the catalog distributed with the reviewed release candidate, then read the+candidate metadata before changing local state:++```bash+cua-driver extension inspect cua-perception --catalog <catalog.json>+```++Check the exact version, platform target, capabilities, protocol range, worker+and model sizes, hashes, install destination, licenses, publisher, and+provenance. If authenticated metadata for the exact artifact is unavailable,+stop. Do not substitute an unsigned archive or infer availability from a+repository-wide release badge.++## Install explicitly++After reviewing the inspection output, install and verify local health:++```bash+cua-driver extension install cua-perception --catalog <catalog.json>+cua-driver extension status cua-perception+```++Installation is never triggered by capture, parsing, Driver startup, or an+update check. A parse on a default installation returns `not_installed`; it does+not download a worker or model.++## Capture a fresh target++Use one persistent MCP connection or one typed SDK runtime for capture, parse,+action, and reobservation. Do not split this loop across one-shot CLI tool+calls: each process owns a disposable runtime, and the next process cannot+resolve its `capture_id`.++Select the exact native window first, then capture it. The exact build's tool+description is authoritative for the result envelope:++```text+state = get_window_state({"pid":844,"window_id":10725})+```++Retain the returned `capture_id`, source target, screenshot dimensions, and+action-coordinate mapping together. A current accessibility `snapshot_id` is+not a visual `capture_id`.++Use `get_desktop_state` only when the workflow explicitly authorizes desktop+capture and a narrower window target cannot represent the task. If the preview+requires a native-resolution source and refuses a resized capture, follow the+returned error and the exact build's configuration description; do not rescale+regions yourself.++## Parse bounded regions++Request only the region kinds and count you need:++```text+regions = parse_visual_regions({+ "capture_id":"capture-from-current-observation",+ "options":{+ "kinds":["text","icon"],+ "min_confidence":0.5,+ "max_regions":100+ }+})+```++The result binds every region to the source capture and reports half-open+rectangles in the source PNG's pixel space: `[x, x + width)` by+`[y, y + height)`, with `(0, 0)` at the top left. The result is an observation,+not an action recommendation. OCR text, icon labels, confidence, grouping, and+interactive hints do not prove that a region accepts input.++## Construct one bounded action++Prefer a current accessibility element or typed browser ref when it identifies+the same control. When a pixel action is necessary:++1. Choose one region from the current parse result.+2. Confirm its capture ID, target, and screenshot dimensions match the retained+ observation.+3. Map a point inside its bounds through the returned action-coordinate mapping.+4. Construct one complete Driver `click` locally, including `x`, `y`, the exact+ target, delivery mode, and the same `capture_id`.+5. Dispatch at most one action derived from that capture.++Do not let a model or remote chooser invent a Driver tool name, arguments, or+coordinates. Do not remove `capture_id` and retry an expired, stale, retired,+or mismatched capture as an unbound coordinate click. Do not reuse the capture+for a second action.++Parsing a window does not make its pixel input background-safe. Driver applies+the platform's normal background route, and `background_unavailable` does not+authorize a foreground retry. `delivery_mode:"foreground"` and desktop input+may change focus, workspace, or the system cursor; use them only when the+workflow already authorizes foreground control.++## Reobserve and verify++Take a fresh observation after every action attempt, including a timeout,+unknown result, partial delivery, or suspected no-op. Verify the task's actual+postcondition from current accessibility, browser, application, or visual+state. A delivered click is not proof that the intended control changed.++Also reobserve after a resize, move, scroll, navigation, display-layout change,+or target-identity change. Never replay an action from stale regions.++## Recover from errors++| Error | Response |+| ------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |+| `not_installed` | Continue without the extension, or return to inspection before an explicit install. |+| `capture_not_found`, `capture_expired`, `capture_stale`, `capture_generation_mismatch` | Capture again and parse the new ID. |+| `unsupported_target`, `unsupported_platform` | Use accessibility, browser state, or caller-owned visual reasoning and preserve the limitation. |+| `incompatible_protocol`, `artifact_invalid` | Stop using the extension and inspect its installed version and provenance. |+| `worker_launch_failed`, `worker_crashed`, `worker_cancelled`, `timeout`, `inference_failed` | Do not act from a partial result; reobserve before a bounded retry or fallback. |+| `invalid_frame`, `resource_limit_exceeded` | Use a supported native-resolution capture or narrow the parse request. |++The worker receives only the admitted screenshot and bounded parse options. It+does not receive desktop capture, accessibility, browser, input,+credential-store, or action authority.++## Update or remove the preview++Inspect replacement metadata before updating:++```bash+cua-driver extension inspect cua-perception --catalog <catalog.json>+cua-driver extension update cua-perception --catalog <catalog.json>+cua-driver extension status cua-perception+```++Remove extension-owned artifacts when they are no longer needed:++```bash+cua-driver extension remove cua-perception+```++Removal does not alter the default Driver or external `cua-som` installations.++## Use an external chooser++To put `jev-use` or another decision provider above this loop, follow [Use+jev-use with visual regions](/how-to-guides/driver/use-jev-use-with-visual-regions).+Driver remains provider-neutral and never receives the provider credential.diff --git a/docs/content/docs/how-to-guides/driver/use-jev-use-with-visual-regions.mdx b/docs/content/docs/how-to-guides/driver/use-jev-use-with-visual-regions.mdxnew file mode 100644index 0000000000..3e42dfba0e--- /dev/null+++ b/docs/content/docs/how-to-guides/driver/use-jev-use-with-visual-regions.mdx@@ -0,0 +1,52 @@+---+title: 'Use jev-use with visual regions'+description: 'Connect an external bounded action chooser without giving it Cua Driver authority.'+---++Use this boundary when an external `jev-use` recipe should select the next+action while Cua Driver retains capture and input authority. Provider setup,+credentials, billing, and request construction belong to the external recipe;+this guide defines only the Driver-facing contract.++## Build candidates locally++Keep one persistent Driver MCP connection or typed SDK runtime. Capture the+exact native window with `get_window_state`, parse its `capture_id` with+`parse_visual_regions`, and validate the result against the returned source,+PNG dimensions, and coordinate mapping.++Construct a small immutable candidate table locally. Each executable candidate+contains an opaque ID and one complete Driver action. A visual pixel candidate+must include `x`, `y`, the exact target, `delivery_mode`, and the same+`capture_id`. Include `reobserve` and `abstain` IDs when the observation can be+ambiguous or stale. Prefer a current accessibility element or typed browser ref+when it identifies the same control.++Send the external chooser only the task context and bounded candidate IDs and+descriptions that the workflow permits. Do not give it a Driver tool name,+free-form arguments, credentials, or permission to invent coordinates.++## Dispatch one selected ID++Accept exactly one returned candidate ID. Reject an unknown, duplicated, or+malformed choice. For an executable ID, dispatch the prebuilt Driver action+unchanged. Never reconstruct it from provider prose, and never remove the+capture ID after a stale or mismatched-capture refusal.++At most one action may derive from a capture. Reobserve after every action+attempt, timeout, unknown result, or refusal, then rebuild the candidate table+from fresh state. Verify completion from current semantic or application state;+a provider choice or delivered click is not proof of the postcondition.++## Preserve delivery limits++Window perception does not grant background input support. A+`background_unavailable` result is a refusal, not permission to retry in the+foreground. Foreground delivery and desktop input can take focus or move the+system cursor and require the workflow's existing authorization.++If `parse_visual_regions` is absent or returns `not_installed`, continue with+semantic evidence, reobserve, or abstain. Do not install the extension as a+side effect of a chooser request. See [Parse visual regions with Cua+Driver](/how-to-guides/driver/parse-visual-regions) for the explicit extension+lifecycle and artifact obligations.diff --git a/docs/content/docs/how-to-guides/index.mdx b/docs/content/docs/how-to-guides/index.mdxindex 8ff0231bb3..3bfb4da1f3 100644--- a/docs/content/docs/how-to-guides/index.mdx+++ b/docs/content/docs/how-to-guides/index.mdx@@ -6,3 +6,6 @@ description: 'Follow recipes for specific Cua goals.'How-to guides are recipes for **a specific goal**. They assume you already know the basics, so do a tutorial first if not. Unlike tutorials, they are *not a lesson*; they get you to a result and stop.They are grouped by product: Cua Driver for operating apps on a physical machine, Sandbox for isolated computers on local infrastructure or Fleet, Lume for local Apple silicon VMs, and Cua-Bench for verifiable computer-use tasks. Recipes and agent context cover workflows that span those products. Check [Sandbox runtime support](/reference/sandbox-sdk/runtime-support) for the image and connection requirements of a sandbox recipe.++For UI that has useful pixels but incomplete accessibility or browser semantics,+see [Parse visual regions with Cua Driver](/how-to-guides/driver/parse-visual-regions).diff --git a/docs/content/docs/reference/cua-driver/cli-reference.mdx b/docs/content/docs/reference/cua-driver/cli-reference.mdxindex de3803d775..6651157f97 100644--- a/docs/content/docs/reference/cua-driver/cli-reference.mdx+++ b/docs/content/docs/reference/cua-driver/cli-reference.mdx@@ -462,6 +462,176 @@ Report local skill-pack and per-agent link state.Print the local skill-pack path.+### `cua-driver extension`++Inspect and manage signed, target-specific optional extensions.++Verified installs bind a pinned publisher identity and Ed25519 key validity/rotation state to exact catalog, archive, manifest, file, original-model, and converted-model hashes plus component licenses/notices and corresponding-source revisions. Inspect previews license, source, and provenance before mutation. Explicit developer-only unsigned installs remain visibly unverified. Install, update, and remove use platform-specific ownership and link/reparse-point checks on macOS, Linux, and Windows.++#### `cua-driver extension list`++List registry-known extensions and local state.++**Flags:**++| Name | Description |+| ---- | ----------- |+| `--json` | Emit machine-readable output. |++#### `cua-driver extension info`++Compatibility alias for installed extension status.++**Arguments:**++| Name | Type | Required | Description |+| ---- | ---- | -------- | ----------- |+| `<name>` | String | Yes | Registry extension name. |++**Flags:**++| Name | Description |+| ---- | ----------- |+| `--json` | Emit machine-readable output. |++#### `cua-driver extension inspect`++Verify and preview license, source, provenance, and hashes without mutation.++**Arguments:**++| Name | Type | Required | Description |+| ---- | ---- | -------- | ----------- |+| `<name>` | String | Yes | Registry extension name. |++**Options:**++| Name | Type | Default | Description |+| ---- | ---- | ------- | ----------- |+| `--catalog` | String | — | Signed local catalog. |+| `--archive` | String | — | Developer-only unsigned local archive. |++**Flags:**++| Name | Description |+| ---- | ----------- |+| `--allow-unsigned-local` | Explicitly select developer-only unverified mode. |+| `--json` | Emit machine-readable output. |++#### `cua-driver extension status`++Verify installed integrity and optionally run the self-test hook.++**Arguments:**++| Name | Type | Required | Description |+| ---- | ---- | -------- | ----------- |+| `<name>` | String | No | Optional registry extension name. |++**Flags:**++| Name | Description |+| ---- | ----------- |+| `--self-test` | Run the extension self-test hook. |+| `--json` | Emit machine-readable output. |++#### `cua-driver extension install`++Verify, stage, and durably activate an extension.++Supported on macOS, Linux, and Windows with platform ownership and link/reparse-point checks.++**Arguments:**++| Name | Type | Required | Description |+| ---- | ---- | -------- | ----------- |+| `<name>` | String | Yes | Registry extension name. |++**Options:**++| Name | Type | Default | Description |+| ---- | ---- | ------- | ----------- |+| `--catalog` | String | — | Signed local catalog. |+| `--archive` | String | — | Developer-only unsigned local archive. |++**Flags:**++| Name | Description |+| ---- | ----------- |+| `--allow-unsigned-local` | Explicitly select developer-only unverified mode. |++#### `cua-driver extension update`++Verify and atomically activate a newer extension version.++Supported on macOS, Linux, and Windows with platform ownership and link/reparse-point checks.++**Arguments:**++| Name | Type | Required | Description |+| ---- | ---- | -------- | ----------- |+| `<name>` | String | Yes | Registry extension name. |++**Options:**++| Name | Type | Default | Description |+| ---- | ---- | ------- | ----------- |+| `--catalog` | String | — | Signed local catalog. |+| `--archive` | String | — | Developer-only unsigned local archive. |++**Flags:**++| Name | Description |+| ---- | ----------- |+| `--allow-unsigned-local` | Explicitly select developer-only unverified mode. |++#### `cua-driver extension remove`++Remove only a fully validated, manager-owned extension tree.++Supported on macOS, Linux, and Windows with platform ownership and link/reparse-point checks.++**Arguments:**++| Name | Type | Required | Description |+| ---- | ---- | -------- | ----------- |+| `<name>` | String | Yes | Registry extension name. |++#### `cua-driver extension path`++Compatibility command that prints the exact active version directory.++**Arguments:**++| Name | Type | Required | Description |+| ---- | ---- | -------- | ----------- |+| `<name>` | String | Yes | Registry extension name. |++### `cua-driver perception`++Parse a local PNG with the installed optional perception extension.++This read-only local-input mode does not create a Driver capture. Its visual-regions JSON marks the result ineligible for Driver action authority.++#### `cua-driver perception parse`++Parse one local PNG into canonical visual regions.++Requires --json. The capture file supplies source metadata only.++**Options:**++| Name | Type | Default | Description |+| ---- | ---- | ------- | ----------- |+| `--image` | String | — | Local PNG path. |+| `--capture` | String | — | Local capture source metadata JSON path. |++**Flags:**++| Name | Description |+| ---- | ----------- |+| `--json` | Emit canonical visual-regions JSON with local-input provenance. |+### `cua-driver manifest`Emit a stable JSON description of the CLI surface.diff --git a/docs/content/docs/reference/cua-driver/mcp-tools-linux.mdx b/docs/content/docs/reference/cua-driver/mcp-tools-linux.mdxindex 8ab3a8fc3e..1c6ba3e80c 100644--- a/docs/content/docs/reference/cua-driver/mcp-tools-linux.mdx+++ b/docs/content/docs/reference/cua-driver/mcp-tools-linux.mdx@@ -16,7 +16,7 @@ This reference describes the **Linux** native tool registry.Other platforms: [macOS MCP tools](/reference/cua-driver/mcp-tools), [Windows MCP tools](/reference/cua-driver/mcp-tools-windows).See [MCP tool notes](/reference/cua-driver/mcp-tool-notes) for shared guidance.-`cua-driver` exposes 60 MCP tools through a single stdio server (`cua-driver mcp`). Every tool is also callable from the shell as `cua-driver <name> '<JSON-args>'`.+`cua-driver` exposes 62 MCP tools through a single stdio server (`cua-driver mcp`). Every tool is also callable from the shell as `cua-driver <name> '<JSON-args>'`.Tool names are `snake_case`. Responses are MCP `CallTool.Result` envelopes: a text content block prefixed with a `✅` summary (or the error reason on failure), plus optional image or structured-content blocks on tools that produce them. See the [CLI reference](/reference/cua-driver/cli-reference) for CLI-specific options like `--socket` and `--screenshot-out-file`.@@ -76,8 +76,9 @@ Optional `max_elements` / `max_depth` bound the AT-SPI walk to mitigate context-- `include_accessibility_tree` (boolean, optional): Default true — walk the AT-SPI tree and return `elements` + `tree_markdown` alongside the screenshot. Set false to SKIP the AT-SPI walk entirely and return just the screenshot plus window metadata (window_bounds, app_name, window_title) — the capture-only path for a live window preview / picture-in-picture. Mirrors include_screenshot. Setting BOTH include_accessibility_tree:false AND include_screenshot:false is an error (nothing to return).- `include_screenshot` (boolean, optional): Default true — returns a grounding screenshot alongside the tree. Set false to skip the grab and return tree only (the cheap path for re-indexing before an element ax action).- `max_depth` (integer, optional): Cap on the AT-SPI tree walk depth. Omit for the default (uncapped). Lower for deeply nested apps. range: 1–unbounded-- `max_dimension` (integer, optional): Optional cap on the returned screenshot's long edge, in pixels (aspect ratio preserved) — the cheap path for a small preview. Applied on top of the configured max_image_dimension ceiling; the tighter wins. Omit for the configured default. range: 1–unbounded+- `max_dimension` (integer, optional): Legacy optional cap on the returned screenshot's long edge. Applied on top of the configured max_image_dimension ceiling when max_image_dimension is omitted. range: 1–unbounded- `max_elements` (integer, optional): Cap on total AT-SPI nodes walked. Omit for the default (5 000). Lower for huge web/Electron trees. range: 1–unbounded+- `max_image_dimension` (integer, optional): Per-call long-edge override. This value wins over configured and legacy limits; 0 returns native-resolution PNG bytes. Omit to preserve configured behavior. range: 0–unbounded- `pid` (integer, required)- `query` (string, optional): Optional case-insensitive substring. Projects both tree_markdown and structured elements to matches plus ancestors while preserving original indices. Compare total_element_count with returned_element_count.- `screenshot_out_file` (string, optional): When set, write the PNG to this file path (~ expanded) instead of embedding base64 in the response. The structured output carries screenshot_file_path instead.@@ -218,6 +219,7 @@ button: "left" (default), "right", or "middle". Defaults to left so the field is**Arguments:**- `button` (string, optional): Mouse button. Default: "left" (legacy back-compat). X11: routed via ButtonPress/Release with the matching evdev code. Native Wayland: only left-button is supported via the virtual-pointer protocol; right/middle return an error.+- `capture_id` (string, optional): Optional one-shot binding to the exact PNG returned by get_window_state or get_desktop_state. When present, x/y are interpreted in that capture and admitted before native dispatch.- `count` (integer, optional)- `cursor_id` (string, optional): Optional multi-cursor instance id. Default: 'default'.- `delivery_mode` (string, optional): Input delivery mode. 'background' (default) never activates or raises the target window. On X11 it injects via XTEST / the XInput2 master pointer (no focus steal). On Wayland it goes through libei + xdg-desktop-portal, which injects to the compositor's input focus — Wayland's security model has no per-window background targeting, so a specific non-focused window cannot be aimed at; when no libei backend is available the tool returns a structured background_unavailable error. 'foreground' is the explicit escalation: activate the target (X11 _NET_ACTIVE_WINDOW; Wayland compositor activate), inject, then restore the prior active window — a brief focus swap unless the target was already active. Matches the macOS / Windows delivery_mode surface. default: `"background"`@@ -465,11 +467,11 @@ Move the synthetic agent cursor without changing the user's pointer. Only an expCapture a cropped JPEG of a window region (x1,y1)–(x2,y2) in screenshot pixels, with 20% padding. Output is at most 500 px wide.-After a zoom, pass from_zoom=true to click/type_text to auto-translate coordinates back to full-window space.+After a zoom, pass from_zoom=true to click/type_text to auto-translate coordinates back to full-window space. Coordinate actions return `screenshot_context_missing` when the latest snapshot does not contain a screenshot owned by this session. `from_zoom` actions return `zoom_context_missing` when the zoom was never created or was replaced; call `get_window_state`, then `zoom`, again on the same connection.**Arguments:**-- `pid` (integer, optional): Target pid — required for from_zoom click/type translation.+- `pid` (integer, optional): Optional target pid. When omitted, the driver resolves the unique current snapshot for this session and window.- `window_id` (integer, required)- `x1` (number, required)- `x2` (number, required)@@ -1063,3 +1065,29 @@ Deprecated compatibility alias that reads a live legacy session's capture policy- `session` (string, optional): Optional public label. When omitted, inspect the caller's attachedimplicit session.++### `install_extension`++Preview or install one Driver-managed optional extension. The first call without confirm returns the exact signed artifact, destination, license, source, and trust plan without mutation. Re-call with confirm=true to perform that exact verified installation.++**Arguments:**++- `confirm` (boolean, optional): Install the previewed extension. Omit or false for a read-only plan.+- `name` (string, required)++```json+{"name":"perception"}+```++### `parse_visual_regions`++Parse one immutable registered capture into model-neutral text and icon regions.++**Arguments:**++- `capture_id` (string, required)+- `options` (object, optional): Optional, model-neutral controls for one bounded parse. default: `{}`++```json+{"capture_id":"example"}+```diff --git a/docs/content/docs/reference/cua-driver/mcp-tools-windows.mdx b/docs/content/docs/reference/cua-driver/mcp-tools-windows.mdxindex 3e2e529fcf..e3ec87497f 100644--- a/docs/content/docs/reference/cua-driver/mcp-tools-windows.mdx+++ b/docs/content/docs/reference/cua-driver/mcp-tools-windows.mdx@@ -16,7 +16,7 @@ This reference describes the **Windows** native tool registry.Other platforms: [macOS MCP tools](/reference/cua-driver/mcp-tools), [Linux MCP tools](/reference/cua-driver/mcp-tools-linux).See [MCP tool notes](/reference/cua-driver/mcp-tool-notes) for shared guidance.-`cua-driver` exposes 57 MCP tools through a single stdio server (`cua-driver mcp`). Every tool is also callable from the shell as `cua-driver <name> '<JSON-args>'`.+`cua-driver` exposes 59 MCP tools through a single stdio server (`cua-driver mcp`). Every tool is also callable from the shell as `cua-driver <name> '<JSON-args>'`.Tool names are `snake_case`. Responses are MCP `CallTool.Result` envelopes: a text content block prefixed with a `✅` summary (or the error reason on failure), plus optional image or structured-content blocks on tools that produce them. See the [CLI reference](/reference/cua-driver/cli-reference) for CLI-specific options like `--socket` and `--screenshot-out-file`.@@ -81,7 +81,7 @@ Set `query` to a case-insensitive substring to project BOTH `tree_markdown` andAlways returns BOTH the element tree AND a screenshot — ground on both and cross-check (the tree lies on some surfaces). Choose the modality at ACTION time: an element ax action (element_index/element_token → accessibility rung) or an element px action (x,y → pixel rung off this screenshot). capture_mode is deprecated and ignored.-The mirror image: pass `include_accessibility_tree:false` to SKIP the UIA walk entirely and return just the screenshot plus window metadata (window_bounds, app_name, window_title) — the capture-only path for a live window preview / picture-in-picture. Setting BOTH `include_accessibility_tree:false` and `include_screenshot:false` is an error. Optional `max_dimension` caps the returned screenshot's long edge in pixels for a cheap thumbnail.+The mirror image: pass `include_accessibility_tree:false` to SKIP the UIA walk entirely and return just the screenshot plus window metadata (window_bounds, app_name, window_title) — the capture-only path for a live window preview / picture-in-picture. Setting BOTH `include_accessibility_tree:false` and `include_screenshot:false` is an error. Optional `max_image_dimension` overrides the configured screenshot long-edge limit for this call; pass 0 for native resolution. Legacy `max_dimension` remains a cap on the configured limit.Uses `IUIAutomationCacheRequest` to batch-fetch all element properties in a single COM call (Chrome's ~5000-element tree returns in ~2-3s instead of timing out at 4s with per-property RPCs).@@ -97,8 +97,9 @@ Windows requires no special permissions.- `include_accessibility_tree` (boolean, optional): Default true — walk the UIA tree and return `elements` + `tree_markdown` alongside the screenshot. Set false to SKIP the UIA walk entirely and return just the screenshot plus window metadata (window_bounds, app_name, window_title) — the capture-only path for a live window preview / picture-in-picture. Mirrors include_screenshot. Setting BOTH include_accessibility_tree:false AND include_screenshot:false is an error (nothing to return).- `include_screenshot` (boolean, optional): Default true — returns a grounding screenshot alongside the tree. Set false to skip the grab and return tree only (the cheap path for re-indexing before an element ax action).- `max_depth` (integer, optional): Cap on the UIA-tree walk depth. Nodes whose rendered indent would exceed this are omitted. Omit for the default (25). Lower for deep menu / Electron trees. range: 1–unbounded-- `max_dimension` (integer, optional): Optional cap on the returned screenshot's long edge, in pixels (aspect ratio preserved) — the cheap path for a small preview. Applied on top of the configured max_image_dimension ceiling; the tighter wins. Omit for the configured default. range: 1–unbounded+- `max_dimension` (integer, optional): Legacy optional cap on the returned screenshot's long edge, in pixels (aspect ratio preserved). Applied on top of the configured max_image_dimension ceiling when max_image_dimension is omitted; the tighter wins. range: 1–unbounded- `max_elements` (integer, optional): Cap on the total number of UIA nodes walked. Truncates depth-first; markdown and structured elements truncate together. Omit for the default (5 000). Lower for Electron / large web apps that produce 10k+ element trees. range: 1–unbounded+- `max_image_dimension` (integer, optional): Per-call long-edge limit for the returned screenshot, in pixels (aspect ratio preserved). Explicit values override configured behavior; 0 returns native resolution. Omit to preserve the configured default. range: 0–unbounded- `pid` (integer, required): Process ID from `list_apps`.- `query` (string, optional): Optional case-insensitive substring. Projects both tree_markdown and structured elements to matches plus ancestors while preserving original indices. Compare total_element_count with returned_element_count.- `screenshot_out_file` (string, optional): When set, write the PNG to this file path instead of embedding base64 in the response. The structured output will contain `screenshot_file_path` instead.@@ -275,6 +276,7 @@ Windows-only convenience: `button: "left"|"right"|"middle"` switches the mouse b**Arguments:**- `button` (string, optional): Mouse button. Default "left".+- `capture_id` (string, optional): Optional ID from get_window_state or get_desktop_state. When present, x and y are admitted against that exact capture and the ID is consumed before native dispatch.- `count` (integer, optional): Click count — 1 (single), 2 (double), 3 (triple). Default 1. range: 1–3- `delivery_mode` (string, optional): Input delivery mode. 'background' (default) never swaps foreground: it routes through UIA Invoke / PostMessage and the window is never raised. For targets whose input stack silently drops posted events (Chromium/Electron content, GTK buttons, VCL/LibreOffice accelerators) the tool returns a structured background_unavailable error rather than fronting. 'foreground' is the explicit escalation: a brief SetForegroundWindow swap + SendInput, restoring the prior foreground afterward. IMPORTANT: 'background' is not a hint to weigh — it is the mandatory first attempt. Do NOT pass 'foreground' preemptively because a target 'looks like' GTK/Chromium/Electron; the DRIVER decides when background is impossible and tells you so via a background_unavailable error (or a verified no-op). Only THEN re-issue the same action with 'foreground'. The lists above are the driver's detectors, not a checklist for you to front on a guess — fronting up-front needlessly steals the user's focus and is a bug, not a shortcut. Matches the macOS delivery_mode surface.- `element_index` (integer, optional): Element index from get_window_state. Requires the matching `snapshot_id` alongside it. Prefer `element_token`, which carries both values.@@ -571,13 +573,13 @@ Coordinates `x1, y1, x2, y2` are in the same pixel space as the screenshot returA 20% padding is automatically added on every side of the requested region so the target remains visible even if the caller's coordinates are slightly off.-After a zoom, pass `from_zoom=true` to click/type_text to auto-translate coordinates back to full-window space.+After a zoom, pass `from_zoom=true` to click/type_text to auto-translate coordinates back to full-window space. Coordinate actions return `screenshot_context_missing` when the latest snapshot does not contain a screenshot owned by this session. `from_zoom` actions return `zoom_context_missing` when the zoom was never created or was replaced; call `get_window_state`, then `zoom`, again on the same connection.-Windows-specific: `window_id` is the canonical addressing field (HWND). `pid` is also required (used to scope the zoom translation registry, matching Swift's per-pid zoom context).+Windows-specific: `window_id` is the canonical addressing field (HWND). `pid` is preferred when available; otherwise the driver resolves the unique current snapshot owned by this session and window.**Arguments:**-- `pid` (integer, optional): Target process ID. Validated in code (an explicit "Missing required integer field pid" error when absent); kept out of `required` to match the shared cross-platform zoom contract.+- `pid` (integer, optional): Optional target process ID. When omitted, the unique current snapshot for this session and HWND is used.- `window_id` (integer, required): HWND of the target window.- `x1` (number, required): Left edge of the region (resized-image pixels).- `x2` (number, required): Right edge of the region (resized-image pixels).@@ -1124,3 +1126,29 @@ Deprecated compatibility alias that reads a live legacy session's capture policy- `session` (string, optional): Optional public label. When omitted, inspect the caller's attachedimplicit session.++### `install_extension`++Preview or install one Driver-managed optional extension. The first call without confirm returns the exact signed artifact, destination, license, source, and trust plan without mutation. Re-call with confirm=true to perform that exact verified installation.++**Arguments:**++- `confirm` (boolean, optional): Install the previewed extension. Omit or false for a read-only plan.+- `name` (string, required)++```json+{"name":"perception"}+```++### `parse_visual_regions`++Parse one immutable registered capture into model-neutral text and icon regions.++**Arguments:**++- `capture_id` (string, required)+- `options` (object, optional): Optional, model-neutral controls for one bounded parse. default: `{}`++```json+{"capture_id":"example"}+```diff --git a/docs/content/docs/reference/cua-driver/mcp-tools.mdx b/docs/content/docs/reference/cua-driver/mcp-tools.mdxindex f401aa5d9d..eafe2902c1 100644--- a/docs/content/docs/reference/cua-driver/mcp-tools.mdx+++ b/docs/content/docs/reference/cua-driver/mcp-tools.mdx@@ -16,7 +16,7 @@ This reference describes the **macOS** native tool registry.Other platforms: [Linux MCP tools](/reference/cua-driver/mcp-tools-linux), [Windows MCP tools](/reference/cua-driver/mcp-tools-windows).See [MCP tool notes](/reference/cua-driver/mcp-tool-notes) for shared guidance.-`cua-driver` exposes 56 MCP tools through a single stdio server (`cua-driver mcp`). Every tool is also callable from the shell as `cua-driver <name> '<JSON-args>'`.+`cua-driver` exposes 58 MCP tools through a single stdio server (`cua-driver mcp`). Every tool is also callable from the shell as `cua-driver <name> '<JSON-args>'`.Tool names are `snake_case`. Responses are MCP `CallTool.Result` envelopes: a text content block prefixed with a `✅` summary (or the error reason on failure), plus optional image or structured-content blocks on tools that produce them. See the [CLI reference](/reference/cua-driver/cli-reference) for CLI-specific options like `--socket` and `--screenshot-out-file`.@@ -69,7 +69,7 @@ PREFERRED CONSUMERS read `structuredContent.elements` (one entry per indexed rowAlways returns BOTH the element tree AND a screenshot — ground on both and cross-check (the tree lies on some surfaces: Electron echo-confirms, Catalyst null values, virtualized off-viewport rows with `h:1` frames). You choose the modality at ACTION time, not here: an element ax action (pass `element_index`/`element_token` → the accessibility rung) or an element px action (pass `x`,`y` → the pixel rung, read straight off this screenshot). `capture_mode` is deprecated and ignored. Pass `include_screenshot:false` to skip the grab and get the tree only — the cheap path when you're just re-indexing before an element ax action.-The mirror image: pass `include_accessibility_tree:false` to SKIP the AX walk entirely (the expensive part, up to 20 s) and return just the screenshot plus window metadata — `window_bounds`, `screenshot_scale`, `screenshot_width`/`screenshot_height`, `app_name`, and `window_title` — the capture-only path for rendering a live window preview / picture-in-picture without paying for perception. Setting BOTH `include_accessibility_tree:false` and `include_screenshot:false` is an error (nothing to return). Optional `max_dimension` caps the returned screenshot's long edge in pixels (aspect preserved) for a cheap thumbnail.+The mirror image: pass `include_accessibility_tree:false` to SKIP the AX walk entirely (the expensive part, up to 20 s) and return just the screenshot plus window metadata — `window_bounds`, `screenshot_scale`, `screenshot_width`/`screenshot_height`, `app_name`, and `window_title` — the capture-only path for rendering a live window preview / picture-in-picture without paying for perception. Setting BOTH `include_accessibility_tree:false` and `include_screenshot:false` is an error (nothing to return). Optional `max_image_dimension` overrides the configured screenshot long-edge limit for this call; use 0 for native resolution. The legacy `max_dimension` remains a tighter cap for compatibility.The snapshot is SCOPED to `window_id`: a window_id that no longer exists is refused with `window_id_not_found`, and one owned by another process is refused with `window_owner_pid_mismatch` naming the real `owner_pid` to retry with (macOS hosts a sandboxed app's Open/Save panel out-of-process, so its window belongs to the panel service, not the app). If the window is live under this pid but its accessibility surface can't be resolved, the tree comes back EMPTY with `degraded_reason: ax_window_unresolved` and the screenshot of the requested window — act by pixel there. This tool never returns another surface's elements under your window_id. Before exposing a screenshot, its raw dimensions are validated as a coherent 1x/2x representation of the requested WindowServer bounds. `px_frame_mismatch` or `px_capture_unavailable` omits an unprovable screenshot/pixel frame instead of guessing a transform; the truthful AX payload remains available.@@ -85,6 +85,7 @@ Optional `max_elements` / `max_depth` bound the AX walk to mitigate context-wind- `max_depth` (integer, optional): Cap on the AX-tree walk depth. Nodes whose rendered indent would exceed this are omitted. Omit for the default (25). Lower this for deep menu/Electron trees. range: 1–unbounded- `max_dimension` (integer, optional): Optional cap on the returned screenshot's long edge, in pixels (aspect ratio preserved) — the cheap path for a small preview / thumbnail. Applied on top of the session/global max_image_dimension ceiling; the tighter of the two wins. Omit for the configured default. range: 1–unbounded- `max_elements` (integer, optional): Cap on the total number of AX nodes walked. Truncates depth-first; markdown and structured elements truncate together. Omit for the default (2 000). Lower this for Electron / Obsidian / large web apps that produce 10k+ element trees and blow context windows. range: 1–unbounded+- `max_image_dimension` (integer, optional): Per-call override for the returned screenshot's long edge in pixels. An explicit value wins over the session/global setting; 0 returns native resolution. Omit to preserve configured behavior. range: 0–unbounded- `pid` (integer, required): Target process ID.- `query` (string, optional): Case-insensitive filter for tree_markdown and structured elements. Returns matching actionable rows plus their actionable ancestors without renumbering element_index values.- `screenshot_out_file` (string, optional): When set, write the PNG to this file path (~ expanded) instead of embedding base64 in the response. The structured output will contain screenshot_file_path instead.@@ -245,6 +246,7 @@ from_zoom: set true after a zoom call to auto-translate zoom-image pixel coordin- `action` (string, optional): AX action: press, show_menu, pick, confirm, cancel, open.- `button` (string, optional): Mouse button. Default: "left" — omit for legacy left-click behaviour. Pixel path uses the matching CGEvent primitive; AX path maps "right" to AXShowMenu and falls back to a pixel middle-click at the element's center for "middle".+- `capture_id` (string, optional): Optional immutable source capture ID returned by get_window_state or get_desktop_state. With x,y, Driver atomically admits and consumes that exact capture before dispatch; stale, mismatched, or out-of-bounds captures are refused without fallback.- `count` (integer, optional): Click count (pixel path only). Default 1.- `debug_image_out` (string, optional): Optional file path. When set on a pixel-addressed click, captures a fresh screenshot, draws a red crosshair at (x, y), and writes the PNG. Use to verify coordinate spaces. Requires window_id; incompatible with from_zoom.- `delivery_mode` (string, optional): Best-effort-background ladder rung (default "background"). "background": perform the AX action or post the CGEvent without fronting. "foreground": briefly front the window, act, let transient UI settle, then restore the prior frontmost app. Requires window_id. Modified clicks require "foreground" so macOS observes physical modifier-key state. A generic click has no independent postcondition read-back, except selection of list-like AX rows whose AXSelected state can be confirmed; otherwise confirm the effect from a fresh state snapshot. Use the agent loop: background AX (element_index) → snapshot → background pixel (x/y) → snapshot → delivery_mode:"foreground".@@ -360,7 +362,7 @@ Insert text into the target pid via `AXSetAttribute(kAXSelectedText)`. Works forOptional `element_index` + `window_id` (from the last `get_window_state` snapshot) directs the write to a specific field. Without `element_index`, the write goes to the pid's currently focused element.-WEB CONTENT (Chromium/WebKit/Electron — browser tabs, Slack, VS Code, X's compose box): AXValue is not independent proof that the renderer/DOM observed an AX write or synthesized keystrokes. The driver detects this at the element level (an AXWebArea ancestor) and refuses to trust AXValue-only read-back there — type_text returns effect:"unverifiable" + escalation, never a false "confirmed" (a browser's own native address bar/toolbar stays trusted). For a browser TAB the reliable path is the `page` tool (drives the DOM via CDP); for an embedded web view use this tool's px form: pass x,y (no element_index) to pixel-click the field then type, in one call. NOTE: a px focus-click won't reliably open+focus a CLOSED control; AX-press to open/activate it first (works in the background), then px-type. Always confirm via the screenshot; if px-background still drops, escalate to delivery_mode:"foreground".+WEB CONTENT (Chromium/WebKit/Electron — browser tabs, Slack, VS Code, X's compose box): AXValue is not independent proof that the renderer/DOM observed an AX write or synthesized keystrokes. The driver detects this at the element level (an AXWebArea ancestor) and refuses to trust AXValue-only read-back there. Electron AX targets that are web content or cannot be proven native refuse background delivery before mutation because the AX route cannot establish exact renderer focus; use the px form or explicit foreground delivery. Other web-content paths return effect:"unverifiable" + escalation, never a false "confirmed" (a browser's own native address bar/toolbar stays trusted). For a browser TAB the reliable path is the `page` tool (drives the DOM via CDP); for an embedded web view use this tool's px form: pass x,y (no element_index) to pixel-click the field then type, in one call. NOTE: a px focus-click won't reliably open+focus a CLOSED control; AX-press to open/activate it first (works in the background), then px-type. Always confirm via the screenshot; if px-background still drops, escalate to delivery_mode:"foreground".**Arguments:**@@ -531,11 +533,11 @@ Move a cursor to (x, y). In window scope (default), moves only the agent cursorCapture a cropped JPEG of a window region (x1,y1)–(x2,y2) in screenshot pixel coordinates, with 20% padding added on each side. The output image is at most 500 px wide.-After a zoom, pass `from_zoom=true` to click/type_text to auto-translate coordinates back to full-window space.+After a zoom, pass `from_zoom=true` to click/type_text to auto-translate coordinates back to full-window space. Coordinate actions return `screenshot_context_missing` when the latest snapshot does not contain a screenshot owned by this session. `from_zoom` actions return `zoom_context_missing` when the zoom was never created or was replaced; call `get_window_state`, then `zoom`, again on the same connection.**Arguments:**-- `pid` (integer, optional): Target pid — required for from_zoom click/type translation.+- `pid` (integer, optional): Optional target pid. When omitted, the driver resolves the unique current snapshot for this session and window.- `window_id` (integer, required): CGWindowID from list_windows.- `x1` (number, required): Left edge of region in screenshot pixels.- `x2` (number, required): Right edge of region in screenshot pixels.@@ -1064,3 +1066,29 @@ Deprecated compatibility alias that reads a live legacy session's capture policy- `session` (string, optional): Optional public label. When omitted, inspect the caller's attachedimplicit session.++### `install_extension`++Preview or install one Driver-managed optional extension. The first call without confirm returns the exact signed artifact, destination, license, source, and trust plan without mutation. Re-call with confirm=true to perform that exact verified installation.++**Arguments:**++- `confirm` (boolean, optional): Install the previewed extension. Omit or false for a read-only plan.+- `name` (string, required)++```json+{"name":"perception"}+```++### `parse_visual_regions`++Parse one immutable registered capture into model-neutral text and icon regions.++**Arguments:**++- `capture_id` (string, required)+- `options` (object, optional): Optional, model-neutral controls for one bounded parse. default: `{}`++```json+{"capture_id":"example"}+```diff --git a/flake.nix b/flake.nixindex 5f4582277f..f272de5dd2 100644--- a/flake.nix+++ b/flake.nix@@ -31,6 +31,7 @@./libs/cua-driver/wayland-helper./libs/cua-driver/compat-fixtures./libs/cua-driver/tests/fixtures/shared/web/index.html+ ./libs/cua-driver/tests/perception-demo/evidence-manifest.schema.json];};diff --git a/libs/cua-driver/README.md b/libs/cua-driver/README.mdindex 875d9758b0..65f4a0bee8 100644--- a/libs/cua-driver/README.md+++ b/libs/cua-driver/README.md@@ -5,6 +5,31 @@ Background computer-use driver for any agents. Speaks MCP over stdio; drives natSee [MCP protocol and skills](docs/mcp-protocol-and-skills.md) for the modernstdio profile, legacy compatibility, bundled skill resources, and HTTP limits.+## Optional visual perception++The default MIT-licensed Driver works without model artifacts. An explicitly+installed `cua-perception` extension can parse one retained native window or+desktop screenshot into model-neutral text and icon regions. Capture and input+authority remain in Driver, and a region-derived pixel click must carry the+same one-use `capture_id` as the observation.++See the [extension and runtime contract](docs/perception-extension.md) for+installation, failure, capture, and action boundaries. Review the [third-party+notices](docs/perception-third-party-notices.md) before distributing the+separate worker, model, or ONNX Runtime artifacts.++For offline inspection of an existing PNG, the CLI also provides a local-only+mode:++```bash+cua-driver perception parse --image /tmp/window.png --capture /tmp/capture.json --json+```++This mode never registers the file as a Driver capture and its output cannot+authorize a Driver action. Its required JSON mode returns failures as+`{"ok":false,"error":{"code":"...","message":"...","retryable":false}}`;+see the extension contract for the stable codes.+**[Documentation](https://cua.ai/docs/cua-driver)** - Installation, guides, and API reference.## Integration surfacesdiff --git a/libs/cua-driver/compat-fixtures/README.md b/libs/cua-driver/compat-fixtures/README.mdindex 02038b94bf..16efcdd93a 100644--- a/libs/cua-driver/compat-fixtures/README.md+++ b/libs/cua-driver/compat-fixtures/README.md@@ -35,6 +35,12 @@ freeze that method. Current language tests cover the new signatures and typednative-window discovery and observation. All other frozen package signatures,the CLI/MCP fixtures, and the baseline application fixtures remain unchanged.+The released `cua-driver-rs-v0.28.2` UniFFI wire order is also frozen:+`ClickPosition` uses `1=Coordinates` and `2=Element`; `CapturedCoordinates` is+appended as ordinal 3. `GetWindowStateInput.max_image_dimension` is appended to+the existing record fields. Future UniFFI enum variants and record fields must+remain append-only unless an explicit compatibility decision says otherwise.+RFC 2549 independently accepts one additive CLI change: `cua-driver mcp--direct`. Bare MCP behavior remains platform-defined (direct on Windows andLinux, signed app service on macOS), while `--socket` continues to select andiff --git a/libs/cua-driver/contract/manifest.json b/libs/cua-driver/contract/manifest.jsonindex 7245868e34..09e8c46a2b 100644--- a/libs/cua-driver/contract/manifest.json+++ b/libs/cua-driver/contract/manifest.json@@ -57,6 +57,11 @@"required": ["y"]+ },+ {+ "required": [+ "capture_id"+ ]}]},@@ -75,6 +80,11 @@],"type": "string"},+ "capture_id": {+ "default": null,+ "minLength": 1,+ "type": "string"+ },"count": {"default": null,"maximum": 3,@@ -1509,6 +1519,11 @@"minimum": 1,"type": "integer"},+ "max_image_dimension": {+ "description": "Optional per-call long-edge ceiling. Zero requests native resolution;\nomit it to preserve the configured session or global behavior.",+ "minimum": 0,+ "type": "integer"+ },"pid": {"maximum": 4294967295,"minimum": 1,@@ -2832,6 +2847,509 @@"type": "object"}},+ {+ "name": "parse_visual_regions",+ "description": "Parse one immutable registered capture into model-neutral text and icon regions.",+ "platforms": [+ "macos",+ "windows",+ "linux"+ ],+ "capabilities": [+ "visual.regions.parse",+ "screen.capture.registry.read"+ ],+ "annotations": {+ "read_only": true,+ "destructive": false,+ "idempotent": true,+ "open_world": false+ },+ "schema_mode": "canonical_runtime",+ "cursor_semantics": {+ "action": "observe"+ },+ "input_schema": {+ "additionalProperties": false,+ "description": "Transport-free request. Runtime use requires the future capture registry.",+ "properties": {+ "capture_id": {+ "minLength": 1,+ "type": "string"+ },+ "options": {+ "additionalProperties": false,+ "default": {},+ "description": "Optional, model-neutral controls for one bounded parse.",+ "properties": {+ "kinds": {+ "anyOf": [+ {+ "items": {+ "enum": [+ "text",+ "icon"+ ]+ },+ "maxItems": 2,+ "minItems": 1,+ "type": "array",+ "uniqueItems": true+ },+ {+ "type": "null"+ }+ ]+ },+ "max_regions": {+ "minimum": 1,+ "type": "integer"+ },+ "min_confidence": {+ "maximum": 1,+ "minimum": 0,+ "type": "number"+ }+ },+ "required": [],+ "type": "object"+ }+ },+ "required": [+ "capture_id"+ ],+ "type": "object"+ },+ "success_output_schema": {+ "additionalProperties": true,+ "properties": {+ "capture": {+ "properties": {+ "action_coordinate_space": {+ "oneOf": [+ {+ "properties": {+ "kind": {+ "const": "screenshot_pixels",+ "type": "string"+ }+ },+ "required": [+ "kind"+ ],+ "type": "object"+ },+ {+ "properties": {+ "kind": {+ "const": "affine",+ "type": "string"+ },+ "m11": {+ "format": "double",+ "type": "number"+ },+ "m12": {+ "format": "double",+ "type": "number"+ },+ "m21": {+ "format": "double",+ "type": "number"+ },+ "m22": {+ "format": "double",+ "type": "number"+ },+ "tx": {+ "format": "double",+ "type": "number"+ },+ "ty": {+ "format": "double",+ "type": "number"+ }+ },+ "required": [+ "kind",+ "m11",+ "m12",+ "m21",+ "m22",+ "tx",+ "ty"+ ],+ "type": "object"+ }+ ]+ },+ "capture_id": {+ "type": "string"+ },+ "captured_at": {+ "type": [+ "string",+ "null"+ ]+ },+ "screenshot": {+ "properties": {+ "height": {+ "minimum": 1,+ "type": "integer"+ },+ "mime_type": {+ "const": "image/png"+ },+ "reference": {+ "type": "string"+ },+ "sha256": {+ "type": [+ "string",+ "null"+ ]+ },+ "width": {+ "minimum": 1,+ "type": "integer"+ }+ },+ "required": [+ "reference",+ "width",+ "height",+ "mime_type"+ ],+ "type": "object"+ },+ "source": {+ "oneOf": [+ {+ "properties": {+ "kind": {+ "const": "window",+ "type": "string"+ },+ "pid": {+ "format": "uint32",+ "minimum": 0,+ "type": "integer"+ },+ "window_id": {+ "format": "uint64",+ "minimum": 0,+ "type": "integer"+ }+ },+ "required": [+ "kind",+ "pid",+ "window_id"+ ],+ "type": "object"+ },+ {+ "properties": {+ "display_id": {+ "const": "primary"+ },+ "kind": {+ "const": "primary_desktop",+ "type": "string"+ }+ },+ "required": [+ "kind",+ "display_id"+ ],+ "type": "object"+ }+ ]+ }+ },+ "required": [+ "capture_id",+ "source",+ "screenshot",+ "action_coordinate_space"+ ],+ "type": "object"+ },+ "parser": {+ "properties": {+ "backend": {+ "type": [+ "string",+ "null"+ ]+ },+ "extension_id": {+ "type": "string"+ },+ "extension_version": {+ "type": "string"+ },+ "fixture_sha256": {+ "type": [+ "string",+ "null"+ ]+ },+ "model_id": {+ "type": "string"+ },+ "model_manifest_sha256": {+ "type": [+ "string",+ "null"+ ]+ },+ "model_source_revision": {+ "type": [+ "string",+ "null"+ ]+ },+ "model_version": {+ "type": "string"+ },+ "onnx_runtime_library_sha256": {+ "type": [+ "string",+ "null"+ ]+ },+ "onnx_runtime_version": {+ "type": [+ "string",+ "null"+ ]+ },+ "runtime": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "required": [+ "extension_id",+ "extension_version",+ "model_id",+ "model_version"+ ],+ "type": "object"+ },+ "regions": {+ "items": {+ "properties": {+ "bounds": {+ "properties": {+ "height": {+ "minimum": 1,+ "type": "integer"+ },+ "width": {+ "minimum": 1,+ "type": "integer"+ },+ "x": {+ "minimum": 0,+ "type": "integer"+ },+ "y": {+ "minimum": 0,+ "type": "integer"+ }+ },+ "required": [+ "x",+ "y",+ "width",+ "height"+ ],+ "type": "object"+ },+ "confidence": {+ "maximum": 1,+ "minimum": 0,+ "type": "number"+ },+ "group_id": {+ "type": [+ "string",+ "null"+ ]+ },+ "id": {+ "type": "string"+ },+ "interactive": {+ "type": "boolean"+ },+ "kind": {+ "enum": [+ "text",+ "icon"+ ],+ "type": "string"+ },+ "label": {+ "type": [+ "string",+ "null"+ ]+ },+ "parent_id": {+ "type": [+ "string",+ "null"+ ]+ },+ "reading_order": {+ "format": "uint32",+ "minimum": 0,+ "type": [+ "integer",+ "null"+ ]+ },+ "text": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "required": [+ "id",+ "kind",+ "bounds",+ "confidence",+ "interactive"+ ],+ "type": "object"+ },+ "type": "array"+ },+ "request_id": {+ "type": [+ "string",+ "null"+ ]+ },+ "schema": {+ "const": "cua.visual_regions_v1"+ },+ "timing": {+ "properties": {+ "duration_ms": {+ "format": "uint64",+ "minimum": 0,+ "type": "integer"+ },+ "inference_ms": {+ "format": "uint64",+ "minimum": 0,+ "type": [+ "integer",+ "null"+ ]+ },+ "preprocess_ms": {+ "format": "uint64",+ "minimum": 0,+ "type": [+ "integer",+ "null"+ ]+ }+ },+ "required": [+ "duration_ms"+ ],+ "type": "object"+ },+ "warnings": {+ "items": {+ "properties": {+ "code": {+ "type": "string"+ },+ "detail": {+ "type": [+ "string",+ "null"+ ]+ },+ "message": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "message"+ ],+ "type": "object"+ },+ "type": "array"+ }+ },+ "required": [+ "schema",+ "capture",+ "parser",+ "regions",+ "timing"+ ],+ "type": "object"+ },+ "error_output_schema": {+ "additionalProperties": false,+ "properties": {+ "code": {+ "enum": [+ "not_installed",+ "capture_not_found",+ "capture_expired",+ "capture_stale",+ "capture_generation_mismatch",+ "unsupported_target",+ "unsupported_platform",+ "incompatible_protocol",+ "invalid_frame",+ "worker_launch_failed",+ "worker_crashed",+ "worker_cancelled",+ "timeout",+ "resource_limit_exceeded",+ "artifact_invalid",+ "inference_failed"+ ],+ "type": "string"+ },+ "detail": {+ "type": [+ "string",+ "null"+ ]+ },+ "message": {+ "type": "string"+ },+ "retryable": {+ "type": "boolean"+ }+ },+ "required": [+ "code",+ "message",+ "retryable"+ ],+ "type": "object"+ }+ },{"name": "press_key","description": "Press one key, with optional modifiers, in the foreground desktop application.",diff --git a/libs/cua-driver/docs/perception-extension.md b/libs/cua-driver/docs/perception-extension.mdnew file mode 100644index 0000000000..87001b549e--- /dev/null+++ b/libs/cua-driver/docs/perception-extension.md@@ -0,0 +1,144 @@+# Optional perception extension++`parse_visual_regions` is a model-neutral Cua Driver tool backed by the+separately installed `cua-perception` extension. It parses one screenshot into+text and icon regions. It does not capture the screen, choose an action, or+send input.++The extension is absent from the default MIT-licensed Driver installation.+Driver startup, capture, parsing, and update checks never install it or+download model weights. A missing extension returns `not_installed`, allowing+the caller to continue with accessibility, typed browser state, or its own+visual reasoning.++## Local image CLI++The read-only CLI convenience mode parses an existing local PNG through the+same installed worker and canonical visual-region validation:++```bash+cua-driver perception parse \+ --image /tmp/window.png \+ --capture /tmp/capture.json \+ --json+```++The capture metadata file has this strict shape:++```json+{+ "source": { "kind": "window", "pid": 844, "window_id": 10725 },+ "snapshot_id": "s0000002a",+ "captured_at": "2026-09-18T12:00:00Z"+}+```++For the primary desktop, use+`{"source":{"kind":"primary_desktop","display_id":"primary"}}`.+`snapshot_id` and `captured_at` are optional. The command validates and hashes+the PNG header and declared image bounds, but it does not decode pixels in the+privileged CLI, create or retain a Driver capture, or include the local input+paths in its output. The JSON result has schema `cua.visual_regions_v1` plus a+`local_input` provenance block that sets `action_eligible` to `false` and+`action_authority` to `none`. Its `local_png_<digest>` label uses a separate+namespace from Driver `capture_<namespace>_<sequence>` IDs and cannot authorize+a Driver action.++Because `--json` is required, every failure is written to stdout as one stable+envelope and the process exits nonzero:++```json+{+ "ok": false,+ "error": {+ "code": "invalid_capture_metadata",+ "message": "captured_at must be an RFC3339 timestamp",+ "retryable": false+ }+}+```++CLI admission codes are `invalid_arguments`, `input_open_failed`,+`input_not_regular_file`, `input_too_large`, `input_read_failed`,+`invalid_capture_metadata`, `invalid_png`, and `internal_error`. Worker and+extension failures preserve the visual parsing codes, including+`not_installed`, `artifact_invalid`, `incompatible_protocol`, timeout, worker,+resource-limit, and inference failures. An optional `detail` string provides+diagnostic context and must not be parsed as a stable field.++## Explicit lifecycle++Use the signed catalog distributed with the reviewed candidate and inspect the+exact target before changing local state:++```bash+cua-driver extension inspect cua-perception --catalog <catalog.json>+cua-driver extension install cua-perception --catalog <catalog.json>+cua-driver extension status cua-perception+```++Inspection must identify the extension version, platform target, protocol+range, capabilities, artifact sizes and hashes, publisher, licenses, notices,+and provenance. Do not substitute an unsigned archive or infer component+availability from the repository-wide latest release.++Inspect a replacement before running `extension update`. Remove only the+extension-owned installation with `extension remove cua-perception`. Neither+operation changes the default Driver or an external `cua-som` installation.++## Capture-bound parse and action++Keep capture, parse, action, and reobservation on one persistent MCP connection+or typed SDK runtime. Each one-shot CLI process owns a disposable capture+registry, so a later process cannot resolve its `capture_id`.++1. Call `get_window_state` for the exact native `(pid, window_id)` target. Use+ `get_desktop_state` only when full-desktop observation is explicitly allowed+ and a window capture cannot represent the task.+2. Retain the returned native `capture_id`, source, PNG dimensions, and+ action-coordinate mapping. An accessibility `snapshot_id` is a different+ identity.+3. Call `parse_visual_regions` with that capture ID and bounded `kinds`,+ `min_confidence`, and `max_regions` options.+4. Prefer a current accessibility element or typed browser ref. If pixels are+ required, choose a point inside one current region and send one `click` with+ `x`, `y`, the exact target, `delivery_mode`, and the same `capture_id`.+5. Reobserve after every action attempt. Never remove `capture_id` and retry an+ expired, stale, retired, or mismatched capture as an unbound click.++A capture-bound click consumes the capture before native dispatch. At most one+action may derive from a capture. Capture again after an action, timeout,+unknown result, resize, move, scroll, navigation, display-layout change, or+target-identity change.++Window parsing does not imply background input support. Driver first applies+the selected platform's normal background route. A structured+`background_unavailable` refusal does not authorize a foreground retry.+`delivery_mode:"foreground"` may change focus, workspace, or the system cursor+and requires the workflow's existing foreground authorization. Desktop input+is foreground/system input even when the parsed screenshot came from Driver.++## Worker boundary and errors++The worker receives only the admitted PNG and bounded parse options. It has no+desktop capture, accessibility, browser, input, credential-store, or provider+credential authority. The local worker performs no network access and does not+require Python.++Treat `capture_not_found`, `capture_expired`, `capture_stale`, and+`capture_generation_mismatch` as a request to capture again. Preserve+`unsupported_target` and `unsupported_platform` as explicit limitations. Stop+using the extension after `incompatible_protocol` or `artifact_invalid` until+the exact installed artifact is inspected. Never act from a partial result+after a worker failure, timeout, invalid frame, or resource-limit error.++## Distribution boundary++The extension artifact has its own license and source obligations. The current+candidate ledgers identify the OmniParser detector artifact as AGPL-3.0-only,+the PP-OCR detector and recognizer artifacts as Apache-2.0, and the packaged+ONNX Runtime by an exact version and hash selected at assembly time. Read the+[perception third-party notices](perception-third-party-notices.md). A release+must include the reviewed notices, ledgers, SBOM, source/conversion materials,+and any corresponding-source offer required for the way the artifact is+distributed or offered over a network.diff --git a/libs/cua-driver/docs/perception-third-party-notices.md b/libs/cua-driver/docs/perception-third-party-notices.mdnew file mode 100644index 0000000000..cf9e1733e4--- /dev/null+++ b/libs/cua-driver/docs/perception-third-party-notices.md@@ -0,0 +1,66 @@+# Cua perception third-party notices++This document describes the reviewed candidate inputs. It is not a substitute+for the `NOTICE`, model ledger, source ledger, SBOM, and license texts shipped+with an exact `cua-perception` artifact. If those authenticated records are+missing or disagree with this summary, do not publish or redistribute the+artifact.++The default Cua Driver remains a separate MIT-licensed component and does not+include the extension, model weights, or ONNX Runtime library.++## OmniParser icon detector++- Origin: `microsoft/OmniParser-v2.0` model repository.+- Pinned revision: `6600256cb0f1b07651e3bc86166196307bad7e2d`.+- Source model: `icon_detect/model.pt`, SHA-256+ `dab3d4351ad00b035db829909a4db98354d5a90f6990e4ac00222a9a95d4bf57`.+- Reviewed converted ONNX artifact: SHA-256+ `d8a876bf7f9fb73d7da9432904ade7fa78e092e9a91674e5a2806b45562a9ab2`.+- Artifact license recorded by the release ledger: AGPL-3.0-only.++The release ledger marks this artifact `license-review-required`. Publication+must remain blocked until that review passes. A distributor must preserve the+AGPL-3.0-only license and notices and provide the corresponding source and+pinned conversion/export material required for this artifact. Network use of a+covered modified version may also trigger the license's corresponding-source+requirements. The artifact must not be presented as MIT merely because Driver+invokes it through an extension protocol.++The OmniParser source repository's license for repository content and the+separate model repository's artifact terms are different records. Verify the+exact model revision above.++## PP-OCRv5++The reviewed OCR inputs are official PaddlePaddle model repositories and are+recorded as Apache-2.0:++| Role | Repository revision | Reviewed ONNX SHA-256 |+| --- | --- | --- |+| Mobile detector | `PaddlePaddle/PP-OCRv5_mobile_det_onnx` at `e6f4fa85f00e168c862bc462aebca69eef9b3d3d` | `a431985659dc921974177a95adcfbb90fd9e51989a5e04d70d0b75f597b6e61d` |+| English recognizer | `PaddlePaddle/en_PP-OCRv5_mobile_rec_onnx` at `3fafbc3b5dcf93dd72add9f48368be8a3a2cd33b` | `b5f833dfc5d0eb71da397b4efa06ebeee9b431b690a47d6af40d77d8eabc557f` |++The recognizer dictionary comes from the pinned recognizer repository's+`inference.yml`, SHA-256+`27e91d0582f40168aa218303c76e184bc78fa7a5d105aad0cfbad8458b441067`.+Preserve the Apache-2.0 license and any notices in the assembled artifact.++## ONNX Runtime and conversion provenance++The worker loads a CPU-only ONNX Runtime dynamic library from the extension+package. Its upstream is Microsoft's+[`microsoft/onnxruntime`](https://github.com/microsoft/onnxruntime) project,+which publishes ONNX Runtime under the MIT license. The reviewed candidate lock+pins official CPU-only ONNX Runtime 1.26.0 archives for each supported target.+Assembly must verify the selected archive and library hashes and record the+exact version, target, SHA-256, license, notices, and source location in the+artifact manifest and SBOM. These candidate records are not evidence that a+particular runtime shipped.++The reviewed OmniParser conversion used Python 3.12.13, PyTorch 2.8.0,+torchvision 0.23.0, Ultralytics 8.3.199, ONNX 1.19.0, ONNX Runtime 1.22.1, opset+17, a fixed 1280 input, graph simplification, and no model-side NMS. These are+conversion-provenance inputs; the Rust worker has no Python runtime dependency.+The ONNX Runtime version used during conversion does not establish which+runtime library was packaged for a release.diff --git a/libs/cua-driver/docs/test-harnesses-guide.md b/libs/cua-driver/docs/test-harnesses-guide.mdindex 17671d546c..cade349248 100644--- a/libs/cua-driver/docs/test-harnesses-guide.md+++ b/libs/cua-driver/docs/test-harnesses-guide.md@@ -283,6 +283,11 @@ background delivery is tested.Canonical runner: `libs/cua-driver/tests/runners/macos-lume/run-all.sh`+Canonical Actions wrapper: manually dispatch+`.github/workflows/e2e-rust-macos.yml` in `lume` mode at the exact source SHA. It runs the+logged-in Lume wrapper with `--standalone-browser` and emits the certification+artifact consumed by protected evidence workflows.+Supplemental hosted runner: manually dispatch`.github/workflows/e2e-rust-macos.yml` with an exact 40-character source SHA.Its probe must pass before independent shared, native, and capture jobs run.diff --git a/libs/cua-driver/examples/jev-use/python/core.py b/libs/cua-driver/examples/jev-use/python/core.pyindex c333e16f20..2de0abcc05 100644--- a/libs/cua-driver/examples/jev-use/python/core.py+++ b/libs/cua-driver/examples/jev-use/python/core.py@@ -273,8 +273,7 @@ def build_candidates(matches = [regionfor region in visual.regions- if region.interactive- and region.confidence >= 0.8+ if region.confidence >= 0.8and _ascii_lower(region.text or region.label or "") == "submit"]if len(matches) == 1:diff --git a/libs/cua-driver/examples/jev-use/python/jev_adapter.py b/libs/cua-driver/examples/jev-use/python/jev_adapter.pyindex 74a71e3a7d..0ab10202d2 100644--- a/libs/cua-driver/examples/jev-use/python/jev_adapter.py+++ b/libs/cua-driver/examples/jev-use/python/jev_adapter.py@@ -29,10 +29,10 @@ def choose_bounded_with_typesafe(from typesafe_sdk import Choiceresponse = client.system_one(- state={"goal": goal, "observation": dict(observation)},+ state={"observation": dict(observation)},questions={"candidate": Choice(- instructions="Select exactly one supplied candidate ID.",+ instructions=goal,criteria=dict(criteria),)},diff --git a/libs/cua-driver/examples/jev-use/python/tests/test_choose_action.py b/libs/cua-driver/examples/jev-use/python/tests/test_choose_action.pyindex 12b6c692c3..960fc917d4 100644--- a/libs/cua-driver/examples/jev-use/python/tests/test_choose_action.py+++ b/libs/cua-driver/examples/jev-use/python/tests/test_choose_action.py@@ -79,6 +79,11 @@ class ChooseActionTest(unittest.TestCase):self.assertEqual(response["model"], "jev-test")criteria = client.sent["questions"]["candidate"].criteriaself.assertEqual(set(criteria), {"submit-form", "reobserve", "abstain"})+ self.assertEqual(+ client.sent["questions"]["candidate"].instructions,+ request()["goal"],+ )+ self.assertEqual(set(client.sent["state"]), {"observation"})observation = client.sent["state"]["observation"]self.assertEqual(observation["capture_id"], "capture-1")self.assertEqual(observation["regions"][0]["id"], "submit")diff --git a/libs/cua-driver/examples/jev-use/python/tests/test_core.py b/libs/cua-driver/examples/jev-use/python/tests/test_core.pyindex 337c617584..4ca0dd89ac 100644--- a/libs/cua-driver/examples/jev-use/python/tests/test_core.py+++ b/libs/cua-driver/examples/jev-use/python/tests/test_core.py@@ -60,8 +60,9 @@ class CoreTest(unittest.TestCase):self.assertEqual([candidate.id for candidate in candidates], ["reobserve", "abstain"])self.assertEqual(choose_mock(candidates)[0], "reobserve")- def test_visual_fixture_builds_equivalent_capture_bound_submit_candidate(self) -> None:+ def test_visual_fixture_builds_candidate_without_claiming_interactivity(self) -> None:payload = json.loads((FIXTURES / "parse-visual-regions-submit-v1.json").read_text())+ payload["regions"][0]["interactive"] = Falsevisual = parse_visual_regions(payload,expected_capture_id="capture-submit",@@ -90,6 +91,8 @@ class CoreTest(unittest.TestCase):def test_visual_ambiguity_offers_only_reserved_candidates(self) -> None:payload = json.loads((FIXTURES / "parse-visual-regions-ambiguous-v1.json").read_text())+ for region in payload["regions"]:+ region["interactive"] = Falsevisual = parse_visual_regions(payload,expected_capture_id="capture-ambiguous",@@ -108,6 +111,29 @@ class CoreTest(unittest.TestCase):["reobserve", "abstain"],)+ def test_visual_non_submit_observation_offers_only_reserved_candidates(self) -> None:+ payload = json.loads((FIXTURES / "parse-visual-regions-submit-v1.json").read_text())+ payload["regions"][0]["text"] = "Continue"+ payload["regions"][0]["interactive"] = True+ visual = parse_visual_regions(+ payload,+ expected_capture_id="capture-submit",+ expected_pid=7,+ expected_window_id=9,+ )+ page = self.snapshot("expected")+ page["refs"] = page["refs"][:1]++ self.assertEqual(+ [+ candidate.id+ for candidate in build_candidates(+ page, "expected", visual, capture_bound_click=True+ )+ ],+ ["reobserve", "abstain"],+ )+def test_visual_candidate_requires_capture_bound_click_contract(self) -> None:payload = json.loads((FIXTURES / "parse-visual-regions-submit-v1.json").read_text())visual = parse_visual_regions(diff --git a/libs/cua-driver/examples/jev-use/typescript/choose_action.test.ts b/libs/cua-driver/examples/jev-use/typescript/choose_action.test.tsindex 213f6599c6..045e89f057 100644--- a/libs/cua-driver/examples/jev-use/typescript/choose_action.test.ts+++ b/libs/cua-driver/examples/jev-use/typescript/choose_action.test.ts@@ -54,6 +54,8 @@ test('bounded chooser uses the SDK and preserves provider model identity', asyncnew Set(Object.keys(sent?.questions.candidate.criteria)),new Set(['submit-form', 'reobserve', 'abstain']));+ assert.equal(sent?.questions.candidate.instructions, request().goal);+ assert.deepEqual(Object.keys(sent?.state ?? {}), ['observation']);const observation = JSON.parse(sent?.state.observation);assert.equal(observation.capture_id, 'capture-fixture-1');assert.equal(observation.regions[0].id, 'submit-text');diff --git a/libs/cua-driver/examples/jev-use/typescript/core.test.ts b/libs/cua-driver/examples/jev-use/typescript/core.test.tsindex 7fc44e49d5..832750f43d 100644--- a/libs/cua-driver/examples/jev-use/typescript/core.test.ts+++ b/libs/cua-driver/examples/jev-use/typescript/core.test.ts@@ -74,9 +74,11 @@ test('reserved candidates are always available', () => {assert.equal(chooseMock(candidates).choice, 'reobserve');});-test('visual fixture builds the equivalent immutable capture-bound submit candidate', () => {+test('visual fixture builds a candidate without claiming interactivity', () => {+ const payload = fixture('parse-visual-regions-submit-v1.json');+ payload.regions[0].interactive = false;const visual = parseVisualRegions(- fixture('parse-visual-regions-submit-v1.json'),+ payload,'capture-submit',7,9@@ -102,8 +104,10 @@ test('visual fixture builds the equivalent immutable capture-bound submit candid});test('ambiguous visual regions offer only reobserve and abstain', () => {+ const payload = fixture('parse-visual-regions-ambiguous-v1.json');+ for (const region of payload.regions) region.interactive = false;const visual = parseVisualRegions(- fixture('parse-visual-regions-ambiguous-v1.json'),+ payload,'capture-ambiguous',7,9@@ -116,6 +120,19 @@ test('ambiguous visual regions offer only reobserve and abstain', () => {);});+test('non-Submit visual observation offers only reobserve and abstain', () => {+ const payload = fixture('parse-visual-regions-submit-v1.json');+ payload.regions[0].text = 'Continue';+ payload.regions[0].interactive = true;+ const visual = parseVisualRegions(payload, 'capture-submit', 7, 9);+ const page = snapshot('expected');+ page.refs = page.refs.slice(0, 1);+ assert.deepEqual(+ buildCandidates(page, 'expected', visual, true).map((candidate) => candidate.id),+ ['reobserve', 'abstain']+ );+});+test('visual candidate requires the capture-bound click contract', () => {const visual = parseVisualRegions(fixture('parse-visual-regions-submit-v1.json'),diff --git a/libs/cua-driver/examples/jev-use/typescript/core.ts b/libs/cua-driver/examples/jev-use/typescript/core.tsindex 12c9338e03..fc7145fdd3 100644--- a/libs/cua-driver/examples/jev-use/typescript/core.ts+++ b/libs/cua-driver/examples/jev-use/typescript/core.ts@@ -246,7 +246,6 @@ export function buildCandidates() {const matches = visual.regions.filter((region) =>- region.interactive &®ion.confidence >= 0.8 &&asciiLower(region.text ?? region.label ?? '') === 'submit');diff --git a/libs/cua-driver/examples/jev-use/typescript/jev_adapter.ts b/libs/cua-driver/examples/jev-use/typescript/jev_adapter.tsindex 2c6c14c895..ad48bac3f5 100644--- a/libs/cua-driver/examples/jev-use/typescript/jev_adapter.ts+++ b/libs/cua-driver/examples/jev-use/typescript/jev_adapter.ts@@ -24,11 +24,10 @@ export async function chooseBoundedWithTypeSafe(): Promise<ProviderChoice> {const response = await client.systemOne({state: {- goal,observation: JSON.stringify(observation),},questions: {- candidate: choice('Select exactly one supplied candidate ID.', { ...criteria }),+ candidate: choice(goal, { ...criteria }),},});const answer = response.answers.candidate;diff --git a/libs/cua-driver/python/src/cua_driver/__init__.py b/libs/cua-driver/python/src/cua_driver/__init__.pyindex 5af9acc2d0..ec9a1e7368 100644--- a/libs/cua-driver/python/src/cua_driver/__init__.py+++ b/libs/cua-driver/python/src/cua_driver/__init__.py@@ -115,6 +115,9 @@ from ._native_contract import (HotkeyInput,InvokeMenuInput,MoveCursorInput,+ ParseVisualRegionsInput,+ ParseVisualRegionsOptions,+ ParseVisualRegionsOutput,Platform,PredicateOutcome,PressKeyInput,@@ -131,6 +134,18 @@ from ._native_contract import (StatePredicate,TypeTextInput,UnknownReason,+ VisualActionCoordinateSpace,+ VisualCaptureProvenance,+ VisualCaptureSource,+ VisualParseError,+ VisualParseErrorCode,+ VisualParseTiming,+ VisualParseWarning,+ VisualParserMetadata,+ VisualRegion,+ VisualRegionBounds,+ VisualRegionKind,+ VisualScreenshotReference,VerificationStatus,VerifyStateInput,VerifyStateOutput,@@ -296,6 +311,9 @@ __all__ = ["ImageContent","MacOsPermissionStatus","MoveCursorInput",+ "ParseVisualRegionsInput",+ "ParseVisualRegionsOptions",+ "ParseVisualRegionsOutput","Platform","PredicateOutcome","PrivateWorkerOptions",@@ -317,6 +335,18 @@ __all__ = ["TrustedSessionOptions","TypeTextInput","UnknownReason",+ "VisualActionCoordinateSpace",+ "VisualCaptureProvenance",+ "VisualCaptureSource",+ "VisualParseError",+ "VisualParseErrorCode",+ "VisualParseTiming",+ "VisualParseWarning",+ "VisualParserMetadata",+ "VisualRegion",+ "VisualRegionBounds",+ "VisualRegionKind",+ "VisualScreenshotReference","VerificationStatus","VerifyStateInput","VerifyStateOutput",diff --git a/libs/cua-driver/python/src/cua_driver/_native.py b/libs/cua-driver/python/src/cua_driver/_native.pyindex dbedf1d88c..a2e0d20f34 100644--- a/libs/cua-driver/python/src/cua_driver/_native.py+++ b/libs/cua-driver/python/src/cua_driver/_native.py@@ -572,6 +572,8 @@ def _uniffi_check_api_checksums(lib):raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_driver_sdk_checksum_method_cuadriver_move_cursor() != 18320:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")+ if lib.uniffi_cua_driver_sdk_checksum_method_cuadriver_parse_visual_regions() != 15013:+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_driver_sdk_checksum_method_cuadriver_press_key() != 63712:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_driver_sdk_checksum_method_cuadriver_runtime_scope_prefix() != 2453:@@ -638,6 +640,8 @@ def _uniffi_check_api_checksums(lib):raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_move_cursor() != 35768:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")+ if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_parse_visual_regions() != 31748:+ raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_press_key() != 36768:raise InternalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")if lib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_scroll() != 8013:@@ -1377,6 +1381,11 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_move_cursor.argtypes = (cua_driver._native_contract._UniffiRustBuffer,)_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_move_cursor.restype = ctypes.c_uint64+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_parse_visual_regions.argtypes = (+ ctypes.c_uint64,+ cua_driver._native_contract._UniffiRustBuffer,+)+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_parse_visual_regions.restype = ctypes.c_uint64_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_press_key.argtypes = (ctypes.c_uint64,cua_driver._native_contract._UniffiRustBuffer,@@ -1542,6 +1551,11 @@ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_move_cursor.argtypescua_driver._native_contract._UniffiRustBuffer,)_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_move_cursor.restype = ctypes.c_uint64+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_parse_visual_regions.argtypes = (+ ctypes.c_uint64,+ cua_driver._native_contract._UniffiRustBuffer,+)+_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_parse_visual_regions.restype = ctypes.c_uint64_UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_press_key.argtypes = (ctypes.c_uint64,cua_driver._native_contract._UniffiRustBuffer,@@ -1828,6 +1842,9 @@ _UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_metadata.restype = ct_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_move_cursor.argtypes = ()_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_move_cursor.restype = ctypes.c_uint16+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_parse_visual_regions.argtypes = (+)+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_parse_visual_regions.restype = ctypes.c_uint16_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_press_key.argtypes = ()_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriver_press_key.restype = ctypes.c_uint16@@ -1927,6 +1944,9 @@ _UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_list_windows.r_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_move_cursor.argtypes = ()_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_move_cursor.restype = ctypes.c_uint16+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_parse_visual_regions.argtypes = (+)+_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_parse_visual_regions.restype = ctypes.c_uint16_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_press_key.argtypes = ()_UniffiLib.uniffi_cua_driver_sdk_checksum_method_cuadriversession_press_key.restype = ctypes.c_uint16@@ -5553,6 +5573,8 @@ class _UniffiFfiConverterTypeSdkClientKind(_UniffiConverterRustBuffer):++@@ -5621,6 +5643,8 @@ class CuaDriverProtocol(typing.Protocol):raise NotImplementedErrorasync def move_cursor(self, input: cua_driver._native_contract.MoveCursorInput) -> ToolResult:raise NotImplementedError+ async def parse_visual_regions(self, input: cua_driver._native_contract.ParseVisualRegionsInput) -> ToolResult:+ raise NotImplementedErrorasync def press_key(self, input: cua_driver._native_contract.PressKeyInput) -> ToolResult:raise NotImplementedErrordef runtime_scope_prefix(self, ) -> typing.Optional[str]:@@ -6415,6 +6439,23 @@ class CuaDriver(CuaDriverProtocol):_uniffi_lift_return,_uniffi_error_converter,)+ async def parse_visual_regions(self, input: cua_driver._native_contract.ParseVisualRegionsInput) -> ToolResult:++ cua_driver._native_contract._UniffiFfiConverterTypeParseVisualRegionsInput.check_lower(input)+ _uniffi_lowered_args = (+ self._uniffi_clone_handle(),+ cua_driver._native_contract._UniffiFfiConverterTypeParseVisualRegionsInput.lower(input),+ )+ _uniffi_lift_return = _UniffiFfiConverterTypeToolResult.lift+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError+ return await _uniffi_rust_call_async(+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriver_parse_visual_regions(*_uniffi_lowered_args),+ _UniffiLib.ffi_cua_driver_sdk_rust_future_poll_rust_buffer,+ _UniffiLib.ffi_cua_driver_sdk_rust_future_complete_rust_buffer,+ _UniffiLib.ffi_cua_driver_sdk_rust_future_free_rust_buffer,+ _uniffi_lift_return,+ _uniffi_error_converter,+ )async def press_key(self, input: cua_driver._native_contract.PressKeyInput) -> ToolResult:cua_driver._native_contract._UniffiFfiConverterTypePressKeyInput.check_lower(input)@@ -6695,6 +6736,8 @@ class CuaDriverSessionProtocol(typing.Protocol):raise NotImplementedErrorasync def move_cursor(self, input: cua_driver._native_contract.MoveCursorInput) -> ToolResult:raise NotImplementedError+ async def parse_visual_regions(self, input: cua_driver._native_contract.ParseVisualRegionsInput) -> ToolResult:+ raise NotImplementedErrorasync def press_key(self, input: cua_driver._native_contract.PressKeyInput) -> ToolResult:raise NotImplementedErrorasync def scroll(self, input: cua_driver._native_contract.ScrollInput) -> ToolResult:@@ -7099,6 +7142,23 @@ class CuaDriverSession(CuaDriverSessionProtocol):_uniffi_lift_return,_uniffi_error_converter,)+ async def parse_visual_regions(self, input: cua_driver._native_contract.ParseVisualRegionsInput) -> ToolResult:++ cua_driver._native_contract._UniffiFfiConverterTypeParseVisualRegionsInput.check_lower(input)+ _uniffi_lowered_args = (+ self._uniffi_clone_handle(),+ cua_driver._native_contract._UniffiFfiConverterTypeParseVisualRegionsInput.lower(input),+ )+ _uniffi_lift_return = _UniffiFfiConverterTypeToolResult.lift+ _uniffi_error_converter = _UniffiFfiConverterTypeDriverError+ return await _uniffi_rust_call_async(+ _UniffiLib.uniffi_cua_driver_sdk_fn_method_cuadriversession_parse_visual_regions(*_uniffi_lowered_args),+ _UniffiLib.ffi_cua_driver_sdk_rust_future_poll_rust_buffer,+ _UniffiLib.ffi_cua_driver_sdk_rust_future_complete_rust_buffer,+ _UniffiLib.ffi_cua_driver_sdk_rust_future_free_rust_buffer,+ _uniffi_lift_return,+ _uniffi_error_converter,+ )async def press_key(self, input: cua_driver._native_contract.PressKeyInput) -> ToolResult:cua_driver._native_contract._UniffiFfiConverterTypePressKeyInput.check_lower(input)diff --git a/libs/cua-driver/python/src/cua_driver/_native_contract.py b/libs/cua-driver/python/src/cua_driver/_native_contract.pyindex 2246229c17..8773cdaaa4 100644--- a/libs/cua-driver/python/src/cua_driver/_native_contract.py+++ b/libs/cua-driver/python/src/cua_driver/_native_contract.py@@ -1843,6 +1843,40 @@ class ClickPosition:return Falsereturn True+ @dataclass+ class CAPTURED_COORDINATES:++ def __init__(self, x:float, y:float, capture_id:str):+ self.x = x+++ self.y = y+++ self.capture_id = capture_id+++ pass++++++ def __str__(self):+ return "ClickPosition.CAPTURED_COORDINATES(x={}, y={}, capture_id={})".format(self.x, self.y, self.capture_id)+ def __eq__(self, other):+ if not isinstance(other, ClickPosition):+ return NotImplemented+ if not other.is_CAPTURED_COORDINATES():+ return False+ if self.x != other.x:+ return False+ if self.y != other.y:+ return False+ if self.capture_id != other.capture_id:+ return False+ return True+# For each variant, we have `is_NAME` and `is_name` methods for easily checking@@ -1855,6 +1889,10 @@ class ClickPosition:return isinstance(self, ClickPosition.ELEMENT)def is_element(self) -> bool:return isinstance(self, ClickPosition.ELEMENT)+ def is_CAPTURED_COORDINATES(self) -> bool:+ return isinstance(self, ClickPosition.CAPTURED_COORDINATES)+ def is_captured_coordinates(self) -> bool:+ return isinstance(self, ClickPosition.CAPTURED_COORDINATES)# Now, a little trick - we make each nested variant class be a subclass of the main@@ -1862,6 +1900,7 @@ class ClickPosition:# We might be able to do this a little more neatly with a metaclass, but this'll do.ClickPosition.COORDINATES = type("ClickPosition.COORDINATES", (ClickPosition.COORDINATES, ClickPosition,), {}) # type: ignoreClickPosition.ELEMENT = type("ClickPosition.ELEMENT", (ClickPosition.ELEMENT, ClickPosition,), {}) # type: ignore+ClickPosition.CAPTURED_COORDINATES = type("ClickPosition.CAPTURED_COORDINATES", (ClickPosition.CAPTURED_COORDINATES, ClickPosition,), {}) # type: ignore@@ -1879,6 +1918,12 @@ class _UniffiFfiConverterTypeClickPosition(_UniffiConverterRustBuffer):return ClickPosition.ELEMENT(_UniffiFfiConverterString.read(buf),)+ if variant == 3:+ return ClickPosition.CAPTURED_COORDINATES(+ _UniffiFfiConverterFloat64.read(buf),+ _UniffiFfiConverterFloat64.read(buf),+ _UniffiFfiConverterString.read(buf),+ )raise InternalError("Raw enum value doesn't match any cases")@staticmethod@@ -1890,6 +1935,11 @@ class _UniffiFfiConverterTypeClickPosition(_UniffiConverterRustBuffer):if value.is_ELEMENT():_UniffiFfiConverterString.check_lower(value.element_token)return+ if value.is_CAPTURED_COORDINATES():+ _UniffiFfiConverterFloat64.check_lower(value.x)+ _UniffiFfiConverterFloat64.check_lower(value.y)+ _UniffiFfiConverterString.check_lower(value.capture_id)+ returnraise ValueError(value)@staticmethod@@ -1901,6 +1951,11 @@ class _UniffiFfiConverterTypeClickPosition(_UniffiConverterRustBuffer):if value.is_ELEMENT():buf.write_i32(2)_UniffiFfiConverterString.write(value.element_token, buf)+ if value.is_CAPTURED_COORDINATES():+ buf.write_i32(3)+ _UniffiFfiConverterFloat64.write(value.x, buf)+ _UniffiFfiConverterFloat64.write(value.y, buf)+ _UniffiFfiConverterString.write(value.capture_id, buf)@@ -3557,7 +3612,7 @@ class _UniffiFfiConverterTypeGetSessionStateInput(_UniffiConverterRustBuffer):@dataclassclass GetWindowStateInput:- def __init__(self, *, pid:int, window_id:int, session:typing.Optional[str], query:typing.Optional[str], include_accessibility_tree:typing.Optional[bool], include_screenshot:typing.Optional[bool], screenshot_out_file:typing.Optional[str], max_elements:typing.Optional[int], max_depth:typing.Optional[int], max_dimension:typing.Optional[int]):+ def __init__(self, *, pid:int, window_id:int, session:typing.Optional[str], query:typing.Optional[str], include_accessibility_tree:typing.Optional[bool], include_screenshot:typing.Optional[bool], screenshot_out_file:typing.Optional[str], max_elements:typing.Optional[int], max_depth:typing.Optional[int], max_dimension:typing.Optional[int], max_image_dimension:typing.Optional[int]):self.pid = pidself.window_id = window_idself.session = session@@ -3568,12 +3623,13 @@ class GetWindowStateInput:self.max_elements = max_elementsself.max_depth = max_depthself.max_dimension = max_dimension+ self.max_image_dimension = max_image_dimensiondef __str__(self):- return "GetWindowStateInput(pid={}, window_id={}, session={}, query={}, include_accessibility_tree={}, include_screenshot={}, screenshot_out_file={}, max_elements={}, max_depth={}, max_dimension={})".format(self.pid, self.window_id, self.session, self.query, self.include_accessibility_tree, self.include_screenshot, self.screenshot_out_file, self.max_elements, self.max_depth, self.max_dimension)+ return "GetWindowStateInput(pid={}, window_id={}, session={}, query={}, include_accessibility_tree={}, include_screenshot={}, screenshot_out_file={}, max_elements={}, max_depth={}, max_dimension={}, max_image_dimension={})".format(self.pid, self.window_id, self.session, self.query, self.include_accessibility_tree, self.include_screenshot, self.screenshot_out_file, self.max_elements, self.max_depth, self.max_dimension, self.max_image_dimension)def __eq__(self, other):if self.pid != other.pid:return False@@ -3595,6 +3651,8 @@ class GetWindowStateInput:return Falseif self.max_dimension != other.max_dimension:return False+ if self.max_image_dimension != other.max_image_dimension:+ return Falsereturn Trueclass _UniffiFfiConverterTypeGetWindowStateInput(_UniffiConverterRustBuffer):@@ -3611,6 +3669,7 @@ class _UniffiFfiConverterTypeGetWindowStateInput(_UniffiConverterRustBuffer):max_elements=_UniffiFfiConverterOptionalUInt32.read(buf),max_depth=_UniffiFfiConverterOptionalUInt32.read(buf),max_dimension=_UniffiFfiConverterOptionalUInt32.read(buf),+ max_image_dimension=_UniffiFfiConverterOptionalUInt32.read(buf),)@staticmethod@@ -3625,6 +3684,7 @@ class _UniffiFfiConverterTypeGetWindowStateInput(_UniffiConverterRustBuffer):_UniffiFfiConverterOptionalUInt32.check_lower(value.max_elements)_UniffiFfiConverterOptionalUInt32.check_lower(value.max_depth)_UniffiFfiConverterOptionalUInt32.check_lower(value.max_dimension)+ _UniffiFfiConverterOptionalUInt32.check_lower(value.max_image_dimension)@staticmethoddef write(value, buf):@@ -3638,6 +3698,7 @@ class _UniffiFfiConverterTypeGetWindowStateInput(_UniffiConverterRustBuffer):_UniffiFfiConverterOptionalUInt32.write(value.max_elements, buf)_UniffiFfiConverterOptionalUInt32.write(value.max_depth, buf)_UniffiFfiConverterOptionalUInt32.write(value.max_dimension, buf)+ _UniffiFfiConverterOptionalUInt32.write(value.max_image_dimension, buf)@dataclassclass HotkeyInput:@@ -4577,134 +4638,69 @@ class _UniffiFfiConverterTypeMoveCursorInput(_UniffiConverterRustBuffer):-class VerificationStatus(enum.Enum):-- SATISFIED = 0+class VisualRegionKind(enum.Enum):- UNSATISFIED = 1+ TEXT = 0- UNKNOWN = 2+ ICON = 1-class _UniffiFfiConverterTypeVerificationStatus(_UniffiConverterRustBuffer):+class _UniffiFfiConverterTypeVisualRegionKind(_UniffiConverterRustBuffer):@staticmethoddef read(buf):variant = buf.read_i32()if variant == 1:- return VerificationStatus.SATISFIED+ return VisualRegionKind.TEXTif variant == 2:- return VerificationStatus.UNSATISFIED- if variant == 3:- return VerificationStatus.UNKNOWN+ return VisualRegionKind.ICONraise InternalError("Raw enum value doesn't match any cases")@staticmethoddef check_lower(value):- if value == VerificationStatus.SATISFIED:- return- if value == VerificationStatus.UNSATISFIED:+ if value == VisualRegionKind.TEXT:return- if value == VerificationStatus.UNKNOWN:+ if value == VisualRegionKind.ICON:returnraise ValueError(value)@staticmethoddef write(value, buf):- if value == VerificationStatus.SATISFIED:+ if value == VisualRegionKind.TEXT:buf.write_i32(1)- if value == VerificationStatus.UNSATISFIED:+ if value == VisualRegionKind.ICON:buf.write_i32(2)- if value == VerificationStatus.UNKNOWN:- buf.write_i32(3)-------class UnknownReason(enum.Enum):-- INVALID_PREDICATE = 0-- UNSUPPORTED_PREDICATE = 1-- UNTRUSTED_SOURCE = 2-- MULTI_MATCH = 3-- TARGET_MISSING = 4-- OBSERVATION_UNAVAILABLE = 5-- STABILITY_UNPROVEN = 6----class _UniffiFfiConverterTypeUnknownReason(_UniffiConverterRustBuffer):- @staticmethod- def read(buf):- variant = buf.read_i32()- if variant == 1:- return UnknownReason.INVALID_PREDICATE- if variant == 2:- return UnknownReason.UNSUPPORTED_PREDICATE- if variant == 3:- return UnknownReason.UNTRUSTED_SOURCE- if variant == 4:- return UnknownReason.MULTI_MATCH- if variant == 5:- return UnknownReason.TARGET_MISSING- if variant == 6:- return UnknownReason.OBSERVATION_UNAVAILABLE- if variant == 7:- return UnknownReason.STABILITY_UNPROVEN- raise InternalError("Raw enum value doesn't match any cases")- @staticmethod- def check_lower(value):- if value == UnknownReason.INVALID_PREDICATE:- return- if value == UnknownReason.UNSUPPORTED_PREDICATE:- return- if value == UnknownReason.UNTRUSTED_SOURCE:- return- if value == UnknownReason.MULTI_MATCH:- return- if value == UnknownReason.TARGET_MISSING:- return- if value == UnknownReason.OBSERVATION_UNAVAILABLE:- return- if value == UnknownReason.STABILITY_UNPROVEN:- return- raise ValueError(value)+class _UniffiFfiConverterSequenceTypeVisualRegionKind(_UniffiConverterRustBuffer):+ @classmethod+ def check_lower(cls, value):+ for item in value:+ _UniffiFfiConverterTypeVisualRegionKind.check_lower(item)- @staticmethod- def write(value, buf):- if value == UnknownReason.INVALID_PREDICATE:- buf.write_i32(1)- if value == UnknownReason.UNSUPPORTED_PREDICATE:- buf.write_i32(2)- if value == UnknownReason.UNTRUSTED_SOURCE:- buf.write_i32(3)- if value == UnknownReason.MULTI_MATCH:- buf.write_i32(4)- if value == UnknownReason.TARGET_MISSING:- buf.write_i32(5)- if value == UnknownReason.OBSERVATION_UNAVAILABLE:- buf.write_i32(6)- if value == UnknownReason.STABILITY_UNPROVEN:- buf.write_i32(7)+ @classmethod+ def write(cls, value, buf):+ items = len(value)+ buf.write_i32(items)+ for item in value:+ _UniffiFfiConverterTypeVisualRegionKind.write(item, buf)+ @classmethod+ def read(cls, buf):+ count = buf.read_i32()+ if count < 0:+ raise InternalError("Unexpected negative sequence length")+ return [+ _UniffiFfiConverterTypeVisualRegionKind.read(buf) for i in range(count)+ ]-class _UniffiFfiConverterOptionalTypeUnknownReason(_UniffiConverterRustBuffer):+class _UniffiFfiConverterOptionalSequenceTypeVisualRegionKind(_UniffiConverterRustBuffer):@classmethoddef check_lower(cls, value):if value is not None:- _UniffiFfiConverterTypeUnknownReason.check_lower(value)+ _UniffiFfiConverterSequenceTypeVisualRegionKind.check_lower(value)@classmethoddef write(cls, value, buf):@@ -4713,7 +4709,7 @@ class _UniffiFfiConverterOptionalTypeUnknownReason(_UniffiConverterRustBuffer):returnbuf.write_u8(1)- _UniffiFfiConverterTypeUnknownReason.write(value, buf)+ _UniffiFfiConverterSequenceTypeVisualRegionKind.write(value, buf)@classmethoddef read(cls, buf):@@ -4721,156 +4717,1230 @@ class _UniffiFfiConverterOptionalTypeUnknownReason(_UniffiConverterRustBuffer):if flag == 0:return Noneelif flag == 1:- return _UniffiFfiConverterTypeUnknownReason.read(buf)+ return _UniffiFfiConverterSequenceTypeVisualRegionKind.read(buf)else:raise InternalError("Unexpected flag byte for optional type")@dataclass-class PredicateOutcome:- def __init__(self, *, index:int, status:VerificationStatus, unknown_reason:typing.Optional[UnknownReason], observed_json:typing.Optional[str]):- self.index = index- self.status = status- self.unknown_reason = unknown_reason- self.observed_json = observed_json+class ParseVisualRegionsOptions:+ """+ Optional, model-neutral controls for one bounded parse.+"""+ def __init__(self, *, kinds:typing.Optional[typing.List[VisualRegionKind]], min_confidence:typing.Optional[float], max_regions:typing.Optional[int]):+ self.kinds = kinds+ self.min_confidence = min_confidence+ self.max_regions = max_regionsdef __str__(self):- return "PredicateOutcome(index={}, status={}, unknown_reason={}, observed_json={})".format(self.index, self.status, self.unknown_reason, self.observed_json)+ return "ParseVisualRegionsOptions(kinds={}, min_confidence={}, max_regions={})".format(self.kinds, self.min_confidence, self.max_regions)def __eq__(self, other):- if self.index != other.index:- return False- if self.status != other.status:+ if self.kinds != other.kinds:return False- if self.unknown_reason != other.unknown_reason:+ if self.min_confidence != other.min_confidence:return False- if self.observed_json != other.observed_json:+ if self.max_regions != other.max_regions:return Falsereturn True-class _UniffiFfiConverterTypePredicateOutcome(_UniffiConverterRustBuffer):+class _UniffiFfiConverterTypeParseVisualRegionsOptions(_UniffiConverterRustBuffer):@staticmethoddef read(buf):- return PredicateOutcome(- index=_UniffiFfiConverterUInt64.read(buf),- status=_UniffiFfiConverterTypeVerificationStatus.read(buf),- unknown_reason=_UniffiFfiConverterOptionalTypeUnknownReason.read(buf),- observed_json=_UniffiFfiConverterOptionalString.read(buf),+ return ParseVisualRegionsOptions(+ kinds=_UniffiFfiConverterOptionalSequenceTypeVisualRegionKind.read(buf),+ min_confidence=_UniffiFfiConverterOptionalFloat64.read(buf),+ max_regions=_UniffiFfiConverterOptionalUInt32.read(buf),)@staticmethoddef check_lower(value):- _UniffiFfiConverterUInt64.check_lower(value.index)- _UniffiFfiConverterTypeVerificationStatus.check_lower(value.status)- _UniffiFfiConverterOptionalTypeUnknownReason.check_lower(value.unknown_reason)- _UniffiFfiConverterOptionalString.check_lower(value.observed_json)+ _UniffiFfiConverterOptionalSequenceTypeVisualRegionKind.check_lower(value.kinds)+ _UniffiFfiConverterOptionalFloat64.check_lower(value.min_confidence)+ _UniffiFfiConverterOptionalUInt32.check_lower(value.max_regions)@staticmethoddef write(value, buf):- _UniffiFfiConverterUInt64.write(value.index, buf)- _UniffiFfiConverterTypeVerificationStatus.write(value.status, buf)- _UniffiFfiConverterOptionalTypeUnknownReason.write(value.unknown_reason, buf)- _UniffiFfiConverterOptionalString.write(value.observed_json, buf)+ _UniffiFfiConverterOptionalSequenceTypeVisualRegionKind.write(value.kinds, buf)+ _UniffiFfiConverterOptionalFloat64.write(value.min_confidence, buf)+ _UniffiFfiConverterOptionalUInt32.write(value.max_regions, buf)@dataclass-class PressKeyInput:- def __init__(self, *, key:str, target:typing.Optional[ActionTarget], scope:typing.Optional[DesktopScope], session:typing.Optional[str], modifiers:typing.Optional[typing.List[str]]):- self.key = key- self.target = target- self.scope = scope- self.session = session- self.modifiers = modifiers+class ParseVisualRegionsInput:+ """+ Transport-free request. Runtime use requires the future capture registry.+"""+ def __init__(self, *, capture_id:str, options:ParseVisualRegionsOptions):+ self.capture_id = capture_id+ self.options = optionsdef __str__(self):- return "PressKeyInput(key={}, target={}, scope={}, session={}, modifiers={})".format(self.key, self.target, self.scope, self.session, self.modifiers)+ return "ParseVisualRegionsInput(capture_id={}, options={})".format(self.capture_id, self.options)def __eq__(self, other):- if self.key != other.key:+ if self.capture_id != other.capture_id:return False- if self.target != other.target:- return False- if self.scope != other.scope:- return False- if self.session != other.session:- return False- if self.modifiers != other.modifiers:+ if self.options != other.options:return Falsereturn True-class _UniffiFfiConverterTypePressKeyInput(_UniffiConverterRustBuffer):+class _UniffiFfiConverterTypeParseVisualRegionsInput(_UniffiConverterRustBuffer):@staticmethoddef read(buf):- return PressKeyInput(- key=_UniffiFfiConverterString.read(buf),- target=_UniffiFfiConverterOptionalTypeActionTarget.read(buf),- scope=_UniffiFfiConverterOptionalTypeDesktopScope.read(buf),- session=_UniffiFfiConverterOptionalString.read(buf),- modifiers=_UniffiFfiConverterOptionalSequenceString.read(buf),+ return ParseVisualRegionsInput(+ capture_id=_UniffiFfiConverterString.read(buf),+ options=_UniffiFfiConverterTypeParseVisualRegionsOptions.read(buf),)@staticmethoddef check_lower(value):- _UniffiFfiConverterString.check_lower(value.key)- _UniffiFfiConverterOptionalTypeActionTarget.check_lower(value.target)- _UniffiFfiConverterOptionalTypeDesktopScope.check_lower(value.scope)- _UniffiFfiConverterOptionalString.check_lower(value.session)- _UniffiFfiConverterOptionalSequenceString.check_lower(value.modifiers)+ _UniffiFfiConverterString.check_lower(value.capture_id)+ _UniffiFfiConverterTypeParseVisualRegionsOptions.check_lower(value.options)@staticmethoddef write(value, buf):- _UniffiFfiConverterString.write(value.key, buf)- _UniffiFfiConverterOptionalTypeActionTarget.write(value.target, buf)- _UniffiFfiConverterOptionalTypeDesktopScope.write(value.scope, buf)- _UniffiFfiConverterOptionalString.write(value.session, buf)- _UniffiFfiConverterOptionalSequenceString.write(value.modifiers, buf)+ _UniffiFfiConverterString.write(value.capture_id, buf)+ _UniffiFfiConverterTypeParseVisualRegionsOptions.write(value.options, buf)-class ScrollDirection(enum.Enum):+class VisualCaptureSource:+ """+ Exact screen content that produced the immutable capture.+"""+ def __init__(self):+ raise RuntimeError("VisualCaptureSource cannot be instantiated directly")- UP = 0+ # Each enum variant is a nested class of the enum itself.+ @dataclass+ class WINDOW:- DOWN = 1+ def __init__(self, pid:int, window_id:int):+ self.pid = pid- LEFT = 2- RIGHT = 3+ self.window_id = window_id+ pass-class _UniffiFfiConverterTypeScrollDirection(_UniffiConverterRustBuffer):- @staticmethod- def read(buf):- variant = buf.read_i32()- if variant == 1:- return ScrollDirection.UP- if variant == 2:- return ScrollDirection.DOWN- if variant == 3:- return ScrollDirection.LEFT- if variant == 4:- return ScrollDirection.RIGHT- raise InternalError("Raw enum value doesn't match any cases")- @staticmethod- def check_lower(value):- if value == ScrollDirection.UP:- return- if value == ScrollDirection.DOWN:- return- if value == ScrollDirection.LEFT:- return- if value == ScrollDirection.RIGHT:- return- raise ValueError(value)- @staticmethod+++ def __str__(self):+ return "VisualCaptureSource.WINDOW(pid={}, window_id={})".format(self.pid, self.window_id)+ def __eq__(self, other):+ if not isinstance(other, VisualCaptureSource):+ return NotImplemented+ if not other.is_WINDOW():+ return False+ if self.pid != other.pid:+ return False+ if self.window_id != other.window_id:+ return False+ return True++ @dataclass+ class PRIMARY_DESKTOP:++ def __init__(self, display_id:str):+ self.display_id = display_id+++ pass++++++ def __str__(self):+ return "VisualCaptureSource.PRIMARY_DESKTOP(display_id={})".format(self.display_id)+ def __eq__(self, other):+ if not isinstance(other, VisualCaptureSource):+ return NotImplemented+ if not other.is_PRIMARY_DESKTOP():+ return False+ if self.display_id != other.display_id:+ return False+ return True++++ # For each variant, we have `is_NAME` and `is_name` methods for easily checking+ # whether an instance is that variant.+ def is_WINDOW(self) -> bool:+ return isinstance(self, VisualCaptureSource.WINDOW)+ def is_window(self) -> bool:+ return isinstance(self, VisualCaptureSource.WINDOW)+ def is_PRIMARY_DESKTOP(self) -> bool:+ return isinstance(self, VisualCaptureSource.PRIMARY_DESKTOP)+ def is_primary_desktop(self) -> bool:+ return isinstance(self, VisualCaptureSource.PRIMARY_DESKTOP)+++# Now, a little trick - we make each nested variant class be a subclass of the main+# enum class, so that method calls and instance checks etc will work intuitively.+# We might be able to do this a little more neatly with a metaclass, but this'll do.+VisualCaptureSource.WINDOW = type("VisualCaptureSource.WINDOW", (VisualCaptureSource.WINDOW, VisualCaptureSource,), {}) # type: ignore+VisualCaptureSource.PRIMARY_DESKTOP = type("VisualCaptureSource.PRIMARY_DESKTOP", (VisualCaptureSource.PRIMARY_DESKTOP, VisualCaptureSource,), {}) # type: ignore+++++class _UniffiFfiConverterTypeVisualCaptureSource(_UniffiConverterRustBuffer):+ @staticmethod+ def read(buf):+ variant = buf.read_i32()+ if variant == 1:+ return VisualCaptureSource.WINDOW(+ _UniffiFfiConverterUInt32.read(buf),+ _UniffiFfiConverterUInt64.read(buf),+ )+ if variant == 2:+ return VisualCaptureSource.PRIMARY_DESKTOP(+ _UniffiFfiConverterString.read(buf),+ )+ raise InternalError("Raw enum value doesn't match any cases")++ @staticmethod+ def check_lower(value):+ if value.is_WINDOW():+ _UniffiFfiConverterUInt32.check_lower(value.pid)+ _UniffiFfiConverterUInt64.check_lower(value.window_id)+ return+ if value.is_PRIMARY_DESKTOP():+ _UniffiFfiConverterString.check_lower(value.display_id)+ return+ raise ValueError(value)++ @staticmethod+ def write(value, buf):+ if value.is_WINDOW():+ buf.write_i32(1)+ _UniffiFfiConverterUInt32.write(value.pid, buf)+ _UniffiFfiConverterUInt64.write(value.window_id, buf)+ if value.is_PRIMARY_DESKTOP():+ buf.write_i32(2)+ _UniffiFfiConverterString.write(value.display_id, buf)++++@dataclass+class VisualScreenshotReference:+ """+ Screenshot identity and geometry retained by the future capture registry.+"""+ def __init__(self, *, reference:str, width:int, height:int, mime_type:str, sha256:typing.Optional[str]):+ self.reference = reference+ self.width = width+ self.height = height+ self.mime_type = mime_type+ self.sha256 = sha256+++++ def __str__(self):+ return "VisualScreenshotReference(reference={}, width={}, height={}, mime_type={}, sha256={})".format(self.reference, self.width, self.height, self.mime_type, self.sha256)+ def __eq__(self, other):+ if self.reference != other.reference:+ return False+ if self.width != other.width:+ return False+ if self.height != other.height:+ return False+ if self.mime_type != other.mime_type:+ return False+ if self.sha256 != other.sha256:+ return False+ return True++class _UniffiFfiConverterTypeVisualScreenshotReference(_UniffiConverterRustBuffer):+ @staticmethod+ def read(buf):+ return VisualScreenshotReference(+ reference=_UniffiFfiConverterString.read(buf),+ width=_UniffiFfiConverterUInt32.read(buf),+ height=_UniffiFfiConverterUInt32.read(buf),+ mime_type=_UniffiFfiConverterString.read(buf),+ sha256=_UniffiFfiConverterOptionalString.read(buf),+ )++ @staticmethod+ def check_lower(value):+ _UniffiFfiConverterString.check_lower(value.reference)+ _UniffiFfiConverterUInt32.check_lower(value.width)+ _UniffiFfiConverterUInt32.check_lower(value.height)+ _UniffiFfiConverterString.check_lower(value.mime_type)+ _UniffiFfiConverterOptionalString.check_lower(value.sha256)++ @staticmethod+ def write(value, buf):+ _UniffiFfiConverterString.write(value.reference, buf)+ _UniffiFfiConverterUInt32.write(value.width, buf)+ _UniffiFfiConverterUInt32.write(value.height, buf)+ _UniffiFfiConverterString.write(value.mime_type, buf)+ _UniffiFfiConverterOptionalString.write(value.sha256, buf)+++++++class VisualActionCoordinateSpace:+ """+ Normative mapping from source screenshot pixels to Driver action coordinates.++ Screenshot coordinates always originate at the encoded PNG's top-left; X+ increases right and Y increases down. The affine form maps a source point+ `(px, py)` exactly as:++ `action_x = m11 * px + m12 * py + tx`++ `action_y = m21 * px + m22 * py + ty`+"""+ def __init__(self):+ raise RuntimeError("VisualActionCoordinateSpace cannot be instantiated directly")++ # Each enum variant is a nested class of the enum itself.+ @dataclass+ class SCREENSHOT_PIXELS:+ """+ Action coordinates are the same physical pixel coordinates as the PNG.+"""++ def __init__(self, ):+ pass++++++ def __str__(self):+ return "VisualActionCoordinateSpace.SCREENSHOT_PIXELS()".format()+ def __eq__(self, other):+ if not isinstance(other, VisualActionCoordinateSpace):+ return NotImplemented+ if not other.is_SCREENSHOT_PIXELS():+ return False+ return True++ @dataclass+ class AFFINE:+ """+ Lossless six-coefficient affine transform retained by the capture registry.+"""++ def __init__(self, m11:float, m12:float, m21:float, m22:float, tx:float, ty:float):+ self.m11 = m11+++ self.m12 = m12+++ self.m21 = m21+++ self.m22 = m22+++ self.tx = tx+++ self.ty = ty+++ pass++++++ def __str__(self):+ return "VisualActionCoordinateSpace.AFFINE(m11={}, m12={}, m21={}, m22={}, tx={}, ty={})".format(self.m11, self.m12, self.m21, self.m22, self.tx, self.ty)+ def __eq__(self, other):+ if not isinstance(other, VisualActionCoordinateSpace):+ return NotImplemented+ if not other.is_AFFINE():+ return False+ if self.m11 != other.m11:+ return False+ if self.m12 != other.m12:+ return False+ if self.m21 != other.m21:+ return False+ if self.m22 != other.m22:+ return False+ if self.tx != other.tx:+ return False+ if self.ty != other.ty:+ return False+ return True++++ # For each variant, we have `is_NAME` and `is_name` methods for easily checking+ # whether an instance is that variant.+ def is_SCREENSHOT_PIXELS(self) -> bool:+ return isinstance(self, VisualActionCoordinateSpace.SCREENSHOT_PIXELS)+ def is_screenshot_pixels(self) -> bool:+ return isinstance(self, VisualActionCoordinateSpace.SCREENSHOT_PIXELS)+ def is_AFFINE(self) -> bool:+ return isinstance(self, VisualActionCoordinateSpace.AFFINE)+ def is_affine(self) -> bool:+ return isinstance(self, VisualActionCoordinateSpace.AFFINE)+++# Now, a little trick - we make each nested variant class be a subclass of the main+# enum class, so that method calls and instance checks etc will work intuitively.+# We might be able to do this a little more neatly with a metaclass, but this'll do.+VisualActionCoordinateSpace.SCREENSHOT_PIXELS = type("VisualActionCoordinateSpace.SCREENSHOT_PIXELS", (VisualActionCoordinateSpace.SCREENSHOT_PIXELS, VisualActionCoordinateSpace,), {}) # type: ignore+VisualActionCoordinateSpace.AFFINE = type("VisualActionCoordinateSpace.AFFINE", (VisualActionCoordinateSpace.AFFINE, VisualActionCoordinateSpace,), {}) # type: ignore+++++class _UniffiFfiConverterTypeVisualActionCoordinateSpace(_UniffiConverterRustBuffer):+ @staticmethod+ def read(buf):+ variant = buf.read_i32()+ if variant == 1:+ return VisualActionCoordinateSpace.SCREENSHOT_PIXELS(+ )+ if variant == 2:+ return VisualActionCoordinateSpace.AFFINE(+ _UniffiFfiConverterFloat64.read(buf),+ _UniffiFfiConverterFloat64.read(buf),+ _UniffiFfiConverterFloat64.read(buf),+ _UniffiFfiConverterFloat64.read(buf),+ _UniffiFfiConverterFloat64.read(buf),+ _UniffiFfiConverterFloat64.read(buf),+ )+ raise InternalError("Raw enum value doesn't match any cases")++ @staticmethod+ def check_lower(value):+ if value.is_SCREENSHOT_PIXELS():+ return+ if value.is_AFFINE():+ _UniffiFfiConverterFloat64.check_lower(value.m11)+ _UniffiFfiConverterFloat64.check_lower(value.m12)+ _UniffiFfiConverterFloat64.check_lower(value.m21)+ _UniffiFfiConverterFloat64.check_lower(value.m22)+ _UniffiFfiConverterFloat64.check_lower(value.tx)+ _UniffiFfiConverterFloat64.check_lower(value.ty)+ return+ raise ValueError(value)++ @staticmethod+ def write(value, buf):+ if value.is_SCREENSHOT_PIXELS():+ buf.write_i32(1)+ if value.is_AFFINE():+ buf.write_i32(2)+ _UniffiFfiConverterFloat64.write(value.m11, buf)+ _UniffiFfiConverterFloat64.write(value.m12, buf)+ _UniffiFfiConverterFloat64.write(value.m21, buf)+ _UniffiFfiConverterFloat64.write(value.m22, buf)+ _UniffiFfiConverterFloat64.write(value.tx, buf)+ _UniffiFfiConverterFloat64.write(value.ty, buf)++++@dataclass+class VisualCaptureProvenance:+ """+ Immutable capture provenance echoed by a parse result.+"""+ def __init__(self, *, capture_id:str, source:VisualCaptureSource, screenshot:VisualScreenshotReference, action_coordinate_space:VisualActionCoordinateSpace, captured_at:typing.Optional[str]):+ self.capture_id = capture_id+ self.source = source+ self.screenshot = screenshot+ self.action_coordinate_space = action_coordinate_space+ self.captured_at = captured_at+++++ def __str__(self):+ return "VisualCaptureProvenance(capture_id={}, source={}, screenshot={}, action_coordinate_space={}, captured_at={})".format(self.capture_id, self.source, self.screenshot, self.action_coordinate_space, self.captured_at)+ def __eq__(self, other):+ if self.capture_id != other.capture_id:+ return False+ if self.source != other.source:+ return False+ if self.screenshot != other.screenshot:+ return False+ if self.action_coordinate_space != other.action_coordinate_space:+ return False+ if self.captured_at != other.captured_at:+ return False+ return True++class _UniffiFfiConverterTypeVisualCaptureProvenance(_UniffiConverterRustBuffer):+ @staticmethod+ def read(buf):+ return VisualCaptureProvenance(+ capture_id=_UniffiFfiConverterString.read(buf),+ source=_UniffiFfiConverterTypeVisualCaptureSource.read(buf),+ screenshot=_UniffiFfiConverterTypeVisualScreenshotReference.read(buf),+ action_coordinate_space=_UniffiFfiConverterTypeVisualActionCoordinateSpace.read(buf),+ captured_at=_UniffiFfiConverterOptionalString.read(buf),+ )++ @staticmethod+ def check_lower(value):+ _UniffiFfiConverterString.check_lower(value.capture_id)+ _UniffiFfiConverterTypeVisualCaptureSource.check_lower(value.source)+ _UniffiFfiConverterTypeVisualScreenshotReference.check_lower(value.screenshot)+ _UniffiFfiConverterTypeVisualActionCoordinateSpace.check_lower(value.action_coordinate_space)+ _UniffiFfiConverterOptionalString.check_lower(value.captured_at)++ @staticmethod+ def write(value, buf):+ _UniffiFfiConverterString.write(value.capture_id, buf)+ _UniffiFfiConverterTypeVisualCaptureSource.write(value.source, buf)+ _UniffiFfiConverterTypeVisualScreenshotReference.write(value.screenshot, buf)+ _UniffiFfiConverterTypeVisualActionCoordinateSpace.write(value.action_coordinate_space, buf)+ _UniffiFfiConverterOptionalString.write(value.captured_at, buf)++@dataclass+class VisualParserMetadata:+ """+ Identity of the extension and model that produced a result.+"""+ def __init__(self, *, extension_id:str, extension_version:str, model_id:str, model_version:str, runtime:typing.Optional[str], backend:typing.Optional[str], model_source_revision:typing.Optional[str], model_manifest_sha256:typing.Optional[str], onnx_runtime_version:typing.Optional[str], onnx_runtime_library_sha256:typing.Optional[str], fixture_sha256:typing.Optional[str]):+ self.extension_id = extension_id+ self.extension_version = extension_version+ self.model_id = model_id+ self.model_version = model_version+ self.runtime = runtime+ self.backend = backend+ self.model_source_revision = model_source_revision+ self.model_manifest_sha256 = model_manifest_sha256+ self.onnx_runtime_version = onnx_runtime_version+ self.onnx_runtime_library_sha256 = onnx_runtime_library_sha256+ self.fixture_sha256 = fixture_sha256+++++ def __str__(self):+ return "VisualParserMetadata(extension_id={}, extension_version={}, model_id={}, model_version={}, runtime={}, backend={}, model_source_revision={}, model_manifest_sha256={}, onnx_runtime_version={}, onnx_runtime_library_sha256={}, fixture_sha256={})".format(self.extension_id, self.extension_version, self.model_id, self.model_version, self.runtime, self.backend, self.model_source_revision, self.model_manifest_sha256, self.onnx_runtime_version, self.onnx_runtime_library_sha256, self.fixture_sha256)+ def __eq__(self, other):+ if self.extension_id != other.extension_id:+ return False+ if self.extension_version != other.extension_version:+ return False+ if self.model_id != other.model_id:+ return False+ if self.model_version != other.model_version:+ return False+ if self.runtime != other.runtime:+ return False+ if self.backend != other.backend:+ return False+ if self.model_source_revision != other.model_source_revision:+ return False+ if self.model_manifest_sha256 != other.model_manifest_sha256:+ return False+ if self.onnx_runtime_version != other.onnx_runtime_version:+ return False+ if self.onnx_runtime_library_sha256 != other.onnx_runtime_library_sha256:+ return False+ if self.fixture_sha256 != other.fixture_sha256:+ return False+ return True++class _UniffiFfiConverterTypeVisualParserMetadata(_UniffiConverterRustBuffer):+ @staticmethod+ def read(buf):+ return VisualParserMetadata(+ extension_id=_UniffiFfiConverterString.read(buf),+ extension_version=_UniffiFfiConverterString.read(buf),+ model_id=_UniffiFfiConverterString.read(buf),+ model_version=_UniffiFfiConverterString.read(buf),+ runtime=_UniffiFfiConverterOptionalString.read(buf),+ backend=_UniffiFfiConverterOptionalString.read(buf),+ model_source_revision=_UniffiFfiConverterOptionalString.read(buf),+ model_manifest_sha256=_UniffiFfiConverterOptionalString.read(buf),+ onnx_runtime_version=_UniffiFfiConverterOptionalString.read(buf),+ onnx_runtime_library_sha256=_UniffiFfiConverterOptionalString.read(buf),+ fixture_sha256=_UniffiFfiConverterOptionalString.read(buf),+ )++ @staticmethod+ def check_lower(value):+ _UniffiFfiConverterString.check_lower(value.extension_id)+ _UniffiFfiConverterString.check_lower(value.extension_version)+ _UniffiFfiConverterString.check_lower(value.model_id)+ _UniffiFfiConverterString.check_lower(value.model_version)+ _UniffiFfiConverterOptionalString.check_lower(value.runtime)+ _UniffiFfiConverterOptionalString.check_lower(value.backend)+ _UniffiFfiConverterOptionalString.check_lower(value.model_source_revision)+ _UniffiFfiConverterOptionalString.check_lower(value.model_manifest_sha256)+ _UniffiFfiConverterOptionalString.check_lower(value.onnx_runtime_version)+ _UniffiFfiConverterOptionalString.check_lower(value.onnx_runtime_library_sha256)+ _UniffiFfiConverterOptionalString.check_lower(value.fixture_sha256)++ @staticmethod+ def write(value, buf):+ _UniffiFfiConverterString.write(value.extension_id, buf)+ _UniffiFfiConverterString.write(value.extension_version, buf)+ _UniffiFfiConverterString.write(value.model_id, buf)+ _UniffiFfiConverterString.write(value.model_version, buf)+ _UniffiFfiConverterOptionalString.write(value.runtime, buf)+ _UniffiFfiConverterOptionalString.write(value.backend, buf)+ _UniffiFfiConverterOptionalString.write(value.model_source_revision, buf)+ _UniffiFfiConverterOptionalString.write(value.model_manifest_sha256, buf)+ _UniffiFfiConverterOptionalString.write(value.onnx_runtime_version, buf)+ _UniffiFfiConverterOptionalString.write(value.onnx_runtime_library_sha256, buf)+ _UniffiFfiConverterOptionalString.write(value.fixture_sha256, buf)++@dataclass+class VisualRegionBounds:+ """+ Integer pixel-edge bounds `[x, x + width) x [y, y + height)`.++ `x` and `y` name the left and top pixel edges. The right and bottom edges+ are excluded. A region therefore covers every pixel whose center lies in+ this half-open box; its geometric center may lie between pixels.+"""+ def __init__(self, *, x:int, y:int, width:int, height:int):+ self.x = x+ self.y = y+ self.width = width+ self.height = height+++++ def __str__(self):+ return "VisualRegionBounds(x={}, y={}, width={}, height={})".format(self.x, self.y, self.width, self.height)+ def __eq__(self, other):+ if self.x != other.x:+ return False+ if self.y != other.y:+ return False+ if self.width != other.width:+ return False+ if self.height != other.height:+ return False+ return True++class _UniffiFfiConverterTypeVisualRegionBounds(_UniffiConverterRustBuffer):+ @staticmethod+ def read(buf):+ return VisualRegionBounds(+ x=_UniffiFfiConverterUInt32.read(buf),+ y=_UniffiFfiConverterUInt32.read(buf),+ width=_UniffiFfiConverterUInt32.read(buf),+ height=_UniffiFfiConverterUInt32.read(buf),+ )++ @staticmethod+ def check_lower(value):+ _UniffiFfiConverterUInt32.check_lower(value.x)+ _UniffiFfiConverterUInt32.check_lower(value.y)+ _UniffiFfiConverterUInt32.check_lower(value.width)+ _UniffiFfiConverterUInt32.check_lower(value.height)++ @staticmethod+ def write(value, buf):+ _UniffiFfiConverterUInt32.write(value.x, buf)+ _UniffiFfiConverterUInt32.write(value.y, buf)+ _UniffiFfiConverterUInt32.write(value.width, buf)+ _UniffiFfiConverterUInt32.write(value.height, buf)++@dataclass+class VisualRegion:+ """+ One parser-observed region in the exact source screenshot pixel space.+"""+ def __init__(self, *, id:str, kind:VisualRegionKind, bounds:VisualRegionBounds, text:typing.Optional[str], label:typing.Optional[str], confidence:float, interactive:bool, parent_id:typing.Optional[str], group_id:typing.Optional[str], reading_order:typing.Optional[int]):+ self.id = id+ self.kind = kind+ self.bounds = bounds+ self.text = text+ self.label = label+ self.confidence = confidence+ self.interactive = interactive+ self.parent_id = parent_id+ self.group_id = group_id+ self.reading_order = reading_order+++++ def __str__(self):+ return "VisualRegion(id={}, kind={}, bounds={}, text={}, label={}, confidence={}, interactive={}, parent_id={}, group_id={}, reading_order={})".format(self.id, self.kind, self.bounds, self.text, self.label, self.confidence, self.interactive, self.parent_id, self.group_id, self.reading_order)+ def __eq__(self, other):+ if self.id != other.id:+ return False+ if self.kind != other.kind:+ return False+ if self.bounds != other.bounds:+ return False+ if self.text != other.text:+ return False+ if self.label != other.label:+ return False+ if self.confidence != other.confidence:+ return False+ if self.interactive != other.interactive:+ return False+ if self.parent_id != other.parent_id:+ return False+ if self.group_id != other.group_id:+ return False+ if self.reading_order != other.reading_order:+ return False+ return True++class _UniffiFfiConverterTypeVisualRegion(_UniffiConverterRustBuffer):+ @staticmethod+ def read(buf):+ return VisualRegion(+ id=_UniffiFfiConverterString.read(buf),+ kind=_UniffiFfiConverterTypeVisualRegionKind.read(buf),+ bounds=_UniffiFfiConverterTypeVisualRegionBounds.read(buf),+ text=_UniffiFfiConverterOptionalString.read(buf),+ label=_UniffiFfiConverterOptionalString.read(buf),+ confidence=_UniffiFfiConverterFloat64.read(buf),+ interactive=_UniffiFfiConverterBoolean.read(buf),+ parent_id=_UniffiFfiConverterOptionalString.read(buf),+ group_id=_UniffiFfiConverterOptionalString.read(buf),+ reading_order=_UniffiFfiConverterOptionalUInt32.read(buf),+ )++ @staticmethod+ def check_lower(value):+ _UniffiFfiConverterString.check_lower(value.id)+ _UniffiFfiConverterTypeVisualRegionKind.check_lower(value.kind)+ _UniffiFfiConverterTypeVisualRegionBounds.check_lower(value.bounds)+ _UniffiFfiConverterOptionalString.check_lower(value.text)+ _UniffiFfiConverterOptionalString.check_lower(value.label)+ _UniffiFfiConverterFloat64.check_lower(value.confidence)+ _UniffiFfiConverterBoolean.check_lower(value.interactive)+ _UniffiFfiConverterOptionalString.check_lower(value.parent_id)+ _UniffiFfiConverterOptionalString.check_lower(value.group_id)+ _UniffiFfiConverterOptionalUInt32.check_lower(value.reading_order)++ @staticmethod+ def write(value, buf):+ _UniffiFfiConverterString.write(value.id, buf)+ _UniffiFfiConverterTypeVisualRegionKind.write(value.kind, buf)+ _UniffiFfiConverterTypeVisualRegionBounds.write(value.bounds, buf)+ _UniffiFfiConverterOptionalString.write(value.text, buf)+ _UniffiFfiConverterOptionalString.write(value.label, buf)+ _UniffiFfiConverterFloat64.write(value.confidence, buf)+ _UniffiFfiConverterBoolean.write(value.interactive, buf)+ _UniffiFfiConverterOptionalString.write(value.parent_id, buf)+ _UniffiFfiConverterOptionalString.write(value.group_id, buf)+ _UniffiFfiConverterOptionalUInt32.write(value.reading_order, buf)++class _UniffiFfiConverterSequenceTypeVisualRegion(_UniffiConverterRustBuffer):+ @classmethod+ def check_lower(cls, value):+ for item in value:+ _UniffiFfiConverterTypeVisualRegion.check_lower(item)++ @classmethod+ def write(cls, value, buf):+ items = len(value)+ buf.write_i32(items)+ for item in value:+ _UniffiFfiConverterTypeVisualRegion.write(item, buf)++ @classmethod+ def read(cls, buf):+ count = buf.read_i32()+ if count < 0:+ raise InternalError("Unexpected negative sequence length")++ return [+ _UniffiFfiConverterTypeVisualRegion.read(buf) for i in range(count)+ ]++@dataclass+class VisualParseWarning:+ def __init__(self, *, code:str, message:str, detail:typing.Optional[str]):+ self.code = code+ self.message = message+ self.detail = detail+++++ def __str__(self):+ return "VisualParseWarning(code={}, message={}, detail={})".format(self.code, self.message, self.detail)+ def __eq__(self, other):+ if self.code != other.code:+ return False+ if self.message != other.message:+ return False+ if self.detail != other.detail:+ return False+ return True++class _UniffiFfiConverterTypeVisualParseWarning(_UniffiConverterRustBuffer):+ @staticmethod+ def read(buf):+ return VisualParseWarning(+ code=_UniffiFfiConverterString.read(buf),+ message=_UniffiFfiConverterString.read(buf),+ detail=_UniffiFfiConverterOptionalString.read(buf),+ )++ @staticmethod+ def check_lower(value):+ _UniffiFfiConverterString.check_lower(value.code)+ _UniffiFfiConverterString.check_lower(value.message)+ _UniffiFfiConverterOptionalString.check_lower(value.detail)++ @staticmethod+ def write(value, buf):+ _UniffiFfiConverterString.write(value.code, buf)+ _UniffiFfiConverterString.write(value.message, buf)+ _UniffiFfiConverterOptionalString.write(value.detail, buf)++class _UniffiFfiConverterSequenceTypeVisualParseWarning(_UniffiConverterRustBuffer):+ @classmethod+ def check_lower(cls, value):+ for item in value:+ _UniffiFfiConverterTypeVisualParseWarning.check_lower(item)++ @classmethod+ def write(cls, value, buf):+ items = len(value)+ buf.write_i32(items)+ for item in value:+ _UniffiFfiConverterTypeVisualParseWarning.write(item, buf)++ @classmethod+ def read(cls, buf):+ count = buf.read_i32()+ if count < 0:+ raise InternalError("Unexpected negative sequence length")++ return [+ _UniffiFfiConverterTypeVisualParseWarning.read(buf) for i in range(count)+ ]++@dataclass+class VisualParseTiming:+ def __init__(self, *, duration_ms:int, preprocess_ms:typing.Optional[int], inference_ms:typing.Optional[int]):+ self.duration_ms = duration_ms+ self.preprocess_ms = preprocess_ms+ self.inference_ms = inference_ms+++++ def __str__(self):+ return "VisualParseTiming(duration_ms={}, preprocess_ms={}, inference_ms={})".format(self.duration_ms, self.preprocess_ms, self.inference_ms)+ def __eq__(self, other):+ if self.duration_ms != other.duration_ms:+ return False+ if self.preprocess_ms != other.preprocess_ms:+ return False+ if self.inference_ms != other.inference_ms:+ return False+ return True++class _UniffiFfiConverterTypeVisualParseTiming(_UniffiConverterRustBuffer):+ @staticmethod+ def read(buf):+ return VisualParseTiming(+ duration_ms=_UniffiFfiConverterUInt64.read(buf),+ preprocess_ms=_UniffiFfiConverterOptionalUInt64.read(buf),+ inference_ms=_UniffiFfiConverterOptionalUInt64.read(buf),+ )++ @staticmethod+ def check_lower(value):+ _UniffiFfiConverterUInt64.check_lower(value.duration_ms)+ _UniffiFfiConverterOptionalUInt64.check_lower(value.preprocess_ms)+ _UniffiFfiConverterOptionalUInt64.check_lower(value.inference_ms)++ @staticmethod+ def write(value, buf):+ _UniffiFfiConverterUInt64.write(value.duration_ms, buf)+ _UniffiFfiConverterOptionalUInt64.write(value.preprocess_ms, buf)+ _UniffiFfiConverterOptionalUInt64.write(value.inference_ms, buf)++@dataclass+class ParseVisualRegionsOutput:+ def __init__(self, *, schema:str, capture:VisualCaptureProvenance, parser:VisualParserMetadata, regions:typing.List[VisualRegion], warnings:typing.List[VisualParseWarning], timing:VisualParseTiming, request_id:typing.Optional[str]):+ self.schema = schema+ self.capture = capture+ self.parser = parser+ self.regions = regions+ self.warnings = warnings+ self.timing = timing+ self.request_id = request_id+++++ def __str__(self):+ return "ParseVisualRegionsOutput(schema={}, capture={}, parser={}, regions={}, warnings={}, timing={}, request_id={})".format(self.schema, self.capture, self.parser, self.regions, self.warnings, self.timing, self.request_id)+ def __eq__(self, other):+ if self.schema != other.schema:+ return False+ if self.capture != other.capture:+ return False+ if self.parser != other.parser:+ return False+ if self.regions != other.regions:+ return False+ if self.warnings != other.warnings:+ return False+ if self.timing != other.timing:+ return False+ if self.request_id != other.request_id:+ return False+ return True++class _UniffiFfiConverterTypeParseVisualRegionsOutput(_UniffiConverterRustBuffer):+ @staticmethod+ def read(buf):+ return ParseVisualRegionsOutput(+ schema=_UniffiFfiConverterString.read(buf),+ capture=_UniffiFfiConverterTypeVisualCaptureProvenance.read(buf),+ parser=_UniffiFfiConverterTypeVisualParserMetadata.read(buf),+ regions=_UniffiFfiConverterSequenceTypeVisualRegion.read(buf),+ warnings=_UniffiFfiConverterSequenceTypeVisualParseWarning.read(buf),+ timing=_UniffiFfiConverterTypeVisualParseTiming.read(buf),+ request_id=_UniffiFfiConverterOptionalString.read(buf),+ )++ @staticmethod+ def check_lower(value):+ _UniffiFfiConverterString.check_lower(value.schema)+ _UniffiFfiConverterTypeVisualCaptureProvenance.check_lower(value.capture)+ _UniffiFfiConverterTypeVisualParserMetadata.check_lower(value.parser)+ _UniffiFfiConverterSequenceTypeVisualRegion.check_lower(value.regions)+ _UniffiFfiConverterSequenceTypeVisualParseWarning.check_lower(value.warnings)+ _UniffiFfiConverterTypeVisualParseTiming.check_lower(value.timing)+ _UniffiFfiConverterOptionalString.check_lower(value.request_id)++ @staticmethod+ def write(value, buf):+ _UniffiFfiConverterString.write(value.schema, buf)+ _UniffiFfiConverterTypeVisualCaptureProvenance.write(value.capture, buf)+ _UniffiFfiConverterTypeVisualParserMetadata.write(value.parser, buf)+ _UniffiFfiConverterSequenceTypeVisualRegion.write(value.regions, buf)+ _UniffiFfiConverterSequenceTypeVisualParseWarning.write(value.warnings, buf)+ _UniffiFfiConverterTypeVisualParseTiming.write(value.timing, buf)+ _UniffiFfiConverterOptionalString.write(value.request_id, buf)+++++++class VerificationStatus(enum.Enum):++ SATISFIED = 0++ UNSATISFIED = 1++ UNKNOWN = 2++++class _UniffiFfiConverterTypeVerificationStatus(_UniffiConverterRustBuffer):+ @staticmethod+ def read(buf):+ variant = buf.read_i32()+ if variant == 1:+ return VerificationStatus.SATISFIED+ if variant == 2:+ return VerificationStatus.UNSATISFIED+ if variant == 3:+ return VerificationStatus.UNKNOWN+ raise InternalError("Raw enum value doesn't match any cases")++ @staticmethod+ def check_lower(value):+ if value == VerificationStatus.SATISFIED:+ return+ if value == VerificationStatus.UNSATISFIED:+ return+ if value == VerificationStatus.UNKNOWN:+ return+ raise ValueError(value)++ @staticmethod+ def write(value, buf):+ if value == VerificationStatus.SATISFIED:+ buf.write_i32(1)+ if value == VerificationStatus.UNSATISFIED:+ buf.write_i32(2)+ if value == VerificationStatus.UNKNOWN:+ buf.write_i32(3)+++++++++class UnknownReason(enum.Enum):++ INVALID_PREDICATE = 0++ UNSUPPORTED_PREDICATE = 1++ UNTRUSTED_SOURCE = 2++ MULTI_MATCH = 3++ TARGET_MISSING = 4++ OBSERVATION_UNAVAILABLE = 5++ STABILITY_UNPROVEN = 6++++class _UniffiFfiConverterTypeUnknownReason(_UniffiConverterRustBuffer):+ @staticmethod+ def read(buf):+ variant = buf.read_i32()+ if variant == 1:+ return UnknownReason.INVALID_PREDICATE+ if variant == 2:+ return UnknownReason.UNSUPPORTED_PREDICATE+ if variant == 3:+ return UnknownReason.UNTRUSTED_SOURCE+ if variant == 4:+ return UnknownReason.MULTI_MATCH+ if variant == 5:+ return UnknownReason.TARGET_MISSING+ if variant == 6:+ return UnknownReason.OBSERVATION_UNAVAILABLE+ if variant == 7:+ return UnknownReason.STABILITY_UNPROVEN+ raise InternalError("Raw enum value doesn't match any cases")++ @staticmethod+ def check_lower(value):+ if value == UnknownReason.INVALID_PREDICATE:+ return+ if value == UnknownReason.UNSUPPORTED_PREDICATE:+ return+ if value == UnknownReason.UNTRUSTED_SOURCE:+ return+ if value == UnknownReason.MULTI_MATCH:+ return+ if value == UnknownReason.TARGET_MISSING:+ return+ if value == UnknownReason.OBSERVATION_UNAVAILABLE:+ return+ if value == UnknownReason.STABILITY_UNPROVEN:+ return+ raise ValueError(value)++ @staticmethod+ def write(value, buf):+ if value == UnknownReason.INVALID_PREDICATE:+ buf.write_i32(1)+ if value == UnknownReason.UNSUPPORTED_PREDICATE:+ buf.write_i32(2)+ if value == UnknownReason.UNTRUSTED_SOURCE:+ buf.write_i32(3)+ if value == UnknownReason.MULTI_MATCH:+ buf.write_i32(4)+ if value == UnknownReason.TARGET_MISSING:+ buf.write_i32(5)+ if value == UnknownReason.OBSERVATION_UNAVAILABLE:+ buf.write_i32(6)+ if value == UnknownReason.STABILITY_UNPROVEN:+ buf.write_i32(7)++++class _UniffiFfiConverterOptionalTypeUnknownReason(_UniffiConverterRustBuffer):+ @classmethod+ def check_lower(cls, value):+ if value is not None:+ _UniffiFfiConverterTypeUnknownReason.check_lower(value)++ @classmethod+ def write(cls, value, buf):+ if value is None:+ buf.write_u8(0)+ return++ buf.write_u8(1)+ _UniffiFfiConverterTypeUnknownReason.write(value, buf)++ @classmethod+ def read(cls, buf):+ flag = buf.read_u8()+ if flag == 0:+ return None+ elif flag == 1:+ return _UniffiFfiConverterTypeUnknownReason.read(buf)+ else:+ raise InternalError("Unexpected flag byte for optional type")++@dataclass+class PredicateOutcome:+ def __init__(self, *, index:int, status:VerificationStatus, unknown_reason:typing.Optional[UnknownReason], observed_json:typing.Optional[str]):+ self.index = index+ self.status = status+ self.unknown_reason = unknown_reason+ self.observed_json = observed_json+++++ def __str__(self):+ return "PredicateOutcome(index={}, status={}, unknown_reason={}, observed_json={})".format(self.index, self.status, self.unknown_reason, self.observed_json)+ def __eq__(self, other):+ if self.index != other.index:+ return False+ if self.status != other.status:+ return False+ if self.unknown_reason != other.unknown_reason:+ return False+ if self.observed_json != other.observed_json:+ return False+ return True++class _UniffiFfiConverterTypePredicateOutcome(_UniffiConverterRustBuffer):+ @staticmethod+ def read(buf):+ return PredicateOutcome(+ index=_UniffiFfiConverterUInt64.read(buf),+ status=_UniffiFfiConverterTypeVerificationStatus.read(buf),+ unknown_reason=_UniffiFfiConverterOptionalTypeUnknownReason.read(buf),+ observed_json=_UniffiFfiConverterOptionalString.read(buf),+ )++ @staticmethod+ def check_lower(value):+ _UniffiFfiConverterUInt64.check_lower(value.index)+ _UniffiFfiConverterTypeVerificationStatus.check_lower(value.status)+ _UniffiFfiConverterOptionalTypeUnknownReason.check_lower(value.unknown_reason)+ _UniffiFfiConverterOptionalString.check_lower(value.observed_json)++ @staticmethod+ def write(value, buf):+ _UniffiFfiConverterUInt64.write(value.index, buf)+ _UniffiFfiConverterTypeVerificationStatus.write(value.status, buf)+ _UniffiFfiConverterOptionalTypeUnknownReason.write(value.unknown_reason, buf)+ _UniffiFfiConverterOptionalString.write(value.observed_json, buf)++@dataclass+class PressKeyInput:+ def __init__(self, *, key:str, target:typing.Optional[ActionTarget], scope:typing.Optional[DesktopScope], session:typing.Optional[str], modifiers:typing.Optional[typing.List[str]]):+ self.key = key+ self.target = target+ self.scope = scope+ self.session = session+ self.modifiers = modifiers+++++ def __str__(self):+ return "PressKeyInput(key={}, target={}, scope={}, session={}, modifiers={})".format(self.key, self.target, self.scope, self.session, self.modifiers)+ def __eq__(self, other):+ if self.key != other.key:+ return False+ if self.target != other.target:+ return False+ if self.scope != other.scope:+ return False+ if self.session != other.session:+ return False+ if self.modifiers != other.modifiers:+ return False+ return True++class _UniffiFfiConverterTypePressKeyInput(_UniffiConverterRustBuffer):+ @staticmethod+ def read(buf):+ return PressKeyInput(+ key=_UniffiFfiConverterString.read(buf),+ target=_UniffiFfiConverterOptionalTypeActionTarget.read(buf),+ scope=_UniffiFfiConverterOptionalTypeDesktopScope.read(buf),+ session=_UniffiFfiConverterOptionalString.read(buf),+ modifiers=_UniffiFfiConverterOptionalSequenceString.read(buf),+ )++ @staticmethod+ def check_lower(value):+ _UniffiFfiConverterString.check_lower(value.key)+ _UniffiFfiConverterOptionalTypeActionTarget.check_lower(value.target)+ _UniffiFfiConverterOptionalTypeDesktopScope.check_lower(value.scope)+ _UniffiFfiConverterOptionalString.check_lower(value.session)+ _UniffiFfiConverterOptionalSequenceString.check_lower(value.modifiers)++ @staticmethod+ def write(value, buf):+ _UniffiFfiConverterString.write(value.key, buf)+ _UniffiFfiConverterOptionalTypeActionTarget.write(value.target, buf)+ _UniffiFfiConverterOptionalTypeDesktopScope.write(value.scope, buf)+ _UniffiFfiConverterOptionalString.write(value.session, buf)+ _UniffiFfiConverterOptionalSequenceString.write(value.modifiers, buf)+++++++class ScrollDirection(enum.Enum):++ UP = 0++ DOWN = 1++ LEFT = 2++ RIGHT = 3++++class _UniffiFfiConverterTypeScrollDirection(_UniffiConverterRustBuffer):+ @staticmethod+ def read(buf):+ variant = buf.read_i32()+ if variant == 1:+ return ScrollDirection.UP+ if variant == 2:+ return ScrollDirection.DOWN+ if variant == 3:+ return ScrollDirection.LEFT+ if variant == 4:+ return ScrollDirection.RIGHT+ raise InternalError("Raw enum value doesn't match any cases")++ @staticmethod+ def check_lower(value):+ if value == ScrollDirection.UP:+ return+ if value == ScrollDirection.DOWN:+ return+ if value == ScrollDirection.LEFT:+ return+ if value == ScrollDirection.RIGHT:+ return+ raise ValueError(value)++ @staticmethoddef write(value, buf):if value == ScrollDirection.UP:buf.write_i32(1)@@ -6072,6 +7142,209 @@ class _UniffiFfiConverterTypeVerifyStateOutput(_UniffiConverterRustBuffer):_UniffiFfiConverterUInt64.write(value.samples, buf)_UniffiFfiConverterSequenceTypePredicateOutcome.write(value.predicates, buf)++++++class VisualParseErrorCode(enum.Enum):+ """+ Stable machine-readable failures for capture lookup and visual parsing.+"""++ NOT_INSTALLED = 0++ CAPTURE_NOT_FOUND = 1++ CAPTURE_EXPIRED = 2++ CAPTURE_STALE = 3++ CAPTURE_GENERATION_MISMATCH = 4++ UNSUPPORTED_TARGET = 5++ UNSUPPORTED_PLATFORM = 6++ INCOMPATIBLE_PROTOCOL = 7++ INVALID_FRAME = 8++ WORKER_LAUNCH_FAILED = 9++ WORKER_CRASHED = 10++ WORKER_CANCELLED = 11++ TIMEOUT = 12++ RESOURCE_LIMIT_EXCEEDED = 13++ ARTIFACT_INVALID = 14++ INFERENCE_FAILED = 15++++class _UniffiFfiConverterTypeVisualParseErrorCode(_UniffiConverterRustBuffer):+ @staticmethod+ def read(buf):+ variant = buf.read_i32()+ if variant == 1:+ return VisualParseErrorCode.NOT_INSTALLED+ if variant == 2:+ return VisualParseErrorCode.CAPTURE_NOT_FOUND+ if variant == 3:+ return VisualParseErrorCode.CAPTURE_EXPIRED+ if variant == 4:+ return VisualParseErrorCode.CAPTURE_STALE+ if variant == 5:+ return VisualParseErrorCode.CAPTURE_GENERATION_MISMATCH+ if variant == 6:+ return VisualParseErrorCode.UNSUPPORTED_TARGET+ if variant == 7:+ return VisualParseErrorCode.UNSUPPORTED_PLATFORM+ if variant == 8:+ return VisualParseErrorCode.INCOMPATIBLE_PROTOCOL+ if variant == 9:+ return VisualParseErrorCode.INVALID_FRAME+ if variant == 10:+ return VisualParseErrorCode.WORKER_LAUNCH_FAILED+ if variant == 11:+ return VisualParseErrorCode.WORKER_CRASHED+ if variant == 12:+ return VisualParseErrorCode.WORKER_CANCELLED+ if variant == 13:+ return VisualParseErrorCode.TIMEOUT+ if variant == 14:+ return VisualParseErrorCode.RESOURCE_LIMIT_EXCEEDED+ if variant == 15:+ return VisualParseErrorCode.ARTIFACT_INVALID+ if variant == 16:+ return VisualParseErrorCode.INFERENCE_FAILED+ raise InternalError("Raw enum value doesn't match any cases")++ @staticmethod+ def check_lower(value):+ if value == VisualParseErrorCode.NOT_INSTALLED:+ return+ if value == VisualParseErrorCode.CAPTURE_NOT_FOUND:+ return+ if value == VisualParseErrorCode.CAPTURE_EXPIRED:+ return+ if value == VisualParseErrorCode.CAPTURE_STALE:+ return+ if value == VisualParseErrorCode.CAPTURE_GENERATION_MISMATCH:+ return+ if value == VisualParseErrorCode.UNSUPPORTED_TARGET:+ return+ if value == VisualParseErrorCode.UNSUPPORTED_PLATFORM:+ return+ if value == VisualParseErrorCode.INCOMPATIBLE_PROTOCOL:+ return+ if value == VisualParseErrorCode.INVALID_FRAME:+ return+ if value == VisualParseErrorCode.WORKER_LAUNCH_FAILED:+ return+ if value == VisualParseErrorCode.WORKER_CRASHED:+ return+ if value == VisualParseErrorCode.WORKER_CANCELLED:+ return+ if value == VisualParseErrorCode.TIMEOUT:+ return+ if value == VisualParseErrorCode.RESOURCE_LIMIT_EXCEEDED:+ return+ if value == VisualParseErrorCode.ARTIFACT_INVALID:+ return+ if value == VisualParseErrorCode.INFERENCE_FAILED:+ return+ raise ValueError(value)++ @staticmethod+ def write(value, buf):+ if value == VisualParseErrorCode.NOT_INSTALLED:+ buf.write_i32(1)+ if value == VisualParseErrorCode.CAPTURE_NOT_FOUND:+ buf.write_i32(2)+ if value == VisualParseErrorCode.CAPTURE_EXPIRED:+ buf.write_i32(3)+ if value == VisualParseErrorCode.CAPTURE_STALE:+ buf.write_i32(4)+ if value == VisualParseErrorCode.CAPTURE_GENERATION_MISMATCH:+ buf.write_i32(5)+ if value == VisualParseErrorCode.UNSUPPORTED_TARGET:+ buf.write_i32(6)+ if value == VisualParseErrorCode.UNSUPPORTED_PLATFORM:+ buf.write_i32(7)+ if value == VisualParseErrorCode.INCOMPATIBLE_PROTOCOL:+ buf.write_i32(8)+ if value == VisualParseErrorCode.INVALID_FRAME:+ buf.write_i32(9)+ if value == VisualParseErrorCode.WORKER_LAUNCH_FAILED:+ buf.write_i32(10)+ if value == VisualParseErrorCode.WORKER_CRASHED:+ buf.write_i32(11)+ if value == VisualParseErrorCode.WORKER_CANCELLED:+ buf.write_i32(12)+ if value == VisualParseErrorCode.TIMEOUT:+ buf.write_i32(13)+ if value == VisualParseErrorCode.RESOURCE_LIMIT_EXCEEDED:+ buf.write_i32(14)+ if value == VisualParseErrorCode.ARTIFACT_INVALID:+ buf.write_i32(15)+ if value == VisualParseErrorCode.INFERENCE_FAILED:+ buf.write_i32(16)++++@dataclass+class VisualParseError:+ def __init__(self, *, code:VisualParseErrorCode, message:str, retryable:bool, detail:typing.Optional[str]):+ self.code = code+ self.message = message+ self.retryable = retryable+ self.detail = detail+++++ def __str__(self):+ return "VisualParseError(code={}, message={}, retryable={}, detail={})".format(self.code, self.message, self.retryable, self.detail)+ def __eq__(self, other):+ if self.code != other.code:+ return False+ if self.message != other.message:+ return False+ if self.retryable != other.retryable:+ return False+ if self.detail != other.detail:+ return False+ return True++class _UniffiFfiConverterTypeVisualParseError(_UniffiConverterRustBuffer):+ @staticmethod+ def read(buf):+ return VisualParseError(+ code=_UniffiFfiConverterTypeVisualParseErrorCode.read(buf),+ message=_UniffiFfiConverterString.read(buf),+ retryable=_UniffiFfiConverterBoolean.read(buf),+ detail=_UniffiFfiConverterOptionalString.read(buf),+ )++ @staticmethod+ def check_lower(value):+ _UniffiFfiConverterTypeVisualParseErrorCode.check_lower(value.code)+ _UniffiFfiConverterString.check_lower(value.message)+ _UniffiFfiConverterBoolean.check_lower(value.retryable)+ _UniffiFfiConverterOptionalString.check_lower(value.detail)++ @staticmethod+ def write(value, buf):+ _UniffiFfiConverterTypeVisualParseErrorCode.write(value.code, buf)+ _UniffiFfiConverterString.write(value.message, buf)+ _UniffiFfiConverterBoolean.write(value.retryable, buf)+ _UniffiFfiConverterOptionalString.write(value.detail, buf)+class _UniffiFfiConverterOptionalTypeElementFrame(_UniffiConverterRustBuffer):@classmethoddef check_lower(cls, value):@@ -6555,12 +7828,16 @@ __all__ = ["SessionLifecycleState","SessionClientKindOutput","SessionTransportOutput",+ "VisualRegionKind",+ "VisualCaptureSource",+ "VisualActionCoordinateSpace","VerificationStatus","UnknownReason","ScrollDirection","ScrollBy","CaptureScope","EffectiveScope",+ "VisualParseErrorCode","Platform","ActionDelivery","ActionEscalation",@@ -6605,6 +7882,16 @@ __all__ = ["WindowInfo","ListWindowsOutput","MoveCursorInput",+ "ParseVisualRegionsOptions",+ "ParseVisualRegionsInput",+ "VisualScreenshotReference",+ "VisualCaptureProvenance",+ "VisualParserMetadata",+ "VisualRegionBounds",+ "VisualRegion",+ "VisualParseWarning",+ "VisualParseTiming",+ "ParseVisualRegionsOutput","PredicateOutcome","PressKeyInput","ScrollInput",@@ -6624,6 +7911,7 @@ __all__ = ["TypeTextInput","VerifyStateInput","VerifyStateOutput",+ "VisualParseError","WindowElement","WindowStateOutput",]diff --git a/libs/cua-driver/python/tests/test_compatibility_contract.py b/libs/cua-driver/python/tests/test_compatibility_contract.pyindex 6c77fcc382..eb73a45446 100644--- a/libs/cua-driver/python/tests/test_compatibility_contract.py+++ b/libs/cua-driver/python/tests/test_compatibility_contract.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport astimport json+import refrom pathlib import Path@@ -12,6 +13,15 @@ FIXTURE = (PACKAGE_ROOT.parent / "compat-fixtures" / "python-package.json")+# UniFFI tags ClickPosition by declaration order. cua-driver-rs-v0.28.2 released+# 1=COORDINATES and 2=ELEMENT; new variants may only be appended. The generated+# binding check in CI ties this list back to the Rust declaration order.+RELEASED_CLICK_POSITION_ORDINALS = [+ (1, "COORDINATES"),+ (2, "ELEMENT"),+ (3, "CAPTURED_COORDINATES"),+]+def _module(path: Path) -> ast.Module:return ast.parse(path.read_text(encoding="utf-8"))@@ -79,6 +89,26 @@ def test_current_native_window_methods_have_typed_outputs() -> None:)+def test_click_position_preserves_released_uniffi_ordinals() -> None:+ generated = (+ PACKAGE_ROOT / "src" / "cua_driver" / "_native_contract.py"+ ).read_text(encoding="utf-8")+ converter = re.search(+ r"class _UniffiFfiConverterTypeClickPosition\b.*?def check_lower",+ generated,+ re.S,+ )+ assert converter, "ClickPosition converter missing from the generated bindings"+ observed = [+ (int(ordinal), variant)+ for ordinal, variant in re.findall(+ r"if variant == (\d+):\s*return ClickPosition\.(\w+)\(",+ converter.group(0),+ )+ ]+ assert observed == RELEASED_CLICK_POSITION_ORDINALS++def test_released_python_exports_and_signatures_remain_available() -> None:expected = json.loads(FIXTURE.read_text(encoding="utf-8"))package_module = _module(PACKAGE_ROOT / "src" / "cua_driver" / "__init__.py")diff --git a/libs/cua-driver/python/tests/test_remote_channel.py b/libs/cua-driver/python/tests/test_remote_channel.pyindex de17c598ee..dd40d7bea5 100644--- a/libs/cua-driver/python/tests/test_remote_channel.py+++ b/libs/cua-driver/python/tests/test_remote_channel.py@@ -324,6 +324,7 @@ class NativeWindowTests(unittest.IsolatedAsyncioTestCase):max_elements=10,max_depth=3,max_dimension=800,+ max_image_dimension=1600,))self.assertIsInstance(state, sdk.WindowStateOutput)@@ -343,6 +344,7 @@ class NativeWindowTests(unittest.IsolatedAsyncioTestCase):"max_elements": 10,"max_depth": 3,"max_dimension": 800,+ "max_image_dimension": 1600,},)diff --git a/libs/cua-driver/python/tests/test_uniffi_loader.py b/libs/cua-driver/python/tests/test_uniffi_loader.pyindex 344b2aeb04..a8f2cb3099 100644--- a/libs/cua-driver/python/tests/test_uniffi_loader.py+++ b/libs/cua-driver/python/tests/test_uniffi_loader.py@@ -25,6 +25,107 @@ LIBRARY = Path(__file__).parents[1] / "src" / "cua_driver" / _library_name()@unittest.skipUnless(LIBRARY.exists(), "host-native UniFFI library is not staged")class GeneratedOptionsTests(unittest.TestCase):+ def test_visual_contract_dtos_construct_and_round_trip_through_uniffi(self) -> None:+ from cua_driver import _native_contract as contract++ def round_trip(converter, value):+ return converter.lift(converter.lower(value))++ request = contract.ParseVisualRegionsInput(+ capture_id="capture-1",+ options=contract.ParseVisualRegionsOptions(+ kinds=[contract.VisualRegionKind.TEXT, contract.VisualRegionKind.ICON],+ min_confidence=0.25,+ max_regions=200,+ ),+ )+ self.assertEqual(+ round_trip(contract._UniffiFfiConverterTypeParseVisualRegionsInput, request),+ request,+ )++ coordinate_space = contract.VisualActionCoordinateSpace.AFFINE(+ m11=0.5,+ m12=0.25,+ m21=-0.5,+ m22=2.0,+ tx=-1920.0,+ ty=10.0,+ )+ output = contract.ParseVisualRegionsOutput(+ schema="cua.visual_regions_v1",+ capture=contract.VisualCaptureProvenance(+ capture_id="capture-1",+ source=contract.VisualCaptureSource.PRIMARY_DESKTOP("primary"),+ screenshot=contract.VisualScreenshotReference(+ reference="png-1",+ width=1920,+ height=1080,+ mime_type="image/png",+ sha256=None,+ ),+ action_coordinate_space=coordinate_space,+ captured_at="2026-09-17T12:00:00Z",+ ),+ parser=contract.VisualParserMetadata(+ extension_id="visual-parser",+ extension_version="1.0.0",+ model_id="default",+ model_version="1",+ runtime="cpu",+ backend="onnx_runtime_cpu",+ model_source_revision="revision-1",+ model_manifest_sha256="a" * 64,+ onnx_runtime_version="1.26.0",+ onnx_runtime_library_sha256="b" * 64,+ fixture_sha256=None,+ ),+ regions=[+ contract.VisualRegion(+ id="text-1",+ kind=contract.VisualRegionKind.TEXT,+ bounds=contract.VisualRegionBounds(x=11, y=20, width=101, height=21),+ text="Apply",+ label=None,+ confidence=0.95,+ interactive=True,+ parent_id=None,+ group_id=None,+ reading_order=1,+ )+ ],+ warnings=[+ contract.VisualParseWarning(+ code="low_contrast",+ message="contrast was low",+ detail="text-1",+ )+ ],+ timing=contract.VisualParseTiming(+ duration_ms=18,+ preprocess_ms=3,+ inference_ms=12,+ ),+ request_id="parse-1",+ )+ lifted = round_trip(contract._UniffiFfiConverterTypeParseVisualRegionsOutput, output)+ self.assertEqual(lifted, output)+ self.assertEqual(+ lifted.capture.action_coordinate_space.m11,+ 0.5,+ )++ error = contract.VisualParseError(+ code=contract.VisualParseErrorCode.CAPTURE_NOT_FOUND,+ message="capture was not found",+ retryable=True,+ detail=None,+ )+ self.assertEqual(+ round_trip(contract._UniffiFfiConverterTypeVisualParseError, error),+ error,+ )+def test_action_target_is_public_and_uses_the_generated_contract(self) -> None:import cua_driverfrom cua_driver import (@@ -41,6 +142,14 @@ class GeneratedOptionsTests(unittest.TestCase):button=ClickButton.LEFT, count=1,)self.assertIs(click.target, target)+ captured = ClickInput(+ position=ClickPosition.CAPTURED_COORDINATES(+ x=10.0, y=20.0, capture_id="capture-1"+ ),+ target=target, delivery_mode=InputDeliveryMode.FOREGROUND,+ session=None, button=ClickButton.LEFT, count=1,+ )+ self.assertEqual(captured.position.capture_id, "capture-1")self.assertTrue(ActionTarget.WINDOW(pid=1, window_id=2).is_WINDOW())with self.assertRaises(TypeError):ClickInput(x=10.0, y=20.0)@@ -49,6 +158,9 @@ class GeneratedOptionsTests(unittest.TestCase):"InputDeliveryMode", "ListAppsInput", "ListAppsOutput", "ListWindowsInput","ListWindowsOutput", "SnapshotImage", "WindowBounds", "WindowElement","WindowInfo", "WindowStateOutput",+ "ParseVisualRegionsInput", "ParseVisualRegionsOptions",+ "ParseVisualRegionsOutput", "VisualCaptureProvenance",+ "VisualParseError", "VisualParseErrorCode", "VisualRegion",):self.assertIn(name, cua_driver.__all__)self.assertIsNotNone(getattr(cua_driver, name))@@ -168,6 +280,8 @@ except FileNotFoundError:EffectiveScope,StatePredicate,StartSessionOutput,+ ParseVisualRegionsInput,+ ParseVisualRegionsOptions,VerificationStatus,VerifyStateInput,WindowPredicate,@@ -189,7 +303,7 @@ except FileNotFoundError:captured: list[dict[str, object]] = []def serve() -> None:- while len(captured) < 2:+ while len(captured) < 3:connection, _ = listener.accept()with connection:line = connection.makefile("r", encoding="utf-8").readline()@@ -214,6 +328,31 @@ except FileNotFoundError:"samples": 2,"predicates": [],}+ elif request["name"] == "parse_visual_regions":+ structured = {+ "schema": "cua.visual_regions_v1",+ "capture": {+ "capture_id": "capture-123",+ "source": {"kind": "primary_desktop", "display_id": "primary"},+ "screenshot": {+ "reference": "sha256:abc",+ "width": 2,+ "height": 2,+ "mime_type": "image/png",+ "sha256": "abc",+ },+ "action_coordinate_space": {"kind": "identity"},+ },+ "parser": {+ "extension_id": "cua-perception",+ "extension_version": "1.0.0",+ "model_id": "fixture",+ "model_version": "1",+ "runtime": "fixture",+ },+ "regions": [],+ "timing": {"duration_ms": 1},+ }else:structured = {"effect": "unverifiable",@@ -256,6 +395,7 @@ except FileNotFoundError:"press_key","hotkey","verify_state",+ "parse_visual_regions",}self.assertTrue(all(hasattr(driver, name) for name in expected_methods))verification_result = asyncio.run(@@ -288,6 +428,16 @@ except FileNotFoundError:)))+ visual_result = asyncio.run(+ driver.parse_visual_regions(+ ParseVisualRegionsInput(+ capture_id="capture-123",+ options=ParseVisualRegionsOptions(+ kinds=None, min_confidence=None, max_regions=None+ ),+ )+ )+ )server.join(timeout=5)listener.close()@@ -300,6 +450,10 @@ except FileNotFoundError:self.assertEqual(action_result.effect, ActionEffect.UNVERIFIABLE)self.assertEqual(action_result.route, ActionRoute.GLOBAL_INPUT)self.assertFalse(hasattr(action_result, "verified"))+ self.assertEqual(+ json.loads(visual_result.structured_json)["schema"],+ "cua.visual_regions_v1",+ )self.assertEqual(captured[0]["name"], "verify_state")self.assertEqual(captured[0]["args"],@@ -327,6 +481,11 @@ except FileNotFoundError:"count": 1,},)+ self.assertEqual(captured[2]["name"], "parse_visual_regions")+ self.assertEqual(+ captured[2]["args"],+ {"capture_id": "capture-123", "options": {}},+ )def test_generated_python_sdk_can_own_the_runtime_in_process(self) -> None:from cua_driver import CuaDriver, DriverExecutionModediff --git a/libs/cua-driver/rust/Cargo.lock b/libs/cua-driver/rust/Cargo.lockindex a91f7242c9..2c0c1f5cdd 100644--- a/libs/cua-driver/rust/Cargo.lock+++ b/libs/cua-driver/rust/Cargo.lock@@ -59,6 +59,12 @@ version = "0.2.21"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"+[[package]]+name = "ambient-authority"+version = "0.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e9d4ee0d472d1cd2e28c97dfa124b3d8d992e10eb0a035f33f5d12e3a177ba3b"+[[package]]name = "android_system_properties"version = "0.1.5"@@ -665,6 +671,48 @@ dependencies = ["serde_core",]+[[package]]+name = "cap-fs-ext"+version = "4.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "56ff379b70af8e08307a8f65e7040c7301cb4a572538ade16b4984f0da77847f"+dependencies = [+ "cap-primitives",+ "cap-std",+ "io-lifetimes 3.0.1",+ "windows-sys 0.61.2",+]++[[package]]+name = "cap-primitives"+version = "4.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8b5f74729fd2f44701d1a8eb47e906cdb3ccd9ec0f02baad85a744b791940b18"+dependencies = [+ "ambient-authority",+ "fs-set-times",+ "io-extras",+ "io-lifetimes 3.0.1",+ "ipnet",+ "maybe-owned",+ "rustix",+ "rustix-linux-procfs",+ "windows-sys 0.61.2",+ "winx",+]++[[package]]+name = "cap-std"+version = "4.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c1ec78e242cfa2cfe276807ac2ecc00315a6c97786977414bcd1c3963b6c91b8"+dependencies = [+ "cap-primitives",+ "io-extras",+ "io-lifetimes 3.0.1",+ "rustix",+]+[[package]]name = "cargo-platform"version = "0.1.9"@@ -743,7 +791,7 @@ version = "0.15.8"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02"dependencies = [- "smallvec",+ "smallvec 1.15.1","target-lexicon",]@@ -1156,6 +1204,8 @@ dependencies = ["anyhow","async-trait","base64",+ "cap-fs-ext",+ "cap-std","core-foundation","cua-driver-contract","cua-driver-core",@@ -1164,6 +1214,7 @@ dependencies = ["cursor-overlay","embed-resource","flate2",+ "fs2","futures-util","httparse","image",@@ -1173,9 +1224,12 @@ dependencies = ["platform-linux","platform-macos","platform-windows",+ "ring",+ "rustix","semver","serde","serde_json",+ "sha2","tar","tempfile","tokio",@@ -1297,6 +1351,21 @@ dependencies = ["tracing-subscriber",]+[[package]]+name = "cua-perception"+version = "0.1.0"+dependencies = [+ "base64",+ "image",+ "libloading",+ "ort",+ "serde",+ "serde_json",+ "serde_yaml",+ "sha2",+ "thiserror 1.0.69",+]+[[package]]name = "cursor-overlay"version = "0.28.2"@@ -1731,6 +1800,17 @@ dependencies = ["autocfg",]+[[package]]+name = "fs-set-times"+version = "0.20.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a"+dependencies = [+ "io-lifetimes 2.0.4",+ "rustix",+ "windows-sys 0.52.0",+]+[[package]]name = "fs2"version = "0.4.3"@@ -2118,7 +2198,7 @@ dependencies = ["icu_normalizer_data","icu_properties","icu_provider",- "smallvec",+ "smallvec 1.15.1","zerovec",]@@ -2176,7 +2256,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"dependencies = ["idna_adapter",- "smallvec",+ "smallvec 1.15.1","utf8_iter",]@@ -2237,6 +2317,28 @@ dependencies = ["hybrid-array",]+[[package]]+name = "io-extras"+version = "0.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f"+dependencies = [+ "io-lifetimes 3.0.1",+ "windows-sys 0.52.0",+]++[[package]]+name = "io-lifetimes"+version = "2.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "06432fb54d3be7964ecd3649233cddf80db2832f47fec34c01f65b3d9d774983"++[[package]]+name = "io-lifetimes"+version = "3.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f0fb0570afe1fed943c5c3d4102d5358592d8625fda6a0007fdbe65a92fba96"+[[package]]name = "ipnet"version = "2.12.0"@@ -2468,6 +2570,22 @@ dependencies = ["regex-automata",]+[[package]]+name = "matrixmultiply"+version = "0.3.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7"+dependencies = [+ "autocfg",+ "rawpointer",+]++[[package]]+name = "maybe-owned"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4"+[[package]]name = "md-5"version = "0.10.6"@@ -2590,6 +2708,21 @@ dependencies = ["tempfile",]+[[package]]+name = "ndarray"+version = "0.16.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "882ed72dce9365842bf196bdeedf5055305f11fc8c03dee7bb0194a6cad34841"+dependencies = [+ "matrixmultiply",+ "num-complex",+ "num-integer",+ "num-traits",+ "portable-atomic",+ "portable-atomic-util",+ "rawpointer",+]+[[package]]name = "nix"version = "0.23.2"@@ -2685,7 +2818,7 @@ dependencies = ["once_cell","rand 0.9.5","serde",- "smallvec",+ "smallvec 1.15.1","zeroize",]@@ -3142,6 +3275,28 @@ dependencies = ["pin-project-lite",]+[[package]]+name = "ort"+version = "2.0.0-rc.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fa7e49bd669d32d7bc2a15ec540a527e7764aec722a45467814005725bcd721"+dependencies = [+ "libloading",+ "ndarray",+ "ort-sys",+ "smallvec 2.0.0-alpha.10",+ "tracing",+]++[[package]]+name = "ort-sys"+version = "2.0.0-rc.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e2aba9f5c7c479925205799216e7e5d07cc1d4fa76ea8058c60a9a30f6a4e890"+dependencies = [+ "pkg-config",+]+[[package]]name = "os_pipe"version = "1.2.3"@@ -3183,7 +3338,7 @@ dependencies = ["cfg-if","libc","redox_syscall",- "smallvec",+ "smallvec 1.15.1","windows-link 0.2.1",]@@ -3455,6 +3610,21 @@ dependencies = ["universal-hash",]+[[package]]+name = "portable-atomic"+version = "1.15.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"++[[package]]+name = "portable-atomic-util"+version = "0.2.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715"+dependencies = [+ "portable-atomic",+]+[[package]]name = "postcard"version = "1.1.3"@@ -3645,6 +3815,12 @@ version = "0.10.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"+[[package]]+name = "rawpointer"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3"+[[package]]name = "redox_syscall"version = "0.5.18"@@ -3825,6 +4001,16 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "rustix-linux-procfs"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2fc84bf7e9aa16c4f2c758f27412dc9841341e16aa682d9c7ac308fe3ee12056"+dependencies = [+ "once_cell",+ "rustix",+]+[[package]]name = "rustls"version = "0.23.40"@@ -4184,6 +4370,12 @@ version = "1.15.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"+[[package]]+name = "smallvec"+version = "2.0.0-alpha.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "51d44cfb396c3caf6fbfd0ab422af02631b69ddd96d2eff0b0f0724f9024051b"+[[package]]name = "smawk"version = "0.3.3"@@ -4662,7 +4854,7 @@ dependencies = ["once_cell","regex-automata","sharded-slab",- "smallvec",+ "smallvec 1.15.1","thread_local","tracing","tracing-core",@@ -5155,7 +5347,7 @@ dependencies = ["cc","downcast-rs","rustix",- "smallvec",+ "smallvec 1.15.1","wayland-sys",]@@ -5749,6 +5941,16 @@ dependencies = ["windows-sys 0.48.0",]+[[package]]+name = "winx"+version = "0.36.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d"+dependencies = [+ "bitflags 2.11.1",+ "windows-sys 0.52.0",+]+[[package]]name = "wit-bindgen"version = "0.51.0"diff --git a/libs/cua-driver/rust/Cargo.toml b/libs/cua-driver/rust/Cargo.tomlindex 351b08600d..7a7307700e 100644--- a/libs/cua-driver/rust/Cargo.toml+++ b/libs/cua-driver/rust/Cargo.toml@@ -14,6 +14,7 @@ members = ["crates/cursor-overlay","crates/cursor-theme-cli","crates/pip-preview",+ "crates/cua-perception",][workspace.package]@@ -41,6 +42,9 @@ zune-core = "=0.5.1"uniffi = "=0.31.0"postcard = { version = "1", features = ["alloc"] }sha2 = "0.10"+ort = { version = "=2.0.0-rc.10", default-features = false, features = ["std", "load-dynamic"] }+serde_yaml = "0.9"+libloading = "0.8"zstd = "0.13"chacha20poly1305 = { version = "0.11", features = ["rand_core", "zeroize"] }hkdf = "0.12"diff --git a/libs/cua-driver/rust/Skills/cua-driver/README.md b/libs/cua-driver/rust/Skills/cua-driver/README.mdindex 40a690c1a4..f227b28944 100644--- a/libs/cua-driver/rust/Skills/cua-driver/README.md+++ b/libs/cua-driver/rust/Skills/cua-driver/README.md@@ -7,7 +7,8 @@ CLI or MCP server.It covers the canonical snapshot-action-verify loop, exact window addressing,accessibility and pixel actions, background/foreground delivery, typed browser-automation, session recording, and platform-specific limitations. The skill+automation, optional visual-region parsing, session recording, and+platform-specific limitations. The skilldefaults to background delivery and requires structured refusal or observedfailure before a caller escalates to foreground input.@@ -66,6 +67,8 @@ Use `--all-platforms` when the agent assists users across operating systems.accessibility, input delivery, permissions, and refusal boundaries.- `BROWSER.md`: exact browser-window binding, explicit profile preparation,page refs, trust-classified click/type/navigation, and native fallbacks.+- `VISUAL.md`: optional model-neutral parsing of one retained screenshot into+ capture-bound text and icon regions.- `RECORDING.md`: trajectory evidence, MP4 capture, and replay.- `EMBEDDING.md`: embedding the driver into another host application.diff --git a/libs/cua-driver/rust/Skills/cua-driver/VISUAL.md b/libs/cua-driver/rust/Skills/cua-driver/VISUAL.mdnew file mode 100644index 0000000000..70d34a8b29--- /dev/null+++ b/libs/cua-driver/rust/Skills/cua-driver/VISUAL.md@@ -0,0 +1,128 @@+# Optional visual-region parsing++Use `parse_visual_regions` when a current Cua Driver screenshot contains useful+text or icons that accessibility and typed browser state do not expose. The+tool returns model-neutral observations. It does not decide that a region is+interactive, choose an action, or grant permission to act.++This capability is a developer preview delivered by the separately installed+`cua-perception` extension. It is absent from the default Cua Driver+installation. The default local Driver remains MIT licensed. The reviewed+candidate records the OmniParser detector artifact as AGPL-3.0-only and the+PP-OCR detector and recognizer as Apache-2.0. The packaged ONNX Runtime must+report its exact version, hash, license, and notices. Inspect the exact catalog,+manifest, SBOM, source ledger, model ledger, and built artifact rather than+applying the Driver license to them. Publication remains blocked while the+OmniParser ledger says `license-review-required`; distribution and remote+service require the applicable notices, corresponding source/conversion+material, and AGPL network source path.++## Inspect before installing++Never install the extension merely because a parse returned `not_installed`.+Use the catalog distributed with the reviewed release candidate, then inspect+the exact candidate:++```bash+cua-driver extension inspect cua-perception --catalog <catalog.json>+```++Review its version, target, capabilities, protocol range, worker and model+sizes, hashes, destination, licenses, publisher, and provenance. Installation+must be an explicit caller decision after that review:++```bash+cua-driver extension install cua-perception --catalog <catalog.json>+cua-driver extension status cua-perception+```++Use `cua-driver extension update cua-perception --catalog <catalog.json>` only+after inspecting the proposed replacement. Use+`cua-driver extension remove cua-perception` to remove extension-owned artifacts+when they are not in use.++Verified-catalog publication and the exact initial OCR/model artifact are still+pending release verification. If `inspect` cannot present authenticated+metadata for the exact artifact, stop. Do not invent an artifact URL, substitute+an unsigned archive, or describe the preview as a stable release.++Installation is never a side effect of Driver startup, capture, parsing, or+update checks. Parsing does not download code or model weights. The extension+is Rust-based and does not install Python. Driver does not request, store, or+forward Jev or any other decision-provider credential.++## Capture, parse, act once, and reobserve++Use one persistent MCP connection or one typed SDK runtime for the stateful+loop. A one-shot CLI tool call owns a disposable runtime, so a later process+cannot resolve its `capture_id`. Keep the four stages separate within the same+runtime:++1. Capture the exact native window with `get_window_state`, or an explicitly+ authorized desktop with `get_desktop_state`. Use a+ native-resolution capture when the preview requires it and retain the+ returned `capture_id`, target, dimensions, and action-coordinate mapping.+2. Call `parse_visual_regions` with that `capture_id` and bounded options. For+ example, request only `text`, set `min_confidence`, and cap `max_regions`.+3. Prefer accessibility or typed browser evidence when it identifies the same+ control. If a pixel action is necessary, construct one complete action+ locally from one region, validate that its bounds and target still match the+ source capture, then dispatch one `click` containing `x`, `y`, the exact+ target, `delivery_mode`, and that same `capture_id`. Never retry a capture+ refusal without `capture_id`. Dispatch at most one action derived from that+ capture.+4. Reobserve after every action attempt, including a timeout, unknown result,+ partial delivery, or suspected no-op. Verify the postcondition from fresh+ state before choosing another action.++Example parse shape:++```json+{+ "capture_id": "capture-from-current-observation",+ "options": {+ "kinds": ["text", "icon"],+ "min_confidence": 0.5,+ "max_regions": 100+ }+}+```++Region rectangles are half-open source-screenshot pixel bounds with a top-left+origin. Do not treat OCR text, an icon label, or an `interactive` hint as proof+that a region is actionable. Do not reuse a region after an action, resize,+move, scroll, navigation, display-layout change, or target-identity change.++## Handle failures by category++- `not_installed`: the optional `cua-perception` extension is absent. Continue with+ accessibility, browser, or caller-owned visual reasoning unless the user has+ chosen to inspect and install the preview.+- `capture_not_found`, `capture_expired`, `capture_stale`, or+ `capture_generation_mismatch`: take a fresh capture and parse that new ID.+- `unsupported_target` or `unsupported_platform`: use another observation+ route and preserve the reported limitation.+- `incompatible_protocol` or `artifact_invalid`: stop using the extension;+ inspect its exact installed state before any update or reinstall.+- `worker_launch_failed`, `worker_crashed`, `worker_cancelled`, `timeout`, or+ `inference_failed`: do not act from a partial or old result. Reobserve before+ a bounded retry or fallback.+- `invalid_frame` or `resource_limit_exceeded`: narrow the request or use a+ supported native-resolution capture; never clamp regions or silently change+ coordinates.++The worker parses only the admitted screenshot and bounded options. It does not+own desktop capture, accessibility, browser, input, credential-store, or action+authority.++Parsing a window does not make its pixel input background-safe. Preserve the+platform action ladder and exact `background_unavailable` refusal. Foreground+delivery and desktop input can change focus, workspace, or the system cursor;+use them only when already authorized for the workflow.++An external chooser, including a `jev-use` recipe, receives a bounded table of+opaque action IDs rather than open-ended Driver tool access. The caller keeps+provider setup and credentials outside Driver, validates one returned ID, and+dispatches the complete prebuilt action unchanged. See [Use jev-use with visual+regions](https://cua.ai/docs/how-to-guides/driver/use-jev-use-with-visual-regions);+do not add provider SDK logic or credentials to this skill.diff --git a/libs/cua-driver/rust/crates/cua-driver-contract/src/cursor.rs b/libs/cua-driver/rust/crates/cua-driver-contract/src/cursor.rsindex 87bc75ea75..482cfdfbc7 100644--- a/libs/cua-driver/rust/crates/cua-driver-contract/src/cursor.rs+++ b/libs/cua-driver/rust/crates/cua-driver-contract/src/cursor.rs@@ -246,7 +246,9 @@ pub fn classify_cursor_semantics(name: &str, args: &Value) -> Option<CursorSeman"start_session" | "escalate_session" | "get_session_state" | "end_session"| "check_permissions" | "get_config" | "set_config" | "health_report"| "browser_prepare" | "browser_close" | "browser_release" | "browser_activate"- | "install_ffmpeg" | "check_update" | "update" => CursorAction::System,+ | "install_ffmpeg" | "install_extension" | "check_update" | "update" => {+ CursorAction::System+ }"set_agent_cursor_enabled"| "set_agent_cursor_motion"diff --git a/libs/cua-driver/rust/crates/cua-driver-contract/src/cursor_tools.rs b/libs/cua-driver/rust/crates/cua-driver-contract/src/cursor_tools.rsindex 89ae2e1a95..c7313e7329 100644--- a/libs/cua-driver/rust/crates/cua-driver-contract/src/cursor_tools.rs+++ b/libs/cua-driver/rust/crates/cua-driver-contract/src/cursor_tools.rs@@ -62,6 +62,7 @@ fn contract<I: ToolInput, O: ToolOutput>(cursor_semantics: None,input_schema: I::input_schema(),success_output_schema: Some(O::output_schema()),+ error_output_schema: None,output_validator: crate::validate_typed_output::<O>,}}diff --git a/libs/cua-driver/rust/crates/cua-driver-contract/src/desktop.rs b/libs/cua-driver/rust/crates/cua-driver-contract/src/desktop.rsindex f30c11709a..1f52857db7 100644--- a/libs/cua-driver/rust/crates/cua-driver-contract/src/desktop.rs+++ b/libs/cua-driver/rust/crates/cua-driver-contract/src/desktop.rs@@ -147,6 +147,7 @@ fn contract<I: ToolInput, O: ToolOutput>(cursor_semantics: Some(CursorSemantics::new(cursor_action)),input_schema: I::input_schema(),success_output_schema: Some(O::output_schema()),+ error_output_schema: None,output_validator: crate::validate_typed_output::<O>,}}diff --git a/libs/cua-driver/rust/crates/cua-driver-contract/src/inputs.rs b/libs/cua-driver/rust/crates/cua-driver-contract/src/inputs.rsindex 69bd68f715..9afc4ff687 100644--- a/libs/cua-driver/rust/crates/cua-driver-contract/src/inputs.rs+++ b/libs/cua-driver/rust/crates/cua-driver-contract/src/inputs.rs@@ -62,6 +62,10 @@ fn string_schema(generator: &mut SchemaGenerator) -> Schema {String::json_schema(generator)}+fn nonempty_string_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({ "type": "string", "minLength": 1 })+}+pub const MULTI_CALL_SESSION_DESCRIPTION: &str ="For multi-call work, prefer a short public session label and repeat it on every call that \accepts it. Omit it to use the authenticated transport's implicit lifecycle session.";@@ -606,6 +610,7 @@ pub enum InputDeliveryMode {pub enum ClickPosition {Coordinates { x: f64, y: f64 },Element { element_token: String },+ CapturedCoordinates { x: f64, y: f64, capture_id: String },}#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, uniffi::Record)]@@ -623,6 +628,11 @@ pub struct ClickInput {pub count: Option<u32>,}+impl ClickInput {+ pub const DESKTOP_BACKGROUND_MESSAGE: &'static str =+ "desktop clicks require delivery_mode:\"foreground\"; background delivery is unavailable for desktop targets";+}+// Parse the flat wire shape before constructing the sum type: an untagged// serde enum alone would silently accept mixed coordinate and element fields.#[derive(Debug, Deserialize, JsonSchema)]@@ -639,6 +649,9 @@ struct ClickWireInput {#[serde(default, deserialize_with = "present_click_field")]#[schemars(schema_with = "string_schema")]element_token: Option<String>,+ #[serde(default, deserialize_with = "present_click_field")]+ #[schemars(schema_with = "nonempty_string_schema")]+ capture_id: Option<String>,/// For multi-call work, prefer a short public session label and repeat it on every call that/// accepts it. Omit it to use the authenticated transport's implicit lifecycle session.#[serde(default)]@@ -663,9 +676,12 @@ whereimpl TryFrom<ClickWireInput> for ClickInput {type Error = String;fn try_from(wire: ClickWireInput) -> Result<Self, Self::Error> {- let position = match (wire.x, wire.y, wire.element_token) {- (Some(x), Some(y), None) => ClickPosition::Coordinates { x, y },- (None, None, Some(element_token)) => ClickPosition::Element { element_token },+ let position = match (wire.x, wire.y, wire.element_token, wire.capture_id) {+ (Some(x), Some(y), None, None) => ClickPosition::Coordinates { x, y },+ (Some(x), Some(y), None, Some(capture_id)) => {+ ClickPosition::CapturedCoordinates { x, y, capture_id }+ }+ (None, None, Some(element_token), None) => ClickPosition::Element { element_token },_ => return Err("click requires exactly x and y, or element_token".into()),};let input = Self {@@ -689,7 +705,7 @@ impl JsonSchema for ClickInput {let mut schema = ClickWireInput::json_schema(generator);schema.insert("oneOf".into(), serde_json::json!([{"required":["x","y"], "not":{"required":["element_token"]}},- {"required":["element_token"], "not":{"anyOf":[{"required":["x"]},{"required":["y"]}]}}+ {"required":["element_token"], "not":{"anyOf":[{"required":["x"]},{"required":["y"]},{"required":["capture_id"]}]}}]));schema}@@ -702,6 +718,11 @@ impl ToolInput for ClickInput {ClickPosition::Coordinates { x, y } if !x.is_finite() || !y.is_finite() => {return Err("click coordinates must be finite".into())}+ ClickPosition::CapturedCoordinates { x, y, capture_id }+ if !x.is_finite() || !y.is_finite() || capture_id.trim().is_empty() =>+ {+ return Err("captured click coordinates and capture_id must be valid".into())+ }ClickPosition::Element { element_token } if element_token.trim().is_empty() => {return Err("element_token must not be empty".into())}@@ -712,7 +733,7 @@ impl ToolInput for ClickInput {return Err("portable desktop target must be primary".into());}if self.delivery_mode != InputDeliveryMode::Foreground {- return Err("desktop clicks require foreground delivery".into());+ return Err(Self::DESKTOP_BACKGROUND_MESSAGE.into());}if matches!(self.position, ClickPosition::Element { .. }) {return Err("element clicks require an exact window target".into());@@ -915,7 +936,11 @@ mod tests {#[test]fn typed_click_round_trips_flat_native_wire_and_exact_window_id() {- for position in [json!({"x":-1.5,"y":2.0}), json!({"element_token":"s1:0"})] {+ for position in [+ json!({"x":-1.5,"y":2.0}),+ json!({"x":-1.5,"y":2.0,"capture_id":"capture-1"}),+ json!({"element_token":"s1:0"}),+ ] {let mut wire = json!({"target":{"kind":"window","pid":7,"window_id":9007199254740993_u64},"delivery_mode":"background"});wire.as_object_mut().unwrap()@@ -927,6 +952,8 @@ mod tests {assert_eq!(schema["required"], json!(["target", "delivery_mode"]));assert!(schema["oneOf"].is_array());assert!(schema["properties"].get("position").is_none());+ assert!(schema["properties"].get("capture_id").is_some());+ assert_eq!(schema["properties"]["capture_id"]["minLength"], 1);}#[test]@@ -936,6 +963,8 @@ mod tests {json!({"x":1}),json!({"y":2}),json!({"x":1,"y":2,"element_token":"s1:0"}),+ json!({"element_token":"s1:0","capture_id":"capture-1"}),+ json!({"x":1,"y":2,"capture_id":" "}),json!({"x":1,"element_token":"s1:0"}),json!({"x":null,"element_token":"s1:0"}),json!({"element_token":" "}),@@ -973,7 +1002,10 @@ mod tests {assert!(input.validate().is_err());input.position = ClickPosition::Coordinates { x: 1.0, y: 2.0 };input.delivery_mode = InputDeliveryMode::Background;- assert!(input.validate().is_err());+ assert_eq!(+ input.validate().unwrap_err(),+ ClickInput::DESKTOP_BACKGROUND_MESSAGE+ );}#[test]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.rsindex ef089ba101..964baf39ac 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@@ -21,6 +21,7 @@ mod inputs;mod outputs;mod session;mod verification;+mod visual;mod windows;pub use windows::*;@@ -55,6 +56,13 @@ pub use verification::{UnknownReason, VerificationStatus, VerifyStateInput, VerifyStateOutput, WindowPredicate,VERIFY_STATE_DEFAULT_TIMEOUT_MS,};+pub use visual::{+ ParseVisualRegionsInput, ParseVisualRegionsOptions, ParseVisualRegionsOutput,+ VisualActionCoordinateSpace, VisualCaptureProvenance, VisualCaptureSource,+ VisualContractValidationError, VisualParseError, VisualParseErrorCode, VisualParseTiming,+ VisualParseWarning, VisualParserMetadata, VisualRegion, VisualRegionBounds, VisualRegionKind,+ VisualScreenshotReference, VISUAL_REGIONS_SCHEMA,+};/// Shape version for the MCP `tools/list` result emitted by cua-driver.pub const TOOLS_LIST_SCHEMA_VERSION: &str = "1";@@ -170,6 +178,10 @@ pub struct ToolContract {/// advertises this as `outputSchema`.#[serde(skip_serializing_if = "Option::is_none")]pub success_output_schema: Option<Value>,+ /// Stable tool-specific structured error payload, when the tool exposes+ /// one in addition to the shared transport refusal envelope.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub error_output_schema: Option<Value>,/// Runtime-only validator bound to the same Rust output type that produced/// `success_output_schema`; omitted from the generated manifest.#[serde(skip, default = "default_output_validator")]@@ -195,6 +207,7 @@ pub fn manifest() -> ContractManifest {tools.extend(desktop::contracts());tools.extend(cursor_tools::contracts());tools.extend(verification::contracts());+ tools.extend(visual::contracts());tools.sort_by(|left, right| left.name.cmp(&right.name));ContractManifest {generated_notice: "Generated by cua-contract-gen; do not edit by hand.".into(),diff --git a/libs/cua-driver/rust/crates/cua-driver-contract/src/session.rs b/libs/cua-driver/rust/crates/cua-driver-contract/src/session.rsindex d887050f06..159ebc35a3 100644--- a/libs/cua-driver/rust/crates/cua-driver-contract/src/session.rs+++ b/libs/cua-driver/rust/crates/cua-driver-contract/src/session.rs@@ -32,6 +32,7 @@ fn contract<I: ToolInput, O: ToolOutput>(cursor_semantics: Some(CursorSemantics::new(CursorAction::System)),input_schema: I::input_schema(),success_output_schema: Some(O::output_schema()),+ error_output_schema: None,output_validator: crate::validate_typed_output::<O>,}}diff --git a/libs/cua-driver/rust/crates/cua-driver-contract/src/verification.rs b/libs/cua-driver/rust/crates/cua-driver-contract/src/verification.rsindex fb4c068baf..acba4dbb6b 100644--- a/libs/cua-driver/rust/crates/cua-driver-contract/src/verification.rs+++ b/libs/cua-driver/rust/crates/cua-driver-contract/src/verification.rs@@ -250,6 +250,7 @@ pub fn contracts() -> Vec<ToolContract> {cursor_semantics: None,input_schema: VerifyStateInput::input_schema(),success_output_schema: Some(VerifyStateOutput::output_schema()),+ error_output_schema: None,output_validator: crate::validate_typed_output::<VerifyStateOutput>,}]}diff --git a/libs/cua-driver/rust/crates/cua-driver-contract/src/visual.rs b/libs/cua-driver/rust/crates/cua-driver-contract/src/visual.rsnew file mode 100644index 0000000000..a86d8b9d6f--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-contract/src/visual.rs@@ -0,0 +1,1008 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 Cua AI, Inc.++//! Model-neutral DTOs for parsing an immutable screenshot into visual regions.+//!+//! This module is a transport-free public contract. It registers the callable+//! tool schema without implementing dispatch. A Driver-owned capture registry+//! must retain an immutable PNG together with its exact+//! target and screenshot-to-action transform for every `capture_id`. Current+//! `WindowStateOutput::snapshot_id` values do not retain screenshot pixels, and+//! `DesktopStateOutput` has no capture ID, so neither satisfies this contract.+//!+//! V1 deliberately refers to registry captures instead of accepting inline+//! bytes or file paths. Existing MCP images carry base64 data in the envelope,+//! while file paths are local-process metadata and are not portable. The V1+//! DTOs use explicit fields compatible with UniFFI; future additive data should+//! use optional typed fields or a new versioned schema rather than dynamic JSON.++use crate::{+ CursorAction, CursorSemantics, Platform, SchemaMode, ToolAnnotations, ToolContract, ToolInput,+ ToolOutput,+};+use schemars::{json_schema, JsonSchema, Schema, SchemaGenerator};+use serde::{Deserialize, Serialize};+use serde_json::Value;+use std::collections::BTreeSet;++pub const VISUAL_REGIONS_SCHEMA: &str = "cua.visual_regions_v1";++fn positive_integer_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({ "type": "integer", "minimum": 1 })+}++fn pixel_integer_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({ "type": "integer", "minimum": 0 })+}++fn confidence_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({ "type": "number", "minimum": 0, "maximum": 1 })+}++fn png_mime_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({ "const": "image/png" })+}++fn primary_display_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({ "const": "primary" })+}++fn visual_regions_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({ "const": VISUAL_REGIONS_SCHEMA })+}++fn region_kinds_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "anyOf": [+ {+ "type": "array",+ "minItems": 1,+ "maxItems": 2,+ "uniqueItems": true,+ "items": { "enum": ["text", "icon"] }+ },+ { "type": "null" }+ ]+ })+}++/// Exact screen content that produced the immutable capture.+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, uniffi::Enum)]+#[serde(tag = "kind", rename_all = "snake_case")]+pub enum VisualCaptureSource {+ Window {+ pid: u32,+ window_id: u64,+ },+ PrimaryDesktop {+ #[schemars(schema_with = "primary_display_schema")]+ display_id: String,+ },+}++/// Screenshot identity and geometry retained by the future capture registry.+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, uniffi::Record)]+pub struct VisualScreenshotReference {+ /// Opaque identity for these exact encoded pixels, such as a content digest.+ pub reference: String,+ #[schemars(schema_with = "positive_integer_schema")]+ pub width: u32,+ #[schemars(schema_with = "positive_integer_schema")]+ pub height: u32,+ #[schemars(schema_with = "png_mime_schema")]+ pub mime_type: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub sha256: Option<String>,+}++/// Normative mapping from source screenshot pixels to Driver action coordinates.+///+/// Screenshot coordinates always originate at the encoded PNG's top-left; X+/// increases right and Y increases down. The affine form maps a source point+/// `(px, py)` exactly as:+///+/// `action_x = m11 * px + m12 * py + tx`+///+/// `action_y = m21 * px + m22 * py + ty`+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, uniffi::Enum)]+#[serde(tag = "kind", rename_all = "snake_case")]+pub enum VisualActionCoordinateSpace {+ /// Action coordinates are the same physical pixel coordinates as the PNG.+ ScreenshotPixels,+ /// Lossless six-coefficient affine transform retained by the capture registry.+ Affine {+ m11: f64,+ m12: f64,+ m21: f64,+ m22: f64,+ tx: f64,+ ty: f64,+ },+}++impl VisualActionCoordinateSpace {+ pub fn map_point(&self, pixel_x: f64, pixel_y: f64) -> (f64, f64) {+ match self {+ Self::ScreenshotPixels => (pixel_x, pixel_y),+ Self::Affine {+ m11,+ m12,+ m21,+ m22,+ tx,+ ty,+ } => (+ m11.mul_add(pixel_x, m12.mul_add(pixel_y, *tx)),+ m21.mul_add(pixel_x, m22.mul_add(pixel_y, *ty)),+ ),+ }+ }++ fn validate(&self) -> Result<(), VisualContractValidationError> {+ match self {+ Self::ScreenshotPixels => Ok(()),+ Self::Affine {+ m11,+ m12,+ m21,+ m22,+ tx,+ ty,+ } if [m11, m12, m21, m22, tx, ty]+ .into_iter()+ .all(|value| value.is_finite())+ && m11.mul_add(*m22, -(*m12 * *m21)).abs() > f64::EPSILON =>+ {+ Ok(())+ }+ Self::Affine { .. } => Err(VisualContractValidationError::InvalidCoordinateSpace),+ }+ }+}++/// Immutable capture provenance echoed by a parse result.+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, uniffi::Record)]+pub struct VisualCaptureProvenance {+ pub capture_id: String,+ pub source: VisualCaptureSource,+ pub screenshot: VisualScreenshotReference,+ pub action_coordinate_space: VisualActionCoordinateSpace,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub captured_at: Option<String>,+}++/// Optional, model-neutral controls for one bounded parse.+#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema, PartialEq, uniffi::Record)]+#[serde(deny_unknown_fields)]+pub struct ParseVisualRegionsOptions {+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(schema_with = "region_kinds_schema")]+ pub kinds: Option<Vec<VisualRegionKind>>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(schema_with = "confidence_schema")]+ pub min_confidence: Option<f64>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(schema_with = "positive_integer_schema")]+ pub max_regions: Option<u32>,+}++/// Transport-free request. Runtime use requires the future capture registry.+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, uniffi::Record)]+#[serde(deny_unknown_fields)]+pub struct ParseVisualRegionsInput {+ #[schemars(length(min = 1))]+ pub capture_id: String,+ #[serde(default)]+ pub options: ParseVisualRegionsOptions,+}++impl ToolInput for ParseVisualRegionsInput {+ const TOOL_NAME: &'static str = "parse_visual_regions";++ fn validate(&self) -> Result<(), String> {+ ParseVisualRegionsInput::validate(self).map_err(|error| error.to_string())+ }+}++#[derive(+ Debug,+ Clone,+ Copy,+ Serialize,+ Deserialize,+ JsonSchema,+ PartialEq,+ Eq,+ PartialOrd,+ Ord,+ uniffi::Enum,+)]+#[serde(rename_all = "snake_case")]+pub enum VisualRegionKind {+ Text,+ Icon,+}++/// Integer pixel-edge bounds `[x, x + width) x [y, y + height)`.+///+/// `x` and `y` name the left and top pixel edges. The right and bottom edges+/// are excluded. A region therefore covers every pixel whose center lies in+/// this half-open box; its geometric center may lie between pixels.+#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema, PartialEq, Eq, uniffi::Record)]+pub struct VisualRegionBounds {+ #[schemars(schema_with = "pixel_integer_schema")]+ pub x: u32,+ #[schemars(schema_with = "pixel_integer_schema")]+ pub y: u32,+ #[schemars(schema_with = "positive_integer_schema")]+ pub width: u32,+ #[schemars(schema_with = "positive_integer_schema")]+ pub height: u32,+}++impl VisualRegionBounds {+ /// Geometric center in screenshot pixels. Odd-sized boxes intentionally+ /// produce half-pixel centers; no redundant rounded integer center is sent.+ /// The `f64` point is preserved through Driver mapping. Native dispatch may+ /// round only under the affected platform action contract, outside V1.+ pub fn center(&self) -> (f64, f64) {+ (+ f64::from(self.x) + f64::from(self.width) / 2.0,+ f64::from(self.y) + f64::from(self.height) / 2.0,+ )+ }+}++/// One parser-observed region in the exact source screenshot pixel space.+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, uniffi::Record)]+pub struct VisualRegion {+ /// Stable identifier unique within this parse result.+ pub id: String,+ pub kind: VisualRegionKind,+ pub bounds: VisualRegionBounds,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub text: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub label: Option<String>,+ #[schemars(schema_with = "confidence_schema")]+ pub confidence: f64,+ pub interactive: bool,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub parent_id: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub group_id: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub reading_order: Option<u32>,+}++impl VisualRegion {+ /// Map the unrounded geometric center into action coordinates. This DTO+ /// layer never applies integer rounding or platform dispatch policy.+ pub fn action_center(&self, space: &VisualActionCoordinateSpace) -> (f64, f64) {+ let (pixel_x, pixel_y) = self.bounds.center();+ space.map_point(pixel_x, pixel_y)+ }+}++/// Identity of the extension and model that produced a result.+#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, uniffi::Record)]+pub struct VisualParserMetadata {+ pub extension_id: String,+ pub extension_version: String,+ pub model_id: String,+ pub model_version: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub runtime: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub backend: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub model_source_revision: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub model_manifest_sha256: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub onnx_runtime_version: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub onnx_runtime_library_sha256: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub fixture_sha256: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, uniffi::Record)]+pub struct VisualParseWarning {+ pub code: String,+ pub message: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub detail: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, uniffi::Record)]+pub struct VisualParseTiming {+ pub duration_ms: u64,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub preprocess_ms: Option<u64>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub inference_ms: Option<u64>,+}++#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, uniffi::Record)]+pub struct ParseVisualRegionsOutput {+ #[schemars(schema_with = "visual_regions_schema")]+ pub schema: String,+ pub capture: VisualCaptureProvenance,+ pub parser: VisualParserMetadata,+ pub regions: Vec<VisualRegion>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub warnings: Vec<VisualParseWarning>,+ pub timing: VisualParseTiming,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub request_id: Option<String>,+}++impl ToolOutput for ParseVisualRegionsOutput {+ fn validate(&self) -> Result<(), String> {+ ParseVisualRegionsOutput::validate(self).map_err(|error| error.to_string())+ }+}++/// Stable machine-readable failures for capture lookup and visual parsing.+#[derive(+ Debug,+ Clone,+ Copy,+ Serialize,+ Deserialize,+ JsonSchema,+ PartialEq,+ Eq,+ PartialOrd,+ Ord,+ uniffi::Enum,+)]+#[serde(rename_all = "snake_case")]+pub enum VisualParseErrorCode {+ NotInstalled,+ CaptureNotFound,+ CaptureExpired,+ CaptureStale,+ CaptureGenerationMismatch,+ UnsupportedTarget,+ UnsupportedPlatform,+ IncompatibleProtocol,+ InvalidFrame,+ WorkerLaunchFailed,+ WorkerCrashed,+ WorkerCancelled,+ Timeout,+ ResourceLimitExceeded,+ ArtifactInvalid,+ InferenceFailed,+}++#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, uniffi::Record)]+pub struct VisualParseError {+ pub code: VisualParseErrorCode,+ pub message: String,+ pub retryable: bool,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub detail: Option<String>,+}++fn error_schema() -> Value {+ crate::outputs::output_schema_with_additional_properties::<VisualParseError>(false)+}++const ALL_PLATFORMS: [Platform; 3] = [Platform::Macos, Platform::Windows, Platform::Linux];++pub(crate) fn contracts() -> Vec<ToolContract> {+ vec![ToolContract {+ name: ParseVisualRegionsInput::TOOL_NAME.into(),+ description:+ "Parse one immutable registered capture into model-neutral text and icon regions."+ .into(),+ platforms: ALL_PLATFORMS.to_vec(),+ aliases: Vec::new(),+ capabilities: vec![+ "visual.regions.parse".into(),+ "screen.capture.registry.read".into(),+ ],+ annotations: ToolAnnotations {+ read_only: true,+ destructive: false,+ idempotent: true,+ open_world: false,+ },+ schema_mode: SchemaMode::CanonicalRuntime,+ cursor_semantics: Some(CursorSemantics::new(CursorAction::Observe)),+ input_schema: ParseVisualRegionsInput::input_schema(),+ success_output_schema: Some(ParseVisualRegionsOutput::output_schema()),+ error_output_schema: Some(error_schema()),+ output_validator: crate::validate_typed_output::<ParseVisualRegionsOutput>,+ }]+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum VisualContractValidationError {+ EmptyCaptureId,+ InvalidCaptureSource,+ EmptyScreenshotReference,+ InvalidScreenshotDimensions,+ UnsupportedScreenshotMimeType,+ InvalidScreenshotDigest,+ InvalidCaptureMetadata,+ InvalidCoordinateSpace,+ InvalidMinimumConfidence,+ InvalidMaximumRegions,+ InvalidRegionKinds,+ InvalidResultSchema,+ InvalidRegionSize,+ RegionOutsideScreenshot,+ InvalidRegionConfidence,+ EmptyRegionId,+ DuplicateRegionId,+ InvalidRegionContent,+ MissingRegionReference,+ SelfRegionReference,+ CyclicParentReference,+ InvalidParserMetadata,+ InvalidWarning,+ InvalidTiming,+ InvalidRequestId,+ InvalidError,+}++impl std::fmt::Display for VisualContractValidationError {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter.write_str(match self {+ Self::EmptyCaptureId => "capture_id must not be empty",+ Self::InvalidCaptureSource => {+ "capture source must identify a positive window or the primary display"+ }+ Self::EmptyScreenshotReference => "screenshot reference must not be empty",+ Self::InvalidScreenshotDimensions => "screenshot dimensions must be positive",+ Self::UnsupportedScreenshotMimeType => "screenshot mime_type must be image/png",+ Self::InvalidScreenshotDigest => "screenshot sha256 must be a 64-character hex digest",+ Self::InvalidCaptureMetadata => "optional capture metadata must not be empty",+ Self::InvalidCoordinateSpace => {+ "action coordinate transform must be finite and invertible"+ }+ Self::InvalidMinimumConfidence => "min_confidence must be finite and between 0 and 1",+ Self::InvalidMaximumRegions => "max_regions must be positive",+ Self::InvalidRegionKinds => "kinds must contain unique text or icon entries",+ Self::InvalidResultSchema => "visual result schema is not cua.visual_regions_v1",+ Self::InvalidRegionSize => "visual region width and height must be positive",+ Self::RegionOutsideScreenshot => "visual region bounds exceed the screenshot",+ Self::InvalidRegionConfidence => "region confidence must be finite and between 0 and 1",+ Self::EmptyRegionId => "visual region id must not be empty",+ Self::DuplicateRegionId => "visual region ids must be unique within a result",+ Self::InvalidRegionContent => "text and icon regions require matching content",+ Self::MissingRegionReference => "parent_id and group_id must reference a result region",+ Self::SelfRegionReference => "a region cannot parent or group itself",+ Self::CyclicParentReference => "parent_id references must not form a cycle",+ Self::InvalidParserMetadata => {+ "parser and model identifiers and versions must not be empty"+ }+ Self::InvalidWarning => "warning code and message must not be empty",+ Self::InvalidTiming => "timing components must not exceed total duration",+ Self::InvalidRequestId => "request_id must not be empty when present",+ Self::InvalidError => {+ "visual parse error message and optional detail must not be empty"+ }+ })+ }+}++impl std::error::Error for VisualContractValidationError {}++fn nonempty(value: &str) -> bool {+ !value.trim().is_empty()+}++fn valid_sha256(value: &str) -> bool {+ value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit())+}++impl VisualScreenshotReference {+ fn validate(&self) -> Result<(), VisualContractValidationError> {+ if !nonempty(&self.reference) {+ return Err(VisualContractValidationError::EmptyScreenshotReference);+ }+ if self.width == 0 || self.height == 0 {+ return Err(VisualContractValidationError::InvalidScreenshotDimensions);+ }+ if self.mime_type != "image/png" {+ return Err(VisualContractValidationError::UnsupportedScreenshotMimeType);+ }+ if self.sha256.as_ref().is_some_and(|digest| {+ digest.len() != 64 || !digest.bytes().all(|byte| byte.is_ascii_hexdigit())+ }) {+ return Err(VisualContractValidationError::InvalidScreenshotDigest);+ }+ Ok(())+ }+}++impl ParseVisualRegionsInput {+ pub fn validate(&self) -> Result<(), VisualContractValidationError> {+ if !nonempty(&self.capture_id) {+ return Err(VisualContractValidationError::EmptyCaptureId);+ }+ if self+ .options+ .min_confidence+ .is_some_and(|value| !value.is_finite() || !(0.0..=1.0).contains(&value))+ {+ return Err(VisualContractValidationError::InvalidMinimumConfidence);+ }+ if self.options.max_regions == Some(0) {+ return Err(VisualContractValidationError::InvalidMaximumRegions);+ }+ if self.options.kinds.as_ref().is_some_and(|kinds| {+ kinds.is_empty()+ || kinds.len() > 2+ || kinds.iter().collect::<BTreeSet<_>>().len() != kinds.len()+ }) {+ return Err(VisualContractValidationError::InvalidRegionKinds);+ }+ Ok(())+ }+}++impl ParseVisualRegionsOutput {+ pub fn validate(&self) -> Result<(), VisualContractValidationError> {+ if self.schema != VISUAL_REGIONS_SCHEMA {+ return Err(VisualContractValidationError::InvalidResultSchema);+ }+ if !nonempty(&self.capture.capture_id) {+ return Err(VisualContractValidationError::EmptyCaptureId);+ }+ match &self.capture.source {+ VisualCaptureSource::Window { pid, window_id } if *pid == 0 || *window_id == 0 => {+ return Err(VisualContractValidationError::InvalidCaptureSource);+ }+ VisualCaptureSource::PrimaryDesktop { display_id } if display_id != "primary" => {+ return Err(VisualContractValidationError::InvalidCaptureSource);+ }+ _ => {}+ }+ self.capture.screenshot.validate()?;+ self.capture.action_coordinate_space.validate()?;+ if self+ .capture+ .captured_at+ .as_ref()+ .is_some_and(|value| !nonempty(value))+ {+ return Err(VisualContractValidationError::InvalidCaptureMetadata);+ }+ if !nonempty(&self.parser.extension_id)+ || !nonempty(&self.parser.extension_version)+ || !nonempty(&self.parser.model_id)+ || !nonempty(&self.parser.model_version)+ || self+ .parser+ .runtime+ .as_ref()+ .is_some_and(|value| !nonempty(value))+ || self+ .parser+ .backend+ .as_ref()+ .is_some_and(|value| !nonempty(value))+ || self+ .parser+ .model_source_revision+ .as_ref()+ .is_some_and(|value| !nonempty(value))+ || self+ .parser+ .onnx_runtime_version+ .as_ref()+ .is_some_and(|value| !nonempty(value))+ || self+ .parser+ .model_manifest_sha256+ .as_ref()+ .is_some_and(|value| !valid_sha256(value))+ || self+ .parser+ .onnx_runtime_library_sha256+ .as_ref()+ .is_some_and(|value| !valid_sha256(value))+ || self+ .parser+ .fixture_sha256+ .as_ref()+ .is_some_and(|value| !valid_sha256(value))+ {+ return Err(VisualContractValidationError::InvalidParserMetadata);+ }+ if self+ .request_id+ .as_ref()+ .is_some_and(|value| !nonempty(value))+ {+ return Err(VisualContractValidationError::InvalidRequestId);+ }+ if self.warnings.iter().any(|warning| {+ !nonempty(&warning.code)+ || !nonempty(&warning.message)+ || warning+ .detail+ .as_ref()+ .is_some_and(|value| !nonempty(value))+ }) {+ return Err(VisualContractValidationError::InvalidWarning);+ }+ if self+ .timing+ .preprocess_ms+ .unwrap_or(0)+ .checked_add(self.timing.inference_ms.unwrap_or(0))+ .is_none_or(|value| value > self.timing.duration_ms)+ {+ return Err(VisualContractValidationError::InvalidTiming);+ }++ if self.regions.iter().any(|region| !nonempty(®ion.id)) {+ return Err(VisualContractValidationError::EmptyRegionId);+ }+ let region_ids: BTreeSet<&str> = self+ .regions+ .iter()+ .map(|region| region.id.as_str())+ .collect();+ if region_ids.len() != self.regions.len() {+ return Err(VisualContractValidationError::DuplicateRegionId);+ }++ for region in &self.regions {+ if region.bounds.width == 0 || region.bounds.height == 0 {+ return Err(VisualContractValidationError::InvalidRegionSize);+ }+ let right = region+ .bounds+ .x+ .checked_add(region.bounds.width)+ .ok_or(VisualContractValidationError::RegionOutsideScreenshot)?;+ let bottom = region+ .bounds+ .y+ .checked_add(region.bounds.height)+ .ok_or(VisualContractValidationError::RegionOutsideScreenshot)?;+ if right > self.capture.screenshot.width || bottom > self.capture.screenshot.height {+ return Err(VisualContractValidationError::RegionOutsideScreenshot);+ }+ if !region.confidence.is_finite() || !(0.0..=1.0).contains(®ion.confidence) {+ return Err(VisualContractValidationError::InvalidRegionConfidence);+ }+ if region.text.as_ref().is_some_and(|value| !nonempty(value))+ || region.label.as_ref().is_some_and(|value| !nonempty(value))+ {+ return Err(VisualContractValidationError::InvalidRegionContent);+ }+ let content_valid = match region.kind {+ VisualRegionKind::Text => region.text.as_deref().is_some_and(nonempty),+ VisualRegionKind::Icon => region.label.as_deref().is_some_and(nonempty),+ };+ if !content_valid {+ return Err(VisualContractValidationError::InvalidRegionContent);+ }+ for reference in [®ion.parent_id, ®ion.group_id].into_iter().flatten() {+ if reference == ®ion.id {+ return Err(VisualContractValidationError::SelfRegionReference);+ }+ if !region_ids.contains(reference.as_str()) {+ return Err(VisualContractValidationError::MissingRegionReference);+ }+ }+ }++ for region in &self.regions {+ let mut visited = BTreeSet::from([region.id.as_str()]);+ let mut parent = region.parent_id.as_deref();+ while let Some(parent_id) = parent {+ if !visited.insert(parent_id) {+ return Err(VisualContractValidationError::CyclicParentReference);+ }+ parent = self+ .regions+ .iter()+ .find(|candidate| candidate.id == parent_id)+ .and_then(|candidate| candidate.parent_id.as_deref());+ }+ }+ Ok(())+ }+}++impl VisualParseError {+ pub fn validate(&self) -> Result<(), VisualContractValidationError> {+ if !nonempty(&self.message) || self.detail.as_ref().is_some_and(|value| !nonempty(value)) {+ return Err(VisualContractValidationError::InvalidError);+ }+ Ok(())+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ fn capture() -> VisualCaptureProvenance {+ VisualCaptureProvenance {+ capture_id: "capture-1".into(),+ source: VisualCaptureSource::Window {+ pid: 7,+ window_id: 9,+ },+ screenshot: VisualScreenshotReference {+ reference: "snapshot-1".into(),+ width: 1280,+ height: 720,+ mime_type: "image/png".into(),+ sha256: None,+ },+ action_coordinate_space: VisualActionCoordinateSpace::Affine {+ m11: 0.5,+ m12: 0.25,+ m21: -0.5,+ m22: 2.0,+ tx: 100.0,+ ty: 200.0,+ },+ captured_at: Some("2026-09-17T12:00:00Z".into()),+ }+ }++ fn parser() -> VisualParserMetadata {+ VisualParserMetadata {+ extension_id: "visual-parser".into(),+ extension_version: "1.0.0".into(),+ model_id: "default".into(),+ model_version: "1".into(),+ runtime: Some("cpu".into()),+ backend: Some("onnx_runtime_cpu".into()),+ model_source_revision: Some("revision-1".into()),+ model_manifest_sha256: Some("a".repeat(64)),+ onnx_runtime_version: Some("1.26.0".into()),+ onnx_runtime_library_sha256: Some("b".repeat(64)),+ fixture_sha256: None,+ }+ }++ fn region(id: &str) -> VisualRegion {+ VisualRegion {+ id: id.into(),+ kind: VisualRegionKind::Text,+ bounds: VisualRegionBounds {+ x: 11,+ y: 20,+ width: 101,+ height: 21,+ },+ text: Some("Apply".into()),+ label: None,+ confidence: 0.95,+ interactive: true,+ parent_id: None,+ group_id: None,+ reading_order: Some(1),+ }+ }++ fn output() -> ParseVisualRegionsOutput {+ let output = ParseVisualRegionsOutput {+ schema: VISUAL_REGIONS_SCHEMA.into(),+ capture: capture(),+ parser: parser(),+ regions: vec![region("region-1")],+ warnings: vec![VisualParseWarning {+ code: "low_contrast".into(),+ message: "contrast was low".into(),+ detail: None,+ }],+ timing: VisualParseTiming {+ duration_ms: 12,+ preprocess_ms: Some(2),+ inference_ms: Some(8),+ },+ request_id: Some("parse-1".into()),+ };+ output.validate().unwrap();+ output+ }++ #[test]+ fn v1_refers_to_a_registry_capture_without_bytes_or_file_paths() {+ let input = ParseVisualRegionsInput {+ capture_id: "capture-1".into(),+ options: ParseVisualRegionsOptions::default(),+ };+ input.validate().unwrap();+ let value = serde_json::to_value(input).unwrap();+ assert_eq!(value["capture_id"], "capture-1");+ assert!(!value.to_string().contains("data_base64"));+ assert!(!value.to_string().contains("file_path"));+ }++ #[test]+ fn capture_sources_are_exact_window_or_primary_desktop() {+ assert_eq!(+ serde_json::to_value(VisualCaptureSource::Window {+ pid: 7,+ window_id: 9+ })+ .unwrap(),+ json!({"kind":"window","pid":7,"window_id":9})+ );+ assert_eq!(+ serde_json::to_value(VisualCaptureSource::PrimaryDesktop {+ display_id: "primary".into()+ })+ .unwrap(),+ json!({"kind":"primary_desktop","display_id":"primary"})+ );+ let schema = serde_json::to_string(&schemars::schema_for!(VisualCaptureSource)).unwrap();+ assert!(schema.contains("\"const\":\"primary\""));+ }++ #[test]+ fn region_center_is_geometric_then_mapped_by_the_normative_equation() {+ let region = region("region-1");+ assert_eq!(region.bounds.center(), (61.5, 30.5));+ assert_eq!(+ region.action_center(&capture().action_coordinate_space),+ (138.375, 230.25)+ );+ assert!(serde_json::to_value(region)+ .unwrap()+ .get("center")+ .is_none());+ }++ #[test]+ fn parse_options_schema_and_validation_require_unique_kinds() {+ let mut input = ParseVisualRegionsInput {+ capture_id: "capture-1".into(),+ options: ParseVisualRegionsOptions {+ kinds: Some(vec![VisualRegionKind::Text, VisualRegionKind::Icon]),+ min_confidence: Some(0.5),+ max_regions: Some(100),+ },+ };+ input.validate().unwrap();+ input.options.kinds = Some(vec![VisualRegionKind::Text, VisualRegionKind::Text]);+ assert_eq!(+ input.validate(),+ Err(VisualContractValidationError::InvalidRegionKinds)+ );++ let schema =+ serde_json::to_string(&schemars::schema_for!(ParseVisualRegionsInput)).unwrap();+ assert!(schema.contains("\"uniqueItems\":true"));+ }++ #[test]+ fn result_validates_metadata_content_and_region_references() {+ let mut result = output();+ result.regions.push(VisualRegion {+ id: "group-1".into(),+ kind: VisualRegionKind::Icon,+ bounds: VisualRegionBounds {+ x: 5,+ y: 5,+ width: 10,+ height: 10,+ },+ text: None,+ label: Some("toolbar".into()),+ confidence: 0.8,+ interactive: false,+ parent_id: None,+ group_id: None,+ reading_order: None,+ });+ result.regions[0].parent_id = Some("group-1".into());+ result.regions[0].group_id = Some("group-1".into());+ result.validate().unwrap();++ result.regions[0].parent_id = Some("missing".into());+ assert_eq!(+ result.validate(),+ Err(VisualContractValidationError::MissingRegionReference)+ );+ result.regions[0].parent_id = None;+ result.parser.model_id.clear();+ assert_eq!(+ result.validate(),+ Err(VisualContractValidationError::InvalidParserMetadata)+ );+ result.parser.model_id = "default".into();+ result.parser.model_manifest_sha256 = Some("not-a-sha256".into());+ assert_eq!(+ result.validate(),+ Err(VisualContractValidationError::InvalidParserMetadata)+ );+ }++ #[test]+ fn output_schema_is_versioned_integer_pixel_data_without_dynamic_extensions() {+ let schema = serde_json::to_value(schemars::schema_for!(ParseVisualRegionsOutput)).unwrap();+ assert_eq!(+ schema["properties"]["schema"]["const"],+ VISUAL_REGIONS_SCHEMA+ );+ let schema_text = serde_json::to_string(&schema).unwrap();+ assert!(schema_text.contains("\"type\":\"integer\""));+ assert!(!schema_text.contains("data_base64"));+ assert!(!schema_text.contains("file_path"));+ assert!(!schema_text.contains("extensions"));+ output().validate().unwrap();+ }++ #[test]+ fn errors_cover_capture_worker_artifact_and_inference_failures() {+ let codes = [+ (VisualParseErrorCode::NotInstalled, "not_installed"),+ (VisualParseErrorCode::CaptureNotFound, "capture_not_found"),+ (VisualParseErrorCode::CaptureExpired, "capture_expired"),+ (VisualParseErrorCode::CaptureStale, "capture_stale"),+ (+ VisualParseErrorCode::CaptureGenerationMismatch,+ "capture_generation_mismatch",+ ),+ (+ VisualParseErrorCode::UnsupportedTarget,+ "unsupported_target",+ ),+ (+ VisualParseErrorCode::UnsupportedPlatform,+ "unsupported_platform",+ ),+ (+ VisualParseErrorCode::IncompatibleProtocol,+ "incompatible_protocol",+ ),+ (VisualParseErrorCode::InvalidFrame, "invalid_frame"),+ (+ VisualParseErrorCode::WorkerLaunchFailed,+ "worker_launch_failed",+ ),+ (VisualParseErrorCode::WorkerCrashed, "worker_crashed"),+ (VisualParseErrorCode::WorkerCancelled, "worker_cancelled"),+ (VisualParseErrorCode::Timeout, "timeout"),+ (+ VisualParseErrorCode::ResourceLimitExceeded,+ "resource_limit_exceeded",+ ),+ (VisualParseErrorCode::ArtifactInvalid, "artifact_invalid"),+ (VisualParseErrorCode::InferenceFailed, "inference_failed"),+ ];+ for (code, expected) in codes {+ assert_eq!(serde_json::to_value(code).unwrap(), expected);+ }+ VisualParseError {+ code: VisualParseErrorCode::CaptureNotFound,+ message: "capture is no longer registered".into(),+ retryable: true,+ detail: None,+ }+ .validate()+ .unwrap();+ }++ #[test]+ fn production_type_names_remain_model_neutral() {+ let schemas = [+ serde_json::to_string(&schemars::schema_for!(ParseVisualRegionsInput)).unwrap(),+ serde_json::to_string(&schemars::schema_for!(ParseVisualRegionsOutput)).unwrap(),+ serde_json::to_string(&schemars::schema_for!(VisualParseError)).unwrap(),+ ]+ .join(" ")+ .to_lowercase();+ for forbidden in ["jev", "typesafe", "omniparser", "prompt", "provider"] {+ assert!(!schemas.contains(forbidden));+ }+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver-contract/src/windows.rs b/libs/cua-driver/rust/crates/cua-driver-contract/src/windows.rsindex 49dea44b0f..70394d03dd 100644--- a/libs/cua-driver/rust/crates/cua-driver-contract/src/windows.rs+++ b/libs/cua-driver/rust/crates/cua-driver-contract/src/windows.rs@@ -19,6 +19,9 @@ fn pid_schema(_: &mut SchemaGenerator) -> Schema {fn positive_integer_schema(_: &mut SchemaGenerator) -> Schema {json_schema!({"type":"integer", "minimum":1})}+fn nonnegative_integer_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({"type":"integer", "minimum":0})+}fn nullable_pid_schema(_: &mut SchemaGenerator) -> Schema {json_schema!({"type":["integer","null"], "minimum":0, "maximum":4294967295_u64})@@ -89,6 +92,11 @@ pub struct GetWindowStateInput {#[serde(default, skip_serializing_if = "Option::is_none")]#[schemars(schema_with = "positive_integer_schema")]pub max_dimension: Option<u32>,+ /// Optional per-call long-edge ceiling. Zero requests native resolution;+ /// omit it to preserve the configured session or global behavior.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(schema_with = "nonnegative_integer_schema")]+ pub max_image_dimension: Option<u32>,}impl ToolInput for GetWindowStateInput {@@ -398,6 +406,21 @@ mod tests {GetWindowStateInput::input_schema()["properties"]["max_elements"]["minimum"],1);+ assert_eq!(+ GetWindowStateInput::input_schema()["properties"]["max_image_dimension"]["minimum"],+ 0+ );+ assert_eq!(+ GetWindowStateInput::input_schema()["properties"]["max_dimension"]["minimum"],+ 1+ );+ let native_resolution: GetWindowStateInput = serde_json::from_value(json!({+ "pid": 7,+ "window_id": 9,+ "max_image_dimension": 0+ }))+ .unwrap();+ native_resolution.validate().unwrap();assert_eq!(ListAppsInput::input_schema()["properties"], json!({}));}diff --git a/libs/cua-driver/rust/crates/cua-driver-contract/tests/fixtures/parse-visual-regions-output-full-v1.json b/libs/cua-driver/rust/crates/cua-driver-contract/tests/fixtures/parse-visual-regions-output-full-v1.jsonnew file mode 100644index 0000000000..ab65558d3e--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-contract/tests/fixtures/parse-visual-regions-output-full-v1.json@@ -0,0 +1,83 @@+{+ "schema": "cua.visual_regions_v1",+ "capture": {+ "capture_id": "capture-full",+ "source": {+ "kind": "primary_desktop",+ "display_id": "primary"+ },+ "screenshot": {+ "reference": "png-sha256:0123456789abcdef",+ "width": 1920,+ "height": 1080,+ "mime_type": "image/png",+ "sha256": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"+ },+ "action_coordinate_space": {+ "kind": "affine",+ "m11": 1.0,+ "m12": 0.25,+ "m21": -0.5,+ "m22": 1.0,+ "tx": -1920.0,+ "ty": 10.0+ },+ "captured_at": "2026-09-17T12:00:00Z"+ },+ "parser": {+ "extension_id": "cua-perception",+ "extension_version": "1.0.0",+ "model_id": "visual-regions-default",+ "model_version": "1",+ "runtime": "onnx_runtime_cpu",+ "backend": "onnx_runtime_cpu",+ "model_source_revision": "6600256cb0f1b07651e3bc86166196307bad7e2d",+ "model_manifest_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",+ "onnx_runtime_version": "1.26.0",+ "onnx_runtime_library_sha256": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"+ },+ "regions": [+ {+ "id": "group-1",+ "kind": "icon",+ "bounds": {+ "x": 10,+ "y": 20,+ "width": 101,+ "height": 21+ },+ "label": "toolbar",+ "confidence": 0.8,+ "interactive": false+ },+ {+ "id": "text-1",+ "kind": "text",+ "bounds": {+ "x": 30,+ "y": 25,+ "width": 40,+ "height": 10+ },+ "text": "Apply",+ "confidence": 0.95,+ "interactive": true,+ "parent_id": "group-1",+ "group_id": "group-1",+ "reading_order": 1+ }+ ],+ "warnings": [+ {+ "code": "low_contrast",+ "message": "One region had low contrast",+ "detail": "text-1"+ }+ ],+ "timing": {+ "duration_ms": 18,+ "preprocess_ms": 3,+ "inference_ms": 12+ },+ "request_id": "parse-request-1"+}diff --git a/libs/cua-driver/rust/crates/cua-driver-contract/tests/fixtures/parse-visual-regions-request-full-v1.json b/libs/cua-driver/rust/crates/cua-driver-contract/tests/fixtures/parse-visual-regions-request-full-v1.jsonnew file mode 100644index 0000000000..e6dce3545a--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-contract/tests/fixtures/parse-visual-regions-request-full-v1.json@@ -0,0 +1,11 @@+{+ "capture_id": "capture-full",+ "options": {+ "kinds": [+ "text",+ "icon"+ ],+ "min_confidence": 0.25,+ "max_regions": 200+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver-contract/tests/fixtures/parse-visual-regions-request-minimal-v1.json b/libs/cua-driver/rust/crates/cua-driver-contract/tests/fixtures/parse-visual-regions-request-minimal-v1.jsonnew file mode 100644index 0000000000..231fe66b77--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-contract/tests/fixtures/parse-visual-regions-request-minimal-v1.json@@ -0,0 +1,4 @@+{+ "capture_id": "capture-minimal",+ "options": {}+}diff --git a/libs/cua-driver/rust/crates/cua-driver-contract/tests/fixtures/visual-parse-errors-v1.json b/libs/cua-driver/rust/crates/cua-driver-contract/tests/fixtures/visual-parse-errors-v1.jsonnew file mode 100644index 0000000000..653dfffe80--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-contract/tests/fixtures/visual-parse-errors-v1.json@@ -0,0 +1,18 @@+[+ { "code": "not_installed", "message": "extension is not installed", "retryable": false },+ { "code": "capture_not_found", "message": "capture was not found", "retryable": true },+ { "code": "capture_expired", "message": "capture expired", "retryable": true },+ { "code": "capture_stale", "message": "capture is stale", "retryable": true },+ { "code": "capture_generation_mismatch", "message": "capture generation changed", "retryable": true },+ { "code": "unsupported_target", "message": "target is unsupported", "retryable": false },+ { "code": "unsupported_platform", "message": "platform is unsupported", "retryable": false },+ { "code": "incompatible_protocol", "message": "worker protocol is incompatible", "retryable": false },+ { "code": "invalid_frame", "message": "capture frame is invalid", "retryable": false, "detail": "dimension mismatch" },+ { "code": "worker_launch_failed", "message": "worker failed to launch", "retryable": true },+ { "code": "worker_crashed", "message": "worker crashed", "retryable": true },+ { "code": "worker_cancelled", "message": "worker request was cancelled", "retryable": true },+ { "code": "timeout", "message": "parse timed out", "retryable": true },+ { "code": "resource_limit_exceeded", "message": "resource limit was exceeded", "retryable": false },+ { "code": "artifact_invalid", "message": "installed artifact is invalid", "retryable": false },+ { "code": "inference_failed", "message": "inference failed", "retryable": true }+]diff --git a/libs/cua-driver/rust/crates/cua-driver-contract/tests/visual_contract.rs b/libs/cua-driver/rust/crates/cua-driver-contract/tests/visual_contract.rsnew file mode 100644index 0000000000..0a4e286cab--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-contract/tests/visual_contract.rs@@ -0,0 +1,100 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 Cua AI, Inc.++use cua_driver_contract::{+ manifest, ParseVisualRegionsInput, ParseVisualRegionsOutput, VisualParseError,+ VisualParseErrorCode,+};+use serde::{de::DeserializeOwned, Serialize};+use serde_json::Value;+use std::collections::BTreeSet;++fn round_trip_valid<T>(fixture: &str, validate: impl FnOnce(&T))+where+ T: DeserializeOwned + Serialize,+{+ let expected: Value = serde_json::from_str(fixture).expect("fixture is JSON");+ let value: T = serde_json::from_value(expected.clone()).expect("fixture matches the DTO");+ validate(&value);+ assert_eq!(serde_json::to_value(value).unwrap(), expected);+}++#[test]+fn versioned_request_fixtures_cover_minimal_and_full_options() {+ for fixture in [+ include_str!("fixtures/parse-visual-regions-request-minimal-v1.json"),+ include_str!("fixtures/parse-visual-regions-request-full-v1.json"),+ ] {+ round_trip_valid::<ParseVisualRegionsInput>(fixture, |input| input.validate().unwrap());+ }+}++#[test]+fn versioned_output_fixture_covers_provenance_regions_warnings_and_optionals() {+ round_trip_valid::<ParseVisualRegionsOutput>(+ include_str!("fixtures/parse-visual-regions-output-full-v1.json"),+ |output| {+ output.validate().unwrap();+ let (pixel_x, pixel_y) = output.regions[0].bounds.center();+ assert_eq!((pixel_x, pixel_y), (60.5, 30.5));+ assert_eq!(+ output.regions[0].action_center(&output.capture.action_coordinate_space),+ (-1851.875, 10.25)+ );+ },+ );+}++#[test]+fn versioned_error_fixture_exhausts_the_stable_v1_codes() {+ let fixture = include_str!("fixtures/visual-parse-errors-v1.json");+ let expected: Value = serde_json::from_str(fixture).unwrap();+ let errors: Vec<VisualParseError> = serde_json::from_value(expected.clone()).unwrap();+ for error in &errors {+ error.validate().unwrap();+ }+ assert_eq!(serde_json::to_value(&errors).unwrap(), expected);++ let actual: BTreeSet<_> = errors.iter().map(|error| error.code).collect();+ let all = BTreeSet::from([+ VisualParseErrorCode::NotInstalled,+ VisualParseErrorCode::CaptureNotFound,+ VisualParseErrorCode::CaptureExpired,+ VisualParseErrorCode::CaptureStale,+ VisualParseErrorCode::CaptureGenerationMismatch,+ VisualParseErrorCode::UnsupportedTarget,+ VisualParseErrorCode::UnsupportedPlatform,+ VisualParseErrorCode::IncompatibleProtocol,+ VisualParseErrorCode::InvalidFrame,+ VisualParseErrorCode::WorkerLaunchFailed,+ VisualParseErrorCode::WorkerCrashed,+ VisualParseErrorCode::WorkerCancelled,+ VisualParseErrorCode::Timeout,+ VisualParseErrorCode::ResourceLimitExceeded,+ VisualParseErrorCode::ArtifactInvalid,+ VisualParseErrorCode::InferenceFailed,+ ]);+ assert_eq!(actual, all);+}++#[test]+fn visual_tool_contract_publishes_stable_request_output_and_error_schemas() {+ let contract = manifest()+ .tools+ .into_iter()+ .find(|tool| tool.name == "parse_visual_regions")+ .expect("visual parser tool contract");+ assert_eq!(+ contract.input_schema["required"],+ serde_json::json!(["capture_id"])+ );+ assert_eq!(+ contract.success_output_schema.as_ref().unwrap()["properties"]["schema"]["const"],+ "cua.visual_regions_v1"+ );+ let error_schema = contract.error_output_schema.expect("visual error schema");+ assert_eq!(error_schema["additionalProperties"], false);+ assert!(error_schema["properties"]["code"]["enum"]+ .as_array()+ .is_some_and(|codes| codes.len() == 16));+}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/Cargo.toml b/libs/cua-driver/rust/crates/cua-driver-core/Cargo.tomlindex 5e6a53e3dd..32827d6448 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/Cargo.toml+++ b/libs/cua-driver/rust/crates/cua-driver-core/Cargo.toml@@ -50,15 +50,22 @@ fs2 = { workspace = true }hmac = { workspace = true }# Validate the raw wire payload; serde permits some shapes the schema rejects.jsonschema = { version = "0.46", default-features = false }+# Private per-request working directory for the optional perception worker.+tempfile = "3"[target.'cfg(unix)'.dependencies]libc = "0.2"# Used by `cursor_sampler::sample_cursor` to poll the OS mouse position-# during video recording. Same version as platform-windows uses to avoid-# a duplicate crate version.-[dev-dependencies]-tempfile = "3"-+# during video recording, and by `perception_client::containment` for the+# worker's Job Object. Same version as platform-windows uses to avoid a+# duplicate crate version.[target.'cfg(windows)'.dependencies]-windows = { version = "0.58", features = ["Win32_Foundation", "Win32_UI_WindowsAndMessaging"] }+windows = { version = "0.58", features = [+ "Win32_Foundation",+ "Win32_Security",+ "Win32_System_Diagnostics_ToolHelp",+ "Win32_System_JobObjects",+ "Win32_System_Threading",+ "Win32_UI_WindowsAndMessaging",+] }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.rsindex 18004509d9..e08a7a2a81 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@@ -1853,6 +1853,22 @@ mod tests {}}+ #[test]+ fn foreground_macos_drag_path_uses_hid_transport() {+ let record = ActionExecutionRecord::from_legacy(+ "drag",+ &serde_json::json!({"delivery_mode": "foreground"}),+ &serde_json::json!({+ "path": "cgevent_hid",+ "effect": "unverifiable",+ }),+ )+ .expect("foreground macOS drag should normalize");++ assert_eq!(record.transport, ActionTransport::MacosCgEventHid);+ assert_eq!(record.actual_delivery, Some(ActualDelivery::Foreground));+ }+#[test]fn every_legacy_text_only_action_is_conservatively_unverifiable() {let tools = [diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/action_target.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/action_target.rsindex 24c80c3785..794ee7d8ca 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/action_target.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/action_target.rs@@ -102,6 +102,28 @@ pub fn normalize_action_target(tool_name: &str, args: &mut Value) -> Result<(),Ok(())}+/// Reject the delivery combination that cannot preserve background posture.+/// Call this only after delivery aliases and typed targets have been normalized.+pub fn enforce_delivery_target(tool_name: &str, args: &Value) -> Result<(), ToolResult> {+ if tool_name != "click"+ || args.get("scope").and_then(Value::as_str) != Some("desktop")+ || args.get("delivery_mode").and_then(Value::as_str) != Some("background")+ {+ return Ok(());+ }++ let message = cua_driver_contract::ClickInput::DESKTOP_BACKGROUND_MESSAGE;+ Err(ToolResult::error(message).with_structured(json!({+ "code": "background_unavailable",+ "effect": "refused",+ "suggestion": "Retry this action with delivery_mode:\"foreground\".",+ "escalation": {+ "recommended": "foreground",+ "reason": message,+ },+ })))+}+#[cfg(test)]mod tests {use super::*;@@ -143,4 +165,43 @@ mod tests {assert!(normalize_action_target("click", &mut args).is_err());}}++ #[test]+ fn desktop_background_guard_is_click_specific() {+ let desktop_background = json!({+ "scope": "desktop",+ "delivery_mode": "background"+ });+ let refusal = enforce_delivery_target("click", &desktop_background).unwrap_err();+ assert_eq!(refusal.is_error, Some(true));+ assert_eq!(+ refusal.structured_content,+ Some(json!({+ "code": "background_unavailable",+ "effect": "refused",+ "suggestion": "Retry this action with delivery_mode:\"foreground\".",+ "escalation": {+ "recommended": "foreground",+ "reason": cua_driver_contract::ClickInput::DESKTOP_BACKGROUND_MESSAGE,+ },+ }))+ );++ for (tool, args) in [+ (+ "click",+ json!({"scope": "desktop", "delivery_mode": "foreground"}),+ ),+ (+ "click",+ json!({"scope": "window", "delivery_mode": "background"}),+ ),+ ("drag", desktop_background),+ ] {+ assert!(+ enforce_delivery_target(tool, &args).is_ok(),+ "{tool}: {args}"+ );+ }+ }}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rsindex 2625ee2ffa..b0902a0605 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/authorization.rs@@ -231,6 +231,7 @@ const PRIVATE_OBSERVATION_OPERATIONS: &[&str] = &["get_desktop_state","get_accessibility_tree","get_window_state",+ "parse_visual_regions","verify_state","list_apps","list_windows",@@ -307,6 +308,7 @@ const FILE_TRANSFER_OPERATIONS: &[&str] = &["stop_recording","replay_trajectory","install_ffmpeg",+ "install_extension",];const FILE_TRANSFER_SCOPE_KEYS: &[&str] = &["daemon_generation",@@ -784,7 +786,8 @@ pub fn enforcement_adapters_for_call(|| (tool == "clipboard_write"&& (args.get("image_path").and_then(Value::as_str).is_some()|| args.get("file_path").and_then(Value::as_str).is_some()))- || (tool == "install_ffmpeg" && args.get("confirm").and_then(Value::as_bool) == Some(true))+ || (matches!(tool, "install_ffmpeg" | "install_extension")+ && args.get("confirm").and_then(Value::as_bool) == Some(true)){add("file_transfer_and_output");}@@ -922,7 +925,8 @@ pub fn advertised_risk_for(tool: &str) -> RiskAssessment {| "browser_type"| "browser_pointer"| "history_status"- | "history_query" => RiskClass::R2,+ | "history_query"+ | "parse_visual_regions" => RiskClass::R2,// External/file side effects or generic compound action surfaces."get_desktop_state"@@ -931,6 +935,7 @@ pub fn advertised_risk_for(tool: &str) -> RiskAssessment {| "stop_recording"| "replay_trajectory"| "install_ffmpeg"+ | "install_extension"| "page"| "browser_dialog"| "browser_set_input_files"@@ -1066,7 +1071,7 @@ pub fn classify_tool_call(tool: &str, args: &Value) -> RiskAssessment {enforcement: RiskEnforcement::Active,operation_sensitive: true,},- "install_ffmpeg" => {+ "install_ffmpeg" | "install_extension" => {let confirmed = args.get("confirm").and_then(Value::as_bool) == Some(true);RiskAssessment {class: if confirmed {@@ -1913,6 +1918,17 @@ mod tests {ids("install_ffmpeg", serde_json::json!({"confirm": true})),vec!["file_transfer_and_output"]);+ assert_eq!(+ ids("install_extension", serde_json::json!({})),+ Vec::<&str>::new()+ );+ assert_eq!(+ ids(+ "install_extension",+ serde_json::json!({"name": "perception", "confirm": true})+ ),+ vec!["file_transfer_and_output"]+ );assert_eq!(ids("get_browser_state", serde_json::json!({})),vec!["private_observation"]diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/capture_registry.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/capture_registry.rsnew file mode 100644index 0000000000..874392aec9--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/capture_registry.rs@@ -0,0 +1,1875 @@+//! Bounded, immutable screenshot storage for later coordinate-bound actions.+//!+//! This registry deliberately does not store accessibility elements or mirror+//! the element cache. A later integration with the snapshot-owned transforms+//! from #3630 should keep the snapshot as the authority for element tokens and+//! screenshot freshness. At capture publication, compose the snapshot's+//! delivered-image-to-native transform with any native-to-action transform and+//! store that single screenshot-to-action transform here. Retire the capture+//! when the owning snapshot, session, or runtime generation is retired.+//!+//! The registry grants no screenshot or action permission. Callers must pass+//! already-authorized PNG bytes and must independently authorize every action.+//! In particular, this foundation is not wired into platform adapters, action+//! dispatch, session hooks, or permission checks. That P1 integration remains+//! required before a capture ID can authorize or drive any production action.+//! Target-specific bounds and coordinate semantics must be revalidated there.+//!+//! TTL cleanup is bounded and lazy: [`CaptureRegistry::prune_expired`] scans at+//! most `max_captures` entries and drops expired PNG references. Registry size+//! metrics call it automatically. An eventual runtime owner must call it from+//! its maintenance/metrics path if no store or lookup traffic is occurring.++use image::{ImageDecoder, Limits};+use sha2::{Digest, Sha256};+use std::collections::{HashMap, HashSet, VecDeque};+use std::fmt;+use std::io::Cursor;+use std::str::FromStr;+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};+use thiserror::Error;+use uuid::Uuid;++pub(crate) const DEFAULT_MAX_CAPTURE_BYTES: usize = 64 * 1024 * 1024;++#[derive(Clone, Copy, Eq, Hash, PartialEq)]+pub struct CaptureId {+ namespace: [u8; 16],+ sequence: u64,+}++impl fmt::Debug for CaptureId {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ formatter.write_str("CaptureId(")?;+ fmt::Display::fmt(self, formatter)?;+ formatter.write_str(")")+ }+}++impl fmt::Display for CaptureId {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ formatter.write_str("capture_")?;+ for byte in self.namespace {+ write!(formatter, "{byte:02x}")?;+ }+ write!(formatter, "_{:016x}", self.sequence)+ }+}++#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]+pub enum CaptureIdParseError {+ #[error("capture id has an invalid format")]+ InvalidFormat,+}++impl FromStr for CaptureId {+ type Err = CaptureIdParseError;++ fn from_str(value: &str) -> Result<Self, Self::Err> {+ let value = value+ .strip_prefix("capture_")+ .ok_or(CaptureIdParseError::InvalidFormat)?;+ let (namespace, sequence) = value+ .split_once('_')+ .ok_or(CaptureIdParseError::InvalidFormat)?;+ if namespace.len() != 32 || sequence.len() != 16 {+ return Err(CaptureIdParseError::InvalidFormat);+ }+ let mut namespace_bytes = [0_u8; 16];+ for (index, byte) in namespace_bytes.iter_mut().enumerate() {+ *byte = u8::from_str_radix(&namespace[index * 2..index * 2 + 2], 16)+ .map_err(|_| CaptureIdParseError::InvalidFormat)?;+ }+ let sequence =+ u64::from_str_radix(sequence, 16).map_err(|_| CaptureIdParseError::InvalidFormat)?;+ Ok(Self {+ namespace: namespace_bytes,+ sequence,+ })+ }+}++#[derive(Clone, Copy, Eq, PartialEq)]+pub struct ContentDigest([u8; 32]);++impl ContentDigest {+ pub fn as_bytes(&self) -> &[u8; 32] {+ &self.0+ }++ pub fn hex(&self) -> String {+ self.0.iter().map(|byte| format!("{byte:02x}")).collect()+ }+}++impl fmt::Debug for ContentDigest {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ formatter.write_str("sha256:")?;+ for byte in self.0 {+ write!(formatter, "{byte:02x}")?;+ }+ Ok(())+ }+}++#[derive(Clone, Debug, Eq, Hash, PartialEq)]+pub enum CaptureTarget {+ Window { pid: u32, window_id: u64 },+ PrimaryDesktop,+}++impl CaptureTarget {+ fn validate(&self) -> Result<(), CaptureStoreError> {+ match self {+ Self::Window { pid, window_id } if *pid == 0 || *window_id == 0 => {+ Err(CaptureStoreError::InvalidTarget)+ }+ Self::Window { .. } | Self::PrimaryDesktop => Ok(()),+ }+ }+}++#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub struct EncodedScreenshotDimensions {+ width: u32,+ height: u32,+}++impl EncodedScreenshotDimensions {+ pub fn new(width: u32, height: u32) -> Result<Self, CaptureStoreError> {+ if width == 0 || height == 0 {+ return Err(CaptureStoreError::InvalidEncodedDimensions);+ }+ Ok(Self { width, height })+ }++ pub fn width(self) -> u32 {+ self.width+ }++ pub fn height(self) -> u32 {+ self.height+ }+}++/// Dimensions of the full-resolution native frame used by action coordinates.+///+/// These may differ from [`EncodedScreenshotDimensions`] when a screenshot is+/// downscaled. They are metadata for later integration; this inert registry+/// does not claim that the action frame matches the target's current bounds.+#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub struct NativeActionDimensions {+ width: u32,+ height: u32,+}++impl NativeActionDimensions {+ pub fn new(width: u32, height: u32) -> Result<Self, CaptureStoreError> {+ if width == 0 || height == 0 {+ return Err(CaptureStoreError::InvalidNativeActionDimensions);+ }+ Ok(Self { width, height })+ }++ pub fn width(self) -> u32 {+ self.width+ }++ pub fn height(self) -> u32 {+ self.height+ }+}++/// Continuous affine mapping from screenshot pixels to action coordinates.+///+/// For a screenshot point `(x, y)`, the action point is:+/// `((m11*x) + (m12*y) + tx, (m21*x) + (m22*y) + ty)`.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct ScreenshotToActionTransform {+ m11: f64,+ m12: f64,+ m21: f64,+ m22: f64,+ tx: f64,+ ty: f64,+}++impl ScreenshotToActionTransform {+ pub fn new(+ m11: f64,+ m12: f64,+ m21: f64,+ m22: f64,+ tx: f64,+ ty: f64,+ ) -> Result<Self, CaptureStoreError> {+ let values = [m11, m12, m21, m22, tx, ty];+ let determinant = m11.mul_add(m22, -(m12 * m21));+ if values.iter().any(|value| !value.is_finite())+ || !determinant.is_finite()+ || determinant.abs() <= f64::EPSILON+ {+ return Err(CaptureStoreError::InvalidTransform);+ }+ Ok(Self {+ m11,+ m12,+ m21,+ m22,+ tx,+ ty,+ })+ }++ pub fn identity() -> Self {+ Self {+ m11: 1.0,+ m12: 0.0,+ m21: 0.0,+ m22: 1.0,+ tx: 0.0,+ ty: 0.0,+ }+ }++ pub fn apply(self, x: f64, y: f64) -> (f64, f64) {+ (+ self.m11.mul_add(x, self.m12.mul_add(y, self.tx)),+ self.m21.mul_add(x, self.m22.mul_add(y, self.ty)),+ )+ }++ pub fn coefficients(self) -> [f64; 6] {+ [self.m11, self.m12, self.m21, self.m22, self.tx, self.ty]+ }++ fn validate_extent(+ self,+ dimensions: EncodedScreenshotDimensions,+ ) -> Result<(), CaptureStoreError> {+ let max_x = f64::from(dimensions.width.saturating_sub(1));+ let max_y = f64::from(dimensions.height.saturating_sub(1));+ for (x, y) in [(0.0, 0.0), (max_x, 0.0), (0.0, max_y), (max_x, max_y)] {+ let (action_x, action_y) = self.apply(x, y);+ if !action_x.is_finite() || !action_y.is_finite() {+ return Err(CaptureStoreError::InvalidTransformExtent);+ }+ }+ Ok(())+ }++ /// Compose two mappings, applying `self` first and `next` second.+ pub fn then(self, next: Self) -> Result<Self, CaptureStoreError> {+ Self::new(+ next.m11.mul_add(self.m11, next.m12 * self.m21),+ next.m11.mul_add(self.m12, next.m12 * self.m22),+ next.m21.mul_add(self.m11, next.m22 * self.m21),+ next.m21.mul_add(self.m12, next.m22 * self.m22),+ next.m11+ .mul_add(self.tx, next.m12.mul_add(self.ty, next.tx)),+ next.m21+ .mul_add(self.tx, next.m22.mul_add(self.ty, next.ty)),+ )+ }+}++#[derive(Clone, Eq, Hash, PartialEq)]+pub struct CaptureBinding {+ runtime_generation: u64,+ session_id: Arc<str>,+ session_generation: u64,+}++impl fmt::Debug for CaptureBinding {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ formatter+ .debug_struct("CaptureBinding")+ .field("runtime_generation", &self.runtime_generation)+ .field("session_id", &"[redacted]")+ .field("session_generation", &self.session_generation)+ .finish()+ }+}++impl CaptureBinding {+ pub fn new(+ runtime_generation: u64,+ session_id: impl Into<Arc<str>>,+ session_generation: u64,+ ) -> Result<Self, CaptureStoreError> {+ let session_id = session_id.into();+ if runtime_generation == 0 || session_generation == 0 || session_id.trim().is_empty() {+ return Err(CaptureStoreError::InvalidBinding);+ }+ Ok(Self {+ runtime_generation,+ session_id,+ session_generation,+ })+ }++ pub fn runtime_generation(&self) -> u64 {+ self.runtime_generation+ }++ pub fn session_id(&self) -> &str {+ &self.session_id+ }++ pub fn session_generation(&self) -> u64 {+ self.session_generation+ }+}++pub trait MonotonicClock: Send + Sync + 'static {+ fn now(&self) -> Duration;+}++#[derive(Debug)]+pub struct SystemMonotonicClock {+ origin: Instant,+}++impl SystemMonotonicClock {+ pub fn new() -> Self {+ Self {+ origin: Instant::now(),+ }+ }+}++impl Default for SystemMonotonicClock {+ fn default() -> Self {+ Self::new()+ }+}++impl MonotonicClock for SystemMonotonicClock {+ fn now(&self) -> Duration {+ self.origin.elapsed()+ }+}++#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub struct CaptureRegistryConfig {+ pub max_captures: usize,+ pub max_total_bytes: usize,+ pub max_encoded_width: u32,+ pub max_encoded_height: u32,+ pub max_decoded_bytes: u64,+ pub ttl: Duration,+}++impl CaptureRegistryConfig {+ fn validate(self) -> Result<Self, CaptureStoreError> {+ if self.max_captures == 0+ || self.max_total_bytes == 0+ || self.max_encoded_width == 0+ || self.max_encoded_height == 0+ || self.max_decoded_bytes == 0+ || self.ttl.is_zero()+ {+ return Err(CaptureStoreError::InvalidConfig);+ }+ Ok(self)+ }+}++impl Default for CaptureRegistryConfig {+ fn default() -> Self {+ Self {+ max_captures: 32,+ max_total_bytes: DEFAULT_MAX_CAPTURE_BYTES,+ max_encoded_width: 16_384,+ max_encoded_height: 16_384,+ max_decoded_bytes: 512 * 1024 * 1024,+ ttl: Duration::from_secs(60),+ }+ }+}++#[derive(Debug, Error, Eq, PartialEq)]+pub enum CaptureStoreError {+ #[error("capture registry limits and ttl must be non-zero")]+ InvalidConfig,+ #[error("capture binding is invalid")]+ InvalidBinding,+ #[error("capture target is invalid")]+ InvalidTarget,+ #[error("encoded screenshot dimensions are invalid or do not match the PNG")]+ InvalidEncodedDimensions,+ #[error("native action dimensions are invalid")]+ InvalidNativeActionDimensions,+ #[error("screenshot-to-action transform is invalid")]+ InvalidTransform,+ #[error("screenshot-to-action transform is not finite across the encoded image extent")]+ InvalidTransformExtent,+ #[error("capture bytes are not a valid PNG")]+ InvalidPng,+ #[error("PNG dimensions or decoded allocation exceed registry limits")]+ PngDecodeLimitExceeded,+ #[error("capture exceeds the registry byte limit")]+ CaptureTooLarge,+ #[error("capture id space is exhausted")]+ IdExhausted,+ #[error("capture expiry cannot be represented")]+ ExpiryOverflow,+}++#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]+pub enum CaptureLookupError {+ #[error("capture id is unknown")]+ Unknown,+ #[error("capture has expired")]+ Expired,+ #[error("capture belongs to another runtime or session generation")]+ GenerationMismatch,+ #[error("capture belongs to another target")]+ TargetMismatch,+}++#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]+pub struct PruneOutcome {+ pub captures_removed: usize,+ pub encoded_bytes_released: usize,+}++pub struct CaptureRegistration {+ pub png_bytes: Vec<u8>,+ pub target: CaptureTarget,+ pub encoded_dimensions: EncodedScreenshotDimensions,+ pub native_action_dimensions: NativeActionDimensions,+ pub screenshot_to_action: ScreenshotToActionTransform,+ pub binding: CaptureBinding,+}++pub struct CapturePublication {+ pub png_bytes: Vec<u8>,+ pub target: CaptureTarget,+ pub encoded_dimensions: EncodedScreenshotDimensions,+ pub native_action_dimensions: NativeActionDimensions,+ pub screenshot_to_action: ScreenshotToActionTransform,+ pub session_id: Arc<str>,+ pub session_generation: u64,+}++pub struct CaptureActionRequest {+ pub capture_id: CaptureId,+ pub binding: CaptureBinding,+ /// Target identity observed immediately before native dispatch.+ pub target: CaptureTarget,+ /// Native action frame observed immediately before native dispatch.+ pub current_native_action_dimensions: NativeActionDimensions,+ pub screenshot_x: f64,+ pub screenshot_y: f64,+}++#[derive(Debug)]+pub struct CaptureActionAdmission {+ pub capture_id: CaptureId,+ pub target: CaptureTarget,+ pub action_x: f64,+ pub action_y: f64,+ pub native_action_dimensions: NativeActionDimensions,+ pub digest: ContentDigest,+}++#[derive(Clone, Copy, Debug, Error, PartialEq)]+pub enum CaptureActionError {+ #[error(transparent)]+ Lookup(#[from] CaptureLookupError),+ #[error("screenshot point must be finite and within the encoded capture")]+ InvalidScreenshotPoint,+ #[error("mapped action point is not finite")]+ InvalidMappedPoint,+ #[error("capture native action frame no longer matches the live target")]+ NativeActionFrameMismatch,+}++#[derive(Clone)]+struct StoredCapture {+ id: CaptureId,+ png_bytes: Arc<[u8]>,+ digest: ContentDigest,+ target: CaptureTarget,+ encoded_dimensions: EncodedScreenshotDimensions,+ native_action_dimensions: NativeActionDimensions,+ screenshot_to_action: ScreenshotToActionTransform,+ binding: CaptureBinding,+ created_at: Duration,+ expires_at: Duration,+}++impl fmt::Debug for StoredCapture {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ formatter+ .debug_struct("StoredCapture")+ .field("id", &self.id)+ .field("byte_len", &self.png_bytes.len())+ .field("digest", &self.digest)+ .field("target", &self.target)+ .field("encoded_dimensions", &self.encoded_dimensions)+ .field("native_action_dimensions", &self.native_action_dimensions)+ .field("screenshot_to_action", &self.screenshot_to_action)+ .field("binding", &self.binding)+ .field("created_at", &self.created_at)+ .field("expires_at", &self.expires_at)+ .finish()+ }+}++#[derive(Clone, Debug)]+pub struct PerceptionCapture(StoredCapture);++impl PerceptionCapture {+ pub fn id(&self) -> CaptureId {+ self.0.id+ }++ pub fn png_bytes(&self) -> Arc<[u8]> {+ self.0.png_bytes.clone()+ }++ pub fn digest(&self) -> ContentDigest {+ self.0.digest+ }++ pub fn target(&self) -> &CaptureTarget {+ &self.0.target+ }++ pub fn encoded_dimensions(&self) -> EncodedScreenshotDimensions {+ self.0.encoded_dimensions+ }++ pub(crate) fn screenshot_to_action(&self) -> ScreenshotToActionTransform {+ self.0.screenshot_to_action+ }++ pub fn created_at(&self) -> Duration {+ self.0.created_at+ }++ pub fn expires_at(&self) -> Duration {+ self.0.expires_at+ }+}++/// A capture atomically removed from the registry for one action attempt.+///+/// The action transform and native action dimensions are exposed only through+/// this consumed form, preventing action integrations from accidentally using+/// a reusable perception read. Failed actions must acquire a fresh capture.+#[derive(Debug)]+#[allow(dead_code)]+pub struct ActionCapture(StoredCapture);++#[allow(dead_code)]+impl ActionCapture {+ pub fn id(&self) -> CaptureId {+ self.0.id+ }++ pub fn png_bytes(&self) -> Arc<[u8]> {+ self.0.png_bytes.clone()+ }++ pub fn digest(&self) -> ContentDigest {+ self.0.digest+ }++ pub fn target(&self) -> &CaptureTarget {+ &self.0.target+ }++ pub fn encoded_dimensions(&self) -> EncodedScreenshotDimensions {+ self.0.encoded_dimensions+ }++ pub fn native_action_dimensions(&self) -> NativeActionDimensions {+ self.0.native_action_dimensions+ }++ pub fn screenshot_to_action(&self) -> ScreenshotToActionTransform {+ self.0.screenshot_to_action+ }++ pub fn created_at(&self) -> Duration {+ self.0.created_at+ }++ pub fn expires_at(&self) -> Duration {+ self.0.expires_at+ }+}++struct RegistryInner {+ captures: HashMap<CaptureId, StoredCapture>,+ insertion_order: VecDeque<CaptureId>,+ expired_ids: HashSet<CaptureId>,+ expired_order: VecDeque<CaptureId>,+ total_bytes: usize,+ next_sequence: u64,+}++pub struct CaptureRegistry {+ config: CaptureRegistryConfig,+ clock: Arc<dyn MonotonicClock>,+ namespace: [u8; 16],+ inner: Mutex<RegistryInner>,+}++#[allow(dead_code)]+impl CaptureRegistry {+ pub fn new(config: CaptureRegistryConfig) -> Result<Self, CaptureStoreError> {+ Self::with_clock(config, Arc::new(SystemMonotonicClock::new()))+ }++ pub fn with_clock(+ config: CaptureRegistryConfig,+ clock: Arc<dyn MonotonicClock>,+ ) -> Result<Self, CaptureStoreError> {+ let config = config.validate()?;+ Ok(Self {+ config,+ clock,+ namespace: *Uuid::new_v4().as_bytes(),+ inner: Mutex::new(RegistryInner {+ captures: HashMap::new(),+ insertion_order: VecDeque::new(),+ expired_ids: HashSet::new(),+ expired_order: VecDeque::new(),+ total_bytes: 0,+ next_sequence: 0,+ }),+ })+ }++ pub fn store(&self, registration: CaptureRegistration) -> Result<CaptureId, CaptureStoreError> {+ registration.target.validate()?;+ if registration.png_bytes.len() > self.config.max_total_bytes {+ return Err(CaptureStoreError::CaptureTooLarge);+ }+ let mut limits = Limits::default();+ limits.max_image_width = Some(self.config.max_encoded_width);+ limits.max_image_height = Some(self.config.max_encoded_height);+ limits.max_alloc = Some(self.config.max_decoded_bytes);+ let decoder = image::codecs::png::PngDecoder::with_limits(+ Cursor::new(®istration.png_bytes),+ limits,+ )+ .map_err(map_png_admission_error)?;+ let decoded_dimensions = decoder.dimensions();+ if decoded_dimensions+ != (+ registration.encoded_dimensions.width,+ registration.encoded_dimensions.height,+ )+ {+ return Err(CaptureStoreError::InvalidEncodedDimensions);+ }+ if decoder.total_bytes() > self.config.max_decoded_bytes {+ return Err(CaptureStoreError::PngDecodeLimitExceeded);+ }+ registration+ .screenshot_to_action+ .validate_extent(registration.encoded_dimensions)?;+ image::DynamicImage::from_decoder(decoder).map_err(map_png_admission_error)?;+ let png_bytes: Arc<[u8]> = registration.png_bytes.into();+ let byte_len = png_bytes.len();+ let digest = ContentDigest(Sha256::digest(&png_bytes).into());+ let created_at = self.clock.now();+ let expires_at = created_at+ .checked_add(self.config.ttl)+ .ok_or(CaptureStoreError::ExpiryOverflow)?;++ let mut inner = self+ .inner+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ self.prune_expired_locked(&mut inner, created_at);+ if inner.next_sequence == u64::MAX {+ return Err(CaptureStoreError::IdExhausted);+ }+ while inner.captures.len() >= self.config.max_captures+ || inner.total_bytes.saturating_add(byte_len) > self.config.max_total_bytes+ {+ self.evict_oldest(&mut inner);+ }+ let sequence = inner.next_sequence;+ inner.next_sequence += 1;+ let id = CaptureId {+ namespace: self.namespace,+ sequence,+ };+ let capture = StoredCapture {+ id,+ png_bytes,+ digest,+ target: registration.target,+ encoded_dimensions: registration.encoded_dimensions,+ native_action_dimensions: registration.native_action_dimensions,+ screenshot_to_action: registration.screenshot_to_action,+ binding: registration.binding,+ created_at,+ expires_at,+ };+ inner.total_bytes += byte_len;+ inner.insertion_order.push_back(id);+ inner.captures.insert(id, capture);+ Ok(id)+ }++ /// Read immutable screenshot material without making it action-capable.+ pub fn read_for_perception(+ &self,+ id: CaptureId,+ binding: &CaptureBinding,+ target: &CaptureTarget,+ ) -> Result<PerceptionCapture, CaptureLookupError> {+ self.resolve_capture(id, binding, target, false)+ .map(PerceptionCapture)+ }++ fn read_for_perception_bound(+ &self,+ id: CaptureId,+ binding: &CaptureBinding,+ ) -> Result<PerceptionCapture, CaptureLookupError> {+ let now = self.clock.now();+ let mut inner = self+ .inner+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ if inner+ .captures+ .get(&id)+ .is_some_and(|capture| capture.expires_at <= now)+ {+ self.remove_capture(&mut inner, id);+ self.remember_expired(&mut inner, id);+ return Err(CaptureLookupError::Expired);+ }+ let capture = inner.captures.get(&id).ok_or_else(|| {+ if inner.expired_ids.contains(&id) {+ CaptureLookupError::Expired+ } else {+ CaptureLookupError::Unknown+ }+ })?;+ if capture.binding != *binding {+ return Err(CaptureLookupError::GenerationMismatch);+ }+ Ok(PerceptionCapture(capture.clone()))+ }++ fn admit_action(+ &self,+ request: CaptureActionRequest,+ ) -> Result<CaptureActionAdmission, CaptureActionError> {+ let now = self.clock.now();+ let mut inner = self+ .inner+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ if inner+ .captures+ .get(&request.capture_id)+ .is_some_and(|capture| capture.expires_at <= now)+ {+ self.remove_capture(&mut inner, request.capture_id);+ self.remember_expired(&mut inner, request.capture_id);+ return Err(CaptureLookupError::Expired.into());+ }+ let capture = inner.captures.get(&request.capture_id).ok_or_else(|| {+ if inner.expired_ids.contains(&request.capture_id) {+ CaptureLookupError::Expired+ } else {+ CaptureLookupError::Unknown+ }+ })?;+ if capture.binding != request.binding {+ return Err(CaptureLookupError::GenerationMismatch.into());+ }+ if capture.target != request.target {+ return Err(CaptureLookupError::TargetMismatch.into());+ }+ if capture.native_action_dimensions != request.current_native_action_dimensions {+ return Err(CaptureActionError::NativeActionFrameMismatch);+ }+ let max_x = f64::from(capture.encoded_dimensions.width);+ let max_y = f64::from(capture.encoded_dimensions.height);+ if !request.screenshot_x.is_finite()+ || !request.screenshot_y.is_finite()+ || request.screenshot_x < 0.0+ || request.screenshot_y < 0.0+ || request.screenshot_x >= max_x+ || request.screenshot_y >= max_y+ {+ return Err(CaptureActionError::InvalidScreenshotPoint);+ }+ let (action_x, action_y) = capture+ .screenshot_to_action+ .apply(request.screenshot_x, request.screenshot_y);+ if !action_x.is_finite() || !action_y.is_finite() {+ return Err(CaptureActionError::InvalidMappedPoint);+ }+ let admission = CaptureActionAdmission {+ capture_id: capture.id,+ target: capture.target.clone(),+ action_x,+ action_y,+ native_action_dimensions: capture.native_action_dimensions,+ digest: capture.digest,+ };+ self.remove_capture(&mut inner, request.capture_id);+ Ok(admission)+ }++ /// Atomically remove and return the capture for exactly one action attempt.+ pub fn consume_for_action(+ &self,+ id: CaptureId,+ binding: &CaptureBinding,+ target: &CaptureTarget,+ ) -> Result<ActionCapture, CaptureLookupError> {+ self.resolve_capture(id, binding, target, true)+ .map(ActionCapture)+ }++ fn resolve_capture(+ &self,+ id: CaptureId,+ binding: &CaptureBinding,+ target: &CaptureTarget,+ consume: bool,+ ) -> Result<StoredCapture, CaptureLookupError> {+ let now = self.clock.now();+ let mut inner = self+ .inner+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ if inner+ .captures+ .get(&id)+ .is_some_and(|capture| capture.expires_at <= now)+ {+ self.remove_capture(&mut inner, id);+ self.remember_expired(&mut inner, id);+ return Err(CaptureLookupError::Expired);+ }+ let capture = inner.captures.get(&id).ok_or_else(|| {+ if inner.expired_ids.contains(&id) {+ CaptureLookupError::Expired+ } else {+ CaptureLookupError::Unknown+ }+ })?;+ if capture.binding != *binding {+ return Err(CaptureLookupError::GenerationMismatch);+ }+ if capture.target != *target {+ return Err(CaptureLookupError::TargetMismatch);+ }+ let capture = capture.clone();+ if consume {+ self.remove_capture(&mut inner, id);+ }+ Ok(capture)+ }++ pub fn retire(+ &self,+ id: CaptureId,+ binding: &CaptureBinding,+ ) -> Result<(), CaptureLookupError> {+ let now = self.clock.now();+ let mut inner = self+ .inner+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ if inner+ .captures+ .get(&id)+ .is_some_and(|capture| capture.expires_at <= now)+ {+ self.remove_capture(&mut inner, id);+ self.remember_expired(&mut inner, id);+ return Err(CaptureLookupError::Expired);+ }+ let capture = inner.captures.get(&id).ok_or_else(|| {+ if inner.expired_ids.contains(&id) {+ CaptureLookupError::Expired+ } else {+ CaptureLookupError::Unknown+ }+ })?;+ if capture.binding != *binding {+ return Err(CaptureLookupError::GenerationMismatch);+ }+ self.remove_capture(&mut inner, id);+ Ok(())+ }++ pub fn retire_session(&self, binding: &CaptureBinding) -> usize {+ self.retire_matching(|capture| capture.binding == *binding)+ }++ pub fn retire_runtime(&self, runtime_generation: u64) -> usize {+ self.retire_matching(|capture| capture.binding.runtime_generation == runtime_generation)+ }++ /// Drop all registry-owned references whose TTL has elapsed.+ ///+ /// Work is bounded by `max_captures`. The returned byte count is the sum of+ /// encoded PNG lengths removed from the registry; independently cloned+ /// perception results may keep their own immutable references alive.+ pub fn prune_expired(&self) -> PruneOutcome {+ let now = self.clock.now();+ let mut inner = self+ .inner+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ self.prune_expired_locked(&mut inner, now)+ }++ pub fn len(&self) -> usize {+ self.prune_expired();+ self.inner+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .captures+ .len()+ }++ pub fn is_empty(&self) -> bool {+ self.len() == 0+ }++ pub fn total_bytes(&self) -> usize {+ self.prune_expired();+ self.inner+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .total_bytes+ }++ fn retire_matching(&self, matches: impl Fn(&StoredCapture) -> bool) -> usize {+ let mut inner = self+ .inner+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ let ids = inner+ .insertion_order+ .iter()+ .copied()+ .filter(|id| inner.captures.get(id).is_some_and(&matches))+ .collect::<Vec<_>>();+ for id in &ids {+ self.remove_capture(&mut inner, *id);+ }+ ids.len()+ }++ fn prune_expired_locked(&self, inner: &mut RegistryInner, now: Duration) -> PruneOutcome {+ let expired = inner+ .insertion_order+ .iter()+ .copied()+ .filter(|id| {+ inner+ .captures+ .get(id)+ .is_some_and(|capture| capture.expires_at <= now)+ })+ .collect::<Vec<_>>();+ let mut outcome = PruneOutcome::default();+ for id in expired {+ outcome.encoded_bytes_released += self.remove_capture(inner, id);+ outcome.captures_removed += 1;+ self.remember_expired(inner, id);+ }+ outcome+ }++ fn evict_oldest(&self, inner: &mut RegistryInner) {+ if let Some(id) = inner.insertion_order.front().copied() {+ self.remove_capture(inner, id);+ }+ }++ fn remove_capture(&self, inner: &mut RegistryInner, id: CaptureId) -> usize {+ let mut removed_bytes = 0;+ if let Some(capture) = inner.captures.remove(&id) {+ removed_bytes = capture.png_bytes.len();+ inner.total_bytes = inner.total_bytes.saturating_sub(removed_bytes);+ }+ if let Some(index) = inner+ .insertion_order+ .iter()+ .position(|candidate| *candidate == id)+ {+ inner.insertion_order.remove(index);+ }+ removed_bytes+ }++ fn remember_expired(&self, inner: &mut RegistryInner, id: CaptureId) {+ if inner.expired_ids.insert(id) {+ inner.expired_order.push_back(id);+ }+ while inner.expired_order.len() > self.config.max_captures {+ if let Some(oldest) = inner.expired_order.pop_front() {+ inner.expired_ids.remove(&oldest);+ }+ }+ }+}++static NEXT_RUNTIME_GENERATION: AtomicU64 = AtomicU64::new(1);++/// Runtime-owned facade for immutable capture publication, perception reads,+/// and one-shot action admission.+pub struct CaptureService {+ runtime_generation: u64,+ registry: CaptureRegistry,+ session_generations: Mutex<HashMap<Arc<str>, u64>>,+}++impl CaptureService {+ pub fn new(config: CaptureRegistryConfig) -> Result<Self, CaptureStoreError> {+ Self::with_clock(config, Arc::new(SystemMonotonicClock::new()))+ }++ pub(crate) fn with_clock(+ config: CaptureRegistryConfig,+ clock: Arc<dyn MonotonicClock>,+ ) -> Result<Self, CaptureStoreError> {+ let runtime_generation = NEXT_RUNTIME_GENERATION+ .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {+ (current != 0 && current != u64::MAX).then_some(current + 1)+ })+ .map_err(|_| CaptureStoreError::IdExhausted)?;+ Ok(Self {+ runtime_generation,+ registry: CaptureRegistry::with_clock(config, clock)?,+ session_generations: Mutex::new(HashMap::new()),+ })+ }++ pub fn runtime_generation(&self) -> u64 {+ self.runtime_generation+ }++ pub fn binding(+ &self,+ session_id: impl Into<Arc<str>>,+ session_generation: u64,+ ) -> Result<CaptureBinding, CaptureStoreError> {+ CaptureBinding::new(self.runtime_generation, session_id, session_generation)+ }++ /// Return the current private generation for a runtime-scoped session.+ pub fn current_binding(+ &self,+ session_id: impl Into<Arc<str>>,+ ) -> Result<CaptureBinding, CaptureStoreError> {+ let session_id = session_id.into();+ if session_id.trim().is_empty() {+ return Err(CaptureStoreError::InvalidBinding);+ }+ let generation = *self+ .session_generations+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .entry(session_id.clone())+ .or_insert(1);+ self.binding(session_id, generation)+ }++ /// Resolve trusted runtime arguments after the dispatch boundary has+ /// replaced the public session label with `_session_id`.+ pub fn binding_from_args(+ &self,+ args: &serde_json::Value,+ ) -> Result<CaptureBinding, CaptureStoreError> {+ let session_id = args+ .get("_session_id")+ .and_then(serde_json::Value::as_str)+ .filter(|value| !value.trim().is_empty())+ .ok_or(CaptureStoreError::InvalidBinding)?;+ self.current_binding(Arc::<str>::from(session_id))+ }++ pub fn publish(&self, publication: CapturePublication) -> Result<CaptureId, CaptureStoreError> {+ let binding = self.binding(publication.session_id, publication.session_generation)?;+ self.registry.store(CaptureRegistration {+ png_bytes: publication.png_bytes,+ target: publication.target,+ encoded_dimensions: publication.encoded_dimensions,+ native_action_dimensions: publication.native_action_dimensions,+ screenshot_to_action: publication.screenshot_to_action,+ binding,+ })+ }++ pub fn parse_capture_id(&self, value: &str) -> Result<CaptureId, CaptureIdParseError> {+ value.parse()+ }++ pub fn read_for_perception(+ &self,+ id: CaptureId,+ binding: &CaptureBinding,+ ) -> Result<PerceptionCapture, CaptureLookupError> {+ self.registry.read_for_perception_bound(id, binding)+ }++ pub fn admit_action(+ &self,+ request: CaptureActionRequest,+ ) -> Result<CaptureActionAdmission, CaptureActionError> {+ self.registry.admit_action(request)+ }++ pub fn retire_session(&self, binding: &CaptureBinding) -> usize {+ let removed = self.registry.retire_session(binding);+ if binding.runtime_generation == self.runtime_generation {+ let mut generations = self+ .session_generations+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ let generation = generations+ .entry(binding.session_id.clone())+ .or_insert(binding.session_generation);+ if *generation == binding.session_generation {+ *generation = generation.saturating_add(1).max(1);+ }+ }+ removed+ }++ /// Retire one capture when its owning snapshot is superseded.+ pub fn retire_capture(+ &self,+ id: CaptureId,+ binding: &CaptureBinding,+ ) -> Result<(), CaptureLookupError> {+ self.registry.retire(id, binding)+ }++ pub fn retire_session_id(&self, session_id: &str) -> usize {+ let Ok(binding) = self.current_binding(Arc::<str>::from(session_id)) else {+ return 0;+ };+ self.retire_session(&binding)+ }++ pub fn retire_runtime(&self) -> usize {+ self.registry.retire_runtime(self.runtime_generation)+ }++ pub fn prune_expired(&self) -> PruneOutcome {+ self.registry.prune_expired()+ }+}++impl Default for CaptureService {+ fn default() -> Self {+ Self::new(CaptureRegistryConfig::default()).expect("default capture config is valid")+ }+}++impl Drop for CaptureService {+ fn drop(&mut self) {+ self.registry.retire_runtime(self.runtime_generation);+ }+}++fn map_png_admission_error(error: image::ImageError) -> CaptureStoreError {+ if matches!(error, image::ImageError::Limits(_)) {+ CaptureStoreError::PngDecodeLimitExceeded+ } else {+ CaptureStoreError::InvalidPng+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::image_utils::encode_rgba_to_png;+ use std::sync::atomic::{AtomicU64, Ordering};++ #[derive(Default)]+ struct ManualClock(AtomicU64);++ impl ManualClock {+ fn advance(&self, duration: Duration) {+ self.0.fetch_add(+ u64::try_from(duration.as_millis()).expect("test duration fits"),+ Ordering::SeqCst,+ );+ }+ }++ impl MonotonicClock for ManualClock {+ fn now(&self) -> Duration {+ Duration::from_millis(self.0.load(Ordering::SeqCst))+ }+ }++ fn config(max_captures: usize, max_total_bytes: usize) -> CaptureRegistryConfig {+ CaptureRegistryConfig {+ max_captures,+ max_total_bytes,+ max_encoded_width: 4096,+ max_encoded_height: 4096,+ max_decoded_bytes: 64 * 1024 * 1024,+ ttl: Duration::from_secs(10),+ }+ }++ fn binding(runtime: u64, session: &str, generation: u64) -> CaptureBinding {+ CaptureBinding::new(runtime, Arc::<str>::from(session), generation).unwrap()+ }++ fn png(width: u32, height: u32, value: u8) -> Vec<u8> {+ encode_rgba_to_png(+ &vec![value; usize::try_from(width * height * 4).unwrap()],+ width,+ height,+ )+ .unwrap()+ }++ fn registration(+ png_bytes: Vec<u8>,+ target: CaptureTarget,+ binding: CaptureBinding,+ ) -> CaptureRegistration {+ CaptureRegistration {+ png_bytes,+ target,+ encoded_dimensions: EncodedScreenshotDimensions::new(2, 2).unwrap(),+ native_action_dimensions: NativeActionDimensions::new(2, 2).unwrap(),+ screenshot_to_action: ScreenshotToActionTransform::identity(),+ binding,+ }+ }++ fn action_request(+ capture_id: CaptureId,+ binding: CaptureBinding,+ target: CaptureTarget,+ native: (u32, u32),+ ) -> CaptureActionRequest {+ CaptureActionRequest {+ capture_id,+ binding,+ target,+ current_native_action_dimensions: NativeActionDimensions::new(native.0, native.1)+ .unwrap(),+ screenshot_x: 0.5,+ screenshot_y: 0.5,+ }+ }++ #[test]+ fn stores_immutable_png_metadata_and_never_reuses_ids() {+ let registry = CaptureRegistry::new(config(2, 10_000)).unwrap();+ let owner = binding(1, "session-a", 1);+ let target = CaptureTarget::Window {+ pid: 7,+ window_id: 9,+ };+ let bytes = png(2, 2, 42);+ let expected_digest = Sha256::digest(&bytes);+ let first = registry+ .store(registration(bytes.clone(), target.clone(), owner.clone()))+ .unwrap();+ let capture = registry+ .read_for_perception(first, &owner, &target)+ .unwrap();+ assert_eq!(capture.png_bytes().as_ref(), bytes.as_slice());+ assert_eq!(capture.digest().as_bytes(), expected_digest.as_slice());+ assert_eq!(+ capture.encoded_dimensions(),+ EncodedScreenshotDimensions::new(2, 2).unwrap()+ );++ registry.retire(first, &owner).unwrap();+ let second = registry.store(registration(bytes, target, owner)).unwrap();+ assert_ne!(first, second);+ }++ #[test]+ fn rejects_invalid_png_dimensions_target_and_transform_before_storage() {+ let registry = CaptureRegistry::new(config(4, 10_000)).unwrap();+ let owner = binding(1, "session-a", 1);+ let target = CaptureTarget::PrimaryDesktop;+ let mut invalid_png = registration(b"not a png".to_vec(), target.clone(), owner.clone());+ assert_eq!(+ registry.store(invalid_png),+ Err(CaptureStoreError::InvalidPng)+ );++ invalid_png = registration(png(3, 2, 1), target, owner.clone());+ assert_eq!(+ registry.store(invalid_png),+ Err(CaptureStoreError::InvalidEncodedDimensions)+ );++ let invalid_target = CaptureTarget::Window {+ pid: 0,+ window_id: 9,+ };+ assert_eq!(+ registry.store(registration(png(2, 2, 1), invalid_target, owner)),+ Err(CaptureStoreError::InvalidTarget)+ );+ assert_eq!(registry.len(), 0);+ assert_eq!(+ ScreenshotToActionTransform::new(f64::NAN, 0.0, 0.0, 1.0, 0.0, 0.0),+ Err(CaptureStoreError::InvalidTransform)+ );+ assert_eq!(+ ScreenshotToActionTransform::new(1.0, 2.0, 2.0, 4.0, 0.0, 0.0),+ Err(CaptureStoreError::InvalidTransform)+ );+ }++ #[test]+ fn rejects_pngs_before_decode_when_dimensions_or_allocation_exceed_limits() {+ let bytes = png(2, 2, 1);+ let owner = binding(1, "session-a", 1);+ let target = CaptureTarget::PrimaryDesktop;++ let mut dimension_config = config(2, 10_000);+ dimension_config.max_encoded_width = 1;+ let registry = CaptureRegistry::new(dimension_config).unwrap();+ assert_eq!(+ registry.store(registration(bytes.clone(), target.clone(), owner.clone())),+ Err(CaptureStoreError::PngDecodeLimitExceeded)+ );++ let mut allocation_config = config(2, 10_000);+ allocation_config.max_decoded_bytes = 8;+ let registry = CaptureRegistry::new(allocation_config).unwrap();+ assert_eq!(+ registry.store(registration(bytes, target, owner)),+ Err(CaptureStoreError::PngDecodeLimitExceeded)+ );+ }++ #[test]+ fn transform_composition_preserves_continuous_coordinates() {+ let image_to_native =+ ScreenshotToActionTransform::new(2.0, 0.0, 0.0, 3.0, 4.0, 5.0).unwrap();+ let native_to_action =+ ScreenshotToActionTransform::new(1.0, 0.5, 0.0, 1.0, -2.0, 7.0).unwrap();+ let composed = image_to_native.then(native_to_action).unwrap();+ let intermediate = image_to_native.apply(1.25, 2.5);+ assert_eq!(+ composed.apply(1.25, 2.5),+ native_to_action.apply(intermediate.0, intermediate.1)+ );+ }++ #[test]+ fn downscaled_capture_keeps_encoded_and_native_action_dimensions_distinct() {+ let registry = CaptureRegistry::new(config(2, 10_000)).unwrap();+ let owner = binding(1, "session-a", 1);+ let target = CaptureTarget::PrimaryDesktop;+ let transform = ScreenshotToActionTransform::new(2.0, 0.0, 0.0, 3.0, 0.0, 0.0).unwrap();+ let id = registry+ .store(CaptureRegistration {+ png_bytes: png(2, 2, 1),+ target: target.clone(),+ encoded_dimensions: EncodedScreenshotDimensions::new(2, 2).unwrap(),+ native_action_dimensions: NativeActionDimensions::new(4, 6).unwrap(),+ screenshot_to_action: transform,+ binding: owner.clone(),+ })+ .unwrap();++ let capture = registry.consume_for_action(id, &owner, &target).unwrap();+ assert_eq!(+ capture.encoded_dimensions(),+ EncodedScreenshotDimensions::new(2, 2).unwrap()+ );+ assert_eq!(+ capture.native_action_dimensions(),+ NativeActionDimensions::new(4, 6).unwrap()+ );+ assert_eq!(capture.screenshot_to_action().apply(1.0, 1.0), (2.0, 3.0));+ }++ #[test]+ fn rejects_transform_that_overflows_across_encoded_extent() {+ let registry = CaptureRegistry::new(config(2, 10_000)).unwrap();+ let mut capture = registration(+ png(3, 2, 1),+ CaptureTarget::PrimaryDesktop,+ binding(1, "session-a", 1),+ );+ capture.encoded_dimensions = EncodedScreenshotDimensions::new(3, 2).unwrap();+ capture.screenshot_to_action =+ ScreenshotToActionTransform::new(f64::MAX, 0.0, 0.0, 1.0, 0.0, 0.0).unwrap();+ assert_eq!(+ registry.store(capture),+ Err(CaptureStoreError::InvalidTransformExtent)+ );+ }++ #[test]+ fn lookup_errors_are_specific_and_action_consumption_is_atomic() {+ let registry = CaptureRegistry::new(config(4, 10_000)).unwrap();+ let owner = binding(1, "session-a", 1);+ let target = CaptureTarget::PrimaryDesktop;+ let id = registry+ .store(registration(png(2, 2, 1), target.clone(), owner.clone()))+ .unwrap();+ let unknown = CaptureId {+ namespace: [0; 16],+ sequence: 99,+ };+ assert_eq!(+ registry+ .read_for_perception(unknown, &owner, &target)+ .unwrap_err(),+ CaptureLookupError::Unknown+ );+ assert_eq!(+ registry+ .read_for_perception(id, &binding(1, "session-a", 2), &target)+ .unwrap_err(),+ CaptureLookupError::GenerationMismatch+ );+ assert_eq!(+ registry+ .read_for_perception(+ id,+ &owner,+ &CaptureTarget::Window {+ pid: 7,+ window_id: 9,+ },+ )+ .unwrap_err(),+ CaptureLookupError::TargetMismatch+ );+ registry.consume_for_action(id, &owner, &target).unwrap();+ assert_eq!(+ registry+ .consume_for_action(id, &owner, &target)+ .unwrap_err(),+ CaptureLookupError::Unknown+ );+ }++ #[test]+ fn unknown_expired_session_runtime_target_replacement_eviction_and_resize_refuse_dispatch() {+ let dispatched = AtomicU64::new(0);+ let attempt = |registry: &CaptureRegistry, request: CaptureActionRequest| {+ let result = registry.admit_action(request);+ if result.is_ok() {+ dispatched.fetch_add(1, Ordering::SeqCst);+ }+ result+ };+ let owner = binding(11, "session-a", 3);+ let target = CaptureTarget::Window {+ pid: 42,+ window_id: 7,+ };++ let registry = CaptureRegistry::new(config(8, 100_000)).unwrap();+ let unknown = CaptureId {+ namespace: [0; 16],+ sequence: 99,+ };+ assert_eq!(+ attempt(+ ®istry,+ action_request(unknown, owner.clone(), target.clone(), (2, 2))+ )+ .unwrap_err(),+ CaptureActionError::Lookup(CaptureLookupError::Unknown)+ );++ for (wrong_binding, expected) in [+ (+ binding(11, "session-b", 3),+ CaptureActionError::Lookup(CaptureLookupError::GenerationMismatch),+ ),+ (+ binding(12, "session-a", 3),+ CaptureActionError::Lookup(CaptureLookupError::GenerationMismatch),+ ),+ ] {+ let id = registry+ .store(registration(png(2, 2, 1), target.clone(), owner.clone()))+ .unwrap();+ assert_eq!(+ attempt(+ ®istry,+ action_request(id, wrong_binding, target.clone(), (2, 2))+ )+ .unwrap_err(),+ expected+ );+ registry.retire(id, &owner).unwrap();+ }++ let id = registry+ .store(registration(png(2, 2, 2), target.clone(), owner.clone()))+ .unwrap();+ assert_eq!(+ attempt(+ ®istry,+ action_request(id, owner.clone(), CaptureTarget::PrimaryDesktop, (2, 2))+ )+ .unwrap_err(),+ CaptureActionError::Lookup(CaptureLookupError::TargetMismatch)+ );+ registry.retire(id, &owner).unwrap();++ let replaced = registry+ .store(registration(png(2, 2, 3), target.clone(), owner.clone()))+ .unwrap();+ registry.retire(replaced, &owner).unwrap();+ let _replacement = registry+ .store(registration(png(2, 2, 4), target.clone(), owner.clone()))+ .unwrap();+ assert_eq!(+ attempt(+ ®istry,+ action_request(replaced, owner.clone(), target.clone(), (2, 2))+ )+ .unwrap_err(),+ CaptureActionError::Lookup(CaptureLookupError::Unknown)+ );++ let resized = registry+ .store(registration(png(2, 2, 5), target.clone(), owner.clone()))+ .unwrap();+ assert_eq!(+ attempt(+ ®istry,+ action_request(resized, owner.clone(), target.clone(), (3, 2))+ )+ .unwrap_err(),+ CaptureActionError::NativeActionFrameMismatch+ );++ let evicting = CaptureRegistry::new(config(1, 100_000)).unwrap();+ let evicted = evicting+ .store(registration(png(2, 2, 6), target.clone(), owner.clone()))+ .unwrap();+ let _newest = evicting+ .store(registration(png(2, 2, 7), target.clone(), owner.clone()))+ .unwrap();+ assert_eq!(+ attempt(+ &evicting,+ action_request(evicted, owner.clone(), target.clone(), (2, 2))+ )+ .unwrap_err(),+ CaptureActionError::Lookup(CaptureLookupError::Unknown)+ );++ let clock = Arc::new(ManualClock::default());+ let expiring = CaptureRegistry::with_clock(config(2, 100_000), clock.clone()).unwrap();+ let expired = expiring+ .store(registration(png(2, 2, 8), target.clone(), owner.clone()))+ .unwrap();+ clock.advance(Duration::from_secs(10));+ assert_eq!(+ attempt(&expiring, action_request(expired, owner, target, (2, 2))).unwrap_err(),+ CaptureActionError::Lookup(CaptureLookupError::Expired)+ );+ assert_eq!(dispatched.load(Ordering::SeqCst), 0);+ }++ #[test]+ fn encoded_pixel_edges_are_half_open_and_refuse_without_consuming() {+ let registry = CaptureRegistry::new(config(2, 10_000)).unwrap();+ let owner = binding(1, "edge", 1);+ let target = CaptureTarget::PrimaryDesktop;+ let id = registry+ .store(registration(png(2, 2, 1), target.clone(), owner.clone()))+ .unwrap();+ let mut request = action_request(id, owner.clone(), target.clone(), (2, 2));+ request.screenshot_x = 2.0;+ assert_eq!(+ registry.admit_action(request).unwrap_err(),+ CaptureActionError::InvalidScreenshotPoint+ );+ assert!(registry.read_for_perception(id, &owner, &target).is_ok());++ let mut request = action_request(id, owner.clone(), target.clone(), (2, 2));+ request.screenshot_y = 2.0;+ assert_eq!(+ registry.admit_action(request).unwrap_err(),+ CaptureActionError::InvalidScreenshotPoint+ );+ assert!(registry.read_for_perception(id, &owner, &target).is_ok());++ let mut request = action_request(id, owner, target, (2, 2));+ request.screenshot_x = 2.0 - f64::EPSILON;+ request.screenshot_y = 2.0 - f64::EPSILON;+ assert!(registry.admit_action(request).is_ok());+ }++ #[test]+ fn bounded_maintenance_releases_expired_png_without_lookup_or_store() {+ let clock = Arc::new(ManualClock::default());+ let registry = CaptureRegistry::with_clock(config(2, 10_000), clock.clone()).unwrap();+ let owner = binding(1, "session-a", 1);+ let target = CaptureTarget::PrimaryDesktop;+ let id = registry+ .store(registration(png(2, 2, 1), target.clone(), owner.clone()))+ .unwrap();+ let bytes = registry+ .read_for_perception(id, &owner, &target)+ .unwrap()+ .png_bytes();+ let weak_bytes = Arc::downgrade(&bytes);+ let byte_len = bytes.len();+ drop(bytes);+ clock.advance(Duration::from_secs(10));+ assert_eq!(+ registry.prune_expired(),+ PruneOutcome {+ captures_removed: 1,+ encoded_bytes_released: byte_len,+ }+ );+ assert!(weak_bytes.upgrade().is_none());+ assert_eq!(+ registry+ .read_for_perception(id, &owner, &target)+ .unwrap_err(),+ CaptureLookupError::Expired+ );+ assert!(registry.is_empty());+ assert_eq!(registry.total_bytes(), 0);+ }++ #[test]+ fn count_and_byte_limits_evict_oldest_deterministically() {+ let sample = png(2, 2, 1);+ let byte_limit = sample.len() * 2;+ let registry = CaptureRegistry::new(config(2, byte_limit)).unwrap();+ let owner = binding(1, "session-a", 1);+ let target = CaptureTarget::PrimaryDesktop;+ let first = registry+ .store(registration(sample.clone(), target.clone(), owner.clone()))+ .unwrap();+ let second = registry+ .store(registration(sample.clone(), target.clone(), owner.clone()))+ .unwrap();+ let third = registry+ .store(registration(sample, target.clone(), owner.clone()))+ .unwrap();+ assert_eq!(registry.len(), 2);+ assert_eq!(registry.total_bytes(), byte_limit);+ assert_eq!(+ registry+ .read_for_perception(first, &owner, &target)+ .unwrap_err(),+ CaptureLookupError::Unknown+ );+ assert!(registry+ .read_for_perception(second, &owner, &target)+ .is_ok());+ assert!(registry.read_for_perception(third, &owner, &target).is_ok());+ }++ #[test]+ fn session_and_runtime_cleanup_are_generation_exact() {+ let registry = CaptureRegistry::new(config(4, 10_000)).unwrap();+ let target = CaptureTarget::PrimaryDesktop;+ let first = binding(1, "same-label", 1);+ let second = binding(1, "same-label", 2);+ let other_runtime = binding(2, "same-label", 1);+ registry+ .store(registration(png(2, 2, 1), target.clone(), first.clone()))+ .unwrap();+ registry+ .store(registration(png(2, 2, 2), target.clone(), second.clone()))+ .unwrap();+ registry+ .store(registration(png(2, 2, 3), target.clone(), other_runtime))+ .unwrap();++ assert_eq!(registry.retire_session(&first), 1);+ assert_eq!(registry.len(), 2);+ assert_eq!(registry.retire_runtime(1), 1);+ assert_eq!(registry.len(), 1);+ assert_eq!(registry.retire_runtime(2), 1);+ assert!(registry.is_empty());+ }++ #[test]+ fn service_round_trips_ids_and_applies_full_affine_once() {+ let service = CaptureService::new(config(4, 10_000)).unwrap();+ let target = CaptureTarget::Window {+ pid: 42,+ window_id: 7,+ };+ let transform = ScreenshotToActionTransform::new(2.0, 0.5, -0.25, 3.0, 11.0, -4.0).unwrap();+ let id = service+ .publish(CapturePublication {+ png_bytes: png(4, 3, 9),+ target: target.clone(),+ encoded_dimensions: EncodedScreenshotDimensions::new(4, 3).unwrap(),+ native_action_dimensions: NativeActionDimensions::new(40, 30).unwrap(),+ screenshot_to_action: transform,+ session_id: Arc::from("session-a"),+ session_generation: 2,+ })+ .unwrap();+ assert_eq!(service.parse_capture_id(&id.to_string()).unwrap(), id);+ let binding = service.binding("session-a", 2).unwrap();+ let admission = service+ .admit_action(CaptureActionRequest {+ capture_id: id,+ binding: binding.clone(),+ target: target.clone(),+ current_native_action_dimensions: NativeActionDimensions::new(40, 30).unwrap(),+ screenshot_x: 2.5,+ screenshot_y: 1.5,+ })+ .unwrap();+ assert_eq!((admission.action_x, admission.action_y), (16.75, -0.125));+ assert_eq!(admission.target, target);+ assert_eq!(+ service+ .admit_action(CaptureActionRequest {+ capture_id: id,+ binding,+ target: CaptureTarget::Window {+ pid: 42,+ window_id: 7,+ },+ current_native_action_dimensions: NativeActionDimensions::new(40, 30).unwrap(),+ screenshot_x: 2.5,+ screenshot_y: 1.5,+ })+ .unwrap_err(),+ CaptureActionError::Lookup(CaptureLookupError::Unknown)+ );+ }++ #[test]+ fn invalid_action_point_does_not_consume_capture() {+ let service = CaptureService::new(config(4, 10_000)).unwrap();+ let target = CaptureTarget::PrimaryDesktop;+ let id = service+ .publish(CapturePublication {+ png_bytes: png(2, 2, 5),+ target: target.clone(),+ encoded_dimensions: EncodedScreenshotDimensions::new(2, 2).unwrap(),+ native_action_dimensions: NativeActionDimensions::new(2, 2).unwrap(),+ screenshot_to_action: ScreenshotToActionTransform::identity(),+ session_id: Arc::from("session-a"),+ session_generation: 1,+ })+ .unwrap();+ let binding = service.binding("session-a", 1).unwrap();+ assert_eq!(+ service+ .admit_action(CaptureActionRequest {+ capture_id: id,+ binding: binding.clone(),+ target: target.clone(),+ current_native_action_dimensions: NativeActionDimensions::new(2, 2).unwrap(),+ screenshot_x: f64::NAN,+ screenshot_y: 0.0,+ })+ .unwrap_err(),+ CaptureActionError::InvalidScreenshotPoint+ );+ assert!(service.read_for_perception(id, &binding).is_ok());+ }++ #[test]+ fn capture_id_parser_rejects_noncanonical_ids() {+ let id = CaptureId {+ namespace: [0xab; 16],+ sequence: 15,+ };+ assert_eq!(id.to_string().parse::<CaptureId>().unwrap(), id);+ for invalid in [+ "",+ "capture_deadbeef_000000000000000f",+ "capture_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz_000000000000000f",+ "capture_abababababababababababababababab_0_f",+ ] {+ assert_eq!(+ invalid.parse::<CaptureId>().unwrap_err(),+ CaptureIdParseError::InvalidFormat+ );+ }+ }++ #[test]+ fn service_owns_session_generation_and_advances_it_on_retirement() {+ let service = CaptureService::new(config(4, 10_000)).unwrap();+ let first = service+ .binding_from_args(&serde_json::json!({"_session_id": "runtime/session-a"}))+ .unwrap();+ assert_eq!(first.session_generation(), 1);+ assert_eq!(service.retire_session_id("runtime/session-a"), 0);+ let second = service.current_binding("runtime/session-a").unwrap();+ assert_eq!(second.session_generation(), 2);+ assert_eq!(first.runtime_generation(), second.runtime_generation());+ assert_eq!(+ service+ .binding_from_args(&serde_json::json!({"session": "public-forgery"}))+ .unwrap_err(),+ CaptureStoreError::InvalidBinding+ );+ }++ #[test]+ fn poisoned_registry_and_session_locks_recover_without_panicking_or_underflowing() {+ let registry = Arc::new(CaptureRegistry::new(config(2, 10_000)).unwrap());+ let id = registry+ .store(registration(+ png(2, 2, 1),+ CaptureTarget::PrimaryDesktop,+ binding(1, "poisoned", 1),+ ))+ .unwrap();+ let poisoned_registry = registry.clone();+ assert!(std::thread::spawn(move || {+ let mut inner = poisoned_registry.inner.lock().unwrap();+ inner.total_bytes = 0;+ panic!("poison registry lock");+ })+ .join()+ .is_err());+ assert_eq!(registry.retire(id, &binding(1, "poisoned", 1)), Ok(()));+ assert_eq!(registry.total_bytes(), 0);++ let service = Arc::new(CaptureService::new(config(2, 10_000)).unwrap());+ let poisoned_sessions = service.clone();+ assert!(std::thread::spawn(move || {+ let _guard = poisoned_sessions.session_generations.lock().unwrap();+ panic!("poison session lock");+ })+ .join()+ .is_err());+ assert_eq!(+ service+ .current_binding("still-available")+ .unwrap()+ .session_generation(),+ 1+ );+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/capture_runtime.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/capture_runtime.rsnew file mode 100644index 0000000000..cd8c868b1f--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/capture_runtime.rs@@ -0,0 +1,8 @@+//! Public runtime facade for capture publication and capture-bound actions.++pub use crate::capture_registry::{+ CaptureActionAdmission, CaptureActionError, CaptureActionRequest, CaptureBinding, CaptureId,+ CaptureIdParseError, CaptureLookupError, CapturePublication, CaptureService, CaptureStoreError,+ CaptureTarget, EncodedScreenshotDimensions, NativeActionDimensions, PruneOutcome,+ ScreenshotToActionTransform,+};diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/element_cache.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/element_cache.rsindex 6446104ba6..77777dbd6d 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/element_cache.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/element_cache.rs@@ -3,7 +3,7 @@ use crate::element_token::{};use crate::protocol::ToolResult;use std::any::Any;-use std::collections::HashMap;+use std::collections::{HashMap, HashSet, VecDeque};use std::sync::{Arc, Mutex, OnceLock, Weak};pub trait SnapshotPayload: Send + Sync + 'static {@@ -15,41 +15,495 @@ pub trait SnapshotPayload: Send + Sync + 'static {struct Snapshot<S> {id: u32,window_id: u64,+ screenshot_owner: Option<String>,+ screenshot_scale: Option<f64>,payload: S,}+struct ElementCacheState<S> {+ snapshots: HashMap<i32, Vec<Snapshot<S>>>,+ retired_screenshots: HashSet<(i32, u64)>,+ retired_screenshot_order: VecDeque<(i32, u64)>,+ retired_screenshot_overflowed: bool,+}++const RETIRED_SCREENSHOT_CAPACITY: usize = 256;++impl<S> Default for ElementCacheState<S> {+ fn default() -> Self {+ Self {+ snapshots: HashMap::new(),+ retired_screenshots: HashSet::new(),+ retired_screenshot_order: VecDeque::new(),+ retired_screenshot_overflowed: false,+ }+ }+}++impl<S> ElementCacheState<S> {+ fn retire_screenshot(&mut self, key: (i32, u64)) {+ if self.retired_screenshot_overflowed || self.retired_screenshots.contains(&key) {+ return;+ }+ if self.retired_screenshots.len() == RETIRED_SCREENSHOT_CAPACITY {+ self.retired_screenshot_overflowed = true;+ return;+ }+ self.retired_screenshots.insert(key);+ self.retired_screenshot_order.push_back(key);+ }++ fn restore_screenshot(&mut self, key: (i32, u64)) {+ if self.retired_screenshots.remove(&key) {+ self.retired_screenshot_order.retain(|entry| *entry != key);+ }+ }++ fn missing_screenshot_is_retired(&self, pid: i32, window_id: Option<u64>) -> bool {+ self.retired_screenshot_overflowed+ || match window_id {+ Some(window_id) => self.retired_screenshots.contains(&(pid, window_id)),+ None => self+ .retired_screenshots+ .iter()+ .any(|(retired_pid, _)| *retired_pid == pid),+ }+ }++ fn reset_retired_screenshots(&mut self) {+ self.retired_screenshots.clear();+ self.retired_screenshot_order.clear();+ self.retired_screenshot_overflowed = false;+ }+}++#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum ScreenshotContextError {+ ReplacedOrUnavailable,+}++#[derive(Clone, Copy, Debug, PartialEq)]+pub struct ScreenshotContext {+ pub snapshot_id: u32,+ pub window_id: u64,+ pub scale: f64,+}++#[derive(Clone, Copy, Debug, PartialEq)]+pub struct SnapshotBoundZoomContext {+ pub screenshot: ScreenshotContext,+ pub origin_x: f64,+ pub origin_y: f64,+ pub scale_inv: f64,+}++impl SnapshotBoundZoomContext {+ pub fn zoom_to_window(&self, x: f64, y: f64) -> (f64, f64) {+ (+ self.origin_x + x * self.scale_inv,+ self.origin_y + y * self.scale_inv,+ )+ }+}++pub struct SnapshotBoundZoomRegistry {+ inner: Mutex<HashMap<(i32, u64, Option<String>), SnapshotBoundZoomContext>>,+}++impl SnapshotBoundZoomRegistry {+ pub fn new() -> Self {+ Self {+ inner: Mutex::new(HashMap::new()),+ }+ }++ pub fn set_if_current<S: SnapshotPayload>(+ &self,+ cache: &ElementCacheCore<S>,+ pid: i32,+ session: Option<&str>,+ context: SnapshotBoundZoomContext,+ ) -> Result<(), ToolResult> {+ cache+ .with_valid_screenshot_context(pid, session, context.screenshot, || {+ self.inner.lock().unwrap().insert(+ (+ pid,+ context.screenshot.window_id,+ session.map(str::to_owned),+ ),+ context,+ );+ })+ .map_err(|_| zoom_context_refusal(pid, Some(context.screenshot.window_id)))+ }++ pub fn resolve<S: SnapshotPayload>(+ &self,+ cache: &ElementCacheCore<S>,+ pid: i32,+ window_id: Option<u64>,+ session: Option<&str>,+ ) -> Result<SnapshotBoundZoomContext, ToolResult> {+ let owner = session.map(str::to_owned);+ let (key, context) = {+ let inner = self.inner.lock().unwrap();+ let mut matches = inner+ .iter()+ .filter(|((entry_pid, entry_window, entry_owner), _)| {+ *entry_pid == pid+ && window_id.is_none_or(|window_id| *entry_window == window_id)+ && entry_owner == &owner+ });+ let Some((key, context)) = matches.next() else {+ return Err(zoom_context_refusal(pid, window_id));+ };+ if matches.next().is_some() {+ return Err(zoom_context_refusal(pid, window_id));+ }+ (key.clone(), *context)+ };+ if cache+ .validate_screenshot_context(pid, session, context.screenshot)+ .is_err()+ {+ self.inner.lock().unwrap().remove(&key);+ return Err(zoom_context_refusal(pid, window_id));+ }+ Ok(context)+ }++ pub fn retire_replaced(&self, pid: i32, window_id: u64, current_snapshot_id: u32) -> bool {+ let mut inner = self.inner.lock().unwrap();+ let before = inner.len();+ inner.retain(|(entry_pid, entry_window, _), context| {+ *entry_pid != pid+ || *entry_window != window_id+ || context.screenshot.snapshot_id == current_snapshot_id+ });+ inner.len() != before+ }++ pub fn retire_session(&self, session: &str) -> usize {+ let mut inner = self.inner.lock().unwrap();+ let before = inner.len();+ inner.retain(|(_, _, owner), _| owner.as_deref() != Some(session));+ before - inner.len()+ }+}++impl Default for SnapshotBoundZoomRegistry {+ fn default() -> Self {+ Self::new()+ }+}++fn screenshot_context_refusal(pid: Option<i32>, window_id: Option<u64>) -> ToolResult {+ ToolResult::error(+ "The latest snapshot for this window does not contain a screenshot owned by this session. Call get_window_state with a screenshot on the same connection before using pixels.",+ )+ .with_structured(serde_json::json!({+ "code": "screenshot_context_missing",+ "pid": pid,+ "window_id": window_id,+ }))+}++fn zoom_context_refusal(pid: i32, window_id: Option<u64>) -> ToolResult {+ ToolResult::error(+ "The zoom coordinate context is missing or was replaced by a newer snapshot. Call get_window_state and zoom again on the same connection before using from_zoom coordinates.",+ )+ .with_structured(serde_json::json!({+ "code": "zoom_context_missing",+ "pid": pid,+ "window_id": window_id,+ }))+}+pub struct ElementCacheCore<S: SnapshotPayload> {runtime_scope: String,- inner: Mutex<HashMap<i32, Vec<Snapshot<S>>>>,+ inner: Mutex<ElementCacheState<S>>,}impl<S: SnapshotPayload> ElementCacheCore<S> {pub fn new() -> Self {Self {runtime_scope: current_runtime_scope(),- inner: Mutex::new(HashMap::new()),+ inner: Mutex::new(ElementCacheState::default()),}}pub fn publish(&self, pid: i32, window_id: u64, payload: S) -> u32 {+ self.publish_for_session(pid, window_id, payload, None, None)+ .expect("anonymous snapshot publication cannot be retired")+ }++ /// Publish the latest runtime-owned snapshot and its screenshot coordinate frame.+ ///+ /// `screenshot_scale` is the native-image-width / delivered-image-width ratio.+ /// A `None` scale deliberately records that the latest observation did not+ /// deliver an actionable screenshot. Publications completing after their+ /// owning session ended are discarded instead of resurrecting retired state.+ pub fn publish_for_session(+ &self,+ pid: i32,+ window_id: u64,+ payload: S,+ session: Option<&str>,+ screenshot_scale: Option<f64>,+ ) -> Option<u32> {let (id, replaced, evicted) = {let mut inner = self.inner.lock().unwrap();- let lane = inner.entry(pid).or_default();- let replaced = lane- .iter()- .position(|entry| entry.window_id == window_id)- .map(|position| lane.remove(position));- let evicted = (lane.len() == LRU_CAP_PER_PID).then(|| lane.remove(0));- let id = crate::element_token::mint_snapshot_id();- lane.push(Snapshot {- id,- window_id,- payload,- });+ if session.is_some_and(crate::session::is_session_ended) {+ return None;+ }+ inner.restore_screenshot((pid, window_id));+ let (id, replaced, evicted) = {+ let lane = inner.snapshots.entry(pid).or_default();+ let replaced = lane+ .iter()+ .position(|entry| entry.window_id == window_id)+ .map(|position| lane.remove(position));+ let evicted = (lane.len() == LRU_CAP_PER_PID).then(|| lane.remove(0));+ let id = crate::element_token::mint_snapshot_id();+ lane.push(Snapshot {+ id,+ window_id,+ screenshot_owner: session.map(str::to_owned),+ screenshot_scale,+ payload,+ });+ (id, replaced, evicted)+ };+ if let Some(evicted) = &evicted {+ inner.retire_screenshot((pid, evicted.window_id));+ }(id, replaced, evicted)};drop((replaced, evicted));- id+ Some(id)+ }++ /// Resolve the screenshot transform from the same authoritative latest+ /// snapshot used for element tokens.+ ///+ /// No snapshot preserves the legacy native-pixel fallback. Once a snapshot+ /// exists, a different owner or a newer observation without a screenshot+ /// makes older image coordinates stale and must be refused.+ pub fn screenshot_scale(+ &self,+ pid: i32,+ window_id: Option<u64>,+ session: Option<&str>,+ ) -> Result<Option<f64>, ScreenshotContextError> {+ Ok(self+ .screenshot_context(pid, window_id, session)?+ .map(|context| context.scale))+ }++ pub fn screenshot_context(+ &self,+ pid: i32,+ window_id: Option<u64>,+ session: Option<&str>,+ ) -> Result<Option<ScreenshotContext>, ScreenshotContextError> {+ let inner = self.inner.lock().unwrap();+ let Some(lane) = inner.snapshots.get(&pid) else {+ return if inner.missing_screenshot_is_retired(pid, window_id) {+ Err(ScreenshotContextError::ReplacedOrUnavailable)+ } else {+ Ok(None)+ };+ };+ if let Some(window_id) = window_id {+ let Some(snapshot) = lane.iter().find(|entry| entry.window_id == window_id) else {+ return if inner.missing_screenshot_is_retired(pid, Some(window_id)) {+ Err(ScreenshotContextError::ReplacedOrUnavailable)+ } else {+ Ok(None)+ };+ };+ if snapshot.screenshot_owner.as_deref() != session {+ return Err(ScreenshotContextError::ReplacedOrUnavailable);+ }+ let scale = snapshot+ .screenshot_scale+ .ok_or(ScreenshotContextError::ReplacedOrUnavailable)?;+ return Ok(Some(ScreenshotContext {+ snapshot_id: snapshot.id,+ window_id,+ scale,+ }));+ }+ if inner.missing_screenshot_is_retired(pid, None) {+ return Err(ScreenshotContextError::ReplacedOrUnavailable);+ }+ let mut agreed: Option<ScreenshotContext> = None;+ for snapshot in lane {+ if snapshot.screenshot_owner.as_deref() != session {+ return Err(ScreenshotContextError::ReplacedOrUnavailable);+ }+ let scale = snapshot+ .screenshot_scale+ .ok_or(ScreenshotContextError::ReplacedOrUnavailable)?;+ let context = ScreenshotContext {+ snapshot_id: snapshot.id,+ window_id: snapshot.window_id,+ scale,+ };+ match agreed {+ None => agreed = Some(context),+ Some(previous) if (previous.scale - scale).abs() < 1e-9 => {}+ Some(_) => return Err(ScreenshotContextError::ReplacedOrUnavailable),+ }+ }+ Ok(agreed)+ }++ pub fn validate_screenshot_context(+ &self,+ pid: i32,+ session: Option<&str>,+ expected: ScreenshotContext,+ ) -> Result<(), ScreenshotContextError> {+ match self.screenshot_context(pid, Some(expected.window_id), session)? {+ Some(current)+ if current.snapshot_id == expected.snapshot_id+ && (current.scale - expected.scale).abs() < 1e-9 =>+ {+ Ok(())+ }+ _ => Err(ScreenshotContextError::ReplacedOrUnavailable),+ }+ }++ fn with_valid_screenshot_context<R>(+ &self,+ pid: i32,+ session: Option<&str>,+ expected: ScreenshotContext,+ publish: impl FnOnce() -> R,+ ) -> Result<R, ScreenshotContextError> {+ let inner = self.inner.lock().unwrap();+ let valid = inner.snapshots.get(&pid).is_some_and(|lane| {+ lane.iter().any(|snapshot| {+ snapshot.window_id == expected.window_id+ && snapshot.id == expected.snapshot_id+ && snapshot.screenshot_owner.as_deref() == session+ && snapshot+ .screenshot_scale+ .is_some_and(|scale| (scale - expected.scale).abs() < 1e-9)+ })+ });+ if !valid {+ return Err(ScreenshotContextError::ReplacedOrUnavailable);+ }+ let result = publish();+ drop(inner);+ Ok(result)+ }++ pub fn unique_screenshot_context_for_window(+ &self,+ window_id: u64,+ session: Option<&str>,+ ) -> Result<(i32, ScreenshotContext), ScreenshotContextError> {+ let inner = self.inner.lock().unwrap();+ let mut matches = inner.snapshots.iter().filter_map(|(pid, lane)| {+ let snapshot = lane+ .iter()+ .find(|snapshot| snapshot.window_id == window_id)?;+ (snapshot.screenshot_owner.as_deref() == session).then_some((pid, snapshot))+ });+ let Some((pid, snapshot)) = matches.next() else {+ return Err(ScreenshotContextError::ReplacedOrUnavailable);+ };+ if matches.next().is_some() {+ return Err(ScreenshotContextError::ReplacedOrUnavailable);+ }+ let scale = snapshot+ .screenshot_scale+ .ok_or(ScreenshotContextError::ReplacedOrUnavailable)?;+ Ok((+ *pid,+ ScreenshotContext {+ snapshot_id: snapshot.id,+ window_id,+ scale,+ },+ ))+ }++ pub fn screenshot_context_or_refusal(+ &self,+ pid: i32,+ window_id: u64,+ session: Option<&str>,+ ) -> Result<ScreenshotContext, ToolResult> {+ match self.screenshot_context(pid, Some(window_id), session) {+ Ok(Some(context)) => Ok(context),+ Ok(None) | Err(ScreenshotContextError::ReplacedOrUnavailable) => {+ Err(screenshot_context_refusal(Some(pid), Some(window_id)))+ }+ }+ }++ pub fn screenshot_context_for_zoom(+ &self,+ pid: Option<i32>,+ window_id: u64,+ session: Option<&str>,+ ) -> Result<(i32, ScreenshotContext), ToolResult> {+ match pid {+ Some(pid) => self+ .screenshot_context_or_refusal(pid, window_id, session)+ .map(|context| (pid, context)),+ None => self+ .unique_screenshot_context_for_window(window_id, session)+ .map_err(|_| screenshot_context_refusal(None, Some(window_id))),+ }+ }++ pub fn screenshot_scale_or_refusal(+ &self,+ pid: i32,+ window_id: Option<u64>,+ session: Option<&str>,+ ) -> Result<f64, ToolResult> {+ match self.screenshot_scale(pid, window_id, session) {+ Ok(scale) => Ok(scale.unwrap_or(1.0)),+ Err(ScreenshotContextError::ReplacedOrUnavailable) => {+ Err(screenshot_context_refusal(Some(pid), window_id))+ }+ }+ }++ pub fn retire_session_screenshots(&self, session: &str) -> usize {+ let retired = {+ let mut inner = self.inner.lock().unwrap();+ let mut retired = Vec::new();+ let mut tombstones = Vec::new();+ for (pid, lane) in inner.snapshots.iter_mut() {+ let mut index = 0;+ while index < lane.len() {+ if lane[index].screenshot_owner.as_deref() == Some(session) {+ tombstones.push((*pid, lane[index].window_id));+ retired.push(lane.remove(index));+ } else {+ index += 1;+ }+ }+ }+ inner.snapshots.retain(|_, lane| !lane.is_empty());+ tombstones.sort_unstable();+ for tombstone in tombstones {+ inner.retire_screenshot(tombstone);+ }+ retired+ };+ let count = retired.len();+ drop(retired);+ count}pub fn resolve_element_args(@@ -79,6 +533,7 @@ impl<S: SnapshotPayload> ElementCacheCore<S> {}let inner = self.inner.lock().unwrap();let entry = inner+ .snapshots.get(&pid).and_then(|lane| lane.iter().find(|entry| entry.id == reference.snapshot_id));let Some(entry) = entry else {@@ -129,17 +584,26 @@ impl<S: SnapshotPayload> ElementCacheCore<S> {pub fn remove(&self, pid: i32, window_id: u64) {let retired = {let mut inner = self.inner.lock().unwrap();- inner.get_mut(&pid).and_then(|lane| {+ let retired = inner.snapshots.get_mut(&pid).and_then(|lane| {let position = lane.iter().position(|entry| entry.window_id == window_id)?;Some(lane.remove(position))- })+ });+ if retired.is_some() {+ inner.retire_screenshot((pid, window_id));+ }+ retired};drop(retired);}pub fn clear(&self) -> usize {- let retired = std::mem::take(&mut *self.inner.lock().unwrap());- retired.len()+ let mut inner = self.inner.lock().unwrap();+ let retired = std::mem::take(&mut inner.snapshots);+ inner.reset_retired_screenshots();+ let count = retired.len();+ drop(inner);+ drop(retired);+ count}}@@ -174,6 +638,7 @@ impl<S: SnapshotPayload> RuntimeCache for ElementCacheCore<S> {self.inner.lock().unwrap()+ .snapshots.get(&pid).is_some_and(|lane| lane.iter().any(|entry| entry.id == snapshot_id))}@@ -260,6 +725,537 @@ mod tests {.is_err());}+ #[test]+ fn screenshot_coordinates_never_borrow_another_sessions_latest_transform() {+ let cache = ElementCacheCore::new();+ cache.publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(7.35));+ assert_eq!(+ cache.screenshot_scale(10, Some(20), Some("client-a")),+ Ok(Some(7.35))+ );++ cache.publish_for_session(10, 20, Payload(vec![]), Some("client-b"), Some(1.0));+ assert_eq!(+ cache.screenshot_scale(10, Some(20), Some("client-b")),+ Ok(Some(1.0))+ );+ assert_eq!(+ cache.screenshot_scale(10, Some(20), Some("client-a")),+ Err(ScreenshotContextError::ReplacedOrUnavailable)+ );+ let refusal = cache+ .screenshot_scale_or_refusal(10, Some(20), Some("client-a"))+ .expect_err("stale image coordinates must be refused");+ assert_eq!(+ refusal.structured_content.as_ref().unwrap()["code"],+ "screenshot_context_missing"+ );+ }++ #[test]+ fn screenshot_transforms_are_independent_across_windows() {+ let cache = ElementCacheCore::new();+ cache.publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(7.35));+ cache.publish_for_session(10, 21, Payload(vec![]), Some("client-b"), Some(2.0));+ assert_eq!(+ cache.screenshot_scale(10, Some(20), Some("client-a")),+ Ok(Some(7.35))+ );+ assert_eq!(+ cache.screenshot_scale(10, Some(21), Some("client-b")),+ Ok(Some(2.0))+ );+ }++ #[test]+ fn same_session_latest_snapshot_replaces_or_refuses_older_image_context() {+ let cache = ElementCacheCore::new();+ cache.publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(7.35));+ cache.publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(1.0));+ assert_eq!(+ cache.screenshot_scale(10, Some(20), Some("client-a")),+ Ok(Some(1.0)),+ "a newer native capture replaces the older resized frame"+ );++ cache.publish_for_session(10, 20, Payload(vec![]), Some("client-a"), None);+ assert_eq!(+ cache.screenshot_scale(10, Some(20), Some("client-a")),+ Err(ScreenshotContextError::ReplacedOrUnavailable),+ "a newer tree-only observation retires the older image frame"+ );+ }++ #[test]+ fn session_retirement_removes_only_snapshots_owned_by_that_session() {+ let cache = ElementCacheCore::new();+ cache.publish_for_session(10, 20, Payload(vec![]), Some("ending"), Some(7.35));+ cache.publish_for_session(10, 21, Payload(vec![]), Some("survivor"), Some(2.0));+ assert_eq!(cache.retire_session_screenshots("ending"), 1);+ assert_eq!(+ cache.screenshot_scale(10, Some(20), Some("ending")),+ Err(ScreenshotContextError::ReplacedOrUnavailable)+ );+ assert_eq!(+ cache.screenshot_scale(10, Some(21), Some("survivor")),+ Ok(Some(2.0))+ );+ }++ #[test]+ fn retired_screenshot_refuses_cross_session_and_anonymous_replay_until_republished() {+ let cache = ElementCacheCore::new();+ cache.publish_for_session(10, 20, Payload(vec![]), Some("ending"), Some(7.35));+ assert_eq!(cache.retire_session_screenshots("ending"), 1);++ for session in [Some("ending"), Some("other"), None] {+ assert_eq!(+ cache.screenshot_scale(10, Some(20), session),+ Err(ScreenshotContextError::ReplacedOrUnavailable),+ "a retired screenshot must not become native-pixel fallback"+ );+ }+ assert_eq!(+ cache.screenshot_scale(10, None, Some("other")),+ Err(ScreenshotContextError::ReplacedOrUnavailable)+ );++ cache.publish_for_session(10, 20, Payload(vec![]), Some("other"), Some(2.0));+ assert_eq!(+ cache.screenshot_scale(10, Some(20), Some("other")),+ Ok(Some(2.0)),+ "a fresh snapshot clears the lightweight retirement tombstone"+ );+ assert_eq!(+ cache.screenshot_scale(10, Some(20), None),+ Err(ScreenshotContextError::ReplacedOrUnavailable)+ );++ cache.publish_for_session(10, 20, Payload(vec![]), None, Some(1.5));+ assert_eq!(+ cache.screenshot_scale(10, Some(20), None),+ Ok(Some(1.5)),+ "a fresh anonymous snapshot also recovers the coordinate context"+ );+ }++ #[test]+ fn lru_eviction_retires_only_the_evicted_screenshot_key() {+ let cache = ElementCacheCore::new();+ for window_id in 0..LRU_CAP_PER_PID as u64 {+ cache.publish_for_session(10, window_id, Payload(vec![]), Some("client-a"), Some(2.0));+ }+ cache.publish_for_session(+ 10,+ LRU_CAP_PER_PID as u64,+ Payload(vec![]),+ Some("client-a"),+ Some(2.0),+ );++ assert_eq!(+ cache.screenshot_scale(10, Some(0), Some("client-a")),+ Err(ScreenshotContextError::ReplacedOrUnavailable),+ "evicting an observed window must not restore native-pixel fallback"+ );+ assert_eq!(+ cache.screenshot_scale(10, Some(1), Some("client-a")),+ Ok(Some(2.0))+ );+ assert_eq!(+ cache.screenshot_scale(10, Some(9999), Some("client-a")),+ Ok(None),+ "a never-observed key keeps the legacy fallback"+ );+ }++ #[test]+ fn explicit_remove_retires_only_a_snapshot_that_existed() {+ let cache = ElementCacheCore::new();+ cache.publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(2.0));+ cache.remove(10, 20);++ assert_eq!(+ cache.screenshot_scale(10, Some(20), Some("client-a")),+ Err(ScreenshotContextError::ReplacedOrUnavailable),+ "removing an observed window must not restore native-pixel fallback"+ );+ cache.remove(10, 21);+ assert_eq!(+ cache.screenshot_scale(10, Some(21), Some("client-a")),+ Ok(None),+ "removing an absent key must not retire a never-observed window"+ );+ }++ #[test]+ fn capture_completing_after_session_end_is_not_published() {+ let cache = ElementCacheCore::new();+ let session = format!("snapshot-late-capture-{}", uuid::Uuid::new_v4());+ assert!(crate::session::fire_session_end(&session));+ assert_eq!(+ cache.publish_for_session(10, 20, Payload(vec![]), Some(&session), Some(7.35)),+ None+ );+ assert_eq!(+ cache.screenshot_scale(10, Some(20), Some(&session)),+ Ok(None)+ );+ }++ #[test]+ fn no_snapshot_keeps_legacy_native_pixel_fallback() {+ let cache = ElementCacheCore::<Payload>::new();+ assert_eq!(+ cache.screenshot_scale(10, Some(20), Some("client-a")),+ Ok(None)+ );+ }++ #[test]+ fn retired_screenshot_index_has_deterministic_fixed_capacity() {+ let mut state = ElementCacheState::<Payload>::default();+ let expected = (0..RETIRED_SCREENSHOT_CAPACITY)+ .map(|index| (1000 + index as i32, 2000 + index as u64))+ .collect::<Vec<_>>();+ for key in &expected {+ state.retire_screenshot(*key);+ }++ assert_eq!(state.retired_screenshots.len(), RETIRED_SCREENSHOT_CAPACITY);+ assert_eq!(+ state+ .retired_screenshot_order+ .iter()+ .copied()+ .collect::<Vec<_>>(),+ expected+ );+ assert!(!state.retired_screenshot_overflowed);++ let order_before_duplicate = state.retired_screenshot_order.clone();+ state.retire_screenshot(expected[0]);+ assert_eq!(state.retired_screenshot_order, order_before_duplicate);++ state.retire_screenshot((9999, 9999));+ assert!(state.retired_screenshot_overflowed);+ assert_eq!(state.retired_screenshots.len(), RETIRED_SCREENSHOT_CAPACITY);+ assert_eq!(state.retired_screenshot_order, order_before_duplicate);+ assert!(!state.retired_screenshots.contains(&(9999, 9999)));+ }++ fn overflow_retired_screenshots(cache: &ElementCacheCore<Payload>) -> (i32, u64) {+ for index in 0..=RETIRED_SCREENSHOT_CAPACITY {+ cache.publish_for_session(+ 1000 + index as i32,+ 2000 + index as u64,+ Payload(vec![]),+ Some("ending"),+ Some(2.0),+ );+ }+ assert_eq!(+ cache.retire_session_screenshots("ending"),+ RETIRED_SCREENSHOT_CAPACITY + 1+ );+ (+ 1000 + RETIRED_SCREENSHOT_CAPACITY as i32,+ 2000 + RETIRED_SCREENSHOT_CAPACITY as u64,+ )+ }++ #[test]+ fn retired_screenshot_overflow_refuses_unrecorded_and_unseen_replay() {+ let cache = ElementCacheCore::new();+ let overflow_key = overflow_retired_screenshots(&cache);++ let inner = cache.inner.lock().unwrap();+ assert!(inner.retired_screenshot_overflowed);+ assert_eq!(inner.retired_screenshots.len(), RETIRED_SCREENSHOT_CAPACITY);+ assert_eq!(+ inner.retired_screenshot_order.len(),+ RETIRED_SCREENSHOT_CAPACITY+ );+ assert!(!inner.retired_screenshots.contains(&overflow_key));+ drop(inner);++ assert_eq!(+ cache.screenshot_scale(overflow_key.0, Some(overflow_key.1), None),+ Err(ScreenshotContextError::ReplacedOrUnavailable)+ );+ assert_eq!(+ cache.screenshot_scale(9999, Some(9999), None),+ Err(ScreenshotContextError::ReplacedOrUnavailable)+ );+ }++ #[test]+ fn fresh_snapshot_resolves_while_retirement_index_is_overflowed() {+ let cache = ElementCacheCore::new();+ let overflow_key = overflow_retired_screenshots(&cache);++ cache.publish_for_session(+ overflow_key.0,+ overflow_key.1,+ Payload(vec![]),+ Some("fresh"),+ Some(3.0),+ );+ assert_eq!(+ cache.screenshot_scale(overflow_key.0, Some(overflow_key.1), Some("fresh")),+ Ok(Some(3.0))+ );+ assert_eq!(+ cache.screenshot_scale(overflow_key.0, Some(overflow_key.1), Some("other")),+ Err(ScreenshotContextError::ReplacedOrUnavailable)+ );+ assert_eq!(+ cache.screenshot_scale(9999, Some(9999), Some("fresh")),+ Err(ScreenshotContextError::ReplacedOrUnavailable)+ );+ }++ #[test]+ fn clear_resets_retired_screenshot_overflow() {+ let cache = ElementCacheCore::new();+ overflow_retired_screenshots(&cache);+ cache.clear();++ let inner = cache.inner.lock().unwrap();+ assert!(inner.retired_screenshots.is_empty());+ assert!(inner.retired_screenshot_order.is_empty());+ assert!(!inner.retired_screenshot_overflowed);+ drop(inner);+ assert_eq!(cache.screenshot_scale(9999, Some(9999), None), Ok(None));+ }++ #[test]+ fn zoom_context_is_bound_to_snapshot_session_and_window() {+ let cache = ElementCacheCore::new();+ let zooms = SnapshotBoundZoomRegistry::new();+ let snapshot = cache+ .publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(7.35))+ .unwrap();+ let context = SnapshotBoundZoomContext {+ screenshot: ScreenshotContext {+ snapshot_id: snapshot,+ window_id: 20,+ scale: 7.35,+ },+ origin_x: 100.0,+ origin_y: 50.0,+ scale_inv: 2.0,+ };+ zooms+ .set_if_current(&cache, 10, Some("client-a"), context)+ .unwrap();++ assert_eq!(+ zooms+ .resolve(&cache, 10, Some(20), Some("client-a"))+ .unwrap(),+ context+ );+ assert_eq!(context.zoom_to_window(3.0, 4.0), (106.0, 58.0));+ assert_eq!(+ zooms+ .resolve(&cache, 10, Some(20), Some("client-b"))+ .unwrap_err()+ .structured_content+ .as_ref()+ .unwrap()["code"],+ "zoom_context_missing"+ );+ assert_eq!(+ zooms+ .resolve(&cache, 10, Some(21), Some("client-a"))+ .unwrap_err()+ .structured_content+ .as_ref()+ .unwrap()["code"],+ "zoom_context_missing"+ );+ }++ #[test]+ fn window_only_screenshot_lookup_requires_one_current_owned_snapshot() {+ let cache = ElementCacheCore::new();+ let first = cache+ .publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(2.0))+ .unwrap();+ assert_eq!(+ cache+ .screenshot_context_for_zoom(None, 20, Some("client-a"))+ .unwrap(),+ (+ 10,+ ScreenshotContext {+ snapshot_id: first,+ window_id: 20,+ scale: 2.0,+ }+ )+ );+ assert_eq!(+ cache+ .screenshot_context_for_zoom(Some(10), 20, Some("client-a"))+ .unwrap()+ .0,+ 10+ );+ assert!(cache+ .unique_screenshot_context_for_window(20, Some("client-b"))+ .is_err());++ cache.publish_for_session(11, 20, Payload(vec![]), Some("client-a"), Some(1.0));+ assert!(cache+ .unique_screenshot_context_for_window(20, Some("client-a"))+ .is_err());+ }++ #[test]+ fn late_zoom_completion_cannot_replace_newer_valid_context() {+ let cache = ElementCacheCore::new();+ let zooms = SnapshotBoundZoomRegistry::new();+ let snapshot_a = cache+ .publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(2.0))+ .unwrap();+ let slow_a = SnapshotBoundZoomContext {+ screenshot: ScreenshotContext {+ snapshot_id: snapshot_a,+ window_id: 20,+ scale: 2.0,+ },+ origin_x: 10.0,+ origin_y: 20.0,+ scale_inv: 2.0,+ };++ let snapshot_b = cache+ .publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(1.0))+ .unwrap();+ let valid_b = SnapshotBoundZoomContext {+ screenshot: ScreenshotContext {+ snapshot_id: snapshot_b,+ window_id: 20,+ scale: 1.0,+ },+ origin_x: 30.0,+ origin_y: 40.0,+ scale_inv: 1.0,+ };+ zooms+ .set_if_current(&cache, 10, Some("client-a"), valid_b)+ .unwrap();+ assert!(zooms+ .set_if_current(&cache, 10, Some("client-a"), slow_a)+ .is_err());+ assert_eq!(+ zooms+ .resolve(&cache, 10, Some(20), Some("client-a"))+ .unwrap(),+ valid_b+ );+ }++ #[test]+ fn newer_snapshot_retires_zoom_for_click_drag_and_held_pointer_coordinates() {+ let cache = ElementCacheCore::new();+ let zooms = SnapshotBoundZoomRegistry::new();+ let snapshot = cache+ .publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(7.35))+ .unwrap();+ let context = SnapshotBoundZoomContext {+ screenshot: ScreenshotContext {+ snapshot_id: snapshot,+ window_id: 20,+ scale: 7.35,+ },+ origin_x: 100.0,+ origin_y: 50.0,+ scale_inv: 2.0,+ };+ zooms+ .set_if_current(&cache, 10, Some("client-a"), context)+ .unwrap();++ let click = context.zoom_to_window(1.0, 2.0);+ let drag_from = context.zoom_to_window(3.0, 4.0);+ let held_pointer_to = context.zoom_to_window(5.0, 6.0);+ assert_eq!(+ (click, drag_from, held_pointer_to),+ ((102.0, 54.0), (106.0, 58.0), (110.0, 62.0))+ );++ let replacement = cache+ .publish_for_session(10, 20, Payload(vec![]), Some("client-b"), Some(1.0))+ .unwrap();+ assert!(zooms.retire_replaced(10, 20, replacement));+ let refusal = zooms+ .resolve(&cache, 10, Some(20), Some("client-a"))+ .expect_err("all uses of the old zoom image must become stale together");+ assert_eq!(+ refusal.structured_content.as_ref().unwrap()["code"],+ "zoom_context_missing"+ );+ }++ #[test]+ fn zoom_context_retires_on_same_session_replacement_and_session_end() {+ let cache = ElementCacheCore::new();+ let zooms = SnapshotBoundZoomRegistry::new();+ let snapshot = cache+ .publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(7.35))+ .unwrap();+ zooms+ .set_if_current(+ &cache,+ 10,+ Some("client-a"),+ SnapshotBoundZoomContext {+ screenshot: ScreenshotContext {+ snapshot_id: snapshot,+ window_id: 20,+ scale: 7.35,+ },+ origin_x: 0.0,+ origin_y: 0.0,+ scale_inv: 1.0,+ },+ )+ .unwrap();++ let replacement = cache+ .publish_for_session(10, 20, Payload(vec![]), Some("client-a"), Some(1.0))+ .unwrap();+ assert!(zooms.retire_replaced(10, 20, replacement));+ assert!(zooms+ .resolve(&cache, 10, Some(20), Some("client-a"))+ .is_err());++ let latest = cache+ .screenshot_context(10, Some(20), Some("client-a"))+ .unwrap()+ .unwrap();+ zooms+ .set_if_current(+ &cache,+ 10,+ Some("client-a"),+ SnapshotBoundZoomContext {+ screenshot: latest,+ origin_x: 0.0,+ origin_y: 0.0,+ scale_inv: 1.0,+ },+ )+ .unwrap();+ assert_eq!(zooms.retire_session("client-a"), 1);+ assert!(zooms+ .resolve(&cache, 10, Some(20), Some("client-a"))+ .is_err());+ }+struct DropCounter {owner: Weak<ElementCacheCore<DropCounter>>,drops: Arc<AtomicUsize>,@@ -285,6 +1281,33 @@ mod tests {}}+ #[test]+ fn screenshot_retirement_keeps_only_tombstone_not_payload() {+ let cache = Arc::new(ElementCacheCore::new());+ let drops = Arc::new(AtomicUsize::new(0));+ cache.publish_for_session(+ 10,+ 20,+ DropCounter {+ owner: Arc::downgrade(&cache),+ drops: drops.clone(),+ },+ Some("ending"),+ Some(2.0),+ );+ assert_eq!(cache.retire_session_screenshots("ending"), 1);+ assert_eq!(drops.load(Ordering::SeqCst), 1);+ let inner = cache.inner.lock().unwrap();+ assert!(inner.snapshots.is_empty());+ assert_eq!(inner.retired_screenshots.len(), 1);+ assert_eq!(inner.retired_screenshot_order.len(), 1);+ drop(inner);+ assert_eq!(+ cache.screenshot_scale(10, Some(20), None),+ Err(ScreenshotContextError::ReplacedOrUnavailable)+ );+ }+#[test]fn replacement_remove_and_clear_run_drop_outside_lock() {let cache = Arc::new(ElementCacheCore::new());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.rsindex cb080f5cf8..cc82578a74 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@@ -47,6 +47,8 @@ pub mod authorization;pub mod background_input;pub mod browser;pub mod capture_mode;+pub(crate) mod capture_registry;+pub mod capture_runtime;pub mod capture_scope;pub mod cdp;pub mod clipboard;@@ -66,6 +68,8 @@ pub mod history;pub mod image_utils;pub mod mcp_result;pub mod page;+pub mod perception_client;+pub mod perception_tools;pub mod pip_hook;pub mod policy;pub mod protocol;diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/mcp_skills.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/mcp_skills.rsindex 8961c00280..8355a40503 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/mcp_skills.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/mcp_skills.rs@@ -47,6 +47,10 @@ const FILES: &[(&str, &str)] = &["SKILL.md",include_str!("../../../Skills/cua-driver/SKILL.md"),),+ (+ "VISUAL.md",+ include_str!("../../../Skills/cua-driver/VISUAL.md"),+ ),("WORKFLOW.md",include_str!("../../../Skills/cua-driver/WORKFLOW.md"),diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/perception_client.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/perception_client.rsnew file mode 100644index 0000000000..e2b6f7f97e--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/perception_client.rs@@ -0,0 +1,2155 @@+//! Bounded, single-use IPC client for the optional perception worker.++pub mod containment;++use std::path::PathBuf;+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};+use std::sync::Arc;+use std::time::{Duration, Instant};++use serde::Deserialize;+use serde_json::{json, Value};+use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};+use tokio::sync::{Mutex as AsyncMutex, Notify};+use uuid::Uuid;++use cua_driver_contract::{VisualParseError, VisualParseErrorCode};++#[cfg(test)]+use containment::ContainmentLimits;+use containment::{ContainedChild, WorkerExit, WorkerStdin, WorkerStdout};++const PROTOCOL_VERSION: &str = "cua-perception/1";+// A default-registry capture expands to four base64 bytes per three PNG bytes.+// Leave a fixed envelope for the bounded request metadata and capture ID.+const DEFAULT_MAX_FRAME_BYTES: usize =+ ((crate::capture_registry::DEFAULT_MAX_CAPTURE_BYTES + 2) / 3) * 4 + 64 * 1024;++/// Signed extension identity the launched worker must echo in every result.+#[derive(Clone, Debug, Eq, PartialEq)]+pub struct ExpectedExtensionIdentity {+ pub id: String,+ pub version: String,+}++#[derive(Clone, Debug)]+pub struct PerceptionWorkerConfig {+ pub executable: PathBuf,+ pub args: Vec<String>,+ pub request_timeout: Duration,+ pub max_frame_bytes: usize,+ pub warm_worker: Option<WarmWorkerPolicy>,+ pub expected_extension_identity: Option<ExpectedExtensionIdentity>,+ installed: bool,+ windows_acl_lease_path: Option<PathBuf>,+ #[cfg(test)]+ containment: ContainmentLimits,+}++impl PerceptionWorkerConfig {+ pub fn new(executable: impl Into<PathBuf>) -> Self {+ Self {+ executable: executable.into(),+ args: Vec::new(),+ request_timeout: Duration::from_secs(30),+ max_frame_bytes: DEFAULT_MAX_FRAME_BYTES,+ warm_worker: None,+ expected_extension_identity: None,+ installed: false,+ windows_acl_lease_path: None,+ #[cfg(test)]+ containment: ContainmentLimits::default(),+ }+ }++ pub fn with_bounded_reuse(mut self, policy: WarmWorkerPolicy) -> Self {+ self.warm_worker = Some(policy);+ self+ }++ /// Coordinate Windows worker ACL grants with extension lifecycle changes.+ pub fn with_windows_acl_lease_path(mut self, path: impl Into<PathBuf>) -> Self {+ self.windows_acl_lease_path = Some(path.into());+ self+ }++ /// Configuration for an installed extension.+ ///+ /// The worker starts cold for every parse and is shut down afterwards. Warm+ /// reuse stays behind [`Self::with_bounded_reuse`] until per-platform+ /// cleanup certification passes, so an installed extension never keeps a+ /// worker process — and the screenshot it was handed — alive between+ /// requests by default.+ pub fn installed(executable: impl Into<PathBuf>) -> Self {+ let mut config = Self::new(executable);+ config.installed = true;+ config+ }++ /// Bind an installed worker invocation and its result to the identity from+ /// the verified signed extension manifest.+ ///+ /// The worker CLI must accept these arguments and copy them verbatim to+ /// `result.identity.extension`. A missing or different identity fails the+ /// parse before its result reaches Driver consumers.+ pub fn installed_with_identity(+ executable: impl Into<PathBuf>,+ id: impl Into<String>,+ version: impl Into<String>,+ ) -> Self {+ let identity = ExpectedExtensionIdentity {+ id: id.into(),+ version: version.into(),+ };+ let mut config = Self::installed(executable);+ config.args.extend([+ "--extension-id".to_owned(),+ identity.id.clone(),+ "--extension-version".to_owned(),+ identity.version.clone(),+ ]);+ config.expected_extension_identity = Some(identity);+ config+ }++ fn containment_limits(&self) -> containment::ContainmentLimits {+ #[cfg(test)]+ {+ let mut limits = self.containment.clone();+ limits.windows_acl_lease_path = self.windows_acl_lease_path.clone();+ limits+ }+ #[cfg(not(test))]+ {+ containment::ContainmentLimits {+ windows_acl_lease_path: self.windows_acl_lease_path.clone(),+ ..containment::ContainmentLimits::default()+ }+ }+ }++ #[cfg(test)]+ pub(crate) fn with_test_containment(+ mut self,+ containment: containment::ContainmentLimits,+ ) -> Self {+ self.containment = containment;+ self+ }+}++#[derive(Clone, Copy, Debug)]+pub struct WarmWorkerPolicy {+ pub startup_timeout: Duration,+ pub inference_timeout: Duration,+ pub shutdown_timeout: Duration,+ pub idle_ttl: Duration,+}++impl Default for WarmWorkerPolicy {+ fn default() -> Self {+ Self {+ startup_timeout: Duration::from_secs(15),+ inference_timeout: Duration::from_secs(30),+ shutdown_timeout: Duration::from_secs(2),+ idle_ttl: Duration::from_secs(30),+ }+ }+}++#[derive(Clone, Default)]+pub struct PerceptionCancellation {+ cancelled: Arc<AtomicBool>,+ notify: Arc<Notify>,+}++impl PerceptionCancellation {+ pub fn cancel(&self) {+ self.cancelled.store(true, Ordering::Release);+ self.notify.notify_waiters();+ }++ pub fn is_cancelled(&self) -> bool {+ self.cancelled.load(Ordering::Acquire)+ }++ async fn cancelled(&self) {+ if self.is_cancelled() {+ return;+ }+ self.notify.notified().await;+ }+}++#[derive(Default)]+struct PerceptionState {+ worker: AsyncMutex<Option<WarmWorker>>,+ cancellation_epoch: AtomicU64,+ cancellation_notify: Notify,+}++impl Drop for PerceptionState {+ fn drop(&mut self) {+ self.worker.get_mut().take();+ }+}++#[derive(Clone, Default)]+pub struct PerceptionClient {+ config: Option<Arc<PerceptionWorkerConfig>>,+ state: Arc<PerceptionState>,+}++impl PerceptionClient {+ pub fn unavailable() -> Self {+ Self {+ config: None,+ state: Arc::new(PerceptionState::default()),+ }+ }++ pub fn new(config: PerceptionWorkerConfig) -> Result<Self, VisualParseError> {+ if config+ .expected_extension_identity+ .as_ref()+ .is_some_and(|identity| {+ identity.id.trim().is_empty() || identity.version.trim().is_empty()+ })+ {+ return Err(error(+ VisualParseErrorCode::ArtifactInvalid,+ "the verified perception extension identity must be non-empty",+ false,+ None,+ ));+ }+ if config.installed && config.expected_extension_identity.is_none() {+ return Err(error(+ VisualParseErrorCode::ArtifactInvalid,+ "an installed perception extension must be bound to its verified identity",+ false,+ None,+ ));+ }+ if config.request_timeout.is_zero()+ || config.max_frame_bytes == 0+ || config.max_frame_bytes > u32::MAX as usize+ || config.warm_worker.is_some_and(|policy| {+ policy.startup_timeout.is_zero()+ || policy.inference_timeout.is_zero()+ || policy.shutdown_timeout.is_zero()+ || policy.idle_ttl.is_zero()+ })+ {+ return Err(error(+ VisualParseErrorCode::ResourceLimitExceeded,+ "perception worker limits must be non-zero and fit the framed protocol",+ false,+ None,+ ));+ }+ config.containment_limits().validate()?;+ Ok(Self {+ config: Some(Arc::new(config)),+ state: Arc::new(PerceptionState::default()),+ })+ }++ pub fn is_available(&self) -> bool {+ self.config.is_some()+ }++ /// Cancel any in-flight request and synchronously drop an idle worker.+ pub fn shutdown_now(&self) {+ self.state.cancellation_epoch.fetch_add(1, Ordering::AcqRel);+ self.state.cancellation_notify.notify_waiters();+ if let Ok(mut worker) = self.state.worker.try_lock() {+ worker.take();+ }+ }++ /// Launch one worker process and issue exactly one parse. Failures are+ /// returned to the caller without replaying the request.+ pub async fn parse(+ &self,+ capture_id: &str,+ width: u32,+ height: u32,+ png_bytes: &[u8],+ cancellation: &PerceptionCancellation,+ ) -> Result<Value, VisualParseError> {+ let config = self.config.as_ref().ok_or_else(|| {+ error(+ VisualParseErrorCode::NotInstalled,+ "the optional cua-perception extension is not installed",+ false,+ None,+ )+ })?;+ if cancellation.is_cancelled() {+ return Err(cancelled_error());+ }++ if let Some(policy) = config.warm_worker {+ return self+ .parse_warm(+ config,+ policy,+ capture_id,+ width,+ height,+ png_bytes,+ cancellation,+ )+ .await;+ }++ let operation = self.parse_cold(config, capture_id, width, height, png_bytes);+ tokio::select! {+ _ = cancellation.cancelled() => Err(cancelled_error()),+ result = tokio::time::timeout(config.request_timeout, operation) => {+ match result {+ Ok(result) => result,+ Err(_) => Err(error(+ VisualParseErrorCode::Timeout,+ "the perception worker exceeded its request deadline",+ true,+ None,+ )),+ }+ }+ }+ }++ async fn parse_cold(+ &self,+ config: &PerceptionWorkerConfig,+ capture_id: &str,+ width: u32,+ height: u32,+ png_bytes: &[u8],+ ) -> Result<Value, VisualParseError> {+ let mut worker = WarmWorker::launch(config).await?;+ let result = worker+ .parse(config, capture_id, width, height, png_bytes)+ .await?;+ // Dropping the writer closes the pipe on every platform, which is what+ // the worker observes as end of file; a named-pipe shutdown would not.+ worker.stdin.take();+ match worker.contained.wait().await.map_err(map_crash_error)? {+ WorkerExit::Success => Ok(result),+ exit => Err(map_worker_exit(exit)),+ }+ }++ async fn parse_warm(+ &self,+ config: &Arc<PerceptionWorkerConfig>,+ policy: WarmWorkerPolicy,+ capture_id: &str,+ width: u32,+ height: u32,+ png_bytes: &[u8],+ cancellation: &PerceptionCancellation,+ ) -> Result<Value, VisualParseError> {+ let epoch = self.state.cancellation_epoch.load(Ordering::Acquire);+ let mut slot = tokio::select! {+ _ = cancellation.cancelled() => return Err(cancelled_error()),+ _ = runtime_cancelled(&self.state, epoch) => return Err(cancelled_error()),+ slot = self.state.worker.lock() => slot,+ };++ if slot+ .as_ref()+ .is_some_and(|worker| worker.last_used.elapsed() >= policy.idle_ttl)+ {+ if let Some(worker) = slot.take() {+ shutdown_worker(worker, policy.shutdown_timeout).await;+ }+ }++ if slot.is_none() {+ let launch = WarmWorker::launch(config);+ let worker = tokio::select! {+ _ = cancellation.cancelled() => return Err(cancelled_error()),+ _ = runtime_cancelled(&self.state, epoch) => return Err(cancelled_error()),+ result = tokio::time::timeout(policy.startup_timeout, launch) => {+ match result {+ Ok(result) => result?,+ Err(_) => return Err(timeout_error("startup")),+ }+ }+ };+ *slot = Some(worker);+ }++ let operation = slot+ .as_mut()+ .expect("warm worker was initialized")+ .parse(config, capture_id, width, height, png_bytes);+ let result = tokio::select! {+ _ = cancellation.cancelled() => Err(cancelled_error()),+ _ = runtime_cancelled(&self.state, epoch) => Err(cancelled_error()),+ result = tokio::time::timeout(policy.inference_timeout, operation) => {+ match result {+ Ok(result) => result,+ Err(_) => Err(timeout_error("inference")),+ }+ }+ };+ let result = match result {+ Ok(result) => result,+ Err(failure) => {+ slot.take();+ return Err(failure);+ }+ };++ let worker = slot.as_mut().expect("successful worker remains present");+ worker.last_used = Instant::now();+ worker.idle_generation = worker.idle_generation.wrapping_add(1);+ let idle_generation = worker.idle_generation;+ drop(slot);+ schedule_idle_shutdown(+ Arc::downgrade(&self.state),+ idle_generation,+ policy.idle_ttl,+ policy.shutdown_timeout,+ );+ Ok(result)+ }+}++struct WarmWorker {+ contained: ContainedChild,+ /// Taken to close the request pipe when the worker should observe end of+ /// file, which is the only way a named-pipe parent end signals it.+ stdin: Option<WorkerStdin>,+ stdout: WorkerStdout,+ _working_directory: tempfile::TempDir,+ last_used: Instant,+ idle_generation: u64,+}++impl WarmWorker {+ async fn launch(config: &PerceptionWorkerConfig) -> Result<Self, VisualParseError> {+ let working_directory = tempfile::Builder::new()+ .prefix("cua-perception-")+ .tempdir()+ .map_err(|cause| {+ error(+ VisualParseErrorCode::WorkerLaunchFailed,+ "failed to create a private perception worker directory",+ true,+ Some(cause.to_string()),+ )+ })?;+ let limits = config.containment_limits();+ let mut contained = containment::spawn(+ &config.executable,+ &config.args,+ working_directory.path(),+ &limits,+ )+ .await?;+ let mut stdin = contained.take_stdin().ok_or_else(|| {+ error(+ VisualParseErrorCode::WorkerLaunchFailed,+ "perception worker stdin was unavailable",+ true,+ None,+ )+ })?;+ let mut stdout = contained.take_stdout().ok_or_else(|| {+ error(+ VisualParseErrorCode::WorkerLaunchFailed,+ "perception worker stdout was unavailable",+ true,+ None,+ )+ })?;+ let health_id = format!("health-{}", Uuid::new_v4());+ write_json_frame(+ &mut stdin,+ &json!({"protocol": PROTOCOL_VERSION, "request_id": health_id, "method": "health", "params": {}}),+ config.max_frame_bytes,+ )+ .await?;+ let health = read_response(&mut stdout, config.max_frame_bytes).await?;+ let health_result = health.into_result(&health_id)?;+ if health_result.get("ready").and_then(Value::as_bool) != Some(true)+ || health_result.get("protocol").and_then(Value::as_str) != Some(PROTOCOL_VERSION)+ {+ return Err(error(+ VisualParseErrorCode::IncompatibleProtocol,+ "perception worker health response is incompatible",+ false,+ None,+ ));+ }+ verify_expected_extension_identity(+ &health_result,+ config.expected_extension_identity.as_ref(),+ )?;+ Ok(Self {+ contained,+ stdin: Some(stdin),+ stdout,+ _working_directory: working_directory,+ last_used: Instant::now(),+ idle_generation: 0,+ })+ }++ async fn parse(+ &mut self,+ config: &PerceptionWorkerConfig,+ capture_id: &str,+ width: u32,+ height: u32,+ png_bytes: &[u8],+ ) -> Result<Value, VisualParseError> {+ use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};++ let stdin = self.stdin.as_mut().ok_or_else(|| {+ error(+ VisualParseErrorCode::WorkerCrashed,+ "the perception worker request pipe was already closed",+ true,+ None,+ )+ })?;+ let request_id = format!("parse-{}", Uuid::new_v4());+ write_json_frame(+ stdin,+ &json!({+ "protocol": PROTOCOL_VERSION,+ "request_id": request_id,+ "method": "parse",+ "params": {+ "capture_id": capture_id,+ "image": {+ "media_type": "image/png",+ "width": width,+ "height": height,+ "byte_length": png_bytes.len(),+ "data_base64": BASE64.encode(png_bytes),+ }+ }+ }),+ config.max_frame_bytes,+ )+ .await?;+ let result = read_response(&mut self.stdout, config.max_frame_bytes)+ .await?+ .into_result(&request_id)?;+ verify_expected_extension_identity(&result, config.expected_extension_identity.as_ref())?;+ Ok(result)+ }+}++fn verify_expected_extension_identity(+ result: &Value,+ expected: Option<&ExpectedExtensionIdentity>,+) -> Result<(), VisualParseError> {+ let Some(expected) = expected else {+ return Ok(());+ };+ let extension = result+ .get("identity")+ .and_then(|identity| identity.get("extension"));+ let actual_id = extension+ .and_then(|value| value.get("id"))+ .and_then(Value::as_str);+ let actual_version = extension+ .and_then(|value| value.get("version"))+ .and_then(Value::as_str);+ if actual_id != Some(expected.id.as_str()) || actual_version != Some(expected.version.as_str())+ {+ return Err(error(+ VisualParseErrorCode::ArtifactInvalid,+ "perception worker identity did not match the verified signed extension manifest",+ false,+ None,+ ));+ }+ Ok(())+}++async fn runtime_cancelled(state: &PerceptionState, epoch: u64) {+ loop {+ let notified = state.cancellation_notify.notified();+ if state.cancellation_epoch.load(Ordering::Acquire) != epoch {+ return;+ }+ notified.await;+ }+}++fn schedule_idle_shutdown(+ state: std::sync::Weak<PerceptionState>,+ generation: u64,+ idle_ttl: Duration,+ shutdown_timeout: Duration,+) {+ tokio::spawn(async move {+ tokio::time::sleep(idle_ttl).await;+ let Some(state) = state.upgrade() else {+ return;+ };+ let mut slot = state.worker.lock().await;+ let should_shutdown = slot.as_ref().is_some_and(|worker| {+ worker.idle_generation == generation && worker.last_used.elapsed() >= idle_ttl+ });+ if should_shutdown {+ if let Some(worker) = slot.take() {+ shutdown_worker(worker, shutdown_timeout).await;+ }+ }+ });+}++async fn shutdown_worker(mut worker: WarmWorker, timeout: Duration) {+ worker.stdin.take();+ let _ = tokio::time::timeout(timeout, worker.contained.wait()).await;+}++/// A worker that a containment ceiling ended is reported as a resource limit+/// rather than a crash, so a caller does not retry a request that cannot+/// succeed until the worker is replaced.+fn map_worker_exit(exit: WorkerExit) -> VisualParseError {+ match exit {+ WorkerExit::Success => error(+ VisualParseErrorCode::InferenceFailed,+ "the perception worker reported success without a result",+ false,+ None,+ ),+ WorkerExit::ResourceLimit(detail) => error(+ VisualParseErrorCode::ResourceLimitExceeded,+ "the perception worker exhausted a containment resource ceiling",+ false,+ Some(detail),+ ),+ WorkerExit::Failure(detail) => error(+ VisualParseErrorCode::WorkerCrashed,+ "perception worker exited unsuccessfully after responding",+ true,+ Some(detail),+ ),+ }+}++#[derive(Deserialize)]+struct WorkerResponse {+ protocol: String,+ request_id: Option<String>,+ status: String,+ #[serde(default)]+ result: Option<Value>,+ #[serde(default)]+ error: Option<WorkerError>,+}++#[derive(Deserialize)]+struct WorkerError {+ code: String,+ message: String,+ #[serde(default)]+ details: Option<Value>,+}++impl WorkerResponse {+ fn into_result(self, expected_request_id: &str) -> Result<Value, VisualParseError> {+ if self.protocol != PROTOCOL_VERSION {+ return Err(error(+ VisualParseErrorCode::IncompatibleProtocol,+ "perception worker returned an incompatible protocol version",+ false,+ Some(self.protocol),+ ));+ }+ if self.request_id.as_deref() != Some(expected_request_id) {+ return Err(error(+ VisualParseErrorCode::InvalidFrame,+ "perception worker response request_id did not match",+ false,+ self.request_id,+ ));+ }+ match self.status.as_str() {+ "ok" => self.result.ok_or_else(|| {+ error(+ VisualParseErrorCode::InvalidFrame,+ "perception worker success omitted its result",+ false,+ None,+ )+ }),+ "error" => {+ let worker = self.error.ok_or_else(|| {+ error(+ VisualParseErrorCode::InvalidFrame,+ "perception worker error omitted its payload",+ false,+ None,+ )+ })?;+ Err(map_worker_error(worker))+ }+ _ => Err(error(+ VisualParseErrorCode::InvalidFrame,+ "perception worker returned an unknown status",+ false,+ Some(self.status),+ )),+ }+ }+}++async fn write_json_frame(+ writer: &mut (impl AsyncWrite + Unpin),+ value: &Value,+ maximum: usize,+) -> Result<(), VisualParseError> {+ let payload = serde_json::to_vec(value).map_err(|cause| {+ error(+ VisualParseErrorCode::ArtifactInvalid,+ "failed to serialize the perception request",+ false,+ Some(cause.to_string()),+ )+ })?;+ if payload.is_empty() || payload.len() > maximum {+ return Err(error(+ VisualParseErrorCode::ResourceLimitExceeded,+ "perception request exceeds the framed IPC limit",+ false,+ Some(payload.len().to_string()),+ ));+ }+ writer+ .write_all(&(payload.len() as u32).to_be_bytes())+ .await+ .map_err(map_io_error)?;+ writer.write_all(&payload).await.map_err(map_io_error)?;+ writer.flush().await.map_err(map_io_error)+}++async fn read_response(+ reader: &mut (impl AsyncRead + Unpin),+ maximum: usize,+) -> Result<WorkerResponse, VisualParseError> {+ let mut prefix = [0_u8; 4];+ reader+ .read_exact(&mut prefix)+ .await+ .map_err(map_crash_error)?;+ let declared = u32::from_be_bytes(prefix) as usize;+ if declared == 0 || declared > maximum {+ return Err(error(+ VisualParseErrorCode::InvalidFrame,+ "perception worker returned an invalid frame length",+ false,+ Some(declared.to_string()),+ ));+ }+ let mut payload = vec![0_u8; declared];+ reader+ .read_exact(&mut payload)+ .await+ .map_err(map_crash_error)?;+ serde_json::from_slice(&payload).map_err(|cause| {+ error(+ VisualParseErrorCode::InvalidFrame,+ "perception worker returned invalid JSON",+ false,+ Some(cause.to_string()),+ )+ })+}++fn map_worker_error(worker: WorkerError) -> VisualParseError {+ let code = match worker.code.as_str() {+ "incompatible_protocol" => VisualParseErrorCode::IncompatibleProtocol,+ "invalid_frame" | "invalid_json" | "invalid_request" => VisualParseErrorCode::InvalidFrame,+ "invalid_image" => VisualParseErrorCode::ArtifactInvalid,+ "resource_limit_exceeded" => VisualParseErrorCode::ResourceLimitExceeded,+ "unsupported_platform" => VisualParseErrorCode::UnsupportedPlatform,+ _ => VisualParseErrorCode::InferenceFailed,+ };+ error(+ code,+ worker.message,+ matches!(code, VisualParseErrorCode::InferenceFailed),+ worker.details.map(|value| value.to_string()),+ )+}++fn map_io_error(cause: std::io::Error) -> VisualParseError {+ error(+ VisualParseErrorCode::WorkerCrashed,+ "perception worker IPC failed",+ true,+ Some(cause.to_string()),+ )+}++fn map_crash_error(cause: std::io::Error) -> VisualParseError {+ error(+ VisualParseErrorCode::WorkerCrashed,+ "perception worker exited before completing its response",+ true,+ Some(cause.to_string()),+ )+}++fn cancelled_error() -> VisualParseError {+ error(+ VisualParseErrorCode::WorkerCancelled,+ "perception worker request was cancelled",+ true,+ None,+ )+}++fn timeout_error(phase: &str) -> VisualParseError {+ error(+ VisualParseErrorCode::Timeout,+ format!("the perception worker exceeded its {phase} deadline"),+ true,+ None,+ )+}++pub(crate) fn error(+ code: VisualParseErrorCode,+ message: impl Into<String>,+ retryable: bool,+ detail: Option<String>,+) -> VisualParseError {+ VisualParseError {+ code,+ message: message.into(),+ retryable,+ detail,+ }+}++#[cfg(all(test, unix))]+#[derive(Clone, Debug)]+pub(crate) struct FixturePythonConfig {+ pub(crate) interpreter: PathBuf,+ pub(crate) readable_roots: Vec<PathBuf>,+ pub(crate) executable_paths: Vec<PathBuf>,+}++#[cfg(all(test, unix))]+pub(crate) fn fixture_python_config() -> Result<FixturePythonConfig, String> {+ fixture_python_config_from(+ std::env::var_os("CUA_TEST_PYTHON"),+ std::env::var_os("CUA_TEST_PYTHON_READ_ROOTS"),+ std::env::var_os("CUA_TEST_PYTHON_DYNAMIC_LINKER"),+ std::path::Path::new("/nix/store"),+ )+}++#[cfg(all(test, unix))]+fn fixture_python_config_from(+ configured_interpreter: Option<std::ffi::OsString>,+ configured_read_roots: Option<std::ffi::OsString>,+ configured_dynamic_linker: Option<std::ffi::OsString>,+ trusted_store_root: &std::path::Path,+) -> Result<FixturePythonConfig, String> {+ if let Some(interpreter) = configured_interpreter {+ let interpreter = PathBuf::from(interpreter);+ let resolved_interpreter = validate_fixture_path(&interpreter, true)?;+ let resolved_store_root = std::fs::canonicalize(trusted_store_root).ok();+ let is_nix_interpreter = interpreter.starts_with(trusted_store_root)+ || resolved_store_root+ .as_ref()+ .is_some_and(|root| resolved_interpreter.starts_with(root));++ if is_nix_interpreter {+ let configured_store_root = trusted_store_root;+ let trusted_store_root = resolved_store_root+ .ok_or_else(|| "trusted test store root is unavailable".to_owned())?;+ if !interpreter.starts_with(configured_store_root) {+ return Err("CUA_TEST_PYTHON must be inside the trusted Nix store".into());+ }+ if !resolved_interpreter.starts_with(&trusted_store_root) {+ return Err("CUA_TEST_PYTHON must resolve inside the trusted Nix store".into());+ }+ let configured_read_roots = configured_read_roots.ok_or_else(|| {+ "CUA_TEST_PYTHON_READ_ROOTS is required for a Nix store interpreter".to_owned()+ })?;+ let mut readable_roots = Vec::new();+ for root in std::env::split_paths(&configured_read_roots) {+ if root == configured_store_root || !root.starts_with(configured_store_root) {+ return Err(+ "CUA_TEST_PYTHON_READ_ROOTS may contain only trusted Nix store paths"+ .into(),+ );+ }+ let resolved = validate_fixture_path(&root, false)?;+ if resolved == trusted_store_root || !resolved.starts_with(&trusted_store_root) {+ return Err(+ "CUA_TEST_PYTHON_READ_ROOTS may contain only trusted Nix store paths"+ .into(),+ );+ }+ readable_roots.push(resolved);+ }+ if readable_roots.is_empty() {+ return Err("CUA_TEST_PYTHON_READ_ROOTS must not be empty".into());+ }+ readable_roots.sort();+ readable_roots.dedup();+ let configured_dynamic_linker = configured_dynamic_linker.ok_or_else(|| {+ "CUA_TEST_PYTHON_DYNAMIC_LINKER is required for a Nix store interpreter".to_owned()+ })?;+ let dynamic_linker = PathBuf::from(configured_dynamic_linker);+ if dynamic_linker == configured_store_root+ || !dynamic_linker.starts_with(configured_store_root)+ {+ return Err(+ "CUA_TEST_PYTHON_DYNAMIC_LINKER must be inside the trusted Nix store".into(),+ );+ }+ let resolved_dynamic_linker = validate_fixture_path(&dynamic_linker, true)?;+ if resolved_dynamic_linker == trusted_store_root+ || !resolved_dynamic_linker.starts_with(&trusted_store_root)+ {+ return Err(+ "CUA_TEST_PYTHON_DYNAMIC_LINKER must resolve inside the trusted Nix store"+ .into(),+ );+ }+ if !readable_roots+ .iter()+ .any(|root| resolved_dynamic_linker.starts_with(root))+ {+ return Err(+ "CUA_TEST_PYTHON_DYNAMIC_LINKER must resolve inside a configured Nix closure root"+ .into(),+ );+ }+ let mut executable_paths = vec![resolved_interpreter, resolved_dynamic_linker];+ executable_paths.sort();+ executable_paths.dedup();+ return Ok(FixturePythonConfig {+ interpreter: interpreter.clone(),+ readable_roots,+ executable_paths,+ });+ }++ if configured_read_roots.is_some() || configured_dynamic_linker.is_some() {+ return Err(+ "Nix fixture path configuration is supported only for a Nix store interpreter"+ .into(),+ );+ }+ return Ok(FixturePythonConfig {+ interpreter: interpreter.clone(),+ readable_roots: host_python_readable_roots(),+ executable_paths: vec![resolved_interpreter],+ });+ }+ if configured_read_roots.is_some() || configured_dynamic_linker.is_some() {+ return Err("Nix fixture path configuration requires CUA_TEST_PYTHON".into());+ }++ #[cfg(target_os = "macos")]+ let candidates = [+ "/Applications/Xcode.app/Contents/Developer/usr/bin/python3",+ "/usr/bin/python3",+ "/usr/local/bin/python3",+ ];+ #[cfg(not(target_os = "macos"))]+ let candidates = ["/usr/bin/python3", "/usr/local/bin/python3"];+ let interpreter = candidates+ .into_iter()+ .map(PathBuf::from)+ .find(|candidate| validate_fixture_path(candidate, true).is_ok())+ .ok_or_else(|| "no trusted fixture python interpreter is installed".to_owned())?;+ let resolved_interpreter = validate_fixture_path(&interpreter, true)?;+ let readable_roots = host_python_readable_roots();+ #[cfg(target_os = "macos")]+ let executable_paths = {+ let mut paths: Vec<_> = macos_fixture_executable_candidates(&interpreter)+ .into_iter()+ .filter_map(|path| validate_fixture_path(&path, true).ok())+ .collect();+ paths.push(resolved_interpreter);+ paths.sort();+ paths.dedup();+ paths+ };+ #[cfg(not(target_os = "macos"))]+ let executable_paths = vec![resolved_interpreter];+ Ok(FixturePythonConfig {+ interpreter,+ readable_roots,+ executable_paths,+ })+}++#[cfg(all(test, unix, target_os = "macos"))]+fn macos_fixture_executable_candidates(interpreter: &std::path::Path) -> Vec<PathBuf> {+ vec![+ interpreter.to_path_buf(),+ PathBuf::from("/usr/bin/env"),+ PathBuf::from("/usr/bin/python3"),+ PathBuf::from("/usr/local/bin/python3"),+ PathBuf::from("/Applications/Xcode.app/Contents/Developer/usr/bin/python3"),+ PathBuf::from("/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/bin/python3.9"),+ PathBuf::from("/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/Python3"),+ PathBuf::from("/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/Resources/Python.app/Contents/MacOS/Python"),+ ]+}++#[cfg(all(test, unix))]+fn host_python_readable_roots() -> Vec<PathBuf> {+ [+ "/usr",+ "/bin",+ "/lib",+ "/lib64",+ "/etc",+ "/opt",+ "/System",+ "/Library",+ "/private/var/db",+ "/private/var/select",+ "/Applications/Xcode.app",+ ]+ .into_iter()+ .map(PathBuf::from)+ .filter(|path| path.is_dir())+ .collect()+}++#[cfg(all(test, unix))]+fn validate_fixture_path(path: &std::path::Path, file: bool) -> Result<PathBuf, String> {+ if !path.is_absolute() {+ return Err("test fixture paths must be absolute".into());+ }+ let resolved = std::fs::canonicalize(path)+ .map_err(|error| format!("test fixture path could not be resolved: {error}"))?;+ if (file && !resolved.is_file()) || (!file && !resolved.is_dir()) {+ return Err("test fixture path has the wrong file type".into());+ }+ Ok(resolved)+}++#[cfg(all(test, unix))]+mod tests {+ use super::*;+ use std::os::unix::fs::PermissionsExt;++ fn with_fixture_interpreter(script: &str) -> String {+ let interpreter = fixture_python_interpreter();+ script.replacen(+ "#!/usr/bin/env python3",+ &format!("#!{}", interpreter.display()),+ 1,+ )+ }++ fn fixture_python_interpreter() -> PathBuf {+ fixture_python_config().unwrap().interpreter+ }++ fn fixture_worker(+ mode: &str,+ counter: Option<&std::path::Path>,+ ) -> (tempfile::TempDir, PathBuf) {+ let directory = tempfile::tempdir().unwrap();+ let path = directory.path().join("fixture-worker.py");+ let script = r#"#!/usr/bin/env python3+import base64, json, os, struct, sys, time++mode = sys.argv[1]+counter = sys.argv[2] if len(sys.argv) > 2 else None++def read_frame():+ prefix = sys.stdin.buffer.read(4)+ if len(prefix) != 4:+ sys.exit(2)+ size = struct.unpack('>I', prefix)[0]+ payload = sys.stdin.buffer.read(size)+ if len(payload) != size:+ sys.exit(3)+ return json.loads(payload)++def write_frame(value):+ payload = json.dumps(value, separators=(',', ':')).encode()+ sys.stdout.buffer.write(struct.pack('>I', len(payload)) + payload)+ sys.stdout.buffer.flush()++health = read_frame()+write_frame({'protocol':'cua-perception/1','request_id':health['request_id'],'status':'ok','result':{'ready':True,'protocol':'cua-perception/1'}})+request = read_frame()+if counter:+ with open(counter, 'a', encoding='utf-8') as handle:+ handle.write('parse\n')+if mode == 'hang':+ time.sleep(60)+elif mode == 'crash':+ sys.exit(9)+elif mode == 'oversized':+ sys.stdout.buffer.write(struct.pack('>I', 1024 * 1024))+ sys.stdout.buffer.flush()+elif mode == 'mismatch':+ write_frame({'protocol':'cua-perception/1','request_id':'wrong','status':'ok','result':{}})+else:+ image = request['params']['image']+ expected = base64.b64encode(bytes([1, 2, 3, 4])).decode()+ if image['data_base64'] != expected or image['byte_length'] != 4:+ write_frame({'protocol':'cua-perception/1','request_id':request['request_id'],'status':'error','error':{'code':'invalid_image','message':'bytes changed'}})+ else:+ write_frame({'protocol':'cua-perception/1','request_id':request['request_id'],'status':'ok','result':{'regions':[],'runtime':'fixture'}})+"#;+ std::fs::write(&path, with_fixture_interpreter(script)).unwrap();+ let mut permissions = std::fs::metadata(&path).unwrap().permissions();+ permissions.set_mode(0o700);+ std::fs::set_permissions(&path, permissions).unwrap();+ let mut args = vec![mode.to_owned()];+ if let Some(counter) = counter {+ args.push(counter.display().to_string());+ }+ // Store arguments beside the script for the caller to recover.+ std::fs::write(+ directory.path().join("args.json"),+ serde_json::to_vec(&args).unwrap(),+ )+ .unwrap();+ (directory, path)+ }++ fn client(+ directory: &tempfile::TempDir,+ path: PathBuf,+ timeout: Duration,+ maximum: usize,+ ) -> PerceptionClient {+ let args: Vec<String> =+ serde_json::from_slice(&std::fs::read(directory.path().join("args.json")).unwrap())+ .unwrap();+ PerceptionClient::new(PerceptionWorkerConfig {+ executable: path,+ containment: fixture_limits(&args),+ args,+ request_timeout: timeout,+ max_frame_bytes: maximum,+ warm_worker: None,+ expected_extension_identity: None,+ installed: false,+ windows_acl_lease_path: None,+ })+ .unwrap()+ }++ fn warm_client(+ directory: &tempfile::TempDir,+ path: PathBuf,+ policy: WarmWorkerPolicy,+ ) -> PerceptionClient {+ let args: Vec<String> =+ serde_json::from_slice(&std::fs::read(directory.path().join("args.json")).unwrap())+ .unwrap();+ PerceptionClient::new(PerceptionWorkerConfig {+ executable: path,+ containment: fixture_limits(&args),+ args,+ request_timeout: Duration::from_secs(10),+ max_frame_bytes: 1024 * 1024,+ warm_worker: Some(policy),+ expected_extension_identity: None,+ installed: false,+ windows_acl_lease_path: None,+ })+ .unwrap()+ }++ /// Production limits widened by exactly what a scripted fixture needs and+ /// nothing else. Production callers leave both lists empty, which is what+ /// the enforcement probes below rely on: every path they are refused is+ /// refused under a production-shaped sandbox too.+ fn fixture_limits(args: &[String]) -> ContainmentLimits {+ ContainmentLimits {+ additional_writable_paths: evidence_paths(args),+ additional_readable_paths: interpreter_read_paths(),+ additional_executable_paths: interpreter_executable_paths(),+ ..ContainmentLimits::default()+ }+ }++ /// The fixture workers record their evidence outside their private working+ /// directory, so the sandbox must be widened to the directories that hold+ /// it. Production callers leave this list empty.+ fn evidence_paths(args: &[String]) -> Vec<PathBuf> {+ args.iter()+ .map(PathBuf::from)+ .filter(|path| path.is_absolute())+ .filter_map(|path| path.parent().map(std::path::Path::to_path_buf))+ .collect()+ }++ /// A shipped worker is a self-contained native binary and reads only its+ /// own bundle. The fixtures are Python scripts, so the host interpreter's+ /// directories are opted in explicitly rather than by widening the derived+ /// allowlist for everyone.+ fn interpreter_read_paths() -> Vec<PathBuf> {+ fixture_python_config().unwrap().readable_roots+ }++ fn interpreter_executable_paths() -> Vec<PathBuf> {+ fixture_python_config().unwrap().executable_paths+ }++ #[test]+ fn fixture_interpreter_uses_an_absolute_containment_grant() {+ let interpreter = fixture_python_interpreter();+ assert!(interpreter.is_absolute());+ assert!(+ interpreter_executable_paths().contains(&std::fs::canonicalize(interpreter).unwrap())+ );+ }++ #[cfg(target_os = "macos")]+ #[test]+ fn fallback_fixture_grants_are_canonical_sorted_and_unique() {+ let config =+ fixture_python_config_from(None, None, None, std::path::Path::new("/nix/store"))+ .unwrap();+ let mut expected: Vec<_> = macos_fixture_executable_candidates(&config.interpreter)+ .into_iter()+ .filter_map(|path| validate_fixture_path(&path, true).ok())+ .collect();+ expected.push(validate_fixture_path(&config.interpreter, true).unwrap());+ expected.sort();+ expected.dedup();++ assert_eq!(config.executable_paths, expected);+ assert!(config+ .executable_paths+ .windows(2)+ .all(|pair| pair[0] < pair[1]));+ }++ #[test]+ fn fixture_python_config_accepts_validated_non_nix_override() {+ let temp = tempfile::tempdir().unwrap();+ let store = temp.path().join("store");+ let outside = temp.path().join("outside");+ std::fs::create_dir(&store).unwrap();+ std::fs::create_dir(&outside).unwrap();+ let outside_interpreter = outside.join("python3");+ std::fs::write(&outside_interpreter, b"fixture").unwrap();++ assert!(fixture_python_config_from(Some("python3".into()), None, None, &store).is_err());+ let config = fixture_python_config_from(+ Some(outside_interpreter.clone().into_os_string()),+ None,+ None,+ &store,+ )+ .unwrap();+ assert_eq!(config.interpreter, outside_interpreter);+ assert_eq!(+ config.executable_paths,+ vec![std::fs::canonicalize(&config.interpreter).unwrap()]+ );+ assert!(fixture_python_config_from(+ Some(config.interpreter.clone().into_os_string()),+ Some(outside.clone().into_os_string()),+ None,+ &store,+ )+ .is_err());+ assert!(fixture_python_config_from(+ Some(config.interpreter.into_os_string()),+ None,+ Some(outside_interpreter.into_os_string()),+ &store,+ )+ .is_err());+ assert!(fixture_python_config_from(+ None,+ None,+ Some(outside.join("python3").into_os_string()),+ &store,+ )+ .is_err());+ }++ #[test]+ fn fixture_python_config_rejects_untrusted_nix_closure_roots() {+ let temp = tempfile::tempdir().unwrap();+ let store = temp.path().join("store");+ let package = store.join("python");+ let bin = package.join("bin");+ std::fs::create_dir_all(&bin).unwrap();+ let interpreter = bin.join("python3");+ std::fs::write(&interpreter, b"fixture").unwrap();+ let outside = temp.path().join("outside");+ std::fs::create_dir(&outside).unwrap();++ assert!(fixture_python_config_from(+ Some(interpreter.clone().into_os_string()),+ None,+ None,+ &store,+ )+ .is_err());+ assert!(fixture_python_config_from(+ Some(interpreter.into_os_string()),+ Some(outside.into_os_string()),+ None,+ &store,+ )+ .is_err());+ }++ #[test]+ fn fixture_python_config_grants_only_exact_closure_roots() {+ let temp = tempfile::tempdir().unwrap();+ let store = temp.path().join("store");+ let python = store.join("python");+ let dependency = store.join("dependency");+ std::fs::create_dir_all(python.join("bin")).unwrap();+ std::fs::create_dir_all(dependency.join("lib")).unwrap();+ let interpreter = python.join("bin/python3");+ let loader = dependency.join("lib/ld-linux.so");+ std::fs::write(&interpreter, b"fixture").unwrap();+ std::fs::write(&loader, b"fixture").unwrap();+ let roots = std::env::join_paths([python.clone(), dependency.clone()]).unwrap();+ let config = fixture_python_config_from(+ Some(interpreter.clone().into_os_string()),+ Some(roots),+ Some(loader.clone().into_os_string()),+ &store,+ )+ .unwrap();+ assert_eq!(config.interpreter, interpreter);+ assert_eq!(+ config.executable_paths,+ vec![+ std::fs::canonicalize(loader).unwrap(),+ std::fs::canonicalize(&interpreter).unwrap(),+ ]+ );+ assert_eq!(+ config.readable_roots,+ vec![+ std::fs::canonicalize(dependency).unwrap(),+ std::fs::canonicalize(python).unwrap(),+ ]+ );+ assert!(!config+ .readable_roots+ .contains(&std::fs::canonicalize(&store).unwrap()));+ assert!(fixture_python_config_from(+ Some(config.interpreter.into_os_string()),+ Some(store.clone().into_os_string()),+ Some(store.join("dependency/lib/ld-linux.so").into_os_string()),+ &store,+ )+ .is_err());+ }++ #[test]+ fn fixture_python_config_rejects_dynamic_linker_outside_configured_closure_roots() {+ let temp = tempfile::tempdir().unwrap();+ let store = temp.path().join("store");+ let python = store.join("python");+ let dependency = store.join("dependency");+ let outside = store.join("outside");+ std::fs::create_dir_all(python.join("bin")).unwrap();+ std::fs::create_dir_all(dependency.join("lib")).unwrap();+ std::fs::create_dir_all(outside.join("lib")).unwrap();+ let interpreter = python.join("bin/python3");+ let loader = dependency.join("lib/ld-linux.so");+ let untrusted = outside.join("lib/arbitrary");+ let escaped = dependency.join("lib/escaped-loader");+ std::fs::write(&interpreter, b"fixture").unwrap();+ std::fs::write(&loader, b"fixture").unwrap();+ std::fs::write(&untrusted, b"fixture").unwrap();+ std::os::unix::fs::symlink(&untrusted, &escaped).unwrap();+ let roots = std::env::join_paths([python, dependency]).unwrap();++ assert!(fixture_python_config_from(+ Some(interpreter.clone().into_os_string()),+ Some(roots.clone()),+ Some(escaped.into_os_string()),+ &store,+ )+ .is_err());+ assert!(fixture_python_config_from(+ Some(interpreter.into_os_string()),+ Some(roots),+ Some(untrusted.into_os_string()),+ &store,+ )+ .is_err());+ }++ #[test]+ fn fixture_python_config_rejects_dynamic_linker_configured_outside_store() {+ let temp = tempfile::tempdir().unwrap();+ let store = temp.path().join("store");+ let python = store.join("python");+ let dependency = store.join("dependency");+ let outside = temp.path().join("outside");+ std::fs::create_dir_all(python.join("bin")).unwrap();+ std::fs::create_dir_all(dependency.join("lib")).unwrap();+ std::fs::create_dir_all(&outside).unwrap();+ let interpreter = python.join("bin/python3");+ let loader = dependency.join("lib/ld-linux.so");+ let configured_outside = outside.join("ld-linux.so");+ std::fs::write(&interpreter, b"fixture").unwrap();+ std::fs::write(&loader, b"fixture").unwrap();+ std::os::unix::fs::symlink(&loader, &configured_outside).unwrap();+ let roots = std::env::join_paths([python, dependency]).unwrap();++ assert!(fixture_python_config_from(+ Some(interpreter.into_os_string()),+ Some(roots),+ Some(configured_outside.into_os_string()),+ &store,+ )+ .is_err());+ }++ fn warm_fixture_worker(+ counter: &std::path::Path,+ pid_file: &std::path::Path,+ ) -> (tempfile::TempDir, PathBuf) {+ let directory = tempfile::tempdir().unwrap();+ let path = directory.path().join("warm-worker.py");+ let script = r#"#!/usr/bin/env python3+import json, os, struct, sys, time+counter, pid_file = sys.argv[1], sys.argv[2]+with open(pid_file, 'a', encoding='utf-8') as handle: handle.write(str(os.getpid()) + '\n')+def read_frame():+ p=sys.stdin.buffer.read(4)+ if not p: return None+ if len(p)!=4: sys.exit(2)+ n=struct.unpack('>I',p)[0]; d=sys.stdin.buffer.read(n)+ if len(d)!=n: sys.exit(3)+ return json.loads(d)+def write(v):+ p=json.dumps(v,separators=(',',':')).encode(); sys.stdout.buffer.write(struct.pack('>I',len(p))+p); sys.stdout.buffer.flush()+h=read_frame(); write({'protocol':'cua-perception/1','request_id':h['request_id'],'status':'ok','result':{'ready':True,'protocol':'cua-perception/1'}})+while True:+ r=read_frame()+ if r is None: sys.exit(0)+ capture=r['params']['capture_id']+ with open(counter,'a',encoding='utf-8') as handle: handle.write(capture+'\n')+ if capture == 'crash': sys.exit(9)+ if capture == 'hang': time.sleep(60)+ write({'protocol':'cua-perception/1','request_id':r['request_id'],'status':'ok','result':{'capture':capture,'pid':os.getpid(),'regions':[]}})+"#;+ std::fs::write(&path, with_fixture_interpreter(script)).unwrap();+ let mut permissions = std::fs::metadata(&path).unwrap().permissions();+ permissions.set_mode(0o700);+ std::fs::set_permissions(&path, permissions).unwrap();+ let args = vec![+ counter.display().to_string(),+ pid_file.display().to_string(),+ ];+ std::fs::write(+ directory.path().join("args.json"),+ serde_json::to_vec(&args).unwrap(),+ )+ .unwrap();+ (directory, path)+ }++ /// Reports what the containment layer actually denied. The probe takes its+ /// targets from `capture_id` rather than from argv, because an absolute+ /// path argument is part of the worker's launch configuration and would+ /// legitimately widen the read allowlist.+ fn containment_probe_worker() -> (tempfile::TempDir, PathBuf) {+ let directory = tempfile::tempdir().unwrap();+ let path = directory.path().join("containment-probe.py");+ let script = r#"#!/usr/bin/env python3+import errno, json, os, socket, struct, sys++def read_frame():+ prefix = sys.stdin.buffer.read(4)+ if len(prefix) != 4:+ sys.exit(2)+ size = struct.unpack('>I', prefix)[0]+ payload = sys.stdin.buffer.read(size)+ if len(payload) != size:+ sys.exit(3)+ return json.loads(payload)++def write_frame(value):+ payload = json.dumps(value, separators=(',', ':')).encode()+ sys.stdout.buffer.write(struct.pack('>I', len(payload)) + payload)+ sys.stdout.buffer.flush()++def name(failure):+ return errno.errorcode.get(failure.errno, str(failure.errno))++def probe_network():+ try:+ endpoint = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ except OSError as failure:+ return name(failure)+ try:+ endpoint.settimeout(2)+ endpoint.connect(('127.0.0.1', 9))+ except OSError as failure:+ return name(failure)+ finally:+ endpoint.close()+ return 'allowed'++def probe_local_socket(path):+ try:+ endpoint = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ except OSError as failure:+ return name(failure)+ try:+ endpoint.settimeout(2)+ endpoint.connect(path)+ except OSError as failure:+ return name(failure)+ finally:+ endpoint.close()+ return 'allowed'++def probe_read(path):+ try:+ with open(path, 'rb') as handle:+ handle.read(1)+ except OSError as failure:+ return name(failure)+ return 'allowed'++def probe_list(path):+ try:+ os.listdir(path)+ except OSError as failure:+ return name(failure)+ return 'allowed'++def probe_write(path):+ try:+ with open(path, 'w', encoding='utf-8') as handle:+ handle.write('probe')+ except OSError as failure:+ return name(failure)+ os.unlink(path)+ return 'allowed'++def probe_fork():+ try:+ child = os.fork()+ except OSError as failure:+ return name(failure)+ if child == 0:+ os._exit(0)+ os.waitpid(child, 0)+ return 'allowed'++def probe_process_memory():+ if not sys.platform.startswith('linux'):+ return 'unavailable'+ try:+ import ctypes+ libc = ctypes.CDLL(None, use_errno=True)+ # PTRACE_ATTACH against the supervising Driver process.+ if libc.ptrace(16, os.getppid(), 0, 0) == 0:+ return 'allowed'+ return errno.errorcode.get(ctypes.get_errno(), str(ctypes.get_errno()))+ except Exception as failure:+ return type(failure).__name__++health = read_frame()+write_frame({'protocol':'cua-perception/1','request_id':health['request_id'],'status':'ok','result':{'ready':True,'protocol':'cua-perception/1'}})+request = read_frame()+targets = json.loads(request['params']['capture_id'])+write_frame({'protocol':'cua-perception/1','request_id':request['request_id'],'status':'ok','result':{+ 'network': probe_network(),+ 'local_socket': probe_local_socket(targets['socket']),+ 'secret_read': probe_read(targets['secret']),+ 'secret_list': probe_list(os.path.dirname(targets['secret'])),+ 'fork': probe_fork(),+ 'process_memory': probe_process_memory(),+ 'outside_write': probe_write(targets['outside']),+ 'inside_write': probe_write(os.path.join(os.getcwd(), 'probe')),+}})+"#;+ std::fs::write(&path, with_fixture_interpreter(script)).unwrap();+ let mut permissions = std::fs::metadata(&path).unwrap().permissions();+ permissions.set_mode(0o700);+ std::fs::set_permissions(&path, permissions).unwrap();+ std::fs::write(directory.path().join("args.json"), b"[]").unwrap();+ (directory, path)+ }++ /// Anything the worker is refused here is refused under a production+ /// sandbox too: the probe runs with no extra writable path and only the+ /// interpreter's own read roots.+ #[tokio::test]+ async fn contained_worker_is_denied_every_route_off_its_own_bundle() {+ let evidence = tempfile::Builder::new()+ .prefix("cua-perception-secrets-")+ .tempdir()+ .unwrap();+ let secret = evidence.path().join("credentials");+ std::fs::write(&secret, b"token").unwrap();+ let socket = evidence.path().join("desktop.sock");+ let listener = std::os::unix::net::UnixListener::bind(&socket).unwrap();+ let targets = serde_json::json!({+ "secret": secret.display().to_string(),+ "socket": socket.display().to_string(),+ "outside": evidence.path().join("escape").display().to_string(),+ })+ .to_string();++ let (directory, worker) = containment_probe_worker();+ let result = client(&directory, worker, Duration::from_secs(20), 1024 * 1024)+ .parse(+ &targets,+ 2,+ 2,+ &[1, 2, 3, 4],+ &PerceptionCancellation::default(),+ )+ .await+ .unwrap();+ drop(listener);++ // A refused connection would mean the sandbox let the syscall through,+ // so "connection refused" is not an acceptable outcome for any of these.+ let denied = ["EPERM", "EACCES", "EAFNOSUPPORT"];+ for (probe, allowed) in [+ ("network", &denied[..]),+ ("local_socket", &denied[..]),+ ("secret_read", &denied[..2]),+ ("secret_list", &denied[..2]),+ ("outside_write", &denied[..2]),+ ] {+ let observed = result[probe].as_str().unwrap_or_default();+ assert!(+ allowed.contains(&observed),+ "the {probe} probe was not denied: {result}"+ );+ }+ assert!(+ matches!(result["fork"].as_str(), Some("EPERM" | "EACCES" | "EAGAIN")),+ "worker process creation was not denied: {result}"+ );+ assert!(+ matches!(+ result["process_memory"].as_str(),+ Some("unavailable" | "EPERM" | "EACCES" | "ENOSYS")+ ),+ "the worker could attach to the Driver process: {result}"+ );+ assert_eq!(result["inside_write"], "allowed");+ }++ #[tokio::test]+ async fn a_bundle_directory_too_broad_to_grant_fails_before_the_worker_runs() {+ // `/usr/bin` is a shared system directory: granting reads beneath it+ // would hand the worker every other program on the machine, so the+ // launch must fail closed instead.+ let directory = tempfile::tempdir().unwrap();+ std::fs::write(directory.path().join("args.json"), b"[]").unwrap();+ let failure = client(+ &directory,+ PathBuf::from("/usr/bin/true"),+ Duration::from_secs(10),+ 1024 * 1024,+ )+ .parse(+ "capture-test",+ 2,+ 2,+ &[1, 2, 3, 4],+ &PerceptionCancellation::default(),+ )+ .await+ .unwrap_err();+ assert_eq!(failure.code, VisualParseErrorCode::WorkerLaunchFailed);+ assert!(!failure.retryable);+ }++ #[tokio::test]+ async fn a_missing_opted_in_sandbox_path_fails_closed() {+ let directory = tempfile::tempdir().unwrap();+ let (fixture, worker) = fixture_worker("ok", None);+ let client = PerceptionClient::new(PerceptionWorkerConfig {+ executable: worker,+ containment: ContainmentLimits {+ additional_readable_paths: vec![directory+ .path()+ .join("this-directory-does-not-exist")],+ ..ContainmentLimits::default()+ },+ args: Vec::new(),+ request_timeout: Duration::from_secs(10),+ max_frame_bytes: 1024 * 1024,+ warm_worker: None,+ expected_extension_identity: None,+ installed: false,+ windows_acl_lease_path: None,+ })+ .unwrap();+ let failure = client+ .parse(+ "capture-test",+ 2,+ 2,+ &[1, 2, 3, 4],+ &PerceptionCancellation::default(),+ )+ .await+ .unwrap_err();+ assert_eq!(failure.code, VisualParseErrorCode::WorkerLaunchFailed);+ drop(fixture);+ }++ #[test]+ fn an_installed_extension_starts_cold() {+ // Warm reuse keeps a worker — and the screenshot it was handed — alive+ // between requests, so it stays behind an explicit opt-in until the+ // per-platform cleanup certification passes.+ assert!(PerceptionWorkerConfig::installed("/opt/cua/worker")+ .warm_worker+ .is_none());+ assert!(PerceptionWorkerConfig::installed("/opt/cua/worker")+ .with_bounded_reuse(WarmWorkerPolicy::default())+ .warm_worker+ .is_some());+ let failure = PerceptionClient::new(PerceptionWorkerConfig::installed("/opt/cua/worker"))+ .err()+ .expect("unbound installed workers must be rejected");+ assert_eq!(failure.code, VisualParseErrorCode::ArtifactInvalid);+ }++ #[test]+ fn default_frame_limit_covers_the_default_capture_registry_limit() {+ let encoded_capture_bytes =+ ((crate::capture_registry::DEFAULT_MAX_CAPTURE_BYTES + 2) / 3) * 4;+ assert!(DEFAULT_MAX_FRAME_BYTES >= encoded_capture_bytes + 64 * 1024);+ }++ #[test]+ fn installed_extension_identity_is_launch_bound_and_verified() {+ let config = PerceptionWorkerConfig::installed_with_identity(+ "/opt/cua/worker",+ "cua-perception",+ "0.1.0",+ )+ .with_windows_acl_lease_path("/opt/cua/.locks/cua-perception.runtime-acl.lock");+ assert_eq!(+ config.args,+ [+ "--extension-id",+ "cua-perception",+ "--extension-version",+ "0.1.0",+ ]+ );+ let expected = config.expected_extension_identity.as_ref();+ assert_eq!(+ config.containment_limits().windows_acl_lease_path,+ Some(PathBuf::from(+ "/opt/cua/.locks/cua-perception.runtime-acl.lock"+ ))+ );+ assert!(verify_expected_extension_identity(+ &json!({+ "identity": {+ "extension": {"id": "cua-perception", "version": "0.1.0"}+ }+ }),+ expected,+ )+ .is_ok());++ let failure = verify_expected_extension_identity(+ &json!({+ "identity": {+ "extension": {"id": "cua-perception", "version": "0.28.2"}+ }+ }),+ expected,+ )+ .unwrap_err();+ assert_eq!(failure.code, VisualParseErrorCode::ArtifactInvalid);+ }++ #[tokio::test]+ async fn installed_worker_health_must_echo_the_bound_identity() {+ let evidence = tempfile::tempdir().unwrap();+ let counter = evidence.path().join("parse-count");+ let (directory, worker) = fixture_worker("ok", Some(&counter));+ let args: Vec<String> =+ serde_json::from_slice(&std::fs::read(directory.path().join("args.json")).unwrap())+ .unwrap();+ let client = PerceptionClient::new(PerceptionWorkerConfig {+ executable: worker,+ containment: fixture_limits(&args),+ args,+ request_timeout: Duration::from_secs(10),+ max_frame_bytes: 1024 * 1024,+ warm_worker: None,+ expected_extension_identity: Some(ExpectedExtensionIdentity {+ id: "cua-perception".into(),+ version: "0.1.0".into(),+ }),+ installed: true,+ windows_acl_lease_path: None,+ })+ .unwrap();+ let failure = client+ .parse(+ "capture-test",+ 2,+ 2,+ &[1, 2, 3, 4],+ &PerceptionCancellation::default(),+ )+ .await+ .unwrap_err();+ assert_eq!(failure.code, VisualParseErrorCode::ArtifactInvalid);+ assert!(+ !counter.exists(),+ "parse must not run after an unbound health response"+ );+ }++ #[tokio::test]+ async fn fixture_worker_receives_exact_bytes_and_returns_once() {+ let counter_directory = tempfile::tempdir().unwrap();+ let counter = counter_directory.path().join("count");+ let (directory, worker) = fixture_worker("ok", Some(&counter));+ let result = client(&directory, worker, Duration::from_secs(10), 1024 * 1024)+ .parse(+ "capture-test",+ 2,+ 2,+ &[1, 2, 3, 4],+ &PerceptionCancellation::default(),+ )+ .await+ .unwrap();+ assert_eq!(result["runtime"], "fixture");+ assert_eq!(std::fs::read_to_string(counter).unwrap(), "parse\n");+ }++ #[tokio::test]+ async fn malformed_response_is_not_replayed() {+ let counter_directory = tempfile::tempdir().unwrap();+ let counter = counter_directory.path().join("count");+ let (directory, worker) = fixture_worker("mismatch", Some(&counter));+ let failure = client(&directory, worker, Duration::from_secs(10), 1024 * 1024)+ .parse(+ "capture-test",+ 2,+ 2,+ &[1, 2, 3, 4],+ &PerceptionCancellation::default(),+ )+ .await+ .unwrap_err();+ assert_eq!(failure.code, VisualParseErrorCode::InvalidFrame);+ assert_eq!(std::fs::read_to_string(counter).unwrap(), "parse\n");+ }++ #[tokio::test]+ async fn timeout_crash_oversized_frame_and_cancellation_are_distinct() {+ let (directory, worker) = fixture_worker("hang", None);+ let failure = client(&directory, worker, Duration::from_millis(200), 1024 * 1024)+ .parse(+ "capture-test",+ 2,+ 2,+ &[1, 2, 3, 4],+ &PerceptionCancellation::default(),+ )+ .await+ .unwrap_err();+ assert_eq!(failure.code, VisualParseErrorCode::Timeout);++ let (directory, worker) = fixture_worker("crash", None);+ let failure = client(&directory, worker, Duration::from_secs(10), 1024 * 1024)+ .parse(+ "capture-test",+ 2,+ 2,+ &[1, 2, 3, 4],+ &PerceptionCancellation::default(),+ )+ .await+ .unwrap_err();+ assert_eq!(failure.code, VisualParseErrorCode::WorkerCrashed);++ let (directory, worker) = fixture_worker("oversized", None);+ let failure = client(&directory, worker, Duration::from_secs(10), 128)+ .parse(+ "capture-test",+ 2,+ 2,+ &[1, 2, 3, 4],+ &PerceptionCancellation::default(),+ )+ .await+ .unwrap_err();+ assert_eq!(failure.code, VisualParseErrorCode::InvalidFrame);++ let cancellation = PerceptionCancellation::default();+ cancellation.cancel();+ let failure = PerceptionClient::unavailable()+ .parse("capture-test", 2, 2, &[1, 2, 3, 4], &cancellation)+ .await+ .unwrap_err();+ assert_eq!(failure.code, VisualParseErrorCode::NotInstalled);++ let (directory, worker) = fixture_worker("hang", None);+ let client = client(&directory, worker, Duration::from_secs(2), 1024 * 1024);+ let cancellation = PerceptionCancellation::default();+ let trigger = cancellation.clone();+ tokio::spawn(async move {+ tokio::time::sleep(Duration::from_millis(25)).await;+ trigger.cancel();+ });+ let failure = client+ .parse("capture-test", 2, 2, &[1, 2, 3, 4], &cancellation)+ .await+ .unwrap_err();+ assert_eq!(failure.code, VisualParseErrorCode::WorkerCancelled);+ }++ #[tokio::test]+ async fn warm_worker_reuses_one_process_then_idle_ttl_reaps_it() {+ let evidence = tempfile::tempdir().unwrap();+ let counter = evidence.path().join("counter");+ let pids = evidence.path().join("pids");+ let (directory, worker) = warm_fixture_worker(&counter, &pids);+ let client = warm_client(+ &directory,+ worker,+ WarmWorkerPolicy {+ startup_timeout: Duration::from_secs(10),+ inference_timeout: Duration::from_secs(2),+ shutdown_timeout: Duration::from_millis(100),+ idle_ttl: Duration::from_millis(100),+ },+ );+ for capture in ["one", "two"] {+ client+ .parse(capture, 1, 1, &[1, 2, 3, 4], &Default::default())+ .await+ .unwrap();+ }+ assert_eq!(std::fs::read_to_string(&pids).unwrap().lines().count(), 1);+ tokio::time::sleep(Duration::from_millis(250)).await;+ client+ .parse("three", 1, 1, &[1, 2, 3, 4], &Default::default())+ .await+ .unwrap();+ assert_eq!(std::fs::read_to_string(&pids).unwrap().lines().count(), 2);+ assert_eq!(+ std::fs::read_to_string(counter).unwrap(),+ "one\ntwo\nthree\n"+ );+ }++ #[tokio::test]+ async fn warm_worker_crash_and_cancel_kill_state_without_replay() {+ let evidence = tempfile::tempdir().unwrap();+ let counter = evidence.path().join("counter");+ let pids = evidence.path().join("pids");+ let (directory, worker) = warm_fixture_worker(&counter, &pids);+ let client = warm_client(+ &directory,+ worker,+ WarmWorkerPolicy {+ startup_timeout: Duration::from_secs(10),+ inference_timeout: Duration::from_secs(2),+ shutdown_timeout: Duration::from_millis(100),+ idle_ttl: Duration::from_secs(5),+ },+ );+ let failure = client+ .parse("crash", 1, 1, &[1, 2, 3, 4], &Default::default())+ .await+ .unwrap_err();+ assert_eq!(failure.code, VisualParseErrorCode::WorkerCrashed);+ client+ .parse("after-crash", 1, 1, &[1, 2, 3, 4], &Default::default())+ .await+ .unwrap();+ assert_eq!(+ std::fs::read_to_string(&counter).unwrap(),+ "crash\nafter-crash\n"+ );++ let cancellation = PerceptionCancellation::default();+ let trigger = cancellation.clone();+ tokio::spawn(async move {+ tokio::time::sleep(Duration::from_millis(50)).await;+ trigger.cancel();+ });+ let failure = client+ .parse("hang", 1, 1, &[1, 2, 3, 4], &cancellation)+ .await+ .unwrap_err();+ assert_eq!(failure.code, VisualParseErrorCode::WorkerCancelled);+ client+ .parse("after-cancel", 1, 1, &[1, 2, 3, 4], &Default::default())+ .await+ .unwrap();+ let calls = std::fs::read_to_string(counter).unwrap();+ assert_eq!(calls.matches("hang\n").count(), 1);+ assert!(calls.ends_with("after-cancel\n"));+ }++ #[tokio::test]+ async fn shutdown_now_cancels_inference_and_drops_warm_worker() {+ let evidence = tempfile::tempdir().unwrap();+ let counter = evidence.path().join("counter");+ let pids = evidence.path().join("pids");+ let (directory, worker) = warm_fixture_worker(&counter, &pids);+ let client = warm_client(+ &directory,+ worker,+ WarmWorkerPolicy {+ startup_timeout: Duration::from_secs(10),+ inference_timeout: Duration::from_secs(5),+ shutdown_timeout: Duration::from_millis(100),+ idle_ttl: Duration::from_secs(5),+ },+ );+ let shutdown = client.clone();+ let observed_counter = counter.clone();+ let original_pid = client+ .parse("before-shutdown", 1, 1, &[1, 2, 3, 4], &Default::default())+ .await+ .unwrap()["pid"]+ .as_u64()+ .unwrap();+ tokio::spawn(async move {+ for _ in 0..100 {+ if std::fs::read_to_string(&observed_counter)+ .is_ok_and(|calls| calls.contains("hang\n"))+ {+ break;+ }+ tokio::time::sleep(Duration::from_millis(10)).await;+ }+ shutdown.shutdown_now();+ });+ let failure = client+ .parse("hang", 1, 1, &[1, 2, 3, 4], &Default::default())+ .await+ .unwrap_err();+ assert_eq!(failure.code, VisualParseErrorCode::WorkerCancelled);+ let replacement_pid = client+ .parse("after-shutdown", 1, 1, &[1, 2, 3, 4], &Default::default())+ .await+ .unwrap()["pid"]+ .as_u64()+ .unwrap();+ assert_ne!(original_pid, replacement_pid);+ }++ /// A stand-in for an installed extension's health or self-test hook. A+ /// shipped hook is the extension's own native binary, so as with the worker+ /// fixtures the interpreter is opted into the sandbox explicitly rather+ /// than by widening the boundary for everyone.+ fn fixture_hook(mode: &str) -> (tempfile::TempDir, PathBuf, Vec<String>) {+ let directory = tempfile::tempdir().unwrap();+ let path = directory.path().join("fixture-hook.py");+ let script = r#"#!/usr/bin/env python3+import sys, time++mode = sys.argv[1]+if mode == 'chatty':+ sys.stdout.buffer.write(b'x' * (4 * 1024 * 1024))+ sys.stdout.buffer.flush()+elif mode == 'hang':+ time.sleep(120)+elif mode == 'fail':+ sys.exit(7)+sys.exit(0)+"#;+ std::fs::write(&path, with_fixture_interpreter(script)).unwrap();+ let mut permissions = std::fs::metadata(&path).unwrap().permissions();+ permissions.set_mode(0o700);+ std::fs::set_permissions(&path, permissions).unwrap();+ (directory, path, vec![mode.to_owned()])+ }++ async fn run_fixture_hook(mode: &str, timeout: Duration) -> containment::HookOutcome {+ let (_directory, hook, args) = fixture_hook(mode);+ containment::run_contained_hook(&hook, &args, &fixture_limits(&args), timeout)+ .await+ .unwrap()+ }++ #[tokio::test]+ async fn a_contained_hook_reports_how_it_exited() {+ assert_eq!(+ run_fixture_hook("ok", Duration::from_secs(30)).await,+ containment::HookOutcome::Succeeded+ );+ assert!(matches!(+ run_fixture_hook("fail", Duration::from_secs(30)).await,+ containment::HookOutcome::Failed(_)+ ));+ }++ /// A hook that never exits is killed at its deadline rather than holding+ /// the install or status command open.+ #[tokio::test]+ async fn a_contained_hook_that_outlives_its_deadline_is_killed() {+ let started = Instant::now();+ assert_eq!(+ run_fixture_hook("hang", Duration::from_millis(500)).await,+ containment::HookOutcome::TimedOut+ );+ assert!(started.elapsed() < Duration::from_secs(30));+ }++ /// The hook's output is discarded as it arrives, so a hook that fills its+ /// pipe still finishes instead of blocking until its deadline.+ #[tokio::test]+ async fn a_contained_hook_that_floods_its_output_still_finishes() {+ assert_eq!(+ run_fixture_hook("chatty", Duration::from_secs(30)).await,+ containment::HookOutcome::Succeeded+ );+ }++ /// A hook gets no more authority than a parse: the same boundary refuses a+ /// launch it cannot fully contain.+ #[tokio::test]+ async fn a_contained_hook_refuses_a_missing_entrypoint() {+ let directory = tempfile::tempdir().unwrap();+ let missing = directory.path().join("absent-hook");+ let failure = containment::run_contained_hook(+ &missing,+ &[],+ &ContainmentLimits::default(),+ Duration::from_secs(5),+ )+ .await+ .unwrap_err();+ assert!(matches!(+ failure.code,+ VisualParseErrorCode::WorkerLaunchFailed | VisualParseErrorCode::UnsupportedPlatform+ ));+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/perception_client/containment.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/perception_client/containment.rsnew file mode 100644index 0000000000..6179d5eac2--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/perception_client/containment.rs@@ -0,0 +1,912 @@+//! Bounded external-process containment for the optional perception worker.+//!+//! Containment is reported as platform capabilities rather than one misleading+//! cross-platform boolean. Each implementation must install every boundary it+//! advertises, or fail before worker code executes. [`spawn`] refuses to launch+//! a worker on any target whose reported capabilities do not meet+//! [`ContainmentCapabilities::meets_contract`], so a partially contained+//! platform is an explicit `unsupported_platform` result rather than a weaker+//! silent mode.+//!+//! Platform coverage:+//!+//! - Linux: process group, `PR_SET_PDEATHSIG`, `PR_SET_NO_NEW_PRIVS`,+//! `close_range`, `RLIMIT_AS`/`RLIMIT_CPU`/`RLIMIT_NOFILE`, a Landlock+//! ruleset that confines reads, executes and writes to an exact allowlist,+//! and a seccomp filter that denies every socket, `io_uring`, process+//! creation, `ptrace` and cross-process memory access.+//! - macOS: process group, a trusted `/bin/sh` parent-death sentinel, inherited+//! descriptor closure, `RLIMIT_CPU`/`RLIMIT_NOFILE`, a supervisor-sampled+//! memory ceiling, and a deny-by-default Seatbelt profile applied through+//! `sandbox-exec` that confines reads, writes, execution, Mach lookups and+//! IPC and denies network, fork and cross-process authority.+//! - Windows: an AppContainer (LowBox) identity with no capabilities, an+//! explicit `PROC_THREAD_ATTRIBUTE_HANDLE_LIST` carrying only the protocol+//! pipes, private security descriptors on the job, process, thread, pipes,+//! desktop and working directory, a private desktop, and a Job Object with+//! kill-on-close, memory, CPU-time, active-process and UI restrictions. The+//! worker is created suspended and resumed only after every boundary is in+//! place. Filesystem ACLs are read and updated through verified no-follow+//! handles so reparse-point swaps cannot redirect a grant.+//!+//! Network denial, read confinement and write confinement are deliberately not+//! configurable. The only tunable surface is [`ContainmentLimits`], including+//! extra readable and writable paths a caller must opt into explicitly.+//!+//! [`run_contained_hook`] reuses the same boundary for a one-shot auxiliary+//! process — an installed extension's health or self-test hook — so such a hook+//! never runs with more authority than an ordinary parse.++use std::path::{Component, Path, PathBuf};+use std::time::Duration;++use cua_driver_contract::{VisualParseError, VisualParseErrorCode};+use tokio::io::AsyncReadExt as _;++use super::error;++#[cfg(unix)]+mod unix;++#[cfg(target_os = "linux")]+mod linux;+#[cfg(target_os = "linux")]+use linux as platform;++#[cfg(target_os = "macos")]+mod macos;+#[cfg(target_os = "macos")]+use macos as platform;++#[cfg(windows)]+mod windows;+#[cfg(windows)]+use windows as platform;++#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]+mod unsupported;+#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]+use unsupported as platform;++/// The parent end of the worker's stdin pipe. Unix uses the child's inherited+/// pipe directly; Windows uses a private named pipe so the parent side can be+/// asynchronous while the child receives an ordinary synchronous stdio handle.+pub(crate) type WorkerStdin = platform::WorkerStdin;+/// The parent end of the worker's stdout pipe.+pub(crate) type WorkerStdout = platform::WorkerStdout;++/// A 16 GiB memory ceiling. Linux applies this to virtual address space, where+/// inference stacks commonly reserve far more than they commit; Windows applies+/// it to total committed memory in the Job Object; macOS has no kernel+/// primitive for it and the supervisor samples the worker instead.+const DEFAULT_MAX_MEMORY_BYTES: u64 = 16 * 1024 * 1024 * 1024;+/// 15 minutes of CPU time. A warm worker accumulates CPU across every reused+/// parse, so this is a session ceiling rather than a per-request one; the+/// per-request bound is [`super::WarmWorkerPolicy::inference_timeout`].+const DEFAULT_MAX_CPU_TIME: Duration = Duration::from_secs(15 * 60);+/// The worker runs alone. Unix denies process creation outright through seccomp+/// and Seatbelt; Windows caps the Job Object's active-process count instead,+/// because a Job Object has no equivalent creation hook.+const DEFAULT_MAX_PROCESSES: u32 = 1;+/// Prevents descriptor exhaustion on Unix. Windows Job Objects have no+/// equivalent handle-count ceiling, which capability reporting makes explicit.+const DEFAULT_MAX_OPEN_FILES: u32 = 256;++/// How a memory ceiling is actually enforced on the current target.+#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum MemoryLimitEnforcement {+ /// The kernel refuses allocations past the ceiling.+ Kernel,+ /// The supervisor samples the worker's footprint and kills the process tree+ /// once the ceiling is exceeded. An allocation burst that both starts and+ /// completes between two samples is not prevented.+ SupervisorSampling,+ /// No ceiling is installed. The worker is not memory bounded.+ None,+}++/// Truthful boundaries installed by the current target implementation.+#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub struct ContainmentCapabilities {+ pub process_tree_cleanup: bool,+ pub parent_death: bool,+ pub parent_eof: bool,+ pub inherited_handle_closure: bool,+ pub memory_limit: MemoryLimitEnforcement,+ pub cpu_limit: bool,+ /// The worker cannot create another process at all. This replaces the+ /// earlier per-UID task ceiling, which bounded neither the worker tree nor+ /// anything else useful.+ pub process_creation_denial: bool,+ pub file_descriptor_limit: bool,+ pub filesystem_read_isolation: bool,+ pub filesystem_write_isolation: bool,+ pub network_isolation: bool,+ /// The worker cannot read or write another process's memory, attach a+ /// debugger, or steal another process's descriptors.+ pub process_memory_isolation: bool,+ /// The worker cannot capture the desktop, synthesize input, install input+ /// hooks, or read the clipboard.+ pub desktop_input_isolation: bool,+}++impl ContainmentCapabilities {+ /// Every boundary the perception worker contract requires before untrusted+ /// worker code may run.+ ///+ /// `file_descriptor_limit` is deliberately absent: Windows Job Objects+ /// expose no per-job handle ceiling, and descriptor exhaustion is bounded+ /// there by the job's memory limit instead.+ pub const fn meets_contract(&self) -> bool {+ self.process_tree_cleanup+ && self.parent_death+ && self.parent_eof+ && self.inherited_handle_closure+ && self.cpu_limit+ && self.process_creation_denial+ && self.filesystem_read_isolation+ && self.filesystem_write_isolation+ && self.network_isolation+ && self.process_memory_isolation+ && self.desktop_input_isolation+ && !matches!(self.memory_limit, MemoryLimitEnforcement::None)+ }+}++/// Capabilities are compile-target facts. Host facilities are still checked at+/// launch and cause a stable fail-closed error when unavailable.+pub const fn capabilities() -> ContainmentCapabilities {+ #[cfg(target_os = "linux")]+ {+ ContainmentCapabilities {+ process_tree_cleanup: true,+ parent_death: true,+ parent_eof: true,+ inherited_handle_closure: true,+ memory_limit: MemoryLimitEnforcement::Kernel,+ cpu_limit: true,+ process_creation_denial: true,+ file_descriptor_limit: true,+ filesystem_read_isolation: true,+ filesystem_write_isolation: true,+ network_isolation: true,+ process_memory_isolation: true,+ desktop_input_isolation: true,+ }+ }+ #[cfg(target_os = "macos")]+ {+ ContainmentCapabilities {+ process_tree_cleanup: true,+ parent_death: true,+ parent_eof: true,+ inherited_handle_closure: true,+ memory_limit: MemoryLimitEnforcement::SupervisorSampling,+ cpu_limit: true,+ process_creation_denial: true,+ file_descriptor_limit: true,+ filesystem_read_isolation: true,+ filesystem_write_isolation: true,+ network_isolation: true,+ process_memory_isolation: true,+ desktop_input_isolation: true,+ }+ }+ #[cfg(windows)]+ {+ ContainmentCapabilities {+ process_tree_cleanup: true,+ parent_death: true,+ parent_eof: true,+ inherited_handle_closure: true,+ memory_limit: MemoryLimitEnforcement::Kernel,+ cpu_limit: true,+ process_creation_denial: true,+ file_descriptor_limit: false,+ filesystem_read_isolation: true,+ filesystem_write_isolation: true,+ network_isolation: true,+ process_memory_isolation: true,+ desktop_input_isolation: true,+ }+ }+ #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]+ {+ ContainmentCapabilities {+ process_tree_cleanup: false,+ parent_death: false,+ parent_eof: false,+ inherited_handle_closure: false,+ memory_limit: MemoryLimitEnforcement::None,+ cpu_limit: false,+ process_creation_denial: false,+ file_descriptor_limit: false,+ filesystem_read_isolation: false,+ filesystem_write_isolation: false,+ network_isolation: false,+ process_memory_isolation: false,+ desktop_input_isolation: false,+ }+ }+}++/// Explicit, testable resource ceilings applied to the worker process tree.+#[derive(Clone, Debug)]+pub struct ContainmentLimits {+ /// Memory ceiling in bytes. Linux applies it to each process's virtual+ /// address space, Windows to the Job Object's total committed memory, and+ /// macOS through supervisor sampling. [`capabilities`] reports which.+ pub max_memory_bytes: u64,+ /// Maximum CPU time each worker process may accumulate. The soft limit is+ /// this value and the hard limit a short grace period above it, so a worker+ /// that exhausts its CPU budget dies with a distinguishable signal.+ pub max_cpu_time: Duration,+ /// Maximum number of concurrently live processes in the Windows Job Object.+ /// Unix denies process creation outright and ignores this count.+ pub max_processes: u32,+ /// Maximum number of open file descriptors on Unix. Windows reports that it+ /// cannot enforce an equivalent per-job handle count.+ pub max_open_files: u32,+ /// Directories the worker may write to in addition to its private working+ /// directory. Every entry widens the sandbox, so callers opt in per path.+ pub additional_writable_paths: Vec<PathBuf>,+ /// Directories the worker may read in addition to its own bundle, runtime+ /// and model paths and the target's immutable system runtime directories.+ /// Every entry widens the sandbox, so callers opt in per path.+ pub additional_readable_paths: Vec<PathBuf>,+ /// Windows-only file whose exclusive lock serializes temporary worker ACLs+ /// with extension lifecycle hardening. Other platforms ignore this path.+ pub windows_acl_lease_path: Option<PathBuf>,+ /// Windows AppContainer recovery journal. Installed workers derive this+ /// from the lease; extension hooks provide it while an outer owner holds+ /// that same lease.+ pub windows_acl_profile_journal_path: Option<PathBuf>,+ /// Require Windows teardown to finish before the containing call returns.+ /// Extension hooks use this while their caller already owns the lifecycle+ /// ACL lease, avoiding a nested lock while forbidding deferred revocation.+ pub windows_require_synchronous_cleanup: bool,+ /// Exact executable files needed only by scripted test fixtures. Shipped+ /// native workers execute only their configured worker binary.+ #[cfg(test)]+ pub additional_executable_paths: Vec<PathBuf>,+}++impl Default for ContainmentLimits {+ fn default() -> Self {+ Self {+ max_memory_bytes: DEFAULT_MAX_MEMORY_BYTES,+ max_cpu_time: DEFAULT_MAX_CPU_TIME,+ max_processes: DEFAULT_MAX_PROCESSES,+ max_open_files: DEFAULT_MAX_OPEN_FILES,+ additional_writable_paths: Vec::new(),+ additional_readable_paths: Vec::new(),+ windows_acl_lease_path: None,+ windows_acl_profile_journal_path: None,+ windows_require_synchronous_cleanup: false,+ #[cfg(test)]+ additional_executable_paths: Vec::new(),+ }+ }+}++#[cfg(windows)]+pub fn windows_acl_profile_journal_path(lease_path: &Path) -> PathBuf {+ platform::acl_profile_journal_path(lease_path)+}++#[cfg(windows)]+pub fn recover_windows_acl_profile_journal(journal_path: &Path) -> Result<(), VisualParseError> {+ platform::recover_acl_profile_journal(journal_path)+}++impl ContainmentLimits {+ pub(crate) fn validate(&self) -> Result<(), VisualParseError> {+ if self.max_memory_bytes == 0+ || self.max_cpu_time.as_secs() == 0+ || self.max_processes == 0+ || self.max_open_files == 0+ {+ return Err(error(+ VisualParseErrorCode::ResourceLimitExceeded,+ "perception worker containment limits must be non-zero",+ false,+ None,+ ));+ }+ Ok(())+ }++ fn max_cpu_seconds(&self) -> u64 {+ self.max_cpu_time.as_secs().max(1)+ }+}++/// The exact, canonical, symlink-free filesystem boundary handed to a platform+/// sandbox. Directory roots are canonical and executable entries are exact+/// canonical files.+struct FilesystemBoundary {+ /// Directories the worker may read from.+ readable: Vec<PathBuf>,+ /// Directories the worker may write to.+ writable: Vec<PathBuf>,+ /// Exact files the worker may execute or map as executable code.+ #[cfg_attr(windows, allow(dead_code))]+ executables: Vec<PathBuf>,+}++/// Derive the worker's filesystem boundary from its launch configuration.+///+/// Read roots come from the worker executable, every absolute path argument+/// (the model manifest and the inference runtime library are passed this way),+/// the private working directory and the caller's explicit opt-ins. Nothing+/// else is readable, so the caller's home directory, credential stores, browser+/// profiles, desktop IPC sockets and the temporary root all stay outside the+/// sandbox.+fn filesystem_boundary(+ executable: &Path,+ args: &[String],+ working_directory: &Path,+ limits: &ContainmentLimits,+) -> Result<FilesystemBoundary, VisualParseError> {+ let working_directory = canonical_directory(working_directory)?;+ let mut readable = vec![working_directory.clone()];+ let mut writable = vec![working_directory];+ #[cfg(not(test))]+ let executables = vec![canonical_file(executable)?];+ #[cfg(test)]+ let mut executables = vec![canonical_file(executable)?];++ readable.push(derived_read_root(executable)?);+ for argument in args {+ let path = Path::new(argument);+ if !path.is_absolute() {+ continue;+ }+ // A configured path that does not exist cannot be a launch or inference+ // input, so it never widens the sandbox.+ if path.symlink_metadata().is_err() {+ continue;+ }+ readable.push(derived_read_root(path)?);+ }+ for path in &limits.additional_readable_paths {+ readable.push(canonical_directory(path)?);+ }+ #[cfg(test)]+ for path in &limits.additional_executable_paths {+ executables.push(canonical_file(path)?);+ }+ for path in &limits.additional_writable_paths {+ let path = canonical_directory(path)?;+ readable.push(path.clone());+ writable.push(path);+ }++ Ok(FilesystemBoundary {+ readable: collapse_roots(readable),+ writable: collapse_roots(writable),+ executables,+ })+}++fn canonical_file(path: &Path) -> Result<PathBuf, VisualParseError> {+ let path = std::fs::canonicalize(path).map_err(|cause| {+ containment_error(+ "failed to resolve a perception worker executable",+ os_detail(&cause),+ )+ })?;+ if !path.is_file() {+ return Err(containment_error(+ "a perception worker executable is not a file",+ None,+ ));+ }+ Ok(path)+}++/// Resolve `path` to the exact directory the worker needs, rejecting a root+/// that would widen the sandbox beyond the worker's own installation.+fn derived_read_root(path: &Path) -> Result<PathBuf, VisualParseError> {+ let resolved = std::fs::canonicalize(path).map_err(|cause| {+ containment_error(+ "failed to resolve a perception worker path for the read sandbox",+ os_detail(&cause),+ )+ })?;+ let root = if resolved.is_dir() {+ resolved+ } else {+ resolved+ .parent()+ .ok_or_else(|| {+ containment_error(+ "a perception worker path has no directory for the read sandbox",+ None,+ )+ })?+ .to_path_buf()+ };+ reject_broad_read_root(&root)?;+ Ok(root)+}++/// A derived read root must be specific to the worker installation. A shared+/// system directory, a home directory or a filesystem root would hand the+/// worker unrelated user data, so those are refused rather than silently+/// widening the sandbox.+fn reject_broad_read_root(path: &Path) -> Result<(), VisualParseError> {+ let named = path+ .components()+ .filter(|component| matches!(component, Component::Normal(_)))+ .count();+ let parent_is_home_root = path.parent().is_some_and(|parent| {+ matches!(+ parent.to_str(),+ Some(+ "/Users"+ | "/home"+ | "/private/Users"+ | "/var/folders"+ | "/private/var/folders"+ | "/root"+ )+ ) || parent+ .file_name()+ .is_some_and(|name| name.eq_ignore_ascii_case("Users"))+ });+ let is_home = home_directory().is_some_and(|home| home == path);+ let denied = BROAD_READ_ROOTS+ .iter()+ .any(|entry| path.as_os_str().eq_ignore_ascii_case(*entry));+ if named < 2 || parent_is_home_root || is_home || denied {+ return Err(containment_error(+ "a perception worker path resolves to a directory too broad to grant the worker",+ None,+ ));+ }+ Ok(())+}++/// Shared directories that must never become a worker read root even though+/// they are deep enough to pass the component check.+const BROAD_READ_ROOTS: &[&str] = &[+ "/usr/bin",+ "/usr/sbin",+ "/usr/lib",+ "/usr/lib64",+ "/usr/libexec",+ "/usr/local",+ "/usr/share",+ "/var/tmp",+ "/var/folders",+ "/private/tmp",+ "/private/var",+ "/System/Library",+ "/Library/Keychains",+ "/Library/Application Support",+ "/etc/ssl",+];++fn home_directory() -> Option<PathBuf> {+ let name = if cfg!(windows) { "USERPROFILE" } else { "HOME" };+ let value = std::env::var_os(name)?;+ std::fs::canonicalize(value).ok()+}++fn canonical_directory(path: &Path) -> Result<PathBuf, VisualParseError> {+ let resolved = std::fs::canonicalize(path).map_err(|cause| {+ containment_error(+ "failed to resolve a perception worker sandbox directory",+ os_detail(&cause),+ )+ })?;+ if !resolved.is_dir() {+ return Err(containment_error(+ "a perception worker sandbox path is not a directory",+ None,+ ));+ }+ Ok(resolved)+}++/// Drop duplicates and any root already covered by an ancestor, so a platform+/// installs the smallest equivalent rule set.+fn collapse_roots(mut roots: Vec<PathBuf>) -> Vec<PathBuf> {+ roots.sort();+ roots.dedup();+ let mut collapsed: Vec<PathBuf> = Vec::with_capacity(roots.len());+ for root in roots {+ if collapsed.iter().any(|kept| root.starts_with(kept)) {+ continue;+ }+ collapsed.push(root);+ }+ collapsed+}++/// The raw operating-system result of a worker exit, before the guard folds in+/// supervisor state such as a sampled memory kill.+struct RawExit {+ success: bool,+ /// The operating system itself ended the process for exhausting a+ /// containment ceiling.+ resource_limited: bool,+ description: String,+}++/// How the worker process finished.+#[derive(Clone, Debug, Eq, PartialEq)]+pub(crate) enum WorkerExit {+ Success,+ /// The worker died or exited unsuccessfully for a reason other than a+ /// containment ceiling.+ Failure(String),+ /// A containment ceiling — CPU time or memory — ended the worker. The+ /// caller reports this as `resource_limit_exceeded` rather than a crash so+ /// an agent does not retry a request that cannot succeed.+ ResourceLimit(String),+}++/// A launched worker process plus the platform handles that bound it.+///+/// Field order is load-bearing: `guard` is declared first so it drops first,+/// tearing down the whole process tree before the process handle is reaped and+/// before the protocol pipes close.+pub(crate) struct ContainedChild {+ guard: platform::Guard,+ process: platform::Process,+ stdin: Option<WorkerStdin>,+ stdout: Option<WorkerStdout>,+}++impl ContainedChild {+ pub(crate) fn take_stdin(&mut self) -> Option<WorkerStdin> {+ self.stdin.take()+ }++ pub(crate) fn take_stdout(&mut self) -> Option<WorkerStdout> {+ self.stdout.take()+ }++ /// Wait for the worker to exit and classify how it ended.+ pub(crate) async fn wait(&mut self) -> std::io::Result<WorkerExit> {+ let raw = self.process.wait().await?;+ // The process table entry is gone, so a later process-group signal+ // could reach a recycled group id. Platforms that cannot prove the+ // group is still occupied stop signalling it here.+ #[cfg(windows)]+ self.guard.note_reaped()?;+ #[cfg(not(windows))]+ self.guard.note_reaped();+ Ok(if raw.success {+ WorkerExit::Success+ } else if raw.resource_limited || self.guard.memory_ceiling_exceeded() {+ WorkerExit::ResourceLimit(raw.description)+ } else {+ WorkerExit::Failure(raw.description)+ })+ }+}++/// Launch the worker under full platform containment.+///+/// Returns [`VisualParseErrorCode::UnsupportedPlatform`] when the target or host+/// lacks a required containment facility and+/// [`VisualParseErrorCode::WorkerLaunchFailed`] when an available facility+/// cannot be configured or the contained process cannot be launched. Neither+/// case executes worker code.+pub(crate) async fn spawn(+ executable: &Path,+ args: &[String],+ working_directory: &Path,+ limits: &ContainmentLimits,+) -> Result<ContainedChild, VisualParseError> {+ limits.validate()?;+ if !capabilities().meets_contract() {+ return Err(unsupported_error(+ "this platform cannot install every perception worker boundary, so no worker is launched",+ ));+ }+ let boundary = filesystem_boundary(executable, args, working_directory, limits)?;+ // Launch through the same canonical names the platform policy contains.+ // This is load-bearing on macOS, where `/var` is a symlink to+ // `/private/var` and Seatbelt evaluates the path used by `exec`.+ let executable = canonical_file(executable)?;+ let working_directory = canonical_directory(working_directory)?;+ let args = args+ .iter()+ .map(|argument| {+ let path = Path::new(argument);+ if path.is_absolute() && path.symlink_metadata().is_ok() {+ std::fs::canonicalize(path)+ .map(|path| path.display().to_string())+ .map_err(|cause| {+ containment_error(+ "failed to resolve a perception worker argument for launch",+ os_detail(&cause),+ )+ })+ } else {+ Ok(argument.clone())+ }+ })+ .collect::<Result<Vec<_>, _>>()?;+ platform::spawn(&executable, &args, &working_directory, &boundary, limits).await+}++/// How a one-shot contained process finished.+#[derive(Clone, Debug, Eq, PartialEq)]+pub enum HookOutcome {+ Succeeded,+ /// The hook ran and ended unsuccessfully for a reason other than a+ /// containment ceiling.+ Failed(String),+ /// A containment ceiling — CPU time or memory — ended the hook.+ ResourceLimited(String),+ /// The hook outlived its deadline, so its process tree was killed and+ /// reaped before this returned.+ TimedOut,+}++/// How long the killed process tree is given to be reaped after a deadline, so+/// a one-shot caller leaves no zombie behind.+const TERMINATION_GRACE: Duration = Duration::from_secs(5);++/// Run one auxiliary process — an installed extension's health or self-test+/// hook — under exactly the boundary [`spawn`] installs for a perception parse.+///+/// The hook is not a protocol peer, so its request pipe is closed immediately+/// and it observes end of file just as a null stdin would; its standard output+/// is read and discarded so a chatty hook can neither block on a full pipe nor+/// reach the Driver's own output; its standard error is discarded by the+/// platform command shape. The private working directory is created here and+/// removed when this returns, and it is the only path the hook may write.+///+/// Containment that cannot be installed is an error rather than a weaker+/// launch, so no hook instruction runs before every boundary is in place.+pub async fn run_contained_hook(+ executable: &Path,+ args: &[String],+ limits: &ContainmentLimits,+ timeout: Duration,+) -> Result<HookOutcome, VisualParseError> {+ if timeout.is_zero() {+ return Err(error(+ VisualParseErrorCode::ResourceLimitExceeded,+ "a contained hook deadline must be non-zero",+ false,+ None,+ ));+ }+ let working_directory = tempfile::Builder::new()+ .prefix("cua-extension-hook-")+ .tempdir()+ .map_err(|cause| {+ containment_error(+ "failed to create a private contained hook directory",+ os_detail(&cause),+ )+ })?;+ let mut contained = spawn(executable, args, working_directory.path(), limits).await?;+ // Closing the request pipe is what makes the hook observe end of file.+ drop(contained.take_stdin());+ let mut stdout = contained.take_stdout();+ let exit = tokio::time::timeout(timeout, async {+ let (_, exit) = tokio::join!(discard_output(stdout.as_mut()), contained.wait());+ exit+ })+ .await;+ match exit {+ Ok(Ok(WorkerExit::Success)) => Ok(HookOutcome::Succeeded),+ Ok(Ok(WorkerExit::Failure(detail))) => Ok(HookOutcome::Failed(detail)),+ Ok(Ok(WorkerExit::ResourceLimit(detail))) => Ok(HookOutcome::ResourceLimited(detail)),+ Ok(Err(cause)) => Err(error(+ VisualParseErrorCode::WorkerCrashed,+ "failed to supervise the contained hook",+ false,+ os_detail(&cause),+ )),+ Err(_) => {+ terminate(contained).await;+ Ok(HookOutcome::TimedOut)+ }+ }+}++/// Drain the hook's output into nothing. A hook that fills its pipe would+/// otherwise block until its deadline instead of exiting.+async fn discard_output(stdout: Option<&mut WorkerStdout>) {+ let Some(stdout) = stdout else {+ return;+ };+ let mut sink = [0_u8; 8 * 1024];+ while matches!(stdout.read(&mut sink).await, Ok(count) if count > 0) {}+}++/// Tear a contained process tree down through its platform guard and reap it.+///+/// Destructuring rather than dropping keeps the documented order explicit: the+/// guard kills the tree first, and only then is the process handle awaited.+async fn terminate(contained: ContainedChild) {+ let ContainedChild {+ guard,+ mut process,+ stdin,+ stdout,+ } = contained;+ // Matches the field order an ordinary drop would follow: the guard tears+ // the tree down first, the process handle is reaped next, and the protocol+ // pipes are released last.+ drop(guard);+ let _ = tokio::time::timeout(TERMINATION_GRACE, process.wait()).await;+ drop(stdin);+ drop(stdout);+}++/// A launch failure that is deterministic for this host: retrying cannot make+/// the containment facility appear.+fn containment_error(message: &'static str, detail: Option<String>) -> VisualParseError {+ error(+ VisualParseErrorCode::WorkerLaunchFailed,+ message,+ false,+ detail,+ )+}++/// A platform or host that cannot install the full containment contract.+fn unsupported_error(message: &'static str) -> VisualParseError {+ error(+ VisualParseErrorCode::UnsupportedPlatform,+ message,+ false,+ None,+ )+}++/// Error detail is limited to an operating-system status. Paths, arguments and+/// environment values never reach the caller through a containment failure.+#[allow(dead_code)]+fn os_detail(cause: &std::io::Error) -> Option<String> {+ Some(match cause.raw_os_error() {+ Some(code) => format!("os error {code}"),+ None => "os error unavailable".to_owned(),+ })+}++#[allow(dead_code)]+fn spawn_error(cause: std::io::Error) -> VisualParseError {+ error(+ VisualParseErrorCode::WorkerLaunchFailed,+ "failed to launch the contained perception worker",+ false,+ os_detail(&cause),+ )+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn every_supported_target_meets_the_containment_contract() {+ // A target that cannot install one of these boundaries must reach the+ // fail-closed branch in `spawn` instead of launching a worker.+ let reported = capabilities();+ #[cfg(any(target_os = "linux", target_os = "macos", windows))]+ assert!(+ reported.meets_contract(),+ "a supported target reported an incomplete boundary set: {reported:?}"+ );+ #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]+ assert!(!reported.meets_contract());+ }++ #[test]+ fn macos_reports_its_memory_ceiling_as_sampled_rather_than_kernel_enforced() {+ // Darwin has no public per-process address-space or footprint limit for+ // a spawned child, so the ceiling must not be advertised as a kernel+ // guarantee.+ #[cfg(target_os = "macos")]+ assert_eq!(+ capabilities().memory_limit,+ MemoryLimitEnforcement::SupervisorSampling+ );+ #[cfg(any(target_os = "linux", windows))]+ assert_eq!(capabilities().memory_limit, MemoryLimitEnforcement::Kernel);+ }++ #[test]+ fn broad_directories_are_refused_as_worker_read_roots() {+ for candidate in [+ "/",+ "/usr",+ "/tmp",+ "/etc",+ "/usr/lib",+ "/usr/local",+ "/Users/someone",+ "/home/someone",+ "/private/var",+ "/System/Library",+ ] {+ assert!(+ reject_broad_read_root(Path::new(candidate)).is_err(),+ "{candidate} was accepted as a worker read root"+ );+ }+ for candidate in [+ "/opt/cua/extensions/cua-perception/bin",+ "/Users/someone/.cua/extensions/cua-perception/0.1.0",+ "/tmp/.tmpA1b2c3",+ ] {+ assert!(+ reject_broad_read_root(Path::new(candidate)).is_ok(),+ "{candidate} was refused as a worker read root"+ );+ }+ }++ #[test]+ fn collapsed_roots_drop_paths_an_ancestor_already_covers() {+ let collapsed = collapse_roots(vec![+ PathBuf::from("/opt/cua/models"),+ PathBuf::from("/opt/cua"),+ PathBuf::from("/opt/cua"),+ PathBuf::from("/opt/cuativity"),+ ]);+ assert_eq!(+ collapsed,+ vec![PathBuf::from("/opt/cua"), PathBuf::from("/opt/cuativity")]+ );+ }++ #[test]+ fn the_worker_bundle_and_model_paths_become_the_only_derived_read_roots() {+ let bundle = tempfile::Builder::new()+ .prefix("cua-perception-bundle-")+ .tempdir()+ .unwrap();+ let working = tempfile::Builder::new()+ .prefix("cua-perception-work-")+ .tempdir()+ .unwrap();+ let executable = bundle.path().join("bin");+ std::fs::create_dir(&executable).unwrap();+ let executable = executable.join("worker");+ std::fs::write(&executable, b"#!/bin/sh\n").unwrap();+ let models = bundle.path().join("models");+ std::fs::create_dir(&models).unwrap();+ let manifest = models.join("manifest.json");+ std::fs::write(&manifest, b"{}").unwrap();++ let boundary = filesystem_boundary(+ &executable,+ &[+ "--manifest".to_owned(),+ manifest.display().to_string(),+ "--threads".to_owned(),+ "2".to_owned(),+ ],+ working.path(),+ &ContainmentLimits::default(),+ )+ .unwrap();++ let canonical_models = std::fs::canonicalize(&models).unwrap();+ let canonical_bin = std::fs::canonicalize(executable.parent().unwrap()).unwrap();+ let canonical_working = std::fs::canonicalize(working.path()).unwrap();+ assert!(boundary.readable.contains(&canonical_models));+ assert!(boundary.readable.contains(&canonical_bin));+ assert!(boundary.readable.contains(&canonical_working));+ assert_eq!(boundary.writable, vec![canonical_working]);+ // The caller's home directory and the temporary root are never granted.+ assert!(!boundary+ .readable+ .iter()+ .any(|root| root == Path::new("/tmp")+ || root == Path::new("/private/tmp")+ || home_directory().is_some_and(|home| *root == home)));+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/perception_client/containment/linux.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/perception_client/containment/linux.rsnew file mode 100644index 0000000000..b089b685bd--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/perception_client/containment/linux.rs@@ -0,0 +1,798 @@+//! Linux worker containment: process group, parent-death signal, resource+//! limits, `PR_SET_NO_NEW_PRIVS`, a Landlock ruleset that confines reads,+//! executes and writes to an exact allowlist, and a seccomp filter that denies+//! every socket, `io_uring`, process creation, debugger attachment and+//! cross-process memory access.+//!+//! Landlock and seccomp are the two unprivileged kernel facilities a parent can+//! install on a child without root, a namespace or a helper binary. Neither is+//! sufficient alone:+//!+//! - Landlock has no hook for `unix_stream_connect` through ABI 5, so it cannot+//! stop the worker from reaching the X11, Wayland, D-Bus or `ssh-agent`+//! sockets. The seccomp filter denies socket creation outright instead, which+//! removes every route — local and external — because the worker also+//! inherits no descriptors.+//! - seccomp cannot express a path policy, and it does not see `io_uring`'s+//! asynchronous operations at all, which is why `io_uring_setup` is denied+//! rather than filtered.+//!+//! Both are prepared in the parent so that a kernel without them fails the+//! launch with a stable error instead of degrading silently.++use std::ffi::CString;+use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};+use std::os::unix::ffi::OsStrExt;+use std::os::unix::process::CommandExt;+use std::path::Path;++use cua_driver_contract::VisualParseError;++use super::unix::{apply_resource_limits, base_command, ProcessGroupGuard};+use super::{+ containment_error, os_detail, spawn_error, unsupported_error, ContainedChild,+ ContainmentLimits, FilesystemBoundary,+};++pub(super) type Guard = ProcessGroupGuard;+pub(super) type Process = super::unix::Process;+pub(super) type WorkerStdin = tokio::process::ChildStdin;+pub(super) type WorkerStdout = tokio::process::ChildStdout;++const SYS_LANDLOCK_CREATE_RULESET: libc::c_long = 444;+const SYS_LANDLOCK_ADD_RULE: libc::c_long = 445;+const SYS_LANDLOCK_RESTRICT_SELF: libc::c_long = 446;+const SYS_CLOSE_RANGE: libc::c_long = 436;+const CLOSE_RANGE_CLOEXEC: u32 = 1 << 2;++const LANDLOCK_CREATE_RULESET_VERSION: u32 = 1 << 0;+const LANDLOCK_RULE_PATH_BENEATH: u32 = 1;++const LANDLOCK_ACCESS_FS_EXECUTE: u64 = 1 << 0;+const LANDLOCK_ACCESS_FS_WRITE_FILE: u64 = 1 << 1;+const LANDLOCK_ACCESS_FS_READ_FILE: u64 = 1 << 2;+const LANDLOCK_ACCESS_FS_READ_DIR: u64 = 1 << 3;+const LANDLOCK_ACCESS_FS_REMOVE_DIR: u64 = 1 << 4;+const LANDLOCK_ACCESS_FS_REMOVE_FILE: u64 = 1 << 5;+const LANDLOCK_ACCESS_FS_MAKE_CHAR: u64 = 1 << 6;+const LANDLOCK_ACCESS_FS_MAKE_DIR: u64 = 1 << 7;+const LANDLOCK_ACCESS_FS_MAKE_REG: u64 = 1 << 8;+const LANDLOCK_ACCESS_FS_MAKE_SOCK: u64 = 1 << 9;+const LANDLOCK_ACCESS_FS_MAKE_FIFO: u64 = 1 << 10;+const LANDLOCK_ACCESS_FS_MAKE_BLOCK: u64 = 1 << 11;+const LANDLOCK_ACCESS_FS_MAKE_SYM: u64 = 1 << 12;+/// Landlock ABI 2.+const LANDLOCK_ACCESS_FS_REFER: u64 = 1 << 13;+/// Landlock ABI 3.+const LANDLOCK_ACCESS_FS_TRUNCATE: u64 = 1 << 14;++/// Every filesystem right Landlock ABI 1-3 can restrict. Handling all of them+/// means the ruleset denies reads, executes and writes by default; a path is+/// reachable only through an explicit rule below.+const LANDLOCK_HANDLED_ACCESS: u64 = LANDLOCK_ACCESS_FS_EXECUTE+ | LANDLOCK_ACCESS_FS_WRITE_FILE+ | LANDLOCK_ACCESS_FS_READ_FILE+ | LANDLOCK_ACCESS_FS_READ_DIR+ | LANDLOCK_ACCESS_FS_REMOVE_DIR+ | LANDLOCK_ACCESS_FS_REMOVE_FILE+ | LANDLOCK_ACCESS_FS_MAKE_CHAR+ | LANDLOCK_ACCESS_FS_MAKE_DIR+ | LANDLOCK_ACCESS_FS_MAKE_REG+ | LANDLOCK_ACCESS_FS_MAKE_SOCK+ | LANDLOCK_ACCESS_FS_MAKE_FIFO+ | LANDLOCK_ACCESS_FS_MAKE_BLOCK+ | LANDLOCK_ACCESS_FS_MAKE_SYM+ | LANDLOCK_ACCESS_FS_REFER+ | LANDLOCK_ACCESS_FS_TRUNCATE;++/// Read a directory tree without making every file beneath it executable.+const LANDLOCK_READ_TREE: u64 = LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_READ_DIR;+/// Immutable system trees contain the ELF interpreter used during `execve`.+/// They remain executable, while caller-controlled readable/writable roots do+/// not acquire this right.+const LANDLOCK_SYSTEM_READ_TREE: u64 = LANDLOCK_READ_TREE | LANDLOCK_ACCESS_FS_EXECUTE;+/// Read a single file. Directory-only rights would make `landlock_add_rule`+/// reject a rule whose target is not a directory.+const LANDLOCK_READ_FILE_ONLY: u64 = LANDLOCK_ACCESS_FS_READ_FILE;+/// Execute one exact, prevalidated worker entry point.+const LANDLOCK_EXECUTABLE_FILE: u64 = LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_EXECUTE;+/// Writable workspace trees remain readable and may create/remove entries, but+/// code written there must never become executable inside the worker.+const LANDLOCK_WRITABLE_TREE: u64 = LANDLOCK_HANDLED_ACCESS & !LANDLOCK_ACCESS_FS_EXECUTE;+/// Read and write one character device, without being able to create, replace+/// or remove anything beside it.+const LANDLOCK_DEVICE_ACCESS: u64 =+ LANDLOCK_ACCESS_FS_READ_FILE | LANDLOCK_ACCESS_FS_WRITE_FILE | LANDLOCK_ACCESS_FS_TRUNCATE;++/// Immutable system directories the native loader and inference runtime read.+/// Each is optional: a distribution that does not have one simply contributes+/// no rule. None of them expose user data.+const SYSTEM_READ_TREES: &[&str] = &[+ "/lib",+ "/lib64",+ "/usr/lib",+ "/usr/lib64",+ "/usr/lib32",+ "/usr/libexec",+ "/etc/ld.so.conf.d",+ "/sys/devices/system/cpu",+];++/// Exact system files the loader and allocator read. Whole-directory rules for+/// `/etc`, `/proc` and `/sys` would expose credentials and other processes, so+/// only these files are granted.+const SYSTEM_READ_FILES: &[&str] = &[+ "/etc/ld.so.cache",+ "/etc/ld.so.conf",+ "/etc/ld.so.preload",+ "/proc/cpuinfo",+ "/proc/meminfo",+ "/proc/stat",+ "/proc/sys/vm/overcommit_memory",+ "/proc/sys/vm/max_map_count",+];++/// The only devices the worker may open. A rule beneath `/dev` itself would let+/// a worker running as root reach `/dev/mem` or a raw block device.+const DEVICE_NODES: &[&str] = &[+ "/dev/null",+ "/dev/zero",+ "/dev/full",+ "/dev/random",+ "/dev/urandom",+];++const SECCOMP_SET_MODE_FILTER: libc::c_ulong = 1;+const SECCOMP_GET_ACTION_AVAIL: libc::c_ulong = 2;++const SECCOMP_RET_KILL_PROCESS: u32 = 0x8000_0000;+const SECCOMP_RET_KILL_THREAD: u32 = 0x0000_0000;+const SECCOMP_RET_ERRNO: u32 = 0x0005_0000;+const SECCOMP_RET_ALLOW: u32 = 0x7fff_0000;++const BPF_LD: u16 = 0x00;+const BPF_W: u16 = 0x00;+const BPF_ABS: u16 = 0x20;+const BPF_ALU: u16 = 0x04;+const BPF_AND: u16 = 0x50;+const BPF_JMP: u16 = 0x05;+const BPF_JEQ: u16 = 0x10;+const BPF_JGE: u16 = 0x30;+const BPF_K: u16 = 0x00;+const BPF_RET: u16 = 0x06;++/// Offsets into `struct seccomp_data`.+const SECCOMP_DATA_NR: u32 = 0;+const SECCOMP_DATA_ARCH: u32 = 4;+/// Low half of `args[0]` on a little-endian target.+const SECCOMP_DATA_ARG0_LOW: u32 = 16;++#[cfg(target_arch = "x86_64")]+const AUDIT_ARCH: u32 = 0xC000_003E;+#[cfg(target_arch = "aarch64")]+const AUDIT_ARCH: u32 = 0xC000_00B7;+/// x32 shares `AUDIT_ARCH_X86_64` but renumbers its syscalls, so a filter+/// written against the 64-bit table does not describe it.+#[cfg(target_arch = "x86_64")]+const X32_SYSCALL_BIT: u32 = 0x4000_0000;++#[repr(C)]+struct LandlockRulesetAttr {+ handled_access_fs: u64,+}++// The kernel declares `landlock_path_beneath_attr` as packed; an unpacked+// layout would add four bytes of tail padding and be rejected.+#[repr(C, packed)]+struct LandlockPathBeneathAttr {+ allowed_access: u64,+ parent_fd: i32,+}++#[repr(C)]+#[derive(Clone, Copy)]+struct SockFilter {+ code: u16,+ jt: u8,+ jf: u8,+ k: u32,+}++#[repr(C)]+struct SockFprog {+ len: u16,+ filter: *const SockFilter,+}++pub(super) async fn spawn(+ executable: &Path,+ args: &[String],+ working_directory: &Path,+ boundary: &FilesystemBoundary,+ limits: &ContainmentLimits,+) -> Result<ContainedChild, VisualParseError> {+ // Both rulesets are built in the parent so an unsupported kernel or+ // architecture is reported explicitly rather than as an opaque+ // `pre_exec` failure after the point of no return.+ let ruleset = build_landlock_ruleset(boundary)?;+ let mut filter = build_seccomp_filter()?;++ let mut command = base_command(executable, working_directory);+ command.args(args).current_dir(working_directory);+ command.process_group(0);++ let max_memory_bytes = limits.max_memory_bytes;+ let max_cpu_seconds = limits.max_cpu_seconds();+ let max_open_files = limits.max_open_files;+ // Runs between fork and exec. Every call below is a raw syscall, nothing+ // allocates, and both the ruleset descriptor and the filter program were+ // materialized before the fork.+ unsafe {+ command.as_std_mut().pre_exec(move || {+ let parent = libc::getppid();+ if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL) != 0 {+ return Err(std::io::Error::last_os_error());+ }+ // The parent may have exited between the fork and the prctl, in+ // which case the death signal was already missed.+ if libc::getppid() != parent {+ libc::raise(libc::SIGKILL);+ }+ apply_resource_limits(Some(max_memory_bytes), max_cpu_seconds, max_open_files)?;+ if libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0 {+ return Err(std::io::Error::last_os_error());+ }+ if libc::syscall(+ SYS_LANDLOCK_RESTRICT_SELF,+ ruleset.as_raw_fd(),+ 0 as libc::c_ulong,+ ) != 0+ {+ return Err(std::io::Error::last_os_error());+ }+ // Mark every non-stdio descriptor close-on-exec. This includes+ // descriptors inherited from the host and closes the otherwise+ // serious bypass where an already-open file or socket survives+ // into the worker past Landlock/seccomp installation.+ if libc::syscall(SYS_CLOSE_RANGE, 3_u32, u32::MAX, CLOSE_RANGE_CLOEXEC) != 0 {+ return Err(std::io::Error::last_os_error());+ }+ // Classic seccomp cannot compare an argument with the caller's+ // dynamic TGID. Patch the prebuilt comparison after fork, before+ // installing it, so `tgkill` remains available to the worker's+ // own threads without becoming a same-UID signalling primitive.+ filter.instructions[filter.worker_tgid_instruction].k = libc::getpid() as u32;+ let program = SockFprog {+ len: filter.instructions.len() as u16,+ filter: filter.instructions.as_ptr(),+ };+ if libc::syscall(+ libc::SYS_seccomp,+ SECCOMP_SET_MODE_FILTER,+ 0 as libc::c_ulong,+ &program as *const SockFprog,+ ) != 0+ {+ return Err(std::io::Error::last_os_error());+ }+ Ok(())+ });+ }++ let mut child = command.spawn().map_err(spawn_error)?;+ let stdin = child.stdin.take();+ let stdout = child.stdout.take();+ // seccomp denies `fork`, `clone` without `CLONE_THREAD`, `setsid` and+ // `setpgid`, so the worker is provably the only member of its process+ // group and the group is empty once it is reaped.+ let guard = ProcessGroupGuard::new(child.id(), false);+ Ok(ContainedChild {+ guard,+ process: Process::new(child),+ stdin,+ stdout,+ })+}++fn landlock_abi() -> Option<u32> {+ let abi = unsafe {+ libc::syscall(+ SYS_LANDLOCK_CREATE_RULESET,+ std::ptr::null::<LandlockRulesetAttr>(),+ 0 as libc::size_t,+ LANDLOCK_CREATE_RULESET_VERSION as libc::c_ulong,+ )+ };+ u32::try_from(abi).ok().filter(|abi| *abi >= 1)+}++fn build_landlock_ruleset(boundary: &FilesystemBoundary) -> Result<OwnedFd, VisualParseError> {+ let Some(abi) = landlock_abi() else {+ return Err(unsupported_error(+ "this Linux kernel does not provide the Landlock filesystem containment the perception worker requires",+ ));+ };+ if abi < 3 {+ return Err(unsupported_error(+ "this Linux kernel cannot restrict file truncation for the perception worker",+ ));+ }++ let attribute = LandlockRulesetAttr {+ handled_access_fs: LANDLOCK_HANDLED_ACCESS,+ };+ let ruleset = unsafe {+ libc::syscall(+ SYS_LANDLOCK_CREATE_RULESET,+ &attribute as *const LandlockRulesetAttr,+ std::mem::size_of::<LandlockRulesetAttr>() as libc::size_t,+ 0 as libc::c_ulong,+ )+ };+ let ruleset = RawFd::try_from(ruleset)+ .ok()+ .filter(|fd| *fd >= 0)+ .ok_or_else(|| {+ containment_error(+ "failed to create the Landlock ruleset for the perception worker",+ os_detail(&std::io::Error::last_os_error()),+ )+ })?;+ let ruleset = unsafe { OwnedFd::from_raw_fd(ruleset) };++ // Writable roots are readable but intentionally non-executable. Model+ // artifacts can be memory-mapped without granting execution of bytes the+ // worker created or modified.+ for path in &boundary.writable {+ add_rule(&ruleset, path, LANDLOCK_WRITABLE_TREE, true)?;+ }+ for path in &boundary.readable {+ add_rule(&ruleset, path, LANDLOCK_READ_TREE, true)?;+ }+ for path in &boundary.executables {+ add_rule(&ruleset, path, LANDLOCK_EXECUTABLE_FILE, true)?;+ }+ for path in SYSTEM_READ_TREES {+ add_rule(&ruleset, Path::new(path), LANDLOCK_SYSTEM_READ_TREE, false)?;+ }+ for path in SYSTEM_READ_FILES {+ add_rule(&ruleset, Path::new(path), LANDLOCK_READ_FILE_ONLY, false)?;+ }+ for path in DEVICE_NODES {+ add_rule(&ruleset, Path::new(path), LANDLOCK_DEVICE_ACCESS, false)?;+ }+ Ok(ruleset)+}++fn add_rule(+ ruleset: &OwnedFd,+ path: &Path,+ allowed_access: u64,+ required: bool,+) -> Result<(), VisualParseError> {+ let Some(parent) = open_path(path, required)? else {+ return Ok(());+ };+ let attribute = LandlockPathBeneathAttr {+ allowed_access,+ parent_fd: parent.as_raw_fd(),+ };+ let added = unsafe {+ libc::syscall(+ SYS_LANDLOCK_ADD_RULE,+ ruleset.as_raw_fd(),+ LANDLOCK_RULE_PATH_BENEATH as libc::c_ulong,+ &attribute as *const LandlockPathBeneathAttr,+ 0 as libc::c_ulong,+ )+ };+ if added != 0 {+ return Err(containment_error(+ "failed to grant a path in the Landlock ruleset for the perception worker",+ os_detail(&std::io::Error::last_os_error()),+ ));+ }+ Ok(())+}++fn open_path(path: &Path, required: bool) -> Result<Option<OwnedFd>, VisualParseError> {+ let raw = CString::new(path.as_os_str().as_bytes()).map_err(|_| {+ containment_error(+ "a path for the Linux worker sandbox contains an interior NUL",+ None,+ )+ })?;+ // `O_PATH` resolves the object without opening it for I/O. Symlinks are+ // followed deliberately: the worker paths are canonicalized before they+ // reach this function, and the system directories below are symlinks to+ // their merged-`/usr` targets on most distributions.+ let fd = unsafe { libc::open(raw.as_ptr(), libc::O_PATH | libc::O_CLOEXEC) };+ if fd < 0 {+ if !required {+ return Ok(None);+ }+ return Err(containment_error(+ "failed to open a path for the Linux worker sandbox",+ os_detail(&std::io::Error::last_os_error()),+ ));+ }+ Ok(Some(unsafe { OwnedFd::from_raw_fd(fd) }))+}++/// Syscalls the worker may never make, on every architecture this filter+/// supports.+///+/// The network group is complete rather than domain-filtered: an `AF_UNIX`+/// endpoint reaches the X11, Wayland, D-Bus and `ssh-agent` sockets, which is+/// desktop capture, input injection and credential authority, so the worker+/// gets no socket at all. The `io_uring` group is denied because seccomp does+/// not see the operations submitted through a ring, which would otherwise+/// reopen every route above.+#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]+fn denied_syscalls() -> Vec<libc::c_long> {+ let mut denied = vec![+ // Sockets: creation, connection and every operation on one.+ libc::SYS_socket,+ libc::SYS_socketpair,+ libc::SYS_connect,+ libc::SYS_bind,+ libc::SYS_listen,+ libc::SYS_accept,+ libc::SYS_accept4,+ libc::SYS_sendto,+ libc::SYS_recvfrom,+ libc::SYS_sendmsg,+ libc::SYS_recvmsg,+ libc::SYS_sendmmsg,+ libc::SYS_recvmmsg,+ libc::SYS_getsockname,+ libc::SYS_getpeername,+ libc::SYS_setsockopt,+ libc::SYS_getsockopt,+ libc::SYS_shutdown,+ // io_uring: an unfiltered asynchronous path to all of the above.+ libc::SYS_io_uring_setup,+ libc::SYS_io_uring_enter,+ libc::SYS_io_uring_register,+ // Debugger attachment and cross-process memory or descriptor access.+ libc::SYS_ptrace,+ libc::SYS_process_vm_readv,+ libc::SYS_process_vm_writev,+ libc::SYS_kcmp,+ libc::SYS_pidfd_open,+ libc::SYS_pidfd_getfd,+ libc::SYS_pidfd_send_signal,+ // Signalling an unrelated process or the whole session. `tgkill` is+ // handled separately so only this worker's TGID is admitted; `tkill`+ // has no TGID argument and therefore cannot be constrained safely.+ libc::SYS_kill,+ libc::SYS_tkill,+ libc::SYS_rt_sigqueueinfo,+ libc::SYS_rt_tgsigqueueinfo,+ // Filesystem policy escapes: a file handle bypasses path resolution,+ // and a mount changes what a Landlock path even refers to.+ libc::SYS_name_to_handle_at,+ libc::SYS_open_by_handle_at,+ libc::SYS_mount,+ libc::SYS_umount2,+ libc::SYS_pivot_root,+ libc::SYS_chroot,+ // Namespaces, kernel objects and keyrings.+ libc::SYS_unshare,+ libc::SYS_setns,+ libc::SYS_bpf,+ libc::SYS_perf_event_open,+ libc::SYS_userfaultfd,+ libc::SYS_add_key,+ libc::SYS_keyctl,+ libc::SYS_request_key,+ libc::SYS_init_module,+ libc::SYS_finit_module,+ libc::SYS_delete_module,+ libc::SYS_kexec_load,+ libc::SYS_kexec_file_load,+ libc::SYS_reboot,+ libc::SYS_syslog,+ libc::SYS_acct,+ libc::SYS_swapon,+ libc::SYS_swapoff,+ libc::SYS_quotactl,+ // Execution-environment changes, including disabling ASLR.+ libc::SYS_personality,+ // The worker must remain its own process-group leader so the guard can+ // always reap it.+ libc::SYS_setsid,+ libc::SYS_setpgid,+ ];+ // Process creation. Runtime threads stay available through the+ // `CLONE_THREAD` rule in the assembled filter.+ #[cfg(target_arch = "x86_64")]+ denied.extend([libc::SYS_fork, libc::SYS_vfork]);+ denied+}++#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]+fn build_seccomp_filter() -> Result<SeccompFilter, VisualParseError> {+ Err(unsupported_error(+ "the perception worker has no seccomp containment for this Linux architecture",+ ))+}++#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]+fn build_seccomp_filter() -> Result<SeccompFilter, VisualParseError> {+ if !seccomp_action_available(SECCOMP_RET_ERRNO) {+ return Err(unsupported_error(+ "this Linux kernel does not provide the seccomp containment the perception worker requires",+ ));+ }+ // A foreign audit architecture means the syscall numbers below do not+ // describe the calling ABI, so the safe response is to stop the process+ // rather than let an unfiltered syscall through.+ let mismatch = if seccomp_action_available(SECCOMP_RET_KILL_PROCESS) {+ SECCOMP_RET_KILL_PROCESS+ } else {+ SECCOMP_RET_KILL_THREAD+ };+ Ok(assemble_seccomp_filter(mismatch))+}++/// Assemble the BPF program. Kept free of host probes so its shape can be+/// asserted on any machine.+#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]+fn assemble_seccomp_filter(mismatch: u32) -> SeccompFilter {+ let denied = SECCOMP_RET_ERRNO | (libc::EPERM as u32 & 0xffff);+ let unavailable = SECCOMP_RET_ERRNO | (libc::ENOSYS as u32 & 0xffff);++ let mut filter = vec![+ load(SECCOMP_DATA_ARCH),+ jump_equal(AUDIT_ARCH, 1, 0),+ ret(mismatch),+ load(SECCOMP_DATA_NR),+ ];+ #[cfg(target_arch = "x86_64")]+ filter.extend([jump_at_least(X32_SYSCALL_BIT, 0, 1), ret(mismatch)]);+ for number in denied_syscalls() {+ filter.extend([jump_equal(number as u32, 0, 1), ret(denied)]);+ }+ filter.extend([+ jump_equal(libc::SYS_tgkill as u32, 0, 4),+ load(SECCOMP_DATA_ARG0_LOW),+ // Filled with the worker TGID between fork and filter installation.+ jump_equal(0, 1, 0),+ ret(denied),+ load(SECCOMP_DATA_NR),+ ]);+ let worker_tgid_instruction = filter.len() - 3;+ filter.extend([+ // Do not let the worker clear the parent-death signal installed just+ // before this filter. Other prctl operations (for example thread names)+ // remain available.+ jump_equal(libc::SYS_prctl as u32, 0, 4),+ load(SECCOMP_DATA_ARG0_LOW),+ jump_equal(libc::PR_SET_PDEATHSIG as u32, 0, 1),+ ret(denied),+ load(SECCOMP_DATA_NR),+ // Returning ENOSYS for clone3 makes pthread implementations fall back+ // to clone, whose flags seccomp can inspect directly.+ jump_equal(libc::SYS_clone3 as u32, 0, 1),+ ret(unavailable),+ jump_equal(libc::SYS_clone as u32, 0, 4),+ load(SECCOMP_DATA_ARG0_LOW),+ and(libc::CLONE_THREAD as u32),+ jump_equal(libc::CLONE_THREAD as u32, 1, 0),+ ret(denied),+ load(SECCOMP_DATA_NR),+ ret(SECCOMP_RET_ALLOW),+ ]);+ SeccompFilter {+ instructions: filter,+ worker_tgid_instruction,+ }+}++struct SeccompFilter {+ instructions: Vec<SockFilter>,+ worker_tgid_instruction: usize,+}++#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]+fn seccomp_action_available(action: u32) -> bool {+ unsafe {+ libc::syscall(+ libc::SYS_seccomp,+ SECCOMP_GET_ACTION_AVAIL,+ 0 as libc::c_ulong,+ &action as *const u32,+ ) == 0+ }+}++fn load(offset: u32) -> SockFilter {+ SockFilter {+ code: BPF_LD | BPF_W | BPF_ABS,+ jt: 0,+ jf: 0,+ k: offset,+ }+}++fn jump_equal(value: u32, jt: u8, jf: u8) -> SockFilter {+ SockFilter {+ code: BPF_JMP | BPF_JEQ | BPF_K,+ jt,+ jf,+ k: value,+ }+}++#[cfg(target_arch = "x86_64")]+fn jump_at_least(value: u32, jt: u8, jf: u8) -> SockFilter {+ SockFilter {+ code: BPF_JMP | BPF_JGE | BPF_K,+ jt,+ jf,+ k: value,+ }+}++fn and(value: u32) -> SockFilter {+ SockFilter {+ code: BPF_ALU | BPF_AND | BPF_K,+ jt: 0,+ jf: 0,+ k: value,+ }+}++fn ret(action: u32) -> SockFilter {+ SockFilter {+ code: BPF_RET | BPF_K,+ jt: 0,+ jf: 0,+ k: action,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn evaluate_filter(filter: &[SockFilter], syscall: libc::c_long, arg0: u32) -> u32 {+ let mut accumulator = 0_u32;+ let mut pc = 0_usize;+ loop {+ let instruction = filter[pc];+ match instruction.code {+ code if code == BPF_LD | BPF_W | BPF_ABS => {+ accumulator = match instruction.k {+ SECCOMP_DATA_ARCH => AUDIT_ARCH,+ SECCOMP_DATA_NR => syscall as u32,+ SECCOMP_DATA_ARG0_LOW => arg0,+ offset => panic!("unexpected seccomp_data offset {offset}"),+ };+ pc += 1;+ }+ code if code == BPF_JMP | BPF_JEQ | BPF_K => {+ pc += 1 + usize::from(if accumulator == instruction.k {+ instruction.jt+ } else {+ instruction.jf+ });+ }+ #[cfg(target_arch = "x86_64")]+ code if code == BPF_JMP | BPF_JGE | BPF_K => {+ pc += 1 + usize::from(if accumulator >= instruction.k {+ instruction.jt+ } else {+ instruction.jf+ });+ }+ code if code == BPF_ALU | BPF_AND | BPF_K => {+ accumulator &= instruction.k;+ pc += 1;+ }+ code if code == BPF_RET | BPF_K => return instruction.k,+ code => panic!("unexpected BPF instruction {code:#x}"),+ }+ }+ }++ #[test]+ fn the_filter_denies_every_socket_and_io_uring_entry_point() {+ let denied = denied_syscalls();+ for required in [+ libc::SYS_socket,+ libc::SYS_socketpair,+ libc::SYS_connect,+ libc::SYS_io_uring_setup,+ libc::SYS_io_uring_enter,+ libc::SYS_io_uring_register,+ libc::SYS_ptrace,+ libc::SYS_process_vm_readv,+ libc::SYS_process_vm_writev,+ libc::SYS_open_by_handle_at,+ ] {+ assert!(+ denied.contains(&required),+ "syscall {required} is not denied by the perception worker filter"+ );+ }+ }++ #[test]+ fn the_filter_fits_the_kernel_program_ceiling_with_single_byte_jumps() {+ let filter = assemble_seccomp_filter(SECCOMP_RET_KILL_PROCESS);+ assert!(+ filter.instructions.len() < 4096,+ "filter is {} long",+ filter.instructions.len()+ );+ assert!(+ filter+ .instructions+ .iter()+ .all(|instruction| instruction.jt <= 4 && instruction.jf <= 4),+ "a jump offset outside this filter's fixed layout would land on the wrong instruction"+ );+ }++ #[test]+ fn signalling_requires_the_workers_exact_thread_group() {+ let mut filter = assemble_seccomp_filter(SECCOMP_RET_KILL_PROCESS);+ assert!(denied_syscalls().contains(&libc::SYS_kill));+ assert!(denied_syscalls().contains(&libc::SYS_tkill));+ assert!(denied_syscalls().contains(&libc::SYS_rt_sigqueueinfo));+ assert!(denied_syscalls().contains(&libc::SYS_rt_tgsigqueueinfo));+ assert!(!denied_syscalls().contains(&libc::SYS_tgkill));+ let check = filter.instructions[filter.worker_tgid_instruction];+ assert_eq!(check.code, BPF_JMP | BPF_JEQ | BPF_K);+ assert_eq!((check.jt, check.jf, check.k), (1, 0, 0));++ filter.instructions[filter.worker_tgid_instruction].k = 4242;+ let denied = SECCOMP_RET_ERRNO | (libc::EPERM as u32 & 0xffff);+ assert_eq!(+ evaluate_filter(&filter.instructions, libc::SYS_tgkill, 4242),+ SECCOMP_RET_ALLOW+ );+ assert_eq!(+ evaluate_filter(&filter.instructions, libc::SYS_tgkill, 4243),+ denied+ );+ assert_eq!(+ evaluate_filter(&filter.instructions, libc::SYS_tkill, 4242),+ denied+ );+ assert_eq!(+ evaluate_filter(&filter.instructions, libc::SYS_kill, 4242),+ denied+ );+ assert_eq!(+ evaluate_filter(&filter.instructions, libc::SYS_rt_sigqueueinfo, 4242),+ denied+ );+ assert_eq!(+ evaluate_filter(&filter.instructions, libc::SYS_rt_tgsigqueueinfo, 4242),+ denied+ );+ }++ #[test]+ fn writable_roots_never_grant_execute() {+ assert_eq!(LANDLOCK_WRITABLE_TREE & LANDLOCK_ACCESS_FS_EXECUTE, 0);+ assert_eq!(LANDLOCK_READ_TREE & LANDLOCK_ACCESS_FS_EXECUTE, 0);+ assert_ne!(LANDLOCK_WRITABLE_TREE & LANDLOCK_ACCESS_FS_WRITE_FILE, 0);+ assert_ne!(LANDLOCK_WRITABLE_TREE & LANDLOCK_ACCESS_FS_READ_FILE, 0);+ assert_ne!(LANDLOCK_EXECUTABLE_FILE & LANDLOCK_ACCESS_FS_EXECUTE, 0);+ assert_ne!(LANDLOCK_SYSTEM_READ_TREE & LANDLOCK_ACCESS_FS_EXECUTE, 0);+ }++ #[test]+ fn the_device_allowlist_never_grants_a_directory_or_raw_memory() {+ for node in DEVICE_NODES {+ assert!(+ !matches!(*node, "/dev" | "/dev/mem" | "/dev/kmem" | "/dev/shm"),+ "{node} must not be in the worker device allowlist"+ );+ }+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/perception_client/containment/macos.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/perception_client/containment/macos.rsnew file mode 100644index 0000000000..28f9d81200--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/perception_client/containment/macos.rs@@ -0,0 +1,655 @@+//! macOS worker containment: a deny-by-default Seatbelt profile, a trusted+//! parent-death sentinel, inherited descriptor closure, resource limits and a+//! supervisor-sampled memory ceiling.+//!+//! The profile is applied by launching the worker through+//! `/usr/bin/sandbox-exec`, which is the only supported way for a parent to+//! impose a Seatbelt profile on a child it does not control. `sandbox_init`+//! cannot be used from a `pre_exec` hook: it allocates and talks to `sandboxd`,+//! neither of which is async-signal-safe after `fork`. A profile that fails to+//! compile makes `sandbox-exec` exit before it execs anything, so a malformed+//! profile can never yield an unsandboxed worker, and a missing `sandbox-exec`+//! fails the launch outright.+//!+//! Darwin has no `PR_SET_PDEATHSIG`, and a `kqueue` watch cannot be installed+//! across `exec`. The worker is therefore launched underneath a fixed+//! `/bin/sh` script that holds one extra descriptor: the read end of a pipe+//! whose write end never leaves the Driver. The script backgrounds a read on+//! that descriptor, closes its own copy, and then `exec`s `sandbox-exec`, so+//! the shell's pid — which is also the process-group id — becomes the worker.+//! When the Driver dies for any reason, including `SIGKILL`, the pipe reaches+//! end of file and the sentinel kills the whole process group.+//!+//! Darwin also has no usable hard address-space limit: `RLIMIT_AS` is an alias+//! for `RLIMIT_RSS`, which XNU does not enforce. Rather than advertise an+//! unenforced ceiling, the supervisor samples the worker's resident footprint+//! and kills the tree when it exceeds the bound. [`super::capabilities`]+//! reports that as [`super::MemoryLimitEnforcement::SupervisorSampling`].++use std::io::Write as _;+use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};+use std::os::unix::fs::OpenOptionsExt as _;+use std::os::unix::process::CommandExt;+use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::Arc;+use std::time::Duration;++use cua_driver_contract::VisualParseError;++use super::unix::{+ apply_resource_limits, base_command, close_inherited_descriptors, ProcessGroupGuard,+};+use super::{+ containment_error, os_detail, spawn_error, unsupported_error, ContainedChild,+ ContainmentLimits, FilesystemBoundary,+};++pub(super) type Process = super::unix::Process;+pub(super) type WorkerStdin = tokio::process::ChildStdin;+pub(super) type WorkerStdout = tokio::process::ChildStdout;++const SHELL: &str = "/bin/sh";+const SANDBOX_EXEC: &str = "/usr/bin/sandbox-exec";+const PROFILE_FILE: &str = ".cua-perception-sandbox.sb";++/// The descriptor the sentinel reads. Chosen because `pre_exec` runs after the+/// standard library has already placed the protocol pipes on 0, 1 and 2.+const SENTINEL_DESCRIPTOR: RawFd = 3;++/// Backgrounds a blocking read on the sentinel descriptor, drops its own copy+/// of that descriptor so the worker never sees it, and replaces itself with+/// `sandbox-exec`. `$$` stays the pid of the original shell across both the+/// subshell and the `exec`, and that pid is the process-group id, so the kill+/// reaches the worker and anything it left behind.+const PARENT_DEATH_SENTINEL: &str = concat!(+ "{ read -r cua_parent_gone <&3; kill -9 -$$; } 0</dev/null 1>/dev/null 2>&1 &\n",+ "exec 3<&-\n",+ "exec \"$@\"\n",+);++/// How often the supervisor samples the worker's footprint.+const MEMORY_SAMPLE_INTERVAL: Duration = Duration::from_millis(250);++/// Immutable system directories the dynamic loader and Objective-C runtime+/// read. None of them expose user data.+const SYSTEM_READ_TREES: &[&str] = &[+ "/usr/lib",+ "/System/Library",+ "/System/Volumes/Preboot/Cryptexes/OS",+ "/private/var/db/dyld",+];++/// The only devices the worker may open. `/dev` as a whole is never granted.+const DEVICE_NODES: &[&str] = &[+ "/dev/null",+ "/dev/zero",+ "/dev/random",+ "/dev/urandom",+ "/dev/dtracehelper",+];++/// The Mach services a non-GUI process needs to start and log. Everything else+/// — `com.apple.windowserver.active`, `com.apple.tccd`, `com.apple.pasteboard.1`+/// and `com.apple.SecurityServer` among them — stays denied by the profile's+/// default, which is what keeps the worker away from the Driver's own screen+/// recording, accessibility and Keychain grants.+const MACH_SERVICES: &[&str] = &[+ "com.apple.system.opendirectoryd.libinfo",+ "com.apple.system.DirectoryService.libinfo_v1",+ "com.apple.system.notification_center",+ "com.apple.system.logger",+ "com.apple.logd",+ "com.apple.diagnosticd",+];++/// Owns the worker's process group, the sentinel pipe and the memory sampler.+///+/// Field order is load-bearing. [`Drop::drop`] runs first and stops the+/// sampler; then `group` drops and kills the tree, which reaches the sentinel+/// before it can observe end of file; only then does `sentinel` close. A+/// sentinel that fired after the group was reaped could otherwise signal a+/// recycled process-group id.+pub(super) struct Guard {+ group: ProcessGroupGuard,+ /// Held only for its `Drop`: closing this end is what makes the sentinel+ /// observe end of file when the Driver goes away.+ _sentinel: OwnedFd,+ memory_watch: tokio::task::JoinHandle<()>,+}++impl Guard {+ pub(super) fn note_reaped(&mut self) {+ self.group.note_reaped();+ }++ pub(super) fn memory_ceiling_exceeded(&self) -> bool {+ self.group.memory_ceiling_exceeded()+ }+}++impl Drop for Guard {+ fn drop(&mut self) {+ self.memory_watch.abort();+ }+}++pub(super) async fn spawn(+ executable: &Path,+ args: &[String],+ working_directory: &Path,+ boundary: &FilesystemBoundary,+ limits: &ContainmentLimits,+) -> Result<ContainedChild, VisualParseError> {+ for required in [SHELL, SANDBOX_EXEC] {+ if !Path::new(required).is_file() {+ return Err(unsupported_error(+ "this macOS build cannot contain the perception worker: sandbox-exec or /bin/sh is unavailable",+ ));+ }+ }+ // `/bin/sh` is what is actually spawned, so a missing worker would+ // otherwise surface as a crashed worker instead of a failed launch.+ if !executable.is_file() {+ return Err(spawn_error(std::io::Error::from_raw_os_error(libc::ENOENT)));+ }+ let profile_path = write_profile(working_directory, boundary)?;+ let (sentinel_read, sentinel_write) = sentinel_pipe()?;++ let mut command = base_command(Path::new(SHELL), working_directory);+ command+ .arg("-c")+ .arg(PARENT_DEATH_SENTINEL)+ .arg("cua-perception-supervisor")+ .arg(SANDBOX_EXEC)+ .arg("-f")+ .arg(&profile_path)+ .arg(executable)+ .args(args);+ command.current_dir(working_directory);+ command.process_group(0);++ let sentinel_source = sentinel_read.as_raw_fd();+ if sentinel_source < SENTINEL_DESCRIPTOR {+ return Err(containment_error(+ "the perception worker sentinel pipe landed on a reserved descriptor",+ None,+ ));+ }+ let max_cpu_seconds = limits.max_cpu_seconds();+ let max_open_files = limits.max_open_files;+ // Runs between fork and exec using only raw syscalls. The limits and the+ // descriptor table survive the exec into `/bin/sh`, its exec of+ // `sandbox-exec`, and that program's exec of the worker itself.+ unsafe {+ command.as_std_mut().pre_exec(move || {+ if sentinel_source != SENTINEL_DESCRIPTOR+ && libc::dup2(sentinel_source, SENTINEL_DESCRIPTOR) < 0+ {+ return Err(std::io::Error::last_os_error());+ }+ close_inherited_descriptors(Some(SENTINEL_DESCRIPTOR))?;+ apply_resource_limits(None, max_cpu_seconds, max_open_files)+ });+ }++ let mut child = command.spawn().map_err(spawn_error)?;+ drop(sentinel_read);+ let stdin = child.stdin.take();+ let stdout = child.stdout.take();+ let pid = child.id();+ // The sentinel subshell stays a live member of the group, so the group id+ // cannot be recycled and remains safe to signal even after the leader has+ // been reaped.+ let group = ProcessGroupGuard::new(pid, true);+ let Some(sample_pid) = pid.and_then(|pid| i32::try_from(pid).ok()) else {+ return Err(containment_error(+ "failed to identify the perception worker for memory enforcement",+ None,+ ));+ };+ if resident_bytes(sample_pid).is_none() {+ unsafe {+ libc::kill(-sample_pid, libc::SIGKILL);+ }+ return Err(containment_error(+ "failed to install the perception worker memory sampler",+ None,+ ));+ }+ let memory_watch = watch_memory(sample_pid, limits.max_memory_bytes, group.memory_flag());+ Ok(ContainedChild {+ guard: Guard {+ group,+ _sentinel: sentinel_write,+ memory_watch,+ },+ process: Process::new(child),+ stdin,+ stdout,+ })+}++/// Create the sentinel pipe with both ends close-on-exec, so no other Driver+/// child can hold the write end open and keep a dead Driver's worker alive.+fn sentinel_pipe() -> Result<(OwnedFd, OwnedFd), VisualParseError> {+ let mut ends = [0 as libc::c_int; 2];+ if unsafe { libc::pipe(ends.as_mut_ptr()) } != 0 {+ return Err(containment_error(+ "failed to create the perception worker parent-death sentinel pipe",+ os_detail(&std::io::Error::last_os_error()),+ ));+ }+ let read = unsafe { OwnedFd::from_raw_fd(ends[0]) };+ let write = unsafe { OwnedFd::from_raw_fd(ends[1]) };+ for end in [&read, &write] {+ if unsafe { libc::fcntl(end.as_raw_fd(), libc::F_SETFD, libc::FD_CLOEXEC) } != 0 {+ return Err(containment_error(+ "failed to isolate the perception worker parent-death sentinel pipe",+ os_detail(&std::io::Error::last_os_error()),+ ));+ }+ }+ Ok((read, write))+}++/// Sample the worker's resident footprint and kill the tree once it exceeds the+/// ceiling. Darwin offers no kernel primitive a parent can install on a child+/// for this, so the boundary is reported as sampled rather than enforced.+fn watch_memory(+ pid: libc::c_int,+ ceiling: u64,+ exceeded: Arc<AtomicBool>,+) -> tokio::task::JoinHandle<()> {+ tokio::spawn(async move {+ loop {+ tokio::time::sleep(MEMORY_SAMPLE_INTERVAL).await;+ let Some(resident) = resident_bytes(pid) else {+ // ESRCH proves the worker is gone. Any other sampling failure+ // leaves the ceiling unobservable, so kill the group rather+ // than silently continuing without enforcement.+ if unsafe { libc::kill(pid, 0) } == 0+ || std::io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH)+ {+ unsafe {+ libc::kill(-pid, libc::SIGKILL);+ }+ }+ return;+ };+ if resident > ceiling {+ exceeded.store(true, Ordering::Release);+ unsafe {+ libc::kill(-pid, libc::SIGKILL);+ }+ return;+ }+ }+ })+}++/// `struct proc_taskinfo` from `<libproc.h>`. The layout is stable ABI.+#[repr(C)]+#[derive(Clone, Copy)]+struct ProcTaskInfo {+ virtual_size: u64,+ resident_size: u64,+ total_user: u64,+ total_system: u64,+ threads_user: u64,+ threads_system: u64,+ policy: i32,+ faults: i32,+ pageins: i32,+ cow_faults: i32,+ messages_sent: i32,+ messages_received: i32,+ syscalls_mach: i32,+ syscalls_unix: i32,+ context_switches: i32,+ thread_count: i32,+ running_threads: i32,+ priority: i32,+}++/// `PROC_PIDTASKINFO` from `<sys/proc_info.h>`.+const PROC_PIDTASKINFO: libc::c_int = 4;++extern "C" {+ fn proc_pidinfo(+ pid: libc::c_int,+ flavor: libc::c_int,+ arg: u64,+ buffer: *mut libc::c_void,+ buffersize: libc::c_int,+ ) -> libc::c_int;+}++fn resident_bytes(pid: libc::c_int) -> Option<u64> {+ let mut info = ProcTaskInfo {+ virtual_size: 0,+ resident_size: 0,+ total_user: 0,+ total_system: 0,+ threads_user: 0,+ threads_system: 0,+ policy: 0,+ faults: 0,+ pageins: 0,+ cow_faults: 0,+ messages_sent: 0,+ messages_received: 0,+ syscalls_mach: 0,+ syscalls_unix: 0,+ context_switches: 0,+ thread_count: 0,+ running_threads: 0,+ priority: 0,+ };+ let size = std::mem::size_of::<ProcTaskInfo>() as libc::c_int;+ let written = unsafe {+ proc_pidinfo(+ pid,+ PROC_PIDTASKINFO,+ 0,+ std::ptr::addr_of_mut!(info).cast(),+ size,+ )+ };+ (written == size).then_some(info.resident_size)+}++/// Write the Seatbelt profile into the private working directory and hand+/// `sandbox-exec` a path rather than the policy text, so the profile and the+/// worker's temporary path never appear in `ps` output.+fn write_profile(+ working_directory: &Path,+ boundary: &FilesystemBoundary,+) -> Result<PathBuf, VisualParseError> {+ let path = working_directory.join(PROFILE_FILE);+ let profile = build_profile(boundary)?;+ let mut file = std::fs::OpenOptions::new()+ .write(true)+ .create_new(true)+ .mode(0o600)+ .open(&path)+ .map_err(|cause| {+ containment_error(+ "failed to create the macOS perception worker sandbox profile",+ os_detail(&cause),+ )+ })?;+ file.write_all(profile.as_bytes()).map_err(|cause| {+ containment_error(+ "failed to write the macOS perception worker sandbox profile",+ os_detail(&cause),+ )+ })?;+ Ok(path)+}++/// Deny-by-default Seatbelt profile.+///+/// Reads, executes and writes are confined to the exact worker bundle, runtime,+/// model and working-directory paths plus the immutable system runtime+/// directories the loader needs. Network, fork, cross-process inspection,+/// IOKit, and every Mach service outside a short logging allowlist are denied+/// by the default rule.+fn build_profile(boundary: &FilesystemBoundary) -> Result<String, VisualParseError> {+ let mut profile = String::from(+ "(version 1)\n\+ (deny default)\n\+ ; Explicit for auditability; the default rule already denies these.\n\+ (deny network*)\n\+ (deny process-fork)\n\+ (deny mach-register)\n\+ (allow sysctl-read)\n\+ (allow process-info* (target self))\n\+ (allow signal (target self))\n",+ );++ profile.push_str("(allow mach-lookup\n");+ for service in MACH_SERVICES {+ profile.push_str(" (global-name \"");+ profile.push_str(&escape(service));+ profile.push_str("\")\n");+ }+ profile.push_str(")\n");+ profile.push_str(+ "(allow ipc-posix-shm-read-data (ipc-posix-name \"apple.shm.notification_center\"))\n",+ );++ let mut metadata_paths = vec![PathBuf::from("/"), PathBuf::from("/var")];+ let mut add_ancestors = |path: &Path| {+ let mut parent = path.parent();+ while let Some(ancestor) = parent {+ metadata_paths.push(ancestor.to_path_buf());+ parent = ancestor.parent();+ }+ };+ for path in boundary+ .readable+ .iter()+ .chain(&boundary.writable)+ .chain(&boundary.executables)+ {+ add_ancestors(path);+ }+ for path in SYSTEM_READ_TREES.iter().chain(DEVICE_NODES) {+ add_ancestors(Path::new(path));+ }+ metadata_paths.sort();+ metadata_paths.dedup();+ let metadata = metadata_paths+ .iter()+ .map(|path| literal_rule(path))+ .collect::<Result<Vec<_>, _>>()?;+ push_rule(&mut profile, "file-read-metadata", metadata.iter());++ // A literal directory rule permits traversal and directory inspection but+ // cannot expose any file below it. Some runtimes inspect `/` at startup.+ let mut readable = vec![" (literal \"/\")\n".to_owned()];+ for path in &boundary.readable {+ readable.push(subpath_rule(path)?);+ }+ for path in SYSTEM_READ_TREES {+ if Path::new(path).exists() {+ readable.push(subpath_rule(Path::new(path))?);+ }+ }+ let devices: Vec<String> = DEVICE_NODES+ .iter()+ .filter(|node| Path::new(node).exists())+ .map(|node| format!(" (literal \"{}\")\n", escape(node)))+ .collect();++ push_rule(&mut profile, "file-read*", readable.iter().chain(&devices));+ let executable: Vec<String> = boundary+ .executables+ .iter()+ .map(|path| literal_rule(path))+ .collect::<Result<_, _>>()?;+ let mut mappable = executable.clone();+ for path in SYSTEM_READ_TREES {+ if Path::new(path).exists() {+ mappable.push(subpath_rule(Path::new(path))?);+ }+ }+ push_rule(&mut profile, "file-map-executable", mappable.iter());+ push_rule(&mut profile, "process-exec*", executable.iter());+ push_rule(&mut profile, "file-ioctl", devices.iter());+ push_rule(&mut profile, "file-write-data", devices.iter());++ let mut writable = Vec::new();+ for path in &boundary.writable {+ writable.push(subpath_rule(path)?);+ }+ push_rule(&mut profile, "file-write*", writable.iter());+ Ok(profile)+}++fn push_rule<'a>(profile: &mut String, operation: &str, entries: impl Iterator<Item = &'a String>) {+ let mut opened = false;+ for entry in entries {+ if !opened {+ profile.push_str("(allow ");+ profile.push_str(operation);+ profile.push('\n');+ opened = true;+ }+ profile.push_str(entry);+ }+ if opened {+ profile.push_str(")\n");+ }+}++fn subpath_rule(path: &Path) -> Result<String, VisualParseError> {+ let text = path.to_str().ok_or_else(|| {+ containment_error(+ "a path for the macOS worker sandbox is not valid UTF-8",+ None,+ )+ })?;+ Ok(format!(" (subpath \"{}\")\n", escape(text)))+}++fn literal_rule(path: &Path) -> Result<String, VisualParseError> {+ let text = path.to_str().ok_or_else(|| {+ containment_error(+ "a path for the macOS worker sandbox is not valid UTF-8",+ None,+ )+ })?;+ Ok(format!(" (literal \"{}\")\n", escape(text)))+}++/// Escape a path for a Seatbelt double-quoted string literal so a crafted path+/// cannot terminate the literal and inject profile syntax.+fn escape(value: &str) -> String {+ let mut escaped = String::with_capacity(value.len());+ for character in value.chars() {+ if matches!(character, '\\' | '"') {+ escaped.push('\\');+ }+ escaped.push(character);+ }+ escaped+}++#[cfg(test)]+mod tests {+ use super::*;++ fn profile_for(readable: &[&str], writable: &[&str]) -> String {+ build_profile(&FilesystemBoundary {+ readable: readable.iter().map(PathBuf::from).collect(),+ writable: writable.iter().map(PathBuf::from).collect(),+ executables: readable.iter().map(PathBuf::from).collect(),+ })+ .unwrap()+ }++ #[test]+ fn the_profile_denies_capture_input_and_credential_authority() {+ let profile = profile_for(&["/opt/cua/worker"], &["/tmp/.tmpworker"]);+ assert!(profile.starts_with("(version 1)\n(deny default)\n"));+ // The broad grants that previously re-granted the Driver's own TCC+ // authority to the worker must not reappear.+ for forbidden in [+ "(allow mach-lookup)",+ "(allow iokit-open)",+ "(allow file-read*)\n",+ "(allow process-exec*)\n",+ "com.apple.windowserver",+ "com.apple.tccd",+ "com.apple.pasteboard",+ "com.apple.SecurityServer",+ ] {+ assert!(+ !profile.contains(forbidden),+ "the profile still contains {forbidden}:\n{profile}"+ );+ }+ assert!(profile.contains("(subpath \"/opt/cua/worker\")"));+ assert!(profile.contains("(deny process-fork)"));+ }++ #[test]+ fn writable_paths_never_widen_beyond_the_requested_roots() {+ let profile = profile_for(&["/opt/cua/worker"], &["/tmp/.tmpworker"]);+ let writes = profile+ .split("(allow file-write*\n")+ .nth(1)+ .expect("the profile grants writes");+ assert!(writes.starts_with(" (subpath \"/tmp/.tmpworker\")\n)\n"));+ }++ #[test]+ fn a_crafted_path_cannot_inject_profile_syntax() {+ let profile = profile_for(&["/opt/\") (allow default) (subpath \"/"], &["/tmp/w"]);+ assert!(profile.contains("(subpath \"/opt/\\\") (allow default) (subpath \\\"/\")"));+ assert!(!profile.contains("(allow default)\n"));+ }++ #[test]+ fn the_sentinel_script_kills_the_group_and_hides_its_descriptor() {+ assert!(PARENT_DEATH_SENTINEL.contains("read -r cua_parent_gone <&3"));+ assert!(PARENT_DEATH_SENTINEL.contains("kill -9 -$$"));+ assert!(PARENT_DEATH_SENTINEL.contains("exec 3<&-"));+ assert!(PARENT_DEATH_SENTINEL.trim_end().ends_with("exec \"$@\""));+ }++ /// Darwin has no `PR_SET_PDEATHSIG`, so the parent-death claim rests+ /// entirely on this sentinel. Closing the Driver's end of the pipe stands in+ /// for the Driver dying; a worker that ignores termination signals must+ /// still be gone afterwards.+ #[test]+ fn closing_the_sentinel_pipe_kills_a_worker_that_ignores_signals() {+ use std::os::unix::process::CommandExt as _;++ let (read, write) = sentinel_pipe().unwrap();+ let source = read.as_raw_fd();+ let mut command = std::process::Command::new(SHELL);+ command+ .arg("-c")+ .arg(PARENT_DEATH_SENTINEL)+ .arg("cua-perception-supervisor")+ .arg(SHELL)+ .arg("-c")+ .arg("trap '' TERM INT HUP; while :; do sleep 1; done")+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .process_group(0);+ unsafe {+ command.pre_exec(move || {+ if source != SENTINEL_DESCRIPTOR && libc::dup2(source, SENTINEL_DESCRIPTOR) < 0 {+ return Err(std::io::Error::last_os_error());+ }+ close_inherited_descriptors(Some(SENTINEL_DESCRIPTOR))+ });+ }+ let mut child = command.spawn().unwrap();+ drop(read);++ // The worker is alive and unreachable by an ordinary termination+ // signal before the Driver's end of the sentinel pipe closes.+ std::thread::sleep(Duration::from_millis(250));+ assert!(child.try_wait().unwrap().is_none());++ drop(write);+ let deadline = std::time::Instant::now() + Duration::from_secs(10);+ loop {+ if let Some(status) = child.try_wait().unwrap() {+ assert!(!status.success(), "the sentinel did not kill the worker");+ return;+ }+ assert!(+ std::time::Instant::now() < deadline,+ "the worker outlived its Driver"+ );+ std::thread::sleep(Duration::from_millis(50));+ }+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/perception_client/containment/unix.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/perception_client/containment/unix.rsnew file mode 100644index 0000000000..62ecee5083--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/perception_client/containment/unix.rs@@ -0,0 +1,221 @@+//! Containment pieces shared by the Unix platforms.++use std::path::Path;+use std::process::Stdio;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::Arc;++use tokio::process::Command;++use super::RawExit;++/// `getrlimit`/`setrlimit` take `__rlimit_resource_t` on glibc and `c_int`+/// everywhere else this crate builds.+#[cfg(all(target_os = "linux", target_env = "gnu"))]+type RlimitResource = libc::__rlimit_resource_t;+#[cfg(not(all(target_os = "linux", target_env = "gnu")))]+type RlimitResource = libc::c_int;++/// The worker keeps this much CPU time past its soft ceiling before the kernel+/// escalates from `SIGXCPU` to `SIGKILL`. The gap is what lets the supervisor+/// report a CPU exhaustion as `resource_limit_exceeded` instead of a crash.+const CPU_LIMIT_GRACE_SECONDS: u64 = 5;++/// Stdio and environment shape shared by every Unix platform: no inherited+/// environment, piped stdin so the worker observes parent EOF, piped stdout for+/// the framed protocol, discarded stderr, and a kill on handle drop.+///+/// `TMPDIR` points at the private working directory because writes are confined+/// to it; a runtime that spills an allocation arena into the system temporary+/// directory would otherwise fail.+pub(super) fn base_command(program: &Path, working_directory: &Path) -> Command {+ let mut command = Command::new(program);+ command+ .env_clear()+ .env("TMPDIR", working_directory)+ .env("TMP", working_directory)+ .env("TEMP", working_directory)+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::null())+ .kill_on_drop(true);+ command+}++/// Apply the CPU-time and file-descriptor ceilings, plus an address-space+/// ceiling on the targets whose kernel enforces one.+///+/// Called between `fork` and `exec`, so it uses only raw syscalls and performs+/// no allocation. `RLIMIT_NPROC` is deliberately absent: Linux and Darwin both+/// count it per real UID rather than per process tree, so it bounded nothing+/// useful while breaking the worker on any desktop whose user already owns more+/// tasks than the ceiling. Process creation is denied outright instead — by the+/// seccomp filter on Linux and by the deny-by-default Seatbelt profile on+/// macOS.+pub(super) fn apply_resource_limits(+ max_address_space_bytes: Option<u64>,+ max_cpu_seconds: u64,+ max_open_files: u32,+) -> std::io::Result<()> {+ if let Some(bytes) = max_address_space_bytes {+ #[cfg(target_os = "linux")]+ set_limit(libc::RLIMIT_AS, bytes, bytes)?;+ #[cfg(not(target_os = "linux"))]+ let _ = bytes;+ }+ set_limit(+ libc::RLIMIT_CPU,+ max_cpu_seconds,+ max_cpu_seconds.saturating_add(CPU_LIMIT_GRACE_SECONDS),+ )?;+ set_limit(+ libc::RLIMIT_NOFILE,+ u64::from(max_open_files),+ u64::from(max_open_files),+ )+}++fn set_limit(resource: RlimitResource, soft: u64, hard: u64) -> std::io::Result<()> {+ let mut current = libc::rlimit {+ rlim_cur: 0,+ rlim_max: 0,+ };+ if unsafe { libc::getrlimit(resource, &mut current) } != 0 {+ return Err(std::io::Error::last_os_error());+ }+ // An unprivileged process cannot raise its inherited hard limit, and the+ // stricter of the two is the safe choice, so clamp instead of failing.+ let clamp = |value: u64| -> libc::rlim_t {+ let requested = value as libc::rlim_t;+ if current.rlim_max == libc::RLIM_INFINITY {+ requested+ } else {+ current.rlim_max.min(requested)+ }+ };+ let limit = libc::rlimit {+ rlim_cur: clamp(soft),+ rlim_max: clamp(hard),+ };+ if unsafe { libc::setrlimit(resource, &limit) } != 0 {+ return Err(std::io::Error::last_os_error());+ }+ Ok(())+}++/// Mark every descriptor above the protocol stdio pipes close-on-exec, so no+/// file, socket or device the Driver had open survives into the worker.+///+/// `retain` stays open: macOS uses it for the parent-death sentinel pipe. Runs+/// between `fork` and `exec`, so it allocates nothing.+///+/// Linux uses `close_range(2)` instead, which is a single syscall and needs no+/// descriptor-table sweep.+#[cfg(target_os = "macos")]+pub(super) fn close_inherited_descriptors(retain: Option<libc::c_int>) -> std::io::Result<()> {+ // Read the ceiling before the descriptor limit is lowered, and cap the+ // sweep so an inherited `RLIM_INFINITY` cannot turn this into an unbounded+ // loop.+ const MAXIMUM_SWEEP: libc::c_int = 65_536;+ let ceiling = unsafe { libc::getdtablesize() }.clamp(3, MAXIMUM_SWEEP);+ for descriptor in 3..ceiling {+ if Some(descriptor) == retain {+ continue;+ }+ unsafe {+ libc::close(descriptor);+ }+ }+ if let Some(retain) = retain {+ // The sentinel descriptor must survive `exec`, so its inherited+ // close-on-exec flag is cleared explicitly.+ if unsafe { libc::fcntl(retain, libc::F_SETFD, 0) } != 0 {+ return Err(std::io::Error::last_os_error());+ }+ }+ Ok(())+}++/// Kills the worker's process group so descendants cannot outlive cancellation,+/// timeout, runtime shutdown, client drop or idle cleanup.+pub(super) struct ProcessGroupGuard {+ pid: Option<u32>,+ reaped: bool,+ /// Whether the group must still be signalled after the leader was reaped.+ ///+ /// Once the leader is reaped its process-group id can be recycled, so+ /// signalling it blindly could reach an unrelated group. Linux sets this to+ /// `false` because seccomp denies `fork`, `setsid` and `setpgid`, which+ /// proves the group is empty. macOS sets it to `true` because its+ /// parent-death sentinel is still a live member, which keeps the group id+ /// reserved and the signal correctly addressed.+ kill_group_after_reap: bool,+ memory_ceiling_exceeded: Arc<AtomicBool>,+}++impl ProcessGroupGuard {+ pub(super) fn new(pid: Option<u32>, kill_group_after_reap: bool) -> Self {+ Self {+ pid,+ reaped: false,+ kill_group_after_reap,+ memory_ceiling_exceeded: Arc::new(AtomicBool::new(false)),+ }+ }++ /// A flag a supervisor task sets when it kills the worker for exceeding its+ /// memory ceiling, so the exit is reported as a resource limit.+ pub(super) fn memory_flag(&self) -> Arc<AtomicBool> {+ Arc::clone(&self.memory_ceiling_exceeded)+ }++ pub(super) fn note_reaped(&mut self) {+ self.reaped = true;+ }++ pub(super) fn memory_ceiling_exceeded(&self) -> bool {+ self.memory_ceiling_exceeded.load(Ordering::Acquire)+ }+}++impl Drop for ProcessGroupGuard {+ fn drop(&mut self) {+ if self.reaped && !self.kill_group_after_reap {+ return;+ }+ if let Some(pid) = self.pid {+ if let Ok(pid) = i32::try_from(pid) {+ // The worker is its own process-group leader, so the negative+ // pid reaches every descendant that did not change group.+ unsafe {+ libc::kill(-pid, libc::SIGKILL);+ }+ }+ }+ }+}++/// The Unix worker process. The child owns the protocol pipes directly, so the+/// supervisor only has to reap it and classify how it ended.+pub(super) struct Process {+ child: tokio::process::Child,+}++impl Process {+ pub(super) fn new(child: tokio::process::Child) -> Self {+ Self { child }+ }++ pub(super) async fn wait(&mut self) -> std::io::Result<RawExit> {+ use std::os::unix::process::ExitStatusExt as _;++ let status = self.child.wait().await?;+ Ok(RawExit {+ success: status.success(),+ // `SIGXCPU` is only ever raised by the soft CPU ceiling installed+ // above; the hard ceiling that follows it is a plain `SIGKILL`.+ resource_limited: status.signal() == Some(libc::SIGXCPU),+ description: status.to_string(),+ })+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/perception_client/containment/unsupported.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/perception_client/containment/unsupported.rsnew file mode 100644index 0000000000..2324f685eb--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/perception_client/containment/unsupported.rs@@ -0,0 +1,50 @@+//! Fallback for targets with no perception worker containment implementation.+//!+//! Launching an unconstrained worker would be a silent downgrade of the+//! cross-platform containment contract, so the launch fails instead.+//! [`super::capabilities`] reports every boundary as absent, which makes+//! [`super::spawn`] fail closed before it ever reaches this module.++use std::path::Path;++use cua_driver_contract::VisualParseError;++use super::{unsupported_error, ContainedChild, ContainmentLimits, FilesystemBoundary, RawExit};++/// Duplex streams stand in for the protocol pipes so the cross-platform client+/// type-checks on a target that never launches a worker.+pub(super) type WorkerStdin = tokio::io::DuplexStream;+pub(super) type WorkerStdout = tokio::io::DuplexStream;++pub(super) struct Guard;++impl Guard {+ pub(super) fn note_reaped(&mut self) {}++ pub(super) fn memory_ceiling_exceeded(&self) -> bool {+ false+ }+}++pub(super) struct Process;++impl Process {+ pub(super) async fn wait(&mut self) -> std::io::Result<RawExit> {+ Err(std::io::Error::new(+ std::io::ErrorKind::Unsupported,+ "this platform never launches a contained perception worker",+ ))+ }+}++pub(super) async fn spawn(+ _executable: &Path,+ _args: &[String],+ _working_directory: &Path,+ _boundary: &FilesystemBoundary,+ _limits: &ContainmentLimits,+) -> Result<ContainedChild, VisualParseError> {+ Err(unsupported_error(+ "this platform cannot contain the perception worker, so it will not be launched",+ ))+}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/perception_client/containment/windows.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/perception_client/containment/windows.rsnew file mode 100644index 0000000000..ac9b94724a--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/perception_client/containment/windows.rs@@ -0,0 +1,3454 @@+//! Windows worker containment.+//!+//! The worker runs as an AppContainer (LowBox) identity with no capabilities,+//! inside a private Job Object, on a private desktop, holding exactly three+//! inherited handles.+//!+//! Each piece closes a specific hole:+//!+//! - An AppContainer with an empty capability set is the documented Windows+//! primitive that denies network access: without `internetClient` or+//! `privateNetworkClientServer` the token cannot reach the transport stack at+//! all. It also denies the user profile, the Credential Manager and DPAPI+//! user secrets, because none of those objects grant the container's SID.+//! The worker's own bundle, runtime, model and working-directory paths are+//! granted to that exact SID and nothing else is.+//! - `PROC_THREAD_ATTRIBUTE_HANDLE_LIST` replaces `bInheritHandles = TRUE`'s+//! "every inheritable handle in the Driver" with exactly the two protocol+//! pipes and the null device. The protocol pipes are private named pipes so+//! the parent side can stay asynchronous while the child receives ordinary+//! synchronous stdio handles.+//! - The Job Object carries kill-on-close, an active-process ceiling, a job+//! memory ceiling, a per-process CPU-time ceiling and the full set of UI+//! restrictions, so the worker cannot read or write the clipboard, use a+//! USER handle it did not create, switch desktops, or change system+//! parameters. `JOB_OBJECT_LIMIT_BREAKAWAY_OK` is deliberately not set.+//! - A private desktop means a screen capture or synthetic input attempt+//! reaches an empty desktop rather than the user's session.+//!+//! The child is created suspended and is resumed only after the job, the+//! limits, the UI restrictions and every handle boundary are installed, so no+//! worker instruction runs before its containment exists. Any failure+//! terminates the suspended process and returns a fail-closed error.++use std::ffi::{c_void, OsStr};+use std::io::{Read as _, Write as _};+use std::os::windows::ffi::{OsStrExt as _, OsStringExt as _};+use std::os::windows::io::FromRawHandle as _;+use std::path::{Path, PathBuf};+use std::time::Duration;++use cua_driver_contract::{VisualParseError, VisualParseErrorCode};+use fs2::FileExt as _;+use tokio::net::windows::named_pipe::{NamedPipeServer, PipeMode, ServerOptions};++use super::{+ containment_error, error, os_detail, spawn_error, ContainedChild, ContainmentLimits,+ FilesystemBoundary, RawExit,+};++pub(super) type WorkerStdin = NamedPipeServer;+pub(super) type WorkerStdout = NamedPipeServer;++type Handle = *mut c_void;+type Bool = i32;++const FALSE: Bool = 0;+const TRUE: Bool = 1;+const INFINITE: u32 = 0xFFFF_FFFF;+const WAIT_OBJECT_0: u32 = 0;+const WAIT_TIMEOUT: u32 = 258;+const WAIT_FAILED: u32 = 0xFFFF_FFFF;+const DUPLICATE_SAME_ACCESS: u32 = 0x0000_0002;+const PROCESS_REAP_GRACE_MILLIS: u32 = 5_000;+const CLEANUP_RETRY_INTERVAL: Duration = Duration::from_millis(100);+const CLEANUP_MAX_RETRY_INTERVAL: Duration = Duration::from_secs(5);+const CLEANUP_WAIT_FAILURE_ATTEMPTS: usize = 3;+const CLEANUP_AUTHORITY_FAILURE_ATTEMPTS: usize = 3;++const GENERIC_READ: u32 = 0x8000_0000;+const GENERIC_WRITE: u32 = 0x4000_0000;+const GENERIC_EXECUTE: u32 = 0x2000_0000;+const GENERIC_ALL: u32 = 0x1000_0000;+const FILE_READ_DATA: u32 = 0x0000_0001;+const READ_CONTROL: u32 = 0x0002_0000;+const WRITE_DAC: u32 = 0x0004_0000;+const OPEN_EXISTING: u32 = 3;+const FILE_SHARE_READ: u32 = 0x0000_0001;+const FILE_SHARE_WRITE: u32 = 0x0000_0002;+const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;+const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;+const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x0000_0010;+const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400;+const FILE_ATTRIBUTE_TAG_INFO_CLASS: u32 = 9;+const FILE_NAME_NORMALIZED: u32 = 0;+const MOVEFILE_WRITE_THROUGH: u32 = 0x0000_0008;++const CREATE_SUSPENDED: u32 = 0x0000_0004;+const CREATE_UNICODE_ENVIRONMENT: u32 = 0x0000_0400;+const CREATE_NO_WINDOW: u32 = 0x0800_0000;+const EXTENDED_STARTUPINFO_PRESENT: u32 = 0x0008_0000;+const STARTF_USESTDHANDLES: u32 = 0x0000_0100;+const STARTF_USESHOWWINDOW: u32 = 0x0000_0001;+const SW_HIDE: u16 = 0;++const PROC_THREAD_ATTRIBUTE_HANDLE_LIST: usize = 0x0002_0002;+const PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES: usize = 0x0002_0009;++const JOB_OBJECT_LIMIT_PROCESS_TIME: u32 = 0x0000_0002;+const JOB_OBJECT_LIMIT_ACTIVE_PROCESS: u32 = 0x0000_0008;+const JOB_OBJECT_LIMIT_JOB_MEMORY: u32 = 0x0000_0200;+const JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION: u32 = 0x0000_0400;+const JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: u32 = 0x0000_2000;++const JOB_OBJECT_BASIC_UI_RESTRICTIONS: u32 = 4;+const JOB_OBJECT_EXTENDED_LIMIT_INFORMATION: u32 = 9;++const JOB_OBJECT_UILIMIT_HANDLES: u32 = 0x0000_0001;+const JOB_OBJECT_UILIMIT_READCLIPBOARD: u32 = 0x0000_0002;+const JOB_OBJECT_UILIMIT_WRITECLIPBOARD: u32 = 0x0000_0004;+const JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS: u32 = 0x0000_0008;+const JOB_OBJECT_UILIMIT_DISPLAYSETTINGS: u32 = 0x0000_0010;+const JOB_OBJECT_UILIMIT_GLOBALATOMS: u32 = 0x0000_0020;+const JOB_OBJECT_UILIMIT_DESKTOP: u32 = 0x0000_0040;+const JOB_OBJECT_UILIMIT_EXITWINDOWS: u32 = 0x0000_0080;++/// Every UI restriction a Job Object can impose.+const JOB_OBJECT_UILIMIT_ALL: u32 = JOB_OBJECT_UILIMIT_HANDLES+ | JOB_OBJECT_UILIMIT_READCLIPBOARD+ | JOB_OBJECT_UILIMIT_WRITECLIPBOARD+ | JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS+ | JOB_OBJECT_UILIMIT_DISPLAYSETTINGS+ | JOB_OBJECT_UILIMIT_GLOBALATOMS+ | JOB_OBJECT_UILIMIT_DESKTOP+ | JOB_OBJECT_UILIMIT_EXITWINDOWS;++const SECURITY_DESCRIPTOR_REVISION: u32 = 1;+const DACL_SECURITY_INFORMATION: u32 = 0x0000_0004;+const UNPROTECTED_DACL_SECURITY_INFORMATION: u32 = 0x2000_0000;+const PROTECTED_DACL_SECURITY_INFORMATION: u32 = 0x8000_0000;+const SE_FILE_OBJECT: u32 = 1;+const TOKEN_QUERY: u32 = 0x0008;+const TOKEN_USER_CLASS: u32 = 1;++const TRUSTEE_IS_SID: u32 = 0;+const TRUSTEE_IS_UNKNOWN: u32 = 0;+const NO_MULTIPLE_TRUSTEE: u32 = 0;+const GRANT_ACCESS: u32 = 1;+const NO_INHERITANCE: u32 = 0x0;+const SUB_CONTAINERS_AND_OBJECTS_INHERIT: u32 = 0x3;++const ERROR_SUCCESS: u32 = 0;+const ERROR_INSUFFICIENT_BUFFER: i32 = 122;+/// The rights a worker needs on its private desktop: it may create its own+/// windows and read its own desktop, but never record or play back journal+/// input, hook another thread, or switch the session to another desktop.+const DESKTOP_WORKER_ACCESS: u32 = 0x0001 | 0x0002 | 0x0004 | 0x0080;++/// Exit statuses that mean a containment ceiling ended the worker rather than a+/// fault in its own code.+const RESOURCE_LIMIT_EXITS: &[u32] = &[+ 0xC000_0017, // STATUS_NO_MEMORY+ 0xC000_0044, // STATUS_QUOTA_EXCEEDED+ 0xC000_009A, // STATUS_INSUFFICIENT_RESOURCES+ 0xC000_012D, // STATUS_COMMITMENT_LIMIT+];++const APP_CONTAINER_NAME_PREFIX: &str = "com.trycua.perception.worker";+const LEGACY_OVERSIZED_APP_CONTAINER_NAME_PREFIX: &str = "com.trycua.cua-driver.perception.worker";+const APP_CONTAINER_DISPLAY_NAME: &str = "Cua Driver perception worker";+const APP_CONTAINER_DESCRIPTION: &str =+ "Contained inference worker for the optional Cua Driver perception extension.";++// Every type below mirrors a Win32 layout. Fields the operating system fills in+// are declared for correct size and offset even where this module never reads+// them, so the layouts are allowed to carry unread members.+#[allow(dead_code)]+#[repr(C)]+struct SecurityAttributes {+ length: u32,+ security_descriptor: *mut c_void,+ inherit_handle: Bool,+}++/// A `SECURITY_DESCRIPTOR` in absolute form. The Win32 minimum is 40 bytes on a+/// 64-bit target; 64 pointer-aligned bytes is comfortably above it.+#[repr(C, align(8))]+struct SecurityDescriptorStorage([u8; 64]);++#[allow(dead_code)]+#[repr(C)]+struct StartupInfoW {+ cb: u32,+ reserved: *mut u16,+ desktop: *mut u16,+ title: *mut u16,+ x: u32,+ y: u32,+ x_size: u32,+ y_size: u32,+ x_count_chars: u32,+ y_count_chars: u32,+ fill_attribute: u32,+ flags: u32,+ show_window: u16,+ reserved2_size: u16,+ reserved2: *mut u8,+ std_input: Handle,+ std_output: Handle,+ std_error: Handle,+}++#[allow(dead_code)]+#[repr(C)]+struct StartupInfoExW {+ startup_info: StartupInfoW,+ attribute_list: *mut c_void,+}++#[allow(dead_code)]+#[repr(C)]+struct ProcessInformation {+ process: Handle,+ thread: Handle,+ process_id: u32,+ thread_id: u32,+}++#[allow(dead_code)]+#[repr(C)]+struct IoCounters {+ read_operation_count: u64,+ write_operation_count: u64,+ other_operation_count: u64,+ read_transfer_count: u64,+ write_transfer_count: u64,+ other_transfer_count: u64,+}++#[allow(dead_code)]+#[repr(C)]+struct JobBasicLimitInformation {+ per_process_user_time_limit: i64,+ per_job_user_time_limit: i64,+ limit_flags: u32,+ minimum_working_set_size: usize,+ maximum_working_set_size: usize,+ active_process_limit: u32,+ affinity: usize,+ priority_class: u32,+ scheduling_class: u32,+}++#[allow(dead_code)]+#[repr(C)]+struct JobExtendedLimitInformation {+ basic_limit_information: JobBasicLimitInformation,+ io_info: IoCounters,+ process_memory_limit: usize,+ job_memory_limit: usize,+ peak_process_memory_used: usize,+ peak_job_memory_used: usize,+}++#[allow(dead_code)]+#[repr(C)]+struct JobBasicUiRestrictions {+ ui_restrictions_class: u32,+}++#[allow(dead_code)]+#[repr(C)]+struct SecurityCapabilities {+ app_container_sid: *mut c_void,+ capabilities: *mut c_void,+ capability_count: u32,+ reserved: u32,+}++#[allow(dead_code)]+#[repr(C)]+struct SidAndAttributes {+ sid: *mut c_void,+ attributes: u32,+}++#[allow(dead_code)]+#[repr(C)]+struct TokenUserInformation {+ user: SidAndAttributes,+}++#[allow(dead_code)]+#[repr(C)]+struct TrusteeW {+ multiple_trustee: *mut c_void,+ multiple_trustee_operation: u32,+ trustee_form: u32,+ trustee_type: u32,+ name: *mut u16,+}++#[allow(dead_code)]+#[repr(C)]+struct ExplicitAccessW {+ access_permissions: u32,+ access_mode: u32,+ inheritance: u32,+ trustee: TrusteeW,+}++#[repr(C)]+struct FileAttributeTagInfo {+ file_attributes: u32,+ reparse_tag: u32,+}++#[allow(dead_code)]+#[repr(C)]+struct FileTime {+ low_date_time: u32,+ high_date_time: u32,+}++#[allow(dead_code)]+#[repr(C)]+struct ByHandleFileInformation {+ file_attributes: u32,+ creation_time: FileTime,+ last_access_time: FileTime,+ last_write_time: FileTime,+ volume_serial_number: u32,+ file_size_high: u32,+ file_size_low: u32,+ number_of_links: u32,+ file_index_high: u32,+ file_index_low: u32,+}++#[link(name = "kernel32")]+extern "system" {+ fn CloseHandle(object: Handle) -> Bool;+ fn CreateFileW(+ file_name: *const u16,+ desired_access: u32,+ share_mode: u32,+ security_attributes: *const SecurityAttributes,+ creation_disposition: u32,+ flags_and_attributes: u32,+ template_file: Handle,+ ) -> Handle;+ fn CreateProcessW(+ application_name: *const u16,+ command_line: *mut u16,+ process_attributes: *const SecurityAttributes,+ thread_attributes: *const SecurityAttributes,+ inherit_handles: Bool,+ creation_flags: u32,+ environment: *const c_void,+ current_directory: *const u16,+ startup_info: *const StartupInfoW,+ process_information: *mut ProcessInformation,+ ) -> Bool;+ fn ResumeThread(thread: Handle) -> u32;+ fn TerminateProcess(process: Handle, exit_code: u32) -> Bool;+ fn WaitForSingleObject(object: Handle, milliseconds: u32) -> u32;+ fn GetExitCodeProcess(process: Handle, exit_code: *mut u32) -> Bool;+ fn GetCurrentProcess() -> Handle;+ fn MoveFileExW(existing: *const u16, new: *const u16, flags: u32) -> Bool;+ fn DuplicateHandle(+ source_process: Handle,+ source: Handle,+ target_process: Handle,+ target: *mut Handle,+ desired_access: u32,+ inherit_handle: Bool,+ options: u32,+ ) -> Bool;+ fn GetSystemWindowsDirectoryW(buffer: *mut u16, size: u32) -> u32;+ fn GetFinalPathNameByHandleW(file: Handle, path: *mut u16, path_size: u32, flags: u32) -> u32;+ fn GetFileInformationByHandleEx(+ file: Handle,+ information_class: u32,+ information: *mut c_void,+ size: u32,+ ) -> Bool;+ fn GetFileInformationByHandle(file: Handle, information: *mut ByHandleFileInformation) -> Bool;+ fn CreateJobObjectW(attributes: *const SecurityAttributes, name: *const u16) -> Handle;+ fn SetInformationJobObject(+ job: Handle,+ class: u32,+ information: *const c_void,+ length: u32,+ ) -> Bool;+ fn AssignProcessToJobObject(job: Handle, process: Handle) -> Bool;+ fn TerminateJobObject(job: Handle, exit_code: u32) -> Bool;+ fn InitializeProcThreadAttributeList(+ list: *mut c_void,+ attribute_count: u32,+ flags: u32,+ size: *mut usize,+ ) -> Bool;+ fn UpdateProcThreadAttribute(+ list: *mut c_void,+ flags: u32,+ attribute: usize,+ value: *mut c_void,+ size: usize,+ previous_value: *mut c_void,+ return_size: *mut usize,+ ) -> Bool;+ fn DeleteProcThreadAttributeList(list: *mut c_void);+ fn LocalFree(memory: *mut c_void) -> *mut c_void;+}++#[link(name = "advapi32")]+extern "system" {+ fn OpenProcessToken(process: Handle, desired_access: u32, token: *mut Handle) -> Bool;+ fn GetTokenInformation(+ token: Handle,+ class: u32,+ information: *mut c_void,+ length: u32,+ return_length: *mut u32,+ ) -> Bool;+ fn InitializeSecurityDescriptor(descriptor: *mut c_void, revision: u32) -> Bool;+ fn SetSecurityDescriptorDacl(+ descriptor: *mut c_void,+ dacl_present: Bool,+ dacl: *mut c_void,+ dacl_defaulted: Bool,+ ) -> Bool;+ fn GetSecurityDescriptorControl(+ descriptor: *mut c_void,+ control: *mut u16,+ revision: *mut u32,+ ) -> Bool;+ fn SetEntriesInAclW(+ count: u32,+ entries: *mut ExplicitAccessW,+ old_acl: *mut c_void,+ new_acl: *mut *mut c_void,+ ) -> u32;+ fn GetSecurityInfo(+ object: Handle,+ object_type: u32,+ security_information: u32,+ owner: *mut *mut c_void,+ group: *mut *mut c_void,+ dacl: *mut *mut c_void,+ sacl: *mut *mut c_void,+ security_descriptor: *mut *mut c_void,+ ) -> u32;+ fn SetSecurityInfo(+ object: Handle,+ object_type: u32,+ security_information: u32,+ owner: *mut c_void,+ group: *mut c_void,+ dacl: *mut c_void,+ sacl: *mut c_void,+ ) -> u32;+ fn FreeSid(sid: *mut c_void) -> *mut c_void;+}++#[link(name = "user32")]+extern "system" {+ fn CreateDesktopW(+ desktop: *const u16,+ device: *const u16,+ devmode: *mut c_void,+ flags: u32,+ desired_access: u32,+ attributes: *const SecurityAttributes,+ ) -> Handle;+ fn CloseDesktop(desktop: Handle) -> Bool;+}++#[link(name = "userenv")]+extern "system" {+ fn CreateAppContainerProfile(+ name: *const u16,+ display_name: *const u16,+ description: *const u16,+ capabilities: *mut c_void,+ capability_count: u32,+ sid: *mut *mut c_void,+ ) -> i32;+ fn DeleteAppContainerProfile(name: *const u16) -> i32;+}++/// Owns the job, primary-process duplicate, private desktop and temporary+/// filesystem grants. Drop terminates the job and either reaps the process+/// within a bounded grace period or transfers cleanup to a background reaper.+/// Kernel handles are stored as `isize` so the guard stays `Send` across the+/// awaits that hold a warm worker.+pub(super) struct Guard {+ job: isize,+ desktop: isize,+ cleanup: Option<PendingCleanup>,+ require_synchronous_cleanup: bool,+}++impl Guard {+ pub(super) fn note_reaped(&mut self) -> std::io::Result<()> {+ // The one allowed job process has exited, so its temporary filesystem+ // authority can be removed before the warm-worker state is released.+ let Some(cleanup) = &mut self.cleanup else {+ return Ok(());+ };+ cleanup.mark_process_reaped();+ cleanup.cleanup_reaped_once()?;+ if cleanup.is_clean() {+ self.cleanup.take();+ }+ Ok(())+ }++ /// The Job Object's memory ceiling is enforced by the kernel and surfaces+ /// as an exit status, so no supervisor state is folded in here.+ pub(super) fn memory_ceiling_exceeded(&self) -> bool {+ false+ }+}++impl Drop for Guard {+ fn drop(&mut self) {+ let wait = unsafe {+ TerminateJobObject(self.job as Handle, 1);+ let wait = self.cleanup.as_ref().and_then(|cleanup| {+ (!cleanup.process_reaped).then(|| {+ WaitForSingleObject(cleanup.process as Handle, PROCESS_REAP_GRACE_MILLIS)+ })+ });+ CloseHandle(self.job as Handle);+ CloseDesktop(self.desktop as Handle);+ wait+ };+ let Some(mut cleanup) = self.cleanup.take() else {+ return;+ };++ if let Some(wait) = wait {+ match classify_wait_status(wait, std::io::Error::last_os_error) {+ Ok(()) => cleanup.mark_process_reaped(),+ Err(cause) if wait != WAIT_TIMEOUT => {+ tracing::warn!(error = %cause, "failed to confirm perception worker exit during cleanup");+ }+ Err(_) => {}+ }+ }+ if cleanup.process_reaped {+ if let Err(cause) = cleanup.cleanup_reaped_once() {+ tracing::warn!(error = %cause, "failed to clean up perception worker authority; retrying");+ } else if cleanup.is_clean() {+ return;+ }+ }+ if self.require_synchronous_cleanup {+ if !cleanup.run_until_clean() {+ fatal_unproven_exit();+ }+ return;+ }++ // Termination is asynchronous. Keep the exact ACL handles, unique SID,+ // profile and cross-process lease alive until the primary process+ // actually signals, without blocking an executor thread indefinitely.+ let shared = std::sync::Arc::new(std::sync::Mutex::new(Some(cleanup)));+ let background = std::sync::Arc::clone(&shared);+ let spawned = std::thread::Builder::new()+ .name("cua-perception-acl-reaper".to_owned())+ .spawn(move || {+ let mut cleanup = background+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .take()+ .expect("perception ACL cleanup state is available");+ if !cleanup.run_until_clean() {+ fatal_unproven_exit();+ }+ });+ if spawned.is_err() {+ fatal_unproven_exit();+ }+ }+}++struct PendingCleanup {+ process: isize,+ process_reaped: bool,+ grants: Option<AclGrantLedger>,+ container: Option<AppContainerSid>,+ journal: Option<AppContainerJournal>,+ lease: Option<AclLease>,+}++impl PendingCleanup {+ fn mark_process_reaped(&mut self) {+ self.process_reaped = true;+ if self.process != 0 {+ unsafe {+ CloseHandle(self.process as Handle);+ }+ self.process = 0;+ }+ }++ fn cleanup_reaped_once(&mut self) -> std::io::Result<()> {+ debug_assert!(self.process_reaped);+ if let Some(grants) = &mut self.grants {+ grants.revoke().map_err(visual_error_to_io)?;+ self.grants.take();+ }+ if let Some(container) = &mut self.container {+ container.delete_profile().map_err(visual_error_to_io)?;+ self.container.take();+ }+ if let Some(journal) = &mut self.journal {+ journal.clear().map_err(visual_error_to_io)?;+ self.journal.take();+ }+ self.lease.take();+ Ok(())+ }++ fn is_clean(&self) -> bool {+ self.process == 0+ && self.grants.is_none()+ && self.container.is_none()+ && self.journal.is_none()+ && self.lease.is_none()+ }++ fn run_until_clean(&mut self) -> bool {+ let mut wait_reported = false;+ let mut cleanup_reported = false;+ let mut retry_interval = CLEANUP_RETRY_INTERVAL;+ let mut wait_failures = 0;+ while !self.process_reaped {+ let status = unsafe { WaitForSingleObject(self.process as Handle, INFINITE) };+ match classify_wait_status(status, std::io::Error::last_os_error) {+ Ok(()) => self.mark_process_reaped(),+ Err(cause) => {+ wait_failures += 1;+ if !wait_reported {+ tracing::warn!(error = %cause, "failed to wait for perception worker cleanup; retrying");+ wait_reported = true;+ }+ if cleanup_wait_is_fatal(wait_failures) {+ return false;+ }+ std::thread::sleep(retry_interval);+ retry_interval = (retry_interval * 2).min(CLEANUP_MAX_RETRY_INTERVAL);+ }+ }+ }+ retry_interval = CLEANUP_RETRY_INTERVAL;+ let mut cleanup_failures = 0;+ while !self.is_clean() {+ match self.cleanup_reaped_once() {+ Ok(()) => {}+ Err(cause) => {+ cleanup_failures += 1;+ if !cleanup_reported {+ tracing::warn!(error = %cause, "failed to clean up perception worker authority; retrying");+ cleanup_reported = true;+ }+ if cleanup_authority_failure_is_fatal(cleanup_failures) {+ return false;+ }+ std::thread::sleep(retry_interval);+ retry_interval = (retry_interval * 2).min(CLEANUP_MAX_RETRY_INTERVAL);+ }+ }+ }+ true+ }+}++fn cleanup_wait_is_fatal(failures: usize) -> bool {+ failures >= CLEANUP_WAIT_FAILURE_ATTEMPTS+}++fn cleanup_authority_failure_is_fatal(failures: usize) -> bool {+ failures >= CLEANUP_AUTHORITY_FAILURE_ATTEMPTS+}++fn fatal_unproven_exit() -> ! {+ tracing::error!(+ "cannot safely finish perception worker teardown; aborting so durable profile recovery runs before the next lifecycle operation"+ );+ // A crash can leave ACEs naming this unique SID. Recovery deletes the+ // journaled profile before any later component operation, making those+ // ACEs inert. Startup hardening repairs installed extension-tree drift;+ // the private working directory is a task-owned TempDir.+ std::process::abort()+}++fn classify_wait_status(+ status: u32,+ last_error: impl FnOnce() -> std::io::Error,+) -> std::io::Result<()> {+ match status {+ WAIT_OBJECT_0 => Ok(()),+ WAIT_FAILED => Err(last_error()),+ other => Err(std::io::Error::other(format!(+ "unexpected WaitForSingleObject status {other:#010x}"+ ))),+ }+}++fn visual_error_to_io(error: VisualParseError) -> std::io::Error {+ let detail = error.detail.map_or_else(+ || error.message.clone(),+ |detail| format!("{}: {detail}", error.message),+ );+ std::io::Error::other(detail)+}++pub(super) struct Process {+ process: isize,+}++impl Process {+ pub(super) async fn wait(&mut self) -> std::io::Result<RawExit> {+ // The blocking waiter owns a duplicate so cancellation may drop and+ // close `Process` without closing a handle under WaitForSingleObject.+ let process = OwnedHandle::duplicate_io(self.process as Handle)?;+ let code = tokio::task::spawn_blocking(move || unsafe {+ let status = WaitForSingleObject(process.get(), INFINITE);+ classify_wait_status(status, std::io::Error::last_os_error)?;+ let mut code = 0_u32;+ if GetExitCodeProcess(process.get(), &mut code) == FALSE {+ return Err(std::io::Error::last_os_error());+ }+ Ok(code)+ })+ .await+ .map_err(std::io::Error::other)??;+ Ok(RawExit {+ success: code == 0,+ resource_limited: RESOURCE_LIMIT_EXITS.contains(&code),+ description: format!("exit code {code:#010x}"),+ })+ }+}++impl Drop for Process {+ fn drop(&mut self) {+ unsafe {+ CloseHandle(self.process as Handle);+ }+ }+}++pub(super) async fn spawn(+ executable: &Path,+ args: &[String],+ working_directory: &Path,+ boundary: &FilesystemBoundary,+ limits: &ContainmentLimits,+) -> Result<ContainedChild, VisualParseError> {+ if !executable.is_file() {+ return Err(spawn_error(std::io::Error::from_raw_os_error(2)));+ }+ let user = current_user_sid()?;+ let acl_lease = match &limits.windows_acl_lease_path {+ Some(path) => Some(AclLease::acquire(path).await?),+ None => None,+ };+ let journal_path = limits.windows_acl_profile_journal_path.clone().or_else(|| {+ limits+ .windows_acl_lease_path+ .as_deref()+ .map(acl_profile_journal_path)+ });+ if limits.windows_acl_lease_path.is_none() {+ if let Some(path) = &journal_path {+ recover_acl_profile_journal(path)?;+ }+ }+ let profile_name = format!(+ "{APP_CONTAINER_NAME_PREFIX}.{}",+ uuid::Uuid::new_v4().simple()+ );+ let (journal, container) = match journal_path {+ Some(path) => {+ let (journal, container) = journal_before_profile(path, &profile_name, || {+ AppContainerSid::create(&profile_name)+ })?;+ (Some(journal), container)+ }+ None => (None, AppContainerSid::create(&profile_name)?),+ };+ let acl_grants = grant_worker_paths(working_directory, boundary, user.sid(), container.sid())?;++ let token = uuid::Uuid::new_v4().simple().to_string();+ let protocol_security =+ PrivateSecurity::new(&[(user.sid(), GENERIC_ALL), (container.sid(), GENERIC_ALL)])?;+ let job_security = PrivateSecurity::new(&[(user.sid(), GENERIC_ALL)])?;+ let desktop_security = PrivateSecurity::new(&[+ (user.sid(), GENERIC_ALL),+ (container.sid(), DESKTOP_WORKER_ACCESS),+ ])?;++ let mut inbound =+ ProtocolPipe::create(&token, "out", Direction::FromWorker, &protocol_security)?;+ let mut outbound = ProtocolPipe::create(&token, "in", Direction::ToWorker, &protocol_security)?;+ // Both ends already exist, so the connections complete before any worker+ // code is created, let alone resumed.+ outbound.connect().await?;+ inbound.connect().await?;+ let null_device = OwnedHandle::open_null()?;+ let job = OwnedHandle::create_job(limits, &job_security)?;+ let mut desktop = PrivateDesktop::create(&token, &desktop_security)?;++ let information = create_suspended(+ executable,+ args,+ working_directory,+ &desktop,+ [outbound.client(), inbound.client(), null_device.get()],+ container.sid(),+ &protocol_security,+ )?;++ // The suspended process has not executed one instruction, so any failure+ // from here on can still be resolved by terminating it.+ if unsafe { AssignProcessToJobObject(job.get(), information.process) } == FALSE {+ let failure =+ last_error("failed to assign the perception worker to its containment job object");+ information.terminate();+ return Err(failure);+ }+ // The child now owns its copies; releasing the parent's copies is what+ // makes the worker observe end of file when the Driver goes away.+ drop(null_device);+ let inbound = inbound.into_server();+ let outbound = outbound.into_server();++ let guard_process = OwnedHandle::duplicate(information.process)?;+ if unsafe { ResumeThread(information.thread) } == u32::MAX {+ let failure = last_error("failed to resume the contained perception worker");+ information.terminate();+ return Err(failure);+ }+ let guard = Guard {+ job: job.release() as isize,+ desktop: desktop.release() as isize,+ cleanup: Some(PendingCleanup {+ process: guard_process.release() as isize,+ process_reaped: false,+ grants: Some(acl_grants),+ container: Some(container),+ journal,+ lease: acl_lease,+ }),+ require_synchronous_cleanup: limits.windows_require_synchronous_cleanup,+ };+ let process = Process {+ process: information.into_process() as isize,+ };+ Ok(ContainedChild {+ guard,+ process,+ stdin: Some(outbound),+ stdout: Some(inbound),+ })+}++/// A handle that is closed when it is dropped unless ownership is released to a+/// longer-lived guard.+struct OwnedHandle(Handle);++// Win32 kernel handles are process-wide values. Ownership stays unique in this+// wrapper, and moving it between executor threads does not change validity.+unsafe impl Send for OwnedHandle {}++impl OwnedHandle {+ fn get(&self) -> Handle {+ self.0+ }++ fn release(mut self) -> Handle {+ let handle = self.0;+ self.0 = std::ptr::null_mut();+ std::mem::forget(self);+ handle+ }++ fn duplicate(handle: Handle) -> Result<Self, VisualParseError> {+ Self::duplicate_io(handle).map_err(|cause| {+ containment_error(+ "failed to retain the perception worker process for ACL cleanup",+ os_detail(&cause),+ )+ })+ }++ fn duplicate_io(handle: Handle) -> std::io::Result<Self> {+ let process = unsafe { GetCurrentProcess() };+ let mut duplicate = std::ptr::null_mut();+ if unsafe {+ DuplicateHandle(+ process,+ handle,+ process,+ &mut duplicate,+ 0,+ FALSE,+ DUPLICATE_SAME_ACCESS,+ )+ } == FALSE+ {+ return Err(std::io::Error::last_os_error());+ }+ Ok(Self(duplicate))+ }++ /// Open the null device as the worker's stderr. Diagnostics travel over the+ /// framed protocol, so the worker never writes to an inherited console.+ fn open_null() -> Result<Self, VisualParseError> {+ let name = wide("NUL");+ let attributes = inheritable_attributes();+ let handle = unsafe {+ CreateFileW(+ name.as_ptr(),+ GENERIC_WRITE,+ 0,+ &attributes,+ OPEN_EXISTING,+ 0,+ std::ptr::null_mut(),+ )+ };+ if handle as isize == -1 {+ return Err(last_error(+ "failed to open the null device for the perception worker",+ ));+ }+ Ok(Self(handle))+ }++ fn create_job(+ limits: &ContainmentLimits,+ security: &PrivateSecurity,+ ) -> Result<Self, VisualParseError> {+ // An unnamed job object with a private, protected security descriptor+ // cannot be opened by name or by an unrelated process.+ let attributes = security.attributes();+ let job = unsafe { CreateJobObjectW(&attributes, std::ptr::null()) };+ if job.is_null() {+ return Err(last_error(+ "failed to create the perception worker containment job object",+ ));+ }+ let job = Self(job);++ let mut information: JobExtendedLimitInformation = unsafe { std::mem::zeroed() };+ information.basic_limit_information.limit_flags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE+ | JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION+ | JOB_OBJECT_LIMIT_ACTIVE_PROCESS+ | JOB_OBJECT_LIMIT_JOB_MEMORY+ | JOB_OBJECT_LIMIT_PROCESS_TIME;+ information.basic_limit_information.active_process_limit = limits.max_processes;+ // `PerProcessUserTimeLimit` counts in 100-nanosecond units.+ information+ .basic_limit_information+ .per_process_user_time_limit =+ i64::try_from(limits.max_cpu_seconds().saturating_mul(10_000_000)).unwrap_or(i64::MAX);+ information.job_memory_limit =+ usize::try_from(limits.max_memory_bytes).unwrap_or(usize::MAX);+ if unsafe {+ SetInformationJobObject(+ job.get(),+ JOB_OBJECT_EXTENDED_LIMIT_INFORMATION,+ std::ptr::addr_of!(information).cast(),+ std::mem::size_of::<JobExtendedLimitInformation>() as u32,+ )+ } == FALSE+ {+ return Err(last_error(+ "failed to apply the perception worker containment job object limits",+ ));+ }++ let restrictions = JobBasicUiRestrictions {+ ui_restrictions_class: JOB_OBJECT_UILIMIT_ALL,+ };+ if unsafe {+ SetInformationJobObject(+ job.get(),+ JOB_OBJECT_BASIC_UI_RESTRICTIONS,+ std::ptr::addr_of!(restrictions).cast(),+ std::mem::size_of::<JobBasicUiRestrictions>() as u32,+ )+ } == FALSE+ {+ return Err(last_error(+ "failed to apply the perception worker containment job object UI restrictions",+ ));+ }+ Ok(job)+ }+}++impl Drop for OwnedHandle {+ fn drop(&mut self) {+ if !self.0.is_null() {+ unsafe {+ CloseHandle(self.0);+ }+ }+ }+}++/// The worker's own desktop. Nothing else runs on it, so a capture or input+/// attempt from inside the worker reaches an empty desktop rather than the+/// user's session.+struct PrivateDesktop {+ handle: Handle,+ name: Vec<u16>,+ released: bool,+}++impl PrivateDesktop {+ fn create(token: &str, security: &PrivateSecurity) -> Result<Self, VisualParseError> {+ let name = wide(&format!("cua-perception-{token}"));+ let attributes = security.attributes();+ let handle = unsafe {+ CreateDesktopW(+ name.as_ptr(),+ std::ptr::null(),+ std::ptr::null_mut(),+ 0,+ GENERIC_ALL,+ &attributes,+ )+ };+ if handle.is_null() {+ return Err(last_error(+ "failed to create the private desktop for the perception worker",+ ));+ }+ Ok(Self {+ handle,+ name,+ released: false,+ })+ }++ fn name(&self) -> *mut u16 {+ self.name.as_ptr().cast_mut()+ }++ /// Hand the desktop handle to the guard that outlives this value. The+ /// desktop exists only while a handle to it is open, so the guard must hold+ /// it for as long as the worker runs.+ fn release(&mut self) -> Handle {+ self.released = true;+ self.handle+ }+}++impl Drop for PrivateDesktop {+ fn drop(&mut self) {+ if !self.released && !self.handle.is_null() {+ unsafe {+ CloseDesktop(self.handle);+ }+ }+ }+}++#[derive(Clone, Copy)]+enum Direction {+ ToWorker,+ FromWorker,+}++/// One half of the framed protocol: an asynchronous private named pipe on the+/// Driver side and a plain inheritable stdio handle on the worker side.+struct ProtocolPipe {+ server: NamedPipeServer,+ client: OwnedHandle,+}++impl ProtocolPipe {+ fn create(+ token: &str,+ suffix: &str,+ direction: Direction,+ security: &PrivateSecurity,+ ) -> Result<Self, VisualParseError> {+ let name = format!(r"\\.\pipe\cua-perception-{token}-{suffix}");+ let mut options = ServerOptions::new();+ options+ .pipe_mode(PipeMode::Byte)+ // One instance, claimed first, so no other process can pre-create+ // or later attach to this name.+ .first_pipe_instance(true)+ .max_instances(1)+ .reject_remote_clients(true);+ match direction {+ Direction::ToWorker => options.access_inbound(false).access_outbound(true),+ Direction::FromWorker => options.access_inbound(true).access_outbound(false),+ };+ let mut attributes = security.attributes();+ let server = unsafe {+ options.create_with_security_attributes_raw(+ &name,+ std::ptr::addr_of_mut!(attributes).cast(),+ )+ }+ .map_err(|cause| {+ containment_error(+ "failed to create a private perception worker protocol pipe",+ os_detail(&cause),+ )+ })?;++ let wide_name = wide(&name);+ let client_attributes = inheritable_attributes();+ let access = match direction {+ Direction::ToWorker => GENERIC_READ,+ Direction::FromWorker => GENERIC_WRITE,+ };+ let client = unsafe {+ CreateFileW(+ wide_name.as_ptr(),+ access,+ 0,+ &client_attributes,+ OPEN_EXISTING,+ 0,+ std::ptr::null_mut(),+ )+ };+ if client as isize == -1 {+ return Err(last_error(+ "failed to open the worker end of a perception protocol pipe",+ ));+ }+ Ok(Self {+ server,+ client: OwnedHandle(client),+ })+ }++ fn client(&self) -> Handle {+ self.client.get()+ }++ async fn connect(&mut self) -> Result<(), VisualParseError> {+ self.server.connect().await.map_err(|cause| {+ containment_error(+ "failed to connect a private perception worker protocol pipe",+ os_detail(&cause),+ )+ })+ }++ /// Release the worker's end, which the child now owns, and keep the+ /// Driver's asynchronous end.+ fn into_server(self) -> NamedPipeServer {+ self.server+ }+}++/// The suspended worker process and its primary thread.+struct SuspendedProcess {+ process: Handle,+ thread: Handle,+}++impl SuspendedProcess {+ fn terminate(self) {+ unsafe {+ TerminateProcess(self.process, 1);+ WaitForSingleObject(self.process, INFINITE);+ CloseHandle(self.thread);+ CloseHandle(self.process);+ }+ std::mem::forget(self);+ }++ fn into_process(self) -> Handle {+ let process = self.process;+ unsafe {+ CloseHandle(self.thread);+ }+ std::mem::forget(self);+ process+ }+}++impl Drop for SuspendedProcess {+ fn drop(&mut self) {+ unsafe {+ TerminateProcess(self.process, 1);+ WaitForSingleObject(self.process, INFINITE);+ CloseHandle(self.thread);+ CloseHandle(self.process);+ }+ }+}++#[allow(clippy::too_many_arguments)]+fn create_suspended(+ executable: &Path,+ args: &[String],+ working_directory: &Path,+ desktop: &PrivateDesktop,+ inherited: [Handle; 3],+ container: *mut c_void,+ security: &PrivateSecurity,+) -> Result<SuspendedProcess, VisualParseError> {+ let application = wide(executable.as_os_str());+ let mut command_line = command_line(executable, args);+ let current_directory = wide(working_directory.as_os_str());+ let environment = environment_block(working_directory)?;++ let mut attributes = AttributeList::new(2)?;+ let mut handles = inherited;+ attributes.set(+ PROC_THREAD_ATTRIBUTE_HANDLE_LIST,+ handles.as_mut_ptr().cast(),+ std::mem::size_of_val(&handles),+ "failed to restrict the perception worker's inherited handles",+ )?;+ let mut capabilities = SecurityCapabilities {+ app_container_sid: container,+ capabilities: std::ptr::null_mut(),+ capability_count: 0,+ reserved: 0,+ };+ attributes.set(+ PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES,+ std::ptr::addr_of_mut!(capabilities).cast(),+ std::mem::size_of::<SecurityCapabilities>(),+ "failed to place the perception worker in its AppContainer",+ )?;++ let mut startup: StartupInfoExW = unsafe { std::mem::zeroed() };+ startup.startup_info.cb = std::mem::size_of::<StartupInfoExW>() as u32;+ startup.startup_info.desktop = desktop.name();+ startup.startup_info.flags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;+ startup.startup_info.show_window = SW_HIDE;+ startup.startup_info.std_input = inherited[0];+ startup.startup_info.std_output = inherited[1];+ startup.startup_info.std_error = inherited[2];+ startup.attribute_list = attributes.pointer();++ let process_attributes = security.attributes();+ let mut information: ProcessInformation = unsafe { std::mem::zeroed() };+ let created = unsafe {+ CreateProcessW(+ application.as_ptr(),+ command_line.as_mut_ptr(),+ &process_attributes,+ &process_attributes,+ // Required by the handle list, which is exactly what narrows this+ // from "every inheritable handle" to the three above.+ TRUE,+ CREATE_SUSPENDED+ | CREATE_NO_WINDOW+ | CREATE_UNICODE_ENVIRONMENT+ | EXTENDED_STARTUPINFO_PRESENT,+ environment.as_ptr().cast(),+ current_directory.as_ptr(),+ std::ptr::addr_of!(startup.startup_info),+ &mut information,+ )+ };+ if created == FALSE {+ return Err(last_error(+ "failed to launch the contained perception worker",+ ));+ }+ Ok(SuspendedProcess {+ process: information.process,+ thread: information.thread,+ })+}++/// A `PROC_THREAD_ATTRIBUTE_LIST` in a pointer-aligned allocation.+struct AttributeList {+ storage: Vec<usize>,+}++impl AttributeList {+ fn new(count: u32) -> Result<Self, VisualParseError> {+ let mut size: usize = 0;+ unsafe {+ InitializeProcThreadAttributeList(std::ptr::null_mut(), count, 0, &mut size);+ }+ if size == 0 {+ return Err(last_error(+ "failed to size the perception worker process attribute list",+ ));+ }+ // `Vec<usize>` guarantees the pointer alignment the attribute list+ // requires; a byte vector does not. The list is only wrapped in the+ // guard once it initializes, so `Drop` never deletes an unformed list.+ let mut storage = vec![0_usize; size.div_ceil(std::mem::size_of::<usize>())];+ if unsafe {+ InitializeProcThreadAttributeList(storage.as_mut_ptr().cast(), count, 0, &mut size)+ } == FALSE+ {+ return Err(last_error(+ "failed to create the perception worker process attribute list",+ ));+ }+ Ok(Self { storage })+ }++ fn pointer(&mut self) -> *mut c_void {+ self.storage.as_mut_ptr().cast()+ }++ fn set(+ &mut self,+ attribute: usize,+ value: *mut c_void,+ size: usize,+ message: &'static str,+ ) -> Result<(), VisualParseError> {+ let list = self.pointer();+ if unsafe {+ UpdateProcThreadAttribute(+ list,+ 0,+ attribute,+ value,+ size,+ std::ptr::null_mut(),+ std::ptr::null_mut(),+ )+ } == FALSE+ {+ return Err(last_error(message));+ }+ Ok(())+ }+}++impl Drop for AttributeList {+ fn drop(&mut self) {+ unsafe {+ DeleteProcThreadAttributeList(self.storage.as_mut_ptr().cast());+ }+ }+}++/// The worker's AppContainer identity.+struct AppContainerSid {+ sid: *mut c_void,+ name: Vec<u16>,+ profile_deleted: bool,+}++struct AppContainerJournal {+ path: PathBuf,+ cleared: bool,+}++impl AppContainerJournal {+ fn persist(path: PathBuf, profile_name: &str) -> Result<Self, VisualParseError> {+ validate_profile_name(profile_name)?;+ let temporary = journal_pending_path(&path);+ if path.symlink_metadata().is_ok()+ || temporary.symlink_metadata().is_ok()+ || journal_tombstone_path(&path).symlink_metadata().is_ok()+ {+ return Err(containment_error(+ "the perception AppContainer recovery journal already exists",+ None,+ ));+ }+ let mut file = std::fs::OpenOptions::new()+ .write(true)+ .create_new(true)+ .open(&temporary)+ .map_err(|cause| {+ containment_error(+ "failed to create the perception AppContainer recovery journal",+ os_detail(&cause),+ )+ })?;+ let persist = (|| {+ file.write_all(profile_name.as_bytes())?;+ file.write_all(b"\n")?;+ file.sync_all()?;+ let temporary = wide(temporary.as_os_str());+ let destination = wide(path.as_os_str());+ if unsafe {+ MoveFileExW(+ temporary.as_ptr(),+ destination.as_ptr(),+ MOVEFILE_WRITE_THROUGH,+ )+ } == FALSE+ {+ return Err(std::io::Error::last_os_error());+ }+ Ok(())+ })();+ if let Err(cause) = persist {+ let _ = std::fs::remove_file(&temporary);+ return Err(containment_error(+ "failed to persist the perception AppContainer recovery journal",+ os_detail(&cause),+ ));+ }+ Ok(Self {+ path,+ cleared: false,+ })+ }++ fn clear(&mut self) -> Result<(), VisualParseError> {+ if self.cleared {+ return Ok(());+ }+ let journal_exists = self.path.symlink_metadata().is_ok();+ let tombstone_exists = journal_tombstone_path(&self.path)+ .symlink_metadata()+ .is_ok();+ if journal_exists && tombstone_exists {+ return Err(containment_error(+ "multiple perception AppContainer recovery journal states exist",+ None,+ ));+ }+ if journal_exists {+ move_journal_to_tombstone(&self.path)?;+ } else if !tombstone_exists {+ return Err(containment_error(+ "the perception AppContainer recovery journal disappeared before cleanup",+ None,+ ));+ }+ remove_journal_tombstone(&self.path)?;+ self.cleared = true;+ Ok(())+ }+}++fn journal_before_profile<T>(+ path: PathBuf,+ profile_name: &str,+ create: impl FnOnce() -> Result<T, VisualParseError>,+) -> Result<(AppContainerJournal, T), VisualParseError> {+ let journal = AppContainerJournal::persist(path, profile_name)?;+ let profile = create()?;+ Ok((journal, profile))+}++fn journal_tombstone_path(path: &Path) -> PathBuf {+ let name = path+ .file_name()+ .map_or_else(|| "runtime-acl.profile".into(), |name| name.to_os_string());+ let mut name = name;+ name.push(".cleared");+ path.with_file_name(name)+}++fn journal_pending_path(path: &Path) -> PathBuf {+ let name = path+ .file_name()+ .map_or_else(|| "runtime-acl.profile".into(), |name| name.to_os_string());+ let mut name = name;+ name.push(".pending");+ path.with_file_name(name)+}++fn move_journal_to_tombstone(path: &Path) -> Result<(), VisualParseError> {+ move_journal_state_to_tombstone(path, path)+}++fn move_journal_state_to_tombstone(+ state: &Path,+ journal_path: &Path,+) -> Result<(), VisualParseError> {+ let tombstone = journal_tombstone_path(journal_path);+ if tombstone.symlink_metadata().is_ok() {+ return Err(containment_error(+ "multiple perception AppContainer recovery journal states exist",+ None,+ ));+ }+ let path_wide = wide(state.as_os_str());+ let tombstone_wide = wide(tombstone.as_os_str());+ if unsafe {+ MoveFileExW(+ path_wide.as_ptr(),+ tombstone_wide.as_ptr(),+ MOVEFILE_WRITE_THROUGH,+ )+ } == FALSE+ {+ return Err(last_error(+ "failed to commit perception AppContainer journal removal",+ ));+ }+ Ok(())+}++fn remove_journal_tombstone(path: &Path) -> Result<(), VisualParseError> {+ let tombstone = journal_tombstone_path(path);+ match std::fs::remove_file(&tombstone) {+ Ok(()) => Ok(()),+ Err(cause) if cause.kind() == std::io::ErrorKind::NotFound => Ok(()),+ Err(cause) => Err(containment_error(+ "failed to remove the cleared perception AppContainer recovery journal",+ os_detail(&cause),+ )),+ }+}++fn validate_profile_name(name: &str) -> Result<(), VisualParseError> {+ if name.encode_utf16().count() > 64 {+ return Err(containment_error(+ "the perception AppContainer profile name exceeds the Windows limit",+ None,+ ));+ }+ if !profile_name_has_shape(name, APP_CONTAINER_NAME_PREFIX) {+ return Err(containment_error(+ "the perception AppContainer recovery journal is malformed",+ None,+ ));+ }+ Ok(())+}++fn profile_name_has_shape(name: &str, prefix: &str) -> bool {+ name.strip_prefix(prefix)+ .and_then(|suffix| suffix.strip_prefix('.'))+ .is_some_and(|token| {+ token.len() == 32 && token.bytes().all(|byte| byte.is_ascii_hexdigit())+ })+}++fn is_legacy_oversized_profile_name(name: &str) -> bool {+ profile_name_has_shape(name, LEGACY_OVERSIZED_APP_CONTAINER_NAME_PREFIX)+ && name.encode_utf16().count() > 64+}++fn read_journal_profile(path: &Path) -> Result<String, VisualParseError> {+ let name = wide(path.as_os_str());+ let handle = unsafe {+ CreateFileW(+ name.as_ptr(),+ GENERIC_READ,+ FILE_SHARE_READ,+ std::ptr::null(),+ OPEN_EXISTING,+ FILE_FLAG_OPEN_REPARSE_POINT,+ std::ptr::null_mut(),+ )+ };+ if handle as isize == -1 {+ return Err(last_error(+ "failed to open the perception AppContainer recovery journal",+ ));+ }+ let mut tag = FileAttributeTagInfo {+ file_attributes: 0,+ reparse_tag: 0,+ };+ if unsafe {+ GetFileInformationByHandleEx(+ handle,+ FILE_ATTRIBUTE_TAG_INFO_CLASS,+ std::ptr::addr_of_mut!(tag).cast(),+ std::mem::size_of::<FileAttributeTagInfo>() as u32,+ )+ } == FALSE+ || tag.file_attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT) != 0+ {+ unsafe { CloseHandle(handle) };+ return Err(containment_error(+ "the perception AppContainer recovery journal is not a regular file",+ None,+ ));+ }+ let mut file = unsafe { std::fs::File::from_raw_handle(handle.cast()) };+ let mut bytes = Vec::new();+ std::io::Read::by_ref(&mut file)+ .take(256)+ .read_to_end(&mut bytes)+ .map_err(|cause| {+ containment_error(+ "failed to read the perception AppContainer recovery journal",+ os_detail(&cause),+ )+ })?;+ let content = std::str::from_utf8(&bytes).map_err(|_| {+ containment_error(+ "the perception AppContainer recovery journal is malformed",+ None,+ )+ })?;+ let profile = content.strip_suffix('\n').ok_or_else(|| {+ containment_error(+ "the perception AppContainer recovery journal is malformed",+ None,+ )+ })?;+ if !is_legacy_oversized_profile_name(profile) {+ validate_profile_name(profile)?;+ }+ Ok(profile.to_owned())+}++fn remove_pending_journal(path: &Path) -> Result<(), VisualParseError> {+ let name = wide(path.as_os_str());+ let handle = unsafe {+ CreateFileW(+ name.as_ptr(),+ GENERIC_READ,+ FILE_SHARE_READ,+ std::ptr::null(),+ OPEN_EXISTING,+ FILE_FLAG_OPEN_REPARSE_POINT,+ std::ptr::null_mut(),+ )+ };+ if handle as isize == -1 {+ return Err(last_error(+ "failed to open the pending perception AppContainer journal",+ ));+ }+ let handle = OwnedHandle(handle);+ let mut tag = FileAttributeTagInfo {+ file_attributes: 0,+ reparse_tag: 0,+ };+ if unsafe {+ GetFileInformationByHandleEx(+ handle.get(),+ FILE_ATTRIBUTE_TAG_INFO_CLASS,+ std::ptr::addr_of_mut!(tag).cast(),+ std::mem::size_of::<FileAttributeTagInfo>() as u32,+ )+ } == FALSE+ || tag.file_attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT) != 0+ {+ return Err(containment_error(+ "the pending perception AppContainer journal is not a regular file",+ None,+ ));+ }+ drop(handle);+ std::fs::remove_file(path).map_err(|cause| {+ containment_error(+ "failed to remove the pending perception AppContainer journal",+ os_detail(&cause),+ )+ })+}++pub(super) fn acl_profile_journal_path(lease_path: &Path) -> PathBuf {+ let name = lease_path+ .file_name()+ .map_or_else(|| "runtime-acl.lock".into(), |name| name.to_os_string());+ let mut name = name;+ name.push(".profile");+ lease_path.with_file_name(name)+}++pub(super) fn recover_acl_profile_journal(path: &Path) -> Result<(), VisualParseError> {+ recover_acl_profile_journal_with(path, delete_app_container_profile)+}++fn recover_acl_profile_journal_with(+ path: &Path,+ delete_profile: impl FnOnce(&str) -> Result<(), VisualParseError>,+) -> Result<(), VisualParseError> {+ let tombstone = journal_tombstone_path(path);+ let pending = journal_pending_path(path);+ let journal_exists = path.symlink_metadata().is_ok();+ let pending_exists = pending.symlink_metadata().is_ok();+ let tombstone_exists = tombstone.symlink_metadata().is_ok();+ if usize::from(journal_exists) + usize::from(pending_exists) + usize::from(tombstone_exists) > 1+ {+ return Err(containment_error(+ "multiple perception AppContainer recovery journal states exist",+ None,+ ));+ }+ if pending_exists {+ // Profile creation starts only after the pending file is synced and+ // atomically renamed to the committed journal. An exclusive pending+ // file therefore cannot name a created profile, even if it is empty or+ // truncated by a crash during the write.+ return remove_pending_journal(&pending);+ }+ let state = if journal_exists {+ path+ } else if tombstone_exists {+ tombstone.as_path()+ } else {+ return Ok(());+ };+ let profile = read_journal_profile(state)?;+ // The prior preview wrote this journal before asking Windows to create a+ // 72-unit profile name. Windows rejects such names, so no profile exists+ // to delete; retaining the journal would permanently block the upgrade.+ if !is_legacy_oversized_profile_name(&profile) {+ delete_profile(&profile)?;+ }+ if !tombstone_exists {+ move_journal_state_to_tombstone(state, path)?;+ }+ remove_journal_tombstone(path)+}++// The SID is an owned allocation released by `FreeSid`; no thread-local state+// is associated with the pointer.+unsafe impl Send for AppContainerSid {}++impl AppContainerSid {+ fn create(profile_name: &str) -> Result<Self, VisualParseError> {+ validate_profile_name(profile_name)?;+ let name = wide(profile_name);+ let display = wide(APP_CONTAINER_DISPLAY_NAME);+ let description = wide(APP_CONTAINER_DESCRIPTION);+ let mut sid: *mut c_void = std::ptr::null_mut();+ let created = unsafe {+ CreateAppContainerProfile(+ name.as_ptr(),+ display.as_ptr(),+ description.as_ptr(),+ std::ptr::null_mut(),+ 0,+ &mut sid,+ )+ };+ if created < 0 {+ return Err(containment_error(+ "failed to create the perception worker AppContainer identity",+ Some(format!("hresult {created:#010x}")),+ ));+ }+ if sid.is_null() {+ unsafe {+ DeleteAppContainerProfile(name.as_ptr());+ }+ return Err(containment_error(+ "the perception worker AppContainer identity was empty",+ None,+ ));+ }+ Ok(Self {+ sid,+ name,+ profile_deleted: false,+ })+ }++ fn sid(&self) -> *mut c_void {+ self.sid+ }++ #[cfg(test)]+ fn create_unique() -> Result<Self, VisualParseError> {+ Self::create(&format!(+ "{APP_CONTAINER_NAME_PREFIX}.{}",+ uuid::Uuid::new_v4().simple()+ ))+ }++ fn delete_profile(&mut self) -> Result<(), VisualParseError> {+ if self.profile_deleted {+ return Ok(());+ }+ let status = unsafe { DeleteAppContainerProfile(self.name.as_ptr()) };+ classify_app_container_delete(status).map_err(|status| {+ containment_error(+ "failed to delete the perception worker AppContainer profile",+ Some(format!("hresult {status:#010x}")),+ )+ })?;+ self.profile_deleted = true;+ Ok(())+ }+}++fn delete_app_container_profile(profile_name: &str) -> Result<(), VisualParseError> {+ validate_profile_name(profile_name)?;+ let name = wide(profile_name);+ let status = unsafe { DeleteAppContainerProfile(name.as_ptr()) };+ classify_app_container_delete(status).map_err(|status| {+ containment_error(+ "failed to delete the perception worker AppContainer profile",+ Some(format!("hresult {status:#010x}")),+ )+ })+}++impl Drop for AppContainerSid {+ fn drop(&mut self) {+ let mut failure = None;+ for _ in 0..3 {+ match self.delete_profile() {+ Ok(()) => break,+ Err(cause) => {+ failure = Some(cause);+ std::thread::sleep(CLEANUP_RETRY_INTERVAL);+ }+ }+ }+ if let Some(cause) = failure.filter(|_| !self.profile_deleted) {+ tracing::warn!(error = %visual_error_to_io(cause), "failed to delete perception worker AppContainer profile during drop");+ }+ unsafe {+ FreeSid(self.sid);+ }+ }+}++fn classify_app_container_delete(status: i32) -> Result<(), i32> {+ const HRESULT_FILE_NOT_FOUND: i32 = -2_147_024_894;+ const HRESULT_NOT_FOUND: i32 = -2_147_023_728;++ if status >= 0 || matches!(status, HRESULT_FILE_NOT_FOUND | HRESULT_NOT_FOUND) {+ Ok(())+ } else {+ Err(status)+ }+}++/// The Driver's own user identity, read from its process token.+struct UserSid {+ buffer: Vec<u8>,+}++impl UserSid {+ fn sid(&self) -> *mut c_void {+ // `TOKEN_USER` starts with the `SID_AND_ATTRIBUTES` whose first field+ // points into this same buffer.+ let information = self.buffer.as_ptr().cast::<TokenUserInformation>();+ unsafe { (*information).user.sid }+ }+}++/// Serializes temporary ACL grants with other Driver processes and with+/// extension startup hardening. Windows releases the byte-range lock if the+/// owning process crashes, while the bounded retry keeps startup cancellable.+struct AclLease {+ _file: std::fs::File,+}++impl AclLease {+ async fn acquire(path: &Path) -> Result<Self, VisualParseError> {+ let name = wide(path.as_os_str());+ let handle = unsafe {+ CreateFileW(+ name.as_ptr(),+ GENERIC_READ | GENERIC_WRITE,+ FILE_SHARE_READ | FILE_SHARE_WRITE,+ std::ptr::null(),+ OPEN_EXISTING,+ FILE_FLAG_OPEN_REPARSE_POINT,+ std::ptr::null_mut(),+ )+ };+ if handle as isize == -1 {+ return Err(last_error(+ "failed to open the perception ACL coordination lease",+ ));+ }+ let mut tag = FileAttributeTagInfo {+ file_attributes: 0,+ reparse_tag: 0,+ };+ if unsafe {+ GetFileInformationByHandleEx(+ handle,+ FILE_ATTRIBUTE_TAG_INFO_CLASS,+ std::ptr::addr_of_mut!(tag).cast(),+ std::mem::size_of::<FileAttributeTagInfo>() as u32,+ )+ } == FALSE+ {+ unsafe {+ CloseHandle(handle);+ }+ return Err(last_error(+ "failed to inspect the perception ACL coordination lease",+ ));+ }+ if tag.file_attributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT) != 0 {+ unsafe {+ CloseHandle(handle);+ }+ return Err(containment_error(+ "the perception ACL coordination lease is not a regular file",+ None,+ ));+ }+ let file = unsafe { std::fs::File::from_raw_handle(handle.cast()) };+ match file.try_lock_exclusive() {+ Ok(()) => {+ recover_acl_profile_journal(&acl_profile_journal_path(path))?;+ Ok(Self { _file: file })+ }+ Err(cause)+ if cause.kind() == std::io::ErrorKind::WouldBlock+ || cause.raw_os_error() == fs2::lock_contended_error().raw_os_error() =>+ {+ Err(error(+ VisualParseErrorCode::WorkerLaunchFailed,+ "another perception worker is using the Windows ACL boundary",+ true,+ None,+ ))+ }+ Err(cause) => Err(containment_error(+ "failed to acquire the perception ACL coordination lease",+ os_detail(&cause),+ )),+ }+ }+}++fn current_user_sid() -> Result<UserSid, VisualParseError> {+ let mut token: Handle = std::ptr::null_mut();+ if unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) } == FALSE {+ return Err(last_error(+ "failed to read the Driver identity for the perception worker sandbox",+ ));+ }+ let token = OwnedHandle(token);+ let mut required = 0_u32;+ unsafe {+ GetTokenInformation(+ token.get(),+ TOKEN_USER_CLASS,+ std::ptr::null_mut(),+ 0,+ &mut required,+ );+ }+ if required == 0+ || std::io::Error::last_os_error().raw_os_error() != Some(ERROR_INSUFFICIENT_BUFFER)+ {+ return Err(last_error(+ "failed to size the Driver identity for the perception worker sandbox",+ ));+ }+ let mut buffer = vec![0_u8; required as usize];+ if unsafe {+ GetTokenInformation(+ token.get(),+ TOKEN_USER_CLASS,+ buffer.as_mut_ptr().cast(),+ required,+ &mut required,+ )+ } == FALSE+ {+ return Err(last_error(+ "failed to read the Driver identity for the perception worker sandbox",+ ));+ }+ Ok(UserSid { buffer })+}++/// A private, protected discretionary access control list plus the security+/// descriptor that carries it.+struct PrivateSecurity {+ descriptor: Box<SecurityDescriptorStorage>,+ _acl: LocalAcl,+}++impl PrivateSecurity {+ fn new(grants: &[(*mut c_void, u32)]) -> Result<Self, VisualParseError> {+ let acl = build_acl(grants, NO_INHERITANCE, std::ptr::null_mut())?;+ let mut descriptor = Box::new(SecurityDescriptorStorage([0_u8; 64]));+ let pointer: *mut c_void = std::ptr::addr_of_mut!(descriptor.0).cast();+ if unsafe { InitializeSecurityDescriptor(pointer, SECURITY_DESCRIPTOR_REVISION) } == FALSE {+ return Err(last_error(+ "failed to create the private security descriptor for the perception worker",+ ));+ }+ if unsafe { SetSecurityDescriptorDacl(pointer, TRUE, acl.0, FALSE) } == FALSE {+ return Err(last_error(+ "failed to apply the private access control list for the perception worker",+ ));+ }+ Ok(Self {+ descriptor,+ _acl: acl,+ })+ }++ fn attributes(&self) -> SecurityAttributes {+ SecurityAttributes {+ length: std::mem::size_of::<SecurityAttributes>() as u32,+ security_descriptor: std::ptr::addr_of!(self.descriptor.0).cast_mut().cast(),+ inherit_handle: FALSE,+ }+ }+}++/// An access control list allocated by `SetEntriesInAclW`.+struct LocalAcl(*mut c_void);++// The ACL is an owned `LocalAlloc` allocation and is only read while installed+// in a descriptor or passed to the security APIs.+unsafe impl Send for LocalAcl {}++impl Drop for LocalAcl {+ fn drop(&mut self) {+ if !self.0.is_null() {+ unsafe {+ LocalFree(self.0);+ }+ }+ }+}++fn build_acl(+ grants: &[(*mut c_void, u32)],+ inheritance: u32,+ existing: *mut c_void,+) -> Result<LocalAcl, VisualParseError> {+ let mut entries: Vec<ExplicitAccessW> = grants+ .iter()+ .map(|(sid, access)| ExplicitAccessW {+ access_permissions: *access,+ access_mode: GRANT_ACCESS,+ inheritance,+ trustee: TrusteeW {+ multiple_trustee: std::ptr::null_mut(),+ multiple_trustee_operation: NO_MULTIPLE_TRUSTEE,+ trustee_form: TRUSTEE_IS_SID,+ trustee_type: TRUSTEE_IS_UNKNOWN,+ name: (*sid).cast(),+ },+ })+ .collect();+ let mut acl: *mut c_void = std::ptr::null_mut();+ let status = unsafe {+ SetEntriesInAclW(+ entries.len() as u32,+ entries.as_mut_ptr(),+ existing,+ &mut acl,+ )+ };+ if status != ERROR_SUCCESS || acl.is_null() {+ return Err(containment_error(+ "failed to build the access control list for the perception worker",+ Some(format!("os error {status}")),+ ));+ }+ Ok(LocalAcl(acl))+}++/// Temporarily give the worker's AppContainer identity exactly the access its+/// bundle, runtime, model and working-directory paths require, and nothing+/// else. Every prior DACL is restored after the process exits.+///+/// The working directory receives a protected list naming only the Driver's+/// user and the worker, so no other account on the machine can read the+/// screenshot the worker is parsing. The remaining roots are merged rather than+/// replaced, because they are shared installation paths whose existing+/// permissions belong to the installer.+fn grant_worker_paths(+ working_directory: &Path,+ boundary: &FilesystemBoundary,+ user: *mut c_void,+ container: *mut c_void,+) -> Result<AclGrantLedger, VisualParseError> {+ let working = std::fs::canonicalize(working_directory).map_err(|cause| {+ containment_error(+ "failed to resolve the private perception worker directory",+ os_detail(&cause),+ )+ })?;+ let mut ledger = AclGrantLedger::default();+ let result = (|| {+ ledger+ .set_protected_dacl_tree(&working, &[(user, GENERIC_ALL), (container, GENERIC_ALL)])?;+ for root in &boundary.writable {+ if *root == working {+ continue;+ }+ ledger.merge_grant_tree(root, container, GENERIC_ALL, true)?;+ }+ for root in &boundary.readable {+ if *root == working+ || boundary+ .writable+ .iter()+ .any(|writable| root.starts_with(writable))+ {+ continue;+ }+ ledger.merge_grant_tree(root, container, GENERIC_READ | GENERIC_EXECUTE, false)?;+ }+ Ok(())+ })();+ match result {+ Ok(()) => Ok(ledger),+ Err(cause) => match ledger.revoke() {+ Ok(()) => Err(cause),+ Err(rollback) => Err(rollback),+ },+ }+}++#[derive(Clone, Copy, Debug, Eq, PartialEq)]+struct FileIdentity {+ volume_serial_number: u32,+ file_index_high: u32,+ file_index_low: u32,+}++struct SavedDacl {+ target: AclTarget,+ descriptor: LocalAcl,+ dacl_offset: Option<usize>,+ protected: bool,+}++impl SavedDacl {+ fn capture(target: AclTarget) -> Result<Self, VisualParseError> {+ let mut dacl: *mut c_void = std::ptr::null_mut();+ let mut descriptor: *mut c_void = std::ptr::null_mut();+ let status = unsafe {+ GetSecurityInfo(+ target.handle.get(),+ SE_FILE_OBJECT,+ DACL_SECURITY_INFORMATION,+ std::ptr::null_mut(),+ std::ptr::null_mut(),+ &mut dacl,+ std::ptr::null_mut(),+ &mut descriptor,+ )+ };+ if status != ERROR_SUCCESS || descriptor.is_null() {+ return Err(containment_error(+ "failed to save the existing permissions of a perception worker path",+ Some(format!("os error {status}")),+ ));+ }+ let descriptor = LocalAcl(descriptor);+ let mut control = 0_u16;+ let mut revision = 0_u32;+ if unsafe { GetSecurityDescriptorControl(descriptor.0, &mut control, &mut revision) }+ == FALSE+ {+ return Err(last_error(+ "failed to save perception worker ACL control flags",+ ));+ }+ let dacl_offset = (!dacl.is_null()).then(|| dacl as usize - descriptor.0 as usize);+ Ok(Self {+ target,+ descriptor,+ dacl_offset,+ protected: control & 0x1000 != 0,+ })+ }++ fn restore(&self) -> Result<(), VisualParseError> {+ let dacl = self.dacl_offset.map_or(std::ptr::null_mut(), |offset| {+ (self.descriptor.0 as usize + offset) as *mut c_void+ });+ let protection = if self.protected {+ PROTECTED_DACL_SECURITY_INFORMATION+ } else {+ UNPROTECTED_DACL_SECURITY_INFORMATION+ };+ apply_dacl(+ self.target.handle.get(),+ dacl,+ DACL_SECURITY_INFORMATION | protection,+ "failed to revoke temporary perception worker filesystem access",+ )+ }+}++#[derive(Default)]+struct AclGrantLedger {+ entries: Vec<SavedDacl>,+}++impl AclGrantLedger {+ fn contains(&self, identity: FileIdentity) -> bool {+ self.entries+ .iter()+ .any(|entry| entry.target.identity == identity)+ }++ fn set_protected_dacl_tree(+ &mut self,+ path: &Path,+ grants: &[(*mut c_void, u32)],+ ) -> Result<(), VisualParseError> {+ walk_acl_tree(path, &mut |target| {+ if self.contains(target.identity) {+ return Ok(());+ }+ let saved = SavedDacl::capture(target)?;+ let acl = build_acl(grants, saved.target.inheritance(true), std::ptr::null_mut())?;+ apply_dacl(+ saved.target.handle.get(),+ acl.0,+ DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,+ "failed to apply the private access control list to the perception worker directory",+ )?;+ self.entries.push(saved);+ Ok(())+ })+ }++ fn merge_grant_tree(+ &mut self,+ path: &Path,+ sid: *mut c_void,+ access: u32,+ inherit_children: bool,+ ) -> Result<(), VisualParseError> {+ walk_acl_tree(path, &mut |target| {+ // Writable trees are processed first. Skipping an already-seen+ // identity prevents a later overlapping read root from adding a+ // duplicate ACE or replacing its stronger grant.+ if self.contains(target.identity) {+ return Ok(());+ }+ let saved = SavedDacl::capture(target)?;+ let existing = saved.dacl_offset.map_or(std::ptr::null_mut(), |offset| {+ (saved.descriptor.0 as usize + offset) as *mut c_void+ });+ let acl = build_acl(+ &[(sid, access)],+ saved.target.inheritance(inherit_children),+ existing,+ )?;+ apply_dacl(+ saved.target.handle.get(),+ acl.0,+ DACL_SECURITY_INFORMATION,+ "failed to grant the perception worker access to its own bundle",+ )?;+ self.entries.push(saved);+ Ok(())+ })+ }++ fn revoke(&mut self) -> Result<(), VisualParseError> {+ let mut first_failure = None;+ let mut failed = Vec::new();+ for entry in std::mem::take(&mut self.entries).into_iter().rev() {+ if let Err(cause) = entry.restore() {+ first_failure.get_or_insert(cause);+ failed.push(entry);+ }+ }+ // Preserve grant order so a later retry still restores descendants+ // before their parents. Guard teardown retries failures after the+ // normal-reap path, and Drop retries a failed pre-launch rollback.+ failed.reverse();+ self.entries = failed;+ first_failure.map_or(Ok(()), Err)+ }+}++impl Drop for AclGrantLedger {+ fn drop(&mut self) {+ let _ = self.revoke();+ }+}++/// Visit an ACL root and every existing descendant. After each verified+/// no-follow handle is acquired without delete sharing, the retained handle+/// blocks new delete or rename opens through DACL restoration. Protected child+/// DACLs do not inherit a root grant, so each object receives its own ACE. Any+/// failed open, validation, enumeration, or ACL update aborts the launch.+fn walk_acl_tree(+ path: &Path,+ apply: &mut impl FnMut(AclTarget) -> Result<(), VisualParseError>,+) -> Result<(), VisualParseError> {+ let target = AclTarget::open(path)?;+ let is_directory = target.is_directory();+ let resolved = target.path.clone();+ apply(target)?;+ if !is_directory {+ return Ok(());+ }++ let entries = std::fs::read_dir(&resolved).map_err(|cause| {+ containment_error(+ "failed to enumerate a perception worker ACL directory",+ os_detail(&cause),+ )+ })?;+ for entry in entries {+ let entry = entry.map_err(|cause| {+ containment_error(+ "failed to enumerate a perception worker ACL directory",+ os_detail(&cause),+ )+ })?;+ walk_acl_tree(&resolved.join(entry.file_name()), apply)?;+ }+ Ok(())+}++fn apply_dacl(+ target: Handle,+ acl: *mut c_void,+ information: u32,+ message: &'static str,+) -> Result<(), VisualParseError> {+ let status = unsafe {+ SetSecurityInfo(+ target,+ SE_FILE_OBJECT,+ information,+ std::ptr::null_mut(),+ std::ptr::null_mut(),+ acl,+ std::ptr::null_mut(),+ )+ };+ if status != ERROR_SUCCESS {+ return Err(containment_error(+ message,+ Some(format!("os error {status}")),+ ));+ }+ Ok(())+}++/// An ACL target opened without following a final reparse point. The final+/// kernel-resolved name is compared with the already canonical policy path+/// before any grant is applied. A concurrent ancestor swap that redirects the+/// open resolves to a different name and is refused. Once acquired, the handle+/// is retained without delete sharing, blocking new delete or rename opens+/// through DACL restoration.+struct AclTarget {+ handle: OwnedHandle,+ path: PathBuf,+ identity: FileIdentity,+ file_attributes: u32,+}++impl AclTarget {+ fn open(path: &Path) -> Result<Self, VisualParseError> {+ let name = wide(path.as_os_str());+ let handle = unsafe {+ CreateFileW(+ name.as_ptr(),+ FILE_READ_DATA | READ_CONTROL | WRITE_DAC,+ // Allow ordinary readers and writers to keep using shared+ // installation roots. FILE_READ_DATA engages file share+ // accounting; descriptor-only rights such as READ_CONTROL and+ // WRITE_DAC do not. Once acquired, withholding delete sharing+ // blocks new delete or rename opens until the handle is released.+ FILE_SHARE_READ | FILE_SHARE_WRITE,+ std::ptr::null(),+ OPEN_EXISTING,+ FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,+ std::ptr::null_mut(),+ )+ };+ if handle as isize == -1 {+ return Err(last_error(+ "failed to open a perception worker path for an ACL update",+ ));+ }+ let handle = OwnedHandle(handle);++ let mut tag = FileAttributeTagInfo {+ file_attributes: 0,+ reparse_tag: 0,+ };+ if unsafe {+ GetFileInformationByHandleEx(+ handle.get(),+ FILE_ATTRIBUTE_TAG_INFO_CLASS,+ std::ptr::addr_of_mut!(tag).cast(),+ std::mem::size_of::<FileAttributeTagInfo>() as u32,+ )+ } == FALSE+ {+ return Err(last_error(+ "failed to validate a perception worker ACL target",+ ));+ }+ if tag.file_attributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 {+ return Err(containment_error(+ "a perception worker ACL target is a reparse point",+ None,+ ));+ }++ let resolved = final_path(&handle)?;+ if normalize_windows_path(&resolved) != normalize_windows_path(path) {+ return Err(containment_error(+ "a perception worker ACL target changed while it was opened",+ None,+ ));+ }+ let mut information = std::mem::MaybeUninit::<ByHandleFileInformation>::uninit();+ if unsafe { GetFileInformationByHandle(handle.get(), information.as_mut_ptr()) } == FALSE {+ return Err(last_error(+ "failed to identify a perception worker ACL target",+ ));+ }+ let information = unsafe { information.assume_init() };+ Ok(Self {+ handle,+ path: resolved,+ identity: FileIdentity {+ volume_serial_number: information.volume_serial_number,+ file_index_high: information.file_index_high,+ file_index_low: information.file_index_low,+ },+ file_attributes: tag.file_attributes,+ })+ }++ fn is_directory(&self) -> bool {+ self.file_attributes & FILE_ATTRIBUTE_DIRECTORY != 0+ }++ fn inheritance(&self, inherit_children: bool) -> u32 {+ if inherit_children && self.is_directory() {+ SUB_CONTAINERS_AND_OBJECTS_INHERIT+ } else {+ NO_INHERITANCE+ }+ }+}++fn final_path(handle: &OwnedHandle) -> Result<std::path::PathBuf, VisualParseError> {+ let required = unsafe {+ GetFinalPathNameByHandleW(handle.get(), std::ptr::null_mut(), 0, FILE_NAME_NORMALIZED)+ };+ if required == 0 {+ return Err(last_error(+ "failed to size a perception worker ACL target path",+ ));+ }+ let mut path = vec![0_u16; required as usize];+ let written = unsafe {+ GetFinalPathNameByHandleW(+ handle.get(),+ path.as_mut_ptr(),+ path.len() as u32,+ FILE_NAME_NORMALIZED,+ )+ };+ if written == 0 || written as usize >= path.len() {+ return Err(last_error(+ "failed to read a perception worker ACL target path",+ ));+ }+ path.truncate(written as usize);+ Ok(std::path::PathBuf::from(std::ffi::OsString::from_wide(+ &path,+ )))+}++fn normalize_windows_path(path: &Path) -> String {+ let mut text = path.as_os_str().to_string_lossy().replace('/', "\\");+ if let Some(stripped) = text.strip_prefix(r"\\?\UNC\") {+ text = format!(r"\\{stripped}");+ } else if let Some(stripped) = text.strip_prefix(r"\\?\") {+ text = stripped.to_owned();+ }+ text.trim_end_matches('\\').to_ascii_lowercase()+}++/// A minimal environment block. The worker inherits nothing from the Driver, so+/// no proxy setting, token, or caller path reaches it; only the loader's+/// `SystemRoot` and private temporary and profile directories inside the+/// working directory are provided.+fn environment_block(working_directory: &Path) -> Result<Vec<u16>, VisualParseError> {+ let profile = working_directory.join("profile");+ let roaming_app_data = profile.join("AppData").join("Roaming");+ let local_app_data = profile.join("AppData").join("Local");+ std::fs::create_dir_all(&profile).map_err(|cause| {+ containment_error(+ "failed to create the perception worker's private profile directory",+ os_detail(&cause),+ )+ })?;+ std::fs::create_dir_all(&roaming_app_data).map_err(|cause| {+ containment_error(+ "failed to create the perception worker's private roaming application data directory",+ os_detail(&cause),+ )+ })?;+ std::fs::create_dir_all(&local_app_data).map_err(|cause| {+ containment_error(+ "failed to create the perception worker's private local application data directory",+ os_detail(&cause),+ )+ })?;++ let mut system_root = vec![0_u16; 260];+ let written =+ unsafe { GetSystemWindowsDirectoryW(system_root.as_mut_ptr(), system_root.len() as u32) };+ if written == 0 || written as usize >= system_root.len() {+ return Err(last_error(+ "failed to read the system directory for the perception worker environment",+ ));+ }+ system_root.truncate(written as usize);+ let system_root = String::from_utf16_lossy(&system_root);+ let temporary = working_directory.display().to_string();+ let profile = profile.display().to_string();+ let roaming_app_data = roaming_app_data.display().to_string();+ let local_app_data = local_app_data.display().to_string();++ let mut block = Vec::new();+ let mut entries = [+ format!("APPDATA={roaming_app_data}"),+ format!("LOCALAPPDATA={local_app_data}"),+ format!("SystemRoot={system_root}"),+ format!("PATH={system_root}\\System32"),+ format!("TEMP={temporary}"),+ format!("TMP={temporary}"),+ format!("USERPROFILE={profile}"),+ format!("windir={system_root}"),+ ];+ entries.sort_by_key(|entry| entry.to_ascii_lowercase());+ for entry in entries {+ block.extend(entry.encode_utf16());+ block.push(0);+ }+ block.push(0);+ Ok(block)+}++fn command_line(executable: &Path, args: &[String]) -> Vec<u16> {+ let mut command_line = Vec::new();+ for argument in+ std::iter::once(executable.as_os_str()).chain(args.iter().map(std::ffi::OsStr::new))+ {+ if !command_line.is_empty() {+ command_line.push(u16::from(b' '));+ }+ append_argument(&mut command_line, argument.encode_wide());+ }+ command_line.push(0);+ command_line+}++/// Quote one argument the way `CommandLineToArgvW` parses it, so an argument+/// containing a space, tab or quote cannot be split or escape into another.+fn append_argument(command_line: &mut Vec<u16>, argument: impl IntoIterator<Item = u16>) {+ let argument = argument.into_iter().collect::<Vec<_>>();+ let quote = argument.is_empty()+ || argument+ .iter()+ .any(|value| matches!(*value, 0x20 | 0x09 | 0x22));+ if !quote {+ command_line.extend(argument);+ return;+ }+ command_line.push(u16::from(b'"'));+ let mut backslashes = 0;+ for value in argument {+ if value == u16::from(b'\\') {+ backslashes += 1;+ } else if value == u16::from(b'"') {+ command_line.extend(std::iter::repeat_n(u16::from(b'\\'), backslashes * 2 + 1));+ command_line.push(value);+ backslashes = 0;+ } else {+ command_line.extend(std::iter::repeat_n(u16::from(b'\\'), backslashes));+ command_line.push(value);+ backslashes = 0;+ }+ }+ command_line.extend(std::iter::repeat_n(u16::from(b'\\'), backslashes * 2));+ command_line.push(u16::from(b'"'));+}++fn inheritable_attributes() -> SecurityAttributes {+ SecurityAttributes {+ length: std::mem::size_of::<SecurityAttributes>() as u32,+ security_descriptor: std::ptr::null_mut(),+ inherit_handle: TRUE,+ }+}++fn wide(value: impl AsRef<OsStr>) -> Vec<u16> {+ value+ .as_ref()+ .encode_wide()+ .chain(std::iter::once(0))+ .collect()+}++fn last_error(message: &'static str) -> VisualParseError {+ containment_error(message, os_detail(&std::io::Error::last_os_error()))+}++#[cfg(test)]+mod tests {+ use super::*;++ // Windows may map generic rights to their file-specific equivalents.+ const FILE_READ_EXECUTE: u32 = 0x0012_00A9;+ const FILE_ALL_ACCESS: u32 = 0x001F_01FF;+ const DELETE: u32 = 0x0001_0000;+ const FILE_SHARE_DELETE: u32 = 0x0000_0004;+ const ERROR_SHARING_VIOLATION: i32 = 32;+ const INHERIT_ONLY_ACE: u8 = 0x08;+ const INHERITED_ACE: u8 = 0x10;++ fn test_profile_name() -> String {+ format!(+ "{APP_CONTAINER_NAME_PREFIX}.{}",+ uuid::Uuid::new_v4().simple()+ )+ }++ fn canonical_test_root(root: &tempfile::TempDir) -> PathBuf {+ std::fs::canonicalize(root.path()).unwrap()+ }++ fn open_delete_shared(path: &Path) -> OwnedHandle {+ let name = wide(path.as_os_str());+ let handle = unsafe {+ CreateFileW(+ name.as_ptr(),+ DELETE,+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,+ std::ptr::null(),+ OPEN_EXISTING,+ FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,+ std::ptr::null_mut(),+ )+ };+ if handle as isize == -1 {+ panic!(+ "failed to pre-open {} with DELETE access: {}",+ path.display(),+ std::io::Error::last_os_error()+ );+ }+ OwnedHandle(handle)+ }++ fn is_equivalent_file_grant(mask: u32, requested: u32) -> bool {+ mask == requested+ || match requested {+ requested if requested == (GENERIC_READ | GENERIC_EXECUTE) => {+ mask == FILE_READ_EXECUTE+ }+ GENERIC_ALL => mask == FILE_ALL_ACCESS,+ _ => false,+ }+ }++ #[test]+ fn generated_profile_names_fit_the_windows_limit() {+ let first = test_profile_name();+ let second = test_profile_name();+ assert_ne!(first, second);+ assert!(first.encode_utf16().count() <= 64);+ validate_profile_name(&first).unwrap();+ }++ #[test]+ fn legacy_oversized_profile_journal_is_removed_without_deletion() {+ let root = tempfile::tempdir().unwrap();+ let path = root.path().join("runtime-acl.lock.profile");+ let legacy = format!(+ "{LEGACY_OVERSIZED_APP_CONTAINER_NAME_PREFIX}.{}",+ uuid::Uuid::new_v4().simple()+ );+ assert!(legacy.encode_utf16().count() > 64);+ let mut file = std::fs::File::create(&path).unwrap();+ file.write_all(legacy.as_bytes()).unwrap();+ file.write_all(b"\n").unwrap();+ file.sync_all().unwrap();+ drop(file);++ recover_acl_profile_journal_with(&path, |_| {+ panic!("an oversized legacy profile could not have been created")+ })+ .unwrap();++ assert!(!path.exists());+ assert!(!journal_tombstone_path(&path).exists());+ }++ #[repr(C)]+ struct AceHeader {+ ace_type: u8,+ ace_flags: u8,+ ace_size: u16,+ }++ #[repr(C)]+ struct AccessAllowedAce {+ header: AceHeader,+ mask: u32,+ sid_start: u32,+ }++ fn matching_grants(+ path: &Path,+ sid: *mut c_void,+ ) -> Result<(bool, Vec<(u32, u8)>), VisualParseError> {+ #[link(name = "advapi32")]+ extern "system" {+ fn EqualSid(left: *mut c_void, right: *mut c_void) -> Bool;+ fn GetAce(acl: *const c_void, index: u32, ace: *mut *mut c_void) -> Bool;+ fn GetSecurityDescriptorControl(+ descriptor: *mut c_void,+ control: *mut u16,+ revision: *mut u32,+ ) -> Bool;+ }++ let target = AclTarget::open(path)?;+ let mut dacl: *mut c_void = std::ptr::null_mut();+ let mut descriptor: *mut c_void = std::ptr::null_mut();+ let status = unsafe {+ GetSecurityInfo(+ target.handle.get(),+ SE_FILE_OBJECT,+ DACL_SECURITY_INFORMATION,+ std::ptr::null_mut(),+ std::ptr::null_mut(),+ &mut dacl,+ std::ptr::null_mut(),+ &mut descriptor,+ )+ };+ if status != ERROR_SUCCESS || dacl.is_null() || descriptor.is_null() {+ return Err(containment_error(+ "failed to inspect a perception worker ACL in a test",+ Some(format!("os error {status}")),+ ));+ }+ let descriptor = LocalAcl(descriptor);+ let mut control = 0_u16;+ let mut revision = 0_u32;+ if unsafe { GetSecurityDescriptorControl(descriptor.0, &mut control, &mut revision) }+ == FALSE+ {+ return Err(last_error(+ "failed to inspect perception worker ACL control flags in a test",+ ));+ }++ #[repr(C)]+ struct AclHeader {+ revision: u8,+ sbz1: u8,+ size: u16,+ ace_count: u16,+ sbz2: u16,+ }++ let ace_count = unsafe { (*(dacl.cast::<AclHeader>())).ace_count };+ let mut grants = Vec::new();+ for index in 0..u32::from(ace_count) {+ let mut raw: *mut c_void = std::ptr::null_mut();+ if unsafe { GetAce(dacl, index, &mut raw) } == FALSE || raw.is_null() {+ return Err(last_error(+ "failed to inspect a perception worker ACL entry in a test",+ ));+ }+ let ace = unsafe { &*raw.cast::<AccessAllowedAce>() };+ if ace.header.ace_type != 0 {+ continue;+ }+ let ace_sid = std::ptr::addr_of!(ace.sid_start).cast_mut().cast();+ if unsafe { EqualSid(ace_sid, sid) } != FALSE {+ grants.push((ace.mask, ace.header.ace_flags));+ }+ }+ Ok((control & 0x1000 != 0, grants))+ }++ fn protect_tree(path: &Path, grants: &[(*mut c_void, u32)]) {+ walk_acl_tree(path, &mut |target| {+ let acl = build_acl(grants, target.inheritance(true), std::ptr::null_mut())?;+ apply_dacl(+ target.handle.get(),+ acl.0,+ DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,+ "failed to protect a perception worker test path",+ )+ })+ .unwrap();+ }++ #[test]+ fn every_job_ui_restriction_is_applied() {+ for restriction in [+ JOB_OBJECT_UILIMIT_HANDLES,+ JOB_OBJECT_UILIMIT_READCLIPBOARD,+ JOB_OBJECT_UILIMIT_WRITECLIPBOARD,+ JOB_OBJECT_UILIMIT_SYSTEMPARAMETERS,+ JOB_OBJECT_UILIMIT_DISPLAYSETTINGS,+ JOB_OBJECT_UILIMIT_GLOBALATOMS,+ JOB_OBJECT_UILIMIT_DESKTOP,+ JOB_OBJECT_UILIMIT_EXITWINDOWS,+ ] {+ assert_eq!(JOB_OBJECT_UILIMIT_ALL & restriction, restriction);+ }+ }++ #[test]+ fn wait_status_requires_a_signaled_process() {+ assert!(classify_wait_status(WAIT_OBJECT_0, || {+ panic!("a successful wait must not inspect the last error")+ })+ .is_ok());++ let failed =+ classify_wait_status(WAIT_FAILED, || std::io::Error::from_raw_os_error(6)).unwrap_err();+ assert_eq!(failed.raw_os_error(), Some(6));++ let timeout = classify_wait_status(WAIT_TIMEOUT, || {+ panic!("an unexpected wait status must not inspect the last error")+ })+ .unwrap_err();+ assert!(timeout+ .to_string()+ .contains("unexpected WaitForSingleObject status"));+ }++ #[test]+ fn app_container_delete_classifies_idempotent_results() {+ assert_eq!(classify_app_container_delete(0), Ok(()));+ assert_eq!(classify_app_container_delete(1), Ok(()));+ assert_eq!(classify_app_container_delete(-2_147_024_894), Ok(()));+ assert_eq!(classify_app_container_delete(-2_147_023_728), Ok(()));+ assert_eq!(classify_app_container_delete(-1), Err(-1));+ }++ #[test]+ fn journal_is_durable_before_profile_creation_runs() {+ let root = tempfile::tempdir().unwrap();+ let path = root.path().join("runtime-acl.lock.profile");+ let profile = test_profile_name();+ let observed = std::cell::Cell::new(false);+ let (mut journal, ()) = journal_before_profile(path.clone(), &profile, || {+ observed.set(path.is_file());+ Ok(())+ })+ .unwrap();++ assert!(observed.get());+ journal.clear().unwrap();+ assert!(!path.exists());+ }++ #[test]+ fn missing_profile_recovery_is_idempotent_and_removes_journal() {+ let root = tempfile::tempdir().unwrap();+ let path = root.path().join("runtime-acl.lock.profile");+ let profile = test_profile_name();+ AppContainerJournal::persist(path.clone(), &profile).unwrap();++ recover_acl_profile_journal(&path).unwrap();+ recover_acl_profile_journal(&path).unwrap();+ assert!(!path.exists());+ assert!(!journal_tombstone_path(&path).exists());+ }++ #[test]+ fn empty_pending_journal_is_removed_without_profile_recovery() {+ let root = tempfile::tempdir().unwrap();+ let path = root.path().join("runtime-acl.lock.profile");+ let pending = journal_pending_path(&path);+ std::fs::write(&pending, b"").unwrap();++ recover_acl_profile_journal_with(&path, |_| {+ panic!("pending state cannot correspond to a created profile")+ })+ .unwrap();+ assert!(!pending.exists());+ }++ #[test]+ fn truncated_pending_journal_is_removed_without_profile_recovery() {+ let root = tempfile::tempdir().unwrap();+ let path = root.path().join("runtime-acl.lock.profile");+ let pending = journal_pending_path(&path);+ std::fs::write(&pending, b"com.trycua.cua-driver").unwrap();++ recover_acl_profile_journal_with(&path, |_| {+ panic!("pending state cannot correspond to a created profile")+ })+ .unwrap();+ assert!(!pending.exists());+ }++ #[test]+ fn pending_journal_directory_is_rejected() {+ let root = tempfile::tempdir().unwrap();+ let path = root.path().join("runtime-acl.lock.profile");+ let pending = journal_pending_path(&path);+ std::fs::create_dir(&pending).unwrap();++ assert!(recover_acl_profile_journal_with(&path, |_| Ok(())).is_err());+ assert!(pending.is_dir());+ }++ #[test]+ fn failed_profile_recovery_retains_the_journal() {+ let root = tempfile::tempdir().unwrap();+ let path = root.path().join("runtime-acl.lock.profile");+ let profile = test_profile_name();+ AppContainerJournal::persist(path.clone(), &profile).unwrap();++ let failure = recover_acl_profile_journal_with(&path, |_| {+ Err(containment_error("injected profile deletion failure", None))+ });+ assert!(failure.is_err());+ assert!(path.is_file());+ }++ #[test]+ fn successful_cleanup_removes_the_profile_journal() {+ let root = tempfile::tempdir().unwrap();+ let path = root.path().join("runtime-acl.lock.profile");+ let profile = test_profile_name();+ let journal = AppContainerJournal::persist(path.clone(), &profile).unwrap();+ let container = AppContainerSid::create(&profile).unwrap();+ let mut cleanup = PendingCleanup {+ process: 0,+ process_reaped: true,+ grants: None,+ container: Some(container),+ journal: Some(journal),+ lease: None,+ };++ cleanup.cleanup_reaped_once().unwrap();+ assert!(cleanup.is_clean());+ assert!(!path.exists());+ }++ #[test]+ fn repeated_wait_failures_reach_the_process_fatal_boundary() {+ assert!(!cleanup_wait_is_fatal(CLEANUP_WAIT_FAILURE_ATTEMPTS - 1));+ assert!(cleanup_wait_is_fatal(CLEANUP_WAIT_FAILURE_ATTEMPTS));+ }++ #[test]+ fn repeated_authority_cleanup_failures_reach_the_process_fatal_boundary() {+ assert!(!cleanup_authority_failure_is_fatal(+ CLEANUP_AUTHORITY_FAILURE_ATTEMPTS - 1+ ));+ assert!(cleanup_authority_failure_is_fatal(+ CLEANUP_AUTHORITY_FAILURE_ATTEMPTS+ ));+ }++ #[test]+ fn the_desktop_grant_withholds_hooks_and_desktop_switching() {+ const DESKTOP_HOOKCONTROL: u32 = 0x0008;+ const DESKTOP_JOURNALRECORD: u32 = 0x0010;+ const DESKTOP_JOURNALPLAYBACK: u32 = 0x0020;+ const DESKTOP_SWITCHDESKTOP: u32 = 0x0100;+ for withheld in [+ DESKTOP_HOOKCONTROL,+ DESKTOP_JOURNALRECORD,+ DESKTOP_JOURNALPLAYBACK,+ DESKTOP_SWITCHDESKTOP,+ ] {+ assert_eq!(DESKTOP_WORKER_ACCESS & withheld, 0);+ }+ }++ #[test]+ fn the_command_line_quotes_arguments_that_could_otherwise_split() {+ let rendered = command_line(+ Path::new(r"C:\Program Files\cua\worker.exe"),+ &["--manifest".to_owned(), r"C:\a b\m.json".to_owned()],+ );+ let rendered = String::from_utf16(&rendered[..rendered.len() - 1]).unwrap();+ assert_eq!(+ rendered,+ "\"C:\\Program Files\\cua\\worker.exe\" --manifest \"C:\\a b\\m.json\""+ );+ }++ #[test]+ fn the_environment_block_carries_only_loader_and_private_worker_paths() {+ let worker_root = tempfile::tempdir().unwrap();+ let block = environment_block(worker_root.path()).unwrap();+ let rendered = String::from_utf16(&block).unwrap();+ let entries = rendered+ .split('\0')+ .filter(|entry| !entry.is_empty())+ .map(|entry| entry.split_once('=').unwrap())+ .collect::<std::collections::HashMap<_, _>>();++ let expected_profile = worker_root.path().join("profile");+ let expected_roaming = expected_profile.join("AppData").join("Roaming");+ let expected_local = expected_profile.join("AppData").join("Local");+ assert_eq!(entries["TEMP"], worker_root.path().display().to_string());+ assert_eq!(entries["TMP"], worker_root.path().display().to_string());+ assert_eq!(+ entries["USERPROFILE"],+ expected_profile.display().to_string()+ );+ assert_eq!(entries["APPDATA"], expected_roaming.display().to_string());+ assert_eq!(+ entries["LOCALAPPDATA"],+ expected_local.display().to_string()+ );+ assert!(entries.contains_key("SystemRoot"));+ assert!(entries.contains_key("windir"));+ assert!(entries.contains_key("PATH"));+ for unrelated in ["HTTP_PROXY", "PATHEXT", "USERNAME", "HOMEDRIVE"] {+ assert!(+ !entries.contains_key(unrelated),+ "{unrelated} reached the worker"+ );+ }+ for path in [&expected_profile, &expected_roaming, &expected_local] {+ assert!(path.is_dir(), "{} was not created", path.display());+ assert!(path.starts_with(worker_root.path()));+ }+ for name in ["USERPROFILE", "APPDATA", "LOCALAPPDATA"] {+ assert!(Path::new(entries[name]).starts_with(worker_root.path()));+ if let Some(host) = std::env::var_os(name) {+ assert_ne!(+ normalize_windows_path(Path::new(entries[name])),+ normalize_windows_path(Path::new(&host)),+ "{name} reused the host profile path"+ );+ }+ }+ assert!(rendered.ends_with("\0\0"));+ }++ #[test]+ fn final_handle_paths_compare_without_win32_namespace_prefixes() {+ assert_eq!(+ normalize_windows_path(Path::new(r"\\?\C:\Cua\Worker")),+ normalize_windows_path(Path::new(r"c:\cua\worker\"))+ );+ assert_eq!(+ normalize_windows_path(Path::new(r"\\?\UNC\server\share\worker")),+ normalize_windows_path(Path::new(r"\\server\share\worker"))+ );+ }++ #[test]+ fn protected_descendants_receive_direct_least_privilege_grants() {+ let root = tempfile::tempdir().unwrap();+ let bundle = root.path().join("bundle");+ let models = bundle.join("models");+ let model = models.join("detector.onnx");+ let working = root.path().join("working");+ let scratch = working.join("capture.png");+ std::fs::create_dir_all(&models).unwrap();+ std::fs::create_dir(&working).unwrap();+ std::fs::write(&model, b"model").unwrap();+ std::fs::write(&scratch, b"capture").unwrap();++ // Production boundaries are canonicalized before ACL admission. Match+ // that contract so Windows short-path aliases cannot affect this test.+ let root = canonical_test_root(&root);+ let bundle = root.join("bundle");+ let models = bundle.join("models");+ let model = models.join("detector.onnx");+ let working = root.join("working");+ let scratch = working.join("capture.png");++ let user = current_user_sid().unwrap();+ protect_tree(&bundle, &[(user.sid(), GENERIC_ALL)]);+ let container = AppContainerSid::create_unique().unwrap();+ let boundary = FilesystemBoundary {+ readable: vec![bundle.clone(), working.clone()],+ writable: vec![working.clone()],+ executables: Vec::new(),+ };+ let mut ledger =+ grant_worker_paths(&working, &boundary, user.sid(), container.sid()).unwrap();++ for directory in [&bundle, &models] {+ let (protected, grants) = matching_grants(directory, container.sid()).unwrap();+ assert!(protected, "{} lost DACL protection", directory.display());+ assert!(grants.iter().any(|(mask, flags)| {+ is_equivalent_file_grant(*mask, GENERIC_READ | GENERIC_EXECUTE)+ && u32::from(*flags) & SUB_CONTAINERS_AND_OBJECTS_INHERIT == NO_INHERITANCE+ }));+ }+ let (protected, grants) = matching_grants(&model, container.sid()).unwrap();+ assert!(protected, "{} lost DACL protection", model.display());+ assert!(grants.iter().any(|(mask, flags)| {+ is_equivalent_file_grant(*mask, GENERIC_READ | GENERIC_EXECUTE)+ && u32::from(*flags) & SUB_CONTAINERS_AND_OBJECTS_INHERIT == NO_INHERITANCE+ }));++ let (_, grants) = matching_grants(&working, container.sid()).unwrap();+ assert!(grants.iter().any(|(mask, flags)| {+ is_equivalent_file_grant(*mask, GENERIC_ALL)+ && u32::from(*flags) & SUB_CONTAINERS_AND_OBJECTS_INHERIT+ == SUB_CONTAINERS_AND_OBJECTS_INHERIT+ }));+ let (_, grants) = matching_grants(&scratch, container.sid()).unwrap();+ assert!(grants.iter().any(|(mask, flags)| {+ is_equivalent_file_grant(*mask, GENERIC_ALL)+ && u32::from(*flags) & SUB_CONTAINERS_AND_OBJECTS_INHERIT == NO_INHERITANCE+ }));++ ledger.revoke().unwrap();+ for path in [&bundle, &models, &model, &working, &scratch] {+ let (_, grants) = matching_grants(path, container.sid()).unwrap();+ assert!(+ grants.is_empty(),+ "{} retained a temporary AppContainer grant",+ path.display()+ );+ }+ assert!(matching_grants(&bundle, container.sid()).unwrap().0);+ assert!(!matching_grants(&working, container.sid()).unwrap().0);+ }++ #[test]+ fn recursive_grants_do_not_escape_the_boundary_root() {+ let root = tempfile::tempdir().unwrap();+ let bundle = root.path().join("bundle");+ let working = root.path().join("working");+ let outside = root.path().join("outside.bin");+ std::fs::create_dir(&bundle).unwrap();+ std::fs::create_dir(&working).unwrap();+ std::fs::write(bundle.join("inside.bin"), b"inside").unwrap();+ std::fs::write(&outside, b"outside").unwrap();++ let root = canonical_test_root(&root);+ let bundle = root.join("bundle");+ let working = root.join("working");+ let outside = root.join("outside.bin");++ let user = current_user_sid().unwrap();+ let container = AppContainerSid::create_unique().unwrap();+ let boundary = FilesystemBoundary {+ readable: vec![bundle, working.clone()],+ writable: vec![working.clone()],+ executables: Vec::new(),+ };+ let _ledger = grant_worker_paths(&working, &boundary, user.sid(), container.sid()).unwrap();++ let (_, grants) = matching_grants(&outside, container.sid()).unwrap();+ assert!(+ grants.is_empty(),+ "a sibling outside the boundary was granted"+ );+ }++ #[test]+ fn a_partial_recursive_grant_is_rolled_back() {+ let root = tempfile::tempdir().unwrap();+ let bundle = root.path().join("bundle");+ let model = bundle.join("detector.onnx");+ let working = root.path().join("working");+ std::fs::create_dir(&bundle).unwrap();+ std::fs::create_dir(&working).unwrap();+ std::fs::write(&model, b"model").unwrap();++ let root = canonical_test_root(&root);+ let bundle = root.join("bundle");+ let model = bundle.join("detector.onnx");+ let missing = root.join("missing");+ let working = root.join("working");++ let user = current_user_sid().unwrap();+ let container = AppContainerSid::create_unique().unwrap();+ let boundary = FilesystemBoundary {+ readable: vec![bundle.clone(), missing],+ writable: vec![working.clone()],+ executables: Vec::new(),+ };+ assert!(grant_worker_paths(&working, &boundary, user.sid(), container.sid()).is_err());++ for path in [&bundle, &model, &working] {+ let (_, grants) = matching_grants(path, container.sid()).unwrap();+ assert!(+ grants.is_empty(),+ "{} retained a grant after rollback",+ path.display()+ );+ }+ }++ #[test]+ fn overlapping_roots_keep_the_stronger_single_grant() {+ let root = tempfile::tempdir().unwrap();+ let bundle = root.path().join("bundle");+ let writable = bundle.join("cache");+ let artifact = writable.join("compiled.bin");+ let working = root.path().join("working");+ std::fs::create_dir_all(&writable).unwrap();+ std::fs::create_dir(&working).unwrap();+ std::fs::write(&artifact, b"cache").unwrap();++ let root = canonical_test_root(&root);+ let bundle = root.join("bundle");+ let writable = bundle.join("cache");+ let artifact = writable.join("compiled.bin");+ let working = root.join("working");++ let user = current_user_sid().unwrap();+ let container = AppContainerSid::create_unique().unwrap();+ let boundary = FilesystemBoundary {+ readable: vec![bundle],+ writable: vec![working.clone(), writable.clone()],+ executables: Vec::new(),+ };+ let _ledger = grant_worker_paths(&working, &boundary, user.sid(), container.sid()).unwrap();++ for path in [&writable, &artifact] {+ let (_, grants) = matching_grants(path, container.sid()).unwrap();+ assert_eq!(+ grants+ .iter()+ .filter(|(_, flags)| flags & (INHERITED_ACE | INHERIT_ONLY_ACE) == 0)+ .count(),+ 1,+ "{} received duplicate direct grants",+ path.display()+ );+ assert!(grants+ .iter()+ .all(|(mask, _)| is_equivalent_file_grant(*mask, GENERIC_ALL)));+ }+ }++ #[test]+ fn only_writable_directories_grant_new_descendants() {+ let root = tempfile::tempdir().unwrap();+ let readable = root.path().join("models");+ let writable = root.path().join("cache");+ let working = root.path().join("working");+ std::fs::create_dir(&readable).unwrap();+ std::fs::create_dir(&writable).unwrap();+ std::fs::create_dir(&working).unwrap();++ let root = canonical_test_root(&root);+ let readable = root.join("models");+ let writable = root.join("cache");+ let working = root.join("working");++ let user = current_user_sid().unwrap();+ let container = AppContainerSid::create_unique().unwrap();+ let boundary = FilesystemBoundary {+ readable: vec![readable.clone(), writable.clone(), working.clone()],+ writable: vec![working.clone(), writable.clone()],+ executables: Vec::new(),+ };+ let _ledger = grant_worker_paths(&working, &boundary, user.sid(), container.sid()).unwrap();++ let new_model = readable.join("late-model.onnx");+ let new_cache = writable.join("late-cache.bin");+ std::fs::write(&new_model, b"model").unwrap();+ std::fs::write(&new_cache, b"cache").unwrap();+ assert!(matching_grants(&new_model, container.sid())+ .unwrap()+ .1+ .is_empty());+ let (_, grants) = matching_grants(&new_cache, container.sid()).unwrap();+ assert!(grants+ .iter()+ .any(|(mask, _)| is_equivalent_file_grant(*mask, GENERIC_ALL)));+ }++ #[test]+ fn acl_target_handles_block_cross_process_renames_until_revocation() {+ const CHILD_MARKER: &str = "CUA_DRIVER_ACL_RENAME_CHILD";+ const CHILD_PROOF: &str = "cross-process rename was blocked";+ const ORIGINAL_PATH: &str = "CUA_DRIVER_ACL_RENAME_ORIGINAL";+ const MOVED_PATH: &str = "CUA_DRIVER_ACL_RENAME_MOVED";+ const TEST_NAME: &str = "perception_client::containment::windows::tests::acl_target_handles_block_cross_process_renames_until_revocation";++ if std::env::var_os(CHILD_MARKER).is_some() {+ let original = PathBuf::from(std::env::var_os(ORIGINAL_PATH).unwrap());+ let moved = PathBuf::from(std::env::var_os(MOVED_PATH).unwrap());+ let error = std::fs::rename(&original, &moved).unwrap_err();+ assert_eq!(+ error.raw_os_error(),+ Some(ERROR_SHARING_VIOLATION),+ "renaming {} to {} failed with an unexpected error: {error}",+ original.display(),+ moved.display()+ );+ println!("{CHILD_PROOF}");+ return;+ }++ let root = tempfile::tempdir().unwrap();+ std::fs::write(root.path().join("model.bin"), b"original").unwrap();+ std::fs::create_dir(root.path().join("models")).unwrap();++ let root = canonical_test_root(&root);+ let container = AppContainerSid::create_unique().unwrap();++ for (original, moved) in [+ (root.join("model.bin"), root.join("moved.bin")),+ (root.join("models"), root.join("moved-models")),+ ] {+ let mut ledger = AclGrantLedger::default();+ ledger+ .merge_grant_tree(&original, container.sid(), GENERIC_READ, false)+ .unwrap();+ let output = std::process::Command::new(std::env::current_exe().unwrap())+ .args(["--exact", TEST_NAME, "--nocapture"])+ .env(CHILD_MARKER, "1")+ .env(ORIGINAL_PATH, &original)+ .env(MOVED_PATH, &moved)+ .output()+ .unwrap();+ let stdout = String::from_utf8_lossy(&output.stdout);+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ output.status.success(),+ "child rename proof failed for {} with {}\nstdout:\n{}\nstderr:\n{}",+ original.display(),+ output.status,+ stdout,+ stderr+ );+ assert!(+ stdout.contains(CHILD_PROOF),+ "child did not run the exact rename test for {}\nstdout:\n{stdout}\nstderr:\n{stderr}",+ original.display()+ );++ ledger.revoke().unwrap();+ drop(ledger);+ std::fs::rename(&original, &moved).unwrap();+ let (_, grants) = matching_grants(&moved, container.sid()).unwrap();+ assert!(+ grants.is_empty(),+ "{} retained a temporary AppContainer grant",+ moved.display()+ );+ }+ }++ #[test]+ fn acl_target_open_conflicts_with_existing_delete_handles() {+ let root = tempfile::tempdir().unwrap();+ std::fs::write(root.path().join("model.bin"), b"model").unwrap();+ std::fs::create_dir(root.path().join("models")).unwrap();++ let root = canonical_test_root(&root);+ for path in [root.join("model.bin"), root.join("models")] {+ let delete_handle = open_delete_shared(&path);+ let error = match AclTarget::open(&path) {+ Ok(_) => panic!(+ "opened {} without delete sharing while a DELETE handle was live",+ path.display()+ ),+ Err(error) => error,+ };+ assert_eq!(+ error.detail.as_deref(),+ Some("os error 32"),+ "opening {} failed with an unexpected error: {error:?}",+ path.display()+ );++ drop(delete_handle);+ AclTarget::open(&path).unwrap_or_else(|error| {+ panic!(+ "failed to open {} after releasing the DELETE handle: {error:?}",+ path.display()+ )+ });+ }+ }++ #[test]+ fn failed_revocation_is_retained_for_retry() {+ let root = tempfile::tempdir().unwrap();+ let target = root.path().join("model.bin");+ std::fs::write(&target, b"model").unwrap();++ let root = canonical_test_root(&root);+ let target = root.join("model.bin");++ let container = AppContainerSid::create_unique().unwrap();+ let mut ledger = AclGrantLedger::default();+ ledger+ .merge_grant_tree(&target, container.sid(), GENERIC_READ, false)+ .unwrap();+ assert_eq!(ledger.entries.len(), 1);++ let handle = ledger.entries[0].target.handle.get();+ assert_ne!(unsafe { CloseHandle(handle) }, FALSE);+ ledger.entries[0].target.handle.0 = std::ptr::null_mut();++ let mut cleanup = PendingCleanup {+ process: 0,+ process_reaped: true,+ grants: Some(ledger),+ container: None,+ journal: None,+ lease: None,+ };+ assert!(cleanup.cleanup_reaped_once().is_err());+ assert_eq!(cleanup.grants.as_ref().unwrap().entries.len(), 1);+ }++ #[tokio::test]+ async fn contended_acl_lease_returns_a_prompt_retryable_busy_error() {+ let root = tempfile::tempdir().unwrap();+ let path = root.path().join("runtime-acl.lock");+ std::fs::write(&path, b"").unwrap();+ let blocker = std::fs::OpenOptions::new()+ .read(true)+ .write(true)+ .open(&path)+ .unwrap();+ blocker.try_lock_exclusive().unwrap();++ let failure =+ match tokio::time::timeout(Duration::from_millis(100), AclLease::acquire(&path))+ .await+ .expect("ACL contention must return promptly")+ {+ Ok(_) => panic!("a contended ACL lease must not be acquired"),+ Err(failure) => failure,+ };+ assert_eq!(failure.code, VisualParseErrorCode::WorkerLaunchFailed);+ assert!(failure.retryable);+ assert!(failure.message.contains("another perception worker"));+ drop(blocker);++ tokio::time::timeout(Duration::from_secs(1), AclLease::acquire(&path))+ .await+ .expect("cancelled waiter released its lease handle")+ .unwrap();+ }++ #[tokio::test]+ async fn worker_lease_acquisition_recovers_the_profile_journal() {+ let root = tempfile::tempdir().unwrap();+ let lease_path = root.path().join("runtime-acl.lock");+ std::fs::write(&lease_path, b"").unwrap();+ let journal_path = acl_profile_journal_path(&lease_path);+ AppContainerJournal::persist(journal_path.clone(), &test_profile_name()).unwrap();++ let _lease = AclLease::acquire(&lease_path).await.unwrap();+ assert!(!journal_path.exists());+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/perception_tools.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/perception_tools.rsnew file mode 100644index 0000000000..59f50d868d--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/perception_tools.rs@@ -0,0 +1,1088 @@+//! Common `parse_visual_regions` tool implementation.++use std::sync::Arc;+use std::time::Instant;++use async_trait::async_trait;+use serde::Deserialize;+use serde_json::{json, Value};++use cua_driver_contract::{+ ParseVisualRegionsInput, ParseVisualRegionsOutput, ToolInput, VisualActionCoordinateSpace,+ VisualCaptureProvenance, VisualCaptureSource, VisualParseError, VisualParseErrorCode,+ VisualParseTiming, VisualParserMetadata, VisualRegion, VisualRegionBounds, VisualRegionKind,+ VisualScreenshotReference, VISUAL_REGIONS_SCHEMA,+};++use crate::capture_registry::{CaptureLookupError, PerceptionCapture};+use crate::capture_runtime::{CaptureBinding, CaptureService, CaptureTarget};+use crate::perception_client::{error, PerceptionCancellation, PerceptionClient};+use crate::protocol::ToolResult;+use crate::tool::{Tool, ToolDef, ToolRegistry};+use crate::tool_args::parse_typed_projection;++pub type CaptureBindingResolver =+ Arc<dyn Fn(&Value) -> Result<CaptureBinding, VisualParseError> + Send + Sync + 'static>;++pub fn register_perception_tool(+ registry: &mut ToolRegistry,+ client: PerceptionClient,+ resolve_binding: CaptureBindingResolver,+) {+ let shutdown_client = client.clone();+ registry.retain_session_end_hook(crate::session::register_scoped_session_end_hook(+ move |_| shutdown_client.shutdown_now(),+ ));+ registry.register(Box::new(ParseVisualRegionsTool::new(+ registry.capture_service(),+ client,+ resolve_binding,+ )));+}++struct ParseVisualRegionsTool {+ def: ToolDef,+ captures: Arc<CaptureService>,+ client: PerceptionClient,+ resolve_binding: CaptureBindingResolver,+}++impl ParseVisualRegionsTool {+ fn new(+ captures: Arc<CaptureService>,+ client: PerceptionClient,+ resolve_binding: CaptureBindingResolver,+ ) -> Self {+ let contract = cua_driver_contract::tool_contract(ParseVisualRegionsInput::TOOL_NAME)+ .expect("parse_visual_regions has a canonical contract");+ Self {+ def: ToolDef::from_contract(&contract),+ captures,+ client,+ resolve_binding,+ }+ }+}++#[async_trait]+impl Tool for ParseVisualRegionsTool {+ fn def(&self) -> &ToolDef {+ &self.def+ }++ async fn protected_resource_scope(+ &self,+ _adapter_id: &str,+ args: &Value,+ ) -> Result<Option<Value>, String> {+ let binding = (self.resolve_binding)(args).map_err(|error| error.message)?;+ let capture_id = args+ .get("capture_id")+ .and_then(Value::as_str)+ .ok_or_else(|| "capture_id is required".to_owned())?;+ let capture_id = self+ .captures+ .parse_capture_id(capture_id)+ .map_err(|error| error.to_string())?;+ let capture = self+ .captures+ .read_for_perception(capture_id, &binding)+ .map_err(|error| error.to_string())?;+ Ok(Some(match capture.target() {+ CaptureTarget::Window { pid, window_id } => {+ json!({"pid": pid, "window_id": window_id, "capture_id": capture.id().to_string()})+ }+ CaptureTarget::PrimaryDesktop => {+ json!({"display": "primary", "capture_id": capture.id().to_string()})+ }+ }))+ }++ async fn invoke(&self, args: Value) -> ToolResult {+ let binding = match (self.resolve_binding)(&args) {+ Ok(binding) => binding,+ Err(error) => return tool_error(error),+ };+ let mut input: ParseVisualRegionsInput = match parse_typed_projection(&self.def.name, &args)+ {+ Ok(input) => input,+ Err(result) => return result,+ };+ if let Err(cause) = input.validate() {+ return tool_error(error(+ VisualParseErrorCode::ArtifactInvalid,+ "parse_visual_regions arguments are invalid",+ false,+ Some(cause.to_string()),+ ));+ }+ let capture_id = match self.captures.parse_capture_id(&input.capture_id) {+ Ok(id) => id,+ Err(cause) => {+ return tool_error(error(+ VisualParseErrorCode::CaptureNotFound,+ "capture_id is unknown",+ false,+ Some(cause.to_string()),+ ))+ }+ };+ input.capture_id = capture_id.to_string();+ let capture = match self.captures.read_for_perception(capture_id, &binding) {+ Ok(capture) => capture,+ Err(cause) => return tool_error(map_capture_error(cause)),+ };+ let started = Instant::now();+ let dimensions = capture.encoded_dimensions();+ let result = self+ .client+ .parse(+ &input.capture_id,+ dimensions.width(),+ dimensions.height(),+ &capture.png_bytes(),+ &PerceptionCancellation::default(),+ )+ .await;+ let worker = match result {+ Ok(result) => result,+ Err(error) => return tool_error(error),+ };+ let output = match build_output(&input, &capture, worker, started.elapsed().as_millis()) {+ Ok(output) => output,+ Err(error) => return tool_error(error),+ };+ let structured = serde_json::to_value(&output).expect("visual output serializes");+ ToolResult::text(format!("Parsed {} visual regions", output.regions.len()))+ .with_structured(structured)+ }+}++#[derive(Deserialize)]+struct WorkerRegion {+ id: String,+ kind: VisualRegionKind,+ bounds: VisualRegionBounds,+ #[serde(default)]+ text: Option<String>,+ #[serde(default)]+ label: Option<String>,+ confidence: f64,+ #[serde(default)]+ interactive: bool,+ #[serde(default)]+ parent_id: Option<String>,+ #[serde(default)]+ group_id: Option<String>,+ #[serde(default)]+ reading_order: Option<u32>,+}++#[derive(Deserialize)]+struct WorkerIdentity {+ extension: WorkerExtensionIdentity,+ backend: String,+ #[serde(default)]+ model: Option<WorkerModelIdentity>,+ #[serde(default)]+ onnx_runtime: Option<WorkerRuntimeIdentity>,+ #[serde(default)]+ fixture_sha256: Option<String>,+}++#[derive(Deserialize)]+#[serde(deny_unknown_fields)]+struct WorkerExtensionIdentity {+ id: String,+ version: String,+}++#[derive(Deserialize)]+#[serde(deny_unknown_fields)]+struct WorkerModelIdentity {+ name: String,+ version: String,+ source_revision: String,+ manifest_sha256: String,+}++#[derive(Deserialize)]+#[serde(deny_unknown_fields)]+struct WorkerRuntimeIdentity {+ version: String,+ library_sha256: String,+ intra_threads: usize,+}++fn build_output(+ input: &ParseVisualRegionsInput,+ capture: &PerceptionCapture,+ worker: Value,+ elapsed_ms: u128,+) -> Result<ParseVisualRegionsOutput, VisualParseError> {+ let provenance = capture_provenance(capture)?;+ build_output_with_provenance(input, provenance, worker, elapsed_ms)+}++/// Normalize one local-image worker result through the same canonical output+/// validation as the capture-bound tool, without registering action authority.+pub fn build_local_output(+ input: &ParseVisualRegionsInput,+ provenance: VisualCaptureProvenance,+ worker: Value,+ elapsed_ms: u128,+) -> Result<ParseVisualRegionsOutput, VisualParseError> {+ input.validate().map_err(invalid_worker_artifact)?;+ build_output_with_provenance(input, provenance, worker, elapsed_ms)+}++fn build_output_with_provenance(+ input: &ParseVisualRegionsInput,+ provenance: VisualCaptureProvenance,+ worker: Value,+ elapsed_ms: u128,+) -> Result<ParseVisualRegionsOutput, VisualParseError> {+ validate_worker_echo(input, &provenance, &worker)?;+ let parser = worker_parser_metadata(&worker)?;+ if let Ok(mut output) = serde_json::from_value::<ParseVisualRegionsOutput>(worker.clone()) {+ // The Driver, rather than the extension, is authoritative for capture provenance.+ output.capture = provenance;+ output.parser = parser;+ apply_options(&mut output.regions, input);+ output.validate().map_err(invalid_worker_artifact)?;+ return Ok(output);+ }++ let regions_value = worker.get("regions").cloned().ok_or_else(|| {+ error(+ VisualParseErrorCode::ArtifactInvalid,+ "perception worker result omitted regions",+ false,+ None,+ )+ })?;+ let worker_regions: Vec<WorkerRegion> =+ serde_json::from_value(regions_value).map_err(|cause| {+ error(+ VisualParseErrorCode::ArtifactInvalid,+ "perception worker returned invalid regions",+ false,+ Some(cause.to_string()),+ )+ })?;+ let mut regions = worker_regions+ .into_iter()+ .map(|region| VisualRegion {+ id: region.id,+ kind: region.kind,+ bounds: region.bounds,+ text: region.text,+ label: region.label,+ confidence: region.confidence,+ interactive: region.interactive,+ parent_id: region.parent_id,+ group_id: region.group_id,+ reading_order: region.reading_order,+ })+ .collect::<Vec<_>>();+ apply_options(&mut regions, input);+ let output = ParseVisualRegionsOutput {+ schema: VISUAL_REGIONS_SCHEMA.into(),+ capture: provenance,+ parser,+ regions,+ warnings: Vec::new(),+ timing: VisualParseTiming {+ duration_ms: u64::try_from(elapsed_ms).unwrap_or(u64::MAX),+ preprocess_ms: None,+ inference_ms: None,+ },+ request_id: None,+ };+ output.validate().map_err(invalid_worker_artifact)?;+ Ok(output)+}++fn worker_parser_metadata(worker: &Value) -> Result<VisualParserMetadata, VisualParseError> {+ let identity: WorkerIdentity = serde_json::from_value(+ worker+ .get("identity")+ .cloned()+ .ok_or_else(|| invalid_worker_artifact("worker result omitted parser identity"))?,+ )+ .map_err(|cause| invalid_worker_artifact(format!("worker identity is malformed: {cause}")))?;+ let runtime = worker+ .get("runtime")+ .and_then(Value::as_str)+ .filter(|value| !value.trim().is_empty())+ .ok_or_else(|| invalid_worker_artifact("worker result omitted runtime identity"))?;+ if identity.extension.id != "cua-perception"+ || identity.extension.version.trim().is_empty()+ || identity.backend.trim().is_empty()+ {+ return Err(invalid_worker_artifact(+ "worker extension or backend identity is invalid",+ ));+ }++ let mut parser = VisualParserMetadata {+ extension_id: identity.extension.id,+ extension_version: identity.extension.version,+ model_id: String::new(),+ model_version: String::new(),+ runtime: Some(runtime.to_owned()),+ backend: Some(identity.backend.clone()),+ model_source_revision: None,+ model_manifest_sha256: None,+ onnx_runtime_version: None,+ onnx_runtime_library_sha256: None,+ fixture_sha256: None,+ };+ match identity.backend.as_str() {+ "onnx_runtime_cpu" => {+ if runtime != "onnx_runtime_cpu" || identity.fixture_sha256.is_some() {+ return Err(invalid_worker_artifact(+ "worker runtime and production backend identity disagree",+ ));+ }+ let model = identity.model.ok_or_else(|| {+ invalid_worker_artifact("production worker identity omitted model provenance")+ })?;+ let onnx_runtime = identity.onnx_runtime.ok_or_else(|| {+ invalid_worker_artifact(+ "production worker identity omitted ONNX Runtime provenance",+ )+ })?;+ if model.name.trim().is_empty()+ || model.version.trim().is_empty()+ || model.source_revision.trim().is_empty()+ || !valid_sha256(&model.manifest_sha256)+ || onnx_runtime.version.trim().is_empty()+ || !valid_sha256(&onnx_runtime.library_sha256)+ || !(1..=64).contains(&onnx_runtime.intra_threads)+ {+ return Err(invalid_worker_artifact(+ "production worker model or runtime identity is invalid",+ ));+ }+ parser.model_id = model.name;+ parser.model_version = model.version;+ parser.model_source_revision = Some(model.source_revision);+ parser.model_manifest_sha256 = Some(model.manifest_sha256);+ parser.onnx_runtime_version = Some(onnx_runtime.version);+ parser.onnx_runtime_library_sha256 = Some(onnx_runtime.library_sha256);+ }+ "deterministic_fixture" => {+ if runtime != "fixture_only"+ || identity.model.is_some()+ || identity.onnx_runtime.is_some()+ {+ return Err(invalid_worker_artifact(+ "worker runtime and fixture backend identity disagree",+ ));+ }+ let fixture_sha256 = identity+ .fixture_sha256+ .filter(|hash| valid_sha256(hash))+ .ok_or_else(|| {+ invalid_worker_artifact("fixture worker identity omitted a valid fixture hash")+ })?;+ parser.model_id = "deterministic_fixture".into();+ parser.model_version = "1".into();+ parser.fixture_sha256 = Some(fixture_sha256);+ }+ _ => {+ return Err(invalid_worker_artifact(+ "worker reported an unsupported backend identity",+ ))+ }+ }+ Ok(parser)+}++fn valid_sha256(value: &str) -> bool {+ value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit())+}++fn capture_provenance(+ capture: &PerceptionCapture,+) -> Result<VisualCaptureProvenance, VisualParseError> {+ let dimensions = capture.encoded_dimensions();+ let digest = capture.digest().hex();+ let source = match capture.target() {+ CaptureTarget::Window { pid, window_id } => VisualCaptureSource::Window {+ pid: *pid,+ window_id: *window_id,+ },+ CaptureTarget::PrimaryDesktop => VisualCaptureSource::PrimaryDesktop {+ display_id: "primary".into(),+ },+ };+ let [m11, m12, m21, m22, tx, ty] = capture.screenshot_to_action().coefficients();+ let action_coordinate_space = if [m11, m12, m21, m22, tx, ty] == [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]+ {+ VisualActionCoordinateSpace::ScreenshotPixels+ } else {+ VisualActionCoordinateSpace::Affine {+ m11,+ m12,+ m21,+ m22,+ tx,+ ty,+ }+ };+ Ok(VisualCaptureProvenance {+ capture_id: capture.id().to_string(),+ source,+ screenshot: VisualScreenshotReference {+ reference: format!("png-sha256:{digest}"),+ width: dimensions.width(),+ height: dimensions.height(),+ mime_type: "image/png".into(),+ sha256: Some(digest),+ },+ action_coordinate_space,+ captured_at: None,+ })+}++fn apply_options(regions: &mut Vec<VisualRegion>, input: &ParseVisualRegionsInput) {+ regions.retain(|region| {+ input+ .options+ .kinds+ .as_ref()+ .is_none_or(|kinds| kinds.contains(®ion.kind))+ && input+ .options+ .min_confidence+ .is_none_or(|minimum| region.confidence >= minimum)+ });+ if let Some(maximum) = input.options.max_regions {+ regions.truncate(maximum as usize);+ }+ let retained = regions+ .iter()+ .map(|region| region.id.clone())+ .collect::<std::collections::HashSet<_>>();+ for region in regions.iter_mut() {+ if region+ .parent_id+ .as_deref()+ .is_some_and(|id| !retained.contains(id))+ {+ region.parent_id = None;+ }+ if region+ .group_id+ .as_deref()+ .is_some_and(|id| !retained.contains(id))+ {+ region.group_id = None;+ }+ }+}++fn validate_worker_echo(+ input: &ParseVisualRegionsInput,+ provenance: &VisualCaptureProvenance,+ worker: &Value,+) -> Result<(), VisualParseError> {+ if let Some(capture_id) = worker.get("capture_id").and_then(Value::as_str) {+ if capture_id != input.capture_id {+ return Err(invalid_worker_artifact(+ "worker capture_id does not match the requested capture",+ ));+ }+ }+ let Some(image) = worker.get("image") else {+ return Ok(());+ };+ let screenshot = &provenance.screenshot;+ let digest_matches = image+ .get("sha256")+ .and_then(Value::as_str)+ .is_some_and(|digest| screenshot.sha256.as_deref() == Some(digest));+ let dimensions_match = image.get("width").and_then(Value::as_u64)+ == Some(u64::from(screenshot.width))+ && image.get("height").and_then(Value::as_u64) == Some(u64::from(screenshot.height));+ if !digest_matches || !dimensions_match {+ return Err(invalid_worker_artifact(+ "worker image identity does not match the retained capture",+ ));+ }+ if worker+ .get("coordinate_space")+ .and_then(Value::as_str)+ .is_some_and(|space| space != "image_pixels")+ {+ return Err(invalid_worker_artifact(+ "worker regions are not expressed in source image pixels",+ ));+ }+ Ok(())+}++fn map_capture_error(cause: CaptureLookupError) -> VisualParseError {+ let code = match cause {+ CaptureLookupError::Unknown | CaptureLookupError::TargetMismatch => {+ VisualParseErrorCode::CaptureNotFound+ }+ CaptureLookupError::Expired => VisualParseErrorCode::CaptureExpired,+ CaptureLookupError::GenerationMismatch => VisualParseErrorCode::CaptureGenerationMismatch,+ };+ error(code, cause.to_string(), false, None)+}++fn invalid_worker_artifact(cause: impl ToString) -> VisualParseError {+ error(+ VisualParseErrorCode::ArtifactInvalid,+ "perception worker output failed contract validation",+ false,+ Some(cause.to_string()),+ )+}++fn tool_error(error: VisualParseError) -> ToolResult {+ let message = error.message.clone();+ ToolResult::error(message)+ .with_structured(serde_json::to_value(error).expect("visual parse error serializes"))+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::capture_registry::{CaptureRegistryConfig, MonotonicClock};+ use crate::capture_runtime::{+ CapturePublication, EncodedScreenshotDimensions, NativeActionDimensions,+ ScreenshotToActionTransform,+ };+ use crate::image_utils::encode_rgba_to_png;+ use sha2::Digest as _;+ use std::sync::atomic::{AtomicU64, Ordering};+ use std::time::Duration;++ #[derive(Default)]+ struct ManualClock(AtomicU64);++ impl MonotonicClock for ManualClock {+ fn now(&self) -> Duration {+ Duration::from_millis(self.0.load(Ordering::SeqCst))+ }+ }++ fn capture(service: &Arc<CaptureService>) -> (String, CaptureBinding) {+ let png = encode_rgba_to_png(&[7, 8, 9, 255], 1, 1).unwrap();+ let id = service+ .publish(CapturePublication {+ png_bytes: png,+ target: CaptureTarget::PrimaryDesktop,+ encoded_dimensions: EncodedScreenshotDimensions::new(1, 1).unwrap(),+ native_action_dimensions: NativeActionDimensions::new(1, 1).unwrap(),+ screenshot_to_action: ScreenshotToActionTransform::identity(),+ session_id: Arc::from("session-a"),+ session_generation: 1,+ })+ .unwrap();+ (id.to_string(), service.binding("session-a", 1).unwrap())+ }++ #[test]+ fn local_output_uses_canonical_validation_without_capture_registration() {+ let digest = "11".repeat(32);+ let input = ParseVisualRegionsInput {+ capture_id: "local_png_fixture".into(),+ options: Default::default(),+ };+ let provenance = VisualCaptureProvenance {+ capture_id: input.capture_id.clone(),+ source: VisualCaptureSource::Window {+ pid: 10,+ window_id: 20,+ },+ screenshot: VisualScreenshotReference {+ reference: format!("local-png-sha256:{digest}"),+ width: 2,+ height: 1,+ mime_type: "image/png".into(),+ sha256: Some(digest.clone()),+ },+ action_coordinate_space: VisualActionCoordinateSpace::ScreenshotPixels,+ captured_at: None,+ };+ let output = build_local_output(+ &input,+ provenance,+ json!({+ "capture_id": input.capture_id,+ "image": {"width": 2, "height": 1, "sha256": digest},+ "coordinate_space": "image_pixels",+ "runtime": "fixture_only",+ "identity": {+ "extension": {"id": "cua-perception", "version": "0.1.0"},+ "backend": "deterministic_fixture",+ "fixture_sha256": "22".repeat(32)+ },+ "regions": [{+ "id": "region-1",+ "kind": "icon",+ "bounds": {"x": 0, "y": 0, "width": 1, "height": 1},+ "label": "fixture",+ "confidence": 0.9+ }]+ }),+ 4,+ )+ .unwrap();+ assert_eq!(output.schema, VISUAL_REGIONS_SCHEMA);+ assert_eq!(output.capture.capture_id, "local_png_fixture");+ assert_eq!(output.regions.len(), 1);+ assert!(!output.regions[0].interactive);+ }++ #[tokio::test]+ async fn absent_extension_returns_stable_not_installed_error() {+ let service = Arc::new(CaptureService::default());+ let (capture_id, binding) = capture(&service);+ let tool = ParseVisualRegionsTool::new(+ service,+ PerceptionClient::unavailable(),+ Arc::new(move |_| Ok(binding.clone())),+ );+ let result = tool.invoke(json!({"capture_id": capture_id})).await;+ assert_eq!(result.is_error, Some(true));+ assert_eq!(result.structured_content.unwrap()["code"], "not_installed");+ }++ #[tokio::test]+ async fn session_metadata_selects_capture_binding_without_entering_typed_input() {+ let service = Arc::new(CaptureService::default());+ let (capture_id, _) = capture(&service);+ let resolve_service = service.clone();+ let tool = ParseVisualRegionsTool::new(+ service,+ PerceptionClient::unavailable(),+ Arc::new(move |args| {+ resolve_service.binding_from_args(args).map_err(|error| {+ crate::perception_client::error(+ VisualParseErrorCode::CaptureGenerationMismatch,+ "capture session binding is unavailable",+ false,+ Some(error.to_string()),+ )+ })+ }),+ );++ let matched = tool+ .invoke(json!({+ "session": "session-a",+ "_session_id": "session-a",+ "_transport_session_id": "transport-a",+ "capture_id": capture_id+ }))+ .await;+ assert_eq!(matched.structured_content.unwrap()["code"], "not_installed");++ let mismatched = tool+ .invoke(json!({+ "session": "session-b",+ "_session_id": "session-b",+ "_transport_session_id": "transport-b",+ "capture_id": capture_id+ }))+ .await;+ assert_eq!(+ mismatched.structured_content.unwrap()["code"],+ "capture_generation_mismatch"+ );+ }++ #[tokio::test]+ async fn invalid_retired_and_cross_session_captures_fail_before_worker_launch() {+ let service = Arc::new(CaptureService::default());+ let (capture_id, binding) = capture(&service);+ let missing_worker =+ PerceptionClient::new(crate::perception_client::PerceptionWorkerConfig::new(+ "/definitely/not/a/perception-worker",+ ))+ .unwrap();++ let other_binding = service.current_binding("session-b").unwrap();+ let cross_session = ParseVisualRegionsTool::new(+ service.clone(),+ missing_worker.clone(),+ Arc::new(move |_| Ok(other_binding.clone())),+ )+ .invoke(json!({"capture_id": capture_id.clone()}))+ .await;+ assert_eq!(+ cross_session.structured_content.unwrap()["code"],+ "capture_generation_mismatch"+ );++ let malformed = ParseVisualRegionsTool::new(+ service.clone(),+ missing_worker.clone(),+ Arc::new({+ let binding = binding.clone();+ move |_| Ok(binding.clone())+ }),+ )+ .invoke(json!({"capture_id": "not-a-capture"}))+ .await;+ assert_eq!(+ malformed.structured_content.unwrap()["code"],+ "capture_not_found"+ );++ let id = service.parse_capture_id(&capture_id).unwrap();+ service.retire_capture(id, &binding).unwrap();+ let retired = ParseVisualRegionsTool::new(+ service,+ missing_worker,+ Arc::new(move |_| Ok(binding.clone())),+ )+ .invoke(json!({"capture_id": capture_id}))+ .await;+ assert_eq!(+ retired.structured_content.unwrap()["code"],+ "capture_not_found"+ );+ }++ #[tokio::test]+ async fn expired_capture_fails_at_the_tool_boundary_before_worker_launch() {+ let clock = Arc::new(ManualClock::default());+ let mut config = CaptureRegistryConfig::default();+ config.ttl = Duration::from_millis(10);+ let service = Arc::new(CaptureService::with_clock(config, clock.clone()).unwrap());+ let (capture_id, binding) = capture(&service);+ clock.0.store(10, Ordering::SeqCst);+ let tool = ParseVisualRegionsTool::new(+ service,+ PerceptionClient::new(crate::perception_client::PerceptionWorkerConfig::new(+ "/definitely/not/a/perception-worker",+ ))+ .unwrap(),+ Arc::new(move |_| Ok(binding.clone())),+ );+ let result = tool.invoke(json!({"capture_id": capture_id})).await;+ assert_eq!(+ result.structured_content.unwrap()["code"],+ "capture_expired"+ );+ }++ #[cfg(unix)]+ #[tokio::test]+ async fn tool_maps_worker_icon_output_into_the_driver_contract() {+ use std::os::unix::fs::PermissionsExt;++ let python = crate::perception_client::fixture_python_config().unwrap();+ let interpreter = python.interpreter;++ let service = Arc::new(CaptureService::default());+ let (capture_id, binding) = capture(&service);+ let expected = service+ .read_for_perception(service.parse_capture_id(&capture_id).unwrap(), &binding)+ .unwrap()+ .digest()+ .hex();+ let extension_version = "0.1.0";+ let directory = tempfile::tempdir().unwrap();+ let worker = directory.path().join("worker.py");+ let script = format!(+ r#"#!{interpreter}+import base64, hashlib, json, struct, sys+def read():+ p=sys.stdin.buffer.read(4); n=struct.unpack('>I',p)[0]; return json.loads(sys.stdin.buffer.read(n))+def write(v):+ p=json.dumps(v,separators=(',',':')).encode(); sys.stdout.buffer.write(struct.pack('>I',len(p))+p); sys.stdout.buffer.flush()+h=read()+health={{'protocol':'cua-perception/1','request_id':h['request_id'],'status':'ok','result':{{+ 'ready':True,+ 'protocol':'cua-perception/1',+ 'identity':{{'extension':{{'id':'cua-perception','version':'{extension_version}'}}}}+}}}}+write(health)+r=read(); raw=base64.b64decode(r['params']['image']['data_base64'])+if hashlib.sha256(raw).hexdigest() != '{expected}':+ write({{'protocol':'cua-perception/1','request_id':r['request_id'],'status':'error','error':{{'code':'invalid_image','message':'wrong capture bytes'}}}})+else:+ write({{'protocol':'cua-perception/1','request_id':r['request_id'],'status':'ok','result':{{'runtime':'fixture_only','identity':{{'extension':{{'id':'cua-perception','version':'{extension_version}'}},'backend':'deterministic_fixture','fixture_sha256':'{expected}'}},'regions':[{{'id':'one','kind':'icon','bounds':{{'x':0,'y':0,'width':1,'height':1}},'label':'icon-class-4','confidence':0.9}}]}}}})+"#,+ interpreter = interpreter.display(),+ );+ std::fs::write(&worker, script).unwrap();+ let mut permissions = std::fs::metadata(&worker).unwrap().permissions();+ permissions.set_mode(0o700);+ std::fs::set_permissions(&worker, permissions).unwrap();+ let containment = crate::perception_client::containment::ContainmentLimits {+ additional_readable_paths: python.readable_roots,+ additional_executable_paths: python.executable_paths,+ ..Default::default()+ };+ let client = PerceptionClient::new(+ crate::perception_client::PerceptionWorkerConfig::installed_with_identity(+ worker,+ "cua-perception",+ extension_version,+ )+ .with_test_containment(containment),+ )+ .unwrap();+ let action_binding = binding.clone();+ let tool = ParseVisualRegionsTool::new(+ service.clone(),+ client,+ Arc::new(move |_| Ok(binding.clone())),+ );+ let result = tool.invoke(json!({"capture_id": capture_id.clone()})).await;+ assert_ne!(+ result.is_error,+ Some(true),+ "worker mapping failed: {:?}",+ result.structured_content+ );+ let output: ParseVisualRegionsOutput =+ serde_json::from_value(result.structured_content.unwrap()).unwrap();+ assert_eq!(output.regions.len(), 1);+ assert_eq!(output.capture.capture_id, capture_id);+ assert_eq!(output.regions[0].label.as_deref(), Some("icon-class-4"));+ assert_eq!(output.parser.extension_id, "cua-perception");+ assert_eq!(output.parser.extension_version, extension_version);+ assert_eq!(+ output.parser.backend.as_deref(),+ Some("deterministic_fixture")+ );+ assert_eq!(+ output.parser.fixture_sha256.as_deref(),+ Some(expected.as_str())+ );+ assert_eq!(+ output.capture.screenshot.sha256.as_deref(),+ Some(expected.as_str())+ );+ assert_eq!(+ output.capture.source,+ VisualCaptureSource::PrimaryDesktop {+ display_id: "primary".into()+ }+ );+ let admitted = service+ .admit_action(crate::capture_runtime::CaptureActionRequest {+ capture_id: service.parse_capture_id(&capture_id).unwrap(),+ binding: action_binding.clone(),+ target: CaptureTarget::PrimaryDesktop,+ current_native_action_dimensions: NativeActionDimensions::new(1, 1).unwrap(),+ screenshot_x: 0.5,+ screenshot_y: 0.5,+ })+ .unwrap();+ assert_eq!((admitted.action_x, admitted.action_y), (0.5, 0.5));+ assert_eq!(admitted.digest.hex(), expected);+ assert_eq!(+ service+ .admit_action(crate::capture_runtime::CaptureActionRequest {+ capture_id: service.parse_capture_id(&capture_id).unwrap(),+ binding: action_binding,+ target: CaptureTarget::PrimaryDesktop,+ current_native_action_dimensions: NativeActionDimensions::new(1, 1).unwrap(),+ screenshot_x: 0.5,+ screenshot_y: 0.5,+ })+ .unwrap_err(),+ crate::capture_runtime::CaptureActionError::Lookup(CaptureLookupError::Unknown)+ );+ output.validate().unwrap();+ }++ fn production_worker_identity() -> Value {+ json!({+ "extension": {+ "id": "cua-perception",+ "version": "0.1.0"+ },+ "backend": "onnx_runtime_cpu",+ "model": {+ "name": "omniparser-v2-ppocrv5-en",+ "version": "2026-09-17",+ "source_revision": "6600256cb0f1b07651e3bc86166196307bad7e2d",+ "manifest_sha256": "a".repeat(64)+ },+ "onnx_runtime": {+ "version": "1.26.0",+ "library_sha256": "b".repeat(64),+ "intra_threads": 2+ }+ })+ }++ #[test]+ fn production_worker_icon_and_verified_identity_reach_the_driver_contract() {+ let service = Arc::new(CaptureService::default());+ let (capture_id, binding) = capture(&service);+ let capture = service+ .read_for_perception(service.parse_capture_id(&capture_id).unwrap(), &binding)+ .unwrap();+ let input = ParseVisualRegionsInput {+ capture_id: capture_id+ .to_ascii_uppercase()+ .replacen("CAPTURE_", "capture_", 1),+ options: Default::default(),+ };+ let output = build_output(+ &input,+ &capture,+ json!({+ "runtime": "onnx_runtime_cpu",+ "identity": production_worker_identity(),+ "regions": [{+ "id": "icon-1",+ "kind": "icon",+ "bounds": {"x": 0, "y": 0, "width": 1, "height": 1},+ "label": "icon-class-4",+ "confidence": 0.9+ }]+ }),+ 7,+ )+ .unwrap();++ output.validate().unwrap();+ assert_eq!(output.capture.capture_id, capture_id);+ assert_eq!(output.regions[0].label.as_deref(), Some("icon-class-4"));+ assert_eq!(output.parser.extension_id, "cua-perception");+ assert_eq!(output.parser.extension_version, "0.1.0");+ assert_eq!(output.parser.model_id, "omniparser-v2-ppocrv5-en");+ assert_eq!(output.parser.model_version, "2026-09-17");+ assert_eq!(+ output.parser.model_source_revision.as_deref(),+ Some("6600256cb0f1b07651e3bc86166196307bad7e2d")+ );+ assert_eq!(output.parser.model_manifest_sha256, Some("a".repeat(64)));+ assert_eq!(+ output.parser.onnx_runtime_version.as_deref(),+ Some("1.26.0")+ );+ assert_eq!(+ output.parser.onnx_runtime_library_sha256,+ Some("b".repeat(64))+ );+ }++ #[test]+ fn malformed_or_missing_production_worker_identity_is_rejected() {+ let service = Arc::new(CaptureService::default());+ let (capture_id, binding) = capture(&service);+ let capture = service+ .read_for_perception(service.parse_capture_id(&capture_id).unwrap(), &binding)+ .unwrap();+ let input = ParseVisualRegionsInput {+ capture_id,+ options: Default::default(),+ };+ let regions = json!([{+ "id": "icon-1",+ "kind": "icon",+ "bounds": {"x": 0, "y": 0, "width": 1, "height": 1},+ "label": "icon-class-4",+ "confidence": 0.9+ }]);+ let missing = build_output(+ &input,+ &capture,+ json!({"runtime": "onnx_runtime_cpu", "regions": regions}),+ 0,+ )+ .unwrap_err();+ assert_eq!(missing.code, VisualParseErrorCode::ArtifactInvalid);++ let mut identity = production_worker_identity();+ identity["model"]["manifest_sha256"] = json!("not-a-sha256");+ let malformed = build_output(+ &input,+ &capture,+ json!({+ "runtime": "onnx_runtime_cpu",+ "identity": identity,+ "regions": regions+ }),+ 0,+ )+ .unwrap_err();+ assert_eq!(malformed.code, VisualParseErrorCode::ArtifactInvalid);+ }++ #[test]+ fn parsed_window_provenance_keeps_native_ids_and_full_affine_mapping() {+ let service = Arc::new(CaptureService::default());+ let png = encode_rgba_to_png(&vec![17; 4 * 3 * 4], 4, 3).unwrap();+ let transform = ScreenshotToActionTransform::new(1.5, 0.25, -0.5, 2.0, 7.25, -3.5).unwrap();+ let target = CaptureTarget::Window {+ pid: 4242,+ window_id: 0xfeed,+ };+ let id = service+ .publish(CapturePublication {+ png_bytes: png.clone(),+ target: target.clone(),+ encoded_dimensions: EncodedScreenshotDimensions::new(4, 3).unwrap(),+ native_action_dimensions: NativeActionDimensions::new(9, 7).unwrap(),+ screenshot_to_action: transform,+ session_id: Arc::from("window-parse"),+ session_generation: 1,+ })+ .unwrap();+ let binding = service.binding("window-parse", 1).unwrap();+ let capture = service.read_for_perception(id, &binding).unwrap();+ let input = ParseVisualRegionsInput {+ capture_id: id.to_string(),+ options: Default::default(),+ };+ let output = build_output(+ &input,+ &capture,+ json!({+ "runtime": "fixture_only",+ "identity": {+ "extension": {"id": "cua-perception", "version": "0.1.0"},+ "backend": "deterministic_fixture",+ "fixture_sha256": "a".repeat(64)+ },+ "regions": [{+ "id": "target",+ "kind": "icon",+ "bounds": {"x": 1, "y": 1, "width": 1, "height": 1},+ "label": "target",+ "confidence": 1.0+ }]+ }),+ 0,+ )+ .unwrap();+ assert_eq!(+ output.capture.source,+ VisualCaptureSource::Window {+ pid: 4242,+ window_id: 0xfeed+ }+ );+ assert_eq!(output.capture.capture_id, id.to_string());+ assert_eq!(+ output.capture.screenshot.sha256,+ Some(+ sha2::Sha256::digest(&png)+ .iter()+ .map(|b| format!("{b:02x}"))+ .collect()+ )+ );+ assert_eq!(+ output.capture.action_coordinate_space.map_point(1.5, 1.5),+ transform.apply(1.5, 1.5)+ );+ }+}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.rsindex d93bf6d202..79c7ded69f 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@@ -348,6 +348,7 @@ pub fn default_capabilities_for(tool_name: &str) -> Vec<String> {"screen.capture","screen.capture.window",],+ "parse_visual_regions" => &["screen.perception.visual_regions"],// ── apps / windows ───────────────────────────────────────────"launch_app" => &["app.launch"],@@ -384,6 +385,7 @@ pub fn default_capabilities_for(tool_name: &str) -> Vec<String> {"get_recording_state" => &["recording.state"],"replay_trajectory" => &["recording.replay"],"install_ffmpeg" => &["recording.install_dependency"],+ "install_extension" => &["extension.install"],// ── cross-platform page ──────────────────────────────────────"page" => &["page.action"],@@ -634,6 +636,7 @@ pub struct ToolRegistry {cursor_outcome_readers: Vec<crate::session::CursorOutcomeReaderRegistration>,_recording_state_readers: Vec<crate::session::RecordingStateReaderRegistration>,runtime_cleanups: Vec<RuntimeCleanup>,+ capture_service: Arc<crate::capture_runtime::CaptureService>,/// Runtime-owned protected-consent broker shared by every resource/// adapter. Keeping it at the canonical dispatch boundary prevents/// browser, desktop, and file adapters from growing independent provider@@ -653,6 +656,7 @@ impl ToolRegistry {pub fn new_with_protected_consent_provider(provider: Option<Arc<dyn crate::consent::ProtectedConsentProvider>>,) -> Self {+ let capture_service = Arc::new(crate::capture_runtime::CaptureService::default());let approval_broker = Arc::new(crate::consent::ApprovalBroker::new(provider));let protected_resource_grants = Arc::new(crate::consent::ProtectedResourceGrants::new(approval_broker.clone(),@@ -661,11 +665,15 @@ impl ToolRegistry {Arc::new(crate::consent::ProtectedResourceOwnershipStore::default());let weak_grants = Arc::downgrade(&protected_resource_grants);let weak_ownership = Arc::downgrade(&protected_resource_ownership);+ let weak_captures = Arc::downgrade(&capture_service);let session_end_hook =crate::session::register_scoped_session_end_hook(move |session_id| {if let Some(ownership) = weak_ownership.upgrade() {ownership.remove_session(session_id);}+ if let Some(captures) = weak_captures.upgrade() {+ captures.retire_session_id(session_id);+ }let Some(grants) = weak_grants.upgrade() else {return;};@@ -701,6 +709,7 @@ impl ToolRegistry {cursor_outcome_readers: Vec::new(),_recording_state_readers: vec![recording_state_reader],runtime_cleanups: Vec::new(),+ capture_service,approval_broker,protected_resource_grants,protected_resource_ownership,@@ -716,6 +725,11 @@ impl ToolRegistry {self.approval_broker.clone()}+ /// Return the immutable-capture service owned by this runtime registry.+ pub fn capture_service(&self) -> Arc<crate::capture_runtime::CaptureService> {+ self.capture_service.clone()+ }+pub fn protected_resource_grants(&self) -> Arc<crate::consent::ProtectedResourceGrants> {self.protected_resource_grants.clone()}@@ -861,6 +875,29 @@ impl ToolRegistry {self.register(Box::new(EndSessionTool));}+ pub fn register_perception_tool(&mut self, client: crate::perception_client::PerceptionClient) {+ let captures = self.capture_service();+ let resolve_binding = Arc::new(move |args: &Value| {+ captures.binding_from_args(args).map_err(|error| {+ crate::perception_client::error(+ cua_driver_contract::VisualParseErrorCode::CaptureGenerationMismatch,+ "capture session binding is unavailable",+ false,+ Some(error.to_string()),+ )+ })+ });+ self.register_perception_tool_with_binding_resolver(client, resolve_binding);+ }++ pub fn register_perception_tool_with_binding_resolver(+ &mut self,+ client: crate::perception_client::PerceptionClient,+ resolve_binding: crate::perception_tools::CaptureBindingResolver,+ ) {+ crate::perception_tools::register_perception_tool(self, client, resolve_binding);+ }+/// Wire up the replay tool's weak self-reference./// Call this once, immediately after `Arc::new(registry)`.pub fn init_self_weak(self: &Arc<Self>) {@@ -1075,6 +1112,9 @@ impl ToolRegistry {{return result;}+ if let Err(result) = crate::action_target::enforce_delivery_target(resolved_name, &args) {+ return result;+ }// This registry is the canonical native dispatch boundary shared by// the same-process SDK and every transport adapter. Authorization must@@ -2137,6 +2177,15 @@ impl ToolRegistry {}),"Allow Cua to install ffmpeg using the detected system package manager".to_owned(),),+ "install_extension" if args.get("confirm").and_then(Value::as_bool) == Some(true) => (+ serde_json::json!({+ "kind": "extension_install",+ "extension": "perception",+ "direction": "local_catalog_to_driver",+ }),+ "Allow Cua to install the reviewed perception extension into the Driver home"+ .to_owned(),+ ),_ => {return Err(protected_scope_refusal("the file-transfer operation has no reviewed exact scope",@@ -3776,6 +3825,68 @@ resources:assert!(received.get("dispatch").is_none());}+ #[tokio::test]+ async fn desktop_background_click_refuses_before_platform_invocation() {+ let hits = Arc::new(AtomicUsize::new(0));+ let last_args = Arc::new(Mutex::new(None));+ let mut registry = super::ToolRegistry::new();+ registry.register(Box::new(ArgumentProbe {+ hits: hits.clone(),+ last_args,+ def: super::ToolDef {+ name: "click".into(),+ description: "test input".into(),+ input_schema: serde_json::json!({+ "type": "object",+ "properties": {+ "delivery_mode": crate::tool_schema::delivery_mode_schema()+ }+ }),+ read_only: false,+ destructive: false,+ idempotent: false,+ open_world: false,+ },+ }));++ for args in [+ serde_json::json!({+ "target": {"kind": "desktop", "display_id": "primary"},+ "delivery_mode": "background",+ "x": 10,+ "y": 20+ }),+ serde_json::json!({+ "scope": "desktop",+ "dispatch": "background",+ "x": 10,+ "y": 20+ }),+ ] {+ let result = registry+ .invoke_with_context("click", args, standard_context())+ .await;+ assert_eq!(result.is_error, Some(true));+ assert_eq!(+ result.structured_content,+ Some(serde_json::json!({+ "code": "background_unavailable",+ "effect": "refused",+ "suggestion": "Retry this action with delivery_mode:\"foreground\".",+ "escalation": {+ "recommended": "foreground",+ "reason": cua_driver_contract::ClickInput::DESKTOP_BACKGROUND_MESSAGE,+ },+ }))+ );+ assert_eq!(+ hits.load(Ordering::SeqCst),+ 0,+ "refusal must occur before the platform tool is invoked"+ );+ }+ }+#[tokio::test]async fn standard_file_transfer_is_promptless_and_still_canonicalizes_paths() {let files = tempfile::tempdir().unwrap();@@ -5097,6 +5208,7 @@ mod capability_tests {"get_recording_state","replay_trajectory","install_ffmpeg",+ "install_extension",// misc"page","check_for_update",@@ -5113,6 +5225,7 @@ mod capability_tests {"browser_pointer","history_status","history_query",+ "parse_visual_regions",];/// All capability tokens in the canonical vocabulary. Any token@@ -5139,8 +5252,10 @@ mod capability_tests {"screen.capture","screen.capture.window","screen.capture.region",+ "screen.capture.registry.read","screen.dimensions","screen.cursor.position",+ "screen.perception.visual_regions",// accessibility"accessibility.tree","accessibility.tree.structured",@@ -5184,6 +5299,8 @@ mod capability_tests {"recording.state","recording.replay","recording.install_dependency",+ "extension.install",+ "visual.regions.parse",// page"page.action",// browser-tool v1diff --git a/libs/cua-driver/rust/crates/cua-driver-core/tests/contract_parity.rs b/libs/cua-driver/rust/crates/cua-driver-core/tests/contract_parity.rsindex 3d5c38ace5..4e1c06ffca 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/tests/contract_parity.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/tests/contract_parity.rs@@ -2,12 +2,14 @@// Copyright (c) 2026 Cua AI, Inc.use cua_driver_contract::{manifest, SchemaMode, CAPABILITY_VERSION, TOOLS_LIST_SCHEMA_VERSION};+use cua_driver_core::perception_client::PerceptionClient;use cua_driver_core::tool::{default_capabilities_for, ToolRegistry};#[test]-fn canonical_session_contract_matches_live_registry() {+fn canonical_core_contracts_match_live_registry() {let mut registry = ToolRegistry::new();registry.register_session_tools();+ registry.register_perception_tool(PerceptionClient::unavailable());let live = registry.tools_list();assert_eq!(live["schema_version"], TOOLS_LIST_SCHEMA_VERSION);@@ -18,10 +20,11 @@ fn canonical_session_contract_matches_live_registry() {.into_iter().filter(|contract| contract.schema_mode == SchemaMode::CanonicalRuntime).filter(|contract| {- contract- .capabilities- .iter()- .any(|capability| capability.starts_with("session."))+ contract.name == "parse_visual_regions"+ || contract+ .capabilities+ .iter()+ .any(|capability| capability.starts_with("session."))}){let entry = live["tools"]diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rsindex 80be06e1b1..0b531e00b0 100644--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rs+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/lib.rs@@ -11,10 +11,10 @@ use cua_driver_contract::{GetDesktopStateInput, GetScreenSizeInput, GetSessionInput, GetSessionStateInput,GetWindowStateInput, HotkeyInput, InvokeMenuInput, ListAppsInput, ListAppsOutput,ListSessionsInput, ListSessionsOutput, ListWindowsInput, ListWindowsOutput, MoveCursorInput,- PressKeyInput, ScrollInput, SessionOutput, SessionStateOutput, SetAgentCursorEnabledInput,- SetAgentCursorMotionInput, SetAgentCursorThemeInput, SetWindowFrameInput, SnapshotImage,- StartSessionInput, StartSessionOutput, ToolInput, ToolOutput, TypeTextInput, VerifyStateInput,- VerifyStateOutput, WindowStateOutput,+ ParseVisualRegionsInput, PressKeyInput, ScrollInput, SessionOutput, SessionStateOutput,+ SetAgentCursorEnabledInput, SetAgentCursorMotionInput, SetAgentCursorThemeInput,+ SetWindowFrameInput, SnapshotImage, StartSessionInput, StartSessionOutput, ToolInput,+ ToolOutput, TypeTextInput, VerifyStateInput, VerifyStateOutput, WindowStateOutput,};use cua_driver_core::daemon::{is_daemon_listening, request_daemon_metadata, send_request, socket_path_for_namespace,@@ -22,7 +22,7 @@ use cua_driver_core::daemon::{};use serde::{Deserialize, Serialize};use serde_json::Value;-use std::sync::Arc;+use std::sync::{Arc, OnceLock};use thiserror::Error;mod abi;@@ -53,6 +53,24 @@ use runtime::RuntimeOptions;use service_session::ServiceSessionClient;use worker::{ActionCompletion, PrivateWorkerClient};+type PerceptionClientProvider = fn() -> cua_driver_core::perception_client::PerceptionClient;+static PERCEPTION_CLIENT_PROVIDER: OnceLock<PerceptionClientProvider> = OnceLock::new();++/// Configure the binary-owned resolver for optional installed perception.+/// Language SDKs without a binary host retain the typed unavailable tool.+#[doc(hidden)]+pub fn configure_perception_client_provider(provider: PerceptionClientProvider) {+ let _ = PERCEPTION_CLIENT_PROVIDER.set(provider);+}++pub(crate) fn configured_perception_client() -> cua_driver_core::perception_client::PerceptionClient+{+ PERCEPTION_CLIENT_PROVIDER+ .get()+ .map(|provider| provider())+ .unwrap_or_else(cua_driver_core::perception_client::PerceptionClient::unavailable)+}+fn host_sessions_json_for_prefix(runtime_prefix: &str) -> Value {let sessions = cua_driver_core::session::list_session_snapshots_with_prefix(runtime_prefix,@@ -641,6 +659,7 @@ macro_rules! desktop_tool_methods {get_screen_size: GetScreenSizeInput,get_cursor_position: GetCursorPositionInput,verify_state: VerifyStateInput,+ parse_visual_regions: ParseVisualRegionsInput,move_cursor: MoveCursorInput,set_window_frame: SetWindowFrameInput,invoke_menu: InvokeMenuInput,@@ -1982,6 +2001,7 @@ mod snapshot_lifecycle_tests;mod tests {mod native_windows;use super::*;+ use cua_driver_contract::{ParseVisualRegionsOutput, VisualParseError};#[cfg(unix)]use std::io::{BufRead, BufReader, Write};#[cfg(unix)]@@ -2785,6 +2805,75 @@ mod tests {assert_eq!(request["client_kind"], "python_sdk");}+ #[tokio::test]+ #[cfg(unix)]+ async fn visual_parse_call_preserves_success_and_error_dtos() {+ let mut output: Value = serde_json::from_str(include_str!(+ "../../cua-driver-contract/tests/fixtures/parse-visual-regions-output-full-v1.json"+ ))+ .unwrap();+ output["capture"]["capture_id"] = "capture-123".into();+ let response = serde_json::json!({+ "ok": true,+ "result": {+ "content": [{"type": "text", "text": "parsed"}],+ "structuredContent": output,+ "isError": false+ }+ });+ let (_directory, socket, server) = serve_once(response);+ let driver =+ CuaDriver::connect_with_client_kind(Some(socket), SdkClientKind::Typescript).unwrap();+ let result = driver+ .parse_visual_regions(ParseVisualRegionsInput {+ capture_id: "capture-123".into(),+ options: cua_driver_contract::ParseVisualRegionsOptions::default(),+ })+ .await+ .unwrap();+ let structured = result.structured_json.as_deref().unwrap();+ let decoded: ParseVisualRegionsOutput = serde_json::from_str(structured).unwrap();+ decoded.validate().unwrap();+ assert_eq!(decoded.schema, "cua.visual_regions_v1");+ assert_eq!(decoded.capture.capture_id, "capture-123");+ let request = server.join().unwrap();+ assert_eq!(request["name"], "parse_visual_regions");+ assert_eq!(+ request["args"],+ serde_json::json!({"capture_id": "capture-123", "options": {}})+ );+ assert_eq!(request["client_kind"], "typescript_sdk");++ let response = serde_json::json!({+ "ok": true,+ "result": {+ "content": [{"type": "text", "text": "not installed"}],+ "structuredContent": {+ "code": "not_installed",+ "message": "the optional cua-perception extension is not installed",+ "retryable": false+ },+ "isError": true+ }+ });+ let (_directory, socket, server) = serve_once(response);+ let driver = CuaDriver::connect(Some(socket)).unwrap();+ let result = driver+ .parse_visual_regions(ParseVisualRegionsInput {+ capture_id: "capture-123".into(),+ options: cua_driver_contract::ParseVisualRegionsOptions::default(),+ })+ .await+ .unwrap();+ assert!(result.is_error);+ assert_eq!(result.error_code.as_deref(), Some("not_installed"));+ let error: VisualParseError =+ serde_json::from_str(result.structured_json.as_deref().unwrap()).unwrap();+ error.validate().unwrap();+ assert!(!error.retryable);+ assert_eq!(server.join().unwrap()["name"], "parse_visual_regions");+ }+#[test]fn result_normalization_exposes_typed_action_and_verification_views() {let action = normalize_result(diff --git a/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs b/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rsindex bc860cd80b..2178f94425 100644--- a/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs+++ b/libs/cua-driver/rust/crates/cua-driver-sdk/src/runtime.rs@@ -590,6 +590,16 @@ fn build_registry(options: &RuntimeOptions) -> ToolRegistry {if let Some(register_host_tools) = options.register_host_tools {register_host_tools(&mut registry);}+ let perception_registered = registry.tools_list()["tools"]+ .as_array()+ .is_some_and(|tools| {+ tools.iter().any(|tool| {+ tool.get("name").and_then(Value::as_str) == Some("parse_visual_regions")+ })+ });+ if !perception_registered {+ registry.register_perception_tool(crate::configured_perception_client());+ }let recording = Arc::downgrade(®istry.recording);let recording_session_end = cua_driver_core::session::register_scoped_fallible_session_end_hook("recording",@@ -731,6 +741,40 @@ mod tests {options}+ #[test]+ fn canonical_inventory_advertises_unavailable_perception_tool() {+ let inventory = tool_inventory(RuntimeOptions::embedded(false));+ let tools = inventory["tools"].as_array().unwrap();+ assert_eq!(+ tools+ .iter()+ .filter(|tool| tool["name"] == "parse_visual_regions")+ .count(),+ 1+ );+ }++ #[test]+ fn host_perception_registration_is_not_duplicated_in_inventory() {+ fn register(registry: &mut ToolRegistry) {+ registry.register_perception_tool(+ cua_driver_core::perception_client::PerceptionClient::unavailable(),+ );+ }+ let mut options = RuntimeOptions::embedded(false);+ options.register_host_tools = Some(register);+ let inventory = tool_inventory(options);+ assert_eq!(+ inventory["tools"]+ .as_array()+ .unwrap()+ .iter()+ .filter(|tool| tool["name"] == "parse_visual_regions")+ .count(),+ 1+ );+ }+#[tokio::test]async fn authorized_dispatch_refreshes_only_the_runtime_private_activity_key() {let _runtime_test = TEST_RUNTIME_LOCK.lock().unwrap();diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/cli.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/cli.rsindex 57c6768a9c..61a237dc8a 100644--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/cli.rs+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/cli.rs@@ -29,11 +29,23 @@ impl CliDriver {Self::with_daemon_env(&[])}+ /// Drive an explicitly selected binary.+ ///+ /// Integration tests that use Cargo's `CARGO_BIN_EXE_*` value should use+ /// this constructor so a restored `target/` artifact cannot be mistaken+ /// for the binary Cargo built for the test.+ pub fn with_binary(bin: impl Into<std::path::PathBuf>) -> Self {+ Self::with_binary_and_daemon_env(bin.into(), &[])+ }+/// Start a test-owned daemon with explicit immutable startup settings./// This is used for permission-mode and policy tests; tool-call child/// processes remain ordinary clients and do not receive these values.pub fn with_daemon_env(env: &[(&str, &str)]) -> Self {- let bin = driver_binary();+ Self::with_binary_and_daemon_env(driver_binary(), env)+ }++ fn with_binary_and_daemon_env(bin: std::path::PathBuf, env: &[(&str, &str)]) -> Self {if !bin.exists() {return CliDriver {bin,diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/e2e.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/e2e.rsindex d789a97894..e0e5e81b72 100644--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/e2e.rs+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/e2e.rs@@ -3093,6 +3093,30 @@ mod tests {);}+ #[test]+ fn macos_pixel_drag_routes_preserve_background_and_use_hid_for_foreground() {+ assert_eq!(+ shared_web_route(+ Platform::Macos,+ DisplayServer::Quartz,+ "drag",+ Targeting::Px,+ Delivery::Background,+ ),+ Ok(DriverRoute::MacosCgEventPid)+ );+ assert_eq!(+ shared_web_route(+ Platform::Macos,+ DisplayServer::Quartz,+ "drag",+ Targeting::Px,+ Delivery::Foreground,+ ),+ Ok(DriverRoute::MacosCgEventHid)+ );+ }+#[test]fn nested_wayland_pixel_route_is_distinct_from_stock_wayland() {let stock = shared_web_route_for_environment(diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/mcp.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/mcp.rsindex a5ed7260c2..a3489b2f46 100644--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/mcp.rs+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/mcp.rs@@ -25,6 +25,7 @@ use crate::CALL_TIMEOUT;pub struct McpDriver {reaper: ChildReaper,_daemon: Option<TestDaemon>,+ socket: String,stdin: ChildStdin,rx: Receiver<String>,next_id: u32,@@ -47,6 +48,11 @@ impl McpDriver {Self::spawn_internal(&[], &[], None, false, true)}+ /// Spawn through the exact binary selected by the caller.+ pub fn spawn_with_binary(bin: impl Into<PathBuf>) -> Option<Self> {+ Self::spawn_internal_with_binary(bin.into(), &[], &[], None, false, true)+ }+/// Spawn the driver with a stable recording label for artifact naming.pub fn spawn_named(recording_label: &str) -> Option<Self> {Self::spawn_internal(&[], &[], Some(recording_label), false, true)@@ -97,6 +103,10 @@ impl McpDriver {Self::spawn_internal(&[], &["mcp", "--socket", socket], None, false, false)}+ pub fn spawn_peer_unrecorded(&self) -> Option<Self> {+ Self::spawn_daemon_proxy_unrecorded(&self.socket)+ }+/// Spawn the driver with extra environment variables set on the child.pub fn spawn_with_env(env: &[(&str, &str)]) -> Option<Self> {Self::spawn_internal(env, &[], None, false, true)@@ -108,6 +118,24 @@ impl McpDriver {recording_label: Option<&str>,overlay_enabled: bool,prepare_recording: bool,+ ) -> Option<Self> {+ Self::spawn_internal_with_binary(+ driver_binary(),+ env,+ args,+ recording_label,+ overlay_enabled,+ prepare_recording,+ )+ }++ fn spawn_internal_with_binary(+ bin: PathBuf,+ env: &[(&str, &str)],+ args: &[&str],+ recording_label: Option<&str>,+ overlay_enabled: bool,+ prepare_recording: bool,) -> Option<Self> {let mut daemon_env = env.to_vec();let e2e_unrestricted = std::env::var_os("CUA_E2E_UNRESTRICTED_GUI").is_some();@@ -124,7 +152,6 @@ impl McpDriver {("CUA_DRIVER_DANGEROUSLY_BYPASS_APPROVALS", "1"),]);}- let bin = driver_binary();if !bin.exists() {eprintln!("[testkit] driver binary not built at {bin:?} — skipping");return None;@@ -188,9 +215,18 @@ impl McpDriver {}});+ let socket = daemon+ .as_ref()+ .map(|daemon| daemon.socket.clone())+ .or_else(|| {+ args.windows(2)+ .find(|pair| pair[0] == "--socket")+ .map(|pair| pair[1].to_owned())+ })?;let mut d = McpDriver {reaper,_daemon: daemon,+ socket,stdin,rx,next_id: 2,diff --git a/libs/cua-driver/rust/crates/cua-driver-testkit/src/raw.rs b/libs/cua-driver/rust/crates/cua-driver-testkit/src/raw.rsindex 401f76298d..635d5a677c 100644--- a/libs/cua-driver/rust/crates/cua-driver-testkit/src/raw.rs+++ b/libs/cua-driver/rust/crates/cua-driver-testkit/src/raw.rs@@ -9,6 +9,7 @@//! don't each re-implement `send_request`/`read_response`.use std::io::{BufRead, BufReader, Write};+use std::path::PathBuf;use std::process::{ChildStdin, ChildStdout, Command, Stdio};use serde_json::Value;@@ -38,7 +39,12 @@ impl RawDriver {/// if the binary isn't built — callers early-return so an un-built binary/// skips rather than fails.pub fn spawn() -> Option<Self> {- Self::spawn_daemon_backed(false, &[])+ Self::spawn_daemon_backed(driver_binary(), false, &[])+ }++ /// Spawn through the exact binary selected by the caller.+ pub fn spawn_with_binary(bin: impl Into<PathBuf>) -> Option<Self> {+ Self::spawn_daemon_backed(bin.into(), false, &[])}/// Spawn the daemon-backed driver with an explicit test environment.@@ -46,23 +52,26 @@ impl RawDriver {/// Permission-mode tests use this to model a trusted host's launch-time/// configuration without mutating the test process environment.pub fn spawn_with_env(env: &[(&str, &str)]) -> Option<Self> {- Self::spawn_daemon_backed(false, env)+ Self::spawn_daemon_backed(driver_binary(), false, env)}/// Spawn a daemon-backed raw driver with the certified platform overlay/// host enabled. Cursor protocol tests use this deliberately; ordinary/// protocol tests keep the no-overlay daemon so they remain headless.pub fn spawn_with_overlay() -> Option<Self> {- Self::spawn_daemon_backed(true, &[])+ Self::spawn_daemon_backed(driver_binary(), true, &[])}/// Spawn an overlay-enabled daemon with explicit trusted launch settings.pub fn spawn_with_overlay_and_env(env: &[(&str, &str)]) -> Option<Self> {- Self::spawn_daemon_backed(true, env)+ Self::spawn_daemon_backed(driver_binary(), true, env)}- fn spawn_daemon_backed(overlay_enabled: bool, env: &[(&str, &str)]) -> Option<Self> {- let bin = driver_binary();+ fn spawn_daemon_backed(+ bin: PathBuf,+ overlay_enabled: bool,+ env: &[(&str, &str)],+ ) -> Option<Self> {if !bin.exists() {eprintln!("[testkit] driver binary not built at {bin:?} — skipping");return None;diff --git a/libs/cua-driver/rust/crates/cua-driver/Cargo.toml b/libs/cua-driver/rust/crates/cua-driver/Cargo.tomlindex 8e114a211f..454c8d556b 100644--- a/libs/cua-driver/rust/crates/cua-driver/Cargo.toml+++ b/libs/cua-driver/rust/crates/cua-driver/Cargo.toml@@ -17,6 +17,7 @@ anyhow = { workspace = true }tracing = { workspace = true }tracing-subscriber = { workspace = true }cua-driver-core = { path = "../cua-driver-core" }+cua-driver-contract = { path = "../cua-driver-contract" }cua-driver-sdk = { path = "../cua-driver-sdk" }cursor-overlay = { path = "../cursor-overlay" }pip-preview = { path = "../pip-preview" }@@ -41,6 +42,13 @@ semver = "1"# dependency is easy to find).tar = { version = "0.4", default-features = false }flate2 = "1"+sha2 = { workspace = true }+ring = "0.17"+fs2 = { workspace = true }+cap-std = "4.0.3"+cap-fs-ext = "4.0.3"+rustix = { version = "1.1", features = ["fs", "process"] }+image = { workspace = true }# Used by crate::bundle::parent_is_not_launchd() for the TCC# auto-relaunch detection path on Unix (only the macOS heuristic@@ -64,6 +72,10 @@ platform-linux = { path = "../platform-linux" }[features]default = []+# Local review builds may replace the production extension trust root with an+# explicitly supplied Ed25519 public key. The build script rejects release+# profiles and missing/invalid overrides; ordinary artifacts never enable it.+review-trust-root = []# GNOME/KDE portal input ships in ordinary Linux releases; PipeWire capture# remains a separate modern-desktop feature. The combined name stays as a# compatibility alias for Nix and downstream builds.@@ -80,10 +92,8 @@ embed-resource = "2"# Shared integration-test harness (MCP/CLI transports, child reaping, paths,# response accessors). Dev-only — never linked into the shipped driver.cua-driver-testkit = { path = "../cua-driver-testkit" }-cua-driver-contract = { path = "../cua-driver-contract" }jsonschema = { version = "0.46", default-features = false }tokio = { workspace = true, features = ["full"] }-image = { workspace = true }base64 = { workspace = true }# Isolated HOME / cache directories for `version_check` unit tests so they# never touch the developer's real `~/.cua-driver/version_check.json`.diff --git a/libs/cua-driver/rust/crates/cua-driver/build.rs b/libs/cua-driver/rust/crates/cua-driver/build.rsindex cc2f15a003..e1dbf7fa76 100644--- a/libs/cua-driver/rust/crates/cua-driver/build.rs+++ b/libs/cua-driver/rust/crates/cua-driver/build.rs@@ -12,6 +12,9 @@// 125%/150%/200% scaling and clicks land where screenshots say they do.fn main() {+ println!("cargo:rerun-if-env-changed=CUA_DRIVER_REVIEW_EXTENSION_PUBLIC_KEY_BASE64");+ validate_review_trust_root_build();+#[cfg(target_os = "windows")]{embed_resource::compile("cua-driver.rc", embed_resource::NONE);@@ -24,6 +27,27 @@ fn main() {emit_swift_runtime_link_args();}+fn validate_review_trust_root_build() {+ if std::env::var_os("CARGO_FEATURE_REVIEW_TRUST_ROOT").is_none() {+ return;+ }+ if std::env::var("PROFILE").as_deref() == Ok("release") {+ panic!("review-trust-root is review-only and cannot be enabled in release artifacts");+ }+ let key = std::env::var("CUA_DRIVER_REVIEW_EXTENSION_PUBLIC_KEY_BASE64").expect(+ "review-trust-root requires CUA_DRIVER_REVIEW_EXTENSION_PUBLIC_KEY_BASE64 at build time",+ );+ let key = key.trim().as_bytes();+ if key.len() != 44+ || key[43] != b'='+ || !key[..43]+ .iter()+ .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'/'))+ {+ panic!("review-trust-root override must be standard base64 for exactly one 32-byte Ed25519 public key");+ }+}+fn emit_sdk_framework_search_path() {if let Some(sdk_root) = active_macos_sdk_root() {println!(diff --git a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs b/libs/cua-driver/rust/crates/cua-driver/src/cli.rsindex 0003669502..81546e382f 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs@@ -8,6 +8,7 @@//! cua-driver describe <tool> → print tool schema//! cua-driver call <tool> [json-args] → invoke tool, print result//! cua-driver <tool> [json-args] → shorthand for call (snake_case names)+//! cua-driver perception parse ... → parse a local PNG without action authority//!//! Cursor-overlay flags (--cursor-theme, --no-overlay, etc.) are consumed by//! `CursorConfig::from_args()` and are ignored here.@@ -50,6 +51,7 @@ pub enum Command {},Serve {socket: Option<String>,+ pid_file: Option<String>,/// Immutable agent-authorization mode selected at trusted daemon/// startup. This is distinct from the macOS OS-permissions gate.permission_mode: Option<String>,@@ -190,6 +192,14 @@ pub enum Command {subcommand: String,flags: Vec<String>,},+ /// Authenticated lifecycle for optional target-specific extensions.+ Extension {+ args: Vec<String>,+ },+ /// Local-file-only visual parsing through the installed extension.+ Perception {+ args: Vec<String>,+ },/// Trusted local cursor-theme authoring and installation workflow. The/// actual parser/compiler is a separate short-lived executable so Lottie,/// ZIP, and JSON are not linked into the privileged daemon.@@ -232,6 +242,9 @@ const VALUE_FLAGS: &[&str] = &["--session","--profile-mode","--profile-name",+ "--archive",+ "--image",+ "--capture",// Experimental PiP preview — value flag for the optional geometry// override (--experimental-pip itself is a bare flag and doesn't// need to be listed here).@@ -319,6 +332,8 @@ fn finite_command_name_from_args(args: &[String]) -> Option<&'static str> {Some("permissions") => Some("permissions"),Some("autostart") => Some("autostart"),Some("skills") => Some("skills"),+ Some("extension") => Some("extension"),+ Some("perception") => Some("perception"),Some("cursor-theme") => Some("cursor_theme"),Some("config") => Some("config"),Some(_) => Some("call"),@@ -417,6 +432,19 @@ fn finite_operation_from_args(args: &[String]) -> &'static str {"path" => "path",_ => "other",},+ Some("extension") => match subcommand.unwrap_or("list") {+ "list" => "list",+ "info" => "info",+ "status" => "status",+ "install" => "install",+ "update" => "update",+ "path" => "path",+ _ => "other",+ },+ Some("perception") => match subcommand.unwrap_or("") {+ "parse" => "parse",+ _ => "other",+ },Some("update") if args.iter().any(|arg| arg == "--apply") => "apply",Some("update") => "check_only",Some("channel") => match subcommand.unwrap_or("status") {@@ -493,7 +521,7 @@ pub fn parse_command() -> Command {env!("CARGO_PKG_VERSION"));println!("Usage: cua-driver [SUBCOMMAND] [OPTIONS]");- println!("Subcommands: mcp, list-tools, describe, call, serve, stop, revoke, status, config, telemetry, recording, update, check-update, doctor, diagnose, permissions, autostart, skills, manifest, channel, cursor-theme, sessions, history");+ println!("Subcommands: mcp, list-tools, describe, call, serve, stop, revoke, status, config, telemetry, recording, update, check-update, doctor, diagnose, permissions, autostart, skills, manifest, extension, perception, channel, cursor-theme, sessions, history");println!();println!("permissions options (macOS):");println!(" cua-driver permissions status Report Accessibility + Screen Recording status. Read-only (no prompt).");@@ -534,6 +562,33 @@ pub fn parse_command() -> Command {println!(" cua-driver skills path Print where the local skill pack lives.");println!(" --from main (install only) Fetch latest from main branch instead of the tagged release.");println!();+ println!("extension options (SIGNED TARGET-SPECIFIC CATALOGS):");+ println!(+ " Verified installs check publisher identity plus exact catalog, archive, manifest,"+ );+ println!(+ " file, original/converted model hashes, component notices, and source revisions."+ );+ println!(+ " Ed25519 key validity windows and publisher-signed key rotation prevent rollback."+ );+ println!(" Inspect previews license, corresponding source, and provenance first.");+ println!(" Install, update, and remove support macOS, Linux, and Windows.");+ println!(" cua-driver extension list [--json]");+ println!(" cua-driver extension inspect <name> --catalog <catalog.json> [--json]");+ println!(" cua-driver extension status [name] [--self-test] [--json]");+ println!(" cua-driver extension install <name> --catalog <catalog.json>");+ println!(" cua-driver extension update <name> --catalog <catalog.json>");+ println!(" cua-driver extension remove <name>");+ println!(+ " Developer only: replace --catalog with --archive <tar.gz> --allow-unsigned-local"+ );+ println!(" Compatibility aliases: extension info <name>; extension path <name>");+ println!();+ println!("local perception (read-only, no Driver action authority):");+ println!(" cua-driver perception parse --image <png> --capture <capture.json> --json");+ println!(" The capture file supplies source metadata only; the image is never registered as a reusable capture.");+ println!();println!("agent authorization (serve only):");println!(" --permission-mode <mode> standard (default), bounded, or unrestricted.");println!(@@ -753,6 +808,7 @@ pub fn parse_command() -> Command {Some("mcp-config") => Command::McpConfig { client: mcp_client },Some("serve") => Command::Serve {socket,+ pid_file: flag_value(&args, "--pid-file"),permission_mode: flag_value(&args, "--permission-mode"),dangerously_bypass_approvals: args.iter()@@ -975,6 +1031,24 @@ pub fn parse_command() -> Command {}Command::Skills { subcommand, flags }}+ Some("extension") => {+ let index = args+ .iter()+ .position(|value| value == "extension")+ .expect("extension positional is present");+ Command::Extension {+ args: args[index + 1..].to_vec(),+ }+ }+ Some("perception") => {+ let index = args+ .iter()+ .position(|value| value == "perception")+ .expect("perception positional is present");+ Command::Perception {+ args: args[index + 1..].to_vec(),+ }+ }Some("cursor-theme") => {let index = args.iter()@@ -1956,7 +2030,26 @@ pub fn build_manifest() -> serde_json::Value {"args": [ { "name": "subcommand", "type": "positional-string", "description": "enable | disable | status | kick" } ] },{ "name": "skills","description": "Manage the cua-driver agent skill pack (install / update / uninstall / status / path).",- "args": [ { "name": "subcommand", "type": "positional-string", "description": "install | update | uninstall | status | path. Default: status." } ] }+ "args": [ { "name": "subcommand", "type": "positional-string", "description": "install | update | uninstall | status | path. Default: status." } ] },+ { "name": "extension",+ "description": "Inspect and manage signed, target-specific optional extensions on macOS, Linux, and Windows. Verified installs bind publisher identity, Ed25519 key validity and signed rotation metadata, provenance, component licenses/notices, corresponding-source revisions, and exact catalog, archive, manifest, file, original-model, and converted-model hashes.",+ "args": [+ { "name": "subcommand", "type": "positional-string", "description": "list | inspect | status | install | update | remove. Default: list." },+ { "name": "name", "type": "positional-string", "description": "Registry extension name." },+ { "name": "--catalog", "type": "string", "description": "Signed local catalog; its target-specific archive path is resolved relative to this file." },+ { "name": "--archive", "type": "string", "description": "Developer-only unsigned local archive; requires --allow-unsigned-local and cannot claim verified identity." },+ { "name": "--allow-unsigned-local", "type": "flag", "description": "Explicitly opt into an unverified developer install." },+ { "name": "--self-test", "type": "flag", "description": "Run the installed extension self-test during status." },+ { "name": "--json", "type": "flag", "description": "Emit machine-readable inspection output." }+ ] },+ { "name": "perception",+ "description": "Parse a local PNG through the installed optional perception extension without creating Driver capture or action authority.",+ "args": [+ { "name": "subcommand", "type": "positional-string", "description": "Only: parse." },+ { "name": "--image", "type": "string", "description": "Local PNG path." },+ { "name": "--capture", "type": "string", "description": "Local capture source metadata JSON path." },+ { "name": "--json", "type": "flag", "description": "Required; emit canonical visual-regions JSON with local-input provenance." }+ ] }]})}@@ -2334,6 +2427,10 @@ pub fn run_call(Ok(resp) => {if resp.ok {if let Some(result) = resp.result {+ let is_error = result+ .get("isError")+ .and_then(serde_json::Value::as_bool)+ .unwrap_or(false);// Walk the content array once: pick up any Image// payloads (either to write to --screenshot-out-file// or to merge into structuredContent below).@@ -2413,6 +2510,9 @@ pub fn run_call(}}}+ if is_error {+ process::exit(1);+ }}} else {if let Some(err) = resp.error {@@ -4149,6 +4249,35 @@ fn cli_docs_json() -> serde_json::Value {{"name":"path","abstract":"Print the local skill-pack path.","discussion":"","arguments":[],"options":[],"flags":[],"subcommands":[]}]},+ {+ "name": "extension",+ "abstract": "Inspect and manage signed, target-specific optional extensions.",+ "discussion": "Verified installs bind a pinned publisher identity and Ed25519 key validity/rotation state to exact catalog, archive, manifest, file, original-model, and converted-model hashes plus component licenses/notices and corresponding-source revisions. Inspect previews license, source, and provenance before mutation. Explicit developer-only unsigned installs remain visibly unverified. Install, update, and remove use platform-specific ownership and link/reparse-point checks on macOS, Linux, and Windows.",+ "arguments": no_args,+ "options": no_options,+ "flags": no_flags,+ "subcommands": [+ {"name":"list","abstract":"List registry-known extensions and local state.","discussion":"","arguments":[],"options":[],"flags":[{"name":"json","short_name":null,"help":"Emit machine-readable output.","default_value":false}],"subcommands":[]},+ {"name":"info","abstract":"Compatibility alias for installed extension status.","discussion":"","arguments":[{"name":"name","help":"Registry extension name.","type":"String","is_optional":false}],"options":[],"flags":[{"name":"json","short_name":null,"help":"Emit machine-readable output.","default_value":false}],"subcommands":[]},+ {"name":"inspect","abstract":"Verify and preview license, source, provenance, and hashes without mutation.","discussion":"","arguments":[{"name":"name","help":"Registry extension name.","type":"String","is_optional":false}],"options":[{"name":"catalog","short_name":null,"help":"Signed local catalog.","type":"String","default_value":null,"is_optional":true},{"name":"archive","short_name":null,"help":"Developer-only unsigned local archive.","type":"String","default_value":null,"is_optional":true}],"flags":[{"name":"allow-unsigned-local","short_name":null,"help":"Explicitly select developer-only unverified mode.","default_value":false},{"name":"json","short_name":null,"help":"Emit machine-readable output.","default_value":false}],"subcommands":[]},+ {"name":"status","abstract":"Verify installed integrity and optionally run the self-test hook.","discussion":"","arguments":[{"name":"name","help":"Optional registry extension name.","type":"String","is_optional":true}],"options":[],"flags":[{"name":"self-test","short_name":null,"help":"Run the extension self-test hook.","default_value":false},{"name":"json","short_name":null,"help":"Emit machine-readable output.","default_value":false}],"subcommands":[]},+ {"name":"install","abstract":"Verify, stage, and durably activate an extension.","discussion":"Supported on macOS, Linux, and Windows with platform ownership and link/reparse-point checks.","arguments":[{"name":"name","help":"Registry extension name.","type":"String","is_optional":false}],"options":[{"name":"catalog","short_name":null,"help":"Signed local catalog.","type":"String","default_value":null,"is_optional":true},{"name":"archive","short_name":null,"help":"Developer-only unsigned local archive.","type":"String","default_value":null,"is_optional":true}],"flags":[{"name":"allow-unsigned-local","short_name":null,"help":"Explicitly select developer-only unverified mode.","default_value":false}],"subcommands":[]},+ {"name":"update","abstract":"Verify and atomically activate a newer extension version.","discussion":"Supported on macOS, Linux, and Windows with platform ownership and link/reparse-point checks.","arguments":[{"name":"name","help":"Registry extension name.","type":"String","is_optional":false}],"options":[{"name":"catalog","short_name":null,"help":"Signed local catalog.","type":"String","default_value":null,"is_optional":true},{"name":"archive","short_name":null,"help":"Developer-only unsigned local archive.","type":"String","default_value":null,"is_optional":true}],"flags":[{"name":"allow-unsigned-local","short_name":null,"help":"Explicitly select developer-only unverified mode.","default_value":false}],"subcommands":[]},+ {"name":"remove","abstract":"Remove only a fully validated, manager-owned extension tree.","discussion":"Supported on macOS, Linux, and Windows with platform ownership and link/reparse-point checks.","arguments":[{"name":"name","help":"Registry extension name.","type":"String","is_optional":false}],"options":[],"flags":[],"subcommands":[]},+ {"name":"path","abstract":"Compatibility command that prints the exact active version directory.","discussion":"","arguments":[{"name":"name","help":"Registry extension name.","type":"String","is_optional":false}],"options":[],"flags":[],"subcommands":[]}+ ]+ },+ {+ "name": "perception",+ "abstract": "Parse a local PNG with the installed optional perception extension.",+ "discussion": "This read-only local-input mode does not create a Driver capture. Its visual-regions JSON marks the result ineligible for Driver action authority.",+ "arguments": no_args,+ "options": no_options,+ "flags": no_flags,+ "subcommands": [+ {"name":"parse","abstract":"Parse one local PNG into canonical visual regions.","discussion":"Requires --json. The capture file supplies source metadata only.","arguments":[],"options":[{"name":"image","short_name":null,"help":"Local PNG path.","type":"String","default_value":null,"is_optional":false},{"name":"capture","short_name":null,"help":"Local capture source metadata JSON path.","type":"String","default_value":null,"is_optional":false}],"flags":[{"name":"json","short_name":null,"help":"Emit canonical visual-regions JSON with local-input provenance.","default_value":false}],"subcommands":[]}+ ]+ },{"name": "manifest","abstract": "Emit a stable JSON description of the CLI surface.",@@ -4866,6 +4995,20 @@ mod tests {assert_eq!(positional_args(&argv), vec!["status"]);}+ #[test]+ fn pid_file_is_parsed_for_serve_before_or_after_the_subcommand() {+ for argv in [+ args(&["serve", "--pid-file", "/tmp/cua-driver.pid"]),+ args(&["--pid-file=/tmp/cua-driver.pid", "serve"]),+ ] {+ assert_eq!(positional_args(&argv), vec!["serve"]);+ assert_eq!(+ flag_value(&argv, "--pid-file"),+ Some("/tmp/cua-driver.pid".to_owned())+ );+ }+ }+#[test]fn finite_call_tool_extraction_supports_subcommand_and_legacy_forms() {assert_eq!(diff --git a/libs/cua-driver/rust/crates/cua-driver/src/extension_manager.rs b/libs/cua-driver/rust/crates/cua-driver/src/extension_manager.rsnew file mode 100644index 0000000000..094f9a41ac--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver/src/extension_manager.rs@@ -0,0 +1,7166 @@+//! Authenticated lifecycle for optional Driver extensions.+//!+//! Normal installs consume a target-specific catalog signed by a pinned+//! publisher and verify the catalog, archive, manifest, payload, and model+//! hashes before activation. An explicitly marked developer mode accepts a+//! local unsigned archive, but records and reports that weaker trust class.++use anyhow::{anyhow, bail, Context, Result};+use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};+use cap_fs_ext::{DirExt, FollowSymlinks, OpenOptionsFollowExt};+use cap_std::ambient_authority;+use cap_std::fs::{Dir, OpenOptions as CapOpenOptions};+use flate2::read::GzDecoder;+use fs2::FileExt;+use semver::{Version, VersionReq};+use serde::{Deserialize, Serialize};+use sha2::{Digest, Sha256};+use std::collections::{BTreeMap, BTreeSet};+use std::fs;+use std::io::{Read, Seek, Write};+use std::path::{Component, Path, PathBuf};+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::OnceLock;+use std::time::{Duration, Instant};++#[cfg(windows)]+use cua_driver_core::perception_client::containment::{+ recover_windows_acl_profile_journal, windows_acl_profile_journal_path,+};+use cua_driver_core::perception_client::containment::{+ run_contained_hook, ContainmentLimits, HookOutcome,+};+use cua_driver_core::perception_client::{PerceptionClient, PerceptionWorkerConfig};+use cua_driver_core::protocol::ToolResult;+use cua_driver_core::tool::{Tool, ToolDef, ToolRegistry};++const MANIFEST_NAME: &str = "extension.json";+const INSTALL_RECORD_NAME: &str = ".install.json";+const ACTIVE_NAME: &str = "active.json";+const ACTIVE_BACKUP_NAME: &str = "active.backup.json";+const ACTIVE_NEW_NAME: &str = "active.new.json";+const TRUST_NAME: &str = ".publisher-trust.json";+const TRUST_NEW_NAME: &str = ".publisher-trust.new.json";+const TRUST_BACKUP_NAME: &str = ".publisher-trust.backup.json";+const MANIFEST_SCHEMA_VERSION: u32 = 1;+const CATALOG_SCHEMA_VERSION: u32 = 1;+// The initial lifecycle targets one executable plus a moderate model bundle.+// These defaults keep disk/memory exposure bounded without claiming support+// for multi-tens-of-gigabytes production model distributions.+const MAX_ARCHIVE_BYTES: u64 = 512 * 1024 * 1024;+const MAX_EXPANDED_BYTES: u64 = 8 * 1024 * 1024 * 1024;+const MAX_FILE_BYTES: u64 = 4 * 1024 * 1024 * 1024;+const MAX_IN_MEMORY_BYTES: u64 = 1024 * 1024;+const MAX_FILE_COUNT: usize = 4_096;+const MAX_ARCHIVE_PATH_BYTES: usize = 512;+const DEVELOPER_TRUST_NOTICE: &str = "developer-only unsigned local install; it is not publisher-verified and cannot be represented as verified";+#[cfg(feature = "review-trust-root")]+const REVIEW_TRUST_NOTICE: &str = "REVIEW ONLY: locally overridden trust root; never production, release, or publishable evidence";+#[cfg_attr(feature = "review-trust-root", allow(dead_code))]+const VERIFIED_PUBLISHER_ID: &str = "cua";+#[cfg_attr(feature = "review-trust-root", allow(dead_code))]+const VERIFIED_PUBLISHER_NAME: &str = "Cua";+#[cfg(not(feature = "review-trust-root"))]+const VERIFIED_KEY_ID: &str = "cua-extension-ed25519-2026-01";+// The corresponding private key is held outside this repository.+#[cfg(not(feature = "review-trust-root"))]+const VERIFIED_KEY_VALID_FROM_UNIX: u64 = 1_735_689_600; // 2025-01-01+#[cfg(not(feature = "review-trust-root"))]+const VERIFIED_KEY_VALID_UNTIL_UNIX: u64 = 2_082_758_400; // 2036-01-01+#[cfg(any(not(feature = "review-trust-root"), test))]+const VERIFIED_PUBLIC_KEY: [u8; 32] = [+ 0x74, 0x1e, 0xc4, 0xff, 0x7e, 0x9f, 0x4d, 0x72, 0xe2, 0x1c, 0xf7, 0xeb, 0xf3, 0x26, 0xb8, 0x8b,+ 0x84, 0xc5, 0x6e, 0xcb, 0x14, 0xfe, 0x3a, 0x4e, 0xf7, 0x3a, 0xd2, 0xf2, 0x09, 0x78, 0x6e, 0xc4,+];+#[cfg(feature = "review-trust-root")]+const REVIEW_PUBLISHER_ID: &str = "cua-review-only";+#[cfg(feature = "review-trust-root")]+const REVIEW_PUBLISHER_NAME: &str = "Cua REVIEW ONLY";+#[cfg(feature = "review-trust-root")]+const REVIEW_KEY_ID: &str = "review-only-build-override";+#[cfg(feature = "review-trust-root")]+const REVIEW_PUBLIC_KEY_BASE64: &str = env!(+ "CUA_DRIVER_REVIEW_EXTENSION_PUBLIC_KEY_BASE64",+ "review-trust-root requires CUA_DRIVER_REVIEW_EXTENSION_PUBLIC_KEY_BASE64 at build time"+);+const PERCEPTION_ID: &str = "cua-perception";+const PERCEPTION_RUNTIME_CONTRACT: &str = "metadata/runtime-contract.json";+const PERCEPTION_MODEL_MANIFEST_NAME: &str = "model-manifest.json";+const EXTENSION_LOCK_RETRY_INTERVAL: Duration = Duration::from_millis(50);+const EXTENSION_LOCK_RETRY_WINDOW: Duration = Duration::from_secs(1);+#[cfg(any(windows, test))]+const WINDOWS_ACL_LEASE_RETRY_INTERVAL: Duration = Duration::from_millis(50);++#[cfg(any(windows, test))]+#[derive(Debug, Clone, Copy)]+struct WindowsAclDrift;++#[cfg(any(windows, test))]+impl std::fmt::Display for WindowsAclDrift {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter.write_str("extension Windows ACL was modified after hardening")+ }+}++#[cfg(any(windows, test))]+impl std::error::Error for WindowsAclDrift {}++#[cfg(windows)]+const WINDOWS_ACL_CONVERGENCE_ATTEMPTS: u32 = 3;+#[cfg(windows)]+const WINDOWS_ACL_CONVERGENCE_RETRY_WINDOW: Duration = Duration::from_secs(90);++#[derive(Clone, Copy)]+struct RegistryEntry {+ id: &'static str,+ display_name: &'static str,+ description: &'static str,+ protocol_version: u32,+}++const REGISTRY: &[RegistryEntry] = &[RegistryEntry {+ id: "cua-perception",+ display_name: "Cua Perception",+ description: "Optional signed perception worker and target-specific model bundle.",+ protocol_version: 1,+}];++#[derive(Debug, Clone, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+struct ExtensionManifest {+ schema_version: u32,+ id: String,+ version: String,+ driver_version: String,+ protocol_version: u32,+ target: String,+ entrypoint: String,+ files: Vec<ManifestFile>,+ models: Vec<ManifestModel>,+ components: Vec<ComponentLicense>,+ #[serde(default)]+ corresponding_source_file: Option<ArtifactBinding>,+ license: String,+ source: String,+ corresponding_source_uri: String,+ corresponding_source_revision: String,+ provenance: String,+ #[serde(default)]+ health_args: Vec<String>,+ #[serde(default)]+ self_test_args: Vec<String>,+}++#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase", deny_unknown_fields)]+struct PerceptionRuntimeContract {+ #[serde(rename = "$schema")]+ schema: Option<String>,+ schema_version: u32,+ target: String,+ protocol_version: u32,+ worker: RuntimeBinding,+ runtime: RuntimeBinding,+ model_manifest: RuntimeBinding,+ models: Vec<RuntimeBinding>,+ dictionary: RuntimeBinding,+ reject_mismatch: bool,+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+struct RuntimeBinding {+ name: String,+ #[serde(default)]+ role: Option<String>,+ sha256: String,+}++#[derive(Debug, Clone, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+struct ManifestFile {+ path: String,+ sha256: String,+ #[serde(default)]+ executable: bool,+}++#[derive(Debug, Clone, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+struct ManifestModel {+ path: String,+ revision: String,+ original_sha256: String,+ conversion_sha256: String,+ #[serde(default)]+ license_file: Option<ArtifactBinding>,+}++#[derive(Debug, Clone, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+struct ComponentLicense {+ name: String,+ version: String,+ license: String,+ notice: String,+ source_uri: String,+ source_revision: String,+ #[serde(default)]+ notice_file: Option<ArtifactBinding>,+}++#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]+#[serde(deny_unknown_fields)]+struct ArtifactBinding {+ path: String,+ sha256: String,+}++#[derive(Debug, Clone, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+struct SignedCatalog {+ payload: CatalogPayload,+ signature_algorithm: String,+ signature: String,+}++#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]+#[serde(deny_unknown_fields)]+struct PublisherKey {+ key_id: String,+ public_key_base64: String,+ valid_from_unix: u64,+ valid_until_unix: u64,+}++#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]+#[serde(deny_unknown_fields)]+struct PublisherTrust {+ schema_version: u32,+ publisher_id: String,+ generation: u64,+ highest_catalog_version: u64,+ current_key: PublisherKey,+ pending_key: Option<PublisherKey>,+}++#[derive(Debug, Clone, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+struct CatalogPayload {+ schema_version: u32,+ catalog_version: u64,+ expires_unix: u64,+ publisher_id: String,+ publisher_name: String,+ key_id: String,+ extension_id: String,+ version: String,+ target: String,+ archive: String,+ archive_size: u64,+ archive_sha256: String,+ manifest_sha256: String,+ license: String,+ source: String,+ corresponding_source_uri: String,+ corresponding_source_revision: String,+ provenance: String,+ #[serde(default)]+ next_key: Option<PublisherKey>,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "kebab-case")]+enum TrustClass {+ PublisherVerified,+ #[cfg(feature = "review-trust-root")]+ ReviewOnlyPublisherVerified,+ DeveloperUnsignedLocal,+}++#[derive(Debug, Clone)]+struct InstallSource {+ archive: PathBuf,+ trust: TrustClass,+ catalog: Option<CatalogPayload>,+ signed_catalog: Option<SignedCatalog>,+ trust_update: Option<PublisherTrust>,+}++#[derive(Debug, Clone, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+struct ActivePointer {+ id: String,+ version: String,+}++#[derive(Debug, Clone, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+struct InstallRecord {+ schema_version: u32,+ id: String,+ version: String,+ manifest_sha256: String,+ trust: TrustClass,+ publisher_id: Option<String>,+ key_id: Option<String>,+ archive_sha256: String,+ catalog_version: Option<u64>,+ #[serde(default)]+ publisher_trust: Option<PublisherTrust>,+}++#[derive(Debug, Serialize)]+struct ExtensionInfo<'a> {+ id: &'a str,+ display_name: &'a str,+ description: &'a str,+ protocol_version: u32,+ installed: bool,+ active_version: Option<String>,+ healthy: bool,+ trust: Option<TrustClass>,+ evidence_class: Option<&'static str>,+ publisher_id: Option<String>,+ publisher_key_id: Option<String>,+ catalog_version: Option<u64>,+ detail: String,+}++#[derive(Debug)]+struct ArchiveFile {+ path: String,+ sha256: String,+ size: u64,+}++#[derive(Debug)]+struct InspectedArchive {+ manifest: ExtensionManifest,+ manifest_bytes: Vec<u8>,+ archive_sha256: String,+ archive_size: u64,+ expanded_size: u64,+}++#[derive(Debug, Serialize)]+struct InstallReview {+ extension: &'static str,+ id: String,+ name: String,+ artifact: String,+ backend: &'static str,+ acceleration: &'static str,+ version: String,+ target: String,+ publisher: Option<String>,+ publisher_id: Option<String>,+ publisher_name: Option<String>,+ publisher_key_id: Option<String>,+ signing_key_algorithm: Option<String>,+ signing_key_status: &'static str,+ publisher_signature_verified: bool,+ catalog_version: Option<u64>,+ catalog_expires_unix: Option<u64>,+ trust: TrustClass,+ evidence_class: &'static str,+ artifact_source: String,+ destination: String,+ download_size: u64,+ installed_size: u64,+ archive_sha256: String,+ manifest_sha256: String,+ license: String,+ license_notices: Vec<LicenseNoticeReview>,+ model_licenses: Vec<ModelLicenseReview>,+ source: String,+ corresponding_source: CorrespondingSourceReview,+ corresponding_source_uri: String,+ corresponding_source_revision: String,+ provenance: String,+ files: Vec<ManifestFile>,+ models: Vec<ManifestModel>,+ components: Vec<ComponentLicense>,+ authorization: InstallAuthorizationReview,+ mutation_performed: bool,+ installed: bool,+ ran: bool,+ #[serde(skip_serializing_if = "Option::is_none")]+ installed_version: Option<String>,+}++#[derive(Debug, Serialize)]+struct LicenseNoticeReview {+ component: String,+ license: String,+ file: Option<ArtifactBinding>,+}++#[derive(Debug, Serialize)]+struct ModelLicenseReview {+ model: String,+ file: Option<ArtifactBinding>,+}++#[derive(Debug, Serialize)]+struct CorrespondingSourceReview {+ file: Option<ArtifactBinding>,+ uri: String,+ revision: String,+}++#[derive(Debug, Serialize)]+struct InstallAuthorizationReview {+ request: &'static str,+ confirmation_required: bool,+ confirmation_received: bool,+ mutation_authorized: bool,+ mutation_performed: bool,+}++#[derive(Clone, Copy)]+enum InstallReviewRequest {+ CliInspect,+ CliInstall,+ CliUpdate,+ Mcp { confirmed: bool },+}++struct BoundedReader<R> {+ inner: R,+ remaining: u64,+}++impl<R: Read> Read for BoundedReader<R> {+ fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {+ if self.remaining == 0 {+ return Err(std::io::Error::new(+ std::io::ErrorKind::InvalidData,+ "compressed archive exceeds its byte limit",+ ));+ }+ let limit = buffer.len().min(self.remaining as usize);+ let read = self.inner.read(&mut buffer[..limit])?;+ self.remaining -= read as u64;+ Ok(read)+ }+}++struct ExtensionStore {+ root: PathBuf,+}++struct InstallLock {+ _file: fs::File,+ #[cfg(windows)]+ _windows_acl_file: fs::File,+ root: Dir,+}++#[derive(Clone, Copy, PartialEq, Eq)]+enum ActivationFailpoint {+ None,+ AfterBackup,+ LeaveInterruptedAfterBackup,+}++#[derive(Debug, PartialEq, Eq)]+struct ParsedCommand {+ subcommand: String,+ id: Option<String>,+ archive: Option<PathBuf>,+ catalog: Option<PathBuf>,+ allow_unsigned_local: bool,+ self_test: bool,+ json: bool,+}++static UNIQUE_COUNTER: AtomicU64 = AtomicU64::new(0);++fn cap_parent(path: &Path) -> Result<(Dir, &std::ffi::OsStr)> {+ let parent = path+ .parent()+ .ok_or_else(|| anyhow!("path has no parent: {}", path.display()))?;+ let name = path+ .file_name()+ .ok_or_else(|| anyhow!("path has no final component: {}", path.display()))?;+ let dir = open_directory_path_nofollow(parent)?;+ Ok((dir, name))+}++fn directory_path_anchor(path: &Path) -> Result<(Dir, Vec<std::ffi::OsString>)> {+ #[cfg(target_os = "macos")]+ let normalized;+ #[cfg(target_os = "macos")]+ let path = if let Ok(suffix) = path.strip_prefix("/var") {+ normalized = Path::new("/private/var").join(suffix);+ normalized.as_path()+ } else if let Ok(suffix) = path.strip_prefix("/tmp") {+ normalized = Path::new("/private/tmp").join(suffix);+ normalized.as_path()+ } else if let Ok(suffix) = path.strip_prefix("/etc") {+ normalized = Path::new("/private/etc").join(suffix);+ normalized.as_path()+ } else {+ path+ };+ let mut components = path.components().peekable();+ let mut anchor = PathBuf::new();+ if let Some(Component::Prefix(prefix)) = components.peek().copied() {+ anchor.push(prefix.as_os_str());+ components.next();+ }+ if matches!(components.peek(), Some(Component::RootDir)) {+ anchor.push(std::path::MAIN_SEPARATOR_STR);+ components.next();+ } else if anchor.as_os_str().is_empty() {+ anchor.push(".");+ }+ let mut names = Vec::new();+ for component in components {+ match component {+ Component::CurDir => {}+ Component::Normal(name) => names.push(name.to_owned()),+ Component::ParentDir => bail!(+ "directory path must not contain parent traversal: {}",+ path.display()+ ),+ Component::Prefix(_) | Component::RootDir => {+ bail!("directory path has an invalid root: {}", path.display())+ }+ }+ }+ let directory = Dir::open_ambient_dir(&anchor, ambient_authority())+ .with_context(|| format!("open directory anchor {}", anchor.display()))?;+ Ok((directory, names))+}++fn open_directory_path_nofollow(path: &Path) -> Result<Dir> {+ let (mut directory, names) = directory_path_anchor(path)?;+ for name in names {+ directory = directory.open_dir_nofollow(&name).with_context(|| {+ format!("open directory component {:?} in {}", name, path.display())+ })?;+ #[cfg(windows)]+ windows_reject_reparse_directory(&directory)?;+ }+ Ok(directory)+}++fn ensure_private_directory_path(path: &Path) -> Result<Dir> {+ let (mut directory, names) = directory_path_anchor(path)?;+ for name in names {+ directory = match directory.open_dir_nofollow(&name) {+ Ok(next) => next,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {+ create_private_subdirectory(&directory, &name)?;+ directory.open_dir_nofollow(&name)?+ }+ Err(error) => {+ return Err(error).with_context(|| {+ format!("open directory component {:?} in {}", name, path.display())+ })+ }+ };+ #[cfg(windows)]+ windows_reject_reparse_directory(&directory)?;+ }+ #[cfg(windows)]+ windows_secure_handle(&directory)?;+ verify_cap_directory_permissions_portable(&directory)?;+ Ok(directory)+}++fn sync_cap_dir(dir: &Dir) -> Result<()> {+ #[cfg(unix)]+ {+ let mut options = CapOpenOptions::new();+ options.read(true).follow(FollowSymlinks::No);+ dir.open_with(".", &options)?+ .sync_all()+ .context("sync containing directory")?;+ }+ Ok(())+}++pub fn run(args: &[String]) {+ if let Err(error) = run_inner(args) {+ eprintln!("cua-driver extension: {error:#}");+ std::process::exit(1);+ }+}++pub(crate) fn register_host_tools(registry: &mut ToolRegistry) {+ registry.register(Box::new(InstallExtensionTool));+}++struct InstallExtensionTool;+static INSTALL_EXTENSION_DEF: OnceLock<ToolDef> = OnceLock::new();++#[async_trait::async_trait]+impl Tool for InstallExtensionTool {+ fn def(&self) -> &ToolDef {+ INSTALL_EXTENSION_DEF.get_or_init(|| ToolDef {+ name: "install_extension".to_owned(),+ description: "Preview or install one Driver-managed optional extension. The first call without confirm returns the exact signed artifact, destination, license, source, and trust plan without mutation. Re-call with confirm=true to perform that exact verified installation.".to_owned(),+ input_schema: serde_json::json!({+ "type": "object",+ "properties": {+ "name": {"type": "string", "enum": ["perception"]},+ "confirm": {"type": "boolean", "description": "Install the previewed extension. Omit or false for a read-only plan."}+ },+ "required": ["name"],+ "additionalProperties": false+ }),+ read_only: false,+ destructive: true,+ idempotent: false,+ open_world: true,+ })+ }++ async fn invoke(&self, args: serde_json::Value) -> ToolResult {+ let confirmed = args.get("confirm").and_then(serde_json::Value::as_bool) == Some(true);+ if args.get("name").and_then(serde_json::Value::as_str) != Some("perception") {+ return ToolResult::error("install_extension requires name=\"perception\"");+ }+ match tokio::task::spawn_blocking(move || install_extension_from_mcp(confirmed)).await {+ Ok(Ok((message, structured))) => ToolResult::text(message).with_structured(structured),+ Ok(Err(error)) => ToolResult::error(format!("install_extension failed: {error:#}")),+ Err(error) => ToolResult::error(format!("install_extension task failed: {error}")),+ }+ }+}++fn install_extension_from_mcp(confirmed: bool) -> Result<(String, serde_json::Value)> {+ let catalog = std::env::var_os("CUA_DRIVER_PERCEPTION_CATALOG")+ .filter(|value| !value.is_empty())+ .map(PathBuf::from)+ .ok_or_else(|| anyhow!("CUA_DRIVER_PERCEPTION_CATALOG must name the reviewed signed catalog at daemon launch"))?;+ let entry = registry_entry("perception")?;+ let store = ExtensionStore::new(extension_root()?);+ let parsed = ParsedCommand {+ subcommand: "install".to_owned(),+ id: Some("perception".to_owned()),+ archive: None,+ catalog: Some(catalog),+ allow_unsigned_local: false,+ self_test: false,+ json: false,+ };+ let source = resolve_install_source(entry, &parsed, &store)?;+ let inspected = inspect_without_mutation(entry, &source)?;+ let mut review = install_review(+ entry,+ &store,+ &inspected,+ &source,+ InstallReviewRequest::Mcp { confirmed },+ );+ if !confirmed {+ return Ok((+ "Perception extension plan verified. Review the structured plan, then re-call install_extension with name=\"perception\" and confirm=true.".to_owned(),+ serde_json::to_value(review)?,+ ));+ }+ if store.active_path(entry.id)?.is_some() {+ bail!("perception is already installed; use the CLI extension update command with a reviewed catalog");+ }+ let installed = store.install_source(entry, &source, false)?;+ review.authorization.mutation_performed = true;+ review.mutation_performed = true;+ review.installed = true;+ review.ran = true;+ review.installed_version = Some(installed.version);+ Ok((+ "Perception extension installed from the verified plan.".to_owned(),+ serde_json::to_value(review)?,+ ))+}++fn install_review(+ entry: &RegistryEntry,+ store: &ExtensionStore,+ inspected: &InspectedArchive,+ source: &InstallSource,+ request: InstallReviewRequest,+) -> InstallReview {+ let manifest = &inspected.manifest;+ let catalog = source.catalog.as_ref();+ let license_notices = manifest+ .components+ .iter()+ .map(|component| LicenseNoticeReview {+ component: component.name.clone(),+ license: component.license.clone(),+ file: component.notice_file.clone(),+ })+ .collect::<Vec<_>>();+ let model_licenses = manifest+ .models+ .iter()+ .map(|model| ModelLicenseReview {+ model: model.path.clone(),+ file: model.license_file.clone(),+ })+ .collect::<Vec<_>>();+ let (request_name, confirmation_required, confirmation_received, mutation_authorized) =+ match request {+ InstallReviewRequest::CliInspect => ("cli-inspect", false, false, false),+ InstallReviewRequest::CliInstall => ("cli-install", false, true, true),+ InstallReviewRequest::CliUpdate => ("cli-update", false, true, true),+ InstallReviewRequest::Mcp { confirmed } => ("mcp-install", true, confirmed, confirmed),+ };+ InstallReview {+ extension: "perception",+ id: entry.id.to_owned(),+ name: entry.display_name.to_owned(),+ artifact: format!("{} {}", entry.id, manifest.version),+ backend: "icon detection and OCR",+ acceleration: "CPU",+ version: manifest.version.clone(),+ target: manifest.target.clone(),+ publisher: catalog.map(|catalog| catalog.publisher_name.clone()),+ publisher_id: catalog.map(|catalog| catalog.publisher_id.clone()),+ publisher_name: catalog.map(|catalog| catalog.publisher_name.clone()),+ publisher_key_id: catalog.map(|catalog| catalog.key_id.clone()),+ signing_key_algorithm: source+ .signed_catalog+ .as_ref()+ .map(|catalog| catalog.signature_algorithm.clone()),+ signing_key_status: if catalog.is_some() {+ "verified"+ } else {+ "unsigned-local"+ },+ publisher_signature_verified: catalog.is_some(),+ catalog_version: catalog.map(|catalog| catalog.catalog_version),+ catalog_expires_unix: catalog.map(|catalog| catalog.expires_unix),+ trust: source.trust.clone(),+ evidence_class: evidence_class(&source.trust),+ artifact_source: source.archive.display().to_string(),+ destination: store+ .versions_dir(entry.id)+ .join(&manifest.version)+ .display()+ .to_string(),+ download_size: inspected.archive_size,+ installed_size: inspected.expanded_size,+ archive_sha256: inspected.archive_sha256.clone(),+ manifest_sha256: hex_sha256(&inspected.manifest_bytes),+ license: manifest.license.clone(),+ license_notices,+ model_licenses,+ source: manifest.source.clone(),+ corresponding_source: CorrespondingSourceReview {+ file: manifest.corresponding_source_file.clone(),+ uri: manifest.corresponding_source_uri.clone(),+ revision: manifest.corresponding_source_revision.clone(),+ },+ corresponding_source_uri: manifest.corresponding_source_uri.clone(),+ corresponding_source_revision: manifest.corresponding_source_revision.clone(),+ provenance: manifest.provenance.clone(),+ files: manifest.files.clone(),+ models: manifest.models.clone(),+ components: manifest.components.clone(),+ authorization: InstallAuthorizationReview {+ request: request_name,+ confirmation_required,+ confirmation_received,+ mutation_authorized,+ mutation_performed: false,+ },+ mutation_performed: false,+ installed: false,+ ran: false,+ installed_version: None,+ }+}++fn run_inner(args: &[String]) -> Result<()> {+ let parsed = parse_command(args)?;+ let subcommand = parsed.subcommand.as_str();+ let id = parsed.id.as_deref();+ let json = parsed.json;+ let store = ExtensionStore::new(extension_root()?);++ match subcommand {+ "list" => print_infos(&store, REGISTRY, json),+ "info" => print_info(+ &store,+ registry_entry(required_id(id, "info")?)?,+ false,+ json,+ ),+ "inspect" => {+ let entry = registry_entry(required_id(id, "inspect")?)?;+ let source = resolve_install_source(entry, &parsed, &store)?;+ let inspected = inspect_without_mutation(entry, &source)?;+ print_preview(+ &install_review(+ entry,+ &store,+ &inspected,+ &source,+ InstallReviewRequest::CliInspect,+ ),+ json,+ )+ }+ "status" => match id {+ Some(id) => print_info(&store, registry_entry(id)?, parsed.self_test, json),+ None => print_infos(&store, REGISTRY, json),+ },+ "install" | "update" => {+ ensure_mutations_supported()?;+ let id = required_id(id, subcommand)?;+ let entry = registry_entry(id)?;+ let source = resolve_install_source(entry, &parsed, &store)?;+ let inspected = inspect_without_mutation(entry, &source)?;+ let request = if subcommand == "update" {+ InstallReviewRequest::CliUpdate+ } else {+ InstallReviewRequest::CliInstall+ };+ print_preview(+ &install_review(entry, &store, &inspected, &source, request),+ false,+ )?;+ let installed = store.install_source(entry, &source, subcommand == "update")?;+ println!(+ "{} {} {} at {} ({})",+ if subcommand == "update" {+ "Updated"+ } else {+ "Installed"+ },+ id,+ installed.version,+ installed.path.display(),+ trust_label(&source.trust),+ );+ Ok(())+ }+ "remove" => {+ ensure_mutations_supported()?;+ let id = required_id(id, "remove")?;+ let entry = registry_entry(id)?;+ store.remove(entry)?;+ println!("Removed {id}");+ Ok(())+ }+ "path" => {+ let id = required_id(id, "path")?;+ registry_entry(id)?;+ let path = store+ .active_path(id)?+ .ok_or_else(|| anyhow!("{id} is not installed"))?;+ println!("{}", path.display());+ Ok(())+ }+ _ => unreachable!(),+ }+}++fn parse_command(args: &[String]) -> Result<ParsedCommand> {+ let subcommand = args.first().map(String::as_str).unwrap_or("list");+ if !matches!(+ subcommand,+ "list" | "info" | "inspect" | "status" | "install" | "update" | "remove" | "path"+ ) {+ bail!("unknown subcommand {subcommand:?}; expected list, inspect, status, install, update, or remove");+ }+ let mut id = None;+ let mut archive = None;+ let mut catalog = None;+ let mut allow_unsigned_local = false;+ let mut self_test = false;+ let mut json = false;+ let mut index = usize::from(!args.is_empty());+ while index < args.len() {+ let value = &args[index];+ match value.as_str() {+ "--json" => {+ if json {+ bail!("duplicate flag --json");+ }+ json = true;+ index += 1;+ }+ "--archive" => {+ if archive.is_some() {+ bail!("duplicate option --archive");+ }+ let next = args+ .get(index + 1)+ .ok_or_else(|| anyhow!("--archive requires a value"))?;+ if next.starts_with('-') {+ bail!("--archive requires a value");+ }+ archive = Some(PathBuf::from(next));+ index += 2;+ }+ "--catalog" => {+ if catalog.is_some() {+ bail!("duplicate option --catalog");+ }+ let next = args+ .get(index + 1)+ .ok_or_else(|| anyhow!("--catalog requires a value"))?;+ if next.starts_with('-') {+ bail!("--catalog requires a value");+ }+ catalog = Some(PathBuf::from(next));+ index += 2;+ }+ "--allow-unsigned-local" => {+ if allow_unsigned_local {+ bail!("duplicate flag --allow-unsigned-local");+ }+ allow_unsigned_local = true;+ index += 1;+ }+ "--self-test" => {+ if self_test {+ bail!("duplicate flag --self-test");+ }+ self_test = true;+ index += 1;+ }+ _ if value.starts_with("--archive=") => {+ if archive.is_some() {+ bail!("duplicate option --archive");+ }+ let path = value.trim_start_matches("--archive=");+ if path.is_empty() {+ bail!("--archive requires a value");+ }+ archive = Some(PathBuf::from(path));+ index += 1;+ }+ _ if value.starts_with("--catalog=") => {+ if catalog.is_some() {+ bail!("duplicate option --catalog");+ }+ let path = value.trim_start_matches("--catalog=");+ if path.is_empty() {+ bail!("--catalog requires a value");+ }+ catalog = Some(PathBuf::from(path));+ index += 1;+ }+ _ if value.starts_with('-') => bail!("unknown extension option {value:?}"),+ _ => {+ if id.replace(value.clone()).is_some() {+ bail!("unexpected extra positional argument {value:?}");+ }+ index += 1;+ }+ }+ }+ match subcommand {+ "list" if id.is_some() => bail!("list does not accept an extension name"),+ "info" | "inspect" | "install" | "update" | "remove" | "path" if id.is_none() => {+ bail!("{subcommand} requires an extension name")+ }+ _ => {}+ }+ if !matches!(subcommand, "inspect" | "install" | "update")+ && (archive.is_some() || catalog.is_some() || allow_unsigned_local)+ {+ bail!("source options are only valid with inspect, install, or update");+ }+ if !matches!(subcommand, "list" | "info" | "inspect" | "status") && json {+ bail!("--json is not valid with {subcommand}");+ }+ if self_test && subcommand != "status" {+ bail!("--self-test is only valid with status");+ }+ if self_test && id.is_none() {+ bail!("status --self-test requires an extension name");+ }+ if allow_unsigned_local && catalog.is_some() {+ bail!("--allow-unsigned-local cannot be combined with --catalog");+ }+ Ok(ParsedCommand {+ subcommand: subcommand.to_owned(),+ id,+ archive,+ catalog,+ allow_unsigned_local,+ self_test,+ json,+ })+}++fn ensure_mutations_supported() -> Result<()> {+ Ok(())+}++fn required_id<'a>(id: Option<&'a str>, command: &str) -> Result<&'a str> {+ id.ok_or_else(|| anyhow!("usage: cua-driver extension {command} <name>"))+}++fn registry_entry(id: &str) -> Result<&'static RegistryEntry> {+ let id = match id {+ "perception" => PERCEPTION_ID,+ other => other,+ };+ REGISTRY+ .iter()+ .find(|entry| entry.id == id)+ .ok_or_else(|| anyhow!("unknown extension {id:?}; run `cua-driver extension list`"))+}++fn extension_root() -> Result<PathBuf> {+ if let Some(home) = std::env::var_os("CUA_DRIVER_RS_HOME").filter(|value| !value.is_empty()) {+ return Ok(PathBuf::from(home).join("extensions"));+ }+ #[cfg(windows)]+ let home = std::env::var_os("USERPROFILE").ok_or_else(|| anyhow!("USERPROFILE not set"))?;+ #[cfg(not(windows))]+ let home = std::env::var_os("HOME").ok_or_else(|| anyhow!("HOME not set"))?;+ Ok(PathBuf::from(home)+ .join(crate::bundle::user_home_subdirectory())+ .join("extensions"))+}++/// Resolve the optional perception worker through the same active-pointer and+/// installed-payload verification used by extension lifecycle commands.+pub(crate) fn perception_client() -> PerceptionClient {+ match perception_worker_config() {+ Ok(Some(config)) => PerceptionClient::new(config).unwrap_or_else(|error| {+ tracing::warn!("installed cua-perception configuration is unusable: {error:?}");+ PerceptionClient::unavailable()+ }),+ Ok(None) => PerceptionClient::unavailable(),+ Err(error) => {+ tracing::warn!("installed cua-perception extension is unavailable: {error:#}");+ PerceptionClient::unavailable()+ }+ }+}++pub(crate) fn perception_client_for_cli() -> Result<PerceptionClient> {+ match perception_worker_config()? {+ Some(config) => PerceptionClient::new(config).map_err(|error| {+ anyhow!(serde_json::to_string(&error).unwrap_or_else(|_| error.message.clone()))+ }),+ None => Ok(PerceptionClient::unavailable()),+ }+}++fn perception_worker_config() -> Result<Option<PerceptionWorkerConfig>> {+ perception_worker_config_in(&ExtensionStore::new(extension_root()?))+}++fn perception_worker_config_in(store: &ExtensionStore) -> Result<Option<PerceptionWorkerConfig>> {+ if !store.root.exists() {+ return Ok(None);+ }+ let Some((active, manifest)) = store.active_path_for_startup(PERCEPTION_ID)? else {+ return Ok(None);+ };++ let contract_path = resolve_owned_file(&active, &manifest, PERCEPTION_RUNTIME_CONTRACT)?;+ let contract: PerceptionRuntimeContract =+ serde_json::from_slice(&read_small_local_file(&contract_path)?)+ .context("parse perception runtime contract")?;+ validate_runtime_contract(&manifest, &contract)?;++ let executable = resolve_owned_file(&active, &manifest, &manifest.entrypoint)?;+ let model_manifest_relative = unique_model_manifest_path(&manifest)?;+ let model_manifest = resolve_owned_file(&active, &manifest, model_manifest_relative)?;+ let runtime_relative = format!("runtime/{}", contract.runtime.name);+ let runtime_library = resolve_owned_file(&active, &manifest, &runtime_relative)?;+ let model_manifest = model_manifest+ .to_str()+ .ok_or_else(|| anyhow!("perception model manifest path is not valid UTF-8"))?;+ let runtime_library = runtime_library+ .to_str()+ .ok_or_else(|| anyhow!("perception runtime library path is not valid UTF-8"))?;++ let mut config = PerceptionWorkerConfig::installed_with_identity(+ executable,+ manifest.id.clone(),+ manifest.version.clone(),+ );+ #[cfg(windows)]+ {+ config = config.with_windows_acl_lease_path(store.windows_acl_lease_path(PERCEPTION_ID));+ }+ config.args = vec![+ "--manifest".to_owned(),+ model_manifest.to_owned(),+ "--onnx-runtime-library".to_owned(),+ runtime_library.to_owned(),+ "--extension-id".to_owned(),+ manifest.id.clone(),+ "--extension-version".to_owned(),+ manifest.version.clone(),+ ];+ Ok(Some(config))+}++fn validate_runtime_contract(+ manifest: &ExtensionManifest,+ contract: &PerceptionRuntimeContract,+) -> Result<()> {+ let _ = &contract.schema;+ if contract.schema_version != 1+ || contract.target != manifest.target+ || contract.protocol_version != manifest.protocol_version+ || !contract.reject_mismatch+ {+ bail!("perception runtime contract does not match the active extension");+ }+ let worker_name = Path::new(&manifest.entrypoint)+ .file_name()+ .and_then(|name| name.to_str())+ .ok_or_else(|| anyhow!("perception entrypoint has no portable file name"))?;+ if contract.worker.name != worker_name {+ bail!("perception runtime contract names a different worker");+ }+ if contract.runtime.name.is_empty()+ || Path::new(&contract.runtime.name)+ .file_name()+ .and_then(|name| name.to_str())+ != Some(contract.runtime.name.as_str())+ {+ bail!("perception runtime contract contains an unsafe runtime name");+ }+ validate_runtime_binding(manifest, &manifest.entrypoint, &contract.worker)?;+ validate_runtime_binding(+ manifest,+ &format!("runtime/{}", contract.runtime.name),+ &contract.runtime,+ )?;+ let model_manifest_path = unique_model_manifest_path(manifest)?;+ let model_manifest_name = Path::new(model_manifest_path)+ .file_name()+ .and_then(|name| name.to_str())+ .ok_or_else(|| anyhow!("perception model manifest has no portable file name"))?;+ if contract.model_manifest.name != model_manifest_name {+ bail!("perception runtime contract names a different model manifest");+ }+ validate_runtime_binding(manifest, model_manifest_path, &contract.model_manifest)?;+ for model in &contract.models {+ validate_runtime_binding(manifest, &format!("models/{}", model.name), model)?;+ }+ validate_runtime_binding(+ manifest,+ &format!("models/{}", contract.dictionary.name),+ &contract.dictionary,+ )?;+ let entrypoint = manifest+ .files+ .iter()+ .find(|file| file.path == manifest.entrypoint)+ .ok_or_else(|| anyhow!("perception entrypoint is not extension-owned"))?;+ if !entrypoint.executable {+ bail!("perception entrypoint is not marked executable");+ }+ Ok(())+}++fn validate_runtime_binding(+ manifest: &ExtensionManifest,+ relative: &str,+ binding: &RuntimeBinding,+) -> Result<()> {+ safe_manifest_path(relative)?;+ validate_sha256("perception runtime binding", &binding.sha256)?;+ if binding.role.as_deref().is_some_and(str::is_empty) {+ bail!("perception runtime binding has an empty role");+ }+ let owned = manifest+ .files+ .iter()+ .find(|file| file.path == relative)+ .ok_or_else(|| anyhow!("perception runtime binding is not extension-owned: {relative}"))?;+ if owned.sha256 != binding.sha256 {+ bail!("perception runtime binding hash differs from the extension manifest");+ }+ Ok(())+}++fn unique_model_manifest_path(manifest: &ExtensionManifest) -> Result<&str> {+ let mut candidates = manifest.files.iter().filter(|file| {+ Path::new(&file.path)+ .file_name()+ .and_then(|name| name.to_str())+ == Some(PERCEPTION_MODEL_MANIFEST_NAME)+ });+ let candidate = candidates+ .next()+ .ok_or_else(|| anyhow!("installed perception extension has no model manifest"))?;+ if candidates.next().is_some() {+ bail!("installed perception extension has ambiguous model manifests");+ }+ Ok(&candidate.path)+}++fn resolve_owned_file(+ active: &Path,+ manifest: &ExtensionManifest,+ relative: &str,+) -> Result<PathBuf> {+ safe_manifest_path(relative)?;+ if !manifest.files.iter().any(|file| file.path == relative) {+ bail!("perception runtime path is not extension-owned: {relative}");+ }+ let path = active.join(relative);+ let metadata = fs::symlink_metadata(&path)+ .with_context(|| format!("inspect installed perception file {relative}"))?;+ if metadata.file_type().is_symlink() || !metadata.is_file() {+ bail!("installed perception path is not a regular non-symlink file: {relative}");+ }+ let canonical_root = fs::canonicalize(active).context("resolve active perception directory")?;+ let canonical_path = fs::canonicalize(&path)+ .with_context(|| format!("resolve installed perception file {relative}"))?;+ if !canonical_path.starts_with(&canonical_root) {+ bail!("installed perception path escapes the active extension: {relative}");+ }+ Ok(canonical_path)+}++fn print_infos(store: &ExtensionStore, entries: &[RegistryEntry], json: bool) -> Result<()> {+ let infos = entries+ .iter()+ .map(|entry| store.info(entry, false))+ .collect::<Result<Vec<_>>>()?;+ if json {+ println!("{}", serde_json::to_string_pretty(&infos)?);+ } else {+ for info in infos {+ let version = info.active_version.as_deref().unwrap_or("not installed");+ println!("{}\t{}\t{}", info.id, version, info.detail);+ }+ }+ Ok(())+}++fn print_info(+ store: &ExtensionStore,+ entry: &RegistryEntry,+ self_test: bool,+ json: bool,+) -> Result<()> {+ let info = store.info(entry, self_test)?;+ if json {+ println!("{}", serde_json::to_string_pretty(&info)?);+ } else {+ println!("{} ({})", info.display_name, info.id);+ println!("{}", info.description);+ println!("Protocol: {}", info.protocol_version);+ println!("Status: {}", info.detail);+ if let Some(version) = info.active_version {+ println!("Active version: {version}");+ }+ }+ Ok(())+}++fn trust_label(trust: &TrustClass) -> &'static str {+ match trust {+ TrustClass::PublisherVerified => "publisher-verified",+ #[cfg(feature = "review-trust-root")]+ TrustClass::ReviewOnlyPublisherVerified => "review-only-publisher-verified",+ TrustClass::DeveloperUnsignedLocal => "developer-unsigned-local",+ }+}++fn evidence_class(trust: &TrustClass) -> &'static str {+ match trust {+ TrustClass::PublisherVerified => "production-publisher-verified",+ #[cfg(feature = "review-trust-root")]+ TrustClass::ReviewOnlyPublisherVerified => "review-only-not-release-evidence",+ TrustClass::DeveloperUnsignedLocal => "developer-local-not-publisher-evidence",+ }+}++fn expected_publisher_id() -> &'static str {+ #[cfg(feature = "review-trust-root")]+ {+ REVIEW_PUBLISHER_ID+ }+ #[cfg(not(feature = "review-trust-root"))]+ {+ VERIFIED_PUBLISHER_ID+ }+}++fn expected_publisher_name() -> &'static str {+ #[cfg(feature = "review-trust-root")]+ {+ REVIEW_PUBLISHER_NAME+ }+ #[cfg(not(feature = "review-trust-root"))]+ {+ VERIFIED_PUBLISHER_NAME+ }+}++fn verified_trust_class() -> TrustClass {+ #[cfg(feature = "review-trust-root")]+ {+ TrustClass::ReviewOnlyPublisherVerified+ }+ #[cfg(not(feature = "review-trust-root"))]+ {+ TrustClass::PublisherVerified+ }+}++fn resolve_install_source(+ entry: &RegistryEntry,+ parsed: &ParsedCommand,+ store: &ExtensionStore,+) -> Result<InstallSource> {+ if parsed.allow_unsigned_local {+ let archive = parsed.archive.clone().ok_or_else(|| {+ anyhow!("developer mode requires --archive <path> with --allow-unsigned-local")+ })?;+ return Ok(InstallSource {+ archive,+ trust: TrustClass::DeveloperUnsignedLocal,+ catalog: None,+ signed_catalog: None,+ trust_update: None,+ });+ }+ if parsed.archive.is_some() {+ bail!("unsigned archives require the explicit developer-only --allow-unsigned-local flag");+ }+ let catalog_path = parsed+ .catalog+ .as_deref()+ .ok_or_else(|| anyhow!("verified installs require --catalog <signed-catalog.json>"))?;+ let bytes = read_small_local_file(catalog_path)?;+ let signed: SignedCatalog =+ serde_json::from_slice(&bytes).context("parse signed extension catalog")?;+ let trust = store.load_publisher_trust()?;+ let trust_update = verify_catalog_at(entry, &signed, &trust, unix_now()?)?;+ let archive_rel = safe_relative_path(Path::new(&signed.payload.archive))?;+ if archive_rel.as_os_str().is_empty() || archive_rel != Path::new(&signed.payload.archive) {+ bail!("catalog archive path must be canonical and relative");+ }+ let archive = catalog_path+ .parent()+ .unwrap_or_else(|| Path::new("."))+ .join(archive_rel);+ Ok(InstallSource {+ archive,+ trust: verified_trust_class(),+ catalog: Some(signed.payload.clone()),+ signed_catalog: Some(signed),+ trust_update: Some(trust_update),+ })+}++fn verify_catalog_at(+ entry: &RegistryEntry,+ signed: &SignedCatalog,+ trust: &PublisherTrust,+ now: u64,+) -> Result<PublisherTrust> {+ validate_publisher_trust(trust)?;+ let payload = &signed.payload;+ if signed.signature_algorithm != "ed25519" {+ bail!("unsupported catalog signature algorithm");+ }+ if payload.schema_version != CATALOG_SCHEMA_VERSION {+ bail!("unsupported catalog schema {}", payload.schema_version);+ }+ if payload.catalog_version == 0 {+ bail!("catalog version must be greater than zero");+ }+ validate_catalog_freshness_at(payload, now)?;+ if payload.publisher_id != expected_publisher_id()+ || payload.publisher_name != expected_publisher_name()+ || trust.publisher_id != expected_publisher_id()+ {+ bail!("catalog publisher identity is not trusted");+ }+ if payload.catalog_version <= trust.highest_catalog_version {+ bail!(+ "catalog anti-rollback version {} must be newer than trusted version {}",+ payload.catalog_version,+ trust.highest_catalog_version+ );+ }+ if payload.extension_id != entry.id {+ bail!("catalog extension id does not match requested extension");+ }+ if payload.target != current_target()? {+ bail!("catalog target does not match the current target");+ }+ validate_sha256("archive", &payload.archive_sha256)?;+ validate_sha256("manifest", &payload.manifest_sha256)?;+ if payload.archive_size > MAX_ARCHIVE_BYTES {+ bail!("catalog archive size exceeds the supported limit");+ }+ Version::parse(&payload.version).context("catalog version is not semantic versioning")?;+ for (name, value) in [+ ("license", payload.license.as_str()),+ ("source", payload.source.as_str()),+ (+ "corresponding_source_uri",+ payload.corresponding_source_uri.as_str(),+ ),+ (+ "corresponding_source_revision",+ payload.corresponding_source_revision.as_str(),+ ),+ ("provenance", payload.provenance.as_str()),+ ] {+ if value.trim().is_empty() {+ bail!("catalog {name} must not be empty");+ }+ }+ let (signing_key, promote_pending) = if payload.key_id == trust.current_key.key_id {+ (&trust.current_key, false)+ } else if trust+ .pending_key+ .as_ref()+ .is_some_and(|key| key.key_id == payload.key_id)+ {+ (+ trust.pending_key.as_ref().expect("checked pending key"),+ true,+ )+ } else {+ bail!("catalog signing key is unknown or has been retired");+ };+ validate_publisher_key(signing_key)?;+ if now < signing_key.valid_from_unix {+ bail!("catalog signing key is not valid yet");+ }+ if now >= signing_key.valid_until_unix {+ bail!("catalog signing key has expired");+ }+ let public_key = decode_publisher_key(signing_key)?;+ let message = serde_json::to_vec(payload)?;+ verify_ed25519_signature(&public_key, &message, &signed.signature)?;++ let mut updated = trust.clone();+ if promote_pending {+ updated.current_key = signing_key.clone();+ updated.pending_key = None;+ updated.generation = updated+ .generation+ .checked_add(1)+ .ok_or_else(|| anyhow!("publisher key generation overflow"))?;+ }+ if let Some(next) = &payload.next_key {+ validate_publisher_key(next)?;+ if next.key_id == updated.current_key.key_id {+ bail!("next publisher key must differ from the current key");+ }+ if next.valid_from_unix <= updated.current_key.valid_from_unix+ || next.valid_from_unix >= next.valid_until_unix+ || next.valid_from_unix >= updated.current_key.valid_until_unix+ {+ bail!("next publisher key has an invalid rotation window");+ }+ match &updated.pending_key {+ Some(existing) if existing != next => {+ bail!("catalog attempts to replace a pending publisher key")+ }+ _ => updated.pending_key = Some(next.clone()),+ }+ }+ updated.highest_catalog_version = payload.catalog_version;+ Ok(updated)+}++fn initial_publisher_trust() -> PublisherTrust {+ #[cfg(feature = "review-trust-root")]+ let (key_id, public_key_base64, valid_from_unix, valid_until_unix) = (+ REVIEW_KEY_ID,+ REVIEW_PUBLIC_KEY_BASE64.to_owned(),+ 1,+ u64::MAX,+ );+ #[cfg(not(feature = "review-trust-root"))]+ let (key_id, public_key_base64, valid_from_unix, valid_until_unix) = (+ VERIFIED_KEY_ID,+ BASE64.encode(VERIFIED_PUBLIC_KEY),+ VERIFIED_KEY_VALID_FROM_UNIX,+ VERIFIED_KEY_VALID_UNTIL_UNIX,+ );+ PublisherTrust {+ schema_version: 1,+ publisher_id: expected_publisher_id().to_owned(),+ generation: 1,+ highest_catalog_version: 0,+ current_key: PublisherKey {+ key_id: key_id.to_owned(),+ public_key_base64,+ valid_from_unix,+ valid_until_unix,+ },+ pending_key: None,+ }+}++fn load_publisher_trust_at(root: &Dir) -> Result<PublisherTrust> {+ let active = private_regular_file_or_missing_at(root, TRUST_NAME)?;+ let backup = private_regular_file_or_missing_at(root, TRUST_BACKUP_NAME)?;+ if !active && backup {+ bail!("publisher trust update is interrupted; run an extension mutation to recover it");+ }+ if !active {+ return Ok(initial_publisher_trust());+ }+ let trust: PublisherTrust =+ serde_json::from_slice(&read_small_file_at(root, Path::new(TRUST_NAME))?)+ .context("parse publisher trust state")?;+ validate_publisher_trust(&trust)?;+ Ok(trust)+}++fn validate_publisher_trust(trust: &PublisherTrust) -> Result<()> {+ if trust.schema_version != 1+ || trust.publisher_id != expected_publisher_id()+ || trust.generation == 0+ {+ bail!("publisher trust state is invalid");+ }+ validate_publisher_key(&trust.current_key)?;+ if let Some(pending) = &trust.pending_key {+ validate_publisher_key(pending)?;+ if pending.key_id == trust.current_key.key_id+ || pending.valid_from_unix <= trust.current_key.valid_from_unix+ || pending.valid_from_unix >= trust.current_key.valid_until_unix+ {+ bail!("publisher trust rotation state is invalid");+ }+ }+ Ok(())+}++fn validate_publisher_key(key: &PublisherKey) -> Result<()> {+ if key.key_id.is_empty()+ || key.key_id.len() > 128+ || !key+ .key_id+ .bytes()+ .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'))+ || key.valid_from_unix >= key.valid_until_unix+ {+ bail!("publisher key metadata is invalid");+ }+ decode_publisher_key(key).map(|_| ())+}++fn decode_publisher_key(key: &PublisherKey) -> Result<[u8; 32]> {+ let bytes = BASE64+ .decode(&key.public_key_base64)+ .context("publisher key is not valid base64")?;+ bytes+ .try_into()+ .map_err(|_| anyhow!("publisher Ed25519 key must be 32 bytes"))+}++fn verify_ed25519_signature(public_key: &[u8], message: &[u8], signature: &str) -> Result<()> {+ let signature = BASE64+ .decode(signature)+ .context("catalog signature is not valid base64")?;+ ring::signature::UnparsedPublicKey::new(&ring::signature::ED25519, public_key)+ .verify(message, &signature)+ .map_err(|_| anyhow!("catalog signature verification failed"))+}++fn validate_catalog_freshness(payload: &CatalogPayload) -> Result<()> {+ validate_catalog_freshness_at(payload, unix_now()?)+}++fn unix_now() -> Result<u64> {+ Ok(std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .context("system clock precedes the Unix epoch")?+ .as_secs())+}++fn validate_catalog_freshness_at(payload: &CatalogPayload, now: u64) -> Result<()> {+ if payload.expires_unix <= now {+ bail!("signed extension catalog has expired");+ }+ Ok(())+}++fn inspect_without_mutation(+ entry: &RegistryEntry,+ source: &InstallSource,+) -> Result<InspectedArchive> {+ let temp_root = std::env::temp_dir().join(unique_name("cua-extension-inspect"));+ let parent = open_directory_path_nofollow(+ temp_root+ .parent()+ .ok_or_else(|| anyhow!("inspection path has no parent"))?,+ )?;+ let name = temp_root+ .file_name()+ .ok_or_else(|| anyhow!("inspection path has no name"))?;+ create_private_subdirectory(&parent, name)?;+ let staging = parent.open_dir_nofollow(name)?;+ let result = inspect_archive(&source.archive, entry, &staging);+ drop(staging);+ let cleanup = remove_cap_subdirectory(&parent, name);+ let inspected = match (result, cleanup) {+ (Ok(inspected), Ok(())) => inspected,+ (Err(error), _) => return Err(error),+ (Ok(_), Err(error)) => return Err(error),+ };+ validate_source_metadata(&inspected, source)?;+ Ok(inspected)+}++fn validate_source_metadata(inspected: &InspectedArchive, source: &InstallSource) -> Result<()> {+ if let Some(catalog) = &source.catalog {+ validate_catalog_freshness(catalog)?;+ let manifest = &inspected.manifest;+ if inspected.archive_size != catalog.archive_size+ || inspected.archive_sha256 != catalog.archive_sha256+ || hex_sha256(&inspected.manifest_bytes) != catalog.manifest_sha256+ || manifest.version != catalog.version+ || manifest.license != catalog.license+ || manifest.source != catalog.source+ || manifest.corresponding_source_uri != catalog.corresponding_source_uri+ || manifest.corresponding_source_revision != catalog.corresponding_source_revision+ || manifest.provenance != catalog.provenance+ {+ bail!("manifest identity or provenance does not exactly match signed catalog");+ }+ if manifest.components.is_empty()+ || manifest.models.is_empty()+ || manifest.corresponding_source_file.is_none()+ || manifest+ .components+ .iter()+ .any(|component| component.notice_file.is_none())+ || manifest+ .models+ .iter()+ .any(|model| model.license_file.is_none())+ {+ bail!("verified perception extensions require digest-bound notice, corresponding-source, and model-license files");+ }+ }+ Ok(())+}++fn print_preview(preview: &InstallReview, json: bool) -> Result<()> {+ if json {+ println!("{}", serde_json::to_string_pretty(&preview)?);+ } else {+ println!("Extension: {} {}", preview.id, preview.version);+ println!("Name: {}", preview.name);+ println!("Trust: {}", trust_label(&preview.trust));+ println!("Evidence class: {}", preview.evidence_class);+ #[cfg(feature = "review-trust-root")]+ if preview.trust == TrustClass::ReviewOnlyPublisherVerified {+ println!("{REVIEW_TRUST_NOTICE}");+ }+ if let (Some(publisher), Some(key), Some(catalog), Some(expires)) = (+ &preview.publisher_name,+ &preview.publisher_key_id,+ preview.catalog_version,+ preview.catalog_expires_unix,+ ) {+ println!(+ "Publisher signature: verified {} with key {} (catalog {}, expires {})",+ publisher, key, catalog, expires+ );+ }+ println!("Signing key status: {}", preview.signing_key_status);+ if let Some(publisher_id) = &preview.publisher_id {+ println!("Publisher ID: {publisher_id}");+ }+ if let Some(algorithm) = &preview.signing_key_algorithm {+ println!("Signing key algorithm: {algorithm}");+ }+ println!("Artifact source: {}", preview.artifact_source);+ println!("Destination: {}", preview.destination);+ println!("Download size: {} bytes", preview.download_size);+ println!("Installed size: {} bytes", preview.installed_size);+ println!("License: {}", preview.license);+ println!("Source: {}", preview.source);+ println!(+ "Corresponding source: {} @ {}",+ preview.corresponding_source_uri, preview.corresponding_source_revision+ );+ if let Some(file) = &preview.corresponding_source.file {+ println!(+ "Corresponding source file: {} | SHA-256 {}",+ file.path, file.sha256+ );+ }+ println!("Provenance: {}", preview.provenance);+ for component in &preview.components {+ println!(+ "Component: {} {} | {} | {} @ {} | notice: {}",+ component.name,+ component.version,+ component.license,+ component.source_uri,+ component.source_revision,+ component.notice+ );+ if let Some(file) = &component.notice_file {+ println!(+ "Component notice file: {} | SHA-256 {}",+ file.path, file.sha256+ );+ }+ }+ for model in &preview.models {+ println!(+ "Model: {} @ {} | original {} | conversion {}",+ model.path, model.revision, model.original_sha256, model.conversion_sha256+ );+ if let Some(file) = &model.license_file {+ println!(+ "Model license file: {} | SHA-256 {}",+ file.path, file.sha256+ );+ }+ }+ println!("Target: {}", preview.target);+ println!("Archive SHA-256: {}", preview.archive_sha256);+ println!("Manifest SHA-256: {}", preview.manifest_sha256);+ println!(+ "Authorization: request={}, confirmation_required={}, confirmation_received={}, mutation_authorized={}",+ preview.authorization.request,+ preview.authorization.confirmation_required,+ preview.authorization.confirmation_received,+ preview.authorization.mutation_authorized,+ );+ println!("Preview complete; no extension state was changed.");+ }+ Ok(())+}++#[derive(Debug)]+struct InstalledVersion {+ version: String,+ path: PathBuf,+}++impl ExtensionStore {+ fn new(root: PathBuf) -> Self {+ Self { root }+ }++ fn extension_dir(&self, id: &str) -> PathBuf {+ self.root.join(id)+ }++ fn versions_dir(&self, id: &str) -> PathBuf {+ self.extension_dir(id).join("versions")+ }++ fn load_publisher_trust(&self) -> Result<PublisherTrust> {+ if !self.root.exists() {+ return Ok(initial_publisher_trust());+ }+ let root = open_directory_path_nofollow(&self.root)?;+ verify_cap_directory_permissions_portable(&root)?;+ let active = private_regular_file_or_missing_at(&root, TRUST_NAME)?;+ let backup = private_regular_file_or_missing_at(&root, TRUST_BACKUP_NAME)?;+ if !active && backup {+ bail!("publisher trust update is interrupted; run an extension mutation to recover it");+ }+ if !active {+ return Ok(initial_publisher_trust());+ }+ load_publisher_trust_at(&root)+ }++ fn recover_publisher_trust_locked(&self, root: &Dir) -> Result<()> {+ let active = private_regular_file_or_missing_at(root, TRUST_NAME)?;+ let backup = private_regular_file_or_missing_at(root, TRUST_BACKUP_NAME)?;+ if !active && backup {+ root.rename(TRUST_BACKUP_NAME, root, TRUST_NAME)+ .context("restore interrupted publisher trust state")?;+ } else if active && backup {+ root.remove_file(TRUST_BACKUP_NAME)+ .context("remove stale publisher trust backup")?;+ }+ if private_regular_file_or_missing_at(root, TRUST_NEW_NAME)? {+ root.remove_file(TRUST_NEW_NAME)+ .context("remove stale publisher trust candidate")?;+ }+ sync_cap_dir(root)+ }++ fn commit_publisher_trust_locked(&self, root: &Dir, trust: &PublisherTrust) -> Result<()> {+ validate_publisher_trust(trust)?;+ self.recover_publisher_trust_locked(root)?;+ write_new_file_at(root, TRUST_NEW_NAME, &serde_json::to_vec_pretty(trust)?)?;+ let had_active = private_regular_file_or_missing_at(root, TRUST_NAME)?;+ if had_active {+ root.rename(TRUST_NAME, root, TRUST_BACKUP_NAME)+ .context("back up publisher trust state")?;+ }+ if let Err(error) = root.rename(TRUST_NEW_NAME, root, TRUST_NAME) {+ let _ = root.remove_file(TRUST_NEW_NAME);+ if had_active {+ root.rename(TRUST_BACKUP_NAME, root, TRUST_NAME)+ .context("restore publisher trust state")?;+ }+ return Err(error).context("activate publisher trust state");+ }+ if had_active {+ root.remove_file(TRUST_BACKUP_NAME)?;+ }+ sync_cap_dir(root)+ }++ fn recover_activation_locked(&self, root: &Dir, id: &str) -> Result<()> {+ let Some(extension) = open_private_subdirectory_if_present(root, id)? else {+ return Ok(());+ };+ let mut has_active = private_regular_file_or_missing_at(&extension, ACTIVE_NAME)?;+ let mut has_backup = private_regular_file_or_missing_at(&extension, ACTIVE_BACKUP_NAME)?;+ let has_new = private_regular_file_or_missing_at(&extension, ACTIVE_NEW_NAME)?;+ if has_active {+ self.validate_pointer_target_locked(id, &extension, ACTIVE_NAME)?;+ }+ if has_backup {+ self.validate_pointer_target_locked(id, &extension, ACTIVE_BACKUP_NAME)?;+ }+ if !has_active && has_backup {+ extension+ .rename(ACTIVE_BACKUP_NAME, &extension, ACTIVE_NAME)+ .with_context(|| format!("restore interrupted activation for {id}"))?;+ sync_cap_dir(&extension)?;+ has_active = true;+ has_backup = false;+ }+ if has_active && has_backup {+ extension+ .remove_file(ACTIVE_BACKUP_NAME)+ .with_context(|| format!("remove stale activation backup for {id}"))?;+ sync_cap_dir(&extension)?;+ }+ if has_new {+ extension+ .remove_file(ACTIVE_NEW_NAME)+ .with_context(|| format!("remove stale activation candidate for {id}"))?;+ sync_cap_dir(&extension)?;+ }+ Ok(())+ }++ fn recover_activation_for_startup_locked(&self, root: &Dir, id: &str) -> Result<()> {+ let Some(extension) = open_private_subdirectory_if_present(root, id)? else {+ return Ok(());+ };+ let mut has_active = private_regular_file_or_missing_at(&extension, ACTIVE_NAME)?;+ let mut has_backup = private_regular_file_or_missing_at(&extension, ACTIVE_BACKUP_NAME)?;+ let has_new = private_regular_file_or_missing_at(&extension, ACTIVE_NEW_NAME)?;+ if !has_backup && !has_new {+ return Ok(());+ }+ if has_active {+ self.validate_pointer_target_for_startup_locked(id, &extension, ACTIVE_NAME)?;+ }+ if has_backup {+ self.validate_pointer_target_for_startup_locked(id, &extension, ACTIVE_BACKUP_NAME)?;+ }+ if !has_active && has_backup {+ extension+ .rename(ACTIVE_BACKUP_NAME, &extension, ACTIVE_NAME)+ .with_context(|| format!("restore interrupted activation for {id}"))?;+ sync_cap_dir(&extension)?;+ has_active = true;+ has_backup = false;+ }+ if has_active && has_backup {+ extension+ .remove_file(ACTIVE_BACKUP_NAME)+ .with_context(|| format!("remove stale activation backup for {id}"))?;+ sync_cap_dir(&extension)?;+ }+ if has_new {+ extension+ .remove_file(ACTIVE_NEW_NAME)+ .with_context(|| format!("remove stale activation candidate for {id}"))?;+ sync_cap_dir(&extension)?;+ }+ Ok(())+ }++ fn recover_publisher_trust_from_active_locked(&self, root: &Dir, id: &str) -> Result<()> {+ let Some(pointer) = self.active_pointer_locked(root, id)? else {+ return Ok(());+ };+ let extension = root.open_dir_nofollow(id)?;+ let version = extension+ .open_dir_nofollow("versions")?+ .open_dir_nofollow(&pointer.version)?;+ let manifest = verify_installed_version_at(&version, registry_entry(id)?, None)?;+ self.recover_publisher_trust_from_verified_active_locked(root, id, &version, &manifest)+ }++ fn recover_publisher_trust_from_verified_active_locked(+ &self,+ root: &Dir,+ id: &str,+ version: &Dir,+ manifest: &ExtensionManifest,+ ) -> Result<()> {+ let record = read_install_record_at(&version, id, &manifest.version)?;+ let Some(candidate) = record.publisher_trust else {+ return Ok(());+ };+ if Some(candidate.highest_catalog_version) != record.catalog_version {+ bail!("installed publisher trust does not match its catalog version");+ }+ let current = load_publisher_trust_at(root)?;+ if candidate.highest_catalog_version > current.highest_catalog_version {+ self.commit_publisher_trust_locked(root, &candidate)?;+ } else if candidate.highest_catalog_version == current.highest_catalog_version+ && candidate != current+ {+ bail!("installed publisher trust conflicts with durable trust state");+ }+ Ok(())+ }++ fn validate_pointer_target_locked(+ &self,+ id: &str,+ extension: &Dir,+ pointer_name: &str,+ ) -> Result<()> {+ let bytes = read_small_file_at(extension, Path::new(pointer_name))?;+ let pointer: ActivePointer = serde_json::from_slice(&bytes)+ .with_context(|| format!("parse activation pointer {pointer_name}"))?;+ if pointer.id != id {+ bail!("activation pointer for {id} names extension {}", pointer.id);+ }+ validate_version_segment(&pointer.version)?;+ let versions = extension+ .open_dir_nofollow("versions")+ .context("active extension has no owned versions directory")?;+ verify_cap_directory_permissions_portable(&versions)?;+ let version = versions+ .open_dir_nofollow(&pointer.version)+ .with_context(|| {+ format!(+ "active extension version {} is not an owned directory",+ pointer.version+ )+ })?;+ verify_cap_directory_permissions_portable(&version)?;+ verify_installed_version_at(&version, registry_entry(id)?, None)?;+ Ok(())+ }++ fn validate_pointer_target_for_startup_locked(+ &self,+ id: &str,+ extension: &Dir,+ pointer_name: &str,+ ) -> Result<()> {+ let bytes = read_small_file_at(extension, Path::new(pointer_name))?;+ let pointer: ActivePointer = serde_json::from_slice(&bytes)+ .with_context(|| format!("parse activation pointer {pointer_name}"))?;+ if pointer.id != id {+ bail!("activation pointer for {id} names extension {}", pointer.id);+ }+ validate_version_segment(&pointer.version)?;+ let versions = extension+ .open_dir_nofollow("versions")+ .context("active extension has no owned versions directory")?;+ verify_cap_directory_permissions_portable(&versions)?;+ let version = versions+ .open_dir_nofollow(&pointer.version)+ .with_context(|| {+ format!(+ "active extension version {} is not an owned directory",+ pointer.version+ )+ })?;+ #[cfg(not(windows))]+ verify_cap_directory_permissions_portable(&version)?;+ verify_installed_version_for_startup(&version, registry_entry(id)?)?;+ Ok(())+ }++ fn lock(&self, id: &str) -> Result<InstallLock> {+ let root = ensure_private_directory_path(&self.root)?;+ let lock_dir = ensure_private_subdirectory(&root, ".locks")?;+ let lock_name = format!("{id}.lock");+ let file = open_lock_file_at(&lock_dir, &lock_name)?;+ let started = Instant::now();+ acquire_extension_lock_with(+ EXTENSION_LOCK_RETRY_WINDOW,+ || started.elapsed(),+ std::thread::sleep,+ || file.try_lock_exclusive(),+ )+ .with_context(|| format!("extension {id} is already being modified"))?;+ #[cfg(windows)]+ let windows_acl_file = {+ let acl_name = windows_acl_lease_name(id);+ let acl_file = open_lock_file_at(&lock_dir, &acl_name)?;+ acquire_windows_acl_lease_and_recover_with(+ || {+ acquire_windows_acl_lease(&acl_file)+ .with_context(|| format!("wait for extension {id} Windows ACL lease"))+ },+ || {+ recover_windows_acl_profile_journal(&windows_acl_profile_journal_path(+ &self.windows_acl_lease_path(id),+ ))+ .map_err(|failure| anyhow!(failure.message))+ .with_context(|| format!("recover extension {id} Windows ACL authority"))+ },+ )?;+ acl_file+ };+ Ok(InstallLock {+ _file: file,+ #[cfg(windows)]+ _windows_acl_file: windows_acl_file,+ root,+ })+ }++ #[cfg(windows)]+ fn windows_acl_lease_path(&self, id: &str) -> PathBuf {+ self.root.join(".locks").join(windows_acl_lease_name(id))+ }++ fn acl_profile_journal_path(&self, id: &str) -> Option<PathBuf> {+ #[cfg(windows)]+ {+ Some(windows_acl_profile_journal_path(+ &self.windows_acl_lease_path(id),+ ))+ }+ #[cfg(not(windows))]+ {+ let _ = id;+ None+ }+ }++ fn install_source(+ &self,+ entry: &RegistryEntry,+ source: &InstallSource,+ is_update: bool,+ ) -> Result<InstalledVersion> {+ let lock = self.lock(entry.id)?;+ self.recover_publisher_trust_locked(&lock.root)?;+ self.recover_activation_locked(&lock.root, entry.id)?;+ self.recover_publisher_trust_from_active_locked(&lock.root, entry.id)?;+ if let Some(signed) = &source.signed_catalog {+ let current_trust = load_publisher_trust_at(&lock.root)?;+ let verified = verify_catalog_at(entry, signed, ¤t_trust, unix_now()?)+ .context("signed catalog changed or became stale before mutation")?;+ if source.trust_update.as_ref() != Some(&verified) {+ bail!("signed catalog trust decision changed before mutation; inspect it again");+ }+ }+ let active = self.active_pointer_locked(&lock.root, entry.id)?;+ if is_update && active.is_none() {+ bail!("{} is not installed; use extension install", entry.id);+ }+ if !is_update && active.is_some() {+ bail!("{} is already installed; use extension update", entry.id);+ }+ if let Some(pointer) = &active {+ let extension = lock.root.open_dir_nofollow(entry.id)?;+ let versions = extension.open_dir_nofollow("versions")?;+ let installed = versions.open_dir_nofollow(&pointer.version)?;+ let manifest = verify_installed_version_at(&installed, entry, None)?;+ let record = read_install_record_at(&installed, entry.id, &manifest.version)?;+ if record.trust != TrustClass::DeveloperUnsignedLocal+ && source.trust == TrustClass::DeveloperUnsignedLocal+ {+ bail!("developer-only unsigned mode cannot replace a publisher-verified install");+ }+ if let (Some(previous), Some(next)) = (+ record.catalog_version,+ source+ .catalog+ .as_ref()+ .map(|catalog| catalog.catalog_version),+ ) {+ if next <= previous {+ bail!(+ "catalog anti-rollback version {next} must be newer than installed version {previous}"+ );+ }+ }+ }+ let extension_handle = ensure_private_subdirectory(&lock.root, entry.id)?;+ let versions = self.versions_dir(entry.id);+ let versions_handle = ensure_private_subdirectory(&extension_handle, "versions")?;+ let staging_parent = self.root.join(".staging");+ let staging_parent_handle = ensure_private_subdirectory(&lock.root, ".staging")?;+ let staging = staging_parent.join(unique_name(entry.id));+ let staging_name = staging.file_name().expect("generated staging name");+ create_private_subdirectory(&staging_parent_handle, staging_name)?;+ let staging_handle = staging_parent_handle.open_dir_nofollow(staging_name)?;+ let inspected = match inspect_archive(&source.archive, entry, &staging_handle) {+ Ok(inspected) => inspected,+ Err(error) => {+ remove_cap_subdirectory(&staging_parent_handle, staging_name)?;+ return Err(error);+ }+ };+ let version = match Version::parse(&inspected.manifest.version)+ .context("manifest version is not valid semantic versioning")+ {+ Ok(version) => version,+ Err(error) => {+ remove_cap_subdirectory(&staging_parent_handle, staging_name)?;+ return Err(error);+ }+ };+ let version_text = version.to_string();+ if let Some(active) = &active {+ let current = Version::parse(&active.version)?;+ if version < current {+ remove_cap_subdirectory(&staging_parent_handle, staging_name)?;+ bail!("update version {version} must be newer than active version {current}");+ }+ }+ validate_source_metadata(&inspected, source)?;+ let destination = versions.join(&version_text);+ match versions_handle.open_dir_nofollow(&version_text) {+ Ok(existing) => {+ verify_cap_directory_permissions_portable(&existing)?;+ let verified =+ verify_installed_version_at(&existing, entry, Some(&inspected.manifest_bytes));+ let cleanup = remove_cap_subdirectory(&staging_parent_handle, staging_name);+ let manifest = verified?;+ verify_install_record_at(&existing, entry.id, &manifest.version)?;+ run_verified_extension_hook(+ &destination,+ &existing,+ &manifest,+ entry,+ Some(&inspected.manifest_bytes),+ true,+ self.acl_profile_journal_path(entry.id),+ )?;+ cleanup?;+ }+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {+ let mut placed = false;+ let staged = (|| -> Result<()> {+ // Record and fully verify the staged version before any+ // hook instruction runs, so a hook can never execute from+ // an unrecorded or unverified install. A failure here+ // removes the staging directory below, so the rollback+ // stays durable whichever step failed.+ write_install_record_at(&staging_handle, &inspected, source)?;+ #[cfg(windows)]+ converge_windows_installed_version(+ &staging_handle,+ entry,+ Some(&inspected.manifest_bytes),+ )?;+ #[cfg(not(windows))]+ verify_installed_version_at(+ &staging_handle,+ entry,+ Some(&inspected.manifest_bytes),+ )?;+ run_verified_extension_hook(+ &staging,+ &staging_handle,+ &inspected.manifest,+ entry,+ Some(&inspected.manifest_bytes),+ true,+ self.acl_profile_journal_path(entry.id),+ )?;+ drop(staging_handle);+ staging_parent_handle+ .rename(staging_name, &versions_handle, &version_text)+ .with_context(|| {+ format!("place extension version at {}", destination.display())+ })?;+ placed = true;+ #[cfg(windows)]+ {+ let installed = versions_handle+ .open_dir_nofollow(&version_text)+ .context("reopen placed extension version")?;+ converge_windows_installed_version(+ &installed,+ entry,+ Some(&inspected.manifest_bytes),+ )?;+ }+ sync_cap_dir(&staging_parent_handle)?;+ sync_cap_dir(&versions_handle)?;+ Ok(())+ })();+ if staged.is_err() {+ if placed {+ #[cfg(windows)]+ if let Ok(installed) = versions_handle.open_dir_nofollow(&version_text) {+ let _ = windows_harden_private_tree(&installed);+ }+ remove_cap_subdirectory(&versions_handle, version_text.as_ref())?;+ } else {+ remove_cap_subdirectory(&staging_parent_handle, staging_name)?;+ }+ }+ staged?;+ }+ Err(error) => {+ return Err(error).with_context(|| {+ format!(+ "inspect existing extension version {}",+ destination.display()+ )+ })+ }+ }++ self.activate_locked(+ &lock.root,+ entry.id,+ &version_text,+ ActivationFailpoint::None,+ )?;+ if let Some(trust) = &source.trust_update {+ self.commit_publisher_trust_locked(&lock.root, trust)?;+ }+ Ok(InstalledVersion {+ version: version_text,+ path: destination,+ })+ }++ #[cfg(test)]+ fn install_archive(&self, entry: &RegistryEntry, archive: &Path) -> Result<InstalledVersion> {+ // Test fixtures own their store exclusively. Inspect the pointer entry+ // directly so the helper does not acquire and immediately reacquire+ // the mutation lock before every install. Some sandbox filesystems can+ // transiently retain that just-released advisory lock and return+ // EAGAIN to the second acquisition.+ let active = self.extension_dir(entry.id).join(ACTIVE_NAME);+ let is_update = match fs::symlink_metadata(&active) {+ Ok(_) => true,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => false,+ Err(error) => {+ return Err(error).with_context(|| {+ format!("inspect test activation pointer {}", active.display())+ })+ }+ };+ self.install_source(+ entry,+ &InstallSource {+ archive: archive.to_owned(),+ trust: TrustClass::DeveloperUnsignedLocal,+ catalog: None,+ signed_catalog: None,+ trust_update: None,+ },+ is_update,+ )+ }++ fn activate_locked(+ &self,+ root: &Dir,+ id: &str,+ version: &str,+ failpoint: ActivationFailpoint,+ ) -> Result<()> {+ let extension = ensure_private_subdirectory(root, id)?;+ let had_active = private_regular_file_or_missing_at(&extension, ACTIVE_NAME)?;+ if private_regular_file_or_missing_at(&extension, ACTIVE_BACKUP_NAME)?+ || private_regular_file_or_missing_at(&extension, ACTIVE_NEW_NAME)?+ {+ bail!("activation pointer state was not recovered before activation");+ }+ let pointer = serde_json::to_vec_pretty(&ActivePointer {+ id: id.to_owned(),+ version: version.to_owned(),+ })?;+ write_new_file_at(&extension, ACTIVE_NEW_NAME, &pointer)?;+ sync_cap_dir(&extension)?;+ if had_active {+ extension+ .rename(ACTIVE_NAME, &extension, ACTIVE_BACKUP_NAME)+ .context("move current active pointer to rollback backup")?;+ sync_cap_dir(&extension)?;+ }+ if failpoint == ActivationFailpoint::LeaveInterruptedAfterBackup {+ return Err(anyhow!(+ "simulated process interruption after activation backup"+ ));+ }+ let switched = if failpoint == ActivationFailpoint::AfterBackup {+ Err(anyhow!("simulated interruption after activation backup"))+ } else {+ extension+ .rename(ACTIVE_NEW_NAME, &extension, ACTIVE_NAME)+ .context("activate inspected extension version")+ };+ if let Err(error) = switched {+ let _ = extension.remove_file(ACTIVE_NEW_NAME);+ if had_active {+ extension+ .rename(ACTIVE_BACKUP_NAME, &extension, ACTIVE_NAME)+ .context("restore previous active extension")?;+ sync_cap_dir(&extension)?;+ }+ return Err(error);+ }+ if private_regular_file_or_missing_at(&extension, ACTIVE_BACKUP_NAME)? {+ extension+ .remove_file(ACTIVE_BACKUP_NAME)+ .context("remove activation rollback backup")?;+ }+ sync_cap_dir(&extension)?;+ Ok(())+ }++ fn active_pointer_locked(&self, root: &Dir, id: &str) -> Result<Option<ActivePointer>> {+ let Some(extension) = open_private_subdirectory_if_present(root, id)? else {+ return Ok(None);+ };+ if !private_regular_file_or_missing_at(&extension, ACTIVE_NAME)? {+ return Ok(None);+ }+ let bytes = read_small_file_at(&extension, Path::new(ACTIVE_NAME))?;+ let pointer: ActivePointer =+ serde_json::from_slice(&bytes).context("parse active extension pointer")?;+ if pointer.id != id {+ bail!("active pointer for {id} names extension {}", pointer.id);+ }+ validate_version_segment(&pointer.version)?;+ Ok(Some(pointer))+ }++ fn active_path(&self, id: &str) -> Result<Option<PathBuf>> {+ let lock = self.lock(id)?;+ self.recover_activation_locked(&lock.root, id)?;+ self.recover_publisher_trust_from_active_locked(&lock.root, id)?;+ let Some(pointer) = self.active_pointer_locked(&lock.root, id)? else {+ return Ok(None);+ };+ let extension = lock.root.open_dir_nofollow(id)?;+ let versions = extension+ .open_dir_nofollow("versions")+ .context("active extension has no owned versions directory")?;+ verify_cap_directory_permissions_portable(&versions)?;+ let version = versions+ .open_dir_nofollow(&pointer.version)+ .with_context(|| {+ format!(+ "active extension version {} is not an owned directory",+ pointer.version+ )+ })?;+ verify_cap_directory_permissions_portable(&version)?;+ let path = self.versions_dir(id).join(&pointer.version);+ verify_installed_version_at(&version, registry_entry(id)?, None)?;+ Ok(Some(path))+ }++ fn active_path_for_startup(&self, id: &str) -> Result<Option<(PathBuf, ExtensionManifest)>> {+ let lock = self.lock(id)?;+ self.recover_activation_for_startup_locked(&lock.root, id)?;+ let Some(pointer) = self.active_pointer_locked(&lock.root, id)? else {+ return Ok(None);+ };+ let extension = lock.root.open_dir_nofollow(id)?;+ let versions = extension+ .open_dir_nofollow("versions")+ .context("active extension has no owned versions directory")?;+ verify_cap_directory_permissions_portable(&versions)?;+ let version = versions+ .open_dir_nofollow(&pointer.version)+ .with_context(|| {+ format!(+ "active extension version {} is not an owned directory",+ pointer.version+ )+ })?;+ #[cfg(not(windows))]+ verify_cap_directory_permissions_portable(&version)?;+ let manifest = verify_installed_version_for_startup(&version, registry_entry(id)?)?;+ self.recover_publisher_trust_from_verified_active_locked(+ &lock.root, id, &version, &manifest,+ )?;+ Ok(Some((+ self.versions_dir(id).join(&pointer.version),+ manifest,+ )))+ }++ fn info<'a>(&self, entry: &'a RegistryEntry, self_test: bool) -> Result<ExtensionInfo<'a>> {+ let lock = match self.lock(entry.id) {+ Ok(lock) => lock,+ Err(error) => {+ return Ok(ExtensionInfo {+ id: entry.id,+ display_name: entry.display_name,+ description: entry.description,+ protocol_version: entry.protocol_version,+ installed: true,+ active_version: None,+ healthy: false,+ trust: None,+ evidence_class: None,+ publisher_id: None,+ publisher_key_id: None,+ catalog_version: None,+ detail: format!("unhealthy: {error:#}"),+ });+ }+ };+ let pointer = match self+ .recover_activation_locked(&lock.root, entry.id)+ .and_then(|()| self.recover_publisher_trust_from_active_locked(&lock.root, entry.id))+ .and_then(|()| self.active_pointer_locked(&lock.root, entry.id))+ {+ Ok(pointer) => pointer,+ Err(error) => {+ return Ok(ExtensionInfo {+ id: entry.id,+ display_name: entry.display_name,+ description: entry.description,+ protocol_version: entry.protocol_version,+ installed: true,+ active_version: None,+ healthy: false,+ trust: None,+ evidence_class: None,+ publisher_id: None,+ publisher_key_id: None,+ catalog_version: None,+ detail: format!("unhealthy: {error:#}"),+ });+ }+ };+ let Some(pointer) = pointer else {+ return Ok(ExtensionInfo {+ id: entry.id,+ display_name: entry.display_name,+ description: entry.description,+ protocol_version: entry.protocol_version,+ installed: false,+ active_version: None,+ healthy: true,+ trust: None,+ evidence_class: None,+ publisher_id: None,+ publisher_key_id: None,+ catalog_version: None,+ detail: "not installed (healthy)".to_owned(),+ });+ };+ let version = pointer.version.clone();+ let verified = (|| -> Result<InstallRecord> {+ let extension = lock.root.open_dir_nofollow(entry.id)?;+ let versions = extension+ .open_dir_nofollow("versions")+ .context("active extension has no owned versions directory")?;+ verify_cap_directory_permissions_portable(&versions)?;+ let installed = versions.open_dir_nofollow(&version).with_context(|| {+ format!("active extension version {version} is not an owned directory")+ })?;+ verify_cap_directory_permissions_portable(&installed)?;+ let manifest = verify_installed_version_at(&installed, entry, None)?;+ let record = run_verified_extension_hook(+ &self.versions_dir(entry.id).join(&version),+ &installed,+ &manifest,+ entry,+ None,+ self_test,+ self.acl_profile_journal_path(entry.id),+ )?;+ Ok(record)+ })();+ match verified {+ Ok(record) => {+ let trust = record.trust.clone();+ let detail = match trust {+ TrustClass::DeveloperUnsignedLocal => {+ format!("healthy; local integrity checks passed; {DEVELOPER_TRUST_NOTICE}")+ }+ #[cfg(feature = "review-trust-root")]+ TrustClass::ReviewOnlyPublisherVerified => {+ format!("healthy; integrity and review-key verification passed; {REVIEW_TRUST_NOTICE}")+ }+ TrustClass::PublisherVerified => {+ "healthy; integrity and publisher verification checks passed".to_owned()+ }+ };+ let record_evidence_class = evidence_class(&trust);+ Ok(ExtensionInfo {+ id: entry.id,+ display_name: entry.display_name,+ description: entry.description,+ protocol_version: entry.protocol_version,+ installed: true,+ active_version: Some(version),+ healthy: true,+ detail,+ trust: Some(trust),+ evidence_class: Some(record_evidence_class),+ publisher_id: record.publisher_id,+ publisher_key_id: record.key_id,+ catalog_version: record.catalog_version,+ })+ }+ Err(error) => Ok(ExtensionInfo {+ id: entry.id,+ display_name: entry.display_name,+ description: entry.description,+ protocol_version: entry.protocol_version,+ installed: true,+ active_version: Some(version),+ healthy: false,+ trust: None,+ evidence_class: None,+ publisher_id: None,+ publisher_key_id: None,+ catalog_version: None,+ detail: format!("unhealthy: {error:#}"),+ }),+ }+ }++ fn remove(&self, entry: &RegistryEntry) -> Result<()> {+ let lock = self.lock(entry.id)?;+ self.recover_activation_locked(&lock.root, entry.id)?;+ self.recover_publisher_trust_from_active_locked(&lock.root, entry.id)?;+ let Some(extension) = open_private_subdirectory_if_present(&lock.root, entry.id)? else {+ bail!("{} is not installed", entry.id);+ };+ let names = extension+ .entries()?+ .map(|item| item.map(|entry| entry.file_name()))+ .collect::<std::io::Result<BTreeSet<_>>>()?;+ let allowed = [+ std::ffi::OsString::from("versions"),+ std::ffi::OsString::from(ACTIVE_NAME),+ ]+ .into_iter()+ .collect::<BTreeSet<_>>();+ if !names.is_subset(&allowed) {+ bail!("refusing removal because the extension directory contains unowned state");+ }+ if let Some(pointer) = self.active_pointer_locked(&lock.root, entry.id)? {+ self.validate_pointer_target_locked(entry.id, &extension, ACTIVE_NAME)?;+ validate_version_segment(&pointer.version)?;+ }+ match extension.open_dir_nofollow("versions") {+ Ok(versions) => {+ for child in versions.entries()? {+ let child = child?;+ if !child.file_type()?.is_dir() {+ bail!("refusing removal because versions contains non-directory state");+ }+ let version_name = child.file_name();+ let version_text = version_name+ .to_str()+ .ok_or_else(|| anyhow!("installed version name is not UTF-8"))?;+ validate_version_segment(version_text)?;+ let version = versions.open_dir_nofollow(&version_name)?;+ verify_installed_version_at(&version, entry, None)?;+ }+ }+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}+ Err(error) => return Err(error).context("open owned versions directory for removal"),+ }+ drop(extension);+ remove_cap_subdirectory(&lock.root, std::ffi::OsStr::new(entry.id))+ }+}++fn inspect_archive(+ path: &Path,+ entry: &RegistryEntry,+ staging_dir: &Dir,+) -> Result<InspectedArchive> {+ let mut file = open_existing_no_follow(path)?;+ let metadata = file+ .metadata()+ .with_context(|| format!("inspect archive {}", path.display()))?;+ #[cfg(windows)]+ {+ use std::os::windows::fs::MetadataExt as _;+ if metadata.file_attributes() & 0x400 != 0 {+ bail!("archive is a Windows reparse point: {}", path.display());+ }+ }+ if !metadata.file_type().is_file() || metadata.file_type().is_symlink() {+ bail!("archive is not a regular local file: {}", path.display());+ }+ if metadata.len() > MAX_ARCHIVE_BYTES {+ bail!("archive exceeds the {MAX_ARCHIVE_BYTES} byte input limit");+ }+ let archive_sha256 = hash_open_file(&mut file, MAX_ARCHIVE_BYTES)?;+ file.seek(std::io::SeekFrom::Start(0))?;+ let decoder = GzDecoder::new(BoundedReader {+ inner: file,+ remaining: MAX_ARCHIVE_BYTES + 1,+ });+ let mut archive = tar::Archive::new(decoder);+ let mut files = Vec::new();+ let mut seen = BTreeSet::new();+ let mut expanded = 0_u64;+ for item in archive+ .entries()+ .context("read extension archive")?+ .raw(true)+ {+ let mut item = item.context("read extension archive entry")?;+ let entry_type = item.header().entry_type();+ let path = item.path().context("read archive entry path")?;+ let normalized = safe_relative_path(&path)?;+ if normalized.as_os_str().is_empty() || entry_type.is_dir() {+ continue;+ }+ if !entry_type.is_file() {+ bail!(+ "archive entry {} is not a regular file",+ normalized.display()+ );+ }+ let normalized = normalized.to_string_lossy().replace('\\', "/");+ if normalized.len() > MAX_ARCHIVE_PATH_BYTES {+ bail!("archive path exceeds the {MAX_ARCHIVE_PATH_BYTES} byte limit");+ }+ if !seen.insert(normalized.clone()) {+ bail!("archive contains duplicate entry {normalized}");+ }+ if files.len() >= MAX_FILE_COUNT {+ bail!("archive contains more than {MAX_FILE_COUNT} files");+ }+ let size = item.header().size().context("read archive entry size")?;+ if size > MAX_FILE_BYTES {+ bail!("archive entry {normalized} exceeds the {MAX_FILE_BYTES} byte file limit");+ }+ if normalized == MANIFEST_NAME && size > MAX_IN_MEMORY_BYTES {+ bail!("{MANIFEST_NAME} exceeds the {MAX_IN_MEMORY_BYTES} byte in-memory limit");+ }+ expanded = expanded+ .checked_add(size)+ .ok_or_else(|| anyhow!("archive size overflow"))?;+ if expanded > MAX_EXPANDED_BYTES {+ bail!(+ "archive expands beyond the {} byte limit",+ MAX_EXPANDED_BYTES+ );+ }+ let relative = Path::new(&normalized);+ create_private_cap_parent_directories(staging_dir, relative)?;+ let sha256 = stream_archive_file_at(staging_dir, &mut item, relative, size)+ .with_context(|| format!("stage archive entry {normalized}"))?;+ files.push(ArchiveFile {+ path: normalized,+ sha256,+ size,+ });+ }+ if !files.iter().any(|file| file.path == MANIFEST_NAME) {+ bail!("archive does not contain {MANIFEST_NAME} at its root");+ }+ let manifest_bytes = read_small_file_at(staging_dir, Path::new(MANIFEST_NAME))?;+ let manifest: ExtensionManifest = serde_json::from_slice(&manifest_bytes)+ .with_context(|| format!("parse {MANIFEST_NAME}"))?;+ validate_manifest(&manifest, entry, &files)?;+ apply_manifest_permissions_at(staging_dir, &manifest)?;+ Ok(InspectedArchive {+ manifest,+ manifest_bytes,+ archive_sha256,+ archive_size: metadata.len(),+ expanded_size: expanded,+ })+}++fn validate_manifest(+ manifest: &ExtensionManifest,+ entry: &RegistryEntry,+ archive_files: &[ArchiveFile],+) -> Result<()> {+ if manifest.schema_version != MANIFEST_SCHEMA_VERSION {+ bail!(+ "unsupported extension manifest schema {}; expected {MANIFEST_SCHEMA_VERSION}",+ manifest.schema_version+ );+ }+ if manifest.id != entry.id {+ bail!(+ "manifest extension id {:?} does not match requested {:?}",+ manifest.id,+ entry.id+ );+ }+ Version::parse(&manifest.version)+ .context("manifest version is not valid semantic versioning")?;+ let requirement = VersionReq::parse(&manifest.driver_version)+ .context("manifest driver_version is not a valid semantic version requirement")?;+ let driver = Version::parse(env!("CARGO_PKG_VERSION"))?;+ if !requirement.matches(&driver) {+ bail!(+ "extension {} requires Driver {}; running Driver is {}",+ manifest.version,+ manifest.driver_version,+ driver+ );+ }+ if manifest.protocol_version != entry.protocol_version {+ bail!(+ "extension protocol {} is incompatible with Driver protocol {}",+ manifest.protocol_version,+ entry.protocol_version+ );+ }+ let target = current_target()?;+ if manifest.target != target {+ bail!(+ "extension target {:?} does not match current target {:?}",+ manifest.target,+ target+ );+ }+ safe_manifest_path(&manifest.entrypoint)?;+ for (name, value) in [+ ("license", manifest.license.as_str()),+ ("source", manifest.source.as_str()),+ (+ "corresponding_source_uri",+ manifest.corresponding_source_uri.as_str(),+ ),+ (+ "corresponding_source_revision",+ manifest.corresponding_source_revision.as_str(),+ ),+ ("provenance", manifest.provenance.as_str()),+ ] {+ if value.trim().is_empty() {+ bail!("manifest {name} must not be empty");+ }+ }+ let mut declared = BTreeMap::new();+ for file in &manifest.files {+ safe_manifest_path(&file.path)?;+ if file.path == MANIFEST_NAME || file.path == INSTALL_RECORD_NAME {+ bail!("manifest cannot claim reserved path {:?}", file.path);+ }+ validate_sha256(&file.path, &file.sha256)?;+ if declared.insert(file.path.as_str(), file).is_some() {+ bail!("manifest declares duplicate file {}", file.path);+ }+ }+ let mut model_paths = BTreeSet::new();+ for model in &manifest.models {+ safe_manifest_path(&model.path)?;+ if model.revision.trim().is_empty() {+ bail!("model {} has no immutable revision", model.path);+ }+ validate_sha256("model original", &model.original_sha256)?;+ validate_sha256("model conversion", &model.conversion_sha256)?;+ if !model_paths.insert(model.path.as_str()) {+ bail!("manifest declares duplicate model {}", model.path);+ }+ let file = declared+ .get(model.path.as_str())+ .ok_or_else(|| anyhow!("model {} is not declared in files", model.path))?;+ if !file.sha256.eq_ignore_ascii_case(&model.conversion_sha256) {+ bail!(+ "model hash does not exactly match file hash for {}",+ model.path+ );+ }+ if let Some(binding) = &model.license_file {+ validate_artifact_binding("model license", binding, &declared)?;+ }+ }+ let mut component_names = BTreeSet::new();+ for component in &manifest.components {+ for (field, value) in [+ ("name", component.name.as_str()),+ ("version", component.version.as_str()),+ ("license", component.license.as_str()),+ ("notice", component.notice.as_str()),+ ("source_uri", component.source_uri.as_str()),+ ("source_revision", component.source_revision.as_str()),+ ] {+ if value.trim().is_empty() {+ bail!("component {} has an empty {field}", component.name);+ }+ }+ if !component_names.insert(component.name.as_str()) {+ bail!("manifest declares duplicate component {}", component.name);+ }+ if let Some(binding) = &component.notice_file {+ validate_artifact_binding("component notice", binding, &declared)?;+ }+ }+ if let Some(binding) = &manifest.corresponding_source_file {+ validate_artifact_binding("corresponding source", binding, &declared)?;+ }+ if !declared.contains_key(manifest.entrypoint.as_str()) {+ bail!(+ "manifest entrypoint {} is not in files",+ manifest.entrypoint+ );+ }+ if !declared+ .get(manifest.entrypoint.as_str())+ .is_some_and(|file| file.executable)+ {+ bail!(+ "manifest entrypoint {} must be executable",+ manifest.entrypoint+ );+ }+ let actual: BTreeMap<&str, &ArchiveFile> = archive_files+ .iter()+ .filter(|file| file.path != MANIFEST_NAME)+ .map(|file| (file.path.as_str(), file))+ .collect();+ if actual.len() != declared.len() {+ bail!("archive file set does not exactly match the manifest");+ }+ for (path, expected) in declared {+ let file = actual+ .get(path)+ .ok_or_else(|| anyhow!("archive is missing declared file {path}"))?;+ if !file.sha256.eq_ignore_ascii_case(&expected.sha256) {+ bail!(+ "SHA-256 mismatch for {path}: expected {}, got {}",+ expected.sha256,+ file.sha256+ );+ }+ if file.size > MAX_FILE_BYTES {+ bail!("file {path} exceeds the supported file limit");+ }+ }+ Ok(())+}++fn validate_artifact_binding(+ label: &str,+ binding: &ArtifactBinding,+ declared: &BTreeMap<&str, &ManifestFile>,+) -> Result<()> {+ safe_manifest_path(&binding.path)?;+ validate_sha256(label, &binding.sha256)?;+ let file = declared+ .get(binding.path.as_str())+ .ok_or_else(|| anyhow!("{label} file {} is not declared in files", binding.path))?;+ if !file.sha256.eq_ignore_ascii_case(&binding.sha256) {+ bail!(+ "{label} digest does not match declared file {}",+ binding.path+ );+ }+ Ok(())+}++fn write_install_record_at(+ root: &Dir,+ inspected: &InspectedArchive,+ source: &InstallSource,+) -> Result<()> {+ let record = InstallRecord {+ schema_version: MANIFEST_SCHEMA_VERSION,+ id: inspected.manifest.id.clone(),+ version: inspected.manifest.version.clone(),+ manifest_sha256: hex_sha256(&inspected.manifest_bytes),+ trust: source.trust.clone(),+ publisher_id: source+ .catalog+ .as_ref()+ .map(|catalog| catalog.publisher_id.clone()),+ key_id: source+ .catalog+ .as_ref()+ .map(|catalog| catalog.key_id.clone()),+ archive_sha256: inspected.archive_sha256.clone(),+ catalog_version: source+ .catalog+ .as_ref()+ .map(|catalog| catalog.catalog_version),+ publisher_trust: source.trust_update.clone(),+ };+ write_new_file_at(+ root,+ INSTALL_RECORD_NAME,+ &serde_json::to_vec_pretty(&record)?,+ )+}++fn write_new_file_at(directory: &Dir, path: &str, bytes: &[u8]) -> Result<()> {+ if bytes.len() as u64 > MAX_IN_MEMORY_BYTES {+ bail!("refusing to write oversized in-memory file {path}");+ }+ let mut options = CapOpenOptions::new();+ options+ .write(true)+ .create_new(true)+ .follow(FollowSymlinks::No);+ #[cfg(unix)]+ {+ use cap_std::fs::OpenOptionsExt;+ options.mode(0o600);+ }+ let mut file = directory.open_with(path, &options)?;+ #[cfg(windows)]+ windows_secure_handle(&file)?;+ file.write_all(bytes)?;+ file.sync_all()?;+ Ok(())+}++fn verify_installed_version_at(+ root: &Dir,+ entry: &RegistryEntry,+ expected_manifest: Option<&[u8]>,+) -> Result<ExtensionManifest> {+ let bytes = read_small_file_at(root, Path::new(MANIFEST_NAME))?;+ if expected_manifest.is_some_and(|expected| expected != bytes) {+ bail!("version directory already exists with a different manifest");+ }+ let manifest: ExtensionManifest = serde_json::from_slice(&bytes)?;+ safe_manifest_path(&manifest.entrypoint)?;+ for file in &manifest.files {+ safe_manifest_path(&file.path)?;+ }+ let actual_paths = installed_regular_files_at(root)?;+ let expected_paths: BTreeSet<String> = manifest+ .files+ .iter()+ .map(|file| file.path.clone())+ .chain([MANIFEST_NAME.to_owned(), INSTALL_RECORD_NAME.to_owned()])+ .collect();+ if actual_paths != expected_paths {+ bail!("installed file set does not exactly match the ownership record");+ }+ let synthetic_files = manifest+ .files+ .iter()+ .map(|file| {+ let path = Path::new(&file.path);+ let metadata = root+ .symlink_metadata(path)+ .with_context(|| format!("inspect installed file {}", path.display()))?;+ if !metadata.file_type().is_file() {+ bail!("installed path is not a regular file: {}", path.display());+ }+ Ok(ArchiveFile {+ path: file.path.clone(),+ sha256: hash_file_at(root, path, MAX_FILE_BYTES)?,+ size: metadata.len(),+ })+ })+ .collect::<Result<Vec<_>>>()?;+ let mut all_files = synthetic_files;+ all_files.push(ArchiveFile {+ path: MANIFEST_NAME.to_owned(),+ sha256: hex_sha256(&bytes),+ size: bytes.len() as u64,+ });+ validate_manifest(&manifest, entry, &all_files)?;+ verify_manifest_permissions_at(root, &manifest)?;+ verify_install_record_at(root, entry.id, &manifest.version)?;+ Ok(manifest)+}++/// Verify the installed payload needed to construct the perception worker+/// without rehashing large, non-executed compliance and corresponding-source+/// files on every daemon start. Lifecycle commands continue to use the full+/// verifier above.+fn verify_installed_version_for_startup_at(+ root: &Dir,+ entry: &RegistryEntry,+) -> Result<ExtensionManifest> {+ let bytes = read_small_file_at(root, Path::new(MANIFEST_NAME))?;+ let manifest: ExtensionManifest = serde_json::from_slice(&bytes)?;+ read_install_record_at(root, entry.id, &manifest.version)?;+ safe_manifest_path(&manifest.entrypoint)?;+ for file in &manifest.files {+ safe_manifest_path(&file.path)?;+ }++ let actual_paths = installed_regular_files_at(root)?;+ let expected_paths: BTreeSet<String> = manifest+ .files+ .iter()+ .map(|file| file.path.clone())+ .chain([MANIFEST_NAME.to_owned(), INSTALL_RECORD_NAME.to_owned()])+ .collect();+ if actual_paths != expected_paths {+ bail!("installed file set does not exactly match the ownership record");+ }+ verify_manifest_permissions_at(root, &manifest)?;++ let contract_file = manifest+ .files+ .iter()+ .find(|file| file.path == PERCEPTION_RUNTIME_CONTRACT)+ .ok_or_else(|| anyhow!("perception runtime contract is not extension-owned"))?;+ let contract_hash = hash_file_at(root, Path::new(PERCEPTION_RUNTIME_CONTRACT), MAX_FILE_BYTES)?;+ if !contract_hash.eq_ignore_ascii_case(&contract_file.sha256) {+ bail!("SHA-256 mismatch for {PERCEPTION_RUNTIME_CONTRACT}");+ }+ let contract: PerceptionRuntimeContract = serde_json::from_slice(&read_small_file_at(+ root,+ Path::new(PERCEPTION_RUNTIME_CONTRACT),+ )?)+ .context("parse perception runtime contract")?;+ validate_runtime_contract(&manifest, &contract)?;++ let mut required = manifest+ .files+ .iter()+ .filter(|file| {+ file.executable+ || ["bin/", "runtime/", "models/"]+ .iter()+ .any(|prefix| file.path.starts_with(prefix))+ })+ .map(|file| file.path.clone())+ .collect::<BTreeSet<_>>();+ required.insert(manifest.entrypoint.clone());+ required.insert(PERCEPTION_RUNTIME_CONTRACT.to_owned());+ required.insert(unique_model_manifest_path(&manifest)?.to_owned());+ required.extend(manifest.models.iter().map(|model| model.path.clone()));+ required.insert(format!("runtime/{}", contract.runtime.name));+ required.extend(+ contract+ .models+ .iter()+ .map(|model| format!("models/{}", model.name)),+ );+ required.insert(format!("models/{}", contract.dictionary.name));+ // Reuse complete manifest validation while hashing only worker execution+ // inputs. Non-executed compliance payload remains covered by exact file-set,+ // ownership, permissions, and full lifecycle/status verification.+ let mut startup_files = manifest+ .files+ .iter()+ .map(|file| {+ let path = Path::new(&file.path);+ let metadata = root+ .symlink_metadata(path)+ .with_context(|| format!("inspect installed file {}", path.display()))?;+ if !metadata.file_type().is_file() {+ bail!("installed path is not a regular file: {}", path.display());+ }+ Ok(ArchiveFile {+ path: file.path.clone(),+ sha256: if required.contains(&file.path) {+ hash_file_at(root, path, MAX_FILE_BYTES)?+ } else {+ file.sha256.clone()+ },+ size: metadata.len(),+ })+ })+ .collect::<Result<Vec<_>>>()?;+ startup_files.push(ArchiveFile {+ path: MANIFEST_NAME.to_owned(),+ sha256: hex_sha256(&bytes),+ size: bytes.len() as u64,+ });+ validate_manifest(&manifest, entry, &startup_files)?;+ Ok(manifest)+}++fn verify_installed_version_for_startup(+ root: &Dir,+ entry: &RegistryEntry,+) -> Result<ExtensionManifest> {+ #[cfg(windows)]+ {+ let started = Instant::now();+ return converge_windows_startup_verification_with(+ WINDOWS_ACL_CONVERGENCE_ATTEMPTS,+ WINDOWS_ACL_CONVERGENCE_RETRY_WINDOW,+ || started.elapsed(),+ std::thread::sleep,+ || windows_harden_private_tree(root),+ || verify_installed_version_for_startup_at(root, entry),+ );+ }+ #[cfg(not(windows))]+ verify_installed_version_for_startup_at(root, entry)+}++fn installed_regular_files_at(root: &Dir) -> Result<BTreeSet<String>> {+ fn visit(+ directory: &Dir,+ prefix: &Path,+ paths: &mut BTreeSet<String>,+ expanded: &mut u64,+ ) -> Result<()> {+ verify_cap_directory_permissions_portable(directory)?;+ for child in directory.entries()? {+ let child = child?;+ let file_type = child.file_type()?;+ let relative = prefix.join(child.file_name());+ if file_type.is_symlink() {+ bail!(+ "installed extension contains a symbolic link: {}",+ relative.display()+ );+ }+ if file_type.is_dir() {+ visit(+ &directory.open_dir_nofollow(child.file_name())?,+ &relative,+ paths,+ expanded,+ )?;+ } else if file_type.is_file() {+ let size = child.metadata()?.len();+ if size > MAX_FILE_BYTES {+ bail!(+ "installed file exceeds the supported file limit: {}",+ relative.display()+ );+ }+ *expanded = expanded+ .checked_add(size)+ .ok_or_else(|| anyhow!("installed extension size overflow"))?;+ if *expanded > MAX_EXPANDED_BYTES {+ bail!("installed extension exceeds the supported expanded size");+ }+ paths.insert(relative.to_string_lossy().replace('\\', "/"));+ if paths.len() > MAX_FILE_COUNT + 2 {+ bail!("installed extension contains too many files");+ }+ } else {+ bail!(+ "installed extension contains a special file: {}",+ relative.display()+ );+ }+ }+ Ok(())+ }+ let mut paths = BTreeSet::new();+ let mut expanded = 0;+ visit(root, Path::new(""), &mut paths, &mut expanded)?;+ Ok(paths)+}++fn read_install_record_at(root: &Dir, id: &str, version: &str) -> Result<InstallRecord> {+ let manifest = read_small_file_at(root, Path::new(MANIFEST_NAME))?;+ let record: InstallRecord =+ serde_json::from_slice(&read_small_file_at(root, Path::new(INSTALL_RECORD_NAME))?)?;+ if record.schema_version != MANIFEST_SCHEMA_VERSION+ || record.id != id+ || record.version != version+ || record.manifest_sha256 != hex_sha256(&manifest)+ || validate_sha256("record archive", &record.archive_sha256).is_err()+ {+ bail!("install record does not verify extension ownership");+ }+ match record.trust {+ TrustClass::PublisherVerified => {+ #[cfg(feature = "review-trust-root")]+ bail!("review-only builds cannot accept production-class install records");+ #[cfg(not(feature = "review-trust-root"))]+ validate_verified_install_record(&record)?;+ }+ #[cfg(feature = "review-trust-root")]+ TrustClass::ReviewOnlyPublisherVerified => validate_verified_install_record(&record)?,+ TrustClass::DeveloperUnsignedLocal => {+ if record.publisher_id.is_some()+ || record.key_id.is_some()+ || record.catalog_version.is_some()+ || record.publisher_trust.is_some()+ {+ bail!("developer install record cannot claim a verified publisher");+ }+ }+ }+ Ok(record)+}++fn validate_verified_install_record(record: &InstallRecord) -> Result<()> {+ if record.publisher_id.as_deref() != Some(expected_publisher_id())+ || record.key_id.as_deref().is_none_or(str::is_empty)+ {+ bail!("verified install record has an untrusted publisher identity");+ }+ if record.catalog_version.is_none() {+ bail!("verified install record has no catalog anti-rollback version");+ }+ let trust = record+ .publisher_trust+ .as_ref()+ .ok_or_else(|| anyhow!("verified install record has no publisher trust snapshot"))?;+ validate_publisher_trust(trust)?;+ if Some(trust.highest_catalog_version) != record.catalog_version+ || Some(trust.current_key.key_id.as_str()) != record.key_id.as_deref()+ && trust.pending_key.as_ref().map(|key| key.key_id.as_str()) != record.key_id.as_deref()+ {+ bail!("verified install record publisher trust does not match its catalog");+ }+ Ok(())+}++fn verify_install_record_at(root: &Dir, id: &str, version: &str) -> Result<()> {+ read_install_record_at(root, id, version).map(drop)+}++fn run_extension_hook(+ root: &Path,+ manifest: &ExtensionManifest,+ self_test: bool,+ journal_path: Option<PathBuf>,+) -> Result<()> {+ run_extension_hook_with_timeout(+ root,+ manifest,+ self_test,+ std::time::Duration::from_secs(10),+ journal_path,+ )+}++#[cfg(windows)]+fn converge_windows_installed_version(+ root: &Dir,+ entry: &RegistryEntry,+ expected_manifest: Option<&[u8]>,+) -> Result<ExtensionManifest> {+ converge_windows_acl(+ WINDOWS_ACL_CONVERGENCE_ATTEMPTS,+ WINDOWS_ACL_CONVERGENCE_RETRY_WINDOW,+ || windows_harden_private_tree(root),+ || verify_installed_version_at(root, entry, expected_manifest),+ )+}++fn run_verified_extension_hook(+ root_path: &Path,+ root: &Dir,+ manifest: &ExtensionManifest,+ entry: &RegistryEntry,+ expected_manifest: Option<&[u8]>,+ self_test: bool,+ journal_path: Option<PathBuf>,+) -> Result<InstallRecord> {+ run_verified_extension_hook_with(root, entry, expected_manifest, &manifest.version, || {+ run_extension_hook(root_path, manifest, self_test, journal_path)+ })+}++fn run_verified_extension_hook_with(+ root: &Dir,+ entry: &RegistryEntry,+ expected_manifest: Option<&[u8]>,+ version: &str,+ hook: impl FnOnce() -> Result<()>,+) -> Result<InstallRecord> {+ let hook = hook();+ #[cfg(windows)]+ {+ let restored = converge_windows_installed_version(root, entry, expected_manifest).map(drop);+ match (hook, restored) {+ (Ok(()), restored) => restored,+ (Err(error), Ok(())) => Err(error),+ (Err(error), Err(restore_error)) => Err(anyhow!(+ "{error:#}; additionally failed to restore and verify private Windows ACLs after the extension hook: {restore_error:#}"+ )),+ }?;+ }+ #[cfg(not(windows))]+ {+ let _ = (root, entry, expected_manifest);+ hook?;+ }+ read_install_record_at(root, entry.id, version)+}++/// Test-only record of the installed state each hook launch could see.+///+/// A hook may run only after its extension has been recorded and fully+/// verified, and the only way to prove that ordering is to inspect the install+/// directory at the moment of launch — a fresh install's staging directory is+/// gone by the time a test could look.+#[cfg(test)]+mod hook_observer {+ use super::{+ open_directory_path_nofollow, read_install_record_at, registry_entry,+ verify_installed_version_at, INSTALL_RECORD_NAME, PERCEPTION_ID,+ };+ use std::path::{Path, PathBuf};+ use std::sync::Mutex;++ #[derive(Clone, Debug)]+ pub(super) struct Launch {+ pub(super) install_record_present: bool,+ pub(super) fully_verified: bool,+ root: PathBuf,+ }++ static LAUNCHES: Mutex<Vec<Launch>> = Mutex::new(Vec::new());++ /// Called before the hook process is created, so nothing it observes can+ /// have been produced by the hook itself.+ pub(super) fn note_launch(root: &Path) {+ let launch = Launch {+ root: root.to_path_buf(),+ install_record_present: root.join(INSTALL_RECORD_NAME).exists(),+ fully_verified: fully_verified(root),+ };+ LAUNCHES.lock().expect("hook launch observer").push(launch);+ }++ /// Whether the manager itself would accept this directory as an installed,+ /// recorded, integrity-verified extension version right now.+ fn fully_verified(root: &Path) -> bool {+ let Ok(directory) = open_directory_path_nofollow(root) else {+ return false;+ };+ let Ok(entry) = registry_entry(PERCEPTION_ID) else {+ return false;+ };+ let Ok(manifest) = verify_installed_version_at(&directory, entry, None) else {+ return false;+ };+ read_install_record_at(&directory, entry.id, &manifest.version).is_ok()+ }++ /// Launches observed anywhere beneath one directory, which is how a test+ /// reaches a fresh install's staging directory without knowing its+ /// generated name. Tests use their own temporary roots, so this stays exact+ /// while the suite runs in parallel.+ pub(super) fn launches_under(root: &Path) -> Vec<Launch> {+ LAUNCHES+ .lock()+ .expect("hook launch observer")+ .iter()+ .filter(|launch| launch.root.starts_with(root))+ .cloned()+ .collect()+ }+}++/// Run one installed extension hook under the same fail-closed native+/// containment boundary a perception parse gets.+///+/// The hook is the extension's own worker binary, so the only authority it is+/// granted beyond the shared boundary is reading its own installed bundle. It+/// inherits no environment, no descriptor, and none of the Driver's capture,+/// input, or credential authority; a platform that cannot install every+/// boundary fails the launch instead of running the hook.+fn run_extension_hook_with_timeout(+ root: &Path,+ manifest: &ExtensionManifest,+ self_test: bool,+ timeout: std::time::Duration,+ journal_path: Option<PathBuf>,+) -> Result<()> {+ let args = if self_test {+ &manifest.self_test_args+ } else {+ &manifest.health_args+ };+ if args.is_empty() {+ return Ok(());+ }+ if args.len() > 16+ || args+ .iter()+ .any(|arg| arg.len() > 4096 || arg.contains('\0'))+ {+ bail!("extension hook arguments exceed safe limits");+ }+ let entrypoint = root.join(&manifest.entrypoint);+ let metadata =+ fs::symlink_metadata(&entrypoint).context("inspect extension hook entrypoint")?;+ if !metadata.file_type().is_file() || metadata.file_type().is_symlink() {+ bail!("extension hook entrypoint is not a regular file");+ }+ #[cfg(test)]+ hook_observer::note_launch(root);+ let limits = extension_hook_containment_limits(root, journal_path);+ let kind = if self_test { "self-test" } else { "health" };+ match run_contained_hook_blocking(&entrypoint, args, &limits, timeout)? {+ HookOutcome::Succeeded => Ok(()),+ HookOutcome::Failed(detail) => bail!("extension {kind} hook failed with {detail}"),+ HookOutcome::ResourceLimited(detail) => {+ bail!("extension {kind} hook exceeded a containment limit: {detail}")+ }+ HookOutcome::TimedOut => bail!("extension hook exceeded its execution limit"),+ }+}++fn extension_hook_containment_limits(+ root: &Path,+ journal_path: Option<PathBuf>,+) -> ContainmentLimits {+ ContainmentLimits {+ additional_readable_paths: vec![root.to_path_buf()],+ // The lifecycle caller already owns this extension's runtime ACL+ // lease. Reacquiring it would deadlock, so hook teardown stays on the+ // dedicated hook thread and must finish before the caller releases it.+ windows_require_synchronous_cleanup: true,+ windows_acl_profile_journal_path: journal_path,+ ..ContainmentLimits::default()+ }+}++/// Bridge the asynchronous contained launch into the synchronous extension+/// lifecycle. The hook owns a dedicated thread and runtime, so this stays+/// correct whether or not the caller already sits inside one.+fn run_contained_hook_blocking(+ entrypoint: &Path,+ args: &[String],+ limits: &ContainmentLimits,+ timeout: std::time::Duration,+) -> Result<HookOutcome> {+ std::thread::scope(|scope| -> Result<HookOutcome> {+ scope+ .spawn(|| -> Result<HookOutcome> {+ let runtime = tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .context("start the contained extension hook runtime")?;+ runtime+ .block_on(run_contained_hook(entrypoint, args, limits, timeout))+ .map_err(|failure| match failure.detail {+ Some(detail) => {+ anyhow!("contain the extension hook: {} ({detail})", failure.message)+ }+ None => anyhow!("contain the extension hook: {}", failure.message),+ })+ })+ .join()+ .map_err(|_| anyhow!("the contained extension hook supervisor panicked"))?+ })+}++fn stream_archive_file_at<R: Read>(+ root: &Dir,+ reader: &mut R,+ path: &Path,+ expected: u64,+) -> Result<String> {+ let (parent, name) = open_cap_parent_nofollow(root, path)?;+ let mut options = CapOpenOptions::new();+ options+ .write(true)+ .create_new(true)+ .follow(FollowSymlinks::No);+ #[cfg(unix)]+ {+ use cap_std::fs::OpenOptionsExt;+ options.mode(0o600);+ }+ let mut file = parent.open_with(&name, &options)?;+ #[cfg(windows)]+ windows_secure_handle(&file)?;+ let mut hasher = Sha256::new();+ let mut copied = 0_u64;+ let mut buffer = [0_u8; 64 * 1024];+ loop {+ let read = reader.read(&mut buffer)?;+ if read == 0 {+ break;+ }+ copied = copied+ .checked_add(read as u64)+ .ok_or_else(|| anyhow!("archive entry size overflow"))?;+ if copied > expected || copied > MAX_FILE_BYTES {+ bail!("archive entry exceeded its declared or supported size");+ }+ hasher.update(&buffer[..read]);+ file.write_all(&buffer[..read])?;+ }+ if copied != expected {+ bail!("archive entry declared {expected} bytes but contained {copied}");+ }+ file.sync_all()?;+ Ok(format!("{:x}", hasher.finalize()))+}++fn hash_file_at(directory: &Dir, path: &Path, limit: u64) -> Result<String> {+ let (parent, name) = open_cap_parent_nofollow(directory, path)?;+ let mut options = CapOpenOptions::new();+ options.read(true).follow(FollowSymlinks::No);+ let mut file = parent.open_with(&name, &options)?;+ if !file.metadata()?.is_file() {+ bail!(+ "extension path is not an owned regular file: {}",+ path.display()+ );+ }+ verify_private_cap_file_permissions(&file, &path.to_string_lossy())?;+ let mut hasher = Sha256::new();+ let mut total = 0_u64;+ let mut buffer = [0_u8; 64 * 1024];+ loop {+ let read = file.read(&mut buffer)?;+ if read == 0 {+ break;+ }+ total = total+ .checked_add(read as u64)+ .ok_or_else(|| anyhow!("file size overflow"))?;+ if total > limit {+ bail!("file {} exceeds the {limit} byte limit", path.display());+ }+ hasher.update(&buffer[..read]);+ }+ Ok(format!("{:x}", hasher.finalize()))+}++fn read_small_file_at(directory: &Dir, path: &Path) -> Result<Vec<u8>> {+ let (parent, name) = open_cap_parent_nofollow(directory, path)?;+ let mut options = CapOpenOptions::new();+ options.read(true).follow(FollowSymlinks::No);+ let file = parent.open_with(&name, &options)?;+ if !file.metadata()?.is_file() {+ bail!(+ "extension path is not an owned regular file: {}",+ path.display()+ );+ }+ verify_private_cap_file_permissions(&file, &path.to_string_lossy())?;+ let mut bytes = Vec::new();+ file.take(MAX_IN_MEMORY_BYTES + 1).read_to_end(&mut bytes)?;+ if bytes.len() as u64 > MAX_IN_MEMORY_BYTES {+ bail!("file {} exceeds the in-memory limit", path.display());+ }+ Ok(bytes)+}++fn create_private_cap_parent_directories(root: &Dir, relative: &Path) -> Result<()> {+ let mut current = root.try_clone()?;+ if let Some(parent) = relative.parent() {+ for component in parent.components() {+ let Component::Normal(segment) = component else {+ bail!("staging destination contains an unsafe parent");+ };+ match current.open_dir_nofollow(segment) {+ Ok(next) => current = next,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {+ create_private_subdirectory(¤t, segment)?;+ current = current.open_dir_nofollow(segment)?;+ }+ Err(error) => return Err(error.into()),+ }+ }+ }+ Ok(())+}++fn open_cap_parent_nofollow(root: &Dir, relative: &Path) -> Result<(Dir, std::ffi::OsString)> {+ let name = relative+ .file_name()+ .ok_or_else(|| anyhow!("relative extension path has no final component"))?+ .to_owned();+ let mut current = root.try_clone()?;+ if let Some(parent) = relative.parent() {+ for component in parent.components() {+ let Component::Normal(segment) = component else {+ bail!("extension path contains an unsafe parent");+ };+ current = current.open_dir_nofollow(segment)?;+ verify_cap_directory_permissions_portable(¤t)?;+ }+ }+ Ok((current, name))+}++fn create_private_subdirectory(parent: &Dir, name: &std::ffi::OsStr) -> Result<()> {+ #[cfg(unix)]+ {+ use cap_std::fs::{DirBuilder, DirBuilderExt};+ let mut builder = DirBuilder::new();+ builder.mode(0o700);+ parent.create_dir_with(name, &builder)?;+ }+ #[cfg(not(unix))]+ parent.create_dir(name)?;+ #[cfg(windows)]+ {+ let directory = parent.open_dir_nofollow(name)?;+ windows_secure_handle(&directory)?;+ }+ sync_cap_dir(parent)+}++fn ensure_private_subdirectory(parent: &Dir, name: &str) -> Result<Dir> {+ match parent.open_dir_nofollow(name) {+ Ok(directory) => {+ verify_cap_directory_permissions_portable(&directory)?;+ Ok(directory)+ }+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {+ create_private_subdirectory(parent, std::ffi::OsStr::new(name))?;+ let directory = parent.open_dir_nofollow(name)?;+ verify_cap_directory_permissions_portable(&directory)?;+ Ok(directory)+ }+ Err(error) => Err(error).with_context(|| format!("open private subdirectory {name}")),+ }+}++fn open_private_subdirectory_if_present(parent: &Dir, name: &str) -> Result<Option<Dir>> {+ match parent.open_dir_nofollow(name) {+ Ok(directory) => {+ verify_cap_directory_permissions_portable(&directory)?;+ Ok(Some(directory))+ }+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),+ Err(error) => Err(error).with_context(|| format!("open private subdirectory {name}")),+ }+}++fn private_regular_file_or_missing_at(directory: &Dir, path: &str) -> Result<bool> {+ let mut options = CapOpenOptions::new();+ options.read(true).follow(FollowSymlinks::No);+ match directory.open_with(path, &options) {+ Ok(file) => {+ let metadata = file.metadata()?;+ if !metadata.is_file() {+ bail!("extension path is not an owned regular file: {path}");+ }+ verify_private_cap_file_permissions(&file, path)?;+ Ok(true)+ }+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),+ Err(error) => Err(error).with_context(|| format!("open {path} without following links")),+ }+}++#[cfg(unix)]+fn verify_private_cap_file_permissions(file: &cap_std::fs::File, path: &str) -> Result<()> {+ use cap_std::fs::MetadataExt;+ let metadata = file.metadata()?;+ let mode = metadata.mode() & 0o777;+ if metadata.uid() != rustix::process::geteuid().as_raw()+ || mode & 0o077 != 0+ || mode & 0o600 != 0o600+ {+ bail!("extension file {path} has unsafe ownership or permissions");+ }+ Ok(())+}++#[cfg(windows)]+fn verify_private_cap_file_permissions(file: &cap_std::fs::File, path: &str) -> Result<()> {+ windows_verify_file_handle(file).with_context(|| format!("verify Windows ACL for {path}"))+}++#[cfg(all(not(unix), not(windows)))]+fn verify_private_cap_file_permissions(_file: &cap_std::fs::File, _path: &str) -> Result<()> {+ Ok(())+}++fn remove_cap_subdirectory(parent: &Dir, name: &std::ffi::OsStr) -> Result<()> {+ let opened = match parent.open_dir_nofollow(name) {+ Ok(opened) => opened,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),+ Err(error) => return Err(error.into()),+ };+ verify_cap_directory_permissions_portable(&opened)?;+ inspect_owned_tree(&opened)?;+ opened.remove_open_dir_all()?;+ sync_cap_dir(parent)+}++fn inspect_owned_tree(directory: &Dir) -> Result<()> {+ for child in directory.entries()? {+ let child = child?;+ let file_type = child.file_type()?;+ #[cfg(windows)]+ {+ use cap_std::fs::MetadataExt as _;+ if child.metadata()?.file_attributes() & 0x400 != 0 {+ bail!(+ "refusing to delete extension directory containing reparse point {:?}",+ child.file_name()+ );+ }+ }+ if file_type.is_symlink() {+ bail!(+ "refusing to delete extension directory containing symbolic link {:?}",+ child.file_name()+ );+ }+ if file_type.is_dir() {+ let opened = directory.open_dir_nofollow(child.file_name())?;+ verify_cap_directory_permissions_portable(&opened)?;+ inspect_owned_tree(&opened)?;+ } else if file_type.is_file() {+ let mut options = CapOpenOptions::new();+ options.read(true).follow(FollowSymlinks::No);+ let file = child.open_with(&options)?;+ verify_private_cap_file_permissions(&file, &child.file_name().to_string_lossy())?;+ } else {+ bail!(+ "refusing to delete extension directory containing special file {:?}",+ child.file_name()+ );+ }+ }+ Ok(())+}++#[cfg(windows)]+fn windows_harden_private_tree(directory: &Dir) -> Result<()> {+ windows_harden_private_tree_with(directory, &mut |_| {})+}++#[cfg(windows)]+fn windows_harden_private_tree_with(+ directory: &Dir,+ after_initial_directory_harden: &mut impl FnMut(&Dir),+) -> Result<()> {+ windows_reject_reparse_directory(directory)?;+ windows_secure_handle(directory)?;+ after_initial_directory_harden(directory);+ for child in directory.entries()? {+ let child = child?;+ let file_type = child.file_type()?;+ use cap_std::fs::MetadataExt as _;+ if child.metadata()?.file_attributes() & 0x400 != 0 {+ bail!(+ "refusing to harden extension directory containing reparse point {:?}",+ child.file_name()+ );+ }+ if file_type.is_symlink() {+ bail!(+ "refusing to harden extension directory containing symbolic link {:?}",+ child.file_name()+ );+ }+ if file_type.is_dir() {+ let opened = directory.open_dir_nofollow(child.file_name())?;+ windows_harden_private_tree_with(&opened, after_initial_directory_harden)?;+ } else if file_type.is_file() {+ let mut options = CapOpenOptions::new();+ options.read(true).follow(FollowSymlinks::No);+ let file = child.open_with(&options)?;+ windows_secure_handle(&file)?;+ } else {+ bail!(+ "refusing to harden extension directory containing special file {:?}",+ child.file_name()+ );+ }+ }+ // Reassert the directory after its descendants so a privileged service+ // cannot use the recursive walk as a window to restore an explicit ACE.+ windows_secure_handle(directory)+}++#[cfg(any(windows, test))]+fn converge_windows_acl_with<T>(+ attempts: u32,+ retry_window: std::time::Duration,+ mut elapsed: impl FnMut() -> std::time::Duration,+ mut sleep: impl FnMut(std::time::Duration),+ mut harden: impl FnMut() -> Result<()>,+ mut verify: impl FnMut() -> Result<T>,+) -> Result<T> {+ // Privileged Windows services can add an explicit ACE after a large tree is+ // hardened. Re-run hardening and the complete content verification as one+ // unit, but only for the typed drift signal and within strict bounds. The+ // retry window controls whether another blocking attempt may begin; it+ // cannot interrupt a Windows filesystem call that is already in flight.+ debug_assert!(attempts > 0);+ for attempt in 1..=attempts {+ if attempt > 1 && elapsed() >= retry_window {+ bail!(+ "extension tree Windows ACLs did not converge before the {:?} retry window after {} hardening attempt(s)",+ retry_window,+ attempt - 1+ );+ }+ let result = match harden() {+ Ok(()) => verify(),+ Err(error) => Err(error),+ };+ match result {+ Ok(value) => return Ok(value),+ Err(error) => {+ let retryable = error.downcast_ref::<WindowsAclDrift>().is_some();+ if !retryable {+ return Err(error);+ }+ if attempt == attempts {+ return Err(error).context(format!(+ "extension tree Windows ACLs did not converge after {attempt} hardening attempt(s)"+ ));+ }+ let remaining = retry_window.saturating_sub(elapsed());+ let backoff = std::time::Duration::from_millis(250 * u64::from(attempt));+ if remaining <= backoff {+ return Err(error).context(format!(+ "extension tree Windows ACLs did not converge before the {:?} retry window after {attempt} hardening attempt(s)",+ retry_window+ ));+ }+ sleep(backoff);+ }+ }+ }+ unreachable!("the final convergence attempt always returns")+}++#[cfg(any(windows, test))]+fn converge_windows_startup_verification_with<T>(+ attempts: u32,+ retry_window: std::time::Duration,+ elapsed: impl FnMut() -> std::time::Duration,+ sleep: impl FnMut(std::time::Duration),+ harden: impl FnMut() -> Result<()>,+ mut verify: impl FnMut() -> Result<T>,+) -> Result<T> {+ match verify() {+ Ok(value) => Ok(value),+ Err(error) if error.downcast_ref::<WindowsAclDrift>().is_some() => {+ converge_windows_acl_with(attempts, retry_window, elapsed, sleep, harden, verify)+ }+ Err(error) => Err(error),+ }+}++#[cfg(windows)]+fn converge_windows_acl<T>(+ attempts: u32,+ retry_window: Duration,+ harden: impl FnMut() -> Result<()>,+ verify: impl FnMut() -> Result<T>,+) -> Result<T> {+ let started = Instant::now();+ converge_windows_acl_with(+ attempts,+ retry_window,+ || started.elapsed(),+ std::thread::sleep,+ harden,+ verify,+ )+}++fn apply_manifest_permissions_at(root: &Dir, manifest: &ExtensionManifest) -> Result<()> {+ set_private_file_permissions_at(root, Path::new(MANIFEST_NAME), false)?;+ for file in &manifest.files {+ set_private_file_permissions_at(root, Path::new(&file.path), file.executable)?;+ }+ Ok(())+}++#[cfg(unix)]+fn set_private_file_permissions_at(root: &Dir, path: &Path, executable: bool) -> Result<()> {+ use cap_std::fs::PermissionsExt;+ let mut options = CapOpenOptions::new();+ options.read(true).follow(FollowSymlinks::No);+ let file = root.open_with(path, &options)?;+ file.set_permissions(cap_std::fs::Permissions::from_mode(if executable {+ 0o700+ } else {+ 0o600+ }))?;+ Ok(())+}++#[cfg(windows)]+fn set_private_file_permissions_at(root: &Dir, path: &Path, _executable: bool) -> Result<()> {+ let mut options = CapOpenOptions::new();+ options.read(true).follow(FollowSymlinks::No);+ let file = root.open_with(path, &options)?;+ windows_secure_handle(&file)+}++#[cfg(all(not(unix), not(windows)))]+fn set_private_file_permissions_at(_root: &Dir, _path: &Path, _executable: bool) -> Result<()> {+ Ok(())+}++fn verify_manifest_permissions_at(root: &Dir, manifest: &ExtensionManifest) -> Result<()> {+ verify_expected_file_permissions_at(root, Path::new(MANIFEST_NAME), false)?;+ verify_expected_file_permissions_at(root, Path::new(INSTALL_RECORD_NAME), false)?;+ for file in &manifest.files {+ verify_expected_file_permissions_at(root, Path::new(&file.path), file.executable)?;+ }+ Ok(())+}++#[cfg(unix)]+fn verify_expected_file_permissions_at(root: &Dir, path: &Path, executable: bool) -> Result<()> {+ use cap_std::fs::MetadataExt;+ let mut options = CapOpenOptions::new();+ options.read(true).follow(FollowSymlinks::No);+ let file = root.open_with(path, &options)?;+ let metadata = file.metadata()?;+ let expected = if executable { 0o700 } else { 0o600 };+ if metadata.uid() != rustix::process::geteuid().as_raw() || metadata.mode() & 0o777 != expected+ {+ bail!(+ "extension file {} has unsafe ownership or permissions",+ path.display()+ );+ }+ Ok(())+}++#[cfg(windows)]+fn verify_expected_file_permissions_at(root: &Dir, path: &Path, _executable: bool) -> Result<()> {+ let mut options = CapOpenOptions::new();+ options.read(true).follow(FollowSymlinks::No);+ let file = root.open_with(path, &options)?;+ windows_verify_file_handle(&file)+}++#[cfg(all(not(unix), not(windows)))]+fn verify_expected_file_permissions_at(_root: &Dir, _path: &Path, _executable: bool) -> Result<()> {+ Ok(())+}++fn open_existing_no_follow(path: &Path) -> Result<fs::File> {+ let (dir, name) = cap_parent(path)?;+ let mut options = CapOpenOptions::new();+ options.read(true).follow(FollowSymlinks::No);+ dir.open_with(name, &options)+ .map(cap_std::fs::File::into_std)+ .with_context(|| format!("open {} without following links", path.display()))+}++fn open_lock_file_at(dir: &Dir, name: &str) -> Result<fs::File> {+ let mut create = CapOpenOptions::new();+ create+ .read(true)+ .write(true)+ .create_new(true)+ .follow(FollowSymlinks::No);+ #[cfg(unix)]+ {+ use cap_std::fs::OpenOptionsExt;+ create.mode(0o600);+ }+ match dir.open_with(name, &create) {+ Ok(file) => {+ #[cfg(windows)]+ windows_secure_handle(&file)?;+ verify_private_cap_file_permissions(&file, name)?;+ sync_cap_dir(dir)?;+ Ok(file.into_std())+ }+ Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {+ let mut existing = CapOpenOptions::new();+ existing.read(true).write(true).follow(FollowSymlinks::No);+ let file = dir+ .open_with(name, &existing)+ .with_context(|| format!("open extension lock {name}"))?;+ verify_private_cap_file_permissions(&file, name)?;+ Ok(file.into_std())+ }+ Err(error) => Err(error).with_context(|| format!("create extension lock {name}")),+ }+}++fn acquire_extension_lock_with(+ retry_window: Duration,+ mut elapsed: impl FnMut() -> Duration,+ mut sleep: impl FnMut(Duration),+ mut try_lock: impl FnMut() -> std::io::Result<()>,+) -> std::io::Result<()> {+ loop {+ match try_lock() {+ Ok(()) => return Ok(()),+ Err(cause)+ if cause.kind() == std::io::ErrorKind::WouldBlock+ || cause.raw_os_error() == fs2::lock_contended_error().raw_os_error() =>+ {+ if elapsed() >= retry_window {+ return Err(cause);+ }+ sleep(EXTENSION_LOCK_RETRY_INTERVAL);+ }+ Err(cause) => return Err(cause),+ }+ }+}++#[cfg(any(windows, test))]+fn windows_acl_lease_name(id: &str) -> String {+ format!("{id}.runtime-acl.lock")+}++#[cfg(any(windows, test))]+fn acquire_windows_acl_lease_with(+ retry_window: Duration,+ mut elapsed: impl FnMut() -> Duration,+ mut sleep: impl FnMut(Duration),+ mut try_lock: impl FnMut() -> std::io::Result<()>,+) -> Result<()> {+ loop {+ match try_lock() {+ Ok(()) => return Ok(()),+ Err(cause)+ if cause.kind() == std::io::ErrorKind::WouldBlock+ || cause.raw_os_error() == fs2::lock_contended_error().raw_os_error() =>+ {+ if elapsed() >= retry_window {+ bail!("timed out waiting for the Windows ACL lease");+ }+ sleep(WINDOWS_ACL_LEASE_RETRY_INTERVAL);+ }+ Err(cause) => return Err(cause).context("acquire Windows ACL lease"),+ }+ }+}++#[cfg(any(windows, test))]+fn acquire_windows_acl_lease_and_recover_with(+ acquire: impl FnOnce() -> Result<()>,+ recover: impl FnOnce() -> Result<()>,+) -> Result<()> {+ acquire()?;+ recover()+}++#[cfg(windows)]+fn acquire_windows_acl_lease(file: &fs::File) -> Result<()> {+ let started = Instant::now();+ acquire_windows_acl_lease_with(+ WINDOWS_ACL_CONVERGENCE_RETRY_WINDOW,+ || started.elapsed(),+ std::thread::sleep,+ || file.try_lock_exclusive(),+ )+}++#[cfg(unix)]+fn verify_cap_directory_permissions(directory: &Dir) -> Result<()> {+ use cap_std::fs::MetadataExt;+ let metadata = directory.dir_metadata()?;+ if metadata.uid() != rustix::process::geteuid().as_raw() {+ bail!("extension directory is not owned by the current user");+ }+ let mode = metadata.mode() & 0o777;+ if mode != 0o700 {+ bail!("extension directory has unsafe permissions {mode:o}; expected 700");+ }+ Ok(())+}++#[cfg(windows)]+fn windows_verify_file_handle(file: &cap_std::fs::File) -> Result<()> {+ use cap_std::fs::MetadataExt as _;+ if file.metadata()?.file_attributes() & 0x400 != 0 {+ bail!("extension file is a Windows reparse point");+ }+ use std::os::windows::io::AsRawHandle as _;+ windows_verify_security(file.as_raw_handle().cast())+}++#[cfg(windows)]+fn windows_verify_directory_handle(directory: &Dir) -> Result<()> {+ windows_reject_reparse_directory(directory)?;+ use std::os::windows::io::AsRawHandle as _;+ windows_verify_security(directory.as_raw_handle().cast())+}++#[cfg(windows)]+fn windows_reject_reparse_directory(directory: &Dir) -> Result<()> {+ use cap_std::fs::MetadataExt as _;+ if directory.dir_metadata()?.file_attributes() & 0x400 != 0 {+ bail!("extension directory is a Windows reparse point");+ }+ Ok(())+}++#[cfg(windows)]+fn windows_secure_handle<T: std::os::windows::io::AsRawHandle>(handle: &T) -> Result<()> {+ windows_set_private_security(handle.as_raw_handle().cast())?;+ windows_verify_security(handle.as_raw_handle().cast())+}++#[cfg(windows)]+#[derive(Clone, Copy, Debug, Eq, PartialEq)]+struct WindowsFileIdentity {+ volume_serial_number: u32,+ file_index_high: u32,+ file_index_low: u32,+}++#[cfg(windows)]+#[repr(C)]+struct WindowsFileTime {+ low_date_time: u32,+ high_date_time: u32,+}++#[cfg(windows)]+#[repr(C)]+struct WindowsByHandleFileInformation {+ file_attributes: u32,+ creation_time: WindowsFileTime,+ last_access_time: WindowsFileTime,+ last_write_time: WindowsFileTime,+ volume_serial_number: u32,+ file_size_high: u32,+ file_size_low: u32,+ number_of_links: u32,+ file_index_high: u32,+ file_index_low: u32,+}++#[cfg(windows)]+fn windows_file_identity(handle: *mut std::ffi::c_void) -> Result<WindowsFileIdentity> {+ let information = windows_file_information(handle)?;+ Ok(WindowsFileIdentity {+ volume_serial_number: information.volume_serial_number,+ file_index_high: information.file_index_high,+ file_index_low: information.file_index_low,+ })+}++#[cfg(windows)]+fn windows_file_information(+ handle: *mut std::ffi::c_void,+) -> Result<WindowsByHandleFileInformation> {+ unsafe {+ #[link(name = "kernel32")]+ extern "system" {+ fn GetFileInformationByHandle(+ file: *mut std::ffi::c_void,+ information: *mut WindowsByHandleFileInformation,+ ) -> i32;+ }+ let mut information = std::mem::MaybeUninit::uninit();+ if GetFileInformationByHandle(handle, information.as_mut_ptr()) == 0 {+ return Err(std::io::Error::last_os_error())+ .context("read Windows extension object identity");+ }+ let information = information.assume_init();+ if information.file_attributes & 0x400 != 0 {+ bail!("extension object is a Windows reparse point");+ }+ Ok(information)+ }+}++#[cfg(windows)]+fn windows_final_path(handle: *mut std::ffi::c_void) -> Result<Vec<u16>> {+ unsafe {+ #[link(name = "kernel32")]+ extern "system" {+ fn GetFinalPathNameByHandleW(+ file: *mut std::ffi::c_void,+ path: *mut u16,+ path_size: u32,+ flags: u32,+ ) -> u32;+ }+ let required = GetFinalPathNameByHandleW(handle, std::ptr::null_mut(), 0, 0);+ if required == 0 {+ return Err(std::io::Error::last_os_error())+ .context("size Windows extension object path");+ }+ let mut path = vec![0_u16; required as usize];+ let written = GetFinalPathNameByHandleW(handle, path.as_mut_ptr(), path.len() as u32, 0);+ if written == 0 {+ return Err(std::io::Error::last_os_error())+ .context("read Windows extension object path");+ }+ if written as usize >= path.len() {+ bail!("Windows extension object path changed while it was read");+ }+ path.truncate(written as usize);+ path.push(0);+ Ok(path)+ }+}++#[cfg(windows)]+fn windows_verify_same_object(+ original: *mut std::ffi::c_void,+ reopened: *mut std::ffi::c_void,+) -> Result<()> {+ let original_identity = windows_file_identity(original)?;+ let reopened_identity = windows_file_identity(reopened)?;+ if original_identity != reopened_identity {+ bail!("extension object changed while reopening it for a Windows ACL update");+ }+ Ok(())+}++#[cfg(windows)]+fn windows_reopen_for_security(+ handle: *mut std::ffi::c_void,+) -> Result<std::os::windows::io::OwnedHandle> {+ use std::os::windows::io::FromRawHandle as _;++ unsafe {+ #[link(name = "kernel32")]+ extern "system" {+ fn CreateFileW(+ file_name: *const u16,+ desired_access: u32,+ share_mode: u32,+ security_attributes: *const std::ffi::c_void,+ creation_disposition: u32,+ flags_and_attributes: u32,+ template_file: *mut std::ffi::c_void,+ ) -> *mut std::ffi::c_void;+ }+ // Reopen the path reported by the capability handle itself. Opening+ // the reparse point prevents the final component from being followed.+ let path = windows_final_path(handle)?;+ let reopened = CreateFileW(+ path.as_ptr(),+ 0x0008_0000 | 0x0004_0000 | 0x0002_0000,+ 0x1 | 0x2 | 0x4,+ std::ptr::null(),+ 3,+ 0x0200_0000 | 0x0020_0000,+ std::ptr::null_mut(),+ );+ if reopened.is_null() || reopened as isize == -1 {+ return Err(std::io::Error::last_os_error())+ .context("reopen extension object for Windows ACL update");+ }+ let reopened = std::os::windows::io::OwnedHandle::from_raw_handle(reopened.cast());+ use std::os::windows::io::AsRawHandle as _;+ // A rename or replacement between path lookup and CreateFileW must not+ // redirect the ACL update to a different filesystem object.+ windows_verify_same_object(handle, reopened.as_raw_handle().cast())?;+ Ok(reopened)+ }+}++#[cfg(windows)]+#[repr(C)]+struct WindowsAcl {+ revision: u8,+ sbz1: u8,+ size: u16,+ ace_count: u16,+ sbz2: u16,+}++#[cfg(windows)]+#[repr(C)]+struct WindowsAceHeader {+ ace_type: u8,+ ace_flags: u8,+ ace_size: u16,+}++#[cfg(windows)]+#[repr(C)]+struct WindowsAccessAllowedAce {+ header: WindowsAceHeader,+ mask: u32,+ sid_start: u32,+}++#[cfg(windows)]+unsafe fn windows_current_user_sid() -> Result<Vec<u8>> {+ #[repr(C)]+ struct SidAndAttributes {+ sid: *mut std::ffi::c_void,+ attributes: u32,+ }+ #[repr(C)]+ struct TokenUser {+ user: SidAndAttributes,+ }+ #[link(name = "kernel32")]+ extern "system" {+ fn GetCurrentProcess() -> *mut std::ffi::c_void;+ fn CloseHandle(handle: *mut std::ffi::c_void) -> i32;+ }+ #[link(name = "advapi32")]+ extern "system" {+ fn OpenProcessToken(+ process: *mut std::ffi::c_void,+ desired_access: u32,+ token: *mut *mut std::ffi::c_void,+ ) -> i32;+ fn GetTokenInformation(+ token: *mut std::ffi::c_void,+ class: u32,+ information: *mut std::ffi::c_void,+ length: u32,+ required: *mut u32,+ ) -> i32;+ fn GetLengthSid(sid: *mut std::ffi::c_void) -> u32;+ }+ let mut token = std::ptr::null_mut();+ if OpenProcessToken(GetCurrentProcess(), 0x0008, &mut token) == 0 {+ bail!("open current process token for extension ACL");+ }+ let mut required = 0;+ let _ = GetTokenInformation(token, 1, std::ptr::null_mut(), 0, &mut required);+ let mut buffer = vec![0_u8; required as usize];+ let ok = required != 0+ && GetTokenInformation(+ token,+ 1,+ buffer.as_mut_ptr().cast(),+ required,+ &mut required,+ ) != 0;+ let _ = CloseHandle(token);+ if !ok {+ bail!("read current process user SID for extension ACL");+ }+ let token_user = std::ptr::read_unaligned(buffer.as_ptr().cast::<TokenUser>());+ let length = GetLengthSid(token_user.user.sid);+ if length == 0 {+ bail!("current process user SID is invalid");+ }+ Ok(std::slice::from_raw_parts(token_user.user.sid.cast::<u8>(), length as usize).to_vec())+}++#[cfg(windows)]+unsafe fn windows_sid_string(sid: *mut std::ffi::c_void) -> Result<String> {+ #[link(name = "advapi32")]+ extern "system" {+ fn ConvertSidToStringSidW(sid: *mut std::ffi::c_void, value: *mut *mut u16) -> i32;+ }+ #[link(name = "kernel32")]+ extern "system" {+ fn LocalFree(memory: *mut std::ffi::c_void) -> *mut std::ffi::c_void;+ }+ let mut value = std::ptr::null_mut();+ if ConvertSidToStringSidW(sid, &mut value) == 0 || value.is_null() {+ bail!("convert Windows SID for extension ACL");+ }+ let length = (0..).find(|&index| *value.add(index) == 0).unwrap_or(0);+ let result = String::from_utf16_lossy(std::slice::from_raw_parts(value, length));+ let _ = LocalFree(value.cast());+ Ok(result)+}++#[cfg(windows)]+fn windows_set_private_security(handle: *mut std::ffi::c_void) -> Result<()> {+ unsafe {+ #[link(name = "advapi32")]+ extern "system" {+ fn ConvertStringSecurityDescriptorToSecurityDescriptorW(+ value: *const u16,+ revision: u32,+ descriptor: *mut *mut std::ffi::c_void,+ size: *mut u32,+ ) -> i32;+ fn GetSecurityDescriptorDacl(+ descriptor: *mut std::ffi::c_void,+ present: *mut i32,+ dacl: *mut *mut WindowsAcl,+ defaulted: *mut i32,+ ) -> i32;+ fn SetSecurityInfo(+ handle: *mut std::ffi::c_void,+ object_type: i32,+ information: u32,+ owner: *mut std::ffi::c_void,+ group: *mut std::ffi::c_void,+ dacl: *mut WindowsAcl,+ sacl: *mut WindowsAcl,+ ) -> u32;+ }+ #[link(name = "kernel32")]+ extern "system" {+ fn LocalFree(memory: *mut std::ffi::c_void) -> *mut std::ffi::c_void;+ }+ let user = windows_current_user_sid()?;+ let user_ptr = user.as_ptr().cast_mut().cast();+ let inheritance = if windows_file_information(handle)?.file_attributes & 0x10 != 0 {+ "OICI"+ } else {+ ""+ };+ let sddl = format!(+ "D:P(A;{inheritance};FA;;;{})(A;{inheritance};FA;;;SY)(A;{inheritance};FA;;;BA)",+ windows_sid_string(user_ptr)?+ );+ let wide = sddl+ .encode_utf16()+ .chain(std::iter::once(0))+ .collect::<Vec<_>>();+ let mut descriptor = std::ptr::null_mut();+ if ConvertStringSecurityDescriptorToSecurityDescriptorW(+ wide.as_ptr(),+ 1,+ &mut descriptor,+ std::ptr::null_mut(),+ ) == 0+ {+ bail!("build private extension ACL");+ }+ let mut present = 0;+ let mut defaulted = 0;+ let mut dacl = std::ptr::null_mut();+ let got_dacl =+ GetSecurityDescriptorDacl(descriptor, &mut present, &mut dacl, &mut defaulted);+ let result = if got_dacl == 0 || present == 0 || dacl.is_null() {+ Err(anyhow!("private extension ACL has no DACL"))+ } else {+ (|| -> Result<()> {+ let security_handle = windows_reopen_for_security(handle)?;+ use std::os::windows::io::AsRawHandle as _;+ let status = SetSecurityInfo(+ security_handle.as_raw_handle().cast(),+ 1,+ 0x1 | 0x4 | 0x8000_0000,+ user_ptr,+ std::ptr::null_mut(),+ dacl,+ std::ptr::null_mut(),+ );+ if status == 0 {+ Ok(())+ } else {+ Err(anyhow!(+ "set private extension ACL failed with Windows error {status}"+ ))+ }+ })()+ };+ let _ = LocalFree(descriptor);+ result+ }+}++#[cfg(windows)]+fn windows_verify_security(handle: *mut std::ffi::c_void) -> Result<()> {+ unsafe {+ #[link(name = "advapi32")]+ extern "system" {+ fn GetSecurityInfo(+ handle: *mut std::ffi::c_void,+ object_type: i32,+ information: u32,+ owner: *mut *mut std::ffi::c_void,+ group: *mut *mut std::ffi::c_void,+ dacl: *mut *mut WindowsAcl,+ sacl: *mut *mut WindowsAcl,+ descriptor: *mut *mut std::ffi::c_void,+ ) -> u32;+ fn GetSecurityDescriptorControl(+ descriptor: *mut std::ffi::c_void,+ control: *mut u16,+ revision: *mut u32,+ ) -> i32;+ fn GetAce(acl: *const WindowsAcl, index: u32, ace: *mut *mut std::ffi::c_void) -> i32;+ fn EqualSid(left: *mut std::ffi::c_void, right: *mut std::ffi::c_void) -> i32;+ fn IsWellKnownSid(sid: *mut std::ffi::c_void, kind: i32) -> i32;+ }+ #[link(name = "kernel32")]+ extern "system" {+ fn LocalFree(memory: *mut std::ffi::c_void) -> *mut std::ffi::c_void;+ }+ let user = windows_current_user_sid()?;+ let user_ptr = user.as_ptr().cast_mut().cast();+ let object = windows_final_path(handle)+ .map(|path| {+ String::from_utf16_lossy(path.strip_suffix(&[0]).unwrap_or(path.as_slice()))+ })+ .unwrap_or_else(|_| "<unresolved extension object>".to_owned());+ let mut owner = std::ptr::null_mut();+ let mut dacl = std::ptr::null_mut();+ let mut descriptor = std::ptr::null_mut();+ let status = GetSecurityInfo(+ handle,+ 1,+ 0x1 | 0x4,+ &mut owner,+ std::ptr::null_mut(),+ &mut dacl,+ std::ptr::null_mut(),+ &mut descriptor,+ );+ if status != 0 {+ bail!("read extension ACL failed with Windows error {status}");+ }+ let result = (|| -> Result<()> {+ if owner.is_null() || EqualSid(owner, user_ptr) == 0 {+ bail!("extension object is not owned by the current Windows user");+ }+ if dacl.is_null() {+ bail!("extension object has an unprotected or absent Windows DACL");+ }+ let mut control = 0_u16;+ let mut revision = 0_u32;+ if GetSecurityDescriptorControl(descriptor, &mut control, &mut revision) == 0+ || control & 0x1000 == 0+ {+ bail!("extension object Windows DACL is not protected");+ }+ let mut user_full_control = false;+ for index in 0..(*dacl).ace_count as u32 {+ let mut raw = std::ptr::null_mut();+ if GetAce(dacl, index, &mut raw) == 0 || raw.is_null() {+ bail!("read extension Windows ACL entry {index} for {object}");+ }+ let ace = &*(raw.cast::<WindowsAccessAllowedAce>());+ if ace.header.ace_type == 1 {+ continue;+ }+ if ace.header.ace_type != 0 {+ bail!(+ "extension Windows ACL for {object} contains unsupported ACE {index}: type={}, flags=0x{:02x}, mask=0x{:08x}",+ ace.header.ace_type,+ ace.header.ace_flags,+ ace.mask+ );+ }+ let sid = std::ptr::addr_of!(ace.sid_start).cast_mut().cast();+ let is_user = EqualSid(sid, user_ptr) != 0;+ let is_system = IsWellKnownSid(sid, 22) != 0;+ let is_admin = IsWellKnownSid(sid, 26) != 0;+ if !is_user && !is_system && !is_admin {+ let sid = windows_sid_string(sid)+ .unwrap_or_else(|_| "<invalid Windows SID>".to_owned());+ return Err(anyhow!(WindowsAclDrift).context(format!(+ "extension Windows ACL for {object} grants access to untrusted principal {sid} in ACE {index}: flags=0x{:02x}, mask=0x{:08x}, inherited={}",+ ace.header.ace_flags,+ ace.mask,+ ace.header.ace_flags & 0x10 != 0+ )));+ }+ if is_user && ace.mask & 0x001f_01ff == 0x001f_01ff {+ user_full_control = true;+ }+ }+ if !user_full_control {+ bail!("extension Windows ACL does not grant the owner full control");+ }+ Ok(())+ })();+ let _ = LocalFree(descriptor);+ result+ }+}++fn safe_relative_path(path: &Path) -> Result<PathBuf> {+ let mut result = PathBuf::new();+ for component in path.components() {+ match component {+ Component::Normal(segment) => {+ let segment = segment.to_str().ok_or_else(|| {+ anyhow!("archive path is not valid UTF-8: {}", path.display())+ })?;+ if segment.contains('\\') {+ bail!("archive contains non-portable path {}", path.display());+ }+ result.push(segment);+ }+ _ => bail!("archive contains unsafe path {}", path.display()),+ }+ }+ Ok(result)+}++#[cfg(unix)]+fn verify_cap_directory_permissions_portable(directory: &Dir) -> Result<()> {+ verify_cap_directory_permissions(directory)+}++#[cfg(not(unix))]+fn verify_cap_directory_permissions_portable(directory: &Dir) -> Result<()> {+ #[cfg(windows)]+ return windows_verify_directory_handle(directory);+ #[cfg(not(windows))]+ Ok(())+}++fn safe_manifest_path(path: &str) -> Result<()> {+ if path.is_empty()+ || safe_relative_path(Path::new(path))?+ .to_string_lossy()+ .replace('\\', "/")+ != path+ {+ bail!("manifest contains unsafe or non-canonical path {path:?}");+ }+ Ok(())+}++fn validate_version_segment(version: &str) -> Result<()> {+ let parsed =+ Version::parse(version).context("active version is not valid semantic versioning")?;+ if parsed.to_string() != version {+ bail!("active version is not canonical semantic versioning");+ }+ Ok(())+}++fn hex_sha256(bytes: &[u8]) -> String {+ format!("{:x}", Sha256::digest(bytes))+}++fn validate_sha256(label: &str, value: &str) -> Result<()> {+ if value.len() != 64+ || !value.bytes().all(|byte| byte.is_ascii_hexdigit())+ || value.bytes().any(|byte| byte.is_ascii_uppercase())+ {+ bail!("invalid canonical SHA-256 for {label}");+ }+ Ok(())+}++fn read_small_local_file(path: &Path) -> Result<Vec<u8>> {+ let file = open_existing_no_follow(path)?;+ let metadata = file.metadata()?;+ if !metadata.is_file() || metadata.len() > MAX_IN_MEMORY_BYTES {+ bail!("file is not a bounded regular file: {}", path.display());+ }+ let mut bytes = Vec::with_capacity(metadata.len() as usize);+ file.take(MAX_IN_MEMORY_BYTES + 1).read_to_end(&mut bytes)?;+ if bytes.len() as u64 > MAX_IN_MEMORY_BYTES {+ bail!("file exceeds the in-memory limit: {}", path.display());+ }+ Ok(bytes)+}++fn hash_open_file(file: &mut fs::File, limit: u64) -> Result<String> {+ let metadata = file.metadata()?;+ if !metadata.is_file() || metadata.len() > limit {+ bail!("archive exceeds the {limit} byte limit");+ }+ let mut hasher = Sha256::new();+ let mut total = 0_u64;+ let mut buffer = [0_u8; 64 * 1024];+ loop {+ let read = file.read(&mut buffer)?;+ if read == 0 {+ break;+ }+ total += read as u64;+ if total > limit {+ bail!("archive exceeds the {limit} byte limit");+ }+ hasher.update(&buffer[..read]);+ }+ Ok(format!("{:x}", hasher.finalize()))+}++fn unique_name(id: &str) -> String {+ let counter = UNIQUE_COUNTER.fetch_add(1, Ordering::Relaxed);+ format!("{id}-{}-{counter}", std::process::id())+}++fn current_target() -> Result<String> {+ target_triple(+ std::env::consts::OS,+ std::env::consts::ARCH,+ option_env!("CARGO_CFG_TARGET_ENV").unwrap_or(if cfg!(target_env = "musl") {+ "musl"+ } else if cfg!(target_env = "msvc") {+ "msvc"+ } else if cfg!(target_env = "gnu") {+ "gnu"+ } else {+ ""+ }),+ )+}++fn target_triple(os: &str, arch: &str, abi: &str) -> Result<String> {+ let triple = match (os, arch, abi) {+ ("macos", "x86_64" | "aarch64", "") => format!("{arch}-apple-darwin"),+ ("windows", "x86_64" | "aarch64", "msvc") => format!("{arch}-pc-windows-msvc"),+ ("linux", "x86_64" | "aarch64", "gnu") => format!("{arch}-unknown-linux-gnu"),+ ("linux", "x86_64" | "aarch64", "musl") => format!("{arch}-unknown-linux-musl"),+ _ => bail!("extension archives are unsupported on target OS={os} arch={arch} ABI={abi}"),+ };+ Ok(triple)+}++#[cfg(test)]+mod tests {+ use super::*;+ use flate2::{write::GzEncoder, Compression};+ use std::cell::Cell;+ use std::io::Cursor;+ use tempfile::TempDir;++ #[cfg(feature = "review-trust-root")]+ const REVIEW_SEED: [u8; 32] = [+ 0x9d, 0x61, 0xb1, 0x9d, 0xef, 0xfd, 0x5a, 0x60, 0xba, 0x84, 0x4a, 0xf4, 0x92, 0xec, 0x2c,+ 0xc4, 0x44, 0x49, 0xc5, 0x69, 0x7b, 0x32, 0x69, 0x19, 0x70, 0x3b, 0xac, 0x03, 0x1c, 0xae,+ 0x7f, 0x60,+ ];++ fn acl_drift_error() -> anyhow::Error {+ anyhow!(WindowsAclDrift)+ .context("extension Windows ACL grants access to untrusted principal in test fixture")+ }++ #[test]+ fn windows_acl_convergence_retries_drift_then_succeeds() {+ let hardens = Cell::new(0);+ let verifies = Cell::new(0);+ let sleeps = Cell::new(0);+ let value = converge_windows_acl_with(+ 3,+ std::time::Duration::from_secs(90),+ || std::time::Duration::ZERO,+ |_| sleeps.set(sleeps.get() + 1),+ || {+ hardens.set(hardens.get() + 1);+ Ok(())+ },+ || {+ verifies.set(verifies.get() + 1);+ if verifies.get() == 1 {+ Err(acl_drift_error())+ } else {+ Ok("verified")+ }+ },+ )+ .unwrap();++ assert_eq!(value, "verified");+ assert_eq!(hardens.get(), 2);+ assert_eq!(verifies.get(), 2);+ assert_eq!(sleeps.get(), 1);+ }++ #[test]+ fn windows_acl_convergence_retries_hardening_drift_then_succeeds() {+ let hardens = Cell::new(0);+ let verifies = Cell::new(0);+ let sleeps = Cell::new(0);+ let value = converge_windows_acl_with(+ 3,+ std::time::Duration::from_secs(90),+ || std::time::Duration::ZERO,+ |_| sleeps.set(sleeps.get() + 1),+ || {+ hardens.set(hardens.get() + 1);+ if hardens.get() == 1 {+ Err(acl_drift_error())+ } else {+ Ok(())+ }+ },+ || {+ verifies.set(verifies.get() + 1);+ Ok("verified")+ },+ )+ .unwrap();++ assert_eq!(value, "verified");+ assert_eq!(hardens.get(), 2);+ assert_eq!(verifies.get(), 1);+ assert_eq!(sleeps.get(), 1);+ }++ #[test]+ fn windows_acl_convergence_stops_after_persistent_hardening_drift() {+ let hardens = Cell::new(0);+ let verifies = Cell::new(0);+ let error = converge_windows_acl_with::<()>(+ 3,+ std::time::Duration::from_secs(90),+ || std::time::Duration::ZERO,+ |_| {},+ || {+ hardens.set(hardens.get() + 1);+ Err(acl_drift_error())+ },+ || {+ verifies.set(verifies.get() + 1);+ Ok(())+ },+ )+ .unwrap_err();++ assert!(error.downcast_ref::<WindowsAclDrift>().is_some());+ assert!(error+ .to_string()+ .contains("did not converge after 3 hardening attempt(s)"));+ assert_eq!(hardens.get(), 3);+ assert_eq!(verifies.get(), 0);+ }++ #[test]+ fn windows_acl_lease_retries_contention_until_acquired() {+ let attempts = Cell::new(0);+ let elapsed = Cell::new(Duration::ZERO);+ let sleeps = Cell::new(0);+ acquire_windows_acl_lease_with(+ Duration::from_secs(1),+ || elapsed.get(),+ |duration| {+ sleeps.set(sleeps.get() + 1);+ elapsed.set(elapsed.get() + duration);+ },+ || {+ attempts.set(attempts.get() + 1);+ if attempts.get() < 3 {+ Err(fs2::lock_contended_error())+ } else {+ Ok(())+ }+ },+ )+ .unwrap();++ assert_eq!(attempts.get(), 3);+ assert_eq!(sleeps.get(), 2);+ }++ #[test]+ fn extension_lock_retries_transient_contention_until_acquired() {+ let attempts = Cell::new(0);+ let elapsed = Cell::new(Duration::ZERO);+ let sleeps = Cell::new(0);+ acquire_extension_lock_with(+ Duration::from_secs(1),+ || elapsed.get(),+ |duration| {+ sleeps.set(sleeps.get() + 1);+ elapsed.set(elapsed.get() + duration);+ },+ || {+ attempts.set(attempts.get() + 1);+ if attempts.get() < 3 {+ Err(fs2::lock_contended_error())+ } else {+ Ok(())+ }+ },+ )+ .unwrap();++ assert_eq!(attempts.get(), 3);+ assert_eq!(sleeps.get(), 2);+ }++ #[test]+ fn extension_lock_returns_persistent_contention_after_retry_window() {+ let attempts = Cell::new(0);+ let error = acquire_extension_lock_with(+ Duration::ZERO,+ || Duration::ZERO,+ |_| panic!("an expired extension lock wait must not sleep"),+ || {+ attempts.set(attempts.get() + 1);+ Err(fs2::lock_contended_error())+ },+ )+ .unwrap_err();++ assert_eq!(attempts.get(), 1);+ assert_eq!(+ error.raw_os_error(),+ fs2::lock_contended_error().raw_os_error()+ );+ }++ #[test]+ fn windows_acl_lease_name_is_component_scoped() {+ assert_eq!(+ windows_acl_lease_name(PERCEPTION_ID),+ "cua-perception.runtime-acl.lock"+ );+ }++ #[test]+ fn extension_hooks_forbid_deferred_windows_acl_cleanup() {+ let root = Path::new("extension-root");+ let journal = Some(PathBuf::from("runtime-acl.lock.profile"));+ let limits = extension_hook_containment_limits(root, journal.clone());++ assert_eq!(limits.additional_readable_paths, vec![root.to_path_buf()]);+ assert!(limits.windows_require_synchronous_cleanup);+ assert!(limits.windows_acl_lease_path.is_none());+ assert_eq!(limits.windows_acl_profile_journal_path, journal);+ }++ #[test]+ fn lifecycle_acl_lock_recovers_before_entering_the_critical_section() {+ let acquired = Cell::new(false);+ let recovered = Cell::new(false);+ acquire_windows_acl_lease_and_recover_with(+ || {+ acquired.set(true);+ Ok(())+ },+ || {+ assert!(acquired.get());+ recovered.set(true);+ Ok(())+ },+ )+ .unwrap();++ assert!(recovered.get());+ }++ #[test]+ fn windows_acl_lease_timeout_never_enters_the_critical_section() {+ let attempts = Cell::new(0);+ let error = acquire_windows_acl_lease_with(+ Duration::ZERO,+ || Duration::ZERO,+ |_| panic!("an expired ACL lease wait must not sleep"),+ || {+ attempts.set(attempts.get() + 1);+ Err(fs2::lock_contended_error())+ },+ )+ .unwrap_err();++ assert_eq!(attempts.get(), 1);+ assert!(error+ .to_string()+ .contains("timed out waiting for the Windows ACL lease"));+ }++ #[test]+ fn windows_acl_convergence_stops_after_persistent_drift() {+ let hardens = Cell::new(0);+ let verifies = Cell::new(0);+ let error = converge_windows_acl_with::<()>(+ 3,+ std::time::Duration::from_secs(90),+ || std::time::Duration::ZERO,+ |_| {},+ || {+ hardens.set(hardens.get() + 1);+ Ok(())+ },+ || {+ verifies.set(verifies.get() + 1);+ Err(acl_drift_error())+ },+ )+ .unwrap_err();++ assert!(error.downcast_ref::<WindowsAclDrift>().is_some());+ assert!(error+ .to_string()+ .contains("did not converge after 3 hardening attempt(s)"));+ assert_eq!(hardens.get(), 3);+ assert_eq!(verifies.get(), 3);+ }++ #[test]+ fn windows_acl_convergence_does_not_retry_matching_untyped_text() {+ let hardens = Cell::new(0);+ let error = converge_windows_acl_with::<()>(+ 3,+ std::time::Duration::from_secs(90),+ || std::time::Duration::ZERO,+ |_| panic!("non-drift verification failure must not sleep"),+ || {+ hardens.set(hardens.get() + 1);+ Ok(())+ },+ || bail!("extension Windows ACL grants access to untrusted principal"),+ )+ .unwrap_err();++ assert!(error.downcast_ref::<WindowsAclDrift>().is_none());+ assert_eq!(hardens.get(), 1);+ }++ #[test]+ fn windows_acl_convergence_does_not_retry_hardening_failure() {+ let hardens = Cell::new(0);+ let verifies = Cell::new(0);+ let error = converge_windows_acl_with::<()>(+ 3,+ std::time::Duration::from_secs(90),+ || std::time::Duration::ZERO,+ |_| panic!("hardening failure must not sleep"),+ || {+ hardens.set(hardens.get() + 1);+ bail!("hardening failed")+ },+ || {+ verifies.set(verifies.get() + 1);+ Ok(())+ },+ )+ .unwrap_err();++ assert_eq!(error.to_string(), "hardening failed");+ assert_eq!(hardens.get(), 1);+ assert_eq!(verifies.get(), 0);+ }++ #[test]+ fn windows_acl_convergence_honors_retry_window_after_attempt() {+ let hardens = Cell::new(0);+ let sleeps = Cell::new(0);+ let elapsed = Cell::new(std::time::Duration::ZERO);+ let error = converge_windows_acl_with::<()>(+ 3,+ std::time::Duration::from_millis(250),+ || elapsed.get(),+ |_| sleeps.set(sleeps.get() + 1),+ || {+ hardens.set(hardens.get() + 1);+ Ok(())+ },+ || {+ elapsed.set(std::time::Duration::from_millis(300));+ Err(acl_drift_error())+ },+ )+ .unwrap_err();++ assert!(error+ .to_string()+ .contains("did not converge before the 250ms retry window"));+ assert!(error.downcast_ref::<WindowsAclDrift>().is_some());+ assert_eq!(hardens.get(), 1);+ assert_eq!(sleeps.get(), 0);+ }++ #[test]+ fn windows_startup_verification_hardens_and_retries_typed_acl_drift() {+ let hardens = Cell::new(0);+ let verifies = Cell::new(0);+ let sleeps = Cell::new(0);+ let manifest = converge_windows_startup_verification_with(+ 3,+ std::time::Duration::from_secs(90),+ || std::time::Duration::ZERO,+ |_| sleeps.set(sleeps.get() + 1),+ || {+ hardens.set(hardens.get() + 1);+ Ok(())+ },+ || {+ verifies.set(verifies.get() + 1);+ if verifies.get() == 1 {+ Err(acl_drift_error())+ } else {+ Ok("startup manifest")+ }+ },+ )+ .unwrap();++ assert_eq!(manifest, "startup manifest");+ assert_eq!(hardens.get(), 1);+ assert_eq!(verifies.get(), 2);+ assert_eq!(sleeps.get(), 0);+ }++ #[test]+ fn windows_startup_verification_does_not_rewrite_a_healthy_tree() {+ let hardens = Cell::new(0);+ let verifies = Cell::new(0);+ let manifest = converge_windows_startup_verification_with(+ 3,+ std::time::Duration::from_secs(90),+ || std::time::Duration::ZERO,+ |_| panic!("healthy startup verification must not sleep"),+ || {+ hardens.set(hardens.get() + 1);+ Ok(())+ },+ || {+ verifies.set(verifies.get() + 1);+ Ok("startup manifest")+ },+ )+ .unwrap();++ assert_eq!(manifest, "startup manifest");+ assert_eq!(hardens.get(), 0);+ assert_eq!(verifies.get(), 1);+ }++ #[test]+ fn windows_startup_verification_preserves_non_acl_failure() {+ let hardens = Cell::new(0);+ let verifies = Cell::new(0);+ let error = converge_windows_startup_verification_with::<()>(+ 3,+ std::time::Duration::from_secs(90),+ || std::time::Duration::ZERO,+ |_| panic!("non-ACL startup verification failure must not sleep"),+ || {+ hardens.set(hardens.get() + 1);+ Ok(())+ },+ || {+ verifies.set(verifies.get() + 1);+ bail!("SHA-256 mismatch for startup worker")+ },+ )+ .unwrap_err();++ assert_eq!(error.to_string(), "SHA-256 mismatch for startup worker");+ assert!(error.downcast_ref::<WindowsAclDrift>().is_none());+ assert_eq!(hardens.get(), 0);+ assert_eq!(verifies.get(), 1);+ }++ fn fixture_archive(+ directory: &Path,+ version: &str,+ target: &str,+ protocol: u32,+ payload: &[u8],+ ) -> PathBuf {+ fixture_archive_with(+ directory,+ version,+ target,+ protocol,+ payload,+ &hex_sha256(payload),+ &format!("={}", env!("CARGO_PKG_VERSION")),+ )+ }++ fn perception_fixture_archive(directory: &Path, version: &str, runtime_name: &str) -> PathBuf {+ let worker = b"fixture-worker";+ let helper = b"fixture-helper";+ let model_manifest = b"{}";+ let runtime = b"fixture-runtime";+ let model = b"fixture-model";+ let dictionary = b"fixture-dictionary";+ let notice = b"fixture-notice";+ let worker_name = if cfg!(windows) {+ "cua-perception.exe"+ } else {+ "cua-perception"+ };+ let installed_runtime_name = if cfg!(target_os = "windows") {+ "onnxruntime.dll"+ } else if cfg!(target_os = "macos") {+ "libonnxruntime.dylib"+ } else {+ "libonnxruntime.so"+ };+ let contract = serde_json::to_vec(&serde_json::json!({+ "$schema": "runtime-contract.schema.json",+ "schemaVersion": 1,+ "target": current_target().unwrap(),+ "protocolVersion": 1,+ "worker": {"name": worker_name, "sha256": hex_sha256(worker)},+ "runtime": {"name": runtime_name, "sha256": hex_sha256(runtime)},+ "modelManifest": {"name": "model-manifest.json", "sha256": hex_sha256(model_manifest)},+ "models": [+ {"name": "icon.onnx", "role": "icon-detect", "sha256": hex_sha256(model)},+ {"name": "ocr-det.onnx", "role": "ocr-detect", "sha256": hex_sha256(model)},+ {"name": "ocr-rec.onnx", "role": "ocr-recognize", "sha256": hex_sha256(model)}+ ],+ "dictionary": {"name": "dictionary.txt", "role": "ocr-dictionary", "sha256": hex_sha256(dictionary)},+ "rejectMismatch": true+ }))+ .unwrap();+ let entrypoint = format!("bin/{worker_name}");+ let runtime_path = format!("runtime/{installed_runtime_name}");+ let files = vec![+ (entrypoint.clone(), worker.as_slice(), true),+ ("bin/helper.dat".to_owned(), helper.as_slice(), false),+ (+ "models/model-manifest.json".to_owned(),+ model_manifest.as_slice(),+ false,+ ),+ (runtime_path, runtime.as_slice(), false),+ ("models/icon.onnx".to_owned(), model.as_slice(), false),+ ("models/ocr-det.onnx".to_owned(), model.as_slice(), false),+ ("models/ocr-rec.onnx".to_owned(), model.as_slice(), false),+ (+ "models/dictionary.txt".to_owned(),+ dictionary.as_slice(),+ false,+ ),+ (+ PERCEPTION_RUNTIME_CONTRACT.to_owned(),+ contract.as_slice(),+ false,+ ),+ (+ "notices/THIRD_PARTY_NOTICES.md".to_owned(),+ notice.as_slice(),+ false,+ ),+ ];+ let manifest = ExtensionManifest {+ schema_version: 1,+ id: PERCEPTION_ID.to_owned(),+ version: version.to_owned(),+ driver_version: format!("={}", env!("CARGO_PKG_VERSION")),+ protocol_version: 1,+ target: current_target().unwrap(),+ entrypoint,+ files: files+ .iter()+ .map(|(path, bytes, executable)| ManifestFile {+ path: path.clone(),+ sha256: hex_sha256(bytes),+ executable: *executable,+ })+ .collect(),+ models: Vec::new(),+ components: vec![ComponentLicense {+ name: PERCEPTION_ID.to_owned(),+ version: version.to_owned(),+ license: "Apache-2.0".to_owned(),+ notice: "fixture".to_owned(),+ source_uri: "https://github.com/trycua/cua".to_owned(),+ source_revision: "fixture".to_owned(),+ notice_file: None,+ }],+ corresponding_source_file: None,+ license: "Apache-2.0".to_owned(),+ source: "https://github.com/trycua/cua".to_owned(),+ corresponding_source_uri: "https://github.com/trycua/cua".to_owned(),+ corresponding_source_revision: "fixture".to_owned(),+ provenance: "fixture".to_owned(),+ health_args: Vec::new(),+ self_test_args: Vec::new(),+ };+ let path = directory.join(format!("perception-{version}.tar.gz"));+ let file = fs::File::create(&path).unwrap();+ let encoder = GzEncoder::new(file, Compression::default());+ let mut builder = tar::Builder::new(encoder);+ append(+ &mut builder,+ MANIFEST_NAME,+ &serde_json::to_vec_pretty(&manifest).unwrap(),+ );+ for (relative, bytes, _) in files {+ append(&mut builder, &relative, bytes);+ }+ builder.finish().unwrap();+ path+ }++ #[test]+ fn absent_perception_extension_has_no_worker_config() {+ let temp = TempDir::new().unwrap();+ let store = ExtensionStore::new(temp.path().join("extensions"));+ assert!(perception_worker_config_in(&store).unwrap().is_none());+ assert!(!store.root.exists());+ }++ #[test]+ fn active_perception_extension_resolves_owned_worker_arguments() {+ let temp = TempDir::new().unwrap();+ let store = ExtensionStore::new(temp.path().join("extensions"));+ let runtime_name = if cfg!(target_os = "windows") {+ "onnxruntime.dll"+ } else if cfg!(target_os = "macos") {+ "libonnxruntime.dylib"+ } else {+ "libonnxruntime.so"+ };+ let archive = perception_fixture_archive(temp.path(), "1.0.0", runtime_name);+ store+ .install_archive(registry_entry(PERCEPTION_ID).unwrap(), &archive)+ .unwrap();++ let config = perception_worker_config_in(&store).unwrap().unwrap();+ assert!(config.executable.ends_with(if cfg!(windows) {+ "bin/cua-perception.exe"+ } else {+ "bin/cua-perception"+ }));+ assert_eq!(config.args[0], "--manifest");+ assert!(config.args[1].ends_with("models/model-manifest.json"));+ assert_eq!(config.args[2], "--onnx-runtime-library");+ assert!(config.args[3].ends_with(&format!("runtime/{runtime_name}")));+ assert_eq!(+ &config.args[4..],+ [+ "--extension-id",+ "cua-perception",+ "--extension-version",+ "1.0.0"+ ]+ );+ assert!(config.warm_worker.is_none());+ assert_eq!(+ config+ .expected_extension_identity+ .as_ref()+ .map(|identity| (identity.id.as_str(), identity.version.as_str(),)),+ Some(("cua-perception", "1.0.0"))+ );+ }++ #[test]+ fn perception_startup_rejects_tampered_execution_inputs() {+ let runtime_name = if cfg!(target_os = "windows") {+ "onnxruntime.dll"+ } else if cfg!(target_os = "macos") {+ "libonnxruntime.dylib"+ } else {+ "libonnxruntime.so"+ };+ let worker = if cfg!(windows) {+ "bin/cua-perception.exe"+ } else {+ "bin/cua-perception"+ };+ for relative in [+ worker.to_owned(),+ "bin/helper.dat".to_owned(),+ "models/model-manifest.json".to_owned(),+ "models/icon.onnx".to_owned(),+ format!("runtime/{runtime_name}"),+ "models/dictionary.txt".to_owned(),+ PERCEPTION_RUNTIME_CONTRACT.to_owned(),+ ] {+ let temp = TempDir::new().unwrap();+ let store = ExtensionStore::new(temp.path().join("extensions"));+ let archive = perception_fixture_archive(temp.path(), "1.0.0", runtime_name);+ store+ .install_archive(registry_entry(PERCEPTION_ID).unwrap(), &archive)+ .unwrap();+ let active = store.active_path(PERCEPTION_ID).unwrap().unwrap();+ fs::write(active.join(&relative), b"tampered execution input").unwrap();++ let error = perception_worker_config_in(&store).unwrap_err();+ assert!(+ error.to_string().contains("SHA-256 mismatch"),+ "relative={relative}, error={error:#}"+ );+ }+ }++ #[test]+ fn nonexecuted_tampering_is_deferred_to_full_verification() {+ let temp = TempDir::new().unwrap();+ let store = ExtensionStore::new(temp.path().join("extensions"));+ let runtime_name = if cfg!(target_os = "windows") {+ "onnxruntime.dll"+ } else if cfg!(target_os = "macos") {+ "libonnxruntime.dylib"+ } else {+ "libonnxruntime.so"+ };+ let archive = perception_fixture_archive(temp.path(), "1.0.0", runtime_name);+ store+ .install_archive(registry_entry(PERCEPTION_ID).unwrap(), &archive)+ .unwrap();+ let active = store.active_path(PERCEPTION_ID).unwrap().unwrap();+ fs::write(+ active.join("notices/THIRD_PARTY_NOTICES.md"),+ b"tampered notice",+ )+ .unwrap();++ perception_worker_config_in(&store).unwrap().unwrap();+ let installed = open_directory_path_nofollow(&active).unwrap();+ let error =+ verify_installed_version_at(&installed, registry_entry(PERCEPTION_ID).unwrap(), None)+ .unwrap_err();+ assert!(error.to_string().contains("SHA-256 mismatch"));+ }++ #[test]+ fn perception_runtime_contract_cannot_escape_the_active_directory() {+ let temp = TempDir::new().unwrap();+ let store = ExtensionStore::new(temp.path().join("extensions"));+ let archive = perception_fixture_archive(temp.path(), "1.0.0", "../outside-runtime");+ store+ .install_archive(registry_entry(PERCEPTION_ID).unwrap(), &archive)+ .unwrap();+ let error = perception_worker_config_in(&store).unwrap_err();+ assert!(error.to_string().contains("unsafe runtime name"));+ }++ #[cfg(unix)]+ #[test]+ fn perception_resolver_rejects_symlinked_installed_payload() {+ use std::os::unix::fs::symlink;++ let temp = TempDir::new().unwrap();+ let store = ExtensionStore::new(temp.path().join("extensions"));+ let runtime_name = if cfg!(target_os = "macos") {+ "libonnxruntime.dylib"+ } else {+ "libonnxruntime.so"+ };+ let archive = perception_fixture_archive(temp.path(), "1.0.0", runtime_name);+ store+ .install_archive(registry_entry(PERCEPTION_ID).unwrap(), &archive)+ .unwrap();+ let active = store.active_path(PERCEPTION_ID).unwrap().unwrap();+ let runtime = active.join("runtime").join(runtime_name);+ fs::remove_file(&runtime).unwrap();+ symlink(temp.path().join("outside-runtime"), &runtime).unwrap();++ let error = perception_worker_config_in(&store).unwrap_err();+ assert!(error.to_string().contains("symbolic link"));+ }++ fn fixture_archive_with(+ directory: &Path,+ version: &str,+ target: &str,+ protocol: u32,+ payload: &[u8],+ declared_hash: &str,+ driver_version: &str,+ ) -> PathBuf {+ fixture_archive_with_executable(+ directory,+ version,+ target,+ protocol,+ payload,+ declared_hash,+ driver_version,+ true,+ )+ }++ #[allow(clippy::too_many_arguments)]+ fn fixture_archive_with_executable(+ directory: &Path,+ version: &str,+ target: &str,+ protocol: u32,+ payload: &[u8],+ declared_hash: &str,+ driver_version: &str,+ executable: bool,+ ) -> PathBuf {+ let manifest = fixture_manifest(+ version,+ target,+ protocol,+ declared_hash,+ driver_version,+ executable,+ );+ write_fixture_archive(directory, version, &manifest, payload)+ }++ /// The same fixture extension, but declaring a self-test hook so a test can+ /// observe when the installer runs it.+ fn fixture_archive_with_self_test(+ directory: &Path,+ version: &str,+ target: &str,+ payload: &[u8],+ self_test_args: &[&str],+ ) -> PathBuf {+ let mut manifest = fixture_manifest(+ version,+ target,+ 1,+ &hex_sha256(payload),+ &format!("={}", env!("CARGO_PKG_VERSION")),+ true,+ );+ manifest.self_test_args = self_test_args.iter().map(|arg| (*arg).to_owned()).collect();+ write_fixture_archive(directory, version, &manifest, payload)+ }++ fn write_fixture_archive(+ directory: &Path,+ version: &str,+ manifest: &ExtensionManifest,+ payload: &[u8],+ ) -> PathBuf {+ let path = directory.join(format!("local-extension-{version}.tar.gz"));+ let file = fs::File::create(&path).unwrap();+ let encoder = GzEncoder::new(file, Compression::default());+ let mut builder = tar::Builder::new(encoder);+ append(+ &mut builder,+ MANIFEST_NAME,+ &serde_json::to_vec_pretty(manifest).unwrap(),+ );+ append(&mut builder, "bin/local-extension", payload);+ builder.finish().unwrap();+ path+ }++ fn fixture_manifest(+ version: &str,+ target: &str,+ protocol: u32,+ declared_hash: &str,+ driver_version: &str,+ executable: bool,+ ) -> ExtensionManifest {+ ExtensionManifest {+ schema_version: 1,+ id: "cua-perception".to_owned(),+ version: version.to_owned(),+ driver_version: driver_version.to_owned(),+ protocol_version: protocol,+ target: target.to_owned(),+ entrypoint: "bin/local-extension".to_owned(),+ files: vec![ManifestFile {+ path: "bin/local-extension".to_owned(),+ sha256: declared_hash.to_owned(),+ executable,+ }],+ models: Vec::new(),+ components: vec![ComponentLicense {+ name: "cua-perception".to_owned(),+ version: version.to_owned(),+ license: "Apache-2.0".to_owned(),+ notice: "Copyright Cua contributors".to_owned(),+ source_uri: "https://github.com/trycua/cua".to_owned(),+ source_revision: "test-fixture".to_owned(),+ notice_file: None,+ }],+ corresponding_source_file: None,+ license: "Apache-2.0".to_owned(),+ source: "https://github.com/trycua/cua".to_owned(),+ corresponding_source_uri: "https://github.com/trycua/cua".to_owned(),+ corresponding_source_revision: "test-fixture".to_owned(),+ provenance: "developer test fixture".to_owned(),+ health_args: Vec::new(),+ self_test_args: Vec::new(),+ }+ }++ #[cfg(feature = "review-trust-root")]+ fn review_fixture(directory: &Path) -> (PathBuf, PathBuf) {+ use ring::signature::Ed25519KeyPair;++ let worker = b"#!/bin/sh\nexit 0\n";+ let model = b"model";+ let notice = b"notice";+ let source = b"source";+ let model_license = b"model license";+ let bindings = [+ ("bin/cua-perception", worker.as_slice(), true),+ ("models/parser.bin", model.as_slice(), false),+ ("LICENSES/NOTICE.txt", notice.as_slice(), false),+ ("LICENSES/model.txt", model_license.as_slice(), false),+ ("SOURCE/source.txt", source.as_slice(), false),+ ];+ let manifest = ExtensionManifest {+ schema_version: 1,+ id: PERCEPTION_ID.to_owned(),+ version: "1.0.0".to_owned(),+ driver_version: format!("={}", env!("CARGO_PKG_VERSION")),+ protocol_version: 1,+ target: current_target().unwrap(),+ entrypoint: "bin/cua-perception".to_owned(),+ files: bindings+ .iter()+ .map(|(path, bytes, executable)| ManifestFile {+ path: (*path).to_owned(),+ sha256: hex_sha256(bytes),+ executable: *executable,+ })+ .collect(),+ models: vec![ManifestModel {+ path: "models/parser.bin".to_owned(),+ revision: "model-v1".to_owned(),+ original_sha256: "1".repeat(64),+ conversion_sha256: hex_sha256(model),+ license_file: Some(ArtifactBinding {+ path: "LICENSES/model.txt".to_owned(),+ sha256: hex_sha256(model_license),+ }),+ }],+ components: vec![ComponentLicense {+ name: PERCEPTION_ID.to_owned(),+ version: "1.0.0".to_owned(),+ license: "AGPL-3.0-or-later".to_owned(),+ notice: "fixture notice".to_owned(),+ source_uri: "https://github.com/trycua/cua".to_owned(),+ source_revision: "fixture".to_owned(),+ notice_file: Some(ArtifactBinding {+ path: "LICENSES/NOTICE.txt".to_owned(),+ sha256: hex_sha256(notice),+ }),+ }],+ corresponding_source_file: Some(ArtifactBinding {+ path: "SOURCE/source.txt".to_owned(),+ sha256: hex_sha256(source),+ }),+ license: "AGPL-3.0-or-later".to_owned(),+ source: "https://github.com/trycua/cua".to_owned(),+ corresponding_source_uri: "https://github.com/trycua/cua".to_owned(),+ corresponding_source_revision: "fixture".to_owned(),+ provenance: "review fixture".to_owned(),+ health_args: Vec::new(),+ self_test_args: Vec::new(),+ };+ let manifest_bytes = serde_json::to_vec_pretty(&manifest).unwrap();+ let archive = directory.join("review-extension.tar.gz");+ let encoder = GzEncoder::new(fs::File::create(&archive).unwrap(), Compression::default());+ let mut builder = tar::Builder::new(encoder);+ append(&mut builder, MANIFEST_NAME, &manifest_bytes);+ for (path, bytes, _) in bindings {+ append(&mut builder, path, bytes);+ }+ builder.finish().unwrap();+ drop(builder);+ let archive_bytes = fs::read(&archive).unwrap();+ let payload = CatalogPayload {+ schema_version: 1,+ catalog_version: 1,+ expires_unix: u64::MAX,+ publisher_id: REVIEW_PUBLISHER_ID.to_owned(),+ publisher_name: REVIEW_PUBLISHER_NAME.to_owned(),+ key_id: REVIEW_KEY_ID.to_owned(),+ extension_id: PERCEPTION_ID.to_owned(),+ version: manifest.version.clone(),+ target: manifest.target.clone(),+ archive: archive.file_name().unwrap().to_str().unwrap().to_owned(),+ archive_size: archive_bytes.len() as u64,+ archive_sha256: hex_sha256(&archive_bytes),+ manifest_sha256: hex_sha256(&manifest_bytes),+ license: manifest.license.clone(),+ source: manifest.source.clone(),+ corresponding_source_uri: manifest.corresponding_source_uri.clone(),+ corresponding_source_revision: manifest.corresponding_source_revision.clone(),+ provenance: manifest.provenance.clone(),+ next_key: None,+ };+ let pair = Ed25519KeyPair::from_seed_unchecked(&REVIEW_SEED).unwrap();+ let signed = sign_test_catalog(&pair, payload);+ let catalog = directory.join("review-catalog.json");+ fs::write(&catalog, serde_json::to_vec_pretty(&signed).unwrap()).unwrap();+ (archive, catalog)+ }++ fn append(builder: &mut tar::Builder<GzEncoder<fs::File>>, path: &str, bytes: &[u8]) {+ let mut header = tar::Header::new_gnu();+ header.set_size(bytes.len() as u64);+ header.set_mode(0o755);+ header.set_cksum();+ builder+ .append_data(&mut header, path, Cursor::new(bytes))+ .unwrap();+ }++ fn unsafe_archive(directory: &Path, kind: &str) -> PathBuf {+ let path = directory.join(format!("unsafe-{kind}.tar.gz"));+ let file = fs::File::create(&path).unwrap();+ let encoder = GzEncoder::new(file, Compression::default());+ let mut builder = tar::Builder::new(encoder);+ let mut header = tar::Header::new_gnu();+ header.set_mode(0o644);+ match kind {+ "traversal" => {+ let name = b"../outside";+ header.as_mut_bytes()[..name.len()].copy_from_slice(name);+ header.set_size(1);+ header.set_cksum();+ builder.append(&header, Cursor::new(b"x")).unwrap();+ }+ "symlink" => {+ header.set_path("link").unwrap();+ header.set_entry_type(tar::EntryType::Symlink);+ header.set_link_name("outside").unwrap();+ header.set_size(0);+ header.set_cksum();+ builder.append(&header, Cursor::new([])).unwrap();+ }+ "pax" => {+ builder+ .append_pax_extensions([("comment", b"untrusted metadata".as_slice())])+ .unwrap();+ }+ "long-path" => {+ let path = format!("{}/payload", "a".repeat(MAX_ARCHIVE_PATH_BYTES + 1));+ append(&mut builder, &path, b"x");+ }+ _ => unreachable!(),+ }+ builder.finish().unwrap();+ path+ }++ #[test]+ fn fresh_and_idempotent_fixture_install() {+ let temp = TempDir::new().unwrap();+ let archive = fixture_archive(+ temp.path(),+ "1.2.3",+ ¤t_target().unwrap(),+ 1,+ b"worker",+ );+ let store = ExtensionStore::new(temp.path().join("extensions"));+ let entry = registry_entry("cua-perception").unwrap();++ let first = store.install_archive(entry, &archive).unwrap();+ let second = store.install_archive(entry, &archive).unwrap();++ assert_eq!(first.path, second.path);+ assert_eq!(+ store.active_path("cua-perception").unwrap(),+ Some(first.path)+ );+ assert!(store.info(entry, false).unwrap().healthy);+ }++ #[test]+ fn rejects_corrupt_target_and_protocol_mismatches() {+ let temp = TempDir::new().unwrap();+ let store = ExtensionStore::new(temp.path().join("extensions"));+ let entry = registry_entry("cua-perception").unwrap();++ let wrong_target = fixture_archive(temp.path(), "1.0.0", "wrong-target", 1, b"worker");+ assert!(store+ .install_archive(entry, &wrong_target)+ .unwrap_err()+ .to_string()+ .contains("target"));++ let wrong_protocol = fixture_archive(+ temp.path(),+ "1.0.1",+ ¤t_target().unwrap(),+ 99,+ b"worker",+ );+ assert!(store+ .install_archive(entry, &wrong_protocol)+ .unwrap_err()+ .to_string()+ .contains("protocol"));++ let wrong_driver = fixture_archive_with(+ temp.path(),+ "1.0.2",+ ¤t_target().unwrap(),+ 1,+ b"worker",+ &hex_sha256(b"worker"),+ ">999.0.0",+ );+ assert!(store+ .install_archive(entry, &wrong_driver)+ .unwrap_err()+ .to_string()+ .contains("requires Driver"));++ let wrong_hash = fixture_archive_with(+ temp.path(),+ "1.0.3",+ ¤t_target().unwrap(),+ 1,+ b"worker",+ &"0".repeat(64),+ &format!("={}", env!("CARGO_PKG_VERSION")),+ );+ assert!(store+ .install_archive(entry, &wrong_hash)+ .unwrap_err()+ .to_string()+ .contains("SHA-256 mismatch"));++ let corrupt = fixture_archive(+ temp.path(),+ "1.0.4",+ ¤t_target().unwrap(),+ 1,+ b"worker",+ );+ let bytes = fs::read(&corrupt).unwrap();+ fs::write(&corrupt, &bytes[..bytes.len() / 2]).unwrap();+ assert!(store.install_archive(entry, &corrupt).is_err());+ assert!(store.active_path("cua-perception").unwrap().is_none());+ }++ #[test]+ fn malformed_manifest_version_cleans_staging() {+ let temp = TempDir::new().unwrap();+ let store = ExtensionStore::new(temp.path().join("extensions"));+ let entry = registry_entry("cua-perception").unwrap();+ let archive = fixture_archive(+ temp.path(),+ "not-a-version",+ ¤t_target().unwrap(),+ 1,+ b"worker",+ );++ assert!(store+ .install_archive(entry, &archive)+ .unwrap_err()+ .to_string()+ .contains("semantic versioning"));+ assert_eq!(+ fs::read_dir(store.root.join(".staging")).unwrap().count(),+ 0+ );+ }++ #[test]+ fn rejects_traversal_and_link_entries_and_cleans_staging() {+ let temp = TempDir::new().unwrap();+ let store = ExtensionStore::new(temp.path().join("extensions"));+ let entry = registry_entry("cua-perception").unwrap();++ for kind in ["traversal", "symlink", "pax", "long-path"] {+ let archive = unsafe_archive(temp.path(), kind);+ assert!(store.install_archive(entry, &archive).is_err(), "{kind}");+ }+ assert_eq!(+ fs::read_dir(store.root.join(".staging")).unwrap().count(),+ 0+ );+ }++ #[test]+ fn compressed_reader_stops_at_its_limit() {+ let mut reader = BoundedReader {+ inner: Cursor::new(vec![b'x'; 16]),+ remaining: 4,+ };+ let mut output = Vec::new();+ let error = reader.read_to_end(&mut output).unwrap_err();+ assert_eq!(output.len(), 4);+ assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);+ }++ #[test]+ fn strict_command_grammar_rejects_ambiguous_arguments() {+ for args in [+ vec!["list", "extra"],+ vec!["inspect", "cua-perception", "extra"],+ vec!["status", "--bogus"],+ vec!["status", "--json", "--json"],+ vec!["install", "cua-perception", "--archive"],+ vec!["install", "cua-perception", "--archive", "a", "--archive=b"],+ vec!["remove", "cua-perception", "--archive=a"],+ ] {+ let args = args.into_iter().map(str::to_owned).collect::<Vec<_>>();+ assert!(parse_command(&args).is_err(), "accepted {args:?}");+ }+ }++ #[test]+ fn mutation_platform_contract_is_explicit() {+ assert!(ensure_mutations_supported().is_ok());+ }++ #[test]+ fn activation_failure_restores_previous_version() {+ let temp = TempDir::new().unwrap();+ let store = ExtensionStore::new(temp.path().join("extensions"));+ let entry = registry_entry("cua-perception").unwrap();+ let archive = fixture_archive(+ temp.path(),+ "1.0.0",+ ¤t_target().unwrap(),+ 1,+ b"worker",+ );+ store.install_archive(entry, &archive).unwrap();++ let lock = store.lock("cua-perception").unwrap();+ let error = store+ .activate_locked(+ &lock.root,+ "cua-perception",+ "2.0.0",+ ActivationFailpoint::AfterBackup,+ )+ .unwrap_err();+ drop(lock);++ assert!(error.to_string().contains("simulated interruption"));+ let lock = store.lock("cua-perception").unwrap();+ assert_eq!(+ store+ .active_pointer_locked(&lock.root, "cua-perception")+ .unwrap()+ .unwrap()+ .version,+ "1.0.0"+ );+ }++ #[test]+ fn recovery_validates_and_restores_interrupted_backup() {+ let temp = TempDir::new().unwrap();+ let store = ExtensionStore::new(temp.path().join("extensions"));+ let entry = registry_entry("cua-perception").unwrap();+ let archive = fixture_archive(+ temp.path(),+ "1.0.0",+ ¤t_target().unwrap(),+ 1,+ b"worker",+ );+ store.install_archive(entry, &archive).unwrap();++ let lock = store.lock(entry.id).unwrap();+ store+ .activate_locked(+ &lock.root,+ entry.id,+ "2.0.0",+ ActivationFailpoint::LeaveInterruptedAfterBackup,+ )+ .unwrap_err();+ drop(lock);++ assert_eq!(+ store.active_path(entry.id).unwrap().unwrap(),+ store.versions_dir(entry.id).join("1.0.0")+ );+ assert!(!store+ .extension_dir(entry.id)+ .join(ACTIVE_BACKUP_NAME)+ .exists());+ assert!(!store.extension_dir(entry.id).join(ACTIVE_NEW_NAME).exists());+ }++ #[test]+ fn absence_is_healthy() {+ let temp = TempDir::new().unwrap();+ let store = ExtensionStore::new(temp.path().join("extensions"));+ let info = store+ .info(registry_entry("cua-perception").unwrap(), false)+ .unwrap();+ assert!(!info.installed);+ assert!(info.healthy);+ assert_eq!(info.detail, "not installed (healthy)");+ }++ #[cfg(unix)]+ #[test]+ fn rejects_symlinked_store_components_without_deleting_external_targets() {+ use std::os::unix::fs::{symlink, PermissionsExt};++ for component in [+ "ancestor",+ "root",+ "extension",+ "versions",+ "staging",+ "active",+ "active-backup",+ "active-new",+ ] {+ let temp = TempDir::new().unwrap();+ let external = temp.path().join("external");+ fs::create_dir(&external).unwrap();+ fs::set_permissions(&external, fs::Permissions::from_mode(0o700)).unwrap();+ fs::write(external.join("sentinel"), b"keep").unwrap();+ fs::set_permissions(external.join("sentinel"), fs::Permissions::from_mode(0o600))+ .unwrap();+ let store = if component == "ancestor" {+ let linked_home = temp.path().join("linked-home");+ symlink(&external, &linked_home).unwrap();+ ExtensionStore::new(linked_home.join("extensions"))+ } else {+ ExtensionStore::new(temp.path().join("extensions"))+ };+ let entry = registry_entry("cua-perception").unwrap();+ let archive = fixture_archive(+ temp.path(),+ "1.0.0",+ ¤t_target().unwrap(),+ 1,+ b"worker",+ );++ if !matches!(component, "ancestor" | "root") {+ ensure_private_directory_path(&store.root).unwrap();+ }+ match component {+ "ancestor" => {}+ "root" => symlink(&external, &store.root).unwrap(),+ "extension" => symlink(&external, store.extension_dir(entry.id)).unwrap(),+ "versions" => {+ ensure_private_directory_path(&store.extension_dir(entry.id)).unwrap();+ symlink(&external, store.versions_dir(entry.id)).unwrap();+ }+ "staging" => symlink(&external, store.root.join(".staging")).unwrap(),+ "active" | "active-backup" | "active-new" => {+ store.install_archive(entry, &archive).unwrap();+ let pointer_name = match component {+ "active" => ACTIVE_NAME,+ "active-backup" => ACTIVE_BACKUP_NAME,+ "active-new" => ACTIVE_NEW_NAME,+ _ => unreachable!(),+ };+ let pointer_path = store.extension_dir(entry.id).join(pointer_name);+ if pointer_path.exists() {+ fs::remove_file(&pointer_path).unwrap();+ }+ symlink(external.join("sentinel"), pointer_path).unwrap();+ }+ _ => unreachable!(),+ }++ let result = store.install_archive(entry, &archive).map(|_| ());+ assert!(result.is_err(), "{component} symlink was accepted");+ assert_eq!(fs::read(external.join("sentinel")).unwrap(), b"keep");+ }+ }++ #[cfg(windows)]+ #[test]+ fn hardens_a_precreated_extension_root_with_a_broad_acl() {+ let temp = TempDir::new().unwrap();+ let root_path = temp.path().join("extensions");+ fs::create_dir(&root_path).unwrap();+ let root = open_directory_path_nofollow(&root_path).unwrap();+ windows_secure_handle(&root).unwrap();+ drop(root);+ let acl = std::process::Command::new("icacls")+ .arg(&root_path)+ .args(["/grant", "*S-1-1-0:(W)"])+ .output()+ .unwrap();+ assert!(+ acl.status.success(),+ "{}",+ String::from_utf8_lossy(&acl.stderr)+ );++ let broad = open_directory_path_nofollow(&root_path).unwrap();+ assert!(windows_verify_directory_handle(&broad)+ .unwrap_err()+ .to_string()+ .contains("untrusted principal"));+ drop(broad);++ let hardened = ensure_private_directory_path(&root_path).unwrap();+ windows_verify_directory_handle(&hardened).unwrap();+ }++ #[cfg(windows)]+ #[test]+ fn installed_directory_tree_inherits_only_private_acl_entries() {+ use std::os::windows::io::AsRawHandle as _;++ unsafe fn assert_private_inheritance(directory: &Dir, relative: &Path) {+ #[link(name = "advapi32")]+ extern "system" {+ fn GetSecurityInfo(+ handle: *mut std::ffi::c_void,+ object_type: i32,+ information: u32,+ owner: *mut *mut std::ffi::c_void,+ group: *mut *mut std::ffi::c_void,+ dacl: *mut *mut WindowsAcl,+ sacl: *mut *mut WindowsAcl,+ descriptor: *mut *mut std::ffi::c_void,+ ) -> u32;+ fn GetAce(+ acl: *const WindowsAcl,+ index: u32,+ ace: *mut *mut std::ffi::c_void,+ ) -> i32;+ }+ #[link(name = "kernel32")]+ extern "system" {+ fn LocalFree(memory: *mut std::ffi::c_void) -> *mut std::ffi::c_void;+ }++ let mut dacl = std::ptr::null_mut();+ let mut descriptor = std::ptr::null_mut();+ let status = GetSecurityInfo(+ directory.as_raw_handle().cast(),+ 1,+ 0x4,+ std::ptr::null_mut(),+ std::ptr::null_mut(),+ &mut dacl,+ std::ptr::null_mut(),+ &mut descriptor,+ );+ assert_eq!(status, 0, "read ACL for {}", relative.display());+ assert!(!dacl.is_null(), "missing DACL for {}", relative.display());+ for index in 0..(*dacl).ace_count as u32 {+ let mut raw = std::ptr::null_mut();+ assert_ne!(+ GetAce(dacl, index, &mut raw),+ 0,+ "read ACE {index} for {}",+ relative.display()+ );+ let ace = &*(raw.cast::<WindowsAccessAllowedAce>());+ if ace.header.ace_type == 0 {+ assert_eq!(+ ace.header.ace_flags & 0x3,+ 0x3,+ "directory ACE {index} does not propagate privately at {}",+ relative.display()+ );+ }+ }+ let _ = LocalFree(descriptor);++ for child in directory.entries().unwrap() {+ let child = child.unwrap();+ if child.file_type().unwrap().is_dir() {+ let child_relative = relative.join(child.file_name());+ let child_directory = directory.open_dir_nofollow(child.file_name()).unwrap();+ assert_private_inheritance(&child_directory, &child_relative);+ }+ }+ }++ let temp = TempDir::new().unwrap();+ let acl = std::process::Command::new("icacls")+ .arg(temp.path())+ .args(["/grant", "*S-1-1-0:(OI)(CI)(W)"])+ .output()+ .unwrap();+ assert!(+ acl.status.success(),+ "{}",+ String::from_utf8_lossy(&acl.stderr)+ );+ let store = ExtensionStore::new(temp.path().join("extensions"));+ let entry = registry_entry("cua-perception").unwrap();+ let archive = fixture_archive(+ temp.path(),+ "1.0.0",+ ¤t_target().unwrap(),+ 1,+ b"worker",+ );++ store.install_archive(entry, &archive).unwrap();+ let root = open_directory_path_nofollow(&store.root).unwrap();+ unsafe { assert_private_inheritance(&root, Path::new("extensions")) };+ }++ #[cfg(windows)]+ #[test]+ fn acl_hardening_reopens_directory_and_file_handles() {+ use std::os::windows::io::AsRawHandle as _;++ let temp = TempDir::new().unwrap();+ let parent = open_directory_path_nofollow(temp.path()).unwrap();++ create_private_subdirectory(&parent, std::ffi::OsStr::new("private")).unwrap();+ let private = parent.open_dir_nofollow("private").unwrap();+ let reopened_directory =+ windows_reopen_for_security(private.as_raw_handle().cast()).unwrap();+ windows_verify_same_object(+ private.as_raw_handle().cast(),+ reopened_directory.as_raw_handle().cast(),+ )+ .unwrap();+ windows_verify_directory_handle(&private).unwrap();++ write_new_file_at(&private, "owned", b"content").unwrap();+ let mut options = CapOpenOptions::new();+ options.read(true).follow(FollowSymlinks::No);+ let file = private.open_with("owned", &options).unwrap();+ let reopened_file = windows_reopen_for_security(file.as_raw_handle().cast()).unwrap();+ windows_verify_same_object(+ file.as_raw_handle().cast(),+ reopened_file.as_raw_handle().cast(),+ )+ .unwrap();+ assert!(private_regular_file_or_missing_at(&private, "owned").unwrap());+ }++ #[cfg(windows)]+ #[test]+ fn recursive_acl_hardening_removes_package_access_from_staged_tree() {+ let temp = TempDir::new().unwrap();+ let parent = open_directory_path_nofollow(temp.path()).unwrap();+ create_private_subdirectory(&parent, std::ffi::OsStr::new("staged")).unwrap();+ let staged = parent.open_dir_nofollow("staged").unwrap();+ create_private_subdirectory(&staged, std::ffi::OsStr::new("nested")).unwrap();+ let nested = staged.open_dir_nofollow("nested").unwrap();+ write_new_file_at(&nested, "payload", b"content").unwrap();++ for path in [+ temp.path().join("staged"),+ temp.path().join("staged/nested"),+ temp.path().join("staged/nested/payload"),+ ] {+ let output = std::process::Command::new("icacls")+ .arg(&path)+ .arg("/grant")+ .arg("*S-1-15-2-1:(RX)")+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "icacls failed for {}: {}",+ path.display(),+ String::from_utf8_lossy(&output.stderr)+ );+ }++ assert!(windows_verify_directory_handle(&staged).is_err());+ assert!(inspect_owned_tree(&staged).is_err());++ windows_harden_private_tree(&staged).unwrap();+ windows_verify_directory_handle(&staged).unwrap();+ inspect_owned_tree(&staged).unwrap();+ }++ #[cfg(windows)]+ #[test]+ fn recursive_acl_hardening_reasserts_root_after_descendant_walk() {+ let temp = TempDir::new().unwrap();+ let parent = open_directory_path_nofollow(temp.path()).unwrap();+ create_private_subdirectory(&parent, std::ffi::OsStr::new("staged")).unwrap();+ let staged = parent.open_dir_nofollow("staged").unwrap();+ create_private_subdirectory(&staged, std::ffi::OsStr::new("nested")).unwrap();+ let nested = staged.open_dir_nofollow("nested").unwrap();+ write_new_file_at(&nested, "payload", b"content").unwrap();++ let injected = Cell::new(false);+ windows_harden_private_tree_with(&staged, &mut |directory| {+ if injected.replace(true) {+ return;+ }+ let output = std::process::Command::new("icacls")+ .arg(temp.path().join("staged"))+ .arg("/grant")+ .arg("*S-1-15-2-1:(RX)")+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "icacls failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ assert!(windows_verify_directory_handle(directory).is_err());+ })+ .unwrap();++ assert!(injected.get());+ windows_verify_directory_handle(&staged).unwrap();+ inspect_owned_tree(&staged).unwrap();+ }++ #[cfg(windows)]+ #[test]+ fn staged_install_verification_survives_acl_drift_during_recursive_hardening() {+ let temp = TempDir::new().unwrap();+ let parent = open_directory_path_nofollow(temp.path()).unwrap();+ create_private_subdirectory(&parent, std::ffi::OsStr::new("staged")).unwrap();+ let staged = parent.open_dir_nofollow("staged").unwrap();+ let entry = registry_entry(PERCEPTION_ID).unwrap();+ let archive = fixture_archive(+ temp.path(),+ "1.0.0",+ ¤t_target().unwrap(),+ 1,+ b"worker",+ );+ let source = InstallSource {+ archive: archive.clone(),+ trust: TrustClass::DeveloperUnsignedLocal,+ catalog: None,+ signed_catalog: None,+ trust_update: None,+ };+ let inspected = inspect_archive(&archive, entry, &staged).unwrap();+ write_install_record_at(&staged, &inspected, &source).unwrap();++ let hardens = Cell::new(0);+ let injected = Cell::new(false);+ let manifest = converge_windows_acl_with(+ 3,+ std::time::Duration::from_secs(90),+ || std::time::Duration::ZERO,+ |_| {},+ || {+ hardens.set(hardens.get() + 1);+ windows_harden_private_tree_with(&staged, &mut |_| {+ if !injected.replace(true) {+ let output = std::process::Command::new("icacls")+ .arg(temp.path().join("staged"))+ .arg("/grant")+ .arg("*S-1-15-2-1:(RX)")+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "icacls failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ }+ })+ },+ || verify_installed_version_at(&staged, entry, Some(&inspected.manifest_bytes)),+ )+ .unwrap();++ assert_eq!(manifest.version, "1.0.0");+ assert!(injected.get());+ assert_eq!(hardens.get(), 1);+ windows_verify_directory_handle(&staged).unwrap();+ inspect_owned_tree(&staged).unwrap();+ }++ #[cfg(windows)]+ #[test]+ fn post_hook_acl_grant_is_removed_before_staged_version_is_placed() {+ let temp = TempDir::new().unwrap();+ let root = open_directory_path_nofollow(temp.path()).unwrap();+ create_private_subdirectory(&root, std::ffi::OsStr::new("staging")).unwrap();+ create_private_subdirectory(&root, std::ffi::OsStr::new("versions")).unwrap();+ let staging = root.open_dir_nofollow("staging").unwrap();+ let versions = root.open_dir_nofollow("versions").unwrap();+ let entry = registry_entry(PERCEPTION_ID).unwrap();+ let archive = fixture_archive(+ temp.path(),+ "1.0.0",+ ¤t_target().unwrap(),+ 1,+ b"worker",+ );+ let source = InstallSource {+ archive: archive.clone(),+ trust: TrustClass::DeveloperUnsignedLocal,+ catalog: None,+ signed_catalog: None,+ trust_update: None,+ };+ let inspected = inspect_archive(&archive, entry, &staging).unwrap();+ write_install_record_at(&staging, &inspected, &source).unwrap();++ run_verified_extension_hook_with(+ &staging,+ entry,+ Some(&inspected.manifest_bytes),+ &inspected.manifest.version,+ || {+ let grant = std::process::Command::new("icacls")+ .arg(temp.path().join("staging"))+ .arg("/grant")+ .arg("*S-1-15-2-1:(OI)(CI)(RX)")+ .output()?;+ if !grant.status.success() {+ bail!("icacls failed: {}", String::from_utf8_lossy(&grant.stderr));+ }+ assert!(verify_installed_version_at(+ &staging,+ entry,+ Some(&inspected.manifest_bytes)+ )+ .is_err());+ Ok(())+ },+ )+ .unwrap();+ drop(staging);+ root.rename("staging", &versions, "1.0.0").unwrap();+ let installed = versions.open_dir_nofollow("1.0.0").unwrap();++ let manifest =+ converge_windows_installed_version(&installed, entry, Some(&inspected.manifest_bytes))+ .unwrap();+ assert_eq!(manifest.version, "1.0.0");+ windows_verify_directory_handle(&installed).unwrap();+ inspect_owned_tree(&installed).unwrap();+ }++ #[cfg(windows)]+ #[test]+ fn health_hook_acl_grant_is_removed_before_status_returns_healthy() {+ let temp = TempDir::new().unwrap();+ let root = open_directory_path_nofollow(temp.path()).unwrap();+ create_private_subdirectory(&root, std::ffi::OsStr::new("installed")).unwrap();+ let installed = root.open_dir_nofollow("installed").unwrap();+ let entry = registry_entry(PERCEPTION_ID).unwrap();+ let archive = fixture_archive(+ temp.path(),+ "1.0.0",+ ¤t_target().unwrap(),+ 1,+ b"worker",+ );+ let source = InstallSource {+ archive: archive.clone(),+ trust: TrustClass::DeveloperUnsignedLocal,+ catalog: None,+ signed_catalog: None,+ trust_update: None,+ };+ let inspected = inspect_archive(&archive, entry, &installed).unwrap();+ write_install_record_at(&installed, &inspected, &source).unwrap();+ converge_windows_installed_version(&installed, entry, None).unwrap();++ let post_hook_archive_sha256 = "ab".repeat(32);+ let record = run_verified_extension_hook_with(+ &installed,+ entry,+ None,+ &inspected.manifest.version,+ || {+ let grant = std::process::Command::new("icacls")+ .arg(temp.path().join("installed"))+ .arg("/grant")+ .arg("*S-1-15-2-1:(OI)(CI)(RX)")+ .output()?;+ if !grant.status.success() {+ bail!("icacls failed: {}", String::from_utf8_lossy(&grant.stderr));+ }+ let mut record =+ read_install_record_at(&installed, entry.id, &inspected.manifest.version)?;+ record.archive_sha256 = post_hook_archive_sha256.clone();+ fs::write(+ temp.path().join("installed").join(INSTALL_RECORD_NAME),+ serde_json::to_vec_pretty(&record)?,+ )?;+ assert!(verify_installed_version_at(&installed, entry, None).is_err());+ Ok(())+ },+ )+ .unwrap();++ assert_eq!(record.archive_sha256, post_hook_archive_sha256);+ let manifest = verify_installed_version_at(&installed, entry, None).unwrap();+ assert_eq!(manifest.version, "1.0.0");+ windows_verify_directory_handle(&installed).unwrap();+ inspect_owned_tree(&installed).unwrap();+ }++ #[cfg(windows)]+ #[test]+ fn acl_identity_check_rejects_a_different_object() {+ use std::os::windows::io::AsRawHandle as _;++ let temp = TempDir::new().unwrap();+ let root = open_directory_path_nofollow(temp.path()).unwrap();+ write_new_file_at(&root, "first", b"first").unwrap();+ write_new_file_at(&root, "second", b"second").unwrap();++ let mut options = CapOpenOptions::new();+ options.read(true).follow(FollowSymlinks::No);+ let first = root.open_with("first", &options).unwrap();+ let second = root.open_with("second", &options).unwrap();+ assert!(windows_verify_same_object(+ first.as_raw_handle().cast(),+ second.as_raw_handle().cast(),+ )+ .is_err());+ }++ #[cfg(windows)]+ #[test]+ fn rejects_windows_junctions_and_broad_acl_entries() {+ let temp = TempDir::new().unwrap();+ let store = ExtensionStore::new(temp.path().join("extensions"));+ let root = ensure_private_directory_path(&store.root).unwrap();+ let external = temp.path().join("external");+ fs::create_dir(&external).unwrap();+ let junction = store.root.join("junction");+ let linked = std::process::Command::new("cmd")+ .args(["/C", "mklink", "/J"])+ .arg(&junction)+ .arg(&external)+ .output()+ .unwrap();+ assert!(+ linked.status.success(),+ "{}",+ String::from_utf8_lossy(&linked.stderr)+ );+ assert!(open_directory_path_nofollow(&junction).is_err());++ write_new_file_at(&root, "owned", b"content").unwrap();+ let file = store.root.join("owned");+ let acl = std::process::Command::new("icacls")+ .arg(&file)+ .args(["/grant", "*S-1-1-0:(W)"])+ .output()+ .unwrap();+ assert!(+ acl.status.success(),+ "{}",+ String::from_utf8_lossy(&acl.stderr)+ );+ assert!(private_regular_file_or_missing_at(&root, "owned").is_err());+ }++ #[cfg(unix)]+ #[test]+ fn retained_directory_handle_survives_name_swap_without_touching_replacement() {+ use std::os::unix::fs::{symlink, PermissionsExt};++ let temp = TempDir::new().unwrap();+ let store = ExtensionStore::new(temp.path().join("extensions"));+ let root = ensure_private_directory_path(&store.root).unwrap();+ let retained = ensure_private_subdirectory(&root, "slot").unwrap();+ let external = temp.path().join("external");+ fs::create_dir(&external).unwrap();+ fs::set_permissions(&external, fs::Permissions::from_mode(0o700)).unwrap();+ fs::write(external.join("sentinel"), b"keep").unwrap();++ root.rename("slot", &root, "slot-original").unwrap();+ sync_cap_dir(&root).unwrap();+ symlink(&external, store.root.join("slot")).unwrap();++ write_new_file_at(&retained, "marker", b"retained").unwrap();+ assert_eq!(+ fs::read(store.root.join("slot-original/marker")).unwrap(),+ b"retained"+ );+ assert!(!external.join("marker").exists());+ assert!(remove_cap_subdirectory(&root, std::ffi::OsStr::new("slot")).is_err());+ assert_eq!(fs::read(external.join("sentinel")).unwrap(), b"keep");+ }++ #[cfg(unix)]+ #[test]+ fn installs_owner_only_files_and_requires_executable_entrypoint() {+ use std::os::unix::fs::PermissionsExt;++ let temp = TempDir::new().unwrap();+ let store = ExtensionStore::new(temp.path().join("extensions"));+ let entry = registry_entry("cua-perception").unwrap();+ let archive = fixture_archive(+ temp.path(),+ "1.0.0",+ ¤t_target().unwrap(),+ 1,+ b"worker",+ );+ let installed = store.install_archive(entry, &archive).unwrap();+ assert_eq!(+ fs::symlink_metadata(installed.path.join("bin/local-extension"))+ .unwrap()+ .permissions()+ .mode()+ & 0o777,+ 0o700+ );+ assert_eq!(+ fs::symlink_metadata(installed.path.join(MANIFEST_NAME))+ .unwrap()+ .permissions()+ .mode()+ & 0o777,+ 0o600+ );++ let invalid = fixture_archive_with_executable(+ temp.path(),+ "2.0.0",+ ¤t_target().unwrap(),+ 1,+ b"worker",+ &hex_sha256(b"worker"),+ &format!("={}", env!("CARGO_PKG_VERSION")),+ false,+ );+ assert!(store+ .install_archive(entry, &invalid)+ .unwrap_err()+ .to_string()+ .contains("must be executable"));+ }++ /// An interpreted entrypoint cannot execute inside the worker boundary:+ /// the sandbox grants execution to the entrypoint file alone, never to an+ /// interpreter. The hook therefore fails before its first instruction, so+ /// nothing it would have done — here, forking a descendant that outlives+ /// the deadline — can happen at all.+ #[cfg(unix)]+ #[test]+ fn a_hook_cannot_run_a_single_instruction_outside_its_containment() {+ use std::os::unix::fs::PermissionsExt;++ let temp = TempDir::new().unwrap();+ let root = temp.path().join("hook");+ fs::create_dir(&root).unwrap();+ fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap();+ let script = root.join("worker");+ fs::write(+ &script,+ b"#!/bin/sh\n(/bin/sleep 1; printf escaped > \"$1\") &\n/bin/sleep 30\n",+ )+ .unwrap();+ fs::set_permissions(&script, fs::Permissions::from_mode(0o700)).unwrap();+ let sentinel = temp.path().join("escaped");+ let manifest = hook_fixture_manifest(vec![sentinel.to_string_lossy().into_owned()]);++ assert!(run_extension_hook_with_timeout(+ &root,+ &manifest,+ false,+ std::time::Duration::from_secs(5),+ None,+ )+ .is_err());+ std::thread::sleep(std::time::Duration::from_millis(1_100));+ assert!(!sentinel.exists());+ // The launch happened through the contained path, so the manager saw+ // the hook root before any process existed.+ assert_eq!(hook_observer::launches_under(&root).len(), 1);+ }++ /// A hook whose entrypoint is not an executable image never reaches the+ /// worker boundary either, and the failure is reported rather than ignored.+ #[test]+ fn a_hook_with_an_unlaunchable_entrypoint_fails_closed() {+ let temp = TempDir::new().unwrap();+ let root = temp.path().join("hook");+ fs::create_dir(&root).unwrap();+ fs::write(root.join("worker"), b"not an executable image").unwrap();+ let manifest = hook_fixture_manifest(vec!["--health".to_owned()]);++ assert!(run_extension_hook_with_timeout(+ &root,+ &manifest,+ false,+ std::time::Duration::from_secs(5),+ None,+ )+ .is_err());+ }++ fn hook_fixture_manifest(health_args: Vec<String>) -> ExtensionManifest {+ ExtensionManifest {+ schema_version: MANIFEST_SCHEMA_VERSION,+ id: "cua-perception".to_owned(),+ version: "1.0.0".to_owned(),+ driver_version: format!("={}", env!("CARGO_PKG_VERSION")),+ protocol_version: 1,+ target: current_target().unwrap(),+ entrypoint: "worker".to_owned(),+ files: Vec::new(),+ models: Vec::new(),+ components: Vec::new(),+ corresponding_source_file: None,+ license: "Apache-2.0".to_owned(),+ source: "test".to_owned(),+ corresponding_source_uri: "test".to_owned(),+ corresponding_source_revision: "test".to_owned(),+ provenance: "test".to_owned(),+ health_args,+ self_test_args: Vec::new(),+ }+ }++ /// A fresh install must write its record and pass full verification before+ /// its self-test hook is allowed to run, so a hook can never execute from+ /// an unrecorded or unverified directory.+ #[test]+ fn a_fresh_install_records_and_verifies_before_running_its_hook() {+ let temp = TempDir::new().unwrap();+ let store = ExtensionStore::new(temp.path().join("extensions"));+ let entry = registry_entry("cua-perception").unwrap();+ let archive = fixture_archive_with_self_test(+ temp.path(),+ "1.0.0",+ ¤t_target().unwrap(),+ b"worker",+ &["--self-test"],+ );++ // The fixture payload is not an executable image, so the contained+ // hook cannot succeed; the install fails and rolls back.+ assert!(store.install_archive(entry, &archive).is_err());+ assert!(store.active_path(entry.id).unwrap().is_none());+ assert!(staging_is_empty(&store), "staging was not rolled back");++ let launches = hook_observer::launches_under(&store.root);+ assert_eq!(launches.len(), 1, "expected exactly one hook launch");+ assert!(+ launches[0].install_record_present,+ "the hook ran before the install record was written"+ );+ assert!(+ launches[0].fully_verified,+ "the hook ran before the staged version was fully verified"+ );+ }++ fn staging_is_empty(store: &ExtensionStore) -> bool {+ let staging = store.root.join(".staging");+ !staging.exists() || fs::read_dir(&staging).unwrap().next().is_none()+ }++ #[test]+ fn rejects_unknown_or_unsupported_target_abis() {+ assert!(target_triple("linux", "x86_64", "unknown").is_err());+ assert!(target_triple("macos", "aarch64", "unknown").is_err());+ assert!(target_triple("freebsd", "x86_64", "gnu").is_err());+ assert_eq!(+ target_triple("linux", "aarch64", "musl").unwrap(),+ "aarch64-unknown-linux-musl"+ );+ }++ #[test]+ fn ed25519_verification_rejects_tampering() {+ use ring::signature::{Ed25519KeyPair, KeyPair};++ let seed = [+ 0x9d, 0x61, 0xb1, 0x9d, 0xef, 0xfd, 0x5a, 0x60, 0xba, 0x84, 0x4a, 0xf4, 0x92, 0xec,+ 0x2c, 0xc4, 0x44, 0x49, 0xc5, 0x69, 0x7b, 0x32, 0x69, 0x19, 0x70, 0x3b, 0xac, 0x03,+ 0x1c, 0xae, 0x7f, 0x60,+ ];+ let pair = Ed25519KeyPair::from_seed_unchecked(&seed).unwrap();+ let message = b"signed target-specific extension catalog";+ let signature = BASE64.encode(pair.sign(message).as_ref());+ verify_ed25519_signature(pair.public_key().as_ref(), message, &signature).unwrap();+ assert!(verify_ed25519_signature(+ pair.public_key().as_ref(),+ b"tampered catalog",+ &signature+ )+ .is_err());+ }++ #[test]+ fn python_node_catalog_golden_is_canonical_and_verified_by_rust() {+ let golden: serde_json::Value = serde_json::from_str(include_str!(+ "../tests/fixtures/extension_catalog/signed-catalog.golden.json"+ ))+ .unwrap();+ let payload: CatalogPayload = serde_json::from_value(golden["payload"].clone()).unwrap();+ assert_eq!(+ serde_json::to_string(&payload).unwrap(),+ golden["canonical_payload"]+ );+ let public_key = BASE64+ .decode(golden["public_key_base64"].as_str().unwrap())+ .unwrap();+ verify_ed25519_signature(+ &public_key,+ golden["canonical_payload"].as_str().unwrap().as_bytes(),+ golden["signature"].as_str().unwrap(),+ )+ .unwrap();+ let mut tampered = golden["canonical_payload"]+ .as_str()+ .unwrap()+ .as_bytes()+ .to_vec();+ tampered[0] ^= 1;+ assert!(verify_ed25519_signature(+ &public_key,+ &tampered,+ golden["signature"].as_str().unwrap(),+ )+ .is_err());+ }++ #[cfg(feature = "review-trust-root")]+ #[test]+ fn review_build_uses_only_the_overridden_review_key_and_evidence_class() {+ let trust = initial_publisher_trust();+ assert_eq!(trust.publisher_id, REVIEW_PUBLISHER_ID);+ assert_eq!(trust.current_key.key_id, REVIEW_KEY_ID);+ assert_eq!(+ trust.current_key.public_key_base64,+ REVIEW_PUBLIC_KEY_BASE64+ );+ assert_eq!(+ evidence_class(&TrustClass::ReviewOnlyPublisherVerified),+ "review-only-not-release-evidence"+ );+ assert_ne!(+ trust.current_key.public_key_base64,+ BASE64.encode(VERIFIED_PUBLIC_KEY)+ );+ }++ #[cfg(feature = "review-trust-root")]+ #[test]+ fn mcp_install_requires_confirm_after_returning_the_exact_verified_plan() {+ static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());+ let _guard = ENV_LOCK.lock().unwrap();+ let temp = TempDir::new().unwrap();+ let (_archive, catalog) = review_fixture(temp.path());+ let home = temp.path().join("driver-home");+ std::env::set_var("CUA_DRIVER_RS_HOME", &home);+ std::env::set_var("CUA_DRIVER_PERCEPTION_CATALOG", &catalog);++ let (_, plan) = install_extension_from_mcp(false).unwrap();+ assert_eq!(plan["extension"], "perception");+ assert_eq!(plan["artifact"], "cua-perception 1.0.0");+ assert_eq!(plan["target"], current_target().unwrap());+ assert_eq!(plan["publisher_id"], REVIEW_PUBLISHER_ID);+ assert_eq!(plan["publisher_name"], REVIEW_PUBLISHER_NAME);+ assert_eq!(plan["publisher_key_id"], REVIEW_KEY_ID);+ assert_eq!(plan["signing_key_algorithm"], "ed25519");+ assert_eq!(plan["signing_key_status"], "verified");+ assert_eq!(plan["publisher_signature_verified"], true);+ assert_eq!(plan["trust"], "review-only-publisher-verified");+ assert_eq!(plan["evidence_class"], "review-only-not-release-evidence");+ assert_eq!(+ plan["artifact_source"],+ temp.path()+ .join("review-extension.tar.gz")+ .to_string_lossy()+ .as_ref()+ );+ assert_eq!(+ plan["destination"],+ home.join("extensions/cua-perception/versions/1.0.0")+ .to_string_lossy()+ .as_ref()+ );+ assert!(plan["download_size"].as_u64().unwrap() > 0);+ assert!(plan["installed_size"].as_u64().unwrap() > 0);+ assert_eq!(plan["models"][0]["revision"], "model-v1");+ assert_eq!(plan["models"][0]["original_sha256"], "1".repeat(64));+ assert_eq!(plan["models"][0]["conversion_sha256"], hex_sha256(b"model"));+ assert_eq!(plan["components"][0]["license"], "AGPL-3.0-or-later");+ assert_eq!(plan["license_notices"][0]["license"], "AGPL-3.0-or-later");+ assert_eq!(plan["authorization"]["request"], "mcp-install");+ assert_eq!(plan["authorization"]["confirmation_required"], true);+ assert_eq!(plan["authorization"]["confirmation_received"], false);+ assert_eq!(plan["authorization"]["mutation_authorized"], false);+ assert_eq!(plan["authorization"]["mutation_performed"], false);+ assert_eq!(plan["mutation_performed"], false);+ assert_eq!(plan["ran"], false);+ assert!(!home.join("extensions/cua-perception").exists());++ let (_, installed) = install_extension_from_mcp(true).unwrap();+ assert_eq!(installed["ran"], true);+ assert_eq!(installed["installed"], true);+ assert_eq!(installed["installed_version"], "1.0.0");+ assert_eq!(installed["authorization"]["confirmation_received"], true);+ assert_eq!(installed["authorization"]["mutation_authorized"], true);+ assert_eq!(installed["authorization"]["mutation_performed"], true);+ assert_eq!(installed["mutation_performed"], true);+ assert!(home.join("extensions/cua-perception/active.json").is_file());++ std::env::remove_var("CUA_DRIVER_PERCEPTION_CATALOG");+ std::env::remove_var("CUA_DRIVER_RS_HOME");+ }++ fn test_catalog_payload(key_id: &str, version: u64) -> CatalogPayload {+ CatalogPayload {+ schema_version: CATALOG_SCHEMA_VERSION,+ catalog_version: version,+ expires_unix: 900,+ publisher_id: expected_publisher_id().to_owned(),+ publisher_name: expected_publisher_name().to_owned(),+ key_id: key_id.to_owned(),+ extension_id: "cua-perception".to_owned(),+ version: format!("1.0.{version}"),+ target: current_target().unwrap(),+ archive: "extension.tar.gz".to_owned(),+ archive_size: 1,+ archive_sha256: "0".repeat(64),+ manifest_sha256: "1".repeat(64),+ license: "Apache-2.0".to_owned(),+ source: "https://github.com/trycua/cua".to_owned(),+ corresponding_source_uri: "https://github.com/trycua/cua".to_owned(),+ corresponding_source_revision: "test".to_owned(),+ provenance: "test catalog".to_owned(),+ next_key: None,+ }+ }++ fn test_publisher_key(+ key_id: &str,+ pair: &ring::signature::Ed25519KeyPair,+ valid_from_unix: u64,+ valid_until_unix: u64,+ ) -> PublisherKey {+ use ring::signature::KeyPair as _;+ PublisherKey {+ key_id: key_id.to_owned(),+ public_key_base64: BASE64.encode(pair.public_key().as_ref()),+ valid_from_unix,+ valid_until_unix,+ }+ }++ fn sign_test_catalog(+ pair: &ring::signature::Ed25519KeyPair,+ payload: CatalogPayload,+ ) -> SignedCatalog {+ SignedCatalog {+ signature_algorithm: "ed25519".to_owned(),+ signature: BASE64.encode(pair.sign(&serde_json::to_vec(&payload).unwrap()).as_ref()),+ payload,+ }+ }++ #[test]+ fn publisher_key_rotation_enforces_windows_and_rollback() {+ let current = ring::signature::Ed25519KeyPair::from_seed_unchecked(&[7; 32]).unwrap();+ let next = ring::signature::Ed25519KeyPair::from_seed_unchecked(&[9; 32]).unwrap();+ let current_key = test_publisher_key("current", ¤t, 100, 800);+ let next_key = test_publisher_key("next", &next, 200, 900);+ let trust = PublisherTrust {+ schema_version: 1,+ publisher_id: expected_publisher_id().to_owned(),+ generation: 1,+ highest_catalog_version: 0,+ current_key: current_key.clone(),+ pending_key: None,+ };+ let entry = registry_entry("cua-perception").unwrap();++ let valid = sign_test_catalog(¤t, test_catalog_payload("current", 1));+ let accepted = verify_catalog_at(entry, &valid, &trust, 150).unwrap();+ assert_eq!(accepted.highest_catalog_version, 1);++ let mut tampered = valid.clone();+ tampered.payload.archive_size = 2;+ assert!(verify_catalog_at(entry, &tampered, &trust, 150)+ .unwrap_err()+ .to_string()+ .contains("signature verification"));++ let mut rotation_payload = test_catalog_payload("current", 2);+ rotation_payload.next_key = Some(next_key.clone());+ let rotation = sign_test_catalog(¤t, rotation_payload);+ let pending = verify_catalog_at(entry, &rotation, &trust, 150).unwrap();+ assert_eq!(pending.pending_key.as_ref().unwrap().key_id, "next");++ let mut retrograde_payload = test_catalog_payload("current", 2);+ retrograde_payload.next_key = Some(test_publisher_key("retrograde", &next, 100, 900));+ assert!(verify_catalog_at(+ entry,+ &sign_test_catalog(¤t, retrograde_payload),+ &trust,+ 150,+ )+ .unwrap_err()+ .to_string()+ .contains("invalid rotation window"));++ let next_catalog = sign_test_catalog(&next, test_catalog_payload("next", 3));+ assert!(verify_catalog_at(entry, &next_catalog, &pending, 199)+ .unwrap_err()+ .to_string()+ .contains("not valid yet"));+ let promoted = verify_catalog_at(entry, &next_catalog, &pending, 250).unwrap();+ assert_eq!(promoted.current_key.key_id, "next");+ assert_eq!(promoted.generation, 2);+ assert!(promoted.pending_key.is_none());++ let retired = sign_test_catalog(¤t, test_catalog_payload("current", 4));+ assert!(verify_catalog_at(entry, &retired, &promoted, 300)+ .unwrap_err()+ .to_string()+ .contains("retired"));++ let rollback = sign_test_catalog(&next, test_catalog_payload("next", 3));+ assert!(verify_catalog_at(entry, &rollback, &promoted, 300)+ .unwrap_err()+ .to_string()+ .contains("anti-rollback"));++ let expired_trust = PublisherTrust {+ current_key: test_publisher_key("expired", ¤t, 100, 200),+ ..trust+ };+ let expired = sign_test_catalog(¤t, test_catalog_payload("expired", 5));+ assert!(verify_catalog_at(entry, &expired, &expired_trust, 200)+ .unwrap_err()+ .to_string()+ .contains("expired"));+ }++ #[test]+ fn catalog_verification_rejects_invalid_trust_and_stale_two_phase_decisions() {+ let pair = ring::signature::Ed25519KeyPair::from_seed_unchecked(&[11; 32]).unwrap();+ let key = test_publisher_key("current", &pair, 1, u64::MAX);+ let entry = registry_entry("cua-perception").unwrap();+ let mut payload = test_catalog_payload("current", 1);+ payload.expires_unix = u64::MAX;+ let signed = sign_test_catalog(&pair, payload.clone());+ let trust = PublisherTrust {+ schema_version: 1,+ publisher_id: expected_publisher_id().to_owned(),+ generation: 1,+ highest_catalog_version: 0,+ current_key: key,+ pending_key: None,+ };+ let mut invalid_trust = trust.clone();+ invalid_trust.generation = 0;+ assert!(verify_catalog_at(entry, &signed, &invalid_trust, 100)+ .unwrap_err()+ .to_string()+ .contains("trust state is invalid"));++ let temp = TempDir::new().unwrap();+ let store = ExtensionStore::new(temp.path().join("extensions"));+ let root = ensure_private_directory_path(&store.root).unwrap();+ store.commit_publisher_trust_locked(&root, &trust).unwrap();+ let decision = verify_catalog_at(entry, &signed, &trust, 100).unwrap();+ let mut advanced = trust.clone();+ advanced.highest_catalog_version = 2;+ store+ .commit_publisher_trust_locked(&root, &advanced)+ .unwrap();+ let source = InstallSource {+ archive: temp.path().join("must-not-be-opened.tar.gz"),+ trust: verified_trust_class(),+ catalog: Some(payload),+ signed_catalog: Some(signed),+ trust_update: Some(decision),+ };+ let error = store.install_source(entry, &source, false).unwrap_err();+ assert!(format!("{error:#}").contains("anti-rollback"));+ assert!(!store.extension_dir(entry.id).exists());+ }++ #[test]+ fn publisher_trust_state_is_durable_and_recovers_backup() {+ let temp = TempDir::new().unwrap();+ let store = ExtensionStore::new(temp.path().join("extensions"));+ let root = ensure_private_directory_path(&store.root).unwrap();+ let mut trust = initial_publisher_trust();+ trust.highest_catalog_version = 7;+ store.commit_publisher_trust_locked(&root, &trust).unwrap();+ assert_eq!(store.load_publisher_trust().unwrap(), trust);++ root.rename(TRUST_NAME, &root, TRUST_BACKUP_NAME).unwrap();+ write_new_file_at(&root, TRUST_NEW_NAME, b"interrupted").unwrap();+ store.recover_publisher_trust_locked(&root).unwrap();+ assert_eq!(store.load_publisher_trust().unwrap(), trust);+ assert!(!store.root.join(TRUST_BACKUP_NAME).exists());+ assert!(!store.root.join(TRUST_NEW_NAME).exists());+ }++ #[test]+ fn model_hash_must_exactly_match_the_declared_file_hash() {+ let file_hash = hex_sha256(b"model");+ let manifest = ExtensionManifest {+ schema_version: MANIFEST_SCHEMA_VERSION,+ id: "cua-perception".to_owned(),+ version: "1.0.0".to_owned(),+ driver_version: format!("={}", env!("CARGO_PKG_VERSION")),+ protocol_version: 1,+ target: current_target().unwrap(),+ entrypoint: "bin/cua-perception".to_owned(),+ files: vec![+ ManifestFile {+ path: "bin/cua-perception".to_owned(),+ sha256: hex_sha256(b"worker"),+ executable: true,+ },+ ManifestFile {+ path: "models/parser.bin".to_owned(),+ sha256: file_hash.clone(),+ executable: false,+ },+ ],+ models: vec![ManifestModel {+ path: "models/parser.bin".to_owned(),+ revision: "model-v1".to_owned(),+ original_sha256: "1".repeat(64),+ conversion_sha256: "0".repeat(64),+ license_file: None,+ }],+ components: vec![ComponentLicense {+ name: "model-runtime".to_owned(),+ version: "1.0.0".to_owned(),+ license: "Apache-2.0".to_owned(),+ notice: "test notice".to_owned(),+ source_uri: "https://example.invalid/source".to_owned(),+ source_revision: "abc123".to_owned(),+ notice_file: None,+ }],+ corresponding_source_file: None,+ license: "Apache-2.0".to_owned(),+ source: "https://github.com/trycua/cua".to_owned(),+ corresponding_source_uri: "https://github.com/trycua/cua".to_owned(),+ corresponding_source_revision: "test".to_owned(),+ provenance: "test".to_owned(),+ health_args: Vec::new(),+ self_test_args: Vec::new(),+ };+ let files = vec![+ ArchiveFile {+ path: MANIFEST_NAME.to_owned(),+ sha256: "0".repeat(64),+ size: 1,+ },+ ArchiveFile {+ path: "bin/cua-perception".to_owned(),+ sha256: hex_sha256(b"worker"),+ size: 6,+ },+ ArchiveFile {+ path: "models/parser.bin".to_owned(),+ sha256: file_hash,+ size: 5,+ },+ ];+ assert!(+ validate_manifest(&manifest, registry_entry("cua-perception").unwrap(), &files)+ .unwrap_err()+ .to_string()+ .contains("model hash")+ );+ }++ #[test]+ fn removal_refuses_unowned_files() {+ let temp = TempDir::new().unwrap();+ let store = ExtensionStore::new(temp.path().join("extensions"));+ let entry = registry_entry("cua-perception").unwrap();+ let archive = fixture_archive(+ temp.path(),+ "1.0.0",+ ¤t_target().unwrap(),+ 1,+ b"worker",+ );+ store.install_archive(entry, &archive).unwrap();+ fs::write(store.extension_dir(entry.id).join("foreign"), b"keep").unwrap();+ let error = store.remove(entry).unwrap_err().to_string();+ assert!(error.contains("unowned state"));+ assert_eq!(+ fs::read(store.extension_dir(entry.id).join("foreign")).unwrap(),+ b"keep"+ );+ }++ #[cfg(unix)]+ #[test]+ fn removal_rejects_a_swapped_versions_symlink_without_touching_its_target() {+ use std::os::unix::fs::symlink;++ let temp = TempDir::new().unwrap();+ let store = ExtensionStore::new(temp.path().join("extensions"));+ let entry = registry_entry("cua-perception").unwrap();+ let archive = fixture_archive(+ temp.path(),+ "1.0.0",+ ¤t_target().unwrap(),+ 1,+ b"worker",+ );+ store.install_archive(entry, &archive).unwrap();+ let external = temp.path().join("external");+ fs::create_dir(&external).unwrap();+ fs::write(external.join("sentinel"), b"keep").unwrap();+ let versions = store.versions_dir(entry.id);+ fs::rename(&versions, temp.path().join("owned-versions")).unwrap();+ fs::remove_file(store.extension_dir(entry.id).join(ACTIVE_NAME)).unwrap();+ symlink(&external, &versions).unwrap();++ assert!(store.remove(entry).is_err());+ assert_eq!(fs::read(external.join("sentinel")).unwrap(), b"keep");+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver/src/main.rs b/libs/cua-driver/rust/crates/cua-driver/src/main.rsindex 5d6ac1f147..2531186727 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/main.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/main.rs@@ -23,9 +23,11 @@ mod check_update_tool;mod cli;mod doctor;mod driver_service_http;+mod extension_manager;mod history_runtime;mod mcp_envelope;mod mcp_http;+mod perception_cli;mod private_worker;mod proxy;mod release_channel;@@ -280,6 +282,11 @@ fn maybe_init_pip() {// ── Public SDK runtime host ──────────────────────────────────────────────+fn register_host_tools(registry: &mut cua_driver_core::tool::ToolRegistry) {+ history_runtime::register_host_tools(registry);+ extension_manager::register_host_tools(registry);+}+/// Construct the canonical SDK-owned runtime for the CLI or daemon host./// The private socket and MCP layers consume this object downstream.fn build_driver(@@ -293,7 +300,7 @@ fn build_driver(host_bundle_id: std::env::var(cua_driver_core::HOST_BUNDLE_ID_ENV).ok(),claude_code_compatibility: compatibility_mode,prepare_desktop_environment: true,- register_host_tools: Some(history_runtime::register_host_tools),+ register_host_tools: Some(register_host_tools),authorization_host: None,activity_observer: None,})@@ -327,7 +334,7 @@ fn inspect_tools_without_runtime() -> serde_json::Value {host_bundle_id: None,claude_code_compatibility: false,prepare_desktop_environment: false,- register_host_tools: Some(history_runtime::register_host_tools),+ register_host_tools: Some(register_host_tools),authorization_host: None,activity_observer: None,})@@ -458,6 +465,7 @@ mod mcp_runtime_selection_tests {#[cfg(target_os = "macos")]fn main() {+ cua_driver_sdk::configure_perception_client_provider(extension_manager::perception_client);if let Some(code) = platform_macos::permissions::gate::run_permission_probe_if_requested() {std::process::exit(code);}@@ -538,6 +546,7 @@ fn main() {}cli::Command::Serve {socket,+ pid_file,permission_mode,dangerously_bypass_approvals,capability_manifest,@@ -628,7 +637,7 @@ fn main() {}};let sp = socket.unwrap_or_else(serve::default_socket_path);- let pid_path = serve::default_pid_file_path();+ let pid_path = pid_file.unwrap_or_else(serve::default_pid_file_path);// Bind the Unix socket FIRST, on a background thread, BEFORE// running the (blocking) permissions gate (#1761).@@ -811,6 +820,12 @@ fn main() {cli::Command::Skills { subcommand, flags } => {skills::run(&subcommand, &flags);}+ cli::Command::Extension { args } => {+ extension_manager::run(&args);+ }+ cli::Command::Perception { args } => {+ perception_cli::run(&args);+ }cli::Command::CursorTheme { args } => {run_cursor_theme_command(&args);}@@ -882,6 +897,7 @@ fn main() {#[cfg(not(target_os = "macos"))]fn main() -> anyhow::Result<()> {+ cua_driver_sdk::configure_perception_client_provider(extension_manager::perception_client);if let Some(code) = history_runtime::run_offline_purge_if_requested() {std::process::exit(code);}@@ -944,6 +960,7 @@ fn main() -> anyhow::Result<()> {}cli::Command::Serve {socket,+ pid_file,permission_mode,dangerously_bypass_approvals,capability_manifest,@@ -995,7 +1012,7 @@ fn main() -> anyhow::Result<()> {)?;maybe_init_pip();let sp = socket.unwrap_or_else(serve::default_socket_path);- let pid_path = serve::default_pid_file_path();+ let pid_path = pid_file.unwrap_or_else(serve::default_pid_file_path);// run_serve_cmd builds its own runtime; must run on a fresh thread.std::thread::spawn(move || {serve::run_serve_cmd(driver, &sp, Some(&pid_path));@@ -1100,6 +1117,14 @@ fn main() -> anyhow::Result<()> {skills::run(&subcommand, &flags);return Ok(());}+ cli::Command::Extension { args } => {+ extension_manager::run(&args);+ return Ok(());+ }+ cli::Command::Perception { args } => {+ perception_cli::run(&args);+ return Ok(());+ }cli::Command::CursorTheme { args } => {run_cursor_theme_command(&args);}diff --git a/libs/cua-driver/rust/crates/cua-driver/src/perception_cli.rs b/libs/cua-driver/rust/crates/cua-driver/src/perception_cli.rsnew file mode 100644index 0000000000..243087c6dc--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver/src/perception_cli.rs@@ -0,0 +1,656 @@+use std::io::{Cursor, Read};+use std::path::{Component, Path, PathBuf};+use std::time::Instant;++use anyhow::Result as AnyhowResult;+use cap_fs_ext::{DirExt, FollowSymlinks, OpenOptionsFollowExt};+use cap_std::ambient_authority;+use cap_std::fs::{Dir, OpenOptions};+use image::{ImageDecoder, Limits};+use serde::{Deserialize, Serialize};+use serde_json::json;+use sha2::{Digest, Sha256};++use cua_driver_contract::{+ ParseVisualRegionsInput, ParseVisualRegionsOptions, VisualActionCoordinateSpace,+ VisualCaptureProvenance, VisualCaptureSource, VisualParseError, VisualParseErrorCode,+ VisualScreenshotReference,+};+use cua_driver_core::perception_client::PerceptionCancellation;+use cua_driver_core::perception_tools::build_local_output;++const MAX_CAPTURE_BYTES: u64 = 1024 * 1024;+const MAX_PNG_BYTES: u64 = 64 * 1024 * 1024;+const MAX_PNG_DIMENSION: u32 = 16_384;+const MAX_DECODED_BYTES: u64 = 512 * 1024 * 1024;++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+struct LocalCaptureMetadata {+ source: LocalCaptureSource,+ #[serde(default)]+ snapshot_id: Option<String>,+ #[serde(default)]+ captured_at: Option<String>,+}++#[derive(Debug, Deserialize)]+#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]+enum LocalCaptureSource {+ Window { pid: u32, window_id: u64 },+ PrimaryDesktop { display_id: String },+}++impl From<LocalCaptureSource> for VisualCaptureSource {+ fn from(source: LocalCaptureSource) -> Self {+ match source {+ LocalCaptureSource::Window { pid, window_id } => Self::Window { pid, window_id },+ LocalCaptureSource::PrimaryDesktop { display_id } => {+ Self::PrimaryDesktop { display_id }+ }+ }+ }+}++#[derive(Debug, Serialize)]+struct ErrorEnvelope {+ ok: bool,+ error: CliError,+}++#[derive(Debug, Serialize)]+struct CliError {+ code: String,+ message: String,+ retryable: bool,+ #[serde(skip_serializing_if = "Option::is_none")]+ detail: Option<String>,+}++impl CliError {+ fn new(code: &str, message: impl Into<String>) -> Self {+ Self {+ code: code.to_owned(),+ message: message.into(),+ retryable: false,+ detail: None,+ }+ }++ fn with_detail(code: &str, message: impl Into<String>, detail: impl Into<String>) -> Self {+ Self {+ code: code.to_owned(),+ message: message.into(),+ retryable: false,+ detail: Some(detail.into()),+ }+ }+}++impl From<VisualParseError> for CliError {+ fn from(error: VisualParseError) -> Self {+ Self {+ code: visual_error_code(error.code).to_owned(),+ message: error.message,+ retryable: error.retryable,+ detail: error.detail,+ }+ }+}++pub fn run(args: &[String]) {+ if let Err(error) = run_inner(args) {+ let envelope = ErrorEnvelope { ok: false, error };+ println!(+ "{}",+ serde_json::to_string(&envelope).unwrap_or_else(|_| {+ r#"{"ok":false,"error":{"code":"internal_error","message":"serialize perception error","retryable":false}}"#.to_owned()+ })+ );+ std::process::exit(1);+ }+}++fn run_inner(args: &[String]) -> Result<(), CliError> {+ let (image_path, capture_path) = parse_args(args)?;+ let capture_bytes = read_bounded_file(&capture_path, MAX_CAPTURE_BYTES, "capture metadata")?;+ let metadata: LocalCaptureMetadata =+ serde_json::from_slice(&capture_bytes).map_err(|error| {+ CliError::with_detail(+ "invalid_capture_metadata",+ "capture metadata is invalid",+ error.to_string(),+ )+ })?;+ if metadata+ .snapshot_id+ .as_ref()+ .is_some_and(|value| value.trim().is_empty())+ {+ return Err(CliError::new(+ "invalid_capture_metadata",+ "snapshot_id must not be empty",+ ));+ }+ if metadata+ .captured_at+ .as_ref()+ .is_some_and(|value| !is_rfc3339(value))+ {+ return Err(CliError::new(+ "invalid_capture_metadata",+ "captured_at must be an RFC3339 timestamp",+ ));+ }+ match &metadata.source {+ LocalCaptureSource::Window { pid, window_id } if *pid == 0 || *window_id == 0 => {+ return Err(CliError::new(+ "invalid_capture_metadata",+ "window capture metadata requires positive pid and window_id",+ ));+ }+ LocalCaptureSource::PrimaryDesktop { display_id } if display_id != "primary" => {+ return Err(CliError::new(+ "invalid_capture_metadata",+ "desktop capture metadata supports only display_id \"primary\"",+ ));+ }+ _ => {}+ }++ let png = read_bounded_file(&image_path, MAX_PNG_BYTES, "PNG image")?;+ let (width, height) = validate_png(&png).map_err(|error| {+ CliError::with_detail("invalid_png", "PNG image is invalid", format!("{error:#}"))+ })?;+ let digest = format!("{:x}", Sha256::digest(&png));+ let capture_id = local_capture_id(&digest);+ let input = ParseVisualRegionsInput {+ capture_id: capture_id.clone(),+ options: ParseVisualRegionsOptions::default(),+ };+ let provenance = VisualCaptureProvenance {+ capture_id: capture_id.clone(),+ source: metadata.source.into(),+ screenshot: VisualScreenshotReference {+ reference: format!("local-png-sha256:{digest}"),+ width,+ height,+ mime_type: "image/png".to_owned(),+ sha256: Some(digest.clone()),+ },+ // This describes region coordinates only. The local_input block below+ // explicitly denies any Driver action authority.+ action_coordinate_space: VisualActionCoordinateSpace::ScreenshotPixels,+ captured_at: metadata.captured_at,+ };++ let client = crate::extension_manager::perception_client_for_cli().map_err(|cause| {+ CliError::from(local_visual_error(+ VisualParseErrorCode::ArtifactInvalid,+ cause.to_string(),+ ))+ })?;+ let runtime = tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .map_err(|error| {+ CliError::with_detail(+ "internal_error",+ "create perception runtime",+ error.to_string(),+ )+ })?;+ let started = Instant::now();+ let worker = runtime+ .block_on(client.parse(+ &capture_id,+ width,+ height,+ &png,+ &PerceptionCancellation::default(),+ ))+ .map_err(CliError::from)?;+ let output = build_local_output(&input, provenance, worker, started.elapsed().as_millis())+ .map_err(CliError::from)?;+ let mut value = serde_json::to_value(output).map_err(|error| {+ CliError::with_detail(+ "internal_error",+ "serialize perception result",+ error.to_string(),+ )+ })?;+ insert_local_input(&mut value, metadata.snapshot_id, digest)?;+ println!(+ "{}",+ serde_json::to_string_pretty(&value).map_err(|error| {+ CliError::with_detail(+ "internal_error",+ "serialize perception result",+ error.to_string(),+ )+ })?+ );+ Ok(())+}++fn parse_args(args: &[String]) -> Result<(PathBuf, PathBuf), CliError> {+ if args.first().map(String::as_str) != Some("parse") {+ return Err(CliError::new(+ "invalid_arguments",+ "usage: cua-driver perception parse --image <png> --capture <capture.json> --json",+ ));+ }+ let mut image = None;+ let mut capture = None;+ let mut json = false;+ let mut index = 1;+ while index < args.len() {+ match args[index].as_str() {+ "--image" | "--capture" => {+ let flag = args[index].as_str();+ let value = args+ .get(index + 1)+ .filter(|value| !value.starts_with('-'))+ .ok_or_else(|| {+ CliError::new("invalid_arguments", format!("{flag} requires a path"))+ })?;+ let slot = if flag == "--image" {+ &mut image+ } else {+ &mut capture+ };+ if slot.replace(PathBuf::from(value)).is_some() {+ return Err(CliError::new(+ "invalid_arguments",+ format!("duplicate option {flag}"),+ ));+ }+ index += 2;+ }+ "--json" => {+ if json {+ return Err(CliError::new("invalid_arguments", "duplicate flag --json"));+ }+ json = true;+ index += 1;+ }+ value => {+ return Err(CliError::new(+ "invalid_arguments",+ format!("unknown perception parse argument {value:?}"),+ ));+ }+ }+ }+ if !json {+ return Err(CliError::new(+ "invalid_arguments",+ "perception parse requires --json",+ ));+ }+ Ok((+ image.ok_or_else(|| {+ CliError::new(+ "invalid_arguments",+ "perception parse requires --image <png>",+ )+ })?,+ capture.ok_or_else(|| {+ CliError::new(+ "invalid_arguments",+ "perception parse requires --capture <capture.json>",+ )+ })?,+ ))+}++fn read_bounded_file(path: &Path, maximum: u64, label: &str) -> Result<Vec<u8>, CliError> {+ let (directory, name) = open_parent_nofollow(path).map_err(|error| {+ CliError::with_detail(+ "input_open_failed",+ format!("cannot open {label}"),+ format!("{}: {error:#}", path.display()),+ )+ })?;+ let mut options = OpenOptions::new();+ options.read(true).follow(FollowSymlinks::No);+ #[cfg(unix)]+ {+ use cap_std::fs::OpenOptionsExt;+ options.custom_flags(libc::O_NONBLOCK);+ }+ let cap_file = directory.open_with(name, &options).map_err(|error| {+ CliError::with_detail(+ "input_open_failed",+ format!("cannot open {label}"),+ format!("{}: {error}", path.display()),+ )+ })?;+ let mut file = cap_file.into_std();+ let metadata = file.metadata().map_err(|error| {+ CliError::with_detail(+ "input_open_failed",+ format!("cannot inspect {label}"),+ format!("{}: {error}", path.display()),+ )+ })?;+ #[cfg(windows)]+ {+ use std::os::windows::fs::MetadataExt;+ const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;+ if metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {+ return Err(CliError::new(+ "input_not_regular_file",+ format!("{label} must not be a symlink or reparse point"),+ ));+ }+ }+ if !metadata.file_type().is_file() || metadata.file_type().is_symlink() {+ return Err(CliError::new(+ "input_not_regular_file",+ format!("{label} is not a regular file"),+ ));+ }+ if metadata.len() > maximum {+ return Err(CliError::new(+ "input_too_large",+ format!("{label} exceeds the {maximum}-byte limit"),+ ));+ }+ let mut bytes = Vec::new();+ file.by_ref()+ .take(maximum + 1)+ .read_to_end(&mut bytes)+ .map_err(|error| {+ CliError::with_detail(+ "input_read_failed",+ format!("cannot read {label}"),+ format!("{}: {error}", path.display()),+ )+ })?;+ if bytes.len() as u64 > maximum {+ return Err(CliError::new(+ "input_too_large",+ format!("{label} exceeds the {maximum}-byte limit"),+ ));+ }+ Ok(bytes)+}++fn open_parent_nofollow(path: &Path) -> AnyhowResult<(Dir, std::ffi::OsString)> {+ let parent = path+ .parent()+ .ok_or_else(|| anyhow::anyhow!("path has no parent"))?;+ let name = path+ .file_name()+ .ok_or_else(|| anyhow::anyhow!("path has no final component"))?+ .to_owned();+ let (mut directory, names) = directory_path_anchor(parent)?;+ for component in names {+ directory = directory.open_dir_nofollow(component)?;+ }+ Ok((directory, name))+}++fn directory_path_anchor(path: &Path) -> AnyhowResult<(Dir, Vec<std::ffi::OsString>)> {+ #[cfg(target_os = "macos")]+ let normalized;+ #[cfg(target_os = "macos")]+ let path = if let Ok(suffix) = path.strip_prefix("/var") {+ normalized = Path::new("/private/var").join(suffix);+ normalized.as_path()+ } else if let Ok(suffix) = path.strip_prefix("/tmp") {+ normalized = Path::new("/private/tmp").join(suffix);+ normalized.as_path()+ } else if let Ok(suffix) = path.strip_prefix("/etc") {+ normalized = Path::new("/private/etc").join(suffix);+ normalized.as_path()+ } else {+ path+ };+ let mut components = path.components().peekable();+ let mut anchor = PathBuf::new();+ if let Some(Component::Prefix(prefix)) = components.peek().copied() {+ anchor.push(prefix.as_os_str());+ components.next();+ }+ if matches!(components.peek(), Some(Component::RootDir)) {+ anchor.push(std::path::MAIN_SEPARATOR_STR);+ components.next();+ } else if anchor.as_os_str().is_empty() {+ anchor.push(".");+ }+ let mut names = Vec::new();+ for component in components {+ match component {+ Component::CurDir => {}+ Component::Normal(name) => names.push(name.to_owned()),+ Component::ParentDir => anyhow::bail!("path must not contain parent traversal"),+ Component::Prefix(_) | Component::RootDir => anyhow::bail!("path has an invalid root"),+ }+ }+ Ok((Dir::open_ambient_dir(anchor, ambient_authority())?, names))+}++fn validate_png(bytes: &[u8]) -> AnyhowResult<(u32, u32)> {+ let mut limits = Limits::default();+ limits.max_image_width = Some(MAX_PNG_DIMENSION);+ limits.max_image_height = Some(MAX_PNG_DIMENSION);+ limits.max_alloc = Some(MAX_DECODED_BYTES);+ let decoder = image::codecs::png::PngDecoder::with_limits(Cursor::new(bytes), limits)?;+ let dimensions = decoder.dimensions();+ if dimensions.0 == 0 || dimensions.1 == 0 || decoder.total_bytes() > MAX_DECODED_BYTES {+ anyhow::bail!("PNG dimensions exceed local perception limits");+ }+ Ok(dimensions)+}++fn local_capture_id(digest: &str) -> String {+ format!("local_png_{}", &digest[..24])+}++fn insert_local_input(+ value: &mut serde_json::Value,+ snapshot_id: Option<String>,+ digest: String,+) -> Result<(), CliError> {+ value+ .as_object_mut()+ .ok_or_else(|| CliError::new("internal_error", "perception result is not an object"))?+ .insert(+ "local_input".to_owned(),+ json!({+ "kind": "local_file",+ "snapshot_id": snapshot_id,+ "sha256": digest,+ "action_eligible": false,+ "action_authority": "none",+ "reason": "Local image input is not a Driver-owned capture and cannot authorize input."+ }),+ );+ Ok(())+}++fn is_rfc3339(value: &str) -> bool {+ let bytes = value.as_bytes();+ if bytes.len() < 20+ || bytes.get(4) != Some(&b'-')+ || bytes.get(7) != Some(&b'-')+ || !matches!(bytes.get(10), Some(b'T' | b't'))+ || bytes.get(13) != Some(&b':')+ || bytes.get(16) != Some(&b':')+ {+ return false;+ }+ let Some(year) = decimal(bytes, 0, 4) else {+ return false;+ };+ let Some(month) = decimal(bytes, 5, 2) else {+ return false;+ };+ let Some(day) = decimal(bytes, 8, 2) else {+ return false;+ };+ let Some(hour) = decimal(bytes, 11, 2) else {+ return false;+ };+ let Some(minute) = decimal(bytes, 14, 2) else {+ return false;+ };+ let Some(second) = decimal(bytes, 17, 2) else {+ return false;+ };+ if month == 0+ || month > 12+ || day == 0+ || day > days_in_month(year, month)+ || hour > 23+ || minute > 59+ || second > 60+ {+ return false;+ }+ let mut index = 19;+ if bytes.get(index) == Some(&b'.') {+ index += 1;+ let start = index;+ while bytes.get(index).is_some_and(u8::is_ascii_digit) {+ index += 1;+ }+ if index == start {+ return false;+ }+ }+ match bytes.get(index) {+ Some(b'Z' | b'z') => index + 1 == bytes.len(),+ Some(b'+' | b'-') => {+ bytes.len() == index + 6+ && bytes.get(index + 3) == Some(&b':')+ && decimal(bytes, index + 1, 2).is_some_and(|value| value <= 23)+ && decimal(bytes, index + 4, 2).is_some_and(|value| value <= 59)+ }+ _ => false,+ }+}++fn decimal(bytes: &[u8], start: usize, len: usize) -> Option<u32> {+ bytes+ .get(start..start + len)?+ .iter()+ .try_fold(0, |value, byte| {+ byte.is_ascii_digit()+ .then_some(value * 10 + u32::from(byte - b'0'))+ })+}++fn days_in_month(year: u32, month: u32) -> u32 {+ match month {+ 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,+ 4 | 6 | 9 | 11 => 30,+ 2 if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) => 29,+ 2 => 28,+ _ => 0,+ }+}++fn local_visual_error(code: VisualParseErrorCode, detail: String) -> VisualParseError {+ VisualParseError {+ code,+ message: "the installed cua-perception extension is invalid".to_owned(),+ retryable: false,+ detail: Some(detail),+ }+}++fn visual_error_code(code: VisualParseErrorCode) -> &'static str {+ match code {+ VisualParseErrorCode::NotInstalled => "not_installed",+ VisualParseErrorCode::CaptureNotFound => "capture_not_found",+ VisualParseErrorCode::CaptureExpired => "capture_expired",+ VisualParseErrorCode::CaptureStale => "capture_stale",+ VisualParseErrorCode::CaptureGenerationMismatch => "capture_generation_mismatch",+ VisualParseErrorCode::UnsupportedTarget => "unsupported_target",+ VisualParseErrorCode::UnsupportedPlatform => "unsupported_platform",+ VisualParseErrorCode::IncompatibleProtocol => "incompatible_protocol",+ VisualParseErrorCode::InvalidFrame => "invalid_frame",+ VisualParseErrorCode::WorkerLaunchFailed => "worker_launch_failed",+ VisualParseErrorCode::WorkerCrashed => "worker_crashed",+ VisualParseErrorCode::WorkerCancelled => "worker_cancelled",+ VisualParseErrorCode::Timeout => "timeout",+ VisualParseErrorCode::ResourceLimitExceeded => "resource_limit_exceeded",+ VisualParseErrorCode::ArtifactInvalid => "artifact_invalid",+ VisualParseErrorCode::InferenceFailed => "inference_failed",+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn arguments_require_both_paths_and_json() {+ assert!(parse_args(&["parse".into(), "--json".into()]).is_err());+ assert!(parse_args(&[+ "parse".into(),+ "--image".into(),+ "image.png".into(),+ "--capture".into(),+ "capture.json".into(),+ ])+ .is_err());+ assert!(parse_args(&[+ "parse".into(),+ "--image".into(),+ "image.png".into(),+ "--capture".into(),+ "capture.json".into(),+ "--json".into(),+ ])+ .is_ok());+ }++ #[test]+ fn validates_rfc3339_timestamps() {+ for valid in [+ "2026-09-18T12:00:00Z",+ "2024-02-29t23:59:60.123+05:30",+ "2026-09-18T12:00:00-00:00",+ ] {+ assert!(is_rfc3339(valid), "rejected {valid}");+ }+ for invalid in [+ "2026-09-18",+ "2026-02-29T12:00:00Z",+ "2026-09-18T24:00:00Z",+ "2026-09-18T12:00:00",+ "2026-09-18T12:00:00.Z",+ ] {+ assert!(!is_rfc3339(invalid), "accepted {invalid}");+ }+ }++ #[test]+ fn successful_local_result_is_non_actionable_and_uses_a_separate_id_namespace() {+ let digest = "ab".repeat(32);+ let capture_id = local_capture_id(&digest);+ let mut output = json!({+ "schema": "cua.visual_regions_v1",+ "capture": {"capture_id": capture_id}+ });+ insert_local_input(&mut output, Some("snapshot-1".into()), digest).unwrap();++ assert_eq!(output["schema"], "cua.visual_regions_v1");+ assert!(output["capture"]["capture_id"]+ .as_str()+ .unwrap()+ .starts_with("local_png_"));+ assert!(!output["capture"]["capture_id"]+ .as_str()+ .unwrap()+ .starts_with("capture_"));+ assert_eq!(output["local_input"]["action_eligible"], false);+ assert_eq!(output["local_input"]["action_authority"], "none");+ assert!(output["local_input"].get("image_path").is_none());+ assert!(output["local_input"].get("capture_metadata_path").is_none());+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver/src/skills.rs b/libs/cua-driver/rust/crates/cua-driver/src/skills.rsindex a2019376c7..c40d979a16 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/skills.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/skills.rs@@ -84,6 +84,7 @@ const SKILL_FILES: &[&str] = &["MACOS.md","LINUX.md","BROWSER.md",+ "VISUAL.md","RECORDING.md","EMBEDDING.md",];@@ -1500,6 +1501,7 @@ mod tests {("cua-driver-rs-v0.2.20-skills/LINUX.md", b"l"),("cua-driver-rs-v0.2.20-skills/RECORDING.md", b"R"),("cua-driver-rs-v0.2.20-skills/BROWSER.md", b"B"),+ ("cua-driver-rs-v0.2.20-skills/VISUAL.md", b"V"),("cua-driver-rs-v0.2.20-skills/EMBEDDING.md", b"E"),]);let dest = tempdir().unwrap();@@ -1510,6 +1512,7 @@ mod tests {"SKILL.md","RECORDING.md","BROWSER.md",+ "VISUAL.md","EMBEDDING.md",] {assert!(diff --git a/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rs b/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rsindex 2453fec210..46a44dc448 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rs@@ -1797,6 +1797,7 @@ pub(crate) fn capture_cli_completed("permissions" => "permissions","autostart" => "autostart","skills" => "skills",+ "extension" => "extension","config" => "config",_ => "other",};@@ -1952,6 +1953,7 @@ fn fixed_cli_command(command: &str) -> &'static str {"permissions" => "permissions","autostart" => "autostart","skills" => "skills",+ "extension" => "extension","config" => "config",_ => "other",}@@ -2020,6 +2022,16 @@ fn fixed_cli_operation(command: &str, operation: &str) -> &'static str {"path" => "path",_ => "other",},+ "extension" => match operation {+ "list" => "list",+ "info" => "info",+ "status" => "status",+ "install" => "install",+ "update" => "update",+ "uninstall" => "uninstall",+ "path" => "path",+ _ => "other",+ },"update" => match operation {"apply" => "apply","check_only" => "check_only",diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/agent_cursor_showcase_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/agent_cursor_showcase_test.rsindex f3df7facd5..95abd82341 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/agent_cursor_showcase_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/agent_cursor_showcase_test.rs@@ -13,9 +13,14 @@ use image::RgbaImage;const CELL_ID: &str = "desktop-agent-cursor-showcase-px";const SESSION: &str = "Cursor showcase";-// MoveTo offsets the cursor artwork by 16 points so its tip lands on the-// requested coordinate. The session badge follows that artwork anchor.-const MAX_CURSOR_ANCHOR_OFFSET: f64 = 16.0;+// MoveTo offsets the artwork centre by a 16-point vector at 45 degrees so the+// cursor tip lands on the requested coordinate. Each axis moves by 16/sqrt(2),+// and the session badge follows that artwork centre.+const CURSOR_ANCHOR_OFFSET_MAGNITUDE: f64 = 16.0;+const CURSOR_ANCHOR_OFFSET_PER_AXIS: f64 =+ CURSOR_ANCHOR_OFFSET_MAGNITUDE * std::f64::consts::FRAC_1_SQRT_2;+const POINTER_ORACLE_RADIUS: f64 = 24.0;+const BADGE_CURSOR_EXCLUSION: f64 = 34.0;#[test]#[ignore]@@ -187,50 +192,39 @@ fn assert_cursor_and_badge_pixels_changed(cursor_frame.dimensions(),"desktop dimensions changed while checking the cursor overlay");- let scale_x = f64::from(baseline.width()) / logical_width;- let scale_y = f64::from(baseline.height()) / logical_height;- let center_x = (logical_x * scale_x).round() as i64;- let center_y = (logical_y * scale_y).round() as i64;-- // The pointer is anchored at the requested coordinate (with at most the- // renderer's small click offset). The session badge is a separate pill- // centered below it. Keep the regions disjoint so a visible pointer alone- // cannot satisfy the badge oracle, which was possible with the previous- // single large region/count check.- let pointer_radius_x = (48.0 * scale_x).ceil() as i64;- let pointer_radius_y = (48.0 * scale_y).ceil() as i64;+ let regions = cursor_oracle_regions(+ baseline.width(),+ baseline.height(),+ logical_x,+ logical_y,+ logical_width,+ logical_height,+ );let pointer_pixels = changed_pixels_in_rect(baseline,cursor_frame,- center_x - pointer_radius_x,- center_y - pointer_radius_y,- center_x + pointer_radius_x,- center_y + (f64::from(BADGE_CURSOR_GAP) * scale_y).floor() as i64,+ regions.pointer.x0,+ regions.pointer.y0,+ regions.pointer.x1,+ regions.pointer.y1,);-- let badge_half_width = (f64::from(BADGE_MAX_WIDTH) * 0.5 * scale_x).ceil() as i64;- let badge_cursor_exclusion = (34.0 * scale_x).ceil() as i64;- let badge_top = center_y + (f64::from(BADGE_CURSOR_GAP) * scale_y).floor() as i64;- let badge_bottom = center_y- + ((f64::from(BADGE_CURSOR_GAP + BADGE_HEIGHT) + MAX_CURSOR_ANCHOR_OFFSET) * scale_y).ceil()- as i64;// Ignore the center corridor where the pointer's lower edge or glow could// overlap the pill. Requiring changed pixels in the badge's outer wings// makes this an independent badge assertion.let badge_pixels = changed_pixels_in_rect(baseline,cursor_frame,- center_x - badge_half_width,- badge_top,- center_x - badge_cursor_exclusion,- badge_bottom,+ regions.badge_left.x0,+ regions.badge_left.y0,+ regions.badge_left.x1,+ regions.badge_left.y1,) + changed_pixels_in_rect(baseline,cursor_frame,- center_x + badge_cursor_exclusion,- badge_top,- center_x + badge_half_width,- badge_bottom,+ regions.badge_right.x0,+ regions.badge_right.y0,+ regions.badge_right.x1,+ regions.badge_right.y1,);assert!(@@ -238,24 +232,96 @@ fn assert_cursor_and_badge_pixels_changed("agent cursor overlay was incomplete near ({logical_x:.0},{logical_y:.0}): \pointer region changed {pointer_pixels} pixels (minimum 12), \badge region changed {badge_pixels} pixels (minimum 24); \- image={}x{}, logical={}x{}, scale={scale_x:.3}x{scale_y:.3}, \+ image={}x{}, logical={}x{}, scale={:.3}x{:.3}, \pointer_rect=({},{}..{},{}), badge_rect=({},{}..{},{}), \- badge_exclusion={badge_cursor_exclusion}",+ badge_exclusion={}",baseline.width(),baseline.height(),logical_width,logical_height,- center_x - pointer_radius_x,- center_y - pointer_radius_y,- center_x,- center_y + (f64::from(BADGE_CURSOR_GAP) * scale_y).floor() as i64,- center_x - badge_half_width,- badge_top,- center_x + badge_half_width,- badge_bottom,+ regions.scale_x,+ regions.scale_y,+ regions.pointer.x0,+ regions.pointer.y0,+ regions.pointer.x1,+ regions.pointer.y1,+ regions.badge_left.x0,+ regions.badge_left.y0,+ regions.badge_right.x1,+ regions.badge_right.y1,+ (BADGE_CURSOR_EXCLUSION * regions.scale_x).ceil() as i64,);}+#[derive(Clone, Copy, Debug)]+struct PixelRect {+ x0: i64,+ y0: i64,+ x1: i64,+ y1: i64,+}++#[derive(Clone, Copy, Debug)]+struct CursorOracleRegions {+ anchor: (i64, i64),+ scale_x: f64,+ scale_y: f64,+ pointer: PixelRect,+ badge_left: PixelRect,+ badge_right: PixelRect,+}++fn cursor_oracle_regions(+ image_width: u32,+ image_height: u32,+ logical_x: f64,+ logical_y: f64,+ logical_width: f64,+ logical_height: f64,+) -> CursorOracleRegions {+ let scale_x = f64::from(image_width) / logical_width;+ let scale_y = f64::from(image_height) / logical_height;+ let anchor_x = (logical_x + CURSOR_ANCHOR_OFFSET_PER_AXIS) * scale_x;+ let anchor_y = (logical_y + CURSOR_ANCHOR_OFFSET_PER_AXIS) * scale_y;++ // The production artwork is 42 points across. A 24-point radius includes+ // its outline while remaining one logical point above the badge. Floor the+ // pointer bottom and ceil the badge top so fractional and unequal scales+ // cannot round the two regions onto the same pixel row.+ let pointer = PixelRect {+ x0: (anchor_x - POINTER_ORACLE_RADIUS * scale_x).floor() as i64,+ y0: (anchor_y - POINTER_ORACLE_RADIUS * scale_y).floor() as i64,+ x1: (anchor_x + POINTER_ORACLE_RADIUS * scale_x).ceil() as i64,+ y1: (anchor_y + POINTER_ORACLE_RADIUS * scale_y).floor() as i64,+ };+ let badge_half_width = f64::from(BADGE_MAX_WIDTH) * 0.5 * scale_x;+ let badge_exclusion = BADGE_CURSOR_EXCLUSION * scale_x;+ let badge_top = (anchor_y + f64::from(BADGE_CURSOR_GAP) * scale_y).ceil() as i64;+ let badge_bottom =+ (anchor_y + f64::from(BADGE_CURSOR_GAP + BADGE_HEIGHT) * scale_y).ceil() as i64;+ let badge_left = PixelRect {+ x0: (anchor_x - badge_half_width).floor() as i64,+ y0: badge_top,+ x1: (anchor_x - badge_exclusion).floor() as i64,+ y1: badge_bottom,+ };+ let badge_right = PixelRect {+ x0: (anchor_x + badge_exclusion).ceil() as i64,+ y0: badge_top,+ x1: (anchor_x + badge_half_width).ceil() as i64,+ y1: badge_bottom,+ };++ CursorOracleRegions {+ anchor: (anchor_x.round() as i64, anchor_y.round() as i64),+ scale_x,+ scale_y,+ pointer,+ badge_left,+ badge_right,+ }+}+fn changed_pixels_in_rect(baseline: &RgbaImage,cursor_frame: &RgbaImage,@@ -381,60 +447,154 @@ mod pixel_oracle_tests {use super::*;use image::Rgba;- const WIDTH: u32 = 400;- const HEIGHT: u32 = 300;const CURSOR_X: f64 = 200.0;const CURSOR_Y: f64 = 150.0;#[test]- fn accepts_independent_pointer_and_badge_changes() {- let baseline = RgbaImage::new(WIDTH, HEIGHT);- let mut overlay = baseline.clone();- paint_changed_rect(&mut overlay, 196, 146, 200, 150);- paint_changed_rect(&mut overlay, 150, 180, 156, 186);+ fn accepts_colocated_pointer_and_badge_at_1x() {+ assert_colocated_overlay(400, 300, 400.0, 300.0, (211, 161));+ }- assert_cursor_and_badge_pixels_changed(- &baseline,- &overlay,- CURSOR_X,- CURSOR_Y,- f64::from(WIDTH),- f64::from(HEIGHT),+ #[test]+ fn accepts_colocated_pointer_and_badge_at_2x() {+ assert_colocated_overlay(800, 600, 400.0, 300.0, (423, 323));+ }++ #[test]+ fn accepts_colocated_pointer_and_badge_at_fractional_unequal_scale() {+ assert_colocated_overlay(500, 525, 400.0, 300.0, (264, 282));+ }++ #[test]+ fn rejects_meaningfully_desynchronized_pointer() {+ let (baseline, mut overlay, regions) = oracle_images(500, 525, 400.0, 300.0);+ paint_badge(&mut overlay, regions);+ paint_changed_rect_i64(+ &mut overlay,+ regions.anchor.0 + (30.0 * regions.scale_x).round() as i64,+ regions.anchor.1 - 2,+ 4,+ 4,+ );++ let failure = std::panic::catch_unwind(|| {+ assert_cursor_and_badge_pixels_changed(+ &baseline, &overlay, CURSOR_X, CURSOR_Y, 400.0, 300.0,+ );+ });+ assert!(+ failure.is_err(),+ "desynchronized pointer unexpectedly passed");}#[test]- fn accepts_badge_at_shifted_cursor_artwork_anchor() {- let baseline = RgbaImage::new(WIDTH, HEIGHT);- let mut overlay = baseline.clone();- paint_changed_rect(&mut overlay, 196, 146, 200, 150);- paint_changed_rect(&mut overlay, 250, 204, 256, 210);+ fn rejects_meaningfully_desynchronized_badge() {+ let (baseline, mut overlay, regions) = oracle_images(800, 600, 400.0, 300.0);+ paint_pointer(&mut overlay, regions);+ paint_changed_rect_i64(+ &mut overlay,+ regions.badge_left.x0 + 2,+ regions.badge_left.y1 + 8,+ 6,+ 4,+ );++ let failure = std::panic::catch_unwind(|| {+ assert_cursor_and_badge_pixels_changed(+ &baseline, &overlay, CURSOR_X, CURSOR_Y, 400.0, 300.0,+ );+ });+ assert!(failure.is_err(), "desynchronized badge unexpectedly passed");+ }++ #[test]+ fn badge_cannot_satisfy_pointer_oracle_at_supported_scales() {+ for (width, height, logical_width, logical_height) in [+ (400, 300, 400.0, 300.0),+ (800, 600, 400.0, 300.0),+ (500, 525, 400.0, 300.0),+ ] {+ let (baseline, mut badge_only, regions) =+ oracle_images(width, height, logical_width, logical_height);+ assert!(regions.pointer.y1 < regions.badge_left.y0);+ paint_badge(&mut badge_only, regions);++ let failure = std::panic::catch_unwind(|| {+ assert_cursor_and_badge_pixels_changed(+ &baseline,+ &badge_only,+ CURSOR_X,+ CURSOR_Y,+ logical_width,+ logical_height,+ );+ });+ assert!(failure.is_err(), "badge-only overlay unexpectedly passed");+ }+ }++ fn assert_colocated_overlay(+ width: u32,+ height: u32,+ logical_width: f64,+ logical_height: f64,+ expected_anchor: (i64, i64),+ ) {+ let (baseline, mut overlay, regions) =+ oracle_images(width, height, logical_width, logical_height);+ assert_eq!(regions.anchor, expected_anchor);+ assert!(regions.pointer.y1 < regions.badge_left.y0);+ paint_pointer(&mut overlay, regions);+ paint_badge(&mut overlay, regions);assert_cursor_and_badge_pixels_changed(&baseline,&overlay,CURSOR_X,CURSOR_Y,- f64::from(WIDTH),- f64::from(HEIGHT),+ logical_width,+ logical_height,);}- #[test]- #[should_panic(expected = "badge region changed 0 pixels")]- fn rejects_pointer_without_badge() {- let baseline = RgbaImage::new(WIDTH, HEIGHT);- let mut pointer_only = baseline.clone();- paint_changed_rect(&mut pointer_only, 196, 146, 200, 150);-- assert_cursor_and_badge_pixels_changed(- &baseline,- &pointer_only,+ fn oracle_images(+ width: u32,+ height: u32,+ logical_width: f64,+ logical_height: f64,+ ) -> (RgbaImage, RgbaImage, CursorOracleRegions) {+ let baseline = RgbaImage::new(width, height);+ let overlay = baseline.clone();+ let regions = cursor_oracle_regions(+ width,+ height,CURSOR_X,CURSOR_Y,- f64::from(WIDTH),- f64::from(HEIGHT),+ logical_width,+ logical_height,);+ (baseline, overlay, regions)+ }++ fn paint_pointer(image: &mut RgbaImage, regions: CursorOracleRegions) {+ paint_changed_rect_i64(image, regions.anchor.0 - 2, regions.anchor.1 - 2, 4, 4);+ }++ fn paint_badge(image: &mut RgbaImage, regions: CursorOracleRegions) {+ paint_changed_rect_i64(+ image,+ regions.badge_left.x0 + 2,+ regions.badge_left.y0 + 2,+ 6,+ 4,+ );+ }++ fn paint_changed_rect_i64(image: &mut RgbaImage, x: i64, y: i64, width: u32, height: u32) {+ let x = u32::try_from(x).expect("test rectangle x");+ let y = u32::try_from(y).expect("test rectangle y");+ paint_changed_rect(image, x, y, x + width, y + height);}fn paint_changed_rect(image: &mut RgbaImage, x0: u32, y0: u32, x1: u32, y1: u32) {diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/authorized_live_jev_use_demo_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/authorized_live_jev_use_demo_test.rsnew file mode 100644index 0000000000..810a8b4510--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver/tests/authorized_live_jev_use_demo_test.rs@@ -0,0 +1,2008 @@+//! Artifact-gated perception demo for a custom-painted surface.+//!+//! The provider-neutral chooser sees bounded observation regions and action+//! descriptions, never Driver tool arguments, environment variables, or+//! credentials. The host validates one selected ID and resolves it to the+//! capture-bound action.++use serde::{Deserialize, Serialize};+use serde_json::{json, Value};+use std::collections::{BTreeMap, BTreeSet};+use std::path::PathBuf;++const MAX_REGIONS: usize = 64;+const MAX_SAFE_ID_BYTES: usize = 96;+const MAX_CHOOSER_ID_BYTES: usize = 64;+const MAX_CANDIDATE_DESCRIPTION_BYTES: usize = 256;+const MIN_CONFIDENCE: f64 = 0.80;+const CHOOSER_GOAL: &str = "Choose exactly one candidate by applying its condition to the supplied state. The host alone authorizes any selected action.";+const REOBSERVE_DESCRIPTION: &str = "Select only when no action candidate condition matches and no regions are supplied. Do not act; request one fresh bounded observation.";+const ABSTAIN_DESCRIPTION: &str = "Select only when no action candidate condition matches and one or more regions are supplied. Do not act; stop.";++#[derive(Clone, Debug, PartialEq)]+struct ClickAction {+ capture_id: String,+ x: f64,+ y: f64,+}++#[derive(Clone, Debug, PartialEq)]+struct Candidate {+ id: String,+ description: String,+ region_id: Option<String>,+ action: Option<ClickAction>,+}++#[derive(Clone, Debug, Serialize)]+#[serde(deny_unknown_fields)]+struct RegionBounds {+ x: u64,+ y: u64,+ width: u64,+ height: u64,+}++#[derive(Clone, Debug, Serialize)]+#[serde(deny_unknown_fields)]+struct CompactRegion {+ id: String,+ kind: String,+ bounds: RegionBounds,+ #[serde(skip_serializing_if = "Option::is_none")]+ text: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ label: Option<String>,+ confidence: f64,+ interactive: bool,+}++#[derive(Clone, Debug, Serialize)]+#[serde(deny_unknown_fields)]+struct CandidateDescription {+ id: String,+ description: String,+}++#[derive(Clone, Debug, Serialize)]+#[serde(deny_unknown_fields)]+struct HistoryEntry {+ selected_id: String,+ outcome: String,+}++#[derive(Clone, Debug, Serialize)]+#[serde(deny_unknown_fields)]+struct ChoiceRequest {+ schema: &'static str,+ goal: &'static str,+ capture_id: String,+ regions: Vec<CompactRegion>,+ history: Vec<HistoryEntry>,+ candidates: Vec<CandidateDescription>,+}++#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]+#[serde(deny_unknown_fields)]+struct ChoiceResponse {+ schema: String,+ selected_id: String,+ model: Option<String>,+ confidence: f64,+ probabilities: BTreeMap<String, f64>,+}++#[derive(Clone, Debug, PartialEq)]+enum ChoiceConfig {+ Mock,+ Live { program: PathBuf, script: PathBuf },+}++fn safe_id(value: &str) -> bool {+ !value.is_empty()+ && value.len() <= MAX_SAFE_ID_BYTES+ && value+ .bytes()+ .all(|byte| byte.is_ascii_alphanumeric() || b"._:-/".contains(&byte))+}++fn safe_region_id(value: &str) -> bool {+ safe_chooser_id(value) && value.len() <= MAX_CHOOSER_ID_BYTES - "region:".len()+}++fn safe_chooser_id(value: &str) -> bool {+ !value.is_empty()+ && value.len() <= MAX_CHOOSER_ID_BYTES+ && value.bytes().enumerate().all(|(index, byte)| {+ byte.is_ascii_alphanumeric() || (index > 0 && b"._:-".contains(&byte))+ })+}++fn safe_text(value: &str, maximum: usize) -> bool {+ !value.trim().is_empty() && value.len() <= maximum && !value.chars().any(char::is_control)+}++fn send_action_description(region_id: &str, kind: &str, text: &str, confidence: f64) -> String {+ format!(+ "Select only if exactly one supplied region has id={region_id}, kind={kind}, exact_text={text:?}, confidence={confidence}, and it is the sole exact Send match at or above {MIN_CONFIDENCE:.2}."+ )+}++fn bounded_candidates(+ payload: &Value,+ capture_id: &str,+) -> Result<(Vec<Candidate>, Vec<CompactRegion>), String> {+ if !safe_id(capture_id)+ || payload["schema"] != "cua.visual_regions_v1"+ || payload["capture"]["capture_id"].as_str() != Some(capture_id)+ {+ return Err("visual result has invalid schema or capture provenance".into());+ }+ let screenshot = &payload["capture"]["screenshot"];+ let screen_width = screenshot["width"]+ .as_u64()+ .filter(|value| *value > 0)+ .ok_or("invalid screenshot width")?;+ let screen_height = screenshot["height"]+ .as_u64()+ .filter(|value| *value > 0)+ .ok_or("invalid screenshot height")?;+ let regions = payload["regions"]+ .as_array()+ .ok_or("visual result omitted regions")?;+ if regions.len() > MAX_REGIONS {+ return Err("visual result exceeded the region bound".into());+ }++ let mut region_ids = BTreeSet::new();+ let mut send_candidate = None;+ let mut ambiguous_send = false;+ let mut compact = Vec::with_capacity(regions.len());+ for region in regions {+ let id = region["id"]+ .as_str()+ .filter(|value| safe_region_id(value))+ .ok_or("region has an unsafe ID")?;+ if !region_ids.insert(id) {+ return Err("duplicate region ID".into());+ }+ let kind = region["kind"]+ .as_str()+ .filter(|kind| matches!(*kind, "text" | "icon"))+ .ok_or("invalid region kind")?;+ let confidence = region["confidence"]+ .as_f64()+ .filter(|value| value.is_finite() && (0.0..=1.0).contains(value))+ .ok_or("invalid confidence")?;+ let interactive = region["interactive"]+ .as_bool()+ .ok_or("invalid interactivity")?;+ let text = region.get("text").and_then(Value::as_str).map(str::trim);+ let label = region.get("label").and_then(Value::as_str).map(str::trim);+ if text.is_some_and(|value| !safe_text(value, 128))+ || label.is_some_and(|value| !safe_text(value, 128))+ || (kind == "text" && text.is_none())+ || (kind == "icon" && label.is_none())+ {+ return Err("region content is unsafe or missing for its kind".into());+ }++ let bounds = ®ion["bounds"];+ let x = bounds["x"].as_u64().ok_or("invalid x")?;+ let y = bounds["y"].as_u64().ok_or("invalid y")?;+ let width = bounds["width"]+ .as_u64()+ .filter(|value| *value > 0)+ .ok_or("invalid width")?;+ let height = bounds["height"]+ .as_u64()+ .filter(|value| *value > 0)+ .ok_or("invalid height")?;+ if x.checked_add(width)+ .is_none_or(|value| value > screen_width)+ || y.checked_add(height)+ .is_none_or(|value| value > screen_height)+ {+ return Err("region lies outside its source screenshot".into());+ }+ compact.push(CompactRegion {+ id: id.into(),+ kind: kind.into(),+ bounds: RegionBounds {+ x,+ y,+ width,+ height,+ },+ text: text.map(str::to_owned),+ label: label.map(str::to_owned),+ confidence,+ interactive,+ });+ if kind == "text" && confidence >= MIN_CONFIDENCE && text == Some("Send") {+ if send_candidate.is_some() {+ ambiguous_send = true;+ continue;+ }+ send_candidate = Some(Candidate {+ id: format!("region:{id}"),+ description: send_action_description(id, kind, "Send", confidence),+ region_id: Some(id.into()),+ action: Some(ClickAction {+ capture_id: capture_id.into(),+ x: x as f64 + width as f64 / 2.0,+ y: y as f64 + height as f64 / 2.0,+ }),+ });+ }+ }+ let mut candidates = if ambiguous_send {+ Vec::new()+ } else {+ send_candidate.into_iter().collect()+ };+ candidates.extend([+ Candidate {+ id: "reobserve".into(),+ description: REOBSERVE_DESCRIPTION.into(),+ region_id: None,+ action: None,+ },+ Candidate {+ id: "abstain".into(),+ description: ABSTAIN_DESCRIPTION.into(),+ region_id: None,+ action: None,+ },+ ]);+ if candidates+ .iter()+ .any(|candidate| !safe_text(&candidate.description, MAX_CANDIDATE_DESCRIPTION_BYTES))+ {+ return Err("candidate description is empty, unsafe, or exceeds 256 bytes".into());+ }+ Ok((candidates, compact))+}++fn require_unique_actionable_send(+ candidates: &[Candidate],+ region_count: usize,+) -> Result<(), String> {+ let actionable_count = candidates+ .iter()+ .filter(|candidate| candidate.action.is_some())+ .count();+ let exact_send_count = candidates+ .iter()+ .filter(|candidate| candidate.action.is_some() && candidate.region_id.is_some())+ .count();+ if actionable_count != 1 || exact_send_count != 1 {+ return Err(format!(+ "expected exactly one actionable Send candidate; region_count={region_count}, candidate_count={}, actionable_count={actionable_count}, exact_send_count={exact_send_count}",+ candidates.len()+ ));+ }+ Ok(())+}++fn choice_request(+ capture_id: &str,+ regions: &[CompactRegion],+ candidates: &[Candidate],+) -> Result<ChoiceRequest, String> {+ if candidates+ .iter()+ .any(|candidate| !safe_text(&candidate.description, MAX_CANDIDATE_DESCRIPTION_BYTES))+ {+ return Err("candidate description is empty, unsafe, or exceeds 256 bytes".into());+ }+ let action_region_ids = candidates+ .iter()+ .filter(|candidate| candidate.action.is_some())+ .filter_map(|candidate| candidate.region_id.as_deref())+ .collect::<BTreeSet<_>>();+ Ok(ChoiceRequest {+ schema: "cua.jev_choice_request_v1",+ goal: CHOOSER_GOAL,+ capture_id: capture_id.into(),+ regions: regions+ .iter()+ .filter(|region| action_region_ids.contains(region.id.as_str()))+ .cloned()+ .collect(),+ history: Vec::new(),+ candidates: candidates+ .iter()+ .map(|candidate| CandidateDescription {+ id: candidate.id.clone(),+ description: candidate.description.clone(),+ })+ .collect(),+ })+}++fn choice_failure_diagnostic(response: &ChoiceResponse, candidates: &[Candidate]) -> String {+ let candidate_ids = candidates+ .iter()+ .map(|candidate| candidate.id.as_str())+ .collect::<BTreeSet<_>>();+ let probabilities = response+ .probabilities+ .iter()+ .filter(|(id, probability)| {+ candidate_ids.contains(id.as_str())+ && probability.is_finite()+ && (0.0..=1.0).contains(*probability)+ })+ .take(MAX_REGIONS + 2)+ .map(|(id, probability)| (id.clone(), *probability))+ .collect::<BTreeMap<_, _>>();+ json!({+ "selected_id": safe_chooser_id(&response.selected_id)+ .then_some(response.selected_id.as_str()),+ "model": response.model.as_deref().filter(|value| safe_id(value)),+ "confidence": (response.confidence.is_finite()+ && (0.0..=1.0).contains(&response.confidence))+ .then_some(response.confidence),+ "probabilities": probabilities,+ })+ .to_string()+}++fn validate_choice(+ response: ChoiceResponse,+ candidates: &[Candidate],+) -> Result<(ChoiceResponse, Candidate), String> {+ if response.schema != "cua.jev_choice_v1"+ || !safe_chooser_id(&response.selected_id)+ || response+ .model+ .as_deref()+ .is_some_and(|value| !safe_id(value))+ || !response.confidence.is_finite()+ || !(0.0..=1.0).contains(&response.confidence)+ {+ return Err("chooser returned invalid metadata".into());+ }+ let ids = candidates+ .iter()+ .map(|candidate| candidate.id.as_str())+ .collect::<BTreeSet<_>>();+ for (id, probability) in &response.probabilities {+ if !ids.contains(id.as_str())+ || !probability.is_finite()+ || !(0.0..=1.0).contains(probability)+ {+ return Err("chooser returned an unknown or invalid probability".into());+ }+ }+ let candidate = candidates+ .iter()+ .find(|candidate| candidate.id == response.selected_id)+ .cloned()+ .ok_or("chooser selected an ID that was not supplied")?;+ Ok((response, candidate))+}++fn mock_choice(candidates: &[Candidate]) -> ChoiceResponse {+ let selected_id = candidates+ .iter()+ .find(|candidate| candidate.action.is_some() && candidate.region_id.is_some())+ .expect("fixture must expose a Send candidate")+ .id+ .clone();+ let probabilities = candidates+ .iter()+ .map(|candidate| {+ (+ candidate.id.clone(),+ if candidate.id == selected_id {+ 1.0+ } else {+ 0.0+ },+ )+ })+ .collect();+ ChoiceResponse {+ schema: "cua.jev_choice_v1".into(),+ selected_id,+ model: Some("mock".into()),+ confidence: 1.0,+ probabilities,+ }+}++fn choice_config_from(+ live: Option<&str>,+ mock: Option<&str>,+ program: Option<&str>,+ script: Option<&str>,+) -> Result<ChoiceConfig, String> {+ if live.is_some_and(|value| value != "1") || mock.is_some_and(|value| value != "1") {+ return Err("chooser mode flags, when present, must equal 1".into());+ }+ if live == Some("1") {+ if mock.is_some() {+ return Err("CUA_JEV_LIVE forbids CUA_JEV_MOCK_DEMO".into());+ }+ let program = PathBuf::from(program.ok_or("CUA_JEV_CHOOSER_PROGRAM is required")?);+ let script = PathBuf::from(script.ok_or("CUA_JEV_CHOOSER_SCRIPT is required")?);+ if !program.is_absolute() || !script.is_absolute() {+ return Err("reviewed chooser program and script paths must be absolute".into());+ }+ if !program.is_file() || !script.is_file() {+ return Err("reviewed chooser program and script must be regular files".into());+ }+ return Ok(ChoiceConfig::Live { program, script });+ }+ if mock == Some("1") {+ if program.is_some() || script.is_some() {+ return Err("mock mode forbids external chooser paths".into());+ }+ return Ok(ChoiceConfig::Mock);+ }+ Err("set CUA_JEV_MOCK_DEMO=1 or CUA_JEV_LIVE=1 with a reviewed chooser".into())+}++#[test]+fn chooser_request_matches_fixture_contract_and_contains_no_action_arguments() {+ let mut payload = json!({+ "schema": "cua.visual_regions_v1",+ "capture": {"capture_id": "capture-1", "screenshot": {"width": 760, "height": 460}},+ "regions": [+ {"id": "save", "kind": "icon", "bounds": {"x": 72, "y": 250, "width": 204, "height": 40}, "label": "Save", "confidence": 0.99, "interactive": false},+ {"id": "send", "kind": "text", "bounds": {"x": 292, "y": 250, "width": 204, "height": 40}, "text": "Send", "confidence": 0.98, "interactive": false}+ ]+ });+ let (candidates, regions) = bounded_candidates(&payload, "capture-1").unwrap();+ assert_eq!(regions.len(), 2, "host must retain the full parsed set");+ let request =+ serde_json::to_value(choice_request("capture-1", ®ions, &candidates).unwrap()).unwrap();+ assert_eq!(request["schema"], "cua.jev_choice_request_v1");+ assert_eq!(request["goal"], CHOOSER_GOAL);+ assert_eq!(+ request+ .as_object()+ .unwrap()+ .keys()+ .map(String::as_str)+ .collect::<BTreeSet<_>>(),+ BTreeSet::from([+ "candidates",+ "capture_id",+ "goal",+ "history",+ "regions",+ "schema",+ ])+ );+ assert_eq!(request["candidates"].as_array().unwrap().len(), 3);+ for candidate in request["candidates"].as_array().unwrap() {+ assert!(+ candidate["description"].as_str().unwrap().len() <= MAX_CANDIDATE_DESCRIPTION_BYTES+ );+ }+ assert_eq!(+ request["candidates"][1]["description"],+ REOBSERVE_DESCRIPTION+ );+ assert_eq!(request["candidates"][2]["description"], ABSTAIN_DESCRIPTION);+ assert_eq!(+ request["regions"][0]+ .as_object()+ .unwrap()+ .keys()+ .map(String::as_str)+ .collect::<BTreeSet<_>>(),+ BTreeSet::from(["bounds", "confidence", "id", "interactive", "kind", "text",])+ );+ assert_eq!(+ request["regions"][0]["bounds"],+ json!({"x": 292, "y": 250, "width": 204, "height": 40})+ );+ assert_eq!(request["regions"].as_array().unwrap().len(), 1);+ assert_eq!(request["regions"][0]["id"], "send");+ assert!(request["regions"][0].get("content").is_none());+ assert!(request["regions"][0].get("label").is_none());+ assert_eq!(+ request["candidates"][0]+ .as_object()+ .unwrap()+ .keys()+ .map(String::as_str)+ .collect::<BTreeSet<_>>(),+ BTreeSet::from(["description", "id"])+ );+ assert!(request.to_string().contains("reobserve"));+ assert!(request.to_string().contains("abstain"));+ assert_eq!(request["candidates"][0]["id"], "region:send");+ assert_eq!(+ request["candidates"][0]["description"],+ send_action_description("send", "text", "Send", 0.98)+ );+ let mut sensitive_candidates = candidates.clone();+ let sensitive_action = sensitive_candidates[0].action.as_mut().unwrap();+ sensitive_action.capture_id = "sensitive-action-capture".into();+ sensitive_action.x = 12345.0;+ sensitive_action.y = 67890.0;+ let sensitive_request = serde_json::to_string(+ &choice_request("capture-1", ®ions, &sensitive_candidates).unwrap(),+ )+ .unwrap();+ for forbidden in [+ "tool",+ "arguments",+ "delivery_mode",+ "secret",+ "screenshot",+ "sensitive-action-capture",+ "12345",+ "67890",+ ] {+ assert!(!sensitive_request.contains(forbidden), "leaked {forbidden}");+ }++ let (response, selected) = validate_choice(mock_choice(&candidates), &candidates).unwrap();+ assert_eq!(response.selected_id, "region:send");+ assert_eq!(selected.action.unwrap().capture_id, "capture-1");++ let oversized_capture_id = "a".repeat(MAX_SAFE_ID_BYTES + 1);+ payload["capture"]["capture_id"] = json!(oversized_capture_id);+ assert!(bounded_candidates(&payload, &oversized_capture_id).is_err());++ let mut oversized_description_candidates = candidates;+ oversized_description_candidates[0].description =+ "a".repeat(MAX_CANDIDATE_DESCRIPTION_BYTES + 1);+ assert!(+ choice_request("capture-1", ®ions, &oversized_description_candidates)+ .unwrap_err()+ .contains("exceeds 256 bytes")+ );+}++#[test]+fn chooser_failure_diagnostic_is_bounded_and_excludes_action_context() {+ let candidates = vec![+ Candidate {+ id: "region:send".into(),+ description: send_action_description("send", "text", "Send", 0.98),+ region_id: Some("send".into()),+ action: Some(ClickAction {+ capture_id: "private-capture-id".into(),+ x: 12345.0,+ y: 67890.0,+ }),+ },+ Candidate {+ id: "reobserve".into(),+ description: "Reobserve.".into(),+ region_id: None,+ action: None,+ },+ Candidate {+ id: "abstain".into(),+ description: "Abstain.".into(),+ region_id: None,+ action: None,+ },+ ];+ let response = ChoiceResponse {+ schema: "cua.jev_choice_v1".into(),+ selected_id: "invented".into(),+ model: Some("jev-model".into()),+ confidence: 0.25,+ probabilities: BTreeMap::from([("region:send".into(), 0.25), ("invented".into(), 0.75)]),+ };++ let diagnostic = choice_failure_diagnostic(&response, &candidates);+ let diagnostic_json: Value = serde_json::from_str(&diagnostic).unwrap();+ assert_eq!(+ diagnostic_json+ .as_object()+ .unwrap()+ .keys()+ .map(String::as_str)+ .collect::<BTreeSet<_>>(),+ BTreeSet::from(["confidence", "model", "probabilities", "selected_id"])+ );+ assert_eq!(diagnostic_json["selected_id"], "invented");+ assert_eq!(diagnostic_json["model"], "jev-model");+ assert_eq!(diagnostic_json["confidence"], 0.25);+ assert_eq!(+ diagnostic_json["probabilities"],+ json!({"region:send": 0.25})+ );+ for forbidden in [+ "private-capture-id",+ "12345",+ "67890",+ "description",+ "regions",+ "coordinates",+ ] {+ assert!(!diagnostic.contains(forbidden), "leaked {forbidden}");+ }+}++#[test]+fn chooser_response_and_live_mode_fail_closed() {+ let candidates = vec![+ Candidate {+ id: "region:send".into(),+ description: send_action_description("send", "text", "Send", 0.98),+ region_id: Some("send".into()),+ action: Some(ClickAction {+ capture_id: "capture-1".into(),+ x: 1.0,+ y: 2.0,+ }),+ },+ Candidate {+ id: "reobserve".into(),+ description: "Reobserve.".into(),+ region_id: None,+ action: None,+ },+ Candidate {+ id: "abstain".into(),+ description: "Abstain.".into(),+ region_id: None,+ action: None,+ },+ ];+ let mut response = mock_choice(&candidates);+ response.selected_id = "invented".into();+ assert!(validate_choice(response, &candidates).is_err());+ let mut response = mock_choice(&candidates);+ response.probabilities.insert("invented".into(), 0.1);+ assert!(validate_choice(response, &candidates).is_err());+ let mut response = mock_choice(&candidates);+ response.model = None;+ response.probabilities = BTreeMap::from([("region:send".into(), 0.4)]);+ assert!(validate_choice(response, &candidates).is_ok());+ assert!(choice_config_from(Some("1"), Some("1"), None, None)+ .unwrap_err()+ .contains("forbids"));+ assert!(choice_config_from(None, None, None, None).is_err());++ let oversized_region_id = "a".repeat(MAX_CHOOSER_ID_BYTES - "region:".len() + 1);+ let payload = json!({+ "schema": "cua.visual_regions_v1",+ "capture": {"capture_id": "capture-1", "screenshot": {"width": 10, "height": 10}},+ "regions": [{+ "id": oversized_region_id,+ "kind": "text",+ "bounds": {"x": 0, "y": 0, "width": 10, "height": 10},+ "text": "Send",+ "confidence": 1.0,+ "interactive": false+ }]+ });+ assert!(bounded_candidates(&payload, "capture-1")+ .unwrap_err()+ .contains("unsafe ID"));+}++#[test]+fn candidate_policy_refuses_ambiguous_and_non_send_regions() {+ let missing_interactivity = json!({+ "schema": "cua.visual_regions_v1",+ "capture": {"capture_id": "capture-1", "screenshot": {"width": 100, "height": 100}},+ "regions": [+ {"id": "send", "kind": "text", "bounds": {"x": 0, "y": 0, "width": 40, "height": 20}, "text": "Send", "confidence": 0.99}+ ]+ });+ assert!(bounded_candidates(&missing_interactivity, "capture-1")+ .unwrap_err()+ .contains("invalid interactivity"));++ let payload = json!({+ "schema": "cua.visual_regions_v1",+ "capture": {"capture_id": "capture-1", "screenshot": {"width": 100, "height": 100}},+ "regions": [+ {"id": "send-1", "kind": "text", "bounds": {"x": 0, "y": 0, "width": 40, "height": 20}, "text": "Send", "confidence": 0.99, "interactive": false},+ {"id": "send-2", "kind": "text", "bounds": {"x": 50, "y": 0, "width": 40, "height": 20}, "text": " Send ", "confidence": 0.98, "interactive": false}+ ]+ });+ let (candidates, regions) = bounded_candidates(&payload, "capture-1").unwrap();+ assert_eq!(regions.len(), 2, "ambiguity check must use the full set");+ assert_eq!(+ candidates+ .iter()+ .map(|candidate| candidate.id.as_str())+ .collect::<Vec<_>>(),+ ["reobserve", "abstain"]+ );+ assert!(require_unique_actionable_send(&candidates, regions.len()).is_err());+ assert!(choice_request("capture-1", ®ions, &candidates)+ .unwrap()+ .regions+ .is_empty());++ let payload = json!({+ "schema": "cua.visual_regions_v1",+ "capture": {"capture_id": "capture-1", "screenshot": {"width": 100, "height": 100}},+ "regions": [+ {"id": "save", "kind": "text", "bounds": {"x": 0, "y": 0, "width": 40, "height": 20}, "text": "Save", "confidence": 0.99, "interactive": true},+ {"id": "send-low-confidence", "kind": "text", "bounds": {"x": 50, "y": 0, "width": 40, "height": 20}, "text": "Send", "confidence": 0.79, "interactive": false}+ ]+ });+ let (candidates, _) = bounded_candidates(&payload, "capture-1").unwrap();+ assert_eq!(+ candidates+ .iter()+ .map(|candidate| candidate.id.as_str())+ .collect::<Vec<_>>(),+ ["reobserve", "abstain"]+ );+}++#[test]+fn cancel_counterfactual_is_not_actionable_and_abstain_fails_closed() {+ let payload = json!({+ "schema": "cua.visual_regions_v1",+ "capture": {"capture_id": "capture-1", "screenshot": {"width": 100, "height": 100}},+ "regions": [+ {"id": "cancel", "kind": "text", "bounds": {"x": 0, "y": 0, "width": 40, "height": 20}, "text": "Cancel", "confidence": 0.99, "interactive": true},+ {"id": "send", "kind": "text", "bounds": {"x": 50, "y": 0, "width": 40, "height": 20}, "text": "Send", "confidence": 0.98, "interactive": false}+ ]+ });+ let (candidates, regions) = bounded_candidates(&payload, "capture-1").unwrap();+ assert_eq!(+ candidates+ .iter()+ .filter_map(|candidate| candidate.region_id.as_deref())+ .collect::<Vec<_>>(),+ ["send"]+ );+ assert_eq!(+ choice_request("capture-1", ®ions, &candidates)+ .unwrap()+ .regions+ .iter()+ .map(|region| region.id.as_str())+ .collect::<Vec<_>>(),+ ["send"]+ );+ let cancel_response = ChoiceResponse {+ schema: "cua.jev_choice_v1".into(),+ selected_id: "region:cancel".into(),+ model: Some("mock".into()),+ confidence: 1.0,+ probabilities: BTreeMap::new(),+ };+ assert!(validate_choice(cancel_response, &candidates).is_err());++ let mut abstain_response = mock_choice(&candidates);+ abstain_response.selected_id = "abstain".into();+ let (_, abstain) = validate_choice(abstain_response, &candidates).unwrap();+ assert!(+ abstain.action.is_none(),+ "abstain must never resolve to an action"+ );+}++#[test]+fn actionable_send_requirement_reports_only_bounded_counts() {+ let fallback_candidates = vec![+ Candidate {+ id: "reobserve".into(),+ description: "Reobserve.".into(),+ region_id: None,+ action: None,+ },+ Candidate {+ id: "abstain".into(),+ description: "Abstain.".into(),+ region_id: None,+ action: None,+ },+ ];+ assert_eq!(+ require_unique_actionable_send(&fallback_candidates, 7).unwrap_err(),+ "expected exactly one actionable Send candidate; region_count=7, candidate_count=2, actionable_count=0, exact_send_count=0"+ );++ let mut candidates = fallback_candidates;+ candidates.push(Candidate {+ id: "region:send".into(),+ description: send_action_description("send", "text", "Send", 0.98),+ region_id: Some("send".into()),+ action: Some(ClickAction {+ capture_id: "capture-1".into(),+ x: 50.0,+ y: 25.0,+ }),+ });+ assert!(require_unique_actionable_send(&candidates, 7).is_ok());+}++#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]+mod e2e {+ use super::*;+ use cua_driver_testkit::{driver_binary, spawn_in_job, Driver, FixtureJournal, McpDriver};+ use sha2::{Digest, Sha256};+ use std::fs;+ use std::io::{Read, Write};+ use std::path::Path;+ use std::process::{Command, Stdio};+ use std::thread;+ use std::time::{Duration, Instant};++ const FIXTURE_TITLE_PREFIX: &str = "Cua Visual-Only Canvas Fixture";+ const FIXTURE_TEST_TITLE: &str = "Cua Visual-Only Canvas Fixture [test-session:window]";+ const FIXTURE_DISCOVERY_ATTEMPTS: usize = 3;+ const CHOOSER_TIMEOUT: Duration = Duration::from_secs(30);+ const MAX_CHOOSER_OUTPUT: u64 = 64 * 1024;+ const PAINTED_LABELS: [&str; 4] = ["Save", "Send", "Cancel", "CHOOSE A SIGNAL"];++ #[derive(Clone, Copy)]+ enum DemoScope {+ Window,+ PrimaryDesktop,+ }++ impl DemoScope {+ fn slug(self) -> &'static str {+ match self {+ Self::Window => "window",+ Self::PrimaryDesktop => "primary-desktop",+ }+ }++ fn capture_scope(self) -> &'static str {+ match self {+ Self::Window => "window",+ Self::PrimaryDesktop => "desktop",+ }+ }++ fn capture_kind(self) -> &'static str {+ match self {+ Self::Window => "get_window_state",+ Self::PrimaryDesktop => "get_desktop_state",+ }+ }++ fn delivery_mode(self) -> &'static str {+ match self {+ Self::Window => "background",+ // Primary-desktop input is screen-absolute and therefore foreground-only.+ Self::PrimaryDesktop => "foreground",+ }+ }+ }++ struct Gate {+ source_sha: String,+ jev_source_sha: String,+ session_label: String,+ os_name: String,+ os_version: String,+ os_arch: String,+ desktop_session: String,+ runner_identity_class: String,+ model: PathBuf,+ candidate_measurements: PathBuf,+ extension_home: PathBuf,+ evidence_dir: PathBuf,+ choice: ChoiceConfig,+ }++ fn required(name: &str) -> String {+ std::env::var(name)+ .unwrap_or_else(|_| panic!("{name} is required for the artifact-gated demo"))+ }++ fn required_sha40(name: &str) -> String {+ let value = required(name);+ assert!(+ value.len() == 40+ && value+ .bytes()+ .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()),+ "{name} must be 40 lowercase hexadecimal characters"+ );+ value+ }++ fn measured_sha256(value: &Value, field: &str) -> String {+ let value = value[field]+ .as_str()+ .unwrap_or_else(|| panic!("candidate measurements omitted {field}"));+ assert!(+ value.len() == 64+ && value+ .bytes()+ .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase()),+ "candidate measurements contain invalid {field}"+ );+ value.to_owned()+ }++ fn hash_file(path: &Path) -> String {+ let mut file =+ fs::File::open(path).unwrap_or_else(|error| panic!("open {}: {error}", path.display()));+ let mut hasher = Sha256::new();+ let mut buffer = [0_u8; 64 * 1024];+ loop {+ let read = file.read(&mut buffer).expect("hash evidence file");+ if read == 0 {+ break;+ }+ hasher.update(&buffer[..read]);+ }+ format!("{:x}", hasher.finalize())+ }++ fn hash_bytes(bytes: &[u8]) -> String {+ format!("{:x}", Sha256::digest(bytes))+ }++ fn recording_metadata(path: &Path) -> Value {+ let output = Command::new("ffprobe")+ .args([+ "-v",+ "error",+ "-select_streams",+ "v:0",+ "-show_entries",+ "stream=width,height,avg_frame_rate:format=duration",+ "-of",+ "json",+ ])+ .arg(path)+ .output()+ .expect("run ffprobe for recording evidence");+ assert!(+ output.status.success(),+ "ffprobe rejected recording evidence"+ );+ let probe: Value = serde_json::from_slice(&output.stdout).expect("parse ffprobe JSON");+ let streams = probe["streams"].as_array().expect("ffprobe video streams");+ assert_eq!(streams.len(), 1, "recording must contain one video stream");+ let width = streams[0]["width"].as_u64().expect("recording width");+ let height = streams[0]["height"].as_u64().expect("recording height");+ let rate = streams[0]["avg_frame_rate"]+ .as_str()+ .expect("recording frame rate");+ let (numerator, denominator) = rate.split_once('/').expect("rational frame rate");+ let numerator: u64 = numerator.parse().expect("frame-rate numerator");+ let denominator: u64 = denominator.parse().expect("frame-rate denominator");+ let duration_ms = (probe["format"]["duration"]+ .as_str()+ .expect("recording duration")+ .parse::<f64>()+ .expect("numeric recording duration")+ * 1000.0)+ .round() as u64;+ assert!(width > 0 && height > 0 && numerator > 0 && denominator > 0 && duration_ms > 0);+ json!({+ "width": width,+ "height": height,+ "frame_rate": {"numerator": numerator, "denominator": denominator},+ "duration_ms": duration_ms+ })+ }++ fn load_gate() -> Gate {+ let choice = choice_config_from(+ std::env::var("CUA_JEV_LIVE").ok().as_deref(),+ std::env::var("CUA_JEV_MOCK_DEMO").ok().as_deref(),+ std::env::var("CUA_JEV_CHOOSER_PROGRAM").ok().as_deref(),+ std::env::var("CUA_JEV_CHOOSER_SCRIPT").ok().as_deref(),+ )+ .unwrap_or_else(|error| panic!("invalid chooser configuration: {error}"));+ let gate = Gate {+ source_sha: required_sha40("CUA_E2E_SOURCE_SHA"),+ jev_source_sha: required_sha40("CUA_JEV_SOURCE_SHA"),+ session_label: required("CUA_SESSION_LABEL"),+ os_name: required("CUA_RUNNER_OS_NAME"),+ os_version: required("CUA_RUNNER_OS_VERSION"),+ os_arch: required("CUA_RUNNER_OS_ARCH"),+ desktop_session: required("CUA_DESKTOP_SESSION_TYPE"),+ runner_identity_class: required("CUA_RUNNER_IDENTITY_CLASS"),+ model: required("CUA_PERCEPTION_MODEL").into(),+ candidate_measurements: required("CUA_CANDIDATE_MEASUREMENTS").into(),+ extension_home: required("CUA_PERCEPTION_EXTENSION_HOME").into(),+ evidence_dir: required("CUA_PERCEPTION_EVIDENCE_DIR").into(),+ choice,+ };+ assert!(gate.model.is_file(), "model is not a regular file");+ assert!(safe_id(&gate.session_label), "session label is unsafe");+ for (label, value) in [+ ("OS name", &gate.os_name),+ ("OS version", &gate.os_version),+ ("OS architecture", &gate.os_arch),+ ("desktop session", &gate.desktop_session),+ ("runner identity class", &gate.runner_identity_class),+ ] {+ assert!(safe_id(value), "{label} is unsafe");+ }+ assert!(+ gate.candidate_measurements.is_file(),+ "candidate measurements are not a regular file"+ );+ assert!(+ gate.extension_home.is_dir(),+ "extension home is not a directory"+ );+ gate+ }++ fn installed_extension_status(gate: &Gate) -> Value {+ let output = Command::new(driver_binary())+ .args([+ "extension",+ "status",+ "cua-perception",+ "--self-test",+ "--json",+ ])+ .env("CUA_DRIVER_RS_HOME", &gate.extension_home)+ .output()+ .expect("measure installed extension state through Driver");+ assert!(+ output.status.success(),+ "Driver rejected installed extension state"+ );+ let status: Value =+ serde_json::from_slice(&output.stdout).expect("Driver extension status must be JSON");+ assert_eq!(status["id"], "cua-perception");+ assert_eq!(status["installed"], true);+ assert_eq!(status["healthy"], true);+ assert_eq!(status["trust"], "review-only-publisher-verified");+ assert!(status["active_version"].as_str().is_some_and(safe_id));+ assert!(status["publisher_id"].as_str().is_some_and(safe_id));+ assert!(status["publisher_key_id"].as_str().is_some_and(safe_id));+ assert!(status["catalog_version"]+ .as_u64()+ .is_some_and(|value| value > 0));+ status+ }++ fn fixture_path() -> PathBuf {+ Path::new(env!("CARGO_MANIFEST_DIR"))+ .join("../../../tests/fixtures/apps/cross-platform/visual-only-canvas/main.py")+ }++ fn fixture_title(session_label: &str, scope: DemoScope) -> String {+ format!("{FIXTURE_TITLE_PREFIX} [{session_label}:{}]", scope.slug())+ }++ fn fixture_command(journal_url: &str, title: &str, scope: DemoScope) -> Command {+ #[cfg(target_os = "windows")]+ let mut command = {+ let mut command = Command::new("py");+ command.arg("-3");+ command+ };+ #[cfg(any(target_os = "linux", target_os = "macos"))]+ let mut command = Command::new("python3");+ command+ .arg(fixture_path())+ .args(["--journal-url", journal_url, "--title", title])+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::inherit());+ if matches!(scope, DemoScope::PrimaryDesktop) {+ command.args(["--send-label-font-pixels", "48"]);+ }+ command+ }++ #[test]+ fn fixture_command_enlarges_only_the_primary_desktop_send_label() {+ let window_args =+ fixture_command("http://127.0.0.1:1234/state", "fixture", DemoScope::Window)+ .get_args()+ .map(|arg| arg.to_string_lossy().into_owned())+ .collect::<Vec<_>>();+ let desktop_args = fixture_command(+ "http://127.0.0.1:1234/state",+ "fixture",+ DemoScope::PrimaryDesktop,+ )+ .get_args()+ .map(|arg| arg.to_string_lossy().into_owned())+ .collect::<Vec<_>>();++ assert!(!window_args+ .iter()+ .any(|arg| arg == "--send-label-font-pixels"));+ assert_eq!(+ &desktop_args[desktop_args.len() - 2..],+ ["--send-label-font-pixels", "48"]+ );+ }++ fn wait_until(mut predicate: impl FnMut() -> bool, message: &str) {+ let deadline = Instant::now() + Duration::from_secs(10);+ while !predicate() {+ assert!(Instant::now() < deadline, "{message}");+ thread::sleep(Duration::from_millis(50));+ }+ }++ fn wait_for_send_transition(+ journal: &FixtureJournal,+ scope: DemoScope,+ window_id: u64,+ choice: &ClickAction,+ click: &cua_driver_testkit::ToolResponse,+ ) {+ let deadline = Instant::now() + Duration::from_secs(10);+ loop {+ let state = journal.snapshot();+ if state["selected"] == "send" && state["action_count"] == 1 {+ return;+ }+ assert!(+ Instant::now() < deadline,+ "journal did not record exactly one Send transition: {}",+ json!({+ "scope": scope.slug(),+ "fixture_window_id": window_id,+ "capture_bound_coordinates": {"x": choice.x, "y": choice.y},+ "click_action": {+ "route": click.action_route(),+ "delivery_mode": click.action_delivery_mode(),+ "effect": click.action_effect(),+ },+ "journal_snapshot": state,+ })+ );+ thread::sleep(Duration::from_millis(50));+ }+ }++ fn fixture_pid(state: &Value) -> Result<i64, String> {+ state["pid"]+ .as_i64()+ .filter(|pid| *pid > 0)+ .ok_or_else(|| format!("fixture journal reported an invalid pid: {}", state["pid"]))+ }++ fn fixture_window_id(window: &Value, pid: i64) -> Result<u64, String> {+ window["window_id"]+ .as_u64()+ .filter(|window_id| *window_id != 0)+ .ok_or_else(|| {+ format!("exact fixture window for pid {pid} has an invalid window_id: {window}")+ })+ }++ fn exact_fixture_window(+ windows: &Value,+ pid: i64,+ title: &str,+ ) -> Result<Option<(u64, String)>, String> {+ let windows = windows+ .as_array()+ .ok_or_else(|| "list_windows omitted its windows array".to_owned())?;+ let titled = windows+ .iter()+ .filter(|window| window["title"].as_str() == Some(title))+ .collect::<Vec<_>>();+ let owned = titled+ .iter()+ .copied()+ .filter(|window| window["pid"].as_i64() == Some(pid))+ .collect::<Vec<_>>();+ match owned.as_slice() {+ [] => match titled.as_slice() {+ [] => Ok(None),+ [window] if window["pid"].as_i64().is_some() => Err(format!(+ "exact fixture title belongs to pid {}, not expected pid {pid}",+ window["pid"]+ )),+ [window] if window.get("pid").is_none_or(Value::is_null) => Ok(None),+ [window] => Err(format!(+ "exact fixture window has invalid pid metadata: {window}"+ )),+ _ => Err(format!(+ "ambiguous fixture identity: {} exact-title windows lacked expected pid {pid}",+ titled.len()+ )),+ },+ [window] => Ok(Some((fixture_window_id(window, pid)?, title.to_owned()))),+ _ => Err(format!(+ "ambiguous fixture identity: {} exact-title windows claimed pid {pid}",+ owned.len()+ )),+ }+ }++ fn fixture_window_diagnostic(windows: &Value, pid: i64, title: &str) -> String {+ let Some(windows) = windows.as_array() else {+ return "structured response omitted the windows array".to_owned();+ };+ let titled = windows+ .iter()+ .filter(|window| window["title"].as_str() == Some(title))+ .map(|window| {+ format!(+ "window_id={} pid={}",+ window["window_id"]+ .as_u64()+ .map_or_else(|| "invalid".to_owned(), |value| value.to_string()),+ window["pid"]+ .as_i64()+ .map_or_else(|| "missing".to_owned(), |value| value.to_string())+ )+ })+ .collect::<Vec<_>>();+ if titled.is_empty() {+ format!(+ "no exact-title fixture among {} listed windows for expected pid {pid}",+ windows.len()+ )+ } else {+ format!(+ "exact-title candidates for expected pid {pid}: {}",+ titled.join(", ")+ )+ }+ }++ fn find_fixture_window(+ driver: &mut impl Driver,+ pid: i64,+ title: &str,+ ) -> Result<(u64, String), String> {+ for attempt in 1..=FIXTURE_DISCOVERY_ATTEMPTS {+ // Validate ownership locally so a backend-side PID filter cannot+ // hide whether the fixture was absent or merely lacked metadata.+ let response = driver.call("list_windows", json!({}));+ let diagnostic = if response.is_error() {+ format!("list_windows failed: {}", response.text())+ } else {+ let windows = &response.structured()["windows"];+ if let Some(window) = exact_fixture_window(windows, pid, title)? {+ return Ok(window);+ }+ fixture_window_diagnostic(windows, pid, title)+ };+ if attempt == FIXTURE_DISCOVERY_ATTEMPTS {+ return Err(format!(+ "fixture window discovery exhausted {attempt} attempts: {diagnostic}"+ ));+ }+ thread::sleep(Duration::from_millis(150));+ }+ unreachable!("fixture discovery attempt range is non-empty")+ }++ fn assert_painted_labels_absent_from_window_ax(observation: &cua_driver_testkit::ToolResponse) {+ for label in PAINTED_LABELS {+ assert!(+ !observation.tree_text().contains(label),+ "painted label leaked into window AX tree: {label}"+ );+ }+ }++ fn assert_painted_labels_are_visual_only(+ scope: DemoScope,+ observation: &cua_driver_testkit::ToolResponse,+ ) {+ match scope {+ DemoScope::Window => assert_painted_labels_absent_from_window_ax(observation),+ DemoScope::PrimaryDesktop => {+ assert!(+ observation.structured().get("tree_markdown").is_none()+ && observation.structured().get("elements").is_none(),+ "get_desktop_state unexpectedly exposed an accessibility tree: {}",+ observation.structured()+ );+ let response_text = observation+ .raw+ .pointer("/result/content")+ .and_then(Value::as_array)+ .into_iter()+ .flatten()+ .filter_map(|part| part.get("text").and_then(Value::as_str))+ .collect::<Vec<_>>()+ .join("\n");+ for label in PAINTED_LABELS {+ assert!(+ !response_text.contains(label),+ "painted label leaked into desktop response text: {label}"+ );+ }+ }+ }+ }++ fn external_choice(program: &Path, script: &Path, request: &ChoiceRequest) -> ChoiceResponse {+ let mut command = Command::new(program);+ command+ .arg(script)+ .env_clear()+ .env("TYPESAFE_API_KEY", required("TYPESAFE_API_KEY"))+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::null());+ #[cfg(target_os = "windows")]+ if let Some(system_root) = std::env::var_os("SYSTEMROOT") {+ command.env("SYSTEMROOT", system_root);+ }+ let mut child = spawn_in_job(&mut command).expect("start reviewed chooser directly");+ let payload = serde_json::to_vec(request).expect("serialize chooser request");+ let mut stdin = child.stdin.take().expect("chooser stdin");+ stdin.write_all(&payload).expect("write chooser request");+ drop(stdin);+ let stdout = child.stdout.take().expect("chooser stdout");+ let reader = thread::spawn(move || {+ let mut bytes = Vec::new();+ stdout+ .take(MAX_CHOOSER_OUTPUT + 1)+ .read_to_end(&mut bytes)+ .expect("read chooser response");+ bytes+ });+ let deadline = Instant::now() + CHOOSER_TIMEOUT;+ let status = loop {+ if let Some(status) = child.try_wait().expect("poll chooser") {+ break status;+ }+ if Instant::now() >= deadline {+ let _ = child.kill();+ let _ = child.wait();+ panic!("chooser exceeded its 30 second deadline");+ }+ thread::sleep(Duration::from_millis(25));+ };+ assert!(status.success(), "chooser exited unsuccessfully");+ let bytes = reader.join().expect("join chooser response reader");+ assert!(+ bytes.len() as u64 <= MAX_CHOOSER_OUTPUT,+ "chooser response exceeded 64 KiB"+ );+ serde_json::from_slice(&bytes).expect("chooser response must match the exact JSON contract")+ }++ fn choose(+ config: &ChoiceConfig,+ request: &ChoiceRequest,+ candidates: &[Candidate],+ ) -> (ChoiceResponse, Candidate) {+ let response = match config {+ ChoiceConfig::Mock => mock_choice(candidates),+ ChoiceConfig::Live { program, script } => external_choice(program, script, request),+ };+ let diagnostic = choice_failure_diagnostic(&response, candidates);+ validate_choice(response, candidates)+ .unwrap_or_else(|error| panic!("chooser response refused: {error}; {diagnostic}"))+ }++ fn run_authorized_visual_only_demo(scope: DemoScope) {+ let gate = load_gate();+ let measured = Command::new("git")+ .args(["rev-parse", "HEAD"])+ .current_dir(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../../.."))+ .output()+ .expect("measure checkout SHA");+ assert!(measured.status.success());+ assert_eq!(+ String::from_utf8(measured.stdout).unwrap().trim(),+ gate.source_sha+ );+ let extension_status = installed_extension_status(&gate);+ let candidate_measurements: Value = serde_json::from_slice(+ &fs::read(&gate.candidate_measurements).expect("read candidate measurements"),+ )+ .expect("candidate measurements must be JSON");+ assert_eq!(candidate_measurements["review_only"], true);+ assert_eq!(candidate_measurements["source_sha"], gate.source_sha);+ assert_eq!(+ candidate_measurements["review_driver_build_profile"],+ "debug-review-trust-root"+ );+ assert_eq!(candidate_measurements["signature_algorithm"], "ed25519");+ let signed_extension_archive_sha256 =+ measured_sha256(&candidate_measurements, "archive_sha256");+ let signing_key_sha256 = measured_sha256(&candidate_measurements, "public_key_sha256");+ let signed_catalog_sha256 = measured_sha256(&candidate_measurements, "catalog_sha256");+ let driver_binary_sha256 = measured_sha256(&candidate_measurements, "review_driver_sha256");+ assert_eq!(driver_binary_sha256, hash_file(&driver_binary()));+ assert_eq!(+ measured_sha256(&candidate_measurements, "supplied_model_sha256"),+ hash_file(&gate.model)+ );++ let journal = FixtureJournal::start();+ let fixture_title = fixture_title(&gate.session_label, scope);+ let fixture = spawn_in_job(&mut fixture_command(journal.url(), &fixture_title, scope))+ .expect("start canvas fixture");+ wait_until(+ || journal.snapshot()["ready"].as_bool() == Some(true),+ "fixture did not become ready",+ );+ let pid = fixture_pid(&journal.snapshot())+ .unwrap_or_else(|error| panic!("read fixture process identity: {error}"));+ #[cfg(target_os = "macos")]+ let mut driver = McpDriver::spawn_macos_daemon_proxy_named(&gate.session_label)+ .expect("connect to the exact TCC-authorized review Driver daemon");+ #[cfg(not(target_os = "macos"))]+ let mut driver = {+ let extension_home = gate.extension_home.to_string_lossy().into_owned();+ McpDriver::spawn_named_with_env(+ &gate.session_label,+ &[("CUA_DRIVER_RS_HOME", extension_home.as_str())],+ )+ .expect("start Driver with installed candidate extension")+ };+ driver.reaper().push(fixture);+ let (window_id, _) = find_fixture_window(&mut driver, pid, &fixture_title)+ .unwrap_or_else(|error| panic!("find canvas fixture: {error}"));++ let window_session = format!("{}-window-target", gate.session_label);+ let action_session = format!("{}-{}", gate.session_label, scope.slug());+ for (session, capture_scope) in [+ (window_session.as_str(), "window"),+ (action_session.as_str(), scope.capture_scope()),+ ] {+ let started = driver.call(+ "start_session",+ json!({"session": session, "capture_scope": capture_scope}),+ );+ assert!(+ !started.is_error(),+ "start_session capture_scope={capture_scope} failed: {}",+ started.text()+ );+ }+ let framed = driver.call(+ "set_window_frame",+ json!({+ "session": window_session, "pid": pid, "window_id": window_id,+ "x": 96, "y": 96, "width": 780, "height": 500+ }),+ );+ assert!(+ !framed.is_error(),+ "could not set deterministic fixture frame: {}",+ framed.text()+ );+ let foregrounded = driver.call(+ "bring_to_front",+ json!({"session": window_session, "pid": pid, "window_id": window_id}),+ );+ assert!(+ !foregrounded.is_error(),+ "could not foreground canvas fixture: {}",+ foregrounded.text()+ );+ thread::sleep(Duration::from_millis(300));++ let started = Instant::now();+ if matches!(scope, DemoScope::PrimaryDesktop) {+ let window_ax = driver.call(+ "get_window_state",+ json!({+ "session": window_session, "pid": pid, "window_id": window_id,+ "capture_mode": "ax"+ }),+ );+ assert!(+ !window_ax.is_error(),+ "fixture AX proof failed before desktop capture: {}",+ window_ax.text()+ );+ assert_painted_labels_absent_from_window_ax(&window_ax);+ }+ let observation_args = match scope {+ DemoScope::Window => {+ json!({"session": action_session, "pid": pid, "window_id": window_id, "capture_mode": "ax"})+ }+ DemoScope::PrimaryDesktop => json!({"session": action_session}),+ };+ let first = driver.call(scope.capture_kind(), observation_args.clone());+ assert!(+ !first.is_error(),+ "initial observation failed: {}",+ first.text()+ );+ assert_painted_labels_are_visual_only(scope, &first);+ let capture_id = first.structured()["capture_id"]+ .as_str()+ .expect("capture_id")+ .to_owned();+ driver.start_behavior_recording();+ let parsed = driver.call("parse_visual_regions", json!({+ "session": action_session,+ "capture_id": capture_id,+ "options": {"kinds": ["text", "icon"], "min_confidence": MIN_CONFIDENCE, "max_regions": MAX_REGIONS}+ }));+ assert!(+ !parsed.is_error(),+ "perception worker failed: {}",+ parsed.text()+ );+ let (candidates, regions) =+ bounded_candidates(parsed.structured(), &capture_id).expect("bounded candidates");+ require_unique_actionable_send(&candidates, regions.len())+ .unwrap_or_else(|error| panic!("perception candidate contract failed: {error}"));+ let request =+ choice_request(&capture_id, ®ions, &candidates).expect("bounded chooser request");+ let (choice_response, selected_candidate) = choose(&gate.choice, &request, &candidates);+ if matches!(&gate.choice, ChoiceConfig::Live { .. }) {+ assert!(+ choice_response.model.as_deref().is_some_and(safe_id),+ "live chooser must return its bounded provider model identity"+ );+ }+ let choice = selected_candidate.action.clone().unwrap_or_else(|| {+ panic!(+ "demo chooser did not select the host-authorized exact Send action; {}",+ choice_failure_diagnostic(&choice_response, &candidates)+ )+ });++ let click_args = match scope {+ DemoScope::Window => json!({+ "session": action_session, "pid": pid, "window_id": window_id,+ "x": choice.x, "y": choice.y, "capture_id": choice.capture_id,+ "delivery_mode": scope.delivery_mode()+ }),+ DemoScope::PrimaryDesktop => json!({+ "session": action_session, "scope": "desktop", "x": choice.x, "y": choice.y,+ "capture_id": choice.capture_id, "delivery_mode": scope.delivery_mode()+ }),+ };+ let (background_desktop_refused, refused_capture_id) =+ if matches!(scope, DemoScope::PrimaryDesktop) {+ let mut refused_args = click_args.clone();+ refused_args["delivery_mode"] = Value::String("background".to_owned());+ let refused_capture_id = refused_args["capture_id"]+ .as_str()+ .expect("background refusal capture_id")+ .to_owned();+ let refused = driver.call("click", refused_args);+ assert!(+ refused.is_error(),+ "desktop/background click was not refused: {}",+ refused.text()+ );+ assert_eq!(+ refused.structured()["code"],+ "background_unavailable",+ "desktop/background refusal used an unexpected code"+ );+ assert_eq!(refused.structured()["effect"], "refused");+ assert_eq!(+ refused.structured()["escalation"]["recommended"],+ "foreground"+ );+ assert_eq!(+ journal.snapshot()["action_count"],+ 0,+ "refused desktop/background click reached the fixture"+ );+ (Some(true), Some(refused_capture_id))+ } else {+ (None, None)+ };+ let click = driver.call("click", click_args.clone());+ let click_succeeded = !click.is_error();+ assert!(+ click_succeeded,+ "capture-bound click failed: {}",+ click.text()+ );+ if matches!(scope, DemoScope::Window) {+ assert_eq!(+ click.action_delivery_mode(),+ Some("background"),+ "Tk window click did not preserve background delivery: {}",+ click.text()+ );+ #[cfg(target_os = "windows")]+ assert_eq!(+ click.action_route(),+ Some("global_input"),+ "Tk window/background click did not use targeted injection: {}",+ click.text()+ );+ }+ wait_for_send_transition(&journal, scope, window_id, &choice, &click);+ let capture_preserved_after_refusal = refused_capture_id+ .map(|refused_capture_id| click_succeeded && refused_capture_id == choice.capture_id);+ assert_eq!(+ capture_preserved_after_refusal, background_desktop_refused,+ "foreground retry did not successfully reuse the refused desktop capture"+ );+ assert!(+ driver.call("click", click_args).is_error(),+ "capture reuse was not refused"+ );++ let second = driver.call(scope.capture_kind(), observation_args);+ assert!(+ !second.is_error(),+ "fresh observation failed: {}",+ second.text()+ );+ let second_capture_id = second.structured()["capture_id"]+ .as_str()+ .expect("fresh capture_id")+ .to_owned();+ assert_ne!(capture_id, second_capture_id);+ let reparsed = driver.call("parse_visual_regions", json!({+ "session": action_session,+ "capture_id": second_capture_id,+ "options": {"kinds": ["text", "icon"], "min_confidence": MIN_CONFIDENCE, "max_regions": MAX_REGIONS}+ }));+ assert!(+ !reparsed.is_error(),+ "fresh perception pass failed: {}",+ reparsed.text()+ );+ let (fresh_candidates, _) = bounded_candidates(reparsed.structured(), &second_capture_id)+ .expect("fresh bounded candidates");+ assert!(fresh_candidates+ .iter()+ .any(|candidate| candidate.id == "reobserve"));+ assert!(fresh_candidates+ .iter()+ .any(|candidate| candidate.id == "abstain"));+ assert!(+ fresh_candidates+ .iter()+ .filter_map(|candidate| candidate.action.as_ref())+ .all(|action| action.capture_id == second_capture_id+ && action.capture_id != capture_id),+ "reobserve reused an action from the consumed capture"+ );++ let oracle = journal.snapshot();+ let recording_dir = driver+ .recording_dir()+ .expect("recording directory")+ .to_path_buf();+ let parser = parsed.structured()["parser"].clone();+ let duration_ms = started.elapsed().as_millis() as u64;+ drop(driver);+ let recording = recording_dir.join("recording.mp4");+ assert!(recording.is_file(), "testkit recording did not finalize");+ let evidence_dir = match scope {+ DemoScope::Window => gate.evidence_dir.clone(),+ DemoScope::PrimaryDesktop => gate.evidence_dir.join("primary-desktop"),+ };+ fs::create_dir_all(&evidence_dir).expect("create evidence directory");+ let published_recording = evidence_dir.join("recording.mp4");+ fs::copy(&recording, &published_recording).expect("copy decoded recording evidence");+ let recording_sha256 = hash_file(&published_recording);+ let recording_size = fs::metadata(&published_recording)+ .expect("measure recording")+ .len();+ let recording_metadata = recording_metadata(&published_recording);+ let capture_width = parsed.structured()["capture"]["screenshot"]["width"]+ .as_u64()+ .expect("parsed capture width");+ let capture_height = parsed.structured()["capture"]["screenshot"]["height"]+ .as_u64()+ .expect("parsed capture height");+ let platform = if cfg!(target_os = "windows") {+ "windows"+ } else if cfg!(target_os = "macos") {+ "macos"+ } else {+ "linux-x11"+ };+ let (mode, chooser_provider) = match &gate.choice {+ ChoiceConfig::Mock => ("mock", "fixture"),+ ChoiceConfig::Live { .. } => ("live", "typesafe"),+ };+ let raw = json!({+ "schema": "cua-visual-perception-demo-raw/v2",+ "source_sha": gate.source_sha,+ "jev_source_sha": gate.jev_source_sha,+ "platform": platform,+ "capture_ids": {"acted": capture_id, "fresh": second_capture_id},+ "observation": {+ "input_scope": scope.capture_scope(), "capture_kind": scope.capture_kind(),+ "capture_source": "driver-screenshot", "width": capture_width,+ "height": capture_height, "desktop_session": gate.desktop_session,+ "runner_identity_class": gate.runner_identity_class,+ "delivery_mode": scope.delivery_mode()+ },+ "fixture_oracle": oracle,+ "extension_status": extension_status,+ "parser": parser,+ "chooser": {"mode": mode, "request": request, "response": choice_response},+ "host_validated_regions": regions,+ "resolved_action": {"candidate_id": selected_candidate.id, "x": choice.x, "y": choice.y},+ "verification": {+ "oracle": "passed",+ "background_desktop_refused": background_desktop_refused,+ "capture_preserved_after_refusal": capture_preserved_after_refusal,+ "stale_capture_refused": true+ },+ "timeline": {"duration_ms": duration_ms, "events": [+ "observed", "parsed", "chosen",+ if background_desktop_refused == Some(true) { "background_desktop_refused" } else { "background_refusal_not_applicable" },+ "clicked", "oracle_verified", "stale_capture_refused", "reobserved"+ ]},+ "recording": {"local_path": recording.to_string_lossy(), "sha256": recording_sha256,+ "metadata": recording_metadata}+ });+ let raw_bytes = serde_json::to_vec_pretty(&raw).expect("serialize raw evidence");+ let raw_sha256 = hash_bytes(&raw_bytes);+ fs::write(evidence_dir.join("raw-manifest.json"), &raw_bytes).expect("write raw evidence");+ fs::write(+ evidence_dir.join("timeline.json"),+ serde_json::to_vec_pretty(&raw["timeline"]).expect("serialize private timeline"),+ )+ .expect("write private timeline evidence");++ let manifest = json!({+ "schema": "cua-visual-perception-demo-evidence/v3",+ "platform": platform,+ "raw_evidence_sha256": raw_sha256,+ "fixture": {"id": "visual-only-canvas/v1", "oracle": {+ "source": "fixture-journal", "initial_ready": true,+ "selected": oracle["selected"], "action_count": oracle["action_count"],+ "result": "passed"+ }},+ "runtime": {+ "driver": {+ "source_sha": gate.source_sha,+ "version": candidate_measurements["review_driver_version"],+ "binary_sha256": driver_binary_sha256,+ "build": {+ "profile": candidate_measurements["review_driver_build_profile"],+ "target": candidate_measurements["target"],+ "sealed_artifact_manifest_sha256": candidate_measurements["sealed_artifact_manifest_sha256"],+ "sealed_extension_manifest_sha256": candidate_measurements["sealed_extension_manifest_sha256"]+ }+ },+ "perception": {+ "extension_id": "cua-perception",+ "extension_version": extension_status["active_version"],+ "trust": "review-only-publisher-verified",+ "publisher_id": extension_status["publisher_id"],+ "publisher_key_id": extension_status["publisher_key_id"],+ "catalog_version": extension_status["catalog_version"],+ "signature_algorithm": "ed25519",+ "signed_extension_archive_sha256": signed_extension_archive_sha256,+ "signing_key_sha256": signing_key_sha256,+ "signed_catalog_sha256": signed_catalog_sha256,+ "protocol_version": candidate_measurements["protocol_version"],+ "worker_sha256": candidate_measurements["worker_sha256"],+ "self_test": candidate_measurements["self_test"],+ "models": candidate_measurements["models"],+ "onnx_runtime": candidate_measurements["onnx_runtime"],+ "parser_model_id": parser["model_id"]+ },+ "chooser": {+ "mode": mode,+ "provider": chooser_provider,+ "model_id": choice_response.model,+ "adapter_source_sha": gate.source_sha,+ "source_sha": gate.jev_source_sha+ }+ },+ "observation": {+ "session_label": action_session,+ "input_scope": scope.capture_scope(), "capture_kind": scope.capture_kind(),+ "capture_source": "driver-screenshot",+ "dimensions": {"width": capture_width, "height": capture_height},+ "acted_capture_id_sha256": hash_bytes(capture_id.as_bytes()),+ "fresh_capture_id_sha256": hash_bytes(second_capture_id.as_bytes()),+ "capture_trace_sha256": hash_bytes(format!("{capture_id}\0{second_capture_id}").as_bytes()),+ "candidates": raw["chooser"]["request"]["candidates"]+ },+ "environment": {+ "os": {"name": gate.os_name, "version": gate.os_version, "arch": gate.os_arch},+ "desktop_session": gate.desktop_session,+ "runner_identity_class": gate.runner_identity_class,+ "delivery_mode": scope.delivery_mode()+ },+ "result": {+ "status": "passed",+ "selected_candidate": selected_candidate.id,+ "background_desktop_refused": background_desktop_refused,+ "capture_preserved_after_refusal": capture_preserved_after_refusal,+ "stale_capture_refused": true+ },+ "recording": {+ "original_dimensions": {"width": recording_metadata["width"], "height": recording_metadata["height"]},+ "delivered_dimensions": {"width": recording_metadata["width"], "height": recording_metadata["height"]},+ "frame_rate": recording_metadata["frame_rate"],+ "cursor": {"agent_overlay": false, "system_cursor": "recorder-default"},+ "edit_operations": [{"operation": "none", "speed": "1x"}],+ "shots": [{"source_sha256": recording_sha256, "start_ms": 0,+ "end_ms": recording_metadata["duration_ms"]}],+ "final_sha256": recording_sha256, "size_bytes": recording_size+ },+ "artifacts": [{"kind": "video", "path": "recording.mp4", "sha256": recording_sha256, "size_bytes": recording_size}]+ });+ let schema: Value = serde_json::from_str(include_str!(+ "../../../../tests/perception-demo/evidence-manifest.schema.json"+ ))+ .expect("parse evidence schema");+ assert!(+ jsonschema::is_valid(&schema, &manifest),+ "redacted manifest must satisfy schema"+ );+ fs::write(+ evidence_dir.join("manifest.json"),+ serde_json::to_vec_pretty(&manifest).unwrap(),+ )+ .expect("write redacted manifest");+ }++ #[test]+ fn fixture_discovery_requires_exact_title_and_owner() {+ let windows = json!([+ {"window_id": 10, "pid": 42, "title": "Cua Visual-Only Canvas Fixture - stale"},+ {"window_id": 11, "pid": 41, "title": FIXTURE_TEST_TITLE},+ {"window_id": 12, "pid": 42, "title": FIXTURE_TEST_TITLE}+ ]);+ assert_eq!(+ exact_fixture_window(&windows, 42, FIXTURE_TEST_TITLE).unwrap(),+ Some((12, FIXTURE_TEST_TITLE.to_owned()))+ );+ }++ #[test]+ fn fixture_journal_requires_positive_integer_pid() {+ assert_eq!(fixture_pid(&json!({"pid": 42})).unwrap(), 42);+ for pid in [+ Value::Null,+ json!(0),+ json!(-1),+ json!("42"),+ json!(1.5),+ json!(u64::MAX),+ ] {+ let error = fixture_pid(&json!({"pid": pid})).unwrap_err();+ assert!(error.contains("invalid pid"), "unexpected error: {error}");+ }+ assert!(fixture_pid(&json!({})).unwrap_err().contains("invalid pid"));+ }++ #[test]+ fn fixture_discovery_refuses_ambiguous_owner_matches() {+ let windows = json!([+ {"window_id": 10, "pid": null, "title": FIXTURE_TEST_TITLE},+ {"window_id": 11, "pid": null, "title": FIXTURE_TEST_TITLE}+ ]);+ assert!(exact_fixture_window(&windows, 42, FIXTURE_TEST_TITLE)+ .unwrap_err()+ .contains("ambiguous fixture identity"));+ }++ #[test]+ fn fixture_discovery_retries_one_unique_title_with_missing_pid() {+ let windows = json!([+ {"window_id": 10, "pid": null, "title": FIXTURE_TEST_TITLE}+ ]);+ assert_eq!(+ exact_fixture_window(&windows, 42, FIXTURE_TEST_TITLE).unwrap(),+ None+ );+ let diagnostic = fixture_window_diagnostic(&windows, 42, FIXTURE_TEST_TITLE);+ assert!(diagnostic.contains("expected pid 42"));+ assert!(diagnostic.contains("pid=missing"));+ }++ #[test]+ fn fixture_discovery_rejects_explicit_mismatched_pid() {+ let windows = json!([+ {"window_id": 10, "pid": 41, "title": FIXTURE_TEST_TITLE}+ ]);+ assert!(exact_fixture_window(&windows, 42, FIXTURE_TEST_TITLE)+ .unwrap_err()+ .contains("not expected pid 42"));+ }++ #[test]+ fn fixture_discovery_refuses_zero_window_id() {+ let windows = json!([+ {"window_id": 0, "pid": 42, "title": FIXTURE_TEST_TITLE}+ ]);+ assert!(exact_fixture_window(&windows, 42, FIXTURE_TEST_TITLE)+ .unwrap_err()+ .contains("invalid window_id"));+ }++ #[test]+ fn fixture_discovery_refuses_missing_or_non_array_windows() {+ for windows in [Value::Null, json!({"window_id": 10})] {+ assert!(exact_fixture_window(&windows, 42, FIXTURE_TEST_TITLE)+ .unwrap_err()+ .contains("omitted its windows array"));+ }+ }++ #[test]+ fn fixture_discovery_accepts_maximum_window_id() {+ let windows = json!([+ {"window_id": u64::MAX, "pid": 42, "title": FIXTURE_TEST_TITLE}+ ]);+ assert_eq!(+ exact_fixture_window(&windows, 42, FIXTURE_TEST_TITLE).unwrap(),+ Some((u64::MAX, FIXTURE_TEST_TITLE.to_owned()))+ );+ }++ #[test]+ #[ignore = "requires the reviewed live Jev chooser and protected credential"]+ fn authorized_live_jev_no_matching_action_control() {+ let config = choice_config_from(+ std::env::var("CUA_JEV_LIVE").ok().as_deref(),+ std::env::var("CUA_JEV_MOCK_DEMO").ok().as_deref(),+ std::env::var("CUA_JEV_CHOOSER_PROGRAM").ok().as_deref(),+ std::env::var("CUA_JEV_CHOOSER_SCRIPT").ok().as_deref(),+ )+ .expect("valid live chooser configuration");+ assert!(matches!(config, ChoiceConfig::Live { .. }));+ let candidates = vec![+ Candidate {+ id: "region:save".into(),+ description: send_action_description("save", "text", "Send", 0.98),+ region_id: Some("save".into()),+ action: Some(ClickAction {+ capture_id: "synthetic-negative-1".into(),+ x: 50.0,+ y: 25.0,+ }),+ },+ Candidate {+ id: "reobserve".into(),+ description: REOBSERVE_DESCRIPTION.into(),+ region_id: None,+ action: None,+ },+ Candidate {+ id: "abstain".into(),+ description: ABSTAIN_DESCRIPTION.into(),+ region_id: None,+ action: None,+ },+ ];+ let regions = vec![CompactRegion {+ id: "save".into(),+ kind: "text".into(),+ bounds: RegionBounds {+ x: 10,+ y: 10,+ width: 80,+ height: 30,+ },+ text: Some("Save".into()),+ label: None,+ confidence: 0.98,+ interactive: true,+ }];+ let request = choice_request("synthetic-negative-1", ®ions, &candidates)+ .expect("bounded synthetic negative request");+ let (response, selected) = choose(&config, &request, &candidates);+ assert_eq!(+ selected.id,+ "abstain",+ "no action condition matches the supplied state; {}",+ choice_failure_diagnostic(&response, &candidates)+ );+ assert!(+ selected.action.is_none(),+ "negative control must never resolve to an action"+ );+ }++ #[test]+ #[ignore = "requires an installed review-only publisher-verified perception extension and desktop session"]+ fn authorized_visual_only_window_demo() {+ run_authorized_visual_only_demo(DemoScope::Window);+ }++ #[test]+ #[ignore = "requires an installed review-only publisher-verified perception extension and desktop session"]+ fn authorized_visual_only_primary_desktop_demo() {+ run_authorized_visual_only_demo(DemoScope::PrimaryDesktop);+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/cross_platform_behavior_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/cross_platform_behavior_test.rsindex 2a69547341..d323066087 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/cross_platform_behavior_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/cross_platform_behavior_test.rs@@ -292,6 +292,34 @@ fn allocate_loopback_port() -> u16 {listener.local_addr().expect("read fixture port").port()}+fn accessibility_readiness_timeout(host_name: &str) -> Duration {+ if matches!(host_name, "electron" | "tauri") {+ Duration::from_secs(30)+ } else {+ Duration::from_secs(10)+ }+}++#[test]+fn electron_and_tauri_receive_extended_accessibility_readiness_budget() {+ assert_eq!(+ accessibility_readiness_timeout("electron"),+ Duration::from_secs(30)+ );+ assert_eq!(+ accessibility_readiness_timeout("tauri"),+ Duration::from_secs(30)+ );+ assert_eq!(+ accessibility_readiness_timeout("webview2"),+ Duration::from_secs(10)+ );+ assert_eq!(+ accessibility_readiness_timeout("wkwebview"),+ Duration::from_secs(10)+ );+}+fn launch_host_with_evidence(spec: &HostSpec, scenario: &str, evidence: &mut Evidence) -> Fixture {if !spec.path.exists() {panic!(@@ -371,17 +399,10 @@ fn launch_host_with_evidence(spec: &HostSpec, scenario: &str, evidence: &mut Eviname: spec.name,journal,};- // A freshly provisioned platform webview can need more than- // the generic fixture budget to start its renderer and- // expose the remote accessibility subtree (observed for- // cold Windows WebView2 and macOS WKWebView helpers). Keep- // the extension Tauri-specific and bounded; every other- // harness still fails fast.- let ax_timeout = if spec.name == "tauri" {- Duration::from_secs(30)- } else {- Duration::from_secs(10)- };+ // Electron and Tauri can need more than the generic fixture+ // budget to start their renderer and expose the remote+ // accessibility subtree on a cold host.+ let ax_timeout = accessibility_readiness_timeout(spec.name);let ax_deadline = Instant::now() + ax_timeout;let mut last_tree = String::new();while Instant::now() < ax_deadline {@@ -856,6 +877,7 @@ fn sdk_window_input(fixture: &Fixture) -> GetWindowStateInput {max_elements: None,max_depth: None,max_dimension: None,+ max_image_dimension: None,}}@@ -1636,6 +1658,9 @@ fn shared_case_with_native_hyprland(}} else if cfg!(target_os = "macos") && delivery_kind == Delivery::Background {match (spec.name, action, targeting) {+ ("electron", "type_text" | "type_submit" | "editor_save", Targeting::Ax) => {+ vec![RefusalCode::BackgroundUnavailable]+ }("electron", "scroll", _) | (_, "drag", Targeting::Px) => {vec![RefusalCode::BackgroundUnavailable]}diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/extension_manager_cli_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/extension_manager_cli_test.rsnew file mode 100644index 0000000000..5c82b803c1--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver/tests/extension_manager_cli_test.rs@@ -0,0 +1,771 @@+#[cfg(feature = "review-trust-root")]+use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};+use flate2::{write::GzEncoder, Compression};+#[cfg(feature = "review-trust-root")]+use ring::signature::Ed25519KeyPair;+#[cfg(feature = "review-trust-root")]+use serde::Serialize;+use serde_json::{json, Value};+use sha2::{Digest, Sha256};+use std::fs;+use std::io::Cursor;+use std::path::{Path, PathBuf};+use std::process::{Command, Output};+use tempfile::TempDir;++fn run(home: &Path, args: &[&str]) -> Output {+ Command::new(env!("CARGO_BIN_EXE_cua-driver"))+ .args(args)+ .env("CUA_DRIVER_RS_HOME", home)+ .env("CUA_DRIVER_CLI_TELEMETRY_CHILD", "1")+ .output()+ .expect("run cua-driver extension command")+}++fn current_target() -> String {+ let suffix = if cfg!(target_os = "macos") {+ "apple-darwin"+ } else if cfg!(all(target_os = "windows", target_env = "msvc")) {+ "pc-windows-msvc"+ } else if cfg!(all(target_os = "linux", target_env = "musl")) {+ "unknown-linux-musl"+ } else if cfg!(all(target_os = "linux", target_env = "gnu")) {+ "unknown-linux-gnu"+ } else {+ panic!("unsupported extension-manager test target")+ };+ format!("{}-{suffix}", std::env::consts::ARCH)+}++fn fixture_archive(directory: &Path, version: &str) -> PathBuf {+ fixture_archive_with_legal_bindings(directory, version, true)+}++fn fixture_archive_with_legal_bindings(+ directory: &Path,+ version: &str,+ legal_bindings: bool,+) -> PathBuf {+ let payload: &[u8] = if cfg!(windows) {+ b"@exit /b 0\r\n"+ } else {+ b"#!/bin/sh\nexit 0\n"+ };+ let entrypoint = if cfg!(windows) {+ "bin/cua-perception.cmd"+ } else {+ "bin/cua-perception"+ };+ let digest = format!("{:x}", Sha256::digest(payload));+ let model = b"fixture-model";+ let model_digest = format!("{:x}", Sha256::digest(model));+ let model_license = b"Fixture model license\n";+ let model_license_digest = format!("{:x}", Sha256::digest(model_license));+ let notice = b"Copyright Cua contributors\n";+ let notice_digest = format!("{:x}", Sha256::digest(notice));+ let corresponding_source = b"source revision integration-fixture\n";+ let corresponding_source_digest = format!("{:x}", Sha256::digest(corresponding_source));+ let mut manifest_value = json!({+ "schema_version": 1,+ "id": "cua-perception",+ "version": version,+ "driver_version": format!("={}", env!("CARGO_PKG_VERSION")),+ "protocol_version": 1,+ "target": current_target(),+ "entrypoint": entrypoint,+ "files": [+ {"path": entrypoint, "sha256": digest, "executable": true},+ {"path": "models/parser.bin", "sha256": model_digest},+ {"path": "LICENSES/model.txt", "sha256": model_license_digest},+ {"path": "LICENSES/NOTICE.txt", "sha256": notice_digest},+ {"path": "SOURCE/corresponding-source.txt", "sha256": corresponding_source_digest}+ ],+ "models": [{+ "path": "models/parser.bin", "revision": "model-v1",+ "original_sha256": "11".repeat(32), "conversion_sha256": model_digest,+ "license_file": {"path": "LICENSES/model.txt", "sha256": model_license_digest}+ }],+ "components": [{+ "name": "cua-perception", "version": version, "license": "Apache-2.0",+ "notice": "Copyright Cua contributors", "source_uri": "https://github.com/trycua/cua",+ "source_revision": "integration-fixture",+ "notice_file": {"path": "LICENSES/NOTICE.txt", "sha256": notice_digest}+ }],+ "corresponding_source_file": {"path": "SOURCE/corresponding-source.txt", "sha256": corresponding_source_digest},+ "license": "Apache-2.0",+ "source": "https://github.com/trycua/cua",+ "corresponding_source_uri": "https://github.com/trycua/cua",+ "corresponding_source_revision": "integration-fixture",+ "provenance": "integration test fixture",+ // Hooks now run inside the perception worker's containment boundary,+ // which grants execution to the entrypoint image alone. A scripted+ // fixture entrypoint cannot launch there, so this end-to-end fixture+ // declares no hook; hook behavior is covered by the focused+ // extension-manager and containment unit tests.+ "health_args": [],+ "self_test_args": []+ });+ if !legal_bindings {+ manifest_value["components"][0]+ .as_object_mut()+ .unwrap()+ .remove("notice_file");+ }+ let manifest = serde_json::to_vec_pretty(&manifest_value).unwrap();+ let path = directory.join(format!("cua-perception-{version}.tar.gz"));+ let encoder = GzEncoder::new(fs::File::create(&path).unwrap(), Compression::default());+ let mut builder = tar::Builder::new(encoder);+ append(&mut builder, "extension.json", &manifest);+ append(&mut builder, entrypoint, payload);+ append(&mut builder, "models/parser.bin", model);+ append(&mut builder, "LICENSES/model.txt", model_license);+ append(&mut builder, "LICENSES/NOTICE.txt", notice);+ append(+ &mut builder,+ "SOURCE/corresponding-source.txt",+ corresponding_source,+ );+ builder.finish().unwrap();+ path+}++fn append(builder: &mut tar::Builder<GzEncoder<fs::File>>, path: &str, bytes: &[u8]) {+ let mut header = tar::Header::new_gnu();+ header.set_size(bytes.len() as u64);+ header.set_mode(0o755);+ header.set_cksum();+ builder+ .append_data(&mut header, path, Cursor::new(bytes))+ .unwrap();+}++#[cfg(feature = "review-trust-root")]+#[derive(Clone, Serialize)]+struct ReviewCatalogPayload {+ schema_version: u32,+ catalog_version: u64,+ expires_unix: u64,+ publisher_id: String,+ publisher_name: String,+ key_id: String,+ extension_id: String,+ version: String,+ target: String,+ archive: String,+ archive_size: u64,+ archive_sha256: String,+ manifest_sha256: String,+ license: String,+ source: String,+ corresponding_source_uri: String,+ corresponding_source_revision: String,+ provenance: String,+ next_key: Option<Value>,+}++#[cfg(feature = "review-trust-root")]+fn archive_manifest(archive: &Path) -> Vec<u8> {+ let decoder = flate2::read::GzDecoder::new(fs::File::open(archive).unwrap());+ let mut tar = tar::Archive::new(decoder);+ for item in tar.entries().unwrap() {+ let mut item = item.unwrap();+ if item.path().unwrap() == Path::new("extension.json") {+ let mut bytes = Vec::new();+ std::io::Read::read_to_end(&mut item, &mut bytes).unwrap();+ return bytes;+ }+ }+ panic!("fixture archive omitted extension.json")+}++#[cfg(feature = "review-trust-root")]+fn review_catalog(+ directory: &Path,+ archive: &Path,+ version: &str,+ catalog_version: u64,+ expires_unix: u64,+ target: String,+ seed: [u8; 32],+) -> PathBuf {+ let archive_bytes = fs::read(archive).unwrap();+ let manifest = archive_manifest(archive);+ let payload = ReviewCatalogPayload {+ schema_version: 1,+ catalog_version,+ expires_unix,+ publisher_id: "cua-review-only".to_owned(),+ publisher_name: "Cua REVIEW ONLY".to_owned(),+ key_id: "review-only-build-override".to_owned(),+ extension_id: "cua-perception".to_owned(),+ version: version.to_owned(),+ target,+ archive: archive.file_name().unwrap().to_str().unwrap().to_owned(),+ archive_size: archive_bytes.len() as u64,+ archive_sha256: format!("{:x}", Sha256::digest(&archive_bytes)),+ manifest_sha256: format!("{:x}", Sha256::digest(&manifest)),+ license: "Apache-2.0".to_owned(),+ source: "https://github.com/trycua/cua".to_owned(),+ corresponding_source_uri: "https://github.com/trycua/cua".to_owned(),+ corresponding_source_revision: "integration-fixture".to_owned(),+ provenance: "integration test fixture".to_owned(),+ next_key: None,+ };+ let pair = Ed25519KeyPair::from_seed_unchecked(&seed).unwrap();+ let signature = BASE64.encode(pair.sign(&serde_json::to_vec(&payload).unwrap()).as_ref());+ let catalog = json!({+ "payload": payload,+ "signature_algorithm": "ed25519",+ "signature": signature,+ });+ let path = directory.join(format!("catalog-{version}-{catalog_version}.json"));+ fs::write(&path, serde_json::to_vec_pretty(&catalog).unwrap()).unwrap();+ path+}++#[cfg(feature = "review-trust-root")]+const REVIEW_SEED: [u8; 32] = [+ 0x9d, 0x61, 0xb1, 0x9d, 0xef, 0xfd, 0x5a, 0x60, 0xba, 0x84, 0x4a, 0xf4, 0x92, 0xec, 0x2c, 0xc4,+ 0x44, 0x49, 0xc5, 0x69, 0x7b, 0x32, 0x69, 0x19, 0x70, 0x3b, 0xac, 0x03, 0x1c, 0xae, 0x7f, 0x60,+];++#[test]+fn developer_lifecycle_is_explicit_previewed_and_removable() {+ let temp = TempDir::new().unwrap();+ let home = temp.path().join("driver-home");+ let archive = fixture_archive(temp.path(), "1.2.3");++ let list = run(&home, &["extension", "list", "--json"]);+ assert!(+ list.status.success(),+ "{}",+ String::from_utf8_lossy(&list.stderr)+ );+ let list_json: Value = serde_json::from_slice(&list.stdout).unwrap();+ assert_eq!(list_json[0]["id"], "cua-perception");+ assert_eq!(list_json[0]["installed"], false);++ let rejected = run(+ &home,+ &[+ "extension",+ "install",+ "cua-perception",+ "--archive",+ archive.to_str().unwrap(),+ ],+ );+ assert!(!rejected.status.success());+ assert!(String::from_utf8_lossy(&rejected.stderr).contains("--allow-unsigned-local"));++ let inspect = run(+ &home,+ &[+ "extension",+ "inspect",+ "cua-perception",+ "--archive",+ archive.to_str().unwrap(),+ "--allow-unsigned-local",+ "--json",+ ],+ );+ assert!(+ inspect.status.success(),+ "{}",+ String::from_utf8_lossy(&inspect.stderr)+ );+ let preview: Value = serde_json::from_slice(&inspect.stdout).unwrap();+ assert_eq!(preview["name"], "Cua Perception");+ assert_eq!(preview["trust"], "developer-unsigned-local");+ assert_eq!(preview["signing_key_status"], "unsigned-local");+ assert_eq!(+ preview["artifact_source"],+ archive.to_string_lossy().as_ref()+ );+ assert_eq!(+ preview["destination"],+ home.join("extensions/cua-perception/versions/1.2.3")+ .to_string_lossy()+ .as_ref()+ );+ assert!(preview["download_size"].as_u64().unwrap() > 0);+ assert!(preview["installed_size"].as_u64().unwrap() > 0);+ assert_eq!(preview["license"], "Apache-2.0");+ assert_eq!(preview["models"][0]["revision"], "model-v1");+ assert_eq!(preview["models"][0]["original_sha256"], "11".repeat(32));+ assert_eq!(+ preview["models"][0]["conversion_sha256"],+ preview["files"][1]["sha256"]+ );+ assert_eq!(preview["components"][0]["license"], "Apache-2.0");+ assert_eq!(preview["model_licenses"][0]["model"], "models/parser.bin");+ assert_eq!(preview["authorization"]["request"], "cli-inspect");+ assert_eq!(preview["authorization"]["confirmation_required"], false);+ assert_eq!(preview["authorization"]["mutation_authorized"], false);+ assert_eq!(preview["authorization"]["mutation_performed"], false);+ assert_eq!(preview["mutation_performed"], false);+ assert!(!home.join("extensions/cua-perception").exists());++ let install = run(+ &home,+ &[+ "extension",+ "install",+ "cua-perception",+ "--archive",+ archive.to_str().unwrap(),+ "--allow-unsigned-local",+ ],+ );+ assert!(+ install.status.success(),+ "{}",+ String::from_utf8_lossy(&install.stderr)+ );+ let install_stdout = String::from_utf8_lossy(&install.stdout);+ assert!(install_stdout.contains("developer-unsigned-local"));+ assert!(install_stdout.contains("Signing key status: unsigned-local"));+ assert!(install_stdout.contains("Destination:"));+ assert!(install_stdout.contains("Download size:"));+ assert!(install_stdout.contains("Model: models/parser.bin @ model-v1"));+ assert!(install_stdout.contains("Model license file: LICENSES/model.txt"));+ assert!(install_stdout.contains("mutation_authorized=true"));++ let status = run(+ &home,+ &[+ "extension",+ "status",+ "cua-perception",+ "--self-test",+ "--json",+ ],+ );+ assert!(+ status.status.success(),+ "{}",+ String::from_utf8_lossy(&status.stderr)+ );+ let status_json: Value = serde_json::from_slice(&status.stdout).unwrap();+ assert_eq!(status_json["active_version"], "1.2.3");+ assert_eq!(status_json["trust"], "developer-unsigned-local");+ assert_eq!(status_json["healthy"], true);++ let update_archive = fixture_archive(temp.path(), "1.2.4");+ let update = run(+ &home,+ &[+ "extension",+ "update",+ "cua-perception",+ "--archive",+ update_archive.to_str().unwrap(),+ "--allow-unsigned-local",+ ],+ );+ assert!(+ update.status.success(),+ "{}",+ String::from_utf8_lossy(&update.stderr)+ );+ let updated_status = run(&home, &["extension", "status", "cua-perception", "--json"]);+ let updated_json: Value = serde_json::from_slice(&updated_status.stdout).unwrap();+ assert_eq!(updated_json["active_version"], "1.2.4");++ let remove = run(&home, &["extension", "remove", "cua-perception"]);+ assert!(+ remove.status.success(),+ "{}",+ String::from_utf8_lossy(&remove.stderr)+ );+ assert!(!home.join("extensions/cua-perception").exists());+}++#[cfg(not(feature = "review-trust-root"))]+#[test]+fn signed_catalog_rejects_forgery_before_state_creation() {+ let temp = TempDir::new().unwrap();+ let home = temp.path().join("driver-home");+ let archive = fixture_archive(temp.path(), "1.2.3");+ let archive_bytes = fs::read(&archive).unwrap();+ let catalog = json!({+ "payload": {+ "schema_version": 1, "catalog_version": 1, "expires_unix": 4102444800_u64,+ "publisher_id": "cua", "publisher_name": "Cua",+ "key_id": "cua-extension-ed25519-2026-01", "extension_id": "cua-perception",+ "version": "1.2.3", "target": current_target(),+ "archive": archive.file_name().unwrap().to_str().unwrap(),+ "archive_size": archive_bytes.len(),+ "archive_sha256": format!("{:x}", Sha256::digest(&archive_bytes)),+ "manifest_sha256": "00".repeat(32), "license": "Apache-2.0",+ "source": "https://github.com/trycua/cua",+ "corresponding_source_uri": "https://github.com/trycua/cua",+ "corresponding_source_revision": "integration-fixture",+ "provenance": "forged test catalog"+ },+ "signature_algorithm": "ed25519",+ "signature": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="+ });+ let catalog_path = temp.path().join("catalog.json");+ fs::write(&catalog_path, serde_json::to_vec_pretty(&catalog).unwrap()).unwrap();+ let output = run(+ &home,+ &[+ "extension",+ "install",+ "cua-perception",+ "--catalog",+ catalog_path.to_str().unwrap(),+ ],+ );+ assert!(!output.status.success());+ assert!(String::from_utf8_lossy(&output.stderr).contains("signature verification failed"));+ assert!(!home.join("extensions").exists());+}++#[test]+fn help_and_generated_surfaces_describe_the_secure_contract() {+ let temp = TempDir::new().unwrap();+ let home = temp.path().join("driver-home");+ let help = String::from_utf8_lossy(&run(&home, &["--help"]).stdout).into_owned();+ assert!(help.contains("SIGNED TARGET-SPECIFIC CATALOGS"));+ assert!(help.contains("extension inspect"));+ assert!(help.contains("extension remove"));+ assert!(help.contains("--allow-unsigned-local"));++ let manifest = String::from_utf8_lossy(&run(&home, &["manifest"]).stdout).to_lowercase();+ assert!(manifest.contains("signed, target-specific"));+ assert!(manifest.contains("publisher identity"));+ assert!(manifest.contains("developer-only unsigned"));++ let docs_output = run(&home, &["dump-docs", "--type", "commands"]);+ let docs = String::from_utf8_lossy(&docs_output.stdout).to_lowercase();+ assert!(docs.contains("original-model, and converted-model hashes"));+ assert!(docs.contains("component licenses/notices"));+ assert!(docs.contains("license, source, and provenance"));+}++#[test]+fn mcp_inventory_exposes_only_the_confirm_gated_extension_installer() {+ let temp = TempDir::new().unwrap();+ let home = temp.path().join("driver-home");+ let listed = run(&home, &["list-tools"]);+ assert!(listed.status.success());+ let tools = String::from_utf8_lossy(&listed.stdout);+ assert!(tools+ .contains("install_extension: Preview or install one Driver-managed optional extension"));++ let described = run(&home, &["describe", "install_extension"]);+ assert!(described.status.success());+ let description = String::from_utf8_lossy(&described.stdout);+ assert!(description.contains("confirm"));+ assert!(description.contains("perception"));+ assert!(!description.contains("catalog"));+}++#[test]+fn cli_rejects_ambiguous_extension_arguments() {+ let temp = TempDir::new().unwrap();+ let home = temp.path().join("driver-home");+ for args in [+ vec!["extension", "list", "extra"],+ vec!["extension", "status", "--json", "--json"],+ vec!["extension", "install", "cua-perception", "--archive"],+ vec![+ "extension",+ "install",+ "cua-perception",+ "--archive",+ "x",+ "--catalog",+ "y",+ "--allow-unsigned-local",+ ],+ vec!["extension", "path", "cua-perception"],+ ] {+ let output = run(&home, &args);+ assert!(!output.status.success(), "accepted {args:?}");+ }+}++#[test]+fn cli_parse_errors_do_not_create_extension_state() {+ let temp = TempDir::new().unwrap();+ let home = temp.path().join("driver-home");+ let output = run(+ &home,+ &["extension", "install", "cua-perception", "--catalog"],+ );+ assert!(!output.status.success());+ assert!(String::from_utf8_lossy(&output.stderr).contains("--catalog requires a value"));+ assert!(!home.join("extensions").exists());+}++#[cfg(feature = "review-trust-root")]+#[test]+fn review_signed_lifecycle_is_distinct_fail_closed_and_rollback_safe() {+ let temp = TempDir::new().unwrap();+ let home = temp.path().join("driver-home");+ let archive = fixture_archive(temp.path(), "1.2.3");+ let catalog = review_catalog(+ temp.path(),+ &archive,+ "1.2.3",+ 1,+ 4_102_444_800,+ current_target(),+ REVIEW_SEED,+ );++ let inspect = run(+ &home,+ &[+ "extension",+ "inspect",+ "perception",+ "--catalog",+ catalog.to_str().unwrap(),+ "--json",+ ],+ );+ assert!(+ inspect.status.success(),+ "{}",+ String::from_utf8_lossy(&inspect.stderr)+ );+ let preview: Value = serde_json::from_slice(&inspect.stdout).unwrap();+ assert_eq!(preview["trust"], "review-only-publisher-verified");+ assert_eq!(+ preview["evidence_class"],+ "review-only-not-release-evidence"+ );+ assert_eq!(preview["target"], current_target());+ assert_eq!(preview["version"], "1.2.3");+ assert_eq!(preview["publisher_id"], "cua-review-only");+ assert_eq!(preview["publisher_name"], "Cua REVIEW ONLY");+ assert_eq!(preview["publisher_key_id"], "review-only-build-override");+ assert_eq!(preview["signing_key_algorithm"], "ed25519");+ assert_eq!(preview["signing_key_status"], "verified");+ assert_eq!(preview["publisher_signature_verified"], true);+ assert_eq!(+ preview["destination"],+ home.join("extensions/cua-perception/versions/1.2.3")+ .to_string_lossy()+ .as_ref()+ );+ assert!(preview["download_size"].as_u64().unwrap() > 0);+ assert!(preview["installed_size"].as_u64().unwrap() > 0);+ assert_eq!(preview["models"][0]["revision"], "model-v1");+ assert_eq!(preview["license_notices"][0]["license"], "Apache-2.0");+ assert_eq!(preview["authorization"]["request"], "cli-inspect");+ assert_eq!(preview["authorization"]["mutation_authorized"], false);+ assert_eq!(preview["mutation_performed"], false);++ let install = run(+ &home,+ &[+ "extension",+ "install",+ "perception",+ "--catalog",+ catalog.to_str().unwrap(),+ ],+ );+ assert!(+ install.status.success(),+ "{}",+ String::from_utf8_lossy(&install.stderr)+ );+ let status = run(&home, &["extension", "status", "perception", "--json"]);+ let status_json: Value = serde_json::from_slice(&status.stdout).unwrap();+ assert_eq!(status_json["active_version"], "1.2.3");+ assert_eq!(status_json["trust"], "review-only-publisher-verified");+ assert_eq!(+ status_json["evidence_class"],+ "review-only-not-release-evidence"+ );+ assert!(status_json["detail"]+ .as_str()+ .unwrap()+ .contains("REVIEW ONLY"));++ let update_archive = fixture_archive(temp.path(), "1.2.4");+ let update_catalog = review_catalog(+ temp.path(),+ &update_archive,+ "1.2.4",+ 2,+ 4_102_444_800,+ current_target(),+ REVIEW_SEED,+ );+ let update = run(+ &home,+ &[+ "extension",+ "update",+ "perception",+ "--catalog",+ update_catalog.to_str().unwrap(),+ ],+ );+ assert!(+ update.status.success(),+ "{}",+ String::from_utf8_lossy(&update.stderr)+ );++ let rollback_archive = fixture_archive(temp.path(), "1.2.2");+ let rollback_catalog = review_catalog(+ temp.path(),+ &rollback_archive,+ "1.2.2",+ 3,+ 4_102_444_800,+ current_target(),+ REVIEW_SEED,+ );+ let rollback = run(+ &home,+ &[+ "extension",+ "update",+ "perception",+ "--catalog",+ rollback_catalog.to_str().unwrap(),+ ],+ );+ assert!(!rollback.status.success());+ assert!(String::from_utf8_lossy(&rollback.stderr).contains("must be newer"));+ let status = run(&home, &["extension", "status", "perception", "--json"]);+ let status_json: Value = serde_json::from_slice(&status.stdout).unwrap();+ assert_eq!(status_json["active_version"], "1.2.4");++ let replay = run(+ &home,+ &[+ "extension",+ "update",+ "perception",+ "--catalog",+ update_catalog.to_str().unwrap(),+ ],+ );+ assert!(!replay.status.success());+ assert!(String::from_utf8_lossy(&replay.stderr).contains("anti-rollback"));+}++#[cfg(feature = "review-trust-root")]+#[test]+fn review_catalog_rejects_wrong_key_tamper_expiry_target_and_missing_legal_files() {+ let temp = TempDir::new().unwrap();+ let archive = fixture_archive(temp.path(), "1.2.3");+ let cases = [+ (+ "wrong-key",+ review_catalog(+ temp.path(),+ &archive,+ "1.2.3",+ 11,+ 4_102_444_800,+ current_target(),+ [7; 32],+ ),+ "signature verification failed",+ ),+ (+ "expired",+ review_catalog(+ temp.path(),+ &archive,+ "1.2.3",+ 12,+ 1,+ current_target(),+ REVIEW_SEED,+ ),+ "expired",+ ),+ (+ "target",+ review_catalog(+ temp.path(),+ &archive,+ "1.2.3",+ 13,+ 4_102_444_800,+ "x86_64-unknown-linux-gnu".to_owned(),+ REVIEW_SEED,+ ),+ "target does not match",+ ),+ ];+ for (name, catalog, expected) in cases {+ let home = temp.path().join(format!("home-{name}"));+ let output = run(+ &home,+ &[+ "extension",+ "install",+ "perception",+ "--catalog",+ catalog.to_str().unwrap(),+ ],+ );+ assert!(!output.status.success(), "accepted {name}");+ assert!(String::from_utf8_lossy(&output.stderr).contains(expected));+ assert!(!home.join("extensions/cua-perception").exists());+ }++ let valid = review_catalog(+ temp.path(),+ &archive,+ "1.2.3",+ 14,+ 4_102_444_800,+ current_target(),+ REVIEW_SEED,+ );+ let mut tampered: Value = serde_json::from_slice(&fs::read(&valid).unwrap()).unwrap();+ tampered["payload"]["archive_size"] = json!(1);+ fs::write(&valid, serde_json::to_vec_pretty(&tampered).unwrap()).unwrap();+ let tamper_home = temp.path().join("home-tamper");+ let output = run(+ &tamper_home,+ &[+ "extension",+ "install",+ "perception",+ "--catalog",+ valid.to_str().unwrap(),+ ],+ );+ assert!(!output.status.success());+ assert!(String::from_utf8_lossy(&output.stderr).contains("signature verification failed"));++ let incomplete = fixture_archive_with_legal_bindings(temp.path(), "1.2.5", false);+ let incomplete_catalog = review_catalog(+ temp.path(),+ &incomplete,+ "1.2.5",+ 15,+ 4_102_444_800,+ current_target(),+ REVIEW_SEED,+ );+ let incomplete_home = temp.path().join("home-incomplete");+ let output = run(+ &incomplete_home,+ &[+ "extension",+ "install",+ "perception",+ "--catalog",+ incomplete_catalog.to_str().unwrap(),+ ],+ );+ assert!(!output.status.success());+ assert!(String::from_utf8_lossy(&output.stderr).contains("digest-bound notice"));+}diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/fixtures/extension_catalog/sign_catalog.js b/libs/cua-driver/rust/crates/cua-driver/tests/fixtures/extension_catalog/sign_catalog.jsnew file mode 100644index 0000000000..27715b6d3c--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver/tests/fixtures/extension_catalog/sign_catalog.js@@ -0,0 +1,31 @@+#!/usr/bin/env node+const crypto = require("node:crypto");++const seed = Buffer.from(+ "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",+ "hex",+);+const privateKey = crypto.createPrivateKey({+ key: Buffer.concat([+ Buffer.from("302e020100300506032b657004220420", "hex"),+ seed,+ ]),+ format: "der",+ type: "pkcs8",+});+const publicDer = crypto.createPublicKey(privateKey).export({+ format: "der",+ type: "spki",+});++const chunks = [];+process.stdin.on("data", (chunk) => chunks.push(chunk));+process.stdin.on("end", () => {+ const message = Buffer.concat(chunks);+ process.stdout.write(+ JSON.stringify({+ public_key_base64: publicDer.subarray(-32).toString("base64"),+ signature: crypto.sign(null, message, privateKey).toString("base64"),+ }),+ );+});diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/fixtures/extension_catalog/signed-catalog.golden.json b/libs/cua-driver/rust/crates/cua-driver/tests/fixtures/extension_catalog/signed-catalog.golden.jsonnew file mode 100644index 0000000000..747f3cb646--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver/tests/fixtures/extension_catalog/signed-catalog.golden.json@@ -0,0 +1,28 @@+{+ "producer": "Python json.dumps(separators) + Node crypto.sign",+ "payload": {+ "schema_version": 1,+ "catalog_version": 7,+ "expires_unix": 4102444800,+ "publisher_id": "cua-review-only",+ "publisher_name": "Cua REVIEW ONLY",+ "key_id": "review-only-build-override",+ "extension_id": "cua-perception",+ "version": "0.1.0",+ "target": "aarch64-apple-darwin",+ "archive": "cua-perception-0.1.0-aarch64-apple-darwin.tar.gz",+ "archive_size": 12345,+ "archive_sha256": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",+ "manifest_sha256": "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789",+ "license": "AGPL-3.0-or-later",+ "source": "https://github.com/trycua/cua",+ "corresponding_source_uri": "https://github.com/trycua/cua/tree/golden",+ "corresponding_source_revision": "golden-revision",+ "provenance": "Python canonical JSON plus Node Ed25519 golden vector",+ "next_key": null+ },+ "canonical_payload": "{\"schema_version\":1,\"catalog_version\":7,\"expires_unix\":4102444800,\"publisher_id\":\"cua-review-only\",\"publisher_name\":\"Cua REVIEW ONLY\",\"key_id\":\"review-only-build-override\",\"extension_id\":\"cua-perception\",\"version\":\"0.1.0\",\"target\":\"aarch64-apple-darwin\",\"archive\":\"cua-perception-0.1.0-aarch64-apple-darwin.tar.gz\",\"archive_size\":12345,\"archive_sha256\":\"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef\",\"manifest_sha256\":\"abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789\",\"license\":\"AGPL-3.0-or-later\",\"source\":\"https://github.com/trycua/cua\",\"corresponding_source_uri\":\"https://github.com/trycua/cua/tree/golden\",\"corresponding_source_revision\":\"golden-revision\",\"provenance\":\"Python canonical JSON plus Node Ed25519 golden vector\",\"next_key\":null}",+ "public_key_base64": "11qYAYKxCrfVS/7TyWQHOg7hcvPapiMlrwIaaPcHURo=",+ "signature_algorithm": "ed25519",+ "signature": "64Zhwa3X7KlzZQ5w1F4Ju9SOqh8NfSKxuyKnx3wb6MsQOAKmHSC/m1eqw5NzkS76RlWmBU5gG4cigxu1CK9hAQ=="+}diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/fixtures/extension_catalog/verify_golden.py b/libs/cua-driver/rust/crates/cua-driver/tests/fixtures/extension_catalog/verify_golden.pynew file mode 100644index 0000000000..ceeefda4ae--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver/tests/fixtures/extension_catalog/verify_golden.py@@ -0,0 +1,25 @@+#!/usr/bin/env python3+"""Reproduce the committed catalog bytes with Python and sign them with Node."""++import base64+import json+import pathlib+import subprocess++HERE = pathlib.Path(__file__).resolve().parent+GOLDEN = json.loads((HERE / "signed-catalog.golden.json").read_text())+CANONICAL = json.dumps(GOLDEN["payload"], separators=(",", ":")).encode()++assert CANONICAL.decode() == GOLDEN["canonical_payload"]+signed = json.loads(+ subprocess.run(+ ["node", str(HERE / "sign_catalog.js")],+ input=CANONICAL,+ check=True,+ capture_output=True,+ ).stdout+)+assert signed["public_key_base64"] == GOLDEN["public_key_base64"]+assert signed["signature"] == GOLDEN["signature"]+assert len(base64.b64decode(signed["public_key_base64"])) == 32+print("Python canonical catalog and Node Ed25519 signature match the Rust golden vector")diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/harness_appkit_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/harness_appkit_test.rsindex b83ba54510..67a9e3c11f 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/harness_appkit_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/harness_appkit_test.rs@@ -1271,8 +1271,102 @@ fn harness_appkit_counter_px_background() {Targeting::Px,DriverRoute::MacosAxAction,|pid, wid, driver| {+ let config = driver.call(+ "set_config",+ serde_json::json!({"max_image_dimension": 200}),+ );+ assert!(+ !config.is_error(),+ "small capture config: {}",+ config.text()+ );let pre = snapshot_elements(driver, pid, wid);let (x, y, width, height) = element_pixel_frame(&pre, "btn-increment");+ let zoom = driver.call(+ "zoom",+ serde_json::json!({+ "pid": pid as i64, "window_id": wid,+ "x1": x, "y1": y, "x2": x + width, "y2": y + height+ }),+ );+ assert!(+ !zoom.is_error(),+ "create owned zoom context: {}",+ zoom.text()+ );+ let small_width = pre.structured()["screenshot_width"]+ .as_u64()+ .expect("small screenshot width");+ let mut observer = driver+ .spawn_peer_unrecorded()+ .expect("start independent capture client on the same daemon");+ let config = observer.call("set_config", serde_json::json!({"max_image_dimension": 0}));+ assert!(+ !config.is_error(),+ "native capture config: {}",+ config.text()+ );+ let other = snapshot_elements(&mut observer, pid, wid);+ assert!(+ other.structured()["screenshot_width"]+ .as_u64()+ .expect("native screenshot width")+ > small_width+ );+ for (tool, args) in [+ (+ "double_click",+ serde_json::json!({"pid":pid as i64,"window_id":wid,"x":x,"y":y,"delivery_mode":"foreground"}),+ ),+ (+ "right_click",+ serde_json::json!({"pid":pid as i64,"window_id":wid,"x":x,"y":y,"delivery_mode":"foreground"}),+ ),+ (+ "scroll",+ serde_json::json!({"pid":pid as i64,"window_id":wid,"x":x,"y":y,"direction":"down","amount":1,"delivery_mode":"foreground"}),+ ),+ (+ "drag",+ serde_json::json!({"pid":pid as i64,"window_id":wid,"from_x":x,"from_y":y,"to_x":x+1.0,"to_y":y+1.0,"duration_ms":0,"steps":1,"delivery_mode":"foreground"}),+ ),+ ] {+ let stale = driver.call(tool, args);+ assert_eq!(+ stale.structured()["code"],+ "screenshot_context_missing",+ "{tool} must refuse another client's screenshot transform"+ );+ }+ for (tool, args) in [+ (+ "click",+ serde_json::json!({"pid":pid as i64,"window_id":wid,"x":1.0,"y":1.0,"from_zoom":true,"delivery_mode":"foreground"}),+ ),+ (+ "drag",+ serde_json::json!({"pid":pid as i64,"window_id":wid,"from_x":1.0,"from_y":1.0,"to_x":2.0,"to_y":2.0,"from_zoom":true,"duration_ms":0,"steps":1,"delivery_mode":"foreground"}),+ ),+ ] {+ let stale = driver.call(tool, args);+ assert_eq!(+ stale.structured()["code"],+ "zoom_context_missing",+ "{tool} must refuse a zoom bound to the replaced snapshot"+ );+ }+ let stale = driver.call(+ "click",+ serde_json::json!({+ "pid": pid as i64, "window_id": wid,+ "x": x + width / 2.0, "y": y + height / 2.0,+ "delivery_mode": "background"+ }),+ );+ assert_eq!(stale.structured()["code"], "screenshot_context_missing");++ let refreshed = snapshot_elements(driver, pid, wid);+ let (x, y, width, height) = element_pixel_frame(&refreshed, "btn-increment");let response = driver.call("click",serde_json::json!({diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/harness_gtk3_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/harness_gtk3_test.rsindex 03cf5d6d9a..25d7bc98f2 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/harness_gtk3_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/harness_gtk3_test.rs@@ -650,7 +650,122 @@ fn invoke_operation(Delivery::Foreground => "foreground",Delivery::NotApplicable => unreachable!("catalog operations require delivery"),};- let pre = snapshot(driver, pid, window_id);+ let resize_probe = !expect_refusal+ && matches!(+ row.operation,+ Operation::PxClick {+ button: "left",+ count: 1,+ ..+ }+ );+ if resize_probe {+ let config = driver.call(+ "set_config",+ serde_json::json!({"max_image_dimension": 200}),+ );+ assert!(+ !config.is_error(),+ "small capture config: {}",+ config.text()+ );+ }+ let mut pre = snapshot(driver, pid, window_id);+ let _observer = if let Operation::PxClick { target, .. } = row.operation {+ resize_probe.then(|| {+ let small_width = pre.structured()["screenshot_width"]+ .as_u64()+ .expect("small screenshot width");+ let (x, y, width, height) = element_rect(driver, pid, window_id, &pre, target);+ let zoom = driver.call(+ "zoom",+ serde_json::json!({+ "pid": pid as i64, "window_id": window_id,+ "x1": x, "y1": y, "x2": x + width, "y2": y + height+ }),+ );+ assert!(!zoom.is_error(), "create owned zoom context: {}", zoom.text());+ let mut observer = driver+ .spawn_peer_unrecorded()+ .expect("start independent capture client on the same daemon");+ let config = observer.call("set_config", serde_json::json!({"max_image_dimension": 0}));+ assert!(+ !config.is_error(),+ "native capture config: {}",+ config.text()+ );+ let other = snapshot(&mut observer, pid, window_id);+ assert!(+ other.structured()["screenshot_width"]+ .as_u64()+ .expect("native screenshot width")+ > small_width+ );+ for (tool, args) in [+ (+ "double_click",+ serde_json::json!({"pid":pid as i64,"window_id":window_id,"x":x,"y":y,"delivery_mode":"foreground"}),+ ),+ (+ "right_click",+ serde_json::json!({"pid":pid as i64,"window_id":window_id,"x":x,"y":y,"delivery_mode":"foreground"}),+ ),+ (+ "scroll",+ serde_json::json!({"pid":pid as i64,"window_id":window_id,"x":x,"y":y,"direction":"down","amount":1,"delivery_mode":"foreground"}),+ ),+ (+ "drag",+ serde_json::json!({"pid":pid as i64,"window_id":window_id,"from_x":x,"from_y":y,"to_x":x+1.0,"to_y":y+1.0,"duration_ms":0,"steps":1,"delivery_mode":"foreground"}),+ ),+ (+ "mouse_button_down",+ serde_json::json!({"pid":pid as i64,"window_id":window_id,"x":x,"y":y}),+ ),+ ] {+ let stale = driver.call(tool, args);+ assert_eq!(+ stale.structured()["code"],+ "screenshot_context_missing",+ "{tool} must refuse another client's screenshot transform"+ );+ }+ for (tool, args) in [+ (+ "click",+ serde_json::json!({"pid":pid as i64,"window_id":window_id,"x":1.0,"y":1.0,"from_zoom":true,"delivery_mode":"foreground"}),+ ),+ (+ "drag",+ serde_json::json!({"pid":pid as i64,"window_id":window_id,"from_x":1.0,"from_y":1.0,"to_x":2.0,"to_y":2.0,"from_zoom":true,"duration_ms":0,"steps":1,"delivery_mode":"foreground"}),+ ),+ (+ "mouse_button_down",+ serde_json::json!({"pid":pid as i64,"window_id":window_id,"x":1.0,"y":1.0,"from_zoom":true}),+ ),+ ] {+ let stale = driver.call(tool, args);+ assert_eq!(+ stale.structured()["code"],+ "zoom_context_missing",+ "{tool} must refuse a zoom bound to the replaced snapshot"+ );+ }+ let stale = driver.call(+ "click",+ serde_json::json!({+ "pid": pid as i64, "window_id": window_id,+ "x": x + width / 2.0, "y": y + height / 2.0,+ "delivery_mode": mode+ }),+ );+ assert_eq!(stale.structured()["code"], "screenshot_context_missing");+ pre = snapshot(driver, pid, window_id);+ observer+ })+ } else {+ None+ };assert!(!ax::looks_empty(pre.tree_text()),"required GTK3 AT-SPI tree is empty"diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/harness_wpf_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/harness_wpf_test.rsindex 31e9da2cd0..df945cd3ba 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/harness_wpf_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/harness_wpf_test.rs@@ -657,7 +657,88 @@ fn harness_wpf_left_click_px_background() {.expect("main window");wait_for_fixture_file_text(&state_path, "lbl-click-count", "clicks=0");+ let config = driver.call(+ "set_config",+ serde_json::json!({"max_image_dimension": 200}),+ );+ assert!(+ !config.is_error(),+ "small capture config: {}",+ config.text()+ );let bounds = window_bounds(&mut driver, pid, wid);+ let ready_state = snapshot(&mut driver, pid, wid);+ let (x, y) = pixel_center(&ready_state, "border-click-target", bounds);+ let zoom = driver.call(+ "zoom",+ serde_json::json!({+ "pid": pid as i64, "window_id": wid,+ "x1": x - 5.0, "y1": y - 5.0, "x2": x + 5.0, "y2": y + 5.0+ }),+ );+ assert!(+ !zoom.is_error(),+ "create owned zoom context: {}",+ zoom.text()+ );+ let small_width = ready_state.structured()["screenshot_width"]+ .as_u64()+ .expect("small screenshot width");+ let mut observer = driver+ .spawn_peer_unrecorded()+ .expect("start independent capture client on the same daemon");+ let config = observer.call("set_config", serde_json::json!({"max_image_dimension": 0}));+ assert!(+ !config.is_error(),+ "native capture config: {}",+ config.text()+ );+ let other = snapshot(&mut observer, pid, wid);+ assert!(+ other.structured()["screenshot_width"]+ .as_u64()+ .expect("native screenshot width")+ > small_width+ );+ for (tool, args) in [+ (+ "double_click",+ serde_json::json!({"pid":pid as i64,"window_id":wid,"x":x,"y":y,"delivery_mode":"foreground"}),+ ),+ (+ "right_click",+ serde_json::json!({"pid":pid as i64,"window_id":wid,"x":x,"y":y,"delivery_mode":"foreground"}),+ ),+ (+ "drag",+ serde_json::json!({"pid":pid as i64,"window_id":wid,"from_x":x,"from_y":y,"to_x":x+1.0,"to_y":y+1.0,"duration_ms":0,"steps":1,"delivery_mode":"foreground"}),+ ),+ ] {+ let stale = driver.call(tool, args);+ assert_eq!(stale.structured()["code"], "screenshot_context_missing");+ }+ for (tool, args) in [+ (+ "click",+ serde_json::json!({"pid":pid as i64,"window_id":wid,"x":1.0,"y":1.0,"from_zoom":true,"delivery_mode":"foreground"}),+ ),+ (+ "drag",+ serde_json::json!({"pid":pid as i64,"window_id":wid,"from_x":1.0,"from_y":1.0,"to_x":2.0,"to_y":2.0,"from_zoom":true,"duration_ms":0,"steps":1,"delivery_mode":"foreground"}),+ ),+ ] {+ let stale = driver.call(tool, args);+ assert_eq!(stale.structured()["code"], "zoom_context_missing");+ }+ let stale = driver.call(+ "click",+ serde_json::json!({+ "pid": pid as i64, "window_id": wid,+ "x": x, "y": y, "delivery_mode": "foreground"+ }),+ );+ assert_eq!(stale.structured()["code"], "screenshot_context_missing");+let ready_state = snapshot(&mut driver, pid, wid);let (x, y) = pixel_center(&ready_state, "border-click-target", bounds);let geometry_probe = driver.call(diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/perception_cli_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/perception_cli_test.rsnew file mode 100644index 0000000000..a5227cd987--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver/tests/perception_cli_test.rs@@ -0,0 +1,536 @@+use std::fs;+use std::io::Cursor;+use std::path::{Path, PathBuf};+use std::process::{Command, Output};++use flate2::{write::GzEncoder, Compression};+use image::{DynamicImage, ImageFormat, Rgba, RgbaImage};+use serde_json::json;+use sha2::{Digest, Sha256};+use tempfile::TempDir;++fn run(home: &std::path::Path, args: &[&str]) -> Output {+ Command::new(env!("CARGO_BIN_EXE_cua-driver"))+ .args(args)+ .env("CUA_DRIVER_RS_HOME", home)+ .env("CUA_DRIVER_CLI_TELEMETRY_CHILD", "1")+ .output()+ .expect("run cua-driver perception command")+}++fn write_fixture(temp: &TempDir) -> (String, String) {+ let image_path = temp.path().join("input.png");+ let mut bytes = Vec::new();+ DynamicImage::ImageRgba8(RgbaImage::from_pixel(2, 1, Rgba([1, 2, 3, 255])))+ .write_to(&mut std::io::Cursor::new(&mut bytes), ImageFormat::Png)+ .unwrap();+ fs::write(&image_path, bytes).unwrap();++ let capture_path = temp.path().join("capture.json");+ fs::write(+ &capture_path,+ serde_json::to_vec(&json!({+ "source": {"kind": "window", "pid": 123, "window_id": 456},+ "snapshot_id": "snapshot-local-fixture"+ }))+ .unwrap(),+ )+ .unwrap();+ (+ image_path.to_string_lossy().into_owned(),+ capture_path.to_string_lossy().into_owned(),+ )+}++fn parse_error(output: &Output) -> serde_json::Value {+ assert!(!output.status.success());+ assert!(+ output.stderr.is_empty(),+ "stderr was not empty: {:?}",+ output.stderr+ );+ let value: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(value["ok"], false);+ value+}++fn run_parse(home: &std::path::Path, image: &str, capture: &str) -> Output {+ run(+ home,+ &[+ "perception",+ "parse",+ "--image",+ image,+ "--capture",+ capture,+ "--json",+ ],+ )+}++fn current_target() -> String {+ let suffix = if cfg!(target_os = "macos") {+ "apple-darwin"+ } else if cfg!(all(target_os = "windows", target_env = "msvc")) {+ "pc-windows-msvc"+ } else if cfg!(all(target_os = "linux", target_env = "musl")) {+ "unknown-linux-musl"+ } else if cfg!(all(target_os = "linux", target_env = "gnu")) {+ "unknown-linux-gnu"+ } else {+ panic!("unsupported perception CLI test target")+ };+ format!("{}-{suffix}", std::env::consts::ARCH)+}++fn sha256(bytes: &[u8]) -> String {+ format!("{:x}", Sha256::digest(bytes))+}++fn append(builder: &mut tar::Builder<GzEncoder<fs::File>>, path: &str, bytes: &[u8]) {+ let mut header = tar::Header::new_gnu();+ header.set_size(bytes.len() as u64);+ header.set_mode(0o755);+ header.set_cksum();+ builder+ .append_data(&mut header, path, Cursor::new(bytes))+ .unwrap();+}++fn compile_fixture_worker(directory: &Path) -> PathBuf {+ let source = directory.join("perception-fixture-worker.rs");+ fs::write(+ &source,+ r###"+use std::io::{self, Read, Write};++fn read_frame() -> String {+ let mut length = [0_u8; 4];+ io::stdin().read_exact(&mut length).unwrap();+ let mut payload = vec![0_u8; u32::from_be_bytes(length) as usize];+ io::stdin().read_exact(&mut payload).unwrap();+ String::from_utf8(payload).unwrap()+}++fn field(payload: &str, name: &str) -> String {+ let marker = format!("\"{name}\":\"");+ let tail = &payload[payload.find(&marker).unwrap() + marker.len()..];+ tail[..tail.find('"').unwrap()].to_owned()+}++fn write_frame(payload: &str) {+ let bytes = payload.as_bytes();+ let mut stdout = io::stdout().lock();+ stdout.write_all(&(bytes.len() as u32).to_be_bytes()).unwrap();+ stdout.write_all(bytes).unwrap();+ stdout.flush().unwrap();+}++fn argument(name: &str) -> String {+ let args = std::env::args().collect::<Vec<_>>();+ let index = args.iter().position(|value| value == name).unwrap();+ args[index + 1].clone()+}++fn main() {+ let extension_id = argument("--extension-id");+ let extension_version = argument("--extension-version");+ let identity = format!(+ r#"{{"extension":{{"id":"{}","version":"{}"}},"backend":"deterministic_fixture","fixture_sha256":"{}"}}"#,+ extension_id,+ extension_version,+ "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"+ );++ let health = read_frame();+ write_frame(&format!(+ r#"{{"protocol":"cua-perception/1","request_id":"{}","status":"ok","result":{{"ready":true,"protocol":"cua-perception/1","identity":{}}}}}"#,+ field(&health, "request_id"), identity+ ));++ let parse = read_frame();+ write_frame(&format!(+ r#"{{"protocol":"cua-perception/1","request_id":"{}","status":"ok","result":{{"runtime":"fixture_only","identity":{},"regions":[{{"id":"fixture-text","kind":"text","bounds":{{"x":0,"y":0,"width":2,"height":1}},"text":"fixture","confidence":0.99,"interactive":false,"reading_order":0}}]}}}}"#,+ field(&parse, "request_id"), identity+ ));+}+"###,+ )+ .unwrap();++ let worker = directory.join(if cfg!(windows) {+ "cua-perception.exe"+ } else {+ "cua-perception"+ });+ let rustc = std::env::var_os("RUSTC").unwrap_or_else(|| "rustc".into());+ let mut command = Command::new(rustc);+ command.arg(&source).arg("--edition=2021");+ if cfg!(target_os = "linux") {+ // Linux containment cannot expose a host-specific dynamic loader to an installed worker.+ command.args(["-C", "target-feature=+crt-static"]);+ if let Some(path) = std::env::var_os("CUA_TEST_GLIBC_STATIC_LIB") {+ let mut native_path = std::ffi::OsString::from("native=");+ native_path.push(path);+ command.arg("-L").arg(native_path);+ }+ }+ let output = command+ .arg("-o")+ .arg(&worker)+ .output()+ .expect("compile deterministic perception fixture worker");+ assert!(+ output.status.success(),+ "fixture worker compilation failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ worker+}++fn fixture_extension_archive(directory: &Path) -> PathBuf {+ let version = "1.0.0";+ let worker_path = compile_fixture_worker(directory);+ let worker = fs::read(&worker_path).unwrap();+ let worker_name = worker_path.file_name().unwrap().to_str().unwrap();+ let entrypoint = format!("bin/{worker_name}");+ let runtime_name = if cfg!(target_os = "windows") {+ "onnxruntime.dll"+ } else if cfg!(target_os = "macos") {+ "libonnxruntime.dylib"+ } else {+ "libonnxruntime.so"+ };+ let runtime = b"fixture-runtime".to_vec();+ let model = b"fixture-model".to_vec();+ let dictionary = b"fixture-dictionary".to_vec();+ let model_manifest = b"{}".to_vec();+ let notice = b"deterministic fixture notice\n".to_vec();+ let model_license = b"deterministic fixture model license\n".to_vec();+ let source = b"deterministic fixture source\n".to_vec();+ let contract = serde_json::to_vec_pretty(&json!({+ "$schema": "runtime-contract.schema.json",+ "schemaVersion": 1,+ "target": current_target(),+ "protocolVersion": 1,+ "worker": {"name": worker_name, "sha256": sha256(&worker)},+ "runtime": {"name": runtime_name, "sha256": sha256(&runtime)},+ "modelManifest": {"name": "model-manifest.json", "sha256": sha256(&model_manifest)},+ "models": [+ {"name": "icon.onnx", "role": "icon-detect", "sha256": sha256(&model)},+ {"name": "ocr-det.onnx", "role": "ocr-detect", "sha256": sha256(&model)},+ {"name": "ocr-rec.onnx", "role": "ocr-recognize", "sha256": sha256(&model)}+ ],+ "dictionary": {+ "name": "dictionary.txt",+ "role": "ocr-dictionary",+ "sha256": sha256(&dictionary)+ },+ "rejectMismatch": true+ }))+ .unwrap();+ let files = vec![+ (entrypoint.clone(), worker, true),+ (+ "models/model-manifest.json".to_owned(),+ model_manifest,+ false,+ ),+ (format!("runtime/{runtime_name}"), runtime, false),+ ("models/icon.onnx".to_owned(), model.clone(), false),+ ("models/ocr-det.onnx".to_owned(), model.clone(), false),+ ("models/ocr-rec.onnx".to_owned(), model, false),+ ("models/dictionary.txt".to_owned(), dictionary, false),+ ("metadata/runtime-contract.json".to_owned(), contract, false),+ ("LICENSES/NOTICE.txt".to_owned(), notice, false),+ ("LICENSES/model.txt".to_owned(), model_license, false),+ ("SOURCE/fixture.txt".to_owned(), source, false),+ ];+ let file_json = files+ .iter()+ .map(|(path, bytes, executable)| {+ json!({"path": path, "sha256": sha256(bytes), "executable": executable})+ })+ .collect::<Vec<_>>();+ let file_hash = |path: &str| {+ let (_, bytes, _) = files+ .iter()+ .find(|(candidate, _, _)| candidate == path)+ .unwrap();+ sha256(bytes)+ };+ let manifest = serde_json::to_vec_pretty(&json!({+ "schema_version": 1,+ "id": "cua-perception",+ "version": version,+ "driver_version": format!("={}", env!("CARGO_PKG_VERSION")),+ "protocol_version": 1,+ "target": current_target(),+ "entrypoint": entrypoint,+ "files": file_json,+ "models": [{+ "path": "models/icon.onnx",+ "revision": "fixture-v1",+ "original_sha256": file_hash("models/icon.onnx"),+ "conversion_sha256": file_hash("models/icon.onnx"),+ "license_file": {"path": "LICENSES/model.txt", "sha256": file_hash("LICENSES/model.txt")}+ }],+ "components": [{+ "name": "cua-perception-fixture",+ "version": version,+ "license": "Apache-2.0",+ "notice": "deterministic CLI integration fixture",+ "source_uri": "https://github.com/trycua/cua",+ "source_revision": "integration-fixture",+ "notice_file": {"path": "LICENSES/NOTICE.txt", "sha256": file_hash("LICENSES/NOTICE.txt")}+ }],+ "corresponding_source_file": {"path": "SOURCE/fixture.txt", "sha256": file_hash("SOURCE/fixture.txt")},+ "license": "Apache-2.0",+ "source": "https://github.com/trycua/cua",+ "corresponding_source_uri": "https://github.com/trycua/cua",+ "corresponding_source_revision": "integration-fixture",+ "provenance": "deterministic CLI integration fixture",+ "health_args": [],+ "self_test_args": []+ }))+ .unwrap();++ let archive = directory.join("cua-perception-fixture.tar.gz");+ let encoder = GzEncoder::new(fs::File::create(&archive).unwrap(), Compression::default());+ let mut builder = tar::Builder::new(encoder);+ append(&mut builder, "extension.json", &manifest);+ for (path, bytes, _) in files {+ append(&mut builder, &path, &bytes);+ }+ builder.finish().unwrap();+ archive+}++#[test]+fn installed_fixture_parses_local_input_without_action_authority() {+ let temp = TempDir::new().unwrap();+ let archive = fixture_extension_archive(temp.path());+ let install = run(+ temp.path(),+ &[+ "extension",+ "install",+ "cua-perception",+ "--archive",+ archive.to_str().unwrap(),+ "--allow-unsigned-local",+ ],+ );+ assert!(+ install.status.success(),+ "extension install failed: {}",+ String::from_utf8_lossy(&install.stderr)+ );++ let (image, capture) = write_fixture(&temp);+ let output = run_parse(temp.path(), &image, &capture);+ assert!(+ output.status.success(),+ "perception parse failed: stdout={} stderr={}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );+ assert!(output.stderr.is_empty());+ let value: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();++ assert_eq!(value["local_input"]["action_authority"], "none");+ assert_eq!(value["local_input"]["action_eligible"], false);+ assert_eq!(+ value["local_input"]["snapshot_id"],+ "snapshot-local-fixture"+ );+ let capture_id = value["capture"]["capture_id"].as_str().unwrap();+ assert!(capture_id.starts_with("local_png_"));+ assert!(!capture_id.starts_with("capture_"));+ assert_eq!(value["capture"]["source"]["kind"], "window");+ assert_eq!(value["capture"]["source"]["pid"], 123);+ assert_eq!(value["capture"]["source"]["window_id"], 456);+ assert_eq!(value["capture"]["screenshot"]["width"], 2);+ assert_eq!(value["capture"]["screenshot"]["height"], 1);+ assert_eq!(value["capture"]["screenshot"]["mime_type"], "image/png");+ assert_eq!(+ value["capture"]["screenshot"]["sha256"],+ value["local_input"]["sha256"]+ );+ assert!(value["capture"]["screenshot"]["reference"]+ .as_str()+ .unwrap()+ .starts_with("local-png-sha256:"));+ assert_eq!(value["parser"]["extension_id"], "cua-perception");+ assert_eq!(value["parser"]["extension_version"], "1.0.0");+ assert_eq!(value["parser"]["backend"], "deterministic_fixture");+ assert_eq!(value["parser"]["runtime"], "fixture_only");+ assert_eq!(value["regions"][0]["id"], "fixture-text");+ assert_eq!(value["regions"][0]["kind"], "text");+ assert_eq!(value["regions"][0]["text"], "fixture");+ assert_eq!(+ value["regions"][0]["bounds"],+ json!({"x": 0, "y": 0, "width": 2, "height": 1})+ );+}++#[test]+fn help_documents_local_parse_as_non_actionable() {+ let temp = TempDir::new().unwrap();+ let output = run(temp.path(), &["--help"]);+ assert!(output.status.success());+ let stdout = String::from_utf8_lossy(&output.stdout);+ assert!(stdout.contains("perception parse --image <png> --capture <capture.json> --json"));+ assert!(stdout.contains("no Driver action authority"));++ let manifest = run(temp.path(), &["manifest"]);+ assert!(manifest.status.success());+ let manifest_json: serde_json::Value = serde_json::from_slice(&manifest.stdout).unwrap();+ let perception = manifest_json["subcommands"]+ .as_array()+ .unwrap()+ .iter()+ .find(|command| command["name"] == "perception")+ .expect("manifest perception command");+ assert!(perception["description"]+ .as_str()+ .unwrap()+ .contains("without creating Driver capture or action authority"));++ let docs = run(temp.path(), &["dump-docs", "--type", "commands"]);+ assert!(docs.status.success());+ let docs_text = String::from_utf8_lossy(&docs.stdout);+ assert!(docs_text.contains("local-input mode does not create a Driver capture"));+}++#[test]+fn valid_local_input_without_extension_returns_not_installed() {+ let temp = TempDir::new().unwrap();+ let (image, capture) = write_fixture(&temp);+ let output = run_parse(temp.path(), &image, &capture);+ assert_eq!(parse_error(&output)["error"]["code"], "not_installed");+ assert!(!temp.path().join("extensions").exists());+}++#[test]+fn invalid_metadata_and_png_fail_before_worker_launch() {+ let temp = TempDir::new().unwrap();+ let (image, capture) = write_fixture(&temp);+ fs::write(+ &capture,+ br#"{"source":{"kind":"window","pid":0,"window_id":1}}"#,+ )+ .unwrap();+ let invalid_metadata = run_parse(temp.path(), &image, &capture);+ assert_eq!(+ parse_error(&invalid_metadata)["error"]["code"],+ "invalid_capture_metadata"+ );++ let (_, capture) = write_fixture(&temp);+ fs::write(&image, b"not a png").unwrap();+ let invalid_png = run_parse(temp.path(), &image, &capture);+ assert_eq!(parse_error(&invalid_png)["error"]["code"], "invalid_png");+}++#[test]+fn invalid_installed_extension_fails_as_artifact_invalid() {+ let temp = TempDir::new().unwrap();+ let (image, capture) = write_fixture(&temp);+ let extension = temp.path().join("extensions/cua-perception");+ fs::create_dir_all(&extension).unwrap();+ fs::write(extension.join("active.json"), b"not json").unwrap();+ let output = run_parse(temp.path(), &image, &capture);+ assert_eq!(parse_error(&output)["error"]["code"], "artifact_invalid");+}++#[test]+fn parser_rejects_missing_json_or_paths() {+ let temp = TempDir::new().unwrap();+ for args in [+ vec!["perception", "parse", "--json"],+ vec!["perception", "parse", "--image", "input.png", "--json"],+ vec![+ "perception",+ "parse",+ "--image",+ "input.png",+ "--capture",+ "capture.json",+ ],+ ] {+ assert!(+ !run(temp.path(), &args).status.success(),+ "accepted {args:?}"+ );+ }+}++#[test]+fn argument_failure_has_an_exact_json_envelope() {+ let temp = TempDir::new().unwrap();+ let output = run(temp.path(), &["perception", "parse", "--json"]);+ assert!(!output.status.success());+ assert!(output.stderr.is_empty());+ assert_eq!(+ String::from_utf8(output.stdout).unwrap(),+ "{\"ok\":false,\"error\":{\"code\":\"invalid_arguments\",\"message\":\"perception parse requires --image <png>\",\"retryable\":false}}\n"+ );+}++#[test]+fn rejects_unknown_nested_source_fields_and_malformed_timestamp() {+ let temp = TempDir::new().unwrap();+ let (image, capture) = write_fixture(&temp);+ fs::write(+ &capture,+ br#"{"source":{"kind":"window","pid":123,"window_id":456,"extra":true}}"#,+ )+ .unwrap();+ let unknown = run_parse(temp.path(), &image, &capture);+ assert_eq!(+ parse_error(&unknown)["error"]["code"],+ "invalid_capture_metadata"+ );++ fs::write(+ &capture,+ br#"{"source":{"kind":"window","pid":123,"window_id":456},"captured_at":"yesterday"}"#,+ )+ .unwrap();+ let timestamp = run_parse(temp.path(), &image, &capture);+ let error = parse_error(×tamp);+ assert_eq!(error["error"]["code"], "invalid_capture_metadata");+ assert_eq!(+ error["error"]["message"],+ "captured_at must be an RFC3339 timestamp"+ );+}++#[cfg(unix)]+#[test]+fn rejects_symlink_and_fifo_inputs_without_blocking() {+ use std::ffi::CString;+ use std::os::unix::ffi::OsStrExt;+ use std::os::unix::fs::symlink;++ let temp = TempDir::new().unwrap();+ let (image, capture) = write_fixture(&temp);+ let image_link = temp.path().join("image-link.png");+ symlink(&image, &image_link).unwrap();+ let symlink_output = run_parse(temp.path(), image_link.to_str().unwrap(), capture.as_str());+ assert_eq!(+ parse_error(&symlink_output)["error"]["code"],+ "input_open_failed"+ );++ let fifo = temp.path().join("capture.fifo");+ let fifo_c = CString::new(fifo.as_os_str().as_bytes()).unwrap();+ assert_eq!(unsafe { libc::mkfifo(fifo_c.as_ptr(), 0o600) }, 0);+ let fifo_output = run_parse(temp.path(), &image, fifo.to_str().unwrap());+ assert_eq!(+ parse_error(&fifo_output)["error"]["code"],+ "input_not_regular_file"+ );+}diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/support/appkit_snapshot_publication.rs b/libs/cua-driver/rust/crates/cua-driver/tests/support/appkit_snapshot_publication.rsindex d65b14ac3d..e7e6d502a2 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/support/appkit_snapshot_publication.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/support/appkit_snapshot_publication.rs@@ -49,7 +49,7 @@ struct PendingCapture<R> {bytes: Vec<u8>,}-impl PendingCapture<ToolResponse> {+impl PendingCapture<(ToolResponse, McpDriver)> {fn start(directory: &Path, pid: u32, window: u64, response_path: PathBuf) -> Self {let path = directory.join("pending.png.pipe");let reader = fifo_reader(&path);@@ -73,7 +73,7 @@ impl PendingCapture<ToolResponse> {serde_json::to_vec_pretty(&response.raw).unwrap(),).unwrap();- response+ (response, driver)});Self {reader: Some(reader),@@ -312,7 +312,7 @@ fn harness_appkit_pending_snapshot_cannot_retarget_token() {serde_json::to_vec_pretty(&after_old).unwrap(),).unwrap();- let second = capture.finish(&output.join("snapshot-pending.png"));+ let (second, _publication_driver) = capture.finish(&output.join("snapshot-pending.png"));assert!(!second.is_error(),"replacement native snapshot: {}",diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/visual_transport_contract_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/visual_transport_contract_test.rsnew file mode 100644index 0000000000..756b0841be--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver/tests/visual_transport_contract_test.rs@@ -0,0 +1,83 @@+//! Callable visual perception must advertise and preserve one contract across+//! the live MCP inventory and the CLI/MCP invocation transports.++#![cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]++use cua_driver_testkit::{CliDriver, Driver, McpDriver, RawDriver};++fn cargo_built_driver() -> std::path::PathBuf {+ // Referencing Cargo's binary variable creates a build dependency on the+ // executable. `--all-targets` alone only guarantees the binary test+ // harness, so a restored target directory could otherwise supply an old+ // standalone `target/debug/cua-driver`.+ std::path::PathBuf::from(env!("CARGO_BIN_EXE_cua-driver"))+}++#[test]+fn visual_tool_inventory_advertises_the_versioned_contract() {+ let Some(mut driver) = RawDriver::spawn_with_binary(cargo_built_driver()) else {+ return;+ };+ driver.send(&serde_json::json!({+ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}+ }));+ driver.recv();+ driver.send(&serde_json::json!({+ "jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}+ }));+ let response = driver.recv();+ let tool = response["result"]["tools"]+ .as_array()+ .unwrap()+ .iter()+ .find(|tool| tool["name"] == "parse_visual_regions")+ .expect("parse_visual_regions in tools/list");++ assert_eq!(+ tool["inputSchema"]["required"],+ serde_json::json!(["capture_id"])+ );+ assert_eq!(+ tool["outputSchema"]["anyOf"][0]["properties"]["schema"]["const"],+ "cua.visual_regions_v1"+ );+ assert_eq!(tool["annotations"]["readOnlyHint"], true);+ assert!(tool["capabilities"]+ .as_array()+ .is_some_and(|values| values.iter().any(|value| value == "visual.regions.parse")));++ let fixture: serde_json::Value = serde_json::from_str(include_str!(+ "../../cua-driver-contract/tests/fixtures/parse-visual-regions-output-full-v1.json"+ ))+ .unwrap();+ let validator =+ jsonschema::validator_for(&tool["outputSchema"]).expect("visual output schema compiles");+ assert!(+ validator.is_valid(&fixture),+ "cua.visual_regions_v1 fixture must match the advertised MCP schema"+ );+}++#[test]+fn cli_and_mcp_preserve_the_same_visual_error_dto() {+ let arguments = serde_json::json!({"capture_id": "capture-does-not-exist"});+ let binary = cargo_built_driver();+ let mut cli = CliDriver::with_binary(binary.clone());+ if !cli.available() {+ return;+ }+ let cli_response = cli.call("parse_visual_regions", arguments.clone());+ let Some(mut mcp) = McpDriver::spawn_with_binary(binary) else {+ return;+ };+ let mcp_response = mcp.call("parse_visual_regions", arguments);++ assert!(cli_response.is_error());+ assert!(mcp_response.is_error());+ assert_eq!(cli_response.structured(), mcp_response.structured());+ assert_eq!(cli_response.structured()["code"], "capture_not_found");+ assert_eq!(cli_response.structured()["retryable"], false);+ let error: cua_driver_contract::VisualParseError =+ serde_json::from_value(cli_response.structured().clone()).unwrap();+ error.validate().unwrap();+}diff --git a/libs/cua-driver/rust/crates/cua-perception/CHANGELOG.md b/libs/cua-driver/rust/crates/cua-perception/CHANGELOG.mdnew file mode 100644index 0000000000..94d2d17e06--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/CHANGELOG.md@@ -0,0 +1,7 @@+# Changelog++All notable changes to Cua Perception release candidates are documented here.++## 0.1.0++- Establish the candidate-only packaging and verification contract.diff --git a/libs/cua-driver/rust/crates/cua-perception/Cargo.toml b/libs/cua-driver/rust/crates/cua-perception/Cargo.tomlnew file mode 100644index 0000000000..42b37ff3bc--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/Cargo.toml@@ -0,0 +1,24 @@+[package]+name = "cua-perception"+version = "0.1.0"+edition.workspace = true+authors.workspace = true+license.workspace = true+repository.workspace = true+publish = false+description = "Offline visual perception worker with manifest-verified ONNX Runtime inference"++[[bin]]+name = "cua-perception"+path = "src/main.rs"++[dependencies]+base64.workspace = true+image.workspace = true+libloading.workspace = true+ort.workspace = true+serde.workspace = true+serde_json.workspace = true+serde_yaml.workspace = true+sha2.workspace = true+thiserror.workspace = truediff --git a/libs/cua-driver/rust/crates/cua-perception/VERSION b/libs/cua-driver/rust/crates/cua-perception/VERSIONnew file mode 100644index 0000000000..6e8bf73aa5--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/VERSION@@ -0,0 +1 @@+0.1.0diff --git a/libs/cua-driver/rust/crates/cua-perception/models/MODEL_LEDGER.md b/libs/cua-driver/rust/crates/cua-perception/models/MODEL_LEDGER.mdnew file mode 100644index 0000000000..7882ca5623--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/models/MODEL_LEDGER.md@@ -0,0 +1,94 @@+# Cua Perception Model Ledger++This directory records the reviewed inputs for an offline worker package. It+does not contain weights. A distributor must place the named files beside a+copy of `model-manifest.template.json`, replace the platform-specific ONNX+Runtime fields, and preserve the listed hashes. The worker performs no network+access and refuses missing or mismatched files before creating a model session.++## OmniParser icon detector++- Source: `microsoft/OmniParser-v2.0` on Hugging Face+- Revision: `6600256cb0f1b07651e3bc86166196307bad7e2d`+- Immutable source URL: `https://huggingface.co/microsoft/OmniParser-v2.0/resolve/6600256cb0f1b07651e3bc86166196307bad7e2d/icon_detect/model.pt`+- Source file: `icon_detect/model.pt`+- Source SHA-256: `dab3d4351ad00b035db829909a4db98354d5a90f6990e4ac00222a9a95d4bf57`+- License recorded for this source model and converted detector artifact:+ AGPL-3.0-only+- Converted file: `omniparser-icon-detect-1280-opset17.onnx`+- Converted SHA-256: `d8a876bf7f9fb73d7da9432904ade7fa78e092e9a91674e5a2806b45562a9ab2`+- Converted size: 80,933,219 bytes+- Input: `images`, float32 `[1,3,1280,1280]`+- Output: `output0`, float32 `[1,5,33600]`, YOLOv8-style `cx,cy,w,h,class_score`++The reviewed conversion used Python 3.12.13, PyTorch 2.8.0, torchvision+0.23.0, ultralytics 8.3.199, ONNX 1.19.0, ONNX Runtime 1.22.1, opset 17,+fixed 1280 input, graph simplification enabled, and model-side NMS disabled.+This records conversion provenance; the Rust worker itself has no Python+runtime dependency. The converted file is an explicitly supplied release+input because the reviewed byte-for-byte export is not published at the+upstream source URL. The assembler rejects any substitute digest.++Every assembled review bundle also contains the exact `model.pt`, pinned source+snapshots for Ultralytics, PyTorch, torchvision, and ONNX, and the executable+command in `export_omniparser_detector.py`. `conversion-recipe.json` is the+machine-readable authority for parameters and expected output. No local patch+was applied. These principal sources do not include every transitive build or+host dependency, so successful reproduction must still match the recorded+ONNX digest and does not by itself complete the pending license review.++## PP-OCRv5 detector++- Source: official PaddlePaddle `PP-OCRv5_mobile_det_onnx` Hugging Face repository+- Revision: `e6f4fa85f00e168c862bc462aebca69eef9b3d3d`+- Immutable ONNX URL: `https://huggingface.co/PaddlePaddle/PP-OCRv5_mobile_det_onnx/resolve/e6f4fa85f00e168c862bc462aebca69eef9b3d3d/inference.onnx`+- ONNX SHA-256: `a431985659dc921974177a95adcfbb90fd9e51989a5e04d70d0b75f597b6e61d`+- `inference.yml` SHA-256: `98069072e1b6b37d727fd9d9f11725faa46d6ea0de012f2ed26caea011c37699`+- License: Apache-2.0+- Input/output: `x` / `fetch_name_0`+- Reviewed preprocessing: BGR, `1/255`, ImageNet mean/std, CHW+- Reviewed postprocessing: DB threshold 0.3, box threshold 0.6, unclip ratio 1.5++## PP-OCRv5 English recognizer++- Source: official PaddlePaddle `en_PP-OCRv5_mobile_rec_onnx` Hugging Face repository+- Revision: `3fafbc3b5dcf93dd72add9f48368be8a3a2cd33b`+- Immutable ONNX URL: `https://huggingface.co/PaddlePaddle/en_PP-OCRv5_mobile_rec_onnx/resolve/3fafbc3b5dcf93dd72add9f48368be8a3a2cd33b/inference.onnx`+- Immutable dictionary URL: `https://huggingface.co/PaddlePaddle/en_PP-OCRv5_mobile_rec_onnx/resolve/3fafbc3b5dcf93dd72add9f48368be8a3a2cd33b/inference.yml`+- ONNX SHA-256: `b5f833dfc5d0eb71da397b4efa06ebeee9b431b690a47d6af40d77d8eabc557f`+- `inference.yml` SHA-256: `27e91d0582f40168aa218303c76e184bc78fa7a5d105aad0cfbad8458b441067`+- License: Apache-2.0+- Input/output: `x` / `fetch_name_0`+- Reviewed input: BGR float32 `[1,3,48,320]`+- Dictionary: `PostProcess.character_dict` in the hashed `inference.yml`++## Packaging checklist++1. Obtain each artifact from its pinned source revision and verify SHA-256.+2. Convert OmniParser with the recorded toolchain and compare the converted+ SHA-256; a different conversion must receive a new ledger entry.+3. Package a CPU-only ONNX Runtime dynamic library and record its exact version+ and SHA-256 in the copied manifest. Set `intra_threads` to the bounded CPU+ concurrency selected for that package and target.+4. Keep every artifact path relative to the manifest. Absolute paths, parent+ traversal, symlinks, empty files, and hash mismatches are rejected.+5. Start with `cua-perception --manifest <path> --onnx-runtime-library <path>`.+ Use `--fixture` only for deterministic protocol tests.++PP-OCR DB detections are returned as axis-aligned bounds. Rotated probability+map regions are not perspective-corrected before recognition; health and parse+identity expose this limitation so a caller can decide whether it is suitable.++## ONNX Runtime CPU library++The reviewed candidate lock pins official CPU-only archives at immutable tag+`v1.26.0` for all three targets. The assembler verifies each platform archive,+extracts exactly one target member, and verifies its digest:++- macOS arm64 archive `7a1280bbb1701ea514f71828765237e7896e0f2e1cd332f1f70dbd5c3e33aca3`; `libonnxruntime.dylib` `cb0462c3fd35ad722e8772313030a33c182f3d4c6b33f4e5e1fcb2ce3199b86c`+- Windows x64 archive `6ebe99b5564bf4d029b6e93eac9ff423682b6212eade769e9ca3f685eaf500b4`; `onnxruntime.dll` `b2ba7ca16e0e4fe71ad5148744ab885a2f5809e52a0c3de4d9ba3853a03977f9`+- Linux x64 archive `1254da24fb389cf39dc0ff3451ab48301740ffbfcbaf646849df92f80ee92c57`; `libonnxruntime.so` `5bd5bedf736fc501692435d0ec4f6e8b2bdf48cd30af8e6d00d61b3ddc9a7ab8`++`scripts/artifacts.lock.json` is the machine-readable authority for URLs,+archive members, sizes, target identities, and hashes. `SOURCE_OFFER.md` and+`THIRD_PARTY_NOTICES.md` must accompany every assembled bundle.diff --git a/libs/cua-driver/rust/crates/cua-perception/models/SOURCE_OFFER.md b/libs/cua-driver/rust/crates/cua-perception/models/SOURCE_OFFER.mdnew file mode 100644index 0000000000..ebe6a8f19d--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/models/SOURCE_OFFER.md@@ -0,0 +1,26 @@+# Corresponding-Source Review Payload++Every sealed Cua Perception review bundle includes `source-ledger.json` and the+source files named there. `source/cua-perception-source.tar.gz` contains the+exact Cua Perception worker source, Cargo workspace metadata, artifact+assembler, conversion command, model ledger, and repository license from the+commit named in the ledger.++The converted OmniParser detector is tied to upstream source file+`icon_detect/model.pt` at revision+`6600256cb0f1b07651e3bc86166196307bad7e2d` and SHA-256+`dab3d4351ad00b035db829909a4db98354d5a90f6990e4ac00222a9a95d4bf57`.+The exact hashed `model.pt` input is bundled under `source/upstream/`. Source+snapshots for the principal exporter components are bundled under+`source/exporter/`. `models/conversion-recipe.json` records the command,+parameters, versions, absence of local patches, expected output, and the+remaining reproducibility limitation. This payload preserves the reviewed+inputs for assessing the source obligations that apply to a distribution.++These files are a review payload, not a claim that legal review is complete or+that the payload is sufficient corresponding source for every distribution+scenario. The model ledger records the specific source model and converted+detector artifact as AGPL-3.0-only and remains `license-review-required`.+Immutable upstream URLs are recorded as provenance and recovery coordinates;+bundle verification uses the included bytes and pinned hashes rather than+trusting those declarations.diff --git a/libs/cua-driver/rust/crates/cua-perception/models/THIRD_PARTY_NOTICES.md b/libs/cua-driver/rust/crates/cua-perception/models/THIRD_PARTY_NOTICES.mdnew file mode 100644index 0000000000..35e70344e1--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/models/THIRD_PARTY_NOTICES.md@@ -0,0 +1,42 @@+# Cua Perception Third-Party Notices++The sealed Cua Perception bundle contains the following separately licensed+components. Exact revisions and SHA-256 digests are recorded in+`model-ledger.json` and `source-inventory.json` in each bundle.++## ONNX Runtime++Copyright Microsoft Corporation. The reviewed candidate lock pins official+CPU-only archives from <https://github.com/microsoft/onnxruntime> release+`v1.26.0`, which is licensed under the MIT License. The assembled bundle's+manifest and SBOM identify the archive and library actually included.++## OmniParser icon detector++The converted icon detector derives from Microsoft OmniParser v2.0 revision+`6600256cb0f1b07651e3bc86166196307bad7e2d`. The release ledger records this+specific source model and converted detector artifact as AGPL-3.0-only.+Publication and redistribution remain blocked pending the release review+recorded in the model ledger. The corresponding-source review payload is+described in `SOURCE_OFFER.md`.++## Bundled exporter source snapshots++The review bundle includes a pinned Ultralytics source snapshot recorded as+AGPL-3.0-only, PyTorch and torchvision snapshots recorded as BSD-3-Clause, and+ONNX and OnnxSlim snapshots recorded as Apache-2.0. Exact revisions, archive+hashes, and required contents are in `source-ledger.json`. These artifact-level+records apply only to the named snapshots. Their inclusion supports review and+reproduction of the detector conversion but does not complete the pending+detector license review.++## PaddleOCR models and dictionary++The PP-OCRv5 mobile detector, English recognizer, and recognizer dictionary+derive from `PaddlePaddle/PP-OCRv5_mobile_det_onnx` revision+`e6f4fa85f00e168c862bc462aebca69eef9b3d3d` and+`PaddlePaddle/en_PP-OCRv5_mobile_rec_onnx` revision+`3fafbc3b5dcf93dd72add9f48368be8a3a2cd33b`. These specific artifacts are+recorded under the Apache License 2.0.++This notice is informational and does not replace the applicable licenses.diff --git a/libs/cua-driver/rust/crates/cua-perception/models/conversion-recipe.json b/libs/cua-driver/rust/crates/cua-perception/models/conversion-recipe.jsonnew file mode 100644index 0000000000..38dffa0beb--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/models/conversion-recipe.json@@ -0,0 +1,38 @@+{+ "schema_version": 1,+ "status": "review-only-license-review-required",+ "input": {+ "bundle_path": "source/upstream/omniparser-icon-detect-model.pt",+ "sha256": "dab3d4351ad00b035db829909a4db98354d5a90f6990e4ac00222a9a95d4bf57",+ "size": 40623819+ },+ "command": [+ "python3",+ "models/export_omniparser_detector.py",+ "source/upstream/omniparser-icon-detect-model.pt",+ "omniparser-icon-detect-1280-opset17.onnx"+ ],+ "parameters": {+ "format": "onnx",+ "imgsz": 1280,+ "opset": 17,+ "simplify": true,+ "dynamic": false,+ "nms": false+ },+ "toolchain": {+ "python": "3.12.13",+ "torch": "2.8.0",+ "torchvision": "0.23.0",+ "ultralytics": "8.3.199",+ "onnx": "1.19.0",+ "onnxslim": "0.1.68",+ "onnxruntime_validation": "1.22.1"+ },+ "patches": [],+ "expected_output": {+ "sha256": "d8a876bf7f9fb73d7da9432904ade7fa78e092e9a91674e5a2806b45562a9ab2",+ "size": 80933219+ },+ "limitations": "The bundle pins the principal exporter sources and exact command. It does not claim that every transitive build dependency or host toolchain is contained; the output digest remains the byte-for-byte acceptance authority."+}diff --git a/libs/cua-driver/rust/crates/cua-perception/models/export_omniparser_detector.py b/libs/cua-driver/rust/crates/cua-perception/models/export_omniparser_detector.pynew file mode 100644index 0000000000..27aa3c9f04--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/models/export_omniparser_detector.py@@ -0,0 +1,63 @@+#!/usr/bin/env python3+"""Re-run the reviewed OmniParser detector export and verify its exact output."""++from __future__ import annotations++import argparse+from hashlib import sha256+from pathlib import Path+import shutil++EXPECTED_INPUT = "dab3d4351ad00b035db829909a4db98354d5a90f6990e4ac00222a9a95d4bf57"+EXPECTED_OUTPUT = "d8a876bf7f9fb73d7da9432904ade7fa78e092e9a91674e5a2806b45562a9ab2"+EXPECTED_VERSIONS = {+ "torch": "2.8.0",+ "torchvision": "0.23.0",+ "ultralytics": "8.3.199",+ "onnx": "1.19.0",+ "onnxslim": "0.1.68",+}+++def digest(path: Path) -> str:+ return sha256(path.read_bytes()).hexdigest()+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("source_model", type=Path)+ parser.add_argument("output", type=Path)+ args = parser.parse_args()+ if digest(args.source_model) != EXPECTED_INPUT:+ parser.error("source model SHA-256 differs from the sealed source input")++ import onnx # type: ignore[import-not-found]+ import onnxslim # type: ignore[import-not-found]+ import torch # type: ignore[import-not-found]+ import torchvision # type: ignore[import-not-found]+ import ultralytics # type: ignore[import-not-found]+ from ultralytics import YOLO # type: ignore[import-not-found]++ actual_versions = {+ "torch": torch.__version__.split("+")[0],+ "torchvision": torchvision.__version__.split("+")[0],+ "ultralytics": ultralytics.__version__,+ "onnx": onnx.__version__,+ "onnxslim": onnxslim.__version__,+ }+ if actual_versions != EXPECTED_VERSIONS:+ parser.error(f"exporter versions differ: expected {EXPECTED_VERSIONS}, got {actual_versions}")++ exported = Path(YOLO(str(args.source_model)).export(+ format="onnx", imgsz=1280, opset=17, simplify=True, dynamic=False, nms=False+ ))+ args.output.parent.mkdir(parents=True, exist_ok=True)+ if exported.resolve() != args.output.resolve():+ shutil.copyfile(exported, args.output)+ if digest(args.output) != EXPECTED_OUTPUT:+ parser.error("export completed, but output differs from the reviewed ONNX digest")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/libs/cua-driver/rust/crates/cua-perception/models/model-manifest.template.json b/libs/cua-driver/rust/crates/cua-perception/models/model-manifest.template.jsonnew file mode 100644index 0000000000..4be7d7d3b6--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/models/model-manifest.template.json@@ -0,0 +1,65 @@+{+ "schema_version": 1,+ "identity": {+ "name": "omniparser-v2-ppocrv5-en",+ "version": "2026-09-17",+ "source_url": "https://huggingface.co/microsoft/OmniParser-v2.0",+ "source_revision": "6600256cb0f1b07651e3bc86166196307bad7e2d",+ "license": "AGPL-3.0 (detector); Apache-2.0 (OCR)"+ },+ "onnx_runtime": {+ "version": "1.26.0",+ "target": "REPLACE_WITH_RUST_TARGET_TRIPLE",+ "library_sha256": "0000000000000000000000000000000000000000000000000000000000000000",+ "intra_threads": 2+ },+ "detector": {+ "model": {+ "path": "artifacts/omniparser-icon-detect-1280-opset17.onnx",+ "sha256": "d8a876bf7f9fb73d7da9432904ade7fa78e092e9a91674e5a2806b45562a9ab2"+ },+ "input_name": "images",+ "output_name": "output0",+ "input_width": 1280,+ "input_height": 1280,+ "confidence_threshold": 0.3,+ "iou_threshold": 0.1,+ "output_layout": "yolo_v8_cxcywh_class_scores",+ "max_candidates": 10000,+ "max_detections": 1000+ },+ "ocr": {+ "detector": {+ "model": {+ "path": "artifacts/ppocrv5-mobile-det.onnx",+ "sha256": "a431985659dc921974177a95adcfbb90fd9e51989a5e04d70d0b75f597b6e61d"+ },+ "input_name": "x",+ "output_name": "fetch_name_0",+ "input_width": 960,+ "input_height": 960,+ "pixel_threshold": 0.3,+ "box_threshold": 0.6,+ "unclip_ratio": 1.5,+ "minimum_area": 3,+ "minimum_side": 3,+ "max_candidates": 1000+ },+ "recognizer": {+ "model": {+ "path": "artifacts/ppocrv5-mobile-rec-en.onnx",+ "sha256": "b5f833dfc5d0eb71da397b4efa06ebeee9b431b690a47d6af40d77d8eabc557f"+ },+ "input_name": "x",+ "output_name": "fetch_name_0",+ "input_width": 320,+ "input_height": 48,+ "blank_index": 0+ },+ "dictionary": {+ "path": "artifacts/ppocrv5-mobile-rec-en-inference.yml",+ "sha256": "27e91d0582f40168aa218303c76e184bc78fa7a5d105aad0cfbad8458b441067"+ },+ "dictionary_format": "paddle_inference_yaml"+ }+}diff --git a/libs/cua-driver/rust/crates/cua-perception/models/source-inventory.template.json b/libs/cua-driver/rust/crates/cua-perception/models/source-inventory.template.jsonnew file mode 100644index 0000000000..fa31ab41c7--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/models/source-inventory.template.json@@ -0,0 +1,36 @@+{+ "schema_version": 1,+ "component": "cua-perception",+ "repository": "https://github.com/trycua/cua",+ "revision": "REPLACE_WITH_EXACT_40_CHARACTER_COMMIT",+ "archive": {+ "path": "source/cua-perception-source.tar.gz",+ "sha256": "REPLACE_WITH_ARCHIVE_SHA256",+ "size": 0+ },+ "included_paths": [+ "LICENSE.md",+ "libs/cua-driver/rust/Cargo.lock",+ "libs/cua-driver/rust/Cargo.toml",+ "libs/cua-driver/rust/crates/cua-perception"+ ],+ "source_offer": "SOURCE_OFFER.md",+ "bundled_upstream_sources": [+ {+ "component": "OmniParser icon detector source",+ "path": "source/upstream/omniparser-icon-detect-model.pt",+ "url": "https://huggingface.co/microsoft/OmniParser-v2.0/resolve/6600256cb0f1b07651e3bc86166196307bad7e2d/icon_detect/model.pt",+ "sha256": "dab3d4351ad00b035db829909a4db98354d5a90f6990e4ac00222a9a95d4bf57"+ },+ {+ "component": "Pinned exporter sources",+ "path": "source/exporter/",+ "url": "See scripts/artifacts.lock.json",+ "sha256": "See scripts/artifacts.lock.json"+ }+ ],+ "immutable_external_coordinates": [+ { "component": "ONNX Runtime and redistributed OCR inputs", "url": "See scripts/artifacts.lock.json", "sha256": "See scripts/artifacts.lock.json" }+ ],+ "review_status": "license-review-required"+}diff --git a/libs/cua-driver/rust/crates/cua-perception/scripts/README.md b/libs/cua-driver/rust/crates/cua-perception/scripts/README.mdnew file mode 100644index 0000000000..4cf3d19706--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/scripts/README.md@@ -0,0 +1,131 @@+# Cua Perception artifact tooling++`assemble_bundle.py` runs on the target platform and creates a sealed bundle+plus a deterministic `.tar.gz`. It accepts a target worker, an exact source+commit, a real-parse PNG, and a directory containing reviewed inputs. The+reviewed OmniParser ONNX conversion must be supplied locally; the two OCR+models, OCR dictionary, and ONNX Runtime archive may be obtained from the+immutable URLs in `artifacts.lock.json`. Every downloaded and supplied byte is+checked before use.++Example on macOS arm64:++```sh+python3 scripts/assemble_bundle.py \+ --target aarch64-apple-darwin \+ --worker target/aarch64-apple-darwin/release/cua-perception \+ --inputs /reviewed/cua-perception-inputs \+ --cache /reviewed/cua-perception-cache \+ --real-parse-fixture /reviewed/known-answer.png \+ --source-sha "$(git rev-parse HEAD)" \+ --version 0.1.0 \+ --output /staging/cua-perception-0.1.0-aarch64-apple-darwin+```++Assembly must run on the target host. The worker and extracted runtime are+checked for the requested executable format before model sessions are created.+The assembler invokes `health`, `self_test`, and a real parse, proves that a+tampered runtime and another platform's binary header are rejected, writes the+release verification reports, then seals every file in `SHA256SUMS`.++After installation, run the same checks without modifying the bundle:++```sh+python3 scripts/verify_bundle.py /installed/cua-perception-0.1.0-aarch64-apple-darwin+```++For review of a foreign-platform bundle, `--static-only` verifies hashes,+model/runtime binding, and executable headers without launching the worker.++## Quality runner++`quality_runner.py` produces the normalized, artifact-bound engine result files+consumed by `measure_quality.py`. It runs the exact closed corpus, performs a+cold startup plus first parse and a warm parse in one process for every image,+and records measured latency plus `sampled_process_peak_rss_bytes`. RSS is+polled every 5 ms for the single worker process, excludes descendant processes,+and can miss a peak between samples. The runner never downloads models or+substitutes fixture detections in its production path.++```sh+python3 scripts/quality_runner.py \+ --engine rust \+ --config /staging/rust-quality-config.json \+ --manifest tests/quality-corpus/manifest.json \+ --output /staging/rust-results.json++python3 scripts/quality_runner.py \+ --engine python \+ --config /staging/python-quality-config.json \+ --manifest tests/quality-corpus/manifest.json \+ --output /staging/python-results.json+```++Both configs contain closed `identity`, `bindings`, and `execution` objects.+Every binding path is relative to the config, confined without symlink+traversal, and paired with its expected SHA-256. `package_artifact_id` and+`installed_artifact_ids` select the bound files summed as+`bound_installed_artifact_bytes`. This is the byte total of those selected+artifacts, not a complete installed footprint. `artifact_size_bytes` is the+size of the selected package archive and is not described as installed size.++Rust execution requires `worker_artifact_id`, `manifest_artifact_id`,+`onnx_runtime_artifact_id`, `source_model_artifact_id`,+`detector_artifact_id`, `ocr_detector_artifact_id`,+`ocr_recognizer_artifact_id`, `ocr_dictionary_artifact_id`, `extension_id`,+`extension_version`, and `timeout_seconds`. The model manifest must be a bound+`model_manifest`; its source revision must match `identity.model.revision`, and+its detector, OCR, dictionary, and runtime paths and hashes must match the+named bound artifacts. A bound `conversion_metadata` artifact requires+`conversion_metadata_artifact_id`; the runner then verifies that its input and+expected-output hashes bind the source `.pt` and converted detector. Without+that record, the source model remains declared provenance and the report does+not claim that it proves derivation of the converted detector.++Python execution requires `python_interpreter_artifact_id`, `python_home`,+`site_packages`, `model_artifact_id`, `ocr_model_artifact_ids`, `cache_dir`,+`force_device`, `box_threshold`, `iou_threshold`, `use_ocr`, and+`timeout_seconds`. The bound Python interpreter has role `worker`; the detector+has role `source_model`; and each bound `ocr_model` file must be directly under+`cache_dir/model` so EasyOCR uses the measured offline cache. For every image,+the runner copies the hash-verified wheel, detector, OCR models, and+manifest-declared corpus image into a fresh runner-owned temporary directory.+The child verifies the staged image hash before inference and uses those same+bytes for both parses. It safely extracts the staged wheel and imports `som`+only from that extraction while retaining the configured offline+`site_packages` dependencies. The child starts with inherited `PYTHON*`+settings removed and Python site initialization disabled, so `sitecustomize`,+`usercustomize`, and `.pth` startup hooks cannot run before the bound wheel is+selected. Arbitrary `source_root` configuration is rejected.++Shortly before each engine process starts, the runner resolves and hashes the+bound executable, manifest, runtime, package, and model files again. Python+execution additionally revalidates `python_home`, `site_packages`, and+`cache_dir` immediately before launch, and the child repeats the directory+checks it can perform after startup. These checks fail closed for changes they+observe; path revalidation alone is not a defense against a same-user process+that races a remaining path-based Rust or Python dependency after its final+check. The staged Python files and corpus input avoid that pathname race for+the bytes copied into the runner-owned directory.+The Python `dependency_lock` binds the declared dependency resolution, but the+current result format has no installed-file manifest for `python_home` or+`site_packages`; the runner therefore does not claim cryptographic proof of+every installed dependency byte. Those directories must be prepared from the+bound lock in the controlled quality environment.++After generating both files, build the canonical comparison report with:++```sh+python3 scripts/measure_quality.py \+ --manifest tests/quality-corpus/manifest.json \+ --rust-results /staging/rust-results.json \+ --python-results /staging/python-results.json \+ --output /staging/quality-report.json+```++Control attribute metrics keep the total geometrically matched control count in+`matched`, report supplied-field coverage separately, and use `evaluated` as+the accuracy denominator. If no matched prediction supplies an attribute, its+accuracy has `status: "unavailable"` and `ratio: null`; omission is not counted+as a wrong classification. Label coverage is limited to matched controls whose+expected annotation has a label.diff --git a/libs/cua-driver/rust/crates/cua-perception/scripts/artifact_tooling.py b/libs/cua-driver/rust/crates/cua-perception/scripts/artifact_tooling.pynew file mode 100755index 0000000000..648b1d0993--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/scripts/artifact_tooling.py@@ -0,0 +1,328 @@+#!/usr/bin/env python3+"""Shared, dependency-free helpers for sealed Cua Perception bundles."""++from __future__ import annotations++import hashlib+import json+import platform+import re+import struct+import subprocess+import tarfile+from pathlib import Path+from pathlib import PurePosixPath+from typing import Any++SCRIPT_DIR = Path(__file__).resolve().parent+CRATE_DIR = SCRIPT_DIR.parent+LOCK_PATH = SCRIPT_DIR / "artifacts.lock.json"+PROTOCOL = "cua-perception/1"+EXTENSION_ID = "cua-perception"+++class ArtifactError(RuntimeError):+ pass+++def read_json(path: Path) -> dict[str, Any]:+ try:+ value = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError) as error:+ raise ArtifactError(f"cannot read JSON {path}: {error}") from error+ if not isinstance(value, dict):+ raise ArtifactError(f"expected a JSON object in {path}")+ return value+++def write_json(path: Path, value: Any) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps(value, indent=2, sort_keys=True) + "\n", encoding="utf-8")+++def sha256(path: Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as stream:+ for block in iter(lambda: stream.read(1024 * 1024), b""):+ digest.update(block)+ return digest.hexdigest()+++def verify_file(path: Path, expected_hash: str, expected_size: int | None = None) -> None:+ if path.is_symlink() or not path.is_file():+ raise ArtifactError(f"missing regular artifact: {path}")+ if expected_size is not None and path.stat().st_size != expected_size:+ raise ArtifactError(+ f"size mismatch for {path}: expected {expected_size}, got {path.stat().st_size}"+ )+ actual = sha256(path)+ if actual != expected_hash:+ raise ArtifactError(f"SHA-256 mismatch for {path}: expected {expected_hash}, got {actual}")+++def host_target() -> str:+ os_name = platform.system().lower()+ machine = platform.machine().lower()+ if os_name == "darwin" and machine in {"arm64", "aarch64"}:+ return "aarch64-apple-darwin"+ if os_name == "windows" and machine in {"amd64", "x86_64"}:+ return "x86_64-pc-windows-msvc"+ if os_name == "linux" and machine in {"amd64", "x86_64"}:+ return "x86_64-unknown-linux-gnu"+ raise ArtifactError(f"unsupported verification host: {platform.system()} {platform.machine()}")+++def extension_identity(manifest: dict[str, Any]) -> tuple[str, str]:+ extension_id = manifest.get("component")+ version = manifest.get("version")+ if extension_id != EXTENSION_ID or not isinstance(version, str) or not re.fullmatch(+ r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)", version+ ):+ raise ArtifactError("artifact manifest has an invalid extension identity")+ return extension_id, version+++def binary_target(path: Path) -> str:+ with path.open("rb") as stream:+ data = stream.read(4096)+ if len(data) >= 20 and data[:4] == b"\x7fELF":+ byte_order = "little" if data[5] == 1 else "big"+ machine = int.from_bytes(data[18:20], byte_order)+ if data[4] == 2 and machine == 62:+ return "x86_64-unknown-linux-gnu"+ if len(data) >= 64 and data[:2] == b"MZ":+ offset = int.from_bytes(data[0x3C:0x40], "little")+ if offset + 6 <= len(data) and data[offset : offset + 4] == b"PE\0\0":+ if int.from_bytes(data[offset + 4 : offset + 6], "little") == 0x8664:+ return "x86_64-pc-windows-msvc"+ if len(data) >= 8 and data[:4] in {b"\xcf\xfa\xed\xfe", b"\xfe\xed\xfa\xcf"}:+ byte_order = "little" if data[:4] == b"\xcf\xfa\xed\xfe" else "big"+ if int.from_bytes(data[4:8], byte_order) == 0x0100000C:+ return "aarch64-apple-darwin"+ raise ArtifactError(f"unsupported or unrecognized executable format: {path}")+++def require_binary_target(path: Path, expected: str) -> None:+ actual = binary_target(path)+ if actual != expected:+ raise ArtifactError(f"wrong-platform binary {path}: expected {expected}, got {actual}")+++def confined_file(root: Path, relative: str) -> Path:+ candidate = Path(relative)+ if candidate.is_absolute() or not candidate.parts or ".." in candidate.parts:+ raise ArtifactError(f"unsafe bundle path: {relative}")+ resolved_root = root.resolve()+ resolved = (root / candidate).resolve()+ if resolved.parent != resolved_root and resolved_root not in resolved.parents:+ raise ArtifactError(f"bundle path escapes root: {relative}")+ if (root / candidate).is_symlink() or not resolved.is_file():+ raise ArtifactError(f"bundle path is not a regular file: {relative}")+ return resolved+++def read_model_paths(bundle: Path, target: str) -> tuple[Path, Path, list[Path]]:+ model_manifest = read_json(bundle / "model-manifest.json")+ target_lock = read_json(LOCK_PATH)["onnx_runtime"]["targets"].get(target)+ if not target_lock:+ raise ArtifactError(f"unsupported bundle target: {target}")+ runtime_name = target_lock["filename"]+ runtime = confined_file(bundle, runtime_name)+ artifacts = [+ model_manifest["detector"]["model"],+ model_manifest["ocr"]["detector"]["model"],+ model_manifest["ocr"]["recognizer"]["model"],+ model_manifest["ocr"]["dictionary"],+ ]+ paths: list[Path] = []+ for artifact in artifacts:+ path = confined_file(bundle, artifact["path"])+ verify_file(path, artifact["sha256"])+ paths.append(path)+ verify_file(runtime, model_manifest["onnx_runtime"]["library_sha256"])+ return bundle / "model-manifest.json", runtime, paths+++def worker_request(+ worker: Path,+ manifest: Path,+ runtime: Path,+ request: dict[str, Any],+ extension_id: str,+ extension_version: str,+) -> dict[str, Any]:+ payload = json.dumps(request, separators=(",", ":")).encode()+ framed = struct.pack(">I", len(payload)) + payload+ process = subprocess.run(+ [+ str(worker),+ "--manifest",+ str(manifest),+ "--onnx-runtime-library",+ str(runtime),+ "--extension-id",+ extension_id,+ "--extension-version",+ extension_version,+ ],+ input=framed,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ timeout=180,+ check=False,+ )+ if process.returncode != 0:+ raise ArtifactError(+ f"worker exited {process.returncode}: {process.stderr.decode(errors='replace').strip()}"+ )+ if len(process.stdout) < 4:+ raise ArtifactError("worker returned a truncated response frame")+ size = struct.unpack(">I", process.stdout[:4])[0]+ if len(process.stdout) != size + 4:+ raise ArtifactError("worker response frame has the wrong length")+ try:+ response = json.loads(process.stdout[4:])+ except json.JSONDecodeError as error:+ raise ArtifactError(f"worker returned invalid JSON: {error}") from error+ if response.get("status") != "ok":+ raise ArtifactError(f"worker request failed: {response}")+ return response+++def request(method: str, params: dict[str, Any], request_id: str) -> dict[str, Any]:+ return {"protocol": PROTOCOL, "request_id": request_id, "method": method, "params": params}+++def _verify_source_archive(path: Path, required_paths: list[str]) -> None:+ try:+ with tarfile.open(path, "r:gz") as archive:+ members = archive.getmembers()+ except tarfile.TarError as error:+ raise ArtifactError(f"invalid corresponding-source archive {path}: {error}") from error+ if not members:+ raise ArtifactError(f"empty corresponding-source archive: {path}")+ safe_names = []+ for member in members:+ pure = PurePosixPath(member.name)+ if pure.is_absolute() or ".." in pure.parts:+ raise ArtifactError(f"unsafe corresponding-source member in {path}: {member.name}")+ if member.issym() or member.islnk():+ target = PurePosixPath(member.linkname)+ parts = list(pure.parent.parts)+ if target.is_absolute():+ raise ArtifactError(f"unsafe corresponding-source link in {path}: {member.name}")+ for part in target.parts:+ if part in {"", "."}:+ continue+ if part == "..":+ if len(parts) <= 1:+ raise ArtifactError(f"corresponding-source link escapes archive root: {member.name}")+ parts.pop()+ else:+ parts.append(part)+ safe_names.append(pure.as_posix().rstrip("/"))+ for required in required_paths:+ wanted = required.rstrip("/")+ if not any(name == wanted or name.endswith("/" + wanted) or f"/{wanted}/" in f"/{name}/" for name in safe_names):+ raise ArtifactError(f"corresponding-source archive {path} lacks required path: {required}")+++def verify_corresponding_sources(bundle: Path, manifest: dict[str, Any], lock: dict[str, Any]) -> list[dict[str, Any]]:+ source_artifacts = {+ item["name"]: item for item in manifest.get("artifacts", []) if item.get("kind") == "source"+ }+ if not source_artifacts:+ raise ArtifactError("bundle does not declare corresponding-source artifacts")+ ledger = read_json(confined_file(bundle, str(manifest.get("sourceLedger", ""))))+ entries = ledger.get("sources")+ if not isinstance(entries, list) or not entries:+ raise ArtifactError("source ledger contains no bundled source entries")+ ledger_entries = {entry.get("artifact"): entry for entry in entries if isinstance(entry, dict)}+ if len(ledger_entries) != len(entries) or set(ledger_entries) != set(source_artifacts):+ raise ArtifactError("source ledger entries differ from declared source artifacts")+ for name, artifact in source_artifacts.items():+ entry = ledger_entries[name]+ path = confined_file(bundle, artifact["path"])+ verify_file(path, artifact["sha256"], artifact["size"])+ if entry.get("artifactSha256") != artifact["sha256"] or entry.get("artifactSize") != artifact["size"]:+ raise ArtifactError(f"source ledger hash or size differs for {name}")+ if entry.get("license") != artifact.get("license", {}).get("spdx"):+ raise ArtifactError(f"source ledger license differs for {name}")+ if entry.get("sourceOfferStatus") not in {"bundled", "bundled-review-only"}:+ raise ArtifactError(f"source ledger does not identify a bundled payload for {name}")+ if entry.get("format") == "tar.gz":+ _verify_source_archive(path, entry.get("requiredPaths", []))+ elif entry.get("format") != "file":+ raise ArtifactError(f"source ledger has an unsupported format for {name}")+ expected = {entry["filename"]: entry for entry in lock.get("corresponding_source", [])}+ for name, pinned in expected.items():+ artifact = source_artifacts.get(name)+ entry = ledger_entries.get(name)+ if not artifact or not entry:+ raise ArtifactError(f"bundle is missing pinned source material: {name}")+ if artifact["path"] != pinned["bundle_path"]:+ raise ArtifactError(f"pinned source material has the wrong path: {name}")+ if artifact["sha256"] != pinned["sha256"] or artifact["size"] != pinned["size"]:+ raise ArtifactError(f"pinned source material differs from the artifact lock: {name}")+ if entry.get("revision") != pinned["revision"] or entry.get("contentKind") != pinned["content_kind"]:+ raise ArtifactError(f"source ledger revision or kind differs from the artifact lock: {name}")+ model_source = ledger_entries.get("omniparser-icon-detect-model.pt")+ if not model_source or model_source.get("contentKind") != "model-source-input":+ raise ArtifactError("exact OmniParser source model is not bundled")+ return entries+++def static_verify(bundle: Path, require_host: bool = True) -> dict[str, Any]:+ manifest = read_json(bundle / "artifact-manifest.json")+ extension_identity(manifest)+ target = manifest.get("target", {}).get("triple")+ lock = read_json(LOCK_PATH)+ if target not in lock["onnx_runtime"]["targets"]:+ raise ArtifactError(f"unsupported bundle target: {target}")+ if require_host and target != host_target():+ raise ArtifactError(f"wrong-platform bundle: host is {host_target()}, bundle is {target}")+ seen: set[str] = set()+ for artifact in manifest.get("artifacts", []):+ relative = artifact.get("path")+ if not isinstance(relative, str) or relative in seen:+ raise ArtifactError("artifact manifest contains a missing or duplicate path")+ seen.add(relative)+ verify_file(confined_file(bundle, relative), artifact["sha256"], artifact["size"])+ worker_entries = [item for item in manifest["artifacts"] if item["kind"] == "worker"]+ runtime_entries = [item for item in manifest["artifacts"] if item["kind"] == "runtime"]+ if len(worker_entries) != 1 or len(runtime_entries) != 1:+ raise ArtifactError("bundle must contain exactly one declared worker and runtime")+ if len(list(bundle.rglob("model-manifest.json"))) != 1:+ raise ArtifactError("bundle must contain one unique model-manifest.json at its root")+ require_binary_target(confined_file(bundle, worker_entries[0]["path"]), target)+ require_binary_target(confined_file(bundle, runtime_entries[0]["path"]), target)+ target_lock = lock["onnx_runtime"]["targets"][target]+ runtime_path = confined_file(bundle, runtime_entries[0]["path"])+ if runtime_path.name != target_lock["filename"]:+ raise ArtifactError("runtime filename does not match the pinned target runtime")+ verify_file(runtime_path, target_lock["sha256"], target_lock["size"])+ _, runtime, _ = read_model_paths(bundle, target)+ if sha256(runtime) != runtime_entries[0]["sha256"]:+ raise ArtifactError("runtime hash differs between model and artifact manifests")+ expected_roles = {entry["role"]: entry for entry in lock["artifacts"]}+ declared_roles = {+ item.get("role"): item+ for item in manifest["artifacts"]+ if item.get("kind") in {"model", "dictionary"}+ }+ if set(declared_roles) != set(expected_roles):+ raise ArtifactError("bundle does not declare exactly the pinned model and dictionary roles")+ for role, expected in expected_roles.items():+ declared = declared_roles[role]+ if declared["name"] != expected["filename"] or declared["sha256"] != expected["sha256"]:+ raise ArtifactError(f"{role} differs from the pinned artifact lock")+ if manifest.get("sourceLedger"):+ verify_corresponding_sources(bundle, manifest, lock)+ sums_path = bundle / "SHA256SUMS"+ if sums_path.exists():+ for line in sums_path.read_text(encoding="utf-8").splitlines():+ digest, marker, relative = line.partition(" ")+ if marker != " " or len(digest) != 64:+ raise ArtifactError("invalid SHA256SUMS line")+ verify_file(confined_file(bundle, relative), digest)+ return manifestdiff --git a/libs/cua-driver/rust/crates/cua-perception/scripts/artifacts.lock.json b/libs/cua-driver/rust/crates/cua-perception/scripts/artifacts.lock.jsonnew file mode 100644index 0000000000..a6ec540495--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/scripts/artifacts.lock.json@@ -0,0 +1,178 @@+{+ "schema_version": 1,+ "onnx_runtime": {+ "version": "1.26.0",+ "license": "MIT",+ "targets": {+ "aarch64-apple-darwin": {+ "os": "macos",+ "arch": "aarch64",+ "archive_url": "https://github.com/microsoft/onnxruntime/releases/download/v1.26.0/onnxruntime-osx-arm64-1.26.0.tgz",+ "archive_sha256": "7a1280bbb1701ea514f71828765237e7896e0f2e1cd332f1f70dbd5c3e33aca3",+ "archive_format": "tar.gz",+ "archive_member": "./onnxruntime-osx-arm64-1.26.0/lib/libonnxruntime.dylib",+ "filename": "libonnxruntime.dylib",+ "sha256": "cb0462c3fd35ad722e8772313030a33c182f3d4c6b33f4e5e1fcb2ce3199b86c",+ "size": 37310032,+ "worker_filename": "cua-perception"+ },+ "x86_64-pc-windows-msvc": {+ "os": "windows",+ "arch": "x86_64",+ "archive_url": "https://github.com/microsoft/onnxruntime/releases/download/v1.26.0/onnxruntime-win-x64-1.26.0.zip",+ "archive_sha256": "6ebe99b5564bf4d029b6e93eac9ff423682b6212eade769e9ca3f685eaf500b4",+ "archive_format": "zip",+ "archive_member": "onnxruntime-win-x64-1.26.0/lib/onnxruntime.dll",+ "filename": "onnxruntime.dll",+ "sha256": "b2ba7ca16e0e4fe71ad5148744ab885a2f5809e52a0c3de4d9ba3853a03977f9",+ "size": 14897976,+ "worker_filename": "cua-perception.exe"+ },+ "x86_64-unknown-linux-gnu": {+ "os": "linux",+ "arch": "x86_64",+ "archive_url": "https://github.com/microsoft/onnxruntime/releases/download/v1.26.0/onnxruntime-linux-x64-1.26.0.tgz",+ "archive_sha256": "1254da24fb389cf39dc0ff3451ab48301740ffbfcbaf646849df92f80ee92c57",+ "archive_format": "tar.gz",+ "archive_member": "onnxruntime-linux-x64-1.26.0/lib/libonnxruntime.so.1.26.0",+ "filename": "libonnxruntime.so",+ "sha256": "5bd5bedf736fc501692435d0ec4f6e8b2bdf48cd30af8e6d00d61b3ddc9a7ab8",+ "size": 23023576,+ "worker_filename": "cua-perception"+ }+ }+ },+ "corresponding_source": [+ {+ "content_kind": "model-source-input",+ "filename": "omniparser-icon-detect-model.pt",+ "bundle_path": "source/upstream/omniparser-icon-detect-model.pt",+ "url": "https://huggingface.co/microsoft/OmniParser-v2.0/resolve/6600256cb0f1b07651e3bc86166196307bad7e2d/icon_detect/model.pt",+ "sha256": "dab3d4351ad00b035db829909a4db98354d5a90f6990e4ac00222a9a95d4bf57",+ "size": 40623819,+ "repository": "https://huggingface.co/microsoft/OmniParser-v2.0",+ "revision": "6600256cb0f1b07651e3bc86166196307bad7e2d",+ "license": "AGPL-3.0-only",+ "format": "file",+ "source_offer_status": "bundled-review-only"+ },+ {+ "content_kind": "exporter-source",+ "filename": "ultralytics-8f7fe171f0db13e5c2eff55eee3443f8903e5068.tar.gz",+ "bundle_path": "source/exporter/ultralytics-8f7fe171f0db13e5c2eff55eee3443f8903e5068.tar.gz",+ "url": "https://codeload.github.com/ultralytics/ultralytics/tar.gz/8f7fe171f0db13e5c2eff55eee3443f8903e5068",+ "sha256": "6c289215a5ce593a872111b87e58ffff6949d235c2af720e8f01704375f7bf44",+ "size": 1872606,+ "repository": "https://github.com/ultralytics/ultralytics",+ "revision": "8f7fe171f0db13e5c2eff55eee3443f8903e5068",+ "license": "AGPL-3.0-only",+ "format": "tar.gz",+ "required_paths": ["ultralytics/engine/exporter.py", "pyproject.toml"],+ "source_offer_status": "bundled-review-only"+ },+ {+ "content_kind": "exporter-source",+ "filename": "pytorch-ba56102387ef21a3b04b357e5b183d48f0afefc7.tar.gz",+ "bundle_path": "source/exporter/pytorch-ba56102387ef21a3b04b357e5b183d48f0afefc7.tar.gz",+ "url": "https://codeload.github.com/pytorch/pytorch/tar.gz/ba56102387ef21a3b04b357e5b183d48f0afefc7",+ "sha256": "a9623012b046e9cc87c919f178782860bcee9fbf014ad5c24a2655b517d0881b",+ "size": 56595340,+ "repository": "https://github.com/pytorch/pytorch",+ "revision": "ba56102387ef21a3b04b357e5b183d48f0afefc7",+ "license": "BSD-3-Clause",+ "format": "tar.gz",+ "required_paths": ["torch/onnx", "torch/_dynamo", "setup.py"],+ "source_offer_status": "bundled-review-only"+ },+ {+ "content_kind": "exporter-source",+ "filename": "torchvision-824e8c8726b65fd9d5abdc9702f81c2b0c4c0dc8.tar.gz",+ "bundle_path": "source/exporter/torchvision-824e8c8726b65fd9d5abdc9702f81c2b0c4c0dc8.tar.gz",+ "url": "https://codeload.github.com/pytorch/vision/tar.gz/824e8c8726b65fd9d5abdc9702f81c2b0c4c0dc8",+ "sha256": "8e44b7705c901b9af76113393fe675b02ceeb43b1c688db50e0d8ff8a9dcef03",+ "size": 14499056,+ "repository": "https://github.com/pytorch/vision",+ "revision": "824e8c8726b65fd9d5abdc9702f81c2b0c4c0dc8",+ "license": "BSD-3-Clause",+ "format": "tar.gz",+ "required_paths": ["torchvision", "setup.py"],+ "source_offer_status": "bundled-review-only"+ },+ {+ "content_kind": "exporter-source",+ "filename": "onnx-57b9c6a4f6eebb09ae1b34cfb632078518f72832.tar.gz",+ "bundle_path": "source/exporter/onnx-57b9c6a4f6eebb09ae1b34cfb632078518f72832.tar.gz",+ "url": "https://codeload.github.com/onnx/onnx/tar.gz/57b9c6a4f6eebb09ae1b34cfb632078518f72832",+ "sha256": "a1a9c44e20ea1f9cf0c094e0f82001113b36e0867e04c06966475c46e3c75739",+ "size": 13109973,+ "repository": "https://github.com/onnx/onnx",+ "revision": "57b9c6a4f6eebb09ae1b34cfb632078518f72832",+ "license": "Apache-2.0",+ "format": "tar.gz",+ "required_paths": ["onnx", "pyproject.toml"],+ "source_offer_status": "bundled-review-only"+ },+ {+ "content_kind": "exporter-source",+ "filename": "onnxslim-0.1.68.tar.gz",+ "bundle_path": "source/exporter/onnxslim-0.1.68.tar.gz",+ "url": "https://files.pythonhosted.org/packages/f3/03/7eecb5b187b7b3e11d066f19211b1850a8b4e5cc79f5e3c78875a676a1c8/onnxslim-0.1.68.tar.gz",+ "sha256": "ff1ec2bf61ff10b75e33990b2046c446dec522ba7f0a12b2f984547ff43f9138",+ "size": 141502,+ "repository": "https://github.com/inisis/OnnxSlim",+ "revision": "0.1.68",+ "license": "Apache-2.0",+ "format": "tar.gz",+ "required_paths": ["onnxslim", "VERSION"],+ "source_offer_status": "bundled-review-only"+ }+ ],+ "artifacts": [+ {+ "role": "icon-detect",+ "filename": "omniparser-icon-detect-1280-opset17.onnx",+ "sha256": "d8a876bf7f9fb73d7da9432904ade7fa78e092e9a91674e5a2806b45562a9ab2",+ "size": 80933219,+ "url": null,+ "origin": "https://huggingface.co/microsoft/OmniParser-v2.0",+ "revision": "6600256cb0f1b07651e3bc86166196307bad7e2d",+ "source_path": "icon_detect/model.pt",+ "source_sha256": "dab3d4351ad00b035db829909a4db98354d5a90f6990e4ac00222a9a95d4bf57",+ "license": "AGPL-3.0-only",+ "verification_status": "license-review-required"+ },+ {+ "role": "ocr-detect",+ "filename": "ppocrv5-mobile-det.onnx",+ "sha256": "a431985659dc921974177a95adcfbb90fd9e51989a5e04d70d0b75f597b6e61d",+ "size": 4826518,+ "url": "https://huggingface.co/PaddlePaddle/PP-OCRv5_mobile_det_onnx/resolve/e6f4fa85f00e168c862bc462aebca69eef9b3d3d/inference.onnx",+ "origin": "https://huggingface.co/PaddlePaddle/PP-OCRv5_mobile_det_onnx",+ "revision": "e6f4fa85f00e168c862bc462aebca69eef9b3d3d",+ "license": "Apache-2.0",+ "verification_status": "release-verified"+ },+ {+ "role": "ocr-recognize",+ "filename": "ppocrv5-mobile-rec-en.onnx",+ "sha256": "b5f833dfc5d0eb71da397b4efa06ebeee9b431b690a47d6af40d77d8eabc557f",+ "size": 7848423,+ "url": "https://huggingface.co/PaddlePaddle/en_PP-OCRv5_mobile_rec_onnx/resolve/3fafbc3b5dcf93dd72add9f48368be8a3a2cd33b/inference.onnx",+ "origin": "https://huggingface.co/PaddlePaddle/en_PP-OCRv5_mobile_rec_onnx",+ "revision": "3fafbc3b5dcf93dd72add9f48368be8a3a2cd33b",+ "license": "Apache-2.0",+ "verification_status": "release-verified"+ },+ {+ "role": "ocr-dictionary",+ "filename": "ppocrv5-mobile-rec-en-inference.yml",+ "sha256": "27e91d0582f40168aa218303c76e184bc78fa7a5d105aad0cfbad8458b441067",+ "size": 3964,+ "url": "https://huggingface.co/PaddlePaddle/en_PP-OCRv5_mobile_rec_onnx/resolve/3fafbc3b5dcf93dd72add9f48368be8a3a2cd33b/inference.yml",+ "origin": "https://huggingface.co/PaddlePaddle/en_PP-OCRv5_mobile_rec_onnx",+ "revision": "3fafbc3b5dcf93dd72add9f48368be8a3a2cd33b",+ "license": "Apache-2.0",+ "verification_status": "release-verified"+ }+ ]+}diff --git a/libs/cua-driver/rust/crates/cua-perception/scripts/assemble_bundle.py b/libs/cua-driver/rust/crates/cua-perception/scripts/assemble_bundle.pynew file mode 100755index 0000000000..cca0b920f9--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/scripts/assemble_bundle.py@@ -0,0 +1,447 @@+#!/usr/bin/env python3+"""Assemble and seal a target-native Cua Perception worker bundle."""++from __future__ import annotations++import argparse+import gzip+import json+import shutil+import subprocess+import tarfile+import tempfile+import urllib.parse+import urllib.request+import zipfile+from pathlib import Path+from typing import Any++from artifact_tooling import (+ ArtifactError,+ CRATE_DIR,+ LOCK_PATH,+ extension_identity,+ host_target,+ read_json,+ require_binary_target,+ sha256,+ static_verify,+ verify_file,+ write_json,+)+from verify_bundle import exercise_bundle++SOURCE_PATHS = (+ "LICENSE.md",+ "libs/cua-driver/rust/Cargo.lock",+ "libs/cua-driver/rust/Cargo.toml",+ "libs/cua-driver/rust/crates/cua-perception",+)+++def immutable_url(url: str) -> None:+ parsed = urllib.parse.urlparse(url)+ if parsed.scheme != "https" or parsed.query or parsed.fragment:+ raise ArtifactError(f"artifact URL is not an immutable HTTPS coordinate: {url}")+ if "github.com/microsoft/onnxruntime/releases/download/v1.26.0/" in url:+ return+ marker = "/resolve/"+ if "huggingface.co/" in url and marker in url:+ revision = url.split(marker, 1)[1].split("/", 1)[0]+ if len(revision) == 40 and all(character in "0123456789abcdef" for character in revision):+ return+ if "codeload.github.com/" in url and "/tar.gz/" in url:+ revision = url.rsplit("/tar.gz/", 1)[1]+ if len(revision) == 40 and all(character in "0123456789abcdef" for character in revision):+ return+ if parsed.netloc == "files.pythonhosted.org" and parsed.path.startswith("/packages/"):+ return+ raise ArtifactError(f"artifact URL does not pin an approved tag or commit: {url}")+++def download(url: str, destination: Path, expected_hash: str, expected_size: int | None) -> Path:+ immutable_url(url)+ if destination.exists():+ verify_file(destination, expected_hash, expected_size)+ return destination+ destination.parent.mkdir(parents=True, exist_ok=True)+ with tempfile.NamedTemporaryFile(prefix=destination.name + ".", dir=destination.parent, delete=False) as stream:+ temporary = Path(stream.name)+ request = urllib.request.Request(url, headers={"User-Agent": "cua-perception-assembler/1"})+ try:+ with urllib.request.urlopen(request, timeout=120) as response:+ shutil.copyfileobj(response, stream, length=1024 * 1024)+ except Exception:+ temporary.unlink(missing_ok=True)+ raise+ try:+ verify_file(temporary, expected_hash, expected_size)+ temporary.replace(destination)+ except Exception:+ temporary.unlink(missing_ok=True)+ raise+ return destination+++def obtain_artifact(entry: dict[str, Any], inputs: Path, cache: Path) -> Path:+ supplied = inputs / entry["filename"]+ if supplied.is_file():+ verify_file(supplied, entry["sha256"], entry["size"])+ return supplied+ if not entry.get("url"):+ raise ArtifactError(+ f"required reviewed conversion is absent: place {entry['filename']} in {inputs}"+ )+ return download(entry["url"], cache / entry["filename"], entry["sha256"], entry["size"])+++def extract_runtime(lock: dict[str, Any], target: str, cache: Path, destination: Path) -> None:+ target_lock = lock["onnx_runtime"]["targets"][target]+ archive_name = target_lock["archive_url"].rsplit("/", 1)[1]+ archive = download(+ target_lock["archive_url"],+ cache / archive_name,+ target_lock["archive_sha256"],+ None,+ )+ if target_lock["archive_format"] == "zip":+ with zipfile.ZipFile(archive) as package:+ members = [name for name in package.namelist() if name == target_lock["archive_member"]]+ if members != [target_lock["archive_member"]]:+ raise ArtifactError(f"runtime archive does not contain one exact target member: {members}")+ with package.open(members[0]) as source, destination.open("wb") as output:+ shutil.copyfileobj(source, output, length=1024 * 1024)+ elif target_lock["archive_format"] == "tar.gz":+ with tarfile.open(archive, mode="r:gz") as package:+ members = [member for member in package.getmembers() if member.name == target_lock["archive_member"]]+ if len(members) != 1 or not members[0].isfile():+ raise ArtifactError("runtime archive does not contain one exact regular target member")+ source = package.extractfile(members[0])+ if source is None:+ raise ArtifactError("runtime archive target member cannot be read")+ with source, destination.open("wb") as output:+ shutil.copyfileobj(source, output, length=1024 * 1024)+ else:+ raise ArtifactError(f"unsupported runtime archive format: {target_lock['archive_format']}")+ verify_file(destination, target_lock["sha256"], target_lock["size"])+ require_binary_target(destination, target)+++def repository_root() -> Path:+ result = subprocess.run(+ ["git", "-C", str(CRATE_DIR), "rev-parse", "--show-toplevel"],+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=True,+ check=False,+ )+ if result.returncode != 0:+ raise ArtifactError(result.stderr.strip())+ return Path(result.stdout.strip())+++def corresponding_source(repo: Path, revision: str, destination: Path) -> None:+ if len(revision) != 40 or any(character not in "0123456789abcdef" for character in revision):+ raise ArtifactError("source revision must be an exact lowercase 40-character commit")+ check = subprocess.run(+ ["git", "-C", str(repo), "cat-file", "-e", f"{revision}^{{commit}}"], check=False+ )+ if check.returncode != 0:+ raise ArtifactError(f"source commit is unavailable locally: {revision}")+ archive = subprocess.run(+ [+ "git",+ "-C",+ str(repo),+ "archive",+ "--format=tar",+ "--prefix=cua-perception-source/",+ revision,+ "--",+ *SOURCE_PATHS,+ ],+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ check=False,+ )+ if archive.returncode != 0:+ raise ArtifactError(archive.stderr.decode(errors="replace").strip())+ destination.parent.mkdir(parents=True, exist_ok=True)+ destination.write_bytes(gzip.compress(archive.stdout, compresslevel=9, mtime=0))+++def model_manifest(lock: dict[str, Any], target: str) -> dict[str, Any]:+ artifacts = {entry["role"]: entry for entry in lock["artifacts"]}+ return {+ "schema_version": 1,+ "identity": {+ "name": "omniparser-v2-ppocrv5-en",+ "version": "2026-09-17",+ "source_url": "https://huggingface.co/microsoft/OmniParser-v2.0",+ "source_revision": artifacts["icon-detect"]["revision"],+ "license": "AGPL-3.0-only (detector); Apache-2.0 (OCR)",+ },+ "onnx_runtime": {+ "version": lock["onnx_runtime"]["version"],+ "target": target,+ "library_sha256": lock["onnx_runtime"]["targets"][target]["sha256"],+ "intra_threads": 2,+ },+ "detector": {+ "model": {"path": f"models/{artifacts['icon-detect']['filename']}", "sha256": artifacts["icon-detect"]["sha256"]},+ "input_name": "images", "output_name": "output0", "input_width": 1280,+ "input_height": 1280, "confidence_threshold": 0.3, "iou_threshold": 0.1,+ "output_layout": "yolo_v8_cxcywh_class_scores",+ "max_candidates": 10000, "max_detections": 1000,+ },+ "ocr": {+ "detector": {+ "model": {"path": f"models/{artifacts['ocr-detect']['filename']}", "sha256": artifacts["ocr-detect"]["sha256"]},+ "input_name": "x", "output_name": "fetch_name_0", "input_width": 960,+ "input_height": 960, "pixel_threshold": 0.3, "box_threshold": 0.6,+ "unclip_ratio": 1.5, "minimum_area": 3, "minimum_side": 3,+ "max_candidates": 1000,+ },+ "recognizer": {+ "model": {"path": f"models/{artifacts['ocr-recognize']['filename']}", "sha256": artifacts["ocr-recognize"]["sha256"]},+ "input_name": "x", "output_name": "fetch_name_0", "input_width": 320,+ "input_height": 48, "blank_index": 0,+ },+ "dictionary": {"path": f"models/{artifacts['ocr-dictionary']['filename']}", "sha256": artifacts["ocr-dictionary"]["sha256"]},+ "dictionary_format": "paddle_inference_yaml",+ },+ }+++def model_ledger(lock: dict[str, Any]) -> dict[str, Any]:+ models = []+ for entry in lock["artifacts"]:+ if entry["role"] == "ocr-dictionary":+ continue+ model = {+ "artifact": entry["filename"], "artifactSha256": entry["sha256"],+ "artifactSize": entry["size"], "origin": entry["origin"],+ "revision": entry["revision"], "license": entry["license"],+ "redistributionAllowed": True, "verificationStatus": entry["verification_status"],+ "exportSource": "source/cua-perception-source.tar.gz contains models/conversion-recipe.json and models/export_omniparser_detector.py; principal exporter sources are bundled under source/exporter/",+ }+ if entry["role"] == "icon-detect":+ model["sourceArtifact"] = {+ "artifact": "omniparser-icon-detect-model.pt",+ "path": "source/upstream/omniparser-icon-detect-model.pt",+ "sha256": entry["source_sha256"], "size": 40623819+ }+ model["usageRestrictions"] = ["Do not publish until AGPL release review is complete"]+ models.append(model)+ return {"schemaVersion": 1, "models": models}+++def artifact(+ path: Path,+ root: Path,+ kind: str,+ license_id: str,+ notice: bool = True,+ source_url: str = "https://github.com/trycua/cua",+ **extra: Any,+) -> dict[str, Any]:+ relative = path.relative_to(root).as_posix()+ license_value: dict[str, str] = {"spdx": license_id, "source": source_url}+ if notice:+ license_value["notice"] = "THIRD_PARTY_NOTICES.md"+ return {+ "kind": kind, "name": path.name, "path": relative, "sha256": sha256(path),+ "size": path.stat().st_size, "license": license_value, **extra,+ }+++def release_manifest(bundle: Path, lock: dict[str, Any], target: str, version: str, revision: str) -> dict[str, Any]:+ target_lock = lock["onnx_runtime"]["targets"][target]+ target_value = {"triple": target, "os": target_lock["os"], "arch": target_lock["arch"]}+ entries = [+ artifact(bundle / target_lock["worker_filename"], bundle, "worker", "MIT", target=target_value, protocolVersion=1),+ artifact(+ bundle / target_lock["filename"], bundle, "runtime", "MIT",+ source_url="https://github.com/microsoft/onnxruntime",+ target=target_value, protocolVersion=1,+ ),+ ]+ for item in lock["artifacts"]:+ kind = "dictionary" if item["role"] == "ocr-dictionary" else "model"+ entries.append(+ artifact(+ bundle / "models" / item["filename"], bundle, kind, item["license"],+ source_url=item["origin"], role=item["role"],+ )+ )+ entries.extend([+ artifact(bundle / "model-manifest.json", bundle, "model-manifest", "MIT"),+ artifact(bundle / "THIRD_PARTY_NOTICES.md", bundle, "notice", "MIT", notice=False),+ artifact(bundle / "SOURCE_OFFER.md", bundle, "notice", "AGPL-3.0-only", notice=False),+ artifact(bundle / "source/cua-perception-source.tar.gz", bundle, "source", "MIT"),+ artifact(bundle / "verification/health.json", bundle, "supplied-verification-report", "MIT", role="health"),+ artifact(bundle / "verification/self-test.json", bundle, "supplied-verification-report", "MIT", role="self-test"),+ artifact(bundle / "verification/real-parse.json", bundle, "supplied-verification-report", "MIT", role="real-parse"),+ ])+ for source in lock["corresponding_source"]:+ entries.append(artifact(+ bundle / source["bundle_path"], bundle, "source", source["license"],+ source_url=source["repository"],+ ))+ return {+ "schemaVersion": 1, "component": "cua-perception", "version": version,+ "driverVersion": ">=0.28.2", "sourceSha": revision, "target": target_value,+ "protocol": {"name": "cua-perception-worker", "version": 1}, "artifacts": entries,+ "modelLedger": "model-ledger.json", "sourceLedger": "source-ledger.json",+ "suppliedVerification": {"health": "verification/health.json", "selfTest": "verification/self-test.json", "realParse": "verification/real-parse.json"},+ }+++def write_sums(bundle: Path) -> None:+ lines = []+ for path in sorted(item for item in bundle.rglob("*") if item.is_file() and item.name != "SHA256SUMS"):+ if path.is_symlink():+ raise ArtifactError(f"bundle cannot contain symlinks: {path}")+ lines.append(f"{sha256(path)} {path.relative_to(bundle).as_posix()}")+ (bundle / "SHA256SUMS").write_text("\n".join(lines) + "\n", encoding="utf-8")+++def deterministic_bundle_archive(bundle: Path, destination: Path) -> None:+ with destination.open("wb") as raw:+ with gzip.GzipFile(filename="", mode="wb", fileobj=raw, compresslevel=9, mtime=0) as zipped:+ with tarfile.open(fileobj=zipped, mode="w") as archive:+ for path in sorted([bundle, *bundle.rglob("*")]):+ if path.is_symlink():+ raise ArtifactError(f"bundle cannot contain symlinks: {path}")+ info = archive.gettarinfo(str(path), arcname=path.relative_to(bundle.parent).as_posix())+ info.uid = info.gid = 0+ info.uname = info.gname = ""+ info.mtime = 0+ if path.is_file():+ with path.open("rb") as stream:+ archive.addfile(info, stream)+ else:+ archive.addfile(info)+++def assemble(args: argparse.Namespace) -> tuple[Path, Path]:+ lock = read_json(LOCK_PATH)+ if args.target not in lock["onnx_runtime"]["targets"]:+ raise ArtifactError(f"unsupported target: {args.target}")+ if args.target != host_target():+ raise ArtifactError(f"assembly must run on target host {args.target}; current host is {host_target()}")+ identity = extension_identity({"component": "cua-perception", "version": args.version})+ if args.output.exists():+ raise ArtifactError(f"refusing to overwrite existing output: {args.output}")+ target_lock = lock["onnx_runtime"]["targets"][args.target]+ require_binary_target(args.worker, args.target)+ repo = repository_root()+ bundle = args.output+ bundle.mkdir(parents=True)+ try:+ worker = bundle / target_lock["worker_filename"]+ shutil.copyfile(args.worker, worker)+ worker.chmod(0o755)+ runtime = bundle / target_lock["filename"]+ extract_runtime(lock, args.target, args.cache, runtime)+ models_dir = bundle / "models"+ models_dir.mkdir()+ for entry in lock["artifacts"]:+ shutil.copyfile(obtain_artifact(entry, args.inputs, args.cache), models_dir / entry["filename"])+ for entry in lock["corresponding_source"]:+ source_material = obtain_artifact(entry, args.inputs, args.cache)+ destination = bundle / entry["bundle_path"]+ destination.parent.mkdir(parents=True, exist_ok=True)+ shutil.copyfile(source_material, destination)+ write_json(bundle / "model-manifest.json", model_manifest(lock, args.target))+ shutil.copyfile(CRATE_DIR / "models/THIRD_PARTY_NOTICES.md", bundle / "THIRD_PARTY_NOTICES.md")+ shutil.copyfile(CRATE_DIR / "models/SOURCE_OFFER.md", bundle / "SOURCE_OFFER.md")+ write_json(bundle / "model-ledger.json", model_ledger(lock))+ source = bundle / "source/cua-perception-source.tar.gz"+ corresponding_source(repo, args.source_sha, source)+ source_entries = [{+ "artifact": source.name, "artifactSha256": sha256(source), "artifactSize": source.stat().st_size,+ "repository": "https://github.com/trycua/cua", "revision": args.source_sha, "license": "MIT",+ "durableLocation": f"Candidate archive {source.relative_to(bundle).as_posix()}",+ "sourceOfferStatus": "bundled-review-only", "contentKind": "cua-source",+ "format": "tar.gz", "requiredPaths": [+ *SOURCE_PATHS,+ "libs/cua-driver/rust/crates/cua-perception/models/conversion-recipe.json",+ "libs/cua-driver/rust/crates/cua-perception/models/export_omniparser_detector.py",+ "libs/cua-driver/rust/crates/cua-perception/scripts/artifacts.lock.json",+ ], "patches": [],+ }]+ for entry in lock["corresponding_source"]:+ material = bundle / entry["bundle_path"]+ source_entries.append({+ "artifact": entry["filename"], "artifactSha256": sha256(material),+ "artifactSize": material.stat().st_size, "repository": entry["repository"],+ "revision": entry["revision"], "license": entry["license"],+ "durableLocation": f"Candidate archive {entry['bundle_path']}",+ "sourceOfferStatus": entry["source_offer_status"],+ "contentKind": entry["content_kind"], "format": entry["format"],+ **({"requiredPaths": entry["required_paths"]} if entry.get("required_paths") else {}),+ "patches": [],+ })+ source_ledger = {"schemaVersion": 1, "sources": source_entries}+ write_json(bundle / "source-ledger.json", source_ledger)+ write_json(bundle / "source-inventory.json", {+ "schema_version": 1, "component": "cua-perception", "repository": "https://github.com/trycua/cua",+ "revision": args.source_sha,+ "archive": {"path": source.relative_to(bundle).as_posix(), "sha256": sha256(source), "size": source.stat().st_size},+ "included_paths": list(SOURCE_PATHS), "source_offer": "SOURCE_OFFER.md",+ "bundled_upstream_sources": [+ {"component": entry["content_kind"], "path": entry["bundle_path"],+ "url": entry["url"], "revision": entry["revision"],+ "sha256": entry["sha256"], "size": entry["size"]}+ for entry in lock["corresponding_source"]+ ],+ "immutable_external_coordinates": [+ {"component": entry["role"], "url": entry["url"],+ "revision": entry["revision"], "sha256": entry["sha256"],+ "size": entry["size"]}+ for entry in lock["artifacts"] if entry.get("url")+ ] + [{+ "component": "onnx-runtime-cpu-archive", "url": target_lock["archive_url"],+ "sha256": target_lock["archive_sha256"],+ }],+ "review_status": "license-review-required",+ })+ fixture = bundle / "verification/known-answer.png"+ fixture.parent.mkdir()+ shutil.copyfile(args.real_parse_fixture, fixture)+ exercise_bundle(bundle, args.target, fixture, identity, fixture.parent)+ write_json(bundle / "artifact-manifest.json", release_manifest(bundle, lock, args.target, args.version, args.source_sha))+ write_sums(bundle)+ static_verify(bundle)+ archive = bundle.parent / f"cua-perception-{args.version}-{args.target}.tar.gz"+ if archive.exists():+ raise ArtifactError(f"refusing to overwrite existing archive: {archive}")+ deterministic_bundle_archive(bundle, archive)+ return bundle, archive+ except Exception:+ shutil.rmtree(bundle)+ raise+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--target", required=True, choices=sorted(read_json(LOCK_PATH)["onnx_runtime"]["targets"]))+ parser.add_argument("--worker", required=True, type=Path)+ parser.add_argument("--inputs", required=True, type=Path, help="directory containing reviewed local artifacts")+ parser.add_argument("--cache", required=True, type=Path, help="content-verified immutable download cache")+ parser.add_argument("--real-parse-fixture", required=True, type=Path)+ parser.add_argument("--source-sha", required=True)+ parser.add_argument("--version", required=True)+ parser.add_argument("--output", required=True, type=Path)+ args = parser.parse_args()+ try:+ bundle, archive = assemble(args)+ print(json.dumps({"bundle": str(bundle), "archive": str(archive), "sha256": sha256(archive)}, sort_keys=True))+ return 0+ except (ArtifactError, OSError, KeyError, ValueError, zipfile.BadZipFile) as error:+ parser.exit(1, f"assembly failed: {error}\n")+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/libs/cua-driver/rust/crates/cua-perception/scripts/measure_quality.py b/libs/cua-driver/rust/crates/cua-perception/scripts/measure_quality.pynew file mode 100644index 0000000000..223fe84acd--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/scripts/measure_quality.py@@ -0,0 +1,936 @@+#!/usr/bin/env python3+"""Measure the synthetic Cua Perception corpus from normalized engine results.++The input contract is intentionally model-neutral. Each Rust or Python result is+a closed JSON object with this shape (all hashes are lowercase SHA-256):++ {+ "schema_version": 1,+ "engine": "rust",+ "identity": {+ "model": {"id": "...", "version": "...", "revision": "..."},+ "runtime": {"id": "...", "version": "..."},+ "adapter": {"id": "...", "version": "..."},+ "reference_machine": {+ "id": "...", "os": "...", "arch": "...", "cpu": "...",+ "memory_bytes": 123+ }+ },+ "bindings": {+ "artifacts": [{"role": "source_model", "id": "omniparser_source",+ "path": "files/model.pt", "sha256": "..."}],+ "package_artifact_id": "package",+ "installed_artifact_ids": ["worker", "runtime"]+ },+ "images": [{+ "file": "images/example.png", "image_sha256": "...",+ "coordinate_space": {"space": "source_pixels", "origin": "top_left",+ "bbox_format": "x_y_width_height", "width": 100, "height": 80},+ "regions": [{+ "id": "optional", "kind": "text|control|icon",+ "bounds": {"x": 0, "y": 0, "width": 10, "height": 10},+ "text": "optional", "label": "optional", "confidence": 0.9+ }],+ "samples": [{"phase": "cold|warm", "latency_ms": 1.2,+ "sampled_process_peak_rss_bytes": 123}]+ }]+ }++All binding paths are confined relative to the result JSON and are omitted from+the report; hashes and sizes are recomputed from those regular files.+Each image must contain exactly one cold sample followed by exactly one warm+sample. RSS is sampled every 5 ms for the single worker process; it does not+include descendants and may miss peaks between samples.+Confidence and duplicate detections do not affect matching. Expected and+predicted regions are compatible when their intersection over union is at least+0.5. OCR additionally requires the manifest's case-sensitive,+outer-whitespace-trimmed target string. Result kinds describe detection+families: both ``control`` and ``icon`` are control detections. Neither family+implies a manifest control subtype; only an explicit ``control_kind`` is scored,+and a missing subtype is reported as unknown through metric coverage. No+release quality threshold is implied.+"""++from __future__ import annotations++import argparse+import hashlib+import json+import math+import re+import struct+import sys+from pathlib import Path, PurePosixPath+from statistics import mean, median+from typing import Any, Callable, Iterable+++MAX_JSON_BYTES = 32 * 1024 * 1024+MAX_IMAGES = 10_000+MAX_REGIONS_PER_IMAGE = 100_000+MAX_SAMPLES_PER_IMAGE = 10_000+SHA256_RE = re.compile(r"[0-9a-f]{64}")+MIN_MATCH_IOU = 0.5+++class MeasurementError(RuntimeError):+ """An input is unsafe, malformed, inconsistent, or incomplete."""+++def _reject_duplicate_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]:+ value: dict[str, Any] = {}+ for key, item in pairs:+ if key in value:+ raise MeasurementError(f"duplicate JSON key: {key}")+ value[key] = item+ return value+++def _reject_constant(value: str) -> None:+ raise MeasurementError(f"non-finite JSON number: {value}")+++def read_json(path: Path) -> tuple[dict[str, Any], str]:+ if path.is_symlink() or not path.is_file():+ raise MeasurementError(f"JSON input is not a regular file: {path}")+ data = path.read_bytes()+ if len(data) > MAX_JSON_BYTES:+ raise MeasurementError(f"JSON input exceeds {MAX_JSON_BYTES} bytes: {path}")+ try:+ value = json.loads(+ data,+ object_pairs_hook=_reject_duplicate_keys,+ parse_constant=_reject_constant,+ )+ except (UnicodeDecodeError, json.JSONDecodeError, OSError) as error:+ raise MeasurementError(f"cannot read JSON {path}: {error}") from error+ if not isinstance(value, dict):+ raise MeasurementError(f"expected a JSON object in {path}")+ return value, hashlib.sha256(data).hexdigest()+++def _closed(value: Any, required: Iterable[str], optional: Iterable[str], where: str) -> dict[str, Any]:+ if not isinstance(value, dict):+ raise MeasurementError(f"{where} must be an object")+ required_set = set(required)+ allowed = required_set | set(optional)+ missing = sorted(required_set - value.keys())+ unknown = sorted(value.keys() - allowed)+ if missing:+ raise MeasurementError(f"{where} is missing fields: {', '.join(missing)}")+ if unknown:+ raise MeasurementError(f"{where} has unknown fields: {', '.join(unknown)}")+ return value+++def _list(value: Any, where: str, maximum: int) -> list[Any]:+ if not isinstance(value, list):+ raise MeasurementError(f"{where} must be an array")+ if len(value) > maximum:+ raise MeasurementError(f"{where} exceeds {maximum} entries")+ return value+++def _string(value: Any, where: str, *, allow_empty: bool = False) -> str:+ if not isinstance(value, str) or (not allow_empty and not value.strip()):+ raise MeasurementError(f"{where} must be a non-empty string")+ if "\x00" in value:+ raise MeasurementError(f"{where} contains a NUL byte")+ return value+++def _integer(value: Any, where: str, *, minimum: int = 0) -> int:+ if isinstance(value, bool) or not isinstance(value, int) or value < minimum:+ raise MeasurementError(f"{where} must be an integer >= {minimum}")+ return value+++def _number(value: Any, where: str, *, minimum: float = 0.0, maximum: float | None = None) -> float:+ if isinstance(value, bool) or not isinstance(value, (int, float)):+ raise MeasurementError(f"{where} must be a number")+ result = float(value)+ if not math.isfinite(result) or result < minimum or (maximum is not None and result > maximum):+ limit = f" and <= {maximum}" if maximum is not None else ""+ raise MeasurementError(f"{where} must be finite and >= {minimum}{limit}")+ return result+++def _sha256(value: Any, where: str) -> str:+ if not isinstance(value, str) or SHA256_RE.fullmatch(value) is None:+ raise MeasurementError(f"{where} must be a lowercase SHA-256 digest")+ return value+++def _safe_relative_file(value: Any, where: str) -> str:+ name = _string(value, where)+ path = PurePosixPath(name)+ if path.is_absolute() or not path.parts or any(part in {"", ".", ".."} for part in path.parts):+ raise MeasurementError(f"{where} is not a safe relative path")+ if "\\" in name:+ raise MeasurementError(f"{where} must use POSIX separators")+ return name+++def _bounds(value: Any, where: str, width: int, height: int) -> tuple[float, float, float, float]:+ item = _closed(value, ("x", "y", "width", "height"), (), where)+ x = _number(item["x"], f"{where}.x")+ y = _number(item["y"], f"{where}.y")+ box_width = _number(item["width"], f"{where}.width", minimum=0.0)+ box_height = _number(item["height"], f"{where}.height", minimum=0.0)+ if box_width <= 0 or box_height <= 0:+ raise MeasurementError(f"{where} width and height must be positive")+ if x + box_width > width or y + box_height > height:+ raise MeasurementError(f"{where} is outside its image")+ return x, y, box_width, box_height+++def _manifest_bounds(value: Any, where: str, width: int, height: int) -> tuple[float, float, float, float]:+ items = _list(value, where, 4)+ if len(items) != 4:+ raise MeasurementError(f"{where} must contain four integers")+ for index, item in enumerate(items):+ _integer(item, f"{where}[{index}]")+ return _bounds(dict(zip(("x", "y", "width", "height"), items)), where, width, height)+++def _png_dimensions(path: Path) -> tuple[int, int]:+ if path.is_symlink() or not path.is_file():+ raise MeasurementError(f"corpus image is not a regular file: {path}")+ with path.open("rb") as stream:+ header = stream.read(24)+ if len(header) != 24 or header[:8] != b"\x89PNG\r\n\x1a\n" or header[12:16] != b"IHDR":+ raise MeasurementError(f"corpus image is not a PNG with an IHDR header: {path}")+ return struct.unpack(">II", header[16:24])+++def _file_sha256(path: Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as stream:+ for block in iter(lambda: stream.read(1024 * 1024), b""):+ digest.update(block)+ return digest.hexdigest()+++def validate_manifest(manifest: dict[str, Any], manifest_path: Path) -> list[dict[str, Any]]:+ top = _closed(+ manifest,+ ("schema_version", "corpus_version", "license", "coordinate_system", "metric_definitions", "images"),+ (),+ "manifest",+ )+ if top["schema_version"] != 1:+ raise MeasurementError("manifest.schema_version must be 1")+ _string(top["corpus_version"], "manifest.corpus_version")+ _string(top["license"], "manifest.license")+ coordinates = _closed(top["coordinate_system"], ("space", "origin", "bbox_format"), (), "manifest.coordinate_system")+ if coordinates != {"space": "source_pixels", "origin": "top_left", "bbox_format": "x_y_width_height"}:+ raise MeasurementError("manifest coordinate system is unsupported")+ definitions = top["metric_definitions"]+ if not isinstance(definitions, dict) or not definitions:+ raise MeasurementError("manifest.metric_definitions must be a non-empty object")+ for name, definition in definitions.items():+ _string(name, "manifest metric name")+ item = _closed(definition, ("unit", "description"), (), f"manifest.metric_definitions.{name}")+ _string(item["unit"], f"manifest.metric_definitions.{name}.unit")+ _string(item["description"], f"manifest.metric_definitions.{name}.description")++ root = manifest_path.parent.resolve()+ images: list[dict[str, Any]] = []+ seen_files: set[str] = set()+ seen_hashes: set[str] = set()+ for index, raw in enumerate(_list(top["images"], "manifest.images", MAX_IMAGES)):+ where = f"manifest.images[{index}]"+ item = _closed(raw, ("file", "sha256", "width", "height", "scenario_tags", "expected"), (), where)+ file_name = _safe_relative_file(item["file"], f"{where}.file")+ digest = _sha256(item["sha256"], f"{where}.sha256")+ width = _integer(item["width"], f"{where}.width", minimum=1)+ height = _integer(item["height"], f"{where}.height", minimum=1)+ if file_name in seen_files or digest in seen_hashes:+ raise MeasurementError(f"{where} duplicates a corpus file or hash")+ seen_files.add(file_name)+ seen_hashes.add(digest)+ tags = _list(item["scenario_tags"], f"{where}.scenario_tags", 1_000)+ if len(tags) != len({_string(tag, f"{where}.scenario_tags") for tag in tags}):+ raise MeasurementError(f"{where}.scenario_tags contains duplicates")+ expected = _closed(item["expected"], ("text", "controls"), (), f"{where}.expected")+ text_items: list[dict[str, Any]] = []+ control_items: list[dict[str, Any]] = []+ ids: set[str] = set()+ for text_index, raw_text in enumerate(_list(expected["text"], f"{where}.expected.text", MAX_REGIONS_PER_IMAGE)):+ text_where = f"{where}.expected.text[{text_index}]"+ text = _closed(raw_text, ("id", "text", "bbox", "role"), (), text_where)+ annotation_id = _string(text["id"], f"{text_where}.id")+ if annotation_id in ids:+ raise MeasurementError(f"{text_where}.id is duplicated")+ ids.add(annotation_id)+ target = _string(text["text"], f"{text_where}.text")+ text_items.append({"id": annotation_id, "text": target.strip(), "bounds": _manifest_bounds(text["bbox"], f"{text_where}.bbox", width, height)})+ _string(text["role"], f"{text_where}.role")+ for control_index, raw_control in enumerate(_list(expected["controls"], f"{where}.expected.controls", MAX_REGIONS_PER_IMAGE)):+ control_where = f"{where}.expected.controls[{control_index}]"+ control = _closed(raw_control, ("id", "kind", "label", "bbox", "state"), (), control_where)+ annotation_id = _string(control["id"], f"{control_where}.id")+ if annotation_id in ids:+ raise MeasurementError(f"{control_where}.id is duplicated")+ ids.add(annotation_id)+ _string(control["kind"], f"{control_where}.kind")+ if control["label"] is not None:+ _string(control["label"], f"{control_where}.label")+ _string(control["state"], f"{control_where}.state")+ control_items.append({+ "id": annotation_id,+ "kind": control["kind"],+ "label": control["label"].strip() if control["label"] is not None else None,+ "state": control["state"],+ "bounds": _manifest_bounds(control["bbox"], f"{control_where}.bbox", width, height),+ })+ image_candidate = manifest_path.parent / PurePosixPath(file_name)+ if image_candidate.is_symlink():+ raise MeasurementError(f"{where}.file must not be a symlink")+ image_path = image_candidate.resolve()+ if image_path.parent != root and root not in image_path.parents:+ raise MeasurementError(f"{where}.file escapes the corpus root")+ actual_dimensions = _png_dimensions(image_path)+ if actual_dimensions != (width, height):+ raise MeasurementError(f"{where} dimensions do not match the PNG IHDR")+ actual_hash = _file_sha256(image_path)+ if actual_hash != digest:+ raise MeasurementError(f"{where} SHA-256 does not match the corpus image")+ images.append({+ "file": file_name,+ "sha256": digest,+ "width": width,+ "height": height,+ "scenario_tags": sorted(tags),+ "text": text_items,+ "controls": control_items,+ })+ if not images:+ raise MeasurementError("manifest.images must not be empty")+ return images+++def _identity_string(value: Any, where: str) -> str:+ result = _string(value, where)+ if (+ "/" in result+ or "\\" in result+ or "://" in result+ or result.startswith((".", "~"))+ or re.match(r"^[A-Za-z]:", result)+ or any(ord(character) < 32 for character in result)+ ):+ raise MeasurementError(f"{where} must be a path-free identity string")+ return result+++def _identity(value: Any, where: str) -> dict[str, Any]:+ identity = _closed(value, ("model", "runtime", "adapter", "reference_machine"), (), where)+ model = _closed(identity["model"], ("id", "version", "revision"), (), f"{where}.model")+ runtime = _closed(identity["runtime"], ("id", "version"), (), f"{where}.runtime")+ adapter = _closed(identity["adapter"], ("id", "version"), (), f"{where}.adapter")+ machine = _closed(identity["reference_machine"], ("id", "os", "arch", "cpu", "memory_bytes"), (), f"{where}.reference_machine")+ return {+ "model": {+ "id": _identity_string(model["id"], f"{where}.model.id"),+ "version": _identity_string(model["version"], f"{where}.model.version"),+ "revision": _identity_string(model["revision"], f"{where}.model.revision"),+ },+ "runtime": {+ "id": _identity_string(runtime["id"], f"{where}.runtime.id"),+ "version": _identity_string(runtime["version"], f"{where}.runtime.version"),+ },+ "adapter": {+ "id": _identity_string(adapter["id"], f"{where}.adapter.id"),+ "version": _identity_string(adapter["version"], f"{where}.adapter.version"),+ },+ "reference_machine": {+ "id": _identity_string(machine["id"], f"{where}.reference_machine.id"),+ "os": _identity_string(machine["os"], f"{where}.reference_machine.os"),+ "arch": _identity_string(machine["arch"], f"{where}.reference_machine.arch"),+ "cpu": _identity_string(machine["cpu"], f"{where}.reference_machine.cpu"),+ "memory_bytes": _integer(machine["memory_bytes"], f"{where}.reference_machine.memory_bytes", minimum=1),+ },+ }+++ARTIFACT_ROLES = {+ "source_model",+ "converted_model",+ "ocr_model",+ "ocr_dictionary",+ "model_manifest",+ "conversion_metadata",+ "runtime",+ "worker",+ "package",+ "dependency_lock",+}+++def _bound_file(root: Path, value: Any, where: str) -> dict[str, Any]:+ binding = _closed(value, ("role", "id", "path", "sha256"), (), where)+ role = _identity_string(binding["role"], f"{where}.role")+ if role not in ARTIFACT_ROLES:+ raise MeasurementError(f"{where}.role is unsupported")+ artifact_id = _identity_string(binding["id"], f"{where}.id")+ relative = _safe_relative_file(binding["path"], f"{where}.path")+ expected_hash = _sha256(binding["sha256"], f"{where}.sha256")+ candidate = root / PurePosixPath(relative)+ current = root+ for part in PurePosixPath(relative).parts:+ current = current / part+ if current.is_symlink():+ raise MeasurementError(f"{where}.path must not traverse a symlink")+ resolved = candidate.resolve()+ if (resolved.parent != root and root not in resolved.parents) or not resolved.is_file():+ raise MeasurementError(f"{where}.path is not a confined regular file")+ actual_hash = _file_sha256(resolved)+ if actual_hash != expected_hash:+ raise MeasurementError(f"{where}.sha256 does not match the bound file")+ return {+ "role": role,+ "id": artifact_id,+ "sha256": actual_hash,+ "size_bytes": resolved.stat().st_size,+ "resolved": resolved,+ }+++def _binding_list(root: Path, value: Any, where: str) -> list[dict[str, Any]]:+ items = [_bound_file(root, raw, f"{where}[{index}]") for index, raw in enumerate(_list(value, where, 10_000))]+ ids = [item["id"] for item in items]+ if len(ids) != len(set(ids)):+ raise MeasurementError(f"{where} contains duplicate artifact ids")+ return sorted(items, key=lambda item: item["id"])+++def _binding_identity(items: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], str]:+ public = [+ {"role": item["role"], "id": item["id"], "sha256": item["sha256"], "size_bytes": item["size_bytes"]}+ for item in items+ ]+ encoded = json.dumps(public, sort_keys=True, separators=(",", ":")).encode()+ return public, hashlib.sha256(encoded).hexdigest()+++def _coordinate_space(value: Any, where: str, source_width: int, source_height: int) -> tuple[float, float]:+ coordinate = _closed(value, ("space", "origin", "bbox_format", "width", "height"), (), where)+ if coordinate["space"] not in {"source_pixels", "adapter_pixels", "normalized"}:+ raise MeasurementError(f"{where}.space is unsupported")+ if coordinate["origin"] != "top_left" or coordinate["bbox_format"] != "x_y_width_height":+ raise MeasurementError(f"{where} origin or bbox format is unsupported")+ width = _number(coordinate["width"], f"{where}.width")+ height = _number(coordinate["height"], f"{where}.height")+ if width <= 0 or height <= 0:+ raise MeasurementError(f"{where} dimensions must be positive")+ if coordinate["space"] == "source_pixels" and (width != source_width or height != source_height):+ raise MeasurementError(f"{where} source-pixel dimensions must match the corpus image")+ if coordinate["space"] == "normalized" and (width != 1.0 or height != 1.0):+ raise MeasurementError(f"{where} normalized dimensions must be 1 by 1")+ return width, height+++def validate_results(+ document: dict[str, Any],+ expected_engine: str,+ corpus: list[dict[str, Any]],+ results_path: Path,+) -> dict[str, Any]:+ top = _closed(document, ("schema_version", "engine", "identity", "bindings", "images"), (), f"{expected_engine} results")+ if top["schema_version"] != 1:+ raise MeasurementError(f"{expected_engine} results schema_version must be 1")+ if top["engine"] != expected_engine:+ raise MeasurementError(f"expected {expected_engine} results, got {top['engine']!r}")+ identity = _identity(top["identity"], f"{expected_engine} results.identity")+ binding_root = results_path.parent.resolve()+ bindings = _closed(+ top["bindings"],+ ("artifacts", "package_artifact_id", "installed_artifact_ids"),+ (),+ f"{expected_engine} results.bindings",+ )+ artifacts = _binding_list(binding_root, bindings["artifacts"], f"{expected_engine} results.bindings.artifacts")+ artifacts_by_id = {item["id"]: item for item in artifacts}+ required_roles = {"source_model", "runtime", "worker", "package", "dependency_lock"}+ missing_roles = sorted(required_roles - {item["role"] for item in artifacts})+ if missing_roles:+ raise MeasurementError(f"{expected_engine} results.bindings.artifacts is missing roles: {', '.join(missing_roles)}")+ role_counts = {role: sum(item["role"] == role for item in artifacts) for role in ARTIFACT_ROLES}+ if role_counts["ocr_model"] == 0:+ raise MeasurementError(f"{expected_engine} results must bind at least one OCR model artifact")+ if expected_engine == "rust" and (+ role_counts["converted_model"] == 0+ or role_counts["ocr_model"] < 2+ or role_counts["ocr_dictionary"] == 0+ ):+ raise MeasurementError(+ "rust results must bind a converted detector, OCR detector and recognizer models, and an OCR dictionary"+ )+ sources = [item for item in artifacts if item["role"] == "source_model"]+ if len(sources) != 1 or sources[0]["id"] != "omniparser_source":+ raise MeasurementError(f"{expected_engine} results must bind exactly one source_model named omniparser_source")+ package_id = _identity_string(bindings["package_artifact_id"], f"{expected_engine} results.bindings.package_artifact_id")+ package = artifacts_by_id.get(package_id)+ if package is None or package["role"] != "package":+ raise MeasurementError(f"{expected_engine} package_artifact_id must identify a package artifact")+ installed_ids = [+ _identity_string(item, f"{expected_engine} results.bindings.installed_artifact_ids")+ for item in _list(bindings["installed_artifact_ids"], f"{expected_engine} results.bindings.installed_artifact_ids", 10_000)+ ]+ if not installed_ids or len(installed_ids) != len(set(installed_ids)):+ raise MeasurementError(f"{expected_engine} installed_artifact_ids must be non-empty and unique")+ try:+ installed = [artifacts_by_id[item] for item in installed_ids]+ except KeyError as error:+ raise MeasurementError(f"{expected_engine} installed_artifact_ids contains an unknown id: {error.args[0]}") from error+ public_artifacts, artifacts_sha256 = _binding_identity(artifacts)+ model_artifacts = [item for item in artifacts if item["role"] in {"source_model", "converted_model", "ocr_model", "ocr_dictionary"}]+ model_public, model_artifacts_sha256 = _binding_identity(model_artifacts)+ runtime_artifacts = [item for item in artifacts if item["role"] in {"runtime", "worker", "dependency_lock"}]+ runtime_public, runtime_artifacts_sha256 = _binding_identity(runtime_artifacts)+ expected_by_file = {image["file"]: image for image in corpus}+ parsed_images: dict[str, dict[str, Any]] = {}+ for index, raw in enumerate(_list(top["images"], f"{expected_engine} results.images", MAX_IMAGES)):+ where = f"{expected_engine} results.images[{index}]"+ item = _closed(raw, ("file", "image_sha256", "coordinate_space", "regions", "samples"), (), where)+ file_name = _safe_relative_file(item["file"], f"{where}.file")+ if file_name in parsed_images:+ raise MeasurementError(f"{where}.file is duplicated")+ corpus_image = expected_by_file.get(file_name)+ if corpus_image is None:+ raise MeasurementError(f"{where}.file is not in the corpus")+ if _sha256(item["image_sha256"], f"{where}.image_sha256") != corpus_image["sha256"]:+ raise MeasurementError(f"{where}.image_sha256 does not match the corpus")+ coordinate_width, coordinate_height = _coordinate_space(+ item["coordinate_space"], f"{where}.coordinate_space", corpus_image["width"], corpus_image["height"]+ )+ regions: list[dict[str, Any]] = []+ for region_index, raw_region in enumerate(_list(item["regions"], f"{where}.regions", MAX_REGIONS_PER_IMAGE)):+ region_where = f"{where}.regions[{region_index}]"+ region = _closed(+ raw_region,+ ("kind", "bounds"),+ ("id", "text", "label", "state", "control_kind", "confidence"),+ region_where,+ )+ kind = region["kind"]+ if kind not in {"text", "control", "icon"}:+ raise MeasurementError(f"{region_where}.kind must be text, control, or icon")+ text = region.get("text")+ label = region.get("label")+ state = region.get("state")+ control_kind = region.get("control_kind")+ if text is not None:+ text = _string(text, f"{region_where}.text").strip()+ if label is not None:+ label = _string(label, f"{region_where}.label").strip()+ if state is not None:+ state = _identity_string(state, f"{region_where}.state")+ if control_kind is not None:+ control_kind = _identity_string(control_kind, f"{region_where}.control_kind")+ if kind == "text" and text is None:+ raise MeasurementError(f"{region_where}.text is required for text regions")+ if "id" in region:+ _string(region["id"], f"{region_where}.id")+ if "confidence" in region:+ _number(region["confidence"], f"{region_where}.confidence", maximum=1.0)+ raw_bounds = _bounds(region["bounds"], f"{region_where}.bounds", coordinate_width, coordinate_height)+ scale_x = corpus_image["width"] / coordinate_width+ scale_y = corpus_image["height"] / coordinate_height+ regions.append({+ "kind": "control" if kind == "icon" else kind,+ "bounds": (raw_bounds[0] * scale_x, raw_bounds[1] * scale_y, raw_bounds[2] * scale_x, raw_bounds[3] * scale_y),+ "text": text,+ "label": label,+ "state": state,+ "control_kind": control_kind,+ })+ samples: list[dict[str, Any]] = []+ raw_samples = _list(item["samples"], f"{where}.samples", MAX_SAMPLES_PER_IMAGE)+ if len(raw_samples) != 2:+ raise MeasurementError(f"{where}.samples must contain exactly one cold and one warm measurement")+ phases: list[str] = []+ for sample_index, raw_sample in enumerate(raw_samples):+ sample_where = f"{where}.samples[{sample_index}]"+ sample = _closed(raw_sample, ("phase", "latency_ms", "sampled_process_peak_rss_bytes"), (), sample_where)+ phase = sample["phase"]+ if phase not in {"cold", "warm"}:+ raise MeasurementError(f"{sample_where}.phase must be cold or warm")+ phases.append(phase)+ samples.append({+ "phase": phase,+ "latency_ms": _number(sample["latency_ms"], f"{sample_where}.latency_ms"),+ "sampled_process_peak_rss_bytes": _integer(+ sample["sampled_process_peak_rss_bytes"],+ f"{sample_where}.sampled_process_peak_rss_bytes",+ minimum=1,+ ),+ })+ if phases != ["cold", "warm"]:+ raise MeasurementError(f"{where}.samples must contain exactly one cold followed by one warm measurement")+ parsed_images[file_name] = {"regions": regions, "samples": samples}+ missing = sorted(expected_by_file.keys() - parsed_images.keys())+ if missing or len(parsed_images) != len(expected_by_file):+ raise MeasurementError(f"{expected_engine} results do not cover the exact corpus image set; missing: {missing}")+ installed_unique = {item["resolved"]: item for item in installed}+ return {+ "identity": {+ **identity,+ "model": {+ **identity["model"],+ "artifacts_sha256": model_artifacts_sha256,+ "artifacts": model_public,+ },+ "runtime": {+ **identity["runtime"],+ "artifacts_sha256": runtime_artifacts_sha256,+ "artifacts": runtime_public,+ },+ "verified_artifacts_sha256": artifacts_sha256,+ "verified_artifacts": public_artifacts,+ },+ "model_comparison": {+ "identity": identity["model"],+ "omniparser_source": {+ "id": sources[0]["id"],+ "sha256": sources[0]["sha256"],+ "size_bytes": sources[0]["size_bytes"],+ },+ },+ "artifact": {+ "sha256": package["sha256"],+ "size_bytes": package["size_bytes"],+ "bound_installed_artifact_bytes": sum(item["size_bytes"] for item in installed_unique.values()),+ },+ "images": parsed_images,+ }+++def _center(bounds: tuple[float, float, float, float]) -> tuple[float, float]:+ x, y, width, height = bounds+ return x + width / 2.0, y + height / 2.0+++def _center_error(left: tuple[float, float, float, float], right: tuple[float, float, float, float]) -> float:+ left_center = _center(left)+ right_center = _center(right)+ return math.hypot(left_center[0] - right_center[0], left_center[1] - right_center[1])+++def _iou(left: tuple[float, float, float, float], right: tuple[float, float, float, float]) -> float:+ left_x, left_y, left_width, left_height = left+ right_x, right_y, right_width, right_height = right+ intersection_width = max(0.0, min(left_x + left_width, right_x + right_width) - max(left_x, right_x))+ intersection_height = max(0.0, min(left_y + left_height, right_y + right_height) - max(left_y, right_y))+ intersection = intersection_width * intersection_height+ union = left_width * left_height + right_width * right_height - intersection+ return intersection / union if union else 0.0+++def _geometrically_compatible(left: tuple[float, float, float, float], right: tuple[float, float, float, float]) -> bool:+ return _iou(left, right) >= MIN_MATCH_IOU+++def _maximum_matching(+ expected: list[dict[str, Any]],+ predicted: list[dict[str, Any]],+ compatible: Callable[[dict[str, Any], dict[str, Any]], bool],+) -> list[tuple[int, int]]:+ adjacency = [+ sorted(+ (index for index, prediction in enumerate(predicted) if compatible(item, prediction)),+ key=lambda index: (-_iou(item["bounds"], predicted[index]["bounds"]), _center_error(item["bounds"], predicted[index]["bounds"]), index),+ )+ for item in expected+ ]+ prediction_to_expected: dict[int, int] = {}++ def augment(expected_index: int, visited: set[int]) -> bool:+ for prediction_index in adjacency[expected_index]:+ if prediction_index in visited:+ continue+ visited.add(prediction_index)+ previous = prediction_to_expected.get(prediction_index)+ if previous is None or augment(previous, visited):+ prediction_to_expected[prediction_index] = expected_index+ return True+ return False++ for expected_index in range(len(expected)):+ augment(expected_index, set())+ return sorted((expected_index, prediction_index) for prediction_index, expected_index in prediction_to_expected.items())+++def _ratio(matched: int, expected: int) -> float | None:+ return matched / expected if expected else None+++def _attribute_accuracy(correct: int, evaluated: int, matched: int, eligible: int) -> dict[str, Any]:+ return {+ "status": "available" if evaluated else "unavailable",+ "correct": correct,+ "matched": matched,+ "evaluated": evaluated,+ "coverage": {+ "available": evaluated,+ "eligible": eligible,+ "ratio": _ratio(evaluated, eligible),+ },+ "ratio": _ratio(correct, evaluated),+ }+++def _percentile(values: list[float], percentile: float) -> float:+ ordered = sorted(values)+ position = max(0, math.ceil(percentile * len(ordered)) - 1)+ return ordered[position]+++def _summary(values: list[float]) -> dict[str, Any]:+ if not values:+ raise MeasurementError("cannot summarize an empty measurement set")+ return {+ "count": len(values),+ "min": min(values),+ "median": median(values),+ "p95": _percentile(values, 0.95),+ "max": max(values),+ "mean": mean(values),+ }+++def _optional_summary(values: list[float]) -> dict[str, Any]:+ return _summary(values) if values else {+ "count": 0,+ "min": None,+ "median": None,+ "p95": None,+ "max": None,+ "mean": None,+ }+++def _duplicate_neutral_false_positives(+ expected: list[dict[str, Any]],+ predicted: list[dict[str, Any]],+ pairs: list[tuple[int, int]],+ compatible: Callable[[dict[str, Any], dict[str, Any]], bool],+ signature: Callable[[dict[str, Any]], tuple[Any, ...]],+) -> int:+ matched_predictions = {prediction_index for _, prediction_index in pairs}+ false_positives = 0+ for prediction_index, prediction in enumerate(predicted):+ if prediction_index in matched_predictions:+ continue+ duplicate = any(+ compatible(expected[expected_index], prediction)+ and signature(prediction) == signature(predicted[matched_prediction_index])+ for expected_index, matched_prediction_index in pairs+ )+ if not duplicate:+ false_positives += 1+ return false_positives+++def measure_engine(corpus: list[dict[str, Any]], results: dict[str, Any], result_sha256: str) -> dict[str, Any]:+ control_expected = 0+ control_matched = 0+ text_expected = 0+ text_matched = 0+ text_recognition_correct = 0+ false_text = 0+ false_controls = 0+ center_errors: list[float] = []+ text_ious: list[float] = []+ control_ious: list[float] = []+ control_kind_correct = 0+ control_kind_evaluated = 0+ control_label_eligible = 0+ control_label_correct = 0+ control_label_evaluated = 0+ control_state_correct = 0+ control_state_evaluated = 0+ latency: dict[str, list[float]] = {"cold": [], "warm": []}+ memory: dict[str, list[float]] = {"cold": [], "warm": []}++ for image in corpus:+ measured = results["images"][image["file"]]+ predicted_text = [region for region in measured["regions"] if region["kind"] == "text"]+ predicted_controls = [region for region in measured["regions"] if region["kind"] == "control"]+ text_detection_pairs = _maximum_matching(+ image["text"],+ predicted_text,+ lambda expected, predicted: _geometrically_compatible(expected["bounds"], predicted["bounds"]),+ )+ ocr_pairs = _maximum_matching(+ image["text"],+ predicted_text,+ lambda expected, predicted: expected["text"] == predicted["text"]+ and _geometrically_compatible(expected["bounds"], predicted["bounds"]),+ )+ control_pairs = _maximum_matching(+ image["controls"],+ predicted_controls,+ lambda expected, predicted: _geometrically_compatible(expected["bounds"], predicted["bounds"]),+ )+ text_expected += len(image["text"])+ text_matched += len(ocr_pairs)+ control_expected += len(image["controls"])+ control_matched += len(control_pairs)+ for expected_index, prediction_index in text_detection_pairs:+ expected = image["text"][expected_index]+ prediction = predicted_text[prediction_index]+ center_errors.append(_center_error(expected["bounds"], prediction["bounds"]))+ text_ious.append(_iou(expected["bounds"], prediction["bounds"]))+ text_recognition_correct += prediction["text"] == expected["text"]+ for expected_index, prediction_index in control_pairs:+ expected = image["controls"][expected_index]+ prediction = predicted_controls[prediction_index]+ center_errors.append(_center_error(expected["bounds"], prediction["bounds"]))+ control_ious.append(_iou(expected["bounds"], prediction["bounds"]))+ if prediction["control_kind"] is not None:+ control_kind_evaluated += 1+ control_kind_correct += prediction["control_kind"] == expected["kind"]+ if prediction["state"] is not None:+ control_state_evaluated += 1+ control_state_correct += prediction["state"] == expected["state"]+ if expected["label"] is not None:+ control_label_eligible += 1+ if prediction["label"] is not None:+ control_label_evaluated += 1+ control_label_correct += prediction["label"] == expected["label"]++ false_text += _duplicate_neutral_false_positives(+ image["text"],+ predicted_text,+ text_detection_pairs,+ lambda expected, predicted: _geometrically_compatible(expected["bounds"], predicted["bounds"]),+ lambda prediction: (prediction["text"],),+ )+ false_controls += _duplicate_neutral_false_positives(+ image["controls"],+ predicted_controls,+ control_pairs,+ lambda expected, predicted: _geometrically_compatible(expected["bounds"], predicted["bounds"]),+ lambda prediction: (prediction["control_kind"], prediction["label"], prediction["state"]),+ )+ for sample in measured["samples"]:+ latency[sample["phase"]].append(sample["latency_ms"])+ memory[sample["phase"]].append(float(sample["sampled_process_peak_rss_bytes"]))++ artifact = results["artifact"]+ return {+ "identity": results["identity"],+ "result_sha256": result_sha256,+ "quality": {+ "expected_control_recall": {"matched": control_matched, "expected": control_expected, "ratio": _ratio(control_matched, control_expected)},+ "false_positives": {"count": false_text + false_controls, "text": false_text, "control": false_controls},+ "false_positive_count": {"count": false_text + false_controls, "text": false_text, "control": false_controls},+ "ocr_target_string_recall": {"matched": text_matched, "expected": text_expected, "ratio": _ratio(text_matched, text_expected)},+ "text_detection_iou": _optional_summary(text_ious),+ "text_recognition_exact": {+ "correct": text_recognition_correct,+ "matched": len(text_ious),+ "ratio": _ratio(text_recognition_correct, len(text_ious)),+ },+ "control_detection_iou": _optional_summary(control_ious),+ "control_kind_accuracy": _attribute_accuracy(+ control_kind_correct, control_kind_evaluated, control_matched, control_matched+ ),+ "control_label_accuracy": {+ **_attribute_accuracy(+ control_label_correct, control_label_evaluated, control_matched, control_label_eligible+ ),+ "expected_labeled": control_label_eligible,+ },+ "control_state_accuracy": _attribute_accuracy(+ control_state_correct, control_state_evaluated, control_matched, control_matched+ ),+ "bounding_box_center_error_pixels": _optional_summary(center_errors),+ },+ "performance": {+ "latency_ms": {"cold": _summary(latency["cold"]), "warm": _summary(latency["warm"])},+ "sampled_process_peak_rss_bytes": {+ "cold": {**_summary(memory["cold"]), "max": int(max(memory["cold"]))},+ "warm": {**_summary(memory["warm"]), "max": int(max(memory["warm"]))},+ "overall_max": int(max(memory["cold"] + memory["warm"])),+ },+ },+ "footprint": {+ "artifact_sha256": artifact["sha256"],+ "artifact_size_bytes": artifact["size_bytes"],+ "bound_installed_artifact_bytes": artifact["bound_installed_artifact_bytes"],+ },+ }+++def build_report(manifest_path: Path, rust_results_path: Path, python_results_path: Path) -> dict[str, Any]:+ manifest, manifest_sha256 = read_json(manifest_path)+ corpus = validate_manifest(manifest, manifest_path)+ rust_document, rust_sha256 = read_json(rust_results_path)+ python_document, python_sha256 = read_json(python_results_path)+ rust = validate_results(rust_document, "rust", corpus, rust_results_path)+ python = validate_results(python_document, "python", corpus, python_results_path)+ if rust["identity"]["reference_machine"] != python["identity"]["reference_machine"]:+ raise MeasurementError("Rust and Python results must use the same reference_machine identity")+ if rust["model_comparison"] != python["model_comparison"]:+ raise MeasurementError(+ "Rust and Python results must bind the same model identity and underlying OmniParser/OCR source artifacts"+ )+ image_set_payload = json.dumps(+ [{"sha256": image["sha256"], "width": image["width"], "height": image["height"]} for image in corpus],+ sort_keys=True,+ separators=(",", ":"),+ ).encode()+ return {+ "schema_version": 1,+ "corpus": {+ "schema_version": manifest["schema_version"],+ "version": manifest["corpus_version"],+ "manifest_sha256": manifest_sha256,+ "image_set_sha256": hashlib.sha256(image_set_payload).hexdigest(),+ "image_count": len(corpus),+ },+ "reference_machine": rust["identity"]["reference_machine"],+ "engines": {+ "python": measure_engine(corpus, python, python_sha256),+ "rust": measure_engine(corpus, rust, rust_sha256),+ },+ "thresholds": {"status": "unset", "values": {}},+ }+++def canonical_json(value: Any) -> str:+ return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True, allow_nan=False) + "\n"+++def parse_args(argv: list[str] | None = None) -> argparse.Namespace:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--manifest", required=True, type=Path)+ parser.add_argument("--rust-results", required=True, type=Path)+ parser.add_argument("--python-results", required=True, type=Path)+ parser.add_argument("--output", type=Path, help="write canonical JSON here; stdout when omitted")+ return parser.parse_args(argv)+++def main(argv: list[str] | None = None) -> int:+ args = parse_args(argv)+ try:+ report = build_report(args.manifest, args.rust_results, args.python_results)+ encoded = canonical_json(report)+ if args.output is None:+ sys.stdout.write(encoded)+ else:+ if args.output.is_symlink() or (args.output.exists() and not args.output.is_file()):+ raise MeasurementError(f"output is not a regular file: {args.output}")+ args.output.parent.mkdir(parents=True, exist_ok=True)+ args.output.write_text(encoded, encoding="utf-8")+ except (MeasurementError, OSError) as error:+ print(f"measure_quality: {error}", file=sys.stderr)+ return 2+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/libs/cua-driver/rust/crates/cua-perception/scripts/quality_runner.py b/libs/cua-driver/rust/crates/cua-perception/scripts/quality_runner.pynew file mode 100644index 0000000000..ec1c9cddcc--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/scripts/quality_runner.py@@ -0,0 +1,1153 @@+#!/usr/bin/env python3+"""Run a bound local perception engine and emit measure_quality.py input JSON."""++from __future__ import annotations++import argparse+import base64+import hashlib+import importlib+import json+import math+import os+import selectors+import shutil+import struct+import subprocess+import sys+import tempfile+import threading+import time+import zipfile+from pathlib import Path, PurePosixPath+from typing import Any++import measure_quality+++MAX_FRAME_BYTES = 16 * 1024 * 1024+MAX_BOUND_FILE_BYTES = 2 * 1024 * 1024 * 1024+PROTOCOL = "cua-perception/1"+++class RunnerError(RuntimeError):+ """The runner configuration, artifact set, or engine output is invalid."""+++def _closed(value: Any, required: tuple[str, ...], optional: tuple[str, ...], where: str) -> dict[str, Any]:+ if not isinstance(value, dict):+ raise RunnerError(f"{where} must be an object")+ missing = sorted(set(required) - value.keys())+ unknown = sorted(value.keys() - set(required) - set(optional))+ if missing:+ raise RunnerError(f"{where} is missing fields: {', '.join(missing)}")+ if unknown:+ raise RunnerError(f"{where} has unknown fields: {', '.join(unknown)}")+ return value+++def _string(value: Any, where: str) -> str:+ if not isinstance(value, str) or not value or "\x00" in value:+ raise RunnerError(f"{where} must be a non-empty string")+ return value+++def _number(value: Any, where: str, minimum: float = 0.0, maximum: float | None = None) -> float:+ if isinstance(value, bool) or not isinstance(value, (int, float)):+ raise RunnerError(f"{where} must be a number")+ result = float(value)+ if not math.isfinite(result) or result < minimum or (maximum is not None and result > maximum):+ raise RunnerError(f"{where} is outside its allowed range")+ return result+++def _sha256(path: Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as stream:+ for block in iter(lambda: stream.read(1024 * 1024), b""):+ digest.update(block)+ return digest.hexdigest()+++def _regular_file(root: Path, value: Any, where: str) -> Path:+ name = _string(value, where)+ relative = PurePosixPath(name)+ if relative.is_absolute() or not relative.parts or any(part in {"", ".", ".."} for part in relative.parts) or "\\" in name:+ raise RunnerError(f"{where} must be a safe relative path")+ current = root+ for part in relative.parts:+ current /= part+ if current.is_symlink():+ raise RunnerError(f"{where} must not traverse a symlink")+ path = current.resolve()+ if (path.parent != root and root not in path.parents) or not path.is_file():+ raise RunnerError(f"{where} is not a confined regular file")+ return path+++def _directory(root: Path, value: Any, where: str) -> Path:+ name = _string(value, where)+ relative = PurePosixPath(name)+ if relative.is_absolute() or not relative.parts or any(part in {"", ".", ".."} for part in relative.parts) or "\\" in name:+ raise RunnerError(f"{where} must be a safe relative path")+ current = root+ for part in relative.parts:+ current /= part+ if current.is_symlink():+ raise RunnerError(f"{where} must not traverse a symlink")+ path = current.resolve()+ if (path != root and root not in path.parents) or not path.is_dir():+ raise RunnerError(f"{where} is not a confined directory")+ return path+++def _directory_binding(root: Path, value: Any, where: str) -> dict[str, Any]:+ return {+ "source": _directory(root, value, where),+ "root": root,+ "relative_path": _string(value, where),+ }+++def _verify_bound_directory(binding: dict[str, Any], where: str) -> Path:+ try:+ current = _directory(binding["root"], binding["relative_path"], where)+ except (OSError, RunnerError) as error:+ raise RunnerError(f"{where} changed after configuration validation: {error}") from error+ if current != binding["source"]:+ raise RunnerError(f"{where} changed after configuration validation")+ return current+++def _load_config(path: Path, engine: str) -> dict[str, Any]:+ try:+ raw, _ = measure_quality.read_json(path)+ except Exception as error:+ raise RunnerError(str(error)) from error+ top = _closed(raw, ("schema_version", "identity", "bindings", "execution"), (), "config")+ if top["schema_version"] != 1:+ raise RunnerError("config.schema_version must be 1")+ # Reuse the consumer's strict identity validation so producer and consumer cannot drift.+ try:+ identity = measure_quality._identity(top["identity"], "config.identity")+ except Exception as error:+ raise RunnerError(str(error)) from error+ bindings = _closed(top["bindings"], ("artifacts", "package_artifact_id", "installed_artifact_ids"), (), "config.bindings")+ artifacts = bindings["artifacts"]+ if not isinstance(artifacts, list) or not artifacts:+ raise RunnerError("config.bindings.artifacts must be a non-empty array")+ root = path.parent.resolve()+ checked: list[dict[str, Any]] = []+ seen: set[str] = set()+ for index, raw_artifact in enumerate(artifacts):+ where = f"config.bindings.artifacts[{index}]"+ item = _closed(raw_artifact, ("role", "id", "path", "sha256"), (), where)+ try:+ role = measure_quality._identity_string(item["role"], f"{where}.role")+ artifact_id = measure_quality._identity_string(item["id"], f"{where}.id")+ except Exception as error:+ raise RunnerError(str(error)) from error+ if role not in measure_quality.ARTIFACT_ROLES:+ raise RunnerError(f"{where}.role is unsupported")+ if artifact_id in seen:+ raise RunnerError(f"duplicate artifact id: {artifact_id}")+ seen.add(artifact_id)+ source = _regular_file(root, item["path"], f"{where}.path")+ expected = _string(item["sha256"], f"{where}.sha256")+ actual = _sha256(source)+ if expected != actual:+ raise RunnerError(f"{where}.sha256 does not match the bound file")+ checked.append({+ "role": role,+ "id": artifact_id,+ "source": source,+ "sha256": actual,+ "root": root,+ "relative_path": item["path"],+ })+ installed = bindings["installed_artifact_ids"]+ if not isinstance(installed, list) or not installed or any(not isinstance(item, str) for item in installed):+ raise RunnerError("config.bindings.installed_artifact_ids must be a non-empty string array")+ if len(installed) != len(set(installed)):+ raise RunnerError("config.bindings.installed_artifact_ids must be unique")+ package_id = _string(bindings["package_artifact_id"], "config.bindings.package_artifact_id")+ artifacts_by_id = {item["id"]: item for item in checked}+ if package_id not in artifacts_by_id or artifacts_by_id[package_id]["role"] != "package":+ raise RunnerError("config.bindings.package_artifact_id must identify a package artifact")+ unknown_installed = sorted(set(installed) - artifacts_by_id.keys())+ if unknown_installed:+ raise RunnerError(f"config.bindings.installed_artifact_ids contains unknown ids: {', '.join(unknown_installed)}")+ execution = _validate_execution(top["execution"], engine, root, artifacts_by_id, package_id)+ if engine == "rust" and execution["source_revision"] != identity["model"]["revision"]:+ raise RunnerError("model manifest.identity.source_revision must match config.identity.model.revision")+ return {+ "identity": identity,+ "artifacts": checked,+ "package_artifact_id": package_id,+ "installed_artifact_ids": installed,+ "execution": execution,+ }+++def _artifact_reference(+ value: Any,+ where: str,+ artifacts: dict[str, dict[str, Any]],+ expected_role: str | None = None,+) -> Path:+ artifact_id = _string(value, where)+ if artifact_id not in artifacts:+ raise RunnerError(f"{where} identifies no bound artifact")+ if expected_role is not None and artifacts[artifact_id]["role"] != expected_role:+ raise RunnerError(f"{where} must identify a {expected_role} artifact")+ return artifacts[artifact_id]["source"]+++def _artifact_binding(+ value: Any,+ where: str,+ artifacts: dict[str, dict[str, Any]],+ expected_role: str | None = None,+) -> dict[str, Any]:+ artifact_id = _string(value, where)+ if artifact_id not in artifacts:+ raise RunnerError(f"{where} identifies no bound artifact")+ artifact = artifacts[artifact_id]+ if expected_role is not None and artifact["role"] != expected_role:+ raise RunnerError(f"{where} must identify a {expected_role} artifact")+ return artifact+++def _verify_bound_artifacts(artifacts: list[dict[str, Any]], where: str) -> None:+ for artifact in artifacts:+ artifact_where = f"{where} artifact {artifact['id']}"+ try:+ current = _regular_file(artifact["root"], artifact["relative_path"], artifact_where)+ actual = _sha256(current)+ except (OSError, RunnerError) as error:+ raise RunnerError(f"{artifact_where} changed after configuration validation: {error}") from error+ if current != artifact["source"] or actual != artifact["sha256"]:+ raise RunnerError(f"{artifact_where} changed after configuration validation")+++def _manifest_artifact(manifest_root: Path, value: Any, where: str) -> tuple[Path, str]:+ item = _closed(value, ("path", "sha256"), (), where)+ path = _regular_file(manifest_root, item["path"], f"{where}.path")+ expected = _string(item["sha256"], f"{where}.sha256")+ if len(expected) != 64 or any(character not in "0123456789abcdef" for character in expected):+ raise RunnerError(f"{where}.sha256 must be a lowercase SHA-256 digest")+ return path, expected+++def _require_manifest_binding(+ manifest_root: Path,+ value: Any,+ where: str,+ artifact: dict[str, Any],+) -> None:+ manifest_path, manifest_sha256 = _manifest_artifact(manifest_root, value, where)+ if manifest_path != artifact["source"] or manifest_sha256 != artifact["sha256"]:+ raise RunnerError(f"{where} does not match its configured bound artifact")+++def _validate_conversion_record(path: Path, source: dict[str, Any], output: dict[str, Any]) -> None:+ try:+ value, _ = measure_quality.read_json(path)+ record = _closed(value, ("input", "expected_output"), ("schema_version", "status", "command", "parameters", "toolchain", "patches", "limitations"), "conversion metadata")+ record_input = _closed(record["input"], ("sha256",), ("bundle_path", "size"), "conversion metadata.input")+ record_output = _closed(record["expected_output"], ("sha256",), ("size",), "conversion metadata.expected_output")+ except Exception as error:+ raise RunnerError(f"invalid conversion metadata: {error}") from error+ if record_input["sha256"] != source["sha256"] or record_output["sha256"] != output["sha256"]:+ raise RunnerError("conversion metadata does not bind the configured source and converted detector artifacts")+++def _validate_execution(+ value: Any,+ engine: str,+ root: Path,+ artifacts: dict[str, dict[str, Any]],+ package_artifact_id: str,+) -> dict[str, Any]:+ if engine == "rust":+ item = _closed(+ value,+ (+ "worker_artifact_id", "manifest_artifact_id", "onnx_runtime_artifact_id",+ "source_model_artifact_id", "detector_artifact_id", "ocr_detector_artifact_id",+ "ocr_recognizer_artifact_id", "ocr_dictionary_artifact_id", "extension_id",+ "extension_version", "timeout_seconds",+ ),+ ("conversion_metadata_artifact_id",),+ "config.execution",+ )+ timeout = _number(item["timeout_seconds"], "config.execution.timeout_seconds", 0.001)+ worker = _artifact_reference(item["worker_artifact_id"], "config.execution.worker_artifact_id", artifacts, "worker")+ if not os.access(worker, os.X_OK):+ raise RunnerError("config.execution.worker_artifact_id is not executable")+ manifest_artifact = _artifact_binding(item["manifest_artifact_id"], "config.execution.manifest_artifact_id", artifacts, "model_manifest")+ runtime_artifact = _artifact_binding(item["onnx_runtime_artifact_id"], "config.execution.onnx_runtime_artifact_id", artifacts, "runtime")+ source_artifact = _artifact_binding(item["source_model_artifact_id"], "config.execution.source_model_artifact_id", artifacts, "source_model")+ detector_artifact = _artifact_binding(item["detector_artifact_id"], "config.execution.detector_artifact_id", artifacts, "converted_model")+ ocr_detector_artifact = _artifact_binding(item["ocr_detector_artifact_id"], "config.execution.ocr_detector_artifact_id", artifacts, "ocr_model")+ ocr_recognizer_artifact = _artifact_binding(item["ocr_recognizer_artifact_id"], "config.execution.ocr_recognizer_artifact_id", artifacts, "ocr_model")+ dictionary_artifact = _artifact_binding(item["ocr_dictionary_artifact_id"], "config.execution.ocr_dictionary_artifact_id", artifacts, "ocr_dictionary")+ try:+ manifest, _ = measure_quality.read_json(manifest_artifact["source"])+ identity = _closed(manifest["identity"], ("source_revision",), ("name", "version", "source_url", "license"), "model manifest.identity")+ runtime = _closed(manifest["onnx_runtime"], ("library_sha256",), ("version", "target", "intra_threads"), "model manifest.onnx_runtime")+ detector = _closed(manifest["detector"], ("model",), tuple(key for key in manifest["detector"] if key != "model"), "model manifest.detector")+ ocr = _closed(manifest["ocr"], ("detector", "recognizer", "dictionary"), tuple(key for key in manifest["ocr"] if key not in {"detector", "recognizer", "dictionary"}), "model manifest.ocr")+ ocr_detector = _closed(ocr["detector"], ("model",), tuple(key for key in ocr["detector"] if key != "model"), "model manifest.ocr.detector")+ ocr_recognizer = _closed(ocr["recognizer"], ("model",), tuple(key for key in ocr["recognizer"] if key != "model"), "model manifest.ocr.recognizer")+ except Exception as error:+ raise RunnerError(f"invalid model manifest bindings: {error}") from error+ source_revision = _string(identity["source_revision"], "model manifest.identity.source_revision")+ _require_manifest_binding(manifest_artifact["source"].parent.resolve(), detector["model"], "model manifest.detector.model", detector_artifact)+ _require_manifest_binding(manifest_artifact["source"].parent.resolve(), ocr_detector["model"], "model manifest.ocr.detector.model", ocr_detector_artifact)+ _require_manifest_binding(manifest_artifact["source"].parent.resolve(), ocr_recognizer["model"], "model manifest.ocr.recognizer.model", ocr_recognizer_artifact)+ _require_manifest_binding(manifest_artifact["source"].parent.resolve(), ocr["dictionary"], "model manifest.ocr.dictionary", dictionary_artifact)+ if runtime["library_sha256"] != runtime_artifact["sha256"]:+ raise RunnerError("model manifest.onnx_runtime.library_sha256 does not match the bound runtime artifact")+ conversion_ids = [artifact["id"] for artifact in artifacts.values() if artifact["role"] == "conversion_metadata"]+ conversion_id = item.get("conversion_metadata_artifact_id")+ if conversion_ids and conversion_id is None:+ raise RunnerError("config.execution.conversion_metadata_artifact_id is required when conversion metadata is bound")+ if conversion_id is not None:+ conversion = _artifact_binding(conversion_id, "config.execution.conversion_metadata_artifact_id", artifacts, "conversion_metadata")+ _validate_conversion_record(conversion["source"], source_artifact, detector_artifact)+ executed_artifacts = [+ _artifact_binding(item["worker_artifact_id"], "config.execution.worker_artifact_id", artifacts, "worker"),+ manifest_artifact,+ runtime_artifact,+ detector_artifact,+ ocr_detector_artifact,+ ocr_recognizer_artifact,+ dictionary_artifact,+ ]+ return {+ "worker": worker,+ "manifest": manifest_artifact["source"],+ "runtime": runtime_artifact["source"],+ "source_revision": source_revision,+ "extension_id": _string(item["extension_id"], "config.execution.extension_id"),+ "extension_version": _string(item["extension_version"], "config.execution.extension_version"),+ "timeout": timeout,+ "executed_artifacts": executed_artifacts,+ }+ item = _closed(value, ("python_interpreter_artifact_id", "python_home", "site_packages", "model_artifact_id", "ocr_model_artifact_ids", "cache_dir", "force_device", "box_threshold", "iou_threshold", "use_ocr", "timeout_seconds"), (), "config.execution")+ if not isinstance(item["use_ocr"], bool):+ raise RunnerError("config.execution.use_ocr must be a boolean")+ python = _artifact_reference(item["python_interpreter_artifact_id"], "config.execution.python_interpreter_artifact_id", artifacts, "worker")+ if not os.access(python, os.X_OK):+ raise RunnerError("config.execution.python_interpreter_artifact_id is not executable")+ cache_dir = _directory(root, item["cache_dir"], "config.execution.cache_dir")+ model_cache = cache_dir / "model"+ if not model_cache.is_dir() or model_cache.is_symlink():+ raise RunnerError("config.execution.cache_dir must contain a regular model directory for EasyOCR")+ ocr_ids = item["ocr_model_artifact_ids"]+ if not isinstance(ocr_ids, list) or not ocr_ids or any(not isinstance(value, str) for value in ocr_ids):+ raise RunnerError("config.execution.ocr_model_artifact_ids must be a non-empty string array")+ if len(ocr_ids) != len(set(ocr_ids)):+ raise RunnerError("config.execution.ocr_model_artifact_ids must be unique")+ ocr_models = [+ _artifact_reference(value, "config.execution.ocr_model_artifact_ids", artifacts, "ocr_model")+ for value in ocr_ids+ ]+ if any(path.parent.resolve() != model_cache.resolve() for path in ocr_models):+ raise RunnerError("configured OCR model artifacts must be direct files in cache_dir/model")+ model_artifact = _artifact_binding(item["model_artifact_id"], "config.execution.model_artifact_id", artifacts, "source_model")+ python_artifact = _artifact_binding(item["python_interpreter_artifact_id"], "config.execution.python_interpreter_artifact_id", artifacts, "worker")+ package_artifact = artifacts[package_artifact_id]+ ocr_artifacts = [+ _artifact_binding(value, "config.execution.ocr_model_artifact_ids", artifacts, "ocr_model")+ for value in ocr_ids+ ]+ python_home = _directory_binding(root, item["python_home"], "config.execution.python_home")+ site_packages = _directory_binding(root, item["site_packages"], "config.execution.site_packages")+ cache_binding = _directory_binding(root, item["cache_dir"], "config.execution.cache_dir")+ return {+ "python": python,+ "python_home": python_home["source"],+ "site_packages": site_packages["source"],+ "package": package_artifact["source"],+ "package_sha256": package_artifact["sha256"],+ "model": model_artifact["source"],+ "ocr_models": ocr_models,+ "cache_dir": cache_dir,+ "force_device": _string(item["force_device"], "config.execution.force_device"),+ "box_threshold": _number(item["box_threshold"], "config.execution.box_threshold", 0.0, 1.0),+ "iou_threshold": _number(item["iou_threshold"], "config.execution.iou_threshold", 0.0, 1.0),+ "use_ocr": item["use_ocr"],+ "timeout": _number(item["timeout_seconds"], "config.execution.timeout_seconds", 0.001),+ "executed_artifacts": [python_artifact, package_artifact, model_artifact, *ocr_artifacts],+ "python_artifact": python_artifact,+ "package_artifact": package_artifact,+ "model_artifact": model_artifact,+ "ocr_artifacts": ocr_artifacts,+ "directory_bindings": {+ "python_home": python_home,+ "site_packages": site_packages,+ "cache_dir": cache_binding,+ },+ }+++def _copy_bindings(config: dict[str, Any], output: Path, engine: str) -> list[dict[str, str]]:+ root = output.parent.resolve()+ directory = root / f"{output.stem}.artifacts" / engine+ directory.mkdir(parents=True, exist_ok=True)+ emitted: list[dict[str, str]] = []+ for index, item in enumerate(config["artifacts"]):+ suffix = item["source"].suffix+ destination = directory / f"{index:03d}-{item['id']}{suffix}"+ if destination.exists():+ if destination.is_symlink() or not destination.is_file() or _sha256(destination) != item["sha256"]:+ raise RunnerError(f"artifact output already exists with different content: {destination}")+ else:+ with tempfile.NamedTemporaryFile(dir=directory, prefix=".copy-", delete=False) as stream:+ temporary = Path(stream.name)+ with item["source"].open("rb") as source:+ shutil.copyfileobj(source, stream)+ try:+ if _sha256(temporary) != item["sha256"]:+ raise RunnerError(f"copied artifact hash changed: {item['id']}")+ os.replace(temporary, destination)+ finally:+ if temporary.exists():+ temporary.unlink()+ emitted.append({+ "role": item["role"],+ "id": item["id"],+ "path": destination.relative_to(root).as_posix(),+ "sha256": item["sha256"],+ })+ return emitted+++def _request(image: dict[str, Any], image_path: Path, request_id: str) -> dict[str, Any]:+ data = image_path.read_bytes()+ return {+ "protocol": PROTOCOL,+ "request_id": request_id,+ "method": "parse",+ "params": {+ "capture_id": image["file"],+ "image": {+ "media_type": "image/png",+ "width": image["width"],+ "height": image["height"],+ "byte_length": len(data),+ "data_base64": base64.b64encode(data).decode("ascii"),+ },+ },+ }+++def _validate_closed_corpus(manifest_path: Path, corpus: list[dict[str, Any]]) -> None:+ root = manifest_path.parent.resolve()+ expected = {image["file"] for image in corpus}+ image_roots = {PurePosixPath(name).parts[0] for name in expected}+ actual: set[str] = set()+ for relative_root in image_roots:+ directory = root / relative_root+ if directory.is_symlink() or not directory.is_dir():+ raise RunnerError(f"corpus image root is not a regular directory: {relative_root}")+ for candidate in directory.rglob("*"):+ relative = candidate.relative_to(root).as_posix()+ if candidate.is_symlink():+ raise RunnerError(f"corpus image tree contains a symlink: {relative}")+ if candidate.is_file() and candidate.suffix.lower() in {".png", ".jpg", ".jpeg"}:+ actual.add(relative)+ missing = sorted(expected - actual)+ extra = sorted(actual - expected)+ if missing or extra:+ raise RunnerError(f"corpus image set is not closed; missing={missing}, extra={extra}")+++def _write_frame(stream: Any, value: dict[str, Any], timeout: float | None = None) -> None:+ payload = json.dumps(value, separators=(",", ":"), allow_nan=False).encode("utf-8")+ if not payload or len(payload) > MAX_FRAME_BYTES:+ raise RunnerError("outbound frame has an invalid size")+ framed = struct.pack(">I", len(payload)) + payload+ if timeout is None:+ stream.write(framed)+ stream.flush()+ return+ deadline = time.monotonic() + timeout+ descriptor = stream.fileno()+ previous = os.get_blocking(descriptor)+ selector = selectors.DefaultSelector()+ selector.register(stream, selectors.EVENT_WRITE)+ os.set_blocking(descriptor, False)+ offset = 0+ try:+ while offset < len(framed):+ remaining = deadline - time.monotonic()+ if remaining <= 0 or not selector.select(remaining):+ raise RunnerError("engine request timed out")+ try:+ offset += os.write(descriptor, framed[offset:])+ except BlockingIOError:+ continue+ finally:+ os.set_blocking(descriptor, previous)+ selector.close()+++def _read_exact(stream: Any, size: int, deadline: float) -> bytes:+ data = bytearray()+ selector = selectors.DefaultSelector()+ selector.register(stream, selectors.EVENT_READ)+ try:+ while len(data) < size:+ remaining = deadline - time.monotonic()+ if remaining <= 0 or not selector.select(remaining):+ raise RunnerError("engine response timed out")+ block = os.read(stream.fileno(), size - len(data))+ if not block:+ raise RunnerError("engine returned a truncated frame")+ data.extend(block)+ finally:+ selector.close()+ return bytes(data)+++def _read_frame(stream: Any, timeout: float) -> dict[str, Any]:+ deadline = time.monotonic() + timeout+ size = struct.unpack(">I", _read_exact(stream, 4, deadline))[0]+ if size == 0 or size > MAX_FRAME_BYTES:+ raise RunnerError("engine returned an invalid frame size")+ payload = _read_exact(stream, size, deadline)+ try:+ value = json.loads(payload)+ except (UnicodeDecodeError, json.JSONDecodeError) as error:+ raise RunnerError(f"engine returned invalid JSON: {error}") from error+ if not isinstance(value, dict):+ raise RunnerError("engine response must be an object")+ return value+++def _wait_for_process(process: subprocess.Popen[bytes], timeout: float) -> int:+ deadline = time.monotonic() + timeout+ if hasattr(os, "wait4"):+ while True:+ pid, status, _ = os.wait4(process.pid, os.WNOHANG)+ if pid:+ process.returncode = os.waitstatus_to_exitcode(status)+ return process.returncode+ if time.monotonic() >= deadline:+ process.kill()+ _, status, _ = os.wait4(process.pid, 0)+ process.returncode = os.waitstatus_to_exitcode(status)+ raise RunnerError("engine did not exit before the timeout")+ time.sleep(0.01)+ try:+ returncode = process.wait(timeout=max(0.001, deadline - time.monotonic()))+ except subprocess.TimeoutExpired as error:+ process.kill()+ process.wait()+ raise RunnerError("engine did not exit before the timeout") from error+ return returncode+++def _rss_bytes(pid: int) -> int:+ status = Path(f"/proc/{pid}/status")+ if status.is_file():+ for line in status.read_text(encoding="ascii").splitlines():+ if line.startswith("VmRSS:"):+ return int(line.split()[1]) * 1024+ raise RunnerError("process RSS is absent from /proc status")+ if sys.platform == "darwin":+ measured = subprocess.run(+ ["ps", "-o", "rss=", "-p", str(pid)],+ check=False,+ capture_output=True,+ text=True,+ )+ if measured.returncode != 0 or not measured.stdout.strip().isdigit():+ raise RunnerError("cannot read process RSS with ps")+ return int(measured.stdout.strip()) * 1024+ try:+ import ctypes+ from ctypes import wintypes++ class Counters(ctypes.Structure):+ _fields_ = [("cb", wintypes.DWORD), ("PageFaultCount", wintypes.DWORD)] + [(name, ctypes.c_size_t) for name in ("PeakWorkingSetSize", "WorkingSetSize", "QuotaPeakPagedPoolUsage", "QuotaPagedPoolUsage", "QuotaPeakNonPagedPoolUsage", "QuotaNonPagedPoolUsage", "PagefileUsage", "PeakPagefileUsage", "PrivateUsage")]++ counters = Counters()+ counters.cb = ctypes.sizeof(counters)+ handle = ctypes.windll.kernel32.OpenProcess(0x0400 | 0x0010, False, pid)+ if not handle:+ raise OSError("OpenProcess failed")+ try:+ ok = ctypes.windll.psapi.GetProcessMemoryInfo(handle, ctypes.byref(counters), counters.cb)+ finally:+ ctypes.windll.kernel32.CloseHandle(handle)+ if not ok:+ raise OSError("GetProcessMemoryInfo failed")+ return int(counters.WorkingSetSize)+ except Exception as error:+ raise RunnerError(f"cannot measure process RSS on this platform: {error}") from error+++def _measure_peak_rss(pid: int, operation: Any) -> tuple[Any, int]:+ stop = threading.Event()+ readings: list[int] = []++ def sample() -> None:+ while not stop.is_set():+ try:+ readings.append(_rss_bytes(pid))+ except Exception:+ return+ stop.wait(0.005)++ thread = threading.Thread(target=sample, name="quality-runner-rss", daemon=True)+ thread.start()+ try:+ result = operation()+ finally:+ try:+ readings.append(_rss_bytes(pid))+ except Exception:+ pass+ stop.set()+ thread.join(timeout=1.0)+ if not readings:+ raise RunnerError("process peak RSS was unavailable")+ return result, max(readings)+++def _validate_rust_response(value: dict[str, Any], request_id: str, image: dict[str, Any], extension: tuple[str, str]) -> list[dict[str, Any]]:+ response = _closed(value, ("protocol", "request_id", "status", "result"), (), "worker response")+ if response["protocol"] != PROTOCOL or response["request_id"] != request_id or response["status"] != "ok":+ raise RunnerError("worker response protocol, request id, or status is invalid")+ result = _closed(response["result"], ("capture_id", "image", "coordinate_space", "regions", "runtime", "identity", "text_geometry"), (), "worker result")+ if result["capture_id"] != image["file"] or result["coordinate_space"] != "image_pixels":+ raise RunnerError("worker result capture or coordinate space is invalid")+ image_result = _closed(result["image"], ("sha256", "width", "height"), (), "worker result.image")+ if image_result != {"sha256": image["sha256"], "width": image["width"], "height": image["height"]}:+ raise RunnerError("worker result image identity does not match the corpus")+ identity = result["identity"]+ if not isinstance(identity, dict) or identity.get("extension") != {"id": extension[0], "version": extension[1]}:+ raise RunnerError("worker result extension identity does not match the config")+ regions = result["regions"]+ if not isinstance(regions, list):+ raise RunnerError("worker result.regions must be an array")+ return [_normalize_rust_region(region, index, image) for index, region in enumerate(regions)]+++def _normalize_rust_region(value: Any, index: int, image: dict[str, Any]) -> dict[str, Any]:+ where = f"worker result.regions[{index}]"+ item = _closed(value, ("id", "kind", "bounds", "confidence"), ("text", "label", "class_id"), where)+ if item["kind"] not in {"text", "icon"}:+ raise RunnerError(f"{where}.kind is unsupported")+ bounds = _closed(item["bounds"], ("x", "y", "width", "height"), (), f"{where}.bounds")+ normalized_bounds = {key: _number(bounds[key], f"{where}.bounds.{key}") for key in ("x", "y", "width", "height")}+ if normalized_bounds["width"] <= 0 or normalized_bounds["height"] <= 0 or normalized_bounds["x"] + normalized_bounds["width"] > image["width"] or normalized_bounds["y"] + normalized_bounds["height"] > image["height"]:+ raise RunnerError(f"{where}.bounds is empty or outside the image")+ result: dict[str, Any] = {"id": _string(item["id"], f"{where}.id"), "kind": item["kind"], "bounds": normalized_bounds, "confidence": _number(item["confidence"], f"{where}.confidence", 0.0, 1.0)}+ if item["kind"] == "text":+ result["text"] = _string(item.get("text"), f"{where}.text")+ elif "label" in item:+ result["label"] = _string(item["label"], f"{where}.label")+ return result+++def _run_rust_image(execution: dict[str, Any], image: dict[str, Any], image_path: Path) -> dict[str, Any]:+ _verify_bound_artifacts(execution["executed_artifacts"], "Rust execution")+ command = [str(execution["worker"]), "--manifest", str(execution["manifest"]), "--onnx-runtime-library", str(execution["runtime"]), "--extension-id", execution["extension_id"], "--extension-version", execution["extension_version"]]+ with tempfile.TemporaryFile() as stderr:+ start = time.perf_counter_ns()+ process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=stderr)+ assert process.stdin is not None and process.stdout is not None+ try:+ cold_id = "quality-cold"+ def cold_call() -> dict[str, Any]:+ _write_frame(process.stdin, _request(image, image_path, cold_id), execution["timeout"])+ return _read_frame(process.stdout, execution["timeout"])++ cold_response, cold_peak = _measure_peak_rss(process.pid, cold_call)+ cold_ms = (time.perf_counter_ns() - start) / 1_000_000+ regions = _validate_rust_response(cold_response, cold_id, image, (execution["extension_id"], execution["extension_version"]))+ warm_start = time.perf_counter_ns()+ warm_id = "quality-warm"+ def warm_call() -> dict[str, Any]:+ _write_frame(process.stdin, _request(image, image_path, warm_id), execution["timeout"])+ return _read_frame(process.stdout, execution["timeout"])++ warm_response, warm_peak = _measure_peak_rss(process.pid, warm_call)+ warm_ms = (time.perf_counter_ns() - warm_start) / 1_000_000+ warm_regions = _validate_rust_response(warm_response, warm_id, image, (execution["extension_id"], execution["extension_version"]))+ if warm_regions != regions:+ raise RunnerError("worker returned different cold and warm regions")+ process.stdin.close()+ process.stdout.close()+ returncode = _wait_for_process(process, execution["timeout"])+ stderr.seek(0)+ error_text = stderr.read().decode("utf-8", errors="replace").strip()+ if returncode != 0:+ raise RunnerError(f"worker exited {returncode}: {error_text}")+ return _image_result(+ image, regions, "source_pixels", image["width"], image["height"],+ cold_ms, warm_ms, cold_peak, warm_peak,+ )+ except Exception:+ if process.poll() is None:+ process.kill()+ try:+ _wait_for_process(process, 5.0)+ except Exception:+ pass+ raise+++def _image_result(image: dict[str, Any], regions: list[dict[str, Any]], space: str, width: float, height: float, cold_ms: float, warm_ms: float, cold_peak: int, warm_peak: int) -> dict[str, Any]:+ return {+ "file": image["file"],+ "image_sha256": image["sha256"],+ "coordinate_space": {"space": space, "origin": "top_left", "bbox_format": "x_y_width_height", "width": width, "height": height},+ "regions": regions,+ "samples": [+ {"phase": "cold", "latency_ms": cold_ms, "sampled_process_peak_rss_bytes": cold_peak},+ {"phase": "warm", "latency_ms": warm_ms, "sampled_process_peak_rss_bytes": warm_peak},+ ],+ }+++def _stage_verified_file(+ artifact: dict[str, Any],+ destination: Path,+ where: str,+ *,+ maximum_bytes: int = MAX_BOUND_FILE_BYTES,+) -> Path:+ source = artifact["source"]+ destination.parent.mkdir(parents=True, exist_ok=True)+ digest = hashlib.sha256()+ total = 0+ try:+ if source.is_symlink() or not source.is_file():+ raise RunnerError(f"{where} is not a regular file")+ with source.open("rb") as input_stream, destination.open("xb") as output_stream:+ while block := input_stream.read(1024 * 1024):+ total += len(block)+ if total > maximum_bytes:+ raise RunnerError(f"{where} exceeds its size limit")+ digest.update(block)+ output_stream.write(block)+ except OSError as error:+ raise RunnerError(f"cannot stage {where}: {error}") from error+ if digest.hexdigest() != artifact["sha256"]:+ raise RunnerError(f"{where} changed while it was staged")+ destination.chmod(0o400)+ return destination+++def _extract_bound_wheel(wheel: Path, expected_sha256: str, destination: Path) -> None:+ if _sha256(wheel) != expected_sha256:+ raise RunnerError("bound Python wheel changed after configuration validation")+ try:+ with zipfile.ZipFile(wheel) as archive:+ members = archive.infolist()+ if len(members) > 100_000 or sum(member.file_size for member in members) > 2 * 1024 * 1024 * 1024:+ raise RunnerError("bound Python wheel exceeds extraction limits")+ seen: set[str] = set()+ for member in members:+ name = member.filename+ relative = PurePosixPath(name)+ if member.flag_bits & 1 or relative.is_absolute() or not relative.parts or any(part in {"", ".", ".."} for part in relative.parts) or "\\" in name:+ raise RunnerError("bound Python wheel contains an unsafe member")+ normalized = relative.as_posix().rstrip("/")+ if normalized in seen:+ raise RunnerError("bound Python wheel contains duplicate members")+ seen.add(normalized)+ mode = member.external_attr >> 16+ if (mode & 0o170000) == 0o120000:+ raise RunnerError("bound Python wheel contains a symlink")+ target = destination.joinpath(*relative.parts)+ if member.is_dir():+ target.mkdir(parents=True, exist_ok=True)+ continue+ target.parent.mkdir(parents=True, exist_ok=True)+ with archive.open(member) as source, target.open("xb") as output:+ shutil.copyfileobj(source, output)+ except (OSError, zipfile.BadZipFile) as error:+ raise RunnerError(f"cannot extract bound Python wheel: {error}") from error+++def _python_child_invocation(execution: dict[str, Any], options: dict[str, Any]) -> tuple[list[str], dict[str, str]]:+ environment = {key: value for key, value in os.environ.items() if not key.startswith("PYTHON")}+ environment.update({+ "PYTHONHOME": str(execution["python_home"]),+ "PYTHONNOUSERSITE": "1",+ "HF_HUB_OFFLINE": "1",+ "TRANSFORMERS_OFFLINE": "1",+ "EASYOCR_MODULE_PATH": str(execution["cache_dir"]),+ })+ command = [+ str(execution["python"]),+ "-S",+ str(Path(__file__).resolve()),+ "--python-child",+ json.dumps(options, separators=(",", ":")),+ ]+ return command, environment+++def _verify_python_directories(execution: dict[str, Any], where: str) -> None:+ bindings = execution["directory_bindings"]+ _verify_bound_directory(bindings["python_home"], f"{where} python_home")+ _verify_bound_directory(bindings["site_packages"], f"{where} site_packages")+ cache_dir = _verify_bound_directory(bindings["cache_dir"], f"{where} cache_dir")+ model_cache = cache_dir / "model"+ if model_cache.is_symlink() or not model_cache.is_dir():+ raise RunnerError(f"{where} cache_dir/model changed after configuration validation")+++def _run_python_image(execution: dict[str, Any], image: dict[str, Any], image_path: Path) -> dict[str, Any]:+ _verify_bound_artifacts(execution["executed_artifacts"], "Python execution")+ _verify_python_directories(execution, "Python execution")+ with tempfile.TemporaryDirectory(prefix="cua-quality-python-") as temporary, tempfile.TemporaryFile() as stderr:+ runtime_root = Path(temporary).resolve()+ staged_wheel = _stage_verified_file(+ execution["package_artifact"], runtime_root / "package.whl", "bound Python wheel"+ )+ staged_model = _stage_verified_file(+ execution["model_artifact"], runtime_root / "model.pt", "bound detector model"+ )+ staged_cache = runtime_root / "cache"+ for artifact in execution["ocr_artifacts"]:+ _stage_verified_file(+ artifact,+ staged_cache / "model" / artifact["source"].name,+ f"bound OCR model {artifact['id']}",+ )+ import_root = runtime_root / "wheel"+ import_root.mkdir()+ _extract_bound_wheel(staged_wheel, execution["package_sha256"], import_root)+ image_artifact = {"source": image_path, "sha256": image["sha256"]}+ staged_image = _stage_verified_file(+ image_artifact,+ runtime_root / "input.png",+ "corpus image",+ maximum_bytes=MAX_FRAME_BYTES,+ )+ options = {+ "import_root": str(import_root), "site_packages": str(execution["site_packages"]),+ "python_home_binding": {+ "root": str(execution["directory_bindings"]["python_home"]["root"]),+ "relative_path": execution["directory_bindings"]["python_home"]["relative_path"],+ "source": str(execution["python_home"]),+ },+ "site_packages_binding": {+ "root": str(execution["directory_bindings"]["site_packages"]["root"]),+ "relative_path": execution["directory_bindings"]["site_packages"]["relative_path"],+ "source": str(execution["site_packages"]),+ },+ "model": str(staged_model), "cache_dir": str(staged_cache),+ "force_device": execution["force_device"], "box_threshold": execution["box_threshold"], "iou_threshold": execution["iou_threshold"],+ "use_ocr": execution["use_ocr"], "image": str(staged_image), "image_sha256": image["sha256"],+ }+ child_execution = dict(execution)+ child_execution["cache_dir"] = staged_cache+ command, environment = _python_child_invocation(child_execution, options)+ _verify_bound_artifacts([execution["python_artifact"]], "Python launch")+ _verify_python_directories(execution, "Python launch")+ cold_start = time.perf_counter_ns()+ process = subprocess.Popen(+ command,+ stdout=subprocess.PIPE,+ stderr=stderr,+ env=environment,+ )+ assert process.stdout is not None+ try:+ cold_response, cold_peak = _measure_peak_rss(+ process.pid, lambda: _read_frame(process.stdout, execution["timeout"])+ )+ cold_ms = (time.perf_counter_ns() - cold_start) / 1_000_000+ if cold_response.get("status") != "ok":+ raise RunnerError(f"Python engine failed: {cold_response.get('error', 'invalid cold response')}")+ cold = _closed(cold_response, ("status", "phase", "regions"), (), "Python cold response")+ if cold["phase"] != "cold":+ raise RunnerError("Python engine returned an invalid cold response")+ warm_start = time.perf_counter_ns()+ warm_response, warm_peak = _measure_peak_rss(+ process.pid, lambda: _read_frame(process.stdout, execution["timeout"])+ )+ warm_ms = (time.perf_counter_ns() - warm_start) / 1_000_000+ process.stdout.close()+ returncode = _wait_for_process(process, execution["timeout"])+ stderr.seek(0)+ error_text = stderr.read().decode("utf-8", errors="replace").strip()+ if returncode != 0 or warm_response.get("status") != "ok":+ raise RunnerError(f"Python engine failed: {warm_response.get('error', error_text)}")+ warm = _closed(warm_response, ("status", "phase", "regions"), (), "Python warm response")+ if warm["phase"] != "warm" or warm["regions"] != cold["regions"]:+ raise RunnerError("Python engine returned an invalid or inconsistent warm response")+ return _image_result(+ image, cold["regions"], "source_pixels", image["width"], image["height"],+ cold_ms, warm_ms, cold_peak, warm_peak,+ )+ except Exception:+ if process.poll() is None:+ process.kill()+ try:+ _wait_for_process(process, 5.0)+ except Exception:+ pass+ raise+++def _python_regions(result: Any, width: int, height: int) -> list[dict[str, Any]]:+ elements = getattr(result, "elements", None)+ if not isinstance(elements, list):+ raise RunnerError("OmniParser result.elements must be a list")+ regions: list[dict[str, Any]] = []+ for index, element in enumerate(elements):+ where = f"OmniParser result.elements[{index}]"+ kind = getattr(element, "type", None)+ if kind not in {"text", "icon"}:+ raise RunnerError(f"{where}.type is unsupported")+ bbox = getattr(element, "bbox", None)+ coordinates = getattr(bbox, "coordinates", None)+ if not isinstance(coordinates, (list, tuple)) or len(coordinates) != 4:+ raise RunnerError(f"{where}.bbox must provide normalized xyxy coordinates")+ x1, y1, x2, y2 = (_number(value, f"{where}.bbox", 0.0, 1.0) for value in coordinates)+ if x2 <= x1 or y2 <= y1:+ raise RunnerError(f"{where}.bbox is empty or inverted")+ region: dict[str, Any] = {+ "id": str(getattr(element, "id", index + 1)),+ "kind": kind,+ "bounds": {+ "x": x1 * width,+ "y": y1 * height,+ "width": (x2 - x1) * width,+ "height": (y2 - y1) * height,+ },+ "confidence": _number(getattr(element, "confidence", None), f"{where}.confidence", 0.0, 1.0),+ }+ if kind == "text":+ region["text"] = _string(getattr(element, "content", None), f"{where}.content")+ regions.append(region)+ return regions+++def _is_som_module(name: str) -> bool:+ return name == "som" or name.startswith("som.")+++def _clear_som_modules() -> None:+ for name in tuple(sys.modules):+ if _is_som_module(name):+ del sys.modules[name]+++def _bound_module_path(value: Any, import_root: Path, where: str, *, directory: bool = False) -> Path:+ if not isinstance(value, (str, os.PathLike)):+ raise RunnerError(f"{where} does not identify a real path")+ try:+ path = Path(value).resolve(strict=True)+ except (OSError, RuntimeError, TypeError, ValueError) as error:+ raise RunnerError(f"{where} does not identify a real path") from error+ if path != import_root and import_root not in path.parents:+ raise RunnerError(f"{where} is outside the extracted bound wheel")+ if (directory and not path.is_dir()) or (not directory and not path.is_file()):+ raise RunnerError(f"{where} does not identify a real {'directory' if directory else 'file'}")+ return path+++def _validate_bound_som_modules(import_root: Path) -> None:+ names = sorted(name for name in sys.modules if _is_som_module(name))+ if "som" not in names:+ raise RunnerError("bound som package is not loaded")+ for name in names:+ module = sys.modules[name]+ if module is None or getattr(module, "__name__", None) != name:+ raise RunnerError(f"loaded {name} module has an invalid module identity")+ module_file = _bound_module_path(getattr(module, "__file__", None), import_root, f"loaded {name} module")+ spec = getattr(module, "__spec__", None)+ loader = getattr(module, "__loader__", None)+ if spec is None or spec.name != name or spec.loader is None or loader is not spec.loader:+ raise RunnerError(f"loaded {name} module has an invalid loader specification")+ origin = _bound_module_path(spec.origin, import_root, f"loaded {name} module origin")+ if origin != module_file:+ raise RunnerError(f"loaded {name} module origin does not match its file")+ get_filename = getattr(loader, "get_filename", None)+ if not callable(get_filename):+ raise RunnerError(f"loaded {name} module loader cannot prove its source file")+ try:+ loader_file = _bound_module_path(get_filename(name), import_root, f"loaded {name} module loader source")+ except (ImportError, AttributeError) as error:+ raise RunnerError(f"loaded {name} module loader cannot prove its source file") from error+ if loader_file != module_file:+ raise RunnerError(f"loaded {name} module loader source does not match its file")+ search_locations = spec.submodule_search_locations+ module_path = getattr(module, "__path__", None)+ if (search_locations is None) != (module_path is None):+ raise RunnerError(f"loaded {name} module has inconsistent package search paths")+ if search_locations is not None:+ locations = list(search_locations)+ paths = list(module_path)+ if not locations or locations != paths:+ raise RunnerError(f"loaded {name} package has invalid search paths")+ for index, location in enumerate(locations):+ _bound_module_path(location, import_root, f"loaded {name} package search path[{index}]", directory=True)+++def _child_bound_directory(value: Any, where: str) -> Path:+ item = _closed(value, ("root", "relative_path", "source"), (), where)+ root = Path(_string(item["root"], f"{where}.root"))+ expected = Path(_string(item["source"], f"{where}.source"))+ path = _directory(root, item["relative_path"], f"{where}.relative_path")+ if path != expected:+ raise RunnerError(f"{where} changed after launch")+ return path+++def _png_dimensions_bytes(data: bytes) -> tuple[int, int]:+ header = data[:24]+ if len(header) != 24 or header[:8] != b"\x89PNG\r\n\x1a\n" or header[12:16] != b"IHDR":+ raise RunnerError("corpus image is not a PNG with an IHDR header")+ return struct.unpack(">II", header[16:24])+++def _python_child(encoded: str) -> int:+ try:+ options = json.loads(encoded)+ os.environ.update({"HF_HUB_OFFLINE": "1", "TRANSFORMERS_OFFLINE": "1", "EASYOCR_MODULE_PATH": options["cache_dir"]})+ import socket++ class OfflineSocket(socket.socket):+ def connect(self, address: Any) -> None:+ raise OSError("network access is disabled by quality_runner")++ def connect_ex(self, address: Any) -> int:+ raise OSError("network access is disabled by quality_runner")++ socket.socket = OfflineSocket+ import_candidate = Path(options["import_root"])+ if import_candidate.is_symlink():+ raise RunnerError("extracted bound wheel is not a regular directory")+ import_root = import_candidate.resolve(strict=True)+ _child_bound_directory(options["python_home_binding"], "configured python_home")+ site_packages = _child_bound_directory(options["site_packages_binding"], "configured site_packages")+ if str(site_packages) != options["site_packages"]:+ raise RunnerError("configured site_packages does not match its binding")+ cache_candidate = Path(options["cache_dir"])+ if cache_candidate.is_symlink() or not cache_candidate.is_dir():+ raise RunnerError("staged cache_dir is not a regular directory")+ cache_dir = cache_candidate.resolve(strict=True)+ model_cache = cache_dir / "model"+ if model_cache.is_symlink() or not model_cache.is_dir():+ raise RunnerError("staged cache_dir/model is not a regular directory")+ sys.path.append(str(site_packages))+ sys.path.insert(0, str(import_root))+ _clear_som_modules()+ som = importlib.import_module("som")+ _validate_bound_som_modules(import_root)+ image_path = Path(options["image"])+ if image_path.is_symlink() or not image_path.is_file():+ raise RunnerError("staged corpus image is not a regular file")+ image = image_path.read_bytes()+ if len(image) > MAX_FRAME_BYTES:+ raise RunnerError("staged corpus image exceeds its size limit")+ if hashlib.sha256(image).hexdigest() != options["image_sha256"]:+ raise RunnerError("staged corpus image does not match the manifest SHA-256")+ width, height = _png_dimensions_bytes(image)++ def cold_call() -> tuple[Any, Any]:+ parser_instance = som.OmniParser(model_path=options["model"], cache_dir=str(cache_dir), force_device=options["force_device"])+ _validate_bound_som_modules(import_root)+ result = parser_instance.parse(image, box_threshold=options["box_threshold"], iou_threshold=options["iou_threshold"], use_ocr=options["use_ocr"])+ _validate_bound_som_modules(import_root)+ return parser_instance, result++ parser, cold = cold_call()+ if getattr(getattr(parser, "detector", None), "model", None) is None:+ raise RunnerError("OmniParser did not load the configured detector model")+ if options["use_ocr"] and getattr(getattr(parser, "ocr", None), "reader", None) is None:+ raise RunnerError("OmniParser did not load its OCR models from the configured cache")+ regions = _python_regions(cold, width, height)+ _write_frame(sys.stdout.buffer, {"status": "ok", "phase": "cold", "regions": regions})+ warm = parser.parse(image, box_threshold=options["box_threshold"], iou_threshold=options["iou_threshold"], use_ocr=options["use_ocr"])+ _validate_bound_som_modules(import_root)+ if _python_regions(warm, width, height) != regions:+ raise RunnerError("OmniParser returned different cold and warm regions")+ _write_frame(sys.stdout.buffer, {"status": "ok", "phase": "warm", "regions": regions})+ return 0+ except Exception as error:+ try:+ _write_frame(sys.stdout.buffer, {"status": "error", "error": str(error)})+ except Exception:+ pass+ return 1+++def build_results(engine: str, config_path: Path, manifest_path: Path, output: Path) -> dict[str, Any]:+ config_path = config_path.absolute()+ manifest_path = manifest_path.absolute()+ config = _load_config(config_path, engine)+ try:+ manifest, _ = measure_quality.read_json(manifest_path)+ corpus = measure_quality.validate_manifest(manifest, manifest_path)+ _validate_closed_corpus(manifest_path, corpus)+ except Exception as error:+ raise RunnerError(str(error)) from error+ images = []+ for image in corpus:+ image_path = manifest_path.parent.resolve() / PurePosixPath(image["file"])+ if engine == "rust":+ images.append(_run_rust_image(config["execution"], image, image_path))+ else:+ images.append(_run_python_image(config["execution"], image, image_path))+ bindings = {+ "artifacts": _copy_bindings(config, output, engine),+ "package_artifact_id": config["package_artifact_id"],+ "installed_artifact_ids": config["installed_artifact_ids"],+ }+ result = {"schema_version": 1, "engine": engine, "identity": config["identity"], "bindings": bindings, "images": images}+ try:+ measure_quality.validate_results(result, engine, corpus, output)+ except Exception as error:+ raise RunnerError(f"generated results failed validation: {error}") from error+ return result+++def main(argv: list[str] | None = None) -> int:+ args_list = sys.argv[1:] if argv is None else argv+ if args_list[:1] == ["--python-child"]:+ if len(args_list) != 2:+ return 2+ return _python_child(args_list[1])+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--engine", required=True, choices=("rust", "python"))+ parser.add_argument("--config", required=True, type=Path)+ parser.add_argument("--manifest", required=True, type=Path)+ parser.add_argument("--output", required=True, type=Path)+ args = parser.parse_args(args_list)+ try:+ if args.output.is_symlink() or (args.output.exists() and not args.output.is_file()):+ raise RunnerError(f"output is not a regular file: {args.output}")+ output = args.output.absolute()+ output.parent.mkdir(parents=True, exist_ok=True)+ result = build_results(args.engine, args.config, args.manifest, output)+ encoded = measure_quality.canonical_json(result)+ with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=output.parent, prefix=f".{output.name}.", delete=False) as stream:+ temporary = Path(stream.name)+ stream.write(encoded)+ try:+ os.replace(temporary, output)+ finally:+ if temporary.exists():+ temporary.unlink()+ return 0+ except (RunnerError, OSError) as error:+ print(f"quality_runner: {error}", file=sys.stderr)+ return 2+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/libs/cua-driver/rust/crates/cua-perception/scripts/tests/test_artifact_tooling.py b/libs/cua-driver/rust/crates/cua-perception/scripts/tests/test_artifact_tooling.pynew file mode 100644index 0000000000..5cbc83100e--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/scripts/tests/test_artifact_tooling.py@@ -0,0 +1,413 @@+from __future__ import annotations++import argparse+import io+import json+import sys+import tarfile+import tempfile+import unittest+from pathlib import Path+from unittest import mock++SCRIPT_DIR = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(SCRIPT_DIR))++from artifact_tooling import ( # noqa: E402+ ArtifactError,+ CRATE_DIR,+ LOCK_PATH,+ binary_target,+ extension_identity,+ sha256,+ static_verify,+ verify_corresponding_sources,+)+import assemble_bundle # noqa: E402+import verify_bundle # noqa: E402+from assemble_bundle import immutable_url # noqa: E402+from verify_bundle import source_inspection # noqa: E402+++def write(path: Path, contents: bytes) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(contents)+++def linux_header(payload: bytes = b"") -> bytes:+ header = bytearray(64)+ header[:4] = b"\x7fELF"+ header[4] = 2+ header[5] = 1+ header[18:20] = (62).to_bytes(2, "little")+ return bytes(header) + payload+++def windows_header() -> bytes:+ header = bytearray(72)+ header[:2] = b"MZ"+ header[0x3C:0x40] = (64).to_bytes(4, "little")+ header[64:68] = b"PE\0\0"+ header[68:70] = (0x8664).to_bytes(2, "little")+ return bytes(header)+++def macos_arm64_header() -> bytes:+ return b"\xcf\xfa\xed\xfe" + (0x0100000C).to_bytes(4, "little") + b"\0" * 56+++class ArtifactToolingTests(unittest.TestCase):+ def test_conversion_recipe_pins_input_exporter_sources_command_and_no_patches(self) -> None:+ lock = json.loads(LOCK_PATH.read_text())+ recipe = json.loads((CRATE_DIR / "models/conversion-recipe.json").read_text())+ materials = lock["corresponding_source"]+ source_input = next(item for item in materials if item["content_kind"] == "model-source-input")+ exporters = [item for item in materials if item["content_kind"] == "exporter-source"]+ self.assertEqual(source_input["sha256"], recipe["input"]["sha256"])+ self.assertEqual(source_input["size"], recipe["input"]["size"])+ self.assertEqual(recipe["patches"], [])+ self.assertEqual(recipe["command"][1], "models/export_omniparser_detector.py")+ self.assertEqual(+ {item["filename"].split("-", 1)[0] for item in exporters},+ {"ultralytics", "pytorch", "torchvision", "onnx", "onnxslim"},+ )+ for item in materials:+ immutable_url(item["url"])+ self.assertEqual(len(item["sha256"]), 64)+ self.assertGreater(item["size"], 0)+ self.assertEqual(recipe["expected_output"]["sha256"], "d8a876bf7f9fb73d7da9432904ade7fa78e092e9a91674e5a2806b45562a9ab2")++ def source_fixture(self, root: Path) -> tuple[dict, dict]:+ archive = root / "source/cua-perception-source.tar.gz"+ archive.parent.mkdir(parents=True)+ with tarfile.open(archive, "w:gz") as package:+ contents = b"recipe\n"+ info = tarfile.TarInfo("cua/libs/cua-driver/rust/crates/cua-perception/models/conversion-recipe.json")+ info.size = len(contents)+ package.addfile(info, io.BytesIO(contents))+ model = root / "source/upstream/omniparser-icon-detect-model.pt"+ write(model, b"exact-source-model")+ artifacts = [+ {"kind": "source", "name": archive.name, "path": archive.relative_to(root).as_posix(), "sha256": sha256(archive), "size": archive.stat().st_size, "license": {"spdx": "MIT"}},+ {"kind": "source", "name": model.name, "path": model.relative_to(root).as_posix(), "sha256": sha256(model), "size": model.stat().st_size, "license": {"spdx": "AGPL-3.0-only"}},+ ]+ ledger = {"schemaVersion": 1, "sources": [+ {"artifact": archive.name, "artifactSha256": sha256(archive), "artifactSize": archive.stat().st_size, "license": "MIT", "revision": "a" * 40, "sourceOfferStatus": "bundled-review-only", "contentKind": "cua-source", "format": "tar.gz", "requiredPaths": ["libs/cua-driver/rust/crates/cua-perception/models/conversion-recipe.json"]},+ {"artifact": model.name, "artifactSha256": sha256(model), "artifactSize": model.stat().st_size, "license": "AGPL-3.0-only", "revision": "b" * 40, "sourceOfferStatus": "bundled-review-only", "contentKind": "model-source-input", "format": "file"},+ ]}+ (root / "source-ledger.json").write_text(json.dumps(ledger), encoding="utf-8")+ manifest = {"artifacts": artifacts, "sourceLedger": "source-ledger.json"}+ lock = {"corresponding_source": [{"filename": model.name, "bundle_path": artifacts[1]["path"], "sha256": sha256(model), "size": model.stat().st_size, "revision": "b" * 40, "content_kind": "model-source-input"}]}+ return manifest, lock++ def test_source_verifier_rejects_missing_and_tampered_source_input(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ root = Path(temporary)+ manifest, lock = self.source_fixture(root)+ verify_corresponding_sources(root, manifest, lock)+ model = root / "source/upstream/omniparser-icon-detect-model.pt"+ model.write_bytes(b"tampered")+ with self.assertRaisesRegex(ArtifactError, "size mismatch"):+ verify_corresponding_sources(root, manifest, lock)+ model.unlink()+ with self.assertRaisesRegex(ArtifactError, "bundle path is not a regular file"):+ verify_corresponding_sources(root, manifest, lock)++ def test_preinstall_inspection_reports_bundled_source_locations(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ root = Path(temporary)+ manifest, _ = self.source_fixture(root)+ sources = source_inspection(root, manifest)+ self.assertEqual(+ {item["location"] for item in sources},+ {+ "source/cua-perception-source.tar.gz",+ "source/upstream/omniparser-icon-detect-model.pt",+ },+ )+ self.assertTrue(all(item["status"] == "bundled-review-only" for item in sources))++ def test_source_verifier_rejects_ledger_mismatch_and_missing_recipe(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ root = Path(temporary)+ manifest, lock = self.source_fixture(root)+ ledger_path = root / "source-ledger.json"+ ledger = json.loads(ledger_path.read_text())+ ledger["sources"][1]["artifactSha256"] = "0" * 64+ ledger_path.write_text(json.dumps(ledger))+ with self.assertRaisesRegex(ArtifactError, "ledger hash or size differs"):+ verify_corresponding_sources(root, manifest, lock)+ ledger["sources"][1]["artifactSha256"] = manifest["artifacts"][1]["sha256"]+ ledger["sources"][0]["requiredPaths"] = ["models/missing-recipe.json"]+ ledger_path.write_text(json.dumps(ledger))+ with self.assertRaisesRegex(ArtifactError, "lacks required path"):+ verify_corresponding_sources(root, manifest, lock)++ def test_binary_headers_are_target_specific(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ root = Path(temporary)+ fixtures = {+ "linux": (linux_header(), "x86_64-unknown-linux-gnu"),+ "windows": (windows_header(), "x86_64-pc-windows-msvc"),+ "macos": (macos_arm64_header(), "aarch64-apple-darwin"),+ }+ for name, (contents, target) in fixtures.items():+ path = root / name+ write(path, contents)+ self.assertEqual(binary_target(path), target)++ def test_only_immutable_approved_download_coordinates_are_accepted(self) -> None:+ immutable_url(+ "https://huggingface.co/PaddlePaddle/PP-OCRv5_mobile_det_onnx/resolve/"+ "e6f4fa85f00e168c862bc462aebca69eef9b3d3d/inference.onnx"+ )+ immutable_url(+ "https://github.com/microsoft/onnxruntime/releases/download/v1.26.0/"+ "onnxruntime-osx-arm64-1.26.0.tgz"+ )+ for url in (+ "http://example.invalid/model.onnx",+ "https://huggingface.co/example/model/resolve/main/model.onnx",+ "https://github.com/microsoft/onnxruntime/releases/latest/download/runtime.zip",+ ):+ with self.assertRaises(ArtifactError):+ immutable_url(url)++ def test_static_verifier_rejects_tampered_runtime(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ bundle = Path(temporary)+ worker = bundle / "cua-perception"+ runtime = bundle / "libonnxruntime.so"+ write(worker, linux_header(b"worker"))+ write(runtime, linux_header(b"runtime"))+ model_files = []+ for name in ("icon.onnx", "ocr-det.onnx", "ocr-rec.onnx", "dict.yml"):+ path = bundle / "models" / name+ write(path, name.encode())+ model_files.append(path)+ model_manifest = {+ "schema_version": 1,+ "identity": {"name": "test", "version": "1", "source_url": "x", "source_revision": "x", "license": "x"},+ "onnx_runtime": {"version": "1.26.0", "library_sha256": sha256(runtime), "intra_threads": 1},+ "detector": {"model": {"path": "models/icon.onnx", "sha256": sha256(model_files[0])}},+ "ocr": {+ "detector": {"model": {"path": "models/ocr-det.onnx", "sha256": sha256(model_files[1])}},+ "recognizer": {"model": {"path": "models/ocr-rec.onnx", "sha256": sha256(model_files[2])}},+ "dictionary": {"path": "models/dict.yml", "sha256": sha256(model_files[3])},+ },+ }+ (bundle / "model-manifest.json").write_text(json.dumps(model_manifest), encoding="utf-8")+ entries = []+ for kind, path in (("worker", worker), ("runtime", runtime)):+ entries.append({"kind": kind, "name": path.name, "path": path.name, "sha256": sha256(path), "size": path.stat().st_size})+ lock_artifacts = {+ "icon-detect": ("icon.onnx", sha256(model_files[0])),+ "ocr-detect": ("ocr-det.onnx", sha256(model_files[1])),+ "ocr-recognize": ("ocr-rec.onnx", sha256(model_files[2])),+ "ocr-dictionary": ("dict.yml", sha256(model_files[3])),+ }+ for role, (name, digest) in lock_artifacts.items():+ model_path = bundle / "models" / name+ entries.append({+ "kind": "dictionary" if role == "ocr-dictionary" else "model",+ "role": role, "name": name, "path": "models/" + name,+ "sha256": digest, "size": model_path.stat().st_size,+ })+ manifest = {+ "component": "cua-perception",+ "version": "0.1.0",+ "target": {"triple": "x86_64-unknown-linux-gnu"},+ "artifacts": entries,+ }+ (bundle / "artifact-manifest.json").write_text(json.dumps(manifest), encoding="utf-8")+ real_read_json = __import__("artifact_tooling").read_json+ synthetic_lock = {+ "onnx_runtime": {"targets": {"x86_64-unknown-linux-gnu": {+ "filename": runtime.name, "sha256": sha256(runtime), "size": runtime.stat().st_size,+ }}},+ "artifacts": [+ {"role": role, "filename": name, "sha256": digest}+ for role, (name, digest) in lock_artifacts.items()+ ],+ }++ def patched_read_json(path: Path):+ return synthetic_lock if path.name == "artifacts.lock.json" else real_read_json(path)++ with mock.patch("artifact_tooling.read_json", side_effect=patched_read_json):+ static_verify(bundle, require_host=False)+ runtime.write_bytes(runtime.read_bytes() + b"tampered")+ with self.assertRaisesRegex(ArtifactError, "size mismatch"):+ static_verify(bundle, require_host=False)++ def test_wrong_platform_worker_is_rejected_before_execution(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ path = Path(temporary) / "worker.exe"+ write(path, windows_header())+ self.assertEqual(binary_target(path), "x86_64-pc-windows-msvc")+ self.assertNotEqual(binary_target(path), "x86_64-unknown-linux-gnu")++ def test_extension_identity_requires_exact_component_and_stable_version(self) -> None:+ manifest = {"component": "cua-perception", "version": "0.1.0"}+ self.assertEqual(extension_identity(manifest), ("cua-perception", "0.1.0"))+ for invalid in (+ {"component": "cua-driver", "version": "0.1.0"},+ {"component": "cua-perception", "version": "0.1.0-dev"},+ {"component": "cua-perception"},+ ):+ with self.assertRaisesRegex(ArtifactError, "invalid extension identity"):+ extension_identity(invalid)++ def test_assembly_exercises_validated_identity_before_sealing_manifest(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ root = Path(temporary)+ inputs = root / "inputs"+ inputs.mkdir()+ roles = (+ "icon-detect",+ "ocr-detect",+ "ocr-recognize",+ "ocr-dictionary",+ )+ artifacts = []+ for role in roles:+ path = inputs / f"{role}.bin"+ write(path, role.encode())+ artifacts.append(+ {+ "role": role,+ "filename": path.name,+ "sha256": sha256(path),+ "size": path.stat().st_size,+ "origin": "https://example.invalid/source",+ "revision": "b" * 40,+ "license": "MIT",+ "verification_status": "reviewed",+ "source_sha256": "c" * 64,+ }+ )++ target = "x86_64-unknown-linux-gnu"+ lock = {+ "onnx_runtime": {+ "version": "1.26.0",+ "targets": {+ target: {+ "worker_filename": "cua-perception",+ "filename": "libonnxruntime.so",+ "sha256": "d" * 64,+ "size": 7,+ "os": "linux",+ "arch": "x86_64",+ "archive_url": "https://example.invalid/runtime",+ "archive_sha256": "e" * 64,+ }+ },+ },+ "artifacts": artifacts,+ "corresponding_source": [],+ }+ worker = root / "worker"+ fixture = root / "fixture.png"+ write(worker, b"worker")+ write(fixture, b"fixture")+ output = root / "bundle"+ args = argparse.Namespace(+ target=target,+ worker=worker,+ inputs=inputs,+ cache=root / "cache",+ real_parse_fixture=fixture,+ source_sha="a" * 40,+ version="1.2.3",+ output=output,+ )+ events = []++ def fake_extract_runtime(_lock, _target, _cache, destination):+ write(destination, b"runtime")++ def fake_corresponding_source(_repo, _revision, destination):+ write(destination, b"source")++ def fake_exercise(bundle, bundle_target, known_answer, identity, report_dir):+ self.assertEqual(bundle_target, target)+ self.assertEqual(known_answer, bundle / "verification/known-answer.png")+ self.assertEqual(identity, ("cua-perception", "1.2.3"))+ self.assertFalse((bundle / "artifact-manifest.json").exists())+ for name in ("health", "self-test", "real-parse"):+ write(report_dir / f"{name}.json", f"{name}\n".encode())+ events.append("exercise")+ return {}++ def fake_static_verify(bundle):+ manifest_path = bundle / "artifact-manifest.json"+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))+ self.assertEqual(extension_identity(manifest), ("cua-perception", "1.2.3"))+ reports = {+ item["role"]: item+ for item in manifest["artifacts"]+ if item["kind"] == "supplied-verification-report"+ }+ self.assertEqual(set(reports), {"health", "self-test", "real-parse"})+ for role, entry in reports.items():+ report = bundle / entry["path"]+ self.assertEqual(entry["sha256"], sha256(report), role)+ self.assertEqual(entry["size"], report.stat().st_size, role)+ sums = (bundle / "SHA256SUMS").read_text(encoding="utf-8")+ self.assertIn(" artifact-manifest.json\n", sums)+ events.append("static-verify")+ return manifest++ def fake_archive(_bundle, destination):+ write(destination, b"archive")+ events.append("archive")++ with (+ mock.patch("assemble_bundle.read_json", return_value=lock),+ mock.patch("assemble_bundle.host_target", return_value=target),+ mock.patch("assemble_bundle.require_binary_target"),+ mock.patch("assemble_bundle.repository_root", return_value=root),+ mock.patch("assemble_bundle.extract_runtime", side_effect=fake_extract_runtime),+ mock.patch(+ "assemble_bundle.corresponding_source",+ side_effect=fake_corresponding_source,+ ),+ mock.patch("assemble_bundle.exercise_bundle", side_effect=fake_exercise),+ mock.patch("assemble_bundle.static_verify", side_effect=fake_static_verify),+ mock.patch(+ "assemble_bundle.deterministic_bundle_archive",+ side_effect=fake_archive,+ ),+ ):+ bundle, archive = assemble_bundle.assemble(args)++ self.assertEqual(bundle, output)+ self.assertEqual(archive, root / f"cua-perception-1.2.3-{target}.tar.gz")+ self.assertEqual(events, ["exercise", "static-verify", "archive"])++ def test_installed_verification_uses_identity_from_final_manifest(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ bundle = Path(temporary)+ manifest = {+ "component": "cua-perception",+ "version": "2.3.4",+ "target": {"triple": "x86_64-unknown-linux-gnu"},+ }++ def fake_exercise(_bundle, _target, _fixture, identity):+ self.assertEqual(identity, ("cua-perception", "2.3.4"))+ return {}++ with (+ mock.patch.object(sys, "argv", ["verify_bundle.py", str(bundle)]),+ mock.patch("verify_bundle.static_verify", return_value=manifest),+ mock.patch("verify_bundle.source_inspection", return_value=[]),+ mock.patch("verify_bundle.exercise_bundle", side_effect=fake_exercise),+ mock.patch("builtins.print"),+ ):+ self.assertEqual(verify_bundle.main(), 0)+++if __name__ == "__main__":+ unittest.main()diff --git a/libs/cua-driver/rust/crates/cua-perception/scripts/tests/test_measure_quality.py b/libs/cua-driver/rust/crates/cua-perception/scripts/tests/test_measure_quality.pynew file mode 100644index 0000000000..2877ad4e27--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/scripts/tests/test_measure_quality.py@@ -0,0 +1,422 @@+from __future__ import annotations++import hashlib+import importlib.util+import json+import struct+import subprocess+import sys+import tempfile+import unittest+import zlib+from pathlib import Path+++SCRIPT = Path(__file__).resolve().parents[1] / "measure_quality.py"+SPEC = importlib.util.spec_from_file_location("measure_quality", SCRIPT)+assert SPEC and SPEC.loader+measure_quality = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(measure_quality)+++def sha256(path: Path) -> str:+ return hashlib.sha256(path.read_bytes()).hexdigest()+++def write(path: Path, data: bytes) -> Path:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(data)+ return path+++def png(path: Path, width: int = 100, height: int = 80) -> None:+ def chunk(kind: bytes, data: bytes) -> bytes:+ return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)++ rows = b"".join(b"\x00" + b"\x00\x00\x00" * width for _ in range(height))+ write(+ path,+ b"\x89PNG\r\n\x1a\n"+ + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))+ + chunk(b"IDAT", zlib.compress(rows))+ + chunk(b"IEND", b""),+ )+++class QualityFixture:+ def __init__(self, root: Path) -> None:+ self.root = root+ self.image = root / "images/screen.png"+ png(self.image)+ self.manifest_path = root / "manifest.json"+ self.manifest = {+ "schema_version": 1,+ "corpus_version": "test-1",+ "license": "MIT",+ "coordinate_system": {"space": "source_pixels", "origin": "top_left", "bbox_format": "x_y_width_height"},+ "metric_definitions": {+ "text_detection_iou": {"unit": "ratio", "description": "Text IoU."},+ "control_detection_iou": {"unit": "ratio", "description": "Control IoU."},+ "control_kind_accuracy": {"unit": "ratio", "description": "Kind accuracy."},+ },+ "images": [{+ "file": "images/screen.png", "sha256": sha256(self.image), "width": 100, "height": 80,+ "scenario_tags": ["synthetic"],+ "expected": {+ "text": [+ {"id": "save-text", "text": "Save", "bbox": [10, 10, 20, 10], "role": "label"},+ {"id": "cancel-text", "text": "Cancel", "bbox": [50, 10, 30, 10], "role": "label"},+ ],+ "controls": [+ {"id": "save", "kind": "button", "label": "Save", "bbox": [8, 30, 30, 20], "state": "enabled"},+ {"id": "cancel", "kind": "button", "label": "Cancel", "bbox": [50, 30, 35, 20], "state": "enabled"},+ ],+ },+ }],+ }+ self.manifest_path.write_text(json.dumps(self.manifest), encoding="utf-8")++ def artifact(self, engine: str, role: str, artifact_id: str, data: bytes) -> dict:+ prefix = "shared" if artifact_id == "omniparser_source" else engine+ path = write(self.root / f"bound/{prefix}/{artifact_id}", data)+ return {"role": role, "id": artifact_id, "path": path.relative_to(self.root).as_posix(), "sha256": sha256(path)}++ def artifacts(self, engine: str) -> list[dict]:+ values = [+ self.artifact(engine, "source_model", "omniparser_source", b"same-upstream-model-pt"),+ self.artifact(engine, "runtime", "runtime", f"{engine}-runtime".encode()),+ self.artifact(engine, "worker", "worker", f"{engine}-worker".encode()),+ self.artifact(engine, "package", "package", f"{engine}-package".encode()),+ self.artifact(engine, "dependency_lock", "dependency_lock", f"{engine}-lock".encode()),+ ]+ if engine == "rust":+ values.extend([+ self.artifact(engine, "converted_model", "omniparser_onnx", b"rust-converted-detector"),+ self.artifact(engine, "ocr_model", "ppocr_detector", b"ppocr-det"),+ self.artifact(engine, "ocr_model", "ppocr_recognizer", b"ppocr-rec"),+ self.artifact(engine, "ocr_dictionary", "ppocr_dictionary", b"ppocr-dict"),+ ])+ else:+ values.extend([+ self.artifact(engine, "ocr_model", "easyocr_detector", b"easyocr-detector"),+ self.artifact(engine, "ocr_model", "easyocr_recognizer", b"easyocr-recognizer"),+ ])+ return values++ def results(self, engine: str) -> dict:+ return {+ "schema_version": 1,+ "engine": engine,+ "identity": {+ "model": {"id": "omniparser", "version": "2", "revision": "upstream-rev"},+ "runtime": {"id": f"{engine}-runtime", "version": "1"},+ "adapter": {"id": f"{engine}-adapter", "version": "1"},+ "reference_machine": {"id": "bench-1", "os": "linux", "arch": "x86_64", "cpu": "test cpu", "memory_bytes": 1024},+ },+ "bindings": {+ "artifacts": self.artifacts(engine),+ "package_artifact_id": "package",+ "installed_artifact_ids": ["worker", "runtime", "omniparser_source"],+ },+ "images": [{+ "file": "images/screen.png", "image_sha256": sha256(self.image),+ "coordinate_space": {"space": "source_pixels", "origin": "top_left", "bbox_format": "x_y_width_height", "width": 100, "height": 80},+ "regions": [+ {"kind": "text", "bounds": {"x": 12, "y": 10, "width": 20, "height": 10}, "text": " Save ", "confidence": 0.01},+ {"kind": "text", "bounds": {"x": 11, "y": 10, "width": 20, "height": 10}, "text": "Save", "confidence": 0.99},+ {"kind": "text", "bounds": {"x": 50, "y": 10, "width": 30, "height": 10}, "text": "cancel"},+ {"kind": "icon", "bounds": {"x": 10, "y": 31, "width": 30, "height": 20}, "control_kind": "button", "label": "Save", "state": "enabled"},+ {"kind": "control", "bounds": {"x": 9, "y": 30, "width": 30, "height": 20}, "control_kind": "button", "label": "Save", "state": "enabled"},+ {"kind": "control", "bounds": {"x": 90, "y": 60, "width": 5, "height": 5}, "control_kind": "button", "label": "Other", "state": "enabled"},+ ],+ "samples": [+ {"phase": "cold", "latency_ms": 10.0, "sampled_process_peak_rss_bytes": 1000},+ {"phase": "warm", "latency_ms": 4.0, "sampled_process_peak_rss_bytes": 800},+ ],+ }],+ }++ def write_results(self, engine: str, value: dict | None = None) -> Path:+ path = self.root / f"{engine}.json"+ path.write_text(json.dumps(value or self.results(engine)), encoding="utf-8")+ return path+++class MeasureQualityTests(unittest.TestCase):+ def test_metrics_are_one_to_one_duplicate_neutral_and_artifact_backed(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ fixture = QualityFixture(Path(temporary))+ report = measure_quality.build_report(+ fixture.manifest_path, fixture.write_results("rust"), fixture.write_results("python")+ )+ self.assertEqual(report["thresholds"], {"status": "unset", "values": {}})+ for engine in ("rust", "python"):+ measured = report["engines"][engine]+ quality = measured["quality"]+ self.assertEqual(quality["expected_control_recall"], {"matched": 1, "expected": 2, "ratio": 0.5})+ self.assertEqual(quality["ocr_target_string_recall"], {"matched": 1, "expected": 2, "ratio": 0.5})+ self.assertEqual(quality["false_positives"], {"count": 1, "text": 0, "control": 1})+ self.assertEqual(quality["false_positive_count"], quality["false_positives"])+ self.assertEqual(quality["text_detection_iou"]["count"], 2)+ self.assertEqual(quality["text_recognition_exact"], {"correct": 1, "matched": 2, "ratio": 0.5})+ self.assertEqual(quality["control_detection_iou"]["count"], 1)+ self.assertEqual(quality["control_kind_accuracy"], {+ "status": "available", "correct": 1, "matched": 1, "evaluated": 1,+ "coverage": {"available": 1, "eligible": 1, "ratio": 1.0}, "ratio": 1.0,+ })+ self.assertEqual(quality["control_label_accuracy"]["ratio"], 1.0)+ self.assertEqual(quality["control_state_accuracy"]["ratio"], 1.0)+ self.assertEqual(quality["bounding_box_center_error_pixels"]["count"], 3)+ self.assertEqual(measured["performance"]["latency_ms"]["warm"]["median"], 4.0)+ self.assertEqual(measured["performance"]["sampled_process_peak_rss_bytes"]["overall_max"], 1000)+ self.assertNotIn("peak_memory_bytes", measured["performance"])+ package = fixture.root / f"bound/{engine}/package"+ installed = [fixture.root / f"bound/{engine}/worker", fixture.root / f"bound/{engine}/runtime", fixture.root / "bound/shared/omniparser_source"]+ self.assertEqual(measured["footprint"]["artifact_size_bytes"], package.stat().st_size)+ self.assertEqual(measured["footprint"]["bound_installed_artifact_bytes"], sum(path.stat().st_size for path in installed))+ self.assertNotIn("installed_size_bytes", measured["footprint"])+ encoded = measure_quality.canonical_json(report)+ self.assertNotIn(temporary, encoded)+ self.assertNotIn("bound/", encoded)++ def test_control_attribute_accuracy_reports_coverage_and_skips_omitted_fields(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ fixture = QualityFixture(Path(temporary))+ for engine in ("rust", "python"):+ results = fixture.results(engine)+ image = results["images"][0]+ image["regions"] = [+ *[region for region in image["regions"] if region["kind"] == "text"],+ {"kind": "control", "bounds": {"x": 9, "y": 30, "width": 30, "height": 20}},+ {+ "kind": "control",+ "bounds": {"x": 50, "y": 30, "width": 35, "height": 20},+ "control_kind": "button",+ "label": "Wrong",+ "state": "disabled",+ },+ ]+ fixture.write_results(engine, results)++ report = measure_quality.build_report(+ fixture.manifest_path, fixture.root / "rust.json", fixture.root / "python.json"+ )+ quality = report["engines"]["rust"]["quality"]+ self.assertEqual(quality["expected_control_recall"], {"matched": 2, "expected": 2, "ratio": 1.0})+ self.assertEqual(quality["control_detection_iou"]["count"], 2)+ self.assertEqual(quality["control_kind_accuracy"], {+ "status": "available", "correct": 1, "matched": 2, "evaluated": 1,+ "coverage": {"available": 1, "eligible": 2, "ratio": 0.5}, "ratio": 1.0,+ })+ self.assertEqual(quality["control_label_accuracy"], {+ "status": "available", "correct": 0, "matched": 2, "evaluated": 1,+ "coverage": {"available": 1, "eligible": 2, "ratio": 0.5}, "ratio": 0.0,+ "expected_labeled": 2,+ })+ self.assertEqual(quality["control_state_accuracy"], {+ "status": "available", "correct": 0, "matched": 2, "evaluated": 1,+ "coverage": {"available": 1, "eligible": 2, "ratio": 0.5}, "ratio": 0.0,+ })++ def test_control_attribute_accuracy_is_unavailable_when_matched_regions_omit_fields(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ fixture = QualityFixture(Path(temporary))+ for engine in ("rust", "python"):+ results = fixture.results(engine)+ image = results["images"][0]+ image["regions"] = [+ *[region for region in image["regions"] if region["kind"] == "text"],+ {"kind": "control", "bounds": {"x": 9, "y": 30, "width": 30, "height": 20}},+ ]+ fixture.write_results(engine, results)++ report = measure_quality.build_report(+ fixture.manifest_path, fixture.root / "rust.json", fixture.root / "python.json"+ )+ quality = report["engines"]["rust"]["quality"]+ for name in ("control_kind_accuracy", "control_label_accuracy", "control_state_accuracy"):+ metric = quality[name]+ self.assertEqual(metric["status"], "unavailable")+ self.assertEqual(metric["matched"], 1)+ self.assertEqual(metric["evaluated"], 0)+ self.assertEqual(metric["coverage"], {"available": 0, "eligible": 1, "ratio": 0.0})+ self.assertIsNone(metric["ratio"])++ def test_generic_control_and_icon_families_leave_control_kind_unknown(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ fixture = QualityFixture(Path(temporary))+ for engine, kind in (("rust", "control"), ("python", "icon")):+ results = fixture.results(engine)+ image = results["images"][0]+ image["regions"] = [+ {"kind": kind, "bounds": {"x": 8, "y": 30, "width": 30, "height": 20}},+ ]+ fixture.write_results(engine, results)++ report = measure_quality.build_report(+ fixture.manifest_path, fixture.root / "rust.json", fixture.root / "python.json"+ )+ rust_quality = report["engines"]["rust"]["quality"]+ python_quality = report["engines"]["python"]["quality"]+ self.assertEqual(rust_quality, python_quality)+ self.assertEqual(rust_quality["expected_control_recall"], {"matched": 1, "expected": 2, "ratio": 0.5})+ self.assertEqual(rust_quality["control_kind_accuracy"], {+ "status": "unavailable", "correct": 0, "matched": 1, "evaluated": 0,+ "coverage": {"available": 0, "eligible": 1, "ratio": 0.0}, "ratio": None,+ })++ def test_center_containment_does_not_match_when_iou_is_below_threshold(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ fixture = QualityFixture(Path(temporary))+ for engine in ("rust", "python"):+ results = fixture.results(engine)+ results["images"][0]["regions"] = [+ {+ "kind": "text",+ "bounds": {"x": 0, "y": 0, "width": 100, "height": 80},+ "text": "Save",+ },+ {+ "kind": "icon",+ "bounds": {"x": 0, "y": 0, "width": 100, "height": 80},+ "control_kind": "button",+ },+ ]+ fixture.write_results(engine, results)++ report = measure_quality.build_report(+ fixture.manifest_path, fixture.root / "rust.json", fixture.root / "python.json"+ )+ quality = report["engines"]["rust"]["quality"]+ self.assertEqual(quality["expected_control_recall"], {"matched": 0, "expected": 2, "ratio": 0.0})+ self.assertEqual(quality["ocr_target_string_recall"], {"matched": 0, "expected": 2, "ratio": 0.0})+ self.assertEqual(quality["text_detection_iou"]["count"], 0)+ self.assertEqual(quality["control_detection_iou"]["count"], 0)+ self.assertEqual(quality["false_positives"], {"count": 2, "text": 1, "control": 1})++ def test_distinct_ocr_conversion_and_runtime_artifacts_are_comparable(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ fixture = QualityFixture(Path(temporary))+ report = measure_quality.build_report(+ fixture.manifest_path, fixture.write_results("rust"), fixture.write_results("python")+ )+ rust = report["engines"]["rust"]["identity"]+ python = report["engines"]["python"]["identity"]+ self.assertNotEqual(rust["model"]["artifacts_sha256"], python["model"]["artifacts_sha256"])+ self.assertNotEqual(rust["runtime"]["artifacts_sha256"], python["runtime"]["artifacts_sha256"])++ def test_source_model_hash_or_revision_mismatch_is_rejected(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ fixture = QualityFixture(Path(temporary))+ rust = fixture.write_results("rust")+ python_results = fixture.results("python")+ python_results["identity"]["model"]["revision"] = "different-rev"+ python = fixture.write_results("python", python_results)+ with self.assertRaisesRegex(measure_quality.MeasurementError, "same model identity"):+ measure_quality.build_report(fixture.manifest_path, rust, python)++ python_results = fixture.results("python")+ source = next(item for item in python_results["bindings"]["artifacts"] if item["id"] == "omniparser_source")+ alternate = write(fixture.root / "bound/python/alternate-source", b"different-upstream-model")+ source["path"] = alternate.relative_to(fixture.root).as_posix()+ source["sha256"] = sha256(alternate)+ python = fixture.write_results("python", python_results)+ with self.assertRaisesRegex(measure_quality.MeasurementError, "same model identity"):+ measure_quality.build_report(fixture.manifest_path, rust, python)++ def test_adapter_coordinates_are_converted_to_source_pixels(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ fixture = QualityFixture(Path(temporary))+ rust_results = fixture.results("rust")+ image = rust_results["images"][0]+ image["coordinate_space"].update({"space": "adapter_pixels", "width": 50, "height": 40})+ for region in image["regions"]:+ for field in ("x", "y", "width", "height"):+ region["bounds"][field] /= 2+ report = measure_quality.build_report(+ fixture.manifest_path,+ fixture.write_results("rust", rust_results),+ fixture.write_results("python"),+ )+ self.assertEqual(report["engines"]["rust"]["quality"], report["engines"]["python"]["quality"])++ def test_bound_bytes_are_hashed_and_symlinks_are_rejected(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ fixture = QualityFixture(Path(temporary))+ corpus = measure_quality.validate_manifest(fixture.manifest, fixture.manifest_path)+ results = fixture.results("rust")+ package = next(item for item in results["bindings"]["artifacts"] if item["id"] == "package")+ (fixture.root / package["path"]).write_bytes(b"tampered")+ with self.assertRaisesRegex(measure_quality.MeasurementError, "does not match the bound file"):+ measure_quality.validate_results(results, "rust", corpus, fixture.root / "rust.json")+ results = fixture.results("rust")+ runtime = next(item for item in results["bindings"]["artifacts"] if item["id"] == "runtime")+ runtime_path = fixture.root / runtime["path"]+ target = fixture.root / "actual-runtime"+ runtime_path.replace(target)+ runtime_path.symlink_to(target)+ with self.assertRaisesRegex(measure_quality.MeasurementError, "must not traverse a symlink"):+ measure_quality.validate_results(results, "rust", corpus, fixture.root / "rust.json")++ def test_closed_structures_path_free_identities_and_exact_roles(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ fixture = QualityFixture(Path(temporary))+ corpus = measure_quality.validate_manifest(fixture.manifest, fixture.manifest_path)+ results = fixture.results("rust")+ results["unknown"] = True+ with self.assertRaisesRegex(measure_quality.MeasurementError, "unknown fields"):+ measure_quality.validate_results(results, "rust", corpus, fixture.root / "rust.json")+ results.pop("unknown")+ results["identity"]["model"]["id"] = "/private/model"+ with self.assertRaisesRegex(measure_quality.MeasurementError, "path-free identity"):+ measure_quality.validate_results(results, "rust", corpus, fixture.root / "rust.json")+ results = fixture.results("rust")+ results["bindings"]["artifacts"][0]["role"] = "arbitrary"+ with self.assertRaisesRegex(measure_quality.MeasurementError, "role is unsupported"):+ measure_quality.validate_results(results, "rust", corpus, fixture.root / "rust.json")++ def test_rejects_unsafe_json_coordinates_and_missing_samples(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ fixture = QualityFixture(Path(temporary))+ duplicate = fixture.root / "duplicate.json"+ duplicate.write_text('{"a":1,"a":2}', encoding="utf-8")+ with self.assertRaisesRegex(measure_quality.MeasurementError, "duplicate JSON key"):+ measure_quality.read_json(duplicate)+ corpus = measure_quality.validate_manifest(fixture.manifest, fixture.manifest_path)+ results = fixture.results("rust")+ results["images"][0]["coordinate_space"]["width"] = 99+ with self.assertRaisesRegex(measure_quality.MeasurementError, "must match the corpus"):+ measure_quality.validate_results(results, "rust", corpus, fixture.root / "rust.json")+ results = fixture.results("rust")+ results["images"][0]["samples"] = [results["images"][0]["samples"][0]]+ with self.assertRaisesRegex(measure_quality.MeasurementError, "exactly one cold and one warm"):+ measure_quality.validate_results(results, "rust", corpus, fixture.root / "rust.json")+ results = fixture.results("rust")+ results["images"][0]["samples"].append(dict(results["images"][0]["samples"][1]))+ with self.assertRaisesRegex(measure_quality.MeasurementError, "exactly one cold and one warm"):+ measure_quality.validate_results(results, "rust", corpus, fixture.root / "rust.json")++ def test_cli_is_repeatable_and_zero_annotations_have_null_ratios(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ fixture = QualityFixture(Path(temporary))+ fixture.manifest["images"][0]["expected"] = {"text": [], "controls": []}+ fixture.manifest_path.write_text(json.dumps(fixture.manifest), encoding="utf-8")+ for engine in ("rust", "python"):+ results = fixture.results(engine)+ results["images"][0]["regions"] = []+ fixture.write_results(engine, results)+ first = fixture.root / "first.json"+ second = fixture.root / "second.json"+ args = [str(SCRIPT), "--manifest", str(fixture.manifest_path), "--rust-results", str(fixture.root / "rust.json"), "--python-results", str(fixture.root / "python.json")]+ subprocess.run([sys.executable, *args, "--output", str(first)], check=True)+ subprocess.run([sys.executable, *args, "--output", str(second)], check=True)+ self.assertEqual(first.read_bytes(), second.read_bytes())+ quality = json.loads(first.read_text())["engines"]["rust"]["quality"]+ self.assertIsNone(quality["expected_control_recall"]["ratio"])+ self.assertIsNone(quality["control_kind_accuracy"]["ratio"])+ self.assertEqual(quality["control_kind_accuracy"]["status"], "unavailable")+ self.assertEqual(quality["text_detection_iou"]["count"], 0)+++if __name__ == "__main__":+ unittest.main()diff --git a/libs/cua-driver/rust/crates/cua-perception/scripts/tests/test_quality_runner.py b/libs/cua-driver/rust/crates/cua-perception/scripts/tests/test_quality_runner.pynew file mode 100644index 0000000000..9db4f6cb43--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/scripts/tests/test_quality_runner.py@@ -0,0 +1,552 @@+from __future__ import annotations++import hashlib+import importlib.util+import json+import os+import shutil+import stat+import struct+import subprocess+import sys+import tempfile+import textwrap+import unittest+import zipfile+import zlib+from pathlib import Path+from unittest import mock+++SCRIPT = Path(__file__).resolve().parents[1] / "quality_runner.py"+sys.path.insert(0, str(SCRIPT.parent))+SPEC = importlib.util.spec_from_file_location("quality_runner", SCRIPT)+assert SPEC and SPEC.loader+quality_runner = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(quality_runner)+++def write(path: Path, data: bytes) -> Path:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(data)+ return path+++def sha256(path: Path) -> str:+ return hashlib.sha256(path.read_bytes()).hexdigest()+++def png(path: Path, width: int = 100, height: int = 80) -> Path:+ def chunk(kind: bytes, data: bytes) -> bytes:+ return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)++ rows = b"".join(b"\x00" + b"\x00\x00\x00" * width for _ in range(height))+ return write(+ path,+ b"\x89PNG\r\n\x1a\n"+ + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))+ + chunk(b"IDAT", zlib.compress(rows))+ + chunk(b"IEND", b""),+ )+++def executable(path: Path, source: str) -> Path:+ path.write_text(textwrap.dedent(source), encoding="utf-8")+ path.chmod(path.stat().st_mode | stat.S_IXUSR)+ return path+++def wheel(path: Path, module_source: str) -> Path:+ path.parent.mkdir(parents=True, exist_ok=True)+ with zipfile.ZipFile(path, "w") as archive:+ archive.writestr("som/__init__.py", textwrap.dedent(module_source))+ archive.writestr("cua_som-1.0.dist-info/METADATA", "Name: cua-som\nVersion: 1.0\n")+ return path+++def bound(root: Path, artifact_id: str, path: Path) -> dict[str, object]:+ return {+ "id": artifact_id,+ "source": path.resolve(),+ "sha256": sha256(path),+ "root": root.resolve(),+ "relative_path": path.relative_to(root).as_posix(),+ }+++def directory_binding(root: Path, path: Path) -> dict[str, object]:+ return {+ "source": path.resolve(),+ "root": root.resolve(),+ "relative_path": path.relative_to(root).as_posix(),+ }+++def json_directory_binding(root: Path, path: Path) -> dict[str, str]:+ binding = directory_binding(root, path)+ return {key: str(value) for key, value in binding.items()}+++class QualityRunnerTests(unittest.TestCase):+ def test_python_invocation_disables_site_startup_and_inherited_python_paths(self) -> None:+ execution = {+ "python": Path("/bound/python"),+ "python_home": Path("/bound/python-home"),+ "cache_dir": Path("/bound/cache"),+ }+ with mock.patch.dict(os.environ, {"PYTHONPATH": "/unbound", "PYTHONSTARTUP": "/unbound/startup.py"}):+ command, environment = quality_runner._python_child_invocation(execution, {"import_root": "/bound/wheel"})+ self.assertEqual(command[1:3], ["-S", str(SCRIPT)])+ self.assertNotIn("PYTHONPATH", environment)+ self.assertNotIn("PYTHONSTARTUP", environment)+ self.assertEqual(environment["PYTHONHOME"], "/bound/python-home")++ def test_rust_worker_uses_real_framing_and_one_process_for_cold_and_warm(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ root = Path(temporary)+ image_path = png(root / "images/screen.png")+ image = {"file": "images/screen.png", "sha256": sha256(image_path), "width": 100, "height": 80}+ worker = executable(+ root / "worker",+ f"""\+ #!{sys.executable}+ import base64, hashlib, json, os, struct, sys+ count = 0+ while True:+ prefix = sys.stdin.buffer.read(4)+ if not prefix:+ break+ size = struct.unpack('>I', prefix)[0]+ request = json.loads(sys.stdin.buffer.read(size))+ image = base64.b64decode(request['params']['image']['data_base64'])+ count += 1+ result = {{+ 'protocol': 'cua-perception/1', 'request_id': request['request_id'], 'status': 'ok',+ 'result': {{+ 'capture_id': request['params']['capture_id'],+ 'image': {{'sha256': hashlib.sha256(image).hexdigest(), 'width': 100, 'height': 80}},+ 'coordinate_space': 'image_pixels',+ 'regions': [{{'id': 'text-1', 'kind': 'text', 'bounds': {{'x': 10, 'y': 8, 'width': 20, 'height': 16}}, 'text': 'Save', 'confidence': 0.9}}],+ 'runtime': 'onnx_runtime_cpu',+ 'identity': {{'extension': {{'id': 'cua-perception', 'version': '1.0.0'}}, 'pid': os.getpid(), 'count': count}},+ 'text_geometry': 'axis_aligned_bounds'+ }}+ }}+ payload = json.dumps(result, separators=(',', ':')).encode()+ sys.stdout.buffer.write(struct.pack('>I', len(payload)) + payload)+ sys.stdout.buffer.flush()+ """,+ )+ manifest = write(root / "model-manifest.json", b"{}")+ runtime = write(root / "runtime.dylib", b"runtime")+ result = quality_runner._run_rust_image(+ {+ "worker": worker,+ "manifest": manifest,+ "runtime": runtime,+ "extension_id": "cua-perception",+ "extension_version": "1.0.0",+ "timeout": 5.0,+ "executed_artifacts": [+ bound(root, "worker", worker),+ bound(root, "manifest", manifest),+ bound(root, "runtime", runtime),+ ],+ },+ image,+ image_path,+ )+ self.assertEqual(result["coordinate_space"]["space"], "source_pixels")+ self.assertEqual(result["regions"][0]["bounds"], {"x": 10.0, "y": 8.0, "width": 20.0, "height": 16.0})+ self.assertEqual([sample["phase"] for sample in result["samples"]], ["cold", "warm"])+ self.assertTrue(all(sample["latency_ms"] > 0 for sample in result["samples"]))+ self.assertTrue(all(sample["sampled_process_peak_rss_bytes"] > 0 for sample in result["samples"]))++ def test_malformed_worker_frame_fails_closed(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ script = executable(+ Path(temporary) / "bad-worker",+ f"""\+ #!{sys.executable}+ import struct, sys+ sys.stdout.buffer.write(struct.pack('>I', 20) + b'{{}}')+ sys.stdout.buffer.flush()+ """,+ )+ process = subprocess.Popen([str(script)], stdout=subprocess.PIPE)+ assert process.stdout is not None+ with self.assertRaisesRegex(quality_runner.RunnerError, "truncated frame"):+ quality_runner._read_frame(process.stdout, 2.0)+ process.stdout.close()+ process.wait(timeout=2)++ def test_python_child_imports_local_som_and_emits_source_pixel_xywh(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ root = Path(temporary)+ import_root = root / "extracted-wheel"+ (import_root / "som").mkdir(parents=True)+ (import_root / "som/__init__.py").write_text(+ textwrap.dedent("""+ from types import SimpleNamespace++ class Box:+ coordinates = [0.1, 0.2, 0.4, 0.5]++ class Element:+ id = 7+ type = "text"+ bbox = Box()+ confidence = 0.75+ content = "Local"++ class OmniParser:+ def __init__(self, model_path, cache_dir, force_device):+ from pathlib import Path+ if not Path(model_path).is_file() or not (Path(cache_dir) / "model").is_dir():+ raise RuntimeError("missing explicit model/cache")+ self.detector = SimpleNamespace(model=object())+ self.ocr = SimpleNamespace(reader=object())++ def parse(self, image, **kwargs):+ return SimpleNamespace(elements=[Element()])+ """),+ encoding="utf-8",+ )+ model = write(root / "model.pt", b"model")+ (root / "cache/model").mkdir(parents=True)+ (root / "site-packages").mkdir()+ (root / "python-home").mkdir()+ image = png(root / "screen.png")+ options = {+ "import_root": str(import_root),+ "site_packages": str((root / "site-packages").resolve()),+ "python_home_binding": json_directory_binding(root, root / "python-home"),+ "site_packages_binding": json_directory_binding(root, root / "site-packages"),+ "model": str(model),+ "cache_dir": str(root / "cache"),+ "force_device": "cpu",+ "box_threshold": 0.3,+ "iou_threshold": 0.1,+ "use_ocr": True,+ "image": str(image),+ "image_sha256": sha256(image),+ }+ process = subprocess.Popen(+ [sys.executable, str(SCRIPT), "--python-child", json.dumps(options, separators=(",", ":"))],+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ )+ assert process.stdout is not None+ cold = quality_runner._read_frame(process.stdout, 5.0)+ warm = quality_runner._read_frame(process.stdout, 5.0)+ _, stderr = process.communicate(timeout=5)+ self.assertEqual(process.returncode, 0, stderr.decode())+ self.assertEqual((cold["phase"], warm["phase"]), ("cold", "warm"))+ self.assertEqual(cold["regions"], warm["regions"])+ self.assertEqual(cold["regions"][0]["bounds"], {"x": 10.0, "y": 16.0, "width": 30.000000000000004, "height": 24.0})++ def test_python_child_suppresses_sitecustomize_and_rejects_unbound_som_submodule(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ root = Path(temporary)+ site_packages = root / "site-packages"+ unbound_som = site_packages / "som"+ unbound_som.mkdir(parents=True)+ (unbound_som / "__init__.py").write_text("", encoding="utf-8")+ (unbound_som / "poison.py").write_text("VALUE = 'unbound'\n", encoding="utf-8")+ marker = root / "sitecustomize-loaded"+ (site_packages / "sitecustomize.py").write_text(+ "import pathlib, som.poison\n"+ f"pathlib.Path({str(marker)!r}).write_text('loaded', encoding='utf-8')\n",+ encoding="utf-8",+ )++ import_root = root / "extracted-wheel"+ (import_root / "som").mkdir(parents=True)+ (import_root / "som/__init__.py").write_text(+ "from som import poison\nclass OmniParser: pass\n",+ encoding="utf-8",+ )+ model = write(root / "model.pt", b"model")+ (root / "cache/model").mkdir(parents=True)+ (root / "python-home").mkdir()+ image = png(root / "screen.png")+ options = {+ "import_root": str(import_root),+ "site_packages": str(site_packages.resolve()),+ "python_home_binding": json_directory_binding(root, root / "python-home"),+ "site_packages_binding": json_directory_binding(root, site_packages),+ "model": str(model),+ "cache_dir": str(root / "cache"),+ "force_device": "cpu",+ "box_threshold": 0.3,+ "iou_threshold": 0.1,+ "use_ocr": False,+ "image": str(image),+ "image_sha256": sha256(image),+ }+ process = subprocess.Popen(+ [sys.executable, "-S", str(SCRIPT), "--python-child", json.dumps(options, separators=(",", ":"))],+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ )+ assert process.stdout is not None+ response = quality_runner._read_frame(process.stdout, 5.0)+ _, stderr = process.communicate(timeout=5)+ self.assertFalse(marker.exists(), stderr.decode())+ self.assertEqual(process.returncode, 1)+ self.assertEqual(response["status"], "error")+ self.assertIn("poison", response["error"])++ def test_python_config_requires_bound_runtime_model_and_easyocr_cache(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ root = Path(temporary)+ python = root / "python"+ shutil.copy2(sys.executable, python)+ model = write(root / "model.pt", b"model")+ ocr_detector = write(root / "cache/model/detector.pth", b"detector")+ ocr_recognizer = write(root / "cache/model/recognizer.pth", b"recognizer")+ package = wheel(root / "cua_som.whl", "class OmniParser: pass")+ runtime = write(root / "requirements.lock", b"lock")+ for directory in (root / "python-home", root / "site-packages"):+ directory.mkdir(parents=True)++ def artifact(role: str, artifact_id: str, path: Path) -> dict[str, str]:+ return {"role": role, "id": artifact_id, "path": path.relative_to(root).as_posix(), "sha256": sha256(path)}++ config = {+ "schema_version": 1,+ "identity": {+ "model": {"id": "omniparser", "version": "2", "revision": "revision"},+ "runtime": {"id": "cpython", "version": "3"},+ "adapter": {"id": "cua-som", "version": "1"},+ "reference_machine": {"id": "test", "os": "test", "arch": "test", "cpu": "test", "memory_bytes": 1},+ },+ "bindings": {+ "artifacts": [+ artifact("worker", "python", python),+ artifact("source_model", "omniparser_source", model),+ artifact("ocr_model", "ocr_detector", ocr_detector),+ artifact("ocr_model", "ocr_recognizer", ocr_recognizer),+ artifact("package", "package", package),+ artifact("dependency_lock", "lock", runtime),+ ],+ "package_artifact_id": "package",+ "installed_artifact_ids": ["python", "package", "lock"],+ },+ "execution": {+ "python_interpreter_artifact_id": "python",+ "python_home": "python-home",+ "site_packages": "site-packages",+ "model_artifact_id": "omniparser_source",+ "ocr_model_artifact_ids": ["ocr_detector", "ocr_recognizer"],+ "cache_dir": "cache",+ "force_device": "cpu",+ "box_threshold": 0.3,+ "iou_threshold": 0.1,+ "use_ocr": True,+ "timeout_seconds": 5,+ },+ }+ config_path = root / "config.json"+ config_path.write_text(json.dumps(config), encoding="utf-8")+ loaded = quality_runner._load_config(config_path, "python")+ self.assertEqual(loaded["execution"]["python"], python.resolve())+ self.assertEqual(loaded["execution"]["package"], package.resolve())+ self.assertEqual(loaded["execution"]["ocr_models"], [ocr_detector.resolve(), ocr_recognizer.resolve()])+ package.write_bytes(b"tampered")+ with self.assertRaisesRegex(quality_runner.RunnerError, "changed after configuration validation"):+ with tempfile.TemporaryDirectory() as extraction:+ quality_runner._extract_bound_wheel(package, loaded["execution"]["package_sha256"], Path(extraction))+ package = wheel(root / "cua_som.whl", "class OmniParser: pass")+ config["bindings"]["artifacts"][4]["sha256"] = sha256(package)+ config["execution"]["source_root"] = "source"+ config_path.write_text(json.dumps(config), encoding="utf-8")+ with self.assertRaisesRegex(quality_runner.RunnerError, "unknown fields: source_root"):+ quality_runner._load_config(config_path, "python")+ config["execution"].pop("source_root")+ (root / "empty-cache").mkdir()+ config["execution"]["cache_dir"] = "empty-cache"+ config_path.write_text(json.dumps(config), encoding="utf-8")+ with self.assertRaisesRegex(quality_runner.RunnerError, "model directory"):+ quality_runner._load_config(config_path, "python")++ def test_python_execution_rejects_replaced_site_packages_directory(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ root = Path(temporary)+ python_home = root / "python-home"+ site_packages = root / "site-packages"+ cache_dir = root / "cache"+ for directory in (python_home, site_packages, cache_dir / "model"):+ directory.mkdir(parents=True)+ execution = {+ "directory_bindings": {+ "python_home": directory_binding(root, python_home),+ "site_packages": directory_binding(root, site_packages),+ "cache_dir": directory_binding(root, cache_dir),+ }+ }+ site_packages.rmdir()+ site_packages.symlink_to(python_home, target_is_directory=True)+ with self.assertRaisesRegex(quality_runner.RunnerError, "site_packages changed"):+ quality_runner._verify_python_directories(execution, "Python launch")++ def test_python_execution_uses_staged_manifest_image_when_source_mutates(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ root = Path(temporary)+ python_home = root / "python-home"+ site_packages = root / "site-packages"+ cache_dir = root / "cache"+ for directory in (python_home, site_packages, cache_dir / "model"):+ directory.mkdir(parents=True)+ python = executable(root / "python", "#!/bin/sh\nexit 1\n")+ package = wheel(root / "package.whl", "class OmniParser: pass")+ model = write(root / "model.pt", b"model")+ ocr = write(cache_dir / "model/ocr.pth", b"ocr")+ image_path = png(root / "screen.png")+ expected_sha256 = sha256(image_path)+ helper = executable(+ root / "child.py",+ """\+ import hashlib, json, struct, sys, time+ options = json.loads(sys.argv[1])+ data = open(options['image'], 'rb').read()+ if hashlib.sha256(data).hexdigest() != options['image_sha256']:+ raise SystemExit(2)+ for phase in ('cold', 'warm'):+ payload = json.dumps({'status': 'ok', 'phase': phase, 'regions': []}, separators=(',', ':')).encode()+ sys.stdout.buffer.write(struct.pack('>I', len(payload)) + payload)+ sys.stdout.buffer.flush()+ time.sleep(0.02)+ """,+ )+ python_artifact = bound(root, "python", python)+ package_artifact = bound(root, "package", package)+ model_artifact = bound(root, "model", model)+ ocr_artifact = bound(root, "ocr", ocr)+ execution = {+ "python": python,+ "python_home": python_home,+ "site_packages": site_packages,+ "package": package,+ "package_sha256": package_artifact["sha256"],+ "model": model,+ "ocr_models": [ocr],+ "cache_dir": cache_dir,+ "force_device": "cpu",+ "box_threshold": 0.3,+ "iou_threshold": 0.1,+ "use_ocr": True,+ "timeout": 5.0,+ "executed_artifacts": [python_artifact, package_artifact, model_artifact, ocr_artifact],+ "python_artifact": python_artifact,+ "package_artifact": package_artifact,+ "model_artifact": model_artifact,+ "ocr_artifacts": [ocr_artifact],+ "directory_bindings": {+ "python_home": directory_binding(root, python_home),+ "site_packages": directory_binding(root, site_packages),+ "cache_dir": directory_binding(root, cache_dir),+ },+ }+ image = {"file": "screen.png", "sha256": expected_sha256, "width": 100, "height": 80}++ def child_invocation(_: dict[str, object], options: dict[str, object]) -> tuple[list[str], dict[str, str]]:+ self.assertNotEqual(Path(str(options["image"])), image_path)+ image_path.write_bytes(b"mutated after staging")+ return [sys.executable, str(helper), json.dumps(options, separators=(",", ":"))], dict(os.environ)++ with mock.patch.object(quality_runner, "_python_child_invocation", side_effect=child_invocation):+ result = quality_runner._run_python_image(execution, image, image_path)+ self.assertEqual(result["image_sha256"], expected_sha256)++ def test_rust_config_binds_every_worker_loaded_manifest_artifact(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ root = Path(temporary)+ worker = executable(root / "worker", "#!/bin/sh\nexit 0\n")+ runtime = write(root / "runtime.dylib", b"runtime")+ source = write(root / "source/model.pt", b"source")+ detector = write(root / "bundle/artifacts/detector.onnx", b"detector")+ ocr_detector = write(root / "bundle/artifacts/ocr-detector.onnx", b"ocr-detector")+ ocr_recognizer = write(root / "bundle/artifacts/ocr-recognizer.onnx", b"ocr-recognizer")+ dictionary = write(root / "bundle/artifacts/dictionary.txt", b"dictionary")+ manifest_value = {+ "identity": {"source_revision": "revision"},+ "onnx_runtime": {"library_sha256": sha256(runtime)},+ "detector": {"model": {"path": "artifacts/detector.onnx", "sha256": sha256(detector)}},+ "ocr": {+ "detector": {"model": {"path": "artifacts/ocr-detector.onnx", "sha256": sha256(ocr_detector)}},+ "recognizer": {"model": {"path": "artifacts/ocr-recognizer.onnx", "sha256": sha256(ocr_recognizer)}},+ "dictionary": {"path": "artifacts/dictionary.txt", "sha256": sha256(dictionary)},+ },+ }+ manifest = root / "bundle/model-manifest.json"+ manifest.write_text(json.dumps(manifest_value), encoding="utf-8")+ conversion_value = {"input": {"sha256": sha256(source)}, "expected_output": {"sha256": sha256(detector)}}+ conversion = root / "conversion.json"+ conversion.write_text(json.dumps(conversion_value), encoding="utf-8")+ package = write(root / "package.tar.gz", b"package")+ lock = write(root / "lock.json", b"lock")++ def artifact(role: str, artifact_id: str, path: Path) -> dict[str, str]:+ return {"role": role, "id": artifact_id, "path": path.relative_to(root).as_posix(), "sha256": sha256(path)}++ artifacts = [+ artifact("worker", "worker", worker), artifact("runtime", "runtime", runtime),+ artifact("source_model", "omniparser_source", source), artifact("converted_model", "detector", detector),+ artifact("ocr_model", "ocr_detector", ocr_detector), artifact("ocr_model", "ocr_recognizer", ocr_recognizer),+ artifact("ocr_dictionary", "dictionary", dictionary), artifact("model_manifest", "manifest", manifest),+ artifact("conversion_metadata", "conversion", conversion), artifact("package", "package", package),+ artifact("dependency_lock", "lock", lock),+ ]+ config = {+ "schema_version": 1,+ "identity": {+ "model": {"id": "omniparser", "version": "2", "revision": "revision"},+ "runtime": {"id": "onnx-runtime", "version": "1"},+ "adapter": {"id": "cua-perception", "version": "1"},+ "reference_machine": {"id": "test", "os": "test", "arch": "test", "cpu": "test", "memory_bytes": 1},+ },+ "bindings": {"artifacts": artifacts, "package_artifact_id": "package", "installed_artifact_ids": ["worker", "runtime", "detector"]},+ "execution": {+ "worker_artifact_id": "worker", "manifest_artifact_id": "manifest", "onnx_runtime_artifact_id": "runtime",+ "source_model_artifact_id": "omniparser_source", "detector_artifact_id": "detector",+ "ocr_detector_artifact_id": "ocr_detector", "ocr_recognizer_artifact_id": "ocr_recognizer",+ "ocr_dictionary_artifact_id": "dictionary", "conversion_metadata_artifact_id": "conversion",+ "extension_id": "cua-perception", "extension_version": "1", "timeout_seconds": 5,+ },+ }+ config_path = root / "config.json"+ config_path.write_text(json.dumps(config), encoding="utf-8")+ loaded = quality_runner._load_config(config_path, "rust")+ self.assertEqual(loaded["execution"]["source_revision"], "revision")++ runtime.write_bytes(b"tampered runtime")+ with self.assertRaisesRegex(quality_runner.RunnerError, "runtime changed after configuration validation"):+ quality_runner._verify_bound_artifacts(loaded["execution"]["executed_artifacts"], "Rust execution")+ runtime.write_bytes(b"runtime")++ alternate = write(root / "alternate.onnx", b"alternate")+ config["bindings"]["artifacts"].append(artifact("converted_model", "alternate", alternate))+ config["execution"]["detector_artifact_id"] = "alternate"+ config_path.write_text(json.dumps(config), encoding="utf-8")+ with self.assertRaisesRegex(quality_runner.RunnerError, "does not match its configured bound artifact"):+ quality_runner._load_config(config_path, "rust")++ def test_closed_corpus_rejects_extra_images_and_symlinks(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ root = Path(temporary)+ manifest = root / "manifest.json"+ expected = png(root / "images/expected.png")+ corpus = [{"file": "images/expected.png"}]+ quality_runner._validate_closed_corpus(manifest, corpus)+ png(root / "images/extra.png")+ with self.assertRaisesRegex(quality_runner.RunnerError, "extra"):+ quality_runner._validate_closed_corpus(manifest, corpus)+ (root / "images/extra.png").unlink()+ (root / "images/link.png").symlink_to(expected)+ with self.assertRaisesRegex(quality_runner.RunnerError, "symlink"):+ quality_runner._validate_closed_corpus(manifest, corpus)+++if __name__ == "__main__":+ unittest.main()diff --git a/libs/cua-driver/rust/crates/cua-perception/scripts/verify_bundle.py b/libs/cua-driver/rust/crates/cua-perception/scripts/verify_bundle.pynew file mode 100755index 0000000000..441c31d864--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/scripts/verify_bundle.py@@ -0,0 +1,264 @@+#!/usr/bin/env python3+"""Verify a sealed Cua Perception installation and exercise its real backend."""++from __future__ import annotations++import argparse+import base64+import json+import shutil+import struct+import subprocess+import tempfile+from pathlib import Path+from typing import Any++from artifact_tooling import (+ ArtifactError,+ LOCK_PATH,+ extension_identity,+ host_target,+ read_json,+ read_model_paths,+ request,+ require_binary_target,+ sha256,+ static_verify,+ worker_request,+ write_json,+)+++def image_dimensions(path: Path) -> tuple[int, int]:+ data = path.read_bytes()+ if len(data) < 24 or data[:8] != b"\x89PNG\r\n\x1a\n" or data[12:16] != b"IHDR":+ raise ArtifactError("real-parse fixture must be a non-empty PNG with an IHDR")+ return struct.unpack(">II", data[16:24])+++def source_inspection(bundle: Path, manifest: dict[str, Any]) -> list[dict[str, Any]]:+ ledger = read_json(bundle / manifest["sourceLedger"])+ artifacts = {+ item["name"]: item for item in manifest["artifacts"] if item["kind"] == "source"+ }+ return [+ {+ "kind": entry["contentKind"],+ "location": artifacts[entry["artifact"]]["path"],+ "revision": entry["revision"],+ "sha256": entry["artifactSha256"],+ "status": entry["sourceOfferStatus"],+ }+ for entry in ledger["sources"]+ ]+++def mismatch_rejection(+ worker: Path,+ manifest: Path,+ runtime: Path,+ target: str,+ identity: tuple[str, str],+) -> None:+ with tempfile.TemporaryDirectory(prefix="cua-perception-mismatch-") as temporary:+ tampered = Path(temporary) / runtime.name+ shutil.copyfile(runtime, tampered)+ with tampered.open("ab") as stream:+ stream.write(b"tampered")+ process = subprocess.run(+ [+ str(worker),+ "--manifest",+ str(manifest),+ "--onnx-runtime-library",+ str(tampered),+ "--extension-id",+ identity[0],+ "--extension-version",+ identity[1],+ ],+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ timeout=30,+ check=False,+ )+ if process.returncode == 0 or b"sha256 mismatch" not in process.stderr.lower():+ raise ArtifactError("worker did not reject a runtime with the wrong hash")++ wrong = Path(temporary) / "wrong-platform"+ if target == "x86_64-unknown-linux-gnu":+ wrong.write_bytes(b"MZ" + b"\0" * 58 + (64).to_bytes(4, "little") + b"PE\0\0\x64\x86")+ else:+ header = bytearray(64)+ header[:4] = b"\x7fELF"+ header[4] = 2+ header[5] = 1+ header[18:20] = (62).to_bytes(2, "little")+ wrong.write_bytes(header)+ try:+ require_binary_target(wrong, target)+ except ArtifactError as error:+ if "wrong-platform" not in str(error):+ raise+ else:+ raise ArtifactError("platform gate accepted a binary for another target")+++def exercise_bundle(+ bundle: Path,+ target: str,+ fixture: Path,+ identity: tuple[str, str],+ report_dir: Path | None = None,+) -> dict[str, Any]:+ lock = read_json(LOCK_PATH)+ target_lock = lock["onnx_runtime"]["targets"].get(target)+ if not target_lock:+ raise ArtifactError(f"unsupported target: {target}")+ if target != host_target():+ raise ArtifactError(f"wrong-platform bundle: host is {host_target()}, bundle is {target}")+ worker = bundle / target_lock["worker_filename"]+ manifest, runtime, _ = read_model_paths(bundle, target)+ require_binary_target(worker, target)+ require_binary_target(runtime, target)+ worker_hash = sha256(worker)+ runtime_hash = sha256(runtime)+ health = worker_request(+ worker, manifest, runtime, request("health", {}, "installed-health"), *identity+ )+ result = health.get("result", {})+ if (+ result.get("ready") is not True+ or result.get("runtime") != "onnx_runtime_cpu"+ or result.get("identity", {}).get("backend") != "onnx_runtime_cpu"+ or result.get("identity", {}).get("extension")+ != {"id": identity[0], "version": identity[1]}+ ):+ raise ArtifactError(f"health returned the wrong backend: {health}")++ self_test = worker_request(+ worker,+ manifest,+ runtime,+ request("self_test", {}, "installed-self-test"),+ *identity,+ )+ if (+ self_test.get("result", {}).get("passed") is not True+ or self_test.get("result", {}).get("identity", {}).get("extension")+ != {"id": identity[0], "version": identity[1]}+ ):+ raise ArtifactError(f"self_test did not pass: {self_test}")+ mismatch_rejection(worker, manifest, runtime, target, identity)++ width, height = image_dimensions(fixture)+ fixture_bytes = fixture.read_bytes()+ parse = worker_request(+ worker,+ manifest,+ runtime,+ request(+ "parse",+ {+ "capture_id": "installed-real-parse",+ "image": {+ "media_type": "image/png",+ "width": width,+ "height": height,+ "byte_length": len(fixture_bytes),+ "data_base64": base64.b64encode(fixture_bytes).decode("ascii"),+ },+ },+ "installed-real-parse",+ ),+ *identity,+ )+ parse_result = parse.get("result", {})+ regions = parse_result.get("regions")+ if (+ parse_result.get("runtime") != "onnx_runtime_cpu"+ or not isinstance(regions, list)+ or not regions+ or parse_result.get("identity", {}).get("extension")+ != {"id": identity[0], "version": identity[1]}+ ):+ raise ArtifactError(f"real parse returned no observations: {parse}")++ reports = {+ "health": {+ "schemaVersion": 1,+ "evidenceKind": "supplied",+ "gate": "health",+ "status": "passed",+ "target": target,+ "protocolVersion": 1,+ "extensionId": identity[0],+ "extensionVersion": identity[1],+ "workerSha256": worker_hash,+ "runtimeSha256": runtime_hash,+ },+ "self-test": {+ "schemaVersion": 1,+ "evidenceKind": "supplied",+ "gate": "self-test",+ "status": "passed",+ "target": target,+ "protocolVersion": 1,+ "extensionId": identity[0],+ "extensionVersion": identity[1],+ "workerSha256": worker_hash,+ "runtimeSha256": runtime_hash,+ "mismatchRejectionPassed": True,+ },+ "real-parse": {+ "schemaVersion": 1,+ "evidenceKind": "supplied",+ "gate": "real-parse",+ "status": "passed",+ "target": target,+ "protocolVersion": 1,+ "extensionId": identity[0],+ "extensionVersion": identity[1],+ "workerSha256": worker_hash,+ "runtimeSha256": runtime_hash,+ "fixtureSha256": sha256(fixture),+ "observations": len(regions),+ },+ }+ if report_dir is not None:+ for name, report in reports.items():+ write_json(report_dir / f"{name}.json", report)+ return reports+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("bundle", type=Path)+ parser.add_argument(+ "--real-parse-fixture",+ type=Path,+ help="PNG fixture; defaults to verification/known-answer.png in the bundle",+ )+ parser.add_argument("--static-only", action="store_true")+ args = parser.parse_args()+ try:+ manifest = static_verify(args.bundle, require_host=not args.static_only)+ sources = source_inspection(args.bundle, manifest)+ if args.static_only:+ print(json.dumps({"status": "passed", "target": manifest["target"]["triple"], "sources": sources}, sort_keys=True))+ return 0+ fixture = args.real_parse_fixture or args.bundle / "verification/known-answer.png"+ reports = exercise_bundle(+ args.bundle,+ manifest["target"]["triple"],+ fixture,+ extension_identity(manifest),+ )+ print(json.dumps({"status": "passed", "reports": reports, "sources": sources}, sort_keys=True))+ return 0+ except (ArtifactError, OSError, KeyError, subprocess.SubprocessError) as error:+ parser.exit(1, f"verification failed: {error}\n")+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/libs/cua-driver/rust/crates/cua-perception/src/lib.rs b/libs/cua-driver/rust/crates/cua-perception/src/lib.rsnew file mode 100644index 0000000000..8b2b9ca007--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/src/lib.rs@@ -0,0 +1,820 @@+//! Length-prefixed stdio protocol and offline inference worker.+//!+//! Production startup requires a local model manifest and a local ONNX Runtime+//! CPU library. Every artifact is hashed before ONNX Runtime is initialized;+//! this crate never downloads models or runtime binaries. The fixture backend+//! is an explicit deterministic test mode and never impersonates inference.++mod manifest;+mod postprocess;+mod preprocess;+mod runtime;++use std::{+ io::{self, Cursor, Read, Write},+ path::Path,+};++use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};+use image::{ImageError, ImageFormat, ImageReader, Limits, RgbImage};+pub use manifest::{ManifestError, ModelManifest, ValidatedManifest};+use runtime::{InferenceRegion, OnnxBackend};+use serde::{Deserialize, Serialize};+use serde_json::{json, Value};+use sha2::{Digest, Sha256};+use thiserror::Error;++pub const PROTOCOL_VERSION: &str = "cua-perception/1";+pub const MAX_FRAME_BYTES: usize = 16 * 1024 * 1024;+pub const MAX_IMAGE_BYTES: u64 = 8 * 1024 * 1024;+pub const MAX_IMAGE_DIMENSION: u32 = 8_192;+pub const MAX_IMAGE_PIXELS: u64 = 32 * 1024 * 1024;+const MAX_DECODE_ALLOC_BYTES: u64 = MAX_IMAGE_PIXELS * 4;++const FIXTURE_PNG_BASE64: &str =+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=";+const FIXTURE_SHA256: &str = "431ced6916a2a21a156e38701afe55bbd7f88969fbbfc56d7fe099d47f265460";++#[derive(Debug, Clone, PartialEq, Eq)]+pub enum FrameError {+ Empty,+ Oversized { declared: usize, maximum: usize },+ TruncatedPrefix { received: usize },+ TruncatedPayload { declared: usize, received: usize },+ Io(String),+}++impl FrameError {+ fn code(&self) -> &'static str {+ match self {+ Self::Empty+ | Self::Oversized { .. }+ | Self::TruncatedPrefix { .. }+ | Self::TruncatedPayload { .. } => "invalid_frame",+ Self::Io(_) => "io_error",+ }+ }++ fn message(&self) -> String {+ match self {+ Self::Empty => "frame payload must not be empty".to_owned(),+ Self::Oversized { declared, maximum } => {+ format!("frame declares {declared} bytes; maximum is {maximum}")+ }+ Self::TruncatedPrefix { received } => {+ format!("frame length prefix is incomplete: received {received} of 4 bytes")+ }+ Self::TruncatedPayload { declared, received } => {+ format!("frame declares {declared} bytes but only {received} were received")+ }+ Self::Io(message) => message.clone(),+ }+ }+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+struct Request {+ protocol: String,+ request_id: String,+ #[serde(flatten)]+ command: Command,+}++#[derive(Debug, Deserialize)]+#[serde(tag = "method", content = "params", rename_all = "snake_case")]+enum Command {+ Health(EmptyParams),+ SelfTest(EmptyParams),+ Parse(ParseParams),+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+struct EmptyParams {}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+struct ParseParams {+ capture_id: String,+ image: ImageInput,+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+struct ImageInput {+ media_type: String,+ width: u32,+ height: u32,+ byte_length: u64,+ data_base64: String,+}++#[derive(Debug, Serialize, PartialEq)]+pub struct Response {+ protocol: &'static str,+ #[serde(skip_serializing_if = "Option::is_none")]+ request_id: Option<String>,+ #[serde(flatten)]+ outcome: Outcome,+}++#[derive(Debug, Serialize, PartialEq)]+#[serde(tag = "status", rename_all = "snake_case")]+enum Outcome {+ Ok { result: Value },+ Error { error: ProtocolError },+}++#[derive(Debug, Serialize, PartialEq)]+pub struct ProtocolError {+ code: &'static str,+ message: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ details: Option<Value>,+}++impl Response {+ fn ok(request_id: String, result: Value) -> Self {+ Self {+ protocol: PROTOCOL_VERSION,+ request_id: Some(request_id),+ outcome: Outcome::Ok { result },+ }+ }++ fn error(+ request_id: Option<String>,+ code: &'static str,+ message: impl Into<String>,+ details: Option<Value>,+ ) -> Self {+ Self {+ protocol: PROTOCOL_VERSION,+ request_id,+ outcome: Outcome::Error {+ error: ProtocolError {+ code,+ message: message.into(),+ details,+ },+ },+ }+ }++ pub fn from_frame_error(error: &FrameError) -> Self {+ Self::error(None, error.code(), error.message(), None)+ }+}++#[derive(Debug, Error)]+pub enum StartupError {+ #[error(transparent)]+ Manifest(#[from] ManifestError),+ #[error(transparent)]+ Inference(#[from] runtime::InferenceError),+ #[error("invalid extension identity: {0}")]+ InvalidExtensionIdentity(String),+}++enum Backend {+ Fixture,+ Onnx(Box<OnnxBackend>),+}++pub struct Worker {+ backend: Backend,+ extension_id: String,+ extension_version: String,+}++impl Worker {+ pub fn fixture() -> Self {+ Self {+ backend: Backend::Fixture,+ extension_id: env!("CARGO_PKG_NAME").to_owned(),+ extension_version: env!("CARGO_PKG_VERSION").to_owned(),+ }+ }++ pub fn from_manifest_with_extension_identity(+ manifest_path: &Path,+ runtime_library_path: &Path,+ extension_id: &str,+ extension_version: &str,+ ) -> Result<Self, StartupError> {+ validate_extension_identity(extension_id, extension_version)?;+ let validated = ValidatedManifest::load(manifest_path, runtime_library_path)?;+ Ok(Self {+ backend: Backend::Onnx(Box::new(OnnxBackend::load(validated)?)),+ extension_id: extension_id.to_owned(),+ extension_version: extension_version.to_owned(),+ })+ }++ pub fn handle_payload(&self, payload: &[u8]) -> Response {+ let value: Value = match serde_json::from_slice(payload) {+ Ok(value) => value,+ Err(error) => {+ return Response::error(+ None,+ "invalid_json",+ "request payload is not valid JSON",+ Some(json!({ "reason": error.to_string() })),+ )+ }+ };+ let request_id = value+ .get("request_id")+ .and_then(Value::as_str)+ .map(str::to_owned);+ let request: Request = match serde_json::from_value(value) {+ Ok(request) => request,+ Err(error) => {+ return Response::error(+ request_id,+ "invalid_request",+ "request does not match the v1 schema",+ Some(json!({ "reason": error.to_string() })),+ )+ }+ };+ if request.protocol != PROTOCOL_VERSION {+ return Response::error(+ Some(request.request_id),+ "incompatible_protocol",+ format!("unsupported protocol version: {}", request.protocol),+ Some(json!({ "supported": [PROTOCOL_VERSION] })),+ );+ }+ if request.request_id.is_empty() || request.request_id.len() > 128 {+ return Response::error(+ Some(request.request_id),+ "invalid_request",+ "request_id must contain 1 to 128 bytes",+ None,+ );+ }++ let result = match request.command {+ Command::Health(_) => Ok(self.health()),+ Command::SelfTest(_) => self.self_test(),+ Command::Parse(params) => self.parse(params),+ };+ match result {+ Ok(result) => Response::ok(request.request_id, result),+ Err(error) => Response::error(+ Some(request.request_id),+ error.code,+ error.message,+ error.details,+ ),+ }+ }++ fn health(&self) -> Value {+ let mut value = match &self.backend {+ Backend::Fixture => json!({+ "ready": true,+ "protocol": PROTOCOL_VERSION,+ "runtime": "fixture_only",+ "identity": { "backend": "deterministic_fixture", "fixture_sha256": FIXTURE_SHA256 },+ "capabilities": ["health", "self_test", "parse_fixture"]+ }),+ Backend::Onnx(backend) => json!({+ "ready": true,+ "protocol": PROTOCOL_VERSION,+ "runtime": "onnx_runtime_cpu",+ "identity": backend.identity(),+ "capabilities": ["health", "self_test", "parse", "icon_detection", "ocr"]+ }),+ };+ self.bind_extension_identity(&mut value);+ value+ }++ fn self_test(&self) -> Result<Value, WorkerError> {+ let mut value = match &self.backend {+ Backend::Fixture => run_fixture_self_test(),+ Backend::Onnx(backend) => backend+ .self_test()+ .map_err(|error| WorkerError::new("self_test_failed", error.to_string())),+ }?;+ self.bind_extension_identity(&mut value);+ Ok(value)+ }++ fn parse(&self, params: ParseParams) -> Result<Value, WorkerError> {+ if params.capture_id.is_empty() || params.capture_id.len() > 256 {+ return Err(WorkerError::new(+ "invalid_request",+ "capture_id must contain 1 to 256 bytes",+ ));+ }+ let ValidatedImage { decoded, sha256 } = validate_image(¶ms.image)?;+ match &self.backend {+ Backend::Fixture => {+ if sha256 != FIXTURE_SHA256 {+ return Err(WorkerError::new(+ "unsupported_fixture",+ "fixture mode accepts only its deterministic test image",+ )+ .with_details(json!({ "sha256": sha256 })));+ }+ Ok(fixture_result(+ ¶ms.capture_id,+ &self.extension_id,+ &self.extension_version,+ ))+ }+ Backend::Onnx(backend) => {+ let regions = backend+ .parse(&decoded)+ .map_err(|error| WorkerError::new("inference_failed", error.to_string()))?;+ Ok(inference_result(+ ¶ms.capture_id,+ &sha256,+ params.image.width,+ params.image.height,+ regions,+ backend.identity(),+ (&self.extension_id, &self.extension_version),+ ))+ }+ }+ }++ fn bind_extension_identity(&self, value: &mut Value) {+ if let Some(root) = value.as_object_mut() {+ let identity = root.entry("identity").or_insert_with(|| json!({}));+ if let Some(identity) = identity.as_object_mut() {+ identity.insert(+ "extension".to_owned(),+ json!({+ "id": self.extension_id,+ "version": self.extension_version,+ }),+ );+ }+ }+ }+}++fn validate_extension_identity(id: &str, version: &str) -> Result<(), StartupError> {+ fn valid(value: &str) -> bool {+ !value.is_empty()+ && value.len() <= 128+ && value+ .bytes()+ .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))+ }+ if !valid(id) || !valid(version) {+ return Err(StartupError::InvalidExtensionIdentity(+ "id and version must contain 1 to 128 ASCII letters, digits, dots, underscores, or hyphens"+ .to_owned(),+ ));+ }+ Ok(())+}++/// Compatibility helper for deterministic protocol tests.+pub fn handle_payload(payload: &[u8]) -> Response {+ Worker::fixture().handle_payload(payload)+}++struct WorkerError {+ code: &'static str,+ message: String,+ details: Option<Value>,+}++impl WorkerError {+ fn new(code: &'static str, message: impl Into<String>) -> Self {+ Self {+ code,+ message: message.into(),+ details: None,+ }+ }++ fn with_details(mut self, details: Value) -> Self {+ self.details = Some(details);+ self+ }+}++struct ValidatedImage {+ decoded: RgbImage,+ sha256: String,+}++fn validate_image(image: &ImageInput) -> Result<ValidatedImage, WorkerError> {+ if image.media_type != "image/png" && image.media_type != "image/jpeg" {+ return Err(WorkerError::new(+ "invalid_image",+ "media_type must be image/png or image/jpeg",+ ));+ }+ if image.width == 0+ || image.height == 0+ || image.width > MAX_IMAGE_DIMENSION+ || image.height > MAX_IMAGE_DIMENSION+ || u64::from(image.width) * u64::from(image.height) > MAX_IMAGE_PIXELS+ {+ return Err(+ WorkerError::new("invalid_image", "image dimensions exceed protocol limits")+ .with_details(json!({+ "width": image.width,+ "height": image.height,+ "max_dimension": MAX_IMAGE_DIMENSION,+ "max_pixels": MAX_IMAGE_PIXELS+ })),+ );+ }+ if image.byte_length == 0 || image.byte_length > MAX_IMAGE_BYTES {+ return Err(+ WorkerError::new("invalid_image", "image byte_length exceeds protocol limits")+ .with_details(json!({+ "byte_length": image.byte_length,+ "max_bytes": MAX_IMAGE_BYTES+ })),+ );+ }+ let byte_length = usize::try_from(image.byte_length).map_err(|_| {+ WorkerError::new(+ "invalid_image",+ "image byte_length cannot be represented on this platform",+ )+ })?;+ let expected_base64_length = byte_length.div_ceil(3) * 4;+ if image.data_base64.len() != expected_base64_length {+ return Err(WorkerError::new(+ "invalid_image",+ "data_base64 length is inconsistent with byte_length",+ )+ .with_details(json!({+ "declared_byte_length": image.byte_length,+ "expected_base64_length": expected_base64_length,+ "actual_base64_length": image.data_base64.len()+ })));+ }+ let bytes = BASE64.decode(&image.data_base64).map_err(|error| {+ WorkerError::new("invalid_image", "data_base64 is not valid base64")+ .with_details(json!({ "reason": error.to_string() }))+ })?;+ if bytes.len() != byte_length {+ return Err(WorkerError::new(+ "invalid_image",+ "decoded image length does not match byte_length",+ ));+ }+ let format = if image.media_type == "image/png" {+ ImageFormat::Png+ } else {+ ImageFormat::Jpeg+ };+ let actual = image_reader(&bytes, format)+ .into_dimensions()+ .map_err(|error| map_image_error(error, format))?;+ if u64::from(actual.0) * u64::from(actual.1) > MAX_IMAGE_PIXELS {+ return Err(WorkerError::new(+ "invalid_image",+ if format == ImageFormat::Png {+ "decoded PNG dimensions exceed image resource limits"+ } else {+ "decoded JPEG dimensions exceed image resource limits"+ },+ ));+ }+ if actual != (image.width, image.height) {+ return Err(WorkerError::new(+ "invalid_image",+ "decoded image dimensions do not match metadata",+ )+ .with_details(json!({+ "declared": { "width": image.width, "height": image.height },+ "actual": { "width": actual.0, "height": actual.1 }+ })));+ }+ let decoded = image_reader(&bytes, format)+ .decode()+ .map_err(|error| map_image_error(error, format))?+ .into_rgb8();+ Ok(ValidatedImage {+ sha256: format!("{:x}", Sha256::digest(&bytes)),+ decoded,+ })+}++fn image_reader(bytes: &[u8], format: ImageFormat) -> ImageReader<Cursor<&[u8]>> {+ let mut limits = Limits::default();+ limits.max_image_width = Some(MAX_IMAGE_DIMENSION);+ limits.max_image_height = Some(MAX_IMAGE_DIMENSION);+ limits.max_alloc = Some(MAX_DECODE_ALLOC_BYTES);+ let mut reader = ImageReader::with_format(Cursor::new(bytes), format);+ reader.limits(limits);+ reader+}++fn map_image_error(error: ImageError, format: ImageFormat) -> WorkerError {+ let label = if format == ImageFormat::Png {+ "PNG"+ } else {+ "JPEG"+ };+ match error {+ ImageError::Limits(_) => WorkerError::new(+ "invalid_image",+ format!("decoded {label} exceeds image resource limits"),+ )+ .with_details(json!({ "reason": error.to_string() })),+ _ => WorkerError::new(+ "invalid_image",+ format!("image bytes are not a valid {label}"),+ )+ .with_details(json!({ "reason": error.to_string() })),+ }+}++fn fixture_result(capture_id: &str, extension_id: &str, extension_version: &str) -> Value {+ json!({+ "capture_id": capture_id,+ "image": { "sha256": FIXTURE_SHA256, "width": 1, "height": 1 },+ "coordinate_space": "image_pixels",+ "regions": [{+ "id": "fixture-text-1",+ "kind": "text",+ "bounds": { "x": 0, "y": 0, "width": 1, "height": 1 },+ "text": "fixture",+ "confidence": 1.0,+ "interactive": false+ }],+ "runtime": "fixture_only",+ "identity": {+ "extension": {+ "id": extension_id,+ "version": extension_version+ },+ "backend": "deterministic_fixture",+ "fixture_sha256": FIXTURE_SHA256+ }+ })+}++fn inference_result(+ capture_id: &str,+ sha256: &str,+ width: u32,+ height: u32,+ regions: Vec<InferenceRegion>,+ identity: Value,+ extension_identity: (&str, &str),+) -> Value {+ let (extension_id, extension_version) = extension_identity;+ let mut identity = identity;+ if let Some(identity) = identity.as_object_mut() {+ identity.insert(+ "extension".to_owned(),+ json!({+ "id": extension_id,+ "version": extension_version+ }),+ );+ }+ let regions = regions+ .into_iter()+ .enumerate()+ .map(|(index, region)| {+ let kind = region.kind;+ let class_id = region.class_id;+ let x = region.bounds.x1.floor().max(0.0) as u32;+ let y = region.bounds.y1.floor().max(0.0) as u32;+ let right = region.bounds.x2.ceil().min(width as f32) as u32;+ let bottom = region.bounds.y2.ceil().min(height as f32) as u32;+ let mut value = json!({+ "id": format!("{}-{}", kind, index + 1),+ "kind": kind,+ "bounds": { "x": x, "y": y, "width": right.saturating_sub(x), "height": bottom.saturating_sub(y) },+ "confidence": region.confidence,+ "interactive": false+ });+ if let Some(text) = region.text {+ value["text"] = Value::String(text);+ }+ if let Some(class_id) = class_id {+ value["class_id"] = json!(class_id);+ }+ if kind == "icon" {+ value["label"] = Value::String(+ class_id.map_or_else(|| "icon".to_owned(), |id| format!("icon-class-{id}")),+ );+ }+ value+ })+ .collect::<Vec<_>>();+ json!({+ "capture_id": capture_id,+ "image": { "sha256": sha256, "width": width, "height": height },+ "coordinate_space": "image_pixels",+ "regions": regions,+ "runtime": "onnx_runtime_cpu",+ "identity": identity,+ "text_geometry": "axis_aligned_bounds"+ })+}++fn run_fixture_self_test() -> Result<Value, WorkerError> {+ let bytes = BASE64+ .decode(FIXTURE_PNG_BASE64)+ .map_err(|error| WorkerError::new("self_test_failed", error.to_string()))?;+ let request = ParseParams {+ capture_id: "self-test".to_owned(),+ image: ImageInput {+ media_type: "image/png".to_owned(),+ width: 1,+ height: 1,+ byte_length: bytes.len() as u64,+ data_base64: FIXTURE_PNG_BASE64.to_owned(),+ },+ };+ let result = Worker::fixture().parse(request)?;+ if result+ != fixture_result(+ "self-test",+ env!("CARGO_PKG_NAME"),+ env!("CARGO_PKG_VERSION"),+ )+ {+ return Err(WorkerError::new(+ "self_test_failed",+ "fixture parser produced an unexpected result",+ ));+ }+ Ok(json!({+ "passed": true,+ "checks": ["fixture_decode", "image_validation", "known_answer_fixture"],+ "identity": { "backend": "deterministic_fixture", "fixture_sha256": FIXTURE_SHA256 }+ }))+}++pub fn read_frame(reader: &mut impl Read) -> Result<Option<Vec<u8>>, FrameError> {+ let mut prefix = [0_u8; 4];+ let mut prefix_read = 0;+ while prefix_read < prefix.len() {+ match reader.read(&mut prefix[prefix_read..]) {+ Ok(0) if prefix_read == 0 => return Ok(None),+ Ok(0) => {+ return Err(FrameError::TruncatedPrefix {+ received: prefix_read,+ })+ }+ Ok(count) => prefix_read += count,+ Err(error) if error.kind() == io::ErrorKind::Interrupted => {}+ Err(error) => return Err(FrameError::Io(error.to_string())),+ }+ }+ let declared = u32::from_be_bytes(prefix) as usize;+ // A zero-length frame is unambiguous and consumes exactly its prefix. Let+ // the request parser return invalid_json, then continue with the next frame.+ if declared == 0 {+ return Ok(Some(Vec::new()));+ }+ if declared > MAX_FRAME_BYTES {+ return Err(FrameError::Oversized {+ declared,+ maximum: MAX_FRAME_BYTES,+ });+ }+ let mut payload = vec![0_u8; declared];+ let mut received = 0;+ while received < declared {+ match reader.read(&mut payload[received..]) {+ Ok(0) => return Err(FrameError::TruncatedPayload { declared, received }),+ Ok(count) => received += count,+ Err(error) if error.kind() == io::ErrorKind::Interrupted => {}+ Err(error) => return Err(FrameError::Io(error.to_string())),+ }+ }+ Ok(Some(payload))+}++pub fn write_frame(writer: &mut impl Write, payload: &[u8]) -> io::Result<()> {+ if payload.len() > MAX_FRAME_BYTES {+ return Err(io::Error::new(+ io::ErrorKind::InvalidInput,+ format!(+ "frame contains {} bytes; maximum is {MAX_FRAME_BYTES}",+ payload.len()+ ),+ ));+ }+ let length = u32::try_from(payload.len())+ .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "frame exceeds u32 length"))?;+ writer.write_all(&length.to_be_bytes())?;+ writer.write_all(payload)?;+ writer.flush()+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::postprocess::Rect;++ #[test]+ fn caller_supplied_extension_identity_is_reported_and_invalid_values_fail_closed() {+ let worker = Worker {+ backend: Backend::Fixture,+ extension_id: "cua-perception".to_owned(),+ extension_version: "0.1.0".to_owned(),+ };+ let health = worker.health();+ assert_eq!(+ health["identity"]["extension"],+ json!({"id": "cua-perception", "version": "0.1.0"})+ );++ let error = match Worker::from_manifest_with_extension_identity(+ Path::new("absent-manifest"),+ Path::new("absent-runtime"),+ "cua/perception",+ "0.1.0",+ ) {+ Ok(_) => panic!("an unsafe identity must fail before reading artifacts"),+ Err(error) => error,+ };+ assert!(matches!(error, StartupError::InvalidExtensionIdentity(_)));+ }++ #[test]+ fn private_inference_regions_map_to_protocol_dto() {+ let result = inference_result(+ "capture-1",+ "abc123",+ 100,+ 50,+ vec![+ InferenceRegion {+ kind: "text",+ bounds: Rect {+ x1: 1.2,+ y1: 2.8,+ x2: 10.1,+ y2: 12.2,+ },+ text: Some("Send".to_owned()),+ confidence: 0.75,+ class_id: None,+ },+ InferenceRegion {+ kind: "icon",+ bounds: Rect {+ x1: 90.0,+ y1: 40.0,+ x2: 110.0,+ y2: 60.0,+ },+ text: None,+ confidence: 0.5,+ class_id: Some(4),+ },+ ],+ json!({ "backend": "test" }),+ (env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")),+ );+ let encoded = serde_json::to_vec(&result).unwrap();+ let decoded: Value = serde_json::from_slice(&encoded).unwrap();++ assert_eq!(decoded["capture_id"], "capture-1");+ assert_eq!(+ decoded["regions"],+ json!([+ {+ "id": "text-1", "kind": "text",+ "bounds": { "x": 1, "y": 2, "width": 10, "height": 11 },+ "confidence": 0.75, "text": "Send", "interactive": false+ },+ {+ "id": "icon-2", "kind": "icon",+ "bounds": { "x": 90, "y": 40, "width": 10, "height": 10 },+ "confidence": 0.5, "class_id": 4, "label": "icon-class-4",+ "interactive": false+ }+ ])+ );+ assert_eq!(+ decoded["identity"]["extension"],+ json!({+ "id": env!("CARGO_PKG_NAME"),+ "version": env!("CARGO_PKG_VERSION")+ })+ );+ assert_eq!(decoded["text_geometry"], "axis_aligned_bounds");+ }++ #[test]+ fn fixture_regions_explicitly_serialize_as_non_interactive() {+ let result = fixture_result("capture-1", "cua-perception", "0.1.0");++ assert_eq!(result["regions"][0]["interactive"], false);+ }+}diff --git a/libs/cua-driver/rust/crates/cua-perception/src/main.rs b/libs/cua-driver/rust/crates/cua-perception/src/main.rsnew file mode 100644index 0000000000..d2d6426815--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/src/main.rs@@ -0,0 +1,357 @@+use std::{+ env, fs,+ io::{self, Write},+ path::{Path, PathBuf},+ time::{SystemTime, UNIX_EPOCH},+};++use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};+use cua_perception::{read_frame, write_frame, Response, Worker};+use serde_json::{json, Value};++fn main() {+ if let Err(error) = start() {+ eprintln!("cua-perception: {error}");+ std::process::exit(1);+ }+}++fn start() -> Result<(), String> {+ match parse_startup()? {+ Startup::Serve(worker) => run(&worker).map_err(|error| error.to_string()),+ Startup::Gate(gate, identity) => run_gate(gate, &identity),+ }+}++enum Startup {+ Serve(Worker),+ Gate(Gate, ExtensionIdentity),+}++struct ExtensionIdentity {+ id: String,+ version: String,+}++#[derive(Clone, Copy)]+enum Gate {+ Health,+ SelfTest,+ RealParse,+ MismatchRejection,+}++fn parse_startup() -> Result<Startup, String> {+ let mut args = env::args_os().skip(1);+ let first = args.next().ok_or_else(usage)?;+ if first == "--fixture" {+ if args.next().is_some() {+ return Err(usage());+ }+ return Ok(Startup::Serve(Worker::fixture()));+ }+ let gate = match first.to_str() {+ Some("--health") => Some(Gate::Health),+ Some("--self-test") => Some(Gate::SelfTest),+ Some("--real-parse-self-test") => Some(Gate::RealParse),+ Some("--mismatch-rejection-self-test") => Some(Gate::MismatchRejection),+ _ => None,+ };+ if let Some(gate) = gate {+ let identity = parse_extension_identity(&mut args)?;+ return Ok(Startup::Gate(gate, identity));+ }+ if first != "--manifest" {+ return Err(usage());+ }+ let manifest = PathBuf::from(args.next().ok_or_else(usage)?);+ if args.next().as_deref() != Some("--onnx-runtime-library".as_ref()) {+ return Err(usage());+ }+ let runtime = PathBuf::from(args.next().ok_or_else(usage)?);+ let identity = parse_extension_identity(&mut args)?;+ Worker::from_manifest_with_extension_identity(+ &manifest,+ &runtime,+ &identity.id,+ &identity.version,+ )+ .map(Startup::Serve)+ .map_err(|error| error.to_string())+}++fn parse_extension_identity(+ args: &mut impl Iterator<Item = std::ffi::OsString>,+) -> Result<ExtensionIdentity, String> {+ let flag = args.next().ok_or_else(usage)?;+ if flag != "--extension-id" {+ return Err(usage());+ }+ let id = args+ .next()+ .and_then(|value| value.into_string().ok())+ .ok_or_else(usage)?;+ if args.next().as_deref() != Some("--extension-version".as_ref()) {+ return Err(usage());+ }+ let version = args+ .next()+ .and_then(|value| value.into_string().ok())+ .ok_or_else(usage)?;+ if args.next().is_some() {+ return Err(usage());+ }+ Ok(ExtensionIdentity { id, version })+}++fn usage() -> String {+ "usage: cua-perception --fixture | --manifest <manifest.json> --onnx-runtime-library <library> --extension-id <id> --extension-version <version> | (--health | --self-test | --real-parse-self-test | --mismatch-rejection-self-test) --extension-id <id> --extension-version <version>".to_owned()+}++fn run_gate(gate: Gate, identity: &ExtensionIdentity) -> Result<(), String> {+ let root = installed_root()?;+ let manifest = find_required_file(+ &root,+ &[+ Path::new("model-manifest.json"),+ Path::new("models/model-manifest.json"),+ ],+ "model manifest",+ )?;+ let runtime = resolve_runtime(&root)?;+ if matches!(gate, Gate::MismatchRejection) {+ return run_mismatch_rejection(&manifest, &runtime, identity);+ }++ let worker = Worker::from_manifest_with_extension_identity(+ &manifest,+ &runtime,+ &identity.id,+ &identity.version,+ )+ .map_err(|error| error.to_string())?;+ let (method, params) = match gate {+ Gate::Health => ("health", json!({})),+ Gate::SelfTest => ("self_test", json!({})),+ Gate::RealParse => {+ let fixture = find_required_file(+ &root,+ &[Path::new("verification/known-answer.png")],+ "real-parse fixture",+ )?;+ let bytes = fs::read(&fixture)+ .map_err(|error| format!("read {}: {error}", fixture.display()))?;+ let (width, height) = png_dimensions(&bytes)?;+ (+ "parse",+ json!({+ "capture_id": "candidate-real-parse",+ "image": {+ "media_type": "image/png",+ "width": width,+ "height": height,+ "byte_length": bytes.len(),+ "data_base64": BASE64.encode(bytes),+ }+ }),+ )+ }+ Gate::MismatchRejection => unreachable!(),+ };+ let payload = serde_json::to_vec(&json!({+ "protocol": "cua-perception/1",+ "request_id": format!("candidate-{method}"),+ "method": method,+ "params": params,+ }))+ .map_err(|error| error.to_string())?;+ let response =+ serde_json::to_value(worker.handle_payload(&payload)).map_err(|error| error.to_string())?;+ require_success(&response)?;+ println!(+ "{}",+ serde_json::to_string(&response).map_err(|error| error.to_string())?+ );+ Ok(())+}++fn installed_root() -> Result<PathBuf, String> {+ let executable = env::current_exe().map_err(|error| error.to_string())?;+ let parent = executable+ .parent()+ .ok_or_else(|| "worker executable has no parent directory".to_owned())?;+ if parent.file_name().and_then(|name| name.to_str()) == Some("bin") {+ parent+ .parent()+ .map(Path::to_path_buf)+ .ok_or_else(|| "installed worker has no extension root".to_owned())+ } else {+ Ok(parent.to_path_buf())+ }+}++fn find_required_file(root: &Path, relatives: &[&Path], label: &str) -> Result<PathBuf, String> {+ relatives+ .iter()+ .map(|relative| root.join(relative))+ .find(|path| path.is_file())+ .ok_or_else(|| format!("{label} is unavailable under {}", root.display()))+}++fn resolve_runtime(root: &Path) -> Result<PathBuf, String> {+ if let Some(path) = env::var_os("CUA_PERCEPTION_RUNTIME") {+ let path = PathBuf::from(path);+ if path.is_file() {+ return Ok(path);+ }+ return Err(format!(+ "CUA_PERCEPTION_RUNTIME is not a regular file: {}",+ path.display()+ ));+ }+ let directory = root.join("runtime");+ let mut matches = fs::read_dir(&directory)+ .map_err(|error| format!("read {}: {error}", directory.display()))?+ .filter_map(Result::ok)+ .map(|entry| entry.path())+ .filter(|path| {+ path.is_file()+ && matches!(+ path.extension().and_then(|extension| extension.to_str()),+ Some("dll" | "dylib" | "so")+ )+ })+ .collect::<Vec<_>>();+ matches.sort();+ match matches.as_slice() {+ [runtime] => Ok(runtime.clone()),+ _ => Err(format!(+ "expected exactly one runtime library under {}, found {}",+ directory.display(),+ matches.len()+ )),+ }+}++fn run_mismatch_rejection(+ manifest: &Path,+ runtime: &Path,+ identity: &ExtensionIdentity,+) -> Result<(), String> {+ let nonce = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map_err(|error| error.to_string())?+ .as_nanos();+ let tampered = env::temp_dir().join(format!(+ "cua-perception-runtime-mismatch-{}-{nonce}",+ std::process::id()+ ));+ fs::copy(runtime, &tampered)+ .map_err(|error| format!("copy runtime mismatch fixture: {error}"))?;+ let result = (|| {+ use std::io::Write as _;+ fs::OpenOptions::new()+ .append(true)+ .open(&tampered)+ .and_then(|mut file| file.write_all(b"tampered"))+ .map_err(|error| format!("tamper runtime mismatch fixture: {error}"))?;+ match Worker::from_manifest_with_extension_identity(+ manifest,+ &tampered,+ &identity.id,+ &identity.version,+ ) {+ Err(error)+ if error+ .to_string()+ .to_ascii_lowercase()+ .contains("sha256 mismatch") =>+ {+ println!("{{\"mismatch_rejection\":true}}");+ Ok(())+ }+ Err(error) => Err(format!(+ "runtime mismatch failed for an unexpected reason: {error}"+ )),+ Ok(_) => Err("worker accepted a runtime whose SHA-256 did not match".to_owned()),+ }+ })();+ let cleanup = fs::remove_file(&tampered)+ .map_err(|error| format!("remove runtime mismatch fixture: {error}"));+ result.and(cleanup)+}++fn png_dimensions(bytes: &[u8]) -> Result<(u32, u32), String> {+ if bytes.len() < 24 || &bytes[..8] != b"\x89PNG\r\n\x1a\n" || &bytes[12..16] != b"IHDR" {+ return Err("real-parse fixture is not a PNG with an IHDR".to_owned());+ }+ let width = u32::from_be_bytes(bytes[16..20].try_into().expect("four bytes"));+ let height = u32::from_be_bytes(bytes[20..24].try_into().expect("four bytes"));+ if width == 0 || height == 0 {+ return Err("real-parse fixture has zero dimensions".to_owned());+ }+ Ok((width, height))+}++fn require_success(response: &Value) -> Result<(), String> {+ if response.get("status").and_then(Value::as_str) == Some("ok") {+ Ok(())+ } else {+ Err(format!("worker gate failed: {response}"))+ }+}++fn run(worker: &Worker) -> io::Result<()> {+ let stdin = io::stdin();+ let stdout = io::stdout();+ let mut reader = stdin.lock();+ let mut writer = stdout.lock();++ loop {+ let response = match read_frame(&mut reader) {+ Ok(Some(payload)) => worker.handle_payload(&payload),+ Ok(None) => return Ok(()),+ Err(error) => {+ let response = Response::from_frame_error(&error);+ write_response(&mut writer, &response)?;+ return Ok(());+ }+ };+ write_response(&mut writer, &response)?;+ }+}++fn write_response(writer: &mut impl Write, response: &Response) -> io::Result<()> {+ let payload = serde_json::to_vec(response)+ .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;+ write_frame(writer, &payload)+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::ffi::OsString;++ #[test]+ fn real_startup_identity_is_explicit_and_complete() {+ let mut missing = Vec::<OsString>::new().into_iter();+ assert_eq!(parse_extension_identity(&mut missing).err(), Some(usage()));++ let mut partial = ["--extension-id", "cua-perception"]+ .map(OsString::from)+ .into_iter();+ assert_eq!(parse_extension_identity(&mut partial).err(), Some(usage()));++ let mut complete = [+ "--extension-id",+ "cua-perception",+ "--extension-version",+ "0.1.0",+ ]+ .map(OsString::from)+ .into_iter();+ let identity = parse_extension_identity(&mut complete).unwrap();+ assert_eq!(identity.id, "cua-perception");+ assert_eq!(identity.version, "0.1.0");+ }+}diff --git a/libs/cua-driver/rust/crates/cua-perception/src/manifest.rs b/libs/cua-driver/rust/crates/cua-perception/src/manifest.rsnew file mode 100644index 0000000000..2e4068e77a--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/src/manifest.rs@@ -0,0 +1,445 @@+use std::{+ fs,+ path::{Component, Path, PathBuf},+};++use serde::{Deserialize, Serialize};+use sha2::{Digest, Sha256};+use thiserror::Error;++pub const MANIFEST_SCHEMA_VERSION: u32 = 1;++#[derive(Debug, Clone, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+pub struct ModelManifest {+ pub schema_version: u32,+ pub identity: ModelIdentity,+ pub onnx_runtime: RuntimeIdentity,+ pub detector: DetectorManifest,+ pub ocr: OcrManifest,+}++#[derive(Debug, Clone, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+pub struct ModelIdentity {+ pub name: String,+ pub version: String,+ pub source_url: String,+ pub source_revision: String,+ pub license: String,+}++#[derive(Debug, Clone, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+pub struct RuntimeIdentity {+ pub version: String,+ pub target: String,+ pub library_sha256: String,+ pub intra_threads: usize,+}++#[derive(Debug, Clone, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+pub struct DetectorManifest {+ pub model: Artifact,+ pub input_name: String,+ pub output_name: String,+ pub input_width: u32,+ pub input_height: u32,+ pub confidence_threshold: f32,+ pub iou_threshold: f32,+ pub output_layout: DetectorOutputLayout,+ pub max_candidates: usize,+ pub max_detections: usize,+}++#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+pub enum DetectorOutputLayout {+ YoloV8CxcywhClassScores,+ XyxyScoreClass,+}++#[derive(Debug, Clone, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+pub struct OcrManifest {+ pub detector: OcrDetectorManifest,+ pub recognizer: OcrRecognizerManifest,+ pub dictionary: Artifact,+ pub dictionary_format: DictionaryFormat,+}++#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+pub enum DictionaryFormat {+ PlainLines,+ PaddleInferenceYaml,+}++#[derive(Debug, Clone, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+pub struct OcrDetectorManifest {+ pub model: Artifact,+ pub input_name: String,+ pub output_name: String,+ pub input_width: u32,+ pub input_height: u32,+ pub pixel_threshold: f32,+ pub box_threshold: f32,+ pub unclip_ratio: f32,+ pub minimum_area: u32,+ pub minimum_side: u32,+ pub max_candidates: usize,+}++#[derive(Debug, Clone, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+pub struct OcrRecognizerManifest {+ pub model: Artifact,+ pub input_name: String,+ pub output_name: String,+ pub input_width: u32,+ pub input_height: u32,+ pub blank_index: usize,+}++#[derive(Debug, Clone, Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+pub struct Artifact {+ pub path: PathBuf,+ pub sha256: String,+}++#[derive(Debug, Clone)]+pub struct ValidatedManifest {+ pub manifest: ModelManifest,+ pub manifest_path: PathBuf,+ pub manifest_sha256: String,+ pub detector_path: PathBuf,+ pub ocr_detector_path: PathBuf,+ pub ocr_recognizer_path: PathBuf,+ pub dictionary_path: PathBuf,+ pub runtime_library_path: PathBuf,+}++#[derive(Debug, Error)]+pub enum ManifestError {+ #[error("failed to read {path}: {reason}")]+ Read { path: PathBuf, reason: String },+ #[error("model manifest is not valid JSON: {0}")]+ Json(#[from] serde_json::Error),+ #[error("unsupported model manifest schema {actual}; expected {expected}")]+ Schema { actual: u32, expected: u32 },+ #[error("manifest field {0} must not be empty")]+ EmptyField(&'static str),+ #[error("manifest field {0} is outside its valid range")]+ InvalidValue(&'static str),+ #[error("artifact path must be a relative path without '..': {0}")]+ UnsafePath(PathBuf),+ #[error("artifact is missing or not a regular file: {0}")]+ MissingArtifact(PathBuf),+ #[error("sha256 mismatch for {path}: expected {expected}, got {actual}")]+ HashMismatch {+ path: PathBuf,+ expected: String,+ actual: String,+ },+}++impl ValidatedManifest {+ pub fn load(manifest_path: &Path, runtime_library_path: &Path) -> Result<Self, ManifestError> {+ let manifest_bytes = read_bytes(manifest_path)?;+ let manifest: ModelManifest = serde_json::from_slice(&manifest_bytes)?;+ manifest.validate_fields()?;+ let root = manifest_path.parent().unwrap_or_else(|| Path::new("."));++ let detector_path = validate_artifact(root, &manifest.detector.model)?;+ let ocr_detector_path = validate_artifact(root, &manifest.ocr.detector.model)?;+ let ocr_recognizer_path = validate_artifact(root, &manifest.ocr.recognizer.model)?;+ let dictionary_path = validate_artifact(root, &manifest.ocr.dictionary)?;+ validate_absolute_artifact(runtime_library_path, &manifest.onnx_runtime.library_sha256)?;++ Ok(Self {+ manifest,+ manifest_path: manifest_path.to_path_buf(),+ manifest_sha256: digest(&manifest_bytes),+ detector_path,+ ocr_detector_path,+ ocr_recognizer_path,+ dictionary_path,+ runtime_library_path: runtime_library_path.to_path_buf(),+ })+ }+}++impl ModelManifest {+ fn validate_fields(&self) -> Result<(), ManifestError> {+ if self.schema_version != MANIFEST_SCHEMA_VERSION {+ return Err(ManifestError::Schema {+ actual: self.schema_version,+ expected: MANIFEST_SCHEMA_VERSION,+ });+ }+ for (name, value) in [+ ("identity.name", self.identity.name.as_str()),+ ("identity.version", self.identity.version.as_str()),+ ("identity.source_url", self.identity.source_url.as_str()),+ (+ "identity.source_revision",+ self.identity.source_revision.as_str(),+ ),+ ("identity.license", self.identity.license.as_str()),+ ("onnx_runtime.version", self.onnx_runtime.version.as_str()),+ ("onnx_runtime.target", self.onnx_runtime.target.as_str()),+ ("detector.input_name", self.detector.input_name.as_str()),+ ("detector.output_name", self.detector.output_name.as_str()),+ (+ "ocr.detector.input_name",+ self.ocr.detector.input_name.as_str(),+ ),+ (+ "ocr.detector.output_name",+ self.ocr.detector.output_name.as_str(),+ ),+ (+ "ocr.recognizer.input_name",+ self.ocr.recognizer.input_name.as_str(),+ ),+ (+ "ocr.recognizer.output_name",+ self.ocr.recognizer.output_name.as_str(),+ ),+ ] {+ if value.trim().is_empty() {+ return Err(ManifestError::EmptyField(name));+ }+ }+ for (name, width, height) in [+ (+ "detector input dimensions",+ self.detector.input_width,+ self.detector.input_height,+ ),+ (+ "OCR detector input dimensions",+ self.ocr.detector.input_width,+ self.ocr.detector.input_height,+ ),+ (+ "OCR recognizer input dimensions",+ self.ocr.recognizer.input_width,+ self.ocr.recognizer.input_height,+ ),+ ] {+ if width == 0 || height == 0 || width > 4096 || height > 4096 {+ return Err(ManifestError::InvalidValue(name));+ }+ }+ if !(0.0..=1.0).contains(&self.detector.confidence_threshold)+ || !(0.0..=1.0).contains(&self.detector.iou_threshold)+ || !(0.0..=1.0).contains(&self.ocr.detector.pixel_threshold)+ || !(0.0..=1.0).contains(&self.ocr.detector.box_threshold)+ || self.ocr.detector.unclip_ratio < 1.0+ || self.ocr.detector.minimum_area == 0+ || self.ocr.detector.minimum_side == 0+ || self.ocr.detector.max_candidates == 0+ || self.detector.max_candidates == 0+ || self.detector.max_detections == 0+ || self.detector.max_detections > self.detector.max_candidates+ {+ return Err(ManifestError::InvalidValue("postprocessing thresholds"));+ }+ validate_sha256(+ "onnx_runtime.library_sha256",+ &self.onnx_runtime.library_sha256,+ )?;+ if self.onnx_runtime.intra_threads == 0 || self.onnx_runtime.intra_threads > 64 {+ return Err(ManifestError::InvalidValue("onnx_runtime.intra_threads"));+ }+ let actual_target = current_target();+ if self.onnx_runtime.target != actual_target {+ return Err(ManifestError::InvalidValue("onnx_runtime.target"));+ }+ for artifact in [+ &self.detector.model,+ &self.ocr.detector.model,+ &self.ocr.recognizer.model,+ &self.ocr.dictionary,+ ] {+ validate_sha256("artifact.sha256", &artifact.sha256)?;+ }+ Ok(())+ }+}++fn current_target() -> String {+ let arch = std::env::consts::ARCH;+ let suffix = match std::env::consts::OS {+ "macos" => "apple-darwin",+ "windows" => "pc-windows-msvc",+ "linux" => "unknown-linux-gnu",+ other => other,+ };+ format!("{arch}-{suffix}")+}++fn validate_sha256(field: &'static str, value: &str) -> Result<(), ManifestError> {+ if value.len() != 64 || !value.bytes().all(|byte| byte.is_ascii_hexdigit()) {+ return Err(ManifestError::InvalidValue(field));+ }+ Ok(())+}++fn validate_artifact(root: &Path, artifact: &Artifact) -> Result<PathBuf, ManifestError> {+ if artifact.path.is_absolute()+ || artifact+ .path+ .components()+ .any(|part| !matches!(part, Component::Normal(_)))+ {+ return Err(ManifestError::UnsafePath(artifact.path.clone()));+ }+ let path = root.join(&artifact.path);+ validate_absolute_artifact(&path, &artifact.sha256)?;+ Ok(path)+}++fn validate_absolute_artifact(path: &Path, expected: &str) -> Result<(), ManifestError> {+ let metadata =+ fs::symlink_metadata(path).map_err(|_| ManifestError::MissingArtifact(path.into()))?;+ if !metadata.file_type().is_file() || metadata.len() == 0 {+ return Err(ManifestError::MissingArtifact(path.into()));+ }+ let actual = digest(&read_bytes(path)?);+ if !actual.eq_ignore_ascii_case(expected) {+ return Err(ManifestError::HashMismatch {+ path: path.into(),+ expected: expected.to_ascii_lowercase(),+ actual,+ });+ }+ Ok(())+}++fn read_bytes(path: &Path) -> Result<Vec<u8>, ManifestError> {+ fs::read(path).map_err(|error| ManifestError::Read {+ path: path.into(),+ reason: error.to_string(),+ })+}++pub fn digest(bytes: &[u8]) -> String {+ format!("{:x}", Sha256::digest(bytes))+}++#[cfg(test)]+mod tests {+ use std::time::{SystemTime, UNIX_EPOCH};++ use serde_json::json;++ use super::*;++ struct TestDirectory(PathBuf);++ impl TestDirectory {+ fn new() -> Self {+ let nonce = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_nanos();+ let path = std::env::temp_dir().join(format!(+ "cua-perception-manifest-{}-{nonce}",+ std::process::id()+ ));+ fs::create_dir(&path).unwrap();+ Self(path)+ }+ }++ impl Drop for TestDirectory {+ fn drop(&mut self) {+ let _ = fs::remove_dir_all(&self.0);+ }+ }++ #[test]+ fn manifest_loads_only_when_every_hash_matches() {+ let directory = TestDirectory::new();+ for name in ["detector.onnx", "ocr-det.onnx", "ocr-rec.onnx"] {+ fs::write(directory.0.join(name), name.as_bytes()).unwrap();+ }+ fs::write(directory.0.join("dictionary.txt"), b"a\nb\n").unwrap();+ fs::write(directory.0.join("runtime.dylib"), b"runtime").unwrap();+ let artifact = |name: &str| {+ json!({+ "path": name,+ "sha256": digest(&fs::read(directory.0.join(name)).unwrap())+ })+ };+ let mut manifest = json!({+ "schema_version": 1,+ "identity": {+ "name": "test", "version": "1", "source_url": "https://example.invalid",+ "source_revision": "abc", "license": "test-only"+ },+ "onnx_runtime": {+ "version": "1", "target": current_target(),+ "library_sha256": digest(b"runtime"), "intra_threads": 1+ },+ "detector": {+ "model": artifact("detector.onnx"), "input_name": "images", "output_name": "output0",+ "input_width": 32, "input_height": 32, "confidence_threshold": 0.3,+ "iou_threshold": 0.1, "output_layout": "yolo_v8_cxcywh_class_scores",+ "max_candidates": 100, "max_detections": 10+ },+ "ocr": {+ "detector": {+ "model": artifact("ocr-det.onnx"), "input_name": "x", "output_name": "out",+ "input_width": 32, "input_height": 32, "pixel_threshold": 0.3,+ "box_threshold": 0.6, "unclip_ratio": 1.5, "minimum_area": 1,+ "minimum_side": 1, "max_candidates": 10+ },+ "recognizer": {+ "model": artifact("ocr-rec.onnx"), "input_name": "x", "output_name": "out",+ "input_width": 32, "input_height": 32, "blank_index": 0+ },+ "dictionary": artifact("dictionary.txt"),+ "dictionary_format": "plain_lines"+ }+ });+ let manifest_path = directory.0.join("manifest.json");+ fs::write(&manifest_path, serde_json::to_vec(&manifest).unwrap()).unwrap();++ let validated =+ ValidatedManifest::load(&manifest_path, &directory.0.join("runtime.dylib")).unwrap();+ assert_eq!(validated.manifest.identity.name, "test");++ manifest["onnx_runtime"]["target"] = json!("wrong-target");+ fs::write(&manifest_path, serde_json::to_vec(&manifest).unwrap()).unwrap();+ assert!(matches!(+ ValidatedManifest::load(&manifest_path, &directory.0.join("runtime.dylib")),+ Err(ManifestError::InvalidValue("onnx_runtime.target"))+ ));+ manifest["onnx_runtime"]["target"] = json!(current_target());+ fs::write(&manifest_path, serde_json::to_vec(&manifest).unwrap()).unwrap();++ fs::write(directory.0.join("detector.onnx"), b"tampered").unwrap();+ assert!(matches!(+ ValidatedManifest::load(&manifest_path, &directory.0.join("runtime.dylib")),+ Err(ManifestError::HashMismatch { .. })+ ));+ }++ #[test]+ fn artifact_paths_cannot_escape_the_manifest_directory() {+ let artifact = Artifact {+ path: PathBuf::from("../model.onnx"),+ sha256: "0".repeat(64),+ };+ assert!(matches!(+ validate_artifact(Path::new("/tmp/models"), &artifact),+ Err(ManifestError::UnsafePath(_))+ ));+ }+}diff --git a/libs/cua-driver/rust/crates/cua-perception/src/postprocess.rs b/libs/cua-driver/rust/crates/cua-perception/src/postprocess.rsnew file mode 100644index 0000000000..3531f8f0eb--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/src/postprocess.rs@@ -0,0 +1,537 @@+use std::collections::VecDeque;++use crate::{manifest::DetectorOutputLayout, preprocess::Letterbox};++#[derive(Debug, Clone, Copy, PartialEq)]+pub struct Rect {+ pub x1: f32,+ pub y1: f32,+ pub x2: f32,+ pub y2: f32,+}++#[derive(Debug, Clone, PartialEq)]+pub struct Detection {+ pub bounds: Rect,+ pub score: f32,+ pub class_id: usize,+}++#[derive(Debug, Clone, Copy)]+pub struct OcrPostprocess {+ pub pixel_threshold: f32,+ pub box_threshold: f32,+ pub unclip_ratio: f32,+ pub minimum_area: u32,+ pub minimum_side: u32,+ pub max_candidates: usize,+}++#[derive(Debug, Clone, Copy)]+pub struct DetectorPostprocess {+ pub confidence_threshold: f32,+ pub iou_threshold: f32,+ pub max_candidates: usize,+ pub max_detections: usize,+}++pub fn decode_detector(+ data: &[f32],+ shape: &[i64],+ layout: DetectorOutputLayout,+ transform: Letterbox,+ config: DetectorPostprocess,+) -> Result<Vec<Detection>, String> {+ let mut candidates = match layout {+ DetectorOutputLayout::YoloV8CxcywhClassScores => {+ decode_yolo_v8(data, shape, transform, config.confidence_threshold)?+ }+ DetectorOutputLayout::XyxyScoreClass => {+ decode_xyxy(data, shape, transform, config.confidence_threshold)?+ }+ };+ candidates.sort_by(|left, right| right.score.total_cmp(&left.score));+ candidates.truncate(config.max_candidates);+ let mut kept: Vec<Detection> = Vec::new();+ for candidate in candidates {+ if kept+ .iter()+ .all(|existing| iou(candidate.bounds, existing.bounds) <= config.iou_threshold)+ {+ kept.push(candidate);+ if kept.len() == config.max_detections {+ break;+ }+ }+ }+ Ok(kept)+}++fn decode_yolo_v8(+ data: &[f32],+ shape: &[i64],+ transform: Letterbox,+ threshold: f32,+) -> Result<Vec<Detection>, String> {+ let dims = squeeze_batch(shape)?;+ if dims.len() != 2 {+ return Err(format!(+ "YOLO detector output must be rank 2 or 3, got {shape:?}"+ ));+ }+ let (features, boxes, feature_major) = if dims[0] >= 5 && (dims[1] < 5 || dims[0] < dims[1]) {+ (dims[0], dims[1], true)+ } else if dims[1] >= 5 {+ (dims[1], dims[0], false)+ } else {+ return Err(format!(+ "YOLO detector output has no class scores: {shape:?}"+ ));+ };+ if data.len() != features * boxes {+ return Err("detector tensor shape does not match its data length".to_owned());+ }+ let at = |box_index: usize, feature: usize| {+ if feature_major {+ data[feature * boxes + box_index]+ } else {+ data[box_index * features + feature]+ }+ };+ let mut detections = Vec::new();+ for box_index in 0..boxes {+ let (class_id, score) = (4..features)+ .map(|feature| (feature - 4, at(box_index, feature)))+ .max_by(|left, right| left.1.total_cmp(&right.1))+ .unwrap();+ if !score.is_finite() || score < threshold {+ continue;+ }+ let cx = at(box_index, 0);+ let cy = at(box_index, 1);+ let width = at(box_index, 2);+ let height = at(box_index, 3);+ let bounds = restore(+ Rect {+ x1: cx - width / 2.0,+ y1: cy - height / 2.0,+ x2: cx + width / 2.0,+ y2: cy + height / 2.0,+ },+ transform,+ );+ if valid(bounds) {+ detections.push(Detection {+ bounds,+ score,+ class_id,+ });+ }+ }+ Ok(detections)+}++fn decode_xyxy(+ data: &[f32],+ shape: &[i64],+ transform: Letterbox,+ threshold: f32,+) -> Result<Vec<Detection>, String> {+ let dims = squeeze_batch(shape)?;+ if dims.len() != 2 || dims[1] != 6 || data.len() != dims[0] * 6 {+ return Err(format!(+ "xyxy detector output must have shape [N,6], got {shape:?}"+ ));+ }+ let mut detections = Vec::new();+ for row in data.chunks_exact(6) {+ if row[4].is_finite() && row[4] >= threshold {+ let bounds = restore(+ Rect {+ x1: row[0],+ y1: row[1],+ x2: row[2],+ y2: row[3],+ },+ transform,+ );+ if valid(bounds) && row[5].is_finite() && row[5] >= 0.0 {+ detections.push(Detection {+ bounds,+ score: row[4],+ class_id: row[5] as usize,+ });+ }+ }+ }+ Ok(detections)+}++pub fn decode_ocr_probability_map(+ data: &[f32],+ shape: &[i64],+ transform: Letterbox,+ config: OcrPostprocess,+) -> Result<Vec<Detection>, String> {+ let (height, width) = probability_map_dimensions(shape)?;+ if data.len() != width * height {+ return Err("OCR detector tensor shape does not match its data length".to_owned());+ }+ let mut visited = vec![false; data.len()];+ let mut regions = Vec::new();+ for start in 0..data.len() {+ if visited[start] || !data[start].is_finite() || data[start] < config.pixel_threshold {+ continue;+ }+ visited[start] = true;+ let mut queue = VecDeque::from([start]);+ let mut min_x = width;+ let mut min_y = height;+ let mut max_x = 0;+ let mut max_y = 0;+ let mut area = 0_u32;+ let mut confidence = 0.0_f32;+ while let Some(index) = queue.pop_front() {+ let x = index % width;+ let y = index / width;+ min_x = min_x.min(x);+ min_y = min_y.min(y);+ max_x = max_x.max(x);+ max_y = max_y.max(y);+ area += 1;+ confidence += data[index];+ for neighbor in neighbors(x, y, width, height) {+ if !visited[neighbor]+ && data[neighbor].is_finite()+ && data[neighbor] >= config.pixel_threshold+ {+ visited[neighbor] = true;+ queue.push_back(neighbor);+ }+ }+ }+ let confidence = confidence / area as f32;+ let box_width = max_x - min_x + 1;+ let box_height = max_y - min_y + 1;+ let rectangle_score = rectangle_mean(data, width, min_x, min_y, max_x, max_y);+ if area < config.minimum_area+ || box_width.min(box_height) < config.minimum_side as usize+ || rectangle_score < config.box_threshold+ {+ continue;+ }+ let perimeter = 2.0 * (box_width + box_height) as f32;+ let expansion =+ ((box_width * box_height) as f32 * config.unclip_ratio / perimeter).ceil() as usize;+ min_x = min_x.saturating_sub(expansion);+ min_y = min_y.saturating_sub(expansion);+ max_x = (max_x + expansion).min(width - 1);+ max_y = (max_y + expansion).min(height - 1);+ let scale_x = transform.input_width as f32 / width as f32;+ let scale_y = transform.input_height as f32 / height as f32;+ let bounds = restore(+ Rect {+ x1: min_x as f32 * scale_x,+ y1: min_y as f32 * scale_y,+ x2: (max_x + 1) as f32 * scale_x,+ y2: (max_y + 1) as f32 * scale_y,+ },+ transform,+ );+ if valid(bounds) {+ regions.push(Detection {+ bounds,+ score: rectangle_score.min(confidence),+ class_id: 0,+ });+ }+ }+ regions.sort_by(|left, right| {+ left.bounds+ .y1+ .total_cmp(&right.bounds.y1)+ .then(left.bounds.x1.total_cmp(&right.bounds.x1))+ });+ regions.truncate(config.max_candidates);+ Ok(regions)+}++fn rectangle_mean(+ data: &[f32],+ width: usize,+ min_x: usize,+ min_y: usize,+ max_x: usize,+ max_y: usize,+) -> f32 {+ let mut sum = 0.0;+ let mut count = 0;+ for y in min_y..=max_y {+ for x in min_x..=max_x {+ let value = data[y * width + x];+ if value.is_finite() {+ sum += value;+ count += 1;+ }+ }+ }+ if count == 0 {+ 0.0+ } else {+ sum / count as f32+ }+}++pub fn ctc_decode(+ data: &[f32],+ shape: &[i64],+ dictionary: &[String],+ blank_index: usize,+) -> Result<(String, f32), String> {+ let dims = squeeze_batch(shape)?;+ if dims.len() != 2 {+ return Err(format!(+ "OCR recognizer output must have shape [1,T,C], got {shape:?}"+ ));+ }+ let (steps, classes) = (dims[0], dims[1]);+ if data.len() != steps * classes || blank_index >= classes {+ return Err("OCR recognizer tensor metadata is inconsistent".to_owned());+ }+ let mut previous = blank_index;+ let mut text = String::new();+ let mut confidence = 0.0;+ let mut emitted = 0_u32;+ for logits in data.chunks_exact(classes) {+ let (index, score) = logits+ .iter()+ .copied()+ .enumerate()+ .max_by(|left, right| left.1.total_cmp(&right.1))+ .unwrap();+ if index != blank_index && index != previous {+ let dictionary_index = if index > blank_index {+ index - 1+ } else {+ index+ };+ let symbol = dictionary.get(dictionary_index).ok_or_else(|| {+ format!("OCR class {index} is missing from the recognition dictionary")+ })?;+ text.push_str(symbol);+ confidence += score;+ emitted += 1;+ }+ previous = index;+ }+ Ok((+ text,+ if emitted == 0 {+ 0.0+ } else {+ confidence / emitted as f32+ },+ ))+}++fn squeeze_batch(shape: &[i64]) -> Result<Vec<usize>, String> {+ let mut dims = shape+ .iter()+ .map(|dimension| {+ usize::try_from(*dimension).map_err(|_| "negative tensor dimension".to_owned())+ })+ .collect::<Result<Vec<_>, _>>()?;+ if dims.first() == Some(&1) {+ dims.remove(0);+ }+ Ok(dims)+}++fn probability_map_dimensions(shape: &[i64]) -> Result<(usize, usize), String> {+ let dims = squeeze_batch(shape)?;+ match dims.as_slice() {+ [1, height, width] | [height, width] => Ok((*height, *width)),+ _ => Err(format!(+ "OCR probability map must have shape [1,1,H,W], got {shape:?}"+ )),+ }+}++fn restore(bounds: Rect, transform: Letterbox) -> Rect {+ let x = |value: f32| {+ ((value - transform.pad_x as f32) / transform.scale_x)+ .clamp(0.0, transform.original_width as f32)+ };+ let y = |value: f32| {+ ((value - transform.pad_y as f32) / transform.scale_y)+ .clamp(0.0, transform.original_height as f32)+ };+ Rect {+ x1: x(bounds.x1),+ y1: y(bounds.y1),+ x2: x(bounds.x2),+ y2: y(bounds.y2),+ }+}++fn valid(bounds: Rect) -> bool {+ bounds.x1.is_finite()+ && bounds.y1.is_finite()+ && bounds.x2.is_finite()+ && bounds.y2.is_finite()+ && bounds.x2 > bounds.x1+ && bounds.y2 > bounds.y1+}++fn iou(left: Rect, right: Rect) -> f32 {+ let intersection_width = (left.x2.min(right.x2) - left.x1.max(right.x1)).max(0.0);+ let intersection_height = (left.y2.min(right.y2) - left.y1.max(right.y1)).max(0.0);+ let intersection = intersection_width * intersection_height;+ let left_area = (left.x2 - left.x1) * (left.y2 - left.y1);+ let right_area = (right.x2 - right.x1) * (right.y2 - right.y1);+ intersection / (left_area + right_area - intersection).max(f32::EPSILON)+}++fn neighbors(x: usize, y: usize, width: usize, height: usize) -> impl Iterator<Item = usize> {+ let mut values = [None; 4];+ if x > 0 {+ values[0] = Some(y * width + x - 1);+ }+ if x + 1 < width {+ values[1] = Some(y * width + x + 1);+ }+ if y > 0 {+ values[2] = Some((y - 1) * width + x);+ }+ if y + 1 < height {+ values[3] = Some((y + 1) * width + x);+ }+ values.into_iter().flatten()+}++#[cfg(test)]+mod tests {+ use super::*;++ fn transform() -> Letterbox {+ Letterbox {+ original_width: 100,+ original_height: 50,+ input_width: 200,+ input_height: 200,+ resized_width: 200,+ resized_height: 100,+ pad_x: 0,+ pad_y: 50,+ scale_x: 2.0,+ scale_y: 2.0,+ }+ }++ #[test]+ fn yolo_decode_restores_coordinates_and_applies_nms() {+ let tensor = [+ 100.0, 102.0, 25.0, // cx+ 100.0, 102.0, 75.0, // cy+ 40.0, 40.0, 10.0, // width+ 20.0, 20.0, 10.0, // height+ 0.9, 0.8, 0.7, // class 0+ ];+ let detections = decode_detector(+ &tensor,+ &[1, 5, 3],+ DetectorOutputLayout::YoloV8CxcywhClassScores,+ transform(),+ DetectorPostprocess {+ confidence_threshold: 0.5,+ iou_threshold: 0.5,+ max_candidates: 100,+ max_detections: 10,+ },+ )+ .unwrap();+ assert_eq!(detections.len(), 2);+ assert_eq!(+ detections[0].bounds,+ Rect {+ x1: 40.0,+ y1: 20.0,+ x2: 60.0,+ y2: 30.0+ }+ );+ assert_eq!(+ detections[1].bounds,+ Rect {+ x1: 10.0,+ y1: 10.0,+ x2: 15.0,+ y2: 15.0+ }+ );+ }++ #[test]+ fn detector_candidate_and_detection_counts_are_bounded() {+ let tensor = [+ 0.0, 60.0, 10.0, 70.0, 0.7, 0.0, 20.0, 60.0, 30.0, 70.0, 0.9, 0.0, 40.0, 60.0, 50.0,+ 70.0, 0.8, 0.0,+ ];+ let decode = |max_candidates, max_detections| {+ decode_detector(+ &tensor,+ &[1, 3, 6],+ DetectorOutputLayout::XyxyScoreClass,+ transform(),+ DetectorPostprocess {+ confidence_threshold: 0.5,+ iou_threshold: 0.5,+ max_candidates,+ max_detections,+ },+ )+ .unwrap()+ };++ let candidates_bounded = decode(2, 2);+ assert_eq!(candidates_bounded.len(), 2);+ assert_eq!(candidates_bounded[0].score, 0.9);+ assert_eq!(candidates_bounded[1].score, 0.8);+ assert_eq!(decode(3, 1).len(), 1);+ }++ #[test]+ fn probability_map_groups_connected_text_pixels() {+ let map = [0.9, 0.8, 0.0, 0.0, 0.9, 0.0, 0.0, 0.7];+ let regions = decode_ocr_probability_map(+ &map,+ &[1, 1, 2, 4],+ transform(),+ OcrPostprocess {+ pixel_threshold: 0.5,+ box_threshold: 0.6,+ unclip_ratio: 1.5,+ minimum_area: 2,+ minimum_side: 1,+ max_candidates: 100,+ },+ )+ .unwrap();+ assert_eq!(regions.len(), 1);+ assert!((regions[0].score - 0.65).abs() < 1e-5);+ }++ #[test]+ fn ctc_decode_collapses_repeats_and_blank() {+ let logits = [+ 0.1, 0.9, 0.0, // a+ 0.1, 0.8, 0.1, // repeated a+ 0.9, 0.1, 0.0, // blank+ 0.0, 0.1, 0.9, // b+ ];+ let (text, confidence) =+ ctc_decode(&logits, &[1, 4, 3], &["a".into(), "b".into()], 0).unwrap();+ assert_eq!(text, "ab");+ assert!((confidence - 0.9).abs() < 1e-6);+ }+}diff --git a/libs/cua-driver/rust/crates/cua-perception/src/preprocess.rs b/libs/cua-driver/rust/crates/cua-perception/src/preprocess.rsnew file mode 100644index 0000000000..7707dd03e3--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/src/preprocess.rs@@ -0,0 +1,196 @@+use image::{imageops::FilterType, Rgb, RgbImage};++#[derive(Debug, Clone, Copy, PartialEq)]+pub struct Letterbox {+ pub original_width: u32,+ pub original_height: u32,+ pub input_width: u32,+ pub input_height: u32,+ pub resized_width: u32,+ pub resized_height: u32,+ pub pad_x: u32,+ pub pad_y: u32,+ pub scale_x: f32,+ pub scale_y: f32,+}++#[derive(Debug, Clone, PartialEq)]+pub struct ImageTensor {+ pub shape: [usize; 4],+ pub data: Vec<f32>,+ pub letterbox: Letterbox,+}++pub fn detector_tensor(image: &RgbImage, width: u32, height: u32) -> ImageTensor {+ let (canvas, letterbox) = letterbox(image, width, height, Rgb([114, 114, 114]));+ ImageTensor {+ shape: [1, 3, height as usize, width as usize],+ data: rgb_chw(&canvas, [0.0; 3], [1.0; 3], 1.0 / 255.0),+ letterbox,+ }+}++pub fn ocr_detector_tensor(image: &RgbImage, resize_long: u32) -> ImageTensor {+ let scale = resize_long as f32 / image.width().max(image.height()) as f32;+ let width = round_to_multiple((image.width() as f32 * scale).round() as u32, 128);+ let height = round_to_multiple((image.height() as f32 * scale).round() as u32, 128);+ let resized = image::imageops::resize(image, width, height, FilterType::Triangle);+ let letterbox = Letterbox {+ original_width: image.width(),+ original_height: image.height(),+ input_width: width,+ input_height: height,+ resized_width: width,+ resized_height: height,+ pad_x: 0,+ pad_y: 0,+ scale_x: width as f32 / image.width() as f32,+ scale_y: height as f32 / image.height() as f32,+ };+ ImageTensor {+ shape: [1, 3, height as usize, width as usize],+ data: bgr_chw(+ &resized,+ [0.485, 0.456, 0.406],+ [0.229, 0.224, 0.225],+ 1.0 / 255.0,+ ),+ letterbox,+ }+}++pub fn ocr_recognizer_tensor(image: &RgbImage, width: u32, height: u32) -> ImageTensor {+ let scale = (height as f32 / image.height() as f32).min(width as f32 / image.width() as f32);+ let resized_width = ((image.width() as f32 * scale).round() as u32).clamp(1, width);+ let resized = image::imageops::resize(image, resized_width, height, FilterType::Triangle);+ // PP-OCR normalization maps 127.5 to zero. Mid-gray padding therefore+ // represents neutral input rather than solid black content.+ let mut canvas = RgbImage::from_pixel(width, height, Rgb([128, 128, 128]));+ image::imageops::replace(&mut canvas, &resized, 0, 0);+ let letterbox = Letterbox {+ original_width: image.width(),+ original_height: image.height(),+ input_width: width,+ input_height: height,+ resized_width,+ resized_height: height,+ pad_x: 0,+ pad_y: 0,+ scale_x: scale,+ scale_y: height as f32 / image.height() as f32,+ };+ ImageTensor {+ shape: [1, 3, height as usize, width as usize],+ data: bgr_chw(&canvas, [0.5; 3], [0.5; 3], 1.0 / 255.0),+ letterbox,+ }+}++fn letterbox(+ image: &RgbImage,+ input_width: u32,+ input_height: u32,+ fill: Rgb<u8>,+) -> (RgbImage, Letterbox) {+ let (original_width, original_height) = image.dimensions();+ let scale = (input_width as f32 / original_width as f32)+ .min(input_height as f32 / original_height as f32);+ let resized_width = ((original_width as f32 * scale).round() as u32).clamp(1, input_width);+ let resized_height = ((original_height as f32 * scale).round() as u32).clamp(1, input_height);+ let pad_x = (input_width - resized_width) / 2;+ let pad_y = (input_height - resized_height) / 2;+ let resized =+ image::imageops::resize(image, resized_width, resized_height, FilterType::Triangle);+ let mut canvas = RgbImage::from_pixel(input_width, input_height, fill);+ image::imageops::replace(&mut canvas, &resized, i64::from(pad_x), i64::from(pad_y));+ (+ canvas,+ Letterbox {+ original_width,+ original_height,+ input_width,+ input_height,+ resized_width,+ resized_height,+ pad_x,+ pad_y,+ scale_x: resized_width as f32 / original_width as f32,+ scale_y: resized_height as f32 / original_height as f32,+ },+ )+}++fn round_to_multiple(value: u32, multiple: u32) -> u32 {+ ((value.max(multiple) + multiple / 2) / multiple * multiple).max(multiple)+}++fn rgb_chw(image: &RgbImage, mean: [f32; 3], std: [f32; 3], scale: f32) -> Vec<f32> {+ channels_chw(image, mean, std, scale, [0, 1, 2])+}++fn bgr_chw(image: &RgbImage, mean: [f32; 3], std: [f32; 3], scale: f32) -> Vec<f32> {+ channels_chw(image, mean, std, scale, [2, 1, 0])+}++fn channels_chw(+ image: &RgbImage,+ mean: [f32; 3],+ std: [f32; 3],+ scale: f32,+ order: [usize; 3],+) -> Vec<f32> {+ let plane = image.width() as usize * image.height() as usize;+ let mut data = vec![0.0; plane * 3];+ for (index, pixel) in image.pixels().enumerate() {+ for channel in 0..3 {+ data[channel * plane + index] =+ (f32::from(pixel[order[channel]]) * scale - mean[channel]) / std[channel];+ }+ }+ data+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn detector_preprocessing_is_chw_and_letterboxed() {+ let image = RgbImage::from_fn(2, 1, |x, _| {+ if x == 0 {+ Rgb([255, 0, 0])+ } else {+ Rgb([0, 255, 0])+ }+ });+ let tensor = detector_tensor(&image, 4, 4);+ assert_eq!(tensor.shape, [1, 3, 4, 4]);+ assert_eq!(tensor.letterbox.resized_width, 4);+ assert_eq!(tensor.letterbox.resized_height, 2);+ assert_eq!(tensor.letterbox.pad_y, 1);+ assert_eq!(tensor.data.len(), 48);+ assert!((tensor.data[4] - 1.0).abs() < 1e-6);+ assert!((tensor.data[16..32].iter().copied().fold(0.0, f32::max) - 1.0).abs() < 1e-6);+ }++ #[test]+ fn recognizer_padding_is_deterministic() {+ let image = RgbImage::from_pixel(2, 2, Rgb([255, 255, 255]));+ let tensor = ocr_recognizer_tensor(&image, 8, 2);+ assert_eq!(tensor.letterbox.resized_width, 2);+ assert_eq!(tensor.data[0], 1.0);+ assert!((tensor.data[2] - (128.0 / 255.0 - 0.5) / 0.5).abs() < 1e-6);+ }++ #[test]+ fn ocr_detector_uses_bgr_and_resize_long() {+ let image = RgbImage::from_pixel(64, 32, Rgb([255, 0, 0]));+ let tensor = ocr_detector_tensor(&image, 96);+ assert_eq!(tensor.shape, [1, 3, 128, 128]);+ assert!(tensor.data[0] < 0.0, "B channel must receive source blue");+ assert!(+ tensor.data[2 * 128 * 128] > 1.0,+ "R channel must receive source red"+ );+ }+}diff --git a/libs/cua-driver/rust/crates/cua-perception/src/runtime.rs b/libs/cua-driver/rust/crates/cua-perception/src/runtime.rsnew file mode 100644index 0000000000..5b40a22153--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/src/runtime.rs@@ -0,0 +1,563 @@+use std::{+ ffi::{c_void, CStr},+ fs,+ os::raw::c_char,+ path::Path,+ sync::Mutex,+};++use image::{Rgb, RgbImage};+use libloading::Library;+use ort::{+ session::{builder::GraphOptimizationLevel, Session},+ tensor::TensorElementType,+ value::Tensor,+ value::ValueType,+};+use serde_json::{json, Value};+use thiserror::Error;++use crate::{+ manifest::{DictionaryFormat, ValidatedManifest},+ postprocess::{+ ctc_decode, decode_detector, decode_ocr_probability_map, Detection, DetectorPostprocess,+ OcrPostprocess, Rect,+ },+ preprocess::{detector_tensor, ocr_detector_tensor, ocr_recognizer_tensor, ImageTensor},+};++#[derive(Debug, Clone, PartialEq)]+pub struct InferenceRegion {+ pub kind: &'static str,+ pub bounds: Rect,+ pub text: Option<String>,+ pub confidence: f32,+ pub class_id: Option<usize>,+}++#[derive(Debug, Error)]+pub enum InferenceError {+ #[error("ONNX Runtime initialization failed: {0}")]+ Runtime(String),+ #[error("model {model} is missing input {name}")]+ MissingInput { model: &'static str, name: String },+ #[error("model {model} is missing output {name}")]+ MissingOutput { model: &'static str, name: String },+ #[error("model {model} inference failed: {reason}")]+ Run { model: &'static str, reason: String },+ #[error("model {model} output is invalid: {reason}")]+ Output { model: &'static str, reason: String },+ #[error("OCR dictionary could not be read: {0}")]+ Dictionary(String),+}++pub struct OnnxBackend {+ validated: ValidatedManifest,+ detector: Mutex<Session>,+ ocr_detector: Mutex<Session>,+ ocr_recognizer: Mutex<Session>,+ dictionary: Vec<String>,+}++impl OnnxBackend {+ pub fn load(validated: ValidatedManifest) -> Result<Self, InferenceError> {+ let runtime_version = runtime_version(&validated.runtime_library_path)?;+ verify_runtime_version(&validated.manifest.onnx_runtime.version, &runtime_version)?;+ ort::init_from(validated.runtime_library_path.to_string_lossy())+ .with_name("cua-perception")+ .with_telemetry(false)+ .commit()+ .map_err(|error| InferenceError::Runtime(error.to_string()))?;++ let threads = validated.manifest.onnx_runtime.intra_threads;+ let detector = load_session(&validated.detector_path, "detector", threads)?;+ verify_io(+ &detector,+ "detector",+ &validated.manifest.detector.input_name,+ &validated.manifest.detector.output_name,+ &[+ 1,+ 3,+ validated.manifest.detector.input_height as i64,+ validated.manifest.detector.input_width as i64,+ ],+ 3,+ )?;+ let ocr_detector = load_session(&validated.ocr_detector_path, "ocr_detector", threads)?;+ verify_io(+ &ocr_detector,+ "ocr_detector",+ &validated.manifest.ocr.detector.input_name,+ &validated.manifest.ocr.detector.output_name,+ &[1, 3, -1, -1],+ 4,+ )?;+ let ocr_recognizer =+ load_session(&validated.ocr_recognizer_path, "ocr_recognizer", threads)?;+ let dictionary_source = fs::read_to_string(&validated.dictionary_path)+ .map_err(|error| InferenceError::Dictionary(error.to_string()))?;+ let dictionary =+ parse_dictionary(&dictionary_source, validated.manifest.ocr.dictionary_format)?;+ verify_recognizer_io(&ocr_recognizer, &validated, dictionary.len())?;++ Ok(Self {+ validated,+ detector: Mutex::new(detector),+ ocr_detector: Mutex::new(ocr_detector),+ ocr_recognizer: Mutex::new(ocr_recognizer),+ dictionary,+ })+ }++ pub fn identity(&self) -> Value {+ json!({+ "backend": "onnx_runtime_cpu",+ "model": {+ "name": self.validated.manifest.identity.name,+ "version": self.validated.manifest.identity.version,+ "source_revision": self.validated.manifest.identity.source_revision,+ "manifest_sha256": self.validated.manifest_sha256,+ },+ "onnx_runtime": {+ "version": self.validated.manifest.onnx_runtime.version,+ "library_sha256": self.validated.manifest.onnx_runtime.library_sha256,+ "intra_threads": self.validated.manifest.onnx_runtime.intra_threads,+ },+ "text_geometry": "axis_aligned_bounds",+ "limitations": ["rotated_text_is_returned_as_an_axis_aligned_bound"]+ })+ }++ pub fn parse(&self, image: &RgbImage) -> Result<Vec<InferenceRegion>, InferenceError> {+ let detector_manifest = &self.validated.manifest.detector;+ let tensor = detector_tensor(+ image,+ detector_manifest.input_width,+ detector_manifest.input_height,+ );+ let detector_transform = tensor.letterbox;+ let (shape, output) = run_tensor(+ &self.detector,+ "detector",+ &detector_manifest.input_name,+ &detector_manifest.output_name,+ tensor,+ )?;+ let icons = decode_detector(+ &output,+ &shape,+ detector_manifest.output_layout,+ detector_transform,+ DetectorPostprocess {+ confidence_threshold: detector_manifest.confidence_threshold,+ iou_threshold: detector_manifest.iou_threshold,+ max_candidates: detector_manifest.max_candidates,+ max_detections: detector_manifest.max_detections,+ },+ )+ .map_err(|reason| InferenceError::Output {+ model: "detector",+ reason,+ })?;++ let ocr_detector_manifest = &self.validated.manifest.ocr.detector;+ let tensor = ocr_detector_tensor(image, ocr_detector_manifest.input_width);+ let ocr_transform = tensor.letterbox;+ let (shape, output) = run_tensor(+ &self.ocr_detector,+ "ocr_detector",+ &ocr_detector_manifest.input_name,+ &ocr_detector_manifest.output_name,+ tensor,+ )?;+ let text_boxes = decode_ocr_probability_map(+ &output,+ &shape,+ ocr_transform,+ OcrPostprocess {+ pixel_threshold: ocr_detector_manifest.pixel_threshold,+ box_threshold: ocr_detector_manifest.box_threshold,+ unclip_ratio: ocr_detector_manifest.unclip_ratio,+ minimum_area: ocr_detector_manifest.minimum_area,+ minimum_side: ocr_detector_manifest.minimum_side,+ max_candidates: ocr_detector_manifest.max_candidates,+ },+ )+ .map_err(|reason| InferenceError::Output {+ model: "ocr_detector",+ reason,+ })?;++ let mut regions = icons+ .into_iter()+ .map(|detection| InferenceRegion {+ kind: "icon",+ bounds: detection.bounds,+ text: None,+ confidence: detection.score,+ class_id: Some(detection.class_id),+ })+ .collect::<Vec<_>>();+ for detection in text_boxes {+ if let Some(region) = self.recognize(image, detection)? {+ regions.push(region);+ }+ }+ regions.sort_by(|left, right| {+ left.bounds+ .y1+ .total_cmp(&right.bounds.y1)+ .then(left.bounds.x1.total_cmp(&right.bounds.x1))+ .then(left.kind.cmp(right.kind))+ });+ Ok(regions)+ }++ pub fn self_test(&self) -> Result<Value, InferenceError> {+ let image = RgbImage::from_pixel(32, 32, Rgb([255, 255, 255]));+ let regions = self.parse(&image)?;+ Ok(json!({+ "passed": true,+ "checks": ["manifest_hashes", "onnx_session_io", "synthetic_inference"],+ "synthetic_region_count": regions.len(),+ "identity": self.identity()+ }))+ }++ fn recognize(+ &self,+ image: &RgbImage,+ detection: Detection,+ ) -> Result<Option<InferenceRegion>, InferenceError> {+ let (image_width, image_height) = image.dimensions();+ let x1 = detection.bounds.x1.floor().max(0.0) as u32;+ let y1 = detection.bounds.y1.floor().max(0.0) as u32;+ let x2 = detection.bounds.x2.ceil().min(image_width as f32) as u32;+ let y2 = detection.bounds.y2.ceil().min(image_height as f32) as u32;+ if x2 <= x1 || y2 <= y1 {+ return Ok(None);+ }+ let crop = image::imageops::crop_imm(image, x1, y1, x2 - x1, y2 - y1).to_image();+ let manifest = &self.validated.manifest.ocr.recognizer;+ let tensor = ocr_recognizer_tensor(&crop, manifest.input_width, manifest.input_height);+ let (shape, output) = run_tensor(+ &self.ocr_recognizer,+ "ocr_recognizer",+ &manifest.input_name,+ &manifest.output_name,+ tensor,+ )?;+ let (text, recognition_confidence) =+ ctc_decode(&output, &shape, &self.dictionary, manifest.blank_index).map_err(+ |reason| InferenceError::Output {+ model: "ocr_recognizer",+ reason,+ },+ )?;+ if text.is_empty() {+ return Ok(None);+ }+ Ok(Some(InferenceRegion {+ kind: "text",+ bounds: detection.bounds,+ text: Some(text),+ confidence: (detection.score * recognition_confidence).clamp(0.0, 1.0),+ class_id: None,+ }))+ }+}++fn parse_dictionary(source: &str, format: DictionaryFormat) -> Result<Vec<String>, InferenceError> {+ let values = match format {+ DictionaryFormat::PlainLines => source+ .lines()+ .map(|line| line.strip_suffix('\r').unwrap_or(line))+ .filter(|line| !line.is_empty())+ .map(str::to_owned)+ .collect(),+ DictionaryFormat::PaddleInferenceYaml => {+ let yaml: serde_yaml::Value = serde_yaml::from_str(source)+ .map_err(|error| InferenceError::Dictionary(error.to_string()))?;+ let sequence = yaml+ .get("PostProcess")+ .and_then(|value| value.get("character_dict"))+ .and_then(serde_yaml::Value::as_sequence)+ .ok_or_else(|| {+ InferenceError::Dictionary(+ "missing or invalid PostProcess.character_dict".to_owned(),+ )+ })?;+ let mut values = sequence+ .iter()+ .map(|value| {+ value.as_str().map(str::to_owned).ok_or_else(|| {+ InferenceError::Dictionary(+ "character_dict entries must be strings".to_owned(),+ )+ })+ })+ .collect::<Result<Vec<_>, _>>()?;+ // Paddle's CTCLabelDecode enables a trailing space class for this+ // model family even though the YAML list contains only symbols.+ values.push(" ".to_owned());+ values+ }+ };+ if values.is_empty() || values.iter().any(String::is_empty) {+ return Err(InferenceError::Dictionary(+ "dictionary contains no symbols".to_owned(),+ ));+ }+ Ok(values)+}++fn load_session(+ path: &Path,+ model: &'static str,+ intra_threads: usize,+) -> Result<Session, InferenceError> {+ Session::builder()+ .and_then(|builder| builder.with_optimization_level(GraphOptimizationLevel::Level3))+ .and_then(|builder| builder.with_intra_threads(intra_threads))+ .and_then(|builder| builder.with_memory_pattern(false))+ .and_then(|builder| builder.commit_from_file(path))+ .map_err(|error| InferenceError::Run {+ model,+ reason: error.to_string(),+ })+}++#[repr(C)]+struct OrtApiBase {+ get_api: unsafe extern "C" fn(u32) -> *const c_void,+ get_version_string: unsafe extern "C" fn() -> *const c_char,+}++fn runtime_version(path: &Path) -> Result<String, InferenceError> {+ // SAFETY: the library was hash-verified before this call. OrtGetApiBase is+ // the stable ONNX Runtime C ABI entry point, and the library remains loaded+ // while its version string is read into an owned Rust string.+ unsafe {+ let library =+ Library::new(path).map_err(|error| InferenceError::Runtime(error.to_string()))?;+ let get_api_base: libloading::Symbol<'_, unsafe extern "C" fn() -> *const OrtApiBase> =+ library+ .get(b"OrtGetApiBase\0")+ .map_err(|error| InferenceError::Runtime(error.to_string()))?;+ let api_base = get_api_base();+ if api_base.is_null() {+ return Err(InferenceError::Runtime(+ "OrtGetApiBase returned null".to_owned(),+ ));+ }+ let version = ((*api_base).get_version_string)();+ if version.is_null() {+ return Err(InferenceError::Runtime(+ "GetVersionString returned null".to_owned(),+ ));+ }+ CStr::from_ptr(version)+ .to_str()+ .map(str::to_owned)+ .map_err(|error| InferenceError::Runtime(error.to_string()))+ }+}++fn verify_runtime_version(declared: &str, actual: &str) -> Result<(), InferenceError> {+ if declared == actual {+ Ok(())+ } else {+ Err(InferenceError::Runtime(format!(+ "manifest declares ONNX Runtime {declared}, but library reports {actual}"+ )))+ }+}++fn verify_io(+ session: &Session,+ model: &'static str,+ input_name: &str,+ output_name: &str,+ expected_input_shape: &[i64],+ expected_output_rank: usize,+) -> Result<(), InferenceError> {+ let input = session+ .inputs+ .iter()+ .find(|input| input.name == input_name)+ .ok_or_else(|| InferenceError::MissingInput {+ model,+ name: input_name.to_owned(),+ })?;+ verify_tensor_type(+ model,+ "input",+ &input.input_type,+ expected_input_shape.len(),+ )?;+ verify_shape(model, "input", &input.input_type, expected_input_shape)?;+ let output = session+ .outputs+ .iter()+ .find(|output| output.name == output_name)+ .ok_or_else(|| InferenceError::MissingOutput {+ model,+ name: output_name.to_owned(),+ })?;+ verify_tensor_type(model, "output", &output.output_type, expected_output_rank)?;+ Ok(())+}++fn verify_recognizer_io(+ session: &Session,+ validated: &ValidatedManifest,+ dictionary_len: usize,+) -> Result<(), InferenceError> {+ let manifest = &validated.manifest.ocr.recognizer;+ verify_io(+ session,+ "ocr_recognizer",+ &manifest.input_name,+ &manifest.output_name,+ &[1, 3, manifest.input_height as i64, -1],+ 3,+ )?;+ let output = session+ .outputs+ .iter()+ .find(|output| output.name == manifest.output_name)+ .expect("verify_io proved the output exists");+ if let ValueType::Tensor { shape, .. } = &output.output_type {+ let classes = shape.last().copied().unwrap_or(-1);+ let expected = (dictionary_len + 1) as i64;+ if classes != expected {+ return Err(InferenceError::Output {+ model: "ocr_recognizer",+ reason: format!(+ "output has {classes} classes; dictionary plus blank requires {expected}"+ ),+ });+ }+ }+ Ok(())+}++fn verify_tensor_type(+ model: &'static str,+ route: &str,+ value_type: &ValueType,+ expected_rank: usize,+) -> Result<(), InferenceError> {+ match value_type {+ ValueType::Tensor { ty, shape, .. }+ if *ty == TensorElementType::Float32 && shape.len() == expected_rank =>+ {+ Ok(())+ }+ other => Err(InferenceError::Output {+ model,+ reason: format!("{route} must be a rank-{expected_rank} float32 tensor, got {other:?}"),+ }),+ }+}++fn verify_shape(+ model: &'static str,+ route: &str,+ value_type: &ValueType,+ expected: &[i64],+) -> Result<(), InferenceError> {+ let ValueType::Tensor { shape, .. } = value_type else {+ unreachable!("verify_tensor_type already checked the value type")+ };+ if shape.len() != expected.len()+ || shape+ .iter()+ .zip(expected)+ .any(|(actual, expected)| *expected >= 0 && *actual >= 0 && actual != expected)+ {+ return Err(InferenceError::Output {+ model,+ reason: format!("{route} shape {shape:?} does not match {expected:?}"),+ });+ }+ Ok(())+}++fn run_tensor(+ session: &Mutex<Session>,+ model: &'static str,+ input_name: &str,+ output_name: &str,+ tensor: ImageTensor,+) -> Result<(Vec<i64>, Vec<f32>), InferenceError> {+ let input =+ Tensor::from_array((tensor.shape, tensor.data.into_boxed_slice())).map_err(|error| {+ InferenceError::Run {+ model,+ reason: error.to_string(),+ }+ })?;+ let mut session = session.lock().map_err(|_| InferenceError::Run {+ model,+ reason: "model session lock was poisoned".to_owned(),+ })?;+ let outputs = session+ .run(vec![(input_name.to_owned(), input)])+ .map_err(|error| InferenceError::Run {+ model,+ reason: error.to_string(),+ })?;+ let output = outputs+ .get(output_name)+ .ok_or_else(|| InferenceError::MissingOutput {+ model,+ name: output_name.to_owned(),+ })?;+ let (shape, data) =+ output+ .try_extract_tensor::<f32>()+ .map_err(|error| InferenceError::Output {+ model,+ reason: error.to_string(),+ })?;+ Ok((shape.to_vec(), data.to_vec()))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn plain_dictionary_preserves_spaces() {+ assert_eq!(+ parse_dictionary("a\r\n \n b \n", DictionaryFormat::PlainLines).unwrap(),+ ["a", " ", " b "]+ );+ }++ #[test]+ fn paddle_yaml_dictionary_parses_quoted_symbols_and_rejects_bad_entries() {+ let parsed = parse_dictionary(+ "PostProcess:\n character_dict: [\"#\", 'a b', \" \" ]\n",+ DictionaryFormat::PaddleInferenceYaml,+ )+ .unwrap();+ assert_eq!(parsed, ["#", "a b", " ", " "]);++ for invalid in [+ "PostProcess:\n character_dict: [a, 7]\n",+ "PostProcess:\n character_dict: [\"\"]\n",+ "PostProcess: {}\n",+ ] {+ assert!(parse_dictionary(invalid, DictionaryFormat::PaddleInferenceYaml).is_err());+ }+ }++ #[test]+ fn runtime_version_must_match_manifest_exactly() {+ verify_runtime_version("1.26.0", "1.26.0").unwrap();+ assert!(verify_runtime_version("1.25.0", "1.26.0").is_err());+ }+}diff --git a/libs/cua-driver/rust/crates/cua-perception/tests/fixtures/parse-request.json b/libs/cua-driver/rust/crates/cua-perception/tests/fixtures/parse-request.jsonnew file mode 100644index 0000000000..c46a51fbaa--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/tests/fixtures/parse-request.json@@ -0,0 +1,15 @@+{+ "protocol": "cua-perception/1",+ "request_id": "fixture-parse-1",+ "method": "parse",+ "params": {+ "capture_id": "synthetic-1x1",+ "image": {+ "media_type": "image/png",+ "width": 1,+ "height": 1,+ "byte_length": 68,+ "data_base64": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="+ }+ }+}diff --git a/libs/cua-driver/rust/crates/cua-perception/tests/fixtures/parse-response.json b/libs/cua-driver/rust/crates/cua-perception/tests/fixtures/parse-response.jsonnew file mode 100644index 0000000000..da02970699--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/tests/fixtures/parse-response.json@@ -0,0 +1,33 @@+{+ "protocol": "cua-perception/1",+ "request_id": "fixture-parse-1",+ "status": "ok",+ "result": {+ "capture_id": "synthetic-1x1",+ "image": {+ "sha256": "431ced6916a2a21a156e38701afe55bbd7f88969fbbfc56d7fe099d47f265460",+ "width": 1,+ "height": 1+ },+ "coordinate_space": "image_pixels",+ "regions": [+ {+ "id": "fixture-text-1",+ "kind": "text",+ "bounds": { "x": 0, "y": 0, "width": 1, "height": 1 },+ "text": "fixture",+ "confidence": 1.0,+ "interactive": false+ }+ ],+ "runtime": "fixture_only",+ "identity": {+ "extension": {+ "id": "cua-perception",+ "version": "0.1.0"+ },+ "backend": "deterministic_fixture",+ "fixture_sha256": "431ced6916a2a21a156e38701afe55bbd7f88969fbbfc56d7fe099d47f265460"+ }+ }+}diff --git a/libs/cua-driver/rust/crates/cua-perception/tests/protocol.rs b/libs/cua-driver/rust/crates/cua-perception/tests/protocol.rsnew file mode 100644index 0000000000..efadeb0388--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/tests/protocol.rs@@ -0,0 +1,358 @@+use std::{+ io::{Cursor, Write},+ process::{Command, Output, Stdio},+};++use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};+use cua_perception::{+ handle_payload, read_frame, write_frame, FrameError, Response, MAX_FRAME_BYTES,+ MAX_IMAGE_DIMENSION,+};+use serde_json::{json, Value};++const FIXTURE_REQUEST: &str = include_str!("fixtures/parse-request.json");+const FIXTURE_RESPONSE: &str = include_str!("fixtures/parse-response.json");++fn response(payload: impl AsRef<[u8]>) -> Value {+ serde_json::to_value(handle_payload(payload.as_ref())).expect("serialize response")+}++#[test]+fn health_request_reports_fixture_only_capabilities() {+ let actual = response(+ br#"{"protocol":"cua-perception/1","request_id":"health-1","method":"health","params":{}}"#,+ );+ assert_eq!(actual["status"], "ok");+ assert_eq!(actual["result"]["ready"], true);+ assert_eq!(actual["result"]["runtime"], "fixture_only");+}++#[test]+fn protocol_mismatch_is_structured() {+ let actual = response(+ br#"{"protocol":"cua-perception/2","request_id":"version-1","method":"health","params":{}}"#,+ );+ assert_eq!(actual["status"], "error");+ assert_eq!(actual["error"]["code"], "incompatible_protocol");+ assert_eq!(actual["request_id"], "version-1");+}++#[test]+fn malformed_json_is_structured() {+ let actual = response(br#"{"protocol": broken"#);+ assert_eq!(actual["status"], "error");+ assert_eq!(actual["error"]["code"], "invalid_json");+ assert!(actual.get("request_id").is_none());+}++#[test]+fn framing_round_trips_and_rejects_malformed_lengths() {+ let payload = br#"{"fixture":true}"#;+ let mut framed = Vec::new();+ write_frame(&mut framed, payload).expect("write frame");+ assert_eq!(+ read_frame(&mut Cursor::new(framed)),+ Ok(Some(payload.to_vec()))+ );++ let mut oversized = Cursor::new(((MAX_FRAME_BYTES as u32) + 1).to_be_bytes());+ assert_eq!(+ read_frame(&mut oversized),+ Err(FrameError::Oversized {+ declared: MAX_FRAME_BYTES + 1,+ maximum: MAX_FRAME_BYTES+ })+ );++ let truncated = [0, 0, 0, 4, b'{', b'}'];+ let error = read_frame(&mut Cursor::new(truncated)).expect_err("reject truncated frame");+ assert_eq!(+ error,+ FrameError::TruncatedPayload {+ declared: 4,+ received: 2+ }+ );+ let structured =+ serde_json::to_value(Response::from_frame_error(&error)).expect("serialize framing error");+ assert_eq!(structured["status"], "error");+ assert_eq!(structured["error"]["code"], "invalid_frame");++ let prefix_error =+ read_frame(&mut Cursor::new([0_u8, 0_u8])).expect_err("reject partial prefix");+ assert_eq!(prefix_error, FrameError::TruncatedPrefix { received: 2 });+ let prefix_response = serde_json::to_value(Response::from_frame_error(&prefix_error))+ .expect("serialize prefix error");+ assert_eq!(+ prefix_response["error"]["message"],+ "frame length prefix is incomplete: received 2 of 4 bytes"+ );++ let error = write_frame(&mut Vec::new(), &vec![0; MAX_FRAME_BYTES + 1])+ .expect_err("reject oversized outbound frame");+ assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);+}++#[test]+fn oversized_dimensions_are_rejected_before_image_decode() {+ let request = json!({+ "protocol": "cua-perception/1",+ "request_id": "large-1",+ "method": "parse",+ "params": {+ "capture_id": "large",+ "image": {+ "media_type": "image/png",+ "width": 16385,+ "height": 1,+ "byte_length": 1,+ "data_base64": "AA=="+ }+ }+ });+ let actual = response(serde_json::to_vec(&request).expect("serialize request"));+ assert_eq!(actual["status"], "error");+ assert_eq!(actual["error"]["code"], "invalid_image");+ assert_eq!(actual["error"]["details"]["width"], 16385);+}++#[test]+fn image_byte_length_is_a_bounded_u64_on_the_wire() {+ let request = json!({+ "protocol": "cua-perception/1",+ "request_id": "large-byte-length",+ "method": "parse",+ "params": {+ "capture_id": "large-byte-length",+ "image": {+ "media_type": "image/png",+ "width": 1,+ "height": 1,+ "byte_length": 4_294_967_296_u64,+ "data_base64": ""+ }+ }+ });+ let actual = response(serde_json::to_vec(&request).expect("serialize request"));+ assert_eq!(actual["status"], "error");+ assert_eq!(actual["error"]["code"], "invalid_image");+ assert_eq!(actual["error"]["details"]["byte_length"], 4_294_967_296_u64);+}++#[test]+fn oversized_png_header_is_rejected_by_decoder_limits() {+ let actual = response_for_png_header(MAX_IMAGE_DIMENSION + 1, 1);+ assert_eq!(actual["status"], "error");+ assert_eq!(actual["error"]["code"], "invalid_image");+ assert_eq!(+ actual["error"]["message"],+ "decoded PNG exceeds image resource limits"+ );+}++#[test]+fn oversized_png_pixel_count_is_rejected_before_full_decode() {+ let actual = response_for_png_header(5793, 5793);+ assert_eq!(actual["status"], "error");+ assert_eq!(actual["error"]["code"], "invalid_image");+ assert_eq!(+ actual["error"]["message"],+ "decoded PNG dimensions exceed image resource limits"+ );+}++#[test]+fn zero_length_frame_is_recoverable() {+ let mut input = vec![0, 0, 0, 0];+ write_frame(+ &mut input,+ br#"{"protocol":"cua-perception/1","request_id":"after-empty","method":"health","params":{}}"#,+ )+ .unwrap();+ let output = run_worker(&input);+ assert!(output.status.success());+ let mut stdout = Cursor::new(output.stdout);+ assert_eq!(+ read_json_frame(&mut stdout)["error"]["code"],+ "invalid_json"+ );+ assert_eq!(read_json_frame(&mut stdout)["request_id"], "after-empty");+}++#[test]+fn fixture_parse_matches_the_checked_in_golden() {+ let actual = response(FIXTURE_REQUEST);+ let expected: Value = serde_json::from_str(FIXTURE_RESPONSE).expect("parse response golden");+ assert_eq!(actual, expected);+ assert_eq!(response(FIXTURE_REQUEST), expected);+}++#[test]+fn self_test_exercises_the_embedded_fixture() {+ let actual = response(+ br#"{"protocol":"cua-perception/1","request_id":"self-test-1","method":"self_test","params":{}}"#,+ );+ assert_eq!(actual["status"], "ok");+ assert_eq!(actual["result"]["passed"], true);+ assert_eq!(+ actual["result"]["checks"],+ json!(["fixture_decode", "image_validation", "known_answer_fixture"])+ );+}++#[test]+fn standalone_binary_serves_multiple_framed_requests_over_stdio() {+ let first_request =+ br#"{"protocol":"cua-perception/1","request_id":"binary-1","method":"health","params":{}}"#;+ let second_request =+ br#"{"protocol":"cua-perception/1","request_id":"binary-2","method":"self_test","params":{}}"#;+ let mut framed = Vec::new();+ write_frame(&mut framed, first_request).expect("frame first request");+ write_frame(&mut framed, second_request).expect("frame second request");++ let output = run_worker(&framed);++ assert!(+ output.status.success(),+ "stderr: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ assert!(output.stderr.is_empty());+ let mut stdout = Cursor::new(output.stdout);+ let first_payload = read_frame(&mut stdout)+ .expect("read response frame")+ .expect("response payload");+ let first: Value = serde_json::from_slice(&first_payload).expect("parse first response JSON");+ assert_eq!(first["request_id"], "binary-1");+ assert_eq!(first["status"], "ok");+ assert_eq!(first["result"]["ready"], true);++ let second_payload = read_frame(&mut stdout)+ .expect("read second response frame")+ .expect("second response payload");+ let second: Value =+ serde_json::from_slice(&second_payload).expect("parse second response JSON");+ assert_eq!(second["request_id"], "binary-2");+ assert_eq!(second["status"], "ok");+ assert_eq!(second["result"]["passed"], true);+ assert_eq!(read_frame(&mut stdout), Ok(None));+}++#[test]+fn standalone_binary_recovers_after_malformed_json_frame() {+ let mut framed = Vec::new();+ write_frame(&mut framed, br#"{"protocol":broken"#).expect("frame malformed JSON");+ write_frame(+ &mut framed,+ br#"{"protocol":"cua-perception/1","request_id":"after-error","method":"health","params":{}}"#,+ )+ .expect("frame valid request");++ let output = run_worker(&framed);+ assert!(output.status.success());+ assert!(output.stderr.is_empty());+ let mut stdout = Cursor::new(output.stdout);+ let malformed = read_json_frame(&mut stdout);+ assert_eq!(malformed["status"], "error");+ assert_eq!(malformed["error"]["code"], "invalid_json");+ let valid = read_json_frame(&mut stdout);+ assert_eq!(valid["request_id"], "after-error");+ assert_eq!(valid["status"], "ok");+ assert_eq!(read_frame(&mut stdout), Ok(None));+}++#[test]+fn standalone_binary_reports_oversized_frame_and_terminates() {+ let mut input = ((MAX_FRAME_BYTES as u32) + 1).to_be_bytes().to_vec();+ write_frame(+ &mut input,+ br#"{"protocol":"cua-perception/1","request_id":"must-not-run","method":"health","params":{}}"#,+ )+ .expect("append valid frame");++ let output = run_worker(&input);+ assert!(output.status.success());+ assert!(output.stderr.is_empty());+ let mut stdout = Cursor::new(output.stdout);+ let error = read_json_frame(&mut stdout);+ assert_eq!(error["status"], "error");+ assert_eq!(error["error"]["code"], "invalid_frame");+ assert!(error.get("request_id").is_none());+ assert_eq!(read_frame(&mut stdout), Ok(None));+}++#[test]+fn standalone_binary_requires_an_explicit_backend() {+ let output = Command::new(env!("CARGO_BIN_EXE_cua-perception"))+ .output()+ .expect("run worker without backend arguments");+ assert!(!output.status.success());+ assert!(output.stdout.is_empty());+ assert!(String::from_utf8_lossy(&output.stderr)+ .contains("usage: cua-perception --fixture | --manifest <manifest.json>"));+}++fn png_crc32(bytes: &[u8]) -> u32 {+ let mut crc = u32::MAX;+ for byte in bytes {+ crc ^= u32::from(*byte);+ for _ in 0..8 {+ let mask = 0_u32.wrapping_sub(crc & 1);+ crc = (crc >> 1) ^ (0xedb8_8320 & mask);+ }+ }+ !crc+}++fn response_for_png_header(width: u32, height: u32) -> Value {+ let request: Value = serde_json::from_str(FIXTURE_REQUEST).expect("parse fixture request");+ let encoded = request["params"]["image"]["data_base64"]+ .as_str()+ .expect("fixture base64");+ let mut png = BASE64.decode(encoded).expect("decode fixture PNG");+ png[16..20].copy_from_slice(&width.to_be_bytes());+ png[20..24].copy_from_slice(&height.to_be_bytes());+ let ihdr_crc = png_crc32(&png[12..29]);+ png[29..33].copy_from_slice(&ihdr_crc.to_be_bytes());++ let request = json!({+ "protocol": "cua-perception/1",+ "request_id": "oversized-ihdr-1",+ "method": "parse",+ "params": {+ "capture_id": "oversized-ihdr",+ "image": {+ "media_type": "image/png",+ "width": 1,+ "height": 1,+ "byte_length": png.len(),+ "data_base64": BASE64.encode(png)+ }+ }+ });+ response(serde_json::to_vec(&request).expect("serialize request"))+}++fn run_worker(input: &[u8]) -> Output {+ let mut child = Command::new(env!("CARGO_BIN_EXE_cua-perception"))+ .arg("--fixture")+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .expect("spawn worker");+ child+ .stdin+ .take()+ .expect("worker stdin")+ .write_all(input)+ .expect("write worker input");+ child.wait_with_output().expect("wait for worker")+}++fn read_json_frame(reader: &mut Cursor<Vec<u8>>) -> Value {+ let payload = read_frame(reader)+ .expect("read response frame")+ .expect("response payload");+ serde_json::from_slice(&payload).expect("parse response JSON")+}diff --git a/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/LICENSE b/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/LICENSEnew file mode 100644index 0000000000..35a6a05f2c--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Cua contributors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/PROVENANCE.md b/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/PROVENANCE.mdnew file mode 100644index 0000000000..d46de01bad--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/PROVENANCE.md@@ -0,0 +1,16 @@+# Provenance++The screenshots, bitmap glyphs, annotations, generator, and documentation in+this directory were created for Cua. They are synthetic and do not derive from+third-party screenshots, product artwork, fonts, icons, model output, customer+data, or recorded desktop sessions.++`generate.py` draws RGB pixels from geometric primitives, an original compact+5x7 bitmap alphabet embedded in the script, and fixed-seed pseudo-random noise.+The browser and remote-desktop scenarios are fictional interfaces. Names and+values are generic test strings and do not identify real users or systems.++The generated PNGs and `manifest.json` are checked in so tests and reviews do+not require a rendering dependency. `python3 generate.py --check` regenerates+the corpus in a temporary directory and compares every generated byte with the+checked-in files.diff --git a/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/README.md b/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/README.mdnew file mode 100644index 0000000000..c5d129e860--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/README.md@@ -0,0 +1,37 @@+# Cua Perception Synthetic Quality Corpus++This directory contains nine deterministic synthetic screenshots for evaluating+perception behavior without redistributing application screenshots or user data.+The scenarios cover native controls, browser canvas content, a remote-desktop-like+surface, light and dark themes, high-DPI and downsampled rendering, small text,+icon-only controls, overlapping OCR/control boxes, an empty surface, and noise.++`manifest.json` is the closed corpus contract. Coordinates are integer+`[x, y, width, height]` boxes in each PNG's source pixels, with the origin at the+top left. It records each image's SHA-256 digest and dimensions, scenario tags,+and expected text and control annotations. Metric definitions describe how a+consumer can report results; the corpus intentionally sets no quality floors.+The canonical scorer matches detections one-to-one at `IoU >= 0.5`. Its result+kind mapping treats both `control` and `icon` regions as control detections so+generic Rust regions and Python `cua-som` icon-only output share a denominator,+but leaves the annotated subtype unknown unless the producer explicitly+supplies `control_kind`.++Regenerate the checked-in PNGs and manifest with:++```sh+python3 generate.py+```++Verify schema semantics, coverage, hashes, dimensions, annotation bounds, the+closed image set, and byte-for-byte reproducibility with:++```sh+python3 generate.py --check+```++Generation uses only the Python standard library. Do not hand-edit generated+PNGs or `manifest.json`; change `generate.py`, regenerate, and rerun the check.++All material in this directory is Cua-authored synthetic test data released+under the MIT license in `LICENSE`. See `PROVENANCE.md` for provenance details.diff --git a/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/generate.py b/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/generate.pynew file mode 100644index 0000000000..9af06f098c--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/generate.py@@ -0,0 +1,516 @@+#!/usr/bin/env python3+"""Generate and validate the cua-perception synthetic quality corpus."""++from __future__ import annotations++import argparse+import hashlib+import json+import struct+import tempfile+import zlib+from dataclasses import dataclass+from pathlib import Path+++ROOT = Path(__file__).resolve().parent+CORPUS_VERSION = "1.0.0"+PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"++# A deliberately small, original 5x7 bitmap font keeps generation dependency-free.+FONT = {+ " ": (0, 0, 0, 0, 0, 0, 0),+ "-": (0, 0, 0, 31, 0, 0, 0),+ ".": (0, 0, 0, 0, 0, 12, 12),+ "/": (1, 2, 4, 8, 16, 0, 0),+ ":": (0, 12, 12, 0, 12, 12, 0),+ "?": (14, 17, 1, 2, 4, 0, 4),+ "0": (14, 17, 19, 21, 25, 17, 14),+ "1": (4, 12, 4, 4, 4, 4, 14),+ "2": (14, 17, 1, 2, 4, 8, 31),+ "3": (30, 1, 1, 14, 1, 1, 30),+ "4": (2, 6, 10, 18, 31, 2, 2),+ "5": (31, 16, 16, 30, 1, 1, 30),+ "6": (14, 16, 16, 30, 17, 17, 14),+ "7": (31, 1, 2, 4, 8, 8, 8),+ "8": (14, 17, 17, 14, 17, 17, 14),+ "9": (14, 17, 17, 15, 1, 1, 14),+ "A": (14, 17, 17, 31, 17, 17, 17),+ "B": (30, 17, 17, 30, 17, 17, 30),+ "C": (14, 17, 16, 16, 16, 17, 14),+ "D": (30, 17, 17, 17, 17, 17, 30),+ "E": (31, 16, 16, 30, 16, 16, 31),+ "F": (31, 16, 16, 30, 16, 16, 16),+ "G": (14, 17, 16, 23, 17, 17, 15),+ "H": (17, 17, 17, 31, 17, 17, 17),+ "I": (14, 4, 4, 4, 4, 4, 14),+ "J": (7, 2, 2, 2, 2, 18, 12),+ "K": (17, 18, 20, 24, 20, 18, 17),+ "L": (16, 16, 16, 16, 16, 16, 31),+ "M": (17, 27, 21, 21, 17, 17, 17),+ "N": (17, 25, 21, 19, 17, 17, 17),+ "O": (14, 17, 17, 17, 17, 17, 14),+ "P": (30, 17, 17, 30, 16, 16, 16),+ "Q": (14, 17, 17, 17, 21, 18, 13),+ "R": (30, 17, 17, 30, 20, 18, 17),+ "S": (15, 16, 16, 14, 1, 1, 30),+ "T": (31, 4, 4, 4, 4, 4, 4),+ "U": (17, 17, 17, 17, 17, 17, 14),+ "V": (17, 17, 17, 17, 17, 10, 4),+ "W": (17, 17, 17, 21, 21, 21, 10),+ "X": (17, 17, 10, 4, 10, 17, 17),+ "Y": (17, 17, 10, 4, 4, 4, 4),+ "Z": (31, 1, 2, 4, 8, 16, 31),+}+++@dataclass+class Scenario:+ filename: str+ width: int+ height: int+ tags: list[str]+ pixels: bytes+ text: list[dict]+ controls: list[dict]+++class Canvas:+ def __init__(self, width: int, height: int, color: tuple[int, int, int]):+ self.width = width+ self.height = height+ self.pixels = bytearray(color * (width * height))++ def point(self, x: int, y: int, color: tuple[int, int, int]) -> None:+ if 0 <= x < self.width and 0 <= y < self.height:+ offset = (y * self.width + x) * 3+ self.pixels[offset : offset + 3] = bytes(color)++ def rect(self, x: int, y: int, width: int, height: int, color: tuple[int, int, int]) -> None:+ x0, y0 = max(0, x), max(0, y)+ x1, y1 = min(self.width, x + width), min(self.height, y + height)+ row = bytes(color) * max(0, x1 - x0)+ for py in range(y0, y1):+ offset = (py * self.width + x0) * 3+ self.pixels[offset : offset + len(row)] = row++ def frame(self, x: int, y: int, width: int, height: int, color: tuple[int, int, int], thickness: int = 1) -> None:+ self.rect(x, y, width, thickness, color)+ self.rect(x, y + height - thickness, width, thickness, color)+ self.rect(x, y, thickness, height, color)+ self.rect(x + width - thickness, y, thickness, height, color)++ def line(self, x0: int, y0: int, x1: int, y1: int, color: tuple[int, int, int], thickness: int = 1) -> None:+ dx, sx = abs(x1 - x0), 1 if x0 < x1 else -1+ dy, sy = -abs(y1 - y0), 1 if y0 < y1 else -1+ error = dx + dy+ while True:+ self.rect(x0 - thickness // 2, y0 - thickness // 2, thickness, thickness, color)+ if x0 == x1 and y0 == y1:+ return+ twice = 2 * error+ if twice >= dy:+ error += dy+ x0 += sx+ if twice <= dx:+ error += dx+ y0 += sy++ def text(self, x: int, y: int, value: str, color: tuple[int, int, int], scale: int = 2) -> list[int]:+ value = value.upper()+ for index, char in enumerate(value):+ glyph = FONT.get(char, FONT["?"])+ gx = x + index * 6 * scale+ for row, bits in enumerate(glyph):+ for column in range(5):+ if bits & (1 << (4 - column)):+ self.rect(gx + column * scale, y + row * scale, scale, scale, color)+ width = max(0, len(value) * 6 * scale - scale)+ return [x, y, width, 7 * scale]++ def icon(self, kind: str, x: int, y: int, size: int, color: tuple[int, int, int]) -> None:+ pad = max(2, size // 5)+ if kind == "search":+ self.frame(x + pad, y + pad, size // 2, size // 2, color, max(1, size // 12))+ self.line(x + size // 2, y + size // 2, x + size - pad, y + size - pad, color, max(1, size // 10))+ elif kind == "close":+ self.line(x + pad, y + pad, x + size - pad, y + size - pad, color, max(1, size // 8))+ self.line(x + size - pad, y + pad, x + pad, y + size - pad, color, max(1, size // 8))+ elif kind == "play":+ for row in range(size - 2 * pad):+ width = max(1, row // 2 if row < (size - 2 * pad) // 2 else (size - 2 * pad - row) // 2)+ self.rect(x + pad, y + pad + row, width, 1, color)+ elif kind == "menu":+ for offset in (pad, size // 2, size - pad):+ self.rect(x + pad, y + offset - 1, size - 2 * pad, 3, color)+ elif kind == "gear":+ self.frame(x + pad, y + pad, size - 2 * pad, size - 2 * pad, color, max(1, size // 10))+ self.rect(x + size // 2 - 2, y + size // 2 - 2, 5, 5, color)+ else:+ self.frame(x + pad, y + pad, size - 2 * pad, size - 2 * pad, color, 2)+++def text_annotation(identifier: str, value: str, bbox: list[int], role: str) -> dict:+ return {"id": identifier, "text": value, "bbox": bbox, "role": role}+++def control_annotation(identifier: str, kind: str, label: str | None, bbox: list[int], state: str) -> dict:+ return {"id": identifier, "kind": kind, "label": label, "bbox": bbox, "state": state}+++def native_light() -> Scenario:+ c = Canvas(960, 600, (236, 239, 243))+ c.rect(0, 0, 960, 42, (36, 42, 52))+ title = c.text(18, 13, "SETTINGS", (244, 247, 250), 2)+ c.rect(28, 72, 904, 494, (255, 255, 255))+ c.frame(28, 72, 904, 494, (184, 190, 199), 1)+ heading = c.text(62, 104, "DEVICE SETTINGS", (31, 38, 49), 3)+ label = c.text(64, 178, "DEVICE NAME", (63, 71, 84), 2)+ c.rect(64, 204, 420, 44, (250, 251, 252)); c.frame(64, 204, 420, 44, (130, 139, 151), 2)+ value = c.text(78, 218, "DESK MAC", (28, 35, 45), 2)+ c.rect(64, 282, 22, 22, (43, 119, 226))+ c.line(69, 293, 74, 298, (255, 255, 255), 2); c.line(74, 298, 82, 287, (255, 255, 255), 2)+ check_label = c.text(100, 287, "ENABLE CAPTURE", (40, 47, 58), 2)+ c.rect(64, 342, 420, 8, (218, 222, 228)); c.rect(64, 342, 278, 8, (43, 119, 226))+ c.rect(330, 332, 24, 28, (255, 255, 255)); c.frame(330, 332, 24, 28, (43, 119, 226), 2)+ c.rect(700, 496, 104, 40, (255, 255, 255)); c.frame(700, 496, 104, 40, (103, 112, 125), 2)+ cancel = c.text(716, 510, "CANCEL", (51, 58, 69), 2)+ c.rect(816, 496, 84, 40, (31, 111, 235)); save = c.text(834, 510, "SAVE", (255, 255, 255), 2)+ return Scenario("native-controls-light.png", 960, 600,+ ["native-controls", "light", "standard-dpi", "small-text"], bytes(c.pixels),+ [text_annotation("window-title", "SETTINGS", title, "title"), text_annotation("heading", "DEVICE SETTINGS", heading, "heading"),+ text_annotation("device-label", "DEVICE NAME", label, "label"),+ text_annotation("device-value", "DESK MAC", value, "value"), text_annotation("capture-label", "ENABLE CAPTURE", check_label, "label"),+ text_annotation("cancel-text", "CANCEL", cancel, "button-label"), text_annotation("save-text", "SAVE", save, "button-label")],+ [control_annotation("device-input", "text-field", "DEVICE NAME", [64, 204, 420, 44], "enabled"),+ control_annotation("capture-checkbox", "checkbox", "ENABLE CAPTURE", [64, 282, 22, 22], "checked"),+ control_annotation("quality-slider", "slider", None, [64, 332, 290, 28], "enabled"),+ control_annotation("cancel-button", "button", "CANCEL", [700, 496, 104, 40], "enabled"),+ control_annotation("save-button", "button", "SAVE", [816, 496, 84, 40], "enabled")])+++def native_dark_hidpi() -> Scenario:+ c = Canvas(1440, 900, (24, 27, 33))+ c.rect(0, 0, 1440, 72, (15, 17, 22)); title = c.text(36, 24, "TRANSFER", (245, 247, 250), 4)+ c.rect(72, 126, 1296, 690, (31, 35, 43)); c.frame(72, 126, 1296, 690, (71, 78, 91), 2)+ heading = c.text(120, 174, "COPY FILES", (242, 244, 247), 5)+ source_label = c.text(124, 282, "SOURCE", (173, 181, 194), 3)+ c.rect(120, 324, 900, 72, (21, 24, 30)); c.frame(120, 324, 900, 72, (94, 104, 120), 3)+ source = c.text(146, 346, "/USERS/DEMO/REPORT.PDF", (231, 235, 241), 3)+ c.rect(1050, 324, 180, 72, (55, 62, 74)); browse = c.text(1080, 348, "BROWSE", (248, 249, 251), 3)+ c.rect(120, 474, 48, 48, (52, 132, 242))+ c.line(131, 498, 141, 508, (255, 255, 255), 4); c.line(141, 508, 158, 484, (255, 255, 255), 4)+ replace = c.text(192, 486, "REPLACE EXISTING", (224, 228, 235), 3)+ c.rect(1020, 700, 210, 72, (52, 132, 242)); copy = c.text(1072, 724, "COPY", (255, 255, 255), 3)+ return Scenario("native-controls-dark-hidpi.png", 1440, 900,+ ["native-controls", "dark", "high-dpi", "small-text"], bytes(c.pixels),+ [text_annotation("window-title", "TRANSFER", title, "title"), text_annotation("heading", "COPY FILES", heading, "heading"),+ text_annotation("source-label", "SOURCE", source_label, "label"), text_annotation("source-value", "/USERS/DEMO/REPORT.PDF", source, "value"),+ text_annotation("browse-text", "BROWSE", browse, "button-label"), text_annotation("replace-label", "REPLACE EXISTING", replace, "label"),+ text_annotation("copy-text", "COPY", copy, "button-label")],+ [control_annotation("source-input", "text-field", "SOURCE", [120, 324, 900, 72], "enabled"),+ control_annotation("browse-button", "button", "BROWSE", [1050, 324, 180, 72], "enabled"),+ control_annotation("replace-checkbox", "checkbox", "REPLACE EXISTING", [120, 474, 48, 48], "checked"),+ control_annotation("copy-button", "button", "COPY", [1020, 700, 210, 72], "enabled")])+++def browser_canvas() -> Scenario:+ c = Canvas(960, 600, (247, 244, 235))+ c.rect(0, 0, 960, 58, (255, 255, 255)); c.frame(0, 57, 960, 2, (211, 207, 198), 1)+ c.rect(72, 14, 720, 32, (239, 241, 244)); c.frame(72, 14, 720, 32, (200, 204, 211), 1)+ address = c.text(92, 25, "LOCAL DASHBOARD", (67, 72, 80), 1)+ c.rect(32, 88, 896, 472, (255, 253, 247)); c.frame(32, 88, 896, 472, (219, 211, 195), 2)+ heading = c.text(62, 118, "WEEKLY SIGNAL", (40, 38, 34), 3)+ subtitle = c.text(64, 170, "CANVAS RENDER", (111, 103, 91), 1)+ c.line(96, 470, 96, 232, (110, 105, 96), 2); c.line(96, 470, 760, 470, (110, 105, 96), 2)+ points = [(110, 418), (220, 382), (330, 401), (440, 318), (550, 336), (660, 250), (748, 276)]+ for first, second in zip(points, points[1:]): c.line(*first, *second, (217, 77, 55), 5)+ for x, y in points: c.rect(x - 5, y - 5, 11, 11, (217, 77, 55))+ c.rect(772, 188, 116, 54, (36, 119, 166)); export = c.text(790, 208, "EXPORT", (255, 255, 255), 2)+ c.icon("menu", 866, 104, 34, (55, 52, 47))+ return Scenario("browser-canvas-light.png", 960, 600,+ ["browser-canvas", "light", "standard-dpi", "icon-only"], bytes(c.pixels),+ [text_annotation("address", "LOCAL DASHBOARD", address, "address"), text_annotation("heading", "WEEKLY SIGNAL", heading, "heading"),+ text_annotation("subtitle", "CANVAS RENDER", subtitle, "label"),+ text_annotation("export-text", "EXPORT", export, "button-label")],+ [control_annotation("chart-canvas", "canvas", None, [80, 210, 700, 280], "enabled"),+ control_annotation("export-button", "button", "EXPORT", [772, 188, 116, 54], "enabled"),+ control_annotation("menu-button", "icon-button", None, [866, 104, 34, 34], "enabled")])+++def remote_desktop() -> Scenario:+ c = Canvas(960, 600, (12, 46, 63))+ for y in range(600):+ shade = (12 + y // 30, 46 + y // 18, min(100, 63 + y // 12))+ c.rect(0, y, 960, 1, shade)+ c.rect(0, 0, 960, 34, (31, 34, 40)); session = c.text(12, 11, "REMOTE SESSION 04", (224, 228, 234), 1)+ c.rect(0, 566, 960, 34, (25, 28, 34)); c.rect(10, 572, 24, 22, (54, 126, 216))+ c.rect(184, 94, 620, 390, (235, 237, 241)); c.frame(184, 94, 620, 390, (54, 58, 67), 3)+ c.rect(187, 97, 614, 34, (63, 70, 82)); title = c.text(204, 108, "SYSTEM MONITOR", (247, 248, 250), 1)+ c.icon("close", 770, 100, 24, (235, 238, 242))+ c.rect(208, 154, 180, 292, (248, 249, 251)); c.frame(208, 154, 180, 292, (191, 197, 207), 1)+ processes = c.text(222, 174, "PROCESSES", (57, 63, 73), 1)+ network = c.text(222, 202, "NETWORK", (57, 63, 73), 1)+ storage = c.text(222, 230, "STORAGE", (57, 63, 73), 1)+ c.rect(416, 154, 354, 126, (255, 255, 255)); c.frame(416, 154, 354, 126, (191, 197, 207), 1)+ cpu = c.text(434, 170, "CPU 37 PERCENT", (45, 51, 61), 1)+ for x, height in enumerate((34, 48, 43, 68, 51, 72, 62, 84)):+ c.rect(438 + x * 36, 260 - height, 20, height, (53, 133, 203))+ c.rect(416, 300, 354, 146, (255, 255, 255)); c.frame(416, 300, 354, 146, (191, 197, 207), 1)+ status = c.text(434, 320, "STATUS CONNECTED", (40, 112, 70), 1)+ # Deterministic sparse transport noise suggests a compressed remote surface.+ value = 0xC0A52026+ for _ in range(1600):+ value = (1664525 * value + 1013904223) & 0xFFFFFFFF+ x, y = value % 960, (value >> 12) % 600+ base = (value >> 24) & 31+ c.point(x, y, (base + 28, base + 32, base + 38))+ return Scenario("remote-desktop-dark.png", 960, 600,+ ["remote-desktop-like", "dark", "standard-dpi", "small-text", "noisy"], bytes(c.pixels),+ [text_annotation("session", "REMOTE SESSION 04", session, "status"), text_annotation("window-title", "SYSTEM MONITOR", title, "title"),+ text_annotation("processes", "PROCESSES", processes, "list-item"), text_annotation("network", "NETWORK", network, "list-item"),+ text_annotation("storage", "STORAGE", storage, "list-item"),+ text_annotation("cpu", "CPU 37 PERCENT", cpu, "value"), text_annotation("status", "STATUS CONNECTED", status, "status")],+ [control_annotation("remote-window", "window", "SYSTEM MONITOR", [184, 94, 620, 390], "active"),+ control_annotation("processes-nav", "list-item", "PROCESSES", [214, 164, 160, 24], "selected"),+ control_annotation("close-window", "icon-button", None, [770, 100, 24, 24], "enabled")])+++def downsampled() -> Scenario:+ high = Canvas(960, 600, (244, 247, 250))+ high.rect(40, 40, 880, 520, (255, 255, 255)); high.frame(40, 40, 880, 520, (170, 178, 188), 2)+ high.text(78, 76, "INVENTORY", (30, 38, 48), 4)+ high.rect(78, 142, 804, 52, (226, 232, 240)); high.text(94, 160, "ITEM STATUS OWNER", (64, 73, 85), 2)+ rows = [("ALPHA READY MAY", 220), ("BRAVO HOLD LEE", 288), ("CHARLIE READY KIM", 356), ("DELTA REVIEW SAM", 424)]+ for index, (value, y) in enumerate(rows):+ if index % 2: high.rect(78, y - 12, 804, 48, (247, 249, 251))+ high.text(94, y, value, (42, 49, 59), 2)+ low = downsample_2x(bytes(high.pixels), 960, 600)+ return Scenario("downsampled-table.png", 480, 300,+ ["downsampled", "light", "small-text", "native-controls"], low,+ [text_annotation("heading", "INVENTORY", [39, 38, 106, 14], "heading"),+ text_annotation("header", "ITEM STATUS OWNER", [47, 80, 101, 7], "column-header"),+ text_annotation("row-alpha", "ALPHA READY MAY", [47, 110, 89, 7], "table-cell"),+ text_annotation("row-bravo", "BRAVO HOLD LEE", [47, 144, 89, 7], "table-cell"),+ text_annotation("row-charlie", "CHARLIE READY KIM", [47, 178, 107, 7], "table-cell"),+ text_annotation("row-delta", "DELTA REVIEW SAM", [47, 212, 101, 7], "table-cell")],+ [control_annotation("inventory-table", "table", "INVENTORY", [39, 71, 402, 169], "enabled")])+++def icon_only() -> Scenario:+ c = Canvas(480, 320, (248, 246, 240))+ c.rect(0, 0, 480, 54, (32, 39, 48))+ specs = [("search", 54), ("play", 142), ("gear", 230), ("menu", 318), ("close", 406)]+ controls = []+ for index, (kind, x) in enumerate(specs):+ c.rect(x - 26, 110, 64, 64, (255, 255, 255)); c.frame(x - 26, 110, 64, 64, (164, 158, 146), 2)+ c.icon(kind, x - 14, 122, 40, (50, 58, 69))+ controls.append(control_annotation(f"tool-{index + 1}", "icon-button", None, [x - 26, 110, 64, 64], "enabled"))+ return Scenario("icon-only-toolbar.png", 480, 320,+ ["icon-only", "light", "standard-dpi", "native-controls"], bytes(c.pixels), [], controls)+++def overlapping() -> Scenario:+ c = Canvas(640, 400, (245, 247, 250))+ c.rect(52, 66, 536, 268, (255, 255, 255)); c.frame(52, 66, 536, 268, (172, 180, 191), 2)+ heading = c.text(82, 98, "FIND COMMAND", (34, 41, 51), 3)+ c.rect(82, 166, 476, 58, (249, 250, 252)); c.frame(82, 166, 476, 58, (92, 105, 123), 2)+ c.icon("search", 94, 175, 40, (64, 76, 92))+ query = c.text(122, 186, "SEARCH FILES", (45, 54, 66), 2)+ c.rect(392, 252, 166, 46, (32, 117, 210)); run = c.text(437, 268, "RUN", (255, 255, 255), 2)+ return Scenario("overlapping-annotations.png", 640, 400,+ ["overlapping-ocr-icon-boxes", "light", "standard-dpi", "small-text"], bytes(c.pixels),+ [text_annotation("heading", "FIND COMMAND", heading, "heading"),+ text_annotation("query", "SEARCH FILES", query, "placeholder"), text_annotation("run-text", "RUN", run, "button-label")],+ [control_annotation("search-icon", "icon", None, [94, 175, 40, 40], "static"),+ control_annotation("search-field", "text-field", "SEARCH FILES", [82, 166, 476, 58], "enabled"),+ control_annotation("run-button", "button", "RUN", [392, 252, 166, 46], "enabled")])+++def empty_surface() -> Scenario:+ c = Canvas(640, 400, (250, 250, 248))+ return Scenario("empty-surface.png", 640, 400, ["empty", "light", "standard-dpi"], bytes(c.pixels), [], [])+++def noisy_surface() -> Scenario:+ c = Canvas(640, 400, (128, 128, 128))+ value = 0x51A7E123+ for y in range(400):+ for x in range(640):+ value = (1103515245 * value + 12345) & 0x7FFFFFFF+ level = 48 + ((value >> 8) % 160)+ c.point(x, y, (level, (level * 5 + 17) % 192 + 32, (level * 3 + 41) % 192 + 32))+ return Scenario("noisy-surface.png", 640, 400, ["noisy", "dark", "standard-dpi"], bytes(c.pixels), [], [])+++def downsample_2x(pixels: bytes, width: int, height: int) -> bytes:+ result = bytearray((width // 2) * (height // 2) * 3)+ for y in range(0, height, 2):+ for x in range(0, width, 2):+ target = ((y // 2) * (width // 2) + x // 2) * 3+ for channel in range(3):+ offsets = [((y + dy) * width + x + dx) * 3 + channel for dy in (0, 1) for dx in (0, 1)]+ result[target + channel] = sum(pixels[offset] for offset in offsets) // 4+ return bytes(result)+++def png_chunk(kind: bytes, data: bytes) -> bytes:+ return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)+++def encode_png(width: int, height: int, pixels: bytes) -> bytes:+ expected = width * height * 3+ if len(pixels) != expected:+ raise ValueError(f"expected {expected} RGB bytes, got {len(pixels)}")+ scanlines = b"".join(b"\x00" + pixels[y * width * 3 : (y + 1) * width * 3] for y in range(height))+ header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)+ return PNG_SIGNATURE + png_chunk(b"IHDR", header) + png_chunk(b"IDAT", zlib.compress(scanlines, 9)) + png_chunk(b"IEND", b"")+++def scenarios() -> list[Scenario]:+ return [native_light(), native_dark_hidpi(), browser_canvas(), remote_desktop(), downsampled(), icon_only(), overlapping(), empty_surface(), noisy_surface()]+++def manifest_for(items: list[Scenario], pngs: dict[str, bytes]) -> dict:+ return {+ "schema_version": 1,+ "corpus_version": CORPUS_VERSION,+ "license": "MIT",+ "coordinate_system": {"space": "source_pixels", "origin": "top_left", "bbox_format": "x_y_width_height"},+ "metric_definitions": {+ "text_detection_iou": {"unit": "ratio", "description": "Intersection over union between a predicted text box and its matched expected box."},+ "text_recognition_exact": {"unit": "boolean", "description": "Case-sensitive equality between predicted and expected text after trimming outer whitespace."},+ "control_detection_iou": {"unit": "ratio", "description": "Intersection over union between a predicted control box and its matched expected box."},+ "control_kind_accuracy": {"unit": "ratio", "description": "Fraction of matched controls whose predicted kind equals the expected kind."},+ "false_positive_count": {"unit": "count", "description": "Unmatched predictions for an image, including images with no annotations."},+ },+ "images": [+ {+ "file": f"images/{item.filename}",+ "sha256": hashlib.sha256(pngs[item.filename]).hexdigest(),+ "width": item.width,+ "height": item.height,+ "scenario_tags": item.tags,+ "expected": {"text": item.text, "controls": item.controls},+ }+ for item in items+ ],+ }+++def write_corpus(destination: Path) -> None:+ image_dir = destination / "images"+ image_dir.mkdir(parents=True, exist_ok=True)+ items = scenarios()+ pngs = {item.filename: encode_png(item.width, item.height, item.pixels) for item in items}+ for filename, data in pngs.items():+ (image_dir / filename).write_bytes(data)+ manifest = manifest_for(items, pngs)+ (destination / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")+++def require_exact_keys(value: dict, expected: set[str], context: str) -> None:+ actual = set(value)+ if actual != expected:+ raise ValueError(f"{context} keys differ: expected {sorted(expected)}, got {sorted(actual)}")+++def png_dimensions(data: bytes) -> tuple[int, int]:+ if not data.startswith(PNG_SIGNATURE) or data[12:16] != b"IHDR":+ raise ValueError("not a PNG with an IHDR first chunk")+ return struct.unpack(">II", data[16:24])+++def validate_manifest(directory: Path) -> None:+ manifest = json.loads((directory / "manifest.json").read_text(encoding="utf-8"))+ require_exact_keys(manifest, {"schema_version", "corpus_version", "license", "coordinate_system", "metric_definitions", "images"}, "manifest")+ if manifest["schema_version"] != 1 or manifest["corpus_version"] != CORPUS_VERSION or manifest["license"] != "MIT":+ raise ValueError("unexpected manifest identity")+ require_exact_keys(manifest["coordinate_system"], {"space", "origin", "bbox_format"}, "coordinate_system")+ if manifest["coordinate_system"] != {"space": "source_pixels", "origin": "top_left", "bbox_format": "x_y_width_height"}:+ raise ValueError("coordinate system must describe source-pixel xywh boxes")+ metric_keys = {"text_detection_iou", "text_recognition_exact", "control_detection_iou", "control_kind_accuracy", "false_positive_count"}+ if set(manifest["metric_definitions"]) != metric_keys:+ raise ValueError("metric definitions are not the closed expected set")+ for name, definition in manifest["metric_definitions"].items():+ require_exact_keys(definition, {"unit", "description"}, f"metric {name}")+ if len(manifest["images"]) != 9:+ raise ValueError("corpus must contain exactly nine scenarios")+ required_tags = {"native-controls", "browser-canvas", "remote-desktop-like", "light", "dark", "high-dpi", "downsampled", "small-text", "icon-only", "overlapping-ocr-icon-boxes", "empty", "noisy"}+ observed_tags: set[str] = set()+ observed_files: set[str] = set()+ for index, image in enumerate(manifest["images"]):+ context = f"images[{index}]"+ require_exact_keys(image, {"file", "sha256", "width", "height", "scenario_tags", "expected"}, context)+ require_exact_keys(image["expected"], {"text", "controls"}, f"{context}.expected")+ if image["file"] in observed_files or not image["file"].startswith("images/"):+ raise ValueError(f"duplicate or invalid image path: {image['file']}")+ observed_files.add(image["file"])+ observed_tags.update(image["scenario_tags"])+ path = directory / image["file"]+ data = path.read_bytes()+ if hashlib.sha256(data).hexdigest() != image["sha256"]:+ raise ValueError(f"hash mismatch: {image['file']}")+ if png_dimensions(data) != (image["width"], image["height"]):+ raise ValueError(f"dimension mismatch: {image['file']}")+ annotation_ids: set[str] = set()+ for annotation in image["expected"]["text"]:+ require_exact_keys(annotation, {"id", "text", "bbox", "role"}, f"{context}.text")+ validate_annotation(annotation, image, annotation_ids, context)+ if not annotation["text"]:+ raise ValueError(f"empty expected text in {context}")+ for annotation in image["expected"]["controls"]:+ require_exact_keys(annotation, {"id", "kind", "label", "bbox", "state"}, f"{context}.controls")+ validate_annotation(annotation, image, annotation_ids, context)+ if annotation["label"] is not None and not isinstance(annotation["label"], str):+ raise ValueError(f"invalid control label in {context}")+ missing_tags = required_tags - observed_tags+ if missing_tags:+ raise ValueError(f"missing required scenario tags: {sorted(missing_tags)}")+ actual_pngs = {str(path.relative_to(directory)) for path in (directory / "images").glob("*.png")}+ if actual_pngs != observed_files:+ raise ValueError("manifest image list is not closed over the images directory")+++def validate_annotation(annotation: dict, image: dict, ids: set[str], context: str) -> None:+ if not isinstance(annotation["id"], str) or not annotation["id"] or annotation["id"] in ids:+ raise ValueError(f"invalid or duplicate annotation id in {context}")+ ids.add(annotation["id"])+ bbox = annotation["bbox"]+ if not isinstance(bbox, list) or len(bbox) != 4 or any(not isinstance(value, int) for value in bbox):+ raise ValueError(f"invalid bbox in {context}")+ x, y, width, height = bbox+ if x < 0 or y < 0 or width <= 0 or height <= 0 or x + width > image["width"] or y + height > image["height"]:+ raise ValueError(f"out-of-bounds bbox in {context}: {bbox}")+++def check_reproducible() -> None:+ validate_manifest(ROOT)+ with tempfile.TemporaryDirectory(prefix="cua-quality-corpus-") as temporary:+ generated = Path(temporary)+ write_corpus(generated)+ validate_manifest(generated)+ expected_files = {"manifest.json"} | {str(path.relative_to(ROOT)) for path in (ROOT / "images").glob("*.png")}+ generated_files = {"manifest.json"} | {str(path.relative_to(generated)) for path in (generated / "images").glob("*.png")}+ if expected_files != generated_files:+ raise ValueError("generated file set differs from checked-in corpus")+ for relative in sorted(expected_files):+ if (ROOT / relative).read_bytes() != (generated / relative).read_bytes():+ raise ValueError(f"generated bytes differ: {relative}")+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--check", action="store_true", help="validate schema and exact reproducibility without changing files")+ args = parser.parse_args()+ if args.check:+ check_reproducible()+ print("quality corpus is valid and reproducible")+ else:+ write_corpus(ROOT)+ validate_manifest(ROOT)+ print("generated quality corpus")+++if __name__ == "__main__":+ main()diff --git a/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/images/browser-canvas-light.png b/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/images/browser-canvas-light.pngnew file mode 100644index 0000000000..7c038a1950Binary files /dev/null and b/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/images/browser-canvas-light.png differdiff --git a/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/images/downsampled-table.png b/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/images/downsampled-table.pngnew file mode 100644index 0000000000..0eb2c816a9Binary files /dev/null and b/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/images/downsampled-table.png differdiff --git a/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/images/empty-surface.png b/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/images/empty-surface.pngnew file mode 100644index 0000000000..7908e0cc4dBinary files /dev/null and b/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/images/empty-surface.png differdiff --git a/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/images/icon-only-toolbar.png b/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/images/icon-only-toolbar.pngnew file mode 100644index 0000000000..9fb2405f19Binary files /dev/null and b/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/images/icon-only-toolbar.png differdiff --git a/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/images/native-controls-dark-hidpi.png b/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/images/native-controls-dark-hidpi.pngnew file mode 100644index 0000000000..9cfaeccb77Binary files /dev/null and b/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/images/native-controls-dark-hidpi.png differdiff --git a/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/images/native-controls-light.png b/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/images/native-controls-light.pngnew file mode 100644index 0000000000..7da8e8a148Binary files /dev/null and b/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/images/native-controls-light.png differdiff --git a/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/images/noisy-surface.png b/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/images/noisy-surface.pngnew file mode 100644index 0000000000..8104cadfb0Binary files /dev/null and b/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/images/noisy-surface.png differdiff --git a/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/images/overlapping-annotations.png b/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/images/overlapping-annotations.pngnew file mode 100644index 0000000000..391384532bBinary files /dev/null and b/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/images/overlapping-annotations.png differdiff --git a/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/images/remote-desktop-dark.png b/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/images/remote-desktop-dark.pngnew file mode 100644index 0000000000..ffe4d76802Binary files /dev/null and b/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/images/remote-desktop-dark.png differdiff --git a/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/manifest.json b/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/manifest.jsonnew file mode 100644index 0000000000..5e14658311--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/tests/quality-corpus/manifest.json@@ -0,0 +1,852 @@+{+ "schema_version": 1,+ "corpus_version": "1.0.0",+ "license": "MIT",+ "coordinate_system": {+ "space": "source_pixels",+ "origin": "top_left",+ "bbox_format": "x_y_width_height"+ },+ "metric_definitions": {+ "text_detection_iou": {+ "unit": "ratio",+ "description": "Intersection over union between a predicted text box and its matched expected box."+ },+ "text_recognition_exact": {+ "unit": "boolean",+ "description": "Case-sensitive equality between predicted and expected text after trimming outer whitespace."+ },+ "control_detection_iou": {+ "unit": "ratio",+ "description": "Intersection over union between a predicted control box and its matched expected box."+ },+ "control_kind_accuracy": {+ "unit": "ratio",+ "description": "Fraction of matched controls whose predicted kind equals the expected kind."+ },+ "false_positive_count": {+ "unit": "count",+ "description": "Unmatched predictions for an image, including images with no annotations."+ }+ },+ "images": [+ {+ "file": "images/native-controls-light.png",+ "sha256": "a4ad401a8d86abf81b187460e05de27aed60dba630c4bdd87d182a9d6f8fc89e",+ "width": 960,+ "height": 600,+ "scenario_tags": [+ "native-controls",+ "light",+ "standard-dpi",+ "small-text"+ ],+ "expected": {+ "text": [+ {+ "id": "window-title",+ "text": "SETTINGS",+ "bbox": [+ 18,+ 13,+ 94,+ 14+ ],+ "role": "title"+ },+ {+ "id": "heading",+ "text": "DEVICE SETTINGS",+ "bbox": [+ 62,+ 104,+ 267,+ 21+ ],+ "role": "heading"+ },+ {+ "id": "device-label",+ "text": "DEVICE NAME",+ "bbox": [+ 64,+ 178,+ 130,+ 14+ ],+ "role": "label"+ },+ {+ "id": "device-value",+ "text": "DESK MAC",+ "bbox": [+ 78,+ 218,+ 94,+ 14+ ],+ "role": "value"+ },+ {+ "id": "capture-label",+ "text": "ENABLE CAPTURE",+ "bbox": [+ 100,+ 287,+ 166,+ 14+ ],+ "role": "label"+ },+ {+ "id": "cancel-text",+ "text": "CANCEL",+ "bbox": [+ 716,+ 510,+ 70,+ 14+ ],+ "role": "button-label"+ },+ {+ "id": "save-text",+ "text": "SAVE",+ "bbox": [+ 834,+ 510,+ 46,+ 14+ ],+ "role": "button-label"+ }+ ],+ "controls": [+ {+ "id": "device-input",+ "kind": "text-field",+ "label": "DEVICE NAME",+ "bbox": [+ 64,+ 204,+ 420,+ 44+ ],+ "state": "enabled"+ },+ {+ "id": "capture-checkbox",+ "kind": "checkbox",+ "label": "ENABLE CAPTURE",+ "bbox": [+ 64,+ 282,+ 22,+ 22+ ],+ "state": "checked"+ },+ {+ "id": "quality-slider",+ "kind": "slider",+ "label": null,+ "bbox": [+ 64,+ 332,+ 290,+ 28+ ],+ "state": "enabled"+ },+ {+ "id": "cancel-button",+ "kind": "button",+ "label": "CANCEL",+ "bbox": [+ 700,+ 496,+ 104,+ 40+ ],+ "state": "enabled"+ },+ {+ "id": "save-button",+ "kind": "button",+ "label": "SAVE",+ "bbox": [+ 816,+ 496,+ 84,+ 40+ ],+ "state": "enabled"+ }+ ]+ }+ },+ {+ "file": "images/native-controls-dark-hidpi.png",+ "sha256": "614c4e18a17c854fc1c979351b60932b3fb55750ddc91b0bc58cb5d0c7087b36",+ "width": 1440,+ "height": 900,+ "scenario_tags": [+ "native-controls",+ "dark",+ "high-dpi",+ "small-text"+ ],+ "expected": {+ "text": [+ {+ "id": "window-title",+ "text": "TRANSFER",+ "bbox": [+ 36,+ 24,+ 188,+ 28+ ],+ "role": "title"+ },+ {+ "id": "heading",+ "text": "COPY FILES",+ "bbox": [+ 120,+ 174,+ 295,+ 35+ ],+ "role": "heading"+ },+ {+ "id": "source-label",+ "text": "SOURCE",+ "bbox": [+ 124,+ 282,+ 105,+ 21+ ],+ "role": "label"+ },+ {+ "id": "source-value",+ "text": "/USERS/DEMO/REPORT.PDF",+ "bbox": [+ 146,+ 346,+ 393,+ 21+ ],+ "role": "value"+ },+ {+ "id": "browse-text",+ "text": "BROWSE",+ "bbox": [+ 1080,+ 348,+ 105,+ 21+ ],+ "role": "button-label"+ },+ {+ "id": "replace-label",+ "text": "REPLACE EXISTING",+ "bbox": [+ 192,+ 486,+ 285,+ 21+ ],+ "role": "label"+ },+ {+ "id": "copy-text",+ "text": "COPY",+ "bbox": [+ 1072,+ 724,+ 69,+ 21+ ],+ "role": "button-label"+ }+ ],+ "controls": [+ {+ "id": "source-input",+ "kind": "text-field",+ "label": "SOURCE",+ "bbox": [+ 120,+ 324,+ 900,+ 72+ ],+ "state": "enabled"+ },+ {+ "id": "browse-button",+ "kind": "button",+ "label": "BROWSE",+ "bbox": [+ 1050,+ 324,+ 180,+ 72+ ],+ "state": "enabled"+ },+ {+ "id": "replace-checkbox",+ "kind": "checkbox",+ "label": "REPLACE EXISTING",+ "bbox": [+ 120,+ 474,+ 48,+ 48+ ],+ "state": "checked"+ },+ {+ "id": "copy-button",+ "kind": "button",+ "label": "COPY",+ "bbox": [+ 1020,+ 700,+ 210,+ 72+ ],+ "state": "enabled"+ }+ ]+ }+ },+ {+ "file": "images/browser-canvas-light.png",+ "sha256": "39e7437f4a83d768a334bbd0a86c369da7af9a3767f900dc47210ab39d1e3f5f",+ "width": 960,+ "height": 600,+ "scenario_tags": [+ "browser-canvas",+ "light",+ "standard-dpi",+ "icon-only"+ ],+ "expected": {+ "text": [+ {+ "id": "address",+ "text": "LOCAL DASHBOARD",+ "bbox": [+ 92,+ 25,+ 89,+ 7+ ],+ "role": "address"+ },+ {+ "id": "heading",+ "text": "WEEKLY SIGNAL",+ "bbox": [+ 62,+ 118,+ 231,+ 21+ ],+ "role": "heading"+ },+ {+ "id": "subtitle",+ "text": "CANVAS RENDER",+ "bbox": [+ 64,+ 170,+ 77,+ 7+ ],+ "role": "label"+ },+ {+ "id": "export-text",+ "text": "EXPORT",+ "bbox": [+ 790,+ 208,+ 70,+ 14+ ],+ "role": "button-label"+ }+ ],+ "controls": [+ {+ "id": "chart-canvas",+ "kind": "canvas",+ "label": null,+ "bbox": [+ 80,+ 210,+ 700,+ 280+ ],+ "state": "enabled"+ },+ {+ "id": "export-button",+ "kind": "button",+ "label": "EXPORT",+ "bbox": [+ 772,+ 188,+ 116,+ 54+ ],+ "state": "enabled"+ },+ {+ "id": "menu-button",+ "kind": "icon-button",+ "label": null,+ "bbox": [+ 866,+ 104,+ 34,+ 34+ ],+ "state": "enabled"+ }+ ]+ }+ },+ {+ "file": "images/remote-desktop-dark.png",+ "sha256": "b3625e11abec0d4280748f55b3b997e211c1e1814d05142209563dc844ee0f4a",+ "width": 960,+ "height": 600,+ "scenario_tags": [+ "remote-desktop-like",+ "dark",+ "standard-dpi",+ "small-text",+ "noisy"+ ],+ "expected": {+ "text": [+ {+ "id": "session",+ "text": "REMOTE SESSION 04",+ "bbox": [+ 12,+ 11,+ 101,+ 7+ ],+ "role": "status"+ },+ {+ "id": "window-title",+ "text": "SYSTEM MONITOR",+ "bbox": [+ 204,+ 108,+ 83,+ 7+ ],+ "role": "title"+ },+ {+ "id": "processes",+ "text": "PROCESSES",+ "bbox": [+ 222,+ 174,+ 53,+ 7+ ],+ "role": "list-item"+ },+ {+ "id": "network",+ "text": "NETWORK",+ "bbox": [+ 222,+ 202,+ 41,+ 7+ ],+ "role": "list-item"+ },+ {+ "id": "storage",+ "text": "STORAGE",+ "bbox": [+ 222,+ 230,+ 41,+ 7+ ],+ "role": "list-item"+ },+ {+ "id": "cpu",+ "text": "CPU 37 PERCENT",+ "bbox": [+ 434,+ 170,+ 83,+ 7+ ],+ "role": "value"+ },+ {+ "id": "status",+ "text": "STATUS CONNECTED",+ "bbox": [+ 434,+ 320,+ 95,+ 7+ ],+ "role": "status"+ }+ ],+ "controls": [+ {+ "id": "remote-window",+ "kind": "window",+ "label": "SYSTEM MONITOR",+ "bbox": [+ 184,+ 94,+ 620,+ 390+ ],+ "state": "active"+ },+ {+ "id": "processes-nav",+ "kind": "list-item",+ "label": "PROCESSES",+ "bbox": [+ 214,+ 164,+ 160,+ 24+ ],+ "state": "selected"+ },+ {+ "id": "close-window",+ "kind": "icon-button",+ "label": null,+ "bbox": [+ 770,+ 100,+ 24,+ 24+ ],+ "state": "enabled"+ }+ ]+ }+ },+ {+ "file": "images/downsampled-table.png",+ "sha256": "b281379be6f5b9bb30d7267ebdd53453bf1aa390d63f9f138d6f7d72ab5bd736",+ "width": 480,+ "height": 300,+ "scenario_tags": [+ "downsampled",+ "light",+ "small-text",+ "native-controls"+ ],+ "expected": {+ "text": [+ {+ "id": "heading",+ "text": "INVENTORY",+ "bbox": [+ 39,+ 38,+ 106,+ 14+ ],+ "role": "heading"+ },+ {+ "id": "header",+ "text": "ITEM STATUS OWNER",+ "bbox": [+ 47,+ 80,+ 101,+ 7+ ],+ "role": "column-header"+ },+ {+ "id": "row-alpha",+ "text": "ALPHA READY MAY",+ "bbox": [+ 47,+ 110,+ 89,+ 7+ ],+ "role": "table-cell"+ },+ {+ "id": "row-bravo",+ "text": "BRAVO HOLD LEE",+ "bbox": [+ 47,+ 144,+ 89,+ 7+ ],+ "role": "table-cell"+ },+ {+ "id": "row-charlie",+ "text": "CHARLIE READY KIM",+ "bbox": [+ 47,+ 178,+ 107,+ 7+ ],+ "role": "table-cell"+ },+ {+ "id": "row-delta",+ "text": "DELTA REVIEW SAM",+ "bbox": [+ 47,+ 212,+ 101,+ 7+ ],+ "role": "table-cell"+ }+ ],+ "controls": [+ {+ "id": "inventory-table",+ "kind": "table",+ "label": "INVENTORY",+ "bbox": [+ 39,+ 71,+ 402,+ 169+ ],+ "state": "enabled"+ }+ ]+ }+ },+ {+ "file": "images/icon-only-toolbar.png",+ "sha256": "db2c8d301d738b6946e0ffb888cd91e8d7d940b6bba194ea622d5af58f78c220",+ "width": 480,+ "height": 320,+ "scenario_tags": [+ "icon-only",+ "light",+ "standard-dpi",+ "native-controls"+ ],+ "expected": {+ "text": [],+ "controls": [+ {+ "id": "tool-1",+ "kind": "icon-button",+ "label": null,+ "bbox": [+ 28,+ 110,+ 64,+ 64+ ],+ "state": "enabled"+ },+ {+ "id": "tool-2",+ "kind": "icon-button",+ "label": null,+ "bbox": [+ 116,+ 110,+ 64,+ 64+ ],+ "state": "enabled"+ },+ {+ "id": "tool-3",+ "kind": "icon-button",+ "label": null,+ "bbox": [+ 204,+ 110,+ 64,+ 64+ ],+ "state": "enabled"+ },+ {+ "id": "tool-4",+ "kind": "icon-button",+ "label": null,+ "bbox": [+ 292,+ 110,+ 64,+ 64+ ],+ "state": "enabled"+ },+ {+ "id": "tool-5",+ "kind": "icon-button",+ "label": null,+ "bbox": [+ 380,+ 110,+ 64,+ 64+ ],+ "state": "enabled"+ }+ ]+ }+ },+ {+ "file": "images/overlapping-annotations.png",+ "sha256": "9806614667aa265e4129ce2a37d37756e5e4008a98bca5fb44238016d95c4bbe",+ "width": 640,+ "height": 400,+ "scenario_tags": [+ "overlapping-ocr-icon-boxes",+ "light",+ "standard-dpi",+ "small-text"+ ],+ "expected": {+ "text": [+ {+ "id": "heading",+ "text": "FIND COMMAND",+ "bbox": [+ 82,+ 98,+ 213,+ 21+ ],+ "role": "heading"+ },+ {+ "id": "query",+ "text": "SEARCH FILES",+ "bbox": [+ 122,+ 186,+ 142,+ 14+ ],+ "role": "placeholder"+ },+ {+ "id": "run-text",+ "text": "RUN",+ "bbox": [+ 437,+ 268,+ 34,+ 14+ ],+ "role": "button-label"+ }+ ],+ "controls": [+ {+ "id": "search-icon",+ "kind": "icon",+ "label": null,+ "bbox": [+ 94,+ 175,+ 40,+ 40+ ],+ "state": "static"+ },+ {+ "id": "search-field",+ "kind": "text-field",+ "label": "SEARCH FILES",+ "bbox": [+ 82,+ 166,+ 476,+ 58+ ],+ "state": "enabled"+ },+ {+ "id": "run-button",+ "kind": "button",+ "label": "RUN",+ "bbox": [+ 392,+ 252,+ 166,+ 46+ ],+ "state": "enabled"+ }+ ]+ }+ },+ {+ "file": "images/empty-surface.png",+ "sha256": "7b252c0297bd0d31a44be27d108fce9fa9163624cd6981b8529fe0237a38d105",+ "width": 640,+ "height": 400,+ "scenario_tags": [+ "empty",+ "light",+ "standard-dpi"+ ],+ "expected": {+ "text": [],+ "controls": []+ }+ },+ {+ "file": "images/noisy-surface.png",+ "sha256": "d7936c181ad42b7d3b28c267e1c2f50179fe11f1c1d2b9a01d4446d804873fa2",+ "width": 640,+ "height": 400,+ "scenario_tags": [+ "noisy",+ "dark",+ "standard-dpi"+ ],+ "expected": {+ "text": [],+ "controls": []+ }+ }+ ]+}diff --git a/libs/cua-driver/rust/crates/cua-perception/tests/real_models.rs b/libs/cua-driver/rust/crates/cua-perception/tests/real_models.rsnew file mode 100644index 0000000000..5aba95d5b2--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-perception/tests/real_models.rs@@ -0,0 +1,79 @@+use std::{env, fs, path::PathBuf};++use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};+use cua_perception::Worker;+use image::ImageReader;+use serde_json::{json, Value};++#[test]+#[ignore = "requires separately obtained, hash-pinned OmniParser/PP-OCR/ORT artifacts"]+fn pinned_real_models_match_the_synthetic_ui_known_answer() {+ let manifest = required_path("CUA_PERCEPTION_REAL_MANIFEST");+ let runtime = required_path("CUA_PERCEPTION_ORT_LIBRARY");+ let image_path = required_path("CUA_PERCEPTION_KNOWN_ANSWER_IMAGE");+ let worker = Worker::from_manifest_with_extension_identity(+ &manifest,+ &runtime,+ "cua-perception",+ env!("CARGO_PKG_VERSION"),+ )+ .expect("load pinned real models");+ let bytes = fs::read(&image_path).expect("read known-answer image");+ let dimensions = ImageReader::open(&image_path)+ .expect("open known-answer image")+ .into_dimensions()+ .expect("read known-answer dimensions");+ let request = json!({+ "protocol": "cua-perception/1",+ "request_id": "real-known-answer",+ "method": "parse",+ "params": {+ "capture_id": "synthetic-ui",+ "image": {+ "media_type": "image/png",+ "width": dimensions.0,+ "height": dimensions.1,+ "byte_length": bytes.len(),+ "data_base64": BASE64.encode(bytes)+ }+ }+ });+ let response = serde_json::to_value(+ worker.handle_payload(&serde_json::to_vec(&request).expect("serialize request")),+ )+ .expect("serialize response");+ assert_eq!(response["status"], "ok", "{response:#}");+ assert_eq!(response["result"]["runtime"], "onnx_runtime_cpu");+ let regions = response["result"]["regions"]+ .as_array()+ .expect("regions array");+ assert_eq!(regions.len(), 8, "{regions:#?}");+ let texts = regions+ .iter()+ .filter_map(|region| region.get("text").and_then(Value::as_str))+ .collect::<Vec<_>>();+ assert!(texts.contains(&"Visual-only action fixture"));+ assert!(texts.contains(&"Archive"));+ assert!(texts.contains(&"Send"));+ assert!(texts.contains(&"Status: draft ready"));+ assert_eq!(+ regions+ .iter()+ .filter(|region| region["kind"] == "icon")+ .count(),+ 3+ );+ assert!(regions+ .iter()+ .filter(|region| region["kind"] == "icon")+ .all(|region| region+ .get("label")+ .and_then(Value::as_str)+ .is_some_and(|label| !label.trim().is_empty())));+}++fn required_path(name: &str) -> PathBuf {+ env::var_os(name)+ .map(PathBuf::from)+ .unwrap_or_else(|| panic!("{name} must point to the pinned local test artifact"))+}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/atspi/native.rs b/libs/cua-driver/rust/crates/platform-linux/src/atspi/native.rsindex 418c6dff40..660a9169e0 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/atspi/native.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/atspi/native.rs@@ -1982,9 +1982,12 @@ pub fn perform_action(pid: u32, idx: usize) -> Result<(String, bool)> {.await.map_err(|e| anyhow!("Action unavailable: {e}"))?;let action = target.actions.get(chosen).cloned().unwrap_or_default();- ap.do_action(chosen as i32)+ let accepted = ap+ .do_action(chosen as i32).await.map_err(|e| anyhow!("doAction failed: {e}"))?;+ require_action_accepted(accepted)+ .with_context(|| format!("element {idx} rejected its native action"))?;// AT-SPI's doAction acknowledgement can precede the renderer's// queued DOM mutation. Give WebKit/Chromium one short event-loop// turn before returning success so a caller's immediate external@@ -2873,10 +2876,14 @@ pub fn perform_action_at_point(pid: u32, win_x: i32, win_y: i32) -> Result<Optio.action().await.map_err(|e| anyhow!("Action unavailable: {e}"))?;- ap.do_action(chosen as i32)+ let accepted = ap+ .do_action(chosen as i32).await.map_err(|e| anyhow!("doAction failed: {e}"))?;- Ok(target.actions.get(chosen).cloned())+ Ok(accepted_action(+ accepted,+ target.actions.get(chosen).cloned(),+ ))},|| Ok(None),)@@ -2902,8 +2909,8 @@ pub fn perform_action_at_point(pid: u32, win_x: i32, win_y: i32) -> Result<Optio////// `screen_x`/`screen_y` are full-display screen pixels (what the vision/// screenshot and `get_window_state` frames are in). Returns `Ok(Some(action))`-/// on a hit, `Ok(None)` when no element covers the point so the caller can fall-/// back to its native injection path.+/// when AT-SPI accepts the action, `Ok(None)` when there is no target or the+/// action is rejected so the caller can fall back to its native injection path.pub fn perform_action_at_screen_point(pid: u32,xid: u64,@@ -2946,15 +2953,35 @@ pub fn perform_action_at_screen_point(.action().await.map_err(|e| anyhow!("Action unavailable: {e}"))?;- ap.do_action(chosen as i32)+ let accepted = ap+ .do_action(chosen as i32).await.map_err(|e| anyhow!("doAction failed: {e}"))?;- Ok(target.actions.get(chosen).cloned())+ Ok(accepted_action(+ accepted,+ target.actions.get(chosen).cloned(),+ ))},|| Ok(None),)}+fn accepted_action(accepted: bool, action: Option<String>) -> Option<String> {+ if accepted {+ action+ } else {+ None+ }+}++fn require_action_accepted(accepted: bool) -> Result<()> {+ if accepted {+ Ok(())+ } else {+ Err(anyhow!("AT-SPI action was rejected"))+ }+}+/// Roles that draw text/graphics but don't *do* anything when actuated. GTK4/// nests a `label` inside every `button` with a near-identical (slightly/// smaller) frame, so an area-only hit-test lands on the inert label —@@ -3814,12 +3841,12 @@ mod frame_correlation_tests {mod coord_tests {use super::parse_gtk_frame_extents;use super::{- activation_index, before_snapshot_deadline, combine_wayland_content_offsets,- hyprland_document_top_inset, is_activation_action, is_enabled_state,- is_indexable_capabilities, is_passive_role, is_web_process_bus,+ accepted_action, activation_index, before_snapshot_deadline,+ combine_wayland_content_offsets, hyprland_document_top_inset, is_activation_action,+ is_enabled_state, is_indexable_capabilities, is_passive_role, is_web_process_bus,prefer_authoritative_wayland_origin, project_screen_extents, rebase_renderer_window_offset,- scoped_component_nodes, screen_extent_rebase, select_click_target, select_web_document,- ApplicationSelection,+ require_action_accepted, scoped_component_nodes, screen_extent_rebase, select_click_target,+ select_web_document, ApplicationSelection,};use atspi::{State, StateSet};use std::time::Duration;@@ -4247,6 +4274,25 @@ mod coord_tests {assert_eq!(select_click_target(&[], 0, 0), None); // no frames}+ #[test]+ fn rejected_action_acknowledgement_does_not_report_success() {+ assert_eq!(accepted_action(false, Some("click".to_owned())), None);+ }++ #[test]+ fn accepted_action_acknowledgement_reports_the_selected_action() {+ assert_eq!(+ accepted_action(true, Some("click".to_owned())),+ Some("click".to_owned())+ );+ }++ #[test]+ fn indexed_action_rejection_is_an_error() {+ assert!(require_action_accepted(false).is_err());+ assert!(require_action_accepted(true).is_ok());+ }+#[test]fn passive_roles_classified() {assert!(is_passive_role("label"));diff --git a/libs/cua-driver/rust/crates/platform-linux/src/capture_action_frame.rs b/libs/cua-driver/rust/crates/platform-linux/src/capture_action_frame.rsnew file mode 100644index 0000000000..0770189a34--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-linux/src/capture_action_frame.rs@@ -0,0 +1,526 @@+use cua_driver_core::capture_runtime::{+ CaptureActionError, CaptureActionRequest, CaptureIdParseError, CaptureLookupError,+ CapturePublication, CaptureService, CaptureTarget, EncodedScreenshotDimensions,+ NativeActionDimensions, ScreenshotToActionTransform,+};+use serde_json::Value;++fn window_target(pid: u32, window_id: u64) -> CaptureTarget {+ CaptureTarget::Window { pid, window_id }+}++pub fn resolve_max_image_dimension(+ configured: u32,+ legacy_max_dimension: Option<u32>,+ max_image_dimension: Option<u32>,+) -> u32 {+ max_image_dimension.unwrap_or_else(|| match legacy_max_dimension {+ Some(value) if configured == 0 => value,+ Some(value) => configured.min(value),+ None => configured,+ })+}++fn publish(+ service: &CaptureService,+ args: &Value,+ png_bytes: &[u8],+ target: CaptureTarget,+ encoded_dimensions: (u32, u32),+ native_action_dimensions: (u32, u32),+ screenshot_to_action: ScreenshotToActionTransform,+) -> anyhow::Result<String> {+ let binding = service.binding_from_args(args)?;+ let capture_id = service.publish(CapturePublication {+ png_bytes: png_bytes.to_vec(),+ target,+ encoded_dimensions: EncodedScreenshotDimensions::new(+ encoded_dimensions.0,+ encoded_dimensions.1,+ )?,+ native_action_dimensions: NativeActionDimensions::new(+ native_action_dimensions.0,+ native_action_dimensions.1,+ )?,+ screenshot_to_action,+ session_id: binding.session_id().into(),+ session_generation: binding.session_generation(),+ })?;+ Ok(capture_id.to_string())+}++pub fn publish_window(+ service: &CaptureService,+ args: &Value,+ png_bytes: &[u8],+ pid: u32,+ window_id: u64,+ encoded_dimensions: (u32, u32),+ native_action_dimensions: (u32, u32),+) -> anyhow::Result<String> {+ // The resizer preserves aspect ratio before rounding each encoded axis.+ // Derive both ratios independently so a one-pixel rounded height does not+ // skew Y coordinates in the native window frame.+ let scale_x = f64::from(native_action_dimensions.0) / f64::from(encoded_dimensions.0);+ let scale_y = f64::from(native_action_dimensions.1) / f64::from(encoded_dimensions.1);+ let screenshot_to_action =+ ScreenshotToActionTransform::new(scale_x, 0.0, 0.0, scale_y, 0.0, 0.0)?;+ publish(+ service,+ args,+ png_bytes,+ window_target(pid, window_id),+ encoded_dimensions,+ native_action_dimensions,+ screenshot_to_action,+ )+}++pub fn publish_desktop(+ service: &CaptureService,+ args: &Value,+ png_bytes: &[u8],+ dimensions: (u32, u32),+) -> anyhow::Result<String> {+ publish(+ service,+ args,+ png_bytes,+ CaptureTarget::PrimaryDesktop,+ dimensions,+ dimensions,+ ScreenshotToActionTransform::identity(),+ )+}++fn admit(+ service: &CaptureService,+ args: &Value,+ capture_id: &str,+ target: CaptureTarget,+ screenshot_x: f64,+ screenshot_y: f64,+) -> anyhow::Result<(f64, f64)> {+ let current_native_action_dimensions = live_action_dimensions(&target)?;+ admit_with_live_dimensions(+ service,+ args,+ capture_id,+ target,+ current_native_action_dimensions,+ screenshot_x,+ screenshot_y,+ )+}++fn admit_with_live_dimensions(+ service: &CaptureService,+ args: &Value,+ capture_id: &str,+ target: CaptureTarget,+ current_native_action_dimensions: NativeActionDimensions,+ screenshot_x: f64,+ screenshot_y: f64,+) -> anyhow::Result<(f64, f64)> {+ let binding = service.binding_from_args(args)?;+ let capture_id = service.parse_capture_id(capture_id)?;+ let admission = service.admit_action(CaptureActionRequest {+ capture_id,+ binding,+ target,+ current_native_action_dimensions,+ screenshot_x,+ screenshot_y,+ })?;+ Ok((admission.action_x, admission.action_y))+}++#[cfg(target_os = "linux")]+fn live_action_dimensions(target: &CaptureTarget) -> anyhow::Result<NativeActionDimensions> {+ let dimensions = match target {+ CaptureTarget::Window { pid, window_id } => {+ let identity_matches = if crate::wayland::is_wayland() {+ crate::wayland::window_was_listed_for_pid(*pid, *window_id)+ } else {+ crate::x11::window_belongs_to_pid(*window_id, *pid)+ };+ anyhow::ensure!(+ identity_matches,+ "native window identity changed after capture"+ );+ let png = crate::wayland::screenshot_dispatch_with_pid(*window_id, *pid)?;+ crate::capture::png_dimensions_pub(&png)?+ }+ CaptureTarget::PrimaryDesktop => {+ let png = crate::capture::screenshot_display_bytes()?;+ let native = crate::capture::png_dimensions_pub(&png)?;+ desktop_action_dimensions(native)?+ }+ };+ Ok(NativeActionDimensions::new(dimensions.0, dimensions.1)?)+}++#[cfg(not(target_os = "linux"))]+fn live_action_dimensions(_target: &CaptureTarget) -> anyhow::Result<NativeActionDimensions> {+ anyhow::bail!("live Linux capture validation is unavailable on this platform")+}++#[cfg(target_os = "linux")]+pub(crate) fn desktop_action_dimensions(native: (u32, u32)) -> anyhow::Result<(u32, u32)> {+ let logical = if crate::wayland::is_wayland() && crate::wayland::hyprland::is_session() {+ let (width, height, _) = crate::wayland::hyprland::screen_size()?;+ Some((width, height))+ } else {+ None+ };+ select_desktop_action_dimensions(native, logical)+}++fn select_desktop_action_dimensions(+ native: (u32, u32),+ compositor_logical: Option<(u32, u32)>,+) -> anyhow::Result<(u32, u32)> {+ let dimensions = compositor_logical.unwrap_or(native);+ anyhow::ensure!(+ dimensions.0 > 0 && dimensions.1 > 0,+ "desktop action frame is empty: {}x{}",+ dimensions.0,+ dimensions.1+ );+ Ok(dimensions)+}++pub(crate) fn admission_error_code(error: &anyhow::Error) -> &'static str {+ if error.downcast_ref::<CaptureIdParseError>().is_some() {+ return "capture_id_invalid";+ }+ match error.downcast_ref::<CaptureActionError>() {+ Some(CaptureActionError::Lookup(CaptureLookupError::Unknown)) => "capture_not_found",+ Some(CaptureActionError::Lookup(CaptureLookupError::Expired)) => "capture_expired",+ Some(CaptureActionError::Lookup(CaptureLookupError::GenerationMismatch)) => {+ "capture_generation_mismatch"+ }+ Some(CaptureActionError::Lookup(CaptureLookupError::TargetMismatch)) => {+ "capture_target_mismatch"+ }+ Some(+ CaptureActionError::InvalidScreenshotPoint | CaptureActionError::InvalidMappedPoint,+ ) => "capture_coordinate_invalid",+ Some(CaptureActionError::NativeActionFrameMismatch) => "capture_frame_mismatch",+ None => "capture_action_refused",+ }+}++pub fn admit_window_click(+ service: &CaptureService,+ args: &Value,+ capture_id: &str,+ pid: u32,+ window_id: u64,+ screenshot_x: f64,+ screenshot_y: f64,+) -> anyhow::Result<(f64, f64)> {+ admit(+ service,+ args,+ capture_id,+ window_target(pid, window_id),+ screenshot_x,+ screenshot_y,+ )+}++pub fn admit_desktop_click(+ service: &CaptureService,+ args: &Value,+ capture_id: &str,+ screenshot_x: f64,+ screenshot_y: f64,+) -> anyhow::Result<(f64, f64)> {+ admit(+ service,+ args,+ capture_id,+ CaptureTarget::PrimaryDesktop,+ screenshot_x,+ screenshot_y,+ )+}++pub fn retire_runtime(service: &CaptureService) {+ service.retire_runtime();+}++#[cfg(test)]+mod tests {+ use super::*;+ use sha2::{Digest, Sha256};++ fn png(width: u32, height: u32, value: u8) -> Vec<u8> {+ let rgba = vec![value; (width * height * 4) as usize];+ cua_driver_core::image_utils::encode_rgba_to_png(&rgba, width, height)+ .expect("encode fixture")+ }++ fn args(session: &str) -> Value {+ serde_json::json!({"_session_id": session})+ }++ fn admit_window(+ service: &CaptureService,+ args: &Value,+ capture_id: &str,+ pid: u32,+ window_id: u64,+ point: (f64, f64),+ native: (u32, u32),+ ) -> anyhow::Result<(f64, f64)> {+ admit_with_live_dimensions(+ service,+ args,+ capture_id,+ window_target(pid, window_id),+ NativeActionDimensions::new(native.0, native.1).unwrap(),+ point.0,+ point.1,+ )+ }++ fn admit_desktop(+ service: &CaptureService,+ args: &Value,+ capture_id: &str,+ point: (f64, f64),+ native: (u32, u32),+ ) -> anyhow::Result<(f64, f64)> {+ admit_with_live_dimensions(+ service,+ args,+ capture_id,+ CaptureTarget::PrimaryDesktop,+ NativeActionDimensions::new(native.0, native.1).unwrap(),+ point.0,+ point.1,+ )+ }++ #[test]+ fn window_publication_digests_the_exact_returned_png() {+ let service = CaptureService::default();+ let delivered = png(2, 2, 0x41);+ let id = publish_window(+ &service,+ &args("digest"),+ &delivered,+ 41,+ 99,+ (2, 2),+ (4, 4),+ )+ .expect("publish window capture");+ let binding = service.binding_from_args(&args("digest")).unwrap();+ let capture = service+ .read_for_perception(service.parse_capture_id(&id).unwrap(), &binding)+ .expect("read published capture");++ assert_eq!(capture.png_bytes().as_ref(), delivered.as_slice());+ let expected: [u8; 32] = Sha256::digest(&delivered).into();+ assert_eq!(capture.digest().as_bytes(), &expected);+ }++ #[test]+ fn target_mismatch_does_not_consume_but_successful_admission_does() {+ let service = CaptureService::default();+ let call_args = args("one-action");+ let id = publish_window(+ &service,+ &call_args,+ &png(10, 10, 0x22),+ 7,+ 11,+ (10, 10),+ (20, 20),+ )+ .unwrap();++ assert!(admit_window(&service, &call_args, &id, 7, 12, (2.0, 3.0), (20, 20)).is_err());+ assert_eq!(+ admit_window(&service, &call_args, &id, 7, 11, (2.0, 3.0), (20, 20)).unwrap(),+ (4.0, 6.0)+ );+ assert!(admit_window(&service, &call_args, &id, 7, 11, (2.0, 3.0), (20, 20)).is_err());+ }++ #[test]+ fn retired_session_capture_is_stale() {+ let service = CaptureService::default();+ let call_args = args("retired");+ let id = publish_desktop(&service, &call_args, &png(3, 2, 0x77), (3, 2)).unwrap();++ let binding = service.binding_from_args(&call_args).unwrap();+ service.retire_session(&binding);++ assert!(admit_desktop(&service, &call_args, &id, (1.0, 1.0), (3, 2)).is_err());+ }++ #[test]+ fn window_transform_preserves_each_rounded_axis() {+ let service = CaptureService::default();+ let call_args = args("rounding");+ let id = publish_window(+ &service,+ &call_args,+ &png(3, 2, 0x33),+ 8,+ 13,+ (3, 2),+ (5, 3),+ )+ .unwrap();++ let (x, y) = admit_window(&service, &call_args, &id, 8, 13, (1.0, 1.0), (5, 3)).unwrap();+ assert_eq!(x, 5.0 / 3.0);+ assert_eq!(y, 3.0 / 2.0);+ }++ #[test]+ fn another_session_cannot_admit_or_consume_a_capture() {+ let service = CaptureService::default();+ let owner = args("owner");+ let id = publish_desktop(&service, &owner, &png(4, 3, 0x21), (4, 3)).unwrap();++ let refusal = admit_desktop(&service, &args("other"), &id, (2.0, 1.0), (4, 3))+ .expect_err("cross-session admission must fail");+ assert_eq!(+ admission_error_code(&refusal),+ "capture_generation_mismatch"+ );+ assert_eq!(+ admit_desktop(&service, &owner, &id, (2.0, 1.0), (4, 3)).unwrap(),+ (2.0, 1.0)+ );+ }++ #[test]+ fn hidpi_desktop_uses_the_compositors_logical_action_frame() {+ let native = (3200, 2000);+ let logical = select_desktop_action_dimensions(native, Some((1600, 1000))).unwrap();+ assert_eq!(logical, (1600, 1000));++ let service = CaptureService::default();+ let call_args = args("hidpi");+ let id = publish_desktop(+ &service,+ &call_args,+ &png(logical.0, logical.1, 0x31),+ logical,+ )+ .unwrap();+ assert_eq!(+ admit_desktop(&service, &call_args, &id, (800.0, 500.0), logical).unwrap(),+ (800.0, 500.0)+ );+ }++ #[test]+ fn capture_action_refusals_have_stable_specific_codes() {+ for (error, code) in [+ (+ CaptureActionError::Lookup(CaptureLookupError::Unknown),+ "capture_not_found",+ ),+ (+ CaptureActionError::Lookup(CaptureLookupError::Expired),+ "capture_expired",+ ),+ (+ CaptureActionError::Lookup(CaptureLookupError::GenerationMismatch),+ "capture_generation_mismatch",+ ),+ (+ CaptureActionError::Lookup(CaptureLookupError::TargetMismatch),+ "capture_target_mismatch",+ ),+ (+ CaptureActionError::InvalidScreenshotPoint,+ "capture_coordinate_invalid",+ ),+ (+ CaptureActionError::InvalidMappedPoint,+ "capture_coordinate_invalid",+ ),+ (+ CaptureActionError::NativeActionFrameMismatch,+ "capture_frame_mismatch",+ ),+ ] {+ assert_eq!(admission_error_code(&anyhow::Error::new(error)), code);+ }+ }++ #[test]+ fn desktop_publication_uses_the_post_normalization_bytes() {+ let service = CaptureService::default();+ let normalized = png(4, 3, 0x18);+ let id = publish_desktop(&service, &args("desktop"), &normalized, (4, 3)).unwrap();+ let binding = service.binding_from_args(&args("desktop")).unwrap();+ let capture = service+ .read_for_perception(service.parse_capture_id(&id).unwrap(), &binding)+ .unwrap();++ assert_eq!(capture.png_bytes().as_ref(), normalized.as_slice());+ assert_eq!(+ admit_desktop(&service, &args("desktop"), &id, (2.0, 1.0), (4, 3)).unwrap(),+ (2.0, 1.0)+ );+ }++ #[test]+ fn explicit_image_dimension_override_wins_including_native_zero() {+ assert_eq!(+ resolve_max_image_dimension(1568, Some(800), Some(2048)),+ 2048+ );+ assert_eq!(resolve_max_image_dimension(1568, Some(800), Some(0)), 0);+ }++ #[test]+ fn omitted_image_dimension_override_preserves_existing_behavior() {+ assert_eq!(resolve_max_image_dimension(1568, None, None), 1568);+ assert_eq!(resolve_max_image_dimension(0, None, None), 0);+ assert_eq!(resolve_max_image_dimension(1568, Some(800), None), 800);+ }++ #[test]+ fn live_resize_refuses_before_dispatch_without_consuming_capture() {+ let service = CaptureService::default();+ let call_args = args("resize");+ let id = publish_window(+ &service,+ &call_args,+ &png(4, 3, 0x44),+ 8,+ 13,+ (4, 3),+ (8, 6),+ )+ .unwrap();+ let mut dispatches = 0;+ let refusal = admit_window(&service, &call_args, &id, 8, 13, (1.25, 1.5), (9, 6));+ if refusal.is_ok() {+ dispatches += 1;+ }+ assert_eq!(dispatches, 0);+ assert!(refusal+ .unwrap_err()+ .downcast_ref::<cua_driver_core::capture_runtime::CaptureActionError>()+ .is_some_and(|error| {+ *error+ == cua_driver_core::capture_runtime::CaptureActionError::NativeActionFrameMismatch+ }));+ assert_eq!(+ admit_window(&service, &call_args, &id, 8, 13, (1.25, 1.5), (8, 6),).unwrap(),+ (2.5, 3.0)+ );+ }+}diff --git a/libs/cua-driver/rust/crates/platform-linux/src/input/mod.rs b/libs/cua-driver/rust/crates/platform-linux/src/input/mod.rsindex 29a4d2d607..6d24eb40f9 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/input/mod.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/input/mod.rs@@ -1821,11 +1821,58 @@ fn deepest_child_at_point(Ok((window, local_x, local_y))}-fn resolve_event_target(conn: &RustConnection, xid: u64, x: i32, y: i32) -> Result<EventTarget> {+fn window_path_at_point(+ conn: &RustConnection,+ window: Window,+ local_x: i32,+ local_y: i32,+) -> Result<Vec<(Window, i32, i32, EventMask)>> {+ let attributes = conn.get_window_attributes(window)?.reply()?;+ let mut path = vec![(window, local_x, local_y, attributes.all_event_masks)];+ let tree = conn.query_tree(window)?.reply()?;+ for child in tree.children.iter().rev() {+ let Ok(geom) = conn.get_geometry(*child)?.reply() else {+ continue;+ };+ if !point_in_rect(local_x, local_y, &geom) {+ continue;+ }+ let child_x = local_x - geom.x as i32;+ let child_y = local_y - geom.y as i32;+ path.extend(window_path_at_point(conn, *child, child_x, child_y)?);+ break;+ }+ Ok(path)+}++fn deepest_event_target(+ path: &[(Window, i32, i32, EventMask)],+ required_masks: EventMask,+) -> (Window, i32, i32) {+ path.iter()+ .rev()+ .find(|(_, _, _, selected)| selected.contains(required_masks))+ .or_else(|| path.last())+ .map(|&(window, x, y, _)| (window, x, y))+ .expect("window path always contains its toplevel")+}++fn click_event_target(path: &[(Window, i32, i32, EventMask)]) -> (Window, i32, i32) {+ deepest_event_target(path, EventMask::BUTTON_PRESS)+}++fn build_event_target(+ conn: &RustConnection,+ xid: u64,+ x: i32,+ y: i32,+ window: Window,+ local_x: i32,+ local_y: i32,+) -> Result<EventTarget> {let top = xid as Window;let root = conn.setup().roots[0].root;let root_pos = conn.translate_coordinates(top, root, 0, 0)?.reply()?;- let (window, local_x, local_y) = deepest_child_at_point(conn, top, x, y)?;Ok(EventTarget {window,local_x: local_x as i16,@@ -1835,6 +1882,28 @@ fn resolve_event_target(conn: &RustConnection, xid: u64, x: i32, y: i32) -> Resu})}+fn resolve_event_target(conn: &RustConnection, xid: u64, x: i32, y: i32) -> Result<EventTarget> {+ let top = xid as Window;+ let (window, local_x, local_y) = deepest_child_at_point(conn, top, x, y)?;+ build_event_target(conn, xid, x, y, window, local_x, local_y)+}++fn resolve_click_event_target(+ conn: &RustConnection,+ xid: u64,+ x: i32,+ y: i32,+) -> Result<EventTarget> {+ let top = xid as Window;+ let path = window_path_at_point(conn, top, x, y)?;+ // Button bindings commonly select only ButtonPress (Tk's <Button-1> is one+ // example). Route the complete synthetic click to that same client-owned+ // window: splitting release onto a different geometric leaf does not form a+ // coherent toolkit click sequence.+ let target = click_event_target(&path);+ build_event_target(conn, xid, x, y, target.0, target.1, target.2)+}+fn button_state_mask(button: u8) -> KeyButMask {match button {1 => KeyButMask::BUTTON1,@@ -1923,7 +1992,7 @@ pub fn send_click_with_modifiers(let modifier_state = modifiers_to_state(modifiers);for _ in 0..count {- let target = resolve_event_target(&conn, xid, x, y)?;+ let target = resolve_click_event_target(&conn, xid, x, y)?;let press = ButtonPressEvent {response_type: BUTTON_PRESS_EVENT,detail: button,@@ -1958,10 +2027,14 @@ pub fn send_click_with_modifiers(same_screen: true,};- conn.send_event(false, target.window, EventMask::BUTTON_PRESS, &press)?;+ // The event mask selects recipients independently of the payload type.+ // Select the press client for both payloads so a press-only toolkit+ // binding (such as Tk's <Button-1>) receives one coherent click.+ conn.send_event(false, target.window, EventMask::BUTTON_PRESS, &press)?+ .check()?;sleep(Duration::from_millis(CLICK_DELAY_MS));- conn.send_event(false, target.window, EventMask::BUTTON_RELEASE, &release)?;- conn.flush()?;+ conn.send_event(false, target.window, EventMask::BUTTON_PRESS, &release)?+ .check()?;if count > 1 {sleep(Duration::from_millis(80));@@ -2967,13 +3040,61 @@ exit 0"#,#[cfg(test)]mod path_tests {use super::{- create_uinput_pointer, ensure_master_pointer_for_session, guarded_uinput_creation,- is_uinput_unavailable, kde_x11_uinput_hotplug_is_unsafe, master_pointer_name,- modifiers_to_state, normalize_uinput_device_name, path_cumulative, point_on_path,- real_pointer_capabilities_available, sample_function, slave_pointer_name,+ click_event_target, create_uinput_pointer, ensure_master_pointer_for_session,+ guarded_uinput_creation, is_uinput_unavailable, kde_x11_uinput_hotplug_is_unsafe,+ master_pointer_name, modifiers_to_state, normalize_uinput_device_name, path_cumulative,+ point_on_path, real_pointer_capabilities_available, sample_function, slave_pointer_name,EVDEV_UINPUT_NAME_MAX_BYTES, UINPUT_POINTER_SUFFIX,};- use x11rb::protocol::xproto::KeyButMask;+ use x11rb::protocol::xproto::{EventMask, KeyButMask};++ #[test]+ fn synthetic_click_keeps_release_on_press_recipient() {+ let path = [+ (+ 10,+ 394,+ 220,+ EventMask::BUTTON_PRESS | EventMask::BUTTON_RELEASE,+ ),+ (11, 24, 30, EventMask::BUTTON_PRESS),+ (12, 6, 8, EventMask::BUTTON_RELEASE),+ ];++ assert_eq!(click_event_target(&path), (11, 24, 30));+ }++ #[test]+ fn synthetic_click_uses_deepest_common_target_for_both_events() {+ let path = [+ (+ 10,+ 394,+ 220,+ EventMask::BUTTON_PRESS | EventMask::BUTTON_RELEASE,+ ),+ (+ 11,+ 24,+ 30,+ EventMask::BUTTON_PRESS | EventMask::BUTTON_RELEASE,+ ),+ (12, 6, 8, EventMask::NO_EVENT),+ ];++ assert_eq!(click_event_target(&path), (11, 24, 30));+ }++ #[test]+ fn synthetic_click_preserves_recipient_local_coordinates_and_event_fallback() {+ let path = [+ (10, 394, 220, EventMask::BUTTON_PRESS),+ (11, 24, 30, EventMask::NO_EVENT),+ (12, 6, 8, EventMask::NO_EVENT),+ ];++ assert_eq!(click_event_target(&path), (10, 394, 220));+ }#[test]fn click_modifier_state_combines_canonical_names_and_aliases() {diff --git a/libs/cua-driver/rust/crates/platform-linux/src/lib.rs b/libs/cua-driver/rust/crates/platform-linux/src/lib.rsindex 879aa53db5..d8f3f39392 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/lib.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/lib.rs@@ -46,6 +46,7 @@ pub mod installed_apps;#[cfg(target_os = "linux")]pub mod capture;+mod capture_action_frame;#[cfg(target_os = "linux")]mod clipboard;diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rsindex 790254fb49..c2fbb95488 100644--- a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs@@ -52,7 +52,7 @@ fn pid_window_guarded<T: Tool + 'static>())}-// ── DriverConfig + ResizeRegistry + ZoomRegistry ─────────────────────────────+// ── DriverConfig + ZoomRegistry ─────────────────────────────────────────────#[derive(Clone)]pub struct DriverConfig {@@ -90,70 +90,15 @@ pub fn load_driver_config() -> DriverConfig {cfg}-pub struct ResizeRegistry {- ratios: std::sync::Mutex<std::collections::HashMap<u32, f64>>,-}--impl ResizeRegistry {- pub fn new() -> Self {- Self {- ratios: std::sync::Mutex::new(Default::default()),- }- }- pub fn set_ratio(&self, pid: u32, ratio: f64) {- self.ratios.lock().unwrap().insert(pid, ratio);- }- pub fn clear_ratio(&self, pid: u32) {- self.ratios.lock().unwrap().remove(&pid);- }- pub fn ratio(&self, pid: u32) -> Option<f64> {- self.ratios.lock().unwrap().get(&pid).copied()- }-}--/// Per-process zoom context — stores padded crop origin and resize scale from-/// the most recent `zoom` call so `click(from_zoom=true)` can translate-/// zoom-image pixel coordinates back to full-window coordinates.-#[derive(Clone, Copy, Debug)]-pub struct ZoomContext {- pub origin_x: f64,- pub origin_y: f64,- /// Inverse resize scale: `cw / out_w` (1.0 = no downscale).- pub scale_inv: f64,-}--impl ZoomContext {- pub fn zoom_to_window(&self, px: f64, py: f64) -> (f64, f64) {- (- self.origin_x + px * self.scale_inv,- self.origin_y + py * self.scale_inv,- )- }-}--pub struct ZoomRegistry {- inner: std::sync::Mutex<std::collections::HashMap<u32, ZoomContext>>,-}--impl ZoomRegistry {- pub fn new() -> Self {- Self {- inner: std::sync::Mutex::new(Default::default()),- }- }- pub fn set(&self, pid: u32, ctx: ZoomContext) {- self.inner.lock().unwrap().insert(pid, ctx);- }- pub fn get(&self, pid: u32) -> Option<ZoomContext> {- self.inner.lock().unwrap().get(&pid).copied()- }-}+use cua_driver_core::element_cache::{+ SnapshotBoundZoomContext as ZoomContext, SnapshotBoundZoomRegistry as ZoomRegistry,+};pub struct ToolState {pub element_cache: Arc<ElementCache>,pub cursor_registry: Arc<CursorRegistry>,- pub resize_registry: Arc<ResizeRegistry>,pub zoom_registry: Arc<ZoomRegistry>,+ pub capture_service: Arc<cua_driver_core::capture_runtime::CaptureService>,pub mouse_hold: std::sync::Mutex<std::collections::HashMap<String, MouseHoldState>>,pub config: Arc<RwLock<DriverConfig>>,}@@ -169,17 +114,52 @@ pub struct MouseHoldState {impl ToolState {pub fn new() -> Arc<Self> {+ Self::new_with_capture_service(Arc::new(+ cua_driver_core::capture_runtime::CaptureService::default(),+ ))+ }++ fn new_with_capture_service(+ capture_service: Arc<cua_driver_core::capture_runtime::CaptureService>,+ ) -> Arc<Self> {let element_cache = Arc::new(ElementCache::new());cua_driver_core::element_cache::register_runtime_cache(&element_cache);Arc::new(Self {element_cache,cursor_registry: Arc::new(CursorRegistry::new()),- resize_registry: Arc::new(ResizeRegistry::new()),zoom_registry: Arc::new(ZoomRegistry::new()),+ capture_service,mouse_hold: std::sync::Mutex::new(Default::default()),config: Arc::new(RwLock::new(load_driver_config())),})}++ fn zoom_context(+ &self,+ args: &Value,+ pid: u32,+ window_id: Option<u64>,+ ) -> Result<ZoomContext, ToolResult> {+ self.zoom_registry.resolve(+ &self.element_cache,+ pid as i32,+ window_id,+ args.get("_session_id").and_then(Value::as_str),+ )+ }+}++fn screenshot_scale(+ state: &ToolState,+ args: &Value,+ pid: u32,+ window_id: Option<u64>,+) -> Result<f64, ToolResult> {+ state.element_cache.screenshot_scale_or_refusal(+ pid as i32,+ window_id,+ args.get("_session_id").and_then(Value::as_str),+ )}// ── list_apps ────────────────────────────────────────────────────────────────@@ -563,18 +543,6 @@ mod list_windows_tests {// ── get_window_state ─────────────────────────────────────────────────────────-/// Fold a per-call `max_dimension` cap with the configured-/// `max_image_dimension` ceiling. `resize_png_if_needed` treats `0` as "no-/// limit", so an unlimited ceiling defers to the per-call cap; otherwise the-/// tighter (smaller, non-zero) of the two wins.-fn fold_max_dimension(ceiling: u32, per_call: Option<u32>) -> u32 {- match per_call {- Some(md) if ceiling == 0 => md,- Some(md) => ceiling.min(md),- None => ceiling,- }-}-/// Build a single structured element entry for `get_window_state`./// Returns `None` when the node has no `element_index` (non-actionable rows).fn build_element_entry(@@ -700,7 +668,8 @@ impl Tool for GetWindowStateTool {"query":{"type":"string","description":"Optional case-insensitive substring. Projects both tree_markdown and structured elements to matches plus ancestors while preserving original indices. Compare total_element_count with returned_element_count."},"max_elements":{"type":"integer","minimum":1,"description":"Cap on total AT-SPI nodes walked. Omit for the default (5 000). Lower for huge web/Electron trees."},"max_depth":{"type":"integer","minimum":1,"description":"Cap on the AT-SPI tree walk depth. Omit for the default (uncapped). Lower for deeply nested apps."},- "max_dimension":{"type":"integer","minimum":1,"description":"Optional cap on the returned screenshot's long edge, in pixels (aspect ratio preserved) — the cheap path for a small preview. Applied on top of the configured max_image_dimension ceiling; the tighter wins. Omit for the configured default."}+ "max_dimension":{"type":"integer","minimum":1,"description":"Legacy optional cap on the returned screenshot's long edge. Applied on top of the configured max_image_dimension ceiling when max_image_dimension is omitted."},+ "max_image_dimension":{"type":"integer","minimum":0,"description":"Per-call long-edge override. This value wins over configured and legacy limits; 0 returns native-resolution PNG bytes. Omit to preserve configured behavior."}},"additionalProperties":false}),read_only: true, destructive: false, idempotent: false, open_world: false,})@@ -716,15 +685,31 @@ impl Tool for GetWindowStateTool {Ok(v) => v,Err(e) => return e,};- // Optional per-call cap on the returned screenshot's long edge, folded- // with the configured ceiling below (the tighter wins).+ // Retain the legacy additive cap, but let the canonical per-call field+ // replace the configured ceiling entirely (including 0 = native size).let max_dimension = args.get("max_dimension").and_then(|v| v.as_u64()).map(|v| v.max(1) as u32);+ let max_image_dimension = match args.get("max_image_dimension") {+ None => None,+ Some(value) => match value.as_u64().and_then(|value| u32::try_from(value).ok()) {+ Some(value) => Some(value),+ None => {+ return ToolResult::error(+ "get_window_state.max_image_dimension must be an integer from 0 through 4294967295.",+ )+ .with_structured(json!({ "code": "invalid_arguments" }))+ }+ },+ };let max_dim = {let cfg = self.state.config.read().unwrap();- fold_max_dimension(cfg.max_image_dimension, max_dimension)+ crate::capture_action_frame::resolve_max_image_dimension(+ cfg.max_image_dimension,+ max_dimension,+ max_image_dimension,+ )};// `capture_mode` is DEPRECATED and ignored — get_window_state always// returns BOTH the AT-SPI tree and a screenshot now, so the agent grounds@@ -734,6 +719,7 @@ impl Tool for GetWindowStateTool {// We don't even read the arg; it stays in the schema only so old callers// don't trip additionalProperties:false.let query = args.opt_str("query");+ let session_id = args.opt_str("_session_id");// include_screenshot (default true) — the perf opt-out. The tree+screenshot// pair is the default; `include_screenshot:false` skips the grab and returns// tree only (the cheap re-index path before an element ax action). A@@ -806,6 +792,7 @@ impl Tool for GetWindowStateTool {.and_then(|value| value.as_bool())== Some(true);let state = self.state.clone();+ let state_for_capture = state.clone();let query_for_walk = query.clone();let result = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {@@ -834,24 +821,38 @@ impl Tool for GetWindowStateTool {// screenshot_out_file set, write to disk and surface the path instead// of embedding base64; otherwise embed base64. Skipped only when// include_screenshot:false and no disk path was requested.- // Tuple: (Option<b64>, Option<file_path>, w, h, Option<original_w>).+ // Keep the exact delivered PNG for capture publication. The action+ // binding must identify the bytes returned to the caller, including+ // any max-dimension resize, rather than the backend's raw frame.let mut screenshot_error = None;let screenshot = if should_capture {match crate::wayland::screenshot_dispatch_with_pid(xid, pid) {Ok(raw) => {- let orig_w = crate::capture::png_dimensions_pub(&raw)- .map(|(w, _)| w)- .unwrap_or(0);+ let (orig_w, orig_h) = crate::capture::png_dimensions_pub(&raw)?;let png = crate::capture::resize_png_if_needed(&raw, max_dim)?;let (w, h) = crate::capture::png_dimensions_pub(&png)?;let original_w = if w < orig_w { Some(orig_w) } else { None };- if let Some(ref path) = screenshot_out_file {+ let (b64, file_path) = if let Some(ref path) = screenshot_out_file {std::fs::write(path, &png)?;- Some((None, Some(path.clone()), w, h, original_w))+ (None, Some(path.clone()))} else {use base64::{engine::general_purpose::STANDARD as B64, Engine as _};- Some((Some(B64.encode(&png)), None, w, h, original_w))- }+ (Some(B64.encode(&png)), None)+ };+ let capture_id = if observation_only {+ None+ } else {+ Some(crate::capture_action_frame::publish_window(+ &state_for_capture.capture_service,+ &args,+ &png,+ pid,+ xid,+ (w, h),+ (orig_w, orig_h),+ )?)+ };+ Some((b64, file_path, w, h, original_w, capture_id))}Err(error) if crate::wayland::is_surface_identity_unproven(&error) => {screenshot_error = Some(error.to_string());@@ -874,6 +875,10 @@ impl Tool for GetWindowStateTool {Ok(Ok((tree_opt, shot_opt, bounds, screenshot_error))) => {let mut content = Vec::new();let mut structured = json!({ "window_id": xid, "pid": pid });+ let screenshot_scale = shot_opt.as_ref().map(|(_, _, w, _, original_w, _)| {+ original_w.map_or(1.0, |ow| ow as f64 / *w as f64)+ });+ let mut published_snapshot = false;if let Some(tr) = tree_opt {let source_trusted = tr.trusted;@@ -899,13 +904,23 @@ impl Tool for GetWindowStateTool {if !observation_only && !target_scoped {state.element_cache.remove(pid as i32, xid);}- let snapshot_id = (!observation_only && target_scoped).then(|| {- state.element_cache.publish(- pid as i32,- xid,- crate::atspi::cache::CachedSnapshot::from_nodes(&tr.nodes),- )- });+ let snapshot_id = (!observation_only && target_scoped)+ .then(|| {+ state.element_cache.publish_for_session(+ pid as i32,+ xid,+ crate::atspi::cache::CachedSnapshot::from_nodes(&tr.nodes),+ session_id.as_deref(),+ screenshot_scale,+ )+ })+ .flatten();+ published_snapshot = snapshot_id.is_some();+ if let Some(snapshot_id) = snapshot_id {+ state+ .zoom_registry+ .retire_replaced(pid as i32, xid, snapshot_id);+ }// Structured `elements` array: one entry per actionable node.// Shape: `{element_index, element_token, role, label,@@ -991,16 +1006,21 @@ impl Tool for GetWindowStateTool {}}- if let Some((b64_opt, file_path, w, h, orig_w)) = shot_opt {- if !observation_only {- if let Some(ow) = orig_w {- if w > 0 {- state.resize_registry.set_ratio(pid, ow as f64 / w as f64);- }- } else {- state.resize_registry.clear_ratio(pid);- }+ if !observation_only && !published_snapshot && screenshot_scale.is_some() {+ if let Some(snapshot_id) = state.element_cache.publish_for_session(+ pid as i32,+ xid,+ crate::atspi::cache::CachedSnapshot::from_nodes(&[]),+ session_id.as_deref(),+ screenshot_scale,+ ) {+ state+ .zoom_registry+ .retire_replaced(pid as i32, xid, snapshot_id);}+ }++ if let Some((b64_opt, file_path, w, h, _orig_w, capture_id)) = shot_opt {// ax mode + screenshot_out_file writes the PNG to disk and// returns b64=None — never embed the image bytes in that case.// Keep a text content part when the image went to disk so the@@ -1019,6 +1039,9 @@ impl Tool for GetWindowStateTool {// the structured payload so consumers don't have to sniff// magic bytes off the base64 to know the format.structured["screenshot_mime_type"] = json!("image/png");+ if let Some(capture_id) = capture_id {+ structured["capture_id"] = json!(capture_id);+ }if let Some(fp) = file_path {structured["screenshot_file_path"] = json!(fp);}@@ -1973,6 +1996,32 @@ fn unavailable_wayland_focused_input_background(})}+#[derive(Debug)]+enum CoordinateContext {+ Zoom(ZoomContext),+ Screenshot(f64),+}++fn coordinate_click_context(+ native_refusal: Option<ToolResult>,+ resolve_context: impl FnOnce() -> Result<CoordinateContext, ToolResult>,+) -> Result<CoordinateContext, ToolResult> {+ if let Some(refusal) = native_refusal {+ return Err(refusal);+ }+ resolve_context()+}++fn coordinate_drag_context(+ native_refusal: Option<ToolResult>,+ resolve_context: impl FnOnce() -> Result<CoordinateContext, ToolResult>,+) -> Result<CoordinateContext, ToolResult> {+ if let Some(refusal) = native_refusal {+ return Err(refusal);+ }+ resolve_context()+}+/// Chromium's X11 renderer drops synthetic input sent to an occluded,/// unfocused toplevel. Returning success here would be a silent loss, so all/// input tools expose the same typed refusal and leave foreground activation@@ -2577,6 +2626,266 @@ fn type_text_routes_isolated_background_before_generic_wayland_refusal() {assert!(invoke.contains("execute_background_text"));}+#[cfg(test)]+#[test]+fn coordinate_click_keeps_wayland_background_refusal_ahead_of_screenshot_context() {+ use std::sync::atomic::{AtomicBool, Ordering};++ let resolved = AtomicBool::new(false);+ let native_refusal = crate::input::delivery::background_unavailable_error(+ crate::input::delivery::BackgroundUnavailable::FocusedInputOnly,+ );+ let result = coordinate_click_context(Some(native_refusal), || {+ resolved.store(true, Ordering::SeqCst);+ Ok(CoordinateContext::Screenshot(7.35))+ })+ .expect_err("unsupported Wayland background delivery must refuse");++ assert_eq!(+ result.structured_content.as_ref().unwrap()["code"],+ "background_unavailable"+ );+ assert!(+ !resolved.load(Ordering::SeqCst),+ "snapshot context must not be consulted before the native refusal"+ );+}++#[cfg(test)]+#[test]+fn coordinate_drag_keeps_wayland_background_refusal_ahead_of_screenshot_context() {+ use std::sync::atomic::{AtomicBool, Ordering};++ let resolved = AtomicBool::new(false);+ let native_refusal = crate::input::delivery::background_unavailable_error(+ crate::input::delivery::BackgroundUnavailable::FocusedInputOnly,+ );+ let result = coordinate_drag_context(Some(native_refusal), || {+ resolved.store(true, Ordering::SeqCst);+ Ok(CoordinateContext::Screenshot(7.35))+ })+ .expect_err("unsupported Wayland background delivery must refuse drag");++ assert_eq!(+ result.structured_content.as_ref().unwrap()["code"],+ "background_unavailable"+ );+ assert!(+ !resolved.load(Ordering::SeqCst),+ "drag snapshot context must not be consulted before the native refusal"+ );+}++#[cfg(test)]+#[test]+fn zoom_schema_keeps_pid_optional_for_window_owned_lookup() {+ let tool = ZoomTool {+ state: ToolState::new(),+ };+ let required = tool.def().input_schema["required"].as_array().unwrap();+ assert!(!required.iter().any(|field| field == "pid"));+ assert!(tool.def().input_schema["properties"].get("pid").is_some());++ tool.state.element_cache.publish_for_session(+ 42,+ 7,+ crate::atspi::cache::CachedSnapshot::from_nodes(&[]),+ Some("zoom-optional-pid-linux"),+ Some(2.0),+ );+ let (pid, context) = tool+ .state+ .element_cache+ .screenshot_context_for_zoom(None, 7, Some("zoom-optional-pid-linux"))+ .unwrap();+ assert_eq!(pid, 42);+ assert_eq!(context.window_id, 7);+ tool.state.element_cache.publish_for_session(+ 43,+ 7,+ crate::atspi::cache::CachedSnapshot::from_nodes(&[]),+ Some("zoom-optional-pid-linux"),+ Some(1.0),+ );+ assert!(tool+ .state+ .element_cache+ .screenshot_context_for_zoom(None, 7, Some("zoom-optional-pid-linux"))+ .is_err());+}++#[cfg(test)]+#[test]+fn coordinate_less_mouse_button_up_survives_snapshot_replacement() {+ let state = ToolState::new();+ let cursor_id = "held-after-replacement";+ let hold = MouseHoldState {+ pid: 42,+ xid: 7,+ button: 1,+ x: 120.0,+ y: 80.0,+ };+ state.element_cache.publish_for_session(+ hold.pid as i32,+ hold.xid,+ crate::atspi::cache::CachedSnapshot::from_nodes(&[]),+ Some("press-owner"),+ Some(2.0),+ );+ state+ .mouse_hold+ .lock()+ .unwrap()+ .insert(cursor_id.to_owned(), hold.clone());++ state.element_cache.publish_for_session(+ hold.pid as i32,+ hold.xid,+ crate::atspi::cache::CachedSnapshot::from_nodes(&[]),+ Some("replacement-owner"),+ Some(1.0),+ );++ let release_args = json!({"_session_id": "press-owner"});+ assert_eq!(+ mouse_button_up_coordinates(&state, &release_args, &hold).unwrap(),+ (hold.x, hold.y),+ "coordinate-less release must use the stored native hold point"+ );++ let stale_coordinate_args = json!({"_session_id": "press-owner", "x": 60.0, "y": 40.0});+ let refusal = mouse_button_up_coordinates(&state, &stale_coordinate_args, &hold)+ .expect_err("coordinate-bearing release must still reject a replaced snapshot");+ assert_eq!(+ refusal.structured_content.as_ref().unwrap()["code"],+ "screenshot_context_missing"+ );++ clear_mouse_hold_after_release(&state, cursor_id);+ assert!(state+ .mouse_hold+ .lock()+ .unwrap()+ .insert(cursor_id.to_owned(), hold)+ .is_none());+}++#[cfg(test)]+#[test]+fn persistent_wayland_pointer_coordinates_include_window_origin() {+ let output = persistent_pointer_coordinates(true, 7, 10, 20, |window_id, x, y| {+ assert_eq!(window_id, 7);+ (x + 100, y + 200)+ });+ assert_eq!(output, (110, 220));++ let x11 = persistent_pointer_coordinates(false, 7, 10, 20, |_, _, _| {+ panic!("X11 coordinates must remain window-local")+ });+ assert_eq!(x11, (10, 20));+}++#[cfg(test)]+#[test]+fn session_end_releases_only_its_hold_before_discarding_state() {+ let state = ToolState::new();+ let session_id = "ending-session";+ let hold = MouseHoldState {+ pid: 42,+ xid: 7,+ button: 1,+ x: 10.0,+ y: 20.0,+ };+ let other_hold = MouseHoldState {+ pid: 43,+ xid: 8,+ button: 3,+ x: 30.0,+ y: 40.0,+ };+ {+ let mut holds = state.mouse_hold.lock().unwrap();+ holds.insert(session_id.to_owned(), hold.clone());+ holds.insert("other-session".to_owned(), other_hold.clone());+ }++ let mut released = Vec::new();+ release_mouse_hold_for_session(&state, session_id, |cursor_id, held| {+ assert!(state.mouse_hold.lock().unwrap().contains_key(cursor_id));+ released.push((cursor_id.to_owned(), held.button));+ Ok(())+ })+ .unwrap();++ assert_eq!(released, vec![(session_id.to_owned(), hold.button)]);+ let mut holds = state.mouse_hold.lock().unwrap();+ assert!(!holds.contains_key(session_id));+ assert_eq!(+ holds.get("other-session").unwrap().button,+ other_hold.button+ );+ assert!(holds.insert(session_id.to_owned(), hold).is_none());+}++#[cfg(test)]+#[test]+fn failed_session_end_release_remains_retryable_and_bounded() {+ let state = ToolState::new();+ let session_id = "failed-release-session";+ let hold = MouseHoldState {+ pid: 42,+ xid: 7,+ button: 1,+ x: 10.0,+ y: 20.0,+ };+ state+ .mouse_hold+ .lock()+ .unwrap()+ .insert(session_id.to_owned(), hold.clone());++ let mut attempts = 0;+ let failure = release_mouse_hold_for_session(&state, session_id, |_, _| {+ attempts += 1;+ anyhow::bail!("compositor disconnected")+ })+ .expect_err("a failed compositor release must fail session cleanup");+ assert!(failure.contains("compositor disconnected"));+ assert_eq!(+ attempts, 1,+ "one cleanup pass must make one bounded attempt"+ );+ assert_eq!(+ state+ .mouse_hold+ .lock()+ .unwrap()+ .get(session_id)+ .unwrap()+ .button,+ hold.button,+ "failed cleanup must retain the hold for the next session-end retry"+ );++ release_mouse_hold_for_session(&state, session_id, |cursor_id, held| {+ attempts += 1;+ assert_eq!(cursor_id, session_id);+ assert_eq!(held.button, hold.button);+ Ok(())+ })+ .unwrap();+ assert_eq!(attempts, 2);+ assert!(state+ .mouse_hold+ .lock()+ .unwrap()+ .insert(session_id.to_owned(), hold)+ .is_none());+}+#[cfg(test)]#[test]fn isolated_hyprland_refused_partial_and_unknown_outcomes_stay_distinct() {@@ -2869,6 +3178,64 @@ fn held_target_mismatch(}}+fn mouse_button_up_coordinates(+ state: &ToolState,+ args: &Value,+ hold: &MouseHoldState,+) -> Result<(f64, f64), ToolResult> {+ if args.get("x").is_none() && args.get("y").is_none() {+ return Ok((hold.x, hold.y));+ }++ let mut x = args.opt_f64("x").unwrap_or(hold.x);+ let mut y = args.opt_f64("y").unwrap_or(hold.y);+ if args.bool_or("from_zoom", false) {+ let context = state.zoom_context(args, hold.pid, Some(hold.xid))?;+ return Ok(context.zoom_to_window(x, y));+ }++ let ratio = screenshot_scale(state, args, hold.pid, Some(hold.xid))?;+ x *= ratio;+ y *= ratio;+ Ok((x, y))+}++fn clear_mouse_hold_after_release(state: &ToolState, cursor_id: &str) {+ state.mouse_hold.lock().unwrap().remove(cursor_id);+}++fn persistent_pointer_coordinates(+ is_wayland: bool,+ window_id: u64,+ x: i32,+ y: i32,+ window_local_to_output: impl FnOnce(u64, i32, i32) -> (i32, i32),+) -> (i32, i32) {+ if is_wayland {+ window_local_to_output(window_id, x, y)+ } else {+ (x, y)+ }+}++fn release_mouse_hold_for_session<Release>(+ state: &ToolState,+ session_id: &str,+ mut release: Release,+) -> Result<(), String>+where+ Release: FnMut(&str, &MouseHoldState) -> anyhow::Result<()>,+{+ let hold = state.mouse_hold.lock().unwrap().get(session_id).cloned();+ let Some(hold) = hold else {+ return Ok(());+ };++ release(session_id, &hold).map_err(|error| error.to_string())?;+ state.mouse_hold.lock().unwrap().remove(session_id);+ Ok(())+}+fn overlay_snap_to_for(cursor_id: &str, sx: f64, sy: f64, heading: Option<f64>) {crate::overlay::send_command_for(cursor_id.to_owned(),@@ -3266,6 +3633,12 @@ fn inject_terminal_input(pid: u32, xid: u64, text: &str) -> anyhow::Result<bool>pub struct ClickTool {state: Arc<ToolState>,}++fn capture_admission_error(error: anyhow::Error) -> ToolResult {+ let code = crate::capture_action_frame::admission_error_code(&error);+ ToolResult::error(format!("capture-bound click refused: {error}"))+ .with_structured(json!({ "code": code, "effect": "refused" }))+}static CLICK_DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();impl ClickTool {@@ -3423,6 +3796,7 @@ impl Tool for ClickTool {"element_index": cua_driver_core::tool_schema::element_index_schema(),"element_token": cua_driver_core::tool_schema::element_token_schema(),"snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),+ "capture_id":{"type":"string","description":"Optional one-shot binding to the exact PNG returned by get_window_state or get_desktop_state. When present, x/y are interpreted in that capture and admitted before native dispatch."},// Shape matches the shared button_schema() canon (string +// [left,right,middle]); kept inline to carry the Linux/Wayland// back-compat prose the click button-schema test asserts on.@@ -3451,6 +3825,10 @@ impl Tool for ClickTool {let has_window_id = args.get("window_id").map(|v| !v.is_null()).unwrap_or(false);let has_xy = args.get("x").map(|v| v.is_number()).unwrap_or(false)&& args.get("y").map(|v| v.is_number()).unwrap_or(false);+ if args.get("capture_id").is_some() && !has_xy {+ return ToolResult::error("click.capture_id requires both x and y coordinates.")+ .with_structured(json!({ "code": "invalid_arguments" }));+ }if has_xy && !has_pid && !has_window_id {if args.get("scope").and_then(Value::as_str) != Some("desktop") {return ToolResult::error(@@ -3468,13 +3846,27 @@ impl Tool for ClickTool {Err(result) => return result,};let button = parse_mouse_button(input.button.unwrap_or(ClickButton::Left).as_str());- let sx = input.x as i32;- let sy = input.y as i32;let n = input.count.unwrap_or(1) as usize;if n == 0 {return ToolResult::error("click.count must be at least 1.").with_structured(json!({ "code": "invalid_arguments" }));}+ let (action_x, action_y) = if let Some(capture_id) = args.opt_str("capture_id") {+ match crate::capture_action_frame::admit_desktop_click(+ &self.state.capture_service,+ &args,+ &capture_id,+ input.x,+ input.y,+ ) {+ Ok(point) => point,+ Err(error) => return capture_admission_error(error),+ }+ } else {+ (input.x, input.y)+ };+ let sx = action_x as i32;+ let sy = action_y as i32;// Glide the agent-cursor overlay to the click point first (the macOS// / Windows desktop paths already do this). Without it the overlay// sits idle elsewhere while only the real pointer warps, so a viewer@@ -3542,6 +3934,7 @@ impl Tool for ClickTool {// We resolve before the legacy `opt_u64("element_index")` branch// so a token-only call (no integer arg) still takes the element path.let element_token_arg = args.opt_str("element_token");+ let capture_id_arg = args.opt_str("capture_id");let window_id_arg = args.opt_u64("window_id");let element_index_arg = args.opt_u64("element_index").map(|v| v as usize);let resolved = match self.state.element_cache.resolve_element_args(@@ -3568,6 +3961,13 @@ impl Tool for ClickTool {cua_driver_core::element_token::ResolvedElement::None => window_id_arg,};+ if capture_id_arg.is_some() && elem_idx_resolved.is_some() {+ return ToolResult::error(+ "click.capture_id is only valid with x/y coordinates, not an element target.",+ )+ .with_structured(json!({ "code": "invalid_arguments" }));+ }+if let Some(idx) = elem_idx_resolved {if !crate::wayland::is_wayland() {let identity = match resolved {@@ -3805,22 +4205,54 @@ impl Tool for ClickTool {let from_zoom = args.bool_or("from_zoom", false);let mut x = args.f64_or("x", 0.0);let mut y = args.f64_or("y", 0.0);- if from_zoom {- match self.state.zoom_registry.get(pid) {- Some(ctx) => {- let (wx, wy) = ctx.zoom_to_window(x, y);- x = wx;- y = wy;+ if capture_id_arg.is_some() && from_zoom {+ return ToolResult::error(+ "click.capture_id cannot be combined with from_zoom; use coordinates from the published capture.",+ )+ .with_structured(json!({ "code": "invalid_arguments" }));+ }+ let native_refusal = (!isolated_background)+ .then(|| unavailable_wayland_focused_input_background(delivery, true))+ .flatten();+ if let Some(capture_id) = capture_id_arg {+ if let Some(refusal) = native_refusal {+ return refusal;+ }+ match crate::capture_action_frame::admit_window_click(+ &self.state.capture_service,+ &args,+ &capture_id,+ pid,+ xid,+ x,+ y,+ ) {+ Ok(point) => (x, y) = point,+ Err(error) => return capture_admission_error(error),+ }+ } else {+ let context = match coordinate_click_context(native_refusal, || {+ if from_zoom {+ self.state+ .zoom_context(&args, pid, Some(xid))+ .map(CoordinateContext::Zoom)+ } else {+ screenshot_scale(&self.state, &args, pid, Some(xid))+ .map(CoordinateContext::Screenshot)}- None => {- return ToolResult::error(format!(- "from_zoom=true but no zoom context for pid {pid}. Call zoom first."- ))+ }) {+ Ok(context) => context,+ Err(refusal) => return refusal,+ };+ match context {+ CoordinateContext::Zoom(context) => {+ (x, y) = context.zoom_to_window(x, y);+ }+ CoordinateContext::Screenshot(scale) => {+ x *= scale;+ y *= scale;}}- } else if let Some(ratio) = self.state.resize_registry.ratio(pid) {- x *= ratio;- y *= ratio;}crate::overlay::send_command_for(@@ -5914,7 +6346,10 @@ impl Tool for ScrollTool {// Pixel targets use the latest screenshot's coordinate frame.// Apply the same buffer-to-window ratio as click/drag before// positioning either the agent cursor or the input device.- let ratio = self.state.resize_registry.ratio(pid).unwrap_or(1.0);+ let ratio = match screenshot_scale(&self.state, &args, pid, Some(xid)) {+ Ok(ratio) => ratio,+ Err(refusal) => return refusal,+ };Some((x * ratio, y * ratio))}(None, None) => None,@@ -6429,19 +6864,19 @@ impl Tool for DoubleClickTool {let mut x = args.f64_or("x", 0.0);let mut y = args.f64_or("y", 0.0);if from_zoom {- match self.state.zoom_registry.get(pid) {- Some(ctx) => {+ match self.state.zoom_context(&args, pid, Some(xid)) {+ Ok(ctx) => {let (wx, wy) = ctx.zoom_to_window(x, y);x = wx;y = wy;}- None => {- return ToolResult::error(format!(- "from_zoom=true but no zoom context for pid {pid}. Call zoom first."- ))- }+ Err(refusal) => return refusal,}- } else if let Some(ratio) = self.state.resize_registry.ratio(pid) {+ } else {+ let ratio = match screenshot_scale(&self.state, &args, pid, Some(xid)) {+ Ok(ratio) => ratio,+ Err(refusal) => return refusal,+ };x *= ratio;y *= ratio;}@@ -6668,19 +7103,19 @@ impl Tool for RightClickTool {let mut x = args.f64_or("x", 0.0);let mut y = args.f64_or("y", 0.0);if from_zoom {- match self.state.zoom_registry.get(pid) {- Some(ctx) => {+ match self.state.zoom_context(&args, pid, Some(xid)) {+ Ok(ctx) => {let (wx, wy) = ctx.zoom_to_window(x, y);x = wx;y = wy;}- None => {- return ToolResult::error(format!(- "from_zoom=true but no zoom context for pid {pid}. Call zoom first."- ))- }+ Err(refusal) => return refusal,}- } else if let Some(ratio) = self.state.resize_registry.ratio(pid) {+ } else {+ let ratio = match screenshot_scale(&self.state, &args, pid, Some(xid)) {+ Ok(ratio) => ratio,+ Err(refusal) => return refusal,+ };x *= ratio;y *= ratio;}@@ -6871,7 +7306,7 @@ impl Tool for DragTool {};let delivery = crate::input::delivery::DeliveryMode::from_args(&args);let isolated_background = isolated_hyprland_background(delivery);- if !isolated_background {+ let native_refusal = if !isolated_background {if let Some(refusal) = unavailable_chromium_background(pid, delivery) {return refusal;}@@ -6881,10 +7316,25 @@ impl Tool for DragTool {if let Some(refusal) = unavailable_gtk_pointer_background(pid, delivery) {return refusal;}- if let Some(refusal) = unavailable_wayland_focused_input_background(delivery, true) {- return refusal;+ unavailable_wayland_focused_input_background(delivery, true)+ } else {+ None+ };++ let from_zoom = args.bool_or("from_zoom", false);+ let context = match coordinate_drag_context(native_refusal, || {+ if from_zoom {+ self.state+ .zoom_context(&args, pid, Some(xid))+ .map(CoordinateContext::Zoom)+ } else {+ screenshot_scale(&self.state, &args, pid, Some(xid))+ .map(CoordinateContext::Screenshot)}- }+ }) {+ Ok(context) => context,+ Err(refusal) => return refusal,+ };let coerce = |key: &str| -> Option<f64> {args.opt_f64(key)@@ -6911,29 +7361,17 @@ impl Tool for DragTool {let steps = args.u64_or("steps", 20) as usize;let button_str = args.str_or("button", "left");let button = parse_mouse_button(button_str.as_str());- let from_zoom = args.bool_or("from_zoom", false);-- if from_zoom {- match self.state.zoom_registry.get(pid) {- Some(ctx) => {- let (wx, wy) = ctx.zoom_to_window(from_x, from_y);- let (wx2, wy2) = ctx.zoom_to_window(to_x, to_y);- from_x = wx;- from_y = wy;- to_x = wx2;- to_y = wy2;- }- None => {- return ToolResult::error(format!(- "from_zoom=true but no zoom context for pid {pid}. Call zoom first."- ))- }+ match context {+ CoordinateContext::Zoom(context) => {+ (from_x, from_y) = context.zoom_to_window(from_x, from_y);+ (to_x, to_y) = context.zoom_to_window(to_x, to_y);+ }+ CoordinateContext::Screenshot(scale) => {+ from_x *= scale;+ from_y *= scale;+ to_x *= scale;+ to_y *= scale;}- } else if let Some(ratio) = self.state.resize_registry.ratio(pid) {- from_x *= ratio;- from_y *= ratio;- to_x *= ratio;- to_y *= ratio;}if hyprland_foreground(delivery) {@@ -7380,19 +7818,19 @@ impl Tool for MouseButtonDownTool {let mut x = args.f64_or("x", 0.0);let mut y = args.f64_or("y", 0.0);if args.bool_or("from_zoom", false) {- match self.state.zoom_registry.get(pid) {- Some(ctx) => {+ match self.state.zoom_context(&args, pid, Some(xid)) {+ Ok(ctx) => {let (wx, wy) = ctx.zoom_to_window(x, y);x = wx;y = wy;}- None => {- return ToolResult::error(format!(- "from_zoom=true but no zoom context for pid {pid}. Call zoom first."- ))- }+ Err(refusal) => return refusal,}- } else if let Some(ratio) = self.state.resize_registry.ratio(pid) {+ } else {+ let ratio = match screenshot_scale(&self.state, &args, pid, Some(xid)) {+ Ok(ratio) => ratio,+ Err(refusal) => return refusal,+ };x *= ratio;y *= ratio;}@@ -7413,13 +7851,21 @@ impl Tool for MouseButtonDownTool {let xi = x as i32;let yi = y as i32;+ let is_wl = crate::wayland::is_wayland();// Native Wayland: route through the persistent virtual-pointer module// so the held button survives across tool calls; the X11 path keeps// the existing input::send_button_down behaviour.- let result = if crate::wayland::is_wayland() {+ let result = if is_wl {let cid = cursor_id.clone();+ let (output_x, output_y) = persistent_pointer_coordinates(+ is_wl,+ xid,+ xi,+ yi,+ crate::wayland::window_local_to_output,+ );tokio::task::spawn_blocking(move || {- crate::wayland::persistent_vptr::press(&cid, xid, xi, yi, button)+ crate::wayland::persistent_vptr::press(&cid, xid, output_x, output_y, button)}).await} else {@@ -7524,21 +7970,19 @@ impl Tool for MouseDragTool {let mut to_x = args.f64_or("x", 0.0);let mut to_y = args.f64_or("y", 0.0);if args.bool_or("from_zoom", false) {- match self.state.zoom_registry.get(hold.pid) {- Some(ctx) => {+ match self.state.zoom_context(&args, hold.pid, Some(hold.xid)) {+ Ok(ctx) => {let (wx, wy) = ctx.zoom_to_window(to_x, to_y);to_x = wx;to_y = wy;}- None => {- return ToolResult::error(format!(- "from_zoom=true but no zoom context for pid {}. Call zoom first.",- hold.pid- ))- .with_structured(mouse_hold_json(&cursor_id, Some(&hold)))- }+ Err(refusal) => return refusal,}- } else if let Some(ratio) = self.state.resize_registry.ratio(hold.pid) {+ } else {+ let ratio = match screenshot_scale(&self.state, &args, hold.pid, Some(hold.xid)) {+ Ok(ratio) => ratio,+ Err(refusal) => return refusal,+ };to_x *= ratio;to_y *= ratio;}@@ -7586,12 +8030,15 @@ impl Tool for MouseDragTool {// X11 keeps the existing input::send_motion path.let cid_inner = cursor_id.clone();let move_result = if is_wl {+ let (output_x, output_y) = persistent_pointer_coordinates(+ is_wl,+ xid,+ ix.round() as i32,+ iy.round() as i32,+ crate::wayland::window_local_to_output,+ );tokio::task::spawn_blocking(move || {- crate::wayland::persistent_vptr::move_to(- &cid_inner,- ix.round() as i32,- iy.round() as i32,- )+ crate::wayland::persistent_vptr::move_to(&cid_inner, output_x, output_y)}).await} else {@@ -7727,27 +8174,10 @@ impl Tool for MouseButtonUpTool {let xid = hold.xid;- let mut x = args.opt_f64("x").unwrap_or(hold.x);- let mut y = args.opt_f64("y").unwrap_or(hold.y);- if args.bool_or("from_zoom", false) {- match self.state.zoom_registry.get(hold.pid) {- Some(ctx) => {- let (wx, wy) = ctx.zoom_to_window(x, y);- x = wx;- y = wy;- }- None => {- return ToolResult::error(format!(- "from_zoom=true but no zoom context for pid {}. Call zoom first.",- hold.pid- ))- .with_structured(mouse_hold_json(&cursor_id, Some(&hold)))- }- }- } else if let Some(ratio) = self.state.resize_registry.ratio(hold.pid) {- x *= ratio;- y *= ratio;- }+ let (x, y) = match mouse_button_up_coordinates(&self.state, &args, &hold) {+ Ok(point) => point,+ Err(refusal) => return refusal,+ };crate::overlay::send_command_for(cursor_id.clone(),@@ -7789,7 +8219,7 @@ impl Tool for MouseButtonUpTool {cursor_id.clone(),cursor_overlay::OverlayCommand::SetPressed(false),);- self.state.mouse_hold.lock().unwrap().remove(&cursor_id);+ clear_mouse_hold_after_release(&self.state, &cursor_id);let cleared = mouse_hold_json(&cursor_id, None);ToolResult::text(format!("✅ Cursor '{cursor_id}' released held {} button at ({x:.1}, {y:.1}).",@@ -8268,7 +8698,9 @@ fn normalize_desktop_capture_for_action_frame(// ── get_desktop_state ─────────────────────────────────────────────────────────-pub struct GetDesktopStateTool;+pub struct GetDesktopStateTool {+ capture_service: Arc<cua_driver_core::capture_runtime::CaptureService>,+}static GDS_DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();#[async_trait]@@ -8288,11 +8720,13 @@ impl Tool for GetDesktopStateTool {}async fn invoke(&self, args: Value) -> ToolResult {+ let capture_args = args.clone();let input = match parse_typed_input::<GetDesktopStateInput>("get_desktop_state", args) {Ok(input) => input,Err(result) => return result,};let out_file = input.screenshot_out_file;+ let capture_service = self.capture_service.clone();let result = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {// Capture the full display at native size first. When the@@ -8310,7 +8744,7 @@ impl Tool for GetDesktopStateTool {// Only fall back to the X11 root-window geometry off Wayland, so// the X11 / XWayland path is unchanged. See #2017 / Sway testing.let (screen_w, screen_h) = if crate::wayland::is_wayland() {- (native_w, native_h)+ crate::capture_action_frame::desktop_action_dimensions((native_w, native_h))?} else {x11_screen_size()?};@@ -8329,6 +8763,12 @@ impl Tool for GetDesktopStateTool {} else {Some(B64.encode(&png))};+ let capture_id = crate::capture_action_frame::publish_desktop(+ &capture_service,+ &capture_args,+ &png,+ (shot_w, shot_h),+ )?;Ok((b64,shot_w,@@ -8337,12 +8777,22 @@ impl Tool for GetDesktopStateTool {screen_h,scale_factor,written,+ capture_id,))}).await;match result {- Ok(Ok((b64_opt, shot_w, shot_h, screen_w, screen_h, scale_factor, written))) => {+ Ok(Ok((+ b64_opt,+ shot_w,+ shot_h,+ screen_w,+ screen_h,+ scale_factor,+ written,+ capture_id,+ ))) => {let mut content = Vec::new();let mut structured = json!({"platform": "linux",@@ -8353,6 +8803,7 @@ impl Tool for GetDesktopStateTool {"screen_height": screen_h,"scale_factor": scale_factor,"screenshot_mime_type": "image/png",+ "capture_id": capture_id,});if let Some(b64) = b64_opt {content.push(cua_driver_core::protocol::Content::image_png(b64));@@ -9112,11 +9563,15 @@ impl Tool for ZoomTool {description: "Capture a cropped JPEG of a window region (x1,y1)–(x2,y2) in \screenshot pixels, with 20% padding. Output is at most 500 px wide.\n\n\After a zoom, pass from_zoom=true to click/type_text to auto-translate \- coordinates back to full-window space.".into(),+ coordinates back to full-window space. Coordinate actions return \+ `screenshot_context_missing` when the latest snapshot does not contain a \+ screenshot owned by this session. `from_zoom` actions return \+ `zoom_context_missing` when the zoom was never created or was replaced; call \+ `get_window_state`, then `zoom`, again on the same connection.".into(),input_schema: json!({"type":"object","required":["window_id","x1","y1","x2","y2"],"properties":{"window_id":{"type":"integer"},- "pid":{"type":"integer","description":"Target pid — required for from_zoom click/type translation."},+ "pid":{"type":"integer","description":"Optional target pid. When omitted, the driver resolves the unique current snapshot for this session and window."},"x1":{"type":"number"},"y1":{"type":"number"},"x2":{"type":"number"},"y2":{"type":"number"}},"additionalProperties":false@@ -9131,7 +9586,22 @@ impl Tool for ZoomTool {Ok(v) => v,Err(e) => return e,};- let pid = args.opt_u64("pid").map(|v| v as u32);+ let requested_pid = match args.get("pid") {+ None => None,+ Some(value) => match value.as_u64().and_then(|pid| i32::try_from(pid).ok()) {+ Some(pid) => Some(pid),+ None => return ToolResult::error("pid must be a positive 32-bit integer"),+ },+ };+ let session_id = args.opt_str("_session_id");+ let (pid, screenshot) = match self.state.element_cache.screenshot_context_for_zoom(+ requested_pid,+ xid,+ session_id.as_deref(),+ ) {+ Ok(context) => context,+ Err(refusal) => return refusal,+ };let x1 = match args.opt_f64("x1") {Some(v) => v,None => return ToolResult::error("Missing x1"),@@ -9152,6 +9622,12 @@ impl Tool for ZoomTool {return ToolResult::error("x2 must be > x1 and y2 must be > y1");}+ let (x1, y1, x2, y2) = (+ x1 * screenshot.scale,+ y1 * screenshot.scale,+ x2 * screenshot.scale,+ y2 * screenshot.scale,+ );let state = self.state.clone();let result = tokio::task::spawn_blocking(move || {// Route through the Wayland-aware window capture dispatcher so@@ -9165,15 +9641,18 @@ impl Tool for ZoomTool {match result {Ok(Ok(crop)) => {- if let Some(p) = pid {- state.zoom_registry.set(- p,- ZoomContext {- origin_x: crop.origin_x,- origin_y: crop.origin_y,- scale_inv: crop.scale_inv,- },- );+ if let Err(refusal) = state.zoom_registry.set_if_current(+ &state.element_cache,+ pid,+ session_id.as_deref(),+ ZoomContext {+ screenshot,+ origin_x: crop.origin_x,+ origin_y: crop.origin_y,+ scale_inv: crop.scale_inv,+ },+ ) {+ return refusal;}use base64::{engine::general_purpose::STANDARD as B64, Engine as _};let b64 = B64.encode(&crop.jpeg_bytes);@@ -9794,8 +10273,8 @@ pub fn build_registry_with_provider(compat: bool,provider: Option<std::sync::Arc<dyn cua_driver_core::consent::ProtectedConsentProvider>>,) -> ToolRegistry {- let state = ToolState::new();let mut r = ToolRegistry::new_with_protected_consent_provider(provider);+ let state = ToolState::new_with_capture_service(r.capture_service());if crate::wayland::is_wayland() && crate::wayland::hyprland::is_session() {let recording_state = Arc::downgrade(&state);r.recording@@ -9806,8 +10285,13 @@ pub fn build_registry_with_provider(// Match ClickTool's screenshot and zoom conversion before// translating to the recording's full-output image.if args.bool_or("from_zoom", false) {- (x, y) = state.zoom_registry.get(pid)?.zoom_to_window(x, y);- } else if let Some(ratio) = state.resize_registry.ratio(pid) {+ (x, y) = state+ .zoom_context(args, pid, args.opt_u64("window_id"))+ .ok()?+ .zoom_to_window(x, y);+ } else if let Ok(ratio) =+ screenshot_scale(&state, args, pid, args.opt_u64("window_id"))+ {x *= ratio;y *= ratio;}@@ -9853,17 +10337,34 @@ pub fn build_registry_with_provider(let session_end_hook = {let cursor_registry = state.cursor_registry.clone();let state_for_session_end = state.clone();- cua_driver_core::session::register_scoped_session_end_hook(move |session_id| {- cursor_registry.remove(session_id);- crate::overlay::remove_cursor(session_id.to_owned());- state_for_session_end- .mouse_hold- .lock()- .unwrap()- .remove(session_id);- crate::input::forget_master_pointer(session_id);- crate::wayland::hyprland_input::cleanup_session(session_id);- })+ cua_driver_core::session::register_scoped_fallible_session_end_hook(+ "linux_input",+ move |session_id| {+ if crate::wayland::is_wayland() {+ release_mouse_hold_for_session(+ &state_for_session_end,+ session_id,+ |cursor_id, held| {+ crate::wayland::persistent_vptr::release(cursor_id, held.button)+ },+ )?;+ } else {+ clear_mouse_hold_after_release(&state_for_session_end, session_id);+ }++ state_for_session_end+ .zoom_registry+ .retire_session(session_id);+ state_for_session_end+ .element_cache+ .retire_session_screenshots(session_id);+ cursor_registry.remove(session_id);+ crate::overlay::remove_cursor(session_id.to_owned());+ crate::input::forget_master_pointer(session_id);+ crate::wayland::hyprland_input::cleanup_session(session_id);+ Ok(())+ },+ )};let session_revive_hook =cua_driver_core::session::register_scoped_session_revive_hook(move |session_id| {@@ -9875,7 +10376,9 @@ pub fn build_registry_with_provider(if let Some(runtime_scope) = cua_driver_core::tool::current_dispatch_runtime_scope() {let prefix = format!("__cua_runtime_{runtime_scope}:");let cursor_registry = state.cursor_registry.clone();+ let capture_service = state.capture_service.clone();r.retain_runtime_cleanup(move || {+ crate::capture_action_frame::retire_runtime(&capture_service);crate::wayland::hyprland_input::cleanup_runtime(&prefix);for cursor in cursor_registry.all_states()@@ -9992,7 +10495,9 @@ pub fn build_registry_with_provider(// screenshot path is `get_window_state` (it always returns a screenshot now).let _ = compat;r.register(Box::new(GetScreenSizeTool));- r.register(Box::new(GetDesktopStateTool));+ r.register(Box::new(GetDesktopStateTool {+ capture_service: state.capture_service.clone(),+ }));r.register(Box::new(GetCursorPositionTool));r.register(Box::new(MoveCursorTool {state: state.clone(),@@ -10238,9 +10743,26 @@ mod session_cursor_target_tests {}}+#[cfg(test)]+mod window_capture_dimension_tests {+ use super::{GetWindowStateTool, ToolState};+ use cua_driver_core::tool::Tool;++ #[test]+ fn schema_exposes_zero_as_native_resolution() {+ let tool = GetWindowStateTool {+ state: ToolState::new(),+ };+ assert_eq!(+ tool.def().input_schema["properties"]["max_image_dimension"]["minimum"],+ 0+ );+ }+}+#[cfg(test)]mod desktop_capture_frame_tests {- use super::normalize_desktop_capture_for_action_frame;+ use super::{capture_admission_error, normalize_desktop_capture_for_action_frame};fn png(width: u32, height: u32) -> Vec<u8> {let rgba = vec![0x7f; (width * height * 4) as usize];@@ -10268,4 +10790,14 @@ mod desktop_capture_frame_tests {.expect_err("nonuniform mapping must fail closed");assert!(error.to_string().contains("cannot be mapped uniformly"));}++ #[test]+ fn capture_refusal_exposes_specific_code_and_refused_effect() {+ let refusal = capture_admission_error(anyhow::Error::new(+ cua_driver_core::capture_runtime::CaptureActionError::NativeActionFrameMismatch,+ ));+ let structured = refusal.structured_content.unwrap();+ assert_eq!(structured["code"], "capture_frame_mismatch");+ assert_eq!(structured["effect"], "refused");+ }}diff --git a/libs/cua-driver/rust/crates/platform-linux/tests/key_input_x11.rs b/libs/cua-driver/rust/crates/platform-linux/tests/key_input_x11.rsindex a60444fa88..e5d6362217 100644--- a/libs/cua-driver/rust/crates/platform-linux/tests/key_input_x11.rs+++ b/libs/cua-driver/rust/crates/platform-linux/tests/key_input_x11.rs@@ -3,13 +3,19 @@use std::time::{Duration, Instant};use anyhow::{bail, Result};-use platform_linux::input::{send_key, send_key_at, send_key_xtest, send_type_text};+use platform_linux::input::{send_click, send_key, send_key_at, send_key_xtest, send_type_text};use x11rb::connection::Connection;use x11rb::protocol::xproto::*;use x11rb::protocol::Event;use x11rb::rust_connection::RustConnection;-fn input_window(conn: &RustConnection, parent: Window, x: i16, y: i16) -> Result<Window> {+fn event_window(+ conn: &RustConnection,+ parent: Window,+ x: i16,+ y: i16,+ event_mask: EventMask,+) -> Result<Window> {let window = conn.generate_id()?;conn.create_window(x11rb::COPY_DEPTH_FROM_PARENT,@@ -24,12 +30,25 @@ fn input_window(conn: &RustConnection, parent: Window, x: i16, y: i16) -> Result0,&CreateWindowAux::new().override_redirect(1)- .event_mask(EventMask::KEY_PRESS | EventMask::KEY_RELEASE),+ .event_mask(event_mask),)?.check()?;conn.map_window(window)?.check()?;let attributes = conn.get_window_attributes(window)?.reply()?;assert_eq!(attributes.map_state, MapState::VIEWABLE);+ assert_eq!(attributes.your_event_mask, event_mask);+ Ok(window)+}++fn input_window(conn: &RustConnection, parent: Window, x: i16, y: i16) -> Result<Window> {+ let window = event_window(+ conn,+ parent,+ x,+ y,+ EventMask::KEY_PRESS | EventMask::KEY_RELEASE,+ )?;+ let attributes = conn.get_window_attributes(window)?.reply()?;assert!(attributes.your_event_mask.contains(EventMask::KEY_PRESS));assert!(attributes.your_event_mask.contains(EventMask::KEY_RELEASE));Ok(window)@@ -62,6 +81,84 @@ fn assert_key(conn: &RustConnection, event: &KeyPressEvent, keysym: u32) -> ResuOk(())}+fn assert_no_button_events(conn: &RustConnection, label: &str) -> Result<()> {+ let deadline = Instant::now() + Duration::from_millis(100);+ while Instant::now() < deadline {+ match conn.poll_for_event()? {+ Some(Event::ButtonPress(event)) => {+ bail!("{label} unexpectedly received ButtonPress: {event:?}")+ }+ Some(Event::ButtonRelease(event)) => {+ bail!("{label} unexpectedly received ButtonRelease: {event:?}")+ }+ Some(Event::Error(error)) => bail!("{label} X11 error: {error:?}"),+ _ => std::thread::sleep(Duration::from_millis(1)),+ }+ }+ Ok(())+}++#[test]+#[ignore = "requires an isolated X11 display"]+fn background_click_delivers_complete_sequence_to_press_recipient_without_focus_change(+) -> Result<()> {+ let (owner, screen) = x11rb::connect(None)?;+ let root = owner.setup().roots[screen].root;+ let target = event_window(&owner, root, 0, 0, EventMask::NO_EVENT)?;+ let leaf = event_window(&owner, target, 20, 20, EventMask::NO_EVENT)?;+ let sentinel = event_window(&owner, root, 400, 0, EventMask::NO_EVENT)?;++ let (press_observer, _) = x11rb::connect(None)?;+ press_observer+ .change_window_attributes(+ target,+ &ChangeWindowAttributesAux::new().event_mask(EventMask::BUTTON_PRESS),+ )?+ .check()?;+ let (release_observer, _) = x11rb::connect(None)?;+ release_observer+ .change_window_attributes(+ leaf,+ &ChangeWindowAttributesAux::new().event_mask(EventMask::BUTTON_RELEASE),+ )?+ .check()?;++ owner.set_input_focus(InputFocus::PARENT, sentinel, x11rb::CURRENT_TIME)?;+ assert_eq!(owner.get_input_focus()?.reply()?.focus, sentinel);++ send_click(u64::from(target), 30, 30, 1, 1)?;++ let deadline = Instant::now() + Duration::from_secs(2);+ let mut events = Vec::new();+ while events.len() < 2 {+ if Instant::now() >= deadline {+ bail!("received {} of 2 button events", events.len());+ }+ match press_observer.poll_for_event()? {+ Some(Event::ButtonPress(event)) => events.push((true, event)),+ Some(Event::ButtonRelease(event)) => events.push((false, event)),+ Some(Event::Error(error)) => bail!("X11 press observer error: {error:?}"),+ _ => std::thread::sleep(Duration::from_millis(1)),+ }+ }++ assert!(events[0].0 && !events[1].0);+ for (_, event) in &events {+ assert_eq!(event.event, target);+ assert_ne!(event.event, leaf);+ assert_eq!((event.event_x, event.event_y), (30, 30));+ assert_ne!(+ event.response_type & 0x80,+ 0,+ "expected XSendEvent delivery"+ );+ }+ assert_no_button_events(&release_observer, "release observer")?;+ assert_no_button_events(&owner, "owner")?;+ assert_eq!(owner.get_input_focus()?.reply()?.focus, sentinel);+ Ok(())+}+/// Run on a disposable display: these tests change keyboard focus./// xvfb-run -a cargo test -p platform-linux --test key_input_x11 -- --ignored --test-threads=1#[test]diff --git a/libs/cua-driver/rust/crates/platform-macos/src/input/mouse.rs b/libs/cua-driver/rust/crates/platform-macos/src/input/mouse.rsindex 8ace326f74..ceaa7d42ba 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/input/mouse.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/input/mouse.rs@@ -17,10 +17,11 @@ use core_graphics::{};use foreign_types::ForeignType;-#[derive(Clone, Copy)]+#[derive(Clone, Copy, Debug, Eq, PartialEq)]enum MousePostMode {Both,PublicOnly,+ HidOnly,}#[derive(Clone, Copy)]@@ -142,6 +143,22 @@ fn click_at_xy_desktop_inner(unsafe { CGAssociateMouseAndMouseCursorPosition(true) };std::thread::sleep(std::time::Duration::from_millis(40));let result = super::keyboard::with_global_modifier_keys(modifiers, |flags| {+ if !modifiers.is_empty() {+ // Prime AppKit's cursor-tracking state after the physical modifiers+ // are down so the modified mouseDown preserves the existing+ // selection. Leave ordinary clicks on their established event path.+ let moved = CGEvent::new_mouse_event(+ source.clone(),+ CGEventType::MouseMoved,+ point,+ CGMouseButton::Left,+ )+ .map_err(|_| anyhow::anyhow!("CGEvent::new_mouse_event(move) failed"))?;+ moved.set_flags(flags);+ moved.post(CGEventTapLocation::HID);+ std::thread::sleep(std::time::Duration::from_millis(12));+ }+for pair_index in 0..count.max(1) {let down = CGEvent::new_mouse_event(source.clone(), down_ty, point, btn).map_err(|_| anyhow::anyhow!("CGEvent::new_mouse_event(down) failed"))?;@@ -257,8 +274,9 @@ extern "C" {}/// Like `click_at_xy` but also targets a specific window. Foreground delivery-/// uses one public pid post; background delivery uses one SkyLight post with a-/// public fallback only when the private symbol is unavailable.+/// uses the supplied window-local point with one public pid post. Background+/// delivery keeps the translated screen point through the SkyLight route, with+/// a public fallback only when the private symbol is unavailable.// The flattened arguments mirror the native event fields used by existing callers.#[allow(clippy::too_many_arguments)]pub fn click_at_xy_with_window_local(@@ -410,8 +428,8 @@ pub fn prepare_background_pixel_click(pid: i32, wid: u32) -> bool {activated}-/// Post the stamped event half of the Chromium-compatible left-click recipe-/// matching Swift's `clickViaAuthSignedPost`.+/// Event kinds in the pure route plan for the Chromium-compatible background+/// left-click recipe.////// The sequence stays PID/window-routed throughout. The caller must first run/// [`prepare_background_pixel_click`] for background delivery, then re-pin any@@ -429,11 +447,110 @@ pub fn prepare_background_pixel_click(pid: i32, wid: u32) -> bool {/// - f40 = target pid (Chromium synthetic-event filter)/// - f51 / f91 / f92 = CGWindowID (window routing)/// - f58 = constant click-group ID across all events (gesture coalescing)-/// - `CGEventSetWindowLocation` per-event (window-local point)+/// - `CGEventSetWindowLocation` per-event (screen point for both routes)////// Uses the SkyLight route required by Chromium-compatible targets, with the/// public API only as a fallback when the private symbol is unavailable.-// The flattened arguments mirror the native event fields used by existing callers.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum ChromiumClickEventKind {+ Move,+ Down,+ Up,+}++#[derive(Clone, Copy, Debug, PartialEq)]+struct ChromiumClickRouteStep {+ kind: ChromiumClickEventKind,+ event_location: (f64, f64),+ skylight_window_location: (f64, f64),+ public_window_location: (f64, f64),+ click_state: i64,+ phase: i64,+ button_number: i64,+ subtype: i64,+ delay_after_ms: u64,+}++fn chromium_click_route_plan(+ screen_x: f64,+ screen_y: f64,+ win_local_x: f64,+ win_local_y: f64,+ count: usize,+) -> Vec<ChromiumClickRouteStep> {+ let screen_target = (screen_x, screen_y);+ let _ = (win_local_x, win_local_y);+ let off_screen = (-1.0, -1.0);+ let mut steps = vec![+ ChromiumClickRouteStep {+ kind: ChromiumClickEventKind::Move,+ event_location: screen_target,+ skylight_window_location: screen_target,+ public_window_location: screen_target,+ click_state: 0,+ phase: 2,+ button_number: 0,+ subtype: 3,+ delay_after_ms: 15,+ },+ ChromiumClickRouteStep {+ kind: ChromiumClickEventKind::Down,+ event_location: off_screen,+ skylight_window_location: off_screen,+ public_window_location: off_screen,+ click_state: 1,+ phase: 1,+ button_number: 0,+ subtype: 3,+ delay_after_ms: 1,+ },+ ChromiumClickRouteStep {+ kind: ChromiumClickEventKind::Up,+ event_location: off_screen,+ skylight_window_location: off_screen,+ public_window_location: off_screen,+ click_state: 1,+ phase: 2,+ button_number: 0,+ subtype: 3,+ delay_after_ms: 100,+ },+ ];++ let click_pairs = count.clamp(1, 2);+ for pair_index in 1..=click_pairs {+ let click_state = pair_index as i64;+ steps.push(ChromiumClickRouteStep {+ kind: ChromiumClickEventKind::Down,+ event_location: screen_target,+ skylight_window_location: screen_target,+ public_window_location: screen_target,+ click_state,+ phase: 3,+ button_number: 0,+ subtype: 3,+ delay_after_ms: 1,+ });+ steps.push(ChromiumClickRouteStep {+ kind: ChromiumClickEventKind::Up,+ event_location: screen_target,+ skylight_window_location: screen_target,+ public_window_location: screen_target,+ click_state,+ phase: 3,+ button_number: 0,+ subtype: 3,+ delay_after_ms: if pair_index < click_pairs { 80 } else { 0 },+ });+ }+ steps+}++/// Post the route plan for the Chromium-compatible background left-click+/// recipe. `CGEvent::new_mouse_event` starts with the screen-space location.+/// `CGEventSetWindowLocation` uses the screen point for both SkyLight and the+/// public PID fallback. macOS interprets the stamped location in screen space+/// even when the public route is used for a background process.#[allow(clippy::too_many_arguments)]pub fn click_at_xy_chromium(pid: i32,@@ -449,12 +566,8 @@ pub fn click_at_xy_chromium(let source = CGEventSource::new(CGEventSourceStateID::HIDSystemState).map_err(|_| anyhow::anyhow!("CGEventSource::new failed"))?;- let target = CGPoint::new(screen_x, screen_y);- let off_screen = CGPoint::new(-1.0, -1.0);- let win_local = (win_local_x, win_local_y);- let off_local = (-1.0_f64, -1.0_f64);+ let route_plan = chromium_click_route_plan(screen_x, screen_y, win_local_x, win_local_y, count);let flags = parse_modifier_flags(modifiers);- let click_pairs = count.clamp(1, 2);let window_id = wid as i64;// All 5 events share the same click-group ID so WindowServer / Chromium@@ -466,15 +579,15 @@ pub fn click_at_xy_chromium(// Stamp required fields onto a CGEvent. All captured values are Copy so// this closure is Fn (callable multiple times).- let stamp = |event: &CGEvent, local: (f64, f64), click_state: i64, phase: i64| {+ let stamp = |event: &CGEvent, step: &ChromiumClickRouteStep| {let ptr = event.as_ptr() as *mut std::ffi::c_void;let set = |f: u32, v: i64| {crate::input::skylight::set_integer_field(ptr, f, v);};- set(0, phase); // kCGMouseEventNumber (gesture phase)- set(1, click_state); // kCGMouseEventClickState- set(3, 0); // kCGMouseEventButtonNumber (left)- set(7, 3); // kCGMouseEventSubtype (NSEventSubtypeTouch)+ set(0, step.phase); // kCGMouseEventNumber (gesture phase)+ set(1, step.click_state); // kCGMouseEventClickState+ set(3, step.button_number); // kCGMouseEventButtonNumber (left)+ set(7, step.subtype); // kCGMouseEventSubtype (NSEventSubtypeTouch)set(40, pid as i64); // Chromium synthetic-event filterif window_id != 0 {set(51, window_id); // windowNumber (NSEvent bridge equivalent)@@ -482,86 +595,46 @@ pub fn click_at_xy_chromium(set(92, window_id); // kCGMouseEventWindowUnderMousePointerThatCanHandleThisEvent}set(58, click_group_id); // click-group ID (gesture coalescing)- crate::input::skylight::set_window_location(ptr, local.0, local.1);+ crate::input::skylight::set_window_location(+ ptr,+ step.skylight_window_location.0,+ step.skylight_window_location.1,+ );if flags != CGEventFlags::CGEventFlagNull {event.set_flags(flags);}};- let post = |event: &CGEvent| {+ let post = |event: &CGEvent, _step: &ChromiumClickRouteStep| {let ptr = event.as_ptr() as *mut std::ffi::c_void;if !crate::input::skylight::post_to_pid(pid as libc::pid_t, ptr, false) {event.post_to_pid(pid as libc::pid_t);}};- // Step 1: mouseMoved at target (phase=2, clickState=0).- let move_event = CGEvent::new_mouse_event(- source.clone(),- CGEventType::MouseMoved,- target,- CGMouseButton::Left,- )- .map_err(|_| anyhow::anyhow!("mouseMoved event creation failed"))?;- stamp(&move_event, win_local, 0, 2);- post(&move_event);- std::thread::sleep(std::time::Duration::from_millis(15));-- // Step 2: off-screen primer click — opens Chromium user-activation gate- // at an off-screen coordinate that can't hit any DOM element.- let primer_down = CGEvent::new_mouse_event(- source.clone(),- CGEventType::LeftMouseDown,- off_screen,- CGMouseButton::Left,- )- .map_err(|_| anyhow::anyhow!("primer down event creation failed"))?;- stamp(&primer_down, off_local, 1, 1);- post(&primer_down);- std::thread::sleep(std::time::Duration::from_millis(1));-- let primer_up = CGEvent::new_mouse_event(- source.clone(),- CGEventType::LeftMouseUp,- off_screen,- CGMouseButton::Left,- )- .map_err(|_| anyhow::anyhow!("primer up event creation failed"))?;- stamp(&primer_up, off_local, 1, 2);- post(&primer_up);- // ≥1 frame so Chromium sees primer + target as separate gestures, not run-on.- std::thread::sleep(std::time::Duration::from_millis(100));-- // Step 3: target click pair(s) with clickState stepped 1→N for double-click- // coalescing (Chromium renderer coalesces pairs into dblclick when state=1→2).- for pair_index in 1..=click_pairs {- let click_state = pair_index as i64;-- let down = CGEvent::new_mouse_event(- source.clone(),- CGEventType::LeftMouseDown,- target,- CGMouseButton::Left,- )- .map_err(|_| anyhow::anyhow!("target down event creation failed"))?;- stamp(&down, win_local, click_state, 3);- post(&down);- std::thread::sleep(std::time::Duration::from_millis(1));-- let up = CGEvent::new_mouse_event(+ for step in route_plan {+ let (event_type, error_label) = match step.kind {+ ChromiumClickEventKind::Move => (CGEventType::MouseMoved, "mouseMoved"),+ ChromiumClickEventKind::Down if step.phase == 1 => {+ (CGEventType::LeftMouseDown, "primer down")+ }+ ChromiumClickEventKind::Up if step.phase == 2 => {+ (CGEventType::LeftMouseUp, "primer up")+ }+ ChromiumClickEventKind::Down => (CGEventType::LeftMouseDown, "target down"),+ ChromiumClickEventKind::Up => (CGEventType::LeftMouseUp, "target up"),+ };+ let event = CGEvent::new_mouse_event(source.clone(),- CGEventType::LeftMouseUp,- target,+ event_type,+ CGPoint::new(step.event_location.0, step.event_location.1),CGMouseButton::Left,)- .map_err(|_| anyhow::anyhow!("target up event creation failed"))?;- stamp(&up, win_local, click_state, 3);- post(&up);-- if pair_index < click_pairs {- // ~80 ms between pairs — under the system double-click threshold,- // clear of coalescing back into pair N.- std::thread::sleep(std::time::Duration::from_millis(80));+ .map_err(|_| anyhow::anyhow!("{error_label} event creation failed"))?;+ stamp(&event, &step);+ post(&event, &step);+ if step.delay_after_ms > 0 {+ std::thread::sleep(std::time::Duration::from_millis(step.delay_after_ms));}}@@ -569,7 +642,7 @@ pub fn click_at_xy_chromium(}/// Press-drag-release gesture from `(from_x, from_y)` to `(to_x, to_y)` in-/// screen coordinates, posted to `pid`.+/// screen coordinates, addressed to `pid` and the optional exact window.////// `duration_ms` is the wall-clock budget for the drag path; `steps` is the/// number of intermediate `leftMouseDragged` events linearly interpolated@@ -592,7 +665,7 @@ pub fn drag_at_xy(steps: usize,modifiers: &[&str],button: DragButton,- foreground_release: bool,+ foreground_hid: bool,) -> anyhow::Result<()> {drag_at_xy_observed(pid,@@ -607,12 +680,16 @@ pub fn drag_at_xy(steps,modifiers,button,- foreground_release,+ foreground_hid,|_, _| {},)}-/// PID-routed drag with an observer called for every native pointer position.+/// Window drag with an observer called for every native pointer position.+///+/// Background delivery keeps the established PID-routed sequence. When+/// `foreground_hid` is true, the same stamped gesture is posted once per event+/// through the global HID queue while the hardware cursor follows the path.////// The cursor overlay uses this for the same reason as/// [`drag_at_xy_foreground_observed`]: the synthetic cursor should follow the@@ -631,15 +708,32 @@ pub fn drag_at_xy_observed<F>(steps: usize,modifiers: &[&str],button: DragButton,- foreground_release: bool,+ foreground_hid: bool,mut observe: F,) -> anyhow::Result<()>whereF: FnMut(f64, f64),{- use core_graphics::event::CGEventTapLocation;use std::time::{SystemTime, UNIX_EPOCH};+ if foreground_hid {+ return drag_at_xy_window_foreground_observed(+ pid,+ from_x,+ from_y,+ to_x,+ to_y,+ from_local,+ to_local,+ wid,+ duration_ms,+ steps,+ modifiers,+ button,+ observe,+ );+ }+let source = CGEventSource::new(CGEventSourceStateID::HIDSystemState).map_err(|_| anyhow::anyhow!("CGEventSource::new failed"))?;let flags = parse_modifier_flags(modifiers);@@ -685,8 +779,21 @@ whereduration_ms};- // MouseDown at start.+ // Prime the routed target's cursor-tracking state immediately before the+ // press, matching the click path's stamped mouseMoved + settle interval.let from_pt = CGPoint::new(from_x, from_y);+ post_mouse_moved_primer(+ pid,+ &source,+ from_pt,+ from_local,+ wid,+ click_group_id,+ MousePostMode::Both,+ );+ std::thread::sleep(std::time::Duration::from_millis(12));++ // MouseDown at start.let down = CGEvent::new_mouse_event(source.clone(), down_type, from_pt, cg_button).map_err(|_| anyhow::anyhow!("drag mouseDown failed"))?;if flags != CGEventFlags::CGEventFlagNull {@@ -737,12 +844,6 @@ whereup.set_flags(flags);}post_mouse_event(pid, &up, to_local, wid, click_group_id, 1, button_number, 0);- if foreground_release {- // A frontmost Chromium surface can consume PID-routed down/move- // events yet filter the synthetic release. Re-post only the release- // through the HID tap while the foreground assist still holds focus.- up.post(CGEventTapLocation::HID);- }// Chromium may process the final pointerup on the next run-loop turn. In// the foreground rung the caller restores the previous app immediately// after this function returns, so let the target consume the release and@@ -752,6 +853,175 @@ whereOk(())}+#[allow(clippy::too_many_arguments)]+fn post_drag_mouse_event(+ pid: i32,+ event_type: CGEventType,+ point: CGPoint,+ button: CGMouseButton,+ window_local: Option<(f64, f64)>,+ wid: Option<u32>,+ click_group_id: Option<i64>,+ click_state: i64,+ button_number: i64,+ subtype: i64,+ mode: MousePostMode,+ flags: CGEventFlags,+ error_context: &str,+) -> anyhow::Result<()> {+ debug_assert_eq!(mode, MousePostMode::HidOnly);+ let event = new_global_mouse_event(event_type, point, button)+ .map_err(|_| anyhow::anyhow!(error_context.to_owned()))?;+ if flags != CGEventFlags::CGEventFlagNull {+ event.set_flags(flags);+ }+ post_mouse_event_with_mode(+ pid,+ &event,+ window_local,+ wid,+ click_group_id,+ click_state,+ button_number,+ subtype,+ mode,+ );+ Ok(())+}++#[allow(clippy::too_many_arguments)]+fn drag_at_xy_window_foreground_observed<F>(+ pid: i32,+ from_x: f64,+ from_y: f64,+ to_x: f64,+ to_y: f64,+ from_local: Option<(f64, f64)>,+ to_local: Option<(f64, f64)>,+ wid: Option<u32>,+ duration_ms: u64,+ steps: usize,+ modifiers: &[&str],+ button: DragButton,+ mut observe: F,+) -> anyhow::Result<()>+where+ F: FnMut(f64, f64),+{+ use core_graphics::display::CGDisplay;+ use std::time::{SystemTime, UNIX_EPOCH};++ let (cg_button, down_type, dragged_type, up_type, button_number) = match button {+ DragButton::Left => (+ CGMouseButton::Left,+ CGEventType::LeftMouseDown,+ CGEventType::LeftMouseDragged,+ CGEventType::LeftMouseUp,+ 0,+ ),+ DragButton::Right => (+ CGMouseButton::Right,+ CGEventType::RightMouseDown,+ CGEventType::RightMouseDragged,+ CGEventType::RightMouseUp,+ 1,+ ),+ DragButton::Middle => (+ CGMouseButton::Center,+ CGEventType::OtherMouseDown,+ CGEventType::OtherMouseDragged,+ CGEventType::OtherMouseUp,+ 2,+ ),+ };+ let click_group_id = wid.map(|_| {+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap_or_default()+ .subsec_nanos() as i64+ });+ let steps = steps.max(1);+ let step_delay_ms = if steps > 1 {+ duration_ms / steps as u64+ } else {+ duration_ms+ };+ let events = foreground_drag_events(from_x, from_y, to_x, to_y, steps);++ super::keyboard::with_global_modifier_keys(modifiers, |flags| {+ for spec in events {+ let (event_type, click_state, event_button, event_button_number, subtype) = match spec+ .kind+ {+ ForegroundDragEventKind::Move => {+ (CGEventType::MouseMoved, 0, CGMouseButton::Left, 0, 3)+ }+ ForegroundDragEventKind::Down => (down_type, 1, cg_button, button_number, 0),+ ForegroundDragEventKind::Dragged => (dragged_type, 1, cg_button, button_number, 0),+ ForegroundDragEventKind::Up => (up_type, 1, cg_button, button_number, 0),+ };+ let local = from_local.zip(to_local).map(|((fx, fy), (tx, ty))| {+ (+ fx + (tx - fx) * spec.progress,+ fy + (ty - fy) * spec.progress,+ )+ });++ match spec.kind {+ ForegroundDragEventKind::Move => {+ let _ = CGDisplay::warp_mouse_cursor_position(spec.point);+ unsafe { CGAssociateMouseAndMouseCursorPosition(true) };+ std::thread::sleep(std::time::Duration::from_millis(40));+ }+ ForegroundDragEventKind::Dragged => {+ let _ = CGDisplay::warp_mouse_cursor_position(spec.point);+ }+ ForegroundDragEventKind::Up => {+ std::thread::sleep(std::time::Duration::from_millis(50));+ }+ ForegroundDragEventKind::Down => {}+ }++ post_drag_mouse_event(+ pid,+ event_type,+ spec.point,+ event_button,+ local,+ wid,+ click_group_id,+ click_state,+ event_button_number,+ subtype,+ MousePostMode::HidOnly,+ flags,+ "foreground drag event creation failed",+ )?;++ match spec.kind {+ ForegroundDragEventKind::Move => {+ std::thread::sleep(std::time::Duration::from_millis(12));+ }+ ForegroundDragEventKind::Down => {+ observe(spec.point.x, spec.point.y);+ std::thread::sleep(std::time::Duration::from_millis(16));+ }+ ForegroundDragEventKind::Dragged => {+ observe(spec.point.x, spec.point.y);+ if step_delay_ms > 0 {+ std::thread::sleep(std::time::Duration::from_millis(step_delay_ms));+ }+ }+ ForegroundDragEventKind::Up => {}+ }+ }+ Ok(())+ })?;++ std::thread::sleep(std::time::Duration::from_millis(100));+ Ok(())+}+/// Foreground drag through the global HID event tap.////// A frontmost Chromium/WebKit surface expects a real HID-origin gesture for@@ -806,9 +1076,6 @@ whereuse core_graphics::display::CGDisplay;use core_graphics::event::CGEventTapLocation;- let source = CGEventSource::new(CGEventSourceStateID::HIDSystemState)- .map_err(|_| anyhow::anyhow!("CGEventSource::new failed"))?;- let flags = parse_modifier_flags(modifiers);let (cg_button, down_type, dragged_type, up_type) = match button {DragButton::Left => (CGMouseButton::Left,@@ -829,6 +1096,7 @@ whereCGEventType::OtherMouseUp,),};+ let events = foreground_drag_events(from_x, from_y, to_x, to_y, steps);let steps = steps.max(1);let step_delay_ms = if steps > 1 {duration_ms / steps as u64@@ -836,8 +1104,6 @@ whereduration_ms};- let post = |event: &CGEvent| event.post(CGEventTapLocation::HID);-// Keep WindowServer's hardware cursor and event stream coupled. AppKit// hit-tests some pointer-capture surfaces against the actual cursor even// when the HID event carries an explicit location.@@ -846,56 +1112,43 @@ whereobserve(from_x, from_y);std::thread::sleep(std::time::Duration::from_millis(40));- // Prime the renderer's tracking state with a genuine HID mouse move.- if let Ok(move_event) = CGEvent::new_mouse_event(- source.clone(),- CGEventType::MouseMoved,- CGPoint::new(from_x, from_y),- cg_button,- ) {- post(&move_event);- }- std::thread::sleep(std::time::Duration::from_millis(30));-- let down = CGEvent::new_mouse_event(- source.clone(),- down_type,- CGPoint::new(from_x, from_y),- cg_button,- )- .map_err(|_| anyhow::anyhow!("foreground drag mouseDown failed"))?;- if flags != CGEventFlags::CGEventFlagNull {- down.set_flags(flags);- }- down.set_integer_value_field(core_graphics::event::EventField::MOUSE_EVENT_CLICK_STATE, 1);- down.post(CGEventTapLocation::HID);- std::thread::sleep(std::time::Duration::from_millis(16));-- for i in 1..=steps {- let t = i as f64 / steps as f64;- let x = from_x + (to_x - from_x) * t;- let y = from_y + (to_y - from_y) * t;- let event =- CGEvent::new_mouse_event(source.clone(), dragged_type, CGPoint::new(x, y), cg_button)- .map_err(|_| anyhow::anyhow!("foreground drag mouseDragged failed"))?;- if flags != CGEventFlags::CGEventFlagNull {+ super::keyboard::with_global_modifier_keys(modifiers, |flags| {+ for spec in events {+ let event_type = match spec.kind {+ ForegroundDragEventKind::Move => CGEventType::MouseMoved,+ ForegroundDragEventKind::Down => down_type,+ ForegroundDragEventKind::Dragged => dragged_type,+ ForegroundDragEventKind::Up => up_type,+ };+ // A null source matches macOS's established global mouse-controller+ // path. WindowServer then carries the pressed-button state from the+ // down through every dragged event instead of treating each event as+ // an independent HIDSystemState snapshot.+ let event =+ new_global_mouse_event(event_type, spec.point, cg_button).map_err(|_| {+ anyhow::anyhow!("foreground drag {:?} event creation failed", spec.kind)+ })?;event.set_flags(flags);+ event.post(CGEventTapLocation::HID);++ match spec.kind {+ ForegroundDragEventKind::Move => {+ std::thread::sleep(std::time::Duration::from_millis(30));+ }+ ForegroundDragEventKind::Down => {+ std::thread::sleep(std::time::Duration::from_millis(16));+ }+ ForegroundDragEventKind::Dragged => {+ observe(spec.point.x, spec.point.y);+ if step_delay_ms > 0 {+ std::thread::sleep(std::time::Duration::from_millis(step_delay_ms));+ }+ }+ ForegroundDragEventKind::Up => {}+ }}- event.set_integer_value_field(core_graphics::event::EventField::MOUSE_EVENT_CLICK_STATE, 1);- post(&event);- observe(x, y);- if step_delay_ms > 0 {- std::thread::sleep(std::time::Duration::from_millis(step_delay_ms));- }- }-- let up = CGEvent::new_mouse_event(source, up_type, CGPoint::new(to_x, to_y), cg_button)- .map_err(|_| anyhow::anyhow!("foreground drag mouseUp failed"))?;- if flags != CGEventFlags::CGEventFlagNull {- up.set_flags(flags);- }- up.set_integer_value_field(core_graphics::event::EventField::MOUSE_EVENT_CLICK_STATE, 1);- post(&up);+ Ok(())+ })?;// The foreground wrapper restores the previous app immediately after this// function returns. Let the target's run loop consume the queued HID// gesture, including pointer-capture release, before that restore happens.@@ -903,6 +1156,71 @@ whereOk(())}+#[derive(Clone, Copy, Debug, Eq, PartialEq)]+enum ForegroundDragEventKind {+ Move,+ Down,+ Dragged,+ Up,+}++#[derive(Clone, Copy, Debug)]+struct ForegroundDragEvent {+ kind: ForegroundDragEventKind,+ point: CGPoint,+ progress: f64,+}++fn foreground_drag_events(+ from_x: f64,+ from_y: f64,+ to_x: f64,+ to_y: f64,+ steps: usize,+) -> Vec<ForegroundDragEvent> {+ let steps = steps.max(1);+ let mut events = Vec::with_capacity(steps + 3);+ let from = CGPoint::new(from_x, from_y);+ events.push(ForegroundDragEvent {+ kind: ForegroundDragEventKind::Move,+ point: from,+ progress: 0.0,+ });+ events.push(ForegroundDragEvent {+ kind: ForegroundDragEventKind::Down,+ point: from,+ progress: 0.0,+ });+ for i in 1..=steps {+ let t = i as f64 / steps as f64;+ events.push(ForegroundDragEvent {+ kind: ForegroundDragEventKind::Dragged,+ point: CGPoint::new(from_x + (to_x - from_x) * t, from_y + (to_y - from_y) * t),+ progress: t,+ });+ }+ events.push(ForegroundDragEvent {+ kind: ForegroundDragEventKind::Up,+ point: CGPoint::new(to_x, to_y),+ progress: 1.0,+ });+ events+}++fn new_global_mouse_event(+ event_type: CGEventType,+ point: CGPoint,+ button: CGMouseButton,+) -> Result<CGEvent, ()> {+ let event_ref =+ unsafe { CGEventCreateMouseEvent(std::ptr::null_mut(), event_type, point, button) };+ if event_ref.is_null() {+ Err(())+ } else {+ Ok(unsafe { CGEvent::from_ptr(event_ref) })+ }+}+/// Mouse button for drag gestures.#[derive(Clone, Copy, Debug)]pub enum DragButton {@@ -1158,6 +1476,7 @@ fn post_mouse_event_with_mode(event.post_to_pid(pid as libc::pid_t);}MousePostMode::PublicOnly => event.post_to_pid(pid as libc::pid_t),+ MousePostMode::HidOnly => event.post(core_graphics::event::CGEventTapLocation::HID),}}@@ -1303,6 +1622,15 @@ pub fn scroll_wheel_at_xy(}extern "C" {+ /// Quartz mouse constructor with a null source, matching established+ /// foreground controller libraries and the global scroll path above.+ fn CGEventCreateMouseEvent(+ source: core_graphics::sys::CGEventSourceRef,+ event_type: core_graphics::event::CGEventType,+ point: CGPoint,+ button: core_graphics::event::CGMouseButton,+ ) -> core_graphics::sys::CGEventRef;+/// `void CGEventSetLocation(CGEventRef event, CGPoint location)`.////// `CGPoint { double x, double y }` is classified as two FP eightbytes on@@ -1325,3 +1653,206 @@ fn parse_modifier_flags(modifiers: &[&str]) -> CGEventFlags {}flags}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn capture_bound_background_route_preserves_nonzero_origin_hit() {+ let frame = crate::tools::px_frame::WindowPxFrame {+ bounds: crate::windows::WindowBounds {+ x: 170.0,+ y: 194.0,+ width: 760.0,+ height: 460.0,+ },+ scale: 2.0,+ };+ let capture_local = (394.0, 310.0);+ let admitted_native = (capture_local.0 * frame.scale, capture_local.1 * frame.scale);+ let (screen_x, screen_y, local_x, local_y) =+ frame.to_screen(admitted_native.0, admitted_native.1);+ assert_eq!((screen_x, screen_y), (564.0, 504.0));+ assert_eq!((local_x, local_y), capture_local);++ let plan = chromium_click_route_plan(screen_x, screen_y, local_x, local_y, 1);+ assert_eq!(+ plan,+ vec![+ ChromiumClickRouteStep {+ kind: ChromiumClickEventKind::Move,+ event_location: (564.0, 504.0),+ skylight_window_location: (564.0, 504.0),+ public_window_location: (564.0, 504.0),+ click_state: 0,+ phase: 2,+ button_number: 0,+ subtype: 3,+ delay_after_ms: 15,+ },+ ChromiumClickRouteStep {+ kind: ChromiumClickEventKind::Down,+ event_location: (-1.0, -1.0),+ skylight_window_location: (-1.0, -1.0),+ public_window_location: (-1.0, -1.0),+ click_state: 1,+ phase: 1,+ button_number: 0,+ subtype: 3,+ delay_after_ms: 1,+ },+ ChromiumClickRouteStep {+ kind: ChromiumClickEventKind::Up,+ event_location: (-1.0, -1.0),+ skylight_window_location: (-1.0, -1.0),+ public_window_location: (-1.0, -1.0),+ click_state: 1,+ phase: 2,+ button_number: 0,+ subtype: 3,+ delay_after_ms: 100,+ },+ ChromiumClickRouteStep {+ kind: ChromiumClickEventKind::Down,+ event_location: (564.0, 504.0),+ skylight_window_location: (564.0, 504.0),+ public_window_location: (564.0, 504.0),+ click_state: 1,+ phase: 3,+ button_number: 0,+ subtype: 3,+ delay_after_ms: 1,+ },+ ChromiumClickRouteStep {+ kind: ChromiumClickEventKind::Up,+ event_location: (564.0, 504.0),+ skylight_window_location: (564.0, 504.0),+ public_window_location: (564.0, 504.0),+ click_state: 1,+ phase: 3,+ button_number: 0,+ subtype: 3,+ delay_after_ms: 0,+ },+ ]+ );++ let screen_to_canvas = (-frame.bounds.x, -frame.bounds.y);+ let unconverted_journal_point = (+ capture_local.0 + screen_to_canvas.0,+ capture_local.1 + screen_to_canvas.1,+ );+ assert_eq!(unconverted_journal_point, (224.0, 116.0));+ assert!(!(292.0..=496.0).contains(&unconverted_journal_point.0));++ let delivered = plan+ .iter()+ .find(|step| step.kind == ChromiumClickEventKind::Down && step.phase == 3)+ .expect("target mouse-down step");+ assert_eq!(delivered.event_location, (564.0, 504.0));+ assert_eq!(delivered.skylight_window_location, (564.0, 504.0));+ assert_eq!(delivered.public_window_location, (564.0, 504.0));+ let skylight_journal_point = (+ delivered.skylight_window_location.0 + screen_to_canvas.0,+ delivered.skylight_window_location.1 + screen_to_canvas.1,+ );+ assert_eq!(skylight_journal_point, capture_local);+ assert!((292.0..=496.0).contains(&skylight_journal_point.0));+ assert!((132.0..=310.0).contains(&skylight_journal_point.1));+ }++ #[test]+ fn foreground_drag_plan_is_one_coherent_gesture() {+ let events = foreground_drag_events(10.0, 20.0, 40.0, 80.0, 3);+ let kinds: Vec<_> = events.iter().map(|event| event.kind).collect();+ assert_eq!(+ kinds,+ [+ ForegroundDragEventKind::Move,+ ForegroundDragEventKind::Down,+ ForegroundDragEventKind::Dragged,+ ForegroundDragEventKind::Dragged,+ ForegroundDragEventKind::Dragged,+ ForegroundDragEventKind::Up,+ ]+ );+ let points: Vec<_> = events+ .iter()+ .map(|event| (event.point.x, event.point.y))+ .collect();+ assert_eq!(+ points,+ [+ (10.0, 20.0),+ (10.0, 20.0),+ (20.0, 40.0),+ (30.0, 60.0),+ (40.0, 80.0),+ (40.0, 80.0),+ ]+ );+ assert_eq!(+ events+ .iter()+ .filter(|event| event.kind == ForegroundDragEventKind::Up)+ .count(),+ 1,+ "the HID gesture must release exactly once"+ );+ let cursor_plan: Vec<_> = events+ .iter()+ .filter(|event| {+ matches!(+ event.kind,+ ForegroundDragEventKind::Move | ForegroundDragEventKind::Dragged+ )+ })+ .map(|event| (event.point.x, event.point.y))+ .collect();+ assert_eq!(+ cursor_plan,+ [(10.0, 20.0), (20.0, 40.0), (30.0, 60.0), (40.0, 80.0)]+ );+ }++ #[test]+ fn hid_only_post_mode_is_distinct_from_routed_background() {+ assert_ne!(MousePostMode::Both, MousePostMode::HidOnly);+ }++ #[test]+ fn foreground_drag_plan_keeps_a_drag_sample_for_zero_steps() {+ let events = foreground_drag_events(1.0, 2.0, 3.0, 4.0, 0);+ assert_eq!(events.len(), 4);+ assert_eq!(events[2].kind, ForegroundDragEventKind::Dragged);+ assert_eq!((events[2].point.x, events[2].point.y), (3.0, 4.0));+ }++ #[test]+ fn global_drag_events_use_hardware_like_source_and_button_fields() {+ use core_graphics::event::EventField;++ let point = CGPoint::new(10.0, 20.0);+ let cases = [+ (CGEventType::LeftMouseDown, 1, 1.0),+ (CGEventType::LeftMouseDragged, 1, 1.0),+ (CGEventType::LeftMouseUp, 0, 0.0),+ ];+ for (event_type, click_state, pressure) in cases {+ let event = new_global_mouse_event(event_type, point, CGMouseButton::Left).unwrap();+ assert_eq!(+ event.get_integer_value_field(EventField::EVENT_SOURCE_STATE_ID),+ CGEventSourceStateID::CombinedSessionState as i64+ );+ assert_eq!(+ event.get_integer_value_field(EventField::MOUSE_EVENT_CLICK_STATE),+ click_state+ );+ assert_eq!(+ event.get_double_value_field(EventField::MOUSE_EVENT_PRESSURE),+ pressure+ );+ }+ }+}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/input/skylight.rs b/libs/cua-driver/rust/crates/platform-macos/src/input/skylight.rsindex a657ced2b2..6fd7c4c647 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/input/skylight.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/input/skylight.rs@@ -351,8 +351,10 @@ pub(super) fn post_to_pid(pid: pid_t, event_ptr: *mut c_void, attach_auth_messagtrue}-/// Stamp a window-local `(x, y)` point onto `event_ptr` via the private-/// `CGEventSetWindowLocation` SPI. Returns `true` when the SPI resolved.+/// Stamp the event's screen-space `(x, y)` point via+/// `CGEventSetWindowLocation`. Both the SkyLight and public PID routes receive+/// this screen-space value; WindowServer derives the receiving window's local+/// point during routing. Returns `true` when the SPI resolved.pub(super) fn set_window_location(event_ptr: *mut c_void, x: f64, y: f64) -> bool {match set_window_loc_fn() {Some(f) => {diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/capture_binding.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/capture_binding.rsnew file mode 100644index 0000000000..b9ec3f61e7--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/capture_binding.rs@@ -0,0 +1,496 @@+//! Thin macOS adapter over the runtime-owned immutable capture service.+//!+//! The common runtime owns registry and session generations plus atomic action+//! admission. Keep its facade calls here so signature changes stay isolated.++use cua_driver_core::{+ capture_runtime::{+ CaptureActionError, CaptureActionRequest, CaptureLookupError, CapturePublication,+ CaptureService, CaptureTarget, EncodedScreenshotDimensions, NativeActionDimensions,+ ScreenshotToActionTransform,+ },+ protocol::ToolResult,+};+use std::sync::Arc;++pub(crate) struct MacCaptureBindings {+ service: Arc<CaptureService>,+}++impl MacCaptureBindings {+ pub(super) fn new(service: Arc<CaptureService>) -> Self {+ Self { service }+ }++ pub(super) fn publish_window(+ &self,+ args: &serde_json::Value,+ pid: i32,+ window_id: u32,+ png_bytes: Vec<u8>,+ encoded_dimensions: (u32, u32),+ native_dimensions: (u32, u32),+ ) -> Result<String, ToolResult> {+ let target = CaptureTarget::Window {+ pid: u32::try_from(pid)+ .map_err(|_| capture_error("invalid_target", "pid is negative"))?,+ window_id: u64::from(window_id),+ };+ self.publish(+ args,+ target,+ png_bytes,+ encoded_dimensions,+ native_dimensions,+ )+ }++ pub(super) fn publish_desktop(+ &self,+ args: &serde_json::Value,+ png_bytes: Vec<u8>,+ encoded_dimensions: (u32, u32),+ native_dimensions: (u32, u32),+ ) -> Result<String, ToolResult> {+ self.publish(+ args,+ CaptureTarget::PrimaryDesktop,+ png_bytes,+ encoded_dimensions,+ native_dimensions,+ )+ }++ fn publish(+ &self,+ args: &serde_json::Value,+ target: CaptureTarget,+ png_bytes: Vec<u8>,+ encoded_dimensions: (u32, u32),+ native_dimensions: (u32, u32),+ ) -> Result<String, ToolResult> {+ let binding = self+ .service+ .binding_from_args(args)+ .map_err(|error| capture_error("capture_binding_failed", error))?;+ let encoded = EncodedScreenshotDimensions::new(encoded_dimensions.0, encoded_dimensions.1)+ .map_err(|error| capture_error("capture_publication_failed", error))?;+ let native = NativeActionDimensions::new(native_dimensions.0, native_dimensions.1)+ .map_err(|error| capture_error("capture_publication_failed", error))?;+ let transform = scale_transform(encoded_dimensions, native_dimensions)?;+ self.service+ .publish(CapturePublication {+ png_bytes,+ target,+ encoded_dimensions: encoded,+ native_action_dimensions: native,+ screenshot_to_action: transform,+ session_id: Arc::<str>::from(binding.session_id()),+ session_generation: binding.session_generation(),+ })+ .map(|capture_id| capture_id.to_string())+ .map_err(|error| capture_error("capture_publication_failed", error))+ }++ pub(super) fn admit_window_click(+ &self,+ capture_id: &str,+ args: &serde_json::Value,+ pid: i32,+ window_id: u32,+ x: f64,+ y: f64,+ ) -> Result<(f64, f64), ToolResult> {+ let target = CaptureTarget::Window {+ pid: u32::try_from(pid)+ .map_err(|_| capture_error("invalid_target", "pid is negative"))?,+ window_id: u64::from(window_id),+ };+ self.admit(capture_id, args, target, x, y)+ }++ pub(super) fn admit_desktop_click(+ &self,+ capture_id: &str,+ args: &serde_json::Value,+ x: f64,+ y: f64,+ ) -> Result<(f64, f64), ToolResult> {+ self.admit(capture_id, args, CaptureTarget::PrimaryDesktop, x, y)+ }++ fn admit(+ &self,+ capture_id: &str,+ args: &serde_json::Value,+ target: CaptureTarget,+ x: f64,+ y: f64,+ ) -> Result<(f64, f64), ToolResult> {+ let current_native_action_dimensions = live_action_dimensions(&target)?;+ self.admit_with_live_dimensions(+ capture_id,+ args,+ target,+ current_native_action_dimensions,+ x,+ y,+ )+ }++ fn admit_with_live_dimensions(+ &self,+ capture_id: &str,+ args: &serde_json::Value,+ target: CaptureTarget,+ current_native_action_dimensions: NativeActionDimensions,+ x: f64,+ y: f64,+ ) -> Result<(f64, f64), ToolResult> {+ let binding = self+ .service+ .binding_from_args(args)+ .map_err(|error| capture_error("capture_binding_failed", error))?;+ let parsed = capture_id+ .parse()+ .map_err(|error| capture_error("capture_id_invalid", error))?;+ self.service+ .admit_action(CaptureActionRequest {+ capture_id: parsed,+ binding,+ target,+ current_native_action_dimensions,+ screenshot_x: x,+ screenshot_y: y,+ })+ .map(|admission| (admission.action_x, admission.action_y))+ .map_err(|error| capture_error(action_error_code(&error), error))+ }++ pub(super) fn retire_session(&self, session_id: &str) {+ self.service.retire_session_id(session_id);+ }++ pub(super) fn retire_runtime(&self) {+ self.service.retire_runtime();+ }+}++fn live_action_dimensions(target: &CaptureTarget) -> Result<NativeActionDimensions, ToolResult> {+ let (width, height) = match target {+ CaptureTarget::Window { pid, window_id } => {+ let pid = i32::try_from(*pid)+ .map_err(|_| capture_error("capture_target_mismatch", "pid is out of range"))?;+ let window_id = u32::try_from(*window_id).map_err(|_| {+ capture_error("capture_target_mismatch", "window id is out of range")+ })?;+ if crate::windows::resolve_window_owner(pid, window_id)+ != crate::windows::WindowOwner::SamePid+ {+ return Err(capture_error(+ "capture_target_mismatch",+ "native window identity changed after capture",+ ));+ }+ let png = crate::capture::screenshot_window_bytes(window_id).map_err(|error| {+ capture_error(+ "capture_target_mismatch",+ format!("live window capture failed: {error}"),+ )+ })?;+ crate::capture::png_dimensions(&png).map_err(|error| {+ capture_error(+ "capture_target_mismatch",+ format!("live window dimensions failed: {error}"),+ )+ })?+ }+ CaptureTarget::PrimaryDesktop => {+ let (width, height, _) =+ super::get_screen_size::main_screen_size().ok_or_else(|| {+ capture_error("capture_target_mismatch", "primary display is unavailable")+ })?;+ (+ u32::try_from(width).map_err(|_| {+ capture_error("capture_target_mismatch", "display width is out of range")+ })?,+ u32::try_from(height).map_err(|_| {+ capture_error("capture_target_mismatch", "display height is out of range")+ })?,+ )+ }+ };+ NativeActionDimensions::new(width, height)+ .map_err(|error| capture_error("capture_target_mismatch", error))+}++fn scale_transform(+ encoded: (u32, u32),+ native: (u32, u32),+) -> Result<ScreenshotToActionTransform, ToolResult> {+ if encoded.0 == 0 || encoded.1 == 0 || native.0 == 0 || native.1 == 0 {+ return Err(capture_error(+ "capture_publication_failed",+ "capture dimensions must be non-zero",+ ));+ }+ ScreenshotToActionTransform::new(+ f64::from(native.0) / f64::from(encoded.0),+ 0.0,+ 0.0,+ f64::from(native.1) / f64::from(encoded.1),+ 0.0,+ 0.0,+ )+ .map_err(|error| capture_error("capture_publication_failed", error))+}++fn capture_error(code: &str, error: impl std::fmt::Display) -> ToolResult {+ ToolResult::error(format!(+ "capture binding failed: {error}. Not dispatching click."+ ))+ .with_structured(serde_json::json!({+ "code": code,+ "effect": "refused"+ }))+}++fn action_error_code(error: &CaptureActionError) -> &'static str {+ match error {+ CaptureActionError::Lookup(CaptureLookupError::Unknown | CaptureLookupError::Expired) => {+ "capture_stale"+ }+ CaptureActionError::Lookup(CaptureLookupError::GenerationMismatch) => {+ "capture_generation_mismatch"+ }+ CaptureActionError::Lookup(CaptureLookupError::TargetMismatch) => "capture_target_mismatch",+ CaptureActionError::InvalidScreenshotPoint | CaptureActionError::InvalidMappedPoint => {+ "capture_coordinate_invalid"+ }+ CaptureActionError::NativeActionFrameMismatch => "capture_frame_mismatch",+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn args(session: &str) -> serde_json::Value {+ serde_json::json!({ "_session_id": session })+ }++ fn png(width: u32, height: u32) -> Vec<u8> {+ let image = image::RgbaImage::from_pixel(width, height, image::Rgba([1, 2, 3, 255]));+ let mut bytes = std::io::Cursor::new(Vec::new());+ image::DynamicImage::ImageRgba8(image)+ .write_to(&mut bytes, image::ImageFormat::Png)+ .unwrap();+ bytes.into_inner()+ }++ fn admit_desktop(+ bindings: &MacCaptureBindings,+ capture_id: &str,+ args: &serde_json::Value,+ x: f64,+ y: f64,+ native: (u32, u32),+ ) -> Result<(f64, f64), ToolResult> {+ bindings.admit_with_live_dimensions(+ capture_id,+ args,+ CaptureTarget::PrimaryDesktop,+ NativeActionDimensions::new(native.0, native.1).unwrap(),+ x,+ y,+ )+ }++ fn admit_window(+ bindings: &MacCaptureBindings,+ capture_id: &str,+ args: &serde_json::Value,+ pid: u32,+ window_id: u64,+ x: f64,+ y: f64,+ native: (u32, u32),+ ) -> Result<(f64, f64), ToolResult> {+ bindings.admit_with_live_dimensions(+ capture_id,+ args,+ CaptureTarget::Window { pid, window_id },+ NativeActionDimensions::new(native.0, native.1).unwrap(),+ x,+ y,+ )+ }++ #[test]+ fn resize_transform_preserves_fractional_coordinate_mapping() {+ let transform = scale_transform((800, 451), (1600, 902)).unwrap();+ assert_eq!(transform.apply(123.25, 17.75), (246.5, 35.5));+ }++ #[test]+ fn independent_axes_preserve_rounded_png_dimensions() {+ let transform = scale_transform((801, 450), (1600, 900)).unwrap();+ let (x, y) = transform.apply(800.0, 449.0);+ assert!((x - 1598.0024968789014).abs() < 1e-9);+ assert_eq!(y, 898.0);+ }++ #[test]+ fn zero_sized_capture_is_refused() {+ let error = scale_transform((0, 100), (100, 100)).unwrap_err();+ assert_eq!(+ error.structured_content.unwrap()["code"],+ "capture_publication_failed"+ );+ }++ #[test]+ fn action_errors_keep_stale_mismatch_and_coordinate_failures_distinct() {+ assert_eq!(+ action_error_code(&CaptureActionError::Lookup(CaptureLookupError::Expired)),+ "capture_stale"+ );+ assert_eq!(+ action_error_code(&CaptureActionError::Lookup(+ CaptureLookupError::GenerationMismatch+ )),+ "capture_generation_mismatch"+ );+ assert_eq!(+ action_error_code(&CaptureActionError::Lookup(+ CaptureLookupError::TargetMismatch+ )),+ "capture_target_mismatch"+ );+ assert_eq!(+ action_error_code(&CaptureActionError::InvalidScreenshotPoint),+ "capture_coordinate_invalid"+ );+ }++ #[test]+ fn publication_retains_exact_png_and_content_digest() {+ let service = Arc::new(CaptureService::default());+ let bindings = MacCaptureBindings::new(service.clone());+ let args = args("digest-session");+ let png = png(2, 2);+ let capture_id = bindings+ .publish_desktop(&args, png.clone(), (2, 2), (2, 2))+ .unwrap();+ let binding = service.binding_from_args(&args).unwrap();+ let capture = service+ .read_for_perception(capture_id.parse().unwrap(), &binding)+ .unwrap();+ assert_eq!(&*capture.png_bytes(), png.as_slice());+ assert_eq!(capture.digest().hex().len(), 64);+ }++ #[test]+ fn mismatch_and_invalid_coordinate_refuse_without_consuming_or_dispatching() {+ let service = Arc::new(CaptureService::default());+ let bindings = MacCaptureBindings::new(service);+ let args = args("click-session");+ let capture_id = bindings+ .publish_desktop(&args, png(4, 4), (4, 4), (2, 2))+ .unwrap();+ let mut dispatched = false;+ let mismatch = admit_window(&bindings, &capture_id, &args, 1, 1, 1.0, 1.0, (2, 2));+ if mismatch.is_ok() {+ dispatched = true;+ }+ assert!(!dispatched);+ assert_eq!(+ mismatch.unwrap_err().structured_content.unwrap()["code"],+ "capture_target_mismatch"+ );++ let invalid = admit_desktop(&bindings, &capture_id, &args, 5.0, 1.0, (2, 2));+ assert_eq!(+ invalid.unwrap_err().structured_content.unwrap()["code"],+ "capture_coordinate_invalid"+ );++ assert_eq!(+ admit_desktop(&bindings, &capture_id, &args, 2.0, 2.0, (2, 2)).unwrap(),+ (1.0, 1.0)+ );+ assert_eq!(+ admit_desktop(&bindings, &capture_id, &args, 2.0, 2.0, (2, 2))+ .unwrap_err()+ .structured_content+ .unwrap()["code"],+ "capture_stale"+ );+ }++ #[test]+ fn another_session_generation_cannot_admit_the_capture() {+ let service = Arc::new(CaptureService::default());+ let bindings = MacCaptureBindings::new(service);+ let owner = args("owner-session");+ let capture_id = bindings+ .publish_desktop(&owner, png(2, 2), (2, 2), (2, 2))+ .unwrap();+ let error = admit_desktop(+ &bindings,+ &capture_id,+ &args("other-session"),+ 1.0,+ 1.0,+ (2, 2),+ )+ .unwrap_err();+ assert_eq!(+ error.structured_content.unwrap()["code"],+ "capture_generation_mismatch"+ );+ }++ #[test]+ fn session_retirement_makes_published_capture_stale() {+ let service = Arc::new(CaptureService::default());+ let bindings = MacCaptureBindings::new(service);+ let args = args("retired-session");+ let capture_id = bindings+ .publish_desktop(&args, png(2, 2), (2, 2), (2, 2))+ .unwrap();+ bindings.retire_session("retired-session");+ let error = admit_desktop(&bindings, &capture_id, &args, 1.0, 1.0, (2, 2)).unwrap_err();+ assert_eq!(error.structured_content.unwrap()["code"], "capture_stale");+ }++ #[test]+ fn live_resize_refuses_before_dispatch_and_preserves_capture() {+ let service = Arc::new(CaptureService::default());+ let bindings = MacCaptureBindings::new(service.clone());+ let args = args("resize-session");+ let capture_id = bindings+ .publish_window(&args, 8, 13, png(4, 3), (4, 3), (8, 6))+ .unwrap();+ let mut dispatches = 0;+ let refusal = admit_window(&bindings, &capture_id, &args, 8, 13, 1.25, 1.5, (9, 6));+ if refusal.is_ok() {+ dispatches += 1;+ }+ assert_eq!(dispatches, 0);+ assert_eq!(+ refusal.unwrap_err().structured_content.unwrap()["code"],+ "capture_frame_mismatch"+ );+ assert_eq!(+ admit_window(&bindings, &capture_id, &args, 8, 13, 1.25, 1.5, (8, 6)).unwrap(),+ (2.5, 3.0)+ );+ assert!(service+ .read_for_perception(+ service.parse_capture_id(&capture_id).unwrap(),+ &service.binding_from_args(&args).unwrap()+ )+ .is_err());+ }+}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rsindex af99862cee..628792c3e1 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/click.rs@@ -25,12 +25,13 @@ use std::sync::Arc;use crate::apps;use crate::ax::bindings::{- copy_action_names, copy_children, copy_string_attr, element_at_screen_position,- element_screen_rect, kAXErrorSuccess, AXUIElementPerformAction, AXUIElementRef,+ copy_action_names, copy_bool_attr, copy_children, copy_element_attr, copy_string_attr,+ element_at_screen_position, element_screen_rect, kAXErrorSuccess, AXUIElementPerformAction,+ AXUIElementRef,};use crate::focus_guard;use crate::window_change_detector::WindowChangeDetector;-use core_foundation::base::{CFRelease, TCFType};+use core_foundation::base::{CFRelease, CFTypeRef, TCFType};use super::ToolState;@@ -66,6 +67,55 @@ struct SelectionPixelTarget {window_y: f64,}+fn selection_pixel_target(+ screen_center: (f64, f64),+ window_origin: (f64, f64),+) -> SelectionPixelTarget {+ SelectionPixelTarget {+ screen_x: screen_center.0,+ screen_y: screen_center.1,+ window_x: screen_center.0 - window_origin.0,+ window_y: screen_center.1 - window_origin.1,+ }+}++/// Resolve the selectable row/item rather than an actionable child such as a+/// selectable NSTextField. A modified click on the child can be consumed as a+/// text interaction without ever reaching the collection's selection model.+fn nearest_selectable_container_center(element_ptr: usize) -> Option<(f64, f64)> {+ let mut current = element_ptr as AXUIElementRef;+ let mut owns_current = false;++ for _ in 0..8 {+ let role = unsafe { copy_string_attr(current, "AXRole") }.unwrap_or_default();+ if matches!(role.as_str(), "AXRow" | "AXCell" | "AXListItem" | "AXImage")+ && unsafe { copy_bool_attr(current, "AXSelected") }.is_some()+ {+ let center = unsafe { element_screen_rect(current) }+ .map(|rect| (rect[0] + rect[2] / 2.0, rect[1] + rect[3] / 2.0));+ if owns_current {+ unsafe { CFRelease(current as CFTypeRef) };+ }+ return center;+ }++ let parent = unsafe { copy_element_attr(current, "AXParent") };+ if owns_current {+ unsafe { CFRelease(current as CFTypeRef) };+ }+ let Some(parent) = parent else {+ return None;+ };+ current = parent;+ owns_current = true;+ }++ if owns_current {+ unsafe { CFRelease(current as CFTypeRef) };+ }+ None+}+fn selection_readback_confirms(before: bool,after: bool,@@ -165,6 +215,7 @@ fn def() -> &'static ToolDef {"element_index": cua_driver_core::tool_schema::element_index_schema(),"element_token": cua_driver_core::tool_schema::element_token_schema(),"snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),+ "capture_id": { "type": "string", "description": "Optional immutable source capture ID returned by get_window_state or get_desktop_state. With x,y, Driver atomically admits and consumes that exact capture before dispatch; stale, mismatched, or out-of-bounds captures are refused without fallback." },"x": { "type": "number", "description": "X in screenshot pixels. A window target uses the get_window_state PNG; a desktop target uses the native get_desktop_state PNG. The driver reverses Retina backing scale and any window-image downscale." },"y": { "type": "number", "description": "Y in screenshot pixels from the image selected by target." },"action": { "type": "string", "description": "AX action: press, show_menu, pick, confirm, cancel, open." },@@ -227,6 +278,11 @@ impl Tool for ClickTool {let has_window_id = args.get("window_id").map(|v| !v.is_null()).unwrap_or(false);let has_xy = args.get("x").map(|v| v.is_number()).unwrap_or(false)&& args.get("y").map(|v| v.is_number()).unwrap_or(false);+ let capture_id = args.opt_str("capture_id");+ if capture_id.is_some() && !has_xy {+ return ToolResult::error("click.capture_id requires pixel coordinates x and y.")+ .with_structured(serde_json::json!({ "code": "invalid_arguments" }));+ }if has_xy && !has_pid && !has_window_id {// `scope` is a per-call param now (default "window"); pass// scope="desktop" to enable screen-absolute clicks.@@ -266,22 +322,32 @@ impl Tool for ClickTool {// screenshot width / logical screen width. This is robust even when// CGDisplayPixelsWide under-reports the backing scale (it returns the// scaled-mode point width on some Retina configs → a bogus 1.0).- let desktop_ratio = tokio::task::spawn_blocking(|| {- let logical_w =- super::get_screen_size::main_screen_size().map(|(w, _, _)| w as f64);- let shot_w = crate::capture::screenshot_display_bytes()- .ok()- .and_then(|png| crate::capture::png_dimensions(&png).ok())- .map(|(w, _)| w as f64);- match (shot_w, logical_w) {- (Some(sw), Some(lw)) if lw > 0.0 && sw > lw => sw / lw,- _ => 1.0,+ let (sx, sy) = if let Some(ref capture_id) = capture_id {+ match self+ .state+ .capture_bindings+ .admit_desktop_click(capture_id, &args, sx_shot, sy_shot)+ {+ Ok(point) => point,+ Err(refusal) => return refusal,}- })- .await- .unwrap_or(1.0);- let sx = sx_shot / desktop_ratio;- let sy = sy_shot / desktop_ratio;+ } else {+ let desktop_ratio = tokio::task::spawn_blocking(|| {+ let logical_w =+ super::get_screen_size::main_screen_size().map(|(w, _, _)| w as f64);+ let shot_w = crate::capture::screenshot_display_bytes()+ .ok()+ .and_then(|png| crate::capture::png_dimensions(&png).ok())+ .map(|(w, _)| w as f64);+ match (shot_w, logical_w) {+ (Some(sw), Some(lw)) if lw > 0.0 && sw > lw => sw / lw,+ _ => 1.0,+ }+ })+ .await+ .unwrap_or(1.0);+ (sx_shot / desktop_ratio, sy_shot / desktop_ratio)+ };let button = match input.button.unwrap_or(ClickButton::Left) {ClickButton::Left => "left",ClickButton::Right => "right",@@ -365,6 +431,12 @@ impl Tool for ClickTool {Err(e) => return e,};let (element_index, window_id, element_guard) = resolved.into_parts(window_id_arg);+ if capture_id.is_some() && element_guard.is_some() {+ return ToolResult::error(+ "click.capture_id is valid only for the pixel x,y path, not element actions.",+ )+ .with_structured(serde_json::json!({ "code": "invalid_arguments" }));+ }let window_id = match super::native_window_id(window_id) {Ok(window_id) => window_id,Err(error) => return error,@@ -543,33 +615,26 @@ impl Tool for ClickTool {// verified coordinate frame only for those collection-like// elements so perform_ax_click can cross that one failed semantic// rung internally and confirm the result by AX read-back.- let selection_candidate = if effective_action == "press" {+ let selection_center = if effective_action == "press" {let selection_guard = element_guard.clone();tokio::task::spawn_blocking(move || {crate::input::ax_actions::nearest_container_selection_state(selection_guard.as_ptr(),)- .is_some()+ .and_then(|_| nearest_selectable_container_center(selection_guard.as_ptr()))}).await- .unwrap_or(false)+ .unwrap_or(None)} else {- false+ None};- let mut selection_pixel = if selection_candidate {- if let Some((cx, cy)) = center {- super::px_frame::resolve_or_refuse(wid)- .await- .ok()- .map(|frame| SelectionPixelTarget {- screen_x: cx,- screen_y: cy,- window_x: cx - frame.bounds.x,- window_y: cy - frame.bounds.y,- })- } else {- None- }+ let mut selection_pixel = if let Some(screen_center) = selection_center {+ super::px_frame::resolve_or_refuse(wid)+ .await+ .ok()+ .map(|frame| {+ selection_pixel_target(screen_center, (frame.bounds.x, frame.bounds.y))+ })} else {None};@@ -748,6 +813,14 @@ impl Tool for ClickTool {} else if let (Some(mut cx), Some(mut cy)) = (x, y) {// ── Pixel path ─────────────────────────────────────────────────+ if capture_id.is_some() && (from_zoom || debug_image_out.is_some()) {+ return ToolResult::error(+ "click.capture_id is incompatible with from_zoom and debug_image_out; \+ pass coordinates from the exact source capture directly.",+ )+ .with_structured(serde_json::json!({ "code": "invalid_arguments" }));+ }+// debug_image_out: capture fresh screenshot, overlay crosshair BEFORE// any coordinate translation (so it shows received coords in the same// space the caller was reasoning in).@@ -792,20 +865,41 @@ impl Tool for ClickTool {}}- if from_zoom {- match self.state.zoom_registry.get(pid) {- Some(ctx) => {+ if let Some(ref capture_id) = capture_id {+ let wid = match window_id {+ Some(window_id) => window_id,+ None => {+ return ToolResult::error(+ "window capture_id requires the matching pid and window_id.",+ )+ .with_structured(serde_json::json!({ "code": "invalid_arguments" }));+ }+ };+ match self+ .state+ .capture_bindings+ .admit_window_click(capture_id, &args, pid, wid, cx, cy)+ {+ Ok((action_x, action_y)) => {+ cx = action_x;+ cy = action_y;+ }+ Err(refusal) => return refusal,+ }+ } else if from_zoom {+ match super::zoom_context(&self.state, &args, pid, window_id) {+ Ok(ctx) => {let (wx, wy) = ctx.zoom_to_window(cx, cy);cx = wx;cy = wy;}- None => {- return ToolResult::error(format!(- "from_zoom=true but no zoom context for pid {pid}. Call zoom first."- ))- }+ Err(refusal) => return refusal,}- } else if let Some(ratio) = self.state.resize_registry.ratio(pid, window_id) {+ } else {+ let ratio = match super::screenshot_scale(&self.state, &args, pid, window_id) {+ Ok(ratio) => ratio,+ Err(refusal) => return refusal,+ };// Coordinates are in the downscaled image space; scale back to native pixels.cx *= ratio;cy *= ratio;@@ -819,8 +913,9 @@ impl Tool for ClickTool {// has no live frame — see px_frame's module docs for why there is// no screen-absolute fallback.//- // win_local_x/y: window-local logical-pixel coords needed for- // CGEventSetWindowLocation in the Chromium recipe.+ // win_local_x/y: window-local logical-pixel coords used when the+ // Chromium recipe falls back to public PID posting. Its SkyLight+ // route uses the translated screen coordinates instead.let (screen_x, screen_y, win_local_x, win_local_y) = if let Some(wid) = window_id {match super::px_frame::resolve_or_refuse(wid).await {Ok(frame) => {@@ -1076,10 +1171,10 @@ impl Tool for ClickTool {}// "left" (default) or anything else — preserve legacy left-click path._ => {- // When we know the window_id, pass the window-local coordinates so- // `click_at_xy_with_window_local` can stamp `CGEventSetWindowLocation`- // and Chromium-specific fields (f40, f51, f58, f91, f92) onto events- // for better backgrounded-target delivery.+ // When we know the window_id, use the targeted primitive so+ // foreground delivery can stamp window-local coordinates and+ // background delivery can retain the translated screen point+ // while adding Chromium routing fields (f40, f51, f58, f91, f92).if let Some(wid) = window_id {return crate::input::mouse::click_at_xy_with_window_local(pid, screen_x, screen_y,@@ -1446,7 +1541,16 @@ fn perform_ax_click(#[cfg(test)]mod selection_fallback_tests {- use super::selection_readback_confirms;+ use super::{selection_pixel_target, selection_readback_confirms};++ #[test]+ fn selection_pixel_uses_container_center_in_both_coordinate_spaces() {+ let target = selection_pixel_target((360.0, 240.0), (100.0, 80.0));+ assert_eq!(target.screen_x, 360.0);+ assert_eq!(target.screen_y, 240.0);+ assert_eq!(target.window_x, 260.0);+ assert_eq!(target.window_y, 160.0);+ }#[test]fn plain_click_requires_selected_readback() {@@ -1502,6 +1606,7 @@ mod tests {assert!(enum_vals.contains(&"left"));assert!(enum_vals.contains(&"right"));assert!(enum_vals.contains(&"middle"));+ assert_eq!(props["capture_id"]["type"], "string");}/// Surface 5 hard constraint: the tool description must mention thediff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/double_click.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/double_click.rsindex 70f10f7698..03190160ed 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/double_click.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/double_click.rs@@ -174,10 +174,12 @@ impl Tool for DoubleClickTool {};// Scale back from downscaled-image space to native pixels when needed.- if let Some(ratio) = self.state.resize_registry.ratio(pid, window_id) {- cx *= ratio;- cy *= ratio;- }+ let ratio = match super::screenshot_scale(&self.state, &args, pid, window_id) {+ Ok(ratio) => ratio,+ Err(refusal) => return refusal,+ };+ cx *= ratio;+ cy *= ratio;// Window-local → screen coordinate translation + win-local logical coords// for CGEventSetWindowLocation (shared with click.rs via px_frame, whichdiff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/drag.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/drag.rsindex f5eb9d0395..91de626694 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/drag.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/drag.rs@@ -219,6 +219,15 @@ impl Tool for DragTool {};let window_id = args.opt_u64("window_id").map(|v| v as u32);+ if delivery_mode.is_foreground() && window_id.is_none() {+ return ToolResult::error(+ "delivery_mode=foreground requires window_id for drag on macOS".to_owned(),+ )+ .with_structured(serde_json::json!({+ "code": "window_id_required",+ "effect": "refused"+ }));+ }let duration_ms = args.u64_or("duration_ms", 500);let steps = args.u64_or("steps", 20) as usize;let from_zoom = args.bool_or("from_zoom", false);@@ -238,8 +247,8 @@ impl Tool for DragTool {// from_zoom: translate from last zoom crop context.if from_zoom {- match self.state.zoom_registry.get(pid) {- Some(ctx) => {+ match super::zoom_context(&self.state, &args, pid, window_id) {+ Ok(ctx) => {let (wx, wy) = ctx.zoom_to_window(from_x, from_y);let (wx2, wy2) = ctx.zoom_to_window(to_x, to_y);from_x = wx;@@ -247,13 +256,13 @@ impl Tool for DragTool {to_x = wx2;to_y = wy2;}- None => {- return ToolResult::error(format!(- "from_zoom=true but no zoom context for pid {pid}. Call zoom first."- ))- }+ Err(refusal) => return refusal,}- } else if let Some(ratio) = self.state.resize_registry.ratio(pid, window_id) {+ } else {+ let ratio = match super::screenshot_scale(&self.state, &args, pid, window_id) {+ Ok(ratio) => ratio,+ Err(refusal) => return refusal,+ };from_x *= ratio;from_y *= ratio;to_x *= ratio;@@ -297,16 +306,17 @@ impl Tool for DragTool {// Dispatch blocking drag synthesis.let mods_owned = modifiers.clone();- let fg = delivery_mode.is_foreground() && window_id.is_some();+ let fg = delivery_mode.is_foreground();+ let foreground_window_id = window_id;let cursor_for_drag = cursor_key.clone();crate::cursor::overlay::send_command(cursor_key.clone(),cursor_overlay::OverlayCommand::SetPressed(true),);let drag_input = focus_guard::with_focus_suppressed(- // Foreground drag deliberately activates the target so the global- // HID stream carries the pressed-button state. A suppression lease- // here would race that activation and restore the prior app before+ // Foreground drag deliberately activates the target while the+ // HID gesture is delivered. A suppression lease here+ // would race that activation and restore the prior app before// Chromium receives the gesture.if fg { None } else { Some(pid) },prior_front,@@ -315,29 +325,36 @@ impl Tool for DragTool {tokio::task::spawn_blocking(move || -> anyhow::Result<()> {let do_it = move || -> anyhow::Result<()> {let m: Vec<&str> = mods_owned.iter().map(String::as_str).collect();- if fg {- // HID delivery is global, so foreground mode must- // establish a real active application before the- // gesture begins. The SkyLight flash can be- // unavailable for Electron child windows; the- // documented Cocoa activation is the fallback.- apps::activate_pid(pid);- std::thread::sleep(std::time::Duration::from_millis(40));- let observed_cursor = cursor_for_drag.clone();- return crate::input::mouse::drag_at_xy_foreground_observed(- from_sx,- from_sy,- to_sx,- to_sy,- duration_ms,- steps,- &m,- button,- move |x, y| {- crate::cursor::overlay::send_command(- observed_cursor.clone(),- cursor_overlay::track_pointer_command(x, y),- );+ if let Some(wid) = foreground_window_id {+ // Keep the exact target window active for the+ // complete HID gesture, then restore the prior+ // front process.+ return crate::input::skylight::with_foreground_hid_activation(+ pid as libc::pid_t,+ wid,+ || {+ let observed_cursor = cursor_for_drag.clone();+ crate::input::mouse::drag_at_xy_observed(+ pid,+ from_sx,+ from_sy,+ to_sx,+ to_sy,+ Some((from_lx, from_ly)),+ Some((to_lx, to_ly)),+ Some(wid),+ duration_ms,+ steps,+ &m,+ button,+ true,+ move |x, y| {+ crate::cursor::overlay::send_command(+ observed_cursor.clone(),+ cursor_overlay::track_pointer_command(x, y),+ );+ },+ )},);}@@ -363,22 +380,7 @@ impl Tool for DragTool {},)};- // Foreground rung: activate for the complete HID gesture,- // then restore the prior app after pointer capture settles.- match (fg, window_id) {- (true, Some(_wid)) => {- let result = do_it();- std::thread::sleep(std::time::Duration::from_millis(100));- if let Some(previous_pid) = prior_front {- if previous_pid != pid {- apps::activate_pid(previous_pid);- }- }- result?;- Ok(())- }- _ => do_it(),- }+ do_it()}).await},@@ -426,18 +428,22 @@ impl Tool for DragTool {from window-pixel ({}, {}) → ({}, {}), \screen ({}, {}) → ({}, {}) \in {duration_ms}ms / {steps} steps{mode_label} \- (background CGEvent; not driver-verified — confirm via screenshot).{}",- from_x as i64, from_y as i64,- to_x as i64, to_y as i64,- from_sx as i64, from_sy as i64,- to_sx as i64, to_sy as i64,+ (foreground HID CGEvent; not driver-verified — confirm via screenshot).{}",+ from_x as i64,+ from_y as i64,+ to_x as i64,+ to_y as i64,+ from_sx as i64,+ from_sy as i64,+ to_sx as i64,+ to_sy as i64,changes.result_suffix(),)).with_structured(serde_json::json!({- "path": if fg { "cgevent_fg" } else { "cgevent" }, "verified": false, "effect": "unverifiable"+ "path": "cgevent_hid", "verified": false, "effect": "unverifiable"})),Ok(Err(e)) => ToolResult::error(format!("drag failed: {e}")),- Err(e) => ToolResult::error(format!("Task error: {e}")),+ Err(e) => ToolResult::error(format!("Task error: {e}")),}}}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_desktop_state.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_desktop_state.rsindex 652a372ade..40b0e8da85 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_desktop_state.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_desktop_state.rs@@ -18,10 +18,19 @@ use cua_driver_core::{tool_args::parse_typed_input,};use serde_json::Value;+use std::sync::Arc;-use super::get_screen_size::main_screen_size;+use super::{get_screen_size::main_screen_size, ToolState};-pub struct GetDesktopStateTool;+pub struct GetDesktopStateTool {+ state: Arc<ToolState>,+}++impl GetDesktopStateTool {+ pub fn new(state: Arc<ToolState>) -> Self {+ Self { state }+ }+}static DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();@@ -55,6 +64,7 @@ impl Tool for GetDesktopStateTool {}async fn invoke(&self, args: Value) -> ToolResult {+ let capture_args = args.clone();let input = match parse_typed_input::<GetDesktopStateInput>("get_desktop_state", args) {Ok(input) => input,Err(result) => return result,@@ -79,29 +89,47 @@ impl Tool for GetDesktopStateTool {// blocking screencapture subprocess off the async runtime.let out_file = screenshot_out_file.clone();let res = tokio::task::spawn_blocking(- move || -> anyhow::Result<(Option<String>, Option<String>, u32, u32)> {- use base64::{engine::general_purpose::STANDARD as BASE64, Engine};+ move || -> anyhow::Result<(Vec<u8>, Option<String>, u32, u32)> {let png = crate::capture::screenshot_display_bytes()?;let (w, h) = crate::capture::png_dimensions(&png)?;if let Some(ref path) = out_file {std::fs::write(path, &png)?;- Ok((None, Some(path.clone()), w, h))+ Ok((png, Some(path.clone()), w, h))} else {- Ok((Some(BASE64.encode(&png)), None, w, h))+ Ok((png, None, w, h))}},).await;- let (b64_opt, file_path, screenshot_width, screenshot_height) = match res {+ let (png, file_path, screenshot_width, screenshot_height) = match res {Ok(Ok(v)) => v,Ok(Err(e)) => return ToolResult::error(format!("Desktop screenshot failed: {e}")),Err(e) => return ToolResult::error(format!("Desktop screenshot task error: {e}")),};+ let native_width = match u32::try_from(screen_width) {+ Ok(width) => width,+ Err(_) => return ToolResult::error("Desktop screen width is out of range."),+ };+ let native_height = match u32::try_from(screen_height) {+ Ok(height) => height,+ Err(_) => return ToolResult::error("Desktop screen height is out of range."),+ };+ let capture_id = match self.state.capture_bindings.publish_desktop(+ &capture_args,+ png.clone(),+ (screenshot_width, screenshot_height),+ (native_width, native_height),+ ) {+ Ok(capture_id) => capture_id,+ Err(error) => return error,+ };+let mut content: Vec<Content> = Vec::new();- if let Some(b64) = b64_opt {- content.push(Content::image_png(b64));+ if file_path.is_none() {+ use base64::{engine::general_purpose::STANDARD as BASE64, Engine};+ content.push(Content::image_png(BASE64.encode(&png)));}let summary = format!("desktop screenshot {screenshot_width}x{screenshot_height} px \@@ -118,6 +146,7 @@ impl Tool for GetDesktopStateTool {"screen_height": screen_height,"scale_factor": scale_factor,"screenshot_mime_type": "image/png",+ "capture_id": capture_id,});if let Some(ref fp) = file_path {structured["screenshot_file_path"] = serde_json::json!(fp);diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rsindex 90786072c0..6208d50287 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs@@ -55,9 +55,10 @@ fn def() -> &'static ToolDef {— the capture-only path for rendering a live window preview / \picture-in-picture without paying for perception. Setting BOTH \`include_accessibility_tree:false` and `include_screenshot:false` is an \- error (nothing to return). Optional `max_dimension` caps the returned \- screenshot's long edge in pixels (aspect preserved) for a cheap \- thumbnail.\n\n\+ error (nothing to return). Optional `max_image_dimension` overrides the \+ configured screenshot long-edge limit for this call; use 0 for native \+ resolution. The legacy `max_dimension` remains a tighter cap for \+ compatibility.\n\n\The snapshot is SCOPED to `window_id`: a window_id that no longer exists is \refused with `window_id_not_found`, and one owned by another process is \refused with `window_owner_pid_mismatch` naming the real `owner_pid` to retry \@@ -116,6 +117,11 @@ fn def() -> &'static ToolDef {"type": "integer","minimum": 1,"description": "Optional cap on the returned screenshot's long edge, in pixels (aspect ratio preserved) — the cheap path for a small preview / thumbnail. Applied on top of the session/global max_image_dimension ceiling; the tighter of the two wins. Omit for the configured default."+ },+ "max_image_dimension": {+ "type": "integer",+ "minimum": 0,+ "description": "Per-call override for the returned screenshot's long edge in pixels. An explicit value wins over the session/global setting; 0 returns native resolution. Omit to preserve configured behavior."}},"additionalProperties": false@@ -140,6 +146,14 @@ fn fold_max_dimension(ceiling: u32, per_call: Option<u32>) -> u32 {}}+fn resolve_max_dimension(+ configured: u32,+ legacy_cap: Option<u32>,+ per_call_override: Option<u32>,+) -> u32 {+ per_call_override.unwrap_or_else(|| fold_max_dimension(configured, legacy_cap))+}+fn chromium_browser_window(pid: i32) -> bool {let identity = format!("{} {}",@@ -267,6 +281,10 @@ impl Tool for GetWindowStateTool {.get("max_dimension").and_then(|v| v.as_u64()).map(|v| v.max(1) as u32);+ let max_image_dimension = args+ .get("max_image_dimension")+ .and_then(|v| v.as_u64())+ .map(|v| v as u32);// Internal direct-tool mode used by verify_state. Registry ingress// strips underscore-prefixed arguments before public dispatch; only// a trusted direct in-process invocation can enable this mode.@@ -346,28 +364,30 @@ impl Tool for GetWindowStateTool {// against. Skipped only when `include_screenshot:false` (and no// screenshot_out_file). With `screenshot_out_file` set, write to disk and// surface the path instead of embedding base64; otherwise embed base64.- // Fold the per-call `max_dimension` with the session/global ceiling- // (the tighter of the two wins).- let max_dim = fold_max_dimension(effective_max_dim, max_dimension);- // Returns the encoded/file capture, delivered dimensions, optional- // downscale source width, the WindowServer bounds it was validated+ // The portable `max_image_dimension` is an explicit per-call override,+ // including 0 for native resolution. Without it, preserve the existing+ // configured ceiling and legacy `max_dimension` tighter-cap behavior.+ let max_dim = resolve_max_dimension(effective_max_dim, max_dimension, max_image_dimension);+ // Returns the exact delivered PNG bytes, optional file path, delivered+ // and native dimensions, the WindowServer bounds it was validated// against, and the raw capture's backing scale.let mut screenshot_frame_error = None;+ let mut screenshot_resize_scale = None;let screenshot = if should_capture {let out_file = screenshot_out_file.clone();let res = tokio::task::spawn_blocking(move || -> Result<(+ Vec<u8>,Option<String>,- Option<String>,u32,u32,- Option<u32>,+ u32,+ u32,crate::windows::WindowBounds,f64,),super::px_frame::PxFrameError,> {- use base64::{engine::general_purpose::STANDARD as BASE64, Engine};let bounds = crate::windows::window_bounds_by_id(window_id).filter(|b| b.width > 0.0 && b.height > 0.0).ok_or(super::px_frame::PxFrameError::WindowNotFound { window_id })?;@@ -397,7 +417,6 @@ impl Tool for GetWindowStateTool {reason: e.to_string(),}})?;- let original_w = if w < orig_w { Some(orig_w) } else { None };if let Some(ref path) = out_file {std::fs::write(path, &png).map_err(|e| {super::px_frame::PxFrameError::CaptureUnavailable {@@ -406,55 +425,39 @@ impl Tool for GetWindowStateTool {}})?;Ok((- None,+ png,Some(path.clone()),w,h,- original_w,+ orig_w,+ orig_h,bounds,scale,))} else {Ok((- Some(BASE64.encode(&png)),+ png,None,w,h,- original_w,+ orig_w,+ orig_h,bounds,scale,))}}).await;match res {- Ok(Ok((b64, file_path, w, h, orig_w, bounds, scale))) => {- // Record resize ratio so ClickTool can scale coordinates back- // up. Keyed per window: two windows of one pid can carry- // different ratios (only the large one downscales), and a- // pid-only key leaked one window's ratio into the other's- // pixel clicks.+ Ok(Ok((png, file_path, w, h, orig_w, orig_h, bounds, scale))) => {if !observation_only {- if let Some(ow) = orig_w {- if w > 0 {- self.state.resize_registry.set_ratio(- pid,- window_id,- ow as f64 / w as f64,- );- }- } else {- self.state.resize_registry.clear_ratio(pid, window_id);- }+ screenshot_resize_scale = Some(orig_w as f64 / w as f64);}- Some((b64, file_path, w, h, bounds, scale))+ Some((png, file_path, w, h, orig_w, orig_h, bounds, scale))}Ok(Err(e)) => {tracing::warn!("Screenshot frame could not be verified for window {window_id}: {e:?}");- if !observation_only {- self.state.resize_registry.clear_ratio(pid, window_id);- }screenshot_frame_error = Some(e);None}@@ -468,20 +471,21 @@ impl Tool for GetWindowStateTool {};// Capture screenshot dimensions before consuming.- let screenshot_dims = screenshot.as_ref().map(|(_, _, w, h, _, _)| (*w, *h));+ let screenshot_dims = screenshot.as_ref().map(|(_, _, w, h, _, _, _, _)| (*w, *h));let screenshot_file_path = screenshot.as_ref()- .and_then(|(_, fp, _, _, _, _)| fp.clone());+ .and_then(|(_, fp, _, _, _, _, _, _)| fp.clone());let screenshot_frame = screenshot.as_ref()- .map(|(_, _, _, _, bounds, scale)| (bounds.clone(), *scale));+ .map(|(_, _, _, _, _, _, bounds, scale)| (bounds.clone(), *scale));// Build response.let mut content: Vec<Content> = Vec::new();- if let Some((b64_opt, _file_path, w, h, _bounds, _scale)) = screenshot {- if let Some(b64) = b64_opt {- content.push(Content::image_png(b64));+ if let Some((png, ref file_path, w, h, _, _, _, _)) = screenshot.as_ref() {+ if file_path.is_none() {+ use base64::{engine::general_purpose::STANDARD as BASE64, Engine};+ content.push(Content::image_png(BASE64.encode(png)));}// Summary text line (matching Swift reference format).@@ -521,13 +525,43 @@ impl Tool for GetWindowStateTool {.map(|r| r.tree_markdown.clone()).unwrap_or_default();- let snapshot_id = prepared_snapshot+ let snapshot_payload = prepared_snapshot.or_else(|| {+ screenshot_resize_scale+ .is_some()+ .then(|| crate::ax::cache::CachedSnapshot::from_nodes(&[]))+ });+ let snapshot_id = snapshot_payload.filter(|_| scope_matched && !observation_only)- .map(|payload| {- self.state- .element_cache- .publish(pid, u64::from(window_id), payload)+ .and_then(|payload| {+ self.state.element_cache.publish_for_session(+ pid,+ u64::from(window_id),+ payload,+ session_id.as_deref(),+ screenshot_resize_scale,+ )});+ if let Some(snapshot_id) = snapshot_id {+ self.state+ .zoom_registry+ .retire_replaced(pid, u64::from(window_id), snapshot_id);+ }+ let capture_id = match (snapshot_id, screenshot.as_ref()) {+ (Some(_), Some((png, _, width, height, native_width, native_height, _, _))) => {+ match self.state.capture_bindings.publish_window(+ &args,+ pid,+ window_id,+ png.clone(),+ (*width, *height),+ (*native_width, *native_height),+ ) {+ Ok(capture_id) => Some(capture_id),+ Err(error) => return error,+ }+ }+ _ => None,+ };// Build the structured `elements` array — one entry per actionable// node, matching the order (and indices) of the markdown rendering.@@ -580,6 +614,9 @@ impl Tool for GetWindowStateTool {.trim_end_matches(":0").to_string());}+ if let Some(capture_id) = capture_id {+ structured["capture_id"] = serde_json::json!(capture_id);+ }// Best-effort-background ladder, rung (2). Both rungs point the agent at// the same next move: an empty AX tree means element_index has nothing// to bind to, so the deliberate action is an element px action — read@@ -710,7 +747,7 @@ impl Tool for GetWindowStateTool {/// remedy-in-the-refusal shape the rest of the driver uses.////// The owner pid is REPORTED, not followed: `element_cache`, the element-token-/// registry and `ResizeRegistry` are all keyed on the caller-supplied pid, so+/// registry and snapshot-owned screenshot transform are keyed on the caller-supplied pid, so/// walking under `owner_pid` while echoing the requested pid would hand back/// indices the caller replays against the wrong key. One retry with the named/// pid is correct and cheap.@@ -1054,6 +1091,7 @@ mod window_scope_contract_tests {props.get("max_dimension").is_some(),"schema must advertise max_dimension");+ assert_eq!(props["max_image_dimension"]["minimum"], 0);let required: Vec<&str> = d.input_schema["required"].as_array().expect("required array")@@ -1086,6 +1124,15 @@ mod window_scope_contract_tests {assert_eq!(fold_max_dimension(1600, None), 1600);assert_eq!(fold_max_dimension(0, None), 0);}++ #[test]+ fn max_image_dimension_explicit_override_wins() {+ assert_eq!(resolve_max_dimension(1024, None, Some(2048)), 2048);+ assert_eq!(resolve_max_dimension(1024, Some(512), Some(2048)), 2048);+ assert_eq!(resolve_max_dimension(1024, Some(512), Some(0)), 0);+ assert_eq!(resolve_max_dimension(1024, Some(512), None), 512);+ assert_eq!(resolve_max_dimension(1024, None, None), 1024);+ }}#[cfg(test)]diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rsindex 5b2ce9ed5b..0c1231e577 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs@@ -1,6 +1,7 @@//! MCP tool implementations for macOS.mod bring_to_front;+mod capture_binding;mod click;mod clipboard;mod double_click;@@ -147,28 +148,9 @@ pub use check_permissions::{PERMISSIONS_HOST_REQUEST_ARG,};-/// Per-process zoom context — stores the padded crop origin and resize scale-/// from the most recent `zoom` call, so `click(from_zoom=true)` can translate-/// zoom-image pixel coordinates back to full-window coordinates.-#[derive(Clone, Copy, Debug)]-pub struct ZoomContext {- /// Padded crop X origin in full-window pixel space.- pub origin_x: f64,- /// Padded crop Y origin in full-window pixel space.- pub origin_y: f64,- /// Inverse resize scale: `cw / out_w` (1.0 = no downscale).- pub scale_inv: f64,-}--impl ZoomContext {- /// Translate a zoom-image coordinate `(px, py)` to full-window pixel coordinates.- pub fn zoom_to_window(&self, px: f64, py: f64) -> (f64, f64) {- (- self.origin_x + px * self.scale_inv,- self.origin_y + py * self.scale_inv,- )- }-}+pub use cua_driver_core::element_cache::{+ SnapshotBoundZoomContext as ZoomContext, SnapshotBoundZoomRegistry as ZoomRegistry,+};/// Input delivery modality — the agent-selected rung of the best-effort-background/// ladder, passed per call (never a stored/config setting).@@ -490,97 +472,6 @@ fn point_within_rect([rx, ry, rw, rh]: [f64; 4], x: f64, y: f64) -> bool {rw > 0.0 && rh > 0.0 && x >= rx && x < rx + rw && y >= ry && y < ry + rh}-/// Thread-safe per-pid zoom context registry.-pub struct ZoomRegistry {- inner: std::sync::Mutex<HashMap<i32, ZoomContext>>,-}--impl Default for ZoomRegistry {- fn default() -> Self {- Self::new()- }-}--impl ZoomRegistry {- pub fn new() -> Self {- Self {- inner: std::sync::Mutex::new(HashMap::new()),- }- }-- pub fn set(&self, pid: i32, ctx: ZoomContext) {- self.inner.lock().unwrap().insert(pid, ctx);- }-- pub fn get(&self, pid: i32) -> Option<ZoomContext> {- self.inner.lock().unwrap().get(&pid).copied()- }-}--/// Tracks the per-(pid, window_id) ratio applied by `max_image_dimension`-/// downscaling.-///-/// `ratio = original_dim / resized_dim` — multiply resized image coordinates-/// by this to recover original (native) window-local pixel coordinates.-/// Mirrors Swift's `ImageResizeRegistry`.-///-/// Keyed per window, matching the element cache and the element-token-/// registry. A pid-only key leaked the ratio recorded while snapshotting-/// window A into pixel clicks aimed at window B of the same pid, sending them-/// off-target (issue #2237).-pub struct ResizeRegistry {- inner: std::sync::Mutex<HashMap<(i32, u32), f64>>,-}--impl Default for ResizeRegistry {- fn default() -> Self {- Self::new()- }-}--impl ResizeRegistry {- pub fn new() -> Self {- Self {- inner: std::sync::Mutex::new(HashMap::new()),- }- }-- /// Record that (pid, window_id)'s screenshot was downscaled by `ratio`.- pub fn set_ratio(&self, pid: i32, window_id: u32, ratio: f64) {- self.inner.lock().unwrap().insert((pid, window_id), ratio);- }-- /// Remove the ratio entry for one window (no active downscale).- pub fn clear_ratio(&self, pid: i32, window_id: u32) {- self.inner.lock().unwrap().remove(&(pid, window_id));- }-- /// The ratio for a window, or `None` if no downscale happened.- ///- /// `window_id: None` is the screen-scope (legacy) path: it returns a ratio- /// only when every window recorded for `pid` agrees on one, so a- /// window-less caller can never inherit some other window's scale. That- /// preserves today's behaviour for the single-window case without guessing- /// across windows.- pub fn ratio(&self, pid: i32, window_id: Option<u32>) -> Option<f64> {- let inner = self.inner.lock().unwrap();- match window_id {- Some(wid) => inner.get(&(pid, wid)).copied(),- None => {- let mut agreed: Option<f64> = None;- for (_, ratio) in inner.iter().filter(|((p, _), _)| *p == pid) {- match agreed {- None => agreed = Some(*ratio),- Some(seen) if (seen - *ratio).abs() < 1e-9 => {}- Some(_) => return None,- }- }- agreed- }- }- }-}-/// Runtime-mutable driver configuration persisted across calls within a session.pub struct DriverConfig {/// Max screenshot dimension (0 = no limit). Applied during screenshot/zoom.@@ -748,7 +639,7 @@ pub struct ToolState {pub element_cache: Arc<ElementCache>,pub cursor_registry: Arc<CursorRegistry>,pub zoom_registry: Arc<ZoomRegistry>,- pub resize_registry: Arc<ResizeRegistry>,+ pub(crate) capture_bindings: Arc<capture_binding::MacCaptureBindings>,/// Global, disk-persisted config — the base layer and the only one the/// anonymous session / CLI writes.pub config: Arc<std::sync::RwLock<DriverConfig>>,@@ -782,12 +673,26 @@ impl ToolState {cursor_overlay_available: bool,host_owns_permission_ux: bool,host_bundle_id: Option<String>,+ ) -> Self {+ Self::new_with_capture_service(+ Arc::new(cua_driver_core::capture_runtime::CaptureService::default()),+ cursor_overlay_available,+ host_owns_permission_ux,+ host_bundle_id,+ )+ }++ fn new_with_capture_service(+ capture_service: Arc<cua_driver_core::capture_runtime::CaptureService>,+ cursor_overlay_available: bool,+ host_owns_permission_ux: bool,+ host_bundle_id: Option<String>,) -> Self {Self {element_cache: Arc::new(ElementCache::new()),cursor_registry: Arc::new(CursorRegistry::new()),zoom_registry: Arc::new(ZoomRegistry::new()),- resize_registry: Arc::new(ResizeRegistry::new()),+ capture_bindings: Arc::new(capture_binding::MacCaptureBindings::new(capture_service)),// Load persisted config from ~/.cua-driver/config.json so that// `cua-driver config set` changes carry over into MCP sessions.config: Arc::new(std::sync::RwLock::new(load_driver_config())),@@ -800,6 +705,33 @@ impl ToolState {}}+pub(super) fn screenshot_scale(+ state: &ToolState,+ args: &serde_json::Value,+ pid: i32,+ window_id: Option<u32>,+) -> Result<f64, cua_driver_core::protocol::ToolResult> {+ state.element_cache.screenshot_scale_or_refusal(+ pid,+ window_id.map(u64::from),+ args.get("_session_id").and_then(serde_json::Value::as_str),+ )+}++pub(super) fn zoom_context(+ state: &ToolState,+ args: &serde_json::Value,+ pid: i32,+ window_id: Option<u32>,+) -> Result<ZoomContext, cua_driver_core::protocol::ToolResult> {+ state.zoom_registry.resolve(+ &state.element_cache,+ pid,+ window_id.map(u64::from),+ args.get("_session_id").and_then(serde_json::Value::as_str),+ )+}+pub(crate) fn cursor_overlay_unavailable() -> cua_driver_core::protocol::ToolResult {let message = "macOS agent cursor overlay is unavailable: this runtime owner has no certified \AppKit main-thread host adapter or no Window Server graphic-session access; \@@ -825,7 +757,8 @@ pub fn register_all(host_owns_permission_ux: bool,host_bundle_id: Option<String>,) {- let state = Arc::new(ToolState::new(+ let state = Arc::new(ToolState::new_with_capture_service(+ registry.capture_service(),cursor_overlay_available,host_owns_permission_ux,host_bundle_id,@@ -869,7 +802,9 @@ pub fn register_all(if let Some(runtime_scope) = cua_driver_core::tool::current_dispatch_runtime_scope() {let prefix = format!("__cua_runtime_{runtime_scope}:");let cursor_registry = state.cursor_registry.clone();+ let capture_bindings = state.capture_bindings.clone();registry.retain_runtime_cleanup(move || {+ capture_bindings.retire_runtime();for cursor in cursor_registry.all_states().into_iter()@@ -889,10 +824,16 @@ pub fn register_all(// recording ownership is handled separately on the core RecordingSession.{let session_config = state.session_config.clone();+ let element_cache = state.element_cache.clone();+ let zoom_registry = state.zoom_registry.clone();let cursor_registry = state.cursor_registry.clone();+ let capture_bindings = state.capture_bindings.clone();let registration =cua_driver_core::session::register_scoped_session_end_hook(move |session_id| {session_config.clear(session_id);+ zoom_registry.retire_session(session_id);+ element_cache.retire_session_screenshots(session_id);+ capture_bindings.retire_session(session_id);// Per-session agent cursor: the session_id is the cursor key when// the caller gave no explicit cursor_id, so dropping it here both// prunes the metadata registry and stops the overlay painting that@@ -982,7 +923,9 @@ pub fn register_all(// triggers Claude Code's computer-use beta-tool injection (see cli.rs).let _ = compat;registry.register(Box::new(get_screen_size::GetScreenSizeTool));- registry.register(Box::new(get_desktop_state::GetDesktopStateTool));+ registry.register(Box::new(get_desktop_state::GetDesktopStateTool::new(+ state.clone(),+ )));registry.register(Box::new(get_cursor_position::GetCursorPositionTool));registry.register(Box::new(move_cursor::MoveCursorTool::new(state.clone())));registry.register(Box::new(cursor_tools::SetAgentCursorEnabledTool::new(@@ -1086,75 +1029,6 @@ mod session_config_guard_tests {}}-#[cfg(test)]-mod resize_registry_tests {- use super::ResizeRegistry;-- /// Issue #2237: the registry was keyed by pid alone, so the downscale- /// ratio recorded while snapshotting one window was applied to pixel- /// clicks aimed at another window of the same app.- #[test]- fn resize_ratio_is_keyed_per_window() {- let reg = ResizeRegistry::new();- reg.set_ratio(800, 11, 2.0);- reg.set_ratio(800, 22, 1.25);- assert_eq!(reg.ratio(800, Some(11)), Some(2.0));- assert_eq!(reg.ratio(800, Some(22)), Some(1.25));- }-- #[test]- fn undownscaled_window_reports_no_ratio() {- let reg = ResizeRegistry::new();- reg.set_ratio(800, 11, 2.0);- assert_eq!(- reg.ratio(800, Some(22)),- None,- "window 22 was never downscaled; it must not inherit window 11's ratio"- );- }-- #[test]- fn clearing_one_window_keeps_the_other() {- let reg = ResizeRegistry::new();- reg.set_ratio(800, 11, 2.0);- reg.set_ratio(800, 22, 1.25);- reg.clear_ratio(800, 11);- assert_eq!(reg.ratio(800, Some(11)), None);- assert_eq!(reg.ratio(800, Some(22)), Some(1.25));- }-- #[test]- fn distinct_pids_with_the_same_window_id_do_not_collide() {- let reg = ResizeRegistry::new();- reg.set_ratio(800, 11, 2.0);- reg.set_ratio(900, 11, 3.0);- assert_eq!(reg.ratio(800, Some(11)), Some(2.0));- assert_eq!(reg.ratio(900, Some(11)), Some(3.0));- }-- /// Screen-scope callers pass no window_id. One window (the common case)- /// keeps working; disagreeing windows refuse to guess.- #[test]- fn screen_scope_lookup_only_answers_when_windows_agree() {- let reg = ResizeRegistry::new();- assert_eq!(reg.ratio(800, None), None, "nothing recorded yet");- reg.set_ratio(800, 11, 2.0);- assert_eq!(- reg.ratio(800, None),- Some(2.0),- "single window is unambiguous"- );- reg.set_ratio(800, 22, 2.0);- assert_eq!(reg.ratio(800, None), Some(2.0), "agreeing windows answer");- reg.set_ratio(800, 33, 1.25);- assert_eq!(- reg.ratio(800, None),- None,- "disagreeing windows must not pick one arbitrarily"- );- }-}-#[cfg(test)]mod cursor_overlay_facility_tests {use super::*;diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/px_frame.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/px_frame.rsindex 19d54df23b..d24fee728c 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/px_frame.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/px_frame.rs@@ -25,8 +25,9 @@ pub struct WindowPxFrame {impl WindowPxFrame {/// Window-local capture pixels → `(screen_x, screen_y, local_pt_x,- /// local_pt_y)`. The local-point pair is what- /// `CGEventSetWindowLocation` needs for background delivery.+ /// local_pt_y)`. Public PID event routes use the local-point pair for+ /// `CGEventSetWindowLocation`; the SkyLight PID/window-routed click keeps+ /// the screen-point pair because WindowServer derives local coordinates.pub fn to_screen(&self, cx: f64, cy: f64) -> (f64, f64, f64, f64) {let lx = cx / self.scale;let ly = cy / self.scale;diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/right_click.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/right_click.rsindex 835551d46f..1a05770851 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/right_click.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/right_click.rs@@ -169,10 +169,12 @@ impl Tool for RightClickTool {// ── Pixel path ───────────────────────────────────────────────────────let (mut cx, mut cy) = (x.unwrap(), y.unwrap());// Scale back from downscaled-image space to native pixels when needed.- if let Some(ratio) = self.state.resize_registry.ratio(pid, window_id) {- cx *= ratio;- cy *= ratio;- }+ let ratio = match super::screenshot_scale(&self.state, &args, pid, window_id) {+ Ok(ratio) => ratio,+ Err(refusal) => return refusal,+ };+ cx *= ratio;+ cy *= ratio;// Window-local → screen coordinate translation + win-local logical coords// for CGEventSetWindowLocation (shared with click.rs via px_frame, whichdiff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/scroll.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/scroll.rsindex 64b98e157b..7d4a63aa47 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/scroll.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/scroll.rs@@ -420,10 +420,12 @@ impl Tool for ScrollTool {// click pixel path — undo any session downscale, then translate// through the shared window frame (which refuses a window with no// live frame rather than scrolling at screen-absolute coords).- if let Some(ratio) = self.state.resize_registry.ratio(pid, window_id) {- cx *= ratio;- cy *= ratio;- }+ let ratio = match super::screenshot_scale(&self.state, &args, pid, window_id) {+ Ok(ratio) => ratio,+ Err(refusal) => return refusal,+ };+ cx *= ratio;+ cy *= ratio;let Some(wid) = window_id else {// Unreachable: the None case refused above. Kept explicit so a// future edit cannot reintroduce the screen-absolute fallback.diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text.rsindex 94c332a807..091f7a7891 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/type_text.rs@@ -75,8 +75,12 @@ fn def() -> &'static ToolDef {X's compose box): AXValue is not independent proof that the \renderer/DOM observed an AX write or synthesized keystrokes. The \driver detects this at the element level (an AXWebArea ancestor) and \- refuses to trust AXValue-only read-back there — type_text returns \- effect:\"unverifiable\" + escalation, never a false \"confirmed\" (a \+ refuses to trust AXValue-only read-back there. Electron AX targets that \+ are web content or cannot be proven native refuse background delivery \+ before mutation because the AX route cannot establish exact renderer \+ focus; use the px form or explicit foreground delivery. Other web-content \+ paths return effect:\"unverifiable\" + \+ escalation, never a false \"confirmed\" (a \browser's own native address bar/toolbar stays trusted). For a browser \TAB the reliable path is the `page` tool (drives the DOM via CDP); for \an embedded web view use this tool's px form: pass x,y (no \@@ -312,6 +316,27 @@ impl Tool for TypeTextTool {// element_index stays None → the type path below writes to the now-// focused element via the CGEvent (key_events) rung.}+ let element_ptr = element_guard+ .as_ref()+ .map(|(g, idx)| (g.as_ptr(), Some(*idx)));++ let electron_background_ax_unsafe = element_ptr.is_some()+ && crate::browser::electron_js::ElectronJs::is_electron(pid)+ && electron_background_ax_ancestry_is_unsafe(classify_target_web_area(+ pid,+ element_ptr,+ window_id,+ ));+ if let Some(refusal) = electron_background_ax_refusal(+ delivery_mode,+ element_ptr.is_some(),+ used_pixel_focus,+ electron_background_ax_unsafe,+ ) {+ let wid = window_id.expect("AX element targets require window_id");+ return super::background_refusal_result(pid, wid, &refusal);+ }+if let (Some((element, _)), Some(wid)) = (element_guard.as_ref(), window_id) {let center_guard = element.clone();if let Ok(Some((screen_x, screen_y))) = tokio::task::spawn_blocking(move || unsafe {@@ -331,10 +356,6 @@ impl Tool for TypeTextTool {.update_position(&cursor_key, screen_x, screen_y);}}- let element_ptr = element_guard- .as_ref()- .map(|(g, idx)| (g.as_ptr(), Some(*idx)));-let text_clone = text.clone();let char_count = text.chars().count();@@ -732,6 +753,27 @@ fn web_readback_next_rung(is_electron: bool, used_pixel_focus: bool) -> Option<&}}+fn electron_background_ax_refusal(+ delivery_mode: super::DeliveryMode,+ has_ax_target: bool,+ used_pixel_focus: bool,+ electron_background_ax_unsafe: bool,+) -> Option<BackgroundRefusal> {+ if delivery_mode.is_foreground()+ || !has_ax_target+ || used_pixel_focus+ || !electron_background_ax_unsafe+ {+ return None;+ }+ Some(BackgroundRefusal {+ code: "background_unavailable",+ reason: "The Electron AX target cannot establish a safe exact background text route on macOS because its ancestry is web content or could not be proven native; use the pixel-targeted type_text form (x,y) or delivery_mode:\"foreground\"."+ .to_owned(),+ advice: Some("px"),+ })+}+const DELIVERY_DRAIN_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);const DELIVERY_DRAIN_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(10);@@ -940,6 +982,37 @@ pub(super) fn target_in_web_area(element_ptr_and_idx: Option<(usize, Option<usize>)>,window_id: Option<u32>,) -> bool {+ web_readback_is_untrusted(classify_target_web_area(+ pid,+ element_ptr_and_idx,+ window_id,+ ))+}++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum WebAreaClassification {+ WebContent,+ NonWebContent,+ Incomplete,+ WindowFocusUnavailable,+}++fn web_readback_is_untrusted(classification: WebAreaClassification) -> bool {+ matches!(+ classification,+ WebAreaClassification::WebContent | WebAreaClassification::WindowFocusUnavailable+ )+}++fn electron_background_ax_ancestry_is_unsafe(classification: WebAreaClassification) -> bool {+ !matches!(classification, WebAreaClassification::NonWebContent)+}++fn classify_target_web_area(+ pid: i32,+ element_ptr_and_idx: Option<(usize, Option<usize>)>,+ window_id: Option<u32>,+) -> WebAreaClassification {use crate::ax::bindings::AXUIElementCopyAttributeValue;use core_foundation::base::{CFTypeRef, TCFType};use core_foundation::string::CFString;@@ -956,26 +1029,30 @@ pub(super) fn target_in_web_area(None => match window_id {Some(wid) => match crate::ax::exact_target::focused_element_in_window(pid, wid) {Some(el) => (el, true),- None => return true,+ None => return WebAreaClassification::WindowFocusUnavailable,},None => match focused_element_of_pid(pid) {Some(el) => (el, true),- None => return false,+ None => return WebAreaClassification::NonWebContent,},},};let parent_attr = CFString::new("AXParent");let mut cur = start;let mut cur_owned = start_owned;- let mut found = false;+ let mut classification = WebAreaClassification::Incomplete;for _ in 0..40 {match copy_string_attr(cur, "AXRole").as_deref() {Some("AXWebArea") => {- found = true;+ classification = WebAreaClassification::WebContent;break;}// No web area lives above the window/app root — stop.- Some("AXWindow") | Some("AXApplication") | None => break,+ Some("AXWindow") | Some("AXApplication") => {+ classification = WebAreaClassification::NonWebContent;+ break;+ }+ None => break,_ => {}}let mut parent: CFTypeRef = std::ptr::null_mut();@@ -995,7 +1072,7 @@ pub(super) fn target_in_web_area(if cur_owned && !cur.is_null() {CFRelease(cur as CFTypeRef);}- found+ classification}}@@ -1617,6 +1694,61 @@ mod tests {assert_eq!(web_readback_next_rung(false, true), Some("page"));}+ #[test]+ fn electron_web_ax_background_refuses_before_synthesis() {+ let refusal = electron_background_ax_refusal(+ crate::tools::DeliveryMode::Background,+ true,+ false,+ true,+ )+ .expect("Electron AX background typing must refuse");+ assert_eq!(refusal.code, "background_unavailable");+ assert_eq!(refusal.advice, Some("px"));++ assert!(electron_background_ax_refusal(+ crate::tools::DeliveryMode::Foreground,+ true,+ false,+ true,+ )+ .is_none());+ assert!(electron_background_ax_refusal(+ crate::tools::DeliveryMode::Background,+ false,+ true,+ true,+ )+ .is_none());+ assert!(electron_background_ax_refusal(+ crate::tools::DeliveryMode::Background,+ true,+ false,+ false,+ )+ .is_none());+ }++ #[test]+ fn incomplete_web_ancestry_only_fails_closed_for_electron_background_ax() {+ assert!(electron_background_ax_ancestry_is_unsafe(+ WebAreaClassification::Incomplete+ ));+ assert!(electron_background_ax_ancestry_is_unsafe(+ WebAreaClassification::WindowFocusUnavailable+ ));+ assert!(!electron_background_ax_ancestry_is_unsafe(+ WebAreaClassification::NonWebContent+ ));++ assert!(!web_readback_is_untrusted(+ WebAreaClassification::Incomplete+ ));+ assert!(web_readback_is_untrusted(+ WebAreaClassification::WindowFocusUnavailable+ ));+ }+#[test]fn foreground_typing_skips_long_rearm_when_target_is_already_frontmost() {assert_eq!(foreground_settle_ms(42, Some(42)), 20);diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/zoom.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/zoom.rsindex f389448f9a..198917a54b 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/zoom.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/zoom.rs@@ -22,13 +22,16 @@ fn def() -> &'static ToolDef {pixel coordinates, with 20% padding added on each side. The output image is at most \500 px wide.\n\n\After a zoom, pass `from_zoom=true` to click/type_text to auto-translate coordinates \- back to full-window space.".into(),+ back to full-window space. Coordinate actions return `screenshot_context_missing` \+ when the latest snapshot does not contain a screenshot owned by this session. \+ `from_zoom` actions return `zoom_context_missing` when the zoom was never created or \+ was replaced; call `get_window_state`, then `zoom`, again on the same connection.".into(),input_schema: serde_json::json!({"type": "object","required": ["window_id", "x1", "y1", "x2", "y2"],"properties": {"window_id": { "type": "integer", "description": "CGWindowID from list_windows." },- "pid": { "type": "integer", "description": "Target pid — required for from_zoom click/type translation." },+ "pid": { "type": "integer", "description": "Optional target pid. When omitted, the driver resolves the unique current snapshot for this session and window." },"x1": { "type": "number", "description": "Left edge of region in screenshot pixels." },"y1": { "type": "number", "description": "Top edge of region in screenshot pixels." },"x2": { "type": "number", "description": "Right edge of region in screenshot pixels." },@@ -55,7 +58,22 @@ impl Tool for ZoomTool {Ok(v) => v,Err(e) => return e,};- let pid = args.opt_i64("pid").map(|v| v as i32);+ let requested_pid = match args.get("pid") {+ None => None,+ Some(value) => match value.as_i64().and_then(|pid| i32::try_from(pid).ok()) {+ Some(pid) => Some(pid),+ None => return ToolResult::error("pid must be a 32-bit integer"),+ },+ };+ let session_id = args.opt_str("_session_id");+ let (pid, screenshot) = match self.state.element_cache.screenshot_context_for_zoom(+ requested_pid,+ u64::from(window_id),+ session_id.as_deref(),+ ) {+ Ok(context) => context,+ Err(refusal) => return refusal,+ };let x1 = match args.require_f64("x1") {Ok(v) => v,Err(e) => return e,@@ -77,6 +95,12 @@ impl Tool for ZoomTool {return ToolResult::error("x2 must be > x1 and y2 must be > y1");}+ let (x1, y1, x2, y2) = (+ x1 * screenshot.scale,+ y1 * screenshot.scale,+ x2 * screenshot.scale,+ y2 * screenshot.scale,+ );let state = self.state.clone();let result = tokio::task::spawn_blocking(move || {let png_bytes = crate::capture::screenshot_window_bytes(window_id)?;@@ -87,15 +111,18 @@ impl Tool for ZoomTool {match result {Ok(Ok(crop)) => {// Store zoom context so from_zoom clicks can translate back.- if let Some(p) = pid {- state.zoom_registry.set(- p,- ZoomContext {- origin_x: crop.origin_x,- origin_y: crop.origin_y,- scale_inv: crop.scale_inv,- },- );+ if let Err(refusal) = state.zoom_registry.set_if_current(+ &state.element_cache,+ pid,+ session_id.as_deref(),+ ZoomContext {+ screenshot,+ origin_x: crop.origin_x,+ origin_y: crop.origin_y,+ scale_inv: crop.scale_inv,+ },+ ) {+ return refusal;}let (w, h) = (crop.out_w, crop.out_h);let b64 = BASE64.encode(&crop.jpeg_bytes);@@ -124,3 +151,45 @@ impl Tool for ZoomTool {}}}++#[cfg(test)]+mod tests {+ use super::{def, ToolState};+ use crate::ax::cache::CachedSnapshot;++ #[test]+ fn schema_keeps_pid_optional_for_window_owned_zoom_lookup() {+ let required = def().input_schema["required"].as_array().unwrap();+ assert!(!required.iter().any(|field| field == "pid"));+ assert!(def().input_schema["properties"].get("pid").is_some());+ }++ #[test]+ fn omitted_pid_resolves_owned_window_snapshot() {+ let state = ToolState::new(false, false, None);+ state.element_cache.publish_for_session(+ 42,+ 7,+ CachedSnapshot::from_nodes(&[]),+ Some("zoom-optional-pid-macos"),+ Some(2.0),+ );+ let (pid, context) = state+ .element_cache+ .screenshot_context_for_zoom(None, 7, Some("zoom-optional-pid-macos"))+ .unwrap();+ assert_eq!(pid, 42);+ assert_eq!(context.window_id, 7);+ state.element_cache.publish_for_session(+ 43,+ 7,+ CachedSnapshot::from_nodes(&[]),+ Some("zoom-optional-pid-macos"),+ Some(1.0),+ );+ assert!(state+ .element_cache+ .screenshot_context_for_zoom(None, 7, Some("zoom-optional-pid-macos"))+ .is_err());+ }+}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/capture_admission.rs b/libs/cua-driver/rust/crates/platform-windows/src/capture_admission.rsnew file mode 100644index 0000000000..f3fce5f24e--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-windows/src/capture_admission.rs@@ -0,0 +1,409 @@+use std::sync::Arc;++use cua_driver_core::capture_runtime::{+ CaptureActionError, CaptureActionRequest, CaptureIdParseError, CaptureLookupError,+ CapturePublication, CaptureService, CaptureTarget, EncodedScreenshotDimensions,+ NativeActionDimensions, ScreenshotToActionTransform,+};+use serde_json::Value;++#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub(crate) enum WindowsCaptureTarget {+ Window { pid: u32, window_id: u64 },+ PrimaryDesktop,+}++impl WindowsCaptureTarget {+ fn core(self) -> CaptureTarget {+ match self {+ Self::Window { pid, window_id } => CaptureTarget::Window { pid, window_id },+ Self::PrimaryDesktop => CaptureTarget::PrimaryDesktop,+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq)]+pub(crate) struct CaptureGeometry {+ pub encoded_width: u32,+ pub encoded_height: u32,+ pub native_width: u32,+ pub native_height: u32,+ pub scale_x: f64,+ pub scale_y: f64,+}++impl CaptureGeometry {+ pub(crate) fn new(+ encoded_width: u32,+ encoded_height: u32,+ native_width: u32,+ native_height: u32,+ ) -> anyhow::Result<Self> {+ anyhow::ensure!(+ encoded_width > 0 && encoded_height > 0 && native_width > 0 && native_height > 0,+ "capture dimensions must be positive"+ );+ Ok(Self {+ encoded_width,+ encoded_height,+ native_width,+ native_height,+ scale_x: f64::from(native_width) / f64::from(encoded_width),+ scale_y: f64::from(native_height) / f64::from(encoded_height),+ })+ }+}++pub(crate) fn round_action_point(x: f64, y: f64) -> anyhow::Result<(i32, i32)> {+ fn round(value: f64) -> anyhow::Result<i32> {+ let rounded = value.round();+ anyhow::ensure!(+ rounded.is_finite() && rounded >= f64::from(i32::MIN) && rounded <= f64::from(i32::MAX),+ "capture action coordinate is outside the Windows pixel range"+ );+ Ok(rounded as i32)+ }+ Ok((round(x)?, round(y)?))+}++pub(crate) fn admission_error_code(error: &anyhow::Error) -> &'static str {+ if error.downcast_ref::<CaptureIdParseError>().is_some() {+ return "capture_id_invalid";+ }+ match error.downcast_ref::<CaptureActionError>() {+ Some(CaptureActionError::Lookup(CaptureLookupError::Unknown)) => "capture_not_found",+ Some(CaptureActionError::Lookup(CaptureLookupError::Expired)) => "capture_expired",+ Some(CaptureActionError::Lookup(CaptureLookupError::GenerationMismatch)) => {+ "capture_generation_mismatch"+ }+ Some(CaptureActionError::Lookup(CaptureLookupError::TargetMismatch)) => {+ "capture_target_mismatch"+ }+ Some(CaptureActionError::InvalidScreenshotPoint) => "capture_point_invalid",+ Some(CaptureActionError::InvalidMappedPoint) => "capture_mapping_invalid",+ Some(CaptureActionError::NativeActionFrameMismatch) => "capture_frame_mismatch",+ None => "capture_action_refused",+ }+}++pub(crate) struct WindowsCaptureBridge {+ service: Arc<CaptureService>,+}++impl WindowsCaptureBridge {+ pub(crate) fn new(service: Arc<CaptureService>) -> Arc<Self> {+ Arc::new(Self { service })+ }++ pub(crate) fn publish(+ &self,+ args: &Value,+ png_bytes: Vec<u8>,+ target: WindowsCaptureTarget,+ geometry: CaptureGeometry,+ ) -> anyhow::Result<Option<String>> {+ let binding = self.service.binding_from_args(args)?;+ let encoded_dimensions =+ EncodedScreenshotDimensions::new(geometry.encoded_width, geometry.encoded_height)?;+ let native_action_dimensions =+ NativeActionDimensions::new(geometry.native_width, geometry.native_height)?;+ let screenshot_to_action = ScreenshotToActionTransform::new(+ geometry.scale_x,+ 0.0,+ 0.0,+ geometry.scale_y,+ 0.0,+ 0.0,+ )?;+ let capture_id = self.service.publish(CapturePublication {+ png_bytes,+ target: target.core(),+ encoded_dimensions,+ native_action_dimensions,+ screenshot_to_action,+ session_id: binding.session_id().into(),+ session_generation: binding.session_generation(),+ })?;+ Ok(Some(capture_id.to_string()))+ }++ pub(crate) fn admit_click(+ &self,+ args: &Value,+ target: WindowsCaptureTarget,+ screenshot_x: f64,+ screenshot_y: f64,+ ) -> anyhow::Result<Option<(f64, f64)>> {+ if args.get("capture_id").and_then(Value::as_str).is_none() {+ return Ok(None);+ }+ let current_geometry = live_geometry(target)?;+ self.admit_click_with_geometry(args, target, current_geometry, screenshot_x, screenshot_y)+ }++ fn admit_click_with_geometry(+ &self,+ args: &Value,+ target: WindowsCaptureTarget,+ current_geometry: CaptureGeometry,+ screenshot_x: f64,+ screenshot_y: f64,+ ) -> anyhow::Result<Option<(f64, f64)>> {+ let Some(capture_id) = args.get("capture_id").and_then(Value::as_str) else {+ return Ok(None);+ };+ let binding = self.service.binding_from_args(args)?;+ let admission = self.service.admit_action(CaptureActionRequest {+ capture_id: capture_id.parse()?,+ binding,+ target: target.core(),+ current_native_action_dimensions: NativeActionDimensions::new(+ current_geometry.native_width,+ current_geometry.native_height,+ )?,+ screenshot_x,+ screenshot_y,+ })?;+ Ok(Some((admission.action_x, admission.action_y)))+ }+}++#[cfg(target_os = "windows")]+fn live_geometry(target: WindowsCaptureTarget) -> anyhow::Result<CaptureGeometry> {+ let png = match target {+ WindowsCaptureTarget::Window { pid, window_id } => {+ use windows::Win32::Foundation::HWND;+ use windows::Win32::UI::WindowsAndMessaging::{GetWindowThreadProcessId, IsWindow};+ let hwnd = HWND(window_id as usize as *mut std::ffi::c_void);+ anyhow::ensure!(+ unsafe { IsWindow(hwnd).as_bool() },+ "native window was replaced"+ );+ let mut owner_pid = 0_u32;+ unsafe { GetWindowThreadProcessId(hwnd, Some(&mut owner_pid)) };+ anyhow::ensure!(+ owner_pid == pid,+ "native window owner changed after capture"+ );+ crate::capture::screenshot_window_bytes(window_id)?+ }+ WindowsCaptureTarget::PrimaryDesktop => crate::capture::screenshot_display_bytes()?,+ };+ let (width, height) = crate::capture::png_dimensions_pub(&png)?;+ CaptureGeometry::new(width, height, width, height)+}++#[cfg(not(target_os = "windows"))]+fn live_geometry(_target: WindowsCaptureTarget) -> anyhow::Result<CaptureGeometry> {+ anyhow::bail!("live Windows capture validation is unavailable on this platform")+}++#[cfg(test)]+mod tests {+ use std::sync::Arc;++ use cua_driver_core::capture_runtime::CaptureService;+ use serde_json::json;++ use super::{+ admission_error_code, round_action_point, CaptureGeometry, WindowsCaptureBridge,+ WindowsCaptureTarget,+ };++ fn png() -> Vec<u8> {+ cua_driver_core::image_utils::encode_rgba_to_png(&[10, 20, 30, 255], 1, 1).unwrap()+ }++ fn args() -> serde_json::Value {+ json!({+ "capture_id": "replaced-after-publication",+ "_session_id": "capture-test",+ })+ }++ fn publish(bridge: &WindowsCaptureBridge, target: WindowsCaptureTarget) -> String {+ let mut publication_args = args();+ publication_args+ .as_object_mut()+ .unwrap()+ .remove("capture_id");+ bridge+ .publish(+ &publication_args,+ png(),+ target,+ CaptureGeometry::new(1, 1, 1, 1).unwrap(),+ )+ .unwrap()+ .unwrap()+ }++ #[test]+ fn resized_capture_maps_each_axis_into_native_window_pixels() {+ let geometry = CaptureGeometry::new(800, 450, 1600, 900).unwrap();+ assert_eq!(geometry.scale_x, 2.0);+ assert_eq!(geometry.scale_y, 2.0);+ }++ #[test]+ fn non_uniform_dimensions_preserve_full_affine_scale() {+ let geometry = CaptureGeometry::new(640, 360, 1280, 1080).unwrap();+ assert_eq!(geometry.scale_x, 2.0);+ assert_eq!(geometry.scale_y, 3.0);+ }++ #[test]+ fn admitted_centers_round_once_at_native_dispatch_boundary() {+ assert_eq!(round_action_point(10.49, -20.49).unwrap(), (10, -20));+ assert_eq!(round_action_point(10.5, -20.5).unwrap(), (11, -21));+ assert!(round_action_point(f64::NAN, 0.0).is_err());+ assert!(round_action_point(f64::from(i32::MAX) + 1.0, 0.0).is_err());+ }++ #[test]+ fn target_mismatch_refuses_before_dispatch() {+ let bridge = WindowsCaptureBridge::new(Arc::new(CaptureService::default()));+ let capture_id = publish(+ &bridge,+ WindowsCaptureTarget::Window {+ pid: 7,+ window_id: 70,+ },+ );+ let mut request = args();+ request["capture_id"] = json!(capture_id);+ let admission = bridge.admit_click_with_geometry(+ &request,+ WindowsCaptureTarget::Window {+ pid: 7,+ window_id: 71,+ },+ CaptureGeometry::new(1, 1, 1, 1).unwrap(),+ 0.0,+ 0.0,+ );+ let mut dispatches = 0;+ if admission.is_ok() {+ dispatches += 1;+ }+ assert_eq!(+ admission_error_code(&admission.unwrap_err()),+ "capture_target_mismatch"+ );+ assert_eq!(dispatches, 0);+ }++ #[test]+ fn retired_capture_refuses_before_dispatch() {+ let bridge = WindowsCaptureBridge::new(Arc::new(CaptureService::default()));+ let target = WindowsCaptureTarget::PrimaryDesktop;+ let capture_id = publish(&bridge, target);+ bridge.service.retire_session_id("capture-test");+ let mut request = args();+ request["capture_id"] = json!(capture_id);+ let admission = bridge.admit_click_with_geometry(+ &request,+ target,+ CaptureGeometry::new(1, 1, 1, 1).unwrap(),+ 0.0,+ 0.0,+ );+ let mut dispatches = 0;+ if admission.is_ok() {+ dispatches += 1;+ }+ assert_eq!(+ admission_error_code(&admission.unwrap_err()),+ "capture_not_found"+ );+ assert_eq!(dispatches, 0);+ }++ #[test]+ fn capture_publication_without_a_runtime_session_is_an_error() {+ let bridge = WindowsCaptureBridge::new(Arc::new(CaptureService::default()));+ let error = bridge+ .publish(+ &json!({}),+ png(),+ WindowsCaptureTarget::PrimaryDesktop,+ CaptureGeometry::new(1, 1, 1, 1).unwrap(),+ )+ .unwrap_err();+ assert_eq!(error.to_string(), "capture binding is invalid");+ }++ #[test]+ fn cross_session_capture_refuses_before_dispatch() {+ let bridge = WindowsCaptureBridge::new(Arc::new(CaptureService::default()));+ let target = WindowsCaptureTarget::PrimaryDesktop;+ let capture_id = publish(&bridge, target);+ let request = json!({+ "capture_id": capture_id,+ "_session_id": "another-session",+ });+ let admission = bridge.admit_click_with_geometry(+ &request,+ target,+ CaptureGeometry::new(1, 1, 1, 1).unwrap(),+ 0.0,+ 0.0,+ );+ assert_eq!(+ admission_error_code(&admission.unwrap_err()),+ "capture_generation_mismatch"+ );+ }++ #[test]+ fn live_resize_refuses_before_dispatch_without_consuming_capture() {+ let bridge = WindowsCaptureBridge::new(Arc::new(CaptureService::default()));+ let target = WindowsCaptureTarget::Window {+ pid: 7,+ window_id: 70,+ };+ let capture_id = publish(&bridge, target);+ let mut request = args();+ request["capture_id"] = json!(capture_id);+ let mut dispatches = 0;+ let refusal = bridge.admit_click_with_geometry(+ &request,+ target,+ CaptureGeometry::new(1, 1, 2, 1).unwrap(),+ 0.25,+ 0.25,+ );+ if refusal.is_ok() {+ dispatches += 1;+ }+ assert_eq!(dispatches, 0);+ assert_eq!(+ admission_error_code(&refusal.unwrap_err()),+ "capture_frame_mismatch"+ );+ assert_eq!(+ bridge+ .admit_click_with_geometry(+ &request,+ target,+ CaptureGeometry::new(1, 1, 1, 1).unwrap(),+ 0.25,+ 0.25,+ )+ .unwrap(),+ Some((0.25, 0.25))+ );+ }++ #[test]+ fn ordinary_click_without_capture_id_skips_live_capture_validation() {+ let bridge = WindowsCaptureBridge::new(Arc::new(CaptureService::default()));+ let request = json!({"_session_id": "capture-test"});+ assert_eq!(+ bridge+ .admit_click(&request, WindowsCaptureTarget::PrimaryDesktop, 0.25, 0.25,)+ .unwrap(),+ None+ );+ }+}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/input/delivery.rs b/libs/cua-driver/rust/crates/platform-windows/src/input/delivery.rsindex 7be6deb348..6aba44d95c 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/input/delivery.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/input/delivery.rs@@ -167,11 +167,11 @@ pub fn would_be_silently_dropped(hwnd: u64, kind: EventKind) -> bool {return wpf_drops_event(kind, target_is_foreground(hwnd));}if is_tk_target_window(hwnd) {- // Tk's Windows event loop does not treat posted WM_CHAR/WM_KEYDOWN as- // genuine keyboard input for the focused widget. The messages can be- // accepted by PostMessage while the Entry receives nothing, so refuse- // instead of reporting a false background success.- return matches!(kind, Keystroke | KeyCombo | TextInput);+ // Tk derives button transitions from GetKeyState rather than trusting+ // a posted WM_*BUTTON message. PostMessage therefore reports success+ // without producing a Tk ButtonPress, just as posted key messages can+ // be accepted without reaching the focused widget.+ return tk_drops_event(kind);}// NB: WinUI3 (`WinUIDesktopWin32WindowClass`) is deliberately NOT flagged// here. It looks WPF-like, but its composition input-site does NOT consume@@ -212,6 +212,13 @@ fn wpf_drops_event(kind: EventKind, target_is_foreground: bool) -> bool {|| (!target_is_foreground && matches!(kind, EventKind::Keystroke | EventKind::KeyCombo))}+fn tk_drops_event(kind: EventKind) -> bool {+ matches!(+ kind,+ EventKind::MouseClick | EventKind::Keystroke | EventKind::KeyCombo | EventKind::TextInput+ )+}+fn target_is_foreground(hwnd: u64) -> bool {use windows::Win32::Foundation::HWND;use windows::Win32::UI::WindowsAndMessaging::{GetAncestor, GetForegroundWindow, GA_ROOT};@@ -414,6 +421,17 @@ mod tests {assert!(!wpf_drops_event(EventKind::TextInput, false));assert!(!wpf_drops_event(EventKind::MouseScroll, false));}++ #[test]+ fn tk_refuses_posted_clicks_and_keyboard_events() {+ assert!(tk_drops_event(EventKind::MouseClick));+ assert!(tk_drops_event(EventKind::Keystroke));+ assert!(tk_drops_event(EventKind::KeyCombo));+ assert!(tk_drops_event(EventKind::TextInput));+ assert!(!tk_drops_event(EventKind::MouseMove));+ assert!(!tk_drops_event(EventKind::MouseScroll));+ }+#[test]fn delivery_mode_parses_known_values() {let j = |s: &str| serde_json::json!({"delivery_mode": s});diff --git a/libs/cua-driver/rust/crates/platform-windows/src/lib.rs b/libs/cua-driver/rust/crates/platform-windows/src/lib.rsindex 66d9f13b3f..e74100605a 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/lib.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/lib.rs@@ -68,6 +68,7 @@ pub mod input;#[cfg(target_os = "windows")]pub mod capture;+mod capture_admission;#[cfg(target_os = "windows")]mod clipboard;diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rsindex 29b2f054f7..883d6d499c 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs@@ -507,7 +507,7 @@ fn is_windowless_desktop_action(args: &serde_json::Value) -> bool {has_num("x") && has_num("y")}-// ── DriverConfig + ResizeRegistry + ZoomRegistry ─────────────────────────────+// ── DriverConfig + ZoomRegistry ─────────────────────────────────────────────#[derive(Clone)]pub struct DriverConfig {@@ -547,83 +547,67 @@ pub fn load_driver_config() -> DriverConfig {cfg}-pub struct ResizeRegistry {- ratios: std::sync::Mutex<std::collections::HashMap<u32, f64>>,-}--impl ResizeRegistry {- pub fn new() -> Self {- Self {- ratios: std::sync::Mutex::new(Default::default()),- }- }- pub fn set_ratio(&self, pid: u32, ratio: f64) {- self.ratios.lock().unwrap().insert(pid, ratio);- }- pub fn clear_ratio(&self, pid: u32) {- self.ratios.lock().unwrap().remove(&pid);- }- pub fn ratio(&self, pid: u32) -> Option<f64> {- self.ratios.lock().unwrap().get(&pid).copied()- }-}--/// Per-process zoom context — stores padded crop origin and resize scale from-/// the most recent `zoom` call so `click(from_zoom=true)` can translate-/// zoom-image pixel coordinates back to full-window coordinates.-#[derive(Clone, Copy, Debug)]-pub struct ZoomContext {- pub origin_x: f64,- pub origin_y: f64,- /// Inverse resize scale: `cw / out_w` (1.0 = no downscale).- pub scale_inv: f64,-}--impl ZoomContext {- pub fn zoom_to_window(&self, px: f64, py: f64) -> (f64, f64) {- (- self.origin_x + px * self.scale_inv,- self.origin_y + py * self.scale_inv,- )- }-}--pub struct ZoomRegistry {- inner: std::sync::Mutex<std::collections::HashMap<u32, ZoomContext>>,-}--impl ZoomRegistry {- pub fn new() -> Self {- Self {- inner: std::sync::Mutex::new(Default::default()),- }- }- pub fn set(&self, pid: u32, ctx: ZoomContext) {- self.inner.lock().unwrap().insert(pid, ctx);- }- pub fn get(&self, pid: u32) -> Option<ZoomContext> {- self.inner.lock().unwrap().get(&pid).copied()- }-}+use cua_driver_core::element_cache::{+ SnapshotBoundZoomContext as ZoomContext, SnapshotBoundZoomRegistry as ZoomRegistry,+};pub struct ToolState {pub element_cache: Arc<ElementCache>,pub cursor_registry: Arc<CursorRegistry>,- pub resize_registry: Arc<ResizeRegistry>,pub zoom_registry: Arc<ZoomRegistry>,pub config: Arc<RwLock<DriverConfig>>,+ capture_bridge: Option<Arc<crate::capture_admission::WindowsCaptureBridge>>,}impl ToolState {- pub fn new() -> Arc<Self> {+ pub fn new(+ capture_service: Option<Arc<cua_driver_core::capture_runtime::CaptureService>>,+ ) -> Arc<Self> {Arc::new(Self {element_cache: Arc::new(ElementCache::new()),cursor_registry: Arc::new(CursorRegistry::new()),- resize_registry: Arc::new(ResizeRegistry::new()),zoom_registry: Arc::new(ZoomRegistry::new()),config: Arc::new(RwLock::new(load_driver_config())),+ capture_bridge: capture_service+ .map(crate::capture_admission::WindowsCaptureBridge::new),})}++ fn zoom_context(+ &self,+ args: &Value,+ pid: u32,+ window_id: Option<u64>,+ ) -> Result<ZoomContext, ToolResult> {+ self.zoom_registry.resolve(+ &self.element_cache,+ pid as i32,+ window_id,+ args.get("_session_id").and_then(Value::as_str),+ )+ }+}++fn screenshot_scale(+ state: &ToolState,+ args: &Value,+ pid: u32,+ window_id: Option<u64>,+) -> Result<f64, ToolResult> {+ state.element_cache.screenshot_scale_or_refusal(+ pid as i32,+ window_id,+ args.get("_session_id").and_then(Value::as_str),+ )+}++fn capture_admission_refusal(error: anyhow::Error) -> ToolResult {+ let code = crate::capture_admission::admission_error_code(&error);+ ToolResult::error(format!("Capture-bound click refused: {error}")).with_structured(json!({+ "code": code,+ "effect": "refused",+ "detail": error.to_string(),+ }))}// ── list_apps ────────────────────────────────────────────────────────────────@@ -1118,6 +1102,17 @@ fn fold_max_dimension(ceiling: u32, per_call: Option<u32>) -> u32 {}}+/// Resolve the screenshot size limit. The canonical per-call override wins+/// outright, including `0` for native resolution. When omitted, preserve the+/// configured ceiling and legacy `max_dimension` folding behavior.+fn resolve_max_image_dimension(+ configured: u32,+ max_image_dimension: Option<u32>,+ legacy_max_dimension: Option<u32>,+) -> u32 {+ max_image_dimension.unwrap_or_else(|| fold_max_dimension(configured, legacy_max_dimension))+}+/// Build a single structured element entry for `get_window_state`./// Returns `None` when the node has no `element_index` (non-actionable rows).fn build_element_entry(@@ -1183,6 +1178,41 @@ pub struct GetWindowStateTool {static GWS_DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();+#[cfg(test)]+mod get_window_state_max_image_dimension_tests {+ use super::{resolve_max_image_dimension, GetWindowStateTool, ToolState};+ use cua_driver_core::tool::Tool;++ #[test]+ fn canonical_override_wins_and_zero_requests_native_resolution() {+ assert_eq!(resolve_max_image_dimension(1568, None, None), 1568);+ assert_eq!(resolve_max_image_dimension(1568, Some(800), None), 800);+ assert_eq!(resolve_max_image_dimension(800, Some(1568), None), 1568);+ assert_eq!(resolve_max_image_dimension(1568, Some(0), None), 0);+ assert_eq!(+ resolve_max_image_dimension(1568, Some(1200), Some(400)),+ 1200+ );+ }++ #[test]+ fn omitted_canonical_override_preserves_legacy_folding() {+ assert_eq!(resolve_max_image_dimension(1568, None, Some(800)), 800);+ assert_eq!(resolve_max_image_dimension(800, None, Some(1568)), 800);+ assert_eq!(resolve_max_image_dimension(0, None, Some(800)), 800);+ }++ #[test]+ fn schema_advertises_canonical_override_and_native_resolution() {+ let tool = GetWindowStateTool {+ state: ToolState::new(None),+ };+ let property = &tool.def().input_schema["properties"]["max_image_dimension"];+ assert_eq!(property["type"], "integer");+ assert_eq!(property["minimum"], 0);+ }+}+#[async_trait]impl Tool for GetWindowStateTool {fn def(&self) -> &ToolDef {@@ -1227,8 +1257,9 @@ impl Tool for GetWindowStateTool {(window_bounds, app_name, window_title) — the capture-only path for a \live window preview / picture-in-picture. Setting BOTH \`include_accessibility_tree:false` and `include_screenshot:false` is an \- error. Optional `max_dimension` caps the returned screenshot's long edge \- in pixels for a cheap thumbnail.\n\n\+ error. Optional `max_image_dimension` overrides the configured screenshot \+ long-edge limit for this call; pass 0 for native resolution. Legacy \+ `max_dimension` remains a cap on the configured limit.\n\n\Uses `IUIAutomationCacheRequest` to batch-fetch all element properties in a \single COM call (Chrome's ~5000-element tree returns in ~2-3s instead of \timing out at 4s with per-property RPCs).\n\n\@@ -1257,7 +1288,8 @@ impl Tool for GetWindowStateTool {"query":{"type":"string","description":"Optional case-insensitive substring. Projects both tree_markdown and structured elements to matches plus ancestors while preserving original indices. Compare total_element_count with returned_element_count."},"max_elements":{"type":"integer","minimum":1,"description":"Cap on the total number of UIA nodes walked. Truncates depth-first; markdown and structured elements truncate together. Omit for the default (5 000). Lower for Electron / large web apps that produce 10k+ element trees."},"max_depth":{"type":"integer","minimum":1,"description":"Cap on the UIA-tree walk depth. Nodes whose rendered indent would exceed this are omitted. Omit for the default (25). Lower for deep menu / Electron trees."},- "max_dimension":{"type":"integer","minimum":1,"description":"Optional cap on the returned screenshot's long edge, in pixels (aspect ratio preserved) — the cheap path for a small preview. Applied on top of the configured max_image_dimension ceiling; the tighter wins. Omit for the configured default."}+ "max_image_dimension":{"type":"integer","minimum":0,"description":"Per-call long-edge limit for the returned screenshot, in pixels (aspect ratio preserved). Explicit values override configured behavior; 0 returns native resolution. Omit to preserve the configured default."},+ "max_dimension":{"type":"integer","minimum":1,"description":"Legacy optional cap on the returned screenshot's long edge, in pixels (aspect ratio preserved). Applied on top of the configured max_image_dimension ceiling when max_image_dimension is omitted; the tighter wins."}},"additionalProperties":false}),// Swift annotation: idempotent: false (each call is a fresh snapshot).read_only: true, destructive: false, idempotent: false, open_world: false,@@ -1318,15 +1350,28 @@ impl Tool for GetWindowStateTool {.ok().flatten();use cua_driver_core::tool_args::ArgsExt;- // Optional per-call cap on the returned screenshot's long edge, folded- // with the configured ceiling (the tighter wins).+ // The canonical per-call value overrides all configured limits,+ // including `0` for native resolution. The legacy field retains its+ // previous cap-folding behavior when the canonical field is omitted.+ let max_image_dimension = match args.get("max_image_dimension") {+ Some(value) => match value.as_u64().and_then(|v| u32::try_from(v).ok()) {+ Some(value) => Some(value),+ None => {+ return ToolResult::error(+ "max_image_dimension must be an integer between 0 and 4294967295.",+ )+ }+ },+ None => None,+ };let max_dimension = args.get("max_dimension").and_then(|v| v.as_u64())- .map(|v| v.max(1) as u32);+ .and_then(|v| u32::try_from(v).ok())+ .map(|v| v.max(1));let max_dim = {let cfg = self.state.config.read().unwrap();- fold_max_dimension(cfg.max_image_dimension, max_dimension)+ resolve_max_image_dimension(cfg.max_image_dimension, max_image_dimension, max_dimension)};// `capture_mode` is DEPRECATED and ignored — get_window_state always// returns BOTH the UIA tree and a screenshot now, so the agent grounds on@@ -1336,6 +1381,7 @@ impl Tool for GetWindowStateTool {// We don't read the arg; it stays in the schema only so old callers don't// trip additionalProperties:false.let query = args.opt_str("query");+ let session_id = args.opt_str("_session_id");let screenshot_out_file = args.opt_str("screenshot_out_file");// Optional caps — when omitted, fall back to the walker's built-in// defaults (#22865). minimum:1 enforced in the schema, but defend@@ -1412,21 +1458,24 @@ impl Tool for GetWindowStateTool {let (screenshot, screenshot_err) = if do_shot {match crate::capture::screenshot_window_bytes(hwnd) {Ok(raw) => {- let orig_w = crate::capture::png_dimensions_pub(&raw)- .map(|(w, _)| w)- .unwrap_or(0);+ let (native_w, native_h) = crate::capture::png_dimensions_pub(&raw)?;let png = crate::capture::resize_png_if_needed(&raw, max_dim)?;let (w, h) = crate::capture::png_dimensions_pub(&png)?;- let original_w = if w < orig_w { Some(orig_w) } else { None };// `screenshot_out_file` set (any mode) → write to disk and// surface the path, never embed bytes. Otherwise (vision,// no out_file) → embed base64.if let Some(ref path) = out_file {std::fs::write(path, &png)?;- (Some((None, Some(path.clone()), w, h, original_w)), None)+ (+ Some((None, Some(path.clone()), w, h, native_w, native_h, png)),+ None,+ )} else {use base64::{engine::general_purpose::STANDARD as B64, Engine as _};- (Some((Some(B64.encode(&png)), None, w, h, original_w)), None)+ (+ Some((Some(B64.encode(&png)), None, w, h, native_w, native_h, png)),+ None,+ )}}Err(e) => (None, Some(format!("{e}"))),@@ -1466,6 +1515,10 @@ impl Tool for GetWindowStateTool {Ok((tree_opt, screenshot_opt, screenshot_err)) => {let mut content = Vec::new();let mut structured = json!({ "window_id": hwnd, "pid": pid });+ let screenshot_scale = screenshot_opt+ .as_ref()+ .map(|(_, _, w, _, native_w, _, _)| *native_w as f64 / *w as f64);+ let mut published_snapshot = false;if let Some((tr, payload)) = tree_opt {let is_msaa = tr.nodes.iter().any(|node| node.msaa_role.is_some());@@ -1486,7 +1539,22 @@ impl Tool for GetWindowStateTool {structured["tree_markdown"] = json!(tr.tree_markdown);let snapshot_id = (!observation_only)- .then(|| state.element_cache.publish(pid as i32, hwnd, payload));+ .then(|| {+ state.element_cache.publish_for_session(+ pid as i32,+ hwnd,+ payload,+ session_id.as_deref(),+ screenshot_scale,+ )+ })+ .flatten();+ published_snapshot = snapshot_id.is_some();+ if let Some(snapshot_id) = snapshot_id {+ state+ .zoom_registry+ .retire_replaced(pid as i32, hwnd, snapshot_id);+ }// Structured `elements` array — preferred consumption// path. Shape matches the cross-platform spec:@@ -1553,16 +1621,59 @@ impl Tool for GetWindowStateTool {}}- if let Some((b64_opt, file_path, w, h, orig_w)) = screenshot_opt {- if !observation_only {- if let Some(ow) = orig_w {- if w > 0 {- state.resize_registry.set_ratio(pid, ow as f64 / w as f64);+ if !observation_only && !published_snapshot && screenshot_scale.is_some() {+ let payload = crate::uia::cache::CachedSnapshot::from_nodes(+ &[],+ crate::uia::cache::SnapshotKind::Uia,+ );+ if let Some(snapshot_id) = state.element_cache.publish_for_session(+ pid as i32,+ hwnd,+ payload,+ session_id.as_deref(),+ screenshot_scale,+ ) {+ state+ .zoom_registry+ .retire_replaced(pid as i32, hwnd, snapshot_id);+ }+ }++ if let Some((b64_opt, file_path, w, h, native_w, native_h, png)) = screenshot_opt {+ let capture_id = if !observation_only {+ if let Some(bridge) = &state.capture_bridge {+ let geometry = match crate::capture_admission::CaptureGeometry::new(+ w, h, native_w, native_h,+ ) {+ Ok(geometry) => geometry,+ Err(error) => {+ return ToolResult::error(format!(+ "Window capture geometry is invalid: {error}"+ ))+ }+ };+ match bridge.publish(+ &args,+ png,+ crate::capture_admission::WindowsCaptureTarget::Window {+ pid,+ window_id: hwnd,+ },+ geometry,+ ) {+ Ok(capture_id) => capture_id,+ Err(error) => {+ return ToolResult::error(format!(+ "Window capture publication failed: {error}"+ ))+ }}} else {- state.resize_registry.clear_ratio(pid);+ None}- }+ } else {+ None+ };// base64 is embedded only when no out_file was given (vision// path). With `screenshot_out_file` the bytes went to disk and// we surface the path instead — never both. Keep a text content@@ -1581,6 +1692,9 @@ impl Tool for GetWindowStateTool {// the structured payload so consumers don't have to sniff// magic bytes off the base64 to know the format.structured["screenshot_mime_type"] = json!("image/png");+ if let Some(capture_id) = capture_id {+ structured["capture_id"] = json!(capture_id);+ }if let Some(fp) = file_path {structured["screenshot_file_path"] = json!(fp);}@@ -3112,6 +3226,7 @@ impl Tool for ClickTool {"element_index": cua_driver_core::tool_schema::element_index_schema(),"element_token": cua_driver_core::tool_schema::element_token_schema(),"snapshot_id": cua_driver_core::tool_schema::snapshot_id_schema(),+ "capture_id":{"type":"string","minLength":1,"description":"Optional ID from get_window_state or get_desktop_state. When present, x and y are admitted against that exact capture and the ID is consumed before native dispatch."},"x":{"type":"number","description":"X in window-local screenshot pixels — same space as the PNG get_window_state returns. Must be provided together with y."},"y":{"type":"number","description":"Y in window-local screenshot pixels. Must be provided together with x."},"button": cua_driver_core::tool_schema::button_schema(),@@ -3166,8 +3281,32 @@ impl Tool for ClickTool {.with_structured(json!({ "code": "invalid_arguments" }));}let modifiers: Vec<String> = args.str_array("modifier");- let sx = input.x as i32;- let sy = input.y as i32;+ let capture_point = match self.state.capture_bridge.as_ref() {+ Some(bridge) => match bridge.admit_click(+ &args,+ crate::capture_admission::WindowsCaptureTarget::PrimaryDesktop,+ input.x,+ input.y,+ ) {+ Ok(point) => point,+ Err(error) => return capture_admission_refusal(error),+ },+ None if args.get("capture_id").is_some() => {+ return capture_admission_refusal(anyhow::anyhow!(+ "capture service is unavailable"+ ))+ }+ None => None,+ };+ let (sx, sy) = match capture_point {+ Some((action_x, action_y)) => {+ match crate::capture_admission::round_action_point(action_x, action_y) {+ Ok(point) => point,+ Err(error) => return capture_admission_refusal(error),+ }+ }+ None => (input.x as i32, input.y as i32),+ };// Resolve the application window before moving the agent cursor.// WindowFromPoint can return a transparent layered overlay, and the@@ -3286,19 +3425,6 @@ impl Tool for ClickTool {}}));}- // For every non-foreground click, mark the target window- // non-activatable (WS_EX_NOACTIVATE) for the duration so a target that- // self-activates in its UIA-Invoke / click handler (WPF- // `UIElement.Focus()`, XAML, Tauri/WebView2) CANNOT steal the user's- // foreground — the window still receives the click. Held for the whole- // invoke; a no-op for delivery_mode:"foreground" (which wants the swap) and- // when no window_id was given.- let _noact = match (delivery != DeliveryMode::Foreground, hwnd_opt) {- (true, Some(h)) => Some(crate::input::NoActivateGuard::arm(- windows::Win32::Foundation::HWND(h as *mut _),- )),- _ => None,- };// Optional `action` arg picks among the actions exposed in the// accessibility tree. Today this only changes behavior for MSAA// BUTTONDROPDOWN: `"expand"` clicks the right-edge (dropdown arrow@@ -3333,6 +3459,47 @@ impl Tool for ClickTool {}}};+ let capture_point = if args.get("capture_id").is_some() {+ if elem_idx.is_some()+ || x.is_none()+ || y.is_none()+ || hwnd_opt.is_none()+ || args.get("from_zoom").and_then(Value::as_bool) == Some(true)+ {+ return capture_admission_refusal(anyhow::anyhow!(+ "capture_id requires x, y, and an exact window_id; element and zoom coordinates are not capture-bound"+ ));+ }+ let Some(bridge) = &self.state.capture_bridge else {+ return capture_admission_refusal(anyhow::anyhow!(+ "capture service is unavailable"+ ));+ };+ match bridge.admit_click(+ &args,+ crate::capture_admission::WindowsCaptureTarget::Window {+ pid,+ window_id: hwnd,+ },+ x.unwrap(),+ y.unwrap(),+ ) {+ Ok(Some(point)) => Some(point),+ Ok(None) => unreachable!("capture_id was present"),+ Err(error) => return capture_admission_refusal(error),+ }+ } else {+ None+ };++ // Arm this only after capture admission so stale or mismatched IDs have+ // no native side effect before the click is refused.+ let _noact = match (delivery != DeliveryMode::Foreground, hwnd_opt) {+ (true, Some(h)) => Some(crate::input::NoActivateGuard::arm(+ windows::Win32::Foundation::HWND(h as *mut _),+ )),+ _ => None,+ };if let Some(idx) = elem_idx {// ── MSAA dispatch (SAL/VCL targets) ────────────────────────────@@ -3856,20 +4023,28 @@ impl Tool for ClickTool {.get("from_zoom").and_then(|v| v.as_bool()).unwrap_or(false);- if from_zoom {- match self.state.zoom_registry.get(pid) {- Some(ctx) => {+ if let Some((mapped_x, mapped_y)) = capture_point {+ let (mapped_x, mapped_y) =+ match crate::capture_admission::round_action_point(mapped_x, mapped_y) {+ Ok(point) => point,+ Err(error) => return capture_admission_refusal(error),+ };+ px = f64::from(mapped_x);+ py = f64::from(mapped_y);+ } else if from_zoom {+ match self.state.zoom_context(&args, pid, Some(hwnd)) {+ Ok(ctx) => {let (wx, wy) = ctx.zoom_to_window(px, py);px = wx;py = wy;}- None => {- return ToolResult::error(format!(- "from_zoom=true but no zoom context for pid {pid}. Call zoom first."- ))- }+ Err(refusal) => return refusal,}- } else if let Some(ratio) = self.state.resize_registry.ratio(pid) {+ } else if !args.bool_or("_native_coordinates", false) {+ let ratio = match screenshot_scale(&self.state, &args, pid, Some(hwnd)) {+ Ok(ratio) => ratio,+ Err(refusal) => return refusal,+ };px *= ratio;py *= ratio;}@@ -4342,8 +4517,7 @@ mod background_element_click_record_tests {/// on the same pixel a px-click would. `Ok(())` on success; `Err(ToolResult)`/// short-circuits the caller. Mirrors macOS `tools::focus_by_pixel`.#[allow(clippy::too_many_arguments)]-async fn focus_by_pixel(- state: &Arc<ToolState>,+fn focus_by_pixel_click_args(pid: u32,window_id: Option<u64>,x: f64,@@ -4352,7 +4526,8 @@ async fn focus_by_pixel(session: Option<String>,session_id: Option<String>,from_zoom: bool,-) -> Result<(), ToolResult> {+ native_coordinates: bool,+) -> Value {let mut click_args = json!({"pid": pid, "x": x, "y": y,"delivery_mode": if foreground { "foreground" } else { "background" },@@ -4369,6 +4544,36 @@ async fn focus_by_pixel(if from_zoom {click_args["from_zoom"] = json!(true);}+ if native_coordinates {+ click_args["_native_coordinates"] = json!(true);+ }+ click_args+}++#[allow(clippy::too_many_arguments)]+async fn focus_by_pixel(+ state: &Arc<ToolState>,+ pid: u32,+ window_id: Option<u64>,+ x: f64,+ y: f64,+ foreground: bool,+ session: Option<String>,+ session_id: Option<String>,+ from_zoom: bool,+ native_coordinates: bool,+) -> Result<(), ToolResult> {+ let click_args = focus_by_pixel_click_args(+ pid,+ window_id,+ x,+ y,+ foreground,+ session,+ session_id,+ from_zoom,+ native_coordinates,+ );let focus = ClickTool {state: state.clone(),}@@ -4603,6 +4808,7 @@ impl Tool for TypeTextTool {args.opt_str("session"),args.opt_str("_session_id"),from_zoom,+ false,).await{@@ -5361,6 +5567,7 @@ impl Tool for PressKeyTool {args.opt_str("session"),args.opt_str("_session_id"),from_zoom,+ false,).await{@@ -5441,11 +5648,7 @@ impl Tool for PressKeyTool {Ok(point) => point,Err(result) => return result,};- let (mut px, mut py) = screen_to_bitmap(hwnd, cx, cy);- if let Some(ratio) = self.state.resize_registry.ratio(pid) {- px = (px as f64 / ratio).round() as i32;- py = (py as f64 / ratio).round() as i32;- }+ let (px, py) = screen_to_bitmap(hwnd, cx, cy);// Release the outer guard before the shared pixel helper. ClickTool// owns a guard around the click itself, then releases it before its// renderer settle period. This is the exact route already proven by@@ -5461,6 +5664,7 @@ impl Tool for PressKeyTool {args.opt_str("session"),args.opt_str("_session_id"),false,+ true,).await{@@ -5798,6 +6002,7 @@ impl Tool for HotkeyTool {args.opt_str("session"),args.opt_str("_session_id"),from_zoom,+ false,).await{@@ -6964,19 +7169,19 @@ impl Tool for DoubleClickTool {.and_then(|v| v.as_bool()).unwrap_or(false);if from_zoom {- match self.state.zoom_registry.get(pid) {- Some(ctx) => {+ match self.state.zoom_context(&args, pid, Some(hwnd)) {+ Ok(ctx) => {let (wx, wy) = ctx.zoom_to_window(px, py);px = wx;py = wy;}- None => {- return ToolResult::error(format!(- "from_zoom=true but no zoom context for pid {pid}. Call zoom first."- ))- }+ Err(refusal) => return refusal,}- } else if let Some(ratio) = self.state.resize_registry.ratio(pid) {+ } else {+ let ratio = match screenshot_scale(&self.state, &args, pid, Some(hwnd)) {+ Ok(ratio) => ratio,+ Err(refusal) => return refusal,+ };px *= ratio;py *= ratio;}@@ -7332,19 +7537,19 @@ impl Tool for RightClickTool {.and_then(|v| v.as_bool()).unwrap_or(false);if from_zoom {- match self.state.zoom_registry.get(pid) {- Some(ctx) => {+ match self.state.zoom_context(&args, pid, Some(hwnd)) {+ Ok(ctx) => {let (wx, wy) = ctx.zoom_to_window(px, py);px = wx;py = wy;}- None => {- return ToolResult::error(format!(- "from_zoom=true but no zoom context for pid {pid}. Call zoom first."- ))- }+ Err(refusal) => return refusal,}- } else if let Some(ratio) = self.state.resize_registry.ratio(pid) {+ } else {+ let ratio = match screenshot_scale(&self.state, &args, pid, Some(hwnd)) {+ Ok(ratio) => ratio,+ Err(refusal) => return refusal,+ };px *= ratio;py *= ratio;}@@ -7580,8 +7785,8 @@ impl Tool for DragTool {let from_zoom = args.bool_or("from_zoom", false);if from_zoom {- match self.state.zoom_registry.get(pid) {- Some(ctx) => {+ match self.state.zoom_context(&args, pid, hwnd_opt) {+ Ok(ctx) => {let (wx, wy) = ctx.zoom_to_window(from_x, from_y);let (wx2, wy2) = ctx.zoom_to_window(to_x, to_y);from_x = wx;@@ -7589,13 +7794,13 @@ impl Tool for DragTool {to_x = wx2;to_y = wy2;}- None => {- return ToolResult::error(format!(- "from_zoom=true but no zoom context for pid {pid}. Call zoom first."- ))- }+ Err(refusal) => return refusal,}- } else if let Some(ratio) = self.state.resize_registry.ratio(pid) {+ } else {+ let ratio = match screenshot_scale(&self.state, &args, pid, hwnd_opt) {+ Ok(ratio) => ratio,+ Err(refusal) => return refusal,+ };from_x *= ratio;from_y *= ratio;to_x *= ratio;@@ -7894,7 +8099,9 @@ impl Tool for GetScreenSizeTool {/// Mirrors the `get_window_state` vision branch's ToolResult shape: an/// `image_png` content part (or a written-out file path), a text summary line,/// and a `structuredContent` object.-pub struct GetDesktopStateTool;+pub struct GetDesktopStateTool {+ state: Arc<ToolState>,+}static GDS_DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();#[async_trait]@@ -7920,6 +8127,7 @@ impl Tool for GetDesktopStateTool {async fn invoke(&self, args: Value) -> ToolResult {use cua_driver_core::protocol::Content;+ let binding_args = args.clone();let input = match parse_typed_input::<GetDesktopStateInput>("get_desktop_state", args) {Ok(input) => input,Err(error) => return error,@@ -7933,21 +8141,21 @@ impl Tool for GetDesktopStateTool {// blocking GDI capture off the async runtime.let out_file = screenshot_out_file.clone();let res = tokio::task::spawn_blocking(- move || -> anyhow::Result<(Option<String>, Option<String>, u32, u32)> {+ move || -> anyhow::Result<(Option<String>, Option<String>, u32, u32, Vec<u8>)> {use base64::{engine::general_purpose::STANDARD as BASE64, Engine};let png = crate::capture::screenshot_display_bytes()?;let (w, h) = crate::capture::png_dimensions_pub(&png)?;if let Some(ref path) = out_file {std::fs::write(path, &png)?;- Ok((None, Some(path.clone()), w, h))+ Ok((None, Some(path.clone()), w, h, png))} else {- Ok((Some(BASE64.encode(&png)), None, w, h))+ Ok((Some(BASE64.encode(&png)), None, w, h, png))}},).await;- let (b64_opt, file_path, screenshot_width, screenshot_height) = match res {+ let (b64_opt, file_path, screenshot_width, screenshot_height, png) = match res {Ok(Ok(v)) => v,Ok(Err(e)) => return ToolResult::error(format!("Desktop screenshot failed: {e}")),Err(e) => return ToolResult::error(format!("Desktop screenshot task error: {e}")),@@ -7976,6 +8184,35 @@ impl Tool for GetDesktopStateTool {},"screenshot_mime_type": "image/png",});+ if let Some(bridge) = &self.state.capture_bridge {+ let geometry = match crate::capture_admission::CaptureGeometry::new(+ screenshot_width,+ screenshot_height,+ screenshot_width,+ screenshot_height,+ ) {+ Ok(geometry) => geometry,+ Err(error) => {+ return ToolResult::error(format!(+ "Desktop capture geometry is invalid: {error}"+ ))+ }+ };+ match bridge.publish(+ &binding_args,+ png,+ crate::capture_admission::WindowsCaptureTarget::PrimaryDesktop,+ geometry,+ ) {+ Ok(Some(capture_id)) => structured["capture_id"] = json!(capture_id),+ Ok(None) => {}+ Err(error) => {+ return ToolResult::error(format!(+ "Desktop capture publication failed: {error}"+ ))+ }+ }+ }if let Some(ref fp) = file_path {structured["screenshot_file_path"] = json!(fp);}@@ -8837,13 +9074,17 @@ impl Tool for ZoomTool {A 20% padding is automatically added on every side of the requested region so \the target remains visible even if the caller's coordinates are slightly off.\n\n\After a zoom, pass `from_zoom=true` to click/type_text to auto-translate \- coordinates back to full-window space.\n\n\+ coordinates back to full-window space. Coordinate actions return \+ `screenshot_context_missing` when the latest snapshot does not contain a \+ screenshot owned by this session. `from_zoom` actions return \+ `zoom_context_missing` when the zoom was never created or was replaced; call \+ `get_window_state`, then `zoom`, again on the same connection.\n\n\Windows-specific: `window_id` is the canonical addressing field (HWND). \- `pid` is also required (used to scope the zoom translation registry, matching \- Swift's per-pid zoom context).".into(),+ `pid` is preferred when available; otherwise the driver resolves the unique \+ current snapshot owned by this session and window.".into(),input_schema: json!({"type":"object","required":["window_id","x1","y1","x2","y2"],"properties":{- "pid":{"type":"integer","description":"Target process ID. Validated in code (an explicit \"Missing required integer field pid\" error when absent); kept out of `required` to match the shared cross-platform zoom contract."},+ "pid":{"type":"integer","description":"Optional target process ID. When omitted, the unique current snapshot for this session and HWND is used."},"window_id":{"type":"integer","description":"HWND of the target window."},"x1":{"type":"number","description":"Left edge of the region (resized-image pixels)."},"y1":{"type":"number","description":"Top edge of the region (resized-image pixels)."},@@ -8857,11 +9098,13 @@ impl Tool for ZoomTool {}async fn invoke(&self, args: Value) -> ToolResult {- let raw_pid = match args.get("pid").and_then(|v| v.as_i64()) {- Some(p) => p,- None => return ToolResult::error("Missing required integer field pid."),+ let requested_pid = match args.get("pid") {+ None => None,+ Some(value) => match value.as_i64().and_then(|pid| i32::try_from(pid).ok()) {+ Some(pid) => Some(pid),+ None => return ToolResult::error("pid must be a 32-bit integer"),+ },};- let pid = Some(raw_pid as u32);let hwnd = match args.get("window_id").and_then(|v| v.as_u64()) {Some(v) => v,None => return ToolResult::error("Missing required integer field window_id."),@@ -8890,12 +9133,21 @@ impl Tool for ZoomTool {// runs on a fresh native-resolution capture. Scale by the stored resize// ratio so the crop lands on the intended region; the zoom context then// holds native-pixel values, which is what `from_zoom` clicks expect.- let ratio = self- .state- .resize_registry- .ratio(raw_pid as u32)- .unwrap_or(1.0);- let (nx1, ny1, nx2, ny2) = (x1 * ratio, y1 * ratio, x2 * ratio, y2 * ratio);+ let session_id = args.opt_str("_session_id");+ let (pid, screenshot) = match self.state.element_cache.screenshot_context_for_zoom(+ requested_pid,+ hwnd,+ session_id.as_deref(),+ ) {+ Ok(context) => context,+ Err(refusal) => return refusal,+ };+ let (nx1, ny1, nx2, ny2) = (+ x1 * screenshot.scale,+ y1 * screenshot.scale,+ x2 * screenshot.scale,+ y2 * screenshot.scale,+ );let state = self.state.clone();let result = tokio::task::spawn_blocking(move || {@@ -8906,15 +9158,18 @@ impl Tool for ZoomTool {match result {Ok(Ok(crop)) => {- if let Some(p) = pid {- state.zoom_registry.set(- p,- ZoomContext {- origin_x: crop.origin_x,- origin_y: crop.origin_y,- scale_inv: crop.scale_inv,- },- );+ if let Err(refusal) = state.zoom_registry.set_if_current(+ &state.element_cache,+ pid,+ session_id.as_deref(),+ ZoomContext {+ screenshot,+ origin_x: crop.origin_x,+ origin_y: crop.origin_y,+ scale_inv: crop.scale_inv,+ },+ ) {+ return refusal;}use base64::{engine::general_purpose::STANDARD as B64, Engine as _};let b64 = B64.encode(&crop.jpeg_bytes);@@ -10038,7 +10293,8 @@ pub fn build_registry_with_provider(compat: bool,provider: Option<std::sync::Arc<dyn cua_driver_core::consent::ProtectedConsentProvider>>,) -> ToolRegistry {- let state = ToolState::new();+ let mut r = ToolRegistry::new_with_protected_consent_provider(provider);+ let state = ToolState::new(Some(r.capture_service()));let cursor_outcome_reader = {let cursor_registry = state.cursor_registry.clone();cua_driver_core::session::register_scoped_cursor_outcome_reader(std::sync::Arc::new(@@ -10087,8 +10343,12 @@ pub fn build_registry_with_provider(// deregisters when that runtime's registry is dropped. Mirrors the macOS// `register_all` session_end hook (platform-macos/src/tools/mod.rs).let cursor_registry = state.cursor_registry.clone();+ let element_cache = state.element_cache.clone();+ let zoom_registry = state.zoom_registry.clone();let session_end_hook =cua_driver_core::session::register_scoped_session_end_hook(move |session_id| {+ zoom_registry.retire_session(session_id);+ element_cache.retire_session_screenshots(session_id);cursor_registry.remove(session_id);crate::overlay::remove_cursor(session_id.to_owned());});@@ -10097,7 +10357,6 @@ pub fn build_registry_with_provider(crate::overlay::revive_cursor(session_id.to_owned());});- let mut r = ToolRegistry::new_with_protected_consent_provider(provider);r.retain_cursor_outcome_reader(cursor_outcome_reader);r.retain_session_end_hook(session_end_hook);r.retain_session_revive_hook(session_revive_hook);@@ -10214,7 +10473,9 @@ pub fn build_registry_with_provider(// depend on them via `Tool` trait reflection.let _ = compat; // formerly drove the ScreenshotCompatTool branchr.register(Box::new(GetScreenSizeTool));- r.register(Box::new(GetDesktopStateTool));+ r.register(Box::new(GetDesktopStateTool {+ state: state.clone(),+ }));r.register(Box::new(GetCursorPositionTool));r.register(Box::new(MoveCursorTool {state: state.clone(),@@ -10596,7 +10857,7 @@ mod click_button_schema_tests {#[test]fn schema_advertises_button_enum() {let tool = ClickTool {- state: super::ToolState::new(),+ state: super::ToolState::new(None),};let d = tool.def();let props = d.input_schema.get("properties").expect("properties");@@ -10612,6 +10873,82 @@ mod click_button_schema_tests {for need in ["left", "right", "middle"] {assert!(enum_vals.contains(&need), "missing {need} in button.enum");}+ let capture_id = props.get("capture_id").expect("capture_id field present");+ assert_eq!(capture_id["type"], "string");+ assert_eq!(capture_id["minLength"], 1);+ }+}++#[cfg(test)]+mod snapshot_coordinate_tests {+ use super::{focus_by_pixel_click_args, ToolState, ZoomTool};+ use crate::uia::cache::{CachedSnapshot, SnapshotKind};+ use cua_driver_core::tool::Tool;++ #[test]+ fn schema_keeps_pid_optional_for_window_owned_lookup() {+ let tool = ZoomTool {+ state: ToolState::new(None),+ };+ let required = tool.def().input_schema["required"].as_array().unwrap();+ assert!(!required.iter().any(|field| field == "pid"));+ assert!(tool.def().input_schema["properties"].get("pid").is_some());++ tool.state.element_cache.publish_for_session(+ 42,+ 7,+ CachedSnapshot::from_nodes(&[], SnapshotKind::Uia),+ Some("zoom-optional-pid-windows"),+ Some(2.0),+ );+ let (pid, context) = tool+ .state+ .element_cache+ .screenshot_context_for_zoom(None, 7, Some("zoom-optional-pid-windows"))+ .unwrap();+ assert_eq!(pid, 42);+ assert_eq!(context.window_id, 7);+ tool.state.element_cache.publish_for_session(+ 43,+ 7,+ CachedSnapshot::from_nodes(&[], SnapshotKind::Uia),+ Some("zoom-optional-pid-windows"),+ Some(1.0),+ );+ assert!(tool+ .state+ .element_cache+ .screenshot_context_for_zoom(None, 7, Some("zoom-optional-pid-windows"))+ .is_err());+ }++ #[test]+ fn press_key_native_element_focus_skips_second_screenshot_scaling() {+ let native = focus_by_pixel_click_args(+ 42,+ Some(7),+ 120.0,+ 80.0,+ false,+ None,+ Some("client-a".to_owned()),+ false,+ true,+ );+ assert_eq!(native["_native_coordinates"], true);++ let screenshot = focus_by_pixel_click_args(+ 42,+ Some(7),+ 60.0,+ 40.0,+ false,+ None,+ Some("client-a".to_owned()),+ false,+ false,+ );+ assert!(screenshot.get("_native_coordinates").is_none());}}@@ -10710,7 +11047,10 @@ mod desktop_scope_tests {#[test]fn get_desktop_state_schema_shape() {- let d = GetDesktopStateTool.def();+ let tool = GetDesktopStateTool {+ state: super::ToolState::new(None),+ };+ let d = tool.def();assert!(d.read_only, "get_desktop_state must be read_only");let props = d.input_schema["properties"].as_object().unwrap();assert!(!props.contains_key("pid"), "must not accept pid");diff --git a/libs/cua-driver/scripts/tests/test_macos_lume_runner.py b/libs/cua-driver/scripts/tests/test_macos_lume_runner.pyindex b6978a9cd0..e9fa98ccb4 100644--- a/libs/cua-driver/scripts/tests/test_macos_lume_runner.py+++ b/libs/cua-driver/scripts/tests/test_macos_lume_runner.py@@ -14,6 +14,7 @@ import reimport shutilimport sqlite3import subprocess+import timefrom pathlib import Pathimport pytest@@ -309,7 +310,9 @@ def test_tcc_guest_seed_sql_executes_against_modern_tcc_schema(tmp_path: Path) -def test_tcc_guest_seed_requires_certificate_backed_requirement_by_default() -> None:text = SEED_TCC_GUEST.read_text(encoding="utf-8")- assert '[[ "${ALLOW_ADHOC}" != 1 && "${REQUIREMENT}" != *"certificate leaf"* ]]' in text+ assert '[[ "${ALLOW_ADHOC}" != 1 ]]' in text+ assert "^Signature=adhoc$" in text+ assert 'certificate (leaf|root) = H"[[:xdigit:]]{40}"' in textassert "is not signed with a certificate-backed identity" in text@@ -502,6 +505,68 @@ def test_previous_artifact_run_is_preserved_without_mixing_results(tmp_path: Pat)+def test_screen_capture_approval_is_written_reloaded_and_verified(tmp_path: Path) -> None:+ fake_bin = tmp_path / "bin"+ calls = tmp_path / "calls.txt"+ approvals = tmp_path / "preferences/ScreenCaptureApprovals.plist"+ artifact_dir = tmp_path / "artifacts"+ artifact_dir.mkdir()+ _write_executable(+ fake_bin / "defaults",+ """printf 'defaults %s\n' "$*" >> "$CUA_TEST_CALLS"+if [ "$1" = "read" ]; then+ printf '{\n kScreenCaptureApprovalLastAlerted = "3024-01-01 00:00:00 +0000";\n kScreenCaptureApprovalLastUsed = "3024-01-01 00:00:00 +0000";\n}\n'+fi+""",+ )+ _write_executable(+ fake_bin / "killall",+ """printf 'killall %s\n' "$*" >> "$CUA_TEST_CALLS"+""",+ )+ completed = _run(+ RUN_ALL,+ 'ARTIFACT_DIR="$TEST_ARTIFACT_DIR"\n'+ 'SCREEN_CAPTURE_APPROVALS="$TEST_APPROVALS"\n'+ "setup_screen_capture_approval\n",+ env={+ "PATH": f"{fake_bin}:/usr/bin:/bin",+ "CUA_TEST_CALLS": str(calls),+ "TEST_APPROVALS": str(approvals),+ "TEST_ARTIFACT_DIR": str(artifact_dir),+ },+ )+ assert completed.returncode == 0, completed.stderr+ assert approvals.parent.is_dir()+ recorded = calls.read_text(encoding="utf-8").splitlines()+ assert recorded == [+ f"defaults write {approvals} com.trycua.driver.local -dict "+ "kScreenCaptureApprovalLastAlerted -date 3024-01-01 00:00:00 +0000 "+ "kScreenCaptureApprovalLastUsed -date 3024-01-01 00:00:00 +0000",+ "killall -HUP replayd",+ f"defaults read {approvals} com.trycua.driver.local",+ ]+ evidence = (artifact_dir / "screen-capture-approval.txt").read_text(encoding="utf-8")+ assert "kScreenCaptureApprovalLastAlerted" in evidence+ assert "kScreenCaptureApprovalLastUsed" in evidence+++def test_screen_capture_approval_precedes_capture_capability_probe() -> None:+ text = RUN_ALL.read_text(encoding="utf-8")+ main = text.split('if [[ "${CUA_E2E_RUNNER_LIB_ONLY:-0}" == 1 ]]', 1)[1]+ approval = main.index("setup_screen_capture_approval")+ assert approval < main.index('"${INSTALLED_BIN}" permissions status --json')+ assert approval < main.index('if [[ "${RETRY_ONLY}" == 1 ]]')+ assert approval < main.index("run_full_matrix")+++def test_lume_runner_gates_persistent_guest_setup_to_virtualmac() -> None:+ text = RUN_ALL.read_text(encoding="utf-8")+ assert 'MODEL="$(/usr/sbin/sysctl -n hw.model 2>/dev/null || true)"' in text+ assert '[[ "${MODEL}" != VirtualMac* ]]' in text+ assert "requires a VirtualMac guest" in text++def test_artifact_history_is_never_overwritten(tmp_path: Path) -> None:artifact_dir = tmp_path / "macos"history_root = tmp_path / "macos-history"@@ -799,6 +864,237 @@ def test_required_keychains_unlock_login_without_retaining_password(]+def test_required_keychains_accept_already_unlocked_noninteractive_keychains(+ tmp_path: Path,+) -> None:+ signing_keychain = tmp_path / "signing.keychain-db"+ login_keychain = tmp_path / "login.keychain-db"+ signing_keychain.touch()+ login_keychain.touch()+ fake_security = tmp_path / "bin/security"+ fake_codesign = tmp_path / "bin/codesign"+ security_log = tmp_path / "security.log"+ codesign_log = tmp_path / "codesign.log"+ _write_executable(+ fake_security,+ """printf '%s\n' "$*" >> "$CUA_TEST_SECURITY_LOG"+command="$1"+shift+if [ "$command" = find-generic-password ]; then+ while [ "$#" -gt 0 ]; do+ if [ "$1" = -s ]; then+ printf '%s' "$2"+ exit 0+ fi+ shift+ done+ exit 1+fi+""",+ )+ _write_executable(+ fake_codesign,+ """printf '%s\n' "$*" >> "$CUA_TEST_CODESIGN_LOG"+""",+ )+ completed = _run(+ RUN_ALL,+ "unlock_required_keychains\n",+ env={+ "PATH": f"{fake_codesign.parent}:{os.environ['PATH']}",+ "CUA_E2E_SIGNING_KEYCHAIN": str(signing_keychain),+ "CUA_E2E_LOGIN_KEYCHAIN": str(login_keychain),+ "CUA_E2E_SIGNING_KEYCHAIN_PASSWORD": "",+ "CUA_TEST_SECURITY_LOG": str(security_log),+ "CUA_TEST_CODESIGN_LOG": str(codesign_log),+ },+ )+ assert completed.returncode == 0, completed.stderr+ codesign_calls = codesign_log.read_text(encoding="utf-8").splitlines()+ assert len(codesign_calls) == 2+ assert codesign_calls[0].startswith(+ "--force --timestamp=none --sign CuaDriver Local Signing "+ f"(cua-driver-rs) --keychain {signing_keychain} "+ )+ probe_binary = codesign_calls[0].rsplit(" ", 1)[1]+ assert codesign_calls[1] == f"--verify --strict {probe_binary}"+ security_calls = security_log.read_text(encoding="utf-8").splitlines()+ assert len(security_calls) == 3+ assert security_calls[0].startswith("add-generic-password -a cua-driver-keychain-probe -s ")+ service = security_calls[0].split(" -s ", 1)[1].split(" -w ", 1)[0]+ assert security_calls[0].endswith(f" -w {service} {login_keychain}")+ assert security_calls[1] == (+ f"find-generic-password -a cua-driver-keychain-probe -s {service} "+ f"-w {login_keychain}"+ )+ assert security_calls[2] == (+ f"delete-generic-password -a cua-driver-keychain-probe -s {service} "+ f"{login_keychain}"+ )+++def test_required_keychains_fail_when_noninteractive_keychain_is_locked(+ tmp_path: Path,+) -> None:+ signing_keychain = tmp_path / "signing.keychain-db"+ login_keychain = tmp_path / "login.keychain-db"+ signing_keychain.touch()+ login_keychain.touch()+ fake_codesign = tmp_path / "bin/codesign"+ probe_tmp = tmp_path / "probe-tmp"+ probe_tmp.mkdir()+ log = tmp_path / "codesign.log"+ _write_executable(+ fake_codesign,+ """printf '%s\n' "$*" >> "$CUA_TEST_SECURITY_LOG"+exit 1+""",+ )+ completed = _run(+ RUN_ALL,+ "unlock_required_keychains\n",+ env={+ "PATH": f"{fake_codesign.parent}:{os.environ['PATH']}",+ "CUA_E2E_SIGNING_KEYCHAIN": str(signing_keychain),+ "CUA_E2E_LOGIN_KEYCHAIN": str(login_keychain),+ "CUA_E2E_SIGNING_KEYCHAIN_PASSWORD": "",+ "CUA_TEST_SECURITY_LOG": str(log),+ "TMPDIR": str(probe_tmp),+ },+ )+ assert completed.returncode == 2+ assert "did not permit the bounded signing and verification probe" in completed.stderr+ assert log.read_text(encoding="utf-8").splitlines()[0].startswith(+ "--force --timestamp=none --sign"+ )+ assert list(probe_tmp.iterdir()) == []+++def test_login_keychain_probe_deletes_item_after_failed_read(tmp_path: Path) -> None:+ login_keychain = tmp_path / "login.keychain-db"+ login_keychain.touch()+ fake_security = tmp_path / "bin/security"+ log = tmp_path / "security.log"+ _write_executable(+ fake_security,+ """printf '%s\n' "$*" >> "$CUA_TEST_SECURITY_LOG"+if [ "$1" = find-generic-password ]; then+ exit 1+fi+""",+ )+ completed = _run(+ RUN_ALL,+ 'probe_login_keychain "$CUA_E2E_LOGIN_KEYCHAIN"\n',+ env={+ "PATH": f"{fake_security.parent}:{os.environ['PATH']}",+ "CUA_E2E_LOGIN_KEYCHAIN": str(login_keychain),+ "CUA_TEST_SECURITY_LOG": str(log),+ },+ )+ assert completed.returncode == 1+ calls = log.read_text(encoding="utf-8").splitlines()+ assert [call.split(" ", 1)[0] for call in calls] == [+ "add-generic-password",+ "find-generic-password",+ "delete-generic-password",+ ]+++def test_login_keychain_probe_reports_repeated_cleanup_failure(tmp_path: Path) -> None:+ login_keychain = tmp_path / "login.keychain-db"+ login_keychain.touch()+ fake_security = tmp_path / "bin/security"+ log = tmp_path / "security.log"+ _write_executable(+ fake_security,+ """printf '%s\n' "$*" >> "$CUA_TEST_SECURITY_LOG"+if [ "$1" = find-generic-password ]; then+ exit 3+fi+if [ "$1" = delete-generic-password ]; then+ exit 7+fi+""",+ )+ completed = _run(+ RUN_ALL,+ 'probe_login_keychain "$CUA_E2E_LOGIN_KEYCHAIN"\n',+ env={+ "PATH": f"{fake_security.parent}:{os.environ['PATH']}",+ "CUA_E2E_LOGIN_KEYCHAIN": str(login_keychain),+ "CUA_TEST_SECURITY_LOG": str(log),+ },+ )+ assert completed.returncode == 7+ calls = log.read_text(encoding="utf-8").splitlines()+ assert [call.split(" ", 1)[0] for call in calls] == [+ "add-generic-password",+ "find-generic-password",+ "delete-generic-password",+ "delete-generic-password",+ ]+ assert "cleanup failed; retrying the bounded delete once" in completed.stderr+ assert "cleanup failed after two bounded delete attempts" in completed.stderr+ assert "temporary item cua-driver-keychain-probe-" in completed.stderr+++def test_bounded_command_kills_the_entire_subprocess_group(tmp_path: Path) -> None:+ hanging_command = tmp_path / "bin/hanging-command"+ child_pid_path = tmp_path / "child.pid"+ _write_executable(+ hanging_command,+ """trap '' TERM+sleep 30 &+child_pid=$!+printf '%s\n' "$child_pid" > "$CUA_TEST_CHILD_PID"+wait "$child_pid"+""",+ )+ started = time.monotonic()+ completed = _run(+ RUN_ALL,+ "KEYCHAIN_COMMAND_TIMEOUT_SECONDS=0.2\n"+ "KEYCHAIN_COMMAND_KILL_GRACE_SECONDS=0.1\n"+ 'run_bounded_command "$CUA_TEST_HANGING_COMMAND"\n',+ env={+ "CUA_TEST_HANGING_COMMAND": str(hanging_command),+ "CUA_TEST_CHILD_PID": str(child_pid_path),+ },+ )+ elapsed = time.monotonic() - started+ assert completed.returncode == 124+ assert elapsed < 2+ child_pid = int(child_pid_path.read_text(encoding="utf-8"))+ for _ in range(20):+ try:+ os.kill(child_pid, 0)+ except ProcessLookupError:+ break+ time.sleep(0.05)+ else:+ pytest.fail(f"timed-out child process {child_pid} is still alive")+++def test_bounded_command_requires_python_and_uses_process_group_kills() -> None:+ text = RUN_ALL.read_text(encoding="utf-8")+ function = text.split("run_bounded_command() {", 1)[1].split("\n}\n", 1)[0]+ assert "command -v python3" in function+ assert "subprocess.Popen(sys.argv[3:], start_new_session=True)" in function+ assert function.count("os.killpg(process.pid") == 2+ assert "osascript python3 security xcrun" in text+++def test_required_keychains_keep_terminal_prompt_fallback() -> None:+ text = RUN_ALL.read_text(encoding="utf-8")+ function = text.split("prepare_keychain() {", 1)[1].split("\n}\n", 1)[0]+ assert '[[ -z "${keychain_password}" && -t 0 ]]' in function+ assert 'read -r -s -p "${label} password: "' in function+ assert "run_bounded_command security unlock-keychain -p" in function+ assert 'probe_signing_keychain "${keychain}"' in function+ assert 'probe_login_keychain "${keychain}"' in function++# --------------------------------------------------------------------------# Retry bookkeeping# --------------------------------------------------------------------------diff --git a/libs/cua-driver/tests/fixtures/apps/cross-platform/visual-only-canvas/main.py b/libs/cua-driver/tests/fixtures/apps/cross-platform/visual-only-canvas/main.pynew file mode 100644index 0000000000..dafeb30833--- /dev/null+++ b/libs/cua-driver/tests/fixtures/apps/cross-platform/visual-only-canvas/main.py@@ -0,0 +1,368 @@+#!/usr/bin/env python3+"""Custom-painted visual fixture with a loopback-only behavioral oracle."""++from __future__ import annotations++import argparse+import ast+import json+import os+import re+import subprocess+import sys+import tkinter as tk+import time+from typing import Callable, Optional+import urllib.parse+import urllib.request+++WIDTH = 760+HEIGHT = 460+CARD_LABEL_FONT_PIXELS = 32+MIN_SEND_LABEL_FONT_PIXELS = 1+MAX_SEND_LABEL_FONT_PIXELS = 48+DEFAULT_TITLE = "Cua Visual-Only Canvas Fixture"+X11_DISCOVERY_ATTEMPTS = 20+X11_DISCOVERY_INTERVAL_SECONDS = 0.05+CARDS = (+ {"id": "save", "label": "Save", "bounds": (72, 132, 276, 310), "color": "#e85d3f"},+ {"id": "send", "label": "Send", "bounds": (292, 132, 496, 310), "color": "#1e8b99"},+ {"id": "cancel", "label": "Cancel", "bounds": (512, 132, 716, 310), "color": "#6f8f3d"},+)+++def send_label_font_pixels(value: str) -> int:+ try:+ pixels = int(value)+ except ValueError as error:+ raise argparse.ArgumentTypeError("send label font pixels must be an integer") from error+ if not MIN_SEND_LABEL_FONT_PIXELS <= pixels <= MAX_SEND_LABEL_FONT_PIXELS:+ raise argparse.ArgumentTypeError(+ "send label font pixels must be between "+ f"{MIN_SEND_LABEL_FONT_PIXELS} and {MAX_SEND_LABEL_FONT_PIXELS}"+ )+ return pixels+++def card_label_font_pixels(card_id: str, send_pixels: int) -> int:+ return send_pixels if card_id == "send" else CARD_LABEL_FONT_PIXELS+++def card_at(x: int, y: int) -> Optional[str]:+ for card in CARDS:+ left, top, right, bottom = card["bounds"]+ if left <= x <= right and top <= y <= bottom:+ return str(card["id"])+ return None+++def bind_background_click(+ toplevel: tk.Misc,+ canvas: tk.Canvas,+ handler: Callable[[tk.Event], str],+) -> None:+ # X11 targets the deepest child while Windows targeted injection may reach+ # the toplevel. Returning "break" keeps a canvas event from firing twice as+ # Tk walks from the widget bindtag to the toplevel bindtag.+ canvas.bind("<Button-1>", handler)+ toplevel.bind("<Button-1>", handler)+++def canvas_point(event: tk.Event, canvas: tk.Canvas) -> tuple[int, int]:+ return (+ int(event.x_root) - canvas.winfo_rootx(),+ int(event.y_root) - canvas.winfo_rooty(),+ )+++def oracle_state(selected: Optional[str], action_count: int) -> dict[str, object]:+ return {+ "fixture": "visual-only-canvas/v1",+ "pid": os.getpid(),+ "ready": True,+ "selected": selected,+ "action_count": action_count,+ }+++def validate_journal_url(url: str) -> None:+ parsed = urllib.parse.urlparse(url)+ if parsed.scheme != "http" or parsed.hostname not in {"127.0.0.1", "::1", "localhost"}:+ raise ValueError("fixture journal must be an HTTP loopback endpoint")+++def post_oracle(url: str, state: dict[str, object]) -> None:+ validate_journal_url(url)+ payload = json.dumps(state, separators=(",", ":")).encode("utf-8")+ request = urllib.request.Request(+ url,+ data=payload,+ headers={"Content-Type": "application/json"},+ method="POST",+ )+ with urllib.request.urlopen(request, timeout=1) as response:+ if response.status != 204:+ raise RuntimeError(f"fixture journal returned HTTP {response.status}")+++def _xprop(*args: str) -> subprocess.CompletedProcess[str]:+ return subprocess.run(+ ["xprop", *args],+ check=True,+ capture_output=True,+ text=True,+ timeout=1,+ )+++def _subprocess_diagnostic(error: OSError | subprocess.SubprocessError) -> str:+ stderr = getattr(error, "stderr", None)+ if isinstance(stderr, bytes):+ stderr = stderr.decode(errors="replace")+ detail = stderr.strip() if isinstance(stderr, str) else ""+ return f"{error}; stderr={detail!r}" if detail else str(error)+++def _x11_client_ids(output: str) -> list[str]:+ matches = re.findall(r"\b0x[0-9a-fA-F]+\b", output)+ return list(dict.fromkeys(match.lower() for match in matches if match != "0x0"))+++def _x11_window_title(output: str) -> Optional[str]:+ titles: dict[str, str] = {}+ for line in output.splitlines():+ match = re.match(+ r"^(?P<name>_NET_WM_NAME|WM_NAME)(?:\([^)]*\))?\s*=\s*(?P<value>.+)$",+ line,+ )+ if match is None:+ continue+ try:+ value = ast.literal_eval(match.group("value"))+ except (SyntaxError, ValueError):+ continue+ if isinstance(value, str):+ titles[match.group("name")] = value+ return titles.get("_NET_WM_NAME", titles.get("WM_NAME"))+++def _x11_property_number(output: str, property_name: str) -> Optional[int]:+ match = re.search(+ rf"^{re.escape(property_name)}(?:\([^)]*\))?\s*=\s*(\d+)\s*$",+ output,+ re.MULTILINE,+ )+ return int(match.group(1)) if match is not None else None+++def publish_x11_owner(+ title: str,+ *,+ attempts: int = X11_DISCOVERY_ATTEMPTS,+ interval_seconds: float = X11_DISCOVERY_INTERVAL_SECONDS,+) -> None:+ if not sys.platform.startswith("linux"):+ return++ if attempts < 1:+ raise ValueError("X11 discovery attempts must be positive")++ last_diagnostic = "root client list was not queried"+ window_id: Optional[str] = None+ for attempt in range(1, attempts + 1):+ try:+ clients = _xprop("-root", "_NET_CLIENT_LIST_STACKING", "_NET_CLIENT_LIST")+ client_ids = _x11_client_ids(clients.stdout)+ matches: list[str] = []+ observed: list[str] = []+ for client_id in client_ids:+ try:+ properties = _xprop("-id", client_id, "_NET_WM_NAME", "WM_NAME")+ except (OSError, subprocess.SubprocessError) as error:+ observed.append(f"{client_id}=<query failed: {_subprocess_diagnostic(error)}>")+ continue+ client_title = _x11_window_title(properties.stdout)+ observed.append(f"{client_id}={client_title!r}")+ if client_title == title:+ matches.append(client_id)+ if len(matches) > 1:+ raise RuntimeError(+ f"X11 title {title!r} matched multiple EWMH clients: {', '.join(matches)}"+ )+ if matches:+ window_id = matches[0]+ break+ displayed = observed[:12]+ if len(observed) > len(displayed):+ displayed.append(f"... {len(observed) - len(displayed)} more")+ last_diagnostic = (+ f"attempt {attempt}/{attempts}: {len(client_ids)} EWMH clients; "+ f"observed {', '.join(displayed) if displayed else '<none>'}"+ )+ except RuntimeError:+ raise+ except (OSError, subprocess.SubprocessError) as error:+ last_diagnostic = (+ f"attempt {attempt}/{attempts}: xprop failed: {_subprocess_diagnostic(error)}"+ )+ if attempt < attempts:+ time.sleep(interval_seconds)++ if window_id is None:+ raise RuntimeError(+ f"could not find unique mapped X11 client titled {title!r}; {last_diagnostic}"+ )++ expected_pid = os.getpid()+ try:+ _xprop(+ "-id",+ window_id,+ "-f",+ "_NET_WM_PID",+ "32c",+ "-set",+ "_NET_WM_PID",+ str(expected_pid),+ )+ published = _xprop("-id", window_id, "_NET_WM_PID")+ except (OSError, subprocess.SubprocessError) as error:+ raise RuntimeError(+ f"failed to publish _NET_WM_PID on X11 client {window_id}: "+ f"{_subprocess_diagnostic(error)}"+ ) from error+ actual_pid = _x11_property_number(published.stdout, "_NET_WM_PID")+ if actual_pid != expected_pid:+ raise RuntimeError(+ f"X11 client {window_id} reported _NET_WM_PID={actual_pid!r}; expected {expected_pid}"+ )+++class VisualFixture:+ def __init__(+ self,+ journal_url: str,+ title: str = DEFAULT_TITLE,+ send_pixels: int = CARD_LABEL_FONT_PIXELS,+ ) -> None:+ self.journal_url = journal_url+ self.send_label_font_pixels = send_label_font_pixels(str(send_pixels))+ self.selected: Optional[str] = None+ self.action_count = 0+ self.root = tk.Tk()+ self.root.title(title)+ self.root.geometry(f"{WIDTH}x{HEIGHT}")+ self.root.resizable(False, False)+ self.root.update_idletasks()+ self.canvas = tk.Canvas(+ self.root,+ width=WIDTH,+ height=HEIGHT,+ background="#f3ead7",+ highlightthickness=0,+ takefocus=0,+ )+ self.canvas.pack(fill="both", expand=True)+ bind_background_click(self.root, self.canvas, self.on_click)+ self.paint()+ if sys.platform.startswith("linux"):+ self.root.update()+ publish_x11_owner(title)+ self.root.after(50, self.publish)++ def paint(self) -> None:+ self.canvas.delete("all")+ self.canvas.create_rectangle(0, 0, WIDTH, 94, fill="#172b36", outline="")+ self.canvas.create_text(+ 42, 34, anchor="nw", text="CHOOSE A SIGNAL", fill="#fff8e8", font=("Helvetica", 25, "bold")+ )+ self.canvas.create_text(+ 44, 72, anchor="nw", text="A painted surface: pixels in, coordinates out", fill="#b8c9c8", font=("Helvetica", 11)+ )+ for card in CARDS:+ left, top, right, bottom = card["bounds"]+ selected = self.selected == card["id"]+ border = "#172b36" if selected else "#cfbea0"+ width = 7 if selected else 2+ self.canvas.create_rectangle(left, top, right, bottom, fill=card["color"], outline=border, width=width)+ self.canvas.create_oval(left + 61, top + 42, left + 143, top + 124, fill="#fff8e8", outline="")+ self.canvas.create_text(+ (left + right) // 2,+ bottom - 28,+ text=card["label"],+ fill="#fff8e8",+ font=(+ "Helvetica",+ -card_label_font_pixels(str(card["id"]), self.send_label_font_pixels),+ "bold",+ ),+ )+ status = "WAITING FOR A VISUAL CHOICE" if self.selected is None else f"SELECTED: {self.selected.upper()}"+ self.canvas.create_text(380, 386, text=status, fill="#172b36", font=("Helvetica", 15, "bold"))++ def on_click(self, event: tk.Event) -> str:+ x, y = canvas_point(event, self.canvas)+ selected = card_at(x, y)+ if selected is not None:+ self.selected = selected+ self.action_count += 1+ self.paint()+ self.publish()+ else:+ print(+ f"visual-only-canvas ignored click outside cards at canvas ({x}, {y})",+ file=sys.stderr,+ flush=True,+ )+ return "break"++ def publish(self) -> None:+ try:+ post_oracle(self.journal_url, oracle_state(self.selected, self.action_count))+ except OSError:+ self.root.after(100, self.publish)++ def run(self) -> None:+ self.root.mainloop()+++def main() -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument("--journal-url")+ parser.add_argument("--title", default=DEFAULT_TITLE)+ parser.add_argument(+ "--send-label-font-pixels",+ default=CARD_LABEL_FONT_PIXELS,+ type=send_label_font_pixels,+ )+ parser.add_argument("--self-test", action="store_true")+ args = parser.parse_args()+ if args.self_test:+ assert args.title+ assert CARD_LABEL_FONT_PIXELS == 32+ assert send_label_font_pixels("48") == MAX_SEND_LABEL_FONT_PIXELS+ assert card_label_font_pixels("send", args.send_label_font_pixels) == args.send_label_font_pixels+ assert card_label_font_pixels("save", args.send_label_font_pixels) == CARD_LABEL_FONT_PIXELS+ assert card_label_font_pixels("cancel", args.send_label_font_pixels) == CARD_LABEL_FONT_PIXELS+ for card in CARDS:+ left, _, right, _ = card["bounds"]+ label = str(card["label"])+ assert label+ pixels = card_label_font_pixels(str(card["id"]), args.send_label_font_pixels)+ assert len(label) * pixels <= right - left+ assert card_at(174, 220) == "save"+ assert card_at(394, 220) == "send"+ assert card_at(614, 220) == "cancel"+ assert card_at(20, 20) is None+ assert oracle_state("send", 2)["action_count"] == 2+ return 0+ if not args.journal_url:+ parser.error("--journal-url is required unless --self-test is used")+ validate_journal_url(args.journal_url)+ VisualFixture(args.journal_url, args.title, args.send_label_font_pixels).run()+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/libs/cua-driver/tests/fixtures/apps/cross-platform/visual-only-canvas/test_fixture.py b/libs/cua-driver/tests/fixtures/apps/cross-platform/visual-only-canvas/test_fixture.pynew file mode 100644index 0000000000..2fa823dbad--- /dev/null+++ b/libs/cua-driver/tests/fixtures/apps/cross-platform/visual-only-canvas/test_fixture.py@@ -0,0 +1,208 @@+import contextlib+import importlib.util+import io+from pathlib import Path+import unittest+from unittest import mock+++MODULE_PATH = Path(__file__).with_name("main.py")+SPEC = importlib.util.spec_from_file_location("visual_only_canvas", MODULE_PATH)+fixture = importlib.util.module_from_spec(SPEC)+assert SPEC.loader is not None+SPEC.loader.exec_module(fixture)+++class VisualOnlyCanvasTests(unittest.TestCase):+ def test_send_label_font_pixels_are_bounded(self):+ self.assertEqual(fixture.send_label_font_pixels("1"), 1)+ self.assertEqual(fixture.send_label_font_pixels("48"), 48)+ for value in ("0", "49", "not-an-integer"):+ with self.subTest(value=value), self.assertRaises(+ fixture.argparse.ArgumentTypeError+ ):+ fixture.send_label_font_pixels(value)++ def test_send_label_font_override_does_not_change_other_cards(self):+ self.assertEqual(fixture.card_label_font_pixels("send", 48), 48)+ self.assertEqual(+ fixture.card_label_font_pixels("save", 48), fixture.CARD_LABEL_FONT_PIXELS+ )+ self.assertEqual(+ fixture.card_label_font_pixels("cancel", 48), fixture.CARD_LABEL_FONT_PIXELS+ )++ def test_hit_testing_uses_painted_geometry(self):+ self.assertEqual(fixture.card_at(174, 220), "save")+ self.assertEqual(fixture.card_at(394, 220), "send")+ self.assertEqual(fixture.card_at(614, 220), "cancel")+ self.assertIsNone(fixture.card_at(40, 220))++ def test_background_click_is_bound_on_canvas_and_toplevel(self):+ toplevel = mock.Mock()+ canvas = mock.Mock()+ handler = mock.Mock()++ fixture.bind_background_click(toplevel, canvas, handler)++ canvas.bind.assert_called_once_with("<Button-1>", handler)+ toplevel.bind.assert_called_once_with("<Button-1>", handler)++ def test_toplevel_event_coordinates_are_translated_to_the_canvas(self):+ canvas = mock.Mock()+ canvas.winfo_rootx.return_value = 120+ canvas.winfo_rooty.return_value = 80+ event = mock.Mock(x_root=514, y_root=300)++ self.assertEqual(fixture.canvas_point(event, canvas), (394, 220))++ def test_toplevel_click_updates_the_oracle_once(self):+ visual_fixture = fixture.VisualFixture.__new__(fixture.VisualFixture)+ visual_fixture.canvas = mock.Mock()+ visual_fixture.canvas.winfo_rootx.return_value = 120+ visual_fixture.canvas.winfo_rooty.return_value = 80+ visual_fixture.selected = None+ visual_fixture.action_count = 0+ visual_fixture.paint = mock.Mock()+ visual_fixture.publish = mock.Mock()++ result = visual_fixture.on_click(mock.Mock(x_root=514, y_root=300))++ self.assertEqual(visual_fixture.selected, "send")+ self.assertEqual(visual_fixture.action_count, 1)+ self.assertEqual(result, "break")+ visual_fixture.paint.assert_called_once_with()+ visual_fixture.publish.assert_called_once_with()++ def test_click_outside_cards_stops_bindtag_propagation_without_mutating_oracle(self):+ visual_fixture = fixture.VisualFixture.__new__(fixture.VisualFixture)+ visual_fixture.canvas = mock.Mock()+ visual_fixture.canvas.winfo_rootx.return_value = 120+ visual_fixture.canvas.winfo_rooty.return_value = 80+ visual_fixture.selected = None+ visual_fixture.action_count = 0+ visual_fixture.paint = mock.Mock()+ visual_fixture.publish = mock.Mock()++ diagnostic = io.StringIO()+ with contextlib.redirect_stderr(diagnostic):+ result = visual_fixture.on_click(mock.Mock(x_root=130, y_root=90))++ self.assertEqual(result, "break")+ self.assertIn("ignored click outside cards at canvas (10, 10)", diagnostic.getvalue())+ self.assertIsNone(visual_fixture.selected)+ self.assertEqual(visual_fixture.action_count, 0)+ visual_fixture.paint.assert_not_called()+ visual_fixture.publish.assert_not_called()++ @mock.patch.object(fixture.os, "getpid", return_value=4242)+ def test_oracle_contains_behavior_and_process_identity_without_coordinates_or_labels(+ self, _getpid+ ):+ self.assertEqual(+ fixture.oracle_state("send", 3),+ {+ "fixture": "visual-only-canvas/v1",+ "pid": 4242,+ "ready": True,+ "selected": "send",+ "action_count": 3,+ },+ )++ def test_oracle_transport_is_loopback_only(self):+ fixture.validate_journal_url("http://127.0.0.1:4321/state")+ with self.assertRaisesRegex(ValueError, "loopback"):+ fixture.validate_journal_url("https://example.test/state")++ @mock.patch.object(fixture.subprocess, "run")+ def test_xprop_is_bounded_and_captures_diagnostics(self, run):+ fixture._xprop("-root", "_NET_CLIENT_LIST")++ run.assert_called_once_with(+ ["xprop", "-root", "_NET_CLIENT_LIST"],+ check=True,+ capture_output=True,+ text=True,+ timeout=1,+ )++ @mock.patch.object(fixture.sys, "platform", "linux")+ @mock.patch.object(fixture.os, "getpid", return_value=4242)+ @mock.patch.object(fixture, "_xprop")+ def test_linux_fixture_discovers_client_by_exact_title_and_verifies_owner(self, xprop, _getpid):+ xprop.side_effect = [+ mock.Mock(stdout="_NET_CLIENT_LIST(WINDOW): window id # 0x100001, 0x20001e\n"),+ mock.Mock(stdout='_NET_WM_NAME(UTF8_STRING) = "Other window"\n'),+ mock.Mock(stdout='_NET_WM_NAME(UTF8_STRING) = "Unique fixture title"\n'),+ mock.Mock(stdout=""),+ mock.Mock(stdout="_NET_WM_PID(CARDINAL) = 4242\n"),+ ]++ fixture.publish_x11_owner("Unique fixture title", attempts=1, interval_seconds=0)++ self.assertEqual(+ xprop.call_args_list,+ [+ mock.call("-root", "_NET_CLIENT_LIST_STACKING", "_NET_CLIENT_LIST"),+ mock.call("-id", "0x100001", "_NET_WM_NAME", "WM_NAME"),+ mock.call("-id", "0x20001e", "_NET_WM_NAME", "WM_NAME"),+ mock.call(+ "-id",+ "0x20001e",+ "-f",+ "_NET_WM_PID",+ "32c",+ "-set",+ "_NET_WM_PID",+ "4242",+ ),+ mock.call("-id", "0x20001e", "_NET_WM_PID"),+ ],+ )++ @mock.patch.object(fixture.sys, "platform", "linux")+ @mock.patch.object(fixture.time, "sleep")+ @mock.patch.object(fixture, "_xprop")+ def test_linux_fixture_retries_then_reports_observed_titles(self, xprop, sleep):+ xprop.side_effect = [+ mock.Mock(stdout="_NET_CLIENT_LIST(WINDOW): window id # 0x100001\n"),+ mock.Mock(stdout='WM_NAME(STRING) = "Other window"\n'),+ mock.Mock(stdout="_NET_CLIENT_LIST(WINDOW): window id # 0x100001\n"),+ mock.Mock(stdout='WM_NAME(STRING) = "Still other"\n'),+ ]++ with self.assertRaisesRegex(RuntimeError, r"attempt 2/2.*0x100001='Still other'"):+ fixture.publish_x11_owner("Missing title", attempts=2, interval_seconds=0.01)++ sleep.assert_called_once_with(0.01)++ @mock.patch.object(fixture.sys, "platform", "linux")+ @mock.patch.object(fixture, "_xprop")+ def test_linux_fixture_rejects_duplicate_exact_titles(self, xprop):+ xprop.side_effect = [+ mock.Mock(stdout="_NET_CLIENT_LIST(WINDOW): window id # 0x100001, 0x20001e\n"),+ mock.Mock(stdout='_NET_WM_NAME(UTF8_STRING) = "Duplicate title"\n'),+ mock.Mock(stdout='_NET_WM_NAME(UTF8_STRING) = "Duplicate title"\n'),+ ]++ with self.assertRaisesRegex(RuntimeError, "matched multiple EWMH clients"):+ fixture.publish_x11_owner("Duplicate title", attempts=1, interval_seconds=0)++ @mock.patch.object(fixture.sys, "platform", "linux")+ @mock.patch.object(fixture.os, "getpid", return_value=4242)+ @mock.patch.object(fixture, "_xprop")+ def test_linux_fixture_rejects_unverified_owner(self, xprop, _getpid):+ xprop.side_effect = [+ mock.Mock(stdout="_NET_CLIENT_LIST(WINDOW): window id # 0x20001e\n"),+ mock.Mock(stdout='_NET_WM_NAME(UTF8_STRING) = "Unique fixture title"\n'),+ mock.Mock(stdout=""),+ mock.Mock(stdout="_NET_WM_PID(CARDINAL) = 9999\n"),+ ]++ with self.assertRaisesRegex(RuntimeError, "reported _NET_WM_PID=9999; expected 4242"):+ fixture.publish_x11_owner("Unique fixture title", attempts=1, interval_seconds=0)+++if __name__ == "__main__":+ unittest.main()diff --git a/libs/cua-driver/tests/perception-demo/README.md b/libs/cua-driver/tests/perception-demo/README.mdnew file mode 100644index 0000000000..8bf01c3dbf--- /dev/null+++ b/libs/cua-driver/tests/perception-demo/README.md@@ -0,0 +1,164 @@+# Visual perception demo evidence++This directory defines the review-only evidence boundary for the visual canvas+demo. Independent exact-SHA workflows run and certify the canonical Windows,+Linux X11, and logged-in macOS Lume Driver harnesses without live-provider+secrets. The protected workflows verify those run IDs and their machine-readable+certification artifacts instead of rerunning the broad matrices. A protected+job consumes an immutable review-candidate aggregate, runs the ignored visual-only test with+the measured review Driver, and makes the API key available only to the bounded+Jev chooser process. After decode and schema validation, each review bundle is+encrypted separately and the artifact upload contains only the resulting+authenticated ciphertext envelopes. Manual and reusable workflow invocations+must also set the required boolean `run_live` acknowledgement to `true` before+the source gate permits protected work.++The private candidate producer runs without an environment or production+secrets on Linux, Windows, and `macos-26`, then returns both its Actions run ID+and the immutable aggregate artifact ID. Consumers require both identifiers so+the artifact download is bound to the reviewed exact-SHA producer run. The+candidate aggregate has `windows`, `linux-x11`, and `macos` directories. Each+directory contains `signed-catalog.json`, the catalog-selected extension+archive, `review-measurements.json`, `signed-candidate-checksums.txt`, and a+`review-cua-driver` binary (`review-cua-driver.exe` on Windows). The measurement+file binds the review-only source, Driver version and debug review-trust-root+build profile, Ed25519 public key, signed catalog, extension archive, worker,+all three model artifacts, ONNX Runtime, executed self-test, Driver binary, and+an explicit platform code-signing measurement. Linux and Windows record Apple+code signing as not applicable. The macOS arm64 Driver is signed before it is+measured with a temporary self-signed review certificate in a temporary+keychain; the keychain and private key are destroyed before artifact upload.+Its measurement records the certificate hash and designated requirement and+does not claim a production identity.+Those extension measurements are extracted from the sealed archive and checked+against its artifact manifest, model ledger, runtime contract, and bytes rather+than copied from workflow constants. The test requires these environment variables:++- `CUA_JEV_MOCK_DEMO=1`, or `CUA_JEV_LIVE=1` with+ `CUA_JEV_CHOOSER_PROGRAM`, `CUA_JEV_CHOOSER_SCRIPT`, and `TYPESAFE_API_KEY`+- `CUA_E2E_SOURCE_SHA`+- `CUA_JEV_SOURCE_SHA`+- `CUA_SESSION_LABEL`+- `CUA_TEST_DRIVER_BIN`+- `CUA_CANDIDATE_MEASUREMENTS`+- `CUA_PERCEPTION_MODEL`+- `CUA_PERCEPTION_EXTENSION_HOME`+- `CUA_PERCEPTION_EVIDENCE_DIR`+- `CUA_RUNNER_OS_NAME`+- `CUA_RUNNER_OS_VERSION`+- `CUA_RUNNER_OS_ARCH`+- `CUA_DESKTOP_SESSION_TYPE`+- `CUA_RUNNER_IDENTITY_CLASS`++The extension home must already contain the candidate installed by the Driver's+signed extension lifecycle. The Driver verifies the signed Ed25519 catalog+against the embedded review-only trust root and reports+`review-only-publisher-verified` before launching the fixture. The+workflow also checks the aggregate checksum file and every measured artifact+hash before executing the review Driver. The test writes measured+`raw-manifest.json` and `timeline.json` files beneath the evidence directory.+It also copies the decoded testkit clip to `recording.mp4` and writes the+schema-checked, redacted `manifest.json`. Capture IDs, coordinates, local paths,+the raw timeline, and the plaintext review bundle remain runner-local.++`sanitize_evidence.py` measures the checked-out source SHA and host platform,+reads the fixture's loopback oracle and provider-returned adapter result, hashes+the Driver, private capture trace, and recording bytes, and binds the sealed+worker, model, runtime, protocol, and self-test measurements. The redacted+manifest records safe bounded candidate IDs and descriptions, capture source+and dimensions, session and runner class, delivery mode, and FFprobe+measured resolution, frame rate, uncut 1x edit record, source time range, cursor+configuration, and final hash. Its output is limited to `manifest.json` and+`recording.mp4`.++The live acceptance test keeps two distinct rows: native-resolution window+capture with background delivery, and primary-desktop capture with foreground+delivery. Primary-desktop actions are screen-absolute on all three supported+desktop families, so background delivery is not supported for that row. The+desktop row writes private evidence beneath `primary-desktop/`; the existing+window evidence remains at the evidence root. Validation stages independently+sanitize and fully decode both rows into review-safe `window/` and+`primary-desktop/` leaves, each containing only `manifest.json` and+`recording.mp4`. `evidence_envelope.py` then validates each exact two-file+directory again and encrypts it for an X25519 recipient. Every unreleased v3+envelope creates a fresh ephemeral X25519 key and derives a one-time+AES-256-GCM key with HKDF-SHA256. The intended recipient public key's SHA-256+fingerprint is included in both the KDF context and authenticated versioned+header. The header also contains the ephemeral public key, nonce, algorithm,+flags, and ciphertext length. Local+decryption derives the public key from the supplied private key and rejects a+recipient fingerprint mismatch before attempting decryption. Encryption logs+only the safe recipient fingerprint, and the same fingerprint remains in each+envelope so protected-run logs and downloaded artifacts identify the key used.+The protected GitHub+environment supplies only the canonical-base64 recipient public key through the+`EVIDENCE_ARCHIVE_RECIPIENT_PUBLIC_KEY` environment variable; this is a GitHub+environment variable, not a secret, and the recipient private key must never be+stored in GitHub or provided to a runner. The uploaded directory contains+exactly `window.cuae` and `primary-desktop.cuae`; it never contains plaintext+manifests, recordings, raw evidence, or timelines. Reviewers decrypt locally+with the canonical-base64+private X25519 key, for example `evidence_envelope.py decrypt --input SCOPE.cuae+--output OUTPUT --private-key-file PRIVATE_KEY_FILE`; `--private-key-env` is+also supported for a local environment variable. Encryption accepts the public+recipient through `--recipient-env` or `--recipient-file`. Windows and Linux+keep raw, mock, and validated plaintext evidence beneath the runner's temporary+directory and remove those exact directories in an `always()` step after the+upload step.++Native macOS certification remains separate from the Windows/Linux live-provider+workflow. This proof runs directly in a logged-in, TCC-authorized Lume guest. A maintainer+dispatches `.github/workflows/e2e-rust-macos.yml` in `lume` mode, whose exact-SHA gate runs+`libs/cua-driver/tests/runners/macos-lume/run-all.sh --standalone-browser` and+publishes a certification artifact without live-provider credentials. The+candidate workflow does not schedule macOS execution, and no GitHub Actions+workflow represents the macOS gate. macOS recordings remain private on the+maintainer-controlled Lume host and are collected for review outside GitHub+Actions. The exact SHA, direct run ID, result, and evidence digest are recorded+in the private review bundle and final PR audit. Windows and Linux continue to+exercise the bounded live Jev chooser; the direct Lume matrix is the macOS+platform acceptance gate.++## Derived reels++Raw evidence remains an uncut 1x record. A shorter review reel is a distinct+artifact governed by `derived-reel-manifest.schema.json` and+`sanitize_derived_reel.py`. Its edit plan names safe source-relative evidence+manifests and recordings, at least two 1x source ranges, and every wait-only+interval removed between ranges from the same source. Each wait cut must state+exactly `wait-only interval removed; no action or result omitted`; the tool+rejects missing, extra, or differently described gaps.++The sanitizer rehashes every source manifest, source recording, and final reel,+requires all source manifests to be passed live evidence for the same Driver+and Jev SHAs, bounds each range by FFprobe's measured source duration, fully+decodes the reel, and checks its duration against the declared edit timeline.+It publishes only `manifest.json` and `reel.mp4`. The derived manifest records+per-source hashes, used ranges, disclosed wait ranges, real trim and concatenate+operations, the expected and decoded durations, and the final hash. Local paths+and the edit plan are not published.++Example edit-plan shape:++```json+{+ "schema": "cua-derived-reel-edit-plan/v1",+ "sources": [+ {"id": "macos", "evidence_manifest": "macos/manifest.json", "recording": "macos/recording.mp4"}+ ],+ "shots": [+ {"source_id": "macos", "start_ms": 500, "end_ms": 1500},+ {"source_id": "macos", "start_ms": 3000, "end_ms": 4000}+ ],+ "wait_cuts": [+ {"source_id": "macos", "start_ms": 1500, "end_ms": 3000, "disclosure": "wait-only interval removed; no action or result omitted"}+ ]+}+```++Render the reel from those exact ranges with FFmpeg, then validate and stage it:++```text+python3 sanitize_derived_reel.py --source-root INPUTS --edit-plan edit-plan.json \+ --reel derived.mp4 --output-dir publish-reel+```diff --git a/libs/cua-driver/tests/perception-demo/derived-reel-manifest.schema.json b/libs/cua-driver/tests/perception-demo/derived-reel-manifest.schema.jsonnew file mode 100644index 0000000000..79ddabc363--- /dev/null+++ b/libs/cua-driver/tests/perception-demo/derived-reel-manifest.schema.json@@ -0,0 +1,125 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://cua.ai/schemas/visual-perception-derived-reel-v1.json",+ "type": "object",+ "additionalProperties": false,+ "required": ["schema", "identity", "sources", "edit_operations", "recording", "artifacts"],+ "$defs": {+ "sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"},+ "sha40": {"type": "string", "pattern": "^[0-9a-f]{40}$"},+ "safeId": {"type": "string", "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$"},+ "range": {+ "type": "object",+ "additionalProperties": false,+ "required": ["start_ms", "end_ms"],+ "properties": {+ "start_ms": {"type": "integer", "minimum": 0},+ "end_ms": {"type": "integer", "minimum": 1}+ }+ }+ },+ "properties": {+ "schema": {"const": "cua-visual-perception-derived-reel/v1"},+ "identity": {+ "type": "object",+ "additionalProperties": false,+ "required": ["source_sha", "jev_source_sha", "fixture", "chooser_provider"],+ "properties": {+ "source_sha": {"$ref": "#/$defs/sha40"},+ "jev_source_sha": {"$ref": "#/$defs/sha40"},+ "fixture": {"const": "visual-only-canvas/v1"},+ "chooser_provider": {"const": "typesafe"}+ }+ },+ "sources": {+ "type": "array",+ "minItems": 1,+ "maxItems": 8,+ "items": {+ "type": "object",+ "additionalProperties": false,+ "required": ["id", "platform", "evidence_manifest_sha256", "recording_sha256", "duration_ms", "used_ranges", "removed_wait_ranges"],+ "properties": {+ "id": {"$ref": "#/$defs/safeId"},+ "platform": {"enum": ["windows", "linux-x11", "macos"]},+ "evidence_manifest_sha256": {"$ref": "#/$defs/sha256"},+ "recording_sha256": {"$ref": "#/$defs/sha256"},+ "duration_ms": {"type": "integer", "minimum": 1},+ "used_ranges": {"type": "array", "minItems": 1, "items": {"$ref": "#/$defs/range"}},+ "removed_wait_ranges": {+ "type": "array",+ "items": {+ "type": "object",+ "additionalProperties": false,+ "required": ["start_ms", "end_ms", "disclosure"],+ "properties": {+ "start_ms": {"type": "integer", "minimum": 0},+ "end_ms": {"type": "integer", "minimum": 1},+ "disclosure": {"const": "wait-only interval removed; no action or result omitted"}+ }+ }+ }+ }+ }+ },+ "edit_operations": {+ "type": "array",+ "minItems": 2,+ "items": {+ "oneOf": [+ {+ "type": "object",+ "additionalProperties": false,+ "required": ["operation", "source_id", "source_start_ms", "source_end_ms", "reel_start_ms", "reel_end_ms", "speed"],+ "properties": {+ "operation": {"const": "trim"},+ "source_id": {"$ref": "#/$defs/safeId"},+ "source_start_ms": {"type": "integer", "minimum": 0},+ "source_end_ms": {"type": "integer", "minimum": 1},+ "reel_start_ms": {"type": "integer", "minimum": 0},+ "reel_end_ms": {"type": "integer", "minimum": 1},+ "speed": {"const": "1x"}+ }+ },+ {+ "type": "object",+ "additionalProperties": false,+ "required": ["operation", "shot_count"],+ "properties": {+ "operation": {"const": "concatenate"},+ "shot_count": {"type": "integer", "minimum": 2}+ }+ }+ ]+ }+ },+ "recording": {+ "type": "object",+ "additionalProperties": false,+ "required": ["expected_duration_ms", "decoded_duration_ms", "fully_decoded", "final_sha256", "size_bytes"],+ "properties": {+ "expected_duration_ms": {"type": "integer", "minimum": 1},+ "decoded_duration_ms": {"type": "integer", "minimum": 1},+ "fully_decoded": {"const": true},+ "final_sha256": {"$ref": "#/$defs/sha256"},+ "size_bytes": {"type": "integer", "minimum": 1, "maximum": 104857600}+ }+ },+ "artifacts": {+ "type": "array",+ "minItems": 1,+ "maxItems": 1,+ "items": {+ "type": "object",+ "additionalProperties": false,+ "required": ["kind", "path", "sha256", "size_bytes"],+ "properties": {+ "kind": {"const": "video"},+ "path": {"const": "reel.mp4"},+ "sha256": {"$ref": "#/$defs/sha256"},+ "size_bytes": {"type": "integer", "minimum": 1, "maximum": 104857600}+ }+ }+ }+ }+}diff --git a/libs/cua-driver/tests/perception-demo/evidence-manifest.schema.json b/libs/cua-driver/tests/perception-demo/evidence-manifest.schema.jsonnew file mode 100644index 0000000000..016eda8f0d--- /dev/null+++ b/libs/cua-driver/tests/perception-demo/evidence-manifest.schema.json@@ -0,0 +1,197 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "$id": "https://cua.ai/schemas/visual-perception-demo-evidence-v3.json",+ "type": "object",+ "additionalProperties": false,+ "required": ["schema", "platform", "raw_evidence_sha256", "fixture", "runtime", "observation", "environment", "result", "recording", "artifacts"],+ "$defs": {+ "sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"},+ "sha40": {"type": "string", "pattern": "^[0-9a-f]{40}$"},+ "safeId": {"type": "string", "pattern": "^[A-Za-z0-9._:/-]{1,96}$"},+ "dimensions": {+ "type": "object", "additionalProperties": false, "required": ["width", "height"],+ "properties": {"width": {"type": "integer", "minimum": 1}, "height": {"type": "integer", "minimum": 1}}+ },+ "model": {+ "type": "object", "additionalProperties": false,+ "required": ["role", "id", "revision", "original_sha256", "converted_sha256", "license"],+ "properties": {+ "role": {"enum": ["icon-detect", "ocr-detect", "ocr-recognize"]},+ "id": {"$ref": "#/$defs/safeId"}, "revision": {"$ref": "#/$defs/safeId"},+ "original_sha256": {"$ref": "#/$defs/sha256"}, "converted_sha256": {"$ref": "#/$defs/sha256"},+ "license": {"$ref": "#/$defs/safeId"}+ }+ }+ },+ "properties": {+ "schema": {"const": "cua-visual-perception-demo-evidence/v3"},+ "platform": {"enum": ["windows", "linux-x11", "macos"]},+ "raw_evidence_sha256": {"$ref": "#/$defs/sha256"},+ "fixture": {+ "type": "object", "additionalProperties": false, "required": ["id", "oracle"],+ "properties": {+ "id": {"const": "visual-only-canvas/v1"},+ "oracle": {+ "type": "object", "additionalProperties": false,+ "required": ["source", "initial_ready", "selected", "action_count", "result"],+ "properties": {+ "source": {"const": "fixture-journal"}, "initial_ready": {"const": true},+ "selected": {"enum": ["save", "send", "cancel"]},+ "action_count": {"type": "integer", "minimum": 1, "maximum": 8}, "result": {"const": "passed"}+ }+ }+ }+ },+ "runtime": {+ "type": "object", "additionalProperties": false, "required": ["driver", "perception", "chooser"],+ "properties": {+ "driver": {+ "type": "object", "additionalProperties": false, "required": ["source_sha", "version", "binary_sha256", "build"],+ "properties": {+ "source_sha": {"$ref": "#/$defs/sha40"}, "version": {"$ref": "#/$defs/safeId"}, "binary_sha256": {"$ref": "#/$defs/sha256"},+ "build": {+ "type": "object", "additionalProperties": false,+ "required": ["profile", "target", "sealed_artifact_manifest_sha256", "sealed_extension_manifest_sha256"],+ "properties": {+ "profile": {"$ref": "#/$defs/safeId"}, "target": {"$ref": "#/$defs/safeId"},+ "sealed_artifact_manifest_sha256": {"$ref": "#/$defs/sha256"},+ "sealed_extension_manifest_sha256": {"$ref": "#/$defs/sha256"}+ }+ }+ }+ },+ "perception": {+ "type": "object", "additionalProperties": false,+ "required": ["extension_id", "extension_version", "trust", "publisher_id", "publisher_key_id", "catalog_version", "signature_algorithm", "signed_extension_archive_sha256", "signing_key_sha256", "signed_catalog_sha256", "protocol_version", "worker_sha256", "self_test", "models", "onnx_runtime", "parser_model_id"],+ "properties": {+ "extension_id": {"const": "cua-perception"}, "extension_version": {"$ref": "#/$defs/safeId"},+ "trust": {"const": "review-only-publisher-verified"}, "publisher_id": {"$ref": "#/$defs/safeId"}, "publisher_key_id": {"$ref": "#/$defs/safeId"},+ "catalog_version": {"type": "integer", "minimum": 1}, "signature_algorithm": {"const": "ed25519"},+ "signed_extension_archive_sha256": {"$ref": "#/$defs/sha256"}, "signing_key_sha256": {"$ref": "#/$defs/sha256"}, "signed_catalog_sha256": {"$ref": "#/$defs/sha256"},+ "protocol_version": {"type": "integer", "minimum": 1}, "worker_sha256": {"$ref": "#/$defs/sha256"},+ "self_test": {+ "type": "object", "additionalProperties": false, "required": ["status", "mismatch_rejection", "evidence_sha256"],+ "properties": {"status": {"const": "passed"}, "mismatch_rejection": {"const": true}, "evidence_sha256": {"$ref": "#/$defs/sha256"}}+ },+ "models": {+ "type": "array", "minItems": 3, "maxItems": 3, "items": false,+ "prefixItems": [+ {"allOf": [{"$ref": "#/$defs/model"}, {"properties": {"role": {"const": "icon-detect"}}}]},+ {"allOf": [{"$ref": "#/$defs/model"}, {"properties": {"role": {"const": "ocr-detect"}}}]},+ {"allOf": [{"$ref": "#/$defs/model"}, {"properties": {"role": {"const": "ocr-recognize"}}}]}+ ]+ },+ "onnx_runtime": {+ "type": "object", "additionalProperties": false, "required": ["revision", "sha256", "license"],+ "properties": {"revision": {"$ref": "#/$defs/safeId"}, "sha256": {"$ref": "#/$defs/sha256"}, "license": {"$ref": "#/$defs/safeId"}}+ },+ "parser_model_id": {"$ref": "#/$defs/safeId"}+ }+ },+ "chooser": {+ "type": "object", "additionalProperties": false, "required": ["mode", "provider", "model_id", "adapter_source_sha", "source_sha"],+ "properties": {+ "mode": {"enum": ["mock", "live"]}, "provider": {"enum": ["fixture", "typesafe"]},+ "model_id": {"type": ["string", "null"], "pattern": "^[A-Za-z0-9._:/-]{1,96}$"},+ "adapter_source_sha": {"$ref": "#/$defs/sha40"}, "source_sha": {"$ref": "#/$defs/sha40"}+ }+ }+ }+ },+ "observation": {+ "type": "object", "additionalProperties": false,+ "required": ["session_label", "input_scope", "capture_kind", "capture_source", "dimensions", "acted_capture_id_sha256", "fresh_capture_id_sha256", "capture_trace_sha256", "candidates"],+ "properties": {+ "session_label": {"$ref": "#/$defs/safeId"}, "input_scope": {"enum": ["window", "desktop"]},+ "capture_kind": {"enum": ["get_window_state", "get_desktop_state"]}, "capture_source": {"const": "driver-screenshot"},+ "dimensions": {"$ref": "#/$defs/dimensions"},+ "acted_capture_id_sha256": {"$ref": "#/$defs/sha256"}, "fresh_capture_id_sha256": {"$ref": "#/$defs/sha256"},+ "capture_trace_sha256": {"$ref": "#/$defs/sha256"},+ "candidates": {+ "type": "array", "minItems": 2, "maxItems": 18,+ "items": {+ "type": "object", "additionalProperties": false, "required": ["id", "description"],+ "properties": {+ "id": {"type": "string", "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$"},+ "description": {"type": "string", "minLength": 1, "maxLength": 256, "pattern": "^[^\\u0000-\\u001f\\u007f]+$"}+ }+ }+ }+ }+ },+ "environment": {+ "type": "object", "additionalProperties": false, "required": ["os", "desktop_session", "runner_identity_class", "delivery_mode"],+ "properties": {+ "os": {+ "type": "object", "additionalProperties": false, "required": ["name", "version", "arch"],+ "properties": {"name": {"$ref": "#/$defs/safeId"}, "version": {"$ref": "#/$defs/safeId"}, "arch": {"$ref": "#/$defs/safeId"}}+ },+ "desktop_session": {"$ref": "#/$defs/safeId"}, "runner_identity_class": {"$ref": "#/$defs/safeId"},+ "delivery_mode": {"enum": ["foreground", "background"]}+ }+ },+ "result": {+ "type": "object", "additionalProperties": false, "required": ["status", "selected_candidate", "background_desktop_refused", "capture_preserved_after_refusal", "stale_capture_refused"],+ "properties": {+ "status": {"const": "passed"}, "selected_candidate": {"type": "string", "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$"},+ "background_desktop_refused": {"type": ["boolean", "null"]},+ "capture_preserved_after_refusal": {"type": ["boolean", "null"]},+ "stale_capture_refused": {"const": true}+ }+ },+ "recording": {+ "type": "object", "additionalProperties": false,+ "required": ["original_dimensions", "delivered_dimensions", "frame_rate", "cursor", "edit_operations", "shots", "final_sha256", "size_bytes"],+ "properties": {+ "original_dimensions": {"$ref": "#/$defs/dimensions"}, "delivered_dimensions": {"$ref": "#/$defs/dimensions"},+ "frame_rate": {+ "type": "object", "additionalProperties": false, "required": ["numerator", "denominator"],+ "properties": {"numerator": {"type": "integer", "minimum": 1}, "denominator": {"type": "integer", "minimum": 1}}+ },+ "cursor": {+ "type": "object", "additionalProperties": false, "required": ["agent_overlay", "system_cursor"],+ "properties": {"agent_overlay": {"const": false}, "system_cursor": {"const": "recorder-default"}}+ },+ "edit_operations": {+ "type": "array", "minItems": 1, "maxItems": 1,+ "items": {"type": "object", "additionalProperties": false, "required": ["operation", "speed"], "properties": {"operation": {"const": "none"}, "speed": {"const": "1x"}}}+ },+ "shots": {+ "type": "array", "minItems": 1,+ "items": {+ "type": "object", "additionalProperties": false, "required": ["source_sha256", "start_ms", "end_ms"],+ "properties": {"source_sha256": {"$ref": "#/$defs/sha256"}, "start_ms": {"type": "integer", "minimum": 0}, "end_ms": {"type": "integer", "minimum": 1}}+ }+ },+ "final_sha256": {"$ref": "#/$defs/sha256"}, "size_bytes": {"type": "integer", "minimum": 1, "maximum": 104857600}+ }+ },+ "artifacts": {+ "type": "array", "minItems": 1, "maxItems": 1,+ "items": {+ "type": "object", "additionalProperties": false, "required": ["kind", "path", "sha256", "size_bytes"],+ "properties": {"kind": {"const": "video"}, "path": {"const": "recording.mp4"}, "sha256": {"$ref": "#/$defs/sha256"}, "size_bytes": {"type": "integer", "minimum": 1, "maximum": 104857600}}+ }+ }+ },+ "allOf": [+ {+ "oneOf": [+ {+ "properties": {+ "observation": {"properties": {"input_scope": {"const": "window"}, "capture_kind": {"const": "get_window_state"}}},+ "environment": {"properties": {"delivery_mode": {"const": "background"}}},+ "result": {"properties": {"background_desktop_refused": {"const": null}, "capture_preserved_after_refusal": {"const": null}}}+ }+ },+ {+ "properties": {+ "observation": {"properties": {"input_scope": {"const": "desktop"}, "capture_kind": {"const": "get_desktop_state"}}},+ "environment": {"properties": {"delivery_mode": {"const": "foreground"}}},+ "result": {"properties": {"background_desktop_refused": {"const": true}, "capture_preserved_after_refusal": {"const": true}}}+ }+ }+ ]+ }+ ]+}diff --git a/libs/cua-driver/tests/perception-demo/evidence_envelope.py b/libs/cua-driver/tests/perception-demo/evidence_envelope.pynew file mode 100644index 0000000000..7416f176f4--- /dev/null+++ b/libs/cua-driver/tests/perception-demo/evidence_envelope.py@@ -0,0 +1,395 @@+#!/usr/bin/env python3+"""Encrypt or decrypt the fixed visual perception evidence bundle."""++from __future__ import annotations++import argparse+import base64+import binascii+import ctypes+import errno+import hashlib+import hmac+from io import BytesIO+import json+import os+from pathlib import Path+import shutil+import stat+import struct+import sys+import tempfile+import zipfile++from cryptography.exceptions import InvalidTag+from cryptography.hazmat.primitives import hashes, serialization+from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey+from cryptography.hazmat.primitives.ciphers.aead import AESGCM+from cryptography.hazmat.primitives.kdf.hkdf import HKDF+++MEMBER_NAMES = ("manifest.json", "recording.mp4")+MANIFEST_SCHEMA = "cua-visual-perception-demo-evidence/v3"+MAX_MANIFEST_SIZE = 1024 * 1024+MAX_RECORDING_SIZE = 100 * 1024 * 1024+MAX_ARCHIVE_SIZE = MAX_MANIFEST_SIZE + MAX_RECORDING_SIZE + 4096++MAGIC = b"CUAEVID\x00"+VERSION = 3+ALGORITHM_X25519_HKDF_SHA256_AES_256_GCM = 2+NONCE_SIZE = 12+TAG_SIZE = 16+X25519_KEY_SIZE = 32+HEADER = struct.Struct(">8sBBH32s32s12sQ")+# Header fields: magic, version, algorithm, flags, recipient fingerprint,+# ephemeral public key, nonce, ciphertext size.+HKDF_INFO = b"cua-visual-perception-evidence-envelope/v3\x00recipient-sha256\x00"+++def _regular_file(path: Path, label: str, maximum: int) -> bytes:+ try:+ mode = path.lstat().st_mode+ except FileNotFoundError as error:+ raise ValueError(f"{label} is missing") from error+ if not stat.S_ISREG(mode) or path.is_symlink():+ raise ValueError(f"{label} must be a regular file, not a link")+ size = path.stat().st_size+ if not 0 < size <= maximum:+ raise ValueError(f"{label} must be nonempty and at most {maximum} bytes")+ data = path.read_bytes()+ if len(data) != size:+ raise ValueError(f"{label} changed while it was being read")+ return data+++def _validate_manifest(manifest_bytes: bytes, recording_bytes: bytes) -> None:+ try:+ manifest = json.loads(manifest_bytes.decode("utf-8"))+ except (UnicodeDecodeError, json.JSONDecodeError) as error:+ raise ValueError("manifest.json must be valid UTF-8 JSON") from error+ if not isinstance(manifest, dict) or manifest.get("schema") != MANIFEST_SCHEMA:+ raise ValueError(f"manifest.json must use {MANIFEST_SCHEMA}")++ expected = [{+ "kind": "video",+ "path": "recording.mp4",+ "sha256": hashlib.sha256(recording_bytes).hexdigest(),+ "size_bytes": len(recording_bytes),+ }]+ if manifest.get("artifacts") != expected:+ raise ValueError("manifest.json does not bind the supplied recording.mp4")+++def _load_bundle(directory: Path) -> dict[str, bytes]:+ if directory.is_symlink() or not directory.is_dir():+ raise ValueError("input directory must be a real directory")+ names = sorted(item.name for item in directory.iterdir())+ if names != sorted(MEMBER_NAMES):+ raise ValueError(f"input directory must contain exactly {list(MEMBER_NAMES)}")+ members = {+ "manifest.json": _regular_file(directory / "manifest.json", "manifest.json", MAX_MANIFEST_SIZE),+ "recording.mp4": _regular_file(directory / "recording.mp4", "recording.mp4", MAX_RECORDING_SIZE),+ }+ _validate_manifest(members["manifest.json"], members["recording.mp4"])+ return members+++def _build_archive(members: dict[str, bytes]) -> bytes:+ output = BytesIO()+ with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_STORED, allowZip64=False) as archive:+ for name in MEMBER_NAMES:+ info = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0))+ info.compress_type = zipfile.ZIP_STORED+ info.create_system = 3+ info.create_version = 20+ info.extract_version = 20+ info.flag_bits = 0+ info.external_attr = (stat.S_IFREG | 0o600) << 16+ archive.writestr(info, members[name])+ value = output.getvalue()+ if len(value) > MAX_ARCHIVE_SIZE:+ raise ValueError("evidence archive exceeds the maximum size")+ return value+++def _read_archive(value: bytes) -> dict[str, bytes]:+ if not value or len(value) > MAX_ARCHIVE_SIZE:+ raise ValueError("decrypted evidence archive has an invalid size")+ try:+ with zipfile.ZipFile(BytesIO(value), "r") as archive:+ infos = archive.infolist()+ if [item.filename for item in infos] != list(MEMBER_NAMES):+ raise ValueError(f"evidence archive must contain exactly {list(MEMBER_NAMES)}")+ limits = (MAX_MANIFEST_SIZE, MAX_RECORDING_SIZE)+ for info, limit in zip(infos, limits):+ if info.is_dir() or info.flag_bits & 0x1 or info.compress_type != zipfile.ZIP_STORED:+ raise ValueError("evidence archive contains an unsupported member")+ if not 0 < info.file_size <= limit or info.compress_size != info.file_size:+ raise ValueError(f"{info.filename} has an invalid archived size")+ members = {info.filename: archive.read(info) for info in infos}+ except (zipfile.BadZipFile, RuntimeError) as error:+ raise ValueError("decrypted evidence archive is invalid") from error++ _validate_manifest(members["manifest.json"], members["recording.mp4"])+ if _build_archive(members) != value:+ raise ValueError("evidence archive is not in the canonical format")+ return members+++def _decode_key(value: str, label: str) -> bytes:+ try:+ encoded = value.encode("ascii")+ key = base64.b64decode(encoded, validate=True)+ except (UnicodeEncodeError, binascii.Error) as error:+ raise ValueError(f"{label} must be canonical base64") from error+ if len(key) != X25519_KEY_SIZE or base64.b64encode(key) != encoded:+ raise ValueError(f"{label} must be canonical base64 for exactly 32 bytes")+ return key+++def load_key(*, environment_name: str | None, key_file: Path | None, label: str) -> bytes:+ if (environment_name is None) == (key_file is None):+ raise ValueError("choose exactly one key source")+ if environment_name is not None:+ if not environment_name or not environment_name.replace("_", "A").isalnum():+ raise ValueError(f"{label} environment variable name is invalid")+ value = os.environ.get(environment_name)+ if value is None:+ raise ValueError(f"{label} environment variable {environment_name} is not set")+ return _decode_key(value, label)++ assert key_file is not None+ raw = _regular_file(key_file, f"{label} file", 256)+ try:+ value = raw.decode("ascii").rstrip("\r\n")+ except UnicodeDecodeError as error:+ raise ValueError(f"{label} file must contain ASCII base64") from error+ return _decode_key(value, label)+++def _require_x25519_key(key: bytes, label: str) -> None:+ if not isinstance(key, bytes) or len(key) != X25519_KEY_SIZE:+ raise ValueError(f"{label} must contain exactly 32 bytes")+++def _public_key_bytes(public_key: X25519PublicKey) -> bytes:+ return public_key.public_bytes(+ encoding=serialization.Encoding.Raw,+ format=serialization.PublicFormat.Raw,+ )+++def recipient_fingerprint(public_key: bytes) -> bytes:+ _require_x25519_key(public_key, "recipient public key")+ return hashlib.sha256(public_key).digest()+++def _derive_key(+ private_key: X25519PrivateKey,+ public_key: X25519PublicKey,+ recipient_key_fingerprint: bytes,+) -> bytes:+ if not isinstance(recipient_key_fingerprint, bytes) or len(recipient_key_fingerprint) != 32:+ raise ValueError("recipient key fingerprint must contain exactly 32 bytes")+ try:+ shared_secret = private_key.exchange(public_key)+ except ValueError as error:+ raise ValueError("X25519 key agreement failed") from error+ return HKDF(+ algorithm=hashes.SHA256(),+ length=32,+ salt=None,+ info=HKDF_INFO + recipient_key_fingerprint,+ ).derive(shared_secret)+++def encrypt_bundle(input_dir: Path, output: Path, recipient_public_key: bytes) -> str:+ _require_x25519_key(recipient_public_key, "recipient public key")+ members = _load_bundle(input_dir)+ archive = _build_archive(members)+ recipient = X25519PublicKey.from_public_bytes(recipient_public_key)+ ephemeral_private = X25519PrivateKey.generate()+ ephemeral_public = _public_key_bytes(ephemeral_private.public_key())+ fingerprint = recipient_fingerprint(recipient_public_key)+ key = _derive_key(ephemeral_private, recipient, fingerprint)+ nonce = os.urandom(NONCE_SIZE)+ ciphertext_size = len(archive) + TAG_SIZE+ header = HEADER.pack(+ MAGIC,+ VERSION,+ ALGORITHM_X25519_HKDF_SHA256_AES_256_GCM,+ 0,+ fingerprint,+ ephemeral_public,+ nonce,+ ciphertext_size,+ )+ ciphertext = AESGCM(key).encrypt(nonce, archive, header)+ _atomic_write(output, header + ciphertext)+ return fingerprint.hex()+++def decrypt_bundle(input_path: Path, output_dir: Path, recipient_private_key: bytes) -> None:+ _require_x25519_key(recipient_private_key, "recipient private key")+ envelope = _regular_file(input_path, "encrypted evidence", HEADER.size + MAX_ARCHIVE_SIZE + TAG_SIZE)+ if len(envelope) < HEADER.size + TAG_SIZE:+ raise ValueError("encrypted evidence envelope is truncated")+ header = envelope[:HEADER.size]+ (+ magic,+ version,+ algorithm,+ flags,+ expected_recipient_fingerprint,+ ephemeral_public,+ nonce,+ ciphertext_size,+ ) = HEADER.unpack(header)+ if (+ magic != MAGIC+ or version != VERSION+ or algorithm != ALGORITHM_X25519_HKDF_SHA256_AES_256_GCM+ or flags != 0+ ):+ raise ValueError("encrypted evidence envelope has an unsupported format")+ ciphertext = envelope[HEADER.size:]+ if ciphertext_size != len(ciphertext) or ciphertext_size > MAX_ARCHIVE_SIZE + TAG_SIZE:+ raise ValueError("encrypted evidence envelope has an invalid length")+ private_key = X25519PrivateKey.from_private_bytes(recipient_private_key)+ actual_recipient_fingerprint = recipient_fingerprint(_public_key_bytes(private_key.public_key()))+ if not hmac.compare_digest(actual_recipient_fingerprint, expected_recipient_fingerprint):+ raise ValueError("recipient private key does not match envelope recipient fingerprint")+ public_key = X25519PublicKey.from_public_bytes(ephemeral_public)+ key = _derive_key(private_key, public_key, expected_recipient_fingerprint)+ try:+ archive = AESGCM(key).decrypt(nonce, ciphertext, header)+ except InvalidTag as error:+ raise ValueError("encrypted evidence authentication failed") from error+ members = _read_archive(archive)+ _atomic_write_directory(output_dir, members)+++def _atomic_write(path: Path, value: bytes) -> None:+ if path.exists() or path.is_symlink():+ raise ValueError("output file already exists")+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)+ temporary: Path | None = None+ try:+ with tempfile.NamedTemporaryFile(prefix=f".{path.name}.", dir=path.parent, delete=False) as handle:+ temporary = Path(handle.name)+ os.chmod(temporary, 0o600)+ handle.write(value)+ handle.flush()+ os.fsync(handle.fileno())+ try:+ os.link(temporary, path)+ except FileExistsError as error:+ raise ValueError("output file already exists") from error+ temporary.unlink()+ temporary = None+ finally:+ if temporary is not None:+ temporary.unlink(missing_ok=True)+++def _atomic_write_directory(path: Path, members: dict[str, bytes]) -> None:+ if path.exists() or path.is_symlink():+ raise ValueError("output directory already exists")+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)+ temporary = Path(tempfile.mkdtemp(prefix=f".{path.name}.", dir=path.parent))+ try:+ for name in MEMBER_NAMES:+ target = temporary / name+ target.write_bytes(members[name])+ os.chmod(target, 0o600)+ try:+ _rename_directory_no_replace(temporary, path)+ except FileExistsError as error:+ raise ValueError("output directory already exists") from error+ finally:+ if temporary.exists():+ shutil.rmtree(temporary)+++def _rename_directory_no_replace(source: Path, destination: Path) -> None:+ if os.name == "nt":+ # Windows rename already fails when the destination exists.+ os.rename(source, destination)+ return++ if sys.platform == "darwin":+ libc = ctypes.CDLL(None, use_errno=True)+ rename_no_replace = libc.renamex_np+ rename_no_replace.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_uint]+ arguments = (os.fsencode(source), os.fsencode(destination), 0x00000004) # RENAME_EXCL+ elif sys.platform.startswith("linux"):+ libc = ctypes.CDLL(None, use_errno=True)+ try:+ rename_no_replace = libc.renameat2+ except AttributeError as error:+ raise OSError(+ errno.ENOTSUP,+ "atomic no-replace directory publication is unsupported",+ ) from error+ rename_no_replace.argtypes = [+ ctypes.c_int,+ ctypes.c_char_p,+ ctypes.c_int,+ ctypes.c_char_p,+ ctypes.c_uint,+ ]+ arguments = (-100, os.fsencode(source), -100, os.fsencode(destination), 1) # AT_FDCWD, RENAME_NOREPLACE+ else:+ raise OSError(errno.ENOTSUP, "atomic no-replace directory publication is unsupported")++ rename_no_replace.restype = ctypes.c_int+ result = rename_no_replace(*arguments)+ if result == 0:+ return++ error_number = ctypes.get_errno()+ if error_number in (errno.EEXIST, errno.ENOTEMPTY):+ raise FileExistsError(error_number, os.strerror(error_number), destination)+ raise OSError(error_number, os.strerror(error_number), destination)+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ subparsers = parser.add_subparsers(dest="command", required=True)+ encrypt = subparsers.add_parser("encrypt")+ encrypt.add_argument("--input", type=Path, required=True)+ encrypt.add_argument("--output", type=Path, required=True)+ recipient = encrypt.add_mutually_exclusive_group(required=True)+ recipient.add_argument("--recipient-env", metavar="NAME")+ recipient.add_argument("--recipient-file", type=Path)++ decrypt = subparsers.add_parser("decrypt")+ decrypt.add_argument("--input", type=Path, required=True)+ decrypt.add_argument("--output", type=Path, required=True)+ private = decrypt.add_mutually_exclusive_group(required=True)+ private.add_argument("--private-key-env", metavar="NAME")+ private.add_argument("--private-key-file", type=Path)+ args = parser.parse_args()+ try:+ if args.command == "encrypt":+ recipient_public_key = load_key(+ environment_name=args.recipient_env,+ key_file=args.recipient_file,+ label="recipient public key",+ )+ fingerprint = encrypt_bundle(args.input, args.output, recipient_public_key)+ print(f"recipient_public_key_sha256={fingerprint}")+ else:+ recipient_private_key = load_key(+ environment_name=args.private_key_env,+ key_file=args.private_key_file,+ label="recipient private key",+ )+ decrypt_bundle(args.input, args.output, recipient_private_key)+ except (OSError, ValueError) as error:+ parser.error(str(error))+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/libs/cua-driver/tests/perception-demo/sanitize_derived_reel.py b/libs/cua-driver/tests/perception-demo/sanitize_derived_reel.pynew file mode 100644index 0000000000..de0186c452--- /dev/null+++ b/libs/cua-driver/tests/perception-demo/sanitize_derived_reel.py@@ -0,0 +1,265 @@+#!/usr/bin/env python3+"""Validate and publish a privacy-bounded reel derived from raw demo evidence."""++from __future__ import annotations++import argparse+import hashlib+import json+from pathlib import Path, PurePosixPath+import re+import shutil+import subprocess+++SHA40 = re.compile(r"^[0-9a-f]{40}$")+SHA64 = re.compile(r"^[0-9a-f]{64}$")+SAFE_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$")+WAIT_DISCLOSURE = "wait-only interval removed; no action or result omitted"+MAX_VIDEO_SIZE = 100 * 1024 * 1024+++def sha256_file(path: Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as source:+ for block in iter(lambda: source.read(1024 * 1024), b""):+ digest.update(block)+ return digest.hexdigest()+++def load_json(path: Path, label: str, maximum: int = 1024 * 1024) -> dict:+ if not path.is_file() or not 0 < path.stat().st_size <= maximum:+ raise ValueError(f"{label} must be a nonempty regular file no larger than {maximum} bytes")+ value = json.loads(path.read_text(encoding="utf-8"))+ if not isinstance(value, dict):+ raise ValueError(f"{label} must be a JSON object")+ return value+++def resolve_input(root: Path, relative_text: str, label: str) -> Path:+ if not isinstance(relative_text, str):+ raise ValueError(f"{label} path must be a string")+ relative = PurePosixPath(relative_text)+ if relative.is_absolute() or not relative.parts or ".." in relative.parts:+ raise ValueError(f"{label} path must be a safe relative path")+ resolved_root = root.resolve()+ resolved = root.joinpath(*relative.parts).resolve()+ try:+ resolved.relative_to(resolved_root)+ except ValueError as error:+ raise ValueError(f"{label} path escapes the source root") from error+ if not resolved.is_file():+ raise ValueError(f"{label} must be a regular file")+ return resolved+++def probe_video(path: Path, *, decode: bool) -> dict:+ if not path.is_file() or not 0 < path.stat().st_size <= MAX_VIDEO_SIZE:+ raise ValueError("video must be a nonempty regular file no larger than 100 MiB")+ if decode:+ subprocess.run(+ ["ffmpeg", "-v", "error", "-xerror", "-i", str(path), "-map", "0:v:0", "-f", "null", "-"],+ check=True,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.PIPE,+ )+ result = subprocess.run(+ ["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=avg_frame_rate:format=duration", "-of", "json", str(path)],+ check=True,+ capture_output=True,+ text=True,+ )+ value = json.loads(result.stdout)+ streams = value.get("streams")+ if not isinstance(streams, list) or len(streams) != 1:+ raise ValueError("video must contain exactly one video stream")+ try:+ numerator, denominator = map(int, streams[0]["avg_frame_rate"].split("/", 1))+ duration_ms = round(float(value["format"]["duration"]) * 1000)+ except (KeyError, TypeError, ValueError, ZeroDivisionError) as error:+ raise ValueError("video metadata is incomplete") from error+ if min(numerator, denominator, duration_ms) <= 0:+ raise ValueError("video metadata must be positive")+ return {"duration_ms": duration_ms, "frame_duration_ms": 1000 * denominator / numerator}+++def validate_source_manifest(manifest: dict, recording: Path) -> tuple[str, str]:+ try:+ artifact = manifest["artifacts"]+ recording_value = manifest["recording"]+ driver = manifest["runtime"]["driver"]+ perception = manifest["runtime"]["perception"]+ chooser = manifest["runtime"]["chooser"]+ except (KeyError, TypeError) as error:+ raise ValueError("source evidence manifest is incomplete") from error+ digest = sha256_file(recording)+ size = recording.stat().st_size+ if (+ manifest.get("schema") != "cua-visual-perception-demo-evidence/v3"+ or manifest.get("platform") not in {"windows", "linux-x11", "macos"}+ or manifest.get("fixture", {}).get("id") != "visual-only-canvas/v1"+ or manifest.get("result", {}).get("status") != "passed"+ or manifest.get("result", {}).get("stale_capture_refused") is not True+ or perception.get("trust") != "review-only-publisher-verified"+ or perception.get("signature_algorithm") != "ed25519"+ or chooser.get("mode") != "live"+ or chooser.get("provider") != "typesafe"+ or not chooser.get("model_id")+ ):+ raise ValueError("source evidence is not a passed, signed, live visual demo")+ if not SHA40.fullmatch(driver.get("source_sha", "")) or not SHA40.fullmatch(chooser.get("source_sha", "")):+ raise ValueError("source evidence contains an invalid source identity")+ expected_artifact = [{"kind": "video", "path": "recording.mp4", "sha256": digest, "size_bytes": size}]+ if artifact != expected_artifact or recording_value.get("final_sha256") != digest or recording_value.get("size_bytes") != size:+ raise ValueError("source recording bytes differ from the source evidence manifest")+ return driver["source_sha"], chooser["source_sha"]+++def checked_range(value: dict, label: str, duration_ms: int) -> dict:+ if not isinstance(value, dict) or set(value) != {"start_ms", "end_ms"}:+ raise ValueError(f"{label} must contain exactly start_ms and end_ms")+ start, end = value["start_ms"], value["end_ms"]+ if type(start) is not int or type(end) is not int or not 0 <= start < end <= duration_ms:+ raise ValueError(f"{label} is outside its measured source duration")+ return {"start_ms": start, "end_ms": end}+++def build_manifest(*, source_root: Path, edit_plan: Path, reel: Path) -> dict:+ plan = load_json(edit_plan, "edit plan")+ if set(plan) != {"schema", "sources", "shots", "wait_cuts"} or plan["schema"] != "cua-derived-reel-edit-plan/v1":+ raise ValueError("edit plan does not match cua-derived-reel-edit-plan/v1")+ source_values, shot_values, wait_values = plan["sources"], plan["shots"], plan["wait_cuts"]+ if not isinstance(source_values, list) or not 1 <= len(source_values) <= 8:+ raise ValueError("edit plan must contain one through eight sources")+ if not isinstance(shot_values, list) or len(shot_values) < 2:+ raise ValueError("derived reel must contain at least two real trim operations")+ if not isinstance(wait_values, list):+ raise ValueError("wait_cuts must be an array")++ sources: dict[str, dict] = {}+ identities: set[tuple[str, str]] = set()+ for source in source_values:+ if not isinstance(source, dict) or set(source) != {"id", "evidence_manifest", "recording"}:+ raise ValueError("each source must contain exactly id, evidence_manifest, and recording")+ source_id = source.get("id")+ if not isinstance(source_id, str) or not SAFE_ID.fullmatch(source_id) or source_id in sources:+ raise ValueError("source IDs must be unique safe identifiers")+ manifest_path = resolve_input(source_root, source["evidence_manifest"], f"{source_id} manifest")+ recording_path = resolve_input(source_root, source["recording"], f"{source_id} recording")+ manifest = load_json(manifest_path, f"{source_id} evidence manifest")+ identities.add(validate_source_manifest(manifest, recording_path))+ probe = probe_video(recording_path, decode=False)+ sources[source_id] = {+ "id": source_id,+ "platform": manifest["platform"],+ "evidence_manifest_sha256": sha256_file(manifest_path),+ "recording_sha256": sha256_file(recording_path),+ "duration_ms": probe["duration_ms"],+ "used_ranges": [],+ "removed_wait_ranges": [],+ }+ if len(identities) != 1:+ raise ValueError("all source evidence must bind the same Driver and Jev source SHAs")++ operations = []+ reel_cursor = 0+ for index, shot in enumerate(shot_values):+ if not isinstance(shot, dict) or set(shot) != {"source_id", "start_ms", "end_ms"}:+ raise ValueError(f"shot {index} must contain exactly source_id, start_ms, and end_ms")+ source_id = shot.get("source_id")+ if source_id not in sources:+ raise ValueError(f"shot {index} names an unknown source")+ span = checked_range({"start_ms": shot["start_ms"], "end_ms": shot["end_ms"]}, f"shot {index}", sources[source_id]["duration_ms"])+ prior = sources[source_id]["used_ranges"]+ if prior and span["start_ms"] < prior[-1]["end_ms"]:+ raise ValueError("shots from each source must be ordered and non-overlapping")+ prior.append(span)+ length = span["end_ms"] - span["start_ms"]+ operations.append({+ "operation": "trim", "source_id": source_id,+ "source_start_ms": span["start_ms"], "source_end_ms": span["end_ms"],+ "reel_start_ms": reel_cursor, "reel_end_ms": reel_cursor + length, "speed": "1x",+ })+ reel_cursor += length++ declared_waits: dict[tuple[str, int, int], dict] = {}+ for index, wait_cut in enumerate(wait_values):+ if not isinstance(wait_cut, dict) or set(wait_cut) != {"source_id", "start_ms", "end_ms", "disclosure"}:+ raise ValueError(f"wait cut {index} has unexpected fields")+ source_id = wait_cut.get("source_id")+ if source_id not in sources or wait_cut.get("disclosure") != WAIT_DISCLOSURE:+ raise ValueError("every removed wait must use the exact no-action-omitted disclosure")+ span = checked_range({"start_ms": wait_cut["start_ms"], "end_ms": wait_cut["end_ms"]}, f"wait cut {index}", sources[source_id]["duration_ms"])+ key = (source_id, span["start_ms"], span["end_ms"])+ if key in declared_waits:+ raise ValueError("wait cuts must be unique")+ disclosed = {**span, "disclosure": WAIT_DISCLOSURE}+ declared_waits[key] = disclosed+ sources[source_id]["removed_wait_ranges"].append(disclosed)++ required_waits = set()+ for source_id, source in sources.items():+ ranges = source["used_ranges"]+ for before, after in zip(ranges, ranges[1:]):+ if before["end_ms"] < after["start_ms"]:+ required_waits.add((source_id, before["end_ms"], after["start_ms"]))+ if set(declared_waits) != required_waits:+ raise ValueError("wait_cuts must disclose every and only internal interval omitted between used ranges")++ reel_probe = probe_video(reel, decode=True)+ tolerance_ms = max(100, round(reel_probe["frame_duration_ms"] * 2))+ if abs(reel_probe["duration_ms"] - reel_cursor) > tolerance_ms:+ raise ValueError("decoded reel duration does not match the declared 1x edit timeline")+ reel_size = reel.stat().st_size+ reel_sha = sha256_file(reel)+ source_sha, jev_source_sha = identities.pop()+ operations.append({"operation": "concatenate", "shot_count": len(shot_values)})+ return {+ "schema": "cua-visual-perception-derived-reel/v1",+ "identity": {+ "source_sha": source_sha, "jev_source_sha": jev_source_sha,+ "fixture": "visual-only-canvas/v1", "chooser_provider": "typesafe",+ },+ "sources": list(sources.values()),+ "edit_operations": operations,+ "recording": {+ "expected_duration_ms": reel_cursor, "decoded_duration_ms": reel_probe["duration_ms"],+ "fully_decoded": True, "final_sha256": reel_sha, "size_bytes": reel_size,+ },+ "artifacts": [{"kind": "video", "path": "reel.mp4", "sha256": reel_sha, "size_bytes": reel_size}],+ }+++def validate_manifest_schema(manifest: dict, schema_path: Path | None = None) -> None:+ """Validate the closed publication shape after semantic/source checks pass."""+ try:+ from jsonschema import Draft202012Validator+ except ImportError as error:+ raise ValueError("jsonschema is required to validate derived reel evidence") from error+ path = schema_path or Path(__file__).with_name("derived-reel-manifest.schema.json")+ schema = load_json(path, "derived reel schema")+ Draft202012Validator.check_schema(schema)+ errors = sorted(Draft202012Validator(schema).iter_errors(manifest), key=lambda item: list(item.path))+ if errors:+ raise ValueError(f"derived reel manifest violates its schema: {errors[0].message}")+++def main() -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument("--source-root", type=Path, required=True)+ parser.add_argument("--edit-plan", type=Path, required=True)+ parser.add_argument("--reel", type=Path, required=True)+ parser.add_argument("--output-dir", type=Path, required=True)+ args = parser.parse_args()+ manifest = build_manifest(source_root=args.source_root, edit_plan=args.edit_plan, reel=args.reel)+ validate_manifest_schema(manifest)+ if args.output_dir.exists() and any(args.output_dir.iterdir()):+ raise ValueError("output directory must be empty before reel publication")+ args.output_dir.mkdir(parents=True, exist_ok=True)+ shutil.copyfile(args.reel, args.output_dir / "reel.mp4")+ (args.output_dir / "manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/libs/cua-driver/tests/perception-demo/sanitize_evidence.py b/libs/cua-driver/tests/perception-demo/sanitize_evidence.pynew file mode 100644index 0000000000..e92199176c--- /dev/null+++ b/libs/cua-driver/tests/perception-demo/sanitize_evidence.py@@ -0,0 +1,748 @@+#!/usr/bin/env python3+"""Build redacted demo evidence from Driver-measured installed state."""++from __future__ import annotations++import argparse+import base64+import hashlib+import json+import math+import os+from pathlib import Path+import re+import shutil+import subprocess+import sys+++SHA40 = re.compile(r"^[0-9a-f]{40}$")+SHA64 = re.compile(r"^[0-9a-f]{64}$")+SAFE_ID = re.compile(r"^[A-Za-z0-9._:/-]{1,96}$")+CHOOSER_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$")+SAFE_TEXT = re.compile(r"^[^\x00-\x1f\x7f]{1,256}$")+MAX_REGIONS = 64+MAX_REGION_TEXT = 128+++def sha256_file(path: Path) -> str:+ hasher = hashlib.sha256()+ with path.open("rb") as source:+ for chunk in iter(lambda: source.read(1024 * 1024), b""):+ hasher.update(chunk)+ return hasher.hexdigest()+++def require_file(path: Path, label: str, maximum: int) -> int:+ if not path.is_file():+ raise ValueError(f"{label} must be a regular file")+ size = path.stat().st_size+ if not 0 < size <= maximum:+ raise ValueError(f"{label} must be nonempty and at most {maximum} bytes")+ return size+++def load_json(path: Path, label: str, maximum: int = 1024 * 1024) -> dict:+ require_file(path, label, maximum)+ value = json.loads(path.read_text(encoding="utf-8"))+ if not isinstance(value, dict):+ raise ValueError(f"{label} must be a JSON object")+ return value+++def measure_source_sha(repo_root: Path, expected_source_sha: str) -> str:+ if not SHA40.fullmatch(expected_source_sha):+ raise ValueError("expected source SHA must be 40 lowercase hexadecimal characters")+ result = subprocess.run(+ ["git", "-C", str(repo_root), "rev-parse", "HEAD"],+ check=True,+ capture_output=True,+ text=True,+ )+ measured = result.stdout.strip()+ if measured != expected_source_sha:+ raise ValueError("checked-out source does not match the approved workflow candidate")+ return measured+++def measure_platform(platform_name: str = sys.platform, environment: dict = os.environ) -> str:+ if platform_name == "win32":+ return "windows"+ if platform_name == "darwin":+ return "macos"+ if platform_name.startswith("linux") and environment.get("DISPLAY"):+ return "linux-x11"+ raise ValueError("evidence sanitizer requires macOS, Windows, or an active Linux X11 session")+++def probe_recording(path: Path) -> dict:+ result = subprocess.run(+ [+ "ffprobe", "-v", "error", "-select_streams", "v:0",+ "-show_entries", "stream=width,height,avg_frame_rate:format=duration",+ "-of", "json", str(path),+ ],+ check=True,+ capture_output=True,+ text=True,+ )+ value = json.loads(result.stdout)+ streams = value.get("streams")+ if not isinstance(streams, list) or len(streams) != 1:+ raise ValueError("recording must contain exactly one measured video stream")+ stream = streams[0]+ try:+ numerator, denominator = (int(part) for part in stream["avg_frame_rate"].split("/", 1))+ width, height = int(stream["width"]), int(stream["height"])+ duration_ms = round(float(value["format"]["duration"]) * 1000)+ except (KeyError, TypeError, ValueError, ZeroDivisionError) as error:+ raise ValueError("recording metadata is incomplete") from error+ if min(width, height, numerator, denominator, duration_ms) <= 0:+ raise ValueError("recording metadata must be positive")+ return {+ "width": width,+ "height": height,+ "frame_rate": {"numerator": numerator, "denominator": denominator},+ "duration_ms": duration_ms,+ }+++def load_extension_status(path: Path) -> dict:+ value = load_json(path, "Driver extension status")+ if (+ value.get("id") != "cua-perception"+ or value.get("installed") is not True+ or value.get("healthy") is not True+ or value.get("trust") != "review-only-publisher-verified"+ ):+ raise ValueError("Driver did not report a healthy review-only publisher-verified perception extension")+ for field in ("active_version", "publisher_id", "publisher_key_id"):+ if not isinstance(value.get(field), str) or not SAFE_ID.fullmatch(value[field]):+ raise ValueError(f"Driver extension status contains an invalid {field}")+ if type(value.get("catalog_version")) is not int or value["catalog_version"] <= 0:+ raise ValueError("Driver extension status contains an invalid catalog_version")+ if type(value.get("protocol_version")) is not int or value["protocol_version"] <= 0:+ raise ValueError("Driver extension status contains an invalid protocol_version")+ return value+++def load_oracle(path: Path) -> dict:+ value = load_json(path, "fixture oracle", 64 * 1024)+ expected = {"fixture", "ready", "selected", "action_count"}+ if set(value) != expected:+ raise ValueError(f"fixture oracle keys must be exactly {sorted(expected)}")+ if value["fixture"] != "visual-only-canvas/v1" or value["ready"] is not True:+ raise ValueError("fixture oracle is not a ready visual-only canvas")+ if value["selected"] not in {"save", "send", "cancel"}:+ raise ValueError("fixture oracle contains an unexpected selection")+ if type(value["action_count"]) is not int or not 1 <= value["action_count"] <= 8:+ raise ValueError("fixture oracle action_count must be an integer from 1 through 8")+ return value+++def load_parser_result(path: Path) -> dict:+ value = load_json(path, "parser result")+ model_id = value.get("parser", {}).get("model_id")+ if value.get("schema") != "cua.visual_regions_v1" or not isinstance(model_id, str) or not SAFE_ID.fullmatch(model_id):+ raise ValueError("parser result does not contain safe measured model metadata")+ return value+++def load_chooser_result(path: Path) -> dict:+ value = load_json(path, "chooser result", 64 * 1024)+ expected = {"schema", "selected_id", "model", "confidence", "probabilities"}+ if set(value) != expected or value["schema"] != "cua.jev_choice_v1":+ raise ValueError("chooser result does not match cua.jev_choice_v1")+ model = value.get("model")+ if model is not None and (not isinstance(model, str) or not SAFE_ID.fullmatch(model)):+ raise ValueError("chooser result contains invalid model metadata")+ if not isinstance(value["selected_id"], str) or not CHOOSER_ID.fullmatch(value["selected_id"]):+ raise ValueError("chooser result contains an unsafe selected_id")+ confidence = value["confidence"]+ probabilities = value["probabilities"]+ if type(confidence) not in (int, float) or not 0 <= confidence <= 1:+ raise ValueError("chooser result contains an invalid confidence")+ if not isinstance(probabilities, dict):+ raise ValueError("chooser probabilities must be an object")+ if any(not isinstance(key, str) or not CHOOSER_ID.fullmatch(key) for key in probabilities):+ raise ValueError("chooser probabilities contain an unsafe candidate ID")+ if any(type(item) not in (int, float) or not 0 <= item <= 1 for item in probabilities.values()):+ raise ValueError("chooser result contains an invalid probability")+ return value+++def validate_compact_regions(value: object, width: int, height: int, label: str) -> list[dict]:+ if not isinstance(value, list) or not 1 <= len(value) <= MAX_REGIONS:+ raise ValueError(f"{label} must be a nonempty bounded region list")+ regions = []+ for region in value:+ if not isinstance(region, dict):+ raise ValueError(f"{label} contains an invalid compact region")+ required = {"id", "kind", "bounds", "confidence", "interactive"}+ optional = {"text", "label"}+ if not required <= set(region) or not set(region) <= required | optional:+ raise ValueError(f"{label} contains an invalid compact region")+ region_id = region["id"]+ kind = region["kind"]+ if (+ not isinstance(region_id, str)+ or not CHOOSER_ID.fullmatch(region_id)+ or len(region_id) > 64 - len("region:")+ or kind not in {"text", "icon"}+ ):+ raise ValueError(f"{label} contains unsafe region identity")+ for field in optional & set(region):+ text = region[field]+ if (+ not isinstance(text, str)+ or text != text.strip()+ or len(text.encode("utf-8")) > MAX_REGION_TEXT+ or not SAFE_TEXT.fullmatch(text)+ ):+ raise ValueError(f"{label} contains unsafe region text or label")+ if (kind == "text" and "text" not in region) or (kind == "icon" and "label" not in region):+ raise ValueError(f"{label} contains content missing for its region kind")+ confidence = region["confidence"]+ if (+ type(confidence) not in (int, float)+ or not math.isfinite(confidence)+ or not 0 <= confidence <= 1+ or type(region["interactive"]) is not bool+ ):+ raise ValueError(f"{label} contains invalid confidence or interactivity")+ bounds = region["bounds"]+ if not isinstance(bounds, dict) or set(bounds) != {"x", "y", "width", "height"}:+ raise ValueError(f"{label} contains invalid region bounds")+ if (+ any(type(bounds[field]) is not int for field in bounds)+ or bounds["x"] < 0+ or bounds["y"] < 0+ or bounds["width"] <= 0+ or bounds["height"] <= 0+ or bounds["x"] + bounds["width"] > width+ or bounds["y"] + bounds["height"] > height+ ):+ raise ValueError(f"{label} contains region bounds outside the observation")+ regions.append(region)+ if len({region["id"] for region in regions}) != len(regions):+ raise ValueError(f"{label} contains duplicate region IDs")+ return regions+++def load_candidate_measurements(path: Path) -> dict:+ value = load_json(path, "candidate measurements", 64 * 1024)+ expected = {+ "review_only",+ "source_sha",+ "target",+ "supplied_model_asset_id",+ "supplied_model_sha256",+ "supplied_model_size",+ "public_key_base64",+ "public_key_sha256",+ "key_id",+ "publisher_id",+ "signature_algorithm",+ "catalog_sha256",+ "archive_sha256",+ "review_driver_relative_path",+ "review_driver_build_profile",+ "review_driver_sha256",+ "code_signing",+ "review_driver_version",+ "extension_version",+ "protocol_version",+ "worker_sha256",+ "models",+ "onnx_runtime",+ "self_test",+ "sealed_artifact_manifest_sha256",+ "sealed_extension_manifest_sha256",+ }+ if (+ set(value) != expected+ or value["review_only"] is not True+ or value["signature_algorithm"] != "ed25519"+ or value["key_id"] != "review-only-build-override"+ or value["publisher_id"] != "cua-review-only"+ or value["review_driver_build_profile"] != "debug-review-trust-root"+ ):+ raise ValueError("candidate measurements do not match the signed artifact contract")+ for field in (+ "supplied_model_sha256",+ "public_key_sha256",+ "catalog_sha256",+ "archive_sha256",+ "review_driver_sha256",+ "worker_sha256",+ "sealed_artifact_manifest_sha256",+ "sealed_extension_manifest_sha256",+ ):+ if not isinstance(value[field], str) or not SHA64.fullmatch(value[field]):+ raise ValueError(f"candidate measurements contain an invalid {field}")+ if not isinstance(value["source_sha"], str) or not SHA40.fullmatch(value["source_sha"]):+ raise ValueError("candidate measurements contain an invalid source_sha")+ for field in ("target", "review_driver_relative_path"):+ if not isinstance(value[field], str) or not SAFE_ID.fullmatch(value[field]):+ raise ValueError(f"candidate measurements contain an invalid {field}")+ for field in ("review_driver_version", "extension_version"):+ if not isinstance(value[field], str) or not SAFE_ID.fullmatch(value[field]):+ raise ValueError(f"candidate measurements contain an invalid {field}")+ if type(value["protocol_version"]) is not int or value["protocol_version"] <= 0:+ raise ValueError("candidate measurements contain an invalid protocol_version")+ code_signing = value["code_signing"]+ if not isinstance(code_signing, dict) or set(code_signing) != {+ "status", "format", "identity", "certificate_sha256", "designated_requirement"+ }:+ raise ValueError("candidate measurements contain invalid code-signing evidence")+ if value["target"] == "aarch64-apple-darwin":+ if (+ code_signing.get("status") != "verified"+ or code_signing.get("format") != "apple-codesign"+ or code_signing.get("identity") != "ephemeral-self-signed-review-only"+ or not isinstance(code_signing.get("certificate_sha256"), str)+ or not SHA64.fullmatch(code_signing["certificate_sha256"])+ or not isinstance(code_signing.get("designated_requirement"), str)+ or not 1 <= len(code_signing["designated_requirement"]) <= 4096+ or not any(marker in code_signing["designated_requirement"] for marker in ("certificate leaf", "certificate root"))+ ):+ raise ValueError("macOS candidate lacks verified certificate-backed review signing")+ elif value["target"] in {"x86_64-unknown-linux-gnu", "x86_64-pc-windows-msvc"}:+ if code_signing != {+ "status": "not-applicable",+ "format": "none",+ "identity": "none",+ "certificate_sha256": None,+ "designated_requirement": None,+ }:+ raise ValueError("non-macOS candidate has misleading code-signing evidence")+ else:+ raise ValueError("candidate measurements contain an unsupported target")+ self_test = value["self_test"]+ if (+ not isinstance(self_test, dict)+ or set(self_test) != {"status", "mismatch_rejection", "evidence_sha256"}+ or self_test.get("status") != "passed"+ or self_test.get("mismatch_rejection") is not True+ or not isinstance(self_test.get("evidence_sha256"), str)+ or not SHA64.fullmatch(self_test["evidence_sha256"])+ ):+ raise ValueError("candidate measurements contain invalid self-test evidence")+ runtime = value["onnx_runtime"]+ if set(runtime) != {"revision", "sha256", "license"} or not SAFE_ID.fullmatch(runtime.get("revision", "")) or not SHA64.fullmatch(runtime.get("sha256", "")) or not SAFE_ID.fullmatch(runtime.get("license", "")):+ raise ValueError("candidate measurements contain invalid ONNX Runtime evidence")+ models = value["models"]+ if (+ not isinstance(models, list)+ or any(not isinstance(item, dict) for item in models)+ or [item.get("role") for item in models]+ != ["icon-detect", "ocr-detect", "ocr-recognize"]+ ):+ raise ValueError("candidate measurements must contain all three ordered model identities")+ for model in models:+ if set(model) != {"role", "id", "revision", "original_sha256", "converted_sha256", "license"}:+ raise ValueError("candidate measurements contain an invalid model record")+ if any(not isinstance(model[field], str) or not SAFE_ID.fullmatch(model[field]) for field in ("role", "id", "revision", "license")):+ raise ValueError("candidate measurements contain unsafe model metadata")+ if any(not SHA64.fullmatch(model[field]) for field in ("original_sha256", "converted_sha256")):+ raise ValueError("candidate measurements contain invalid model hashes")+ for field in ("supplied_model_asset_id", "supplied_model_size"):+ if type(value[field]) is not int or value[field] <= 0:+ raise ValueError(f"candidate measurements contain an invalid {field}")+ try:+ public_key = base64.b64decode(value["public_key_base64"], validate=True)+ except (ValueError, TypeError) as error:+ raise ValueError("candidate measurements contain invalid public_key_base64") from error+ if len(public_key) != 32 or hashlib.sha256(public_key).hexdigest() != value["public_key_sha256"]:+ raise ValueError("candidate measurements contain a mismatched Ed25519 public key")+ return value+++def build_manifest(+ *,+ source_sha: str,+ platform: str,+ jev_source_sha: str,+ session_label: str,+ os_name: str,+ os_version: str,+ os_arch: str,+ chooser_mode: str,+ candidate_measurements: Path,+ driver_binary: Path,+ extension_status: Path,+ parser_result: Path,+ chooser_result: Path,+ model: Path,+ oracle: Path,+ raw_evidence: Path,+ recording: Path,+) -> dict:+ if not SHA40.fullmatch(source_sha):+ raise ValueError("source_sha must be 40 lowercase hexadecimal characters")+ if platform not in {"windows", "linux-x11", "macos"}:+ raise ValueError("platform must be windows, linux-x11, or macos")+ if not SHA40.fullmatch(jev_source_sha):+ raise ValueError("jev_source_sha must be 40 lowercase hexadecimal characters")+ for label, value in (+ ("session_label", session_label),+ ("os_name", os_name),+ ("os_version", os_version),+ ("os_arch", os_arch),+ ):+ if not SAFE_ID.fullmatch(value):+ raise ValueError(f"{label} must be a safe bounded identifier")+ if chooser_mode not in {"mock", "live"}:+ raise ValueError("chooser_mode must be mock or live")+ status = load_extension_status(extension_status)+ parser = load_parser_result(parser_result)+ chooser = load_chooser_result(chooser_result)+ oracle_value = load_oracle(oracle)+ measurements = load_candidate_measurements(candidate_measurements)+ if measurements["source_sha"] != source_sha:+ raise ValueError("candidate measurements do not match source_sha")+ expected_target = {+ "windows": "x86_64-pc-windows-msvc",+ "linux-x11": "x86_64-unknown-linux-gnu",+ "macos": "aarch64-apple-darwin",+ }[platform]+ if measurements["target"] != expected_target:+ raise ValueError("candidate measurements do not match the measured platform")+ if (+ status["publisher_id"] != measurements["publisher_id"]+ or status["publisher_key_id"] != measurements["key_id"]+ ):+ raise ValueError("Driver status does not match candidate publisher identity")+ if status["active_version"] != measurements["extension_version"] or status.get("protocol_version") != measurements["protocol_version"]:+ raise ValueError("Driver status does not match sealed extension version or protocol")+ if chooser_mode == "live" and chooser["model"] is None:+ raise ValueError("live chooser did not return its model identity")+ raw = load_json(raw_evidence, "raw evidence", 8 * 1024 * 1024)+ expected_raw_keys = {+ "schema", "source_sha", "jev_source_sha", "platform", "capture_ids",+ "observation", "fixture_oracle", "extension_status", "parser", "chooser",+ "host_validated_regions", "resolved_action", "verification", "timeline", "recording",+ }+ if set(raw) != expected_raw_keys or raw.get("schema") != "cua-visual-perception-demo-raw/v2":+ raise ValueError("raw evidence does not match the closed live demo contract")+ if (+ raw["source_sha"] != source_sha+ or raw["jev_source_sha"] != jev_source_sha+ or raw["platform"] != platform+ ):+ raise ValueError("raw evidence does not match the approved sources and measured platform")+ if raw["fixture_oracle"] != oracle_value:+ raise ValueError("raw evidence fixture oracle differs from the measured fixture result")+ if raw["extension_status"] != status:+ raise ValueError("raw evidence extension status differs from Driver measured state")+ if raw["parser"] != parser["parser"]:+ raise ValueError("raw evidence parser identity differs from the measured parser result")+ chooser_record = raw.get("chooser")+ if (+ not isinstance(chooser_record, dict)+ or set(chooser_record) != {"mode", "request", "response"}+ or chooser_record["mode"] != chooser_mode+ or chooser_record["response"] != chooser+ ):+ raise ValueError("raw evidence chooser result differs from the measured chooser result")+ is_desktop = raw.get("observation", {}).get("input_scope") == "desktop"+ expected_route_proof = True if is_desktop else None+ expected_verification = {+ "oracle": "passed",+ "background_desktop_refused": expected_route_proof,+ "capture_preserved_after_refusal": expected_route_proof,+ "stale_capture_refused": True,+ }+ if raw.get("verification") != expected_verification:+ raise ValueError(+ "raw evidence does not prove the fixture result, desktop/background refusal, "+ "capture preservation, and stale-capture refusal"+ )+ background_event = (+ "background_desktop_refused" if is_desktop else "background_refusal_not_applicable"+ )+ timeline = raw.get("timeline")+ if (+ not isinstance(timeline, dict)+ or set(timeline) != {"duration_ms", "events"}+ or type(timeline["duration_ms"]) is not int+ or timeline["duration_ms"] <= 0+ or timeline["events"] != [+ "observed", "parsed", "chosen", background_event, "clicked", "oracle_verified",+ "stale_capture_refused", "reobserved",+ ]+ ):+ raise ValueError("raw evidence timeline does not prove the complete live demo sequence")+ captures = raw.get("capture_ids")+ if (+ not isinstance(captures, dict)+ or set(captures) != {"acted", "fresh"}+ or any(not isinstance(value, str) or not SAFE_ID.fullmatch(value) for value in captures.values())+ ):+ raise ValueError("raw evidence must contain exact safe acted and fresh capture IDs")+ require_file(driver_binary, "Driver binary", 512 * 1024 * 1024)+ driver_binary_sha256 = sha256_file(driver_binary)+ if driver_binary_sha256 != measurements["review_driver_sha256"]:+ raise ValueError("Driver binary hash does not match candidate measurements")+ require_file(model, "model", 8 * 1024 * 1024 * 1024)+ model_sha256 = sha256_file(model)+ if model_sha256 != measurements["supplied_model_sha256"]:+ raise ValueError("model hash is absent from candidate measurements")+ if model_sha256 != measurements["models"][0]["converted_sha256"]:+ raise ValueError("model hash differs from the sealed OmniParser identity")+ require_file(raw_evidence, "raw evidence", 8 * 1024 * 1024)+ video_size = require_file(recording, "recording.mp4", 100 * 1024 * 1024)+ recording_probe = probe_recording(recording)+ observation = raw.get("observation")+ if not isinstance(observation, dict) or set(observation) != {+ "input_scope", "capture_kind", "capture_source", "width", "height",+ "desktop_session", "runner_identity_class", "delivery_mode",+ }:+ raise ValueError("raw evidence must contain exact measured observation context")+ for field in ("input_scope", "capture_kind", "capture_source", "desktop_session", "runner_identity_class", "delivery_mode"):+ if not isinstance(observation[field], str) or not SAFE_ID.fullmatch(observation[field]):+ raise ValueError(f"raw evidence contains invalid observation {field}")+ accepted_routes = {+ ("window", "get_window_state", "background"),+ ("desktop", "get_desktop_state", "foreground"),+ }+ route = (+ observation["input_scope"],+ observation["capture_kind"],+ observation["delivery_mode"],+ )+ if route not in accepted_routes or observation["capture_source"] != "driver-screenshot":+ raise ValueError("raw evidence observation context differs from the executed demo")+ if any(type(observation[field]) is not int or observation[field] <= 0 for field in ("width", "height")):+ raise ValueError("raw evidence contains invalid capture dimensions")+ request = chooser_record["request"]+ if not isinstance(request, dict):+ raise ValueError("raw evidence chooser request must be an object")+ host_regions = validate_compact_regions(+ raw.get("host_validated_regions"), observation["width"], observation["height"],+ "raw evidence host_validated_regions",+ )+ request_regions = validate_compact_regions(+ request.get("regions"), observation["width"], observation["height"],+ "raw evidence chooser request regions",+ )+ host_regions_by_id = {region["id"]: region for region in host_regions}+ if any(host_regions_by_id.get(region["id"]) != region for region in request_regions):+ raise ValueError("chooser request regions are not a subset of host_validated_regions")+ candidate_values = request.get("candidates")+ if not isinstance(candidate_values, list) or not 2 <= len(candidate_values) <= 18:+ raise ValueError("raw evidence must contain the bounded chooser candidates")+ candidates = []+ for candidate in candidate_values:+ if (+ not isinstance(candidate, dict)+ or set(candidate) != {"id", "description"}+ or not CHOOSER_ID.fullmatch(candidate.get("id", ""))+ or not SAFE_TEXT.fullmatch(candidate.get("description", ""))+ ):+ raise ValueError("raw evidence contains an unsafe candidate")+ candidates.append(candidate)+ if len({candidate["id"] for candidate in candidates}) != len(candidates):+ raise ValueError("raw evidence contains duplicate candidate IDs")+ executable_region_ids = {+ candidate["id"][len("region:"):]+ for candidate in candidates+ if candidate["id"].startswith("region:")+ }+ if {region["id"] for region in request_regions} != executable_region_ids:+ raise ValueError("chooser request regions do not match executable candidate-linked regions")+ if chooser["selected_id"] not in {candidate["id"] for candidate in candidates}:+ raise ValueError("selected candidate was not in the bounded candidate set")+ selected_candidate_id = chooser["selected_id"]+ if not selected_candidate_id.startswith("region:"):+ raise ValueError("selected candidate does not resolve to an executable region action")+ selected_region = {+ region["id"]: region for region in request_regions+ }.get(selected_candidate_id[len("region:"):])+ if selected_region is None:+ raise ValueError("selected executable candidate has no exact chooser request region")+ resolved_action = raw.get("resolved_action")+ if (+ not isinstance(resolved_action, dict)+ or set(resolved_action) != {"candidate_id", "x", "y"}+ or resolved_action["candidate_id"] != selected_candidate_id+ or any(type(resolved_action[field]) not in (int, float) for field in ("x", "y"))+ ):+ raise ValueError("raw evidence resolved action differs from the selected candidate")+ action_x = resolved_action["x"]+ action_y = resolved_action["y"]+ if (+ not math.isfinite(action_x)+ or not math.isfinite(action_y)+ or not 0 <= action_x < observation["width"]+ or not 0 <= action_y < observation["height"]+ ):+ raise ValueError("raw evidence resolved action coordinates are outside the observation")+ bounds = selected_region["bounds"]+ expected_x = float(bounds["x"]) + float(bounds["width"]) / 2.0+ expected_y = float(bounds["y"]) + float(bounds["height"]) / 2.0+ if (+ not math.isclose(action_x, expected_x, rel_tol=0.0, abs_tol=math.ulp(expected_x))+ or not math.isclose(action_y, expected_y, rel_tol=0.0, abs_tol=math.ulp(expected_y))+ ):+ raise ValueError("raw evidence resolved action does not match the selected region center")+ recording_sha256 = sha256_file(recording)+ raw_recording = raw.get("recording")+ if (+ not isinstance(raw_recording, dict)+ or set(raw_recording) != {"local_path", "sha256", "metadata"}+ or not isinstance(raw_recording["local_path"], str)+ or raw_recording["sha256"] != recording_sha256+ or raw_recording["metadata"] != recording_probe+ ):+ raise ValueError("raw evidence recording differs from the decoded recording")+ capture_trace_sha256 = hashlib.sha256(+ f"{captures['acted']}\0{captures['fresh']}".encode()+ ).hexdigest()+ return {+ "schema": "cua-visual-perception-demo-evidence/v3",+ "platform": platform,+ "raw_evidence_sha256": sha256_file(raw_evidence),+ "fixture": {+ "id": oracle_value["fixture"],+ "oracle": {+ "source": "fixture-journal",+ "initial_ready": True,+ "selected": oracle_value["selected"],+ "action_count": oracle_value["action_count"],+ "result": "passed",+ },+ },+ "runtime": {+ "driver": {+ "source_sha": source_sha,+ "version": measurements["review_driver_version"],+ "binary_sha256": driver_binary_sha256,+ "build": {+ "profile": measurements["review_driver_build_profile"],+ "target": measurements["target"],+ "sealed_artifact_manifest_sha256": measurements["sealed_artifact_manifest_sha256"],+ "sealed_extension_manifest_sha256": measurements["sealed_extension_manifest_sha256"],+ },+ },+ "perception": {+ "extension_id": status["id"],+ "extension_version": status["active_version"],+ "trust": status["trust"],+ "publisher_id": status["publisher_id"],+ "publisher_key_id": status["publisher_key_id"],+ "catalog_version": status["catalog_version"],+ "signature_algorithm": measurements["signature_algorithm"],+ "signed_extension_archive_sha256": measurements["archive_sha256"],+ "signing_key_sha256": measurements["public_key_sha256"],+ "signed_catalog_sha256": measurements["catalog_sha256"],+ "protocol_version": measurements["protocol_version"],+ "worker_sha256": measurements["worker_sha256"],+ "self_test": measurements["self_test"],+ "models": measurements["models"],+ "onnx_runtime": measurements["onnx_runtime"],+ "parser_model_id": parser["parser"]["model_id"],+ },+ "chooser": {+ "mode": chooser_mode,+ "provider": "typesafe" if chooser_mode == "live" else "fixture",+ "model_id": chooser["model"],+ "adapter_source_sha": source_sha,+ "source_sha": jev_source_sha,+ },+ },+ "observation": {+ "session_label": session_label,+ "input_scope": observation["input_scope"],+ "capture_kind": observation["capture_kind"],+ "capture_source": observation["capture_source"],+ "dimensions": {"width": observation["width"], "height": observation["height"]},+ "acted_capture_id_sha256": hashlib.sha256(captures["acted"].encode()).hexdigest(),+ "fresh_capture_id_sha256": hashlib.sha256(captures["fresh"].encode()).hexdigest(),+ "capture_trace_sha256": capture_trace_sha256,+ "candidates": candidates,+ },+ "environment": {+ "os": {"name": os_name, "version": os_version, "arch": os_arch},+ "desktop_session": observation["desktop_session"],+ "runner_identity_class": observation["runner_identity_class"],+ "delivery_mode": observation["delivery_mode"],+ },+ "result": {+ "status": "passed",+ "selected_candidate": chooser["selected_id"],+ "background_desktop_refused": raw["verification"]["background_desktop_refused"],+ "capture_preserved_after_refusal": raw["verification"]["capture_preserved_after_refusal"],+ "stale_capture_refused": True,+ },+ "recording": {+ "original_dimensions": {"width": recording_probe["width"], "height": recording_probe["height"]},+ "delivered_dimensions": {"width": recording_probe["width"], "height": recording_probe["height"]},+ "frame_rate": recording_probe["frame_rate"],+ "cursor": {"agent_overlay": False, "system_cursor": "recorder-default"},+ "edit_operations": [{"operation": "none", "speed": "1x"}],+ "shots": [{"source_sha256": recording_sha256, "start_ms": 0, "end_ms": recording_probe["duration_ms"]}],+ "final_sha256": recording_sha256,+ "size_bytes": video_size,+ },+ "artifacts": [{+ "kind": "video",+ "path": "recording.mp4",+ "sha256": recording_sha256,+ "size_bytes": video_size,+ }],+ }+++def main() -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument("--repo-root", type=Path, required=True)+ parser.add_argument("--expected-source-sha", required=True)+ parser.add_argument("--chooser-mode", choices=("mock", "live"), required=True)+ parser.add_argument("--jev-source-sha", required=True)+ parser.add_argument("--session-label", required=True)+ parser.add_argument("--os-name", required=True)+ parser.add_argument("--os-version", required=True)+ parser.add_argument("--os-arch", required=True)+ parser.add_argument("--candidate-measurements", type=Path, required=True)+ parser.add_argument("--driver-binary", type=Path, required=True)+ parser.add_argument("--extension-status", type=Path, required=True)+ parser.add_argument("--parser-result", type=Path, required=True)+ parser.add_argument("--chooser-result", type=Path, required=True)+ parser.add_argument("--model", type=Path, required=True)+ parser.add_argument("--oracle", type=Path, required=True)+ parser.add_argument("--raw-evidence", type=Path, required=True)+ parser.add_argument("--recording", type=Path, required=True)+ parser.add_argument("--output-dir", type=Path, required=True)+ args = parser.parse_args()+ manifest = build_manifest(+ source_sha=measure_source_sha(args.repo_root, args.expected_source_sha),+ platform=measure_platform(),+ jev_source_sha=args.jev_source_sha,+ session_label=args.session_label,+ os_name=args.os_name,+ os_version=args.os_version,+ os_arch=args.os_arch,+ chooser_mode=args.chooser_mode,+ candidate_measurements=args.candidate_measurements,+ driver_binary=args.driver_binary,+ extension_status=args.extension_status,+ parser_result=args.parser_result,+ chooser_result=args.chooser_result,+ model=args.model,+ oracle=args.oracle,+ raw_evidence=args.raw_evidence,+ recording=args.recording,+ )+ if args.output_dir.exists() and any(args.output_dir.iterdir()):+ raise ValueError("output directory must be empty before evidence publication")+ args.output_dir.mkdir(mode=0o700, parents=True, exist_ok=True)+ shutil.copyfile(args.recording, args.output_dir / "recording.mp4")+ (args.output_dir / "manifest.json").write_text(+ json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8"+ )+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/libs/cua-driver/tests/perception-demo/test_evidence_envelope.py b/libs/cua-driver/tests/perception-demo/test_evidence_envelope.pynew file mode 100644index 0000000000..f8d8b7298b--- /dev/null+++ b/libs/cua-driver/tests/perception-demo/test_evidence_envelope.py@@ -0,0 +1,333 @@+import base64+from contextlib import redirect_stdout+import hashlib+import importlib.util+from io import BytesIO, StringIO+import json+import os+from pathlib import Path+import stat+import tempfile+import unittest+from unittest import mock+import zipfile+++HERE = Path(__file__).parent+SPEC = importlib.util.spec_from_file_location("evidence_envelope", HERE / "evidence_envelope.py")+envelope = importlib.util.module_from_spec(SPEC)+assert SPEC.loader is not None+SPEC.loader.exec_module(envelope)+++class EvidenceEnvelopeTests(unittest.TestCase):+ def setUp(self):+ self.temporary = tempfile.TemporaryDirectory()+ self.root = Path(self.temporary.name)+ self.bundle = self.root / "bundle"+ self.bundle.mkdir()+ recording = b"small deterministic mp4 fixture"+ (self.bundle / "recording.mp4").write_bytes(recording)+ manifest = {+ "schema": envelope.MANIFEST_SCHEMA,+ "artifacts": [{+ "kind": "video",+ "path": "recording.mp4",+ "sha256": hashlib.sha256(recording).hexdigest(),+ "size_bytes": len(recording),+ }],+ }+ (self.bundle / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8")+ self.private_key = bytes(range(1, 33))+ self.public_key = (+ envelope.X25519PrivateKey.from_private_bytes(self.private_key)+ .public_key()+ .public_bytes(+ encoding=envelope.serialization.Encoding.Raw,+ format=envelope.serialization.PublicFormat.Raw,+ )+ )++ def tearDown(self):+ self.temporary.cleanup()++ def write_authenticated_archive(self, archive):+ ephemeral_private = envelope.X25519PrivateKey.from_private_bytes(b"e" * 32)+ ephemeral_public = envelope._public_key_bytes(ephemeral_private.public_key())+ fingerprint = envelope.recipient_fingerprint(self.public_key)+ nonce = b"n" * envelope.NONCE_SIZE+ size = len(archive) + envelope.TAG_SIZE+ header = envelope.HEADER.pack(+ envelope.MAGIC,+ envelope.VERSION,+ envelope.ALGORITHM_X25519_HKDF_SHA256_AES_256_GCM,+ 0,+ fingerprint,+ ephemeral_public,+ nonce,+ size,+ )+ recipient = envelope.X25519PublicKey.from_public_bytes(self.public_key)+ key = envelope._derive_key(ephemeral_private, recipient, fingerprint)+ encrypted = self.root / "crafted.cuae"+ encrypted.write_bytes(header + envelope.AESGCM(key).encrypt(nonce, archive, header))+ return encrypted++ def test_round_trip_has_fixed_envelope_and_archive_contract(self):+ encrypted = self.root / "evidence.cuae"+ restored = self.root / "restored"+ envelope.encrypt_bundle(self.bundle, encrypted, self.public_key)++ self.assertEqual(encrypted.read_bytes()[:8], envelope.MAGIC)+ header = envelope.HEADER.unpack(encrypted.read_bytes()[:envelope.HEADER.size])+ self.assertEqual(header[1], 3)+ self.assertEqual(header[4], hashlib.sha256(self.public_key).digest())+ envelope.decrypt_bundle(encrypted, restored, self.private_key)++ self.assertEqual(sorted(item.name for item in restored.iterdir()), sorted(envelope.MEMBER_NAMES))+ for name in envelope.MEMBER_NAMES:+ self.assertEqual((restored / name).read_bytes(), (self.bundle / name).read_bytes())++ def test_archive_bytes_are_deterministic(self):+ members = envelope._load_bundle(self.bundle)+ self.assertEqual(envelope._build_archive(members), envelope._build_archive(members))++ def test_tampered_ciphertext_is_rejected_without_output(self):+ encrypted = self.root / "evidence.cuae"+ output = self.root / "restored"+ envelope.encrypt_bundle(self.bundle, encrypted, self.public_key)+ value = bytearray(encrypted.read_bytes())+ value[-1] ^= 1+ encrypted.write_bytes(value)++ with self.assertRaisesRegex(ValueError, "authentication failed"):+ envelope.decrypt_bundle(encrypted, output, self.private_key)+ self.assertFalse(output.exists())++ def test_wrong_recipient_is_rejected_before_decryption_without_output(self):+ encrypted = self.root / "evidence.cuae"+ output = self.root / "restored"+ envelope.encrypt_bundle(self.bundle, encrypted, self.public_key)++ with mock.patch.object(envelope.AESGCM, "decrypt") as decrypt:+ with self.assertRaisesRegex(+ ValueError, "private key does not match envelope recipient fingerprint"+ ):+ envelope.decrypt_bundle(encrypted, output, b"x" * 32)+ decrypt.assert_not_called()+ self.assertFalse(output.exists())++ def test_tampered_recipient_fingerprint_is_rejected_without_output(self):+ encrypted = self.root / "evidence.cuae"+ output = self.root / "restored"+ envelope.encrypt_bundle(self.bundle, encrypted, self.public_key)+ value = bytearray(encrypted.read_bytes())+ value[12] ^= 1+ encrypted.write_bytes(value)++ with self.assertRaisesRegex(+ ValueError, "private key does not match envelope recipient fingerprint"+ ):+ envelope.decrypt_bundle(encrypted, output, self.private_key)+ self.assertFalse(output.exists())++ def test_refuses_extra_input_file_and_existing_outputs(self):+ (self.bundle / "raw-manifest.json").write_text("private", encoding="utf-8")+ with self.assertRaisesRegex(ValueError, "exactly"):+ envelope.encrypt_bundle(self.bundle, self.root / "evidence.cuae", self.public_key)+ (self.bundle / "raw-manifest.json").unlink()++ encrypted = self.root / "evidence.cuae"+ encrypted.write_bytes(b"keep")+ with self.assertRaisesRegex(ValueError, "already exists"):+ envelope.encrypt_bundle(self.bundle, encrypted, self.public_key)+ self.assertEqual(encrypted.read_bytes(), b"keep")++ encrypted.unlink()+ envelope.encrypt_bundle(self.bundle, encrypted, self.public_key)+ restored = self.root / "restored"+ restored.mkdir()+ marker = restored / "keep.txt"+ marker.write_text("keep", encoding="utf-8")+ with self.assertRaisesRegex(ValueError, "already exists"):+ envelope.decrypt_bundle(encrypted, restored, self.private_key)+ self.assertEqual(marker.read_text(encoding="utf-8"), "keep")++ def test_encrypt_refuses_file_created_during_finalization(self):+ encrypted = self.root / "evidence.cuae"+ real_link = os.link++ def create_competing_file(source, destination):+ Path(destination).write_bytes(b"racer")+ return real_link(source, destination)++ with mock.patch.object(envelope.os, "link", side_effect=create_competing_file):+ with self.assertRaisesRegex(ValueError, "already exists"):+ envelope.encrypt_bundle(self.bundle, encrypted, self.public_key)++ self.assertEqual(encrypted.read_bytes(), b"racer")+ self.assertEqual(list(self.root.glob(f".{encrypted.name}.*")), [])++ def test_decrypt_refuses_directory_created_during_finalization(self):+ encrypted = self.root / "evidence.cuae"+ restored = self.root / "restored"+ envelope.encrypt_bundle(self.bundle, encrypted, self.public_key)+ real_rename = envelope._rename_directory_no_replace+ competing_identity = []++ def create_competing_directory(source, destination):+ destination = Path(destination)+ destination.mkdir()+ status = destination.stat()+ competing_identity.append((status.st_dev, status.st_ino))+ return real_rename(source, destination)++ with mock.patch.object(+ envelope,+ "_rename_directory_no_replace",+ side_effect=create_competing_directory,+ ):+ with self.assertRaisesRegex(ValueError, "already exists"):+ envelope.decrypt_bundle(encrypted, restored, self.private_key)++ status = restored.stat()+ self.assertEqual((status.st_dev, status.st_ino), competing_identity[0])+ self.assertEqual(list(restored.iterdir()), [])+ self.assertEqual(list(self.root.glob(f".{restored.name}.*")), [])++ def test_refuses_symlink_member(self):+ (self.bundle / "recording.mp4").unlink()+ target = self.root / "outside.mp4"+ target.write_bytes(b"outside")+ try:+ (self.bundle / "recording.mp4").symlink_to(target)+ except (NotImplementedError, OSError):+ self.skipTest("symlinks are unavailable on this host")+ with self.assertRaisesRegex(ValueError, "regular file"):+ envelope.encrypt_bundle(self.bundle, self.root / "evidence.cuae", self.public_key)++ def test_refuses_manifest_mismatch_and_invalid_x25519_key_length(self):+ manifest_path = self.bundle / "manifest.json"+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))+ manifest["artifacts"][0]["sha256"] = "0" * 64+ manifest_path.write_text(json.dumps(manifest), encoding="utf-8")+ with self.assertRaisesRegex(ValueError, "does not bind"):+ envelope.encrypt_bundle(self.bundle, self.root / "evidence.cuae", self.public_key)++ with self.assertRaisesRegex(ValueError, "exactly 32 bytes"):+ envelope.encrypt_bundle(self.bundle, self.root / "evidence.cuae", b"short")++ def test_loads_only_canonical_32_byte_base64_from_env_or_file(self):+ encoded = base64.b64encode(self.public_key).decode("ascii")+ with mock.patch.dict(os.environ, {"CUA_EVIDENCE_RECIPIENT": encoded}, clear=True):+ self.assertEqual(+ envelope.load_key(+ environment_name="CUA_EVIDENCE_RECIPIENT",+ key_file=None,+ label="recipient public key",+ ),+ self.public_key,+ )++ key_file = self.root / "key.txt"+ key_file.write_text(encoded + "\n", encoding="ascii")+ self.assertEqual(+ envelope.load_key(+ environment_name=None,+ key_file=key_file,+ label="recipient private key",+ ),+ self.public_key,+ )+ for invalid in ("not-base64", base64.b64encode(b"short").decode("ascii"), encoded.rstrip("=")):+ with self.assertRaisesRegex(ValueError, "base64"):+ envelope._decode_key(invalid, "recipient public key")++ def test_each_envelope_uses_a_distinct_ephemeral_x25519_key(self):+ first = self.root / "first.cuae"+ second = self.root / "second.cuae"+ envelope.encrypt_bundle(self.bundle, first, self.public_key)+ envelope.encrypt_bundle(self.bundle, second, self.public_key)++ first_header = envelope.HEADER.unpack(first.read_bytes()[:envelope.HEADER.size])+ second_header = envelope.HEADER.unpack(second.read_bytes()[:envelope.HEADER.size])+ self.assertEqual(first_header[4], envelope.recipient_fingerprint(self.public_key))+ self.assertEqual(second_header[4], envelope.recipient_fingerprint(self.public_key))+ self.assertNotEqual(first_header[5], second_header[5])++ def test_recipient_fingerprint_is_bound_into_hkdf(self):+ ephemeral_private = envelope.X25519PrivateKey.from_private_bytes(b"e" * 32)+ recipient = envelope.X25519PublicKey.from_public_bytes(self.public_key)+ fingerprint = envelope.recipient_fingerprint(self.public_key)++ expected = envelope._derive_key(ephemeral_private, recipient, fingerprint)+ different = envelope._derive_key(ephemeral_private, recipient, b"x" * 32)++ self.assertNotEqual(expected, different)++ def test_tampered_authenticated_header_is_rejected(self):+ encrypted = self.root / "evidence.cuae"+ output = self.root / "restored"+ envelope.encrypt_bundle(self.bundle, encrypted, self.public_key)+ value = bytearray(encrypted.read_bytes())+ value[envelope.HEADER.size - 9] ^= 1+ encrypted.write_bytes(value)++ with self.assertRaisesRegex(ValueError, "authentication failed"):+ envelope.decrypt_bundle(encrypted, output, self.private_key)+ self.assertFalse(output.exists())++ def test_cli_logs_only_the_safe_recipient_fingerprint(self):+ encoded = base64.b64encode(self.public_key).decode("ascii")+ encrypted = self.root / "evidence.cuae"+ stdout = StringIO()+ with mock.patch.dict(os.environ, {"RECIPIENT": encoded}, clear=True), mock.patch(+ "sys.argv",+ [+ "evidence_envelope.py",+ "encrypt",+ "--input",+ str(self.bundle),+ "--output",+ str(encrypted),+ "--recipient-env",+ "RECIPIENT",+ ],+ ), redirect_stdout(stdout):+ self.assertEqual(envelope.main(), 0)++ self.assertEqual(+ stdout.getvalue().strip(),+ f"recipient_public_key_sha256={hashlib.sha256(self.public_key).hexdigest()}",+ )+ self.assertNotIn(encoded, stdout.getvalue())++ def test_refuses_trailing_archive_data_even_when_authenticated(self):+ members = envelope._load_bundle(self.bundle)+ noncanonical = envelope._build_archive(members) + b"trailing"+ encrypted = self.write_authenticated_archive(noncanonical)++ with self.assertRaisesRegex(ValueError, "canonical format"):+ envelope.decrypt_bundle(encrypted, self.root / "restored", self.private_key)++ def test_refuses_noncanonical_member_order_even_when_authenticated(self):+ members = envelope._load_bundle(self.bundle)+ output = BytesIO()+ with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_STORED, allowZip64=False) as archive:+ for name in reversed(envelope.MEMBER_NAMES):+ info = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0))+ info.compress_type = zipfile.ZIP_STORED+ info.create_system = 3+ info.create_version = 20+ info.extract_version = 20+ info.flag_bits = 0+ info.external_attr = (stat.S_IFREG | 0o600) << 16+ archive.writestr(info, members[name])+ encrypted = self.write_authenticated_archive(output.getvalue())++ with self.assertRaisesRegex(ValueError, "must contain exactly"):+ envelope.decrypt_bundle(encrypted, self.root / "restored", self.private_key)+++if __name__ == "__main__":+ unittest.main()diff --git a/libs/cua-driver/tests/perception-demo/test_sanitize_derived_reel.py b/libs/cua-driver/tests/perception-demo/test_sanitize_derived_reel.pynew file mode 100644index 0000000000..d52326f608--- /dev/null+++ b/libs/cua-driver/tests/perception-demo/test_sanitize_derived_reel.py@@ -0,0 +1,146 @@+import importlib.util+import json+from pathlib import Path+import tempfile+import unittest+from unittest import mock+++HERE = Path(__file__).parent+SPEC = importlib.util.spec_from_file_location("sanitize_derived_reel", HERE / "sanitize_derived_reel.py")+reel = importlib.util.module_from_spec(SPEC)+assert SPEC.loader is not None+SPEC.loader.exec_module(reel)+++class DerivedReelEvidenceTests(unittest.TestCase):+ def setUp(self):+ self.temporary = tempfile.TemporaryDirectory()+ self.root = Path(self.temporary.name)+ self.reel_path = self.root / "derived.mp4"+ self.reel_path.write_bytes(b"derived-reel")+ self.video_probes = mock.patch.object(+ reel,+ "probe_video",+ side_effect=lambda path, decode: {+ "duration_ms": 2000 if decode else 5000,+ "frame_duration_ms": 1000 / 30,+ },+ )+ self.probe = self.video_probes.start()++ def tearDown(self):+ self.video_probes.stop()+ self.temporary.cleanup()++ def source(self, source_id="macos", platform="macos", source_sha="a" * 40):+ directory = self.root / source_id+ directory.mkdir()+ recording = directory / "recording.mp4"+ recording.write_bytes((source_id + "-recording").encode())+ digest = reel.sha256_file(recording)+ manifest = {+ "schema": "cua-visual-perception-demo-evidence/v3",+ "platform": platform,+ "fixture": {"id": "visual-only-canvas/v1"},+ "runtime": {+ "driver": {"source_sha": source_sha},+ "perception": {"trust": "review-only-publisher-verified", "signature_algorithm": "ed25519"},+ "chooser": {"mode": "live", "provider": "typesafe", "model_id": "jev-model", "source_sha": "b" * 40},+ },+ "result": {"status": "passed", "stale_capture_refused": True},+ "recording": {"final_sha256": digest, "size_bytes": recording.stat().st_size},+ "artifacts": [{"kind": "video", "path": "recording.mp4", "sha256": digest, "size_bytes": recording.stat().st_size}],+ }+ manifest_path = directory / "manifest.json"+ manifest_path.write_text(json.dumps(manifest))+ return {"id": source_id, "evidence_manifest": f"{source_id}/manifest.json", "recording": f"{source_id}/recording.mp4"}++ def plan(self):+ source = self.source()+ plan = self.root / "edit-plan.json"+ plan.write_text(json.dumps({+ "schema": "cua-derived-reel-edit-plan/v1",+ "sources": [source],+ "shots": [+ {"source_id": "macos", "start_ms": 500, "end_ms": 1500},+ {"source_id": "macos", "start_ms": 3000, "end_ms": 4000},+ ],+ "wait_cuts": [{+ "source_id": "macos", "start_ms": 1500, "end_ms": 3000,+ "disclosure": reel.WAIT_DISCLOSURE,+ }],+ }))+ return plan++ def test_manifest_binds_sources_ranges_edits_and_full_decode(self):+ manifest = reel.build_manifest(source_root=self.root, edit_plan=self.plan(), reel=self.reel_path)+ reel.validate_manifest_schema(manifest)+ self.assertEqual(manifest["schema"], "cua-visual-perception-derived-reel/v1")+ self.assertEqual(manifest["identity"]["source_sha"], "a" * 40)+ self.assertEqual(manifest["identity"]["jev_source_sha"], "b" * 40)+ source = manifest["sources"][0]+ self.assertEqual(source["used_ranges"], [+ {"start_ms": 500, "end_ms": 1500},+ {"start_ms": 3000, "end_ms": 4000},+ ])+ self.assertEqual(source["removed_wait_ranges"], [{+ "start_ms": 1500, "end_ms": 3000, "disclosure": reel.WAIT_DISCLOSURE,+ }])+ self.assertEqual([item["operation"] for item in manifest["edit_operations"]], ["trim", "trim", "concatenate"])+ self.assertEqual(manifest["recording"]["expected_duration_ms"], 2000)+ self.assertTrue(manifest["recording"]["fully_decoded"])+ self.assertEqual(manifest["artifacts"][0]["sha256"], reel.sha256_file(self.reel_path))+ self.assertNotIn(str(self.root), json.dumps(manifest))+ self.assertEqual(self.probe.call_args_list[-1].kwargs, {"decode": True})++ def test_rejects_undisclosed_or_misrepresented_wait_cut(self):+ plan_path = self.plan()+ value = json.loads(plan_path.read_text())+ value["wait_cuts"] = []+ plan_path.write_text(json.dumps(value))+ with self.assertRaisesRegex(ValueError, "every and only"):+ reel.build_manifest(source_root=self.root, edit_plan=plan_path, reel=self.reel_path)++ value["wait_cuts"] = [{+ "source_id": "macos", "start_ms": 1500, "end_ms": 3000,+ "disclosure": "probably idle",+ }]+ plan_path.write_text(json.dumps(value))+ with self.assertRaisesRegex(ValueError, "exact no-action-omitted"):+ reel.build_manifest(source_root=self.root, edit_plan=plan_path, reel=self.reel_path)++ def test_rejects_source_hash_or_identity_mismatch(self):+ plan_path = self.plan()+ (self.root / "macos" / "recording.mp4").write_bytes(b"changed")+ with self.assertRaisesRegex(ValueError, "differ from the source evidence"):+ reel.build_manifest(source_root=self.root, edit_plan=plan_path, reel=self.reel_path)++ def test_rejects_reel_duration_that_does_not_match_edits(self):+ plan_path = self.plan()+ self.video_probes.stop()+ with mock.patch.object(reel, "probe_video", side_effect=lambda path, decode: {+ "duration_ms": 2600 if decode else 5000, "frame_duration_ms": 1000 / 30,+ }):+ with self.assertRaisesRegex(ValueError, "duration does not match"):+ reel.build_manifest(source_root=self.root, edit_plan=plan_path, reel=self.reel_path)+ self.probe = self.video_probes.start()++ def test_rejects_path_escape_and_too_few_real_edits(self):+ plan_path = self.plan()+ value = json.loads(plan_path.read_text())+ value["sources"][0]["recording"] = "../private.mp4"+ plan_path.write_text(json.dumps(value))+ with self.assertRaisesRegex(ValueError, "safe relative"):+ reel.build_manifest(source_root=self.root, edit_plan=plan_path, reel=self.reel_path)++ value["sources"][0]["recording"] = "macos/recording.mp4"+ value["shots"] = value["shots"][:1]+ value["wait_cuts"] = []+ plan_path.write_text(json.dumps(value))+ with self.assertRaisesRegex(ValueError, "at least two"):+ reel.build_manifest(source_root=self.root, edit_plan=plan_path, reel=self.reel_path)+++if __name__ == "__main__":+ unittest.main()diff --git a/libs/cua-driver/tests/perception-demo/test_sanitize_evidence.py b/libs/cua-driver/tests/perception-demo/test_sanitize_evidence.pynew file mode 100644index 0000000000..dd9918b92a--- /dev/null+++ b/libs/cua-driver/tests/perception-demo/test_sanitize_evidence.py@@ -0,0 +1,602 @@+import importlib.util+import base64+import json+from pathlib import Path+import subprocess+import tempfile+import unittest+from unittest import mock+++HERE = Path(__file__).parent+SPEC = importlib.util.spec_from_file_location("sanitize_evidence", HERE / "sanitize_evidence.py")+sanitizer = importlib.util.module_from_spec(SPEC)+assert SPEC.loader is not None+SPEC.loader.exec_module(sanitizer)+++class EvidenceSanitizerTests(unittest.TestCase):+ def setUp(self):+ self.temporary = tempfile.TemporaryDirectory()+ self.root = Path(self.temporary.name)+ self.probe = mock.patch.object(sanitizer, "probe_recording", return_value={+ "width": 1920, "height": 1080,+ "frame_rate": {"numerator": 30, "denominator": 1},+ "duration_ms": 1250,+ })+ self.probe.start()++ def tearDown(self):+ self.probe.stop()+ self.temporary.cleanup()++ def inputs(self):+ extension_status = self.root / "extension-status.json"+ parser_result = self.root / "parser-result.json"+ chooser_result = self.root / "chooser-result.json"+ candidate_measurements = self.root / "candidate-measurements.json"+ driver_binary = self.root / "cua-driver"+ model = self.root / "model.bin"+ oracle = self.root / "oracle.json"+ raw_evidence = self.root / "raw-manifest.json"+ recording = self.root / "recording.mp4"+ extension_status.write_text(json.dumps({+ "id": "cua-perception",+ "display_name": "Cua Perception",+ "description": "fixture",+ "protocol_version": 1,+ "installed": True,+ "active_version": "0.1.0",+ "healthy": True,+ "trust": "review-only-publisher-verified",+ "publisher_id": "cua-review-only",+ "publisher_key_id": "review-only-build-override",+ "catalog_version": 7,+ "detail": "healthy",+ }))+ parser_result.write_text(json.dumps({+ "schema": "cua.visual_regions_v1",+ "parser": {"model_id": "cua-perception/demo-v1"},+ "regions": [{"private": "raw-only"}],+ }))+ chooser_result.write_text(json.dumps({+ "schema": "cua.jev_choice_v1",+ "selected_id": "region:send",+ "model": "mock",+ "confidence": 1.0,+ "probabilities": {"region:send": 1.0, "reobserve": 0.0, "abstain": 0.0},+ }))+ model.write_bytes(b"measured-model-bytes")+ driver_binary.write_bytes(b"measured-driver-bytes")+ public_key = bytes(range(32))+ candidate_measurements.write_text(json.dumps({+ "review_only": True,+ "source_sha": "a" * 40,+ "target": "x86_64-unknown-linux-gnu",+ "supplied_model_asset_id": 1234,+ "supplied_model_sha256": sanitizer.sha256_file(model),+ "supplied_model_size": model.stat().st_size,+ "public_key_base64": base64.b64encode(public_key).decode(),+ "public_key_sha256": sanitizer.hashlib.sha256(public_key).hexdigest(),+ "key_id": "review-only-build-override",+ "publisher_id": "cua-review-only",+ "signature_algorithm": "ed25519",+ "catalog_sha256": "d" * 64,+ "archive_sha256": "b" * 64,+ "review_driver_relative_path": "review-cua-driver",+ "review_driver_build_profile": "debug-review-trust-root",+ "review_driver_sha256": sanitizer.sha256_file(driver_binary),+ "code_signing": {+ "status": "not-applicable",+ "format": "none",+ "identity": "none",+ "certificate_sha256": None,+ "designated_requirement": None,+ },+ "review_driver_version": "0.28.2",+ "extension_version": "0.1.0",+ "protocol_version": 1,+ "worker_sha256": "1" * 64,+ "models": [+ {"role": "icon-detect", "id": "omniparser.onnx", "revision": "a" * 40,+ "original_sha256": "2" * 64, "converted_sha256": sanitizer.sha256_file(model), "license": "AGPL-3.0-only"},+ {"role": "ocr-detect", "id": "ppocr-det.onnx", "revision": "b" * 40,+ "original_sha256": "3" * 64, "converted_sha256": "3" * 64, "license": "Apache-2.0"},+ {"role": "ocr-recognize", "id": "ppocr-rec.onnx", "revision": "c" * 40,+ "original_sha256": "4" * 64, "converted_sha256": "4" * 64, "license": "Apache-2.0"},+ ],+ "onnx_runtime": {"revision": "1.26.0", "sha256": "5" * 64, "license": "MIT"},+ "self_test": {"status": "passed", "mismatch_rejection": True, "evidence_sha256": "6" * 64},+ "sealed_artifact_manifest_sha256": "7" * 64,+ "sealed_extension_manifest_sha256": "8" * 64,+ }))+ oracle.write_text(json.dumps({+ "fixture": "visual-only-canvas/v1",+ "ready": True,+ "selected": "send",+ "action_count": 1,+ }))+ recording.write_bytes(b"measured-video-bytes")+ send_region = {+ "id": "send", "kind": "text",+ "bounds": {"x": 354, "y": 250, "width": 80, "height": 40},+ "text": "Send", "confidence": 0.99, "interactive": True,+ }+ archive_region = {+ "id": "archive", "kind": "icon",+ "bounds": {"x": 20, "y": 20, "width": 24, "height": 24},+ "label": "Archive", "confidence": 0.95, "interactive": False,+ }+ raw_evidence.write_text(json.dumps({+ "schema": "cua-visual-perception-demo-raw/v2",+ "source_sha": "a" * 40,+ "jev_source_sha": "e" * 40,+ "platform": "linux-x11",+ "capture_ids": {"acted": "private-capture", "fresh": "fresh-capture"},+ "observation": {"input_scope": "window", "capture_kind": "get_window_state",+ "capture_source": "driver-screenshot", "width": 760, "height": 460,+ "desktop_session": "x11-openbox", "runner_identity_class": "github-hosted",+ "delivery_mode": "background"},+ "chooser": {"request": {"regions": [send_region], "candidates": [+ {"id": "region:send", "description": "Activate Send."},+ {"id": "reobserve", "description": "Capture again."},+ {"id": "abstain", "description": "Stop safely."},+ ]}, "mode": "mock", "response": {+ "schema": "cua.jev_choice_v1",+ "selected_id": "region:send",+ "model": "mock",+ "confidence": 1.0,+ "probabilities": {"region:send": 1.0, "reobserve": 0.0, "abstain": 0.0},+ }},+ "fixture_oracle": {+ "fixture": "visual-only-canvas/v1", "ready": True,+ "selected": "send", "action_count": 1,+ },+ "extension_status": json.loads(extension_status.read_text()),+ "parser": {"model_id": "cua-perception/demo-v1"},+ "host_validated_regions": [send_region, archive_region],+ "resolved_action": {"candidate_id": "region:send", "x": 394.0, "y": 270.0},+ "verification": {+ "oracle": "passed",+ "background_desktop_refused": None,+ "capture_preserved_after_refusal": None,+ "stale_capture_refused": True,+ },+ "timeline": {"duration_ms": 1250, "events": [+ "observed", "parsed", "chosen", "background_refusal_not_applicable",+ "clicked", "oracle_verified",+ "stale_capture_refused", "reobserved",+ ]},+ "recording": {"local_path": "/private/recording.mp4",+ "sha256": sanitizer.sha256_file(recording),+ "metadata": {"width": 1920, "height": 1080,+ "frame_rate": {"numerator": 30, "denominator": 1},+ "duration_ms": 1250}},+ }))+ return {+ "source_sha": "a" * 40,+ "platform": "linux-x11",+ "jev_source_sha": "e" * 40,+ "session_label": "authorized-jev-choice-demo",+ "os_name": "ubuntu22",+ "os_version": "20260915.1",+ "os_arch": "X64",+ "chooser_mode": "mock",+ "candidate_measurements": candidate_measurements,+ "driver_binary": driver_binary,+ "extension_status": extension_status,+ "parser_result": parser_result,+ "chooser_result": chooser_result,+ "model": model,+ "oracle": oracle,+ "raw_evidence": raw_evidence,+ "recording": recording,+ }++ def test_manifest_is_bound_to_driver_status_and_raw_evidence(self):+ inputs = self.inputs()+ manifest = sanitizer.build_manifest(**inputs)+ perception = manifest["runtime"]["perception"]+ self.assertEqual(manifest["schema"], "cua-visual-perception-demo-evidence/v3")+ self.assertEqual(manifest["raw_evidence_sha256"], sanitizer.sha256_file(inputs["raw_evidence"]))+ self.assertEqual(perception["trust"], "review-only-publisher-verified")+ self.assertEqual(perception["signature_algorithm"], "ed25519")+ self.assertEqual(perception["publisher_key_id"], "review-only-build-override")+ self.assertEqual(perception["catalog_version"], 7)+ self.assertEqual(perception["signed_extension_archive_sha256"], "b" * 64)+ public_key = bytes(range(32))+ self.assertEqual(perception["signing_key_sha256"], sanitizer.hashlib.sha256(public_key).hexdigest())+ self.assertEqual(perception["signed_catalog_sha256"], "d" * 64)+ self.assertEqual(manifest["runtime"]["driver"]["source_sha"], "a" * 40)+ self.assertEqual(manifest["runtime"]["driver"]["version"], "0.28.2")+ self.assertEqual(manifest["runtime"]["driver"]["binary_sha256"],+ sanitizer.sha256_file(inputs["driver_binary"]))+ self.assertEqual(manifest["runtime"]["driver"]["build"], {+ "profile": "debug-review-trust-root", "target": "x86_64-unknown-linux-gnu",+ "sealed_artifact_manifest_sha256": "7" * 64,+ "sealed_extension_manifest_sha256": "8" * 64,+ })+ self.assertEqual(manifest["runtime"]["perception"]["models"][0]["role"], "icon-detect")+ self.assertEqual(manifest["runtime"]["perception"]["onnx_runtime"]["revision"], "1.26.0")+ self.assertEqual(manifest["runtime"]["perception"]["self_test"]["status"], "passed")+ self.assertEqual({+ "source_sha": "a" * 40,+ "binary_sha256": sanitizer.sha256_file(inputs["driver_binary"]),+ }, {key: manifest["runtime"]["driver"][key] for key in ("source_sha", "binary_sha256")})+ self.assertEqual(manifest["runtime"]["chooser"]["provider"], "fixture")+ self.assertEqual(manifest["runtime"]["chooser"]["model_id"], "mock")+ self.assertEqual(manifest["runtime"]["chooser"]["adapter_source_sha"], "a" * 40)+ self.assertEqual(manifest["runtime"]["chooser"]["source_sha"], "e" * 40)+ self.assertEqual(manifest["observation"]["input_scope"], "window")+ self.assertEqual(manifest["observation"]["dimensions"], {"width": 760, "height": 460})+ self.assertEqual(len(manifest["observation"]["candidates"]), 3)+ self.assertEqual(manifest["environment"]["os"], {"name": "ubuntu22", "version": "20260915.1", "arch": "X64"})+ self.assertEqual(manifest["recording"]["original_dimensions"], {"width": 1920, "height": 1080})+ self.assertEqual(manifest["recording"]["frame_rate"], {"numerator": 30, "denominator": 1})+ self.assertEqual(manifest["result"]["selected_candidate"], "region:send")+ self.assertIsNone(manifest["result"]["background_desktop_refused"])+ self.assertIsNone(manifest["result"]["capture_preserved_after_refusal"])+ self.assertNotIn("capture_ids", json.dumps(manifest))+ self.assertNotIn("coordinates", json.dumps(manifest))+ self.assertNotIn("host_validated_regions", json.dumps(manifest))++ def test_rejects_unsafe_or_out_of_bounds_host_validated_regions(self):+ invalid_regions = [+ [{+ "id": "send", "kind": "text",+ "bounds": {"x": 740, "y": 250, "width": 80, "height": 40},+ "text": "Send", "confidence": 0.99, "interactive": True,+ }],+ [{+ "id": "send", "kind": "text",+ "bounds": {"x": 354, "y": 250, "width": 80, "height": 40},+ "text": "Send\nsecret", "confidence": 0.99, "interactive": True,+ }],+ [{+ "id": "send", "kind": "text",+ "bounds": {"x": 354, "y": 250, "width": 80, "height": 40},+ "text": "Send", "confidence": float("inf"), "interactive": True,+ }],+ [{+ "id": "send", "kind": "text",+ "bounds": {"x": 354, "y": 250, "width": 80, "height": 40},+ "text": "Send", "confidence": 0.99, "interactive": 1,+ }],+ ]+ for regions in invalid_regions:+ with self.subTest(regions=regions):+ inputs = self.inputs()+ raw = json.loads(inputs["raw_evidence"].read_text())+ raw["host_validated_regions"] = regions+ inputs["raw_evidence"].write_text(json.dumps(raw))+ with self.assertRaisesRegex(ValueError, "host_validated_regions"):+ sanitizer.build_manifest(**inputs)++ def test_rejects_chooser_regions_outside_host_validated_subset(self):+ inputs = self.inputs()+ raw = json.loads(inputs["raw_evidence"].read_text())+ raw["chooser"]["request"]["regions"][0]["confidence"] = 0.98+ inputs["raw_evidence"].write_text(json.dumps(raw))+ with self.assertRaisesRegex(ValueError, "not a subset"):+ sanitizer.build_manifest(**inputs)++ def test_rejects_chooser_region_ids_that_do_not_match_executable_candidates(self):+ inputs = self.inputs()+ raw = json.loads(inputs["raw_evidence"].read_text())+ raw["chooser"]["request"]["regions"] = [raw["host_validated_regions"][1]]+ inputs["raw_evidence"].write_text(json.dumps(raw))+ with self.assertRaisesRegex(ValueError, "executable candidate-linked regions"):+ sanitizer.build_manifest(**inputs)++ inputs = self.inputs()+ raw = json.loads(inputs["raw_evidence"].read_text())+ raw["chooser"]["request"]["candidates"].insert(1, {+ "id": "region:missing", "description": "Activate missing region.",+ })+ inputs["raw_evidence"].write_text(json.dumps(raw))+ with self.assertRaisesRegex(ValueError, "executable candidate-linked regions"):+ sanitizer.build_manifest(**inputs)++ def test_rejects_fallback_selection_as_a_resolved_action(self):+ for selected_id in ("reobserve", "abstain"):+ with self.subTest(selected_id=selected_id):+ inputs = self.inputs()+ choice = json.loads(inputs["chooser_result"].read_text())+ choice["selected_id"] = selected_id+ inputs["chooser_result"].write_text(json.dumps(choice))+ raw = json.loads(inputs["raw_evidence"].read_text())+ raw["chooser"]["response"] = choice+ raw["resolved_action"]["candidate_id"] = selected_id+ inputs["raw_evidence"].write_text(json.dumps(raw))+ with self.assertRaisesRegex(ValueError, "executable region action"):+ sanitizer.build_manifest(**inputs)++ def test_rejects_invalid_or_unbound_resolved_action_coordinates(self):+ invalid_coordinates = [+ (float("nan"), 270.0, "outside the observation"),+ (float("inf"), 270.0, "outside the observation"),+ (-1.0, 270.0, "outside the observation"),+ (760.0, 270.0, "outside the observation"),+ (394.0, 460.0, "outside the observation"),+ (395.0, 270.0, "selected region center"),+ (32.0, 32.0, "selected region center"),+ ]+ for x, y, error in invalid_coordinates:+ with self.subTest(x=x, y=y):+ inputs = self.inputs()+ raw = json.loads(inputs["raw_evidence"].read_text())+ raw["resolved_action"].update({"x": x, "y": y})+ inputs["raw_evidence"].write_text(json.dumps(raw))+ with self.assertRaisesRegex(ValueError, error):+ sanitizer.build_manifest(**inputs)++ def test_primary_desktop_observation_is_a_closed_foreground_route(self):+ inputs = self.inputs()+ raw = json.loads(inputs["raw_evidence"].read_text())+ raw["observation"].update({+ "input_scope": "desktop",+ "capture_kind": "get_desktop_state",+ "delivery_mode": "foreground",+ })+ raw["verification"].update({+ "background_desktop_refused": True,+ "capture_preserved_after_refusal": True,+ })+ raw["timeline"]["events"][3] = "background_desktop_refused"+ inputs["raw_evidence"].write_text(json.dumps(raw))+ manifest = sanitizer.build_manifest(**inputs)+ self.assertEqual(manifest["observation"]["input_scope"], "desktop")+ self.assertEqual(manifest["observation"]["capture_kind"], "get_desktop_state")+ self.assertEqual(manifest["environment"]["delivery_mode"], "foreground")+ self.assertTrue(manifest["result"]["background_desktop_refused"])+ self.assertTrue(manifest["result"]["capture_preserved_after_refusal"])++ raw["observation"]["delivery_mode"] = "background"+ inputs["raw_evidence"].write_text(json.dumps(raw))+ with self.assertRaisesRegex(ValueError, "observation context"):+ sanitizer.build_manifest(**inputs)++ def test_rejects_unverified_or_unhealthy_installed_state(self):+ inputs = self.inputs()+ status = json.loads(inputs["extension_status"].read_text())+ status["trust"] = "developer-unsigned-local"+ inputs["extension_status"].write_text(json.dumps(status))+ with self.assertRaisesRegex(ValueError, "review-only publisher-verified"):+ sanitizer.build_manifest(**inputs)++ inputs = self.inputs()+ status = json.loads(inputs["extension_status"].read_text())+ status["healthy"] = False+ inputs["extension_status"].write_text(json.dumps(status))+ with self.assertRaisesRegex(ValueError, "review-only publisher-verified"):+ sanitizer.build_manifest(**inputs)++ def test_rejects_malformed_chooser_result(self):+ inputs = self.inputs()+ choice = json.loads(inputs["chooser_result"].read_text())+ choice["tool_arguments"] = {"x": 394, "y": 270}+ inputs["chooser_result"].write_text(json.dumps(choice))+ with self.assertRaisesRegex(ValueError, "cua.jev_choice_v1"):+ sanitizer.build_manifest(**inputs)++ inputs = self.inputs()+ choice = json.loads(inputs["chooser_result"].read_text())+ choice["probabilities"] = {"region:send": 0.4}+ inputs["chooser_result"].write_text(json.dumps(choice))+ raw = json.loads(inputs["raw_evidence"].read_text())+ raw["chooser"]["response"] = choice+ inputs["raw_evidence"].write_text(json.dumps(raw))+ manifest = sanitizer.build_manifest(**inputs)+ self.assertEqual(manifest["result"]["selected_candidate"], "region:send")++ inputs = self.inputs()+ choice = json.loads(inputs["chooser_result"].read_text())+ choice["probabilities"] = {"region:send": 1.1}+ inputs["chooser_result"].write_text(json.dumps(choice))+ with self.assertRaisesRegex(ValueError, "invalid probability"):+ sanitizer.build_manifest(**inputs)++ def test_live_provider_model_identity_is_preserved(self):+ inputs = self.inputs()+ choice = json.loads(inputs["chooser_result"].read_text())+ choice["model"] = "provider-returned-model"+ inputs["chooser_result"].write_text(json.dumps(choice))+ inputs["chooser_mode"] = "live"+ raw = json.loads(inputs["raw_evidence"].read_text())+ raw["chooser"]["mode"] = "live"+ raw["chooser"]["response"] = choice+ inputs["raw_evidence"].write_text(json.dumps(raw))+ manifest = sanitizer.build_manifest(**inputs)+ self.assertEqual(manifest["runtime"]["chooser"], {+ "mode": "live",+ "provider": "typesafe",+ "model_id": "provider-returned-model",+ "adapter_source_sha": "a" * 40,+ "source_sha": "e" * 40,+ })++ def test_live_provider_must_return_model_identity(self):+ inputs = self.inputs()+ choice = json.loads(inputs["chooser_result"].read_text())+ choice["model"] = None+ inputs["chooser_result"].write_text(json.dumps(choice))+ inputs["chooser_mode"] = "live"+ with self.assertRaisesRegex(ValueError, "return its model identity"):+ sanitizer.build_manifest(**inputs)++ def test_rejects_incomplete_sealed_model_measurements(self):+ inputs = self.inputs()+ measurements = json.loads(inputs["candidate_measurements"].read_text())+ measurements["models"].pop()+ inputs["candidate_measurements"].write_text(json.dumps(measurements))+ with self.assertRaisesRegex(ValueError, "all three ordered model identities"):+ sanitizer.build_manifest(**inputs)++ def test_requires_truthful_platform_code_signing_measurement(self):+ inputs = self.inputs()+ measurements = json.loads(inputs["candidate_measurements"].read_text())+ measurements["code_signing"]["status"] = "verified"+ inputs["candidate_measurements"].write_text(json.dumps(measurements))+ with self.assertRaisesRegex(ValueError, "misleading code-signing evidence"):+ sanitizer.build_manifest(**inputs)++ inputs = self.inputs()+ measurements = json.loads(inputs["candidate_measurements"].read_text())+ measurements["target"] = "aarch64-apple-darwin"+ measurements["code_signing"] = {+ "status": "verified",+ "format": "apple-codesign",+ "identity": "ephemeral-self-signed-review-only",+ "certificate_sha256": "9" * 64,+ "designated_requirement": 'identifier "cua-driver" and certificate leaf = H"00"',+ }+ inputs["candidate_measurements"].write_text(json.dumps(measurements))+ inputs["platform"] = "macos"+ raw = json.loads(inputs["raw_evidence"].read_text())+ raw["platform"] = "macos"+ inputs["raw_evidence"].write_text(json.dumps(raw))+ sanitizer.build_manifest(**inputs)++ def test_raw_evidence_digest_changes_without_exposing_raw_fields(self):+ inputs = self.inputs()+ first = sanitizer.build_manifest(**inputs)+ raw = json.loads(inputs["raw_evidence"].read_text())+ raw["capture_ids"]["acted"] = "different"+ inputs["raw_evidence"].write_text(json.dumps(raw))+ second = sanitizer.build_manifest(**inputs)+ self.assertNotEqual(first["raw_evidence_sha256"], second["raw_evidence_sha256"])+ self.assertNotIn("different", json.dumps(second))++ def test_rejects_unproven_stale_capture_refusal(self):+ inputs = self.inputs()+ raw = json.loads(inputs["raw_evidence"].read_text())+ raw["verification"]["stale_capture_refused"] = False+ inputs["raw_evidence"].write_text(json.dumps(raw))+ with self.assertRaisesRegex(ValueError, "stale-capture refusal"):+ sanitizer.build_manifest(**inputs)++ def test_rejects_desktop_evidence_without_background_refusal_and_capture_preservation(self):+ inputs = self.inputs()+ raw = json.loads(inputs["raw_evidence"].read_text())+ raw["observation"].update({+ "input_scope": "desktop",+ "capture_kind": "get_desktop_state",+ "delivery_mode": "foreground",+ })+ raw["timeline"]["events"][3] = "background_desktop_refused"+ inputs["raw_evidence"].write_text(json.dumps(raw))+ with self.assertRaisesRegex(ValueError, "desktop/background refusal"):+ sanitizer.build_manifest(**inputs)++ inputs = self.inputs()+ raw = json.loads(inputs["raw_evidence"].read_text())+ raw["observation"].update({+ "input_scope": "desktop",+ "capture_kind": "get_desktop_state",+ "delivery_mode": "foreground",+ })+ raw["verification"].update({+ "background_desktop_refused": True,+ "capture_preserved_after_refusal": False,+ })+ raw["timeline"]["events"][3] = "background_desktop_refused"+ inputs["raw_evidence"].write_text(json.dumps(raw))+ with self.assertRaisesRegex(ValueError, "capture preservation"):+ sanitizer.build_manifest(**inputs)++ inputs = self.inputs()+ raw = json.loads(inputs["raw_evidence"].read_text())+ raw["observation"].update({+ "input_scope": "desktop",+ "capture_kind": "get_desktop_state",+ "delivery_mode": "foreground",+ })+ raw["verification"].update({+ "background_desktop_refused": False,+ "capture_preserved_after_refusal": True,+ })+ raw["timeline"]["events"][3] = "background_desktop_refused"+ inputs["raw_evidence"].write_text(json.dumps(raw))+ with self.assertRaisesRegex(ValueError, "desktop/background refusal"):+ sanitizer.build_manifest(**inputs)++ def test_rejects_boolean_proof_for_window_route(self):+ inputs = self.inputs()+ raw = json.loads(inputs["raw_evidence"].read_text())+ raw["verification"].update({+ "background_desktop_refused": False,+ "capture_preserved_after_refusal": False,+ })+ inputs["raw_evidence"].write_text(json.dumps(raw))+ with self.assertRaisesRegex(ValueError, "desktop/background refusal"):+ sanitizer.build_manifest(**inputs)++ def test_rejects_raw_source_or_measured_result_mismatch(self):+ inputs = self.inputs()+ raw = json.loads(inputs["raw_evidence"].read_text())+ raw["source_sha"] = "f" * 40+ inputs["raw_evidence"].write_text(json.dumps(raw))+ with self.assertRaisesRegex(ValueError, "approved sources"):+ sanitizer.build_manifest(**inputs)++ inputs = self.inputs()+ raw = json.loads(inputs["raw_evidence"].read_text())+ raw["chooser"]["response"]["selected_id"] = "abstain"+ inputs["raw_evidence"].write_text(json.dumps(raw))+ with self.assertRaisesRegex(ValueError, "measured chooser result"):+ sanitizer.build_manifest(**inputs)++ def test_source_and_platform_are_runtime_measured(self):+ repo_root = HERE.parents[3]+ measured = subprocess.run(+ ["git", "-C", repo_root, "rev-parse", "HEAD"],+ check=True,+ capture_output=True,+ text=True,+ ).stdout.strip()+ self.assertEqual(sanitizer.measure_source_sha(repo_root, measured), measured)+ with self.assertRaisesRegex(ValueError, "approved workflow candidate"):+ sanitizer.measure_source_sha(repo_root, "0" * 40)+ self.assertEqual(sanitizer.measure_platform("win32", {}), "windows")+ self.assertEqual(sanitizer.measure_platform("linux", {"DISPLAY": ":99"}), "linux-x11")+ self.assertEqual(sanitizer.measure_platform("darwin", {}), "macos")++ def test_schema_is_closed_and_requires_ed25519_trust_evidence(self):+ schema = json.loads((HERE / "evidence-manifest.schema.json").read_text())+ perception = schema["properties"]["runtime"]["properties"]["perception"]+ chooser = schema["properties"]["runtime"]["properties"]["chooser"]+ result = schema["properties"]["result"]+ self.assertFalse(schema["additionalProperties"])+ self.assertFalse(perception["additionalProperties"])+ self.assertEqual(perception["properties"]["signature_algorithm"]["const"], "ed25519")+ self.assertEqual(perception["properties"]["trust"]["const"], "review-only-publisher-verified")+ self.assertIn("catalog_version", perception["required"])+ self.assertIn("signed_extension_archive_sha256", perception["required"])+ self.assertIn("signed_catalog_sha256", perception["required"])+ self.assertIn("driver", schema["properties"]["runtime"]["required"])+ self.assertFalse(chooser["additionalProperties"])+ self.assertFalse(result["additionalProperties"])+ self.assertEqual(chooser["properties"]["provider"]["enum"], ["fixture", "typesafe"])+ self.assertIn("null", chooser["properties"]["model_id"]["type"])+ self.assertIn("worker_sha256", perception["required"])+ self.assertIn("models", perception["required"])+ model_items = perception["properties"]["models"]["prefixItems"]+ self.assertEqual(+ [item["allOf"][1]["properties"]["role"]["const"] for item in model_items],+ ["icon-detect", "ocr-detect", "ocr-recognize"],+ )+ self.assertIn("onnx_runtime", perception["required"])+ self.assertIn("raw_evidence_sha256", schema["required"])+ self.assertIn("observation", schema["required"])+ self.assertIn("environment", schema["required"])+ self.assertIn("recording", schema["required"])+ self.assertEqual(len(schema["allOf"][0]["oneOf"]), 2)+ window_route, desktop_route = schema["allOf"][0]["oneOf"]+ self.assertIsNone(window_route["properties"]["result"]["properties"]["background_desktop_refused"]["const"])+ self.assertIsNone(window_route["properties"]["result"]["properties"]["capture_preserved_after_refusal"]["const"])+ self.assertTrue(desktop_route["properties"]["result"]["properties"]["background_desktop_refused"]["const"])+ self.assertTrue(desktop_route["properties"]["result"]["properties"]["capture_preserved_after_refusal"]["const"])+++if __name__ == "__main__":+ unittest.main()diff --git a/libs/cua-driver/tests/runners/macos-lume/README.md b/libs/cua-driver/tests/runners/macos-lume/README.mdindex 7585e94e99..c737fa0242 100644--- a/libs/cua-driver/tests/runners/macos-lume/README.md+++ b/libs/cua-driver/tests/runners/macos-lume/README.md@@ -4,6 +4,10 @@ This is the maintainer-owned macOS GUI acceptance gate for `cua-driver`. It isnot a GitHub Actions job. Run it on an Apple Silicon Mac with Lume, from adisposable clone of a stopped SIP-disabled golden image.+Do not install or register a GitHub Actions runner inside the guest. GitHub may+record the result afterward, but the canonical harness itself runs directly from+Terminal in the logged-in VM session.+The golden image supplies the logged-in Aqua session, stable local signingidentity, and existing Accessibility and Screen Recording grants. Every runinstalls the requested source commit before testing. The preflight rejects a@@ -391,6 +395,25 @@ cd ~/cualibs/cua-driver/tests/runners/macos-lume/run-all.sh --standalone-browser```+After a successful run, `artifacts/cua-driver/macos/direct-result.json` records+the exact source SHA and run ID. Preserve the private artifacts and register+their digest without uploading them publicly:++```bash+SOURCE_SHA="$(jq -r .source_sha artifacts/cua-driver/macos/direct-result.json)"+tar -czf "/tmp/cua-macos-lume-${SOURCE_SHA}.tgz" \+ artifacts/cua-driver/macos artifacts/cua-driver/macos-standalone-browser+shasum -a 256 "/tmp/cua-macos-lume-${SOURCE_SHA}.tgz"+jq -r .run_id artifacts/cua-driver/macos/direct-result.json+base64 < artifacts/cua-driver/macos/direct-result.json | tr -d '\n'+```++Dispatch `.github/workflows/e2e-rust-macos.yml` in `lume` mode at the same+source SHA, passing the run ID printed by the harness and the lowercase digest.+Also pass the one-line base64 value of `direct-result.json`. The protected+GitHub-hosted job validates and records the result; it does not rerun the guest+or require a self-hosted runner.+This adds the declared adversarial installed-browser rows and writes theirseparate typed results and MP4 evidence under`artifacts/cua-driver/macos-standalone-browser/`. Missing external browsers arediff --git a/libs/cua-driver/tests/runners/macos-lume/run-all.sh b/libs/cua-driver/tests/runners/macos-lume/run-all.shindex 5155bed344..ca857ece33 100755--- a/libs/cua-driver/tests/runners/macos-lume/run-all.sh+++ b/libs/cua-driver/tests/runners/macos-lume/run-all.sh@@ -18,6 +18,8 @@ LOCAL_APP="/Applications/CuaDriverLocal.app"INSTALLED_BIN="${HOME}/.local/bin/cua-driver-local"LOCAL_PLIST="${HOME}/Library/LaunchAgents/com.trycua.cua-driver-local.plist"CUA_E2E_MACOS_DAEMON_SOCKET="${CUA_E2E_MACOS_DAEMON_SOCKET:-${HOME}/Library/Caches/cua-driver-local/cua-driver-local.sock}"+SCREEN_CAPTURE_APPROVALS="${HOME}/Library/Group Containers/group.com.apple.replayd/ScreenCaptureApprovals.plist"+SCREEN_CAPTURE_CLIENT="com.trycua.driver.local"# A run-owned Cargo namespace keeps a certification build off the seed image's# and any other commit's target state without deleting a shared cache.CARGO_TARGET_ROOT="${CUA_E2E_CARGO_TARGET_ROOT:-${HOME}/Library/Caches/cua-driver-e2e/cargo-target}"@@ -27,6 +29,8 @@ RETRY_INTERNAL_LANE=sharedRETRY_ATTEMPTS_LIMIT=3# How long to wait for a daemon mode transition, in one-second polls.DAEMON_MODE_WAIT_ATTEMPTS="${CUA_E2E_DAEMON_WAIT_ATTEMPTS:-10}"+KEYCHAIN_COMMAND_TIMEOUT_SECONDS=5+KEYCHAIN_COMMAND_KILL_GRACE_SECONDS=1# Lanes whose failure is attributable to one typed matrix cell that an exact# single-cell rerun can reproduce. The embedded-browser lane is excluded on# purpose: filtering to one of its cells leaves the shared web-action lane with@@ -187,30 +191,160 @@ output_contains() {[[ "${CAPTURED_OUTPUT}" == *"${needle}"* ]]}-unlock_required_keychains() {- local keychain_password="${CUA_E2E_SIGNING_KEYCHAIN_PASSWORD:-}"- unset CUA_E2E_SIGNING_KEYCHAIN_PASSWORD+run_bounded_command() {+ command -v python3 >/dev/null 2>&1 || {+ echo "Missing golden-image dependency: python3" >&2+ return 127+ }+ python3 - "${KEYCHAIN_COMMAND_TIMEOUT_SECONDS}" \+ "${KEYCHAIN_COMMAND_KILL_GRACE_SECONDS}" "$@" <<'PY'+import os+import signal+import subprocess+import sys++timeout = float(sys.argv[1])+kill_grace = float(sys.argv[2])+try:+ process = subprocess.Popen(sys.argv[3:], start_new_session=True)+except OSError as error:+ print(f"failed to start bounded command {sys.argv[3]}: {error}", file=sys.stderr)+ raise SystemExit(127)+try:+ raise SystemExit(process.wait(timeout=timeout))+except subprocess.TimeoutExpired:+ try:+ os.killpg(process.pid, signal.SIGTERM)+ except ProcessLookupError:+ raise SystemExit(process.wait())+ try:+ process.wait(timeout=kill_grace)+ except subprocess.TimeoutExpired:+ try:+ os.killpg(process.pid, signal.SIGKILL)+ except ProcessLookupError:+ pass+ process.wait()+ raise SystemExit(124)+PY+}- echo "[SIGNING] Unlocking the golden image's dedicated signing keychain"- if [[ -n "${keychain_password}" ]]; then- security unlock-keychain -p "${keychain_password}" "${SIGNING_KEYCHAIN}"+probe_signing_keychain() {+ local keychain="$1"+ local signing_identity="${CUA_E2E_SIGNING_IDENTITY:-${SIGNING_CN}}"+ local probe_dir probe_binary status=0+ probe_dir="$(mktemp -d \+ "${TMPDIR:-/tmp}/cua-signing-keychain-probe.XXXXXX")" || return 1+ probe_binary="${probe_dir}/probe"+ cp /usr/bin/true "${probe_binary}" || status=$?+ if ((status == 0)); then+ run_bounded_command codesign --force --timestamp=none \+ --sign "${signing_identity}" \+ --keychain "${keychain}" "${probe_binary}" || status=$?+ fi+ if ((status == 0)); then+ run_bounded_command codesign --verify --strict "${probe_binary}" || status=$?+ fi+ rm -f "${probe_binary}"+ rmdir "${probe_dir}" 2>/dev/null || true+ return "${status}"+}++probe_login_keychain() {+ local keychain="$1"+ local service="cua-driver-keychain-probe-${$}-${RANDOM}"+ local account="cua-driver-keychain-probe"+ local probe_value="${service}"+ local observed_value="" status=0 cleanup_status=0++ if run_bounded_command security add-generic-password -a "${account}" \+ -s "${service}" -w "${probe_value}" "${keychain}"; then+ :else- security unlock-keychain "${SIGNING_KEYCHAIN}"+ status=$?+ fi+ if ((status == 0)); then+ observed_value="$(run_bounded_command security find-generic-password \+ -a "${account}" -s "${service}" -w "${keychain}")" || status=$?+ if ((status == 0)) && [[ "${observed_value}" != "${probe_value}" ]]; then+ status=1+ fifi+ run_bounded_command security delete-generic-password -a "${account}" \+ -s "${service}" "${keychain}" >/dev/null || cleanup_status=$?+ if ((cleanup_status != 0)); then+ echo "Login keychain probe cleanup failed; retrying the bounded delete once" >&2+ cleanup_status=0+ run_bounded_command security delete-generic-password -a "${account}" \+ -s "${service}" "${keychain}" >/dev/null || cleanup_status=$?+ fi+ if ((cleanup_status != 0)); then+ echo "Login keychain probe cleanup failed after two bounded delete attempts; temporary item ${service} may remain" >&2+ status=${cleanup_status}+ fi+ observed_value=""+ probe_value=""+ return "${status}"+}- if [[ ! -f "${LOGIN_KEYCHAIN}" ]]; then- echo "Missing console user's login Keychain: ${LOGIN_KEYCHAIN}" >&2- return 2+prepare_keychain() {+ local label="$1"+ local keychain="$2"+ local provided_password="$3"+ local probe_kind="$4"+ local keychain_password="${provided_password}"++ if [[ -z "${keychain_password}" && -t 0 ]]; then+ read -r -s -p "${label} password: " keychain_password+ printf '\n'fi- echo "[HISTORY] Unlocking the login Keychain for encrypted computer history"if [[ -n "${keychain_password}" ]]; then- security unlock-keychain -p "${keychain_password}" "${LOGIN_KEYCHAIN}"+ if ! run_bounded_command security unlock-keychain -p \+ "${keychain_password}" "${keychain}"; then+ echo "${label} could not be unlocked within the bounded operation" >&2+ return 2+ fielse- security unlock-keychain "${LOGIN_KEYCHAIN}"+ case "${probe_kind}" in+ signing)+ if ! probe_signing_keychain "${keychain}"; then+ echo "${label} did not permit the bounded signing and verification probe" >&2+ return 2+ fi+ ;;+ login)+ if ! probe_login_keychain "${keychain}"; then+ echo "${label} did not permit the bounded add/read/delete probe" >&2+ return 2+ fi+ ;;+ *)+ echo "Unknown keychain probe kind: ${probe_kind}" >&2+ return 2+ ;;+ esacfikeychain_password=""}+unlock_required_keychains() {+ local provided_password="${CUA_E2E_SIGNING_KEYCHAIN_PASSWORD:-}"+ unset CUA_E2E_SIGNING_KEYCHAIN_PASSWORD++ echo "[SIGNING] Preparing the golden image's dedicated signing keychain"+ prepare_keychain "Dedicated signing keychain" "${SIGNING_KEYCHAIN}" \+ "${provided_password}" signing++ if [[ ! -f "${LOGIN_KEYCHAIN}" ]]; then+ echo "Missing console user's login Keychain: ${LOGIN_KEYCHAIN}" >&2+ return 2+ fi+ echo "[HISTORY] Preparing the login Keychain for encrypted computer history"+ prepare_keychain "Login keychain" "${LOGIN_KEYCHAIN}" \+ "${provided_password}" login+ provided_password=""+}+json_string_array() {local itemlocal result=''@@ -258,6 +392,26 @@ preserve_previous_artifacts() {echo "[EVIDENCE] Preserved the previous certification run at ${destination}"}+setup_screen_capture_approval() {+ local evidence_file="${ARTIFACT_DIR}/screen-capture-approval.txt"+ echo "[CAPTURE] Suppressing the app-specific private-window-picker reminder"+ mkdir -p "$(dirname "${SCREEN_CAPTURE_APPROVALS}")"+ defaults write "${SCREEN_CAPTURE_APPROVALS}" "${SCREEN_CAPTURE_CLIENT}" -dict \+ kScreenCaptureApprovalLastAlerted -date "3024-01-01 00:00:00 +0000" \+ kScreenCaptureApprovalLastUsed -date "3024-01-01 00:00:00 +0000"+ killall -HUP replayd >/dev/null 2>&1 || true+ defaults read "${SCREEN_CAPTURE_APPROVALS}" "${SCREEN_CAPTURE_CLIENT}" \+ > "${evidence_file}"+ grep -Fq "kScreenCaptureApprovalLastAlerted" "${evidence_file}" || {+ echo "The app-specific screen capture reminder approval was not stored" >&2+ return 1+ }+ grep -Fq "kScreenCaptureApprovalLastUsed" "${evidence_file}" || {+ echo "The app-specific screen capture last-used approval was not stored" >&2+ return 1+ }+}+RESTORE_STANDARD_DAEMON=0UNRESTRICTED_WATCHDOG_PID=""@@ -738,6 +892,11 @@ fiecho "The Lume macOS runner must run in a macOS guest" >&2exit 2}+MODEL="$(/usr/sbin/sysctl -n hw.model 2>/dev/null || true)"+if [[ "${MODEL}" != VirtualMac* ]]; then+ echo "The Lume macOS runner requires a VirtualMac guest, got: ${MODEL:-unknown}" >&2+ exit 2+fiif [[ -n "${SSH_CONNECTION:-}" || -n "${SSH_TTY:-}" ]]; thenecho "Run this command from Terminal in the VM display so fixtures inherit the GUI login session" >&2exit 2@@ -761,7 +920,7 @@ if [[ "${SIP_STATUS}" != *"System Integrity Protection status: disabled."* ]]; texit 2fi-for command_name in cargo codesign ffmpeg ffprobe jq node npm osascript security xcrun; do+for command_name in cargo codesign ffmpeg ffprobe jq node npm osascript python3 security xcrun; docommand -v "${command_name}" >/dev/null 2>&1 || {echo "Missing golden-image dependency: ${command_name}" >&2exit 2@@ -815,6 +974,7 @@ export CUA_E2E_FRESH_FIXTURE_STATE=1preserve_previous_artifacts "${RUN_ID}"printf '%s\n' "${SIP_STATUS}" > "${ARTIFACT_DIR}/sip-status.txt"printf '%s\n' "${SOURCE_SHA}" > "${ARTIFACT_DIR}/requested-source-sha.txt"+printf '%s\n' "${RUN_ID}" > "${ARTIFACT_DIR}/run-id.txt"{sw_versprintf 'console_user:\t%s\n' "${CONSOLE_USER}"@@ -855,6 +1015,7 @@ if ! grep -Fq "certificate leaf" "${ARTIFACT_DIR}/codesign-requirement.txt"; theecho "CuaDriverLocal.app is not signed with the golden image's stable certificate identity" >&2exit 1fi+setup_screen_capture_approvalexport CUA_E2E_INSTALLED_DRIVER_BIN="${INSTALLED_BIN}"export CUA_E2E_MACOS_DAEMON_SOCKET@@ -963,3 +1124,15 @@ if [[ "${RUN_STANDALONE_BROWSER}" == 1 ]]; thenexit "${BROWSER_STATUS}"fifi++jq -n \+ --arg schema 'cua-driver/macos-lume-direct-result@v1' \+ --arg source_sha "${SOURCE_SHA}" \+ --arg run_id "${RUN_ID}" \+ --arg completed_at "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \+ --argjson standalone_browser "${RUN_STANDALONE_BROWSER}" \+ '{schema: $schema, source_sha: $source_sha, run_id: $run_id,+ completed_at: $completed_at, standalone_browser: ($standalone_browser == 1),+ passed: true}' > "${ARTIFACT_DIR}/direct-result.json"++echo "macOS direct Lume run passed: ${RUN_ID}"diff --git a/libs/cua-driver/tests/runners/macos-lume/seed-tcc-guest.sh b/libs/cua-driver/tests/runners/macos-lume/seed-tcc-guest.shindex b2e63069a9..20f1e8f01a 100755--- a/libs/cua-driver/tests/runners/macos-lume/seed-tcc-guest.sh+++ b/libs/cua-driver/tests/runners/macos-lume/seed-tcc-guest.sh@@ -154,8 +154,14 @@ if ! REQUIREMENT_INFO="$(/usr/bin/codesign -d -r- "${SIGN_TARGET}" 2>&1)"; thenfiREQUIREMENT="$(/usr/bin/awk -F 'designated => ' '/^(# )?designated =>/ { print $2; exit }' <<< "${REQUIREMENT_INFO}")"[[ -n "${REQUIREMENT}" ]] || fail "could not read designated requirement from ${SIGN_TARGET}"-if [[ "${ALLOW_ADHOC}" != 1 && "${REQUIREMENT}" != *"certificate leaf"* ]]; then- fail "${SIGN_TARGET} is not signed with a certificate-backed identity; rerun install-local with --require-stable-signing or pass --allow-adhoc for a one-build-only grant"+if [[ "${ALLOW_ADHOC}" != 1 ]]; then+ if printf '%s\n' "${CODESIGN_INFO}" | /usr/bin/grep -q '^Signature=adhoc$'; then+ fail "${SIGN_TARGET} has an ad hoc signature; rerun install-local with --require-stable-signing, or use --allow-adhoc only for an explicitly authorized one-build grant"+ fi+ if ! printf '%s\n' "${REQUIREMENT}" |+ /usr/bin/grep -Eq 'certificate (leaf|root) = H"[[:xdigit:]]{40}"'; then+ fail "${SIGN_TARGET} is not signed with a certificate-backed identity; expected its designated requirement to bind a certificate leaf or root hash"+ fifiCSREQ_TMPDIR="$(/usr/bin/mktemp -d /tmp/cua-driver-tcc-csreq.XXXXXX)"@@ -179,7 +185,7 @@ if [[ "$(/usr/bin/id -u)" -ne 0 ]]; thenfiprintf '%s\n' "${SUDO_PASSWORD_CACHE}" | /usr/bin/sudo -S -p '' -v >/dev/nullelse- fail "sudo is required to write ${TCC_DB}; pass the password through the host wrapper or run as root"+ fail "non-interactive sudo preflight failed (no active sudo timestamp or NOPASSWD rule); pass the password through the host wrapper, configure narrowly scoped NOPASSWD sudo for this disposable guest, or run as root"fifidiff --git a/libs/cua-driver/typescript/src/native/cua_driver_contract.ts b/libs/cua-driver/typescript/src/native/cua_driver_contract.tsindex 2c57cd782d..eba4dc48cc 100644--- a/libs/cua-driver/typescript/src/native/cua_driver_contract.ts+++ b/libs/cua-driver/typescript/src/native/cua_driver_contract.ts@@ -715,7 +715,8 @@ const FfiConverterTypeActionTarget = (() => {// Enum: ClickPositionexport enum ClickPosition_Tags {Coordinates = "Coordinates",- Element = "Element"+ Element = "Element",+ CapturedCoordinates = "CapturedCoordinates"}export const ClickPosition = (() => {@@ -781,6 +782,37 @@ inner: {elementToken: string }): Element_ {}+ type CapturedCoordinates__interface = {+ tag: ClickPosition_Tags.CapturedCoordinates;+ inner:+Readonly<{x: number; y: number; captureId: string}>+ };+ class CapturedCoordinates_ extends UniffiEnum implements CapturedCoordinates__interface {+ /**+ * @private+ * This field is private and should not be used, use `tag` instead.+ */+ readonly [uniffiTypeNameSymbol] = "ClickPosition";+ readonly tag = ClickPosition_Tags.CapturedCoordinates;+ readonly inner:+Readonly<{x: number; y: number; captureId: string}>;+ constructor(+inner: {x: number; y: number; captureId: string }) {+ super("ClickPosition", "CapturedCoordinates");++ this.inner = Object.freeze(inner);+ }+ static new(+inner: {x: number; y: number; captureId: string }): CapturedCoordinates_ {+ return new CapturedCoordinates_(inner);+ }++ static instanceOf(obj: any): obj is CapturedCoordinates_ {+ return obj.tag === ClickPosition_Tags.CapturedCoordinates;+ }++ }+function instanceOf(obj: any): obj is ClickPosition {return obj[uniffiTypeNameSymbol] === "ClickPosition";}@@ -788,12 +820,13 @@ inner: {elementToken: string }): Element_ {return Object.freeze({instanceOf,Coordinates: Coordinates_,- Element: Element_+ Element: Element_,+ CapturedCoordinates: CapturedCoordinates_});})();export type ClickPosition = InstanceType<- typeof ClickPosition['Coordinates' | 'Element']+ typeof ClickPosition['Coordinates' | 'Element' | 'CapturedCoordinates']>;// FfiConverter for enum ClickPosition@@ -805,6 +838,7 @@ const FfiConverterTypeClickPosition = (() => {switch (ordinalConverter.read(from)) {case 1: return new ClickPosition.Coordinates({x: FfiConverterFloat64.read(from), y: FfiConverterFloat64.read(from) });case 2: return new ClickPosition.Element({elementToken: FfiConverterString.read(from) });+ case 3: return new ClickPosition.CapturedCoordinates({x: FfiConverterFloat64.read(from), y: FfiConverterFloat64.read(from), captureId: FfiConverterString.read(from) });default: throw new UniffiInternalError.UnexpectedEnumCase();}}@@ -823,6 +857,14 @@ const FfiConverterTypeClickPosition = (() => {FfiConverterString.write(inner.elementToken, into);return;}+ case ClickPosition_Tags.CapturedCoordinates: {+ ordinalConverter.write(3, into);+ const inner = value.inner;+ FfiConverterFloat64.write(inner.x, into);+ FfiConverterFloat64.write(inner.y, into);+ FfiConverterString.write(inner.captureId, into);+ return;+ }default:// Throwing from here means that ClickPosition_Tags hasn't matched an ordinal.throw new UniffiInternalError.UnexpectedEnumCase();@@ -843,6 +885,14 @@ const FfiConverterTypeClickPosition = (() => {size += FfiConverterString.allocationSize(inner.elementToken);return size;}+ case ClickPosition_Tags.CapturedCoordinates: {+ const inner = value.inner;+ let size = ordinalConverter.allocationSize(3);+ size += FfiConverterFloat64.allocationSize(inner.x);+ size += FfiConverterFloat64.allocationSize(inner.y);+ size += FfiConverterString.allocationSize(inner.captureId);+ return size;+ }default: throw new UniffiInternalError.UnexpectedEnumCase();}}@@ -2332,7 +2382,12 @@ export type GetWindowStateInput = {screenshotOutFile?: string,maxElements?: number,maxDepth?: number,- maxDimension?: number+ maxDimension?: number,+ /**+ * Optional per-call long-edge ceiling. Zero requests native resolution;+ * omit it to preserve the configured session or global behavior.+ */+ maxImageDimension?: number}/**@@ -2365,7 +2420,8 @@ const FfiConverterTypeGetWindowStateInput = (() => {screenshotOutFile: FfiConverterOptionalString.read(from),maxElements: FfiConverterOptionalUInt32.read(from),maxDepth: FfiConverterOptionalUInt32.read(from),- maxDimension: FfiConverterOptionalUInt32.read(from)+ maxDimension: FfiConverterOptionalUInt32.read(from),+ maxImageDimension: FfiConverterOptionalUInt32.read(from)};}write(value: TypeName, into: RustBuffer): void {@@ -2379,6 +2435,7 @@ const FfiConverterTypeGetWindowStateInput = (() => {FfiConverterOptionalUInt32.write(value.maxElements, into);FfiConverterOptionalUInt32.write(value.maxDepth, into);FfiConverterOptionalUInt32.write(value.maxDimension, into);+ FfiConverterOptionalUInt32.write(value.maxImageDimension, into);}allocationSize(value: TypeName): number {return FfiConverterUInt32.allocationSize(value.pid) +@@ -2390,7 +2447,8 @@ const FfiConverterTypeGetWindowStateInput = (() => {FfiConverterOptionalString.allocationSize(value.screenshotOutFile) +FfiConverterOptionalUInt32.allocationSize(value.maxElements) +FfiConverterOptionalUInt32.allocationSize(value.maxDepth) +- FfiConverterOptionalUInt32.allocationSize(value.maxDimension);+ FfiConverterOptionalUInt32.allocationSize(value.maxDimension) ++ FfiConverterOptionalUInt32.allocationSize(value.maxImageDimension);}};@@ -3149,73 +3207,26 @@ const FfiConverterTypeMoveCursorInput = (() => {return new FFIConverter();})();-export enum VerificationStatus {- Satisfied,- Unsatisfied,- Unknown-}--const FfiConverterTypeVerificationStatus = (() => {- const ordinalConverter = FfiConverterInt32;- type TypeName = VerificationStatus;- class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {- read(from: RustBuffer): TypeName {- switch (ordinalConverter.read(from)) {- case 1: return VerificationStatus.Satisfied;- case 2: return VerificationStatus.Unsatisfied;- case 3: return VerificationStatus.Unknown;- default: throw new UniffiInternalError.UnexpectedEnumCase();- }- }- write(value: TypeName, into: RustBuffer): void {- switch (value) {- case VerificationStatus.Satisfied: return ordinalConverter.write(1, into);- case VerificationStatus.Unsatisfied: return ordinalConverter.write(2, into);- case VerificationStatus.Unknown: return ordinalConverter.write(3, into);- }- }- allocationSize(value: TypeName): number {- return ordinalConverter.allocationSize(0);- }- }- return new FFIConverter();-})();--export enum UnknownReason {- InvalidPredicate,- UnsupportedPredicate,- UntrustedSource,- MultiMatch,- TargetMissing,- ObservationUnavailable,- StabilityUnproven+export enum VisualRegionKind {+ Text,+ Icon}-const FfiConverterTypeUnknownReason = (() => {+const FfiConverterTypeVisualRegionKind = (() => {const ordinalConverter = FfiConverterInt32;- type TypeName = UnknownReason;+ type TypeName = VisualRegionKind;class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {read(from: RustBuffer): TypeName {switch (ordinalConverter.read(from)) {- case 1: return UnknownReason.InvalidPredicate;- case 2: return UnknownReason.UnsupportedPredicate;- case 3: return UnknownReason.UntrustedSource;- case 4: return UnknownReason.MultiMatch;- case 5: return UnknownReason.TargetMissing;- case 6: return UnknownReason.ObservationUnavailable;- case 7: return UnknownReason.StabilityUnproven;+ case 1: return VisualRegionKind.Text;+ case 2: return VisualRegionKind.Icon;default: throw new UniffiInternalError.UnexpectedEnumCase();}}write(value: TypeName, into: RustBuffer): void {switch (value) {- case UnknownReason.InvalidPredicate: return ordinalConverter.write(1, into);- case UnknownReason.UnsupportedPredicate: return ordinalConverter.write(2, into);- case UnknownReason.UntrustedSource: return ordinalConverter.write(3, into);- case UnknownReason.MultiMatch: return ordinalConverter.write(4, into);- case UnknownReason.TargetMissing: return ordinalConverter.write(5, into);- case UnknownReason.ObservationUnavailable: return ordinalConverter.write(6, into);- case UnknownReason.StabilityUnproven: return ordinalConverter.write(7, into);+ case VisualRegionKind.Text: return ordinalConverter.write(1, into);+ case VisualRegionKind.Icon: return ordinalConverter.write(2, into);}}allocationSize(value: TypeName): number {@@ -3225,185 +3236,1162 @@ const FfiConverterTypeUnknownReason = (() => {return new FFIConverter();})();-export type PredicateOutcome = {- index: bigint,- status: VerificationStatus,- unknownReason?: UnknownReason,- /**- * Normalized, bounded JSON projection of the matched state.- */- observedJson?: string+/**+ * Optional, model-neutral controls for one bounded parse.+ */+export type ParseVisualRegionsOptions = {+ kinds?: Array<VisualRegionKind>,+ minConfidence?: number,+ maxRegions?: number}/**- * Generated factory for {@link PredicateOutcome} record objects.+ * Generated factory for {@link ParseVisualRegionsOptions} record objects.*/-export const PredicateOutcome = (() => {+export const ParseVisualRegionsOptions = (() => {const defaults = () => ({});const create = (() => {- return uniffiCreateRecord<PredicateOutcome, ReturnType<typeof defaults>>(defaults);+ return uniffiCreateRecord<ParseVisualRegionsOptions, ReturnType<typeof defaults>>(defaults);})();return Object.freeze({create,new: create,- defaults: () => Object.freeze(defaults()) as Partial<PredicateOutcome>,+ defaults: () => Object.freeze(defaults()) as Partial<ParseVisualRegionsOptions>,});})();-const FfiConverterTypePredicateOutcome = (() => {- type TypeName = PredicateOutcome;+const FfiConverterTypeParseVisualRegionsOptions = (() => {+ type TypeName = ParseVisualRegionsOptions;class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {read(from: RustBuffer): TypeName {return {- index: FfiConverterUInt64.read(from),- status: FfiConverterTypeVerificationStatus.read(from),- unknownReason: FfiConverterOptionalTypeUnknownReason.read(from),- observedJson: FfiConverterOptionalString.read(from)+ kinds: FfiConverterOptionalSequenceTypeVisualRegionKind.read(from),+ minConfidence: FfiConverterOptionalFloat64.read(from),+ maxRegions: FfiConverterOptionalUInt32.read(from)};}write(value: TypeName, into: RustBuffer): void {- FfiConverterUInt64.write(value.index, into);- FfiConverterTypeVerificationStatus.write(value.status, into);- FfiConverterOptionalTypeUnknownReason.write(value.unknownReason, into);- FfiConverterOptionalString.write(value.observedJson, into);+ FfiConverterOptionalSequenceTypeVisualRegionKind.write(value.kinds, into);+ FfiConverterOptionalFloat64.write(value.minConfidence, into);+ FfiConverterOptionalUInt32.write(value.maxRegions, into);}allocationSize(value: TypeName): number {- return FfiConverterUInt64.allocationSize(value.index) +- FfiConverterTypeVerificationStatus.allocationSize(value.status) +- FfiConverterOptionalTypeUnknownReason.allocationSize(value.unknownReason) +- FfiConverterOptionalString.allocationSize(value.observedJson);+ return FfiConverterOptionalSequenceTypeVisualRegionKind.allocationSize(value.kinds) ++ FfiConverterOptionalFloat64.allocationSize(value.minConfidence) ++ FfiConverterOptionalUInt32.allocationSize(value.maxRegions);}};return new FFIConverter();})();-export type PressKeyInput = {- key: string,- target?: ActionTarget,- /**- * Deprecated flat desktop target retained for wire compatibility.- */- scope?: DesktopScope,- /**- * For multi-call work, prefer a short public session label and repeat it on every call that- * accepts it. Omit it to use the authenticated transport's implicit lifecycle session.- */- session?: string,- modifiers?: Array<string>+/**+ * Transport-free request. Runtime use requires the future capture registry.+ */+export type ParseVisualRegionsInput = {+ captureId: string,+ options: ParseVisualRegionsOptions}/**- * Generated factory for {@link PressKeyInput} record objects.+ * Generated factory for {@link ParseVisualRegionsInput} record objects.*/-export const PressKeyInput = (() => {+export const ParseVisualRegionsInput = (() => {const defaults = () => ({});const create = (() => {- return uniffiCreateRecord<PressKeyInput, ReturnType<typeof defaults>>(defaults);+ return uniffiCreateRecord<ParseVisualRegionsInput, ReturnType<typeof defaults>>(defaults);})();return Object.freeze({create,new: create,- defaults: () => Object.freeze(defaults()) as Partial<PressKeyInput>,+ defaults: () => Object.freeze(defaults()) as Partial<ParseVisualRegionsInput>,});})();-const FfiConverterTypePressKeyInput = (() => {- type TypeName = PressKeyInput;+const FfiConverterTypeParseVisualRegionsInput = (() => {+ type TypeName = ParseVisualRegionsInput;class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {read(from: RustBuffer): TypeName {return {- key: FfiConverterString.read(from),- target: FfiConverterOptionalTypeActionTarget.read(from),- scope: FfiConverterOptionalTypeDesktopScope.read(from),- session: FfiConverterOptionalString.read(from),- modifiers: FfiConverterOptionalSequenceString.read(from)+ captureId: FfiConverterString.read(from),+ options: FfiConverterTypeParseVisualRegionsOptions.read(from)};}write(value: TypeName, into: RustBuffer): void {- FfiConverterString.write(value.key, into);- FfiConverterOptionalTypeActionTarget.write(value.target, into);- FfiConverterOptionalTypeDesktopScope.write(value.scope, into);- FfiConverterOptionalString.write(value.session, into);- FfiConverterOptionalSequenceString.write(value.modifiers, into);+ FfiConverterString.write(value.captureId, into);+ FfiConverterTypeParseVisualRegionsOptions.write(value.options, into);}allocationSize(value: TypeName): number {- return FfiConverterString.allocationSize(value.key) +- FfiConverterOptionalTypeActionTarget.allocationSize(value.target) +- FfiConverterOptionalTypeDesktopScope.allocationSize(value.scope) +- FfiConverterOptionalString.allocationSize(value.session) +- FfiConverterOptionalSequenceString.allocationSize(value.modifiers);+ return FfiConverterString.allocationSize(value.captureId) ++ FfiConverterTypeParseVisualRegionsOptions.allocationSize(value.options);}};return new FFIConverter();})();-export enum ScrollDirection {- Up,- Down,- Left,- Right++// Enum: VisualCaptureSource+export enum VisualCaptureSource_Tags {+ Window = "Window",+ PrimaryDesktop = "PrimaryDesktop"}+/**+ * Exact screen content that produced the immutable capture.+ */+export const VisualCaptureSource = (() => {-const FfiConverterTypeScrollDirection = (() => {- const ordinalConverter = FfiConverterInt32;- type TypeName = ScrollDirection;- class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {- read(from: RustBuffer): TypeName {- switch (ordinalConverter.read(from)) {- case 1: return ScrollDirection.Up;- case 2: return ScrollDirection.Down;- case 3: return ScrollDirection.Left;- case 4: return ScrollDirection.Right;- default: throw new UniffiInternalError.UnexpectedEnumCase();- }+ type Window__interface = {+ tag: VisualCaptureSource_Tags.Window;+ inner:+Readonly<{pid: number; windowId: bigint}>+ };+ class Window_ extends UniffiEnum implements Window__interface {+ /**+ * @private+ * This field is private and should not be used, use `tag` instead.+ */+ readonly [uniffiTypeNameSymbol] = "VisualCaptureSource";+ readonly tag = VisualCaptureSource_Tags.Window;+ readonly inner:+Readonly<{pid: number; windowId: bigint}>;+ constructor(+inner: {pid: number; windowId: bigint }) {+ super("VisualCaptureSource", "Window");++ this.inner = Object.freeze(inner);}- write(value: TypeName, into: RustBuffer): void {- switch (value) {- case ScrollDirection.Up: return ordinalConverter.write(1, into);- case ScrollDirection.Down: return ordinalConverter.write(2, into);- case ScrollDirection.Left: return ordinalConverter.write(3, into);- case ScrollDirection.Right: return ordinalConverter.write(4, into);- }+ static new(+inner: {pid: number; windowId: bigint }): Window_ {+ return new Window_(inner);}- allocationSize(value: TypeName): number {- return ordinalConverter.allocationSize(0);++ static instanceOf(obj: any): obj is Window_ {+ return obj.tag === VisualCaptureSource_Tags.Window;}+}- return new FFIConverter();-})();-export enum ScrollBy {- Line,- Page-}+ type PrimaryDesktop__interface = {+ tag: VisualCaptureSource_Tags.PrimaryDesktop;+ inner:+Readonly<{displayId: string}>+ };+ class PrimaryDesktop_ extends UniffiEnum implements PrimaryDesktop__interface {+ /**+ * @private+ * This field is private and should not be used, use `tag` instead.+ */+ readonly [uniffiTypeNameSymbol] = "VisualCaptureSource";+ readonly tag = VisualCaptureSource_Tags.PrimaryDesktop;+ readonly inner:+Readonly<{displayId: string}>;+ constructor(+inner: {displayId: string }) {+ super("VisualCaptureSource", "PrimaryDesktop");-const FfiConverterTypeScrollBy = (() => {+ this.inner = Object.freeze(inner);+ }+ static new(+inner: {displayId: string }): PrimaryDesktop_ {+ return new PrimaryDesktop_(inner);+ }++ static instanceOf(obj: any): obj is PrimaryDesktop_ {+ return obj.tag === VisualCaptureSource_Tags.PrimaryDesktop;+ }++ }++ function instanceOf(obj: any): obj is VisualCaptureSource {+ return obj[uniffiTypeNameSymbol] === "VisualCaptureSource";+ }++ return Object.freeze({+ instanceOf,+ Window: Window_,+ PrimaryDesktop: PrimaryDesktop_+ });++})();+/**+ * Exact screen content that produced the immutable capture.+ */+export type VisualCaptureSource = InstanceType<+ typeof VisualCaptureSource['Window' | 'PrimaryDesktop']+>;++// FfiConverter for enum VisualCaptureSource+const FfiConverterTypeVisualCaptureSource = (() => {const ordinalConverter = FfiConverterInt32;- type TypeName = ScrollBy;+ type TypeName = VisualCaptureSource;class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {read(from: RustBuffer): TypeName {switch (ordinalConverter.read(from)) {- case 1: return ScrollBy.Line;- case 2: return ScrollBy.Page;+ case 1: return new VisualCaptureSource.Window({pid: FfiConverterUInt32.read(from), windowId: FfiConverterUInt64.read(from) });+ case 2: return new VisualCaptureSource.PrimaryDesktop({displayId: FfiConverterString.read(from) });default: throw new UniffiInternalError.UnexpectedEnumCase();}}write(value: TypeName, into: RustBuffer): void {- switch (value) {- case ScrollBy.Line: return ordinalConverter.write(1, into);- case ScrollBy.Page: return ordinalConverter.write(2, into);- }- }- allocationSize(value: TypeName): number {- return ordinalConverter.allocationSize(0);- }- }- return new FFIConverter();-})();+ switch (value.tag) {+ case VisualCaptureSource_Tags.Window: {+ ordinalConverter.write(1, into);+ const inner = value.inner;+ FfiConverterUInt32.write(inner.pid, into);+ FfiConverterUInt64.write(inner.windowId, into);+ return;+ }+ case VisualCaptureSource_Tags.PrimaryDesktop: {+ ordinalConverter.write(2, into);+ const inner = value.inner;+ FfiConverterString.write(inner.displayId, into);+ return;+ }+ default:+ // Throwing from here means that VisualCaptureSource_Tags hasn't matched an ordinal.+ throw new UniffiInternalError.UnexpectedEnumCase();+ }+ }+ allocationSize(value: TypeName): number {+ switch (value.tag) {+ case VisualCaptureSource_Tags.Window: {+ const inner = value.inner;+ let size = ordinalConverter.allocationSize(1);+ size += FfiConverterUInt32.allocationSize(inner.pid);+ size += FfiConverterUInt64.allocationSize(inner.windowId);+ return size;+ }+ case VisualCaptureSource_Tags.PrimaryDesktop: {+ const inner = value.inner;+ let size = ordinalConverter.allocationSize(2);+ size += FfiConverterString.allocationSize(inner.displayId);+ return size;+ }+ default: throw new UniffiInternalError.UnexpectedEnumCase();+ }+ }+ }+ return new FFIConverter();+})();++/**+ * Screenshot identity and geometry retained by the future capture registry.+ */+export type VisualScreenshotReference = {+ /**+ * Opaque identity for these exact encoded pixels, such as a content digest.+ */+ reference: string,+ width: number,+ height: number,+ mimeType: string,+ sha256?: string+}++/**+ * Generated factory for {@link VisualScreenshotReference} record objects.+ */+export const VisualScreenshotReference = (() => {+ const defaults = () => ({+ });+ const create = (() => {+ return uniffiCreateRecord<VisualScreenshotReference, ReturnType<typeof defaults>>(defaults);+ })();+ return Object.freeze({+ create,+ new: create,+ defaults: () => Object.freeze(defaults()) as Partial<VisualScreenshotReference>,+ });+})();++const FfiConverterTypeVisualScreenshotReference = (() => {+ type TypeName = VisualScreenshotReference;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ return {+ reference: FfiConverterString.read(from),+ width: FfiConverterUInt32.read(from),+ height: FfiConverterUInt32.read(from),+ mimeType: FfiConverterString.read(from),+ sha256: FfiConverterOptionalString.read(from)+ };+ }+ write(value: TypeName, into: RustBuffer): void {+ FfiConverterString.write(value.reference, into);+ FfiConverterUInt32.write(value.width, into);+ FfiConverterUInt32.write(value.height, into);+ FfiConverterString.write(value.mimeType, into);+ FfiConverterOptionalString.write(value.sha256, into);+ }+ allocationSize(value: TypeName): number {+ return FfiConverterString.allocationSize(value.reference) ++ FfiConverterUInt32.allocationSize(value.width) ++ FfiConverterUInt32.allocationSize(value.height) ++ FfiConverterString.allocationSize(value.mimeType) ++ FfiConverterOptionalString.allocationSize(value.sha256);++ }+ };+ return new FFIConverter();+})();+++// Enum: VisualActionCoordinateSpace+export enum VisualActionCoordinateSpace_Tags {+ ScreenshotPixels = "ScreenshotPixels",+ Affine = "Affine"+}+/**+ * Normative mapping from source screenshot pixels to Driver action coordinates.+ *+ * Screenshot coordinates always originate at the encoded PNG's top-left; X+ * increases right and Y increases down. The affine form maps a source point+ * `(px, py)` exactly as:+ *+ * `action_x = m11 * px + m12 * py + tx`+ *+ * `action_y = m21 * px + m22 * py + ty`+ */+export const VisualActionCoordinateSpace = (() => {++ type ScreenshotPixels__interface = {+ tag: VisualActionCoordinateSpace_Tags.ScreenshotPixels+ };+ /**+ * Action coordinates are the same physical pixel coordinates as the PNG.+ */+ class ScreenshotPixels_ extends UniffiEnum implements ScreenshotPixels__interface {+ /**+ * @private+ * This field is private and should not be used, use `tag` instead.+ */+ readonly [uniffiTypeNameSymbol] = "VisualActionCoordinateSpace";+ readonly tag = VisualActionCoordinateSpace_Tags.ScreenshotPixels;+ constructor() {+ super("VisualActionCoordinateSpace", "ScreenshotPixels");+ }++ static new(): ScreenshotPixels_ {+ return new ScreenshotPixels_();+ }++ static instanceOf(obj: any): obj is ScreenshotPixels_ {+ return obj.tag === VisualActionCoordinateSpace_Tags.ScreenshotPixels;+ }++ }++ type Affine__interface = {+ tag: VisualActionCoordinateSpace_Tags.Affine;+ inner:+Readonly<{m11: number; m12: number; m21: number; m22: number; tx: number; ty: number}>+ };+ /**+ * Lossless six-coefficient affine transform retained by the capture registry.+ */+ class Affine_ extends UniffiEnum implements Affine__interface {+ /**+ * @private+ * This field is private and should not be used, use `tag` instead.+ */+ readonly [uniffiTypeNameSymbol] = "VisualActionCoordinateSpace";+ readonly tag = VisualActionCoordinateSpace_Tags.Affine;+ readonly inner:+Readonly<{m11: number; m12: number; m21: number; m22: number; tx: number; ty: number}>;+ constructor(+inner: {m11: number; m12: number; m21: number; m22: number; tx: number; ty: number }) {+ super("VisualActionCoordinateSpace", "Affine");++ this.inner = Object.freeze(inner);+ }+ static new(+inner: {m11: number; m12: number; m21: number; m22: number; tx: number; ty: number }): Affine_ {+ return new Affine_(inner);+ }++ static instanceOf(obj: any): obj is Affine_ {+ return obj.tag === VisualActionCoordinateSpace_Tags.Affine;+ }++ }++ function instanceOf(obj: any): obj is VisualActionCoordinateSpace {+ return obj[uniffiTypeNameSymbol] === "VisualActionCoordinateSpace";+ }++ return Object.freeze({+ instanceOf,+ ScreenshotPixels: ScreenshotPixels_,+ Affine: Affine_+ });++})();+/**+ * Normative mapping from source screenshot pixels to Driver action coordinates.+ *+ * Screenshot coordinates always originate at the encoded PNG's top-left; X+ * increases right and Y increases down. The affine form maps a source point+ * `(px, py)` exactly as:+ *+ * `action_x = m11 * px + m12 * py + tx`+ *+ * `action_y = m21 * px + m22 * py + ty`+ */+export type VisualActionCoordinateSpace = InstanceType<+ typeof VisualActionCoordinateSpace['ScreenshotPixels' | 'Affine']+>;++// FfiConverter for enum VisualActionCoordinateSpace+const FfiConverterTypeVisualActionCoordinateSpace = (() => {+ const ordinalConverter = FfiConverterInt32;+ type TypeName = VisualActionCoordinateSpace;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ switch (ordinalConverter.read(from)) {+ case 1: return new VisualActionCoordinateSpace.ScreenshotPixels();+ case 2: return new VisualActionCoordinateSpace.Affine({m11: FfiConverterFloat64.read(from), m12: FfiConverterFloat64.read(from), m21: FfiConverterFloat64.read(from), m22: FfiConverterFloat64.read(from), tx: FfiConverterFloat64.read(from), ty: FfiConverterFloat64.read(from) });+ default: throw new UniffiInternalError.UnexpectedEnumCase();+ }+ }+ write(value: TypeName, into: RustBuffer): void {+ switch (value.tag) {+ case VisualActionCoordinateSpace_Tags.ScreenshotPixels: {+ ordinalConverter.write(1, into);+ return;+ }+ case VisualActionCoordinateSpace_Tags.Affine: {+ ordinalConverter.write(2, into);+ const inner = value.inner;+ FfiConverterFloat64.write(inner.m11, into);+ FfiConverterFloat64.write(inner.m12, into);+ FfiConverterFloat64.write(inner.m21, into);+ FfiConverterFloat64.write(inner.m22, into);+ FfiConverterFloat64.write(inner.tx, into);+ FfiConverterFloat64.write(inner.ty, into);+ return;+ }+ default:+ // Throwing from here means that VisualActionCoordinateSpace_Tags hasn't matched an ordinal.+ throw new UniffiInternalError.UnexpectedEnumCase();+ }+ }+ allocationSize(value: TypeName): number {+ switch (value.tag) {+ case VisualActionCoordinateSpace_Tags.ScreenshotPixels: {+ return ordinalConverter.allocationSize(1);+ }+ case VisualActionCoordinateSpace_Tags.Affine: {+ const inner = value.inner;+ let size = ordinalConverter.allocationSize(2);+ size += FfiConverterFloat64.allocationSize(inner.m11);+ size += FfiConverterFloat64.allocationSize(inner.m12);+ size += FfiConverterFloat64.allocationSize(inner.m21);+ size += FfiConverterFloat64.allocationSize(inner.m22);+ size += FfiConverterFloat64.allocationSize(inner.tx);+ size += FfiConverterFloat64.allocationSize(inner.ty);+ return size;+ }+ default: throw new UniffiInternalError.UnexpectedEnumCase();+ }+ }+ }+ return new FFIConverter();+})();++/**+ * Immutable capture provenance echoed by a parse result.+ */+export type VisualCaptureProvenance = {+ captureId: string,+ source: VisualCaptureSource,+ screenshot: VisualScreenshotReference,+ actionCoordinateSpace: VisualActionCoordinateSpace,+ capturedAt?: string+}++/**+ * Generated factory for {@link VisualCaptureProvenance} record objects.+ */+export const VisualCaptureProvenance = (() => {+ const defaults = () => ({+ });+ const create = (() => {+ return uniffiCreateRecord<VisualCaptureProvenance, ReturnType<typeof defaults>>(defaults);+ })();+ return Object.freeze({+ create,+ new: create,+ defaults: () => Object.freeze(defaults()) as Partial<VisualCaptureProvenance>,+ });+})();++const FfiConverterTypeVisualCaptureProvenance = (() => {+ type TypeName = VisualCaptureProvenance;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ return {+ captureId: FfiConverterString.read(from),+ source: FfiConverterTypeVisualCaptureSource.read(from),+ screenshot: FfiConverterTypeVisualScreenshotReference.read(from),+ actionCoordinateSpace: FfiConverterTypeVisualActionCoordinateSpace.read(from),+ capturedAt: FfiConverterOptionalString.read(from)+ };+ }+ write(value: TypeName, into: RustBuffer): void {+ FfiConverterString.write(value.captureId, into);+ FfiConverterTypeVisualCaptureSource.write(value.source, into);+ FfiConverterTypeVisualScreenshotReference.write(value.screenshot, into);+ FfiConverterTypeVisualActionCoordinateSpace.write(value.actionCoordinateSpace, into);+ FfiConverterOptionalString.write(value.capturedAt, into);+ }+ allocationSize(value: TypeName): number {+ return FfiConverterString.allocationSize(value.captureId) ++ FfiConverterTypeVisualCaptureSource.allocationSize(value.source) ++ FfiConverterTypeVisualScreenshotReference.allocationSize(value.screenshot) ++ FfiConverterTypeVisualActionCoordinateSpace.allocationSize(value.actionCoordinateSpace) ++ FfiConverterOptionalString.allocationSize(value.capturedAt);++ }+ };+ return new FFIConverter();+})();++/**+ * Identity of the extension and model that produced a result.+ */+export type VisualParserMetadata = {+ extensionId: string,+ extensionVersion: string,+ modelId: string,+ modelVersion: string,+ runtime?: string,+ backend?: string,+ modelSourceRevision?: string,+ modelManifestSha256?: string,+ onnxRuntimeVersion?: string,+ onnxRuntimeLibrarySha256?: string,+ fixtureSha256?: string+}++/**+ * Generated factory for {@link VisualParserMetadata} record objects.+ */+export const VisualParserMetadata = (() => {+ const defaults = () => ({+ });+ const create = (() => {+ return uniffiCreateRecord<VisualParserMetadata, ReturnType<typeof defaults>>(defaults);+ })();+ return Object.freeze({+ create,+ new: create,+ defaults: () => Object.freeze(defaults()) as Partial<VisualParserMetadata>,+ });+})();++const FfiConverterTypeVisualParserMetadata = (() => {+ type TypeName = VisualParserMetadata;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ return {+ extensionId: FfiConverterString.read(from),+ extensionVersion: FfiConverterString.read(from),+ modelId: FfiConverterString.read(from),+ modelVersion: FfiConverterString.read(from),+ runtime: FfiConverterOptionalString.read(from),+ backend: FfiConverterOptionalString.read(from),+ modelSourceRevision: FfiConverterOptionalString.read(from),+ modelManifestSha256: FfiConverterOptionalString.read(from),+ onnxRuntimeVersion: FfiConverterOptionalString.read(from),+ onnxRuntimeLibrarySha256: FfiConverterOptionalString.read(from),+ fixtureSha256: FfiConverterOptionalString.read(from)+ };+ }+ write(value: TypeName, into: RustBuffer): void {+ FfiConverterString.write(value.extensionId, into);+ FfiConverterString.write(value.extensionVersion, into);+ FfiConverterString.write(value.modelId, into);+ FfiConverterString.write(value.modelVersion, into);+ FfiConverterOptionalString.write(value.runtime, into);+ FfiConverterOptionalString.write(value.backend, into);+ FfiConverterOptionalString.write(value.modelSourceRevision, into);+ FfiConverterOptionalString.write(value.modelManifestSha256, into);+ FfiConverterOptionalString.write(value.onnxRuntimeVersion, into);+ FfiConverterOptionalString.write(value.onnxRuntimeLibrarySha256, into);+ FfiConverterOptionalString.write(value.fixtureSha256, into);+ }+ allocationSize(value: TypeName): number {+ return FfiConverterString.allocationSize(value.extensionId) ++ FfiConverterString.allocationSize(value.extensionVersion) ++ FfiConverterString.allocationSize(value.modelId) ++ FfiConverterString.allocationSize(value.modelVersion) ++ FfiConverterOptionalString.allocationSize(value.runtime) ++ FfiConverterOptionalString.allocationSize(value.backend) ++ FfiConverterOptionalString.allocationSize(value.modelSourceRevision) ++ FfiConverterOptionalString.allocationSize(value.modelManifestSha256) ++ FfiConverterOptionalString.allocationSize(value.onnxRuntimeVersion) ++ FfiConverterOptionalString.allocationSize(value.onnxRuntimeLibrarySha256) ++ FfiConverterOptionalString.allocationSize(value.fixtureSha256);++ }+ };+ return new FFIConverter();+})();++/**+ * Integer pixel-edge bounds `[x, x + width) x [y, y + height)`.+ *+ * `x` and `y` name the left and top pixel edges. The right and bottom edges+ * are excluded. A region therefore covers every pixel whose center lies in+ * this half-open box; its geometric center may lie between pixels.+ */+export type VisualRegionBounds = {+ x: number,+ y: number,+ width: number,+ height: number+}++/**+ * Generated factory for {@link VisualRegionBounds} record objects.+ */+export const VisualRegionBounds = (() => {+ const defaults = () => ({+ });+ const create = (() => {+ return uniffiCreateRecord<VisualRegionBounds, ReturnType<typeof defaults>>(defaults);+ })();+ return Object.freeze({+ create,+ new: create,+ defaults: () => Object.freeze(defaults()) as Partial<VisualRegionBounds>,+ });+})();++const FfiConverterTypeVisualRegionBounds = (() => {+ type TypeName = VisualRegionBounds;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ return {+ x: FfiConverterUInt32.read(from),+ y: FfiConverterUInt32.read(from),+ width: FfiConverterUInt32.read(from),+ height: FfiConverterUInt32.read(from)+ };+ }+ write(value: TypeName, into: RustBuffer): void {+ FfiConverterUInt32.write(value.x, into);+ FfiConverterUInt32.write(value.y, into);+ FfiConverterUInt32.write(value.width, into);+ FfiConverterUInt32.write(value.height, into);+ }+ allocationSize(value: TypeName): number {+ return FfiConverterUInt32.allocationSize(value.x) ++ FfiConverterUInt32.allocationSize(value.y) ++ FfiConverterUInt32.allocationSize(value.width) ++ FfiConverterUInt32.allocationSize(value.height);++ }+ };+ return new FFIConverter();+})();++/**+ * One parser-observed region in the exact source screenshot pixel space.+ */+export type VisualRegion = {+ /**+ * Stable identifier unique within this parse result.+ */+ id: string,+ kind: VisualRegionKind,+ bounds: VisualRegionBounds,+ text?: string,+ label?: string,+ confidence: number,+ interactive: boolean,+ parentId?: string,+ groupId?: string,+ readingOrder?: number+}++/**+ * Generated factory for {@link VisualRegion} record objects.+ */+export const VisualRegion = (() => {+ const defaults = () => ({+ });+ const create = (() => {+ return uniffiCreateRecord<VisualRegion, ReturnType<typeof defaults>>(defaults);+ })();+ return Object.freeze({+ create,+ new: create,+ defaults: () => Object.freeze(defaults()) as Partial<VisualRegion>,+ });+})();++const FfiConverterTypeVisualRegion = (() => {+ type TypeName = VisualRegion;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ return {+ id: FfiConverterString.read(from),+ kind: FfiConverterTypeVisualRegionKind.read(from),+ bounds: FfiConverterTypeVisualRegionBounds.read(from),+ text: FfiConverterOptionalString.read(from),+ label: FfiConverterOptionalString.read(from),+ confidence: FfiConverterFloat64.read(from),+ interactive: FfiConverterBool.read(from),+ parentId: FfiConverterOptionalString.read(from),+ groupId: FfiConverterOptionalString.read(from),+ readingOrder: FfiConverterOptionalUInt32.read(from)+ };+ }+ write(value: TypeName, into: RustBuffer): void {+ FfiConverterString.write(value.id, into);+ FfiConverterTypeVisualRegionKind.write(value.kind, into);+ FfiConverterTypeVisualRegionBounds.write(value.bounds, into);+ FfiConverterOptionalString.write(value.text, into);+ FfiConverterOptionalString.write(value.label, into);+ FfiConverterFloat64.write(value.confidence, into);+ FfiConverterBool.write(value.interactive, into);+ FfiConverterOptionalString.write(value.parentId, into);+ FfiConverterOptionalString.write(value.groupId, into);+ FfiConverterOptionalUInt32.write(value.readingOrder, into);+ }+ allocationSize(value: TypeName): number {+ return FfiConverterString.allocationSize(value.id) ++ FfiConverterTypeVisualRegionKind.allocationSize(value.kind) ++ FfiConverterTypeVisualRegionBounds.allocationSize(value.bounds) ++ FfiConverterOptionalString.allocationSize(value.text) ++ FfiConverterOptionalString.allocationSize(value.label) ++ FfiConverterFloat64.allocationSize(value.confidence) ++ FfiConverterBool.allocationSize(value.interactive) ++ FfiConverterOptionalString.allocationSize(value.parentId) ++ FfiConverterOptionalString.allocationSize(value.groupId) ++ FfiConverterOptionalUInt32.allocationSize(value.readingOrder);++ }+ };+ return new FFIConverter();+})();++export type VisualParseWarning = {+ code: string,+ message: string,+ detail?: string+}++/**+ * Generated factory for {@link VisualParseWarning} record objects.+ */+export const VisualParseWarning = (() => {+ const defaults = () => ({+ });+ const create = (() => {+ return uniffiCreateRecord<VisualParseWarning, ReturnType<typeof defaults>>(defaults);+ })();+ return Object.freeze({+ create,+ new: create,+ defaults: () => Object.freeze(defaults()) as Partial<VisualParseWarning>,+ });+})();++const FfiConverterTypeVisualParseWarning = (() => {+ type TypeName = VisualParseWarning;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ return {+ code: FfiConverterString.read(from),+ message: FfiConverterString.read(from),+ detail: FfiConverterOptionalString.read(from)+ };+ }+ write(value: TypeName, into: RustBuffer): void {+ FfiConverterString.write(value.code, into);+ FfiConverterString.write(value.message, into);+ FfiConverterOptionalString.write(value.detail, into);+ }+ allocationSize(value: TypeName): number {+ return FfiConverterString.allocationSize(value.code) ++ FfiConverterString.allocationSize(value.message) ++ FfiConverterOptionalString.allocationSize(value.detail);++ }+ };+ return new FFIConverter();+})();++export type VisualParseTiming = {+ durationMs: bigint,+ preprocessMs?: bigint,+ inferenceMs?: bigint+}++/**+ * Generated factory for {@link VisualParseTiming} record objects.+ */+export const VisualParseTiming = (() => {+ const defaults = () => ({+ });+ const create = (() => {+ return uniffiCreateRecord<VisualParseTiming, ReturnType<typeof defaults>>(defaults);+ })();+ return Object.freeze({+ create,+ new: create,+ defaults: () => Object.freeze(defaults()) as Partial<VisualParseTiming>,+ });+})();++const FfiConverterTypeVisualParseTiming = (() => {+ type TypeName = VisualParseTiming;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ return {+ durationMs: FfiConverterUInt64.read(from),+ preprocessMs: FfiConverterOptionalUInt64.read(from),+ inferenceMs: FfiConverterOptionalUInt64.read(from)+ };+ }+ write(value: TypeName, into: RustBuffer): void {+ FfiConverterUInt64.write(value.durationMs, into);+ FfiConverterOptionalUInt64.write(value.preprocessMs, into);+ FfiConverterOptionalUInt64.write(value.inferenceMs, into);+ }+ allocationSize(value: TypeName): number {+ return FfiConverterUInt64.allocationSize(value.durationMs) ++ FfiConverterOptionalUInt64.allocationSize(value.preprocessMs) ++ FfiConverterOptionalUInt64.allocationSize(value.inferenceMs);++ }+ };+ return new FFIConverter();+})();++export type ParseVisualRegionsOutput = {+ schema: string,+ capture: VisualCaptureProvenance,+ parser: VisualParserMetadata,+ regions: Array<VisualRegion>,+ warnings: Array<VisualParseWarning>,+ timing: VisualParseTiming,+ requestId?: string+}++/**+ * Generated factory for {@link ParseVisualRegionsOutput} record objects.+ */+export const ParseVisualRegionsOutput = (() => {+ const defaults = () => ({+ });+ const create = (() => {+ return uniffiCreateRecord<ParseVisualRegionsOutput, ReturnType<typeof defaults>>(defaults);+ })();+ return Object.freeze({+ create,+ new: create,+ defaults: () => Object.freeze(defaults()) as Partial<ParseVisualRegionsOutput>,+ });+})();++const FfiConverterTypeParseVisualRegionsOutput = (() => {+ type TypeName = ParseVisualRegionsOutput;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ return {+ schema: FfiConverterString.read(from),+ capture: FfiConverterTypeVisualCaptureProvenance.read(from),+ parser: FfiConverterTypeVisualParserMetadata.read(from),+ regions: FfiConverterSequenceTypeVisualRegion.read(from),+ warnings: FfiConverterSequenceTypeVisualParseWarning.read(from),+ timing: FfiConverterTypeVisualParseTiming.read(from),+ requestId: FfiConverterOptionalString.read(from)+ };+ }+ write(value: TypeName, into: RustBuffer): void {+ FfiConverterString.write(value.schema, into);+ FfiConverterTypeVisualCaptureProvenance.write(value.capture, into);+ FfiConverterTypeVisualParserMetadata.write(value.parser, into);+ FfiConverterSequenceTypeVisualRegion.write(value.regions, into);+ FfiConverterSequenceTypeVisualParseWarning.write(value.warnings, into);+ FfiConverterTypeVisualParseTiming.write(value.timing, into);+ FfiConverterOptionalString.write(value.requestId, into);+ }+ allocationSize(value: TypeName): number {+ return FfiConverterString.allocationSize(value.schema) ++ FfiConverterTypeVisualCaptureProvenance.allocationSize(value.capture) ++ FfiConverterTypeVisualParserMetadata.allocationSize(value.parser) ++ FfiConverterSequenceTypeVisualRegion.allocationSize(value.regions) ++ FfiConverterSequenceTypeVisualParseWarning.allocationSize(value.warnings) ++ FfiConverterTypeVisualParseTiming.allocationSize(value.timing) ++ FfiConverterOptionalString.allocationSize(value.requestId);++ }+ };+ return new FFIConverter();+})();++export enum VerificationStatus {+ Satisfied,+ Unsatisfied,+ Unknown+}++const FfiConverterTypeVerificationStatus = (() => {+ const ordinalConverter = FfiConverterInt32;+ type TypeName = VerificationStatus;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ switch (ordinalConverter.read(from)) {+ case 1: return VerificationStatus.Satisfied;+ case 2: return VerificationStatus.Unsatisfied;+ case 3: return VerificationStatus.Unknown;+ default: throw new UniffiInternalError.UnexpectedEnumCase();+ }+ }+ write(value: TypeName, into: RustBuffer): void {+ switch (value) {+ case VerificationStatus.Satisfied: return ordinalConverter.write(1, into);+ case VerificationStatus.Unsatisfied: return ordinalConverter.write(2, into);+ case VerificationStatus.Unknown: return ordinalConverter.write(3, into);+ }+ }+ allocationSize(value: TypeName): number {+ return ordinalConverter.allocationSize(0);+ }+ }+ return new FFIConverter();+})();++export enum UnknownReason {+ InvalidPredicate,+ UnsupportedPredicate,+ UntrustedSource,+ MultiMatch,+ TargetMissing,+ ObservationUnavailable,+ StabilityUnproven+}++const FfiConverterTypeUnknownReason = (() => {+ const ordinalConverter = FfiConverterInt32;+ type TypeName = UnknownReason;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ switch (ordinalConverter.read(from)) {+ case 1: return UnknownReason.InvalidPredicate;+ case 2: return UnknownReason.UnsupportedPredicate;+ case 3: return UnknownReason.UntrustedSource;+ case 4: return UnknownReason.MultiMatch;+ case 5: return UnknownReason.TargetMissing;+ case 6: return UnknownReason.ObservationUnavailable;+ case 7: return UnknownReason.StabilityUnproven;+ default: throw new UniffiInternalError.UnexpectedEnumCase();+ }+ }+ write(value: TypeName, into: RustBuffer): void {+ switch (value) {+ case UnknownReason.InvalidPredicate: return ordinalConverter.write(1, into);+ case UnknownReason.UnsupportedPredicate: return ordinalConverter.write(2, into);+ case UnknownReason.UntrustedSource: return ordinalConverter.write(3, into);+ case UnknownReason.MultiMatch: return ordinalConverter.write(4, into);+ case UnknownReason.TargetMissing: return ordinalConverter.write(5, into);+ case UnknownReason.ObservationUnavailable: return ordinalConverter.write(6, into);+ case UnknownReason.StabilityUnproven: return ordinalConverter.write(7, into);+ }+ }+ allocationSize(value: TypeName): number {+ return ordinalConverter.allocationSize(0);+ }+ }+ return new FFIConverter();+})();++export type PredicateOutcome = {+ index: bigint,+ status: VerificationStatus,+ unknownReason?: UnknownReason,+ /**+ * Normalized, bounded JSON projection of the matched state.+ */+ observedJson?: string+}++/**+ * Generated factory for {@link PredicateOutcome} record objects.+ */+export const PredicateOutcome = (() => {+ const defaults = () => ({+ });+ const create = (() => {+ return uniffiCreateRecord<PredicateOutcome, ReturnType<typeof defaults>>(defaults);+ })();+ return Object.freeze({+ create,+ new: create,+ defaults: () => Object.freeze(defaults()) as Partial<PredicateOutcome>,+ });+})();++const FfiConverterTypePredicateOutcome = (() => {+ type TypeName = PredicateOutcome;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ return {+ index: FfiConverterUInt64.read(from),+ status: FfiConverterTypeVerificationStatus.read(from),+ unknownReason: FfiConverterOptionalTypeUnknownReason.read(from),+ observedJson: FfiConverterOptionalString.read(from)+ };+ }+ write(value: TypeName, into: RustBuffer): void {+ FfiConverterUInt64.write(value.index, into);+ FfiConverterTypeVerificationStatus.write(value.status, into);+ FfiConverterOptionalTypeUnknownReason.write(value.unknownReason, into);+ FfiConverterOptionalString.write(value.observedJson, into);+ }+ allocationSize(value: TypeName): number {+ return FfiConverterUInt64.allocationSize(value.index) ++ FfiConverterTypeVerificationStatus.allocationSize(value.status) ++ FfiConverterOptionalTypeUnknownReason.allocationSize(value.unknownReason) ++ FfiConverterOptionalString.allocationSize(value.observedJson);++ }+ };+ return new FFIConverter();+})();++export type PressKeyInput = {+ key: string,+ target?: ActionTarget,+ /**+ * Deprecated flat desktop target retained for wire compatibility.+ */+ scope?: DesktopScope,+ /**+ * For multi-call work, prefer a short public session label and repeat it on every call that+ * accepts it. Omit it to use the authenticated transport's implicit lifecycle session.+ */+ session?: string,+ modifiers?: Array<string>+}++/**+ * Generated factory for {@link PressKeyInput} record objects.+ */+export const PressKeyInput = (() => {+ const defaults = () => ({+ });+ const create = (() => {+ return uniffiCreateRecord<PressKeyInput, ReturnType<typeof defaults>>(defaults);+ })();+ return Object.freeze({+ create,+ new: create,+ defaults: () => Object.freeze(defaults()) as Partial<PressKeyInput>,+ });+})();++const FfiConverterTypePressKeyInput = (() => {+ type TypeName = PressKeyInput;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ return {+ key: FfiConverterString.read(from),+ target: FfiConverterOptionalTypeActionTarget.read(from),+ scope: FfiConverterOptionalTypeDesktopScope.read(from),+ session: FfiConverterOptionalString.read(from),+ modifiers: FfiConverterOptionalSequenceString.read(from)+ };+ }+ write(value: TypeName, into: RustBuffer): void {+ FfiConverterString.write(value.key, into);+ FfiConverterOptionalTypeActionTarget.write(value.target, into);+ FfiConverterOptionalTypeDesktopScope.write(value.scope, into);+ FfiConverterOptionalString.write(value.session, into);+ FfiConverterOptionalSequenceString.write(value.modifiers, into);+ }+ allocationSize(value: TypeName): number {+ return FfiConverterString.allocationSize(value.key) ++ FfiConverterOptionalTypeActionTarget.allocationSize(value.target) ++ FfiConverterOptionalTypeDesktopScope.allocationSize(value.scope) ++ FfiConverterOptionalString.allocationSize(value.session) ++ FfiConverterOptionalSequenceString.allocationSize(value.modifiers);++ }+ };+ return new FFIConverter();+})();++export enum ScrollDirection {+ Up,+ Down,+ Left,+ Right+}++const FfiConverterTypeScrollDirection = (() => {+ const ordinalConverter = FfiConverterInt32;+ type TypeName = ScrollDirection;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ switch (ordinalConverter.read(from)) {+ case 1: return ScrollDirection.Up;+ case 2: return ScrollDirection.Down;+ case 3: return ScrollDirection.Left;+ case 4: return ScrollDirection.Right;+ default: throw new UniffiInternalError.UnexpectedEnumCase();+ }+ }+ write(value: TypeName, into: RustBuffer): void {+ switch (value) {+ case ScrollDirection.Up: return ordinalConverter.write(1, into);+ case ScrollDirection.Down: return ordinalConverter.write(2, into);+ case ScrollDirection.Left: return ordinalConverter.write(3, into);+ case ScrollDirection.Right: return ordinalConverter.write(4, into);+ }+ }+ allocationSize(value: TypeName): number {+ return ordinalConverter.allocationSize(0);+ }+ }+ return new FFIConverter();+})();++export enum ScrollBy {+ Line,+ Page+}++const FfiConverterTypeScrollBy = (() => {+ const ordinalConverter = FfiConverterInt32;+ type TypeName = ScrollBy;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ switch (ordinalConverter.read(from)) {+ case 1: return ScrollBy.Line;+ case 2: return ScrollBy.Page;+ default: throw new UniffiInternalError.UnexpectedEnumCase();+ }+ }+ write(value: TypeName, into: RustBuffer): void {+ switch (value) {+ case ScrollBy.Line: return ordinalConverter.write(1, into);+ case ScrollBy.Page: return ordinalConverter.write(2, into);+ }+ }+ allocationSize(value: TypeName): number {+ return ordinalConverter.allocationSize(0);+ }+ }+ return new FFIConverter();+})();export type ScrollInput = {x: number,@@ -4414,6 +5402,131 @@ const FfiConverterTypeVerifyStateOutput = (() => {return new FFIConverter();})();+/**+ * Stable machine-readable failures for capture lookup and visual parsing.+ */+export enum VisualParseErrorCode {+ NotInstalled,+ CaptureNotFound,+ CaptureExpired,+ CaptureStale,+ CaptureGenerationMismatch,+ UnsupportedTarget,+ UnsupportedPlatform,+ IncompatibleProtocol,+ InvalidFrame,+ WorkerLaunchFailed,+ WorkerCrashed,+ WorkerCancelled,+ Timeout,+ ResourceLimitExceeded,+ ArtifactInvalid,+ InferenceFailed+}++const FfiConverterTypeVisualParseErrorCode = (() => {+ const ordinalConverter = FfiConverterInt32;+ type TypeName = VisualParseErrorCode;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ switch (ordinalConverter.read(from)) {+ case 1: return VisualParseErrorCode.NotInstalled;+ case 2: return VisualParseErrorCode.CaptureNotFound;+ case 3: return VisualParseErrorCode.CaptureExpired;+ case 4: return VisualParseErrorCode.CaptureStale;+ case 5: return VisualParseErrorCode.CaptureGenerationMismatch;+ case 6: return VisualParseErrorCode.UnsupportedTarget;+ case 7: return VisualParseErrorCode.UnsupportedPlatform;+ case 8: return VisualParseErrorCode.IncompatibleProtocol;+ case 9: return VisualParseErrorCode.InvalidFrame;+ case 10: return VisualParseErrorCode.WorkerLaunchFailed;+ case 11: return VisualParseErrorCode.WorkerCrashed;+ case 12: return VisualParseErrorCode.WorkerCancelled;+ case 13: return VisualParseErrorCode.Timeout;+ case 14: return VisualParseErrorCode.ResourceLimitExceeded;+ case 15: return VisualParseErrorCode.ArtifactInvalid;+ case 16: return VisualParseErrorCode.InferenceFailed;+ default: throw new UniffiInternalError.UnexpectedEnumCase();+ }+ }+ write(value: TypeName, into: RustBuffer): void {+ switch (value) {+ case VisualParseErrorCode.NotInstalled: return ordinalConverter.write(1, into);+ case VisualParseErrorCode.CaptureNotFound: return ordinalConverter.write(2, into);+ case VisualParseErrorCode.CaptureExpired: return ordinalConverter.write(3, into);+ case VisualParseErrorCode.CaptureStale: return ordinalConverter.write(4, into);+ case VisualParseErrorCode.CaptureGenerationMismatch: return ordinalConverter.write(5, into);+ case VisualParseErrorCode.UnsupportedTarget: return ordinalConverter.write(6, into);+ case VisualParseErrorCode.UnsupportedPlatform: return ordinalConverter.write(7, into);+ case VisualParseErrorCode.IncompatibleProtocol: return ordinalConverter.write(8, into);+ case VisualParseErrorCode.InvalidFrame: return ordinalConverter.write(9, into);+ case VisualParseErrorCode.WorkerLaunchFailed: return ordinalConverter.write(10, into);+ case VisualParseErrorCode.WorkerCrashed: return ordinalConverter.write(11, into);+ case VisualParseErrorCode.WorkerCancelled: return ordinalConverter.write(12, into);+ case VisualParseErrorCode.Timeout: return ordinalConverter.write(13, into);+ case VisualParseErrorCode.ResourceLimitExceeded: return ordinalConverter.write(14, into);+ case VisualParseErrorCode.ArtifactInvalid: return ordinalConverter.write(15, into);+ case VisualParseErrorCode.InferenceFailed: return ordinalConverter.write(16, into);+ }+ }+ allocationSize(value: TypeName): number {+ return ordinalConverter.allocationSize(0);+ }+ }+ return new FFIConverter();+})();++export type VisualParseError = {+ code: VisualParseErrorCode,+ message: string,+ retryable: boolean,+ detail?: string+}++/**+ * Generated factory for {@link VisualParseError} record objects.+ */+export const VisualParseError = (() => {+ const defaults = () => ({+ });+ const create = (() => {+ return uniffiCreateRecord<VisualParseError, ReturnType<typeof defaults>>(defaults);+ })();+ return Object.freeze({+ create,+ new: create,+ defaults: () => Object.freeze(defaults()) as Partial<VisualParseError>,+ });+})();++const FfiConverterTypeVisualParseError = (() => {+ type TypeName = VisualParseError;+ class FFIConverter extends AbstractFfiConverterByteArray<TypeName> {+ read(from: RustBuffer): TypeName {+ return {+ code: FfiConverterTypeVisualParseErrorCode.read(from),+ message: FfiConverterString.read(from),+ retryable: FfiConverterBool.read(from),+ detail: FfiConverterOptionalString.read(from)+ };+ }+ write(value: TypeName, into: RustBuffer): void {+ FfiConverterTypeVisualParseErrorCode.write(value.code, into);+ FfiConverterString.write(value.message, into);+ FfiConverterBool.write(value.retryable, into);+ FfiConverterOptionalString.write(value.detail, into);+ }+ allocationSize(value: TypeName): number {+ return FfiConverterTypeVisualParseErrorCode.allocationSize(value.code) ++ FfiConverterString.allocationSize(value.message) ++ FfiConverterBool.allocationSize(value.retryable) ++ FfiConverterOptionalString.allocationSize(value.detail);++ }+ };+ return new FFIConverter();+})();+export type WindowElement = {elementIndex: bigint,role: string,@@ -4741,6 +5854,18 @@ const FfiConverterOptionalSequenceUInt64 = new FfiConverterOptional(FfiConverter// FfiConverter for Array<WindowInfo>const FfiConverterSequenceTypeWindowInfo = new FfiConverterArray(FfiConverterTypeWindowInfo);+// FfiConverter for Array<VisualRegionKind>+const FfiConverterSequenceTypeVisualRegionKind = new FfiConverterArray(FfiConverterTypeVisualRegionKind);++// FfiConverter for Array<VisualRegionKind> | undefined+const FfiConverterOptionalSequenceTypeVisualRegionKind = new FfiConverterOptional(FfiConverterSequenceTypeVisualRegionKind);++// FfiConverter for Array<VisualRegion>+const FfiConverterSequenceTypeVisualRegion = new FfiConverterArray(FfiConverterTypeVisualRegion);++// FfiConverter for Array<VisualParseWarning>+const FfiConverterSequenceTypeVisualParseWarning = new FfiConverterArray(FfiConverterTypeVisualParseWarning);+// FfiConverter for UnknownReason | undefinedconst FfiConverterOptionalTypeUnknownReason = new FfiConverterOptional(FfiConverterTypeUnknownReason);@@ -4867,6 +5992,9 @@ export default Object.freeze({FfiConverterTypeListWindowsInput,FfiConverterTypeListWindowsOutput,FfiConverterTypeMoveCursorInput,+ FfiConverterTypeParseVisualRegionsInput,+ FfiConverterTypeParseVisualRegionsOptions,+ FfiConverterTypeParseVisualRegionsOutput,FfiConverterTypePlatform,FfiConverterTypePredicateOutcome,FfiConverterTypePressKeyInput,@@ -4894,6 +6022,18 @@ export default Object.freeze({FfiConverterTypeVerificationStatus,FfiConverterTypeVerifyStateInput,FfiConverterTypeVerifyStateOutput,+ FfiConverterTypeVisualActionCoordinateSpace,+ FfiConverterTypeVisualCaptureProvenance,+ FfiConverterTypeVisualCaptureSource,+ FfiConverterTypeVisualParseError,+ FfiConverterTypeVisualParseErrorCode,+ FfiConverterTypeVisualParseTiming,+ FfiConverterTypeVisualParseWarning,+ FfiConverterTypeVisualParserMetadata,+ FfiConverterTypeVisualRegion,+ FfiConverterTypeVisualRegionBounds,+ FfiConverterTypeVisualRegionKind,+ FfiConverterTypeVisualScreenshotReference,FfiConverterTypeWindowBounds,FfiConverterTypeWindowElement,FfiConverterTypeWindowInfo,diff --git a/libs/cua-driver/typescript/src/native/cua_driver_sdk-ffi.ts b/libs/cua-driver/typescript/src/native/cua_driver_sdk-ffi.tsindex 51bcd16db2..0dc83f185c 100644--- a/libs/cua-driver/typescript/src/native/cua_driver_sdk-ffi.ts+++ b/libs/cua-driver/typescript/src/native/cua_driver_sdk-ffi.ts@@ -593,6 +593,11 @@ const DEFINITIONS = {ret: FfiType.Handle,hasRustCallStatus: false,},+ "uniffi_cua_driver_sdk_fn_method_cuadriver_parse_visual_regions": {+ args: [FfiType.Handle, FfiType.RustBuffer],+ ret: FfiType.Handle,+ hasRustCallStatus: false,+ },"uniffi_cua_driver_sdk_fn_method_cuadriver_press_key": {args: [FfiType.Handle, FfiType.RustBuffer],ret: FfiType.Handle,@@ -758,6 +763,11 @@ const DEFINITIONS = {ret: FfiType.Handle,hasRustCallStatus: false,},+ "uniffi_cua_driver_sdk_fn_method_cuadriversession_parse_visual_regions": {+ args: [FfiType.Handle, FfiType.RustBuffer],+ ret: FfiType.Handle,+ hasRustCallStatus: false,+ },"uniffi_cua_driver_sdk_fn_method_cuadriversession_press_key": {args: [FfiType.Handle, FfiType.RustBuffer],ret: FfiType.Handle,@@ -1143,6 +1153,11 @@ const DEFINITIONS = {ret: FfiType.UInt16,hasRustCallStatus: false,},+ "uniffi_cua_driver_sdk_checksum_method_cuadriver_parse_visual_regions": {+ args: [],+ ret: FfiType.UInt16,+ hasRustCallStatus: false,+ },"uniffi_cua_driver_sdk_checksum_method_cuadriver_press_key": {args: [],ret: FfiType.UInt16,@@ -1308,6 +1323,11 @@ const DEFINITIONS = {ret: FfiType.UInt16,hasRustCallStatus: false,},+ "uniffi_cua_driver_sdk_checksum_method_cuadriversession_parse_visual_regions": {+ args: [],+ ret: FfiType.UInt16,+ hasRustCallStatus: false,+ },"uniffi_cua_driver_sdk_checksum_method_cuadriversession_press_key": {args: [],ret: FfiType.UInt16,@@ -1730,6 +1750,7 @@ interface NativeModuleInterface {uniffi_cua_driver_sdk_fn_method_cuadriver_list_windows(uniffiSelf: bigint, input: Uint8Array): bigint;uniffi_cua_driver_sdk_fn_method_cuadriver_metadata(uniffiSelf: bigint): bigint;uniffi_cua_driver_sdk_fn_method_cuadriver_move_cursor(uniffiSelf: bigint, input: Uint8Array): bigint;+ uniffi_cua_driver_sdk_fn_method_cuadriver_parse_visual_regions(uniffiSelf: bigint, input: Uint8Array): bigint;uniffi_cua_driver_sdk_fn_method_cuadriver_press_key(uniffiSelf: bigint, input: Uint8Array): bigint;uniffi_cua_driver_sdk_fn_method_cuadriver_runtime_scope_prefix(uniffiSelf: bigint, uniffi_out_err: UniffiRustCallStatus): Uint8Array;uniffi_cua_driver_sdk_fn_method_cuadriver_scroll(uniffiSelf: bigint, input: Uint8Array): bigint;@@ -1763,6 +1784,7 @@ interface NativeModuleInterface {uniffi_cua_driver_sdk_fn_method_cuadriversession_list_sessions(uniffiSelf: bigint, input: Uint8Array): bigint;uniffi_cua_driver_sdk_fn_method_cuadriversession_list_windows(uniffiSelf: bigint, input: Uint8Array): bigint;uniffi_cua_driver_sdk_fn_method_cuadriversession_move_cursor(uniffiSelf: bigint, input: Uint8Array): bigint;+ uniffi_cua_driver_sdk_fn_method_cuadriversession_parse_visual_regions(uniffiSelf: bigint, input: Uint8Array): bigint;uniffi_cua_driver_sdk_fn_method_cuadriversession_press_key(uniffiSelf: bigint, input: Uint8Array): bigint;uniffi_cua_driver_sdk_fn_method_cuadriversession_scroll(uniffiSelf: bigint, input: Uint8Array): bigint;uniffi_cua_driver_sdk_fn_method_cuadriversession_set_agent_cursor_enabled(uniffiSelf: bigint, input: Uint8Array): bigint;@@ -1840,6 +1862,7 @@ interface NativeModuleInterface {uniffi_cua_driver_sdk_checksum_method_cuadriver_list_windows(): number;uniffi_cua_driver_sdk_checksum_method_cuadriver_metadata(): number;uniffi_cua_driver_sdk_checksum_method_cuadriver_move_cursor(): number;+ uniffi_cua_driver_sdk_checksum_method_cuadriver_parse_visual_regions(): number;uniffi_cua_driver_sdk_checksum_method_cuadriver_press_key(): number;uniffi_cua_driver_sdk_checksum_method_cuadriver_runtime_scope_prefix(): number;uniffi_cua_driver_sdk_checksum_method_cuadriver_scroll(): number;@@ -1873,6 +1896,7 @@ interface NativeModuleInterface {uniffi_cua_driver_sdk_checksum_method_cuadriversession_list_sessions(): number;uniffi_cua_driver_sdk_checksum_method_cuadriversession_list_windows(): number;uniffi_cua_driver_sdk_checksum_method_cuadriversession_move_cursor(): number;+ uniffi_cua_driver_sdk_checksum_method_cuadriversession_parse_visual_regions(): number;uniffi_cua_driver_sdk_checksum_method_cuadriversession_press_key(): number;uniffi_cua_driver_sdk_checksum_method_cuadriversession_scroll(): number;uniffi_cua_driver_sdk_checksum_method_cuadriversession_set_agent_cursor_enabled(): number;diff --git a/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts b/libs/cua-driver/typescript/src/native/cua_driver_sdk.tsindex 72eb92fa1a..542c14c79a 100644--- a/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts+++ b/libs/cua-driver/typescript/src/native/cua_driver_sdk.ts@@ -6,12 +6,12 @@import nativeModule from "./cua_driver_sdk-ffi.js";import { type UniffiRustFutureContinuationCallback, type UniffiForeignFutureDroppedCallback, type UniffiForeignFutureDroppedCallbackStruct, type UniffiVTableCallbackInterfaceCuaDriverSdkDriverActivityObserver, type UniffiForeignFutureResultRustBuffer, type UniffiForeignFutureCompleterustBuffer, type UniffiVTableCallbackInterfaceCuaDriverSdkDriverAuthorizationHost, type UniffiVTableCallbackInterfaceCuaDriverSdkDriverServiceTransport, type UniffiForeignFutureResultVoid, type UniffiForeignFutureCompletevoid, type UniffiVTableCallbackInterfaceCuaDriverSdkForeignDriverEnvelopeChannel,} from "./cua_driver_sdk-ffi.js";-import { type ActionResult, type ClickInput, type ClipboardReadInput, type ClipboardWriteInput, type DragInput, type EndSessionInput, type EndSessionOutput, type EscalateSessionInput, type GetAgentCursorStateInput, type GetCursorPositionInput, type GetDesktopStateInput, type GetScreenSizeInput, type GetSessionInput, type GetSessionStateInput, type GetWindowStateInput, type HotkeyInput, type InvokeMenuInput, type ListAppsInput, type ListAppsOutput, type ListSessionsInput, type ListSessionsOutput, type ListWindowsInput, type ListWindowsOutput, type MoveCursorInput, type PressKeyInput, type ScrollInput, type SessionOutput, type SessionStateOutput, type SetAgentCursorEnabledInput, type SetAgentCursorMotionInput, type SetAgentCursorThemeInput, type SetWindowFrameInput, type StartSessionInput, type StartSessionOutput, type TypeTextInput, type VerifyStateInput, type VerifyStateOutput, type WindowStateOutput,+import { type ActionResult, type ClickInput, type ClipboardReadInput, type ClipboardWriteInput, type DragInput, type EndSessionInput, type EndSessionOutput, type EscalateSessionInput, type GetAgentCursorStateInput, type GetCursorPositionInput, type GetDesktopStateInput, type GetScreenSizeInput, type GetSessionInput, type GetSessionStateInput, type GetWindowStateInput, type HotkeyInput, type InvokeMenuInput, type ListAppsInput, type ListAppsOutput, type ListSessionsInput, type ListSessionsOutput, type ListWindowsInput, type ListWindowsOutput, type MoveCursorInput, type ParseVisualRegionsInput, type PressKeyInput, type ScrollInput, type SessionOutput, type SessionStateOutput, type SetAgentCursorEnabledInput, type SetAgentCursorMotionInput, type SetAgentCursorThemeInput, type SetWindowFrameInput, type StartSessionInput, type StartSessionOutput, type TypeTextInput, type VerifyStateInput, type VerifyStateOutput, type WindowStateOutput,} from "./cua_driver_contract.js";import { type FfiConverter, type UniffiByteArray, type UniffiGcObject, type UniffiHandle, type UniffiObjectFactory, type UniffiReferenceHolder, type UniffiRustCallStatus, AbstractFfiConverterByteArray, FfiConverterArray, FfiConverterArrayBuffer, FfiConverterBool, FfiConverterInt32, FfiConverterObject, FfiConverterObjectWithCallbacks, FfiConverterOptional, FfiConverterUInt16, FfiConverterUInt32, FfiConverterUInt64, FfiConverterUInt8, RustBuffer, UniffiAbstractObject, UniffiEnum, UniffiError, UniffiInternalError, UniffiResult, UniffiRustCaller, destructorGuardSymbol, pointerLiteralSymbol, uniffiCreateFfiConverterString, uniffiCreateRecord, uniffiRustCallAsync, uniffiTraitInterfaceCall, uniffiTraitInterfaceCallAsyncWithError, uniffiTraitInterfaceCallWithError, uniffiTypeNameSymbol, variantOrdinalSymbol,} from "@ubjs/core";import uniffiCuaDriverContractModule from "./cua_driver_contract.js";-const { FfiConverterTypeActionResult, FfiConverterTypeClickInput, FfiConverterTypeClipboardReadInput, FfiConverterTypeClipboardWriteInput, FfiConverterTypeDragInput, FfiConverterTypeEndSessionInput, FfiConverterTypeEndSessionOutput, FfiConverterTypeEscalateSessionInput, FfiConverterTypeGetAgentCursorStateInput, FfiConverterTypeGetCursorPositionInput, FfiConverterTypeGetDesktopStateInput, FfiConverterTypeGetScreenSizeInput, FfiConverterTypeGetSessionInput, FfiConverterTypeGetSessionStateInput, FfiConverterTypeGetWindowStateInput, FfiConverterTypeHotkeyInput, FfiConverterTypeInvokeMenuInput, FfiConverterTypeListAppsInput, FfiConverterTypeListAppsOutput, FfiConverterTypeListSessionsInput, FfiConverterTypeListSessionsOutput, FfiConverterTypeListWindowsInput, FfiConverterTypeListWindowsOutput, FfiConverterTypeMoveCursorInput, FfiConverterTypePressKeyInput, FfiConverterTypeScrollInput, FfiConverterTypeSessionOutput, FfiConverterTypeSessionStateOutput, FfiConverterTypeSetAgentCursorEnabledInput, FfiConverterTypeSetAgentCursorMotionInput, FfiConverterTypeSetAgentCursorThemeInput, FfiConverterTypeSetWindowFrameInput, FfiConverterTypeStartSessionInput, FfiConverterTypeStartSessionOutput, FfiConverterTypeTypeTextInput, FfiConverterTypeVerifyStateInput, FfiConverterTypeVerifyStateOutput, FfiConverterTypeWindowStateOutput } = uniffiCuaDriverContractModule.converters;+const { FfiConverterTypeActionResult, FfiConverterTypeClickInput, FfiConverterTypeClipboardReadInput, FfiConverterTypeClipboardWriteInput, FfiConverterTypeDragInput, FfiConverterTypeEndSessionInput, FfiConverterTypeEndSessionOutput, FfiConverterTypeEscalateSessionInput, FfiConverterTypeGetAgentCursorStateInput, FfiConverterTypeGetCursorPositionInput, FfiConverterTypeGetDesktopStateInput, FfiConverterTypeGetScreenSizeInput, FfiConverterTypeGetSessionInput, FfiConverterTypeGetSessionStateInput, FfiConverterTypeGetWindowStateInput, FfiConverterTypeHotkeyInput, FfiConverterTypeInvokeMenuInput, FfiConverterTypeListAppsInput, FfiConverterTypeListAppsOutput, FfiConverterTypeListSessionsInput, FfiConverterTypeListSessionsOutput, FfiConverterTypeListWindowsInput, FfiConverterTypeListWindowsOutput, FfiConverterTypeMoveCursorInput, FfiConverterTypeParseVisualRegionsInput, FfiConverterTypePressKeyInput, FfiConverterTypeScrollInput, FfiConverterTypeSessionOutput, FfiConverterTypeSessionStateOutput, FfiConverterTypeSetAgentCursorEnabledInput, FfiConverterTypeSetAgentCursorMotionInput, FfiConverterTypeSetAgentCursorThemeInput, FfiConverterTypeSetWindowFrameInput, FfiConverterTypeStartSessionInput, FfiConverterTypeStartSessionOutput, FfiConverterTypeTypeTextInput, FfiConverterTypeVerifyStateInput, FfiConverterTypeVerifyStateOutput, FfiConverterTypeWindowStateOutput } = uniffiCuaDriverContractModule.converters;const uniffiCaller = new UniffiRustCaller(() => ({ code: 0 }));const uniffiIsDebug =@@ -3813,6 +3813,7 @@ export interface CuaDriverLike {listWindows(input: ListWindowsInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ListWindowsOutput>;metadata(asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<DriverMetadata>;moveCursor(input: MoveCursorInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;+ parseVisualRegions(input: ParseVisualRegionsInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;pressKey(input: PressKeyInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;runtimeScopePrefix(): string | undefined;scroll(input: ScrollInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;@@ -4875,6 +4876,38 @@ private constructor(pointer: UniffiHandle) {}}+ async parseVisualRegions(input: ParseVisualRegionsInput, asyncOpts_?: { signal: AbortSignal }): Promise<ToolResult> /*throws*/ {+ const __stack = uniffiIsDebug ? new Error().stack : undefined;+ try {+ return await uniffiRustCallAsync(+ /*rustCaller:*/ uniffiCaller,+ /*rustFutureFunc:*/ () => {+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriver_parse_visual_regions(+ uniffiTypeCuaDriverObjectFactory.clonePointer(this),FfiConverterTypeParseVisualRegionsInput.lower(input, nativeModule().rustbuffer_alloc)+ );+ },+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_rust_buffer,+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_rust_buffer,+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_rust_buffer,+ // Async returns always go through the JS-side converter: the+ // FFI symbol returns the future handle (u64), and the user-level+ // RustBuffer comes back via the shared `rust_future_complete_*`+ // export. The bytes the runtime hands back must be deserialized+ // here using the per-callable return-type converter.+ /*liftFunc:*/ FfiConverterTypeToolResult.lift.bind(FfiConverterTypeToolResult),+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),+ /*asyncOpts:*/ asyncOpts_,+ /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)+ );+ } catch (__error: any) {+ if (uniffiIsDebug && __error instanceof Error) {+ __error.stack = __stack;+ }+ throw __error;+ }+ }+async pressKey(input: PressKeyInput, asyncOpts_?: { signal: AbortSignal }): Promise<ToolResult> /*throws*/ {const __stack = uniffiIsDebug ? new Error().stack : undefined;try {@@ -5341,6 +5374,7 @@ export interface CuaDriverSessionLike {listSessions(input: ListSessionsInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ListSessionsOutput>;listWindows(input: ListWindowsInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ListWindowsOutput>;moveCursor(input: MoveCursorInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;+ parseVisualRegions(input: ParseVisualRegionsInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;pressKey(input: PressKeyInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;scroll(input: ScrollInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;setAgentCursorEnabled(input: SetAgentCursorEnabledInput, asyncOpts_?: { signal: AbortSignal }) /*throws*/: Promise<ToolResult>;@@ -6027,6 +6061,38 @@ private constructor(pointer: UniffiHandle) {}}+ async parseVisualRegions(input: ParseVisualRegionsInput, asyncOpts_?: { signal: AbortSignal }): Promise<ToolResult> /*throws*/ {+ const __stack = uniffiIsDebug ? new Error().stack : undefined;+ try {+ return await uniffiRustCallAsync(+ /*rustCaller:*/ uniffiCaller,+ /*rustFutureFunc:*/ () => {+ return nativeModule().uniffi_cua_driver_sdk_fn_method_cuadriversession_parse_visual_regions(+ uniffiTypeCuaDriverSessionObjectFactory.clonePointer(this),FfiConverterTypeParseVisualRegionsInput.lower(input, nativeModule().rustbuffer_alloc)+ );+ },+ /*pollFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_poll_rust_buffer,+ /*cancelFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_cancel_rust_buffer,+ /*completeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_complete_rust_buffer,+ /*freeFunc:*/ nativeModule().ffi_cua_driver_sdk_rust_future_free_rust_buffer,+ // Async returns always go through the JS-side converter: the+ // FFI symbol returns the future handle (u64), and the user-level+ // RustBuffer comes back via the shared `rust_future_complete_*`+ // export. The bytes the runtime hands back must be deserialized+ // here using the per-callable return-type converter.+ /*liftFunc:*/ FfiConverterTypeToolResult.lift.bind(FfiConverterTypeToolResult),+ /*liftString:*/ FfiConverterString.lift.bind(FfiConverterString),+ /*asyncOpts:*/ asyncOpts_,+ /*errorHandler:*/ FfiConverterTypeDriverError.lift.bind(FfiConverterTypeDriverError)+ );+ } catch (__error: any) {+ if (uniffiIsDebug && __error instanceof Error) {+ __error.stack = __stack;+ }+ throw __error;+ }+ }+async pressKey(input: PressKeyInput, asyncOpts_?: { signal: AbortSignal }): Promise<ToolResult> /*throws*/ {const __stack = uniffiIsDebug ? new Error().stack : undefined;try {@@ -7665,6 +7731,9 @@ function uniffiEnsureInitialized() {if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriver_move_cursor() !== 18320) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriver_move_cursor");}+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriver_parse_visual_regions() !== 15013) {+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriver_parse_visual_regions");+ }if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriver_press_key() !== 63712) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriver_press_key");}@@ -7764,6 +7833,9 @@ function uniffiEnsureInitialized() {if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriversession_move_cursor() !== 35768) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriversession_move_cursor");}+ if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriversession_parse_visual_regions() !== 31748) {+ throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriversession_parse_visual_regions");+ }if (nativeModule().uniffi_cua_driver_sdk_checksum_method_cuadriversession_press_key() !== 36768) {throw new UniffiInternalError.ApiChecksumMismatch("uniffi_cua_driver_sdk_checksum_method_cuadriversession_press_key");}diff --git a/libs/cua-driver/typescript/test/compatibility-contract.test.mjs b/libs/cua-driver/typescript/test/compatibility-contract.test.mjsindex 0beee1cf7f..8274a09359 100644--- a/libs/cua-driver/typescript/test/compatibility-contract.test.mjs+++ b/libs/cua-driver/typescript/test/compatibility-contract.test.mjs@@ -14,6 +14,15 @@ const fixture = JSON.parse(const normalize = (value) => value.replace(/\s+/g, " ").trim()+// UniFFI tags ClickPosition by declaration order. cua-driver-rs-v0.28.2 released+// 1=Coordinates and 2=Element; new variants may only be appended. The generated+// binding check in CI ties this list back to the Rust declaration order.+const RELEASED_CLICK_POSITION_ORDINALS = [+ [1, "Coordinates"],+ [2, "Element"],+ [3, "CapturedCoordinates"],+]+test("current native-window methods return typed outputs", () => {const declarations = normalize(fs.readFileSync(path.join(packageRoot, "dist", "native", "cua_driver_sdk.d.ts"), "utf8",@@ -28,6 +37,16 @@ test("current native-window methods return typed outputs", () => {}})+test("ClickPosition preserves released UniFFI ordinals", () => {+ const generated = fs.readFileSync(+ path.join(packageRoot, "src", "native", "cua_driver_contract.ts"), "utf8",+ )+ const observed = [+ ...generated.matchAll(/case (\d+): return new ClickPosition\.(\w+)\(/g),+ ].map(([, ordinal, variant]) => [Number(ordinal), variant])+ assert.deepEqual(observed, RELEASED_CLICK_POSITION_ORDINALS)+})+test("released package exports and declarations remain available", () => {const packageJson = JSON.parse(fs.readFileSync(path.join(packageRoot, "package.json"), "utf8"),diff --git a/libs/cua-driver/typescript/test/native-daemon-fixture.mjs b/libs/cua-driver/typescript/test/native-daemon-fixture.mjsindex f31343e355..41851b6b93 100644--- a/libs/cua-driver/typescript/test/native-daemon-fixture.mjs+++ b/libs/cua-driver/typescript/test/native-daemon-fixture.mjs@@ -49,6 +49,18 @@ const server = net.createServer((connection) => {if (request.name === "list_apps") structuredContent = { apps: [{ pid: 42, name: "Editor", running: true, active: false }] }if (request.name === "list_windows") structuredContent = { windows: [{ pid: 42, window_id: 123, app_name: "Editor", title: "Document", bounds: { x: 0, y: 0, width: 800, height: 600 }, is_on_screen: true, z_index: null }] }if (request.name === "get_window_state") structuredContent = { pid: 42, window_id: 123, snapshot_id: "snapshot-1", screenshot_width: 800, screenshot_height: 600, elements: [{ element_index: 0, role: "button", depth: 0, element_token: "fresh-token", label: "Save" }] }+ if (request.name === "parse_visual_regions") structuredContent = {+ schema: "cua.visual_regions_v1",+ capture: {+ capture_id: "capture-123",+ source: { kind: "primary_desktop", display_id: "primary" },+ screenshot: { reference: "sha256:abc", width: 2, height: 2, mime_type: "image/png", sha256: "abc" },+ action_coordinate_space: { kind: "identity" },+ },+ parser: { extension_id: "cua-perception", extension_version: "1.0.0", model_id: "fixture", model_version: "1", runtime: "fixture" },+ regions: [],+ timing: { duration_ms: 1 },+ }if (request.name === "click" && (request.args.element_token === "stale-token" || request.args.target?.window_id === 124)) {isError = truestructuredContent = { code: request.args.element_token === "stale-token" ? "stale_element_token" : "element_target_mismatch" }@@ -67,7 +79,7 @@ const server = net.createServer((connection) => {})}\n`,)completedCalls += 1- if (completedCalls === 8) server.close()+ if (completedCalls === 9) server.close()})})diff --git a/libs/cua-driver/typescript/test/native-loader.test.mjs b/libs/cua-driver/typescript/test/native-loader.test.mjsindex 710a67baa4..ff33fc89c0 100644--- a/libs/cua-driver/typescript/test/native-loader.test.mjs+++ b/libs/cua-driver/typescript/test/native-loader.test.mjs@@ -114,7 +114,7 @@ test(fixture.on("error", reject)fixture.on("message", (message) => {if (message.request) requests.push(message.request)- if (requests.length === 8) resolve(requests)+ if (requests.length === 9) resolve(requests)})}),)@@ -132,6 +132,8 @@ test(ClickButton,ClickInput,CuaDriver,+ ParseVisualRegionsInput,+ ParseVisualRegionsOptions,StatePredicate,VerificationStatus,VerifyStateInput,@@ -168,6 +170,7 @@ test("pressKey","hotkey","verifyState",+ "parseVisualRegions",]assert.equal(expectedMethods.every((name) => typeof driver[name] === "function"),@@ -206,7 +209,7 @@ test(const state = await driver.getWindowState(sdk.GetWindowStateInput.new({pid: 42, windowId: 123n, session: "node-run", query: "Save",includeScreenshot: true, includeAccessibilityTree: true,- maxElements: 10, maxDepth: 3, maxDimension: 800,+ maxElements: 10, maxDepth: 3, maxDimension: 800, maxImageDimension: 1600,}))assert.equal(state.snapshotId, "snapshot-1")assert.equal(state.elements[0].label, "Save")@@ -231,6 +234,12 @@ test(return true})}+ const visualResult = await driver.parseVisualRegions(+ ParseVisualRegionsInput.new({+ captureId: "capture-123",+ options: ParseVisualRegionsOptions.new({}),+ }),+ )await requestsPromisedriver.uniffiDestroy()@@ -241,13 +250,14 @@ test(assert.equal(actionResult.verification, undefined)assert.equal(actionResult.effect, ActionEffect.Unverifiable)assert.equal(actionResult.route, ActionRoute.GlobalInput)+ assert.equal(JSON.parse(visualResult.structuredJson).schema, "cua.visual_regions_v1")assert.equal("verified" in actionResult, false)assert.deepEqual(requests[2].args, {})assert.deepEqual(requests[3].args, { pid: 42, on_screen_only: true })assert.deepEqual(requests[4].args, {pid: 42, window_id: 123, session: "node-run", query: "Save",include_screenshot: true, include_accessibility_tree: true,- max_elements: 10, max_depth: 3, max_dimension: 800,+ max_elements: 10, max_depth: 3, max_dimension: 800, max_image_dimension: 1600,})assert.deepEqual(requests[5].args, {target: { kind: "window", pid: 42, window_id: 123 },@@ -255,6 +265,11 @@ test(})assert.equal(requests[6].args.element_token, "stale-token")assert.equal(requests[7].args.target.window_id, 124)+ assert.equal(requests[8].name, "parse_visual_regions")+ assert.deepEqual(requests[8].args, {+ capture_id: "capture-123",+ options: {},+ })assert.equal(requests[0].name, "verify_state")assert.deepEqual(requests[0].args, {pid: 123,diff --git a/libs/cua-driver/typescript/test/visual-contract.test.mjs b/libs/cua-driver/typescript/test/visual-contract.test.mjsnew file mode 100644index 0000000000..7db0a27e91--- /dev/null+++ b/libs/cua-driver/typescript/test/visual-contract.test.mjs@@ -0,0 +1,140 @@+import assert from "node:assert/strict"+import test from "node:test"++import contractModule, {+ ActionTarget,+ ClickInput,+ ClickPosition,+ InputDeliveryMode,+ ParseVisualRegionsInput,+ ParseVisualRegionsOptions,+ ParseVisualRegionsOutput,+ VisualActionCoordinateSpace,+ VisualCaptureProvenance,+ VisualCaptureSource,+ VisualParseError,+ VisualParseErrorCode,+ VisualParseTiming,+ VisualParseWarning,+ VisualParserMetadata,+ VisualRegion,+ VisualRegionBounds,+ VisualRegionKind,+ VisualScreenshotReference,+} from "../dist/native/cua_driver_contract.js"++const roundTrip = (converter, value) =>+ converter.lift(converter.lower(value, size => new Uint8Array(size)))++test("visual contract records round-trip through generated UniFFI converters", () => {+ contractModule.initialize()++ const input = ParseVisualRegionsInput.create({+ captureId: "capture-1",+ options: ParseVisualRegionsOptions.create({+ kinds: [VisualRegionKind.Text, VisualRegionKind.Icon],+ minConfidence: 0.75,+ maxRegions: 50,+ }),+ })+ assert.deepEqual(+ roundTrip(contractModule.converters.FfiConverterTypeParseVisualRegionsInput, input),+ input,+ )++ const capturedClick = ClickInput.create({+ target: new ActionTarget.Desktop({ displayId: "primary" }),+ position: new ClickPosition.CapturedCoordinates({+ x: 12,+ y: 34,+ captureId: "capture-1",+ }),+ deliveryMode: InputDeliveryMode.Foreground,+ session: undefined,+ button: undefined,+ count: undefined,+ })+ assert.deepEqual(+ roundTrip(contractModule.converters.FfiConverterTypeClickInput, capturedClick),+ capturedClick,+ )++ const output = ParseVisualRegionsOutput.create({+ schema: "cua.visual_regions_v1",+ capture: VisualCaptureProvenance.create({+ captureId: "capture-1",+ source: new VisualCaptureSource.PrimaryDesktop({ displayId: "primary" }),+ screenshot: VisualScreenshotReference.create({+ reference: "sha256:abc123",+ width: 1440,+ height: 900,+ mimeType: "image/png",+ sha256: "abc123",+ }),+ actionCoordinateSpace: new VisualActionCoordinateSpace.Affine({+ m11: 0.5,+ m12: 0.25,+ m21: -0.5,+ m22: 2,+ tx: 10.25,+ ty: 20.75,+ }),+ capturedAt: "2026-09-17T12:00:00Z",+ }),+ parser: VisualParserMetadata.create({+ extensionId: "cua-perception",+ extensionVersion: "1.0.0",+ modelId: "visual-parser",+ modelVersion: "2026-09-17",+ runtime: "local",+ backend: "onnx_runtime_cpu",+ modelSourceRevision: "revision-1",+ modelManifestSha256: "a".repeat(64),+ onnxRuntimeVersion: "1.26.0",+ onnxRuntimeLibrarySha256: "b".repeat(64),+ fixtureSha256: undefined,+ }),+ regions: [VisualRegion.create({+ id: "region-1",+ kind: VisualRegionKind.Text,+ bounds: VisualRegionBounds.create({ x: 11, y: 20, width: 4, height: 3 }),+ text: "Open",+ label: "Open button",+ confidence: 0.99,+ interactive: true,+ parentId: "group-1",+ groupId: "toolbar",+ readingOrder: 1,+ })],+ warnings: [VisualParseWarning.create({+ code: "partial-ocr",+ message: "Some text could not be read",+ detail: "region-2",+ })],+ timing: VisualParseTiming.create({+ durationMs: 18n,+ preprocessMs: 3n,+ inferenceMs: 12n,+ }),+ requestId: "request-1",+ })+ const restored = roundTrip(+ contractModule.converters.FfiConverterTypeParseVisualRegionsOutput,+ output,+ )+ assert.deepEqual(restored, output)+ assert.equal(restored.capture.actionCoordinateSpace.inner.m11, 0.5)+ assert.equal(restored.regions[0].bounds.width, 4)+ assert.equal(restored.warnings[0].detail, "region-2")++ const error = VisualParseError.create({+ code: VisualParseErrorCode.CaptureExpired,+ message: "Capture expired",+ retryable: true,+ detail: "capture-1",+ })+ assert.deepEqual(+ roundTrip(contractModule.converters.FfiConverterTypeVisualParseError, error),+ error,+ )+})diff --git a/libs/python/som/README.md b/libs/python/som/README.mdindex 7355889787..961ae3cd5e 100644--- a/libs/python/som/README.md+++ b/libs/python/som/README.md@@ -77,4 +77,11 @@ for elem in result.elements:## License-MIT License - See LICENSE file for details.+`cua-som` is licensed under AGPL-3.0-or-later. See [LICENSE](LICENSE) for the+complete terms. Its dependencies retain their own licenses. Inspect the exact+resolved Ultralytics dependency version and its notices before redistribution.++By default, `OmniParser` can download model files from Microsoft's separate+`OmniParser-v2.0` model repository. Those downloaded files are not relicensed by+the `cua-som` package. Inspect the license and provenance published with the+exact model revision before use or redistribution.diff --git a/nix/cua-driver/tests/rust-unit.nix b/nix/cua-driver/tests/rust-unit.nixindex 1aef6e580d..3cb0e79a2c 100644--- a/nix/cua-driver/tests/rust-unit.nix+++ b/nix/cua-driver/tests/rust-unit.nix@@ -12,6 +12,9 @@letrustSrc = if sourceSubdir == null then src else "${src}/${sourceSubdir}";+ pythonClosure = pkgs.closureInfo {+ rootPaths = [ pkgs.python3 ];+ };inpkgs.rustPlatform.buildRustPackage {pname = "cua-driver-rust-unit-tests";@@ -38,7 +41,14 @@ pkgs.rustPlatform.buildRustPackage {pkg-configrustPlatform.bindgenHookclang+ python3];+ CUA_TEST_PYTHON = "${pkgs.python3}/bin/python3";+ CUA_TEST_PYTHON_DYNAMIC_LINKER = pkgs.stdenv.cc.bintools.dynamicLinker;+ CUA_TEST_GLIBC_STATIC_LIB = "${pkgs.glibc.static}/lib";+ preCheck = ''+ export CUA_TEST_PYTHON_READ_ROOTS="$(paste -sd: ${pythonClosure}/store-paths)"+ '';buildInputs = with pkgs; [libx11libxidiff --git a/release-please-config.json b/release-please-config.jsonindex dae490aa94..58a913cded 100644--- a/release-please-config.json+++ b/release-please-config.json@@ -6,6 +6,22 @@"draft": true,"force-tag-creation": true,"packages": {+ "libs/cua-driver/rust/crates/cua-perception": {+ "release-type": "simple",+ "component": "cua-perception",+ "package-name": "cua-perception",+ "bump-minor-pre-major": true,+ "version-file": "VERSION",+ "changelog-path": "CHANGELOG.md",+ "skip-github-release": true,+ "extra-files": [+ {+ "type": "toml",+ "path": "Cargo.toml",+ "jsonpath": "$.package.version"+ }+ ]+ },"libs/cua-driver": {"release-type": "simple","component": "cua-driver-rs",@@ -15,8 +31,11 @@"changelog-path": "rust/CHANGELOG.md","exclude-paths": ["libs/cua-driver/docs",+ "libs/cua-driver/examples","libs/cua-driver/python",- "libs/cua-driver/tests"+ "libs/cua-driver/tests",+ "libs/cua-driver/rust/crates/cua-perception",+ "libs/cua-driver/experiments/cua-perception-inference"],"extra-files": [{diff --git a/scripts/ci/README.md b/scripts/ci/README.mdindex 1a1e69ffb6..b713944b68 100644--- a/scripts/ci/README.md+++ b/scripts/ci/README.md@@ -134,6 +134,17 @@ Lume seed, installs the exact committed source, and then delegates to the thinthe optional installed Chrome/Edge browser matrix after the canonical repo-localharness matrix.+Run the canonical logged-in Lume gate directly from Terminal in the disposable+guest; do not install or register a GitHub Actions runner in that guest. After a+successful `run-all.sh --standalone-browser` invocation, bundle the private+artifact directories, calculate their SHA-256 digest, and dispatch+`.github/workflows/e2e-rust-macos.yml` in `lume` mode at the exact candidate SHA+with the harness run ID and digest. That protected `ubuntu-latest` job only+registers the direct result as a machine-readable certification artifact. It+does not execute macOS code or receive the live Jev credential. The separate+protected evidence workflow verifies that exact-SHA registration before exposing+its bounded credential.+The manual `.github/workflows/e2e-rust-macos.yml` workflow first probes a freshGitHub-hosted macOS 26 runner. It records the image, SIP state, desktop session,display geometry, and OCR-verified TextEdit window and display captures for onediff --git a/scripts/ci/windows/verify-user-session.ps1 b/scripts/ci/windows/verify-user-session.ps1index e9161aee16..802fa26d50 100644--- a/scripts/ci/windows/verify-user-session.ps1+++ b/scripts/ci/windows/verify-user-session.ps1@@ -7,5 +7,78 @@ if ($sessionId -eq 0) {throw "The test runner is in Session 0. Start it from the active console/RDP user session."}+Add-Type -TypeDefinition @"+using System;+using System.ComponentModel;+using System.Runtime.InteropServices;+using System.Text;++public static class CuaInteractiveDesktopProbe {+ const int UOI_NAME = 2;+ const uint DESKTOP_READOBJECTS = 0x0001;+ const uint DESKTOP_SWITCHDESKTOP = 0x0100;++ [DllImport("user32.dll", SetLastError = true)]+ static extern IntPtr GetProcessWindowStation();++ [DllImport("kernel32.dll")]+ static extern uint GetCurrentThreadId();++ [DllImport("user32.dll", SetLastError = true)]+ static extern IntPtr GetThreadDesktop(uint threadId);++ [DllImport("user32.dll", SetLastError = true)]+ static extern IntPtr OpenInputDesktop(uint flags, bool inherit, uint access);++ [DllImport("user32.dll", SetLastError = true)]+ static extern bool CloseDesktop(IntPtr desktop);++ [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]+ static extern bool GetUserObjectInformation(+ IntPtr handle, int index, StringBuilder info, int length, out int needed);++ static string Name(IntPtr handle, string kind) {+ if (handle == IntPtr.Zero) {+ throw new Win32Exception(Marshal.GetLastWin32Error(), kind + " handle is null");+ }+ int needed;+ GetUserObjectInformation(handle, UOI_NAME, null, 0, out needed);+ if (needed <= 2) {+ throw new Win32Exception(Marshal.GetLastWin32Error(), kind + " name is unavailable");+ }+ var value = new StringBuilder(needed / 2);+ if (!GetUserObjectInformation(handle, UOI_NAME, value, needed, out needed)) {+ throw new Win32Exception(Marshal.GetLastWin32Error(), kind + " name query failed");+ }+ return value.ToString();+ }++ public static string[] Inspect() {+ var station = Name(GetProcessWindowStation(), "window station");+ var threadDesktop = Name(GetThreadDesktop(GetCurrentThreadId()), "thread desktop");+ var input = OpenInputDesktop(0, false, DESKTOP_READOBJECTS | DESKTOP_SWITCHDESKTOP);+ if (input == IntPtr.Zero) {+ throw new Win32Exception(Marshal.GetLastWin32Error(), "OpenInputDesktop failed");+ }+ try {+ return new [] { station, threadDesktop, Name(input, "input desktop") };+ } finally {+ CloseDesktop(input);+ }+ }+}+"@++$desktopState = [CuaInteractiveDesktopProbe]::Inspect()+$windowStation = $desktopState[0]+$threadDesktop = $desktopState[1]+$inputDesktop = $desktopState[2]+if ($windowStation -ne "WinSta0") {+ throw "The test runner is attached to window station '$windowStation', not interactive WinSta0."+}+if ($threadDesktop -ne $inputDesktop) {+ throw "The test thread desktop '$threadDesktop' is not the active input desktop '$inputDesktop'."+}+$sessionName = if ($env:SESSIONNAME) { $env:SESSIONNAME } else { "unknown" }-Write-Host "Interactive Windows session verified: id=$sessionId name=$sessionName" -ForegroundColor Green+Write-Host "Interactive Windows session verified: id=$sessionId name=$sessionName station=$windowStation desktop=$threadDesktop" -ForegroundColor Green