@glittering0717/ai-browser 2.5.2 → 2.5.6

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/src/main/index.js CHANGED
@@ -3,6 +3,8 @@
3
3
  import { app, BrowserWindow, BrowserView, ipcMain, net, session, dialog, screen, powerMonitor, shell, nativeImage } from 'electron';
4
4
  import path from 'node:path';
5
5
  import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import v8 from 'node:v8';
6
8
  import { fileURLToPath } from 'node:url';
7
9
  import { startWSServer } from './ws_server.js';
8
10
  import { PageManager } from './page_manager.js';
@@ -10,7 +12,7 @@ import { config } from '../shared/config.js';
10
12
  import mediaDoc from '../shared/media_doc.cjs';
11
13
  import { parseWatchdogTargets, isWatchdogEnabled } from '../shared/watchdog.js';
12
14
  import { wrapSetActive } from '../shared/tab_hooks.js';
13
- import { initErrorLog, recordError, markShutdown, getLogPath } from './error_log.js';
15
+ import { initErrorLog, recordError, markShutdown, getLogPath, recordDiag } from './error_log.js';
14
16
  import errorBanner from '../shared/error_banner.cjs';
15
17
  // .cjs 一律默认导入:ESM 从 .cjs 做具名导入依赖 cjs-module-lexer 静态识别,
16
18
  // 而 tests/test_imports.js 只认 ESM `export` 语法,会误报"没有导出它"。全项目约定
@@ -43,6 +45,57 @@ app.setPath('userData', config.userDataDir);
43
45
  const LOG_DIR = path.join(config.userDataDir, 'logs');
44
46
  initErrorLog({ dir: LOG_DIR, meta: { port: config.wsPort, userData: config.userDataDir } });
45
47
 
48
+ // === 运行轨迹记录(只记录,不干预)===
49
+ // 2026-11-08 实测:一个从源码起的实例连跑约 3 天后在主进程 V8 层 SIGABRT
50
+ // (node::OnFatalError → abort),error.jsonl 里只有一条 boot、没有 shutdown。
51
+ // 这种 native fatal 绕过所有 JS 处理器,唯一的证据是 C 层写入 fd 2 的
52
+ // "FATAL ERROR: ..."(由启动器重定向到 logs/stderr.log 捕获,见 scripts/start.cjs)。
53
+ // 这里补另一半:崩之前的运行轨迹 —— 内存 / 堆上限 / 标签数,每 5 分钟一条。
54
+ // 明确**不做阈值判断、不自动重启**:只记录,是否处置交给看日志的人。
55
+ let heartbeatTimer = null;
56
+ function memSnapshot() {
57
+ try {
58
+ const m = process.memoryUsage();
59
+ const mb = (n) => Math.round(n / 1048576);
60
+ const out = {
61
+ rss_mb: mb(m.rss),
62
+ heap_used_mb: mb(m.heapUsed),
63
+ heap_total_mb: mb(m.heapTotal),
64
+ external_mb: mb(m.external),
65
+ arraybuf_mb: mb(m.arrayBuffers),
66
+ };
67
+ try { out.heap_limit_mb = Math.round(v8.getHeapStatistics().heap_size_limit / 1048576); } catch {}
68
+ return out;
69
+ } catch { return {}; }
70
+ }
71
+ function startRuntimeHeartbeat(everyMs = 5 * 60 * 1000) {
72
+ if (heartbeatTimer) return;
73
+ const tick = () => {
74
+ const info = { uptime_s: Math.round(process.uptime()), ...memSnapshot() };
75
+ try {
76
+ if (pageManager) {
77
+ info.tabs = pageManager.tabs && typeof pageManager.tabs.size === 'number' ? pageManager.tabs.size : null;
78
+ info.active_tab = pageManager.activeTab == null ? null : pageManager.activeTab;
79
+ }
80
+ } catch { /* PageManager 正在拆 */ }
81
+ try { recordDiag('heartbeat', info); } catch {}
82
+ };
83
+ tick();
84
+ heartbeatTimer = setInterval(tick, everyMs);
85
+ if (heartbeatTimer.unref) heartbeatTimer.unref();
86
+ }
87
+ // 启动即记一条环境快照:物理内存、堆上限、CPU 数。崩溃报告里只有虚拟内存,
88
+ // 这里回答的是"当时机器还有多少可用内存"这个前提。
89
+ try {
90
+ recordDiag('runtime', {
91
+ phase: 'boot',
92
+ ...memSnapshot(),
93
+ total_mem_mb: Math.round(os.totalmem() / 1048576),
94
+ free_mem_mb: Math.round(os.freemem() / 1048576),
95
+ cpus: os.cpus().length,
96
+ });
97
+ } catch {}
98
+
46
99
  // === 主进程兜底 ===
47
100
  // 注册 uncaughtException 就等于接管 Electron 的默认行为 —— 而那个默认行为正是
48
101
  // "弹一个只有栈的原生框,栈不进任何文件"。用户看到的是「弹了个框说 js 崩溃」,
@@ -685,6 +738,9 @@ function createWindow() {
685
738
  pageManager.renderPath = { gpu: !gpuDisabled, reason: gpuPref === 'off' ? 'env' : (gpuDisabled ? 'fallback' : 'default') };
686
739
  pageManager._preloadPath = path.join(__dirname, '../preload/bridge.cjs');
687
740
 
741
+ // 从这里起才有 pageManager,心跳开始带标签数(第一条在 pageManager 就绪后立刻写)。
742
+ startRuntimeHeartbeat();
743
+
688
744
  // Create first tab.
689
745
  //
690
746
  // 默认页用 baidu.com:国内可达、无登录墙、重定向链短。但注意它**不是**必须的 ——
@@ -843,7 +899,10 @@ function createWindow() {
843
899
  // while the agent works. When the user finally looks at it, they may be
844
900
  // looking at a stale frame. Repainting on show/restore/focus means the view
845
901
  // catches up the moment it becomes visible — no clicking tabs required.
846
- const repaintActive = () => { try { pageManager.repaint(pageManager.activeTab); } catch (e) {} };
902
+ // 档位由 pageManager 的同一个判据给:默认 soft(只 invalidate,不改几何),
903
+ // AI_BROWSER_HOT_REPAINT=hard 时才用 1px 微调。把它无条件写成 hard 试过,
904
+ // 结果是"窗口每回到前台就大一下小一下" —— 判据与代价见 PageManager._hotRepaintHard。
905
+ const repaintActive = () => { try { pageManager.repaint(pageManager.activeTab, pageManager.hotRepaintOpts()); } catch (e) {} };
847
906
  // 拖动窗口边缘时会连发几十个 resize;逐个重绘会抖成幻灯片。150ms 去抖:松手就补一帧。
848
907
  let repaintTimer = null;
849
908
  const repaintActiveSoon = (ms = 150) => {
@@ -1213,15 +1272,20 @@ function updateWindowTitle() {
1213
1272
  function buildNavState() {
1214
1273
  const wc = activeWebContents();
1215
1274
  if (!wc) {
1216
- return { tab: null, url: '', canBack: false, canForward: false, loading: false, status: '', media_doc: null, download: null };
1275
+ return { tab: null, url: '', canBack: false, canForward: false, loading: false, status: '', media_doc: null, download: null, pending_url: null };
1217
1276
  }
1218
1277
  const tab = pageManager.activeTab;
1219
- const url = wc.getURL();
1278
+ // 加载窗口期显示**请求中的地址**,避免地址栏闪回上一页(判据在
1279
+ // PageManager.pendingNavUrl:只在 state='loading' 期间返回,导航一落地就没了)。
1280
+ const pendingUrl = pageManager.pendingNavUrl(tab);
1281
+ const committedUrl = wc.getURL();
1282
+ const url = pendingUrl || committedUrl;
1220
1283
  let media = null;
1221
1284
  try { media = pageManager.mediaDocOf(tab); } catch (_) { media = null; }
1222
1285
  return {
1223
1286
  tab,
1224
1287
  url,
1288
+ pending_url: pendingUrl,
1225
1289
  canBack: wc.navigationHistory ? wc.navigationHistory.canGoBack() : wc.canGoBack(),
1226
1290
  canForward: wc.navigationHistory ? wc.navigationHistory.canGoForward() : wc.canGoForward(),
1227
1291
  loading: wc.isLoading(),
@@ -1484,6 +1548,10 @@ function _finishCleanup() {
1484
1548
  // 收尾行:日志里**没有** shutdown 行,就说明上一次是硬退(崩溃 / 被 kill)——
1485
1549
  // 这是事后判断"到底有没有崩过"最直接的依据。
1486
1550
  try { markShutdown('cleanup'); } catch {}
1551
+ if (heartbeatTimer) {
1552
+ clearInterval(heartbeatTimer);
1553
+ heartbeatTimer = null;
1554
+ }
1487
1555
  if (tabRefreshInterval) {
1488
1556
  clearInterval(tabRefreshInterval);
1489
1557
  tabRefreshInterval = null;
@@ -0,0 +1,37 @@
1
+ // main/mcp_instructions.js — MCP 初始化时交给客户端的那段自我介绍。
2
+ //
3
+ // 为什么单独成文件(2026-11-25):
4
+ //
5
+ // MCP 的 InitializeResult 有一个 `instructions` 字段,客户端会把它拼进 system
6
+ // prompt —— 这是**协议里唯一**能让服务端主动说"我是什么、什么时候该用我"的地方。
7
+ // 此前它是空的,于是 agent 对这个 server 的全部认知只剩一份 17 个
8
+ // `browse_*` 工具清单:名字像通用动词,描述是写给人看的机制说明
9
+ // (data-ai-id、subset、milestone)。实测后果很直接 —— 用户说"用 ai-browser",
10
+ // 新会话里的 agent 不知道那是什么,得被点名 GitHub 仓库才肯去查。
11
+ //
12
+ // 判据不是"描述够不够详细",而是"只拿到工具清单的模型能不能判断该不该用"。
13
+ // 所以这段文字只回答四件事,不重复 schema 里的参数细节:
14
+ // 1. 它是什么(真窗口,不是无头/截图驱动)
15
+ // 2. 什么意图下必须用它,以及为什么要用它而不是别的浏览器工具
16
+ // 3. 最小循环,且把 success 只代表"发出去了"这条硬规矩放在这里
17
+ // 4. 需要人时的正确姿势
18
+ //
19
+ // 成本:这段文字每个会话注入一次(不是每轮),但仍要克制。预算见
20
+ // tests/test_mcp_instructions.js 的 MAX_CHARS,超了 CI 红。
21
+ //
22
+ // 为什么没有做成 MCP prompt / resource:tests/test_invariants.js 把
23
+ // "prompts/resources 三个 list 必须应答空集合"钉成了不变量(目录扫描器会把
24
+ // Method not found 记为健康检查失败),那是刻意保留的,不在这轮改动范围内。
25
+
26
+ export const MCP_INSTRUCTIONS = [
27
+ 'AI Browser is a real, visible browser that you drive on the user\'s behalf.',
28
+ 'Use it whenever a task involves a website: open a page, read what it says, click, fill a form, log in, publish, upload or download, or pull data that sits behind a login.',
29
+ '',
30
+ 'Prefer it over headless or screenshot-driven browser tools when the page needs JS to render, when a session is already logged in, or when the user should be able to watch and take over. The window is a normal app window: the user can click and type in it at any time.',
31
+ '',
32
+ 'Loop: browse_navigate {url} -> browse_get_tree {subset:"interactive"} -> browse_act {action, target:<id from the tree>}. Repeat. success:true means the action was dispatched, not that anything changed - use browse_diff when the outcome matters.',
33
+ '',
34
+ 'Never invent a target id or a password. For login, QR scan, captcha or payment, ask the user to do it in the window and continue once they confirm.',
35
+ '',
36
+ 'If these tools are not registered in this client, the same engine is reachable from a shell: `ai-browser call ui.get_tree \'{"subset":"interactive"}\'`.',
37
+ ].join('\n');
@@ -14,7 +14,9 @@ import { fileURLToPath } from 'node:url';
14
14
  // 启动逻辑与 CLI 共用一份(scripts/ensure_running.cjs)。曾经这里有一份私有实现,
15
15
  // 结果 MCP 能自动拉起浏览器、CLI 不能 —— 同一件事两个行为。
16
16
  import ensureMod from '../../scripts/ensure_running.cjs';
17
+ import skillMod from '../../scripts/skill.cjs';
17
18
  import { MCP_TOOLS } from './mcp_tools.js';
19
+ import { MCP_INSTRUCTIONS } from './mcp_instructions.js';
18
20
  import { actParams, networkParams } from './mcp_args.js';
19
21
  import { evaluateGuardError } from '../shared/guards.js';
20
22
  import { timeoutForTool } from '../shared/tool_timeout.js';
@@ -78,7 +80,12 @@ const server = new Server(
78
80
  // resources/prompts 声明为空能力:协议要求即使一个都没有也要正常应答这两个
79
81
  // list 请求(部分目录扫描器,如 Smithery,会把 "Method not found" 记为健康
80
82
  // 检查失败)。能力清单保留声明,客户端据此知道服务端支持该方法族。
81
- { capabilities: { tools: {}, resources: {}, prompts: {} } }
83
+ //
84
+ // instructions:客户端会把它拼进 system prompt,是协议里唯一能让服务端主动
85
+ // 说"我是什么、什么时候用我"的地方。此前这一位是空的,agent 只看到一份
86
+ // 名字像通用动词的工具清单 —— 用户说"用 ai-browser",新会话根本不知道那是
87
+ // 什么。内容与成本见 ./mcp_instructions.js。
88
+ { capabilities: { tools: {}, resources: {}, prompts: {} }, instructions: MCP_INSTRUCTIONS }
82
89
  );
83
90
 
84
91
  // Tool definitions — curated minimal MCP_TOOLS (see mcp_tools.js). Kept small
@@ -400,6 +407,24 @@ async function main() {
400
407
  // up on first use, inside wsClient's connection-retry loop (via ensureRunning).
401
408
  const listening = await checkPort(ELECTRON_PORT);
402
409
  if (!listening) console.error('[mcp] ai-browser not running — will auto-start on first browse_* call');
410
+
411
+ // 技能漂移提示:package upgrade 不会刷新用户目录里的技能副本,agent 会继续
412
+ // 照着旧说明操作(实测有机器停在 2.1.1 而包已 2.4.1,缺 tabs.md 整节)。
413
+ // 只提示、不自动写盘 —— 启动过程不该有副作用,也可能根本没有写权限。
414
+ try {
415
+ const stale = skillMod.drift();
416
+ if (stale.length) {
417
+ const s = stale[0];
418
+ console.error(
419
+ `[mcp] skills out of date (${s.target}/${s.skill} ${s.from} -> ${VERSION})` +
420
+ (stale.length > 1 ? ` and ${stale.length - 1} more` : '') +
421
+ ' — run `ai-browser skill install` to refresh'
422
+ );
423
+ }
424
+ } catch {
425
+ // 技能目录存在与否绝不能影响 MCP 启动
426
+ }
427
+
403
428
  const transport = new StdioServerTransport();
404
429
  await server.connect(transport);
405
430
  // stderr is for logging only; stdout is the MCP protocol
@@ -11,7 +11,7 @@ export const MCP_TOOLS = [
11
11
  {
12
12
  name: 'browse_navigate',
13
13
  title: 'Navigate tab',
14
- description: 'Navigate your tab to a URL. Returns at the requested milestone (default: DOM ready) — it does not wait for load, which SPAs often never fire.',
14
+ description: 'Use when the user wants to open a page or reach a URL in your tab, before reading or acting. Returns at the milestone (default: DOM ready), not load, which SPAs never fire.',
15
15
  annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },
16
16
  inputSchema: {
17
17
  type: 'object',
@@ -26,7 +26,7 @@ export const MCP_TOOLS = [
26
26
  {
27
27
  name: 'browse_get_tree',
28
28
  title: 'Read semantic tree',
29
- description: 'Return the page semantic tree (roles, labels, actions, bounds). Root adds editors (primary) when 2+ editable.',
29
+ description: 'Use to read the page: every element as a node with role, label, id and its actions. This is how you see the screen and find click targets. subset:"interactive" saves tokens.',
30
30
  annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true },
31
31
  inputSchema: {
32
32
  type: 'object',
@@ -42,7 +42,7 @@ export const MCP_TOOLS = [
42
42
  {
43
43
  name: 'browse_act',
44
44
  title: 'Act on element',
45
- description: 'Act on a data-ai-id element. type appends at caret, setContent replaces all. page_changed:false = dispatched but page unchanged (wrapper).',
45
+ description: 'Use to click, type, fill, select, upload or press keys — the act that does the work. target = an id from browse_get_tree, never visible text. type appends at caret; setContent replaces all.',
46
46
  annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },
47
47
  inputSchema: {
48
48
  type: 'object',
@@ -172,7 +172,7 @@ export const MCP_TOOLS = [
172
172
  {
173
173
  name: 'browse_auth_state',
174
174
  title: 'Check login / auth-wall state',
175
- description: 'Is this tab still logged in, or bounced to a login wall? auth_wall.detected=true means stop debugging and re-authenticate first. logged_in is heuristic; auth_wall is the signal to trust.',
175
+ description: 'Is this tab still logged in, or bounced to a wall? auth_wall.detected=true means stop debugging and re-authenticate first. logged_in is heuristic; auth_wall is the signal.',
176
176
  annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true },
177
177
  inputSchema: {
178
178
  type: 'object',
@@ -184,7 +184,7 @@ export const MCP_TOOLS = [
184
184
  {
185
185
  name: 'browse_screenshot',
186
186
  title: 'Screenshot the viewport',
187
- description: 'Screenshot the viewport (base64). Use FIRST when an action misbehaves: the tree cannot show overlays, canvas, occlusion or glitches. Warns about visible password inputs.',
187
+ description: 'Screenshot the viewport (base64). Use FIRST when an action misbehaves — the tree cannot show overlays, occlusion or glitches. Warns about password inputs.',
188
188
  annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true },
189
189
  inputSchema: {
190
190
  type: 'object',
@@ -203,6 +203,11 @@ export const MCP_TOOLS = [
203
203
  height: { type: 'number' },
204
204
  scale: { type: 'number', description: 'Device scale factor, 0-4. Default 1.' }
205
205
  }
206
+ },
207
+ source: {
208
+ type: 'string',
209
+ enum: ['auto', 'surface', 'cdp'],
210
+ description: 'auto|surface|cdp; receipt echoes source.',
206
211
  }
207
212
  }
208
213
  }
@@ -230,7 +235,7 @@ export const MCP_TOOLS = [
230
235
  {
231
236
  name: 'browse_network',
232
237
  title: 'Inspect network',
233
- description: 'Query captured HTTP requests: list/get/clear/configure. Captures headers and POST bodies; sensitive headers redacted. Each op reads its own group: filters / include / body_offset / configure.',
238
+ description: 'Query captured HTTP requests: list/get/clear/configure. Headers and POST bodies captured; sensitive headers redacted. Each op reads its own group.',
234
239
  annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },
235
240
  inputSchema: {
236
241
  type: 'object',
@@ -289,7 +294,7 @@ export const MCP_TOOLS = [
289
294
  {
290
295
  name: 'browse_canvas',
291
296
  title: 'Read canvas',
292
- description: 'Read <canvas> via captured draw calls (not pixels): list, read texts/regions, configure, or capture a PNG fallback. 2D text comes from fillText, so no OCR; WebGL is opaque.',
297
+ description: 'Read <canvas> from captured draw calls, not pixels: list/read/configure/capture. 2D text comes from fillText, so no OCR; WebGL is opaque.',
293
298
  annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },
294
299
  inputSchema: {
295
300
  type: 'object',
@@ -328,7 +333,7 @@ export const MCP_TOOLS = [
328
333
  {
329
334
  name: 'browse_capabilities',
330
335
  title: 'Probe capabilities',
331
- description: 'Probe how to operate a page: DOM vs canvas, iframes, app objects on window, JSON endpoints, plus a plan. deep=true also probes closure-hidden models (canvas editors that report none).',
336
+ description: 'Probe how to operate a page: DOM vs canvas, iframes, window objects, JSON endpoints, plus a plan. deep=true also probes closure-hidden models.',
332
337
  annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true },
333
338
  inputSchema: {
334
339
  type: 'object',
@@ -355,7 +360,7 @@ export const MCP_TOOLS = [
355
360
  {
356
361
  name: 'browse_downloads',
357
362
  title: 'List downloads',
358
- description: 'List a tab\'s downloads with on-disk paths. Downloads are async: poll this after clicking export/download instead of expecting the path in the click response.',
363
+ description: 'List a tab\'s downloads with on-disk paths. Downloads are async: poll this after clicking export, not in the click response.',
359
364
  annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
360
365
  inputSchema: {
361
366
  type: 'object',
@@ -367,7 +372,7 @@ export const MCP_TOOLS = [
367
372
  {
368
373
  name: 'browse_errors',
369
374
  title: 'Read error log',
370
- description: 'Read the main-process error log: uncaught exceptions, crashes, failed navigations, RPC errors. Each entry includes recent calls as context. Returns the on-disk JSONL path.',
375
+ description: 'Read the main-process error log: uncaught exceptions, crashes, failed navigations, RPC errors. Returns the on-disk JSONL path.',
371
376
  annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false },
372
377
  inputSchema: {
373
378
  type: 'object',