@runtypelabs/persona 4.30.0 → 4.31.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 (128) hide show
  1. package/README.md +22 -1
  2. package/dist/activity-ui.d.cts +3 -3
  3. package/dist/activity-ui.d.ts +3 -3
  4. package/dist/animations/glyph-cycle.d.cts +1 -1
  5. package/dist/animations/glyph-cycle.d.ts +1 -1
  6. package/dist/animations/wipe.d.cts +1 -1
  7. package/dist/animations/wipe.d.ts +1 -1
  8. package/dist/approval-ui.d.cts +2 -2
  9. package/dist/approval-ui.d.ts +2 -2
  10. package/dist/artifacts-ui.d.cts +3 -3
  11. package/dist/artifacts-ui.d.ts +3 -3
  12. package/dist/background-runtime.d.cts +1 -1
  13. package/dist/background-runtime.d.ts +1 -1
  14. package/dist/{chunk-gayfbmEU.js → chunk-BBtVdcKU.js} +1 -1
  15. package/dist/chunk-C2IbR39s.js +1 -0
  16. package/dist/chunk-CjhA_5Jk.js +1 -0
  17. package/dist/{chunk-n96BB0YH.js → chunk-Co4LmTFv.js} +1 -1
  18. package/dist/chunk-DABqu7C3.js +2 -0
  19. package/dist/chunk-DbD5qyBw.js +3 -0
  20. package/dist/{chunk-UyZbbbz3.js → chunk-MdlQetfC.js} +2 -2
  21. package/dist/{chunk-CqEWCkJt.js → chunk-WA9UucGf.js} +1 -1
  22. package/dist/client-dispatch.js +1 -1
  23. package/dist/client-history.js +1 -1
  24. package/dist/codegen.cjs +1 -1
  25. package/dist/codegen.js +1 -1
  26. package/dist/composer-actions-runtime.d.cts +2 -2
  27. package/dist/composer-actions-runtime.d.ts +2 -2
  28. package/dist/{composer-input-C76gfIoK.d.cts → composer-input-C2_WizXV.d.cts} +1 -1
  29. package/dist/{composer-input-C76gfIoK.d.ts → composer-input-C2_WizXV.d.ts} +1 -1
  30. package/dist/{composer-store-C7tvaz90.d.cts → composer-store-BV6kTlKv.d.cts} +1 -1
  31. package/dist/{composer-store-C7tvaz90.d.ts → composer-store-BV6kTlKv.d.ts} +1 -1
  32. package/dist/{context-mention-manager-IfT4JHma.d.cts → context-mention-manager-BfZzcydV.d.cts} +2 -2
  33. package/dist/{context-mention-manager-IfT4JHma.d.ts → context-mention-manager-BfZzcydV.d.ts} +2 -2
  34. package/dist/context-mentions-inline.d.cts +2 -2
  35. package/dist/context-mentions-inline.d.ts +2 -2
  36. package/dist/context-mentions.d.cts +3 -3
  37. package/dist/context-mentions.d.ts +3 -3
  38. package/dist/{defaults-Cc_p0PGM.d.cts → defaults-DiTeXyr3.d.cts} +1 -1
  39. package/dist/{defaults-Cc_p0PGM.d.ts → defaults-DiTeXyr3.d.ts} +1 -1
  40. package/dist/dictation-runtime.d.cts +2 -2
  41. package/dist/dictation-runtime.d.ts +2 -2
  42. package/dist/event-stream-view.d.cts +1 -1
  43. package/dist/event-stream-view.d.ts +1 -1
  44. package/dist/{fallback-speech-engine-CSxWpG0A.d.cts → fallback-speech-engine-DZ6Of7VU.d.cts} +1 -1
  45. package/dist/{fallback-speech-engine-CSxWpG0A.d.ts → fallback-speech-engine-DZ6Of7VU.d.ts} +1 -1
  46. package/dist/{feature-preferences-eeSOmDxg.d.cts → feature-preferences-BT549D_E.d.cts} +1 -1
  47. package/dist/{feature-preferences-eeSOmDxg.d.ts → feature-preferences-BT549D_E.d.ts} +1 -1
  48. package/dist/forms-ui.d.cts +2 -2
  49. package/dist/forms-ui.d.ts +2 -2
  50. package/dist/{history-confirm-dialog-DXkuAgh-.d.cts → history-confirm-dialog-Cm4oK4am.d.cts} +1 -1
  51. package/dist/{history-confirm-dialog-DXkuAgh-.d.ts → history-confirm-dialog-Cm4oK4am.d.ts} +1 -1
  52. package/dist/history-shell.d.cts +6 -6
  53. package/dist/history-shell.d.ts +6 -6
  54. package/dist/history-view.d.cts +1 -1
  55. package/dist/history-view.d.ts +1 -1
  56. package/dist/index.cjs +48 -47
  57. package/dist/index.cjs.map +1 -1
  58. package/dist/index.d.cts +9 -9
  59. package/dist/index.d.ts +9 -9
  60. package/dist/index.global.js +1 -1
  61. package/dist/index.global.js.map +1 -1
  62. package/dist/index.js +42 -41
  63. package/dist/index.js.map +1 -1
  64. package/dist/{loading-label-runtime-loader-C53YyPJ-.d.cts → loading-label-runtime-loader-DmiPDkBu.d.cts} +1 -1
  65. package/dist/{loading-label-runtime-loader-C53YyPJ-.d.ts → loading-label-runtime-loader-DmiPDkBu.d.ts} +1 -1
  66. package/dist/loading-label-runtime.d.cts +1 -1
  67. package/dist/loading-label-runtime.d.ts +1 -1
  68. package/dist/markdown-parsers.js +18 -15
  69. package/dist/{message-bubble-Cg_sTXUN.d.cts → message-bubble-D0rosKuK.d.cts} +1 -1
  70. package/dist/{message-bubble-Cg_sTXUN.d.ts → message-bubble-D0rosKuK.d.ts} +1 -1
  71. package/dist/preferences-runtime.d.cts +1 -1
  72. package/dist/preferences-runtime.d.ts +1 -1
  73. package/dist/{preview-BeMKALry.d.cts → preview-DRU27q-X.d.cts} +2 -2
  74. package/dist/{preview-BeMKALry.d.ts → preview-DRU27q-X.d.ts} +2 -2
  75. package/dist/{registry-BBe-Lesw.d.ts → registry-DRk3VMFc.d.cts} +3 -1
  76. package/dist/{registry-BBe-Lesw.d.cts → registry-DRk3VMFc.d.ts} +3 -1
  77. package/dist/{session-C0fSteA4.d.cts → session-Dj4bOm5y.d.cts} +18 -9
  78. package/dist/{session-C0fSteA4.d.ts → session-Dj4bOm5y.d.ts} +18 -9
  79. package/dist/session-reconnect.d.cts +2 -2
  80. package/dist/session-reconnect.d.ts +2 -2
  81. package/dist/smart-dom-reader.d.cts +1 -1
  82. package/dist/smart-dom-reader.d.ts +1 -1
  83. package/dist/theme-editor-preview.cjs +46 -45
  84. package/dist/theme-editor-preview.d.cts +1 -1
  85. package/dist/theme-editor-preview.d.ts +1 -1
  86. package/dist/theme-editor-preview.js +17 -19
  87. package/dist/theme-editor.d.cts +2 -2
  88. package/dist/theme-editor.d.ts +2 -2
  89. package/dist/theme-reference.d.cts +2 -2
  90. package/dist/theme-reference.d.ts +2 -2
  91. package/dist/{tool-loading-animation-BvdaZfwh.d.cts → tool-loading-animation-D1MS5Ace.d.cts} +1 -1
  92. package/dist/{tool-loading-animation-BvdaZfwh.d.ts → tool-loading-animation-D1MS5Ace.d.ts} +1 -1
  93. package/dist/{turn-activity-ui-BYBlInZQ.d.cts → turn-activity-ui-CorwdlI0.d.cts} +2 -2
  94. package/dist/{turn-activity-ui-BYBlInZQ.d.ts → turn-activity-ui-CorwdlI0.d.ts} +2 -2
  95. package/dist/turn-activity-ui.d.cts +1 -1
  96. package/dist/turn-activity-ui.d.ts +1 -1
  97. package/dist/{types-CiXi4ICM.d.cts → types-CSXHl5cN.d.cts} +5 -0
  98. package/dist/{types-CiXi4ICM.d.ts → types-CSXHl5cN.d.ts} +5 -0
  99. package/dist/voice-client-tools.d.cts +1 -1
  100. package/dist/voice-client-tools.d.ts +1 -1
  101. package/dist/voice-runtime.cjs +1 -1
  102. package/dist/voice-runtime.d.cts +2 -2
  103. package/dist/voice-runtime.d.ts +2 -2
  104. package/dist/voice-runtime.js +1 -1
  105. package/dist/voice-worklet-player.d.cts +2 -2
  106. package/dist/voice-worklet-player.d.ts +2 -2
  107. package/dist/{webmcp-runtime-entry-BTbOg3Au.d.cts → webmcp-runtime-entry-DpDN6k-6.d.cts} +1 -1
  108. package/dist/{webmcp-runtime-entry-BTbOg3Au.d.ts → webmcp-runtime-entry-DpDN6k-6.d.ts} +1 -1
  109. package/dist/webmcp-runtime.d.cts +1 -1
  110. package/dist/webmcp-runtime.d.ts +1 -1
  111. package/package.json +2 -2
  112. package/src/index-core.ts +1 -0
  113. package/src/markdown-parsers-eager.ts +2 -1
  114. package/src/markdown-parsers-entry.ts +1 -0
  115. package/src/markdown-parsers-loader.ts +2 -0
  116. package/src/postprocessors.ts +14 -0
  117. package/src/session.ts +3 -0
  118. package/src/types.ts +5 -0
  119. package/src/ui.background-conversations.test.ts +6 -0
  120. package/src/ui.page-cache.test.ts +268 -0
  121. package/src/ui.postprocess.test.ts +80 -1
  122. package/src/ui.ts +95 -27
  123. package/src/utils/actions.ts +3 -0
  124. package/src/utils/streaming-markdown.test.ts +103 -0
  125. package/src/utils/streaming-markdown.ts +186 -0
  126. package/dist/chunk-18tPmsiJ.js +0 -1
  127. package/dist/chunk-Dp2vWE9V.js +0 -1
  128. package/dist/chunk-VloQ2dnh.js +0 -1
package/README.md CHANGED
@@ -28,6 +28,7 @@ import {
28
28
  initAgentWidget,
29
29
  createAgentExperience,
30
30
  markdownPostprocessor,
31
+ preprocessStreamingMarkdown,
31
32
  DEFAULT_WIDGET_CONFIG
32
33
  } from '@runtypelabs/persona';
33
34
 
@@ -43,7 +44,8 @@ createAgentExperience(inlineHost, {
43
44
  semantic: { colors: { accent: '#2563eb' } }
44
45
  },
45
46
  suggestions: { starters: { items: ['What can you do?', 'Show API docs'] } },
46
- postprocessMessage: ({ text }) => markdownPostprocessor(text)
47
+ postprocessMessage: ({ text, streaming }) =>
48
+ markdownPostprocessor(preprocessStreamingMarkdown(text, streaming))
47
49
  });
48
50
 
49
51
  // Floating launcher with runtime updates
@@ -274,3 +276,22 @@ for an actionable error message: v6 replaces thrown callback errors with a
274
276
  generic error and rejects `undefined` and other non-serializable results. v5's
275
277
  existing result conversion remains unchanged. Registration cleanup uses an
276
278
  AbortSignal in both versions.
279
+
280
+ ### Custom Markdown rendering during streaming
281
+
282
+ `postprocessMessage` receives the original display text, including incomplete Markdown.
283
+ After applying your own text transforms, call `preprocessStreamingMarkdown(text, streaming)`
284
+ before your Markdown parser to use the same display repairs as the built-in renderer:
285
+
286
+ ```ts
287
+ postprocessMessage: ({ text, streaming }) => {
288
+ const transformed = text.replace(/<answer>|<\/answer>/g, '');
289
+ return markdownPostprocessor(preprocessStreamingMarkdown(transformed, streaming));
290
+ }
291
+ ```
292
+
293
+ The helper returns completed text unchanged and does not change stored message content
294
+ or the callback's `raw` payload. It does not parse HTML or sanitize output; Persona's
295
+ configured sanitizer still runs after the callback. On the CDN build it is available as
296
+ `AgentWidget.preprocessStreamingMarkdown`. It uses the existing lazy Markdown parser
297
+ chunk when ready, with lightweight table repairs available before that chunk loads.
@@ -1,6 +1,6 @@
1
- import { Ct as AgentWidgetMessage, Ta as renderLucideIcon, k as AgentWidgetConfig } from "./types-CiXi4ICM.cjs";
2
- import { a as hasExplicitThemeStyle$1, c as updateActivityElapsed, i as getExplicitLegacyStyle$1, n as TurnActivityRuntime, o as groupToolRows, s as ActivityKind } from "./turn-activity-ui-BYBlInZQ.cjs";
3
- import { t as LoadingLabelRuntime } from "./loading-label-runtime-loader-C53YyPJ-.cjs";
1
+ import { Ct as AgentWidgetMessage, Ta as renderLucideIcon, k as AgentWidgetConfig } from "./types-CSXHl5cN.cjs";
2
+ import { a as hasExplicitThemeStyle$1, c as updateActivityElapsed, i as getExplicitLegacyStyle$1, n as TurnActivityRuntime, o as groupToolRows, s as ActivityKind } from "./turn-activity-ui-CorwdlI0.cjs";
3
+ import { t as LoadingLabelRuntime } from "./loading-label-runtime-loader-DmiPDkBu.cjs";
4
4
  //#region src/components/tool-bubble.d.ts
5
5
  export declare const updateToolBubbleUI: (messageId: string, bubble: HTMLElement, expansionState: Set<string>, config?: AgentWidgetConfig) => void;
6
6
  export declare const createToolBubble: (message: AgentWidgetMessage, config?: AgentWidgetConfig, expansionState?: Set<string>) => HTMLElement;
@@ -1,6 +1,6 @@
1
- import { Ct as AgentWidgetMessage, Ta as renderLucideIcon, k as AgentWidgetConfig } from "./types-CiXi4ICM.js";
2
- import { a as hasExplicitThemeStyle$1, c as updateActivityElapsed, i as getExplicitLegacyStyle$1, n as TurnActivityRuntime, o as groupToolRows, s as ActivityKind } from "./turn-activity-ui-BYBlInZQ.js";
3
- import { t as LoadingLabelRuntime } from "./loading-label-runtime-loader-C53YyPJ-.js";
1
+ import { Ct as AgentWidgetMessage, Ta as renderLucideIcon, k as AgentWidgetConfig } from "./types-CSXHl5cN.js";
2
+ import { a as hasExplicitThemeStyle$1, c as updateActivityElapsed, i as getExplicitLegacyStyle$1, n as TurnActivityRuntime, o as groupToolRows, s as ActivityKind } from "./turn-activity-ui-CorwdlI0.js";
3
+ import { t as LoadingLabelRuntime } from "./loading-label-runtime-loader-DmiPDkBu.js";
4
4
  //#region src/components/tool-bubble.d.ts
5
5
  export declare const updateToolBubbleUI: (messageId: string, bubble: HTMLElement, expansionState: Set<string>, config?: AgentWidgetConfig) => void;
6
6
  export declare const createToolBubble: (message: AgentWidgetMessage, config?: AgentWidgetConfig, expansionState?: Set<string>) => HTMLElement;
@@ -1,4 +1,4 @@
1
- import { Ki as StreamAnimationPlugin } from "../types-CiXi4ICM.cjs";
1
+ import { Ki as StreamAnimationPlugin } from "../types-CSXHl5cN.cjs";
2
2
  //#region src/animations/glyph-cycle.d.ts
3
3
  export declare const glyphCycle: StreamAnimationPlugin;
4
4
  //#endregion
@@ -1,4 +1,4 @@
1
- import { Ki as StreamAnimationPlugin } from "../types-CiXi4ICM.js";
1
+ import { Ki as StreamAnimationPlugin } from "../types-CSXHl5cN.js";
2
2
  //#region src/animations/glyph-cycle.d.ts
3
3
  export declare const glyphCycle: StreamAnimationPlugin;
4
4
  //#endregion
@@ -1,4 +1,4 @@
1
- import { Ki as StreamAnimationPlugin } from "../types-CiXi4ICM.cjs";
1
+ import { Ki as StreamAnimationPlugin } from "../types-CSXHl5cN.cjs";
2
2
  //#region src/animations/wipe.d.ts
3
3
  export declare const wipe: StreamAnimationPlugin;
4
4
  //#endregion
@@ -1,4 +1,4 @@
1
- import { Ki as StreamAnimationPlugin } from "../types-CiXi4ICM.js";
1
+ import { Ki as StreamAnimationPlugin } from "../types-CSXHl5cN.js";
2
2
  //#region src/animations/wipe.d.ts
3
3
  export declare const wipe: StreamAnimationPlugin;
4
4
  //#endregion
@@ -1,5 +1,5 @@
1
- import { Ct as AgentWidgetMessage, Ta as renderLucideIcon, jo as AgentWidgetPlugin, k as AgentWidgetConfig } from "./types-CiXi4ICM.cjs";
2
- import { i as MessageTransform } from "./message-bubble-Cg_sTXUN.cjs";
1
+ import { Ct as AgentWidgetMessage, Ta as renderLucideIcon, jo as AgentWidgetPlugin, k as AgentWidgetConfig } from "./types-CSXHl5cN.cjs";
2
+ import { i as MessageTransform } from "./message-bubble-D0rosKuK.cjs";
3
3
  import { i as createPopover, s as isEditableEventTarget } from "./plugin-kit-C1mRjLgW.cjs";
4
4
  import { IconNode } from "lucide";
5
5
  //#region src/utils/humanize-tool-name.d.ts
@@ -1,5 +1,5 @@
1
- import { Ct as AgentWidgetMessage, Ta as renderLucideIcon, jo as AgentWidgetPlugin, k as AgentWidgetConfig } from "./types-CiXi4ICM.js";
2
- import { i as MessageTransform } from "./message-bubble-Cg_sTXUN.js";
1
+ import { Ct as AgentWidgetMessage, Ta as renderLucideIcon, jo as AgentWidgetPlugin, k as AgentWidgetConfig } from "./types-CSXHl5cN.js";
2
+ import { i as MessageTransform } from "./message-bubble-D0rosKuK.js";
3
3
  import { i as createPopover, s as isEditableEventTarget } from "./plugin-kit-C1mRjLgW.js";
4
4
  import { IconNode } from "lucide";
5
5
  //#region src/utils/humanize-tool-name.d.ts
@@ -1,6 +1,6 @@
1
- import { T as provideMarkdownParsers, f as buttons_d_exports, r as ComponentRenderer, t as ComponentContext } from "./registry-BBe-Lesw.cjs";
2
- import { Ei as PersonaArtifactFileMeta, Si as PersonaArtifactCustomAction, ji as PersonaArtifactRecord, k as AgentWidgetConfig } from "./types-CiXi4ICM.cjs";
3
- import { t as LoadingLabelRuntime } from "./loading-label-runtime-loader-C53YyPJ-.cjs";
1
+ import { T as provideMarkdownParsers, f as buttons_d_exports, r as ComponentRenderer, t as ComponentContext } from "./registry-DRk3VMFc.cjs";
2
+ import { Ei as PersonaArtifactFileMeta, Si as PersonaArtifactCustomAction, ji as PersonaArtifactRecord, k as AgentWidgetConfig } from "./types-CSXHl5cN.cjs";
3
+ import { t as LoadingLabelRuntime } from "./loading-label-runtime-loader-DmiPDkBu.cjs";
4
4
  import { IconNode } from "lucide";
5
5
  //#region src/components/artifact-pane.d.ts
6
6
  type ArtifactPaneApi = {
@@ -1,6 +1,6 @@
1
- import { T as provideMarkdownParsers, f as buttons_d_exports, r as ComponentRenderer, t as ComponentContext } from "./registry-BBe-Lesw.js";
2
- import { Ei as PersonaArtifactFileMeta, Si as PersonaArtifactCustomAction, ji as PersonaArtifactRecord, k as AgentWidgetConfig } from "./types-CiXi4ICM.js";
3
- import { t as LoadingLabelRuntime } from "./loading-label-runtime-loader-C53YyPJ-.js";
1
+ import { T as provideMarkdownParsers, f as buttons_d_exports, r as ComponentRenderer, t as ComponentContext } from "./registry-DRk3VMFc.js";
2
+ import { Ei as PersonaArtifactFileMeta, Si as PersonaArtifactCustomAction, ji as PersonaArtifactRecord, k as AgentWidgetConfig } from "./types-CSXHl5cN.js";
3
+ import { t as LoadingLabelRuntime } from "./loading-label-runtime-loader-DmiPDkBu.js";
4
4
  import { IconNode } from "lucide";
5
5
  //#region src/components/artifact-pane.d.ts
6
6
  type ArtifactPaneApi = {
@@ -1,4 +1,4 @@
1
- import { Ct as AgentWidgetMessage, Li as ResumableHandle, Rr as ConversationExecutionState, Wn as BackgroundConversationAdapter, cn as AgentWidgetStreamCheckpoint, ji as PersonaArtifactRecord } from "./types-CiXi4ICM.cjs";
1
+ import { Ct as AgentWidgetMessage, Li as ResumableHandle, Rr as ConversationExecutionState, Wn as BackgroundConversationAdapter, cn as AgentWidgetStreamCheckpoint, ji as PersonaArtifactRecord } from "./types-CSXHl5cN.cjs";
2
2
  //#region src/session-background.d.ts
3
3
  type BackgroundCheckpoint = {
4
4
  conversationId: string;
@@ -1,4 +1,4 @@
1
- import { Ct as AgentWidgetMessage, Li as ResumableHandle, Rr as ConversationExecutionState, Wn as BackgroundConversationAdapter, cn as AgentWidgetStreamCheckpoint, ji as PersonaArtifactRecord } from "./types-CiXi4ICM.js";
1
+ import { Ct as AgentWidgetMessage, Li as ResumableHandle, Rr as ConversationExecutionState, Wn as BackgroundConversationAdapter, cn as AgentWidgetStreamCheckpoint, ji as PersonaArtifactRecord } from "./types-CSXHl5cN.js";
2
2
  //#region src/session-background.d.ts
3
3
  type BackgroundCheckpoint = {
4
4
  conversationId: string;
@@ -1 +1 @@
1
- import{n as e}from"./chunk-BAdIgC5d.js";import{t}from"./chunk-18tPmsiJ.js";import{t as n}from"./chunk-Bz9jAgba.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=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),u=e=>{let t=e.agentMetadata?.providerPhase??e.agentMetadata?.phase;return e.role===`assistant`&&(t===`commentary`||t===`partial_answer`||t===`final_answer`)?{phase:t}:{}},d=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt,...u(e)});var f=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`)},l=this.host.clientSession??await this.host.initSession();r();let u=async()=>{r();let t=l,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.`);l=this.host.finishInit(i,t.conversationId??null,!1),this.host.clientSession=l,this.host.resetSessionWarmLatch(),this.host.resetClientToolsFingerprint(),this.host.config.onSessionInit?.(l)};Date.now()>=l.expiresAt.getTime()-6e4&&await u();let d=await this.#c(e.messages),f=d.metadata?Object.fromEntries(Object.entries(d.metadata).filter(([e])=>e!==`sessionId`&&e!==`session_id`)):void 0,p=this.host.isHistoryCapable(),m={sessionId:l.sessionId,messages:e.messages.filter(c).map(e=>{let t=p?n(e):void 0;return{id:e.id,role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,...t!==void 0&&{displayContent:t}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...f&&Object.keys(f).length>0&&{metadata:f},...d.inputs&&Object.keys(d.inputs).length>0&&{inputs:d.inputs},...d.context&&{context:d.context},turnId:i,...e.interrupt&&{submitMode:`interrupt`},...e.voiceSpoken&&{voice:{spoken:!0,...e.voicePriorToolResults?.length&&{priorToolResults:e.voicePriorToolResults}}}},h=async()=>{r();let n=l.durableRecovery?.enabled===!0?await this.host.readVisitorToken():null;return r(),this.host.sendWithClientToolsDiff(l.sessionId,d.clientTools,async i=>{r();let a=await this.host.resolveChatIdentityProof(e.signal);r();let o={...m,sessionId:l.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})})},g=await h();if(r(),g.response.status===401){let e=await g.response.clone().json().catch(()=>null);r(),e?.error===`Session not found or expired`&&(await u(),g=await h(),r())}let{response:_,commit:v}=g;if(!_.ok){let e=await _.json().catch(()=>({error:`Chat request failed`}));if(_.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(_.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(_.status===429){let t=Error(e.hint||`Message limit reached for this session.`);throw s({type:`error`,error:t}),t}if(_.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(!_.body){let e=/* @__PURE__ */ Error(`No response body received`);throw s({type:`error`,error:e}),e}v(),s({type:`status`,status:`connected`});try{await this.host.streamResponse(_.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.#c(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.#s(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}async#s(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(l(e),e=>c(e)&&(e.role===`user`||e.role===`assistant`||e.role===`system`)&&(!e.variant||e.variant===`assistant`)?d(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 u=await this.#i(e);return u&&(a.context=u),a}async#c(e,t){let n=s(l(e),e=>c(e)?d(e):null),r=this.host.routing(),i={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[e,t]of Object.entries(r.targetPayload))e!==`messages`&&(i[e]=t);let a=[...this.host.builtInClientTools(this.host.config),...await(await this.host.getWebMcpBridge())?.snapshotForDispatch()??[]];a.length>0&&(i.clientTools=a);let o=await this.#i(e);o&&(i.context=o);let u=this.#a(t);if(u&&(i.composerOptions=u),this.host.requestMiddleware)try{let e=await this.host.requestMiddleware({payload:{...i},config:this.host.config});if(e&&typeof e==`object`){let t=e;return i.clientTools!==void 0&&!(`clientTools`in t)&&(t.clientTools=i.clientTools),t}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Request middleware error:`,e)}return i}};export{f as ClientDispatch};
1
+ import{n as e}from"./chunk-BAdIgC5d.js";import{t}from"./chunk-CjhA_5Jk.js";import{t as n}from"./chunk-Bz9jAgba.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=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),u=e=>{let t=e.agentMetadata?.providerPhase??e.agentMetadata?.phase;return e.role===`assistant`&&(t===`commentary`||t===`partial_answer`||t===`final_answer`)?{phase:t}:{}},d=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt,...u(e)});var f=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`)},l=this.host.clientSession??await this.host.initSession();r();let u=async()=>{r();let t=l,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.`);l=this.host.finishInit(i,t.conversationId??null,!1),this.host.clientSession=l,this.host.resetSessionWarmLatch(),this.host.resetClientToolsFingerprint(),this.host.config.onSessionInit?.(l)};Date.now()>=l.expiresAt.getTime()-6e4&&await u();let d=await this.#c(e.messages),f=d.metadata?Object.fromEntries(Object.entries(d.metadata).filter(([e])=>e!==`sessionId`&&e!==`session_id`)):void 0,p=this.host.isHistoryCapable(),m={sessionId:l.sessionId,messages:e.messages.filter(c).map(e=>{let t=p?n(e):void 0;return{id:e.id,role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,...t!==void 0&&{displayContent:t}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...f&&Object.keys(f).length>0&&{metadata:f},...d.inputs&&Object.keys(d.inputs).length>0&&{inputs:d.inputs},...d.context&&{context:d.context},turnId:i,...e.interrupt&&{submitMode:`interrupt`},...e.voiceSpoken&&{voice:{spoken:!0,...e.voicePriorToolResults?.length&&{priorToolResults:e.voicePriorToolResults}}}},h=async()=>{r();let n=l.durableRecovery?.enabled===!0?await this.host.readVisitorToken():null;return r(),this.host.sendWithClientToolsDiff(l.sessionId,d.clientTools,async i=>{r();let a=await this.host.resolveChatIdentityProof(e.signal);r();let o={...m,sessionId:l.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})})},g=await h();if(r(),g.response.status===401){let e=await g.response.clone().json().catch(()=>null);r(),e?.error===`Session not found or expired`&&(await u(),g=await h(),r())}let{response:_,commit:v}=g;if(!_.ok){let e=await _.json().catch(()=>({error:`Chat request failed`}));if(_.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(_.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(_.status===429){let t=Error(e.hint||`Message limit reached for this session.`);throw s({type:`error`,error:t}),t}if(_.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(!_.body){let e=/* @__PURE__ */ Error(`No response body received`);throw s({type:`error`,error:e}),e}v(),s({type:`status`,status:`connected`});try{await this.host.streamResponse(_.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.#c(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.#s(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}async#s(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(l(e),e=>c(e)&&(e.role===`user`||e.role===`assistant`||e.role===`system`)&&(!e.variant||e.variant===`assistant`)?d(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 u=await this.#i(e);return u&&(a.context=u),a}async#c(e,t){let n=s(l(e),e=>c(e)?d(e):null),r=this.host.routing(),i={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[e,t]of Object.entries(r.targetPayload))e!==`messages`&&(i[e]=t);let a=[...this.host.builtInClientTools(this.host.config),...await(await this.host.getWebMcpBridge())?.snapshotForDispatch()??[]];a.length>0&&(i.clientTools=a);let o=await this.#i(e);o&&(i.context=o);let u=this.#a(t);if(u&&(i.composerOptions=u),this.host.requestMiddleware)try{let e=await this.host.requestMiddleware({payload:{...i},config:this.host.config});if(e&&typeof e==`object`){let t=e;return i.clientTools!==void 0&&!(`clientTools`in t)&&(t.clientTools=i.clientTools),t}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Request middleware error:`,e)}return i}};export{f as ClientDispatch};
@@ -0,0 +1 @@
1
+ import{a as e}from"./chunk-CHAwCqpk.js";import{r as t}from"./chunk-BnfM7-qg.js";import{t as n}from"./chunk-DbD5qyBw.js";const{setLoader:r,load:i,provide:a,getSync:o}=t({fallbackImport:()=>import(`./chunk-DABqu7C3.js`)}),s=/* @__PURE__ */ new Set,c=()=>{let e=[...s];s.clear();for(let t of e)try{t()}catch{}},l=()=>{let e=o();return e?Promise.resolve(e):i().then(e=>(c(),e))},u=e=>o()?()=>{}:(s.add(e),()=>{s.delete(e)}),d=e=>{a(e),c()},f=o,p=new class{#e=/* @__PURE__ */ new Map;#t=/* @__PURE__ */ new Map;register(e,t,n){this.#e.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.#e.set(e,t),n?this.#t.set(e,n):this.#t.delete(e)}unregister(e){this.#e.delete(e),this.#t.delete(e)}get(e){return this.#e.get(e)}has(e){return this.#e.has(e)}getOptions(e){return this.#t.get(e)}getAllNames(){return Array.from(this.#e.keys())}clear(){this.#e.clear(),this.#t.clear()}registerAll(e){Object.entries(e).forEach(([e,t])=>{this.register(e,t)})}};function m(e,t){return e.components&&Object.prototype.hasOwnProperty.call(e.components,t)?e.components[t]:p.get(t)}function h(e,t){return e.components&&Object.prototype.hasOwnProperty.call(e.components,t)?void 0:p.getOptions(t)}const g=(e,t)=>t?(f()?.stabilizeStreamingMarkdown??n)(e):e,_=e=>{if(!e)return;let t={},n=e;if(n.heading){let e=n.heading;t.heading=(t,n,r)=>e({type:`heading`,raw:r,depth:n,text:t,tokens:[]})}if(n.code){let e=n.code;t.code=(t,n,r)=>e({type:`code`,raw:``,text:t,lang:n,escaped:r})}if(n.blockquote){let e=n.blockquote;t.blockquote=t=>e({type:`blockquote`,raw:``,text:t,tokens:[]})}if(n.table){let e=n.table;t.table=(t,n)=>e({type:`table`,raw:``,header:[],rows:[],align:[],headerHtml:t,bodyHtml:n})}if(n.link){let e=n.link;t.link=(t,n,r)=>e({type:`link`,raw:``,href:t,title:n??null,text:r,tokens:[]})}if(n.image){let e=n.image;t.image=(t,n,r)=>e({type:`image`,raw:``,href:t,title:n??null,text:r})}if(n.list){let e=n.list;t.list=(t,n,r)=>e({type:`list`,raw:``,ordered:n,start:r,loose:!1,items:[],itemsHtml:t})}if(n.listitem){let e=n.listitem;t.listitem=(t,n,r)=>e({type:`list_item`,raw:``,task:n,checked:r,loose:!1,text:t,tokens:[]})}if(n.paragraph){let e=n.paragraph;t.paragraph=t=>e({type:`paragraph`,raw:``,text:t,tokens:[]})}if(n.codespan){let e=n.codespan;t.codespan=t=>e({type:`codespan`,raw:``,text:t})}if(n.strong){let e=n.strong;t.strong=t=>e({type:`strong`,raw:``,text:t,tokens:[]})}if(n.em){let e=n.em;t.em=t=>e({type:`em`,raw:``,text:t,tokens:[]})}if(n.del){let e=n.del;t.del=t=>e({type:`del`,raw:``,text:t,tokens:[]})}if(n.html){let e=n.html;t.html=t=>e({type:`html`,raw:t,text:t})}if(n.text){let e=n.text;t.text=t=>e({type:`text`,raw:t,text:t})}if(n.checkbox){let e=n.checkbox;t.checkbox=t=>e({checked:t})}return n.hr&&(t.hr=n.hr),n.br&&(t.br=n.br),t},v=e=>{let t=null;return n=>{let r=f();if(!r)return b(n);if(!t){let{Marked:n}=r,i=e?.markedOptions;t=new n({gfm:i?.gfm??!0,breaks:i?.breaks??!0,pedantic:i?.pedantic,silent:i?.silent});let a=_(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},y=e=>e?v({markedOptions:e.options,renderer:e.renderer}):v(),b=e=>e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`),x={ALLOWED_TAGS:/* @__PURE__ */ `h1.h2.h3.h4.h5.h6.p.br.hr.div.span.ul.ol.li.dl.dt.dd.strong.em.b.i.u.s.del.ins.mark.small.sub.sup.abbr.kbd.var.samp.code.a.img.blockquote.pre.details.summary.table.thead.tbody.tfoot.tr.th.td.caption.colgroup.col.input.label.select.option.textarea.button`.split(`.`),ALLOWED_ATTR:/* @__PURE__ */ `href.src.alt.title.target.rel.loading.width.height.colspan.rowspan.scope.class.id.type.name.value.placeholder.disabled.checked.for.aria-label.aria-hidden.aria-expanded.role.tabindex.data-tv-form.data-message-id.data-persona-component-directive.data-preserve-animation.data-persona-instance`.split(`.`)},S=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,C=()=>{let e=null;return t=>{let n=f();if(!n)return b(t);if(!e){let{DOMPurify:t}=n;e=t(typeof window<`u`?window:void 0),e.addHook(`uponSanitizeAttribute`,(e,t)=>{if(t.attrName===`src`||t.attrName===`href`){let e=t.attrValue;e.toLowerCase().startsWith(`data:`)&&!S.test(e)&&(t.attrValue=``,t.keepAttr=!1)}})}return e.sanitize(t,x)}},w=e=>e===!1?null:typeof e==`function`?e:C();function T(t,n,r){return n?.trim()||(e(t,`artifact.${r}`)?`var(--persona-components-artifact-${r.split(`.`).join(`-`)})`:void 0)}function E(e){return e?.features?.artifacts?.enabled===!0}function D(e,t){if(e.classList.remove(`persona-artifact-border-full`,`persona-artifact-border-left`),e.style.removeProperty(`--persona-artifact-pane-border`),e.style.removeProperty(`--persona-artifact-pane-border-left`),!E(t))return;let n=t.features?.artifacts?.layout,r=T(t,n?.paneBorder,`pane.border`),i=T(t,n?.paneBorderLeft,`pane.borderLeft`);r?(e.classList.add(`persona-artifact-border-full`),e.style.setProperty(`--persona-artifact-pane-border`,r)):i&&(e.classList.add(`persona-artifact-border-left`),e.style.setProperty(`--persona-artifact-pane-border-left`,i))}function O(e){e.style.removeProperty(`--persona-artifact-doc-toolbar-icon-color`),e.style.removeProperty(`--persona-artifact-doc-toggle-active-bg`),e.style.removeProperty(`--persona-artifact-doc-toggle-active-border`),e.style.removeProperty(`--persona-artifact-doc-toggle-active-color`)}const k=[`panel`,`seamless`,`detached`];function A(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&k.includes(t)?t:t?`panel`:e.launcher?.detachedPanel?`detached`:`panel`}function j(e){return!e||!E(e)?!1:A(e)===`detached`}function M(e,t){if(!E(t)){e.style.removeProperty(`--persona-artifact-split-gap`),e.style.removeProperty(`--persona-artifact-pane-width`),e.style.removeProperty(`--persona-artifact-pane-max-width`),e.style.removeProperty(`--persona-artifact-pane-min-width`),e.style.removeProperty(`--persona-artifact-drawer-width`),e.style.removeProperty(`--persona-artifact-pane-bg`),e.style.removeProperty(`--persona-artifact-pane-padding`),O(e),D(e,t);return}let n=t.features?.artifacts?.layout,r=A(t)===`detached`?`var(--persona-panel-inset)`:`0`;e.style.setProperty(`--persona-artifact-split-gap`,n?.splitGap??r),e.style.setProperty(`--persona-artifact-pane-width`,n?.paneWidth??`40%`),e.style.setProperty(`--persona-artifact-pane-max-width`,n?.paneMaxWidth??`28rem`),n?.drawerWidth?e.style.setProperty(`--persona-artifact-drawer-width`,n.drawerWidth):e.style.removeProperty(`--persona-artifact-drawer-width`),n?.paneMinWidth?e.style.setProperty(`--persona-artifact-pane-min-width`,n.paneMinWidth):e.style.removeProperty(`--persona-artifact-pane-min-width`);let i=T(t,n?.paneBackground,`pane.background`);i?e.style.setProperty(`--persona-artifact-pane-bg`,i):e.style.removeProperty(`--persona-artifact-pane-bg`);let a=T(t,n?.panePadding,`pane.padding`);a?e.style.setProperty(`--persona-artifact-pane-padding`,a):e.style.removeProperty(`--persona-artifact-pane-padding`);let o=[[T(t,n?.documentToolbarIconColor,`toolbar.iconColor`),`--persona-artifact-doc-toolbar-icon-color`],[T(t,n?.documentToolbarToggleActiveBackground,`toolbar.toggleActiveBackground`),`--persona-artifact-doc-toggle-active-bg`],[T(t,n?.documentToolbarToggleActiveBorderColor,`toolbar.toggleActiveBorderColor`),`--persona-artifact-doc-toggle-active-border`],[T(t,n?.documentToolbarToggleActiveColor,`toolbar.toggleActiveColor`),`--persona-artifact-doc-toggle-active-color`]];for(let[t,n]of o){let r=t?.trim();r?e.style.setProperty(n,r):e.style.removeProperty(n)}D(e,t)}function N(e,t){for(let t of k)e.classList.remove(`persona-artifact-appearance-${t}`);if(e.style.removeProperty(`--persona-artifact-pane-radius`),e.style.removeProperty(`--persona-artifact-pane-shadow`),e.style.removeProperty(`--persona-artifact-chat-shadow`),!E(t))return;let n=t.features?.artifacts?.layout,r=A(t);e.classList.add(`persona-artifact-appearance-${r}`);let i=T(t,n?.paneBorderRadius,`pane.borderRadius`);i&&e.style.setProperty(`--persona-artifact-pane-radius`,i);let a=T(t,n?.paneShadow,`pane.shadow`);a&&e.style.setProperty(`--persona-artifact-pane-shadow`,a);let o=T(t,n?.chatShadow,`chat.shadow`);o&&e.style.setProperty(`--persona-artifact-chat-shadow`,o)}function P(e,t){return!t||!E(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}function F(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function I(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function L(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function R(e,t,n,r){let i=e-r-2*t-n;return Math.max(0,i)}function z(e,t){let n=(t.getComputedStyle(e).gap||`0px`).trim().split(/\s+/)[0]??`0px`,r=/^([\d.]+)px$/i.exec(n);if(r)return Number(r[1]);let i=/^([\d.]+)/.exec(n);return i?Number(i[1]):8}function B(e,t,n,r,i,a,o=200){let s=F(i,200),c=R(t,n,r,o);c=Math.max(s,c);let l=I(a);return l!==null&&(c=Math.min(c,l)),L(e,s,c)}export{l as _,T as a,P as c,b as d,g as f,f as g,m as h,N as i,w as l,h as m,B as n,E as o,p,M as r,j as s,z as t,y as u,u as v,d as y};
@@ -0,0 +1 @@
1
+ const e=`4.31.0`;export{e as t};
@@ -1 +1 @@
1
- import{t as e}from"./chunk-18tPmsiJ.js";const t=32768,n=49152,r=e=>{let t=e??{},n=typeof t.targetId==`string`?t.targetId:null;return{id:typeof t.id==`string`?t.id:``,title:typeof t.title==`string`?t.title:``,targetId:n,preview:typeof t.preview==`string`?t.preview:null,messageCount:typeof t.messageCount==`number`?t.messageCount:0,createdAt:typeof t.createdAt==`string`?t.createdAt:``,updatedAt:typeof t.updatedAt==`string`?t.updatedAt:``}},i=`The identity proof was not admitted; account history is unavailable`,a=`The identity proof was rejected`,o=`The request carried no visitor credential`,s=`The stored visitor belongs to a different signed-in user`;function c(e,t,n){let r=new URLSearchParams;for(let[e,t]of Object.entries(n))t!==void 0&&t!==``&&r.set(e,String(t));let i=r.toString();return`${e.clientApiBase()}/v1/client/${t}${i?`?${i}`:``}`}function l(e,t){return t||e.config.features?.history?.scope||(e.config.getIdentityProof?`verified-user`:`browser`)}async function u(e,t,n){let r=e.config.getIdentityProof;if(!r)return n&&e.setHistoryIdentityStatus(e.browserOnlyStatus()),null;n&&e.setHistoryIdentityStatus({state:`verifying`});let i;try{i=await r()??null}catch{throw n&&e.setHistoryIdentityStatus({state:`identity_provider_failed`}),new e.HistoryClientError(`identity_provider_failed`,`The identity proof provider failed`)}if(i)return i;if(t.visitor?.endUserId!=null)throw n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`authentication_required`,`This browser is bound to a signed-in user and needs a fresh identity proof`);return n&&e.setHistoryIdentityStatus({state:`browser_only`,reason:`proof_unavailable_before_binding`}),null}async function d(e,t,n,r){if(t.visitor?.endUserId!=null)return t;let a=await e.reinitWithProof(n);if(a.visitor?.identityStatus!==`admitted`||a.visitor?.endUserId==null)throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,i);return a}async function f(e,t){let n=await t.json().catch(()=>({}));return typeof n.error==`string`?n.error:typeof n.message==`string`?n.message:``}async function p(e,t,n,r){let i=t.toLowerCase();if(i.includes(`invalid_identity_proof`))throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,a);if(i.includes(`visitor token required`))throw new e.HistoryClientError(`visitor_token_missing`,o);if(i.includes(`visitor_identity_mismatch`)){if(!n)throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`visitor_identity_mismatch`,s);return e.reinitWithProof(n)}if(i.includes(`expired`)||i.includes(`not found`))return e.clearClientSession(),e.initSession();throw new e.HistoryClientError(`unauthorized`,t||`History request was not authorized`)}async function m(e,t,n){let r=await f(e,t);if(t.status===404)return new e.HistoryClientError(`not_found`,`Conversation not found`);if(t.status===429){let n=Number.parseInt(t.headers.get(`Retry-After`)??``,10);return new e.HistoryClientError(`rate_limited`,`Too many history requests`,{...Number.isFinite(n)?{retryAfterSeconds:n}:{}})}if(t.status===503&&r.includes(`identity_proof_not_admitted`))return n&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,i);if(t.status===401){let t=r.toLowerCase();return t.includes(`invalid_identity_proof`)?(n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,a)):t.includes(`visitor token required`)?new e.HistoryClientError(`visitor_token_missing`,o):t.includes(`visitor_identity_mismatch`)?new e.HistoryClientError(`visitor_identity_mismatch`,s):new e.HistoryClientError(`unauthorized`,r||`History request was not authorized`)}return new e.HistoryClientError(`request_failed`,r||`History request failed (${t.status})`)}function h(e,t,n,r){let i=t?.toLowerCase()??null;if(n){if(i===`admitted`){r&&e.setHistoryIdentityStatus({state:`verified`});return}throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),i===`ignored`?new e.HistoryClientError(`identity_contract_violation`,`Server reported an ignored identity proof on a success response`):new e.HistoryClientError(`proof_not_admitted`,`The response did not acknowledge the identity proof this request sent`)}if(i===`admitted`)throw new e.HistoryClientError(`identity_contract_violation`,`Server admitted an identity proof that was never sent`);r&&e.setHistoryIdentityStatus(e.browserOnlyStatus())}async function g(t,n,r){_(t);let i=r.trackIdentity!==!1,a=await t.initSession(),o=null;l(t,r.scope)===`verified-user`&&(o=await u(t,a,i),o&&(a=await d(t,a,o,i)));let s=t.historyInternals.visitorStore,g=!1;for(;;){let l=s?.revision()??0,u=await t.readVisitorToken();if(!u&&!r.visitorTokenOptional)throw new t.HistoryClientError(`visitor_token_missing`,`No visitor credential is stored for this browser`);let d=await fetch(c(t,n,{...r.query,sessionId:a.sessionId}),{method:r.method,headers:{"X-Persona-Version":e,...u?{"X-Visitor-Token":u}:{},...o?{"X-Identity-Proof":o}:{},...r.body===void 0?{}:{"Content-Type":`application/json`}},...r.body===void 0?{}:{body:JSON.stringify(r.body)},...r.keepalive?{keepalive:!0}:{}});if(d.status===401&&!g){g=!0,a=await p(t,await f(t,d),o,i);continue}if(!d.ok)throw await m(t,d,i);let _=d.headers.get(`X-History-Identity-Status`),v=await d.json().catch(()=>void 0);if(s&&s.revision()!==l)throw new t.HistoryClientError(`credential_changed`,`The visitor credential changed while the request was in flight`);return h(t,_,o!==null,i),v}}function _(e){if(!e.isClientTokenMode())throw Error(`Conversation history is only available in client token mode`);if(!e.isHistoryCapable())throw new e.HistoryClientError(`history_disabled`,`Visitor history is disabled for this surface`)}async function v(e,t){let n=await g(e,`conversations`,{method:`GET`,query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit===void 0?{}:{limit:t.limit},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(r),nextCursor:typeof n?.nextCursor==`string`?n.nextCursor:null}}async function y(e,t,n){let i=await g(e,`conversations/${encodeURIComponent(t)}`,{method:`GET`,query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:r(i),messages:Array.isArray(i?.messages)?i.messages:[],nextMessageCursor:typeof i?.nextMessageCursor==`string`?i.nextMessageCursor:null,conversationRevision:typeof i?.conversationRevision==`string`?i.conversationRevision:null}}async function b(e,r,i){_(e);let a=0;for(let n of i){let r=n.displayContent.length;if(r>t)throw new e.HistoryClientError(`payload_too_large`,`displayContent exceeds the ${t} character limit`);a+=r}if(a>n)throw new e.HistoryClientError(`payload_too_large`,`Display projection batch exceeds the ${n} character limit`);await e.initSession();let o=e.historyInternals.visitorStore,s=o?.revision()??0,c=await g(e,`conversations/${encodeURIComponent(r)}/display-projections`,{method:`PATCH`,body:{messages:i},scope:`browser`,keepalive:a<=n,trackIdentity:!1}),l=typeof c?.conversationRevision==`string`?c.conversationRevision:null;return l&&e.clientSession?.conversationId===r&&(o?.revision()??0)===s&&e.historyInternals.setStoredConversationRevision?.(l),{conversationRevision:l}}async function x(e,t,n){let r=await g(e,`conversations/${encodeURIComponent(t)}`,{method:`DELETE`,...n?.scope?{scope:n.scope}:{}});return{deleted:typeof r?.deleted==`number`?r.deleted:0}}async function S(e,t){let n=await g(e,`conversations`,{method:`DELETE`,query:{...t?.targetId===void 0?{}:{targetId:t.targetId}},...t?.scope?{scope:t.scope}:{}});return{deleted:typeof n?.deleted==`number`?n.deleted:0}}async function C(e){_(e),e.setHistoryIdentityStatus({state:`resetting`});try{await g(e,`visitor/reset`,{method:`POST`,scope:`browser`,visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}export{S as deleteAllConversations,x as deleteConversation,b as finalizeDisplayProjections,y as getConversation,m as historyErrorFor,v as listConversations,f as readErrorCode,p as recoverFromUnauthorized,C as resetVisitor};
1
+ import{t as e}from"./chunk-CjhA_5Jk.js";const t=32768,n=49152,r=e=>{let t=e??{},n=typeof t.targetId==`string`?t.targetId:null;return{id:typeof t.id==`string`?t.id:``,title:typeof t.title==`string`?t.title:``,targetId:n,preview:typeof t.preview==`string`?t.preview:null,messageCount:typeof t.messageCount==`number`?t.messageCount:0,createdAt:typeof t.createdAt==`string`?t.createdAt:``,updatedAt:typeof t.updatedAt==`string`?t.updatedAt:``}},i=`The identity proof was not admitted; account history is unavailable`,a=`The identity proof was rejected`,o=`The request carried no visitor credential`,s=`The stored visitor belongs to a different signed-in user`;function c(e,t,n){let r=new URLSearchParams;for(let[e,t]of Object.entries(n))t!==void 0&&t!==``&&r.set(e,String(t));let i=r.toString();return`${e.clientApiBase()}/v1/client/${t}${i?`?${i}`:``}`}function l(e,t){return t||e.config.features?.history?.scope||(e.config.getIdentityProof?`verified-user`:`browser`)}async function u(e,t,n){let r=e.config.getIdentityProof;if(!r)return n&&e.setHistoryIdentityStatus(e.browserOnlyStatus()),null;n&&e.setHistoryIdentityStatus({state:`verifying`});let i;try{i=await r()??null}catch{throw n&&e.setHistoryIdentityStatus({state:`identity_provider_failed`}),new e.HistoryClientError(`identity_provider_failed`,`The identity proof provider failed`)}if(i)return i;if(t.visitor?.endUserId!=null)throw n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`authentication_required`,`This browser is bound to a signed-in user and needs a fresh identity proof`);return n&&e.setHistoryIdentityStatus({state:`browser_only`,reason:`proof_unavailable_before_binding`}),null}async function d(e,t,n,r){if(t.visitor?.endUserId!=null)return t;let a=await e.reinitWithProof(n);if(a.visitor?.identityStatus!==`admitted`||a.visitor?.endUserId==null)throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,i);return a}async function f(e,t){let n=await t.json().catch(()=>({}));return typeof n.error==`string`?n.error:typeof n.message==`string`?n.message:``}async function p(e,t,n,r){let i=t.toLowerCase();if(i.includes(`invalid_identity_proof`))throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,a);if(i.includes(`visitor token required`))throw new e.HistoryClientError(`visitor_token_missing`,o);if(i.includes(`visitor_identity_mismatch`)){if(!n)throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`visitor_identity_mismatch`,s);return e.reinitWithProof(n)}if(i.includes(`expired`)||i.includes(`not found`))return e.clearClientSession(),e.initSession();throw new e.HistoryClientError(`unauthorized`,t||`History request was not authorized`)}async function m(e,t,n){let r=await f(e,t);if(t.status===404)return new e.HistoryClientError(`not_found`,`Conversation not found`);if(t.status===429){let n=Number.parseInt(t.headers.get(`Retry-After`)??``,10);return new e.HistoryClientError(`rate_limited`,`Too many history requests`,{...Number.isFinite(n)?{retryAfterSeconds:n}:{}})}if(t.status===503&&r.includes(`identity_proof_not_admitted`))return n&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,i);if(t.status===401){let t=r.toLowerCase();return t.includes(`invalid_identity_proof`)?(n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,a)):t.includes(`visitor token required`)?new e.HistoryClientError(`visitor_token_missing`,o):t.includes(`visitor_identity_mismatch`)?new e.HistoryClientError(`visitor_identity_mismatch`,s):new e.HistoryClientError(`unauthorized`,r||`History request was not authorized`)}return new e.HistoryClientError(`request_failed`,r||`History request failed (${t.status})`)}function h(e,t,n,r){let i=t?.toLowerCase()??null;if(n){if(i===`admitted`){r&&e.setHistoryIdentityStatus({state:`verified`});return}throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),i===`ignored`?new e.HistoryClientError(`identity_contract_violation`,`Server reported an ignored identity proof on a success response`):new e.HistoryClientError(`proof_not_admitted`,`The response did not acknowledge the identity proof this request sent`)}if(i===`admitted`)throw new e.HistoryClientError(`identity_contract_violation`,`Server admitted an identity proof that was never sent`);r&&e.setHistoryIdentityStatus(e.browserOnlyStatus())}async function g(t,n,r){_(t);let i=r.trackIdentity!==!1,a=await t.initSession(),o=null;l(t,r.scope)===`verified-user`&&(o=await u(t,a,i),o&&(a=await d(t,a,o,i)));let s=t.historyInternals.visitorStore,g=!1;for(;;){let l=s?.revision()??0,u=await t.readVisitorToken();if(!u&&!r.visitorTokenOptional)throw new t.HistoryClientError(`visitor_token_missing`,`No visitor credential is stored for this browser`);let d=await fetch(c(t,n,{...r.query,sessionId:a.sessionId}),{method:r.method,headers:{"X-Persona-Version":e,...u?{"X-Visitor-Token":u}:{},...o?{"X-Identity-Proof":o}:{},...r.body===void 0?{}:{"Content-Type":`application/json`}},...r.body===void 0?{}:{body:JSON.stringify(r.body)},...r.keepalive?{keepalive:!0}:{}});if(d.status===401&&!g){g=!0,a=await p(t,await f(t,d),o,i);continue}if(!d.ok)throw await m(t,d,i);let _=d.headers.get(`X-History-Identity-Status`),v=await d.json().catch(()=>void 0);if(s&&s.revision()!==l)throw new t.HistoryClientError(`credential_changed`,`The visitor credential changed while the request was in flight`);return h(t,_,o!==null,i),v}}function _(e){if(!e.isClientTokenMode())throw Error(`Conversation history is only available in client token mode`);if(!e.isHistoryCapable())throw new e.HistoryClientError(`history_disabled`,`Visitor history is disabled for this surface`)}async function v(e,t){let n=await g(e,`conversations`,{method:`GET`,query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit===void 0?{}:{limit:t.limit},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(r),nextCursor:typeof n?.nextCursor==`string`?n.nextCursor:null}}async function y(e,t,n){let i=await g(e,`conversations/${encodeURIComponent(t)}`,{method:`GET`,query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:r(i),messages:Array.isArray(i?.messages)?i.messages:[],nextMessageCursor:typeof i?.nextMessageCursor==`string`?i.nextMessageCursor:null,conversationRevision:typeof i?.conversationRevision==`string`?i.conversationRevision:null}}async function b(e,r,i){_(e);let a=0;for(let n of i){let r=n.displayContent.length;if(r>t)throw new e.HistoryClientError(`payload_too_large`,`displayContent exceeds the ${t} character limit`);a+=r}if(a>n)throw new e.HistoryClientError(`payload_too_large`,`Display projection batch exceeds the ${n} character limit`);await e.initSession();let o=e.historyInternals.visitorStore,s=o?.revision()??0,c=await g(e,`conversations/${encodeURIComponent(r)}/display-projections`,{method:`PATCH`,body:{messages:i},scope:`browser`,keepalive:a<=n,trackIdentity:!1}),l=typeof c?.conversationRevision==`string`?c.conversationRevision:null;return l&&e.clientSession?.conversationId===r&&(o?.revision()??0)===s&&e.historyInternals.setStoredConversationRevision?.(l),{conversationRevision:l}}async function x(e,t,n){let r=await g(e,`conversations/${encodeURIComponent(t)}`,{method:`DELETE`,...n?.scope?{scope:n.scope}:{}});return{deleted:typeof r?.deleted==`number`?r.deleted:0}}async function S(e,t){let n=await g(e,`conversations`,{method:`DELETE`,query:{...t?.targetId===void 0?{}:{targetId:t.targetId}},...t?.scope?{scope:t.scope}:{}});return{deleted:typeof n?.deleted==`number`?n.deleted:0}}async function C(e){_(e),e.setHistoryIdentityStatus({state:`resetting`});try{await g(e,`visitor/reset`,{method:`POST`,scope:`browser`,visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}export{S as deleteAllConversations,x as deleteConversation,b as finalizeDisplayProjections,y as getConversation,m as historyErrorFor,v as listConversations,f as readErrorCode,p as recoverFromUnauthorized,C as resetVisitor};
@@ -0,0 +1,2 @@
1
+ import{t as e}from"./chunk-DbD5qyBw.js";import{Marked as t}from"marked";import n from"dompurify";const r=e=>!e||/\s/.test(e),i=e=>!!e&&/[\p{P}\p{S}]/u.test(e),a=(e,t,n)=>{let r=e.slice(t,n),i=n;for(;(i=e.indexOf(r,i))!==-1;){if(e[i-1]!=="`"&&e[i+r.length]!=="`")return i+r.length;i+=r.length}return-1},o=(e,t=!0)=>{let n=[],s=/* @__PURE__ */ new Set,c=``;for(let l=0;l<e.length;){let u=e[l];if(u===`\\`)c+=e.slice(l,l+2),l+=2;else if(u==="`"){let t=l+1;for(;e[t]==="`";)t++;let n=e.slice(l,t),r=a(e,l,t);if(r!==-1)c+=e.slice(l,r),l=r;else{let r=e.slice(t);c+=r?`${n}${r}${r.endsWith("`")?` `:``}${n}`:``,l=e.length}}else if(u===`<`){let t=e.indexOf(`>`,l+1);c+=e.slice(l,t<0?e.length:t+1),l=t<0?e.length:t+1}else if(t&&(u===`[`||u===`!`&&e[l+1]===`[`)){let t=u===`!`,n=l+(t?2:1),i=1,s=n;for(;s<e.length;s++)if(e[s]===`\\`)s++;else if(e[s]==="`"){let t=s+1;for(;e[t]==="`";)t++;let n=a(e,s,t);s=(n<0?t:n)-1}else if(e[s]===`[`&&i++,e[s]===`]`&&--i===0)break;if(s>=e.length){c+=t?``:o(e.slice(n),!1);break}if(e[s+1]===`(`){let i=1,a=``,u=!1,d=s+2;for(;d<e.length;d++){let t=e[d];if(t===`\\`)d++;else if(a)t===a&&(a=``);else if((t===`"`||t===`'`)&&r(e[d-1]))a=t;else if(t===`<`&&(u=!0),t===`>`&&(u=!1),!u&&t===`(`&&i++,!u&&t===`)`&&--i===0)break}if(d>=e.length){c+=t?``:o(e.slice(n,s),!1);break}c+=e.slice(l,d+1),l=d+1;continue}if(s===e.length-1){c+=t?``:o(e.slice(n,s),!1);break}c+=e.slice(l,s+1),l=s+1}else if(u===`*`||u===`_`){let t=l+1;for(;e[t]===u;)t++;let a=e.slice(l,t),o=e[l-1]??``,d=e[t]??``,f=!r(d)&&(!i(d)||r(o)||i(o)),p=!r(o)&&(!i(o)||r(d)||i(d)),m=a.length;if(p&&(u!==`_`||!f||i(d)))for(;m&&n[n.length-1]?.marker[0]===u;){let e=n[n.length-1],t=Math.min(m,e.marker.length);m-=t,e.marker=e.marker.slice(t),e.marker||n.pop()}if(m&&a.length<=3&&f&&!p)n.push({marker:u.repeat(m)});else if(m===a.length&&t===e.length&&r(o)&&e.slice(e.lastIndexOf(`
2
+ `,l)+1,l).trim()&&(n.length>0||!s.has(u))){l=t;continue}r(o)&&r(d)&&t<e.length&&s.add(u),c+=a,l=t}else c+=u,l++}let l=c.match(/\s*$/)?.[0]??``;c=c.slice(0,c.length-l.length),n.length&&(c.match(/\\+$/)?.[0].length??0)%2&&(c+=`\\`);for(let e=n.length-1;e>=0;e--)c+=n[e].marker;return c+l},s=t=>{let n=``,r=``,i=``,a=()=>{n+=e(r).split(/(\n\s*\n)/).map(e=>/^\n\s*\n$/.test(e)?e:o(e)).join(``),r=``};for(let e of t.match(/[^\n]*\n|[^\n]+$/g)??[]){let t=/^(?: {0,3}> ?)* {0,3}(?:[-+*] )?(`{3,}|~{3,})(.*)/.exec(e);i?(n+=e,t&&t[1][0]===i[0]&&t[1].length>=i.length&&!t[2].trim()&&(i=``)):t?(a(),i=t[1],n+=e):/^(?: {4}|\t)/.test(e)?(a(),n+=e):r+=e}return a(),n};export{n as DOMPurify,t as Marked,s as stabilizeStreamingMarkdown};
@@ -0,0 +1,3 @@
1
+ const e=/^\s*\|?[\s:|-]*-[\s:|-]*$/,t=e=>e.includes(`|`),n=e=>{let t=e.trim();return t.startsWith(`|`)&&(t=t.slice(1)),t.endsWith(`|`)&&(t=t.slice(0,-1)),t.split(`|`).map(e=>e.trim())},r=e=>`| ${e.join(` | `)} |`,i=e=>`| ${Array.from({length:e},()=>`---`).join(` | `)} |`,a=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>``)),o=o=>{if(!o||!o.includes(`|`))return o;let s=o.split(`
2
+ `),c=!1;for(let o=0;o<s.length-1;o++){let l=s[o],u=s[o+1];if(!t(l)||e.test(l)||!e.test(u))continue;let d=n(l).length;if(d<1)continue;let f=i(d);s[o+1]!==f&&(s[o+1]=f,c=!0);let p=o+2;for(;p<s.length;p++){let e=s[p];if(e.trim()===``||!t(e))break;let i=r(a(n(e),d));s[p]!==i&&(s[p]=i,c=!0)}o=p-1}return c?s.join(`
3
+ `):o};export{o as t};