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,2946 @@
1
+ // dist/extensions/agent-browser/lib/browser-session-conversion.js
2
+ import { randomUUID as randomUUID2 } from "node:crypto";
3
+ import { constants } from "node:fs";
4
+ import { link, lstat, mkdir, open, unlink } from "node:fs/promises";
5
+ import { dirname, resolve } from "node:path";
6
+
7
+ // dist/extensions/agent-browser/lib/parsing.js
8
+ function isRecord(value) {
9
+ return typeof value === "object" && value !== null;
10
+ }
11
+
12
+ // dist/extensions/agent-browser/lib/browser-journal-projection.js
13
+ var ENVELOPE_MAX_BYTES = 16 * 1024 * 1024;
14
+ var MAX_NESTING = 1024;
15
+ var RESERVE_PER_BYTE = 16;
16
+ var NATIVE_RECORD_BYTES = ENVELOPE_MAX_BYTES / RESERVE_PER_BYTE;
17
+ var NATIVE_STRUCTURE_LIMIT = 64 * 1024;
18
+ var JOURNAL_CHUNK_BYTES = 64 * 1024;
19
+ function matches(field, key) {
20
+ return field === key || field === "*" && typeof key === "number";
21
+ }
22
+ function selectedPath(path, fields) {
23
+ return fields.some((field) => field.every((key, index) => matches(key, path[index])) || path.every((key, index) => matches(field[index], key)));
24
+ }
25
+ var JsonProjection = class {
26
+ fields;
27
+ maxBytes;
28
+ stack = [];
29
+ root;
30
+ literal;
31
+ inKey = false;
32
+ keyText = "";
33
+ bytes = 0;
34
+ constructor(fields, maxBytes) {
35
+ this.fields = fields;
36
+ this.maxBytes = maxBytes;
37
+ }
38
+ result() {
39
+ return isRecord(this.root) ? this.root : void 0;
40
+ }
41
+ reserve(size) {
42
+ this.bytes += size;
43
+ if (this.bytes > this.maxBytes) {
44
+ throw new Error("Selected journal envelope exceeds its bounded read size.");
45
+ }
46
+ }
47
+ path() {
48
+ const frame = this.stack.at(-1);
49
+ return frame ? [...frame.path, frame.key ?? frame.index] : [];
50
+ }
51
+ excluded() {
52
+ const frame = this.stack.at(-1);
53
+ return frame !== void 0 && frame.value === void 0;
54
+ }
55
+ frame() {
56
+ const frame = this.stack.at(-1);
57
+ if (!frame) {
58
+ throw new Error("Journal JSON container is missing.");
59
+ }
60
+ return frame;
61
+ }
62
+ put(value) {
63
+ const parent = this.stack.at(-1);
64
+ if (!parent) {
65
+ this.root = value;
66
+ return;
67
+ }
68
+ if (parent.value && value !== void 0) {
69
+ if (Array.isArray(parent.value)) {
70
+ parent.value[parent.index] = value;
71
+ } else {
72
+ if (parent.key === void 0) {
73
+ throw new Error("Journal object key is missing.");
74
+ }
75
+ Object.defineProperty(parent.value, parent.key, {
76
+ value,
77
+ writable: true,
78
+ enumerable: true,
79
+ configurable: true
80
+ });
81
+ }
82
+ }
83
+ parent.key = void 0;
84
+ parent.index += 1;
85
+ }
86
+ consume(token) {
87
+ if (token.name === "startKey") {
88
+ this.inKey = true;
89
+ this.keyText = "";
90
+ return;
91
+ }
92
+ if (token.name === "endKey") {
93
+ this.inKey = false;
94
+ this.frame().key = this.keyText;
95
+ return;
96
+ }
97
+ if (this.inKey) {
98
+ this.consumeKey(token);
99
+ return;
100
+ }
101
+ switch (token.name) {
102
+ case "startObject":
103
+ case "startArray":
104
+ this.startContainer(token.name);
105
+ break;
106
+ case "endObject":
107
+ case "endArray": {
108
+ const frame = this.stack.pop();
109
+ if (!frame) {
110
+ throw new Error("Journal JSON container is missing.");
111
+ }
112
+ this.put(frame.value);
113
+ break;
114
+ }
115
+ case "startString":
116
+ case "startNumber":
117
+ this.literal = {
118
+ value: "",
119
+ selected: !this.excluded() && selectedPath(this.path(), this.fields),
120
+ number: token.name === "startNumber"
121
+ };
122
+ break;
123
+ case "stringChunk":
124
+ case "numberChunk":
125
+ this.consumeLiteral(token.value);
126
+ break;
127
+ case "endString":
128
+ case "endNumber":
129
+ this.endLiteral();
130
+ break;
131
+ case "trueValue":
132
+ case "falseValue":
133
+ case "nullValue":
134
+ this.consumeConstant(token.name);
135
+ break;
136
+ case "keyValue":
137
+ case "numberValue":
138
+ case "stringValue":
139
+ case "whitespace":
140
+ break;
141
+ }
142
+ }
143
+ consumeKey(token) {
144
+ if (token.name !== "stringChunk" || this.excluded()) {
145
+ return;
146
+ }
147
+ const path = this.frame().path;
148
+ const wholeContainer = this.fields.some((field) => field.every((key, index) => matches(key, path[index])));
149
+ if (wholeContainer || this.keyText.length <= 1024) {
150
+ if (wholeContainer) {
151
+ this.reserve(Buffer.byteLength(token.value));
152
+ }
153
+ this.keyText += token.value;
154
+ }
155
+ }
156
+ startContainer(name) {
157
+ if (this.stack.length >= MAX_NESTING) {
158
+ throw new Error("Journal JSON nesting exceeds 1024 levels.");
159
+ }
160
+ const currentPath = this.excluded() ? [] : this.path();
161
+ const selected = !this.excluded() && selectedPath(currentPath, this.fields);
162
+ if (selected) {
163
+ this.reserve(32);
164
+ }
165
+ let value;
166
+ if (selected) {
167
+ value = name === "startObject" ? {} : [];
168
+ }
169
+ this.stack.push({ path: currentPath, index: 0, value });
170
+ }
171
+ consumeLiteral(value) {
172
+ if (this.literal?.selected === true) {
173
+ this.reserve(Buffer.byteLength(value));
174
+ this.literal.value += value;
175
+ }
176
+ }
177
+ endLiteral() {
178
+ const literal = this.literal;
179
+ let value;
180
+ if (literal?.selected === true) {
181
+ value = literal.number ? Number(literal.value) : literal.value;
182
+ }
183
+ this.put(value);
184
+ this.literal = void 0;
185
+ }
186
+ consumeConstant(name) {
187
+ const selected = !this.excluded() && selectedPath(this.path(), this.fields);
188
+ if (selected) {
189
+ this.reserve(8);
190
+ }
191
+ let value;
192
+ if (selected) {
193
+ value = name === "nullValue" ? null : name === "trueValue";
194
+ }
195
+ this.put(value);
196
+ }
197
+ };
198
+ async function projectJson(input, fields, maxBytes = ENVELOPE_MAX_BYTES) {
199
+ const { jsonParser } = await import("stream-json/core/parser.js");
200
+ const chain = await import("stream-chain/defs.js");
201
+ const tokenize = jsonParser({ packValues: false, streamValues: true });
202
+ const projection = new JsonProjection(fields, maxBytes);
203
+ const decoder = new TextDecoder("utf-8", { fatal: true });
204
+ const consume = (text) => {
205
+ const tokens = tokenize(text);
206
+ if (tokens !== chain.none) {
207
+ for (const token of chain.getManyValues(tokens)) {
208
+ projection.consume(token);
209
+ }
210
+ }
211
+ };
212
+ for await (const chunk of input) {
213
+ consume(decoder.decode(chunk, { stream: true }));
214
+ }
215
+ const tail = decoder.decode();
216
+ if (tail.length > 0) {
217
+ consume(tail);
218
+ }
219
+ consume(chain.none);
220
+ return projection.result();
221
+ }
222
+ function stringEnd(bytes, open2) {
223
+ for (let quote = bytes.indexOf(34, open2 + 1); quote !== -1; quote = bytes.indexOf(34, quote + 1)) {
224
+ let escapes = 0;
225
+ while (bytes[quote - 1 - escapes] === 92) {
226
+ escapes++;
227
+ }
228
+ if (escapes % 2 === 0) {
229
+ return quote;
230
+ }
231
+ }
232
+ return -1;
233
+ }
234
+ var DEPTH_STEP = new Int8Array(256);
235
+ var STRUCTURE_STEP = new Uint8Array(256);
236
+ for (const byte of [91, 123]) {
237
+ DEPTH_STEP[byte] = 1;
238
+ STRUCTURE_STEP[byte] = 1;
239
+ }
240
+ for (const byte of [93, 125]) {
241
+ DEPTH_STEP[byte] = -1;
242
+ }
243
+ for (const byte of [44, 58]) {
244
+ STRUCTURE_STEP[byte] = 1;
245
+ }
246
+ function fitsNativeParse(bytes) {
247
+ let depth = 0;
248
+ let structure = 0;
249
+ for (let index = 0; index < bytes.length; index++) {
250
+ const byte = bytes[index];
251
+ if (byte === 34) {
252
+ index = stringEnd(bytes, index);
253
+ if (index === -1) {
254
+ return false;
255
+ }
256
+ continue;
257
+ }
258
+ depth += DEPTH_STEP[byte];
259
+ structure += STRUCTURE_STEP[byte];
260
+ if (depth > MAX_NESTING || structure > NATIVE_STRUCTURE_LIMIT) {
261
+ return false;
262
+ }
263
+ }
264
+ return true;
265
+ }
266
+ function selectValue(value, path, fields) {
267
+ if (typeof value !== "object" || value === null || fields.some((field) => field.every((key, index) => matches(key, path[index])))) {
268
+ return value;
269
+ }
270
+ if (Array.isArray(value)) {
271
+ const selected2 = [];
272
+ for (const [index, item] of value.entries()) {
273
+ const itemPath = [...path, index];
274
+ if (selectedPath(itemPath, fields)) {
275
+ selected2[index] = selectValue(item, itemPath, fields);
276
+ }
277
+ }
278
+ return selected2;
279
+ }
280
+ const selected = {};
281
+ for (const [key, item] of Object.entries(value)) {
282
+ const itemPath = [...path, key];
283
+ if (selectedPath(itemPath, fields)) {
284
+ Object.defineProperty(selected, key, {
285
+ value: selectValue(item, itemPath, fields),
286
+ writable: true,
287
+ enumerable: true,
288
+ configurable: true
289
+ });
290
+ }
291
+ }
292
+ return selected;
293
+ }
294
+ function nativeProjection(bytes, fields) {
295
+ if (!fitsNativeParse(bytes)) {
296
+ return void 0;
297
+ }
298
+ let value;
299
+ try {
300
+ value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
301
+ } catch {
302
+ return void 0;
303
+ }
304
+ if (!isRecord(value)) {
305
+ return void 0;
306
+ }
307
+ const selected = selectValue(value, [], fields);
308
+ return isRecord(selected) ? selected : void 0;
309
+ }
310
+ async function* chunks(bytes) {
311
+ for (let start = 0; start < bytes.length; start += JOURNAL_CHUNK_BYTES) {
312
+ yield bytes.subarray(start, start + JOURNAL_CHUNK_BYTES);
313
+ }
314
+ }
315
+ async function projectJsonBytes(bytes, fields, maxBytes = ENVELOPE_MAX_BYTES) {
316
+ const native = bytes.length * RESERVE_PER_BYTE <= maxBytes ? nativeProjection(bytes, fields) : void 0;
317
+ return native ?? projectJson(chunks(bytes), fields, maxBytes);
318
+ }
319
+
320
+ // dist/extensions/agent-browser/lib/browser-journal-reader.js
321
+ async function* readRange(file, range) {
322
+ let position = range.offset;
323
+ const end = range.offset + range.length;
324
+ while (position < end) {
325
+ const buffer = Buffer.allocUnsafe(Math.min(JOURNAL_CHUNK_BYTES, end - position));
326
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, position);
327
+ if (bytesRead === 0) {
328
+ throw new Error("Journal changed or truncated during read.");
329
+ }
330
+ position += bytesRead;
331
+ yield buffer.subarray(0, bytesRead);
332
+ }
333
+ }
334
+ function hasContent(buffer, start, end) {
335
+ for (let index = start; index < end; index++) {
336
+ const byte = buffer[index];
337
+ if (byte !== 9 && byte !== 13 && byte !== 32) {
338
+ return true;
339
+ }
340
+ }
341
+ return false;
342
+ }
343
+ var JournalLineFramer = class {
344
+ start;
345
+ nonblank = false;
346
+ parts = [];
347
+ held = 0;
348
+ constructor(offset) {
349
+ this.start = offset;
350
+ }
351
+ *accept(buffer, position) {
352
+ let index = 0;
353
+ while (index < buffer.length) {
354
+ const newline = buffer.indexOf(10, index);
355
+ const end = newline === -1 ? buffer.length : newline;
356
+ this.nonblank ||= hasContent(buffer, index, end);
357
+ this.hold(buffer.subarray(index, newline === -1 ? end : end + 1));
358
+ if (newline === -1) {
359
+ return;
360
+ }
361
+ const record = this.take(position + newline + 1);
362
+ if (record) {
363
+ yield record;
364
+ }
365
+ index = newline + 1;
366
+ }
367
+ }
368
+ final(end, sealed) {
369
+ return sealed ? this.take(end) : void 0;
370
+ }
371
+ hold(part) {
372
+ this.held += part.length;
373
+ if (this.held > NATIVE_RECORD_BYTES) {
374
+ this.parts = void 0;
375
+ } else {
376
+ this.parts?.push(part);
377
+ }
378
+ }
379
+ take(next) {
380
+ let record;
381
+ if (this.nonblank) {
382
+ const range = { offset: this.start, length: next - this.start };
383
+ record = this.parts ? { ...range, bytes: Buffer.concat(this.parts) } : range;
384
+ }
385
+ this.start = next;
386
+ this.nonblank = false;
387
+ this.parts = [];
388
+ this.held = 0;
389
+ return record;
390
+ }
391
+ };
392
+ async function* journalRanges(file, end, sealed = false, offset = 0) {
393
+ let position = offset;
394
+ const framer = new JournalLineFramer(offset);
395
+ while (position < end) {
396
+ const buffer = Buffer.allocUnsafe(Math.min(JOURNAL_CHUNK_BYTES, end - position));
397
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, position);
398
+ if (bytesRead === 0) {
399
+ throw new Error("Journal truncated during read.");
400
+ }
401
+ yield* framer.accept(buffer.subarray(0, bytesRead), position);
402
+ position += bytesRead;
403
+ }
404
+ const final = framer.final(end, sealed);
405
+ if (final) {
406
+ yield final;
407
+ }
408
+ }
409
+ var STRUCTURAL_FIELDS = [
410
+ ["type"],
411
+ ["id"],
412
+ ["parentId"],
413
+ ["timestamp"],
414
+ ["version"],
415
+ ["customType"],
416
+ ["data", "event", "version"],
417
+ ["data", "snapshot", "id"],
418
+ ["message", "toolName"],
419
+ ["message", "details", "browserEventVersion"],
420
+ ["message", "details", "sessionName"],
421
+ ["message", "details", "artifactManifest", "version"],
422
+ ["message", "details", "electron", "action"]
423
+ ];
424
+ async function scanJournalMetadata(file, end, sealed = false, offset = 0) {
425
+ const entries = [];
426
+ for await (const range of journalRanges(file, end, sealed, offset)) {
427
+ const value = range.bytes ? await projectJsonBytes(range.bytes, STRUCTURAL_FIELDS) : await projectJson(readRange(file, range), STRUCTURAL_FIELDS);
428
+ if (!value) {
429
+ throw new Error(`Expected a journal object at byte ${range.offset}.`);
430
+ }
431
+ entries.push({ offset: range.offset, length: range.length, value });
432
+ }
433
+ return entries;
434
+ }
435
+
436
+ // dist/extensions/agent-browser/lib/process-errors.js
437
+ function getErrorCode(error) {
438
+ return isRecord(error) && typeof error.code === "string" ? error.code : void 0;
439
+ }
440
+
441
+ // dist/extensions/agent-browser/lib/browser-session-conversion-stream.js
442
+ import { createHash as createHash2 } from "node:crypto";
443
+ import { Readable } from "node:stream";
444
+ import { pipeline } from "node:stream/promises";
445
+ import tokenizeJson from "stream-json/parser.js";
446
+ import ignoreJson from "stream-json/filters/ignore.js";
447
+ import stringifyJson from "stream-json/stringer.js";
448
+ import disassembleJson from "stream-json/disassembler.js";
449
+
450
+ // dist/extensions/agent-browser/lib/browser-transcript-contracts.js
451
+ var BROWSER_TRANSITION_ENTRY = "agent-browser-transition";
452
+ var BROWSER_RESULT_TOOLS = /* @__PURE__ */ new Set([
453
+ "agent_browser",
454
+ "agent_browser_code",
455
+ "agent_browser_action",
456
+ "agent_browser_qa",
457
+ "agent_browser_electron",
458
+ "agent_browser_source",
459
+ "agent_browser_network_source"
460
+ ]);
461
+ var BROWSER_STATE_FIELDS = [
462
+ "args",
463
+ "command",
464
+ "subcommand",
465
+ "sessionName",
466
+ "namespace",
467
+ "sessionMode",
468
+ "usedImplicitSession",
469
+ "managedSessionSocketDir",
470
+ "managedSessionDaemon",
471
+ "ownerSessionId",
472
+ "agentBrowserStarted",
473
+ "resultCategory",
474
+ "exitCode",
475
+ "closeAllApplied",
476
+ "attachedBrowserSession",
477
+ "readConfirmation",
478
+ "compatibilityWorkaround",
479
+ "managedSessionHeadedAutosaveDisabled",
480
+ "managedSessionHeadedAutosaveInterval",
481
+ "managedSessionOutcome",
482
+ "managedSessionCwd",
483
+ "managedSessionRestoreDisabled",
484
+ "nativeSucceeded"
485
+ ];
486
+
487
+ // dist/extensions/agent-browser/lib/browser-legacy-projection.js
488
+ import { randomUUID } from "node:crypto";
489
+
490
+ // dist/extensions/agent-browser/lib/command-capabilities.js
491
+ var ADDITIONAL_COMMAND_TOKENS = [
492
+ "a11y",
493
+ "auth",
494
+ "chat",
495
+ "clipboard",
496
+ "confirm",
497
+ "connect",
498
+ "dashboard",
499
+ "deny",
500
+ "device",
501
+ "dialog",
502
+ "diff",
503
+ "doctor",
504
+ "errors",
505
+ "eval",
506
+ "find",
507
+ "frame",
508
+ "get",
509
+ "highlight",
510
+ "inspect",
511
+ "install",
512
+ "is",
513
+ "mcp",
514
+ "plugin",
515
+ "plugins",
516
+ "profiles",
517
+ "profiler",
518
+ "react",
519
+ "record",
520
+ "removeinitscript",
521
+ "session",
522
+ "set",
523
+ "skills",
524
+ "snapshot",
525
+ "state",
526
+ "stream",
527
+ "trace",
528
+ "upgrade",
529
+ "vitals",
530
+ "wait",
531
+ "web-vitals",
532
+ "webmcp",
533
+ "window"
534
+ ];
535
+ var COMMAND_CAPABILITIES = [
536
+ {
537
+ command: "back",
538
+ eligibleForElectronHealthProbe: true,
539
+ eligibleForPageChangeSummary: true,
540
+ invalidatesBatchRefs: true,
541
+ navigationObservable: true,
542
+ triggersPostMutationSnapshot: true
543
+ },
544
+ {
545
+ command: "batch",
546
+ excludedFromPostCommandCorrection: true
547
+ },
548
+ {
549
+ command: "check",
550
+ eligibleForElectronHealthProbe: true,
551
+ eligibleForPageChangeSummary: true,
552
+ guardsPageRefs: true,
553
+ invalidatesBatchRefs: true,
554
+ triggersPostMutationSnapshot: true
555
+ },
556
+ {
557
+ command: "click",
558
+ eligibleForElectronHealthProbe: true,
559
+ eligibleForPageChangeSummary: true,
560
+ guardsPageRefs: true,
561
+ invalidatesBatchRefs: true,
562
+ navigationObservable: true,
563
+ triggersPostMutationSnapshot: true
564
+ },
565
+ {
566
+ aliases: ["quit", "exit"],
567
+ closesSession: true,
568
+ command: "close",
569
+ excludedFromPinning: true,
570
+ excludedFromPostCommandCorrection: true
571
+ },
572
+ {
573
+ command: "console",
574
+ readOnlyDiagnosticSessionTarget: true
575
+ },
576
+ {
577
+ command: "cookies",
578
+ readOnlyDiagnosticSessionTarget: true
579
+ },
580
+ {
581
+ command: "dblclick",
582
+ eligibleForElectronHealthProbe: true,
583
+ eligibleForPageChangeSummary: true,
584
+ guardsPageRefs: true,
585
+ invalidatesBatchRefs: true,
586
+ navigationObservable: true,
587
+ triggersPostMutationSnapshot: true
588
+ },
589
+ {
590
+ command: "dialog",
591
+ eligibleForPageChangeSummary: true,
592
+ invalidatesBatchRefs: true,
593
+ triggersPostMutationSnapshot: true
594
+ },
595
+ {
596
+ command: "diff",
597
+ guardsPageRefs: true
598
+ },
599
+ {
600
+ command: "download",
601
+ eligibleForPageChangeSummary: true,
602
+ guardsPageRefs: true
603
+ },
604
+ {
605
+ command: "drag",
606
+ guardsPageRefs: true,
607
+ invalidatesBatchRefs: true
608
+ },
609
+ {
610
+ command: "errors",
611
+ readOnlyDiagnosticSessionTarget: true
612
+ },
613
+ {
614
+ command: "eval",
615
+ invalidatesBatchRefs: true,
616
+ navigationObservable: true,
617
+ triggersPostMutationSnapshot: true
618
+ },
619
+ {
620
+ command: "fill",
621
+ eligibleForElectronHealthProbe: true,
622
+ eligibleForPageChangeSummary: true,
623
+ guardsPageRefs: true,
624
+ triggersPostMutationSnapshot: true
625
+ },
626
+ {
627
+ command: "find",
628
+ eligibleForElectronHealthProbe: true
629
+ },
630
+ {
631
+ command: "frame",
632
+ guardsPageRefs: true
633
+ },
634
+ {
635
+ command: "focus",
636
+ guardsPageRefs: true
637
+ },
638
+ {
639
+ command: "forward",
640
+ eligibleForElectronHealthProbe: true,
641
+ eligibleForPageChangeSummary: true,
642
+ invalidatesBatchRefs: true,
643
+ navigationObservable: true,
644
+ triggersPostMutationSnapshot: true
645
+ },
646
+ {
647
+ command: "get",
648
+ guardsPageRefs: true
649
+ },
650
+ {
651
+ command: "highlight",
652
+ guardsPageRefs: true
653
+ },
654
+ {
655
+ command: "hover",
656
+ eligibleForPageChangeSummary: true,
657
+ guardsPageRefs: true,
658
+ invalidatesBatchRefs: true,
659
+ triggersPostMutationSnapshot: true
660
+ },
661
+ {
662
+ command: "is",
663
+ guardsPageRefs: true
664
+ },
665
+ {
666
+ command: "keydown",
667
+ eligibleForElectronHealthProbe: true,
668
+ eligibleForPageChangeSummary: true,
669
+ invalidatesBatchRefs: true,
670
+ triggersPostMutationSnapshot: true
671
+ },
672
+ {
673
+ command: "keyboard",
674
+ eligibleForElectronHealthProbe: true,
675
+ eligibleForPageChangeSummary: true,
676
+ invalidatesBatchRefs: true,
677
+ triggersPostMutationSnapshot: true
678
+ },
679
+ {
680
+ command: "keyup",
681
+ eligibleForElectronHealthProbe: true,
682
+ eligibleForPageChangeSummary: true,
683
+ invalidatesBatchRefs: true,
684
+ triggersPostMutationSnapshot: true
685
+ },
686
+ {
687
+ command: "mouse",
688
+ eligibleForElectronHealthProbe: true,
689
+ invalidatesBatchRefs: true
690
+ },
691
+ {
692
+ command: "network",
693
+ readOnlyDiagnosticSessionTarget: true
694
+ },
695
+ {
696
+ aliases: ["goto", "navigate"],
697
+ command: "open",
698
+ eligibleForPageChangeSummary: true,
699
+ excludedFromPinning: true,
700
+ invalidatesBatchRefs: true,
701
+ openNavigation: true
702
+ },
703
+ {
704
+ command: "pdf",
705
+ eligibleForPageChangeSummary: true
706
+ },
707
+ {
708
+ aliases: ["key"],
709
+ command: "press",
710
+ eligibleForElectronHealthProbe: true,
711
+ eligibleForPageChangeSummary: true,
712
+ invalidatesBatchRefs: true,
713
+ triggersPostMutationSnapshot: true
714
+ },
715
+ {
716
+ command: "pushstate",
717
+ eligibleForPageChangeSummary: true,
718
+ invalidatesBatchRefs: true,
719
+ triggersPostMutationSnapshot: true
720
+ },
721
+ {
722
+ command: "reload",
723
+ eligibleForElectronHealthProbe: true,
724
+ eligibleForPageChangeSummary: true,
725
+ invalidatesBatchRefs: true,
726
+ navigationObservable: true,
727
+ triggersPostMutationSnapshot: true
728
+ },
729
+ {
730
+ command: "read",
731
+ readOnlyDiagnosticSessionTarget: true
732
+ },
733
+ {
734
+ command: "screenshot",
735
+ eligibleForPageChangeSummary: true,
736
+ guardsPageRefs: true
737
+ },
738
+ {
739
+ command: "scroll",
740
+ eligibleForPageChangeSummary: true,
741
+ guardsPageRefs: true,
742
+ invalidatesBatchRefs: true,
743
+ triggersPostMutationSnapshot: true
744
+ },
745
+ {
746
+ aliases: ["scrollinto"],
747
+ command: "scrollintoview",
748
+ eligibleForPageChangeSummary: true,
749
+ guardsPageRefs: true,
750
+ invalidatesBatchRefs: true,
751
+ triggersPostMutationSnapshot: true
752
+ },
753
+ {
754
+ command: "select",
755
+ eligibleForElectronHealthProbe: true,
756
+ eligibleForPageChangeSummary: true,
757
+ guardsPageRefs: true,
758
+ invalidatesBatchRefs: true,
759
+ triggersPostMutationSnapshot: true
760
+ },
761
+ {
762
+ command: "session",
763
+ excludedFromPinning: true,
764
+ excludedFromPostCommandCorrection: true
765
+ },
766
+ {
767
+ command: "storage",
768
+ readOnlyDiagnosticSessionTarget: true
769
+ },
770
+ {
771
+ command: "swipe",
772
+ eligibleForPageChangeSummary: true,
773
+ invalidatesBatchRefs: true,
774
+ triggersPostMutationSnapshot: true
775
+ },
776
+ {
777
+ command: "tab",
778
+ excludedFromPinning: true,
779
+ excludedFromPostCommandCorrection: true
780
+ },
781
+ {
782
+ command: "tap",
783
+ eligibleForElectronHealthProbe: true,
784
+ eligibleForPageChangeSummary: true,
785
+ guardsPageRefs: true,
786
+ invalidatesBatchRefs: true,
787
+ triggersPostMutationSnapshot: true
788
+ },
789
+ {
790
+ command: "type",
791
+ eligibleForElectronHealthProbe: true,
792
+ eligibleForPageChangeSummary: true,
793
+ guardsPageRefs: true,
794
+ invalidatesBatchRefs: true,
795
+ triggersPostMutationSnapshot: true
796
+ },
797
+ {
798
+ command: "uncheck",
799
+ eligibleForElectronHealthProbe: true,
800
+ eligibleForPageChangeSummary: true,
801
+ guardsPageRefs: true,
802
+ invalidatesBatchRefs: true,
803
+ triggersPostMutationSnapshot: true
804
+ },
805
+ {
806
+ command: "upload",
807
+ guardsPageRefs: true,
808
+ invalidatesBatchRefs: true
809
+ }
810
+ ];
811
+ var COMMAND_CAPABILITY_BY_NAME = /* @__PURE__ */ new Map();
812
+ for (const entry of COMMAND_CAPABILITIES) {
813
+ COMMAND_CAPABILITY_BY_NAME.set(entry.command, entry);
814
+ for (const alias of entry.aliases ?? []) {
815
+ COMMAND_CAPABILITY_BY_NAME.set(alias, entry);
816
+ }
817
+ }
818
+ var KNOWN_COMMAND_TOKENS = /* @__PURE__ */ new Set([
819
+ ...COMMAND_CAPABILITY_BY_NAME.keys(),
820
+ ...ADDITIONAL_COMMAND_TOKENS
821
+ ]);
822
+ function isKnownCommandToken(token) {
823
+ return KNOWN_COMMAND_TOKENS.has(token);
824
+ }
825
+ function getCommandCapability(command) {
826
+ return command === void 0 ? void 0 : COMMAND_CAPABILITY_BY_NAME.get(command);
827
+ }
828
+ function hasCommandCapability(command, capability) {
829
+ return getCommandCapability(command)?.[capability] === true;
830
+ }
831
+
832
+ // dist/extensions/agent-browser/lib/command-taxonomy.js
833
+ var WEBMCP_PAGE_MUTATION_SUBCOMMANDS = /* @__PURE__ */ new Set(["invoke", "result", "cancel"]);
834
+ function isCloseCommand(command) {
835
+ return hasCommandCapability(command, "closesSession");
836
+ }
837
+ function isCloseAllCommand(commandTokens) {
838
+ return isCloseCommand(commandTokens[0]) && commandTokens.slice(1).includes("--all");
839
+ }
840
+ function isOpenNavigationCommand(command) {
841
+ return hasCommandCapability(command, "openNavigation");
842
+ }
843
+ function isReadOnlyDiagnosticSessionTargetCommand(command, subcommand) {
844
+ return hasCommandCapability(command, "readOnlyDiagnosticSessionTarget") || command === "webmcp" && subcommand === "list";
845
+ }
846
+ function isWindowOrDiffPageTransitionCommand(command, subcommand) {
847
+ return command === "window" && subcommand === "new" || command === "diff" && subcommand === "url";
848
+ }
849
+ function isWebMcpPageMutation(command, subcommand) {
850
+ return command === "webmcp" && WEBMCP_PAGE_MUTATION_SUBCOMMANDS.has(subcommand ?? "");
851
+ }
852
+ function isUnverifiedPageTransitionCommand(command, subcommand) {
853
+ return ["back", "connect", "eval", "forward", "reload"].includes(command ?? "") || command === "state" && subcommand === "load" || command === "tab" && subcommand !== void 0 && !["list", "new"].includes(subcommand) || isWindowOrDiffPageTransitionCommand(command, subcommand) || isWebMcpPageMutation(command, subcommand);
854
+ }
855
+
856
+ // dist/extensions/agent-browser/lib/session-identity.js
857
+ var SESSION_COMPONENT_ALPHANUMERIC = /^[\p{Alphabetic}\p{Number}]$/u;
858
+ function canonicalizeAgentBrowserNamespace(value) {
859
+ if (value === void 0) {
860
+ return void 0;
861
+ }
862
+ let normalized = "";
863
+ let lastWasSeparator = false;
864
+ for (const character of value) {
865
+ if (SESSION_COMPONENT_ALPHANUMERIC.test(character)) {
866
+ normalized += character.toLowerCase();
867
+ lastWasSeparator = false;
868
+ continue;
869
+ }
870
+ if (normalized.length > 0 && !lastWasSeparator) {
871
+ normalized += character === "_" ? "_" : "-";
872
+ lastWasSeparator = true;
873
+ }
874
+ }
875
+ const result = normalized.replace(/[-_]+$/u, "");
876
+ return result.length > 0 ? result : void 0;
877
+ }
878
+ function foldAgentBrowserFilesystemIdentity(value, platform) {
879
+ if (platform !== "darwin" && platform !== "win32") {
880
+ return value;
881
+ }
882
+ return value.normalize("NFC").toLowerCase().toUpperCase().toLowerCase().normalize("NFC");
883
+ }
884
+ function getAgentBrowserSessionIdentityKey(sessionName, namespace, platform = process.platform) {
885
+ const canonicalNamespace = canonicalizeAgentBrowserNamespace(namespace);
886
+ const canonicalSessionName = foldAgentBrowserFilesystemIdentity(sessionName, platform);
887
+ return canonicalNamespace !== void 0 ? `${foldAgentBrowserFilesystemIdentity(canonicalNamespace, platform)}\0${canonicalSessionName}` : canonicalSessionName;
888
+ }
889
+ function isAgentBrowserSessionIdentityKeyInNamespace(identityKey, namespace) {
890
+ const prefix = getAgentBrowserSessionIdentityKey("", namespace);
891
+ return prefix.length > 0 ? identityKey.startsWith(prefix) : !identityKey.includes("\0");
892
+ }
893
+
894
+ // dist/extensions/agent-browser/lib/argv-grammar.js
895
+ var GLOBAL_VALUE_FLAGS = [
896
+ "--session",
897
+ "--namespace",
898
+ "--cdp",
899
+ "--config",
900
+ "--profile",
901
+ "--session-name",
902
+ "--restore-save",
903
+ "--restore-check-url",
904
+ "--restore-check-text",
905
+ "--restore-check-fn",
906
+ "--proxy",
907
+ "--proxy-bypass",
908
+ "--ca-cert",
909
+ "--headers",
910
+ "--executable-path",
911
+ "--extension",
912
+ "--init-script",
913
+ "--enable",
914
+ "--provider",
915
+ "-p",
916
+ "--engine",
917
+ "--state",
918
+ "--download-path",
919
+ "--screenshot-dir",
920
+ "--screenshot-format",
921
+ "--screenshot-quality",
922
+ "--color-scheme",
923
+ "--device",
924
+ "--args",
925
+ "--user-agent",
926
+ "--allowed-domains",
927
+ "--action-policy",
928
+ "--confirm-actions",
929
+ "--max-output",
930
+ "--model",
931
+ "--idle-timeout",
932
+ "--input-mode"
933
+ ];
934
+ var COMMAND_VALUE_FLAGS = [
935
+ "--allowed-origins",
936
+ "--baseline",
937
+ "--body",
938
+ "--categories",
939
+ "--content",
940
+ "--curl",
941
+ "--depth",
942
+ "-d",
943
+ "--domain",
944
+ "--expires",
945
+ "--filter",
946
+ "--frame",
947
+ "--fn",
948
+ "--label",
949
+ "--load",
950
+ "--method",
951
+ "--name",
952
+ "--older-than",
953
+ "--output",
954
+ "--prefix",
955
+ "--path",
956
+ "--port",
957
+ "--params",
958
+ "--resource-type",
959
+ "--resource-types",
960
+ "--sameSite",
961
+ "--scope",
962
+ "--selector",
963
+ "-s",
964
+ "--status",
965
+ "--tags",
966
+ "--text",
967
+ "--threshold",
968
+ "--timeout",
969
+ "--type",
970
+ "--url",
971
+ "--username",
972
+ "--password",
973
+ "--wait-until"
974
+ ];
975
+ var OPTIONAL_GLOBAL_VALUE_FLAGS = /* @__PURE__ */ new Set(["--restore"]);
976
+ var VALUE_FLAGS = /* @__PURE__ */ new Set([
977
+ ...GLOBAL_VALUE_FLAGS,
978
+ ...COMMAND_VALUE_FLAGS
979
+ ]);
980
+ var PREVALIDATED_VALUE_FLAGS = new Set(GLOBAL_VALUE_FLAGS);
981
+ var GLOBAL_BOOLEAN_FLAGS_WITH_OPTIONAL_VALUES = /* @__PURE__ */ new Set([
982
+ "--allow-file-access",
983
+ "--annotate",
984
+ "--auto-connect",
985
+ "--confirm-interactive",
986
+ "--content-boundaries",
987
+ "--debug",
988
+ "--headed",
989
+ "--hide-scrollbars",
990
+ "--ignore-https-errors",
991
+ "--json",
992
+ "--no-auto-dialog",
993
+ "--no-ca-cert",
994
+ "--no-pin-tab",
995
+ "--no-webmcp",
996
+ "--offline",
997
+ "--pin-tab",
998
+ "--quick",
999
+ "--fix",
1000
+ "--quiet",
1001
+ "-q",
1002
+ "--verbose",
1003
+ "-v",
1004
+ "--use-system-ca",
1005
+ "--webgpu"
1006
+ ]);
1007
+ function optionalGlobalValueFlagConsumesNext(flag, nextToken) {
1008
+ if (!OPTIONAL_GLOBAL_VALUE_FLAGS.has(flag) || nextToken === void 0 || nextToken.startsWith("-")) {
1009
+ return false;
1010
+ }
1011
+ return !isKnownCommandToken(nextToken);
1012
+ }
1013
+ function globalFlagWidth(token, next, seenCommand) {
1014
+ if (token.startsWith("--restore=")) {
1015
+ return 1;
1016
+ }
1017
+ if (token === "--restore") {
1018
+ return !seenCommand && optionalGlobalValueFlagConsumesNext(token, next) ? 2 : 1;
1019
+ }
1020
+ if (PREVALIDATED_VALUE_FLAGS.has(token)) {
1021
+ return 2;
1022
+ }
1023
+ if (GLOBAL_BOOLEAN_FLAGS_WITH_OPTIONAL_VALUES.has(token)) {
1024
+ return ["true", "false"].includes(next ?? "") ? 2 : 1;
1025
+ }
1026
+ return 0;
1027
+ }
1028
+ function projectUpstreamGlobalFlags(args) {
1029
+ const indices = [];
1030
+ const tokens = [];
1031
+ let seenCommand = false;
1032
+ for (let index = 0; index < args.length; index += 1) {
1033
+ const token = args[index];
1034
+ const width = globalFlagWidth(token, args[index + 1], seenCommand);
1035
+ if (width > 0) {
1036
+ index += width - 1;
1037
+ continue;
1038
+ }
1039
+ tokens.push(token);
1040
+ indices.push(index);
1041
+ if (isKnownCommandToken(token)) {
1042
+ seenCommand = true;
1043
+ }
1044
+ }
1045
+ return { indices, tokens };
1046
+ }
1047
+ function stripUpstreamGlobalFlags(args) {
1048
+ return projectUpstreamGlobalFlags(args).tokens;
1049
+ }
1050
+
1051
+ // dist/extensions/agent-browser/lib/argv-descriptor.js
1052
+ function isBooleanLiteral(token) {
1053
+ const normalized = token?.trim().toLowerCase();
1054
+ return normalized === "true" || normalized === "false";
1055
+ }
1056
+ function flagConsumesFollowingToken(token, nextToken) {
1057
+ const normalizedToken = token.split("=", 1).at(0) ?? token;
1058
+ if (optionalGlobalValueFlagConsumesNext(normalizedToken, nextToken)) {
1059
+ return true;
1060
+ }
1061
+ if (token.includes("=")) {
1062
+ return false;
1063
+ }
1064
+ return VALUE_FLAGS.has(normalizedToken) || GLOBAL_BOOLEAN_FLAGS_WITH_OPTIONAL_VALUES.has(normalizedToken) && isBooleanLiteral(nextToken);
1065
+ }
1066
+ function findCommandStartIndex(args) {
1067
+ for (let index = 0; index < args.length; index += 1) {
1068
+ const token = args[index];
1069
+ if (token.startsWith("--session=") || token.startsWith("--namespace=") || token.startsWith("--restore=")) {
1070
+ continue;
1071
+ }
1072
+ if (token.startsWith("-")) {
1073
+ if (flagConsumesFollowingToken(token, args[index + 1])) {
1074
+ index += 1;
1075
+ }
1076
+ continue;
1077
+ }
1078
+ return index;
1079
+ }
1080
+ return void 0;
1081
+ }
1082
+ function extractCommandTokens(args) {
1083
+ const commandStartIndex = findCommandStartIndex(args);
1084
+ return commandStartIndex === void 0 ? [] : args.slice(commandStartIndex);
1085
+ }
1086
+ function extractUpstreamCommandTokens(args) {
1087
+ return stripUpstreamGlobalFlags(extractCommandTokens(args));
1088
+ }
1089
+
1090
+ // dist/extensions/agent-browser/lib/page-target-navigation.js
1091
+ var POSITIONAL_VALUE_FLAGS = /* @__PURE__ */ new Set([...VALUE_FLAGS, "--llms"]);
1092
+
1093
+ // dist/extensions/agent-browser/lib/native-confirmation.js
1094
+ function isSuccessfulNativeConfirmedClose(commandTokens, data) {
1095
+ if (commandTokens[0] !== "confirm" || commandTokens.length !== 2 || !isRecord(data) || data.confirmed !== true || data.action !== "close") {
1096
+ return false;
1097
+ }
1098
+ return isRecord(data.result) && data.result.success === true && isRecord(data.result.data) && data.result.data.closed === true;
1099
+ }
1100
+
1101
+ // dist/extensions/agent-browser/lib/results/confirmation.js
1102
+ var CONFIRMATION_REQUIRED_FIELD_NAMES = [
1103
+ "confirmation_required",
1104
+ "confirmationRequired",
1105
+ "requires_confirmation",
1106
+ "requiresConfirmation"
1107
+ ];
1108
+ var CONFIRMATION_REQUIRED_RECORD_FIELD_NAMES = [
1109
+ "confirmation",
1110
+ "pendingConfirmation",
1111
+ "pending_confirmation"
1112
+ ];
1113
+ var CONFIRMATION_ID_FIELD_NAMES = ["confirmation_id", "confirmationId", "id"];
1114
+ var CONFIRMATION_ACTION_TEXT_FIELD_NAMES = [
1115
+ "action",
1116
+ "description",
1117
+ "message",
1118
+ "summary"
1119
+ ];
1120
+ var CONFIRMATION_REQUIRED_MARKER = "confirmation_required";
1121
+ function getTrimmedStringField(data, fieldNames) {
1122
+ for (const fieldName of fieldNames) {
1123
+ const value = data[fieldName];
1124
+ if (typeof value === "string" && value.trim().length > 0) {
1125
+ return value.trim();
1126
+ }
1127
+ }
1128
+ return void 0;
1129
+ }
1130
+ function hasConfirmationRequiredMarker(data) {
1131
+ return CONFIRMATION_REQUIRED_FIELD_NAMES.some((fieldName) => data[fieldName] === true) || data.type === CONFIRMATION_REQUIRED_MARKER || data.status === CONFIRMATION_REQUIRED_MARKER || data.kind === CONFIRMATION_REQUIRED_MARKER;
1132
+ }
1133
+ function getNestedConfirmationRecord(data) {
1134
+ for (const fieldName of CONFIRMATION_REQUIRED_RECORD_FIELD_NAMES) {
1135
+ const value = data[fieldName];
1136
+ if (isRecord(value)) {
1137
+ return value;
1138
+ }
1139
+ }
1140
+ return void 0;
1141
+ }
1142
+ function getConfirmationPayload(data) {
1143
+ return isRecord(data) && data.confirmed === true && isRecord(data.result) && data.result.success === true ? data.result.data : data;
1144
+ }
1145
+ function detectConfirmationRequired(data) {
1146
+ const payload = getConfirmationPayload(data);
1147
+ if (!isRecord(payload)) {
1148
+ return void 0;
1149
+ }
1150
+ const nestedRecord = getNestedConfirmationRecord(payload);
1151
+ const candidateRecords = nestedRecord ? [payload, nestedRecord] : [payload];
1152
+ if (!candidateRecords.some(hasConfirmationRequiredMarker)) {
1153
+ return void 0;
1154
+ }
1155
+ for (const record of candidateRecords) {
1156
+ const id = getTrimmedStringField(record, CONFIRMATION_ID_FIELD_NAMES);
1157
+ if (id === void 0 || id.length === 0) {
1158
+ continue;
1159
+ }
1160
+ return {
1161
+ actionText: getTrimmedStringField(record, CONFIRMATION_ACTION_TEXT_FIELD_NAMES),
1162
+ id
1163
+ };
1164
+ }
1165
+ return void 0;
1166
+ }
1167
+
1168
+ // dist/extensions/agent-browser/lib/batch-lifecycle.js
1169
+ function rowCommand(value, fallback) {
1170
+ return Array.isArray(value) && value.every((token) => typeof token === "string") ? value : fallback;
1171
+ }
1172
+ function rowResult(row) {
1173
+ if (isRecord(row.result)) {
1174
+ return row.result;
1175
+ }
1176
+ return isRecord(row.data) ? row.data : void 0;
1177
+ }
1178
+ function rowBrowserLaunched(row, result) {
1179
+ const lifecycle = isRecord(row.lifecycle) ? row.lifecycle : result?.lifecycle;
1180
+ if (!isRecord(lifecycle) || !isRecord(lifecycle.effectiveLaunch)) {
1181
+ return void 0;
1182
+ }
1183
+ const launched = lifecycle.effectiveLaunch.browserLaunched;
1184
+ return typeof launched === "boolean" ? launched : void 0;
1185
+ }
1186
+ function lifecycleStep(value, fallback) {
1187
+ if (!isRecord(value)) {
1188
+ return void 0;
1189
+ }
1190
+ const result = rowResult(value);
1191
+ const command = rowCommand(value.command, fallback);
1192
+ return {
1193
+ result,
1194
+ succeeded: value.success === true,
1195
+ browserLaunched: rowBrowserLaunched(value, result),
1196
+ tokens: command === void 0 ? void 0 : extractUpstreamCommandTokens(command)
1197
+ };
1198
+ }
1199
+ function batchHasSuccessfulCloseAll(data, fallbackCommands = []) {
1200
+ if (!Array.isArray(data)) {
1201
+ return false;
1202
+ }
1203
+ return data.some((row, index) => {
1204
+ if (!isRecord(row) || row.success !== true) {
1205
+ return false;
1206
+ }
1207
+ const command = rowCommand(row.command, fallbackCommands.at(index));
1208
+ return command !== void 0 && !detectConfirmationRequired(row.result) && isCloseAllCommand(extractUpstreamCommandTokens(command));
1209
+ });
1210
+ }
1211
+ function successfulClose(step) {
1212
+ return step.succeeded && step.tokens !== void 0 && !detectConfirmationRequired(step.result) && (isCloseCommand(step.tokens[0]) || isSuccessfulNativeConfirmedClose(step.tokens, step.result));
1213
+ }
1214
+ function closedState(step) {
1215
+ const result = step.result;
1216
+ const closeData = step.tokens?.[0] === "confirm" && isRecord(result) && isRecord(result.result) ? result.result.data : result;
1217
+ return {
1218
+ endsClosed: true,
1219
+ browserActiveAfterClose: false,
1220
+ recordingClosedAfterBatch: true,
1221
+ statePath: isRecord(closeData) && typeof closeData.statePath === "string" ? closeData.statePath : void 0
1222
+ };
1223
+ }
1224
+ function recordingState(state, step) {
1225
+ const relaunched = step.browserLaunched !== false;
1226
+ const browserActiveAfterClose = state.browserActiveAfterClose || relaunched;
1227
+ let recordingClosedAfterBatch = state.recordingClosedAfterBatch;
1228
+ const subcommand = step.tokens?.[1];
1229
+ if (step.succeeded && subcommand === "stop") {
1230
+ recordingClosedAfterBatch = true;
1231
+ } else if (step.succeeded && browserActiveAfterClose && (subcommand === "start" || subcommand === "restart")) {
1232
+ recordingClosedAfterBatch = false;
1233
+ }
1234
+ return {
1235
+ ...state,
1236
+ endsClosed: state.endsClosed && !relaunched,
1237
+ browserActiveAfterClose,
1238
+ recordingClosedAfterBatch
1239
+ };
1240
+ }
1241
+ function advanceClosedState(state, step) {
1242
+ if (step.tokens?.[0] === "record") {
1243
+ return recordingState(state, step);
1244
+ }
1245
+ if (step.browserLaunched === false) {
1246
+ return state;
1247
+ }
1248
+ return {
1249
+ ...state,
1250
+ endsClosed: false,
1251
+ browserActiveAfterClose: true,
1252
+ recordingClosedAfterBatch: step.tokens === void 0 ? false : state.recordingClosedAfterBatch
1253
+ };
1254
+ }
1255
+ function getSuccessfulBatchCloseLifecycle(rows, fallbackCommands = []) {
1256
+ if (!Array.isArray(rows)) {
1257
+ return void 0;
1258
+ }
1259
+ let state;
1260
+ for (const [index, row] of rows.entries()) {
1261
+ const step = lifecycleStep(row, fallbackCommands.at(index));
1262
+ if (step === void 0) {
1263
+ continue;
1264
+ }
1265
+ if (successfulClose(step)) {
1266
+ state = closedState(step);
1267
+ } else if (state !== void 0) {
1268
+ state = advanceClosedState(state, step);
1269
+ }
1270
+ }
1271
+ return state === void 0 ? void 0 : {
1272
+ endsClosed: state.endsClosed,
1273
+ recordingClosedAfterBatch: state.recordingClosedAfterBatch,
1274
+ statePath: state.statePath
1275
+ };
1276
+ }
1277
+
1278
+ // dist/extensions/agent-browser/lib/redaction-fields.js
1279
+ 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;
1280
+ var ENV_SECRET_ASSIGNMENT_PATTERN = /\b((?:export\s+)?([A-Za-z_][A-Za-z0-9_-]*)(\s*[:=]\s*))(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\s,;]+)/g;
1281
+ function isSensitiveFieldName(key) {
1282
+ SENSITIVE_FIELD_NAME_PATTERN.lastIndex = 0;
1283
+ return SENSITIVE_FIELD_NAME_PATTERN.test(key);
1284
+ }
1285
+ function isEnvSecretAssignmentKey(key) {
1286
+ if (!isSensitiveFieldName(key)) {
1287
+ return false;
1288
+ }
1289
+ if (key === "password" || key.includes("_") || key.includes("-") || key === key.toUpperCase()) {
1290
+ return true;
1291
+ }
1292
+ 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);
1293
+ }
1294
+ function isLineBoundary(text, index) {
1295
+ return index < 0 || index >= text.length || text[index] === "\n" || text[index] === "\r";
1296
+ }
1297
+ function redactPasswordAssignment(text, match, prefix, offset) {
1298
+ const end = offset + match.length;
1299
+ if (!isLineBoundary(text, offset - 1) || !isLineBoundary(text, end) || /^(?:\[REDACTED\]|%5Bredacted%5D)/i.test(match.slice(prefix.length))) {
1300
+ return match;
1301
+ }
1302
+ const value = match.slice(prefix.length);
1303
+ const boundary = value[0] === '"' || value[0] === "'" ? -1 : value.search(/[&#](?=[A-Za-z_][A-Za-z0-9_-]*\s*=)/);
1304
+ return `${prefix}[REDACTED]${boundary < 0 ? "" : value.slice(boundary)}`;
1305
+ }
1306
+ function redactEnvSecretAssignments(text) {
1307
+ return text.replace(
1308
+ ENV_SECRET_ASSIGNMENT_PATTERN,
1309
+ // String.replace supplies match, three captures, then the source offset.
1310
+ (match, prefix, key, _separator, offset) => {
1311
+ if (!isEnvSecretAssignmentKey(key)) {
1312
+ return match;
1313
+ }
1314
+ return key === "password" ? redactPasswordAssignment(text, match, prefix, offset) : `${prefix}[REDACTED]`;
1315
+ }
1316
+ );
1317
+ }
1318
+ function credentialTrailingPunctuation(credential) {
1319
+ return credential.match(/[,.:;!?]+$/)?.[0] ?? "";
1320
+ }
1321
+ function formatRedactedCredential(label, credential, trailing = "") {
1322
+ return `${label} [REDACTED]${credentialTrailingPunctuation(credential)}${trailing}`;
1323
+ }
1324
+ function redactBearerCredentials(text) {
1325
+ return text.replace(
1326
+ /((?:\b([A-Za-z][A-Za-z0-9_-]*)\s*[:=]\s*|(?:^|\s)(?:-H\s*|--header(?:\s+|=)))["']?Bearer)\s+([^\s"',)[\]]+)([),.]?)/gi,
1327
+ // String.replace supplies the match followed by this expression's four captures.
1328
+ (match, label, field, credential, trailing) => {
1329
+ if (field !== void 0 && field.length > 0 && !isSensitiveFieldName(field)) {
1330
+ return match;
1331
+ }
1332
+ return formatRedactedCredential(label, credential, trailing);
1333
+ }
1334
+ ).replace(/\b(Bearer)\s+([^\s\\"',)[\]]+)([),.]?)/gi, (match, label, credential, trailing) => {
1335
+ const token = credential.slice(0, credential.length - credentialTrailingPunctuation(credential).length);
1336
+ if (!/^[A-Za-z0-9._~+/-]+=*$/.test(token) || !/[0-9._~+/=-]/.test(token)) {
1337
+ return match;
1338
+ }
1339
+ return formatRedactedCredential(label, credential, trailing);
1340
+ });
1341
+ }
1342
+ function redactStandaloneBasicCredential(text) {
1343
+ return text.replace(/\b(Basic)\s+([A-Za-z0-9+/=]{12,})/gi, (match, label, credential) => {
1344
+ if (!/[0-9+/=]/.test(credential)) {
1345
+ return match;
1346
+ }
1347
+ return `${label} [REDACTED]`;
1348
+ });
1349
+ }
1350
+
1351
+ // dist/extensions/agent-browser/lib/redaction-json.js
1352
+ function nextQuotePosition(options) {
1353
+ if (options.char === '"') {
1354
+ return options.index;
1355
+ }
1356
+ return options.char === "\\" ? options.quoteAfterNext : options.quoteAtNext;
1357
+ }
1358
+ function buildJsonBoundaries(text) {
1359
+ const boundaries = new Int32Array(text.length + 1).fill(-1);
1360
+ let quoteAtNext = -1;
1361
+ let quoteAfterNext = -1;
1362
+ for (let index = text.length - 1; index >= 0; index -= 1) {
1363
+ const char = text[index];
1364
+ switch (char) {
1365
+ case "}":
1366
+ case "]":
1367
+ boundaries[index] = index;
1368
+ break;
1369
+ case '"':
1370
+ boundaries[index] = quoteAtNext < 0 ? -1 : boundaries[quoteAtNext + 1];
1371
+ break;
1372
+ case "{":
1373
+ case "[": {
1374
+ const end = boundaries[index + 1];
1375
+ boundaries[index] = end >= 0 && text[end] === (char === "{" ? "}" : "]") ? boundaries[end + 1] : -1;
1376
+ break;
1377
+ }
1378
+ default:
1379
+ boundaries[index] = boundaries[index + 1];
1380
+ }
1381
+ const quote = nextQuotePosition({ char, index, quoteAtNext, quoteAfterNext });
1382
+ quoteAfterNext = quoteAtNext;
1383
+ quoteAtNext = quote;
1384
+ }
1385
+ return boundaries;
1386
+ }
1387
+ function createBalancedJsonEndFinder(text) {
1388
+ let boundaries;
1389
+ return (startIndex) => {
1390
+ const opener = text[startIndex];
1391
+ if (opener !== "{" && opener !== "[") {
1392
+ return;
1393
+ }
1394
+ boundaries ??= buildJsonBoundaries(text);
1395
+ const end = boundaries[startIndex + 1];
1396
+ return end >= 0 && text[end] === (opener === "{" ? "}" : "]") ? end : void 0;
1397
+ };
1398
+ }
1399
+ function parseJsonString(token) {
1400
+ const value = JSON.parse(token);
1401
+ if (typeof value !== "string") {
1402
+ throw new Error("Expected a JSON string token");
1403
+ }
1404
+ return value;
1405
+ }
1406
+ function isSerializedJson(text) {
1407
+ if (text === "[REDACTED]" || !/^\s*[[{"\d\-tfn]/.test(text)) {
1408
+ return false;
1409
+ }
1410
+ try {
1411
+ JSON.parse(text);
1412
+ return true;
1413
+ } catch {
1414
+ return false;
1415
+ }
1416
+ }
1417
+ function findJsonValueEnd(text, start, findEnd) {
1418
+ const balancedEnd = findEnd(start);
1419
+ if (balancedEnd !== void 0) {
1420
+ return balancedEnd + 1;
1421
+ }
1422
+ if (text[start] === '"') {
1423
+ const strings = /"(?:\\.|[^"\\])*"/g;
1424
+ strings.lastIndex = start;
1425
+ const fieldValue = strings.exec(text);
1426
+ if (fieldValue === null) {
1427
+ throw new Error("Expected a validated JSON string field value");
1428
+ }
1429
+ return parseJsonString(fieldValue[0]) === "[REDACTED]" ? void 0 : strings.lastIndex;
1430
+ }
1431
+ let end = start;
1432
+ while (end < text.length && !/[\s,\]}]/.test(text[end])) {
1433
+ end += 1;
1434
+ }
1435
+ return end;
1436
+ }
1437
+ function redactSerializedJson(text, redact) {
1438
+ if (!isSerializedJson(text)) {
1439
+ return;
1440
+ }
1441
+ let output = "";
1442
+ let cursor = 0;
1443
+ const findEnd = createBalancedJsonEndFinder(text);
1444
+ const strings = /"(?:\\.|[^"\\])*"/g;
1445
+ let match;
1446
+ while ((match = strings.exec(text)) !== null) {
1447
+ const end = strings.lastIndex;
1448
+ const value = parseJsonString(match[0]);
1449
+ const redacted = redact(value);
1450
+ if (redacted !== value) {
1451
+ output += text.slice(cursor, match.index) + JSON.stringify(redacted);
1452
+ cursor = end;
1453
+ }
1454
+ const separator = /^\s*:\s*/.exec(text.slice(end));
1455
+ if (separator === null || !isSensitiveFieldName(value)) {
1456
+ continue;
1457
+ }
1458
+ const valueStart = end + separator[0].length;
1459
+ const valueEnd = findJsonValueEnd(text, valueStart, findEnd);
1460
+ if (valueEnd === void 0) {
1461
+ strings.lastIndex = valueStart;
1462
+ strings.exec(text);
1463
+ continue;
1464
+ }
1465
+ output += text.slice(cursor, valueStart) + '"[REDACTED]"';
1466
+ cursor = valueEnd;
1467
+ strings.lastIndex = valueEnd;
1468
+ }
1469
+ return output + text.slice(cursor);
1470
+ }
1471
+ function redactEmbeddedStructuredText(text, redact) {
1472
+ let output = "";
1473
+ let cursor = 0;
1474
+ const findEnd = createBalancedJsonEndFinder(text);
1475
+ const openers = /[[{]/g;
1476
+ let match;
1477
+ while ((match = openers.exec(text)) !== null) {
1478
+ const endIndex = findEnd(match.index);
1479
+ if (endIndex === void 0) {
1480
+ continue;
1481
+ }
1482
+ const candidate = text.slice(match.index, endIndex + 1);
1483
+ const redacted = redactSerializedJson(candidate, redact) ?? candidate;
1484
+ if (redacted !== candidate) {
1485
+ output += text.slice(cursor, match.index) + redacted;
1486
+ cursor = endIndex + 1;
1487
+ }
1488
+ openers.lastIndex = endIndex + 1;
1489
+ }
1490
+ return cursor === 0 ? text : output + text.slice(cursor);
1491
+ }
1492
+
1493
+ // dist/extensions/agent-browser/lib/redaction-url.js
1494
+ 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;
1495
+ var AUTH_STATE_QUERY_PARAM_PATTERN = /^(?:nonce|state)$/i;
1496
+ var AUTH_URL_CONTEXT_PATTERN = /(?:^|[./_-])(?:auth|authorize|callback|login|oauth2?|oidc|saml|sso)(?:[./?#_-]|$)/i;
1497
+ function shouldRedactQueryParam(name) {
1498
+ return SENSITIVE_QUERY_PARAM_PATTERN.test(name) || isSensitiveFieldName(name);
1499
+ }
1500
+ function isSensitiveParameter(name, authContext) {
1501
+ return shouldRedactQueryParam(name) || authContext && AUTH_STATE_QUERY_PARAM_PATTERN.test(name);
1502
+ }
1503
+ function redactParameters(params, authContext) {
1504
+ let mutated = false;
1505
+ for (const [name] of params) {
1506
+ if (isSensitiveParameter(name, authContext)) {
1507
+ params.set(name, "[REDACTED]");
1508
+ mutated = true;
1509
+ }
1510
+ }
1511
+ return mutated;
1512
+ }
1513
+ function getHashParameters(hash) {
1514
+ const text = hash.startsWith("#") ? hash.slice(1) : hash;
1515
+ return text.includes("=") ? new URLSearchParams(text) : void 0;
1516
+ }
1517
+ function redactUrlToken(token) {
1518
+ let parsed;
1519
+ try {
1520
+ parsed = new URL(token);
1521
+ } catch {
1522
+ return token;
1523
+ }
1524
+ const originalHref = parsed.href;
1525
+ if (parsed.username.length > 0) {
1526
+ parsed.username = "[REDACTED]";
1527
+ }
1528
+ if (parsed.password.length > 0) {
1529
+ parsed.password = "[REDACTED]";
1530
+ }
1531
+ const hashParams = getHashParameters(parsed.hash);
1532
+ const authContext = AUTH_URL_CONTEXT_PATTERN.test(`${parsed.hostname}${parsed.pathname}`) || [...parsed.searchParams.keys(), ...hashParams?.keys() ?? []].some(shouldRedactQueryParam);
1533
+ redactParameters(parsed.searchParams, authContext);
1534
+ if (hashParams && redactParameters(hashParams, authContext)) {
1535
+ parsed.hash = `#${hashParams.toString()}`;
1536
+ }
1537
+ return parsed.href === originalHref ? token : parsed.href;
1538
+ }
1539
+ function decodeParameterName(raw) {
1540
+ try {
1541
+ return decodeURIComponent(raw.replace(/\+/g, " "));
1542
+ } catch {
1543
+ return raw;
1544
+ }
1545
+ }
1546
+ function redactLooseUrlParameterText(text) {
1547
+ return text.replace(/(?<![^\s"'`<>\])}])[^\s"'`<>\])}]*[?#&][^\s"'`<>\])}]*/g, (token) => {
1548
+ const queryNames = [...token.matchAll(/[?#&]([^=&#\s"'`<>\])}]+)=/g)].map((match) => decodeParameterName(match[1]));
1549
+ const authContext = AUTH_URL_CONTEXT_PATTERN.test(token) || queryNames.some(shouldRedactQueryParam);
1550
+ return token.replace(/([?#&])([^=&#\s"'`<>\])}]+)=([^&#\s"'`<>\])}]*)/g, (match, separator, rawName, rawValue) => {
1551
+ if (rawValue === "[REDACTED" || rawValue === "[REDACTED]" || /%5Bredacted%5D/i.test(rawValue)) {
1552
+ return match;
1553
+ }
1554
+ if (!isSensitiveParameter(decodeParameterName(rawName), authContext)) {
1555
+ return match;
1556
+ }
1557
+ return `${separator}${rawName}=[REDACTED]`;
1558
+ });
1559
+ });
1560
+ }
1561
+ function redactLooseUrlUserinfo(text) {
1562
+ return text.replace(/\b([A-Za-z][A-Za-z0-9+.-]*:\/\/)([^\s"'`/@]+)@([^\s"'`]+)/g, (match, prefix, userinfo, suffix) => {
1563
+ if (/%5Bredacted%5D/i.test(userinfo)) {
1564
+ return match;
1565
+ }
1566
+ if (userinfo.includes("[REDACTED]")) {
1567
+ return redactLooseUrlParameterText(match);
1568
+ }
1569
+ return redactLooseUrlParameterText(`${prefix}${userinfo.includes(":") ? "[REDACTED]:[REDACTED]" : "[REDACTED]"}@${suffix}`);
1570
+ });
1571
+ }
1572
+ function redactLooseUrls(text) {
1573
+ const urls = text.replace(/\b[A-Za-z][A-Za-z0-9+.-]*:\/\/[^\s"'`<>\])]+/g, (match) => redactUrlToken(match));
1574
+ return redactLooseUrlParameterText(redactLooseUrlUserinfo(urls));
1575
+ }
1576
+
1577
+ // dist/extensions/agent-browser/lib/runtime-redaction.js
1578
+ function redactSensitiveText(text) {
1579
+ const serialized = redactSerializedJson(text, redactSensitiveText);
1580
+ if (serialized !== void 0) {
1581
+ return serialized;
1582
+ }
1583
+ const embedded = redactEmbeddedStructuredText(text, redactSensitiveText);
1584
+ 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]");
1585
+ return redactEmbeddedStructuredText(redactEnvSecretAssignments(credentials), redactSensitiveText);
1586
+ }
1587
+ function redactSensitiveValue(value) {
1588
+ if (typeof value === "string") {
1589
+ return redactSensitiveText(value);
1590
+ }
1591
+ if (Array.isArray(value)) {
1592
+ return value.map((item) => redactSensitiveValue(item));
1593
+ }
1594
+ if (!isRecord(value)) {
1595
+ return value;
1596
+ }
1597
+ return Object.fromEntries(Object.entries(value).map(([key, entryValue]) => [
1598
+ key,
1599
+ isSensitiveFieldName(key) ? "[REDACTED]" : redactSensitiveValue(entryValue)
1600
+ ]));
1601
+ }
1602
+
1603
+ // dist/extensions/agent-browser/lib/browser-value-parsing.js
1604
+ function isBrowserStringArray(value) {
1605
+ if (!Array.isArray(value)) {
1606
+ return false;
1607
+ }
1608
+ const rows = value;
1609
+ return rows.every((row) => typeof row === "string");
1610
+ }
1611
+ function browserStringArray(value) {
1612
+ if (!Array.isArray(value)) {
1613
+ return [];
1614
+ }
1615
+ const rows = value;
1616
+ return rows.filter((row) => typeof row === "string");
1617
+ }
1618
+
1619
+ // dist/extensions/agent-browser/lib/session-page-observation.js
1620
+ function normalizeComparableUrl(url) {
1621
+ const normalizedUrl = url?.trim();
1622
+ if (normalizedUrl === void 0 || normalizedUrl.length === 0) {
1623
+ return void 0;
1624
+ }
1625
+ try {
1626
+ const parsedUrl = new URL(normalizedUrl);
1627
+ parsedUrl.hash = "";
1628
+ return parsedUrl.toString();
1629
+ } catch {
1630
+ return void 0;
1631
+ }
1632
+ }
1633
+ function trimmedOptionalValue(value) {
1634
+ const trimmed = value?.trim();
1635
+ return trimmed !== void 0 && trimmed.length > 0 ? trimmed : void 0;
1636
+ }
1637
+ function normalizeSessionTabTarget(target) {
1638
+ if (!target) {
1639
+ return void 0;
1640
+ }
1641
+ const url = trimmedOptionalValue(target.url);
1642
+ if (url === void 0 || normalizeComparableUrl(url) === void 0) {
1643
+ return void 0;
1644
+ }
1645
+ const targetId = trimmedOptionalValue(target.targetId);
1646
+ return {
1647
+ ...targetId !== void 0 ? { targetId } : {},
1648
+ title: trimmedOptionalValue(target.title),
1649
+ url
1650
+ };
1651
+ }
1652
+ function extractStringResultField(data, fieldName) {
1653
+ if (typeof data === "string") {
1654
+ if (fieldName === "value") {
1655
+ return data;
1656
+ }
1657
+ const text2 = data.trim();
1658
+ return text2.length > 0 ? text2 : void 0;
1659
+ }
1660
+ if (!isRecord(data) || typeof data[fieldName] !== "string") {
1661
+ return void 0;
1662
+ }
1663
+ if (fieldName === "value") {
1664
+ return data[fieldName];
1665
+ }
1666
+ const text = data[fieldName].trim();
1667
+ return text.length > 0 ? text : void 0;
1668
+ }
1669
+ function extractSessionTabTargetFromData(data) {
1670
+ const directTarget = normalizeSessionTabTarget({
1671
+ targetId: isRecord(data) && typeof data.targetId === "string" ? data.targetId : void 0,
1672
+ title: extractStringResultField(data, "title"),
1673
+ url: extractStringResultField(data, "url")
1674
+ });
1675
+ if (directTarget) {
1676
+ return directTarget;
1677
+ }
1678
+ if (isRecord(data) && typeof data.origin === "string") {
1679
+ return normalizeSessionTabTarget({ url: data.origin });
1680
+ }
1681
+ return void 0;
1682
+ }
1683
+ function extractBatchResultCommand(item) {
1684
+ return browserStringArray(item.command);
1685
+ }
1686
+ function confirmedNavigationResult(command, data) {
1687
+ if (command === "confirm" && isRecord(data) && data.confirmed === true && (data.action === "navigate" || data.action === "url") && isRecord(data.result) && data.result.success === true && !detectConfirmationRequired(data)) {
1688
+ return data.result;
1689
+ }
1690
+ return void 0;
1691
+ }
1692
+ function extractSessionTabTargetFromCommandData(commandTokens, data) {
1693
+ const [command, subcommand] = commandTokens;
1694
+ const confirmed = confirmedNavigationResult(command, data);
1695
+ if (confirmed) {
1696
+ return extractSessionTabTargetFromData(confirmed.data);
1697
+ }
1698
+ if (command === "get" && subcommand === "url") {
1699
+ return normalizeSessionTabTarget({
1700
+ url: extractStringResultField(data, "url") ?? extractStringResultField(data, "result")
1701
+ });
1702
+ }
1703
+ return isReadOnlyDiagnosticSessionTargetCommand(command, subcommand) ? void 0 : extractSessionTabTargetFromData(data);
1704
+ }
1705
+ var BatchTargetObservation = class {
1706
+ target;
1707
+ pendingTitle;
1708
+ observe(item) {
1709
+ if (detectConfirmationRequired(item.result)) {
1710
+ return;
1711
+ }
1712
+ if (this.target?.targetId !== void 0 && this.target.targetId.length > 0) {
1713
+ this.target = normalizeSessionTabTarget({ title: this.target.title, url: this.target.url });
1714
+ }
1715
+ const tokens = extractUpstreamCommandTokens(extractBatchResultCommand(item));
1716
+ this.invalidateTransition(tokens);
1717
+ if (item.success === false) {
1718
+ return;
1719
+ }
1720
+ this.observeResult(tokens, item.result);
1721
+ }
1722
+ invalidateTransition(tokens) {
1723
+ const [name, subcommand] = tokens;
1724
+ if (isOpenNavigationCommand(name) || isUnverifiedPageTransitionCommand(name, subcommand) || name === "click" && tokens.includes("--new-tab")) {
1725
+ this.target = void 0;
1726
+ this.pendingTitle = void 0;
1727
+ }
1728
+ }
1729
+ observeResult(tokens, result) {
1730
+ const [name, subcommand] = tokens;
1731
+ if (isCloseCommand(name) || isSuccessfulNativeConfirmedClose(tokens, result)) {
1732
+ this.target = void 0;
1733
+ this.pendingTitle = void 0;
1734
+ return;
1735
+ }
1736
+ if (name === "get" && subcommand === "title") {
1737
+ this.pendingTitle = extractStringResultField(result, "title");
1738
+ return;
1739
+ }
1740
+ if (name === "get" && subcommand === "url") {
1741
+ const target = normalizeSessionTabTarget({
1742
+ title: this.pendingTitle,
1743
+ url: extractStringResultField(result, "url")
1744
+ });
1745
+ if (target) {
1746
+ this.target = target;
1747
+ }
1748
+ } else {
1749
+ const target = extractSessionTabTargetFromCommandData(tokens.slice(0, 2), result);
1750
+ if (target) {
1751
+ this.target = target;
1752
+ }
1753
+ }
1754
+ this.pendingTitle = void 0;
1755
+ }
1756
+ };
1757
+ function extractSessionTabTargetFromBatchResults(data) {
1758
+ if (!Array.isArray(data)) {
1759
+ return void 0;
1760
+ }
1761
+ const observation = new BatchTargetObservation();
1762
+ for (const item of data) {
1763
+ if (isRecord(item)) {
1764
+ observation.observe(item);
1765
+ }
1766
+ }
1767
+ return observation.target;
1768
+ }
1769
+ function buildNoActivePageRefSnapshotInvalidation() {
1770
+ return {
1771
+ reason: "no-active-page",
1772
+ summary: "The latest snapshot for this session reported No active page. Old page-scoped refs are invalid until snapshot -i succeeds."
1773
+ };
1774
+ }
1775
+ function isNoActivePageSnapshotFailure(command, text) {
1776
+ return command === "snapshot" && /\bno active page\b/i.test(text ?? "");
1777
+ }
1778
+
1779
+ // dist/extensions/agent-browser/lib/results/artifact-manifest-validation.js
1780
+ function finiteNonnegative(value) {
1781
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
1782
+ }
1783
+ function safeCount(value) {
1784
+ return finiteNonnegative(value) && Number.isSafeInteger(value);
1785
+ }
1786
+ function optionalStrings(value, keys) {
1787
+ return keys.every((key) => value[key] === void 0 || typeof value[key] === "string");
1788
+ }
1789
+ function nullableStrings(value, keys) {
1790
+ return keys.every((key) => value[key] === null || typeof value[key] === "string");
1791
+ }
1792
+ function nullableNumbers(value, keys) {
1793
+ return keys.every((key) => value[key] === null || finiteNonnegative(value[key]));
1794
+ }
1795
+ function nullableBoolean(value) {
1796
+ return value === null || typeof value === "boolean";
1797
+ }
1798
+ function captureIsValid(value) {
1799
+ return nullableStrings(value, [
1800
+ "startedAt",
1801
+ "endedAt",
1802
+ "firstFrameAt",
1803
+ "lastFrameAt",
1804
+ "timestampSource"
1805
+ ]) && nullableNumbers(value, [
1806
+ "durationMs",
1807
+ "firstFrameAfterMs",
1808
+ "lastFrameAfterMs",
1809
+ "averageFps",
1810
+ "maxFrameGapMs"
1811
+ ]);
1812
+ }
1813
+ function outputIsValid(value) {
1814
+ return nullableStrings(value, ["durationSource"]) && nullableNumbers(value, [
1815
+ "frames",
1816
+ "fps",
1817
+ "encodedFrames",
1818
+ "durationMs",
1819
+ "heldFrames",
1820
+ "droppedFrames",
1821
+ "skippedFrames"
1822
+ ]) && nullableBoolean(value.encoderSucceeded);
1823
+ }
1824
+ function recordingIsValid(value) {
1825
+ if (!isRecord(value) || !isRecord(value.capture) || !isRecord(value.output) || !isRecord(value.file)) {
1826
+ return false;
1827
+ }
1828
+ return recordingScalarsAreValid(value) && captureIsValid(value.capture) && outputIsValid(value.output) && nullableBoolean(value.file.exists) && nullableNumbers(value.file, ["sizeBytes"]);
1829
+ }
1830
+ function recordingScalarsAreValid(value) {
1831
+ return typeof value.warning === "string" && typeof value.path === "string" && nullableStrings(value, ["recordingId", "error"]) && nullableBoolean(value.success) && nullableNumbers(value, ["frames", "capturedFrames", "fps"]);
1832
+ }
1833
+ function optionalNumbersAreValid(value) {
1834
+ return ["evictedAtMs", "recordingStartedAtMs"].every((key) => value[key] === void 0 || typeof value[key] === "number" && Number.isFinite(value[key])) && (value.sizeBytes === void 0 || finiteNonnegative(value.sizeBytes));
1835
+ }
1836
+ function optionalRecordingIsValid(value) {
1837
+ return (value.recordingState === void 0 || value.recordingState === "openRecording") && (value.recording === void 0 || recordingIsValid(value.recording)) && (value.status === void 0 || [
1838
+ "failed",
1839
+ "missing",
1840
+ "pending",
1841
+ "repaired-from-temp",
1842
+ "saved",
1843
+ "stale",
1844
+ "unverified",
1845
+ "upstream-temp-only"
1846
+ ].some((status) => status === value.status));
1847
+ }
1848
+ function optionalEvidenceIsValid(value) {
1849
+ return optionalStrings(value, [
1850
+ "absolutePath",
1851
+ "command",
1852
+ "cwd",
1853
+ "extension",
1854
+ "mediaType",
1855
+ "namespace",
1856
+ "requestedPath",
1857
+ "session",
1858
+ "subcommand"
1859
+ ]) && (value.exists === void 0 || typeof value.exists === "boolean") && optionalNumbersAreValid(value) && optionalRecordingIsValid(value);
1860
+ }
1861
+ function isManifestEntry(value) {
1862
+ if (!isRecord(value)) {
1863
+ return false;
1864
+ }
1865
+ return typeof value.path === "string" && value.path.trim().length > 0 && typeof value.createdAtMs === "number" && Number.isFinite(value.createdAtMs) && ["evicted", "ephemeral", "live", "missing"].some((state) => state === value.retentionState) && ["explicit-path", "persistent-session", "process-temp"].some((scope) => scope === value.storageScope) && ["download", "file", "har", "image", "pdf", "profile", "trace", "video", "spill"].some((kind) => kind === value.kind) && optionalEvidenceIsValid(value);
1866
+ }
1867
+ function manifestCountsAreValid(value) {
1868
+ return safeCount(value.maxEntries) && value.maxEntries !== 0 && safeCount(value.liveCount) && safeCount(value.evictedCount);
1869
+ }
1870
+ function isSessionArtifactManifest(value) {
1871
+ if (!isRecord(value)) {
1872
+ return false;
1873
+ }
1874
+ return value.version === 1 && Array.isArray(value.entries) && value.entries.every(isManifestEntry) && typeof value.updatedAtMs === "number" && Number.isFinite(value.updatedAtMs) && manifestCountsAreValid(value);
1875
+ }
1876
+
1877
+ // dist/extensions/agent-browser/lib/results/artifact-manifest.js
1878
+ function isPendingRecordingCommand(command, subcommand, kind) {
1879
+ return command === "record" && (subcommand === "start" || subcommand === "restart") && kind === "video";
1880
+ }
1881
+ function isPendingRecordingArtifact(artifact) {
1882
+ return artifact.recordingState === "openRecording" || artifact.status === "pending" || artifact.status === void 0 && isPendingRecordingCommand(artifact.command, artifact.subcommand, artifact.kind);
1883
+ }
1884
+ function getSessionArtifactManifestEntryKey(entry) {
1885
+ const pathKey = entry.storageScope === "explicit-path" && entry.absolutePath !== void 0 && entry.absolutePath.length > 0 ? `${entry.storageScope}:${entry.absolutePath}` : `${entry.storageScope}:${entry.path}`;
1886
+ const recordingSessionKey = entry.command === "record" && entry.kind === "video" && entry.session !== void 0 && entry.session.length > 0 ? getAgentBrowserSessionIdentityKey(entry.session, entry.namespace) : void 0;
1887
+ return recordingSessionKey !== void 0 && recordingSessionKey.length > 0 ? `${pathKey}\0${recordingSessionKey}` : pathKey;
1888
+ }
1889
+
1890
+ // dist/extensions/agent-browser/lib/results/presentation/common.js
1891
+ function getNestedLifecycleRow(row) {
1892
+ return isRecord(row) ? row.result ?? row.data ?? row : row;
1893
+ }
1894
+ function extractAgentBrowserLifecycle(result) {
1895
+ if (Array.isArray(result)) {
1896
+ let latest;
1897
+ for (const row of result) {
1898
+ const nested = getNestedLifecycleRow(row);
1899
+ latest = extractAgentBrowserLifecycle(nested) ?? latest;
1900
+ }
1901
+ return latest;
1902
+ }
1903
+ if (!isRecord(result)) {
1904
+ return void 0;
1905
+ }
1906
+ if (isRecord(result.lifecycle) && isRecord(result.lifecycle.effectiveLaunch)) {
1907
+ const browserLaunched = result.lifecycle.effectiveLaunch.browserLaunched;
1908
+ if (typeof browserLaunched === "boolean") {
1909
+ return { effectiveLaunch: { browserLaunched } };
1910
+ }
1911
+ }
1912
+ return extractAgentBrowserLifecycle(result.result ?? result.data);
1913
+ }
1914
+
1915
+ // dist/extensions/agent-browser/lib/browser-transcript-validation.js
1916
+ function invalidEvent() {
1917
+ throw new Error("Invalid browser event; inspect or convert the retained session before browser work.");
1918
+ }
1919
+ function invalidPage() {
1920
+ throw new Error("Invalid browser page disposition; refs cannot be restored.");
1921
+ }
1922
+ function parseInvalidation(value) {
1923
+ if (value === void 0) {
1924
+ return void 0;
1925
+ }
1926
+ if (!isRecord(value) || value.reason !== "page-transition" && value.reason !== "no-active-page" || typeof value.summary !== "string") {
1927
+ return invalidPage();
1928
+ }
1929
+ return { ...value, reason: value.reason, summary: value.summary };
1930
+ }
1931
+ function parseRefs(value) {
1932
+ if (!isRecord(value)) {
1933
+ return invalidPage();
1934
+ }
1935
+ if (value.kind === "reuse" || value.kind === "replace") {
1936
+ if (typeof value.snapshotId !== "string" || value.snapshotId.length === 0) {
1937
+ return invalidPage();
1938
+ }
1939
+ return { ...value, kind: value.kind, snapshotId: value.snapshotId };
1940
+ }
1941
+ if (value.kind !== "unknown" && value.kind !== "invalidate") {
1942
+ return invalidPage();
1943
+ }
1944
+ const invalidation = parseInvalidation(value.invalidation);
1945
+ return { ...value, kind: value.kind, ...invalidation ? { invalidation } : {} };
1946
+ }
1947
+ function decodeBrowserTarget(value) {
1948
+ if (!isRecord(value) || typeof value.url !== "string") {
1949
+ return void 0;
1950
+ }
1951
+ if (value.title !== void 0 && typeof value.title !== "string" || value.targetId !== void 0 && typeof value.targetId !== "string") {
1952
+ return void 0;
1953
+ }
1954
+ const target = { ...value, url: value.url };
1955
+ return normalizeSessionTabTarget(target) === void 0 ? void 0 : target;
1956
+ }
1957
+ function parseBrowserTarget(value) {
1958
+ if (value === void 0) {
1959
+ return void 0;
1960
+ }
1961
+ return decodeBrowserTarget(value) ?? invalidPage();
1962
+ }
1963
+ function pageScalarsValid(value) {
1964
+ return (value.confirmActions === void 0 || value.confirmActions === null || typeof value.confirmActions === "string") && (value.unknown === void 0 || value.unknown === true) && (value.clear === void 0 || value.clear === true);
1965
+ }
1966
+ function pagePolicyValid(value) {
1967
+ return (value.reopenPending === void 0 || typeof value.reopenPending === "boolean") && (value.pinningReason === void 0 || value.pinningReason === "restore" || value.pinningReason === "drift");
1968
+ }
1969
+ function parsePage(value) {
1970
+ if (!isRecord(value) || typeof value.key !== "string" || !pageScalarsValid(value) || !pagePolicyValid(value)) {
1971
+ return invalidPage();
1972
+ }
1973
+ const target = parseBrowserTarget(value.target);
1974
+ return { ...value, key: value.key, refs: parseRefs(value.refs), ...target ? { target } : {} };
1975
+ }
1976
+ function parsePages(value) {
1977
+ if (value === void 0) {
1978
+ return void 0;
1979
+ }
1980
+ if (!Array.isArray(value)) {
1981
+ return invalidPage();
1982
+ }
1983
+ const pages = value;
1984
+ return pages.map(parsePage);
1985
+ }
1986
+ function parseArtifacts(value) {
1987
+ if (value === void 0) {
1988
+ return void 0;
1989
+ }
1990
+ if (!isRecord(value) || !isBrowserStringArray(value.removals)) {
1991
+ throw new Error("Invalid browser artifact changes; inspect the retained journal.");
1992
+ }
1993
+ const manifest = {
1994
+ version: 1,
1995
+ entries: value.upserts,
1996
+ maxEntries: value.maxEntries,
1997
+ updatedAtMs: value.updatedAtMs,
1998
+ liveCount: 0,
1999
+ evictedCount: 0
2000
+ };
2001
+ if (!isSessionArtifactManifest(manifest)) {
2002
+ throw new Error("Invalid browser artifact changes; inspect the retained journal.");
2003
+ }
2004
+ return {
2005
+ ...value,
2006
+ upserts: manifest.entries,
2007
+ removals: value.removals,
2008
+ maxEntries: manifest.maxEntries,
2009
+ updatedAtMs: manifest.updatedAtMs
2010
+ };
2011
+ }
2012
+ function eventIdentity(value) {
2013
+ if (typeof value.operationId !== "string" || typeof value.toolCallId !== "string" || typeof value.commandIndex !== "number" || !Number.isSafeInteger(value.commandIndex) || value.commandIndex < 0 || typeof value.isError !== "boolean") {
2014
+ return invalidEvent();
2015
+ }
2016
+ return {
2017
+ operationId: value.operationId,
2018
+ toolCallId: value.toolCallId,
2019
+ commandIndex: value.commandIndex,
2020
+ isError: value.isError
2021
+ };
2022
+ }
2023
+ function parseBrowserEvent(value) {
2024
+ const phase = value.phase;
2025
+ if (phase !== "begin" && phase !== "finish" && phase !== "state") {
2026
+ return invalidEvent();
2027
+ }
2028
+ if (!isRecord(value.state)) {
2029
+ return invalidEvent();
2030
+ }
2031
+ const identity = eventIdentity(value);
2032
+ const pages = parsePages(value.pages);
2033
+ const artifacts = parseArtifacts(value.artifacts);
2034
+ return {
2035
+ ...value,
2036
+ ...identity,
2037
+ version: 1,
2038
+ phase,
2039
+ state: value.state,
2040
+ ...pages ? { pages } : {},
2041
+ ...artifacts ? { artifacts } : {}
2042
+ };
2043
+ }
2044
+
2045
+ // dist/extensions/agent-browser/lib/browser-transcript.js
2046
+ var BROWSER_EVENT_VERSION = 1;
2047
+ function browserStateEffects(details) {
2048
+ const state = Object.fromEntries(BROWSER_STATE_FIELDS.filter((key) => details[key] !== void 0).map((key) => [
2049
+ key,
2050
+ details[key]
2051
+ ]));
2052
+ if (Array.isArray(details.batchSteps)) {
2053
+ state.batchSteps = details.batchSteps.filter(isRecord).map((step) => ({
2054
+ command: step.command,
2055
+ success: step.success,
2056
+ lifecycle: extractAgentBrowserLifecycle(step)
2057
+ }));
2058
+ }
2059
+ if (isRecord(details.electron) && (details.electron.launch !== void 0 || details.electron.cleanup !== void 0)) {
2060
+ state.electron = { launch: details.electron.launch, cleanup: details.electron.cleanup };
2061
+ }
2062
+ return state;
2063
+ }
2064
+ function getBrowserRecord(entry) {
2065
+ if (!isRecord(entry) || !isRecord(entry.data)) {
2066
+ return void 0;
2067
+ }
2068
+ if (entry.type !== "message" && !(entry.type === "custom" && entry.customType === BROWSER_TRANSITION_ENTRY)) {
2069
+ return void 0;
2070
+ }
2071
+ const event = entry.data.event;
2072
+ if (!isRecord(event) || event.version !== BROWSER_EVENT_VERSION) {
2073
+ return void 0;
2074
+ }
2075
+ return { ...entry.data, event: parseBrowserEvent(event) };
2076
+ }
2077
+ function snapshotDefinition(snapshot) {
2078
+ if (snapshot.snapshotId === void 0 || snapshot.snapshotId.length === 0) {
2079
+ throw new Error("A snapshot capture must have an identity before publication.");
2080
+ }
2081
+ return {
2082
+ id: snapshot.snapshotId,
2083
+ refs: Object.fromEntries(snapshot.refIds.map((id) => [id, snapshot.refs?.[id] ?? {}])),
2084
+ target: snapshot.target,
2085
+ generation: snapshot.generation
2086
+ };
2087
+ }
2088
+ function indexedArtifacts(manifest) {
2089
+ return new Map((manifest?.entries ?? []).map((row) => [getSessionArtifactManifestEntryKey(row), row]));
2090
+ }
2091
+ function redactedArtifact(row) {
2092
+ const manifest = {
2093
+ version: 1,
2094
+ entries: [redactSensitiveValue(row)],
2095
+ maxEntries: 1,
2096
+ updatedAtMs: row.createdAtMs,
2097
+ liveCount: 0,
2098
+ evictedCount: 0
2099
+ };
2100
+ if (!isSessionArtifactManifest(manifest)) {
2101
+ throw new Error("Redacted browser artifact has no valid manifest receipt.");
2102
+ }
2103
+ return manifest.entries[0];
2104
+ }
2105
+ function artifactChanges(previous, next) {
2106
+ if (previous === next) {
2107
+ return void 0;
2108
+ }
2109
+ const before = indexedArtifacts(previous);
2110
+ const after = indexedArtifacts(next);
2111
+ const upserts = [...after].filter(([key, row]) => JSON.stringify(before.get(key)) !== JSON.stringify(row)).map(([, row]) => redactedArtifact(row));
2112
+ const removals = [...before.keys()].filter((key) => !after.has(key));
2113
+ return upserts.length > 0 || removals.length > 0 ? {
2114
+ upserts,
2115
+ removals,
2116
+ maxEntries: (next ?? previous)?.maxEntries ?? 100,
2117
+ updatedAtMs: next?.updatedAtMs ?? Date.now()
2118
+ } : void 0;
2119
+ }
2120
+ function applyArtifactChanges(previous, changes) {
2121
+ if (!changes) {
2122
+ return previous;
2123
+ }
2124
+ const rows = new Map((previous?.entries ?? []).map((row) => [getSessionArtifactManifestEntryKey(row), row]));
2125
+ for (const key of changes.removals) {
2126
+ rows.delete(key);
2127
+ }
2128
+ for (const row of changes.upserts) {
2129
+ rows.set(getSessionArtifactManifestEntryKey(row), row);
2130
+ }
2131
+ const entries = [...rows.values()].sort((a, b) => {
2132
+ const age = (b.evictedAtMs ?? b.createdAtMs) - (a.evictedAtMs ?? a.createdAtMs);
2133
+ if (age !== 0) {
2134
+ return age;
2135
+ }
2136
+ const pending = Number(isPendingRecordingArtifact(b)) - Number(isPendingRecordingArtifact(a));
2137
+ return pending !== 0 ? pending : a.path.localeCompare(b.path);
2138
+ }).slice(0, changes.maxEntries);
2139
+ const manifest = {
2140
+ version: 1,
2141
+ entries,
2142
+ maxEntries: changes.maxEntries,
2143
+ updatedAtMs: changes.updatedAtMs,
2144
+ liveCount: entries.filter((row) => row.retentionState === "live").length,
2145
+ evictedCount: entries.filter((row) => row.retentionState === "evicted").length
2146
+ };
2147
+ if (!isSessionArtifactManifest(manifest)) {
2148
+ throw new Error("Invalid browser artifact changes; inspect the retained journal.");
2149
+ }
2150
+ return entries.length > 0 ? manifest : void 0;
2151
+ }
2152
+
2153
+ // dist/extensions/agent-browser/lib/browser-legacy-pages.js
2154
+ import { createHash } from "node:crypto";
2155
+ function legacyTarget(value) {
2156
+ return normalizeSessionTabTarget({
2157
+ url: typeof value.url === "string" ? value.url : void 0,
2158
+ title: typeof value.title === "string" ? value.title : void 0,
2159
+ targetId: typeof value.targetId === "string" ? value.targetId : void 0
2160
+ });
2161
+ }
2162
+ function legacySnapshot(value, id) {
2163
+ if (!isRecord(value) || !Array.isArray(value.refIds)) {
2164
+ return void 0;
2165
+ }
2166
+ const refIds = browserStringArray(value.refIds).filter((ref) => /^e\d+$/.test(ref));
2167
+ const sourceRefs = isRecord(value.refs) ? value.refs : {};
2168
+ return snapshotDefinition({
2169
+ snapshotId: typeof value.snapshotId === "string" ? value.snapshotId : id,
2170
+ refIds,
2171
+ generation: typeof value.generation === "string" ? value.generation : void 0,
2172
+ refs: Object.fromEntries(refIds.flatMap((refId) => {
2173
+ const ref = sourceRefs[refId];
2174
+ if (!isRecord(ref) || typeof ref.name !== "string" || typeof ref.role !== "string") {
2175
+ return [];
2176
+ }
2177
+ return [
2178
+ [
2179
+ refId,
2180
+ {
2181
+ name: ref.name,
2182
+ role: ref.role,
2183
+ ...typeof ref.isEditable === "boolean" ? { isEditable: ref.isEditable } : {},
2184
+ ...typeof ref.isContentEditable === "boolean" ? { isContentEditable: ref.isContentEditable } : {}
2185
+ }
2186
+ ]
2187
+ ];
2188
+ })),
2189
+ target: isRecord(value.target) ? legacyTarget(value.target) : void 0
2190
+ });
2191
+ }
2192
+ function snapshotDigest(definition) {
2193
+ return createHash("sha256").update(JSON.stringify({
2194
+ refs: definition.refs,
2195
+ target: definition.target,
2196
+ generation: definition.generation
2197
+ })).digest("hex");
2198
+ }
2199
+ function canonicalPage(prior, canonical, page) {
2200
+ const definition = isRecord(canonical.snapshot) ? canonical.snapshot : void 0;
2201
+ const digest = definition !== void 0 && Boolean(definition.refs) ? snapshotDigest(definition) : prior.snapshot?.digest ?? "";
2202
+ let snapshot;
2203
+ if (page.refs.kind === "replace" || page.refs.kind === "reuse") {
2204
+ snapshot = { id: page.refs.snapshotId, digest, usable: true, candidate: false };
2205
+ } else if (prior.snapshot) {
2206
+ snapshot = { ...prior.snapshot, usable: false, candidate: canonical.event.phase === "begin" };
2207
+ }
2208
+ return {
2209
+ target: page.target,
2210
+ unknown: page.unknown,
2211
+ reopenPending: page.reopenPending,
2212
+ snapshot,
2213
+ pending: canonical.event.phase === "begin" ? {
2214
+ operationId: canonical.event.operationId,
2215
+ toolCallId: canonical.event.toolCallId,
2216
+ index: canonical.event.commandIndex
2217
+ } : void 0
2218
+ };
2219
+ }
2220
+ function parseInvalidation2(value, fallbackSummary) {
2221
+ if (!isRecord(value)) {
2222
+ return void 0;
2223
+ }
2224
+ if (value.reason !== "no-active-page" && value.reason !== "page-transition") {
2225
+ throw new Error("Invalid legacy browser ref invalidation.");
2226
+ }
2227
+ if (typeof value.summary === "string") {
2228
+ return { reason: value.reason, summary: value.summary };
2229
+ }
2230
+ if (fallbackSummary) {
2231
+ return {
2232
+ reason: value.reason,
2233
+ summary: "The prior refs were invalidated; take a fresh snapshot."
2234
+ };
2235
+ }
2236
+ throw new Error("Invalid legacy browser ref invalidation summary.");
2237
+ }
2238
+ function observedInvalidation(ctx) {
2239
+ const value = ctx.details.refSnapshotInvalidation;
2240
+ if (isRecord(value) && (value.reason === "no-active-page" || value.reason === "page-transition")) {
2241
+ return parseInvalidation2(value, true);
2242
+ }
2243
+ let error;
2244
+ if (typeof ctx.details.error === "string") {
2245
+ error = ctx.details.error;
2246
+ } else if (typeof ctx.details.summary === "string") {
2247
+ error = ctx.details.summary;
2248
+ }
2249
+ return isNoActivePageSnapshotFailure(ctx.command, error) ? buildNoActivePageRefSnapshotInvalidation() : void 0;
2250
+ }
2251
+ function snapshotReusable(page, details, digest) {
2252
+ return page.snapshot?.digest === digest && (page.snapshot.usable || page.snapshot.candidate) && (!isRecord(details.refSnapshot) || typeof details.refSnapshot.snapshotId !== "string" || details.refSnapshot.snapshotId === page.snapshot.id);
2253
+ }
2254
+ var LegacyPageConversion = class {
2255
+ ctx;
2256
+ page;
2257
+ definition;
2258
+ constructor(ctx, prior) {
2259
+ this.ctx = ctx;
2260
+ this.page = { ...prior };
2261
+ }
2262
+ knownTarget() {
2263
+ const { details, command, subcommand } = this.ctx;
2264
+ if (!isRecord(details.compiledNetworkSourceLookup) && !isReadOnlyDiagnosticSessionTargetCommand(command, subcommand) && isRecord(details.sessionTabTarget)) {
2265
+ this.page.target = legacyTarget(details.sessionTabTarget) ?? this.page.target;
2266
+ } else if (command === "batch" && !isRecord(details.compiledNetworkSourceLookup)) {
2267
+ this.page.target = extractSessionTabTargetFromBatchResults(details.data) ?? this.page.target;
2268
+ }
2269
+ if (this.page.target) {
2270
+ this.page.unknown = void 0;
2271
+ }
2272
+ if (typeof details.sessionTabReopenPending === "boolean") {
2273
+ this.page.reopenPending = details.sessionTabReopenPending;
2274
+ }
2275
+ }
2276
+ knownRefs() {
2277
+ const invalidation = observedInvalidation(this.ctx);
2278
+ const candidate = invalidation ? void 0 : legacySnapshot(this.ctx.details.refSnapshot, `snapshot-${this.ctx.nativeId}`);
2279
+ if (candidate) {
2280
+ const digest = snapshotDigest(candidate);
2281
+ let refs;
2282
+ if (snapshotReusable(this.page, this.ctx.details, digest) && this.page.snapshot) {
2283
+ refs = { kind: "reuse", snapshotId: this.page.snapshot.id };
2284
+ } else {
2285
+ this.definition = candidate;
2286
+ refs = { kind: "replace", snapshotId: candidate.id };
2287
+ }
2288
+ this.page.snapshot = { id: refs.snapshotId, digest, usable: true, candidate: false };
2289
+ return refs;
2290
+ }
2291
+ if (invalidation) {
2292
+ this.disableSnapshot(false);
2293
+ return { kind: "invalidate", invalidation };
2294
+ }
2295
+ return this.page.snapshot?.usable === true ? { kind: "reuse", snapshotId: this.page.snapshot.id } : { kind: "invalidate" };
2296
+ }
2297
+ disableSnapshot(candidate) {
2298
+ if (this.page.snapshot) {
2299
+ this.page.snapshot = { ...this.page.snapshot, usable: false, candidate };
2300
+ }
2301
+ }
2302
+ change(key) {
2303
+ return {
2304
+ ...this.pageChange(key),
2305
+ ...typeof this.ctx.details.sessionConfirmActions === "string" || this.ctx.details.sessionConfirmActions === null ? { confirmActions: this.ctx.details.sessionConfirmActions } : {}
2306
+ };
2307
+ }
2308
+ pageChange(key) {
2309
+ const ctx = this.ctx;
2310
+ if (ctx.begin) {
2311
+ this.page.target = void 0;
2312
+ this.page.unknown = true;
2313
+ this.page.snapshot = ctx.prior.snapshot ? { ...ctx.prior.snapshot, usable: false, candidate: true } : void 0;
2314
+ this.page.pending = {
2315
+ toolCallId: ctx.toolCallId,
2316
+ operationId: ctx.operationId,
2317
+ index: ctx.commandIndex
2318
+ };
2319
+ return { key, refs: { kind: "unknown" }, unknown: true };
2320
+ }
2321
+ if (ctx.details.sessionTabTargetUnknown === true) {
2322
+ this.page.target = void 0;
2323
+ this.page.unknown = true;
2324
+ this.page.pending = void 0;
2325
+ this.disableSnapshot(false);
2326
+ return {
2327
+ key,
2328
+ refs: {
2329
+ kind: "unknown",
2330
+ invalidation: parseInvalidation2(ctx.details.refSnapshotInvalidation, false)
2331
+ },
2332
+ unknown: true
2333
+ };
2334
+ }
2335
+ this.knownTarget();
2336
+ const refs = this.knownRefs();
2337
+ this.page.pending = void 0;
2338
+ return {
2339
+ key,
2340
+ target: this.page.target,
2341
+ unknown: this.page.unknown,
2342
+ reopenPending: this.page.reopenPending,
2343
+ refs
2344
+ };
2345
+ }
2346
+ };
2347
+
2348
+ // dist/extensions/agent-browser/lib/browser-conversion-branches.js
2349
+ var BrowserConversionBranches = class {
2350
+ states = /* @__PURE__ */ new Map();
2351
+ children = /* @__PURE__ */ new Map();
2352
+ constructor(parentIds) {
2353
+ for (const id of parentIds) {
2354
+ if (typeof id === "string") {
2355
+ this.children.set(id, (this.children.get(id) ?? 0) + 1);
2356
+ }
2357
+ }
2358
+ }
2359
+ get(id) {
2360
+ return this.states.get(id);
2361
+ }
2362
+ advance(id, parentId, projection) {
2363
+ if (typeof parentId === "string") {
2364
+ const remaining = (this.children.get(parentId) ?? 0) - 1;
2365
+ if (remaining > 0) {
2366
+ this.children.set(parentId, remaining);
2367
+ } else {
2368
+ this.children.delete(parentId);
2369
+ this.states.delete(parentId);
2370
+ }
2371
+ }
2372
+ if (this.children.has(id)) {
2373
+ this.states.set(id, projection);
2374
+ }
2375
+ }
2376
+ };
2377
+
2378
+ // dist/extensions/agent-browser/lib/browser-legacy-projection.js
2379
+ var emptyProjection = () => ({ pages: /* @__PURE__ */ new Map(), nextIndex: 0 });
2380
+ function legacyMessage(entry) {
2381
+ if (entry.type === "custom" && entry.customType === BROWSER_TRANSITION_ENTRY && isRecord(entry.data) && isRecord(entry.data.details)) {
2382
+ return entry.data;
2383
+ }
2384
+ const message = entry.type === "message" && isRecord(entry.message) ? entry.message : void 0;
2385
+ return isLegacyToolMessage(message) ? message : void 0;
2386
+ }
2387
+ function isLegacyToolMessage(message) {
2388
+ return message !== void 0 && typeof message.toolName === "string" && BROWSER_RESULT_TOOLS.has(message.toolName) && isRecord(message.details) && message.details.browserEventVersion !== 1;
2389
+ }
2390
+ function applyCanonical(current, parent, canonical) {
2391
+ current.manifest = applyArtifactChanges(parent.manifest, canonical.event.artifacts);
2392
+ for (const page of canonical.event.pages ?? []) {
2393
+ if (page.clear === true) {
2394
+ current.pages.delete(page.key);
2395
+ continue;
2396
+ }
2397
+ current.pages.set(page.key, canonicalPage(current.pages.get(page.key) ?? {}, canonical, page));
2398
+ }
2399
+ }
2400
+ function scriptRecord(entry, nativeId, ownerSessionId) {
2401
+ if (entry.type !== "custom" || entry.customType !== "agent-browser-script-session" || !isRecord(entry.data)) {
2402
+ return void 0;
2403
+ }
2404
+ return {
2405
+ event: {
2406
+ version: 1,
2407
+ phase: "state",
2408
+ operationId: `legacy-${nativeId}`,
2409
+ toolCallId: `legacy-${nativeId}`,
2410
+ commandIndex: 0,
2411
+ isError: entry.data.cleanup !== "closed",
2412
+ state: {
2413
+ scriptLease: { ...entry.data, ownerSessionId: entry.data.ownerSessionId ?? ownerSessionId }
2414
+ }
2415
+ }
2416
+ };
2417
+ }
2418
+ function isLegacyBegin(entry, details) {
2419
+ return entry.type === "custom" && details.sessionTabTargetUnknown === true && details.command === void 0 && details.exitCode === void 0 && details.agentBrowserStarted === void 0;
2420
+ }
2421
+ function legacyIdentity(details) {
2422
+ const sessionName = typeof details.sessionName === "string" ? details.sessionName : void 0;
2423
+ const namespace = typeof details.namespace === "string" ? details.namespace : void 0;
2424
+ const key = sessionName !== void 0 && sessionName.length > 0 ? getAgentBrowserSessionIdentityKey(sessionName, namespace) : void 0;
2425
+ const tokens = extractUpstreamCommandTokens(browserStringArray(details.args));
2426
+ return {
2427
+ key,
2428
+ namespace,
2429
+ tokens,
2430
+ command: typeof details.command === "string" ? details.command : tokens[0],
2431
+ subcommand: typeof details.subcommand === "string" ? details.subcommand : tokens[1]
2432
+ };
2433
+ }
2434
+ function legacyPrior(key, current) {
2435
+ return key === void 0 ? {} : current.pages.get(key) ?? {};
2436
+ }
2437
+ function operationIdentity(options, current) {
2438
+ const prior = legacyPrior(options.key, current);
2439
+ const begin = isLegacyBegin(options.entry, options.details);
2440
+ const pending = prior.pending?.toolCallId === options.toolCallId ? prior.pending : void 0;
2441
+ let phase = "state";
2442
+ if (begin) {
2443
+ phase = "begin";
2444
+ } else if (pending) {
2445
+ phase = "finish";
2446
+ }
2447
+ let commandIndex = pending?.index ?? 0;
2448
+ if (begin) {
2449
+ commandIndex = current.nextIndex;
2450
+ current.nextIndex++;
2451
+ }
2452
+ return {
2453
+ prior,
2454
+ begin,
2455
+ phase,
2456
+ commandIndex,
2457
+ operationId: pending?.operationId ?? `legacy-${options.nativeId}`
2458
+ };
2459
+ }
2460
+ function normalizeLegacyBatchStep(step) {
2461
+ return step.success === true && isSuccessfulNativeConfirmedClose(browserStringArray(step.command), step.data) ? { ...step, command: ["close"] } : step;
2462
+ }
2463
+ function normalizeLegacyDetails(details, isError) {
2464
+ const closed = !isError && isSuccessfulNativeConfirmedClose(extractUpstreamCommandTokens(browserStringArray(details.args)), details.data);
2465
+ const batchSteps = Array.isArray(details.batchSteps) ? details.batchSteps.filter(isRecord).map(normalizeLegacyBatchStep) : void 0;
2466
+ return {
2467
+ ...details,
2468
+ ...closed ? { command: "close", subcommand: void 0 } : {},
2469
+ ...batchSteps !== void 0 ? { batchSteps } : {}
2470
+ };
2471
+ }
2472
+ function context(entry, message, details, current) {
2473
+ const nativeId = typeof entry.id === "string" ? entry.id : randomUUID();
2474
+ const toolCallId = typeof message.toolCallId === "string" ? message.toolCallId : `legacy-${nativeId}`;
2475
+ const replayDetails = normalizeLegacyDetails(details, message.isError === true);
2476
+ const identity = legacyIdentity(replayDetails);
2477
+ const operation = operationIdentity({ entry, details: replayDetails, key: identity.key, toolCallId, nativeId }, current);
2478
+ return {
2479
+ ...identity,
2480
+ ...operation,
2481
+ nativeId,
2482
+ details: replayDetails,
2483
+ isError: message.isError === true,
2484
+ toolCallId
2485
+ };
2486
+ }
2487
+ function closingLifecycle(ctx) {
2488
+ const close = getSuccessfulBatchCloseLifecycle(ctx.details.batchSteps);
2489
+ const closeAll = ctx.details.closeAllApplied === true || !ctx.isError && isCloseAllCommand(ctx.tokens) || batchHasSuccessfulCloseAll(ctx.details.batchSteps);
2490
+ return {
2491
+ closeAll,
2492
+ lifecycleReset: !ctx.isError && isCloseCommand(ctx.command) || close !== void 0,
2493
+ endsClosed: close?.endsClosed === true
2494
+ };
2495
+ }
2496
+ function closePages(current, ctx) {
2497
+ const closing = closingLifecycle(ctx);
2498
+ const pages = [];
2499
+ if (closing.closeAll) {
2500
+ for (const key of current.pages.keys()) {
2501
+ if (isAgentBrowserSessionIdentityKeyInNamespace(key, ctx.namespace)) {
2502
+ current.pages.delete(key);
2503
+ pages.push({ key, clear: true, refs: { kind: "invalidate" } });
2504
+ }
2505
+ }
2506
+ } else if (ctx.key !== void 0 && closing.lifecycleReset) {
2507
+ current.pages.delete(ctx.key);
2508
+ pages.push({ key: ctx.key, clear: true, refs: { kind: "invalidate" } });
2509
+ }
2510
+ return { ...closing, pages };
2511
+ }
2512
+ function hasPageEffects(ctx) {
2513
+ return ctx.begin || [
2514
+ "sessionTabTargetUnknown",
2515
+ "sessionTabTarget",
2516
+ "sessionTabReopenPending",
2517
+ "sessionConfirmActions",
2518
+ "refSnapshot",
2519
+ "refSnapshotInvalidation"
2520
+ ].some((field) => ctx.details[field] !== void 0) || ctx.command === "batch" && Array.isArray(ctx.details.data);
2521
+ }
2522
+ function stampElectronState(state, ownerSessionId) {
2523
+ if (!isRecord(state.electron)) {
2524
+ return state;
2525
+ }
2526
+ const stamp = (value) => isRecord(value) ? { ...value, ownerSessionId: value.ownerSessionId ?? ownerSessionId } : value;
2527
+ const cleanup = isRecord(state.electron.cleanup) ? state.electron.cleanup : void 0;
2528
+ return {
2529
+ ...state,
2530
+ electron: {
2531
+ ...state.electron,
2532
+ launch: stamp(state.electron.launch),
2533
+ ...cleanup ? {
2534
+ cleanup: {
2535
+ ...cleanup,
2536
+ records: Array.isArray(cleanup.records) ? cleanup.records.map(stamp) : cleanup.records,
2537
+ results: Array.isArray(cleanup.results) ? cleanup.results.map((row) => isRecord(row) ? { ...row, record: stamp(row.record) } : row) : cleanup.results
2538
+ }
2539
+ } : {}
2540
+ }
2541
+ };
2542
+ }
2543
+ function updateManifest(current, parent, details) {
2544
+ if (isSessionArtifactManifest(details.artifactManifest) && (!parent.manifest || details.artifactManifest.updatedAtMs >= parent.manifest.updatedAtMs)) {
2545
+ current.manifest = details.artifactManifest;
2546
+ }
2547
+ const changes = artifactChanges(parent.manifest, current.manifest);
2548
+ if (!changes) {
2549
+ current.manifest = parent.manifest;
2550
+ }
2551
+ return changes;
2552
+ }
2553
+ function convertMessage(ctx, parent, current, ownerSessionId) {
2554
+ const closing = closePages(current, ctx);
2555
+ const pages = closing.pages;
2556
+ let definition;
2557
+ const suppressPage = (closing.closeAll || closing.lifecycleReset) && (isCloseCommand(ctx.command) || closing.endsClosed);
2558
+ if (ctx.key !== void 0 && hasPageEffects(ctx) && !suppressPage) {
2559
+ const conversion = new LegacyPageConversion(ctx, current.pages.get(ctx.key) ?? {});
2560
+ pages.push(conversion.change(ctx.key));
2561
+ current.pages.set(ctx.key, conversion.page);
2562
+ definition = conversion.definition;
2563
+ }
2564
+ const artifacts = updateManifest(current, parent, ctx.details);
2565
+ return {
2566
+ event: {
2567
+ version: 1,
2568
+ phase: ctx.phase,
2569
+ operationId: ctx.operationId,
2570
+ toolCallId: ctx.toolCallId,
2571
+ commandIndex: ctx.commandIndex,
2572
+ isError: ctx.isError,
2573
+ state: stampElectronState(browserStateEffects(ctx.details), ownerSessionId),
2574
+ pages,
2575
+ artifacts
2576
+ },
2577
+ ...definition ? { snapshot: definition } : {}
2578
+ };
2579
+ }
2580
+ function hasCanonicalBrowserEvent(entry) {
2581
+ return isRecord(entry.data) && Object.hasOwn(entry.data, "event") && (entry.type === "message" || entry.customType === BROWSER_TRANSITION_ENTRY);
2582
+ }
2583
+ function convertLegacyBrowserEntry(entry, parent = emptyProjection(), ownerSessionId) {
2584
+ const current = {
2585
+ pages: new Map(parent.pages),
2586
+ manifest: parent.manifest,
2587
+ nextIndex: parent.nextIndex
2588
+ };
2589
+ const canonical = getBrowserRecord(entry);
2590
+ if (canonical) {
2591
+ applyCanonical(current, parent, canonical);
2592
+ return { projection: current };
2593
+ }
2594
+ if (hasCanonicalBrowserEvent(entry)) {
2595
+ throw new Error("Invalid browser event; legacy replay cannot bypass canonical validation.");
2596
+ }
2597
+ const script = scriptRecord(entry, typeof entry.id === "string" ? entry.id : randomUUID(), ownerSessionId);
2598
+ if (script) {
2599
+ return { record: script, projection: current };
2600
+ }
2601
+ const message = legacyMessage(entry);
2602
+ if (!message || !isRecord(message.details)) {
2603
+ return { projection: parent };
2604
+ }
2605
+ return {
2606
+ record: convertMessage(context(entry, message, message.details, current), parent, current, ownerSessionId),
2607
+ projection: current
2608
+ };
2609
+ }
2610
+ function archiveParent(value, branches, linear) {
2611
+ if (typeof value.parentId === "string") {
2612
+ return branches.get(value.parentId) ?? emptyProjection();
2613
+ }
2614
+ return Object.hasOwn(value, "parentId") ? emptyProjection() : linear;
2615
+ }
2616
+ function convertBrowserEntries(entries, ownerSessionId) {
2617
+ const branches = new BrowserConversionBranches(entries.map((value) => isRecord(value) ? value.parentId : void 0));
2618
+ let linear = emptyProjection();
2619
+ return entries.map((value, index) => {
2620
+ if (!isRecord(value)) {
2621
+ return value;
2622
+ }
2623
+ const entry = {
2624
+ ...value,
2625
+ id: typeof value.id === "string" ? value.id : `archive-${index}`,
2626
+ parentId: value.parentId ?? null
2627
+ };
2628
+ const converted = convertLegacyBrowserEntry(entry, archiveParent(value, branches, linear), ownerSessionId);
2629
+ branches.advance(entry.id, value.parentId, converted.projection);
2630
+ linear = converted.projection;
2631
+ return converted.record ? {
2632
+ ...entry,
2633
+ ...entry.type === "custom" ? { customType: BROWSER_TRANSITION_ENTRY } : {},
2634
+ data: converted.record
2635
+ } : entry;
2636
+ });
2637
+ }
2638
+
2639
+ // dist/extensions/agent-browser/lib/browser-legacy-fields.js
2640
+ var DETAILS_FIELDS = [
2641
+ ...BROWSER_STATE_FIELDS,
2642
+ "browserEventVersion",
2643
+ "electron",
2644
+ "compiledNetworkSourceLookup",
2645
+ "sessionTabTarget",
2646
+ "sessionTabTargetUnknown",
2647
+ "sessionTabReopenPending",
2648
+ "sessionConfirmActions",
2649
+ "refSnapshot",
2650
+ "refSnapshotInvalidation",
2651
+ "artifactManifest",
2652
+ "error",
2653
+ "summary"
2654
+ ];
2655
+ var CONFIRMED_CLOSE_FIELDS = [
2656
+ ["confirmed"],
2657
+ ["action"],
2658
+ ["result", "success"],
2659
+ ["result", "data", "closed"]
2660
+ ];
2661
+ var LEGACY_BROWSER_FIELDS = [
2662
+ ["data", "event"],
2663
+ ["data", "snapshot"],
2664
+ ["data", "cleanup"],
2665
+ ["data", "sessionName"],
2666
+ ["data", "ownerSessionId"],
2667
+ ["data", "closeCommandArgs"],
2668
+ ["data", "launchAttempted"],
2669
+ ["data", "toolCallId"],
2670
+ ["data", "isError"],
2671
+ ["message", "toolName"],
2672
+ ["message", "toolCallId"],
2673
+ ["message", "isError"],
2674
+ ...["data", "message"].flatMap((root) => DETAILS_FIELDS.map((field) => [root, "details", field])),
2675
+ ...["data", "message"].flatMap((root) => CONFIRMED_CLOSE_FIELDS.flatMap((field) => [
2676
+ [root, "details", "data", ...field],
2677
+ [root, "details", "batchSteps", "*", "data", ...field]
2678
+ ])),
2679
+ ...["data", "message"].flatMap((root) => ["command", "success", "lifecycle"].map((field) => [root, "details", "batchSteps", "*", field]).concat([
2680
+ ["data", "lifecycle"],
2681
+ ["result", "lifecycle"]
2682
+ ].map((field) => [root, "details", "batchSteps", "*"].concat(field)))),
2683
+ ...["data", "message"].flatMap((root) => ["command", "success", "error"].map((field) => [root, "details", "data", "*", field]).concat(["url", "title", "origin", "targetId"].map((field) => [
2684
+ root,
2685
+ "details",
2686
+ "data",
2687
+ "*",
2688
+ "result",
2689
+ field
2690
+ ])))
2691
+ ];
2692
+
2693
+ // dist/extensions/agent-browser/lib/browser-session-conversion-stream.js
2694
+ async function sourceChecksum(file, size) {
2695
+ const hash = createHash2("sha256");
2696
+ for await (const chunk of readRange(file, { offset: 0, length: size })) {
2697
+ hash.update(chunk);
2698
+ }
2699
+ return hash.digest("hex");
2700
+ }
2701
+ async function writeBytes(file, chunks2) {
2702
+ for await (const chunk of chunks2) {
2703
+ const buffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
2704
+ let offset = 0;
2705
+ while (offset < buffer.length) {
2706
+ const { bytesWritten } = await file.write(buffer, offset, buffer.length - offset);
2707
+ if (bytesWritten === 0) {
2708
+ throw new Error("Could not write converted journal.");
2709
+ }
2710
+ offset += bytesWritten;
2711
+ }
2712
+ }
2713
+ }
2714
+ async function* decodeRange(file, range) {
2715
+ const decoder = new TextDecoder("utf-8", { fatal: true });
2716
+ for await (const bytes of readRange(file, range)) {
2717
+ yield decoder.decode(bytes, { stream: true });
2718
+ }
2719
+ const tail = decoder.decode();
2720
+ if (tail.length > 0) {
2721
+ yield tail;
2722
+ }
2723
+ }
2724
+ async function rewriteMessage(file, range, destination, record) {
2725
+ const tokenizer = tokenizeJson.asStream({ packValues: false, packKeys: true, streamKeys: false });
2726
+ const filter = ignoreJson.asStream({
2727
+ filter: /^(?:data|message\.details\.(?:refSnapshot|artifactManifest|browserEventVersion))$/
2728
+ });
2729
+ async function* inject(tokens) {
2730
+ let depth = 0;
2731
+ for await (const token of tokens) {
2732
+ if (token.name === "startObject" || token.name === "startArray") {
2733
+ depth++;
2734
+ }
2735
+ if (token.name === "endObject" || token.name === "endArray") {
2736
+ depth--;
2737
+ if (depth === 0) {
2738
+ const key = { name: "keyValue", value: "data" };
2739
+ yield key;
2740
+ yield* disassembleJson({ packValues: false, packKeys: true, streamKeys: false })(record);
2741
+ }
2742
+ }
2743
+ yield token;
2744
+ }
2745
+ }
2746
+ const output = stringifyJson.asStream({ useKeyValues: true });
2747
+ const processing = pipeline(Readable.from(decodeRange(file, range)), tokenizer, filter, inject, output);
2748
+ try {
2749
+ await Promise.all([writeBytes(destination, output), processing]);
2750
+ } finally {
2751
+ tokenizer.destroy();
2752
+ filter.destroy();
2753
+ output.destroy();
2754
+ }
2755
+ await destination.write("\n");
2756
+ }
2757
+ function isLegacyBrowserEntry(value) {
2758
+ if (value.type === "custom" && typeof value.customType === "string" && [BROWSER_TRANSITION_ENTRY, "agent-browser-script-session"].includes(value.customType)) {
2759
+ return true;
2760
+ }
2761
+ return isRecord(value.message) && typeof value.message.toolName === "string" && BROWSER_RESULT_TOOLS.has(value.message.toolName);
2762
+ }
2763
+ var BrowserConversionWriter = class {
2764
+ file;
2765
+ stage;
2766
+ source;
2767
+ ids = /* @__PURE__ */ new Set();
2768
+ branches;
2769
+ convertedRecords = 0;
2770
+ snapshotDefinitions = 0;
2771
+ constructor(file, stage, source, metadata) {
2772
+ this.file = file;
2773
+ this.stage = stage;
2774
+ this.source = source;
2775
+ this.branches = new BrowserConversionBranches(metadata.map((entry) => entry.value.type === "session" ? void 0 : entry.value.parentId));
2776
+ }
2777
+ get counts() {
2778
+ return {
2779
+ entryCount: this.ids.size,
2780
+ convertedRecords: this.convertedRecords,
2781
+ snapshotDefinitions: this.snapshotDefinitions
2782
+ };
2783
+ }
2784
+ async conversion(entry) {
2785
+ if (entry.value.type === "session") {
2786
+ return void 0;
2787
+ }
2788
+ const id = entry.value.id;
2789
+ if (typeof id !== "string" || this.ids.has(id)) {
2790
+ throw new Error("Conversion source contains a missing or duplicate native entry ID.");
2791
+ }
2792
+ const parentId = entry.value.parentId;
2793
+ if (parentId !== null && (typeof parentId !== "string" || !this.ids.has(parentId))) {
2794
+ throw new Error("Conversion source contains a missing or forward parent.");
2795
+ }
2796
+ this.ids.add(id);
2797
+ const parent = typeof parentId === "string" ? this.branches.get(parentId) ?? emptyProjection() : emptyProjection();
2798
+ if (!isLegacyBrowserEntry(entry.value)) {
2799
+ this.branches.advance(id, parentId, parent);
2800
+ return void 0;
2801
+ }
2802
+ const details = await projectJson(readRange(this.file, entry), LEGACY_BROWSER_FIELDS, Infinity);
2803
+ const conversion = convertLegacyBrowserEntry({ ...entry.value, ...details }, parent, this.source.sessionId);
2804
+ this.branches.advance(id, parentId, conversion.projection);
2805
+ return conversion.record;
2806
+ }
2807
+ async write(entry, sourceSize) {
2808
+ const record = await this.conversion(entry);
2809
+ if (!record) {
2810
+ await writeBytes(this.stage, readRange(this.file, entry));
2811
+ if (entry.offset + entry.length === sourceSize) {
2812
+ await this.completeLastLine(sourceSize);
2813
+ }
2814
+ return;
2815
+ }
2816
+ const data = {
2817
+ ...record,
2818
+ archive: { sourceSha256: this.source.checksum, offset: entry.offset, length: entry.length }
2819
+ };
2820
+ if (entry.value.type === "message") {
2821
+ await rewriteMessage(this.file, entry, this.stage, data);
2822
+ } else {
2823
+ await this.stage.write(`${JSON.stringify({ ...entry.value, customType: BROWSER_TRANSITION_ENTRY, data })}
2824
+ `);
2825
+ }
2826
+ this.convertedRecords++;
2827
+ if (record.snapshot !== void 0) {
2828
+ this.snapshotDefinitions++;
2829
+ }
2830
+ }
2831
+ async completeLastLine(size) {
2832
+ const lastByte = Buffer.alloc(1);
2833
+ await this.file.read(lastByte, 0, 1, size - 1);
2834
+ if (lastByte[0] !== 10) {
2835
+ await this.stage.write("\n");
2836
+ }
2837
+ }
2838
+ };
2839
+
2840
+ // dist/extensions/agent-browser/lib/browser-session-conversion.js
2841
+ async function validateConversionPaths(options) {
2842
+ if (!options.confirmedStopped) {
2843
+ throw new Error("Stop/quiesce the exact session writer first, then pass --confirm-stopped. Conversion never stops a session.");
2844
+ }
2845
+ const source = resolve(options.source);
2846
+ const destination = resolve(options.destination);
2847
+ if (source === destination) {
2848
+ throw new Error("Conversion requires a separate destination; originals are never rewritten.");
2849
+ }
2850
+ const sourceStat = await lstat(source);
2851
+ if (!sourceStat.isFile() || sourceStat.isSymbolicLink()) {
2852
+ throw new Error("Conversion source must be a regular file, not a symlink.");
2853
+ }
2854
+ const directory = dirname(destination);
2855
+ await mkdir(directory, { mode: 448, recursive: true });
2856
+ await validateDestination(directory, destination);
2857
+ return { source, destination, directory, sourceStat };
2858
+ }
2859
+ async function validateDestination(directory, destination) {
2860
+ const entry = await lstat(directory);
2861
+ if (!entry.isDirectory() || entry.isSymbolicLink() || process.platform !== "win32" && (entry.uid !== process.getuid?.() || (entry.mode & 63) !== 0)) {
2862
+ throw new Error("Conversion destination must be a private current-user directory (0700 on POSIX), without symlinks.");
2863
+ }
2864
+ try {
2865
+ await lstat(destination);
2866
+ throw new Error("Conversion destination is occupied.");
2867
+ } catch (error) {
2868
+ if (getErrorCode(error) !== "ENOENT") {
2869
+ throw error;
2870
+ }
2871
+ }
2872
+ }
2873
+ async function verifySourceUnchanged(file, source, initial, checksum) {
2874
+ const final = await file.stat();
2875
+ const finalPath = await lstat(source);
2876
+ if (final.dev !== initial.dev || final.ino !== initial.ino || final.size !== initial.size || final.mtimeMs !== initial.mtimeMs || finalPath.dev !== initial.dev || finalPath.ino !== initial.ino || await sourceChecksum(file, initial.size) !== checksum) {
2877
+ throw new Error("Conversion source changed; no destination was published.");
2878
+ }
2879
+ }
2880
+ async function syncPublishedDirectory(directory) {
2881
+ const parent = await open(directory, constants.O_RDONLY);
2882
+ try {
2883
+ await parent.sync();
2884
+ } finally {
2885
+ await parent.close();
2886
+ }
2887
+ }
2888
+ async function convertBrowserSession(options) {
2889
+ const { source, destination, directory, sourceStat } = await validateConversionPaths(options);
2890
+ const file = await open(source, constants.O_RDONLY | constants.O_NOFOLLOW);
2891
+ const stagePath = `${destination}.${randomUUID2()}.tmp`;
2892
+ let stage;
2893
+ let published = false;
2894
+ try {
2895
+ const initial = await file.stat();
2896
+ if (initial.dev !== sourceStat.dev || initial.ino !== sourceStat.ino) {
2897
+ throw new Error("Conversion source changed before capture.");
2898
+ }
2899
+ const checksum = await sourceChecksum(file, initial.size);
2900
+ const metadata = await scanJournalMetadata(file, initial.size, true);
2901
+ const header = metadata.at(0);
2902
+ if (header === void 0 || header.value.type !== "session" || typeof header.value.id !== "string") {
2903
+ throw new Error("Conversion source has no native session header.");
2904
+ }
2905
+ stage = await open(stagePath, "wx+", 384);
2906
+ const writer = new BrowserConversionWriter(file, stage, { sessionId: header.value.id, checksum }, metadata);
2907
+ for (const entry of metadata) {
2908
+ await writer.write(entry, initial.size);
2909
+ }
2910
+ await stage.sync();
2911
+ const output = await stage.stat();
2912
+ const destinationSha256 = await sourceChecksum(stage, output.size);
2913
+ await verifySourceUnchanged(file, source, initial, checksum);
2914
+ await stage.close();
2915
+ stage = void 0;
2916
+ await link(stagePath, destination);
2917
+ published = true;
2918
+ return {
2919
+ version: 1,
2920
+ source,
2921
+ destination,
2922
+ sessionId: header.value.id,
2923
+ sourceSha256: checksum,
2924
+ destinationSha256,
2925
+ ...writer.counts,
2926
+ sourceBytes: initial.size,
2927
+ destinationBytes: output.size
2928
+ };
2929
+ } finally {
2930
+ await stage?.close();
2931
+ await file.close();
2932
+ await unlink(stagePath).catch((error) => {
2933
+ if (getErrorCode(error) !== "ENOENT") {
2934
+ throw error;
2935
+ }
2936
+ });
2937
+ if (published && process.platform !== "win32") {
2938
+ await syncPublishedDirectory(directory);
2939
+ }
2940
+ }
2941
+ }
2942
+ export {
2943
+ convertBrowserEntries,
2944
+ convertBrowserSession,
2945
+ convertLegacyBrowserEntry
2946
+ };