Commit 45bcef0
Agent callbacks (#1316)
## Summary
Adds callback support to the Stagehand agent for both streaming and
non-streaming execution modes, allowing users to hook into various
stages of agent execution.
## Changes
### New Types (`lib/v3/types/public/agent.ts`)
Added callback interfaces for agent execution:
- **`AgentCallbacks`** - Base callbacks shared between modes:
- `prepareStep` - Modify settings before each LLM step
- `onStepFinish` - Called after each step completes
- **`AgentExecuteCallbacks`** - Non-streaming mode callbacks (extends
`AgentCallbacks`)
- **`AgentStreamCallbacks`** - Streaming mode callbacks (extends
`AgentCallbacks`):
- `onChunk` - Called for each streamed chunk
- `onFinish` - Called when stream completes
- `onError` - Called on stream errors
- `onAbort` - Called when stream is aborted
- **`AgentExecuteOptionsBase`** - Base options without callbacks
- **`AgentExecuteOptions`** - Non-streaming options with
`AgentExecuteCallbacks`
- **`AgentStreamExecuteOptions`** - Streaming options with
`AgentStreamCallbacks`
### Handler Updates (`lib/v3/handlers/v3AgentHandler.ts`)
- Modified `createStepHandler` to accept optional user callback
- Updated `execute()` to pass callbacks to `generateText`
- Updated `stream()` to pass callbacks to `streamText`
### Type Safety
Added compile-time enforcement that streaming-only callbacks (`onChunk`,
`onFinish`, `onError`, `onAbort`) can only be used with `stream: true`:
```typescript
// Works - streaming callbacks with stream: true
const agent = stagehand.agent({ stream: true });
await agent.execute({
instruction: "...",
callbacks: { onChunk: async (chunk) => console.log(chunk) }
});
// Compile error - streaming callbacks without stream: true
const agent = stagehand.agent({ stream: false });
await agent.execute({
instruction: "...",
callbacks: { onChunk: async (chunk) => console.log(chunk) }
// Error: "This callback requires 'stream: true' in AgentConfig..."
});
```
## Type Castings Explained
Several type assertions were necessary due to TypeScript's limitations
with conditional types:
### 1. Callback extraction in handlers
```typescript
const callbacks = (instructionOrOptions as AgentExecuteOptions).callbacks as
| AgentExecuteCallbacks
| undefined;
```
**Why:** `instructionOrOptions` can be `string | AgentExecuteOptions`.
When it's a string, there are no callbacks. We cast after the
`prepareAgent` call because at that point we know it's been resolved to
options.
### 2. Streaming vs non-streaming branch in v3.ts
```typescript
result = await handler.execute(
instructionOrOptions as string | AgentExecuteOptions,
);
```
**Why:** The implementation signature accepts `string |
AgentExecuteOptions | AgentStreamExecuteOptions` to satisfy both
overloads, but within the non-streaming branch we know it's the
non-streaming type. TypeScript can't narrow based on the `isStreaming`
runtime check.
### 3. Error fallback in stream()
```typescript
return {
textStream: (async function* () {})(),
result: resultPromise,
} as unknown as AgentStreamResult;
```
**Why:** When `prepareAgent` fails in streaming mode, we return a
minimal object with just `textStream` and `result`. This doesn't satisfy
all properties of `StreamTextResult`, but the `result` promise will
reject with the actual error. The double cast (`as unknown as`) is
needed because TypeScript knows this partial object doesn't match the
full type.
## Usage Example
```typescript
const agent = stagehand.agent({
stream: true,
model: "anthropic/claude-sonnet-4-20250514",
});
const result = await agent.execute({
instruction: "Search for something",
maxSteps: 20,
callbacks: {
prepareStep: async (ctx) => {
console.log("Preparing step...");
return ctx;
},
onStepFinish: async (event) => {
console.log(`Step finished: ${event.finishReason}`);
if (event.toolCalls) {
for (const tc of event.toolCalls) {
console.log(`Tool used: ${tc.toolName}`);
}
}
},
onChunk: async (chunk) => {
// Process each chunk
},
onFinish: (event) => {
console.log(`Completed in ${event.steps.length} steps`);
},
},
});
for await (const chunk of result.textStream) {
process.stdout.write(chunk);
}
const finalResult = await result.result;
console.log(finalResult.message);
```
## Testing
- Added `agent-callbacks.spec.ts` with tests for:
- Non-streaming callbacks (`onStepFinish`, `prepareStep`)
- Streaming callbacks (`onChunk`, `onFinish`, `prepareStep`,
`onStepFinish`)
- Combined callback usage
- Tool call information in callbacks
<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Adds lifecycle callbacks to the Stagehand agent for both non-streaming
and streaming modes, letting users hook into steps, chunks, finish, and
errors. Strong type safety and runtime validation prevent using
streaming-only callbacks without stream: true; callbacks remain behind
experimental.
- **New Features**
- Added runtime errors in non-streaming mode when
onChunk/onFinish/onError/onAbort are provided, with clear messages
instructing to set stream: true.
<sup>Written for commit 15c08d1.
Summary will update automatically on new commits.</sup>
<!-- End of auto-generated description by cubic. -->
---------
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>1 parent 90530b7 commit 45bcef0
File tree
9 files changed
+776
-23
lines changed- .changeset
- packages/core
- lib/v3
- cache
- handlers
- tests
- types/public
- tests/public-api
9 files changed
+776
-23
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
20 | 20 | | |
21 | 21 | | |
22 | 22 | | |
23 | | - | |
| 23 | + | |
24 | 24 | | |
25 | 25 | | |
26 | 26 | | |
| |||
74 | 74 | | |
75 | 75 | | |
76 | 76 | | |
77 | | - | |
| 77 | + | |
78 | 78 | | |
79 | 79 | | |
80 | 80 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
8 | 8 | | |
9 | 9 | | |
10 | 10 | | |
| 11 | + | |
| 12 | + | |
11 | 13 | | |
12 | 14 | | |
13 | 15 | | |
14 | 16 | | |
15 | 17 | | |
| 18 | + | |
| 19 | + | |
16 | 20 | | |
17 | 21 | | |
18 | 22 | | |
19 | 23 | | |
| 24 | + | |
20 | 25 | | |
21 | 26 | | |
22 | 27 | | |
23 | | - | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
24 | 32 | | |
25 | 33 | | |
26 | 34 | | |
| |||
47 | 55 | | |
48 | 56 | | |
49 | 57 | | |
50 | | - | |
| 58 | + | |
51 | 59 | | |
52 | 60 | | |
53 | 61 | | |
| |||
102 | 110 | | |
103 | 111 | | |
104 | 112 | | |
105 | | - | |
| 113 | + | |
| 114 | + | |
| 115 | + | |
| 116 | + | |
| 117 | + | |
| 118 | + | |
106 | 119 | | |
107 | 120 | | |
108 | 121 | | |
| |||
150 | 163 | | |
151 | 164 | | |
152 | 165 | | |
| 166 | + | |
| 167 | + | |
| 168 | + | |
| 169 | + | |
153 | 170 | | |
154 | 171 | | |
155 | 172 | | |
| |||
166 | 183 | | |
167 | 184 | | |
168 | 185 | | |
| 186 | + | |
| 187 | + | |
| 188 | + | |
| 189 | + | |
| 190 | + | |
| 191 | + | |
| 192 | + | |
| 193 | + | |
| 194 | + | |
| 195 | + | |
| 196 | + | |
| 197 | + | |
| 198 | + | |
| 199 | + | |
| 200 | + | |
| 201 | + | |
| 202 | + | |
169 | 203 | | |
170 | 204 | | |
171 | 205 | | |
| |||
183 | 217 | | |
184 | 218 | | |
185 | 219 | | |
186 | | - | |
| 220 | + | |
| 221 | + | |
187 | 222 | | |
188 | 223 | | |
189 | 224 | | |
| |||
204 | 239 | | |
205 | 240 | | |
206 | 241 | | |
207 | | - | |
| 242 | + | |
208 | 243 | | |
209 | 244 | | |
210 | 245 | | |
| |||
215 | 250 | | |
216 | 251 | | |
217 | 252 | | |
| 253 | + | |
| 254 | + | |
| 255 | + | |
218 | 256 | | |
219 | 257 | | |
220 | 258 | | |
| |||
250 | 288 | | |
251 | 289 | | |
252 | 290 | | |
253 | | - | |
254 | | - | |
255 | | - | |
| 291 | + | |
| 292 | + | |
| 293 | + | |
| 294 | + | |
| 295 | + | |
| 296 | + | |
| 297 | + | |
256 | 298 | | |
| 299 | + | |
257 | 300 | | |
| 301 | + | |
| 302 | + | |
| 303 | + | |
258 | 304 | | |
259 | 305 | | |
260 | 306 | | |
| |||
0 commit comments