codebuff 1.0.253 → 1.0.255
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/background-process-manager.d.ts +50 -0
- package/dist/background-process-manager.js +359 -0
- package/dist/background-process-manager.js.map +1 -0
- package/dist/browser-runner.d.ts +35 -0
- package/dist/browser-runner.js +680 -0
- package/dist/browser-runner.js.map +1 -0
- package/dist/chat-storage.d.ts +2 -0
- package/dist/chat-storage.js +93 -0
- package/dist/chat-storage.js.map +1 -0
- package/dist/checkpoints/checkpoint-manager.d.ts +94 -0
- package/dist/checkpoints/checkpoint-manager.js +280 -0
- package/dist/checkpoints/checkpoint-manager.js.map +1 -0
- package/dist/checkpoints/file-manager.d.ts +72 -0
- package/dist/checkpoints/file-manager.js +311 -0
- package/dist/checkpoints/file-manager.js.map +1 -0
- package/dist/cli-handlers/api-key.d.ts +25 -0
- package/dist/cli-handlers/api-key.js +66 -0
- package/dist/cli-handlers/api-key.js.map +1 -0
- package/dist/cli-handlers/checkpoint.d.ts +18 -0
- package/dist/cli-handlers/checkpoint.js +195 -0
- package/dist/cli-handlers/checkpoint.js.map +1 -0
- package/dist/cli-handlers/diff.d.ts +2 -0
- package/dist/cli-handlers/diff.js +31 -0
- package/dist/cli-handlers/diff.js.map +1 -0
- package/dist/cli-handlers/easter-egg.d.ts +1 -0
- package/dist/cli-handlers/easter-egg.js +126 -0
- package/dist/cli-handlers/easter-egg.js.map +1 -0
- package/dist/cli-handlers/inititalization-flow.d.ts +1 -0
- package/dist/cli-handlers/inititalization-flow.js +24 -0
- package/dist/cli-handlers/inititalization-flow.js.map +1 -0
- package/dist/cli.d.ts +44 -0
- package/dist/cli.js +478 -0
- package/dist/cli.js.map +1 -0
- package/dist/client.d.ts +157 -0
- package/dist/client.js +836 -0
- package/dist/client.js.map +1 -0
- package/dist/code-map/tsconfig.tsbuildinfo +1 -1
- package/dist/config.d.ts +4 -0
- package/dist/config.js +12 -0
- package/dist/config.js.map +1 -0
- package/dist/create-template-project.d.ts +1 -0
- package/dist/create-template-project.js +107 -0
- package/dist/create-template-project.js.map +1 -0
- package/dist/credentials.d.ts +4 -0
- package/dist/credentials.js +38 -0
- package/dist/credentials.js.map +1 -0
- package/dist/dev-process-manager.d.ts +10 -0
- package/dist/dev-process-manager.js +54 -0
- package/dist/dev-process-manager.js.map +1 -0
- package/dist/fingerprint.d.ts +1 -0
- package/dist/fingerprint.js +48 -0
- package/dist/fingerprint.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +117 -0
- package/dist/index.js.map +1 -0
- package/dist/menu.d.ts +3 -0
- package/dist/menu.js +126 -0
- package/dist/menu.js.map +1 -0
- package/dist/project-files.d.ts +114 -0
- package/dist/project-files.js +513 -0
- package/dist/project-files.js.map +1 -0
- package/dist/startup-process-handler.d.ts +2 -0
- package/dist/startup-process-handler.js +21 -0
- package/dist/startup-process-handler.js.map +1 -0
- package/dist/tool-handlers.d.ts +28 -0
- package/dist/tool-handlers.js +240 -0
- package/dist/tool-handlers.js.map +1 -0
- package/dist/types.d.ts +15 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/dist/update-codebuff.d.ts +1 -0
- package/dist/update-codebuff.js +160 -0
- package/dist/update-codebuff.js.map +1 -0
- package/dist/utils/__tests__/background-process-manager.test.d.ts +1 -0
- package/dist/utils/__tests__/background-process-manager.test.js +289 -0
- package/dist/utils/__tests__/background-process-manager.test.js.map +1 -0
- package/dist/utils/__tests__/tool-renderers.test.d.ts +1 -0
- package/dist/utils/__tests__/tool-renderers.test.js +51 -0
- package/dist/utils/__tests__/tool-renderers.test.js.map +1 -0
- package/dist/utils/__tests__/xml-stream-parser.test.d.ts +1 -0
- package/dist/utils/__tests__/xml-stream-parser.test.js +229 -0
- package/dist/utils/__tests__/xml-stream-parser.test.js.map +1 -0
- package/dist/utils/analytics.d.ts +6 -0
- package/dist/utils/analytics.js +59 -0
- package/dist/utils/analytics.js.map +1 -0
- package/dist/utils/detect-shell.d.ts +1 -0
- package/dist/utils/detect-shell.js +60 -0
- package/dist/utils/detect-shell.js.map +1 -0
- package/dist/utils/logger.d.ts +21 -0
- package/dist/utils/logger.js +105 -0
- package/dist/utils/logger.js.map +1 -0
- package/dist/utils/spinner.d.ts +11 -0
- package/dist/utils/spinner.js +87 -0
- package/dist/utils/spinner.js.map +1 -0
- package/dist/utils/system-info.d.ts +8 -0
- package/dist/utils/system-info.js +22 -0
- package/dist/utils/system-info.js.map +1 -0
- package/dist/utils/terminal.d.ts +41 -0
- package/dist/utils/terminal.js +467 -0
- package/dist/utils/terminal.js.map +1 -0
- package/dist/utils/tool-renderers.d.ts +16 -0
- package/dist/utils/tool-renderers.js +148 -0
- package/dist/utils/tool-renderers.js.map +1 -0
- package/dist/utils/xml-stream-parser.d.ts +9 -0
- package/dist/utils/xml-stream-parser.js +128 -0
- package/dist/utils/xml-stream-parser.js.map +1 -0
- package/dist/web-scraper.d.ts +3 -0
- package/dist/web-scraper.js +57 -0
- package/dist/web-scraper.js.map +1 -0
- package/dist/workers/checkpoint-worker.d.ts +1 -0
- package/dist/workers/checkpoint-worker.js +48 -0
- package/dist/workers/checkpoint-worker.js.map +1 -0
- package/dist/workers/project-context.d.ts +1 -0
- package/dist/workers/project-context.js +17 -0
- package/dist/workers/project-context.js.map +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1,680 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
+
if (mod && mod.__esModule) return mod;
|
|
20
|
+
var result = {};
|
|
21
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
22
|
+
__setModuleDefault(result, mod);
|
|
23
|
+
return result;
|
|
24
|
+
};
|
|
25
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
26
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
27
|
+
};
|
|
28
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
29
|
+
exports.activeBrowserRunner = exports.handleBrowserInstruction = exports.BrowserRunner = void 0;
|
|
30
|
+
const puppeteer_core_1 = __importDefault(require("puppeteer-core"));
|
|
31
|
+
const promise_1 = require("./common/util/promise");
|
|
32
|
+
const string_1 = require("./common/util/string");
|
|
33
|
+
const browser_actions_1 = require("./common/browser-actions");
|
|
34
|
+
const fs = __importStar(require("fs"));
|
|
35
|
+
const path = __importStar(require("path"));
|
|
36
|
+
const project_files_1 = require("./project-files");
|
|
37
|
+
const file_1 = require("./common/util/file");
|
|
38
|
+
class BrowserRunner {
|
|
39
|
+
// Add getter methods for diagnostic loop
|
|
40
|
+
getLogs() {
|
|
41
|
+
return this.logs;
|
|
42
|
+
}
|
|
43
|
+
getNetworkEvents() {
|
|
44
|
+
return this.networkEvents;
|
|
45
|
+
}
|
|
46
|
+
browser = null;
|
|
47
|
+
page = null;
|
|
48
|
+
logs = [];
|
|
49
|
+
jsErrorCount = 0;
|
|
50
|
+
retryCount = 0;
|
|
51
|
+
startTime = 0;
|
|
52
|
+
// Error tracking
|
|
53
|
+
consecutiveErrors = 0;
|
|
54
|
+
totalErrors = 0;
|
|
55
|
+
constructor() { }
|
|
56
|
+
// Error tracking configuration
|
|
57
|
+
maxConsecutiveErrors = 3;
|
|
58
|
+
totalErrorThreshold = 10;
|
|
59
|
+
performanceMetrics = {};
|
|
60
|
+
networkEvents = [];
|
|
61
|
+
async executeWithRetry(action) {
|
|
62
|
+
const retryOptions = action.retryOptions ?? browser_actions_1.BROWSER_DEFAULTS.retryOptions;
|
|
63
|
+
let lastError = null;
|
|
64
|
+
for (let attempt = 0; attempt <= (retryOptions.maxRetries ?? 3); attempt++) {
|
|
65
|
+
try {
|
|
66
|
+
const result = await this.executeAction(action);
|
|
67
|
+
// Reset consecutive errors on success
|
|
68
|
+
this.consecutiveErrors = 0;
|
|
69
|
+
return result;
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
// Track errors
|
|
73
|
+
this.consecutiveErrors++;
|
|
74
|
+
this.totalErrors++;
|
|
75
|
+
// Log error analysis
|
|
76
|
+
this.logErrorForAnalysis(error);
|
|
77
|
+
// Check error thresholds
|
|
78
|
+
if (this.consecutiveErrors >= this.maxConsecutiveErrors) {
|
|
79
|
+
const msg = `Max consecutive errors reached (${this.maxConsecutiveErrors}).`;
|
|
80
|
+
this.logs.push({
|
|
81
|
+
type: 'error',
|
|
82
|
+
message: msg,
|
|
83
|
+
timestamp: Date.now(),
|
|
84
|
+
source: 'tool',
|
|
85
|
+
});
|
|
86
|
+
await this.shutdown();
|
|
87
|
+
return {
|
|
88
|
+
success: false,
|
|
89
|
+
error: msg,
|
|
90
|
+
logs: this.logs,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
if (this.totalErrors >= this.totalErrorThreshold) {
|
|
94
|
+
const msg = `Total error threshold reached (${this.totalErrorThreshold}).`;
|
|
95
|
+
this.logs.push({
|
|
96
|
+
type: 'error',
|
|
97
|
+
message: msg,
|
|
98
|
+
timestamp: Date.now(),
|
|
99
|
+
source: 'tool',
|
|
100
|
+
});
|
|
101
|
+
await this.shutdown();
|
|
102
|
+
return {
|
|
103
|
+
success: false,
|
|
104
|
+
error: msg,
|
|
105
|
+
logs: this.logs,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
lastError = error;
|
|
109
|
+
const shouldRetry = retryOptions.retryOnErrors?.includes(error.name);
|
|
110
|
+
if (!shouldRetry || attempt === retryOptions.maxRetries) {
|
|
111
|
+
throw error;
|
|
112
|
+
}
|
|
113
|
+
await new Promise((resolve) => setTimeout(resolve, retryOptions.retryDelay ?? 1000));
|
|
114
|
+
this.logs.push({
|
|
115
|
+
type: 'info',
|
|
116
|
+
message: `Retrying action (attempt ${attempt + 1}/${retryOptions.maxRetries})`,
|
|
117
|
+
timestamp: Date.now(),
|
|
118
|
+
category: 'retry',
|
|
119
|
+
source: 'tool',
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
throw lastError;
|
|
124
|
+
}
|
|
125
|
+
async executeAction(action) {
|
|
126
|
+
try {
|
|
127
|
+
// Only take pre-action screenshot if browser is already running
|
|
128
|
+
let preActionResult = null;
|
|
129
|
+
if (this.browser && this.page) {
|
|
130
|
+
// preActionResult = await this.takeScreenshot(
|
|
131
|
+
// {
|
|
132
|
+
// type: 'screenshot',
|
|
133
|
+
// },
|
|
134
|
+
// this.page
|
|
135
|
+
// )
|
|
136
|
+
}
|
|
137
|
+
let response;
|
|
138
|
+
switch (action.type) {
|
|
139
|
+
case 'start':
|
|
140
|
+
await this.getBrowser(action);
|
|
141
|
+
if (!action.url) {
|
|
142
|
+
break;
|
|
143
|
+
}
|
|
144
|
+
case 'navigate':
|
|
145
|
+
response = await this.navigate({ ...action, type: 'navigate' });
|
|
146
|
+
break;
|
|
147
|
+
case 'click':
|
|
148
|
+
console.log('Clicking has not been implemented yet');
|
|
149
|
+
break;
|
|
150
|
+
case 'type':
|
|
151
|
+
await this.typeText(action);
|
|
152
|
+
break;
|
|
153
|
+
case 'scroll':
|
|
154
|
+
await this.scroll(action);
|
|
155
|
+
break;
|
|
156
|
+
case 'screenshot':
|
|
157
|
+
break;
|
|
158
|
+
case 'stop':
|
|
159
|
+
await this.shutdown();
|
|
160
|
+
return {
|
|
161
|
+
success: true,
|
|
162
|
+
logs: this.logs,
|
|
163
|
+
metrics: await this.collectMetrics(),
|
|
164
|
+
};
|
|
165
|
+
default:
|
|
166
|
+
throw new Error(`Unknown action type: ${action.type}`);
|
|
167
|
+
}
|
|
168
|
+
// Take post-action screenshot
|
|
169
|
+
let postActionResult = null;
|
|
170
|
+
if (this.page) {
|
|
171
|
+
// postActionResult = await this.takeScreenshot(
|
|
172
|
+
// {
|
|
173
|
+
// type: 'screenshot',
|
|
174
|
+
// },
|
|
175
|
+
// this.page
|
|
176
|
+
// )
|
|
177
|
+
}
|
|
178
|
+
const metrics = await this.collectMetrics();
|
|
179
|
+
response = {
|
|
180
|
+
success: true,
|
|
181
|
+
logs: this.logs,
|
|
182
|
+
metrics,
|
|
183
|
+
// ...(postActionResult && {
|
|
184
|
+
// screenshots: {
|
|
185
|
+
// ...(preActionResult && {
|
|
186
|
+
// pre: {
|
|
187
|
+
// type: 'image',
|
|
188
|
+
// source: {
|
|
189
|
+
// type: 'base64',
|
|
190
|
+
// media_type: 'image/jpeg',
|
|
191
|
+
// data: preActionResult.data,
|
|
192
|
+
// },
|
|
193
|
+
// },
|
|
194
|
+
// }),
|
|
195
|
+
// post: {
|
|
196
|
+
// type: 'image',
|
|
197
|
+
// source: {
|
|
198
|
+
// type: 'base64',
|
|
199
|
+
// media_type: 'image/jpeg',
|
|
200
|
+
// data: postActionResult.data,
|
|
201
|
+
// },
|
|
202
|
+
// },
|
|
203
|
+
// },
|
|
204
|
+
// }),
|
|
205
|
+
};
|
|
206
|
+
return response;
|
|
207
|
+
}
|
|
208
|
+
catch (err) {
|
|
209
|
+
await this.shutdown();
|
|
210
|
+
return {
|
|
211
|
+
success: false,
|
|
212
|
+
error: err?.message ?? String(err),
|
|
213
|
+
logs: this.logs,
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
logErrorForAnalysis(error) {
|
|
218
|
+
// Add helpful hints based on error patterns
|
|
219
|
+
const errorPatterns = {
|
|
220
|
+
'not defined': 'Check for missing script dependencies or undefined variables',
|
|
221
|
+
'Failed to fetch': 'Verify endpoint URLs and network connectivity',
|
|
222
|
+
'404': 'Resource not found - verify URLs and paths',
|
|
223
|
+
SSL: 'SSL certificate error - check HTTPS configuration',
|
|
224
|
+
ERR_NAME_NOT_RESOLVED: 'DNS resolution failed - check domain name',
|
|
225
|
+
ERR_CONNECTION_TIMED_OUT: 'Connection timeout - check network or firewall',
|
|
226
|
+
ERR_NETWORK_CHANGED: 'Network changed during request - retry operation',
|
|
227
|
+
ERR_INTERNET_DISCONNECTED: 'No internet connection',
|
|
228
|
+
'Navigation timeout': 'Page took too long to load - check performance or timeouts',
|
|
229
|
+
WebSocket: 'WebSocket connection issue - check server status',
|
|
230
|
+
ERR_TUNNEL_CONNECTION_FAILED: 'Proxy or VPN connection issue',
|
|
231
|
+
ERR_CERT_: 'SSL/TLS certificate validation error',
|
|
232
|
+
ERR_BLOCKED_BY_CLIENT: 'Request blocked by browser extension or policy',
|
|
233
|
+
ERR_TOO_MANY_REDIRECTS: 'Redirect loop detected',
|
|
234
|
+
'Frame detached': 'Target frame or element no longer exists',
|
|
235
|
+
'Node is detached': 'Element was removed from DOM',
|
|
236
|
+
ERR_ABORTED: 'Request was aborted - possible navigation or reload',
|
|
237
|
+
ERR_CONTENT_LENGTH_MISMATCH: 'Incomplete response - check server stability',
|
|
238
|
+
ERR_RESPONSE_HEADERS_TRUNCATED: 'Response headers too large or malformed',
|
|
239
|
+
};
|
|
240
|
+
for (const [pattern, hint] of Object.entries(errorPatterns)) {
|
|
241
|
+
if (error.message.includes(pattern)) {
|
|
242
|
+
this.logs.push({
|
|
243
|
+
type: 'info',
|
|
244
|
+
message: `Hint: ${hint}`,
|
|
245
|
+
timestamp: Date.now(),
|
|
246
|
+
category: 'hint',
|
|
247
|
+
source: 'tool',
|
|
248
|
+
});
|
|
249
|
+
break; // Stop after first matching pattern
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
this.logs.push({
|
|
253
|
+
type: 'error',
|
|
254
|
+
message: `Action error: ${error.message}`,
|
|
255
|
+
timestamp: Date.now(),
|
|
256
|
+
stack: error.stack,
|
|
257
|
+
source: 'tool',
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
async getBrowser(config) {
|
|
261
|
+
// Check if browser exists and is connected
|
|
262
|
+
if (!this.browser || !this.page) {
|
|
263
|
+
await this.startBrowser(config);
|
|
264
|
+
}
|
|
265
|
+
else {
|
|
266
|
+
try {
|
|
267
|
+
// Test if browser is still responsive
|
|
268
|
+
await this.page.evaluate(() => true);
|
|
269
|
+
}
|
|
270
|
+
catch (error) {
|
|
271
|
+
// Browser is dead or unresponsive, restart it
|
|
272
|
+
await this.shutdown();
|
|
273
|
+
await this.startBrowser(config);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
if (!this.browser || !this.page) {
|
|
277
|
+
throw new Error('Failed to initialize browser');
|
|
278
|
+
}
|
|
279
|
+
return { browser: this.browser, page: this.page };
|
|
280
|
+
}
|
|
281
|
+
async startBrowser(config) {
|
|
282
|
+
if (this.browser) {
|
|
283
|
+
await this.shutdown();
|
|
284
|
+
}
|
|
285
|
+
// Set start time for session tracking
|
|
286
|
+
this.startTime = Date.now();
|
|
287
|
+
// Update session configuration
|
|
288
|
+
this.maxConsecutiveErrors =
|
|
289
|
+
config?.maxConsecutiveErrors ?? browser_actions_1.BROWSER_DEFAULTS.maxConsecutiveErrors;
|
|
290
|
+
this.totalErrorThreshold =
|
|
291
|
+
config?.totalErrorThreshold ?? browser_actions_1.BROWSER_DEFAULTS.totalErrorThreshold;
|
|
292
|
+
// Reset error counters
|
|
293
|
+
this.consecutiveErrors = 0;
|
|
294
|
+
this.totalErrors = 0;
|
|
295
|
+
// Set up user data directory for profile persistence, scoped to current project
|
|
296
|
+
let userDataDir = undefined;
|
|
297
|
+
try {
|
|
298
|
+
userDataDir = path.join((0, project_files_1.getProjectDataDir)(), browser_actions_1.BROWSER_DEFAULTS.userDataDir);
|
|
299
|
+
(0, file_1.ensureDirectoryExists)(userDataDir);
|
|
300
|
+
}
|
|
301
|
+
catch (error) { }
|
|
302
|
+
try {
|
|
303
|
+
// Define helper to find Chrome in standard locations
|
|
304
|
+
const findChrome = () => {
|
|
305
|
+
switch (process.platform) {
|
|
306
|
+
case 'win32':
|
|
307
|
+
return 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe';
|
|
308
|
+
case 'darwin':
|
|
309
|
+
return '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
|
|
310
|
+
default:
|
|
311
|
+
return '/usr/bin/google-chrome';
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
this.browser = await puppeteer_core_1.default.launch({
|
|
315
|
+
defaultViewport: {
|
|
316
|
+
width: browser_actions_1.BROWSER_DEFAULTS.viewportWidth,
|
|
317
|
+
height: browser_actions_1.BROWSER_DEFAULTS.viewportHeight,
|
|
318
|
+
},
|
|
319
|
+
headless: browser_actions_1.BROWSER_DEFAULTS.headless,
|
|
320
|
+
userDataDir,
|
|
321
|
+
waitForInitialPage: true,
|
|
322
|
+
args: [
|
|
323
|
+
'--window-size=1200,800',
|
|
324
|
+
'--disable-backgrounding-occluded-windows',
|
|
325
|
+
'--disable-breakpad',
|
|
326
|
+
'--disable-sync',
|
|
327
|
+
'--no-sandbox',
|
|
328
|
+
'--no-first-run',
|
|
329
|
+
'--disable-session-crashed-bubble',
|
|
330
|
+
'--disable-restore-session-state',
|
|
331
|
+
'--hide-crash-restore-bubble',
|
|
332
|
+
'--noerrdialogs',
|
|
333
|
+
'--disable-infobars',
|
|
334
|
+
],
|
|
335
|
+
executablePath: findChrome(),
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
catch (error) {
|
|
339
|
+
// If launch fails, guide the user to install Google Chrome
|
|
340
|
+
console.log("Couldn't launch Chrome browser. Please ensure Google Chrome is installed on your system.");
|
|
341
|
+
return {
|
|
342
|
+
success: false,
|
|
343
|
+
error: 'Chrome browser not found. Please install Google Chrome to use browser features.',
|
|
344
|
+
logs: this.logs,
|
|
345
|
+
networkEvents: this.networkEvents,
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
// this.logs.push({
|
|
349
|
+
// type: 'info',
|
|
350
|
+
// message: 'Browser started',
|
|
351
|
+
// timestamp: Date.now(),
|
|
352
|
+
// source: 'tool',
|
|
353
|
+
// })
|
|
354
|
+
// Pick the first existing page or create a new one
|
|
355
|
+
const pages = await this.browser.pages();
|
|
356
|
+
this.page = pages.length > 0 ? pages[0] : await this.browser.newPage();
|
|
357
|
+
this.attachPageListeners();
|
|
358
|
+
await (0, promise_1.sleep)(500);
|
|
359
|
+
return {
|
|
360
|
+
success: true,
|
|
361
|
+
logs: this.logs,
|
|
362
|
+
networkEvents: [],
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
async navigate(action) {
|
|
366
|
+
try {
|
|
367
|
+
const { page } = await this.getBrowser(action);
|
|
368
|
+
const url = (0, string_1.ensureUrlProtocol)(action.url);
|
|
369
|
+
await page.goto(url, {
|
|
370
|
+
waitUntil: action.waitUntil ?? browser_actions_1.BROWSER_DEFAULTS.waitUntil,
|
|
371
|
+
timeout: action.timeout ?? browser_actions_1.BROWSER_DEFAULTS.timeout,
|
|
372
|
+
});
|
|
373
|
+
this.logs.push({
|
|
374
|
+
type: 'info',
|
|
375
|
+
message: `Navigated to ${url}`,
|
|
376
|
+
timestamp: Date.now(),
|
|
377
|
+
source: 'tool',
|
|
378
|
+
});
|
|
379
|
+
return {
|
|
380
|
+
success: true,
|
|
381
|
+
logs: this.logs,
|
|
382
|
+
networkEvents: [],
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
catch (error) {
|
|
386
|
+
const errorMessage = error?.message || 'Unknown navigation error';
|
|
387
|
+
this.logs.push({
|
|
388
|
+
type: 'error',
|
|
389
|
+
message: `Navigation failed: ${errorMessage}`,
|
|
390
|
+
timestamp: Date.now(),
|
|
391
|
+
source: 'tool',
|
|
392
|
+
});
|
|
393
|
+
return {
|
|
394
|
+
success: false,
|
|
395
|
+
error: errorMessage,
|
|
396
|
+
logs: this.logs,
|
|
397
|
+
networkEvents: [],
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
async typeText(action) {
|
|
402
|
+
const { page } = await this.getBrowser();
|
|
403
|
+
await page.type(action.selector, action.text, {
|
|
404
|
+
delay: action.delay ?? browser_actions_1.BROWSER_DEFAULTS.delay,
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
async scroll(action) {
|
|
408
|
+
const { page } = await this.getBrowser();
|
|
409
|
+
// Get viewport height
|
|
410
|
+
const viewport = page.viewport();
|
|
411
|
+
if (!viewport)
|
|
412
|
+
throw new Error('No viewport found');
|
|
413
|
+
// Default to scrolling down if no direction specified
|
|
414
|
+
const direction = action.direction ?? 'down';
|
|
415
|
+
const scrollAmount = direction === 'up' ? -viewport.height : viewport.height;
|
|
416
|
+
await page.evaluate((amount) => {
|
|
417
|
+
window.scrollBy(0, amount);
|
|
418
|
+
}, scrollAmount);
|
|
419
|
+
this.logs.push({
|
|
420
|
+
type: 'info',
|
|
421
|
+
message: `Scrolled ${direction}`,
|
|
422
|
+
timestamp: Date.now(),
|
|
423
|
+
source: 'tool',
|
|
424
|
+
});
|
|
425
|
+
return {
|
|
426
|
+
success: true,
|
|
427
|
+
logs: this.logs,
|
|
428
|
+
networkEvents: [],
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
async takeScreenshot(action, page) {
|
|
432
|
+
// Take a screenshot with aggressive compression settings
|
|
433
|
+
const screenshot = await page.screenshot({
|
|
434
|
+
fullPage: browser_actions_1.BROWSER_DEFAULTS.fullPage,
|
|
435
|
+
type: 'jpeg',
|
|
436
|
+
quality: action.screenshotCompressionQuality ??
|
|
437
|
+
browser_actions_1.BROWSER_DEFAULTS.screenshotCompressionQuality,
|
|
438
|
+
encoding: 'base64',
|
|
439
|
+
});
|
|
440
|
+
// Log screenshot capture and size
|
|
441
|
+
const sizeInKB = Math.round((screenshot.length * 3) / 4 / 1024);
|
|
442
|
+
this.logs.push({
|
|
443
|
+
type: 'info',
|
|
444
|
+
message: `Captured screenshot (${sizeInKB}KB)`,
|
|
445
|
+
timestamp: Date.now(),
|
|
446
|
+
category: 'screenshot',
|
|
447
|
+
source: 'tool',
|
|
448
|
+
});
|
|
449
|
+
// If debug mode is enabled, save the screenshot
|
|
450
|
+
if (action.debug) {
|
|
451
|
+
console.debug({
|
|
452
|
+
message: 'Saving screenshot to disk...',
|
|
453
|
+
timestamp: Date.now(),
|
|
454
|
+
source: 'tool',
|
|
455
|
+
});
|
|
456
|
+
try {
|
|
457
|
+
const chatDir = (0, project_files_1.getCurrentChatDir)();
|
|
458
|
+
const screenshotsDir = path.join(chatDir, 'screenshots');
|
|
459
|
+
(0, file_1.ensureDirectoryExists)(screenshotsDir);
|
|
460
|
+
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
461
|
+
const filename = `screenshot-${timestamp}.jpg`;
|
|
462
|
+
const filepath = path.join(screenshotsDir, filename);
|
|
463
|
+
fs.writeFileSync(filepath, Buffer.from(screenshot, 'base64'));
|
|
464
|
+
console.debug({
|
|
465
|
+
type: 'debug',
|
|
466
|
+
message: `Saved screenshot to ${filepath}`,
|
|
467
|
+
timestamp: Date.now(),
|
|
468
|
+
source: 'tool',
|
|
469
|
+
});
|
|
470
|
+
// Save metadata
|
|
471
|
+
const metadataPath = path.join(screenshotsDir, `${timestamp}-metadata.json`);
|
|
472
|
+
const metadata = {
|
|
473
|
+
timestamp,
|
|
474
|
+
format: 'jpeg',
|
|
475
|
+
quality: 25,
|
|
476
|
+
fullPage: action.fullPage ?? browser_actions_1.BROWSER_DEFAULTS.fullPage,
|
|
477
|
+
metrics: await this.collectMetrics(),
|
|
478
|
+
};
|
|
479
|
+
fs.writeFileSync(metadataPath, JSON.stringify(metadata, null, 2));
|
|
480
|
+
}
|
|
481
|
+
catch (error) {
|
|
482
|
+
console.error({
|
|
483
|
+
message: `Failed to save screenshot: ${error.message}`,
|
|
484
|
+
timestamp: Date.now(),
|
|
485
|
+
source: 'tool',
|
|
486
|
+
});
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
return {
|
|
490
|
+
data: screenshot,
|
|
491
|
+
logs: this.logs,
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
attachPageListeners() {
|
|
495
|
+
if (!this.page)
|
|
496
|
+
return;
|
|
497
|
+
// Console messages
|
|
498
|
+
this.page.on('console', (msg) => {
|
|
499
|
+
const type = msg.type() === 'error' ? 'error' : msg.type();
|
|
500
|
+
this.logs.push({
|
|
501
|
+
type,
|
|
502
|
+
message: msg.text(),
|
|
503
|
+
timestamp: Date.now(),
|
|
504
|
+
source: 'browser',
|
|
505
|
+
});
|
|
506
|
+
});
|
|
507
|
+
// Page errors
|
|
508
|
+
this.page.on('pageerror', (err) => {
|
|
509
|
+
this.logs.push({
|
|
510
|
+
type: 'error',
|
|
511
|
+
message: err.message,
|
|
512
|
+
timestamp: Date.now(),
|
|
513
|
+
stack: err.stack,
|
|
514
|
+
source: 'browser',
|
|
515
|
+
});
|
|
516
|
+
this.jsErrorCount++;
|
|
517
|
+
});
|
|
518
|
+
// Network requests
|
|
519
|
+
this.page.on('request', (request) => {
|
|
520
|
+
const method = request.method();
|
|
521
|
+
if (method) {
|
|
522
|
+
this.networkEvents.push({
|
|
523
|
+
url: request.url(),
|
|
524
|
+
method,
|
|
525
|
+
timestamp: Date.now(),
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
});
|
|
529
|
+
// Network responses
|
|
530
|
+
this.page.on('response', async (response) => {
|
|
531
|
+
const req = response.request();
|
|
532
|
+
const index = this.networkEvents.findIndex((evt) => evt.url === req.url() && evt.method === req.method());
|
|
533
|
+
const status = response.status();
|
|
534
|
+
const errorText = status >= 400 ? await response.text().catch(() => '') : undefined;
|
|
535
|
+
if (index !== -1) {
|
|
536
|
+
this.networkEvents[index].status = status;
|
|
537
|
+
this.networkEvents[index].errorText = errorText;
|
|
538
|
+
}
|
|
539
|
+
else {
|
|
540
|
+
const method = req.method();
|
|
541
|
+
if (method) {
|
|
542
|
+
this.networkEvents.push({
|
|
543
|
+
url: req.url(),
|
|
544
|
+
method,
|
|
545
|
+
status,
|
|
546
|
+
errorText,
|
|
547
|
+
timestamp: Date.now(),
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
// Log network errors
|
|
552
|
+
if (status >= 400) {
|
|
553
|
+
this.logs.push({
|
|
554
|
+
type: 'error',
|
|
555
|
+
message: `Network error ${status} for ${req.url()}`,
|
|
556
|
+
timestamp: Date.now(),
|
|
557
|
+
source: 'tool',
|
|
558
|
+
});
|
|
559
|
+
}
|
|
560
|
+
});
|
|
561
|
+
}
|
|
562
|
+
async collectPerformanceMetrics() {
|
|
563
|
+
if (!this.page)
|
|
564
|
+
return;
|
|
565
|
+
// Collect Web Vitals and other performance metrics
|
|
566
|
+
const metrics = await this.page.evaluate(() => {
|
|
567
|
+
const lcpEntry = performance.getEntriesByType('largest-contentful-paint')[0];
|
|
568
|
+
const navEntry = performance.getEntriesByType('navigation')[0];
|
|
569
|
+
const fcpEntry = performance
|
|
570
|
+
.getEntriesByType('paint')
|
|
571
|
+
.find((entry) => entry.name === 'first-contentful-paint');
|
|
572
|
+
return {
|
|
573
|
+
ttfb: navEntry?.responseStart - navEntry?.requestStart,
|
|
574
|
+
lcp: lcpEntry?.startTime,
|
|
575
|
+
fcp: fcpEntry?.startTime,
|
|
576
|
+
domContentLoaded: navEntry?.domContentLoadedEventEnd - navEntry?.startTime,
|
|
577
|
+
};
|
|
578
|
+
});
|
|
579
|
+
this.performanceMetrics = metrics;
|
|
580
|
+
}
|
|
581
|
+
async collectMetrics() {
|
|
582
|
+
if (!this.page)
|
|
583
|
+
return undefined;
|
|
584
|
+
const perfEntries = JSON.parse(await this.page.evaluate(() => JSON.stringify(performance.getEntriesByType('navigation'))));
|
|
585
|
+
let loadTime = 0;
|
|
586
|
+
if (perfEntries && perfEntries.length > 0) {
|
|
587
|
+
const navTiming = perfEntries[0];
|
|
588
|
+
loadTime = navTiming.loadEventEnd - navTiming.startTime;
|
|
589
|
+
}
|
|
590
|
+
const memoryUsed = await this.page
|
|
591
|
+
.metrics()
|
|
592
|
+
.then((m) => m.JSHeapUsedSize || 0);
|
|
593
|
+
await this.collectPerformanceMetrics();
|
|
594
|
+
return {
|
|
595
|
+
loadTime,
|
|
596
|
+
memoryUsage: memoryUsed,
|
|
597
|
+
jsErrors: this.jsErrorCount,
|
|
598
|
+
networkErrors: this.networkEvents.filter((e) => e.status && e.status >= 400).length,
|
|
599
|
+
ttfb: this.performanceMetrics.ttfb,
|
|
600
|
+
lcp: this.performanceMetrics.lcp,
|
|
601
|
+
fcp: this.performanceMetrics.fcp,
|
|
602
|
+
domContentLoaded: this.performanceMetrics.domContentLoaded,
|
|
603
|
+
sessionDuration: Date.now() - this.startTime,
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
filterLogs(logs, filter) {
|
|
607
|
+
// First deduplicate logs
|
|
608
|
+
const seen = new Set();
|
|
609
|
+
logs = logs.filter((log) => {
|
|
610
|
+
const key = `${log.type}|${log.message}|${log.timestamp}|${log.source}`;
|
|
611
|
+
if (seen.has(key)) {
|
|
612
|
+
return false;
|
|
613
|
+
}
|
|
614
|
+
seen.add(key);
|
|
615
|
+
return true;
|
|
616
|
+
});
|
|
617
|
+
// Then apply any filters
|
|
618
|
+
if (!filter)
|
|
619
|
+
return logs;
|
|
620
|
+
return logs.filter((log) => {
|
|
621
|
+
if (filter.types && !filter.types.includes(log.type))
|
|
622
|
+
return false;
|
|
623
|
+
if (filter.minLevel && log.level && log.level < filter.minLevel)
|
|
624
|
+
return false;
|
|
625
|
+
if (filter.categories &&
|
|
626
|
+
log.category &&
|
|
627
|
+
!filter.categories.includes(log.category))
|
|
628
|
+
return false;
|
|
629
|
+
return true;
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
async execute(action) {
|
|
633
|
+
try {
|
|
634
|
+
const response = await this.executeWithRetry(action);
|
|
635
|
+
// Filter and deduplicate logs
|
|
636
|
+
response.logs = this.filterLogs(response.logs, action.logFilter ?? undefined);
|
|
637
|
+
this.logs = []; // Clear logs after sending them in response
|
|
638
|
+
return response;
|
|
639
|
+
}
|
|
640
|
+
catch (error) {
|
|
641
|
+
if (error.name === 'TargetClosedError' ||
|
|
642
|
+
(error.message && error.message.includes('detached Frame'))) {
|
|
643
|
+
this.logs.push({
|
|
644
|
+
type: 'error',
|
|
645
|
+
message: 'Browser was closed or detached. Starting new session...',
|
|
646
|
+
timestamp: Date.now(),
|
|
647
|
+
category: 'browser',
|
|
648
|
+
source: 'tool',
|
|
649
|
+
});
|
|
650
|
+
await this.shutdown();
|
|
651
|
+
if (action.type !== 'stop') {
|
|
652
|
+
return this.executeWithRetry(action);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
throw error;
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
async shutdown() {
|
|
659
|
+
const browser = this.browser;
|
|
660
|
+
if (browser) {
|
|
661
|
+
// Clear references first to prevent double shutdown
|
|
662
|
+
this.browser = null;
|
|
663
|
+
this.page = null;
|
|
664
|
+
try {
|
|
665
|
+
await browser.close();
|
|
666
|
+
}
|
|
667
|
+
catch (err) {
|
|
668
|
+
console.error('Error closing browser:', err);
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
exports.BrowserRunner = BrowserRunner;
|
|
674
|
+
const handleBrowserInstruction = async (action) => {
|
|
675
|
+
const response = await exports.activeBrowserRunner.execute(action);
|
|
676
|
+
return response;
|
|
677
|
+
};
|
|
678
|
+
exports.handleBrowserInstruction = handleBrowserInstruction;
|
|
679
|
+
exports.activeBrowserRunner = new BrowserRunner();
|
|
680
|
+
//# sourceMappingURL=browser-runner.js.map
|