diff --git a/CHANGELOG.md b/CHANGELOG.md index 31e789b..6fa1bff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,37 @@ # Changelog +## 0.8.0 (unreleased) + +- Mac computers: `validation()` and `extract()` run on a Mac opened with `open({ platform: 'mac', inference: true })`, answered by that Mac's own vision model next to the computer, usually in 2 to 3 seconds, with `engine: 'local'` on the result. They post the computer's `/steps`. They carry no inference charge: you pay the Mac's minutes. A false validation throws `VALIDATION_FAILED` unless `soft`, an answer the model can't confirm or an `extract()` that finds nothing throws `STEP_FAILED` with the model's reason, a Mac without its model answering throws `NOT_AVAILABLE_ON_PLATFORM` (`step_engine_unavailable`) naming the fix, a model busy with another step `SESSION_BUSY` (`step_engine_busy`), and a Linux computer `NOT_AVAILABLE_ON_PLATFORM` before anything is sent. `instruction()` on computers still throws `NOT_AVAILABLE_ON_PLATFORM`, now naming `tap({ target })` and `type({ target }, text)`. +- Mac computers: `inference: true` on a Mac target sends `inference: true` on create, and the computer's `inference` property reads `'ready'`, `'unavailable'` or `'unknown'` from each report (`undefined` without it). A create refused with `inference_not_enabled` (local inference is enabled per organization; ask support@revyl.ai) or `inference_unavailable` (no Mac with a model is up) throws `NOT_AVAILABLE_ON_PLATFORM` with that reason. `inference` on a Linux target throws `INVALID_ARGUMENT`. Leaving it out sends the same create as before. +- Local inference for app sessions: iOS and Web sessions opened with `computer.open()` inside a Mac opened with `inference: true` run their validations, and instructions that are a single tap, on the Mac's model first, with Revyl's hosted model as the fallback for every other step and for answers the Mac's model can't give within 25 seconds. **This is the default inside an inference Mac**; `inference: false` on the target turns it off for that session, and `inference: true` on Android throws `INVALID_ARGUMENT`. It sends `inference: 'local'` on the hosted start. A verdict the Mac's model gives is final. A start Revyl refuses with `computer_local_inference_unavailable` throws `NOT_AVAILABLE_ON_PLATFORM` with that reason and a message naming both fixes; it was reported as `SESSION_BUSY` (HTTP 409) before. Steps the Mac's model answers carry no inference charge, and app sessions inside a computer add no device minutes. +- `extract(text)` on every session reads one value off the screen and returns it in the new `StepResult.value`. On web, iOS and Android it runs on Revyl's agent as the live step `extract`; a session opened with `model` or `agent` throws `INVALID_ARGUMENT`. `StepResult.type` adds `'extract'`, and the new `StepResult.engine` (`'local'` or `'hosted'`) says who answered when Revyl says. `ExtractOptions` and `ComputerInferenceReadiness` are exported. +- Persistent computers: `openPersistent(name, { inference: true })` creates a computer that runs on Macs with their own model on every start; `withoutInference: true` starts a stopped one once without the model, and a backend that doesn't offer it throws `INVALID_ARGUMENT` saying so (it is sent only when true). `savedDiskExpiresAt` on `listPersistent()` and snapshot entries says when a save stops being able to start a computer, when Revyl reports one. `inference_not_enabled` and `inference_unavailable` map as on `open()`. +- Docs: three new guides, [checks on a Mac's own model](packages/verify/docs/guides/mac-model-checks.md), [apps inside an inference Mac](packages/verify/docs/guides/apps-inside-an-inference-mac.md) and [persistent computers and snapshots](packages/verify/docs/guides/persistent-computers.md), with use cases for a dev environment set up once, parallel copies from a snapshot, a browser that stays signed in and a long-running agent workspace. Persistent computers, shipped in 0.7.0 without docs, are now on the computers and API pages. The computers, API, errors and agents pages, the README and llms.txt no longer say validation doesn't run on computers or that there is no snapshot API, and the agents page adds the 30-second recording note. Runnable examples: `examples/mac-inference`, `python/examples/mac_inference.py` and `go/examples/macinference`. + +## Go 0.7.0 (unreleased) + +To be published as the `go/v0.7.0` tag. + +- Computers: `Validation` and `Extract` work on a Mac opened with `verify.Target{Platform: verify.Mac, Inference: new(true)}`, on the Mac's own vision model, as in TypeScript 0.8.0. Results carry `Engine` `"local"`. `s.Inference()` reports the model's readiness as `verify.InferenceReady`, `verify.InferenceUnavailable` or `verify.InferenceUnknown`, refreshed at `Open`, `Attach`, `OpenPersistent` and `Report`, and is `""` on every other session. A step on a Mac opened without inference returns `ErrNotAvailableOnPlatform` with `Reason` `ReasonStepEngineUnavailable` and says to open it with inference. `step_engine_busy` and `screen_control_held` return `ErrSessionBusy`, and an uncertain answer returns `ErrStepFailed`, never a pass. On a Linux computer the steps return `ErrNotAvailableOnPlatform` before sending, and `Inference` on a Linux target returns `ErrInvalidArgument`. A create refused with `inference_not_enabled` or `inference_unavailable` returns `ErrNotAvailableOnPlatform` with `Reason` `ReasonInferenceNotEnabled` or `ReasonInferenceUnavailable`. `Instruction` on a computer still returns `ErrNotAvailableOnPlatform`, and its message now names `Tap(ctx, verify.Element("the Save button"))` and `Type(ctx, verify.Element("the search field"), text)`. +- `Extract(ctx, text, ExtractOptions{Timeout})` on every session reads one value off the screen into the new `StepResult.Value`, as in TypeScript 0.8.0. On web, iOS and Android it runs on Revyl's agent. It returns `ErrStepFailed` when nothing is read, and `ErrInvalidArgument` on a session opened with `WithModel`, `WithCustomModel` or `WithAgent`. The new `StepResult.Engine` (`"local"` or `"hosted"`) says who answered, only when Revyl says. +- iOS and Web sessions that `computer.Open` starts inside a Mac opened with inference run their steps on the Mac's model first, with Revyl's hosted model as the fallback, by default, as in TypeScript 0.8.0. `Inference: new(false)` in the `Target` opts out, and `Inference: new(true)` on Android returns `ErrInvalidArgument`. A start refused with `computer_local_inference_unavailable` returns `ErrNotAvailableOnPlatform` with `Reason` `ReasonComputerLocalInferenceUnavailable`, saying to try again shortly or pass `Inference: new(false)`. +- Persistent computers: `OpenPersistentOptions.Inference` asks for the Mac's model when the call creates the computer, and `WithoutInference` starts a stopped inference computer once without it, as in TypeScript 0.8.0. A backend that doesn't offer `WithoutInference` returns `ErrInvalidArgument` saying so. `PersistentComputer.SavedDiskExpiresAt` and `ComputerSnapshot.SavedDiskExpiresAt` show when a save stops being startable, when Revyl reports an end. +- `go/examples/macinference` runs `Validation` and `Extract` on a Mac opened with inference and, with `IOS_APP_ID` and `IOS_BUILD_ID` set, a soft validation in an iOS session inside it. +- Docs: the README documents `Validation` and `Extract` on a Mac opened with inference, `Extract` with `StepResult.Value` and `Engine` on every session, local inference for iOS and Web sessions inside an inference Mac, billing, and, for the first time, persistent computers and snapshots. It corrects the sentences and the "Which call works where" rows that said `Validation` isn't available on computers, and says that a `Recording` check already under way when the 15 minutes run out can take up to 30 seconds more. +- `verify.Version` and the `User-Agent` report 0.7.0. A call that uses none of these sends the same requests as v0.6.1. + +## Python 0.6.0 (unreleased) + +- Mac computers: `validation()` and `extract()` work on a Mac opened with `open(Target(platform="mac", inference=True))`, as in TypeScript 0.8.0. They run on the Mac's own vision model and return a `StepResult` with `engine="local"`; a false statement raises `VALIDATION_FAILED` unless `soft=True`, and an uncertain answer or nothing read raises `STEP_FAILED`. On a Mac opened without inference they raise `NOT_AVAILABLE_ON_PLATFORM` with `reason="step_engine_unavailable"` and a message saying to open it with inference; on a Linux computer they raise it before anything is sent. A busy model or someone holding the screen in the viewer raises `SESSION_BUSY` (`step_engine_busy`, `screen_control_held`). `instruction()` on computers still raises `NOT_AVAILABLE_ON_PLATFORM`, now naming `tap("the Save button")` and `type("the search field", text)`. +- `Target(..., inference=...)`: on a Mac target, `inference=True` asks for a Mac with its own model. A create refused with `inference_not_enabled` or `inference_unavailable` raises `NOT_AVAILABLE_ON_PLATFORM` with that `reason`, and the message says what to do. `inference=True` on a Linux target raises `INVALID_ARGUMENT`, as does `inference` on a `Target` passed to `open()` for Web, iOS or Android. +- `inference` on `Session` and `AsyncSession` is `"ready"`, `"unavailable"` or `"unknown"` on a Mac opened with inference, refreshed whenever Verify reads the computer's report (`open()`, `attach()`, `open_persistent()`, `report()`), and `None` on every other session, as in TypeScript 0.8.0. The `ComputerInferenceReadiness` type is exported. +- `extract(text)` on every `Session` and `AsyncSession` reads one value off the screen and returns a `StepResult` with `value`, as in TypeScript 0.8.0. On Web, iOS and Android it runs on Revyl's agent; a session opened with `model` or `agent` raises `INVALID_ARGUMENT`. `StepResult` gains `value` (extract steps only) and `engine` (`"local"` or `"hosted"` when Revyl says, else `None`). +- Local inference for app sessions inside an inference Mac, as in TypeScript 0.8.0: iOS and Web sessions from `computer.open()` inside a Mac opened with `inference=True` run their steps on the Mac's model first, with Revyl's hosted model as the fallback, by default. `Target(..., inference=False)` opts one session out; `inference=True` on Android raises `INVALID_ARGUMENT`. A start refused because the Mac's model isn't answering raises `NOT_AVAILABLE_ON_PLATFORM` with `reason="computer_local_inference_unavailable"` and a message saying to try again shortly or pass `inference=False`. +- Persistent computers, as in TypeScript 0.8.0: `open_persistent(name, inference=True)` creates a computer that runs on a Mac with its own model on every start; `without_inference=True` starts a stopped inference computer once without the model, and raises `INVALID_ARGUMENT` on a Revyl backend that doesn't offer it. `inference_not_enabled` and `inference_unavailable` raise `NOT_AVAILABLE_ON_PLATFORM` with that `reason`. `PersistentComputer` and `ComputerSnapshot` gain `saved_disk_expires_at`. +- `revyl_verify.__version__` and the `User-Agent` report 0.6.0. A call that uses none of these sends the same requests as 0.5.1. +- Docs: the README documents `validation()` and `extract()` on a Mac opened with inference, `extract()` on every session, local inference for iOS and Web sessions inside a Mac, what inference costs, and, for the first time, persistent computers and snapshots; the "which call works where" table, the platform table, the Mac `Target` fields, `StepResult` fields and troubleshooting no longer say validations are unavailable on computers, and the recording paragraph says a check already under way when `timeout` runs out can take up to 30 seconds more. New runnable example `python/examples/mac_inference.py`. + ## 0.7.1 (2026-11-25) - Web: `typeFocused()` with no text field focused throws `ACTION_FAILED` with the new reason `no_focused_input` and the message `Nothing was typed: no text field has focus (no_focused_input). Use type({ target: 'the email field' }, text), which taps the field and types into it, or tap the field first.` Revyl answers this with HTTP 409, which 0.7.0 reported as `SESSION_BUSY`, so a script or agent gave up on a call it could fix. Your own model's loop now feeds the message back to the model instead of ending the step, because `ACTION_FAILED` doesn't abort it. A session that really is busy, such as a second step while one runs, still throws `SESSION_BUSY`. diff --git a/README.md b/README.md index f727022..9d8a132 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,7 @@ await session.validation('The welcome screen is shown'); **Typing: one rule on every platform.** To type, call `type({ target: 'Email field' }, text)`: it taps the field you describe and types into it, replacing its text unless you pass `{ clear: false }`. It works the same on Web, iOS, Android and a Mac computer. `typeFocused(text)` types wherever focus already is, without tapping, and only on Web and computers; on Web, when no field has focus it throws `ACTION_FAILED` with reason `no_focused_input` and types nothing. -`doubleTap`, `typeFocused`, `back`, `goHome`, `openUrl`, `launchApp`, `locate` and `screenSize` round them out; [which call works where](#which-call-works-where) shows the platform limits. Early access. Since TypeScript (`@revyl/verify`) 0.4.0, Python (`revyl-verify`) 0.2.0 and Go v0.3.0. `doubleTap`, `longPress`, `drag`, `typeFocused`, `goHome`, and Web keys and modifiers in `pressKey`, are new in TypeScript 0.5.0, Python 0.3.0 and Go v0.4.0. On a Mac computer's screen, `tap` (by point or by description), `screenSize`, `typeFocused` and `pressKey` are new in TypeScript 0.6.0, Python 0.4.0 and Go v0.5.0, and `type` in TypeScript 0.7.1, Python 0.5.1 and Go v0.6.1. The [Python](https://github.com/RevylAI/verify/blob/v0.7.1/python/README.md#exact-actions) and [Go](https://github.com/RevylAI/verify/blob/v0.7.1/go/README.md#exact-actions) READMEs show them with each language's names. The [web](packages/verify/docs/web.md#exact-actions) and [mobile](packages/verify/docs/mobile.md#exact-actions) guides have runnable scripts, and [api.md](packages/verify/docs/api.md#exact-actions) lists every call. +`doubleTap`, `typeFocused`, `back`, `goHome`, `openUrl`, `launchApp`, `locate` and `screenSize` round them out; [which call works where](#which-call-works-where) shows the platform limits. Early access. Since TypeScript (`@revyl/verify`) 0.4.0, Python (`revyl-verify`) 0.2.0 and Go v0.3.0. `doubleTap`, `longPress`, `drag`, `typeFocused`, `goHome`, and Web keys and modifiers in `pressKey`, are new in TypeScript 0.5.0, Python 0.3.0 and Go v0.4.0. On a Mac computer's screen, `tap` (by point or by description), `screenSize`, `typeFocused` and `pressKey` are new in TypeScript 0.6.0, Python 0.4.0 and Go v0.5.0, and `type` in TypeScript 0.7.1, Python 0.5.1 and Go v0.6.1. The [Python](https://github.com/RevylAI/verify/blob/v0.8.0/python/README.md#exact-actions) and [Go](https://github.com/RevylAI/verify/blob/v0.8.0/go/README.md#exact-actions) READMEs show them with each language's names. The [web](packages/verify/docs/web.md#exact-actions) and [mobile](packages/verify/docs/mobile.md#exact-actions) guides have runnable scripts, and [api.md](packages/verify/docs/api.md#exact-actions) lists every call. ## Your own model @@ -76,7 +76,7 @@ await session.instruction('Open Privacy', { model: 'openai/gpt-5.5' }); await open('ios', { model: { id: 'qwen-3.8-27b', baseURL: 'https://api.cerebras.ai/v1', apiKey: process.env.CEREBRAS_API_KEY } }); ``` -Since TypeScript (`@revyl/verify`) 0.4.0, Python (`revyl-verify`) 0.2.0 and Go v0.3.0; the [Python](https://github.com/RevylAI/verify/blob/v0.7.1/python/README.md#your-own-model) and [Go](https://github.com/RevylAI/verify/blob/v0.7.1/go/README.md#your-own-model) READMEs show them with each language's names. Built in: `anthropic`, `openai`, `google`, `openrouter`, `groq`, `cerebras`, `xai` and `ollama`; anything OpenAI-compatible works through `baseURL`. Early access; [Use your own model](packages/verify/docs/own-model.md) covers the providers, picking a model, what Revyl still sees, limits and troubleshooting. +Since TypeScript (`@revyl/verify`) 0.4.0, Python (`revyl-verify`) 0.2.0 and Go v0.3.0; the [Python](https://github.com/RevylAI/verify/blob/v0.8.0/python/README.md#your-own-model) and [Go](https://github.com/RevylAI/verify/blob/v0.8.0/go/README.md#your-own-model) READMEs show them with each language's names. Built in: `anthropic`, `openai`, `google`, `openrouter`, `groq`, `cerebras`, `xai` and `ollama`; anything OpenAI-compatible works through `baseURL`. Early access; [Use your own model](packages/verify/docs/own-model.md) covers the providers, picking a model, what Revyl still sees, limits and troubleshooting. ## Packages @@ -84,7 +84,7 @@ Since TypeScript (`@revyl/verify`) 0.4.0, Python (`revyl-verify`) 0.2.0 and Go v | --- | --- | --- | | [`@revyl/verify`](https://www.npmjs.com/package/@revyl/verify) | `npm install @revyl/verify` | TypeScript SDK and the `verify` CLI (`init`, `login`, `logout`, `whoami`). Published on npm, Node.js 22.18 or later. | | [`revyl-verify`](https://www.npmjs.com/package/revyl-verify) (npm) | `npm install revyl-verify` | Alias of `@revyl/verify` at the same version. | -| [Go module](https://github.com/RevylAI/verify/tree/go/v0.6.1/go) | `go get github.com/RevylAI/verify/go@v0.6.1` | Published as the `go/v0.6.1` tag, Go 1.26.9 or later. Calls return errors instead of throwing. | +| [Go module](https://github.com/RevylAI/verify/tree/go/v0.7.0/go) | `go get github.com/RevylAI/verify/go@v0.7.0` | Published as the `go/v0.7.0` tag, Go 1.26.9 or later. Calls return errors instead of throwing. | | [`revyl-verify`](https://pypi.org/project/revyl-verify/) (PyPI) | `pip install revyl-verify` or `uv add revyl-verify` | Python SDK, published on PyPI. Python 3.10 or later, sync and asyncio APIs, no CLI; see the [Python guide](python/README.md). | ## Platforms @@ -94,7 +94,7 @@ Since TypeScript (`@revyl/verify`) 0.4.0, Python (`revyl-verify`) 0.2.0 and Go v | Web | Yes | Yes | — | Yes | | iOS simulator | Yes | Yes | — | Yes | | Android emulator | Yes | Yes | — | Yes | -| Mac computer | — | Screen: `tap`, `type`, `typeFocused`, `pressKey` | Yes | Yes | +| Mac computer | Validations and `extract` on a Mac opened with `inference: true`; no instructions | Screen: `tap`, `type`, `typeFocused`, `pressKey` | Yes | Yes | ### Which call works where @@ -111,7 +111,8 @@ Since TypeScript (`@revyl/verify`) 0.4.0, Python (`revyl-verify`) 0.2.0 and Go v | `openUrl(url)` | Yes, loads an http(s) URL in the tab | Yes, a URL or deep link | Yes, a URL or deep link | No | | `launchApp(bundleId)` | No, use `openUrl` or `navigate` | Yes | Yes | No | | `navigate(url)` | Yes | No, use `openUrl` | No, use `openUrl` | No | -| `instruction`, `validation`, your own model | Yes | Yes | Yes | No, use `exec()` and the screen calls above | +| `instruction`, your own model | Yes | Yes | Yes | No, use `tap({ target })`, `type({ target }, text)` and `exec()` | +| `validation`, `extract` | Yes | Yes | Yes | Yes, on a Mac opened with `inference: true`, answered by its own model; see the [guide](packages/verify/docs/guides/mac-model-checks.md) | | `screenshot()` | Yes | Yes | Yes | Yes | | `exec`, files, processes | No, open a Mac computer | No, open a Mac computer | No, open a Mac computer | Yes | @@ -123,6 +124,8 @@ Web is available to every organization. Mac computers are available to organizat ## Documentation +Three guides walk through what's new in 0.8.0: [checks on a Mac's own model](packages/verify/docs/guides/mac-model-checks.md), [testing an iOS or Web app inside an inference Mac](packages/verify/docs/guides/apps-inside-an-inference-mac.md), where its steps run on the Mac's model with no inference charge, and [keeping a Mac between runs](packages/verify/docs/guides/persistent-computers.md) with persistent computers and snapshots. Runnable examples are in [examples/mac-inference](examples/mac-inference), [python/examples/mac_inference.py](python/examples/mac_inference.py) and [go/examples/macinference](go/examples/macinference). + The [documentation](packages/verify/docs/) covers the [API](packages/verify/docs/api.md), [configuration](packages/verify/docs/configuration.md), [web](packages/verify/docs/web.md), [mobile](packages/verify/docs/mobile.md), [computers](packages/verify/docs/computers.md), [CI](packages/verify/docs/ci.md), [your own model](packages/verify/docs/own-model.md), [errors and troubleshooting](packages/verify/docs/errors.md), [coding agents](packages/verify/docs/agents.md), and [live end-to-end results](packages/verify/docs/end-to-end.md). The npm package ships these pages in `node_modules/@revyl/verify/docs/`, with an [llms.txt](packages/verify/docs/llms.txt) index, so a coding agent can read the docs for the version you installed. The Revyl docs site has an overview at [docs.revyl.com/verify](https://docs.revyl.com/verify). ## Status diff --git a/examples/agent-platform/README.md b/examples/agent-platform/README.md index c783b85..0cb4d22 100644 --- a/examples/agent-platform/README.md +++ b/examples/agent-platform/README.md @@ -6,7 +6,7 @@ One task fans out to a cloud browser and an iOS simulator through `@revyl/verify You need Node.js **22.18+**, the [Revyl CLI](https://docs.revyl.com/cli), and a Revyl account with web and mobile session access. No Xcode, Android SDK, extra app IDs, or mobile builds are needed. -This checkout uses the local workspace SDK (**0.7.1**). From the repository root, install and build once, before loading any API credentials: +This checkout uses the local workspace SDK (**0.8.0**). From the repository root, install and build once, before loading any API credentials: ```sh npm ci diff --git a/examples/agent-platform/package.json b/examples/agent-platform/package.json index 108d823..ccf04d5 100644 --- a/examples/agent-platform/package.json +++ b/examples/agent-platform/package.json @@ -10,7 +10,7 @@ "typecheck": "tsc -p tsconfig.json" }, "devDependencies": { - "@revyl/verify": "0.7.1", + "@revyl/verify": "0.8.0", "@types/node": "^22.10.0", "typescript": "^5.9.0" } diff --git a/examples/byo-model/package.json b/examples/byo-model/package.json index 127fc3c..943db65 100644 --- a/examples/byo-model/package.json +++ b/examples/byo-model/package.json @@ -10,7 +10,7 @@ "typecheck": "tsc -p tsconfig.json" }, "devDependencies": { - "@revyl/verify": "0.7.1", + "@revyl/verify": "0.8.0", "@types/node": "^22.10.0", "typescript": "^5.9.0" } diff --git a/examples/mac-inference/README.md b/examples/mac-inference/README.md new file mode 100644 index 0000000..3894901 --- /dev/null +++ b/examples/mac-inference/README.md @@ -0,0 +1,14 @@ +# Mac inference example + +Opens a Revyl Mac computer with its own vision model (`inference: true`), checks its screen with `validation()`, and reads the menu bar date with `extract()`. Both run on the Mac's model, so they carry no inference charge; you pay the Mac's minutes. When `IOS_APP_ID` and `IOS_BUILD_ID` name an iOS app and build in Revyl, it also opens that app inside the Mac, where its validation runs on the same model by default, and prints which model answered. It closes everything in `finally`. + +It needs an organization with Mac computers and local inference; ask support@revyl.ai if yours can't open one. To run it: + +```bash +export REVYL_API_KEY=... # or: revyl auth login +export IOS_APP_ID=... IOS_BUILD_ID=... # optional +npm install +node verify/checks.ts +``` + +Running the script starts a paid cloud computer. `npm run typecheck` only compiles it and makes no live requests. See [the Mac model guide](../../packages/verify/docs/guides/mac-model-checks.md) and [apps inside an inference Mac](../../packages/verify/docs/guides/apps-inside-an-inference-mac.md). diff --git a/examples/mac-inference/package.json b/examples/mac-inference/package.json new file mode 100644 index 0000000..61508d3 --- /dev/null +++ b/examples/mac-inference/package.json @@ -0,0 +1,16 @@ +{ + "name": "verify-example-mac-inference", + "version": "0.0.0", + "private": true, + "description": "Verify example: validation and extract on a Mac's own model, and an iOS app inside it", + "type": "module", + "scripts": { + "checks": "node verify/checks.ts", + "typecheck": "tsc -p tsconfig.json" + }, + "devDependencies": { + "@revyl/verify": "0.8.0", + "@types/node": "^22.10.0", + "typescript": "^5.9.0" + } +} diff --git a/examples/mac-inference/tsconfig.json b/examples/mac-inference/tsconfig.json new file mode 100644 index 0000000..97d165f --- /dev/null +++ b/examples/mac-inference/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "erasableSyntaxOnly": true, + "types": ["node"] + }, + "include": ["verify"] +} diff --git a/examples/mac-inference/verify/checks.ts b/examples/mac-inference/verify/checks.ts new file mode 100644 index 0000000..9ed7908 --- /dev/null +++ b/examples/mac-inference/verify/checks.ts @@ -0,0 +1,24 @@ +import { open } from '@revyl/verify'; + +const mac = await open({ platform: 'mac', inference: true }); +try { + console.log("Mac's model:", mac.inference); + const dock = await mac.validation('The Dock is visible at the bottom of the screen'); + console.log('Dock visible:', dock.passed, `(${dock.engine})`); + const date = await mac.extract('the date at the right end of the menu bar'); + console.log('Menu bar date:', date.value, `(${date.engine})`); + + const appId = process.env.IOS_APP_ID; + const buildId = process.env.IOS_BUILD_ID; + if (appId && buildId) { + const app = await mac.open({ platform: 'ios', app: { appId, buildId } }); + try { + const shown = await app.validation("The app's first screen is showing", { soft: true }); + console.log('App first screen:', shown.passed, `(${shown.engine})`); + } finally { + await app.close(); + } + } +} finally { + await mac.close(); +} diff --git a/examples/mac-workspace/README.md b/examples/mac-workspace/README.md index b72ddd4..c60922c 100644 --- a/examples/mac-workspace/README.md +++ b/examples/mac-workspace/README.md @@ -10,4 +10,4 @@ npm install node verify/workspace.ts ``` -Running the script starts a paid cloud computer. `npm run typecheck` only compiles it and makes no live requests. See [computers.md](../../packages/verify/docs/computers.md) for bounds, process handles, screenshots, and failure semantics. Instruction and validation steps are not available on computers. +Running the script starts a paid cloud computer. `npm run typecheck` only compiles it and makes no live requests. See [computers.md](../../packages/verify/docs/computers.md) for bounds, process handles, screenshots, and failure semantics. `instruction()` is not available on computers; `validation()` and `extract()` work on a Mac opened with `inference: true`, as in [mac-inference](../mac-inference). diff --git a/examples/mac-workspace/package.json b/examples/mac-workspace/package.json index cf9ff3e..cc625df 100644 --- a/examples/mac-workspace/package.json +++ b/examples/mac-workspace/package.json @@ -9,7 +9,7 @@ "typecheck": "tsc -p tsconfig.json" }, "devDependencies": { - "@revyl/verify": "0.7.1", + "@revyl/verify": "0.8.0", "@types/node": "^22.10.0", "typescript": "^5.9.0" } diff --git a/examples/mobile-settings/package.json b/examples/mobile-settings/package.json index 59cc98b..f76f3d3 100644 --- a/examples/mobile-settings/package.json +++ b/examples/mobile-settings/package.json @@ -10,7 +10,7 @@ "typecheck": "tsc -p tsconfig.json" }, "devDependencies": { - "@revyl/verify": "0.7.1", + "@revyl/verify": "0.8.0", "@types/node": "^22.10.0", "typescript": "^5.9.0" } diff --git a/examples/web-cdp/package.json b/examples/web-cdp/package.json index 4fad296..c7d3718 100644 --- a/examples/web-cdp/package.json +++ b/examples/web-cdp/package.json @@ -9,7 +9,7 @@ "typecheck": "tsc -p tsconfig.json" }, "devDependencies": { - "@revyl/verify": "0.7.1", + "@revyl/verify": "0.8.0", "@types/node": "^22.10.0", "playwright-core": "^1.65.1", "typescript": "^5.9.0" diff --git a/examples/web-store/package.json b/examples/web-store/package.json index c2729cb..f0c4579 100644 --- a/examples/web-store/package.json +++ b/examples/web-store/package.json @@ -9,7 +9,7 @@ "typecheck": "tsc -p tsconfig.json" }, "devDependencies": { - "@revyl/verify": "0.7.1", + "@revyl/verify": "0.8.0", "@types/node": "^22.10.0", "typescript": "^5.9.0" } diff --git a/go/README.md b/go/README.md index 291dd71..8ccf3d7 100644 --- a/go/README.md +++ b/go/README.md @@ -9,10 +9,10 @@ Use Go 1.26.9 or later and a Revyl account. Set `REVYL_API_KEY` through your she The module lives in the repository's `go/` subdirectory. Install the tagged release with: ```sh -go get github.com/RevylAI/verify/go@v0.6.1 +go get github.com/RevylAI/verify/go@v0.7.0 ``` -Go releases use independent repository tags such as `go/v0.6.1`; npm versions do not version this module. Commit the resulting `go.mod` and `go.sum` in your app to pin dependencies. +Go releases use independent repository tags such as `go/v0.7.0`; npm versions do not version this module. Commit the resulting `go.mod` and `go.sum` in your app to pin dependencies. ## Quick start: iOS Settings @@ -21,7 +21,7 @@ This program opens the iOS Settings app on a cloud simulator, which every accoun ```sh mkdir verify-go && cd verify-go go mod init example.com/verify-go -go get github.com/RevylAI/verify/go@v0.6.1 +go get github.com/RevylAI/verify/go@v0.7.0 ``` Save this as `main.go`: @@ -69,7 +69,7 @@ Run it with `go run .`. It prints `ios: starting ios session ` as soon as ## Core API -Inside a function returning `error`, with `verify "github.com/RevylAI/verify/go"`, `context`, and `time` imported: +Inside a function returning `error`, with `verify "github.com/RevylAI/verify/go"`, `context`, `log`, and `time` imported: ```go s, err := verify.Open(ctx, verify.Target{Platform: verify.Android, BundleID: "com.example.app"}) @@ -87,12 +87,19 @@ if _, err := s.Instruction(ctx, "Open the cart"); err != nil { if _, err := s.Validation(ctx, "The cart shows one item"); err != nil { return err } +total, err := s.Extract(ctx, "the cart total") +if err != nil { + return err +} +log.Println("Total:", total.Value) _, err = s.Screenshot(ctx, "artifacts/cart.png") return err ``` This sketch ignores cleanup errors for brevity; the complete example below reports them. Go has no automatic process-exit cleanup: explicitly close every successful session, including on error. Use a fresh, bounded cleanup context so canceling the work context does not prevent cleanup. `Close` is idempotent. An abrupt process termination cannot run deferred functions. +`Extract(ctx, text)` reads one value off the screen and returns it in `StepResult.Value`. Describe one value that is visible now, such as `"the order number"`. On web, iOS and Android it runs on Revyl's agent, like `Instruction` and `Validation`; on a Mac computer it runs on the Mac's own model and needs a Mac opened with inference (see [Validation and Extract on a Mac](#validation-and-extract-on-a-mac)). When nothing is read, it returns `ErrStepFailed` with the reason: describe a value that is on the screen now. A session opened with `WithModel`, `WithCustomModel` or `WithAgent` returns `ErrInvalidArgument`, because `Extract` runs on Revyl's agent: read the value from `Screenshot` with your model instead. `ExtractOptions{Timeout: time.Minute}` overrides the step timeout. + On web/mobile, `Close` requests a device stop (or cancels startup when no session ID was returned); success acknowledges the request, not confirmed physical release. Computers require confirmed physical release. Concurrent/repeated calls share the first close result, including an error. It does not retry a failed close as a new operation. After connection and any explicit mobile bundle launch, `Open` observes screenshots for up to 10 seconds, bounded by its startup context, looking for distinct RGB pixels in the central 80% of a PNG. This is best-effort blank-frame detection: the runtime has no rendered-readiness signal, and content does not prove that the intended app is foreground or loaded. Exhaustion, unavailable screenshots, and undecodable images produce a debug note through `OpenOptions.Log` and continue; caller cancellation still returns an error and attempts cleanup. Begin with an instruction that waits for the screen your workflow needs. @@ -149,16 +156,16 @@ Run with `go test -v -timeout 6m`. `t.Fatal` runs deferred cleanup. The URL and - **Web:** `Target{Platform: verify.Web, AppID: "…", URL: "https://…"}` registers a deployed HTTPS URL as a web build. Alternatively supply `BuildID`, or omit URL and build ID to select the latest web build on `Branch` (the app's default branch if omitted). `Viewport` accepts `Width`, `Height`, and optional `DeviceScaleFactor`; `SignIn` accepts `Path`, `Secret` (the stored secret's name, never its value), and optional `Persona`. - **iOS and Android:** set `Platform` to `verify.IOS` or `verify.Android` and exactly one of `AppID`, `BuildID`, `ArtifactURL` (HTTPS), or `BundleID` (an app already installed). `DeviceModel` and `OSVersion` are optional and written as Revyl names them, such as `DeviceModel: "iPhone 16", OSVersion: "iOS 18.5"` or `DeviceModel: "Pixel 7", OSVersion: "Android 14"`. A value Revyl doesn't offer returns `ErrInvalidArgument` listing the values it accepts, and no session starts. An `AppID` or `BuildID` Revyl can't find returns `ErrInvalidArgument` naming what wasn't found and how to fix it, and no session starts. A `BundleID` that can't be launched returns `ErrSessionStartFailed` naming the bundle ID, with the session link. `URL`, `Branch`, `Viewport`, and `SignIn` are web-only. -- **Mac computers:** `Target{Platform: verify.Mac}` creates a workspace; only `StartTimeout` is accepted alongside the platform. Mac computers are available to organizations on a current paid Revyl plan. When Revyl says Pro would unlock Macs for a Free-plan organization (`computer_not_enabled` with `unlocks_with_card: true`), `Open` and `OpenPersistent` return `ErrNotAvailableOnPlatform` with `Reason` `ReasonUpgradeRequired`, and the message gives Revyl's upgrade offer and its HTTPS billing link, or says to add a card in Revyl's billing settings when Revyl sends no offer. A 429 `ErrComputerLimit` means queued work or a concurrency limit; Verify does not guess which cause applies or retry creation. See [computer availability](https://github.com/RevylAI/verify/blob/main/packages/verify/docs/computers.md#availability-and-errors). +- **Mac computers:** `Target{Platform: verify.Mac}` creates a workspace; only `StartTimeout`, `Timeout` and `Inference` are accepted alongside the platform. `Inference: new(true)` runs it on a Mac whose own vision model is loaded, so `Validation` and `Extract` work on it; see [Validation and Extract on a Mac](#validation-and-extract-on-a-mac). Mac computers are available to organizations on a current paid Revyl plan. When Revyl says Pro would unlock Macs for a Free-plan organization (`computer_not_enabled` with `unlocks_with_card: true`), `Open` and `OpenPersistent` return `ErrNotAvailableOnPlatform` with `Reason` `ReasonUpgradeRequired`, and the message gives Revyl's upgrade offer and its HTTPS billing link, or says to add a card in Revyl's billing settings when Revyl sends no offer. A 429 `ErrComputerLimit` means queued work or a concurrency limit; Verify does not guess which cause applies or retry creation. See [computer availability](https://github.com/RevylAI/verify/blob/main/packages/verify/docs/computers.md#availability-and-errors). - `Target.StartTimeout` bounds startup (default 10 minutes); on web/mobile, `IdleTimeoutSeconds` sets the session's idle timeout (default 600 seconds). All methods also honor the caller's context. -- `Open` takes at most one `OpenOptions` value, plus `WithModel`, `WithCustomModel` or `WithAgent` to run steps on your own model; `Instruction` and `Validation` take the same options for one step. `OpenOptions{StepTimeout: 3*time.Minute}` changes the default step timeout. Per-call `StepOptions{Timeout: time.Minute}` and `ValidationOptions{Timeout: time.Minute, Soft: true}` override it. Run one step at a time per session. +- `Open` takes at most one `OpenOptions` value, plus `WithModel`, `WithCustomModel` or `WithAgent` to run steps on your own model; `Instruction` and `Validation` take the same options for one step. `OpenOptions{StepTimeout: 3*time.Minute}` changes the default step timeout. Per-call `StepOptions{Timeout: time.Minute}`, `ValidationOptions{Timeout: time.Minute, Soft: true}` and `ExtractOptions{Timeout: time.Minute}` override it. Run one step at a time per session, on computers too. - `OpenOptions{Profile: "signed-in"}` runs a session profile from your project's `.revyl/config.yaml` before `Open` returns; `Profile: "none"` runs no profile. Left empty, the project's `session.default_profile` runs when it sets one. Web, iOS, Android and Mac computers. See [Session profiles](#session-profiles). - Redirects are rejected, not followed with credentials. - `OpenOptions{Log: func(line string) { ... }}` opts into progress lines: `: starting session ` as soon as the session ID exists, before the browser or device is ready, then `ready`, on web, iOS, Android and hosted sessions; computer lifecycle; evidence-gap messages; mobile best-effort first-screen debug notes; and the turns of steps run on your own model. The default is quiet for all targets, so pass `Log: func(line string) { log.Println(line) }` to see the session link while a slow start runs. Keep that callback concurrency-safe if operations run concurrently. A confirmed execution result remains usable when its report evidence is pending or failed; the callback identifies that gap without logging private output or recording URLs. Requests have bounded deadlines even when passed `context.Background()`: ordinary HTTP requests use 30 seconds, device session creation up to 2 minutes, and accepted-step cancellation up to 5 seconds on a fresh context. Ordinary responses are limited to 16 MiB; computer screenshots allow up to 128 MiB of decoded image data. Safe reads and idempotent device build-registration/stop requests retry at most twice on transient failures; session creation, launch, and step/operation submission are never replayed. Caller cancellation remains detectable with `errors.Is(err, context.Canceled)` or `context.DeadlineExceeded`, alongside `verify.ErrTimeout` for device operations; interrupted computer mutation observation returns `verify.ErrActionUncertain`. -The Go SDK does not read `verify.config.ts`, resolve named targets, or provide an init CLI. Every step runs on the live session; there is no cached replay. Instruction and validation methods on computers return `ErrNotAvailableOnPlatform` locally; computer-only methods on web/mobile do the same. +The Go SDK does not read `verify.config.ts`, resolve named targets, or provide an init CLI. Every step runs on the live session; there is no cached replay. `Instruction` on a computer returns `ErrNotAvailableOnPlatform` locally, and its message names `Tap(ctx, verify.Element("the Save button"))` and `Type(ctx, verify.Element("the search field"), text)`. `Validation` and `Extract` work on a Mac opened with `Inference: new(true)`, and return `ErrNotAvailableOnPlatform` locally on a Linux computer. Computer-only methods on web/mobile return `ErrNotAvailableOnPlatform` locally too. ## Session profiles @@ -245,7 +252,9 @@ Neither errors nor logs contain the script's content or output. Check the code w | `LaunchApp` | No, use `OpenURL` or `Navigate` | Yes | Yes | No | | `Navigate` | Yes | No, use `OpenURL` | No, use `OpenURL` | No | | `CDP`, for chromedp, Playwright and Puppeteer | Yes, see [CDP](#cdp-playwright-puppeteer) | No | No | No | -| `Instruction`, `Validation`, your own model | Yes | Yes | Yes | No, use `Exec` and the screen calls above | +| `Instruction` | Yes | Yes | Yes | No, use `Tap(ctx, verify.Element("the Save button"))` and `Type(ctx, verify.Element("the search field"), text)` | +| `Validation`, `Extract` | Yes | Yes | Yes | Yes, on a Mac opened with `Inference: new(true)`; see [Validation and Extract on a Mac](#validation-and-extract-on-a-mac) | +| Your own model (`WithModel`, `WithCustomModel`, `WithAgent`) | Yes, except `Extract` | Yes, except `Extract` | Yes, except `Extract` | No | | `Screenshot` | Yes | Yes | Yes | Yes | | `Exec`, files, processes | No, open a Mac computer | No, open a Mac computer | No, open a Mac computer | Yes | @@ -537,7 +546,7 @@ To attach without taking ownership, set `stop := false` and pass `verify.OpenOpt Call `computer.Open(ctx, target)` to start a web, iOS, or Android app session inside that computer, rather than on an unrelated worker. It reuses the computer's credentials, backend, viewer, HTTP client, step timeout, and log callback. Both `AppID` and `BuildID` must be exact Revyl UUIDs. Hosted targets cannot select `URL`, `Branch`, `ArtifactURL`, `BundleID`, `DeviceModel`, or `OSVersion`. Web targets allow `Viewport`, `SignIn`, `IdleTimeoutSeconds`, and `StartTimeout`; native targets allow the two timeouts and always request simulation. -Mac computers can host web and iOS. This is a client-side compatibility limit, not a capacity guarantee: the server can refuse any hosted start. +Mac computers can host web and iOS. This is a client-side compatibility limit, not a capacity guarantee: the server can refuse any hosted start. Inside a Mac opened with inference, the session's steps run on the Mac's model first; see [iOS and Web sessions inside an inference Mac](#ios-and-web-sessions-inside-an-inference-mac). Inside a function returning `error`, with a computer ID and existing app/build UUIDs supplied by your caller: @@ -567,7 +576,7 @@ _, err = browser.Validation(ctx, "The Swag Labs login form is shown") return err ``` -Select an existing HTTPS web build for startup. Leave out `StopOnClose` only for a computer your program owns. `Navigate` can also reach a guest-local HTTP service, but only one already listening there, such as one an earlier step of a `revyl-macos` job started: Verify has no call that starts one, and a process started through `Exec` ends when the command returns. `Navigate(ctx, url)` is web-only and submits `open_url` once, without retries. HTTP and HTTPS URLs of up to 2048 characters are accepted, including localhost; credentials, whitespace, control characters, backslashes, and invalid ports are rejected. On a hosted child, localhost refers to its parent computer; on an ordinary cloud web session, it refers to that web runtime, not your computer or another Revyl computer. A cold development server may need a warm-up request before navigation succeeds. If navigation returns `ACTION_UNCERTAIN`, the request may still commit; re-navigating is the caller's choice. The runtime is responsible for enforcing its navigation network policy. It checks the success envelope and returns only an error, without logging the URL. Hosted sessions reuse `Instruction`, `Validation`, `Screenshot`, and `Close`. +Select an existing HTTPS web build for startup. Leave out `StopOnClose` only for a computer your program owns. `Navigate` can also reach a guest-local HTTP service, but only one already listening there, such as one an earlier step of a `revyl-macos` job started: Verify has no call that starts one, and a process started through `Exec` ends when the command returns. `Navigate(ctx, url)` is web-only and submits `open_url` once, without retries. HTTP and HTTPS URLs of up to 2048 characters are accepted, including localhost; credentials, whitespace, control characters, backslashes, and invalid ports are rejected. On a hosted child, localhost refers to its parent computer; on an ordinary cloud web session, it refers to that web runtime, not your computer or another Revyl computer. A cold development server may need a warm-up request before navigation succeeds. If navigation returns `ACTION_UNCERTAIN`, the request may still commit; re-navigating is the caller's choice. The runtime is responsible for enforcing its navigation network policy. It checks the success envelope and returns only an error, without logging the URL. Hosted sessions reuse `Instruction`, `Validation`, `Extract`, `Screenshot`, and `Close`. Each hosted start gets a distinct preallocated session ID and is never replayed. Ambiguous startup failures attempt cleanup of that child ID; definite refusals do not. Child startup failure never stops the parent. Parent close prevents new child opens and cancels in-flight startup. It spends at most five seconds total waiting for startup cleanup and closing children, or half the caller's remaining deadline if shorter, then requests parent stop with the remaining budget. Prompt child cleanup finishes before parent stop; slow child cleanup cannot consume the whole stop budget. The server's parent stop also stops its children. Confirmed physical parent release completes cleanup even if a child stop failed; the optional log callback reports that failure without response content. Otherwise cleanup errors remain observable. Child readiness is bounded by both `StartTimeout` and the computer's remaining lifetime; older computer reports without an expiry cannot host sessions. Child worker operations also honor the parent's expiry and close cancellation; cleanup and reports remain available afterward. Explicitly closing a child does not close its parent. @@ -642,7 +651,7 @@ if err != nil { } ``` -Revyl saves the video a few seconds after release, so `Recording` asks every 5 seconds until it is saved and returns `*ComputerRecording{URL, Duration, StartedAt}` without downloading the video; `Duration` and `StartedAt` are nullable pointers. It returns `(nil, nil)` only when none was saved within 15 minutes or before `ctx`'s deadline, and `ctx.Err()` when `ctx` is canceled. Since `v0.6.1`; earlier versions returned `(nil, nil)` at once while the video was still uploading. On a computer that is still running it returns `ErrSessionBusy` saying to call `Close` first. `Attach` can't reopen a closed computer, so a later process can't fetch it. Signed recording URLs last up to one hour, are private, and are never logged; call `Recording` again to refresh metadata rather than retaining an expired URL. +Revyl saves the video a few seconds after release, so `Recording` asks every 5 seconds until it is saved and returns `*ComputerRecording{URL, Duration, StartedAt}` without downloading the video; `Duration` and `StartedAt` are nullable pointers. It returns `(nil, nil)` only when none was saved within 15 minutes or before `ctx`'s deadline, and `ctx.Err()` when `ctx` is canceled. A check already under way when the 15 minutes run out can take up to 30 seconds more. Since `v0.6.1`; earlier versions returned `(nil, nil)` at once while the video was still uploading. On a computer that is still running it returns `ErrSessionBusy` saying to call `Close` first. `Attach` can't reopen a closed computer, so a later process can't fetch it. Signed recording URLs last up to one hour, are private, and are never logged; call `Recording` again to refresh metadata rather than retaining an expired URL. ## Mac screen @@ -673,9 +682,168 @@ if _, err := s.Tap(ctx, verify.Point{X: 400, Y: 300}); err != nil { // or click On a computer, as everywhere, type with `Type(ctx, verify.Element("description"), text)`: it clicks the field, selects its text with Command+A unless `Clear` points to `false`, and types. `TypeFocused` needs `Clear` pointing to `false`: it types where the cursor is and clears nothing, so to replace text, select it first. `ModifierMeta` is Command and `ModifierAlt` is Option. `ScreenSize` works too. `Tap(ctx, verify.Element("the Help menu in the menu bar"))` clicks a description and returns the `Point` it clicked. It takes several seconds and can click a look-alike, or something else when the target isn't on the screen, so check the point or take a screenshot afterwards, and use a `verify.Point` from a screenshot for anything that's hard to undo. `Locate` and the exact actions other than `Tap`, `Type`, `TypeFocused`, `PressKey` and `ScreenSize` aren't available on computers and return `ErrNotAvailableOnPlatform` before anything is sent. When Revyl answers `screen_starting`, nothing happened, so Verify waits and tries again for up to 30 seconds. A program keeps control of the screen for 120 seconds after its last action, so a teammate can't take control in the Revyl viewer until then; while someone does control it there, actions return `ErrSessionBusy` and nothing happens. A 403 returns `ErrAuthRejected`: the key's owner needs the Member role or above, and CI runner keys can't control the screen yet. Revyl's `screen_input_uncertain` returns `ErrActionUncertain`, so take a screenshot before you act again. [computers.md](https://github.com/RevylAI/verify/blob/main/packages/verify/docs/computers.md#screen) lists every screen error. +## Validation and Extract on a Mac + +Since `v0.7.0`. On a Mac computer opened with `Inference: new(true)`, `Validation` and `Extract` run on the Mac's own vision model, next to the computer. A typical answer takes 1.3 to 3 seconds. Local inference is enabled per organization: ask support@revyl.ai. Inside a function returning `error`, with `verify`, `context`, `log` and `time` imported: + +```go +mac, err := verify.Open(ctx, verify.Target{Platform: verify.Mac, Inference: new(true)}) +if err != nil { + return err +} +defer func() { + cleanup, cancel := context.WithTimeout(context.Background(), 310*time.Second) + defer cancel() + _ = mac.Close(cleanup) +}() +log.Println("Model:", mac.Inference()) // verify.InferenceReady, InferenceUnavailable or InferenceUnknown +if _, err := mac.Validation(ctx, "The Dock is visible at the bottom of the screen"); err != nil { + return err +} +date, err := mac.Extract(ctx, "the date at the right end of the menu bar") +if err != nil { + return err +} +log.Println(date.Value, date.Engine) // Engine is "local": the Mac's model answered +``` + +- `Validation` returns a `StepResult` with `Passed` and `Engine` `"local"`. A false statement returns `ErrValidationFailed`, unless you pass `ValidationOptions{Soft: true}`, which returns `Passed` false without an error. +- `Extract` returns the string it read in `StepResult.Value`. Describe one value that is visible now, such as `"the date at the right end of the menu bar"`. +- An answer the model can't confirm is never a pass: it returns `ErrStepFailed`. So does an `Extract` that finds nothing, with the model's reason in the message, such as `local_model_found_no_value`. Describe one thing that is visible on the screen now. +- `Instruction` is still not available on computers. It returns `ErrNotAvailableOnPlatform`, and the message points to `Tap(ctx, verify.Element("the Save button"))` and `Type(ctx, verify.Element("the search field"), text)`. +- Run one step at a time per computer: the Mac's model is shared with the app sessions inside it. +- `mac.Inference()` says whether the Mac's model answers: `verify.InferenceReady`, `verify.InferenceUnavailable`, or `verify.InferenceUnknown` when it can't be told yet. Verify refreshes it whenever it reads the computer's report: at `Open`, `Attach` and `OpenPersistent`, and on each `Report(ctx)`. It is `""` on every other session. + +| Error | When | What to do | +| --- | --- | --- | +| `ErrNotAvailableOnPlatform`, `Reason` `ReasonInferenceNotEnabled` | `Open` with `Inference: new(true)`, and the organization doesn't have local inference (HTTP 403) | Ask support@revyl.ai to turn it on, or open the Mac without `Inference` | +| `ErrNotAvailableOnPlatform`, `Reason` `ReasonInferenceUnavailable` | No Mac with a model is up right now (HTTP 409). Nothing was started | Try again later, or open the Mac without `Inference` | +| `ErrNotAvailableOnPlatform`, `Reason` `ReasonStepEngineUnavailable` | A step on a Mac opened without inference, or on a Linux computer (returned before anything is sent), or the Mac's model isn't answering | Open a Mac with `Inference: new(true)` (a persistent computer gets it only when it is created; see [Persistent computers and snapshots](#persistent-computers-and-snapshots)). If it was opened with inference, check `Inference()` and try again shortly | +| `ErrInvalidArgument` | `Inference: new(true)` on a Linux target | Open a Mac instead | +| `ErrSessionBusy` (`step_engine_busy`) | The Mac's model was busy with another step for too long | Run one step at a time per computer, and try again in a few seconds | +| `ErrSessionBusy` (`screen_control_held`) | Someone controls the screen in the Revyl viewer | Try again after they release it; control frees itself after 2 minutes without input | +| `ErrStepFailed` | The model wasn't sure, or `Extract` read nothing | Describe one thing that is visible on the screen now | + +[examples/macinference](examples/macinference/main.go) runs all of this, and the iOS session below: `cd go && go run ./examples/macinference`, with `IOS_APP_ID` and `IOS_BUILD_ID` set to also open your iOS app inside the Mac. It starts a real, billable Mac computer. The [Mac model checks guide](https://github.com/RevylAI/verify/blob/main/packages/verify/docs/guides/mac-model-checks.md) has more examples. + +### iOS and Web sessions inside an inference Mac + +`mac.Open(ctx, target)` with an iOS or Web target, inside a Mac opened with inference, runs that session's steps on the Mac's model first, with Revyl's hosted model as the fallback. This is the default for every iOS and Web session opened inside an inference Mac. To run a session's steps only on the hosted model, pass `Inference: new(false)` in its `Target`. Macs host iOS and Web sessions only, so `Inference: new(true)` on an Android target returns `ErrInvalidArgument`, as does `Inference` on a target passed to `verify.Open` for a browser or device. + +```go +app, err := mac.Open(ctx, verify.Target{Platform: verify.IOS, AppID: appID, BuildID: buildID}) // local inference by default +if err != nil { + return err +} +step, err := app.Validation(ctx, "The app's first screen is showing", verify.ValidationOptions{Soft: true}) +if err != nil { + return err +} +log.Println(step.Passed, step.Engine) // "local" when the Mac's model answered, "hosted" when Revyl's did +``` + +- **Runs on the Mac's model:** validations, and instructions that are a single plain tap on one thing. +- **Goes to the hosted model:** `Extract`, typing, multi-step instructions such as "scroll down and then tap back", and any local answer that is uncertain or slower than 25 seconds. +- `StepResult.Engine` says who answered each step: `"local"` or `"hosted"`. +- Local verdicts are final: a validation the Mac's model answers is not checked again by the hosted model. +- If the Mac's model isn't answering when the session starts, the start is refused with `ErrNotAvailableOnPlatform` and `Reason` `ReasonComputerLocalInferenceUnavailable`. Try again shortly, or pass `Inference: new(false)` to run the session on the hosted model. + +The [apps inside an inference Mac guide](https://github.com/RevylAI/verify/blob/main/packages/verify/docs/guides/apps-inside-an-inference-mac.md) covers this in more depth. + +### Billing + +- Steps on a computer have no per-step fee. `Validation` and `Extract` on a Mac computer run only on the Mac's own model, so they carry no inference charge; you pay the Mac's minutes, as for any computer. +- App sessions inside a computer add no device minutes of their own. +- Inside an inference Mac, steps the Mac's model answers carry no inference charge; steps that fall back to Revyl's hosted model are billed as usual. +- Local inference is enabled per organization: ask support@revyl.ai. + +## Persistent computers and snapshots + +Since `v0.6.0`. A persistent computer is a Mac whose disk outlives every stop, so tools you install and files you write are there the next time you open it. macOS only. Persistent computers are enabled per organization: without them, `OpenPersistent` and `SaveSnapshot` return `ErrNotAvailableOnPlatform` with `Reason` `ReasonPersistentComputersNotEnabled`; ask support@revyl.ai to turn them on. The [persistent computers guide](https://github.com/RevylAI/verify/blob/main/packages/verify/docs/guides/persistent-computers.md) walks through a full workflow. + +```go +package main + +import ( + "context" + "errors" + "fmt" + "log" + "time" + + verify "github.com/RevylAI/verify/go" +) + +func main() { + if err := run(); err != nil { + log.Fatal(err) + } +} + +func run() (err error) { + ctx := context.Background() + mac, err := verify.OpenPersistent(ctx, "build-cache") + if err != nil { + return err + } + defer func() { + cleanup, cancel := context.WithTimeout(context.Background(), 10*time.Minute) + defer cancel() + err = errors.Join(err, mac.Close(cleanup)) // stops it and keeps the disk + }() + if mac.Created { + if err := mac.WriteFile(ctx, "created-at.txt", []byte(time.Now().Format(time.RFC3339))); err != nil { + return err + } + } + data, err := mac.ReadFile(ctx, "created-at.txt") // still there on every later run + if err != nil { + return err + } + fmt.Printf("created by this run: %v, created at: %s\n", mac.Created, data) + return nil +} +``` + +- **Open, close, reopen.** `OpenPersistent(ctx, name)` opens the Mac with that name, creating it if needed; `Created` says whether this call created it. A stopped one boots from its disk, and a running one is connected to. It has every method of a Mac from `Open`. Names are 1-64 letters, digits, `.`, `_` or `-`, starting with a letter or digit, and not a UUID; the same name opens the same computer from Go, TypeScript and Python. An ID from `ListPersistent` works too. `Close` stops it and keeps the whole disk; it returns once the disk is saved on its Mac, which can take a few minutes. Go doesn't stop it when your program exits, so always `Close` it. +- **What's kept.** Everything on the disk: files, installed tools, repositories, build products, simulators, app data, system settings, the login keychain and browser profiles. Memory and running processes are not kept: the next open is a cold boot, so start your servers again. +- **Runs.** Each open is a new run with the usual computer lifetime: 2 hours by default, up to 24 hours with `OpenPersistentOptions{Timeout: 8 * time.Hour}`. A run starts saving its disk 3 minutes before it ends, and reaching the end keeps the disk. A running persistent computer bills like any computer. `OpenPersistent` waits up to `StartTimeout` (15 minutes by default) for it to be ready. +- **Snapshots.** `SaveSnapshot(ctx, computer, name)` saves a stopped computer's disk under a name that is unique in your organization. The computer must be stopped: `Close` it first, or `SaveSnapshot` returns `ErrSessionBusy`. It waits until the save is copied off its Mac, about 5 minutes after `Close`, for up to `SaveSnapshotOptions{WaitTimeout}` (15 minutes by default), then returns `ErrTimeout`. +- **Copies.** `OpenPersistent(ctx, newName, verify.OpenPersistentOptions{FromSnapshot: name})` creates a new persistent computer whose disk starts as the snapshot's. `FromSnapshot` is used only when the call creates the computer. A copy gets the same disk, but things tied to the original Mac's hardware identity (Apple Account, iCloud, Safari's saved passwords) don't carry over, and websites may open signed out. Starting on a different Mac than the one holding the save, as most copies do, restores the disk first and can take several minutes. +- **Inference.** `OpenPersistentOptions{Inference: true}` is used only when the call creates the computer, which keeps it for every later start. A copy made with `FromSnapshot` doesn't inherit it, so pass `Inference: true` there too. `WithoutInference: true` is used only when starting a stopped computer created with inference: it starts that one run without the model, for when no Mac with one is up. A Revyl backend that doesn't offer it returns `ErrInvalidArgument` saying so. +- **Saved-disk expiry.** Saves are kept until you delete the computer or snapshot. Some saves have an end: `PersistentComputer.SavedDiskExpiresAt` and `ComputerSnapshot.SavedDiskExpiresAt` show it when Revyl reports one, and are zero otherwise. From then on it can't start, and `OpenPersistent` returns `ErrSessionStartFailed` (`saved_disk_expired` or `snapshot_expired`). +- **Limits.** 10 persistent computers and 100 snapshots per organization, unless Revyl raised them. Past that, `ErrComputerLimit` (`persistent_computer_limit` or `snapshot_limit`): delete one you no longer need, then try again. +- **Cleanup.** `DeletePersistent(ctx, nameOrID)` deletes the computer and its disk for good; a running one stops first, without saving, and its snapshots stay. `DeleteSnapshot(ctx, nameOrID)` deletes a snapshot; computers made from it keep their disks. +- **Lists.** `ListPersistent(ctx)` lists your organization's persistent computers by ID, because Revyl stores no names: compare with the `ID()` of a session `OpenPersistent` returned. `ListSnapshots(ctx)` lists snapshots. +- **Busy or unavailable.** `ErrSessionBusy` (`run_conflict`) means the last run hasn't finished stopping: its disk is kept, so try again in a few minutes. `ErrSessionStartFailed` (`saved_disk_unavailable`) means the Mac holding the save is offline or no Mac can start it right now: the disk is kept, so try again later. + +After the program above has closed `build-cache`, inside a function returning `error`: + +```go +if _, err := verify.SaveSnapshot(ctx, "build-cache", "build-cache-v1"); err != nil { // waits about 5 minutes after Close + return err +} +clone, err := verify.OpenPersistent(ctx, "build-cache-copy", verify.OpenPersistentOptions{FromSnapshot: "build-cache-v1"}) +if err != nil { + return err +} +if err := clone.Close(ctx); err != nil { // stops it and keeps its disk + return err +} +computers, err := verify.ListPersistent(ctx) // IDs, stopped computers included +if err != nil { + return err +} +log.Println(len(computers), "persistent computers") +if err := verify.DeletePersistent(ctx, "build-cache-copy"); err != nil { // the computer and its disk, for good + return err +} +return verify.DeleteSnapshot(ctx, "build-cache-v1") +``` + ## Results and errors -`Instruction` and `Validation` return `StepResult{Type, Text, Reason, Passed, Duration, Model}`; `Model` is set only when the step ran on your own model. Failed instructions return `ErrInstructionFailed`; failed validation verdicts return `ErrValidationFailed`. `Soft: true` returns a false verdict without an error, but a missing verdict, failed execution, or cancellation still returns an error such as `ErrStepFailed`. `Screenshot` returns PNG bytes and optionally writes a path, creating parent directories. +`Instruction`, `Validation` and `Extract` return `StepResult{Type, Text, Passed, Value, Reason, Duration, Engine, Model}`. `Value` is what `Extract` read, on `Extract` steps only. `Engine` is who answered, only when Revyl says: `"local"` for the Mac's own model, `"hosted"` for Revyl's hosted model, and empty on ordinary sessions. `Model` is set only when the step ran on your own model. Failed instructions return `ErrInstructionFailed`; failed validation verdicts return `ErrValidationFailed`; an `Extract` that reads nothing returns `ErrStepFailed`. `Soft: true` returns a false verdict without an error, but a missing verdict, failed execution, or cancellation still returns an error such as `ErrStepFailed`. `Screenshot` returns PNG bytes and optionally writes a path, creating parent directories. Errors support `errors.Is(err, verify.ErrTimeout)` and `errors.As(err, &sdkError)` where `var sdkError *verify.Error`. Stable codes distinguish invalid arguments/configuration, missing/rejected credentials, startup failure, ended/busy sessions, unavailable operations, action failure/uncertainty, step failure, model failure (`ErrModelError`) and a missing model key (`ErrModelKeyMissing`), and timeout. `Error.Cause` is available through `errors.Unwrap` when present. Do not replay mutations after `ErrActionUncertain`: the action may already have happened. Inspect the session in Revyl instead. @@ -685,7 +853,7 @@ Errors support `errors.Is(err, verify.ErrTimeout)` and `errors.As(err, &sdkError Credentials resolve from `REVYL_API_KEY`, then `~/.revyl/credentials.json`. A usable CLI login marked `local_auth_override` takes precedence over the environment key, matching the TypeScript SDK and Revyl CLI. Expired access tokens fall back to a stored API key. Never put keys, tokens, or private session content in source, fixtures, or logs. -Instruction and validation text is sent to Revyl for remote processing, unless the step runs on your own model. The Go SDK does not log that text locally; do not include credentials or sensitive content in step descriptions. +Instruction, validation and extract text is sent to Revyl for processing, on Revyl's hosted model or a Revyl Mac's own model, unless the step runs on your own model. The Go SDK does not log that text locally; do not include credentials or sensitive content in step descriptions. ## Develop diff --git a/go/client.go b/go/client.go index 0a4dfb5..bc6a49f 100644 --- a/go/client.go +++ b/go/client.go @@ -19,7 +19,7 @@ import ( const ( backendURL = "https://backend.revyl.ai" appURL = "https://app.revyl.ai" - Version = "0.6.1" + Version = "0.7.0" ) type client struct { diff --git a/go/computer.go b/go/computer.go index 3faff41..3c39c78 100644 --- a/go/computer.go +++ b/go/computer.go @@ -95,6 +95,30 @@ type ComputerRecording struct { StartedAt *time.Time } +// ComputerInferenceReadiness is whether a Mac computer opened with Inference has its own vision model answering. +type ComputerInferenceReadiness string + +const ( + InferenceReady ComputerInferenceReadiness = "ready" + InferenceUnavailable ComputerInferenceReadiness = "unavailable" + InferenceUnknown ComputerInferenceReadiness = "unknown" +) + +// Inference is, on a Mac computer opened with Inference set to true, whether its own vision model answered when Verify +// last read the computer's report (at Open, Attach and OpenPersistent, and on each Report): InferenceReady answers now, +// InferenceUnavailable doesn't, InferenceUnknown can't be told yet. It is empty on every other session. +func (s *Session) Inference() ComputerInferenceReadiness { + s.mu.Lock() + defer s.mu.Unlock() + if !s.inference { + return "" + } + if s.inferenceReadiness == "" { + return InferenceUnknown + } + return s.inferenceReadiness +} + type computerReport struct { ID string `json:"computer_session_id"` OS string `json:"os"` @@ -103,6 +127,7 @@ type computerReport struct { FailureReason string `json:"failure_reason"` ExpiresAt *time.Time `json:"expires_at"` SessionProfile json.RawMessage `json:"session_profile"` + Inference string `json:"inference"` } type processHandle struct { @@ -137,7 +162,7 @@ func startComputer(ctx context.Context, c *client, viewer string, target Target, return nil, failure(ErrAPI, "Could not generate a computer session ID.") } lifetime, stop := context.WithCancel(context.Background()) - s := &Session{client: c, id: id, platform: target.Platform, viewer: viewer + "/sessions/" + url.PathEscape(id) + "?kind=computer", viewerBase: viewer, lifetime: lifetime, stopLifetime: stop, log: options.Log, stepTimeout: options.StepTimeout, profile: profile, startTimeout: target.StartTimeout} + s := &Session{client: c, id: id, platform: target.Platform, viewer: viewer + "/sessions/" + url.PathEscape(id) + "?kind=computer", viewerBase: viewer, lifetime: lifetime, stopLifetime: stop, log: options.Log, stepTimeout: options.StepTimeout, profile: profile, startTimeout: target.StartTimeout, inference: target.Inference != nil && *target.Inference} s.logLine("starting " + string(s.platform) + " computer " + s.viewer) computerOS := "macos" if target.Platform == Linux { @@ -149,6 +174,9 @@ func startComputer(ctx context.Context, c *client, viewer string, target Target, if target.Timeout != 0 { request["timeout_seconds"] = int64(target.Timeout / time.Second) } + if s.inference { + request["inference"] = true + } profile.addTo(request) r, err := withRepositoryRetry(ctx, func() (response, error) { return s.computerRequest(ctx, "POST", "", request) }) if err != nil { @@ -237,10 +265,83 @@ const ( const computerScreenCalls = "For the screen, use Screenshot, Tap with a Point or an Element, Type with an Element, TypeFocused with Clear set to false, and PressKey; for commands, use Exec." +const computerNoModel = "Validation and Extract on a computer run on the vision model of the Mac it runs on, so open it with " + macInferenceOpen + ". A persistent computer gets the model only when it is created: verify.OpenPersistent(ctx, newName, verify.OpenPersistentOptions{Inference: true})." + func (s *Session) computerAgentUnavailable(method string) error { return failure(ErrNotAvailableOnPlatform, method+" is not available on computers. "+computerScreenCalls+" See "+s.viewer) } +func (s *Session) computerStep(ctx context.Context, kind, text string, timeout time.Duration, ownModel bool) (StepResult, error) { + if err := s.assertComputerOpen(); err != nil { + return StepResult{}, err + } + name := "Validation" + if kind == "extract" { + name = "Extract" + } + if strings.TrimSpace(text) == "" || textLength(text) > 2000 { + return StepResult{}, failure(ErrInvalidArgument, name+" on a computer takes a description of 1 to 2000 characters.") + } + if ownModel { + return StepResult{}, failure(ErrNotAvailableOnPlatform, "Your own model runs steps on browsers and devices, not on computers. Leave out WithModel, WithCustomModel and WithAgent; "+name+" on a Mac runs on the Mac's own vision model.") + } + if timeout == 0 { + timeout = s.stepTimeout + } + if timeout < time.Second { + return StepResult{}, failure(ErrInvalidArgument, "Step timeout must be at least one second.") + } + if s.platform != Mac { + return StepResult{}, &Error{Code: ErrNotAvailableOnPlatform, Reason: ReasonStepEngineUnavailable, Message: name + " is not available on Linux computers: " + computerNoModel + " " + computerScreenCalls} + } + description := strings.TrimSpace(text) + started := time.Now() + stepCtx, cancel := s.computerContext(ctx, started.Add(timeout)) + defer cancel() + r, err := s.computerRequestTimeout(stepCtx, "POST", "/steps", map[string]string{"step_type": kind, "description": description}, timeout) + if err != nil { + if openErr := s.assertComputerOpen(); openErr != nil { + return StepResult{}, openErr + } + if ctx.Err() == nil && stepCtx.Err() != nil { + return StepResult{}, &Error{Code: ErrTimeout, Message: fmt.Sprintf("The %s did not finish within %d ms: \"%s\". Pass a larger Timeout. See %s", kind, timeout.Milliseconds(), description, s.viewer), Cause: err} + } + return StepResult{}, err + } + var raw struct { + StepType string `json:"step_type"` + Status string `json:"status"` + Reason *string `json:"status_reason"` + Validation *bool `json:"validation_result"` + Extracted *struct { + Information *string `json:"information"` + } `json:"extracted_data"` + Engine string `json:"engine"` + } + if decode(r, &raw) != nil || raw.StepType != kind || (raw.Status != "passed" && raw.Status != "failed" && raw.Status != "uncertain") || (raw.Engine != "local" && raw.Engine != "hosted") { + return StepResult{}, invalidComputerResponse() + } + reason := "" + if raw.Reason != nil { + reason = *raw.Reason + } + var value *string + if raw.Extracted != nil { + value = raw.Extracted.Information + } + if raw.Status == "uncertain" || (kind == "validation" && raw.Validation == nil) || (kind == "extract" && (raw.Status != "passed" || value == nil)) { + if kind == "validation" { + return StepResult{}, failure(ErrStepFailed, "Validation did not reach a verdict: \""+description+"\". "+reasonPrefix(reason)+"The Mac's model wasn't sure; describe one thing that is visible on the screen now. See "+s.viewer) + } + return StepResult{}, failure(ErrStepFailed, "Extract read nothing: \""+description+"\". "+reasonPrefix(reason)+"Describe one value that is on the screen now, such as \"the version number in the About window\". See "+s.viewer) + } + result := StepResult{Type: kind, Text: description, Passed: kind == "extract" || *raw.Validation, Reason: reason, Duration: time.Since(started), Engine: raw.Engine} + if kind == "extract" { + result.Value = *value + } + return result, nil +} + func computerLocateUnavailable() error { return failure(ErrNotAvailableOnPlatform, "Locate isn't available on computers, because Revyl can't find a point there without clicking it. Tap with a verify.Element clicks a description and returns the point it clicked; to choose the point yourself, read it off Screenshot and pass it to Tap(ctx, verify.Point{X: x, Y: y}).") } @@ -479,6 +580,12 @@ func (s *Session) readComputerReport(r response) (computerReport, error) { } switch report.State { case "starting", "active", "closing", "stopped", "failed", "owner_lost": + switch readiness := ComputerInferenceReadiness(report.Inference); readiness { + case InferenceReady, InferenceUnavailable, InferenceUnknown: + s.mu.Lock() + s.inference, s.inferenceReadiness = true, readiness + s.mu.Unlock() + } return report, nil default: return report, invalidComputerResponse() @@ -597,6 +704,29 @@ func (s *Session) computerRequestTimeout(ctx context.Context, method, suffix str } return r, &Error{Code: ErrNotAvailableOnPlatform, Reason: ReasonLifetimeUnsupported, HTTPStatus: r.status, Message: "No host can keep this computer running that long (lifetime_unsupported); pass " + fix + "."} } + if suffix == "" && method == "POST" && detail == "inference_not_enabled" { + return r, &Error{Code: ErrNotAvailableOnPlatform, Reason: ReasonInferenceNotEnabled, HTTPStatus: r.status, Message: "Local inference isn't enabled for this API key's organization (inference_not_enabled). Ask support@revyl.ai to turn it on, or open the Mac without inference: verify.Open(ctx, verify.Target{Platform: verify.Mac})."} + } + if suffix == "" && method == "POST" && detail == "inference_unavailable" { + return r, &Error{Code: ErrNotAvailableOnPlatform, Reason: ReasonInferenceUnavailable, HTTPStatus: r.status, Message: "No Mac with its own vision model is up to take this computer right now (inference_unavailable), so nothing was started. Try again later, or open the Mac without inference: verify.Open(ctx, verify.Target{Platform: verify.Mac})."} + } + if suffix == "/steps" { + switch detail { + case "step_engine_unavailable": + s.mu.Lock() + inference := s.inference + s.mu.Unlock() + message := "This computer has no vision model of its own (step_engine_unavailable), so the step didn't run. " + computerNoModel + " To click or type by description on any Mac, use Tap and Type with a verify.Element. See " + s.viewer + if inference { + message = "This Mac's own vision model isn't answering right now (step_engine_unavailable), so the step didn't run. computer.Inference() shows whether it is ready; try again shortly. See " + s.viewer + } + return r, &Error{Code: ErrNotAvailableOnPlatform, Reason: ReasonStepEngineUnavailable, HTTPStatus: r.status, Message: message} + case "step_engine_busy": + return r, responseFailure(r, ErrSessionBusy, "This Mac's vision model is busy with another step (step_engine_busy), so the step didn't run. Run one step at a time on a computer, and try again in a few seconds. See "+s.viewer) + case "screen_control_held": + return r, responseFailure(r, ErrSessionBusy, "The step didn't run: someone else is controlling this computer's screen in the viewer (screen_control_held). Try again after they release it; control frees itself after 2 minutes without input. See "+s.viewer) + } + } if r.status == 409 && detail == "extend_unsupported" { return r, responseFailure(r, ErrNotAvailableOnPlatform, "This computer's host can't extend its lifetime (extend_unsupported); its expiry is unchanged. See "+s.viewer) } @@ -652,7 +782,7 @@ func (s *Session) computerRequestTimeout(ctx context.Context, method, suffix str } reason := fmt.Sprintf("HTTP %d", r.status) switch detail { - case "computer_not_enabled", "run_closed", "inaccessible", "invalid_handle", "operation_not_found", "owner_unavailable", "invalid_request", "unauthenticated", "forbidden", "runtime_unavailable", "start_failed", "computer_limit", "request_conflict", "run_conflict", "evidence_conflict", "evidence_unavailable", "authentication_unavailable", "operation_limit", "screen_starting", "screen_unavailable", "screen_control_held", "screen_control_lost", "screen_input_unavailable", "screen_input_uncertain", "screen_key_unsupported", "screen_text_unsupported", "screen_target_not_found", "screen_target_unavailable": + case "computer_not_enabled", "run_closed", "inaccessible", "invalid_handle", "operation_not_found", "owner_unavailable", "invalid_request", "unauthenticated", "forbidden", "runtime_unavailable", "start_failed", "computer_limit", "request_conflict", "run_conflict", "evidence_conflict", "evidence_unavailable", "authentication_unavailable", "operation_limit", "screen_starting", "screen_unavailable", "screen_control_held", "screen_control_lost", "screen_input_unavailable", "screen_input_uncertain", "screen_key_unsupported", "screen_text_unsupported", "screen_target_not_found", "screen_target_unavailable", "step_engine_unavailable", "step_engine_busy", "inference_unavailable", "inference_not_enabled": reason = detail } next := computerRefusalNextSteps[code] diff --git a/go/computer_test.go b/go/computer_test.go index da4a59a..7211c71 100644 --- a/go/computer_test.go +++ b/go/computer_test.go @@ -346,7 +346,13 @@ func operationResult(result map[string]any) map[string]any { } func TestComputerLifecycleAndExec(t *testing.T) { - f := newComputerFake(t, nil) + f := newComputerFake(t, func(f *fakeRevyl, w http.ResponseWriter, r *http.Request, body map[string]any) bool { + if r.Method != "POST" || !strings.HasSuffix(r.URL.Path, "/steps") { + return false + } + writeJSON(w, 409, map[string]any{"detail": "step_engine_unavailable"}) + return true + }) s := f.open(verify.Target{Platform: verify.Mac}) create := f.calls("POST", computerPath) if len(create) != 1 || !reflectMaps(create[0].Body, map[string]any{"computer_session_id": s.ID(), "os": "macos"}) { diff --git a/go/errors.go b/go/errors.go index e8a60df..4a765e7 100644 --- a/go/errors.go +++ b/go/errors.go @@ -47,6 +47,11 @@ const ( ReasonLifetimeUnsupported RefusalReason = "lifetime_unsupported" ReasonUpgradeRequired RefusalReason = "upgrade_required" ReasonNoFocusedInput RefusalReason = "no_focused_input" + + ReasonComputerLocalInferenceUnavailable RefusalReason = "computer_local_inference_unavailable" + ReasonInferenceNotEnabled RefusalReason = "inference_not_enabled" + ReasonInferenceUnavailable RefusalReason = "inference_unavailable" + ReasonStepEngineUnavailable RefusalReason = "step_engine_unavailable" ) func (c Code) Error() string { return string(c) } @@ -134,7 +139,7 @@ func refusalReason(r response) RefusalReason { ReasonComputerAtCapacity, ReasonComputerPlatformAtCapacity, ReasonComputerNotRunning, ReasonComputerCannotHostPlatform, ReasonComputerNotFound, ReasonWebBuildRequired, ReasonWebBuildNotSupported, ReasonIOSBuildRequired, ReasonIOSBuildNotSupported, ReasonAndroidBuildRequired, ReasonAndroidBuildNotSupported, ReasonWebSessionConflict, ReasonIOSSessionConflict, - ReasonAndroidSessionConflict, ReasonNotAvailableOnPlatform, ReasonRequestTimeout, ReasonProtocolError: + ReasonAndroidSessionConflict, ReasonNotAvailableOnPlatform, ReasonRequestTimeout, ReasonProtocolError, ReasonComputerLocalInferenceUnavailable: return reason } } diff --git a/go/examples/cdp/go.mod b/go/examples/cdp/go.mod index 5dd426d..b71fcb1 100644 --- a/go/examples/cdp/go.mod +++ b/go/examples/cdp/go.mod @@ -3,7 +3,7 @@ module github.com/RevylAI/verify/go/examples/cdp go 1.26.9 require ( - github.com/RevylAI/verify/go v0.6.1 + github.com/RevylAI/verify/go v0.7.0 github.com/chromedp/cdproto v0.160.1 github.com/chromedp/chromedp v0.24.0 ) diff --git a/go/examples/macinference/main.go b/go/examples/macinference/main.go new file mode 100644 index 0000000..e36a2fd --- /dev/null +++ b/go/examples/macinference/main.go @@ -0,0 +1,71 @@ +// Command macinference checks a Mac computer's screen with the Mac's own vision model: it opens a Mac with +// inference, prints whether the model is ready, runs a validation and an extract on the Mac's screen and, when +// IOS_APP_ID and IOS_BUILD_ID are set, opens that iOS app inside the Mac, where its steps run on the same model first. +// +// cd go && go run ./examples/macinference +// +// It needs REVYL_API_KEY (or a saved Revyl login) and an organization with Mac computers and local inference (ask +// support@revyl.ai). It starts a real, billable Mac computer. +package main + +import ( + "context" + "errors" + "fmt" + "log" + "os" + "time" + + verify "github.com/RevylAI/verify/go" +) + +func main() { + if err := run(); err != nil { + log.Fatal(err) + } +} + +func run() (err error) { + ctx := context.Background() + mac, err := verify.Open(ctx, verify.Target{Platform: verify.Mac, Inference: new(true)}, + verify.OpenOptions{Log: func(line string) { log.Println(line) }}) + if err != nil { + return err + } + defer func() { + cleanup, cancel := context.WithTimeout(context.Background(), 310*time.Second) + defer cancel() + err = errors.Join(err, mac.Close(cleanup)) + }() + log.Println("Watch:", mac.ViewerURL()) + fmt.Println("Mac model:", mac.Inference()) + if _, err := mac.Validation(ctx, "The Dock is visible at the bottom of the screen"); err != nil { + return err + } + date, err := mac.Extract(ctx, "the date at the right end of the menu bar") + if err != nil { + return err + } + fmt.Printf("Menu bar date: %q (engine %s)\n", date.Value, date.Engine) + + appID, buildID := os.Getenv("IOS_APP_ID"), os.Getenv("IOS_BUILD_ID") + if appID == "" || buildID == "" { + fmt.Println("Set IOS_APP_ID and IOS_BUILD_ID to also open your iOS app inside this Mac.") + return nil + } + app, err := mac.Open(ctx, verify.Target{Platform: verify.IOS, AppID: appID, BuildID: buildID}) + if err != nil { + return err + } + defer func() { + cleanup, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + err = errors.Join(err, app.Close(cleanup)) + }() + step, err := app.Validation(ctx, "The app's first screen is showing", verify.ValidationOptions{Soft: true}) + if err != nil { + return err + } + fmt.Printf("First screen showing: %v (engine %s)\n", step.Passed, step.Engine) + return nil +} diff --git a/go/hosted.go b/go/hosted.go index 8fba0dc..8c8ddc0 100644 --- a/go/hosted.go +++ b/go/hosted.go @@ -110,6 +110,7 @@ func (s *Session) Open(ctx context.Context, target Target) (*Session, error) { return nil, failure(ErrSessionEnded, "The computer was closed or expired.") } s.childOpens.Add(1) + parentInference := s.inference s.mu.Unlock() defer s.childOpens.Done() ctx, cancel := context.WithTimeout(ctx, target.StartTimeout) @@ -145,16 +146,23 @@ func (s *Session) Open(ctx context.Context, target Target) (*Session, error) { } else { request["is_simulation"] = true } + inference := parentInference && target.Platform != Android + if target.Inference != nil { + inference = *target.Inference + } + if inference { + request["inference"] = "local" + } r, err := s.client.send(ctx, http.MethodPost, "/api/v1/execution/start_device", request, false, 2*time.Minute, false) reason := refusalReason(r) if err == nil && ((r.status >= 400 && r.status < 500 && r.status != 408) || (r.status == 503 && reason != "" && reason != ReasonRequestTimeout && reason != ReasonProtocolError)) { - return nil, hostedStartError(r) + return nil, hostedStartError(r, target.Platform, parentInference) } s.mu.Lock() s.children = append(s.children, child) s.mu.Unlock() if err == nil && (r.status < 200 || r.status >= 300) { - err = hostedStartError(r) + err = hostedStartError(r, target.Platform, parentInference) } if err == nil { var start struct { @@ -198,9 +206,16 @@ func (s *Session) Open(ctx context.Context, target Target) (*Session, error) { return child, nil } -func hostedStartError(r response) error { +func hostedStartError(r response, platform Platform, parentInference bool) error { code := ErrAPI reason := refusalReason(r) + if reason == ReasonComputerLocalInferenceUnavailable { + fix := "Open the computer with " + macInferenceOpen + " to use its model, or" + if parentInference { + fix = "It was opened with Inference set to true but its Mac's model isn't answering now (computer.Inference() shows it); try again shortly, or" + } + return &Error{Code: ErrNotAvailableOnPlatform, Reason: reason, HTTPStatus: r.status, Message: fmt.Sprintf("Revyl refused the %s session's local inference (computer_local_inference_unavailable): the hosting computer has no vision model answering. %s pass Inference: new(false) in the Target you give computer.Open to run this session's steps on Revyl's hosted model.", platform, fix)} + } switch { case r.status == 401 || r.status == 403: code = ErrAuthRejected diff --git a/go/persistent.go b/go/persistent.go index 3af029d..06ba2c3 100644 --- a/go/persistent.go +++ b/go/persistent.go @@ -38,6 +38,8 @@ var persistentRefusals = map[string]struct { "saved_disk_expired": {ErrSessionStartFailed, "This computer's saved disk has reached its end and can't start again (saved_disk_expired). Delete it with DeletePersistent; OpenPersistent with its name then creates a new one."}, "snapshot_expired": {ErrSessionStartFailed, "This snapshot's saved disk has reached its end and can't start a computer (snapshot_expired). Save a new snapshot of a recently stopped computer."}, "computer_not_persistent": {ErrInvalidArgument, "This ID names a computer that isn't persistent (computer_not_persistent). Pass a name, or an ID from ListPersistent."}, + "inference_not_enabled": {ErrNotAvailableOnPlatform, "Local inference isn't enabled for this API key's organization (inference_not_enabled). Ask support@revyl.ai to turn it on, or leave out Inference."}, + "inference_unavailable": {ErrNotAvailableOnPlatform, "No Mac with its own vision model is up to take this computer right now (inference_unavailable), so nothing was started. Try again later; to start an existing computer without the model this once, set WithoutInference to true."}, "run_conflict": {ErrSessionBusy, "The computer's last run hasn't finished stopping (run_conflict). Its disk is kept; try again in a few minutes."}, } @@ -61,6 +63,13 @@ type OpenPersistentOptions struct { // from 1 minute to 24 hours, otherwise ErrInvalidArgument. Zero means 2 hours. Not applied when the computer // was already running. Same as Target.Timeout for Open. Timeout time.Duration + // Inference is used only when this call creates the computer: run it on Macs whose own vision model is loaded, as + // Target.Inference does for Open, so Validation and Extract work on it. The computer keeps this for every later start. + Inference bool + // WithoutInference is used only when this call starts a stopped computer that was created with Inference: start this + // run on any Mac, without the model, for when no Mac with one is up. Later starts ask for the model again. Needs a + // Revyl backend that offers it. + WithoutInference bool // StartTimeout is how long OpenPersistent waits for the computer to be ready, from 10 seconds to 30 minutes. // Zero means 15 minutes. It covers waiting for an earlier stop to finish saving, and a start from a snapshot, // which takes about 3 minutes. @@ -108,6 +117,9 @@ type PersistentComputer struct { // waits for it. SavedOffHost bool CreatedAt time.Time + // SavedDiskExpiresAt is when its current save stops being startable, if Revyl reports an end; zero otherwise. After + // it, OpenPersistent returns ErrSessionStartFailed (saved_disk_expired). + SavedDiskExpiresAt time.Time } // ComputerSnapshot is a saved disk that OpenPersistent can start a new computer from. @@ -119,6 +131,9 @@ type ComputerSnapshot struct { SavedAt time.Time // ExpiresAt is when the save stops being usable; zero when it has no end. ExpiresAt time.Time + // SavedDiskExpiresAt is when a computer can no longer be created from it, if Revyl reports an end; zero otherwise. + // After it, OpenPersistent with FromSnapshot returns ErrSessionStartFailed (snapshot_expired). + SavedDiskExpiresAt time.Time } // OpenPersistent opens the persistent Mac with this name, creating it if it doesn't exist, starting it if it is @@ -290,10 +305,20 @@ func openPersistent(ctx context.Context, name string, options OpenPersistentOpti } var body any create := map[string]any{"computer_session_id": id, "os": "macos", "persistent": true} + start := map[string]any{} if options.Timeout != 0 { - body = map[string]any{"timeout_seconds": int64(options.Timeout / time.Second)} + start["timeout_seconds"] = int64(options.Timeout / time.Second) create["timeout_seconds"] = int64(options.Timeout / time.Second) } + if options.WithoutInference { + start["without_inference"] = true + } + if len(start) > 0 { + body = start + } + if options.Inference { + create["inference"] = true + } started, attempted := false, false err = func() error { var r response @@ -316,11 +341,17 @@ func openPersistent(ctx context.Context, name string, options OpenPersistentOpti if options.FromSnapshot != "" { s.logLine("already exists, so FromSnapshot " + options.FromSnapshot + " was not used") } + if options.Inference { + s.logLine("already exists, so Inference was not changed; a computer keeps the inference it was created with") + } waiting := false for status.State == "stopping" || status.State == "stopped" { if status.State == "stopped" { attempted = true r, err := persistentCall(ctx, c, "POST", persistentBase+"/"+id+"/start", body, true, "", "run_conflict") + if err != nil && options.WithoutInference && errors.Is(err, ErrInvalidArgument) && persistentRefusals[persistentDetail(r)].code == "" { + return &Error{Code: ErrInvalidArgument, HTTPStatus: r.status, Message: "This Revyl backend refused WithoutInference, which it does not offer yet. Leave it out to start the computer as it was created.", Cause: err} + } if err != nil { return err } @@ -680,8 +711,9 @@ func persistentCall(ctx context.Context, c *client, method, path string, body an } if known, ok := persistentRefusals[detail]; ok { var reason RefusalReason - if detail == string(ReasonPersistentComputersNotEnabled) { - reason = ReasonPersistentComputersNotEnabled + switch RefusalReason(detail) { + case ReasonPersistentComputersNotEnabled, ReasonInferenceNotEnabled, ReasonInferenceUnavailable: + reason = RefusalReason(detail) } return r, &Error{Code: known.code, Reason: reason, HTTPStatus: r.status, Message: known.message} } @@ -740,11 +772,12 @@ func checkComputerReference(value, call string) error { } type persistentStatusJSON struct { - ComputerID string `json:"computer_id"` - State string `json:"state"` - SavedAt *time.Time `json:"saved_at"` - Durable *bool `json:"durable"` - CreatedAt time.Time `json:"created_at"` + ComputerID string `json:"computer_id"` + State string `json:"state"` + SavedAt *time.Time `json:"saved_at"` + Durable *bool `json:"durable"` + CreatedAt time.Time `json:"created_at"` + SavedDiskExpiresAt *time.Time `json:"saved_disk_expires_at"` } func decodePersistentDetail(body []byte) (*PersistentComputer, error) { @@ -778,16 +811,20 @@ func decodePersistentComputer(raw []byte) (PersistentComputer, error) { if status.SavedAt != nil { computer.SavedAt = *status.SavedAt } + if status.SavedDiskExpiresAt != nil { + computer.SavedDiskExpiresAt = *status.SavedDiskExpiresAt + } return computer, nil } func decodeSnapshot(raw []byte) (ComputerSnapshot, error) { var snapshot struct { - ID string `json:"id"` - Name string `json:"name"` - ComputerID string `json:"computer_id"` - SavedAt time.Time `json:"saved_at"` - ExpiresAt *time.Time `json:"expires_at"` + ID string `json:"id"` + Name string `json:"name"` + ComputerID string `json:"computer_id"` + SavedAt time.Time `json:"saved_at"` + ExpiresAt *time.Time `json:"expires_at"` + SavedDiskExpiresAt *time.Time `json:"saved_disk_expires_at"` } if json.Unmarshal(raw, &snapshot) != nil || !uuidPattern.MatchString(snapshot.ID) || !uuidPattern.MatchString(snapshot.ComputerID) || snapshot.Name == "" || snapshot.SavedAt.IsZero() { return ComputerSnapshot{}, invalidPersistentResponse() @@ -796,6 +833,9 @@ func decodeSnapshot(raw []byte) (ComputerSnapshot, error) { if snapshot.ExpiresAt != nil { result.ExpiresAt = *snapshot.ExpiresAt } + if snapshot.SavedDiskExpiresAt != nil { + result.SavedDiskExpiresAt = *snapshot.SavedDiskExpiresAt + } return result, nil } diff --git a/go/session.go b/go/session.go index a04e0c2..a1a7591 100644 --- a/go/session.go +++ b/go/session.go @@ -41,6 +41,7 @@ type StepOption interface{ stepOption() } type ValidationOption interface{ validationOption() } type StepOptions struct{ Timeout time.Duration } +type ExtractOptions struct{ Timeout time.Duration } type ValidationOptions struct { Timeout time.Duration Soft bool @@ -51,11 +52,16 @@ func (StepOptions) stepOption() {} func (ValidationOptions) validationOption() {} type StepResult struct { - Type string - Text string - Passed bool + Type string + Text string + Passed bool + // Value is what Extract read off the screen. Extract steps only. + Value string Reason string Duration time.Duration + // Engine is who answered, when Revyl says: "local" is the vision model on the Revyl computer the step ran on or + // inside (a Mac opened with Inference), "hosted" is Revyl's hosted model. Empty when Revyl doesn't say. + Engine string // Model is set when the step ran on your own model: its name, grounding, turns and token use. Model *ModelRun } @@ -88,6 +94,8 @@ type Session struct { profile *sessionProfilePlan startTimeout time.Duration persistentName string + inference bool + inferenceReadiness ComputerInferenceReadiness } func (s *Session) ID() string { return s.id } diff --git a/go/step.go b/go/step.go index 1313778..291b0d0 100644 --- a/go/step.go +++ b/go/step.go @@ -20,12 +20,16 @@ type liveStep struct { Reason string `json:"status_reason"` Reasoning string `json:"reasoning"` Validation *bool `json:"validation_result"` + Extracted *struct { + Information *string `json:"information"` + } `json:"extracted_data"` + Engine string `json:"engine"` } `json:"step_output"` } func (s *Session) Instruction(ctx context.Context, text string, options ...StepOption) (StepResult, error) { if s.platform.computer() { - return StepResult{}, s.computerAgentUnavailable("Instruction") + return StepResult{}, failure(ErrNotAvailableOnPlatform, "Instruction is not available on computers. To click one thing by its description, use Tap(ctx, verify.Element(\"the Save button\")); to type into a field, use Type(ctx, verify.Element(\"the search field\"), text). Validation and Extract do work on a Mac opened with Inference set to true. See "+s.viewer) } settings, agent, err := splitOptions[StepOptions](options, "Instruction") if err != nil { @@ -45,10 +49,9 @@ func (s *Session) Instruction(ctx context.Context, text string, options ...StepO return result, err } +// Validation asks whether something holds on screen, and returns ErrValidationFailed when it does not, unless Soft is +// set. On a Mac computer it runs on the Mac's own vision model and needs one opened with Inference set to true. func (s *Session) Validation(ctx context.Context, text string, options ...ValidationOption) (StepResult, error) { - if s.platform.computer() { - return StepResult{}, s.computerAgentUnavailable("Validation") - } settings, agent, err := splitOptions[ValidationOptions](options, "Validation") if err != nil { return StepResult{}, err @@ -60,6 +63,13 @@ func (s *Session) Validation(ctx context.Context, text string, options ...Valida if len(settings) == 1 { opt = settings[0] } + if s.platform.computer() { + result, err := s.computerStep(ctx, "validation", text, opt.Timeout, agent != nil) + if err == nil && !result.Passed && !opt.Soft { + err = failure(ErrValidationFailed, "Validation failed: \""+result.Text+"\". "+reasonPrefix(result.Reason)+"See "+s.viewer) + } + return result, err + } result, err := s.step(ctx, "validation", text, opt.Timeout, agent) if err == nil && !result.Passed && !opt.Soft { err = failure(ErrValidationFailed, "Validation failed: \""+result.Text+"\". "+stepReason(result)+" See "+s.viewer) @@ -67,6 +77,32 @@ func (s *Session) Validation(ctx context.Context, text string, options ...Valida return result, err } +// Extract reads a value off the screen, such as "the order number", and returns the step with it in Value. It returns +// ErrStepFailed when nothing could be read. On browsers and devices it runs on Revyl's agent, so a session opened with +// your own model returns ErrInvalidArgument; on a Mac computer it runs on the Mac's own vision model and needs one +// opened with Inference set to true. +func (s *Session) Extract(ctx context.Context, text string, options ...ExtractOptions) (StepResult, error) { + if len(options) > 1 { + return StepResult{}, failure(ErrInvalidArgument, "Extract accepts at most one options value.") + } + var timeout time.Duration + if len(options) == 1 { + timeout = options[0].Timeout + } + if s.platform.computer() { + return s.computerStep(ctx, "extract", text, timeout, false) + } + return s.step(ctx, "extract", text, timeout, nil) +} + +func reasonPrefix(reason string) string { + reason = strings.TrimRight(reason, ". \t\r\n") + if reason == "" { + return "" + } + return reason + ". " +} + func stepReason(result StepResult) string { return sentence(result.Reason) } @@ -89,6 +125,9 @@ func (s *Session) step(ctx context.Context, kind, text string, timeout time.Dura if strings.TrimSpace(text) == "" || textLength(text) > 4000 { return StepResult{}, failure(ErrInvalidArgument, "Step description must contain 1–4000 characters.") } + if kind == "extract" && s.agent != nil { + return StepResult{}, failure(ErrInvalidArgument, "Extract runs on Revyl's agent, and this session runs steps on your model because Open was passed WithModel, WithCustomModel or WithAgent. Read the value from Screenshot with your model, or open a session without them to use Extract.") + } if timeout == 0 { timeout = s.stepTimeout } @@ -98,7 +137,7 @@ func (s *Session) step(ctx context.Context, kind, text string, timeout time.Dura s.mu.Lock() if s.stepRunning { s.mu.Unlock() - return StepResult{}, failure(ErrInvalidArgument, "Run one instruction or validation at a time on a session.") + return StepResult{}, failure(ErrInvalidArgument, "Run one instruction, validation or extract at a time on a session.") } s.stepRunning = true s.mu.Unlock() @@ -144,11 +183,29 @@ func (s *Session) step(ctx context.Context, kind, text string, timeout time.Dura if kind == "validation" && (!success || outcome.Output.Validation == nil) { return StepResult{}, failure(ErrStepFailed, "Validation did not reach a verdict. See "+s.viewer) } + var value *string + if outcome.Output.Extracted != nil { + value = outcome.Output.Extracted.Information + } + if kind == "extract" && (!success || outcome.Output.Status == "failed" || value == nil) { + why := sentence(reason) + if success && outcome.Output.Status != "failed" { + why = "Revyl returned no value." + } + return StepResult{}, failure(ErrStepFailed, "Extract read nothing: \""+text+"\". "+why+" Describe one value that is on the screen now, such as \"the order number on the confirmation\". See "+s.viewer) + } passed := success && outcome.Output.Status != "failed" if kind == "validation" { passed = *outcome.Output.Validation } - return StepResult{Type: kind, Text: text, Passed: passed, Reason: reason, Duration: time.Since(started)}, nil + result := StepResult{Type: kind, Text: text, Passed: passed, Reason: reason, Duration: time.Since(started)} + if kind == "extract" { + result.Value = *value + } + if outcome.Output.Engine == "local" || outcome.Output.Engine == "hosted" { + result.Engine = outcome.Output.Engine + } + return result, nil } func (s *Session) runStep(ctx context.Context, kind, text string, timeout time.Duration) (out liveStep, err error) { diff --git a/go/target.go b/go/target.go index 624217b..4d1738f 100644 --- a/go/target.go +++ b/go/target.go @@ -47,8 +47,16 @@ type Target struct { IdleTimeoutSeconds int Viewport *Viewport SignIn *SignIn + // Inference, on a Mac computer, runs it on a Mac whose own vision model is loaded, so Validation and Extract work on + // it and iOS and Web sessions it opens use that model too; it is enabled per organization. On an iOS or Web target + // passed to a computer's Open, it runs that session's steps on the hosting Mac's model first, with Revyl's hosted + // model as the fallback: nil means true inside a computer opened with Inference and false otherwise, and a pointer + // to false opts out. + Inference *bool } +const macInferenceOpen = "verify.Open(ctx, verify.Target{Platform: verify.Mac, Inference: new(true)})" + var uuidPattern = regexp.MustCompile(`(?i)^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`) var webPattern = regexp.MustCompile(`^https://[^/?#@\s]+(/[^?#\s]*)?$`) var signInPathPattern = regexp.MustCompile(`^/[^?#\\\s]{0,511}$`) @@ -69,7 +77,10 @@ func (t *Target) validate(hosted bool) error { } if t.Platform.computer() { if t.AppID != "" || t.BundleID != "" || t.URL != "" || t.BuildID != "" || t.ArtifactURL != "" || t.Branch != "" || t.DeviceModel != "" || t.OSVersion != "" || t.IdleTimeoutSeconds != 0 || t.Viewport != nil || t.SignIn != nil { - return bad("Computer targets accept only Platform, StartTimeout, and Timeout.") + return bad("Computer targets accept only Platform, StartTimeout, Timeout, and Inference.") + } + if t.Platform == Linux && t.Inference != nil && *t.Inference { + return bad("Inference is for Mac computers only; open one with " + macInferenceOpen + ".") } if t.Timeout != 0 && (t.Timeout < time.Minute || t.Timeout > 24*time.Hour || t.Timeout%time.Second != 0) { return bad("Timeout must be whole seconds from 1 minute to 24 hours.") @@ -79,6 +90,12 @@ func (t *Target) validate(hosted bool) error { if t.Timeout != 0 { return bad("Timeout applies only to computer targets.") } + if t.Inference != nil && !hosted { + return bad("Inference applies only to Mac computers and to iOS and Web sessions a computer's Open starts.") + } + if t.Inference != nil && *t.Inference && t.Platform == Android { + return bad("Inference runs only for iOS and Web sessions inside a Mac computer; leave it out for Android.") + } if t.IdleTimeoutSeconds == 0 { t.IdleTimeoutSeconds = 600 } diff --git a/package-lock.json b/package-lock.json index f081200..a5e1086 100644 --- a/package-lock.json +++ b/package-lock.json @@ -18,7 +18,7 @@ "name": "verify-example-agent-platform", "version": "0.0.0", "devDependencies": { - "@revyl/verify": "0.7.1", + "@revyl/verify": "0.8.0", "@types/node": "^22.10.0", "typescript": "^5.9.0" } @@ -27,7 +27,16 @@ "name": "verify-example-byo-model", "version": "0.0.0", "devDependencies": { - "@revyl/verify": "0.7.1", + "@revyl/verify": "0.8.0", + "@types/node": "^22.10.0", + "typescript": "^5.9.0" + } + }, + "examples/mac-inference": { + "name": "verify-example-mac-inference", + "version": "0.0.0", + "devDependencies": { + "@revyl/verify": "0.8.0", "@types/node": "^22.10.0", "typescript": "^5.9.0" } @@ -36,7 +45,7 @@ "name": "verify-example-mac-workspace", "version": "0.0.0", "devDependencies": { - "@revyl/verify": "0.7.1", + "@revyl/verify": "0.8.0", "@types/node": "^22.10.0", "typescript": "^5.9.0" } @@ -45,7 +54,7 @@ "name": "verify-example-mobile-settings", "version": "0.0.0", "devDependencies": { - "@revyl/verify": "0.7.1", + "@revyl/verify": "0.8.0", "@types/node": "^22.10.0", "typescript": "^5.9.0" } @@ -54,7 +63,7 @@ "name": "verify-example-web-cdp", "version": "0.0.0", "devDependencies": { - "@revyl/verify": "0.7.1", + "@revyl/verify": "0.8.0", "@types/node": "^22.10.0", "playwright-core": "^1.65.1", "typescript": "^5.9.0" @@ -64,7 +73,7 @@ "name": "verify-example-web-store", "version": "0.0.0", "devDependencies": { - "@revyl/verify": "0.7.1", + "@revyl/verify": "0.8.0", "@types/node": "^22.10.0", "typescript": "^5.9.0" } @@ -1117,6 +1126,10 @@ "resolved": "examples/byo-model", "link": true }, + "node_modules/verify-example-mac-inference": { + "resolved": "examples/mac-inference", + "link": true + }, "node_modules/verify-example-mac-workspace": { "resolved": "examples/mac-workspace", "link": true @@ -1324,10 +1337,10 @@ } }, "packages/revyl-verify": { - "version": "0.7.1", + "version": "0.8.0", "license": "Apache-2.0", "dependencies": { - "@revyl/verify": "0.7.1" + "@revyl/verify": "0.8.0" }, "bin": { "revyl-verify": "cli.js" @@ -1338,7 +1351,7 @@ }, "packages/verify": { "name": "@revyl/verify", - "version": "0.7.1", + "version": "0.8.0", "license": "Apache-2.0", "dependencies": { "jiti": "^2.6.0", diff --git a/packages/revyl-verify/README.md b/packages/revyl-verify/README.md index 58b76a6..3a3fcb9 100644 --- a/packages/revyl-verify/README.md +++ b/packages/revyl-verify/README.md @@ -15,4 +15,4 @@ The CLI delegates to `@revyl/verify`, including its output, generated imports, a import { open } from 'revyl-verify'; ``` -Use Node.js 22.18 or later. See the [Verify documentation](https://github.com/RevylAI/verify/tree/v0.7.1/packages/verify/docs) for configuration, API and platform availability. This package shares Verify's [Apache 2.0 license](https://github.com/RevylAI/verify/blob/v0.7.1/LICENSE). +Use Node.js 22.18 or later. See the [Verify documentation](https://github.com/RevylAI/verify/tree/v0.8.0/packages/verify/docs) for configuration, API and platform availability. This package shares Verify's [Apache 2.0 license](https://github.com/RevylAI/verify/blob/v0.8.0/LICENSE). diff --git a/packages/revyl-verify/package.json b/packages/revyl-verify/package.json index 9917523..cf49aee 100644 --- a/packages/revyl-verify/package.json +++ b/packages/revyl-verify/package.json @@ -1,6 +1,6 @@ { "name": "revyl-verify", - "version": "0.7.1", + "version": "0.8.0", "description": "Unscoped alias for @revyl/verify, with the same API and CLI.", "homepage": "https://github.com/RevylAI/verify#readme", "repository": { @@ -29,7 +29,7 @@ "node": ">=22.18" }, "dependencies": { - "@revyl/verify": "0.7.1" + "@revyl/verify": "0.8.0" }, "scripts": { "prepack": "cp ../../LICENSE LICENSE && chmod +x cli.js" diff --git a/packages/verify/docs/README.md b/packages/verify/docs/README.md index 5fb2d79..2be838f 100644 --- a/packages/verify/docs/README.md +++ b/packages/verify/docs/README.md @@ -15,5 +15,8 @@ These files ship inside the npm package at `node_modules/@revyl/verify/docs/`, s | [own-model.md](own-model.md) | Run instructions and validations on your own model, such as Claude, GPT or a local model | | [errors.md](errors.md) | Understand an error code and fix it, or troubleshoot a common problem | | [agents.md](agents.md) | Use Verify as a coding agent | +| [guides/mac-model-checks.md](guides/mac-model-checks.md) | Check a Mac's screen with `validation()` and `extract()` on its own model | +| [guides/apps-inside-an-inference-mac.md](guides/apps-inside-an-inference-mac.md) | Run an iOS or Web app inside a Mac whose model answers its steps | +| [guides/persistent-computers.md](guides/persistent-computers.md) | Keep a Mac's disk between runs and copy it with snapshots, with use cases | [llms.txt](llms.txt) lists the same files in the llms.txt format. diff --git a/packages/verify/docs/agents.md b/packages/verify/docs/agents.md index 178692a..13a01fd 100644 --- a/packages/verify/docs/agents.md +++ b/packages/verify/docs/agents.md @@ -53,18 +53,20 @@ try { } ``` -The [Python](https://github.com/RevylAI/verify/blob/v0.7.1/python/README.md#exact-actions) and [Go](https://github.com/RevylAI/verify/blob/v0.7.1/go/README.md#exact-actions) READMEs state the same rule with each language's names. [api.md](api.md#exact-actions) lists every call and its errors. +The [Python](https://github.com/RevylAI/verify/blob/v0.8.0/python/README.md#exact-actions) and [Go](https://github.com/RevylAI/verify/blob/v0.8.0/go/README.md#exact-actions) READMEs state the same rule with each language's names. [api.md](api.md#exact-actions) lists every call and its errors. ## Rules Mac computers are available to organizations on a current paid Revyl plan. Ask before starting a computer, as for a device; do not repeat an uncertain start/stop to probe availability. -For computer work, use structured `exec(['program', 'arg'])`, `readFile`, `writeFile`, `stat`, and run-owned handles from `processes()`/`terminate(id)`. Check command output with ordinary assertions and close in `finally`; screenshots are supported, but instruction/validation are not. To use the screen, read a point off `screenshot()` and `tap({ x, y })` it, or describe it with `tap({ target })`, and type with `type({ target: 'the search field' }, text)`, which clicks the field and types into it, or `typeFocused(text, { clear: false })` where the cursor already is. A described click takes several seconds, because Revyl takes a screenshot and finds the element first. It can pick a look-alike, and when the target isn't on the screen it can still click something else instead of failing. So check the point it returns or take a screenshot afterwards, and for anything that's hard to undo, read the point off `screenshot()` and use `tap({ x, y })`. After `ACTION_UNCERTAIN`, take a screenshot before you act again. Do not fall back to agent steps on computers or shell/file methods on mobile/web. See [computers.md](computers.md) for limits. Starting a computer is a paid external action and needs the same approval as starting a device. +For computer work, use structured `exec(['program', 'arg'])`, `readFile`, `writeFile`, `stat`, and run-owned handles from `processes()`/`terminate(id)`. Check command output with ordinary assertions and close in `finally`; screenshots are supported. `instruction()` doesn't run on computers. To check the screen, open the Mac with `open({ platform: 'mac', inference: true })` and use `validation()` and `extract()`, which its own model answers ([guide](guides/mac-model-checks.md)); on a Mac without `inference` they throw `NOT_AVAILABLE_ON_PLATFORM`. To use the screen, read a point off `screenshot()` and `tap({ x, y })` it, or describe it with `tap({ target })`, and type with `type({ target: 'the search field' }, text)`, which clicks the field and types into it, or `typeFocused(text, { clear: false })` where the cursor already is. A described click takes several seconds, because Revyl takes a screenshot and finds the element first. It can pick a look-alike, and when the target isn't on the screen it can still click something else instead of failing. So check the point it returns or take a screenshot afterwards, and for anything that's hard to undo, read the point off `screenshot()` and use `tap({ x, y })`. After `ACTION_UNCERTAIN`, take a screenshot before you act again. Do not fall back to `instruction()` on computers or shell/file methods on mobile/web. See [computers.md](computers.md) for limits. Starting a computer is a paid external action and needs the same approval as starting a device. -Computers have a hard lifetime from create, not from readiness or activity: 2 hours by default, up to 24 hours with `timeoutMs` on the target, and `extend(timeoutMs)` lengthens a running computer up to 24 hours from create. `expiresAt` is the authoritative deadline. `expiresAt` is optional on older APIs; expiry does not prevent close. To get the screen recording, call `await computer.close()` and then `await computer.recording()` on the same object before the script exits: it waits until Revyl has saved the video, usually a few seconds, and returns `{ url, durationSeconds?, startedAt? }`, or null if none was saved within 15 minutes. `attach()` can't reopen a closed computer to fetch it later. Never log or share its signed URL/query. Do not retry `COMPUTER_LIMIT` starts: queued work (including iOS) or the concurrency limit may be responsible. +Computers have a hard lifetime from create, not from readiness or activity: 2 hours by default, up to 24 hours with `timeoutMs` on the target, and `extend(timeoutMs)` lengthens a running computer up to 24 hours from create. `expiresAt` is the authoritative deadline. `expiresAt` is optional on older APIs; expiry does not prevent close. To get the screen recording, call `await computer.close()` and then `await computer.recording()` on the same object before the script exits: it waits until Revyl has saved the video, usually a few seconds, and returns `{ url, durationSeconds?, startedAt? }`, or null if none was saved within 15 minutes; a check already under way then can take up to 30 seconds more. `attach()` can't reopen a closed computer to fetch it later. Never log or share its signed URL/query. Do not retry `COMPUTER_LIMIT` starts: queued work (including iOS) or the concurrency limit may be responsible. - Write steps the way you would brief a person: what to do, or what should be true, in one sentence. Name visible things ("the blue Save button in the footer"), not implementation details. -- Use `instruction` for doing and `validation` for checking. Do not ask an instruction to check something, or a validation to change anything. +- Use `instruction` for doing, `validation` for checking and `extract` for reading one value, such as `extract('the order number')`, which returns it in `value`. Do not ask an instruction to check something, or a validation to change anything. +- Inside a Mac opened with `inference: true`, iOS and Web sessions run validations and single-tap instructions on the Mac's own model first, by default. `engine` on each result says whether the Mac's model (`'local'`) or Revyl's hosted model (`'hosted'`) answered. A local verdict is final; open the session with `inference: false` when a check must run on the hosted model. See [apps inside an inference Mac](guides/apps-inside-an-inference-mac.md). +- A persistent computer (`openPersistent(name)`) keeps its disk after `close()`, and every copy you create from a snapshot is a computer that counts toward the organization's limit of 10 until deleted. Delete the ones you created with `deletePersistent(name)`, by exact name, never by listing and deleting everything. See [the persistence guide](guides/persistent-computers.md). - Prefer several small steps to one long one. Small steps fail with clearer reasons and time out less. - Each step stands alone: Revyl does not carry values from one step to the next. Put everything a step needs into its text. - Every step runs Revyl's agent again; nothing is cached or replayed. Do not rerun a whole script to probe one step. diff --git a/packages/verify/docs/api.md b/packages/verify/docs/api.md index 81e4847..970f23b 100644 --- a/packages/verify/docs/api.md +++ b/packages/verify/docs/api.md @@ -21,6 +21,7 @@ const mac = await open({ platform: 'mac' }); // computer, - `options.log`: where progress lines go. By default Verify writes the session link and each step's outcome to stderr, prefixed with `[verify]`. Pass a function to receive the lines yourself, or `false` to turn them off. - `options.model`: runs every instruction and validation on your own model instead of Revyl's agent; see [Your own model](#your-own-model). Browsers and devices only; computers throw `NOT_AVAILABLE_ON_PLATFORM`. - `options.agent`: the same with a custom agent; see [Custom agents](#custom-agents). Pass `model` or `agent`, not both. +- `options.backendUrl`, `options.appUrl`: the Revyl API and web origins. They default to Revyl's production origins; change them only to test another Revyl environment. `openPersistent()` and the other persistent-computer calls take them too. - `options.profile`: a session profile from your project's `.revyl/config.yaml`, such as `'signed-in'`, that Revyl runs before `open()` returns, or `'none'` for no profile. Left out, the project's `session.default_profile` runs when it sets one. Web, iOS, Android and Mac computers. See [Session profiles](#session-profiles). `open` needs credentials: `REVYL_API_KEY` or a Revyl CLI login. It throws `AUTH_MISSING` without them, `CONFIG_NOT_FOUND` or `CONFIG_INVALID` for config problems, and `SESSION_START_FAILED` or `TIMEOUT` when the browser or device does not start. @@ -146,6 +147,8 @@ try { } ``` +Inside a Mac opened with `inference: true`, an iOS or Web child runs its validations, and instructions that are a single tap, on the Mac's own model first, with Revyl's hosted model as the fallback for other steps and for answers the Mac's model can't give. That is the default; `inference: false` in the target turns it off for that child, and `inference: true` on Android is refused. If the Mac's model isn't answering, the child's start throws `NOT_AVAILABLE_ON_PLATFORM` with reason `computer_local_inference_unavailable`. See [apps inside an inference Mac](guides/apps-inside-an-inference-mac.md). + The initial Web build uses HTTPS. After start, `navigate()` can also reach `http://localhost:` on the computer, but only when a service is already listening there, such as one an earlier step of a `revyl-macos` job started. Verify has no call that starts one, and a process started through `exec()` ends when the command returns. Leave out `stopOnClose: false` only for a computer your script owns: then `close()` stops it. ## session.navigate(url) @@ -192,7 +195,7 @@ On iOS, Android and Mac computers `cdp()` throws `NOT_AVAILABLE_ON_PLATFORM` bef ## Exact actions -**Early access.** Since TypeScript (`@revyl/verify`) 0.4.0, Python (`revyl-verify`) 0.2.0 and Go v0.3.0. `doubleTap`, `longPress`, `drag`, `typeFocused`, `goHome`, and Web keys and modifiers in `pressKey`, are new in TypeScript 0.5.0, Python 0.3.0 and Go v0.4.0. On a Mac computer's screen, `tap` (by point or by description), `screenSize`, `typeFocused` and `pressKey` are new in TypeScript 0.6.0, Python 0.4.0 and Go v0.5.0, and `type` in TypeScript 0.7.1, Python 0.5.1 and Go v0.6.1. The [Python](https://github.com/RevylAI/verify/blob/v0.7.1/python/README.md#exact-actions) and [Go](https://github.com/RevylAI/verify/blob/v0.7.1/go/README.md#exact-actions) READMEs show them with each language's names. Web, iOS and Android sessions, and a Mac computer's screen, take device actions that need no agent. +**Early access.** Since TypeScript (`@revyl/verify`) 0.4.0, Python (`revyl-verify`) 0.2.0 and Go v0.3.0. `doubleTap`, `longPress`, `drag`, `typeFocused`, `goHome`, and Web keys and modifiers in `pressKey`, are new in TypeScript 0.5.0, Python 0.3.0 and Go v0.4.0. On a Mac computer's screen, `tap` (by point or by description), `screenSize`, `typeFocused` and `pressKey` are new in TypeScript 0.6.0, Python 0.4.0 and Go v0.5.0, and `type` in TypeScript 0.7.1, Python 0.5.1 and Go v0.6.1. The [Python](https://github.com/RevylAI/verify/blob/v0.8.0/python/README.md#exact-actions) and [Go](https://github.com/RevylAI/verify/blob/v0.8.0/go/README.md#exact-actions) READMEs show them with each language's names. Web, iOS and Android sessions, and a Mac computer's screen, take device actions that need no agent. **Typing: one rule on every platform.** To type, call `type({ target: 'Email field' }, text)`: it taps the field you describe and types into it, replacing its text unless you pass `{ clear: false }`. It works the same on Web, iOS, Android and a Mac computer. `typeFocused(text)` types wherever focus already is, without tapping, and only on Web and computers; on Web, when no field has focus it throws `ACTION_FAILED` with reason `no_focused_input` and types nothing. @@ -210,7 +213,8 @@ On iOS, Android and Mac computers `cdp()` throws `NOT_AVAILABLE_ON_PLATFORM` bef | `launchApp(bundleId)` | No, use `openUrl` or `navigate` | Yes | Yes | No | | `navigate(url)` | Yes | No, use `openUrl` | No, use `openUrl` | No | | `cdp()`, for Playwright and Puppeteer | Yes, see [CDP](#cdp-playwright-puppeteer) | No | No | No | -| `instruction`, `validation`, your own model | Yes | Yes | Yes | No, use `exec()` and the screen calls above | +| `instruction`, your own model | Yes | Yes | Yes | No, use `tap({ target })`, `type({ target }, text)` and `exec()` | +| `validation`, `extract` | Yes | Yes | Yes | Yes, on a Mac opened with `inference: true`; see [computers.md](computers.md#checks-on-the-macs-own-model) | | `screenshot()` | Yes | Yes | Yes | Yes | | `exec`, files, processes | No, open a Mac computer | No, open a Mac computer | No, open a Mac computer | Yes | @@ -265,7 +269,7 @@ Returns authenticated JSON metadata: `/execution/device-sessions/{id}` for norma ## session.instruction(text, options?) -Available on web/iOS/Android only. Computers throw `NOT_AVAILABLE_ON_PLATFORM` without sending an agent request. +Available on web/iOS/Android only. Computers throw `NOT_AVAILABLE_ON_PLATFORM` without sending anything; the message names `tap({ target: 'the Save button' })` and `type({ target: 'the search field' }, text)`, which click and type by description there. In a session opened inside a Mac with `inference: true`, an instruction that is a single tap on one thing runs on the Mac's own model first; see [computer.open(target)](#computeropentarget). Asks Revyl's agent to do something in the app, described the way you would tell a person: `'Sign in as the demo user and open Settings'`. The agent looks at the screen and acts until it is done or decides it cannot. @@ -275,7 +279,7 @@ Asks Revyl's agent to do something in the app, described the way you would tell ## session.validation(text, options?) -Available on web/iOS/Android only, not computers. +Available on web, iOS and Android, and since 0.8.0 on a Mac opened with `inference: true`, where the Mac's own vision model answers it; other Macs throw `NOT_AVAILABLE_ON_PLATFORM` (`step_engine_unavailable`). See [checks on the Mac's own model](computers.md#checks-on-the-macs-own-model). Asks Revyl's agent whether something holds on screen right now: `'The cart shows 2 items and a total of $40'`. @@ -285,26 +289,46 @@ Asks Revyl's agent whether something holds on screen right now: `'The cart shows - `options.soft: true` returns a failed result instead of throwing `VALIDATION_FAILED`, for scripts that want to collect several outcomes. It does not turn `STEP_FAILED` into a result. - `options.timeout`: as for `instruction`. +## session.extract(text, options?) + +**Since 0.8.0.** Web, iOS, Android, and a Mac opened with `inference: true`. + +Reads one value off the screen, described the way you would ask a person: `'the order number'`, `'the total in the cart'`. + +```ts +const order = await session.extract('the order number on the confirmation screen'); +console.log(order.value); // e.g. 'A-10293' +``` + +- Resolves with a `StepResult` whose `value` is the text it read. +- Throws `STEP_FAILED`, with the reason, when nothing could be read or the step was cancelled. Describe one value that is on the screen now. +- On web, iOS and Android it runs on Revyl's agent, including inside an inference Mac. A session opened with `model` or `agent` throws `INVALID_ARGUMENT`: read the value from `screenshot()` with your model instead. On a Mac it runs on the Mac's own model and needs `inference: true`, like `validation()`. +- `options.timeout`: as for `instruction`. + ## StepResult ```ts interface StepResult { - type: 'instruction' | 'validation'; + type: 'instruction' | 'validation' | 'extract'; text: string; // the step as sent, trimmed passed: boolean; + value?: string; // extract only: what it read reason?: string; // Revyl's explanation, or your model's on a local agent durationMs: number; + engine?: 'local' | 'hosted'; // who answered, when Revyl says: the Mac's own model or Revyl's hosted model model?: ModelRun; // set when the step ran on your model } ``` +`engine` is set on steps that run on a Mac opened with `inference: true` and in sessions inside one, and left out elsewhere. + `session.steps` lists every step run on the session, in order. When inspecting `revyl device report --session-id `, read validation verdicts from the step's `effective_status` and `validation_result`, with `validations_passed` / `total_validations` for the validation summary. `passed_steps` / `failed_steps` and transport `status` are not enough: a successfully executed validation can have a false verdict. The SDK's `StepResult.passed` reflects that verdict, not just transport success. ## Your own model -**Early access.** Since TypeScript (`@revyl/verify`) 0.4.0, Python (`revyl-verify`) 0.2.0 and Go v0.3.0; the [Python](https://github.com/RevylAI/verify/blob/v0.7.1/python/README.md#your-own-model) and [Go](https://github.com/RevylAI/verify/blob/v0.7.1/go/README.md#your-own-model) READMEs show them with each language's names. Runs instructions and validations on a model you choose, in your process, instead of Revyl's agent. Revyl still provides the browser or device. Leave `model` out and Revyl's agent runs the step, as before. +**Early access.** Since TypeScript (`@revyl/verify`) 0.4.0, Python (`revyl-verify`) 0.2.0 and Go v0.3.0; the [Python](https://github.com/RevylAI/verify/blob/v0.8.0/python/README.md#your-own-model) and [Go](https://github.com/RevylAI/verify/blob/v0.8.0/go/README.md#your-own-model) READMEs show them with each language's names. Runs instructions and validations on a model you choose, in your process, instead of Revyl's agent. Revyl still provides the browser or device. Leave `model` out and Revyl's agent runs the step, as before. ```ts const session = await open('ios', { model: 'anthropic/claude-sonnet-5-5' }); // every step on your model @@ -355,7 +379,7 @@ For owning computers, cleanup must be confirmed; a terminal state alone does not ## Computer commands, files, and processes -Mac sessions provide `exec(argv: string[], options?)`, `readFile(path, options?)` returning `Buffer`, `writeFile(path, string | Uint8Array, options?)`, `stat(path, options?)` returning `{ kind, size }`, `processes(options?)` returning `{ id, state, exitCode? }[]`, and `terminate(id, options?)`. They throw `NOT_AVAILABLE_ON_PLATFORM` on web/iOS/Android. See [computers.md](computers.md) for complete signatures, limits, timeouts, and examples. Both support `screenshot()`, and computers take `tap({ x, y })`, `tap({ target })`, `type({ target }, text)`, `screenSize()`, `typeFocused(text, { clear: false })` and `pressKey` on the screen (see [computers.md](computers.md#screen)); instruction/validation do not run on computers. +Mac sessions provide `exec(argv: string[], options?)`, `readFile(path, options?)` returning `Buffer`, `writeFile(path, string | Uint8Array, options?)`, `stat(path, options?)` returning `{ kind, size }`, `processes(options?)` returning `{ id, state, exitCode? }[]`, and `terminate(id, options?)`. They throw `NOT_AVAILABLE_ON_PLATFORM` on web/iOS/Android. See [computers.md](computers.md) for complete signatures, limits, timeouts, and examples. Both support `screenshot()`, and computers take `tap({ x, y })`, `tap({ target })`, `type({ target }, text)`, `screenSize()`, `typeFocused(text, { clear: false })` and `pressKey` on the screen (see [computers.md](computers.md#screen)). `instruction()` doesn't run on computers; `validation()` and `extract()` run on a Mac opened with `inference: true`. ### `session.extend(timeoutMs: number): Promise` @@ -385,6 +409,26 @@ It reads the report and requires terminal state plus confirmed release; on a com | `expiresAt` | **Since 0.2.0.** Validated API expiry as a `Date`, or undefined for devices and older APIs. Computers have a hard lifetime from create (2 hours by default, up to 24 hours with `timeoutMs`); this value is the authoritative deadline, and `extend()` updates it. Operations/screenshot observation are bounded by expiry; close and recording remain possible. | | `target` | The target name, or the platform for a target object | | `closed` | Whether `close()` was called | +| `inference` | **Since 0.8.0.** On a Mac opened with `inference: true`: `'ready'`, `'unavailable'` or `'unknown'`, whether its own model answered when Verify last read the report (at open and on each `report()`). `undefined` on every other session | + +## Persistent computers + +**Since 0.7.0**, for organizations with persistent computers enabled; others get `NOT_AVAILABLE_ON_PLATFORM` with reason `persistent_computers_not_enabled`. See [the persistence guide](guides/persistent-computers.md) for what is kept and for use cases. + +```ts +import { openPersistent, saveSnapshot, listPersistent, listSnapshots, deletePersistent, deleteSnapshot } from '@revyl/verify'; +``` + +| Call | Result | +| --- | --- | +| `openPersistent(name, { fromSnapshot?, inference?, withoutInference?, timeoutMs?, startTimeout?, log? }?)` | A running Mac with every computer method, plus `name` and `created`. Creates the computer the first time, boots a stopped one from its disk, and connects to a running one. `close()` stops it and keeps its disk | +| `saveSnapshot(computer, name, { waitTimeout? }?)` | A `ComputerSnapshot` of a stopped computer's disk, once the save is copied off its Mac | +| `listPersistent()` | `{ id, state, savedAt?, savedOffHost, createdAt, savedDiskExpiresAt? }[]` | +| `listSnapshots()` | `{ id, name, computerId, savedAt, expiresAt?, savedDiskExpiresAt? }[]` | +| `deletePersistent(computer)` | Deletes the computer and its disk for good; its snapshots stay | +| `deleteSnapshot(snapshot)` | Deletes the snapshot; computers made from it keep their disks | + +`computer` and `snapshot` take a name or an ID. Every call also takes `log`, `backendUrl` and `appUrl`, as `open()` does. `savedDiskExpiresAt` (since 0.8.0) is when a save stops being able to start a computer, when Revyl reports one. `inference` (since 0.8.0) is used only when the call creates the computer; `withoutInference` (since 0.8.0) starts a stopped inference computer once without its model. ## Rules worth knowing diff --git a/packages/verify/docs/computers.md b/packages/verify/docs/computers.md index 89d053d..2943b4e 100644 --- a/packages/verify/docs/computers.md +++ b/packages/verify/docs/computers.md @@ -12,6 +12,12 @@ node verify/example.mts Installed tools, paths, resources, and desktop dimensions are not fixed SDK guarantees. +Three guides cover what this page only summarizes: + +- [Check a Mac's screen with its own model](guides/mac-model-checks.md): `validation()` and `extract()` on a Mac opened with `inference: true`. +- [Test an iOS or Web app inside an inference Mac](guides/apps-inside-an-inference-mac.md): app sessions whose steps run on the Mac's model first. +- [Keep a Mac between runs](guides/persistent-computers.md): persistent computers and snapshots, with use cases, what is kept, lifetimes and cleanup. + ## Commands and files ```ts @@ -44,7 +50,7 @@ try { `exec` takes structured argv, not a shell line. For shell syntax, explicitly invoke a shell, such as `['/bin/sh', '-c', 'printf hello']`. Never interpolate untrusted input into shell text. `stdin` accepts a string or `Uint8Array`. At most 64 arguments and 16,384 UTF-8 argv plus stdin bytes are allowed. Revyl keeps only the first 1 MiB of combined stdout/stderr; the command still runs to completion. Commands are synchronous at the library boundary; there is no interactive terminal or background-process creation API. -Paths are relative to the computer's workspace: no leading slash, empty components, `.` or `..`, backslashes, colons, or control characters. A path is at most 1,024 UTF-8 bytes. To make a directory, run a command such as `['mkdir', '-p', 'output']` before writing into it. There is no recursive sync or snapshot API. +Paths are relative to the computer's workspace: no leading slash, empty components, `.` or `..`, backslashes, colons, or control characters. A path is at most 1,024 UTF-8 bytes. To make a directory, run a command such as `['mkdir', '-p', 'output']` before writing into it. There is no recursive sync API. To keep the whole disk between runs, use a [persistent computer](#persistent-computers-and-snapshots). Operation `timeout` is milliseconds, defaults to 30,000, and must be an integer from 1 to 300,000. It is also bounded by the run's remaining lifetime. A computer has a hard lifetime **from create**, not from readiness or last activity: 2 hours by default, or up to 24 hours with `timeoutMs` on the target (whole seconds, 60000 to 86400000). `extend(timeoutMs)` keeps a running computer going at least that long from now, up to 24 hours after create, and updates `expiresAt`; it never shortens the lifetime, so retrying is safe. Lifetimes over 2 hours can be refused with `COMPUTER_LIMIT` (`computer_long_limit`: at most 2 such computers per organization at once) or `NOT_AVAILABLE_ON_PLATFORM` (no host can run that long, or the host can't extend). `expiresAt` is authoritative; `idleTimeoutSeconds` and the agent `stepTimeout` do not configure computer lifetime or commands. `expiresAt` is a `Date` when the API returns `expires_at`, and otherwise undefined (including on devices and older APIs). Verify refuses new operations after that deadline and bounds operation/screenshot observation by it; expiry does not prevent explicit close or recording retrieval. Revyl allows at most 256 operations per run. @@ -117,6 +123,30 @@ A script that controls the screen keeps control for 120 seconds after its last a When long text fails part way, the error says how many characters were certainly typed and whether the piece that failed may have been typed, counting characters as Unicode code points, so an emoji is one. Every other refusal names its reason and what to do next, such as starting a new computer after `run_closed`. +## Checks on the Mac's own model + +**New in TypeScript 0.8.0, Python 0.6.0 and Go v0.7.0.** Open a Mac with `inference: true` and it runs on a Revyl Mac that has its own vision model. Then `validation(text, { soft? })` checks a statement against its screen and `extract(text)` reads a value off it, returning a `StepResult` with the value in `value`. The Mac's model answers both, usually in 2 to 3 seconds, and `engine` on the result is `'local'`: + +```ts +const mac = await open({ platform: 'mac', inference: true }); +try { + await mac.validation('The Dock is visible at the bottom of the screen'); + const date = await mac.extract('the date at the right end of the menu bar'); + console.log(date.value); +} finally { + await mac.close(); +} +``` + +- **Cost.** Steps on a computer have no per-step fee, and these run only on the Mac's own model, so they carry no inference charge. You pay the Mac's minutes, as for any computer. +- **Availability.** Local inference is enabled per organization, on top of Mac computers. Opening a Mac with `inference` throws `NOT_AVAILABLE_ON_PLATFORM` with reason `inference_not_enabled` when your organization doesn't have it (ask support@revyl.ai), and `inference_unavailable` when no Mac with a model is free right now; nothing is started either way. Linux computers don't take `inference`. +- **`computer.inference`** is `'ready'`, `'unavailable'` or `'unknown'`: whether the Mac's model answered when Verify last read the computer's report, at open and on each `report()`. It is `undefined` on a computer opened without inference. +- **Results.** A false statement throws `VALIDATION_FAILED` unless `soft: true`. An answer the model can't confirm is never a pass: it throws `STEP_FAILED` with the model's reason, as does an `extract()` that finds nothing (`local_model_found_no_value`). +- **Refusals.** On a Mac opened without inference, or when its model stopped answering, both throw `NOT_AVAILABLE_ON_PLATFORM` (`step_engine_unavailable`) without running. The model answers one step at a time for the Mac and the app sessions inside it: when it stayed busy too long the step throws `SESSION_BUSY`, naming `step_engine_busy`, so run one step at a time per computer. While someone controls the screen in the viewer they throw `SESSION_BUSY` (`screen_control_held`). +- **`instruction()`** stays unavailable on computers. To click one thing by its description, use `tap({ target: 'the Save button' })`; to type into a field, use `type({ target: 'the search field' }, text)`. + +The [Mac model guide](guides/mac-model-checks.md) has the Python and Go versions and more on writing steps the model can answer. + ## Recording To get a computer's screen recording, close it and then call `recording()` on the same object, in the same process: @@ -136,16 +166,46 @@ Mac computers are available to organizations on a current paid Revyl plan. A `50 The default `startTimeout` remains 600000 ms; override it explicitly if needed. An unclaimed start can transition to `failed` with `failure_reason: 'no_host'` after 120 seconds from create. Verify stops readiness polling and throws `SESSION_START_FAILED` with that context, then attempts bounded cleanup. This is not a 120-second timeout for every start: claimed guests may take longer. `device_limit` also yields `SESSION_START_FAILED`, with queued-work/concurrency context. A start timeout or unconfirmed close does not prove resources were released. Inspect the session and contact support rather than blindly repeating a start or stop. -`instruction()` and `validation()` throw `NOT_AVAILABLE_ON_PLATFORM` on computers without sending agent requests. Screenshots are supported, but screenshot readiness is separate from command readiness. For the screen, use the calls in [Screen](#screen). On web, iOS, and Android, shell/file/process methods throw `NOT_AVAILABLE_ON_PLATFORM`. +`instruction()` throws `NOT_AVAILABLE_ON_PLATFORM` on computers without sending anything. `validation()` and `extract()` run on a Mac opened with `inference: true` and throw `NOT_AVAILABLE_ON_PLATFORM` (`step_engine_unavailable`) on other Macs; see [Checks on the Mac's own model](#checks-on-the-macs-own-model). Screenshots are supported, but screenshot readiness is separate from command readiness. For the screen, use the calls in [Screen](#screen). On web, iOS, and Android, shell/file/process methods throw `NOT_AVAILABLE_ON_PLATFORM`. For the first 30 seconds after a computer becomes active, `screenshot()` retries exact structured `screen_unavailable` responses (HTTP 409 or 503) and `screen_starting` (HTTP 409). Backoff starts at 500 ms and doubles up to 2 seconds; the fixed window does not restart on each call. Cancellation, close, expiry, and the observation deadline still bound the wait. Exhausting that window yields `SESSION_BUSY` with a desktop-not-ready message, rather than requiring a caller sleep. Authentication failures, unrelated errors, malformed responses, and transport failures are not replayed. Commands and other mutations are never retried by this screenshot behavior. Missing files and access denials throw `NOT_FOUND` and `ACCESS_DENIED`. An operation timeout with confirmed termination throws `TIMEOUT`; unconfirmed termination or execution throws `ACTION_UNCERTAIN`. Neither implies rollback. Execution outcome, evidence recording, and physical release are independent: an observed successful command can return its result while logging pending/failed report evidence. Do not repeat a mutation merely because its response was lost. Check the computer in Revyl before deciding what to do next. See [errors.md](errors.md). +## Persistent computers and snapshots + +A computer from `open()` is deleted when it closes. Organizations with persistent computers enabled can keep one instead: `openPersistent(name, options?)` opens the Mac with that name, creating it if needed, and `close()` stops it and keeps its whole disk, so the next `openPersistent(name)` boots from it. Memory and running processes don't survive a stop. `saveSnapshot(computer, name)` saves a stopped computer's disk as a snapshot, `openPersistent(other, { fromSnapshot })` creates a new computer from it, and `listPersistent()`, `listSnapshots()`, `deletePersistent()` and `deleteSnapshot()` manage them. Without the feature, `openPersistent()` and `saveSnapshot()` throw `NOT_AVAILABLE_ON_PLATFORM` with reason `persistent_computers_not_enabled`; ask [support@revyl.ai](mailto:support@revyl.ai). + +```ts +import { openPersistent } from '@revyl/verify'; + +const mac = await openPersistent('ios-dev'); +try { + if ((await mac.exec(['test', '-f', '.setup-done'], { check: false })).exitCode !== 0) { + await mac.exec(['/bin/zsh', '-lc', 'brew install swiftlint'], { timeout: 300_000 }); + await mac.writeFile('.setup-done', 'v1\n'); + } +} finally { + await mac.close(); // stops it and keeps the disk +} +``` + +| Option of `openPersistent()` | Meaning | +| --- | --- | +| `fromSnapshot` | Only when this call creates the computer: start its disk as this snapshot's. `created` on the session says whether it did | +| `inference` | Only when this call creates the computer: run it on Macs with their own model, on every later start too. Copies from a snapshot don't inherit it | +| `withoutInference` | Start a stopped inference computer once without the model, when none is up. Needs a Revyl backend that offers it, otherwise `INVALID_ARGUMENT` | +| `timeoutMs` | This run's lifetime, as on `open()`: 2 hours by default, up to 24 hours | +| `startTimeout` | How long to wait until it is ready: 15 minutes by default, since a start from a snapshot restores the disk first | + +Each run bills like any Mac. A few saves have an end, which `savedDiskExpiresAt` on list entries shows when Revyl reports one. An organization keeps at most 10 persistent computers and 100 snapshots unless Revyl raised its limits. The [persistence guide](guides/persistent-computers.md) covers what is kept and what isn't, use cases (a dev environment set up once, parallel copies from a snapshot, a browser that stays signed in, a long-running agent workspace), lifetimes, cleanup and every error. + ## Lifecycle and transport Use `attach(computerId)` to take cleanup ownership of an existing active computer without creating one. `computer.open(target)` starts Web and iOS children on a Mac. A child requires an existing app/build pair and inherits the parent's client and expiry. Parent close attempts child cleanup for at most five seconds before requesting computer release; the server also stops remaining children. See [the hosted API](api.md#computeropentarget) for arguments, localhost navigation, and cleanup semantics. These are app sessions, not natural-language control of the computer desktop itself. +Inside a Mac opened with `inference: true`, iOS and Web sessions run their validations, and instructions that are a single tap, on the Mac's own model first, with Revyl's hosted model as the fallback for every other step and for answers the Mac's model can't give. This is the default; pass `inference: false` to `computer.open()` to run a session on the hosted model only. `engine` on each step says which answered. Steps the Mac's model answers carry no inference charge, and app sessions inside a computer add no device minutes of their own. When the Mac's model isn't answering, the session's start throws `NOT_AVAILABLE_ON_PLATFORM` (`computer_local_inference_unavailable`). See [the guide](guides/apps-inside-an-inference-mac.md). + For a computer owned by another caller, such as a CI runner, use `attach(computerId, { stopOnClose: false })`. It is not registered for automatic cleanup. Explicit close still cancels pending child starts and closes hosted children within the five-second cleanup phase, but never sends a stop for the computer. The computer's owner is responsible for releasing it; a child-cleanup failure does not authorize stopping the parent. Verify mints a session UUID, creates `/api/v1/computer-runs` with `os: 'macos'` for `platform: 'mac'`, then polls `GET /computer-runs/{id}/report` until `state: 'active'`, which means it is ready. `starting` alone is not readiness. The public Mac target spelling is `mac`, not `macos`. diff --git a/packages/verify/docs/errors.md b/packages/verify/docs/errors.md index 901aab9..7e259f1 100644 --- a/packages/verify/docs/errors.md +++ b/packages/verify/docs/errors.md @@ -22,6 +22,11 @@ | Computer HTTP 409: no host can keep it running for the requested `timeoutMs` | `NOT_AVAILABLE_ON_PLATFORM` | `lifetime_unsupported` | | Computer HTTP 403 `computer_not_enabled` that Pro would lift (`unlocks_with_card: true`) | `NOT_AVAILABLE_ON_PLATFORM` | `upgrade_required` | | Web HTTP 409 on `typeFocused`: no text field has focus, and nothing was typed | `ACTION_FAILED` | `no_focused_input` | +| Mac create with `inference: true`: your organization doesn't have local inference (HTTP 403) | `NOT_AVAILABLE_ON_PLATFORM` | `inference_not_enabled` | +| Mac create or persistent start with `inference`: no Mac with its own model is up now (HTTP 409); nothing was started | `NOT_AVAILABLE_ON_PLATFORM` | `inference_unavailable` | +| `validation()` or `extract()` on a Mac without a model answering (HTTP 409); the step didn't run | `NOT_AVAILABLE_ON_PLATFORM` | `step_engine_unavailable` | +| iOS or Web start inside a Mac whose model isn't answering, with local inference on (HTTP 409); nothing was started | `NOT_AVAILABLE_ON_PLATFORM` | `computer_local_inference_unavailable` | +| `openPersistent()` or `saveSnapshot()` in an organization without persistent computers (HTTP 403) | `NOT_AVAILABLE_ON_PLATFORM` | `persistent_computers_not_enabled` | `web_runtime_unavailable` does not distinguish full capacity from an unavailable runtime. `computer_limit` does not distinguish queued work from concurrency exhaustion. Inspect these fields to classify refusal without parsing prose; do not infer a specific cause or automatically start a replacement session. @@ -56,7 +61,7 @@ try { | `SESSION_ENDED` | The session was closed, stopped, or expired, or Revyl answered 404 for the session itself | Close explicitly; computer expiry does not prove release | | `SESSION_BUSY` | A step conflict, computer operation limit, someone controlling a computer's screen in the Revyl viewer, or `recording()` on a computer you haven't closed | Inspect the state before another call; a terminal computer alone does not prove release | | `COMPUTER_LIMIT` | Computer admission was refused due to queued work (including iOS) or the concurrency limit | Wait for capacity; Verify does not retry or stop a definitely refused start | -| `NOT_AVAILABLE_ON_PLATFORM` | The call is unavailable: computer agent steps, device shell/file/recording methods, an exact action the platform lacks (such as `back()` on iOS, `goHome()` or `launchApp()` on Web, `typeFocused()` or keys other than Enter and Backspace on iOS and Android), computer access or runtime unavailable, or a backend without web steps | See [web.md](web.md) and [computers.md](computers.md#availability-and-errors) | +| `NOT_AVAILABLE_ON_PLATFORM` | The call is unavailable: `instruction()` on a computer, `validation()` or `extract()` on a Mac without its own model or on Linux, local inference or persistent computers not enabled for the organization, device shell/file/recording methods, an exact action the platform lacks (such as `back()` on iOS, `goHome()` or `launchApp()` on Web, `typeFocused()` or keys other than Enter and Backspace on iOS and Android), computer access or runtime unavailable, or a backend without web steps | See [web.md](web.md) and [computers.md](computers.md#availability-and-errors) | | `COMMAND_FAILED` | A computer command exited nonzero | Read its reason; use `exec(argv, { check: false })` to inspect the exit code and output instead | | `NOT_FOUND` | A computer file or resource was not found | Check the workspace-relative path | | `ACCESS_DENIED` | The computer refused access | Check permissions; do not assume host/root access | @@ -98,7 +103,7 @@ Any other refusal of a computer request names its reason and what to do next: `r ## Troubleshooting -- **`NOT_AVAILABLE_ON_PLATFORM`:** the requested method is not available for that target. Computer targets do not run instruction or validation steps or `locate()`; Web and mobile targets do not expose computer commands or files. +- **`NOT_AVAILABLE_ON_PLATFORM`:** the requested method is not available for that target. Computers don't run `instruction()` or `locate()`; use `tap({ target })` and `type({ target }, text)`. `validation()` and `extract()` run only on a Mac opened with `inference: true` ([guide](guides/mac-model-checks.md)). Web and mobile targets do not expose computer commands or files. Read `error.reason` for the exact refusal. - **`COMPUTER_LIMIT`:** computer admission was refused because of queued work or a concurrency limit. Verify does not retry creation or stop a definitely refused start. - **Blank first screen:** mobile startup uses a bounded, best-effort blank-frame observation, not a rendered-readiness guarantee. Begin with an instruction that reaches the screen your workflow needs. See [mobile.md](mobile.md#steps). - **A validation report looks successful but the assertion failed:** inspect each step's `effective_status` and `validation_result`, and compare `validations_passed` with `total_validations` rather than transport counters. See [reading the verdict](end-to-end.md#reading-the-verdict). diff --git a/packages/verify/docs/getting-started.md b/packages/verify/docs/getting-started.md index b830d55..7acd939 100644 --- a/packages/verify/docs/getting-started.md +++ b/packages/verify/docs/getting-started.md @@ -86,7 +86,7 @@ The generated iOS and Android targets open Settings. To test your own app, repla - **Web:** create a Web app in Revyl (see [web.md](web.md#create-the-web-app)) and set `app.url` to a public HTTPS URL. Revyl's cloud browser cannot reach `localhost`. - **iOS and Android:** upload a build to the app in Revyl, for example with `revyl build upload`; each session installs the newest one. See [mobile.md](mobile.md). -- **Mac:** computers are available to organizations on a current paid Revyl plan. Agent instruction/validation are unavailable. See [computers.md](computers.md#availability-and-errors). +- **Mac:** computers are available to organizations on a current paid Revyl plan. `instruction()` is unavailable there; `validation()` and `extract()` work on a Mac opened with `inference: true`. See [computers.md](computers.md#availability-and-errors). ## Run the script diff --git a/packages/verify/docs/guides/apps-inside-an-inference-mac.md b/packages/verify/docs/guides/apps-inside-an-inference-mac.md new file mode 100644 index 0000000..1426bf7 --- /dev/null +++ b/packages/verify/docs/guides/apps-inside-an-inference-mac.md @@ -0,0 +1,110 @@ +# Test an iOS or Web app inside an inference Mac + +**New in TypeScript 0.8.0, Python 0.6.0 and Go v0.7.0.** A Mac computer can host iOS and Web app sessions with `computer.open(target)`. When the Mac was opened with `inference`, those sessions run their steps on the Mac's own vision model first, with Revyl's hosted model as the fallback. That is the default; you don't pass anything for it. + +Local inference is enabled per organization, on top of Mac computers. Without it, opening the Mac with `inference` throws `NOT_AVAILABLE_ON_PLATFORM` with reason `inference_not_enabled`; ask [support@revyl.ai](mailto:support@revyl.ai). + +## What it costs + +App sessions inside a computer add no device minutes of their own: you pay the Mac's minutes. Steps the Mac's model answers carry no inference charge. Steps that go to Revyl's hosted model, listed below, are billed as they are on any session. + +## Open the app inside the Mac + +You need an app and build in Revyl, as for any hosted session: its `appId` and `buildId`. + +TypeScript: + +```ts +import { open } from '@revyl/verify'; + +const mac = await open({ platform: 'mac', inference: true }); +try { + const app = await mac.open({ platform: 'ios', app: { appId: process.env.IOS_APP_ID!, buildId: process.env.IOS_BUILD_ID! } }); + try { + const check = await app.validation('The sign-in screen is showing'); + console.log(check.passed, check.engine); // true 'local' + await app.instruction('Tap the Sign in button'); // one tap: the Mac's model first + await app.type({ target: 'the email field' }, 'user@example.com'); // exact actions work as usual + const greeting = await app.extract('the greeting at the top'); // extract: Revyl's hosted model + console.log(greeting.value, greeting.engine); // ... 'hosted' + } finally { + await app.close(); + } +} finally { + await mac.close(); +} +``` + +Python: + +```python +import os + +from revyl_verify import Target, open + +with open(Target(platform="mac", inference=True)) as mac: + app = mac.open(Target(platform="ios", app_id=os.environ["IOS_APP_ID"], build_id=os.environ["IOS_BUILD_ID"])) + try: + check = app.validation("The sign-in screen is showing") + print(check.passed, check.engine) # True local + app.instruction("Tap the Sign in button") + greeting = app.extract("the greeting at the top") + print(greeting.value, greeting.engine) # ... hosted + finally: + app.close() +``` + +Go: + +```go +mac, err := verify.Open(ctx, verify.Target{Platform: verify.Mac, Inference: new(true)}) +if err != nil { + return err +} +defer mac.Close(context.Background()) +app, err := mac.Open(ctx, verify.Target{Platform: verify.IOS, AppID: os.Getenv("IOS_APP_ID"), BuildID: os.Getenv("IOS_BUILD_ID")}) +if err != nil { + return err +} +defer app.Close(context.Background()) +check, err := app.Validation(ctx, "The sign-in screen is showing") +if err != nil { + return err +} +fmt.Println(check.Passed, check.Engine) // true local +``` + +Close the app session before the Mac, or just close the Mac: closing it closes the sessions inside it. + +## Which steps run on the Mac's model + +| Step | Who answers | +| --- | --- | +| `validation()` | The Mac's model first | +| `instruction()` that is a single tap on one thing, such as `'Tap the Sign in button'` | The Mac's model first | +| `instruction()` that does more, such as typing or `'Scroll down and then tap Back'` | Revyl's hosted model | +| `extract()` | Revyl's hosted model, so it is billed as usual. `extract()` on the Mac itself reads the Mac's own screen, not the app's | +| A step the Mac's model can't answer with confidence, or doesn't answer within 25 seconds | Falls back to Revyl's hosted model | +| Exact actions (`tap`, `type`, `swipe` and the rest) | No model; they run as on any session | + +Every `StepResult` has `engine`: `'local'` when the Mac's model answered and `'hosted'` when Revyl's hosted model did. A session not opened inside an inference Mac leaves it out (Python `None`, Go `""`). Within a session inside an inference Mac, a local answer the Mac's model isn't sure of goes to the hosted model, so a soft validation still comes back passed or failed. + +A verdict the Mac's model gives is final: a validation it passes or fails isn't checked again by the hosted model. If a check matters more than its speed, run that session with the hosted model, as below. + +## Turn it off for one session + +Pass `inference: false` to `computer.open()` (Python `Target(..., inference=False)`, Go `Inference: new(false)`), and that session's steps run on Revyl's hosted model as they do outside a computer: + +```ts +const app = await mac.open({ platform: 'ios', inference: false, app: { appId, buildId } }); +``` + +Sessions inside a Mac opened without `inference` always use the hosted model. Macs host iOS and Web sessions; Android sessions don't run inside a Mac. + +## When the Mac's model is down + +If the Mac's model isn't answering when the app session starts, Revyl refuses the start instead of quietly using the hosted model: `computer.open()` throws `NOT_AVAILABLE_ON_PLATFORM` with reason `computer_local_inference_unavailable`, and nothing was started. Check `mac.inference` (Python `mac.inference`, Go `mac.Inference()`), try again shortly, or open the session with `inference: false` to run it on the hosted model. + +The Mac's model answers one step at a time, shared by the Mac and every session inside it. Run one step at a time per computer. + +See [computers.md](../computers.md#lifecycle-and-transport) for how hosted sessions start and stop, and [checks on the Mac's own screen](mac-model-checks.md) to use the same model on the Mac itself. diff --git a/packages/verify/docs/guides/mac-model-checks.md b/packages/verify/docs/guides/mac-model-checks.md new file mode 100644 index 0000000..a3c33e2 --- /dev/null +++ b/packages/verify/docs/guides/mac-model-checks.md @@ -0,0 +1,98 @@ +# Check a Mac's screen with its own model + +**New in TypeScript 0.8.0, Python 0.6.0 and Go v0.7.0.** A Mac computer opened with `inference` runs on a Revyl Mac that has its own vision model. `validation()` checks a statement against the Mac's screen and `extract()` reads a value off it, and that model answers both, next to the computer, in about 2 to 3 seconds. + +Local inference is enabled per organization, on top of Mac computers. If yours doesn't have it, opening the Mac throws `NOT_AVAILABLE_ON_PLATFORM` with reason `inference_not_enabled`; ask [support@revyl.ai](mailto:support@revyl.ai) to turn it on. + +## What it costs + +Steps on a computer have no per-step fee. `validation()` and `extract()` on a Mac run only on that Mac's own model, so they carry no inference charge: you pay the Mac's minutes, as for any computer. + +## Open the Mac and check its screen + +TypeScript: + +```ts +import { open } from '@revyl/verify'; + +const mac = await open({ platform: 'mac', inference: true }); +try { + console.log('Model:', mac.inference); // 'ready', 'unavailable' or 'unknown' + await mac.validation('The Dock is visible at the bottom of the screen'); // throws VALIDATION_FAILED if not + const date = await mac.extract('the date at the right end of the menu bar'); + console.log(date.value, date.engine); // e.g. 'Thu Nov 26' 'local' +} finally { + await mac.close(); +} +``` + +Python: + +```python +from revyl_verify import Target, open + +with open(Target(platform="mac", inference=True)) as mac: + print("Model:", mac.inference) # "ready", "unavailable" or "unknown" + mac.validation("The Dock is visible at the bottom of the screen") # raises VALIDATION_FAILED if not + date = mac.extract("the date at the right end of the menu bar") + print(date.value, date.engine) # e.g. Thu Nov 26 local +``` + +Go (`new(true)` needs Go 1.26, which the module already requires): + +```go +mac, err := verify.Open(ctx, verify.Target{Platform: verify.Mac, Inference: new(true)}) +if err != nil { + return err +} +defer mac.Close(context.Background()) +fmt.Println("Model:", mac.Inference()) // ready, unavailable or unknown +if _, err := mac.Validation(ctx, "The Dock is visible at the bottom of the screen"); err != nil { + return err // ErrValidationFailed if not +} +date, err := mac.Extract(ctx, "the date at the right end of the menu bar") +if err != nil { + return err +} +fmt.Println(date.Value, date.Engine) // e.g. Thu Nov 26 local +``` + +Runnable versions: [examples/mac-inference](https://github.com/RevylAI/verify/tree/main/examples/mac-inference), [python/examples/mac_inference.py](https://github.com/RevylAI/verify/blob/main/python/examples/mac_inference.py) and [go/examples/macinference](https://github.com/RevylAI/verify/tree/main/go/examples/macinference). + +## Check the result of your own commands + +The model reads the screen, so pair it with `exec()` and the screen calls. Open something, then check what is on screen: + +```ts +await mac.writeFile('notes.txt', 'Release notes for 2.4\n'); +await mac.exec(['open', '-a', 'TextEdit', 'notes.txt']); +await new Promise((resolve) => setTimeout(resolve, 3_000)); // let the window open +await mac.validation('A TextEdit window shows the text "Release notes for 2.4"'); +const title = await mac.extract('the title of the frontmost window'); +``` + +To check without throwing, pass `{ soft: true }` (Python `soft=True`, Go `verify.ValidationOptions{Soft: true}`) and read `passed`. + +## Write steps the model can answer + +- **One statement or one value per step.** `'The Save button is enabled'`, not `'The file saved and the button is enabled'`. For `extract()`, describe one value that is on the screen now, such as `'the version number in the About window'`. +- **Run one step at a time per computer.** The Mac's model answers one step at a time, shared with the app sessions inside the computer. Await each step before the next. +- **An answer the model can't confirm is never a pass.** When it can't decide, or `extract()` finds nothing, the step throws `STEP_FAILED` with the model's reason, such as `local_model_found_no_value`. Change the description, or take a `screenshot()` to see what was on the screen. +- **`instruction()` stays off on computers.** To click one thing by its description, use `tap({ target: 'the Save button' })`; to type into a field, use `type({ target: 'the search field' }, text)`. Python: `tap("the Save button")` and `type("the search field", text)`. Go: `Tap(ctx, verify.Element("the Save button"))` and `Type(ctx, verify.Element("the search field"), text)`. + +## When the model isn't there + +`inference` on the computer (Python `inference`, Go `Inference()`) is `'ready'` when its model answered when Verify last read the computer's report, `'unavailable'` when it didn't, and `'unknown'` while that can't be told yet. Verify reads the report when the computer opens and on each `report()`; in our runs it read `'ready'` as soon as `open()` returned. On a computer opened without inference it is `undefined` (Python `None`, Go `""`). + +`error.reason` holds the code for every refusal below except the two `SESSION_BUSY` rows, whose message names it. + +| What happened | Error and code | What to do | +| --- | --- | --- | +| Your organization doesn't have local inference | `NOT_AVAILABLE_ON_PLATFORM`, `inference_not_enabled`, when opening | Ask support@revyl.ai, or open the Mac without `inference` | +| No Mac with a model is free right now | `NOT_AVAILABLE_ON_PLATFORM`, `inference_unavailable`, when opening; nothing was started | Try again later, or open the Mac without `inference` | +| `validation()` or `extract()` on a Mac opened without `inference`, or its model stopped answering | `NOT_AVAILABLE_ON_PLATFORM`, `step_engine_unavailable`; the step didn't run | Open the Mac with `inference`; if it was, check `inference` and try again shortly | +| The model was busy with another step for too long | `SESSION_BUSY`, `step_engine_busy` | Run one step at a time, and try again in a few seconds | +| Someone controls the screen in the Revyl viewer | `SESSION_BUSY`, `screen_control_held` | Try again after they release it | +| A Linux computer | `NOT_AVAILABLE_ON_PLATFORM` before anything is sent | Use a Mac | + +See [computers.md](../computers.md) for everything else a computer does, and [apps inside an inference Mac](apps-inside-an-inference-mac.md) to run an iOS or Web app's steps on the same model. diff --git a/packages/verify/docs/guides/persistent-computers.md b/packages/verify/docs/guides/persistent-computers.md new file mode 100644 index 0000000..55fc5b8 --- /dev/null +++ b/packages/verify/docs/guides/persistent-computers.md @@ -0,0 +1,182 @@ +# Keep a Mac between runs: persistent computers and snapshots + +A Mac from `open({ platform: 'mac' })` is deleted when it closes. A **persistent computer** keeps its whole disk instead: `openPersistent(name)` opens it, `close()` stops it and saves the disk, and the next `openPersistent(name)` boots from that disk, from any machine and from TypeScript, Python or Go. A **snapshot** names a stopped computer's saved disk, so new persistent computers can start from it. + +The calls are in TypeScript since 0.7.0, Python (`open_persistent` and the rest) since 0.5.0 and Go (`OpenPersistent` and the rest) since v0.6.0. Persistent computers and snapshots are enabled per organization. Without them, `openPersistent()` and `saveSnapshot()` throw `NOT_AVAILABLE_ON_PLATFORM` with reason `persistent_computers_not_enabled`; ask [support@revyl.ai](mailto:support@revyl.ai) to turn them on. + +## What is kept, and what isn't + +| Kept on the same computer | Not kept | +| --- | --- | +| Everything on the disk: files, repositories, installed tools such as Homebrew packages, build products, simulators, app data, system settings, browser profiles and the login keychain | Memory and running processes. Every open is a cold boot, so start your servers again | + +A computer started from a snapshot gets the same disk, except what is tied to the original Mac's hardware: Apple Account, iCloud and Safari's saved passwords don't carry over, and websites may open signed out. Anyone in your organization who can open computers can use what a snapshot holds, so don't snapshot a disk with secrets you wouldn't share with them. + +## Lifetime, cost and limits + +- **Stop and reopen.** `close()` returns once the disk is saved on its Mac, so you can reopen or delete the computer right away. If you reopen while a stop is still finishing, `openPersistent()` waits for it, within `startTimeout`. +- **Runs.** Each open is a new run with the usual computer lifetime: 2 hours by default, up to 24 hours with `timeoutMs` (Python `timeout` in seconds, Go `Timeout`), and `extend()` works as on any computer. A run starts saving its disk 3 minutes before it ends, and reaching the end keeps the disk, as `close()` does. +- **Cost.** A running persistent computer bills its minutes like any Mac. It costs nothing while stopped; Revyl doesn't charge for stored disks and snapshots while persistent computers are in limited preview. +- **How long a save lasts.** A computer's disk is kept until you delete the computer, and a snapshot until you delete it. A few saves have an end: `savedDiskExpiresAt` on `listPersistent()` and `listSnapshots()` entries (Python `saved_disk_expires_at`, Go `SavedDiskExpiresAt`) says when, if Revyl reports one. From then on that save can't start a computer, and opening it throws `SESSION_START_FAILED` (`saved_disk_expired` or `snapshot_expired`). +- **Limits.** An organization keeps at most 10 persistent computers and 100 snapshots unless Revyl raised its limits (`COMPUTER_LIMIT`, reason `persistent_computer_limit` or `snapshot_limit`). Persistent computers are Macs only. +- **Names.** 1 to 64 letters, digits, `.`, `_` or `-`, starting with a letter or digit. The same name opens the same computer from every language and machine. Revyl stores IDs, not names, so `listPersistent()` shows each computer's `id`; compare it with the `id` of the session `openPersistent()` returned. You can pass that ID instead of the name. + +## Use case: a dev environment you set up once + +Install the tools once, then reuse them in every run. Mark the setup as done on the disk itself, so a setup that failed halfway runs again: + +```ts +import { openPersistent } from '@revyl/verify'; + +const mac = await openPersistent('ios-dev'); // creates it the first time +try { + const ready = await mac.exec(['test', '-f', '.setup-done'], { check: false }); + if (ready.exitCode !== 0) { + await mac.exec(['/bin/zsh', '-lc', 'brew install swiftlint xcbeautify'], { timeout: 300_000 }); + await mac.exec(['git', 'clone', '--depth', '1', 'https://github.com/your-org/app', 'app'], { timeout: 300_000 }); + await mac.writeFile('.setup-done', 'v1\n'); + } + await mac.exec(['git', '-C', 'app', 'pull'], { timeout: 120_000 }); + const lint = await mac.exec(['/bin/zsh', '-lc', 'cd app && swiftlint'], { timeout: 300_000, check: false }); + console.log(lint.stdout); +} finally { + await mac.close(); // stops it and keeps the disk +} +``` + +`mac.created` is `true` when this call created the computer, but a marker file is the safer test. One command runs for at most 5 minutes (`timeout` up to 300000 ms), so split long setup into several commands. + +Python: + +```python +from revyl_verify import open_persistent + +with open_persistent("ios-dev") as mac: # leaving the block stops it and keeps the disk + if mac.exec(["test", "-f", ".setup-done"], check=False).exit_code != 0: + mac.exec(["/bin/zsh", "-lc", "brew install swiftlint xcbeautify"], timeout=300) + mac.write_file(".setup-done", "v1\n") + print(mac.exec(["/bin/zsh", "-lc", "swiftlint version"]).stdout) +``` + +Go: + +```go +mac, err := verify.OpenPersistent(ctx, "ios-dev") +if err != nil { + return err +} +defer mac.Close(context.Background()) // stops it and keeps the disk +ready, err := mac.Exec(ctx, []string{"test", "-f", ".setup-done"}, verify.ExecOptions{Check: new(false)}) +if err != nil { + return err +} +if ready.ExitCode != 0 { + if _, err := mac.Exec(ctx, []string{"/bin/zsh", "-lc", "brew install swiftlint xcbeautify"}, verify.ExecOptions{Timeout: 5 * time.Minute}); err != nil { + return err + } + if err := mac.WriteFile(ctx, ".setup-done", []byte("v1\n")); err != nil { + return err + } +} +``` + +## Use case: parallel runs from one prepared Mac + +Set a Mac up once, save it as a snapshot, then start a copy per shard. Each copy is its own persistent computer, so the runs don't touch each other: + +```ts +import { openPersistent, saveSnapshot, deletePersistent, isVerifyError } from '@revyl/verify'; + +// Once: after the setup run above has closed 'ios-dev'. +await saveSnapshot('ios-dev', 'ios-dev-base'); // waits until the save is copied off its Mac, about 5 minutes after close() + +// Every run: one copy per shard. +const shards = ['shard-1', 'shard-2']; +const opened = await Promise.allSettled(shards.map((name) => openPersistent(name, { fromSnapshot: 'ios-dev-base' }))); +try { + const macs = opened.map((result) => { if (result.status === 'rejected') throw result.reason; return result.value; }); + await Promise.all(macs.map((mac, i) => mac.exec(['/bin/zsh', '-lc', `cd app && ./run-tests.sh --shard ${i + 1}`], { timeout: 300_000 }))); +} finally { + for (const result of opened) if (result.status === 'fulfilled') await result.value.close(); + for (const name of shards) { + await deletePersistent(name).catch((error) => { if (!isVerifyError(error) || error.code !== 'NOT_FOUND') throw error; }); // copies count toward your 10 until deleted + } +} +``` + +- `Promise.allSettled` waits for every open, so when one copy fails, for example with `COMPUTER_LIMIT`, the copies that did open are still closed and deleted. +- `saveSnapshot()` needs a stopped computer: close it first, or it throws `SESSION_BUSY`. It waits until the save is copied off its Mac, up to `waitTimeout` (15 minutes by default), then throws `TIMEOUT`; calling it again keeps waiting. Snapshot names are unique in your organization. +- `fromSnapshot` is used only when the call creates the computer. If a computer with that name already exists, it opens as it is; check `created`. +- A copy usually starts on a different Mac than the one that saved the disk, so it restores the disk first and can take several minutes. `openPersistent()` waits up to `startTimeout`, 15 minutes by default. +- Each copy takes one of your organization's computer slots while it runs, so more shards than slots throw `COMPUTER_LIMIT`. + +Python: `save_snapshot("ios-dev", "ios-dev-base")`, then `open_persistent("shard-1", from_snapshot="ios-dev-base")` and `delete_persistent("shard-1")`. Go: `verify.SaveSnapshot(ctx, "ios-dev", "ios-dev-base")`, then `verify.OpenPersistent(ctx, "shard-1", verify.OpenPersistentOptions{FromSnapshot: "ios-dev-base"})` and `verify.DeletePersistent(ctx, "shard-1")`. + +## Use case: a browser that stays signed in + +Sign in to a site once, by hand, and the same computer opens signed in next time: + +1. `const mac = await openPersistent('signed-in-safari')`, then `await mac.exec(['open', '-a', 'Safari', 'https://app.example.com/login'])`. +2. Open `mac.viewerUrl` in your browser, take control of the screen, and sign in. Signing in by hand keeps the password out of your script and its logs. +3. `await mac.close()`. The next `openPersistent('signed-in-safari')` boots with Safari's cookies where you left them. + +This holds for that computer only. Copies started from a snapshot of it may open websites signed out, and Safari's saved passwords don't carry over. Sites still end sessions on their own schedule. + +## Use case: a long-running workspace for an agent + +Give a coding agent one Mac that keeps its checkout, build products and simulators between sessions: + +```ts +const mac = await openPersistent('agent-workspace', { timeoutMs: 8 * 60 * 60 * 1000 }); // 8 hours for this run +try { + // ... the agent works through exec(), the screen calls and, on an inference Mac, validation() ... + await mac.extend(4 * 60 * 60 * 1000); // needs longer: keep it 4 more hours from now +} finally { + await mac.close(); +} +``` + +Every open is a cold boot, so the agent's first step each session is to start what it needs again. A run lasts at most 24 hours from when it opened. Lifetimes over 2 hours can be refused with `COMPUTER_LIMIT` (`computer_long_limit`) when your organization already has 2 such computers running. + +## With local inference + +`inference: true` on `openPersistent()` (Python `inference=True`, Go `Inference: true`) is used only when the call creates the computer, and the computer keeps it on every later start (passing it again on a reopen changes nothing, and `inference` on the session reads the model's readiness either way), so `validation()` and `extract()` work on it as described in [checks on the Mac's own screen](mac-model-checks.md): + +```ts +const mac = await openPersistent('checked-dev', { inference: true }); +await mac.validation('The Dock is visible at the bottom of the screen'); +``` + +- A copy from a snapshot doesn't take the source computer's setting: pass `inference: true` with `fromSnapshot` when you want the model on it. +- When no Mac with a model is up, starting the computer throws `NOT_AVAILABLE_ON_PLATFORM` (`inference_unavailable`) and nothing starts. To start that one run without the model, pass `withoutInference: true` (Python `without_inference=True`, Go `WithoutInference: true`); later starts ask for the model again. A Revyl backend that doesn't offer it yet throws `INVALID_ARGUMENT` saying so. + +## Clean up + +```ts +import { deletePersistent, deleteSnapshot, listPersistent, listSnapshots } from '@revyl/verify'; + +console.log(await listPersistent()); // [{ id, state, savedAt?, savedOffHost, createdAt, savedDiskExpiresAt? }] +console.log(await listSnapshots()); // [{ id, name, computerId, savedAt, expiresAt?, savedDiskExpiresAt? }] +await deletePersistent('ios-dev'); // the computer and its disk, for good; a running one stops first, without saving +await deleteSnapshot('ios-dev-base'); // computers already started from it keep their disks +``` + +Deleting a computer keeps its snapshots, and deleting a snapshot keeps the computers made from it. Both throw `NOT_FOUND` when there is nothing by that name or ID, so cleanup that runs twice should catch it. Python: `list_persistent()`, `list_snapshots()`, `delete_persistent()`, `delete_snapshot()`. Go: `ListPersistent`, `ListSnapshots`, `DeletePersistent`, `DeleteSnapshot`. + +## Errors + +`error.reason` is set for `persistent_computers_not_enabled`; for the other refusals the message names the code in parentheses. + +| What happened | Error and code | What to do | +| --- | --- | --- | +| Persistent computers aren't enabled for your organization | `NOT_AVAILABLE_ON_PLATFORM`, reason `persistent_computers_not_enabled` | Ask support@revyl.ai | +| The computer's last run hasn't finished saving | `SESSION_BUSY` (`run_conflict`) | Try again in a few minutes; the disk is kept | +| `saveSnapshot()` on a running computer | `SESSION_BUSY` | `close()` it first | +| The save isn't copied off its Mac within `waitTimeout` | `TIMEOUT` | Call `saveSnapshot()` again | +| The snapshot name is taken | `INVALID_ARGUMENT` | Pick another name or delete the old snapshot | +| The Mac holding a save is offline and the save isn't copied yet | `SESSION_START_FAILED` (`saved_disk_unavailable`) | Try again later; the disk is kept | +| A save has reached its end | `SESSION_START_FAILED` (`saved_disk_expired`, `snapshot_expired`) | Delete the computer and create a new one, or save a new snapshot | +| 10 computers or 100 snapshots already | `COMPUTER_LIMIT` | Delete ones you no longer need | +| No computer or snapshot by that name or ID | `NOT_FOUND` | Check `listPersistent()` or `listSnapshots()` | + +See [computers.md](../computers.md) for everything a computer does while it runs. diff --git a/packages/verify/docs/llms.txt b/packages/verify/docs/llms.txt index 3e67f12..d67ab45 100644 --- a/packages/verify/docs/llms.txt +++ b/packages/verify/docs/llms.txt @@ -1,23 +1,29 @@ # Verify -> Verify (@revyl/verify) is an open-source TypeScript library for Revyl. It opens cloud browsers and iOS/Android devices for agent instruction/validation steps, or Mac computers for commands, files, processes, screenshots, clicks and keys on the screen, and the private screen recording after close. Call it from a plain script, coding agent, CI, or any test runner. It has no test runner of its own. +> Verify (@revyl/verify) is an open-source TypeScript library for Revyl. It opens cloud browsers and iOS/Android devices for agent instruction/validation/extract steps, or Mac computers for commands, files, processes, screenshots, clicks and keys on the screen, checks answered by the Mac's own vision model, and the private screen recording after close. Call it from a plain script, coding agent, CI, or any test runner. It has no test runner of its own. ## Docs Mac computers are available to organizations on a current paid Revyl plan. See computers.md#availability-and-errors. - [Getting started](getting-started.md): install, authenticate, init, run a script -- [API](api.md): open() and session profiles (Revyl runs a profile from .revyl/config.yaml before open() returns), attach(), hosted children, navigate(), cdp() for Playwright and Puppeteer on web, report(), agent steps, screenshot(), exec(), file/process methods, close() +- [API](api.md): open() and session profiles (Revyl runs a profile from .revyl/config.yaml before open() returns), attach(), hosted children, navigate(), cdp() for Playwright and Puppeteer on web, report(), agent steps, extract(), screenshot(), exec(), file/process methods, close(), persistent computers - [Configuration](configuration.md): verify.config.ts targets, environment variables, the init and whoami commands - [Web](web.md): Revyl web sessions, URLs and builds, sign-in, steps, and exact actions - [Mobile](mobile.md): iOS and Android devices, installing apps, and exact actions -- [Computers](computers.md#availability-and-errors): Mac availability, commands and files, the screen (clicks, typing and keys), expiry, capacity errors, recording metadata, and confirmed release +- [Computers](computers.md#availability-and-errors): Mac availability, commands and files, the screen (clicks, typing and keys), validation() and extract() on a Mac opened with inference, app sessions inside a Mac, persistent computers, expiry, capacity errors, recording metadata, and confirmed release - [Verify working end to end](end-to-end.md): live verification scope, observed outcomes, and limits of the evidence - [CI and test runners](ci.md): GitHub Actions, node:test, Vitest, Jest, Playwright Test - [Use your own model](own-model.md): run instructions and validations on Claude, GPT, Gemini, a local model or any OpenAI-compatible endpoint; providers, limits, privacy and troubleshooting - [Errors](errors.md): every error code and what to do about it - [For coding agents](agents.md): the workflow and rules for agents using Verify, and the coordinate rule for exact actions +## Guides + +- [Checks on a Mac's own model](guides/mac-model-checks.md): open({ platform: 'mac', inference: true }), then validation() and extract() answered by the Mac's vision model, with no inference charge; readiness and refusals +- [Apps inside an inference Mac](guides/apps-inside-an-inference-mac.md): iOS and Web sessions from computer.open() run validations and single-tap instructions on the Mac's model first by default; engine, opt-out with inference: false, billing +- [Persistent computers and snapshots](guides/persistent-computers.md): openPersistent(), saveSnapshot(), fromSnapshot copies, what is kept, lifetimes, limits, cleanup, and use cases + ## Exact actions and coordinates Prefer a description, such as `tap({ target: 'Sign in button' })`: Revyl finds the element on the current screen, and you never handle coordinates. Otherwise a point is `{ x, y }` in screenshot pixels on every platform: whole numbers from the top-left corner of the image `screenshot()` returns. So a position you read off a screenshot goes to `tap()`, `type()`, `swipe()` and every other exact action unchanged. `screenSize()` returns the screenshot's width and height, and `locate()` and the points `tap()`, `doubleTap()`, `longPress()` and `type()` return use the same pixels. A point outside the screenshot is refused with `INVALID_ARGUMENT` before any action is sent, and the message names the valid range. On iOS, Verify converts the pixels to the screen's points for you. On Web they equal CSS pixels at the default device scale factor of 1, and you still pass screenshot pixels at any other. This holds from TypeScript 0.4.1, Python 0.2.1 and Go v0.3.1; earlier versions took iOS points. On a Mac computer a point is in screenshot pixels too, and `tap({ target })` returns the point it clicked in the same pixels. Verify refuses a negative or fractional point before sending it, and Revyl refuses one past the screen's edge without clicking; both throw `INVALID_ARGUMENT` naming the valid range. See [For coding agents](agents.md#exact-actions-and-coordinates) for a runnable example. diff --git a/packages/verify/docs/mobile.md b/packages/verify/docs/mobile.md index c3e7847..b72ab15 100644 --- a/packages/verify/docs/mobile.md +++ b/packages/verify/docs/mobile.md @@ -114,7 +114,8 @@ On Android, `back()` presses the system back button. On both platforms, `goHome( | `openUrl(url)` | Yes, loads an http(s) URL in the tab | Yes, a URL or deep link | Yes, a URL or deep link | No | | `launchApp(bundleId)` | No, use `openUrl` or `navigate` | Yes | Yes | No | | `navigate(url)` | Yes | No, use `openUrl` | No, use `openUrl` | No | -| `instruction`, `validation`, your own model | Yes | Yes | Yes | No, use `exec()` and the screen calls above | +| `instruction`, your own model | Yes | Yes | Yes | No, use `tap({ target })`, `type({ target }, text)` and `exec()` | +| `validation`, `extract` | Yes | Yes | Yes | Yes, on a Mac opened with `inference: true`; see [computers.md](computers.md#checks-on-the-macs-own-model) | | `screenshot()` | Yes | Yes | Yes | Yes | | `exec`, files, processes | No, open a Mac computer | No, open a Mac computer | No, open a Mac computer | Yes | diff --git a/packages/verify/docs/own-model.md b/packages/verify/docs/own-model.md index 4d90849..38cd54c 100644 --- a/packages/verify/docs/own-model.md +++ b/packages/verify/docs/own-model.md @@ -1,6 +1,6 @@ # Use your own model -**Early access.** Since TypeScript (`@revyl/verify`) 0.4.0, Python (`revyl-verify`) 0.2.0 and Go v0.3.0; the [Python](https://github.com/RevylAI/verify/blob/v0.7.1/python/README.md#your-own-model) and [Go](https://github.com/RevylAI/verify/blob/v0.7.1/go/README.md#your-own-model) READMEs show them with each language's names. Verify normally runs `instruction()` and `validation()` on Revyl's agent. Pass a `model` and the agent loop runs in your process instead, on a model you choose, with your own key. Revyl still provides the cloud browser or device and, by default, finds the elements your model names on screen. +**Early access.** Since TypeScript (`@revyl/verify`) 0.4.0, Python (`revyl-verify`) 0.2.0 and Go v0.3.0; the [Python](https://github.com/RevylAI/verify/blob/v0.8.0/python/README.md#your-own-model) and [Go](https://github.com/RevylAI/verify/blob/v0.8.0/go/README.md#your-own-model) READMEs show them with each language's names. Verify normally runs `instruction()` and `validation()` on Revyl's agent. Pass a `model` and the agent loop runs in your process instead, on a model you choose, with your own key. Revyl still provides the cloud browser or device and, by default, finds the elements your model names on screen. Use it when you want a specific model, your own prompts and key, or faster steps on a cheap model. Leave `model` out and nothing changes. @@ -52,7 +52,7 @@ log.Println(step.Model.ID, len(step.Model.Turns), step.Model.InputTokens, step.M _, err = s.Validation(ctx, "The screen shows the iOS version") ``` -The [Python](https://github.com/RevylAI/verify/blob/v0.7.1/python/README.md#your-own-model) and [Go](https://github.com/RevylAI/verify/blob/v0.7.1/go/README.md#your-own-model) READMEs have the full reference for each. +The [Python](https://github.com/RevylAI/verify/blob/v0.8.0/python/README.md#your-own-model) and [Go](https://github.com/RevylAI/verify/blob/v0.8.0/go/README.md#your-own-model) READMEs have the full reference for each. Set `model` on `open()` to run every step on it, or on one step to override it: diff --git a/packages/verify/docs/web.md b/packages/verify/docs/web.md index 11f4588..18b287e 100644 --- a/packages/verify/docs/web.md +++ b/packages/verify/docs/web.md @@ -118,7 +118,8 @@ try { | `openUrl(url)` | Yes, loads an http(s) URL in the tab | Yes, a URL or deep link | Yes, a URL or deep link | No | | `launchApp(bundleId)` | No, use `openUrl` or `navigate` | Yes | Yes | No | | `navigate(url)` | Yes | No, use `openUrl` | No, use `openUrl` | No | -| `instruction`, `validation`, your own model | Yes | Yes | Yes | No, use `exec()` and the screen calls above | +| `instruction`, your own model | Yes | Yes | Yes | No, use `tap({ target })`, `type({ target }, text)` and `exec()` | +| `validation`, `extract` | Yes | Yes | Yes | Yes, on a Mac opened with `inference: true`; see [computers.md](computers.md#checks-on-the-macs-own-model) | | `screenshot()` | Yes | Yes | Yes | Yes | | `exec`, files, processes | No, open a Mac computer | No, open a Mac computer | No, open a Mac computer | Yes | diff --git a/packages/verify/package.json b/packages/verify/package.json index f1e3a39..26350aa 100644 --- a/packages/verify/package.json +++ b/packages/verify/package.json @@ -1,6 +1,6 @@ { "name": "@revyl/verify", - "version": "0.7.1", + "version": "0.8.0", "description": "Open Revyl cloud browsers and mobile devices for agent steps, or Mac computers for commands and files, from TypeScript.", "keywords": [ "e2e", diff --git a/packages/verify/src/api/client.ts b/packages/verify/src/api/client.ts index f4ffc59..5eae612 100644 --- a/packages/verify/src/api/client.ts +++ b/packages/verify/src/api/client.ts @@ -284,7 +284,7 @@ const REFUSAL_REASONS = new Set([ 'computer_at_capacity', 'computer_platform_at_capacity', 'computer_not_running', 'computer_cannot_host_platform', 'computer_not_found', 'web_build_required', 'web_build_not_supported', 'ios_build_required', 'ios_build_not_supported', 'android_build_required', 'android_build_not_supported', 'web_session_conflict', 'ios_session_conflict', - 'android_session_conflict', 'not_available_on_platform', 'request_timeout', 'protocol_error', + 'android_session_conflict', 'not_available_on_platform', 'request_timeout', 'protocol_error', 'computer_local_inference_unavailable', ]); const START_ERROR_DETAILS = new Set([ diff --git a/packages/verify/src/api/types.ts b/packages/verify/src/api/types.ts index 59f1c19..6fff2c8 100644 --- a/packages/verify/src/api/types.ts +++ b/packages/verify/src/api/types.ts @@ -31,6 +31,7 @@ export interface StartDeviceRequest { session_profile?: SessionProfileFields['session_profile']; session_profile_source?: SessionProfileFields['session_profile_source']; session_profile_files?: SessionProfileFields['session_profile_files']; + inference?: 'local'; } export interface StartDeviceResponse { @@ -120,7 +121,7 @@ export interface WorkerActionResult { error?: string | null; } -export type LiveStepType = 'instruction' | 'validation'; +export type LiveStepType = 'instruction' | 'validation' | 'extract'; export interface LiveStepOutput { status?: 'success' | 'warning' | 'failed' | null; @@ -128,6 +129,9 @@ export interface LiveStepOutput { /** The verdict of a validation step. Revyl reports a validation that ran as status 'success', whatever its verdict. */ validation_result?: boolean | null; reasoning?: string | null; + extracted_data?: { information?: string | null } | null; + /** Who answered a step of a session started with local inference inside a computer. */ + engine?: 'local' | 'hosted' | null; } export interface LiveStepResult { @@ -166,6 +170,20 @@ export interface ComputerReport { release: 'pending' | 'confirmed' | 'unknown'; failure_reason?: string | null; expires_at?: string | null; + /** Only on a computer created with inference: whether its host's own vision model answers now. */ + inference?: ComputerInferenceReadiness | null; +} + +export type ComputerInferenceReadiness = 'ready' | 'unavailable' | 'unknown'; + +export interface ComputerStepResponse { + step_type: string; + success: boolean; + status: 'passed' | 'failed' | 'uncertain'; + status_reason?: string | null; + validation_result?: boolean | null; + extracted_data?: { information: string } | null; + engine: 'local' | 'hosted'; } export interface ComputerRecordingResponse { diff --git a/packages/verify/src/computer-session.ts b/packages/verify/src/computer-session.ts index d18cd69..8c9702e 100644 --- a/packages/verify/src/computer-session.ts +++ b/packages/verify/src/computer-session.ts @@ -3,20 +3,20 @@ import { mkdir, writeFile } from 'node:fs/promises'; import { dirname, resolve } from 'node:path'; import { setTimeout as delay } from 'node:timers/promises'; import { RevylClient, edgeBlockedError, macUpgradeMessage, responseDetail, responseErrorCode, responseRefusalReason, sessionViewerUrl, type RawResponse } from './api/client.js'; -import type { ComputerCommand, ComputerCommandResponse, ComputerPlatform, ComputerRecordingResponse, ComputerReport, ComputerResult, ComputerScreenshot } from './api/types.js'; +import type { ComputerCommand, ComputerCommandResponse, ComputerInferenceReadiness, ComputerPlatform, ComputerRecordingResponse, ComputerReport, ComputerResult, ComputerScreenshot, ComputerStepResponse } from './api/types.js'; import { trackSession, untrackSession } from './cleanup.js'; import { validateHostedTarget, type HostedTargetConfig, type ResolvedComputerTarget } from './config.js'; import { VerifyError, isVerifyError, type VerifyErrorCode } from './errors.js'; import { missingBranchNotice, profileFailedError, profileNotReportedError, profileRefusalError, reportedSessionProfile, withRepositoryRetry } from './session-profile.js'; import { WEB_KEYS, checkKey, type Key, type KeyModifier, type Location, type Point } from './agent/loop.js'; -import { CDP_WEB_ONLY, DeviceSession, checkLocation, checkSettle, pngSize, type ActionOptions, type CDPEndpoint, type ComputerProcess, type ComputerRecording, type ExecOptions, type ExecResult, type FileStat, type OpenedSession, type OperationOptions, type Session, type SessionOptions, type StepResult } from './session.js'; +import { CDP_WEB_ONLY, DeviceSession, checkLocation, checkSettle, pngSize, type ActionOptions, type CDPEndpoint, type ComputerProcess, type ComputerRecording, type ExecOptions, type ExecResult, type ExtractOptions, type FileStat, type OpenedSession, type OperationOptions, type Session, type SessionOptions, type StepResult, type ValidationOptions } from './session.js'; const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; const STATES = new Set(['starting', 'active', 'closing', 'stopped', 'failed', 'owner_lost']); const MAX_OUTPUT_BYTES = 1_048_576; const COMPUTER_AVAILABILITY = 'Mac computers need a current paid Revyl plan, and Linux computers are not generally available. Ask support@revyl.ai about access.'; const COMPUTER_CAPACITY = 'Computer admission was refused because of queued work (including iOS) or the concurrency limit. Verify will not retry the start.'; -const ERROR_CODES = new Set(['computer_not_enabled', 'run_closed', 'inaccessible', 'invalid_handle', 'operation_not_found', 'owner_unavailable', 'invalid_request', 'unauthenticated', 'forbidden', 'runtime_unavailable', 'start_failed', 'computer_limit', 'request_conflict', 'run_conflict', 'evidence_conflict', 'evidence_unavailable', 'authentication_unavailable', 'operation_limit', 'screen_starting', 'screen_unavailable', 'screen_control_held', 'screen_control_lost', 'screen_input_unavailable', 'screen_input_uncertain', 'screen_key_unsupported', 'screen_text_unsupported', 'screen_target_not_found', 'screen_target_unavailable']); +const ERROR_CODES = new Set(['computer_not_enabled', 'run_closed', 'inaccessible', 'invalid_handle', 'operation_not_found', 'owner_unavailable', 'invalid_request', 'unauthenticated', 'forbidden', 'runtime_unavailable', 'start_failed', 'computer_limit', 'request_conflict', 'run_conflict', 'evidence_conflict', 'evidence_unavailable', 'authentication_unavailable', 'operation_limit', 'screen_starting', 'screen_unavailable', 'screen_control_held', 'screen_control_lost', 'screen_input_unavailable', 'screen_input_uncertain', 'screen_key_unsupported', 'screen_text_unsupported', 'screen_target_not_found', 'screen_target_unavailable', 'step_engine_unavailable', 'step_engine_busy', 'inference_unavailable', 'inference_not_enabled']); const COMPUTER_KEYS: Record = { enter: 'Return', backspace: 'BackSpace', tab: 'Tab', escape: 'Escape', delete: 'Delete', space: 'space', arrowup: 'Up', arrowdown: 'Down', arrowleft: 'Left', arrowright: 'Right', home: 'Home', end: 'End', pageup: 'Page_Up', pagedown: 'Page_Down' }; const REFUSAL_NEXT_STEPS = { AUTH_REJECTED: "Check that REVYL_API_KEY is a current key and that its owner has the Member role or above in this computer's organization.", @@ -32,6 +32,7 @@ const RECORDING_WAIT_MS = 900_000; const RECORDING_POLL_MS = 5_000; const COMPUTER_CONTROL_CHARACTER = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]|[\ud800-\udbff](?![\udc00-\udfff])|(?(); private readonly childStarts = new Set>(); private closing = false; + private inferenceRequested: boolean; + private inferenceReadiness: ComputerInferenceReadiness | undefined; protected constructor(protected readonly client: RevylClient, target: ResolvedComputerTarget, protected readonly options: SessionOptions, id: string = randomUUID(), private readonly stopOnClose = true) { this.id = id; this.target = target.name; this.platform = target.platform; + this.inferenceRequested = target.inference === true; this.viewerUrl = sessionViewerUrl(this.id, 'computer', options.appUrl); this.startTimeoutMs = target.startTimeout; } @@ -64,7 +68,7 @@ export class ComputerSession implements Session { trackSession(session); try { session.log(`starting computer ${session.viewerUrl}`); - const body = { computer_session_id: session.id, os: target.platform === 'mac' ? 'macos' : 'linux', ...(target.timeoutMs !== undefined ? { timeout_seconds: target.timeoutMs / 1_000 } : {}), ...options.profile?.fields }; + const body = { computer_session_id: session.id, os: target.platform === 'mac' ? 'macos' : 'linux', ...(target.timeoutMs !== undefined ? { timeout_seconds: target.timeoutMs / 1_000 } : {}), ...(target.inference ? { inference: true } : {}), ...options.profile?.fields }; const response = await withRepositoryRetry(() => session.request('POST', '', body, signal)); createAcknowledged = true; const plan = options.profile?.name ? options.profile : undefined; @@ -114,6 +118,15 @@ export class ComputerSession implements Session { return this.closePromise !== undefined; } + /** + * Only on a Mac opened with { inference: true }: whether its own vision model answered when Verify last read the + * computer's report (at open, and on each report() call). 'ready' answers now, 'unavailable' doesn't, 'unknown' + * can't be told yet. Undefined on a computer opened without inference. + */ + get inference(): ComputerInferenceReadiness | undefined { + return this.inferenceRequested ? (this.inferenceReadiness ?? 'unknown') : undefined; + } + static async attach(client: RevylClient, computerId: string, options: SessionOptions & { stopOnClose?: boolean }): Promise { if (typeof computerId !== 'string' || !UUID.test(computerId)) throw new VerifyError('INVALID_ARGUMENT', 'attach() requires a computer session UUID.'); const probe = new ComputerSession(client, { name: 'computer', platform: 'mac', startTimeout: 600_000 }, options, computerId); @@ -131,10 +144,12 @@ export class ComputerSession implements Session { this.assertOpen(); if (this.expiresAtMs === undefined) throw new VerifyError('API_ERROR', 'The computer report must include expiry before opening a hosted child.'); const resolved = validateHostedTarget(target); + if (resolved.inference === undefined && this.inferenceRequested && resolved.platform !== 'android') resolved.inference = true; if ((this.platform === 'mac' && resolved.platform === 'android') || (this.platform === 'linux' && resolved.platform === 'ios')) throw new VerifyError('NOT_AVAILABLE_ON_PLATFORM', 'This computer cannot host the requested platform.', { reason: 'computer_cannot_host_platform' }); const expiresAt = () => this.expiresAt; const pending = DeviceSession.start(this.client, resolved, { ...this.options, profile: undefined }, { id: this.id, + inference: this.inferenceRequested, signal: this.lifetime.signal, get expiresAt() { return expiresAt(); }, register: (session) => { this.children.add(session); }, @@ -343,11 +358,62 @@ export class ComputerSession implements Session { } instruction(): Promise { - return this.unavailable('instruction'); + return Promise.reject(new VerifyError('NOT_AVAILABLE_ON_PLATFORM', `instruction() is not available on computers. To click one thing by its description, use tap({ target: 'the Save button' }); to type into a field, use type({ target: 'the search field' }, text). validation() and extract() do work on a Mac opened with { inference: true }. See ${this.viewerUrl}`)); + } + + /** + * Asks the Mac's own vision model whether something holds on screen, such as "the Settings window is open". Throws + * VALIDATION_FAILED when it does not, unless soft is set, and STEP_FAILED when the model could not reach a verdict. + * Needs a Mac opened with { inference: true }; otherwise throws NOT_AVAILABLE_ON_PLATFORM. + */ + async validation(text: string, options: ValidationOptions = {}): Promise { + const result = await this.runComputerStep('validation', text, options); + if (!result.passed && !options.soft) throw new VerifyError('VALIDATION_FAILED', `Validation failed: "${result.text}". ${result.reason ? `${result.reason.replace(/[.\s]*$/, '')}. ` : ''}See ${this.viewerUrl}`, { result }); + return result; } - validation(): Promise { - return this.unavailable('validation'); + /** + * Reads a value off the screen with the Mac's own vision model, such as "the build number in the About window", and + * returns the step with it in value. Throws STEP_FAILED when nothing could be read. Needs a Mac opened with + * { inference: true }; otherwise throws NOT_AVAILABLE_ON_PLATFORM. + */ + extract(text: string, options: ExtractOptions = {}): Promise { + return this.runComputerStep('extract', text, options); + } + + private async runComputerStep(type: 'validation' | 'extract', text: string, options: { timeout?: number; model?: unknown; agent?: unknown }): Promise { + this.assertOpen(); + if (typeof text !== 'string' || text.trim() === '' || text.length > 2_000) throw new VerifyError('INVALID_ARGUMENT', `${type}() on a computer takes a description of 1 to 2000 characters.`); + if (options.model !== undefined || options.agent !== undefined) throw new VerifyError('NOT_AVAILABLE_ON_PLATFORM', `Your own model runs steps on browsers and devices, not on computers. Leave out model and agent; ${type}() on a Mac runs on the Mac's own vision model.`); + const timeoutMs = options.timeout ?? this.options.stepTimeout; + if (!Number.isInteger(timeoutMs) || timeoutMs < 1_000) throw new VerifyError('INVALID_ARGUMENT', `${type}() takes a timeout of at least 1000 ms.`); + if (this.platform !== 'mac') throw new VerifyError('NOT_AVAILABLE_ON_PLATFORM', `${type}() is not available on Linux computers: ${NO_MODEL} ${SCREEN_CALLS}`, { reason: 'step_engine_unavailable' }); + const description = text.trim(); + const startedAt = Date.now(); + const signal = this.observationSignal(timeoutMs); + let response: RawResponse; + try { + response = await this.request('POST', '/steps', { step_type: type, description }, signal, timeoutMs); + } catch (error) { + this.log(`✗ ${type} "${description}": ${isVerifyError(error) ? error.code : 'API_ERROR'}`); + if (signal.aborted && !this.lifetime.signal.aborted) throw new VerifyError('TIMEOUT', `The ${type} did not finish within ${timeoutMs} ms: "${description}". Pass a larger timeout. See ${this.viewerUrl}`, { cause: error }); + throw error; + } + const raw = parseComputerJson(response); + if (!raw || raw.step_type !== type || !['passed', 'failed', 'uncertain'].includes(raw.status) || (raw.engine !== 'local' && raw.engine !== 'hosted')) throw invalidResponse(); + const reason = typeof raw.status_reason === 'string' && raw.status_reason ? raw.status_reason : undefined; + const value = raw.extracted_data?.information; + if (raw.status === 'uncertain' || (type === 'validation' && typeof raw.validation_result !== 'boolean') || (type === 'extract' && (raw.status !== 'passed' || typeof value !== 'string'))) { + this.log(`✗ ${type} "${description}": no ${type === 'validation' ? 'verdict' : 'value'}`); + throw new VerifyError('STEP_FAILED', type === 'validation' + ? `Validation did not reach a verdict: "${description}". ${reason ? `${reason.replace(/[.\s]*$/, '')}. ` : ''}The Mac's model wasn't sure; describe one thing that is visible on the screen now. See ${this.viewerUrl}` + : `Extract read nothing: "${description}". ${reason ? `${reason.replace(/[.\s]*$/, '')}. ` : ''}Describe one value that is on the screen now, such as "the version number in the About window". See ${this.viewerUrl}`); + } + const passed = type === 'validation' ? raw.validation_result === true : true; + const result: StepResult = { type, text: description, passed, ...(type === 'extract' ? { value: value as string } : {}), ...(reason ? { reason } : {}), durationMs: Date.now() - startedAt, engine: raw.engine }; + this.steps.push(result); + this.log(`${passed ? '✓' : '✗'} ${type} "${description}" (${(result.durationMs / 1_000).toFixed(1)} s, ${raw.engine} model)${type === 'extract' ? `: ${value}` : !passed && reason ? `: ${reason}` : ''}`); + return result; } async screenshot(options: { path?: string } = {}): Promise { @@ -586,6 +652,15 @@ export class ComputerSession implements Session { const fix = typeof max === 'number' && Number.isInteger(max) && max > 0 ? `timeoutMs of at most ${max * 1_000}` : 'a shorter timeoutMs'; throw new VerifyError('NOT_AVAILABLE_ON_PLATFORM', `No host can keep this computer running that long (lifetime_unsupported); pass ${fix}.`, { reason: 'lifetime_unsupported', httpStatus: response.status }); } + if (suffix === '' && method === 'POST' && detail === 'inference_not_enabled') throw new VerifyError('NOT_AVAILABLE_ON_PLATFORM', `Local inference isn't enabled for this API key's organization (inference_not_enabled). Ask support@revyl.ai to turn it on, or open the Mac without inference: open({ platform: 'mac' }).`, { reason: 'inference_not_enabled', httpStatus: response.status }); + if (suffix === '' && method === 'POST' && detail === 'inference_unavailable') throw new VerifyError('NOT_AVAILABLE_ON_PLATFORM', `No Mac with its own vision model is up to take this computer right now (inference_unavailable), so nothing was started. Try again later, or open the Mac without inference: open({ platform: 'mac' }).`, { reason: 'inference_unavailable', httpStatus: response.status }); + if (suffix === '/steps') { + if (detail === 'step_engine_unavailable') throw new VerifyError('NOT_AVAILABLE_ON_PLATFORM', this.inferenceRequested + ? `This Mac's own vision model isn't answering right now (step_engine_unavailable), so the step didn't run. computer.inference shows whether it is ready; try again shortly. See ${this.viewerUrl}` + : `This computer has no vision model of its own (step_engine_unavailable), so the step didn't run. ${NO_MODEL} To click or type by description on any Mac, use tap({ target }) and type({ target }, text). See ${this.viewerUrl}`, { reason: 'step_engine_unavailable', httpStatus: response.status }); + if (detail === 'step_engine_busy') throw new VerifyError('SESSION_BUSY', `This Mac's vision model is busy with another step (step_engine_busy), so the step didn't run. Run one step at a time on a computer, and try again in a few seconds. See ${this.viewerUrl}`, refusal); + if (detail === 'screen_control_held') throw new VerifyError('SESSION_BUSY', `The step didn't run: someone else is controlling this computer's screen in the viewer (screen_control_held). Try again after they release it; control frees itself after 2 minutes without input. See ${this.viewerUrl}`, refusal); + } if (response.status === 409 && detail === 'extend_unsupported') throw new VerifyError('NOT_AVAILABLE_ON_PLATFORM', `This computer's host can't extend its lifetime (extend_unsupported); its expiry is unchanged. See ${this.viewerUrl}`, refusal); if (suffix === '/screen/actions') { if (response.status === 422 && detail === 'screen_point_outside') return response; @@ -643,6 +718,10 @@ export class ComputerSession implements Session { const report = parseComputerJson(response); if (!report || report.computer_session_id !== this.id || !STATES.has(report.state)) throw invalidResponse(); if (report.expires_at != null) this.expiresAtMs = Math.max(parseTimestamp(report.expires_at).getTime(), this.expiresAtMs ?? -Infinity); + if (report.inference === 'ready' || report.inference === 'unavailable' || report.inference === 'unknown') { + this.inferenceRequested = true; + this.inferenceReadiness = report.inference; + } return report; } diff --git a/packages/verify/src/config.ts b/packages/verify/src/config.ts index 907ae94..c955ab6 100644 --- a/packages/verify/src/config.ts +++ b/packages/verify/src/config.ts @@ -45,18 +45,28 @@ export interface MobileTargetConfig { idleTimeoutSeconds?: number; } -/** A Revyl computer that runs commands and files instead of agent steps. See docs/computers.md. */ +/** A Revyl computer for commands, files and the screen. See docs/computers.md. */ export interface ComputerTargetConfig { platform: ComputerPlatform; startTimeout?: number; /** How long the computer runs from create, in milliseconds: whole seconds from 60000 to 86400000. Defaults to Revyl's 2 hours. */ timeoutMs?: number; + /** + * Mac only: run the computer on a Mac whose own vision model is loaded, so validation() and extract() work on it and + * iOS and Web sessions opened inside it use that model too. Enabled per organization; see docs/computers.md. + */ + inference?: boolean; } export type TargetConfig = WebTargetConfig | MobileTargetConfig | ComputerTargetConfig; export type HostedTargetConfig = (Omit | Omit) & { app: { appId: string; buildId: string }; + /** + * iOS and Web: run this session's steps on the hosting Mac's own vision model first, with Revyl's hosted model as the + * fallback. Defaults to true inside a computer opened with { inference: true } and false otherwise; pass false to opt out. + */ + inference?: boolean; }; export interface VerifyConfig { @@ -68,7 +78,7 @@ export interface VerifyConfig { type Resolved = T & { name: string; startTimeout: number }; -export type ResolvedDeviceTarget = Resolved<(WebTargetConfig | MobileTargetConfig) & { idleTimeoutSeconds: number }>; +export type ResolvedDeviceTarget = Resolved<(WebTargetConfig | MobileTargetConfig) & { idleTimeoutSeconds: number; inference?: boolean }>; export type ResolvedComputerTarget = Resolved; export type ResolvedTarget = ResolvedDeviceTarget | ResolvedComputerTarget; @@ -161,18 +171,21 @@ export function validateHostedTarget(raw: HostedTargetConfig): ResolvedDeviceTar type Fail = (path: string, problem: string) => never; function parseTarget(raw: unknown, name: string, path: string, fail: Fail, hosted = false): ResolvedTarget { - const target = asRecord(raw, path, fail); + let target = asRecord(raw, path, fail); const platform = target.platform; if (typeof platform !== 'string' || !(PLATFORMS as readonly string[]).includes(platform)) { fail(`${path}.platform`, "must be 'web', 'ios', 'android', 'mac', or 'linux'."); } const startTimeout = integer(target.startTimeout, `${path}.startTimeout`, 10_000, 1_800_000, 600_000, fail); if (platform === 'mac' || platform === 'linux') { - rejectUnknownKeys(target, ['platform', 'startTimeout', 'timeoutMs'], path, fail); - if (target.timeoutMs === undefined) return { name, startTimeout, platform }; + rejectUnknownKeys(target, ['platform', 'startTimeout', 'timeoutMs', 'inference'], path, fail); + if (target.inference !== undefined && typeof target.inference !== 'boolean') fail(`${path}.inference`, 'must be true or false.'); + if (target.inference === true && platform === 'linux') fail(`${path}.inference`, "is for Mac computers only; use { platform: 'mac', inference: true }."); + const inference = target.inference === true ? { inference: true } : {}; + if (target.timeoutMs === undefined) return { name, startTimeout, platform, ...inference }; const timeoutMs = integer(target.timeoutMs, `${path}.timeoutMs`, 60_000, 86_400_000, undefined, fail); if (timeoutMs % 1_000 !== 0) fail(`${path}.timeoutMs`, 'must be whole seconds.'); - return { name, startTimeout, platform, timeoutMs }; + return { name, startTimeout, platform, timeoutMs, ...inference }; } const common = { name, @@ -180,7 +193,13 @@ function parseTarget(raw: unknown, name: string, path: string, fail: Fail, hoste idleTimeoutSeconds: integer(target.idleTimeoutSeconds, `${path}.idleTimeoutSeconds`, 60, 3_600, 600, fail), }; const app = asRecord(target.app, `${path}.app`, fail); + let inference: { inference?: boolean } = {}; if (hosted) { + if (target.inference !== undefined && typeof target.inference !== 'boolean') fail(`${path}.inference`, 'must be true or false.'); + if (target.inference === true && platform === 'android') fail(`${path}.inference`, 'runs only for iOS and Web sessions inside a Mac computer; leave it out for Android.'); + if (target.inference !== undefined) inference = { inference: target.inference as boolean }; + const { inference: _ignored, ...rest } = target; + target = rest; uuid(app.appId, `${path}.app.appId`, true, fail); uuid(app.buildId, `${path}.app.buildId`, true, fail); rejectUnknownKeys(app, ['appId', 'buildId'], `${path}.app`, fail); @@ -238,6 +257,7 @@ function parseTarget(raw: unknown, name: string, path: string, fail: Fail, hoste }, ...(viewport ? { viewport } : {}), ...(signIn ? { signIn } : {}), + ...inference, }; } @@ -274,6 +294,7 @@ function parseTarget(raw: unknown, name: string, path: string, fail: Fail, hoste ...(app.bundleId !== undefined ? { bundleId: app.bundleId as string } : {}), }, ...(device ? { device } : {}), + ...inference, }; } diff --git a/packages/verify/src/errors.ts b/packages/verify/src/errors.ts index 7a794bc..9315835 100644 --- a/packages/verify/src/errors.ts +++ b/packages/verify/src/errors.ts @@ -28,7 +28,7 @@ export type VerifyErrorCode = | 'SESSION_PROFILE_FAILED' | 'TIMEOUT'; -export type RefusalReason = 'web_runtime_unavailable' | 'web_runtime_not_configured' | 'computer_limit' | 'runtime_unavailable' | 'computer_runtime_unavailable' | 'computer_at_capacity' | 'computer_platform_at_capacity' | 'computer_not_running' | 'computer_cannot_host_platform' | 'computer_not_found' | 'web_build_required' | 'web_build_not_supported' | 'ios_build_required' | 'ios_build_not_supported' | 'android_build_required' | 'android_build_not_supported' | 'web_session_conflict' | 'ios_session_conflict' | 'android_session_conflict' | 'not_available_on_platform' | 'persistent_computers_not_enabled' | 'upgrade_required' | 'request_timeout' | 'protocol_error' | 'session_profile_undefined' | 'session_profile_source_required' | 'session_profile_files_need_named' | 'session_profile_script_unavailable' | 'repository_connection_missing' | 'project_not_found' | 'repository_unavailable' | 'lifetime_unsupported' | 'no_focused_input'; +export type RefusalReason = 'web_runtime_unavailable' | 'web_runtime_not_configured' | 'computer_limit' | 'runtime_unavailable' | 'computer_runtime_unavailable' | 'computer_at_capacity' | 'computer_platform_at_capacity' | 'computer_not_running' | 'computer_cannot_host_platform' | 'computer_not_found' | 'web_build_required' | 'web_build_not_supported' | 'ios_build_required' | 'ios_build_not_supported' | 'android_build_required' | 'android_build_not_supported' | 'web_session_conflict' | 'ios_session_conflict' | 'android_session_conflict' | 'not_available_on_platform' | 'persistent_computers_not_enabled' | 'upgrade_required' | 'request_timeout' | 'protocol_error' | 'session_profile_undefined' | 'session_profile_source_required' | 'session_profile_files_need_named' | 'session_profile_script_unavailable' | 'repository_connection_missing' | 'project_not_found' | 'repository_unavailable' | 'lifetime_unsupported' | 'no_focused_input' | 'computer_local_inference_unavailable' | 'inference_not_enabled' | 'inference_unavailable' | 'step_engine_unavailable'; export class VerifyError extends Error { readonly code: VerifyErrorCode; diff --git a/packages/verify/src/index.ts b/packages/verify/src/index.ts index ad53c2e..a1b29f9 100644 --- a/packages/verify/src/index.ts +++ b/packages/verify/src/index.ts @@ -1,9 +1,9 @@ export { attach, currentComputer, open } from './open.js'; export type { AttachOptions, OpenOptions } from './open.js'; -export type { ActionOptions, CDPEndpoint, OpenedSession, Session, StepOptions, StepResult, StepType, ValidationOptions, OperationOptions, ExecOptions, ExecResult, FileStat, ComputerProcess, ComputerRecording } from './session.js'; +export type { ActionOptions, CDPEndpoint, ExtractOptions, OpenedSession, Session, StepOptions, StepResult, StepType, ValidationOptions, OperationOptions, ExecOptions, ExecResult, FileStat, ComputerProcess, ComputerRecording } from './session.js'; export { defineConfig } from './config.js'; export type { HostedTargetConfig, MobileAppConfig, MobileTargetConfig, ComputerTargetConfig, TargetConfig, VerifyConfig, WebAppConfig, WebTargetConfig } from './config.js'; -export type { Platform, ComputerPlatform, MobilePlatform } from './api/types.js'; +export type { Platform, ComputerInferenceReadiness, ComputerPlatform, MobilePlatform } from './api/types.js'; export { openPersistent, saveSnapshot, listPersistent, listSnapshots, deletePersistent, deleteSnapshot } from './persistent.js'; export type { ComputerSnapshot, PersistentComputer, PersistentComputerSession, PersistentComputerState, PersistentOpenOptions, PersistentOptions, SaveSnapshotOptions } from './persistent.js'; export { VerifyError, isVerifyError } from './errors.js'; diff --git a/packages/verify/src/persistent.ts b/packages/verify/src/persistent.ts index b74b7e9..349cf3e 100644 --- a/packages/verify/src/persistent.ts +++ b/packages/verify/src/persistent.ts @@ -26,6 +26,16 @@ export interface PersistentOpenOptions extends PersistentOptions { fromSnapshot?: string; /** How long this run may last before the computer stops itself (keeping its disk), in ms: whole seconds from 60000 to 86400000. Defaults to 2 hours. Not applied when the computer was already running. Same as timeoutMs on open('mac'). */ timeoutMs?: number; + /** + * Only when this call creates the computer: run it on Macs whose own vision model is loaded, as open({ platform: 'mac', inference: true }) + * does, so validation() and extract() work on it. The computer keeps this for every later start. + */ + inference?: boolean; + /** + * Only when this call starts a stopped computer that was created with inference: start this run on any Mac, without + * the model, for when no Mac with one is up. Later starts ask for the model again. Needs a Revyl backend that offers it. + */ + withoutInference?: boolean; /** How long openPersistent() waits for the computer to be ready, in ms from 10000 to 1800000. Defaults to 900000 (15 minutes). Covers waiting for an earlier stop to finish saving, and a start from a snapshot, which takes up to about 3 minutes. Same unit as startTimeout on open('mac'). */ startTimeout?: number; } @@ -46,6 +56,8 @@ export interface PersistentComputer { /** Whether that save has been copied off the Mac that made it. saveSnapshot() needs this and waits for it. */ savedOffHost: boolean; createdAt: Date; + /** When its current save stops being startable, if Revyl reports an end; after it, openPersistent() throws SESSION_START_FAILED (saved_disk_expired). */ + savedDiskExpiresAt?: Date; } export interface ComputerSnapshot { @@ -56,6 +68,8 @@ export interface ComputerSnapshot { savedAt: Date; /** When the save stops being usable, if it has an end. */ expiresAt?: Date; + /** When a computer can no longer be created from it, if Revyl reports an end; after it, openPersistent() with fromSnapshot throws SESSION_START_FAILED (snapshot_expired). */ + savedDiskExpiresAt?: Date; } /** @@ -116,6 +130,7 @@ export class PersistentComputerSession extends ComputerSession { const session = new PersistentComputerSession(client, found.id, name, found.status === undefined, sessionOptions); const signal = AbortSignal.any([deadline, session.lifetime.signal]); const lifetime = options.timeoutMs === undefined ? undefined : { timeout_seconds: options.timeoutMs / 1_000 }; + const startBody = options.withoutInference ? { ...lifetime, without_inference: true } : lifetime; let started = false; let attempted = false; try { @@ -124,7 +139,7 @@ export class PersistentComputerSession extends ComputerSession { session.log(`creating persistent computer${options.fromSnapshot ? ` from snapshot ${options.fromSnapshot}` : ''} ${session.viewerUrl}`); attempted = true; const response = await call(client, 'POST', BASE, { - body: { computer_session_id: found.id, os: 'macos', persistent: true, ...lifetime, ...(options.fromSnapshot ? { from_snapshot: options.fromSnapshot } : {}) }, + body: { computer_session_id: found.id, os: 'macos', persistent: true, ...lifetime, ...(options.fromSnapshot ? { from_snapshot: options.fromSnapshot } : {}), ...(options.inference ? { inference: true } : {}) }, signal, retry: true, notFound: `There is no snapshot named or with the ID ${options.fromSnapshot}. listSnapshots() shows your organization's snapshots.`, @@ -134,12 +149,13 @@ export class PersistentComputerSession extends ComputerSession { first = session.parseReport(response); } else { if (options.fromSnapshot) session.log(`already exists, so fromSnapshot ${options.fromSnapshot} was not used`); + if (options.inference) session.log('already exists, so inference was not changed; a computer keeps the inference it was created with'); let status = found.status; let waiting = false; while (status.state === 'stopping' || status.state === 'stopped') { if (status.state === 'stopped') { attempted = true; - const response = await call(client, 'POST', `${BASE}/${found.id}/start`, { body: lifetime, signal, retry: true, accept: ['run_conflict'] }); + const response = await call(client, 'POST', `${BASE}/${found.id}/start`, { body: startBody, signal, retry: true, accept: ['run_conflict'], invalid: options.withoutInference ? 'This Revyl backend refused withoutInference, which it does not offer yet. Leave it out to start the computer as it was created.' : undefined }); if (response.status < 300) { session.log(`starting from its saved disk ${session.viewerUrl}`); break; @@ -191,6 +207,8 @@ export class PersistentComputerSession extends ComputerSession { export async function openPersistent(name: string, options: PersistentOpenOptions = {}): Promise { checkComputerReference(name, 'openPersistent()'); if (options.fromSnapshot !== undefined) checkSnapshotReference(options.fromSnapshot, 'fromSnapshot'); + if (options.inference !== undefined && typeof options.inference !== 'boolean') throw new VerifyError('INVALID_ARGUMENT', 'inference must be true or false.'); + if (options.withoutInference !== undefined && typeof options.withoutInference !== 'boolean') throw new VerifyError('INVALID_ARGUMENT', 'withoutInference must be true or false.'); if (options.timeoutMs !== undefined && (!Number.isInteger(options.timeoutMs) || options.timeoutMs % 1_000 !== 0 || options.timeoutMs < 60_000 || options.timeoutMs > 86_400_000)) throw new VerifyError('INVALID_ARGUMENT', 'timeoutMs must be whole seconds from 60000 to 86400000.'); const startTimeout = options.startTimeout ?? 900_000; if (!Number.isInteger(startTimeout) || startTimeout < 10_000 || startTimeout > 1_800_000) throw new VerifyError('INVALID_ARGUMENT', 'startTimeout must be an integer from 10000 to 1800000 ms.'); @@ -343,6 +361,7 @@ interface CallOptions { retry?: boolean; notFound?: string; accept?: string[]; + invalid?: string; } async function call(client: RevylClient, method: 'GET' | 'POST' | 'DELETE', path: string, options: CallOptions): Promise { @@ -359,6 +378,7 @@ async function call(client: RevylClient, method: 'GET' | 'POST' | 'DELETE', path if (known) throw new VerifyError(known[0], known[1], { ...refusal, reason: known[2] }); if (response.status === 401 || response.status === 403) throw new VerifyError('AUTH_REJECTED', `Revyl rejected the request (HTTP ${response.status}${detail ? `, ${detail}` : ''}). Check that REVYL_API_KEY is a current key and that its owner has the Member role or above.`, refusal); if (response.status === 404) throw new VerifyError('NOT_FOUND', options.notFound ?? `Revyl could not find ${path} (inaccessible).`, refusal); + if ((response.status === 422 || detail === 'invalid_request') && options.invalid) throw new VerifyError('INVALID_ARGUMENT', options.invalid, refusal); if (response.status === 422 || detail === 'invalid_request') throw new VerifyError('INVALID_ARGUMENT', `Revyl refused the request as invalid (${detail ?? `HTTP ${response.status}`}). Check the call's arguments against its doc comment; if they match, update Verify.`, refusal); throw new VerifyError('API_ERROR', `Revyl request ${method} ${path} failed (HTTP ${response.status}${detail ? `, ${detail}` : ''}). It is safe to try again; if it keeps failing, send this message to support@revyl.ai.`, refusal); } @@ -375,6 +395,8 @@ const REFUSALS: Record = { saved_disk_expired: ['SESSION_START_FAILED', "This computer's saved disk has reached its end and can't start again (saved_disk_expired). Delete it with deletePersistent(); openPersistent() with its name then creates a new one."], snapshot_expired: ['SESSION_START_FAILED', "This snapshot's saved disk has reached its end and can't start a computer (snapshot_expired). Save a new snapshot of a recently stopped computer."], computer_not_persistent: ['INVALID_ARGUMENT', "This ID names a computer that isn't persistent (computer_not_persistent). Pass a name, or an ID from listPersistent()."], + inference_not_enabled: ['NOT_AVAILABLE_ON_PLATFORM', "Local inference isn't enabled for this API key's organization (inference_not_enabled). Ask support@revyl.ai to turn it on, or leave out inference.", 'inference_not_enabled'], + inference_unavailable: ['NOT_AVAILABLE_ON_PLATFORM', "No Mac with its own vision model is up to take this computer right now (inference_unavailable), so nothing was started. Try again later; to start an existing computer without the model this once, pass withoutInference: true.", 'inference_unavailable'], run_conflict: ['SESSION_BUSY', "The computer's last run hasn't finished stopping (run_conflict). Its disk is kept; try again in a few minutes."], }; @@ -394,14 +416,16 @@ function toComputer(raw: unknown): PersistentComputer { const record = raw as Record | null; if (!record || typeof record !== 'object' || typeof record.computer_id !== 'string' || !UUID.test(record.computer_id) || typeof record.state !== 'string' || !STATES.has(record.state) || typeof record.durable !== 'boolean') throw invalidResponse(); const savedAt = record.saved_at == null ? undefined : date(record.saved_at); - return { id: record.computer_id.toLowerCase(), state: record.state as PersistentComputerState, ...(savedAt ? { savedAt } : {}), savedOffHost: record.durable, createdAt: date(record.created_at) }; + const savedDiskExpiresAt = record.saved_disk_expires_at == null ? undefined : date(record.saved_disk_expires_at); + return { id: record.computer_id.toLowerCase(), state: record.state as PersistentComputerState, ...(savedAt ? { savedAt } : {}), savedOffHost: record.durable, createdAt: date(record.created_at), ...(savedDiskExpiresAt ? { savedDiskExpiresAt } : {}) }; } function toSnapshot(raw: unknown): ComputerSnapshot { const record = raw as Record | null; if (!record || typeof record !== 'object' || typeof record.id !== 'string' || !UUID.test(record.id) || typeof record.name !== 'string' || typeof record.computer_id !== 'string' || !UUID.test(record.computer_id)) throw invalidResponse(); const expiresAt = record.expires_at == null ? undefined : date(record.expires_at); - return { id: record.id.toLowerCase(), name: record.name, computerId: record.computer_id.toLowerCase(), savedAt: date(record.saved_at), ...(expiresAt ? { expiresAt } : {}) }; + const savedDiskExpiresAt = record.saved_disk_expires_at == null ? undefined : date(record.saved_disk_expires_at); + return { id: record.id.toLowerCase(), name: record.name, computerId: record.computer_id.toLowerCase(), savedAt: date(record.saved_at), ...(expiresAt ? { expiresAt } : {}), ...(savedDiskExpiresAt ? { savedDiskExpiresAt } : {}) }; } function date(value: unknown): Date { diff --git a/packages/verify/src/session.ts b/packages/verify/src/session.ts index 6149448..3787f49 100644 --- a/packages/verify/src/session.ts +++ b/packages/verify/src/session.ts @@ -15,6 +15,7 @@ import { type RawResponse, } from './api/client.js'; import type { + ComputerInferenceReadiness, LiveStepResult, LiveStepType, Platform, @@ -54,18 +55,30 @@ const WEB_TARGET_ERRORS = new Set(['stale_target', 'target_unstable', 'invalid_c export type StepType = LiveStepType; -/** The outcome of one instruction or validation, as Revyl's agent reported it. */ +/** The outcome of one instruction, validation or extract, as Revyl's agent reported it. */ export interface StepResult { type: StepType; text: string; passed: boolean; + /** What extract() read off the screen. Extract steps only. */ + value?: string; /** Revyl's explanation, or your model's when the step ran on a local agent. */ reason?: string; durationMs: number; + /** + * Who answered, when Revyl says: 'local' is the vision model on the Revyl computer the step ran on or inside + * (open({ platform: 'mac', inference: true })), 'hosted' is Revyl's hosted model. + */ + engine?: 'local' | 'hosted'; /** Present when the step ran on your model: its name, grounding, turns and token use. */ model?: ModelRun; } +export interface ExtractOptions { + /** Milliseconds before the step is cancelled. Defaults to stepTimeout from the config, or 180000. */ + timeout?: number; +} + export interface StepOptions { /** Milliseconds before the step is cancelled. Defaults to stepTimeout from the config, or 180000. */ timeout?: number; @@ -158,16 +171,18 @@ export interface Session { readonly id: string; /** The live view of the session in Revyl, and its recording and report once it ends. */ readonly viewerUrl: string; - /** Every instruction and validation run on this session, in order. */ + /** Every instruction, validation and extract run on this session, in order. */ readonly steps: StepResult[]; readonly closed: boolean; readonly expiresAt?: Date; /** A computer's recording after close(), waiting until Revyl has saved it; null when none was saved within timeoutMs (default 15 minutes). Computers only. */ recording(options?: { timeoutMs?: number }): Promise; - /** Asks Revyl's agent to do something on the app. Browsers and devices only. */ + /** Asks Revyl's agent to do something on the app. Browsers and devices; on a computer, use tap({ target }) or type({ target }, text). */ instruction(text: string, options?: StepOptions): Promise; - /** Asks Revyl's agent whether something holds on screen. Browsers and devices only. */ + /** Asks whether something holds on screen. Every platform; a Mac computer needs open({ platform: 'mac', inference: true }). */ validation(text: string, options?: ValidationOptions): Promise; + /** Reads a value off the screen, such as "the order number", and returns it as result.value. Every platform; a Mac computer needs open({ platform: 'mac', inference: true }). */ + extract(text: string, options?: ExtractOptions): Promise; /** A PNG of the screen right now, also written to path when given. */ screenshot(options?: { path?: string }): Promise; /** Runs a program with its arguments, not a shell line. Computers only. */ @@ -197,6 +212,11 @@ export interface OpenedSession extends Session { * instruction() and validation() keep working. Each connection needs a fresh url: it works once and expires after 60 seconds. Web only. */ cdp(): Promise; + /** + * Computers opened with { inference: true } only: whether the Mac's own vision model answered when Verify last read the + * computer's report (at open and on each report()): 'ready', 'unavailable' or 'unknown'. Undefined everywhere else. + */ + readonly inference?: ComputerInferenceReadiness; /** Keeps the computer running at least timeoutMs (whole seconds, 60000 to 86400000) from now, up to 24 hours after it started. Never shortens it. Computers only. */ extend(timeoutMs: number): Promise; /** @@ -245,6 +265,8 @@ export interface HostingParent { id: string; signal: AbortSignal; expiresAt?: Date; + /** Whether the hosting computer was opened with inference. */ + inference: boolean; register(session: Session): void; } @@ -257,7 +279,7 @@ export class DeviceSession implements Session { readonly id: string; /** The live view of the session in Revyl, and its recording and report once it ends. */ readonly viewerUrl: string; - /** Every instruction and validation run on this session, in order. */ + /** Every instruction, validation and extract run on this session, in order. */ readonly steps: StepResult[] = []; private workflowRunId: string; private closePromise: Promise | undefined; @@ -376,6 +398,7 @@ export class DeviceSession implements Session { ...(target.viewport ? { viewport: { width: target.viewport.width, height: target.viewport.height, device_scale_factor: target.viewport.deviceScaleFactor } } : {}), ...(target.signIn ? { sign_in: { path: target.signIn.path, secret_name: target.signIn.secret, persona: target.signIn.persona } } : {}), } } : { is_simulation: true }), + ...(target.inference ? { inference: 'local' as const } : {}), }; let submitted = false; let refused = false; @@ -388,6 +411,9 @@ export class DeviceSession implements Session { refused = [400, 401, 403, 404, 405, 409, 422, 429].includes(response.status) || (response.status === 503 && reason !== undefined && reason !== 'request_timeout' && reason !== 'protocol_error'); const blocked = edgeBlockedError(response); if (blocked) throw blocked; + if (reason === 'computer_local_inference_unavailable') { + throw new VerifyError('NOT_AVAILABLE_ON_PLATFORM', `Revyl refused the ${target.platform} session's local inference (computer_local_inference_unavailable): the hosting computer has no vision model answering. ${parent.inference ? "It was opened with { inference: true } but its Mac's model isn't answering now (computer.inference shows it); try again shortly, or" : "Open the computer with open({ platform: 'mac', inference: true }) to use its model, or"} pass { inference: false } to computer.open() to run this session's steps on Revyl's hosted model.`, { reason, httpStatus: response.status }); + } const code = response.status === 401 || response.status === 403 ? 'AUTH_REJECTED' : reason === 'computer_not_found' || response.status === 404 ? 'NOT_FOUND' : reason === 'computer_not_running' ? 'SESSION_ENDED' @@ -447,6 +473,14 @@ export class DeviceSession implements Session { return result; } + /** + * Reads a value off the screen, such as "the order number", and returns the step with it in value. Throws STEP_FAILED + * when Revyl could not read it. Runs on Revyl's agent, so a session opened with your own model throws INVALID_ARGUMENT. + */ + async extract(text: string, options: ExtractOptions = {}): Promise { + return this.step('extract', text, options); + } + /** A PNG of the screen right now, also written to path when given. */ async screenshot(options: { path?: string } = {}): Promise { const response = await this.worker('GET', 'screenshot', { retry: true }); @@ -585,18 +619,21 @@ export class DeviceSession implements Session { throw new VerifyError('INVALID_ARGUMENT', `${type}() takes a description of 1 to ${MAX_STEP_TEXT_LENGTH} characters.`); } const agent = chooseAgent(options, `${type}()`) ?? this.options.agent; + if (type === 'extract' && agent) { + throw new VerifyError('INVALID_ARGUMENT', "extract() runs on Revyl's agent, and this session runs steps on your model because open() was passed model or agent. Read the value from screenshot() with your model, or open a session without model or agent to use extract()."); + } const timeoutMs = options.timeout ?? this.options.stepTimeout; if (!Number.isInteger(timeoutMs) || timeoutMs < 1_000) { throw new VerifyError('INVALID_ARGUMENT', `${type}() takes a timeout of at least 1000 ms.`); } if (this.stepRunning) { - throw new VerifyError('INVALID_ARGUMENT', 'Run one step at a time on a session: await each instruction or validation before starting the next.'); + throw new VerifyError('INVALID_ARGUMENT', 'Run one step at a time on a session: await each instruction, validation or extract before starting the next.'); } this.stepRunning = true; const description = text.trim(); const startedAt = Date.now(); try { - if (agent) { + if (agent && type !== 'extract') { const local = await this.runLocal(type, description, timeoutMs, agent); const result: StepResult = { type, text: description, passed: local.passed, ...(local.reason ? { reason: local.reason } : {}), durationMs: Date.now() - startedAt, model: local.run }; this.steps.push(result); @@ -610,10 +647,16 @@ export class DeviceSession implements Session { const why = outcome.success === true ? 'Revyl returned no verdict.' : sentence(reason); throw new VerifyError('STEP_FAILED', `Validation did not reach a verdict: "${description}". ${why} See ${this.viewerUrl}`); } + const value = output.extracted_data?.information; + if (type === 'extract' && (outcome.success !== true || output.status === 'failed' || typeof value !== 'string')) { + const why = outcome.success === true && output.status !== 'failed' ? 'Revyl returned no value.' : sentence(reason); + throw new VerifyError('STEP_FAILED', `Extract read nothing: "${description}". ${why} Describe one value that is on the screen now, such as "the order number on the confirmation". See ${this.viewerUrl}`); + } const passed = type === 'validation' ? output.validation_result === true : outcome.success === true && output.status !== 'failed'; - const result: StepResult = { type, text: description, passed, ...(reason ? { reason } : {}), durationMs: Date.now() - startedAt }; + const engine = output.engine === 'local' || output.engine === 'hosted' ? output.engine : undefined; + const result: StepResult = { type, text: description, passed, ...(type === 'extract' ? { value: value as string } : {}), ...(reason ? { reason } : {}), durationMs: Date.now() - startedAt, ...(engine ? { engine } : {}) }; this.steps.push(result); - this.log(`${passed ? '✓' : '✗'} ${type} "${description}" (${formatDuration(result.durationMs)})${!passed && reason ? `: ${reason}` : ''}`); + this.log(`${passed ? '✓' : '✗'} ${type} "${description}" (${formatDuration(result.durationMs)}${engine ? `, ${engine} model` : ''})${type === 'extract' ? `: ${value}` : !passed && reason ? `: ${reason}` : ''}`); return result; } catch (error) { this.log(`✗ ${type} "${description}": ${isVerifyError(error) ? error.code : errorMessage(error)}`); @@ -681,7 +724,7 @@ export class DeviceSession implements Session { } } - private async runLocal(type: StepType, description: string, timeoutMs: number, agent: LocalAgent): Promise<{ passed: boolean; reason?: string; run: ModelRun }> { + private async runLocal(type: 'instruction' | 'validation', description: string, timeoutMs: number, agent: LocalAgent): Promise<{ passed: boolean; reason?: string; run: ModelRun }> { const signal = AbortSignal.timeout(timeoutMs); this.attribution = { 'X-Revyl-Agent': `Verify local: ${agent.model.name}`.replace(/[^\x20-\x7e]/g, '?').slice(0, 100), diff --git a/packages/verify/test/computer.test.ts b/packages/verify/test/computer.test.ts index 8e34c62..1160b39 100644 --- a/packages/verify/test/computer.test.ts +++ b/packages/verify/test/computer.test.ts @@ -161,11 +161,11 @@ describe('computer lifecycle', () => { }); it('does not send unsupported agent steps', async () => { - const fake = fakeMac(); + const fake = fakeMac().on('POST', /\/steps$/, () => json({ detail: 'step_engine_unavailable' }, 409)); const session = await start(fake); await expect(session.instruction('hi')).rejects.toMatchObject({ code: 'NOT_AVAILABLE_ON_PLATFORM' }); - await expect(session.validation('ready', { soft: true })).rejects.toMatchObject({ code: 'NOT_AVAILABLE_ON_PLATFORM' }); expect(fake.requests).toHaveLength(1); + await expect(session.validation('ready', { soft: true })).rejects.toMatchObject({ code: 'NOT_AVAILABLE_ON_PLATFORM' }); }); it.each([ diff --git a/python/README.md b/python/README.md index f9ef84d..4655f6d 100644 --- a/python/README.md +++ b/python/README.md @@ -2,7 +2,7 @@

Cloud browsers, mobile devices and computers from Python.

-Verify is a thin [Revyl](https://revyl.com) SDK, not a test runner. Open a web browser, iOS simulator or Android emulator for natural-language instructions and validations, or an early-access Mac computer for commands, files, processes and screenshots. +Verify is a thin [Revyl](https://revyl.com) SDK, not a test runner. Open a web browser, iOS simulator or Android emulator for natural-language instructions and validations, or an early-access Mac computer for commands, files, processes, screenshots and, on a Mac opened with inference, validations and extracts. ## For coding agents @@ -90,6 +90,23 @@ asyncio.run(main()) `async_open` returns an `AsyncSession`. Its async methods adapt the synchronous implementation through worker threads, rather than introducing another HTTP stack. Cancelling a method schedules best-effort session close; cancelling open interrupts startup and attempts cleanup as soon as an identity is known. Cancellation does not forcibly terminate an in-flight thread or undo a remote operation; do not replay an uncertain mutation. Always close explicitly or use `async with await async_open(...)`. +### Read a value with extract() + +**Since 0.6.0.** `extract(text)` reads one value off the screen and returns a `StepResult` whose `value` is the string it read: + +```python +from revyl_verify import Target, open + +with open(Target(platform="ios", bundle_id="com.apple.Preferences")) as session: + session.instruction("Open General, then About") + version = session.extract("the iOS version number") + print(version.value) +``` + +Describe one value that is on the screen now, such as `"the order number on the confirmation"`. When nothing can be read, it raises `STEP_FAILED` with the reason and a hint on how to describe the value. It works on every session: on Web, iOS and Android it runs on Revyl's agent like `instruction()` and `validation()`, and on a Mac computer opened with `inference=True` it reads the Mac's own screen with the Mac's own model (see [validation() and extract() on a Mac](#validation-and-extract-on-a-mac)). A session opened with `model` or `agent` raises `INVALID_ARGUMENT`: read the value from `screenshot()` with your model instead. `AsyncSession.extract()` is the same, awaited. + +Every `StepResult` also has `engine`: `"local"` when the vision model of the Mac the step ran on or inside answered, `"hosted"` when Revyl's hosted model did, and `None` when Revyl doesn't say, as on ordinary Web, iOS and Android sessions. `value` is set on extract steps only. + ### Mac computer Mac computers are available to organizations on a current paid Revyl plan. If yours can't start one, ask support@revyl.ai: @@ -107,7 +124,7 @@ with open(Target(platform="mac", start_timeout=600)) as session: recording = session.recording() # after close; waits until the video is saved ``` -`exec(argv, stdin=bytes_or_string, timeout=30, check=True)` preserves argument boundaries and raises on command failure by default. File and process operations are computer-only. File paths are workspace-relative, not arbitrary absolute guest paths. To get the screen recording, call `recording()` after the computer is closed (after its `with` block or `close()`), on the same object and before your script exits: Revyl saves the video a few seconds after release, so it asks every 5 seconds until it is saved and returns `ComputerRecording(url, duration_seconds, started_at)`, or `None` if none was saved within `timeout` seconds (`recording(timeout=900)`, 15 minutes by default; 0 asks once; a check under way at that point can take up to 30 seconds more). Called on a computer that is still running it raises `SESSION_BUSY` saying to close it first. `attach()` can't reopen a closed computer, so a later process can't fetch it. Since 0.5.1; earlier versions returned `None` at once while the video was still uploading. It doesn't download the video. Signed URLs in that metadata are credentials. Recording is locally unavailable on devices. +`exec(argv, stdin=bytes_or_string, timeout=30, check=True)` preserves argument boundaries and raises on command failure by default. File and process operations are computer-only. File paths are workspace-relative, not arbitrary absolute guest paths. To get the screen recording, call `recording()` after the computer is closed (after its `with` block or `close()`), on the same object and before your script exits: Revyl saves the video a few seconds after release, so it asks every 5 seconds until it is saved and returns `ComputerRecording(url, duration_seconds, started_at)`, or `None` if none was saved within `timeout` seconds (`recording(timeout=900)`, 15 minutes by default; 0 asks once). A check already under way when `timeout` runs out can take up to 30 seconds more. Called on a computer that is still running it raises `SESSION_BUSY` saying to close it first. `attach()` can't reopen a closed computer, so a later process can't fetch it. Since 0.5.1; earlier versions returned `None` at once while the video was still uploading. It doesn't download the video. Signed URLs in that metadata are credentials. Recording is locally unavailable on devices. Since 0.4.0, a script can click, type and press keys on the computer's screen at points it reads off `screenshot()`: @@ -131,6 +148,38 @@ On a computer, as everywhere, type with `type("description", text)`: it clicks t **Breaking wire change:** computer-operation arguments use `argv_b64` (one padded URL-safe base64 UTF-8 string per argument) and file paths use `path_b64`, with no raw `argv` or `path`. This SDK is incompatible with the previous backend contract. Deploy the encoded-only backend before publishing or upgrading to this SDK. Public APIs and decoded limits are unchanged; `stdin` and file `data` retain their existing standard base64 encoding, and process commands are unchanged. Encoding is not encryption, and Verify does not fall back to plaintext or replay the request. +### validation() and extract() on a Mac + +**Since 0.6.0.** On a Mac opened with `inference=True`, `validation()` and `extract()` run on the Mac's own vision model, next to the computer, and their `StepResult` has `engine="local"`. A typical answer takes 1 to 3 seconds. Local inference is enabled per organization: ask support@revyl.ai. + +```python +from revyl_verify import Target, open + +with open(Target(platform="mac", inference=True)) as mac: + print(mac.inference) # "ready", "unavailable" or "unknown" + mac.validation("The Dock is visible at the bottom of the screen") + date = mac.extract("the date at the right end of the menu bar") + print(date.value, date.engine) # the date as shown, then "local" +``` + +- `validation(text, soft=False)` returns a `StepResult` with `passed`. A false statement raises `VALIDATION_FAILED`, unless you pass `soft=True`, which returns `passed=False`. +- `extract(text)` returns a `StepResult` whose `value` is the string read off the screen. Describe one value that is visible now. When the model finds nothing, it raises `STEP_FAILED` with the model's reason, such as `local_model_found_no_value`. +- An answer the model can't confirm is never a pass: it raises `STEP_FAILED`. Describe one thing that is visible on the screen now. +- Run one step at a time on a computer. The Mac's model also answers for the app sessions inside it, so a step that waits too long for it raises `SESSION_BUSY`, with `step_engine_busy` in the message; try again in a few seconds. While someone controls the screen in the viewer, a step raises `SESSION_BUSY` (`screen_control_held`); try again after they release it. +- `instruction()` stays unavailable on computers. It raises `NOT_AVAILABLE_ON_PLATFORM` and names the calls to use instead: `tap("the Save button")` to click one thing, and `type("the search field", text)` to type into a field. +- Your own `model` or `agent` doesn't run steps on computers; passing one raises `NOT_AVAILABLE_ON_PLATFORM`. + +`mac.inference` says whether the Mac's model answered: `"ready"`, `"unavailable"`, or `"unknown"` when Verify can't tell yet. Verify refreshes it whenever it reads the computer's report: at `open()`, `attach()` and `open_persistent()`, and on each `report()`. It is `None` on every other session, including a Mac opened without inference. + +| Error | When | What to do | +| --- | --- | --- | +| `NOT_AVAILABLE_ON_PLATFORM`, `reason="inference_not_enabled"` | `open()` with `inference=True`, and your organization doesn't have local inference | Ask support@revyl.ai to turn it on, or open the Mac without `inference` | +| `NOT_AVAILABLE_ON_PLATFORM`, `reason="inference_unavailable"` | No Mac with a model is up right now; nothing was started | Try again later, or open the Mac without `inference` | +| `NOT_AVAILABLE_ON_PLATFORM`, `reason="step_engine_unavailable"` | `validation()` or `extract()` on a Mac opened without inference; on a Linux computer, before anything is sent; or on a Mac opened with inference whose model isn't answering | Open the Mac with `Target(platform="mac", inference=True)`. If it already was, check `mac.inference` and try again shortly | +| `INVALID_ARGUMENT` | `inference=True` on a Linux target | Use `Target(platform="mac", inference=True)` | + +[`examples/mac_inference.py`](https://github.com/RevylAI/verify/blob/main/python/examples/mac_inference.py) runs these steps, and with `IOS_APP_ID` and `IOS_BUILD_ID` set also an iOS app inside the Mac (`cd python && uv run python examples/mac_inference.py`). It starts a billable Mac computer. The [Mac model checks guide](https://github.com/RevylAI/verify/blob/main/packages/verify/docs/guides/mac-model-checks.md) has more. + ### Attach and open a hosted browser Attach to an existing active computer with `attach(computer_id)`, or create one with `open(Target(platform="mac"))`. Attaching checks its identity, operating system and unexpired active report without creating or stopping anything on failure. A successful attach takes close ownership by default: exiting its context stops that computer, not merely the local handle. @@ -152,14 +201,47 @@ with attach("aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee", stop_on_close=False) as comp Use real IDs from the same authorized environment; these are placeholders. `stop_on_close=False` leaves a computer you don't own running when the context exits; leave it out only for a computer your script owns. To reach `http://localhost:` on the computer, a service must already be listening there, such as one an earlier step of a `revyl-macos` job started: Verify has no call that starts one, and a process started through `exec()` ends when the command returns. The existing Web build must point to a supported HTTPS source. After startup, `navigate(url)` sends a single deterministic navigation request and accepts HTTP or HTTPS, including localhost, on every Web session. A cold development server may need a warm-up request before navigation succeeds. For hosted browsers localhost means the hosting computer; for ordinary cloud browsers it means that browser's runtime, not your own computer. If navigation times out uncertainly, it may still commit and the session remains usable; re-navigating is your choice. The server runtime owns navigation network policy. The SDK rejects credentials, control characters and backslashes; it never logs the URL. Navigation is unavailable on mobile and computer sessions and returns `None` after a confirmed response. -`computer.open(target)` requires **both** `app_id` and `build_id` UUIDs. Hosted Web accepts `viewport`, `sign_in`, `idle_timeout_seconds` and `start_timeout`, but no `url` or `branch`; the server currently accepts external Web builds, not bundled Web artifacts. Hosted iOS/Android use the selected build and fixed simulator/emulator configuration, so `bundle_id`, `artifact_url`, `device_model`, `os_version`, `url`, `branch`, `viewport` and `sign_in` are unavailable. Mac hosts Web/iOS. All hosting depends on server capability and capacity. +`computer.open(target)` requires **both** `app_id` and `build_id` UUIDs. Hosted Web accepts `viewport`, `sign_in`, `idle_timeout_seconds` and `start_timeout`, but no `url` or `branch`; the server currently accepts external Web builds, not bundled Web artifacts. Hosted iOS/Android use the selected build and fixed simulator/emulator configuration, so `bundle_id`, `artifact_url`, `device_model`, `os_version`, `url`, `branch`, `viewport` and `sign_in` are unavailable. Mac hosts Web/iOS. Hosted iOS and Web also accept `inference`; see [Local inference for iOS and Web inside a Mac](#local-inference-for-ios-and-web-inside-a-mac). All hosting depends on server capability and capacity. -Children reuse their parent's credentials, API/viewer origins, step timeout and log callback. They return normal sessions with instruction, validation, screenshot, report and close methods. The parent's remaining lifetime bounds child startup and worker requests; report and close remain available after expiry. Closing a parent prevents new children, cancels in-flight starts, and gives pending starts and child closes one shared five-second cleanup budget before attempting the computer stop. Child startup failure never closes the parent. Confirmed physical parent release supersedes an earlier child-close uncertainty, which is logged safely. An ambiguous child start is cleaned up using its preallocated ID, without replaying creation. A definitive refusal does not issue a child stop. +Children reuse their parent's credentials, API/viewer origins, step timeout and log callback. They return normal sessions with instruction, validation, extract, screenshot, report and close methods. The parent's remaining lifetime bounds child startup and worker requests; report and close remain available after expiry. Closing a parent prevents new children, cancels in-flight starts, and gives pending starts and child closes one shared five-second cleanup budget before attempting the computer stop. Child startup failure never closes the parent. Confirmed physical parent release supersedes an earlier child-close uncertainty, which is logged safely. An ambiguous child start is cleaned up using its preallocated ID, without replaying creation. A definitive refusal does not issue a child stop. When the computer belongs to another caller, such as a CI runner, use `attach(computer_id, stop_on_close=False)` or `await async_attach(computer_id, stop_on_close=False)`. These attachments are not registered for automatic cleanup. Explicit close or context-manager exit still cancels pending child starts and closes hosted children within the five-second cleanup phase, but never stops the computer; its owner must release it. Child-cleanup failures remain observable. The default is `True`, and ownership is never inferred from the environment. For async code use `async with await async_attach(computer_id) as computer`, then `async with await computer.open(target) as browser` and `await browser.navigate(url)`. Cancelling a child open cleans up only that child and leaves the parent open; cancelling attach before it succeeds does not stop the existing computer. +### Local inference for iOS and Web inside a Mac + +**Since 0.6.0.** An iOS or Web session you open with `computer.open()` inside a Mac opened with `inference=True` runs its steps on the Mac's own vision model first, with Revyl's hosted model as the fallback. This is the default. To run one session's steps on the hosted model only, pass `inference=False` on its `Target`. Macs host iOS and Web sessions only, so leave `inference` out for Android. + +```python +import os + +from revyl_verify import Target, open + +app = Target(platform="ios", app_id=os.environ["IOS_APP_ID"], build_id=os.environ["IOS_BUILD_ID"]) + +with open(Target(platform="mac", inference=True)) as mac: + with mac.open(app) as session: # local inference by default + step = session.validation("The app's first screen is showing") + print(step.engine) # "local" or "hosted" +``` + +- **Runs on the Mac's model:** validations, and instructions that are a single plain tap on one thing. +- **Goes to the hosted model:** `extract()`, typing, multi-step instructions such as "scroll down and then tap back", and any local answer that is uncertain or takes longer than 25 seconds. +- `engine` on each `StepResult` says which model answered. +- **Local verdicts are final.** A validation the Mac's model answers is not checked again by the hosted model. +- If the Mac's model isn't answering when the session starts, `computer.open()` raises `NOT_AVAILABLE_ON_PLATFORM` with `reason="computer_local_inference_unavailable"`. The message says to try again shortly, or to pass `inference=False` to run on the hosted model. +- `inference` on a `Target` you pass to `open()` rather than `computer.open()` raises `INVALID_ARGUMENT`, except on a Mac target. `inference=True` on Android raises `INVALID_ARGUMENT`. + +In a small live comparison on one iOS app, 20 validations (10 true, 10 false), the Mac's model and the hosted model each answered all 20 correctly and never disagreed. Local answers typically took about 2.7 seconds (one took 20) and hosted ones about 10 seconds. The [apps inside an inference Mac guide](https://github.com/RevylAI/verify/blob/main/packages/verify/docs/guides/apps-inside-an-inference-mac.md) has more. + +### What inference costs + +- Steps on a computer have no per-step fee. `validation()` and `extract()` on a Mac computer run only on the Mac's own model, so they carry no inference charge; you pay the Mac's minutes, as for any computer. +- App sessions inside a computer add no device minutes of their own. +- Inside an inference Mac, steps the Mac's model answers carry no inference charge; steps that fall back to Revyl's hosted model are billed as usual. +- Local inference is enabled per organization: ask support@revyl.ai. + ### open() options `open(target, ...)` and `async_open(target, ...)` take these keyword options: @@ -172,6 +254,59 @@ For async code use `async with await async_attach(computer_id) as computer`, the - `agent`: the same with a custom agent from `local_agent()`. Pass `model` or `agent`, not both. - `profile`: a session profile from your project's `.revyl/config.yaml`, such as `"signed-in"`, that Revyl runs before `open()` returns, or `"none"` for no profile. Left out, the project's `session.default_profile` runs when it sets one. Web, iOS, Android and Mac computers. See [Session profiles](#session-profiles). +## Persistent computers and snapshots + +**Since 0.5.0, enabled per organization.** A persistent computer is a Mac whose disk outlives every stop: open it by name, close it, and the next open boots from the same disk. Without persistent computers enabled, `open_persistent()` and `save_snapshot()` raise `NOT_AVAILABLE_ON_PLATFORM` with `reason="persistent_computers_not_enabled"`; ask support@revyl.ai to turn them on. macOS only. + +```python +from revyl_verify import delete_persistent, delete_snapshot, open_persistent, save_snapshot + +with open_persistent("notes-mac") as mac: # creates it the first time + if mac.created: + mac.exec(["sh", "-c", 'echo "kept across stops" > "$HOME/notes.txt"']) +# leaving the with block stops it and keeps its disk + +with open_persistent("notes-mac") as mac: # boots from the same disk + print(mac.created, mac.exec(["sh", "-c", 'cat "$HOME/notes.txt"']).stdout) + +save_snapshot("notes-mac", "notes-base") # waits until the save is copied off its Mac +with open_persistent("notes-copy", from_snapshot="notes-base") as copy: + print(copy.exec(["sh", "-c", 'cat "$HOME/notes.txt"']).stdout) + +delete_persistent("notes-copy") +delete_persistent("notes-mac") +delete_snapshot("notes-base") +``` + +The example starts billable Mac computers and takes several minutes: `save_snapshot()` waits about 5 minutes after the close. + +- **Open.** `open_persistent(name)` opens the Mac with that name, creating it if needed; `mac.created` says which. A stopped one boots from its disk, and a running one is connected to. Names are 1 to 64 letters, digits, `.`, `_` or `-`, start with a letter or digit, and aren't a UUID. The same name opens the same computer from Python, TypeScript and Go. An ID from `list_persistent()` works too. +- **Close.** `close()`, or leaving the `with` block, stops it and keeps the whole disk. The next open is a cold boot: memory and running processes don't survive, so start your servers again. +- **What's kept.** Everything on the disk: files, installed tools, repositories, build products, simulators, app data, system settings, the login keychain and browser profiles. A computer created from a snapshot gets the same disk, but things tied to the original Mac's hardware identity (Apple Account, iCloud, Safari's saved passwords) don't carry over, and websites may open signed out. +- **Each open is a new run** with the usual computer lifetime: 2 hours by default, up to 24 hours with `timeout` (whole seconds). A run starts saving its disk 3 minutes before it ends, so reaching the end keeps the disk. A running persistent computer bills like any computer. +- **Snapshots.** `save_snapshot(computer, name)` saves a stopped computer's disk; close it first, or it raises `SESSION_BUSY`. It waits until the save is copied off its Mac, about 5 minutes after the close, for up to `wait_timeout` seconds (900 by default), then raises `TIMEOUT`; call it again to keep waiting. Snapshot names follow the computer-name rule and are unique in your organization. +- **Copies.** `open_persistent(new_name, from_snapshot="name")` creates a new persistent computer whose disk starts as the snapshot's. `from_snapshot` is used only when the call creates the computer; if one with that name exists, it opens as it is, so check `created`. Starting on a different Mac than the one holding the save, as most snapshot copies do, restores the disk first and can take several minutes. `open_persistent()` waits up to `start_timeout` seconds (900 by default). +- **Inference.** `open_persistent(name, inference=True)` is used only when the call creates the computer, and the computer keeps it for every later start. A copy doesn't inherit it: pass `inference=True` with `from_snapshot` too. `without_inference=True` applies only when starting a stopped computer created with inference: it starts this one run without the model, for when no Mac with one is up (`inference_unavailable`). It needs a Revyl backend that offers it; otherwise it raises `INVALID_ARGUMENT` saying so. +- **How long saves last.** Until you delete the computer or the snapshot. Some saves have an end: `saved_disk_expires_at` on `PersistentComputer` and `ComputerSnapshot` is a `datetime` when Revyl reports one, else `None`. From then on, that save can't start. +- **Limits.** 10 persistent computers and 100 snapshots per organization, unless Revyl raised them. +- **Cleanup.** `delete_persistent(name_or_id)` deletes the computer and its disk for good; a running one stops first, without saving. Its snapshots stay. `delete_snapshot(name_or_id)` deletes a snapshot; computers made from it keep their disks. Both raise `NOT_FOUND` when nothing has that name or ID. +- **Lists.** `list_persistent()` returns a `PersistentComputer` for each of your organization's persistent computers, with `id`, `state`, `saved_at`, `saved_off_host`, `created_at` and `saved_disk_expires_at`. Revyl stores no names, so compare `id` with `mac.id`. `list_snapshots()` returns a `ComputerSnapshot` for each snapshot, with `id`, `name`, `computer_id`, `saved_at` and `saved_disk_expires_at`. + +Where the table shows no `reason`, the message names Revyl's code, shown here in parentheses. + +| Error | When | What to do | +| --- | --- | --- | +| `NOT_AVAILABLE_ON_PLATFORM`, `reason="persistent_computers_not_enabled"` | Your organization doesn't have persistent computers | Ask support@revyl.ai to turn them on | +| `NOT_AVAILABLE_ON_PLATFORM`, `reason="inference_not_enabled"` | `inference=True`, and your organization doesn't have local inference | Ask support@revyl.ai, or leave out `inference` | +| `NOT_AVAILABLE_ON_PLATFORM`, `reason="inference_unavailable"` | No Mac with a model is up right now; nothing was started | Try again later, or pass `without_inference=True` to start an existing computer without the model this once | +| `SESSION_BUSY` (`run_conflict`) | The computer's last run is still stopping | Try again in a few minutes; the disk is kept | +| `SESSION_START_FAILED` (`saved_disk_unavailable`) | The Mac holding the save is offline and the save isn't copied off it yet, or no Mac can start it now | Try again later; the disk is kept | +| `SESSION_START_FAILED` (`saved_disk_expired`) | The computer's save has reached `saved_disk_expires_at` | `delete_persistent()` it; `open_persistent()` with its name then creates a new one | +| `SESSION_START_FAILED` (`snapshot_expired`) | The snapshot has reached `saved_disk_expires_at` | Save a new snapshot of a recently stopped computer | +| `COMPUTER_LIMIT` (`persistent_computer_limit` or `snapshot_limit`) | Your organization keeps as many computers or snapshots as it may | Delete one you no longer need with `delete_persistent()` or `delete_snapshot()`, then try again | + +The [persistent computers guide](https://github.com/RevylAI/verify/blob/main/packages/verify/docs/guides/persistent-computers.md) has more. + ## Session profiles A session profile is a script from your Revyl project that prepares a session before your first step: it signs a user in, seeds data, or sets launch values. Revyl runs the script, never Verify: on Revyl's hosted runner for a browser or an iOS or Android device, and on the Mac itself for a Mac computer. `open()` returns once Revyl reports that the profile succeeded. @@ -350,7 +485,9 @@ size = session.screen_size() # the screenshot's size: x is 0 to size.width - 1 | `launch_app(bundle_id)` | No, use `open_url` or `navigate` | Yes | Yes | No | | `navigate(url)` | Yes | No, use `open_url` | No, use `open_url` | No | | `cdp()`, for Playwright and Puppeteer | Yes, see [CDP](#cdp-playwright-puppeteer) | No | No | No | -| `instruction`, `validation`, your own model | Yes | Yes | Yes | No, use `exec()` and the screen calls above | +| `instruction` | Yes | Yes | Yes | No, use `tap("the Save button")` and `type("the search field", text)` | +| `validation`, `extract` | Yes | Yes | Yes | Yes, on a Mac opened with `inference=True`; see [validation() and extract() on a Mac](#validation-and-extract-on-a-mac) | +| your own model (`model`, `agent`) | Yes | Yes | Yes | No | | `screenshot()` | Yes | Yes | Yes | Yes | | `exec`, files, processes | No, open a Mac computer | No, open a Mac computer | No, open a Mac computer | Yes | @@ -501,7 +638,7 @@ Construct a frozen `Target(platform=...)`: - **Web:** `app_id` (Revyl UUID) is required. Supply `url` for a public HTTPS site, `build_id` for a specific build, or `branch` for the selected app's latest build. `build_id` cannot be combined with `url` or `branch`. Optional `Viewport(width, height, device_scale_factor=...)` and `SignIn(path, secret, persona=...)` configure the browser and saved sign-in secret reference, not a raw credential. - **iOS / Android:** provide exactly one of `app_id`, `build_id`, HTTPS `artifact_url` or installed-app `bundle_id`. Optional `device_model` and `os_version` select the device, written as Revyl names them, such as `device_model="iPhone 16", os_version="iOS 18.5"` or `device_model="Pixel 7", os_version="Android 14"`. A value Revyl doesn't offer raises `INVALID_ARGUMENT` listing the values it accepts, and no session starts. An `app_id` or `build_id` Revyl can't find raises `INVALID_ARGUMENT` naming what wasn't found and how to fix it, and no session starts. A `bundle_id` that can't be launched raises `SESSION_START_FAILED` naming the bundle id, with the session link. Do not combine mobile app sources. -- **Mac:** only `platform` and `start_timeout` are accepted; app/browser/device fields are unavailable. +- **Mac:** only `platform`, `start_timeout`, `timeout` (the lifetime in seconds) and `inference` (run on a Mac with its own vision model; see [validation() and extract() on a Mac](#validation-and-extract-on-a-mac)) are accepted; app/browser/device fields are unavailable. `start_timeout` defaults to 600 seconds (allowed range 10–1800). Web/mobile also accept `idle_timeout_seconds` (60–3600). `open`, `async_open`, `attach` and `async_attach` accept default `step_timeout` in seconds. @@ -525,17 +662,17 @@ else: Cleanup status is `acknowledged` for a validated device stop response, `confirmed` for terminal computer state plus physical release, `unconfirmed` when cleanup failed or no usable mobile identity was returned, and `not_required` after a definite create refusal. `not_attempted` applies before startup ownership exists. An unknown mobile ID is `None`, never invented. Web/computer caller-generated IDs remain available after an uncertain create; a mismatched web acknowledgment never authorizes stopping the other ID. Startup cleanup uses a fresh bounded deadline, preserves the original failure, and attaches a separate cleanup error. Do not retry creation to recover an uncertain outcome; inspect the known session privately. A device stop acknowledgment does not prove physical release. -Session properties include `id`, `platform`, `viewer_url`, `expires_at` and `closed`. Steps return `StepResult` with `passed`, `reason`, `duration_seconds` and, for a step run on your own model, `model`; commands return `ExecResult` with `exit_code`, `stdout` and `stderr`. Computer methods also include `stat(path)`, `processes()` and `terminate(handle_id)`, with bounded seconds-based timeouts. Errors raise `VerifyError` with a stable `code`. Async session methods have the same arguments/results and are awaited. +Session properties include `id`, `platform`, `viewer_url`, `expires_at` and `closed`. Steps return `StepResult` with `passed`, `reason`, `duration_seconds`, `value` (extract steps only), `engine` (`"local"` or `"hosted"` when Revyl says which model answered, else `None`) and, for a step run on your own model, `model`; commands return `ExecResult` with `exit_code`, `stdout` and `stderr`. Computer methods also include `stat(path)`, `processes()` and `terminate(handle_id)`, with bounded seconds-based timeouts. Errors raise `VerifyError` with a stable `code`. Async session methods have the same arguments/results and are awaited. `EDGE_BLOCKED` identifies HTTP 403 with a `text/html` content type and nonempty `cf-ray`, unless the body is syntactically valid JSON. HTML branding is not required; `cf-ray` alone is not enough. Other responses retain their existing mapping, including JSON 401/403 authentication errors. Edge-block errors expose `http_status` but no body or ray ID. Check network access or contact support; Verify does not retry blocked requests. `VerifyError.reason` is an optional exported `RefusalReason` literal containing only a known safe server code; `http_status` is the response status when available. Raw server messages and payloads are not exposed through these fields. Ordinary Web startup `409 web_runtime_unavailable` keeps `code="API_ERROR"`, computer admission keeps `COMPUTER_LIMIT` for `computer_limit` and `NOT_AVAILABLE_ON_PLATFORM` for `runtime_unavailable`; inspect `reason` to distinguish availability from other failures. Hosted errors use `NOT_AVAILABLE_ON_PLATFORM` for runtime/capability refusals, `COMPUTER_LIMIT` for capacity, `SESSION_ENDED` for `computer_not_running`, `NOT_FOUND` for `computer_not_found`, `INVALID_ARGUMENT` for build selection and `SESSION_BUSY` for child identity conflicts. Unknown reasons remain `None`; no refusal automatically retries creation. -| Platform | Instructions / validations | Commands / files / processes | PNG screenshot | +| Platform | Instructions / validations / extract | Commands / files / processes | PNG screenshot | | --- | :---: | :---: | :---: | | Web | Yes, if the backend supports web steps | — | Yes | | iOS simulator / Android emulator | Yes | — | Yes | -| Mac computer | — | Yes | Yes | +| Mac computer | Validations and extract, on a Mac opened with `inference=True` | Yes | Yes | Mac computers are available to organizations on a current paid Revyl plan. When Revyl says Pro would unlock Macs for a Free-plan organization (`computer_not_enabled` with `unlocks_with_card: true`), `open()` and `open_persistent()` raise `NOT_AVAILABLE_ON_PLATFORM` with `reason="upgrade_required"`. The message starts `Mac computers come with Pro, so Revyl refused this computer (computer_not_enabled, upgrade_required).` and ends with Revyl's upgrade offer and its HTTPS billing link, or with `Add a card in Revyl's billing settings to unlock them.` when Revyl sends no offer. Any other `computer_not_enabled` keeps the support guidance and no reason. Computer admission may return `COMPUTER_LIMIT`; the SDK does not retry creation. Computer sessions have a hard lifetime from creation: 2 hours by default, or up to 24 hours with `Target(platform="mac", timeout=...)` (seconds, 60 to 86400). `session.extend(timeout)` keeps a running computer going at least that long from now, up to 24 hours after creation; it never shortens the lifetime, so retrying is safe, and it refreshes `expires_at`, the authoritative deadline. Lifetimes over 2 hours can be refused with `COMPUTER_LIMIT` (`computer_long_limit`, at most 2 such computers per organization at once) or `NOT_AVAILABLE_ON_PLATFORM` (no host can run that long, or the host can't extend). Screenshot observation retries structured startup screen-not-ready errors within a bounded window; other errors are not silently replayed. @@ -564,13 +701,17 @@ Use an empty `dist/` before building; the package checker rejects stale or extra - [TypeScript API and platform contracts](https://github.com/RevylAI/verify/tree/main/packages/verify/docs) - [Use your own model](https://github.com/RevylAI/verify/blob/main/packages/verify/docs/own-model.md): providers, live results and troubleshooting, which apply to Python too +- [Mac model checks](https://github.com/RevylAI/verify/blob/main/packages/verify/docs/guides/mac-model-checks.md): `validation()` and `extract()` on a Mac opened with inference +- [Apps inside an inference Mac](https://github.com/RevylAI/verify/blob/main/packages/verify/docs/guides/apps-inside-an-inference-mac.md): local inference for iOS and Web sessions +- [Persistent computers](https://github.com/RevylAI/verify/blob/main/packages/verify/docs/guides/persistent-computers.md): persistent Macs and snapshots - [Go SDK](https://github.com/RevylAI/verify/tree/main/go) - [Live results from other SDKs and limitations](https://github.com/RevylAI/verify/blob/main/packages/verify/docs/end-to-end.md) - [Python release procedure](https://github.com/RevylAI/verify/blob/main/RELEASING.md#python) ## Troubleshooting -- **`NOT_AVAILABLE_ON_PLATFORM`:** computers do not support instruction/validation, your own model, or exact actions other than `tap`, `type`, `screen_size()`, `type_focused(text, clear=False)` and `press_key`; devices do not support commands, files, processes or recording metadata; iOS has no `back()`, Web has no `launch_app()` or `go_home()`, and iOS and Android have no `type_focused()` and no keys other than Enter and Backspace. +- **`NOT_AVAILABLE_ON_PLATFORM`:** computers do not support `instruction()` (use `tap("the Save button")` and `type("the search field", text)`), `validation()` or `extract()` except on a Mac opened with `inference=True`, your own model, or exact actions other than `tap`, `type`, `screen_size()`, `type_focused(text, clear=False)` and `press_key`; devices do not support commands, files, processes or recording metadata; iOS has no `back()`, Web has no `launch_app()` or `go_home()`, and iOS and Android have no `type_focused()` and no keys other than Enter and Backspace. +- **`STEP_FAILED` from `extract()` or a Mac validation:** nothing was read, or the model couldn't confirm an answer. Describe one value or one thing that is visible on the screen now, and check it with `screenshot()`. - **`SESSION_PROFILE_FAILED`:** the session profile's script couldn't be sent, Revyl couldn't find it, or it ran and failed. `error.outcome` and `error.failure_reason` say which; see [Session profile errors](#session-profile-errors). - **`MODEL_KEY_MISSING`:** the provider's key variable named in the message is not set. Set it, or pass `CustomModel(id, base_url, api_key=...)`. - **`MODEL_ERROR`:** the model's endpoint refused the request or the model misbehaved. The message names the host, the HTTP status and the next step: a rejected key and the variable it came from, an unknown model, the path Verify added on a 404, a rate limit after retries, a text-only model, no tool support, a reply cut off at its output cap, or three turns without a tool call. diff --git a/python/examples/mac_inference.py b/python/examples/mac_inference.py new file mode 100644 index 0000000..a96cda0 --- /dev/null +++ b/python/examples/mac_inference.py @@ -0,0 +1,28 @@ +"""Check a Revyl Mac computer's screen with the Mac's own vision model, then an iOS app inside it. + + cd python && uv run python examples/mac_inference.py + +Needs REVYL_API_KEY (or a saved Revyl login from 'revyl auth login') and an organization with +Mac computers and local inference (ask support@revyl.ai to turn them on). It starts a real, +billable Mac computer. Set IOS_APP_ID and IOS_BUILD_ID to also open that iOS build inside the +Mac, where its steps run on the Mac's model first by default. +""" + +import os + +from revyl_verify import Target, open + +mac = open(Target(platform="mac", inference=True)) +try: + print(f"inference: {mac.inference}") # "ready", "unavailable" or "unknown" + mac.validation("The Dock is visible at the bottom of the screen") + date = mac.extract("the date at the right end of the menu bar") + print(f"menu bar date: {date.value} (engine: {date.engine})") + + app_id, build_id = os.environ.get("IOS_APP_ID"), os.environ.get("IOS_BUILD_ID") + if app_id and build_id: + with mac.open(Target(platform="ios", app_id=app_id, build_id=build_id)) as app: + step = app.validation("The app's first screen is showing", soft=True) + print(f"app validation passed: {step.passed} (engine: {step.engine})") +finally: + mac.close() diff --git a/python/pyproject.toml b/python/pyproject.toml index e4df0d4..f05f675 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "revyl-verify" -version = "0.5.1" +version = "0.6.0" description = "Cloud browsers, mobile devices and computers from Python with Revyl" readme = "README.md" requires-python = ">=3.10" diff --git a/python/src/revyl_verify/__init__.py b/python/src/revyl_verify/__init__.py index b16a550..3267416 100644 --- a/python/src/revyl_verify/__init__.py +++ b/python/src/revyl_verify/__init__.py @@ -33,6 +33,7 @@ ) from ._models import ( CDPEndpoint, + ComputerInferenceReadiness, ComputerProcess, ComputerRecording, ExecResult, @@ -69,10 +70,11 @@ seconds, ) -__version__ = "0.5.1" +__version__ = "0.6.0" __all__ = [ "AsyncSession", "CDPEndpoint", + "ComputerInferenceReadiness", "ComputerProcess", "ComputerRecording", "ComputerSession", diff --git a/python/src/revyl_verify/_async.py b/python/src/revyl_verify/_async.py index cb24ea1..428f64e 100644 --- a/python/src/revyl_verify/_async.py +++ b/python/src/revyl_verify/_async.py @@ -13,6 +13,7 @@ from ._cleanup import _close, install_signal_cleanup from ._models import ( CDPEndpoint, + ComputerInferenceReadiness, ComputerProcess, ComputerRecording, ExecResult, @@ -57,6 +58,10 @@ def closed(self) -> bool: def steps(self) -> list[StepResult]: return list(self._session.steps) + @property + def inference(self) -> ComputerInferenceReadiness | None: + return self._session.inference + async def __aenter__(self) -> AsyncSession: return self @@ -113,6 +118,9 @@ async def validation( ) ) + async def extract(self, text: str, *, timeout: float | None = None) -> StepResult: + return await self._call(functools.partial(self._session.extract, text, timeout=timeout)) + async def tap(self, at: Location, *, settle: bool = True) -> Point: return await self._call(functools.partial(self._session.tap, at, settle=settle)) diff --git a/python/src/revyl_verify/_computer.py b/python/src/revyl_verify/_computer.py index 768f3b7..c609e10 100644 --- a/python/src/revyl_verify/_computer.py +++ b/python/src/revyl_verify/_computer.py @@ -7,9 +7,10 @@ import time import uuid from collections.abc import Callable, Sequence +from dataclasses import replace from datetime import datetime, timezone from pathlib import Path -from typing import NoReturn +from typing import Literal, NoReturn, cast from urllib.parse import quote, urlsplit from ._agent import ( @@ -24,6 +25,7 @@ ) from ._cleanup import track, untrack from ._models import ( + ComputerInferenceReadiness, ComputerProcess, ComputerRecording, ExecResult, @@ -31,6 +33,7 @@ Platform, Point, ScreenSize, + StepResult, Target, text_length, ) @@ -56,6 +59,7 @@ mac_upgrade_message, obj, refusal_reason, + seconds, timestamp, ) @@ -93,6 +97,10 @@ "screen_text_unsupported", "screen_target_not_found", "screen_target_unavailable", + "step_engine_unavailable", + "step_engine_busy", + "inference_unavailable", + "inference_not_enabled", } _AVAILABILITY = ( "Mac computers need a current paid Revyl plan, and Linux computers are not generally " @@ -119,6 +127,11 @@ 'type("description", text), type_focused(text, clear=False) and press_key(); for ' "commands, use exec()." ) +_NO_MODEL = ( + "validation() and extract() on a computer run on the vision model of the Mac it runs on, so " + 'open it with open(Target(platform="mac", inference=True)). A persistent computer gets the ' + "model only when it is created: open_persistent(new_name, inference=True)." +) _REFUSAL_NEXT_STEPS: dict[str, str] = { "AUTH_REJECTED": "Check that REVYL_API_KEY is a current key and that its owner has the " "Member role or above in this computer's organization.", @@ -301,6 +314,18 @@ def __init__( self._child_condition = threading.Condition(self._lock) self._stop_on_close: bool = True self._start_timeout: float = 600 + self._inference_requested: bool = False + self._inference_readiness: ComputerInferenceReadiness | None = None + + @property + def inference(self) -> ComputerInferenceReadiness | None: + """Only on a Mac opened with inference=True: whether its own vision model answered when + Verify last read the computer's report (at open, and on each report() call). "ready" + answers now, "unavailable" doesn't, "unknown" can't be told yet. None on a computer opened + without inference.""" + if not self._inference_requested: + return None + return self._inference_readiness or "unknown" @classmethod def attach( @@ -346,6 +371,8 @@ def open(self, target: Target, *, _cancellation: Cancellation | None = None) -> if not isinstance(target, Target): raise VerifyError("INVALID_ARGUMENT", "open() requires a Target value.") target.validate(hosted=True) + if target.inference is None and self._inference_requested and target.platform != "android": + target = replace(target, inference=True) with self._child_condition: self._assert_computer_open() if self.expires_at is None: @@ -374,6 +401,7 @@ def open(self, target: Target, *, _cancellation: Cancellation | None = None) -> cancellation, computer_session_id=self.id, expires_at=self.expires_at, + computer_inference=self._inference_requested, ) with self._child_condition: closing = self._closed @@ -405,11 +433,13 @@ def start( computer_session_id: str | None = None, expires_at: datetime | None = None, profile: SessionProfilePlan | None = None, + computer_inference: bool = False, ) -> ComputerSession: if ( target.platform not in {"mac", "linux"} or computer_session_id is not None or expires_at is not None + or computer_inference ): raise VerifyError("INVALID_ARGUMENT", "A computer target must be mac or linux.") session_id = str(uuid.uuid4()) @@ -427,6 +457,7 @@ def start( session._log_callback = log session._profile = profile session._start_timeout = target.start_timeout + session._inference_requested = target.inference is True acknowledged = False try: track(session) @@ -437,6 +468,8 @@ def start( } if target.timeout is not None: body["timeout_seconds"] = target.timeout + if target.inference: + body["inference"] = True if profile is not None: body.update(profile.fields) for attempt in range(len(REPOSITORY_RETRY_DELAYS) + 1): @@ -660,6 +693,57 @@ def _request( reason="lifetime_unsupported", http_status=response.status, ) + if suffix == "" and method == "POST" and detail == "inference_not_enabled": + raise VerifyError( + "NOT_AVAILABLE_ON_PLATFORM", + "Local inference isn't enabled for this API key's organization " + "(inference_not_enabled). Ask support@revyl.ai to turn it on, or open the Mac " + 'without inference: open(Target(platform="mac")).', + reason="inference_not_enabled", + http_status=response.status, + ) + if suffix == "" and method == "POST" and detail == "inference_unavailable": + raise VerifyError( + "NOT_AVAILABLE_ON_PLATFORM", + "No Mac with its own vision model is up to take this computer right now " + "(inference_unavailable), so nothing was started. Try again later, or open the Mac " + 'without inference: open(Target(platform="mac")).', + reason="inference_unavailable", + http_status=response.status, + ) + if suffix == "/steps": + if detail == "step_engine_unavailable": + raise VerifyError( + "NOT_AVAILABLE_ON_PLATFORM", + "This Mac's own vision model isn't answering right now " + "(step_engine_unavailable), so the step didn't run. computer.inference shows " + f"whether it is ready; try again shortly. See {self.viewer_url}" + if self._inference_requested + else "This computer has no vision model of its own (step_engine_unavailable), " + f"so the step didn't run. {_NO_MODEL} To click or type by description on any " + 'Mac, use tap("description") and type("description", text). ' + f"See {self.viewer_url}", + reason="step_engine_unavailable", + http_status=response.status, + ) + if detail == "step_engine_busy": + raise VerifyError( + "SESSION_BUSY", + "This Mac's vision model is busy with another step (step_engine_busy), so the " + "step didn't run. Run one step at a time on a computer, and try again in a few " + f"seconds. See {self.viewer_url}", + reason=reason, + http_status=response.status, + ) + if detail == "screen_control_held": + raise VerifyError( + "SESSION_BUSY", + "The step didn't run: someone else is controlling this computer's screen in " + "the viewer (screen_control_held). Try again after they release it; control " + f"frees itself after 2 minutes without input. See {self.viewer_url}", + reason=reason, + http_status=response.status, + ) if response.status == 409 and detail == "extend_unsupported": raise VerifyError( "NOT_AVAILABLE_ON_PLATFORM", @@ -771,6 +855,11 @@ def _report(self, response: Response) -> dict[str, Json]: ) for child in self._children: child._expires_at = self._expires_at + inference = raw.get("inference") + if inference in ("ready", "unavailable", "unknown"): + with self._lock: + self._inference_requested = True + self._inference_readiness = cast(ComputerInferenceReadiness, inference) return raw def report(self) -> dict[str, Json]: @@ -1168,7 +1257,13 @@ def instruction( model: ModelOption | None = None, agent: LocalAgent | None = None, ) -> NoReturn: - self._unavailable("instruction") + raise VerifyError( + "NOT_AVAILABLE_ON_PLATFORM", + "instruction() is not available on computers. To click one thing by its description, " + 'use tap("the Save button"); to type into a field, use type("the search field", ' + "text). validation() and extract() do work on a Mac opened with " + f'Target(platform="mac", inference=True). See {self.viewer_url}', + ) def validation( self, @@ -1178,8 +1273,134 @@ def validation( soft: bool = False, model: ModelOption | None = None, agent: LocalAgent | None = None, - ) -> NoReturn: - self._unavailable("validation") + ) -> StepResult: + """Asks the Mac's own vision model whether something holds on screen, such as "the + Settings window is open". Raises VALIDATION_FAILED when it does not, unless soft is set, + and STEP_FAILED when the model could not reach a verdict. Needs a Mac opened with + inference=True; otherwise raises NOT_AVAILABLE_ON_PLATFORM.""" + if not isinstance(soft, bool): + raise VerifyError("INVALID_ARGUMENT", "soft must be a boolean.") + result = self._computer_step("validation", text, timeout, model, agent) + if not result.passed and not soft: + reason = re.sub(r"[.\s]*$", "", result.reason) + ". " if result.reason else "" + raise VerifyError( + "VALIDATION_FAILED", + f'Validation failed: "{result.text}". {reason}See {self.viewer_url}', + result=result, + ) + return result + + def extract(self, text: str, *, timeout: float | None = None) -> StepResult: + """Reads a value off the screen with the Mac's own vision model, such as "the build number + in the About window", and returns the step with it in value. Raises STEP_FAILED when + nothing could be read. Needs a Mac opened with inference=True; otherwise raises + NOT_AVAILABLE_ON_PLATFORM.""" + return self._computer_step("extract", text, timeout, None, None) + + def _computer_step( + self, + kind: Literal["validation", "extract"], + text: str, + timeout: float | None, + model: ModelOption | None, + agent: LocalAgent | None, + ) -> StepResult: + self._assert_computer_open() + if not isinstance(text, str) or not text.strip() or text_length(text) > 2_000: + raise VerifyError( + "INVALID_ARGUMENT", + f"{kind}() on a computer takes a description of 1 to 2000 characters.", + ) + if model is not None or agent is not None: + raise VerifyError( + "NOT_AVAILABLE_ON_PLATFORM", + "Your own model runs steps on browsers and devices, not on computers. Leave out " + f"model and agent; {kind}() on a Mac runs on the Mac's own vision model.", + ) + duration = seconds( + self._step_timeout if timeout is None else timeout, 1, 3600, "Step timeout" + ) + if self.platform != "mac": + raise VerifyError( + "NOT_AVAILABLE_ON_PLATFORM", + f"{kind}() is not available on Linux computers: {_NO_MODEL} {_SCREEN_CALLS}", + reason="step_engine_unavailable", + ) + description = text.strip() + started = time.monotonic() + deadline = self._observation_deadline(duration) + try: + response = self._request( + "POST", + "/steps", + {"step_type": kind, "description": description}, + deadline, + duration, + ) + except VerifyError as error: + self._log(f'✗ {kind} "{description}": {error.code}') + if deadline.expired() and not self._cancellation.event.is_set(): + raise VerifyError( + "TIMEOUT", + f'The {kind} did not finish within {duration:g} seconds: "{description}". ' + f"Pass a larger timeout. See {self.viewer_url}", + ) from error + raise + raw = obj(response.json()) + status, engine = raw.get("status"), raw.get("engine") + if ( + raw.get("step_type") != kind + or status not in ("passed", "failed", "uncertain") + or engine not in ("local", "hosted") + ): + raise _invalid() + status_reason = raw.get("status_reason") + reason = status_reason if isinstance(status_reason, str) and status_reason else None + extracted = raw.get("extracted_data") + value = extracted.get("information") if isinstance(extracted, dict) else None + verdict = raw.get("validation_result") + if ( + status == "uncertain" + or (kind == "validation" and not isinstance(verdict, bool)) + or (kind == "extract" and (status != "passed" or not isinstance(value, str))) + ): + self._log( + f'✗ {kind} "{description}": no {"verdict" if kind == "validation" else "value"}' + ) + because = re.sub(r"[.\s]*$", "", reason) + ". " if reason else "" + raise VerifyError( + "STEP_FAILED", + f'Validation did not reach a verdict: "{description}". {because}The Mac' + "'s model wasn't sure; describe one thing that is visible on the screen now. " + f"See {self.viewer_url}" + if kind == "validation" + else f'Extract read nothing: "{description}". {because}Describe one value that ' + 'is on the screen now, such as "the version number in the About window". ' + f"See {self.viewer_url}", + ) + passed = verdict is True if kind == "validation" else True + result = StepResult( + kind, + description, + passed, + reason, + time.monotonic() - started, + value=value if kind == "extract" and isinstance(value, str) else None, + engine="local" if engine == "local" else "hosted", + ) + self.steps.append(result) + self._log( + f'{"✓" if passed else "✗"} {kind} "{description}" ' + f"({result.duration_seconds:.1f}s, {result.engine} model)" + + ( + f": {value}" + if kind == "extract" + else f": {reason}" + if not passed and reason + else "" + ) + ) + return result def tap(self, at: Location, *, settle: bool = True) -> Point: """Clicks a point in screenshot pixels, or an element Revyl finds from a description. diff --git a/python/src/revyl_verify/_login.py b/python/src/revyl_verify/_login.py index d745ef1..ad73cf8 100644 --- a/python/src/revyl_verify/_login.py +++ b/python/src/revyl_verify/_login.py @@ -179,7 +179,7 @@ def _call( ) -> dict[str, Json]: headers = { "Accept": "application/json", - "User-Agent": "revyl-verify/0.5.1 python", + "User-Agent": "revyl-verify/0.6.0 python", "X-Revyl-Client": "verify", } data = None diff --git a/python/src/revyl_verify/_models.py b/python/src/revyl_verify/_models.py index 3d02cdb..66edf83 100644 --- a/python/src/revyl_verify/_models.py +++ b/python/src/revyl_verify/_models.py @@ -9,6 +9,7 @@ from ._transport import VerifyError, seconds Platform = Literal["web", "ios", "android", "mac", "linux"] +ComputerInferenceReadiness = Literal["ready", "unavailable", "unknown"] UUID_PATTERN = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", re.I) @@ -46,6 +47,12 @@ class Target: viewport: Viewport | None = None sign_in: SignIn | None = None timeout: int | None = None + inference: bool | None = None + """Mac: run the computer on a Mac whose own vision model is loaded, so validation() and + extract() work on it and iOS and Web sessions opened inside it use that model too. Enabled per + organization. Inside a computer (computer.open()), iOS and Web: run this session's steps on + the hosting Mac's own vision model first, with Revyl's hosted model as the fallback; defaults + to True inside a computer opened with inference=True, and False turns it off.""" def validate(self, *, hosted: bool = False) -> None: def bad(message: str) -> None: @@ -53,6 +60,8 @@ def bad(message: str) -> None: if self.platform not in ("web", "ios", "android", "mac", "linux"): bad("Platform must be web, ios, android, mac, or linux.") + if self.inference is not None and not isinstance(self.inference, bool): + bad("inference must be True or False.") if hosted: if self.platform not in ("web", "ios", "android"): bad("Hosted targets must be web, ios, or android.") @@ -91,9 +100,14 @@ def bad(message: str) -> None: if any( getattr(self, field.name) is not None for field in fields(self) - if field.name not in ("platform", "start_timeout", "timeout") + if field.name not in ("platform", "start_timeout", "timeout", "inference") ): - bad("Computer targets accept only platform, start_timeout, and timeout.") + bad("Computer targets accept only platform, start_timeout, timeout, and inference.") + if self.inference is True and self.platform == "linux": + bad( + 'inference is for Mac computers only; use Target(platform="mac", ' + "inference=True)." + ) if self.timeout is not None and ( type(self.timeout) is not int or not 60 <= self.timeout <= 86_400 ): @@ -101,6 +115,16 @@ def bad(message: str) -> None: return if self.timeout is not None: bad("timeout applies only to mac and linux targets.") + if self.inference is not None and not hosted: + bad( + "inference applies only to mac targets and to iOS and Web targets passed to " + "computer.open()." + ) + if self.inference is True and self.platform == "android": + bad( + "inference runs only for iOS and Web sessions inside a Mac computer; leave it " + "out for Android." + ) if self.idle_timeout_seconds is not None and ( type(self.idle_timeout_seconds) is not int or not 60 <= self.idle_timeout_seconds <= 3600 @@ -220,12 +244,17 @@ class ModelRun: @dataclass(frozen=True) class StepResult: - type: Literal["instruction", "validation"] + type: Literal["instruction", "validation", "extract"] text: str passed: bool reason: str | None duration_seconds: float model: ModelRun | None = None + value: str | None = None + """What extract() read off the screen. Extract steps only.""" + engine: Literal["local", "hosted"] | None = None + """Who answered, when Revyl says: "local" is the vision model on the Revyl computer the step + ran on or inside (Target(platform="mac", inference=True)), "hosted" is Revyl's hosted model.""" @dataclass(frozen=True) diff --git a/python/src/revyl_verify/_persistent.py b/python/src/revyl_verify/_persistent.py index 380adb6..e67cc84 100644 --- a/python/src/revyl_verify/_persistent.py +++ b/python/src/revyl_verify/_persistent.py @@ -18,6 +18,7 @@ Client, Deadline, Json, + RefusalReason, Response, VerifyError, edge_blocked_error, @@ -64,6 +65,9 @@ class PersistentComputer: """Whether that save has been copied off the Mac that made it. save_snapshot() needs this and waits for it.""" created_at: datetime + saved_disk_expires_at: datetime | None = None + """When its current save stops being startable, if Revyl reports an end; after it, + open_persistent() raises SESSION_START_FAILED (saved_disk_expired).""" @dataclass(frozen=True) @@ -75,6 +79,9 @@ class ComputerSnapshot: saved_at: datetime expires_at: datetime | None """When the save stops being usable, if it has an end.""" + saved_disk_expires_at: datetime | None = None + """When a computer can no longer be created from it, if Revyl reports an end; after it, + open_persistent() with from_snapshot raises SESSION_START_FAILED (snapshot_expired).""" class PersistentComputerSession(ComputerSession): @@ -153,6 +160,8 @@ def open_persistent( *, from_snapshot: str | None = None, timeout: int | None = None, + inference: bool = False, + without_inference: bool = False, start_timeout: float = 900, backend_url: str | None = None, app_url: str | None = None, @@ -173,6 +182,14 @@ def open_persistent( whole seconds from 60 to 86400. Defaults to 2 hours. Not applied when the computer was already running. Same as Target("mac", timeout=...). + inference: used only when this call creates the computer: run it on Macs whose own vision + model is loaded, as Target("mac", inference=True) does, so validation() and extract() work on + it. The computer keeps this for every later start. + + without_inference: used only when this call starts a stopped computer that was created with + inference: start this run on any Mac, without the model, for when no Mac with one is up. Later + starts ask for the model again. Needs a Revyl backend that offers it. + start_timeout: seconds to wait until it is ready, 10-1800, default 900. Covers waiting for an earlier stop to finish saving, and a start from a snapshot, which takes up to about 3 minutes. @@ -201,6 +218,10 @@ def open_persistent( isinstance(timeout, bool) or not isinstance(timeout, int) or not 60 <= timeout <= 86400 ): raise VerifyError("INVALID_ARGUMENT", "timeout must be whole seconds from 60 to 86400.") + if not isinstance(inference, bool): + raise VerifyError("INVALID_ARGUMENT", "inference must be True or False.") + if not isinstance(without_inference, bool): + raise VerifyError("INVALID_ARGUMENT", "without_inference must be True or False.") if ( isinstance(start_timeout, bool) or not isinstance(start_timeout, (int, float)) @@ -223,6 +244,9 @@ def open_persistent( session._save_lock = threading.RLock() session._log_callback = progress lifetime: dict[str, Json] | None = None if timeout is None else {"timeout_seconds": timeout} + start_body: dict[str, Json] | None = ( + {**(lifetime or {}), "without_inference": True} if without_inference else lifetime + ) started = False attempted = False try: @@ -241,6 +265,8 @@ def open_persistent( body.update(lifetime) if from_snapshot: body["from_snapshot"] = from_snapshot + if inference: + body["inference"] = True attempted = True response = _call( client, @@ -257,6 +283,11 @@ def open_persistent( else: if from_snapshot: session._log(f"already exists, so from_snapshot {from_snapshot} was not used") + if inference: + session._log( + "already exists, so inference was not changed; a computer keeps the " + "inference it was created with" + ) waiting = False while status.state in ("stopping", "stopped"): if status.state == "stopped": @@ -266,9 +297,13 @@ def open_persistent( "POST", f"{_BASE}/{computer_id}/start", deadline, - lifetime, + start_body, retry=True, accept=("run_conflict",), + invalid="This Revyl backend refused without_inference, which it does not " + "offer yet. Leave it out to start the computer as it was created." + if without_inference + else None, ) if started_response.status < 300: started = True @@ -583,6 +618,7 @@ def _call( retry: bool | None = None, not_found: str | None = None, accept: tuple[str, ...] = (), + invalid: str | None = None, ) -> Response: response = client.request( method, @@ -613,9 +649,7 @@ def _call( raise VerifyError( known[0], known[1], - reason="persistent_computers_not_enabled" - if detail == "persistent_computers_not_enabled" - else None, + reason=_REFUSAL_REASONS.get(detail or ""), http_status=response.status, ) suffix = f", {detail}" if detail else "" @@ -633,6 +667,8 @@ def _call( not_found or f"Revyl could not find {path} (inaccessible).", http_status=404, ) + if (response.status == 422 or detail == "invalid_request") and invalid: + raise VerifyError("INVALID_ARGUMENT", invalid, http_status=response.status) if response.status == 422 or detail == "invalid_request": raise VerifyError( "INVALID_ARGUMENT", @@ -715,6 +751,17 @@ def _call( "an ID from " "list_persistent().", ), + "inference_not_enabled": ( + "NOT_AVAILABLE_ON_PLATFORM", + "Local inference isn't enabled for this API key's organization (inference_not_enabled). " + "Ask support@revyl.ai to turn it on, or leave out inference.", + ), + "inference_unavailable": ( + "NOT_AVAILABLE_ON_PLATFORM", + "No Mac with its own vision model is up to take this computer right now " + "(inference_unavailable), so nothing was started. Try again later; to start an existing " + "computer without the model this once, pass without_inference=True.", + ), "run_conflict": ( "SESSION_BUSY", "The computer's last run hasn't finished stopping (run_conflict). Its disk is kept; try " @@ -722,6 +769,11 @@ def _call( "minutes.", ), } +_REFUSAL_REASONS: dict[str, RefusalReason] = { + "persistent_computers_not_enabled": "persistent_computers_not_enabled", + "inference_not_enabled": "inference_not_enabled", + "inference_unavailable": "inference_unavailable", +} def _detail(response: Response) -> str | None: @@ -772,12 +824,16 @@ def _to_computer(raw: Json) -> PersistentComputer: ): raise _invalid() saved_at = record.get("saved_at") + saved_disk_expires_at = record.get("saved_disk_expires_at") return PersistentComputer( id=computer_id.lower(), state=cast(PersistentComputerState, state), saved_at=None if saved_at is None else timestamp(saved_at), saved_off_host=durable, created_at=timestamp(record.get("created_at")), + saved_disk_expires_at=None + if saved_disk_expires_at is None + else timestamp(saved_disk_expires_at), ) @@ -793,12 +849,16 @@ def _to_snapshot(raw: Json) -> ComputerSnapshot: ): raise _invalid() expires_at = record.get("expires_at") + saved_disk_expires_at = record.get("saved_disk_expires_at") return ComputerSnapshot( id=snapshot_id.lower(), name=name, computer_id=computer_id.lower(), saved_at=timestamp(record.get("saved_at")), expires_at=None if expires_at is None else timestamp(expires_at), + saved_disk_expires_at=None + if saved_disk_expires_at is None + else timestamp(saved_disk_expires_at), ) diff --git a/python/src/revyl_verify/_session.py b/python/src/revyl_verify/_session.py index 4ba5cba..79b922f 100644 --- a/python/src/revyl_verify/_session.py +++ b/python/src/revyl_verify/_session.py @@ -47,6 +47,7 @@ from ._models import ( UUID_PATTERN, CDPEndpoint, + ComputerInferenceReadiness, ComputerProcess, ComputerRecording, ExecResult, @@ -237,6 +238,13 @@ def expires_at(self) -> datetime | None: def closed(self) -> bool: return self._closed + @property + def inference(self) -> ComputerInferenceReadiness | None: + """Computers opened with inference=True only: whether the Mac's own vision model answered + when Verify last read the computer's report (at open and on each report()): "ready", + "unavailable" or "unknown". None everywhere else.""" + return None + def __enter__(self) -> Session: return self @@ -268,6 +276,7 @@ def start( computer_session_id: str | None = None, expires_at: datetime | None = None, profile: SessionProfilePlan | None = None, + computer_inference: bool = False, ) -> Session: cancellation = cancellation or Cancellation() deadline = Deadline(target.start_timeout, cancellation) @@ -318,6 +327,8 @@ def start( body[key] = value if profile is not None: body.update(profile.fields) + if hosted and target.inference: + body["inference"] = "local" session = cls( client, proposed_id if target.platform == "web" or hosted else "", @@ -360,6 +371,24 @@ def start( or (start_refusal(response) if mobile else None) or http_error(response, hosted=hosted) ) + if hosted and error.reason == "computer_local_inference_unavailable": + error = VerifyError( + "NOT_AVAILABLE_ON_PLATFORM", + f"Revyl refused the {target.platform} session's local inference " + "(computer_local_inference_unavailable): the hosting computer has no " + "vision model answering. " + + ( + "It was opened with inference=True but its Mac's model isn't " + "answering now (computer.inference shows it); try again shortly, or" + if computer_inference + else 'Open the computer with open(Target(platform="mac", ' + "inference=True)) to use its model, or" + ) + + " set inference=False on the Target you pass to computer.open() to run " + "this session's steps on Revyl's hosted model.", + reason=error.reason, + http_status=response.status, + ) if profile_refusal is not None: refused = True if error.reason == "repository_unavailable" and attempt < len( @@ -1234,9 +1263,15 @@ def validation( ) return result + def extract(self, text: str, *, timeout: float | None = None) -> StepResult: + """Reads a value off the screen, such as "the order number", and returns the step with it + in value. Raises STEP_FAILED when Revyl could not read it. Runs on Revyl's agent, so a + session opened with your own model raises INVALID_ARGUMENT.""" + return self._step("extract", text, timeout, None, None) + def _step( self, - kind: Literal["instruction", "validation"], + kind: Literal["instruction", "validation", "extract"], text: str, timeout: float | None, model: ModelOption | None, @@ -1247,20 +1282,28 @@ def _step( "INVALID_ARGUMENT", "Step description must contain 1–4000 characters." ) local = choose_agent(model, agent, f"{kind}()") or self._agent + if kind == "extract" and local is not None: + raise VerifyError( + "INVALID_ARGUMENT", + "extract() runs on Revyl's agent, and this session runs steps on your model " + "because open() was passed model or agent. Read the value from screenshot() with " + "your model, or open a session without model or agent to use extract().", + ) duration = seconds( self._step_timeout if timeout is None else timeout, 1, 3600, "Step timeout" ) with self._lock: if self._step_running: raise VerifyError( - "INVALID_ARGUMENT", "Run one instruction or validation at a time on a session." + "INVALID_ARGUMENT", + "Run one instruction, validation or extract at a time on a session.", ) self._step_running = True deadline = Deadline(duration, self._cancellation) started = time.monotonic() step_id: str | None = None try: - if local is not None: + if local is not None and kind != "extract": passed, explanation, run = self._run_local( kind, text.strip(), duration, local, deadline ) @@ -1352,6 +1395,32 @@ def _step( "STEP_FAILED", "Validation did not reach a verdict. See " + self.viewer_url ) reason = output.get("status_reason") or output.get("reasoning") + extracted = output.get("extracted_data") + value = None if extracted is None else obj(extracted).get("information") + if kind == "extract" and ( + not success or output.get("status") == "failed" or not isinstance(value, str) + ): + why = ( + "Revyl returned no value." + if success and output.get("status") != "failed" + else (reason.strip() if isinstance(reason, str) else "") + or "Revyl gave no reason." + ) + if why[-1] not in ".!?": + why += "." + raise VerifyError( + "STEP_FAILED", + f'Extract read nothing: "{text.strip()}". {why} Describe one value that is on ' + 'the screen now, such as "the order number on the confirmation". See ' + + self.viewer_url, + ) + engine: Literal["local", "hosted"] | None = ( + "local" + if output.get("engine") == "local" + else "hosted" + if output.get("engine") == "hosted" + else None + ) result = StepResult( kind, text.strip(), @@ -1360,9 +1429,16 @@ def _step( else success and output.get("status") != "failed", reason if isinstance(reason, str) else None, time.monotonic() - started, + value=value if kind == "extract" and isinstance(value, str) else None, + engine=engine, ) self.steps.append(result) - self._log(f"{'✓' if result.passed else '✗'} {kind} ({result.duration_seconds:.1f}s)") + self._log( + f"{'✓' if result.passed else '✗'} {kind} ({result.duration_seconds:.1f}s" + + (f", {engine} model" if engine else "") + + ")" + + (f": {result.value}" if result.value is not None else "") + ) return result except VerifyError as error: self._log(f"✗ {kind}: {error.code}") diff --git a/python/src/revyl_verify/_transport.py b/python/src/revyl_verify/_transport.py index 1a30294..b721852 100644 --- a/python/src/revyl_verify/_transport.py +++ b/python/src/revyl_verify/_transport.py @@ -49,6 +49,7 @@ "persistent_computers_not_enabled", "request_timeout", "protocol_error", + "computer_local_inference_unavailable", ] RefusalReason = Literal[ _ResponseRefusalReason, @@ -62,6 +63,9 @@ "lifetime_unsupported", "upgrade_required", "no_focused_input", + "inference_not_enabled", + "inference_unavailable", + "step_engine_unavailable", ] SessionProfileOutcome = Literal[ "succeeded", @@ -629,7 +633,7 @@ def _once( headers = { "Authorization": f"Bearer {self._token}", "Accept": "application/json", - "User-Agent": "revyl-verify/0.5.1 python", + "User-Agent": "revyl-verify/0.6.0 python", "X-Revyl-Client": "verify", } if worker: diff --git a/python/tests/test_computer.py b/python/tests/test_computer.py index deb45a7..a311a17 100644 --- a/python/tests/test_computer.py +++ b/python/tests/test_computer.py @@ -233,7 +233,7 @@ def test_platforms_and_all_operations(self) -> None: self.assertTrue(session.closed) self.assert_code("SESSION_ENDED", lambda: session.exec(["true"])) self.assert_code("NOT_AVAILABLE_ON_PLATFORM", lambda: session.instruction("click")) - self.assert_code("NOT_AVAILABLE_ON_PLATFORM", lambda: session.validation("exists")) + self.assert_code("SESSION_ENDED", lambda: session.validation("exists")) self.assertEqual(session.report()["state"], "stopped") recording = session.recording() self.assertIsNotNone(recording) diff --git a/python/tests/test_release.py b/python/tests/test_release.py index aa32d73..1335b6a 100644 --- a/python/tests/test_release.py +++ b/python/tests/test_release.py @@ -31,7 +31,7 @@ def __init__(self, content: bytes | Exception) -> None: self.content = content def open(self, request: Request, *, timeout: int) -> Response: - assert request.full_url == "https://pypi.org/pypi/revyl-verify/0.5.1/json" + assert request.full_url == "https://pypi.org/pypi/revyl-verify/0.6.0/json" assert timeout == 30 if isinstance(self.content, Exception): raise self.content @@ -65,19 +65,19 @@ def test_registry_only_skips_exact_published_distribution(monkeypatch: pytest.Mo module, json.dumps( { - "info": {"name": "revyl-verify", "version": "0.5.1"}, + "info": {"name": "revyl-verify", "version": "0.6.0"}, "urls": [ { - "filename": "revyl_verify-0.5.1-py3-none-any.whl", + "filename": "revyl_verify-0.6.0-py3-none-any.whl", "digests": {"sha256": "a" * 64}, } ], } ).encode(), ) - assert module.published_version_exists("revyl-verify", "0.5.1") is True + assert module.published_version_exists("revyl-verify", "0.6.0") is True patch_registry(monkeypatch, module, HTTPError("", 404, "missing", Message(), None)) - assert module.published_version_exists("revyl-verify", "0.5.1") is False + assert module.published_version_exists("revyl-verify", "0.6.0") is False @pytest.mark.parametrize("status", [301, 302, 401, 403, 429, 500, 503]) @@ -85,7 +85,7 @@ def test_registry_http_errors_fail_closed(monkeypatch: pytest.MonkeyPatch, statu module = release_module() patch_registry(monkeypatch, module, HTTPError("", status, "failure", Message(), None)) with pytest.raises(RuntimeError, match=f"HTTP {status}"): - module.published_version_exists("revyl-verify", "0.5.1") + module.published_version_exists("revyl-verify", "0.6.0") @pytest.mark.parametrize( @@ -94,11 +94,11 @@ def test_registry_http_errors_fail_closed(monkeypatch: pytest.MonkeyPatch, statu b"not json", b"[]", b"{}", - b'{"info":{"name":"other","version":"0.5.1"},"urls":[{}]}', + b'{"info":{"name":"other","version":"0.6.0"},"urls":[{}]}', b'{"info":{"name":"revyl-verify","version":"0.0.1"},"urls":[{}]}', - b'{"info":{"name":"revyl-verify","version":"0.5.1"},"urls":[]}', - b'{"info":{"name":"revyl-verify","version":"0.5.1"},"urls":[{}]}', - b'{"info":{"name":"revyl-verify","version":"0.5.1"},"urls":["invalid"]}', + b'{"info":{"name":"revyl-verify","version":"0.6.0"},"urls":[]}', + b'{"info":{"name":"revyl-verify","version":"0.6.0"},"urls":[{}]}', + b'{"info":{"name":"revyl-verify","version":"0.6.0"},"urls":["invalid"]}', ], ) def test_registry_malformed_metadata_fails_closed( @@ -107,14 +107,14 @@ def test_registry_malformed_metadata_fails_closed( module = release_module() patch_registry(monkeypatch, module, content) with pytest.raises(ValueError): - module.published_version_exists("revyl-verify", "0.5.1") + module.published_version_exists("revyl-verify", "0.6.0") def test_registry_transport_errors_fail_closed(monkeypatch: pytest.MonkeyPatch) -> None: module = release_module() patch_registry(monkeypatch, module, URLError("network unavailable")) with pytest.raises(URLError): - module.published_version_exists("revyl-verify", "0.5.1") + module.published_version_exists("revyl-verify", "0.6.0") @pytest.mark.parametrize("enabled", [None, "", "false", "TRUE", "1"]) diff --git a/python/tests/wheel_smoke.py b/python/tests/wheel_smoke.py index 550d1bd..b196d32 100644 --- a/python/tests/wheel_smoke.py +++ b/python/tests/wheel_smoke.py @@ -125,7 +125,7 @@ def respond(self) -> None: try: import revyl_verify - assert revyl_verify.__version__ == "0.5.1" + assert revyl_verify.__version__ == "0.6.0" assert callable(revyl_verify.attach) and callable(revyl_verify.async_attach) assert callable(revyl_verify.ComputerSession.open) assert callable(revyl_verify.Session.navigate) diff --git a/python/uv.lock b/python/uv.lock index 6be9e09..330960f 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -1311,7 +1311,7 @@ wheels = [ [[package]] name = "revyl-verify" -version = "0.5.1" +version = "0.6.0" source = { editable = "." } dependencies = [ { name = "pillow", version = "12.3.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, diff --git a/scripts/check-package.mjs b/scripts/check-package.mjs index b8c57df..36a46f0 100644 --- a/scripts/check-package.mjs +++ b/scripts/check-package.mjs @@ -93,7 +93,7 @@ try { } const files = new Set(pack.files.map((file) => file.path)); const missing = required.filter((path) => !files.has(path)); -const unexpected = [...files].filter((path) => !required.includes(path) && !/^dist\/[a-z0-9/-]+\.(js|d\.ts)$/.test(path) && !/^docs\/[a-z-]+\.(md|txt)$/.test(path)); +const unexpected = [...files].filter((path) => !required.includes(path) && !/^dist\/[a-z0-9/-]+\.(js|d\.ts)$/.test(path) && !/^docs\/(guides\/)?[a-z-]+\.(md|txt)$/.test(path)); if (missing.length > 0 || unexpected.length > 0) { console.error(`Missing from the package: ${missing.join(', ') || 'none'}`); console.error(`Should not be in the package: ${unexpected.join(', ') || 'none'}`);