[Claimed #1978] fix: add variable substitution to keys step during cache replay
Mirrored from external contributor PR #1978 after approval by @pirate.
Original author: @a7med3liamin
Original PR: https://github.com/browserbase/stagehand/pull/1978
Approved source head SHA: 2149aa265a04dc37154d5a84411f3ab4d1045897
@a7med3liamin, please continue any follow-up discussion on this mirrored PR. When the external PR gets new commits, this same internal PR will be marked stale until the latest external commit is approved and refreshed here.
Original description
- Check the documentation for relevant information
- Search existing issues to avoid duplicates
Fixes #1776
Problem
The keys tool has no variable substitution in either the live execution or cache replay paths. When the agent uses %variableName% tokens with the keys tool, the literal token string gets typed instead of the resolved value.
Fix
This PR combines two fixes into one:
1. Live execution (original fix by @trillville from #1777)
- Accept
variablesparameter inkeysTool(matchingtypeTool) - Call
substituteVariables()beforepage.type()in themethod === "type"branch - Pass
variablestokeysToolincreateAgentTools - Update schema description to advertise available variables to the LLM
- Return original token in result to avoid exposing sensitive values to LLM
2. Cache replay (new fix)
- Import
substituteVariablesinAgentCache.ts - Pass
variablesthrough toreplayAgentKeysStep - Call
substituteVariables(text, variables)beforepage.type()in the replay path
Without fix #2, cached keys steps with method="type" replay by typing literal %variableName% tokens even when variables are provided, since replayAgentKeysStep had no access to the variables map.
Credit
The live execution fix (part 1) is from @trillville's work in #1777/#1813. We merged it here with the cache replay fix per @pirate's request to consolidate into a single PR.
Summary by cubic
Add variable substitution to the keys tool for both live execution and cache replay so %variableName% tokens are resolved before typing. This fixes cases where literal tokens were typed and brings parity with the type tool.
- Bug Fixes
- Pass
variablesintokeysand callsubstituteVariables()beforepage.type(); update the input schema to list available variables. - In cache replay, forward
variablestoreplayAgentKeysStepand substitute before typing to avoid replaying literal tokens. - Record and return the original tokenized value (not the resolved value) to avoid leaking sensitive data.
- Pass