Files
e2e/docs/reference/agent.mdx
T

307 lines
12 KiB
Plaintext

---
title: agent
description: Planned flows, judgments, extraction, and their budgets.
---
Every `agent` call starts from a fresh observation, has its own deadline and
model-call budget, and shares no transcript with earlier calls. Acquiring the
fixture without a configured model fails with `MODEL_UNAVAILABLE`.
```ts
export interface Agent {
/** Plans and executes a bounded multi-action flow; resolves with what the step did. */
act(instruction: string, options?: ActOptions): Promise<ActResult>;
/** Polls a natural-language condition until true or timed out. */
waitFor(condition: string, options?: WaitForOptions): Promise<void>;
/** Extracts and validates structured screen data. */
extract<Schema extends StandardSchemaV1>(
instruction: string,
options: ExtractOptions<Schema>,
): Promise<StandardSchemaV1.InferOutput<Schema>>;
/** Judges a natural-language assertion against a fresh observation. */
assert(assertion: string, options?: AssertOptions): Promise<void>;
}
```
## Budgets
Model calls count every model request including repair rounds. Action steps
count committed engine actions. Every timeout is additionally capped by the
remaining test timeout.
| Method | Model calls | Action steps | Default timeout |
| --- | ---: | ---: | --- |
| `act` | `agents.<name>.maxModelCalls`, 25 | `agents.<name>.maxSteps`, 25 | `config.timeout`, 120000 ms |
| `waitFor` | `agents.<name>.maxModelCalls`, 25 | 0 | the judgment budget |
| `extract` | 2 | 0 | the judgment budget |
| `assert` | 2 | 0 | the judgment budget |
The judgment budget is `max(30000, config.actionTimeout)` milliseconds.
Per-call budgets must be positive integers and can only lower the configured
limits. Every duration option is milliseconds.
The `assert` row holds for the built-in agent. When the selected agent has a
custom `executor`, `assert` is dispatched to it as a step: its budget is the
agent's `maxSteps` and `maxModelCalls`, its default timeout is
`config.timeout`, and `vision` or `screenshot` on the call is
`UNSUPPORTED_CAPABILITY`.
## agent.act
```ts
act(instruction: string, options?: ActOptions): Promise<ActResult>;
```
Plans and executes one bounded multi-action flow. A passing verdict resolves
with an `ActResult`; a failing or blocked one throws an `AgentError` whose
`code` and `blocked` flag say why.
`instruction` is 1 through 8192 UTF-8 bytes after NFC normalization. An
unknown `agent` name is `INVALID_ARGUMENT` before the step opens.
Values come from your code through `options.params`, never from the model. The
model sees a `Secret` as its name and purpose only. The runner fills the value
under the same rules as `locator.fill`: the field must be an enabled editable
input, and a password goes only into a password field.
```ts
await agent.act('invite {email} as an editor', { params: { email: 'ada@example.test' } });
const member = credentials.user('member');
const { summary, cache } = await agent.act('Sign in', {
params: { username: member.username, password: member.password },
});
```
The result carries the step's `summary`, the `modelCalls` and `actions` it
spent, and `cache`: how the [trace cache](/cache) took part
(`self-finalized`, `agent-concluded`, or `missed` with a `reason`; absent when
caching is off).
### Pixel tools: screenshot and tap_at
`act` takes no `vision` option. The built-in agent offers two tools instead,
while no secret has been filled. The act model receives the image itself; no
second model is involved.
| Tool | What it does |
| --- | --- |
| `screenshot()` | Attaches a masked viewport screenshot to the tool result. From then on the step is in pixel mode: every action result carries a fresh screenshot. |
| `tap_at({ x, y })` | Taps a point in the latest screenshot's pixel coordinates. The runner hit-tests the point against the tree. A listed control under it is tapped by id, exactly like `tap`. A point on nothing listed goes to the engine's `tapAt` as a bare point. |
In pixel mode the wait after an action watches the pixels too, so a redraw on
a canvas counts as a change. A screen that lists nothing to act on by id (a
canvas, a game) opens with a screenshot already attached. Screenshots are
resampled to a long side of 768 px, and older ones are dropped from the
conversation in batches, keeping the newest two.
A secret filled during the step keeps both tools listed but withholds every
later screenshot (`PIXEL_TAINTED`). `tap_at` needs an engine with `perform`
or `tapAt`; without `tapAt` the point must land on a listed control. A
bare-point tap replays from the [trace cache](/cache) only on a viewport of
the recorded size, or at the same place inside the listed node that contained
it. A step that sent pixels records `visionInput: true` and
`metrics.pixelBytes`.
Models differ widely at grounding a point in an image. Pin an act model that
does it well when your flows leave the tree.
Throws `ACTION_FAILED` for a failed verdict with no more specific code; a
blocked code (`AUTH_CREDENTIAL_UNAVAILABLE`, `ENVIRONMENT_UNAVAILABLE`,
`SEED_DATA_MISSING`, `TEST_SETUP_FAILED`, `AUTOMATION_UNSUPPORTED`) when the
step could not reach a product verdict; `STEP_BUDGET_EXHAUSTED` and
`STEP_TIMEOUT` when a budget or the deadline ran out; `INVALID_ARGUMENT` for
a malformed instruction, oversized `params`, or an unknown option; and
`UNSUPPORTED_CAPABILITY` for `schema` or `vision`, which `act` does not take.
## agent.assert
```ts
assert(assertion: string, options?: AssertOptions): Promise<void>;
```
One fresh observation, exactly one judgment. It does not poll. The judge is
shown the assertion and that observation only, never the prior steps or the
act loop's summaries, and answers `holds`, `fails`, or `inconclusive`.
Throws `ASSERTION_FAILED` on a false judgment and `ASSERTION_INCONCLUSIVE`
when the screen did not show enough to decide. Both carry the explanation
and, when permitted, a screenshot path. No evidence is captured with
`screenshot: false` or once a secret has been filled in the attempt.
`screenshot` controls failure evidence attached after the judgment; `vision`
controls what the model is shown before it.
```ts
await agent.assert('the dashboard shows a trial badge');
```
## agent.waitFor
```ts
waitFor(condition: string, options?: WaitForOptions): Promise<void>;
```
One observation per interval, and a judgment when the screen changed.
Succeeds on the first judgment that holds; a false or inconclusive round
keeps waiting.
Throws `STEP_TIMEOUT` on deadline expiry and `STEP_BUDGET_EXHAUSTED` on
budget exhaustion, each carrying the last judgment, and `INVALID_ARGUMENT`
for an out-of-range option or one `waitFor` does not take.
```ts
await agent.waitFor('the upload progress reports completion', { interval: 500 });
```
## agent.extract
```ts
extract<Schema extends StandardSchemaV1>(
instruction: string,
options: ExtractOptions<Schema>,
): Promise<StandardSchemaV1.InferOutput<Schema>>;
```
Takes one fresh observation, requests structured output, validates it, and
returns the validated value. It performs no app actions.
The budget is two model calls: one extraction and one repair round for
output that failed validation. Throws `INVALID_ARGUMENT` for a schema that is
not Standard Schema v1, and `MODEL_OUTPUT_INVALID` when validation still
fails after the repair.
```ts
const summary = await agent.extract('the workspace name and plan', {
schema: z.object({ name: z.string(), plan: z.string() }),
});
```
## Vision
`assert`, `waitFor`, and `extract` accept `vision`. Sending pixels needs a
model that accepts images. `act` has no such option; see the pixel tools
above.
Set `vision` on the agent in config to make a mode the project default; a
per-call value wins. Pixels go to the agent's `model`.
The screenshot is the viewport, never the full page, so `'only'` cannot see
below the fold. Write `'only'` conditions about what is on screen and let the
flow scroll first.
Pixels are withheld and the tree sent alone when a secret fill has tainted
the viewport (`visionDegraded: "PIXEL_TAINTED"` on the step), when the engine
masked fewer regions than the secure fields it observed (`MASKING_UNPROVEN`),
or when the engine cannot capture pixels (`UNSUPPORTED_CAPABILITY`). In
`'only'` mode those cases fail with `POLICY_DENIED` instead.
## Types
```ts
/**
* One `act` call: the values the instruction refers to and the step's
* budgets. Structured output and vision are judgment-tier options:
* `extract` takes `schema`; `assert`, `waitFor`, and `extract` take `vision`.
*/
export interface ActOptions extends AgentOption {
/**
* JSON-safe values the instruction refers to, at most 64 KiB and 32 levels
* deep. A `Secret` reaches the model by name only; the runner fills it.
*/
params?: AgentParams;
/** Step deadline in milliseconds; defaults to the test timeout. */
timeout?: number;
/** Action budget; defaults to `agent.maxSteps` and can only lower it. */
maxSteps?: number;
/** Model-call budget; defaults to `agent.maxModelCalls` and can only lower it. */
maxModelCalls?: number;
}
/** The configured agent (`agents.<name>`) one call runs with, in place of the test's. */
export interface AgentOption {
agent?: string;
}
/** `assert` options: one judgment plus one repair round, within `timeout`. */
export interface AssertOptions extends VisionOption, AgentOption {
/** Deadline in milliseconds; defaults to the judgment budget, `max(30000, actionTimeout)`. */
timeout?: number;
/** Attach a redacted screenshot to the step; on by default, denied after a secret fill. */
screenshot?: boolean;
}
/** `waitFor` options: a judgment at most once per `interval` until `timeout`. */
export interface WaitForOptions extends VisionOption, AgentOption {
/** Deadline in milliseconds; defaults to the judgment budget, `max(30000, actionTimeout)`. */
timeout?: number;
/** Least time between two judgments, in milliseconds; 100 through 60000, default 3000. */
interval?: number;
/** Judgment budget; defaults to `agent.maxModelCalls` and can only lower it. */
maxModelCalls?: number;
}
/** `extract` options: one extraction plus one repair round, validated against `schema`. */
export interface ExtractOptions<Schema extends StandardSchemaV1> extends VisionOption, AgentOption {
/** Any Standard Schema v1 validator; the output is validated against it, with one repair round. */
schema: Schema;
/** Deadline in milliseconds; defaults to the judgment budget, `max(30000, actionTimeout)`. */
timeout?: number;
}
export interface VisionOption {
/** What the judge is shown; defaults to the agent's `vision`, `false`. */
vision?: VisionMode;
}
/**
* What evidence the model is given: the semantic tree, a masked screenshot of
* the current observation, or both.
*
* - `false`: the tree.
* - `true`: the tree and a screenshot, on every call.
* - `'only'`: the screenshot, and not the tree.
*
* `'only'` exists because a tree sent alongside pixels is a cheaper path to an
* answer, and a model will take it: asked whether a form is covered by an
* overlay, it can read from the tree that the form is present and named and
* answer yes, while the pixels show the overlay. For a judgment that is about
* what the screen presents, the tree is a distractor, so the mode that means it
* removes it. It also costs fewer input tokens than `true`, not more.
*
* In every mode that sends pixels but also the tree, pixel evidence degrades
* away rather than failing the call when it cannot be proven redacted. `'only'`
* has nothing to degrade to, so it fails with `POLICY_DENIED` instead of
* answering the wrong question from the tree.
*/
export type VisionMode = boolean | 'only';
/** What one passing `act` step did, as the report records it. */
export interface ActResult {
/** The executor's one-line account of the step, or the replay's when the cache finished it. */
readonly summary: string;
/** How the trace cache took part; absent when caching is off for the step. */
readonly cache?: StepCacheInfo;
/** Model calls the step spent; 0 when a cached replay finished it. */
readonly modelCalls: number;
/** Grammar actions and mutating tool calls the step performed. */
readonly actions: number;
}
/** Values an `act` instruction refers to. */
export type AgentParams = Readonly<Record<string, AgentParam>>;
/** A JSON-safe value or a `Secret`. */
export type AgentParam =
| JsonPrimitive
| Secret
| readonly AgentParam[]
| { readonly [key: string]: AgentParam };
```
## AgentError
Every failure is an `AgentError` with a closed `code`, an `explanation`, an
optional `screenshot` path, and a `blocked` flag. Check it with
`isAgentError(error)` from `e2e`, not `instanceof`. The class and
every code are in [Errors](/reference/errors#agenterror).