-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.ts
More file actions
494 lines (442 loc) · 14.6 KB
/
agent.ts
File metadata and controls
494 lines (442 loc) · 14.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
/**
* Sentience Agent: High-level automation agent using LLM + SDK
* Implements observe-think-act loop for natural language commands
*/
import { SentienceBrowser } from './browser';
import { snapshot, SnapshotOptions } from './snapshot';
import { Snapshot } from './types';
import { LLMProvider, LLMResponse } from './llm-provider';
import { Tracer } from './tracing/tracer';
import { randomUUID } from 'crypto';
import { TraceEventBuilder } from './utils/trace-event-builder';
import { LLMInteractionHandler } from './utils/llm-interaction-handler';
import { ActionExecutor } from './utils/action-executor';
import { SnapshotEventBuilder } from './utils/snapshot-event-builder';
import { SnapshotProcessor } from './utils/snapshot-processor';
/**
* Execution result from agent.act()
*/
export interface AgentActResult {
success: boolean;
action?: string;
elementId?: number;
text?: string;
key?: string;
outcome?: string;
urlChanged?: boolean;
durationMs: number;
attempt: number;
goal: string;
error?: string;
message?: string;
/** Optional action metadata (e.g., human-like cursor movement path) */
cursor?: Record<string, any>;
}
/**
* History entry for executed action
*/
export interface HistoryEntry {
goal: string;
action: string;
result: AgentActResult;
success: boolean;
attempt: number;
durationMs: number;
}
/**
* Token usage statistics
*/
export interface TokenStats {
totalPromptTokens: number;
totalCompletionTokens: number;
totalTokens: number;
byAction: Array<{
goal: string;
promptTokens?: number;
completionTokens?: number;
totalTokens?: number;
model?: string;
}>;
}
/**
* High-level agent that combines Sentience SDK with any LLM provider.
*
* Uses observe-think-act loop to execute natural language commands:
* 1. OBSERVE: Get snapshot of current page state
* 2. THINK: Query LLM to decide next action
* 3. ACT: Execute action using SDK
*
* Example:
* ```typescript
* import { SentienceBrowser, SentienceAgent, OpenAIProvider } from 'sentience-ts';
*
* const browser = await SentienceBrowser.create({ apiKey: 'sentience_key' });
* const llm = new OpenAIProvider('openai_key', 'gpt-4o');
* const agent = new SentienceAgent(browser, llm);
*
* await browser.getPage().goto('https://google.com');
* await agent.act('Click the search box');
* await agent.act("Type 'magic mouse' into the search field");
* await agent.act('Press Enter key');
* ```
*/
export class SentienceAgent {
private browser: SentienceBrowser;
private llm: LLMProvider;
private snapshotLimit: number;
private verbose: boolean;
private tracer?: Tracer;
private stepCount: number;
private history: HistoryEntry[];
private tokenUsage: TokenStats;
private showOverlay: boolean;
private previousSnapshot?: Snapshot;
private llmHandler: LLMInteractionHandler;
private actionExecutor: ActionExecutor;
/**
* Initialize Sentience Agent
* @param browser - SentienceBrowser instance
* @param llm - LLM provider (OpenAIProvider, AnthropicProvider, etc.)
* @param snapshotLimit - Maximum elements to include in context (default: 50)
* @param verbose - Print execution logs (default: true)
* @param tracer - Optional tracer for recording execution (default: undefined)
* @param showOverlay - Show green bbox overlay in browser (default: false)
*/
constructor(
browser: SentienceBrowser,
llm: LLMProvider,
snapshotLimit: number = 50,
verbose: boolean = true,
tracer?: Tracer,
showOverlay: boolean = false
) {
this.browser = browser;
this.llm = llm;
this.snapshotLimit = snapshotLimit;
this.verbose = verbose;
this.tracer = tracer;
this.showOverlay = showOverlay;
this.stepCount = 0;
this.history = [];
this.tokenUsage = {
totalPromptTokens: 0,
totalCompletionTokens: 0,
totalTokens: 0,
byAction: [],
};
// Initialize handlers
this.llmHandler = new LLMInteractionHandler(this.llm, this.verbose);
this.actionExecutor = new ActionExecutor(this.browser, this.verbose);
}
/**
* Get bounding box for an element from snapshot
*/
private getElementBbox(
elementId: number | undefined,
snap: Snapshot
): { x: number; y: number; width: number; height: number } | undefined {
if (elementId === undefined) return undefined;
const el = snap.elements.find(e => e.id === elementId);
if (!el) return undefined;
return {
x: el.bbox.x,
y: el.bbox.y,
width: el.bbox.width,
height: el.bbox.height,
};
}
/**
* @deprecated Use LLMInteractionHandler.buildContext() instead
*/
private buildContext(snap: Snapshot, goal: string): string {
return this.llmHandler.buildContext(snap, goal);
}
/**
* @deprecated Use LLMInteractionHandler.queryLLM() instead
*/
private async queryLLM(domContext: string, goal: string): Promise<LLMResponse> {
return this.llmHandler.queryLLM(domContext, goal);
}
/**
* @deprecated Use ActionExecutor.executeAction() instead
*/
private async executeAction(actionStr: string, snap: Snapshot): Promise<AgentActResult> {
return this.actionExecutor.executeAction(actionStr, snap);
}
/**
* Execute a high-level goal using observe → think → act loop
* @param goal - Natural language instruction (e.g., "Click the Sign In button")
* @param maxRetries - Number of retries on failure (default: 2)
* @param snapshotOptions - Optional snapshot parameters (limit, filter, etc.)
* @returns Result dict with status, action_taken, reasoning, and execution data
*
* Example:
* ```typescript
* const result = await agent.act('Click the search box');
* console.log(result);
* // { success: true, action: 'click', elementId: 42, ... }
* ```
*/
async act(
goal: string,
maxRetries: number = 2,
snapshotOptions?: SnapshotOptions
): Promise<AgentActResult> {
if (this.verbose) {
console.log('\n' + '='.repeat(70));
console.log(`🤖 Agent Goal: ${goal}`);
console.log('='.repeat(70));
}
// Increment step counter and generate step ID
this.stepCount += 1;
const stepId = randomUUID();
// Emit step_start event
if (this.tracer) {
const page = this.browser.getPage();
const currentUrl = page ? page.url() : 'unknown';
this.tracer.emitStepStart(stepId, this.stepCount, goal, 0, currentUrl);
}
// Track data collected during step execution for step_end emission on failure
let stepSnapWithDiff: Snapshot | null = null;
let stepPreUrl: string | null = null;
let stepLlmResponse: LLMResponse | null = null;
let stepStartTime: number = Date.now();
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
// 1. OBSERVE: Get refined semantic snapshot
const startTime = Date.now();
stepStartTime = startTime;
const snapOpts: SnapshotOptions = {
...snapshotOptions,
goal: snapshotOptions?.goal ?? goal,
limit: snapshotOptions?.limit || this.snapshotLimit,
};
// Apply showOverlay from agent config if not explicitly set in snapshotOptions
if (snapshotOptions?.show_overlay === undefined) {
snapOpts.show_overlay = this.showOverlay;
}
const snap = await snapshot(this.browser, snapOpts);
if (snap.status !== 'success') {
throw new Error(`Snapshot failed: ${snap.error}`);
}
// Process snapshot: compute diff status and filter elements
const processed = SnapshotProcessor.process(
snap,
this.previousSnapshot,
goal,
this.snapshotLimit
);
// Update previous snapshot for next comparison
this.previousSnapshot = snap;
const snapWithDiff = processed.withDiff;
const filteredSnap = processed.filtered;
// Track for step_end emission on failure
stepSnapWithDiff = snapWithDiff;
stepPreUrl = snap.url;
// Emit snapshot event
if (this.tracer) {
const snapshotData = SnapshotEventBuilder.buildSnapshotEventData(snapWithDiff, stepId);
this.tracer.emit('snapshot', snapshotData, stepId);
}
// 2. GROUND: Format elements for LLM context (filteredSnap already created above)
const context = this.llmHandler.buildContext(filteredSnap, goal);
// 3. THINK: Query LLM for next action
const llmResponse = await this.llmHandler.queryLLM(context, goal);
// Track for step_end emission on failure
stepLlmResponse = llmResponse;
if (this.verbose) {
console.log(`🧠 LLM Decision: ${llmResponse.content}`);
}
// Emit LLM response event
if (this.tracer) {
this.tracer.emit(
'llm_response',
{
model: llmResponse.modelName,
prompt_tokens: llmResponse.promptTokens,
completion_tokens: llmResponse.completionTokens,
response_text: llmResponse.content.substring(0, 500),
},
stepId
);
}
// Track token usage
this.trackTokens(goal, llmResponse);
// Parse action from LLM response
const actionStr = this.llmHandler.extractAction(llmResponse);
// 4. EXECUTE: Parse and run action
const result = await this.actionExecutor.executeAction(actionStr, filteredSnap);
const durationMs = Date.now() - startTime;
result.durationMs = durationMs;
result.attempt = attempt;
result.goal = goal;
// Emit action event
if (this.tracer) {
this.tracer.emit(
'action',
{
action_type: result.action,
element_id: result.elementId,
text: result.text,
key: result.key,
success: result.success,
cursor: result.cursor,
},
stepId
);
}
// 5. RECORD: Track history
this.history.push({
goal,
action: actionStr,
result,
success: result.success,
attempt,
durationMs,
});
if (this.verbose) {
const status = result.success ? '✅' : '❌';
console.log(`${status} Completed in ${durationMs}ms`);
}
// Emit step_end event if tracer is enabled
if (this.tracer) {
const preUrl = snap.url;
const postUrl = this.browser.getPage()?.url() || null;
let postSnapshotDigest: string | undefined;
try {
const postSnap = await snapshot(this.browser, {
goal: `${goal} (post)`,
limit: Math.min(this.snapshotLimit, 10),
show_overlay: this.showOverlay,
});
if (postSnap.status === 'success') {
postSnapshotDigest = TraceEventBuilder.buildSnapshotDigest(postSnap);
}
} catch {
postSnapshotDigest = undefined;
}
// Build step_end event using TraceEventBuilder
// Use snapWithDiff to include elements with diff_status in pre field
const stepEndData = TraceEventBuilder.buildStepEndData({
stepId,
stepIndex: this.stepCount,
goal,
attempt,
preUrl,
postUrl,
postSnapshotDigest,
snapshot: snapWithDiff,
llmResponse,
result,
});
this.tracer.emit('step_end', stepEndData, stepId);
}
return result;
} catch (error: any) {
// Emit error event
if (this.tracer) {
this.tracer.emitError(stepId, error.message, attempt);
}
if (attempt < maxRetries) {
if (this.verbose) {
console.log(`⚠️ Retry ${attempt + 1}/${maxRetries}: ${error.message}`);
}
await new Promise(resolve => setTimeout(resolve, 1000));
continue;
} else {
// Emit step_end with whatever data we collected before failure
// This ensures diff_status and other fields are preserved in traces
if (this.tracer && stepSnapWithDiff) {
const postUrl = this.browser.getPage()?.url() || null;
const durationMs = Date.now() - stepStartTime;
const stepEndData = TraceEventBuilder.buildPartialStepEndData({
stepId,
stepIndex: this.stepCount,
goal,
attempt,
preUrl: stepPreUrl,
postUrl,
snapshot: stepSnapWithDiff,
llmResponse: stepLlmResponse,
error: error.message,
durationMs,
});
this.tracer.emit('step_end', stepEndData, stepId);
}
const errorResult: AgentActResult = {
success: false,
goal,
error: error.message,
attempt,
durationMs: 0,
};
this.history.push(errorResult as any);
throw new Error(`Failed after ${maxRetries} retries: ${error.message}`);
}
}
}
throw new Error('Unexpected: loop should have returned or thrown');
}
/**
* Track token usage for analytics
*/
private trackTokens(goal: string, llmResponse: LLMResponse): void {
if (llmResponse.promptTokens) {
this.tokenUsage.totalPromptTokens += llmResponse.promptTokens;
}
if (llmResponse.completionTokens) {
this.tokenUsage.totalCompletionTokens += llmResponse.completionTokens;
}
if (llmResponse.totalTokens) {
this.tokenUsage.totalTokens += llmResponse.totalTokens;
}
this.tokenUsage.byAction.push({
goal,
promptTokens: llmResponse.promptTokens,
completionTokens: llmResponse.completionTokens,
totalTokens: llmResponse.totalTokens,
model: llmResponse.modelName,
});
}
/**
* Get token usage statistics
* @returns Dictionary with token usage breakdown
*/
getTokenStats(): TokenStats {
return { ...this.tokenUsage };
}
/**
* Get execution history
* @returns List of all actions taken with results
*/
getHistory(): HistoryEntry[] {
return [...this.history];
}
/**
* Clear execution history and reset token counters
*/
clearHistory(): void {
this.history = [];
this.stepCount = 0;
this.tokenUsage = {
totalPromptTokens: 0,
totalCompletionTokens: 0,
totalTokens: 0,
byAction: [],
};
}
/**
* Close the tracer and flush events to disk
*/
async closeTracer(): Promise<void> {
if (this.tracer) {
await this.tracer.close();
}
}
/**
* Get the tracer instance (if any)
*/
getTracer(): Tracer | undefined {
return this.tracer;
}
}