Repository navigation
[feat]: generalize decision callback requests - #3628
seanmcguire12 wants to merge 11 commits into
Conversation
|
There was a problem hiding this comment.
1 issue found across 50 files
Confidence score: 4/5
- The table row in
prompt-locator.mdxuses 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
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
There was a problem hiding this comment.
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
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
c9f1a66 to
3d6f585
Compare
| 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) { |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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"), |
There was a problem hiding this comment.
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]
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
choosewithdecidein both sdks &decision.choosewithdecision.requeston the wire. requests contain sharedstate, typedquestions, & optionalmetadata; results contain one answer per question, matched by id. the old, unreleased contract is removed.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.supports&limitsto 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 againstmaxChoicesbefore dispatch.click,select, &upload. python callbacks receive concrete question & state models directly, & both sdks export the concrete decision types, includingDecisionCriterion.test plan
added & extended tests covering:
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
choosebecomesdecidein both SDKs, anddecision.choosebecomesdecision.requeston the wire; the unreleased old contract is removed.state, typed questions keyed by ID, and optionalmetadata; results contain one answer per question, matched by question ID.supportsandlimits; prompt actions validate configuration and capacity before scope resolution or capture.Prompt locators
Written for commit 3d6f585. Summary will update on new commits.