-
Notifications
You must be signed in to change notification settings - Fork 13.9k
Expand file tree
/
Copy pathbrowserAgentFactory.ts
More file actions
328 lines (296 loc) · 10.6 KB
/
browserAgentFactory.ts
File metadata and controls
328 lines (296 loc) · 10.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
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview Factory for creating browser agent definitions with configured tools.
*
* This factory is called when the browser agent is invoked via delegate_to_agent.
* It creates a BrowserManager, connects the isolated MCP client, wraps tools,
* and returns a fully configured LocalAgentDefinition.
*
* IMPORTANT: The MCP tools are ONLY available to the browser agent's isolated
* registry. They are NOT registered in the main agent's ToolRegistry.
*/
import type { Config } from '../../config/config.js';
import { AuthType } from '../../core/contentGenerator.js';
import type { LocalAgentDefinition } from '../types.js';
import type { MessageBus } from '../../confirmation-bus/message-bus.js';
import type { AnyDeclarativeTool } from '../../tools/tools.js';
import { BrowserManager } from './browserManager.js';
import { BROWSER_AGENT_NAME } from './browserAgentDefinition.js';
import { MCP_TOOL_PREFIX } from '../../tools/mcp-tool.js';
import {
BrowserAgentDefinition,
type BrowserTaskResultSchema,
} from './browserAgentDefinition.js';
import { createMcpDeclarativeTools } from './mcpToolWrapper.js';
import { createAnalyzeScreenshotTool } from './analyzeScreenshot.js';
import { injectAutomationOverlay } from './automationOverlay.js';
import { injectInputBlocker } from './inputBlocker.js';
import { debugLogger } from '../../utils/debugLogger.js';
import {
recordBrowserAgentToolDiscovery,
recordBrowserAgentVisionStatus,
recordBrowserAgentCleanup,
} from '../../telemetry/metrics.js';
import {
PolicyDecision,
PRIORITY_SUBAGENT_TOOL,
type PolicyRule,
MODES_BY_PERMISSIVENESS,
} from '../../policy/types.js';
/**
* Structured return type for vision disabled reasons.
* Separates the condition code from the human-readable message.
*/
type VisionDisabledReason =
| { code: 'no_visual_model'; message: string }
| { code: 'missing_visual_tools'; message: string }
| { code: 'blocked_auth_type'; message: string }
| undefined;
/**
* Creates a browser agent definition with MCP tools configured.
*
* This is called when the browser agent is invoked via delegate_to_agent.
* The MCP client is created fresh and tools are wrapped for the agent's
* isolated registry - NOT registered with the main agent.
*
* @param config Runtime configuration
* @param messageBus Message bus for tool invocations
* @param printOutput Optional callback for progress messages
* @returns Fully configured LocalAgentDefinition with MCP tools
*/
export async function createBrowserAgentDefinition(
config: Config,
messageBus: MessageBus,
_printOutput?: (msg: string) => void,
): Promise<{
definition: LocalAgentDefinition<typeof BrowserTaskResultSchema>;
browserManager: BrowserManager;
visionEnabled: boolean;
sessionMode: 'persistent' | 'isolated' | 'existing';
}> {
debugLogger.log(
'Creating browser agent definition with isolated MCP tools...',
);
// Get or create browser manager singleton for this session mode/profile
const browserManager = BrowserManager.getInstance(config);
await browserManager.ensureConnection();
debugLogger.log('Browser connected with isolated MCP client.');
// Determine if input blocker should be active (non-headless + enabled)
const shouldDisableInput = config.shouldDisableBrowserUserInput();
// Inject automation overlay and input blocker if not in headless mode
const browserConfig = config.getBrowserAgentConfig();
if (!browserConfig?.customConfig?.headless) {
debugLogger.log('Injecting automation overlay...');
await injectAutomationOverlay(browserManager);
if (shouldDisableInput) {
debugLogger.log('Injecting input blocker...');
await injectInputBlocker(browserManager);
}
}
// Create declarative tools from dynamically discovered MCP tools
// These tools dispatch to browserManager's isolated client
const mcpTools = await createMcpDeclarativeTools(
browserManager,
messageBus,
shouldDisableInput,
browserConfig.customConfig.blockFileUploads,
);
const availableToolNames = mcpTools.map((t) => t.name);
// Register high-priority policy rules for sensitive actions which is not
// able to be overwrite by YOLO mode.
const policyEngine = config.getPolicyEngine();
if (policyEngine) {
const existingRules = policyEngine.getRules();
const restrictedTools = ['fill', 'fill_form'];
// ASK_USER for upload_file and evaluate_script when sensitive action
// need confirmation.
if (browserConfig.customConfig.confirmSensitiveActions) {
restrictedTools.push('upload_file', 'evaluate_script');
}
for (const toolName of restrictedTools) {
const rule = generateAskUserRules(toolName);
if (!existingRules.some((r) => isRuleEqual(r, rule))) {
policyEngine.addRule(rule);
}
}
// Reduce noise for read-only tools in default mode
const readOnlyTools = (await browserManager.getDiscoveredTools())
.filter((t) => !!t.annotations?.readOnlyHint)
.map((t) => t.name);
const allowlistedReadonlyTools = ['take_snapshot', 'take_screenshot'];
for (const toolName of [...readOnlyTools, ...allowlistedReadonlyTools]) {
if (availableToolNames.includes(toolName)) {
const rule = generateAllowRules(toolName);
if (!existingRules.some((r) => isRuleEqual(r, rule))) {
policyEngine.addRule(rule);
}
}
}
}
function generateAskUserRules(toolName: string): PolicyRule {
return {
toolName: `${MCP_TOOL_PREFIX}${BROWSER_AGENT_NAME}_${toolName}`,
decision: PolicyDecision.ASK_USER,
priority: 999,
modes: MODES_BY_PERMISSIVENESS,
source: 'BrowserAgent (Sensitive Actions)',
mcpName: BROWSER_AGENT_NAME,
};
}
function generateAllowRules(toolName: string): PolicyRule {
return {
toolName: `${MCP_TOOL_PREFIX}${BROWSER_AGENT_NAME}_${toolName}`,
decision: PolicyDecision.ALLOW,
priority: PRIORITY_SUBAGENT_TOOL,
modes: MODES_BY_PERMISSIVENESS,
source: 'BrowserAgent (Read-Only)',
mcpName: BROWSER_AGENT_NAME,
};
}
// Check if policy rule the same in all the attributes that we care about
function isRuleEqual(rule1: PolicyRule, rule2: PolicyRule) {
return (
rule1.toolName === rule2.toolName &&
rule1.decision === rule2.decision &&
rule1.priority === rule2.priority &&
rule1.mcpName === rule2.mcpName &&
rule1.modes.length === rule2.modes.length &&
rule1.modes.every((m) => rule2.modes.includes(m))
);
}
// Validate required semantic tools are available
const requiredSemanticTools = [
'click',
'fill',
'navigate_page',
'take_snapshot',
];
const missingSemanticTools = requiredSemanticTools.filter(
(t) => !availableToolNames.includes(t),
);
const rawSessionMode = browserConfig?.customConfig?.sessionMode;
const sessionMode =
rawSessionMode === 'isolated' || rawSessionMode === 'existing'
? rawSessionMode
: 'persistent';
recordBrowserAgentToolDiscovery(
config,
mcpTools.length,
missingSemanticTools,
sessionMode,
);
if (missingSemanticTools.length > 0) {
debugLogger.warn(
`Semantic tools missing (${missingSemanticTools.join(', ')}). ` +
'Some browser interactions may not work correctly.',
);
}
// Only click_at is strictly required — text input can use press_key or fill.
const requiredVisualTools = ['click_at'];
const missingVisualTools = requiredVisualTools.filter(
(t) => !availableToolNames.includes(t),
);
// Check whether vision can be enabled; returns structured type with code and message.
function getVisionDisabledReason(): VisionDisabledReason {
const browserConfig = config.getBrowserAgentConfig();
if (!browserConfig.customConfig.visualModel) {
return {
code: 'no_visual_model',
message: 'No visualModel configured.',
};
}
if (missingVisualTools.length > 0) {
return {
code: 'missing_visual_tools',
message:
`Visual tools missing (${missingVisualTools.join(', ')}). ` +
`The installed chrome-devtools-mcp version may be too old.`,
};
}
const authType = config.getContentGeneratorConfig()?.authType;
const blockedAuthTypes = new Set([
AuthType.LOGIN_WITH_GOOGLE,
AuthType.LEGACY_CLOUD_SHELL,
AuthType.COMPUTE_ADC,
]);
if (authType && blockedAuthTypes.has(authType)) {
return {
code: 'blocked_auth_type',
message: 'Visual agent model not available for current auth type.',
};
}
return undefined;
}
const allTools: AnyDeclarativeTool[] = [...mcpTools];
const visionDisabledReason = getVisionDisabledReason();
recordBrowserAgentVisionStatus(config, {
enabled: !visionDisabledReason,
disabled_reason: visionDisabledReason?.code,
});
if (visionDisabledReason) {
debugLogger.log(`Vision disabled: ${visionDisabledReason.message}`);
} else {
allTools.push(
createAnalyzeScreenshotTool(browserManager, config, messageBus),
);
}
debugLogger.log(
`Created ${allTools.length} tools for browser agent: ` +
allTools.map((t) => t.name).join(', '),
);
// Create configured definition with tools
// BrowserAgentDefinition is a factory function - call it with config
const baseDefinition = BrowserAgentDefinition(config, !visionDisabledReason);
const definition: LocalAgentDefinition<typeof BrowserTaskResultSchema> = {
...baseDefinition,
toolConfig: {
tools: allTools,
},
};
return {
definition,
browserManager,
visionEnabled: !visionDisabledReason,
sessionMode,
};
}
/**
* Closes all persistent browser sessions and cleans up resources.
*
* @param browserManager The browser manager to clean up
* @param config Runtime configuration
* @param sessionMode The browser session mode
*/
export async function cleanupBrowserAgent(
browserManager: BrowserManager,
config: Config,
sessionMode: 'persistent' | 'isolated' | 'existing',
): Promise<void> {
const startMs = Date.now();
try {
await browserManager.close();
recordBrowserAgentCleanup(config, Date.now() - startMs, {
session_mode: sessionMode,
success: true,
});
debugLogger.log('Browser agent cleanup complete');
} catch (error) {
recordBrowserAgentCleanup(config, Date.now() - startMs, {
session_mode: sessionMode,
success: false,
});
debugLogger.error(
`Error during browser cleanup: ${error instanceof Error ? error.message : String(error)}`,
);
}
}
/**
* Call this on /clear commands and CLI exit to reset browser state.
*/
export async function resetBrowserSession(): Promise<void> {
await BrowserManager.resetAll();
}