@runtypelabs/persona 4.33.0 → 4.34.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 (186) hide show
  1. package/dist/activity-ui.d.cts +3 -15
  2. package/dist/activity-ui.d.ts +3 -15
  3. package/dist/animations/glyph-cycle.d.cts +1 -3
  4. package/dist/animations/glyph-cycle.d.ts +1 -3
  5. package/dist/animations/wipe.d.cts +1 -3
  6. package/dist/animations/wipe.d.ts +1 -3
  7. package/dist/approval-ui.cjs +2 -2
  8. package/dist/approval-ui.d.cts +3 -15
  9. package/dist/approval-ui.d.ts +3 -15
  10. package/dist/approval-ui.js +1 -1
  11. package/dist/artifacts-ui.cjs +1 -1
  12. package/dist/artifacts-ui.d.cts +3 -21
  13. package/dist/artifacts-ui.d.ts +3 -21
  14. package/dist/background-runtime.d.cts +2 -3
  15. package/dist/background-runtime.d.ts +2 -3
  16. package/dist/{chunk-gu34lr-P.js → chunk-Brdx4NCz.js} +1 -1
  17. package/dist/{chunk-dLJWKfOb.js → chunk-C-rux8Q9.js} +1 -1
  18. package/dist/{chunk-Ds_twaZn.js → chunk-C4v-HNhS.js} +1 -1
  19. package/dist/{chunk-Bkma5hIU.js → chunk-CE4seJxF.js} +1 -1
  20. package/dist/{chunk-D6U0E82p.js → chunk-CV8EPIhT.js} +1 -1
  21. package/dist/{chunk-ql5N2I_t.js → chunk-CWzHNuVK.js} +1 -1
  22. package/dist/{chunk-DbGLjU2P.js → chunk-CYpt7PsO.js} +1 -1
  23. package/dist/{chunk-DOZmcve8.js → chunk-Csr59G5V.js} +1 -1
  24. package/dist/{chunk-DW7Vg_l2.js → chunk-CxNPSY-b.js} +1 -1
  25. package/dist/chunk-Dqa_GOcj.js +1 -0
  26. package/dist/chunk-DsWv3EGF.js +1 -0
  27. package/dist/{chunk-C7-m0EmI.js → chunk-NUNdcnAZ.js} +1 -1
  28. package/dist/{chunk-CXQJG7pb.js → chunk-YMkMvAsa.js} +2 -2
  29. package/dist/{chunk-C-EHtpbB.js → chunk-h5aOI_Pa.js} +1 -1
  30. package/dist/chunk-kizhspe5.js +1 -0
  31. package/dist/client-dispatch.js +1 -1
  32. package/dist/client-history.js +1 -1
  33. package/dist/client-stream.js +1 -1
  34. package/dist/{code-generators-DqauYyfX.d.cts → code-generators-DPAqTcAz.d.cts} +0 -2
  35. package/dist/{code-generators-DqauYyfX.d.ts → code-generators-DPAqTcAz.d.ts} +0 -2
  36. package/dist/codegen.cjs +1 -1
  37. package/dist/codegen.d.cts +1 -1
  38. package/dist/codegen.d.ts +1 -1
  39. package/dist/codegen.js +1 -1
  40. package/dist/composer-actions-runtime.cjs +1 -1
  41. package/dist/composer-actions-runtime.d.cts +4 -20
  42. package/dist/composer-actions-runtime.d.ts +4 -20
  43. package/dist/composer-actions-runtime.js +1 -1
  44. package/dist/{composer-input-DnqGCXZz.d.ts → composer-input-i_FiUp6J.d.cts} +1 -7
  45. package/dist/{composer-input-DnqGCXZz.d.cts → composer-input-i_FiUp6J.d.ts} +1 -7
  46. package/dist/{composer-store-6Iwy6WLI.d.ts → composer-store-DhGNgG7Z.d.cts} +1 -3
  47. package/dist/{composer-store-6Iwy6WLI.d.cts → composer-store-DhGNgG7Z.d.ts} +1 -3
  48. package/dist/config-diagnostics.d.cts +0 -2
  49. package/dist/config-diagnostics.d.ts +0 -2
  50. package/dist/{context-mention-manager-B-rHF98n.d.ts → context-mention-manager-DL-xwGfL.d.cts} +2 -6
  51. package/dist/{context-mention-manager-B-rHF98n.d.cts → context-mention-manager-DL-xwGfL.d.ts} +2 -6
  52. package/dist/context-mentions-inline.cjs +1 -1
  53. package/dist/context-mentions-inline.d.cts +2 -4
  54. package/dist/context-mentions-inline.d.ts +2 -4
  55. package/dist/context-mentions-inline.js +1 -1
  56. package/dist/context-mentions.cjs +1 -1
  57. package/dist/context-mentions.d.cts +3 -9
  58. package/dist/context-mentions.d.ts +3 -9
  59. package/dist/{defaults-BuOjqUAG.d.ts → defaults-Bga2Xrsp.d.cts} +1 -5
  60. package/dist/{defaults-BuOjqUAG.d.cts → defaults-Bga2Xrsp.d.ts} +1 -5
  61. package/dist/dictation-runtime.cjs +1 -1
  62. package/dist/dictation-runtime.d.cts +4 -13
  63. package/dist/dictation-runtime.d.ts +4 -13
  64. package/dist/dictation-runtime.js +1 -1
  65. package/dist/{dom-context-DHTabIn7.d.cts → dom-context-Bw-_9Evh.d.cts} +0 -2
  66. package/dist/{dom-context-DHTabIn7.d.ts → dom-context-Bw-_9Evh.d.ts} +0 -2
  67. package/dist/event-stream-view.cjs +1 -1
  68. package/dist/event-stream-view.d.cts +3 -16
  69. package/dist/event-stream-view.d.ts +3 -16
  70. package/dist/{fallback-speech-engine-SqEfkGda.d.ts → fallback-speech-engine-kLdyPcmk.d.cts} +1 -3
  71. package/dist/{fallback-speech-engine-SqEfkGda.d.cts → fallback-speech-engine-kLdyPcmk.d.ts} +1 -3
  72. package/dist/{feature-preferences-DqAmje-2.d.ts → feature-preferences-CmwZGKrf.d.cts} +1 -5
  73. package/dist/{feature-preferences-DqAmje-2.d.cts → feature-preferences-CmwZGKrf.d.ts} +1 -5
  74. package/dist/forms-ui.d.cts +2 -4
  75. package/dist/forms-ui.d.ts +2 -4
  76. package/dist/{history-confirm-dialog-B3L7QNcO.d.cts → history-confirm-dialog-i46-lPN_.d.cts} +2 -14
  77. package/dist/{history-confirm-dialog-B3L7QNcO.d.ts → history-confirm-dialog-i46-lPN_.d.ts} +2 -14
  78. package/dist/history-shell.cjs +1 -1
  79. package/dist/history-shell.d.cts +8 -27
  80. package/dist/history-shell.d.ts +8 -27
  81. package/dist/history-shell.js +1 -1
  82. package/dist/history-view.d.cts +1 -1
  83. package/dist/history-view.d.ts +1 -1
  84. package/dist/icons-extra.cjs +1 -1
  85. package/dist/icons-extra.d.cts +0 -2
  86. package/dist/icons-extra.d.ts +0 -2
  87. package/dist/index.cjs +45 -45
  88. package/dist/index.cjs.map +1 -1
  89. package/dist/index.d.cts +10 -10
  90. package/dist/index.d.ts +10 -10
  91. package/dist/index.global.js +1 -1
  92. package/dist/index.global.js.map +1 -1
  93. package/dist/index.js +49 -49
  94. package/dist/index.js.map +1 -1
  95. package/dist/install.global.js +1 -1
  96. package/dist/install.global.js.map +1 -1
  97. package/dist/launcher.global.js +2 -2
  98. package/dist/launcher.global.js.map +1 -1
  99. package/dist/{loading-label-runtime-loader-JecjOfJS.d.ts → loading-label-runtime-loader-Ccr3ETd3.d.cts} +1 -3
  100. package/dist/{loading-label-runtime-loader-JecjOfJS.d.cts → loading-label-runtime-loader-Ccr3ETd3.d.ts} +1 -3
  101. package/dist/loading-label-runtime.cjs +1 -1
  102. package/dist/loading-label-runtime.d.cts +1 -1
  103. package/dist/loading-label-runtime.d.ts +1 -1
  104. package/dist/loading-label-runtime.js +1 -1
  105. package/dist/markdown-parsers.js +1 -1
  106. package/dist/{message-bubble-CBYtpDsT.d.ts → message-bubble-C6AVaH7f.d.cts} +20 -3
  107. package/dist/{message-bubble-CBYtpDsT.d.cts → message-bubble-C6AVaH7f.d.ts} +20 -3
  108. package/dist/{plugin-kit-C1mRjLgW.d.cts → plugin-kit-BVggqE3C.d.cts} +0 -2
  109. package/dist/{plugin-kit-C1mRjLgW.d.ts → plugin-kit-BVggqE3C.d.ts} +0 -2
  110. package/dist/plugin-kit.d.cts +1 -1
  111. package/dist/plugin-kit.d.ts +1 -1
  112. package/dist/preferences-runtime.cjs +1 -1
  113. package/dist/preferences-runtime.d.cts +1 -1
  114. package/dist/preferences-runtime.d.ts +1 -1
  115. package/dist/preferences-runtime.js +1 -1
  116. package/dist/{preview-_UJwwt2L.d.cts → preview-BMdRffo4.d.cts} +2 -6
  117. package/dist/{preview-_UJwwt2L.d.ts → preview-BMdRffo4.d.ts} +2 -6
  118. package/dist/{registry-B5ZV3K-h.d.ts → registry-B16l8s1b.d.cts} +1 -8
  119. package/dist/{registry-B5ZV3K-h.d.cts → registry-B16l8s1b.d.ts} +1 -8
  120. package/dist/{session-Bys8_XuB.d.cts → session-CtZHe7fc.d.cts} +8 -92
  121. package/dist/{session-Bys8_XuB.d.ts → session-CtZHe7fc.d.ts} +8 -92
  122. package/dist/session-reconnect.d.cts +2 -4
  123. package/dist/session-reconnect.d.ts +2 -4
  124. package/dist/smart-dom-reader.d.cts +2 -8
  125. package/dist/smart-dom-reader.d.ts +2 -8
  126. package/dist/testing.d.cts +0 -2
  127. package/dist/testing.d.ts +0 -2
  128. package/dist/theme-editor-preview.cjs +42 -42
  129. package/dist/theme-editor-preview.d.cts +1 -1
  130. package/dist/theme-editor-preview.d.ts +1 -1
  131. package/dist/theme-editor-preview.js +25 -25
  132. package/dist/theme-editor.cjs +25 -5
  133. package/dist/theme-editor.d.cts +2 -22
  134. package/dist/theme-editor.d.ts +2 -22
  135. package/dist/theme-editor.js +1 -1
  136. package/dist/theme-reference.cjs +1 -1
  137. package/dist/theme-reference.d.cts +2 -4
  138. package/dist/theme-reference.d.ts +2 -4
  139. package/dist/theme-reference.js +1 -1
  140. package/dist/{tool-loading-animation-d5qAQcwv.d.ts → tool-loading-animation-D2cyFvmM.d.cts} +1 -7
  141. package/dist/{tool-loading-animation-d5qAQcwv.d.cts → tool-loading-animation-D2cyFvmM.d.ts} +1 -7
  142. package/dist/{tooltip-BkW-8MnD.d.cts → tooltip-DbXkAuJL.d.cts} +0 -2
  143. package/dist/{tooltip-BkW-8MnD.d.ts → tooltip-DbXkAuJL.d.ts} +0 -2
  144. package/dist/{turn-activity-ui-q6fHVnx-.d.cts → turn-activity-ui-Do1Nd-Ow.d.cts} +2 -12
  145. package/dist/{turn-activity-ui-q6fHVnx-.d.ts → turn-activity-ui-Do1Nd-Ow.d.ts} +2 -12
  146. package/dist/turn-activity-ui.d.cts +1 -1
  147. package/dist/turn-activity-ui.d.ts +1 -1
  148. package/dist/{types-B_mj21jg.d.cts → types-BC7MRxO5.d.cts} +76 -29
  149. package/dist/{types-B_mj21jg.d.ts → types-BC7MRxO5.d.ts} +76 -29
  150. package/dist/ui-extras.js +3 -3
  151. package/dist/voice-client-tools.d.cts +1 -3
  152. package/dist/voice-client-tools.d.ts +1 -3
  153. package/dist/voice-runtime.cjs +1 -1
  154. package/dist/voice-runtime.d.cts +2 -12
  155. package/dist/voice-runtime.d.ts +2 -12
  156. package/dist/voice-runtime.js +2 -2
  157. package/dist/voice-worklet-player.d.cts +2 -6
  158. package/dist/voice-worklet-player.d.ts +2 -6
  159. package/dist/{webmcp-runtime-entry-ClEO3qdI.d.ts → webmcp-runtime-entry-B8g46vS0.d.cts} +1 -5
  160. package/dist/{webmcp-runtime-entry-ClEO3qdI.d.cts → webmcp-runtime-entry-B8g46vS0.d.ts} +1 -5
  161. package/dist/webmcp-runtime.d.cts +1 -1
  162. package/dist/webmcp-runtime.d.ts +1 -1
  163. package/dist/widget.css +1 -1
  164. package/package.json +4 -4
  165. package/src/components/event-stream-view.test.ts +5 -0
  166. package/src/components/message-bubble.ts +26 -6
  167. package/src/components/scroll-to-bottom.test.ts +135 -0
  168. package/src/components/scroll-to-bottom.ts +50 -13
  169. package/src/components/user-message-collapse.ts +117 -0
  170. package/src/defaults.ts +6 -0
  171. package/src/styles/widget.css +56 -0
  172. package/src/theme-reference.ts +2 -2
  173. package/src/types/theme.ts +29 -0
  174. package/src/types.ts +49 -5
  175. package/src/ui.scroll-additive.test.ts +219 -117
  176. package/src/ui.scroll.test.ts +176 -13
  177. package/src/ui.ts +230 -107
  178. package/src/ui.turn-activity.test.ts +7 -7
  179. package/src/ui.user-message-collapse.test.ts +540 -0
  180. package/src/utils/auto-follow.test.ts +0 -38
  181. package/src/utils/auto-follow.ts +0 -35
  182. package/src/utils/theme.test.ts +23 -0
  183. package/src/utils/tokens.ts +16 -0
  184. package/dist/chunk-CVMIncEY.js +0 -1
  185. package/dist/chunk-DVgzoVCB.js +0 -1
  186. package/dist/chunk-d54BJdKd.js +0 -1
@@ -1,8 +1,7 @@
1
- import { T as provideMarkdownParsers, f as buttons_d_exports, r as ComponentRenderer, t as ComponentContext } from "./registry-B5ZV3K-h.cjs";
2
- import { Li as PersonaArtifactRecord, Mi as PersonaArtifactFileMeta, Oi as PersonaArtifactCustomAction, k as AgentWidgetConfig } from "./types-B_mj21jg.cjs";
3
- import { t as LoadingLabelRuntime } from "./loading-label-runtime-loader-JecjOfJS.cjs";
1
+ import { T as provideMarkdownParsers, f as buttons_d_exports, r as ComponentRenderer, t as ComponentContext } from "./registry-B16l8s1b.cjs";
2
+ import { Li as PersonaArtifactRecord, Mi as PersonaArtifactFileMeta, Oi as PersonaArtifactCustomAction, k as AgentWidgetConfig } from "./types-BC7MRxO5.cjs";
3
+ import { t as LoadingLabelRuntime } from "./loading-label-runtime-loader-Ccr3ETd3.cjs";
4
4
  import { IconNode } from "lucide";
5
- //#region src/components/artifact-pane.d.ts
6
5
  type ArtifactPaneApi = {
7
6
  element: HTMLElement;
8
7
  /** Backdrop for mobile drawer (optional separate layer) */
@@ -56,8 +55,6 @@ export declare function createArtifactPane(config: AgentWidgetConfig, options: {
56
55
  /** User clicked the expand/collapse toggle: parent owns the state and calls back via setExpanded. */
57
56
  onToggleExpand?: () => void;
58
57
  }): ArtifactPaneApi;
59
- //#endregion
60
- //#region src/components/artifact-preview.d.ts
61
58
  /**
62
59
  * Clipboard payload for an artifact, shared by the pane copy control and the
63
60
  * inline chrome copy button so both derive the same text:
@@ -66,8 +63,6 @@ export declare function createArtifactPane(config: AgentWidgetConfig, options: {
66
63
  * - component artifacts → pretty-printed `{ component, props }` JSON
67
64
  */
68
65
  export declare function artifactCopyText(record: PersonaArtifactRecord | undefined): string;
69
- //#endregion
70
- //#region src/components/artifact-inline.d.ts
71
66
  /**
72
67
  * Built-in inline artifact block component (display: "inline").
73
68
  *
@@ -144,8 +139,6 @@ export declare function updateInlineArtifactBlocks(root: HTMLElement, artifacts:
144
139
  */
145
140
  export declare function hasLiveInlineArtifactBlock(el: HTMLElement): boolean;
146
141
  export declare const PersonaArtifactInline: (props: Record<string, unknown>, context: ComponentContext) => HTMLElement;
147
- //#endregion
148
- //#region src/components/artifact-card.d.ts
149
142
  /**
150
143
  * Built-in artifact reference card component.
151
144
  * Renders a compact clickable card in the chat thread that links to an artifact.
@@ -155,8 +148,6 @@ export declare const PersonaArtifactInline: (props: Record<string, unknown>, con
155
148
  * that can override the default card rendering.
156
149
  */
157
150
  export declare const PersonaArtifactCard: (props: Record<string, unknown>, context: ComponentContext) => HTMLElement;
158
- //#endregion
159
- //#region src/utils/artifact-file.d.ts
160
151
  /** Minimal record shape needed to compute download info. */
161
152
  interface ArtifactDownloadSource {
162
153
  title?: string;
@@ -181,8 +172,6 @@ export declare function triggerArtifactDownload(info: {
181
172
  mime: string;
182
173
  content: string;
183
174
  }): void;
184
- //#endregion
185
- //#region src/components/artifacts-deps.d.ts
186
175
  /**
187
176
  * Injected core dependencies for the lazy artifacts-ui chunk.
188
177
  *
@@ -205,8 +194,6 @@ interface ArtifactsUiDeps {
205
194
  };
206
195
  }
207
196
  export declare const initArtifactsUi: (deps: ArtifactsUiDeps) => void;
208
- //#endregion
209
- //#region src/icons-extra-loader.d.ts
210
197
  /**
211
198
  * Loader indirection for the lazy icons-extra chunk (the config-only tail of
212
199
  * the icon registry). Stays in the core bundle AND the critical launcher
@@ -225,8 +212,6 @@ type IconsExtraModule = {
225
212
  };
226
213
  /** Override how the chunk is fetched (each IIFE registers a sibling-URL loader). */
227
214
  declare const setIconsExtraLoader: (l: () => Promise<IconsExtraModule>) => void;
228
- //#endregion
229
- //#region src/artifact-resizer.d.ts
230
215
  /** Resizing is owned by the optional artifact pane and dies with that pane. */
231
216
  export declare function createArtifactResizer(options: {
232
217
  mount: HTMLElement;
@@ -241,10 +226,7 @@ export declare function createArtifactResizer(options: {
241
226
  update: () => void;
242
227
  destroy(): void;
243
228
  };
244
- //#endregion
245
- //#region src/components/artifact-styles.d.ts
246
229
  /** Artifact styles travel with the renderer, including into shadow roots. */
247
230
  export declare const ensureArtifactStyles: (target: Node) => void;
248
- //#endregion
249
231
  export { type ArtifactPaneApi, type ArtifactsUiDeps, provideMarkdownParsers as __provideMarkdownParsers, setIconsExtraLoader as __setIconsExtraLoader };
250
232
  export {}
@@ -1,8 +1,7 @@
1
- import { T as provideMarkdownParsers, f as buttons_d_exports, r as ComponentRenderer, t as ComponentContext } from "./registry-B5ZV3K-h.js";
2
- import { Li as PersonaArtifactRecord, Mi as PersonaArtifactFileMeta, Oi as PersonaArtifactCustomAction, k as AgentWidgetConfig } from "./types-B_mj21jg.js";
3
- import { t as LoadingLabelRuntime } from "./loading-label-runtime-loader-JecjOfJS.js";
1
+ import { T as provideMarkdownParsers, f as buttons_d_exports, r as ComponentRenderer, t as ComponentContext } from "./registry-B16l8s1b.js";
2
+ import { Li as PersonaArtifactRecord, Mi as PersonaArtifactFileMeta, Oi as PersonaArtifactCustomAction, k as AgentWidgetConfig } from "./types-BC7MRxO5.js";
3
+ import { t as LoadingLabelRuntime } from "./loading-label-runtime-loader-Ccr3ETd3.js";
4
4
  import { IconNode } from "lucide";
5
- //#region src/components/artifact-pane.d.ts
6
5
  type ArtifactPaneApi = {
7
6
  element: HTMLElement;
8
7
  /** Backdrop for mobile drawer (optional separate layer) */
@@ -56,8 +55,6 @@ export declare function createArtifactPane(config: AgentWidgetConfig, options: {
56
55
  /** User clicked the expand/collapse toggle: parent owns the state and calls back via setExpanded. */
57
56
  onToggleExpand?: () => void;
58
57
  }): ArtifactPaneApi;
59
- //#endregion
60
- //#region src/components/artifact-preview.d.ts
61
58
  /**
62
59
  * Clipboard payload for an artifact, shared by the pane copy control and the
63
60
  * inline chrome copy button so both derive the same text:
@@ -66,8 +63,6 @@ export declare function createArtifactPane(config: AgentWidgetConfig, options: {
66
63
  * - component artifacts → pretty-printed `{ component, props }` JSON
67
64
  */
68
65
  export declare function artifactCopyText(record: PersonaArtifactRecord | undefined): string;
69
- //#endregion
70
- //#region src/components/artifact-inline.d.ts
71
66
  /**
72
67
  * Built-in inline artifact block component (display: "inline").
73
68
  *
@@ -144,8 +139,6 @@ export declare function updateInlineArtifactBlocks(root: HTMLElement, artifacts:
144
139
  */
145
140
  export declare function hasLiveInlineArtifactBlock(el: HTMLElement): boolean;
146
141
  export declare const PersonaArtifactInline: (props: Record<string, unknown>, context: ComponentContext) => HTMLElement;
147
- //#endregion
148
- //#region src/components/artifact-card.d.ts
149
142
  /**
150
143
  * Built-in artifact reference card component.
151
144
  * Renders a compact clickable card in the chat thread that links to an artifact.
@@ -155,8 +148,6 @@ export declare const PersonaArtifactInline: (props: Record<string, unknown>, con
155
148
  * that can override the default card rendering.
156
149
  */
157
150
  export declare const PersonaArtifactCard: (props: Record<string, unknown>, context: ComponentContext) => HTMLElement;
158
- //#endregion
159
- //#region src/utils/artifact-file.d.ts
160
151
  /** Minimal record shape needed to compute download info. */
161
152
  interface ArtifactDownloadSource {
162
153
  title?: string;
@@ -181,8 +172,6 @@ export declare function triggerArtifactDownload(info: {
181
172
  mime: string;
182
173
  content: string;
183
174
  }): void;
184
- //#endregion
185
- //#region src/components/artifacts-deps.d.ts
186
175
  /**
187
176
  * Injected core dependencies for the lazy artifacts-ui chunk.
188
177
  *
@@ -205,8 +194,6 @@ interface ArtifactsUiDeps {
205
194
  };
206
195
  }
207
196
  export declare const initArtifactsUi: (deps: ArtifactsUiDeps) => void;
208
- //#endregion
209
- //#region src/icons-extra-loader.d.ts
210
197
  /**
211
198
  * Loader indirection for the lazy icons-extra chunk (the config-only tail of
212
199
  * the icon registry). Stays in the core bundle AND the critical launcher
@@ -225,8 +212,6 @@ type IconsExtraModule = {
225
212
  };
226
213
  /** Override how the chunk is fetched (each IIFE registers a sibling-URL loader). */
227
214
  declare const setIconsExtraLoader: (l: () => Promise<IconsExtraModule>) => void;
228
- //#endregion
229
- //#region src/artifact-resizer.d.ts
230
215
  /** Resizing is owned by the optional artifact pane and dies with that pane. */
231
216
  export declare function createArtifactResizer(options: {
232
217
  mount: HTMLElement;
@@ -241,10 +226,7 @@ export declare function createArtifactResizer(options: {
241
226
  update: () => void;
242
227
  destroy(): void;
243
228
  };
244
- //#endregion
245
- //#region src/components/artifact-styles.d.ts
246
229
  /** Artifact styles travel with the renderer, including into shadow roots. */
247
230
  export declare const ensureArtifactStyles: (target: Node) => void;
248
- //#endregion
249
231
  export { type ArtifactPaneApi, type ArtifactsUiDeps, provideMarkdownParsers as __provideMarkdownParsers, setIconsExtraLoader as __setIconsExtraLoader };
250
232
  export {}
@@ -1,5 +1,4 @@
1
- import { Ct as AgentWidgetMessage, Li as PersonaArtifactRecord, Ui as ResumableHandle, Wr as ConversationExecutionState, Xn as BackgroundConversationAdapter, mn as AgentWidgetStreamCheckpoint } from "./types-B_mj21jg.cjs";
2
- //#region src/session-background.d.ts
1
+ import { Ct as AgentWidgetMessage, Li as PersonaArtifactRecord, Ui as ResumableHandle, Wr as ConversationExecutionState, Xn as BackgroundConversationAdapter, mn as AgentWidgetStreamCheckpoint } from "./types-BC7MRxO5.cjs";
3
2
  type BackgroundCheckpoint = {
4
3
  conversationId: string;
5
4
  handle: ResumableHandle;
@@ -21,5 +20,5 @@ export declare class BackgroundConversationController {
21
20
  take(conversationId: string): BackgroundCheckpoint | undefined;
22
21
  clear(conversationId?: string): void;
23
22
  }
24
- //#endregion
23
+ export {};
25
24
  export {}
@@ -1,5 +1,4 @@
1
- import { Ct as AgentWidgetMessage, Li as PersonaArtifactRecord, Ui as ResumableHandle, Wr as ConversationExecutionState, Xn as BackgroundConversationAdapter, mn as AgentWidgetStreamCheckpoint } from "./types-B_mj21jg.js";
2
- //#region src/session-background.d.ts
1
+ import { Ct as AgentWidgetMessage, Li as PersonaArtifactRecord, Ui as ResumableHandle, Wr as ConversationExecutionState, Xn as BackgroundConversationAdapter, mn as AgentWidgetStreamCheckpoint } from "./types-BC7MRxO5.js";
3
2
  type BackgroundCheckpoint = {
4
3
  conversationId: string;
5
4
  handle: ResumableHandle;
@@ -21,5 +20,5 @@ export declare class BackgroundConversationController {
21
20
  take(conversationId: string): BackgroundCheckpoint | undefined;
22
21
  clear(conversationId?: string): void;
23
22
  }
24
- //#endregion
23
+ export {};
25
24
  export {}
@@ -1,4 +1,4 @@
1
- import"./chunk-Bb41bKyp.js";import{i as e}from"./chunk-BAdIgC5d.js";import{i as t,l as n,t as r,u as i}from"./chunk-BRM3bHcJ.js";async function a(e,t,n,r){let i={"Content-Type":`application/json`,...e.headers};e.getHeaders&&Object.assign(i,await e.getHeaders());let a={executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0},o=(t,n)=>fetch(`${e.clientApiBase()}${t}`,{method:`POST`,headers:i,body:JSON.stringify({...n,...a})}),s=`/v1/agents/${t.agentId}/approve`;if(!e.isClientTokenMode())return o(s);let{sessionId:c}=await e.initSession(),l=await o(`/v1/client/approve`,{sessionId:c,...r?.assistantMessageId?{assistantMessageId:r.assistantMessageId}:{}});if(l.status===404){let e=await l.clone().json().catch(()=>null);if(!e||e.error===`Not Found`)return o(s)}return l}async function o(e,t,n,r){let a=e.isClientTokenMode(),o=a?e.getClientApiUrl(`resume`):`${e.config.apiUrl?.replace(/\/+$/,``)||`https://api.runtype.com`}/resume`,s,c=null;if(a){let t=await e.initSession();s=t.sessionId,t.durableRecovery?.enabled===!0&&(c=await e.readVisitorToken())}let l={"Content-Type":`application/json`,...c?{"X-Visitor-Token":c}:{},...e.headers};e.getHeaders&&Object.assign(l,await e.getHeaders());let u={executionId:t,toolOutputs:n,streamResponse:r?.streamResponse??!0,...r?.after?{after:r.after}:{}};if(s&&(u.sessionId=s,r?.assistantMessageId&&(u.assistantMessageId=r.assistantMessageId)),a&&s){let t=[...i(e.config),...await(await e.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:n,commit:a}=await e.sendWithClientToolsDiff(s,t,t=>{let n={...u,...t};return e.debug&&console.debug(`[AgentWidgetClient] client token resume`,n),fetch(o,{method:`POST`,headers:l,body:JSON.stringify(n),signal:r?.signal})},{emptyMeansReplace:!0});return n.ok&&a(),n}return fetch(o,{method:`POST`,headers:l,body:JSON.stringify(u),signal:r?.signal})}const s=e=>e===`commentary`||e===`partial_answer`||e===`final_answer`?e:void 0;function c(e){let t=e.toLowerCase(),n=t===`text/plain`?`txt`:t===`text/markdown`?`md`:void 0;if(n)return`attachment.${n}`;let r=t.indexOf(`/`);if(r>0){let e=t.slice(r+1).split(`;`)[0]?.trim()??``;if(e&&e!==`octet-stream`&&/^[a-z0-9.+-]+$/i.test(e))return`attachment.${e}`}return`attachment`}const l=e=>/^[{[<]/.test(e);function u(e,t){if(!e)return t;let r=e.trim(),i=t.trim();if(!r)return t;if(!i)return e;let a=l(r);if(!l(i))return e;if(!a||i.startsWith(r))return t;let o=n(e);return n(t)!==null&&o===null?t:e}async function d(e,t,n,r,i,a,o){if(!e.parseSSEEvent)return!1;try{let s=await e.parseSSEEvent(t);if(s===null)return!1;let c=e=>{let t={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`assistant`,sequence:a(),...e!==void 0&&{partId:e}};return r.current=t,i(t),t},l=e=>r.current?r.current:c(e);if(s.text!==void 0){s.partId!==void 0&&o.current!==null&&s.partId!==o.current&&(r.current&&(r.current.streaming=!1,i(r.current)),c(s.partId)),s.partId!==void 0&&(o.current=s.partId);let e=l(s.partId);s.partId!==void 0&&!e.partId&&(e.partId=s.partId),e.content+=s.text,i(e)}return s.done&&(r.current&&(r.current.streaming=!1,i(r.current)),o.current=null,n({type:`status`,status:`idle`})),s.error&&(o.current=null,n({type:`error`,error:Error(s.error)})),!0}catch(e){return typeof console<`u`&&console.error(`[AgentWidget] parseSSEEvent error:`,e),!1}}async function ee(i,a,o,l,ee,f,p,m){let h=i.streamGeneration(),g=a.getReader();i.streamReaders.add(g);let te=!!i.config().backgroundConversations,ne=()=>{te&&g.cancel().catch(()=>{})};f?.addEventListener(`abort`,ne,{once:!0});let re=new TextDecoder,_=``,ie=Date.now(),ae=0,v=()=>ie+ae++,oe=e=>({...e,chunks:e.chunks?[...e.chunks]:void 0}),y=e=>({...e,reasoning:e.reasoning?{...e.reasoning,chunks:[...e.reasoning.chunks]}:void 0,toolCall:e.toolCall?oe(e.toolCall):void 0,tools:e.tools?.map(oe)}),se=e=>{if(e.role!==`assistant`||e.variant)return!0;let t=Array.isArray(e.contentParts)&&e.contentParts.length>0,n=typeof e.rawContent==`string`&&e.rawContent.trim()!==``;return typeof e.content==`string`&&e.content.trim()!==``||t||n||!!e.stopReason},b=e=>{!f?.aborted&&h===i.streamGeneration()&&se(e)&&o({type:`message`,message:y(e)})},x=null,S=null,C={current:null},ce={current:null},w=null,T=``,E=new Map(m?.textPhases),D=/* @__PURE__ */ new Map,O=/* @__PURE__ */ new Map,k=/* @__PURE__ */ new Map,A=/* @__PURE__ */ new Map,j=/* @__PURE__ */ new Map,M=l,N=!1,P=p?.find(e=>e.id===l);P&&(x=y(P),x.streaming=m?.openAssistant??!0,N=!0,w=P.agentMetadata?.textBlockId??null,T=P.rawContent??P.content,S=x,m&&!m.openAssistant&&(x=null)),m&&(w=m.textBlockId,T=m.rawText,m.nestedParents.forEach(([e,t])=>D.set(e,t)),m.nestedRaw.forEach(([e,t])=>k.set(e,t)));for(let e of p??[]){e.variant===`tool`&&e.toolCall?.id&&j.set(e.toolCall.id,y(e)),e.variant===`reasoning`&&e.reasoning?.id&&A.set(e.reasoning.id,y(e));let t=e.agentMetadata?.textBlockId;t&&(O.set(t,e.id===x?.id?x:y(e)),e.agentMetadata?.phase&&E.set(t,e.agentMetadata.phase));let n=e.agentMetadata?.parentToolId;t&&n&&(D.set(t,n),k.set(t,e.rawContent??e.content))}let le=()=>{if(x)return x;let e,t=``,n=w;return!N&&M?(e=M,N=!0,t=ee??``):e=M&&n?`${M}_${n}`:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,x={id:e,role:`assistant`,content:t,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:v()},b(x),x},F=(e,t)=>{let n=A.get(e);if(n)return n;let r={id:`reason-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`reasoning`,agentMetadata:{executionId:t},sequence:v(),reasoning:{id:e,status:`streaming`,chunks:[]}};return A.set(e,r),b(r),r},I=/* @__PURE__ */ new Set,L=/* @__PURE__ */ new Map,R=/* @__PURE__ */ new Set;for(let e of p??[])if(e.id.startsWith(`artifact-ref-`)){let t=e.id.slice(13);R.add(t),L.set(t,y(e))}m?.artifactTools.forEach(e=>I.add(e));let z=/* @__PURE__ */ new Map;m?.artifactContent.forEach(([e,t])=>z.set(e,{...t}));let ue=e=>{if(!e)return!1;let t=e.replace(/_+/g,`_`).replace(/^_|_$/g,``);return t===`emit_artifact_markdown`||t===`emit_artifact_component`},B=(e,t,n)=>{let r=j.get(e),i={...r?.agentMetadata,executionId:t??r?.agentMetadata?.executionId,iteration:n??r?.agentMetadata?.iteration??(Y||void 0)};if(r)return r.agentMetadata=i,r;let a={id:`tool-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`tool`,agentMetadata:i,sequence:v(),toolCall:{id:e,status:`pending`}};return j.set(e,a),b(a),a},de=e=>{if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`){let t=Number(e);if(Number.isFinite(t))return t;let n=Date.parse(e);if(!Number.isNaN(n))return n}return Date.now()},V=e=>{if(typeof e==`string`)return e;if(e==null)return``;try{return JSON.stringify(e)}catch{return String(e)}},H=/* @__PURE__ */ new Map,U=/* @__PURE__ */ new Map,fe=(e,t)=>{let r=V(t),i=u(U.get(e.id),r);e.rawContent=i;let a=H.get(e.id),o=t=>{let n=e.content??``;t.trim()!==``&&(!n.trim()||t.startsWith(n)||t.trimStart().startsWith(n.trim()))&&(e.content=t)},s=()=>{let t=a?.close?.();t instanceof Promise&&t.catch(()=>{}),H.delete(e.id),U.delete(e.id),e.streaming=!1,b(e)};if(!a){o(r),s();return}let c=n(i);if(c!==null&&c.trim()!==``){o(c),s();return}let l=e=>{let t=typeof e==`string`?e:e?.text??null;if(t!==null&&t.trim()!==``)return t;let n=a.getExtractedText();return n!==null&&n.trim()!==``?n:r},d;try{d=a.processChunk(i)}catch{o(r),s();return}d instanceof Promise?d.then(e=>{o(l(e)),s()}).catch(()=>{o(r),s()}):(o(l(d)),s())},W=null,pe=p?.find(e=>e.id===m?.sealedFlowMessageId);pe&&(W=y(pe));let me=(e,t,n)=>{e.rawContent=t,H.has(e.id)||H.set(e.id,i.createStreamParser());let r=H.get(e.id),a=/^[{[]/.test(t.trim());a&&U.set(e.id,t);let o=()=>{e.content+=n,U.delete(e.id),H.delete(e.id),e.rawContent=void 0,b(e)};if(r.__isPlainTextParser===!0){o();return}let s=n=>{let r=typeof n==`string`?n:n?.text??null;r!==null&&r.trim()!==``?(e.content=r,b(e)):!a&&!t.trim().startsWith(`<`)&&o()},c=r.processChunk(t);c instanceof Promise?c.then(s).catch(o):s(c)},G=(e,t)=>{let r=t??e.content;if(r==null||r===``){e.streaming=!1,b(e);return}let i=U.get(e.id)??V(r);e.rawContent=i;let a=H.get(e.id),o=null,s=!1;if(a&&(o=a.getExtractedText(),o===null&&(o=n(i)),o===null)){let t=a.processChunk(i);t instanceof Promise?(s=!0,t.then(t=>{let n=typeof t==`string`?t:t?.text??null;n!==null&&(e.content=n,e.streaming=!1,H.delete(e.id),U.delete(e.id),b(e))}).catch(()=>{})):o=typeof t==`string`?t:t?.text??null}if(!s){o!==null&&o.trim()!==``?e.content=o:U.has(e.id)||(e.content=V(r));let t=H.get(e.id);if(t){let n=t.close?.();n instanceof Promise&&n.catch(()=>{}),H.delete(e.id)}U.delete(e.id),e.streaming=!1,b(e)}},he=(e,t,n,r)=>{let i=O.get(e);if(i)return i;let a={id:`nested-${t}-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:v(),...n?{variant:n}:{},...n===`reasoning`?{reasoning:{id:e,status:`streaming`,chunks:[]}}:{},agentMetadata:{parentToolId:t,textBlockId:e,executionId:r,phase:E.get(e)}};return O.set(e,a),b(a),a},K=[],q,J=/* @__PURE__ */ new Map;m?.media.forEach(([e,t])=>J.set(e,{...t,parts:[...t.parts]}));let Y=m?.iteration??0,X=m?.executionKind??`agent`,Z=m?.executionKindResolved??!1,Q=m?.turnId??null,$=null,ge=i.config().iterationDisplay??`separate`;q=()=>{for(let n=0;n<K.length;n++){let a=K[n];if(!Z&&X!==`flow`&&typeof a.stepType==`string`&&(X=`flow`),a.type===`reasoning_start`){let e=typeof a.id==`string`?a.id:null,t=typeof a.parentToolCallId==`string`&&a.parentToolCallId?a.parentToolCallId:null;if(e&&t){D.set(e,t),he(e,t,`reasoning`,a.executionId);continue}let n=a.id,r=F(n,a.executionId);r.reasoning=r.reasoning??{id:n,status:`streaming`,chunks:[]},r.reasoning.startedAt=r.reasoning.startedAt??Date.now(),r.reasoning.completedAt=void 0,r.reasoning.durationMs=void 0,(a.scope===`loop`||a.scope===`turn`)&&(r.reasoning.scope=a.scope),r.streaming=!0,r.reasoning.status=`streaming`,b(r)}else if(a.type===`reasoning_delta`){let e=typeof a.id==`string`?a.id:null;if(e&&D.has(e)&&O.has(e)){let t=O.get(e),n=a.delta;n&&t.reasoning&&(t.reasoning.chunks.push(String(n)),b(t));continue}let t=a.id,n=F(t,a.executionId);n.reasoning=n.reasoning??{id:t,status:`streaming`,chunks:[]},n.reasoning.startedAt=n.reasoning.startedAt??Date.now(),a.delta&&n.reasoning.chunks.push(a.delta),n.reasoning.status=`streaming`,n.streaming=!0,b(n)}else if(a.type===`reasoning_complete`){let e=typeof a.id==`string`?a.id:null;if(e&&D.has(e)&&O.has(e)){let t=O.get(e);if(t.reasoning){let e=typeof a.text==`string`?a.text:``;e&&t.reasoning.chunks.length===0&&t.reasoning.chunks.push(e),t.reasoning.status=`complete`,t.streaming=!1,b(t)}D.delete(e),O.delete(e);continue}let t=a.id,n=typeof a.text==`string`?a.text:``;!A.get(t)&&(n||a.scope===`loop`)&&F(t,a.executionId);let r=A.get(t);if(r?.reasoning){(a.scope===`loop`||a.scope===`turn`)&&(r.reasoning.scope=a.scope),n&&r.reasoning.chunks.length===0&&r.reasoning.chunks.push(n),r.reasoning.status=`complete`,r.reasoning.completedAt=Date.now();let e=r.reasoning.startedAt??Date.now();r.reasoning.durationMs=Math.max(0,(r.reasoning.completedAt??Date.now())-e),r.streaming=!1,b(r)}}else if(a.type===`tool_start`){x&&=(x.streaming=!1,b(x),null),typeof a.iteration==`number`&&(Y=a.iteration);let e=a.toolCallId,t=a.toolName;if(ue(t)){I.add(e);continue}let n=B(e,a.executionId,a.iteration),r=n.toolCall??{id:e,status:`pending`};r.name=t??r.name,r.status=`running`,r.success=void 0,r.error=void 0,r.duration=void 0,a.parameters!==void 0&&(r.args=a.parameters),r.startedAt=r.startedAt??de(a.startedAt),r.completedAt=void 0,r.durationMs=void 0,n.toolCall=r,n.streaming=!0,b(n)}else if(a.type===`tool_output_delta`){let e=a.toolCallId;if(I.has(e))continue;let t=B(e,a.executionId),n=t.toolCall??{id:e,status:`running`};n.startedAt=n.startedAt??Date.now();let r=a.delta;r&&(n.chunks=n.chunks??[],n.chunks.push(String(r))),n.status=`running`,t.toolCall=n,t.streaming=!0,b(t)}else if(a.type===`tool_complete`){let e=a.toolCallId;if(I.has(e)){I.delete(e);continue}let t=B(e,a.executionId,a.iteration),n=t.toolCall??{id:e,status:`running`};n.status=`complete`,a.result!==void 0&&(n.result=a.result),n.name=a.toolName??n.name,n.success=a.success,n.error=a.error,n.completedAt=Date.now();let r=a.executionTime;if(typeof r==`number`)n.durationMs=r,n.duration=r;else{let e=n.startedAt??Date.now();n.durationMs=Math.max(0,(n.completedAt??Date.now())-e)}t.toolCall=n,t.streaming=!1,b(t)}else if(a.type===`await`&&a.toolName){let t=typeof a.toolCallId==`string`&&a.toolCallId.length>0?a.toolCallId:void 0,n=t??a.toolId??`local-${v()}`,r=B(n,a.executionId),i=a.toolName,o=a.origin===`webmcp`&&!e(i)?`webmcp:${i}`:i,s=e(o),c=r.toolCall??{id:n,status:`pending`};c.name=o,c.args=a.parameters,c.status=s?`running`:`complete`,c.chunks=c.chunks??[],c.startedAt=c.startedAt??de(a.awaitedAt),s?(c.completedAt=void 0,c.duration=void 0,c.durationMs=void 0):c.completedAt=c.completedAt??c.startedAt,r.toolCall=c,r.streaming=!1,r.agentMetadata={...r.agentMetadata,executionId:a.executionId??r.agentMetadata?.executionId,awaitingLocalTool:!0,...t?{webMcpToolCallId:t}:{}},b(r)}else if(a.type===`text_start`){let e=typeof a.id==`string`?a.id:null;if(e){let t=s(a.phase);t?E.set(e,t):E.delete(e)}let t=typeof a.parentToolCallId==`string`&&a.parentToolCallId?a.parentToolCallId:null;if(e&&t){D.set(e,t);continue}let n=x;n&&(X===`flow`?(G(n),W=n):(n.streaming=!1,b(n)),x=null),w=e??w,T=``}else if(a.type===`text_delta`){let e=typeof a.id==`string`?a.id:null,t=e?D.get(e):void 0;if(e&&t){let n=typeof a.delta==`string`?a.delta:``,r=(k.get(e)??``)+n;if(k.set(e,r),r.trim()===``)continue;let i=he(e,t,void 0,a.executionId);me(i,r,n);continue}w=e??w;let n=typeof a.delta==`string`?a.delta:``;if(T+=n,X===`flow`&&T.trim()===``)continue;let r=le();r.agentMetadata={textBlockId:w??void 0,phase:E.get(w??``),executionId:a.executionId,iteration:Y,...X===`flow`?{}:{turnId:Q??void 0,agentName:$?.agentName}},w&&O.set(w,r),me(r,T,n),S=r}else if(a.type===`text_complete`){let e=typeof a.id==`string`?a.id:null;e&&E.delete(e);let t=e?O.get(e):x,n=s(a.phase);if(t&&n&&(t.agentMetadata={...t.agentMetadata,providerPhase:n}),e&&D.has(e)){let t=O.get(e);t&&G(t),D.delete(e),k.delete(e),O.delete(e);continue}if(e&&t!==x){t&&(t.streaming=!1,b(t));continue}let r=x;r&&(X===`flow`?(G(r),W=r):((r.content??``)===``&&typeof a.text==`string`&&(r.content=a.text),r.streaming=!1,b(r)),x=null),w=null,T=``}else if(a.type===`step_complete`){if(a.stepType===`tool`)continue;if(a.success===!1){let e=a.error||`Step failed`;o({type:`error`,error:Error(e)});let t=x;t&&t.streaming&&(t.streaming=!1,b(t)),o({type:`status`,status:`idle`});continue}{let e=W;W=null;let t=a.stopReason,n=(a.result&&typeof a.result==`object`?a.result:null)?.response;if(e)t&&(e.stopReason=t),n==null?e.streaming!==!1&&(H.delete(e.id),U.delete(e.id),e.streaming=!1,b(e)):fe(e,n);else{let e=n!=null&&n!==``;if(e||t&&t!==`end_turn`&&t!==`unknown`){let r=le();t&&(r.stopReason=t),e?G(r,n):(r.streaming=!1,b(r))}}continue}}else if(a.type===`execution_start`)X=a.kind===`flow`?`flow`:`agent`,Z=!0,i.config().backgroundConversations&&o({type:`status`,status:`connected`,executionId:a.executionId}),X===`agent`&&($={executionId:a.executionId,agentId:a.agentId??`virtual`,agentName:a.agentName??``});else if(a.type===`turn_start`){let e=typeof a.iteration==`number`?a.iteration:Y;if(e!==Y){if(ge===`separate`&&e>1){let e=x;e&&(e.streaming=!1,b(e),x=null)}Y=e}Q=typeof a.id==`string`?a.id:null,S=null}else if(a.type===`tool_input_delta`){let e=a.toolCallId;if(e){let t=j.get(e);t?.toolCall&&(t.toolCall.chunks=t.toolCall.chunks??[],t.toolCall.chunks.push(a.delta??``),b(t))}}else if(a.type===`tool_input_complete`){if(I.has(a.toolCallId))continue;let e=B(a.toolCallId,a.executionId),t=e.toolCall;t.args=a.parameters,t.name=a.toolName??t.name,b(e)}else if(a.type===`turn_complete`){let e=a.stopReason,t=x??S;if(e&&t!==null){let n=a.id;(!n||t.agentMetadata?.turnId===n)&&(t.stopReason=e,b(t))}Q===a.id&&(Q=null)}else if(a.type===`media_start`){let e=String(a.id);J.set(e,{mediaType:typeof a.mediaType==`string`?a.mediaType:void 0,toolCallId:a.toolCallId,parts:[]})}else if(a.type===`media_delta`){let e=J.get(String(a.id));e&&typeof a.delta==`string`&&e.parts.push(a.delta)}else if(a.type===`media_complete`){let e=String(a.id),t=J.get(e);J.delete(e);let n=(typeof a.mediaType==`string`?a.mediaType:void 0)??t?.mediaType??`application/octet-stream`,r=typeof a.data==`string`?a.data:void 0,i=typeof a.url==`string`?a.url:t&&t.parts.length>0?t.parts.join(``):void 0,o=null;if(r)o={type:`media`,data:r,mediaType:n};else if(i){let e=n.toLowerCase();o={type:e===`image`||e.startsWith(`image/`)?`image-url`:`file-url`,url:i,mediaType:n}}let s=a.toolCallId??t?.toolCallId,l=o?[o]:[],u=[];for(let e of l){if(!e||typeof e!=`object`)continue;let t=e,n=typeof t.type==`string`?t.type:void 0,r=typeof t.mediaType==`string`?t.mediaType.toLowerCase():``,i=null,a=``;if(n===`media`){let e=typeof t.data==`string`?t.data:void 0;if(!e)continue;a=r.length>0?r:`application/octet-stream`,i=`data:${a};base64,${e}`}else if(n===`image-url`){let e=typeof t.url==`string`?t.url:void 0;if(!e)continue;a=r,i=e}else if(n===`file-url`){let e=typeof t.url==`string`?t.url:void 0;if(!e)continue;a=r,i=e}else continue;if(i){if(n===`image-url`||a.startsWith(`image/`))u.push({type:`image`,image:i,...a.includes(`/`)?{mimeType:a}:{}});else if(a.startsWith(`audio/`))u.push({type:`audio`,audio:i,mimeType:a});else if(a.startsWith(`video/`))u.push({type:`video`,video:i,mimeType:a});else{let e=a||`application/octet-stream`;u.push({type:`file`,data:i,mimeType:e,filename:c(e)})}}}if(u.length>0){let e=v(),t=s,n={id:`agent-media-${typeof t==`string`&&t.length>0?`${t}-${e}`:String(e)}`,role:`assistant`,content:``,contentParts:u,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e,agentMetadata:{executionId:a.executionId,iteration:Y}};b(n);let r=x;r&&(r.streaming=!1,b(r)),x=null,C.current=null}}else if(a.type===`execution_complete`){let e=x;e&&(a.kind===`flow`&&e.streaming!==!1?G(e):(e.streaming=!1,b(e)),x=null),w=null,T=``,W=null,o({type:`status`,status:a.success===!1?`error`:`idle`,terminal:!0})}else if(a.type===`execution_error`){let e=typeof a.error==`string`?a.error:a.error?.message??`Execution error`;o({type:`error`,error:Error(e)})}else if(a.type!==`ping`){if(a.type===`approval_start`){let e=a.approvalId??`approval-${v()}`,t={id:`approval-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,sequence:v(),approval:{id:e,status:`pending`,agentId:$?.agentId??`virtual`,executionId:a.executionId??$?.executionId??``,toolName:a.toolName??``,toolType:a.toolType,description:a.description??`Execute ${a.toolName??`tool`}`,...typeof a.reason==`string`&&a.reason?{reason:a.reason}:{},parameters:a.parameters,...typeof a.toolCallId==`string`&&a.toolCallId?{toolCallId:a.toolCallId}:{}}};b(t)}else if(a.type===`approval_complete`){let e=a.approvalId;if(e){let t={id:`approval-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,sequence:v(),approval:{id:e,status:a.decision??`approved`,agentId:$?.agentId??`virtual`,executionId:a.executionId??$?.executionId??``,toolName:``,description:``,resolvedAt:Date.now()}};b(t)}}else if(a.type===`artifact_start`||a.type===`artifact_delta`||a.type===`artifact_update`||a.type===`artifact_complete`){if(a.type===`artifact_start`){let e=a.artifactType,n=String(a.id),s=typeof a.title==`string`?a.title:void 0,c=a.file,l;if(c&&typeof c==`object`&&!Array.isArray(c)&&typeof c.path==`string`&&typeof c.mimeType==`string`&&(l={path:c.path,mimeType:c.mimeType,...typeof c.language==`string`?{language:c.language}:{}}),o({type:`artifact_start`,id:n,artifactType:e,title:s,component:typeof a.component==`string`?a.component:void 0,...l?{file:l}:{}}),z.set(n,{markdown:``,title:s,file:l}),!R.has(n)){R.add(n);let o=t(i.config().features?.artifacts,{artifactType:e,...l?{file:l}:{}}),c=typeof a.component==`string`?a.component:void 0,u={id:`artifact-ref-${n}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:v(),rawContent:r(o,{artifactId:n,title:s,artifactType:e,status:`streaming`,...l?{file:l}:{},...c?{component:c}:{}})};L.set(n,u),b(u)}}else if(a.type===`artifact_delta`){let e=String(a.id),t=typeof a.delta==`string`?a.delta:String(a.delta??``);o({type:`artifact_delta`,id:e,artDelta:t});let n=z.get(e);n&&(n.markdown+=t)}else if(a.type===`artifact_update`){let e=a.props&&typeof a.props==`object`&&!Array.isArray(a.props)?a.props:{};o({type:`artifact_update`,id:String(a.id),props:e,component:typeof a.component==`string`?a.component:void 0});let t=z.get(String(a.id));t&&(t.props={...t.props??{},...e})}else if(a.type===`artifact_complete`){let e=String(a.id);o({type:`artifact_complete`,id:e});let t=L.get(e);if(t){t.streaming=!1;try{let n=JSON.parse(t.rawContent??`{}`);if(n.props){n.props.status=`complete`;let t=z.get(e);t?.markdown&&(n.props.markdown=t.markdown),t?.file&&(n.props.file=t.file),n.component===`PersonaArtifactInline`&&t?.props&&Object.keys(t.props).length>0&&(n.props.componentProps=t.props)}t.rawContent=JSON.stringify(n)}catch{}z.delete(e),b(t),L.delete(e)}}}else if(a.type===`error`&&a.recoverable===!1&&a.error!=null&&a.error!==``){let e=typeof a.error==`string`?a.error:a.error?.message==null?`Execution error`:String(a.error.message);o({type:`error`,error:Error(e)});let t=x;t&&t.streaming&&(t.streaming=!1,b(t)),o({type:`status`,status:`idle`})}}}K.length=0};try{for(;;){if(h!==i.streamGeneration())return;f?.throwIfAborted();let{done:e,value:t}=await g.read();if(h!==i.streamGeneration())return;if(f?.throwIfAborted(),e)break;_+=re.decode(t,{stream:!0});let n=_.split(`
1
+ import"./chunk-Bb41bKyp.js";import{i as e}from"./chunk-BAdIgC5d.js";import{i as t,l as n,t as r,u as i}from"./chunk-BRM3bHcJ.js";async function a(e,t,n,r){let i={"Content-Type":`application/json`,...e.headers};e.getHeaders&&Object.assign(i,await e.getHeaders());let a={executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0},o=(t,n)=>fetch(`${e.clientApiBase()}${t}`,{method:`POST`,headers:i,body:JSON.stringify({...n,...a})}),s=`/v1/agents/${t.agentId}/approve`;if(!e.isClientTokenMode())return o(s);let{sessionId:c}=await e.initSession(),l=await o(`/v1/client/approve`,{sessionId:c,...r?.assistantMessageId?{assistantMessageId:r.assistantMessageId}:{}});if(l.status===404){let e=await l.clone().json().catch(()=>null);if(!e||e.error===`Not Found`)return o(s)}return l}async function o(e,t,n,r){let a=e.isClientTokenMode(),o=a?e.getClientApiUrl(`resume`):`${e.config.apiUrl?.replace(/\/+$/,``)||`https://api.runtype.com`}/resume`,s,c=null;if(a){let t=await e.initSession();s=t.sessionId,t.durableRecovery?.enabled===!0&&(c=await e.readVisitorToken())}let l={"Content-Type":`application/json`,...c?{"X-Visitor-Token":c}:{},...e.headers};e.getHeaders&&Object.assign(l,await e.getHeaders());let u={executionId:t,toolOutputs:n,streamResponse:r?.streamResponse??!0,...r?.after?{after:r.after}:{}};if(s&&(u.sessionId=s,r?.assistantMessageId&&(u.assistantMessageId=r.assistantMessageId)),a&&s){let t=[...i(e.config),...await(await e.getWebMcpBridge())?.snapshotForDispatch()??[]],{response:n,commit:a}=await e.sendWithClientToolsDiff(s,t,t=>{let n={...u,...t};return e.debug&&console.debug(`[AgentWidgetClient] client token resume`,n),fetch(o,{method:`POST`,headers:l,body:JSON.stringify(n),signal:r?.signal})},{emptyMeansReplace:!0});return n.ok&&a(),n}return fetch(o,{method:`POST`,headers:l,body:JSON.stringify(u),signal:r?.signal})}const s=e=>e===`commentary`||e===`partial_answer`||e===`final_answer`?e:void 0;function c(e){let t=e.toLowerCase(),n=t===`text/plain`?`txt`:t===`text/markdown`?`md`:void 0;if(n)return`attachment.${n}`;let r=t.indexOf(`/`);if(r>0){let e=t.slice(r+1).split(`;`)[0]?.trim()??``;if(e&&e!==`octet-stream`&&/^[a-z0-9.+-]+$/i.test(e))return`attachment.${e}`}return`attachment`}const l=e=>/^[{[<]/.test(e);function u(e,t){if(!e)return t;let r=e.trim(),i=t.trim();if(!r)return t;if(!i)return e;let a=l(r);if(!l(i))return e;if(!a||i.startsWith(r))return t;let o=n(e);return n(t)!==null&&o===null?t:e}async function d(e,t,n,r,i,a,o){if(!e.parseSSEEvent)return!1;try{let s=await e.parseSSEEvent(t);if(s===null)return!1;let c=e=>{let t={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`assistant`,sequence:a(),...e!==void 0&&{partId:e}};return r.current=t,i(t),t},l=e=>r.current?r.current:c(e);if(s.text!==void 0){s.partId!==void 0&&o.current!==null&&s.partId!==o.current&&(r.current&&(r.current.streaming=!1,i(r.current)),c(s.partId)),s.partId!==void 0&&(o.current=s.partId);let e=l(s.partId);s.partId!==void 0&&!e.partId&&(e.partId=s.partId),e.content+=s.text,i(e)}return s.done&&(r.current&&(r.current.streaming=!1,i(r.current)),o.current=null,n({type:`status`,status:`idle`})),s.error&&(o.current=null,n({type:`error`,error:Error(s.error)})),!0}catch(e){return typeof console<`u`&&console.error(`[AgentWidget] parseSSEEvent error:`,e),!1}}async function ee(i,a,o,l,ee,f,p,m){let h=i.streamGeneration(),g=a.getReader();i.streamReaders.add(g);let te=!!i.config().backgroundConversations,ne=()=>{te&&g.cancel().catch(()=>{})};f?.addEventListener(`abort`,ne,{once:!0});let re=new TextDecoder,_=``,ie=Date.now(),ae=0,v=()=>ie+ae++,oe=e=>({...e,chunks:e.chunks?[...e.chunks]:void 0}),y=e=>({...e,reasoning:e.reasoning?{...e.reasoning,chunks:[...e.reasoning.chunks]}:void 0,toolCall:e.toolCall?oe(e.toolCall):void 0,tools:e.tools?.map(oe)}),se=e=>{if(e.role!==`assistant`||e.variant)return!0;let t=Array.isArray(e.contentParts)&&e.contentParts.length>0,n=typeof e.rawContent==`string`&&e.rawContent.trim()!==``;return typeof e.content==`string`&&e.content.trim()!==``||t||n||!!e.stopReason},b=e=>{!f?.aborted&&h===i.streamGeneration()&&se(e)&&o({type:`message`,message:y(e)})},x=null,S=null,C={current:null},ce={current:null},w=null,T=``,E=new Map(m?.textPhases),D=/* @__PURE__ */ new Map,O=/* @__PURE__ */ new Map,k=/* @__PURE__ */ new Map,A=/* @__PURE__ */ new Map,j=/* @__PURE__ */ new Map,M=l,N=!1,P=p?.find(e=>e.id===l);P&&(x=y(P),x.streaming=m?.openAssistant??!0,N=!0,w=P.agentMetadata?.textBlockId??null,T=P.rawContent??P.content,S=x,m&&!m.openAssistant&&(x=null)),m&&(w=m.textBlockId,T=m.rawText,m.nestedParents.forEach(([e,t])=>D.set(e,t)),m.nestedRaw.forEach(([e,t])=>k.set(e,t)));for(let e of p??[]){e.variant===`tool`&&e.toolCall?.id&&j.set(e.toolCall.id,y(e)),e.variant===`reasoning`&&e.reasoning?.id&&A.set(e.reasoning.id,y(e));let t=e.agentMetadata?.textBlockId;t&&(O.set(t,e.id===x?.id?x:y(e)),e.agentMetadata?.phase&&E.set(t,e.agentMetadata.phase));let n=e.agentMetadata?.parentToolId;t&&n&&(D.set(t,n),k.set(t,e.rawContent??e.content))}let le=()=>{if(x)return x;let e,t=``,n=w;return!N&&M?(e=M,N=!0,t=ee??``):e=M&&n?`${M}_${n}`:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,x={id:e,role:`assistant`,content:t,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:v()},b(x),x},F=(e,t)=>{let n=A.get(e);if(n)return n;let r={id:`reason-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`reasoning`,agentMetadata:{executionId:t},sequence:v(),reasoning:{id:e,status:`streaming`,chunks:[]}};return A.set(e,r),b(r),r},I=/* @__PURE__ */ new Set,L=/* @__PURE__ */ new Map,R=/* @__PURE__ */ new Set;for(let e of p??[])if(e.id.startsWith(`artifact-ref-`)){let t=e.id.slice(13);R.add(t),L.set(t,y(e))}m?.artifactTools.forEach(e=>I.add(e));let z=/* @__PURE__ */ new Map;m?.artifactContent.forEach(([e,t])=>z.set(e,{...t}));let ue=e=>{if(!e)return!1;let t=e.replace(/_+/g,`_`).replace(/^_|_$/g,``);return t===`emit_artifact_markdown`||t===`emit_artifact_component`},B=(e,t,n)=>{let r=j.get(e),i={...r?.agentMetadata,executionId:t??r?.agentMetadata?.executionId,iteration:n??r?.agentMetadata?.iteration??(Y||void 0)};if(r)return r.agentMetadata=i,r;let a={id:`tool-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,variant:`tool`,agentMetadata:i,sequence:v(),toolCall:{id:e,status:`pending`}};return j.set(e,a),b(a),a},de=e=>{if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`){let t=Number(e);if(Number.isFinite(t))return t;let n=Date.parse(e);if(!Number.isNaN(n))return n}return Date.now()},V=e=>{if(typeof e==`string`)return e;if(e==null)return``;try{return JSON.stringify(e)}catch{return String(e)}},H=/* @__PURE__ */ new Map,U=/* @__PURE__ */ new Map,fe=(e,t)=>{let r=V(t),i=u(U.get(e.id),r);e.rawContent=i;let a=H.get(e.id),o=t=>{let n=e.content??``;t.trim()!==``&&(!n.trim()||t.startsWith(n)||t.trimStart().startsWith(n.trim()))&&(e.content=t)},s=()=>{let t=a?.close?.();t instanceof Promise&&t.catch(()=>{}),H.delete(e.id),U.delete(e.id),e.streaming=!1,b(e)};if(!a){o(r),s();return}let c=n(i);if(c!==null&&c.trim()!==``){o(c),s();return}let l=e=>{let t=typeof e==`string`?e:e?.text??null;if(t!==null&&t.trim()!==``)return t;let n=a.getExtractedText();return n!==null&&n.trim()!==``?n:r},d;try{d=a.processChunk(i)}catch{o(r),s();return}d instanceof Promise?d.then(e=>{o(l(e)),s()}).catch(()=>{o(r),s()}):(o(l(d)),s())},W=null,pe=p?.find(e=>e.id===m?.sealedFlowMessageId);pe&&(W=y(pe));let me=(e,t,n)=>{e.rawContent=t,H.has(e.id)||H.set(e.id,i.createStreamParser());let r=H.get(e.id),a=/^[{[]/.test(t.trim());a&&U.set(e.id,t);let o=()=>{e.content+=n,U.delete(e.id),H.delete(e.id),e.rawContent=void 0,b(e)};if(r.__isPlainTextParser===!0){o();return}let s=n=>{let r=typeof n==`string`?n:n?.text??null;r!==null&&r.trim()!==``?(e.content=r,b(e)):!a&&!t.trim().startsWith(`<`)&&o()},c=r.processChunk(t);c instanceof Promise?c.then(s).catch(o):s(c)},G=(e,t)=>{let r=t??e.content;if(r==null||r===``){e.streaming=!1,b(e);return}let i=U.get(e.id)??V(r);e.rawContent=i;let a=H.get(e.id),o=null,s=!1;if(a&&(o=a.getExtractedText(),o===null&&(o=n(i)),o===null)){let t=a.processChunk(i);t instanceof Promise?(s=!0,t.then(t=>{let n=typeof t==`string`?t:t?.text??null;n!==null&&(e.content=n,e.streaming=!1,H.delete(e.id),U.delete(e.id),b(e))}).catch(()=>{})):o=typeof t==`string`?t:t?.text??null}if(!s){o!==null&&o.trim()!==``?e.content=o:U.has(e.id)||(e.content=V(r));let t=H.get(e.id);if(t){let n=t.close?.();n instanceof Promise&&n.catch(()=>{}),H.delete(e.id)}U.delete(e.id),e.streaming=!1,b(e)}},he=(e,t,n,r)=>{let i=O.get(e);if(i)return i;let a={id:`nested-${t}-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:v(),...n?{variant:n}:{},...n===`reasoning`?{reasoning:{id:e,status:`streaming`,chunks:[]}}:{},agentMetadata:{parentToolId:t,textBlockId:e,executionId:r,phase:E.get(e)}};return O.set(e,a),b(a),a},K=[],q,J=/* @__PURE__ */ new Map;m?.media.forEach(([e,t])=>J.set(e,{...t,parts:[...t.parts]}));let Y=m?.iteration??0,X=m?.executionKind??`agent`,Z=m?.executionKindResolved??!1,Q=m?.turnId??null,$=null,ge=i.config().iterationDisplay??`separate`;q=()=>{for(let n=0;n<K.length;n++){let a=K[n];if(!Z&&X!==`flow`&&typeof a.stepType==`string`&&(X=`flow`),a.type===`reasoning_start`){let e=typeof a.id==`string`?a.id:null,t=typeof a.parentToolCallId==`string`&&a.parentToolCallId?a.parentToolCallId:null;if(e&&t){D.set(e,t),he(e,t,`reasoning`,a.executionId);continue}let n=a.id,r=F(n,a.executionId);r.reasoning=r.reasoning??{id:n,status:`streaming`,chunks:[]},r.reasoning.startedAt=r.reasoning.startedAt??Date.now(),r.reasoning.completedAt=void 0,r.reasoning.durationMs=void 0,(a.scope===`loop`||a.scope===`turn`)&&(r.reasoning.scope=a.scope),r.streaming=!0,r.reasoning.status=`streaming`,b(r)}else if(a.type===`reasoning_delta`){let e=typeof a.id==`string`?a.id:null;if(e&&D.has(e)&&O.has(e)){let t=O.get(e),n=a.delta;n&&t.reasoning&&(t.reasoning.chunks.push(String(n)),b(t));continue}let t=a.id,n=F(t,a.executionId);n.reasoning=n.reasoning??{id:t,status:`streaming`,chunks:[]},n.reasoning.startedAt=n.reasoning.startedAt??Date.now(),a.delta&&n.reasoning.chunks.push(a.delta),n.reasoning.status=`streaming`,n.streaming=!0,b(n)}else if(a.type===`reasoning_complete`){let e=typeof a.id==`string`?a.id:null;if(e&&D.has(e)&&O.has(e)){let t=O.get(e);if(t.reasoning){let e=typeof a.text==`string`?a.text:``;e&&t.reasoning.chunks.length===0&&t.reasoning.chunks.push(e),t.reasoning.status=`complete`,t.streaming=!1,b(t)}D.delete(e),O.delete(e);continue}let t=a.id,n=typeof a.text==`string`?a.text:``;!A.get(t)&&(n||a.scope===`loop`)&&F(t,a.executionId);let r=A.get(t);if(r?.reasoning){(a.scope===`loop`||a.scope===`turn`)&&(r.reasoning.scope=a.scope),n&&r.reasoning.chunks.length===0&&r.reasoning.chunks.push(n),r.reasoning.status=`complete`,r.reasoning.completedAt=Date.now();let e=r.reasoning.startedAt??Date.now();r.reasoning.durationMs=Math.max(0,(r.reasoning.completedAt??Date.now())-e),r.streaming=!1,b(r)}}else if(a.type===`tool_start`){x&&=(x.streaming=!1,b(x),null),typeof a.iteration==`number`&&(Y=a.iteration);let e=a.toolCallId,t=a.toolName;if(ue(t)){I.add(e);continue}let n=B(e,a.executionId,a.iteration),r=n.toolCall??{id:e,status:`pending`};r.name=t??r.name,r.status=`running`,r.success=void 0,r.error=void 0,r.duration=void 0,a.parameters!==void 0&&(r.args=a.parameters),r.startedAt=r.startedAt??de(a.startedAt),r.completedAt=void 0,r.durationMs=void 0,n.toolCall=r,n.streaming=!0,b(n)}else if(a.type===`tool_output_delta`){let e=a.toolCallId;if(I.has(e))continue;let t=B(e,a.executionId),n=t.toolCall??{id:e,status:`running`};n.startedAt=n.startedAt??Date.now();let r=a.delta;r&&(n.chunks=n.chunks??[],n.chunks.push(String(r))),n.status=`running`,t.toolCall=n,t.streaming=!0,b(t)}else if(a.type===`tool_complete`){let e=a.toolCallId;if(I.has(e)){I.delete(e);continue}let t=B(e,a.executionId,a.iteration),n=t.toolCall??{id:e,status:`running`};n.status=`complete`,a.result!==void 0&&(n.result=a.result),n.name=a.toolName??n.name,n.success=a.success,n.error=a.error,n.completedAt=Date.now();let r=a.executionTime;if(typeof r==`number`)n.durationMs=r,n.duration=r;else{let e=n.startedAt??Date.now();n.durationMs=Math.max(0,(n.completedAt??Date.now())-e)}t.toolCall=n,t.streaming=!1,b(t)}else if(a.type===`await`&&a.toolName){let t=typeof a.toolCallId==`string`&&a.toolCallId.length>0?a.toolCallId:void 0,n=t??a.toolId??`local-${v()}`,r=B(n,a.executionId),i=a.toolName,o=a.origin===`webmcp`&&!e(i)?`webmcp:${i}`:i,s=e(o),c=r.toolCall??{id:n,status:`pending`};c.name=o,c.args=a.parameters,c.status=s?`running`:`complete`,c.chunks=c.chunks??[],c.startedAt=c.startedAt??de(a.awaitedAt),s?(c.completedAt=void 0,c.duration=void 0,c.durationMs=void 0):c.completedAt=c.completedAt??c.startedAt,r.toolCall=c,r.streaming=!1,r.agentMetadata={...r.agentMetadata,executionId:a.executionId??r.agentMetadata?.executionId,awaitingLocalTool:!0,...t?{webMcpToolCallId:t}:{}},b(r)}else if(a.type===`text_start`){let e=typeof a.id==`string`?a.id:null;if(e){let t=s(a.phase);t?E.set(e,t):E.delete(e)}let t=typeof a.parentToolCallId==`string`&&a.parentToolCallId?a.parentToolCallId:null;if(e&&t){D.set(e,t);continue}let n=x;n&&(X===`flow`?(G(n),W=n):(n.streaming=!1,b(n)),x=null),w=e??w,T=``}else if(a.type===`text_delta`){let e=typeof a.id==`string`?a.id:null,t=e?D.get(e):void 0;if(e&&t){let n=typeof a.delta==`string`?a.delta:``,r=(k.get(e)??``)+n;if(k.set(e,r),r.trim()===``)continue;let i=he(e,t,void 0,a.executionId);me(i,r,n);continue}w=e??w;let n=typeof a.delta==`string`?a.delta:``;if(T+=n,X===`flow`&&T.trim()===``)continue;let r=le();r.agentMetadata={textBlockId:w??void 0,phase:E.get(w??``),executionId:a.executionId,iteration:Y,...X===`flow`?{}:{turnId:Q??void 0,agentName:$?.agentName}},w&&O.set(w,r),me(r,T,n),S=r}else if(a.type===`text_complete`){let e=typeof a.id==`string`?a.id:null;e&&E.delete(e);let t=e?O.get(e):x,n=s(a.phase);if(t&&n&&(t.agentMetadata={...t.agentMetadata,providerPhase:n}),e&&D.has(e)){let t=O.get(e);t&&G(t),D.delete(e),k.delete(e),O.delete(e);continue}if(e&&t!==x){t&&(t.streaming=!1,b(t));continue}let r=x;r&&(X===`flow`?(G(r),W=r):((r.content??``)===``&&typeof a.text==`string`&&(r.content=a.text),r.streaming=!1,b(r)),x=null),w=null,T=``}else if(a.type===`step_complete`){if(a.stepType===`tool`)continue;if(a.success===!1){let e=a.error||`Step failed`;o({type:`error`,error:Error(e)});let t=x;t&&t.streaming&&(t.streaming=!1,b(t)),o({type:`status`,status:`idle`});continue}{let e=W;W=null;let t=a.stopReason,n=(a.result&&typeof a.result==`object`?a.result:null)?.response;if(e)t&&(e.stopReason=t),n==null?e.streaming!==!1&&(H.delete(e.id),U.delete(e.id),e.streaming=!1,b(e)):fe(e,n);else{let e=n!=null&&n!==``;if(e||t&&t!==`end_turn`&&t!==`unknown`){let r=le();t&&(r.stopReason=t),e?G(r,n):(r.streaming=!1,b(r))}}continue}}else if(a.type===`execution_start`)X=a.kind===`flow`?`flow`:`agent`,Z=!0,i.config().backgroundConversations&&o({type:`status`,status:`connected`,executionId:a.executionId}),X===`agent`&&($={executionId:a.executionId,agentId:a.agentId??`virtual`,agentName:a.agentName??``});else if(a.type===`turn_start`){let e=typeof a.iteration==`number`?a.iteration:Y;if(e!==Y){if(ge===`separate`&&e>1){let e=x;e&&(e.streaming=!1,b(e),x=null)}Y=e}Q=typeof a.id==`string`?a.id:null,S=null}else if(a.type===`tool_input_delta`){let e=a.toolCallId;if(e){let t=j.get(e);t?.toolCall&&(t.toolCall.chunks=t.toolCall.chunks??[],t.toolCall.chunks.push(a.delta??``),b(t))}}else if(a.type===`tool_input_complete`){if(I.has(a.toolCallId))continue;let e=B(a.toolCallId,a.executionId),t=e.toolCall;t.args=a.parameters,t.name=a.toolName??t.name,b(e)}else if(a.type===`turn_complete`){let e=a.stopReason,t=x??S;if(e&&t!==null){let n=a.id;n&&t.agentMetadata?.turnId!==n||(t.stopReason=e,b(t))}Q===a.id&&(Q=null)}else if(a.type===`media_start`){let e=String(a.id);J.set(e,{mediaType:typeof a.mediaType==`string`?a.mediaType:void 0,toolCallId:a.toolCallId,parts:[]})}else if(a.type===`media_delta`){let e=J.get(String(a.id));e&&typeof a.delta==`string`&&e.parts.push(a.delta)}else if(a.type===`media_complete`){let e=String(a.id),t=J.get(e);J.delete(e);let n=(typeof a.mediaType==`string`?a.mediaType:void 0)??t?.mediaType??`application/octet-stream`,r=typeof a.data==`string`?a.data:void 0,i=typeof a.url==`string`?a.url:t&&t.parts.length>0?t.parts.join(``):void 0,o=null;if(r)o={type:`media`,data:r,mediaType:n};else if(i){let e=n.toLowerCase();o={type:e===`image`||e.startsWith(`image/`)?`image-url`:`file-url`,url:i,mediaType:n}}let s=a.toolCallId??t?.toolCallId,l=o?[o]:[],u=[];for(let e of l){if(!e||typeof e!=`object`)continue;let t=e,n=typeof t.type==`string`?t.type:void 0,r=typeof t.mediaType==`string`?t.mediaType.toLowerCase():``,i=null,a=``;if(n===`media`){let e=typeof t.data==`string`?t.data:void 0;if(!e)continue;a=r.length>0?r:`application/octet-stream`,i=`data:${a};base64,${e}`}else if(n===`image-url`){let e=typeof t.url==`string`?t.url:void 0;if(!e)continue;a=r,i=e}else if(n===`file-url`){let e=typeof t.url==`string`?t.url:void 0;if(!e)continue;a=r,i=e}else continue;if(i){if(n===`image-url`||a.startsWith(`image/`))u.push({type:`image`,image:i,...a.includes(`/`)?{mimeType:a}:{}});else if(a.startsWith(`audio/`))u.push({type:`audio`,audio:i,mimeType:a});else if(a.startsWith(`video/`))u.push({type:`video`,video:i,mimeType:a});else{let e=a||`application/octet-stream`;u.push({type:`file`,data:i,mimeType:e,filename:c(e)})}}}if(u.length>0){let e=v(),t=s,n={id:`agent-media-${typeof t==`string`&&t.length>0?`${t}-${e}`:String(e)}`,role:`assistant`,content:``,contentParts:u,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,sequence:e,agentMetadata:{executionId:a.executionId,iteration:Y}};b(n);let r=x;r&&(r.streaming=!1,b(r)),x=null,C.current=null}}else if(a.type===`execution_complete`){let e=x;e&&(a.kind===`flow`&&e.streaming!==!1?G(e):(e.streaming=!1,b(e)),x=null),w=null,T=``,W=null,o({type:`status`,status:a.success===!1?`error`:`idle`,terminal:!0})}else if(a.type===`execution_error`){let e=typeof a.error==`string`?a.error:a.error?.message??`Execution error`;o({type:`error`,error:Error(e)})}else if(a.type!==`ping`){if(a.type===`approval_start`){let e=a.approvalId??`approval-${v()}`,t={id:`approval-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,sequence:v(),approval:{id:e,status:`pending`,agentId:$?.agentId??`virtual`,executionId:a.executionId??$?.executionId??``,toolName:a.toolName??``,toolType:a.toolType,description:a.description??`Execute ${a.toolName??`tool`}`,...typeof a.reason==`string`&&a.reason?{reason:a.reason}:{},parameters:a.parameters,...typeof a.toolCallId==`string`&&a.toolCallId?{toolCallId:a.toolCallId}:{}}};b(t)}else if(a.type===`approval_complete`){let e=a.approvalId;if(e){let t={id:`approval-${e}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!1,variant:`approval`,sequence:v(),approval:{id:e,status:a.decision??`approved`,agentId:$?.agentId??`virtual`,executionId:a.executionId??$?.executionId??``,toolName:``,description:``,resolvedAt:Date.now()}};b(t)}}else if(a.type===`artifact_start`||a.type===`artifact_delta`||a.type===`artifact_update`||a.type===`artifact_complete`){if(a.type===`artifact_start`){let e=a.artifactType,n=String(a.id),s=typeof a.title==`string`?a.title:void 0,c=a.file,l;if(c&&typeof c==`object`&&!Array.isArray(c)&&typeof c.path==`string`&&typeof c.mimeType==`string`&&(l={path:c.path,mimeType:c.mimeType,...typeof c.language==`string`?{language:c.language}:{}}),o({type:`artifact_start`,id:n,artifactType:e,title:s,component:typeof a.component==`string`?a.component:void 0,...l?{file:l}:{}}),z.set(n,{markdown:``,title:s,file:l}),!R.has(n)){R.add(n);let o=t(i.config().features?.artifacts,{artifactType:e,...l?{file:l}:{}}),c=typeof a.component==`string`?a.component:void 0,u={id:`artifact-ref-${n}`,role:`assistant`,content:``,createdAt:(/* @__PURE__ */ new Date()).toISOString(),streaming:!0,sequence:v(),rawContent:r(o,{artifactId:n,title:s,artifactType:e,status:`streaming`,...l?{file:l}:{},...c?{component:c}:{}})};L.set(n,u),b(u)}}else if(a.type===`artifact_delta`){let e=String(a.id),t=typeof a.delta==`string`?a.delta:String(a.delta??``);o({type:`artifact_delta`,id:e,artDelta:t});let n=z.get(e);n&&(n.markdown+=t)}else if(a.type===`artifact_update`){let e=a.props&&typeof a.props==`object`&&!Array.isArray(a.props)?a.props:{};o({type:`artifact_update`,id:String(a.id),props:e,component:typeof a.component==`string`?a.component:void 0});let t=z.get(String(a.id));t&&(t.props={...t.props??{},...e})}else if(a.type===`artifact_complete`){let e=String(a.id);o({type:`artifact_complete`,id:e});let t=L.get(e);if(t){t.streaming=!1;try{let n=JSON.parse(t.rawContent??`{}`);if(n.props){n.props.status=`complete`;let t=z.get(e);t?.markdown&&(n.props.markdown=t.markdown),t?.file&&(n.props.file=t.file),n.component===`PersonaArtifactInline`&&t?.props&&Object.keys(t.props).length>0&&(n.props.componentProps=t.props)}t.rawContent=JSON.stringify(n)}catch{}z.delete(e),b(t),L.delete(e)}}}else if(a.type===`error`&&a.recoverable===!1&&a.error!=null&&a.error!==``){let e=typeof a.error==`string`?a.error:a.error?.message==null?`Execution error`:String(a.error.message);o({type:`error`,error:Error(e)});let t=x;t&&t.streaming&&(t.streaming=!1,b(t)),o({type:`status`,status:`idle`})}}}K.length=0};try{for(;;){if(h!==i.streamGeneration())return;f?.throwIfAborted();let{done:e,value:t}=await g.read();if(h!==i.streamGeneration())return;if(f?.throwIfAborted(),e)break;_+=re.decode(t,{stream:!0});let n=_.split(`
2
2
 
3
3
  `);_=n.pop()??``;for(let e of n){if(h!==i.streamGeneration())return;f?.throwIfAborted();let t=e.split(`
4
4
  `),n=`message`,r=``,a=null;for(let e of t)e.startsWith(`event:`)?n=e.replace(`event:`,``).trim():e.startsWith(`data:`)?r+=e.replace(`data:`,``).trim():e.startsWith(`id:`)&&(a=e.slice(3).trim());let s=()=>{a!==null&&a!==``&&o({type:`cursor`,id:a,...i.config().backgroundConversations?{checkpoint:{textBlockId:w,openAssistant:x!==null,sealedFlowMessageId:W?.id??null,rawText:T,executionKind:X,executionKindResolved:Z,turnId:Q,iteration:Y,textPhases:[...E],nestedParents:[...D],nestedRaw:[...k],media:[...J].map(([e,t])=>[e,{...t,parts:[...t.parts]}]),artifactContent:[...z].map(([e,t])=>[e,{...t,props:t.props?{...t.props}:void 0}]),artifactTools:[...I]}}:{}})};if(!r){s();continue}let c;try{c=JSON.parse(r)}catch(e){o({type:`error`,error:e instanceof Error?e:/* @__PURE__ */ Error(`Failed to parse chat stream payload`)});continue}let l=typeof c==`object`&&c&&!Array.isArray(c)?c:null,u=n===`message`?typeof l?.type==`string`?l.type:`message`:n;if(i.onSSEEvent?.(u,c),i.parseSSEEvent){C.current=x;let e=await d(i,c,o,C,b,v,ce);if(h!==i.streamGeneration())return;if(f?.throwIfAborted(),C.current&&C.current!==x&&(x=C.current),e){s();continue}}l&&(K.push({...l,type:u}),q()),s()}}q()}finally{i.streamReaders.delete(g),f?.removeEventListener(`abort`,ne),g.releaseLock()}}export{u as preferFinalStructuredContent,a as resolveApproval,o as resumeFlow,ee as streamResponse};
@@ -1 +1 @@
1
- import{n as e}from"./chunk-BAdIgC5d.js";import{t}from"./chunk-DVgzoVCB.js";import{t as n}from"./chunk-i4qGOJAL.js";import{n as r}from"./chunk-DTDHeUsG.js";const i=e=>e.replace(/[^a-zA-Z0-9_]/g,`_`).toLowerCase().replace(/_+/g,`_`).replace(/^_|_$/g,``),a=e=>typeof e==`object`&&!!e&&!Array.isArray(e),o=e=>{if(e.variant!==`tool`)return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=i(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:a(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},s=(e,t)=>{let n=[],r=[],i=[],a=``,s,c=()=>{r.length!==0&&(n.push({role:`assistant`,content:``,createdAt:a,toolCalls:r},{role:`tool`,content:``,createdAt:a,toolResults:i}),r=[],i=[])};for(let l of e){let e=o(l);if(e){let t=l.agentMetadata?.clientToolAnswer?.batch;r.length>0&&(t===void 0||t!==s)&&c(),r.length===0&&(a=l.createdAt,s=t),r.some(t=>t.toolCallId===e.call.toolCallId)||(r.push(e.call),i.push(e.result));continue}let u=t(l);u&&(c(),n.push(u))}return c(),n},c=e=>e.voiceCaption||r(e)?!1:!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0),l=e=>typeof e==`string`?!0:Array.isArray(e)?e.every(e=>{if(!e||typeof e!=`object`)return!1;switch(e.type){case`text`:return typeof e.text==`string`;case`image`:return typeof e.image==`string`;case`audio`:return typeof e.audio==`string`;case`video`:return typeof e.video==`string`;case`file`:return typeof e.data==`string`&&typeof e.mimeType==`string`&&typeof e.filename==`string`;default:return!1}}):!1,u=e=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),d=e=>{let t=e.agentMetadata?.providerPhase??e.agentMetadata?.phase;return e.role===`assistant`&&(t===`commentary`||t===`partial_answer`||t===`final_answer`)?{phase:t}:{}},f=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt,...d(e)});var p=class{constructor(e){this.host=e}async initializeSession(){await this.host.historyInternals.historyBootstrapReady;let e=this.host.config.getStoredConversationId?.()||null,t=this.host.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.host.isHistoryCapable()&&!t)return this.#e(e,!1);let n=await this.host.readVisitorToken();if(e&&n)try{let n=await this.createClientSession({conversationId:e,durableResume:t});return t&&n.durableRecovery?.enabled!==!0&&this.host.historyInternals.setStoredResumableHandle?.(null),this.host.finishInit(n,e,!1)}catch(n){if(!(n instanceof this.host.HistoryClientError&&n.code===`not_found`)&&!(n instanceof this.host.HistoryClientError&&n.code===`visitor_required`)&&!(n instanceof this.host.HistoryClientError&&n.code===`history_disabled`))throw n;return t&&this.host.historyInternals.setStoredResumableHandle?.(null),this.#e(e,!0)}return this.#e(e,!1)}async#e(e,t){let n=this.host.historyInternals.visitorStore;return n&&!await this.host.readVisitorToken()?n.withFirstInitLock(()=>this.#t(e,t)):this.#t(e,t)}async#t(e,t){let n=this.host.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:n}),i=await this.#n(r);return this.host.finishInit(i,e,t)}async#n(e){if(!e.visitor?.token||this.host.claimInFlight||!this.host.isHistoryCapable()&&e.durableRecovery?.enabled!==!0)return e;this.host.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:e.sessionId})}catch{return e}finally{this.host.claimInFlight=!1}}async sendWithClientToolsDiff(t,n,r,i){let a=!!(n&&n.length>0),o=a?e(n):void 0,s=this.host.clientToolsFingerprintSessionId===t,c=a&&s&&this.host.lastSentClientToolsFingerprint===o,l=!a&&i?.emptyMeansReplace===!0&&this.host.sentNonEmptyClientToolsSessionId===t,u=!1,d;for(let e=0;d=await r({...a&&(u||!c)&&n?{clientTools:n}:{},...l?{clientTools:[]}:{},...o?{clientToolsFingerprint:o}:{}}),d.status===409&&e===0&&a&&(await d.clone().json().catch(()=>null))?.error===`client_tools_resend_required`;e++)u=!0,this.host.lastSentClientToolsFingerprint=null;return{response:d,commit:()=>{this.host.lastSentClientToolsFingerprint=o??null,this.host.clientToolsFingerprintSessionId=t,a?this.host.sentNonEmptyClientToolsSessionId=t:l&&(this.host.sentNonEmptyClientToolsSessionId=null)}}}async createClientSession(e){let n=this.host.isHistoryCapable()&&!e.omitVisitorFields,r=!e.omitVisitorFields,i=null;(n||r)&&(await this.host.historyInternals.historyBootstrapReady,i=await this.host.readVisitorToken());let a=this.host.routing(),o=a.agentId??a.flowId,s=n||e.durableResume?e.conversationId:void 0,c={token:this.host.config.clientToken,...o&&{flowId:o},...n&&{visitorHistory:!0},...r&&{durableRecovery:!0},...(n||r)&&i?{visitorToken:i}:{},...n&&e.identityProof?{identityProof:e.identityProof}:{},...s?{conversationId:s}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let l=await fetch(this.host.getClientApiUrl(`init`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":t},body:JSON.stringify(c),signal:e.signal});if(!l.ok){let t=await l.json().catch(()=>({error:`Session initialization failed`}));if(n&&l.status===403&&t.error===`visitor_history_disabled`){if(this.host.markHistoryUnavailable(),s)throw new this.host.HistoryClientError(`history_disabled`,`Visitor history is disabled for this surface`);return this.createClientSession({...e,omitVisitorFields:!0})}throw l.status===403&&t.error===`durable_recovery_disabled`?new this.host.HistoryClientError(`history_disabled`,`Durable recovery is disabled for this surface`):(n||e.durableResume)&&l.status===401&&t.error===`visitor_required`?new this.host.HistoryClientError(`visitor_required`,`Visitor credential no longer resolves`):s&&l.status===404?new this.host.HistoryClientError(`not_found`,`Conversation not found`):l.status===401?Error(`Invalid client token: ${t.hint||t.error}`):l.status===403?Error(`Origin not allowed: ${t.hint||t.error}`):Error(t.error||`Failed to initialize session`)}let u=await l.json();return u.visitor?.token&&await this.host.historyInternals.visitorStore?.set(u.visitor.token),{sessionId:u.sessionId,expiresAt:new Date(u.expiresAt),flow:u.flow,...u.conversationId?{conversationId:u.conversationId}:{},...u.targetId?{targetId:u.targetId}:{},...u.conversationRevision?{conversationRevision:u.conversationRevision}:{},...u.durableRecovery?{durableRecovery:u.durableRecovery}:{},...u.visitor?{visitor:u.visitor}:{},config:{welcomeMessage:u.config.welcomeMessage,placeholder:u.config.placeholder,theme:u.config.theme}}}async sendFeedback(e){if([`upvote`,`downvote`,`copy`].includes(e.type)&&!e.messageId)throw Error(`messageId is required for ${e.type} feedback type`);if(e.type===`csat`&&(e.rating===void 0||e.rating<1||e.rating>5))throw Error(`CSAT rating must be between 1 and 5`);if(e.type===`nps`&&(e.rating===void 0||e.rating<0||e.rating>10))throw Error(`NPS rating must be between 0 and 10`);this.host.debug&&console.debug(`[AgentWidgetClient] sending feedback`,e);let n={...e,...this.host.config.clientToken&&{token:this.host.config.clientToken}},r=await fetch(`${this.host.clientApiBase()}/v1/client/feedback`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":t},body:JSON.stringify(n)});if(!r.ok){let e=await r.json().catch(()=>({error:`Feedback submission failed`}));throw r.status===401?(this.host.clientSession=null,this.host.resetSessionWarmLatch(),this.host.config.onSessionExpired?.(),Error(`Session expired. Please refresh to continue.`)):Error(e.error||`Failed to submit feedback`)}}async dispatchClientToken(e,r,i){let{HistoryClientError:a}=this.host,o=()=>this.host.isCurrentTurn(i),s=e=>{o()&&r(e)};try{let r=()=>{if(e.signal?.throwIfAborted(),!o())throw new DOMException(`Turn superseded`,`AbortError`)},c=this.host.clientSession??await this.host.initSession();r();let l=async()=>{r();let t=c,n=t.durableRecovery?.enabled===!0;if(n&&(!t.conversationId||!await this.host.readVisitorToken()))throw Error(`Renewing this conversation requires its visitor credential.`);r();let i=await this.host.createClientSession({...n||this.host.isHistoryCapable()?{conversationId:t.conversationId,durableResume:n}:{storedSessionId:t.sessionId},signal:e.signal});if(r(),t.conversationId&&i.conversationId!==t.conversationId||n&&i.durableRecovery?.enabled!==!0)throw Error(`Session renewal did not preserve this conversation.`);c=this.host.finishInit(i,t.conversationId??null,!1),this.host.clientSession=c,this.host.resetSessionWarmLatch(),this.host.resetClientToolsFingerprint(),this.host.config.onSessionInit?.(c)};Date.now()>=c.expiresAt.getTime()-6e4&&await l();let d=new Map(u(e.messages).map(e=>[e,this.#s(e)])),f=await this.#l(e.messages,void 0,d),p=f.metadata?Object.fromEntries(Object.entries(f.metadata).filter(([e])=>e!==`sessionId`&&e!==`session_id`)):void 0,m=this.host.isHistoryCapable(),h={sessionId:c.sessionId,messages:u(e.messages).flatMap(e=>{let t=d.get(e);if(!t)return[];let r=m?n(e,t.content):void 0;return[{id:e.id,role:t.role,content:t.content,...r!==void 0&&{displayContent:r}}]}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...f.inputs&&Object.keys(f.inputs).length>0&&{inputs:f.inputs},...f.context&&{context:f.context},turnId:i,...e.interrupt&&{submitMode:`interrupt`},...e.voiceSpoken&&{voice:{spoken:!0,...e.voicePriorToolResults?.length&&{priorToolResults:e.voicePriorToolResults}}}},g=async()=>{r();let n=c.durableRecovery?.enabled===!0?await this.host.readVisitorToken():null;return r(),this.host.sendWithClientToolsDiff(c.sessionId,f.clientTools,async i=>{r();let a=await this.host.resolveChatIdentityProof(e.signal);r();let o={...h,sessionId:c.sessionId,...i,...a&&{identityProof:a}};return this.host.debug&&console.debug(`[AgentWidgetClient] client token dispatch`,{...o,...a&&{identityProof:{provider:a.provider,token:`[REDACTED]`}}}),fetch(this.host.getClientApiUrl(`chat`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":t,...n?{"X-Visitor-Token":n}:{}},body:JSON.stringify(o),signal:e.signal})})},_=await g();if(r(),_.response.status===401){let e=await _.response.clone().json().catch(()=>null);r(),e?.error===`Session not found or expired`&&(await l(),_=await g(),r())}let{response:v,commit:y}=_;if(!v.ok){let e=await v.json().catch(()=>({error:`Chat request failed`}));if(v.status===401&&e.error===`invalid_identity_proof`){let e=new a(`invalid_identity_proof`,`The identity proof was rejected`);throw s({type:`error`,error:e}),e}if(v.status===401){this.host.clearClientSession(),this.host.config.onSessionExpired?.();let e=/* @__PURE__ */ Error(`Session expired. Please refresh to continue.`);throw s({type:`error`,error:e}),e}if(v.status===429){let t=Error(e.hint||`Message limit reached for this session.`);throw s({type:`error`,error:t}),t}if(v.status===410&&e.error===`conversation_deleted`){let e=new a(`conversation_deleted`,`This conversation was deleted`);throw s({type:`error`,error:e}),e}let t=Error(e.error||`Failed to send message`);throw s({type:`error`,error:t}),t}if(!v.body){let e=/* @__PURE__ */ Error(`No response body received`);throw s({type:`error`,error:e}),e}y(),s({type:`status`,status:`connected`});try{await this.host.streamResponse(v.body,s,e.assistantMessageId,void 0,e.signal)}finally{s({type:`status`,status:`idle`})}}catch(e){let t=e instanceof Error?e:Error(String(e));throw!(t instanceof a)&&!t.message.includes(`Session expired`)&&!t.message.includes(`Message limit`)&&s({type:`error`,error:t}),t}}async dispatchProxy(e,t){let n=await this.#l(e.messages,e.composerOptions);this.host.debug&&console.debug(`[AgentWidgetClient] dispatch payload`,n);let r={...this.host.headers};if(this.host.getHeaders)try{let e=await this.host.getHeaders();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.host.customFetch)try{i=await this.host.customFetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.host.streamResponse(i.body,t,void 0,void 0,e.signal)}finally{t({type:`status`,status:`idle`})}}async dispatchAgent(e,t){let n=await this.#c(e.messages,e.composerOptions);this.host.debug&&console.debug(`[AgentWidgetClient] agent dispatch payload`,n);let r={...this.host.headers};if(this.host.getHeaders)try{let e=await this.host.getHeaders();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.host.customFetch)try{i=await this.host.customFetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.host.streamResponse(i.body,t,e.assistantMessageId,void 0,e.signal)}finally{t({type:`status`,status:`idle`})}}#r(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`user`)return n.mentionContext&&Object.keys(n.mentionContext).length>0?{mentions:n.mentionContext}:null}return null}async#i(e){let t={};this.host.contextProviders.length&&await Promise.all(this.host.contextProviders.map(async n=>{try{let r=await n({messages:e,config:this.host.config});r&&typeof r==`object`&&Object.assign(t,r)}catch(e){typeof console<`u`&&console.warn(`[AgentWidget] Context provider failed:`,e)}}));let n=this.#r(e);return n&&Object.assign(t,n),Object.keys(t).length?t:null}#a(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}#o(e,t){let n=t?.selectedModelId;return!n||!(`model`in e)?e:this.host.config.composer?.models?.some(e=>e.id===n)?{...e,model:n}:e}#s(e){if(!c(e))return null;let t=e.contentParts??e.llmContent??e.rawContent??e.content,n=e.role===`operator`?null:f(e),r=this.host.config.modelMessageTransform;if(!r)return n;let i=r({message:e,content:t,modelMessage:n});if(i===null)return null;if(!i||typeof i!=`object`||![`user`,`assistant`,`system`].includes(i.role)||!l(i.content)||typeof i.createdAt!=`string`)throw TypeError(`modelMessageTransform must return a supported model message or null`);return{role:i.role,content:i.content,createdAt:i.createdAt,...i.role===`assistant`&&i.phase&&{phase:i.phase}}}async#c(e,t){let n=this.host.routing().agentId;if(!this.host.config.agent&&!n)throw Error(`Agent configuration required for agent mode`);let r=s(u(e),e=>!e.variant||e.variant===`assistant`?this.#s(e):null),i=this.#a(t),a={agent:this.#o(this.host.config.agent??{agentId:n},i),messages:r,options:{streamResponse:!0,recordMode:`virtual`,...this.host.config.agentOptions}};i&&(a.composerOptions=i);let o=[...this.host.builtInClientTools(this.host.config),...await(await this.host.getWebMcpBridge())?.snapshotForDispatch()??[]];o.length>0&&(a.clientTools=o);let c=await this.#i(e);return c&&(a.context=c),a}async#l(e,t,n){let r=s(u(e),e=>n?n.get(e)??null:this.#s(e)),i=this.host.routing(),a={messages:r,...i.agentId?{agent:{agentId:i.agentId}}:i.flowId?{flowId:i.flowId}:{}};if(i.targetPayload)for(let[e,t]of Object.entries(i.targetPayload))e!==`messages`&&(a[e]=t);let o=[...this.host.builtInClientTools(this.host.config),...await(await this.host.getWebMcpBridge())?.snapshotForDispatch()??[]];o.length>0&&(a.clientTools=o);let c=await this.#i(e);c&&(a.context=c);let l=this.#a(t);if(l&&(a.composerOptions=l),this.host.requestMiddleware)try{let e=await this.host.requestMiddleware({payload:{...a},config:this.host.config});if(e&&typeof e==`object`){let t=e;return a.clientTools!==void 0&&!(`clientTools`in t)&&(t.clientTools=a.clientTools),t}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Request middleware error:`,e)}return a}};export{p as ClientDispatch};
1
+ import{n as e}from"./chunk-BAdIgC5d.js";import{t}from"./chunk-Dqa_GOcj.js";import{t as n}from"./chunk-i4qGOJAL.js";import{n as r}from"./chunk-DTDHeUsG.js";const i=e=>e.replace(/[^a-zA-Z0-9_]/g,`_`).toLowerCase().replace(/_+/g,`_`).replace(/^_|_$/g,``),a=e=>typeof e==`object`&&!!e&&!Array.isArray(e),o=e=>{if(e.variant!==`tool`)return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=i(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:a(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},s=(e,t)=>{let n=[],r=[],i=[],a=``,s,c=()=>{r.length!==0&&(n.push({role:`assistant`,content:``,createdAt:a,toolCalls:r},{role:`tool`,content:``,createdAt:a,toolResults:i}),r=[],i=[])};for(let l of e){let e=o(l);if(e){let t=l.agentMetadata?.clientToolAnswer?.batch;r.length>0&&(t===void 0||t!==s)&&c(),r.length===0&&(a=l.createdAt,s=t),r.some(t=>t.toolCallId===e.call.toolCallId)||(r.push(e.call),i.push(e.result));continue}let u=t(l);u&&(c(),n.push(u))}return c(),n},c=e=>e.voiceCaption||r(e)?!1:!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0),l=e=>typeof e==`string`?!0:Array.isArray(e)?e.every(e=>{if(!e||typeof e!=`object`)return!1;switch(e.type){case`text`:return typeof e.text==`string`;case`image`:return typeof e.image==`string`;case`audio`:return typeof e.audio==`string`;case`video`:return typeof e.video==`string`;case`file`:return typeof e.data==`string`&&typeof e.mimeType==`string`&&typeof e.filename==`string`;default:return!1}}):!1,u=e=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),d=e=>{let t=e.agentMetadata?.providerPhase??e.agentMetadata?.phase;return e.role===`assistant`&&(t===`commentary`||t===`partial_answer`||t===`final_answer`)?{phase:t}:{}},f=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt,...d(e)});var p=class{constructor(e){this.host=e}async initializeSession(){await this.host.historyInternals.historyBootstrapReady;let e=this.host.config.getStoredConversationId?.()||null,t=this.host.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.host.isHistoryCapable()&&!t)return this.#e(e,!1);let n=await this.host.readVisitorToken();if(e&&n)try{let n=await this.createClientSession({conversationId:e,durableResume:t});return t&&n.durableRecovery?.enabled!==!0&&this.host.historyInternals.setStoredResumableHandle?.(null),this.host.finishInit(n,e,!1)}catch(n){if(!(n instanceof this.host.HistoryClientError&&n.code===`not_found`)&&!(n instanceof this.host.HistoryClientError&&n.code===`visitor_required`)&&!(n instanceof this.host.HistoryClientError&&n.code===`history_disabled`))throw n;return t&&this.host.historyInternals.setStoredResumableHandle?.(null),this.#e(e,!0)}return this.#e(e,!1)}async#e(e,t){let n=this.host.historyInternals.visitorStore;return n&&!await this.host.readVisitorToken()?n.withFirstInitLock(()=>this.#t(e,t)):this.#t(e,t)}async#t(e,t){let n=this.host.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:n}),i=await this.#n(r);return this.host.finishInit(i,e,t)}async#n(e){if(!e.visitor?.token||this.host.claimInFlight||!this.host.isHistoryCapable()&&e.durableRecovery?.enabled!==!0)return e;this.host.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:e.sessionId})}catch{return e}finally{this.host.claimInFlight=!1}}async sendWithClientToolsDiff(t,n,r,i){let a=!!(n&&n.length>0),o=a?e(n):void 0,s=this.host.clientToolsFingerprintSessionId===t,c=a&&s&&this.host.lastSentClientToolsFingerprint===o,l=!a&&i?.emptyMeansReplace===!0&&this.host.sentNonEmptyClientToolsSessionId===t,u=!1,d;for(let e=0;d=await r({...a&&(u||!c)&&n?{clientTools:n}:{},...l?{clientTools:[]}:{},...o?{clientToolsFingerprint:o}:{}}),d.status===409&&e===0&&a&&(await d.clone().json().catch(()=>null))?.error===`client_tools_resend_required`;e++)u=!0,this.host.lastSentClientToolsFingerprint=null;return{response:d,commit:()=>{this.host.lastSentClientToolsFingerprint=o??null,this.host.clientToolsFingerprintSessionId=t,a?this.host.sentNonEmptyClientToolsSessionId=t:l&&(this.host.sentNonEmptyClientToolsSessionId=null)}}}async createClientSession(e){let n=this.host.isHistoryCapable()&&!e.omitVisitorFields,r=!e.omitVisitorFields,i=null;(n||r)&&(await this.host.historyInternals.historyBootstrapReady,i=await this.host.readVisitorToken());let a=this.host.routing(),o=a.agentId??a.flowId,s=n||e.durableResume?e.conversationId:void 0,c={token:this.host.config.clientToken,...o&&{flowId:o},...n&&{visitorHistory:!0},...r&&{durableRecovery:!0},...(n||r)&&i?{visitorToken:i}:{},...n&&e.identityProof?{identityProof:e.identityProof}:{},...s?{conversationId:s}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let l=await fetch(this.host.getClientApiUrl(`init`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":t},body:JSON.stringify(c),signal:e.signal});if(!l.ok){let t=await l.json().catch(()=>({error:`Session initialization failed`}));if(n&&l.status===403&&t.error===`visitor_history_disabled`){if(this.host.markHistoryUnavailable(),s)throw new this.host.HistoryClientError(`history_disabled`,`Visitor history is disabled for this surface`);return this.createClientSession({...e,omitVisitorFields:!0})}throw l.status===403&&t.error===`durable_recovery_disabled`?new this.host.HistoryClientError(`history_disabled`,`Durable recovery is disabled for this surface`):(n||e.durableResume)&&l.status===401&&t.error===`visitor_required`?new this.host.HistoryClientError(`visitor_required`,`Visitor credential no longer resolves`):s&&l.status===404?new this.host.HistoryClientError(`not_found`,`Conversation not found`):l.status===401?Error(`Invalid client token: ${t.hint||t.error}`):l.status===403?Error(`Origin not allowed: ${t.hint||t.error}`):Error(t.error||`Failed to initialize session`)}let u=await l.json();return u.visitor?.token&&await this.host.historyInternals.visitorStore?.set(u.visitor.token),{sessionId:u.sessionId,expiresAt:new Date(u.expiresAt),flow:u.flow,...u.conversationId?{conversationId:u.conversationId}:{},...u.targetId?{targetId:u.targetId}:{},...u.conversationRevision?{conversationRevision:u.conversationRevision}:{},...u.durableRecovery?{durableRecovery:u.durableRecovery}:{},...u.visitor?{visitor:u.visitor}:{},config:{welcomeMessage:u.config.welcomeMessage,placeholder:u.config.placeholder,theme:u.config.theme}}}async sendFeedback(e){if([`upvote`,`downvote`,`copy`].includes(e.type)&&!e.messageId)throw Error(`messageId is required for ${e.type} feedback type`);if(e.type===`csat`&&(e.rating===void 0||e.rating<1||e.rating>5))throw Error(`CSAT rating must be between 1 and 5`);if(e.type===`nps`&&(e.rating===void 0||e.rating<0||e.rating>10))throw Error(`NPS rating must be between 0 and 10`);this.host.debug&&console.debug(`[AgentWidgetClient] sending feedback`,e);let n={...e,...this.host.config.clientToken&&{token:this.host.config.clientToken}},r=await fetch(`${this.host.clientApiBase()}/v1/client/feedback`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":t},body:JSON.stringify(n)});if(!r.ok){let e=await r.json().catch(()=>({error:`Feedback submission failed`}));throw r.status===401?(this.host.clientSession=null,this.host.resetSessionWarmLatch(),this.host.config.onSessionExpired?.(),Error(`Session expired. Please refresh to continue.`)):Error(e.error||`Failed to submit feedback`)}}async dispatchClientToken(e,r,i){let{HistoryClientError:a}=this.host,o=()=>this.host.isCurrentTurn(i),s=e=>{o()&&r(e)};try{let r=()=>{if(e.signal?.throwIfAborted(),!o())throw new DOMException(`Turn superseded`,`AbortError`)},c=this.host.clientSession??await this.host.initSession();r();let l=async()=>{r();let t=c,n=t.durableRecovery?.enabled===!0;if(n&&(!t.conversationId||!await this.host.readVisitorToken()))throw Error(`Renewing this conversation requires its visitor credential.`);r();let i=await this.host.createClientSession({...n||this.host.isHistoryCapable()?{conversationId:t.conversationId,durableResume:n}:{storedSessionId:t.sessionId},signal:e.signal});if(r(),t.conversationId&&i.conversationId!==t.conversationId||n&&i.durableRecovery?.enabled!==!0)throw Error(`Session renewal did not preserve this conversation.`);c=this.host.finishInit(i,t.conversationId??null,!1),this.host.clientSession=c,this.host.resetSessionWarmLatch(),this.host.resetClientToolsFingerprint(),this.host.config.onSessionInit?.(c)};Date.now()>=c.expiresAt.getTime()-6e4&&await l();let d=new Map(u(e.messages).map(e=>[e,this.#s(e)])),f=await this.#l(e.messages,void 0,d),p=f.metadata?Object.fromEntries(Object.entries(f.metadata).filter(([e])=>e!==`sessionId`&&e!==`session_id`)):void 0,m=this.host.isHistoryCapable(),h={sessionId:c.sessionId,messages:u(e.messages).flatMap(e=>{let t=d.get(e);if(!t)return[];let r=m?n(e,t.content):void 0;return[{id:e.id,role:t.role,content:t.content,...r!==void 0&&{displayContent:r}}]}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...f.inputs&&Object.keys(f.inputs).length>0&&{inputs:f.inputs},...f.context&&{context:f.context},turnId:i,...e.interrupt&&{submitMode:`interrupt`},...e.voiceSpoken&&{voice:{spoken:!0,...e.voicePriorToolResults?.length&&{priorToolResults:e.voicePriorToolResults}}}},g=async()=>{r();let n=c.durableRecovery?.enabled===!0?await this.host.readVisitorToken():null;return r(),this.host.sendWithClientToolsDiff(c.sessionId,f.clientTools,async i=>{r();let a=await this.host.resolveChatIdentityProof(e.signal);r();let o={...h,sessionId:c.sessionId,...i,...a&&{identityProof:a}};return this.host.debug&&console.debug(`[AgentWidgetClient] client token dispatch`,{...o,...a&&{identityProof:{provider:a.provider,token:`[REDACTED]`}}}),fetch(this.host.getClientApiUrl(`chat`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":t,...n?{"X-Visitor-Token":n}:{}},body:JSON.stringify(o),signal:e.signal})})},_=await g();if(r(),_.response.status===401){let e=await _.response.clone().json().catch(()=>null);r(),e?.error===`Session not found or expired`&&(await l(),_=await g(),r())}let{response:v,commit:y}=_;if(!v.ok){let e=await v.json().catch(()=>({error:`Chat request failed`}));if(v.status===401&&e.error===`invalid_identity_proof`){let e=new a(`invalid_identity_proof`,`The identity proof was rejected`);throw s({type:`error`,error:e}),e}if(v.status===401){this.host.clearClientSession(),this.host.config.onSessionExpired?.();let e=/* @__PURE__ */ Error(`Session expired. Please refresh to continue.`);throw s({type:`error`,error:e}),e}if(v.status===429){let t=Error(e.hint||`Message limit reached for this session.`);throw s({type:`error`,error:t}),t}if(v.status===410&&e.error===`conversation_deleted`){let e=new a(`conversation_deleted`,`This conversation was deleted`);throw s({type:`error`,error:e}),e}let t=Error(e.error||`Failed to send message`);throw s({type:`error`,error:t}),t}if(!v.body){let e=/* @__PURE__ */ Error(`No response body received`);throw s({type:`error`,error:e}),e}y(),s({type:`status`,status:`connected`});try{await this.host.streamResponse(v.body,s,e.assistantMessageId,void 0,e.signal)}finally{s({type:`status`,status:`idle`})}}catch(e){let t=e instanceof Error?e:Error(String(e));throw t instanceof a||t.message.includes(`Session expired`)||t.message.includes(`Message limit`)||s({type:`error`,error:t}),t}}async dispatchProxy(e,t){let n=await this.#l(e.messages,e.composerOptions);this.host.debug&&console.debug(`[AgentWidgetClient] dispatch payload`,n);let r={...this.host.headers};if(this.host.getHeaders)try{let e=await this.host.getHeaders();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.host.customFetch)try{i=await this.host.customFetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.host.streamResponse(i.body,t,void 0,void 0,e.signal)}finally{t({type:`status`,status:`idle`})}}async dispatchAgent(e,t){let n=await this.#c(e.messages,e.composerOptions);this.host.debug&&console.debug(`[AgentWidgetClient] agent dispatch payload`,n);let r={...this.host.headers};if(this.host.getHeaders)try{let e=await this.host.getHeaders();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.host.customFetch)try{i=await this.host.customFetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.host.streamResponse(i.body,t,e.assistantMessageId,void 0,e.signal)}finally{t({type:`status`,status:`idle`})}}#r(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`user`)return n.mentionContext&&Object.keys(n.mentionContext).length>0?{mentions:n.mentionContext}:null}return null}async#i(e){let t={};this.host.contextProviders.length&&await Promise.all(this.host.contextProviders.map(async n=>{try{let r=await n({messages:e,config:this.host.config});r&&typeof r==`object`&&Object.assign(t,r)}catch(e){typeof console<`u`&&console.warn(`[AgentWidget] Context provider failed:`,e)}}));let n=this.#r(e);return n&&Object.assign(t,n),Object.keys(t).length?t:null}#a(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}#o(e,t){let n=t?.selectedModelId;return!n||!(`model`in e)?e:this.host.config.composer?.models?.some(e=>e.id===n)?{...e,model:n}:e}#s(e){if(!c(e))return null;let t=e.contentParts??e.llmContent??e.rawContent??e.content,n=e.role===`operator`?null:f(e),r=this.host.config.modelMessageTransform;if(!r)return n;let i=r({message:e,content:t,modelMessage:n});if(i===null)return null;if(!i||typeof i!=`object`||![`user`,`assistant`,`system`].includes(i.role)||!l(i.content)||typeof i.createdAt!=`string`)throw TypeError(`modelMessageTransform must return a supported model message or null`);return{role:i.role,content:i.content,createdAt:i.createdAt,...i.role===`assistant`&&i.phase&&{phase:i.phase}}}async#c(e,t){let n=this.host.routing().agentId;if(!this.host.config.agent&&!n)throw Error(`Agent configuration required for agent mode`);let r=s(u(e),e=>!e.variant||e.variant===`assistant`?this.#s(e):null),i=this.#a(t),a={agent:this.#o(this.host.config.agent??{agentId:n},i),messages:r,options:{streamResponse:!0,recordMode:`virtual`,...this.host.config.agentOptions}};i&&(a.composerOptions=i);let o=[...this.host.builtInClientTools(this.host.config),...await(await this.host.getWebMcpBridge())?.snapshotForDispatch()??[]];o.length>0&&(a.clientTools=o);let c=await this.#i(e);return c&&(a.context=c),a}async#l(e,t,n){let r=s(u(e),e=>n?n.get(e)??null:this.#s(e)),i=this.host.routing(),a={messages:r,...i.agentId?{agent:{agentId:i.agentId}}:i.flowId?{flowId:i.flowId}:{}};if(i.targetPayload)for(let[e,t]of Object.entries(i.targetPayload))e!==`messages`&&(a[e]=t);let o=[...this.host.builtInClientTools(this.host.config),...await(await this.host.getWebMcpBridge())?.snapshotForDispatch()??[]];o.length>0&&(a.clientTools=o);let c=await this.#i(e);c&&(a.context=c);let l=this.#a(t);if(l&&(a.composerOptions=l),this.host.requestMiddleware)try{let e=await this.host.requestMiddleware({payload:{...a},config:this.host.config});if(e&&typeof e==`object`){let t=e;return a.clientTools!==void 0&&!(`clientTools`in t)&&(t.clientTools=a.clientTools),t}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Request middleware error:`,e)}return a}};export{p as ClientDispatch};
@@ -1 +1 @@
1
- import{r as e}from"./chunk-D5BxWOFB.js";var t=class{constructor(e){this.callbacks=e,this.state=Object.freeze({phase:`idle`,recordingId:0,transcript:``,interimTranscript:``,error:null,audioLevel:null}),this.provider=null,this.generation=0,this.destroyed=!1,this.sendOnCompletion=!1,this.sent=!1,this.ready=!1,this.finishRequested=!1,this.disconnecting=Promise.resolve()}getState(){return this.state}refresh(){this.destroyed||this.callbacks.onState(this.state,!1)}publish(e,t=!1){this.state=Object.freeze({...this.state,...e}),this.callbacks.onState(this.state,t)}start(e,t){if(this.destroyed||this.state.phase===`recording`||this.state.phase===`processing`)return!1;this.release();let r=++this.generation;this.sendOnCompletion=t.autoSend,this.sent=!1,this.ready=!1,this.finishRequested=!1,this.publish({phase:`recording`,recordingId:r,transcript:``,interimTranscript:``,error:null,audioLevel:null});let i=()=>!this.destroyed&&r===this.generation&&[`recording`,`processing`].includes(this.state.phase);try{let r=e.custom,a=e.type===`custom`?typeof r==`function`?r():r:n(e.browser,t.pauseDuration);if(!a||a.type===`runtype`)throw Error(`Dictation requires a speech-to-text provider.`);this.provider=a;let o=(e,t)=>{i()&&(t?(this.publish({transcript:e,interimTranscript:``}),this.complete()):this.publish({interimTranscript:e}))};a.onResult(e=>o(e.text,e.isFinal!==!1)),a.onTranscript?.((e,t,n)=>{e===`user`&&o(t,n)}),a.onLevel?.(e=>{i()&&this.state.phase===`recording`&&Number.isFinite(e)&&this.publish({audioLevel:Math.max(0,Math.min(1,e))},!0)}),a.onError(e=>{i()&&this.fail(e)}),a.onProcessingStart?.(()=>{i()&&this.publish({phase:`processing`,audioLevel:null})}),a.onStatusChange(e=>{i()&&(e===`processing`&&this.publish({phase:`processing`,audioLevel:null}),e===`idle`&&this.complete(),e===`error`&&this.fail(/* @__PURE__ */ Error(`Speech recognition failed.`)))}),this.disconnecting.then(async()=>{i()&&(await a.connect(),i()?(await a.startListening(),i()?(this.ready=!0,this.finishRequested&&await a.stopListening()):await a.disconnect()):await a.disconnect())}).catch(e=>{i()&&this.fail(e)})}catch(e){this.fail(e)}return!0}finish(e=!1){if(this.state.phase===`review`)return e?this.send():!1;if(this.state.phase!==`recording`)return!1;this.sendOnCompletion||=e;let t=this.generation;return this.publish({phase:`processing`,audioLevel:null}),this.finishRequested=!0,this.ready&&this.provider?.stopListening().catch(e=>{t===this.generation&&this.state.phase===`processing`&&this.fail(e)}),!0}cancel(){return this.destroyed||this.state.phase===`idle`?!1:(++this.generation,this.release(),this.publish({phase:`idle`,transcript:``,interimTranscript:``,error:null,audioLevel:null}),!0)}send(){return this.destroyed||this.state.phase!==`review`||this.sent?!1:(this.sent=!0,this.publish({phase:`idle`,audioLevel:null}),this.callbacks.onSend(),!0)}complete(){if(![`recording`,`processing`].includes(this.state.phase))return;let e=(this.state.transcript||this.state.interimTranscript).trim();e?(this.state.phase===`recording`&&this.publish({phase:`processing`,audioLevel:null}),this.release(),this.callbacks.onReview(e),this.publish({phase:`review`,transcript:e,interimTranscript:``,audioLevel:null}),this.sendOnCompletion&&this.send()):this.fail(/* @__PURE__ */ Error(`No speech was recognized.`))}fail(e){this.release(),this.publish({phase:`error`,error:e instanceof Error?e.message:String(e),audioLevel:null})}release(){let e=this.provider;this.provider=null,e&&(this.disconnecting=this.disconnecting.then(()=>e.disconnect()).catch(()=>{}))}destroy(){this.destroyed=!0,++this.generation,this.release()}};function n(e,t=2e3){let n=window,r=n.SpeechRecognition??n.webkitSpeechRecognition;if(!r)throw Error(`Browser speech recognition is unavailable.`);let i=new r;i.lang=e?.language??`en-US`,i.continuous=e?.continuous??!0,i.interimResults=!0;let a=``,o,s=!1,c=()=>{},l=()=>{},u=()=>{},d=()=>{clearTimeout(o),o=void 0};return i.onresult=e=>{s||(a=Array.from(e.results).map(e=>e[0].transcript).join(` `),c({text:a,provider:`browser`,isFinal:!1}),d(),a.trim()&&(o=setTimeout(()=>{u(`processing`),i.stop()},t)))},i.onend=()=>{s||(d(),c({text:a,provider:`browser`}),u(`idle`))},i.onerror=({error:e})=>{!s&&e!==`no-speech`&&l(Error(e))},{type:`browser`,connect:async()=>{},startListening:async()=>{i.start()},stopListening:async()=>{d(),i.stop()},disconnect:async()=>{s=!0,d(),i.abort(),i.onresult=null,i.onend=null,i.onerror=null},onResult:e=>{c=e},onError:e=>{l=e},onStatusChange:e=>{u=e}}}function r(t,{renderLucideIcon:n,attachTooltip:r}){let i=t,a=e(`section`,{className:`persona-dictation`,attrs:{"data-persona-dictation":``,"aria-label":`Voice dictation`},style:{display:`flex`,flexWrap:`wrap`,alignItems:`center`,gap:`12px`,width:`100%`,minWidth:`0`,gridColumn:`1 / -1`,color:`var(--persona-text, #18181b)`,fontFamily:`inherit`,fontSize:`var(--persona-composer-font-size, 16px)`,lineHeight:`1.5`}}),o=e(`div`,{attrs:{"data-persona-dictation-transcript":``,dir:`auto`},style:{flex:`1 1 auto`,width:`max-content`,maxWidth:`100%`,boxSizing:`border-box`,whiteSpace:`pre-wrap`,overflowWrap:`anywhere`,maxHeight:`120px`,overflowY:`auto`,padding:`2px 4px`}}),s=e(`span`),c=e(`span`,{attrs:{"data-persona-dictation-interim":``}});o.append(s,c);let l=e(`div`,{style:{display:`flex`,flex:`0 1 auto`,alignItems:`center`,gap:`10px`,width:`100%`,maxWidth:`100%`,minWidth:`0`,marginInlineStart:`auto`}}),u=e(`div`,{attrs:{role:`status`,"aria-live":`polite`,"aria-atomic":`true`},style:{flex:`1 1 0`,minWidth:`0`,color:`var(--persona-input-placeholder, var(--persona-text-muted, #71717a))`}}),d=e(`div`,{attrs:{"data-persona-dictation-waveform":``,"aria-hidden":`true`},style:{alignItems:`center`,justifyContent:`center`,gap:`4px`,height:`36px`,minWidth:`0`,color:`var(--persona-input-placeholder, var(--persona-text-muted, #71717a))`}}),f=Array.from({length:19},()=>e(`span`,{style:{width:`3px`,flexShrink:`0`,borderRadius:`3px`,background:`currentColor`}}));d.append(...f);let p=[],m=(t,a,o)=>{let s=e(`button`,{className:`persona-composer-control`,attrs:{type:`button`,"aria-label":a,"data-persona-dictation-action":t},style:{flexShrink:`0`,borderRadius:`50%`,alignItems:`center`,justifyContent:`center`,border:`1px solid var(--persona-border, #d4d4d8)`,color:`inherit`,background:`transparent`,cursor:`pointer`,padding:`0`}}),c=n(o,18,`currentColor`,2);return c?s.append(c):s.textContent=a,s.addEventListener(`click`,()=>i.actions[t]?.()),p.push(r({anchor:s,text:()=>s.getAttribute(`aria-label`)??a})),s},h=m(`cancel`,`Cancel dictation`,`x`),g=m(`finish`,`Finish dictation`,`check`),_=m(`send`,`Finish and send`,`arrow-up`);l.append(u,d,h,g,_),a.append(o,l);let v=(e,t,n=`block`)=>{e.hidden=!t,e.style.display=t?n:`none`},y=e=>{let t=i.state;i=e;let{state:n}=e,r=e.config.voiceRecognition?.dictation??{},p=r.display===`waveform`,m=!!(n.transcript||n.interimTranscript);v(a,n.phase!==`idle`&&n.phase!==`review`,`flex`),a.dataset.phase=n.phase,a.dataset.display=r.display??`transcript`,(n.phase!==t.phase||n.error!==t.error||!u.textContent)&&(u.textContent=n.phase===`recording`?`Listening…`:n.phase===`processing`?`Transcribing…`:n.error??``),s.textContent=n.transcript,c.textContent=n.interimTranscript,c.style.fontStyle=r.interimText?.fontStyle??`italic`,c.style.color=r.interimText?.color??`var(--persona-input-placeholder, var(--persona-text-muted, #71717a))`,u.style.fontStyle=n.phase===`recording`&&!p?r.interimText?.fontStyle??`italic`:`normal`,v(o,m&&r.display!==`inline`&&!p&&n.phase!==`error`),l.style.width=o.hidden?`100%`:`auto`;let y=(r.waveform??p)&&n.audioLevel!==null&&n.phase===`recording`;v(d,y,`flex`);let b=n.phase===`recording`&&(p?y:m);u.className=b?`persona-sr-only`:``,u.style.flex=b?`0 0 auto`:`1 1 0`,d.style.flex=p?`1 1 0`:`0 1 140px`,d.style.width=p?``:`140px`,d.style.marginInlineStart=`auto`,h.style.order=p?`-1`:`0`;let x=a.ownerDocument.defaultView?.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches;f.forEach((e,t)=>{let r=x?6:3+(n.audioLevel??0)*Math.max(2,31-Math.abs(9-t)*3);e.style.height=`${r}px`,e.style.transition=x?`none`:`height 80ms linear`}),v(h,r.showCancel!==!1,`inline-flex`),v(g,r.showFinish!==!1&&n.phase!==`error`,`inline-flex`),g.disabled=n.phase!==`recording`,g.style.opacity=g.disabled?`0.45`:`1`,v(_,!!e.actions.send&&n.phase!==`error`,`inline-flex`),_.disabled=n.phase!==`recording`,_.style.opacity=_.disabled?`0.45`:`1`};return y(t),{element:a,update:y,destroy:()=>{p.forEach(e=>e.destroy()),a.remove()}}}function i(e){let n=null,i=``,a=null,o=!1,s=null,c=`idle`,l=/* @__PURE__ */ new Map,u=()=>{for(let[e,t]of l)e.style.display=t;l.clear()},d=(t=``)=>{let n=(i&&t&&!/\s$/.test(i)?` `:``)+t,r=e.getInlineInput();r?.replaceLogicalRange&&a!==null?(r.replaceLogicalRange(a,r.getLogicalText().length,n),r.dispatchInput()):e.getTextarea().value=i+n,e.syncText()},f=new t({onReview:d,onSend:()=>{e.isSendBlocked()||e.onSend()},onState:(t,i)=>{let a=e.getConfig(),p=e.getTextarea(),m=e.getFooter(),h=c;c=t.phase;let g=t.phase===`recording`||t.phase===`processing`;if(p.readOnly=g||o,p instanceof HTMLTextAreaElement||p.setAttribute(`contenteditable`,g||e.isInputDisabled()?`false`:s??`true`),t.phase===`idle`&&[`recording`,`processing`,`error`].includes(h))d();else if(g&&a.voiceRecognition?.dictation?.display===`inline`){let e=t.transcript||t.interimTranscript;d(e)}t.phase===`error`&&d();let _={instanceId:e.instanceId,state:t,config:a,actions:{cancel:()=>{f.cancel()},finish:()=>{f.finish()},...a.voiceRecognition?.dictation?.showSend&&!e.isSendBlocked()?{send:()=>{e.isSendBlocked()||f.finish(!0)||f.send()}}:{}},defaultRenderer:()=>r(_,e.rendererDeps)},v=[`recording`,`processing`,`error`].includes(t.phase);if(!n&&v){for(let t of e.plugins){let e=t.renderDictation?.(_);if(e){n=e instanceof HTMLElement?{element:e}:e;break}}n??=_.defaultRenderer(),n.element.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),f.cancel())})}if(n&&v){let e=m.querySelector(`[data-persona-composer-form]`)??m;n.element.parentElement!==e&&e.append(n.element),u();let r=a.voiceRecognition?.dictation?.display===`inline`?Array.from(e.querySelectorAll(`[data-persona-composer-actions-start], [data-persona-composer-actions-end]`)):Array.from(e.children).filter(e=>e instanceof HTMLElement&&e!==n?.element);for(let e of r)l.set(e,e.style.display),e.style.display=`none`;n.update?.(_),(t.phase===`recording`&&h!==`recording`&&h!==`processing`||t.phase===`error`&&h!==`error`)&&n.element.querySelector(`button:not(:disabled), [tabindex]`)?.focus()}else u(),n?.destroy?.(),n?.element.remove(),n=null,(t.phase===`review`||t.phase===`idle`)&&t.phase!==h&&p.focus();i||e.onState(t,g)}});return{start(e,t,n){return i=n.text,a=n.logicalEnd,o=n.readOnly,s=n.contentEditable,f.start(e,t)},getState:()=>f.getState(),refresh:()=>f.refresh(),cancel:()=>f.cancel(),finish:(e=!1)=>f.finish(e),send:()=>f.send(),destroy(){f.destroy(),u(),n?.destroy?.(),n?.element.remove()}}}function a(e){let t=`--persona-voice-level`,n=.5,r=null,i=-1,a=0,o=n=>{let r=Math.round(Math.max(0,Math.min(1,n))*100)/100;if(r!==i){i=r;for(let n of e.targets())n.style.setProperty(t,String(r))}},s=()=>{i=-1,a=0;for(let n of e.targets())n.style.removeProperty(t)};function c(){if(r!==null)return;if(typeof requestAnimationFrame!=`function`){o(e.sample().level??n);return}let t=()=>{r=requestAnimationFrame(t);let{level:i,fallback:c}=e.sample();i===null&&!c?s():i===null?o(n):(a+=(i-a)*.3,o(a))};r=requestAnimationFrame(t)}function l(){r!==null&&(cancelAnimationFrame(r),r=null),s()}return{start:c,stop:l}}function o(e){let t=null;return{result:n=>{if(!e.isActive())return;let r=``,i=``;for(let e=0;e<n.results.length;e++){let t=n.results[e],a=t[0].transcript;t.isFinal?r+=a+` `:i=a}let a=e.initialText+r+i;e.textarea.value=a,e.syncText(),t&&clearTimeout(t),(r||i)&&(t=window.setTimeout(()=>{if(e.textarea.value.trim()&&e.isActive()){if(e.stop(),e.review())return;e.submit()}},e.pauseDuration))},error:t=>{e.isActive()&&t.error!==`no-speech`&&e.stop()},end:()=>{if(e.isActive()&&e.isActive()){let t=e.textarea.value.trim();!e.review()&&t&&t!==e.initialText.trim()&&e.submit(),e.stop()}},dispose:()=>{t!==null&&clearTimeout(t),t=null}}}export{t as DictationController,o as createBrowserRecognitionHandlers,r as createDictationRenderer,i as createDictationSession,a as createVoiceLevelIndicator};
1
+ import{r as e}from"./chunk-D5BxWOFB.js";var t=class{constructor(e){this.callbacks=e,this.state=Object.freeze({phase:`idle`,recordingId:0,transcript:``,interimTranscript:``,error:null,audioLevel:null}),this.provider=null,this.generation=0,this.destroyed=!1,this.sendOnCompletion=!1,this.sent=!1,this.ready=!1,this.finishRequested=!1,this.disconnecting=Promise.resolve()}getState(){return this.state}refresh(){this.destroyed||this.callbacks.onState(this.state,!1)}publish(e,t=!1){this.state=Object.freeze({...this.state,...e}),this.callbacks.onState(this.state,t)}start(e,t){if(this.destroyed||this.state.phase===`recording`||this.state.phase===`processing`)return!1;this.release();let r=++this.generation;this.sendOnCompletion=t.autoSend,this.sent=!1,this.ready=!1,this.finishRequested=!1,this.publish({phase:`recording`,recordingId:r,transcript:``,interimTranscript:``,error:null,audioLevel:null});let i=()=>!this.destroyed&&r===this.generation&&[`recording`,`processing`].includes(this.state.phase);try{let r=e.custom,a=e.type===`custom`?typeof r==`function`?r():r:n(e.browser,t.pauseDuration);if(!a||a.type===`runtype`)throw Error(`Dictation requires a speech-to-text provider.`);this.provider=a;let o=(e,t)=>{i()&&(t?(this.publish({transcript:e,interimTranscript:``}),this.complete()):this.publish({interimTranscript:e}))};a.onResult(e=>o(e.text,e.isFinal!==!1)),a.onTranscript?.((e,t,n)=>{e===`user`&&o(t,n)}),a.onLevel?.(e=>{i()&&this.state.phase===`recording`&&Number.isFinite(e)&&this.publish({audioLevel:Math.max(0,Math.min(1,e))},!0)}),a.onError(e=>{i()&&this.fail(e)}),a.onProcessingStart?.(()=>{i()&&this.publish({phase:`processing`,audioLevel:null})}),a.onStatusChange(e=>{i()&&(e===`processing`&&this.publish({phase:`processing`,audioLevel:null}),e===`idle`&&this.complete(),e===`error`&&this.fail(/* @__PURE__ */ Error(`Speech recognition failed.`)))}),this.disconnecting.then(async()=>{i()&&(await a.connect(),i()?(await a.startListening(),i()?(this.ready=!0,this.finishRequested&&await a.stopListening()):await a.disconnect()):await a.disconnect())}).catch(e=>{i()&&this.fail(e)})}catch(e){this.fail(e)}return!0}finish(e=!1){if(this.state.phase===`review`)return e?this.send():!1;if(this.state.phase!==`recording`)return!1;this.sendOnCompletion||=e;let t=this.generation;return this.publish({phase:`processing`,audioLevel:null}),this.finishRequested=!0,this.ready&&this.provider?.stopListening().catch(e=>{t===this.generation&&this.state.phase===`processing`&&this.fail(e)}),!0}cancel(){return this.destroyed||this.state.phase===`idle`?!1:(++this.generation,this.release(),this.publish({phase:`idle`,transcript:``,interimTranscript:``,error:null,audioLevel:null}),!0)}send(){return this.destroyed||this.state.phase!==`review`||this.sent?!1:(this.sent=!0,this.publish({phase:`idle`,audioLevel:null}),this.callbacks.onSend(),!0)}complete(){if(![`recording`,`processing`].includes(this.state.phase))return;let e=(this.state.transcript||this.state.interimTranscript).trim();e?(this.state.phase===`recording`&&this.publish({phase:`processing`,audioLevel:null}),this.release(),this.callbacks.onReview(e),this.publish({phase:`review`,transcript:e,interimTranscript:``,audioLevel:null}),this.sendOnCompletion&&this.send()):this.fail(/* @__PURE__ */ Error(`No speech was recognized.`))}fail(e){this.release(),this.publish({phase:`error`,error:e instanceof Error?e.message:String(e),audioLevel:null})}release(){let e=this.provider;this.provider=null,e&&(this.disconnecting=this.disconnecting.then(()=>e.disconnect()).catch(()=>{}))}destroy(){this.destroyed=!0,++this.generation,this.release()}};function n(e,t=2e3){let n=window,r=n.SpeechRecognition??n.webkitSpeechRecognition;if(!r)throw Error(`Browser speech recognition is unavailable.`);let i=new r;i.lang=e?.language??`en-US`,i.continuous=e?.continuous??!0,i.interimResults=!0;let a=``,o,s=!1,c=()=>{},l=()=>{},u=()=>{},d=()=>{clearTimeout(o),o=void 0};return i.onresult=e=>{s||(a=Array.from(e.results).map(e=>e[0].transcript).join(` `),c({text:a,provider:`browser`,isFinal:!1}),d(),a.trim()&&(o=setTimeout(()=>{u(`processing`),i.stop()},t)))},i.onend=()=>{s||(d(),c({text:a,provider:`browser`}),u(`idle`))},i.onerror=({error:e})=>{!s&&e!==`no-speech`&&l(Error(e))},{type:`browser`,connect:async()=>{},startListening:async()=>{i.start()},stopListening:async()=>{d(),i.stop()},disconnect:async()=>{s=!0,d(),i.abort(),i.onresult=null,i.onend=null,i.onerror=null},onResult:e=>{c=e},onError:e=>{l=e},onStatusChange:e=>{u=e}}}function r(t,{renderLucideIcon:n,attachTooltip:r}){let i=t,a=e(`section`,{className:`persona-dictation`,attrs:{"data-persona-dictation":``,"aria-label":`Voice dictation`},style:{display:`flex`,flexWrap:`wrap`,alignItems:`center`,gap:`12px`,width:`100%`,minWidth:`0`,gridColumn:`1 / -1`,color:`var(--persona-text, #18181b)`,fontFamily:`inherit`,fontSize:`var(--persona-composer-font-size, 16px)`,lineHeight:`1.5`}}),o=e(`div`,{attrs:{"data-persona-dictation-transcript":``,dir:`auto`},style:{flex:`1 1 auto`,width:`max-content`,maxWidth:`100%`,boxSizing:`border-box`,whiteSpace:`pre-wrap`,overflowWrap:`anywhere`,maxHeight:`120px`,overflowY:`auto`,padding:`2px 4px`}}),s=e(`span`),c=e(`span`,{attrs:{"data-persona-dictation-interim":``}});o.append(s,c);let l=e(`div`,{style:{display:`flex`,flex:`0 1 auto`,alignItems:`center`,gap:`10px`,width:`100%`,maxWidth:`100%`,minWidth:`0`,marginInlineStart:`auto`}}),u=e(`div`,{attrs:{role:`status`,"aria-live":`polite`,"aria-atomic":`true`},style:{flex:`1 1 0`,minWidth:`0`,color:`var(--persona-input-placeholder, var(--persona-text-muted, #71717a))`}}),d=e(`div`,{attrs:{"data-persona-dictation-waveform":``,"aria-hidden":`true`},style:{alignItems:`center`,justifyContent:`center`,gap:`4px`,height:`36px`,minWidth:`0`,color:`var(--persona-input-placeholder, var(--persona-text-muted, #71717a))`}}),f=Array.from({length:19},()=>e(`span`,{style:{width:`3px`,flexShrink:`0`,borderRadius:`3px`,background:`currentColor`}}));d.append(...f);let p=[],m=(t,a,o)=>{let s=e(`button`,{className:`persona-composer-control`,attrs:{type:`button`,"aria-label":a,"data-persona-dictation-action":t},style:{flexShrink:`0`,borderRadius:`50%`,alignItems:`center`,justifyContent:`center`,border:`1px solid var(--persona-border, #d4d4d8)`,color:`inherit`,background:`transparent`,cursor:`pointer`,padding:`0`}}),c=n(o,18,`currentColor`,2);return c?s.append(c):s.textContent=a,s.addEventListener(`click`,()=>i.actions[t]?.()),p.push(r({anchor:s,text:()=>s.getAttribute(`aria-label`)??a})),s},h=m(`cancel`,`Cancel dictation`,`x`),g=m(`finish`,`Finish dictation`,`check`),_=m(`send`,`Finish and send`,`arrow-up`);l.append(u,d,h,g,_),a.append(o,l);let v=(e,t,n=`block`)=>{e.hidden=!t,e.style.display=t?n:`none`},y=e=>{let t=i.state;i=e;let{state:n}=e,r=e.config.voiceRecognition?.dictation??{},p=r.display===`waveform`,m=!!(n.transcript||n.interimTranscript);v(a,n.phase!==`idle`&&n.phase!==`review`,`flex`),a.dataset.phase=n.phase,a.dataset.display=r.display??`transcript`,n.phase===t.phase&&n.error===t.error&&u.textContent||(u.textContent=n.phase===`recording`?`Listening…`:n.phase===`processing`?`Transcribing…`:n.error??``),s.textContent=n.transcript,c.textContent=n.interimTranscript,c.style.fontStyle=r.interimText?.fontStyle??`italic`,c.style.color=r.interimText?.color??`var(--persona-input-placeholder, var(--persona-text-muted, #71717a))`,u.style.fontStyle=n.phase===`recording`&&!p?r.interimText?.fontStyle??`italic`:`normal`,v(o,m&&r.display!==`inline`&&!p&&n.phase!==`error`),l.style.width=o.hidden?`100%`:`auto`;let y=(r.waveform??p)&&n.audioLevel!==null&&n.phase===`recording`;v(d,y,`flex`);let b=n.phase===`recording`&&(p?y:m);u.className=b?`persona-sr-only`:``,u.style.flex=b?`0 0 auto`:`1 1 0`,d.style.flex=p?`1 1 0`:`0 1 140px`,d.style.width=p?``:`140px`,d.style.marginInlineStart=`auto`,h.style.order=p?`-1`:`0`;let x=a.ownerDocument.defaultView?.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches;f.forEach((e,t)=>{let r=x?6:3+(n.audioLevel??0)*Math.max(2,31-Math.abs(9-t)*3);e.style.height=`${r}px`,e.style.transition=x?`none`:`height 80ms linear`}),v(h,r.showCancel!==!1,`inline-flex`),v(g,r.showFinish!==!1&&n.phase!==`error`,`inline-flex`),g.disabled=n.phase!==`recording`,g.style.opacity=g.disabled?`0.45`:`1`,v(_,!!e.actions.send&&n.phase!==`error`,`inline-flex`),_.disabled=n.phase!==`recording`,_.style.opacity=_.disabled?`0.45`:`1`};return y(t),{element:a,update:y,destroy:()=>{p.forEach(e=>e.destroy()),a.remove()}}}function i(e){let n=null,i=``,a=null,o=!1,s=null,c=`idle`,l=/* @__PURE__ */ new Map,u=()=>{for(let[e,t]of l)e.style.display=t;l.clear()},d=(t=``)=>{let n=(i&&t&&!/\s$/.test(i)?` `:``)+t,r=e.getInlineInput();r?.replaceLogicalRange&&a!==null?(r.replaceLogicalRange(a,r.getLogicalText().length,n),r.dispatchInput()):e.getTextarea().value=i+n,e.syncText()},f=new t({onReview:d,onSend:()=>{e.isSendBlocked()||e.onSend()},onState:(t,i)=>{let a=e.getConfig(),p=e.getTextarea(),m=e.getFooter(),h=c;c=t.phase;let g=t.phase===`recording`||t.phase===`processing`;if(p.readOnly=g||o,p instanceof HTMLTextAreaElement||p.setAttribute(`contenteditable`,g||e.isInputDisabled()?`false`:s??`true`),t.phase===`idle`&&[`recording`,`processing`,`error`].includes(h))d();else if(g&&a.voiceRecognition?.dictation?.display===`inline`){let e=t.transcript||t.interimTranscript;d(e)}t.phase===`error`&&d();let _={instanceId:e.instanceId,state:t,config:a,actions:{cancel:()=>{f.cancel()},finish:()=>{f.finish()},...a.voiceRecognition?.dictation?.showSend&&!e.isSendBlocked()?{send:()=>{e.isSendBlocked()||f.finish(!0)||f.send()}}:{}},defaultRenderer:()=>r(_,e.rendererDeps)},v=[`recording`,`processing`,`error`].includes(t.phase);if(!n&&v){for(let t of e.plugins){let e=t.renderDictation?.(_);if(e){n=e instanceof HTMLElement?{element:e}:e;break}}n??=_.defaultRenderer(),n.element.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),f.cancel())})}if(n&&v){let e=m.querySelector(`[data-persona-composer-form]`)??m;n.element.parentElement!==e&&e.append(n.element),u();let r=a.voiceRecognition?.dictation?.display===`inline`?Array.from(e.querySelectorAll(`[data-persona-composer-actions-start], [data-persona-composer-actions-end]`)):Array.from(e.children).filter(e=>e instanceof HTMLElement&&e!==n?.element);for(let e of r)l.set(e,e.style.display),e.style.display=`none`;n.update?.(_),(t.phase===`recording`&&h!==`recording`&&h!==`processing`||t.phase===`error`&&h!==`error`)&&n.element.querySelector(`button:not(:disabled), [tabindex]`)?.focus()}else u(),n?.destroy?.(),n?.element.remove(),n=null,(t.phase===`review`||t.phase===`idle`)&&t.phase!==h&&p.focus();i||e.onState(t,g)}});return{start(e,t,n){return i=n.text,a=n.logicalEnd,o=n.readOnly,s=n.contentEditable,f.start(e,t)},getState:()=>f.getState(),refresh:()=>f.refresh(),cancel:()=>f.cancel(),finish:(e=!1)=>f.finish(e),send:()=>f.send(),destroy(){f.destroy(),u(),n?.destroy?.(),n?.element.remove()}}}function a(e){let t=`--persona-voice-level`,n=.5,r=null,i=-1,a=0,o=n=>{let r=Math.round(Math.max(0,Math.min(1,n))*100)/100;if(r!==i){i=r;for(let n of e.targets())n.style.setProperty(t,String(r))}},s=()=>{i=-1,a=0;for(let n of e.targets())n.style.removeProperty(t)};function c(){if(r!==null)return;if(typeof requestAnimationFrame!=`function`){o(e.sample().level??n);return}let t=()=>{r=requestAnimationFrame(t);let{level:i,fallback:c}=e.sample();i===null&&!c?s():i===null?o(n):(a+=(i-a)*.3,o(a))};r=requestAnimationFrame(t)}function l(){r!==null&&(cancelAnimationFrame(r),r=null),s()}return{start:c,stop:l}}function o(e){let t=null;return{result:n=>{if(!e.isActive())return;let r=``,i=``;for(let e=0;e<n.results.length;e++){let t=n.results[e],a=t[0].transcript;t.isFinal?r+=a+` `:i=a}let a=e.initialText+r+i;e.textarea.value=a,e.syncText(),t&&clearTimeout(t),(r||i)&&(t=window.setTimeout(()=>{if(e.textarea.value.trim()&&e.isActive()){if(e.stop(),e.review())return;e.submit()}},e.pauseDuration))},error:t=>{e.isActive()&&t.error!==`no-speech`&&e.stop()},end:()=>{if(e.isActive()&&e.isActive()){let t=e.textarea.value.trim();!e.review()&&t&&t!==e.initialText.trim()&&e.submit(),e.stop()}},dispose:()=>{t!==null&&clearTimeout(t),t=null}}}export{t as DictationController,o as createBrowserRecognitionHandlers,r as createDictationRenderer,i as createDictationSession,a as createVoiceLevelIndicator};
@@ -1,4 +1,4 @@
1
- import{n as e}from"./chunk-py2YB6PV.js";function t(e){return e.kind===`text`?e.value.length:1}function n(e){let t=[],n=e=>{let n=t[t.length-1];n&&n.kind===`text`?n.value+=e:t.push({kind:`text`,value:e})};(e.length===0||e[0].kind!==`text`)&&t.push({kind:`text`,value:``});for(let r of e){if(r.kind===`text`){n(r.value);continue}let e=t[t.length-1];(!e||e.kind!==`text`)&&t.push({kind:`text`,value:``}),t.push({kind:`mention`,id:r.id,ref:r.ref}),t.push({kind:`text`,value:``})}let r=t[t.length-1];return(!r||r.kind!==`text`)&&t.push({kind:`text`,value:``}),t}function r(){return{blocks:[{kind:`text`,value:``}]}}function i(e){return{blocks:[{kind:`text`,value:e}]}}function a(e){return e.blocks.map(e=>e.kind===`text`?e.value:`@${e.ref.label}`).join(``)}function o(e){return e.blocks.map(e=>e.kind===`text`?e.value:``).join(``)}function s(e){return e.blocks.reduce((e,n)=>e+t(n),0)}function c(e){let t=[];for(let n of e.blocks)n.kind===`mention`&&t.push({id:n.id,ref:n.ref});return t}function l(e,n){let r=[],i=[],a=0;for(let o of e){let e=t(o),s=a+e;if(s<=n)r.push(o);else if(a>=n)i.push(o);else if(o.kind===`text`){let t=n-a;t>0&&r.push({kind:`text`,value:o.value.slice(0,t)}),t<e&&i.push({kind:`text`,value:o.value.slice(t)})}else i.push(o);a=s}return{left:r,right:i}}function u(e,t,r,i){let a=l(e.blocks,t.start).left,o=l(e.blocks,t.end).right,s=o[0],c=s?.kind===`text`?s.value.charAt(0):``,u=c!==` `&&c!==` `&&c!==`
1
+ import{n as e}from"./chunk-py2YB6PV.js";function t(e){return e.kind===`text`?e.value.length:1}function n(e){let t=[],n=e=>{let n=t[t.length-1];n&&n.kind===`text`?n.value+=e:t.push({kind:`text`,value:e})};(e.length===0||e[0].kind!==`text`)&&t.push({kind:`text`,value:``});for(let r of e){if(r.kind===`text`){n(r.value);continue}let e=t[t.length-1];e&&e.kind===`text`||t.push({kind:`text`,value:``}),t.push({kind:`mention`,id:r.id,ref:r.ref}),t.push({kind:`text`,value:``})}let r=t[t.length-1];return r&&r.kind===`text`||t.push({kind:`text`,value:``}),t}function r(){return{blocks:[{kind:`text`,value:``}]}}function i(e){return{blocks:[{kind:`text`,value:e}]}}function a(e){return e.blocks.map(e=>e.kind===`text`?e.value:`@${e.ref.label}`).join(``)}function o(e){return e.blocks.map(e=>e.kind===`text`?e.value:``).join(``)}function s(e){return e.blocks.reduce((e,n)=>e+t(n),0)}function c(e){let t=[];for(let n of e.blocks)n.kind===`mention`&&t.push({id:n.id,ref:n.ref});return t}function l(e,n){let r=[],i=[],a=0;for(let o of e){let e=t(o),s=a+e;if(s<=n)r.push(o);else if(a>=n)i.push(o);else if(o.kind===`text`){let t=n-a;t>0&&r.push({kind:`text`,value:o.value.slice(0,t)}),t<e&&i.push({kind:`text`,value:o.value.slice(t)})}else i.push(o);a=s}return{left:r,right:i}}function u(e,t,r,i){let a=l(e.blocks,t.start).left,o=l(e.blocks,t.end).right,s=o[0],c=s?.kind===`text`?s.value.charAt(0):``,u=c!==` `&&c!==` `&&c!==`
2
2
  `,d=n([...a,{kind:`mention`,id:i,ref:r},...u?[{kind:`text`,value:` `}]:[],...o]),f=t.start+1+(c===`
3
3
  `?0:1);return{doc:{blocks:d},caret:f}}function d(e,r){let i=0,a=0,o=!1;for(let n of e.blocks)n.kind===`mention`&&n.id===r&&(i=a,o=!0),a+=t(n);return o?{doc:{blocks:n(e.blocks.filter(e=>e.kind!==`mention`||e.id!==r))},caret:i}:{doc:e,caret:a}}function f(e,t,r,i){let a=s(e),o=Math.max(0,Math.min(t,r,a)),c=Math.min(a,Math.max(t,r,0)),u=l(e.blocks,o).left,d=l(e.blocks,c).right;return{doc:{blocks:n([...u,{kind:`text`,value:i},...d])},caret:o+i.length}}function p(e){let t=[];for(let n of e.blocks)n.kind===`text`?n.value.length>0&&t.push({kind:`text`,text:n.value}):t.push({kind:`mention`,ref:n.ref});return{content:a(e),contextMentions:c(e).map(e=>e.ref),contentSegments:t}}const m=`data-mention-id`,h=`data-mention-prev-label`,g=`data-mention-prev-title`;function _(e){return e.nodeType===1&&e.hasAttribute(m)}function v(e){return e.nodeType===1&&e.tagName===`BR`}function y(e){return e.nodeType===3?e.data.length:_(e)||v(e)?1:e.textContent?.length??0}function b(e,t,n){let r=0;for(let i of Array.from(e.childNodes)){if(i===t)return i.nodeType===3?r+n:r+(n>0?y(i):0);if(i.contains(t))return _(i)?r+1:r+x(i,t,n);r+=y(i)}if(t===e){let t=0,r=Array.from(e.childNodes);for(let e=0;e<Math.min(n,r.length);e++)t+=y(r[e]);return t}return r}function x(e,t,n){let r=0,i=e=>{if(e===t)return r+=e.nodeType===3?n:0,!0;if(e.nodeType===3)return r+=e.data.length,!1;for(let t of Array.from(e.childNodes))if(i(t))return!0;return!1};return i(e),r}function S(e,t){let n=0,r=Array.from(e.childNodes);for(let i=0;i<r.length;i++){let a=r[i],o=y(a);if(t<=n+o)return a.nodeType===3?{node:a,offset:t-n}:{node:e,offset:t<=n?i:i+1};n+=o}return{node:e,offset:r.length}}function C(e,t){let n=[];for(let r of Array.from(e.childNodes))if(_(r)){let e=r.getAttribute(m),i=t.get(e);i&&n.push({kind:`mention`,id:e,ref:i})}else if(v(r))n.push({kind:`text`,value:`
4
4
  `});else if(r.nodeType===3)n.push({kind:`text`,value:r.data});else{let e=r.textContent??``;e&&n.push({kind:`text`,value:e})}return n.length===0&&n.push({kind:`text`,value:``}),{blocks:n}}function w(t){let n=t.renderToken,c=/* @__PURE__ */ new Map,l=t.element??document.createElement(`div`);l.setAttribute(`contenteditable`,`true`),l.setAttribute(`data-persona-composer-input`,``),l.setAttribute(`role`,`textbox`),l.setAttribute(`aria-multiline`,`true`),l.setAttribute(`dir`,`auto`),l.classList.add(`persona-composer-contenteditable`),t.placeholder!=null&&l.setAttribute(`data-placeholder`,t.placeholder);let p=!1,v=0,y=()=>C(l,c),x=e=>{l.replaceChildren();for(let t of e.blocks)if(t.kind===`text`)t.value.length>0&&l.appendChild(document.createTextNode(t.value));else{c.set(t.id,t.ref);let e=n(t.ref);e.setAttribute(`contenteditable`,`false`),e.setAttribute(m,t.id),l.appendChild(e)}},w=()=>{let e=l.getRootNode().activeElement;return e===l||e!=null&&l.contains(e)},T=(e,t)=>{if(v=e,!t?.focus&&!w())return;let n=typeof window<`u`?window.getSelection():null;if(!n)return;let r=S(l,e);try{let e=document.createRange();e.setStart(r.node,r.offset),e.collapse(!0),n.removeAllRanges(),n.addRange(e)}catch{}},E=()=>{l.dispatchEvent(new Event(`input`,{bubbles:!0}))},D=()=>{let e={start:v,end:v},t=typeof window<`u`?window.getSelection():null;if(!t||t.rangeCount===0)return e;let n=t.getRangeAt(0);if(!l.contains(n.startContainer))return e;let r=b(l,n.startContainer,n.startOffset),i=n.collapsed?r:b(l,n.endContainer,n.endOffset);return{start:Math.min(r,i),end:Math.max(r,i)}},O=()=>{let e=/* @__PURE__ */ new Set;for(let t of Array.from(l.childNodes))_(t)&&e.add(t.getAttribute(m));for(let n of Array.from(c.keys()))e.has(n)||(c.delete(n),t.onMentionRemoved?.(n))},k=()=>{p||c.size!==0&&O()},A=()=>{p=!0},j=()=>{p=!1,O()},M=e=>{e.preventDefault();let t=e.clipboardData?.getData(`text/plain`)??``;if(typeof document.execCommand==`function`)document.execCommand(`insertText`,!1,t);else{let{start:e,end:n}=D(),r=f(y(),e,n,t);x(r.doc),T(r.caret,{focus:!0}),O()}E()},N=e=>{if(p)return;let t=e.inputType;if(t===`insertParagraph`){e.preventDefault();let{start:t,end:n}=D(),r=f(y(),t,n,`
@@ -1,3 +1,3 @@
1
- import{I as e,T as t,n,t as r,w as i}from"./chunk-d54BJdKd.js";import{r as a}from"./chunk-D5BxWOFB.js";import{a as o,c as s,d as c,f as l,i as u,l as d,n as f,o as p,p as m}from"./chunk-Dj2a9f9w.js";import{n as h,t as g}from"./chunk-Di5V0tA0.js";import{t as _}from"./chunk-D3NN94Ru.js";const v=e=>{let{mount:t,overlay:n,sessionRef:r}=e,i=(i,a,o)=>{let s=a.trim();if(!s||!r.current)return;let c=i.getAttribute(`data-tool-call-id`)??``,u=o.source===`free-text`;t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:answered`,{detail:{instanceId:e.instanceId,toolUseId:c,answer:s,answers:o.structured,values:o.values??(o.source===`multi`?s.split(`, `):[s]),isFreeText:u,source:o.source},bubbles:!0,composed:!0})),l(n,c);let d=r.current.getMessages().find(e=>e.toolCall?.id===c);d?.agentMetadata?.awaitingLocalTool?r.current.resolveAskUserQuestion(d,o.structured??s):r.current.sendMessage(s)},a=e=>{let t=r.current;if(!t)return;let n=e.getAttribute(`data-tool-call-id`)??``,i=t.getMessages().find(e=>e.toolCall?.id===n);i&&t.persistAskUserQuestionProgress(i,{answers:f(e,i),currentIndex:u(e)})},h=e=>Object.entries(e).map(([e,t])=>`${e}: ${Array.isArray(t)?t.join(`, `):t}`).join(` | `),g=t=>{if(e.config().features?.askUserQuestion?.groupedAutoAdvance===!1)return;let n=u(t);if(n>=o(t)-1)return;let i=r.current?.getMessages().find(e=>e.toolCall?.id===t.getAttribute(`data-tool-call-id`));i&&(d(t,i,e.config(),n+1),a(t))};return{click:_=>{let v=_.target.closest(`[data-ask-user-action]`);if(!v)return;let y=v.closest(`[data-persona-ask-sheet-for]`);if(!y)return;let b=v.getAttribute(`data-ask-user-action`);if(_.preventDefault(),_.stopPropagation(),b===`dismiss`){let i=y.getAttribute(`data-tool-call-id`)??``;t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:dismissed`,{detail:{instanceId:e.instanceId,toolUseId:i},bubbles:!0,composed:!0})),l(n,i);let a=r.current?.getMessages().find(e=>e.toolCall?.id===i);a?.agentMetadata?.awaitingLocalTool&&(r.current?.markAskUserQuestionResolved(a),r.current?.resolveAskUserQuestion(a,`(dismissed)`))}else if(b===`pick`){let e=v.getAttribute(`data-option-label`);if(!e)return;let t=y.getAttribute(`data-multi-select`)===`true`,n=s(y);if(n&&t){let t=c(y)[u(y)],n=new Set(Array.isArray(t)?t:[]);n.has(e)?n.delete(e):n.add(e),m(y,Array.from(n)),a(y);return}if(n){m(y,e),a(y),g(y);return}if(t){let e=v.getAttribute(`aria-pressed`)===`true`;v.setAttribute(`aria-pressed`,e?`false`:`true`),v.classList.toggle(`persona-ask-pill-selected`,!e);let t=y.querySelector(`[data-ask-user-action="submit-multi"]`);t&&(t.disabled=p(y).length===0);return}i(y,e,{source:`pick`,values:[e]})}else if(b===`submit-multi`){let e=p(y);if(e.length===0)return;i(y,e.join(`, `),{source:`multi`,values:e})}else if(b===`open-free-text`){let e=y.querySelector(`[data-ask-free-text-row="true"]`);e&&(e.classList.remove(`persona-hidden`),e.querySelector(`[data-ask-free-text-input="true"]`)?.focus())}else if(b===`focus-free-text`)y.querySelector(`[data-ask-free-text-input="true"]`)?.focus();else if(b===`submit-free-text`){let e=y.querySelector(`[data-ask-free-text-input="true"]`)?.value??``;if(!e.trim())return;if(s(y)){m(y,e.trim()),a(y),g(y);return}i(y,e,{source:`free-text`})}else if(b===`next`||b===`back`){if(!r.current)return;let t=y.getAttribute(`data-tool-call-id`)??``,n=r.current.getMessages().find(e=>e.toolCall?.id===t);if(!n)return;let i=y.querySelector(`[data-ask-free-text-input="true"]`)?.value?.trim()??``;if(i){let e=c(y)[u(y)];(typeof e!=`string`||e!==i)&&m(y,i)}let o=b===`next`?1:-1,s=u(y)+o;d(y,n,e.config(),s),a(y)}else if(b===`submit-all`){if(!r.current)return;let e=y.getAttribute(`data-tool-call-id`)??``,t=r.current.getMessages().find(t=>t.toolCall?.id===e);if(!t)return;let n=y.querySelector(`[data-ask-free-text-input="true"]`)?.value?.trim()??``;n&&m(y,n);let a=f(y,t);r.current.persistAskUserQuestionProgress(t,{answers:a,currentIndex:u(y)});let o=h(a);i(y,o||`(submitted)`,{source:`submit-all`,structured:a})}else if(b===`skip`){if(!r.current)return;let c=y.getAttribute(`data-tool-call-id`)??``,p=r.current.getMessages().find(e=>e.toolCall?.id===c);if(!p)return;let g=s(y),_=u(y),v=_>=o(y)-1;if(!g){t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:dismissed`,{detail:{instanceId:e.instanceId,toolUseId:c},bubbles:!0,composed:!0})),l(n,c),p.agentMetadata?.awaitingLocalTool&&(r.current.markAskUserQuestionResolved(p),r.current.resolveAskUserQuestion(p,`(dismissed)`));return}m(y,``);let b=y.querySelector(`[data-ask-free-text-input="true"]`);if(b&&(b.value=``),v){let e=f(y,p),t=h(e);i(y,t||`(skipped)`,{source:`submit-all`,structured:e});return}d(y,p,e.config(),_+1),a(y)}},keydown:e=>{if(e.key!==`Enter`)return;let t=e.target;if(!t.matches?.(`[data-ask-free-text-input="true"]`))return;let n=t.closest(`[data-persona-ask-sheet-for]`);if(!n)return;e.preventDefault();let r=t.value;r.trim()&&(s(n)?(m(n,r.trim()),a(n),g(n)):i(n,r,{source:`free-text`}))}}},y={loadContextMentions:()=>t(),loadContextMentionsInline:()=>i(),renderLucideIcon:(...t)=>e(...t),createMentionButton:(...e)=>n(...e)};function b(e){let{loadContextMentions:t,loadContextMentionsInline:n,renderLucideIcon:i,createMentionButton:o}=e.deps??y,s=e.config.contextMentions;if(!s?.enabled)return null;let c=_(s).filter(e=>e.sources.length>0);if(c.length===0)return typeof console<`u`&&console.warn(`[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled.`),null;let l=c.filter(e=>e.sources.some(e=>typeof e.matchCommand==`function`)),u=e=>l.some(t=>t.trigger?t.position===`line-start`?e.split(`
1
+ import{I as e,T as t,n,t as r,w as i}from"./chunk-DsWv3EGF.js";import{r as a}from"./chunk-D5BxWOFB.js";import{a as o,c as s,d as c,f as l,i as u,l as d,n as f,o as p,p as m}from"./chunk-Dj2a9f9w.js";import{n as h,t as g}from"./chunk-Di5V0tA0.js";import{t as _}from"./chunk-D3NN94Ru.js";const v=e=>{let{mount:t,overlay:n,sessionRef:r}=e,i=(i,a,o)=>{let s=a.trim();if(!s||!r.current)return;let c=i.getAttribute(`data-tool-call-id`)??``,u=o.source===`free-text`;t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:answered`,{detail:{instanceId:e.instanceId,toolUseId:c,answer:s,answers:o.structured,values:o.values??(o.source===`multi`?s.split(`, `):[s]),isFreeText:u,source:o.source},bubbles:!0,composed:!0})),l(n,c);let d=r.current.getMessages().find(e=>e.toolCall?.id===c);d?.agentMetadata?.awaitingLocalTool?r.current.resolveAskUserQuestion(d,o.structured??s):r.current.sendMessage(s)},a=e=>{let t=r.current;if(!t)return;let n=e.getAttribute(`data-tool-call-id`)??``,i=t.getMessages().find(e=>e.toolCall?.id===n);i&&t.persistAskUserQuestionProgress(i,{answers:f(e,i),currentIndex:u(e)})},h=e=>Object.entries(e).map(([e,t])=>`${e}: ${Array.isArray(t)?t.join(`, `):t}`).join(` | `),g=t=>{if(e.config().features?.askUserQuestion?.groupedAutoAdvance===!1)return;let n=u(t);if(n>=o(t)-1)return;let i=r.current?.getMessages().find(e=>e.toolCall?.id===t.getAttribute(`data-tool-call-id`));i&&(d(t,i,e.config(),n+1),a(t))};return{click:_=>{let v=_.target.closest(`[data-ask-user-action]`);if(!v)return;let y=v.closest(`[data-persona-ask-sheet-for]`);if(!y)return;let b=v.getAttribute(`data-ask-user-action`);if(_.preventDefault(),_.stopPropagation(),b===`dismiss`){let i=y.getAttribute(`data-tool-call-id`)??``;t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:dismissed`,{detail:{instanceId:e.instanceId,toolUseId:i},bubbles:!0,composed:!0})),l(n,i);let a=r.current?.getMessages().find(e=>e.toolCall?.id===i);a?.agentMetadata?.awaitingLocalTool&&(r.current?.markAskUserQuestionResolved(a),r.current?.resolveAskUserQuestion(a,`(dismissed)`))}else if(b===`pick`){let e=v.getAttribute(`data-option-label`);if(!e)return;let t=y.getAttribute(`data-multi-select`)===`true`,n=s(y);if(n&&t){let t=c(y)[u(y)],n=new Set(Array.isArray(t)?t:[]);n.has(e)?n.delete(e):n.add(e),m(y,Array.from(n)),a(y);return}if(n){m(y,e),a(y),g(y);return}if(t){let e=v.getAttribute(`aria-pressed`)===`true`;v.setAttribute(`aria-pressed`,e?`false`:`true`),v.classList.toggle(`persona-ask-pill-selected`,!e);let t=y.querySelector(`[data-ask-user-action="submit-multi"]`);t&&(t.disabled=p(y).length===0);return}i(y,e,{source:`pick`,values:[e]})}else if(b===`submit-multi`){let e=p(y);if(e.length===0)return;i(y,e.join(`, `),{source:`multi`,values:e})}else if(b===`open-free-text`){let e=y.querySelector(`[data-ask-free-text-row="true"]`);e&&(e.classList.remove(`persona-hidden`),e.querySelector(`[data-ask-free-text-input="true"]`)?.focus())}else if(b===`focus-free-text`)y.querySelector(`[data-ask-free-text-input="true"]`)?.focus();else if(b===`submit-free-text`){let e=y.querySelector(`[data-ask-free-text-input="true"]`)?.value??``;if(!e.trim())return;if(s(y)){m(y,e.trim()),a(y),g(y);return}i(y,e,{source:`free-text`})}else if(b===`next`||b===`back`){if(!r.current)return;let t=y.getAttribute(`data-tool-call-id`)??``,n=r.current.getMessages().find(e=>e.toolCall?.id===t);if(!n)return;let i=y.querySelector(`[data-ask-free-text-input="true"]`)?.value?.trim()??``;if(i){let e=c(y)[u(y)];(typeof e!=`string`||e!==i)&&m(y,i)}let o=b===`next`?1:-1,s=u(y)+o;d(y,n,e.config(),s),a(y)}else if(b===`submit-all`){if(!r.current)return;let e=y.getAttribute(`data-tool-call-id`)??``,t=r.current.getMessages().find(t=>t.toolCall?.id===e);if(!t)return;let n=y.querySelector(`[data-ask-free-text-input="true"]`)?.value?.trim()??``;n&&m(y,n);let a=f(y,t);r.current.persistAskUserQuestionProgress(t,{answers:a,currentIndex:u(y)});let o=h(a);i(y,o||`(submitted)`,{source:`submit-all`,structured:a})}else if(b===`skip`){if(!r.current)return;let c=y.getAttribute(`data-tool-call-id`)??``,p=r.current.getMessages().find(e=>e.toolCall?.id===c);if(!p)return;let g=s(y),_=u(y),v=_>=o(y)-1;if(!g){t.dispatchEvent(new CustomEvent(`persona:askUserQuestion:dismissed`,{detail:{instanceId:e.instanceId,toolUseId:c},bubbles:!0,composed:!0})),l(n,c),p.agentMetadata?.awaitingLocalTool&&(r.current.markAskUserQuestionResolved(p),r.current.resolveAskUserQuestion(p,`(dismissed)`));return}m(y,``);let b=y.querySelector(`[data-ask-free-text-input="true"]`);if(b&&(b.value=``),v){let e=f(y,p),t=h(e);i(y,t||`(skipped)`,{source:`submit-all`,structured:e});return}d(y,p,e.config(),_+1),a(y)}},keydown:e=>{if(e.key!==`Enter`)return;let t=e.target;if(!t.matches?.(`[data-ask-free-text-input="true"]`))return;let n=t.closest(`[data-persona-ask-sheet-for]`);if(!n)return;e.preventDefault();let r=t.value;r.trim()&&(s(n)?(m(n,r.trim()),a(n),g(n)):i(n,r,{source:`free-text`}))}}},y={loadContextMentions:()=>t(),loadContextMentionsInline:()=>i(),renderLucideIcon:(...t)=>e(...t),createMentionButton:(...e)=>n(...e)};function b(e){let{loadContextMentions:t,loadContextMentionsInline:n,renderLucideIcon:i,createMentionButton:o}=e.deps??y,s=e.config.contextMentions;if(!s?.enabled)return null;let c=_(s).filter(e=>e.sources.length>0);if(c.length===0)return typeof console<`u`&&console.warn(`[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled.`),null;let l=c.filter(e=>e.sources.some(e=>typeof e.matchCommand==`function`)),u=e=>l.some(t=>t.trigger?t.position===`line-start`?e.split(`
2
2
  `).some(e=>e.startsWith(t.trigger)):(t.position===`anywhere`?e:e.split(`
3
3
  `)[0]).startsWith(t.trigger):!1),d=(t,n)=>{if(typeof window<`u`)try{window.dispatchEvent(new CustomEvent(`persona:mention:${t}`,{detail:{...n,instanceId:e.textarea.closest(`[data-persona-instance]`)?.dataset.personaInstance}}))}catch{}},f=!e.chipRow,p=e.chipRow??a(`div`,{className:`persona-mention-context-row`,attrs:{"data-persona-mention-context-row":``}}),m=null,v=null,b=e.textarea,x=null,S=null,C=null,w=null,T=()=>{if(m)return Promise.resolve(m);if(v)return v;let n=t().then(t=>(t.setMentionIconRenderer(i),m=t.mountContextMentions({mentionConfig:s,textarea:e.textarea,composerInput:x??void 0,anchor:e.anchor,contextRow:p,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:O,emit:d}),m)).catch(e=>(typeof console<`u`&&console.warn(`[Persona] Failed to load context mentions runtime`,e),v===n&&(v=null),null));return v=n,n};s.display===`inline`&&n().then(t=>{let n=t.mountInlineComposer({textarea:e.textarea,renderToken:e=>r(e,{render:s.renderMentionToken}),onMentionRemoved:e=>m?.untrackMention(e)});x=n.input,S=n.destroy;let i=b;i.replaceWith(n.element),b=n.element,w={next:n.element,prev:i},C?.(n.element,i),m?m.rebindComposer(n.input):v&&v.then(e=>e?.rebindComposer(n.input))}).catch(e=>{typeof console<`u`&&console.warn(`[Persona] Failed to load inline mention composer`,e)});let E=[],D=/* @__PURE__ */ new Map;for(let e of c){if(!e.showButton)continue;let t=o({config:{...s,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},onOpen:()=>{T().then(t=>t?.openMenu(e.trigger))}});E.push(t),D.set(e.trigger,t.button)}let O=(e,t,n)=>{let r=D.get(t);r&&(r.setAttribute(`aria-expanded`,e?`true`:`false`),e?r.setAttribute(`aria-controls`,n):r.removeAttribute(`aria-controls`))};return{affordanceButtons:E.map(e=>e.wrapper),contextRow:p,handleInput:e=>{if(m){m.handleInput();return}if(!g(e))return;let t=b,n=t.selectionStart??0;h(t.value,n,c)&&T().then(e=>e?.handleInput())},handleKeydown:e=>{if(m?.isMenuOpen())return m.handleKeydown(e);if(e.key===`Backspace`&&m?.hasMentions()&&!w){let t=b,n=t.selectionStart===0&&t.selectionEnd===0;if((t.value.length===0||n)&&m.removeLastChip())return e.preventDefault(),!0}return!1},isMenuOpen:()=>m?.isMenuOpen()??!1,hasMentions:()=>m?.hasMentions()??!1,getMentionRefs:()=>m?.getMentionRefs()??[],captureDraft:()=>m?.captureDraft()??[],restoreDraft:e=>m?.restoreDraft(e),getInlineInput:()=>x,collectForSubmit:()=>m?.collectForSubmit()??null,takeInlineCommand:async e=>u(e)?(m??await T())?.dispatchInlineCommand(e)??null:null,clear:()=>m?.clear(),prefetch:()=>{t().catch(()=>{})},onComposerSwap:e=>{C=e,w&&e(w.next,w.prev)},destroy:()=>{m?.destroy(),S?.();for(let e of E)e.wrapper.remove();f&&p.remove()}}}export{v as createAskUserSheetHandlers,b as createContextMentionOrchestrator};