pi-agent-browser-native 0.9.5 → 0.9.7

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 (398) hide show
  1. package/CHANGELOG.md +114 -1
  2. package/README.md +17 -6
  3. package/dist/extensions/agent-browser/index.js +2482 -925
  4. package/dist/packaged/lib/browser-session-conversion.js +2946 -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 +728 -0
  8. package/dist/packaged/lib/results/snapshot.js +2800 -0
  9. package/dist/packaged/lib/runtime.js +3075 -0
  10. package/docs/ARCHITECTURE.md +29 -10
  11. package/docs/CODE_QUALITY.md +32 -5
  12. package/docs/COMMAND_REFERENCE.md +156 -40
  13. package/docs/ELECTRON.md +1 -1
  14. package/docs/PERFORMANCE.md +252 -0
  15. package/docs/REFERENCE.md +15 -15
  16. package/docs/RELEASE.md +41 -18
  17. package/docs/REQUIREMENTS.md +6 -0
  18. package/docs/SESSION_STORAGE.md +13 -5
  19. package/docs/SUPPORT_MATRIX.md +31 -25
  20. package/docs/TOOL_CONTRACT.md +41 -18
  21. package/docs/performance/2026-10-12.json +7257 -0
  22. package/docs/platform-smoke.md +18 -14
  23. package/package.json +18 -4
  24. package/platform-smoke.config.mjs +3 -2
  25. package/scripts/agent-browser-capability-baseline.mjs +16 -2
  26. package/scripts/agent-browser-target.mjs +1 -1
  27. package/scripts/build.mjs +16 -5
  28. package/scripts/capability-options.mjs +20 -0
  29. package/scripts/capability-samples.mjs +23 -10
  30. package/scripts/config.mjs +1 -1
  31. package/scripts/convert-browser-session.mjs +1 -1
  32. package/scripts/platform-smoke/commands.mjs +30 -4
  33. package/scripts/platform-smoke/doctor-support.mjs +11 -2
  34. package/scripts/platform-smoke/doctor-windows.mjs +1 -1
  35. package/scripts/platform-smoke/doctor.mjs +26 -11
  36. package/scripts/platform-smoke/linux-image/Dockerfile +6 -3
  37. package/scripts/platform-smoke/platform-build-windows.ps1 +23 -3
  38. package/scripts/platform-smoke/suite-checks.mjs +11 -1
  39. package/scripts/platform-smoke/targets.mjs +4 -3
  40. package/scripts/platform-smoke.mjs +68 -25
  41. package/dist/extensions/agent-browser/lib/argv-descriptor.js +0 -123
  42. package/dist/extensions/agent-browser/lib/argv-grammar.js +0 -320
  43. package/dist/extensions/agent-browser/lib/bash-guard.js +0 -193
  44. package/dist/extensions/agent-browser/lib/batch-lifecycle.js +0 -131
  45. package/dist/extensions/agent-browser/lib/browser-execution-claim-codec.js +0 -61
  46. package/dist/extensions/agent-browser/lib/browser-execution-claim-storage.js +0 -232
  47. package/dist/extensions/agent-browser/lib/browser-execution-claims.js +0 -202
  48. package/dist/extensions/agent-browser/lib/browser-execution-identity.js +0 -77
  49. package/dist/extensions/agent-browser/lib/browser-journal-branch.js +0 -98
  50. package/dist/extensions/agent-browser/lib/browser-journal-contracts.js +0 -1
  51. package/dist/extensions/agent-browser/lib/browser-journal-projection.js +0 -221
  52. package/dist/extensions/agent-browser/lib/browser-journal-reader.js +0 -89
  53. package/dist/extensions/agent-browser/lib/browser-journal-replay.js +0 -246
  54. package/dist/extensions/agent-browser/lib/browser-journal.js +0 -148
  55. package/dist/extensions/agent-browser/lib/browser-legacy-pages.js +0 -220
  56. package/dist/extensions/agent-browser/lib/browser-legacy-projection.js +0 -282
  57. package/dist/extensions/agent-browser/lib/browser-legacy-types.js +0 -1
  58. package/dist/extensions/agent-browser/lib/browser-session-conversion-stream.js +0 -217
  59. package/dist/extensions/agent-browser/lib/browser-session-conversion.js +0 -126
  60. package/dist/extensions/agent-browser/lib/browser-transcript-contracts.js +0 -35
  61. package/dist/extensions/agent-browser/lib/browser-transcript-validation.js +0 -166
  62. package/dist/extensions/agent-browser/lib/browser-transcript.js +0 -189
  63. package/dist/extensions/agent-browser/lib/browser-value-parsing.js +0 -15
  64. package/dist/extensions/agent-browser/lib/command-capabilities.js +0 -340
  65. package/dist/extensions/agent-browser/lib/command-policy.js +0 -155
  66. package/dist/extensions/agent-browser/lib/command-taxonomy.js +0 -105
  67. package/dist/extensions/agent-browser/lib/config-policy.js +0 -450
  68. package/dist/extensions/agent-browser/lib/config-providers.js +0 -71
  69. package/dist/extensions/agent-browser/lib/config-validation.js +0 -231
  70. package/dist/extensions/agent-browser/lib/config.js +0 -69
  71. package/dist/extensions/agent-browser/lib/electron/cdp.js +0 -62
  72. package/dist/extensions/agent-browser/lib/electron/cleanup.js +0 -274
  73. package/dist/extensions/agent-browser/lib/electron/discovery-darwin.js +0 -109
  74. package/dist/extensions/agent-browser/lib/electron/discovery-desktop.js +0 -136
  75. package/dist/extensions/agent-browser/lib/electron/discovery-evidence.js +0 -90
  76. package/dist/extensions/agent-browser/lib/electron/discovery-linux.js +0 -93
  77. package/dist/extensions/agent-browser/lib/electron/discovery-packages.js +0 -162
  78. package/dist/extensions/agent-browser/lib/electron/discovery-types.js +0 -2
  79. package/dist/extensions/agent-browser/lib/electron/discovery.js +0 -217
  80. package/dist/extensions/agent-browser/lib/electron/launch-monitor.js +0 -102
  81. package/dist/extensions/agent-browser/lib/electron/launch-process.js +0 -209
  82. package/dist/extensions/agent-browser/lib/electron/launch-types.js +0 -2
  83. package/dist/extensions/agent-browser/lib/electron/launch.js +0 -340
  84. package/dist/extensions/agent-browser/lib/executable-path.js +0 -29
  85. package/dist/extensions/agent-browser/lib/execution-cwd.js +0 -67
  86. package/dist/extensions/agent-browser/lib/fs-utils.js +0 -10
  87. package/dist/extensions/agent-browser/lib/input-modes/electron.js +0 -201
  88. package/dist/extensions/agent-browser/lib/input-modes/job.js +0 -198
  89. package/dist/extensions/agent-browser/lib/input-modes/lookup-network-evidence.js +0 -116
  90. package/dist/extensions/agent-browser/lib/input-modes/lookup-plan.js +0 -132
  91. package/dist/extensions/agent-browser/lib/input-modes/lookup-redaction.js +0 -57
  92. package/dist/extensions/agent-browser/lib/input-modes/lookup-source-evidence.js +0 -151
  93. package/dist/extensions/agent-browser/lib/input-modes/lookup-workspace.js +0 -142
  94. package/dist/extensions/agent-browser/lib/input-modes/lookups.js +0 -84
  95. package/dist/extensions/agent-browser/lib/input-modes/params.js +0 -195
  96. package/dist/extensions/agent-browser/lib/input-modes/qa-analysis.js +0 -268
  97. package/dist/extensions/agent-browser/lib/input-modes/qa-presentation.js +0 -117
  98. package/dist/extensions/agent-browser/lib/input-modes/script-child.js +0 -396
  99. package/dist/extensions/agent-browser/lib/input-modes/script-protocol.js +0 -86
  100. package/dist/extensions/agent-browser/lib/input-modes/script-types.js +0 -1
  101. package/dist/extensions/agent-browser/lib/input-modes/script-validation.js +0 -60
  102. package/dist/extensions/agent-browser/lib/input-modes/script.js +0 -108
  103. package/dist/extensions/agent-browser/lib/input-modes/semantic-action.js +0 -243
  104. package/dist/extensions/agent-browser/lib/input-modes/shared.js +0 -48
  105. package/dist/extensions/agent-browser/lib/input-modes/types.js +0 -65
  106. package/dist/extensions/agent-browser/lib/json-schema.js +0 -65
  107. package/dist/extensions/agent-browser/lib/launch-scoped-flags.js +0 -212
  108. package/dist/extensions/agent-browser/lib/managed-session-policy-lock.js +0 -165
  109. package/dist/extensions/agent-browser/lib/managed-session-posix-storage.js +0 -58
  110. package/dist/extensions/agent-browser/lib/managed-session-project-identity.js +0 -244
  111. package/dist/extensions/agent-browser/lib/managed-session-restore-context.js +0 -84
  112. package/dist/extensions/agent-browser/lib/managed-session-restore-policy.js +0 -119
  113. package/dist/extensions/agent-browser/lib/managed-session-restore-state.js +0 -83
  114. package/dist/extensions/agent-browser/lib/managed-session-restore.js +0 -212
  115. package/dist/extensions/agent-browser/lib/managed-session-snapshot-records.js +0 -277
  116. package/dist/extensions/agent-browser/lib/managed-session-snapshots.js +0 -181
  117. package/dist/extensions/agent-browser/lib/managed-session-storage.js +0 -126
  118. package/dist/extensions/agent-browser/lib/native-confirmation.js +0 -140
  119. package/dist/extensions/agent-browser/lib/native-output.js +0 -81
  120. package/dist/extensions/agent-browser/lib/orchestration/batch-stdin.js +0 -182
  121. package/dist/extensions/agent-browser/lib/orchestration/browser-run/artifact-merge.js +0 -30
  122. package/dist/extensions/agent-browser/lib/orchestration/browser-run/artifact-paths.js +0 -188
  123. package/dist/extensions/agent-browser/lib/orchestration/browser-run/browser-observation-result.js +0 -82
  124. package/dist/extensions/agent-browser/lib/orchestration/browser-run/click-dispatch.js +0 -406
  125. package/dist/extensions/agent-browser/lib/orchestration/browser-run/diagnostic-values.js +0 -31
  126. package/dist/extensions/agent-browser/lib/orchestration/browser-run/diagnostics.js +0 -240
  127. package/dist/extensions/agent-browser/lib/orchestration/browser-run/electron-observation.js +0 -203
  128. package/dist/extensions/agent-browser/lib/orchestration/browser-run/electron-text-diagnostics.js +0 -109
  129. package/dist/extensions/agent-browser/lib/orchestration/browser-run/fill-diagnostics.js +0 -119
  130. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-action-recovery.js +0 -147
  131. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-actions.js +0 -144
  132. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-content.js +0 -123
  133. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-contracts.js +0 -1
  134. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-details.js +0 -156
  135. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-electron.js +0 -187
  136. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-evidence.js +0 -39
  137. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-missing-binary.js +0 -89
  138. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-recovery.js +0 -97
  139. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-redaction.js +0 -106
  140. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-timeout.js +0 -110
  141. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result.js +0 -53
  142. package/dist/extensions/agent-browser/lib/orchestration/browser-run/index.js +0 -224
  143. package/dist/extensions/agent-browser/lib/orchestration/browser-run/interaction-diagnostics.js +0 -290
  144. package/dist/extensions/agent-browser/lib/orchestration/browser-run/managed-session-close.js +0 -167
  145. package/dist/extensions/agent-browser/lib/orchestration/browser-run/managed-session-daemon-inspection.js +0 -108
  146. package/dist/extensions/agent-browser/lib/orchestration/browser-run/managed-session-daemon-policy.js +0 -174
  147. package/dist/extensions/agent-browser/lib/orchestration/browser-run/native-helper-observation.js +0 -65
  148. package/dist/extensions/agent-browser/lib/orchestration/browser-run/observation-types.js +0 -1
  149. package/dist/extensions/agent-browser/lib/orchestration/browser-run/overlay-diagnostics.js +0 -120
  150. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare/network-page-filter.js +0 -192
  151. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare/scroll-shims.js +0 -225
  152. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare/snapshot-filter-data.js +0 -150
  153. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare/snapshot-filter.js +0 -174
  154. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare/snapshot-rendered-text.js +0 -147
  155. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare/wait-timeouts.js +0 -145
  156. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-artifacts.js +0 -159
  157. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-command.js +0 -131
  158. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-contracts.js +0 -1
  159. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-daemon.js +0 -93
  160. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-failure.js +0 -42
  161. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-guards.js +0 -242
  162. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-input.js +0 -75
  163. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-observations.js +0 -92
  164. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-page-selection.js +0 -254
  165. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-page-state.js +0 -121
  166. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-refs.js +0 -130
  167. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-resources.js +0 -114
  168. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-semantic.js +0 -121
  169. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-session-plan.js +0 -222
  170. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-timeouts.js +0 -68
  171. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare.js +0 -202
  172. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-analysis.js +0 -191
  173. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-confirmation.js +0 -152
  174. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-diagnostics.js +0 -182
  175. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-electron.js +0 -150
  176. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-lifecycle-contracts.js +0 -1
  177. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-lifecycle-phase-contracts.js +0 -1
  178. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-lifecycle-phase.js +0 -115
  179. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-lifecycle.js +0 -256
  180. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-managed-contracts.js +0 -1
  181. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-managed.js +0 -256
  182. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-native-phase-contracts.js +0 -1
  183. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-native-phase.js +0 -93
  184. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-native.js +0 -113
  185. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-navigation-contracts.js +0 -1
  186. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-navigation.js +0 -316
  187. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-ownership.js +0 -28
  188. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-page-phase-contracts.js +0 -1
  189. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-page-phase.js +0 -142
  190. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-presentation-contracts.js +0 -1
  191. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-presentation.js +0 -333
  192. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-publication-phase-contracts.js +0 -1
  193. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-publication-phase.js +0 -71
  194. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-publication.js +0 -201
  195. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-receipts.js +0 -183
  196. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-refs.js +0 -200
  197. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-tabs.js +0 -142
  198. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output.js +0 -25
  199. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prompt-guards.js +0 -50
  200. package/dist/extensions/agent-browser/lib/orchestration/browser-run/recording-receipt-reconciliation.js +0 -198
  201. package/dist/extensions/agent-browser/lib/orchestration/browser-run/recording-recovery-contracts.js +0 -1
  202. package/dist/extensions/agent-browser/lib/orchestration/browser-run/recording-recovery-presentation.js +0 -154
  203. package/dist/extensions/agent-browser/lib/orchestration/browser-run/recording-recovery.js +0 -80
  204. package/dist/extensions/agent-browser/lib/orchestration/browser-run/screenshot-capture.js +0 -14
  205. package/dist/extensions/agent-browser/lib/orchestration/browser-run/screenshot-observation.js +0 -206
  206. package/dist/extensions/agent-browser/lib/orchestration/browser-run/session-state-commands.js +0 -130
  207. package/dist/extensions/agent-browser/lib/orchestration/browser-run/session-state-electron.js +0 -212
  208. package/dist/extensions/agent-browser/lib/orchestration/browser-run/session-state-observations.js +0 -61
  209. package/dist/extensions/agent-browser/lib/orchestration/browser-run/session-state-outcomes.js +0 -187
  210. package/dist/extensions/agent-browser/lib/orchestration/browser-run/session-state-refs.js +0 -169
  211. package/dist/extensions/agent-browser/lib/orchestration/browser-run/session-state-tabs.js +0 -228
  212. package/dist/extensions/agent-browser/lib/orchestration/browser-run/session-state.js +0 -117
  213. package/dist/extensions/agent-browser/lib/orchestration/browser-run/text-visibility-diagnostics.js +0 -182
  214. package/dist/extensions/agent-browser/lib/orchestration/browser-run/timeout-diagnostics.js +0 -256
  215. package/dist/extensions/agent-browser/lib/orchestration/browser-run/timeout-progress.js +0 -108
  216. package/dist/extensions/agent-browser/lib/orchestration/browser-run/types.js +0 -1
  217. package/dist/extensions/agent-browser/lib/orchestration/code-artifact-observation.js +0 -39
  218. package/dist/extensions/agent-browser/lib/orchestration/code-image-observation.js +0 -119
  219. package/dist/extensions/agent-browser/lib/orchestration/electron-host/branch.js +0 -93
  220. package/dist/extensions/agent-browser/lib/orchestration/electron-host/cleanup-result.js +0 -58
  221. package/dist/extensions/agent-browser/lib/orchestration/electron-host/cleanup.js +0 -78
  222. package/dist/extensions/agent-browser/lib/orchestration/electron-host/contracts.js +0 -1
  223. package/dist/extensions/agent-browser/lib/orchestration/electron-host/discovery.js +0 -106
  224. package/dist/extensions/agent-browser/lib/orchestration/electron-host/index.js +0 -60
  225. package/dist/extensions/agent-browser/lib/orchestration/electron-host/policy.js +0 -86
  226. package/dist/extensions/agent-browser/lib/orchestration/electron-host/probe-collection.js +0 -68
  227. package/dist/extensions/agent-browser/lib/orchestration/electron-host/probe-data.js +0 -169
  228. package/dist/extensions/agent-browser/lib/orchestration/electron-host/probe-presentation.js +0 -182
  229. package/dist/extensions/agent-browser/lib/orchestration/electron-host/probe.js +0 -161
  230. package/dist/extensions/agent-browser/lib/orchestration/electron-host/status.js +0 -167
  231. package/dist/extensions/agent-browser/lib/orchestration/execution-queue.js +0 -98
  232. package/dist/extensions/agent-browser/lib/orchestration/extension-artifact-preflight.js +0 -211
  233. package/dist/extensions/agent-browser/lib/orchestration/extension-artifacts.js +0 -23
  234. package/dist/extensions/agent-browser/lib/orchestration/extension-attachment-replay.js +0 -99
  235. package/dist/extensions/agent-browser/lib/orchestration/extension-branch-restore.js +0 -275
  236. package/dist/extensions/agent-browser/lib/orchestration/extension-code.js +0 -280
  237. package/dist/extensions/agent-browser/lib/orchestration/extension-command-admission.js +0 -303
  238. package/dist/extensions/agent-browser/lib/orchestration/extension-command-output.js +0 -36
  239. package/dist/extensions/agent-browser/lib/orchestration/extension-command-result.js +0 -335
  240. package/dist/extensions/agent-browser/lib/orchestration/extension-command-run.js +0 -227
  241. package/dist/extensions/agent-browser/lib/orchestration/extension-command-state.js +0 -1
  242. package/dist/extensions/agent-browser/lib/orchestration/extension-electron-ownership.js +0 -204
  243. package/dist/extensions/agent-browser/lib/orchestration/extension-execution-locks.js +0 -139
  244. package/dist/extensions/agent-browser/lib/orchestration/extension-execution-queue.js +0 -24
  245. package/dist/extensions/agent-browser/lib/orchestration/extension-host-coordination.js +0 -98
  246. package/dist/extensions/agent-browser/lib/orchestration/extension-host-run.js +0 -295
  247. package/dist/extensions/agent-browser/lib/orchestration/extension-intent-replay.js +0 -41
  248. package/dist/extensions/agent-browser/lib/orchestration/extension-invocation.js +0 -7
  249. package/dist/extensions/agent-browser/lib/orchestration/extension-lifecycle.js +0 -102
  250. package/dist/extensions/agent-browser/lib/orchestration/extension-managed-ownership.js +0 -133
  251. package/dist/extensions/agent-browser/lib/orchestration/extension-observation.js +0 -120
  252. package/dist/extensions/agent-browser/lib/orchestration/extension-prompt.js +0 -180
  253. package/dist/extensions/agent-browser/lib/orchestration/extension-recording.js +0 -290
  254. package/dist/extensions/agent-browser/lib/orchestration/extension-resource-contracts.js +0 -1
  255. package/dist/extensions/agent-browser/lib/orchestration/extension-resource-replay.js +0 -269
  256. package/dist/extensions/agent-browser/lib/orchestration/extension-result-state.js +0 -113
  257. package/dist/extensions/agent-browser/lib/orchestration/extension-runtime.js +0 -146
  258. package/dist/extensions/agent-browser/lib/orchestration/extension-script-leases.js +0 -58
  259. package/dist/extensions/agent-browser/lib/orchestration/extension-tool-boundary.js +0 -62
  260. package/dist/extensions/agent-browser/lib/orchestration/extension-version-check.js +0 -54
  261. package/dist/extensions/agent-browser/lib/orchestration/input-plan-types.js +0 -1
  262. package/dist/extensions/agent-browser/lib/orchestration/input-plan.js +0 -313
  263. package/dist/extensions/agent-browser/lib/orchestration/input-redaction.js +0 -62
  264. package/dist/extensions/agent-browser/lib/orchestration/native-config.js +0 -144
  265. package/dist/extensions/agent-browser/lib/orchestration/native-root-launch.js +0 -77
  266. package/dist/extensions/agent-browser/lib/orchestration/native-session-defaults.js +0 -231
  267. package/dist/extensions/agent-browser/lib/orchestration/operation-paths.js +0 -142
  268. package/dist/extensions/agent-browser/lib/orchestration/output-file.js +0 -276
  269. package/dist/extensions/agent-browser/lib/orchestration/script-mode.js +0 -220
  270. package/dist/extensions/agent-browser/lib/owned-managed-session-context.js +0 -55
  271. package/dist/extensions/agent-browser/lib/page-target-batch.js +0 -118
  272. package/dist/extensions/agent-browser/lib/page-target-guards.js +0 -50
  273. package/dist/extensions/agent-browser/lib/page-target-navigation.js +0 -104
  274. package/dist/extensions/agent-browser/lib/page-target-validation.js +0 -90
  275. package/dist/extensions/agent-browser/lib/parsing.js +0 -30
  276. package/dist/extensions/agent-browser/lib/pi-tool-rendering.js +0 -343
  277. package/dist/extensions/agent-browser/lib/playbook.js +0 -146
  278. package/dist/extensions/agent-browser/lib/process-child.js +0 -284
  279. package/dist/extensions/agent-browser/lib/process-environment.js +0 -48
  280. package/dist/extensions/agent-browser/lib/process-errors.js +0 -23
  281. package/dist/extensions/agent-browser/lib/process-identity.js +0 -127
  282. package/dist/extensions/agent-browser/lib/process-socket-storage.js +0 -256
  283. package/dist/extensions/agent-browser/lib/process-stdout.js +0 -74
  284. package/dist/extensions/agent-browser/lib/process.js +0 -216
  285. package/dist/extensions/agent-browser/lib/prompt-artifacts.js +0 -287
  286. package/dist/extensions/agent-browser/lib/prompt-policy.js +0 -54
  287. package/dist/extensions/agent-browser/lib/read-command.js +0 -41
  288. package/dist/extensions/agent-browser/lib/read-confirmation.js +0 -162
  289. package/dist/extensions/agent-browser/lib/recording-reservations.js +0 -208
  290. package/dist/extensions/agent-browser/lib/redaction-fields.js +0 -75
  291. package/dist/extensions/agent-browser/lib/redaction-json.js +0 -149
  292. package/dist/extensions/agent-browser/lib/redaction-url.js +0 -88
  293. package/dist/extensions/agent-browser/lib/results/action-contracts.js +0 -1
  294. package/dist/extensions/agent-browser/lib/results/action-recommendations.js +0 -38
  295. package/dist/extensions/agent-browser/lib/results/artifact-contracts.js +0 -1
  296. package/dist/extensions/agent-browser/lib/results/artifact-manifest-validation.js +0 -133
  297. package/dist/extensions/agent-browser/lib/results/artifact-manifest.js +0 -173
  298. package/dist/extensions/agent-browser/lib/results/artifact-recommendations.js +0 -73
  299. package/dist/extensions/agent-browser/lib/results/categories.js +0 -152
  300. package/dist/extensions/agent-browser/lib/results/confirmation.js +0 -75
  301. package/dist/extensions/agent-browser/lib/results/contracts.js +0 -1
  302. package/dist/extensions/agent-browser/lib/results/editable-ref-evidence.js +0 -99
  303. package/dist/extensions/agent-browser/lib/results/electron-recommendations.js +0 -83
  304. package/dist/extensions/agent-browser/lib/results/envelope-decoding.js +0 -48
  305. package/dist/extensions/agent-browser/lib/results/envelope.js +0 -198
  306. package/dist/extensions/agent-browser/lib/results/evidence-contracts.js +0 -1
  307. package/dist/extensions/agent-browser/lib/results/failure-recommendations.js +0 -180
  308. package/dist/extensions/agent-browser/lib/results/network-routes.js +0 -133
  309. package/dist/extensions/agent-browser/lib/results/network.js +0 -89
  310. package/dist/extensions/agent-browser/lib/results/next-actions.js +0 -111
  311. package/dist/extensions/agent-browser/lib/results/presentation/artifact-files.js +0 -320
  312. package/dist/extensions/agent-browser/lib/results/presentation/artifact-format.js +0 -138
  313. package/dist/extensions/agent-browser/lib/results/presentation/artifact-images.js +0 -113
  314. package/dist/extensions/agent-browser/lib/results/presentation/artifact-verification.js +0 -145
  315. package/dist/extensions/agent-browser/lib/results/presentation/artifacts.js +0 -165
  316. package/dist/extensions/agent-browser/lib/results/presentation/batch-contracts.js +0 -1
  317. package/dist/extensions/agent-browser/lib/results/presentation/batch-recording.js +0 -118
  318. package/dist/extensions/agent-browser/lib/results/presentation/batch-redaction.js +0 -68
  319. package/dist/extensions/agent-browser/lib/results/presentation/batch-rendering.js +0 -135
  320. package/dist/extensions/agent-browser/lib/results/presentation/batch-step.js +0 -227
  321. package/dist/extensions/agent-browser/lib/results/presentation/batch-summary.js +0 -91
  322. package/dist/extensions/agent-browser/lib/results/presentation/batch.js +0 -123
  323. package/dist/extensions/agent-browser/lib/results/presentation/browser-profile-recovery.js +0 -54
  324. package/dist/extensions/agent-browser/lib/results/presentation/command-presenters.js +0 -216
  325. package/dist/extensions/agent-browser/lib/results/presentation/common.js +0 -81
  326. package/dist/extensions/agent-browser/lib/results/presentation/content.js +0 -119
  327. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-a11y.js +0 -67
  328. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-health.js +0 -79
  329. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-identity.js +0 -199
  330. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-logs.js +0 -75
  331. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-network-actions.js +0 -216
  332. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-network.js +0 -124
  333. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-redaction.js +0 -64
  334. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-storage.js +0 -209
  335. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-stream.js +0 -69
  336. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-summary.js +0 -222
  337. package/dist/extensions/agent-browser/lib/results/presentation/diagnostics.js +0 -124
  338. package/dist/extensions/agent-browser/lib/results/presentation/early-result.js +0 -70
  339. package/dist/extensions/agent-browser/lib/results/presentation/errors.js +0 -285
  340. package/dist/extensions/agent-browser/lib/results/presentation/input-contracts.js +0 -1
  341. package/dist/extensions/agent-browser/lib/results/presentation/large-output.js +0 -117
  342. package/dist/extensions/agent-browser/lib/results/presentation/navigation.js +0 -231
  343. package/dist/extensions/agent-browser/lib/results/presentation/notices.js +0 -75
  344. package/dist/extensions/agent-browser/lib/results/presentation/observation-contracts.js +0 -1
  345. package/dist/extensions/agent-browser/lib/results/presentation/observation-rendering.js +0 -127
  346. package/dist/extensions/agent-browser/lib/results/presentation/outcomes.js +0 -120
  347. package/dist/extensions/agent-browser/lib/results/presentation/output-completion.js +0 -77
  348. package/dist/extensions/agent-browser/lib/results/presentation/output-spill.js +0 -51
  349. package/dist/extensions/agent-browser/lib/results/presentation/registry.js +0 -145
  350. package/dist/extensions/agent-browser/lib/results/presentation/semantic-action.js +0 -104
  351. package/dist/extensions/agent-browser/lib/results/presentation/skills.js +0 -183
  352. package/dist/extensions/agent-browser/lib/results/presentation/source.js +0 -109
  353. package/dist/extensions/agent-browser/lib/results/presentation.js +0 -19
  354. package/dist/extensions/agent-browser/lib/results/recommendation-contracts.js +0 -1
  355. package/dist/extensions/agent-browser/lib/results/recording.js +0 -88
  356. package/dist/extensions/agent-browser/lib/results/recovery-actions.js +0 -118
  357. package/dist/extensions/agent-browser/lib/results/recovery-next-actions.js +0 -60
  358. package/dist/extensions/agent-browser/lib/results/selector-recovery-target.js +0 -83
  359. package/dist/extensions/agent-browser/lib/results/selector-recovery.js +0 -261
  360. package/dist/extensions/agent-browser/lib/results/snapshot-compact.js +0 -266
  361. package/dist/extensions/agent-browser/lib/results/snapshot-content.js +0 -32
  362. package/dist/extensions/agent-browser/lib/results/snapshot-high-value-controls.js +0 -240
  363. package/dist/extensions/agent-browser/lib/results/snapshot-refs.js +0 -103
  364. package/dist/extensions/agent-browser/lib/results/snapshot-segments.js +0 -383
  365. package/dist/extensions/agent-browser/lib/results/snapshot-spill.js +0 -53
  366. package/dist/extensions/agent-browser/lib/results/snapshot.js +0 -44
  367. package/dist/extensions/agent-browser/lib/results/text.js +0 -44
  368. package/dist/extensions/agent-browser/lib/runtime-args-validation.js +0 -133
  369. package/dist/extensions/agent-browser/lib/runtime-compatibility.js +0 -81
  370. package/dist/extensions/agent-browser/lib/runtime-contracts.js +0 -1
  371. package/dist/extensions/agent-browser/lib/runtime-redaction.js +0 -118
  372. package/dist/extensions/agent-browser/lib/runtime-replay-events.js +0 -144
  373. package/dist/extensions/agent-browser/lib/runtime-session-identity.js +0 -76
  374. package/dist/extensions/agent-browser/lib/runtime-session-plan.js +0 -114
  375. package/dist/extensions/agent-browser/lib/runtime-session-replay.js +0 -123
  376. package/dist/extensions/agent-browser/lib/runtime-tab-correction.js +0 -65
  377. package/dist/extensions/agent-browser/lib/runtime-timeouts.js +0 -28
  378. package/dist/extensions/agent-browser/lib/runtime.js +0 -163
  379. package/dist/extensions/agent-browser/lib/session-identity.js +0 -51
  380. package/dist/extensions/agent-browser/lib/session-page-observation.js +0 -357
  381. package/dist/extensions/agent-browser/lib/session-page-state.js +0 -353
  382. package/dist/extensions/agent-browser/lib/session-page-types.js +0 -1
  383. package/dist/extensions/agent-browser/lib/string-enum-schema.js +0 -8
  384. package/dist/extensions/agent-browser/lib/temp-artifact-budget.js +0 -81
  385. package/dist/extensions/agent-browser/lib/temp-mutation-queue.js +0 -7
  386. package/dist/extensions/agent-browser/lib/temp-root-ownership.js +0 -234
  387. package/dist/extensions/agent-browser/lib/temp-root.js +0 -211
  388. package/dist/extensions/agent-browser/lib/temp.js +0 -91
  389. package/dist/extensions/agent-browser/lib/tool-surface.js +0 -239
  390. package/dist/extensions/agent-browser/lib/upstream-version.js +0 -15
  391. package/dist/extensions/agent-browser/lib/web-search-providers.js +0 -193
  392. package/dist/extensions/agent-browser/lib/web-search-request.js +0 -102
  393. package/dist/extensions/agent-browser/lib/web-search-results.js +0 -281
  394. package/dist/extensions/agent-browser/lib/web-search-schema.js +0 -82
  395. package/dist/extensions/agent-browser/lib/web-search.js +0 -167
  396. package/dist/extensions/agent-browser/lib/webmcp-observation.js +0 -35
  397. package/dist/extensions/agent-browser/lib/windows-stock-launcher.js +0 -96
  398. package/dist/scripts/agent-browser-target.mjs +0 -23
@@ -0,0 +1,2800 @@
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 as readFile2, 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 { readFile } from "node:fs/promises";
1921
+ import { dirname, join, win32 } from "node:path";
1922
+
1923
+ // dist/extensions/agent-browser/lib/browser-execution-policy-debug.js
1924
+ import { AsyncLocalStorage } from "node:async_hooks";
1925
+ import { debuglog } from "node:util";
1926
+ var debug = debuglog("pi-agent-browser-policy");
1927
+ var policyDebugEnabled = debug.enabled;
1928
+ var attempts = policyDebugEnabled ? new AsyncLocalStorage() : void 0;
1929
+ var syscalls = /* @__PURE__ */ new Set([
1930
+ "mkdir",
1931
+ "lstat",
1932
+ "stat",
1933
+ "scandir",
1934
+ "open",
1935
+ "read",
1936
+ "write",
1937
+ "rename",
1938
+ "rmdir",
1939
+ "unlink",
1940
+ "rm",
1941
+ "kill",
1942
+ "spawn",
1943
+ "connect",
1944
+ "listen"
1945
+ ]);
1946
+ function debugPolicyFailure(stage, reason, error) {
1947
+ if (!policyDebugEnabled) {
1948
+ return;
1949
+ }
1950
+ const context = attempts?.getStore();
1951
+ const code = nativeField(error, "code");
1952
+ const syscall = nativeField(error, "syscall");
1953
+ const exit = isRecord(error) && typeof error.code === "number" && Number.isSafeInteger(error.code) ? error.code : "-";
1954
+ debug("attempt=%s phase=%s stage=%s reason=%s code=%s syscall=%s exit=%s", context?.attempt ?? 0, context?.phase ?? "standalone", stage, reason, code, syscall, exit);
1955
+ }
1956
+ function nativeField(error, field) {
1957
+ const value = isRecord(error) ? error[field] : void 0;
1958
+ if (typeof value !== "string") {
1959
+ return "-";
1960
+ }
1961
+ if (field === "code") {
1962
+ return /^(?:E[A-Z0-9]{1,24}|ABORT_ERR|ERR_[A-Z_]{1,48})$/.test(value) ? value : "unknown";
1963
+ }
1964
+ if (value.startsWith("spawn ")) {
1965
+ return "spawn";
1966
+ }
1967
+ return syscalls.has(value) ? value : "unknown";
1968
+ }
1969
+
1970
+ // dist/extensions/agent-browser/lib/process-identity.js
1971
+ var WINDOWS_PROCESS_START_IDENTITY_PREFIX = "win32-powershell-ticks-v1:";
1972
+ var POSIX_PROCESS_START_IDENTITY_PREFIX = "posix-ps-utc-v1:";
1973
+ var LINUX_PROCESS_START_IDENTITY_PREFIX = "linux-proc-boot-ticks-v1:";
1974
+ var PROCESS_START_IDENTITY_FORMATS = [
1975
+ WINDOWS_PROCESS_START_IDENTITY_PREFIX,
1976
+ POSIX_PROCESS_START_IDENTITY_PREFIX,
1977
+ LINUX_PROCESS_START_IDENTITY_PREFIX
1978
+ ];
1979
+ var PROCESS_START_IDENTITY_TIMEOUT_MS = process.platform === "win32" ? 1e4 : 5e3;
1980
+ var DEFAULT_WINDOWS_SYSTEM_ROOT = "C:\\Windows";
1981
+ var LINUX_BOOT_ID_PATH = "/proc/sys/kernel/random/boot_id";
1982
+ var LINUX_BOOT_ID_PATTERN = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
1983
+ var LINUX_STAT_START_TICKS_INDEX = 22 - 3;
1984
+ function buildProcessStartIdentityCommand(pid, platform = process.platform) {
1985
+ if (!Number.isSafeInteger(pid) || pid <= 0 || platform === "linux") {
1986
+ return void 0;
1987
+ }
1988
+ const configuredSystemRoot = process.env.SystemRoot;
1989
+ const windowsSystemRoot = configuredSystemRoot !== void 0 && configuredSystemRoot.length > 0 && win32.isAbsolute(configuredSystemRoot) ? configuredSystemRoot : DEFAULT_WINDOWS_SYSTEM_ROOT;
1990
+ return platform === "win32" ? {
1991
+ args: [
1992
+ "-NoProfile",
1993
+ "-NonInteractive",
1994
+ "-Command",
1995
+ `$ErrorActionPreference = 'Stop'; $p = $null; try { $p = [System.Diagnostics.Process]::GetProcessById(${pid}); [long]$ticks = $p.StartTime.ToUniversalTime().Ticks; if ($ticks -le 0) { throw 'Process start ticks unavailable' }; [Console]::Out.WriteLine("${WINDOWS_PROCESS_START_IDENTITY_PREFIX}" + $ticks.ToString([Globalization.CultureInfo]::InvariantCulture)) } finally { if ($null -ne $p) { $p.Dispose() } }`
1996
+ ],
1997
+ file: win32.join(windowsSystemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
1998
+ } : {
1999
+ args: ["-p", String(pid), "-o", "lstart="],
2000
+ env: { ...process.env, TZ: "UTC0", LC_ALL: "C" },
2001
+ file: platform === "android" ? join(dirname(process.execPath), "ps") : "/bin/ps"
2002
+ };
2003
+ }
2004
+ function buildProcessStartIdentityCommands(pid, platform = process.platform) {
2005
+ const primary = buildProcessStartIdentityCommand(pid, platform);
2006
+ if (!primary) {
2007
+ return [];
2008
+ }
2009
+ return platform === "win32" ? [primary] : [
2010
+ primary,
2011
+ ...platform === "android" ? [
2012
+ { ...primary, file: "/bin/ps" },
2013
+ { ...primary, file: "/usr/bin/ps" }
2014
+ ] : [
2015
+ { ...primary, file: "/usr/bin/ps" },
2016
+ { ...primary, file: "ps" }
2017
+ ]
2018
+ ];
2019
+ }
2020
+ function normalizeProcessStartIdentity(stdout) {
2021
+ const trimmed = stdout.trim();
2022
+ if (trimmed.length === 0 || trimmed.includes("\0") || /[\r\n]/.test(trimmed)) {
2023
+ return void 0;
2024
+ }
2025
+ return trimmed.replace(/\s+/g, " ");
2026
+ }
2027
+ var currentProcessStartIdentityPromise;
2028
+ var currentProcessStartIdentity;
2029
+ function debugIdentityBudget(budget) {
2030
+ debugPolicyFailure("probe.budget", budget?.signal?.aborted === true ? "cancelled" : "deadline");
2031
+ }
2032
+ async function executeProcessStartIdentityCommand(command, budget = {}) {
2033
+ if (budget.signal?.aborted === true || budget.deadline !== void 0 && performance.now() >= budget.deadline) {
2034
+ debugIdentityBudget(budget);
2035
+ return void 0;
2036
+ }
2037
+ const timeout = Math.max(1, Math.ceil(Math.min(PROCESS_START_IDENTITY_TIMEOUT_MS, (budget.deadline ?? Infinity) - performance.now())));
2038
+ return await new Promise((resolve3) => {
2039
+ execFile(command.file, command.args, { env: command.env, timeout, signal: budget.signal }, (error, stdout) => {
2040
+ const identity = error ? void 0 : normalizeProcessStartIdentity(stdout);
2041
+ if (identity === void 0) {
2042
+ debugPolicyFailure("probe.execute", error ? "native-error" : "invalid-output", error);
2043
+ }
2044
+ resolve3(identity);
2045
+ });
2046
+ });
2047
+ }
2048
+ async function resolveProcessStartIdentityFromCommands(commands, execute = executeProcessStartIdentityCommand) {
2049
+ for (const command of commands) {
2050
+ const identity = await execute(command);
2051
+ if (identity !== void 0 && identity.length > 0) {
2052
+ return identity;
2053
+ }
2054
+ }
2055
+ return void 0;
2056
+ }
2057
+ async function readLinuxProcfsText(path, budget) {
2058
+ if (identityBudgetExpired(budget)) {
2059
+ debugIdentityBudget(budget);
2060
+ return void 0;
2061
+ }
2062
+ try {
2063
+ return await readFile(path, { encoding: "latin1", signal: budget.signal });
2064
+ } catch (error) {
2065
+ debugPolicyFailure("probe.read", "native-error", error);
2066
+ return void 0;
2067
+ }
2068
+ }
2069
+ async function readLinuxBootId(budget) {
2070
+ const bootId = (await readLinuxProcfsText(LINUX_BOOT_ID_PATH, budget))?.replace(/\n$/, "");
2071
+ if (bootId === void 0 || !LINUX_BOOT_ID_PATTERN.test(bootId)) {
2072
+ debugPolicyFailure("probe.boot-id", bootId === void 0 ? "unavailable" : "invalid-output");
2073
+ return void 0;
2074
+ }
2075
+ return bootId;
2076
+ }
2077
+ function parseLinuxStartTicks(stat4, pid) {
2078
+ const header = `${String(pid)} (`;
2079
+ const commEnd = stat4.lastIndexOf(")");
2080
+ if (!stat4.startsWith(header) || commEnd < header.length || stat4[commEnd + 1] !== " ") {
2081
+ return void 0;
2082
+ }
2083
+ const ticks = stat4.slice(commEnd + 2).replace(/\n$/, "").split(" ").at(LINUX_STAT_START_TICKS_INDEX);
2084
+ return ticks !== void 0 && /^[0-9]+$/.test(ticks) ? ticks : void 0;
2085
+ }
2086
+ async function readLinuxProcessStartIdentity(pid, budget = {}) {
2087
+ if (!Number.isSafeInteger(pid) || pid <= 0) {
2088
+ return void 0;
2089
+ }
2090
+ const bootId = await readLinuxBootId(budget);
2091
+ if (bootId === void 0) {
2092
+ return void 0;
2093
+ }
2094
+ const stat4 = await readLinuxProcfsText(`/proc/${String(pid)}/stat`, budget);
2095
+ if (stat4 === void 0) {
2096
+ return void 0;
2097
+ }
2098
+ const ticks = parseLinuxStartTicks(stat4, pid);
2099
+ if (ticks === void 0) {
2100
+ debugPolicyFailure("probe.stat", "invalid-output");
2101
+ return void 0;
2102
+ }
2103
+ return `${LINUX_PROCESS_START_IDENTITY_PREFIX}${bootId}:${ticks}`;
2104
+ }
2105
+ async function readUncachedProcessStartIdentity(pid, platform, budget) {
2106
+ if (platform === "linux") {
2107
+ return await readLinuxProcessStartIdentity(pid, budget);
2108
+ }
2109
+ const identity = await resolveProcessStartIdentityFromCommands(buildProcessStartIdentityCommands(pid, platform), (command) => executeProcessStartIdentityCommand(command, budget));
2110
+ return identity === void 0 || platform === "win32" ? identity : `${POSIX_PROCESS_START_IDENTITY_PREFIX}${identity}`;
2111
+ }
2112
+ function identityBudgetExpired(budget) {
2113
+ return budget?.signal?.aborted === true || budget?.deadline !== void 0 && performance.now() >= budget.deadline;
2114
+ }
2115
+ async function readProcessStartIdentity(pid, platform = process.platform, budget) {
2116
+ if (identityBudgetExpired(budget)) {
2117
+ debugIdentityBudget(budget);
2118
+ return void 0;
2119
+ }
2120
+ if (pid !== process.pid || platform !== process.platform) {
2121
+ return await readUncachedProcessStartIdentity(pid, platform, budget);
2122
+ }
2123
+ if (currentProcessStartIdentity !== void 0 && currentProcessStartIdentity.length > 0) {
2124
+ return currentProcessStartIdentity;
2125
+ }
2126
+ if (budget) {
2127
+ const identity = await readUncachedProcessStartIdentity(pid, platform, budget);
2128
+ if (identity !== void 0 && identity.length > 0) {
2129
+ currentProcessStartIdentity = identity;
2130
+ }
2131
+ return identity;
2132
+ }
2133
+ return await readCachedProcessStartIdentity(pid, platform);
2134
+ }
2135
+ async function readCachedProcessStartIdentity(pid, platform) {
2136
+ currentProcessStartIdentityPromise ??= readUncachedProcessStartIdentity(pid, platform).then((identity) => {
2137
+ if (identity === void 0 || identity.length === 0) {
2138
+ currentProcessStartIdentityPromise = void 0;
2139
+ } else {
2140
+ currentProcessStartIdentity = identity;
2141
+ }
2142
+ return identity;
2143
+ });
2144
+ return await currentProcessStartIdentityPromise;
2145
+ }
2146
+ function processStartIdentitiesMatch(recorded, current) {
2147
+ const format = PROCESS_START_IDENTITY_FORMATS.find((prefix) => current.startsWith(prefix));
2148
+ if (format === void 0 || !recorded.startsWith(format)) {
2149
+ return void 0;
2150
+ }
2151
+ return recorded === current;
2152
+ }
2153
+
2154
+ // dist/extensions/agent-browser/lib/process-errors.js
2155
+ function getErrorCode(error) {
2156
+ return isRecord(error) && typeof error.code === "string" ? error.code : void 0;
2157
+ }
2158
+
2159
+ // dist/extensions/agent-browser/lib/temp-root-ownership.js
2160
+ var TEMP_ROOT_MARKER_FILE_NAME = ".pi-agent-browser-owner.json";
2161
+ var TEMP_ROOT_MARKER_KIND = "pi-agent-browser-temp-root";
2162
+ var TEMP_ROOT_MARKER_VERSION = 2;
2163
+ function getCurrentProcessUid() {
2164
+ return typeof process.getuid === "function" ? process.getuid() : void 0;
2165
+ }
2166
+ function isPositiveFiniteNumber(value) {
2167
+ return typeof value === "number" && Number.isFinite(value) && value > 0;
2168
+ }
2169
+ function isProtectedTempChildName(value) {
2170
+ if (typeof value !== "string") {
2171
+ return false;
2172
+ }
2173
+ if (value === "" || value === "." || value === ".." || value === TEMP_ROOT_MARKER_FILE_NAME) {
2174
+ return false;
2175
+ }
2176
+ if (value.includes("/") || value.includes("\\")) {
2177
+ return false;
2178
+ }
2179
+ return basename(value) === value;
2180
+ }
2181
+ function isTempRootOwnershipRecord(value) {
2182
+ if (!isRecord(value)) {
2183
+ return false;
2184
+ }
2185
+ if (value.kind !== TEMP_ROOT_MARKER_KIND || value.version !== TEMP_ROOT_MARKER_VERSION) {
2186
+ return false;
2187
+ }
2188
+ if (!isPositiveFiniteNumber(value.createdAtMs)) {
2189
+ return false;
2190
+ }
2191
+ return validLeaseAndProcess(value) && validOwnershipAndChildren(value);
2192
+ }
2193
+ function validLeaseAndProcess(value) {
2194
+ if (value.leaseUpdatedAtMs !== void 0 && !isPositiveFiniteNumber(value.leaseUpdatedAtMs)) {
2195
+ return false;
2196
+ }
2197
+ if (value.ownerPid !== void 0 && (typeof value.ownerPid !== "number" || !Number.isSafeInteger(value.ownerPid) || value.ownerPid <= 0)) {
2198
+ return false;
2199
+ }
2200
+ return value.ownerProcessStartIdentity === void 0 || typeof value.ownerProcessStartIdentity === "string" && value.ownerProcessStartIdentity.trim() !== "";
2201
+ }
2202
+ function validOwnershipAndChildren(value) {
2203
+ if (value.ownerUid !== void 0 && (typeof value.ownerUid !== "number" || !Number.isSafeInteger(value.ownerUid) || value.ownerUid < 0)) {
2204
+ return false;
2205
+ }
2206
+ if (value.protectedChildNames === void 0) {
2207
+ return true;
2208
+ }
2209
+ if (!Array.isArray(value.protectedChildNames)) {
2210
+ return false;
2211
+ }
2212
+ const names = value.protectedChildNames;
2213
+ return names.every(isProtectedTempChildName);
2214
+ }
2215
+ async function readTempRootOwnershipMarker(tempRoot) {
2216
+ try {
2217
+ const markerText = await readFile2(join2(tempRoot, TEMP_ROOT_MARKER_FILE_NAME), "utf8");
2218
+ const parsed = JSON.parse(markerText);
2219
+ return isTempRootOwnershipRecord(parsed) ? parsed : void 0;
2220
+ } catch {
2221
+ return void 0;
2222
+ }
2223
+ }
2224
+ function getPersistedProtectedChildPaths(tempRoot, ownershipMarker) {
2225
+ const normalizedTempRoot = resolve(tempRoot);
2226
+ return new Set((ownershipMarker?.protectedChildNames ?? []).map((childName) => resolve(join2(normalizedTempRoot, childName))));
2227
+ }
2228
+ async function writeTempRootOwnershipMarkerRecord(tempRoot, markerRecord, options = {}) {
2229
+ const markerPath = join2(tempRoot, TEMP_ROOT_MARKER_FILE_NAME);
2230
+ await writeFile(markerPath, JSON.stringify(markerRecord, null, 2), {
2231
+ encoding: "utf8",
2232
+ flag: options.flag,
2233
+ mode: 384
2234
+ });
2235
+ await chmod(markerPath, 384).catch(() => void 0);
2236
+ return markerPath;
2237
+ }
2238
+ async function getExistingProtectedChildren(tempRoot, protectedChildren) {
2239
+ const normalizedTempRoot = resolve(tempRoot);
2240
+ const existingChildren = /* @__PURE__ */ new Set();
2241
+ for (const path of protectedChildren) {
2242
+ const normalizedPath = resolve(path);
2243
+ if (dirname2(normalizedPath) !== normalizedTempRoot) {
2244
+ continue;
2245
+ }
2246
+ if (
2247
+ // Scan in bounded sequence instead of opening an unbounded number of filesystem requests.
2248
+ // oxlint-disable-next-line no-await-in-loop
2249
+ await stat(normalizedPath).then((stats) => stats.isDirectory(), () => false)
2250
+ ) {
2251
+ existingChildren.add(normalizedPath);
2252
+ }
2253
+ }
2254
+ return existingChildren;
2255
+ }
2256
+ async function removeTempRootChildrenExcept(tempRoot, protectedChildren) {
2257
+ const entries = await readdir(tempRoot, { withFileTypes: true }).catch(() => []);
2258
+ await Promise.all(entries.map(async (entry) => {
2259
+ if (entry.name === TEMP_ROOT_MARKER_FILE_NAME) {
2260
+ return;
2261
+ }
2262
+ const entryPath = join2(tempRoot, entry.name);
2263
+ if (protectedChildren.has(resolve(entryPath))) {
2264
+ return;
2265
+ }
2266
+ await rm(entryPath, { force: true, recursive: true }).catch(() => void 0);
2267
+ }));
2268
+ }
2269
+ async function getProcessStartIdentity(pid) {
2270
+ return pid === void 0 ? void 0 : await readProcessStartIdentity(pid);
2271
+ }
2272
+ async function writeSecureTempRootOwnershipMarker(tempRoot, options = {}) {
2273
+ const createdAtMs = options.createdAtMs ?? Date.now();
2274
+ const ownerPid = options.ownerPid ?? process.pid;
2275
+ const markerRecord = {
2276
+ createdAtMs,
2277
+ kind: TEMP_ROOT_MARKER_KIND,
2278
+ leaseUpdatedAtMs: options.leaseUpdatedAtMs ?? createdAtMs,
2279
+ ownerPid,
2280
+ ownerProcessStartIdentity: options.ownerProcessStartIdentity ?? await getProcessStartIdentity(ownerPid),
2281
+ ownerUid: getCurrentProcessUid(),
2282
+ version: TEMP_ROOT_MARKER_VERSION
2283
+ };
2284
+ return await writeTempRootOwnershipMarkerRecord(tempRoot, markerRecord, { flag: "wx" });
2285
+ }
2286
+ async function refreshSecureTempRootLease(tempRoot) {
2287
+ const ownershipMarker = await readTempRootOwnershipMarker(tempRoot);
2288
+ if (!ownershipMarker) {
2289
+ return;
2290
+ }
2291
+ if (ownershipMarker.ownerPid !== process.pid) {
2292
+ return;
2293
+ }
2294
+ const currentUid = getCurrentProcessUid();
2295
+ if (currentUid !== void 0 && ownershipMarker.ownerUid !== void 0 && ownershipMarker.ownerUid !== currentUid) {
2296
+ return;
2297
+ }
2298
+ const currentProcessStartIdentity2 = await getProcessStartIdentity(process.pid);
2299
+ if (ownershipMarker.ownerProcessStartIdentity !== void 0 && currentProcessStartIdentity2 !== void 0) {
2300
+ const identitiesMatch = processStartIdentitiesMatch(ownershipMarker.ownerProcessStartIdentity, currentProcessStartIdentity2);
2301
+ if (identitiesMatch !== true) {
2302
+ return;
2303
+ }
2304
+ }
2305
+ const refreshedMarker = {
2306
+ ...ownershipMarker,
2307
+ leaseUpdatedAtMs: Date.now(),
2308
+ ownerPid: process.pid,
2309
+ ownerProcessStartIdentity: currentProcessStartIdentity2 ?? ownershipMarker.ownerProcessStartIdentity,
2310
+ ownerUid: currentUid,
2311
+ version: TEMP_ROOT_MARKER_VERSION
2312
+ };
2313
+ await writeTempRootOwnershipMarkerRecord(tempRoot, refreshedMarker);
2314
+ }
2315
+ async function getMarkerOwnerLiveness(ownershipMarker) {
2316
+ const pid = ownershipMarker.ownerPid;
2317
+ if (pid === void 0) {
2318
+ return "unknown";
2319
+ }
2320
+ try {
2321
+ process.kill(pid, 0);
2322
+ } catch (error) {
2323
+ const code = getErrorCode(error);
2324
+ if (code === "ESRCH") {
2325
+ return "dead";
2326
+ }
2327
+ if (code !== "EPERM") {
2328
+ return "unknown";
2329
+ }
2330
+ }
2331
+ const currentProcessStartIdentity2 = await getProcessStartIdentity(pid);
2332
+ if (ownershipMarker.ownerProcessStartIdentity === void 0 || currentProcessStartIdentity2 === void 0) {
2333
+ return "unknown";
2334
+ }
2335
+ const identitiesMatch = processStartIdentitiesMatch(ownershipMarker.ownerProcessStartIdentity, currentProcessStartIdentity2);
2336
+ if (identitiesMatch === void 0) {
2337
+ return "unknown";
2338
+ }
2339
+ return identitiesMatch ? "alive" : "dead";
2340
+ }
2341
+
2342
+ // dist/extensions/agent-browser/lib/temp-root.js
2343
+ var TEMP_ROOT_PREFIX = "pi-agent-browser-";
2344
+ var STALE_TEMP_ROOT_MAX_AGE_MS = 24 * 60 * 60 * 1e3;
2345
+ var STALE_TEMP_ROOT_BATCH_SIZE = 8;
2346
+ var lastTempGcName;
2347
+ var sessionTempRootPromise;
2348
+ var exitCleanupRegistered = false;
2349
+ var ownedTempRoots = /* @__PURE__ */ new Set();
2350
+ var protectedTempChildren = /* @__PURE__ */ new Set();
2351
+ function markerMatchesUid(marker, uid) {
2352
+ return uid === void 0 || marker.ownerUid === void 0 || marker.ownerUid === uid;
2353
+ }
2354
+ async function pruneTempRoot(path, currentUid, cutoffTime) {
2355
+ const marker = await readTempRootOwnershipMarker(path);
2356
+ if (!marker || !markerMatchesUid(marker, currentUid)) {
2357
+ return;
2358
+ }
2359
+ if ((marker.leaseUpdatedAtMs ?? marker.createdAtMs) >= cutoffTime) {
2360
+ return;
2361
+ }
2362
+ if (await getMarkerOwnerLiveness(marker) !== "dead") {
2363
+ return;
2364
+ }
2365
+ const stats = await stat2(path).catch(() => void 0);
2366
+ if (stats?.isDirectory() !== true) {
2367
+ return;
2368
+ }
2369
+ const protectedChildren = await getExistingProtectedChildren(path, getPersistedProtectedChildPaths(path, marker));
2370
+ if (protectedChildren.size > 0) {
2371
+ await removeTempRootChildrenExcept(path, protectedChildren);
2372
+ return;
2373
+ }
2374
+ await rm2(path, { force: true, recursive: true }).catch(() => {
2375
+ });
2376
+ }
2377
+ async function pruneStaleTempRoots(currentTempRoot) {
2378
+ const entries = await readdir2(tmpdir(), { withFileTypes: true }).catch(() => []);
2379
+ const cutoffTime = Date.now() - STALE_TEMP_ROOT_MAX_AGE_MS;
2380
+ const currentUid = getCurrentProcessUid();
2381
+ const candidates = entries.filter((entry) => entry.isDirectory() && entry.name.startsWith(TEMP_ROOT_PREFIX)).map((entry) => entry.name).sort();
2382
+ if (candidates.length === 0) {
2383
+ return;
2384
+ }
2385
+ const previousName = lastTempGcName;
2386
+ const start = previousName === void 0 ? randomInt(candidates.length) : Math.max(0, candidates.findIndex((name) => name > previousName));
2387
+ const batch = Array.from({ length: Math.min(STALE_TEMP_ROOT_BATCH_SIZE, candidates.length) }, (_, offset) => candidates[(start + offset) % candidates.length]);
2388
+ lastTempGcName = batch.at(-1);
2389
+ await Promise.all(batch.map(async (name) => {
2390
+ const path = join3(tmpdir(), name);
2391
+ if (path !== currentTempRoot) {
2392
+ await pruneTempRoot(path, currentUid, cutoffTime);
2393
+ }
2394
+ }));
2395
+ }
2396
+ function getProtectedChildrenForRoot(tempRoot) {
2397
+ const normalizedTempRoot = resolve2(tempRoot);
2398
+ return new Set([...protectedTempChildren].filter((path) => dirname3(path) === normalizedTempRoot && existsSync(path)));
2399
+ }
2400
+ function removeTempRootChildrenExceptSync(tempRoot, protectedChildren) {
2401
+ for (const entry of readdirSync(tempRoot, { withFileTypes: true })) {
2402
+ if (entry.name === TEMP_ROOT_MARKER_FILE_NAME) {
2403
+ continue;
2404
+ }
2405
+ const entryPath = join3(tempRoot, entry.name);
2406
+ if (protectedChildren.has(resolve2(entryPath))) {
2407
+ continue;
2408
+ }
2409
+ rmSync(entryPath, { force: true, recursive: true });
2410
+ }
2411
+ }
2412
+ function registerExitCleanup() {
2413
+ if (exitCleanupRegistered) {
2414
+ return;
2415
+ }
2416
+ exitCleanupRegistered = true;
2417
+ process.once("exit", () => {
2418
+ for (const tempRoot of ownedTempRoots) {
2419
+ try {
2420
+ const protectedChildren = getProtectedChildrenForRoot(tempRoot);
2421
+ if (protectedChildren.size === 0) {
2422
+ rmSync(tempRoot, { force: true, recursive: true });
2423
+ } else {
2424
+ removeTempRootChildrenExceptSync(tempRoot, protectedChildren);
2425
+ }
2426
+ } catch {
2427
+ }
2428
+ }
2429
+ });
2430
+ }
2431
+ async function allocateSessionTempRoot() {
2432
+ const tempRoot = await mkdtemp(join3(tmpdir(), TEMP_ROOT_PREFIX));
2433
+ try {
2434
+ await chmod2(tempRoot, 448).catch(() => {
2435
+ });
2436
+ await writeSecureTempRootOwnershipMarker(tempRoot);
2437
+ ownedTempRoots.add(tempRoot);
2438
+ registerExitCleanup();
2439
+ return tempRoot;
2440
+ } catch (error) {
2441
+ await rm2(tempRoot, { force: true, recursive: true }).catch(() => {
2442
+ });
2443
+ throw error;
2444
+ }
2445
+ }
2446
+ async function getSessionTempRoot() {
2447
+ sessionTempRootPromise ??= allocateSessionTempRoot().catch((error) => {
2448
+ sessionTempRootPromise = void 0;
2449
+ throw error;
2450
+ });
2451
+ const tempRoot = await sessionTempRootPromise;
2452
+ await refreshSecureTempRootLease(tempRoot).catch(() => {
2453
+ });
2454
+ await pruneStaleTempRoots(tempRoot).catch(() => {
2455
+ });
2456
+ return tempRoot;
2457
+ }
2458
+
2459
+ // dist/extensions/agent-browser/lib/temp-artifact-budget.js
2460
+ import { readdir as readdir3, rm as rm3, stat as stat3 } from "node:fs/promises";
2461
+ import { join as join4 } from "node:path";
2462
+ var DEFAULT_MAX_BYTES = 32 * 1024 * 1024;
2463
+ function getTempArtifactByteLength(content) {
2464
+ return typeof content === "string" ? Buffer.byteLength(content) : content.byteLength;
2465
+ }
2466
+ async function listArtifactFiles(directory, excludedNames = /* @__PURE__ */ new Set()) {
2467
+ const entries = await readdir3(directory, { withFileTypes: true }).catch(() => []);
2468
+ const files = [];
2469
+ const candidates = entries.filter((entry) => entry.isFile() && !excludedNames.has(entry.name));
2470
+ for (let index = 0; index < candidates.length; index += 4) {
2471
+ const batch = await Promise.all(candidates.slice(index, index + 4).map(async (entry) => {
2472
+ const path = join4(directory, entry.name);
2473
+ const stats = await stat3(path).catch(() => void 0);
2474
+ return stats?.isFile() === true ? { mtimeMs: stats.mtimeMs, path, size: stats.size } : void 0;
2475
+ }));
2476
+ for (const file of batch) {
2477
+ if (file !== void 0) {
2478
+ files.push(file);
2479
+ }
2480
+ }
2481
+ }
2482
+ return files;
2483
+ }
2484
+ function getSecureTempRootMaxBytes(env = process.env) {
2485
+ return parsePositiveInteger(env.PI_AGENT_BROWSER_TEMP_ROOT_MAX_BYTES) ?? DEFAULT_MAX_BYTES;
2486
+ }
2487
+ function getPersistentSessionArtifactMaxBytes(env = process.env) {
2488
+ if (env.PI_AGENT_BROWSER_SESSION_ARTIFACT_MAX_BYTES?.trim() === "0") {
2489
+ return 0;
2490
+ }
2491
+ return parsePositiveInteger(env.PI_AGENT_BROWSER_SESSION_ARTIFACT_MAX_BYTES) ?? DEFAULT_MAX_BYTES;
2492
+ }
2493
+ async function assertSecureTempRootBudget(tempRoot, additionalBytes) {
2494
+ if (additionalBytes <= 0) {
2495
+ return;
2496
+ }
2497
+ const files = await listArtifactFiles(tempRoot, /* @__PURE__ */ new Set([".pi-agent-browser-owner.json"]));
2498
+ const currentBytes = files.reduce((total, file) => total + file.size, 0);
2499
+ const maxBytes = getSecureTempRootMaxBytes();
2500
+ const nextBytes = currentBytes + additionalBytes;
2501
+ if (nextBytes > maxBytes) {
2502
+ throw new Error(`pi-agent-browser temp spill budget exceeded (${nextBytes} bytes > ${maxBytes} byte limit).`);
2503
+ }
2504
+ }
2505
+ async function prunePersistentSessionArtifactsToBudget(sessionArtifactDir, additionalBytes, protectedPaths) {
2506
+ if (additionalBytes <= 0) {
2507
+ return [];
2508
+ }
2509
+ const maxBytes = getPersistentSessionArtifactMaxBytes();
2510
+ if (maxBytes === 0) {
2511
+ return [];
2512
+ }
2513
+ const files = await listArtifactFiles(sessionArtifactDir);
2514
+ let totalBytes = files.reduce((total, file) => total + file.size, 0);
2515
+ if (totalBytes + additionalBytes <= maxBytes) {
2516
+ return [];
2517
+ }
2518
+ const evictedArtifacts = [];
2519
+ files.sort((left, right) => {
2520
+ const time = left.mtimeMs - right.mtimeMs;
2521
+ return time === 0 ? left.path.localeCompare(right.path) : time;
2522
+ });
2523
+ for (const file of files) {
2524
+ if (protectedPaths.has(file.path)) {
2525
+ continue;
2526
+ }
2527
+ const removed = await rm3(file.path, { force: true }).then(() => true, () => false);
2528
+ if (!removed) {
2529
+ continue;
2530
+ }
2531
+ evictedArtifacts.push({ mtimeMs: file.mtimeMs, path: file.path, sizeBytes: file.size });
2532
+ totalBytes -= file.size;
2533
+ if (totalBytes + additionalBytes <= maxBytes) {
2534
+ return evictedArtifacts;
2535
+ }
2536
+ }
2537
+ throw new Error(`pi-agent-browser persisted spill budget exceeded (${totalBytes + additionalBytes} bytes > ${maxBytes} byte limit).`);
2538
+ }
2539
+
2540
+ // dist/extensions/agent-browser/lib/temp.js
2541
+ async function ensurePersistentSessionArtifactDir(store) {
2542
+ const rootDir = join5(store.sessionDir, ".pi-agent-browser-artifacts");
2543
+ const sessionDir = join5(rootDir, store.sessionId);
2544
+ await mkdir(rootDir, { recursive: true, mode: 448 });
2545
+ await chmod3(rootDir, 448).catch(() => {
2546
+ });
2547
+ await mkdir(sessionDir, { recursive: true, mode: 448 });
2548
+ await chmod3(sessionDir, 448).catch(() => {
2549
+ });
2550
+ return sessionDir;
2551
+ }
2552
+ async function openSecureTempFile(prefix, suffix) {
2553
+ const tempRoot = await getSessionTempRoot();
2554
+ const path = join5(tempRoot, `${prefix}-${randomBytes(8).toString("hex")}${suffix}`);
2555
+ const fileHandle = await open(path, "wx", 384);
2556
+ return { fileHandle, path };
2557
+ }
2558
+ async function writeSecureTempChunk(options) {
2559
+ const { content, fileHandle, path } = options;
2560
+ await enqueueTempMutation(async () => {
2561
+ const tempRoot = dirname4(path);
2562
+ await refreshSecureTempRootLease(tempRoot).catch(() => {
2563
+ });
2564
+ await assertSecureTempRootBudget(tempRoot, getTempArtifactByteLength(content));
2565
+ await fileHandle.appendFile(content);
2566
+ });
2567
+ }
2568
+ async function writeSecureTempFile(options) {
2569
+ const { content, prefix, suffix } = options;
2570
+ const { fileHandle, path } = await openSecureTempFile(prefix, suffix);
2571
+ try {
2572
+ await writeSecureTempChunk({ content, fileHandle, path });
2573
+ } catch (error) {
2574
+ await rm4(path, { force: true }).catch(() => {
2575
+ });
2576
+ throw error;
2577
+ } finally {
2578
+ await fileHandle.close();
2579
+ }
2580
+ return path;
2581
+ }
2582
+ async function writePersistentSessionArtifactFile(options) {
2583
+ const { content, prefix, store, suffix } = options;
2584
+ return await enqueueTempMutation(async () => {
2585
+ const artifactDir = await ensurePersistentSessionArtifactDir(store);
2586
+ const evictedArtifacts = await prunePersistentSessionArtifactsToBudget(artifactDir, getTempArtifactByteLength(content), new Set((store.protectedPaths ?? []).filter((path2) => dirname4(path2) === artifactDir)));
2587
+ const path = join5(artifactDir, `${prefix}-${randomBytes(8).toString("hex")}${suffix}`);
2588
+ const fileHandle = await open(path, "wx", 384);
2589
+ try {
2590
+ await fileHandle.writeFile(content);
2591
+ } catch (error) {
2592
+ await rm4(path, { force: true }).catch(() => {
2593
+ });
2594
+ throw error;
2595
+ } finally {
2596
+ await fileHandle.close().catch(() => {
2597
+ });
2598
+ }
2599
+ return { evictedArtifacts, path };
2600
+ });
2601
+ }
2602
+
2603
+ // dist/extensions/agent-browser/lib/results/artifact-manifest.js
2604
+ function isPendingRecordingCommand(command, subcommand, kind) {
2605
+ return command === "record" && (subcommand === "start" || subcommand === "restart") && kind === "video";
2606
+ }
2607
+ function isPendingRecordingArtifact(artifact) {
2608
+ return artifact.recordingState === "openRecording" || artifact.status === "pending" || artifact.status === void 0 && isPendingRecordingCommand(artifact.command, artifact.subcommand, artifact.kind);
2609
+ }
2610
+ var SESSION_ARTIFACT_MANIFEST_VERSION = 1;
2611
+ var SESSION_ARTIFACT_MANIFEST_MAX_ENTRIES_ENV = "PI_AGENT_BROWSER_SESSION_ARTIFACT_MANIFEST_MAX_ENTRIES";
2612
+ var DEFAULT_SESSION_ARTIFACT_MANIFEST_MAX_ENTRIES = 100;
2613
+ function parsePositiveSafeInteger(value) {
2614
+ if (value === void 0) {
2615
+ return void 0;
2616
+ }
2617
+ const parsed = Number(value);
2618
+ if (!Number.isSafeInteger(parsed) || parsed <= 0) {
2619
+ return void 0;
2620
+ }
2621
+ return parsed;
2622
+ }
2623
+ function getSessionArtifactManifestMaxEntries(env = process.env) {
2624
+ return parsePositiveSafeInteger(env[SESSION_ARTIFACT_MANIFEST_MAX_ENTRIES_ENV]) ?? DEFAULT_SESSION_ARTIFACT_MANIFEST_MAX_ENTRIES;
2625
+ }
2626
+ function buildEvictedSessionArtifactEntries(evictedArtifacts, nowMs) {
2627
+ return evictedArtifacts.map((artifact) => ({
2628
+ createdAtMs: artifact.mtimeMs,
2629
+ evictedAtMs: nowMs,
2630
+ kind: "spill",
2631
+ path: artifact.path,
2632
+ retentionState: "evicted",
2633
+ sizeBytes: artifact.sizeBytes,
2634
+ storageScope: "persistent-session"
2635
+ }));
2636
+ }
2637
+ function formatSessionArtifactRetentionSummary(manifest) {
2638
+ const ephemeralCount = manifest.entries.filter((entry) => entry.retentionState === "ephemeral").length;
2639
+ const missingCount = manifest.entries.filter((entry) => entry.retentionState === "missing").length;
2640
+ const parts = [`${manifest.liveCount} live`, `${manifest.evictedCount} evicted`];
2641
+ if (ephemeralCount > 0) {
2642
+ parts.push(`${ephemeralCount} ephemeral`);
2643
+ }
2644
+ if (missingCount > 0) {
2645
+ parts.push(`${missingCount} missing`);
2646
+ }
2647
+ return `Session artifacts: ${parts.join(", ")} (${manifest.entries.length}/${manifest.maxEntries} recent).`;
2648
+ }
2649
+ function getSessionArtifactManifestEntryKey(entry) {
2650
+ const pathKey = entry.storageScope === "explicit-path" && entry.absolutePath !== void 0 && entry.absolutePath.length > 0 ? `${entry.storageScope}:${entry.absolutePath}` : `${entry.storageScope}:${entry.path}`;
2651
+ const recordingSessionKey = entry.command === "record" && entry.kind === "video" && entry.session !== void 0 && entry.session.length > 0 ? getAgentBrowserSessionIdentityKey(entry.session, entry.namespace) : void 0;
2652
+ return recordingSessionKey !== void 0 && recordingSessionKey.length > 0 ? `${pathKey}\0${recordingSessionKey}` : pathKey;
2653
+ }
2654
+ function getSupersededRecordingKeys(candidates, entry, key) {
2655
+ if (entry.command !== "record" || entry.kind !== "video") {
2656
+ return [];
2657
+ }
2658
+ const entrySessionKey = entry.session !== void 0 && entry.session.length > 0 ? getAgentBrowserSessionIdentityKey(entry.session, entry.namespace) : void 0;
2659
+ return [...candidates].filter(([candidateKey, candidate]) => {
2660
+ const sameRecordingSession = entrySessionKey === void 0 ? candidate.session === void 0 : candidate.session !== void 0 && getAgentBrowserSessionIdentityKey(candidate.session, candidate.namespace) === entrySessionKey;
2661
+ return candidateKey !== key && sameRecordingSession && candidate.kind === "video" && isPendingRecordingArtifact(candidate);
2662
+ }).map(([candidateKey]) => candidateKey);
2663
+ }
2664
+ function mergeManifestEntry(existing, entry, nowMs) {
2665
+ return {
2666
+ ...existing,
2667
+ ...entry,
2668
+ createdAtMs: entry.command === "record" && entry.kind === "video" ? entry.createdAtMs : existing?.createdAtMs ?? entry.createdAtMs,
2669
+ evictedAtMs: entry.retentionState === "evicted" ? entry.evictedAtMs ?? nowMs : entry.evictedAtMs
2670
+ };
2671
+ }
2672
+ function compareManifestEntries(left, right) {
2673
+ const difference = (right.evictedAtMs ?? right.createdAtMs) - (left.evictedAtMs ?? left.createdAtMs);
2674
+ if (difference !== 0 && !Number.isNaN(difference)) {
2675
+ return difference;
2676
+ }
2677
+ const pendingDifference = Number(isPendingRecordingArtifact(right)) - Number(isPendingRecordingArtifact(left));
2678
+ return pendingDifference !== 0 ? pendingDifference : left.path.localeCompare(right.path);
2679
+ }
2680
+ function mergeSessionArtifactManifest(options) {
2681
+ const nowMs = options.nowMs ?? Date.now();
2682
+ const maxEntries = getSessionArtifactManifestMaxEntries();
2683
+ const byPath = /* @__PURE__ */ new Map();
2684
+ for (const entry of options.base?.entries ?? []) {
2685
+ byPath.set(getSessionArtifactManifestEntryKey(entry), entry);
2686
+ }
2687
+ const orderedEntries = (options.entries ?? []).map((entry, index) => ({ entry, index })).sort((left, right) => {
2688
+ const difference = left.entry.createdAtMs - right.entry.createdAtMs;
2689
+ return difference !== 0 && !Number.isNaN(difference) ? difference : left.index - right.index;
2690
+ }).map(({ entry }) => entry);
2691
+ for (const entry of orderedEntries) {
2692
+ const key = getSessionArtifactManifestEntryKey(entry);
2693
+ for (const candidateKey of getSupersededRecordingKeys(byPath, entry, key)) {
2694
+ byPath.delete(candidateKey);
2695
+ }
2696
+ const existing = byPath.get(key);
2697
+ byPath.set(key, mergeManifestEntry(existing, entry, nowMs));
2698
+ }
2699
+ if (byPath.size === 0) {
2700
+ return void 0;
2701
+ }
2702
+ const entries = [...byPath.values()].sort(compareManifestEntries).slice(0, maxEntries);
2703
+ return {
2704
+ entries,
2705
+ evictedCount: entries.filter((entry) => entry.retentionState === "evicted").length,
2706
+ liveCount: entries.filter((entry) => entry.retentionState === "live").length,
2707
+ maxEntries,
2708
+ updatedAtMs: nowMs,
2709
+ version: SESSION_ARTIFACT_MANIFEST_VERSION
2710
+ };
2711
+ }
2712
+
2713
+ // dist/extensions/agent-browser/lib/results/snapshot-spill.js
2714
+ var SNAPSHOT_SPILL_FILE_PREFIX = "pi-agent-browser-snapshot";
2715
+ async function writeSnapshotSpillFile(data, persistentArtifactStore) {
2716
+ const options = {
2717
+ content: JSON.stringify(redactSensitiveValue(data), null, 2),
2718
+ prefix: SNAPSHOT_SPILL_FILE_PREFIX,
2719
+ suffix: ".json"
2720
+ };
2721
+ if (persistentArtifactStore) {
2722
+ const result = await writePersistentSessionArtifactFile({
2723
+ ...options,
2724
+ store: persistentArtifactStore
2725
+ });
2726
+ return { ...result, storageScope: "persistent-session" };
2727
+ }
2728
+ return {
2729
+ evictedArtifacts: [],
2730
+ path: await writeSecureTempFile(options),
2731
+ storageScope: "process-temp"
2732
+ };
2733
+ }
2734
+ function applySnapshotArtifactManifest(options) {
2735
+ if (options.fullOutputPath === void 0 || options.fullOutputPath.length === 0 || !options.spill) {
2736
+ return {};
2737
+ }
2738
+ const nowMs = Date.now();
2739
+ const entries = [
2740
+ {
2741
+ command: options.command,
2742
+ createdAtMs: nowMs,
2743
+ kind: "spill",
2744
+ path: options.fullOutputPath,
2745
+ retentionState: options.spill.storageScope === "persistent-session" ? "live" : "ephemeral",
2746
+ storageScope: options.spill.storageScope
2747
+ },
2748
+ ...buildEvictedSessionArtifactEntries(options.spill.evictedArtifacts, nowMs)
2749
+ ];
2750
+ const artifactManifest = mergeSessionArtifactManifest({
2751
+ base: options.baseManifest,
2752
+ entries,
2753
+ nowMs
2754
+ });
2755
+ return artifactManifest ? {
2756
+ artifactManifest,
2757
+ artifactRetentionSummary: formatSessionArtifactRetentionSummary(artifactManifest)
2758
+ } : {};
2759
+ }
2760
+
2761
+ // dist/extensions/agent-browser/lib/results/snapshot.js
2762
+ function shouldCompactSnapshot(rawText, data) {
2763
+ return rawText.length > 6e3 || countLines(getSnapshotText(data) ?? "") > 80 || Object.keys(getSnapshotRefRecord(data) ?? {}).length > 60;
2764
+ }
2765
+ async function getSnapshotSpill(data, store) {
2766
+ try {
2767
+ const spill = await writeSnapshotSpillFile(data, store);
2768
+ return { spill, fullOutputPath: spill.path };
2769
+ } catch (error) {
2770
+ return { spillErrorText: error instanceof Error ? error.message : stringifyUnknown(error) };
2771
+ }
2772
+ }
2773
+ async function buildSnapshotPresentation(data, persistentArtifactStore, artifactManifest) {
2774
+ const summary = formatSnapshotSummary(data);
2775
+ const rawText = formatRawSnapshotText(data);
2776
+ if (isRecord(data.snapshot) && data.snapshot.kind !== "full" || !shouldCompactSnapshot(rawText, data)) {
2777
+ return { content: [{ type: "text", text: rawText }], data, summary };
2778
+ }
2779
+ const { spill, fullOutputPath, spillErrorText } = await getSnapshotSpill(data, persistentArtifactStore);
2780
+ const compact = buildCompactSnapshotView(data, fullOutputPath, spillErrorText);
2781
+ const manifestFields = applySnapshotArtifactManifest({
2782
+ baseManifest: artifactManifest,
2783
+ command: "snapshot",
2784
+ fullOutputPath,
2785
+ spill
2786
+ });
2787
+ const notice = manifestFields.artifactRetentionSummary;
2788
+ const text = compact.content.at(0);
2789
+ if (notice !== void 0 && notice.length > 0 && text?.type === "text") {
2790
+ compact.content[0] = { type: "text", text: `${text.text}
2791
+
2792
+ ${notice}` };
2793
+ }
2794
+ return { ...manifestFields, ...compact, fullOutputPath, summary: `${summary} (compact)` };
2795
+ }
2796
+ export {
2797
+ buildSnapshotPresentation,
2798
+ formatRawSnapshotText,
2799
+ formatSnapshotSummary
2800
+ };