browser-action-artifacts.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. import { mkdir, writeFile } from 'node:fs/promises';
  2. import path from 'node:path';
  3. import {
  4. asNumber,
  5. asString,
  6. cdp,
  7. isRecord,
  8. type BrowserSessionState as SessionState,
  9. type PageSummary,
  10. } from './browser-state.js';
  11. const DOWNLOAD_DETECTION_TIMEOUT_MS = 500;
  12. // Downloads are provider-owned background work. Keep click latency bounded
  13. // while returning an explicit in-progress observation that prevents a model
  14. // from clicking the download control again.
  15. const DOWNLOAD_COMPLETION_TIMEOUT_MS = 5_000;
  16. const MAX_DOWNLOAD_COMPLETION_TIMEOUT_MS = 120_000;
  17. const MAX_SCREENSHOT_BYTES = 2 * 1024 * 1024;
  18. export interface BrowserDownloadObservation {
  19. guid: string;
  20. state: 'inProgress' | 'completed' | 'canceled';
  21. /** `timeout` means the download started but completion was not observed in time. */
  22. observation?: 'timeout';
  23. url?: string;
  24. fileName?: string;
  25. filePath?: string;
  26. receivedBytes?: number;
  27. totalBytes?: number;
  28. }
  29. export async function captureBrowserScreenshot(
  30. session: SessionState,
  31. input: Record<string, unknown>,
  32. readPageSummary: () => Promise<PageSummary>,
  33. ): Promise<unknown> {
  34. const scope = asString(input.scope, 'viewport');
  35. let clip: Record<string, number> | undefined;
  36. let captureBeyondViewport = false;
  37. if (scope === 'clip' && isRecord(input.clip)) {
  38. clip = {
  39. x: asNumber(input.clip.x),
  40. y: asNumber(input.clip.y),
  41. width: Math.max(1, asNumber(input.clip.width)),
  42. height: Math.max(1, asNumber(input.clip.height)),
  43. scale: 1,
  44. };
  45. } else if (scope === 'fullPage') {
  46. const page = await readPageSummary();
  47. captureBeyondViewport =
  48. page.pageWidth > page.viewport.width || page.pageHeight > page.viewport.height;
  49. if (captureBeyondViewport) {
  50. clip = {
  51. x: 0,
  52. y: 0,
  53. width: Math.max(1, page.pageWidth),
  54. height: Math.max(1, page.pageHeight),
  55. scale: 1,
  56. };
  57. }
  58. }
  59. let format: 'png' | 'jpeg' = 'png';
  60. let quality: number | undefined;
  61. let result = await cdp<{ data?: string }>(session, 'Page.captureScreenshot', {
  62. format,
  63. captureBeyondViewport,
  64. ...(clip ? { clip } : {}),
  65. });
  66. if (!result.data) throw new Error('SCREENSHOT_EMPTY');
  67. let buffer = Buffer.from(result.data, 'base64');
  68. if (buffer.byteLength > MAX_SCREENSHOT_BYTES) {
  69. format = 'jpeg';
  70. quality = 60;
  71. result = await cdp<{ data?: string }>(session, 'Page.captureScreenshot', {
  72. format,
  73. quality,
  74. captureBeyondViewport,
  75. ...(clip ? { clip } : {}),
  76. });
  77. if (!result.data) throw new Error('SCREENSHOT_EMPTY');
  78. buffer = Buffer.from(result.data, 'base64');
  79. }
  80. const fallbackSize = clip ?? (await readPageSummary()).viewport;
  81. const isPng =
  82. buffer.length >= 24 && buffer.subarray(0, 8).equals(Buffer.from('\x89PNG\r\n\x1a\n', 'binary'));
  83. const width = isPng ? buffer.readUInt32BE(16) : fallbackSize.width;
  84. const height = isPng ? buffer.readUInt32BE(20) : fallbackSize.height;
  85. const filePath = asString(input.file_path);
  86. if (filePath) {
  87. await mkdir(path.dirname(filePath), { recursive: true }).catch(() => undefined);
  88. await writeFile(filePath, buffer);
  89. }
  90. return {
  91. success: true,
  92. format,
  93. width,
  94. height,
  95. bytes: buffer.byteLength,
  96. ...(buffer.byteLength <= MAX_SCREENSHOT_BYTES ? { data: result.data } : { dataOmitted: true }),
  97. ...(quality === undefined ? {} : { quality }),
  98. ...(filePath ? { file_path: filePath } : {}),
  99. };
  100. }
  101. /** Observe provider-owned download events without touching host clipboard or personal files. */
  102. export function observeBrowserDownload(
  103. session: SessionState,
  104. options: {
  105. completionTimeoutMs?: number;
  106. signal?: AbortSignal;
  107. } = {},
  108. ): Promise<BrowserDownloadObservation | undefined> {
  109. if (!session.transport.downloadDirectory) return Promise.resolve(undefined);
  110. return new Promise((resolve) => {
  111. let observation: BrowserDownloadObservation | undefined;
  112. let finished = false;
  113. let detectionTimer: ReturnType<typeof setTimeout> | undefined;
  114. let completionTimer: ReturnType<typeof setTimeout> | undefined;
  115. const requestedCompletionTimeoutMs =
  116. typeof options.completionTimeoutMs === 'number' &&
  117. Number.isFinite(options.completionTimeoutMs) &&
  118. options.completionTimeoutMs > 0
  119. ? Math.floor(options.completionTimeoutMs)
  120. : DOWNLOAD_COMPLETION_TIMEOUT_MS;
  121. const completionTimeoutMs = Math.max(
  122. DOWNLOAD_DETECTION_TIMEOUT_MS,
  123. Math.min(MAX_DOWNLOAD_COMPLETION_TIMEOUT_MS, requestedCompletionTimeoutMs),
  124. );
  125. detectionTimer = setTimeout(() => finish(observation), DOWNLOAD_DETECTION_TIMEOUT_MS);
  126. detectionTimer.unref?.();
  127. const unsubscribe = session.transport.onEvent((event) => {
  128. if (
  129. (event.method === 'Browser.downloadWillBegin' ||
  130. event.method === 'Page.downloadWillBegin') &&
  131. isRecord(event.params)
  132. ) {
  133. const guid = asString(event.params.guid);
  134. if (!guid) return;
  135. const fileName = safeDownloadFileName(asString(event.params.suggestedFilename));
  136. observation = {
  137. guid,
  138. state: 'inProgress',
  139. url: asString(event.params.url) || undefined,
  140. ...(fileName ? { fileName } : {}),
  141. ...(fileName && session.transport.downloadDirectory
  142. ? { filePath: path.join(session.transport.downloadDirectory, fileName) }
  143. : {}),
  144. };
  145. if (detectionTimer) clearTimeout(detectionTimer);
  146. completionTimer = setTimeout(
  147. () =>
  148. finish(
  149. observation
  150. ? { ...observation, state: 'inProgress', observation: 'timeout' }
  151. : undefined,
  152. ),
  153. completionTimeoutMs,
  154. );
  155. completionTimer.unref?.();
  156. return;
  157. }
  158. if (event.method !== 'Browser.downloadProgress' && event.method !== 'Page.downloadProgress') {
  159. return;
  160. }
  161. if (!isRecord(event.params)) return;
  162. const guid = asString(event.params.guid);
  163. if (!observation || guid !== observation.guid) return;
  164. const state = event.params.state;
  165. if (state !== 'inProgress' && state !== 'completed' && state !== 'canceled') return;
  166. const receivedBytes = finiteNumber(event.params.receivedBytes);
  167. const totalBytes = finiteNumber(event.params.totalBytes);
  168. observation = {
  169. ...observation,
  170. state,
  171. ...(receivedBytes !== undefined ? { receivedBytes } : {}),
  172. ...(totalBytes !== undefined ? { totalBytes } : {}),
  173. ...(typeof event.params.filePath === 'string' ? { filePath: event.params.filePath } : {}),
  174. };
  175. if (state === 'completed' || state === 'canceled') finish(observation);
  176. });
  177. function finish(value: BrowserDownloadObservation | undefined): void {
  178. if (finished) return;
  179. finished = true;
  180. if (detectionTimer) clearTimeout(detectionTimer);
  181. if (completionTimer) clearTimeout(completionTimer);
  182. options.signal?.removeEventListener('abort', onAbort);
  183. unsubscribe();
  184. resolve(value);
  185. }
  186. const onAbort = (): void => {
  187. finish(observation);
  188. };
  189. options.signal?.addEventListener('abort', onAbort, { once: true });
  190. if (options.signal?.aborted) onAbort();
  191. });
  192. }
  193. function safeDownloadFileName(value: string): string | undefined {
  194. if (!value) return undefined;
  195. const fileName = path.basename(value).trim();
  196. return fileName && fileName !== '.' && fileName !== '..' ? fileName : undefined;
  197. }
  198. function finiteNumber(value: unknown): number | undefined {
  199. return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
  200. }