Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/judgment-params.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
"e2e": patch
---

`agent.assert` and `agent.waitFor` take `params`, like `agent.act`. The judge reads `{name}` with its value, a `unique()` value included. A `Secret` reaches the judge by name only, so check a secret's value on screen with a locator assertion.

```ts
const name = unique(`acme-${Date.now()}`);
await agent.act('create a company named {name}', { params: { name } });
await agent.assert('the table shows company {name}', { params: { name } });
```
4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -533,8 +533,8 @@ trees, on both platforms, without a device.
- No implicit default model. For the built-in agent, the entry's `model`
serves `act`; the judgment calls (`assert`, `waitFor`, `extract`) use its
`judge` when one is configured, else `model`. A judgment never sees the
prior-step ledger or the acting agent's summaries, only the instruction and
the current screen. Without a model, the first `agent` acquisition in a run
prior-step ledger or the acting agent's summaries; it sees the instruction, its
params, the agent's context, and the current screen. Without a model, the first `agent` acquisition in a run
reports one run-level `MODEL_UNAVAILABLE` and stops the run (exit 2). A
custom executor handles `act` and `assert` through `runStep` and needs no
model; its `waitFor` and `extract` still use the built-in judgments. No implicit target either: `targets` is required and
Expand Down
24 changes: 21 additions & 3 deletions docs/reference/agent.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -140,10 +140,11 @@ Checks one fresh observation without polling.

```ts
await agent.assert('the dashboard shows a trial badge');
await agent.assert('the table lists {name}', { params: { name } });
```

- The judge sees the assertion, the current observation, and the agent's
`context`, never prior steps or `act` summaries. It answers `holds`,
- The judge sees the assertion, its `params`, the current observation, and
the agent's `context`, never prior steps or `act` summaries. It answers `holds`,
`fails`, or `inconclusive`.
- When the subject appears more than once, such as a total in a summary and
on a pay button, every instance must agree: one that contradicts it fails.
Expand All @@ -153,6 +154,7 @@ await agent.assert('the dashboard shows a trial badge');

| Option | Type | Default |
| --- | --- | --- |
| `params` | `AgentParams` | none |
| `timeout` | `number` | `agents.<name>.judgmentTimeout`, 30000 |
| `screenshot` | `boolean` | `true` |
| `vision` | [`VisionMode`](#vision) | `false` |
Expand All @@ -163,6 +165,10 @@ failing.
`vision` controls what the model is shown before it. No evidence is captured
with `screenshot: false`.

`params` follow the [`agent.act`](#agent-act) rules, and invalid ones throw
`INVALID_ARGUMENT`. A `Secret` param reaches the judge as its name, never its
value. To check that a secret's value is on screen, use a locator assertion.

| Throws | When |
| --- | --- |
| `ASSERTION_FAILED` | The judgment is false. |
Expand Down Expand Up @@ -207,19 +213,21 @@ await agent.waitFor('the upload progress reports completion', { interval: 500 })

| Option | Type | Default |
| --- | --- | --- |
| `params` | `AgentParams` | none |
| `timeout` | `number` | `agents.<name>.judgmentTimeout`, 30000 |
| `interval` | `number` | 3000 |
| `maxModelCalls` | `number` | `agents.<name>.maxModelCalls`, 25 |
| `vision` | [`VisionMode`](#vision) | `false` |
| `agent` | `string` | the test's agent |

`interval` is the least time between two judgments, 100 through 60000 ms.
`params` work as in [`agent.assert`](#agent-assert).

| Throws | When |
| --- | --- |
| `STEP_TIMEOUT` | The deadline expired. |
| `STEP_BUDGET_EXHAUSTED` | The budget ran out. |
| `INVALID_ARGUMENT` | An out-of-range option, or one `waitFor` does not take. |
| `INVALID_ARGUMENT` | An out-of-range option, invalid `params`, or an option `waitFor` does not take. |

`STEP_TIMEOUT` and `STEP_BUDGET_EXHAUSTED` carry the last judgment. When that
round was inconclusive, they add the same vision hint as `agent.assert`.
Expand Down Expand Up @@ -520,6 +528,11 @@ export interface AgentOption {

/** `assert` options: one judgment plus one repair round, within `timeout`. */
export interface AssertOptions extends VisionOption, AgentOption {
/**
* Values the assertion refers to as `{name}`, with the same rules as `act`
* params. A `Secret` reaches the judge by name only, never its value.
*/
params?: AgentParams;
/** Deadline in milliseconds; defaults to the agent's `judgmentTimeout`, 30000. */
timeout?: number;
/** Attach a redacted screenshot to the step; on by default. */
Expand All @@ -528,6 +541,11 @@ export interface AssertOptions extends VisionOption, AgentOption {

/** `waitFor` options: a judgment at most once per `interval` until `timeout`. */
export interface WaitForOptions extends VisionOption, AgentOption {
/**
* Values the condition refers to as `{name}`, with the same rules as `act`
* params. A `Secret` reaches the judge by name only, never its value.
*/
params?: AgentParams;
/** Deadline in milliseconds; defaults to the agent's `judgmentTimeout`, 30000. */
timeout?: number;
/** Least time between two judgments, in milliseconds; 100 through 60000, default 3000. */
Expand Down
33 changes: 18 additions & 15 deletions packages/e2e/src/agent/act-validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,26 +99,26 @@ export function validateActOptions(options: ActOptions | undefined, extraArgumen
* JSON Pointer for the trace cache to template. The JSON round-trip is
* deliberate: it bounds the canonical size (spec 02) and freezes what the
* executor sees, so a getter or proxy cannot change values — or run code —
* during later serialization.
* during later serialization. `api` names the call in error messages.
*/
export function validateParams(params: AgentParams | undefined): {
export function validateParams(params: AgentParams | undefined, api: string): {
projected: Readonly<Record<string, JsonValue>> | undefined;
secrets: ReadonlyMap<string, Secret>;
templates: readonly ParamTemplate[];
} {
if (params === undefined) return { projected: undefined, secrets: new Map(), templates: [] };
if (typeof params !== 'object' || params === null || Array.isArray(params)) {
throw new TestError('INVALID_ARGUMENT', 'agent.act params must be a plain object');
throw new TestError('INVALID_ARGUMENT', `${api} params must be a plain object`);
}
const found: FoundParams = { secrets: new Map(), templates: [] };
const projectedRaw = projectParams(params, '', found, new Set());
validateJsonValue(projectedRaw, 'agent.act params', { maxDepth: MAX_PARAMS_DEPTH });
const projectedRaw = projectParams(params, '', found, new Set(), api);
validateJsonValue(projectedRaw, `${api} params`, { maxDepth: MAX_PARAMS_DEPTH });
const canonical = JSON.stringify(projectedRaw);
const bytes = new TextEncoder().encode(canonical).byteLength;
if (bytes > MAX_PARAMS_BYTES) {
throw new TestError(
'INVALID_ARGUMENT',
`agent.act params are ${bytes} canonical bytes; the maximum is ${MAX_PARAMS_BYTES}`,
`${api} params are ${bytes} canonical bytes; the maximum is ${MAX_PARAMS_BYTES}`,
);
}
return {
Expand All @@ -133,15 +133,17 @@ export function validateParams(params: AgentParams | undefined): {
* Projected params with `redact` applied to every string in them, object
* keys included, and their `unique()` templates moved with their leaves: a
* template's pointer follows the redacted keys and its value is redacted as
* the leaf is, so the trace cache slots what the params hold.
* the leaf is, so the trace cache slots what the params hold. `api` names
* the call in error messages.
*/
export function redactParams(
params: Readonly<Record<string, JsonValue>>,
templates: readonly ParamTemplate[],
redact: (text: string) => string,
api: string,
): { params: Readonly<Record<string, JsonValue>>; templates: readonly ParamTemplate[] } {
const pointers = new Map<string, string>();
const redacted = redactJson(params, redact, { from: '', to: '' }, pointers) as Readonly<Record<string, JsonValue>>;
const redacted = redactJson(params, redact, { from: '', to: '' }, pointers, api) as Readonly<Record<string, JsonValue>>;
return {
params: redacted,
templates: templates.map((template) => ({
Expand All @@ -162,12 +164,13 @@ function redactJson(
redact: (text: string) => string,
at: { readonly from: string; readonly to: string },
pointers: Map<string, string>,
api: string,
): JsonValue {
pointers.set(at.from, at.to);
if (typeof value === 'string') return redact(value);
if (Array.isArray(value)) {
return value.map((entry, index) =>
redactJson(entry, redact, { from: paramPointer(at.from, index), to: paramPointer(at.to, index) }, pointers),
redactJson(entry, redact, { from: paramPointer(at.from, index), to: paramPointer(at.to, index) }, pointers, api),
);
}
if (typeof value !== 'object' || value === null) return value;
Expand All @@ -177,12 +180,12 @@ function redactJson(
if (Object.hasOwn(out, clean)) {
throw new TestError(
'INVALID_ARGUMENT',
`agent.act params has two keys that read ${JSON.stringify(clean)} once secret values are redacted; a key cannot be told apart by a secret`,
`${api} params has two keys that read ${JSON.stringify(clean)} once secret values are redacted; a key cannot be told apart by a secret`,
);
}
// Defined, not assigned, so a `__proto__` key stays an own property.
Object.defineProperty(out, clean, {
value: redactJson(entry, redact, { from: paramPointer(at.from, key), to: paramPointer(at.to, clean) }, pointers),
value: redactJson(entry, redact, { from: paramPointer(at.from, key), to: paramPointer(at.to, clean) }, pointers, api),
enumerable: true,
writable: true,
configurable: true,
Expand All @@ -198,7 +201,7 @@ interface FoundParams {
}

/** Replaces every Secret leaf with its placeholder and every Unique leaf with its value, collecting both. */
function projectParams(value: unknown, pointer: string, found: FoundParams, seen: Set<unknown>): unknown {
function projectParams(value: unknown, pointer: string, found: FoundParams, seen: Set<unknown>, api: string): unknown {
if (isSecret(value)) {
found.secrets.set(value.name, value);
return { kind: 'secret', name: value.name, purpose: value.purpose };
Expand All @@ -209,14 +212,14 @@ function projectParams(value: unknown, pointer: string, found: FoundParams, seen
}
if (typeof value !== 'object' || value === null) return value;
if (seen.has(value)) {
throw new TestError('INVALID_ARGUMENT', 'agent.act params contains a cycle');
throw new TestError('INVALID_ARGUMENT', `${api} params contains a cycle`);
}
seen.add(value);
if (Array.isArray(value)) {
return value.map((entry, index) => projectParams(entry, paramPointer(pointer, index), found, seen));
return value.map((entry, index) => projectParams(entry, paramPointer(pointer, index), found, seen, api));
}
return Object.fromEntries(
Object.entries(value).map(([key, entry]) => [key, projectParams(entry, paramPointer(pointer, key), found, seen)]),
Object.entries(value).map(([key, entry]) => [key, projectParams(entry, paramPointer(pointer, key), found, seen, api)]),
);
}

Expand Down
14 changes: 8 additions & 6 deletions packages/e2e/src/agent/act.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import { join } from 'node:path';
import { resolveVision } from '../config/agent.ts';
import { ConfigurationError } from '../internal/errors.ts';
import { withAbort, withTimeout } from '../internal/time.ts';
import type { ActionHook, ActOptions, BeforeActionHook, ActResult, AgentErrorCode, JsonValue, ModelInstance, Secret, VisionMode } from '../types.ts';
import type { ActionHook, ActOptions, AssertOptions, BeforeActionHook, ActResult, AgentErrorCode, JsonValue, ModelInstance, Secret, VisionMode } from '../types.ts';
import { AgentError, CATEGORY_BY_CODE, toAgentError } from './error.ts';
import { redactParams, validateActOptions, validateInstruction, validateParams, validateVerdict } from './act-validation.ts';
import { ActionDispatcher } from './action-dispatcher.ts';
Expand Down Expand Up @@ -82,7 +82,7 @@ export async function runActStep(
): Promise<ActResult> {
const normalized = validateInstruction(instruction, 'agent.act');
validateActOptions(options, extraArguments);
const { projected, secrets, templates } = validateParams(options?.params);
const { projected, secrets, templates } = validateParams(options?.params, 'agent.act');
return dispatchAgentStep(runtime, {
api: 'agent.act',
kind: 'act',
Expand Down Expand Up @@ -112,9 +112,11 @@ export async function runActStep(
export async function runAssertStep(
runtime: AgentContext,
assertion: string,
options: { timeout?: number; vision?: VisionMode; screenshot?: boolean; agent?: string } | undefined,
options: AssertOptions | undefined,
): Promise<void> {
const normalized = validateInstruction(assertion, 'agent.assert');
// An assert changes no state, so its secrets are named to the executor but never fillable.
const { projected, templates } = validateParams(options?.params, 'agent.assert');
const agent = runtime.select(options?.agent);
const vision = resolveVision(options?.vision);
if (options?.vision !== undefined && agent.executor.vision !== true) {
Expand All @@ -127,9 +129,9 @@ export async function runAssertStep(
api: 'agent.assert',
kind: 'assert',
instruction: normalized,
params: undefined,
params: projected,
secrets: new Map(),
templates: [],
templates,
defaultFailureCode: 'ASSERTION_FAILED',
timeout: options?.timeout,
maxSteps: undefined,
Expand Down Expand Up @@ -195,7 +197,7 @@ export async function dispatchAgentStep(
function redactSpec(spec: DispatchSpec, redact: (text: string) => string): DispatchSpec {
const instruction = redact(spec.instruction);
if (spec.params === undefined) return { ...spec, instruction };
return { ...spec, instruction, ...redactParams(spec.params, spec.templates, redact) };
return { ...spec, instruction, ...redactParams(spec.params, spec.templates, redact, spec.api) };
}

/** One step's wiring: the collaborators, the executor's context, and the verdict mapping. */
Expand Down
29 changes: 24 additions & 5 deletions packages/e2e/src/agent/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ import { rejectUnknownOptions } from '../internal/options.ts';
import { describeIssue, requireStandardSchema } from '../internal/standard-schema.ts';
import { sleep } from '../internal/time.ts';
import type { StepRunOptions } from '../run/steps.ts';
import type { Agent, StandardSchemaV1, VisionMode } from '../types.ts';
import type { Agent, AgentParams, JsonValue, StandardSchemaV1, VisionMode } from '../types.ts';
import { redactParams, validateParams } from './act-validation.ts';
import { AgentError, isAgentError, toAgentError } from './error.ts';
import { isUnservedModelError, unservedModelError } from './model/sdk.ts';
import { resolveBoundedBudget, resolveTimeout } from './call-options.ts';
Expand Down Expand Up @@ -65,9 +66,9 @@ const VISION_HINT = 'the judge saw the semantic tree only; pass vision: true whe
const VISION_HINT_UNPROVEN =
'the judge saw the semantic tree only; if the engine captures pixels, pass vision: true when the answer is in pixels';

const WAIT_FOR_KEYS = ['timeout', 'interval', 'maxModelCalls', 'vision', 'agent'] as const;
const WAIT_FOR_KEYS = ['params', 'timeout', 'interval', 'maxModelCalls', 'vision', 'agent'] as const;
const EXTRACT_KEYS = ['schema', 'timeout', 'vision', 'agent'] as const;
const ASSERT_KEYS = ['timeout', 'screenshot', 'vision', 'agent'] as const;
const ASSERT_KEYS = ['params', 'timeout', 'screenshot', 'vision', 'agent'] as const;

/** Builds the agent fixture for one attempt. */
export function createAgentFixture(runtime: AgentContext): Agent {
Expand Down Expand Up @@ -125,8 +126,9 @@ export function createAgentFixture(runtime: AgentContext): Agent {

/**
* One judgment call against a fresh observation. The judge is shown the
* instruction and the screen, never the prior steps or the acting agent's
* summaries: a verdict rests on evidence, not on what the actor said it did.
* instruction, its params, the agent's context, and the screen, never the
* prior steps or the acting agent's summaries: a verdict rests on evidence,
* not on what the actor said it did.
*/
const askJudgment = (invocation: Invocation, instruction: string, observation: AgentObservation) =>
invocation.ask({
Expand All @@ -136,19 +138,34 @@ export function createAgentFixture(runtime: AgentContext): Agent {
prompt: { request: JUDGMENT_REQUEST, instruction, observation },
});

/**
* A judgment's params as the judge reads them: projected as `act` projects
* them, a `Secret` by name only and a `unique()` value as its string, then
* redacted per call, so a registered value spelled into a param never reaches the model.
*/
const judgmentParams = (
params: AgentParams | undefined,
api: string,
): Readonly<Record<string, JsonValue>> | undefined => {
const { projected, templates } = validateParams(params, api);
return projected === undefined ? undefined : redactParams(projected, templates, runtime.redact, api).params;
};

const agent: Agent = {
// The rest parameter exists only to catch the pre-0.8 three-argument call.
act: (instruction, options, ...legacy: readonly unknown[]) =>
runActStep(runtime, instruction, options, legacy.length),
waitFor(condition, options) {
rejectUnknownOptions('agent.waitFor', options, WAIT_FOR_KEYS);
const params = judgmentParams(options?.params, 'agent.waitFor');
const intervalMs = validateInterval(options?.interval);
const { config } = runtime.select(options?.agent);
const vision = resolveVision(options?.vision);
return step(
{
api: 'agent.waitFor',
agent: options?.agent,
params,
task: 'judge whether a condition holds',
timeoutMs: resolveTimeout(options?.timeout, config.judgmentTimeout),
maxModelCalls: resolveBoundedBudget(options?.maxModelCalls, config.maxModelCalls, 'maxModelCalls'),
Expand Down Expand Up @@ -249,11 +266,13 @@ export function createAgentFixture(runtime: AgentContext): Agent {
if (customExecutor) {
return runAssertStep(runtime, assertion, options);
}
const params = judgmentParams(options?.params, 'agent.assert');
const vision = resolveVision(options?.vision);
return step(
{
api: 'agent.assert',
agent: options?.agent,
params,
task: 'judge whether an assertion holds',
timeoutMs: resolveTimeout(options?.timeout, config.judgmentTimeout),
maxModelCalls: ASSERT_MODEL_CALLS,
Expand Down
2 changes: 1 addition & 1 deletion packages/e2e/src/agent/interactive-step.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export interface InteractiveStep {
* never resolved and the budgets a model loop needs do not apply.
*/
export async function openInteractiveStep(runtime: AgentContext, options: InteractiveStepOptions): Promise<InteractiveStep> {
const { projected, secrets, templates } = validateParams(options.params);
const { projected, secrets, templates } = validateParams(options.params, 'session');
const executor = new HostExecutor();
const config: ResolvedAgentConfig = { ...runtime.config.agent, maxSteps: UNBOUNDED, maxModelCalls: UNBOUNDED };
const agent: DispatchAgent = { name: executor.name, config, executor, agentContext: undefined };
Expand Down
Loading
Loading