pi-agent-browser-native 0.9.5 → 0.9.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (380) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +3 -0
  3. package/dist/extensions/agent-browser/index.js +1214 -583
  4. package/dist/packaged/lib/browser-session-conversion.js +2810 -0
  5. package/dist/packaged/lib/config-policy.js +599 -0
  6. package/dist/packaged/lib/parsing.js +34 -0
  7. package/dist/packaged/lib/playbook.js +694 -0
  8. package/dist/packaged/lib/results/snapshot.js +2671 -0
  9. package/dist/packaged/lib/runtime.js +3027 -0
  10. package/docs/ARCHITECTURE.md +11 -1
  11. package/docs/CODE_QUALITY.md +11 -0
  12. package/docs/COMMAND_REFERENCE.md +2 -2
  13. package/docs/PERFORMANCE.md +243 -0
  14. package/docs/REFERENCE.md +3 -3
  15. package/docs/SESSION_STORAGE.md +11 -3
  16. package/docs/SUPPORT_MATRIX.md +8 -4
  17. package/docs/TOOL_CONTRACT.md +4 -4
  18. package/docs/performance/2026-10-12.json +7257 -0
  19. package/package.json +13 -2
  20. package/scripts/build.mjs +16 -5
  21. package/scripts/config.mjs +1 -1
  22. package/scripts/convert-browser-session.mjs +1 -1
  23. package/dist/extensions/agent-browser/lib/argv-descriptor.js +0 -123
  24. package/dist/extensions/agent-browser/lib/argv-grammar.js +0 -320
  25. package/dist/extensions/agent-browser/lib/bash-guard.js +0 -193
  26. package/dist/extensions/agent-browser/lib/batch-lifecycle.js +0 -131
  27. package/dist/extensions/agent-browser/lib/browser-execution-claim-codec.js +0 -61
  28. package/dist/extensions/agent-browser/lib/browser-execution-claim-storage.js +0 -232
  29. package/dist/extensions/agent-browser/lib/browser-execution-claims.js +0 -202
  30. package/dist/extensions/agent-browser/lib/browser-execution-identity.js +0 -77
  31. package/dist/extensions/agent-browser/lib/browser-journal-branch.js +0 -98
  32. package/dist/extensions/agent-browser/lib/browser-journal-contracts.js +0 -1
  33. package/dist/extensions/agent-browser/lib/browser-journal-projection.js +0 -221
  34. package/dist/extensions/agent-browser/lib/browser-journal-reader.js +0 -89
  35. package/dist/extensions/agent-browser/lib/browser-journal-replay.js +0 -246
  36. package/dist/extensions/agent-browser/lib/browser-journal.js +0 -148
  37. package/dist/extensions/agent-browser/lib/browser-legacy-pages.js +0 -220
  38. package/dist/extensions/agent-browser/lib/browser-legacy-projection.js +0 -282
  39. package/dist/extensions/agent-browser/lib/browser-legacy-types.js +0 -1
  40. package/dist/extensions/agent-browser/lib/browser-session-conversion-stream.js +0 -217
  41. package/dist/extensions/agent-browser/lib/browser-session-conversion.js +0 -126
  42. package/dist/extensions/agent-browser/lib/browser-transcript-contracts.js +0 -35
  43. package/dist/extensions/agent-browser/lib/browser-transcript-validation.js +0 -166
  44. package/dist/extensions/agent-browser/lib/browser-transcript.js +0 -189
  45. package/dist/extensions/agent-browser/lib/browser-value-parsing.js +0 -15
  46. package/dist/extensions/agent-browser/lib/command-capabilities.js +0 -340
  47. package/dist/extensions/agent-browser/lib/command-policy.js +0 -155
  48. package/dist/extensions/agent-browser/lib/command-taxonomy.js +0 -105
  49. package/dist/extensions/agent-browser/lib/config-policy.js +0 -450
  50. package/dist/extensions/agent-browser/lib/config-providers.js +0 -71
  51. package/dist/extensions/agent-browser/lib/config-validation.js +0 -231
  52. package/dist/extensions/agent-browser/lib/config.js +0 -69
  53. package/dist/extensions/agent-browser/lib/electron/cdp.js +0 -62
  54. package/dist/extensions/agent-browser/lib/electron/cleanup.js +0 -274
  55. package/dist/extensions/agent-browser/lib/electron/discovery-darwin.js +0 -109
  56. package/dist/extensions/agent-browser/lib/electron/discovery-desktop.js +0 -136
  57. package/dist/extensions/agent-browser/lib/electron/discovery-evidence.js +0 -90
  58. package/dist/extensions/agent-browser/lib/electron/discovery-linux.js +0 -93
  59. package/dist/extensions/agent-browser/lib/electron/discovery-packages.js +0 -162
  60. package/dist/extensions/agent-browser/lib/electron/discovery-types.js +0 -2
  61. package/dist/extensions/agent-browser/lib/electron/discovery.js +0 -217
  62. package/dist/extensions/agent-browser/lib/electron/launch-monitor.js +0 -102
  63. package/dist/extensions/agent-browser/lib/electron/launch-process.js +0 -209
  64. package/dist/extensions/agent-browser/lib/electron/launch-types.js +0 -2
  65. package/dist/extensions/agent-browser/lib/electron/launch.js +0 -340
  66. package/dist/extensions/agent-browser/lib/executable-path.js +0 -29
  67. package/dist/extensions/agent-browser/lib/execution-cwd.js +0 -67
  68. package/dist/extensions/agent-browser/lib/fs-utils.js +0 -10
  69. package/dist/extensions/agent-browser/lib/input-modes/electron.js +0 -201
  70. package/dist/extensions/agent-browser/lib/input-modes/job.js +0 -198
  71. package/dist/extensions/agent-browser/lib/input-modes/lookup-network-evidence.js +0 -116
  72. package/dist/extensions/agent-browser/lib/input-modes/lookup-plan.js +0 -132
  73. package/dist/extensions/agent-browser/lib/input-modes/lookup-redaction.js +0 -57
  74. package/dist/extensions/agent-browser/lib/input-modes/lookup-source-evidence.js +0 -151
  75. package/dist/extensions/agent-browser/lib/input-modes/lookup-workspace.js +0 -142
  76. package/dist/extensions/agent-browser/lib/input-modes/lookups.js +0 -84
  77. package/dist/extensions/agent-browser/lib/input-modes/params.js +0 -195
  78. package/dist/extensions/agent-browser/lib/input-modes/qa-analysis.js +0 -268
  79. package/dist/extensions/agent-browser/lib/input-modes/qa-presentation.js +0 -117
  80. package/dist/extensions/agent-browser/lib/input-modes/script-child.js +0 -396
  81. package/dist/extensions/agent-browser/lib/input-modes/script-protocol.js +0 -86
  82. package/dist/extensions/agent-browser/lib/input-modes/script-types.js +0 -1
  83. package/dist/extensions/agent-browser/lib/input-modes/script-validation.js +0 -60
  84. package/dist/extensions/agent-browser/lib/input-modes/script.js +0 -108
  85. package/dist/extensions/agent-browser/lib/input-modes/semantic-action.js +0 -243
  86. package/dist/extensions/agent-browser/lib/input-modes/shared.js +0 -48
  87. package/dist/extensions/agent-browser/lib/input-modes/types.js +0 -65
  88. package/dist/extensions/agent-browser/lib/json-schema.js +0 -65
  89. package/dist/extensions/agent-browser/lib/launch-scoped-flags.js +0 -212
  90. package/dist/extensions/agent-browser/lib/managed-session-policy-lock.js +0 -165
  91. package/dist/extensions/agent-browser/lib/managed-session-posix-storage.js +0 -58
  92. package/dist/extensions/agent-browser/lib/managed-session-project-identity.js +0 -244
  93. package/dist/extensions/agent-browser/lib/managed-session-restore-context.js +0 -84
  94. package/dist/extensions/agent-browser/lib/managed-session-restore-policy.js +0 -119
  95. package/dist/extensions/agent-browser/lib/managed-session-restore-state.js +0 -83
  96. package/dist/extensions/agent-browser/lib/managed-session-restore.js +0 -212
  97. package/dist/extensions/agent-browser/lib/managed-session-snapshot-records.js +0 -277
  98. package/dist/extensions/agent-browser/lib/managed-session-snapshots.js +0 -181
  99. package/dist/extensions/agent-browser/lib/managed-session-storage.js +0 -126
  100. package/dist/extensions/agent-browser/lib/native-confirmation.js +0 -140
  101. package/dist/extensions/agent-browser/lib/native-output.js +0 -81
  102. package/dist/extensions/agent-browser/lib/orchestration/batch-stdin.js +0 -182
  103. package/dist/extensions/agent-browser/lib/orchestration/browser-run/artifact-merge.js +0 -30
  104. package/dist/extensions/agent-browser/lib/orchestration/browser-run/artifact-paths.js +0 -188
  105. package/dist/extensions/agent-browser/lib/orchestration/browser-run/browser-observation-result.js +0 -82
  106. package/dist/extensions/agent-browser/lib/orchestration/browser-run/click-dispatch.js +0 -406
  107. package/dist/extensions/agent-browser/lib/orchestration/browser-run/diagnostic-values.js +0 -31
  108. package/dist/extensions/agent-browser/lib/orchestration/browser-run/diagnostics.js +0 -240
  109. package/dist/extensions/agent-browser/lib/orchestration/browser-run/electron-observation.js +0 -203
  110. package/dist/extensions/agent-browser/lib/orchestration/browser-run/electron-text-diagnostics.js +0 -109
  111. package/dist/extensions/agent-browser/lib/orchestration/browser-run/fill-diagnostics.js +0 -119
  112. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-action-recovery.js +0 -147
  113. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-actions.js +0 -144
  114. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-content.js +0 -123
  115. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-contracts.js +0 -1
  116. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-details.js +0 -156
  117. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-electron.js +0 -187
  118. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-evidence.js +0 -39
  119. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-missing-binary.js +0 -89
  120. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-recovery.js +0 -97
  121. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-redaction.js +0 -106
  122. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result-timeout.js +0 -110
  123. package/dist/extensions/agent-browser/lib/orchestration/browser-run/final-result.js +0 -53
  124. package/dist/extensions/agent-browser/lib/orchestration/browser-run/index.js +0 -224
  125. package/dist/extensions/agent-browser/lib/orchestration/browser-run/interaction-diagnostics.js +0 -290
  126. package/dist/extensions/agent-browser/lib/orchestration/browser-run/managed-session-close.js +0 -167
  127. package/dist/extensions/agent-browser/lib/orchestration/browser-run/managed-session-daemon-inspection.js +0 -108
  128. package/dist/extensions/agent-browser/lib/orchestration/browser-run/managed-session-daemon-policy.js +0 -174
  129. package/dist/extensions/agent-browser/lib/orchestration/browser-run/native-helper-observation.js +0 -65
  130. package/dist/extensions/agent-browser/lib/orchestration/browser-run/observation-types.js +0 -1
  131. package/dist/extensions/agent-browser/lib/orchestration/browser-run/overlay-diagnostics.js +0 -120
  132. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare/network-page-filter.js +0 -192
  133. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare/scroll-shims.js +0 -225
  134. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare/snapshot-filter-data.js +0 -150
  135. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare/snapshot-filter.js +0 -174
  136. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare/snapshot-rendered-text.js +0 -147
  137. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare/wait-timeouts.js +0 -145
  138. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-artifacts.js +0 -159
  139. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-command.js +0 -131
  140. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-contracts.js +0 -1
  141. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-daemon.js +0 -93
  142. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-failure.js +0 -42
  143. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-guards.js +0 -242
  144. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-input.js +0 -75
  145. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-observations.js +0 -92
  146. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-page-selection.js +0 -254
  147. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-page-state.js +0 -121
  148. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-refs.js +0 -130
  149. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-resources.js +0 -114
  150. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-semantic.js +0 -121
  151. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-session-plan.js +0 -222
  152. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-timeouts.js +0 -68
  153. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prepare.js +0 -202
  154. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-analysis.js +0 -191
  155. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-confirmation.js +0 -152
  156. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-diagnostics.js +0 -182
  157. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-electron.js +0 -150
  158. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-lifecycle-contracts.js +0 -1
  159. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-lifecycle-phase-contracts.js +0 -1
  160. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-lifecycle-phase.js +0 -115
  161. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-lifecycle.js +0 -256
  162. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-managed-contracts.js +0 -1
  163. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-managed.js +0 -256
  164. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-native-phase-contracts.js +0 -1
  165. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-native-phase.js +0 -93
  166. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-native.js +0 -113
  167. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-navigation-contracts.js +0 -1
  168. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-navigation.js +0 -316
  169. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-ownership.js +0 -28
  170. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-page-phase-contracts.js +0 -1
  171. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-page-phase.js +0 -142
  172. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-presentation-contracts.js +0 -1
  173. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-presentation.js +0 -333
  174. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-publication-phase-contracts.js +0 -1
  175. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-publication-phase.js +0 -71
  176. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-publication.js +0 -201
  177. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-receipts.js +0 -183
  178. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-refs.js +0 -200
  179. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output-tabs.js +0 -142
  180. package/dist/extensions/agent-browser/lib/orchestration/browser-run/process-output.js +0 -25
  181. package/dist/extensions/agent-browser/lib/orchestration/browser-run/prompt-guards.js +0 -50
  182. package/dist/extensions/agent-browser/lib/orchestration/browser-run/recording-receipt-reconciliation.js +0 -198
  183. package/dist/extensions/agent-browser/lib/orchestration/browser-run/recording-recovery-contracts.js +0 -1
  184. package/dist/extensions/agent-browser/lib/orchestration/browser-run/recording-recovery-presentation.js +0 -154
  185. package/dist/extensions/agent-browser/lib/orchestration/browser-run/recording-recovery.js +0 -80
  186. package/dist/extensions/agent-browser/lib/orchestration/browser-run/screenshot-capture.js +0 -14
  187. package/dist/extensions/agent-browser/lib/orchestration/browser-run/screenshot-observation.js +0 -206
  188. package/dist/extensions/agent-browser/lib/orchestration/browser-run/session-state-commands.js +0 -130
  189. package/dist/extensions/agent-browser/lib/orchestration/browser-run/session-state-electron.js +0 -212
  190. package/dist/extensions/agent-browser/lib/orchestration/browser-run/session-state-observations.js +0 -61
  191. package/dist/extensions/agent-browser/lib/orchestration/browser-run/session-state-outcomes.js +0 -187
  192. package/dist/extensions/agent-browser/lib/orchestration/browser-run/session-state-refs.js +0 -169
  193. package/dist/extensions/agent-browser/lib/orchestration/browser-run/session-state-tabs.js +0 -228
  194. package/dist/extensions/agent-browser/lib/orchestration/browser-run/session-state.js +0 -117
  195. package/dist/extensions/agent-browser/lib/orchestration/browser-run/text-visibility-diagnostics.js +0 -182
  196. package/dist/extensions/agent-browser/lib/orchestration/browser-run/timeout-diagnostics.js +0 -256
  197. package/dist/extensions/agent-browser/lib/orchestration/browser-run/timeout-progress.js +0 -108
  198. package/dist/extensions/agent-browser/lib/orchestration/browser-run/types.js +0 -1
  199. package/dist/extensions/agent-browser/lib/orchestration/code-artifact-observation.js +0 -39
  200. package/dist/extensions/agent-browser/lib/orchestration/code-image-observation.js +0 -119
  201. package/dist/extensions/agent-browser/lib/orchestration/electron-host/branch.js +0 -93
  202. package/dist/extensions/agent-browser/lib/orchestration/electron-host/cleanup-result.js +0 -58
  203. package/dist/extensions/agent-browser/lib/orchestration/electron-host/cleanup.js +0 -78
  204. package/dist/extensions/agent-browser/lib/orchestration/electron-host/contracts.js +0 -1
  205. package/dist/extensions/agent-browser/lib/orchestration/electron-host/discovery.js +0 -106
  206. package/dist/extensions/agent-browser/lib/orchestration/electron-host/index.js +0 -60
  207. package/dist/extensions/agent-browser/lib/orchestration/electron-host/policy.js +0 -86
  208. package/dist/extensions/agent-browser/lib/orchestration/electron-host/probe-collection.js +0 -68
  209. package/dist/extensions/agent-browser/lib/orchestration/electron-host/probe-data.js +0 -169
  210. package/dist/extensions/agent-browser/lib/orchestration/electron-host/probe-presentation.js +0 -182
  211. package/dist/extensions/agent-browser/lib/orchestration/electron-host/probe.js +0 -161
  212. package/dist/extensions/agent-browser/lib/orchestration/electron-host/status.js +0 -167
  213. package/dist/extensions/agent-browser/lib/orchestration/execution-queue.js +0 -98
  214. package/dist/extensions/agent-browser/lib/orchestration/extension-artifact-preflight.js +0 -211
  215. package/dist/extensions/agent-browser/lib/orchestration/extension-artifacts.js +0 -23
  216. package/dist/extensions/agent-browser/lib/orchestration/extension-attachment-replay.js +0 -99
  217. package/dist/extensions/agent-browser/lib/orchestration/extension-branch-restore.js +0 -275
  218. package/dist/extensions/agent-browser/lib/orchestration/extension-code.js +0 -280
  219. package/dist/extensions/agent-browser/lib/orchestration/extension-command-admission.js +0 -303
  220. package/dist/extensions/agent-browser/lib/orchestration/extension-command-output.js +0 -36
  221. package/dist/extensions/agent-browser/lib/orchestration/extension-command-result.js +0 -335
  222. package/dist/extensions/agent-browser/lib/orchestration/extension-command-run.js +0 -227
  223. package/dist/extensions/agent-browser/lib/orchestration/extension-command-state.js +0 -1
  224. package/dist/extensions/agent-browser/lib/orchestration/extension-electron-ownership.js +0 -204
  225. package/dist/extensions/agent-browser/lib/orchestration/extension-execution-locks.js +0 -139
  226. package/dist/extensions/agent-browser/lib/orchestration/extension-execution-queue.js +0 -24
  227. package/dist/extensions/agent-browser/lib/orchestration/extension-host-coordination.js +0 -98
  228. package/dist/extensions/agent-browser/lib/orchestration/extension-host-run.js +0 -295
  229. package/dist/extensions/agent-browser/lib/orchestration/extension-intent-replay.js +0 -41
  230. package/dist/extensions/agent-browser/lib/orchestration/extension-invocation.js +0 -7
  231. package/dist/extensions/agent-browser/lib/orchestration/extension-lifecycle.js +0 -102
  232. package/dist/extensions/agent-browser/lib/orchestration/extension-managed-ownership.js +0 -133
  233. package/dist/extensions/agent-browser/lib/orchestration/extension-observation.js +0 -120
  234. package/dist/extensions/agent-browser/lib/orchestration/extension-prompt.js +0 -180
  235. package/dist/extensions/agent-browser/lib/orchestration/extension-recording.js +0 -290
  236. package/dist/extensions/agent-browser/lib/orchestration/extension-resource-contracts.js +0 -1
  237. package/dist/extensions/agent-browser/lib/orchestration/extension-resource-replay.js +0 -269
  238. package/dist/extensions/agent-browser/lib/orchestration/extension-result-state.js +0 -113
  239. package/dist/extensions/agent-browser/lib/orchestration/extension-runtime.js +0 -146
  240. package/dist/extensions/agent-browser/lib/orchestration/extension-script-leases.js +0 -58
  241. package/dist/extensions/agent-browser/lib/orchestration/extension-tool-boundary.js +0 -62
  242. package/dist/extensions/agent-browser/lib/orchestration/extension-version-check.js +0 -54
  243. package/dist/extensions/agent-browser/lib/orchestration/input-plan-types.js +0 -1
  244. package/dist/extensions/agent-browser/lib/orchestration/input-plan.js +0 -313
  245. package/dist/extensions/agent-browser/lib/orchestration/input-redaction.js +0 -62
  246. package/dist/extensions/agent-browser/lib/orchestration/native-config.js +0 -144
  247. package/dist/extensions/agent-browser/lib/orchestration/native-root-launch.js +0 -77
  248. package/dist/extensions/agent-browser/lib/orchestration/native-session-defaults.js +0 -231
  249. package/dist/extensions/agent-browser/lib/orchestration/operation-paths.js +0 -142
  250. package/dist/extensions/agent-browser/lib/orchestration/output-file.js +0 -276
  251. package/dist/extensions/agent-browser/lib/orchestration/script-mode.js +0 -220
  252. package/dist/extensions/agent-browser/lib/owned-managed-session-context.js +0 -55
  253. package/dist/extensions/agent-browser/lib/page-target-batch.js +0 -118
  254. package/dist/extensions/agent-browser/lib/page-target-guards.js +0 -50
  255. package/dist/extensions/agent-browser/lib/page-target-navigation.js +0 -104
  256. package/dist/extensions/agent-browser/lib/page-target-validation.js +0 -90
  257. package/dist/extensions/agent-browser/lib/parsing.js +0 -30
  258. package/dist/extensions/agent-browser/lib/pi-tool-rendering.js +0 -343
  259. package/dist/extensions/agent-browser/lib/playbook.js +0 -146
  260. package/dist/extensions/agent-browser/lib/process-child.js +0 -284
  261. package/dist/extensions/agent-browser/lib/process-environment.js +0 -48
  262. package/dist/extensions/agent-browser/lib/process-errors.js +0 -23
  263. package/dist/extensions/agent-browser/lib/process-identity.js +0 -127
  264. package/dist/extensions/agent-browser/lib/process-socket-storage.js +0 -256
  265. package/dist/extensions/agent-browser/lib/process-stdout.js +0 -74
  266. package/dist/extensions/agent-browser/lib/process.js +0 -216
  267. package/dist/extensions/agent-browser/lib/prompt-artifacts.js +0 -287
  268. package/dist/extensions/agent-browser/lib/prompt-policy.js +0 -54
  269. package/dist/extensions/agent-browser/lib/read-command.js +0 -41
  270. package/dist/extensions/agent-browser/lib/read-confirmation.js +0 -162
  271. package/dist/extensions/agent-browser/lib/recording-reservations.js +0 -208
  272. package/dist/extensions/agent-browser/lib/redaction-fields.js +0 -75
  273. package/dist/extensions/agent-browser/lib/redaction-json.js +0 -149
  274. package/dist/extensions/agent-browser/lib/redaction-url.js +0 -88
  275. package/dist/extensions/agent-browser/lib/results/action-contracts.js +0 -1
  276. package/dist/extensions/agent-browser/lib/results/action-recommendations.js +0 -38
  277. package/dist/extensions/agent-browser/lib/results/artifact-contracts.js +0 -1
  278. package/dist/extensions/agent-browser/lib/results/artifact-manifest-validation.js +0 -133
  279. package/dist/extensions/agent-browser/lib/results/artifact-manifest.js +0 -173
  280. package/dist/extensions/agent-browser/lib/results/artifact-recommendations.js +0 -73
  281. package/dist/extensions/agent-browser/lib/results/categories.js +0 -152
  282. package/dist/extensions/agent-browser/lib/results/confirmation.js +0 -75
  283. package/dist/extensions/agent-browser/lib/results/contracts.js +0 -1
  284. package/dist/extensions/agent-browser/lib/results/editable-ref-evidence.js +0 -99
  285. package/dist/extensions/agent-browser/lib/results/electron-recommendations.js +0 -83
  286. package/dist/extensions/agent-browser/lib/results/envelope-decoding.js +0 -48
  287. package/dist/extensions/agent-browser/lib/results/envelope.js +0 -198
  288. package/dist/extensions/agent-browser/lib/results/evidence-contracts.js +0 -1
  289. package/dist/extensions/agent-browser/lib/results/failure-recommendations.js +0 -180
  290. package/dist/extensions/agent-browser/lib/results/network-routes.js +0 -133
  291. package/dist/extensions/agent-browser/lib/results/network.js +0 -89
  292. package/dist/extensions/agent-browser/lib/results/next-actions.js +0 -111
  293. package/dist/extensions/agent-browser/lib/results/presentation/artifact-files.js +0 -320
  294. package/dist/extensions/agent-browser/lib/results/presentation/artifact-format.js +0 -138
  295. package/dist/extensions/agent-browser/lib/results/presentation/artifact-images.js +0 -113
  296. package/dist/extensions/agent-browser/lib/results/presentation/artifact-verification.js +0 -145
  297. package/dist/extensions/agent-browser/lib/results/presentation/artifacts.js +0 -165
  298. package/dist/extensions/agent-browser/lib/results/presentation/batch-contracts.js +0 -1
  299. package/dist/extensions/agent-browser/lib/results/presentation/batch-recording.js +0 -118
  300. package/dist/extensions/agent-browser/lib/results/presentation/batch-redaction.js +0 -68
  301. package/dist/extensions/agent-browser/lib/results/presentation/batch-rendering.js +0 -135
  302. package/dist/extensions/agent-browser/lib/results/presentation/batch-step.js +0 -227
  303. package/dist/extensions/agent-browser/lib/results/presentation/batch-summary.js +0 -91
  304. package/dist/extensions/agent-browser/lib/results/presentation/batch.js +0 -123
  305. package/dist/extensions/agent-browser/lib/results/presentation/browser-profile-recovery.js +0 -54
  306. package/dist/extensions/agent-browser/lib/results/presentation/command-presenters.js +0 -216
  307. package/dist/extensions/agent-browser/lib/results/presentation/common.js +0 -81
  308. package/dist/extensions/agent-browser/lib/results/presentation/content.js +0 -119
  309. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-a11y.js +0 -67
  310. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-health.js +0 -79
  311. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-identity.js +0 -199
  312. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-logs.js +0 -75
  313. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-network-actions.js +0 -216
  314. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-network.js +0 -124
  315. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-redaction.js +0 -64
  316. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-storage.js +0 -209
  317. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-stream.js +0 -69
  318. package/dist/extensions/agent-browser/lib/results/presentation/diagnostic-summary.js +0 -222
  319. package/dist/extensions/agent-browser/lib/results/presentation/diagnostics.js +0 -124
  320. package/dist/extensions/agent-browser/lib/results/presentation/early-result.js +0 -70
  321. package/dist/extensions/agent-browser/lib/results/presentation/errors.js +0 -285
  322. package/dist/extensions/agent-browser/lib/results/presentation/input-contracts.js +0 -1
  323. package/dist/extensions/agent-browser/lib/results/presentation/large-output.js +0 -117
  324. package/dist/extensions/agent-browser/lib/results/presentation/navigation.js +0 -231
  325. package/dist/extensions/agent-browser/lib/results/presentation/notices.js +0 -75
  326. package/dist/extensions/agent-browser/lib/results/presentation/observation-contracts.js +0 -1
  327. package/dist/extensions/agent-browser/lib/results/presentation/observation-rendering.js +0 -127
  328. package/dist/extensions/agent-browser/lib/results/presentation/outcomes.js +0 -120
  329. package/dist/extensions/agent-browser/lib/results/presentation/output-completion.js +0 -77
  330. package/dist/extensions/agent-browser/lib/results/presentation/output-spill.js +0 -51
  331. package/dist/extensions/agent-browser/lib/results/presentation/registry.js +0 -145
  332. package/dist/extensions/agent-browser/lib/results/presentation/semantic-action.js +0 -104
  333. package/dist/extensions/agent-browser/lib/results/presentation/skills.js +0 -183
  334. package/dist/extensions/agent-browser/lib/results/presentation/source.js +0 -109
  335. package/dist/extensions/agent-browser/lib/results/presentation.js +0 -19
  336. package/dist/extensions/agent-browser/lib/results/recommendation-contracts.js +0 -1
  337. package/dist/extensions/agent-browser/lib/results/recording.js +0 -88
  338. package/dist/extensions/agent-browser/lib/results/recovery-actions.js +0 -118
  339. package/dist/extensions/agent-browser/lib/results/recovery-next-actions.js +0 -60
  340. package/dist/extensions/agent-browser/lib/results/selector-recovery-target.js +0 -83
  341. package/dist/extensions/agent-browser/lib/results/selector-recovery.js +0 -261
  342. package/dist/extensions/agent-browser/lib/results/snapshot-compact.js +0 -266
  343. package/dist/extensions/agent-browser/lib/results/snapshot-content.js +0 -32
  344. package/dist/extensions/agent-browser/lib/results/snapshot-high-value-controls.js +0 -240
  345. package/dist/extensions/agent-browser/lib/results/snapshot-refs.js +0 -103
  346. package/dist/extensions/agent-browser/lib/results/snapshot-segments.js +0 -383
  347. package/dist/extensions/agent-browser/lib/results/snapshot-spill.js +0 -53
  348. package/dist/extensions/agent-browser/lib/results/snapshot.js +0 -44
  349. package/dist/extensions/agent-browser/lib/results/text.js +0 -44
  350. package/dist/extensions/agent-browser/lib/runtime-args-validation.js +0 -133
  351. package/dist/extensions/agent-browser/lib/runtime-compatibility.js +0 -81
  352. package/dist/extensions/agent-browser/lib/runtime-contracts.js +0 -1
  353. package/dist/extensions/agent-browser/lib/runtime-redaction.js +0 -118
  354. package/dist/extensions/agent-browser/lib/runtime-replay-events.js +0 -144
  355. package/dist/extensions/agent-browser/lib/runtime-session-identity.js +0 -76
  356. package/dist/extensions/agent-browser/lib/runtime-session-plan.js +0 -114
  357. package/dist/extensions/agent-browser/lib/runtime-session-replay.js +0 -123
  358. package/dist/extensions/agent-browser/lib/runtime-tab-correction.js +0 -65
  359. package/dist/extensions/agent-browser/lib/runtime-timeouts.js +0 -28
  360. package/dist/extensions/agent-browser/lib/runtime.js +0 -163
  361. package/dist/extensions/agent-browser/lib/session-identity.js +0 -51
  362. package/dist/extensions/agent-browser/lib/session-page-observation.js +0 -357
  363. package/dist/extensions/agent-browser/lib/session-page-state.js +0 -353
  364. package/dist/extensions/agent-browser/lib/session-page-types.js +0 -1
  365. package/dist/extensions/agent-browser/lib/string-enum-schema.js +0 -8
  366. package/dist/extensions/agent-browser/lib/temp-artifact-budget.js +0 -81
  367. package/dist/extensions/agent-browser/lib/temp-mutation-queue.js +0 -7
  368. package/dist/extensions/agent-browser/lib/temp-root-ownership.js +0 -234
  369. package/dist/extensions/agent-browser/lib/temp-root.js +0 -211
  370. package/dist/extensions/agent-browser/lib/temp.js +0 -91
  371. package/dist/extensions/agent-browser/lib/tool-surface.js +0 -239
  372. package/dist/extensions/agent-browser/lib/upstream-version.js +0 -15
  373. package/dist/extensions/agent-browser/lib/web-search-providers.js +0 -193
  374. package/dist/extensions/agent-browser/lib/web-search-request.js +0 -102
  375. package/dist/extensions/agent-browser/lib/web-search-results.js +0 -281
  376. package/dist/extensions/agent-browser/lib/web-search-schema.js +0 -82
  377. package/dist/extensions/agent-browser/lib/web-search.js +0 -167
  378. package/dist/extensions/agent-browser/lib/webmcp-observation.js +0 -35
  379. package/dist/extensions/agent-browser/lib/windows-stock-launcher.js +0 -96
  380. package/dist/scripts/agent-browser-target.mjs +0 -23
@@ -959,8 +959,7 @@ function getCommandSubcommand(tokens) {
959
959
  }
960
960
  return tokens.at(1);
961
961
  }
962
- function parseCommandInfoFromTokens(commandTokens) {
963
- const upstreamCommandTokens = stripUpstreamGlobalFlags(commandTokens);
962
+ function parseCommandInfoFromTokens(upstreamCommandTokens) {
964
963
  const command = upstreamCommandTokens[0];
965
964
  return {
966
965
  command,
@@ -968,13 +967,13 @@ function parseCommandInfoFromTokens(commandTokens) {
968
967
  };
969
968
  }
970
969
  function parseCommandInfo(args) {
971
- return parseCommandInfoFromTokens(extractCommandTokens(args));
970
+ return parseCommandInfoFromTokens(extractUpstreamCommandTokens(args));
972
971
  }
973
972
  function parseArgvDescriptor(args) {
974
973
  const commandTokens = extractCommandTokens(args);
975
974
  const upstreamCommandTokens = stripUpstreamGlobalFlags(commandTokens);
976
975
  return {
977
- commandInfo: parseCommandInfoFromTokens(commandTokens),
976
+ commandInfo: parseCommandInfoFromTokens(upstreamCommandTokens),
978
977
  commandTokens,
979
978
  upstreamCommandTokens
980
979
  };
@@ -1054,16 +1053,16 @@ function isString(value) {
1054
1053
  function isStringArray(value) {
1055
1054
  return Array.isArray(value) && value.every(isString);
1056
1055
  }
1057
- function getSelectValues(input, context) {
1056
+ function getSelectValues(input, context2) {
1058
1057
  const rawValue = input.value;
1059
1058
  const rawValues = input.values;
1060
1059
  if (rawValue !== void 0 && rawValues !== void 0) {
1061
- return { error: `${context}.value and ${context}.values cannot both be provided for select.` };
1060
+ return { error: `${context2}.value and ${context2}.values cannot both be provided for select.` };
1062
1061
  }
1063
1062
  if (rawValues !== void 0) {
1064
1063
  if (!isStringArray(rawValues) || rawValues.length === 0 || rawValues.some((value) => value.trim().length === 0)) {
1065
1064
  return {
1066
- error: `${context}.values must be a non-empty array of non-empty strings for select.`
1065
+ error: `${context2}.values must be a non-empty array of non-empty strings for select.`
1067
1066
  };
1068
1067
  }
1069
1068
  return { values: rawValues };
@@ -1071,7 +1070,7 @@ function getSelectValues(input, context) {
1071
1070
  if (typeof rawValue === "string" && rawValue.trim().length > 0) {
1072
1071
  return { values: [rawValue] };
1073
1072
  }
1074
- return { error: `${context}.value or ${context}.values is required for select.` };
1073
+ return { error: `${context2}.value or ${context2}.values is required for select.` };
1075
1074
  }
1076
1075
  function getBatchResultItems(data) {
1077
1076
  return Array.isArray(data) ? data.filter(isRecord) : [];
@@ -1526,24 +1525,22 @@ function redactEmbeddedStructuredText(text3, redact) {
1526
1525
  let output = "";
1527
1526
  let cursor = 0;
1528
1527
  const findEnd = createBalancedJsonEndFinder(text3);
1529
- while (cursor < text3.length) {
1530
- const char = text3[cursor];
1531
- if (char !== "{" && char !== "[") {
1532
- output += char;
1533
- cursor += 1;
1534
- continue;
1535
- }
1536
- const endIndex = findEnd(cursor);
1528
+ const openers = /[[{]/g;
1529
+ let match;
1530
+ while ((match = openers.exec(text3)) !== null) {
1531
+ const endIndex = findEnd(match.index);
1537
1532
  if (endIndex === void 0) {
1538
- output += char;
1539
- cursor += 1;
1540
1533
  continue;
1541
1534
  }
1542
- const candidate = text3.slice(cursor, endIndex + 1);
1543
- output += redactSerializedJson(candidate, redact) ?? candidate;
1544
- cursor = endIndex + 1;
1535
+ const candidate = text3.slice(match.index, endIndex + 1);
1536
+ const redacted = redactSerializedJson(candidate, redact) ?? candidate;
1537
+ if (redacted !== candidate) {
1538
+ output += text3.slice(cursor, match.index) + redacted;
1539
+ cursor = endIndex + 1;
1540
+ }
1541
+ openers.lastIndex = endIndex + 1;
1545
1542
  }
1546
- return output;
1543
+ return cursor === 0 ? text3 : output + text3.slice(cursor);
1547
1544
  }
1548
1545
  var init_redaction_json = __esm({
1549
1546
  "dist/extensions/agent-browser/lib/redaction-json.js"() {
@@ -3502,7 +3499,7 @@ function getSupersededRecordingKeys(candidates, entry, key) {
3502
3499
  return [];
3503
3500
  }
3504
3501
  const entrySessionKey = entry.session !== void 0 && entry.session.length > 0 ? getAgentBrowserSessionIdentityKey(entry.session, entry.namespace) : void 0;
3505
- return candidates.filter(([candidateKey2, candidate]) => {
3502
+ return [...candidates].filter(([candidateKey2, candidate]) => {
3506
3503
  const sameRecordingSession = entrySessionKey === void 0 ? candidate.session === void 0 : candidate.session !== void 0 && getAgentBrowserSessionIdentityKey(candidate.session, candidate.namespace) === entrySessionKey;
3507
3504
  return candidateKey2 !== key && sameRecordingSession && candidate.kind === "video" && isPendingRecordingArtifact(candidate);
3508
3505
  }).map(([candidateKey2]) => candidateKey2);
@@ -3536,7 +3533,7 @@ function mergeSessionArtifactManifest(options) {
3536
3533
  }).map(({ entry }) => entry);
3537
3534
  for (const entry of orderedEntries) {
3538
3535
  const key = getSessionArtifactManifestEntryKey(entry);
3539
- for (const candidateKey2 of getSupersededRecordingKeys([...byPath], entry, key)) {
3536
+ for (const candidateKey2 of getSupersededRecordingKeys(byPath, entry, key)) {
3540
3537
  byPath.delete(candidateKey2);
3541
3538
  }
3542
3539
  const existing = byPath.get(key);
@@ -4414,25 +4411,142 @@ var init_process_errors = __esm({
4414
4411
  }
4415
4412
  });
4416
4413
 
4417
- // dist/extensions/agent-browser/lib/launch-scoped-flags.js
4418
- function hasLaunchScopedFlagToken(args, flag) {
4419
- const commandStartIndex = findCommandStartIndex(args);
4420
- const command = commandStartIndex === void 0 ? void 0 : args[commandStartIndex];
4421
- return args.some((token, index) => {
4422
- if (token.startsWith(`${flag}=`)) {
4423
- return flag === "--restore";
4424
- }
4425
- if (token !== flag) {
4414
+ // dist/extensions/agent-browser/lib/batch-lifecycle.js
4415
+ function rowCommand(value, fallback) {
4416
+ return Array.isArray(value) && value.every((token) => typeof token === "string") ? value : fallback;
4417
+ }
4418
+ function rowResult(row) {
4419
+ if (isRecord(row.result)) {
4420
+ return row.result;
4421
+ }
4422
+ return isRecord(row.data) ? row.data : void 0;
4423
+ }
4424
+ function rowBrowserLaunched(row, result) {
4425
+ const lifecycle = isRecord(row.lifecycle) ? row.lifecycle : result?.lifecycle;
4426
+ if (!isRecord(lifecycle) || !isRecord(lifecycle.effectiveLaunch)) {
4427
+ return void 0;
4428
+ }
4429
+ const launched = lifecycle.effectiveLaunch.browserLaunched;
4430
+ return typeof launched === "boolean" ? launched : void 0;
4431
+ }
4432
+ function lifecycleStep(value, fallback) {
4433
+ if (!isRecord(value)) {
4434
+ return void 0;
4435
+ }
4436
+ const result = rowResult(value);
4437
+ const command = rowCommand(value.command, fallback);
4438
+ return {
4439
+ result,
4440
+ succeeded: value.success === true,
4441
+ browserLaunched: rowBrowserLaunched(value, result),
4442
+ tokens: command === void 0 ? void 0 : extractUpstreamCommandTokens(command)
4443
+ };
4444
+ }
4445
+ function batchHasSuccessfulCloseAll(data, fallbackCommands = []) {
4446
+ if (!Array.isArray(data)) {
4447
+ return false;
4448
+ }
4449
+ return data.some((row, index) => {
4450
+ if (!isRecord(row) || row.success !== true) {
4426
4451
  return false;
4427
4452
  }
4428
- if (flag === "--auto-connect") {
4429
- return isBooleanFlagEnabled(args, flag);
4453
+ const command = rowCommand(row.command, fallbackCommands.at(index));
4454
+ return command !== void 0 && !detectConfirmationRequired(row.result) && isCloseAllCommand(extractUpstreamCommandTokens(command));
4455
+ });
4456
+ }
4457
+ function successfulClose(step) {
4458
+ return step.succeeded && step.tokens !== void 0 && !detectConfirmationRequired(step.result) && (isCloseCommand(step.tokens[0]) || isSuccessfulNativeConfirmedClose(step.tokens, step.result));
4459
+ }
4460
+ function closedState(step) {
4461
+ const result = step.result;
4462
+ const closeData = step.tokens?.[0] === "confirm" && isRecord(result) && isRecord(result.result) ? result.result.data : result;
4463
+ return {
4464
+ endsClosed: true,
4465
+ browserActiveAfterClose: false,
4466
+ recordingClosedAfterBatch: true,
4467
+ statePath: isRecord(closeData) && typeof closeData.statePath === "string" ? closeData.statePath : void 0
4468
+ };
4469
+ }
4470
+ function recordingState(state, step) {
4471
+ const relaunched = step.browserLaunched !== false;
4472
+ const browserActiveAfterClose = state.browserActiveAfterClose || relaunched;
4473
+ let recordingClosedAfterBatch = state.recordingClosedAfterBatch;
4474
+ const subcommand = step.tokens?.[1];
4475
+ if (step.succeeded && subcommand === "stop") {
4476
+ recordingClosedAfterBatch = true;
4477
+ } else if (step.succeeded && browserActiveAfterClose && (subcommand === "start" || subcommand === "restart")) {
4478
+ recordingClosedAfterBatch = false;
4479
+ }
4480
+ return {
4481
+ ...state,
4482
+ endsClosed: state.endsClosed && !relaunched,
4483
+ browserActiveAfterClose,
4484
+ recordingClosedAfterBatch
4485
+ };
4486
+ }
4487
+ function advanceClosedState(state, step) {
4488
+ if (step.tokens?.[0] === "record") {
4489
+ return recordingState(state, step);
4490
+ }
4491
+ if (step.browserLaunched === false) {
4492
+ return state;
4493
+ }
4494
+ return {
4495
+ ...state,
4496
+ endsClosed: false,
4497
+ browserActiveAfterClose: true,
4498
+ recordingClosedAfterBatch: step.tokens === void 0 ? false : state.recordingClosedAfterBatch
4499
+ };
4500
+ }
4501
+ function getSuccessfulBatchCloseLifecycle(rows, fallbackCommands = []) {
4502
+ if (!Array.isArray(rows)) {
4503
+ return void 0;
4504
+ }
4505
+ let state;
4506
+ for (const [index, row] of rows.entries()) {
4507
+ const step = lifecycleStep(row, fallbackCommands.at(index));
4508
+ if (step === void 0) {
4509
+ continue;
4430
4510
  }
4431
- if (flag === "--state" && command === "wait" && commandStartIndex !== void 0 && index > commandStartIndex) {
4432
- return false;
4511
+ if (successfulClose(step)) {
4512
+ state = closedState(step);
4513
+ } else if (state !== void 0) {
4514
+ state = advanceClosedState(state, step);
4433
4515
  }
4516
+ }
4517
+ return state === void 0 ? void 0 : {
4518
+ endsClosed: state.endsClosed,
4519
+ recordingClosedAfterBatch: state.recordingClosedAfterBatch,
4520
+ statePath: state.statePath
4521
+ };
4522
+ }
4523
+ var init_batch_lifecycle = __esm({
4524
+ "dist/extensions/agent-browser/lib/batch-lifecycle.js"() {
4525
+ "use strict";
4526
+ init_argv_descriptor();
4527
+ init_command_taxonomy();
4528
+ init_parsing();
4529
+ init_native_confirmation();
4530
+ init_confirmation();
4531
+ }
4532
+ });
4533
+
4534
+ // dist/extensions/agent-browser/lib/launch-scoped-flags.js
4535
+ function hasLaunchScopedFlagToken(args, flag) {
4536
+ if (flag === "--restore" && args.some((token) => token.startsWith("--restore="))) {
4434
4537
  return true;
4435
- });
4538
+ }
4539
+ if (!args.includes(flag)) {
4540
+ return false;
4541
+ }
4542
+ if (flag === "--auto-connect") {
4543
+ return isBooleanFlagEnabled(args, flag);
4544
+ }
4545
+ if (flag !== "--state") {
4546
+ return true;
4547
+ }
4548
+ const commandStartIndex = findCommandStartIndex(args);
4549
+ return commandStartIndex === void 0 || args[commandStartIndex] !== "wait" || args.indexOf(flag) < commandStartIndex;
4436
4550
  }
4437
4551
  var LAUNCH_SCOPED_FLAG_DEFINITIONS, LAUNCH_SCOPED_FLAGS, LAUNCH_SCOPED_FLAG_LABEL, OPEN_RESULT_TAB_CORRECTION_FLAGS, MANAGED_RESTORE_INCOMPATIBLE_FLAGS, MANAGED_RESTORE_INCOMPATIBLE_ENVS, MANAGED_RESTORE_INCOMPATIBLE_BOOLEAN_ENVS;
4438
4552
  var init_launch_scoped_flags = __esm({
@@ -5190,14 +5304,17 @@ function getTempArtifactByteLength(content) {
5190
5304
  async function listArtifactFiles(directory, excludedNames = /* @__PURE__ */ new Set()) {
5191
5305
  const entries = await readdir3(directory, { withFileTypes: true }).catch(() => []);
5192
5306
  const files = [];
5193
- for (const entry of entries) {
5194
- if (!entry.isFile() || excludedNames.has(entry.name)) {
5195
- continue;
5196
- }
5197
- const path = join4(directory, entry.name);
5198
- const stats = await stat5(path).catch(() => void 0);
5199
- if (stats?.isFile() === true) {
5200
- files.push({ mtimeMs: stats.mtimeMs, path, size: stats.size });
5307
+ const candidates = entries.filter((entry) => entry.isFile() && !excludedNames.has(entry.name));
5308
+ for (let index = 0; index < candidates.length; index += 4) {
5309
+ const batch = await Promise.all(candidates.slice(index, index + 4).map(async (entry) => {
5310
+ const path = join4(directory, entry.name);
5311
+ const stats = await stat5(path).catch(() => void 0);
5312
+ return stats?.isFile() === true ? { mtimeMs: stats.mtimeMs, path, size: stats.size } : void 0;
5313
+ }));
5314
+ for (const file of batch) {
5315
+ if (file !== void 0) {
5316
+ files.push(file);
5317
+ }
5201
5318
  }
5202
5319
  }
5203
5320
  return files;
@@ -5870,7 +5987,7 @@ var init_managed_session_posix_storage = __esm({
5870
5987
  });
5871
5988
 
5872
5989
  // dist/extensions/agent-browser/lib/managed-session-project-identity.js
5873
- import { createHash, randomUUID as randomUUID2 } from "node:crypto";
5990
+ import { createHash as createHash2, randomUUID as randomUUID3 } from "node:crypto";
5874
5991
  import { linkSync, lstatSync as lstatSync2, readFileSync, realpathSync, statSync, unlinkSync, writeFileSync } from "node:fs";
5875
5992
  import { dirname as dirname5, join as join7, resolve as resolve3 } from "node:path";
5876
5993
  function isManagedSessionRestoreKey(value) {
@@ -5976,7 +6093,7 @@ function matchingCacheIdentity(cached, checkout, filesystem) {
5976
6093
  return cached.gitDirectory === checkout.gitDirectory && cached.worktreeDirectory === checkout.worktreeDirectory && cached.gitFilesystemIdentity === filesystem.git && cached.worktreeFilesystemIdentity === filesystem.worktree && cached.marker === filesystem.marker ? cached.identity : void 0;
5977
6094
  }
5978
6095
  function publishGenerationMarker(markerPath, platform) {
5979
- const content = JSON.stringify({ id: randomUUID2(), version: 1 });
6096
+ const content = JSON.stringify({ id: randomUUID3(), version: 1 });
5980
6097
  if (platform === "android") {
5981
6098
  try {
5982
6099
  writeFileSync(markerPath, content, { encoding: "utf8", flag: "wx", mode: 384 });
@@ -5985,7 +6102,7 @@ function publishGenerationMarker(markerPath, platform) {
5985
6102
  return getErrorCode(error) === "EEXIST";
5986
6103
  }
5987
6104
  }
5988
- const candidatePath = `${markerPath}.candidate-${process.pid}-${randomUUID2()}`;
6105
+ const candidatePath = `${markerPath}.candidate-${process.pid}-${randomUUID3()}`;
5989
6106
  try {
5990
6107
  writeFileSync(candidatePath, content, { encoding: "utf8", flag: "wx", mode: 384 });
5991
6108
  try {
@@ -6064,7 +6181,7 @@ function createManagedSessionRestoreKey(cwd, restoreScope = "", platform = proce
6064
6181
  }
6065
6182
  const identity = resolveProjectGenerationIdentity(canonicalCwd, platform);
6066
6183
  const material = identity ?? `unavailable:${canonicalCwd}`;
6067
- const digest = createHash("sha256").update(`restore-v3:${material}:scope:${restoreScope}`).digest("hex").slice(0, MANAGED_SESSION_RESTORE_KEY_HASH_LENGTH);
6184
+ const digest = createHash2("sha256").update(`restore-v3:${material}:scope:${restoreScope}`).digest("hex").slice(0, MANAGED_SESSION_RESTORE_KEY_HASH_LENGTH);
6068
6185
  return `${MANAGED_SESSION_NAME_PREFIX}${digest}`;
6069
6186
  }
6070
6187
  var MANAGED_SESSION_RESTORE_KEY_PATTERN, MANAGED_SESSION_NAME_PREFIX, MANAGED_SESSION_FRESH_SUFFIX_PATTERN, MANAGED_SESSION_RESTORE_KEY_HASH_LENGTH, PROJECT_GENERATION_MARKER_NAME, PROJECT_GENERATION_MARKER_MAX_BYTES, projectGenerationCache;
@@ -6207,8 +6324,8 @@ var init_managed_session_storage = __esm({
6207
6324
 
6208
6325
  // dist/extensions/agent-browser/lib/owned-managed-session-context.js
6209
6326
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
6210
- async function withOwnedManagedSessionContext(context, run) {
6211
- return await ownedManagedSessionStorage.run(context, run);
6327
+ async function withOwnedManagedSessionContext(context2, run) {
6328
+ return await ownedManagedSessionStorage.run(context2, run);
6212
6329
  }
6213
6330
  function resolveOwnedManagedSessionContext(options) {
6214
6331
  const namespace = canonicalizeAgentBrowserNamespace(options.namespace);
@@ -6380,7 +6497,7 @@ var init_managed_session_restore_policy = __esm({
6380
6497
  });
6381
6498
 
6382
6499
  // dist/extensions/agent-browser/lib/managed-session-snapshot-records.js
6383
- import { createHash as createHash2, randomUUID as randomUUID3 } from "node:crypto";
6500
+ import { createHash as createHash3, randomUUID as randomUUID4 } from "node:crypto";
6384
6501
  import { chmodSync, lstatSync as lstatSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync2, readdirSync as readdirSync3, realpathSync as realpathSync3, renameSync, rmdirSync, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "node:fs";
6385
6502
  import { basename as basename2, dirname as dirname6, isAbsolute as isAbsolute2, join as join9 } from "node:path";
6386
6503
  function pathExistsOrIsUnreadable(path) {
@@ -6433,7 +6550,7 @@ function getCheckoutLineageHash(cwd, platform) {
6433
6550
  if (root === void 0 || root.length === 0) {
6434
6551
  return void 0;
6435
6552
  }
6436
- return createHash2("sha256").update(`managed-snapshot-lineage-v1:${platform}:${platform === "win32" ? root.toLowerCase() : root}`).digest("hex");
6553
+ return createHash3("sha256").update(`managed-snapshot-lineage-v1:${platform}:${platform === "win32" ? root.toLowerCase() : root}`).digest("hex");
6437
6554
  }
6438
6555
  function privateOwnedDirectory(entry, platform) {
6439
6556
  if (platform === "win32") {
@@ -6492,7 +6609,7 @@ function removeManifestLineages(directory, platform) {
6492
6609
  }
6493
6610
  }
6494
6611
  function getRecordPath(directory, snapshotPath) {
6495
- return join9(directory, `${createHash2("sha256").update(snapshotPath).digest("hex")}.json`);
6612
+ return join9(directory, `${createHash3("sha256").update(snapshotPath).digest("hex")}.json`);
6496
6613
  }
6497
6614
  function discardRecord(path) {
6498
6615
  try {
@@ -6529,7 +6646,7 @@ function verifyRecord(path, snapshotPath, platform) {
6529
6646
  }
6530
6647
  }
6531
6648
  function publishRecord(path, snapshotPath, content, platform) {
6532
- const temporaryPath = join9(dirname6(path), `.tmp-${process.pid}-${randomUUID3()}`);
6649
+ const temporaryPath = join9(dirname6(path), `.tmp-${process.pid}-${randomUUID4()}`);
6533
6650
  try {
6534
6651
  writeFileSync2(temporaryPath, content, { encoding: "utf8", flag: "wx", mode: 384 });
6535
6652
  renameSync(temporaryPath, path);
@@ -6957,8 +7074,8 @@ function getOwnedManagedSessionNamespaceEnv(options) {
6957
7074
  const { namespace, owned, ownedContext } = resolveManagedSessionRestorePolicy(options);
6958
7075
  return owned ? { AGENT_BROWSER_NAMESPACE: ownedContext?.namespace ?? namespace ?? "" } : {};
6959
7076
  }
6960
- function compatibilityForReuse(context, env, args, explicit) {
6961
- return explicit === void 0 && context.headedManagedAutosaveInterval !== void 0 && !agentBrowserExplicitConfigIsPresent(env, args) ? { AGENT_BROWSER_AUTOSAVE_INTERVAL_MS: context.headedManagedAutosaveInterval } : {};
7077
+ function compatibilityForReuse(context2, env, args, explicit) {
7078
+ return explicit === void 0 && context2.headedManagedAutosaveInterval !== void 0 && !agentBrowserExplicitConfigIsPresent(env, args) ? { AGENT_BROWSER_AUTOSAVE_INTERVAL_MS: context2.headedManagedAutosaveInterval } : {};
6962
7079
  }
6963
7080
  function explicitAutosaveInterval(options) {
6964
7081
  const parent = options.parentEnv ?? getAgentBrowserProcessEnvironment();
@@ -6998,14 +7115,14 @@ function getManagedSessionRestoreProtectedEnv(options, restoreEnv) {
6998
7115
  ...options.env
6999
7116
  });
7000
7117
  }
7001
- function validRestoreIdentity(context, cwd) {
7002
- if (context.restoreKey === void 0 || context.restoreKey.length === 0 || context.restoreScope === void 0 || context.restoreScope.length === 0) {
7118
+ function validRestoreIdentity(context2, cwd) {
7119
+ if (context2.restoreKey === void 0 || context2.restoreKey.length === 0 || context2.restoreScope === void 0 || context2.restoreScope.length === 0) {
7003
7120
  return false;
7004
7121
  }
7005
- return createManagedSessionRestoreKey(cwd, context.restoreScope) === context.restoreKey && hasManagedSessionRestoreProjectIdentity(cwd);
7122
+ return createManagedSessionRestoreKey(cwd, context2.restoreScope) === context2.restoreKey && hasManagedSessionRestoreProjectIdentity(cwd);
7006
7123
  }
7007
- function validLaunchEnvironment(options, context, env) {
7008
- if (context.reuseOnly === true) {
7124
+ function validLaunchEnvironment(options, context2, env) {
7125
+ if (context2.reuseOnly === true) {
7009
7126
  return true;
7010
7127
  }
7011
7128
  if (isDisabledEnvFlag(env[MANAGED_SESSION_RESTORE_ENV])) {
@@ -7017,7 +7134,7 @@ function validLaunchEnvironment(options, context, env) {
7017
7134
  if (MANAGED_RESTORE_INCOMPATIBLE_BOOLEAN_ENVS.some((name) => isUpstreamEnvFlagEnabled(env[name]))) {
7018
7135
  return false;
7019
7136
  }
7020
- return options.env?.[AGENT_BROWSER_RESTORE_ENV] === void 0 || options.env[AGENT_BROWSER_RESTORE_ENV] === context.restoreKey;
7137
+ return options.env?.[AGENT_BROWSER_RESTORE_ENV] === void 0 || options.env[AGENT_BROWSER_RESTORE_ENV] === context2.restoreKey;
7021
7138
  }
7022
7139
  function validateManagedSessionRestoreContextForSpawn(options) {
7023
7140
  const { namespace, ownedContext, parentEnv } = resolveManagedSessionRestorePolicy(options);
@@ -7030,20 +7147,20 @@ function validateManagedSessionRestoreContextForSpawn(options) {
7030
7147
  const env = { ...parentEnv, ...options.env };
7031
7148
  return validLaunchEnvironment(options, ownedContext, env) && ensureManagedSessionRestoreStorageIsSecure({ ...env, ...ownedContext.protectedStorageEnv }, process.platform, namespace);
7032
7149
  }
7033
- function reuseRestoreEnv(options, context) {
7034
- return context.restoreKey !== void 0 && context.restoreKey.length > 0 && context.restoreSuppressed !== true && validateManagedSessionRestoreContextForSpawn(options) ? { [AGENT_BROWSER_RESTORE_ENV]: context.restoreKey } : {};
7150
+ function reuseRestoreEnv(options, context2) {
7151
+ return context2.restoreKey !== void 0 && context2.restoreKey.length > 0 && context2.restoreSuppressed !== true && validateManagedSessionRestoreContextForSpawn(options) ? { [AGENT_BROWSER_RESTORE_ENV]: context2.restoreKey } : {};
7035
7152
  }
7036
- function disabledByPolicy(options, context, namespace) {
7037
- return managedSessionRestoreOptedOut(options) || context?.restoreSuppressed === true || isManagedSessionRestoreIncompatible(options, namespace);
7153
+ function disabledByPolicy(options, context2, namespace) {
7154
+ return managedSessionRestoreOptedOut(options) || context2?.restoreSuppressed === true || isManagedSessionRestoreIncompatible(options, namespace);
7038
7155
  }
7039
- function configuredRestoreEnv(options, context, policy) {
7040
- if (context.restoreDecision !== "enabled" || !policy.restoreState || policy.restoreState.isDisabled(policy.sessionName, policy.namespace)) {
7156
+ function configuredRestoreEnv(options, context2, policy) {
7157
+ if (context2.restoreDecision !== "enabled" || !policy.restoreState || policy.restoreState.isDisabled(policy.sessionName, policy.namespace)) {
7041
7158
  return {};
7042
7159
  }
7043
- if (policy.sessionName === void 0 || policy.sessionName.length === 0 || context.restoreKey === void 0 || context.restoreKey.length === 0 || !validateManagedSessionRestoreContextForSpawn(options)) {
7160
+ if (policy.sessionName === void 0 || policy.sessionName.length === 0 || context2.restoreKey === void 0 || context2.restoreKey.length === 0 || !validateManagedSessionRestoreContextForSpawn(options)) {
7044
7161
  return {};
7045
7162
  }
7046
- return { [AGENT_BROWSER_RESTORE_ENV]: context.restoreKey };
7163
+ return { [AGENT_BROWSER_RESTORE_ENV]: context2.restoreKey };
7047
7164
  }
7048
7165
  function automaticRestoreEnv(options, policy) {
7049
7166
  if (disabledByPolicy({ ...options, parentEnv: policy.parentEnv }, policy.ownedContext, policy.namespace)) {
@@ -7061,37 +7178,37 @@ function getManagedSessionRestoreEnv(options) {
7061
7178
  if (!policy.owned || !policy.restoreState || closesBrowserSession(options.args)) {
7062
7179
  return {};
7063
7180
  }
7064
- const context = policy.ownedContext;
7065
- if (context?.reuseOnly === true) {
7066
- return reuseRestoreEnv(options, context);
7181
+ const context2 = policy.ownedContext;
7182
+ if (context2?.reuseOnly === true) {
7183
+ return reuseRestoreEnv(options, context2);
7067
7184
  }
7068
- if (context?.restoreDecision !== void 0) {
7069
- return configuredRestoreEnv(options, context, policy);
7185
+ if (context2?.restoreDecision !== void 0) {
7186
+ return configuredRestoreEnv(options, context2, policy);
7070
7187
  }
7071
7188
  return automaticRestoreEnv(options, policy);
7072
7189
  }
7073
- function recordEnabledDaemonKey(options, context) {
7190
+ function recordEnabledDaemonKey(options, context2) {
7074
7191
  const { namespace, restoreState, sessionName } = resolveManagedSessionRestorePolicy(options);
7075
7192
  if (options.ownedManagedSession !== true || !restoreState) {
7076
7193
  return;
7077
7194
  }
7078
7195
  const disabled = restoreState.isDisabled(sessionName, namespace);
7079
- if (!disabled && context.restoreKey !== void 0 && context.restoreKey.length > 0) {
7080
- restoreState.recordDaemonRestoreKey(sessionName, namespace, context.restoreKey);
7196
+ if (!disabled && context2.restoreKey !== void 0 && context2.restoreKey.length > 0) {
7197
+ restoreState.recordDaemonRestoreKey(sessionName, namespace, context2.restoreKey);
7081
7198
  } else if (disabled && !restoreState.hasDaemonRestoreKey(sessionName, namespace)) {
7082
7199
  restoreState.recordDaemonRestoreKey(sessionName, namespace, null);
7083
7200
  }
7084
7201
  }
7085
- function commitPlannedDecision(options, context, policy) {
7086
- if (context.restoreDecision === "enabled") {
7087
- recordEnabledDaemonKey(options, context);
7202
+ function commitPlannedDecision(options, context2, policy) {
7203
+ if (context2.restoreDecision === "enabled") {
7204
+ recordEnabledDaemonKey(options, context2);
7088
7205
  return;
7089
7206
  }
7090
7207
  if (!policy.restoreState) {
7091
7208
  return;
7092
7209
  }
7093
7210
  if (options.ownedManagedSession === true) {
7094
- policy.restoreState.recordDaemonRestoreKey(policy.sessionName, policy.namespace, context.expectedDaemonRestoreKey ?? null);
7211
+ policy.restoreState.recordDaemonRestoreKey(policy.sessionName, policy.namespace, context2.expectedDaemonRestoreKey ?? null);
7095
7212
  }
7096
7213
  policy.restoreState.disable(policy.sessionName, policy.namespace);
7097
7214
  }
@@ -7136,7 +7253,7 @@ var init_managed_session_restore = __esm({
7136
7253
  });
7137
7254
 
7138
7255
  // dist/extensions/agent-browser/lib/runtime-session-identity.js
7139
- import { createHash as createHash3, randomUUID as randomUUID4 } from "node:crypto";
7256
+ import { createHash as createHash4, randomUUID as randomUUID5 } from "node:crypto";
7140
7257
  import { basename as basename3 } from "node:path";
7141
7258
  function namespaceFields(namespace) {
7142
7259
  return namespace === void 0 ? {} : { namespace };
@@ -7176,23 +7293,23 @@ function getRestorableManagedSessionName(value, fallbackSessionName) {
7176
7293
  return typeof value === "string" && isRestorableManagedSessionName(value, fallbackSessionName) ? value : void 0;
7177
7294
  }
7178
7295
  function createEphemeralSessionSeed() {
7179
- return randomUUID4();
7296
+ return randomUUID5();
7180
7297
  }
7181
7298
  function createImplicitSessionName(sessionId, cwd, ephemeralSeed, platform = process.platform) {
7182
7299
  const normalizedSessionId = sessionId?.replaceAll("-", "").toLowerCase();
7183
7300
  const identity = normalizedSessionId !== void 0 && normalizedSessionId.length > 0 ? `session:${normalizedSessionId}:cwd:${cwd}` : `ephemeral:${cwd}:${ephemeralSeed}`;
7184
7301
  if (platform === "android") {
7185
- return `${MANAGED_SESSION_NAME_PREFIX2}${createHash3("sha256").update(identity).digest("hex").slice(0, 20)}`;
7302
+ return `${MANAGED_SESSION_NAME_PREFIX2}${createHash4("sha256").update(identity).digest("hex").slice(0, 20)}`;
7186
7303
  }
7187
7304
  const projectSlug = basename3(cwd).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 24);
7188
7305
  const slug = projectSlug.length > 0 ? projectSlug : "project";
7189
- const cwdHash = createHash3("sha256").update(`cwd:${cwd}`).digest("hex").slice(0, 8);
7306
+ const cwdHash = createHash4("sha256").update(`cwd:${cwd}`).digest("hex").slice(0, 8);
7190
7307
  const sessionIdentity = normalizedSessionId !== void 0 && normalizedSessionId.length > 0 ? `session:${normalizedSessionId}` : identity;
7191
- const digest = createHash3("sha256").update(sessionIdentity).digest("hex").slice(0, 12);
7308
+ const digest = createHash4("sha256").update(sessionIdentity).digest("hex").slice(0, 12);
7192
7309
  return `${MANAGED_SESSION_NAME_PREFIX2}${slug}-${digest}-${cwdHash}`;
7193
7310
  }
7194
7311
  function createFreshSessionName(baseSessionName, ephemeralSeed, ordinal) {
7195
- const suffix = createHash3("sha256").update(`fresh:${baseSessionName}:${ephemeralSeed}:${ordinal}`).digest("hex").slice(0, 10);
7312
+ const suffix = createHash4("sha256").update(`fresh:${baseSessionName}:${ephemeralSeed}:${ordinal}`).digest("hex").slice(0, 10);
7196
7313
  return `${baseSessionName}-fresh-${suffix}`;
7197
7314
  }
7198
7315
  var init_runtime_session_identity = __esm({
@@ -7204,126 +7321,6 @@ var init_runtime_session_identity = __esm({
7204
7321
  }
7205
7322
  });
7206
7323
 
7207
- // dist/extensions/agent-browser/lib/batch-lifecycle.js
7208
- function rowCommand(value, fallback) {
7209
- return Array.isArray(value) && value.every((token) => typeof token === "string") ? value : fallback;
7210
- }
7211
- function rowResult(row) {
7212
- if (isRecord(row.result)) {
7213
- return row.result;
7214
- }
7215
- return isRecord(row.data) ? row.data : void 0;
7216
- }
7217
- function rowBrowserLaunched(row, result) {
7218
- const lifecycle = isRecord(row.lifecycle) ? row.lifecycle : result?.lifecycle;
7219
- if (!isRecord(lifecycle) || !isRecord(lifecycle.effectiveLaunch)) {
7220
- return void 0;
7221
- }
7222
- const launched = lifecycle.effectiveLaunch.browserLaunched;
7223
- return typeof launched === "boolean" ? launched : void 0;
7224
- }
7225
- function lifecycleStep(value, fallback) {
7226
- if (!isRecord(value)) {
7227
- return void 0;
7228
- }
7229
- const result = rowResult(value);
7230
- const command = rowCommand(value.command, fallback);
7231
- return {
7232
- result,
7233
- succeeded: value.success === true,
7234
- browserLaunched: rowBrowserLaunched(value, result),
7235
- tokens: command === void 0 ? void 0 : extractUpstreamCommandTokens(command)
7236
- };
7237
- }
7238
- function batchHasSuccessfulCloseAll(data, fallbackCommands = []) {
7239
- if (!Array.isArray(data)) {
7240
- return false;
7241
- }
7242
- return data.some((row, index) => {
7243
- if (!isRecord(row) || row.success !== true) {
7244
- return false;
7245
- }
7246
- const command = rowCommand(row.command, fallbackCommands.at(index));
7247
- return command !== void 0 && !detectConfirmationRequired(row.result) && isCloseAllCommand(extractUpstreamCommandTokens(command));
7248
- });
7249
- }
7250
- function successfulClose(step) {
7251
- return step.succeeded && step.tokens !== void 0 && !detectConfirmationRequired(step.result) && (isCloseCommand(step.tokens[0]) || isSuccessfulNativeConfirmedClose(step.tokens, step.result));
7252
- }
7253
- function closedState(step) {
7254
- const result = step.result;
7255
- const closeData = step.tokens?.[0] === "confirm" && isRecord(result) && isRecord(result.result) ? result.result.data : result;
7256
- return {
7257
- endsClosed: true,
7258
- browserActiveAfterClose: false,
7259
- recordingClosedAfterBatch: true,
7260
- statePath: isRecord(closeData) && typeof closeData.statePath === "string" ? closeData.statePath : void 0
7261
- };
7262
- }
7263
- function recordingState(state, step) {
7264
- const relaunched = step.browserLaunched !== false;
7265
- const browserActiveAfterClose = state.browserActiveAfterClose || relaunched;
7266
- let recordingClosedAfterBatch = state.recordingClosedAfterBatch;
7267
- const subcommand = step.tokens?.[1];
7268
- if (step.succeeded && subcommand === "stop") {
7269
- recordingClosedAfterBatch = true;
7270
- } else if (step.succeeded && browserActiveAfterClose && (subcommand === "start" || subcommand === "restart")) {
7271
- recordingClosedAfterBatch = false;
7272
- }
7273
- return {
7274
- ...state,
7275
- endsClosed: state.endsClosed && !relaunched,
7276
- browserActiveAfterClose,
7277
- recordingClosedAfterBatch
7278
- };
7279
- }
7280
- function advanceClosedState(state, step) {
7281
- if (step.tokens?.[0] === "record") {
7282
- return recordingState(state, step);
7283
- }
7284
- if (step.browserLaunched === false) {
7285
- return state;
7286
- }
7287
- return {
7288
- ...state,
7289
- endsClosed: false,
7290
- browserActiveAfterClose: true,
7291
- recordingClosedAfterBatch: step.tokens === void 0 ? false : state.recordingClosedAfterBatch
7292
- };
7293
- }
7294
- function getSuccessfulBatchCloseLifecycle(rows, fallbackCommands = []) {
7295
- if (!Array.isArray(rows)) {
7296
- return void 0;
7297
- }
7298
- let state;
7299
- for (const [index, row] of rows.entries()) {
7300
- const step = lifecycleStep(row, fallbackCommands.at(index));
7301
- if (step === void 0) {
7302
- continue;
7303
- }
7304
- if (successfulClose(step)) {
7305
- state = closedState(step);
7306
- } else if (state !== void 0) {
7307
- state = advanceClosedState(state, step);
7308
- }
7309
- }
7310
- return state === void 0 ? void 0 : {
7311
- endsClosed: state.endsClosed,
7312
- recordingClosedAfterBatch: state.recordingClosedAfterBatch,
7313
- statePath: state.statePath
7314
- };
7315
- }
7316
- var init_batch_lifecycle = __esm({
7317
- "dist/extensions/agent-browser/lib/batch-lifecycle.js"() {
7318
- "use strict";
7319
- init_argv_descriptor();
7320
- init_command_taxonomy();
7321
- init_parsing();
7322
- init_native_confirmation();
7323
- init_confirmation();
7324
- }
7325
- });
7326
-
7327
7324
  // dist/extensions/agent-browser/lib/runtime-replay-events.js
7328
7325
  function text(value) {
7329
7326
  return typeof value === "string" ? value : void 0;
@@ -9112,15 +9109,15 @@ function sourceSummary(status, candidateCount, electronWorkspace) {
9112
9109
  return "Source lookup found no candidate locations.";
9113
9110
  }
9114
9111
  }
9115
- async function analyzeSourceLookupResults(data, compiled, cwd, context) {
9112
+ async function analyzeSourceLookupResults(data, compiled, cwd, context2) {
9116
9113
  const { distinctSourceCandidates: distinctSourceCandidates2, observeSourceCandidates: observeSourceCandidates2 } = await Promise.resolve().then(() => (init_lookup_source_evidence(), lookup_source_evidence_exports));
9117
9114
  const { scanWorkspaceComponent: scanWorkspaceComponent2 } = await Promise.resolve().then(() => (init_lookup_workspace(), lookup_workspace_exports));
9118
9115
  const observed = observeSourceCandidates2(data);
9119
9116
  const workspace = await scanWorkspaceComponent2(compiled.query, cwd);
9120
9117
  const candidates = distinctSourceCandidates2([...observed.candidates, ...workspace.candidates]);
9121
9118
  const status = sourceStatus(candidates.length, observed.unsupported);
9122
- const electronContext = status === "no-candidates" ? context?.electronContext : void 0;
9123
- const workspaceRoot = context?.workspaceRoot ?? cwd;
9119
+ const electronContext = status === "no-candidates" ? context2?.electronContext : void 0;
9120
+ const workspaceRoot = context2?.workspaceRoot ?? cwd;
9124
9121
  const limitations = [
9125
9122
  "Experimental lookup only reports candidates with evidence; it cannot guarantee a DOM node maps to one source file.",
9126
9123
  "React source hints require the page to be opened with --enable react-devtools and source information from the app build.",
@@ -9538,8 +9535,8 @@ function selectObservationFields(details) {
9538
9535
  return observation2;
9539
9536
  }
9540
9537
  function projectBatchMetadata(step) {
9541
- const { data: _data, ...metadata } = projectAgentBrowserObservation(step, step.success !== false);
9542
- return Object.assign({ index: step.index }, metadata);
9538
+ const { data: _data, stdout: _stdout, ...metadata } = step;
9539
+ return Object.assign({ index: step.index }, projectAgentBrowserObservation(metadata, step.success !== false));
9543
9540
  }
9544
9541
  function projectAgentBrowserObservation(details, succeeded) {
9545
9542
  const observation2 = selectObservationFields(details);
@@ -10459,8 +10456,8 @@ function hasScopedNamesSeen(text3, command) {
10459
10456
  function isUpstreamLocatorMiss(text3, command) {
10460
10457
  return /\bNo element found:\s*(?:getBy[A-Za-z]+|role=|text=|label=|placeholder=|alt=|title=|testid=)/i.test(text3) || /\bElement not found:/i.test(text3) && /\bVerify the selector, role, or name\b/i.test(text3) || /\bnone match name\b/i.test(text3) || hasScopedNamesSeen(text3, command) || /\belement has role\b[\s\S]*\bnone match\b/i.test(text3);
10461
10458
  }
10462
- function classifyNativeFailure(context) {
10463
- const { options, text: text3, command } = context;
10459
+ function classifyNativeFailure(context2) {
10460
+ const { options, text: text3, command } = context2;
10464
10461
  if (options.confirmationRequired === true) {
10465
10462
  return "confirmation-required";
10466
10463
  }
@@ -10475,8 +10472,8 @@ function classifyNativeFailure(context) {
10475
10472
  }
10476
10473
  return void 0;
10477
10474
  }
10478
- function classifyProcessFailure(context) {
10479
- const { options, text: text3 } = context;
10475
+ function classifyProcessFailure(context2) {
10476
+ const { options, text: text3 } = context2;
10480
10477
  if (options.timedOut === true || /\b(?:timed\s+out|timeout exceeded|watchdog|IPC read timeout)\b|must stay under its 30s IPC read timeout|Operation timed out/i.test(text3)) {
10481
10478
  return "timeout";
10482
10479
  }
@@ -10491,8 +10488,8 @@ function classifyProcessFailure(context) {
10491
10488
  }
10492
10489
  return void 0;
10493
10490
  }
10494
- function classifyLifecycleFailure(context) {
10495
- const { options, text: text3 } = context;
10491
+ function classifyLifecycleFailure(context2) {
10492
+ const { options, text: text3 } = context2;
10496
10493
  if (/policy[- ]blocked|blocked by caller policy|caller deny policy|caller allow policy/i.test(text3)) {
10497
10494
  return "policy-blocked";
10498
10495
  }
@@ -10513,8 +10510,8 @@ function reportsSelectorMatchFailure(text3) {
10513
10510
  function reportsUnsupportedSelector(text3) {
10514
10511
  return /\b(?:unsupported|unknown|invalid)\s+(?:selector|locator)\b/i.test(text3) || /\bfailed to parse selector\b/i.test(text3) || /\bselector\b.*\b(?:parse|syntax|unsupported|invalid)\b/i.test(text3) || /(?:\btext=|:has-text\(|\bgetByRole\b|\bgetByText\b)/i.test(text3) && reportsSelectorMatchFailure(text3);
10515
10512
  }
10516
- function classifySelectorFailure(context) {
10517
- const { options, text: text3, command } = context;
10513
+ function classifySelectorFailure(context2) {
10514
+ const { options, text: text3, command } = context2;
10518
10515
  if (/\bUnknown ref\b|\bstale ref\b|@ref may be stale|\bref\b.*\b(?:not found|missing|expired)\b/i.test(text3)) {
10519
10516
  return "stale-ref";
10520
10517
  }
@@ -10530,8 +10527,8 @@ function classifySelectorFailure(context) {
10530
10527
  }
10531
10528
  return reportsSelectorMatchFailure(text3) ? "selector-not-found" : void 0;
10532
10529
  }
10533
- function classifyDownloadFailure(context) {
10534
- const { text: text3, command } = context;
10530
+ function classifyDownloadFailure(context2) {
10531
+ const { text: text3, command } = context2;
10535
10532
  return (command === "download" || text3.includes("wait --download") || /\bdownload\b/i.test(text3)) && /missing|not verified|not found|failed|timeout|timed out/i.test(text3) ? "download-not-verified" : "upstream-error";
10536
10533
  }
10537
10534
  function classifyAgentBrowserFailureCategory(options) {
@@ -10542,8 +10539,8 @@ function classifyAgentBrowserFailureCategory(options) {
10542
10539
  options.spawnError,
10543
10540
  options.stderr
10544
10541
  ].filter(Boolean).join("\n");
10545
- const context = { options, text: text3, command: options.command ?? "" };
10546
- return classifyNativeFailure(context) ?? classifyProcessFailure(context) ?? classifyLifecycleFailure(context) ?? classifySelectorFailure(context) ?? classifyDownloadFailure(context);
10542
+ const context2 = { options, text: text3, command: options.command ?? "" };
10543
+ return classifyNativeFailure(context2) ?? classifyProcessFailure(context2) ?? classifyLifecycleFailure(context2) ?? classifySelectorFailure(context2) ?? classifyDownloadFailure(context2);
10547
10544
  }
10548
10545
  function buildAgentBrowserResultCategoryDetails(options) {
10549
10546
  if (options.succeeded) {
@@ -12054,9 +12051,9 @@ var init_process_child = __esm({
12054
12051
  exitCode = null;
12055
12052
  timer;
12056
12053
  completed = false;
12057
- constructor(child, complete, context) {
12054
+ constructor(child, complete, context2) {
12058
12055
  this.complete = complete;
12059
- this.context = context;
12056
+ this.context = context2;
12060
12057
  child.once("exit", (code) => {
12061
12058
  this.exited = true;
12062
12059
  this.exitCode = code;
@@ -12076,13 +12073,13 @@ var init_process_child = __esm({
12076
12073
  }
12077
12074
  this.completed = true;
12078
12075
  this.clear();
12079
- const context = this.context();
12076
+ const context2 = this.context();
12080
12077
  this.complete(resolveSpawnedChildExitCode({
12081
12078
  closeCode,
12082
12079
  exitCode: this.exitCode,
12083
12080
  useExitFallback: this.exited,
12084
- timedOut: context.timedOut,
12085
- spawnError: context.spawnError
12081
+ timedOut: context2.timedOut,
12082
+ spawnError: context2.spawnError
12086
12083
  }));
12087
12084
  }
12088
12085
  clear() {
@@ -12281,6 +12278,8 @@ function canOperateWithoutVerifiedPage(command, subcommand) {
12281
12278
  return subcommand !== void 0 && subcommand !== "new";
12282
12279
  case "get":
12283
12280
  return subcommand === "url";
12281
+ case "session":
12282
+ return subcommand === void 0;
12284
12283
  case "webmcp":
12285
12284
  return ["result", "cancel"].includes(subcommand ?? "");
12286
12285
  case "record":
@@ -15277,7 +15276,7 @@ var init_browser_execution_claim_codec = __esm({
15277
15276
  });
15278
15277
 
15279
15278
  // dist/extensions/agent-browser/lib/browser-execution-identity.js
15280
- import { createHash as createHash4 } from "node:crypto";
15279
+ import { createHash as createHash5 } from "node:crypto";
15281
15280
  import { lstat as lstat3, mkdir as mkdir3, realpath } from "node:fs/promises";
15282
15281
  import { tmpdir as tmpdir2 } from "node:os";
15283
15282
  import { join as join18 } from "node:path";
@@ -15288,7 +15287,7 @@ function getCoordinationDirectory(platform = process.platform) {
15288
15287
  return platform === "android" ? join18(tmpdir2(), `pi-agent-browser-policy${suffix2}`) : `/tmp/pi-agent-browser-policy${suffix2}`;
15289
15288
  }
15290
15289
  const user = process.env.USERNAME ?? process.env.USER ?? "unknown";
15291
- const suffix = createHash4("sha256").update(user).digest("hex").slice(0, 12);
15290
+ const suffix = createHash5("sha256").update(user).digest("hex").slice(0, 12);
15292
15291
  return join18(tmpdir2(), `pi-agent-browser-policy-${suffix}`);
15293
15292
  }
15294
15293
  function directoryOwnerTrusted(entry, platform) {
@@ -15336,7 +15335,7 @@ async function resolveBrowserExecutionIdentity(options) {
15336
15335
  };
15337
15336
  }
15338
15337
  function getBrowserExecutionLockPath(identity) {
15339
- return join18(getCoordinationDirectory(), `.pi-agent-browser-policy-${createHash4("sha256").update(identity.socketContext).digest("hex")}.lock-v4`);
15338
+ return join18(getCoordinationDirectory(), `.pi-agent-browser-policy-${createHash5("sha256").update(identity.socketContext).digest("hex")}.lock-v4`);
15340
15339
  }
15341
15340
  var init_browser_execution_identity = __esm({
15342
15341
  "dist/extensions/agent-browser/lib/browser-execution-identity.js"() {
@@ -15349,7 +15348,7 @@ var init_browser_execution_identity = __esm({
15349
15348
  });
15350
15349
 
15351
15350
  // dist/extensions/agent-browser/lib/browser-execution-claim-storage.js
15352
- import { randomInt as randomInt2, randomUUID as randomUUID5 } from "node:crypto";
15351
+ import { randomInt as randomInt2, randomUUID as randomUUID6 } from "node:crypto";
15353
15352
  import { lstat as lstat4, readFile as readFile6, readdir as readdir6, rename, rm as rm8 } from "node:fs/promises";
15354
15353
  import { basename as basename5, dirname as dirname11, join as join19 } from "node:path";
15355
15354
  function secureEntry(entry, directory) {
@@ -15482,7 +15481,7 @@ async function moveOwnedClaim(path, movedPath, token, deadline) {
15482
15481
  }
15483
15482
  }
15484
15483
  async function removeClaimOwnedBy(path, token, deadline = 0) {
15485
- const movedPath = join19(dirname11(path), `.pi-agent-browser-policy-remove-${token}-${randomUUID5()}`);
15484
+ const movedPath = join19(dirname11(path), `.pi-agent-browser-policy-remove-${token}-${randomUUID6()}`);
15486
15485
  const movement = await moveOwnedClaim(path, movedPath, token, deadline);
15487
15486
  if (movement === "absent") {
15488
15487
  return true;
@@ -15559,7 +15558,7 @@ var init_browser_execution_claim_storage = __esm({
15559
15558
  });
15560
15559
 
15561
15560
  // dist/extensions/agent-browser/lib/browser-execution-claims.js
15562
- import { randomUUID as randomUUID6 } from "node:crypto";
15561
+ import { randomUUID as randomUUID7 } from "node:crypto";
15563
15562
  import { lstat as lstat5, mkdir as mkdir4, rename as rename2, rm as rm9, writeFile as writeFile2 } from "node:fs/promises";
15564
15563
  import { join as join20 } from "node:path";
15565
15564
  function claimPrecedes(left, right) {
@@ -15622,7 +15621,7 @@ async function prepareClaim(identity, budget) {
15622
15621
  return void 0;
15623
15622
  }
15624
15623
  const basePath = getBrowserExecutionLockPath(identity);
15625
- const token = randomUUID6();
15624
+ const token = randomUUID7();
15626
15625
  const startIdentity = await readProcessStartIdentity(process.pid, process.platform, budget);
15627
15626
  if (startIdentity === void 0 || startIdentity.length === 0) {
15628
15627
  return void 0;
@@ -16157,12 +16156,12 @@ var init_managed_session_close = __esm({
16157
16156
  function hasElectronAttachmentIdentity(record) {
16158
16157
  return record.webSocketDebuggerUrl !== void 0 && record.webSocketDebuggerUrl !== "" && record.sessionName !== void 0 && record.sessionName !== "";
16159
16158
  }
16160
- function restoredAttachmentTarget(context, record) {
16161
- const cwd = context.cwd;
16159
+ function restoredAttachmentTarget(context2, record) {
16160
+ const cwd = context2.cwd;
16162
16161
  if (cwd === void 0 || cwd === "" || !record || !hasElectronAttachmentIdentity(record)) {
16163
16162
  return void 0;
16164
16163
  }
16165
- if (record.cleanupState === "cleaned" || getAgentBrowserSessionIdentityKey(record.sessionName ?? "", record.namespace) !== getAgentBrowserSessionIdentityKey(context.sessionName, context.namespace)) {
16164
+ if (record.cleanupState === "cleaned" || getAgentBrowserSessionIdentityKey(record.sessionName ?? "", record.namespace) !== getAgentBrowserSessionIdentityKey(context2.sessionName, context2.namespace)) {
16166
16165
  return void 0;
16167
16166
  }
16168
16167
  return { cwd, record };
@@ -16174,8 +16173,8 @@ function attachmentConnectionMatches(connection, record, status) {
16174
16173
  return isRecord(connection) && typeof connection.cdpUrl === "string" && (connection.cdpUrl === record.webSocketDebuggerUrl || status.targets.some((target) => target.webSocketDebuggerUrl === connection.cdpUrl));
16175
16174
  }
16176
16175
  async function verifyRestoredElectronAttachment(options) {
16177
- const { context, signal } = options;
16178
- const attachment = restoredAttachmentTarget(context, options.electronLaunchRecord);
16176
+ const { context: context2, signal } = options;
16177
+ const attachment = restoredAttachmentTarget(context2, options.electronLaunchRecord);
16179
16178
  if (!attachment) {
16180
16179
  return false;
16181
16180
  }
@@ -16186,10 +16185,10 @@ async function verifyRestoredElectronAttachment(options) {
16186
16185
  const connection = await withAttachedBrowserSessionContext(true, () => withOwnedManagedSessionContext(void 0, () => runSessionCommandData({
16187
16186
  args: ["get", "cdp-url"],
16188
16187
  cwd: attachment.cwd,
16189
- env: getHeadedManagedAutosaveEnv(context.headedManagedAutosaveInterval),
16190
- namespace: context.namespace,
16188
+ env: getHeadedManagedAutosaveEnv(context2.headedManagedAutosaveInterval),
16189
+ namespace: context2.namespace,
16191
16190
  pinNamespace: true,
16192
- sessionName: context.sessionName,
16191
+ sessionName: context2.sessionName,
16193
16192
  signal,
16194
16193
  timeoutMs: options.electronVerificationTimeoutMs
16195
16194
  })));
@@ -16199,17 +16198,17 @@ async function verifyRestoredElectronAttachment(options) {
16199
16198
  !(signal?.aborted ?? false) && attachmentConnectionMatches(connection, attachment.record, status)
16200
16199
  );
16201
16200
  }
16202
- function reconcileDaemonReceipt(context, daemon, receipt) {
16201
+ function reconcileDaemonReceipt(context2, daemon, receipt) {
16203
16202
  if (daemon.status === "inactive") {
16204
- context.restoreState.forgetDaemonRestoreKey(context.sessionName, context.namespace);
16203
+ context2.restoreState.forgetDaemonRestoreKey(context2.sessionName, context2.namespace);
16205
16204
  }
16206
- if (daemon.status !== "active" || receipt === void 0 || context.restoreState.hasDaemonRestoreKey(context.sessionName, context.namespace)) {
16205
+ if (daemon.status !== "active" || receipt === void 0 || context2.restoreState.hasDaemonRestoreKey(context2.sessionName, context2.namespace)) {
16207
16206
  return;
16208
16207
  }
16209
16208
  if (daemon.generation === receipt.generation && daemon.restoreKey === receipt.restoreKey) {
16210
- context.restoreState.recordDaemonRestoreKey(context.sessionName, context.namespace, daemon.restoreKey, daemon.generation);
16209
+ context2.restoreState.recordDaemonRestoreKey(context2.sessionName, context2.namespace, daemon.restoreKey, daemon.generation);
16211
16210
  } else {
16212
- context.restoreState.forgetDaemonRestoreKey(context.sessionName, context.namespace);
16211
+ context2.restoreState.forgetDaemonRestoreKey(context2.sessionName, context2.namespace);
16213
16212
  }
16214
16213
  }
16215
16214
  function daemonPolicyMismatch(daemon, restoreDisabledPolicyNeedsProvenance, hasKnownDaemonRestoreKey) {
@@ -16223,40 +16222,50 @@ function daemonPolicyMismatch(daemon, restoreDisabledPolicyNeedsProvenance, hasK
16223
16222
  };
16224
16223
  }
16225
16224
  async function validateReusableDaemonPolicy(options, daemon) {
16226
- const { context } = options;
16227
- const stickyDisabled = context.restoreState.isDisabled(context.sessionName, context.namespace);
16228
- let hasKnownDaemonRestoreKey = context.restoreState.hasDaemonRestoreKey(context.sessionName, context.namespace);
16229
- const knownDaemonRestoreKey = context.restoreState.getDaemonRestoreKey(context.sessionName, context.namespace);
16230
- const requestedDaemonRestoreKey = context.restoreDecision === "enabled" && stickyDisabled ? knownDaemonRestoreKey ?? null : context.expectedDaemonRestoreKey;
16225
+ const { context: context2 } = options;
16226
+ const stickyDisabled = context2.restoreState.isDisabled(context2.sessionName, context2.namespace);
16227
+ let hasKnownDaemonRestoreKey = context2.restoreState.hasDaemonRestoreKey(context2.sessionName, context2.namespace);
16228
+ const knownDaemonRestoreKey = context2.restoreState.getDaemonRestoreKey(context2.sessionName, context2.namespace);
16229
+ const requestedDaemonRestoreKey = context2.restoreDecision === "enabled" && stickyDisabled ? knownDaemonRestoreKey ?? null : context2.expectedDaemonRestoreKey;
16231
16230
  if (daemon.status === "unknown") {
16232
16231
  return {
16233
16232
  error: `The wrapper could not verify this managed session's live daemon restore policy. Retry, close that session, or use sessionMode: "fresh".`
16234
16233
  };
16235
16234
  }
16236
- const restoreDisabledPolicyNeedsProvenance = stickyDisabled || context.restoreDecision !== "enabled";
16237
- if (daemon.status === "active" && restoreDisabledPolicyNeedsProvenance && !hasKnownDaemonRestoreKey && daemon.restoreKey === requestedDaemonRestoreKey) {
16235
+ const restoreDisabledPolicyNeedsProvenance = stickyDisabled || context2.restoreDecision !== "enabled";
16236
+ const verifyAttachment = daemon.status === "active" && restoreDisabledPolicyNeedsProvenance && !hasKnownDaemonRestoreKey && daemon.restoreKey === requestedDaemonRestoreKey;
16237
+ if (verifyAttachment) {
16238
16238
  hasKnownDaemonRestoreKey = await verifyRestoredElectronAttachment(options);
16239
16239
  }
16240
- return finishReusableDaemonPolicy(context, daemon, {
16240
+ return finishReusableDaemonPolicy(context2, daemon, {
16241
16241
  restoreDisabledPolicyNeedsProvenance,
16242
- requestedDaemonRestoreKey
16242
+ requestedDaemonRestoreKey,
16243
+ includeGeneration: options.includeGeneration,
16244
+ verifyAttachment
16243
16245
  }, hasKnownDaemonRestoreKey);
16244
16246
  }
16245
- function finishReusableDaemonPolicy(context, daemon, policy, hasKnownDaemonRestoreKey) {
16247
+ function finishReusableDaemonPolicy(context2, daemon, policy, hasKnownDaemonRestoreKey) {
16246
16248
  const activePolicyMatches = daemon.status === "active" && (!policy.restoreDisabledPolicyNeedsProvenance || hasKnownDaemonRestoreKey) && daemon.restoreKey === policy.requestedDaemonRestoreKey;
16247
16249
  if (activePolicyMatches) {
16248
- context.restoreState.recordDaemonRestoreKey(context.sessionName, context.namespace, daemon.restoreKey);
16250
+ context2.restoreState.recordDaemonRestoreKey(context2.sessionName, context2.namespace, daemon.restoreKey);
16249
16251
  }
16250
- return !["inactive", "missing-binary"].includes(daemon.status) && !activePolicyMatches ? daemonPolicyMismatch(daemon, policy.restoreDisabledPolicyNeedsProvenance, hasKnownDaemonRestoreKey) : { daemonStatus: daemon.status };
16252
+ return !["inactive", "missing-binary"].includes(daemon.status) && !activePolicyMatches ? daemonPolicyMismatch(daemon, policy.restoreDisabledPolicyNeedsProvenance, hasKnownDaemonRestoreKey) : {
16253
+ daemonStatus: daemon.status,
16254
+ // The native CDP provenance helper can change the browser; never reuse its preceding sample.
16255
+ generationInspection: policy.includeGeneration === true && !policy.verifyAttachment ? daemon : void 0
16256
+ };
16257
+ }
16258
+ function daemonGenerationRequired(context2, receipt, includeGeneration) {
16259
+ return includeGeneration === true || receipt !== void 0 && !context2.restoreState.hasDaemonRestoreKey(context2.sessionName, context2.namespace);
16251
16260
  }
16252
16261
  async function acquireOwnedManagedSessionDaemonPolicy(options) {
16253
- const { context, signal } = options;
16254
- if (context.cwd === void 0 || context.cwd === "") {
16262
+ const { context: context2, signal } = options;
16263
+ if (context2.cwd === void 0 || context2.cwd === "") {
16255
16264
  return { error: "Managed-session policy validation requires the wrapper-owned session cwd." };
16256
16265
  }
16257
16266
  const lock = await acquireManagedSessionPolicyLock({
16258
- namespace: context.namespace,
16259
- sessionName: context.sessionName,
16267
+ namespace: context2.namespace,
16268
+ sessionName: context2.sessionName,
16260
16269
  signal
16261
16270
  });
16262
16271
  if (!lock) {
@@ -16265,19 +16274,19 @@ async function acquireOwnedManagedSessionDaemonPolicy(options) {
16265
16274
  };
16266
16275
  }
16267
16276
  try {
16268
- const receipt = context.restoreState.getDaemonReceipt(context.sessionName, context.namespace);
16277
+ const receipt = context2.restoreState.getDaemonReceipt(context2.sessionName, context2.namespace);
16269
16278
  const daemon = await inspectManagedSessionDaemon({
16270
- cwd: context.cwd,
16271
- includeGeneration: receipt !== void 0 && !context.restoreState.hasDaemonRestoreKey(context.sessionName, context.namespace),
16272
- headedManagedAutosaveInterval: context.headedManagedAutosaveInterval,
16273
- namespace: context.namespace,
16274
- sessionName: context.sessionName,
16279
+ cwd: context2.cwd,
16280
+ includeGeneration: daemonGenerationRequired(context2, receipt, options.includeGeneration),
16281
+ headedManagedAutosaveInterval: context2.headedManagedAutosaveInterval,
16282
+ namespace: context2.namespace,
16283
+ sessionName: context2.sessionName,
16275
16284
  signal
16276
16285
  });
16277
- reconcileDaemonReceipt(context, daemon, receipt);
16286
+ reconcileDaemonReceipt(context2, daemon, receipt);
16278
16287
  if (options.mode === "close") {
16279
16288
  if (daemon.status === "active") {
16280
- context.restoreState.recordDaemonRestoreKey(context.sessionName, context.namespace, daemon.restoreKey);
16289
+ context2.restoreState.recordDaemonRestoreKey(context2.sessionName, context2.namespace, daemon.restoreKey);
16281
16290
  }
16282
16291
  return { daemonStatus: daemon.status, lock };
16283
16292
  }
@@ -16518,9 +16527,10 @@ function firstNonempty(values) {
16518
16527
  }
16519
16528
  async function inspectDarwinApp(appPath) {
16520
16529
  const framework = join22(appPath, "Contents", "Frameworks", "Electron Framework.framework");
16521
- const hasFramework = await isDirectory(framework);
16522
- const hasPayload = await hasElectronAppPayload(join22(appPath, "Contents", "Resources"));
16523
- if (!hasFramework || !hasPayload) {
16530
+ if (!await isDirectory(framework)) {
16531
+ return void 0;
16532
+ }
16533
+ if (!await hasElectronAppPayload(join22(appPath, "Contents", "Resources"))) {
16524
16534
  return void 0;
16525
16535
  }
16526
16536
  const info = await readMacInfoPlist(appPath);
@@ -17707,14 +17717,14 @@ function buildSourceLookupElectronNextActions(sourceLookup) {
17707
17717
  return actions;
17708
17718
  }
17709
17719
  function collectElectronBroadGetTextScopeDiagnostics(options) {
17710
- const context = getSourceLookupElectronContext(options);
17711
- if (!context) {
17720
+ const context2 = getSourceLookupElectronContext(options);
17721
+ if (!context2) {
17712
17722
  return [];
17713
17723
  }
17714
17724
  const electronContext = {
17715
- launchId: context.launchId,
17716
- sessionName: context.sessionName,
17717
- url: context.url
17725
+ launchId: context2.launchId,
17726
+ sessionName: context2.sessionName,
17727
+ url: context2.url
17718
17728
  };
17719
17729
  return getSuccessfulGetTextSelectors(options).filter(isBroadGetTextSelector).map((selector) => ({
17720
17730
  electronContext,
@@ -19247,24 +19257,34 @@ async function statTimeoutArtifactPath(absolutePath) {
19247
19257
  return { exists: false };
19248
19258
  }
19249
19259
  async function collectTimeoutArtifactEvidence(cwd, steps) {
19250
- const evidence = [];
19251
- for (const step of steps) {
19260
+ const paths = steps.flatMap((step) => {
19252
19261
  const path = getTimeoutStepArtifactPath(step.args);
19253
19262
  if (path === void 0 || path === "") {
19254
- continue;
19263
+ return [];
19255
19264
  }
19256
19265
  const absolutePath = isAbsolute8(path) ? path : resolve11(cwd, path);
19266
+ return [{ absolutePath, path, stepIndex: step.index }];
19267
+ });
19268
+ return Promise.all(paths.map(async ({ absolutePath, path, stepIndex }) => {
19257
19269
  const artifact = await statTimeoutArtifactPath(absolutePath);
19258
- evidence.push({
19270
+ if (artifact.exists) {
19271
+ return {
19272
+ absolutePath,
19273
+ exists: true,
19274
+ path,
19275
+ sizeBytes: artifact.sizeBytes,
19276
+ state: "verified",
19277
+ stepIndex
19278
+ };
19279
+ }
19280
+ return {
19259
19281
  absolutePath,
19260
- exists: artifact.exists,
19282
+ exists: false,
19261
19283
  path,
19262
- ...artifact.exists ? { sizeBytes: artifact.sizeBytes } : {},
19263
- state: artifact.exists ? "verified" : "missing",
19264
- stepIndex: step.index
19265
- });
19266
- }
19267
- return evidence;
19284
+ state: "missing",
19285
+ stepIndex
19286
+ };
19287
+ }));
19268
19288
  }
19269
19289
  function getPlannedCurrentPageUrl(steps) {
19270
19290
  for (let index = steps.length - 1; index >= 0; index -= 1) {
@@ -20425,10 +20445,10 @@ var init_final_result = __esm({
20425
20445
  });
20426
20446
 
20427
20447
  // dist/extensions/agent-browser/lib/orchestration/electron-host/policy.js
20428
- async function acquireElectronPolicy(options, context) {
20448
+ async function acquireElectronPolicy(options, context2) {
20429
20449
  try {
20430
20450
  return await acquireOwnedManagedSessionDaemonPolicy({
20431
- context,
20451
+ context: context2,
20432
20452
  electronLaunchRecord: options.electronLaunchRecord,
20433
20453
  electronVerificationTimeoutMs: options.timeoutMs,
20434
20454
  signal: options.signal
@@ -20454,7 +20474,7 @@ async function withOwnedElectronManagedSessionPolicy(options, run) {
20454
20474
  if (autosavePolicyChangeError !== void 0 && autosavePolicyChangeError.length > 0) {
20455
20475
  throw new ElectronManagedSessionPolicyError(autosavePolicyChangeError);
20456
20476
  }
20457
- const context = buildOwnedManagedSessionRestoreContext({
20477
+ const context2 = buildOwnedManagedSessionRestoreContext({
20458
20478
  args: [
20459
20479
  "--namespace",
20460
20480
  options.namespace ?? "",
@@ -20469,13 +20489,13 @@ async function withOwnedElectronManagedSessionPolicy(options, run) {
20469
20489
  namespace: options.namespace,
20470
20490
  restoreState: options.restoreState
20471
20491
  });
20472
- if (!context) {
20492
+ if (!context2) {
20473
20493
  throw new ElectronManagedSessionPolicyError("Electron helper could not establish wrapper ownership for its managed session.");
20474
20494
  }
20475
- const policy = await acquireElectronPolicy(options, context);
20495
+ const policy = await acquireElectronPolicy(options, context2);
20476
20496
  try {
20477
20497
  requirePolicyLock(policy, options.signal);
20478
- return await withOwnedManagedSessionContext(context, run);
20498
+ return await withOwnedManagedSessionContext(context2, run);
20479
20499
  } finally {
20480
20500
  await policy.lock?.release();
20481
20501
  }
@@ -20946,17 +20966,17 @@ function formatElectronProbeFocusedElement(element) {
20946
20966
  const suffix = formatFocusedElementAttributes(element);
20947
20967
  return `Focused: ${descriptor}${label !== void 0 && label.length > 0 ? ` "${label}"` : ""}${suffix.length > 0 ? ` (${suffix})` : ""}`;
20948
20968
  }
20949
- function formatElectronProbeContextText(context) {
20950
- if (context.mode === "launchId") {
20951
- return `Probe context: wrapper launch ${context.launchId ?? "undefined"} session ${context.sessionName}.`;
20969
+ function formatElectronProbeContextText(context2) {
20970
+ if (context2.mode === "launchId") {
20971
+ return `Probe context: wrapper launch ${context2.launchId ?? "undefined"} session ${context2.sessionName}.`;
20952
20972
  }
20953
- if (context.note !== void 0 && context.note.length > 0) {
20954
- return `Probe context: current managed session ${context.sessionName}; ${context.note}`;
20973
+ if (context2.note !== void 0 && context2.note.length > 0) {
20974
+ return `Probe context: current managed session ${context2.sessionName}; ${context2.note}`;
20955
20975
  }
20956
- if (context.launchId !== void 0 && context.launchId.length > 0) {
20957
- return `Probe context: current managed session ${context.sessionName} maps to Electron launch ${context.launchId}.`;
20976
+ if (context2.launchId !== void 0 && context2.launchId.length > 0) {
20977
+ return `Probe context: current managed session ${context2.sessionName} maps to Electron launch ${context2.launchId}.`;
20958
20978
  }
20959
- return `Probe context: current managed session ${context.sessionName} only; pass electron.probe.launchId to compare wrapper-tracked launch status.`;
20979
+ return `Probe context: current managed session ${context2.sessionName} only; pass electron.probe.launchId to compare wrapper-tracked launch status.`;
20960
20980
  }
20961
20981
  function formatElectronProbeLaunchStatusText(status, probe) {
20962
20982
  if (!status) {
@@ -21200,7 +21220,7 @@ async function inspectProbeIdentity(options, identity, input, visibleInput) {
21200
21220
  record: identity.record,
21201
21221
  statusTargets: status.targets
21202
21222
  }) : void 0;
21203
- const context = probeContext(identity, input, probe);
21223
+ const context2 = probeContext(identity, input, probe);
21204
21224
  const target = publishProbePageState(options.sessionPageState, probe, identity.namespace);
21205
21225
  return buildElectronProbeResult({
21206
21226
  compiledElectron: visibleInput,
@@ -21209,7 +21229,7 @@ async function inspectProbeIdentity(options, identity, input, visibleInput) {
21209
21229
  mismatch,
21210
21230
  namespace: identity.namespace,
21211
21231
  probe,
21212
- probeContext: context,
21232
+ probeContext: context2,
21213
21233
  record: identity.record,
21214
21234
  sessionTabTarget: target,
21215
21235
  status
@@ -21354,11 +21374,11 @@ function formatSnapshotSummary(data) {
21354
21374
  if (isRecord(data.snapshot) && data.snapshot.kind !== "full") {
21355
21375
  return `Snapshot ${stringifyUnknown(data.snapshot.kind)}: revision ${stringifyUnknown(data.snapshot.revision)} on ${origin}`;
21356
21376
  }
21357
- return `Snapshot: ${getSnapshotRefEntries(data).length} refs on ${origin}`;
21377
+ return `Snapshot: ${Object.keys(getSnapshotRefRecord(data) ?? {}).length} refs on ${origin}`;
21358
21378
  }
21359
21379
  function formatRawSnapshotText(data) {
21360
21380
  const origin = getSnapshotOrigin(data);
21361
- const refs = getSnapshotRefEntries(data).length;
21381
+ const refs = Object.keys(getSnapshotRefRecord(data) ?? {}).length;
21362
21382
  const snapshot = getSnapshotText(data);
21363
21383
  if (isRecord(data.snapshot) && data.snapshot.kind !== "full") {
21364
21384
  return `Origin: ${origin}
@@ -21932,7 +21952,7 @@ var init_snapshot_spill = __esm({
21932
21952
 
21933
21953
  // dist/extensions/agent-browser/lib/results/snapshot.js
21934
21954
  function shouldCompactSnapshot(rawText, data) {
21935
- return rawText.length > 6e3 || countLines(getSnapshotText(data) ?? "") > 80 || getSnapshotRefEntries(data).length > 60;
21955
+ return rawText.length > 6e3 || countLines(getSnapshotText(data) ?? "") > 80 || Object.keys(getSnapshotRefRecord(data) ?? {}).length > 60;
21936
21956
  }
21937
21957
  async function getSnapshotSpill(data, store) {
21938
21958
  try {
@@ -26007,7 +26027,7 @@ var init_launch_process = __esm({
26007
26027
  });
26008
26028
 
26009
26029
  // dist/extensions/agent-browser/lib/electron/launch.js
26010
- import { randomUUID as randomUUID10 } from "node:crypto";
26030
+ import { randomUUID as randomUUID11 } from "node:crypto";
26011
26031
  import { rm as rm13 } from "node:fs/promises";
26012
26032
  function normalizeTimeoutMs(timeoutMs) {
26013
26033
  if (typeof timeoutMs !== "number" || !Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) {
@@ -26265,7 +26285,7 @@ var init_launch = __esm({
26265
26285
  createdAtMs: Date.now(),
26266
26286
  desktopId: this.target.desktopId,
26267
26287
  executablePath: this.target.executablePath,
26268
- launchId: `electron-${randomUUID10()}`,
26288
+ launchId: `electron-${randomUUID11()}`,
26269
26289
  launchedByWrapper: true,
26270
26290
  packageSource: this.target.packageSource,
26271
26291
  pid,
@@ -26783,6 +26803,7 @@ function prepareSessionPlan(owners, facts, preparedArgs, request) {
26783
26803
  return {
26784
26804
  plan,
26785
26805
  session: {
26806
+ hasPriorRefs: (owners.pageState.get(getSessionContextKey(plan.sessionName, plan.namespace)).refSnapshot?.refIds.length ?? 0) > 0,
26786
26807
  browserIndependent,
26787
26808
  readConfirmation,
26788
26809
  recordedOwnedSession: recorded,
@@ -26828,12 +26849,12 @@ function daemonReuseError(plan, session, policy) {
26828
26849
  }
26829
26850
  return void 0;
26830
26851
  }
26831
- function applyColdCompatibility(plan, session, context, status) {
26852
+ function applyColdCompatibility(plan, session, context2, status) {
26832
26853
  if (isCloseCommand(plan.commandInfo.command) || status !== "inactive" || session.compatibilityUserAgent === void 0 || session.compatibilityUserAgent === "" || session.compatibilityUserAgentApplied) {
26833
- return { plan, ownedManagedSession: context };
26854
+ return { plan, ownedManagedSession: context2 };
26834
26855
  }
26835
26856
  return {
26836
- ownedManagedSession: { ...context, compatibilityUserAgent: session.compatibilityUserAgent },
26857
+ ownedManagedSession: { ...context2, compatibilityUserAgent: session.compatibilityUserAgent },
26837
26858
  plan: {
26838
26859
  ...plan,
26839
26860
  effectiveArgs: ["--user-agent", session.compatibilityUserAgent, ...plan.effectiveArgs]
@@ -26842,25 +26863,28 @@ function applyColdCompatibility(plan, session, context, status) {
26842
26863
  }
26843
26864
  async function prepareDaemonPolicy(process2, electronLaunchRecord, planning) {
26844
26865
  const { plan, session } = planning;
26845
- const context = session.ownedManagedSession;
26846
- if (session.browserIndependent || planHasValidationError(plan) || !context) {
26866
+ const context2 = session.ownedManagedSession;
26867
+ if (session.browserIndependent || planHasValidationError(plan) || !context2) {
26847
26868
  return { plan, session, policy: { inactive: false } };
26848
26869
  }
26870
+ const closeCommand = isCloseCommand(plan.commandInfo.command);
26849
26871
  const policy = await acquireOwnedManagedSessionDaemonPolicy({
26850
- context,
26872
+ context: context2,
26851
26873
  electronLaunchRecord,
26852
26874
  electronVerificationTimeoutMs: process2.timeoutMs,
26853
- mode: isCloseCommand(plan.commandInfo.command) ? "close" : "reuse",
26875
+ mode: closeCommand ? "close" : "reuse",
26876
+ includeGeneration: session.hasPriorRefs && !closeCommand,
26854
26877
  signal: process2.signal
26855
26878
  });
26856
26879
  const error = daemonReuseError(plan, session, policy);
26857
- const resolved = error !== void 0 && error !== "" ? { plan: withPlanValidationError(plan, error), ownedManagedSession: context } : applyColdCompatibility(plan, session, context, policy.daemonStatus);
26880
+ const resolved = error !== void 0 && error !== "" ? { plan: withPlanValidationError(plan, error), ownedManagedSession: context2 } : applyColdCompatibility(plan, session, context2, policy.daemonStatus);
26858
26881
  return {
26859
26882
  plan: resolved.plan,
26860
26883
  session: { ...session, ownedManagedSession: resolved.ownedManagedSession },
26861
26884
  policy: {
26862
26885
  lock: policy.lock,
26863
26886
  inactive: policy.daemonStatus === "inactive",
26887
+ generationInspection: policy.generationInspection,
26864
26888
  cleanupOnlyReason: policy.error !== void 0 && policy.error !== "" ? policy.cleanupOnlyReason : void 0
26865
26889
  }
26866
26890
  };
@@ -26878,7 +26902,7 @@ async function prepareChromeStartupArgs(facts, planning, request) {
26878
26902
  const { plan, session, policy } = planning;
26879
26903
  let inactive = policy.inactive;
26880
26904
  if (!session.ownedManagedSession) {
26881
- inactive = facts.daemonInactive ?? (plan.sessionName !== void 0 && (await inspectManagedSessionDaemon({
26905
+ inactive = (facts.initialDaemonObservation?.identity === getAgentBrowserSessionIdentityKey(plan.sessionName ?? "", plan.namespace) ? facts.initialDaemonObservation.daemon.status === "inactive" : void 0) ?? (plan.sessionName !== void 0 && (await inspectManagedSessionDaemon({
26882
26906
  cwd: facts.cwd,
26883
26907
  signal: facts.signal,
26884
26908
  sessionName: plan.sessionName,
@@ -26891,6 +26915,7 @@ var init_prepare_daemon = __esm({
26891
26915
  "dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-daemon.js"() {
26892
26916
  "use strict";
26893
26917
  init_argv_descriptor();
26918
+ init_argv_grammar();
26894
26919
  init_command_policy();
26895
26920
  init_command_taxonomy();
26896
26921
  init_managed_session_daemon_policy();
@@ -26899,8 +26924,8 @@ var init_prepare_daemon = __esm({
26899
26924
  });
26900
26925
 
26901
26926
  // dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-page-state.js
26902
- async function inspectPreparationGeneration(process2, identity) {
26903
- return inspectManagedSessionDaemon({
26927
+ async function inspectPreparationGeneration(process2, identity, priorInspection) {
26928
+ return priorInspection ?? inspectManagedSessionDaemon({
26904
26929
  ...process2,
26905
26930
  namespace: identity.namespace,
26906
26931
  sessionName: identity.sessionName,
@@ -26937,7 +26962,7 @@ async function reconcileGeneration(pageState, process2, request) {
26937
26962
  namespace: plan.namespace,
26938
26963
  sessionName: name,
26939
26964
  owned: session.ownedManagedSession
26940
- });
26965
+ }, request.generationInspection);
26941
26966
  pageState.bindSnapshotGeneration(key, daemon.status === "active" ? daemon.generation : void 0);
26942
26967
  const generationKnown = daemon.status === "active" && daemon.generation !== void 0;
26943
26968
  if (generationKnown && snapshot.generation === daemon.generation) {
@@ -26970,6 +26995,7 @@ async function preparePageState(state, process2, request) {
26970
26995
  plan,
26971
26996
  session,
26972
26997
  update,
26998
+ generationInspection: request.generationInspection,
26973
26999
  page: {
26974
27000
  sessionStateKey: key,
26975
27001
  priorSessionTabTarget: prior.tabTarget,
@@ -27518,30 +27544,30 @@ var init_prompt_guards = __esm({
27518
27544
  });
27519
27545
 
27520
27546
  // dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-guards.js
27521
- function prepareGuardEvidence(preserveAttachedBrowserSession, context) {
27522
- const plan = context.semantic.selection.executionPlan;
27547
+ function prepareGuardEvidence(preserveAttachedBrowserSession, context2) {
27548
+ const plan = context2.semantic.selection.executionPlan;
27523
27549
  return {
27524
- redactedEffectiveArgs: redactInvocationArgs(prepareAgentBrowserSpawnArgs(plan.effectiveArgs, void 0, preserveAttachedBrowserSession, context.chromeStartupArgs)),
27550
+ redactedEffectiveArgs: redactInvocationArgs(prepareAgentBrowserSpawnArgs(plan.effectiveArgs, void 0, preserveAttachedBrowserSession, context2.chromeStartupArgs)),
27525
27551
  redactedRecoveryHint: redactRecoveryHint(plan.recoveryHint),
27526
- statePatch: plan.managedSessionName === context.freshSessionName ? { freshSessionOrdinal: context.freshSessionOrdinal + 1 } : {},
27552
+ statePatch: plan.managedSessionName === context2.freshSessionName ? { freshSessionOrdinal: context2.freshSessionOrdinal + 1 } : {},
27527
27553
  exactSensitiveValues: getExactSensitiveStdinValues({
27528
27554
  command: plan.commandInfo.command,
27529
- commandTokens: context.semantic.commandTokens,
27530
- stdin: context.stdin
27555
+ commandTokens: context2.semantic.commandTokens,
27556
+ stdin: context2.stdin
27531
27557
  })
27532
27558
  };
27533
27559
  }
27534
- function guardRequest(context, evidence) {
27560
+ function guardRequest(context2, evidence) {
27535
27561
  return {
27536
- plan: context.semantic.selection.executionPlan,
27537
- redactedArgs: context.input.redactedArgs,
27562
+ plan: context2.semantic.selection.executionPlan,
27563
+ redactedArgs: context2.input.redactedArgs,
27538
27564
  effectiveArgs: evidence.redactedEffectiveArgs,
27539
- sessionMode: context.sessionMode,
27565
+ sessionMode: context2.sessionMode,
27540
27566
  statePatch: evidence.statePatch
27541
27567
  };
27542
27568
  }
27543
- function planRecoveryActions(context, tabError) {
27544
- const { selection, scrollRecovery } = context.semantic;
27569
+ function planRecoveryActions(context2, tabError) {
27570
+ const { selection, scrollRecovery } = context2.semantic;
27545
27571
  const plan = selection.executionPlan;
27546
27572
  return applyNamespaceToNextActions(tabError ? buildSessionTabRecoveryNextActions({
27547
27573
  kind: "tab-drift",
@@ -27551,17 +27577,17 @@ function planRecoveryActions(context, tabError) {
27551
27577
  target: selection.page.priorSessionTabTarget
27552
27578
  }) : scrollRecovery?.nextActions, plan.namespace);
27553
27579
  }
27554
- function planFailure(restoreDisabled, context, evidence, cleanup) {
27555
- const { selection } = context.semantic;
27580
+ function planFailure(restoreDisabled, context2, evidence, cleanup) {
27581
+ const { selection } = context2.semantic;
27556
27582
  const { executionPlan: plan, page } = selection;
27557
27583
  const error = plan.validationError;
27558
27584
  if (error === void 0 || error === "") {
27559
27585
  return void 0;
27560
27586
  }
27561
27587
  const tabError = selection.sessionTabSelectionError !== void 0 && selection.sessionTabSelectionError !== "";
27562
- const nextActions = planRecoveryActions(context, tabError);
27588
+ const nextActions = planRecoveryActions(context2, tabError);
27563
27589
  const nextActionsText = formatAgentBrowserNextActionsText(nextActions);
27564
- const input = context.input;
27590
+ const input = context2.input;
27565
27591
  return preparationFailure({
27566
27592
  message: [error, nextActionsText].filter((text3) => text3 !== void 0).join("\n\n"),
27567
27593
  statePatch: evidence.statePatch,
@@ -27577,7 +27603,7 @@ function planFailure(restoreDisabled, context, evidence, cleanup) {
27577
27603
  ...preparationSessionDetails(restoreDisabled, plan),
27578
27604
  ...cleanup.reason !== void 0 ? { namespace: cleanup.namespace ?? "" } : {},
27579
27605
  nextActions,
27580
- sessionMode: context.sessionMode,
27606
+ sessionMode: context2.sessionMode,
27581
27607
  sessionRecoveryHint: evidence.redactedRecoveryHint,
27582
27608
  startupScopedFlags: plan.startupScopedFlags,
27583
27609
  ...tabError ? {
@@ -27597,41 +27623,41 @@ function planFailure(restoreDisabled, context, evidence, cleanup) {
27597
27623
  }
27598
27624
  });
27599
27625
  }
27600
- function synchronousGuards(traceOwners, restoreDisabled, context, evidence) {
27601
- const plan = context.semantic.selection.executionPlan;
27626
+ function synchronousGuards(traceOwners, restoreDisabled, context2, evidence) {
27627
+ const plan = context2.semantic.selection.executionPlan;
27602
27628
  const traceError = getTraceOwnerGuardMessage({
27603
27629
  command: plan.commandInfo.command,
27604
- sessionName: context.semantic.selection.page.sessionStateKey,
27630
+ sessionName: context2.semantic.selection.page.sessionStateKey,
27605
27631
  subcommand: plan.commandInfo.subcommand,
27606
27632
  traceOwners
27607
27633
  });
27608
27634
  const error = traceError !== void 0 && traceError !== "" ? traceError : validateStdinCommandContract({
27609
27635
  command: plan.commandInfo.command,
27610
- commandTokens: context.semantic.commandTokens,
27611
- stdin: context.stdin
27636
+ commandTokens: context2.semantic.commandTokens,
27637
+ stdin: context2.stdin
27612
27638
  });
27613
- return error !== void 0 && error !== "" ? categorizedGuardFailure(restoreDisabled, guardRequest(context, evidence), {
27639
+ return error !== void 0 && error !== "" ? categorizedGuardFailure(restoreDisabled, guardRequest(context2, evidence), {
27614
27640
  message: error,
27615
27641
  validationError: error
27616
27642
  }) : void 0;
27617
27643
  }
27618
- async function artifactCloseGuard(artifactManifest, facts, context, evidence) {
27644
+ async function artifactCloseGuard(artifactManifest, facts, context2, evidence) {
27619
27645
  const violation = await findRequestedArtifactCloseViolation({
27620
27646
  artifactManifest,
27621
- command: context.semantic.selection.executionPlan.commandInfo.command,
27647
+ command: context2.semantic.selection.executionPlan.commandInfo.command,
27622
27648
  cwd: facts.cwd,
27623
27649
  promptPolicy: facts.promptPolicy
27624
27650
  });
27625
- return violation ? categorizedGuardFailure(facts.isRestoreDisabled(), guardRequest(context, evidence), {
27651
+ return violation ? categorizedGuardFailure(facts.isRestoreDisabled(), guardRequest(context2, evidence), {
27626
27652
  message: violation.message,
27627
27653
  validationError: violation.message,
27628
27654
  failureCategory: "policy-blocked",
27629
27655
  details: { promptGuard: violation }
27630
27656
  }) : void 0;
27631
27657
  }
27632
- function staleRefFailure(restoreDisabled, context, evidence, request) {
27633
- const plan = context.semantic.selection.executionPlan;
27634
- return categorizedGuardFailure(restoreDisabled, guardRequest(context, evidence), {
27658
+ function staleRefFailure(restoreDisabled, context2, evidence, request) {
27659
+ const plan = context2.semantic.selection.executionPlan;
27660
+ return categorizedGuardFailure(restoreDisabled, guardRequest(context2, evidence), {
27635
27661
  message: request.stale.message,
27636
27662
  failureCategory: "stale-ref",
27637
27663
  details: {
@@ -27642,8 +27668,8 @@ function staleRefFailure(restoreDisabled, context, evidence, request) {
27642
27668
  }
27643
27669
  });
27644
27670
  }
27645
- async function refGuards(owners, facts, context, evidence) {
27646
- const { commandTokens, resolvedSnapshot, selection } = context.semantic;
27671
+ async function refGuards(owners, facts, context2, evidence) {
27672
+ const { commandTokens, resolvedSnapshot, selection } = context2.semantic;
27647
27673
  const { page, executionPlan: plan } = selection;
27648
27674
  const stale = buildStaleRefPreflight({
27649
27675
  commandTokens,
@@ -27651,10 +27677,10 @@ async function refGuards(owners, facts, context, evidence) {
27651
27677
  requireExactTargetUrl: page.reuseConfirmedCapture,
27652
27678
  refSnapshot: resolvedSnapshot ?? page.priorRefSnapshotState,
27653
27679
  refSnapshotInvalidation: resolvedSnapshot ? void 0 : page.priorRefSnapshotInvalidation,
27654
- stdin: context.stdin
27680
+ stdin: context2.stdin
27655
27681
  });
27656
27682
  if (stale) {
27657
- return staleRefFailure(facts.isRestoreDisabled(), context, evidence, {
27683
+ return staleRefFailure(facts.isRestoreDisabled(), context2, evidence, {
27658
27684
  stale,
27659
27685
  includeInvalidation: true
27660
27686
  });
@@ -27664,7 +27690,7 @@ async function refGuards(owners, facts, context, evidence) {
27664
27690
  cwd: facts.cwd,
27665
27691
  currentTarget: page.priorSessionTabTarget,
27666
27692
  previousSnapshot: resolvedSnapshot || page.reuseConfirmedCapture ? void 0 : page.priorRefSnapshotState,
27667
- stdin: context.stdin,
27693
+ stdin: context2.stdin,
27668
27694
  namespace: plan.namespace,
27669
27695
  sessionName: plan.sessionName,
27670
27696
  signal: facts.signal
@@ -27680,53 +27706,53 @@ async function refGuards(owners, facts, context, evidence) {
27680
27706
  update: owners.update
27681
27707
  });
27682
27708
  }
27683
- return staleRefFailure(facts.isRestoreDisabled(), context, evidence, {
27709
+ return staleRefFailure(facts.isRestoreDisabled(), context2, evidence, {
27684
27710
  stale: freshness,
27685
27711
  includeInvalidation: false
27686
27712
  });
27687
27713
  }
27688
- async function qaAttachedGuard(facts, context, evidence) {
27689
- if (context.input.compiledQaPreset?.checks.attached !== true) {
27714
+ async function qaAttachedGuard(facts, context2, evidence) {
27715
+ if (context2.input.compiledQaPreset?.checks.attached !== true) {
27690
27716
  return void 0;
27691
27717
  }
27692
- const plan = context.semantic.selection.executionPlan;
27718
+ const plan = context2.semantic.selection.executionPlan;
27693
27719
  const failure = await validateQaAttachedPrecondition({
27694
27720
  cwd: facts.cwd,
27695
27721
  namespace: plan.namespace,
27696
27722
  sessionName: plan.sessionName,
27697
27723
  signal: facts.signal
27698
27724
  });
27699
- return failure ? categorizedGuardFailure(facts.isRestoreDisabled(), guardRequest(context, evidence), {
27725
+ return failure ? categorizedGuardFailure(facts.isRestoreDisabled(), guardRequest(context2, evidence), {
27700
27726
  omitCommand: true,
27701
27727
  message: failure.error,
27702
27728
  validationError: failure.error,
27703
27729
  details: {
27704
- compiledQaPreset: context.input.redactedCompiledQaPreset,
27730
+ compiledQaPreset: context2.input.redactedCompiledQaPreset,
27705
27731
  nextActions: applyNamespaceToNextActions(failure.nextActions, plan.namespace)
27706
27732
  }
27707
27733
  }) : void 0;
27708
27734
  }
27709
- async function validatePreparationGuards(owners, facts, context, evidence) {
27710
- const invalidPlan = planFailure(facts.isRestoreDisabled(), context, evidence, {
27711
- reason: context.policy.cleanupOnlyReason,
27712
- namespace: context.session.ownedManagedSession?.namespace
27735
+ async function validatePreparationGuards(owners, facts, context2, evidence) {
27736
+ const invalidPlan = planFailure(facts.isRestoreDisabled(), context2, evidence, {
27737
+ reason: context2.policy.cleanupOnlyReason,
27738
+ namespace: context2.session.ownedManagedSession?.namespace
27713
27739
  });
27714
27740
  if (invalidPlan) {
27715
27741
  return invalidPlan;
27716
27742
  }
27717
- const synchronous = synchronousGuards(owners.traceOwners, facts.isRestoreDisabled(), context, evidence);
27743
+ const synchronous = synchronousGuards(owners.traceOwners, facts.isRestoreDisabled(), context2, evidence);
27718
27744
  if (synchronous) {
27719
27745
  return synchronous;
27720
27746
  }
27721
- const artifact = await artifactCloseGuard(owners.artifactManifest, facts, context, evidence);
27747
+ const artifact = await artifactCloseGuard(owners.artifactManifest, facts, context2, evidence);
27722
27748
  if (artifact) {
27723
27749
  return artifact;
27724
27750
  }
27725
- const refs = await refGuards(owners, facts, context, evidence);
27751
+ const refs = await refGuards(owners, facts, context2, evidence);
27726
27752
  if (refs) {
27727
27753
  return refs;
27728
27754
  }
27729
- return qaAttachedGuard(facts, context, evidence);
27755
+ return qaAttachedGuard(facts, context2, evidence);
27730
27756
  }
27731
27757
  var init_prepare_guards = __esm({
27732
27758
  "dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-guards.js"() {
@@ -27861,14 +27887,14 @@ function formatRenderedTextSearchMatches(result) {
27861
27887
  return void 0;
27862
27888
  }
27863
27889
  const lines = result.matches.map((match) => {
27864
- const context = [
27890
+ const context2 = [
27865
27891
  match.kind === "validation" ? "validation" : void 0,
27866
27892
  match.offscreen ? "outside viewport" : void 0,
27867
27893
  match.role,
27868
27894
  match.tagName,
27869
27895
  match.ref !== void 0 && match.ref !== "" ? `@${match.ref}` : void 0
27870
27896
  ].filter(Boolean).join(", ");
27871
- return `- ${JSON.stringify(match.text)}${context !== "" ? ` (${context})` : ""}`;
27897
+ return `- ${JSON.stringify(match.text)}${context2 !== "" ? ` (${context2})` : ""}`;
27872
27898
  });
27873
27899
  if (result.truncated) {
27874
27900
  lines.push(`- ... (${result.totalMatches - result.matches.length} additional rendered-text matches omitted)`);
@@ -28611,24 +28637,24 @@ var init_scroll_shims = __esm({
28611
28637
  });
28612
28638
 
28613
28639
  // dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-observations.js
28614
- function observationRequest(process2, restoreDisabled, context, evidence) {
28615
- const plan = context.semantic.selection.executionPlan;
28640
+ function observationRequest(process2, restoreDisabled, context2, evidence) {
28641
+ const plan = context2.semantic.selection.executionPlan;
28616
28642
  return {
28617
- commandTokens: [...context.semantic.commandTokens],
28643
+ commandTokens: [...context2.semantic.commandTokens],
28618
28644
  compatibilityWorkaround: plan.compatibilityWorkaround,
28619
28645
  cwd: process2.cwd,
28620
28646
  effectiveArgs: [...evidence.redactedEffectiveArgs],
28621
28647
  managedSessionRestoreDisabled: restoreDisabled,
28622
- redactedArgs: context.input.redactedArgs,
28623
- sessionMode: context.sessionMode,
28648
+ redactedArgs: context2.input.redactedArgs,
28649
+ sessionMode: context2.sessionMode,
28624
28650
  namespace: plan.namespace,
28625
28651
  sessionName: plan.sessionName,
28626
28652
  signal: process2.signal,
28627
28653
  usedImplicitSession: plan.usedImplicitSession
28628
28654
  };
28629
28655
  }
28630
- async function bindFilteredSnapshotGeneration(owners, process2, context) {
28631
- const { page, executionPlan: plan } = context.semantic.selection;
28656
+ async function bindFilteredSnapshotGeneration(owners, process2, context2) {
28657
+ const { page, executionPlan: plan } = context2.semantic.selection;
28632
28658
  const key = page.sessionStateKey;
28633
28659
  if (key === void 0 || key === "" || plan.sessionName === void 0 || plan.sessionName === "") {
28634
28660
  return;
@@ -28636,18 +28662,18 @@ async function bindFilteredSnapshotGeneration(owners, process2, context) {
28636
28662
  const daemon = await inspectPreparationGeneration(process2, {
28637
28663
  namespace: plan.namespace,
28638
28664
  sessionName: plan.sessionName,
28639
- owned: context.session.ownedManagedSession
28665
+ owned: context2.session.ownedManagedSession
28640
28666
  });
28641
28667
  owners.pageState.bindSnapshotGeneration(key, daemon.status === "active" ? daemon.generation : void 0);
28642
- if (context.session.ownedManagedSession && daemon.status === "active" && daemon.generation !== void 0 && daemon.generation !== "") {
28668
+ if (context2.session.ownedManagedSession && daemon.status === "active" && daemon.generation !== void 0 && daemon.generation !== "") {
28643
28669
  owners.restoreState.recordDaemonRestoreKey(plan.sessionName, plan.namespace, daemon.restoreKey, daemon.generation);
28644
28670
  }
28645
28671
  return { refSnapshot: owners.pageState.get(key).refSnapshot };
28646
28672
  }
28647
- async function filteredSnapshot(owners, process2, context, evidence) {
28648
- const { page } = context.semantic.selection;
28673
+ async function filteredSnapshot(owners, process2, context2, evidence) {
28674
+ const { page } = context2.semantic.selection;
28649
28675
  const result = await trySnapshotFilter({
28650
- ...observationRequest(process2, () => owners.restoreState.isDisabled(context.semantic.selection.executionPlan.sessionName, context.semantic.selection.executionPlan.namespace), context, evidence),
28676
+ ...observationRequest(process2, () => owners.restoreState.isDisabled(context2.semantic.selection.executionPlan.sessionName, context2.semantic.selection.executionPlan.namespace), context2, evidence),
28651
28677
  modelVisible: process2.modelVisible,
28652
28678
  artifactManifest: owners.artifactManifest,
28653
28679
  persistentArtifactStore: owners.artifactStore,
@@ -28659,7 +28685,7 @@ async function filteredSnapshot(owners, process2, context, evidence) {
28659
28685
  if (!result) {
28660
28686
  return void 0;
28661
28687
  }
28662
- const generation = await bindFilteredSnapshotGeneration(owners, process2, context);
28688
+ const generation = await bindFilteredSnapshotGeneration(owners, process2, context2);
28663
28689
  const toolResult = generation && isRecord(result.result.details) ? { ...result.result, details: { ...result.result.details, ...generation } } : result.result;
28664
28690
  return {
28665
28691
  kind: "early-result",
@@ -28670,17 +28696,17 @@ async function filteredSnapshot(owners, process2, context, evidence) {
28670
28696
  result: toolResult
28671
28697
  };
28672
28698
  }
28673
- async function prepareObservations(owners, process2, context, evidence) {
28674
- const snapshot = await filteredSnapshot(owners, process2, context, evidence);
28699
+ async function prepareObservations(owners, process2, context2, evidence) {
28700
+ const snapshot = await filteredSnapshot(owners, process2, context2, evidence);
28675
28701
  if (snapshot) {
28676
28702
  return snapshot;
28677
28703
  }
28678
- const request = observationRequest(process2, () => owners.restoreState.isDisabled(context.semantic.selection.executionPlan.sessionName, context.semantic.selection.executionPlan.namespace), context, evidence);
28704
+ const request = observationRequest(process2, () => owners.restoreState.isDisabled(context2.semantic.selection.executionPlan.sessionName, context2.semantic.selection.executionPlan.namespace), context2, evidence);
28679
28705
  const network = await tryNetworkRequestsPageFilter(request);
28680
28706
  if (network) {
28681
28707
  return { kind: "early-result", statePatch: evidence.statePatch, result: network };
28682
28708
  }
28683
- if (context.semantic.selection.executionPlan.startupScopedFlags.length !== 0) {
28709
+ if (context2.semantic.selection.executionPlan.startupScopedFlags.length !== 0) {
28684
28710
  return void 0;
28685
28711
  }
28686
28712
  const container = await tryContainerScroll(request);
@@ -28768,30 +28794,30 @@ var init_prepare_timeouts = __esm({
28768
28794
  });
28769
28795
 
28770
28796
  // dist/extensions/agent-browser/lib/orchestration/browser-run/prepare-command.js
28771
- function shouldProbeScrollNoop(managedSessionActive, context) {
28772
- const plan = context.semantic.selection.executionPlan;
28773
- const amount = Number(context.semantic.commandTokens.find((token) => /^\d+(?:\.\d+)?$/.test(token)));
28774
- return plan.commandInfo.command === "scroll" && plan.startupScopedFlags.length === 0 && (managedSessionActive || context.sessionMode === "fresh") && (!Number.isFinite(amount) || amount >= 500);
28775
- }
28776
- function redactedSemanticAction(context) {
28777
- const compiled = context.input.redactedCompiledSemanticAction;
28778
- return context.semantic.resolution && compiled?.action === "select" ? { ...compiled, args: redactInvocationArgs(context.semantic.resolution.args) } : compiled;
28779
- }
28780
- async function nativeCommandEvidence(facts, context) {
28781
- const plan = context.semantic.selection.executionPlan;
28782
- const page = context.semantic.selection.page;
28783
- const promptSnapshot = context.semantic.resolvedSnapshot ?? page.priorRefSnapshotState;
28784
- const processStdin = context.preparedArgs.stdin ?? context.stdin;
28797
+ function shouldProbeScrollNoop(managedSessionActive, context2) {
28798
+ const plan = context2.semantic.selection.executionPlan;
28799
+ const amount = Number(context2.semantic.commandTokens.find((token) => /^\d+(?:\.\d+)?$/.test(token)));
28800
+ return plan.commandInfo.command === "scroll" && plan.startupScopedFlags.length === 0 && (managedSessionActive || context2.sessionMode === "fresh") && (!Number.isFinite(amount) || amount >= 500);
28801
+ }
28802
+ function redactedSemanticAction(context2) {
28803
+ const compiled = context2.input.redactedCompiledSemanticAction;
28804
+ return context2.semantic.resolution && compiled?.action === "select" ? { ...compiled, args: redactInvocationArgs(context2.semantic.resolution.args) } : compiled;
28805
+ }
28806
+ async function nativeCommandEvidence(facts, context2) {
28807
+ const plan = context2.semantic.selection.executionPlan;
28808
+ const page = context2.semantic.selection.page;
28809
+ const promptSnapshot = context2.semantic.resolvedSnapshot ?? page.priorRefSnapshotState;
28810
+ const processStdin = context2.preparedArgs.stdin ?? context2.stdin;
28785
28811
  const processTimeoutMs = await prepareProcessTimeout(facts, {
28786
- commandTokens: context.semantic.commandTokens,
28812
+ commandTokens: context2.semantic.commandTokens,
28787
28813
  namespace: plan.namespace,
28788
28814
  sessionName: plan.sessionName,
28789
28815
  stdin: processStdin,
28790
28816
  pageUrl: page.priorSessionTabTarget?.url,
28791
28817
  refSnapshot: promptSnapshot
28792
28818
  });
28793
- const clickDispatchProbe = context.input.compiledElectron === void 0 ? await prepareClickDispatchProbe({
28794
- commandTokens: [...context.semantic.commandTokens],
28819
+ const clickDispatchProbe = context2.input.compiledElectron === void 0 ? await prepareClickDispatchProbe({
28820
+ commandTokens: [...context2.semantic.commandTokens],
28795
28821
  cwd: facts.cwd,
28796
28822
  namespace: plan.namespace,
28797
28823
  refSnapshot: promptSnapshot,
@@ -28799,8 +28825,8 @@ async function nativeCommandEvidence(facts, context) {
28799
28825
  signal: facts.signal,
28800
28826
  timeoutMs: processTimeoutMs
28801
28827
  }) : void 0;
28802
- const redactedProcessArgs = redactInvocationArgs(prepareAgentBrowserSpawnArgs(plan.effectiveArgs, context.session.ownedManagedSession?.compatibilityUserAgent, facts.preserveAttachedBrowserSession, context.chromeStartupArgs));
28803
- const probeScroll = shouldProbeScrollNoop(facts.managedSessionActive, context);
28828
+ const redactedProcessArgs = redactInvocationArgs(prepareAgentBrowserSpawnArgs(plan.effectiveArgs, context2.session.ownedManagedSession?.compatibilityUserAgent, facts.preserveAttachedBrowserSession, context2.chromeStartupArgs));
28829
+ const probeScroll = shouldProbeScrollNoop(facts.managedSessionActive, context2);
28804
28830
  const scrollPositionBefore = probeScroll ? await collectScrollPositionSnapshot({
28805
28831
  cwd: facts.cwd,
28806
28832
  namespace: plan.namespace,
@@ -28817,8 +28843,8 @@ async function nativeCommandEvidence(facts, context) {
28817
28843
  details: {
28818
28844
  compatibilityWorkaround: plan.compatibilityWorkaround,
28819
28845
  effectiveArgs: redactedProcessArgs,
28820
- sessionMode: context.sessionMode,
28821
- sessionTabCorrection: context.semantic.selection.sessionTabCorrection,
28846
+ sessionMode: context2.sessionMode,
28847
+ sessionTabCorrection: context2.semantic.selection.sessionTabCorrection,
28822
28848
  ...preparationSessionDetails(facts.isRestoreDisabled(), plan)
28823
28849
  }
28824
28850
  });
@@ -28832,11 +28858,11 @@ async function nativeCommandEvidence(facts, context) {
28832
28858
  scrollPositionBefore
28833
28859
  };
28834
28860
  }
28835
- async function prepareNativeCommand(facts, context, evidence) {
28836
- const native = await nativeCommandEvidence(facts, context);
28837
- const plan = context.semantic.selection.executionPlan;
28838
- const page = context.semantic.selection.page;
28839
- const input = context.input;
28861
+ async function prepareNativeCommand(facts, context2, evidence) {
28862
+ const native = await nativeCommandEvidence(facts, context2);
28863
+ const plan = context2.semantic.selection.executionPlan;
28864
+ const page = context2.semantic.selection.page;
28865
+ const input = context2.input;
28840
28866
  return {
28841
28867
  kind: "ready",
28842
28868
  prepared: {
@@ -28853,32 +28879,32 @@ async function prepareNativeCommand(facts, context, evidence) {
28853
28879
  redactedCompiledQaPreset: input.redactedCompiledQaPreset,
28854
28880
  redactedCompiledSourceLookup: input.redactedCompiledSourceLookup,
28855
28881
  ...native,
28856
- chromeStartupArgs: context.chromeStartupArgs,
28857
- commandTokens: [...context.semantic.commandTokens],
28858
- headedLaunch: context.session.headedLaunch,
28859
- providerLaunch: context.session.providerLaunch,
28860
- managedSessionPolicyLock: context.policy.lock,
28882
+ chromeStartupArgs: context2.chromeStartupArgs,
28883
+ commandTokens: [...context2.semantic.commandTokens],
28884
+ headedLaunch: context2.session.headedLaunch,
28885
+ providerLaunch: context2.session.providerLaunch,
28886
+ managedSessionPolicyLock: context2.policy.lock,
28861
28887
  compatibilityWorkaround: plan.compatibilityWorkaround,
28862
- electronLaunch: context.electronLaunch,
28888
+ electronLaunch: context2.electronLaunch,
28863
28889
  exactSensitiveValues: [...evidence.exactSensitiveValues],
28864
28890
  executionPlan: plan,
28865
- ownedManagedSessionContext: context.session.ownedManagedSession,
28866
- preparedArgs: context.preparedArgs,
28867
- readConfirmation: context.session.readConfirmation,
28891
+ ownedManagedSessionContext: context2.session.ownedManagedSession,
28892
+ preparedArgs: context2.preparedArgs,
28893
+ readConfirmation: context2.session.readConfirmation,
28868
28894
  priorRefSnapshotState: page.priorRefSnapshotState,
28869
28895
  priorSessionTabTarget: page.priorSessionTabTarget,
28870
28896
  priorSessionTabTargetUnknown: page.priorSessionTabTargetUnknown,
28871
- redactedCompiledSemanticAction: redactedSemanticAction(context),
28897
+ redactedCompiledSemanticAction: redactedSemanticAction(context2),
28872
28898
  redactedEffectiveArgs: [...evidence.redactedEffectiveArgs],
28873
28899
  redactedRecoveryHint: evidence.redactedRecoveryHint,
28874
- resolvedSemanticActionRefSnapshot: context.semantic.resolvedSnapshot,
28875
- runtimeToolArgs: [...context.runtimeToolArgs],
28876
- runtimeToolStdin: context.stdin,
28877
- sessionMode: context.sessionMode,
28878
- sessionTabCorrection: context.semantic.selection.sessionTabCorrection,
28900
+ resolvedSemanticActionRefSnapshot: context2.semantic.resolvedSnapshot,
28901
+ runtimeToolArgs: [...context2.runtimeToolArgs],
28902
+ runtimeToolStdin: context2.stdin,
28903
+ sessionMode: context2.sessionMode,
28904
+ sessionTabCorrection: context2.semantic.selection.sessionTabCorrection,
28879
28905
  sessionTabPinningReason: page.sessionTabPinningReason,
28880
28906
  statePatch: evidence.statePatch,
28881
- userRequestedJson: getBooleanFlagValue(context.runtimeToolArgs, "--json") === true
28907
+ userRequestedJson: getBooleanFlagValue(context2.runtimeToolArgs, "--json") === true
28882
28908
  }
28883
28909
  };
28884
28910
  }
@@ -28930,39 +28956,41 @@ function rawPageFailure(input) {
28930
28956
  }
28931
28957
  });
28932
28958
  }
28933
- async function prepareCommandPhases(state, controls, context) {
28934
- const plan = context.semantic.selection.executionPlan;
28959
+ async function prepareCommandPhases(state, controls, context2) {
28960
+ const plan = context2.semantic.selection.executionPlan;
28935
28961
  const isRestoreDisabled = () => state.managedSessionRestoreState.isDisabled(plan.sessionName, plan.namespace);
28936
- const evidence = prepareGuardEvidence(controls.preserveAttachedBrowserSession, context);
28962
+ const evidence = prepareGuardEvidence(controls.preserveAttachedBrowserSession, context2);
28937
28963
  const guarded = await validatePreparationGuards({
28938
28964
  pageState: state.sessionPageState,
28939
- update: context.update,
28965
+ update: context2.update,
28940
28966
  traceOwners: state.traceOwners,
28941
28967
  artifactManifest: state.artifactManifest
28942
- }, { ...controls, isRestoreDisabled }, context, evidence);
28968
+ }, { ...controls, isRestoreDisabled }, context2, evidence);
28943
28969
  if (guarded) {
28944
28970
  return guarded;
28945
28971
  }
28946
28972
  const observation2 = await prepareObservations({
28947
28973
  pageState: state.sessionPageState,
28948
28974
  restoreState: state.managedSessionRestoreState,
28949
- update: context.update,
28975
+ update: context2.update,
28950
28976
  artifactManifest: state.artifactManifest,
28951
28977
  artifactStore: controls.artifactStore
28952
- }, controls, context, evidence);
28978
+ }, controls, context2, evidence);
28953
28979
  if (observation2) {
28954
28980
  return observation2;
28955
28981
  }
28956
- return prepareNativeCommand({ ...controls, managedSessionActive: state.managedSessionActive, isRestoreDisabled }, context, evidence);
28982
+ return prepareNativeCommand({ ...controls, managedSessionActive: state.managedSessionActive, isRestoreDisabled }, context2, evidence);
28957
28983
  }
28958
28984
  async function preparePagePhases(state, controls, planning, request) {
28959
28985
  const { plan, session, policy } = planning;
28986
+ const initial = controls.initialDaemonObservation;
28960
28987
  const page = await preparePageState(state, controls, {
28961
28988
  plan,
28962
28989
  session,
28963
28990
  inactive: policy.inactive,
28964
28991
  update: request.update,
28965
- preserveAttachedBrowserSession: controls.preserveAttachedBrowserSession
28992
+ preserveAttachedBrowserSession: controls.preserveAttachedBrowserSession,
28993
+ generationInspection: policy.generationInspection ?? (!session.ownedManagedSession && initial?.generationInspected === true && initial.identity === getAgentBrowserSessionIdentityKey(plan.sessionName ?? "", plan.namespace) ? initial.daemon : void 0)
28966
28994
  });
28967
28995
  const selection = await preparePageSelection(state.sessionPageState, controls, session.readConfirmation !== void 0, {
28968
28996
  ...request,
@@ -29019,7 +29047,8 @@ function preparationControls(options) {
29019
29047
  promptPolicy: options.promptPolicy,
29020
29048
  preserveAttachedBrowserSession: options.preserveAttachedBrowserSession,
29021
29049
  establishAttachedBrowserSession: options.establishAttachedBrowserSession,
29022
- artifactStore: getPersistentSessionArtifactStore(options.ctx)
29050
+ artifactStore: getPersistentSessionArtifactStore(options.ctx),
29051
+ initialDaemonObservation: options.initialDaemonObservation
29023
29052
  };
29024
29053
  }
29025
29054
  function preparationSessionFacts(state) {
@@ -29067,8 +29096,7 @@ async function prepareBrowserRun(options) {
29067
29096
  const chromeStartupArgs = await prepareChromeStartupArgs({
29068
29097
  ...controls,
29069
29098
  chromeStartupArgs: options.input.chromeStartupArgs,
29070
- configuredChromeLaunch: options.input.configuredChromeLaunch,
29071
- daemonInactive: options.daemonInactive
29099
+ configuredChromeLaunch: options.input.configuredChromeLaunch
29072
29100
  }, planning, { preparedArgs: artifacts.preparedArgs, stdin: request.stdin });
29073
29101
  const result = await withChromeStartupArgs(chromeStartupArgs, () => withOwnedManagedSessionContext(planning.session.ownedManagedSession, () => preparePagePhases(state, controls, planning, {
29074
29102
  ...request,
@@ -29097,6 +29125,7 @@ var init_prepare = __esm({
29097
29125
  init_categories();
29098
29126
  init_process();
29099
29127
  init_managed_session_restore();
29128
+ init_argv_grammar();
29100
29129
  init_session_state();
29101
29130
  init_prepare_input();
29102
29131
  init_prepare_failure();
@@ -32443,9 +32472,6 @@ import { open as open2, stat as stat2 } from "node:fs/promises";
32443
32472
 
32444
32473
  // dist/extensions/agent-browser/lib/browser-journal-projection.js
32445
32474
  init_parsing();
32446
- init_process_errors();
32447
- import { Readable, Writable } from "node:stream";
32448
- import { pipeline } from "node:stream/promises";
32449
32475
  var ENVELOPE_MAX_BYTES = 16 * 1024 * 1024;
32450
32476
  function matches(field, key) {
32451
32477
  return field === key || field === "*" && typeof key === "number";
@@ -32627,30 +32653,27 @@ var JsonProjection = class {
32627
32653
  }
32628
32654
  };
32629
32655
  async function projectJson(input, fields, maxBytes = ENVELOPE_MAX_BYTES) {
32630
- const { parser } = await import("stream-json/parser.js");
32631
- async function* decode() {
32632
- const decoder = new TextDecoder("utf-8", { fatal: true });
32633
- for await (const chunk of input) {
32634
- yield decoder.decode(chunk, { stream: true });
32635
- }
32636
- const tail = decoder.decode();
32637
- if (tail.length > 0) {
32638
- yield tail;
32639
- }
32640
- }
32656
+ const { jsonParser } = await import("stream-json/core/parser.js");
32657
+ const chain = await import("stream-chain/defs.js");
32658
+ const tokenize = jsonParser({ packValues: false, streamValues: true });
32641
32659
  const projection = new JsonProjection(fields, maxBytes);
32642
- const sink = new Writable({
32643
- objectMode: true,
32644
- write(token, _encoding, done) {
32645
- try {
32660
+ const decoder = new TextDecoder("utf-8", { fatal: true });
32661
+ const consume = (text3) => {
32662
+ const tokens = tokenize(text3);
32663
+ if (tokens !== chain.none) {
32664
+ for (const token of chain.getManyValues(tokens)) {
32646
32665
  projection.consume(token);
32647
- done();
32648
- } catch (error) {
32649
- done(normalizeProcessError(error));
32650
32666
  }
32651
32667
  }
32652
- });
32653
- await pipeline(Readable.from(decode()), parser.asStream({ packValues: false, streamValues: true }), sink);
32668
+ };
32669
+ for await (const chunk of input) {
32670
+ consume(decoder.decode(chunk, { stream: true }));
32671
+ }
32672
+ const tail = decoder.decode();
32673
+ if (tail.length > 0) {
32674
+ consume(tail);
32675
+ }
32676
+ consume(chain.none);
32654
32677
  return projection.result();
32655
32678
  }
32656
32679
 
@@ -32743,6 +32766,566 @@ init_parsing();
32743
32766
  init_process_errors();
32744
32767
  import { constants } from "node:fs";
32745
32768
  import { open, stat } from "node:fs/promises";
32769
+
32770
+ // dist/extensions/agent-browser/lib/browser-conversion-branches.js
32771
+ var BrowserConversionBranches = class {
32772
+ states = /* @__PURE__ */ new Map();
32773
+ children = /* @__PURE__ */ new Map();
32774
+ constructor(parentIds) {
32775
+ for (const id of parentIds) {
32776
+ if (typeof id === "string") {
32777
+ this.children.set(id, (this.children.get(id) ?? 0) + 1);
32778
+ }
32779
+ }
32780
+ }
32781
+ get(id) {
32782
+ return this.states.get(id);
32783
+ }
32784
+ advance(id, parentId, projection) {
32785
+ if (typeof parentId === "string") {
32786
+ const remaining = (this.children.get(parentId) ?? 0) - 1;
32787
+ if (remaining > 0) {
32788
+ this.children.set(parentId, remaining);
32789
+ } else {
32790
+ this.children.delete(parentId);
32791
+ this.states.delete(parentId);
32792
+ }
32793
+ }
32794
+ if (this.children.has(id)) {
32795
+ this.states.set(id, projection);
32796
+ }
32797
+ }
32798
+ };
32799
+
32800
+ // dist/extensions/agent-browser/lib/browser-legacy-projection.js
32801
+ init_argv_descriptor();
32802
+ init_argv_grammar();
32803
+ init_batch_lifecycle();
32804
+ init_browser_transcript();
32805
+ init_command_taxonomy();
32806
+ init_parsing();
32807
+ init_artifact_manifest();
32808
+ init_native_confirmation();
32809
+ init_browser_value_parsing();
32810
+ import { randomUUID as randomUUID2 } from "node:crypto";
32811
+
32812
+ // dist/extensions/agent-browser/lib/browser-legacy-pages.js
32813
+ init_browser_transcript();
32814
+ init_browser_value_parsing();
32815
+ init_parsing();
32816
+ init_command_taxonomy();
32817
+ init_session_page_observation();
32818
+ import { createHash } from "node:crypto";
32819
+ function legacyTarget(value) {
32820
+ return normalizeSessionTabTarget({
32821
+ url: typeof value.url === "string" ? value.url : void 0,
32822
+ title: typeof value.title === "string" ? value.title : void 0,
32823
+ targetId: typeof value.targetId === "string" ? value.targetId : void 0
32824
+ });
32825
+ }
32826
+ function legacySnapshot(value, id) {
32827
+ if (!isRecord(value) || !Array.isArray(value.refIds)) {
32828
+ return void 0;
32829
+ }
32830
+ const refIds = browserStringArray(value.refIds).filter((ref) => /^e\d+$/.test(ref));
32831
+ const sourceRefs = isRecord(value.refs) ? value.refs : {};
32832
+ return snapshotDefinition({
32833
+ snapshotId: typeof value.snapshotId === "string" ? value.snapshotId : id,
32834
+ refIds,
32835
+ generation: typeof value.generation === "string" ? value.generation : void 0,
32836
+ refs: Object.fromEntries(refIds.flatMap((refId) => {
32837
+ const ref = sourceRefs[refId];
32838
+ if (!isRecord(ref) || typeof ref.name !== "string" || typeof ref.role !== "string") {
32839
+ return [];
32840
+ }
32841
+ return [
32842
+ [
32843
+ refId,
32844
+ {
32845
+ name: ref.name,
32846
+ role: ref.role,
32847
+ ...typeof ref.isEditable === "boolean" ? { isEditable: ref.isEditable } : {},
32848
+ ...typeof ref.isContentEditable === "boolean" ? { isContentEditable: ref.isContentEditable } : {}
32849
+ }
32850
+ ]
32851
+ ];
32852
+ })),
32853
+ target: isRecord(value.target) ? legacyTarget(value.target) : void 0
32854
+ });
32855
+ }
32856
+ function snapshotDigest(definition) {
32857
+ return createHash("sha256").update(JSON.stringify({
32858
+ refs: definition.refs,
32859
+ target: definition.target,
32860
+ generation: definition.generation
32861
+ })).digest("hex");
32862
+ }
32863
+ function canonicalPage(prior, canonical, page) {
32864
+ const definition = isRecord(canonical.snapshot) ? canonical.snapshot : void 0;
32865
+ const digest = definition !== void 0 && Boolean(definition.refs) ? snapshotDigest(definition) : prior.snapshot?.digest ?? "";
32866
+ let snapshot;
32867
+ if (page.refs.kind === "replace" || page.refs.kind === "reuse") {
32868
+ snapshot = { id: page.refs.snapshotId, digest, usable: true, candidate: false };
32869
+ } else if (prior.snapshot) {
32870
+ snapshot = { ...prior.snapshot, usable: false, candidate: canonical.event.phase === "begin" };
32871
+ }
32872
+ return {
32873
+ target: page.target,
32874
+ unknown: page.unknown,
32875
+ reopenPending: page.reopenPending,
32876
+ snapshot,
32877
+ pending: canonical.event.phase === "begin" ? {
32878
+ operationId: canonical.event.operationId,
32879
+ toolCallId: canonical.event.toolCallId,
32880
+ index: canonical.event.commandIndex
32881
+ } : void 0
32882
+ };
32883
+ }
32884
+ function parseInvalidation2(value, fallbackSummary) {
32885
+ if (!isRecord(value)) {
32886
+ return void 0;
32887
+ }
32888
+ if (value.reason !== "no-active-page" && value.reason !== "page-transition") {
32889
+ throw new Error("Invalid legacy browser ref invalidation.");
32890
+ }
32891
+ if (typeof value.summary === "string") {
32892
+ return { reason: value.reason, summary: value.summary };
32893
+ }
32894
+ if (fallbackSummary) {
32895
+ return {
32896
+ reason: value.reason,
32897
+ summary: "The prior refs were invalidated; take a fresh snapshot."
32898
+ };
32899
+ }
32900
+ throw new Error("Invalid legacy browser ref invalidation summary.");
32901
+ }
32902
+ function observedInvalidation(ctx) {
32903
+ const value = ctx.details.refSnapshotInvalidation;
32904
+ if (isRecord(value) && (value.reason === "no-active-page" || value.reason === "page-transition")) {
32905
+ return parseInvalidation2(value, true);
32906
+ }
32907
+ let error;
32908
+ if (typeof ctx.details.error === "string") {
32909
+ error = ctx.details.error;
32910
+ } else if (typeof ctx.details.summary === "string") {
32911
+ error = ctx.details.summary;
32912
+ }
32913
+ return isNoActivePageSnapshotFailure(ctx.command, error) ? buildNoActivePageRefSnapshotInvalidation() : void 0;
32914
+ }
32915
+ function snapshotReusable(page, details, digest) {
32916
+ 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);
32917
+ }
32918
+ var LegacyPageConversion = class {
32919
+ ctx;
32920
+ page;
32921
+ definition;
32922
+ constructor(ctx, prior) {
32923
+ this.ctx = ctx;
32924
+ this.page = { ...prior };
32925
+ }
32926
+ knownTarget() {
32927
+ const { details, command, subcommand } = this.ctx;
32928
+ if (!isRecord(details.compiledNetworkSourceLookup) && !isReadOnlyDiagnosticSessionTargetCommand(command, subcommand) && isRecord(details.sessionTabTarget)) {
32929
+ this.page.target = legacyTarget(details.sessionTabTarget) ?? this.page.target;
32930
+ } else if (command === "batch" && !isRecord(details.compiledNetworkSourceLookup)) {
32931
+ this.page.target = extractSessionTabTargetFromBatchResults(details.data) ?? this.page.target;
32932
+ }
32933
+ if (this.page.target) {
32934
+ this.page.unknown = void 0;
32935
+ }
32936
+ if (typeof details.sessionTabReopenPending === "boolean") {
32937
+ this.page.reopenPending = details.sessionTabReopenPending;
32938
+ }
32939
+ }
32940
+ knownRefs() {
32941
+ const invalidation = observedInvalidation(this.ctx);
32942
+ const candidate = invalidation ? void 0 : legacySnapshot(this.ctx.details.refSnapshot, `snapshot-${this.ctx.nativeId}`);
32943
+ if (candidate) {
32944
+ const digest = snapshotDigest(candidate);
32945
+ let refs;
32946
+ if (snapshotReusable(this.page, this.ctx.details, digest) && this.page.snapshot) {
32947
+ refs = { kind: "reuse", snapshotId: this.page.snapshot.id };
32948
+ } else {
32949
+ this.definition = candidate;
32950
+ refs = { kind: "replace", snapshotId: candidate.id };
32951
+ }
32952
+ this.page.snapshot = { id: refs.snapshotId, digest, usable: true, candidate: false };
32953
+ return refs;
32954
+ }
32955
+ if (invalidation) {
32956
+ this.disableSnapshot(false);
32957
+ return { kind: "invalidate", invalidation };
32958
+ }
32959
+ return this.page.snapshot?.usable === true ? { kind: "reuse", snapshotId: this.page.snapshot.id } : { kind: "invalidate" };
32960
+ }
32961
+ disableSnapshot(candidate) {
32962
+ if (this.page.snapshot) {
32963
+ this.page.snapshot = { ...this.page.snapshot, usable: false, candidate };
32964
+ }
32965
+ }
32966
+ change(key) {
32967
+ return {
32968
+ ...this.pageChange(key),
32969
+ ...typeof this.ctx.details.sessionConfirmActions === "string" || this.ctx.details.sessionConfirmActions === null ? { confirmActions: this.ctx.details.sessionConfirmActions } : {}
32970
+ };
32971
+ }
32972
+ pageChange(key) {
32973
+ const ctx = this.ctx;
32974
+ if (ctx.begin) {
32975
+ this.page.target = void 0;
32976
+ this.page.unknown = true;
32977
+ this.page.snapshot = ctx.prior.snapshot ? { ...ctx.prior.snapshot, usable: false, candidate: true } : void 0;
32978
+ this.page.pending = {
32979
+ toolCallId: ctx.toolCallId,
32980
+ operationId: ctx.operationId,
32981
+ index: ctx.commandIndex
32982
+ };
32983
+ return { key, refs: { kind: "unknown" }, unknown: true };
32984
+ }
32985
+ if (ctx.details.sessionTabTargetUnknown === true) {
32986
+ this.page.target = void 0;
32987
+ this.page.unknown = true;
32988
+ this.page.pending = void 0;
32989
+ this.disableSnapshot(false);
32990
+ return {
32991
+ key,
32992
+ refs: {
32993
+ kind: "unknown",
32994
+ invalidation: parseInvalidation2(ctx.details.refSnapshotInvalidation, false)
32995
+ },
32996
+ unknown: true
32997
+ };
32998
+ }
32999
+ this.knownTarget();
33000
+ const refs = this.knownRefs();
33001
+ this.page.pending = void 0;
33002
+ return {
33003
+ key,
33004
+ target: this.page.target,
33005
+ unknown: this.page.unknown,
33006
+ reopenPending: this.page.reopenPending,
33007
+ refs
33008
+ };
33009
+ }
33010
+ };
33011
+
33012
+ // dist/extensions/agent-browser/lib/browser-legacy-projection.js
33013
+ var emptyProjection = () => ({ pages: /* @__PURE__ */ new Map(), nextIndex: 0 });
33014
+ function legacyMessage(entry) {
33015
+ if (entry.type === "custom" && entry.customType === BROWSER_TRANSITION_ENTRY && isRecord(entry.data) && isRecord(entry.data.details)) {
33016
+ return entry.data;
33017
+ }
33018
+ const message = entry.type === "message" && isRecord(entry.message) ? entry.message : void 0;
33019
+ return isLegacyToolMessage(message) ? message : void 0;
33020
+ }
33021
+ function isLegacyToolMessage(message) {
33022
+ return message !== void 0 && typeof message.toolName === "string" && BROWSER_RESULT_TOOLS.has(message.toolName) && isRecord(message.details) && message.details.browserEventVersion !== 1;
33023
+ }
33024
+ function applyCanonical(current, parent, canonical) {
33025
+ current.manifest = applyArtifactChanges(parent.manifest, canonical.event.artifacts);
33026
+ for (const page of canonical.event.pages ?? []) {
33027
+ if (page.clear === true) {
33028
+ current.pages.delete(page.key);
33029
+ continue;
33030
+ }
33031
+ current.pages.set(page.key, canonicalPage(current.pages.get(page.key) ?? {}, canonical, page));
33032
+ }
33033
+ }
33034
+ function scriptRecord(entry, nativeId, ownerSessionId) {
33035
+ if (entry.type !== "custom" || entry.customType !== "agent-browser-script-session" || !isRecord(entry.data)) {
33036
+ return void 0;
33037
+ }
33038
+ return {
33039
+ event: {
33040
+ version: 1,
33041
+ phase: "state",
33042
+ operationId: `legacy-${nativeId}`,
33043
+ toolCallId: `legacy-${nativeId}`,
33044
+ commandIndex: 0,
33045
+ isError: entry.data.cleanup !== "closed",
33046
+ state: {
33047
+ scriptLease: { ...entry.data, ownerSessionId: entry.data.ownerSessionId ?? ownerSessionId }
33048
+ }
33049
+ }
33050
+ };
33051
+ }
33052
+ function isLegacyBegin(entry, details) {
33053
+ return entry.type === "custom" && details.sessionTabTargetUnknown === true && details.command === void 0 && details.exitCode === void 0 && details.agentBrowserStarted === void 0;
33054
+ }
33055
+ function legacyIdentity(details) {
33056
+ const sessionName = typeof details.sessionName === "string" ? details.sessionName : void 0;
33057
+ const namespace = typeof details.namespace === "string" ? details.namespace : void 0;
33058
+ const key = sessionName !== void 0 && sessionName.length > 0 ? getAgentBrowserSessionIdentityKey(sessionName, namespace) : void 0;
33059
+ const tokens = extractUpstreamCommandTokens(browserStringArray(details.args));
33060
+ return {
33061
+ key,
33062
+ namespace,
33063
+ tokens,
33064
+ command: typeof details.command === "string" ? details.command : tokens[0],
33065
+ subcommand: typeof details.subcommand === "string" ? details.subcommand : tokens[1]
33066
+ };
33067
+ }
33068
+ function legacyPrior(key, current) {
33069
+ return key === void 0 ? {} : current.pages.get(key) ?? {};
33070
+ }
33071
+ function operationIdentity(options, current) {
33072
+ const prior = legacyPrior(options.key, current);
33073
+ const begin = isLegacyBegin(options.entry, options.details);
33074
+ const pending = prior.pending?.toolCallId === options.toolCallId ? prior.pending : void 0;
33075
+ let phase = "state";
33076
+ if (begin) {
33077
+ phase = "begin";
33078
+ } else if (pending) {
33079
+ phase = "finish";
33080
+ }
33081
+ let commandIndex = pending?.index ?? 0;
33082
+ if (begin) {
33083
+ commandIndex = current.nextIndex;
33084
+ current.nextIndex++;
33085
+ }
33086
+ return {
33087
+ prior,
33088
+ begin,
33089
+ phase,
33090
+ commandIndex,
33091
+ operationId: pending?.operationId ?? `legacy-${options.nativeId}`
33092
+ };
33093
+ }
33094
+ function normalizeLegacyBatchStep(step) {
33095
+ return step.success === true && isSuccessfulNativeConfirmedClose(browserStringArray(step.command), step.data) ? { ...step, command: ["close"] } : step;
33096
+ }
33097
+ function normalizeLegacyDetails(details, isError) {
33098
+ const closed = !isError && isSuccessfulNativeConfirmedClose(extractUpstreamCommandTokens(browserStringArray(details.args)), details.data);
33099
+ const batchSteps = Array.isArray(details.batchSteps) ? details.batchSteps.filter(isRecord).map(normalizeLegacyBatchStep) : void 0;
33100
+ return {
33101
+ ...details,
33102
+ ...closed ? { command: "close", subcommand: void 0 } : {},
33103
+ ...batchSteps !== void 0 ? { batchSteps } : {}
33104
+ };
33105
+ }
33106
+ function context(entry, message, details, current) {
33107
+ const nativeId = typeof entry.id === "string" ? entry.id : randomUUID2();
33108
+ const toolCallId = typeof message.toolCallId === "string" ? message.toolCallId : `legacy-${nativeId}`;
33109
+ const replayDetails = normalizeLegacyDetails(details, message.isError === true);
33110
+ const identity = legacyIdentity(replayDetails);
33111
+ const operation = operationIdentity({ entry, details: replayDetails, key: identity.key, toolCallId, nativeId }, current);
33112
+ return {
33113
+ ...identity,
33114
+ ...operation,
33115
+ nativeId,
33116
+ details: replayDetails,
33117
+ isError: message.isError === true,
33118
+ toolCallId
33119
+ };
33120
+ }
33121
+ function closingLifecycle(ctx) {
33122
+ const close = getSuccessfulBatchCloseLifecycle(ctx.details.batchSteps);
33123
+ const closeAll = ctx.details.closeAllApplied === true || !ctx.isError && isCloseAllCommand(ctx.tokens) || batchHasSuccessfulCloseAll(ctx.details.batchSteps);
33124
+ return {
33125
+ closeAll,
33126
+ lifecycleReset: !ctx.isError && isCloseCommand(ctx.command) || close !== void 0,
33127
+ endsClosed: close?.endsClosed === true
33128
+ };
33129
+ }
33130
+ function closePages(current, ctx) {
33131
+ const closing = closingLifecycle(ctx);
33132
+ const pages = [];
33133
+ if (closing.closeAll) {
33134
+ for (const key of current.pages.keys()) {
33135
+ if (isAgentBrowserSessionIdentityKeyInNamespace(key, ctx.namespace)) {
33136
+ current.pages.delete(key);
33137
+ pages.push({ key, clear: true, refs: { kind: "invalidate" } });
33138
+ }
33139
+ }
33140
+ } else if (ctx.key !== void 0 && closing.lifecycleReset) {
33141
+ current.pages.delete(ctx.key);
33142
+ pages.push({ key: ctx.key, clear: true, refs: { kind: "invalidate" } });
33143
+ }
33144
+ return { ...closing, pages };
33145
+ }
33146
+ function hasPageEffects(ctx) {
33147
+ return ctx.begin || [
33148
+ "sessionTabTargetUnknown",
33149
+ "sessionTabTarget",
33150
+ "sessionTabReopenPending",
33151
+ "sessionConfirmActions",
33152
+ "refSnapshot",
33153
+ "refSnapshotInvalidation"
33154
+ ].some((field) => ctx.details[field] !== void 0) || ctx.command === "batch" && Array.isArray(ctx.details.data);
33155
+ }
33156
+ function stampElectronState(state, ownerSessionId) {
33157
+ if (!isRecord(state.electron)) {
33158
+ return state;
33159
+ }
33160
+ const stamp = (value) => isRecord(value) ? { ...value, ownerSessionId: value.ownerSessionId ?? ownerSessionId } : value;
33161
+ const cleanup = isRecord(state.electron.cleanup) ? state.electron.cleanup : void 0;
33162
+ return {
33163
+ ...state,
33164
+ electron: {
33165
+ ...state.electron,
33166
+ launch: stamp(state.electron.launch),
33167
+ ...cleanup ? {
33168
+ cleanup: {
33169
+ ...cleanup,
33170
+ records: Array.isArray(cleanup.records) ? cleanup.records.map(stamp) : cleanup.records,
33171
+ results: Array.isArray(cleanup.results) ? cleanup.results.map((row) => isRecord(row) ? { ...row, record: stamp(row.record) } : row) : cleanup.results
33172
+ }
33173
+ } : {}
33174
+ }
33175
+ };
33176
+ }
33177
+ function updateManifest(current, parent, details) {
33178
+ if (isSessionArtifactManifest(details.artifactManifest) && (!parent.manifest || details.artifactManifest.updatedAtMs >= parent.manifest.updatedAtMs)) {
33179
+ current.manifest = details.artifactManifest;
33180
+ }
33181
+ const changes = artifactChanges(parent.manifest, current.manifest);
33182
+ if (!changes) {
33183
+ current.manifest = parent.manifest;
33184
+ }
33185
+ return changes;
33186
+ }
33187
+ function convertMessage(ctx, parent, current, ownerSessionId) {
33188
+ const closing = closePages(current, ctx);
33189
+ const pages = closing.pages;
33190
+ let definition;
33191
+ const suppressPage = (closing.closeAll || closing.lifecycleReset) && (isCloseCommand(ctx.command) || closing.endsClosed);
33192
+ if (ctx.key !== void 0 && hasPageEffects(ctx) && !suppressPage) {
33193
+ const conversion = new LegacyPageConversion(ctx, current.pages.get(ctx.key) ?? {});
33194
+ pages.push(conversion.change(ctx.key));
33195
+ current.pages.set(ctx.key, conversion.page);
33196
+ definition = conversion.definition;
33197
+ }
33198
+ const artifacts = updateManifest(current, parent, ctx.details);
33199
+ return {
33200
+ event: {
33201
+ version: 1,
33202
+ phase: ctx.phase,
33203
+ operationId: ctx.operationId,
33204
+ toolCallId: ctx.toolCallId,
33205
+ commandIndex: ctx.commandIndex,
33206
+ isError: ctx.isError,
33207
+ state: stampElectronState(browserStateEffects(ctx.details), ownerSessionId),
33208
+ pages,
33209
+ artifacts
33210
+ },
33211
+ ...definition ? { snapshot: definition } : {}
33212
+ };
33213
+ }
33214
+ function hasCanonicalBrowserEvent(entry) {
33215
+ return isRecord(entry.data) && Object.hasOwn(entry.data, "event") && (entry.type === "message" || entry.customType === BROWSER_TRANSITION_ENTRY);
33216
+ }
33217
+ function convertLegacyBrowserEntry(entry, parent = emptyProjection(), ownerSessionId) {
33218
+ const current = {
33219
+ pages: new Map(parent.pages),
33220
+ manifest: parent.manifest,
33221
+ nextIndex: parent.nextIndex
33222
+ };
33223
+ const canonical = getBrowserRecord(entry);
33224
+ if (canonical) {
33225
+ applyCanonical(current, parent, canonical);
33226
+ return { projection: current };
33227
+ }
33228
+ if (hasCanonicalBrowserEvent(entry)) {
33229
+ throw new Error("Invalid browser event; legacy replay cannot bypass canonical validation.");
33230
+ }
33231
+ const script = scriptRecord(entry, typeof entry.id === "string" ? entry.id : randomUUID2(), ownerSessionId);
33232
+ if (script) {
33233
+ return { record: script, projection: current };
33234
+ }
33235
+ const message = legacyMessage(entry);
33236
+ if (!message || !isRecord(message.details)) {
33237
+ return { projection: parent };
33238
+ }
33239
+ return {
33240
+ record: convertMessage(context(entry, message, message.details, current), parent, current, ownerSessionId),
33241
+ projection: current
33242
+ };
33243
+ }
33244
+ function archiveParent(value, branches, linear) {
33245
+ if (typeof value.parentId === "string") {
33246
+ return branches.get(value.parentId) ?? emptyProjection();
33247
+ }
33248
+ return Object.hasOwn(value, "parentId") ? emptyProjection() : linear;
33249
+ }
33250
+ function convertBrowserEntries(entries, ownerSessionId) {
33251
+ const branches = new BrowserConversionBranches(entries.map((value) => isRecord(value) ? value.parentId : void 0));
33252
+ let linear = emptyProjection();
33253
+ return entries.map((value, index) => {
33254
+ if (!isRecord(value)) {
33255
+ return value;
33256
+ }
33257
+ const entry = {
33258
+ ...value,
33259
+ id: typeof value.id === "string" ? value.id : `archive-${index}`,
33260
+ parentId: value.parentId ?? null
33261
+ };
33262
+ const converted = convertLegacyBrowserEntry(entry, archiveParent(value, branches, linear), ownerSessionId);
33263
+ branches.advance(entry.id, value.parentId, converted.projection);
33264
+ linear = converted.projection;
33265
+ return converted.record ? {
33266
+ ...entry,
33267
+ ...entry.type === "custom" ? { customType: BROWSER_TRANSITION_ENTRY } : {},
33268
+ data: converted.record
33269
+ } : entry;
33270
+ });
33271
+ }
33272
+
33273
+ // dist/extensions/agent-browser/lib/browser-legacy-fields.js
33274
+ init_browser_transcript_contracts();
33275
+ var DETAILS_FIELDS = [
33276
+ ...BROWSER_STATE_FIELDS,
33277
+ "browserEventVersion",
33278
+ "electron",
33279
+ "compiledNetworkSourceLookup",
33280
+ "sessionTabTarget",
33281
+ "sessionTabTargetUnknown",
33282
+ "sessionTabReopenPending",
33283
+ "sessionConfirmActions",
33284
+ "refSnapshot",
33285
+ "refSnapshotInvalidation",
33286
+ "artifactManifest",
33287
+ "error",
33288
+ "summary"
33289
+ ];
33290
+ var CONFIRMED_CLOSE_FIELDS = [
33291
+ ["confirmed"],
33292
+ ["action"],
33293
+ ["result", "success"],
33294
+ ["result", "data", "closed"]
33295
+ ];
33296
+ var LEGACY_BROWSER_FIELDS = [
33297
+ ["data", "event"],
33298
+ ["data", "snapshot"],
33299
+ ["data", "cleanup"],
33300
+ ["data", "sessionName"],
33301
+ ["data", "ownerSessionId"],
33302
+ ["data", "closeCommandArgs"],
33303
+ ["data", "launchAttempted"],
33304
+ ["data", "toolCallId"],
33305
+ ["data", "isError"],
33306
+ ["message", "toolName"],
33307
+ ["message", "toolCallId"],
33308
+ ["message", "isError"],
33309
+ ...["data", "message"].flatMap((root) => DETAILS_FIELDS.map((field) => [root, "details", field])),
33310
+ ...["data", "message"].flatMap((root) => CONFIRMED_CLOSE_FIELDS.flatMap((field) => [
33311
+ [root, "details", "data", ...field],
33312
+ [root, "details", "batchSteps", "*", "data", ...field]
33313
+ ])),
33314
+ ...["data", "message"].flatMap((root) => ["command", "success", "lifecycle"].map((field) => [root, "details", "batchSteps", "*", field]).concat([
33315
+ ["data", "lifecycle"],
33316
+ ["result", "lifecycle"]
33317
+ ].map((field) => [root, "details", "batchSteps", "*"].concat(field)))),
33318
+ ...["data", "message"].flatMap((root) => ["command", "success", "error"].map((field) => [root, "details", "data", "*", field]).concat(["url", "title", "origin", "targetId"].map((field) => [
33319
+ root,
33320
+ "details",
33321
+ "data",
33322
+ "*",
33323
+ "result",
33324
+ field
33325
+ ])))
33326
+ ];
33327
+
33328
+ // dist/extensions/agent-browser/lib/browser-journal-replay.js
32746
33329
  var REPLAY_CUSTOM_TYPES = /* @__PURE__ */ new Set([
32747
33330
  BROWSER_TRANSITION_ENTRY,
32748
33331
  "agent-browser-recording-reservation",
@@ -32795,18 +33378,6 @@ function legacyBrowserResult(entry) {
32795
33378
  }
32796
33379
  return message.details.sessionName !== void 0 || message.details.artifactManifest !== void 0 || message.details.electron !== void 0;
32797
33380
  }
32798
- function validateMemoryEntry(entry) {
32799
- if (!isRecord(entry)) {
32800
- return;
32801
- }
32802
- if (legacyCustom(entry) && !getBrowserRecord(entry)) {
32803
- throw new Error("Legacy browser records require stopped separate-copy conversion before replay.");
32804
- }
32805
- const message = browserMessage(entry);
32806
- if (entry.type === "message" && message && isRecord(message.details) && message.details.browserEventVersion !== 1 && !getBrowserRecord(entry)) {
32807
- throw new Error("Legacy browser observations require stopped separate-copy conversion before replay.");
32808
- }
32809
- }
32810
33381
  function inMemoryEntries(manager, physical) {
32811
33382
  const entries = physical ? manager.getEntries() : [];
32812
33383
  if (!physical) {
@@ -32826,17 +33397,53 @@ function inMemoryEntries(manager, physical) {
32826
33397
  }
32827
33398
  entries.reverse();
32828
33399
  }
32829
- for (const entry of entries) {
32830
- validateMemoryEntry(entry);
33400
+ return convertBrowserEntries(entries, legacyOwner(manager));
33401
+ }
33402
+ function legacyOwner(manager) {
33403
+ const header = manager.getHeader();
33404
+ return header?.parentSession !== void 0 ? void 0 : header?.id ?? manager.getSessionId();
33405
+ }
33406
+ function replayFields(value, legacy) {
33407
+ if (legacy) {
33408
+ return LEGACY_BROWSER_FIELDS;
32831
33409
  }
32832
- return entries;
33410
+ return value.customType === BROWSER_TRANSITION_ENTRY || value.type === "message" ? [
33411
+ ["data", "event"],
33412
+ ["data", "snapshot", "id"]
33413
+ ] : [["data"]];
33414
+ }
33415
+ function projectedRecord(value, record) {
33416
+ return {
33417
+ ...value,
33418
+ ...value.type === "custom" ? { customType: BROWSER_TRANSITION_ENTRY } : {},
33419
+ data: {
33420
+ ...record,
33421
+ ...isRecord(record.snapshot) ? { snapshot: { id: record.snapshot.id } } : {}
33422
+ }
33423
+ };
33424
+ }
33425
+ function winningSnapshot(body, source) {
33426
+ if (!source.legacy) {
33427
+ return isRecord(body?.data) ? body.data.snapshot : void 0;
33428
+ }
33429
+ const value = body?.[source.root];
33430
+ return isRecord(value) && isRecord(value.details) ? legacySnapshot(value.details.refSnapshot, source.id) : void 0;
32833
33431
  }
32834
33432
  var PublishedJournalReplay = class {
32835
33433
  file;
33434
+ ownerSessionId;
32836
33435
  projected = [];
32837
33436
  definitions = /* @__PURE__ */ new Map();
32838
- constructor(file) {
33437
+ branches;
33438
+ constructor(file, entries, ownerSessionId) {
32839
33439
  this.file = file;
33440
+ this.ownerSessionId = ownerSessionId;
33441
+ if (entries.some(({ value }) => legacyCustom(value) || legacyBrowserResult(value))) {
33442
+ this.branches = new BrowserConversionBranches(entries.map(({ value }) => value.parentId));
33443
+ }
33444
+ }
33445
+ parentProjection(parentId) {
33446
+ return typeof parentId === "string" ? this.branches?.get(parentId) ?? emptyProjection() : emptyProjection();
32840
33447
  }
32841
33448
  async project(entries) {
32842
33449
  for (const entry of entries) {
@@ -32845,25 +33452,35 @@ var PublishedJournalReplay = class {
32845
33452
  }
32846
33453
  async projectEntry(entry) {
32847
33454
  const { value } = entry;
32848
- const definition = isRecord(value.data) && isRecord(value.data.snapshot) ? value.data.snapshot.id : void 0;
32849
- if (typeof definition === "string") {
32850
- if (this.definitions.has(definition)) {
33455
+ const parent = this.parentProjection(value.parentId);
33456
+ const legacy = legacyCustom(value) || legacyBrowserResult(value);
33457
+ if (!legacy && !replayRelevant(value)) {
33458
+ this.advance(value, parent);
33459
+ return;
33460
+ }
33461
+ const body = await projectJson(readRange(this.file, entry), replayFields(value, legacy), legacy ? Infinity : void 0);
33462
+ const candidate = { ...value, ...body };
33463
+ const record = this.normalizeRecord(candidate, parent);
33464
+ this.rememberSnapshot(entry, legacy, record?.snapshot);
33465
+ this.projected.push(record ? projectedRecord(value, record) : candidate);
33466
+ }
33467
+ normalizeRecord(candidate, parent) {
33468
+ const conversion = this.branches ? convertLegacyBrowserEntry(candidate, parent, this.ownerSessionId) : void 0;
33469
+ this.advance(candidate, conversion?.projection ?? parent);
33470
+ return conversion?.record ?? getBrowserRecord(candidate);
33471
+ }
33472
+ rememberSnapshot(entry, legacy, snapshot) {
33473
+ if (isRecord(snapshot) && typeof snapshot.id === "string") {
33474
+ if (this.definitions.has(snapshot.id)) {
32851
33475
  throw new Error("Browser snapshot identity is defined more than once on this ancestry.");
32852
33476
  }
32853
- this.definitions.set(definition, entry);
33477
+ this.definitions.set(snapshot.id, { entry, legacy });
32854
33478
  }
32855
- if (legacyCustom(value) || legacyBrowserResult(value)) {
32856
- throw new Error("This session contains legacy browser records. Convert a stopped separate copy with npm exec --package pi-agent-browser-native -- pi-agent-browser-convert before resuming browser work; the original journal is retained.");
32857
- }
32858
- if (!replayRelevant(value, definition)) {
32859
- return;
33479
+ }
33480
+ advance(value, projection) {
33481
+ if (typeof value.id === "string") {
33482
+ this.branches?.advance(value.id, value.parentId, projection);
32860
33483
  }
32861
- const fields = value.customType === BROWSER_TRANSITION_ENTRY || value.type === "message" ? [
32862
- ["data", "event"],
32863
- ["data", "snapshot", "id"]
32864
- ] : [["data"]];
32865
- const body = await projectJson(readRange(this.file, entry), fields);
32866
- this.projected.push({ ...value, ...body });
32867
33484
  }
32868
33485
  async resolveWinningDefinitions(physical) {
32869
33486
  const { SessionPageState: SessionPageState2 } = await Promise.resolve().then(() => (init_session_page_state(), session_page_state_exports));
@@ -32879,24 +33496,27 @@ var PublishedJournalReplay = class {
32879
33496
  return this.projected;
32880
33497
  }
32881
33498
  async resolveDefinition(id) {
32882
- const entry = this.definitions.get(id);
32883
- if (!entry) {
33499
+ const definition = this.definitions.get(id);
33500
+ if (!definition) {
32884
33501
  throw new Error(`Browser snapshot ${id} has no ancestral definition; inspect and take a fresh snapshot.`);
32885
33502
  }
32886
- const body = await projectJson(readRange(this.file, entry), [["data", "snapshot"]], Infinity);
33503
+ const { entry, legacy } = definition;
33504
+ const root = entry.value.type === "message" ? "message" : "data";
33505
+ const body = await projectJson(readRange(this.file, entry), legacy ? [[root, "details", "refSnapshot"]] : [["data", "snapshot"]], Infinity);
33506
+ const resolved = winningSnapshot(body, { root, legacy, id });
32887
33507
  const destination = this.projected.find((candidate) => isRecord(candidate) && candidate.id === entry.value.id);
32888
- if (!isRecord(destination) || !isRecord(destination.data) || !isRecord(body?.data)) {
33508
+ if (!isRecord(destination) || !isRecord(destination.data)) {
32889
33509
  throw new Error("Winning browser snapshot could not be read.");
32890
33510
  }
32891
- destination.data.snapshot = body.data.snapshot;
32892
- if (!isRecord(body.data.snapshot) || body.data.snapshot.id !== id) {
33511
+ destination.data.snapshot = resolved;
33512
+ if (!isRecord(resolved) || resolved.id !== id) {
32893
33513
  throw new Error("Winning browser snapshot identity is invalid.");
32894
33514
  }
32895
- snapshotFromDefinition(body.data.snapshot);
33515
+ snapshotFromDefinition(resolved);
32896
33516
  }
32897
33517
  };
32898
- function replayRelevant(value, definition) {
32899
- return value.type === "custom" && typeof value.customType === "string" && REPLAY_CUSTOM_TYPES.has(value.customType) || isRecord(value.data) && isRecord(value.data.event) || definition !== void 0;
33518
+ function replayRelevant(value) {
33519
+ return value.type === "custom" && typeof value.customType === "string" && REPLAY_CUSTOM_TYPES.has(value.customType) || isRecord(value.data) && isRecord(value.data.event) || isRecord(value.data) && isRecord(value.data.snapshot) && value.data.snapshot.id !== void 0;
32900
33520
  }
32901
33521
  async function verifyCapturedFile(file, path, captured) {
32902
33522
  const current = await file.stat();
@@ -32939,8 +33559,9 @@ async function readBrowserEntries(manager, physical = false) {
32939
33559
  const metadata = await scanJournalMetadata(file, captured.size);
32940
33560
  validateJournalHeader(metadata, manager.getHeader()?.id ?? manager.getSessionId());
32941
33561
  const records = metadata.filter((entry) => entry.value.type !== "session");
32942
- const replay = new PublishedJournalReplay(file);
32943
- await replay.project(physical ? records : branchEntries(records, leaf));
33562
+ const selected = physical ? records : branchEntries(records, leaf);
33563
+ const replay = new PublishedJournalReplay(file, selected, legacyOwner(manager));
33564
+ await replay.project(selected);
32944
33565
  const entries = await replay.resolveWinningDefinitions(physical);
32945
33566
  await verifyCapturedFile(file, path, captured);
32946
33567
  return entries;
@@ -33432,14 +34053,14 @@ function artifactKind(path) {
33432
34053
  }
33433
34054
  return void 0;
33434
34055
  }
33435
- function intentClause(context) {
33436
- return context.split(CLAUSE_BOUNDARY_PATTERN).at(-1) ?? context;
34056
+ function intentClause(context2) {
34057
+ return context2.split(CLAUSE_BOUNDARY_PATTERN).at(-1) ?? context2;
33437
34058
  }
33438
- function trailingClause(context) {
33439
- return context.split(CLAUSE_BOUNDARY_PATTERN)[0] ?? context;
34059
+ function trailingClause(context2) {
34060
+ return context2.split(CLAUSE_BOUNDARY_PATTERN)[0] ?? context2;
33440
34061
  }
33441
- function hasOutputIntent(context) {
33442
- const clause = intentClause(context).replace(/\[[^\]\r\n]*\]\(\s*$/, "").replace(/[([{"'`]+\s*$/, "");
34062
+ function hasOutputIntent(context2) {
34063
+ const clause = intentClause(context2).replace(/\[[^\]\r\n]*\]\(\s*$/, "").replace(/[([{"'`]+\s*$/, "");
33443
34064
  const match = clause.match(OUTPUT_INTENT_PATTERN) ?? clause.match(COLON_OUTPUT_INTENT_PATTERN);
33444
34065
  if (!match) {
33445
34066
  return false;
@@ -33451,8 +34072,8 @@ function hasOutputIntent(context) {
33451
34072
  }
33452
34073
  return governingPrefix.trim().length === 0 || AFFIRMATIVE_PREFIX_PATTERN.test(governingPrefix.trim()) || AFFIRMATIVE_LEAD_IN_PATTERN.test(governingPrefix);
33453
34074
  }
33454
- function stripListPrefix(context) {
33455
- return context.replace(LIST_PREFIX_PATTERN, "");
34075
+ function stripListPrefix(context2) {
34076
+ return context2.replace(LIST_PREFIX_PATTERN, "");
33456
34077
  }
33457
34078
  function pathMatches(line) {
33458
34079
  PATH_PATTERN.lastIndex = 0;
@@ -33499,10 +34120,10 @@ ${localContext}`;
33499
34120
  }
33500
34121
  return localContext;
33501
34122
  }
33502
- selectGroup(direct, priorLine, context) {
34123
+ selectGroup(direct, priorLine, context2) {
33503
34124
  if (direct) {
33504
34125
  const group = this.nextGroup++;
33505
- this.groupOptional.set(group, this.input.recordingOptional || OPTIONAL_RECORDING_PATTERN.test(intentClause(context)));
34126
+ this.groupOptional.set(group, this.input.recordingOptional || OPTIONAL_RECORDING_PATTERN.test(intentClause(context2)));
33506
34127
  return group;
33507
34128
  }
33508
34129
  if (priorLine) {
@@ -33512,30 +34133,30 @@ ${localContext}`;
33512
34133
  }
33513
34134
  return void 0;
33514
34135
  }
33515
- excludesCandidate(path, context, trailing, direct) {
34136
+ excludesCandidate(path, context2, trailing, direct) {
33516
34137
  if (/(?:^|[\\/])pi-(?:attachment|clipboard|paste|upload)-/i.test(path)) {
33517
34138
  return true;
33518
34139
  }
33519
- return direct && (REFERENCE_INTENT_PATTERN.test(intentClause(context)) || EXPLICIT_OPTIONAL_PATTERN.test(intentClause(context)) || EXPLICIT_OPTIONAL_PATTERN.test(trailing));
34140
+ return direct && (REFERENCE_INTENT_PATTERN.test(intentClause(context2)) || EXPLICIT_OPTIONAL_PATTERN.test(intentClause(context2)) || EXPLICIT_OPTIONAL_PATTERN.test(trailing));
33520
34141
  }
33521
- continuesPriorLine(index, kind, context) {
33522
- return index === 0 && this.isPathList && kind === this.input.continuation?.kind && LIST_CONNECTOR_PATTERN.test(context);
34142
+ continuesPriorLine(index, kind, context2) {
34143
+ return index === 0 && this.isPathList && kind === this.input.continuation?.kind && LIST_CONNECTOR_PATTERN.test(context2);
33523
34144
  }
33524
- continuesSameLine(kind, context) {
33525
- return kind === this.previousKind && this.previousGroup !== void 0 && LIST_CONNECTOR_PATTERN.test(context);
34145
+ continuesSameLine(kind, context2) {
34146
+ return kind === this.previousKind && this.previousGroup !== void 0 && LIST_CONNECTOR_PATTERN.test(context2);
33526
34147
  }
33527
34148
  collectCandidate(index) {
33528
34149
  const { end, path, start } = this.input.matches[index];
33529
34150
  const localContext = stripListPrefix(this.input.line.slice(this.previousPathEnd, start));
33530
- const context = this.candidateContext(index, localContext);
34151
+ const context2 = this.candidateContext(index, localContext);
33531
34152
  const kind = artifactKind(path);
33532
- const direct = hasOutputIntent(context);
34153
+ const direct = hasOutputIntent(context2);
33533
34154
  const sameLine = this.continuesSameLine(kind, localContext);
33534
34155
  const priorLine = this.continuesPriorLine(index, kind, localContext);
33535
- const group = !direct && sameLine ? this.previousGroup : this.selectGroup(direct, priorLine, context);
34156
+ const group = !direct && sameLine ? this.previousGroup : this.selectGroup(direct, priorLine, context2);
33536
34157
  const trailing = trailingClause(this.input.line.slice(end, this.input.matches[index + 1]?.start ?? this.input.line.length));
33537
34158
  this.previousPathEnd = end;
33538
- if (kind === void 0 || group === void 0 || this.excludesCandidate(path, context, trailing, direct)) {
34159
+ if (kind === void 0 || group === void 0 || this.excludesCandidate(path, context2, trailing, direct)) {
33539
34160
  this.previousGroup = void 0;
33540
34161
  this.previousKind = void 0;
33541
34162
  return;
@@ -34631,9 +35252,9 @@ function registerCoreTools(pi, options, execute) {
34631
35252
  parameters: AGENT_BROWSER_CODE_PARAMS,
34632
35253
  execute: async (id, params, signal, onUpdate, ctx) => finalizeAgentBrowserNativeResult(await options.executeCode(id, params, signal, onUpdate, ctx), params),
34633
35254
  executionMode: options.executionMode,
34634
- renderCall(args, theme, context) {
34635
- const text3 = context.lastComponent instanceof Text2 ? context.lastComponent : new Text2("", 0, 0);
34636
- text3.setText(formatAgentBrowserRenderCall(args, theme, context.expanded));
35255
+ renderCall(args, theme, context2) {
35256
+ const text3 = context2.lastComponent instanceof Text2 ? context2.lastComponent : new Text2("", 0, 0);
35257
+ text3.setText(formatAgentBrowserRenderCall(args, theme, context2.expanded));
34637
35258
  return text3;
34638
35259
  },
34639
35260
  renderResult: options.renderResult
@@ -38415,7 +39036,7 @@ async function runAgentBrowserScript(options) {
38415
39036
 
38416
39037
  // dist/extensions/agent-browser/lib/orchestration/script-mode.js
38417
39038
  import { stat as stat13 } from "node:fs/promises";
38418
- import { randomUUID as randomUUID7 } from "node:crypto";
39039
+ import { randomUUID as randomUUID8 } from "node:crypto";
38419
39040
  init_parsing();
38420
39041
  init_browser_transcript();
38421
39042
  init_runtime();
@@ -38623,7 +39244,7 @@ function appendScriptSessionLease(pi, sessionName, cleanup, ownerSessionId) {
38623
39244
  event: {
38624
39245
  version: 1,
38625
39246
  phase: "state",
38626
- operationId: randomUUID7(),
39247
+ operationId: randomUUID8(),
38627
39248
  toolCallId: "cleanup",
38628
39249
  commandIndex: 0,
38629
39250
  isError: cleanup !== "closed",
@@ -38724,7 +39345,7 @@ var BrowserCodeOutput = class {
38724
39345
  }
38725
39346
  return run.failureCategory ?? (run.rejectedCallCount > 0 ? "validation-error" : void 0);
38726
39347
  }
38727
- observation(run, context, output) {
39348
+ observation(run, context2, output) {
38728
39349
  const failureCategory3 = this.failureCategory(run, output.error);
38729
39350
  const success = run.ok && failureCategory3 === void 0;
38730
39351
  return {
@@ -38733,7 +39354,7 @@ var BrowserCodeOutput = class {
38733
39354
  failureCategory: failureCategory3,
38734
39355
  data: output.data,
38735
39356
  error: output.error ?? (run.error !== void 0 && run.error.length > 0 ? redactSensitiveText(run.error) : void 0),
38736
- ...context,
39357
+ ...context2,
38737
39358
  codeRun: {
38738
39359
  callCount: run.callCount,
38739
39360
  emitCount: run.emitCount,
@@ -39520,7 +40141,7 @@ import { Text as Text3 } from "@earendil-works/pi-tui";
39520
40141
 
39521
40142
  // dist/extensions/agent-browser/lib/orchestration/extension-observation.js
39522
40143
  init_browser_transcript();
39523
- import { randomUUID as randomUUID8 } from "node:crypto";
40144
+ import { randomUUID as randomUUID9 } from "node:crypto";
39524
40145
  init_runtime();
39525
40146
  init_argv_grammar();
39526
40147
  init_parsing();
@@ -39547,9 +40168,9 @@ function observedResult(observation2, manifest) {
39547
40168
  var ObservationPublication = class {
39548
40169
  resources;
39549
40170
  context;
39550
- constructor(resources, context) {
40171
+ constructor(resources, context2) {
39551
40172
  this.resources = resources;
39552
- this.context = context;
40173
+ this.context = context2;
39553
40174
  }
39554
40175
  async render(result, params) {
39555
40176
  const details = observationDetails(result);
@@ -39588,7 +40209,7 @@ var ObservationPublication = class {
39588
40209
  event: {
39589
40210
  version: 1,
39590
40211
  phase: "state",
39591
- operationId: randomUUID8(),
40212
+ operationId: randomUUID9(),
39592
40213
  toolCallId: "observation",
39593
40214
  commandIndex: 0,
39594
40215
  isError: observation2.result.isError === true,
@@ -39623,8 +40244,8 @@ var ObservationPublication = class {
39623
40244
  return this.resources.queue.run(() => this.publish(observation2));
39624
40245
  }
39625
40246
  };
39626
- function finalizeObservation(resources, result, params, context) {
39627
- return new ObservationPublication(resources, context).run(result, params);
40247
+ function finalizeObservation(resources, result, params, context2) {
40248
+ return new ObservationPublication(resources, context2).run(result, params);
39628
40249
  }
39629
40250
 
39630
40251
  // dist/extensions/agent-browser/lib/orchestration/extension-code.js
@@ -39641,7 +40262,7 @@ init_batch_stdin();
39641
40262
  init_launch_scoped_flags();
39642
40263
  init_process_environment();
39643
40264
  init_runtime();
39644
- import { createHash as createHash5 } from "node:crypto";
40265
+ import { createHash as createHash6 } from "node:crypto";
39645
40266
  import { homedir as homedir4 } from "node:os";
39646
40267
  import { join as join28, resolve as resolve13 } from "node:path";
39647
40268
 
@@ -40141,12 +40762,25 @@ function rootRestoreKey(policy, status, restoreKey) {
40141
40762
  }
40142
40763
  return status === "inactive" ? policy.rootName : void 0;
40143
40764
  }
40144
- async function withRootBrowserLaunch(policy, browserRun, signal) {
40765
+ function rootLaunchEnvironment(policy, daemon) {
40766
+ const bootstrap = daemon.status === "inactive";
40767
+ const restore = rootRestoreKey(policy, daemon.status, daemon.status === "active" ? daemon.restoreKey : void 0);
40768
+ const profile = bootstrapProfile(policy, bootstrap);
40769
+ const executablePath = bootstrapExecutable(policy, bootstrap);
40770
+ return {
40771
+ ...restore !== void 0 ? { AGENT_BROWSER_RESTORE: restore } : {},
40772
+ ...profile !== void 0 ? { AGENT_BROWSER_PROFILE: profile } : {},
40773
+ ...executablePath !== void 0 ? { AGENT_BROWSER_EXECUTABLE_PATH: executablePath } : {}
40774
+ };
40775
+ }
40776
+ async function withRootBrowserLaunch(policy, browserRun, signal, includeGeneration = false) {
40777
+ const namespace = cliValue(policy.input.toolArgs, "--namespace") ?? policy.namespace;
40145
40778
  const daemon = await inspectManagedSessionDaemon({
40146
40779
  cwd: policy.cwd,
40147
40780
  signal,
40148
40781
  sessionName: policy.rootName,
40149
- namespace: cliValue(policy.input.toolArgs, "--namespace") ?? policy.namespace,
40782
+ namespace,
40783
+ includeGeneration,
40150
40784
  timeoutMs: 5e3
40151
40785
  });
40152
40786
  if (daemon.status === "missing-binary") {
@@ -40171,15 +40805,11 @@ async function withRootBrowserLaunch(policy, browserRun, signal) {
40171
40805
  validationError: "qa.attached requires an active attached session. Open the root browser first, or select an existing native session."
40172
40806
  });
40173
40807
  }
40174
- const bootstrap = daemon.status === "inactive";
40175
- const restore = rootRestoreKey(policy, daemon.status, daemon.status === "active" ? daemon.restoreKey : void 0);
40176
- const profile = bootstrapProfile(policy, bootstrap);
40177
- const executablePath = bootstrapExecutable(policy, bootstrap);
40178
- return withAgentBrowserProcessEnvironment({
40179
- ...restore !== void 0 ? { AGENT_BROWSER_RESTORE: restore } : {},
40180
- ...profile !== void 0 ? { AGENT_BROWSER_PROFILE: profile } : {},
40181
- ...executablePath !== void 0 ? { AGENT_BROWSER_EXECUTABLE_PATH: executablePath } : {}
40182
- }, () => withChromeStartupArgs(bootstrap || policy.configuredChromeLaunch ? policy.chromeStartupArgs : void 0, () => browserRun(bootstrap)));
40808
+ return withAgentBrowserProcessEnvironment(rootLaunchEnvironment(policy, daemon), () => withChromeStartupArgs(daemon.status === "inactive" || policy.configuredChromeLaunch ? policy.chromeStartupArgs : void 0, () => browserRun({
40809
+ identity: getAgentBrowserSessionIdentityKey(policy.rootName, namespace),
40810
+ daemon,
40811
+ generationInspected: includeGeneration
40812
+ })));
40183
40813
  }
40184
40814
 
40185
40815
  // dist/extensions/agent-browser/lib/orchestration/native-session-defaults.js
@@ -40190,7 +40820,7 @@ function requestsConnection(tokens, stdin) {
40190
40820
  return tokens[0] === "connect" || getUpstreamEffectiveBatchSteps(tokens, stdin).some((step) => requestsConnection(step));
40191
40821
  }
40192
40822
  function rootBrowserSessionName(rootSessionId) {
40193
- return `pi-root-${createHash5("sha256").update(rootSessionId).digest("hex").slice(0, 24)}`;
40823
+ return `pi-root-${createHash6("sha256").update(rootSessionId).digest("hex").slice(0, 24)}`;
40194
40824
  }
40195
40825
  function nativeBooleanOverrides(args) {
40196
40826
  const overrides = [];
@@ -40213,20 +40843,20 @@ var NativeSessionCall = class {
40213
40843
  browserCommand;
40214
40844
  rootFallback;
40215
40845
  identity = {};
40216
- constructor(input, context, runner) {
40846
+ constructor(input, context2, runner) {
40217
40847
  this.input = input;
40218
- this.context = context;
40848
+ this.context = context2;
40219
40849
  this.runner = runner;
40220
40850
  const configArg = scanUpstreamGlobalFlagOccurrences([...input.toolArgs], "--config").at(0);
40221
40851
  this.configPath = configArg?.value ?? this.env.AGENT_BROWSER_CONFIG;
40222
- this.configPaths = this.configPath !== void 0 ? [resolve13(context.cwd, this.configPath)] : [
40852
+ this.configPaths = this.configPath !== void 0 ? [resolve13(context2.cwd, this.configPath)] : [
40223
40853
  join28(homedir4(), ".agent-browser", "config.json"),
40224
- join28(context.cwd, "agent-browser.json")
40854
+ join28(context2.cwd, "agent-browser.json")
40225
40855
  ];
40226
- this.rootName = context.root === void 0 ? void 0 : rootBrowserSessionName(context.root.id);
40856
+ this.rootName = context2.root === void 0 ? void 0 : rootBrowserSessionName(context2.root.id);
40227
40857
  this.browserCommand = input.kind !== "electron" && needsManagedSession(parseArgvDescriptor([...input.toolArgs]), input.toolStdin);
40228
40858
  const session = extractExplicitSessionName([...input.toolArgs]);
40229
- this.rootFallback = context.root !== void 0 && this.env.AGENT_BROWSER_SESSION === void 0 && (session === void 0 || session === this.rootName) && this.browserCommand;
40859
+ this.rootFallback = context2.root !== void 0 && this.env.AGENT_BROWSER_SESSION === void 0 && (session === void 0 || session === this.rootName) && this.browserCommand;
40230
40860
  }
40231
40861
  attachment() {
40232
40862
  const autoConnect = getBooleanFlagValue([...this.input.toolArgs], "--auto-connect") ?? (isUpstreamEnvFlagEnabled(this.env.AGENT_BROWSER_AUTO_CONNECT) || this.identity.autoConnect === true);
@@ -40336,7 +40966,7 @@ var NativeSessionCall = class {
40336
40966
  return withAgentBrowserProcessEnvironment(this.executionEnvironment(args, session, namespace), () => this.runner(input, defaults), nativeBooleanOverrides(args));
40337
40967
  }
40338
40968
  rootLaunchRunner(policy) {
40339
- return (browserRun, signal = this.context.signal) => withRootBrowserLaunch(policy, browserRun, signal);
40969
+ return (browserRun, signal = this.context.signal, includeGeneration) => withRootBrowserLaunch(policy, browserRun, signal, includeGeneration);
40340
40970
  }
40341
40971
  async run() {
40342
40972
  this.identity = await loadNativeIdentity(this.configPaths, {
@@ -40348,11 +40978,11 @@ var NativeSessionCall = class {
40348
40978
  return this.input.kind === "electron" ? this.runElectron() : this.runBrowser();
40349
40979
  }
40350
40980
  };
40351
- async function withNativeSessionDefaults(input, context, run) {
40981
+ async function withNativeSessionDefaults(input, context2, run) {
40352
40982
  if (isPlainTextInspectionArgs([...input.toolArgs])) {
40353
40983
  return run(input);
40354
40984
  }
40355
- return new NativeSessionCall(input, context, run).run();
40985
+ return new NativeSessionCall(input, context2, run).run();
40356
40986
  }
40357
40987
 
40358
40988
  // dist/extensions/agent-browser/lib/execution-cwd.js
@@ -41101,7 +41731,7 @@ init_managed_session_policy_lock();
41101
41731
 
41102
41732
  // dist/extensions/agent-browser/lib/orchestration/extension-host-run.js
41103
41733
  init_browser_transcript();
41104
- import { randomUUID as randomUUID9 } from "node:crypto";
41734
+ import { randomUUID as randomUUID10 } from "node:crypto";
41105
41735
  init_runtime();
41106
41736
  init_argv_grammar();
41107
41737
  init_parsing();
@@ -41135,7 +41765,7 @@ var ElectronHostTransaction = class {
41135
41765
  this.workingPageState = this.runtime.sessions.pages.fork();
41136
41766
  this.priorPages = this.workingPageState.views();
41137
41767
  this.priorManifest = this.runtime.artifacts.manifest;
41138
- this.operationId = randomUUID9();
41768
+ this.operationId = randomUUID10();
41139
41769
  this.launchId = this.call.compiledElectron && "launchId" in this.call.compiledElectron ? this.call.compiledElectron.launchId : void 0;
41140
41770
  this.selected = this.launchId !== void 0 && this.launchId !== "" ? [this.electronHostLaunchRecords.get(this.launchId)].filter((record) => record !== void 0) : getActiveElectronRecords(this.electronHostLaunchRecords);
41141
41771
  this.keys = this.selectedKeys();
@@ -41451,13 +42081,14 @@ init_runtime();
41451
42081
  init_runtime();
41452
42082
  init_argv_grammar();
41453
42083
  init_process();
42084
+ init_command_taxonomy();
41454
42085
  init_wait_timeouts();
41455
42086
  init_process_environment();
41456
42087
  init_managed_session_policy_lock();
41457
42088
 
41458
42089
  // dist/extensions/agent-browser/lib/orchestration/extension-command-run.js
41459
42090
  init_browser_transcript();
41460
- import { randomUUID as randomUUID11 } from "node:crypto";
42091
+ import { randomUUID as randomUUID12 } from "node:crypto";
41461
42092
  init_runtime();
41462
42093
  init_argv_grammar();
41463
42094
  init_argv_descriptor();
@@ -42369,7 +43000,7 @@ function prepareBrowserCommand(runtime, call, executionSignal) {
42369
43000
  const priorPages = workingPageState.views();
42370
43001
  const sessionPageStateUpdate = workingPageState.beginUpdate();
42371
43002
  const selectedPlan = selectCommandPlan(browserRunState, call);
42372
- const operationId = randomUUID11();
43003
+ const operationId = randomUUID12();
42373
43004
  const selectedKey = getAgentBrowserSessionIdentityKey(selectedPlan.sessionName ?? "default", selectedPlan.namespace);
42374
43005
  browserRunState.confirmationPolicyIdentity = selectedKey;
42375
43006
  const confirmActions = getAgentBrowserProcessEnvironment().AGENT_BROWSER_CONFIRM_ACTIONS;
@@ -42433,7 +43064,7 @@ function captureDispatch(attachedSessionKeys, call, prepared) {
42433
43064
  async function dispatchBrowserCommand(timeouts, call, prepared, dispatch) {
42434
43065
  try {
42435
43066
  return await runAgentBrowserTool({
42436
- daemonInactive: dispatch.daemonInactive,
43067
+ initialDaemonObservation: dispatch.initialDaemonObservation,
42437
43068
  ctx: call.ctx,
42438
43069
  cwd: call.browserCwd,
42439
43070
  operationCwd: call.operationCwd,
@@ -42463,7 +43094,7 @@ async function dispatchBrowserCommand(timeouts, call, prepared, dispatch) {
42463
43094
  };
42464
43095
  }
42465
43096
  }
42466
- async function runBrowserCommand(runtime, call, daemonInactive, executionSignal = call.signal) {
43097
+ async function runBrowserCommand(runtime, call, initialDaemonObservation, executionSignal = call.signal) {
42467
43098
  const prepared = prepareBrowserCommand(runtime, call, executionSignal);
42468
43099
  const admissionFailure = await admitBrowserCommand(runtime.pi, runtime.sessions.pages, call, prepared);
42469
43100
  if (admissionFailure) {
@@ -42472,7 +43103,7 @@ async function runBrowserCommand(runtime, call, daemonInactive, executionSignal
42472
43103
  const dispatch = captureDispatch(runtime.sessions.attached, call, prepared);
42473
43104
  const result = await dispatchBrowserCommand({ close: runtime.implicitSessionCloseTimeoutMs, idle: runtime.implicitSessionIdleTimeoutMs }, call, prepared, {
42474
43105
  ...dispatch,
42475
- daemonInactive
43106
+ initialDaemonObservation
42476
43107
  });
42477
43108
  const completion = new BrowserCommandResult(runtime, call, prepared, { ...dispatch, result });
42478
43109
  completion.reconcileNativeIdentity();
@@ -42516,7 +43147,7 @@ var BrowserCommandCoordinator = class {
42516
43147
  };
42517
43148
  }
42518
43149
  execute(signal) {
42519
- return this.call.withLaunchDefaults ? this.call.withLaunchDefaults((inactive) => runBrowserCommand(this.runtime, this.call, inactive, signal), signal) : runBrowserCommand(this.runtime, this.call, void 0, signal);
43150
+ return this.call.withLaunchDefaults ? this.call.withLaunchDefaults((observation2) => runBrowserCommand(this.runtime, this.call, observation2, signal), signal, !isCloseCommand(this.plan.commandInfo.command) && (this.runtime.sessions.pages.get(this.key).refSnapshot?.refIds.length ?? 0) > 0) : runBrowserCommand(this.runtime, this.call, void 0, signal);
42520
43151
  }
42521
43152
  async preflightAndExecute(signal) {
42522
43153
  const error = getArtifactPreflightValidationError({
@@ -43122,15 +43753,15 @@ function executeCode(runtime, invocation) {
43122
43753
 
43123
43754
  // dist/extensions/agent-browser/lib/orchestration/extension-tool-boundary.js
43124
43755
  function registerBrowserTools(runtime) {
43125
- const renderResult = (result, options, theme, context) => {
43126
- const component = context.lastComponent instanceof AgentBrowserResultComponent ? context.lastComponent : new AgentBrowserResultComponent();
43127
- component.setResult(result, options, theme, context.isError);
43756
+ const renderResult = (result, options, theme, context2) => {
43757
+ const component = context2.lastComponent instanceof AgentBrowserResultComponent ? context2.lastComponent : new AgentBrowserResultComponent();
43758
+ component.setResult(result, options, theme, context2.isError);
43128
43759
  return component;
43129
43760
  };
43130
43761
  const renderers = {
43131
- renderCall: (args, theme, context) => {
43132
- const text3 = context.lastComponent instanceof Text3 ? context.lastComponent : new Text3("", 0, 0);
43133
- text3.setText(formatAgentBrowserRenderCall(args, theme, context.expanded));
43762
+ renderCall: (args, theme, context2) => {
43763
+ const text3 = context2.lastComponent instanceof Text3 ? context2.lastComponent : new Text3("", 0, 0);
43764
+ text3.setText(formatAgentBrowserRenderCall(args, theme, context2.expanded));
43134
43765
  return text3;
43135
43766
  },
43136
43767
  renderResult