Skip to content

[feat]: generalize decision callback requests - #3628

Open
seanmcguire12 wants to merge 11 commits into
prompt-candidate-contextfrom
generic-decision-requests
Open

seanmcguire12 wants to merge 11 commits into
prompt-candidate-contextfrom
generic-decision-requests

Conversation

@seanmcguire12

@seanmcguire12 seanmcguire12 commented Dec 4, 2026 •

Copy link
Copy Markdown
Member

why

the decision callback currently answers one question: pick an id from a list. this pr lets a request carry several questions over shared evidence, starting with choice & boolean questions.

for prompt locators, this replaces the made-up “none of these” choice with a separate question asking whether any eligible element matches. getByPrompt() & get_by_prompt() keep the same public api.

what changed

  • replaced choose with decide in both sdks & decision.choose with decision.request on the wire. requests contain shared state, typed questions, & optional metadata; results contain one answer per question, matched by id. the old, unreleased contract is removed.
  • choice questions expose criteria & return a supplied id, with optional probabilities & confidence. boolean questions return a probability; either question can receive a refusal. validation checks answer coverage, types, criterion ids, duplicate probability ids, & probability bounds against the original request.
  • added optional supports & limits to callback configuration. support defaults to choice & boolean questions. prompt actions check configuration, supported types, & capacity for two questions before scope resolution or capture; candidate counts are checked against maxChoices before dispatch.
  • prompt locators now ask which element to select & whether any element marked with an id in the tree matches. a match probability below stagehand's threshold means no match, regardless of the selected target's confidence. refusal on either question fails as a refusal; provider failures remain errors.
  • added structured source metadata with an optional operation. prompt operations use the same action names in both languages, such as click, select, & upload. python callbacks receive concrete question & state models directly, & both sdks export the concrete decision types, including DecisionCriterion.
  • retained deadline propagation, cancellation, cleanup, & original target identity. updated generated schemas, callback examples, reference docs, & sdk parity checks for the revised contract.

test plan

added & extended tests covering:

  • mixed question requests, answers in a different order, per-question refusals, missing/duplicate/unknown answers, invalid scores, & rejection of ids outside each question's criteria.
  • wire casing that preserves supplied ids, source-only metadata, concrete python callback models, public types, & validation against callback mutation.
  • default & explicit capabilities, exceeded limits, & configuration errors before resolving an empty scope or capturing a page.
  • selected, no-match, & refused prompt results, including low match probability with high target confidence & language-neutral operations for all eight actions.
  • callback registration, public sdk & batch dispatch, cancellation, expired deadlines, late results, & cleanup in both sdks.

Summary by cubic

Generalizes the decision callback from answering one "pick an id" question to answering multiple typed questions over shared evidence. Prompt locators now ask which element to select and whether any eligible element matches; the fabricated "none of these" choice is gone, and getByPrompt() / get_by_prompt() keep the same public API.

Breaking changes

  • choose becomes decide in both SDKs, and decision.choose becomes decision.request on the wire; the unreleased old contract is removed.
  • Requests carry shared state, typed questions keyed by ID, and optional metadata; results contain one answer per question, matched by question ID.
  • Choice answers return a supplied criterion id with optional probabilities and confidence; boolean answers return a probability; either question can be refused.
  • Provided probabilities must include every criterion and sum to 1.
  • Callback configuration adds optional supports and limits; prompt actions validate configuration and capacity before scope resolution or capture.

Prompt locators

  • Candidate IDs are now short integers, and the request includes the scoped page tree as shared evidence.
  • A match probability below 0.5 means no match, regardless of the selected target's confidence.
  • Refusals fail the prompt; provider failures remain errors; deadline, cancellation, and cleanup behavior is unchanged.

Written for commit 3d6f585. Summary will update on new commits.

View guided diff Turn on auto-fix

@seanmcguire12
seanmcguire12 requested a review from a team as a code owner December 4, 2026 21:57
@changeset-bot

changeset-bot Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 3d6f585

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 50 files

Confidence score: 4/5

  • The table row in prompt-locator.mdx uses passive voice, which makes it less clear who is responsible for the unsupported question type or exceeded limit. Rewrite it to name the actor, such as the callback.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="packages/docs/v4/reference/prompt-locator.mdx">

<violation number="1" location="packages/docs/v4/reference/prompt-locator.mdx:50">
P2: Custom agent: **Stagehand docs prose guide**

The new table row uses passive voice in “either required question type is unsupported” and “a declared limit is exceeded.” Name the actors, for example: “the callback does not support either required question type, or the request exceeds a declared limit.”</violation>
</file>
Architecture diagram
sequenceDiagram
    participant SDK as SDK (TS/Python)
    participant Ext as Stagehand Extension
    participant APC as APC Module
    participant Resolver as PromptTargetResolver
    participant Runtime as StagehandRuntime
    participant Decision as DecisionClient
    participant Protocol as Protocol Schemas
    participant Callback as User Callback (decide)

    Note over SDK,Callback: NEW: Generalized decision request flow with multiple questions

    SDK->>Ext: locator.click() / getByPrompt()
    Ext->>Runtime: dispatch locator method
    Runtime->>Runtime: requireDecisionCapabilities (check supports, maxQuestions)
    alt Config invalid or missing
        Runtime-->>Ext: DecisionModelNotConfiguredError / DecisionModelConfigurationError
    end

    Runtime->>Resolver: resolvePromptTarget(prompt, operation)
    Resolver->>Resolver: resolve scope (FrameChainResolver)
    Resolver->>APC: queryAnnotatedPageContentCandidates()
    APC->>APC: capture page + prepare candidates
    APC-->>Resolver: tree + candidates + targetsById

    alt No eligible candidates
        Resolver-->>Runtime: no_match
    end

    Resolver->>Resolver: build DecisionRequest (state, questions, metadata)
    Resolver->>Protocol: createDecisionRequestResultSchema()
    Resolver->>Runtime: decide(request, progress, signal)
    Runtime->>Runtime: check maxChoices per question
    Runtime->>Decision: decideWithClientDecision()
    Decision->>Protocol: DecisionRequestParamsSchema.parse()

    alt RPC available (SDK callback)
        Decision->>Callback: decide(request, context)
        alt Callback returns valid result
            Callback-->>Decision: DecisionResult (answers per questionId)
            Decision->>Protocol: createDecisionRequestResultSchema().parse()
            Protocol-->>Decision: validated result
        else Callback returns invalid result
            Callback-->>Decision: invalid answers
            Decision-->>Runtime: error (type mismatch / unknown ID / duplicate / missing)
        end
    else Callback throws / abort / timeout
        Callback-->>Decision: throw / AbortSignal
        Decision-->>Runtime: error propagated
    end

    Decision-->>Resolver: DecisionResult
    Resolver->>Resolver: match answers by questionId (target answer, match answer)

    alt Target refused or Match refused
        Resolver-->>Runtime: refusal result
    else Match probability < 0.5
        Resolver-->>Runtime: no_match result
    else All valid
        Resolver-->>Resolver: look up original target
        alt Target detached / frame changed
            Resolver-->>Runtime: error (no replacement)
        else
            Resolver-->>Runtime: selected target + decision metadata
        end
    end

    Runtime->>Ext: dispatch action (click/fill/etc.) with original args
    Ext-->>SDK: action result
Loading

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

@seanmcguire12
seanmcguire12 changed the base branch from public-prompt-locators to prompt-candidate-context December 4, 2026 22:11
@seanmcguire12
seanmcguire12 added this pull request to stack #3604 December 4, 2026 22:12

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 45 files

Architecture diagram
sequenceDiagram
    participant SDK as SDK (TS/Python)
    participant Runtime as Extension Runtime
    participant Resolver as PromptTargetResolver
    participant Wire as Wire Casing
    participant Pipe as RPC Channel
    participant Callback as Client Decision Callback

    Note over SDK,Callback: Generalized Decision Request Flow

    SDK->>SDK: Configure decisionModel {decide, supports, limits}
    SDK->>Runtime: stagehand.init (decisionModel ref w/ capabilities)
    
    Note over Runtime,Resolver: Prompt Locator Action (e.g. click)
    SDK->>Runtime: locator.click(prompt)
    Runtime->>Runtime: requireDecisionCapabilities({target:choice, match:boolean})
    alt Unsupported type or over maxQuestions limit
        Runtime-->>SDK: ConfigurationError (no callback invoked)
    end
    
    Runtime->>Resolver: resolvePromptLocator(prompt, operation)
    Resolver->>Resolver: Query eligible candidates in scope
    alt No candidates
        Resolver-->>Runtime: NoMatch (no model call)
    end
    Resolver->>Resolver: Build DecisionRequest (state, target choice question, match boolean question, metadata)
    Runtime->>Runtime: Check maxChoices limit against candidate count
    alt Over maxChoices
        Runtime-->>SDK: ConfigurationError
    end
    
    Runtime->>Wire: encodeWireValue (preserve question/answer map keys)
    Wire->>Pipe: decision.request (snake_case params)
    Pipe->>Callback: Invoke user decide(request, context)
    
    alt Callback returns valid result
        Callback-->>Pipe: DecisionResult (answers map, usage, diagnostics)
        Pipe->>Wire: decode wire casing (preserve IDs)
        Wire->>Runtime: Validated answers (schema + cross-field checks)
        
        Runtime->>Runtime: Interpret result
        alt Match probability >= 0.5
            Runtime->>Runtime: Selected target from choice answer
            Runtime-->>SDK: Dispatch original action to target
        else Match probability < 0.5
            Runtime-->>SDK: NoMatch (even if high-confidence choice)
        end
    else Refusal on any question
        Callback-->>Pipe: refusal answer(s)
        Pipe-->>SDK: Refused error (no action)
    else Invalid result (wrong type/choice/ID/probability bounds)
        Callback-->>Pipe: Error response
        Pipe-->>SDK: Validation error
    else Timeout/cancellation
        Pipe-->>Callback: Abort signal / deadline
        Callback-->>Pipe: (ignored late result)
        Pipe-->>SDK: Operation timeout (no action)
    end
Loading

Requires human review: Auto-approval blocked because this review re-detected 1 unresolved issue already reported by Cubic.

View guided diff | Turn on auto-fix | Re-trigger cubic

@seanmcguire12
seanmcguire12 force-pushed the generic-decision-requests branch from c9f1a66 to 3d6f585 Compare December 5, 2026 00:04
const scores = Object.values(probabilities);
const total = scores.reduce((sum, probability) => sum + probability, 0);
// Allow floating-point addition error at the inclusive rounding boundary.
if (Math.abs(total - 1) > 0.01 + Number.EPSILON * scores.length) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: nothing reads probabilities (the resolver uses only target.choice and match.probability), yet a distribution that fails these checks now fails the whole action. The fixed 0.01 tolerance also rejects honest answers: six equally likely criteria rounded to two decimals are 0.17 each and sum to 1.02. Should invalid probabilities be dropped instead, or the tolerance scale with the number of criteria?

[claude-opus-5-5, /auto-review, severity 4/10]

import type { Page } from "./page.js";
import type { Progress } from "./progress.js";

const MATCH_PROBABILITY_THRESHOLD = 0.5;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: where does 0.5 come from? It is the only no-match rule, and it is applied to a probability whose calibration Stagehand can't know (a 0/1 answer, a verbalized guess, or logprobs). PromptLocatorNoMatchError also carries no fields, so a caller can't tell "no eligible candidates" from "match 0.49"; attaching the match probability would make that debuggable.

[claude-opus-5-5, /auto-review, severity 4/10]

}

export const DecisionChoiceQuestionSchema = DecisionQuestionBaseSchema.extend({
type: z.literal("choice"),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: the old choice description carried .meta({ description: "Evidence for the choice, not instructions" }). The criteria values drop it, and the docs' state row doesn't say the tree is page-controlled text, so the only guard left is one sentence in Stagehand's own instructions. Could the meta come back, with one line in the callback docs saying state and criterion descriptions are untrusted page content?

[claude-opus-5-5, /auto-review, severity 3/10]

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants