File size: 9,569 Bytes
033af1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**

 * Browser Agent - AI-Powered Browser Automation with Vision

 * Uses Qwen VL to see screenshots and decide actions like a human

 */

// Vision Model Configuration
export const VISION_MODEL = 'qwen/qwen-2.5-vl-7b-instruct:free';

// Get OpenRouter API Keys with fallback (same pattern as Vercel)
function getOpenRouterKeys() {
    const keys = [];
    for (let i = 1; i <= 10; i++) {
        const key = process.env[`OPENROUTER_API_KEY_${i}`];
        if (key && key.trim()) keys.push(key.trim());
    }
    // Also check the base key
    if (process.env.OPENROUTER_API_KEY) {
        keys.push(process.env.OPENROUTER_API_KEY.trim());
    }
    return keys;
}

/**

 * Analyze screenshot with Vision AI and decide next action

 */
async function analyzeWithVision(screenshotBase64, task, previousSteps = [], currentUrl = '') {
    const stepHistory = previousSteps.map((s, i) =>
        `Step ${i + 1}: ${s.action.type} - ${s.action.description || ''}`
    ).join('\n');

    const prompt = `You are a browser automation agent. You can see the current webpage screenshot.



TASK: ${task}



CURRENT URL: ${currentUrl}



PREVIOUS STEPS:

${stepHistory || 'None yet'}



Based on what you see in the screenshot, decide the NEXT ACTION to complete the task.



Respond in this exact JSON format:

{

    "observation": "Brief description of what you see on the page",

    "thinking": "Your reasoning about what to do next",

    "action": {

        "type": "click" | "type" | "scroll" | "goto" | "wait" | "done",

        "x": 500,

        "y": 300,

        "text": "text to type if action is type",

        "url": "url if action is goto",

        "direction": "up or down if scroll",

        "description": "human readable description of this action"

    },

    "taskComplete": false,

    "result": "Only fill this if taskComplete is true - the final answer/result"

}



IMPORTANT:

- If you see search results with the information needed, extract it and set taskComplete: true

- For click actions, estimate x,y coordinates based on where you see the element

- If you see a search box, type the search query

- If the page needs to scroll to see more, use scroll action

- Be efficient - don't take unnecessary steps`;

    const keys = getOpenRouterKeys();
    if (keys.length === 0) {
        console.error('[BrowserAgent] No OpenRouter API keys found!');
        return {
            observation: 'No API keys configured',
            thinking: 'Cannot analyze without API keys',
            action: { type: 'wait', description: 'Waiting - no API keys' },
            taskComplete: false
        };
    }

    // Try each key until one works
    for (const apiKey of keys) {
        try {
            const response = await fetch('https://openrouter.ai/api/v1/chat/completions', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${apiKey}`,
                    'Content-Type': 'application/json',
                    'HTTP-Referer': 'https://luks-pied.vercel.app',
                    'X-Title': 'Lukas Browser Agent'
                },
                body: JSON.stringify({
                    model: VISION_MODEL,
                    messages: [{
                        role: 'user',
                        content: [
                            { type: 'text', text: prompt },
                            {
                                type: 'image_url',
                                image_url: {
                                    url: `data:image/png;base64,${screenshotBase64}`
                                }
                            }
                        ]
                    }],
                    max_tokens: 1000
                })
            });

            if (response.status === 429) {
                console.log('[BrowserAgent] Rate limited, trying next key...');
                continue;
            }

            const data = await response.json();

            if (data.choices && data.choices[0]?.message?.content) {
                const content = data.choices[0].message.content;
                // Extract JSON from response (handle markdown code blocks)
                const jsonMatch = content.match(/\{[\s\S]*\}/);
                if (jsonMatch) {
                    return JSON.parse(jsonMatch[0]);
                }
            }

            if (data.error) {
                console.log(`[BrowserAgent] API error: ${data.error.message}, trying next key...`);
                continue;
            }
        } catch (error) {
            console.log(`[BrowserAgent] Key failed: ${error.message}, trying next...`);
            continue;
        }
    }

    console.error('[BrowserAgent] All API keys failed');
    return {
        observation: 'Error analyzing screenshot',
        thinking: 'All API keys failed',
        action: { type: 'wait', description: 'Waiting due to error' },
        taskComplete: false
    };
}

/**

 * Execute a browser action

 */
async function executeAction(page, action) {
    try {
        switch (action.type) {
            case 'click':
                await page.mouse.click(action.x, action.y);
                await page.waitForTimeout(1000);
                break;

            case 'type':
                if (action.x && action.y) {
                    await page.mouse.click(action.x, action.y);
                    await page.waitForTimeout(300);
                }
                await page.keyboard.type(action.text, { delay: 50 });
                await page.keyboard.press('Enter');
                await page.waitForTimeout(2000);
                break;

            case 'scroll':
                const amount = action.direction === 'up' ? -400 : 400;
                await page.mouse.wheel(0, amount);
                await page.waitForTimeout(500);
                break;

            case 'goto':
                await page.goto(action.url, { waitUntil: 'domcontentloaded', timeout: 30000 });
                await page.waitForTimeout(2000);
                break;

            case 'wait':
                await page.waitForTimeout(2000);
                break;

            case 'done':
                // Task is complete, no action needed
                break;

            default:
                console.log('[BrowserAgent] Unknown action:', action.type);
        }
        return true;
    } catch (error) {
        console.error('[BrowserAgent] Action execution error:', error.message);
        return false;
    }
}

/**

 * Run the Browser Agent loop

 */
async function runBrowserAgent(page, task, socket, maxSteps = 10) {
    console.log(`[BrowserAgent] Starting task: "${task}"`);

    const steps = [];
    let taskComplete = false;
    let finalResult = null;

    // Start by going to Google
    await page.goto('https://www.google.com', { waitUntil: 'domcontentloaded' });
    await page.waitForTimeout(1000);

    for (let i = 0; i < maxSteps && !taskComplete; i++) {
        console.log(`[BrowserAgent] Step ${i + 1}/${maxSteps}`);

        // 1. Take screenshot
        const screenshotBuffer = await page.screenshot({ type: 'png' });
        const screenshotBase64 = screenshotBuffer.toString('base64');

        // 2. Get current URL
        const currentUrl = page.url();

        // 3. Analyze with Vision AI
        console.log('[BrowserAgent] Analyzing screenshot with Vision AI...');
        const analysis = await analyzeWithVision(screenshotBase64, task, steps, currentUrl);

        console.log(`[BrowserAgent] Observation: ${analysis.observation}`);
        console.log(`[BrowserAgent] Thinking: ${analysis.thinking}`);
        console.log(`[BrowserAgent] Action: ${analysis.action?.type} - ${analysis.action?.description}`);

        // 4. Record step
        const step = {
            stepNumber: i + 1,
            screenshot: screenshotBase64,
            observation: analysis.observation,
            thinking: analysis.thinking,
            action: analysis.action,
            timestamp: Date.now()
        };
        steps.push(step);

        // 5. Send update to frontend
        if (socket) {
            socket.emit('agent:step', {
                step: i + 1,
                total: maxSteps,
                screenshot: screenshotBase64,
                observation: analysis.observation,
                action: analysis.action?.description || analysis.action?.type,
                taskComplete: analysis.taskComplete
            });
        }

        // 6. Check if task is complete
        if (analysis.taskComplete) {
            taskComplete = true;
            finalResult = analysis.result;
            console.log('[BrowserAgent] Task completed!');
            console.log('[BrowserAgent] Result:', finalResult);
            break;
        }

        // 7. Execute the action
        if (analysis.action && analysis.action.type !== 'done') {
            await executeAction(page, analysis.action);
        }
    }

    // Take final screenshot
    const finalScreenshot = await page.screenshot({ type: 'png' });

    return {
        success: taskComplete,
        steps: steps,
        result: finalResult,
        finalScreenshot: finalScreenshot.toString('base64'),
        totalSteps: steps.length
    };
}

export {
    runBrowserAgent,
    analyzeWithVision,
    executeAction
};