@runtypelabs/persona 4.24.0 → 4.26.0

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 (237) hide show
  1. package/dist/animations/glyph-cycle.d.cts +1 -1
  2. package/dist/animations/glyph-cycle.d.ts +1 -1
  3. package/dist/animations/{types-Db61aI9J.d.cts → types-BwKTZhg9.d.cts} +14 -0
  4. package/dist/animations/{types-Db61aI9J.d.ts → types-BwKTZhg9.d.ts} +14 -0
  5. package/dist/animations/wipe.d.cts +1 -1
  6. package/dist/animations/wipe.d.ts +1 -1
  7. package/dist/animations-extra.d.cts +14 -0
  8. package/dist/animations-extra.d.ts +14 -0
  9. package/dist/approval-ui-QAKWNFNM.js +1 -0
  10. package/dist/approval-ui.cjs +2 -2
  11. package/dist/approval-ui.d.cts +243 -8
  12. package/dist/approval-ui.d.ts +243 -8
  13. package/dist/approval-ui.js +2 -2
  14. package/dist/{artifacts-ui-IGB5YKLO.js → artifacts-ui-NJGMM27I.js} +1 -1
  15. package/dist/artifacts-ui.cjs +4 -4
  16. package/dist/artifacts-ui.d.cts +243 -8
  17. package/dist/artifacts-ui.d.ts +243 -8
  18. package/dist/artifacts-ui.js +5 -5
  19. package/dist/chunk-2ANTRKTV.js +1 -0
  20. package/dist/chunk-4HPTPUC6.js +1 -0
  21. package/dist/chunk-6V3MNEKB.js +1 -0
  22. package/dist/chunk-HGUCGM3K.js +9 -0
  23. package/dist/chunk-IO5VVUKP.js +3 -0
  24. package/dist/chunk-J4J3Y2P2.js +1 -0
  25. package/dist/chunk-K6HKIP5K.js +1 -0
  26. package/dist/chunk-K7NA7G7J.js +1 -0
  27. package/dist/chunk-MXUTS3LB.js +1 -0
  28. package/dist/chunk-PDPVORUF.js +1 -0
  29. package/dist/chunk-QPPJUSZH.js +1 -0
  30. package/dist/chunk-QRKGQPU7.js +1 -0
  31. package/dist/chunk-S6PBWE75.js +1 -0
  32. package/dist/chunk-T7QM7YMF.js +1 -0
  33. package/dist/chunk-TR2H475E.js +1 -0
  34. package/dist/chunk-UPO4GUFC.js +1 -0
  35. package/dist/chunk-ZC66NAIR.js +1 -0
  36. package/dist/client-history-YPEG45Q4.js +1 -0
  37. package/dist/client-history.js +1 -0
  38. package/dist/client-stream-42FOI3EC.js +4 -0
  39. package/dist/client-stream.js +5 -0
  40. package/dist/codegen.cjs +1 -1
  41. package/dist/codegen.js +1 -1
  42. package/dist/context-mentions-E7HJYWO6.js +161 -0
  43. package/dist/{context-mentions-inline-I2RDEBAK.js → context-mentions-inline-QVESLW55.js} +1 -1
  44. package/dist/context-mentions.cjs +7 -7
  45. package/dist/context-mentions.d.cts +243 -8
  46. package/dist/context-mentions.d.ts +243 -8
  47. package/dist/context-mentions.js +8 -8
  48. package/dist/event-stream-view-FOIJHFQO.js +1 -0
  49. package/dist/event-stream-view.cjs +1 -1
  50. package/dist/event-stream-view.d.cts +246 -31
  51. package/dist/event-stream-view.d.ts +246 -31
  52. package/dist/event-stream-view.js +1 -1
  53. package/dist/forms-ui.d.cts +295 -667
  54. package/dist/forms-ui.d.ts +295 -667
  55. package/dist/history-shell-QDQ44PSE.js +3 -0
  56. package/dist/history-shell.js +3 -0
  57. package/dist/{history-view-BD6OXLNA.js → history-view-NCFBI5GR.js} +2 -2
  58. package/dist/history-view.cjs +2 -2
  59. package/dist/history-view.d.cts +35 -1
  60. package/dist/history-view.d.ts +35 -1
  61. package/dist/history-view.js +2 -2
  62. package/dist/index.cjs +80 -74
  63. package/dist/index.cjs.map +1 -1
  64. package/dist/index.d.cts +301 -738
  65. package/dist/index.d.ts +301 -738
  66. package/dist/index.global.js +3 -215
  67. package/dist/index.global.js.map +1 -1
  68. package/dist/index.js +81 -75
  69. package/dist/index.js.map +1 -1
  70. package/dist/install.global.js +1 -1
  71. package/dist/install.global.js.map +1 -1
  72. package/dist/launcher.global.js +3 -67
  73. package/dist/launcher.global.js.map +1 -1
  74. package/dist/markdown-parsers.js +22 -22
  75. package/dist/runtype-tts-entry-NFBVWR7N.js +1 -0
  76. package/dist/runtype-tts.js +1 -1
  77. package/dist/session-actions-ISSKSI66.js +1 -0
  78. package/dist/session-actions.js +1 -0
  79. package/dist/session-reconnect.d.cts +243 -8
  80. package/dist/session-reconnect.d.ts +243 -8
  81. package/dist/smart-dom-reader.cjs +13 -13
  82. package/dist/smart-dom-reader.d.cts +243 -8
  83. package/dist/smart-dom-reader.d.ts +243 -8
  84. package/dist/smart-dom-reader.js +11 -11
  85. package/dist/theme-editor-preview.cjs +116 -98
  86. package/dist/theme-editor-preview.d.cts +245 -8
  87. package/dist/theme-editor-preview.d.ts +245 -8
  88. package/dist/theme-editor-preview.js +49 -54
  89. package/dist/theme-editor.cjs +2 -2
  90. package/dist/theme-editor.d.cts +244 -23
  91. package/dist/theme-editor.d.ts +244 -23
  92. package/dist/theme-editor.js +2 -2
  93. package/dist/theme-reference.d.cts +14 -0
  94. package/dist/theme-reference.d.ts +14 -0
  95. package/dist/ui-extras-entry-WAYFKVNW.js +3 -0
  96. package/dist/ui-extras.js +72 -0
  97. package/dist/voice-runtime-UOQOFAFY.js +17 -0
  98. package/dist/voice-runtime.cjs +17 -1
  99. package/dist/voice-runtime.d.cts +11643 -192
  100. package/dist/voice-runtime.d.ts +11643 -192
  101. package/dist/voice-runtime.js +17 -1
  102. package/dist/voice-worklet-player.cjs +19 -4
  103. package/dist/voice-worklet-player.d.cts +9 -10
  104. package/dist/voice-worklet-player.d.ts +9 -10
  105. package/dist/voice-worklet-player.js +19 -4
  106. package/dist/webmcp-polyfill.js +1 -1
  107. package/dist/webmcp-runtime-V6ZWW3PI.js +6 -0
  108. package/dist/webmcp-runtime.cjs +2 -2
  109. package/dist/webmcp-runtime.d.cts +1 -33
  110. package/dist/webmcp-runtime.d.ts +1 -33
  111. package/dist/webmcp-runtime.js +2 -2
  112. package/dist/widget.css +1 -1
  113. package/package.json +11 -5
  114. package/src/approval-paused-tool-settle.test.ts +221 -0
  115. package/src/client-approve.test.ts +311 -0
  116. package/src/client-history-eager.ts +9 -0
  117. package/src/client-history-loader.ts +23 -0
  118. package/src/client-history.ts +579 -0
  119. package/src/client-resume.ts +177 -0
  120. package/src/client-stream-eager.ts +12 -0
  121. package/src/client-stream-loader.ts +25 -0
  122. package/src/client-stream.ts +1880 -0
  123. package/src/client.test.ts +31 -1
  124. package/src/client.ts +293 -2607
  125. package/src/components/approval-actions.test.ts +27 -0
  126. package/src/components/approval-actions.ts +27 -3
  127. package/src/components/message-bubble.test.ts +19 -0
  128. package/src/components/message-bubble.ts +2 -0
  129. package/src/components/registry.ts +6 -6
  130. package/src/components/tool-bubble.test.ts +9 -0
  131. package/src/components/tool-bubble.ts +1 -0
  132. package/src/history-shell-bundle.test.ts +54 -0
  133. package/src/history-shell-eager.ts +12 -0
  134. package/src/history-shell-loader.ts +27 -0
  135. package/src/history-shell.ts +2362 -0
  136. package/src/history-view-loader.ts +2 -0
  137. package/src/history-view.ts +3 -0
  138. package/src/index-core.ts +8 -0
  139. package/src/index-global.ts +90 -248
  140. package/src/index.ts +13 -0
  141. package/src/install.ts +6 -4
  142. package/src/internal/runtype-history-provider.test.ts +1 -0
  143. package/src/internal/runtype-history-provider.ts +28 -13
  144. package/src/plugins/registry.ts +8 -8
  145. package/src/session-actions-chunk.test.ts +55 -0
  146. package/src/session-actions-eager.ts +11 -0
  147. package/src/session-actions-loader.ts +37 -0
  148. package/src/session-actions.ts +909 -0
  149. package/src/session-history.test.ts +3 -1
  150. package/src/session.ts +875 -1530
  151. package/src/session.voice.test.ts +1241 -5
  152. package/src/styles/widget.css +58 -0
  153. package/src/theme-editor/state.ts +91 -91
  154. package/src/types.ts +269 -5
  155. package/src/ui-ask-user-sheet.ts +382 -0
  156. package/src/ui-extras-eager.ts +10 -0
  157. package/src/ui-extras-entry.ts +9 -0
  158. package/src/ui-extras-loader.ts +26 -0
  159. package/src/ui.artifact-rail-resize.test.ts +2 -1
  160. package/src/ui.ask-user-chunk.test.ts +93 -0
  161. package/src/ui.history-chunk.test.ts +2 -1
  162. package/src/ui.history-config-provider.test.ts +2 -1
  163. package/src/ui.history-confirm-fallback.test.ts +142 -0
  164. package/src/ui.history-controller.test.ts +2 -1
  165. package/src/ui.history-lifecycle.test.ts +2 -1
  166. package/src/ui.history-render-hooks.test.ts +2 -1
  167. package/src/ui.history-shell.test.ts +2 -1
  168. package/src/ui.rail-overlay.test.ts +2 -1
  169. package/src/ui.rail-resize.test.ts +2 -1
  170. package/src/ui.rail-trigger-pending.test.ts +2 -1
  171. package/src/ui.ts +399 -2770
  172. package/src/ui.voice-prewarm.test.ts +222 -0
  173. package/src/utils/attachment-manager.ts +67 -67
  174. package/src/utils/constants.ts +3 -0
  175. package/src/utils/context-mention-controller.ts +323 -323
  176. package/src/utils/context-mention-manager.ts +40 -40
  177. package/src/utils/context-mention-orchestrator.ts +28 -0
  178. package/src/utils/event-stream-buffer.ts +50 -50
  179. package/src/utils/event-stream-store.ts +43 -43
  180. package/src/utils/throughput-tracker.ts +34 -34
  181. package/src/utils/virtual-scroller.ts +67 -67
  182. package/src/utils/visitor-store.test.ts +50 -0
  183. package/src/utils/visitor-store.ts +23 -5
  184. package/src/voice/__fixtures__/voice-wire/README.md +1 -0
  185. package/src/voice/__fixtures__/voice-wire/client/cancel.json +3 -0
  186. package/src/voice/__fixtures__/voice-wire/client/context.json +4 -0
  187. package/src/voice/__fixtures__/voice-wire/client/delegation_result.json +6 -0
  188. package/src/voice/__fixtures__/voice-wire/client/delegation_update.json +6 -0
  189. package/src/voice/__fixtures__/voice-wire/client/ping.json +3 -0
  190. package/src/voice/__fixtures__/voice-wire/client/playback_progress.json +5 -0
  191. package/src/voice/__fixtures__/voice-wire/client/start.json +3 -0
  192. package/src/voice/__fixtures__/voice-wire/server/artifact.json +11 -0
  193. package/src/voice/__fixtures__/voice-wire/server/attached.json +4 -0
  194. package/src/voice/__fixtures__/voice-wire/server/audio_clear.json +4 -0
  195. package/src/voice/__fixtures__/voice-wire/server/audio_end.json +3 -0
  196. package/src/voice/__fixtures__/voice-wire/server/delegation_cancelled.json +5 -0
  197. package/src/voice/__fixtures__/voice-wire/server/delegation_completed.json +8 -0
  198. package/src/voice/__fixtures__/voice-wire/server/delegation_started.json +15 -0
  199. package/src/voice/__fixtures__/voice-wire/server/error.json +6 -0
  200. package/src/voice/__fixtures__/voice-wire/server/metrics.json +10 -0
  201. package/src/voice/__fixtures__/voice-wire/server/pong.json +3 -0
  202. package/src/voice/__fixtures__/voice-wire/server/session_config.json +16 -0
  203. package/src/voice/__fixtures__/voice-wire/server/transcript_final.json +7 -0
  204. package/src/voice/__fixtures__/voice-wire/server/transcript_interim.json +4 -0
  205. package/src/voice/__fixtures__/voice-wire/server/transcript_partial.json +6 -0
  206. package/src/voice/__fixtures__/voice-wire/server/transcript_update.json +10 -0
  207. package/src/voice/__fixtures__/voice-wire/server/warning.json +5 -0
  208. package/src/voice/audio-playback-manager.test.ts +57 -0
  209. package/src/voice/audio-playback-manager.ts +120 -98
  210. package/src/voice/browser-voice-provider.ts +37 -37
  211. package/src/voice/fallback-speech-engine.ts +22 -16
  212. package/src/voice/keyed-voice-transcript.ts +314 -0
  213. package/src/voice/mic-state-styles.ts +182 -0
  214. package/src/voice/read-aloud-controller.ts +46 -44
  215. package/src/voice/runtype-speech-engine.ts +35 -33
  216. package/src/voice/runtype-voice-provider.ts +856 -164
  217. package/src/voice/session-voice-wiring.ts +266 -0
  218. package/src/voice/voice-delegation.test.ts +71 -0
  219. package/src/voice/voice-delegation.ts +364 -0
  220. package/src/voice/voice-turn-tracker.ts +6 -6
  221. package/src/voice/voice.test.ts +1250 -7
  222. package/src/voice/worklet-playback-engine.test.ts +81 -0
  223. package/src/voice/worklet-playback-engine.ts +21 -3
  224. package/src/voice-runtime-loader.ts +4 -1
  225. package/src/voice-runtime.ts +7 -0
  226. package/src/webmcp-runtime-entry.ts +41 -39
  227. package/dist/approval-ui-3NMYNXBD.js +0 -1
  228. package/dist/chunk-5EIIHQLQ.js +0 -1
  229. package/dist/chunk-7CO4T5KB.js +0 -1
  230. package/dist/chunk-EFJBUH5F.js +0 -1
  231. package/dist/chunk-R2TMIMDI.js +0 -3
  232. package/dist/chunk-UTVLOTWB.js +0 -9
  233. package/dist/context-mentions-45MODWOY.js +0 -161
  234. package/dist/event-stream-view-GL3ADRY2.js +0 -1
  235. package/dist/runtype-tts-entry-UJAEF7NZ.js +0 -1
  236. package/dist/voice-runtime-EFR3R5ES.js +0 -1
  237. package/dist/webmcp-runtime-JI7T4QYF.js +0 -6
@@ -6846,6 +6846,22 @@ type AgentWidgetStatusIndicatorConfig = {
6846
6846
  /** Status text while a reconnect attempt is in flight. */
6847
6847
  resumingText?: string;
6848
6848
  };
6849
+ /** Built-in `voiceRecognition.prewarm` triggers. See {@link AgentWidgetVoiceRecognitionConfig.prewarm}. */
6850
+ type AgentWidgetVoicePrewarmTrigger = 'hover';
6851
+ /**
6852
+ * Custom `voiceRecognition.prewarm` trigger. Runs while the composer has a mic
6853
+ * button, and again when the button is rebuilt or `update()` swaps in a
6854
+ * different function. Call `warm()` whenever the visitor shows intent to talk
6855
+ * (it is safe to call repeatedly). Return a cleanup to run on replacement.
6856
+ */
6857
+ type AgentWidgetVoicePrewarmHook = (context: {
6858
+ /** Fire-and-forget voice warm-up; latched and error-swallowing. */
6859
+ warm: () => void;
6860
+ /** The composer's current mic button. */
6861
+ micButton: HTMLButtonElement;
6862
+ /** The widget's mount element. */
6863
+ mount: HTMLElement;
6864
+ }) => void | (() => void);
6849
6865
  type AgentWidgetVoiceRecognitionConfig = {
6850
6866
  /**
6851
6867
  * Enable the mic button and voice input. The mic still only renders when the
@@ -6911,6 +6927,29 @@ type AgentWidgetVoiceRecognitionConfig = {
6911
6927
  * Fires once per turn after the reply completes.
6912
6928
  */
6913
6929
  onMetrics?: (metrics: VoiceMetrics) => void;
6930
+ /**
6931
+ * Warm the voice path when the visitor shows intent to talk, before the mic
6932
+ * click, so the call starts faster.
6933
+ *
6934
+ * - `'hover'`: when the pointer enters the mic button, it receives focus, or
6935
+ * (on touch) the first pointer-down on it.
6936
+ * - `false`: never.
6937
+ * - A function: custom trigger. Called with `{ warm, micButton, mount }`
6938
+ * while the mic button exists (and again when the button is rebuilt or
6939
+ * `update()` swaps in a different function); call `warm()` whenever you
6940
+ * decide, e.g. when the panel opens. May return a cleanup that runs on
6941
+ * destroy, rebuild, or replacement. Replaces the built-in trigger.
6942
+ *
6943
+ * What `warm()` does depends on the provider: `runtype` fires its prewarm
6944
+ * (see `provider.runtype.prewarmMode`), a `custom` provider's optional
6945
+ * {@link VoiceProvider.prewarm} runs, and the browser (Web Speech) path
6946
+ * starts the client-token session init (as `sessionInit` does), since speech
6947
+ * recognition itself cannot start before the click. Warming is
6948
+ * fire-and-forget, latched, and never surfaces an error or UI state.
6949
+ *
6950
+ * @default 'hover' in client token mode, otherwise `false`
6951
+ */
6952
+ prewarm?: AgentWidgetVoicePrewarmTrigger | AgentWidgetVoicePrewarmHook | false;
6914
6953
  provider?: {
6915
6954
  type: 'browser' | 'runtype' | 'custom';
6916
6955
  browser?: {
@@ -6932,6 +6971,62 @@ type AgentWidgetVoiceRecognitionConfig = {
6932
6971
  * `@runtypelabs/persona/voice-worklet-player` for a jitter-buffered engine.
6933
6972
  */
6934
6973
  createPlaybackEngine?: () => VoicePlaybackEngine | Promise<VoicePlaybackEngine>;
6974
+ /**
6975
+ * How `prewarm()` warms the voice path (see `voiceRecognition.prewarm`).
6976
+ *
6977
+ * - `'request'` (default): a fire-and-forget
6978
+ * `POST {host}/v1/client/agents/{agentId}/voice/prewarm`.
6979
+ * - `'attach'`: open the voice WebSocket ahead of the click without
6980
+ * starting a call; the click then starts the call on that socket. It can
6981
+ * create server work before the visitor clicks, so it is opt-in.
6982
+ * @default 'request'
6983
+ */
6984
+ prewarmMode?: 'request' | 'attach';
6985
+ /**
6986
+ * `'attach'` mode: how long (ms) an attached socket waits for the click
6987
+ * before it closes. The server clamps it to 30000..600000.
6988
+ * @default 30000
6989
+ */
6990
+ attachIdleMs?: number;
6991
+ /**
6992
+ * Full-duplex (speech-to-speech, e.g. GPT-Live) calls: run the turns the
6993
+ * voice model hands off to the agent through this widget's normal chat
6994
+ * pipeline. The spoken request becomes the user message, and the answer
6995
+ * renders as a regular assistant message (streaming, tool and approval
6996
+ * UI, WebMCP page tools, persistence) that the voice model then reads
6997
+ * aloud. Only takes effect when the server supports it (it confirms in
6998
+ * `session_config`); otherwise the agent turn runs on the server and its
6999
+ * spoken reply is transcribed, as before. Set `false` to always keep the
7000
+ * agent turn on the server.
7001
+ * @default true
7002
+ */
7003
+ clientDelegation?: boolean;
7004
+ /**
7005
+ * Full-duplex calls: extra context for the voice model (for example the
7006
+ * page the visitor is on), sent after the chat history as of call start.
7007
+ * The frame goes out once, when the visitor finishes their first
7008
+ * utterance (or at the first agent hand-off). A function is
7009
+ * called at call start and may be async. This text is capped at 4000 characters and the whole frame
7010
+ * (history included) at 8000. Sent only to servers that accept call
7011
+ * context (they announce it in `session_config`).
7012
+ */
7013
+ callContext?: string | (() => string | Promise<string>);
7014
+ /**
7015
+ * Full-duplex calls with client delegation: how long a tool approval
7016
+ * that a spoken request raised may wait before it is declined as
7017
+ * expired (and the voice model says so). Server-side approval gates
7018
+ * keep their own timeout too. Hanging up never declines it: the
7019
+ * approval card in the chat stays usable. Capped at 540000 (9 minutes),
7020
+ * under the server's 10-minute delegation deadline.
7021
+ * @default 300000
7022
+ */
7023
+ approvalTimeoutMs?: number;
7024
+ /**
7025
+ * Speech-to-speech calls: the one-line notice shown in the composer
7026
+ * status area when the call starts. `false` hides it.
7027
+ * @default "You're talking to an AI assistant. Voice is processed by OpenAI."
7028
+ */
7029
+ disclosureText?: string | false;
6935
7030
  /** @deprecated No-op on the realtime path: the server's STT owns turn-taking. */
6936
7031
  pauseDuration?: number;
6937
7032
  /** @deprecated No-op on the realtime path: the server's STT owns turn-taking. */
@@ -7161,6 +7256,13 @@ interface VoicePlaybackEngine {
7161
7256
  onFinished(callback: () => void): void;
7162
7257
  /** Release all audio resources. */
7163
7258
  destroy(): Promise<void> | void;
7259
+ /**
7260
+ * Optional. Speech-to-speech calls stream reply audio with no end-of-stream
7261
+ * marker, so an engine that holds audio below a prebuffer waterline must, while
7262
+ * continuous, release that held tail on its own (e.g. after a short input gap)
7263
+ * instead of waiting for {@link markStreamEnd}. Engines without a prebuffer can omit it.
7264
+ */
7265
+ setContinuousMode?(enabled: boolean): void;
7164
7266
  }
7165
7267
  /**
7166
7268
  * A {@link VoicePlaybackEngine} that also supports pause/resume. Returned by
@@ -7204,14 +7306,23 @@ interface VoiceProvider {
7204
7306
  * Register a callback for incremental transcript updates during a voice turn.
7205
7307
  * `isFinal=false` is a live interim update (user partials, or assistant deltas
7206
7308
  * on providers that stream them); `isFinal=true` finalizes that role's text.
7207
- * On the realtime `runtype` path, interim updates fire for the `user` only and
7208
- * the `assistant` arrives as a single final. Providers with overlapping turns
7209
- * must include the same turnId on user and assistant finals; without IDs,
7210
- * providers must discard cancelled output before emitting the next user final.
7211
- */
7212
- onTranscript?(callback: (role: 'user' | 'assistant', text: string, isFinal: boolean, metadata?: {
7213
- turnId?: string;
7214
- }) => void): void;
7309
+ * On the classic realtime `runtype` path, interim updates fire for the `user`
7310
+ * only and the `assistant` arrives as a single final; without a turnId the
7311
+ * session assumes strictly alternating turns, and providers must discard
7312
+ * cancelled output before emitting the next user final.
7313
+ *
7314
+ * When `metadata.turnId` is present (full-duplex / speech-to-speech, e.g.
7315
+ * GPT-Live), the session reconciles by `(turnId, role)`: each pair owns one
7316
+ * bubble that later updates replace in place, turns may overlap or arrive in
7317
+ * any order, and no empty assistant placeholder is injected. User and
7318
+ * assistant may share a turnId (a late user bubble then renders above its
7319
+ * reply) or use distinct ones. `metadata.startMs` (call-relative ms when the
7320
+ * utterance began) orders a new bubble among the call's other keyed bubbles;
7321
+ * without it bubbles order by first arrival. After a stop, keyed providers
7322
+ * must drop the cancelled reply's output until the server acknowledges the
7323
+ * cancel: the session renders every reply it receives.
7324
+ */
7325
+ onTranscript?(callback: (role: 'user' | 'assistant', text: string, isFinal: boolean, metadata?: VoiceTranscriptMetadata) => void): void;
7215
7326
  /** Register a callback for per-turn latency metrics (realtime path). */
7216
7327
  onMetrics?(callback: (metrics: VoiceMetrics) => void): void;
7217
7328
  /**
@@ -7232,6 +7343,116 @@ interface VoiceProvider {
7232
7343
  deactivateBargeIn?(): Promise<void>;
7233
7344
  /** Stop playback / cancel in-flight request without starting recording */
7234
7345
  stopPlayback?(): void;
7346
+ /**
7347
+ * Warm the provider ahead of `startListening()` (the widget calls it on mic
7348
+ * intent, see `voiceRecognition.prewarm`). Must be fire-and-forget: never
7349
+ * throw, emit errors or status, or acquire the microphone. May be called
7350
+ * repeatedly; throttle as needed.
7351
+ */
7352
+ prewarm?(): void;
7353
+ /**
7354
+ * Called by the session once after construction with the chat-side surface
7355
+ * a full-duplex provider uses to hand agent turns to the chat pipeline
7356
+ * ({@link VoiceSessionBridge}). Providers without client delegation omit it.
7357
+ */
7358
+ setSessionBridge?(bridge: VoiceSessionBridge): void;
7359
+ /** The AI-disclosure notice for the live call, if one should show (speech-to-speech). */
7360
+ getDisclosure?(): string | null;
7361
+ }
7362
+ /** Metadata on a {@link VoiceProvider.onTranscript} update. */
7363
+ type VoiceTranscriptMetadata = {
7364
+ /** Groups updates that belong to one utterance bubble (full duplex). */
7365
+ turnId?: string;
7366
+ /** Call-relative ms when the utterance began; orders late bubbles. */
7367
+ startMs?: number;
7368
+ /** Call-relative ms of the latest audio this update covers. */
7369
+ endMs?: number;
7370
+ /**
7371
+ * The bubble only captions speech (see `AgentWidgetMessage.voiceCaption`).
7372
+ * The chat pipeline owns the conversation, as with client delegation.
7373
+ */
7374
+ caption?: boolean;
7375
+ };
7376
+ /** An agent turn a full-duplex voice model handed to the widget. */
7377
+ type VoiceDelegationRequest = {
7378
+ /** The voice model's delegation id (`delegation_started.delegationId`). */
7379
+ delegationId: string;
7380
+ /** What the visitor asked, as the voice model heard it. */
7381
+ userText: string;
7382
+ /**
7383
+ * The user transcript utterances `userText` joins, oldest first (the last
7384
+ * is the one it came from). May be empty.
7385
+ */
7386
+ userUtteranceIds: string[];
7387
+ /** The voice model's view of the conversation it delegated from. */
7388
+ messages: Array<{
7389
+ role: string;
7390
+ content: unknown;
7391
+ }>;
7392
+ };
7393
+ /**
7394
+ * How a delegated turn ended, or that it waits on an approval (contract
7395
+ * Amendment 5). `pending_approval` is the only non-terminal status. Open:
7396
+ * a receiver treats an unknown terminal status as `failed`.
7397
+ * - `completed`: the work ran.
7398
+ * - `denied`: the visitor said no (Deny tap, or a spoken decline).
7399
+ * - `timeout`: the approval lapsed (`approvalTimeoutMs`, or the server's own timeout).
7400
+ * - `cancelled`: replaced by a newer request, or abandoned by the system.
7401
+ * - `failed`: an error.
7402
+ */
7403
+ type VoiceDelegationStatus = 'completed' | 'pending_approval' | 'denied' | 'timeout' | 'cancelled' | 'failed' | (string & {});
7404
+ /** The terminal result of a turn that parked on approvals. */
7405
+ type VoiceDelegationFollowUp = {
7406
+ status: VoiceDelegationStatus;
7407
+ /** What to read aloud (Markdown allowed). May be empty: nothing more to say. */
7408
+ text: string;
7409
+ };
7410
+ /** The delegated turn's answer, sent back for the voice model to read aloud. */
7411
+ type VoiceDelegationResult = {
7412
+ /** `pending_approval` when `followUp` is set; otherwise terminal. */
7413
+ status: VoiceDelegationStatus;
7414
+ /** The assistant text (Markdown allowed). */
7415
+ text: string;
7416
+ /**
7417
+ * Set when the turn parked on approvals (`text` then asks for the decision).
7418
+ * Resolves with the terminal result once the visitor decides (or the
7419
+ * approval is replaced, declined by voice, or unanswered for
7420
+ * `approvalTimeoutMs`) and the resumed turn finishes; `null` only when
7421
+ * `signal` aborts first (hang-up, or the server cancelled the delegation).
7422
+ */
7423
+ followUp?: (options: {
7424
+ signal: AbortSignal;
7425
+ approvalTimeoutMs?: number;
7426
+ /** `false`: run only the approval bookkeeping (expiry, supersede); nothing will be read back. @default true */
7427
+ readBack?: boolean;
7428
+ /** The resumed turn stopped on another approval: ask for it too (`text` is its approval script). */
7429
+ onUpdate?: (text: string) => void;
7430
+ }) => Promise<VoiceDelegationFollowUp | null>;
7431
+ };
7432
+ /**
7433
+ * Chat-side surface the session hands a full-duplex provider: the visible
7434
+ * history (for the call-start context) and a way to run a delegated turn
7435
+ * through the normal chat pipeline.
7436
+ */
7437
+ interface VoiceSessionBridge {
7438
+ /** Visible user/assistant messages, oldest first. */
7439
+ getHistory(): Array<{
7440
+ role: 'user' | 'assistant';
7441
+ content: string;
7442
+ }>;
7443
+ /**
7444
+ * Submit the turn as the visitor's message (reusing its transcript bubble)
7445
+ * and resolve with the assistant's final answer once the turn settles.
7446
+ * Waits for any chat turn already in flight first. Never rejects.
7447
+ */
7448
+ runDelegatedTurn(request: VoiceDelegationRequest): Promise<VoiceDelegationResult>;
7449
+ /**
7450
+ * The server dropped this delegation's result (cancelled it, or refused a
7451
+ * late result): its chat answer is no longer spoken, so browser TTS may read it.
7452
+ * `expired`: the server's deadline passed, so its pending approvals are
7453
+ * declined too, as the approval TTL would.
7454
+ */
7455
+ dropDelegation?(delegationId: string, expired?: boolean): void;
7235
7456
  }
7236
7457
  /**
7237
7458
  * Extra context for an approval decision, surfaced to `onDecision` and to the
@@ -9828,6 +10049,11 @@ type AgentWidgetToolCall = {
9828
10049
  startedAt?: number;
9829
10050
  completedAt?: number;
9830
10051
  durationMs?: number;
10052
+ /**
10053
+ * The call paused for an approval that was granted, and the agent re-ran it
10054
+ * as a new tool call: that later call carries the result, this one has none.
10055
+ */
10056
+ superseded?: boolean;
9831
10057
  };
9832
10058
  /**
9833
10059
  * Represents a tool approval request in the chat conversation.
@@ -9849,6 +10075,8 @@ type AgentWidgetApproval = {
9849
10075
  */
9850
10076
  reason?: string;
9851
10077
  parameters?: unknown;
10078
+ /** The paused tool call this approval gates (`approval_start.toolCallId`). */
10079
+ toolCallId?: string;
9852
10080
  resolvedAt?: number;
9853
10081
  };
9854
10082
  type AgentWidgetMessageVariant = "assistant" | "reasoning" | "tool" | "approval";
@@ -9948,6 +10176,13 @@ type AgentWidgetMessage = {
9948
10176
  * }
9949
10177
  */
9950
10178
  voiceProcessing?: boolean;
10179
+ /**
10180
+ * Display-only caption of full-duplex voice speech, such as the voice
10181
+ * model's own words, or something the visitor said that wasn't submitted
10182
+ * as a chat turn. It renders in the transcript but is never sent to the
10183
+ * model as conversation.
10184
+ */
10185
+ voiceCaption?: boolean;
9951
10186
  /**
9952
10187
  * Raw structured payload for this message (e.g., JSON action response).
9953
10188
  * Populated automatically when structured parsers run.
@@ -1,16 +1,16 @@
1
- var Q=Object.defineProperty;var J=(o,e,t)=>e in o?Q(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var w=(o,e,t)=>J(o,typeof e!="symbol"?e+"":e,t);var I=Object.defineProperty,Z=Object.getOwnPropertyDescriptor,tt=Object.getOwnPropertyNames,W=Object.prototype.hasOwnProperty,C=(o,e)=>()=>(o&&(e=o(o=0)),e),et=(o,e)=>{let t={};for(var n in o)I(t,n,{get:o[n],enumerable:!0});return e||I(t,Symbol.toStringTag,{value:"Module"}),t},nt=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(var r=tt(e),i=0,s=r.length,a;i<s;i++)a=r[i],!W.call(o,a)&&a!==t&&I(o,a,{get:(c=>e[c]).bind(null,a),enumerable:!(n=Z(e,a))||n.enumerable});return o},rt=o=>W.call(o,"module.exports")?o["module.exports"]:nt(I({},"__esModule",{value:!0}),o),ot=void 0,T,H=C((()=>{T=class y{static findMainContent(e){let t=e.querySelector('main, [role="main"]');return t||(e.body?y.detectMainContent(e.body):e.documentElement)}static detectMainContent(e){let t=[];if(y.collectCandidates(e,t,15),t.length===0)return e;t.sort((r,i)=>y.calculateContentScore(i)-y.calculateContentScore(r));let n=t[0];for(let r=1;r<t.length;r++){let i=t[r];!t.some((s,a)=>a!==r&&s.contains(i))&&y.calculateContentScore(i)>y.calculateContentScore(n)&&(n=i)}return n}static collectCandidates(e,t,n){y.calculateContentScore(e)>=n&&t.push(e),Array.from(e.children).forEach(r=>{y.collectCandidates(r,t,n)})}static calculateContentScore(e){let t=0,n=["article","content","main-container","main","main-content","post","entry"],r=["content","main","article","post","entry"];n.forEach(u=>{e.classList.contains(u)&&(t+=10)}),r.forEach(u=>{e.id?.toLowerCase().includes(u)&&(t+=10)});let i=e.tagName.toLowerCase();["article","main","section"].includes(i)&&(t+=8);let s=e.getElementsByTagName("p").length;t+=Math.min(s*2,10);let a=e.querySelectorAll("h1, h2, h3").length;t+=Math.min(a*3,9);let c=e.textContent?.trim().length||0;c>300&&(t+=Math.min(Math.floor(c/300)*2,10));let l=y.calculateLinkDensity(e);l<.3?t+=5:l>.5&&(t-=5),(e.hasAttribute("data-main")||e.hasAttribute("data-content")||e.hasAttribute("itemprop"))&&(t+=8);let d=e.getAttribute("role");return(d==="main"||d==="article")&&(t+=10),e.matches("aside, nav, header, footer, .sidebar, .navigation, .menu, .ad, .advertisement")&&(t-=10),e.getElementsByTagName("form").length>2&&(t-=5),Math.max(0,t)}static calculateLinkDensity(e){let t=e.getElementsByTagName("a"),n=0;for(let i of Array.from(t))n+=i.textContent?.length||0;let r=e.textContent?.length||1;return n/r}static isNavigation(e){if(e.tagName.toLowerCase()==="nav"||e.getAttribute("role")==="navigation")return!0;let t=[/nav/i,/menu/i,/sidebar/i,/toolbar/i],n=`${e.className} ${e.id}`.toLowerCase();return t.some(r=>r.test(n))}static isSupplementary(e){if(e.tagName.toLowerCase()==="aside"||e.getAttribute("role")==="complementary")return!0;let t=[/sidebar/i,/widget/i,/related/i,/advertisement/i,/social/i],n=`${e.className} ${e.id}`.toLowerCase();return t.some(r=>r.test(n))}static detectLandmarks(e){let t={navigation:[],main:[],complementary:[],contentinfo:[],banner:[],search:[],form:[],region:[]};for(let[n,r]of Object.entries({navigation:'nav, [role="navigation"]',main:'main, [role="main"]',complementary:'aside, [role="complementary"]',contentinfo:'footer, [role="contentinfo"]',banner:'header, [role="banner"]',search:'[role="search"]',form:'form[aria-label], form[aria-labelledby], [role="form"]',region:'section[aria-label], section[aria-labelledby], [role="region"]'})){let i=e.querySelectorAll(r);t[n]=Array.from(i)}return t}}})),b,D=C((()=>{b=class x{static generateSelectors(e){let t=e.ownerDocument||document,n=[];e.id&&x.isUniqueId(e.id,t)&&n.push({type:"id",value:`#${CSS.escape(e.id)}`,score:100});let r=x.getDataTestId(e);if(r){let h=`[data-testid="${CSS.escape(r)}"]`;n.push({type:"data-testid",value:h,score:90+(x.isUniqueSelectorSafe(h,t)?5:0)})}let i=e.getAttribute("role"),s=e.getAttribute("aria-label");if(i&&s){let h=`[role="${CSS.escape(i)}"][aria-label="${CSS.escape(s)}"]`;n.push({type:"role-aria",value:h,score:85+(x.isUniqueSelectorSafe(h,t)?5:0)})}let a=e.getAttribute("name");if(a){let h=`[name="${CSS.escape(a)}"]`;n.push({type:"name",value:h,score:78+(x.isUniqueSelectorSafe(h,t)?5:0)})}let c=x.generateCSSSelector(e,t),l=(c.match(/:nth-child\(/g)||[]).length*10,d=c.includes(".")?8:0,u=Math.max(0,70+d-l);n.push({type:"class-path",value:c,score:u});let m=x.generateXPath(e,t);n.push({type:"xpath",value:m,score:40});let f=x.generateTextBasedSelector(e);f&&n.push({type:"text",value:f,score:30}),n.sort((h,L)=>L.score-h.score);let S={css:n.find(h=>h.type!=="xpath"&&h.type!=="text")?.value||c,xpath:m,candidates:n};return f&&(S.textBased=f),r&&(S.dataTestId=r),s&&(S.ariaLabel=s),S}static generateCSSSelector(e,t){if(e.id&&x.isUniqueId(e.id,t))return`#${CSS.escape(e.id)}`;let n=x.getDataTestId(e);if(n)return`[data-testid="${CSS.escape(n)}"]`;let r=[],i=e;for(;i&&i.nodeType===Node.ELEMENT_NODE;){let s=i.nodeName.toLowerCase();if(i.id&&x.isUniqueId(i.id,t)){s=`#${CSS.escape(i.id)}`,r.unshift(s);break}let a=x.getMeaningfulClasses(i);a.length>0&&(s+=`.${a.map(l=>CSS.escape(l)).join(".")}`);let c=i.parentElement?.children;if(c&&c.length>1){let l=Array.from(c).indexOf(i);(l>0||!x.isUniqueSelector(s,i.parentElement))&&(s+=`:nth-child(${l+1})`)}r.unshift(s),i=i.parentElement}return x.optimizePath(r,e,t)}static generateXPath(e,t){if(e.id&&x.isUniqueId(e.id,t))return`//*[@id="${e.id}"]`;let n=[],r=e;for(;r&&r.nodeType===Node.ELEMENT_NODE;){let i=r.nodeName.toLowerCase();if(r.id&&x.isUniqueId(r.id,t)){n.unshift(`//*[@id="${r.id}"]`);break}let s=i,a=r.parentElement?.children;if(a){let c=Array.from(a).filter(l=>l.nodeName.toLowerCase()===i);if(c.length>1){let l=c.indexOf(r)+1;s+=`[${l}]`}}n.unshift(s),r=r.parentElement}return`//${n.join("/")}`}static generateTextBasedSelector(e){let t=e.textContent?.trim();if(!t||t.length>50)return;let n=e.nodeName.toLowerCase();if(["button","a","label"].includes(n))return`${n}:contains("${t.replace(/['"\\]/g,"\\$&")}")`}static getDataTestId(e){return e.getAttribute("data-testid")||e.getAttribute("data-test-id")||e.getAttribute("data-test")||e.getAttribute("data-cy")||void 0}static isUniqueId(e,t){return t.querySelectorAll(`#${CSS.escape(e)}`).length===1}static isUniqueSelector(e,t){try{return t.querySelectorAll(e).length===1}catch{return!1}}static isUniqueSelectorSafe(e,t){try{return t.querySelectorAll(e).length===1}catch{return!1}}static getMeaningfulClasses(e){let t=Array.from(e.classList),n=[/^(p|m|w|h|text|bg|border|flex|grid|col|row)-/,/^(xs|sm|md|lg|xl|2xl):/,/^(hover|focus|active|disabled|checked):/,/^js-/,/^is-/,/^has-/];return t.filter(r=>r.length<3?!1:!n.some(i=>i.test(r))).slice(0,2)}static optimizePath(e,t,n){for(let r=0;r<e.length-1;r++){let i=e.slice(r).join(" > ");try{let s=n.querySelectorAll(i);if(s.length===1&&s[0]===t)return i}catch{}}return e.join(" > ")}static getContextPath(e){let t=[],n=e,r=0,i=5;for(;n&&n!==e.ownerDocument?.body&&r<i;){let s=n.nodeName.toLowerCase(),a=s;if(n.id)a=`${s}#${n.id}`;else if(n.className&&typeof n.className=="string"){let l=n.className.split(" ")[0];l&&(a=`${s}.${l}`)}let c=n.getAttribute("role");c&&(a+=`[role="${c}"]`),t.unshift(a),n=n.parentElement,r++}return t}}})),g,j=C((()=>{var o;D(),g=(o=class{static isVisible(t,n){let r=t.getBoundingClientRect(),i=n||t.ownerDocument?.defaultView?.getComputedStyle(t);return i?r.width>0&&r.height>0&&i.display!=="none"&&i.visibility!=="hidden"&&i.opacity!=="0"&&t.offsetParent!==null:!1}static isInViewport(t,n){let r=t.getBoundingClientRect(),i=n||{width:t.ownerDocument?.defaultView?.innerWidth||0,height:t.ownerDocument?.defaultView?.innerHeight||0};return r.top<i.height&&r.bottom>0&&r.left<i.width&&r.right>0}static passesFilter(t,n){if(!n)return!0;let r=t;if(n.excludeSelectors?.length){for(let s of n.excludeSelectors)if(t.matches(s))return!1}if(n.includeSelectors?.length){let s=!1;for(let a of n.includeSelectors)if(t.matches(a)){s=!0;break}if(!s)return!1}if(n.tags?.length&&!n.tags.includes(t.tagName.toLowerCase()))return!1;let i=r.textContent?.toLowerCase()||"";if(n.textContains?.length){let s=!1;for(let a of n.textContains)if(i.includes(a.toLowerCase())){s=!0;break}if(!s)return!1}if(n.textMatches?.length){let s=!1;for(let a of n.textMatches)if(a.test(i)){s=!0;break}if(!s)return!1}if(n.hasAttributes?.length){for(let s of n.hasAttributes)if(!t.hasAttribute(s))return!1}if(n.attributeValues)for(let[s,a]of Object.entries(n.attributeValues)){let c=t.getAttribute(s);if(!c)return!1;if(typeof a=="string"){if(c!==a)return!1}else if(a instanceof RegExp&&!a.test(c))return!1}if(n.withinSelectors?.length){let s=!1;for(let a of n.withinSelectors)if(t.closest(a)){s=!0;break}if(!s)return!1}if(n.interactionTypes?.length){let s=o.getInteractionInfo(t),a=!1;for(let c of n.interactionTypes)if(s[c]){a=!0;break}if(!a)return!1}if(n.nearText){let s=t.parentElement;if(!s||!s.textContent?.toLowerCase().includes(n.nearText.toLowerCase()))return!1}return!0}static extractElement(t,n,r=0){if(n.maxDepth&&r>n.maxDepth||!n.includeHidden&&!o.isVisible(t)||n.viewportOnly&&!o.isInViewport(t)||!o.passesFilter(t,n.filter))return null;let i=t,s={tag:t.tagName.toLowerCase(),text:o.getElementText(t,n),selector:b.generateSelectors(t),attributes:o.getRelevantAttributes(t,n),context:o.getElementContext(t),interaction:o.getInteractionInfo(t)};if(n.mode==="full"&&o.isSemanticContainer(t)){let a=[];if(n.includeShadowDOM&&i.shadowRoot){let l=o.extractChildren(i.shadowRoot,n,r+1);a.push(...l)}let c=o.extractChildren(t,n,r+1);a.push(...c),a.length>0&&(s.children=a)}return s}static extractChildren(t,n,r){let i=[],s=t.querySelectorAll("*");for(let a of Array.from(s)){if(o.hasExtractedAncestor(a,s))continue;let c=o.extractElement(a,n,r);c&&i.push(c)}return i}static hasExtractedAncestor(t,n){let r=t.parentElement;for(;r;){if(Array.from(n).includes(r))return!0;r=r.parentElement}return!1}static getRelevantAttributes(t,n){let r=["id","class","name","type","value","placeholder","href","src","alt","title","action","method","aria-label","aria-describedby","aria-controls","role","disabled","readonly","required","checked","min","max","pattern","step","autocomplete","data-testid","data-test","data-cy"],i={},s=n.attributeTruncateLength??100,a=n.dataAttributeTruncateLength??50;for(let c of r){let l=t.getAttribute(c);l&&(i[c]=l.length>s?`${l.substring(0,s)}...`:l)}for(let c of t.attributes)c.name.startsWith("data-")&&!r.includes(c.name)&&(i[c.name]=c.value.length>a?`${c.value.substring(0,a)}...`:c.value);return i}static getElementContext(t){let n={parentChain:b.getContextPath(t)},r=t.closest("form");r&&(n.nearestForm=b.generateSelectors(r).css);let i=t.closest('section, [role="region"]');i&&(n.nearestSection=b.generateSelectors(i).css);let s=t.closest('main, [role="main"]');s&&(n.nearestMain=b.generateSelectors(s).css);let a=t.closest('nav, [role="navigation"]');return a&&(n.nearestNav=b.generateSelectors(a).css),n}static getInteractionInfo(t){let n=t,r={};(n.onclick||t.getAttribute("onclick")||t.matches('button, a[href], [role="button"], [tabindex]:not([tabindex="-1"])'))&&(r.click=!0),(n.onchange||t.getAttribute("onchange")||t.matches("input, select, textarea"))&&(r.change=!0),(n.onsubmit||t.getAttribute("onsubmit")||t.matches("form"))&&(r.submit=!0),t.matches('a[href], button[type="submit"]')&&(r.nav=!0),(n.hasAttribute("disabled")||n.getAttribute("aria-disabled")==="true")&&(r.disabled=!0),o.isVisible(t)||(r.hidden=!0);let i=t.getAttribute("role");if(i&&(r.role=i),t.matches("input, textarea, select, button")){let s=t.form||t.closest("form");s&&(r.form=b.generateSelectors(s).css)}return r}static getElementText(t,n){if(t.matches("input, textarea")){let s=t;return s.value||s.placeholder||""}if(t.matches("img"))return t.alt||"";let r=t.textContent?.trim()||"",i=n?.textTruncateLength;return i&&r.length>i?`${r.substring(0,i)}...`:r}static isSemanticContainer(t){return t.matches('article, section, nav, aside, main, header, footer, form, table, ul, ol, dl, figure, details, dialog, [role="region"], [role="navigation"], [role="main"], [role="complementary"]')}static getInteractiveElements(t,n){let r=[],i=o.INTERACTIVE_SELECTORS.join(", "),s=t.querySelectorAll(i);for(let a of Array.from(s)){let c=o.extractElement(a,n);c&&r.push(c)}if(n.customSelectors)for(let a of n.customSelectors)try{let c=t.querySelectorAll(a);for(let l of Array.from(c)){let d=o.extractElement(l,n);d&&r.push(d)}}catch{console.warn(`Invalid custom selector: ${a}`)}return r}static getSemanticElements(t,n){let r=[],i=o.SEMANTIC_SELECTORS.join(", "),s=t.querySelectorAll(i);for(let a of Array.from(s)){let c=o.extractElement(a,n);c&&r.push(c)}return r}},w(o,"INTERACTIVE_SELECTORS",["button","a[href]",'input:not([type="hidden"])',"textarea","select",'[role="button"]',"[onclick]",'[contenteditable="true"]',"summary",'[tabindex]:not([tabindex="-1"])']),w(o,"SEMANTIC_SELECTORS",["h1","h2","h3","h4","h5","h6","article","section","nav","aside","main","header","footer","form","table","ul","ol","img[alt]","figure","video","audio",'[role="navigation"]','[role="main"]','[role="complementary"]','[role="contentinfo"]']),o)}));function A(o,e){let t=(o??"").trim();if(!e||t.length<=e)return t;let n=["login","log in","sign in","sign up","submit","search","filter","add to cart","next","continue"],r=t.toLowerCase(),i=n.map(l=>({k:l,i:r.indexOf(l)})).find(l=>l.i>-1),s=Math.max(0,Math.floor(e*.66));if(i&&i.i>s){let l=Math.max(12,e-s-5),d=Math.max(0,i.i-Math.floor(l/2)),u=Math.min(t.length,d+l);return`${t.slice(0,s).trimEnd()} \u2026 ${t.slice(d,u).trim()}\u2026`}let a=t.slice(0,e),c=a.lastIndexOf(" ");return`${c>32?a.slice(0,c):a}\u2026`}function it(o){return o.selector?.css||""}function st(o){let e=5381;for(let t=0;t<o.length;t++)e=e*33^o.charCodeAt(t);return`sec-${(e>>>0).toString(36)}`}function F(o){switch(o){case"header":return"\u{1F9ED}";case"navigation":return"\u{1F4D1}";case"main":return"\u{1F4C4}";case"sections":return"\u{1F5C2}\uFE0F";case"sidebar":return"\u{1F4DA}";case"footer":return"\u{1F53B}";case"modals":return"\u{1F4AC}";default:return"\u{1F539}"}}function M(o,e){let t=A(o.text||o.attributes?.ariaLabel,e?.maxTextLength??80),n=it(o),r=o.tag.toLowerCase(),i=o.interaction?.submit?"submit":o.interaction?.click?"click":o.interaction?.change?"change":void 0,s=i?` (${i})`:"";return`- ${r.toUpperCase()}: ${t||"(no text)"} \u2192 \`${n}\`${s}`}function at(o){let e=[];e.push(...o.buttons.map(a=>a.selector?.css||"")),e.push(...o.links.map(a=>a.selector?.css||"")),e.push(...o.inputs.map(a=>a.selector?.css||"")),e.push(...o.clickable.map(a=>a.selector?.css||""));let t=e.length||1,n=e.filter(a=>a.startsWith("#")).length,r=e.filter(a=>/\[data-testid=/.test(a)).length,i=e.filter(a=>/:nth-child\(/.test(a)).length,s=n+r;return`Selector quality: ${Math.round(s/t*100)}% stable (ID/data-testid), ${Math.round(i/t*100)}% structural (:nth-child)`}function ct(o,e){let t=[],n=r=>typeof e?.maxElements=="number"?r.slice(0,e.maxElements):r;if(o.buttons.length){t.push("Buttons:");for(let r of n(o.buttons))t.push(M(r,e))}if(o.links.length){t.push("Links:");for(let r of n(o.links))t.push(M(r,e))}if(o.inputs.length){t.push("Inputs:");for(let r of n(o.inputs))t.push(M(r,e))}if(o.clickable.length){t.push("Other Clickable:");for(let r of n(o.clickable))t.push(M(r,e))}if(o.forms.length){t.push("Forms:");for(let r of n(o.forms))t.push(`- FORM: action=${r.action??"-"} method=${r.method??"-"} \u2192 \`${r.selector}\``)}return t.join(`
2
- `)}function q(o){let e=F("region"),t=st(`${o.selector}|${o.label??""}|${o.role??""}`),n=o.label?` ${o.label}`:"",r=[];o.buttonCount&&r.push(`${o.buttonCount} buttons`),o.linkCount&&r.push(`${o.linkCount} links`),o.inputCount&&r.push(`${o.inputCount} inputs`),o.textPreview&&r.push(`\u201C${A(o.textPreview,80)}\u201D`);let i=r.length?`: ${r.join(", ")}`:"";return`${e} ${n} \u2192 \`${o.selector}\` [${t}]${i}`}function O(o,e,t="section"){return`<page ${[e?.title?`title="${P(e?.title)}"`:null,e?.url?`url="${P(e?.url)}"`:null].filter(Boolean).join(" ")}>
3
- <${t}><![CDATA[
1
+ var I=Object.defineProperty,Q=Object.getOwnPropertyDescriptor,J=Object.getOwnPropertyNames,W=Object.prototype.hasOwnProperty,v=(o,t)=>()=>(o&&(t=o(o=0)),t),Z=(o,t)=>{let e={};for(var n in o)I(e,n,{get:o[n],enumerable:!0});return t||I(e,Symbol.toStringTag,{value:"Module"}),e},tt=(o,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(var r=J(t),i=0,s=r.length,a;i<s;i++)a=r[i],!W.call(o,a)&&a!==e&&I(o,a,{get:(c=>t[c]).bind(null,a),enumerable:!(n=Q(t,a))||n.enumerable});return o},et=o=>W.call(o,"module.exports")?o["module.exports"]:tt(I({},"__esModule",{value:!0}),o),nt=void 0,L,H=v((()=>{L=class E{static findMainContent(t){let e=t.querySelector('main, [role="main"]');return e||(t.body?E.detectMainContent(t.body):t.documentElement)}static detectMainContent(t){let e=[];if(E.collectCandidates(t,e,15),e.length===0)return t;e.sort((r,i)=>E.calculateContentScore(i)-E.calculateContentScore(r));let n=e[0];for(let r=1;r<e.length;r++){let i=e[r];!e.some((s,a)=>a!==r&&s.contains(i))&&E.calculateContentScore(i)>E.calculateContentScore(n)&&(n=i)}return n}static collectCandidates(t,e,n){E.calculateContentScore(t)>=n&&e.push(t),Array.from(t.children).forEach(r=>{E.collectCandidates(r,e,n)})}static calculateContentScore(t){let e=0,n=["article","content","main-container","main","main-content","post","entry"],r=["content","main","article","post","entry"];n.forEach(u=>{t.classList.contains(u)&&(e+=10)}),r.forEach(u=>{t.id?.toLowerCase().includes(u)&&(e+=10)});let i=t.tagName.toLowerCase();["article","main","section"].includes(i)&&(e+=8);let s=t.getElementsByTagName("p").length;e+=Math.min(s*2,10);let a=t.querySelectorAll("h1, h2, h3").length;e+=Math.min(a*3,9);let c=t.textContent?.trim().length||0;c>300&&(e+=Math.min(Math.floor(c/300)*2,10));let l=E.calculateLinkDensity(t);l<.3?e+=5:l>.5&&(e-=5),(t.hasAttribute("data-main")||t.hasAttribute("data-content")||t.hasAttribute("itemprop"))&&(e+=8);let d=t.getAttribute("role");return(d==="main"||d==="article")&&(e+=10),t.matches("aside, nav, header, footer, .sidebar, .navigation, .menu, .ad, .advertisement")&&(e-=10),t.getElementsByTagName("form").length>2&&(e-=5),Math.max(0,e)}static calculateLinkDensity(t){let e=t.getElementsByTagName("a"),n=0;for(let i of Array.from(e))n+=i.textContent?.length||0;let r=t.textContent?.length||1;return n/r}static isNavigation(t){if(t.tagName.toLowerCase()==="nav"||t.getAttribute("role")==="navigation")return!0;let e=[/nav/i,/menu/i,/sidebar/i,/toolbar/i],n=`${t.className} ${t.id}`.toLowerCase();return e.some(r=>r.test(n))}static isSupplementary(t){if(t.tagName.toLowerCase()==="aside"||t.getAttribute("role")==="complementary")return!0;let e=[/sidebar/i,/widget/i,/related/i,/advertisement/i,/social/i],n=`${t.className} ${t.id}`.toLowerCase();return e.some(r=>r.test(n))}static detectLandmarks(t){let e={navigation:[],main:[],complementary:[],contentinfo:[],banner:[],search:[],form:[],region:[]};for(let[n,r]of Object.entries({navigation:'nav, [role="navigation"]',main:'main, [role="main"]',complementary:'aside, [role="complementary"]',contentinfo:'footer, [role="contentinfo"]',banner:'header, [role="banner"]',search:'[role="search"]',form:'form[aria-label], form[aria-labelledby], [role="form"]',region:'section[aria-label], section[aria-labelledby], [role="region"]'})){let i=t.querySelectorAll(r);e[n]=Array.from(i)}return e}}})),S,D=v((()=>{S=class b{static generateSelectors(t){let e=t.ownerDocument||document,n=[];t.id&&b.isUniqueId(t.id,e)&&n.push({type:"id",value:`#${CSS.escape(t.id)}`,score:100});let r=b.getDataTestId(t);if(r){let h=`[data-testid="${CSS.escape(r)}"]`;n.push({type:"data-testid",value:h,score:90+(b.isUniqueSelectorSafe(h,e)?5:0)})}let i=t.getAttribute("role"),s=t.getAttribute("aria-label");if(i&&s){let h=`[role="${CSS.escape(i)}"][aria-label="${CSS.escape(s)}"]`;n.push({type:"role-aria",value:h,score:85+(b.isUniqueSelectorSafe(h,e)?5:0)})}let a=t.getAttribute("name");if(a){let h=`[name="${CSS.escape(a)}"]`;n.push({type:"name",value:h,score:78+(b.isUniqueSelectorSafe(h,e)?5:0)})}let c=b.generateCSSSelector(t,e),l=(c.match(/:nth-child\(/g)||[]).length*10,d=c.includes(".")?8:0,u=Math.max(0,70+d-l);n.push({type:"class-path",value:c,score:u});let m=b.generateXPath(t,e);n.push({type:"xpath",value:m,score:40});let f=b.generateTextBasedSelector(t);f&&n.push({type:"text",value:f,score:30}),n.sort((h,w)=>w.score-h.score);let y={css:n.find(h=>h.type!=="xpath"&&h.type!=="text")?.value||c,xpath:m,candidates:n};return f&&(y.textBased=f),r&&(y.dataTestId=r),s&&(y.ariaLabel=s),y}static generateCSSSelector(t,e){if(t.id&&b.isUniqueId(t.id,e))return`#${CSS.escape(t.id)}`;let n=b.getDataTestId(t);if(n)return`[data-testid="${CSS.escape(n)}"]`;let r=[],i=t;for(;i&&i.nodeType===Node.ELEMENT_NODE;){let s=i.nodeName.toLowerCase();if(i.id&&b.isUniqueId(i.id,e)){s=`#${CSS.escape(i.id)}`,r.unshift(s);break}let a=b.getMeaningfulClasses(i);a.length>0&&(s+=`.${a.map(l=>CSS.escape(l)).join(".")}`);let c=i.parentElement?.children;if(c&&c.length>1){let l=Array.from(c).indexOf(i);(l>0||!b.isUniqueSelector(s,i.parentElement))&&(s+=`:nth-child(${l+1})`)}r.unshift(s),i=i.parentElement}return b.optimizePath(r,t,e)}static generateXPath(t,e){if(t.id&&b.isUniqueId(t.id,e))return`//*[@id="${t.id}"]`;let n=[],r=t;for(;r&&r.nodeType===Node.ELEMENT_NODE;){let i=r.nodeName.toLowerCase();if(r.id&&b.isUniqueId(r.id,e)){n.unshift(`//*[@id="${r.id}"]`);break}let s=i,a=r.parentElement?.children;if(a){let c=Array.from(a).filter(l=>l.nodeName.toLowerCase()===i);if(c.length>1){let l=c.indexOf(r)+1;s+=`[${l}]`}}n.unshift(s),r=r.parentElement}return`//${n.join("/")}`}static generateTextBasedSelector(t){let e=t.textContent?.trim();if(!e||e.length>50)return;let n=t.nodeName.toLowerCase();if(["button","a","label"].includes(n))return`${n}:contains("${e.replace(/['"\\]/g,"\\$&")}")`}static getDataTestId(t){return t.getAttribute("data-testid")||t.getAttribute("data-test-id")||t.getAttribute("data-test")||t.getAttribute("data-cy")||void 0}static isUniqueId(t,e){return e.querySelectorAll(`#${CSS.escape(t)}`).length===1}static isUniqueSelector(t,e){try{return e.querySelectorAll(t).length===1}catch{return!1}}static isUniqueSelectorSafe(t,e){try{return e.querySelectorAll(t).length===1}catch{return!1}}static getMeaningfulClasses(t){let e=Array.from(t.classList),n=[/^(p|m|w|h|text|bg|border|flex|grid|col|row)-/,/^(xs|sm|md|lg|xl|2xl):/,/^(hover|focus|active|disabled|checked):/,/^js-/,/^is-/,/^has-/];return e.filter(r=>r.length<3?!1:!n.some(i=>i.test(r))).slice(0,2)}static optimizePath(t,e,n){for(let r=0;r<t.length-1;r++){let i=t.slice(r).join(" > ");try{let s=n.querySelectorAll(i);if(s.length===1&&s[0]===e)return i}catch{}}return t.join(" > ")}static getContextPath(t){let e=[],n=t,r=0,i=5;for(;n&&n!==t.ownerDocument?.body&&r<i;){let s=n.nodeName.toLowerCase(),a=s;if(n.id)a=`${s}#${n.id}`;else if(n.className&&typeof n.className=="string"){let l=n.className.split(" ")[0];l&&(a=`${s}.${l}`)}let c=n.getAttribute("role");c&&(a+=`[role="${c}"]`),e.unshift(a),n=n.parentElement,r++}return e}}})),g,j=v((()=>{D(),g=class p{static INTERACTIVE_SELECTORS=["button","a[href]",'input:not([type="hidden"])',"textarea","select",'[role="button"]',"[onclick]",'[contenteditable="true"]',"summary",'[tabindex]:not([tabindex="-1"])'];static SEMANTIC_SELECTORS=["h1","h2","h3","h4","h5","h6","article","section","nav","aside","main","header","footer","form","table","ul","ol","img[alt]","figure","video","audio",'[role="navigation"]','[role="main"]','[role="complementary"]','[role="contentinfo"]'];static isVisible(t,e){let n=t.getBoundingClientRect(),r=e||t.ownerDocument?.defaultView?.getComputedStyle(t);return r?n.width>0&&n.height>0&&r.display!=="none"&&r.visibility!=="hidden"&&r.opacity!=="0"&&t.offsetParent!==null:!1}static isInViewport(t,e){let n=t.getBoundingClientRect(),r=e||{width:t.ownerDocument?.defaultView?.innerWidth||0,height:t.ownerDocument?.defaultView?.innerHeight||0};return n.top<r.height&&n.bottom>0&&n.left<r.width&&n.right>0}static passesFilter(t,e){if(!e)return!0;let n=t;if(e.excludeSelectors?.length){for(let i of e.excludeSelectors)if(t.matches(i))return!1}if(e.includeSelectors?.length){let i=!1;for(let s of e.includeSelectors)if(t.matches(s)){i=!0;break}if(!i)return!1}if(e.tags?.length&&!e.tags.includes(t.tagName.toLowerCase()))return!1;let r=n.textContent?.toLowerCase()||"";if(e.textContains?.length){let i=!1;for(let s of e.textContains)if(r.includes(s.toLowerCase())){i=!0;break}if(!i)return!1}if(e.textMatches?.length){let i=!1;for(let s of e.textMatches)if(s.test(r)){i=!0;break}if(!i)return!1}if(e.hasAttributes?.length){for(let i of e.hasAttributes)if(!t.hasAttribute(i))return!1}if(e.attributeValues)for(let[i,s]of Object.entries(e.attributeValues)){let a=t.getAttribute(i);if(!a)return!1;if(typeof s=="string"){if(a!==s)return!1}else if(s instanceof RegExp&&!s.test(a))return!1}if(e.withinSelectors?.length){let i=!1;for(let s of e.withinSelectors)if(t.closest(s)){i=!0;break}if(!i)return!1}if(e.interactionTypes?.length){let i=p.getInteractionInfo(t),s=!1;for(let a of e.interactionTypes)if(i[a]){s=!0;break}if(!s)return!1}if(e.nearText){let i=t.parentElement;if(!i||!i.textContent?.toLowerCase().includes(e.nearText.toLowerCase()))return!1}return!0}static extractElement(t,e,n=0){if(e.maxDepth&&n>e.maxDepth||!e.includeHidden&&!p.isVisible(t)||e.viewportOnly&&!p.isInViewport(t)||!p.passesFilter(t,e.filter))return null;let r=t,i={tag:t.tagName.toLowerCase(),text:p.getElementText(t,e),selector:S.generateSelectors(t),attributes:p.getRelevantAttributes(t,e),context:p.getElementContext(t),interaction:p.getInteractionInfo(t)};if(e.mode==="full"&&p.isSemanticContainer(t)){let s=[];if(e.includeShadowDOM&&r.shadowRoot){let c=p.extractChildren(r.shadowRoot,e,n+1);s.push(...c)}let a=p.extractChildren(t,e,n+1);s.push(...a),s.length>0&&(i.children=s)}return i}static extractChildren(t,e,n){let r=[],i=t.querySelectorAll("*");for(let s of Array.from(i)){if(p.hasExtractedAncestor(s,i))continue;let a=p.extractElement(s,e,n);a&&r.push(a)}return r}static hasExtractedAncestor(t,e){let n=t.parentElement;for(;n;){if(Array.from(e).includes(n))return!0;n=n.parentElement}return!1}static getRelevantAttributes(t,e){let n=["id","class","name","type","value","placeholder","href","src","alt","title","action","method","aria-label","aria-describedby","aria-controls","role","disabled","readonly","required","checked","min","max","pattern","step","autocomplete","data-testid","data-test","data-cy"],r={},i=e.attributeTruncateLength??100,s=e.dataAttributeTruncateLength??50;for(let a of n){let c=t.getAttribute(a);c&&(r[a]=c.length>i?`${c.substring(0,i)}...`:c)}for(let a of t.attributes)a.name.startsWith("data-")&&!n.includes(a.name)&&(r[a.name]=a.value.length>s?`${a.value.substring(0,s)}...`:a.value);return r}static getElementContext(t){let e={parentChain:S.getContextPath(t)},n=t.closest("form");n&&(e.nearestForm=S.generateSelectors(n).css);let r=t.closest('section, [role="region"]');r&&(e.nearestSection=S.generateSelectors(r).css);let i=t.closest('main, [role="main"]');i&&(e.nearestMain=S.generateSelectors(i).css);let s=t.closest('nav, [role="navigation"]');return s&&(e.nearestNav=S.generateSelectors(s).css),e}static getInteractionInfo(t){let e=t,n={};(e.onclick||t.getAttribute("onclick")||t.matches('button, a[href], [role="button"], [tabindex]:not([tabindex="-1"])'))&&(n.click=!0),(e.onchange||t.getAttribute("onchange")||t.matches("input, select, textarea"))&&(n.change=!0),(e.onsubmit||t.getAttribute("onsubmit")||t.matches("form"))&&(n.submit=!0),t.matches('a[href], button[type="submit"]')&&(n.nav=!0),(e.hasAttribute("disabled")||e.getAttribute("aria-disabled")==="true")&&(n.disabled=!0),p.isVisible(t)||(n.hidden=!0);let r=t.getAttribute("role");if(r&&(n.role=r),t.matches("input, textarea, select, button")){let i=t.form||t.closest("form");i&&(n.form=S.generateSelectors(i).css)}return n}static getElementText(t,e){if(t.matches("input, textarea")){let i=t;return i.value||i.placeholder||""}if(t.matches("img"))return t.alt||"";let n=t.textContent?.trim()||"",r=e?.textTruncateLength;return r&&n.length>r?`${n.substring(0,r)}...`:n}static isSemanticContainer(t){return t.matches('article, section, nav, aside, main, header, footer, form, table, ul, ol, dl, figure, details, dialog, [role="region"], [role="navigation"], [role="main"], [role="complementary"]')}static getInteractiveElements(t,e){let n=[],r=p.INTERACTIVE_SELECTORS.join(", "),i=t.querySelectorAll(r);for(let s of Array.from(i)){let a=p.extractElement(s,e);a&&n.push(a)}if(e.customSelectors)for(let s of e.customSelectors)try{let a=t.querySelectorAll(s);for(let c of Array.from(a)){let l=p.extractElement(c,e);l&&n.push(l)}}catch{console.warn(`Invalid custom selector: ${s}`)}return n}static getSemanticElements(t,e){let n=[],r=p.SEMANTIC_SELECTORS.join(", "),i=t.querySelectorAll(r);for(let s of Array.from(i)){let a=p.extractElement(s,e);a&&n.push(a)}return n}}}));function T(o,t){let e=(o??"").trim();if(!t||e.length<=t)return e;let n=["login","log in","sign in","sign up","submit","search","filter","add to cart","next","continue"],r=e.toLowerCase(),i=n.map(l=>({k:l,i:r.indexOf(l)})).find(l=>l.i>-1),s=Math.max(0,Math.floor(t*.66));if(i&&i.i>s){let l=Math.max(12,t-s-5),d=Math.max(0,i.i-Math.floor(l/2)),u=Math.min(e.length,d+l);return`${e.slice(0,s).trimEnd()} \u2026 ${e.slice(d,u).trim()}\u2026`}let a=e.slice(0,t),c=a.lastIndexOf(" ");return`${c>32?a.slice(0,c):a}\u2026`}function rt(o){return o.selector?.css||""}function ot(o){let t=5381;for(let e=0;e<o.length;e++)t=t*33^o.charCodeAt(e);return`sec-${(t>>>0).toString(36)}`}function F(o){switch(o){case"header":return"\u{1F9ED}";case"navigation":return"\u{1F4D1}";case"main":return"\u{1F4C4}";case"sections":return"\u{1F5C2}\uFE0F";case"sidebar":return"\u{1F4DA}";case"footer":return"\u{1F53B}";case"modals":return"\u{1F4AC}";default:return"\u{1F539}"}}function M(o,t){let e=T(o.text||o.attributes?.ariaLabel,t?.maxTextLength??80),n=rt(o),r=o.tag.toLowerCase(),i=o.interaction?.submit?"submit":o.interaction?.click?"click":o.interaction?.change?"change":void 0,s=i?` (${i})`:"";return`- ${r.toUpperCase()}: ${e||"(no text)"} \u2192 \`${n}\`${s}`}function it(o){let t=[];t.push(...o.buttons.map(a=>a.selector?.css||"")),t.push(...o.links.map(a=>a.selector?.css||"")),t.push(...o.inputs.map(a=>a.selector?.css||"")),t.push(...o.clickable.map(a=>a.selector?.css||""));let e=t.length||1,n=t.filter(a=>a.startsWith("#")).length,r=t.filter(a=>/\[data-testid=/.test(a)).length,i=t.filter(a=>/:nth-child\(/.test(a)).length,s=n+r;return`Selector quality: ${Math.round(s/e*100)}% stable (ID/data-testid), ${Math.round(i/e*100)}% structural (:nth-child)`}function st(o,t){let e=[],n=r=>typeof t?.maxElements=="number"?r.slice(0,t.maxElements):r;if(o.buttons.length){e.push("Buttons:");for(let r of n(o.buttons))e.push(M(r,t))}if(o.links.length){e.push("Links:");for(let r of n(o.links))e.push(M(r,t))}if(o.inputs.length){e.push("Inputs:");for(let r of n(o.inputs))e.push(M(r,t))}if(o.clickable.length){e.push("Other Clickable:");for(let r of n(o.clickable))e.push(M(r,t))}if(o.forms.length){e.push("Forms:");for(let r of n(o.forms))e.push(`- FORM: action=${r.action??"-"} method=${r.method??"-"} \u2192 \`${r.selector}\``)}return e.join(`
2
+ `)}function q(o){let t=F("region"),e=ot(`${o.selector}|${o.label??""}|${o.role??""}`),n=o.label?` ${o.label}`:"",r=[];o.buttonCount&&r.push(`${o.buttonCount} buttons`),o.linkCount&&r.push(`${o.linkCount} links`),o.inputCount&&r.push(`${o.inputCount} inputs`),o.textPreview&&r.push(`\u201C${T(o.textPreview,80)}\u201D`);let i=r.length?`: ${r.join(", ")}`:"";return`${t} ${n} \u2192 \`${o.selector}\` [${e}]${i}`}function O(o,t,e="section"){return`<page ${[t?.title?`title="${P(t?.title)}"`:null,t?.url?`url="${P(t?.url)}"`:null].filter(Boolean).join(" ")}>
3
+ <${e}><![CDATA[
4
4
  ${o}
5
- ]]></${t}>
6
- </page>`}function P(o){return o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function k(o){return o.charAt(0).toUpperCase()+o.slice(1)}var U,lt=C((()=>{U=class{static structure(o,e={},t){let n=[];n.push("# Page Outline"),(t?.title||t?.url)&&(n.push(`Title: ${t?.title??""}`.trim()),n.push(`URL: ${t?.url??""}`.trim())),n.push("");let r=o.regions,i=[["header",r.header],["navigation",r.navigation],["main",r.main],["sections",r.sections],["sidebar",r.sidebar],["footer",r.footer],["modals",r.modals]];for(let[s,a]of i){if(!a)continue;let c=F(s);if(Array.isArray(a)){if(!a.length)continue;n.push(`## ${c} ${k(s)}`);for(let l of a)n.push(q(l))}else n.push(`## ${c} ${k(s)}`),n.push(q(a));n.push("")}if(o.suggestions?.length){n.push("## Suggestions");for(let s of o.suggestions)n.push(`- ${s}`);n.push("")}return n.push("Next: choose a region (by selector or [sectionId]) and call dom_extract_region for actionable details."),O(n.join(`
7
- `),t,"outline")}static region(o,e={},t){let n=[];n.push("# Region Details"),(t?.title||t?.url)&&(n.push(`Title: ${t?.title??""}`.trim()),n.push(`URL: ${t?.url??""}`.trim())),n.push("");let r=o.interactive;if(o.page){let a=[o.page.hasErrors?"errors: yes":"errors: no",o.page.isLoading?"loading: yes":"loading: no",o.page.hasModals?"modals: yes":"modals: no"];n.push(`Page state: ${a.join(", ")}`)}let i=[],s=a=>a?a.length:0;return i.push(`${s(r.buttons)} buttons`),i.push(`${s(r.links)} links`),i.push(`${s(r.inputs)} inputs`),r.forms?.length&&i.push(`${s(r.forms)} forms`),n.push(`Summary: ${i.join(", ")}`),n.push(at(r)),n.push(""),n.push(ct(r,e)),n.push(""),n.push("Next: write a script using the most stable selectors above. If selectors look unstable, rerun dom_extract_region with higher detail or call dom_extract_content for text context."),O(n.join(`
8
- `),t,"section")}static content(o,e={},t){let n=[];if(n.push("# Content"),n.push(`Selector: \`${o.selector}\``),n.push(""),o.text.headings?.length){n.push("Headings:");for(let r of o.text.headings)n.push(`- H${r.level}: ${A(r.text,e.maxTextLength??120)}`);n.push("")}if(o.text.paragraphs?.length){let r=typeof e.maxElements=="number"?e.maxElements:o.text.paragraphs.length;n.push("Paragraphs:");for(let i of o.text.paragraphs.slice(0,r))n.push(`- ${A(i,e.maxTextLength??200)}`);n.push("")}if(o.text.lists?.length){n.push("Lists:");for(let r of o.text.lists){n.push(`- ${r.type.toUpperCase()}:`);let i=typeof e.maxElements=="number"?e.maxElements:r.items.length;for(let s of r.items.slice(0,i))n.push(` - ${A(s,e.maxTextLength??120)}`)}n.push("")}if(o.tables?.length){n.push("Tables:");for(let r of o.tables){n.push(`- Headers: ${r.headers.join(" | ")}`);let i=typeof e.maxElements=="number"?e.maxElements:r.rows.length;for(let s of r.rows.slice(0,i))n.push(` - ${s.join(" | ")}`)}n.push("")}if(o.media?.length){n.push("Media:");let r=typeof e.maxElements=="number"?e.maxElements:o.media.length;for(let i of o.media.slice(0,r))n.push(`- ${i.type.toUpperCase()}: ${i.alt??""} ${i.src?`\u2192 ${i.src}`:""}`.trim());n.push("")}return n.push("Next: if text is insufficient for targeting, call dom_extract_region for interactive selectors."),O(n.join(`
9
- `),t,"content")}}}));function ut(){if(typeof window<"u"){let o=window,e=o.SmartDOMReader;if(typeof e=="function")return e;let t=o.SmartDOMReaderNamespace;if(t&&typeof t.SmartDOMReader=="function")return t.SmartDOMReader}try{if(typeof ot=="function"){let o=(B(),rt(ft));if(o&&typeof o.SmartDOMReader=="function")return o.SmartDOMReader;if(o&&typeof o.default=="function")return o.default}}catch{}}var V,dt=C((()=>{H(),D(),j(),V=class p{static extractStructure(e){let t={},n=e.querySelector('header, [role="banner"], .header, #header');n&&(t.header=p.analyzeRegion(n));let r=e.querySelectorAll('nav, [role="navigation"], .nav, .navigation');if(r.length>0&&(t.navigation=Array.from(r).map(u=>p.analyzeRegion(u))),e instanceof Document){let u=T.findMainContent(e);if(u){t.main=p.analyzeRegion(u);let m=u.querySelectorAll('section, article, [role="region"]');m.length>0&&(t.sections=Array.from(m).filter(f=>!f.closest("nav, header, footer")).map(f=>p.analyzeRegion(f)))}}else{t.main=p.analyzeRegion(e);let u=e.querySelectorAll('section, article, [role="region"]');u.length>0&&(t.sections=Array.from(u).filter(m=>!m.closest("nav, header, footer")).map(m=>p.analyzeRegion(m)))}let i=e.querySelectorAll('aside, [role="complementary"], .sidebar, #sidebar');i.length>0&&(t.sidebar=Array.from(i).map(u=>p.analyzeRegion(u)));let s=e.querySelector('footer, [role="contentinfo"], .footer, #footer');s&&(t.footer=p.analyzeRegion(s));let a=e.querySelectorAll('[role="dialog"], .modal, .popup, .overlay'),c=Array.from(a).filter(u=>g.isVisible(u));c.length>0&&(t.modals=c.map(u=>p.analyzeRegion(u)));let l=p.extractFormOverview(e),d=p.calculateSummary(e,t,l);return{regions:t,forms:l,summary:d,suggestions:p.generateSuggestions(t,d)}}static extractRegion(e,t,n={},r){let i=t.querySelector(e);if(!i)return null;let s=r??ut();if(!s)throw new Error("SmartDOMReader is unavailable. Ensure the Smart DOM Reader module is loaded before calling extractRegion.");return new s(n).extract(i,n)}static extractContent(e,t,n={}){let r=t.querySelector(e);if(!r)return null;let i={selector:e,text:{},metadata:{wordCount:0,hasInteractive:!1}};if(n.includeHeadings!==!1){let c=r.querySelectorAll("h1, h2, h3, h4, h5, h6");i.text.headings=Array.from(c).map(l=>({level:Number.parseInt(l.tagName[1],10),text:p.getTextContent(l,n.maxTextLength)}))}let s=r.querySelectorAll("p");if(s.length>0&&(i.text.paragraphs=Array.from(s).map(c=>p.getTextContent(c,n.maxTextLength)).filter(c=>c.length>0)),n.includeLists!==!1){let c=r.querySelectorAll("ul, ol");i.text.lists=Array.from(c).map(l=>({type:l.tagName.toLowerCase(),items:Array.from(l.querySelectorAll("li")).map(d=>p.getTextContent(d,n.maxTextLength))}))}if(n.includeTables!==!1){let c=r.querySelectorAll("table");i.tables=Array.from(c).map(l=>({headers:Array.from(l.querySelectorAll("th")).map(d=>p.getTextContent(d)),rows:Array.from(l.querySelectorAll("tr")).filter(d=>d.querySelector("td")).map(d=>Array.from(d.querySelectorAll("td")).map(u=>p.getTextContent(u)))}))}if(n.includeMedia!==!1){let c=r.querySelectorAll("img"),l=r.querySelectorAll("video"),d=r.querySelectorAll("audio");i.media=[...Array.from(c).map(u=>{let m={type:"img"},f=u.getAttribute("alt"),S=u.getAttribute("src");return f&&(m.alt=f),S&&(m.src=S),m}),...Array.from(l).map(u=>{let m={type:"video"},f=u.getAttribute("src");return f&&(m.src=f),m}),...Array.from(d).map(u=>{let m={type:"audio"},f=u.getAttribute("src");return f&&(m.src=f),m})]}let a=r.textContent||"";return i.metadata.wordCount=a.trim().split(/\s+/).length,i.metadata.hasInteractive=r.querySelectorAll("button, a, input, textarea, select").length>0,i}static analyzeRegion(e){let t=b.generateSelectors(e).css,n=e.querySelectorAll('button, [role="button"]'),r=e.querySelectorAll("a[href]"),i=e.querySelectorAll("input, textarea, select"),s=e.querySelectorAll("form"),a=e.querySelectorAll("ul, ol"),c=e.querySelectorAll("table"),l=e.querySelectorAll("img, video, audio"),d=n.length+r.length+i.length,u,m=e.getAttribute("aria-label");if(m)u=m;else if(e.getAttribute("aria-labelledby")){let v=e.getAttribute("aria-labelledby");if(v){let N=e.ownerDocument?.getElementById(v);N&&(u=N.textContent?.trim())}}else{let v=e.querySelector("h1, h2, h3");v&&(u=v.textContent?.trim())}let f=e.textContent?.trim()||"",S=f.length>50?`${f.substring(0,50)}...`:f,h={selector:t,interactiveCount:d,hasForm:s.length>0,hasList:a.length>0,hasTable:c.length>0,hasMedia:l.length>0};u&&(h.label=u);let L=e.getAttribute("role");return L&&(h.role=L),n.length>0&&(h.buttonCount=n.length),r.length>0&&(h.linkCount=r.length),i.length>0&&(h.inputCount=i.length),S.length>0&&(h.textPreview=S),h}static extractFormOverview(e){let t=e.querySelectorAll("form");return Array.from(t).map(n=>{let r=n.querySelectorAll("input, textarea, select"),i=b.generateSelectors(n).css,s="unknown";n.closest('header, [role="banner"]')?s="header":n.closest('nav, [role="navigation"]')?s="navigation":n.closest('main, [role="main"]')?s="main":n.closest('aside, [role="complementary"]')?s="sidebar":n.closest('footer, [role="contentinfo"]')&&(s="footer");let a,c=n.getAttribute("id")?.toLowerCase(),l=n.getAttribute("class")?.toLowerCase(),d=n.getAttribute("action")?.toLowerCase(),u=n.querySelector('input[type="email"]'),m=n.querySelector('input[type="password"]');n.querySelector('input[type="search"]')||c?.includes("search")||l?.includes("search")?a="search":m&&u?a="login":m?a="authentication":c?.includes("contact")||l?.includes("contact")?a="contact":c?.includes("subscribe")||l?.includes("subscribe")?a="subscription":(d?.includes("checkout")||l?.includes("checkout"))&&(a="checkout");let f={selector:i,location:s,inputCount:r.length};return a&&(f.purpose=a),f})}static calculateSummary(e,t,n){let r=e.querySelectorAll("button, a[href], input, textarea, select"),i=e.querySelectorAll('section, article, [role="region"]'),s=(t.modals?.length||0)>0,a=[".error",".alert-danger",'[role="alert"]'].some(u=>{let m=e.querySelector(u);return m?g.isVisible(m):!1}),c=[".loading",".spinner",'[aria-busy="true"]'].some(u=>{let m=e.querySelector(u);return m?g.isVisible(m):!1}),l={totalInteractive:r.length,totalForms:n.length,totalSections:i.length,hasModals:s,hasErrors:a,isLoading:c},d=t.main?.selector;return d&&(l.mainContentSelector=d),l}static generateSuggestions(e,t){let n=[];return t.hasErrors&&n.push("Page has error indicators - check error messages before interacting"),t.isLoading&&n.push("Page appears to be loading - wait or check loading state"),t.hasModals&&n.push("Modal/dialog is open - may need to interact with or close it first"),e.main&&e.main.interactiveCount>10&&n.push(`Main content has ${e.main.interactiveCount} interactive elements - consider filtering`),t.totalForms>0&&n.push(`Found ${t.totalForms} form(s) on the page`),e.main||n.push("No clear main content area detected - may need to explore regions"),n}static getTextContent(e,t){let n=e.textContent?.trim()||"";return t&&n.length>t?`${n.substring(0,t)}...`:n}}})),mt=C((()=>{})),ft=et({ContentDetection:()=>T,MarkdownFormatter:()=>U,ProgressiveExtractor:()=>V,SelectorGenerator:()=>b,SmartDOMReader:()=>E,default:()=>E}),E,B=C((()=>{H(),D(),j(),lt(),dt(),mt(),E=class ${constructor(e={}){w(this,"options");this.options={mode:e.mode||"interactive",maxDepth:e.maxDepth||5,includeHidden:e.includeHidden||!1,includeShadowDOM:e.includeShadowDOM??!0,includeIframes:e.includeIframes||!1,viewportOnly:e.viewportOnly||!1,mainContentOnly:e.mainContentOnly||!1,customSelectors:e.customSelectors||[],...e.attributeTruncateLength!==void 0&&{attributeTruncateLength:e.attributeTruncateLength},...e.dataAttributeTruncateLength!==void 0&&{dataAttributeTruncateLength:e.dataAttributeTruncateLength},...e.textTruncateLength!==void 0&&{textTruncateLength:e.textTruncateLength},...e.filter!==void 0&&{filter:e.filter}}}extract(e=document,t){let n=Date.now(),r=e instanceof Document?e:e.ownerDocument,i={...this.options,...t},s=e instanceof Document?r:e;i.mainContentOnly&&e instanceof Document&&(s=T.findMainContent(r));let a=this.extractPageState(r),c=this.extractLandmarks(r),l=this.extractInteractiveElements(s,i),d={mode:i.mode,timestamp:n,page:a,landmarks:c,interactive:l};if(i.mode==="full"){let u=this.extractSemanticElements(s,i),m=this.extractMetadata(r,s,i);return{...d,semantic:u,metadata:m}}return d}extractPageState(e){let t=this.getFocusedElement(e);return{url:e.location?.href||"",title:e.title||"",hasErrors:this.detectErrors(e),isLoading:this.detectLoading(e),hasModals:this.detectModals(e),...t!==void 0&&{hasFocus:t}}}extractLandmarks(e){let t=T.detectLandmarks(e);return{navigation:this.elementsToSelectors(t.navigation||[]),main:this.elementsToSelectors(t.main||[]),forms:this.elementsToSelectors(t.form||[]),headers:this.elementsToSelectors(t.banner||[]),footers:this.elementsToSelectors(t.contentinfo||[]),articles:this.elementsToSelectors(t.region||[]),sections:this.elementsToSelectors(t.region||[])}}elementsToSelectors(e){return e.map(t=>b.generateSelectors(t).css)}extractInteractiveElements(e,t){let n=[],r=[],i=[],s=[];return e.querySelectorAll('button, [role="button"], input[type="button"], input[type="submit"]').forEach(a=>{if(this.shouldIncludeElement(a,t)){let c=g.extractElement(a,t);c&&n.push(c)}}),e.querySelectorAll("a[href]").forEach(a=>{if(this.shouldIncludeElement(a,t)){let c=g.extractElement(a,t);c&&r.push(c)}}),e.querySelectorAll('input:not([type="button"]):not([type="submit"]), textarea, select').forEach(a=>{if(this.shouldIncludeElement(a,t)){let c=g.extractElement(a,t);c&&i.push(c)}}),t.customSelectors&&t.customSelectors.forEach(a=>{e.querySelectorAll(a).forEach(c=>{if(this.shouldIncludeElement(c,t)){let l=g.extractElement(c,t);l&&s.push(l)}})}),{buttons:n,links:r,inputs:i,forms:this.extractForms(e,t),clickable:s}}extractForms(e,t){let n=[];return e.querySelectorAll("form").forEach(r=>{if(!this.shouldIncludeElement(r,t))return;let i=[],s=[];r.querySelectorAll('input:not([type="button"]):not([type="submit"]), textarea, select').forEach(d=>{let u=g.extractElement(d,t);u&&i.push(u)}),r.querySelectorAll('button, input[type="button"], input[type="submit"]').forEach(d=>{let u=g.extractElement(d,t);u&&s.push(u)});let a=r.getAttribute("action"),c=r.getAttribute("method"),l={selector:b.generateSelectors(r).css,inputs:i,buttons:s};a&&(l.action=a),c&&(l.method=c),n.push(l)}),n}extractSemanticElements(e,t){let n=[],r=[],i=[],s=[],a=[];return e.querySelectorAll("h1, h2, h3, h4, h5, h6").forEach(c=>{if(this.shouldIncludeElement(c,t)){let l=g.extractElement(c,t);l&&n.push(l)}}),e.querySelectorAll("img").forEach(c=>{if(this.shouldIncludeElement(c,t)){let l=g.extractElement(c,t);l&&r.push(l)}}),e.querySelectorAll("table").forEach(c=>{if(this.shouldIncludeElement(c,t)){let l=g.extractElement(c,t);l&&i.push(l)}}),e.querySelectorAll("ul, ol").forEach(c=>{if(this.shouldIncludeElement(c,t)){let l=g.extractElement(c,t);l&&s.push(l)}}),e.querySelectorAll('article, [role="article"]').forEach(c=>{if(this.shouldIncludeElement(c,t)){let l=g.extractElement(c,t);l&&a.push(l)}}),{headings:n,images:r,tables:i,lists:s,articles:a}}extractMetadata(e,t,n){let r=t.querySelectorAll("*"),i=t.querySelectorAll("button, a, input, textarea, select, h1, h2, h3, h4, h5, h6, img, table, ul, ol, article").length,s={totalElements:r.length,extractedElements:i};n.mainContentOnly&&t instanceof Element&&(s.mainContent=b.generateSelectors(t).css);let a=e.documentElement.getAttribute("lang");return a&&(s.language=a),s}shouldIncludeElement(e,t){return!(!t.includeHidden&&!g.isVisible(e)||t.viewportOnly&&!g.isInViewport(e)||t.filter&&!g.passesFilter(e,t.filter))}detectErrors(e){return[".error",".alert-danger",'[role="alert"]',".error-message"].some(t=>{let n=e.querySelector(t);return n?g.isVisible(n):!1})}detectLoading(e){return[".loading",".spinner",'[aria-busy="true"]',".loader"].some(t=>{let n=e.querySelector(t);return n?g.isVisible(n):!1})}detectModals(e){return['[role="dialog"]',".modal",".popup",".overlay"].some(t=>{let n=e.querySelector(t);return n?g.isVisible(n):!1})}getFocusedElement(e){let t=e.activeElement;if(t&&t!==e.body)return b.generateSelectors(t).css}static extractInteractive(e,t={}){return new $({...t,mode:"interactive"}).extract(e)}static extractFull(e,t={}){return new $({...t,mode:"full"}).extract(e)}static extractFromElement(e,t="interactive",n={}){return new $({...n,mode:t}).extract(e)}}}));B();var ht=new Set(["id","data-testid","role-aria","name","class-path","css-path"]);function _(o){let e=o.trim();return e.startsWith("/")||e.startsWith("(")||e.startsWith("./")}function gt(o){let e=o.selector.candidates;if(e&&e.length>0){let n=null;for(let r of e)ht.has(r.type)&&(!r.value||_(r.value)||(!n||r.score>n.score)&&(n=r));if(n)return n.value}let t=o.selector.css;return t&&!_(t)?t:null}function pt(o){let e=o.tag.toLowerCase(),t=o.interaction.role??o.attributes.role;return e==="a"&&(o.interaction.nav||o.attributes.href!=null)?"navigable":e==="input"||e==="select"||e==="textarea"||t==="textbox"||t==="combobox"||t==="listbox"||t==="spinbutton"||o.interaction.change&&!o.interaction.click?"input":e==="button"||t==="button"||o.interaction.click||o.interaction.submit?"clickable":"static"}function xt(o){let e={...o.attributes},t=o.interaction.role;return t&&!e.role&&(e.role=t),e}function bt(o,e){return e?[o.selector.css,o.selector.xpath,o.context.nearestForm,o.context.nearestSection,o.context.nearestMain,o.context.nearestNav,...o.selector.candidates?.map(n=>n.value)??[],...o.context.parentChain].some(n=>!!n&&n.includes(e)):!1}function z(o,e={}){let t=e.includeSemantic??!0,n=e.excludeSelector??".persona-host",r=e.maxTextLength??200,i=[o.interactive.buttons,o.interactive.links,o.interactive.inputs,o.interactive.clickable];t&&o.semantic&&i.push(o.semantic.headings,o.semantic.images,o.semantic.tables,o.semantic.lists,o.semantic.articles);let s=[],a=new Set,c=l=>{if(bt(l,n))return!0;let d=gt(l);if(d&&!a.has(d)&&(a.add(d),s.push({selector:d,tagName:l.tag.toLowerCase(),text:(l.text??"").trim().substring(0,r),role:l.interaction.role??l.attributes.role??null,interactivity:pt(l),attributes:xt(l)}),e.maxElements&&s.length>=e.maxElements))return!1;if(l.children){for(let u of l.children)if(!c(u))return!1}return!0};for(let l of i)if(l){for(let d of l)if(!c(d))return s}return s}var R=100;function X(o,e={}){if(o.length===0)return"No page elements found.";let t=e.mode??"structured",n=[];if(t==="structured"){let i=o.map(s=>s.formattedSummary).filter(s=>!!s&&s.length>0);i.length>0&&n.push(`Structured summaries:
5
+ ]]></${e}>
6
+ </page>`}function P(o){return o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function k(o){return o.charAt(0).toUpperCase()+o.slice(1)}var U,at=v((()=>{U=class{static structure(o,t={},e){let n=[];n.push("# Page Outline"),(e?.title||e?.url)&&(n.push(`Title: ${e?.title??""}`.trim()),n.push(`URL: ${e?.url??""}`.trim())),n.push("");let r=o.regions,i=[["header",r.header],["navigation",r.navigation],["main",r.main],["sections",r.sections],["sidebar",r.sidebar],["footer",r.footer],["modals",r.modals]];for(let[s,a]of i){if(!a)continue;let c=F(s);if(Array.isArray(a)){if(!a.length)continue;n.push(`## ${c} ${k(s)}`);for(let l of a)n.push(q(l))}else n.push(`## ${c} ${k(s)}`),n.push(q(a));n.push("")}if(o.suggestions?.length){n.push("## Suggestions");for(let s of o.suggestions)n.push(`- ${s}`);n.push("")}return n.push("Next: choose a region (by selector or [sectionId]) and call dom_extract_region for actionable details."),O(n.join(`
7
+ `),e,"outline")}static region(o,t={},e){let n=[];n.push("# Region Details"),(e?.title||e?.url)&&(n.push(`Title: ${e?.title??""}`.trim()),n.push(`URL: ${e?.url??""}`.trim())),n.push("");let r=o.interactive;if(o.page){let a=[o.page.hasErrors?"errors: yes":"errors: no",o.page.isLoading?"loading: yes":"loading: no",o.page.hasModals?"modals: yes":"modals: no"];n.push(`Page state: ${a.join(", ")}`)}let i=[],s=a=>a?a.length:0;return i.push(`${s(r.buttons)} buttons`),i.push(`${s(r.links)} links`),i.push(`${s(r.inputs)} inputs`),r.forms?.length&&i.push(`${s(r.forms)} forms`),n.push(`Summary: ${i.join(", ")}`),n.push(it(r)),n.push(""),n.push(st(r,t)),n.push(""),n.push("Next: write a script using the most stable selectors above. If selectors look unstable, rerun dom_extract_region with higher detail or call dom_extract_content for text context."),O(n.join(`
8
+ `),e,"section")}static content(o,t={},e){let n=[];if(n.push("# Content"),n.push(`Selector: \`${o.selector}\``),n.push(""),o.text.headings?.length){n.push("Headings:");for(let r of o.text.headings)n.push(`- H${r.level}: ${T(r.text,t.maxTextLength??120)}`);n.push("")}if(o.text.paragraphs?.length){let r=typeof t.maxElements=="number"?t.maxElements:o.text.paragraphs.length;n.push("Paragraphs:");for(let i of o.text.paragraphs.slice(0,r))n.push(`- ${T(i,t.maxTextLength??200)}`);n.push("")}if(o.text.lists?.length){n.push("Lists:");for(let r of o.text.lists){n.push(`- ${r.type.toUpperCase()}:`);let i=typeof t.maxElements=="number"?t.maxElements:r.items.length;for(let s of r.items.slice(0,i))n.push(` - ${T(s,t.maxTextLength??120)}`)}n.push("")}if(o.tables?.length){n.push("Tables:");for(let r of o.tables){n.push(`- Headers: ${r.headers.join(" | ")}`);let i=typeof t.maxElements=="number"?t.maxElements:r.rows.length;for(let s of r.rows.slice(0,i))n.push(` - ${s.join(" | ")}`)}n.push("")}if(o.media?.length){n.push("Media:");let r=typeof t.maxElements=="number"?t.maxElements:o.media.length;for(let i of o.media.slice(0,r))n.push(`- ${i.type.toUpperCase()}: ${i.alt??""} ${i.src?`\u2192 ${i.src}`:""}`.trim());n.push("")}return n.push("Next: if text is insufficient for targeting, call dom_extract_region for interactive selectors."),O(n.join(`
9
+ `),e,"content")}}}));function ct(){if(typeof window<"u"){let o=window,t=o.SmartDOMReader;if(typeof t=="function")return t;let e=o.SmartDOMReaderNamespace;if(e&&typeof e.SmartDOMReader=="function")return e.SmartDOMReader}try{if(typeof nt=="function"){let o=(B(),et(dt));if(o&&typeof o.SmartDOMReader=="function")return o.SmartDOMReader;if(o&&typeof o.default=="function")return o.default}}catch{}}var V,lt=v((()=>{H(),D(),j(),V=class x{static extractStructure(t){let e={},n=t.querySelector('header, [role="banner"], .header, #header');n&&(e.header=x.analyzeRegion(n));let r=t.querySelectorAll('nav, [role="navigation"], .nav, .navigation');if(r.length>0&&(e.navigation=Array.from(r).map(u=>x.analyzeRegion(u))),t instanceof Document){let u=L.findMainContent(t);if(u){e.main=x.analyzeRegion(u);let m=u.querySelectorAll('section, article, [role="region"]');m.length>0&&(e.sections=Array.from(m).filter(f=>!f.closest("nav, header, footer")).map(f=>x.analyzeRegion(f)))}}else{e.main=x.analyzeRegion(t);let u=t.querySelectorAll('section, article, [role="region"]');u.length>0&&(e.sections=Array.from(u).filter(m=>!m.closest("nav, header, footer")).map(m=>x.analyzeRegion(m)))}let i=t.querySelectorAll('aside, [role="complementary"], .sidebar, #sidebar');i.length>0&&(e.sidebar=Array.from(i).map(u=>x.analyzeRegion(u)));let s=t.querySelector('footer, [role="contentinfo"], .footer, #footer');s&&(e.footer=x.analyzeRegion(s));let a=t.querySelectorAll('[role="dialog"], .modal, .popup, .overlay'),c=Array.from(a).filter(u=>g.isVisible(u));c.length>0&&(e.modals=c.map(u=>x.analyzeRegion(u)));let l=x.extractFormOverview(t),d=x.calculateSummary(t,e,l);return{regions:e,forms:l,summary:d,suggestions:x.generateSuggestions(e,d)}}static extractRegion(t,e,n={},r){let i=e.querySelector(t);if(!i)return null;let s=r??ct();if(!s)throw new Error("SmartDOMReader is unavailable. Ensure the Smart DOM Reader module is loaded before calling extractRegion.");return new s(n).extract(i,n)}static extractContent(t,e,n={}){let r=e.querySelector(t);if(!r)return null;let i={selector:t,text:{},metadata:{wordCount:0,hasInteractive:!1}};if(n.includeHeadings!==!1){let c=r.querySelectorAll("h1, h2, h3, h4, h5, h6");i.text.headings=Array.from(c).map(l=>({level:Number.parseInt(l.tagName[1],10),text:x.getTextContent(l,n.maxTextLength)}))}let s=r.querySelectorAll("p");if(s.length>0&&(i.text.paragraphs=Array.from(s).map(c=>x.getTextContent(c,n.maxTextLength)).filter(c=>c.length>0)),n.includeLists!==!1){let c=r.querySelectorAll("ul, ol");i.text.lists=Array.from(c).map(l=>({type:l.tagName.toLowerCase(),items:Array.from(l.querySelectorAll("li")).map(d=>x.getTextContent(d,n.maxTextLength))}))}if(n.includeTables!==!1){let c=r.querySelectorAll("table");i.tables=Array.from(c).map(l=>({headers:Array.from(l.querySelectorAll("th")).map(d=>x.getTextContent(d)),rows:Array.from(l.querySelectorAll("tr")).filter(d=>d.querySelector("td")).map(d=>Array.from(d.querySelectorAll("td")).map(u=>x.getTextContent(u)))}))}if(n.includeMedia!==!1){let c=r.querySelectorAll("img"),l=r.querySelectorAll("video"),d=r.querySelectorAll("audio");i.media=[...Array.from(c).map(u=>{let m={type:"img"},f=u.getAttribute("alt"),y=u.getAttribute("src");return f&&(m.alt=f),y&&(m.src=y),m}),...Array.from(l).map(u=>{let m={type:"video"},f=u.getAttribute("src");return f&&(m.src=f),m}),...Array.from(d).map(u=>{let m={type:"audio"},f=u.getAttribute("src");return f&&(m.src=f),m})]}let a=r.textContent||"";return i.metadata.wordCount=a.trim().split(/\s+/).length,i.metadata.hasInteractive=r.querySelectorAll("button, a, input, textarea, select").length>0,i}static analyzeRegion(t){let e=S.generateSelectors(t).css,n=t.querySelectorAll('button, [role="button"]'),r=t.querySelectorAll("a[href]"),i=t.querySelectorAll("input, textarea, select"),s=t.querySelectorAll("form"),a=t.querySelectorAll("ul, ol"),c=t.querySelectorAll("table"),l=t.querySelectorAll("img, video, audio"),d=n.length+r.length+i.length,u,m=t.getAttribute("aria-label");if(m)u=m;else if(t.getAttribute("aria-labelledby")){let A=t.getAttribute("aria-labelledby");if(A){let N=t.ownerDocument?.getElementById(A);N&&(u=N.textContent?.trim())}}else{let A=t.querySelector("h1, h2, h3");A&&(u=A.textContent?.trim())}let f=t.textContent?.trim()||"",y=f.length>50?`${f.substring(0,50)}...`:f,h={selector:e,interactiveCount:d,hasForm:s.length>0,hasList:a.length>0,hasTable:c.length>0,hasMedia:l.length>0};u&&(h.label=u);let w=t.getAttribute("role");return w&&(h.role=w),n.length>0&&(h.buttonCount=n.length),r.length>0&&(h.linkCount=r.length),i.length>0&&(h.inputCount=i.length),y.length>0&&(h.textPreview=y),h}static extractFormOverview(t){let e=t.querySelectorAll("form");return Array.from(e).map(n=>{let r=n.querySelectorAll("input, textarea, select"),i=S.generateSelectors(n).css,s="unknown";n.closest('header, [role="banner"]')?s="header":n.closest('nav, [role="navigation"]')?s="navigation":n.closest('main, [role="main"]')?s="main":n.closest('aside, [role="complementary"]')?s="sidebar":n.closest('footer, [role="contentinfo"]')&&(s="footer");let a,c=n.getAttribute("id")?.toLowerCase(),l=n.getAttribute("class")?.toLowerCase(),d=n.getAttribute("action")?.toLowerCase(),u=n.querySelector('input[type="email"]'),m=n.querySelector('input[type="password"]');n.querySelector('input[type="search"]')||c?.includes("search")||l?.includes("search")?a="search":m&&u?a="login":m?a="authentication":c?.includes("contact")||l?.includes("contact")?a="contact":c?.includes("subscribe")||l?.includes("subscribe")?a="subscription":(d?.includes("checkout")||l?.includes("checkout"))&&(a="checkout");let f={selector:i,location:s,inputCount:r.length};return a&&(f.purpose=a),f})}static calculateSummary(t,e,n){let r=t.querySelectorAll("button, a[href], input, textarea, select"),i=t.querySelectorAll('section, article, [role="region"]'),s=(e.modals?.length||0)>0,a=[".error",".alert-danger",'[role="alert"]'].some(u=>{let m=t.querySelector(u);return m?g.isVisible(m):!1}),c=[".loading",".spinner",'[aria-busy="true"]'].some(u=>{let m=t.querySelector(u);return m?g.isVisible(m):!1}),l={totalInteractive:r.length,totalForms:n.length,totalSections:i.length,hasModals:s,hasErrors:a,isLoading:c},d=e.main?.selector;return d&&(l.mainContentSelector=d),l}static generateSuggestions(t,e){let n=[];return e.hasErrors&&n.push("Page has error indicators - check error messages before interacting"),e.isLoading&&n.push("Page appears to be loading - wait or check loading state"),e.hasModals&&n.push("Modal/dialog is open - may need to interact with or close it first"),t.main&&t.main.interactiveCount>10&&n.push(`Main content has ${t.main.interactiveCount} interactive elements - consider filtering`),e.totalForms>0&&n.push(`Found ${e.totalForms} form(s) on the page`),t.main||n.push("No clear main content area detected - may need to explore regions"),n}static getTextContent(t,e){let n=t.textContent?.trim()||"";return e&&n.length>e?`${n.substring(0,e)}...`:n}}})),ut=v((()=>{})),dt=Z({ContentDetection:()=>L,MarkdownFormatter:()=>U,ProgressiveExtractor:()=>V,SelectorGenerator:()=>S,SmartDOMReader:()=>C,default:()=>C}),C,B=v((()=>{H(),D(),j(),at(),lt(),ut(),C=class ${options;constructor(t={}){this.options={mode:t.mode||"interactive",maxDepth:t.maxDepth||5,includeHidden:t.includeHidden||!1,includeShadowDOM:t.includeShadowDOM??!0,includeIframes:t.includeIframes||!1,viewportOnly:t.viewportOnly||!1,mainContentOnly:t.mainContentOnly||!1,customSelectors:t.customSelectors||[],...t.attributeTruncateLength!==void 0&&{attributeTruncateLength:t.attributeTruncateLength},...t.dataAttributeTruncateLength!==void 0&&{dataAttributeTruncateLength:t.dataAttributeTruncateLength},...t.textTruncateLength!==void 0&&{textTruncateLength:t.textTruncateLength},...t.filter!==void 0&&{filter:t.filter}}}extract(t=document,e){let n=Date.now(),r=t instanceof Document?t:t.ownerDocument,i={...this.options,...e},s=t instanceof Document?r:t;i.mainContentOnly&&t instanceof Document&&(s=L.findMainContent(r));let a=this.extractPageState(r),c=this.extractLandmarks(r),l=this.extractInteractiveElements(s,i),d={mode:i.mode,timestamp:n,page:a,landmarks:c,interactive:l};if(i.mode==="full"){let u=this.extractSemanticElements(s,i),m=this.extractMetadata(r,s,i);return{...d,semantic:u,metadata:m}}return d}extractPageState(t){let e=this.getFocusedElement(t);return{url:t.location?.href||"",title:t.title||"",hasErrors:this.detectErrors(t),isLoading:this.detectLoading(t),hasModals:this.detectModals(t),...e!==void 0&&{hasFocus:e}}}extractLandmarks(t){let e=L.detectLandmarks(t);return{navigation:this.elementsToSelectors(e.navigation||[]),main:this.elementsToSelectors(e.main||[]),forms:this.elementsToSelectors(e.form||[]),headers:this.elementsToSelectors(e.banner||[]),footers:this.elementsToSelectors(e.contentinfo||[]),articles:this.elementsToSelectors(e.region||[]),sections:this.elementsToSelectors(e.region||[])}}elementsToSelectors(t){return t.map(e=>S.generateSelectors(e).css)}extractInteractiveElements(t,e){let n=[],r=[],i=[],s=[];return t.querySelectorAll('button, [role="button"], input[type="button"], input[type="submit"]').forEach(a=>{if(this.shouldIncludeElement(a,e)){let c=g.extractElement(a,e);c&&n.push(c)}}),t.querySelectorAll("a[href]").forEach(a=>{if(this.shouldIncludeElement(a,e)){let c=g.extractElement(a,e);c&&r.push(c)}}),t.querySelectorAll('input:not([type="button"]):not([type="submit"]), textarea, select').forEach(a=>{if(this.shouldIncludeElement(a,e)){let c=g.extractElement(a,e);c&&i.push(c)}}),e.customSelectors&&e.customSelectors.forEach(a=>{t.querySelectorAll(a).forEach(c=>{if(this.shouldIncludeElement(c,e)){let l=g.extractElement(c,e);l&&s.push(l)}})}),{buttons:n,links:r,inputs:i,forms:this.extractForms(t,e),clickable:s}}extractForms(t,e){let n=[];return t.querySelectorAll("form").forEach(r=>{if(!this.shouldIncludeElement(r,e))return;let i=[],s=[];r.querySelectorAll('input:not([type="button"]):not([type="submit"]), textarea, select').forEach(d=>{let u=g.extractElement(d,e);u&&i.push(u)}),r.querySelectorAll('button, input[type="button"], input[type="submit"]').forEach(d=>{let u=g.extractElement(d,e);u&&s.push(u)});let a=r.getAttribute("action"),c=r.getAttribute("method"),l={selector:S.generateSelectors(r).css,inputs:i,buttons:s};a&&(l.action=a),c&&(l.method=c),n.push(l)}),n}extractSemanticElements(t,e){let n=[],r=[],i=[],s=[],a=[];return t.querySelectorAll("h1, h2, h3, h4, h5, h6").forEach(c=>{if(this.shouldIncludeElement(c,e)){let l=g.extractElement(c,e);l&&n.push(l)}}),t.querySelectorAll("img").forEach(c=>{if(this.shouldIncludeElement(c,e)){let l=g.extractElement(c,e);l&&r.push(l)}}),t.querySelectorAll("table").forEach(c=>{if(this.shouldIncludeElement(c,e)){let l=g.extractElement(c,e);l&&i.push(l)}}),t.querySelectorAll("ul, ol").forEach(c=>{if(this.shouldIncludeElement(c,e)){let l=g.extractElement(c,e);l&&s.push(l)}}),t.querySelectorAll('article, [role="article"]').forEach(c=>{if(this.shouldIncludeElement(c,e)){let l=g.extractElement(c,e);l&&a.push(l)}}),{headings:n,images:r,tables:i,lists:s,articles:a}}extractMetadata(t,e,n){let r=e.querySelectorAll("*"),i=e.querySelectorAll("button, a, input, textarea, select, h1, h2, h3, h4, h5, h6, img, table, ul, ol, article").length,s={totalElements:r.length,extractedElements:i};n.mainContentOnly&&e instanceof Element&&(s.mainContent=S.generateSelectors(e).css);let a=t.documentElement.getAttribute("lang");return a&&(s.language=a),s}shouldIncludeElement(t,e){return!(!e.includeHidden&&!g.isVisible(t)||e.viewportOnly&&!g.isInViewport(t)||e.filter&&!g.passesFilter(t,e.filter))}detectErrors(t){return[".error",".alert-danger",'[role="alert"]',".error-message"].some(e=>{let n=t.querySelector(e);return n?g.isVisible(n):!1})}detectLoading(t){return[".loading",".spinner",'[aria-busy="true"]',".loader"].some(e=>{let n=t.querySelector(e);return n?g.isVisible(n):!1})}detectModals(t){return['[role="dialog"]',".modal",".popup",".overlay"].some(e=>{let n=t.querySelector(e);return n?g.isVisible(n):!1})}getFocusedElement(t){let e=t.activeElement;if(e&&e!==t.body)return S.generateSelectors(e).css}static extractInteractive(t,e={}){return new $({...e,mode:"interactive"}).extract(t)}static extractFull(t,e={}){return new $({...e,mode:"full"}).extract(t)}static extractFromElement(t,e="interactive",n={}){return new $({...n,mode:e}).extract(t)}}}));B();var mt=new Set(["id","data-testid","role-aria","name","class-path","css-path"]);function _(o){let t=o.trim();return t.startsWith("/")||t.startsWith("(")||t.startsWith("./")}function ft(o){let t=o.selector.candidates;if(t&&t.length>0){let n=null;for(let r of t)mt.has(r.type)&&(!r.value||_(r.value)||(!n||r.score>n.score)&&(n=r));if(n)return n.value}let e=o.selector.css;return e&&!_(e)?e:null}function ht(o){let t=o.tag.toLowerCase(),e=o.interaction.role??o.attributes.role;return t==="a"&&(o.interaction.nav||o.attributes.href!=null)?"navigable":t==="input"||t==="select"||t==="textarea"||e==="textbox"||e==="combobox"||e==="listbox"||e==="spinbutton"||o.interaction.change&&!o.interaction.click?"input":t==="button"||e==="button"||o.interaction.click||o.interaction.submit?"clickable":"static"}function gt(o){let t={...o.attributes},e=o.interaction.role;return e&&!t.role&&(t.role=e),t}function pt(o,t){return t?[o.selector.css,o.selector.xpath,o.context.nearestForm,o.context.nearestSection,o.context.nearestMain,o.context.nearestNav,...o.selector.candidates?.map(n=>n.value)??[],...o.context.parentChain].some(n=>!!n&&n.includes(t)):!1}function z(o,t={}){let e=t.includeSemantic??!0,n=t.excludeSelector??".persona-host",r=t.maxTextLength??200,i=[o.interactive.buttons,o.interactive.links,o.interactive.inputs,o.interactive.clickable];e&&o.semantic&&i.push(o.semantic.headings,o.semantic.images,o.semantic.tables,o.semantic.lists,o.semantic.articles);let s=[],a=new Set,c=l=>{if(pt(l,n))return!0;let d=ft(l);if(d&&!a.has(d)&&(a.add(d),s.push({selector:d,tagName:l.tag.toLowerCase(),text:(l.text??"").trim().substring(0,r),role:l.interaction.role??l.attributes.role??null,interactivity:ht(l),attributes:gt(l)}),t.maxElements&&s.length>=t.maxElements))return!1;if(l.children){for(let u of l.children)if(!c(u))return!1}return!0};for(let l of i)if(l){for(let d of l)if(!c(d))return s}return s}var R=100;function X(o,t={}){if(o.length===0)return"No page elements found.";let e=t.mode??"structured",n=[];if(e==="structured"){let i=o.map(s=>s.formattedSummary).filter(s=>!!s&&s.length>0);i.length>0&&n.push(`Structured summaries:
10
10
  ${i.map(s=>`- ${s.split(`
11
11
  `).join(`
12
12
  `)}`).join(`
13
- `)}`)}let r={clickable:[],navigable:[],input:[],static:[]};for(let i of o)t==="structured"&&i.formattedSummary||r[i.interactivity].push(i);if(r.clickable.length>0){let i=r.clickable.map(s=>`- ${s.selector}: "${s.text.substring(0,R)}" (clickable)`);n.push(`Interactive elements:
13
+ `)}`)}let r={clickable:[],navigable:[],input:[],static:[]};for(let i of o)e==="structured"&&i.formattedSummary||r[i.interactivity].push(i);if(r.clickable.length>0){let i=r.clickable.map(s=>`- ${s.selector}: "${s.text.substring(0,R)}" (clickable)`);n.push(`Interactive elements:
14
14
  ${i.join(`
15
15
  `)}`)}if(r.navigable.length>0){let i=r.navigable.map(s=>`- ${s.selector}${s.attributes.href?`[href="${s.attributes.href}"]`:""}: "${s.text.substring(0,R)}" (navigable)`);n.push(`Navigation links:
16
16
  ${i.join(`
@@ -20,5 +20,5 @@ ${i.join(`
20
20
  ${i.join(`
21
21
  `)}`)}return n.join(`
22
22
 
23
- `)}function St(o,e){if(!o)return!0;let t=0;for(let n=0;n<e.length&&t<o.length;n++)e[n]===o[t]&&t++;return t===o.length}function yt(o,e){let t=o.toLowerCase(),n=e.toLowerCase();return t.startsWith(n)?0:o.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[\s\-_/.]+/).some(i=>i.toLowerCase().startsWith(n))?1:St(n,t)?2:3}function G(o,e){let t=o.recencyScore??0,n=e.recencyScore??0;return n!==t?n-t:o.label.localeCompare(e.label)}function Y(o,e){let t=e.trim();if(!t)return[...o].sort(G);let n=[];for(let r of o){let i=yt(r.label,t);i!==3&&n.push({item:r,tier:i})}return n.sort((r,i)=>r.tier!==i.tier?r.tier-i.tier:G(r.item,i.item)),n.map(r=>r.item)}function K(o={}){let e=o.mode??"interactive",t;if(o.root)t=E.extractFromElement(o.root,e,o.extractionOptions);else{let n=o.document??(typeof document<"u"?document:void 0);if(!n)return[];t=e==="full"?E.extractFull(n,o.extractionOptions):E.extractInteractive(n,o.extractionOptions)}return z(t,{includeSemantic:o.includeSemantic??e==="full",excludeSelector:o.excludeSelector,maxTextLength:o.maxTextLength,maxElements:o.maxElements})}function qt(o={}){let e=o.contextKey??"pageContext";return()=>{let t=K(o);return t.length===0?{}:{[e]:X(t)}}}var Et=2e3,Ct=o=>{switch(o){case"clickable":return"mouse-pointer-click";case"input":return"text-cursor-input";case"navigable":return"link";default:return"text"}},vt=o=>{let t=(o.attributes["aria-label"]||o.text||o.tagName).trim(),n=t.length>48?`${t.slice(0,47)}\u2026`:t||o.tagName,r=[o.role??o.tagName,o.interactivity].filter(Boolean);return{id:o.selector,label:n,description:r.join(" \xB7 "),iconName:Ct(o.interactivity),group:void 0}};function Pt(o={}){let e=o.id??"page",t=o.label??"Page",n=null,r=0,i=()=>{let s=K(o).map(a=>{let c=vt(a);return o.mapItem?o.mapItem(a,c):c});return r=Date.now(),s};return{id:e,label:t,resolveOn:"submit",search:s=>{let a=!n||Date.now()-r>Et;return(!n||s===""&&a)&&(n=i()),Y(n,s)},resolve:s=>{let a=o.document??(typeof document<"u"?document:void 0),c="";try{c=a?.querySelector(s.id)?.textContent?.trim()??""}catch{}return{llmAppend:`Page element "${s.label}" (${s.id}):
24
- ${c||"(no text)"}`,context:{selector:s.id}}}}}export{K as collectSmartDomContext,Pt as createSmartDomMentionSource,qt as createSmartDomReaderContextProvider,z as smartDomResultToEnriched};
23
+ `)}function xt(o,t){if(!o)return!0;let e=0;for(let n=0;n<t.length&&e<o.length;n++)t[n]===o[e]&&e++;return e===o.length}function bt(o,t){let e=o.toLowerCase(),n=t.toLowerCase();return e.startsWith(n)?0:o.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[\s\-_/.]+/).some(i=>i.toLowerCase().startsWith(n))?1:xt(n,e)?2:3}function G(o,t){let e=o.recencyScore??0,n=t.recencyScore??0;return n!==e?n-e:o.label.localeCompare(t.label)}function Y(o,t){let e=t.trim();if(!e)return[...o].sort(G);let n=[];for(let r of o){let i=bt(r.label,e);i!==3&&n.push({item:r,tier:i})}return n.sort((r,i)=>r.tier!==i.tier?r.tier-i.tier:G(r.item,i.item)),n.map(r=>r.item)}function K(o={}){let t=o.mode??"interactive",e;if(o.root)e=C.extractFromElement(o.root,t,o.extractionOptions);else{let n=o.document??(typeof document<"u"?document:void 0);if(!n)return[];e=t==="full"?C.extractFull(n,o.extractionOptions):C.extractInteractive(n,o.extractionOptions)}return z(e,{includeSemantic:o.includeSemantic??t==="full",excludeSelector:o.excludeSelector,maxTextLength:o.maxTextLength,maxElements:o.maxElements})}function Rt(o={}){let t=o.contextKey??"pageContext";return()=>{let e=K(o);return e.length===0?{}:{[t]:X(e)}}}var St=2e3,yt=o=>{switch(o){case"clickable":return"mouse-pointer-click";case"input":return"text-cursor-input";case"navigable":return"link";default:return"text"}},Et=o=>{let e=(o.attributes["aria-label"]||o.text||o.tagName).trim(),n=e.length>48?`${e.slice(0,47)}\u2026`:e||o.tagName,r=[o.role??o.tagName,o.interactivity].filter(Boolean);return{id:o.selector,label:n,description:r.join(" \xB7 "),iconName:yt(o.interactivity),group:void 0}};function Ot(o={}){let t=o.id??"page",e=o.label??"Page",n=null,r=0,i=()=>{let s=K(o).map(a=>{let c=Et(a);return o.mapItem?o.mapItem(a,c):c});return r=Date.now(),s};return{id:t,label:e,resolveOn:"submit",search:s=>{let a=!n||Date.now()-r>St;return(!n||s===""&&a)&&(n=i()),Y(n,s)},resolve:s=>{let a=o.document??(typeof document<"u"?document:void 0),c="";try{c=a?.querySelector(s.id)?.textContent?.trim()??""}catch{}return{llmAppend:`Page element "${s.label}" (${s.id}):
24
+ ${c||"(no text)"}`,context:{selector:s.id}}}}}export{K as collectSmartDomContext,Ot as createSmartDomMentionSource,Rt as createSmartDomReaderContextProvider,z as smartDomResultToEnriched};