pi-agent-browser-native 0.9.5 → 0.9.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (380) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +3 -0
  3. package/dist/extensions/agent-browser/index.js +1214 -583
  4. package/dist/packaged/lib/browser-session-conversion.js +2810 -0
  5. package/dist/packaged/lib/config-policy.js +599 -0
  6. package/dist/packaged/lib/parsing.js +34 -0
  7. package/dist/packaged/lib/playbook.js +694 -0
  8. package/dist/packaged/lib/results/snapshot.js +2671 -0
  9. package/dist/packaged/lib/runtime.js +3027 -0
  10. package/docs/ARCHITECTURE.md +11 -1
  11. package/docs/CODE_QUALITY.md +11 -0
  12. package/docs/COMMAND_REFERENCE.md +2 -2
  13. package/docs/PERFORMANCE.md +243 -0
  14. package/docs/REFERENCE.md +3 -3
  15. package/docs/SESSION_STORAGE.md +11 -3
  16. package/docs/SUPPORT_MATRIX.md +8 -4
  17. package/docs/TOOL_CONTRACT.md +4 -4
  18. package/docs/performance/2026-10-12.json +7257 -0
  19. package/package.json +13 -2
  20. package/scripts/build.mjs +16 -5
  21. package/scripts/config.mjs +1 -1
  22. package/scripts/convert-browser-session.mjs +1 -1
  23. package/dist/extensions/agent-browser/lib/argv-descriptor.js +0 -123
  24. package/dist/extensions/agent-browser/lib/argv-grammar.js +0 -320
  25. package/dist/extensions/agent-browser/lib/bash-guard.js +0 -193
  26. package/dist/extensions/agent-browser/lib/batch-lifecycle.js +0 -131
  27. package/dist/extensions/agent-browser/lib/browser-execution-claim-codec.js +0 -61
  28. package/dist/extensions/agent-browser/lib/browser-execution-claim-storage.js +0 -232
  29. package/dist/extensions/agent-browser/lib/browser-execution-claims.js +0 -202
  30. package/dist/extensions/agent-browser/lib/browser-execution-identity.js +0 -77
  31. package/dist/extensions/agent-browser/lib/browser-journal-branch.js +0 -98
  32. package/dist/extensions/agent-browser/lib/browser-journal-contracts.js +0 -1
  33. package/dist/extensions/agent-browser/lib/browser-journal-projection.js +0 -221
  34. package/dist/extensions/agent-browser/lib/browser-journal-reader.js +0 -89
  35. package/dist/extensions/agent-browser/lib/browser-journal-replay.js +0 -246
  36. package/dist/extensions/agent-browser/lib/browser-journal.js +0 -148
  37. package/dist/extensions/agent-browser/lib/browser-legacy-pages.js +0 -220
  38. package/dist/extensions/agent-browser/lib/browser-legacy-projection.js +0 -282
  39. package/dist/extensions/agent-browser/lib/browser-legacy-types.js +0 -1
  40. package/dist/extensions/agent-browser/lib/browser-session-conversion-stream.js +0 -217
  41. package/dist/extensions/agent-browser/lib/browser-session-conversion.js +0 -126
  42. package/dist/extensions/agent-browser/lib/browser-transcript-contracts.js +0 -35
  43. package/dist/extensions/agent-browser/lib/browser-transcript-validation.js +0 -166
  44. package/dist/extensions/agent-browser/lib/browser-transcript.js +0 -189
  45. package/dist/extensions/agent-browser/lib/browser-value-parsing.js +0 -15
  46. package/dist/extensions/agent-browser/lib/command-capabilities.js +0 -340
  47. package/dist/extensions/agent-browser/lib/command-policy.js +0 -155
  48. package/dist/extensions/agent-browser/lib/command-taxonomy.js +0 -105
  49. package/dist/extensions/agent-browser/lib/config-policy.js +0 -450
  50. package/dist/extensions/agent-browser/lib/config-providers.js +0 -71
  51. package/dist/extensions/agent-browser/lib/config-validation.js +0 -231
  52. package/dist/extensions/agent-browser/lib/config.js +0 -69
  53. package/dist/extensions/agent-browser/lib/electron/cdp.js +0 -62
  54. package/dist/extensions/agent-browser/lib/electron/cleanup.js +0 -274
  55. package/dist/extensions/agent-browser/lib/electron/discovery-darwin.js +0 -109
  56. package/dist/extensions/agent-browser/lib/electron/discovery-desktop.js +0 -136
  57. package/dist/extensions/agent-browser/lib/electron/discovery-evidence.js +0 -90
  58. package/dist/extensions/agent-browser/lib/electron/discovery-linux.js +0 -93
  59. package/dist/extensions/agent-browser/lib/electron/discovery-packages.js +0 -162
  60. package/dist/extensions/agent-browser/lib/electron/discovery-types.js +0 -2
  61. package/dist/extensions/agent-browser/lib/electron/discovery.js +0 -217
  62. package/dist/extensions/agent-browser/lib/electron/launch-monitor.js +0 -102
  63. package/dist/extensions/agent-browser/lib/electron/launch-process.js +0 -209
  64. package/dist/extensions/agent-browser/lib/electron/launch-types.js +0 -2
  65. package/dist/extensions/agent-browser/lib/electron/launch.js +0 -340
  66. package/dist/extensions/agent-browser/lib/executable-path.js +0 -29
  67. package/dist/extensions/agent-browser/lib/execution-cwd.js +0 -67
  68. package/dist/extensions/agent-browser/lib/fs-utils.js +0 -10
  69. package/dist/extensions/agent-browser/lib/input-modes/electron.js +0 -201
  70. package/dist/extensions/agent-browser/lib/input-modes/job.js +0 -198
  71. package/dist/extensions/agent-browser/lib/input-modes/lookup-network-evidence.js +0 -116
  72. package/dist/extensions/agent-browser/lib/input-modes/lookup-plan.js +0 -132
  73. package/dist/extensions/agent-browser/lib/input-modes/lookup-redaction.js +0 -57
  74. package/dist/extensions/agent-browser/lib/input-modes/lookup-source-evidence.js +0 -151
  75. package/dist/extensions/agent-browser/lib/input-modes/lookup-workspace.js +0 -142
  76. package/dist/extensions/agent-browser/lib/input-modes/lookups.js +0 -84
  77. package/dist/extensions/agent-browser/lib/input-modes/params.js +0 -195
  78. package/dist/extensions/agent-browser/lib/input-modes/qa-analysis.js +0 -268
  79. package/dist/extensions/agent-browser/lib/input-modes/qa-presentation.js +0 -117
  80. package/dist/extensions/agent-browser/lib/input-modes/script-child.js +0 -396
  81. package/dist/extensions/agent-browser/lib/input-modes/script-protocol.js +0 -86
  82. package/dist/extensions/agent-browser/lib/input-modes/script-types.js +0 -1
  83. package/dist/extensions/agent-browser/lib/input-modes/script-validation.js +0 -60
  84. package/dist/extensions/agent-browser/lib/input-modes/script.js +0 -108
  85. package/dist/extensions/agent-browser/lib/input-modes/semantic-action.js +0 -243
  86. package/dist/extensions/agent-browser/lib/input-modes/shared.js +0 -48
  87. package/dist/extensions/agent-browser/lib/input-modes/types.js +0 -65
  88. package/dist/extensions/agent-browser/lib/json-schema.js +0 -65
  89. package/dist/extensions/agent-browser/lib/launch-scoped-flags.js +0 -212
  90. package/dist/extensions/agent-browser/lib/managed-session-policy-lock.js +0 -165
  91. package/dist/extensions/agent-browser/lib/managed-session-posix-storage.js +0 -58
  92. package/dist/extensions/agent-browser/lib/managed-session-project-identity.js +0 -244
  93. package/dist/extensions/agent-browser/lib/managed-session-restore-context.js +0 -84
  94. package/dist/extensions/agent-browser/lib/managed-session-restore-policy.js +0 -119
  95. package/dist/extensions/agent-browser/lib/managed-session-restore-state.js +0 -83
  96. package/dist/extensions/agent-browser/lib/managed-session-restore.js +0 -212
  97. package/dist/extensions/agent-browser/lib/managed-session-snapshot-records.js +0 -277
  98. package/dist/extensions/agent-browser/lib/managed-session-snapshots.js +0 -181
  99. package/dist/extensions/agent-browser/lib/managed-session-storage.js +0 -126
  100. package/dist/extensions/agent-browser/lib/native-confirmation.js +0 -140
  101. package/dist/extensions/agent-browser/lib/native-output.js +0 -81
  102. package/dist/extensions/agent-browser/lib/orchestration/batch-stdin.js +0 -182
  103. package/dist/extensions/agent-browser/lib/orchestration/browser-run/artifact-merge.js +0 -30
  104. package/dist/extensions/agent-browser/lib/orchestration/browser-run/artifact-paths.js +0 -188
  105. package/dist/extensions/agent-browser/lib/orchestration/browser-run/browser-observation-result.js +0 -82
  106. package/dist/extensions/agent-browser/lib/orchestration/browser-run/click-dispatch.js +0 -406
  107. package/dist/extensions/agent-browser/lib/orchestration/browser-run/diagnostic-values.js +0 -31
  108. package/dist/extensions/agent-browser/lib/orchestration/browser-run/diagnostics.js +0 -240
  109. package/dist/extensions/agent-browser/lib/orchestration/browser-run/electron-observation.js +0 -203
  110. package/dist/extensions/agent-browser/lib/orchestration/browser-run/electron-text-diagnostics.js +0 -109
  111. package/dist/extensions/agent-browser/lib/orchestration/browser-run/fill-diagnostics.js +0 -119
  112. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-action-recovery.js +0 -147
  113. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-actions.js +0 -144
  114. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-content.js +0 -123
  115. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-contracts.js +0 -1
  116. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-details.js +0 -156
  117. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-electron.js +0 -187
  118. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-evidence.js +0 -39
  119. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-missing-binary.js +0 -89
  120. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-recovery.js +0 -97
  121. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-redaction.js +0 -106
  122. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-timeout.js +0 -110
  123. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result.js +0 -53
  124. package/dist/extensions/agent-browser/lib/orchestration/browser-run/index.js +0 -224
  125. package/dist/extensions/agent-browser/lib/orchestration/browser-run/interaction-diagnostics.js +0 -290
  126. package/dist/extensions/agent-browser/lib/orchestration/browser-run/managed-session-close.js +0 -167
  127. package/dist/extensions/agent-browser/lib/orchestration/browser-run/managed-session-daemon-inspection.js +0 -108
  128. package/dist/extensions/agent-browser/lib/orchestration/browser-run/managed-session-daemon-policy.js +0 -174
  129. package/dist/extensions/agent-browser/lib/orchestration/browser-run/native-helper-observation.js +0 -65
  130. package/dist/extensions/agent-browser/lib/orchestration/browser-run/observation-types.js +0 -1
  131. package/dist/extensions/agent-browser/lib/orchestration/browser-run/overlay-diagnostics.js +0 -120
  132. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare/network-page-filter.js +0 -192
  133. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare/scroll-shims.js +0 -225
  134. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare/snapshot-filter-data.js +0 -150
  135. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare/snapshot-filter.js +0 -174
  136. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare/snapshot-rendered-text.js +0 -147
  137. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare/wait-timeouts.js +0 -145
  138. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-artifacts.js +0 -159
  139. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-command.js +0 -131
  140. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-contracts.js +0 -1
  141. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-daemon.js +0 -93
  142. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-failure.js +0 -42
  143. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-guards.js +0 -242
  144. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-input.js +0 -75
  145. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-observations.js +0 -92
  146. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-page-selection.js +0 -254
  147. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-page-state.js +0 -121
  148. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-refs.js +0 -130
  149. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-resources.js +0 -114
  150. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-semantic.js +0 -121
  151. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-session-plan.js +0 -222
  152. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-timeouts.js +0 -68
  153. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare.js +0 -202
  154. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-analysis.js +0 -191
  155. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-confirmation.js +0 -152
  156. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-diagnostics.js +0 -182
  157. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-electron.js +0 -150
  158. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-lifecycle-contracts.js +0 -1
  159. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-lifecycle-phase-contracts.js +0 -1
  160. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-lifecycle-phase.js +0 -115
  161. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-lifecycle.js +0 -256
  162. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-managed-contracts.js +0 -1
  163. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-managed.js +0 -256
  164. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-native-phase-contracts.js +0 -1
  165. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-native-phase.js +0 -93
  166. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-native.js +0 -113
  167. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-navigation-contracts.js +0 -1
  168. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-navigation.js +0 -316
  169. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-ownership.js +0 -28
  170. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-page-phase-contracts.js +0 -1
  171. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-page-phase.js +0 -142
  172. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-presentation-contracts.js +0 -1
  173. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-presentation.js +0 -333
  174. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-publication-phase-contracts.js +0 -1
  175. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-publication-phase.js +0 -71
  176. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-publication.js +0 -201
  177. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-receipts.js +0 -183
  178. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-refs.js +0 -200
  179. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-tabs.js +0 -142
  180. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output.js +0 -25
  181. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prompt-guards.js +0 -50
  182. package/dist/extensions/agent-browser/lib/orchestration/browser-run/recording-receipt-reconciliation.js +0 -198
  183. package/dist/extensions/agent-browser/lib/orchestration/browser-run/recording-recovery-contracts.js +0 -1
  184. package/dist/extensions/agent-browser/lib/orchestration/browser-run/recording-recovery-presentation.js +0 -154
  185. package/dist/extensions/agent-browser/lib/orchestration/browser-run/recording-recovery.js +0 -80
  186. package/dist/extensions/agent-browser/lib/orchestration/browser-run/screenshot-capture.js +0 -14
  187. package/dist/extensions/agent-browser/lib/orchestration/browser-run/screenshot-observation.js +0 -206
  188. package/dist/extensions/agent-browser/lib/orchestration/browser-run/session-state-commands.js +0 -130
  189. package/dist/extensions/agent-browser/lib/orchestration/browser-run/session-state-electron.js +0 -212
  190. package/dist/extensions/agent-browser/lib/orchestration/browser-run/session-state-observations.js +0 -61
  191. package/dist/extensions/agent-browser/lib/orchestration/browser-run/session-state-outcomes.js +0 -187
  192. package/dist/extensions/agent-browser/lib/orchestration/browser-run/session-state-refs.js +0 -169
  193. package/dist/extensions/agent-browser/lib/orchestration/browser-run/session-state-tabs.js +0 -228
  194. package/dist/extensions/agent-browser/lib/orchestration/browser-run/session-state.js +0 -117
  195. package/dist/extensions/agent-browser/lib/orchestration/browser-run/text-visibility-diagnostics.js +0 -182
  196. package/dist/extensions/agent-browser/lib/orchestration/browser-run/timeout-diagnostics.js +0 -256
  197. package/dist/extensions/agent-browser/lib/orchestration/browser-run/timeout-progress.js +0 -108
  198. package/dist/extensions/agent-browser/lib/orchestration/browser-run/types.js +0 -1
  199. package/dist/extensions/agent-browser/lib/orchestration/code-artifact-observation.js +0 -39
  200. package/dist/extensions/agent-browser/lib/orchestration/code-image-observation.js +0 -119
  201. package/dist/extensions/agent-browser/lib/orchestration/electron-host/branch.js +0 -93
  202. package/dist/extensions/agent-browser/lib/orchestration/electron-host/cleanup-result.js +0 -58
  203. package/dist/extensions/agent-browser/lib/orchestration/electron-host/cleanup.js +0 -78
  204. package/dist/extensions/agent-browser/lib/orchestration/electron-host/contracts.js +0 -1
  205. package/dist/extensions/agent-browser/lib/orchestration/electron-host/discovery.js +0 -106
  206. package/dist/extensions/agent-browser/lib/orchestration/electron-host/index.js +0 -60
  207. package/dist/extensions/agent-browser/lib/orchestration/electron-host/policy.js +0 -86
  208. package/dist/extensions/agent-browser/lib/orchestration/electron-host/probe-collection.js +0 -68
  209. package/dist/extensions/agent-browser/lib/orchestration/electron-host/probe-data.js +0 -169
  210. package/dist/extensions/agent-browser/lib/orchestration/electron-host/probe-presentation.js +0 -182
  211. package/dist/extensions/agent-browser/lib/orchestration/electron-host/probe.js +0 -161
  212. package/dist/extensions/agent-browser/lib/orchestration/electron-host/status.js +0 -167
  213. package/dist/extensions/agent-browser/lib/orchestration/execution-queue.js +0 -98
  214. package/dist/extensions/agent-browser/lib/orchestration/extension-artifact-preflight.js +0 -211
  215. package/dist/extensions/agent-browser/lib/orchestration/extension-artifacts.js +0 -23
  216. package/dist/extensions/agent-browser/lib/orchestration/extension-attachment-replay.js +0 -99
  217. package/dist/extensions/agent-browser/lib/orchestration/extension-branch-restore.js +0 -275
  218. package/dist/extensions/agent-browser/lib/orchestration/extension-code.js +0 -280
  219. package/dist/extensions/agent-browser/lib/orchestration/extension-command-admission.js +0 -303
  220. package/dist/extensions/agent-browser/lib/orchestration/extension-command-output.js +0 -36
  221. package/dist/extensions/agent-browser/lib/orchestration/extension-command-result.js +0 -335
  222. package/dist/extensions/agent-browser/lib/orchestration/extension-command-run.js +0 -227
  223. package/dist/extensions/agent-browser/lib/orchestration/extension-command-state.js +0 -1
  224. package/dist/extensions/agent-browser/lib/orchestration/extension-electron-ownership.js +0 -204
  225. package/dist/extensions/agent-browser/lib/orchestration/extension-execution-locks.js +0 -139
  226. package/dist/extensions/agent-browser/lib/orchestration/extension-execution-queue.js +0 -24
  227. package/dist/extensions/agent-browser/lib/orchestration/extension-host-coordination.js +0 -98
  228. package/dist/extensions/agent-browser/lib/orchestration/extension-host-run.js +0 -295
  229. package/dist/extensions/agent-browser/lib/orchestration/extension-intent-replay.js +0 -41
  230. package/dist/extensions/agent-browser/lib/orchestration/extension-invocation.js +0 -7
  231. package/dist/extensions/agent-browser/lib/orchestration/extension-lifecycle.js +0 -102
  232. package/dist/extensions/agent-browser/lib/orchestration/extension-managed-ownership.js +0 -133
  233. package/dist/extensions/agent-browser/lib/orchestration/extension-observation.js +0 -120
  234. package/dist/extensions/agent-browser/lib/orchestration/extension-prompt.js +0 -180
  235. package/dist/extensions/agent-browser/lib/orchestration/extension-recording.js +0 -290
  236. package/dist/extensions/agent-browser/lib/orchestration/extension-resource-contracts.js +0 -1
  237. package/dist/extensions/agent-browser/lib/orchestration/extension-resource-replay.js +0 -269
  238. package/dist/extensions/agent-browser/lib/orchestration/extension-result-state.js +0 -113
  239. package/dist/extensions/agent-browser/lib/orchestration/extension-runtime.js +0 -146
  240. package/dist/extensions/agent-browser/lib/orchestration/extension-script-leases.js +0 -58
  241. package/dist/extensions/agent-browser/lib/orchestration/extension-tool-boundary.js +0 -62
  242. package/dist/extensions/agent-browser/lib/orchestration/extension-version-check.js +0 -54
  243. package/dist/extensions/agent-browser/lib/orchestration/input-plan-types.js +0 -1
  244. package/dist/extensions/agent-browser/lib/orchestration/input-plan.js +0 -313
  245. package/dist/extensions/agent-browser/lib/orchestration/input-redaction.js +0 -62
  246. package/dist/extensions/agent-browser/lib/orchestration/native-config.js +0 -144
  247. package/dist/extensions/agent-browser/lib/orchestration/native-root-launch.js +0 -77
  248. package/dist/extensions/agent-browser/lib/orchestration/native-session-defaults.js +0 -231
  249. package/dist/extensions/agent-browser/lib/orchestration/operation-paths.js +0 -142
  250. package/dist/extensions/agent-browser/lib/orchestration/output-file.js +0 -276
  251. package/dist/extensions/agent-browser/lib/orchestration/script-mode.js +0 -220
  252. package/dist/extensions/agent-browser/lib/owned-managed-session-context.js +0 -55
  253. package/dist/extensions/agent-browser/lib/page-target-batch.js +0 -118
  254. package/dist/extensions/agent-browser/lib/page-target-guards.js +0 -50
  255. package/dist/extensions/agent-browser/lib/page-target-navigation.js +0 -104
  256. package/dist/extensions/agent-browser/lib/page-target-validation.js +0 -90
  257. package/dist/extensions/agent-browser/lib/parsing.js +0 -30
  258. package/dist/extensions/agent-browser/lib/pi-tool-rendering.js +0 -343
  259. package/dist/extensions/agent-browser/lib/playbook.js +0 -146
  260. package/dist/extensions/agent-browser/lib/process-child.js +0 -284
  261. package/dist/extensions/agent-browser/lib/process-environment.js +0 -48
  262. package/dist/extensions/agent-browser/lib/process-errors.js +0 -23
  263. package/dist/extensions/agent-browser/lib/process-identity.js +0 -127
  264. package/dist/extensions/agent-browser/lib/process-socket-storage.js +0 -256
  265. package/dist/extensions/agent-browser/lib/process-stdout.js +0 -74
  266. package/dist/extensions/agent-browser/lib/process.js +0 -216
  267. package/dist/extensions/agent-browser/lib/prompt-artifacts.js +0 -287
  268. package/dist/extensions/agent-browser/lib/prompt-policy.js +0 -54
  269. package/dist/extensions/agent-browser/lib/read-command.js +0 -41
  270. package/dist/extensions/agent-browser/lib/read-confirmation.js +0 -162
  271. package/dist/extensions/agent-browser/lib/recording-reservations.js +0 -208
  272. package/dist/extensions/agent-browser/lib/redaction-fields.js +0 -75
  273. package/dist/extensions/agent-browser/lib/redaction-json.js +0 -149
  274. package/dist/extensions/agent-browser/lib/redaction-url.js +0 -88
  275. package/dist/extensions/agent-browser/lib/results/action-contracts.js +0 -1
  276. package/dist/extensions/agent-browser/lib/results/action-recommendations.js +0 -38
  277. package/dist/extensions/agent-browser/lib/results/artifact-contracts.js +0 -1
  278. package/dist/extensions/agent-browser/lib/results/artifact-manifest-validation.js +0 -133
  279. package/dist/extensions/agent-browser/lib/results/artifact-manifest.js +0 -173
  280. package/dist/extensions/agent-browser/lib/results/artifact-recommendations.js +0 -73
  281. package/dist/extensions/agent-browser/lib/results/categories.js +0 -152
  282. package/dist/extensions/agent-browser/lib/results/confirmation.js +0 -75
  283. package/dist/extensions/agent-browser/lib/results/contracts.js +0 -1
  284. package/dist/extensions/agent-browser/lib/results/editable-ref-evidence.js +0 -99
  285. package/dist/extensions/agent-browser/lib/results/electron-recommendations.js +0 -83
  286. package/dist/extensions/agent-browser/lib/results/envelope-decoding.js +0 -48
  287. package/dist/extensions/agent-browser/lib/results/envelope.js +0 -198
  288. package/dist/extensions/agent-browser/lib/results/evidence-contracts.js +0 -1
  289. package/dist/extensions/agent-browser/lib/results/failure-recommendations.js +0 -180
  290. package/dist/extensions/agent-browser/lib/results/network-routes.js +0 -133
  291. package/dist/extensions/agent-browser/lib/results/network.js +0 -89
  292. package/dist/extensions/agent-browser/lib/results/next-actions.js +0 -111
  293. package/dist/extensions/agent-browser/lib/results/presentation/artifact-files.js +0 -320
  294. package/dist/extensions/agent-browser/lib/results/presentation/artifact-format.js +0 -138
  295. package/dist/extensions/agent-browser/lib/results/presentation/artifact-images.js +0 -113
  296. package/dist/extensions/agent-browser/lib/results/presentation/artifact-verification.js +0 -145
  297. package/dist/extensions/agent-browser/lib/results/presentation/artifacts.js +0 -165
  298. package/dist/extensions/agent-browser/lib/results/presentation/batch-contracts.js +0 -1
  299. package/dist/extensions/agent-browser/lib/results/presentation/batch-recording.js +0 -118
  300. package/dist/extensions/agent-browser/lib/results/presentation/batch-redaction.js +0 -68
  301. package/dist/extensions/agent-browser/lib/results/presentation/batch-rendering.js +0 -135
  302. package/dist/extensions/agent-browser/lib/results/presentation/batch-step.js +0 -227
  303. package/dist/extensions/agent-browser/lib/results/presentation/batch-summary.js +0 -91
  304. package/dist/extensions/agent-browser/lib/results/presentation/batch.js +0 -123
  305. package/dist/extensions/agent-browser/lib/results/presentation/browser-profile-recovery.js +0 -54
  306. package/dist/extensions/agent-browser/lib/results/presentation/command-presenters.js +0 -216
  307. package/dist/extensions/agent-browser/lib/results/presentation/common.js +0 -81
  308. package/dist/extensions/agent-browser/lib/results/presentation/content.js +0 -119
  309. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-a11y.js +0 -67
  310. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-health.js +0 -79
  311. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-identity.js +0 -199
  312. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-logs.js +0 -75
  313. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-network-actions.js +0 -216
  314. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-network.js +0 -124
  315. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-redaction.js +0 -64
  316. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-storage.js +0 -209
  317. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-stream.js +0 -69
  318. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-summary.js +0 -222
  319. package/dist/extensions/agent-browser/lib/results/presentation/diagnostics.js +0 -124
  320. package/dist/extensions/agent-browser/lib/results/presentation/early-result.js +0 -70
  321. package/dist/extensions/agent-browser/lib/results/presentation/errors.js +0 -285
  322. package/dist/extensions/agent-browser/lib/results/presentation/input-contracts.js +0 -1
  323. package/dist/extensions/agent-browser/lib/results/presentation/large-output.js +0 -117
  324. package/dist/extensions/agent-browser/lib/results/presentation/navigation.js +0 -231
  325. package/dist/extensions/agent-browser/lib/results/presentation/notices.js +0 -75
  326. package/dist/extensions/agent-browser/lib/results/presentation/observation-contracts.js +0 -1
  327. package/dist/extensions/agent-browser/lib/results/presentation/observation-rendering.js +0 -127
  328. package/dist/extensions/agent-browser/lib/results/presentation/outcomes.js +0 -120
  329. package/dist/extensions/agent-browser/lib/results/presentation/output-completion.js +0 -77
  330. package/dist/extensions/agent-browser/lib/results/presentation/output-spill.js +0 -51
  331. package/dist/extensions/agent-browser/lib/results/presentation/registry.js +0 -145
  332. package/dist/extensions/agent-browser/lib/results/presentation/semantic-action.js +0 -104
  333. package/dist/extensions/agent-browser/lib/results/presentation/skills.js +0 -183
  334. package/dist/extensions/agent-browser/lib/results/presentation/source.js +0 -109
  335. package/dist/extensions/agent-browser/lib/results/presentation.js +0 -19
  336. package/dist/extensions/agent-browser/lib/results/recommendation-contracts.js +0 -1
  337. package/dist/extensions/agent-browser/lib/results/recording.js +0 -88
  338. package/dist/extensions/agent-browser/lib/results/recovery-actions.js +0 -118
  339. package/dist/extensions/agent-browser/lib/results/recovery-next-actions.js +0 -60
  340. package/dist/extensions/agent-browser/lib/results/selector-recovery-target.js +0 -83
  341. package/dist/extensions/agent-browser/lib/results/selector-recovery.js +0 -261
  342. package/dist/extensions/agent-browser/lib/results/snapshot-compact.js +0 -266
  343. package/dist/extensions/agent-browser/lib/results/snapshot-content.js +0 -32
  344. package/dist/extensions/agent-browser/lib/results/snapshot-high-value-controls.js +0 -240
  345. package/dist/extensions/agent-browser/lib/results/snapshot-refs.js +0 -103
  346. package/dist/extensions/agent-browser/lib/results/snapshot-segments.js +0 -383
  347. package/dist/extensions/agent-browser/lib/results/snapshot-spill.js +0 -53
  348. package/dist/extensions/agent-browser/lib/results/snapshot.js +0 -44
  349. package/dist/extensions/agent-browser/lib/results/text.js +0 -44
  350. package/dist/extensions/agent-browser/lib/runtime-args-validation.js +0 -133
  351. package/dist/extensions/agent-browser/lib/runtime-compatibility.js +0 -81
  352. package/dist/extensions/agent-browser/lib/runtime-contracts.js +0 -1
  353. package/dist/extensions/agent-browser/lib/runtime-redaction.js +0 -118
  354. package/dist/extensions/agent-browser/lib/runtime-replay-events.js +0 -144
  355. package/dist/extensions/agent-browser/lib/runtime-session-identity.js +0 -76
  356. package/dist/extensions/agent-browser/lib/runtime-session-plan.js +0 -114
  357. package/dist/extensions/agent-browser/lib/runtime-session-replay.js +0 -123
  358. package/dist/extensions/agent-browser/lib/runtime-tab-correction.js +0 -65
  359. package/dist/extensions/agent-browser/lib/runtime-timeouts.js +0 -28
  360. package/dist/extensions/agent-browser/lib/runtime.js +0 -163
  361. package/dist/extensions/agent-browser/lib/session-identity.js +0 -51
  362. package/dist/extensions/agent-browser/lib/session-page-observation.js +0 -357
  363. package/dist/extensions/agent-browser/lib/session-page-state.js +0 -353
  364. package/dist/extensions/agent-browser/lib/session-page-types.js +0 -1
  365. package/dist/extensions/agent-browser/lib/string-enum-schema.js +0 -8
  366. package/dist/extensions/agent-browser/lib/temp-artifact-budget.js +0 -81
  367. package/dist/extensions/agent-browser/lib/temp-mutation-queue.js +0 -7
  368. package/dist/extensions/agent-browser/lib/temp-root-ownership.js +0 -234
  369. package/dist/extensions/agent-browser/lib/temp-root.js +0 -211
  370. package/dist/extensions/agent-browser/lib/temp.js +0 -91
  371. package/dist/extensions/agent-browser/lib/tool-surface.js +0 -239
  372. package/dist/extensions/agent-browser/lib/upstream-version.js +0 -15
  373. package/dist/extensions/agent-browser/lib/web-search-providers.js +0 -193
  374. package/dist/extensions/agent-browser/lib/web-search-request.js +0 -102
  375. package/dist/extensions/agent-browser/lib/web-search-results.js +0 -281
  376. package/dist/extensions/agent-browser/lib/web-search-schema.js +0 -82
  377. package/dist/extensions/agent-browser/lib/web-search.js +0 -167
  378. package/dist/extensions/agent-browser/lib/webmcp-observation.js +0 -35
  379. package/dist/extensions/agent-browser/lib/windows-stock-launcher.js +0 -96
  380. package/dist/scripts/agent-browser-target.mjs +0 -23
@@ -0,0 +1,2671 @@
1
+ // dist/extensions/agent-browser/lib/parsing.js
2
+ function isRecord(value) {
3
+ return typeof value === "object" && value !== null;
4
+ }
5
+ function parsePositiveInteger(rawValue) {
6
+ if (typeof rawValue !== "string") {
7
+ return void 0;
8
+ }
9
+ const normalizedValue = rawValue.trim();
10
+ if (!/^\d+$/.test(normalizedValue)) {
11
+ return void 0;
12
+ }
13
+ const parsedValue = Number(normalizedValue);
14
+ if (!Number.isSafeInteger(parsedValue) || parsedValue <= 0) {
15
+ return void 0;
16
+ }
17
+ return parsedValue;
18
+ }
19
+
20
+ // dist/extensions/agent-browser/lib/results/editable-ref-evidence.js
21
+ var EDITABLE_REF_EVIDENCE_KEYS = [
22
+ "editable",
23
+ "contentEditable",
24
+ "contenteditable",
25
+ "isContentEditable"
26
+ ];
27
+ var EDITABLE_FALSE_TEXT_PATTERN = /\b(?:contenteditable|editable)\s*=\s*["']?(?:false|0)["']?/i;
28
+ var EDITABLE_ASSIGNMENT_TEXT_PATTERN = /\b(contenteditable|editable)\s*=\s*("[^"]*"|'[^']*'|[^\s,\]]+)/gi;
29
+ var EDITABLE_BARE_TEXT_PATTERN = /\b(?:contenteditable|editable)\b(?!\s*=)/i;
30
+ function parseEditableEvidenceValue(value) {
31
+ if (typeof value === "boolean") {
32
+ return value;
33
+ }
34
+ if (typeof value === "number") {
35
+ if (value === 1) {
36
+ return true;
37
+ }
38
+ if (value === 0) {
39
+ return false;
40
+ }
41
+ return void 0;
42
+ }
43
+ if (typeof value !== "string") {
44
+ return void 0;
45
+ }
46
+ const normalized = value.trim().replace(/^["']|["']$/g, "").toLowerCase();
47
+ if (["false", "0", "no"].includes(normalized)) {
48
+ return false;
49
+ }
50
+ if (["", "true", "1", "yes", "plaintext-only"].includes(normalized)) {
51
+ return true;
52
+ }
53
+ return void 0;
54
+ }
55
+ function stripLeadingSnapshotAccessibleName(text) {
56
+ return text.replace(/^(\s*[-*]\s+\S+\s+)(?:"[^"]*"|'[^']*')/, "$1");
57
+ }
58
+ function parseEditableAssignments(markerText) {
59
+ let hasPositiveAssignment = false;
60
+ for (const match of markerText.matchAll(EDITABLE_ASSIGNMENT_TEXT_PATTERN)) {
61
+ const key = match[1]?.toLowerCase();
62
+ const evidence = parseEditableEvidenceValue(match[2]);
63
+ if (evidence === false) {
64
+ return false;
65
+ }
66
+ if (evidence === true && (key === "contenteditable" || key === "editable")) {
67
+ hasPositiveAssignment = true;
68
+ }
69
+ }
70
+ return hasPositiveAssignment ? true : void 0;
71
+ }
72
+ function parseEditableEvidenceText(text) {
73
+ if (text === void 0 || text.length === 0) {
74
+ return void 0;
75
+ }
76
+ const markerText = stripLeadingSnapshotAccessibleName(text);
77
+ if (EDITABLE_FALSE_TEXT_PATTERN.test(markerText)) {
78
+ return false;
79
+ }
80
+ const assignment = parseEditableAssignments(markerText);
81
+ if (assignment !== void 0) {
82
+ return assignment;
83
+ }
84
+ return EDITABLE_BARE_TEXT_PATTERN.test(markerText) ? true : void 0;
85
+ }
86
+ function getStructuredEditableEvidence(ref) {
87
+ if (!ref) {
88
+ return void 0;
89
+ }
90
+ let hasPositiveEvidence = false;
91
+ for (const key of EDITABLE_REF_EVIDENCE_KEYS) {
92
+ const evidence = parseEditableEvidenceValue(ref[key]);
93
+ if (evidence === false) {
94
+ return false;
95
+ }
96
+ if (evidence === true) {
97
+ hasPositiveEvidence = true;
98
+ }
99
+ }
100
+ return hasPositiveEvidence ? true : void 0;
101
+ }
102
+ function getEditableRefEvidence(options) {
103
+ const structuredEvidence = getStructuredEditableEvidence(options.ref);
104
+ if (structuredEvidence === false) {
105
+ return false;
106
+ }
107
+ let hasPositiveEvidence = structuredEvidence === true;
108
+ const textEvidence = parseEditableEvidenceText(options.text);
109
+ if (textEvidence === false) {
110
+ return false;
111
+ }
112
+ if (textEvidence === true) {
113
+ hasPositiveEvidence = true;
114
+ }
115
+ return hasPositiveEvidence ? true : void 0;
116
+ }
117
+
118
+ // dist/extensions/agent-browser/lib/results/text.js
119
+ function stringifyUnknown(value) {
120
+ if (typeof value === "string") {
121
+ return value;
122
+ }
123
+ if (typeof value === "number" || typeof value === "boolean") {
124
+ return String(value);
125
+ }
126
+ if (value === null || value === void 0) {
127
+ return "";
128
+ }
129
+ try {
130
+ const serialized = JSON.stringify(value, null, 2);
131
+ return typeof serialized === "string" ? serialized : "";
132
+ } catch {
133
+ return stringifyFallback(value);
134
+ }
135
+ }
136
+ function stringifyFallback(value) {
137
+ if (typeof value === "bigint" || typeof value === "symbol" || typeof value === "function") {
138
+ return String(value);
139
+ }
140
+ return Object.prototype.toString.call(value);
141
+ }
142
+ function countLines(text) {
143
+ return text.length === 0 ? 0 : text.split("\n").length;
144
+ }
145
+ function normalizeWhitespace(text) {
146
+ return text.replace(/\s+/g, " ").trim();
147
+ }
148
+ function truncateText(text, maxChars) {
149
+ if (text.length <= maxChars) {
150
+ return text;
151
+ }
152
+ return `${text.slice(0, Math.max(1, maxChars - 1))}\u2026`;
153
+ }
154
+ function compareRefIds(left, right) {
155
+ const leftMatch = left.match(/^(?:[a-zA-Z]+)?(\d+)$/);
156
+ const rightMatch = right.match(/^(?:[a-zA-Z]+)?(\d+)$/);
157
+ if (leftMatch && rightMatch) {
158
+ return Number(leftMatch[1]) - Number(rightMatch[1]);
159
+ }
160
+ return left.localeCompare(right);
161
+ }
162
+
163
+ // dist/extensions/agent-browser/lib/results/snapshot-refs.js
164
+ function getFullSnapshotData(data) {
165
+ if (!isRecord(data)) {
166
+ return void 0;
167
+ }
168
+ if (!isRecord(data.snapshot)) {
169
+ return data;
170
+ }
171
+ return data.snapshot.kind === "full" ? { ...data, snapshot: data.snapshot.tree, refs: data.snapshot.refs } : void 0;
172
+ }
173
+ function getSnapshotRefRecord(data) {
174
+ const full = getFullSnapshotData(data);
175
+ return full && isRecord(full.refs) ? full.refs : void 0;
176
+ }
177
+ function getSnapshotRefEntries(data) {
178
+ const refs = getSnapshotRefRecord(data);
179
+ if (!refs) {
180
+ return [];
181
+ }
182
+ return Object.entries(refs).map(([id, value]) => {
183
+ if (!isRecord(value)) {
184
+ return { id, name: "", role: "unknown" };
185
+ }
186
+ const name = typeof value.name === "string" ? normalizeWhitespace(value.name) : "";
187
+ const role = typeof value.role === "string" && value.role.length > 0 ? value.role : "unknown";
188
+ const isEditable = getEditableRefEvidence({ ref: value });
189
+ return { id, isEditable, name, refData: value, role };
190
+ }).sort((a, b) => compareRefIds(a.id, b.id));
191
+ }
192
+ function isEditableSnapshotLine(line) {
193
+ const editableEvidence = getEditableRefEvidence({ text: line.raw });
194
+ if (editableEvidence !== void 0) {
195
+ return editableEvidence;
196
+ }
197
+ return line.role === "searchbox" || line.role === "textbox" || line.role === "combobox" ? true : void 0;
198
+ }
199
+ function getSnapshotRefRole(entry, editableEvidence) {
200
+ const rawRole = typeof entry.role === "string" && entry.role.length > 0 ? entry.role : "unknown";
201
+ const normalizedRole = rawRole.toLowerCase();
202
+ if ((normalizedRole === "generic" || normalizedRole === "unknown") && editableEvidence === true) {
203
+ return "textbox";
204
+ }
205
+ return rawRole;
206
+ }
207
+ function getSnapshotRefFallbackRole(role, line) {
208
+ if (role !== "unknown" && role !== "generic") {
209
+ return role;
210
+ }
211
+ return line && line.role !== "unknown" ? line.role : role;
212
+ }
213
+ function resolveSnapshotRefEditableEvidence(evidence, line) {
214
+ if (evidence !== void 0) {
215
+ return evidence;
216
+ }
217
+ return line !== void 0 && isEditableSnapshotLine(line) === true && !["unknown", "generic"].includes(line.role);
218
+ }
219
+ function enrichSnapshotRefEntries(refEntries, snapshotLines) {
220
+ const lineByRef = /* @__PURE__ */ new Map();
221
+ for (const line of snapshotLines) {
222
+ if (line.ref === void 0 || line.ref.length === 0 || lineByRef.has(line.ref)) {
223
+ continue;
224
+ }
225
+ lineByRef.set(line.ref, line);
226
+ }
227
+ return refEntries.map((entry) => {
228
+ const line = lineByRef.get(entry.id);
229
+ const editableEvidence = getEditableRefEvidence({ ref: entry.refData, text: line?.raw });
230
+ const isEditable = resolveSnapshotRefEditableEvidence(editableEvidence, line);
231
+ const roleFromRefOrLine = getSnapshotRefFallbackRole(entry.role, line);
232
+ const role = getSnapshotRefRole({ role: roleFromRefOrLine }, isEditable);
233
+ return {
234
+ ...entry,
235
+ isEditable,
236
+ lineIndex: line?.index,
237
+ name: entry.name.length > 0 ? entry.name : line?.name ?? "",
238
+ role
239
+ };
240
+ });
241
+ }
242
+
243
+ // dist/extensions/agent-browser/lib/results/snapshot-content.js
244
+ function getSnapshotText(data) {
245
+ const full = getFullSnapshotData(data);
246
+ if (typeof full?.snapshot === "string") {
247
+ return full.snapshot;
248
+ }
249
+ return isRecord(data.snapshot) ? JSON.stringify(data.snapshot) : void 0;
250
+ }
251
+ function getSnapshotOrigin(data) {
252
+ return typeof data.origin === "string" ? data.origin : "(unknown origin)";
253
+ }
254
+ function formatSnapshotSummary(data) {
255
+ const origin = typeof data.origin === "string" ? data.origin : "page";
256
+ if (isRecord(data.snapshot) && data.snapshot.kind !== "full") {
257
+ return `Snapshot ${stringifyUnknown(data.snapshot.kind)}: revision ${stringifyUnknown(data.snapshot.revision)} on ${origin}`;
258
+ }
259
+ return `Snapshot: ${Object.keys(getSnapshotRefRecord(data) ?? {}).length} refs on ${origin}`;
260
+ }
261
+ function formatRawSnapshotText(data) {
262
+ const origin = getSnapshotOrigin(data);
263
+ const refs = Object.keys(getSnapshotRefRecord(data) ?? {}).length;
264
+ const snapshot = getSnapshotText(data);
265
+ if (isRecord(data.snapshot) && data.snapshot.kind !== "full") {
266
+ return `Origin: ${origin}
267
+ ${formatSnapshotSummary(data)}
268
+
269
+ ${snapshot ?? "undefined"}`;
270
+ }
271
+ if (snapshot === void 0 || snapshot.length === 0) {
272
+ return `Origin: ${origin}
273
+ Refs: ${refs}
274
+
275
+ (no interactive elements)`;
276
+ }
277
+ return `Origin: ${origin}
278
+ Refs: ${refs}
279
+
280
+ ${snapshot}`;
281
+ }
282
+
283
+ // dist/extensions/agent-browser/lib/results/snapshot-high-value-controls.js
284
+ var SNAPSHOT_HIGH_VALUE_EDITABLE_REF_FILL_TARGET_LINES = 4;
285
+ var SNAPSHOT_HIGH_VALUE_SURFACE_REF_FILL_TARGET_LINES = 3;
286
+ var SNAPSHOT_HIGH_VALUE_PRIMARY_ACTION_REF_FILL_TARGET_LINES = 3;
287
+ var SNAPSHOT_HIGH_VALUE_NAMED_LINK_REF_FILL_TARGET_LINES = 6;
288
+ var SNAPSHOT_HIGH_VALUE_LINK_NAME_MAX_LENGTH = 80;
289
+ var SNAPSHOT_HIGH_VALUE_CONTROL_ROLES = /* @__PURE__ */ new Set([
290
+ "button",
291
+ "checkbox",
292
+ "combobox",
293
+ "link",
294
+ "menuitem",
295
+ "option",
296
+ "radio",
297
+ "searchbox",
298
+ "tab",
299
+ "textbox"
300
+ ]);
301
+ var SNAPSHOT_HIGH_VALUE_CONTROL_ROLE_PRIORITY = {
302
+ searchbox: 0,
303
+ textbox: 1,
304
+ combobox: 2,
305
+ button: 3,
306
+ link: 4,
307
+ tab: 5,
308
+ checkbox: 6,
309
+ radio: 7,
310
+ option: 8,
311
+ menuitem: 9
312
+ };
313
+ var SNAPSHOT_SURFACE_CONTROL_NAME_PATTERNS = [
314
+ /\b(?:agents?|browser|canvas|chat|editor|panel|pane|preview|surface|tab|terminal|thread|view|window|workspace)\b/i
315
+ ];
316
+ var SNAPSHOT_PRIMARY_ACTION_BUTTON_NAME_PATTERNS = [
317
+ /^(?:add|apply|ask|attach|choose|confirm|connect|continue|create|deploy|done|download|go|insert|launch|log in|new|next|ok|open|publish|refresh|retry|run|save|search|select|send|sign in|sign up|start|submit|upload)$/i,
318
+ /^(?:add|apply|ask|confirm|connect|continue|create|launch|new|open|refresh|retry|run|save|search|send|start|submit)\b/i
319
+ ];
320
+ function getHighValueControlRole(entry) {
321
+ return entry.isEditable === true && (entry.role === "unknown" || entry.role === "generic") ? "textbox" : entry.role;
322
+ }
323
+ function isEditableControlRef(entry) {
324
+ if (entry.isEditable === false) {
325
+ return false;
326
+ }
327
+ const role = getHighValueControlRole(entry);
328
+ return entry.isEditable === true || role === "searchbox" || role === "textbox" || role === "combobox";
329
+ }
330
+ function isNamedSurfaceControlRef(entry) {
331
+ if (entry.name.length === 0) {
332
+ return false;
333
+ }
334
+ const role = getHighValueControlRole(entry);
335
+ if (role === "tab") {
336
+ return true;
337
+ }
338
+ if (role !== "button" && role !== "menuitem" && role !== "option") {
339
+ return false;
340
+ }
341
+ return SNAPSHOT_SURFACE_CONTROL_NAME_PATTERNS.some((pattern) => pattern.test(entry.name));
342
+ }
343
+ function isPrimaryActionButtonRef(entry) {
344
+ return getHighValueControlRole(entry) === "button" && entry.name.length > 0 && SNAPSHOT_PRIMARY_ACTION_BUTTON_NAME_PATTERNS.some((pattern) => pattern.test(entry.name));
345
+ }
346
+ var SNAPSHOT_HIGH_VALUE_CONTROL_CATEGORY_RULES = [
347
+ {
348
+ bucketKey: () => "editable",
349
+ fillTarget: SNAPSHOT_HIGH_VALUE_EDITABLE_REF_FILL_TARGET_LINES,
350
+ id: "editable",
351
+ matches: (entry) => isEditableControlRef(entry),
352
+ priority: 0
353
+ },
354
+ {
355
+ bucketKey: () => "named-surface",
356
+ fillTarget: SNAPSHOT_HIGH_VALUE_SURFACE_REF_FILL_TARGET_LINES,
357
+ id: "named-surface",
358
+ matches: (entry) => isNamedSurfaceControlRef(entry),
359
+ priority: 1
360
+ },
361
+ {
362
+ bucketKey: () => "primary-action",
363
+ fillTarget: SNAPSHOT_HIGH_VALUE_PRIMARY_ACTION_REF_FILL_TARGET_LINES,
364
+ id: "primary-action",
365
+ matches: (entry) => isPrimaryActionButtonRef(entry),
366
+ priority: 2
367
+ },
368
+ {
369
+ bucketKey: () => "named-link",
370
+ fillTarget: SNAPSHOT_HIGH_VALUE_NAMED_LINK_REF_FILL_TARGET_LINES,
371
+ id: "named-link",
372
+ matches: (entry) => getHighValueControlRole(entry) === "link" && isNamedActionLinkRef(entry),
373
+ priority: 3
374
+ },
375
+ {
376
+ bucketKey: (_entry, role) => role,
377
+ id: "role",
378
+ matches: () => true,
379
+ priority: 4
380
+ }
381
+ ];
382
+ function isNamedActionLinkRef(entry) {
383
+ return entry.name.length > 0 && entry.name.length <= SNAPSHOT_HIGH_VALUE_LINK_NAME_MAX_LENGTH;
384
+ }
385
+ function isHighValueControlEntry(entry) {
386
+ const role = getHighValueControlRole(entry);
387
+ if (!SNAPSHOT_HIGH_VALUE_CONTROL_ROLES.has(role)) {
388
+ return false;
389
+ }
390
+ if (role === "link") {
391
+ return isNamedActionLinkRef(entry);
392
+ }
393
+ if (entry.isEditable === false && (role === "searchbox" || role === "textbox" || role === "combobox")) {
394
+ return false;
395
+ }
396
+ return entry.name.length > 0 || isEditableControlRef(entry);
397
+ }
398
+ function getHighValueControlCategoryRule(entry, role) {
399
+ return SNAPSHOT_HIGH_VALUE_CONTROL_CATEGORY_RULES.find((rule) => rule.matches(entry, role));
400
+ }
401
+ function classifyHighValueControlRef(entry) {
402
+ if (!isHighValueControlEntry(entry)) {
403
+ return void 0;
404
+ }
405
+ const role = getHighValueControlRole(entry);
406
+ const rule = getHighValueControlCategoryRule(entry, role);
407
+ if (!rule) {
408
+ return void 0;
409
+ }
410
+ return {
411
+ entry,
412
+ score: {
413
+ category: rule.id,
414
+ categoryPriority: rule.priority,
415
+ diversityBucketKey: `${rule.priority}:${rule.bucketKey(entry, role)}`,
416
+ lineIndex: entry.lineIndex ?? Number.MAX_SAFE_INTEGER,
417
+ namePriority: entry.name.length > 0 ? 0 : 1,
418
+ refId: entry.id,
419
+ role,
420
+ rolePriority: SNAPSHOT_HIGH_VALUE_CONTROL_ROLE_PRIORITY[role] ?? 50,
421
+ roundRobinBucketKey: `${rule.priority}:${role}`
422
+ }
423
+ };
424
+ }
425
+ function compareHighValueControlCandidates(left, right) {
426
+ const differences = [
427
+ left.score.categoryPriority - right.score.categoryPriority,
428
+ left.score.rolePriority - right.score.rolePriority,
429
+ left.score.namePriority - right.score.namePriority,
430
+ left.score.lineIndex - right.score.lineIndex
431
+ ];
432
+ return differences.find((difference) => difference !== 0 && !Number.isNaN(difference)) ?? compareRefIds(left.score.refId, right.score.refId);
433
+ }
434
+ var HighValueSelection = class {
435
+ selected = [];
436
+ selectedIds = /* @__PURE__ */ new Set();
437
+ candidates;
438
+ limit;
439
+ constructor(candidates, limit) {
440
+ this.candidates = candidates;
441
+ this.limit = limit;
442
+ }
443
+ take(candidate) {
444
+ this.selected.push(candidate);
445
+ this.selectedIds.add(candidate.entry.id);
446
+ }
447
+ takeFirstPerDiversityBucket() {
448
+ const seenBuckets = /* @__PURE__ */ new Set();
449
+ for (const candidate of this.candidates) {
450
+ if (this.selected.length >= this.limit) {
451
+ break;
452
+ }
453
+ if (!seenBuckets.has(candidate.score.diversityBucketKey)) {
454
+ seenBuckets.add(candidate.score.diversityBucketKey);
455
+ this.take(candidate);
456
+ }
457
+ }
458
+ }
459
+ topUp(category, target) {
460
+ let count = this.selected.filter((candidate) => candidate.score.category === category).length;
461
+ for (const candidate of this.candidates) {
462
+ if (this.selected.length >= this.limit || count >= target) {
463
+ break;
464
+ }
465
+ if (!this.selectedIds.has(candidate.entry.id) && candidate.score.category === category) {
466
+ this.take(candidate);
467
+ count += 1;
468
+ }
469
+ }
470
+ }
471
+ buildRemainingBuckets() {
472
+ const buckets = /* @__PURE__ */ new Map();
473
+ for (const candidate of this.candidates) {
474
+ if (this.selectedIds.has(candidate.entry.id)) {
475
+ continue;
476
+ }
477
+ const key = candidate.score.roundRobinBucketKey;
478
+ const bucket = buckets.get(key);
479
+ if (bucket) {
480
+ bucket.push(candidate);
481
+ } else {
482
+ buckets.set(key, [candidate]);
483
+ }
484
+ }
485
+ return [...buckets.values()].sort((left, right) => compareHighValueControlCandidates(left[0], right[0]));
486
+ }
487
+ fillRemaining() {
488
+ const buckets = this.buildRemainingBuckets();
489
+ let bucketIndex = 0;
490
+ while (this.selected.length < this.limit && buckets.some((bucket) => bucket.length > 0)) {
491
+ const candidate = buckets[bucketIndex % buckets.length].shift();
492
+ if (candidate) {
493
+ this.take(candidate);
494
+ }
495
+ bucketIndex += 1;
496
+ }
497
+ }
498
+ select() {
499
+ this.takeFirstPerDiversityBucket();
500
+ for (const rule of SNAPSHOT_HIGH_VALUE_CONTROL_CATEGORY_RULES) {
501
+ if (rule.fillTarget !== void 0) {
502
+ this.topUp(rule.id, rule.fillTarget);
503
+ }
504
+ }
505
+ this.fillRemaining();
506
+ return this.selected.map((candidate) => candidate.entry);
507
+ }
508
+ };
509
+ function selectHighValueControlEntries(entries, limit) {
510
+ const candidates = entries.map(classifyHighValueControlRef).filter((candidate) => candidate !== void 0).sort(compareHighValueControlCandidates);
511
+ return new HighValueSelection(candidates, limit).select();
512
+ }
513
+
514
+ // dist/extensions/agent-browser/lib/results/snapshot-segments.js
515
+ var SNAPSHOT_MAX_ADDITIONAL_SECTIONS = 2;
516
+ var SNAPSHOT_FALLBACK_PREVIEW_MAX_LINES = 12;
517
+ var SNAPSHOT_LINE_MAX_CHARS = 140;
518
+ var SNAPSHOT_SIGNAL_ROLES = /* @__PURE__ */ new Set([
519
+ "article",
520
+ "banner",
521
+ "button",
522
+ "checkbox",
523
+ "combobox",
524
+ "dialog",
525
+ "gridcell",
526
+ "heading",
527
+ "link",
528
+ "listitem",
529
+ "main",
530
+ "menu",
531
+ "menuitem",
532
+ "navigation",
533
+ "option",
534
+ "radio",
535
+ "region",
536
+ "row",
537
+ "searchbox",
538
+ "tab",
539
+ "textbox"
540
+ ]);
541
+ var SNAPSHOT_SEGMENT_ROOT_ROLES = /* @__PURE__ */ new Set([
542
+ "article",
543
+ "dialog",
544
+ "heading",
545
+ "main",
546
+ "menu",
547
+ "region"
548
+ ]);
549
+ var SNAPSHOT_ROLE_PRIORITY = {
550
+ article: 0,
551
+ main: 1,
552
+ dialog: 2,
553
+ menu: 3,
554
+ region: 4,
555
+ heading: 5,
556
+ searchbox: 6,
557
+ textbox: 7,
558
+ combobox: 8,
559
+ button: 9,
560
+ checkbox: 10,
561
+ radio: 11,
562
+ tab: 12,
563
+ option: 13,
564
+ link: 14,
565
+ listitem: 14,
566
+ row: 15,
567
+ gridcell: 16,
568
+ navigation: 17,
569
+ generic: 99,
570
+ unknown: 100
571
+ };
572
+ var SNAPSHOT_NOISE_NAME_PATTERNS = [
573
+ /^skip to /i,
574
+ /^ad$/i,
575
+ /^don't want to see ads\??$/i,
576
+ /keyboard shortcuts/i,
577
+ /\bpromoted\b/i,
578
+ /\bsponsored\b/i
579
+ ];
580
+ var SNAPSHOT_CHROME_SECTION_PATTERNS = [
581
+ /^primary$/i,
582
+ /^footer$/i,
583
+ /^navigation$/i,
584
+ /\bwhat['’]?s happening\b/i,
585
+ /\brelevant people\b/i,
586
+ /\btrending\b/i,
587
+ /\brelated\b/i,
588
+ /\brecommended\b/i,
589
+ /\bsuggested\b/i
590
+ ];
591
+ function getSnapshotRolePriority(role) {
592
+ return SNAPSHOT_ROLE_PRIORITY[role] ?? 50;
593
+ }
594
+ function parseSnapshotHeadingLevel(text) {
595
+ const level = text.match(/\blevel=(\d+)/)?.[1];
596
+ return level !== void 0 && level.length > 0 ? Number(level) : void 0;
597
+ }
598
+ function parseSnapshotLines(snapshot) {
599
+ return snapshot.split("\n").filter((line) => line.length > 0).map((raw, index) => {
600
+ const trimmed = raw.trimStart();
601
+ const depth = Math.floor((raw.match(/^\s*/)?.[0].length ?? 0) / 2);
602
+ const role = trimmed.match(/^[-*]\s+([^\s"]+)/)?.[1] ?? "unknown";
603
+ const name = normalizeWhitespace(trimmed.match(/"([^"]*)"/)?.[1] ?? "");
604
+ const ref = trimmed.match(/\bref=([^,\]\s]+)/)?.[1];
605
+ return {
606
+ depth,
607
+ headingLevel: parseSnapshotHeadingLevel(trimmed),
608
+ index,
609
+ name,
610
+ raw,
611
+ ref,
612
+ role
613
+ };
614
+ });
615
+ }
616
+ function isNoiseName(name) {
617
+ return SNAPSHOT_NOISE_NAME_PATTERNS.some((pattern) => pattern.test(name));
618
+ }
619
+ function isChromeSectionName(name) {
620
+ return SNAPSHOT_CHROME_SECTION_PATTERNS.some((pattern) => pattern.test(name));
621
+ }
622
+ function isNoiseSnapshotLine(line) {
623
+ if (line.name.length > 0 && isNoiseName(line.name)) {
624
+ return true;
625
+ }
626
+ const loweredRaw = line.raw.toLowerCase();
627
+ return loweredRaw.includes("promoted") || loweredRaw.includes("sponsored");
628
+ }
629
+ function isPotentialSegmentRootLine(line) {
630
+ if (!SNAPSHOT_SEGMENT_ROOT_ROLES.has(line.role)) {
631
+ return false;
632
+ }
633
+ if (isNoiseSnapshotLine(line)) {
634
+ return false;
635
+ }
636
+ if (line.role === "heading") {
637
+ return line.name.length > 0 && (line.headingLevel ?? 99) <= 3;
638
+ }
639
+ if (line.role === "region") {
640
+ return line.name.length > 0;
641
+ }
642
+ return true;
643
+ }
644
+ function getHeadingPriorityScore(level) {
645
+ switch (level) {
646
+ case 1:
647
+ return 40;
648
+ case 2:
649
+ return 22;
650
+ case 3:
651
+ return 12;
652
+ case void 0:
653
+ return 0;
654
+ default:
655
+ return 0;
656
+ }
657
+ }
658
+ function scoreSegment(segment) {
659
+ const { root } = segment;
660
+ const distinctRefs = new Set(segment.lines.flatMap((line) => line.ref !== void 0 && line.ref.length > 0 ? [line.ref] : [])).size;
661
+ let score = 0;
662
+ score += 120 - getSnapshotRolePriority(root.role) * 8;
663
+ score += Math.min(distinctRefs, 16);
664
+ score += Math.min(segment.lines.length, 12);
665
+ score -= Math.min(root.index, 60) / 3;
666
+ score -= root.depth * 6;
667
+ if (root.role === "heading") {
668
+ score += getHeadingPriorityScore(root.headingLevel);
669
+ }
670
+ if (root.name.length > 0) {
671
+ score += 10;
672
+ }
673
+ if (root.name.length <= 2) {
674
+ score -= 18;
675
+ }
676
+ if (isChromeSectionName(root.name)) {
677
+ score -= 45;
678
+ }
679
+ if (isNoiseName(root.name)) {
680
+ score -= 1e3;
681
+ }
682
+ return score;
683
+ }
684
+ function hasDuplicateSegmentAncestor(line, stack) {
685
+ const name = normalizeWhitespace(line.name.toLowerCase());
686
+ if (name.length === 0) {
687
+ return false;
688
+ }
689
+ for (let index = stack.length - 1; index >= 0; index -= 1) {
690
+ const ancestor = stack.at(index);
691
+ if (ancestor && normalizeWhitespace(ancestor.name.toLowerCase()) === name && SNAPSHOT_SEGMENT_ROOT_ROLES.has(ancestor.role)) {
692
+ return true;
693
+ }
694
+ }
695
+ return false;
696
+ }
697
+ function buildSnapshotSegments(snapshotLines) {
698
+ const roots = [];
699
+ const stack = [];
700
+ for (const line of snapshotLines) {
701
+ stack.length = line.depth;
702
+ if (isPotentialSegmentRootLine(line) && !hasDuplicateSegmentAncestor(line, stack)) {
703
+ roots.push(line);
704
+ }
705
+ stack[line.depth] = line;
706
+ }
707
+ return roots.map((root, index) => {
708
+ let endIndexExclusive = snapshotLines.length;
709
+ for (let nextIndex = index + 1; nextIndex < roots.length; nextIndex += 1) {
710
+ const candidate = roots[nextIndex];
711
+ if (candidate.depth <= root.depth) {
712
+ endIndexExclusive = candidate.index;
713
+ break;
714
+ }
715
+ }
716
+ const lines = snapshotLines.slice(root.index, endIndexExclusive);
717
+ const segment = {
718
+ endIndexExclusive,
719
+ lines,
720
+ root,
721
+ score: 0,
722
+ startIndex: root.index
723
+ };
724
+ return Object.assign({}, segment, { score: scoreSegment(segment) });
725
+ });
726
+ }
727
+ function choosePrimarySegment(segments) {
728
+ if (segments.length === 0) {
729
+ return void 0;
730
+ }
731
+ return segments.find((segment) => segment.root.role === "main" || segment.root.role === "article") ?? segments.find((segment) => segment.root.role === "heading" && segment.root.headingLevel === 1) ?? segments.find((segment) => segment.score >= 90) ?? [...segments].sort((left, right) => {
732
+ const difference = right.score - left.score;
733
+ return difference !== 0 && !Number.isNaN(difference) ? difference : left.startIndex - right.startIndex;
734
+ })[0];
735
+ }
736
+ function isChromePreviewSegment(segment) {
737
+ return isChromeSectionName(segment.root.name) || segment.root.role === "heading" && segment.root.name.length <= 2;
738
+ }
739
+ function chooseAdditionalSegments(segments, primary) {
740
+ if (!primary) {
741
+ return [];
742
+ }
743
+ const seenNames = /* @__PURE__ */ new Set([normalizeWhitespace(primary.root.name.toLowerCase())]);
744
+ const rankedCandidates = segments.filter((segment) => segment !== primary && segment.score >= 45).sort((left, right) => {
745
+ const leftDistance = Math.abs(left.startIndex - primary.startIndex);
746
+ const rightDistance = Math.abs(right.startIndex - primary.startIndex);
747
+ if (leftDistance !== rightDistance) {
748
+ return leftDistance - rightDistance;
749
+ }
750
+ if (right.score !== left.score) {
751
+ return right.score - left.score;
752
+ }
753
+ return left.startIndex - right.startIndex;
754
+ });
755
+ const chosen = [];
756
+ for (const segment of rankedCandidates) {
757
+ if (chosen.length >= SNAPSHOT_MAX_ADDITIONAL_SECTIONS) {
758
+ break;
759
+ }
760
+ if (isChromePreviewSegment(segment)) {
761
+ continue;
762
+ }
763
+ const nameKey = normalizeWhitespace(segment.root.name.toLowerCase());
764
+ if (nameKey.length > 0 && seenNames.has(nameKey)) {
765
+ continue;
766
+ }
767
+ chosen.push(segment);
768
+ if (nameKey.length > 0) {
769
+ seenNames.add(nameKey);
770
+ }
771
+ }
772
+ return chosen.sort((left, right) => left.startIndex - right.startIndex);
773
+ }
774
+ function getMeaningfulSegmentLines(segment) {
775
+ return segment.lines.filter((line) => {
776
+ if (isNoiseSnapshotLine(line)) {
777
+ return false;
778
+ }
779
+ if (line.role === "generic" && (line.ref ?? "") === "" && line.name.length === 0) {
780
+ return false;
781
+ }
782
+ if (line.role === "link" && line.name.length === 0) {
783
+ return false;
784
+ }
785
+ return true;
786
+ });
787
+ }
788
+ function formatPreviewLine(line, baseDepth) {
789
+ const leadingWhitespace = (line.raw.match(/^\s*/) ?? [""])[0].length;
790
+ const stripChars = Math.min(leadingWhitespace, Math.max(0, baseDepth) * 2);
791
+ return truncateText(line.raw.slice(stripChars), SNAPSHOT_LINE_MAX_CHARS);
792
+ }
793
+ function isRedundantPreviewLine(line, root) {
794
+ if (line === root) {
795
+ return false;
796
+ }
797
+ return root.role !== "heading" && line.depth - root.depth > 2 || root.name.length > 0 && line.name === root.name && (line.role === "heading" || line.role === "link");
798
+ }
799
+ function buildSegmentPreview(segment, maxLines) {
800
+ const meaningfulLines = getMeaningfulSegmentLines(segment);
801
+ if (meaningfulLines.length === 0) {
802
+ return { omittedCount: 0, refIds: [], lines: [] };
803
+ }
804
+ const previewLines = [];
805
+ const previewRefIds = /* @__PURE__ */ new Set();
806
+ const seenPreviewKeys = /* @__PURE__ */ new Set();
807
+ const rootDepth = segment.root.depth;
808
+ for (const line of meaningfulLines) {
809
+ if (previewLines.length >= maxLines) {
810
+ break;
811
+ }
812
+ if (isRedundantPreviewLine(line, segment.root)) {
813
+ continue;
814
+ }
815
+ const key = `${line.role}:${line.name}:${line.ref ?? ""}:${line.depth}`;
816
+ if (seenPreviewKeys.has(key)) {
817
+ continue;
818
+ }
819
+ seenPreviewKeys.add(key);
820
+ previewLines.push(line);
821
+ if (line.ref !== void 0 && line.ref.length > 0) {
822
+ previewRefIds.add(line.ref);
823
+ }
824
+ }
825
+ return {
826
+ omittedCount: Math.max(0, meaningfulLines.length - previewLines.length),
827
+ refIds: [...previewRefIds],
828
+ lines: previewLines.map((line) => formatPreviewLine(line, rootDepth))
829
+ };
830
+ }
831
+ function hasSnapshotSignal(line) {
832
+ return SNAPSHOT_SIGNAL_ROLES.has(line.role) || (line.ref ?? "").length > 0 || line.name.length > 0;
833
+ }
834
+ function buildFallbackSnapshotOutline(snapshotLines) {
835
+ const selected = /* @__PURE__ */ new Set();
836
+ for (let index = 0; index < snapshotLines.length && selected.size < 4; index += 1) {
837
+ if (!isNoiseSnapshotLine(snapshotLines[index])) {
838
+ selected.add(index);
839
+ }
840
+ }
841
+ for (let index = 0; index < snapshotLines.length && selected.size < SNAPSHOT_FALLBACK_PREVIEW_MAX_LINES; index += 1) {
842
+ const line = snapshotLines[index];
843
+ if (isNoiseSnapshotLine(line)) {
844
+ continue;
845
+ }
846
+ if (hasSnapshotSignal(line)) {
847
+ selected.add(index);
848
+ }
849
+ }
850
+ const chosenLines = [...selected].sort((left, right) => left - right).slice(0, SNAPSHOT_FALLBACK_PREVIEW_MAX_LINES).map((index) => snapshotLines[index]);
851
+ return {
852
+ omittedCount: Math.max(0, snapshotLines.length - chosenLines.length),
853
+ refIds: chosenLines.flatMap((line) => line.ref !== void 0 && line.ref.length > 0 ? [line.ref] : []),
854
+ lines: chosenLines.map((line) => truncateText(line.raw, SNAPSHOT_LINE_MAX_CHARS))
855
+ };
856
+ }
857
+ function buildRefLineOrderMap(snapshotLines) {
858
+ const map = /* @__PURE__ */ new Map();
859
+ for (const line of snapshotLines) {
860
+ if (line.ref === void 0 || line.ref.length === 0 || map.has(line.ref)) {
861
+ continue;
862
+ }
863
+ map.set(line.ref, line.index);
864
+ }
865
+ return map;
866
+ }
867
+ function canUseStructuredSnapshotPreview(snapshotLines, refEntries) {
868
+ if (snapshotLines.length === 0) {
869
+ return false;
870
+ }
871
+ const linesWithRecognizedRoles = snapshotLines.filter((line) => line.role !== "unknown").length;
872
+ const linesWithNames = snapshotLines.filter((line) => line.name.length > 0).length;
873
+ const parsedRefIds = new Set(snapshotLines.flatMap((line) => line.ref !== void 0 && line.ref.length > 0 ? [line.ref] : []));
874
+ return linesWithRecognizedRoles >= Math.min(snapshotLines.length, 3) || linesWithNames >= Math.min(snapshotLines.length, 3) || parsedRefIds.size >= Math.min(refEntries.length, 3);
875
+ }
876
+
877
+ // dist/extensions/agent-browser/lib/results/snapshot-compact.js
878
+ var PRIMARY_PREVIEW_LINES = 8;
879
+ var SECTION_PREVIEW_LINES = 2;
880
+ var KEY_REF_MAX_LINES = 8;
881
+ var OTHER_REF_MAX_LINES = 4;
882
+ var HIGH_VALUE_REF_MAX_LINES = 10;
883
+ function getSnapshotRoleCounts(entries) {
884
+ const counts = {};
885
+ for (const entry of entries) {
886
+ counts[entry.role] = (counts[entry.role] ?? 0) + 1;
887
+ }
888
+ return counts;
889
+ }
890
+ function formatRoleCounts(counts) {
891
+ const entries = Object.entries(counts);
892
+ if (entries.length === 0) {
893
+ return void 0;
894
+ }
895
+ const ordered = entries.sort((left, right) => right[1] !== left[1] ? right[1] - left[1] : getSnapshotRolePriority(left[0]) - getSnapshotRolePriority(right[0]));
896
+ const visible = ordered.slice(0, 4).map(([role, count]) => `${role} ${count}`);
897
+ const omitted = Math.max(0, ordered.length - visible.length);
898
+ if (omitted > 0) {
899
+ visible.push(`+${omitted} more`);
900
+ }
901
+ return visible.join(", ");
902
+ }
903
+ function rankRefEntries(entries, preview, focus, lines) {
904
+ const previewIds = new Set(preview);
905
+ const focusIds = new Set(focus);
906
+ const order = buildRefLineOrderMap(lines);
907
+ const refBucket = (id) => {
908
+ if (previewIds.has(id)) {
909
+ return 0;
910
+ }
911
+ return focusIds.has(id) ? 1 : 2;
912
+ };
913
+ return [...entries].sort((left, right) => {
914
+ const bucketDifference = refBucket(left.id) - refBucket(right.id);
915
+ if (bucketDifference !== 0) {
916
+ return bucketDifference;
917
+ }
918
+ const roleDifference = getSnapshotRolePriority(left.role) - getSnapshotRolePriority(right.role);
919
+ if (roleDifference !== 0) {
920
+ return roleDifference;
921
+ }
922
+ const nameDifference = Number(left.name.length === 0) - Number(right.name.length === 0);
923
+ if (nameDifference !== 0) {
924
+ return nameDifference;
925
+ }
926
+ const lineDifference = (order.get(left.id) ?? Number.MAX_SAFE_INTEGER) - (order.get(right.id) ?? Number.MAX_SAFE_INTEGER);
927
+ return lineDifference !== 0 ? lineDifference : compareRefIds(left.id, right.id);
928
+ });
929
+ }
930
+ function getFallbackPreview(lines, structured, primary) {
931
+ return !structured || !primary || primary.lines.length === 0 ? buildFallbackSnapshotOutline(lines) : void 0;
932
+ }
933
+ function buildPagePreview(lines, entries) {
934
+ const useStructured = canUseStructuredSnapshotPreview(lines, entries);
935
+ const segments = useStructured ? buildSnapshotSegments(lines) : [];
936
+ const primarySegment = useStructured ? choosePrimarySegment(segments) : void 0;
937
+ const additionalSegments = useStructured ? chooseAdditionalSegments(segments, primarySegment) : [];
938
+ const additionalSegmentCount = primarySegment ? Math.max(0, segments.length - 1) : 0;
939
+ const primaryPreview = primarySegment ? buildSegmentPreview(primarySegment, PRIMARY_PREVIEW_LINES) : void 0;
940
+ return {
941
+ useStructured,
942
+ primarySegment,
943
+ primaryPreview,
944
+ additionalSegments,
945
+ additionalPreviews: additionalSegments.map((segment) => ({ segment, preview: buildSegmentPreview(segment, SECTION_PREVIEW_LINES) })).filter(({ preview }) => preview.lines.length > 0),
946
+ fallbackPreview: getFallbackPreview(lines, useStructured, primaryPreview),
947
+ omittedAdditionalSectionCount: Math.max(0, additionalSegmentCount - additionalSegments.length)
948
+ };
949
+ }
950
+ function getPreviewRefIds(page) {
951
+ return [
952
+ .../* @__PURE__ */ new Set([
953
+ ...page.primaryPreview?.refIds ?? [],
954
+ ...page.additionalPreviews.flatMap(({ preview }) => preview.refIds),
955
+ ...page.fallbackPreview?.refIds ?? []
956
+ ])
957
+ ];
958
+ }
959
+ function getFocusRefIds(page) {
960
+ const primary = page.useStructured && page.primarySegment ? getMeaningfulSegmentLines(page.primarySegment) : [];
961
+ const additional = page.useStructured ? page.additionalSegments.flatMap(getMeaningfulSegmentLines) : [];
962
+ return [
963
+ ...new Set([...primary, ...additional].flatMap((line) => line.ref !== void 0 && line.ref.length > 0 ? [line.ref] : []).concat(page.fallbackPreview?.refIds ?? []))
964
+ ];
965
+ }
966
+ function selectCompactRefs(entries) {
967
+ const visible = entries.filter((entry) => !isNoiseName(entry.name) && !isChromeSectionName(entry.name) && !(entry.role === "heading" && entry.name.length <= 2));
968
+ const key = visible.slice(0, KEY_REF_MAX_LINES);
969
+ const keyIds = new Set(key.map((entry) => entry.id));
970
+ const other = visible.filter((entry) => !keyIds.has(entry.id)).slice(0, OTHER_REF_MAX_LINES);
971
+ const displayedIds = new Set([...key, ...other].map((entry) => entry.id));
972
+ const omitted = visible.filter((entry) => !displayedIds.has(entry.id));
973
+ const highValueCandidates = omitted.filter((entry) => isHighValueControlEntry(entry) && !isNoiseName(entry.name) && !isChromeSectionName(entry.name));
974
+ const highValue = selectHighValueControlEntries(highValueCandidates, HIGH_VALUE_REF_MAX_LINES);
975
+ return {
976
+ key,
977
+ other,
978
+ highValue,
979
+ omittedHighValueControls: Math.max(0, highValueCandidates.length - highValue.length),
980
+ omittedNonHighlightedRefs: Math.max(0, omitted.length - highValueCandidates.length)
981
+ };
982
+ }
983
+ function formatCompactRef(entry) {
984
+ const suffix = entry.name.length > 0 ? ` "${truncateText(entry.name, 96)}"` : "";
985
+ return `- ${entry.id} ${entry.role}${suffix}`;
986
+ }
987
+ function formatAdditionalPreviews(page) {
988
+ if (page.additionalPreviews.length === 0) {
989
+ return [];
990
+ }
991
+ const lines = ["", "Additional sections:"];
992
+ page.additionalPreviews.forEach(({ preview }, index) => {
993
+ if (index > 0) {
994
+ lines.push("");
995
+ }
996
+ lines.push(...preview.lines);
997
+ if (preview.omittedCount > 0) {
998
+ lines.push(`- ... (${preview.omittedCount} more lines in this section)`);
999
+ }
1000
+ });
1001
+ if (page.omittedAdditionalSectionCount > 0) {
1002
+ lines.push(`- ... (${page.omittedAdditionalSectionCount} more sections omitted)`);
1003
+ }
1004
+ return lines;
1005
+ }
1006
+ function formatFallbackPreview(preview, fullOutputPath) {
1007
+ const lines = [
1008
+ "",
1009
+ "Compact outline:",
1010
+ ...preview.lines.length > 0 ? preview.lines : ["(no interactive elements)"]
1011
+ ];
1012
+ if (preview.omittedCount > 0) {
1013
+ const source = fullOutputPath !== void 0 && fullOutputPath.length > 0 ? `full output path: ${fullOutputPath}` : "the full redacted snapshot was omitted";
1014
+ lines.push(`- ... (${preview.omittedCount} additional snapshot lines omitted; ${source})`);
1015
+ }
1016
+ return lines;
1017
+ }
1018
+ function formatPagePreview(page, fullOutputPath) {
1019
+ if (page.fallbackPreview) {
1020
+ return formatFallbackPreview(page.fallbackPreview, fullOutputPath);
1021
+ }
1022
+ const lines = [
1023
+ "",
1024
+ "Primary content:",
1025
+ ...page.primaryPreview?.lines ?? ["(no interactive elements)"]
1026
+ ];
1027
+ if ((page.primaryPreview?.omittedCount ?? 0) > 0) {
1028
+ lines.push(`- ... (${page.primaryPreview?.omittedCount ?? "undefined"} more lines in this section)`);
1029
+ }
1030
+ return [...lines, ...formatAdditionalPreviews(page)];
1031
+ }
1032
+ function formatRefSelection(selection) {
1033
+ const lines = [
1034
+ "",
1035
+ "Key refs:",
1036
+ ...selection.key.length > 0 ? selection.key.map(formatCompactRef) : ["(no refs)"]
1037
+ ];
1038
+ if (selection.other.length > 0) {
1039
+ lines.push("", "Other refs:", ...selection.other.map(formatCompactRef));
1040
+ }
1041
+ if (selection.omittedNonHighlightedRefs > 0) {
1042
+ lines.push(`- ... (${selection.omittedNonHighlightedRefs} additional refs omitted)`);
1043
+ }
1044
+ if (selection.highValue.length > 0) {
1045
+ lines.push("", "Omitted high-value controls:", ...selection.highValue.map(formatCompactRef));
1046
+ if (selection.omittedHighValueControls > 0) {
1047
+ lines.push(`- ... (${selection.omittedHighValueControls} additional high-value controls omitted)`);
1048
+ }
1049
+ }
1050
+ return lines;
1051
+ }
1052
+ function getPreviewSections(page) {
1053
+ const primary = page.primarySegment ? [
1054
+ {
1055
+ linesShown: page.primaryPreview?.lines.length ?? 0,
1056
+ omittedLines: page.primaryPreview?.omittedCount ?? 0,
1057
+ role: page.primarySegment.root.role,
1058
+ title: page.primarySegment.root.name
1059
+ }
1060
+ ] : [];
1061
+ return [
1062
+ ...primary,
1063
+ ...page.additionalPreviews.map(({ preview, segment }) => ({
1064
+ linesShown: preview.lines.length,
1065
+ omittedLines: preview.omittedCount,
1066
+ role: segment.root.role,
1067
+ title: segment.root.name
1068
+ }))
1069
+ ];
1070
+ }
1071
+ function buildCompactSnapshotView(data, fullOutputPath, spillErrorText) {
1072
+ const snapshot = getSnapshotText(data) ?? "(no interactive elements)";
1073
+ const snapshotLines = parseSnapshotLines(snapshot);
1074
+ const refEntries = enrichSnapshotRefEntries(getSnapshotRefEntries(data), snapshotLines);
1075
+ const roleCounts = getSnapshotRoleCounts(refEntries);
1076
+ const roleCountsText = formatRoleCounts(roleCounts);
1077
+ const page = buildPagePreview(snapshotLines, refEntries);
1078
+ const previewRefIds = getPreviewRefIds(page);
1079
+ const ranked = rankRefEntries(refEntries, previewRefIds, getFocusRefIds(page), page.useStructured ? snapshotLines : []);
1080
+ const refs = selectCompactRefs(ranked);
1081
+ const origin = getSnapshotOrigin(data);
1082
+ const lines = [
1083
+ `Origin: ${origin}`,
1084
+ `Refs: ${refEntries.length}`,
1085
+ ...roleCountsText !== void 0 ? [`Top roles: ${roleCountsText}`] : [],
1086
+ "",
1087
+ "Compact snapshot view.",
1088
+ "Viewport note: compact snapshots are DOM/signal-prioritized, not guaranteed to start with the currently scrolled viewport; use the full redacted snapshot, a screenshot, or listed high-value refs when viewport context matters.",
1089
+ ...formatPagePreview(page, fullOutputPath),
1090
+ ...formatRefSelection(refs),
1091
+ "",
1092
+ fullOutputPath !== void 0 && fullOutputPath.length > 0 ? `Full redacted snapshot path: ${fullOutputPath}` : `Full redacted snapshot unavailable: ${spillErrorText ?? "temp spill file could not be created."}`
1093
+ ];
1094
+ return {
1095
+ content: [{ type: "text", text: lines.join("\n") }],
1096
+ data: {
1097
+ compacted: true,
1098
+ fullOutputPath,
1099
+ origin,
1100
+ previewMode: page.fallbackPreview ? "outline" : "structured",
1101
+ viewportOrdering: "dom-signal-prioritized",
1102
+ spillError: spillErrorText,
1103
+ previewRefIds,
1104
+ highValueControlRefIds: refs.highValue.map((entry) => entry.id),
1105
+ additionalSectionsOmitted: page.omittedAdditionalSectionCount,
1106
+ previewSections: getPreviewSections(page),
1107
+ refCount: refEntries.length,
1108
+ roleCounts,
1109
+ snapshotLineCount: countLines(snapshot),
1110
+ structuredPreviewUsed: !page.fallbackPreview
1111
+ }
1112
+ };
1113
+ }
1114
+
1115
+ // dist/extensions/agent-browser/lib/command-capabilities.js
1116
+ var ADDITIONAL_COMMAND_TOKENS = [
1117
+ "a11y",
1118
+ "auth",
1119
+ "chat",
1120
+ "clipboard",
1121
+ "confirm",
1122
+ "connect",
1123
+ "dashboard",
1124
+ "deny",
1125
+ "device",
1126
+ "dialog",
1127
+ "diff",
1128
+ "doctor",
1129
+ "errors",
1130
+ "eval",
1131
+ "find",
1132
+ "frame",
1133
+ "get",
1134
+ "highlight",
1135
+ "inspect",
1136
+ "install",
1137
+ "is",
1138
+ "mcp",
1139
+ "plugin",
1140
+ "plugins",
1141
+ "profiles",
1142
+ "profiler",
1143
+ "react",
1144
+ "record",
1145
+ "removeinitscript",
1146
+ "session",
1147
+ "set",
1148
+ "skills",
1149
+ "snapshot",
1150
+ "state",
1151
+ "stream",
1152
+ "trace",
1153
+ "upgrade",
1154
+ "vitals",
1155
+ "wait",
1156
+ "web-vitals",
1157
+ "webmcp",
1158
+ "window"
1159
+ ];
1160
+ var COMMAND_CAPABILITIES = [
1161
+ {
1162
+ command: "back",
1163
+ eligibleForElectronHealthProbe: true,
1164
+ eligibleForPageChangeSummary: true,
1165
+ invalidatesBatchRefs: true,
1166
+ navigationObservable: true,
1167
+ triggersPostMutationSnapshot: true
1168
+ },
1169
+ {
1170
+ command: "batch",
1171
+ excludedFromPostCommandCorrection: true
1172
+ },
1173
+ {
1174
+ command: "check",
1175
+ eligibleForElectronHealthProbe: true,
1176
+ eligibleForPageChangeSummary: true,
1177
+ guardsPageRefs: true,
1178
+ invalidatesBatchRefs: true,
1179
+ triggersPostMutationSnapshot: true
1180
+ },
1181
+ {
1182
+ command: "click",
1183
+ eligibleForElectronHealthProbe: true,
1184
+ eligibleForPageChangeSummary: true,
1185
+ guardsPageRefs: true,
1186
+ invalidatesBatchRefs: true,
1187
+ navigationObservable: true,
1188
+ triggersPostMutationSnapshot: true
1189
+ },
1190
+ {
1191
+ aliases: ["quit", "exit"],
1192
+ closesSession: true,
1193
+ command: "close",
1194
+ excludedFromPinning: true,
1195
+ excludedFromPostCommandCorrection: true
1196
+ },
1197
+ {
1198
+ command: "console",
1199
+ readOnlyDiagnosticSessionTarget: true
1200
+ },
1201
+ {
1202
+ command: "cookies",
1203
+ readOnlyDiagnosticSessionTarget: true
1204
+ },
1205
+ {
1206
+ command: "dblclick",
1207
+ eligibleForElectronHealthProbe: true,
1208
+ eligibleForPageChangeSummary: true,
1209
+ guardsPageRefs: true,
1210
+ invalidatesBatchRefs: true,
1211
+ navigationObservable: true,
1212
+ triggersPostMutationSnapshot: true
1213
+ },
1214
+ {
1215
+ command: "dialog",
1216
+ eligibleForPageChangeSummary: true,
1217
+ invalidatesBatchRefs: true,
1218
+ triggersPostMutationSnapshot: true
1219
+ },
1220
+ {
1221
+ command: "diff",
1222
+ guardsPageRefs: true
1223
+ },
1224
+ {
1225
+ command: "download",
1226
+ eligibleForPageChangeSummary: true,
1227
+ guardsPageRefs: true
1228
+ },
1229
+ {
1230
+ command: "drag",
1231
+ guardsPageRefs: true,
1232
+ invalidatesBatchRefs: true
1233
+ },
1234
+ {
1235
+ command: "errors",
1236
+ readOnlyDiagnosticSessionTarget: true
1237
+ },
1238
+ {
1239
+ command: "eval",
1240
+ invalidatesBatchRefs: true,
1241
+ navigationObservable: true,
1242
+ triggersPostMutationSnapshot: true
1243
+ },
1244
+ {
1245
+ command: "fill",
1246
+ eligibleForElectronHealthProbe: true,
1247
+ eligibleForPageChangeSummary: true,
1248
+ guardsPageRefs: true,
1249
+ triggersPostMutationSnapshot: true
1250
+ },
1251
+ {
1252
+ command: "find",
1253
+ eligibleForElectronHealthProbe: true
1254
+ },
1255
+ {
1256
+ command: "frame",
1257
+ guardsPageRefs: true
1258
+ },
1259
+ {
1260
+ command: "focus",
1261
+ guardsPageRefs: true
1262
+ },
1263
+ {
1264
+ command: "forward",
1265
+ eligibleForElectronHealthProbe: true,
1266
+ eligibleForPageChangeSummary: true,
1267
+ invalidatesBatchRefs: true,
1268
+ navigationObservable: true,
1269
+ triggersPostMutationSnapshot: true
1270
+ },
1271
+ {
1272
+ command: "get",
1273
+ guardsPageRefs: true
1274
+ },
1275
+ {
1276
+ command: "highlight",
1277
+ guardsPageRefs: true
1278
+ },
1279
+ {
1280
+ command: "hover",
1281
+ eligibleForPageChangeSummary: true,
1282
+ guardsPageRefs: true,
1283
+ invalidatesBatchRefs: true,
1284
+ triggersPostMutationSnapshot: true
1285
+ },
1286
+ {
1287
+ command: "is",
1288
+ guardsPageRefs: true
1289
+ },
1290
+ {
1291
+ command: "keydown",
1292
+ eligibleForElectronHealthProbe: true,
1293
+ eligibleForPageChangeSummary: true,
1294
+ invalidatesBatchRefs: true,
1295
+ triggersPostMutationSnapshot: true
1296
+ },
1297
+ {
1298
+ command: "keyboard",
1299
+ eligibleForElectronHealthProbe: true,
1300
+ eligibleForPageChangeSummary: true,
1301
+ invalidatesBatchRefs: true,
1302
+ triggersPostMutationSnapshot: true
1303
+ },
1304
+ {
1305
+ command: "keyup",
1306
+ eligibleForElectronHealthProbe: true,
1307
+ eligibleForPageChangeSummary: true,
1308
+ invalidatesBatchRefs: true,
1309
+ triggersPostMutationSnapshot: true
1310
+ },
1311
+ {
1312
+ command: "mouse",
1313
+ eligibleForElectronHealthProbe: true,
1314
+ invalidatesBatchRefs: true
1315
+ },
1316
+ {
1317
+ command: "network",
1318
+ readOnlyDiagnosticSessionTarget: true
1319
+ },
1320
+ {
1321
+ aliases: ["goto", "navigate"],
1322
+ command: "open",
1323
+ eligibleForPageChangeSummary: true,
1324
+ excludedFromPinning: true,
1325
+ invalidatesBatchRefs: true,
1326
+ openNavigation: true
1327
+ },
1328
+ {
1329
+ command: "pdf",
1330
+ eligibleForPageChangeSummary: true
1331
+ },
1332
+ {
1333
+ aliases: ["key"],
1334
+ command: "press",
1335
+ eligibleForElectronHealthProbe: true,
1336
+ eligibleForPageChangeSummary: true,
1337
+ invalidatesBatchRefs: true,
1338
+ triggersPostMutationSnapshot: true
1339
+ },
1340
+ {
1341
+ command: "pushstate",
1342
+ eligibleForPageChangeSummary: true,
1343
+ invalidatesBatchRefs: true,
1344
+ triggersPostMutationSnapshot: true
1345
+ },
1346
+ {
1347
+ command: "reload",
1348
+ eligibleForElectronHealthProbe: true,
1349
+ eligibleForPageChangeSummary: true,
1350
+ invalidatesBatchRefs: true,
1351
+ navigationObservable: true,
1352
+ triggersPostMutationSnapshot: true
1353
+ },
1354
+ {
1355
+ command: "read",
1356
+ readOnlyDiagnosticSessionTarget: true
1357
+ },
1358
+ {
1359
+ command: "screenshot",
1360
+ eligibleForPageChangeSummary: true,
1361
+ guardsPageRefs: true
1362
+ },
1363
+ {
1364
+ command: "scroll",
1365
+ eligibleForPageChangeSummary: true,
1366
+ guardsPageRefs: true,
1367
+ invalidatesBatchRefs: true,
1368
+ triggersPostMutationSnapshot: true
1369
+ },
1370
+ {
1371
+ aliases: ["scrollinto"],
1372
+ command: "scrollintoview",
1373
+ eligibleForPageChangeSummary: true,
1374
+ guardsPageRefs: true,
1375
+ invalidatesBatchRefs: true,
1376
+ triggersPostMutationSnapshot: true
1377
+ },
1378
+ {
1379
+ command: "select",
1380
+ eligibleForElectronHealthProbe: true,
1381
+ eligibleForPageChangeSummary: true,
1382
+ guardsPageRefs: true,
1383
+ invalidatesBatchRefs: true,
1384
+ triggersPostMutationSnapshot: true
1385
+ },
1386
+ {
1387
+ command: "session",
1388
+ excludedFromPinning: true,
1389
+ excludedFromPostCommandCorrection: true
1390
+ },
1391
+ {
1392
+ command: "storage",
1393
+ readOnlyDiagnosticSessionTarget: true
1394
+ },
1395
+ {
1396
+ command: "swipe",
1397
+ eligibleForPageChangeSummary: true,
1398
+ invalidatesBatchRefs: true,
1399
+ triggersPostMutationSnapshot: true
1400
+ },
1401
+ {
1402
+ command: "tab",
1403
+ excludedFromPinning: true,
1404
+ excludedFromPostCommandCorrection: true
1405
+ },
1406
+ {
1407
+ command: "tap",
1408
+ eligibleForElectronHealthProbe: true,
1409
+ eligibleForPageChangeSummary: true,
1410
+ guardsPageRefs: true,
1411
+ invalidatesBatchRefs: true,
1412
+ triggersPostMutationSnapshot: true
1413
+ },
1414
+ {
1415
+ command: "type",
1416
+ eligibleForElectronHealthProbe: true,
1417
+ eligibleForPageChangeSummary: true,
1418
+ guardsPageRefs: true,
1419
+ invalidatesBatchRefs: true,
1420
+ triggersPostMutationSnapshot: true
1421
+ },
1422
+ {
1423
+ command: "uncheck",
1424
+ eligibleForElectronHealthProbe: true,
1425
+ eligibleForPageChangeSummary: true,
1426
+ guardsPageRefs: true,
1427
+ invalidatesBatchRefs: true,
1428
+ triggersPostMutationSnapshot: true
1429
+ },
1430
+ {
1431
+ command: "upload",
1432
+ guardsPageRefs: true,
1433
+ invalidatesBatchRefs: true
1434
+ }
1435
+ ];
1436
+ var COMMAND_CAPABILITY_BY_NAME = /* @__PURE__ */ new Map();
1437
+ for (const entry of COMMAND_CAPABILITIES) {
1438
+ COMMAND_CAPABILITY_BY_NAME.set(entry.command, entry);
1439
+ for (const alias of entry.aliases ?? []) {
1440
+ COMMAND_CAPABILITY_BY_NAME.set(alias, entry);
1441
+ }
1442
+ }
1443
+ var KNOWN_COMMAND_TOKENS = /* @__PURE__ */ new Set([
1444
+ ...COMMAND_CAPABILITY_BY_NAME.keys(),
1445
+ ...ADDITIONAL_COMMAND_TOKENS
1446
+ ]);
1447
+
1448
+ // dist/extensions/agent-browser/lib/session-identity.js
1449
+ var SESSION_COMPONENT_ALPHANUMERIC = /^[\p{Alphabetic}\p{Number}]$/u;
1450
+ function canonicalizeAgentBrowserNamespace(value) {
1451
+ if (value === void 0) {
1452
+ return void 0;
1453
+ }
1454
+ let normalized = "";
1455
+ let lastWasSeparator = false;
1456
+ for (const character of value) {
1457
+ if (SESSION_COMPONENT_ALPHANUMERIC.test(character)) {
1458
+ normalized += character.toLowerCase();
1459
+ lastWasSeparator = false;
1460
+ continue;
1461
+ }
1462
+ if (normalized.length > 0 && !lastWasSeparator) {
1463
+ normalized += character === "_" ? "_" : "-";
1464
+ lastWasSeparator = true;
1465
+ }
1466
+ }
1467
+ const result = normalized.replace(/[-_]+$/u, "");
1468
+ return result.length > 0 ? result : void 0;
1469
+ }
1470
+ function foldAgentBrowserFilesystemIdentity(value, platform) {
1471
+ if (platform !== "darwin" && platform !== "win32") {
1472
+ return value;
1473
+ }
1474
+ return value.normalize("NFC").toLowerCase().toUpperCase().toLowerCase().normalize("NFC");
1475
+ }
1476
+ function getAgentBrowserSessionIdentityKey(sessionName, namespace, platform = process.platform) {
1477
+ const canonicalNamespace = canonicalizeAgentBrowserNamespace(namespace);
1478
+ const canonicalSessionName = foldAgentBrowserFilesystemIdentity(sessionName, platform);
1479
+ return canonicalNamespace !== void 0 ? `${foldAgentBrowserFilesystemIdentity(canonicalNamespace, platform)}\0${canonicalSessionName}` : canonicalSessionName;
1480
+ }
1481
+
1482
+ // dist/extensions/agent-browser/lib/argv-grammar.js
1483
+ var GLOBAL_VALUE_FLAGS = [
1484
+ "--session",
1485
+ "--namespace",
1486
+ "--cdp",
1487
+ "--config",
1488
+ "--profile",
1489
+ "--session-name",
1490
+ "--restore-save",
1491
+ "--restore-check-url",
1492
+ "--restore-check-text",
1493
+ "--restore-check-fn",
1494
+ "--proxy",
1495
+ "--proxy-bypass",
1496
+ "--ca-cert",
1497
+ "--headers",
1498
+ "--executable-path",
1499
+ "--extension",
1500
+ "--init-script",
1501
+ "--enable",
1502
+ "--provider",
1503
+ "-p",
1504
+ "--engine",
1505
+ "--state",
1506
+ "--download-path",
1507
+ "--screenshot-dir",
1508
+ "--screenshot-format",
1509
+ "--screenshot-quality",
1510
+ "--color-scheme",
1511
+ "--device",
1512
+ "--args",
1513
+ "--user-agent",
1514
+ "--allowed-domains",
1515
+ "--action-policy",
1516
+ "--confirm-actions",
1517
+ "--max-output",
1518
+ "--model",
1519
+ "--idle-timeout",
1520
+ "--input-mode"
1521
+ ];
1522
+ var COMMAND_VALUE_FLAGS = [
1523
+ "--allowed-origins",
1524
+ "--baseline",
1525
+ "--body",
1526
+ "--categories",
1527
+ "--content",
1528
+ "--curl",
1529
+ "--depth",
1530
+ "-d",
1531
+ "--domain",
1532
+ "--expires",
1533
+ "--filter",
1534
+ "--frame",
1535
+ "--fn",
1536
+ "--label",
1537
+ "--load",
1538
+ "--method",
1539
+ "--name",
1540
+ "--older-than",
1541
+ "--output",
1542
+ "--prefix",
1543
+ "--path",
1544
+ "--port",
1545
+ "--params",
1546
+ "--resource-type",
1547
+ "--resource-types",
1548
+ "--sameSite",
1549
+ "--scope",
1550
+ "--selector",
1551
+ "-s",
1552
+ "--status",
1553
+ "--tags",
1554
+ "--text",
1555
+ "--threshold",
1556
+ "--timeout",
1557
+ "--type",
1558
+ "--url",
1559
+ "--username",
1560
+ "--password",
1561
+ "--wait-until"
1562
+ ];
1563
+ var VALUE_FLAGS = /* @__PURE__ */ new Set([
1564
+ ...GLOBAL_VALUE_FLAGS,
1565
+ ...COMMAND_VALUE_FLAGS
1566
+ ]);
1567
+ var PREVALIDATED_VALUE_FLAGS = new Set(GLOBAL_VALUE_FLAGS);
1568
+
1569
+ // dist/extensions/agent-browser/lib/redaction-fields.js
1570
+ var SENSITIVE_FIELD_NAME_PATTERN = /^(?:[A-Za-z0-9_-]*(?:api[_-]?key|access[_-]?key|private[_-]?key|secret(?:[_-]?(?:key|access[_-]?key))?|token|password|passwd|credentials?|database[_-]?url|db[_-]?url|connection[_-]?string|mongo(?:db)?[_-]?uri|redis[_-]?url)|[A-Za-z0-9]*(?:apiKey|ApiKey|apikey|privateKey|PrivateKey|databaseUrl|DatabaseUrl|dbUrl|DbUrl|connectionString|ConnectionString|mongoUri|MongoUri|mongodbUri|MongodbUri|mongoDbUri|MongoDbUri|redisUrl|RedisUrl|Token|Secret|Password|Credential|Credentials)|auth(?:orization)?|bearer|client(?:_|-)?secret|cookie|id(?:_|-)?token|pass(?:word)?|proxy(?:_|-)?authorization|refresh(?:_|-)?token|sentry(?:_|-)?key|session(?:_|-)?id|set(?:_|-)?cookie|sig(?:nature)?|write(?:_|-)?key|x(?:_|-)?api(?:_|-)?key)$/i;
1571
+ var ENV_SECRET_ASSIGNMENT_PATTERN = /\b((?:export\s+)?([A-Za-z_][A-Za-z0-9_-]*)(\s*[:=]\s*))(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\s,;]+)/g;
1572
+ function isSensitiveFieldName(key) {
1573
+ SENSITIVE_FIELD_NAME_PATTERN.lastIndex = 0;
1574
+ return SENSITIVE_FIELD_NAME_PATTERN.test(key);
1575
+ }
1576
+ function isEnvSecretAssignmentKey(key) {
1577
+ if (!isSensitiveFieldName(key)) {
1578
+ return false;
1579
+ }
1580
+ if (key === "password" || key.includes("_") || key.includes("-") || key === key.toUpperCase()) {
1581
+ return true;
1582
+ }
1583
+ return /(?:apiKey|ApiKey|privateKey|PrivateKey|databaseUrl|DatabaseUrl|dbUrl|DbUrl|connectionString|ConnectionString|mongoUri|MongoUri|mongodbUri|MongodbUri|mongoDbUri|MongoDbUri|redisUrl|RedisUrl|Token|Secret|Password|Credential|Credentials)$/.test(key);
1584
+ }
1585
+ function isLineBoundary(text, index) {
1586
+ return index < 0 || index >= text.length || text[index] === "\n" || text[index] === "\r";
1587
+ }
1588
+ function redactPasswordAssignment(text, match, prefix, offset) {
1589
+ const end = offset + match.length;
1590
+ if (!isLineBoundary(text, offset - 1) || !isLineBoundary(text, end) || /^(?:\[REDACTED\]|%5Bredacted%5D)/i.test(match.slice(prefix.length))) {
1591
+ return match;
1592
+ }
1593
+ const value = match.slice(prefix.length);
1594
+ const boundary = value[0] === '"' || value[0] === "'" ? -1 : value.search(/[&#](?=[A-Za-z_][A-Za-z0-9_-]*\s*=)/);
1595
+ return `${prefix}[REDACTED]${boundary < 0 ? "" : value.slice(boundary)}`;
1596
+ }
1597
+ function redactEnvSecretAssignments(text) {
1598
+ return text.replace(
1599
+ ENV_SECRET_ASSIGNMENT_PATTERN,
1600
+ // String.replace supplies match, three captures, then the source offset.
1601
+ (match, prefix, key, _separator, offset) => {
1602
+ if (!isEnvSecretAssignmentKey(key)) {
1603
+ return match;
1604
+ }
1605
+ return key === "password" ? redactPasswordAssignment(text, match, prefix, offset) : `${prefix}[REDACTED]`;
1606
+ }
1607
+ );
1608
+ }
1609
+ function credentialTrailingPunctuation(credential) {
1610
+ return credential.match(/[,.:;!?]+$/)?.[0] ?? "";
1611
+ }
1612
+ function formatRedactedCredential(label, credential, trailing = "") {
1613
+ return `${label} [REDACTED]${credentialTrailingPunctuation(credential)}${trailing}`;
1614
+ }
1615
+ function redactBearerCredentials(text) {
1616
+ return text.replace(
1617
+ /((?:\b([A-Za-z][A-Za-z0-9_-]*)\s*[:=]\s*|(?:^|\s)(?:-H\s*|--header(?:\s+|=)))["']?Bearer)\s+([^\s"',)[\]]+)([),.]?)/gi,
1618
+ // String.replace supplies the match followed by this expression's four captures.
1619
+ (match, label, field, credential, trailing) => {
1620
+ if (field !== void 0 && field.length > 0 && !isSensitiveFieldName(field)) {
1621
+ return match;
1622
+ }
1623
+ return formatRedactedCredential(label, credential, trailing);
1624
+ }
1625
+ ).replace(/\b(Bearer)\s+([^\s\\"',)[\]]+)([),.]?)/gi, (match, label, credential, trailing) => {
1626
+ const token = credential.slice(0, credential.length - credentialTrailingPunctuation(credential).length);
1627
+ if (!/^[A-Za-z0-9._~+/-]+=*$/.test(token) || !/[0-9._~+/=-]/.test(token)) {
1628
+ return match;
1629
+ }
1630
+ return formatRedactedCredential(label, credential, trailing);
1631
+ });
1632
+ }
1633
+ function redactStandaloneBasicCredential(text) {
1634
+ return text.replace(/\b(Basic)\s+([A-Za-z0-9+/=]{12,})/gi, (match, label, credential) => {
1635
+ if (!/[0-9+/=]/.test(credential)) {
1636
+ return match;
1637
+ }
1638
+ return `${label} [REDACTED]`;
1639
+ });
1640
+ }
1641
+
1642
+ // dist/extensions/agent-browser/lib/redaction-json.js
1643
+ function nextQuotePosition(options) {
1644
+ if (options.char === '"') {
1645
+ return options.index;
1646
+ }
1647
+ return options.char === "\\" ? options.quoteAfterNext : options.quoteAtNext;
1648
+ }
1649
+ function buildJsonBoundaries(text) {
1650
+ const boundaries = new Int32Array(text.length + 1).fill(-1);
1651
+ let quoteAtNext = -1;
1652
+ let quoteAfterNext = -1;
1653
+ for (let index = text.length - 1; index >= 0; index -= 1) {
1654
+ const char = text[index];
1655
+ switch (char) {
1656
+ case "}":
1657
+ case "]":
1658
+ boundaries[index] = index;
1659
+ break;
1660
+ case '"':
1661
+ boundaries[index] = quoteAtNext < 0 ? -1 : boundaries[quoteAtNext + 1];
1662
+ break;
1663
+ case "{":
1664
+ case "[": {
1665
+ const end = boundaries[index + 1];
1666
+ boundaries[index] = end >= 0 && text[end] === (char === "{" ? "}" : "]") ? boundaries[end + 1] : -1;
1667
+ break;
1668
+ }
1669
+ default:
1670
+ boundaries[index] = boundaries[index + 1];
1671
+ }
1672
+ const quote = nextQuotePosition({ char, index, quoteAtNext, quoteAfterNext });
1673
+ quoteAfterNext = quoteAtNext;
1674
+ quoteAtNext = quote;
1675
+ }
1676
+ return boundaries;
1677
+ }
1678
+ function createBalancedJsonEndFinder(text) {
1679
+ let boundaries;
1680
+ return (startIndex) => {
1681
+ const opener = text[startIndex];
1682
+ if (opener !== "{" && opener !== "[") {
1683
+ return;
1684
+ }
1685
+ boundaries ??= buildJsonBoundaries(text);
1686
+ const end = boundaries[startIndex + 1];
1687
+ return end >= 0 && text[end] === (opener === "{" ? "}" : "]") ? end : void 0;
1688
+ };
1689
+ }
1690
+ function parseJsonString(token) {
1691
+ const value = JSON.parse(token);
1692
+ if (typeof value !== "string") {
1693
+ throw new Error("Expected a JSON string token");
1694
+ }
1695
+ return value;
1696
+ }
1697
+ function isSerializedJson(text) {
1698
+ if (text === "[REDACTED]" || !/^\s*[[{"\d\-tfn]/.test(text)) {
1699
+ return false;
1700
+ }
1701
+ try {
1702
+ JSON.parse(text);
1703
+ return true;
1704
+ } catch {
1705
+ return false;
1706
+ }
1707
+ }
1708
+ function findJsonValueEnd(text, start, findEnd) {
1709
+ const balancedEnd = findEnd(start);
1710
+ if (balancedEnd !== void 0) {
1711
+ return balancedEnd + 1;
1712
+ }
1713
+ if (text[start] === '"') {
1714
+ const strings = /"(?:\\.|[^"\\])*"/g;
1715
+ strings.lastIndex = start;
1716
+ const fieldValue = strings.exec(text);
1717
+ if (fieldValue === null) {
1718
+ throw new Error("Expected a validated JSON string field value");
1719
+ }
1720
+ return parseJsonString(fieldValue[0]) === "[REDACTED]" ? void 0 : strings.lastIndex;
1721
+ }
1722
+ let end = start;
1723
+ while (end < text.length && !/[\s,\]}]/.test(text[end])) {
1724
+ end += 1;
1725
+ }
1726
+ return end;
1727
+ }
1728
+ function redactSerializedJson(text, redact) {
1729
+ if (!isSerializedJson(text)) {
1730
+ return;
1731
+ }
1732
+ let output = "";
1733
+ let cursor = 0;
1734
+ const findEnd = createBalancedJsonEndFinder(text);
1735
+ const strings = /"(?:\\.|[^"\\])*"/g;
1736
+ let match;
1737
+ while ((match = strings.exec(text)) !== null) {
1738
+ const end = strings.lastIndex;
1739
+ const value = parseJsonString(match[0]);
1740
+ const redacted = redact(value);
1741
+ if (redacted !== value) {
1742
+ output += text.slice(cursor, match.index) + JSON.stringify(redacted);
1743
+ cursor = end;
1744
+ }
1745
+ const separator = /^\s*:\s*/.exec(text.slice(end));
1746
+ if (separator === null || !isSensitiveFieldName(value)) {
1747
+ continue;
1748
+ }
1749
+ const valueStart = end + separator[0].length;
1750
+ const valueEnd = findJsonValueEnd(text, valueStart, findEnd);
1751
+ if (valueEnd === void 0) {
1752
+ strings.lastIndex = valueStart;
1753
+ strings.exec(text);
1754
+ continue;
1755
+ }
1756
+ output += text.slice(cursor, valueStart) + '"[REDACTED]"';
1757
+ cursor = valueEnd;
1758
+ strings.lastIndex = valueEnd;
1759
+ }
1760
+ return output + text.slice(cursor);
1761
+ }
1762
+ function redactEmbeddedStructuredText(text, redact) {
1763
+ let output = "";
1764
+ let cursor = 0;
1765
+ const findEnd = createBalancedJsonEndFinder(text);
1766
+ const openers = /[[{]/g;
1767
+ let match;
1768
+ while ((match = openers.exec(text)) !== null) {
1769
+ const endIndex = findEnd(match.index);
1770
+ if (endIndex === void 0) {
1771
+ continue;
1772
+ }
1773
+ const candidate = text.slice(match.index, endIndex + 1);
1774
+ const redacted = redactSerializedJson(candidate, redact) ?? candidate;
1775
+ if (redacted !== candidate) {
1776
+ output += text.slice(cursor, match.index) + redacted;
1777
+ cursor = endIndex + 1;
1778
+ }
1779
+ openers.lastIndex = endIndex + 1;
1780
+ }
1781
+ return cursor === 0 ? text : output + text.slice(cursor);
1782
+ }
1783
+
1784
+ // dist/extensions/agent-browser/lib/redaction-url.js
1785
+ var SENSITIVE_QUERY_PARAM_PATTERN = /^(?:access(?:_|-)?token|api(?:_|-)?key|auth|authorization|authorization(?:_|-)?session(?:_|-)?id|bearer|client(?:_|-)?secret|code|cookie|id(?:_|-)?token|key|pass(?:word)?|refresh(?:_|-)?token|relay(?:_|-)?state|saml(?:_|-)?request|saml(?:_|-)?response|secret|sentry(?:_|-)?key|session(?:_|-)?id|sig(?:nature)?|token|write(?:_|-)?key)$/i;
1786
+ var AUTH_STATE_QUERY_PARAM_PATTERN = /^(?:nonce|state)$/i;
1787
+ var AUTH_URL_CONTEXT_PATTERN = /(?:^|[./_-])(?:auth|authorize|callback|login|oauth2?|oidc|saml|sso)(?:[./?#_-]|$)/i;
1788
+ function shouldRedactQueryParam(name) {
1789
+ return SENSITIVE_QUERY_PARAM_PATTERN.test(name) || isSensitiveFieldName(name);
1790
+ }
1791
+ function isSensitiveParameter(name, authContext) {
1792
+ return shouldRedactQueryParam(name) || authContext && AUTH_STATE_QUERY_PARAM_PATTERN.test(name);
1793
+ }
1794
+ function redactParameters(params, authContext) {
1795
+ let mutated = false;
1796
+ for (const [name] of params) {
1797
+ if (isSensitiveParameter(name, authContext)) {
1798
+ params.set(name, "[REDACTED]");
1799
+ mutated = true;
1800
+ }
1801
+ }
1802
+ return mutated;
1803
+ }
1804
+ function getHashParameters(hash) {
1805
+ const text = hash.startsWith("#") ? hash.slice(1) : hash;
1806
+ return text.includes("=") ? new URLSearchParams(text) : void 0;
1807
+ }
1808
+ function redactUrlToken(token) {
1809
+ let parsed;
1810
+ try {
1811
+ parsed = new URL(token);
1812
+ } catch {
1813
+ return token;
1814
+ }
1815
+ const originalHref = parsed.href;
1816
+ if (parsed.username.length > 0) {
1817
+ parsed.username = "[REDACTED]";
1818
+ }
1819
+ if (parsed.password.length > 0) {
1820
+ parsed.password = "[REDACTED]";
1821
+ }
1822
+ const hashParams = getHashParameters(parsed.hash);
1823
+ const authContext = AUTH_URL_CONTEXT_PATTERN.test(`${parsed.hostname}${parsed.pathname}`) || [...parsed.searchParams.keys(), ...hashParams?.keys() ?? []].some(shouldRedactQueryParam);
1824
+ redactParameters(parsed.searchParams, authContext);
1825
+ if (hashParams && redactParameters(hashParams, authContext)) {
1826
+ parsed.hash = `#${hashParams.toString()}`;
1827
+ }
1828
+ return parsed.href === originalHref ? token : parsed.href;
1829
+ }
1830
+ function decodeParameterName(raw) {
1831
+ try {
1832
+ return decodeURIComponent(raw.replace(/\+/g, " "));
1833
+ } catch {
1834
+ return raw;
1835
+ }
1836
+ }
1837
+ function redactLooseUrlParameterText(text) {
1838
+ return text.replace(/(?<![^\s"'`<>\])}])[^\s"'`<>\])}]*[?#&][^\s"'`<>\])}]*/g, (token) => {
1839
+ const queryNames = [...token.matchAll(/[?#&]([^=&#\s"'`<>\])}]+)=/g)].map((match) => decodeParameterName(match[1]));
1840
+ const authContext = AUTH_URL_CONTEXT_PATTERN.test(token) || queryNames.some(shouldRedactQueryParam);
1841
+ return token.replace(/([?#&])([^=&#\s"'`<>\])}]+)=([^&#\s"'`<>\])}]*)/g, (match, separator, rawName, rawValue) => {
1842
+ if (rawValue === "[REDACTED" || rawValue === "[REDACTED]" || /%5Bredacted%5D/i.test(rawValue)) {
1843
+ return match;
1844
+ }
1845
+ if (!isSensitiveParameter(decodeParameterName(rawName), authContext)) {
1846
+ return match;
1847
+ }
1848
+ return `${separator}${rawName}=[REDACTED]`;
1849
+ });
1850
+ });
1851
+ }
1852
+ function redactLooseUrlUserinfo(text) {
1853
+ return text.replace(/\b([A-Za-z][A-Za-z0-9+.-]*:\/\/)([^\s"'`/@]+)@([^\s"'`]+)/g, (match, prefix, userinfo, suffix) => {
1854
+ if (/%5Bredacted%5D/i.test(userinfo)) {
1855
+ return match;
1856
+ }
1857
+ if (userinfo.includes("[REDACTED]")) {
1858
+ return redactLooseUrlParameterText(match);
1859
+ }
1860
+ return redactLooseUrlParameterText(`${prefix}${userinfo.includes(":") ? "[REDACTED]:[REDACTED]" : "[REDACTED]"}@${suffix}`);
1861
+ });
1862
+ }
1863
+ function redactLooseUrls(text) {
1864
+ const urls = text.replace(/\b[A-Za-z][A-Za-z0-9+.-]*:\/\/[^\s"'`<>\])]+/g, (match) => redactUrlToken(match));
1865
+ return redactLooseUrlParameterText(redactLooseUrlUserinfo(urls));
1866
+ }
1867
+
1868
+ // dist/extensions/agent-browser/lib/runtime-redaction.js
1869
+ function redactSensitiveText(text) {
1870
+ const serialized = redactSerializedJson(text, redactSensitiveText);
1871
+ if (serialized !== void 0) {
1872
+ return serialized;
1873
+ }
1874
+ const embedded = redactEmbeddedStructuredText(text, redactSensitiveText);
1875
+ const credentials = redactStandaloneBasicCredential(redactBearerCredentials(redactLooseUrls(embedded))).replace(/\b(Authorization\s*:\s*Basic)\s+[^\s",]+/gi, "$1 [REDACTED]").replace(/\b(Cookie|Set-Cookie)\s*:\s*[^\n\r"]+/gi, "$1: [REDACTED]");
1876
+ return redactEmbeddedStructuredText(redactEnvSecretAssignments(credentials), redactSensitiveText);
1877
+ }
1878
+ function redactSensitiveValue(value) {
1879
+ if (typeof value === "string") {
1880
+ return redactSensitiveText(value);
1881
+ }
1882
+ if (Array.isArray(value)) {
1883
+ return value.map((item) => redactSensitiveValue(item));
1884
+ }
1885
+ if (!isRecord(value)) {
1886
+ return value;
1887
+ }
1888
+ return Object.fromEntries(Object.entries(value).map(([key, entryValue]) => [
1889
+ key,
1890
+ isSensitiveFieldName(key) ? "[REDACTED]" : redactSensitiveValue(entryValue)
1891
+ ]));
1892
+ }
1893
+
1894
+ // dist/extensions/agent-browser/lib/temp.js
1895
+ import { randomBytes } from "node:crypto";
1896
+ import { chmod as chmod3, mkdir, mkdtemp as mkdtemp2, open, rm as rm4 } from "node:fs/promises";
1897
+ import { dirname as dirname4, join as join5 } from "node:path";
1898
+
1899
+ // dist/extensions/agent-browser/lib/temp-mutation-queue.js
1900
+ var tempMutationQueue = Promise.resolve();
1901
+ function enqueueTempMutation(task) {
1902
+ const nextTask = tempMutationQueue.then(task, task);
1903
+ tempMutationQueue = nextTask.then(() => void 0, () => void 0);
1904
+ return nextTask;
1905
+ }
1906
+
1907
+ // dist/extensions/agent-browser/lib/temp-root.js
1908
+ import { randomInt } from "node:crypto";
1909
+ import { existsSync, readdirSync, rmSync } from "node:fs";
1910
+ import { chmod as chmod2, mkdtemp, readdir as readdir2, rm as rm2, stat as stat2 } from "node:fs/promises";
1911
+ import { tmpdir } from "node:os";
1912
+ import { dirname as dirname3, join as join3, resolve as resolve2 } from "node:path";
1913
+
1914
+ // dist/extensions/agent-browser/lib/temp-root-ownership.js
1915
+ import { chmod, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
1916
+ import { basename, dirname as dirname2, join as join2, resolve } from "node:path";
1917
+
1918
+ // dist/extensions/agent-browser/lib/process-identity.js
1919
+ import { execFile } from "node:child_process";
1920
+ import { dirname, join, win32 } from "node:path";
1921
+ var WINDOWS_PROCESS_START_IDENTITY_PREFIX = "win32-powershell-ticks-v1:";
1922
+ var PROCESS_START_IDENTITY_TIMEOUT_MS = process.platform === "win32" ? 1e4 : 5e3;
1923
+ var DEFAULT_WINDOWS_SYSTEM_ROOT = "C:\\Windows";
1924
+ function buildProcessStartIdentityCommand(pid, platform = process.platform) {
1925
+ if (!Number.isSafeInteger(pid) || pid <= 0) {
1926
+ return void 0;
1927
+ }
1928
+ const configuredSystemRoot = process.env.SystemRoot;
1929
+ const windowsSystemRoot = configuredSystemRoot !== void 0 && configuredSystemRoot.length > 0 && win32.isAbsolute(configuredSystemRoot) ? configuredSystemRoot : DEFAULT_WINDOWS_SYSTEM_ROOT;
1930
+ return platform === "win32" ? {
1931
+ args: [
1932
+ "-NoProfile",
1933
+ "-NonInteractive",
1934
+ "-Command",
1935
+ `$p = Get-Process -Id ${pid} -ErrorAction Stop; Write-Output ("${WINDOWS_PROCESS_START_IDENTITY_PREFIX}" + $p.StartTime.ToUniversalTime().Ticks)`
1936
+ ],
1937
+ file: win32.join(windowsSystemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
1938
+ } : {
1939
+ args: ["-p", String(pid), "-o", "lstart="],
1940
+ file: platform === "android" ? join(dirname(process.execPath), "ps") : "/bin/ps"
1941
+ };
1942
+ }
1943
+ function buildProcessStartIdentityCommands(pid, platform = process.platform) {
1944
+ const primary = buildProcessStartIdentityCommand(pid, platform);
1945
+ if (!primary) {
1946
+ return [];
1947
+ }
1948
+ return platform === "win32" ? [primary] : [
1949
+ primary,
1950
+ ...platform === "android" ? [
1951
+ { ...primary, file: "/bin/ps" },
1952
+ { ...primary, file: "/usr/bin/ps" }
1953
+ ] : [
1954
+ { ...primary, file: "/usr/bin/ps" },
1955
+ { ...primary, file: "ps" }
1956
+ ]
1957
+ ];
1958
+ }
1959
+ function normalizeProcessStartIdentity(stdout) {
1960
+ const trimmed = stdout.trim();
1961
+ if (trimmed.length === 0 || trimmed.includes("\0") || /[\r\n]/.test(trimmed)) {
1962
+ return void 0;
1963
+ }
1964
+ return trimmed.replace(/\s+/g, " ");
1965
+ }
1966
+ var currentProcessStartIdentityPromise;
1967
+ var currentProcessStartIdentity;
1968
+ async function executeProcessStartIdentityCommand(command, budget = {}) {
1969
+ if (budget.signal?.aborted === true || budget.deadline !== void 0 && Date.now() >= budget.deadline) {
1970
+ return void 0;
1971
+ }
1972
+ const timeout = Math.max(1, Math.min(PROCESS_START_IDENTITY_TIMEOUT_MS, (budget.deadline ?? Infinity) - Date.now()));
1973
+ return await new Promise((resolve3) => {
1974
+ execFile(command.file, command.args, { timeout, signal: budget.signal }, (error, stdout) => {
1975
+ resolve3(error ? void 0 : normalizeProcessStartIdentity(stdout));
1976
+ });
1977
+ });
1978
+ }
1979
+ async function resolveProcessStartIdentityFromCommands(commands, execute = executeProcessStartIdentityCommand) {
1980
+ for (const command of commands) {
1981
+ const identity = await execute(command);
1982
+ if (identity !== void 0 && identity.length > 0) {
1983
+ return identity;
1984
+ }
1985
+ }
1986
+ return void 0;
1987
+ }
1988
+ async function readUncachedProcessStartIdentity(pid, platform, budget) {
1989
+ return await resolveProcessStartIdentityFromCommands(buildProcessStartIdentityCommands(pid, platform), (command) => executeProcessStartIdentityCommand(command, budget));
1990
+ }
1991
+ function identityBudgetExpired(budget) {
1992
+ return budget?.signal?.aborted === true || budget?.deadline !== void 0 && Date.now() >= budget.deadline;
1993
+ }
1994
+ async function readProcessStartIdentity(pid, platform = process.platform, budget) {
1995
+ if (identityBudgetExpired(budget)) {
1996
+ return void 0;
1997
+ }
1998
+ if (pid !== process.pid || platform !== process.platform) {
1999
+ return await readUncachedProcessStartIdentity(pid, platform, budget);
2000
+ }
2001
+ if (currentProcessStartIdentity !== void 0 && currentProcessStartIdentity.length > 0) {
2002
+ return currentProcessStartIdentity;
2003
+ }
2004
+ if (budget) {
2005
+ const identity = await readUncachedProcessStartIdentity(pid, platform, budget);
2006
+ if (identity !== void 0 && identity.length > 0) {
2007
+ currentProcessStartIdentity = identity;
2008
+ }
2009
+ return identity;
2010
+ }
2011
+ return await readCachedProcessStartIdentity(pid, platform);
2012
+ }
2013
+ async function readCachedProcessStartIdentity(pid, platform) {
2014
+ currentProcessStartIdentityPromise ??= readUncachedProcessStartIdentity(pid, platform).then((identity) => {
2015
+ if (identity === void 0 || identity.length === 0) {
2016
+ currentProcessStartIdentityPromise = void 0;
2017
+ } else {
2018
+ currentProcessStartIdentity = identity;
2019
+ }
2020
+ return identity;
2021
+ });
2022
+ return await currentProcessStartIdentityPromise;
2023
+ }
2024
+ function processStartIdentitiesMatch(recorded, current) {
2025
+ return recorded === current;
2026
+ }
2027
+
2028
+ // dist/extensions/agent-browser/lib/process-errors.js
2029
+ function getErrorCode(error) {
2030
+ return isRecord(error) && typeof error.code === "string" ? error.code : void 0;
2031
+ }
2032
+
2033
+ // dist/extensions/agent-browser/lib/temp-root-ownership.js
2034
+ var TEMP_ROOT_MARKER_FILE_NAME = ".pi-agent-browser-owner.json";
2035
+ var TEMP_ROOT_MARKER_KIND = "pi-agent-browser-temp-root";
2036
+ var TEMP_ROOT_MARKER_VERSION = 2;
2037
+ function getCurrentProcessUid() {
2038
+ return typeof process.getuid === "function" ? process.getuid() : void 0;
2039
+ }
2040
+ function isPositiveFiniteNumber(value) {
2041
+ return typeof value === "number" && Number.isFinite(value) && value > 0;
2042
+ }
2043
+ function isProtectedTempChildName(value) {
2044
+ if (typeof value !== "string") {
2045
+ return false;
2046
+ }
2047
+ if (value === "" || value === "." || value === ".." || value === TEMP_ROOT_MARKER_FILE_NAME) {
2048
+ return false;
2049
+ }
2050
+ if (value.includes("/") || value.includes("\\")) {
2051
+ return false;
2052
+ }
2053
+ return basename(value) === value;
2054
+ }
2055
+ function isTempRootOwnershipRecord(value) {
2056
+ if (!isRecord(value)) {
2057
+ return false;
2058
+ }
2059
+ if (value.kind !== TEMP_ROOT_MARKER_KIND || value.version !== TEMP_ROOT_MARKER_VERSION) {
2060
+ return false;
2061
+ }
2062
+ if (!isPositiveFiniteNumber(value.createdAtMs)) {
2063
+ return false;
2064
+ }
2065
+ return validLeaseAndProcess(value) && validOwnershipAndChildren(value);
2066
+ }
2067
+ function validLeaseAndProcess(value) {
2068
+ if (value.leaseUpdatedAtMs !== void 0 && !isPositiveFiniteNumber(value.leaseUpdatedAtMs)) {
2069
+ return false;
2070
+ }
2071
+ if (value.ownerPid !== void 0 && (typeof value.ownerPid !== "number" || !Number.isSafeInteger(value.ownerPid) || value.ownerPid <= 0)) {
2072
+ return false;
2073
+ }
2074
+ return value.ownerProcessStartIdentity === void 0 || typeof value.ownerProcessStartIdentity === "string" && value.ownerProcessStartIdentity.trim() !== "";
2075
+ }
2076
+ function validOwnershipAndChildren(value) {
2077
+ if (value.ownerUid !== void 0 && (typeof value.ownerUid !== "number" || !Number.isSafeInteger(value.ownerUid) || value.ownerUid < 0)) {
2078
+ return false;
2079
+ }
2080
+ if (value.protectedChildNames === void 0) {
2081
+ return true;
2082
+ }
2083
+ if (!Array.isArray(value.protectedChildNames)) {
2084
+ return false;
2085
+ }
2086
+ const names = value.protectedChildNames;
2087
+ return names.every(isProtectedTempChildName);
2088
+ }
2089
+ async function readTempRootOwnershipMarker(tempRoot) {
2090
+ try {
2091
+ const markerText = await readFile(join2(tempRoot, TEMP_ROOT_MARKER_FILE_NAME), "utf8");
2092
+ const parsed = JSON.parse(markerText);
2093
+ return isTempRootOwnershipRecord(parsed) ? parsed : void 0;
2094
+ } catch {
2095
+ return void 0;
2096
+ }
2097
+ }
2098
+ function getPersistedProtectedChildPaths(tempRoot, ownershipMarker) {
2099
+ const normalizedTempRoot = resolve(tempRoot);
2100
+ return new Set((ownershipMarker?.protectedChildNames ?? []).map((childName) => resolve(join2(normalizedTempRoot, childName))));
2101
+ }
2102
+ async function writeTempRootOwnershipMarkerRecord(tempRoot, markerRecord, options = {}) {
2103
+ const markerPath = join2(tempRoot, TEMP_ROOT_MARKER_FILE_NAME);
2104
+ await writeFile(markerPath, JSON.stringify(markerRecord, null, 2), {
2105
+ encoding: "utf8",
2106
+ flag: options.flag,
2107
+ mode: 384
2108
+ });
2109
+ await chmod(markerPath, 384).catch(() => void 0);
2110
+ return markerPath;
2111
+ }
2112
+ async function getExistingProtectedChildren(tempRoot, protectedChildren) {
2113
+ const normalizedTempRoot = resolve(tempRoot);
2114
+ const existingChildren = /* @__PURE__ */ new Set();
2115
+ for (const path of protectedChildren) {
2116
+ const normalizedPath = resolve(path);
2117
+ if (dirname2(normalizedPath) !== normalizedTempRoot) {
2118
+ continue;
2119
+ }
2120
+ if (
2121
+ // Scan in bounded sequence instead of opening an unbounded number of filesystem requests.
2122
+ // oxlint-disable-next-line no-await-in-loop
2123
+ await stat(normalizedPath).then((stats) => stats.isDirectory(), () => false)
2124
+ ) {
2125
+ existingChildren.add(normalizedPath);
2126
+ }
2127
+ }
2128
+ return existingChildren;
2129
+ }
2130
+ async function removeTempRootChildrenExcept(tempRoot, protectedChildren) {
2131
+ const entries = await readdir(tempRoot, { withFileTypes: true }).catch(() => []);
2132
+ await Promise.all(entries.map(async (entry) => {
2133
+ if (entry.name === TEMP_ROOT_MARKER_FILE_NAME) {
2134
+ return;
2135
+ }
2136
+ const entryPath = join2(tempRoot, entry.name);
2137
+ if (protectedChildren.has(resolve(entryPath))) {
2138
+ return;
2139
+ }
2140
+ await rm(entryPath, { force: true, recursive: true }).catch(() => void 0);
2141
+ }));
2142
+ }
2143
+ async function getProcessStartIdentity(pid) {
2144
+ return pid === void 0 ? void 0 : await readProcessStartIdentity(pid);
2145
+ }
2146
+ async function writeSecureTempRootOwnershipMarker(tempRoot, options = {}) {
2147
+ const createdAtMs = options.createdAtMs ?? Date.now();
2148
+ const ownerPid = options.ownerPid ?? process.pid;
2149
+ const markerRecord = {
2150
+ createdAtMs,
2151
+ kind: TEMP_ROOT_MARKER_KIND,
2152
+ leaseUpdatedAtMs: options.leaseUpdatedAtMs ?? createdAtMs,
2153
+ ownerPid,
2154
+ ownerProcessStartIdentity: options.ownerProcessStartIdentity ?? await getProcessStartIdentity(ownerPid),
2155
+ ownerUid: getCurrentProcessUid(),
2156
+ version: TEMP_ROOT_MARKER_VERSION
2157
+ };
2158
+ return await writeTempRootOwnershipMarkerRecord(tempRoot, markerRecord, { flag: "wx" });
2159
+ }
2160
+ async function refreshSecureTempRootLease(tempRoot) {
2161
+ const ownershipMarker = await readTempRootOwnershipMarker(tempRoot);
2162
+ if (!ownershipMarker) {
2163
+ return;
2164
+ }
2165
+ if (ownershipMarker.ownerPid !== process.pid) {
2166
+ return;
2167
+ }
2168
+ const currentUid = getCurrentProcessUid();
2169
+ if (currentUid !== void 0 && ownershipMarker.ownerUid !== void 0 && ownershipMarker.ownerUid !== currentUid) {
2170
+ return;
2171
+ }
2172
+ const currentProcessStartIdentity2 = await getProcessStartIdentity(process.pid);
2173
+ if (ownershipMarker.ownerProcessStartIdentity !== void 0 && currentProcessStartIdentity2 !== void 0) {
2174
+ const identitiesMatch = processStartIdentitiesMatch(ownershipMarker.ownerProcessStartIdentity, currentProcessStartIdentity2);
2175
+ if (!identitiesMatch) {
2176
+ return;
2177
+ }
2178
+ }
2179
+ const refreshedMarker = {
2180
+ ...ownershipMarker,
2181
+ leaseUpdatedAtMs: Date.now(),
2182
+ ownerPid: process.pid,
2183
+ ownerProcessStartIdentity: currentProcessStartIdentity2 ?? ownershipMarker.ownerProcessStartIdentity,
2184
+ ownerUid: currentUid,
2185
+ version: TEMP_ROOT_MARKER_VERSION
2186
+ };
2187
+ await writeTempRootOwnershipMarkerRecord(tempRoot, refreshedMarker);
2188
+ }
2189
+ async function getMarkerOwnerLiveness(ownershipMarker) {
2190
+ const pid = ownershipMarker.ownerPid;
2191
+ if (pid === void 0) {
2192
+ return "unknown";
2193
+ }
2194
+ try {
2195
+ process.kill(pid, 0);
2196
+ } catch (error) {
2197
+ const code = getErrorCode(error);
2198
+ if (code === "ESRCH") {
2199
+ return "dead";
2200
+ }
2201
+ if (code !== "EPERM") {
2202
+ return "unknown";
2203
+ }
2204
+ }
2205
+ const currentProcessStartIdentity2 = await getProcessStartIdentity(pid);
2206
+ if (ownershipMarker.ownerProcessStartIdentity === void 0 || currentProcessStartIdentity2 === void 0) {
2207
+ return "unknown";
2208
+ }
2209
+ const identitiesMatch = processStartIdentitiesMatch(ownershipMarker.ownerProcessStartIdentity, currentProcessStartIdentity2);
2210
+ return identitiesMatch ? "alive" : "dead";
2211
+ }
2212
+
2213
+ // dist/extensions/agent-browser/lib/temp-root.js
2214
+ var TEMP_ROOT_PREFIX = "pi-agent-browser-";
2215
+ var STALE_TEMP_ROOT_MAX_AGE_MS = 24 * 60 * 60 * 1e3;
2216
+ var STALE_TEMP_ROOT_BATCH_SIZE = 8;
2217
+ var lastTempGcName;
2218
+ var sessionTempRootPromise;
2219
+ var exitCleanupRegistered = false;
2220
+ var ownedTempRoots = /* @__PURE__ */ new Set();
2221
+ var protectedTempChildren = /* @__PURE__ */ new Set();
2222
+ function markerMatchesUid(marker, uid) {
2223
+ return uid === void 0 || marker.ownerUid === void 0 || marker.ownerUid === uid;
2224
+ }
2225
+ async function pruneTempRoot(path, currentUid, cutoffTime) {
2226
+ const marker = await readTempRootOwnershipMarker(path);
2227
+ if (!marker || !markerMatchesUid(marker, currentUid)) {
2228
+ return;
2229
+ }
2230
+ if ((marker.leaseUpdatedAtMs ?? marker.createdAtMs) >= cutoffTime) {
2231
+ return;
2232
+ }
2233
+ if (await getMarkerOwnerLiveness(marker) !== "dead") {
2234
+ return;
2235
+ }
2236
+ const stats = await stat2(path).catch(() => void 0);
2237
+ if (stats?.isDirectory() !== true) {
2238
+ return;
2239
+ }
2240
+ const protectedChildren = await getExistingProtectedChildren(path, getPersistedProtectedChildPaths(path, marker));
2241
+ if (protectedChildren.size > 0) {
2242
+ await removeTempRootChildrenExcept(path, protectedChildren);
2243
+ return;
2244
+ }
2245
+ await rm2(path, { force: true, recursive: true }).catch(() => {
2246
+ });
2247
+ }
2248
+ async function pruneStaleTempRoots(currentTempRoot) {
2249
+ const entries = await readdir2(tmpdir(), { withFileTypes: true }).catch(() => []);
2250
+ const cutoffTime = Date.now() - STALE_TEMP_ROOT_MAX_AGE_MS;
2251
+ const currentUid = getCurrentProcessUid();
2252
+ const candidates = entries.filter((entry) => entry.isDirectory() && entry.name.startsWith(TEMP_ROOT_PREFIX)).map((entry) => entry.name).sort();
2253
+ if (candidates.length === 0) {
2254
+ return;
2255
+ }
2256
+ const previousName = lastTempGcName;
2257
+ const start = previousName === void 0 ? randomInt(candidates.length) : Math.max(0, candidates.findIndex((name) => name > previousName));
2258
+ const batch = Array.from({ length: Math.min(STALE_TEMP_ROOT_BATCH_SIZE, candidates.length) }, (_, offset) => candidates[(start + offset) % candidates.length]);
2259
+ lastTempGcName = batch.at(-1);
2260
+ await Promise.all(batch.map(async (name) => {
2261
+ const path = join3(tmpdir(), name);
2262
+ if (path !== currentTempRoot) {
2263
+ await pruneTempRoot(path, currentUid, cutoffTime);
2264
+ }
2265
+ }));
2266
+ }
2267
+ function getProtectedChildrenForRoot(tempRoot) {
2268
+ const normalizedTempRoot = resolve2(tempRoot);
2269
+ return new Set([...protectedTempChildren].filter((path) => dirname3(path) === normalizedTempRoot && existsSync(path)));
2270
+ }
2271
+ function removeTempRootChildrenExceptSync(tempRoot, protectedChildren) {
2272
+ for (const entry of readdirSync(tempRoot, { withFileTypes: true })) {
2273
+ if (entry.name === TEMP_ROOT_MARKER_FILE_NAME) {
2274
+ continue;
2275
+ }
2276
+ const entryPath = join3(tempRoot, entry.name);
2277
+ if (protectedChildren.has(resolve2(entryPath))) {
2278
+ continue;
2279
+ }
2280
+ rmSync(entryPath, { force: true, recursive: true });
2281
+ }
2282
+ }
2283
+ function registerExitCleanup() {
2284
+ if (exitCleanupRegistered) {
2285
+ return;
2286
+ }
2287
+ exitCleanupRegistered = true;
2288
+ process.once("exit", () => {
2289
+ for (const tempRoot of ownedTempRoots) {
2290
+ try {
2291
+ const protectedChildren = getProtectedChildrenForRoot(tempRoot);
2292
+ if (protectedChildren.size === 0) {
2293
+ rmSync(tempRoot, { force: true, recursive: true });
2294
+ } else {
2295
+ removeTempRootChildrenExceptSync(tempRoot, protectedChildren);
2296
+ }
2297
+ } catch {
2298
+ }
2299
+ }
2300
+ });
2301
+ }
2302
+ async function allocateSessionTempRoot() {
2303
+ const tempRoot = await mkdtemp(join3(tmpdir(), TEMP_ROOT_PREFIX));
2304
+ try {
2305
+ await chmod2(tempRoot, 448).catch(() => {
2306
+ });
2307
+ await writeSecureTempRootOwnershipMarker(tempRoot);
2308
+ ownedTempRoots.add(tempRoot);
2309
+ registerExitCleanup();
2310
+ return tempRoot;
2311
+ } catch (error) {
2312
+ await rm2(tempRoot, { force: true, recursive: true }).catch(() => {
2313
+ });
2314
+ throw error;
2315
+ }
2316
+ }
2317
+ async function getSessionTempRoot() {
2318
+ sessionTempRootPromise ??= allocateSessionTempRoot().catch((error) => {
2319
+ sessionTempRootPromise = void 0;
2320
+ throw error;
2321
+ });
2322
+ const tempRoot = await sessionTempRootPromise;
2323
+ await refreshSecureTempRootLease(tempRoot).catch(() => {
2324
+ });
2325
+ await pruneStaleTempRoots(tempRoot).catch(() => {
2326
+ });
2327
+ return tempRoot;
2328
+ }
2329
+
2330
+ // dist/extensions/agent-browser/lib/temp-artifact-budget.js
2331
+ import { readdir as readdir3, rm as rm3, stat as stat3 } from "node:fs/promises";
2332
+ import { join as join4 } from "node:path";
2333
+ var DEFAULT_MAX_BYTES = 32 * 1024 * 1024;
2334
+ function getTempArtifactByteLength(content) {
2335
+ return typeof content === "string" ? Buffer.byteLength(content) : content.byteLength;
2336
+ }
2337
+ async function listArtifactFiles(directory, excludedNames = /* @__PURE__ */ new Set()) {
2338
+ const entries = await readdir3(directory, { withFileTypes: true }).catch(() => []);
2339
+ const files = [];
2340
+ const candidates = entries.filter((entry) => entry.isFile() && !excludedNames.has(entry.name));
2341
+ for (let index = 0; index < candidates.length; index += 4) {
2342
+ const batch = await Promise.all(candidates.slice(index, index + 4).map(async (entry) => {
2343
+ const path = join4(directory, entry.name);
2344
+ const stats = await stat3(path).catch(() => void 0);
2345
+ return stats?.isFile() === true ? { mtimeMs: stats.mtimeMs, path, size: stats.size } : void 0;
2346
+ }));
2347
+ for (const file of batch) {
2348
+ if (file !== void 0) {
2349
+ files.push(file);
2350
+ }
2351
+ }
2352
+ }
2353
+ return files;
2354
+ }
2355
+ function getSecureTempRootMaxBytes(env = process.env) {
2356
+ return parsePositiveInteger(env.PI_AGENT_BROWSER_TEMP_ROOT_MAX_BYTES) ?? DEFAULT_MAX_BYTES;
2357
+ }
2358
+ function getPersistentSessionArtifactMaxBytes(env = process.env) {
2359
+ if (env.PI_AGENT_BROWSER_SESSION_ARTIFACT_MAX_BYTES?.trim() === "0") {
2360
+ return 0;
2361
+ }
2362
+ return parsePositiveInteger(env.PI_AGENT_BROWSER_SESSION_ARTIFACT_MAX_BYTES) ?? DEFAULT_MAX_BYTES;
2363
+ }
2364
+ async function assertSecureTempRootBudget(tempRoot, additionalBytes) {
2365
+ if (additionalBytes <= 0) {
2366
+ return;
2367
+ }
2368
+ const files = await listArtifactFiles(tempRoot, /* @__PURE__ */ new Set([".pi-agent-browser-owner.json"]));
2369
+ const currentBytes = files.reduce((total, file) => total + file.size, 0);
2370
+ const maxBytes = getSecureTempRootMaxBytes();
2371
+ const nextBytes = currentBytes + additionalBytes;
2372
+ if (nextBytes > maxBytes) {
2373
+ throw new Error(`pi-agent-browser temp spill budget exceeded (${nextBytes} bytes > ${maxBytes} byte limit).`);
2374
+ }
2375
+ }
2376
+ async function prunePersistentSessionArtifactsToBudget(sessionArtifactDir, additionalBytes, protectedPaths) {
2377
+ if (additionalBytes <= 0) {
2378
+ return [];
2379
+ }
2380
+ const maxBytes = getPersistentSessionArtifactMaxBytes();
2381
+ if (maxBytes === 0) {
2382
+ return [];
2383
+ }
2384
+ const files = await listArtifactFiles(sessionArtifactDir);
2385
+ let totalBytes = files.reduce((total, file) => total + file.size, 0);
2386
+ if (totalBytes + additionalBytes <= maxBytes) {
2387
+ return [];
2388
+ }
2389
+ const evictedArtifacts = [];
2390
+ files.sort((left, right) => {
2391
+ const time = left.mtimeMs - right.mtimeMs;
2392
+ return time === 0 ? left.path.localeCompare(right.path) : time;
2393
+ });
2394
+ for (const file of files) {
2395
+ if (protectedPaths.has(file.path)) {
2396
+ continue;
2397
+ }
2398
+ const removed = await rm3(file.path, { force: true }).then(() => true, () => false);
2399
+ if (!removed) {
2400
+ continue;
2401
+ }
2402
+ evictedArtifacts.push({ mtimeMs: file.mtimeMs, path: file.path, sizeBytes: file.size });
2403
+ totalBytes -= file.size;
2404
+ if (totalBytes + additionalBytes <= maxBytes) {
2405
+ return evictedArtifacts;
2406
+ }
2407
+ }
2408
+ throw new Error(`pi-agent-browser persisted spill budget exceeded (${totalBytes + additionalBytes} bytes > ${maxBytes} byte limit).`);
2409
+ }
2410
+
2411
+ // dist/extensions/agent-browser/lib/temp.js
2412
+ async function ensurePersistentSessionArtifactDir(store) {
2413
+ const rootDir = join5(store.sessionDir, ".pi-agent-browser-artifacts");
2414
+ const sessionDir = join5(rootDir, store.sessionId);
2415
+ await mkdir(rootDir, { recursive: true, mode: 448 });
2416
+ await chmod3(rootDir, 448).catch(() => {
2417
+ });
2418
+ await mkdir(sessionDir, { recursive: true, mode: 448 });
2419
+ await chmod3(sessionDir, 448).catch(() => {
2420
+ });
2421
+ return sessionDir;
2422
+ }
2423
+ async function openSecureTempFile(prefix, suffix) {
2424
+ const tempRoot = await getSessionTempRoot();
2425
+ const path = join5(tempRoot, `${prefix}-${randomBytes(8).toString("hex")}${suffix}`);
2426
+ const fileHandle = await open(path, "wx", 384);
2427
+ return { fileHandle, path };
2428
+ }
2429
+ async function writeSecureTempChunk(options) {
2430
+ const { content, fileHandle, path } = options;
2431
+ await enqueueTempMutation(async () => {
2432
+ const tempRoot = dirname4(path);
2433
+ await refreshSecureTempRootLease(tempRoot).catch(() => {
2434
+ });
2435
+ await assertSecureTempRootBudget(tempRoot, getTempArtifactByteLength(content));
2436
+ await fileHandle.appendFile(content);
2437
+ });
2438
+ }
2439
+ async function writeSecureTempFile(options) {
2440
+ const { content, prefix, suffix } = options;
2441
+ const { fileHandle, path } = await openSecureTempFile(prefix, suffix);
2442
+ try {
2443
+ await writeSecureTempChunk({ content, fileHandle, path });
2444
+ } catch (error) {
2445
+ await rm4(path, { force: true }).catch(() => {
2446
+ });
2447
+ throw error;
2448
+ } finally {
2449
+ await fileHandle.close();
2450
+ }
2451
+ return path;
2452
+ }
2453
+ async function writePersistentSessionArtifactFile(options) {
2454
+ const { content, prefix, store, suffix } = options;
2455
+ return await enqueueTempMutation(async () => {
2456
+ const artifactDir = await ensurePersistentSessionArtifactDir(store);
2457
+ const evictedArtifacts = await prunePersistentSessionArtifactsToBudget(artifactDir, getTempArtifactByteLength(content), new Set((store.protectedPaths ?? []).filter((path2) => dirname4(path2) === artifactDir)));
2458
+ const path = join5(artifactDir, `${prefix}-${randomBytes(8).toString("hex")}${suffix}`);
2459
+ const fileHandle = await open(path, "wx", 384);
2460
+ try {
2461
+ await fileHandle.writeFile(content);
2462
+ } catch (error) {
2463
+ await rm4(path, { force: true }).catch(() => {
2464
+ });
2465
+ throw error;
2466
+ } finally {
2467
+ await fileHandle.close().catch(() => {
2468
+ });
2469
+ }
2470
+ return { evictedArtifacts, path };
2471
+ });
2472
+ }
2473
+
2474
+ // dist/extensions/agent-browser/lib/results/artifact-manifest.js
2475
+ function isPendingRecordingCommand(command, subcommand, kind) {
2476
+ return command === "record" && (subcommand === "start" || subcommand === "restart") && kind === "video";
2477
+ }
2478
+ function isPendingRecordingArtifact(artifact) {
2479
+ return artifact.recordingState === "openRecording" || artifact.status === "pending" || artifact.status === void 0 && isPendingRecordingCommand(artifact.command, artifact.subcommand, artifact.kind);
2480
+ }
2481
+ var SESSION_ARTIFACT_MANIFEST_VERSION = 1;
2482
+ var SESSION_ARTIFACT_MANIFEST_MAX_ENTRIES_ENV = "PI_AGENT_BROWSER_SESSION_ARTIFACT_MANIFEST_MAX_ENTRIES";
2483
+ var DEFAULT_SESSION_ARTIFACT_MANIFEST_MAX_ENTRIES = 100;
2484
+ function parsePositiveSafeInteger(value) {
2485
+ if (value === void 0) {
2486
+ return void 0;
2487
+ }
2488
+ const parsed = Number(value);
2489
+ if (!Number.isSafeInteger(parsed) || parsed <= 0) {
2490
+ return void 0;
2491
+ }
2492
+ return parsed;
2493
+ }
2494
+ function getSessionArtifactManifestMaxEntries(env = process.env) {
2495
+ return parsePositiveSafeInteger(env[SESSION_ARTIFACT_MANIFEST_MAX_ENTRIES_ENV]) ?? DEFAULT_SESSION_ARTIFACT_MANIFEST_MAX_ENTRIES;
2496
+ }
2497
+ function buildEvictedSessionArtifactEntries(evictedArtifacts, nowMs) {
2498
+ return evictedArtifacts.map((artifact) => ({
2499
+ createdAtMs: artifact.mtimeMs,
2500
+ evictedAtMs: nowMs,
2501
+ kind: "spill",
2502
+ path: artifact.path,
2503
+ retentionState: "evicted",
2504
+ sizeBytes: artifact.sizeBytes,
2505
+ storageScope: "persistent-session"
2506
+ }));
2507
+ }
2508
+ function formatSessionArtifactRetentionSummary(manifest) {
2509
+ const ephemeralCount = manifest.entries.filter((entry) => entry.retentionState === "ephemeral").length;
2510
+ const missingCount = manifest.entries.filter((entry) => entry.retentionState === "missing").length;
2511
+ const parts = [`${manifest.liveCount} live`, `${manifest.evictedCount} evicted`];
2512
+ if (ephemeralCount > 0) {
2513
+ parts.push(`${ephemeralCount} ephemeral`);
2514
+ }
2515
+ if (missingCount > 0) {
2516
+ parts.push(`${missingCount} missing`);
2517
+ }
2518
+ return `Session artifacts: ${parts.join(", ")} (${manifest.entries.length}/${manifest.maxEntries} recent).`;
2519
+ }
2520
+ function getSessionArtifactManifestEntryKey(entry) {
2521
+ const pathKey = entry.storageScope === "explicit-path" && entry.absolutePath !== void 0 && entry.absolutePath.length > 0 ? `${entry.storageScope}:${entry.absolutePath}` : `${entry.storageScope}:${entry.path}`;
2522
+ const recordingSessionKey = entry.command === "record" && entry.kind === "video" && entry.session !== void 0 && entry.session.length > 0 ? getAgentBrowserSessionIdentityKey(entry.session, entry.namespace) : void 0;
2523
+ return recordingSessionKey !== void 0 && recordingSessionKey.length > 0 ? `${pathKey}\0${recordingSessionKey}` : pathKey;
2524
+ }
2525
+ function getSupersededRecordingKeys(candidates, entry, key) {
2526
+ if (entry.command !== "record" || entry.kind !== "video") {
2527
+ return [];
2528
+ }
2529
+ const entrySessionKey = entry.session !== void 0 && entry.session.length > 0 ? getAgentBrowserSessionIdentityKey(entry.session, entry.namespace) : void 0;
2530
+ return [...candidates].filter(([candidateKey, candidate]) => {
2531
+ const sameRecordingSession = entrySessionKey === void 0 ? candidate.session === void 0 : candidate.session !== void 0 && getAgentBrowserSessionIdentityKey(candidate.session, candidate.namespace) === entrySessionKey;
2532
+ return candidateKey !== key && sameRecordingSession && candidate.kind === "video" && isPendingRecordingArtifact(candidate);
2533
+ }).map(([candidateKey]) => candidateKey);
2534
+ }
2535
+ function mergeManifestEntry(existing, entry, nowMs) {
2536
+ return {
2537
+ ...existing,
2538
+ ...entry,
2539
+ createdAtMs: entry.command === "record" && entry.kind === "video" ? entry.createdAtMs : existing?.createdAtMs ?? entry.createdAtMs,
2540
+ evictedAtMs: entry.retentionState === "evicted" ? entry.evictedAtMs ?? nowMs : entry.evictedAtMs
2541
+ };
2542
+ }
2543
+ function compareManifestEntries(left, right) {
2544
+ const difference = (right.evictedAtMs ?? right.createdAtMs) - (left.evictedAtMs ?? left.createdAtMs);
2545
+ if (difference !== 0 && !Number.isNaN(difference)) {
2546
+ return difference;
2547
+ }
2548
+ const pendingDifference = Number(isPendingRecordingArtifact(right)) - Number(isPendingRecordingArtifact(left));
2549
+ return pendingDifference !== 0 ? pendingDifference : left.path.localeCompare(right.path);
2550
+ }
2551
+ function mergeSessionArtifactManifest(options) {
2552
+ const nowMs = options.nowMs ?? Date.now();
2553
+ const maxEntries = getSessionArtifactManifestMaxEntries();
2554
+ const byPath = /* @__PURE__ */ new Map();
2555
+ for (const entry of options.base?.entries ?? []) {
2556
+ byPath.set(getSessionArtifactManifestEntryKey(entry), entry);
2557
+ }
2558
+ const orderedEntries = (options.entries ?? []).map((entry, index) => ({ entry, index })).sort((left, right) => {
2559
+ const difference = left.entry.createdAtMs - right.entry.createdAtMs;
2560
+ return difference !== 0 && !Number.isNaN(difference) ? difference : left.index - right.index;
2561
+ }).map(({ entry }) => entry);
2562
+ for (const entry of orderedEntries) {
2563
+ const key = getSessionArtifactManifestEntryKey(entry);
2564
+ for (const candidateKey of getSupersededRecordingKeys(byPath, entry, key)) {
2565
+ byPath.delete(candidateKey);
2566
+ }
2567
+ const existing = byPath.get(key);
2568
+ byPath.set(key, mergeManifestEntry(existing, entry, nowMs));
2569
+ }
2570
+ if (byPath.size === 0) {
2571
+ return void 0;
2572
+ }
2573
+ const entries = [...byPath.values()].sort(compareManifestEntries).slice(0, maxEntries);
2574
+ return {
2575
+ entries,
2576
+ evictedCount: entries.filter((entry) => entry.retentionState === "evicted").length,
2577
+ liveCount: entries.filter((entry) => entry.retentionState === "live").length,
2578
+ maxEntries,
2579
+ updatedAtMs: nowMs,
2580
+ version: SESSION_ARTIFACT_MANIFEST_VERSION
2581
+ };
2582
+ }
2583
+
2584
+ // dist/extensions/agent-browser/lib/results/snapshot-spill.js
2585
+ var SNAPSHOT_SPILL_FILE_PREFIX = "pi-agent-browser-snapshot";
2586
+ async function writeSnapshotSpillFile(data, persistentArtifactStore) {
2587
+ const options = {
2588
+ content: JSON.stringify(redactSensitiveValue(data), null, 2),
2589
+ prefix: SNAPSHOT_SPILL_FILE_PREFIX,
2590
+ suffix: ".json"
2591
+ };
2592
+ if (persistentArtifactStore) {
2593
+ const result = await writePersistentSessionArtifactFile({
2594
+ ...options,
2595
+ store: persistentArtifactStore
2596
+ });
2597
+ return { ...result, storageScope: "persistent-session" };
2598
+ }
2599
+ return {
2600
+ evictedArtifacts: [],
2601
+ path: await writeSecureTempFile(options),
2602
+ storageScope: "process-temp"
2603
+ };
2604
+ }
2605
+ function applySnapshotArtifactManifest(options) {
2606
+ if (options.fullOutputPath === void 0 || options.fullOutputPath.length === 0 || !options.spill) {
2607
+ return {};
2608
+ }
2609
+ const nowMs = Date.now();
2610
+ const entries = [
2611
+ {
2612
+ command: options.command,
2613
+ createdAtMs: nowMs,
2614
+ kind: "spill",
2615
+ path: options.fullOutputPath,
2616
+ retentionState: options.spill.storageScope === "persistent-session" ? "live" : "ephemeral",
2617
+ storageScope: options.spill.storageScope
2618
+ },
2619
+ ...buildEvictedSessionArtifactEntries(options.spill.evictedArtifacts, nowMs)
2620
+ ];
2621
+ const artifactManifest = mergeSessionArtifactManifest({
2622
+ base: options.baseManifest,
2623
+ entries,
2624
+ nowMs
2625
+ });
2626
+ return artifactManifest ? {
2627
+ artifactManifest,
2628
+ artifactRetentionSummary: formatSessionArtifactRetentionSummary(artifactManifest)
2629
+ } : {};
2630
+ }
2631
+
2632
+ // dist/extensions/agent-browser/lib/results/snapshot.js
2633
+ function shouldCompactSnapshot(rawText, data) {
2634
+ return rawText.length > 6e3 || countLines(getSnapshotText(data) ?? "") > 80 || Object.keys(getSnapshotRefRecord(data) ?? {}).length > 60;
2635
+ }
2636
+ async function getSnapshotSpill(data, store) {
2637
+ try {
2638
+ const spill = await writeSnapshotSpillFile(data, store);
2639
+ return { spill, fullOutputPath: spill.path };
2640
+ } catch (error) {
2641
+ return { spillErrorText: error instanceof Error ? error.message : stringifyUnknown(error) };
2642
+ }
2643
+ }
2644
+ async function buildSnapshotPresentation(data, persistentArtifactStore, artifactManifest) {
2645
+ const summary = formatSnapshotSummary(data);
2646
+ const rawText = formatRawSnapshotText(data);
2647
+ if (isRecord(data.snapshot) && data.snapshot.kind !== "full" || !shouldCompactSnapshot(rawText, data)) {
2648
+ return { content: [{ type: "text", text: rawText }], data, summary };
2649
+ }
2650
+ const { spill, fullOutputPath, spillErrorText } = await getSnapshotSpill(data, persistentArtifactStore);
2651
+ const compact = buildCompactSnapshotView(data, fullOutputPath, spillErrorText);
2652
+ const manifestFields = applySnapshotArtifactManifest({
2653
+ baseManifest: artifactManifest,
2654
+ command: "snapshot",
2655
+ fullOutputPath,
2656
+ spill
2657
+ });
2658
+ const notice = manifestFields.artifactRetentionSummary;
2659
+ const text = compact.content.at(0);
2660
+ if (notice !== void 0 && notice.length > 0 && text?.type === "text") {
2661
+ compact.content[0] = { type: "text", text: `${text.text}
2662
+
2663
+ ${notice}` };
2664
+ }
2665
+ return { ...manifestFields, ...compact, fullOutputPath, summary: `${summary} (compact)` };
2666
+ }
2667
+ export {
2668
+ buildSnapshotPresentation,
2669
+ formatRawSnapshotText,
2670
+ formatSnapshotSummary
2671
+ };