@agenticmail/enterprise 0.5.327 → 0.5.329

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.
Files changed (888) hide show
  1. package/dist/agent-tools-F3CYENMK.js +13949 -0
  2. package/dist/browser-tool-P57PLVW2.js +4002 -0
  3. package/dist/chunk-3RI3AIJN.js +1519 -0
  4. package/dist/chunk-AD4DFKHR.js +4928 -0
  5. package/dist/chunk-UQXPVWXG.js +5101 -0
  6. package/dist/cli-agent-K6UFZRXC.js +2473 -0
  7. package/dist/cli-serve-4MT7RDEL.js +260 -0
  8. package/dist/cli.js +3 -3
  9. package/dist/dashboard/app.js +1 -1
  10. package/dist/dashboard/components/transport-encryption.js +0 -62
  11. package/dist/dashboard/pages/agent-detail/index.js +5 -2
  12. package/dist/dashboard/pages/agent-detail/manager.js +1 -1
  13. package/dist/dashboard/pages/agent-detail/overview.js +4 -2
  14. package/dist/dashboard/pages/agent-detail/tool-security.js +1 -1
  15. package/dist/dashboard/pages/domain-status.js +3 -6
  16. package/dist/dashboard/pages/memory-transfer.js +1 -1
  17. package/dist/dashboard/pages/messages.js +0 -1
  18. package/dist/dashboard/pages/roles.js +0 -2
  19. package/dist/dashboard/pages/workforce.js +0 -1
  20. package/dist/index.js +3 -3
  21. package/dist/runtime-L5ADJORP.js +45 -0
  22. package/dist/server-KSN56EZQ.js +28 -0
  23. package/dist/setup-UUNBBOQH.js +20 -0
  24. package/logs/cloudflared-error.log +42 -0
  25. package/logs/enterprise-out.log +6 -0
  26. package/package.json +1 -1
  27. package/src/admin/page-registry.ts +0 -290
  28. package/src/admin/routes.ts +0 -2968
  29. package/src/agent-tools/common.ts +0 -260
  30. package/src/agent-tools/index.ts +0 -542
  31. package/src/agent-tools/merge.ts +0 -62
  32. package/src/agent-tools/middleware.ts +0 -436
  33. package/src/agent-tools/schema/typebox.ts +0 -25
  34. package/src/agent-tools/security.ts +0 -352
  35. package/src/agent-tools/tool-resolver.ts +0 -1018
  36. package/src/agent-tools/tools/agenticmail.ts +0 -1017
  37. package/src/agent-tools/tools/bash.ts +0 -179
  38. package/src/agent-tools/tools/browser-tool.schema.ts +0 -112
  39. package/src/agent-tools/tools/browser-tool.ts +0 -388
  40. package/src/agent-tools/tools/browser.ts +0 -764
  41. package/src/agent-tools/tools/edit.ts +0 -100
  42. package/src/agent-tools/tools/enterprise-code-sandbox.ts +0 -395
  43. package/src/agent-tools/tools/enterprise-database.ts +0 -377
  44. package/src/agent-tools/tools/enterprise-diff.ts +0 -580
  45. package/src/agent-tools/tools/enterprise-documents.ts +0 -896
  46. package/src/agent-tools/tools/enterprise-http.ts +0 -485
  47. package/src/agent-tools/tools/enterprise-security-scan.ts +0 -528
  48. package/src/agent-tools/tools/enterprise-spreadsheet.ts +0 -825
  49. package/src/agent-tools/tools/glob.ts +0 -129
  50. package/src/agent-tools/tools/google/calendar.ts +0 -230
  51. package/src/agent-tools/tools/google/chat.ts +0 -725
  52. package/src/agent-tools/tools/google/contacts.ts +0 -209
  53. package/src/agent-tools/tools/google/docs.ts +0 -162
  54. package/src/agent-tools/tools/google/drive.ts +0 -392
  55. package/src/agent-tools/tools/google/forms.ts +0 -367
  56. package/src/agent-tools/tools/google/gmail.ts +0 -897
  57. package/src/agent-tools/tools/google/index.ts +0 -86
  58. package/src/agent-tools/tools/google/maps.ts +0 -543
  59. package/src/agent-tools/tools/google/meeting-voice.ts +0 -885
  60. package/src/agent-tools/tools/google/meetings.ts +0 -1094
  61. package/src/agent-tools/tools/google/sheets.ts +0 -215
  62. package/src/agent-tools/tools/google/slides.ts +0 -559
  63. package/src/agent-tools/tools/google/tasks.ts +0 -200
  64. package/src/agent-tools/tools/grep.ts +0 -178
  65. package/src/agent-tools/tools/integrations/_factory.ts +0 -102
  66. package/src/agent-tools/tools/integrations/activecampaign.ts +0 -14
  67. package/src/agent-tools/tools/integrations/adobe-sign.ts +0 -14
  68. package/src/agent-tools/tools/integrations/adp.ts +0 -14
  69. package/src/agent-tools/tools/integrations/airtable.ts +0 -14
  70. package/src/agent-tools/tools/integrations/apollo.ts +0 -14
  71. package/src/agent-tools/tools/integrations/asana.ts +0 -14
  72. package/src/agent-tools/tools/integrations/auth0.ts +0 -14
  73. package/src/agent-tools/tools/integrations/aws.ts +0 -14
  74. package/src/agent-tools/tools/integrations/azure-devops.ts +0 -14
  75. package/src/agent-tools/tools/integrations/bamboohr.ts +0 -14
  76. package/src/agent-tools/tools/integrations/basecamp.ts +0 -14
  77. package/src/agent-tools/tools/integrations/bigcommerce.ts +0 -14
  78. package/src/agent-tools/tools/integrations/bitbucket.ts +0 -14
  79. package/src/agent-tools/tools/integrations/box.ts +0 -14
  80. package/src/agent-tools/tools/integrations/brex.ts +0 -14
  81. package/src/agent-tools/tools/integrations/buffer.ts +0 -14
  82. package/src/agent-tools/tools/integrations/calendly.ts +0 -14
  83. package/src/agent-tools/tools/integrations/canva.ts +0 -14
  84. package/src/agent-tools/tools/integrations/chargebee.ts +0 -14
  85. package/src/agent-tools/tools/integrations/circleci.ts +0 -14
  86. package/src/agent-tools/tools/integrations/clickup.ts +0 -14
  87. package/src/agent-tools/tools/integrations/close.ts +0 -14
  88. package/src/agent-tools/tools/integrations/cloudflare.ts +0 -14
  89. package/src/agent-tools/tools/integrations/confluence.ts +0 -14
  90. package/src/agent-tools/tools/integrations/contentful.ts +0 -14
  91. package/src/agent-tools/tools/integrations/copper.ts +0 -14
  92. package/src/agent-tools/tools/integrations/crisp.ts +0 -14
  93. package/src/agent-tools/tools/integrations/crowdstrike.ts +0 -14
  94. package/src/agent-tools/tools/integrations/datadog.ts +0 -14
  95. package/src/agent-tools/tools/integrations/digitalocean.ts +0 -14
  96. package/src/agent-tools/tools/integrations/discord.ts +0 -14
  97. package/src/agent-tools/tools/integrations/docker.ts +0 -14
  98. package/src/agent-tools/tools/integrations/docusign.ts +0 -14
  99. package/src/agent-tools/tools/integrations/drift.ts +0 -14
  100. package/src/agent-tools/tools/integrations/dropbox.ts +0 -14
  101. package/src/agent-tools/tools/integrations/figma.ts +0 -14
  102. package/src/agent-tools/tools/integrations/firebase.ts +0 -14
  103. package/src/agent-tools/tools/integrations/flyio.ts +0 -14
  104. package/src/agent-tools/tools/integrations/freshbooks.ts +0 -14
  105. package/src/agent-tools/tools/integrations/freshdesk.ts +0 -14
  106. package/src/agent-tools/tools/integrations/freshsales.ts +0 -14
  107. package/src/agent-tools/tools/integrations/freshservice.ts +0 -14
  108. package/src/agent-tools/tools/integrations/front.ts +0 -14
  109. package/src/agent-tools/tools/integrations/github-actions.ts +0 -14
  110. package/src/agent-tools/tools/integrations/github.ts +0 -14
  111. package/src/agent-tools/tools/integrations/gitlab.ts +0 -14
  112. package/src/agent-tools/tools/integrations/gong.ts +0 -14
  113. package/src/agent-tools/tools/integrations/google-ads.ts +0 -14
  114. package/src/agent-tools/tools/integrations/google-analytics.ts +0 -14
  115. package/src/agent-tools/tools/integrations/google-cloud.ts +0 -14
  116. package/src/agent-tools/tools/integrations/gotomeeting.ts +0 -14
  117. package/src/agent-tools/tools/integrations/grafana.ts +0 -14
  118. package/src/agent-tools/tools/integrations/greenhouse.ts +0 -14
  119. package/src/agent-tools/tools/integrations/gusto.ts +0 -14
  120. package/src/agent-tools/tools/integrations/hashicorp-vault.ts +0 -14
  121. package/src/agent-tools/tools/integrations/heroku.ts +0 -14
  122. package/src/agent-tools/tools/integrations/hibob.ts +0 -14
  123. package/src/agent-tools/tools/integrations/hootsuite.ts +0 -14
  124. package/src/agent-tools/tools/integrations/hubspot.ts +0 -14
  125. package/src/agent-tools/tools/integrations/huggingface.ts +0 -14
  126. package/src/agent-tools/tools/integrations/index.ts +0 -474
  127. package/src/agent-tools/tools/integrations/intercom.ts +0 -14
  128. package/src/agent-tools/tools/integrations/jira.ts +0 -14
  129. package/src/agent-tools/tools/integrations/klaviyo.ts +0 -14
  130. package/src/agent-tools/tools/integrations/kubernetes.ts +0 -14
  131. package/src/agent-tools/tools/integrations/lattice.ts +0 -14
  132. package/src/agent-tools/tools/integrations/launchdarkly.ts +0 -14
  133. package/src/agent-tools/tools/integrations/lever.ts +0 -14
  134. package/src/agent-tools/tools/integrations/linear.ts +0 -14
  135. package/src/agent-tools/tools/integrations/linkedin.ts +0 -14
  136. package/src/agent-tools/tools/integrations/livechat.ts +0 -14
  137. package/src/agent-tools/tools/integrations/loom.ts +0 -14
  138. package/src/agent-tools/tools/integrations/mailchimp.ts +0 -14
  139. package/src/agent-tools/tools/integrations/mailgun.ts +0 -14
  140. package/src/agent-tools/tools/integrations/miro.ts +0 -14
  141. package/src/agent-tools/tools/integrations/mixpanel.ts +0 -14
  142. package/src/agent-tools/tools/integrations/monday.ts +0 -14
  143. package/src/agent-tools/tools/integrations/mongodb-atlas.ts +0 -14
  144. package/src/agent-tools/tools/integrations/neon.ts +0 -14
  145. package/src/agent-tools/tools/integrations/netlify.ts +0 -14
  146. package/src/agent-tools/tools/integrations/netsuite.ts +0 -14
  147. package/src/agent-tools/tools/integrations/newrelic.ts +0 -14
  148. package/src/agent-tools/tools/integrations/notion.ts +0 -14
  149. package/src/agent-tools/tools/integrations/okta.ts +0 -14
  150. package/src/agent-tools/tools/integrations/openai.ts +0 -14
  151. package/src/agent-tools/tools/integrations/opsgenie.ts +0 -14
  152. package/src/agent-tools/tools/integrations/outreach.ts +0 -14
  153. package/src/agent-tools/tools/integrations/paddle.ts +0 -14
  154. package/src/agent-tools/tools/integrations/pagerduty.ts +0 -14
  155. package/src/agent-tools/tools/integrations/pandadoc.ts +0 -14
  156. package/src/agent-tools/tools/integrations/paypal.ts +0 -14
  157. package/src/agent-tools/tools/integrations/personio.ts +0 -14
  158. package/src/agent-tools/tools/integrations/pinecone.ts +0 -14
  159. package/src/agent-tools/tools/integrations/pipedrive.ts +0 -14
  160. package/src/agent-tools/tools/integrations/plaid.ts +0 -14
  161. package/src/agent-tools/tools/integrations/postmark.ts +0 -14
  162. package/src/agent-tools/tools/integrations/power-automate.ts +0 -14
  163. package/src/agent-tools/tools/integrations/quickbooks.ts +0 -14
  164. package/src/agent-tools/tools/integrations/recurly.ts +0 -14
  165. package/src/agent-tools/tools/integrations/reddit.ts +0 -14
  166. package/src/agent-tools/tools/integrations/render.ts +0 -14
  167. package/src/agent-tools/tools/integrations/ringcentral.ts +0 -14
  168. package/src/agent-tools/tools/integrations/rippling.ts +0 -14
  169. package/src/agent-tools/tools/integrations/salesforce.ts +0 -14
  170. package/src/agent-tools/tools/integrations/salesloft.ts +0 -14
  171. package/src/agent-tools/tools/integrations/sanity.ts +0 -14
  172. package/src/agent-tools/tools/integrations/sap.ts +0 -14
  173. package/src/agent-tools/tools/integrations/segment.ts +0 -14
  174. package/src/agent-tools/tools/integrations/sendgrid.ts +0 -14
  175. package/src/agent-tools/tools/integrations/sentry.ts +0 -14
  176. package/src/agent-tools/tools/integrations/servicenow.ts +0 -14
  177. package/src/agent-tools/tools/integrations/shopify.ts +0 -14
  178. package/src/agent-tools/tools/integrations/shortcut.ts +0 -14
  179. package/src/agent-tools/tools/integrations/slack.ts +0 -14
  180. package/src/agent-tools/tools/integrations/smartsheet.ts +0 -14
  181. package/src/agent-tools/tools/integrations/snowflake.ts +0 -14
  182. package/src/agent-tools/tools/integrations/snyk.ts +0 -14
  183. package/src/agent-tools/tools/integrations/splunk.ts +0 -14
  184. package/src/agent-tools/tools/integrations/square.ts +0 -14
  185. package/src/agent-tools/tools/integrations/statuspage.ts +0 -14
  186. package/src/agent-tools/tools/integrations/stripe.ts +0 -14
  187. package/src/agent-tools/tools/integrations/supabase.ts +0 -14
  188. package/src/agent-tools/tools/integrations/teamwork.ts +0 -14
  189. package/src/agent-tools/tools/integrations/telegram.ts +0 -14
  190. package/src/agent-tools/tools/integrations/terraform.ts +0 -14
  191. package/src/agent-tools/tools/integrations/todoist.ts +0 -14
  192. package/src/agent-tools/tools/integrations/trello.ts +0 -14
  193. package/src/agent-tools/tools/integrations/twilio.ts +0 -14
  194. package/src/agent-tools/tools/integrations/twitter.ts +0 -14
  195. package/src/agent-tools/tools/integrations/vercel.ts +0 -14
  196. package/src/agent-tools/tools/integrations/weaviate.ts +0 -14
  197. package/src/agent-tools/tools/integrations/webex.ts +0 -14
  198. package/src/agent-tools/tools/integrations/webflow.ts +0 -14
  199. package/src/agent-tools/tools/integrations/whatsapp.ts +0 -14
  200. package/src/agent-tools/tools/integrations/whereby.ts +0 -14
  201. package/src/agent-tools/tools/integrations/woocommerce.ts +0 -14
  202. package/src/agent-tools/tools/integrations/wordpress.ts +0 -14
  203. package/src/agent-tools/tools/integrations/workday.ts +0 -14
  204. package/src/agent-tools/tools/integrations/wrike.ts +0 -14
  205. package/src/agent-tools/tools/integrations/xero.ts +0 -14
  206. package/src/agent-tools/tools/integrations/youtube.ts +0 -14
  207. package/src/agent-tools/tools/integrations/zendesk.ts +0 -14
  208. package/src/agent-tools/tools/integrations/zoho-crm.ts +0 -14
  209. package/src/agent-tools/tools/integrations/zoom.ts +0 -14
  210. package/src/agent-tools/tools/integrations/zuora.ts +0 -14
  211. package/src/agent-tools/tools/knowledge-search.ts +0 -318
  212. package/src/agent-tools/tools/local/coding.ts +0 -626
  213. package/src/agent-tools/tools/local/dependency-manager.ts +0 -647
  214. package/src/agent-tools/tools/local/file-edit.ts +0 -31
  215. package/src/agent-tools/tools/local/file-list.ts +0 -39
  216. package/src/agent-tools/tools/local/file-ops.ts +0 -48
  217. package/src/agent-tools/tools/local/file-read.ts +0 -39
  218. package/src/agent-tools/tools/local/file-search.ts +0 -46
  219. package/src/agent-tools/tools/local/file-write.ts +0 -28
  220. package/src/agent-tools/tools/local/filesystem.ts +0 -5
  221. package/src/agent-tools/tools/local/index.ts +0 -55
  222. package/src/agent-tools/tools/local/resolve-path.ts +0 -18
  223. package/src/agent-tools/tools/local/shell.ts +0 -277
  224. package/src/agent-tools/tools/local/system-info.ts +0 -29
  225. package/src/agent-tools/tools/management.ts +0 -425
  226. package/src/agent-tools/tools/mcp-bridge.ts +0 -142
  227. package/src/agent-tools/tools/mcp-server-tools.ts +0 -91
  228. package/src/agent-tools/tools/meeting-lifecycle.ts +0 -438
  229. package/src/agent-tools/tools/memory.ts +0 -509
  230. package/src/agent-tools/tools/messaging/index.ts +0 -6
  231. package/src/agent-tools/tools/messaging/telegram.ts +0 -167
  232. package/src/agent-tools/tools/messaging/whatsapp.ts +0 -651
  233. package/src/agent-tools/tools/microsoft/contacts.ts +0 -176
  234. package/src/agent-tools/tools/microsoft/excel-vba.ts +0 -331
  235. package/src/agent-tools/tools/microsoft/excel.ts +0 -261
  236. package/src/agent-tools/tools/microsoft/graph-api.ts +0 -161
  237. package/src/agent-tools/tools/microsoft/index.ts +0 -95
  238. package/src/agent-tools/tools/microsoft/onedrive.ts +0 -429
  239. package/src/agent-tools/tools/microsoft/onenote.ts +0 -186
  240. package/src/agent-tools/tools/microsoft/outlook-calendar.ts +0 -286
  241. package/src/agent-tools/tools/microsoft/outlook-mail.ts +0 -723
  242. package/src/agent-tools/tools/microsoft/planner.ts +0 -200
  243. package/src/agent-tools/tools/microsoft/powerbi.ts +0 -266
  244. package/src/agent-tools/tools/microsoft/powerpoint.ts +0 -186
  245. package/src/agent-tools/tools/microsoft/sharepoint.ts +0 -328
  246. package/src/agent-tools/tools/microsoft/teams.ts +0 -463
  247. package/src/agent-tools/tools/microsoft/todo.ts +0 -181
  248. package/src/agent-tools/tools/oauth-token-provider.ts +0 -101
  249. package/src/agent-tools/tools/read.ts +0 -160
  250. package/src/agent-tools/tools/visual-memory/capture.ts +0 -217
  251. package/src/agent-tools/tools/visual-memory/diff.ts +0 -283
  252. package/src/agent-tools/tools/visual-memory/index.ts +0 -698
  253. package/src/agent-tools/tools/visual-memory/phash.ts +0 -120
  254. package/src/agent-tools/tools/visual-memory/similarity.ts +0 -354
  255. package/src/agent-tools/tools/visual-memory/storage.ts +0 -534
  256. package/src/agent-tools/tools/visual-memory/types.ts +0 -100
  257. package/src/agent-tools/tools/web-fetch-utils.ts +0 -202
  258. package/src/agent-tools/tools/web-fetch.ts +0 -464
  259. package/src/agent-tools/tools/web-search.ts +0 -480
  260. package/src/agent-tools/tools/web-shared.ts +0 -232
  261. package/src/agent-tools/tools/write.ts +0 -68
  262. package/src/agent-tools/types.ts +0 -214
  263. package/src/agenticmail/index.ts +0 -34
  264. package/src/agenticmail/manager.ts +0 -253
  265. package/src/agenticmail/providers/google.ts +0 -391
  266. package/src/agenticmail/providers/imap.ts +0 -454
  267. package/src/agenticmail/providers/index.ts +0 -28
  268. package/src/agenticmail/providers/microsoft.ts +0 -260
  269. package/src/agenticmail/types.ts +0 -173
  270. package/src/auth/routes.ts +0 -1589
  271. package/src/browser/bridge-auth-registry.ts +0 -34
  272. package/src/browser/bridge-server.ts +0 -93
  273. package/src/browser/cdp.helpers.ts +0 -180
  274. package/src/browser/cdp.ts +0 -466
  275. package/src/browser/chrome.executables.ts +0 -625
  276. package/src/browser/chrome.profile-decoration.ts +0 -198
  277. package/src/browser/chrome.ts +0 -349
  278. package/src/browser/client-actions-core.ts +0 -259
  279. package/src/browser/client-actions-observe.ts +0 -184
  280. package/src/browser/client-actions-state.ts +0 -284
  281. package/src/browser/client-actions-types.ts +0 -16
  282. package/src/browser/client-actions-url.ts +0 -11
  283. package/src/browser/client-actions.ts +0 -4
  284. package/src/browser/client-fetch.ts +0 -253
  285. package/src/browser/client.ts +0 -337
  286. package/src/browser/config.ts +0 -301
  287. package/src/browser/constants.ts +0 -8
  288. package/src/browser/control-auth.ts +0 -94
  289. package/src/browser/control-service.ts +0 -81
  290. package/src/browser/csrf.ts +0 -87
  291. package/src/browser/enterprise-compat.ts +0 -562
  292. package/src/browser/extension-relay.ts +0 -834
  293. package/src/browser/http-auth.ts +0 -63
  294. package/src/browser/navigation-guard.ts +0 -50
  295. package/src/browser/paths.ts +0 -49
  296. package/src/browser/playwright.d.ts +0 -12
  297. package/src/browser/profiles-service.ts +0 -187
  298. package/src/browser/profiles.ts +0 -114
  299. package/src/browser/proxy-files.ts +0 -41
  300. package/src/browser/pw-ai-module.ts +0 -52
  301. package/src/browser/pw-ai-state.ts +0 -9
  302. package/src/browser/pw-ai.ts +0 -65
  303. package/src/browser/pw-role-snapshot.ts +0 -434
  304. package/src/browser/pw-session.ts +0 -810
  305. package/src/browser/pw-tools-core.activity.ts +0 -68
  306. package/src/browser/pw-tools-core.downloads.ts +0 -281
  307. package/src/browser/pw-tools-core.interactions.ts +0 -646
  308. package/src/browser/pw-tools-core.responses.ts +0 -124
  309. package/src/browser/pw-tools-core.shared.ts +0 -70
  310. package/src/browser/pw-tools-core.snapshot.ts +0 -213
  311. package/src/browser/pw-tools-core.state.ts +0 -209
  312. package/src/browser/pw-tools-core.storage.ts +0 -128
  313. package/src/browser/pw-tools-core.trace.ts +0 -37
  314. package/src/browser/pw-tools-core.ts +0 -8
  315. package/src/browser/resolved-config-refresh.ts +0 -59
  316. package/src/browser/routes/agent.act.shared.ts +0 -52
  317. package/src/browser/routes/agent.act.ts +0 -575
  318. package/src/browser/routes/agent.debug.ts +0 -149
  319. package/src/browser/routes/agent.shared.ts +0 -143
  320. package/src/browser/routes/agent.snapshot.ts +0 -333
  321. package/src/browser/routes/agent.storage.ts +0 -451
  322. package/src/browser/routes/agent.ts +0 -13
  323. package/src/browser/routes/basic.ts +0 -202
  324. package/src/browser/routes/dispatcher.ts +0 -126
  325. package/src/browser/routes/index.ts +0 -11
  326. package/src/browser/routes/path-output.ts +0 -1
  327. package/src/browser/routes/tabs.ts +0 -217
  328. package/src/browser/routes/types.ts +0 -26
  329. package/src/browser/routes/utils.ts +0 -73
  330. package/src/browser/screenshot.ts +0 -54
  331. package/src/browser/server-context.ts +0 -688
  332. package/src/browser/server-context.types.ts +0 -65
  333. package/src/browser/server-lifecycle.ts +0 -48
  334. package/src/browser/server-middleware.ts +0 -37
  335. package/src/browser/server.ts +0 -110
  336. package/src/browser/target-id.ts +0 -30
  337. package/src/browser/trash.ts +0 -21
  338. package/src/cli-agent.ts +0 -2452
  339. package/src/cli-reset-password.ts +0 -138
  340. package/src/cli-serve.ts +0 -314
  341. package/src/cli.ts +0 -103
  342. package/src/dashboard/app.js +0 -579
  343. package/src/dashboard/assets/brand-logos.js +0 -350
  344. package/src/dashboard/assets/icons/emoji-icons.js +0 -893
  345. package/src/dashboard/assets/logo.png +0 -0
  346. package/src/dashboard/assets/provider-logos.js +0 -139
  347. package/src/dashboard/components/error-boundary.js +0 -21
  348. package/src/dashboard/components/help-button.js +0 -65
  349. package/src/dashboard/components/icons.js +0 -64
  350. package/src/dashboard/components/knowledge-link.js +0 -79
  351. package/src/dashboard/components/modal.js +0 -125
  352. package/src/dashboard/components/org-switcher.js +0 -156
  353. package/src/dashboard/components/persona-fields.js +0 -460
  354. package/src/dashboard/components/settings-help.js +0 -193
  355. package/src/dashboard/components/tag-input.js +0 -96
  356. package/src/dashboard/components/timezones.js +0 -352
  357. package/src/dashboard/components/transport-encryption.js +0 -288
  358. package/src/dashboard/components/utils.js +0 -205
  359. package/src/dashboard/data/countries.js +0 -255
  360. package/src/dashboard/docs/activity.html +0 -253
  361. package/src/dashboard/docs/agent-activity.html +0 -199
  362. package/src/dashboard/docs/agent-autonomy.html +0 -161
  363. package/src/dashboard/docs/agent-budget.html +0 -190
  364. package/src/dashboard/docs/agent-channels.html +0 -189
  365. package/src/dashboard/docs/agent-communication.html +0 -171
  366. package/src/dashboard/docs/agent-configuration.html +0 -194
  367. package/src/dashboard/docs/agent-deployment.html +0 -323
  368. package/src/dashboard/docs/agent-email.html +0 -184
  369. package/src/dashboard/docs/agent-guardrails.html +0 -206
  370. package/src/dashboard/docs/agent-manager.html +0 -226
  371. package/src/dashboard/docs/agent-memory.html +0 -215
  372. package/src/dashboard/docs/agent-overview.html +0 -226
  373. package/src/dashboard/docs/agent-permissions.html +0 -305
  374. package/src/dashboard/docs/agent-personal.html +0 -155
  375. package/src/dashboard/docs/agent-security.html +0 -188
  376. package/src/dashboard/docs/agent-skills.html +0 -224
  377. package/src/dashboard/docs/agent-tool-security.html +0 -205
  378. package/src/dashboard/docs/agent-tools.html +0 -238
  379. package/src/dashboard/docs/agent-whatsapp.html +0 -210
  380. package/src/dashboard/docs/agent-workforce.html +0 -199
  381. package/src/dashboard/docs/agents.html +0 -258
  382. package/src/dashboard/docs/approvals.html +0 -200
  383. package/src/dashboard/docs/audit.html +0 -206
  384. package/src/dashboard/docs/browser-providers.html +0 -313
  385. package/src/dashboard/docs/cluster.html +0 -285
  386. package/src/dashboard/docs/community-skills.html +0 -253
  387. package/src/dashboard/docs/compliance.html +0 -221
  388. package/src/dashboard/docs/dashboard.html +0 -84
  389. package/src/dashboard/docs/database-access.html +0 -322
  390. package/src/dashboard/docs/dlp.html +0 -268
  391. package/src/dashboard/docs/docs-style.css +0 -26
  392. package/src/dashboard/docs/domain-status.html +0 -294
  393. package/src/dashboard/docs/guardrails.html +0 -265
  394. package/src/dashboard/docs/journal.html +0 -197
  395. package/src/dashboard/docs/knowledge-contributions.html +0 -286
  396. package/src/dashboard/docs/knowledge.html +0 -268
  397. package/src/dashboard/docs/memory-transfer.html +0 -311
  398. package/src/dashboard/docs/messages.html +0 -217
  399. package/src/dashboard/docs/multi-tenant.html +0 -311
  400. package/src/dashboard/docs/org-chart.html +0 -239
  401. package/src/dashboard/docs/organizations.html +0 -182
  402. package/src/dashboard/docs/roles.html +0 -195
  403. package/src/dashboard/docs/settings-network.html +0 -321
  404. package/src/dashboard/docs/settings-security.html +0 -347
  405. package/src/dashboard/docs/settings-tool-security.html +0 -176
  406. package/src/dashboard/docs/settings.html +0 -280
  407. package/src/dashboard/docs/skill-connections.html +0 -270
  408. package/src/dashboard/docs/skills.html +0 -206
  409. package/src/dashboard/docs/task-pipeline.html +0 -261
  410. package/src/dashboard/docs/transport-encryption.html +0 -359
  411. package/src/dashboard/docs/users.html +0 -225
  412. package/src/dashboard/docs/vault.html +0 -260
  413. package/src/dashboard/docs/workforce.html +0 -245
  414. package/src/dashboard/index.html +0 -444
  415. package/src/dashboard/pages/activity.js +0 -379
  416. package/src/dashboard/pages/agent-detail/activity.js +0 -277
  417. package/src/dashboard/pages/agent-detail/autonomy.js +0 -244
  418. package/src/dashboard/pages/agent-detail/budget.js +0 -269
  419. package/src/dashboard/pages/agent-detail/channels.js +0 -494
  420. package/src/dashboard/pages/agent-detail/communication.js +0 -296
  421. package/src/dashboard/pages/agent-detail/configuration.js +0 -882
  422. package/src/dashboard/pages/agent-detail/deployment.js +0 -958
  423. package/src/dashboard/pages/agent-detail/email.js +0 -674
  424. package/src/dashboard/pages/agent-detail/guardrails.js +0 -521
  425. package/src/dashboard/pages/agent-detail/index.js +0 -261
  426. package/src/dashboard/pages/agent-detail/manager.js +0 -357
  427. package/src/dashboard/pages/agent-detail/meeting-browser.js +0 -933
  428. package/src/dashboard/pages/agent-detail/memory.js +0 -368
  429. package/src/dashboard/pages/agent-detail/overview.js +0 -844
  430. package/src/dashboard/pages/agent-detail/permissions.js +0 -1163
  431. package/src/dashboard/pages/agent-detail/personal-details.js +0 -404
  432. package/src/dashboard/pages/agent-detail/security.js +0 -409
  433. package/src/dashboard/pages/agent-detail/shared.js +0 -85
  434. package/src/dashboard/pages/agent-detail/skills-section.js +0 -183
  435. package/src/dashboard/pages/agent-detail/tool-security.js +0 -380
  436. package/src/dashboard/pages/agent-detail/tools.js +0 -322
  437. package/src/dashboard/pages/agent-detail/whatsapp.js +0 -824
  438. package/src/dashboard/pages/agent-detail/workforce.js +0 -683
  439. package/src/dashboard/pages/agents.js +0 -1242
  440. package/src/dashboard/pages/approvals.js +0 -100
  441. package/src/dashboard/pages/audit.js +0 -198
  442. package/src/dashboard/pages/cluster.js +0 -512
  443. package/src/dashboard/pages/community-skills.js +0 -1219
  444. package/src/dashboard/pages/compliance.js +0 -475
  445. package/src/dashboard/pages/dashboard.js +0 -180
  446. package/src/dashboard/pages/database-access.js +0 -812
  447. package/src/dashboard/pages/dlp.js +0 -293
  448. package/src/dashboard/pages/domain-status.js +0 -951
  449. package/src/dashboard/pages/guardrails.js +0 -1035
  450. package/src/dashboard/pages/journal.js +0 -172
  451. package/src/dashboard/pages/knowledge-contributions.js +0 -1682
  452. package/src/dashboard/pages/knowledge-import.js +0 -455
  453. package/src/dashboard/pages/knowledge.js +0 -582
  454. package/src/dashboard/pages/login.js +0 -1056
  455. package/src/dashboard/pages/memory-transfer.js +0 -631
  456. package/src/dashboard/pages/messages.js +0 -303
  457. package/src/dashboard/pages/org-chart.js +0 -349
  458. package/src/dashboard/pages/organizations.js +0 -1081
  459. package/src/dashboard/pages/roles.js +0 -780
  460. package/src/dashboard/pages/settings.js +0 -3790
  461. package/src/dashboard/pages/skill-connections.js +0 -982
  462. package/src/dashboard/pages/skills.js +0 -879
  463. package/src/dashboard/pages/task-pipeline.js +0 -684
  464. package/src/dashboard/pages/users.js +0 -867
  465. package/src/dashboard/pages/vault.js +0 -791
  466. package/src/dashboard/pages/workforce.js +0 -851
  467. package/src/dashboard/vendor/react-dom.development.js +0 -29924
  468. package/src/dashboard/vendor/react-dom.production.min.js +0 -267
  469. package/src/dashboard/vendor/react.development.js +0 -3343
  470. package/src/dashboard/vendor/react.production.min.js +0 -31
  471. package/src/database-access/agent-tools.ts +0 -193
  472. package/src/database-access/connection-manager.ts +0 -1341
  473. package/src/database-access/index.ts +0 -21
  474. package/src/database-access/query-sanitizer.ts +0 -220
  475. package/src/database-access/routes.ts +0 -226
  476. package/src/database-access/types.ts +0 -226
  477. package/src/db/adapter.ts +0 -510
  478. package/src/db/dynamodb.ts +0 -454
  479. package/src/db/factory.ts +0 -129
  480. package/src/db/mongodb.ts +0 -360
  481. package/src/db/mysql.ts +0 -531
  482. package/src/db/postgres.ts +0 -863
  483. package/src/db/proxy.ts +0 -39
  484. package/src/db/resolve-driver.ts +0 -29
  485. package/src/db/sql-schema.ts +0 -124
  486. package/src/db/sqlite.ts +0 -493
  487. package/src/db/turso.ts +0 -470
  488. package/src/deploy/fly.ts +0 -368
  489. package/src/deploy/managed.ts +0 -235
  490. package/src/domain-lock/cli-recover.ts +0 -591
  491. package/src/domain-lock/cli-verify.ts +0 -190
  492. package/src/domain-lock/index.ts +0 -220
  493. package/src/engine/activity-routes.ts +0 -154
  494. package/src/engine/activity.ts +0 -568
  495. package/src/engine/agent-autonomy.ts +0 -974
  496. package/src/engine/agent-config.ts +0 -646
  497. package/src/engine/agent-heartbeat.ts +0 -720
  498. package/src/engine/agent-hierarchy.ts +0 -1064
  499. package/src/engine/agent-memory.ts +0 -806
  500. package/src/engine/agent-notify.ts +0 -50
  501. package/src/engine/agent-routes.ts +0 -2583
  502. package/src/engine/agent-status.ts +0 -311
  503. package/src/engine/ambient-memory.ts +0 -401
  504. package/src/engine/approvals.ts +0 -615
  505. package/src/engine/assets/thinking-hum.mp3 +0 -0
  506. package/src/engine/catalog-routes.ts +0 -232
  507. package/src/engine/chat-poller.ts +0 -913
  508. package/src/engine/chat-webhook-routes.ts +0 -304
  509. package/src/engine/cli-build-skill.ts +0 -285
  510. package/src/engine/cli-submit-skill.ts +0 -200
  511. package/src/engine/cli-validate.ts +0 -188
  512. package/src/engine/cluster.ts +0 -278
  513. package/src/engine/communication-routes.ts +0 -139
  514. package/src/engine/communication.ts +0 -765
  515. package/src/engine/community-registry.ts +0 -1529
  516. package/src/engine/community-routes.ts +0 -260
  517. package/src/engine/compliance-routes.ts +0 -133
  518. package/src/engine/compliance.ts +0 -1679
  519. package/src/engine/config-bus.ts +0 -103
  520. package/src/engine/db-adapter.ts +0 -1156
  521. package/src/engine/db-schema.ts +0 -1945
  522. package/src/engine/deploy-schema-routes.ts +0 -176
  523. package/src/engine/deployer.ts +0 -957
  524. package/src/engine/dlp-routes.ts +0 -101
  525. package/src/engine/dlp.ts +0 -410
  526. package/src/engine/email-poller.ts +0 -855
  527. package/src/engine/emoji.ts +0 -106
  528. package/src/engine/guardrail-routes.ts +0 -125
  529. package/src/engine/guardrails.ts +0 -465
  530. package/src/engine/index.ts +0 -255
  531. package/src/engine/journal-routes.ts +0 -56
  532. package/src/engine/journal.ts +0 -249
  533. package/src/engine/knowledge-contribution-routes.ts +0 -633
  534. package/src/engine/knowledge-contribution.ts +0 -1386
  535. package/src/engine/knowledge-import/chunker.ts +0 -241
  536. package/src/engine/knowledge-import/import-manager.ts +0 -416
  537. package/src/engine/knowledge-import/index.ts +0 -27
  538. package/src/engine/knowledge-import/processors/clean.ts +0 -149
  539. package/src/engine/knowledge-import/processors/extract-gdrive.ts +0 -102
  540. package/src/engine/knowledge-import/processors/extract-github.ts +0 -74
  541. package/src/engine/knowledge-import/processors/extract-sharepoint.ts +0 -69
  542. package/src/engine/knowledge-import/processors/extract-web.ts +0 -275
  543. package/src/engine/knowledge-import/processors/index.ts +0 -18
  544. package/src/engine/knowledge-import/processors/pipeline.ts +0 -171
  545. package/src/engine/knowledge-import/processors/types.ts +0 -78
  546. package/src/engine/knowledge-import/processors/validate.ts +0 -150
  547. package/src/engine/knowledge-import/provider-file-upload.ts +0 -95
  548. package/src/engine/knowledge-import/provider-github.ts +0 -144
  549. package/src/engine/knowledge-import/provider-google-sites.ts +0 -323
  550. package/src/engine/knowledge-import/provider-sharepoint.ts +0 -276
  551. package/src/engine/knowledge-import/provider-url.ts +0 -218
  552. package/src/engine/knowledge-import/routes.ts +0 -94
  553. package/src/engine/knowledge-import/types.ts +0 -92
  554. package/src/engine/knowledge-routes.ts +0 -231
  555. package/src/engine/knowledge.ts +0 -587
  556. package/src/engine/lifecycle.ts +0 -1420
  557. package/src/engine/mcp-process-manager.ts +0 -573
  558. package/src/engine/meeting-monitor.ts +0 -483
  559. package/src/engine/meeting-voice-intelligence.ts +0 -340
  560. package/src/engine/memory-routes.ts +0 -142
  561. package/src/engine/memory-transfer-routes.ts +0 -339
  562. package/src/engine/messaging-history.ts +0 -177
  563. package/src/engine/messaging-poller.ts +0 -786
  564. package/src/engine/model-fallback.ts +0 -141
  565. package/src/engine/oauth-connect-routes.ts +0 -603
  566. package/src/engine/oauth-connect.ts +0 -304
  567. package/src/engine/onboarding-routes.ts +0 -148
  568. package/src/engine/onboarding.ts +0 -574
  569. package/src/engine/org-approval-routes.ts +0 -146
  570. package/src/engine/org-integration-routes.ts +0 -399
  571. package/src/engine/org-integrations.ts +0 -608
  572. package/src/engine/org-policies.ts +0 -502
  573. package/src/engine/policy-import-routes.ts +0 -125
  574. package/src/engine/policy-import.ts +0 -1186
  575. package/src/engine/policy-routes.ts +0 -163
  576. package/src/engine/routes.ts +0 -1236
  577. package/src/engine/screen-unlock.ts +0 -136
  578. package/src/engine/session-router.ts +0 -212
  579. package/src/engine/skill-updater-routes.ts +0 -132
  580. package/src/engine/skill-updater.ts +0 -480
  581. package/src/engine/skill-validator.ts +0 -331
  582. package/src/engine/skills/agent-management.ts +0 -119
  583. package/src/engine/skills/agent-memory.ts +0 -19
  584. package/src/engine/skills/agenticmail.ts +0 -116
  585. package/src/engine/skills/core-tools.ts +0 -25
  586. package/src/engine/skills/database-access.ts +0 -78
  587. package/src/engine/skills/enterprise-code-sandbox.ts +0 -113
  588. package/src/engine/skills/enterprise-database.ts +0 -123
  589. package/src/engine/skills/enterprise-diff.ts +0 -95
  590. package/src/engine/skills/enterprise-documents.ts +0 -162
  591. package/src/engine/skills/enterprise-http.ts +0 -99
  592. package/src/engine/skills/enterprise-security-scan.ts +0 -125
  593. package/src/engine/skills/enterprise-spreadsheet.ts +0 -171
  594. package/src/engine/skills/gws-admin.ts +0 -18
  595. package/src/engine/skills/gws-calendar.ts +0 -21
  596. package/src/engine/skills/gws-chat.ts +0 -29
  597. package/src/engine/skills/gws-contacts.ts +0 -20
  598. package/src/engine/skills/gws-docs.ts +0 -18
  599. package/src/engine/skills/gws-drive.ts +0 -23
  600. package/src/engine/skills/gws-forms.ts +0 -23
  601. package/src/engine/skills/gws-gmail.ts +0 -30
  602. package/src/engine/skills/gws-groups.ts +0 -17
  603. package/src/engine/skills/gws-keep.ts +0 -17
  604. package/src/engine/skills/gws-maps.ts +0 -25
  605. package/src/engine/skills/gws-meet.ts +0 -23
  606. package/src/engine/skills/gws-sheets.ts +0 -22
  607. package/src/engine/skills/gws-sites.ts +0 -16
  608. package/src/engine/skills/gws-slides.ts +0 -27
  609. package/src/engine/skills/gws-tasks.ts +0 -22
  610. package/src/engine/skills/gws-vault.ts +0 -17
  611. package/src/engine/skills/index.ts +0 -159
  612. package/src/engine/skills/knowledge-search.ts +0 -18
  613. package/src/engine/skills/local-system.ts +0 -61
  614. package/src/engine/skills/m365-admin.ts +0 -18
  615. package/src/engine/skills/m365-bookings.ts +0 -17
  616. package/src/engine/skills/m365-copilot.ts +0 -17
  617. package/src/engine/skills/m365-excel.ts +0 -60
  618. package/src/engine/skills/m365-forms.ts +0 -17
  619. package/src/engine/skills/m365-onedrive.ts +0 -60
  620. package/src/engine/skills/m365-onenote.ts +0 -17
  621. package/src/engine/skills/m365-outlook.ts +0 -27
  622. package/src/engine/skills/m365-planner.ts +0 -18
  623. package/src/engine/skills/m365-power-automate.ts +0 -18
  624. package/src/engine/skills/m365-power-bi.ts +0 -19
  625. package/src/engine/skills/m365-powerpoint.ts +0 -33
  626. package/src/engine/skills/m365-sharepoint.ts +0 -20
  627. package/src/engine/skills/m365-teams.ts +0 -21
  628. package/src/engine/skills/m365-todo.ts +0 -17
  629. package/src/engine/skills/m365-whiteboard.ts +0 -16
  630. package/src/engine/skills/m365-word.ts +0 -42
  631. package/src/engine/skills/mcp-bridge.ts +0 -45
  632. package/src/engine/skills/meeting-lifecycle.ts +0 -20
  633. package/src/engine/skills/messaging.ts +0 -46
  634. package/src/engine/skills/visual-memory.ts +0 -25
  635. package/src/engine/skills.ts +0 -688
  636. package/src/engine/soul-library.ts +0 -142
  637. package/src/engine/soul-templates.json +0 -1525
  638. package/src/engine/storage-manager.ts +0 -252
  639. package/src/engine/storage-routes.ts +0 -113
  640. package/src/engine/storage.ts +0 -528
  641. package/src/engine/task-poller.ts +0 -394
  642. package/src/engine/task-queue-after-spawn.ts +0 -66
  643. package/src/engine/task-queue-before-spawn.ts +0 -113
  644. package/src/engine/task-queue-routes.ts +0 -161
  645. package/src/engine/task-queue.ts +0 -664
  646. package/src/engine/tenant.ts +0 -409
  647. package/src/engine/tool-catalog.ts +0 -354
  648. package/src/engine/vault-routes.ts +0 -134
  649. package/src/engine/vault.ts +0 -601
  650. package/src/engine/workforce-routes.ts +0 -331
  651. package/src/engine/workforce.ts +0 -1161
  652. package/src/index.ts +0 -77
  653. package/src/lib/cidr.ts +0 -122
  654. package/src/lib/config-store.ts +0 -86
  655. package/src/lib/resilience.ts +0 -326
  656. package/src/lib/text-search.ts +0 -358
  657. package/src/mcp/adapters/activecampaign.adapter.ts +0 -391
  658. package/src/mcp/adapters/adobe-sign.adapter.ts +0 -469
  659. package/src/mcp/adapters/adp.adapter.ts +0 -358
  660. package/src/mcp/adapters/airtable.adapter.ts +0 -273
  661. package/src/mcp/adapters/apollo.adapter.ts +0 -420
  662. package/src/mcp/adapters/asana.adapter.ts +0 -315
  663. package/src/mcp/adapters/auth0.adapter.ts +0 -386
  664. package/src/mcp/adapters/aws.adapter.ts +0 -345
  665. package/src/mcp/adapters/azure-devops.adapter.ts +0 -389
  666. package/src/mcp/adapters/bamboohr.adapter.ts +0 -376
  667. package/src/mcp/adapters/basecamp.adapter.ts +0 -366
  668. package/src/mcp/adapters/bigcommerce.adapter.ts +0 -429
  669. package/src/mcp/adapters/bitbucket.adapter.ts +0 -260
  670. package/src/mcp/adapters/box.adapter.ts +0 -350
  671. package/src/mcp/adapters/brex.adapter.ts +0 -367
  672. package/src/mcp/adapters/buffer.adapter.ts +0 -303
  673. package/src/mcp/adapters/calendly.adapter.ts +0 -262
  674. package/src/mcp/adapters/canva.adapter.ts +0 -256
  675. package/src/mcp/adapters/chargebee.adapter.ts +0 -448
  676. package/src/mcp/adapters/circleci.adapter.ts +0 -216
  677. package/src/mcp/adapters/clickup.adapter.ts +0 -335
  678. package/src/mcp/adapters/close.adapter.ts +0 -390
  679. package/src/mcp/adapters/cloudflare.adapter.ts +0 -378
  680. package/src/mcp/adapters/confluence.adapter.ts +0 -301
  681. package/src/mcp/adapters/contentful.adapter.ts +0 -355
  682. package/src/mcp/adapters/copper.adapter.ts +0 -468
  683. package/src/mcp/adapters/crisp.adapter.ts +0 -415
  684. package/src/mcp/adapters/crowdstrike.adapter.ts +0 -413
  685. package/src/mcp/adapters/datadog.adapter.ts +0 -373
  686. package/src/mcp/adapters/digitalocean.adapter.ts +0 -336
  687. package/src/mcp/adapters/discord.adapter.ts +0 -248
  688. package/src/mcp/adapters/docker.adapter.ts +0 -238
  689. package/src/mcp/adapters/docusign.adapter.ts +0 -431
  690. package/src/mcp/adapters/drift.adapter.ts +0 -386
  691. package/src/mcp/adapters/dropbox.adapter.ts +0 -315
  692. package/src/mcp/adapters/figma.adapter.ts +0 -302
  693. package/src/mcp/adapters/firebase.adapter.ts +0 -446
  694. package/src/mcp/adapters/flyio.adapter.ts +0 -302
  695. package/src/mcp/adapters/freshbooks.adapter.ts +0 -474
  696. package/src/mcp/adapters/freshdesk.adapter.ts +0 -441
  697. package/src/mcp/adapters/freshsales.adapter.ts +0 -457
  698. package/src/mcp/adapters/freshservice.adapter.ts +0 -481
  699. package/src/mcp/adapters/front.adapter.ts +0 -357
  700. package/src/mcp/adapters/github-actions.adapter.ts +0 -329
  701. package/src/mcp/adapters/github.adapter.ts +0 -387
  702. package/src/mcp/adapters/gitlab.adapter.ts +0 -368
  703. package/src/mcp/adapters/gong.adapter.ts +0 -386
  704. package/src/mcp/adapters/google-ads.adapter.ts +0 -363
  705. package/src/mcp/adapters/google-analytics.adapter.ts +0 -316
  706. package/src/mcp/adapters/google-cloud.adapter.ts +0 -312
  707. package/src/mcp/adapters/gotomeeting.adapter.ts +0 -255
  708. package/src/mcp/adapters/grafana.adapter.ts +0 -361
  709. package/src/mcp/adapters/greenhouse.adapter.ts +0 -354
  710. package/src/mcp/adapters/gusto.adapter.ts +0 -329
  711. package/src/mcp/adapters/hashicorp-vault.adapter.ts +0 -355
  712. package/src/mcp/adapters/heroku.adapter.ts +0 -291
  713. package/src/mcp/adapters/hibob.adapter.ts +0 -334
  714. package/src/mcp/adapters/hootsuite.adapter.ts +0 -322
  715. package/src/mcp/adapters/hubspot.adapter.ts +0 -400
  716. package/src/mcp/adapters/huggingface.adapter.ts +0 -349
  717. package/src/mcp/adapters/index.ts +0 -524
  718. package/src/mcp/adapters/intercom.adapter.ts +0 -269
  719. package/src/mcp/adapters/jira.adapter.ts +0 -482
  720. package/src/mcp/adapters/klaviyo.adapter.ts +0 -353
  721. package/src/mcp/adapters/kubernetes.adapter.ts +0 -431
  722. package/src/mcp/adapters/lattice.adapter.ts +0 -339
  723. package/src/mcp/adapters/launchdarkly.adapter.ts +0 -368
  724. package/src/mcp/adapters/lever.adapter.ts +0 -347
  725. package/src/mcp/adapters/linear.adapter.ts +0 -300
  726. package/src/mcp/adapters/linkedin.adapter.ts +0 -331
  727. package/src/mcp/adapters/livechat.adapter.ts +0 -259
  728. package/src/mcp/adapters/loom.adapter.ts +0 -230
  729. package/src/mcp/adapters/mailchimp.adapter.ts +0 -394
  730. package/src/mcp/adapters/mailgun.adapter.ts +0 -425
  731. package/src/mcp/adapters/miro.adapter.ts +0 -274
  732. package/src/mcp/adapters/mixpanel.adapter.ts +0 -324
  733. package/src/mcp/adapters/monday.adapter.ts +0 -308
  734. package/src/mcp/adapters/mongodb-atlas.adapter.ts +0 -345
  735. package/src/mcp/adapters/neon.adapter.ts +0 -312
  736. package/src/mcp/adapters/netlify.adapter.ts +0 -324
  737. package/src/mcp/adapters/netsuite.adapter.ts +0 -411
  738. package/src/mcp/adapters/newrelic.adapter.ts +0 -339
  739. package/src/mcp/adapters/notion.adapter.ts +0 -338
  740. package/src/mcp/adapters/okta.adapter.ts +0 -394
  741. package/src/mcp/adapters/openai.adapter.ts +0 -315
  742. package/src/mcp/adapters/opsgenie.adapter.ts +0 -375
  743. package/src/mcp/adapters/outreach.adapter.ts +0 -372
  744. package/src/mcp/adapters/paddle.adapter.ts +0 -467
  745. package/src/mcp/adapters/pagerduty.adapter.ts +0 -412
  746. package/src/mcp/adapters/pandadoc.adapter.ts +0 -389
  747. package/src/mcp/adapters/paypal.adapter.ts +0 -465
  748. package/src/mcp/adapters/personio.adapter.ts +0 -401
  749. package/src/mcp/adapters/pinecone.adapter.ts +0 -340
  750. package/src/mcp/adapters/pipedrive.adapter.ts +0 -324
  751. package/src/mcp/adapters/plaid.adapter.ts +0 -444
  752. package/src/mcp/adapters/postmark.adapter.ts +0 -387
  753. package/src/mcp/adapters/power-automate.adapter.ts +0 -388
  754. package/src/mcp/adapters/quickbooks.adapter.ts +0 -431
  755. package/src/mcp/adapters/recurly.adapter.ts +0 -433
  756. package/src/mcp/adapters/reddit.adapter.ts +0 -371
  757. package/src/mcp/adapters/render.adapter.ts +0 -332
  758. package/src/mcp/adapters/ringcentral.adapter.ts +0 -281
  759. package/src/mcp/adapters/rippling.adapter.ts +0 -287
  760. package/src/mcp/adapters/salesforce.adapter.ts +0 -321
  761. package/src/mcp/adapters/salesloft.adapter.ts +0 -413
  762. package/src/mcp/adapters/sanity.adapter.ts +0 -363
  763. package/src/mcp/adapters/sap.adapter.ts +0 -483
  764. package/src/mcp/adapters/segment.adapter.ts +0 -260
  765. package/src/mcp/adapters/sendgrid.adapter.ts +0 -265
  766. package/src/mcp/adapters/sentry.adapter.ts +0 -331
  767. package/src/mcp/adapters/servicenow.adapter.ts +0 -468
  768. package/src/mcp/adapters/shopify.adapter.ts +0 -451
  769. package/src/mcp/adapters/shortcut.adapter.ts +0 -290
  770. package/src/mcp/adapters/slack.adapter.ts +0 -380
  771. package/src/mcp/adapters/smartsheet.adapter.ts +0 -326
  772. package/src/mcp/adapters/snowflake.adapter.ts +0 -347
  773. package/src/mcp/adapters/snyk.adapter.ts +0 -394
  774. package/src/mcp/adapters/splunk.adapter.ts +0 -403
  775. package/src/mcp/adapters/square.adapter.ts +0 -467
  776. package/src/mcp/adapters/statuspage.adapter.ts +0 -401
  777. package/src/mcp/adapters/stripe.adapter.ts +0 -380
  778. package/src/mcp/adapters/supabase.adapter.ts +0 -334
  779. package/src/mcp/adapters/teamwork.adapter.ts +0 -404
  780. package/src/mcp/adapters/telegram.adapter.ts +0 -299
  781. package/src/mcp/adapters/terraform.adapter.ts +0 -300
  782. package/src/mcp/adapters/todoist.adapter.ts +0 -239
  783. package/src/mcp/adapters/trello.adapter.ts +0 -316
  784. package/src/mcp/adapters/twilio.adapter.ts +0 -233
  785. package/src/mcp/adapters/twitter.adapter.ts +0 -348
  786. package/src/mcp/adapters/vercel.adapter.ts +0 -219
  787. package/src/mcp/adapters/weaviate.adapter.ts +0 -371
  788. package/src/mcp/adapters/webex.adapter.ts +0 -237
  789. package/src/mcp/adapters/webflow.adapter.ts +0 -287
  790. package/src/mcp/adapters/whatsapp.adapter.ts +0 -273
  791. package/src/mcp/adapters/whereby.adapter.ts +0 -240
  792. package/src/mcp/adapters/woocommerce.adapter.ts +0 -454
  793. package/src/mcp/adapters/wordpress.adapter.ts +0 -455
  794. package/src/mcp/adapters/workday.adapter.ts +0 -354
  795. package/src/mcp/adapters/wrike.adapter.ts +0 -349
  796. package/src/mcp/adapters/xero.adapter.ts +0 -472
  797. package/src/mcp/adapters/youtube.adapter.ts +0 -401
  798. package/src/mcp/adapters/zendesk.adapter.ts +0 -399
  799. package/src/mcp/adapters/zoho-crm.adapter.ts +0 -410
  800. package/src/mcp/adapters/zoom.adapter.ts +0 -241
  801. package/src/mcp/adapters/zuora.adapter.ts +0 -476
  802. package/src/mcp/framework/api-executor.ts +0 -192
  803. package/src/mcp/framework/aws-sigv4.ts +0 -216
  804. package/src/mcp/framework/credential-resolver.ts +0 -128
  805. package/src/mcp/framework/oauth-token-manager.ts +0 -22
  806. package/src/mcp/framework/skill-mcp-framework.ts +0 -226
  807. package/src/mcp/framework/types.ts +0 -130
  808. package/src/mcp/index.ts +0 -124
  809. package/src/mcp/integration-catalog.ts +0 -178
  810. package/src/middleware/dns-rebinding.ts +0 -44
  811. package/src/middleware/egress-filter.ts +0 -104
  812. package/src/middleware/firewall.ts +0 -192
  813. package/src/middleware/geo-ip.ts +0 -156
  814. package/src/middleware/index.ts +0 -390
  815. package/src/middleware/network-config.ts +0 -90
  816. package/src/middleware/proxy-config.ts +0 -71
  817. package/src/middleware/request-limits.ts +0 -59
  818. package/src/middleware/transport-encryption.ts +0 -398
  819. package/src/registry/cli.ts +0 -63
  820. package/src/registry/server.ts +0 -504
  821. package/src/runtime/agent-loop.ts +0 -779
  822. package/src/runtime/compaction.ts +0 -638
  823. package/src/runtime/email-channel.ts +0 -120
  824. package/src/runtime/environment.ts +0 -300
  825. package/src/runtime/followup.ts +0 -211
  826. package/src/runtime/gateway.ts +0 -260
  827. package/src/runtime/hooks.ts +0 -564
  828. package/src/runtime/index.ts +0 -1110
  829. package/src/runtime/llm-client.ts +0 -1056
  830. package/src/runtime/model-router.ts +0 -97
  831. package/src/runtime/providers.ts +0 -228
  832. package/src/runtime/session-manager.ts +0 -345
  833. package/src/runtime/subagent.ts +0 -153
  834. package/src/runtime/tool-executor.ts +0 -208
  835. package/src/runtime/types.ts +0 -255
  836. package/src/security/brute-force.ts +0 -423
  837. package/src/security/config.ts +0 -159
  838. package/src/security/csp.ts +0 -407
  839. package/src/security/external-content.ts +0 -299
  840. package/src/security/index.ts +0 -557
  841. package/src/security/input-sanitizer.ts +0 -452
  842. package/src/security/output-filter.ts +0 -575
  843. package/src/security/port-scanner.ts +0 -342
  844. package/src/security/prompt-guard.ts +0 -387
  845. package/src/security/sql-guard.ts +0 -338
  846. package/src/security/threat-logger.ts +0 -484
  847. package/src/server.ts +0 -828
  848. package/src/setup/company.ts +0 -183
  849. package/src/setup/database.ts +0 -153
  850. package/src/setup/deployment.ts +0 -561
  851. package/src/setup/domain.ts +0 -112
  852. package/src/setup/index.ts +0 -171
  853. package/src/setup/provision.ts +0 -532
  854. package/src/setup/registration.ts +0 -302
  855. package/src/system-prompts/catchup.ts +0 -48
  856. package/src/system-prompts/google/calendar.ts +0 -37
  857. package/src/system-prompts/google/chat.ts +0 -92
  858. package/src/system-prompts/google/contacts.ts +0 -25
  859. package/src/system-prompts/google/docs.ts +0 -29
  860. package/src/system-prompts/google/drive.ts +0 -34
  861. package/src/system-prompts/google/forms.ts +0 -25
  862. package/src/system-prompts/google/gmail.ts +0 -50
  863. package/src/system-prompts/google/index.ts +0 -23
  864. package/src/system-prompts/google/maps.ts +0 -20
  865. package/src/system-prompts/google/meet.ts +0 -130
  866. package/src/system-prompts/google/sheets.ts +0 -32
  867. package/src/system-prompts/google/slides.ts +0 -26
  868. package/src/system-prompts/google/tasks.ts +0 -27
  869. package/src/system-prompts/index.ts +0 -88
  870. package/src/system-prompts/microsoft/contacts.ts +0 -34
  871. package/src/system-prompts/microsoft/excel.ts +0 -52
  872. package/src/system-prompts/microsoft/index.ts +0 -31
  873. package/src/system-prompts/microsoft/onedrive.ts +0 -41
  874. package/src/system-prompts/microsoft/onenote.ts +0 -36
  875. package/src/system-prompts/microsoft/outlook-calendar.ts +0 -37
  876. package/src/system-prompts/microsoft/outlook-mail.ts +0 -46
  877. package/src/system-prompts/microsoft/planner.ts +0 -37
  878. package/src/system-prompts/microsoft/powerbi.ts +0 -38
  879. package/src/system-prompts/microsoft/powerpoint.ts +0 -35
  880. package/src/system-prompts/microsoft/sharepoint.ts +0 -44
  881. package/src/system-prompts/microsoft/teams.ts +0 -49
  882. package/src/system-prompts/microsoft/todo.ts +0 -37
  883. package/src/system-prompts/shared-blocks.ts +0 -87
  884. package/src/system-prompts/task.ts +0 -21
  885. package/src/system-prompts/triage.ts +0 -34
  886. package/src/types/hono-env.ts +0 -18
  887. package/src/types/optional-deps.d.ts +0 -10
  888. /package/{src → dist}/dashboard/HELP-TOOLTIPS-GUIDE.md +0 -0
@@ -0,0 +1,4002 @@
1
+ import {
2
+ imageResultFromFile,
3
+ jsonResult,
4
+ readStringParam
5
+ } from "./chunk-ZB3VC2MR.js";
6
+ import {
7
+ DEFAULT_AGENTICMAIL_BROWSER_COLOR,
8
+ DEFAULT_AGENTICMAIL_BROWSER_ENABLED,
9
+ DEFAULT_AGENTICMAIL_BROWSER_PROFILE_NAME,
10
+ DEFAULT_AI_SNAPSHOT_EFFICIENT_DEPTH,
11
+ DEFAULT_AI_SNAPSHOT_EFFICIENT_MAX_CHARS,
12
+ DEFAULT_AI_SNAPSHOT_MAX_CHARS,
13
+ DEFAULT_BROWSER_CONTROL_PORT,
14
+ DEFAULT_BROWSER_DEFAULT_PROFILE_NAME,
15
+ DEFAULT_BROWSER_EVALUATE_ENABLED,
16
+ DEFAULT_UPLOAD_DIR,
17
+ IMAGE_REDUCE_QUALITY_STEPS,
18
+ InvalidBrowserNavigationUrlError,
19
+ SsrFBlockedError,
20
+ appendCdpPath,
21
+ assertBrowserNavigationAllowed,
22
+ buildImageResizeSideGrid,
23
+ captureScreenshot,
24
+ createConfigIO,
25
+ createSubsystemLogger,
26
+ createTargetViaCdp,
27
+ deriveDefaultBrowserCdpPortRange,
28
+ deriveDefaultBrowserControlPort,
29
+ ensureChromeExtensionRelayServer,
30
+ ensureGatewayStartupAuth,
31
+ ensureMediaDir,
32
+ escapeRegExp,
33
+ extractErrorCode,
34
+ fetchJson,
35
+ fetchOk,
36
+ formatCliCommand,
37
+ formatErrorMessage,
38
+ getImageMetadata,
39
+ isChromeCdpReady,
40
+ isChromeReachable,
41
+ isLoopbackHost,
42
+ launchAgenticMailChrome,
43
+ loadConfig,
44
+ normalizeCdpWsUrl,
45
+ parseBooleanValue,
46
+ resizeToJpeg,
47
+ resolveAgenticMailUserDataDir,
48
+ resolveBrowserExecutableForPlatform,
49
+ resolveGatewayAuth,
50
+ resolveGatewayPort,
51
+ resolvePathsWithinRoot,
52
+ resolvePreferredAgenticMailTmpDir,
53
+ runExec,
54
+ saveMediaBuffer,
55
+ snapshotAria,
56
+ stopAgenticMailChrome,
57
+ stopChromeExtensionRelayServer,
58
+ withBrowserNavigationPolicy,
59
+ wrapExternalContent,
60
+ writeConfigFile
61
+ } from "./chunk-CQV7GGHT.js";
62
+ import "./chunk-KFQGP6VL.js";
63
+
64
+ // src/browser/client-actions-url.ts
65
+ function buildProfileQuery(profile) {
66
+ return profile ? `?profile=${encodeURIComponent(profile)}` : "";
67
+ }
68
+ function withBaseUrl(baseUrl, path6) {
69
+ const trimmed = baseUrl?.trim();
70
+ if (!trimmed) {
71
+ return path6;
72
+ }
73
+ return `${trimmed.replace(/\/$/, "")}${path6}`;
74
+ }
75
+
76
+ // src/browser/bridge-auth-registry.ts
77
+ var authByPort = /* @__PURE__ */ new Map();
78
+ function getBridgeAuthForPort(port) {
79
+ if (!Number.isFinite(port) || port <= 0) {
80
+ return void 0;
81
+ }
82
+ return authByPort.get(port);
83
+ }
84
+
85
+ // src/browser/control-auth.ts
86
+ function resolveBrowserControlAuth(cfg, env = process.env) {
87
+ const auth = resolveGatewayAuth({
88
+ authConfig: cfg?.gateway?.auth,
89
+ env,
90
+ tailscaleMode: cfg?.gateway?.tailscale?.mode
91
+ });
92
+ const token = typeof auth?.token === "string" ? auth.token.trim() : "";
93
+ const password = typeof auth?.password === "string" ? auth.password.trim() : "";
94
+ return {
95
+ token: token || void 0,
96
+ password: password || void 0
97
+ };
98
+ }
99
+ function shouldAutoGenerateBrowserAuth(env) {
100
+ const nodeEnv = (env.NODE_ENV ?? "").trim().toLowerCase();
101
+ if (nodeEnv === "test") {
102
+ return false;
103
+ }
104
+ const vitest = (env.VITEST ?? "").trim().toLowerCase();
105
+ if (vitest && vitest !== "0" && vitest !== "false" && vitest !== "off") {
106
+ return false;
107
+ }
108
+ return true;
109
+ }
110
+ async function ensureBrowserControlAuth(params) {
111
+ const env = params.env ?? process.env;
112
+ const auth = resolveBrowserControlAuth(params.cfg, env);
113
+ if (auth.token || auth.password) {
114
+ return { auth };
115
+ }
116
+ if (!shouldAutoGenerateBrowserAuth(env)) {
117
+ return { auth };
118
+ }
119
+ if (params.cfg.gateway?.auth?.mode === "password") {
120
+ return { auth };
121
+ }
122
+ if (params.cfg.gateway?.auth?.mode === "none") {
123
+ return { auth };
124
+ }
125
+ if (params.cfg.gateway?.auth?.mode === "trusted-proxy") {
126
+ return { auth };
127
+ }
128
+ const latestCfg = loadConfig();
129
+ const latestAuth = resolveBrowserControlAuth(latestCfg, env);
130
+ if (latestAuth.token || latestAuth.password) {
131
+ return { auth: latestAuth };
132
+ }
133
+ if (latestCfg.gateway?.auth?.mode === "password") {
134
+ return { auth: latestAuth };
135
+ }
136
+ if (latestCfg.gateway?.auth?.mode === "none") {
137
+ return { auth: latestAuth };
138
+ }
139
+ if (latestCfg.gateway?.auth?.mode === "trusted-proxy") {
140
+ return { auth: latestAuth };
141
+ }
142
+ const ensured = await ensureGatewayStartupAuth({
143
+ cfg: latestCfg,
144
+ env,
145
+ persist: true
146
+ });
147
+ const ensuredAuth = resolveBrowserControlAuth(ensured.cfg, env);
148
+ return {
149
+ auth: ensuredAuth,
150
+ generatedToken: ensured.generatedToken
151
+ };
152
+ }
153
+
154
+ // src/browser/profiles.ts
155
+ var CDP_PORT_RANGE_START = 18800;
156
+ var CDP_PORT_RANGE_END = 18899;
157
+ var PROFILE_NAME_REGEX = /^[a-z0-9][a-z0-9-]*$/;
158
+ function isValidProfileName(name) {
159
+ if (!name || name.length > 64) {
160
+ return false;
161
+ }
162
+ return PROFILE_NAME_REGEX.test(name);
163
+ }
164
+ function allocateCdpPort(usedPorts, range) {
165
+ const start = range?.start ?? CDP_PORT_RANGE_START;
166
+ const end = range?.end ?? CDP_PORT_RANGE_END;
167
+ if (!Number.isFinite(start) || !Number.isFinite(end) || start <= 0 || end <= 0) {
168
+ return null;
169
+ }
170
+ if (start > end) {
171
+ return null;
172
+ }
173
+ for (let port = start; port <= end; port++) {
174
+ if (!usedPorts.has(port)) {
175
+ return port;
176
+ }
177
+ }
178
+ return null;
179
+ }
180
+ function getUsedPorts(profiles) {
181
+ if (!profiles) {
182
+ return /* @__PURE__ */ new Set();
183
+ }
184
+ const used = /* @__PURE__ */ new Set();
185
+ for (const profile of Object.values(profiles)) {
186
+ if (typeof profile.cdpPort === "number") {
187
+ used.add(profile.cdpPort);
188
+ continue;
189
+ }
190
+ const rawUrl = profile.cdpUrl?.trim();
191
+ if (!rawUrl) {
192
+ continue;
193
+ }
194
+ try {
195
+ const parsed = new URL(rawUrl);
196
+ const port = parsed.port && Number.parseInt(parsed.port, 10) > 0 ? Number.parseInt(parsed.port, 10) : parsed.protocol === "https:" ? 443 : 80;
197
+ if (!Number.isNaN(port) && port > 0 && port <= 65535) {
198
+ used.add(port);
199
+ }
200
+ } catch {
201
+ }
202
+ }
203
+ return used;
204
+ }
205
+ var PROFILE_COLORS = [
206
+ "#FF4500",
207
+ // Orange-red (agenticmail default)
208
+ "#0066CC",
209
+ // Blue
210
+ "#00AA00",
211
+ // Green
212
+ "#9933FF",
213
+ // Purple
214
+ "#FF6699",
215
+ // Pink
216
+ "#00CCCC",
217
+ // Cyan
218
+ "#FF9900",
219
+ // Orange
220
+ "#6666FF",
221
+ // Indigo
222
+ "#CC3366",
223
+ // Magenta
224
+ "#339966"
225
+ // Teal
226
+ ];
227
+ function allocateColor(usedColors) {
228
+ for (const color of PROFILE_COLORS) {
229
+ if (!usedColors.has(color.toUpperCase())) {
230
+ return color;
231
+ }
232
+ }
233
+ const index = usedColors.size % PROFILE_COLORS.length;
234
+ return PROFILE_COLORS[index] ?? PROFILE_COLORS[0];
235
+ }
236
+ function getUsedColors(profiles) {
237
+ if (!profiles) {
238
+ return /* @__PURE__ */ new Set();
239
+ }
240
+ return new Set(Object.values(profiles).map((p) => (p.color || "").toUpperCase()));
241
+ }
242
+
243
+ // src/browser/config.ts
244
+ function normalizeHexColor(raw) {
245
+ const value = (raw ?? "").trim();
246
+ if (!value) {
247
+ return DEFAULT_AGENTICMAIL_BROWSER_COLOR;
248
+ }
249
+ const normalized = value.startsWith("#") ? value : `#${value}`;
250
+ if (!/^#[0-9a-fA-F]{6}$/.test(normalized)) {
251
+ return DEFAULT_AGENTICMAIL_BROWSER_COLOR;
252
+ }
253
+ return normalized.toUpperCase();
254
+ }
255
+ function normalizeTimeoutMs(raw, fallback) {
256
+ const value = typeof raw === "number" && Number.isFinite(raw) ? Math.floor(raw) : fallback;
257
+ return value < 0 ? fallback : value;
258
+ }
259
+ function normalizeStringList(raw) {
260
+ if (!Array.isArray(raw) || raw.length === 0) {
261
+ return void 0;
262
+ }
263
+ const values = raw.map((value) => value.trim()).filter((value) => value.length > 0);
264
+ return values.length > 0 ? values : void 0;
265
+ }
266
+ function resolveBrowserSsrFPolicy(cfg) {
267
+ const allowPrivateNetwork = cfg?.ssrfPolicy?.allowPrivateNetwork;
268
+ const allowedHostnames = normalizeStringList(cfg?.ssrfPolicy?.allowedHostnames);
269
+ const hostnameAllowlist = normalizeStringList(cfg?.ssrfPolicy?.hostnameAllowlist);
270
+ if (allowPrivateNetwork === void 0 && allowedHostnames === void 0 && hostnameAllowlist === void 0) {
271
+ return void 0;
272
+ }
273
+ return {
274
+ mode: "permissive",
275
+ allowedPatterns: [],
276
+ blockedPatterns: [],
277
+ allowFileUrls: false,
278
+ allowPrivateIps: allowPrivateNetwork || false,
279
+ ...allowPrivateNetwork === true ? { allowPrivateNetwork: true } : {},
280
+ ...allowedHostnames ? { allowedHostnames } : {},
281
+ ...hostnameAllowlist ? { hostnameAllowlist } : {}
282
+ };
283
+ }
284
+ function parseHttpUrl(raw, label) {
285
+ const trimmed = raw.trim();
286
+ const parsed = new URL(trimmed);
287
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
288
+ throw new Error(`${label} must be http(s), got: ${parsed.protocol.replace(":", "")}`);
289
+ }
290
+ const port = parsed.port && Number.parseInt(parsed.port, 10) > 0 ? Number.parseInt(parsed.port, 10) : parsed.protocol === "https:" ? 443 : 80;
291
+ if (Number.isNaN(port) || port <= 0 || port > 65535) {
292
+ throw new Error(`${label} has invalid port: ${parsed.port}`);
293
+ }
294
+ return {
295
+ parsed,
296
+ port,
297
+ normalized: parsed.toString().replace(/\/$/, "")
298
+ };
299
+ }
300
+ function ensureDefaultProfile(profiles, defaultColor, legacyCdpPort, derivedDefaultCdpPort) {
301
+ const result = { ...profiles };
302
+ if (!result[DEFAULT_AGENTICMAIL_BROWSER_PROFILE_NAME]) {
303
+ result[DEFAULT_AGENTICMAIL_BROWSER_PROFILE_NAME] = {
304
+ cdpPort: legacyCdpPort ?? derivedDefaultCdpPort ?? CDP_PORT_RANGE_START,
305
+ color: defaultColor
306
+ };
307
+ }
308
+ return result;
309
+ }
310
+ function ensureDefaultChromeExtensionProfile(profiles, controlPort) {
311
+ const result = { ...profiles };
312
+ if (result.chrome) {
313
+ return result;
314
+ }
315
+ const relayPort = controlPort + 1;
316
+ if (!Number.isFinite(relayPort) || relayPort <= 0 || relayPort > 65535) {
317
+ return result;
318
+ }
319
+ if (getUsedPorts(result).has(relayPort)) {
320
+ return result;
321
+ }
322
+ result.chrome = {
323
+ driver: "extension",
324
+ cdpUrl: `http://127.0.0.1:${relayPort}`,
325
+ color: "#00AA00"
326
+ };
327
+ return result;
328
+ }
329
+ function resolveBrowserConfig(cfg, rootConfig) {
330
+ const enabled = cfg?.enabled ?? DEFAULT_AGENTICMAIL_BROWSER_ENABLED;
331
+ const evaluateEnabled = cfg?.evaluateEnabled ?? DEFAULT_BROWSER_EVALUATE_ENABLED;
332
+ const gatewayPort = resolveGatewayPort(rootConfig);
333
+ const controlPort = deriveDefaultBrowserControlPort(gatewayPort ?? DEFAULT_BROWSER_CONTROL_PORT);
334
+ const defaultColor = normalizeHexColor(cfg?.color);
335
+ const remoteCdpTimeoutMs = normalizeTimeoutMs(cfg?.remoteCdpTimeoutMs, 1500);
336
+ const remoteCdpHandshakeTimeoutMs = normalizeTimeoutMs(
337
+ cfg?.remoteCdpHandshakeTimeoutMs,
338
+ Math.max(2e3, remoteCdpTimeoutMs * 2)
339
+ );
340
+ const derivedCdpRange = deriveDefaultBrowserCdpPortRange(controlPort);
341
+ const rawCdpUrl = (cfg?.cdpUrl ?? "").trim();
342
+ let cdpInfo;
343
+ if (rawCdpUrl) {
344
+ cdpInfo = parseHttpUrl(rawCdpUrl, "browser.cdpUrl");
345
+ } else {
346
+ const derivedPort = controlPort + 1;
347
+ if (derivedPort > 65535) {
348
+ throw new Error(
349
+ `Derived CDP port (${derivedPort}) is too high; check gateway port configuration.`
350
+ );
351
+ }
352
+ const derived = new URL(`http://127.0.0.1:${derivedPort}`);
353
+ cdpInfo = {
354
+ parsed: derived,
355
+ port: derivedPort,
356
+ normalized: derived.toString().replace(/\/$/, "")
357
+ };
358
+ }
359
+ const headless = cfg?.headless === true;
360
+ const noSandbox = cfg?.noSandbox === true;
361
+ const attachOnly = cfg?.attachOnly === true;
362
+ const executablePath = cfg?.executablePath?.trim() || void 0;
363
+ const defaultProfileFromConfig = cfg?.defaultProfile?.trim() || void 0;
364
+ const legacyCdpPort = rawCdpUrl ? cdpInfo.port : void 0;
365
+ const profiles = ensureDefaultChromeExtensionProfile(
366
+ ensureDefaultProfile(cfg?.profiles, defaultColor, legacyCdpPort, derivedCdpRange.start),
367
+ controlPort
368
+ );
369
+ const cdpProtocol = cdpInfo.parsed.protocol === "https:" ? "https" : "http";
370
+ const defaultProfile = defaultProfileFromConfig ?? (profiles[DEFAULT_BROWSER_DEFAULT_PROFILE_NAME] ? DEFAULT_BROWSER_DEFAULT_PROFILE_NAME : DEFAULT_AGENTICMAIL_BROWSER_PROFILE_NAME);
371
+ const extraArgs = Array.isArray(cfg?.extraArgs) ? cfg.extraArgs.filter((a) => typeof a === "string" && a.trim().length > 0) : [];
372
+ const ssrfPolicy = resolveBrowserSsrFPolicy(cfg);
373
+ return {
374
+ enabled,
375
+ evaluateEnabled,
376
+ controlPort,
377
+ cdpProtocol,
378
+ cdpHost: cdpInfo.parsed.hostname,
379
+ cdpIsLoopback: isLoopbackHost(cdpInfo.parsed.hostname),
380
+ remoteCdpTimeoutMs,
381
+ remoteCdpHandshakeTimeoutMs,
382
+ color: defaultColor,
383
+ executablePath,
384
+ headless,
385
+ noSandbox,
386
+ attachOnly,
387
+ defaultProfile,
388
+ profiles,
389
+ ssrfPolicy,
390
+ extraArgs
391
+ };
392
+ }
393
+ function resolveProfile(resolved, profileName) {
394
+ const profile = resolved.profiles[profileName];
395
+ if (!profile) {
396
+ return null;
397
+ }
398
+ const rawProfileUrl = profile.cdpUrl?.trim() ?? "";
399
+ let cdpHost = resolved.cdpHost;
400
+ let cdpPort = profile.cdpPort ?? 0;
401
+ let cdpUrl = "";
402
+ const driver = profile.driver === "extension" ? "extension" : "agenticmail";
403
+ if (rawProfileUrl) {
404
+ const parsed = parseHttpUrl(rawProfileUrl, `browser.profiles.${profileName}.cdpUrl`);
405
+ cdpHost = parsed.parsed.hostname;
406
+ cdpPort = parsed.port;
407
+ cdpUrl = parsed.normalized;
408
+ } else if (cdpPort) {
409
+ cdpUrl = `${resolved.cdpProtocol}://${resolved.cdpHost}:${cdpPort}`;
410
+ } else {
411
+ throw new Error(`Profile "${profileName}" must define cdpPort or cdpUrl.`);
412
+ }
413
+ return {
414
+ name: profileName,
415
+ cdpPort,
416
+ cdpUrl,
417
+ cdpHost,
418
+ cdpIsLoopback: isLoopbackHost(cdpHost),
419
+ color: profile.color || "#666",
420
+ driver
421
+ };
422
+ }
423
+
424
+ // src/browser/server-context.ts
425
+ import fs2 from "fs";
426
+
427
+ // src/browser/pw-ai-module.ts
428
+ var pwAiModuleSoft = null;
429
+ var pwAiModuleStrict = null;
430
+ function isModuleNotFoundError(err) {
431
+ const code = extractErrorCode(err);
432
+ if (code === "ERR_MODULE_NOT_FOUND") {
433
+ return true;
434
+ }
435
+ const msg = formatErrorMessage(err);
436
+ return msg.includes("Cannot find module") || msg.includes("Cannot find package") || msg.includes("Failed to resolve import") || msg.includes("Failed to resolve entry for package") || msg.includes("Failed to load url");
437
+ }
438
+ async function loadPwAiModule(mode) {
439
+ try {
440
+ return await import("./pw-ai-NK5GKBDG.js");
441
+ } catch (err) {
442
+ if (mode === "soft") {
443
+ return null;
444
+ }
445
+ if (isModuleNotFoundError(err)) {
446
+ return null;
447
+ }
448
+ throw err;
449
+ }
450
+ }
451
+ async function getPwAiModule(opts) {
452
+ const mode = opts?.mode ?? "soft";
453
+ if (mode === "soft") {
454
+ if (!pwAiModuleSoft) {
455
+ pwAiModuleSoft = loadPwAiModule("soft");
456
+ }
457
+ return await pwAiModuleSoft;
458
+ }
459
+ if (!pwAiModuleStrict) {
460
+ pwAiModuleStrict = loadPwAiModule("strict");
461
+ }
462
+ return await pwAiModuleStrict;
463
+ }
464
+
465
+ // src/browser/resolved-config-refresh.ts
466
+ function applyResolvedConfig(current, freshResolved) {
467
+ current.resolved = freshResolved;
468
+ for (const [name, runtime] of current.profiles) {
469
+ const nextProfile = resolveProfile(freshResolved, name);
470
+ if (nextProfile) {
471
+ runtime.profile = nextProfile;
472
+ continue;
473
+ }
474
+ if (!runtime.running) {
475
+ current.profiles.delete(name);
476
+ }
477
+ }
478
+ }
479
+ function refreshResolvedBrowserConfigFromDisk(params) {
480
+ if (!params.refreshConfigFromDisk) {
481
+ return;
482
+ }
483
+ const cfg = params.mode === "fresh" ? createConfigIO().load() : loadConfig();
484
+ const freshResolved = resolveBrowserConfig(cfg.browser, cfg);
485
+ applyResolvedConfig(params.current, freshResolved);
486
+ }
487
+ function resolveBrowserProfileWithHotReload(params) {
488
+ refreshResolvedBrowserConfigFromDisk({
489
+ current: params.current,
490
+ refreshConfigFromDisk: params.refreshConfigFromDisk,
491
+ mode: "cached"
492
+ });
493
+ let profile = resolveProfile(params.current.resolved, params.name);
494
+ if (profile) {
495
+ return profile;
496
+ }
497
+ refreshResolvedBrowserConfigFromDisk({
498
+ current: params.current,
499
+ refreshConfigFromDisk: params.refreshConfigFromDisk,
500
+ mode: "fresh"
501
+ });
502
+ profile = resolveProfile(params.current.resolved, params.name);
503
+ return profile;
504
+ }
505
+
506
+ // src/browser/target-id.ts
507
+ function resolveTargetIdFromTabs(input, tabs) {
508
+ const needle = input.trim();
509
+ if (!needle) {
510
+ return { ok: false, reason: "not_found" };
511
+ }
512
+ const exact = tabs.find((t) => t.targetId === needle);
513
+ if (exact) {
514
+ return { ok: true, targetId: exact.targetId };
515
+ }
516
+ const lower = needle.toLowerCase();
517
+ const matches = tabs.map((t) => t.targetId).filter((id) => id.toLowerCase().startsWith(lower));
518
+ const only = matches.length === 1 ? matches[0] : void 0;
519
+ if (only) {
520
+ return { ok: true, targetId: only };
521
+ }
522
+ if (matches.length === 0) {
523
+ return { ok: false, reason: "not_found" };
524
+ }
525
+ return { ok: false, reason: "ambiguous", matches };
526
+ }
527
+
528
+ // src/browser/trash.ts
529
+ import fs from "fs";
530
+ import os from "os";
531
+ import path from "path";
532
+ async function movePathToTrash(targetPath) {
533
+ try {
534
+ await runExec("trash", [targetPath], { timeoutMs: 1e4 });
535
+ return targetPath;
536
+ } catch {
537
+ const trashDir = path.join(os.homedir(), ".Trash");
538
+ fs.mkdirSync(trashDir, { recursive: true });
539
+ const base = path.basename(targetPath);
540
+ let dest = path.join(trashDir, `${base}-${Date.now()}`);
541
+ if (fs.existsSync(dest)) {
542
+ dest = path.join(trashDir, `${base}-${Date.now()}-${Math.random()}`);
543
+ }
544
+ fs.renameSync(targetPath, dest);
545
+ return dest;
546
+ }
547
+ }
548
+
549
+ // src/browser/server-context.ts
550
+ function normalizeWsUrl(raw, cdpBaseUrl) {
551
+ if (!raw) {
552
+ return void 0;
553
+ }
554
+ try {
555
+ return normalizeCdpWsUrl(raw, cdpBaseUrl);
556
+ } catch {
557
+ return raw;
558
+ }
559
+ }
560
+ function createProfileContext(opts, profile) {
561
+ const state2 = () => {
562
+ const current = opts.getState();
563
+ if (!current) {
564
+ throw new Error("Browser server not started");
565
+ }
566
+ return current;
567
+ };
568
+ const getProfileState = () => {
569
+ const current = state2();
570
+ let profileState = current.profiles.get(profile.name);
571
+ if (!profileState) {
572
+ profileState = { profile, running: null, lastTargetId: null };
573
+ current.profiles.set(profile.name, profileState);
574
+ }
575
+ return profileState;
576
+ };
577
+ const setProfileRunning = (running) => {
578
+ const profileState = getProfileState();
579
+ profileState.running = running;
580
+ };
581
+ const listTabs = async () => {
582
+ if (!profile.cdpIsLoopback) {
583
+ const mod = await getPwAiModule({ mode: "strict" });
584
+ const listPagesViaPlaywright = mod?.listPagesViaPlaywright;
585
+ if (typeof listPagesViaPlaywright === "function") {
586
+ const pages = await listPagesViaPlaywright({ cdpUrl: profile.cdpUrl });
587
+ return pages.map((p) => ({
588
+ targetId: p.targetId,
589
+ title: p.title,
590
+ url: p.url,
591
+ type: p.type
592
+ }));
593
+ }
594
+ }
595
+ const raw = await fetchJson(appendCdpPath(profile.cdpUrl, "/json/list"));
596
+ return raw.map((t) => ({
597
+ targetId: t.id ?? "",
598
+ title: t.title ?? "",
599
+ url: t.url ?? "",
600
+ wsUrl: normalizeWsUrl(t.webSocketDebuggerUrl, profile.cdpUrl),
601
+ type: t.type
602
+ })).filter((t) => Boolean(t.targetId));
603
+ };
604
+ const openTab = async (url) => {
605
+ const ssrfPolicyOpts = withBrowserNavigationPolicy(state2().resolved.ssrfPolicy);
606
+ await assertBrowserNavigationAllowed({ url, ...ssrfPolicyOpts });
607
+ if (!profile.cdpIsLoopback) {
608
+ const mod = await getPwAiModule({ mode: "strict" });
609
+ const createPageViaPlaywright = mod?.createPageViaPlaywright;
610
+ if (typeof createPageViaPlaywright === "function") {
611
+ const page = await createPageViaPlaywright({
612
+ cdpUrl: profile.cdpUrl,
613
+ url,
614
+ ...ssrfPolicyOpts,
615
+ navigationChecked: true
616
+ });
617
+ const profileState2 = getProfileState();
618
+ profileState2.lastTargetId = page.targetId;
619
+ return {
620
+ targetId: page.targetId,
621
+ title: page.title,
622
+ url: page.url,
623
+ type: page.type
624
+ };
625
+ }
626
+ }
627
+ const createdViaCdp = await createTargetViaCdp({
628
+ cdpUrl: profile.cdpUrl,
629
+ url,
630
+ ...ssrfPolicyOpts,
631
+ navigationChecked: true
632
+ }).then((r) => r.targetId).catch(() => null);
633
+ if (createdViaCdp) {
634
+ const profileState2 = getProfileState();
635
+ profileState2.lastTargetId = createdViaCdp;
636
+ const deadline = Date.now() + 2e3;
637
+ while (Date.now() < deadline) {
638
+ const tabs = await listTabs().catch(() => []);
639
+ const found = tabs.find((t) => t.targetId === createdViaCdp);
640
+ if (found) {
641
+ return found;
642
+ }
643
+ await new Promise((r) => setTimeout(r, 100));
644
+ }
645
+ return { targetId: createdViaCdp, title: "", url, type: "page" };
646
+ }
647
+ const encoded = encodeURIComponent(url);
648
+ const endpointUrl = new URL(appendCdpPath(profile.cdpUrl, "/json/new"));
649
+ const endpoint = endpointUrl.search ? (() => {
650
+ endpointUrl.searchParams.set("url", url);
651
+ return endpointUrl.toString();
652
+ })() : `${endpointUrl.toString()}?${encoded}`;
653
+ const created = await fetchJson(endpoint, 1500, {
654
+ method: "PUT"
655
+ }).catch(async (err) => {
656
+ if (String(err).includes("HTTP 405")) {
657
+ return await fetchJson(endpoint, 1500);
658
+ }
659
+ throw err;
660
+ });
661
+ if (!created.id) {
662
+ throw new Error("Failed to open tab (missing id)");
663
+ }
664
+ const profileState = getProfileState();
665
+ profileState.lastTargetId = created.id;
666
+ return {
667
+ targetId: created.id,
668
+ title: created.title ?? "",
669
+ url: created.url ?? url,
670
+ wsUrl: normalizeWsUrl(created.webSocketDebuggerUrl, profile.cdpUrl),
671
+ type: created.type
672
+ };
673
+ };
674
+ const resolveRemoteHttpTimeout = (timeoutMs) => {
675
+ if (profile.cdpIsLoopback) {
676
+ return timeoutMs ?? 300;
677
+ }
678
+ const resolved = state2().resolved;
679
+ if (typeof timeoutMs === "number" && Number.isFinite(timeoutMs)) {
680
+ return Math.max(Math.floor(timeoutMs), resolved.remoteCdpTimeoutMs);
681
+ }
682
+ return resolved.remoteCdpTimeoutMs;
683
+ };
684
+ const resolveRemoteWsTimeout = (timeoutMs) => {
685
+ if (profile.cdpIsLoopback) {
686
+ const base = timeoutMs ?? 300;
687
+ return Math.max(200, Math.min(2e3, base * 2));
688
+ }
689
+ const resolved = state2().resolved;
690
+ if (typeof timeoutMs === "number" && Number.isFinite(timeoutMs)) {
691
+ return Math.max(Math.floor(timeoutMs) * 2, resolved.remoteCdpHandshakeTimeoutMs);
692
+ }
693
+ return resolved.remoteCdpHandshakeTimeoutMs;
694
+ };
695
+ const isReachable = async (timeoutMs) => {
696
+ const httpTimeout = resolveRemoteHttpTimeout(timeoutMs);
697
+ const wsTimeout = resolveRemoteWsTimeout(timeoutMs);
698
+ return await isChromeCdpReady(profile.cdpUrl, httpTimeout, wsTimeout);
699
+ };
700
+ const isHttpReachable = async (timeoutMs) => {
701
+ const httpTimeout = resolveRemoteHttpTimeout(timeoutMs);
702
+ return await isChromeReachable(profile.cdpUrl, httpTimeout);
703
+ };
704
+ const attachRunning = (running) => {
705
+ setProfileRunning(running);
706
+ running.proc.on("exit", () => {
707
+ if (!opts.getState()) {
708
+ return;
709
+ }
710
+ const profileState = getProfileState();
711
+ if (profileState.running?.pid === running.pid) {
712
+ setProfileRunning(null);
713
+ }
714
+ });
715
+ };
716
+ const ensureBrowserAvailable = async () => {
717
+ const current = state2();
718
+ const remoteCdp = !profile.cdpIsLoopback;
719
+ const isExtension = profile.driver === "extension";
720
+ const profileState = getProfileState();
721
+ const httpReachable = await isHttpReachable();
722
+ if (isExtension && remoteCdp) {
723
+ throw new Error(
724
+ `Profile "${profile.name}" uses driver=extension but cdpUrl is not loopback (${profile.cdpUrl}).`
725
+ );
726
+ }
727
+ if (isExtension) {
728
+ if (!httpReachable) {
729
+ await ensureChromeExtensionRelayServer({ cdpUrl: profile.cdpUrl });
730
+ if (await isHttpReachable(1200)) {
731
+ } else {
732
+ throw new Error(
733
+ `Chrome extension relay for profile "${profile.name}" is not reachable at ${profile.cdpUrl}.`
734
+ );
735
+ }
736
+ }
737
+ if (await isReachable(600)) {
738
+ return;
739
+ }
740
+ throw new Error(
741
+ `Chrome extension relay is running, but no tab is connected. Click the AgenticMail Chrome extension icon on a tab to attach it (profile "${profile.name}").`
742
+ );
743
+ }
744
+ if (!httpReachable) {
745
+ if ((current.resolved.attachOnly || remoteCdp) && opts.onEnsureAttachTarget) {
746
+ await opts.onEnsureAttachTarget(profile);
747
+ if (await isHttpReachable(1200)) {
748
+ return;
749
+ }
750
+ }
751
+ if (current.resolved.attachOnly || remoteCdp) {
752
+ throw new Error(
753
+ remoteCdp ? `Remote CDP for profile "${profile.name}" is not reachable at ${profile.cdpUrl}.` : `Browser attachOnly is enabled and profile "${profile.name}" is not running.`
754
+ );
755
+ }
756
+ const launched = await launchAgenticMailChrome(current.resolved, profile);
757
+ attachRunning(launched);
758
+ return;
759
+ }
760
+ if (await isReachable()) {
761
+ return;
762
+ }
763
+ if (!profileState.running) {
764
+ throw new Error(
765
+ `Port ${profile.cdpPort} is in use for profile "${profile.name}" but not by agenticmail. Run action=reset-profile profile=${profile.name} to kill the process.`
766
+ );
767
+ }
768
+ if (current.resolved.attachOnly || remoteCdp) {
769
+ if (opts.onEnsureAttachTarget) {
770
+ await opts.onEnsureAttachTarget(profile);
771
+ if (await isReachable(1200)) {
772
+ return;
773
+ }
774
+ }
775
+ throw new Error(
776
+ remoteCdp ? `Remote CDP websocket for profile "${profile.name}" is not reachable.` : `Browser attachOnly is enabled and CDP websocket for profile "${profile.name}" is not reachable.`
777
+ );
778
+ }
779
+ await stopAgenticMailChrome(profileState.running);
780
+ setProfileRunning(null);
781
+ const relaunched = await launchAgenticMailChrome(current.resolved, profile);
782
+ attachRunning(relaunched);
783
+ if (!await isReachable(600)) {
784
+ throw new Error(
785
+ `Chrome CDP websocket for profile "${profile.name}" is not reachable after restart.`
786
+ );
787
+ }
788
+ };
789
+ const ensureTabAvailable = async (targetId) => {
790
+ await ensureBrowserAvailable();
791
+ const profileState = getProfileState();
792
+ const tabs1 = await listTabs();
793
+ if (tabs1.length === 0) {
794
+ if (profile.driver === "extension") {
795
+ throw new Error(
796
+ `tab not found (no attached Chrome tabs for profile "${profile.name}"). Click the AgenticMail Browser Relay toolbar icon on the tab you want to control (badge ON).`
797
+ );
798
+ }
799
+ await openTab("about:blank");
800
+ }
801
+ const tabs = await listTabs();
802
+ const candidates = profile.driver === "extension" || !profile.cdpIsLoopback ? tabs : tabs.filter((t) => Boolean(t.wsUrl));
803
+ const resolveById = (raw) => {
804
+ const resolved = resolveTargetIdFromTabs(raw, candidates);
805
+ if (!resolved.ok) {
806
+ if (resolved.reason === "ambiguous") {
807
+ return "AMBIGUOUS";
808
+ }
809
+ return null;
810
+ }
811
+ return candidates.find((t) => t.targetId === resolved.targetId) ?? null;
812
+ };
813
+ const pickDefault = () => {
814
+ const last = profileState.lastTargetId?.trim() || "";
815
+ const lastResolved = last ? resolveById(last) : null;
816
+ if (lastResolved && lastResolved !== "AMBIGUOUS") {
817
+ return lastResolved;
818
+ }
819
+ const page = candidates.find((t) => (t.type ?? "page") === "page");
820
+ return page ?? candidates.at(0) ?? null;
821
+ };
822
+ let chosen = targetId ? resolveById(targetId) : pickDefault();
823
+ if (!chosen && profile.driver === "extension" && candidates.length === 1) {
824
+ chosen = candidates[0] ?? null;
825
+ }
826
+ if (chosen === "AMBIGUOUS") {
827
+ throw new Error("ambiguous target id prefix");
828
+ }
829
+ if (!chosen) {
830
+ throw new Error("tab not found");
831
+ }
832
+ profileState.lastTargetId = chosen.targetId;
833
+ return chosen;
834
+ };
835
+ const focusTab = async (targetId) => {
836
+ const tabs = await listTabs();
837
+ const resolved = resolveTargetIdFromTabs(targetId, tabs);
838
+ if (!resolved.ok) {
839
+ if (resolved.reason === "ambiguous") {
840
+ throw new Error("ambiguous target id prefix");
841
+ }
842
+ throw new Error("tab not found");
843
+ }
844
+ if (!profile.cdpIsLoopback) {
845
+ const mod = await getPwAiModule({ mode: "strict" });
846
+ const focusPageByTargetIdViaPlaywright = mod?.focusPageByTargetIdViaPlaywright;
847
+ if (typeof focusPageByTargetIdViaPlaywright === "function") {
848
+ await focusPageByTargetIdViaPlaywright({
849
+ cdpUrl: profile.cdpUrl,
850
+ targetId: resolved.targetId
851
+ });
852
+ const profileState2 = getProfileState();
853
+ profileState2.lastTargetId = resolved.targetId;
854
+ return;
855
+ }
856
+ }
857
+ await fetchOk(appendCdpPath(profile.cdpUrl, `/json/activate/${resolved.targetId}`));
858
+ const profileState = getProfileState();
859
+ profileState.lastTargetId = resolved.targetId;
860
+ };
861
+ const closeTab = async (targetId) => {
862
+ const tabs = await listTabs();
863
+ const resolved = resolveTargetIdFromTabs(targetId, tabs);
864
+ if (!resolved.ok) {
865
+ if (resolved.reason === "ambiguous") {
866
+ throw new Error("ambiguous target id prefix");
867
+ }
868
+ throw new Error("tab not found");
869
+ }
870
+ if (!profile.cdpIsLoopback) {
871
+ const mod = await getPwAiModule({ mode: "strict" });
872
+ const closePageByTargetIdViaPlaywright = mod?.closePageByTargetIdViaPlaywright;
873
+ if (typeof closePageByTargetIdViaPlaywright === "function") {
874
+ await closePageByTargetIdViaPlaywright({
875
+ cdpUrl: profile.cdpUrl,
876
+ targetId: resolved.targetId
877
+ });
878
+ return;
879
+ }
880
+ }
881
+ await fetchOk(appendCdpPath(profile.cdpUrl, `/json/close/${resolved.targetId}`));
882
+ };
883
+ const stopRunningBrowser = async () => {
884
+ if (profile.driver === "extension") {
885
+ const stopped = await stopChromeExtensionRelayServer({
886
+ cdpUrl: profile.cdpUrl
887
+ });
888
+ return { stopped };
889
+ }
890
+ const profileState = getProfileState();
891
+ if (!profileState.running) {
892
+ return { stopped: false };
893
+ }
894
+ await stopAgenticMailChrome(profileState.running);
895
+ setProfileRunning(null);
896
+ return { stopped: true };
897
+ };
898
+ const resetProfile = async () => {
899
+ if (profile.driver === "extension") {
900
+ await stopChromeExtensionRelayServer({ cdpUrl: profile.cdpUrl }).catch(() => {
901
+ });
902
+ return { moved: false, from: profile.cdpUrl };
903
+ }
904
+ if (!profile.cdpIsLoopback) {
905
+ throw new Error(
906
+ `reset-profile is only supported for local profiles (profile "${profile.name}" is remote).`
907
+ );
908
+ }
909
+ const userDataDir = resolveAgenticMailUserDataDir(profile.name);
910
+ const profileState = getProfileState();
911
+ const httpReachable = await isHttpReachable(300);
912
+ if (httpReachable && !profileState.running) {
913
+ try {
914
+ const mod = await import("./pw-ai-NK5GKBDG.js");
915
+ await mod.closePlaywrightBrowserConnection();
916
+ } catch {
917
+ }
918
+ }
919
+ if (profileState.running) {
920
+ await stopRunningBrowser();
921
+ }
922
+ try {
923
+ const mod = await import("./pw-ai-NK5GKBDG.js");
924
+ await mod.closePlaywrightBrowserConnection();
925
+ } catch {
926
+ }
927
+ if (!fs2.existsSync(userDataDir)) {
928
+ return { moved: false, from: userDataDir };
929
+ }
930
+ const moved = await movePathToTrash(userDataDir);
931
+ return { moved: true, from: userDataDir, to: moved };
932
+ };
933
+ return {
934
+ profile,
935
+ ensureBrowserAvailable,
936
+ ensureTabAvailable,
937
+ isHttpReachable,
938
+ isReachable,
939
+ listTabs,
940
+ openTab,
941
+ focusTab,
942
+ closeTab,
943
+ stopRunningBrowser,
944
+ resetProfile
945
+ };
946
+ }
947
+ function createBrowserRouteContext(opts) {
948
+ const refreshConfigFromDisk = opts.refreshConfigFromDisk === true;
949
+ const state2 = () => {
950
+ const current = opts.getState();
951
+ if (!current) {
952
+ throw new Error("Browser server not started");
953
+ }
954
+ return current;
955
+ };
956
+ const forProfile = (profileName) => {
957
+ const current = state2();
958
+ const name = profileName ?? current.resolved.defaultProfile;
959
+ const profile = resolveBrowserProfileWithHotReload({
960
+ current,
961
+ refreshConfigFromDisk,
962
+ name
963
+ });
964
+ if (!profile) {
965
+ const available = Object.keys(current.resolved.profiles).join(", ");
966
+ throw new Error(`Profile "${name}" not found. Available profiles: ${available || "(none)"}`);
967
+ }
968
+ return createProfileContext(opts, profile);
969
+ };
970
+ const listProfiles = async () => {
971
+ const current = state2();
972
+ refreshResolvedBrowserConfigFromDisk({
973
+ current,
974
+ refreshConfigFromDisk,
975
+ mode: "cached"
976
+ });
977
+ const result = [];
978
+ for (const name of Object.keys(current.resolved.profiles)) {
979
+ const profileState = current.profiles.get(name);
980
+ const profile = resolveProfile(current.resolved, name);
981
+ if (!profile) {
982
+ continue;
983
+ }
984
+ let tabCount = 0;
985
+ let running = false;
986
+ if (profileState?.running) {
987
+ running = true;
988
+ try {
989
+ const ctx = createProfileContext(opts, profile);
990
+ const tabs = await ctx.listTabs();
991
+ tabCount = tabs.filter((t) => t.type === "page").length;
992
+ } catch {
993
+ }
994
+ } else {
995
+ try {
996
+ const reachable = await isChromeReachable(profile.cdpUrl, 200);
997
+ if (reachable) {
998
+ running = true;
999
+ const ctx = createProfileContext(opts, profile);
1000
+ const tabs = await ctx.listTabs().catch(() => []);
1001
+ tabCount = tabs.filter((t) => t.type === "page").length;
1002
+ }
1003
+ } catch {
1004
+ }
1005
+ }
1006
+ result.push({
1007
+ name,
1008
+ cdpPort: profile.cdpPort,
1009
+ cdpUrl: profile.cdpUrl,
1010
+ color: profile.color,
1011
+ running,
1012
+ tabCount,
1013
+ isDefault: name === current.resolved.defaultProfile,
1014
+ isRemote: !profile.cdpIsLoopback
1015
+ });
1016
+ }
1017
+ return result;
1018
+ };
1019
+ const getDefaultContext = () => forProfile();
1020
+ const mapTabError = (err) => {
1021
+ if (err instanceof SsrFBlockedError) {
1022
+ return { status: 400, message: err.message };
1023
+ }
1024
+ if (err instanceof InvalidBrowserNavigationUrlError) {
1025
+ return { status: 400, message: err.message };
1026
+ }
1027
+ const msg = String(err);
1028
+ if (msg.includes("ambiguous target id prefix")) {
1029
+ return { status: 409, message: "ambiguous target id prefix" };
1030
+ }
1031
+ if (msg.includes("tab not found")) {
1032
+ return { status: 404, message: msg };
1033
+ }
1034
+ if (msg.includes("not found")) {
1035
+ return { status: 404, message: msg };
1036
+ }
1037
+ return null;
1038
+ };
1039
+ return {
1040
+ state: state2,
1041
+ forProfile,
1042
+ listProfiles,
1043
+ // Legacy methods delegate to default profile
1044
+ ensureBrowserAvailable: () => getDefaultContext().ensureBrowserAvailable(),
1045
+ ensureTabAvailable: (targetId) => getDefaultContext().ensureTabAvailable(targetId),
1046
+ isHttpReachable: (timeoutMs) => getDefaultContext().isHttpReachable(timeoutMs),
1047
+ isReachable: (timeoutMs) => getDefaultContext().isReachable(timeoutMs),
1048
+ listTabs: () => getDefaultContext().listTabs(),
1049
+ openTab: (url) => getDefaultContext().openTab(url),
1050
+ focusTab: (targetId) => getDefaultContext().focusTab(targetId),
1051
+ closeTab: (targetId) => getDefaultContext().closeTab(targetId),
1052
+ stopRunningBrowser: () => getDefaultContext().stopRunningBrowser(),
1053
+ resetProfile: () => getDefaultContext().resetProfile(),
1054
+ mapTabError
1055
+ };
1056
+ }
1057
+
1058
+ // src/browser/server-lifecycle.ts
1059
+ async function ensureExtensionRelayForProfiles(params) {
1060
+ for (const name of Object.keys(params.resolved.profiles)) {
1061
+ const profile = resolveProfile(params.resolved, name);
1062
+ if (!profile || profile.driver !== "extension") {
1063
+ continue;
1064
+ }
1065
+ await ensureChromeExtensionRelayServer({ cdpUrl: profile.cdpUrl }).catch((err) => {
1066
+ params.onWarn(`Chrome extension relay init failed for profile "${name}": ${String(err)}`);
1067
+ });
1068
+ }
1069
+ }
1070
+
1071
+ // src/browser/control-service.ts
1072
+ var state = null;
1073
+ var log = createSubsystemLogger("browser");
1074
+ var logService = log.child("service");
1075
+ function createBrowserControlContext() {
1076
+ return createBrowserRouteContext({
1077
+ getState: () => state,
1078
+ refreshConfigFromDisk: true
1079
+ });
1080
+ }
1081
+ async function startBrowserControlServiceFromConfig() {
1082
+ if (state) {
1083
+ return state;
1084
+ }
1085
+ const cfg = loadConfig();
1086
+ const resolved = resolveBrowserConfig(cfg.browser, cfg);
1087
+ if (!resolved.enabled) {
1088
+ return null;
1089
+ }
1090
+ try {
1091
+ const ensured = await ensureBrowserControlAuth({ cfg });
1092
+ if (ensured.generatedToken) {
1093
+ logService.info("No browser auth configured; generated gateway.auth.token automatically.");
1094
+ }
1095
+ } catch (err) {
1096
+ logService.warn(`failed to auto-configure browser auth: ${String(err)}`);
1097
+ }
1098
+ state = {
1099
+ server: null,
1100
+ port: resolved.controlPort,
1101
+ resolved,
1102
+ profiles: /* @__PURE__ */ new Map()
1103
+ };
1104
+ await ensureExtensionRelayForProfiles({
1105
+ resolved,
1106
+ onWarn: (message) => logService.warn(message)
1107
+ });
1108
+ logService.info(
1109
+ `Browser control service ready (profiles=${Object.keys(resolved.profiles).length})`
1110
+ );
1111
+ return state;
1112
+ }
1113
+
1114
+ // src/browser/routes/agent.act.shared.ts
1115
+ var ACT_KINDS = [
1116
+ "click",
1117
+ "close",
1118
+ "drag",
1119
+ "evaluate",
1120
+ "fill",
1121
+ "hover",
1122
+ "scrollIntoView",
1123
+ "press",
1124
+ "resize",
1125
+ "select",
1126
+ "type",
1127
+ "wait"
1128
+ ];
1129
+ function isActKind(value) {
1130
+ if (typeof value !== "string") {
1131
+ return false;
1132
+ }
1133
+ return ACT_KINDS.includes(value);
1134
+ }
1135
+ var ALLOWED_CLICK_MODIFIERS = /* @__PURE__ */ new Set([
1136
+ "Alt",
1137
+ "Control",
1138
+ "ControlOrMeta",
1139
+ "Meta",
1140
+ "Shift"
1141
+ ]);
1142
+ function parseClickButton(raw) {
1143
+ if (raw === "left" || raw === "right" || raw === "middle") {
1144
+ return raw;
1145
+ }
1146
+ return void 0;
1147
+ }
1148
+ function parseClickModifiers(raw) {
1149
+ const invalid = raw.filter((m) => !ALLOWED_CLICK_MODIFIERS.has(m));
1150
+ if (invalid.length) {
1151
+ return { error: "modifiers must be Alt|Control|ControlOrMeta|Meta|Shift" };
1152
+ }
1153
+ return { modifiers: raw.length ? raw : void 0 };
1154
+ }
1155
+
1156
+ // src/browser/routes/utils.ts
1157
+ function getProfileContext(req, ctx) {
1158
+ let profileName;
1159
+ if (typeof req.query.profile === "string") {
1160
+ profileName = req.query.profile.trim() || void 0;
1161
+ }
1162
+ if (!profileName && req.body && typeof req.body === "object") {
1163
+ const body = req.body;
1164
+ if (typeof body.profile === "string") {
1165
+ profileName = body.profile.trim() || void 0;
1166
+ }
1167
+ }
1168
+ try {
1169
+ return ctx.forProfile(profileName);
1170
+ } catch (err) {
1171
+ return { error: String(err), status: 404 };
1172
+ }
1173
+ }
1174
+ function jsonError(res, status, message) {
1175
+ res.status(status).json({ error: message });
1176
+ }
1177
+ function toStringOrEmpty(value) {
1178
+ if (typeof value === "string") {
1179
+ return value.trim();
1180
+ }
1181
+ if (typeof value === "number" || typeof value === "boolean") {
1182
+ return String(value).trim();
1183
+ }
1184
+ return "";
1185
+ }
1186
+ function toNumber(value) {
1187
+ if (typeof value === "number" && Number.isFinite(value)) {
1188
+ return value;
1189
+ }
1190
+ if (typeof value === "string" && value.trim()) {
1191
+ const parsed = Number(value);
1192
+ return Number.isFinite(parsed) ? parsed : void 0;
1193
+ }
1194
+ return void 0;
1195
+ }
1196
+ function toBoolean(value) {
1197
+ return parseBooleanValue(value, {
1198
+ truthy: ["true", "1", "yes"],
1199
+ falsy: ["false", "0", "no"]
1200
+ });
1201
+ }
1202
+ function toStringArray(value) {
1203
+ if (!Array.isArray(value)) {
1204
+ return void 0;
1205
+ }
1206
+ const strings = value.map((v) => toStringOrEmpty(v)).filter(Boolean);
1207
+ return strings.length ? strings : void 0;
1208
+ }
1209
+
1210
+ // src/browser/routes/agent.shared.ts
1211
+ var SELECTOR_UNSUPPORTED_MESSAGE = [
1212
+ "Error: 'selector' is not supported. Use 'ref' from snapshot instead.",
1213
+ "",
1214
+ "Example workflow:",
1215
+ "1. snapshot action to get page state with refs",
1216
+ '2. act with ref: "e123" to interact with element',
1217
+ "",
1218
+ "This is more reliable for modern SPAs."
1219
+ ].join("\n");
1220
+ function readBody(req) {
1221
+ const body = req.body;
1222
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
1223
+ return {};
1224
+ }
1225
+ return body;
1226
+ }
1227
+ function resolveTargetIdFromBody(body) {
1228
+ const targetId = typeof body.targetId === "string" ? body.targetId.trim() : "";
1229
+ return targetId || void 0;
1230
+ }
1231
+ function resolveTargetIdFromQuery(query) {
1232
+ const targetId = typeof query.targetId === "string" ? query.targetId.trim() : "";
1233
+ return targetId || void 0;
1234
+ }
1235
+ function handleRouteError(ctx, res, err) {
1236
+ const mapped = ctx.mapTabError(err);
1237
+ if (mapped) {
1238
+ return jsonError(res, mapped.status, mapped.message);
1239
+ }
1240
+ jsonError(res, 500, String(err));
1241
+ }
1242
+ function resolveProfileContext(req, res, ctx) {
1243
+ const profileCtx = getProfileContext(req, ctx);
1244
+ if ("error" in profileCtx) {
1245
+ jsonError(res, profileCtx.status, profileCtx.error);
1246
+ return null;
1247
+ }
1248
+ return profileCtx;
1249
+ }
1250
+ async function getPwAiModule2() {
1251
+ return await getPwAiModule({ mode: "soft" });
1252
+ }
1253
+ async function requirePwAi(res, feature) {
1254
+ const mod = await getPwAiModule2();
1255
+ if (mod) {
1256
+ return mod;
1257
+ }
1258
+ jsonError(
1259
+ res,
1260
+ 501,
1261
+ [
1262
+ `Playwright is not available in this gateway build; '${feature}' is unsupported.`,
1263
+ "Install the full Playwright package (not playwright-core) and restart the gateway, or reinstall with browser support.",
1264
+ "Docs: /tools/browser#playwright-requirement"
1265
+ ].join("\n")
1266
+ );
1267
+ return null;
1268
+ }
1269
+ async function withRouteTabContext(params) {
1270
+ const profileCtx = resolveProfileContext(params.req, params.res, params.ctx);
1271
+ if (!profileCtx) {
1272
+ return void 0;
1273
+ }
1274
+ try {
1275
+ const tab = await profileCtx.ensureTabAvailable(params.targetId);
1276
+ return await params.run({
1277
+ profileCtx,
1278
+ tab,
1279
+ cdpUrl: profileCtx.profile.cdpUrl
1280
+ });
1281
+ } catch (err) {
1282
+ handleRouteError(params.ctx, params.res, err);
1283
+ return void 0;
1284
+ }
1285
+ }
1286
+ async function withPlaywrightRouteContext(params) {
1287
+ return await withRouteTabContext({
1288
+ req: params.req,
1289
+ res: params.res,
1290
+ ctx: params.ctx,
1291
+ targetId: params.targetId,
1292
+ run: async ({ profileCtx, tab, cdpUrl }) => {
1293
+ const pw = await requirePwAi(params.res, params.feature);
1294
+ if (!pw) {
1295
+ return void 0;
1296
+ }
1297
+ return await params.run({ profileCtx, tab, cdpUrl, pw });
1298
+ }
1299
+ });
1300
+ }
1301
+
1302
+ // src/browser/paths.ts
1303
+ import path2 from "path";
1304
+ var DEFAULT_BROWSER_TMP_DIR = resolvePreferredAgenticMailTmpDir();
1305
+ var DEFAULT_TRACE_DIR = DEFAULT_BROWSER_TMP_DIR;
1306
+ var DEFAULT_DOWNLOAD_DIR = path2.join(DEFAULT_BROWSER_TMP_DIR, "downloads");
1307
+ var DEFAULT_UPLOAD_DIR2 = path2.join(DEFAULT_BROWSER_TMP_DIR, "uploads");
1308
+ function resolvePathWithinRoot(params) {
1309
+ const root = path2.resolve(params.rootDir);
1310
+ const raw = params.requestedPath.trim();
1311
+ if (!raw) {
1312
+ if (!params.defaultFileName) {
1313
+ return { ok: false, error: "path is required" };
1314
+ }
1315
+ return { ok: true, path: path2.join(root, params.defaultFileName) };
1316
+ }
1317
+ const resolved = path2.resolve(root, raw);
1318
+ const rel = path2.relative(root, resolved);
1319
+ if (!rel || rel.startsWith("..") || path2.isAbsolute(rel)) {
1320
+ return { ok: false, error: `Invalid path: must stay within ${params.scopeLabel}` };
1321
+ }
1322
+ return { ok: true, path: resolved };
1323
+ }
1324
+ function resolvePathsWithinRoot2(params) {
1325
+ const resolvedPaths = [];
1326
+ for (const raw of params.requestedPaths) {
1327
+ const pathResult = resolvePathWithinRoot({
1328
+ rootDir: params.rootDir,
1329
+ requestedPath: raw,
1330
+ scopeLabel: params.scopeLabel
1331
+ });
1332
+ if (!pathResult.ok) {
1333
+ return { ok: false, error: pathResult.error };
1334
+ }
1335
+ resolvedPaths.push(pathResult.path);
1336
+ }
1337
+ return { ok: true, paths: resolvedPaths };
1338
+ }
1339
+
1340
+ // src/browser/routes/agent.act.ts
1341
+ function resolveDownloadPathOrRespond(res, requestedPath) {
1342
+ const downloadPathResult = resolvePathWithinRoot({
1343
+ rootDir: DEFAULT_DOWNLOAD_DIR,
1344
+ requestedPath,
1345
+ scopeLabel: "downloads directory"
1346
+ });
1347
+ if (!downloadPathResult.ok) {
1348
+ res.status(400).json({ error: downloadPathResult.error });
1349
+ return null;
1350
+ }
1351
+ return downloadPathResult.path;
1352
+ }
1353
+ function buildDownloadRequestBase(cdpUrl, targetId, timeoutMs) {
1354
+ return {
1355
+ cdpUrl,
1356
+ targetId,
1357
+ timeoutMs: timeoutMs ?? void 0
1358
+ };
1359
+ }
1360
+ function respondWithDownloadResult(res, targetId, result) {
1361
+ res.json({ ok: true, targetId, download: result });
1362
+ }
1363
+ function registerBrowserAgentActRoutes(app, ctx) {
1364
+ app.post("/act", async (req, res) => {
1365
+ const body = readBody(req);
1366
+ const kindRaw = toStringOrEmpty(body.kind);
1367
+ if (!isActKind(kindRaw)) {
1368
+ return jsonError(res, 400, "kind is required");
1369
+ }
1370
+ const kind = kindRaw;
1371
+ const targetId = resolveTargetIdFromBody(body);
1372
+ if (Object.hasOwn(body, "selector") && kind !== "wait") {
1373
+ return jsonError(res, 400, SELECTOR_UNSUPPORTED_MESSAGE);
1374
+ }
1375
+ await withPlaywrightRouteContext({
1376
+ req,
1377
+ res,
1378
+ ctx,
1379
+ targetId,
1380
+ feature: `act:${kind}`,
1381
+ run: async ({ cdpUrl, tab, pw }) => {
1382
+ const evaluateEnabled = ctx.state().resolved.evaluateEnabled;
1383
+ switch (kind) {
1384
+ case "click": {
1385
+ const ref = toStringOrEmpty(body.ref);
1386
+ if (!ref) {
1387
+ return jsonError(res, 400, "ref is required");
1388
+ }
1389
+ const doubleClick = toBoolean(body.doubleClick) ?? false;
1390
+ const timeoutMs = toNumber(body.timeoutMs);
1391
+ const buttonRaw = toStringOrEmpty(body.button) || "";
1392
+ const button = buttonRaw ? parseClickButton(buttonRaw) : void 0;
1393
+ if (buttonRaw && !button) {
1394
+ return jsonError(res, 400, "button must be left|right|middle");
1395
+ }
1396
+ const modifiersRaw = toStringArray(body.modifiers) ?? [];
1397
+ const parsedModifiers = parseClickModifiers(modifiersRaw);
1398
+ if (parsedModifiers.error) {
1399
+ return jsonError(res, 400, parsedModifiers.error);
1400
+ }
1401
+ const modifiers = parsedModifiers.modifiers;
1402
+ const clickRequest = {
1403
+ cdpUrl,
1404
+ targetId: tab.targetId,
1405
+ ref,
1406
+ doubleClick
1407
+ };
1408
+ if (button) {
1409
+ clickRequest.button = button;
1410
+ }
1411
+ if (modifiers) {
1412
+ clickRequest.modifiers = modifiers;
1413
+ }
1414
+ if (timeoutMs) {
1415
+ clickRequest.timeoutMs = timeoutMs;
1416
+ }
1417
+ await pw.clickViaPlaywright(clickRequest);
1418
+ return res.json({ ok: true, targetId: tab.targetId, url: tab.url });
1419
+ }
1420
+ case "type": {
1421
+ const ref = toStringOrEmpty(body.ref);
1422
+ if (!ref) {
1423
+ return jsonError(res, 400, "ref is required");
1424
+ }
1425
+ if (typeof body.text !== "string") {
1426
+ return jsonError(res, 400, "text is required");
1427
+ }
1428
+ const text = body.text;
1429
+ const submit = toBoolean(body.submit) ?? false;
1430
+ const slowly = toBoolean(body.slowly) ?? false;
1431
+ const timeoutMs = toNumber(body.timeoutMs);
1432
+ const typeRequest = {
1433
+ cdpUrl,
1434
+ targetId: tab.targetId,
1435
+ ref,
1436
+ text,
1437
+ submit,
1438
+ slowly
1439
+ };
1440
+ if (timeoutMs) {
1441
+ typeRequest.timeoutMs = timeoutMs;
1442
+ }
1443
+ await pw.typeViaPlaywright(typeRequest);
1444
+ return res.json({ ok: true, targetId: tab.targetId });
1445
+ }
1446
+ case "press": {
1447
+ const key = toStringOrEmpty(body.key);
1448
+ if (!key) {
1449
+ return jsonError(res, 400, "key is required");
1450
+ }
1451
+ const delayMs = toNumber(body.delayMs);
1452
+ await pw.pressKeyViaPlaywright({
1453
+ cdpUrl,
1454
+ targetId: tab.targetId,
1455
+ key,
1456
+ delayMs: delayMs ?? void 0
1457
+ });
1458
+ return res.json({ ok: true, targetId: tab.targetId });
1459
+ }
1460
+ case "hover": {
1461
+ const ref = toStringOrEmpty(body.ref);
1462
+ if (!ref) {
1463
+ return jsonError(res, 400, "ref is required");
1464
+ }
1465
+ const timeoutMs = toNumber(body.timeoutMs);
1466
+ await pw.hoverViaPlaywright({
1467
+ cdpUrl,
1468
+ targetId: tab.targetId,
1469
+ ref,
1470
+ timeoutMs: timeoutMs ?? void 0
1471
+ });
1472
+ return res.json({ ok: true, targetId: tab.targetId });
1473
+ }
1474
+ case "scrollIntoView": {
1475
+ const ref = toStringOrEmpty(body.ref);
1476
+ if (!ref) {
1477
+ return jsonError(res, 400, "ref is required");
1478
+ }
1479
+ const timeoutMs = toNumber(body.timeoutMs);
1480
+ const scrollRequest = {
1481
+ cdpUrl,
1482
+ targetId: tab.targetId,
1483
+ ref
1484
+ };
1485
+ if (timeoutMs) {
1486
+ scrollRequest.timeoutMs = timeoutMs;
1487
+ }
1488
+ await pw.scrollIntoViewViaPlaywright(scrollRequest);
1489
+ return res.json({ ok: true, targetId: tab.targetId });
1490
+ }
1491
+ case "drag": {
1492
+ const startRef = toStringOrEmpty(body.startRef);
1493
+ const endRef = toStringOrEmpty(body.endRef);
1494
+ if (!startRef || !endRef) {
1495
+ return jsonError(res, 400, "startRef and endRef are required");
1496
+ }
1497
+ const timeoutMs = toNumber(body.timeoutMs);
1498
+ await pw.dragViaPlaywright({
1499
+ cdpUrl,
1500
+ targetId: tab.targetId,
1501
+ startRef,
1502
+ endRef,
1503
+ timeoutMs: timeoutMs ?? void 0
1504
+ });
1505
+ return res.json({ ok: true, targetId: tab.targetId });
1506
+ }
1507
+ case "select": {
1508
+ const ref = toStringOrEmpty(body.ref);
1509
+ const values = toStringArray(body.values);
1510
+ if (!ref || !values?.length) {
1511
+ return jsonError(res, 400, "ref and values are required");
1512
+ }
1513
+ const timeoutMs = toNumber(body.timeoutMs);
1514
+ await pw.selectOptionViaPlaywright({
1515
+ cdpUrl,
1516
+ targetId: tab.targetId,
1517
+ ref,
1518
+ values,
1519
+ timeoutMs: timeoutMs ?? void 0
1520
+ });
1521
+ return res.json({ ok: true, targetId: tab.targetId });
1522
+ }
1523
+ case "fill": {
1524
+ const rawFields = Array.isArray(body.fields) ? body.fields : [];
1525
+ const fields = rawFields.map((field) => {
1526
+ if (!field || typeof field !== "object") {
1527
+ return null;
1528
+ }
1529
+ const rec = field;
1530
+ const ref = toStringOrEmpty(rec.ref);
1531
+ const type = toStringOrEmpty(rec.type);
1532
+ if (!ref || !type) {
1533
+ return null;
1534
+ }
1535
+ const value = typeof rec.value === "string" || typeof rec.value === "number" || typeof rec.value === "boolean" ? rec.value : void 0;
1536
+ const parsed = value === void 0 ? { ref, type } : { ref, type, value };
1537
+ return parsed;
1538
+ }).filter((field) => field !== null);
1539
+ if (!fields.length) {
1540
+ return jsonError(res, 400, "fields are required");
1541
+ }
1542
+ const timeoutMs = toNumber(body.timeoutMs);
1543
+ await pw.fillFormViaPlaywright({
1544
+ cdpUrl,
1545
+ targetId: tab.targetId,
1546
+ fields,
1547
+ timeoutMs: timeoutMs ?? void 0
1548
+ });
1549
+ return res.json({ ok: true, targetId: tab.targetId });
1550
+ }
1551
+ case "resize": {
1552
+ const width = toNumber(body.width);
1553
+ const height = toNumber(body.height);
1554
+ if (!width || !height) {
1555
+ return jsonError(res, 400, "width and height are required");
1556
+ }
1557
+ await pw.resizeViewportViaPlaywright({
1558
+ cdpUrl,
1559
+ targetId: tab.targetId,
1560
+ width,
1561
+ height
1562
+ });
1563
+ return res.json({ ok: true, targetId: tab.targetId, url: tab.url });
1564
+ }
1565
+ case "wait": {
1566
+ const timeMs = toNumber(body.timeMs);
1567
+ const text = toStringOrEmpty(body.text) || void 0;
1568
+ const textGone = toStringOrEmpty(body.textGone) || void 0;
1569
+ const selector = toStringOrEmpty(body.selector) || void 0;
1570
+ const url = toStringOrEmpty(body.url) || void 0;
1571
+ const loadStateRaw = toStringOrEmpty(body.loadState);
1572
+ const loadState = loadStateRaw === "load" || loadStateRaw === "domcontentloaded" || loadStateRaw === "networkidle" ? loadStateRaw : void 0;
1573
+ const fn = toStringOrEmpty(body.fn) || void 0;
1574
+ const timeoutMs = toNumber(body.timeoutMs) ?? void 0;
1575
+ if (fn && !evaluateEnabled) {
1576
+ return jsonError(
1577
+ res,
1578
+ 403,
1579
+ [
1580
+ "wait --fn is disabled by config (browser.evaluateEnabled=false).",
1581
+ "Docs: /gateway/configuration#browser-agenticmail-managed-browser"
1582
+ ].join("\n")
1583
+ );
1584
+ }
1585
+ if (timeMs === void 0 && !text && !textGone && !selector && !url && !loadState && !fn) {
1586
+ return jsonError(
1587
+ res,
1588
+ 400,
1589
+ "wait requires at least one of: timeMs, text, textGone, selector, url, loadState, fn"
1590
+ );
1591
+ }
1592
+ await pw.waitForViaPlaywright({
1593
+ cdpUrl,
1594
+ targetId: tab.targetId,
1595
+ timeMs,
1596
+ text,
1597
+ textGone,
1598
+ selector,
1599
+ url,
1600
+ loadState,
1601
+ fn,
1602
+ timeoutMs
1603
+ });
1604
+ return res.json({ ok: true, targetId: tab.targetId });
1605
+ }
1606
+ case "evaluate": {
1607
+ if (!evaluateEnabled) {
1608
+ return jsonError(
1609
+ res,
1610
+ 403,
1611
+ [
1612
+ "act:evaluate is disabled by config (browser.evaluateEnabled=false).",
1613
+ "Docs: /gateway/configuration#browser-agenticmail-managed-browser"
1614
+ ].join("\n")
1615
+ );
1616
+ }
1617
+ const fn = toStringOrEmpty(body.fn);
1618
+ if (!fn) {
1619
+ return jsonError(res, 400, "fn is required");
1620
+ }
1621
+ const ref = toStringOrEmpty(body.ref) || void 0;
1622
+ const evalTimeoutMs = toNumber(body.timeoutMs);
1623
+ const evalRequest = {
1624
+ cdpUrl,
1625
+ targetId: tab.targetId,
1626
+ fn,
1627
+ ref,
1628
+ signal: req.signal
1629
+ };
1630
+ if (evalTimeoutMs !== void 0) {
1631
+ evalRequest.timeoutMs = evalTimeoutMs;
1632
+ }
1633
+ const result = await pw.evaluateViaPlaywright(evalRequest);
1634
+ return res.json({
1635
+ ok: true,
1636
+ targetId: tab.targetId,
1637
+ url: tab.url,
1638
+ result
1639
+ });
1640
+ }
1641
+ case "close": {
1642
+ await pw.closePageViaPlaywright({ cdpUrl, targetId: tab.targetId });
1643
+ return res.json({ ok: true, targetId: tab.targetId });
1644
+ }
1645
+ default: {
1646
+ return jsonError(res, 400, "unsupported kind");
1647
+ }
1648
+ }
1649
+ }
1650
+ });
1651
+ });
1652
+ app.post("/hooks/file-chooser", async (req, res) => {
1653
+ const body = readBody(req);
1654
+ const targetId = resolveTargetIdFromBody(body);
1655
+ const ref = toStringOrEmpty(body.ref) || void 0;
1656
+ const inputRef = toStringOrEmpty(body.inputRef) || void 0;
1657
+ const element = toStringOrEmpty(body.element) || void 0;
1658
+ const paths = toStringArray(body.paths) ?? [];
1659
+ const timeoutMs = toNumber(body.timeoutMs);
1660
+ if (!paths.length) {
1661
+ return jsonError(res, 400, "paths are required");
1662
+ }
1663
+ await withPlaywrightRouteContext({
1664
+ req,
1665
+ res,
1666
+ ctx,
1667
+ targetId,
1668
+ feature: "file chooser hook",
1669
+ run: async ({ cdpUrl, tab, pw }) => {
1670
+ const uploadPathsResult = resolvePathsWithinRoot2({
1671
+ rootDir: DEFAULT_UPLOAD_DIR2,
1672
+ requestedPaths: paths,
1673
+ scopeLabel: `uploads directory (${DEFAULT_UPLOAD_DIR2})`
1674
+ });
1675
+ if (!uploadPathsResult.ok) {
1676
+ res.status(400).json({ error: uploadPathsResult.error });
1677
+ return;
1678
+ }
1679
+ const resolvedPaths = uploadPathsResult.paths;
1680
+ if (inputRef || element) {
1681
+ if (ref) {
1682
+ return jsonError(res, 400, "ref cannot be combined with inputRef/element");
1683
+ }
1684
+ await pw.setInputFilesViaPlaywright({
1685
+ cdpUrl,
1686
+ targetId: tab.targetId,
1687
+ inputRef,
1688
+ element,
1689
+ paths: resolvedPaths
1690
+ });
1691
+ } else {
1692
+ await pw.armFileUploadViaPlaywright({
1693
+ cdpUrl,
1694
+ targetId: tab.targetId,
1695
+ paths: resolvedPaths,
1696
+ timeoutMs: timeoutMs ?? void 0
1697
+ });
1698
+ if (ref) {
1699
+ await pw.clickViaPlaywright({
1700
+ cdpUrl,
1701
+ targetId: tab.targetId,
1702
+ ref
1703
+ });
1704
+ }
1705
+ }
1706
+ res.json({ ok: true });
1707
+ }
1708
+ });
1709
+ });
1710
+ app.post("/hooks/dialog", async (req, res) => {
1711
+ const body = readBody(req);
1712
+ const targetId = resolveTargetIdFromBody(body);
1713
+ const accept = toBoolean(body.accept);
1714
+ const promptText = toStringOrEmpty(body.promptText) || void 0;
1715
+ const timeoutMs = toNumber(body.timeoutMs);
1716
+ if (accept === void 0) {
1717
+ return jsonError(res, 400, "accept is required");
1718
+ }
1719
+ await withPlaywrightRouteContext({
1720
+ req,
1721
+ res,
1722
+ ctx,
1723
+ targetId,
1724
+ feature: "dialog hook",
1725
+ run: async ({ cdpUrl, tab, pw }) => {
1726
+ await pw.armDialogViaPlaywright({
1727
+ cdpUrl,
1728
+ targetId: tab.targetId,
1729
+ accept,
1730
+ promptText,
1731
+ timeoutMs: timeoutMs ?? void 0
1732
+ });
1733
+ res.json({ ok: true });
1734
+ }
1735
+ });
1736
+ });
1737
+ app.post("/wait/download", async (req, res) => {
1738
+ const body = readBody(req);
1739
+ const targetId = resolveTargetIdFromBody(body);
1740
+ const out = toStringOrEmpty(body.path) || "";
1741
+ const timeoutMs = toNumber(body.timeoutMs);
1742
+ await withPlaywrightRouteContext({
1743
+ req,
1744
+ res,
1745
+ ctx,
1746
+ targetId,
1747
+ feature: "wait for download",
1748
+ run: async ({ cdpUrl, tab, pw }) => {
1749
+ let downloadPath;
1750
+ if (out.trim()) {
1751
+ const resolvedDownloadPath = resolveDownloadPathOrRespond(res, out);
1752
+ if (!resolvedDownloadPath) {
1753
+ return;
1754
+ }
1755
+ downloadPath = resolvedDownloadPath;
1756
+ }
1757
+ const requestBase = buildDownloadRequestBase(cdpUrl, tab.targetId, timeoutMs);
1758
+ const result = await pw.waitForDownloadViaPlaywright({
1759
+ ...requestBase,
1760
+ path: downloadPath
1761
+ });
1762
+ respondWithDownloadResult(res, tab.targetId, result);
1763
+ }
1764
+ });
1765
+ });
1766
+ app.post("/download", async (req, res) => {
1767
+ const body = readBody(req);
1768
+ const targetId = resolveTargetIdFromBody(body);
1769
+ const ref = toStringOrEmpty(body.ref);
1770
+ const out = toStringOrEmpty(body.path);
1771
+ const timeoutMs = toNumber(body.timeoutMs);
1772
+ if (!ref) {
1773
+ return jsonError(res, 400, "ref is required");
1774
+ }
1775
+ if (!out) {
1776
+ return jsonError(res, 400, "path is required");
1777
+ }
1778
+ await withPlaywrightRouteContext({
1779
+ req,
1780
+ res,
1781
+ ctx,
1782
+ targetId,
1783
+ feature: "download",
1784
+ run: async ({ cdpUrl, tab, pw }) => {
1785
+ const downloadPath = resolveDownloadPathOrRespond(res, out);
1786
+ if (!downloadPath) {
1787
+ return;
1788
+ }
1789
+ const requestBase = buildDownloadRequestBase(cdpUrl, tab.targetId, timeoutMs);
1790
+ const result = await pw.downloadViaPlaywright({
1791
+ ...requestBase,
1792
+ ref,
1793
+ path: downloadPath
1794
+ });
1795
+ respondWithDownloadResult(res, tab.targetId, result);
1796
+ }
1797
+ });
1798
+ });
1799
+ app.post("/response/body", async (req, res) => {
1800
+ const body = readBody(req);
1801
+ const targetId = resolveTargetIdFromBody(body);
1802
+ const url = toStringOrEmpty(body.url);
1803
+ const timeoutMs = toNumber(body.timeoutMs);
1804
+ const maxChars = toNumber(body.maxChars);
1805
+ if (!url) {
1806
+ return jsonError(res, 400, "url is required");
1807
+ }
1808
+ await withPlaywrightRouteContext({
1809
+ req,
1810
+ res,
1811
+ ctx,
1812
+ targetId,
1813
+ feature: "response body",
1814
+ run: async ({ cdpUrl, tab, pw }) => {
1815
+ const result = await pw.responseBodyViaPlaywright({
1816
+ cdpUrl,
1817
+ targetId: tab.targetId,
1818
+ url,
1819
+ timeoutMs: timeoutMs ?? void 0,
1820
+ maxChars: maxChars ?? void 0
1821
+ });
1822
+ res.json({ ok: true, targetId: tab.targetId, response: result });
1823
+ }
1824
+ });
1825
+ });
1826
+ app.post("/highlight", async (req, res) => {
1827
+ const body = readBody(req);
1828
+ const targetId = resolveTargetIdFromBody(body);
1829
+ const ref = toStringOrEmpty(body.ref);
1830
+ if (!ref) {
1831
+ return jsonError(res, 400, "ref is required");
1832
+ }
1833
+ await withPlaywrightRouteContext({
1834
+ req,
1835
+ res,
1836
+ ctx,
1837
+ targetId,
1838
+ feature: "highlight",
1839
+ run: async ({ cdpUrl, tab, pw }) => {
1840
+ await pw.highlightViaPlaywright({
1841
+ cdpUrl,
1842
+ targetId: tab.targetId,
1843
+ ref
1844
+ });
1845
+ res.json({ ok: true, targetId: tab.targetId });
1846
+ }
1847
+ });
1848
+ });
1849
+ }
1850
+
1851
+ // src/browser/routes/agent.debug.ts
1852
+ import crypto from "crypto";
1853
+ import fs3 from "fs/promises";
1854
+ import path3 from "path";
1855
+ function registerBrowserAgentDebugRoutes(app, ctx) {
1856
+ app.get("/console", async (req, res) => {
1857
+ const targetId = resolveTargetIdFromQuery(req.query);
1858
+ const level = typeof req.query.level === "string" ? req.query.level : "";
1859
+ await withPlaywrightRouteContext({
1860
+ req,
1861
+ res,
1862
+ ctx,
1863
+ targetId,
1864
+ feature: "console messages",
1865
+ run: async ({ cdpUrl, tab, pw }) => {
1866
+ const messages = await pw.getConsoleMessagesViaPlaywright({
1867
+ cdpUrl,
1868
+ targetId: tab.targetId,
1869
+ level: level.trim() || void 0
1870
+ });
1871
+ res.json({ ok: true, messages, targetId: tab.targetId });
1872
+ }
1873
+ });
1874
+ });
1875
+ app.get("/errors", async (req, res) => {
1876
+ const targetId = resolveTargetIdFromQuery(req.query);
1877
+ const clear = toBoolean(req.query.clear) ?? false;
1878
+ await withPlaywrightRouteContext({
1879
+ req,
1880
+ res,
1881
+ ctx,
1882
+ targetId,
1883
+ feature: "page errors",
1884
+ run: async ({ cdpUrl, tab, pw }) => {
1885
+ const result = await pw.getPageErrorsViaPlaywright({
1886
+ cdpUrl,
1887
+ targetId: tab.targetId,
1888
+ clear
1889
+ });
1890
+ res.json({ ok: true, targetId: tab.targetId, ...result });
1891
+ }
1892
+ });
1893
+ });
1894
+ app.get("/requests", async (req, res) => {
1895
+ const targetId = resolveTargetIdFromQuery(req.query);
1896
+ const filter = typeof req.query.filter === "string" ? req.query.filter : "";
1897
+ const clear = toBoolean(req.query.clear) ?? false;
1898
+ await withPlaywrightRouteContext({
1899
+ req,
1900
+ res,
1901
+ ctx,
1902
+ targetId,
1903
+ feature: "network requests",
1904
+ run: async ({ cdpUrl, tab, pw }) => {
1905
+ const result = await pw.getNetworkRequestsViaPlaywright({
1906
+ cdpUrl,
1907
+ targetId: tab.targetId,
1908
+ filter: filter.trim() || void 0,
1909
+ clear
1910
+ });
1911
+ res.json({ ok: true, targetId: tab.targetId, ...result });
1912
+ }
1913
+ });
1914
+ });
1915
+ app.post("/trace/start", async (req, res) => {
1916
+ const body = readBody(req);
1917
+ const targetId = resolveTargetIdFromBody(body);
1918
+ const screenshots = toBoolean(body.screenshots) ?? void 0;
1919
+ const snapshots = toBoolean(body.snapshots) ?? void 0;
1920
+ const sources = toBoolean(body.sources) ?? void 0;
1921
+ await withPlaywrightRouteContext({
1922
+ req,
1923
+ res,
1924
+ ctx,
1925
+ targetId,
1926
+ feature: "trace start",
1927
+ run: async ({ cdpUrl, tab, pw }) => {
1928
+ await pw.traceStartViaPlaywright({
1929
+ cdpUrl,
1930
+ targetId: tab.targetId,
1931
+ screenshots,
1932
+ snapshots,
1933
+ sources
1934
+ });
1935
+ res.json({ ok: true, targetId: tab.targetId });
1936
+ }
1937
+ });
1938
+ });
1939
+ app.post("/trace/stop", async (req, res) => {
1940
+ const body = readBody(req);
1941
+ const targetId = resolveTargetIdFromBody(body);
1942
+ const out = toStringOrEmpty(body.path) || "";
1943
+ await withPlaywrightRouteContext({
1944
+ req,
1945
+ res,
1946
+ ctx,
1947
+ targetId,
1948
+ feature: "trace stop",
1949
+ run: async ({ cdpUrl, tab, pw }) => {
1950
+ const id = crypto.randomUUID();
1951
+ const dir = DEFAULT_TRACE_DIR;
1952
+ await fs3.mkdir(dir, { recursive: true });
1953
+ const tracePathResult = resolvePathWithinRoot({
1954
+ rootDir: dir,
1955
+ requestedPath: out,
1956
+ scopeLabel: "trace directory",
1957
+ defaultFileName: `browser-trace-${id}.zip`
1958
+ });
1959
+ if (!tracePathResult.ok) {
1960
+ res.status(400).json({ error: tracePathResult.error });
1961
+ return;
1962
+ }
1963
+ const tracePath = tracePathResult.path;
1964
+ await pw.traceStopViaPlaywright({
1965
+ cdpUrl,
1966
+ targetId: tab.targetId,
1967
+ path: tracePath
1968
+ });
1969
+ res.json({
1970
+ ok: true,
1971
+ targetId: tab.targetId,
1972
+ path: path3.resolve(tracePath)
1973
+ });
1974
+ }
1975
+ });
1976
+ });
1977
+ }
1978
+
1979
+ // src/browser/routes/agent.snapshot.ts
1980
+ import path4 from "path";
1981
+
1982
+ // src/browser/screenshot.ts
1983
+ var DEFAULT_BROWSER_SCREENSHOT_MAX_SIDE = 2e3;
1984
+ var DEFAULT_BROWSER_SCREENSHOT_MAX_BYTES = 5 * 1024 * 1024;
1985
+ async function normalizeBrowserScreenshot(buffer, opts) {
1986
+ const maxSide = Math.max(1, Math.round(opts?.maxSide ?? DEFAULT_BROWSER_SCREENSHOT_MAX_SIDE));
1987
+ const maxBytes = Math.max(1, Math.round(opts?.maxBytes ?? DEFAULT_BROWSER_SCREENSHOT_MAX_BYTES));
1988
+ const meta = await getImageMetadata(buffer);
1989
+ const width = Number(meta?.width ?? 0);
1990
+ const height = Number(meta?.height ?? 0);
1991
+ const maxDim = Math.max(width, height);
1992
+ if (buffer.byteLength <= maxBytes && (maxDim === 0 || width <= maxSide && height <= maxSide)) {
1993
+ return { buffer };
1994
+ }
1995
+ const sideStart = maxDim > 0 ? Math.min(maxSide, maxDim) : maxSide;
1996
+ const sideGrid = buildImageResizeSideGrid(maxSide, sideStart);
1997
+ let smallest = null;
1998
+ for (const side of sideGrid) {
1999
+ for (const quality of IMAGE_REDUCE_QUALITY_STEPS) {
2000
+ const out = await resizeToJpeg({
2001
+ buffer,
2002
+ maxSide: side,
2003
+ quality,
2004
+ withoutEnlargement: true
2005
+ });
2006
+ if (!smallest || out.byteLength < smallest.size) {
2007
+ smallest = { buffer: out, size: out.byteLength };
2008
+ }
2009
+ if (out.byteLength <= maxBytes) {
2010
+ return { buffer: out, contentType: "image/jpeg" };
2011
+ }
2012
+ }
2013
+ }
2014
+ const best = smallest?.buffer ?? buffer;
2015
+ throw new Error(
2016
+ `Browser screenshot could not be reduced below ${(maxBytes / (1024 * 1024)).toFixed(0)}MB (got ${(best.byteLength / (1024 * 1024)).toFixed(2)}MB)`
2017
+ );
2018
+ }
2019
+
2020
+ // src/browser/routes/agent.snapshot.ts
2021
+ async function saveBrowserMediaResponse(params) {
2022
+ await ensureMediaDir();
2023
+ const saved = await saveMediaBuffer(
2024
+ params.buffer,
2025
+ params.contentType,
2026
+ "browser",
2027
+ params.maxBytes
2028
+ );
2029
+ params.res.json({
2030
+ ok: true,
2031
+ path: path4.resolve(saved.path),
2032
+ targetId: params.targetId,
2033
+ url: params.url
2034
+ });
2035
+ }
2036
+ function registerBrowserAgentSnapshotRoutes(app, ctx) {
2037
+ app.post("/navigate", async (req, res) => {
2038
+ const body = readBody(req);
2039
+ const url = toStringOrEmpty(body.url);
2040
+ const targetId = toStringOrEmpty(body.targetId) || void 0;
2041
+ if (!url) {
2042
+ return jsonError(res, 400, "url is required");
2043
+ }
2044
+ await withPlaywrightRouteContext({
2045
+ req,
2046
+ res,
2047
+ ctx,
2048
+ targetId,
2049
+ feature: "navigate",
2050
+ run: async ({ cdpUrl, tab, pw }) => {
2051
+ const result = await pw.navigateViaPlaywright({
2052
+ cdpUrl,
2053
+ targetId: tab.targetId,
2054
+ url,
2055
+ ...withBrowserNavigationPolicy(ctx.state().resolved.ssrfPolicy)
2056
+ });
2057
+ res.json({ ok: true, targetId: tab.targetId, ...result });
2058
+ }
2059
+ });
2060
+ });
2061
+ app.post("/pdf", async (req, res) => {
2062
+ const body = readBody(req);
2063
+ const targetId = toStringOrEmpty(body.targetId) || void 0;
2064
+ await withPlaywrightRouteContext({
2065
+ req,
2066
+ res,
2067
+ ctx,
2068
+ targetId,
2069
+ feature: "pdf",
2070
+ run: async ({ cdpUrl, tab, pw }) => {
2071
+ const pdf = await pw.pdfViaPlaywright({
2072
+ cdpUrl,
2073
+ targetId: tab.targetId
2074
+ });
2075
+ await saveBrowserMediaResponse({
2076
+ res,
2077
+ buffer: pdf.buffer,
2078
+ contentType: "application/pdf",
2079
+ maxBytes: pdf.buffer.byteLength,
2080
+ targetId: tab.targetId,
2081
+ url: tab.url
2082
+ });
2083
+ }
2084
+ });
2085
+ });
2086
+ app.post("/screenshot", async (req, res) => {
2087
+ const body = readBody(req);
2088
+ const targetId = toStringOrEmpty(body.targetId) || void 0;
2089
+ const fullPage = toBoolean(body.fullPage) ?? false;
2090
+ const ref = toStringOrEmpty(body.ref) || void 0;
2091
+ const element = toStringOrEmpty(body.element) || void 0;
2092
+ const type = body.type === "jpeg" ? "jpeg" : "png";
2093
+ if (fullPage && (ref || element)) {
2094
+ return jsonError(res, 400, "fullPage is not supported for element screenshots");
2095
+ }
2096
+ await withRouteTabContext({
2097
+ req,
2098
+ res,
2099
+ ctx,
2100
+ targetId,
2101
+ run: async ({ profileCtx, tab, cdpUrl }) => {
2102
+ let buffer;
2103
+ const shouldUsePlaywright = profileCtx.profile.driver === "extension" || !tab.wsUrl || Boolean(ref) || Boolean(element);
2104
+ if (shouldUsePlaywright) {
2105
+ const pw = await requirePwAi(res, "screenshot");
2106
+ if (!pw) {
2107
+ return;
2108
+ }
2109
+ const snap = await pw.takeScreenshotViaPlaywright({
2110
+ cdpUrl,
2111
+ targetId: tab.targetId,
2112
+ ref,
2113
+ element,
2114
+ fullPage,
2115
+ type
2116
+ });
2117
+ buffer = snap.buffer;
2118
+ } else {
2119
+ buffer = await captureScreenshot({
2120
+ wsUrl: tab.wsUrl ?? "",
2121
+ fullPage,
2122
+ format: type,
2123
+ quality: type === "jpeg" ? 85 : void 0
2124
+ });
2125
+ }
2126
+ const normalized = await normalizeBrowserScreenshot(buffer, {
2127
+ maxSide: DEFAULT_BROWSER_SCREENSHOT_MAX_SIDE,
2128
+ maxBytes: DEFAULT_BROWSER_SCREENSHOT_MAX_BYTES
2129
+ });
2130
+ await saveBrowserMediaResponse({
2131
+ res,
2132
+ buffer: normalized.buffer,
2133
+ contentType: normalized.contentType ?? `image/${type}`,
2134
+ maxBytes: DEFAULT_BROWSER_SCREENSHOT_MAX_BYTES,
2135
+ targetId: tab.targetId,
2136
+ url: tab.url
2137
+ });
2138
+ }
2139
+ });
2140
+ });
2141
+ app.get("/snapshot", async (req, res) => {
2142
+ const profileCtx = resolveProfileContext(req, res, ctx);
2143
+ if (!profileCtx) {
2144
+ return;
2145
+ }
2146
+ const targetId = typeof req.query.targetId === "string" ? req.query.targetId.trim() : "";
2147
+ const mode = req.query.mode === "efficient" ? "efficient" : void 0;
2148
+ const labels = toBoolean(req.query.labels) ?? void 0;
2149
+ const explicitFormat = req.query.format === "aria" ? "aria" : req.query.format === "ai" ? "ai" : void 0;
2150
+ const format = explicitFormat ?? (mode ? "ai" : await getPwAiModule2() ? "ai" : "aria");
2151
+ const limitRaw = typeof req.query.limit === "string" ? Number(req.query.limit) : void 0;
2152
+ const hasMaxChars = Object.hasOwn(req.query, "maxChars");
2153
+ const maxCharsRaw = typeof req.query.maxChars === "string" ? Number(req.query.maxChars) : void 0;
2154
+ const limit = Number.isFinite(limitRaw) ? limitRaw : void 0;
2155
+ const maxChars = typeof maxCharsRaw === "number" && Number.isFinite(maxCharsRaw) && maxCharsRaw > 0 ? Math.floor(maxCharsRaw) : void 0;
2156
+ const resolvedMaxChars = format === "ai" ? hasMaxChars ? maxChars : mode === "efficient" ? DEFAULT_AI_SNAPSHOT_EFFICIENT_MAX_CHARS : DEFAULT_AI_SNAPSHOT_MAX_CHARS : void 0;
2157
+ const interactiveRaw = toBoolean(req.query.interactive);
2158
+ const compactRaw = toBoolean(req.query.compact);
2159
+ const depthRaw = toNumber(req.query.depth);
2160
+ const refsModeRaw = toStringOrEmpty(req.query.refs).trim();
2161
+ const refsMode = refsModeRaw === "aria" ? "aria" : refsModeRaw === "role" ? "role" : void 0;
2162
+ const interactive = interactiveRaw ?? (mode === "efficient" ? true : void 0);
2163
+ const compact = compactRaw ?? (mode === "efficient" ? true : void 0);
2164
+ const depth = depthRaw ?? (mode === "efficient" ? DEFAULT_AI_SNAPSHOT_EFFICIENT_DEPTH : void 0);
2165
+ const selector = toStringOrEmpty(req.query.selector);
2166
+ const frameSelector = toStringOrEmpty(req.query.frame);
2167
+ const selectorValue = selector.trim() || void 0;
2168
+ const frameSelectorValue = frameSelector.trim() || void 0;
2169
+ try {
2170
+ const tab = await profileCtx.ensureTabAvailable(targetId || void 0);
2171
+ if ((labels || mode === "efficient") && format === "aria") {
2172
+ return jsonError(res, 400, "labels/mode=efficient require format=ai");
2173
+ }
2174
+ if (format === "ai") {
2175
+ const pw = await requirePwAi(res, "ai snapshot");
2176
+ if (!pw) {
2177
+ return;
2178
+ }
2179
+ const wantsRoleSnapshot = labels === true || mode === "efficient" || interactive === true || compact === true || depth !== void 0 || Boolean(selectorValue) || Boolean(frameSelectorValue);
2180
+ const roleSnapshotArgs = {
2181
+ cdpUrl: profileCtx.profile.cdpUrl,
2182
+ targetId: tab.targetId,
2183
+ selector: selectorValue,
2184
+ frameSelector: frameSelectorValue,
2185
+ refsMode,
2186
+ options: {
2187
+ interactive: interactive ?? void 0,
2188
+ compact: compact ?? void 0,
2189
+ maxDepth: depth ?? void 0
2190
+ }
2191
+ };
2192
+ const snap2 = wantsRoleSnapshot ? await pw.snapshotRoleViaPlaywright(roleSnapshotArgs) : await pw.snapshotAiViaPlaywright({
2193
+ cdpUrl: profileCtx.profile.cdpUrl,
2194
+ targetId: tab.targetId,
2195
+ ...typeof resolvedMaxChars === "number" ? { maxChars: resolvedMaxChars } : {}
2196
+ }).catch(async (err) => {
2197
+ if (String(err).toLowerCase().includes("_snapshotforai")) {
2198
+ return await pw.snapshotRoleViaPlaywright(roleSnapshotArgs);
2199
+ }
2200
+ throw err;
2201
+ });
2202
+ if (labels) {
2203
+ const labeled = await pw.screenshotWithLabelsViaPlaywright({
2204
+ cdpUrl: profileCtx.profile.cdpUrl,
2205
+ targetId: tab.targetId,
2206
+ refs: "refs" in snap2 ? snap2.refs : {},
2207
+ type: "png"
2208
+ });
2209
+ const normalized = await normalizeBrowserScreenshot(labeled.buffer, {
2210
+ maxSide: DEFAULT_BROWSER_SCREENSHOT_MAX_SIDE,
2211
+ maxBytes: DEFAULT_BROWSER_SCREENSHOT_MAX_BYTES
2212
+ });
2213
+ await ensureMediaDir();
2214
+ const saved = await saveMediaBuffer(
2215
+ normalized.buffer,
2216
+ normalized.contentType ?? "image/png",
2217
+ "browser",
2218
+ DEFAULT_BROWSER_SCREENSHOT_MAX_BYTES
2219
+ );
2220
+ const imageType = normalized.contentType?.includes("jpeg") ? "jpeg" : "png";
2221
+ return res.json({
2222
+ ok: true,
2223
+ format,
2224
+ targetId: tab.targetId,
2225
+ url: tab.url,
2226
+ labels: true,
2227
+ labelsCount: labeled.labels,
2228
+ labelsSkipped: labeled.skipped,
2229
+ imagePath: path4.resolve(saved.path),
2230
+ imageType,
2231
+ ...snap2
2232
+ });
2233
+ }
2234
+ return res.json({
2235
+ ok: true,
2236
+ format,
2237
+ targetId: tab.targetId,
2238
+ url: tab.url,
2239
+ ...snap2
2240
+ });
2241
+ }
2242
+ const snap = profileCtx.profile.driver === "extension" || !tab.wsUrl ? (() => {
2243
+ return requirePwAi(res, "aria snapshot").then(async (pw) => {
2244
+ if (!pw) {
2245
+ return null;
2246
+ }
2247
+ return await pw.snapshotAriaViaPlaywright({
2248
+ cdpUrl: profileCtx.profile.cdpUrl,
2249
+ targetId: tab.targetId,
2250
+ limit
2251
+ });
2252
+ });
2253
+ })() : snapshotAria({ wsUrl: tab.wsUrl ?? "", limit });
2254
+ const resolved = await Promise.resolve(snap);
2255
+ if (!resolved) {
2256
+ return;
2257
+ }
2258
+ return res.json({
2259
+ ok: true,
2260
+ format,
2261
+ targetId: tab.targetId,
2262
+ url: tab.url,
2263
+ ...resolved
2264
+ });
2265
+ } catch (err) {
2266
+ handleRouteError(ctx, res, err);
2267
+ }
2268
+ });
2269
+ }
2270
+
2271
+ // src/browser/routes/agent.storage.ts
2272
+ function parseStorageKind(raw) {
2273
+ if (raw === "local" || raw === "session") {
2274
+ return raw;
2275
+ }
2276
+ return null;
2277
+ }
2278
+ function parseStorageMutationRequest(kindParam, body) {
2279
+ return {
2280
+ kind: parseStorageKind(toStringOrEmpty(kindParam)),
2281
+ targetId: resolveTargetIdFromBody(body)
2282
+ };
2283
+ }
2284
+ function parseRequiredStorageMutationRequest(kindParam, body) {
2285
+ const parsed = parseStorageMutationRequest(kindParam, body);
2286
+ if (!parsed.kind) {
2287
+ return null;
2288
+ }
2289
+ return {
2290
+ kind: parsed.kind,
2291
+ targetId: parsed.targetId
2292
+ };
2293
+ }
2294
+ function parseStorageMutationOrRespond(res, kindParam, body) {
2295
+ const parsed = parseRequiredStorageMutationRequest(kindParam, body);
2296
+ if (!parsed) {
2297
+ jsonError(res, 400, "kind must be local|session");
2298
+ return null;
2299
+ }
2300
+ return parsed;
2301
+ }
2302
+ function parseStorageMutationFromRequest(req, res) {
2303
+ const body = readBody(req);
2304
+ const parsed = parseStorageMutationOrRespond(res, req.params.kind, body);
2305
+ if (!parsed) {
2306
+ return null;
2307
+ }
2308
+ return { body, parsed };
2309
+ }
2310
+ function registerBrowserAgentStorageRoutes(app, ctx) {
2311
+ app.get("/cookies", async (req, res) => {
2312
+ const targetId = resolveTargetIdFromQuery(req.query);
2313
+ await withPlaywrightRouteContext({
2314
+ req,
2315
+ res,
2316
+ ctx,
2317
+ targetId,
2318
+ feature: "cookies",
2319
+ run: async ({ cdpUrl, tab, pw }) => {
2320
+ const result = await pw.cookiesGetViaPlaywright({
2321
+ cdpUrl,
2322
+ targetId: tab.targetId
2323
+ });
2324
+ res.json({ ok: true, targetId: tab.targetId, ...result });
2325
+ }
2326
+ });
2327
+ });
2328
+ app.post("/cookies/set", async (req, res) => {
2329
+ const body = readBody(req);
2330
+ const targetId = resolveTargetIdFromBody(body);
2331
+ const cookie = body.cookie && typeof body.cookie === "object" && !Array.isArray(body.cookie) ? body.cookie : null;
2332
+ if (!cookie) {
2333
+ return jsonError(res, 400, "cookie is required");
2334
+ }
2335
+ await withPlaywrightRouteContext({
2336
+ req,
2337
+ res,
2338
+ ctx,
2339
+ targetId,
2340
+ feature: "cookies set",
2341
+ run: async ({ cdpUrl, tab, pw }) => {
2342
+ await pw.cookiesSetViaPlaywright({
2343
+ cdpUrl,
2344
+ targetId: tab.targetId,
2345
+ cookie: {
2346
+ name: toStringOrEmpty(cookie.name),
2347
+ value: toStringOrEmpty(cookie.value),
2348
+ url: toStringOrEmpty(cookie.url) || void 0,
2349
+ domain: toStringOrEmpty(cookie.domain) || void 0,
2350
+ path: toStringOrEmpty(cookie.path) || void 0,
2351
+ expires: toNumber(cookie.expires) ?? void 0,
2352
+ httpOnly: toBoolean(cookie.httpOnly) ?? void 0,
2353
+ secure: toBoolean(cookie.secure) ?? void 0,
2354
+ sameSite: cookie.sameSite === "Lax" || cookie.sameSite === "None" || cookie.sameSite === "Strict" ? cookie.sameSite : void 0
2355
+ }
2356
+ });
2357
+ res.json({ ok: true, targetId: tab.targetId });
2358
+ }
2359
+ });
2360
+ });
2361
+ app.post("/cookies/clear", async (req, res) => {
2362
+ const body = readBody(req);
2363
+ const targetId = resolveTargetIdFromBody(body);
2364
+ await withPlaywrightRouteContext({
2365
+ req,
2366
+ res,
2367
+ ctx,
2368
+ targetId,
2369
+ feature: "cookies clear",
2370
+ run: async ({ cdpUrl, tab, pw }) => {
2371
+ await pw.cookiesClearViaPlaywright({
2372
+ cdpUrl,
2373
+ targetId: tab.targetId
2374
+ });
2375
+ res.json({ ok: true, targetId: tab.targetId });
2376
+ }
2377
+ });
2378
+ });
2379
+ app.get("/storage/:kind", async (req, res) => {
2380
+ const kind = parseStorageKind(toStringOrEmpty(req.params.kind));
2381
+ if (!kind) {
2382
+ return jsonError(res, 400, "kind must be local|session");
2383
+ }
2384
+ const targetId = resolveTargetIdFromQuery(req.query);
2385
+ const key = toStringOrEmpty(req.query.key);
2386
+ await withPlaywrightRouteContext({
2387
+ req,
2388
+ res,
2389
+ ctx,
2390
+ targetId,
2391
+ feature: "storage get",
2392
+ run: async ({ cdpUrl, tab, pw }) => {
2393
+ const result = await pw.storageGetViaPlaywright({
2394
+ cdpUrl,
2395
+ targetId: tab.targetId,
2396
+ kind,
2397
+ key: key.trim() || void 0
2398
+ });
2399
+ res.json({ ok: true, targetId: tab.targetId, ...result });
2400
+ }
2401
+ });
2402
+ });
2403
+ app.post("/storage/:kind/set", async (req, res) => {
2404
+ const mutation = parseStorageMutationFromRequest(req, res);
2405
+ if (!mutation) {
2406
+ return;
2407
+ }
2408
+ const key = toStringOrEmpty(mutation.body.key);
2409
+ if (!key) {
2410
+ return jsonError(res, 400, "key is required");
2411
+ }
2412
+ const value = typeof mutation.body.value === "string" ? mutation.body.value : "";
2413
+ await withPlaywrightRouteContext({
2414
+ req,
2415
+ res,
2416
+ ctx,
2417
+ targetId: mutation.parsed.targetId,
2418
+ feature: "storage set",
2419
+ run: async ({ cdpUrl, tab, pw }) => {
2420
+ await pw.storageSetViaPlaywright({
2421
+ cdpUrl,
2422
+ targetId: tab.targetId,
2423
+ kind: mutation.parsed.kind,
2424
+ key,
2425
+ value
2426
+ });
2427
+ res.json({ ok: true, targetId: tab.targetId });
2428
+ }
2429
+ });
2430
+ });
2431
+ app.post("/storage/:kind/clear", async (req, res) => {
2432
+ const mutation = parseStorageMutationFromRequest(req, res);
2433
+ if (!mutation) {
2434
+ return;
2435
+ }
2436
+ await withPlaywrightRouteContext({
2437
+ req,
2438
+ res,
2439
+ ctx,
2440
+ targetId: mutation.parsed.targetId,
2441
+ feature: "storage clear",
2442
+ run: async ({ cdpUrl, tab, pw }) => {
2443
+ await pw.storageClearViaPlaywright({
2444
+ cdpUrl,
2445
+ targetId: tab.targetId,
2446
+ kind: mutation.parsed.kind
2447
+ });
2448
+ res.json({ ok: true, targetId: tab.targetId });
2449
+ }
2450
+ });
2451
+ });
2452
+ app.post("/set/offline", async (req, res) => {
2453
+ const body = readBody(req);
2454
+ const targetId = resolveTargetIdFromBody(body);
2455
+ const offline = toBoolean(body.offline);
2456
+ if (offline === void 0) {
2457
+ return jsonError(res, 400, "offline is required");
2458
+ }
2459
+ await withPlaywrightRouteContext({
2460
+ req,
2461
+ res,
2462
+ ctx,
2463
+ targetId,
2464
+ feature: "offline",
2465
+ run: async ({ cdpUrl, tab, pw }) => {
2466
+ await pw.setOfflineViaPlaywright({
2467
+ cdpUrl,
2468
+ targetId: tab.targetId,
2469
+ offline
2470
+ });
2471
+ res.json({ ok: true, targetId: tab.targetId });
2472
+ }
2473
+ });
2474
+ });
2475
+ app.post("/set/headers", async (req, res) => {
2476
+ const body = readBody(req);
2477
+ const targetId = resolveTargetIdFromBody(body);
2478
+ const headers = body.headers && typeof body.headers === "object" && !Array.isArray(body.headers) ? body.headers : null;
2479
+ if (!headers) {
2480
+ return jsonError(res, 400, "headers is required");
2481
+ }
2482
+ const parsed = {};
2483
+ for (const [k, v] of Object.entries(headers)) {
2484
+ if (typeof v === "string") {
2485
+ parsed[k] = v;
2486
+ }
2487
+ }
2488
+ await withPlaywrightRouteContext({
2489
+ req,
2490
+ res,
2491
+ ctx,
2492
+ targetId,
2493
+ feature: "headers",
2494
+ run: async ({ cdpUrl, tab, pw }) => {
2495
+ await pw.setExtraHTTPHeadersViaPlaywright({
2496
+ cdpUrl,
2497
+ targetId: tab.targetId,
2498
+ headers: parsed
2499
+ });
2500
+ res.json({ ok: true, targetId: tab.targetId });
2501
+ }
2502
+ });
2503
+ });
2504
+ app.post("/set/credentials", async (req, res) => {
2505
+ const body = readBody(req);
2506
+ const targetId = resolveTargetIdFromBody(body);
2507
+ const clear = toBoolean(body.clear) ?? false;
2508
+ const username = toStringOrEmpty(body.username) || void 0;
2509
+ const password = typeof body.password === "string" ? body.password : void 0;
2510
+ await withPlaywrightRouteContext({
2511
+ req,
2512
+ res,
2513
+ ctx,
2514
+ targetId,
2515
+ feature: "http credentials",
2516
+ run: async ({ cdpUrl, tab, pw }) => {
2517
+ await pw.setHttpCredentialsViaPlaywright({
2518
+ cdpUrl,
2519
+ targetId: tab.targetId,
2520
+ username,
2521
+ password,
2522
+ clear
2523
+ });
2524
+ res.json({ ok: true, targetId: tab.targetId });
2525
+ }
2526
+ });
2527
+ });
2528
+ app.post("/set/geolocation", async (req, res) => {
2529
+ const body = readBody(req);
2530
+ const targetId = resolveTargetIdFromBody(body);
2531
+ const clear = toBoolean(body.clear) ?? false;
2532
+ const latitude = toNumber(body.latitude);
2533
+ const longitude = toNumber(body.longitude);
2534
+ const accuracy = toNumber(body.accuracy) ?? void 0;
2535
+ const origin = toStringOrEmpty(body.origin) || void 0;
2536
+ await withPlaywrightRouteContext({
2537
+ req,
2538
+ res,
2539
+ ctx,
2540
+ targetId,
2541
+ feature: "geolocation",
2542
+ run: async ({ cdpUrl, tab, pw }) => {
2543
+ await pw.setGeolocationViaPlaywright({
2544
+ cdpUrl,
2545
+ targetId: tab.targetId,
2546
+ latitude,
2547
+ longitude,
2548
+ accuracy,
2549
+ origin,
2550
+ clear
2551
+ });
2552
+ res.json({ ok: true, targetId: tab.targetId });
2553
+ }
2554
+ });
2555
+ });
2556
+ app.post("/set/media", async (req, res) => {
2557
+ const body = readBody(req);
2558
+ const targetId = resolveTargetIdFromBody(body);
2559
+ const schemeRaw = toStringOrEmpty(body.colorScheme);
2560
+ const colorScheme = schemeRaw === "dark" || schemeRaw === "light" || schemeRaw === "no-preference" ? schemeRaw : schemeRaw === "none" ? null : void 0;
2561
+ if (colorScheme === void 0) {
2562
+ return jsonError(res, 400, "colorScheme must be dark|light|no-preference|none");
2563
+ }
2564
+ await withPlaywrightRouteContext({
2565
+ req,
2566
+ res,
2567
+ ctx,
2568
+ targetId,
2569
+ feature: "media emulation",
2570
+ run: async ({ cdpUrl, tab, pw }) => {
2571
+ await pw.emulateMediaViaPlaywright({
2572
+ cdpUrl,
2573
+ targetId: tab.targetId,
2574
+ colorScheme
2575
+ });
2576
+ res.json({ ok: true, targetId: tab.targetId });
2577
+ }
2578
+ });
2579
+ });
2580
+ app.post("/set/timezone", async (req, res) => {
2581
+ const body = readBody(req);
2582
+ const targetId = resolveTargetIdFromBody(body);
2583
+ const timezoneId = toStringOrEmpty(body.timezoneId);
2584
+ if (!timezoneId) {
2585
+ return jsonError(res, 400, "timezoneId is required");
2586
+ }
2587
+ await withPlaywrightRouteContext({
2588
+ req,
2589
+ res,
2590
+ ctx,
2591
+ targetId,
2592
+ feature: "timezone",
2593
+ run: async ({ cdpUrl, tab, pw }) => {
2594
+ await pw.setTimezoneViaPlaywright({
2595
+ cdpUrl,
2596
+ targetId: tab.targetId,
2597
+ timezoneId
2598
+ });
2599
+ res.json({ ok: true, targetId: tab.targetId });
2600
+ }
2601
+ });
2602
+ });
2603
+ app.post("/set/locale", async (req, res) => {
2604
+ const body = readBody(req);
2605
+ const targetId = resolveTargetIdFromBody(body);
2606
+ const locale = toStringOrEmpty(body.locale);
2607
+ if (!locale) {
2608
+ return jsonError(res, 400, "locale is required");
2609
+ }
2610
+ await withPlaywrightRouteContext({
2611
+ req,
2612
+ res,
2613
+ ctx,
2614
+ targetId,
2615
+ feature: "locale",
2616
+ run: async ({ cdpUrl, tab, pw }) => {
2617
+ await pw.setLocaleViaPlaywright({
2618
+ cdpUrl,
2619
+ targetId: tab.targetId,
2620
+ locale
2621
+ });
2622
+ res.json({ ok: true, targetId: tab.targetId });
2623
+ }
2624
+ });
2625
+ });
2626
+ app.post("/set/device", async (req, res) => {
2627
+ const body = readBody(req);
2628
+ const targetId = resolveTargetIdFromBody(body);
2629
+ const name = toStringOrEmpty(body.name);
2630
+ if (!name) {
2631
+ return jsonError(res, 400, "name is required");
2632
+ }
2633
+ await withPlaywrightRouteContext({
2634
+ req,
2635
+ res,
2636
+ ctx,
2637
+ targetId,
2638
+ feature: "device emulation",
2639
+ run: async ({ cdpUrl, tab, pw }) => {
2640
+ await pw.setDeviceViaPlaywright({
2641
+ cdpUrl,
2642
+ targetId: tab.targetId,
2643
+ name
2644
+ });
2645
+ res.json({ ok: true, targetId: tab.targetId });
2646
+ }
2647
+ });
2648
+ });
2649
+ }
2650
+
2651
+ // src/browser/routes/agent.ts
2652
+ function registerBrowserAgentRoutes(app, ctx) {
2653
+ registerBrowserAgentSnapshotRoutes(app, ctx);
2654
+ registerBrowserAgentActRoutes(app, ctx);
2655
+ registerBrowserAgentDebugRoutes(app, ctx);
2656
+ registerBrowserAgentStorageRoutes(app, ctx);
2657
+ }
2658
+
2659
+ // src/browser/profiles-service.ts
2660
+ import fs4 from "fs";
2661
+ import path5 from "path";
2662
+ var HEX_COLOR_RE = /^#[0-9A-Fa-f]{6}$/;
2663
+ function createBrowserProfilesService(ctx) {
2664
+ const listProfiles = async () => {
2665
+ return await ctx.listProfiles();
2666
+ };
2667
+ const createProfile = async (params) => {
2668
+ const name = params.name.trim();
2669
+ const rawCdpUrl = params.cdpUrl?.trim() || void 0;
2670
+ const driver = params.driver === "extension" ? "extension" : void 0;
2671
+ if (!isValidProfileName(name)) {
2672
+ throw new Error("invalid profile name: use lowercase letters, numbers, and hyphens only");
2673
+ }
2674
+ const state2 = ctx.state();
2675
+ const resolvedProfiles = state2.resolved.profiles;
2676
+ if (name in resolvedProfiles) {
2677
+ throw new Error(`profile "${name}" already exists`);
2678
+ }
2679
+ const cfg = loadConfig();
2680
+ const rawProfiles = cfg.browser?.profiles ?? {};
2681
+ if (name in rawProfiles) {
2682
+ throw new Error(`profile "${name}" already exists`);
2683
+ }
2684
+ const usedColors = getUsedColors(resolvedProfiles);
2685
+ const profileColor = params.color && HEX_COLOR_RE.test(params.color) ? params.color : allocateColor(usedColors);
2686
+ let profileConfig;
2687
+ if (rawCdpUrl) {
2688
+ const parsed = parseHttpUrl(rawCdpUrl, "browser.profiles.cdpUrl");
2689
+ profileConfig = {
2690
+ cdpUrl: parsed.normalized,
2691
+ ...driver ? { driver } : {},
2692
+ color: profileColor
2693
+ };
2694
+ } else {
2695
+ const usedPorts = getUsedPorts(resolvedProfiles);
2696
+ const range = deriveDefaultBrowserCdpPortRange(state2.resolved.controlPort);
2697
+ const cdpPort = allocateCdpPort(usedPorts, range);
2698
+ if (cdpPort === null) {
2699
+ throw new Error("no available CDP ports in range");
2700
+ }
2701
+ profileConfig = {
2702
+ cdpPort,
2703
+ ...driver ? { driver } : {},
2704
+ color: profileColor
2705
+ };
2706
+ }
2707
+ const nextConfig = {
2708
+ ...cfg,
2709
+ browser: {
2710
+ ...cfg.browser,
2711
+ profiles: {
2712
+ ...rawProfiles,
2713
+ [name]: profileConfig
2714
+ }
2715
+ }
2716
+ };
2717
+ await writeConfigFile(nextConfig);
2718
+ state2.resolved.profiles[name] = profileConfig;
2719
+ const resolved = resolveProfile(state2.resolved, name);
2720
+ if (!resolved) {
2721
+ throw new Error(`profile "${name}" not found after creation`);
2722
+ }
2723
+ return {
2724
+ ok: true,
2725
+ profile: name,
2726
+ cdpPort: resolved.cdpPort,
2727
+ cdpUrl: resolved.cdpUrl,
2728
+ color: resolved.color,
2729
+ isRemote: !resolved.cdpIsLoopback
2730
+ };
2731
+ };
2732
+ const deleteProfile = async (nameRaw) => {
2733
+ const name = nameRaw.trim();
2734
+ if (!name) {
2735
+ throw new Error("profile name is required");
2736
+ }
2737
+ if (!isValidProfileName(name)) {
2738
+ throw new Error("invalid profile name");
2739
+ }
2740
+ const cfg = loadConfig();
2741
+ const profiles = cfg.browser?.profiles ?? {};
2742
+ if (!(name in profiles)) {
2743
+ throw new Error(`profile "${name}" not found`);
2744
+ }
2745
+ const defaultProfile = cfg.browser?.defaultProfile ?? DEFAULT_BROWSER_DEFAULT_PROFILE_NAME;
2746
+ if (name === defaultProfile) {
2747
+ throw new Error(
2748
+ `cannot delete the default profile "${name}"; change browser.defaultProfile first`
2749
+ );
2750
+ }
2751
+ let deleted = false;
2752
+ const state2 = ctx.state();
2753
+ const resolved = resolveProfile(state2.resolved, name);
2754
+ if (resolved?.cdpIsLoopback) {
2755
+ try {
2756
+ await ctx.forProfile(name).stopRunningBrowser();
2757
+ } catch {
2758
+ }
2759
+ const userDataDir = resolveAgenticMailUserDataDir(name);
2760
+ const profileDir = path5.dirname(userDataDir);
2761
+ if (fs4.existsSync(profileDir)) {
2762
+ await movePathToTrash(profileDir);
2763
+ deleted = true;
2764
+ }
2765
+ }
2766
+ const { [name]: _removed, ...remainingProfiles } = profiles;
2767
+ const nextConfig = {
2768
+ ...cfg,
2769
+ browser: {
2770
+ ...cfg.browser,
2771
+ profiles: remainingProfiles
2772
+ }
2773
+ };
2774
+ await writeConfigFile(nextConfig);
2775
+ delete state2.resolved.profiles[name];
2776
+ state2.profiles.delete(name);
2777
+ return { ok: true, profile: name, deleted };
2778
+ };
2779
+ return {
2780
+ listProfiles,
2781
+ createProfile,
2782
+ deleteProfile
2783
+ };
2784
+ }
2785
+
2786
+ // src/browser/routes/basic.ts
2787
+ async function withBasicProfileRoute(params) {
2788
+ const profileCtx = resolveProfileContext(params.req, params.res, params.ctx);
2789
+ if (!profileCtx) {
2790
+ return;
2791
+ }
2792
+ try {
2793
+ await params.run(profileCtx);
2794
+ } catch (err) {
2795
+ jsonError(params.res, 500, String(err));
2796
+ }
2797
+ }
2798
+ function registerBrowserBasicRoutes(app, ctx) {
2799
+ app.get("/profiles", async (_req, res) => {
2800
+ try {
2801
+ const service = createBrowserProfilesService(ctx);
2802
+ const profiles = await service.listProfiles();
2803
+ res.json({ profiles });
2804
+ } catch (err) {
2805
+ jsonError(res, 500, String(err));
2806
+ }
2807
+ });
2808
+ app.get("/", async (req, res) => {
2809
+ let current;
2810
+ try {
2811
+ current = ctx.state();
2812
+ } catch {
2813
+ return jsonError(res, 503, "browser server not started");
2814
+ }
2815
+ const profileCtx = getProfileContext(req, ctx);
2816
+ if ("error" in profileCtx) {
2817
+ return jsonError(res, profileCtx.status, profileCtx.error);
2818
+ }
2819
+ const [cdpHttp, cdpReady] = await Promise.all([
2820
+ profileCtx.isHttpReachable(300),
2821
+ profileCtx.isReachable(600)
2822
+ ]);
2823
+ const profileState = current.profiles.get(profileCtx.profile.name);
2824
+ let detectedBrowser = null;
2825
+ let detectedExecutablePath = null;
2826
+ let detectError = null;
2827
+ try {
2828
+ const detected = resolveBrowserExecutableForPlatform(current.resolved, process.platform);
2829
+ if (detected) {
2830
+ detectedBrowser = detected.kind;
2831
+ detectedExecutablePath = detected.path;
2832
+ }
2833
+ } catch (err) {
2834
+ detectError = String(err);
2835
+ }
2836
+ res.json({
2837
+ enabled: current.resolved.enabled,
2838
+ profile: profileCtx.profile.name,
2839
+ running: cdpReady,
2840
+ cdpReady,
2841
+ cdpHttp,
2842
+ pid: profileState?.running?.pid ?? null,
2843
+ cdpPort: profileCtx.profile.cdpPort,
2844
+ cdpUrl: profileCtx.profile.cdpUrl,
2845
+ chosenBrowser: profileState?.running?.exe.kind ?? null,
2846
+ detectedBrowser,
2847
+ detectedExecutablePath,
2848
+ detectError,
2849
+ userDataDir: profileState?.running?.userDataDir ?? null,
2850
+ color: profileCtx.profile.color,
2851
+ headless: current.resolved.headless,
2852
+ noSandbox: current.resolved.noSandbox,
2853
+ executablePath: current.resolved.executablePath ?? null,
2854
+ attachOnly: current.resolved.attachOnly
2855
+ });
2856
+ });
2857
+ app.post("/start", async (req, res) => {
2858
+ await withBasicProfileRoute({
2859
+ req,
2860
+ res,
2861
+ ctx,
2862
+ run: async (profileCtx) => {
2863
+ await profileCtx.ensureBrowserAvailable();
2864
+ res.json({ ok: true, profile: profileCtx.profile.name });
2865
+ }
2866
+ });
2867
+ });
2868
+ app.post("/stop", async (req, res) => {
2869
+ await withBasicProfileRoute({
2870
+ req,
2871
+ res,
2872
+ ctx,
2873
+ run: async (profileCtx) => {
2874
+ const result = await profileCtx.stopRunningBrowser();
2875
+ res.json({
2876
+ ok: true,
2877
+ stopped: result.stopped,
2878
+ profile: profileCtx.profile.name
2879
+ });
2880
+ }
2881
+ });
2882
+ });
2883
+ app.post("/reset-profile", async (req, res) => {
2884
+ await withBasicProfileRoute({
2885
+ req,
2886
+ res,
2887
+ ctx,
2888
+ run: async (profileCtx) => {
2889
+ const result = await profileCtx.resetProfile();
2890
+ res.json({ ok: true, profile: profileCtx.profile.name, ...result });
2891
+ }
2892
+ });
2893
+ });
2894
+ app.post("/profiles/create", async (req, res) => {
2895
+ const name = toStringOrEmpty(req.body?.name);
2896
+ const color = toStringOrEmpty(req.body?.color);
2897
+ const cdpUrl = toStringOrEmpty(req.body?.cdpUrl);
2898
+ const driver = toStringOrEmpty(req.body?.driver);
2899
+ if (!name) {
2900
+ return jsonError(res, 400, "name is required");
2901
+ }
2902
+ try {
2903
+ const service = createBrowserProfilesService(ctx);
2904
+ const result = await service.createProfile({
2905
+ name,
2906
+ color: color || void 0,
2907
+ cdpUrl: cdpUrl || void 0,
2908
+ driver: driver === "extension" ? "extension" : void 0
2909
+ });
2910
+ res.json(result);
2911
+ } catch (err) {
2912
+ const msg = String(err);
2913
+ if (msg.includes("already exists")) {
2914
+ return jsonError(res, 409, msg);
2915
+ }
2916
+ if (msg.includes("invalid profile name")) {
2917
+ return jsonError(res, 400, msg);
2918
+ }
2919
+ if (msg.includes("no available CDP ports")) {
2920
+ return jsonError(res, 507, msg);
2921
+ }
2922
+ if (msg.includes("cdpUrl")) {
2923
+ return jsonError(res, 400, msg);
2924
+ }
2925
+ jsonError(res, 500, msg);
2926
+ }
2927
+ });
2928
+ app.delete("/profiles/:name", async (req, res) => {
2929
+ const name = toStringOrEmpty(req.params.name);
2930
+ if (!name) {
2931
+ return jsonError(res, 400, "profile name is required");
2932
+ }
2933
+ try {
2934
+ const service = createBrowserProfilesService(ctx);
2935
+ const result = await service.deleteProfile(name);
2936
+ res.json(result);
2937
+ } catch (err) {
2938
+ const msg = String(err);
2939
+ if (msg.includes("invalid profile name")) {
2940
+ return jsonError(res, 400, msg);
2941
+ }
2942
+ if (msg.includes("default profile")) {
2943
+ return jsonError(res, 400, msg);
2944
+ }
2945
+ if (msg.includes("not found")) {
2946
+ return jsonError(res, 404, msg);
2947
+ }
2948
+ jsonError(res, 500, msg);
2949
+ }
2950
+ });
2951
+ }
2952
+
2953
+ // src/browser/routes/tabs.ts
2954
+ function resolveTabsProfileContext(req, res, ctx) {
2955
+ const profileCtx = getProfileContext(req, ctx);
2956
+ if ("error" in profileCtx) {
2957
+ jsonError(res, profileCtx.status, profileCtx.error);
2958
+ return null;
2959
+ }
2960
+ return profileCtx;
2961
+ }
2962
+ function handleTabsRouteError(ctx, res, err, opts) {
2963
+ if (opts?.mapTabError) {
2964
+ const mapped = ctx.mapTabError(err);
2965
+ if (mapped) {
2966
+ return jsonError(res, mapped.status, mapped.message);
2967
+ }
2968
+ }
2969
+ return jsonError(res, 500, String(err));
2970
+ }
2971
+ async function withTabsProfileRoute(params) {
2972
+ const profileCtx = resolveTabsProfileContext(params.req, params.res, params.ctx);
2973
+ if (!profileCtx) {
2974
+ return;
2975
+ }
2976
+ try {
2977
+ await params.run(profileCtx);
2978
+ } catch (err) {
2979
+ handleTabsRouteError(params.ctx, params.res, err, { mapTabError: params.mapTabError });
2980
+ }
2981
+ }
2982
+ async function ensureBrowserRunning(profileCtx, res) {
2983
+ if (!await profileCtx.isReachable(300)) {
2984
+ jsonError(res, 409, "browser not running");
2985
+ return false;
2986
+ }
2987
+ return true;
2988
+ }
2989
+ function resolveIndexedTab(tabs, index) {
2990
+ return typeof index === "number" ? tabs[index] : tabs.at(0);
2991
+ }
2992
+ function parseRequiredTargetId(res, rawTargetId) {
2993
+ const targetId = toStringOrEmpty(rawTargetId);
2994
+ if (!targetId) {
2995
+ jsonError(res, 400, "targetId is required");
2996
+ return null;
2997
+ }
2998
+ return targetId;
2999
+ }
3000
+ async function runTabTargetMutation(params) {
3001
+ await withTabsProfileRoute({
3002
+ req: params.req,
3003
+ res: params.res,
3004
+ ctx: params.ctx,
3005
+ mapTabError: true,
3006
+ run: async (profileCtx) => {
3007
+ if (!await ensureBrowserRunning(profileCtx, params.res)) {
3008
+ return;
3009
+ }
3010
+ await params.mutate(profileCtx, params.targetId);
3011
+ params.res.json({ ok: true });
3012
+ }
3013
+ });
3014
+ }
3015
+ function registerBrowserTabRoutes(app, ctx) {
3016
+ app.get("/tabs", async (req, res) => {
3017
+ await withTabsProfileRoute({
3018
+ req,
3019
+ res,
3020
+ ctx,
3021
+ run: async (profileCtx) => {
3022
+ const reachable = await profileCtx.isReachable(300);
3023
+ if (!reachable) {
3024
+ return res.json({ running: false, tabs: [] });
3025
+ }
3026
+ const tabs = await profileCtx.listTabs();
3027
+ res.json({ running: true, tabs });
3028
+ }
3029
+ });
3030
+ });
3031
+ app.post("/tabs/open", async (req, res) => {
3032
+ const url = toStringOrEmpty(req.body?.url);
3033
+ if (!url) {
3034
+ return jsonError(res, 400, "url is required");
3035
+ }
3036
+ await withTabsProfileRoute({
3037
+ req,
3038
+ res,
3039
+ ctx,
3040
+ mapTabError: true,
3041
+ run: async (profileCtx) => {
3042
+ await profileCtx.ensureBrowserAvailable();
3043
+ const tab = await profileCtx.openTab(url);
3044
+ res.json(tab);
3045
+ }
3046
+ });
3047
+ });
3048
+ app.post("/tabs/focus", async (req, res) => {
3049
+ const targetId = parseRequiredTargetId(res, req.body?.targetId);
3050
+ if (!targetId) {
3051
+ return;
3052
+ }
3053
+ await runTabTargetMutation({
3054
+ req,
3055
+ res,
3056
+ ctx,
3057
+ targetId,
3058
+ mutate: async (profileCtx, id) => {
3059
+ await profileCtx.focusTab(id);
3060
+ }
3061
+ });
3062
+ });
3063
+ app.delete("/tabs/:targetId", async (req, res) => {
3064
+ const targetId = parseRequiredTargetId(res, req.params.targetId);
3065
+ if (!targetId) {
3066
+ return;
3067
+ }
3068
+ await runTabTargetMutation({
3069
+ req,
3070
+ res,
3071
+ ctx,
3072
+ targetId,
3073
+ mutate: async (profileCtx, id) => {
3074
+ await profileCtx.closeTab(id);
3075
+ }
3076
+ });
3077
+ });
3078
+ app.post("/tabs/action", async (req, res) => {
3079
+ const action = toStringOrEmpty(req.body?.action);
3080
+ const index = toNumber(req.body?.index);
3081
+ await withTabsProfileRoute({
3082
+ req,
3083
+ res,
3084
+ ctx,
3085
+ mapTabError: true,
3086
+ run: async (profileCtx) => {
3087
+ if (action === "list") {
3088
+ const reachable = await profileCtx.isReachable(300);
3089
+ if (!reachable) {
3090
+ return res.json({ ok: true, tabs: [] });
3091
+ }
3092
+ const tabs = await profileCtx.listTabs();
3093
+ return res.json({ ok: true, tabs });
3094
+ }
3095
+ if (action === "new") {
3096
+ await profileCtx.ensureBrowserAvailable();
3097
+ const tab = await profileCtx.openTab("about:blank");
3098
+ return res.json({ ok: true, tab });
3099
+ }
3100
+ if (action === "close") {
3101
+ const tabs = await profileCtx.listTabs();
3102
+ const target = resolveIndexedTab(tabs, index);
3103
+ if (!target) {
3104
+ return jsonError(res, 404, "tab not found");
3105
+ }
3106
+ await profileCtx.closeTab(target.targetId);
3107
+ return res.json({ ok: true, targetId: target.targetId });
3108
+ }
3109
+ if (action === "select") {
3110
+ if (typeof index !== "number") {
3111
+ return jsonError(res, 400, "index is required");
3112
+ }
3113
+ const tabs = await profileCtx.listTabs();
3114
+ const target = tabs[index];
3115
+ if (!target) {
3116
+ return jsonError(res, 404, "tab not found");
3117
+ }
3118
+ await profileCtx.focusTab(target.targetId);
3119
+ return res.json({ ok: true, targetId: target.targetId });
3120
+ }
3121
+ return jsonError(res, 400, "unknown tab action");
3122
+ }
3123
+ });
3124
+ });
3125
+ }
3126
+
3127
+ // src/browser/routes/index.ts
3128
+ function registerBrowserRoutes(app, ctx) {
3129
+ registerBrowserBasicRoutes(app, ctx);
3130
+ registerBrowserTabRoutes(app, ctx);
3131
+ registerBrowserAgentRoutes(app, ctx);
3132
+ }
3133
+
3134
+ // src/browser/routes/dispatcher.ts
3135
+ function compileRoute(path6) {
3136
+ const paramNames = [];
3137
+ const parts = path6.split("/").map((part) => {
3138
+ if (part.startsWith(":")) {
3139
+ const name = part.slice(1);
3140
+ paramNames.push(name);
3141
+ return "([^/]+)";
3142
+ }
3143
+ return escapeRegExp(part);
3144
+ });
3145
+ return { regex: new RegExp(`^${parts.join("/")}$`), paramNames };
3146
+ }
3147
+ function createRegistry() {
3148
+ const routes = [];
3149
+ const register = (method) => (path6, handler) => {
3150
+ const { regex, paramNames } = compileRoute(path6);
3151
+ routes.push({ method, path: path6, regex, paramNames, handler });
3152
+ };
3153
+ const router = {
3154
+ get: register("GET"),
3155
+ post: register("POST"),
3156
+ delete: register("DELETE")
3157
+ };
3158
+ return { routes, router };
3159
+ }
3160
+ function normalizePath(path6) {
3161
+ if (!path6) {
3162
+ return "/";
3163
+ }
3164
+ return path6.startsWith("/") ? path6 : `/${path6}`;
3165
+ }
3166
+ function createBrowserRouteDispatcher(ctx) {
3167
+ const registry = createRegistry();
3168
+ registerBrowserRoutes(registry.router, ctx);
3169
+ return {
3170
+ dispatch: async (req) => {
3171
+ const method = req.method;
3172
+ const path6 = normalizePath(req.path);
3173
+ const query = req.query ?? {};
3174
+ const body = req.body;
3175
+ const signal = req.signal;
3176
+ const match = registry.routes.find((route) => {
3177
+ if (route.method !== method) {
3178
+ return false;
3179
+ }
3180
+ return route.regex.test(path6);
3181
+ });
3182
+ if (!match) {
3183
+ return { status: 404, body: { error: "Not Found" } };
3184
+ }
3185
+ const exec = match.regex.exec(path6);
3186
+ const params = {};
3187
+ if (exec) {
3188
+ for (const [idx, name] of match.paramNames.entries()) {
3189
+ const value = exec[idx + 1];
3190
+ if (typeof value === "string") {
3191
+ params[name] = decodeURIComponent(value);
3192
+ }
3193
+ }
3194
+ }
3195
+ let status = 200;
3196
+ let payload = void 0;
3197
+ const res = {
3198
+ status(code) {
3199
+ status = code;
3200
+ return res;
3201
+ },
3202
+ json(bodyValue) {
3203
+ payload = bodyValue;
3204
+ }
3205
+ };
3206
+ try {
3207
+ await match.handler(
3208
+ {
3209
+ params,
3210
+ query,
3211
+ body,
3212
+ signal
3213
+ },
3214
+ res
3215
+ );
3216
+ } catch (err) {
3217
+ return { status: 500, body: { error: String(err) } };
3218
+ }
3219
+ return { status, body: payload };
3220
+ }
3221
+ };
3222
+ }
3223
+
3224
+ // src/browser/client-fetch.ts
3225
+ function isAbsoluteHttp(url) {
3226
+ return /^https?:\/\//i.test(url.trim());
3227
+ }
3228
+ function isLoopbackHttpUrl(url) {
3229
+ try {
3230
+ const host = new URL(url).hostname.trim().toLowerCase();
3231
+ const normalizedHost = host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
3232
+ return normalizedHost === "127.0.0.1" || normalizedHost === "localhost" || normalizedHost === "::1";
3233
+ } catch {
3234
+ return false;
3235
+ }
3236
+ }
3237
+ function withLoopbackBrowserAuthImpl(url, init, deps) {
3238
+ const headers = new Headers(init?.headers ?? {});
3239
+ if (headers.has("authorization") || headers.has("x-agenticmail-password")) {
3240
+ return { ...init, headers };
3241
+ }
3242
+ if (!isLoopbackHttpUrl(url)) {
3243
+ return { ...init, headers };
3244
+ }
3245
+ try {
3246
+ const cfg = deps.loadConfig();
3247
+ const auth = deps.resolveBrowserControlAuth(cfg);
3248
+ if (auth.token) {
3249
+ headers.set("Authorization", `Bearer ${auth.token}`);
3250
+ return { ...init, headers };
3251
+ }
3252
+ if (auth.password) {
3253
+ headers.set("x-agenticmail-password", auth.password);
3254
+ return { ...init, headers };
3255
+ }
3256
+ } catch {
3257
+ }
3258
+ try {
3259
+ const parsed = new URL(url);
3260
+ const port = parsed.port && Number.parseInt(parsed.port, 10) > 0 ? Number.parseInt(parsed.port, 10) : parsed.protocol === "https:" ? 443 : 80;
3261
+ const bridgeAuth = deps.getBridgeAuthForPort(port);
3262
+ if (bridgeAuth?.token) {
3263
+ headers.set("Authorization", `Bearer ${bridgeAuth.token}`);
3264
+ } else if (bridgeAuth?.password) {
3265
+ headers.set("x-agenticmail-password", bridgeAuth.password);
3266
+ }
3267
+ } catch {
3268
+ }
3269
+ return { ...init, headers };
3270
+ }
3271
+ function withLoopbackBrowserAuth(url, init) {
3272
+ return withLoopbackBrowserAuthImpl(url, init, {
3273
+ loadConfig,
3274
+ resolveBrowserControlAuth,
3275
+ getBridgeAuthForPort
3276
+ });
3277
+ }
3278
+ function enhanceBrowserFetchError(url, err, timeoutMs) {
3279
+ const isLocal = !isAbsoluteHttp(url);
3280
+ const operatorHint = isLocal ? `Restart the AgenticMail gateway (AgenticMail.app menubar, or \`${formatCliCommand("agenticmail gateway")}\`).` : "If this is a sandboxed session, ensure the sandbox browser is running.";
3281
+ const modelHint = "Do NOT retry the browser tool \u2014 it will keep failing. Use an alternative approach or inform the user that the browser is currently unavailable.";
3282
+ const msg = String(err);
3283
+ const msgLower = msg.toLowerCase();
3284
+ const looksLikeTimeout = msgLower.includes("timed out") || msgLower.includes("timeout") || msgLower.includes("aborted") || msgLower.includes("abort") || msgLower.includes("aborterror");
3285
+ if (looksLikeTimeout) {
3286
+ return new Error(
3287
+ `Can't reach the AgenticMail browser control service (timed out after ${timeoutMs}ms). ${operatorHint} ${modelHint}`
3288
+ );
3289
+ }
3290
+ return new Error(
3291
+ `Can't reach the AgenticMail browser control service. ${operatorHint} ${modelHint} (${msg})`
3292
+ );
3293
+ }
3294
+ async function fetchHttpJson(url, init) {
3295
+ const timeoutMs = init.timeoutMs ?? 5e3;
3296
+ const ctrl = new AbortController();
3297
+ const upstreamSignal = init.signal;
3298
+ let upstreamAbortListener;
3299
+ if (upstreamSignal) {
3300
+ if (upstreamSignal.aborted) {
3301
+ ctrl.abort(upstreamSignal.reason);
3302
+ } else {
3303
+ upstreamAbortListener = () => ctrl.abort(upstreamSignal.reason);
3304
+ upstreamSignal.addEventListener("abort", upstreamAbortListener, { once: true });
3305
+ }
3306
+ }
3307
+ const t = setTimeout(() => ctrl.abort(new Error("timed out")), timeoutMs);
3308
+ try {
3309
+ const res = await fetch(url, { ...init, signal: ctrl.signal });
3310
+ if (!res.ok) {
3311
+ const text = await res.text().catch(() => "");
3312
+ throw new Error(text || `HTTP ${res.status}`);
3313
+ }
3314
+ return await res.json();
3315
+ } finally {
3316
+ clearTimeout(t);
3317
+ if (upstreamSignal && upstreamAbortListener) {
3318
+ upstreamSignal.removeEventListener("abort", upstreamAbortListener);
3319
+ }
3320
+ }
3321
+ }
3322
+ async function fetchBrowserJson(url, init) {
3323
+ const timeoutMs = init?.timeoutMs ?? 5e3;
3324
+ try {
3325
+ if (isAbsoluteHttp(url)) {
3326
+ const httpInit = withLoopbackBrowserAuth(url, init);
3327
+ return await fetchHttpJson(url, { ...httpInit, timeoutMs });
3328
+ }
3329
+ const started = await startBrowserControlServiceFromConfig();
3330
+ if (!started) {
3331
+ throw new Error("browser control disabled");
3332
+ }
3333
+ const dispatcher = createBrowserRouteDispatcher(createBrowserControlContext());
3334
+ const parsed = new URL(url, "http://localhost");
3335
+ const query = {};
3336
+ for (const [key, value] of parsed.searchParams.entries()) {
3337
+ query[key] = value;
3338
+ }
3339
+ let body = init?.body;
3340
+ if (typeof body === "string") {
3341
+ try {
3342
+ body = JSON.parse(body);
3343
+ } catch {
3344
+ }
3345
+ }
3346
+ const abortCtrl = new AbortController();
3347
+ const upstreamSignal = init?.signal;
3348
+ let upstreamAbortListener;
3349
+ if (upstreamSignal) {
3350
+ if (upstreamSignal.aborted) {
3351
+ abortCtrl.abort(upstreamSignal.reason);
3352
+ } else {
3353
+ upstreamAbortListener = () => abortCtrl.abort(upstreamSignal.reason);
3354
+ upstreamSignal.addEventListener("abort", upstreamAbortListener, { once: true });
3355
+ }
3356
+ }
3357
+ let abortListener;
3358
+ const abortPromise = abortCtrl.signal.aborted ? Promise.reject(abortCtrl.signal.reason ?? new Error("aborted")) : new Promise((_, reject) => {
3359
+ abortListener = () => reject(abortCtrl.signal.reason ?? new Error("aborted"));
3360
+ abortCtrl.signal.addEventListener("abort", abortListener, { once: true });
3361
+ });
3362
+ let timer;
3363
+ if (timeoutMs) {
3364
+ timer = setTimeout(() => abortCtrl.abort(new Error("timed out")), timeoutMs);
3365
+ }
3366
+ const dispatchPromise = dispatcher.dispatch({
3367
+ method: init?.method?.toUpperCase() === "DELETE" ? "DELETE" : init?.method?.toUpperCase() === "POST" ? "POST" : "GET",
3368
+ path: parsed.pathname,
3369
+ query,
3370
+ body,
3371
+ signal: abortCtrl.signal
3372
+ });
3373
+ const result = await Promise.race([dispatchPromise, abortPromise]).finally(() => {
3374
+ if (timer) {
3375
+ clearTimeout(timer);
3376
+ }
3377
+ if (abortListener) {
3378
+ abortCtrl.signal.removeEventListener("abort", abortListener);
3379
+ }
3380
+ if (upstreamSignal && upstreamAbortListener) {
3381
+ upstreamSignal.removeEventListener("abort", upstreamAbortListener);
3382
+ }
3383
+ });
3384
+ if (result.status >= 400) {
3385
+ const message = result.body && typeof result.body === "object" && "error" in result.body ? String(result.body.error) : `HTTP ${result.status}`;
3386
+ throw new Error(message);
3387
+ }
3388
+ return result.body;
3389
+ } catch (err) {
3390
+ throw enhanceBrowserFetchError(url, err, timeoutMs);
3391
+ }
3392
+ }
3393
+
3394
+ // src/browser/client-actions-core.ts
3395
+ async function browserNavigate(baseUrl, opts) {
3396
+ const q = buildProfileQuery(opts.profile);
3397
+ return await fetchBrowserJson(withBaseUrl(baseUrl, `/navigate${q}`), {
3398
+ method: "POST",
3399
+ headers: { "Content-Type": "application/json" },
3400
+ body: JSON.stringify({ url: opts.url, targetId: opts.targetId }),
3401
+ timeoutMs: 2e4
3402
+ });
3403
+ }
3404
+ async function browserArmDialog(baseUrl, opts) {
3405
+ const q = buildProfileQuery(opts.profile);
3406
+ return await fetchBrowserJson(withBaseUrl(baseUrl, `/hooks/dialog${q}`), {
3407
+ method: "POST",
3408
+ headers: { "Content-Type": "application/json" },
3409
+ body: JSON.stringify({
3410
+ accept: opts.accept,
3411
+ promptText: opts.promptText,
3412
+ targetId: opts.targetId,
3413
+ timeoutMs: opts.timeoutMs
3414
+ }),
3415
+ timeoutMs: 2e4
3416
+ });
3417
+ }
3418
+ async function browserArmFileChooser(baseUrl, opts) {
3419
+ const q = buildProfileQuery(opts.profile);
3420
+ return await fetchBrowserJson(withBaseUrl(baseUrl, `/hooks/file-chooser${q}`), {
3421
+ method: "POST",
3422
+ headers: { "Content-Type": "application/json" },
3423
+ body: JSON.stringify({
3424
+ paths: opts.paths,
3425
+ ref: opts.ref,
3426
+ inputRef: opts.inputRef,
3427
+ element: opts.element,
3428
+ targetId: opts.targetId,
3429
+ timeoutMs: opts.timeoutMs
3430
+ }),
3431
+ timeoutMs: 2e4
3432
+ });
3433
+ }
3434
+ async function browserAct(baseUrl, req, opts) {
3435
+ const q = buildProfileQuery(opts?.profile);
3436
+ return await fetchBrowserJson(withBaseUrl(baseUrl, `/act${q}`), {
3437
+ method: "POST",
3438
+ headers: { "Content-Type": "application/json" },
3439
+ body: JSON.stringify(req),
3440
+ timeoutMs: 2e4
3441
+ });
3442
+ }
3443
+ async function browserScreenshotAction(baseUrl, opts) {
3444
+ const q = buildProfileQuery(opts.profile);
3445
+ return await fetchBrowserJson(withBaseUrl(baseUrl, `/screenshot${q}`), {
3446
+ method: "POST",
3447
+ headers: { "Content-Type": "application/json" },
3448
+ body: JSON.stringify({
3449
+ targetId: opts.targetId,
3450
+ fullPage: opts.fullPage,
3451
+ ref: opts.ref,
3452
+ element: opts.element,
3453
+ type: opts.type
3454
+ }),
3455
+ timeoutMs: 2e4
3456
+ });
3457
+ }
3458
+
3459
+ // src/browser/client-actions-observe.ts
3460
+ function buildQuerySuffix(params) {
3461
+ const query = new URLSearchParams();
3462
+ for (const [key, value] of params) {
3463
+ if (typeof value === "boolean") {
3464
+ query.set(key, String(value));
3465
+ continue;
3466
+ }
3467
+ if (typeof value === "string" && value.length > 0) {
3468
+ query.set(key, value);
3469
+ }
3470
+ }
3471
+ const encoded = query.toString();
3472
+ return encoded.length > 0 ? `?${encoded}` : "";
3473
+ }
3474
+ async function browserConsoleMessages(baseUrl, opts = {}) {
3475
+ const suffix = buildQuerySuffix([
3476
+ ["level", opts.level],
3477
+ ["targetId", opts.targetId],
3478
+ ["profile", opts.profile]
3479
+ ]);
3480
+ return await fetchBrowserJson(withBaseUrl(baseUrl, `/console${suffix}`), { timeoutMs: 2e4 });
3481
+ }
3482
+ async function browserPdfSave(baseUrl, opts = {}) {
3483
+ const q = buildProfileQuery(opts.profile);
3484
+ return await fetchBrowserJson(withBaseUrl(baseUrl, `/pdf${q}`), {
3485
+ method: "POST",
3486
+ headers: { "Content-Type": "application/json" },
3487
+ body: JSON.stringify({ targetId: opts.targetId }),
3488
+ timeoutMs: 2e4
3489
+ });
3490
+ }
3491
+
3492
+ // src/browser/client.ts
3493
+ function buildProfileQuery2(profile) {
3494
+ return profile ? `?profile=${encodeURIComponent(profile)}` : "";
3495
+ }
3496
+ function withBaseUrl2(baseUrl, path6) {
3497
+ const trimmed = baseUrl?.trim();
3498
+ if (!trimmed) {
3499
+ return path6;
3500
+ }
3501
+ return `${trimmed.replace(/\/$/, "")}${path6}`;
3502
+ }
3503
+ async function browserStatus(baseUrl, opts) {
3504
+ const q = buildProfileQuery2(opts?.profile);
3505
+ return await fetchBrowserJson(withBaseUrl2(baseUrl, `/${q}`), {
3506
+ timeoutMs: 1500
3507
+ });
3508
+ }
3509
+ async function browserProfiles(baseUrl) {
3510
+ const res = await fetchBrowserJson(
3511
+ withBaseUrl2(baseUrl, `/profiles`),
3512
+ {
3513
+ timeoutMs: 3e3
3514
+ }
3515
+ );
3516
+ return res.profiles ?? [];
3517
+ }
3518
+ async function browserStart(baseUrl, opts) {
3519
+ const q = buildProfileQuery2(opts?.profile);
3520
+ await fetchBrowserJson(withBaseUrl2(baseUrl, `/start${q}`), {
3521
+ method: "POST",
3522
+ timeoutMs: 15e3
3523
+ });
3524
+ }
3525
+ async function browserStop(baseUrl, opts) {
3526
+ const q = buildProfileQuery2(opts?.profile);
3527
+ await fetchBrowserJson(withBaseUrl2(baseUrl, `/stop${q}`), {
3528
+ method: "POST",
3529
+ timeoutMs: 15e3
3530
+ });
3531
+ }
3532
+ async function browserTabs(baseUrl, opts) {
3533
+ const q = buildProfileQuery2(opts?.profile);
3534
+ const res = await fetchBrowserJson(
3535
+ withBaseUrl2(baseUrl, `/tabs${q}`),
3536
+ { timeoutMs: 3e3 }
3537
+ );
3538
+ return res.tabs ?? [];
3539
+ }
3540
+ async function browserOpenTab(baseUrl, url, opts) {
3541
+ const q = buildProfileQuery2(opts?.profile);
3542
+ return await fetchBrowserJson(withBaseUrl2(baseUrl, `/tabs/open${q}`), {
3543
+ method: "POST",
3544
+ headers: { "Content-Type": "application/json" },
3545
+ body: JSON.stringify({ url }),
3546
+ timeoutMs: 15e3
3547
+ });
3548
+ }
3549
+ async function browserFocusTab(baseUrl, targetId, opts) {
3550
+ const q = buildProfileQuery2(opts?.profile);
3551
+ await fetchBrowserJson(withBaseUrl2(baseUrl, `/tabs/focus${q}`), {
3552
+ method: "POST",
3553
+ headers: { "Content-Type": "application/json" },
3554
+ body: JSON.stringify({ targetId }),
3555
+ timeoutMs: 5e3
3556
+ });
3557
+ }
3558
+ async function browserCloseTab(baseUrl, targetId, opts) {
3559
+ const q = buildProfileQuery2(opts?.profile);
3560
+ await fetchBrowserJson(withBaseUrl2(baseUrl, `/tabs/${encodeURIComponent(targetId)}${q}`), {
3561
+ method: "DELETE",
3562
+ timeoutMs: 5e3
3563
+ });
3564
+ }
3565
+ async function browserSnapshot(baseUrl, opts) {
3566
+ const q = new URLSearchParams();
3567
+ q.set("format", opts.format);
3568
+ if (opts.targetId) {
3569
+ q.set("targetId", opts.targetId);
3570
+ }
3571
+ if (typeof opts.limit === "number") {
3572
+ q.set("limit", String(opts.limit));
3573
+ }
3574
+ if (typeof opts.maxChars === "number" && Number.isFinite(opts.maxChars)) {
3575
+ q.set("maxChars", String(opts.maxChars));
3576
+ }
3577
+ if (opts.refs === "aria" || opts.refs === "role") {
3578
+ q.set("refs", opts.refs);
3579
+ }
3580
+ if (typeof opts.interactive === "boolean") {
3581
+ q.set("interactive", String(opts.interactive));
3582
+ }
3583
+ if (typeof opts.compact === "boolean") {
3584
+ q.set("compact", String(opts.compact));
3585
+ }
3586
+ if (typeof opts.depth === "number" && Number.isFinite(opts.depth)) {
3587
+ q.set("depth", String(opts.depth));
3588
+ }
3589
+ if (opts.selector?.trim()) {
3590
+ q.set("selector", opts.selector.trim());
3591
+ }
3592
+ if (opts.frame?.trim()) {
3593
+ q.set("frame", opts.frame.trim());
3594
+ }
3595
+ if (opts.labels === true) {
3596
+ q.set("labels", "1");
3597
+ }
3598
+ if (opts.mode) {
3599
+ q.set("mode", opts.mode);
3600
+ }
3601
+ if (opts.profile) {
3602
+ q.set("profile", opts.profile);
3603
+ }
3604
+ return await fetchBrowserJson(withBaseUrl2(baseUrl, `/snapshot?${q.toString()}`), {
3605
+ timeoutMs: 2e4
3606
+ });
3607
+ }
3608
+
3609
+ // src/agent-tools/tools/browser-tool.schema.ts
3610
+ import { Type as Type2 } from "@sinclair/typebox";
3611
+
3612
+ // src/agent-tools/schema/typebox.ts
3613
+ import { Type } from "@sinclair/typebox";
3614
+ function stringEnum(values, options = {}) {
3615
+ return Type.Unsafe({
3616
+ type: "string",
3617
+ enum: [...values],
3618
+ ...options
3619
+ });
3620
+ }
3621
+ function optionalStringEnum(values, options = {}) {
3622
+ return Type.Optional(stringEnum(values, options));
3623
+ }
3624
+
3625
+ // src/agent-tools/tools/browser-tool.schema.ts
3626
+ var BROWSER_ACT_KINDS = [
3627
+ "click",
3628
+ "type",
3629
+ "press",
3630
+ "hover",
3631
+ "drag",
3632
+ "select",
3633
+ "fill",
3634
+ "resize",
3635
+ "wait",
3636
+ "evaluate",
3637
+ "close"
3638
+ ];
3639
+ var BROWSER_TOOL_ACTIONS = [
3640
+ "status",
3641
+ "start",
3642
+ "stop",
3643
+ "profiles",
3644
+ "tabs",
3645
+ "open",
3646
+ "focus",
3647
+ "close",
3648
+ "snapshot",
3649
+ "screenshot",
3650
+ "navigate",
3651
+ "console",
3652
+ "pdf",
3653
+ "upload",
3654
+ "dialog",
3655
+ "act"
3656
+ ];
3657
+ var BROWSER_TARGETS = ["sandbox", "host", "node"];
3658
+ var BROWSER_SNAPSHOT_FORMATS = ["aria", "ai"];
3659
+ var BROWSER_SNAPSHOT_MODES = ["efficient"];
3660
+ var BROWSER_SNAPSHOT_REFS = ["role", "aria"];
3661
+ var BROWSER_IMAGE_TYPES = ["png", "jpeg"];
3662
+ var BrowserActSchema = Type2.Object({
3663
+ kind: stringEnum(BROWSER_ACT_KINDS),
3664
+ // Common fields
3665
+ targetId: Type2.Optional(Type2.String()),
3666
+ ref: Type2.Optional(Type2.String()),
3667
+ // click
3668
+ doubleClick: Type2.Optional(Type2.Boolean()),
3669
+ button: Type2.Optional(Type2.String()),
3670
+ modifiers: Type2.Optional(Type2.Array(Type2.String())),
3671
+ // type
3672
+ text: Type2.Optional(Type2.String()),
3673
+ submit: Type2.Optional(Type2.Boolean()),
3674
+ slowly: Type2.Optional(Type2.Boolean()),
3675
+ // press
3676
+ key: Type2.Optional(Type2.String()),
3677
+ // drag
3678
+ startRef: Type2.Optional(Type2.String()),
3679
+ endRef: Type2.Optional(Type2.String()),
3680
+ // select
3681
+ values: Type2.Optional(Type2.Array(Type2.String())),
3682
+ // fill - use permissive array of objects
3683
+ fields: Type2.Optional(Type2.Array(Type2.Object({}, { additionalProperties: true }))),
3684
+ // resize
3685
+ width: Type2.Optional(Type2.Number()),
3686
+ height: Type2.Optional(Type2.Number()),
3687
+ // wait
3688
+ timeMs: Type2.Optional(Type2.Number()),
3689
+ textGone: Type2.Optional(Type2.String()),
3690
+ // evaluate
3691
+ fn: Type2.Optional(Type2.String())
3692
+ });
3693
+ var BrowserToolSchema = Type2.Object({
3694
+ action: stringEnum(BROWSER_TOOL_ACTIONS),
3695
+ target: optionalStringEnum(BROWSER_TARGETS),
3696
+ node: Type2.Optional(Type2.String()),
3697
+ profile: Type2.Optional(Type2.String()),
3698
+ targetUrl: Type2.Optional(Type2.String()),
3699
+ targetId: Type2.Optional(Type2.String()),
3700
+ limit: Type2.Optional(Type2.Number()),
3701
+ maxChars: Type2.Optional(Type2.Number()),
3702
+ mode: optionalStringEnum(BROWSER_SNAPSHOT_MODES),
3703
+ snapshotFormat: optionalStringEnum(BROWSER_SNAPSHOT_FORMATS),
3704
+ refs: optionalStringEnum(BROWSER_SNAPSHOT_REFS),
3705
+ interactive: Type2.Optional(Type2.Boolean()),
3706
+ compact: Type2.Optional(Type2.Boolean()),
3707
+ depth: Type2.Optional(Type2.Number()),
3708
+ selector: Type2.Optional(Type2.String()),
3709
+ frame: Type2.Optional(Type2.String()),
3710
+ labels: Type2.Optional(Type2.Boolean()),
3711
+ fullPage: Type2.Optional(Type2.Boolean()),
3712
+ ref: Type2.Optional(Type2.String()),
3713
+ element: Type2.Optional(Type2.String()),
3714
+ type: optionalStringEnum(BROWSER_IMAGE_TYPES),
3715
+ level: Type2.Optional(Type2.String()),
3716
+ paths: Type2.Optional(Type2.Array(Type2.String())),
3717
+ inputRef: Type2.Optional(Type2.String()),
3718
+ timeoutMs: Type2.Optional(Type2.Number()),
3719
+ accept: Type2.Optional(Type2.Boolean()),
3720
+ promptText: Type2.Optional(Type2.String()),
3721
+ request: Type2.Optional(BrowserActSchema)
3722
+ });
3723
+
3724
+ // src/agent-tools/tools/browser-tool.ts
3725
+ function wrapBrowserExternalJson(params) {
3726
+ const extractedText = JSON.stringify(params.payload, null, 2);
3727
+ const wrappedText = wrapExternalContent(extractedText, {
3728
+ source: "browser",
3729
+ includeWarning: params.includeWarning ?? true
3730
+ });
3731
+ return {
3732
+ wrappedText,
3733
+ safeDetails: {
3734
+ ok: true,
3735
+ externalContent: {
3736
+ untrusted: true,
3737
+ source: "browser",
3738
+ kind: params.kind,
3739
+ wrapped: true
3740
+ }
3741
+ }
3742
+ };
3743
+ }
3744
+ function createEnterpriseBrowserTool(config) {
3745
+ const baseUrl = config?.baseUrl;
3746
+ const defaultProfile = config?.defaultProfile;
3747
+ return {
3748
+ label: "Browser",
3749
+ name: "browser",
3750
+ description: [
3751
+ "Control the browser for web automation \u2014 navigate, screenshot, snapshot (accessibility tree), click, type, hover, drag, fill forms, manage tabs, capture console logs, save PDFs, upload files, and handle dialogs.",
3752
+ "Actions: status, start, stop, profiles, tabs, open, focus, close, snapshot, screenshot, navigate, console, pdf, upload, dialog, act.",
3753
+ "Use snapshot+act for UI automation. snapshot returns the page accessibility tree; use refs from it with act to interact.",
3754
+ 'snapshot format="ai" returns a text description; format="aria" returns structured nodes.',
3755
+ "act supports: click, type, press, hover, drag, select, fill, resize, wait, evaluate, close.",
3756
+ "For multi-tab workflows, use tabs to list, open to create, focus to switch, close to remove."
3757
+ ].join(" "),
3758
+ parameters: BrowserToolSchema,
3759
+ execute: async (_toolCallId, args) => {
3760
+ const params = args;
3761
+ const action = readStringParam(params, "action", { required: true });
3762
+ const profile = readStringParam(params, "profile") || defaultProfile;
3763
+ switch (action) {
3764
+ case "status":
3765
+ return jsonResult(await browserStatus(baseUrl, { profile }));
3766
+ case "start":
3767
+ await browserStart(baseUrl, { profile });
3768
+ return jsonResult(await browserStatus(baseUrl, { profile }));
3769
+ case "stop":
3770
+ await browserStop(baseUrl, { profile });
3771
+ return jsonResult(await browserStatus(baseUrl, { profile }));
3772
+ case "profiles":
3773
+ return jsonResult({ profiles: await browserProfiles(baseUrl) });
3774
+ case "tabs": {
3775
+ const tabs = await browserTabs(baseUrl, { profile });
3776
+ const wrapped = wrapBrowserExternalJson({
3777
+ kind: "tabs",
3778
+ payload: { tabs },
3779
+ includeWarning: false
3780
+ });
3781
+ return {
3782
+ content: [{ type: "text", text: wrapped.wrappedText }],
3783
+ details: { ...wrapped.safeDetails, tabCount: tabs.length }
3784
+ };
3785
+ }
3786
+ case "open": {
3787
+ const targetUrl = readStringParam(params, "targetUrl", { required: true });
3788
+ return jsonResult(await browserOpenTab(baseUrl, targetUrl, { profile }));
3789
+ }
3790
+ case "focus": {
3791
+ const targetId = readStringParam(params, "targetId", { required: true });
3792
+ await browserFocusTab(baseUrl, targetId, { profile });
3793
+ return jsonResult({ ok: true });
3794
+ }
3795
+ case "close": {
3796
+ const targetId = readStringParam(params, "targetId");
3797
+ if (targetId) {
3798
+ await browserCloseTab(baseUrl, targetId, { profile });
3799
+ } else {
3800
+ await browserAct(baseUrl, { kind: "close" }, { profile });
3801
+ }
3802
+ return jsonResult({ ok: true });
3803
+ }
3804
+ case "snapshot": {
3805
+ const format = params.snapshotFormat === "ai" || params.snapshotFormat === "aria" ? params.snapshotFormat : "ai";
3806
+ const mode = params.mode === "efficient" ? "efficient" : void 0;
3807
+ const labels = typeof params.labels === "boolean" ? params.labels : void 0;
3808
+ const refs = params.refs === "aria" || params.refs === "role" ? params.refs : void 0;
3809
+ const hasMaxChars = Object.hasOwn(params, "maxChars");
3810
+ const targetId = typeof params.targetId === "string" ? params.targetId.trim() : void 0;
3811
+ const limit = typeof params.limit === "number" && Number.isFinite(params.limit) ? params.limit : void 0;
3812
+ const maxChars = typeof params.maxChars === "number" && Number.isFinite(params.maxChars) && params.maxChars > 0 ? Math.floor(params.maxChars) : void 0;
3813
+ const resolvedMaxChars = format === "ai" ? hasMaxChars ? maxChars : mode === "efficient" ? void 0 : DEFAULT_AI_SNAPSHOT_MAX_CHARS : void 0;
3814
+ const interactive = typeof params.interactive === "boolean" ? params.interactive : void 0;
3815
+ const compact = typeof params.compact === "boolean" ? params.compact : void 0;
3816
+ const depth = typeof params.depth === "number" && Number.isFinite(params.depth) ? params.depth : void 0;
3817
+ const selector = typeof params.selector === "string" ? params.selector.trim() : void 0;
3818
+ const frame = typeof params.frame === "string" ? params.frame.trim() : void 0;
3819
+ const snapshot = await browserSnapshot(baseUrl, {
3820
+ format,
3821
+ targetId,
3822
+ limit,
3823
+ ...typeof resolvedMaxChars === "number" ? { maxChars: resolvedMaxChars } : {},
3824
+ refs,
3825
+ interactive,
3826
+ compact,
3827
+ depth,
3828
+ selector,
3829
+ frame,
3830
+ labels,
3831
+ mode,
3832
+ profile
3833
+ });
3834
+ if (snapshot.format === "ai") {
3835
+ const extractedText = snapshot.snapshot ?? "";
3836
+ const wrappedSnapshot = wrapExternalContent(extractedText, {
3837
+ source: "browser",
3838
+ includeWarning: true
3839
+ });
3840
+ const safeDetails = {
3841
+ ok: true,
3842
+ format: snapshot.format,
3843
+ targetId: snapshot.targetId,
3844
+ url: snapshot.url,
3845
+ truncated: snapshot.truncated,
3846
+ stats: snapshot.stats,
3847
+ refs: snapshot.refs ? Object.keys(snapshot.refs).length : void 0,
3848
+ labels: snapshot.labels,
3849
+ labelsCount: snapshot.labelsCount,
3850
+ labelsSkipped: snapshot.labelsSkipped,
3851
+ imagePath: snapshot.imagePath,
3852
+ imageType: snapshot.imageType,
3853
+ externalContent: {
3854
+ untrusted: true,
3855
+ source: "browser",
3856
+ kind: "snapshot",
3857
+ format: "ai",
3858
+ wrapped: true
3859
+ }
3860
+ };
3861
+ if (labels && snapshot.imagePath) {
3862
+ return await imageResultFromFile({
3863
+ label: "browser:snapshot",
3864
+ path: snapshot.imagePath,
3865
+ extraText: wrappedSnapshot,
3866
+ details: safeDetails
3867
+ });
3868
+ }
3869
+ return {
3870
+ content: [{ type: "text", text: wrappedSnapshot }],
3871
+ details: safeDetails
3872
+ };
3873
+ }
3874
+ const wrapped = wrapBrowserExternalJson({
3875
+ kind: "snapshot",
3876
+ payload: snapshot
3877
+ });
3878
+ return {
3879
+ content: [{ type: "text", text: wrapped.wrappedText }],
3880
+ details: {
3881
+ ...wrapped.safeDetails,
3882
+ format: "aria",
3883
+ targetId: snapshot.targetId,
3884
+ url: snapshot.url,
3885
+ nodeCount: snapshot.nodes.length
3886
+ }
3887
+ };
3888
+ }
3889
+ case "screenshot": {
3890
+ const targetId = readStringParam(params, "targetId");
3891
+ const fullPage = Boolean(params.fullPage);
3892
+ const ref = readStringParam(params, "ref");
3893
+ const element = readStringParam(params, "element");
3894
+ const type = params.type === "jpeg" ? "jpeg" : "png";
3895
+ const result = await browserScreenshotAction(baseUrl, {
3896
+ targetId,
3897
+ fullPage,
3898
+ ref,
3899
+ element,
3900
+ type,
3901
+ profile
3902
+ });
3903
+ return await imageResultFromFile({
3904
+ label: "browser:screenshot",
3905
+ path: result.path,
3906
+ details: result
3907
+ });
3908
+ }
3909
+ case "navigate": {
3910
+ const targetUrl = readStringParam(params, "targetUrl", { required: true });
3911
+ const targetId = readStringParam(params, "targetId");
3912
+ return jsonResult(
3913
+ await browserNavigate(baseUrl, {
3914
+ url: targetUrl,
3915
+ targetId,
3916
+ profile
3917
+ })
3918
+ );
3919
+ }
3920
+ case "console": {
3921
+ const level = typeof params.level === "string" ? params.level.trim() : void 0;
3922
+ const targetId = typeof params.targetId === "string" ? params.targetId.trim() : void 0;
3923
+ const result = await browserConsoleMessages(baseUrl, { level, targetId, profile });
3924
+ const wrapped = wrapBrowserExternalJson({
3925
+ kind: "console",
3926
+ payload: result,
3927
+ includeWarning: false
3928
+ });
3929
+ return {
3930
+ content: [{ type: "text", text: wrapped.wrappedText }],
3931
+ details: {
3932
+ ...wrapped.safeDetails,
3933
+ targetId: result.targetId,
3934
+ messageCount: result.messages.length
3935
+ }
3936
+ };
3937
+ }
3938
+ case "pdf": {
3939
+ const targetId = typeof params.targetId === "string" ? params.targetId.trim() : void 0;
3940
+ const result = await browserPdfSave(baseUrl, { targetId, profile });
3941
+ return {
3942
+ content: [{ type: "text", text: `FILE:${result.path}` }],
3943
+ details: result
3944
+ };
3945
+ }
3946
+ case "upload": {
3947
+ const paths = Array.isArray(params.paths) ? params.paths.map((p) => String(p)) : [];
3948
+ if (paths.length === 0) throw new Error("paths required");
3949
+ const uploadDir = config?.uploadDir || DEFAULT_UPLOAD_DIR;
3950
+ const normalizedPaths = resolvePathsWithinRoot(uploadDir, ...paths);
3951
+ const ref = readStringParam(params, "ref");
3952
+ const inputRef = readStringParam(params, "inputRef");
3953
+ const element = readStringParam(params, "element");
3954
+ const targetId = typeof params.targetId === "string" ? params.targetId.trim() : void 0;
3955
+ const timeoutMs = typeof params.timeoutMs === "number" && Number.isFinite(params.timeoutMs) ? params.timeoutMs : void 0;
3956
+ return jsonResult(
3957
+ await browserArmFileChooser(baseUrl, {
3958
+ paths: normalizedPaths,
3959
+ ref,
3960
+ inputRef,
3961
+ element,
3962
+ targetId,
3963
+ timeoutMs,
3964
+ profile
3965
+ })
3966
+ );
3967
+ }
3968
+ case "dialog": {
3969
+ const accept = Boolean(params.accept);
3970
+ const promptText = typeof params.promptText === "string" ? params.promptText : void 0;
3971
+ const targetId = typeof params.targetId === "string" ? params.targetId.trim() : void 0;
3972
+ const timeoutMs = typeof params.timeoutMs === "number" && Number.isFinite(params.timeoutMs) ? params.timeoutMs : void 0;
3973
+ return jsonResult(
3974
+ await browserArmDialog(baseUrl, {
3975
+ accept,
3976
+ promptText,
3977
+ targetId,
3978
+ timeoutMs,
3979
+ profile
3980
+ })
3981
+ );
3982
+ }
3983
+ case "act": {
3984
+ const request = params.request;
3985
+ if (!request || typeof request !== "object") throw new Error("request required");
3986
+ if (request.kind === "evaluate" && config?.allowEvaluate === false) {
3987
+ throw new Error("JavaScript evaluation is disabled for this agent. Enable it in agent config.");
3988
+ }
3989
+ const result = await browserAct(baseUrl, request, {
3990
+ profile
3991
+ });
3992
+ return jsonResult(result);
3993
+ }
3994
+ default:
3995
+ throw new Error(`Unknown browser action: ${action}`);
3996
+ }
3997
+ }
3998
+ };
3999
+ }
4000
+ export {
4001
+ createEnterpriseBrowserTool
4002
+ };