browser-query.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. import {
  2. asNumber,
  3. asString,
  4. byteLength,
  5. evaluate,
  6. getBrowserSnapshot,
  7. isRecord,
  8. type ElementRecord,
  9. type Snapshot,
  10. stringArray,
  11. type BrowserSessionState as SessionState,
  12. } from './browser-state.js';
  13. import { BrowserSnapshotSupport } from './browser-snapshot.js';
  14. import { exposeElement } from './browser-snapshot-helpers.js';
  15. import {
  16. sanitizeConsoleDiagnosticUrl,
  17. type CDPConsoleDiagnosticLevelFilter,
  18. type CDPNetworkDiagnosticResourceType,
  19. type CDPNetworkDiagnosticStatusFilter,
  20. } from './cdp-helper.js';
  21. import { isBrowserOperationInterruption } from './operation-timeout.js';
  22. const NON_EDITABLE_INPUT_TYPES = new Set([
  23. 'button',
  24. 'checkbox',
  25. 'file',
  26. 'hidden',
  27. 'image',
  28. 'radio',
  29. 'reset',
  30. 'submit',
  31. ]);
  32. export abstract class BrowserQuerySupport extends BrowserSnapshotSupport {
  33. protected async query(session: SessionState, input: Record<string, unknown>): Promise<unknown> {
  34. const kind = asString(input.kind);
  35. if (kind === 'snapshot') return this.inspect(session, input);
  36. if (kind === 'semantic') return this.searchSemantic(session, input);
  37. if (kind === 'editable') {
  38. const requestedSnapshotId = asString(input.snapshotId);
  39. if (requestedSnapshotId) {
  40. const snapshot = getBrowserSnapshot(session, requestedSnapshotId);
  41. if (!snapshot) {
  42. throw new Error('STALE_SNAPSHOT: editable query continuation is no longer available');
  43. }
  44. if ((snapshot.continuationKind ?? 'inspect') !== 'query-editable') {
  45. throw new Error(
  46. 'SNAPSHOT_KIND_MISMATCH: continue the snapshot with the action returned by its continuation',
  47. );
  48. }
  49. const current = snapshot.editableQuery;
  50. if (!current) {
  51. throw new Error('STALE_SNAPSHOT: editable query continuation is no longer available');
  52. }
  53. const offset = Math.max(0, Math.floor(asNumber(input.offset, 0)));
  54. if (current.nextOffset === null || offset !== current.nextOffset) {
  55. throw new Error(
  56. 'SNAPSHOT_CONTINUATION_MISMATCH: continue from the exact nextOffset returned by the previous page',
  57. );
  58. }
  59. return editablePage(snapshot, current, offset, input);
  60. }
  61. if (asNumber(input.offset, 0) > 0) {
  62. throw new Error('editable query offset requires snapshotId from a previous query');
  63. }
  64. await this.inspect(session, { limit: 1 }, 'query-editable');
  65. const snapshot = session.snapshot;
  66. if (!snapshot) throw new Error('EDITABLE_QUERY_FAILED: no current Browser snapshot');
  67. const elements = snapshot.elements.filter(isEditableElement);
  68. snapshot.editableQuery = {
  69. elements,
  70. nextOffset: 0,
  71. };
  72. return editablePage(snapshot, snapshot.editableQuery, 0, input);
  73. }
  74. if (kind === 'text') {
  75. const selector = asString(input.selector, 'body');
  76. const maxChars = Math.max(1, Math.floor(asNumber(input.maxChars, 20_000)));
  77. try {
  78. const result = await evaluate<{
  79. found: boolean;
  80. text: string;
  81. totalLength: number;
  82. url: string;
  83. title: string;
  84. }>(
  85. session,
  86. `(() => {
  87. const element = document.querySelector(${JSON.stringify(selector)});
  88. if (!element) return { found: false, text: '', totalLength: 0, url: location.href, title: document.title };
  89. const text = String(element.innerText || element.textContent || '');
  90. return { found: true, text: text.slice(0, ${maxChars}), totalLength: text.length, url: location.href, title: document.title };
  91. })()`,
  92. );
  93. if (!result.found) return selectorNotFound(selector);
  94. const { found: _found, ...content } = result;
  95. return {
  96. success: true,
  97. ...content,
  98. truncated: result.totalLength > result.text.length,
  99. };
  100. } catch (error) {
  101. if (isBrowserOperationInterruption(error)) throw error;
  102. return browserQueryFailure(error);
  103. }
  104. }
  105. if (kind === 'dom') {
  106. const selector = asString(input.selector, 'body');
  107. const maxChars = Math.max(1, Math.min(50_000, Math.floor(asNumber(input.maxChars, 20_000))));
  108. try {
  109. const result = await evaluate<{ found: boolean; html: string }>(
  110. session,
  111. sanitizedDomQueryExpression(selector),
  112. );
  113. if (!result.found) return selectorNotFound(selector);
  114. return {
  115. success: true,
  116. html: result.html.slice(0, maxChars),
  117. truncated: result.html.length > maxChars,
  118. totalLength: result.html.length,
  119. url: await evaluate<string>(session, 'location.href'),
  120. title: await evaluate<string>(session, 'document.title'),
  121. };
  122. } catch (error) {
  123. if (isBrowserOperationInterruption(error)) throw error;
  124. return browserQueryFailure(error);
  125. }
  126. }
  127. if (kind === 'console') {
  128. const diagnosticsReady = await session.cdpHelper.ensureConsoleDiagnosticsReady(
  129. session.commandSignal,
  130. );
  131. if (!diagnosticsReady || !session.cdpHelper.isConsoleDiagnosticsAvailable()) {
  132. return {
  133. success: false,
  134. code: 'CONSOLE_DIAGNOSTICS_UNAVAILABLE',
  135. error: 'Console diagnostics are unavailable for the current Browser tab.',
  136. recovery: 'Keep the current Browser tab open and retry once it finishes initializing.',
  137. };
  138. }
  139. const diagnostics = session.cdpHelper.getConsoleDiagnostics({
  140. ...(input.levels !== undefined
  141. ? {
  142. levels: stringArray(input.levels) as CDPConsoleDiagnosticLevelFilter[],
  143. }
  144. : {}),
  145. ...(input.filter !== undefined ? { filter: asString(input.filter) } : {}),
  146. limit: Math.max(1, Math.min(200, Math.floor(asNumber(input.limit, 100)))),
  147. });
  148. const page = await evaluate<{ url: string; title: string }>(
  149. session,
  150. '({ url: location.href, title: document.title })',
  151. );
  152. return {
  153. success: true,
  154. kind: 'console',
  155. url: sanitizeConsoleDiagnosticUrl(asString(page.url)),
  156. title: asString(page.title),
  157. ...diagnostics,
  158. };
  159. }
  160. if (kind === 'network') {
  161. const diagnosticsReady = await session.cdpHelper.ensureNetworkDiagnosticsReady(
  162. session.commandSignal,
  163. );
  164. if (!diagnosticsReady || !session.cdpHelper.isNetworkDiagnosticsAvailable()) {
  165. return {
  166. success: false,
  167. code: 'NETWORK_DIAGNOSTICS_UNAVAILABLE',
  168. error: 'Network diagnostics are unavailable for the current Browser tab.',
  169. recovery: 'Keep the current Browser tab open and retry once it finishes initializing.',
  170. };
  171. }
  172. const diagnostics = session.cdpHelper.getNetworkDiagnostics({
  173. ...(input.status !== undefined
  174. ? { status: stringArray(input.status) as CDPNetworkDiagnosticStatusFilter[] }
  175. : {}),
  176. ...(input.resourceTypes !== undefined
  177. ? {
  178. resourceTypes: stringArray(input.resourceTypes) as CDPNetworkDiagnosticResourceType[],
  179. }
  180. : {}),
  181. ...(input.filter !== undefined ? { filter: asString(input.filter) } : {}),
  182. ...(input.afterSequence !== undefined
  183. ? { afterSequence: Math.max(0, Math.floor(asNumber(input.afterSequence))) }
  184. : {}),
  185. limit: Math.max(1, Math.min(200, Math.floor(asNumber(input.limit, 100)))),
  186. });
  187. const page = await evaluate<{ url: string; title: string }>(
  188. session,
  189. '({ url: location.href, title: document.title })',
  190. );
  191. return {
  192. success: true,
  193. kind: 'network',
  194. url: sanitizeConsoleDiagnosticUrl(asString(page.url)),
  195. title: asString(page.title),
  196. ...diagnostics,
  197. };
  198. }
  199. throw new Error(
  200. 'query requires kind: text, semantic, dom, editable, snapshot, console, or network',
  201. );
  202. }
  203. }
  204. function sanitizedDomQueryExpression(selector: string): string {
  205. return `(() => {
  206. const source = document.querySelector(${JSON.stringify(selector)});
  207. if (!source || source.closest('[data-mavis-agent-cursor-host]')) return { found: false, html: '' };
  208. const blocked = 'script, noscript, style, link, template, iframe, object, embed, svg defs, svg symbol';
  209. if (source.matches('[data-mavis-agent-cursor-host], ' + blocked)) return { found: true, html: '' };
  210. const clone = source.cloneNode(true);
  211. clone.querySelectorAll('[data-mavis-agent-cursor-host]').forEach((element) => element.remove());
  212. clone.querySelectorAll(blocked).forEach((element) => element.remove());
  213. const walker = document.createTreeWalker(clone, NodeFilter.SHOW_COMMENT);
  214. const comments = [];
  215. while (walker.nextNode()) comments.push(walker.currentNode);
  216. comments.forEach((comment) => comment.remove());
  217. clone.querySelectorAll('[hidden], [aria-hidden="true"], [style*="display: none"], [style*="display:none"], [style*="visibility: hidden"], [style*="visibility:hidden"]').forEach((element) => element.remove());
  218. const keepAttrs = new Set([
  219. 'href', 'src', 'alt', 'title', 'type', 'name', 'id', 'class', 'for',
  220. 'placeholder', 'value', 'checked', 'disabled', 'readonly', 'required',
  221. 'min', 'max', 'pattern', 'maxlength', 'minlength', 'role',
  222. 'aria-label', 'aria-labelledby', 'aria-describedby', 'aria-expanded',
  223. 'aria-selected', 'aria-checked', 'aria-disabled', 'aria-haspopup',
  224. 'aria-controls', 'aria-hidden', 'data-testid', 'data-id', 'data-value',
  225. 'data-name', 'colspan', 'rowspan', 'scope', 'target', 'rel', 'download',
  226. 'action', 'method', 'enctype', 'tabindex', 'contenteditable', 'lang', 'dir'
  227. ]);
  228. clone.querySelectorAll('*').forEach((element) => {
  229. Array.from(element.attributes).forEach((attribute) => {
  230. const name = attribute.name;
  231. if (!keepAttrs.has(name) && !name.startsWith('aria-') && !name.startsWith('data-')) {
  232. element.removeAttribute(name);
  233. }
  234. });
  235. });
  236. return { found: true, html: clone.outerHTML || '' };
  237. })()`;
  238. }
  239. function selectorNotFound(selector: string): Record<string, unknown> {
  240. return {
  241. success: false,
  242. code: 'QUERY_FAILED',
  243. error: `Element not found: ${selector}`,
  244. recovery: 'Inspect the current page and retry with a selector that matches the current DOM.',
  245. };
  246. }
  247. function browserQueryFailure(error: unknown): Record<string, unknown> {
  248. const message = error instanceof Error ? error.message : String(error);
  249. const invalidSelector =
  250. /(?:failed to execute ['"]?queryselector|not a valid selector|invalid selector|selector[^\n]*syntaxerror|syntaxerror[^\n]*selector)/iu.test(
  251. message,
  252. );
  253. return {
  254. success: false,
  255. code: invalidSelector ? 'INVALID_SELECTOR' : 'QUERY_FAILED',
  256. error: message,
  257. recovery: invalidSelector
  258. ? 'Use query with kind: "text" for text matching, or continue inspect and act through a returned opaque ref. CSS selectors must use standard CSS syntax.'
  259. : 'Inspect the current page state and retry the query once; if navigation occurred, continue from the new snapshot.',
  260. };
  261. }
  262. function editablePage(
  263. snapshot: Snapshot,
  264. query: NonNullable<Snapshot['editableQuery']>,
  265. offset: number,
  266. input: Record<string, unknown>,
  267. ): Record<string, unknown> {
  268. const limit = Math.max(1, Math.min(200, Math.floor(asNumber(input.limit, 100))));
  269. const pageElements = query.elements.slice(offset, offset + limit);
  270. const exposed: Record<string, unknown>[] = pageElements.map((element) =>
  271. exposeElement(
  272. element,
  273. snapshot.page.viewport,
  274. snapshot.frameRefs?.get(element.frameId ?? 'main'),
  275. ),
  276. );
  277. let returned = exposed;
  278. while (returned.length > 1 && byteLength({ targets: returned }) > 56 * 1024) {
  279. returned = returned.slice(0, -1);
  280. }
  281. const end = offset + returned.length;
  282. const truncated = end < query.elements.length;
  283. query.nextOffset = truncated ? end : null;
  284. return {
  285. success: true,
  286. url: snapshot.page.url,
  287. title: snapshot.page.title,
  288. viewport: snapshot.page.viewport,
  289. snapshotId: snapshot.id,
  290. offset,
  291. totalTargets: query.elements.length,
  292. returnedTargets: returned.length,
  293. targets: returned,
  294. truncated,
  295. ...(truncated ? { nextOffset: end } : {}),
  296. ...(truncated
  297. ? {
  298. continuation: {
  299. action: 'query',
  300. input: { kind: 'editable', snapshotId: snapshot.id, offset: end },
  301. },
  302. }
  303. : {}),
  304. };
  305. }
  306. function isEditableElement(
  307. element: Pick<ElementRecord, 'tag' | 'role' | 'type' | 'attributes'>,
  308. ): boolean {
  309. const tag = asString(element.tag).toLowerCase();
  310. const role = asString(element.role).toLowerCase();
  311. const attributes = isRecord(element.attributes) ? element.attributes : {};
  312. const type = asString(attributes.type, asString(element.type)).toLowerCase();
  313. if (tag === 'input' && NON_EDITABLE_INPUT_TYPES.has(type)) return false;
  314. return (
  315. tag === 'input' ||
  316. tag === 'textarea' ||
  317. role === 'textbox' ||
  318. role === 'searchbox' ||
  319. asString(attributes.contenteditable).toLowerCase() === 'true' ||
  320. asString(attributes.role).toLowerCase() === 'textbox' ||
  321. asString(attributes.role).toLowerCase() === 'searchbox'
  322. );
  323. }