element-map-manager.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. /**
  2. * Element Map Manager. Maintains mappings of interactive page elements and generates dom_simple_map
  3. * for model understanding.
  4. *
  5. * Design:
  6. * 1. elementMap: Complete element information saved locally as JSON.
  7. * 2. simpleMap: Compact representation sent to the model via the message's <browserState> tag.
  8. * 3. Update elementMap after every browser action.
  9. * 4. Cache by URL path using LRU, up to a configurable maximum (default five).
  10. */
  11. import * as fs from 'fs';
  12. import * as path from 'path';
  13. import * as crypto from 'crypto';
  14. import type { InteractiveElement } from './browser-core-contracts.js';
  15. import type { ElementRecord } from './browser-state.js';
  16. import type { SemanticPageTree } from './browser-semantic-tree.js';
  17. import { DOMSerializer, type SerializerConfig } from './dom-serializer.js';
  18. /**
  19. * Simplified element information sent to the model.
  20. * Format: [index]type:text
  21. * Example: [0]btn:Submit [1]lnk:Home [2]txt:Search...
  22. */
  23. export interface SimpleElement {
  24. /** Element index. */
  25. i: number;
  26. /** Element type abbreviation. */
  27. t: string;
  28. /** Truncated element text. */
  29. n: string;
  30. /** Normalized coordinates [x, y]. */
  31. p: [number, number];
  32. }
  33. /**
  34. * Simplified page state sent to the model.
  35. */
  36. export interface SimpleBrowserState {
  37. /** Current URL. */
  38. url: string;
  39. /** Page title. */
  40. title: string;
  41. /** Viewport dimensions [width, height]. */
  42. viewport: [number, number];
  43. /** Scroll position [x, y]. */
  44. scroll: [number, number];
  45. /** Total page height. */
  46. pageHeight: number;
  47. /** Number of interactive elements. */
  48. elementCount: number;
  49. /** Simplified element list, limited to the viewport. */
  50. elements: SimpleElement[];
  51. /** Index of the currently focused element. */
  52. focusedIndex?: number;
  53. }
  54. /**
  55. * Scroll information (following browser-use).
  56. */
  57. export interface ScrollInfo {
  58. /** Current Y scroll position. */
  59. scrollY: number;
  60. /** Current X scroll position. */
  61. scrollX: number;
  62. /** Total page height. */
  63. pageHeight: number;
  64. /** Total page width. */
  65. pageWidth: number;
  66. /** Viewport height. */
  67. viewportHeight: number;
  68. /** Viewport width. */
  69. viewportWidth: number;
  70. /** Number of pages above. */
  71. pagesAbove: number;
  72. /** Number of pages below. */
  73. pagesBelow: number;
  74. /** Vertical scroll percentage. */
  75. scrollPercentY: number;
  76. /** Whether upward scrolling is possible. */
  77. canScrollUp: boolean;
  78. /** Whether downward scrolling is possible. */
  79. canScrollDown: boolean;
  80. }
  81. /**
  82. * Page information.
  83. */
  84. interface PageInfo {
  85. url: string;
  86. title: string;
  87. viewport: { width: number; height: number };
  88. scrollPosition: { x: number; y: number };
  89. pageHeight: number;
  90. pageWidth: number;
  91. focusedElement: string | null;
  92. }
  93. /**
  94. * Cache entry.
  95. */
  96. interface CacheEntry {
  97. urlPath: string;
  98. elements: InteractiveElement[];
  99. semanticTree: SemanticPageTree | null;
  100. pageInfo: PageInfo;
  101. filePath: string;
  102. lastAccess: number;
  103. }
  104. /**
  105. * Element Map manager with LRU caching by URL path.
  106. */
  107. export class ElementMapManager {
  108. /** URL path → cache entry. */
  109. private cache: Map<string, CacheEntry> = new Map();
  110. /** Maximum cache entries. */
  111. private maxCacheSize: number;
  112. /** Cache directory. */
  113. private cacheDir: string | null = null;
  114. /** Currently active URL path. */
  115. private currentUrlPath: string | null = null;
  116. /** Opaque refs for exactly one Browser Core snapshot generation. */
  117. private opaqueRefs = new Map<string, ElementRecord>();
  118. /** Type mapping table. */
  119. private static readonly TYPE_MAP: Record<string, string> = {
  120. button: 'btn',
  121. link: 'lnk',
  122. textbox: 'txt',
  123. searchbox: 'txt',
  124. checkbox: 'chk',
  125. radio: 'rad',
  126. combobox: 'sel',
  127. listbox: 'sel',
  128. menuitem: 'menu',
  129. tab: 'tab',
  130. switch: 'sw',
  131. generic: 'gene',
  132. tabpanel: 'tpnl',
  133. };
  134. constructor(maxCacheSize = 5) {
  135. this.maxCacheSize = maxCacheSize;
  136. }
  137. /**
  138. * Set the cache directory.
  139. */
  140. setCacheDir(dir: string): void {
  141. this.cacheDir = dir;
  142. }
  143. /**
  144. * Get the cache directory.
  145. */
  146. getCacheDir(): string | null {
  147. return this.cacheDir;
  148. }
  149. /**
  150. * Extract the path from a URL for use as a cache key.
  151. * Example: https://example.com/path/to/page?query=1 → example.com/path/to/page
  152. */
  153. private getUrlPath(url: string): string {
  154. try {
  155. const urlObj = new URL(url);
  156. // Use host + pathname as the key, ignoring query and hash.
  157. return `${urlObj.host}${urlObj.pathname}`;
  158. } catch {
  159. // Use the original URL if parsing fails.
  160. return url;
  161. }
  162. }
  163. /**
  164. * Generate a filename from the URL path's hash.
  165. */
  166. private getFileName(urlPath: string): string {
  167. const hash = crypto.createHash('md5').update(urlPath).digest('hex').slice(0, 12);
  168. // Use the domain as a prefix to aid debugging.
  169. const domain = urlPath
  170. .split('/')[0]!
  171. .replace(/[^a-zA-Z0-9]/g, '_')
  172. .slice(0, 20);
  173. return `element-map-${domain}-${hash}.json`;
  174. }
  175. /**
  176. * Update the element map.
  177. * @param elements List of interactive elements.
  178. * @param pageInfo Page information.
  179. * @param semanticTree Semantic understanding tree generated in the same scan as the element list.
  180. */
  181. async update(
  182. elements: InteractiveElement[],
  183. pageInfo: PageInfo,
  184. semanticTree: SemanticPageTree | null = null,
  185. ): Promise<void> {
  186. const urlPath = this.getUrlPath(pageInfo.url);
  187. this.currentUrlPath = urlPath;
  188. // Check for an existing cache entry.
  189. let entry = this.cache.get(urlPath);
  190. if (entry) {
  191. // Update the existing cache entry.
  192. entry.elements = elements;
  193. entry.semanticTree = semanticTree;
  194. entry.pageInfo = pageInfo;
  195. entry.lastAccess = Date.now();
  196. } else {
  197. // Create a new cache entry.
  198. const fileName = this.getFileName(urlPath);
  199. const filePath = this.cacheDir ? path.join(this.cacheDir, fileName) : '';
  200. entry = {
  201. urlPath,
  202. elements,
  203. semanticTree,
  204. pageInfo,
  205. filePath,
  206. lastAccess: Date.now(),
  207. };
  208. // Check whether the cache is full and needs eviction.
  209. if (this.cache.size >= this.maxCacheSize) {
  210. await this.evictLRU();
  211. }
  212. this.cache.set(urlPath, entry);
  213. }
  214. // Save to file.
  215. if (entry.filePath) {
  216. await this.saveToFile(entry);
  217. }
  218. }
  219. /**
  220. * Evict the least recently used (LRU) cache entry.
  221. */
  222. private async evictLRU(): Promise<void> {
  223. let oldestKey: string | null = null;
  224. let oldestTime = Infinity;
  225. for (const [key, entry] of this.cache) {
  226. if (entry.lastAccess < oldestTime) {
  227. oldestTime = entry.lastAccess;
  228. oldestKey = key;
  229. }
  230. }
  231. if (oldestKey) {
  232. const entry = this.cache.get(oldestKey);
  233. // Delete the corresponding file.
  234. if (entry?.filePath) {
  235. try {
  236. await fs.promises.unlink(entry.filePath);
  237. } catch {
  238. // Ignore missing files.
  239. }
  240. }
  241. this.cache.delete(oldestKey);
  242. }
  243. }
  244. /**
  245. * Save the element map to a file.
  246. */
  247. private async saveToFile(entry: CacheEntry): Promise<void> {
  248. if (!entry.filePath) return;
  249. try {
  250. const dir = path.dirname(entry.filePath);
  251. await fs.promises.mkdir(dir, { recursive: true });
  252. const data = {
  253. timestamp: Date.now(),
  254. urlPath: entry.urlPath,
  255. pageInfo: entry.pageInfo,
  256. elements: entry.elements,
  257. };
  258. await fs.promises.writeFile(entry.filePath, JSON.stringify(data, null, 2), 'utf-8');
  259. } catch (error) {
  260. console.error('Failed to save element map:', error);
  261. }
  262. }
  263. /**
  264. * Get the current page's complete element map.
  265. */
  266. getElementMap(): InteractiveElement[] {
  267. if (!this.currentUrlPath) return [];
  268. const entry = this.cache.get(this.currentUrlPath);
  269. return entry?.elements || [];
  270. }
  271. /** Returns the semantic tree captured atomically with the current ElementMap. */
  272. getSemanticPageTree(): SemanticPageTree | null {
  273. if (!this.currentUrlPath) return null;
  274. return this.cache.get(this.currentUrlPath)?.semanticTree ?? null;
  275. }
  276. /**
  277. * Get the element map for a specified URL.
  278. */
  279. getElementMapByUrl(url: string): InteractiveElement[] | null {
  280. const urlPath = this.getUrlPath(url);
  281. const entry = this.cache.get(urlPath);
  282. if (entry) {
  283. // Update access time.
  284. entry.lastAccess = Date.now();
  285. return entry.elements;
  286. }
  287. return null;
  288. }
  289. /**
  290. * Get an element by index.
  291. */
  292. getElementById(index: number): InteractiveElement | null {
  293. const elements = this.getElementMap();
  294. return elements[index] || null;
  295. }
  296. /**
  297. * Get an element by selector.
  298. */
  299. getElementBySelector(selector: string): InteractiveElement | null {
  300. const elements = this.getElementMap();
  301. return elements.find((el) => el.selector === selector) || null;
  302. }
  303. /**
  304. * Get current page information.
  305. */
  306. private getCurrentPageInfo(): PageInfo | null {
  307. if (!this.currentUrlPath) return null;
  308. const entry = this.cache.get(this.currentUrlPath);
  309. return entry?.pageInfo || null;
  310. }
  311. /**
  312. * Generate simplified browser state for the model, using an LLM-friendly format for understanding
  313. * the page and planning the next action.
  314. */
  315. getSimpleBrowserState(): SimpleBrowserState | null {
  316. const pageInfo = this.getCurrentPageInfo();
  317. if (!pageInfo) return null;
  318. const elements = this.getElementMap();
  319. // Return only elements in the viewport.
  320. const viewportElements = elements.filter((el) => el.isInViewport);
  321. // Find the focused element's index.
  322. let focusedIndex: number | undefined;
  323. if (pageInfo.focusedElement) {
  324. const focusedEl = elements.find((el) => el.selector === pageInfo.focusedElement);
  325. if (focusedEl) {
  326. focusedIndex = focusedEl.index;
  327. }
  328. }
  329. return {
  330. url: pageInfo.url,
  331. title: pageInfo.title,
  332. viewport: [pageInfo.viewport.width, pageInfo.viewport.height],
  333. scroll: [pageInfo.scrollPosition.x, pageInfo.scrollPosition.y],
  334. pageHeight: pageInfo.pageHeight,
  335. elementCount: elements.length,
  336. elements: viewportElements.map((el) => ({
  337. i: el.index,
  338. t: ElementMapManager.TYPE_MAP[el.type] || el.type.slice(0, 4),
  339. n: el.text.slice(0, 50),
  340. p: [el.normalizedPosition.x, el.normalizedPosition.y] as [number, number],
  341. })),
  342. focusedIndex,
  343. };
  344. }
  345. /**
  346. * Generate a dom_simple_map string for embedding in messages. Compact JSON contains only what the
  347. * model needs to understand the page and plan actions; details such as exact positions and
  348. * selectors remain in the local elementMap file.
  349. *
  350. * Example output:
  351. * {"u":"https://example.com","t":"Example","v":[1200,800],"s":[0,100],"c":45,"e":[{"i":0,"t":"btn","n":"Submit"},{"i":1,"t":"lnk","n":"Home"}],"m":"/path/to/element-map.json"}
  352. *
  353. * Fields:
  354. * - u: url
  355. * - t: title
  356. * - v: viewport [width, height]
  357. * - s: scroll position [x, y]
  358. * - c: total element count
  359. * - e: visible elements (i: index, t: type, n: name/text)
  360. * - f: focused element index (optional)
  361. * - m: elementMap file path (the model may read this file for details)
  362. */
  363. generateSimpleMapString(): string {
  364. const state = this.getSimpleBrowserState();
  365. if (!state) return '';
  366. // Compact format: retain only the minimum information needed for the model to understand the page.
  367. // Do not send position (p) to the model; it references elements by index (i).
  368. // Look up details in the local elementMap file during execution.
  369. const output: Record<string, unknown> = {
  370. u: state.url,
  371. t: state.title,
  372. v: state.viewport,
  373. s: state.scroll,
  374. c: state.elementCount,
  375. e: state.elements.map((el) => ({
  376. i: el.i,
  377. t: el.t,
  378. n: el.n,
  379. })),
  380. };
  381. if (state.focusedIndex !== undefined) {
  382. output.f = state.focusedIndex;
  383. }
  384. // elementMap file path, available for the model to read selectors, exact positions, and other details.
  385. const filePath = this.getCacheDir();
  386. if (filePath) {
  387. output.m = filePath;
  388. }
  389. return JSON.stringify(output);
  390. }
  391. /**
  392. * Generate <browserState> tag content for embedding in messages sent to the model.
  393. */
  394. generateBrowserStateTag(): string {
  395. const simpleMap = this.generateSimpleMapString();
  396. if (!simpleMap) return '';
  397. return `<browserState>${simpleMap}</browserState>`;
  398. }
  399. /**
  400. * Generate optimized hierarchical text following browser-use. Apply paint-order and bounding-box
  401. * filtering for compact output.
  402. *
  403. * @param config Serialization configuration.
  404. * @returns Browser state in hierarchical text format.
  405. */
  406. generateOptimizedBrowserState(config?: Partial<SerializerConfig>): string {
  407. const pageInfo = this.getCurrentPageInfo();
  408. if (!pageInfo) return '';
  409. const elements = this.getElementMap();
  410. if (elements.length === 0) return '';
  411. const serializer = new DOMSerializer({
  412. outputFormat: 'tree',
  413. ...config,
  414. });
  415. const result = serializer.serialize(elements, pageInfo);
  416. return result.text;
  417. }
  418. /**
  419. * Generate an optimized <browserState> tag using token-efficient hierarchical text, including the
  420. * elementMap file path for the model to read details.
  421. */
  422. generateOptimizedBrowserStateTag(config?: Partial<SerializerConfig>): string {
  423. const text = this.generateOptimizedBrowserState(config);
  424. if (!text) return '';
  425. // Add the elementMap file path.
  426. const filePath = this.getCurrentFilePath();
  427. const mapLine = filePath ? `[Map] ${filePath}` : '';
  428. return `<browserState>\n${text}${mapLine ? '\n' + mapLine : ''}\n</browserState>`;
  429. }
  430. /**
  431. * Get the current elementMap file path.
  432. */
  433. private getCurrentFilePath(): string | null {
  434. if (!this.currentUrlPath) return null;
  435. const entry = this.cache.get(this.currentUrlPath);
  436. return entry?.filePath || null;
  437. }
  438. /**
  439. * Get an element by backendNodeId.
  440. */
  441. getElementByBackendNodeId(backendNodeId: number): InteractiveElement | null {
  442. const elements = this.getElementMap();
  443. return elements.find((el) => el.backendNodeId === backendNodeId) || null;
  444. }
  445. /** Replace the current generation's opaque refs atomically with its ElementMap. */
  446. replaceOpaqueRefs(elements: readonly ElementRecord[]): void {
  447. this.opaqueRefs = new Map(elements.map((element) => [element.ref, element]));
  448. }
  449. /** Resolve only refs produced by the current snapshot generation. */
  450. getElementByOpaqueRef(ref: string): ElementRecord | null {
  451. return this.opaqueRefs.get(ref) ?? null;
  452. }
  453. hasOpaqueRef(ref: string): boolean {
  454. return this.opaqueRefs.has(ref);
  455. }
  456. clearOpaqueRefs(): void {
  457. this.opaqueRefs.clear();
  458. }
  459. /**
  460. * Clear all caches.
  461. */
  462. clear(): void {
  463. // Delete all cache files.
  464. for (const entry of this.cache.values()) {
  465. if (entry.filePath) {
  466. fs.promises.unlink(entry.filePath).catch(() => {
  467. // Ignore deletion errors.
  468. });
  469. }
  470. }
  471. this.cache.clear();
  472. this.currentUrlPath = null;
  473. this.clearOpaqueRefs();
  474. }
  475. /**
  476. * Clear the cache for a specified URL.
  477. */
  478. clearByUrl(url: string): void {
  479. const urlPath = this.getUrlPath(url);
  480. const entry = this.cache.get(urlPath);
  481. if (entry) {
  482. if (entry.filePath) {
  483. fs.promises.unlink(entry.filePath).catch(() => {
  484. // Ignore deletion errors.
  485. });
  486. }
  487. this.cache.delete(urlPath);
  488. if (this.currentUrlPath === urlPath) {
  489. this.currentUrlPath = null;
  490. }
  491. }
  492. }
  493. /**
  494. * Check whether a specified URL has a cache entry.
  495. */
  496. hasCache(url: string): boolean {
  497. const urlPath = this.getUrlPath(url);
  498. return this.cache.has(urlPath);
  499. }
  500. /**
  501. * Check whether an update is needed because the URL changed or no cache exists.
  502. */
  503. needsUpdate(currentUrl: string): boolean {
  504. const urlPath = this.getUrlPath(currentUrl);
  505. return !this.cache.has(urlPath);
  506. }
  507. /**
  508. * Get cache statistics.
  509. */
  510. getCacheStats(): { size: number; maxSize: number; urls: string[] } {
  511. return {
  512. size: this.cache.size,
  513. maxSize: this.maxCacheSize,
  514. urls: Array.from(this.cache.keys()),
  515. };
  516. }
  517. /**
  518. * Set the maximum number of cache entries.
  519. */
  520. setMaxCacheSize(size: number): void {
  521. this.maxCacheSize = size;
  522. // Evict excess entries if the current cache exceeds the new maximum.
  523. while (this.cache.size > this.maxCacheSize) {
  524. this.evictLRU();
  525. }
  526. }
  527. }