Skip to content

Decision models

E2E.Decision runs ActAsync and AssertAsync through a decision model instead of an LLM agent. For each action, the decision model picks an operation, then an element, from the goal, the recent actions, and the newest semantic tree. It never writes free text: a small text model writes field values. The runner still authorizes every action. This ports upstream’s @e2e-dev/decision (decisionExecutor). The same package holds Filter.DecisionFilter, which runs only the tests a change can affect: see Test filters.

Any decision model that answers choice questions with probabilities works, such as TypeSafe Jev (DecisionTypeSafeAiModel), OpenAIDecisionModel with gpt-6-luna, or a Vercel AI Gateway model (GatewayDecisionProvider) such as typesafe-ai/jev. A model id string or a language model in Model fails the executor’s construction with INVALID_CONFIG.

dotnet add package E2E.Decision

Set the executor on the agent. An executor is code, so a config file cannot hold one:

using E2E;
using E2E.Decision;
using E2E.Decision.Sdk;
using E2E.NUnit;
public sealed class TodoTests : E2ETest
{
protected override IAgentModel? CreateModel() => /* the small text model */ null;
protected override IStepExecutor? AgentExecutor =>
Executor.DecisionExecutor(
new DecisionExecutorOptions
{
Model = new OpenAIDecisionModel("gpt-6-luna"),
// The text model. Without one, set the agent's Model instead.
TextModel = CreateModel(),
}
);
}

A deprecated evaluation model (IEvaluationModel) works too: set it as EvaluationModel instead of Model. Set one of the two.

Tests are plain ActAsync and AssertAsync calls. Set OPENAI_API_KEY for OpenAIDecisionModel.

Each turn offers the operations the engine supports on the elements of the newest screen: tap, type, typeSecret, submit, select, check, upload, hover, secondary_tap (a right-click), double_tap, long_press, drag, scroll_to, scroll_up, scroll_down, and back. Hover, right-click, drag, and scroll-to also reach labeled nodes that are not controls, such as a card that opens a menu on hover, and a drag can drop onto any of them. tap also reaches text fields, to open a date picker or a suggestion list. While an on-screen keyboard shows on an engine that can dismiss it, such as the mobile engine, the executor also offers dismiss_keyboard, even when the keyboard is missing from the tree.

Every operation that acts on an element asks for its target, even when only one element fits it. Every target question has a none option, so a provider with no fitting target answers none instead of refusing. none blocks the step.

When the decision model picks type, the text model writes the value from the goal, the params, the field’s label, and the page text. The executor types exactly that string. With no value in the goal, it types nothing and the decision model picks again. For upload, the text model lists the project-relative paths the goal or params name, and the runner authorizes each one. Model output never becomes a selector, a URL, or a key.

Password fields never reach the text model, unless a page script hides one from e2e. Then the text model sees its value, and type can fill it (where redaction stops). Only typeSecret fills a configured secret, from its declared handle.

The text model also answers WaitForAsync and ExtractAsync. Instead of TextModel, you can set Model on the agent entry. With neither, the executor never offers type, upload, tap_at, or type_at.

When the decision model answers done or failed, the executor checks the claim on a fresh screen with one question: is the step’s task complete? The check never sees model reasoning or a secret.

A confirmed done passes the step, and a confirmed failed fails it with ACTION_FAILED. An unconfirmed claim goes back to the decision model as history. A second one ends the step: ACTION_FAILED when the screen contradicts the goal, else blocked with AUTOMATION_UNSUPPORTED.

Both gates are off by default, so the executor follows the most probable choice. Set MinProbability or MinConfidence to block weaker actions, reject weaker completion checks, and fail weaker assertions as inconclusive:

var executor = Executor.DecisionExecutor(
new DecisionExecutorOptions { Model = model, MinProbability = 0.9, MinConfidence = 0.8 }
);

Probability is the chosen option’s share of the answer distribution. Confidence is the provider’s own statistic, 0 when it reports none. OpenAI rounds both to two decimals. Measure accuracy on your own tests before you set a threshold.

Vision = true adds a masked screenshot to every observation. Assertions and completion checks see it, so the model can judge drawn content the tree doesn’t show. The operation and target questions read the tree only. AssertAsync(..., new AssertOptions { Vision = VisionMode.On }) and VisionMode.Only also require Vision = true on the executor. Without it, the call fails with UNSUPPORTED_CAPABILITY.

The model must accept images and answer score questions. TypeSafe Jev does, with a TypeSafe API key in TYPESAFE_AI_API_KEY:

using E2E.Decision.Sdk.TypeSafeAi;
var model = new TypeSafeAiProvider().DecisionModel("jev-latest");

TYPESAFE_AI_BASE_URL routes the provider through a trusted proxy or a self-hosted TypeSafe-compatible server. The default base URL is https://api.typesafe.ai/v1. TypeSafeAiProviderSettings.BaseUrl takes precedence over the variable. The configured server receives the API key and the decision input. The provider sends requests through the TypeSafe .NET SDK, which adds /v1 to the root of the base URL, so give a base URL that ends in /v1; a base URL without it is requested with /v1 added.

OpenAIDecisionModel takes images too. Vercel AI Gateway rejects the screenshot for every decision model, so keep Vision off there.

TypeSafeAiProviderSettings.BaseUrl defaults to the TYPESAFE_AI_BASE_URL environment variable, then https://api.typesafe.ai/v1; TypeSafeAiProvider.TypeSafeAi is the provider that environment configures. TypeSafe has no language, embedding, or image models, so LanguageModel, EmbeddingModel, and ImageModel throw NoSuchModelException. TypeSafeAiModelCatalog lists the decision models (ModelCatalog, GetTypeSafeAiDecisionModelEntry) and their provider options (TypeSafeAiProviderOptions).

TypeSafe takes PNG and JPEG images. Each image gets a reference that the request puts in the state at the image’s position (or, when the state already contains the reference, leaves alone). Name your own in the part’s typesafe provider options, { "reference": "[photo]", "insertReference": false }, to point at the image from a question’s instructions or criteria. longContext: true in the call’s typesafe provider options raises the context limits to 262k tokens, at the cost of speed and accuracy.

With a text model, vision also offers tap_at for a control the tree doesn’t list. The text model names the control, such as “the 3 key on the keypad”, and the decision model finds it on the screenshot, then on two zoomed crops. A point tap costs four decide calls and one text call, or one of each to repeat a tap on the same page.

When the engine can type into whatever has focus, vision also offers type_at for a drawn field. The text model names the field and the value from the goal, the decision model finds the field on the screenshot, and the executor taps it and types the value at the caret, after any text already there. It costs two decide calls and one text call.

The executor’s ProviderOptions go with every decide call, completion checks included, and reach the decision model only. The text model takes the agent entry’s ProviderOptions, so a setting for one model never reaches the other. Each value maps a provider name to an option object, and any other shape fails the construction with INVALID_CONFIG. Use them for options such as zero data retention on Vercel AI Gateway:

using E2E.Decision.Sdk.Gateway;
var model = new GatewayDecisionProvider().DecisionModel("typesafe-ai/jev");
// ProviderOptions = { ["gateway"] = { "zeroDataRetention": true } }

GatewayDecisionProvider is the port’s way into the Vercel AI Gateway. The Gateway client is the Vercel.AI package’s Vercel.AI.Gateway.GatewayProvider, which the provider wraps: new GatewayDecisionProvider() makes a default one, and new GatewayDecisionProvider(GatewayProvider.Create(new GatewayOptions { ApiKey, BaseUrl, TeamIdOrSlug })) wraps your own, which stays reachable as Gateway. It reads AI_GATEWAY_API_KEY or, without it, the Vercel OIDC token. Like getVercelOidcToken in @vercel/oidc, it reads VERCEL_OIDC_TOKEN and, when that is missing or expired, refreshes the token with the file-backed credentials of the Vercel CLI (vercel login) for the project linked in .vercel/project.json. A host that serves Vercel requests supplies the request context with VercelRequestContext.Use(headers) (Vercel.AI.Gateway.VercelRequestContext): its x-vercel-oidc-token header is the OIDC token and its x-vercel-id header goes out as ai-o11y-request-id. AI Gateway can rerun an uncertain decision on another model. Add a conditional entry to gateway.models, and it reaches every decide call. A triggered fallback bills both models:

{ "gateway": { "models": [{ "model": "openai/gpt-6-luna-decisions", "when": { "confidenceBelow": 0.6 } }] } }

The entry must come first and there can be only one. A when is a confidenceBelow (0 to 1) or a probabilityBetween pair, optionally for one question, or an any, all, or atLeast group of up to 20 conditions, nested at most five levels. A bad entry fails the call with invalid gateway provider options before any request.

Everything else the Gateway offers is Vercel.AI’s, reached through GatewayDecisionProvider.Gateway: GetAvailableModelsAsync(), GetCreditsAsync(), GetSpendReportAsync(...), GetGenerationInfoAsync(...), ExperimentalBatch, and the realtime and language models. See the Vercel AI SDK for .NET for those.

A failed Gateway decision call throws a Vercel.AI.Gateway.GatewayError. Its subclasses name the failure (GatewayAuthenticationError, GatewayRateLimitError, GatewayModelNotFoundError, GatewayTimeoutError, and so on). StatusCode, GenerationId, and IsRetryable say what happened, and ExperimentalDecide.RunAsync retries a retryable one. A caller’s cancellation is never wrapped: it surfaces as the OperationCanceledException you raised.

Model ids, deprecated aliases, and provider factories

Section titled “Model ids, deprecated aliases, and provider factories”

DecideOptions takes the model one of three ways: Model (an IDecisionModel), EvaluationModel (a deprecated IEvaluationModel, the doEvaluate shape), or ModelId, a string that ResolveModel.AiSdkDefaultProvider resolves (the Vercel AI Gateway when none is set). Set exactly one, or the call fails with an invalid argument error. ExperimentalDecide.ExperimentalEvaluate is the deprecated alias of ExperimentalDecide.RunAsync.

A provider that makes decision models implements IDecisionProvider. DecisionModel(modelId) is preferred; the deprecated EvaluationModel(modelId) is used when the provider has no DecisionModel. new CustomProvider(new CustomProviderOptions { DecisionModels = ..., FallbackProvider = ... }) serves its own models and falls back to another provider; DecisionModels takes precedence over the deprecated EvaluationModels. ProviderRegistry.CreateProviderRegistry(providers, new ProviderRegistryOptions { Separator = "|" }) returns a registry whose DecisionModel("provider|model") and deprecated EvaluationModel("provider|model") resolve a combined id. An id with no separator fails with NoSuchModelException, and an unknown provider with NoSuchProviderException.

ExperimentalDecide.RunAsync (the AI SDK’s experimental_decide, in E2E.Decision.Sdk) reports its lifecycle two ways. DecideOptions.OnStart runs when the operation begins, before the decision model is called, and DecideOptions.OnEnd runs when it completes. Both take the whole event, with the call id, the provider and model ids, the state, the questions, MaxOutputTokens, Reasoning, MaxRetries, the headers, the provider options, and the RuntimeContext you passed. DecideEndEvent adds the answers, the usage, the warnings, the rounding, the provider metadata, and the response id, model id, headers, and body, and the timestamp. DecisionResult carries the same response id, model id, headers, and body, and the timestamp the model’s response reported (the time of the call when it reported none). A decision model sets DecisionModelResult.ResponseId and ResponseTimestamp. The warnings of a call go to LogWarnings.AiSdkLogWarnings (standard error by default). OnEnd and the model-call end event fire only after the call completes. If the call fails, including when its retries run out, the model-call start event has fired, neither end event fires, and each integration receives OnErrorAsync. A callback that throws does not fail the call, and a caller’s cancellation ends the wait for the callbacks.

var result = await ExperimentalDecide.RunAsync(new DecideOptions
{
Model = model,
State = [new DecisionTextPart("Refund request")],
Questions = questions,
RuntimeContext = new Dictionary<string, object?> { ["requestId"] = "req_abc" },
OnStart = e => { Console.WriteLine($"{e.CallId} {e.ModelId}"); return Task.CompletedTask; },
OnEnd = e => { Console.WriteLine($"{e.Usage.TotalTokens} tokens"); return Task.CompletedTask; },
});

DecideOptions.Telemetry takes TelemetryOptions with Integrations, a list of ITelemetry. An integration overrides the members it listens to: OnDecideStartAsync, OnDecisionModelCallStartAsync, OnDecisionModelCallEndAsync, OnDecideEndAsync, and OnErrorAsync. It also has the generic OnStartAsync and OnEndAsync, which upstream fires for its other operations; decide never calls them. The decision model call events cover the logical model call, so a retried call fires one start, and one end only if a retry succeeds. Every integration event carries the call’s RecordInputs, RecordOutputs, FunctionId, and AiVersion. A call that sets no Integrations uses the global ones added with TelemetryRegistry.RegisterTelemetry(params ITelemetry[]), in registration order; TelemetryOptions.Integrations replaces them, and IsEnabled = false ignores them.

The deprecated OnEvaluateStartAsync, OnEvaluationModelCallStartAsync, OnEvaluationModelCallEndAsync, and OnEvaluateEndAsync still receive the same events (experimental_onEvaluate* upstream). An integration that implements the current member gets the call there and not on the alias. The error that OnErrorAsync receives goes through the telemetry view of the error first: an exception that implements ITelemetryRedactable hands integrations the copy RedactForTelemetry() returns, and the call still throws the original. If the redactor throws, integrations receive a generic InvalidOperationException instead.

  • RecordInputs = false empties the state, the questions, and the provider options of the events an integration receives. RecordOutputs = false empties the answers. Either one also drops the provider metadata and replaces the error with a generic one.
  • RecordInputs = false does not remove Headers: integrations still receive them on the decide start and end events. Do not place credentials in Headers if an integration exports telemetry.
  • An integration receives no runtime context unless IncludeRuntimeContext marks a top-level key true. OnStart and OnEnd always get the whole context.
  • IsEnabled = false turns the integrations off for the call.
  • The call also runs inside the AI SDK’s tracing channel. DiagnosticsChannel.GetTracingChannel(TelemetryTracingChannel.AiSdkTelemetryTracingChannel) ("ai:telemetry", the stand-in for Node’s diagnostics_channel) takes a TracingChannelSubscribers, and its Start subscriber receives a TelemetryTracingChannelMessage of type TelemetryTracingEventType.ExperimentalDecide whose Event is the start event with AiVersion and the runtime context filtered by IncludeRuntimeContext. AsyncEnd receives the same message with Result set, or Error set when the call fails; RecordInputs = false empties the state, questions and provider options of the start event, IsEnabled = false publishes nothing, and RecordInputs = false or RecordOutputs = false hides the result and replaces the error with a generic one. With no subscribers the call runs as before. Start.BindStore runs a store for the length of the call.
  • The port has no global integration registry: a call with no Integrations has none.

A state part can be a file at a URL: new DecisionFileUrlPart("image/png", new Uri("https://example.com/package.png")). ExperimentalDecide.RunAsync downloads it before the decision model is called and hands the model a DecisionFilePart with the bytes. The downloaded media type replaces a partial one such as image, never a full one such as image/png.

The call never fetches a URL on its own. Without DecideOptions.ExperimentalDownload (the AI SDK’s experimental_download), a URL file part fails with a DownloadException before the model request. Create the function with CreateDownload.Create:

var result = await ExperimentalDecide.RunAsync(new DecideOptions
{
Model = model,
Questions = questions,
ExperimentalDownload = CreateDownload.Create(new CreateDownloadOptions { MaxBytes = 10_000_000 }),
State = [new DecisionFileUrlPart("image", new Uri("https://example.com/package.png"))],
});

The download refuses a non-http(s) URL, localhost and internal names, and literal private IP addresses, and checks every redirect hop. It does not resolve DNS, so a name that resolves to a private address gets through. For untrusted URLs, set CreateDownloadOptions.Fetch to a transport that validates DNS when it connects. A failed download, including an error status or a body over MaxBytes (2 GiB by default), throws DownloadException and no decision-model call is made.

CreateDownload.Create returns a Download. Besides the array form that ExperimentalDownload takes, call DownloadAsync(url, cancellationToken) on it to download a single URL with the same guards. CreateDefaultDownloadFunction.Create(download, cancellationToken) builds the default function, which downloads every URL the model does not support, from any single-request DownloadFile; a token you pass replaces the call’s token.

  • No navigate. In-app navigation is a tap on a link. URLs belong in test code.
  • No multi-select listbox and no scrollUntil. type_at never clears a drawn field first, so it suits empty fields.
  • The text model that names a drawn control doesn’t see pixels. It can’t follow an instruction that exists only as drawn text, such as a wizard that paints “tap the circle”.
  • Every decide call and text call counts against MaxModelCalls.
  • Three actions in a row that fail or change nothing block the step with AUTOMATION_UNSUPPORTED.
  • A question the provider refuses fails the step with MODEL_OUTPUT_INVALID.
  • A question has at most 255 options, TypeSafe’s limit. On a larger screen, nodes in the viewport come first and the rest count as omitted, so the model can scroll.
  • The tree the executor reads lists the page’s top-level nodes. It has no root node of its own, so unlike upstream a top-level labeled node is a target for pointer operations too.
  • The port ships OpenAIDecisionModel, DecisionTypeSafeAiModel, and GatewayDecisionProvider, which serves the Gateway’s decision model through the Vercel.AI package. DecisionTypeSafeAiModel.WorkflowSerialize and WorkflowDeserialize carry a TypeSafe model across a workflow boundary (upstream’s WORKFLOW_SERIALIZE and WORKFLOW_DESERIALIZE). The HttpClient is not serialized, so a restored model uses its own default client unless you pass one. The headers are resolved when serialized; without them, the restored model reads TYPESAFE_AI_API_KEY at each call.