@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,7 +1,7 @@
1
- import{t as e}from"./chunk-DVgzoVCB.js";import{t}from"./chunk-DqbzUVEI.js";const n=16e3,r=/* @__PURE__ */ new Map([[`idle_timeout`,`Voice call ended after a quiet period.`],[`max_duration`,`This voice call reached its time limit.`],[`provider_ended`,`The voice session ended.`],[`quota`,`Voice is unavailable right now.`],[`auth_expired`,`Voice session expired. Tap the mic to reconnect.`]]),i=[`provider_error`,`server_restart`],a=`Voice connection lost.`;function o(e,t){let n=t.slice(0,4e3).trim(),r=8e3-(n?n.length+2:0)-20,i=[];for(let t of e.slice(-12).reverse()){let e=t.content.replace(/\s+/g,` `).trim();if(!e)continue;e.length>2e3&&(e=`${e.slice(0,1999)}…`);let n=`${t.role===`user`?`User`:`Assistant`}: ${e}`;if(n.length+1>r)break;r-=n.length+1,i.unshift(n)}let a=i.length>0?[`Conversation so far:\n${i.join(`
1
+ import{t as e}from"./chunk-Dqa_GOcj.js";import{t}from"./chunk-DqbzUVEI.js";const n=16e3,r=/* @__PURE__ */ new Map([[`idle_timeout`,`Voice call ended after a quiet period.`],[`max_duration`,`This voice call reached its time limit.`],[`provider_ended`,`The voice session ended.`],[`quota`,`Voice is unavailable right now.`],[`auth_expired`,`Voice session expired. Tap the mic to reconnect.`]]),i=[`provider_error`,`server_restart`],a=`Voice connection lost.`;function o(e,t){let n=t.slice(0,4e3).trim(),r=8e3-(n?n.length+2:0)-20,i=[];for(let t of e.slice(-12).reverse()){let e=t.content.replace(/\s+/g,` `).trim();if(!e)continue;e.length>2e3&&(e=`${e.slice(0,1999)}…`);let n=`${t.role===`user`?`User`:`Assistant`}: ${e}`;if(n.length+1>r)break;r-=n.length+1,i.unshift(n)}let a=i.length>0?[`Conversation so far:\n${i.join(`
2
2
  `)}`]:[];return n&&a.push(n),a.join(`
3
3
 
4
- `)}function s(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===1380533830?new Uint8Array(e,44):new Uint8Array(e)}function c(e){let t=e.replace(/\/+$/,``);return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,`ws`):`${typeof window<`u`&&window.location?.protocol===`https:`?`wss:`:`ws:`}//${t}`}function l(e){return c(e).replace(/^ws/i,`http`)}function u(e){return typeof e!=`number`||!Number.isFinite(e)?3e4:Math.min(6e5,Math.max(3e4,Math.round(e)))}var d=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;#E;#D;#O;#k;#A;#j;#M;#N;#P;#F;#I;#L;#R;#z;#B;#V;#H;#U;#W;#G;#K;#q;#J;#Y;constructor(e){this.config=e,this.type=`runtype`,this.#e=null,this.#t=null,this.#n=[],this.#r=null,this.#i=null,this.#a=null,this.#o=[],this.#s=0,this.#c=null,this.#l=!1,this.#u=!1,this.#d=0,this.#f=!1,this.#p=-1/0,this.#m=null,this.#h=!1,this.#g=!1,this.#_=0,this.#v=0,this.#b=!1,this.bridge=null,this.#x=!1,this.#S=/* @__PURE__ */ new Set,this.#C=/* @__PURE__ */ new Map,this.#w=/* @__PURE__ */ new Set,this.#E=null,this.#D=null,this.#k=!1,this.#A=!1,this.#j=!1,this.#M=null,this.#N=null,this.#P=Promise.resolve(),this.#F=/* @__PURE__ */ new Set,this.#I=/* @__PURE__ */ new Set,this.#L=null,this.#R=!1,this.#z=/* @__PURE__ */ new Set,this.#B=/* @__PURE__ */ new Set,this.#V=null,this.#H=/* @__PURE__ */ new Set,this.#U=null,this.#W=/* @__PURE__ */ new Map,this.#G=[],this.#K=[],this.#q=[],this.#J=[],this.#Y=[]}async connect(){}setSessionBridge(e){this.bridge=e}prewarm(){if(this.#l||this.#m)return;let e=this.config?.agentId,t=this.config?.clientToken,n=this.config?.host;if(!e||!t||!n)return;let r=Date.now();if(!(r-this.#p<3e4)){this.#p=r;try{this.config?.prewarmMode===`attach`?this.#Z(n,e,t):this.#X(n,e,t)}catch{}}}#X(e,t,n){if(typeof fetch!=`function`)return;let r=`${l(e)}/v1/client/agents/${encodeURIComponent(t)}/voice/prewarm`;fetch(r,{method:`POST`,headers:{Authorization:`Bearer ${n}`},keepalive:!0}).catch(()=>{})}#Z(e,t,n){let r=new URLSearchParams,i=this.config?.attachIdleMs,a=u(i);i!==void 0&&r.set(`attachIdleMs`,String(a));let o=new WebSocket(this.#te(e,t,r),[`runtype.bearer`,`runtype.attach`,n]);o.binaryType=`arraybuffer`;let s=()=>{},c={ws:o,state:`connecting`,ready:new Promise(e=>{s=e}),settle:s,openedAt:0,idleTimer:void 0};this.#m=c,o.onopen=()=>{this.#m===c&&(c.state=o.protocol===`runtype.attach`?`attached`:`live`,c.openedAt=Date.now(),this.#Q(c,a),c.state===`attached`&&o.send(`{"type":"ping"}`),c.settle())},o.onmessage=e=>{if(this.#m!==c||typeof e.data!=`string`)return;let t;try{t=JSON.parse(e.data)}catch{return}t.type===`attached`&&typeof t.idleMs==`number`&&this.#Q(c,t.idleMs-(Date.now()-c.openedAt))},o.onerror=()=>{},o.onclose=()=>{this.#m===c&&this.#$()}}#Q(e,t){clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>{this.#m===e&&this.#$()},Math.max(0,t))}#$(){let e=this.#m;if(!e)return;this.#m=null,clearTimeout(e.idleTimer);let{ws:t}=e;if(t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null,e.settle(),t.readyState===WebSocket.CONNECTING||t.readyState===WebSocket.OPEN)try{t.close(1e3,`prewarm released`)}catch{}}async#ee(){let e=this.#m;if(!e)return null;if(e.state===`connecting`){let t;await Promise.race([e.ready,new Promise(e=>{t=setTimeout(e,5e3)})]),clearTimeout(t)}return this.#m===e?e.state===`connecting`||e.ws.readyState!==WebSocket.OPEN?(this.#$(),null):(this.#m=null,clearTimeout(e.idleTimer),{ws:e.ws,live:e.state===`live`}):null}#te(t,n,r){let i=`partial_transcript,context`;this.bridge&&this.config?.clientDelegation!==!1&&(i+=`,client_delegation,delegation_update,delegation_read_back,delegation_stream`,this.bridge.clientTools?.()&&(i+=`,client_tools,prior_tool_results`)),r&&(i=`attach,${i}`);let a=new URLSearchParams({voiceProtocol:`runtype-browser-v1`,clientVersion:`persona/${e}`,voiceCapabilities:`full-duplex-v1`,clientCapabilities:i});return r?.forEach((e,t)=>a.set(t,e)),`${c(t)}/ws/agents/${encodeURIComponent(n)}/voice?${a}`}async startListening(){if(this.#l)return;let e=this.#A;e||(this.#k=!1,this.#D=null),this.#A=!1;let r=this.config?.agentId,i=this.config?.clientToken,o=this.config?.host;if(!r)throw Error(`Runtype voice requires an agentId`);if(!i)throw Error(`Runtype voice requires a clientToken`);if(!o)throw Error(`Runtype voice requires a host (or widget apiUrl)`);let s=++this.#d;this.#f=!1,this.#l=!0;try{let c=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:n,channelCount:1,echoCancellation:!0}});if(s!==this.#d){c.getTracks().forEach(e=>e.stop());return}this.#r=c;let l=new(window.AudioContext||window.webkitAudioContext)({sampleRate:n});if(this.#t=l,l.state===`suspended`){if(await Promise.race([l.resume().catch(()=>{}),new Promise(t=>setTimeout(t,e?500:1e3))]),s!==this.#d)return;if(l.state!==`running`)throw Error(e?this.#D=`${a} Tap the mic to reconnect.`:`Audio blocked until a tap`)}let u=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new t(24e3);if(s!==this.#d){u.destroy(),c.getTracks().forEach(e=>e.stop()),l.close().catch(()=>{});return}this.#c=u,this.#he(),this.#ie(l,c,s);let d=await this.#ee();if(s!==this.#d){d?.ws.close(1e3,`client ended call`);return}if(d){let{ws:e}=d;this.#e=e,this.#ne(e,s),d.live||e.send(`{"type":"start"}`),this.#ae(e),this.#be(`listening`);return}let f=new WebSocket(this.#te(o,r),[`runtype.bearer`,i]);f.binaryType=`arraybuffer`,this.#e=f,f.onopen=()=>{s===this.#d&&(this.#ae(f),this.#be(`listening`))},this.#ne(f,s)}catch(e){throw this.#ye(),this.#xe(e),this.#be(`error`),e}}#ne(e,t){e.onmessage=e=>this.#oe(e,t),e.onerror=()=>{t!==this.#d||this.#E||(this.#xe(/* @__PURE__ */ Error(`Voice connection failed`)),this.#be(`error`),this.#ye())},e.onclose=e=>{if(this.#f){this.#f=!1;return}if(t!==this.#d)return;let n=this.#E??(e.code===4408?{reason:`idle_timeout`}:null);if(n)this.#re(n.reason,n.message);else{if(e.code!==1e3){let t=e.code?` (code ${e.code})`:``;this.#xe(/* @__PURE__ */ Error(`Voice connection closed${t}`)),this.#be(`error`)}else this.#be(`idle`);this.#ye()}}}#re(e,t){let n=i.includes(e)&&!this.#k;if(this.#ye(),n)this.#k=!0,this.#l=!0,this.#D=e===`provider_error`?`${a} Reconnecting…`:`Reconnecting…`,this.#O=setTimeout(()=>{this.#l=!1,this.#A=!0,this.startListening().catch(()=>{})},1e3+Math.random()*1e3),this.#be(`idle`);else{if(i.includes(e))return this.#D=a,this.#xe(/* @__PURE__ */ Error(a)),this.#be(`error`);if(e===`error`)return this.#be(`error`);this.#D=e===`quota`&&t||r.get(e)||null,this.#be(`idle`)}}takeNotice(){let e=this.#D;return this.#D=null,e}getDisclosure(){let e=this.config?.disclosureText;return this.#l&&this.#h&&e!==!1?e||`You're talking to an AI assistant. Voice is processed by OpenAI.`:null}async stopListening(){this.#ye(),this.#be(`idle`)}async disconnect(){this.#ye(),this.#be(`disconnected`),this.#G=[],this.#K=[],this.#q=[],this.#J=[],this.#Y=[]}stopPlayback(){this.#ve();let e=this.#e;e&&e.readyState===WebSocket.OPEN&&(this.#h&&(this.#_=Date.now()+2e3,e.send(`{"type":"cancel"}`)),this.#be(`listening`))}getInterruptionMode(){return`barge-in`}isBargeInActive(){return this.#l}onLevel(e){this.#n.push(e)}async deactivateBargeIn(){this.#ye(),this.#be(`idle`)}#ie(e,t,n){let r=e.createMediaStreamSource(t);this.#i=r;let i=e.createScriptProcessor(4096,1,1);this.#a=i,i.onaudioprocess=e=>{if(n!==this.#d)return;let t=this.#e,r=t?.readyState===WebSocket.OPEN;if(t&&!r&&t.readyState!==WebSocket.CONNECTING)return;let i=e.inputBuffer.getChannelData(0),a=new Int16Array(i.length),o=0;for(let e=0;e<i.length;e++){let t=Math.max(-1,Math.min(1,i[e]));o+=t*t,a[e]=t<0?t*32768:t*32767}if(t&&r)this.#ae(t),t.send(a.buffer);else for(this.#o.push(a.buffer),this.#s+=a.byteLength;this.#s>256e3;)this.#s-=this.#o.shift().byteLength;if(this.#n.length>0){let e=Math.sqrt(o/i.length),t=Math.max(0,Math.min(1,e*4));for(let e of this.#n)e(t)}},r.connect(i),i.connect(e.destination)}#ae(e){for(let t of this.#o)e.send(t);this.#o=[],this.#s=0}#oe(e,t){if(t!==this.#d)return;if(e.data instanceof ArrayBuffer){this.#pe(e.data,t);return}let n;try{n=JSON.parse(e.data)}catch{return}switch(n.type){case`session_config`:n.speechMode&&(this.#h=n.speechMode===`speech_to_speech`,this.#c?.setContinuousMode?.(this.#h)),Array.isArray(n.capabilities)&&(this.#S=new Set(n.capabilities)),typeof n.callId==`string`&&(this.#T=n.callId),this.#x=this.#h&&this.#S.has(`client_delegation`)&&!!this.bridge,this.#h&&!this.#u&&this.#be(`listening`),this.#S.has(`context`)&&!this.#j&&(this.#j=!0,this.#M=this.#se()),this.#x&&this.#S.has(`client_tools`)&&!this.#V&&(this.#V=this.bridge.clientTools?.()?.open({send:e=>{let n=this.#e;return t!==this.#d||n?.readyState!==WebSocket.OPEN?!1:(n.send(JSON.stringify(e)),!0)},cancelled:e=>this.#w.has(e)}).catch(()=>null)??null);break;case`client_tool_call`:{let e=String(n.delegationId);this.#V&&!this.#W.has(e)&&(this.#W.set(e,this.#U),this.#F.add(e)),this.#V?.then(e=>e?.call(n));break}case`transcript_update`:{let e=n.role===`assistant`?`assistant`:`user`,r=n.utteranceId??n.turnId;if(!r||e===`assistant`&&this.#me())break;let i=String(r);if(e===`user`)n.final===!0&&(this.#ce(t),this.#U={id:i,text:String(n.text??``)}),this.#R=!1;else{if(this.#S.has(`delegation_read_back`)){let e=n.delegationId;(typeof e==`string`&&this.#F.has(e)&&!this.#z.has(i)||this.#R&&!this.#z.has(i))&&(this.#B.add(i),this.#R=!1)}else this.#R&&!this.#z.has(i)&&(this.#B.add(i),this.#R=!1);if(this.#z.add(i),this.#B.has(i))break}this.#Se(e,n.text??``,n.final===!0,{turnId:i,...typeof n.startMs==`number`&&{startMs:n.startMs},...typeof n.endMs==`number`&&{endMs:n.endMs},...this.#x&&{caption:!0}});break}case`delegation_started`:case`delegation_completed`:{let e=String(n.delegationId??n.turnId);if(n.type===`delegation_started`){this.#ce(t),this.#H.add(e),this.#F.delete(e),this.#W.delete(e)&&this.#V?.then(t=>t?.abort(e));let r=n.input;this.#x&&r&&this.#fe(e,{delegationId:e,userText:String(r.text??``),userUtteranceIds:Array.isArray(r.userUtteranceIds)?r.userUtteranceIds.filter(e=>typeof e==`string`):[],messages:Array.isArray(r.messages)?r.messages:[],priorToolResults:r.priorToolResults},t)}else if(n.route===`direct`&&this.#V&&!this.#H.has(e)){let t=this.#W.get(e)??this.#U;this.#W.delete(e),this.#H.add(e),this.#F.add(e),this.bridge?.recordDirectTurn?.({delegationId:e,userText:t?.text??``,userUtteranceIds:t?[t.id]:[],assistantText:typeof n.text==`string`?n.text:``})}n.type===`delegation_completed`&&n.speak!==!1&&this.#F.has(e)&&!this.#I.delete(e)&&!this.#S.has(`delegation_read_back`)&&this.#ue(e),this.#g=n.type===`delegation_started`,!this.#u&&!this.#me()&&this.#be(this.#g?`processing`:`listening`);break}case`delegation_progress`:{let e=String(n.delegationId);this.#F.has(e)&&!this.#I.has(e)&&!this.#w.has(e)&&(this.#I.add(e),this.#ue(e));break}case`delegation_cancelled`:this.#de(String(n.delegationId),n.reason!==`session_ending`&&n.reason!==`provider_cancelled`);break;case`warning`:console.warn(`[Persona voice] ${n.code}: ${n.message??``}`,this.#T??``),n.delegationId&&(n.code===`UNKNOWN_DELEGATION`||n.code===`LATE_RESULT_LIMIT`)&&this.#de(String(n.delegationId));break;case`audio_clear`:this.#ve(),this.#_=0,this.#be(`listening`);break;case`transcript_interim`:this.#be(`listening`),this.#Se(`user`,n.text??``,!1);break;case`transcript_final`:{let e=n.role===`assistant`?`assistant`:`user`;this.#be(e===`user`?`processing`:`speaking`),this.#Se(e,n.text??``,!0);break}case`audio_end`:this.#c?this.#c.markStreamEnd():(this.#u=!1,this.#be(`listening`));break;case`metrics`:this.#Ce({llmMs:n.llm_ms,ttsMs:n.tts_ms,firstAudioMs:n.first_audio_ms,totalMs:n.total_ms});break;case`error`:this.#xe(Error(n.error||`Voice error`)),this.#be(`error`);break;case`session_end`:this.#E={reason:String(n.reason),...typeof n.message==`string`&&{message:n.message}}}}async#se(){let e=this.bridge?.getHistory()??[],t=``;try{let e=this.config?.callContext;t=String((typeof e==`function`?await e():e)??``)}catch{}return o(e,t)}#ce(e){let t=this.#M;if(!t)return;this.#M=null;let n=!1,r=t.then(t=>{let r=this.#e;!n&&t&&e===this.#d&&r?.readyState===WebSocket.OPEN&&r.send(JSON.stringify({type:`context`,text:t}))});this.#N={done:r,drop:()=>n=!0}}async#le(){let e=this.#N;if(!e)return;let t,n=await Promise.race([e.done.then(()=>!1),new Promise(e=>{t=setTimeout(()=>e(!0),2e3)})]);clearTimeout(t),n&&e.drop()}#ue(e){this.#R=!0,this.#L=e}#de(e,t=!1){this.#w.add(e),this.#L===e&&(this.#R=!1),this.#I.delete(e),this.#H.has(e)||this.#F.delete(e),this.#V?.then(t=>t?.abort(e)),this.bridge?.dropDelegation?.(e,t),this.#C.get(e)?.abort()}#fe(e,t,n){let r=this.bridge,i=({type:t,...r})=>{let i=this.#e;return n!==this.#d||i?.readyState!==WebSocket.OPEN||this.#w.has(e)?!1:(i.send(JSON.stringify({type:t,delegationId:e,...r})),!0)},a=(e,t,n,r=0)=>i({type:e,status:t,text:n,...r>0&&{streamedChars:r}});this.#P=this.#P.then(async()=>{if(n!==this.#d||this.#w.has(e))return;let o=null,s=this.#S.has(`delegation_stream`)&&this.#S.has(`delegation_read_back`),c=t=>{o=(o??this.#le()).then(()=>{i({type:`delegation_delta`,text:t})&&this.#F.add(e)})},l=await r.runDelegatedTurn(s?{...t,stream:c}:t).catch(()=>({status:`failed`,text:``}));await this.#le(),await o;let u=s?l.streamedChars??0:0,d=!!l.followUp,f=d&&this.#S.has(`delegation_update`);if(!a(f?`delegation_update`:`delegation_result`,d&&!f?`completed`:l.status,l.text,u)||(l.status!==`failed`&&l.inChat!==!1&&this.#F.add(e),!l.followUp))return;let p=new AbortController;this.#C.set(e,p),l.followUp({signal:p.signal,approvalTimeoutMs:this.config?.approvalTimeoutMs&&Math.min(this.config.approvalTimeoutMs,54e4),readBack:f,onUpdate:e=>a(`delegation_update`,`pending_approval`,e)}).then(t=>{this.#C.delete(e),f&&t&&!p.signal.aborted&&a(`delegation_result`,t.status,t.text)})})}#pe(e,t){if(t!==this.#d||!this.#c||this.#me())return;let n=s(e);n.length!==0&&(this.#u||(this.#u=!0,this.#be(`speaking`)),this.#he(),this.#c.enqueue(n),this.#h&&this.#ge(n.length))}#me(){return Date.now()<this.#_}#he(){if(this.#b||!this.#c)return;this.#b=!0;let e=this.#d;this.#c.onFinished(()=>{e===this.#d&&(this.#b=!1,this.#_e())})}#ge(e){let t=Date.now();this.#v=Math.max(t,this.#v)+e/48,clearTimeout(this.#y),this.#y=setTimeout(()=>this.#_e(),this.#v-t+300)}#_e(){this.#u=!1,this.#v=0,this.#e&&this.#e.readyState===WebSocket.OPEN&&this.#be(this.#g?`processing`:`listening`)}#ve(){this.#c?.flush(),this.#b=!1,this.#he(),this.#u=!1,this.#v=0,clearTimeout(this.#y)}#ye(){this.#d+=1,this.#l=!1,this.#u=!1,this.#$(),this.#h=!1,this.#g=!1,this.#x=!1,this.#S=/* @__PURE__ */ new Set;for(let e of this.#C.values())e.abort();if(this.#C.clear(),this.#w.clear(),this.#T=void 0,this.#E=null,clearTimeout(this.#O),this.#j=!1,this.#M=null,this.#N=null,this.#P=Promise.resolve(),this.#F.clear(),this.#I.clear(),this.#L=null,this.#R=!1,this.#z.clear(),this.#B.clear(),this.#V?.then(e=>e?.close()),this.#V=null,this.#H.clear(),this.#W.clear(),this.#U=null,this.#b=!1,this.#_=0,this.#v=0,clearTimeout(this.#y),this.#o=[],this.#s=0,this.#a&&=(this.#a.onaudioprocess=null,this.#a.disconnect(),null),this.#i&&=(this.#i.disconnect(),null),this.#r&&=(this.#r.getTracks().forEach(e=>e.stop()),null),this.#t&&=(this.#t.close().catch(()=>{}),null),this.#c&&=(this.#c.destroy(),null),this.#e){this.#f=!0;try{this.#e.close(1e3,`client ended call`)}catch{}this.#e=null}}onResult(e){this.#G.push(e)}onError(e){this.#K.push(e)}onStatusChange(e){this.#q.push(e)}onTranscript(e){this.#J.push(e)}onMetrics(e){this.#Y.push(e)}#be(e){this.#q.forEach(t=>t(e))}#xe(e){this.#K.forEach(t=>t(e))}#Se(e,t,n,r){this.#J.forEach(i=>i(e,t,n,r))}#Ce(e){this.#Y.forEach(t=>t(e))}},f=class{#e;#t;#n;#r;#i;#a;constructor(e={}){this.config=e,this.type=`browser`,this.#e=null,this.#t=[],this.#n=[],this.#r=[],this.#i=!1,this.#a=typeof window<`u`?window:void 0}async connect(){this.#r.forEach(e=>e(`connected`))}async startListening(){try{if(this.#i)throw Error(`Already listening`);if(!this.#a)throw Error(`Window object not available`);let e=this.#a.SpeechRecognition||this.#a.webkitSpeechRecognition;if(!e)throw Error(`Browser speech recognition not supported`);this.#e=new e,this.#e.lang=this.config?.language||`en-US`,this.#e.continuous=this.config?.continuous||!1,this.#e.interimResults=!0,this.#e.onresult=e=>{let t=Array.from(e.results).map(e=>e[0]).map(e=>e.transcript).join(``),n=e.results[e.results.length-1].isFinal;this.#t.forEach(e=>e({text:t,confidence:n?.8:.5,provider:`browser`})),n&&!this.config?.continuous&&this.stopListening()},this.#e.onerror=e=>{this.#n.forEach(t=>t(Error(e.error))),this.#r.forEach(e=>e(`error`))},this.#e.onstart=()=>{this.#i=!0,this.#r.forEach(e=>e(`listening`))},this.#e.onend=()=>{this.#i=!1,this.#r.forEach(e=>e(`idle`))},this.#e.start()}catch(e){throw this.#n.forEach(t=>t(e)),this.#r.forEach(e=>e(`error`)),e}}async stopListening(){this.#e&&=(this.#e.stop(),null),this.#i=!1,this.#r.forEach(e=>e(`idle`))}onResult(e){this.#t.push(e)}onError(e){this.#n.push(e)}onStatusChange(e){this.#r.push(e)}async disconnect(){await this.stopListening(),this.#r.forEach(e=>e(`disconnected`))}static isSupported(){return`SpeechRecognition`in window||`webkitSpeechRecognition`in window}};function p(e){switch(e.type){case`runtype`:if(!e.runtype)throw Error(`Runtype voice provider requires configuration`);return new d(e.runtype);case`browser`:if(!f.isSupported())throw Error(`Browser speech recognition not supported`);return new f(e.browser||{});case`custom`:{let t=e.custom;if(!t)throw Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t==`function`?t():t;if(!n||typeof n.startListening!=`function`)throw Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw Error(`Unknown voice provider type: ${e.type}`)}}function m(e){if(e?.type===`custom`&&e.custom)return p({type:`custom`,custom:e.custom});if(e?.type===`runtype`&&e.runtype)return p({type:`runtype`,runtype:e.runtype});if(f.isSupported())return p({type:`browser`,browser:e?.browser||{language:`en-US`}});throw Error(`No supported voice providers available`)}function h(e){try{return m(e),!0}catch{return!1}}const g=e=>e.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,``);var _=class{constructor(e){this.host=e,this.turns=/* @__PURE__ */ new Map,this.latestId=null,this.cancelled=/* @__PURE__ */ new Set}apply(e,t,n,r,i,a){let o=this.host;t=t.trim();let s=this.turns.get(r);if(s||(s={},this.turns.set(r,s),this.latestId=r),e===`user`){s.userFinal=n;let e=s.userId?o.find(s.userId):void 0;if(e){let r=s.userStartMs===void 0&&i!==void 0;r&&(s.userStartMs=i),o.upsert({...e,content:t,voiceProcessing:!n,...r&&this.placeBefore(this.startedAfter(i))})}else{s.userStartMs=i;let e=s.assistantId?o.find(s.assistantId):void 0;s.userId=o.inject({role:`user`,content:t,streaming:!1,voiceProcessing:!n,voiceCaption:a,...this.placeBefore(this.startedAfter(i)??e)}).id}}else if(!this.cancelled.has(r)){s.assistantFinal=n;let e=s.assistantId?o.find(s.assistantId):void 0;if(e){let r=s.assistantStartMs===void 0&&i!==void 0;r&&(s.assistantStartMs=i),o.upsert({...e,content:t,streaming:!n,voiceProcessing:!n,...r&&this.placeBefore(this.startedAfter(i))})}else t&&(s.assistantStartMs=i,s.assistantId=o.inject({role:`assistant`,content:t,streaming:!n,voiceProcessing:!n,voiceCaption:a,...this.placeBefore(this.startedAfter(i))}).id);n&&s.assistantId&&o.markSpoken(s.assistantId)}this.sync()}claimUserTurn(e,t=[]){let n=t[t.length-1];for(let e of t)e!==n&&(this.turns.has(e)||this.turns.set(e,{}),this.turns.get(e).claimed=!0);let r;if(n){if(r=this.turns.get(n),r||(r={},this.turns.set(n,r)),r.claimed)return null;(!r.userId||!this.host.find(r.userId))&&(r.userFinal=!0,r.userId=this.host.inject({role:`user`,content:e.trim()}).id)}else{let t=g(e),n=[...this.turns.values()].reverse().flatMap(e=>{let t=e.userId&&!e.claimed?this.host.find(e.userId):void 0;return t?[{turn:e,text:g(t.content)}]:[]}).filter(({text:e})=>e&&t);r=(n.find(({text:e})=>e===t)??n.find(({text:e})=>e.startsWith(t)||t.startsWith(e)))?.turn}return r?(r.claimed=!0,r.userId):null}cancel(){let e=this.inFlight();if(e.length===0){let t=this.awaiting();if(!t)return;e=[t]}for(let t of e)this.cancelled.add(t);this.closeReplies(e),this.sync()}fail(e){let t=this.awaiting(),n=this.inFlight();if(!t&&n.length===0)return;for(let e of n)this.turns.get(e).assistantFinal=!0;this.closeReplies(n);let r=this.host.inject({role:`assistant`,content:e,streaming:!1,voiceProcessing:!1}),i=t?this.turns.get(t):void 0;i&&(i.assistantId=r.id,i.assistantFinal=!0),this.sync()}settle(){if(this.turns.size===0)return;let e=this.pending(),t=/* @__PURE__ */ new Set;for(let e of this.turns.values())e.userId&&t.add(e.userId),e.assistantId&&(t.add(e.assistantId),this.host.markSpoken(e.assistantId));this.turns.clear(),this.latestId=null,this.host.settle(t),e&&this.host.setStreaming(!1)}startedAfter(e){if(e===void 0)return;let t;for(let n of this.turns.values())for(let[r,i]of[[n.userId,n.userStartMs],[n.assistantId,n.assistantStartMs]])r&&i!==void 0&&i>e&&(!t||i<t.start)&&(t={start:i,id:r});return t&&this.host.find(t.id)}placeBefore(e){if(!e)return;let t=e.sequence??0,n=t-1;for(let r of this.turns.values())for(let i of[r.userId,r.assistantId]){let r=i?this.host.find(i):void 0,a=r?.sequence;r?.createdAt===e.createdAt&&a!==void 0&&a>n&&a<t&&(n=a)}return{createdAt:e.createdAt,sequence:(n+t)/2}}closeReplies(e){let t=/* @__PURE__ */ new Set;for(let n of e){let e=this.turns.get(n)?.assistantId;e&&(t.add(e),this.host.markSpoken(e))}t.size>0&&this.host.settle(t)}inFlight(){let e=[];for(let[t,n]of this.turns)n.assistantId&&!n.assistantFinal&&!this.cancelled.has(t)&&e.push(t);return e}awaiting(){let e=this.latestId;if(!e)return null;let t=this.turns.get(e);return t?.userFinal&&!t.assistantId&&!t.claimed&&!this.cancelled.has(e)?e:null}pending(){return this.awaiting()!==null||this.inFlight().length>0}sync(){this.host.setStreaming(this.pending())}};const v=/* @__PURE__ */ new Set(/* @__PURE__ */ `mr,mrs,ms,dr,prof,sr,jr,st,mt,vs,etc,approx,inc,ltd,co,corp,no,nos,fig,ft,dept,est,min,max,e.g,i.e,a.m,p.m,u.s,u.k`.split(`,`)),y=/([.!?]+|[,;:])(["'”’)\]*_]*)(\s+)|\n\s*/g;function b(e){let t=/(\S+)$/.exec(e)?.[1];if(!t)return!1;let n=t.replace(/^[("'“‘[*_]+/,``).toLowerCase();if(v.has(n)||/^[a-z](?:\.[a-z])*$/.test(n))return!0;if(/^\d+$/.test(t)){let n=e.length-t.length;return n===0||/\n\s*$/.test(e.slice(0,n))}return!1}function*x(e,t){let n=new RegExp(y.source,`g`);for(let r=n.exec(e);r;r=n.exec(e)){let n=r[1];if(!e.slice(0,r.index+(n?.length??0)).trim()||n!==void 0&&(/^[,;:]$/.test(n)&&!t||n===`.`&&b(e.slice(0,r.index))))continue;let i=r.index+r[0].length;i<e.length&&(yield i)}}function S(e,t){let n=e.slice(0,t),r=0;for(let e of n.matchAll(/\s+/g))n.slice(0,e.index).trim()&&(r=e.index+e[0].length);return r}function C(e){let t=0;for(let n of x(e.slice(0,220),!0))t=n;if(t)return t;let n=S(e,220);if(n)return n;let r=e.charCodeAt(219);return r>=55296&&r<=56319?219:220}var w=class{#e=``;#t=!0;push(e){return this.#e+=e,this.#n()}flush(){let e=this.#n(),t=this.#e;if(this.#e=``,t.trim()){for(let n=0;n<t.length;){let r=t.slice(n),i=r.length>220?C(r):r.length;e.push(r.slice(0,i)),n+=i}this.#t=!1}return e}idle(){let e=this.#e;if(!e.trim()||!/(?:[.!?…]["'”’)\]*_]*|\n)\s*$/.test(e))return[];this.#e=``,this.#t=!1;let t=[];for(let n=0;n<e.length;){let r=e.slice(n),i=r.length>220?C(r):r.length;t.push(r.slice(0,i)),n+=i}return t}#n(){let e=[];for(let t=this.#r();t>0;t=this.#r())e.push(this.#e.slice(0,t)),this.#e=this.#e.slice(t),this.#t=!1;return e}#r(){let e=this.#e;if(!e.trim())return 0;let t=x(e,this.#t).next().value??0;if(t&&t<=220)return t;let n=/[.!?]["'”’)\]*_]*$/.test(e);if(this.#t&&!n){let t=e.match(/\S+\s+/g)?.length??0;if(e.trim().length>=30||t>=6){let t=S(e,220);if(t)return t}}return e.length>220?C(e):0}};const T=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n+=1;return n},E=`no|nope|never ?mind|decline(?: it| that)?|cancel(?: it| that| this)?(?: (?:the|my|that|this) (?:[a-z]+ )?(?:order|request))?|don'?t (?:do|place) (?:it|that|the (?:[a-z]+ )?order)`,D=RegExp(`^(?:${E})(?: (?:${E}))?(?: thanks| thank you)?$`),O=e=>D.test(e.toLowerCase().replace(/[^a-z' ]+/g,` `).replace(/\s+/g,` `).trim()),k=()=>new Promise(e=>setTimeout(e,50)),A=(e,t)=>e.length>t?`${e.slice(0,t-1).trimEnd()}…`:e,j=e=>e.replace(/^webmcp:/,``).replace(/([a-z\d])([A-Z])/g,`$1 $2`).replace(/[_\-.]+/g,` `).trim().toLowerCase();function M(e,t=0){if(e==null||e===``)return``;if(typeof e!=`object`)return String(e);if(t>2)return``;if(Array.isArray(e))return e.map(e=>M(e,t+1)).filter(Boolean).join(`, `);let n=e,r=n.quantity??n.qty??n.count,i=n.name??n.item??n.product??n.title;return r!=null&&i!=null&&typeof i!=`object`?`${r} ${i}`:Object.entries(n).filter(([e])=>!e.startsWith(`_`)).map(([e,n])=>{let r=M(n,t+1);return r&&(t?`${j(e)} ${r}`:`${j(e)}: ${r}`)}).filter(Boolean).join(t?`, `:`; `)}function N(e){let t=e.length>1?`These actions need the user's approval in the chat before they happen:`:`This action needs the user's approval in the chat before it happens:`,n=1e3-t.length-119-2;return`${t}\n${e.map(t=>{let r=[j(t.toolName)];t.description&&r.push(`(${A(t.description.trim(),160)})`);let i=M(t.parameters);return i&&r.push(`with ${i}`),t.reason&&r.push(`because: ${A(t.reason.trim(),160)}`),A(`- ${r.join(` `)}`,Math.floor(n/e.length)-1)}).join(`
4
+ `)}function s(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===1380533830?new Uint8Array(e,44):new Uint8Array(e)}function c(e){let t=e.replace(/\/+$/,``);return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,`ws`):`${typeof window<`u`&&window.location?.protocol===`https:`?`wss:`:`ws:`}//${t}`}function l(e){return c(e).replace(/^ws/i,`http`)}function u(e){return typeof e!=`number`||!Number.isFinite(e)?3e4:Math.min(6e5,Math.max(3e4,Math.round(e)))}var d=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m;#h;#g;#_;#v;#y;#b;#x;#S;#C;#w;#T;#E;#D;#O;#k;#A;#j;#M;#N;#P;#F;#I;#L;#R;#z;#B;#V;#H;#U;#W;#G;#K;#q;#J;#Y;constructor(e){this.config=e,this.type=`runtype`,this.#e=null,this.#t=null,this.#n=[],this.#r=null,this.#i=null,this.#a=null,this.#o=[],this.#s=0,this.#c=null,this.#l=!1,this.#u=!1,this.#d=0,this.#f=!1,this.#p=-1/0,this.#m=null,this.#h=!1,this.#g=!1,this.#_=0,this.#v=0,this.#b=!1,this.bridge=null,this.#x=!1,this.#S=/* @__PURE__ */ new Set,this.#C=/* @__PURE__ */ new Map,this.#w=/* @__PURE__ */ new Set,this.#E=null,this.#D=null,this.#k=!1,this.#A=!1,this.#j=!1,this.#M=null,this.#N=null,this.#P=Promise.resolve(),this.#F=/* @__PURE__ */ new Set,this.#I=/* @__PURE__ */ new Set,this.#L=null,this.#R=!1,this.#z=/* @__PURE__ */ new Set,this.#B=/* @__PURE__ */ new Set,this.#V=null,this.#H=/* @__PURE__ */ new Set,this.#U=null,this.#W=/* @__PURE__ */ new Map,this.#G=[],this.#K=[],this.#q=[],this.#J=[],this.#Y=[]}async connect(){}setSessionBridge(e){this.bridge=e}prewarm(){if(this.#l||this.#m)return;let e=this.config?.agentId,t=this.config?.clientToken,n=this.config?.host;if(!e||!t||!n)return;let r=Date.now();if(!(r-this.#p<3e4)){this.#p=r;try{this.config?.prewarmMode===`attach`?this.#Z(n,e,t):this.#X(n,e,t)}catch{}}}#X(e,t,n){if(typeof fetch!=`function`)return;let r=`${l(e)}/v1/client/agents/${encodeURIComponent(t)}/voice/prewarm`;fetch(r,{method:`POST`,headers:{Authorization:`Bearer ${n}`},keepalive:!0}).catch(()=>{})}#Z(e,t,n){let r=new URLSearchParams,i=this.config?.attachIdleMs,a=u(i);i!==void 0&&r.set(`attachIdleMs`,String(a));let o=new WebSocket(this.#te(e,t,r),[`runtype.bearer`,`runtype.attach`,n]);o.binaryType=`arraybuffer`;let s=()=>{},c={ws:o,state:`connecting`,ready:new Promise(e=>{s=e}),settle:s,openedAt:0,idleTimer:void 0};this.#m=c,o.onopen=()=>{this.#m===c&&(c.state=o.protocol===`runtype.attach`?`attached`:`live`,c.openedAt=Date.now(),this.#Q(c,a),c.state===`attached`&&o.send(`{"type":"ping"}`),c.settle())},o.onmessage=e=>{if(this.#m!==c||typeof e.data!=`string`)return;let t;try{t=JSON.parse(e.data)}catch{return}t.type===`attached`&&typeof t.idleMs==`number`&&this.#Q(c,t.idleMs-(Date.now()-c.openedAt))},o.onerror=()=>{},o.onclose=()=>{this.#m===c&&this.#$()}}#Q(e,t){clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>{this.#m===e&&this.#$()},Math.max(0,t))}#$(){let e=this.#m;if(!e)return;this.#m=null,clearTimeout(e.idleTimer);let{ws:t}=e;if(t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null,e.settle(),t.readyState===WebSocket.CONNECTING||t.readyState===WebSocket.OPEN)try{t.close(1e3,`prewarm released`)}catch{}}async#ee(){let e=this.#m;if(!e)return null;if(e.state===`connecting`){let t;await Promise.race([e.ready,new Promise(e=>{t=setTimeout(e,5e3)})]),clearTimeout(t)}return this.#m===e?e.state===`connecting`||e.ws.readyState!==WebSocket.OPEN?(this.#$(),null):(this.#m=null,clearTimeout(e.idleTimer),{ws:e.ws,live:e.state===`live`}):null}#te(t,n,r){let i=`partial_transcript,context`;this.bridge&&this.config?.clientDelegation!==!1&&(i+=`,client_delegation,delegation_update,delegation_read_back,delegation_stream`,this.bridge.clientTools?.()&&(i+=`,client_tools,prior_tool_results`)),r&&(i=`attach,${i}`);let a=new URLSearchParams({voiceProtocol:`runtype-browser-v1`,clientVersion:`persona/${e}`,voiceCapabilities:`full-duplex-v1`,clientCapabilities:i});return r?.forEach((e,t)=>a.set(t,e)),`${c(t)}/ws/agents/${encodeURIComponent(n)}/voice?${a}`}async startListening(){if(this.#l)return;let e=this.#A;e||(this.#k=!1,this.#D=null),this.#A=!1;let r=this.config?.agentId,i=this.config?.clientToken,o=this.config?.host;if(!r)throw Error(`Runtype voice requires an agentId`);if(!i)throw Error(`Runtype voice requires a clientToken`);if(!o)throw Error(`Runtype voice requires a host (or widget apiUrl)`);let s=++this.#d;this.#f=!1,this.#l=!0;try{let c=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:n,channelCount:1,echoCancellation:!0}});if(s!==this.#d){c.getTracks().forEach(e=>e.stop());return}this.#r=c;let l=new(window.AudioContext||window.webkitAudioContext)({sampleRate:n});if(this.#t=l,l.state===`suspended`){if(await Promise.race([l.resume().catch(()=>{}),new Promise(t=>setTimeout(t,e?500:1e3))]),s!==this.#d)return;if(l.state!==`running`)throw Error(e?this.#D=`${a} Tap the mic to reconnect.`:`Audio blocked until a tap`)}let u=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new t(24e3);if(s!==this.#d){u.destroy(),c.getTracks().forEach(e=>e.stop()),l.close().catch(()=>{});return}this.#c=u,this.#he(),this.#ie(l,c,s);let d=await this.#ee();if(s!==this.#d){d?.ws.close(1e3,`client ended call`);return}if(d){let{ws:e}=d;this.#e=e,this.#ne(e,s),d.live||e.send(`{"type":"start"}`),this.#ae(e),this.#be(`listening`);return}let f=new WebSocket(this.#te(o,r),[`runtype.bearer`,i]);f.binaryType=`arraybuffer`,this.#e=f,f.onopen=()=>{s===this.#d&&(this.#ae(f),this.#be(`listening`))},this.#ne(f,s)}catch(e){throw this.#ye(),this.#xe(e),this.#be(`error`),e}}#ne(e,t){e.onmessage=e=>this.#oe(e,t),e.onerror=()=>{t!==this.#d||this.#E||(this.#xe(/* @__PURE__ */ Error(`Voice connection failed`)),this.#be(`error`),this.#ye())},e.onclose=e=>{if(this.#f){this.#f=!1;return}if(t!==this.#d)return;let n=this.#E??(e.code===4408?{reason:`idle_timeout`}:null);if(n)this.#re(n.reason,n.message);else{if(e.code!==1e3){let t=e.code?` (code ${e.code})`:``;this.#xe(/* @__PURE__ */ Error(`Voice connection closed${t}`)),this.#be(`error`)}else this.#be(`idle`);this.#ye()}}}#re(e,t){let n=i.includes(e)&&!this.#k;if(this.#ye(),n)this.#k=!0,this.#l=!0,this.#D=e===`provider_error`?`${a} Reconnecting…`:`Reconnecting…`,this.#O=setTimeout(()=>{this.#l=!1,this.#A=!0,this.startListening().catch(()=>{})},1e3+Math.random()*1e3),this.#be(`idle`);else{if(i.includes(e))return this.#D=a,this.#xe(/* @__PURE__ */ Error(a)),this.#be(`error`);if(e===`error`)return this.#be(`error`);this.#D=e===`quota`&&t||r.get(e)||null,this.#be(`idle`)}}takeNotice(){let e=this.#D;return this.#D=null,e}getDisclosure(){let e=this.config?.disclosureText;return this.#l&&this.#h&&e!==!1?e||`You're talking to an AI assistant. Voice is processed by OpenAI.`:null}async stopListening(){this.#ye(),this.#be(`idle`)}async disconnect(){this.#ye(),this.#be(`disconnected`),this.#G=[],this.#K=[],this.#q=[],this.#J=[],this.#Y=[]}stopPlayback(){this.#ve();let e=this.#e;e&&e.readyState===WebSocket.OPEN&&(this.#h&&(this.#_=Date.now()+2e3,e.send(`{"type":"cancel"}`)),this.#be(`listening`))}getInterruptionMode(){return`barge-in`}isBargeInActive(){return this.#l}onLevel(e){this.#n.push(e)}async deactivateBargeIn(){this.#ye(),this.#be(`idle`)}#ie(e,t,n){let r=e.createMediaStreamSource(t);this.#i=r;let i=e.createScriptProcessor(4096,1,1);this.#a=i,i.onaudioprocess=e=>{if(n!==this.#d)return;let t=this.#e,r=t?.readyState===WebSocket.OPEN;if(t&&!r&&t.readyState!==WebSocket.CONNECTING)return;let i=e.inputBuffer.getChannelData(0),a=new Int16Array(i.length),o=0;for(let e=0;e<i.length;e++){let t=Math.max(-1,Math.min(1,i[e]));o+=t*t,a[e]=t<0?t*32768:t*32767}if(t&&r)this.#ae(t),t.send(a.buffer);else for(this.#o.push(a.buffer),this.#s+=a.byteLength;this.#s>256e3;)this.#s-=this.#o.shift().byteLength;if(this.#n.length>0){let e=Math.sqrt(o/i.length),t=Math.max(0,Math.min(1,e*4));for(let e of this.#n)e(t)}},r.connect(i),i.connect(e.destination)}#ae(e){for(let t of this.#o)e.send(t);this.#o=[],this.#s=0}#oe(e,t){if(t!==this.#d)return;if(e.data instanceof ArrayBuffer){this.#pe(e.data,t);return}let n;try{n=JSON.parse(e.data)}catch{return}switch(n.type){case`session_config`:n.speechMode&&(this.#h=n.speechMode===`speech_to_speech`,this.#c?.setContinuousMode?.(this.#h)),Array.isArray(n.capabilities)&&(this.#S=new Set(n.capabilities)),typeof n.callId==`string`&&(this.#T=n.callId),this.#x=this.#h&&this.#S.has(`client_delegation`)&&!!this.bridge,this.#h&&!this.#u&&this.#be(`listening`),this.#S.has(`context`)&&!this.#j&&(this.#j=!0,this.#M=this.#se()),this.#x&&this.#S.has(`client_tools`)&&!this.#V&&(this.#V=this.bridge.clientTools?.()?.open({send:e=>{let n=this.#e;return t!==this.#d||n?.readyState!==WebSocket.OPEN?!1:(n.send(JSON.stringify(e)),!0)},cancelled:e=>this.#w.has(e)}).catch(()=>null)??null);break;case`client_tool_call`:{let e=String(n.delegationId);this.#V&&!this.#W.has(e)&&(this.#W.set(e,this.#U),this.#F.add(e)),this.#V?.then(e=>e?.call(n));break}case`transcript_update`:{let e=n.role===`assistant`?`assistant`:`user`,r=n.utteranceId??n.turnId;if(!r||e===`assistant`&&this.#me())break;let i=String(r);if(e===`user`)n.final===!0&&(this.#ce(t),this.#U={id:i,text:String(n.text??``)}),this.#R=!1;else{if(this.#S.has(`delegation_read_back`)){let e=n.delegationId;(typeof e==`string`&&this.#F.has(e)&&!this.#z.has(i)||this.#R&&!this.#z.has(i))&&(this.#B.add(i),this.#R=!1)}else this.#R&&!this.#z.has(i)&&(this.#B.add(i),this.#R=!1);if(this.#z.add(i),this.#B.has(i))break}this.#Se(e,n.text??``,n.final===!0,{turnId:i,...typeof n.startMs==`number`&&{startMs:n.startMs},...typeof n.endMs==`number`&&{endMs:n.endMs},...this.#x&&{caption:!0}});break}case`delegation_started`:case`delegation_completed`:{let e=String(n.delegationId??n.turnId);if(n.type===`delegation_started`){this.#ce(t),this.#H.add(e),this.#F.delete(e),this.#W.delete(e)&&this.#V?.then(t=>t?.abort(e));let r=n.input;this.#x&&r&&this.#fe(e,{delegationId:e,userText:String(r.text??``),userUtteranceIds:Array.isArray(r.userUtteranceIds)?r.userUtteranceIds.filter(e=>typeof e==`string`):[],messages:Array.isArray(r.messages)?r.messages:[],priorToolResults:r.priorToolResults},t)}else if(n.route===`direct`&&this.#V&&!this.#H.has(e)){let t=this.#W.get(e)??this.#U;this.#W.delete(e),this.#H.add(e),this.#F.add(e),this.bridge?.recordDirectTurn?.({delegationId:e,userText:t?.text??``,userUtteranceIds:t?[t.id]:[],assistantText:typeof n.text==`string`?n.text:``})}n.type===`delegation_completed`&&n.speak!==!1&&this.#F.has(e)&&!this.#I.delete(e)&&!this.#S.has(`delegation_read_back`)&&this.#ue(e),this.#g=n.type===`delegation_started`,!this.#u&&!this.#me()&&this.#be(this.#g?`processing`:`listening`);break}case`delegation_progress`:{let e=String(n.delegationId);this.#F.has(e)&&!this.#I.has(e)&&!this.#w.has(e)&&(this.#I.add(e),this.#ue(e));break}case`delegation_cancelled`:this.#de(String(n.delegationId),n.reason!==`session_ending`&&n.reason!==`provider_cancelled`);break;case`warning`:console.warn(`[Persona voice] ${n.code}: ${n.message??``}`,this.#T??``),n.delegationId&&(n.code===`UNKNOWN_DELEGATION`||n.code===`LATE_RESULT_LIMIT`)&&this.#de(String(n.delegationId));break;case`audio_clear`:this.#ve(),this.#_=0,this.#be(`listening`);break;case`transcript_interim`:this.#be(`listening`),this.#Se(`user`,n.text??``,!1);break;case`transcript_final`:{let e=n.role===`assistant`?`assistant`:`user`;this.#be(e===`user`?`processing`:`speaking`),this.#Se(e,n.text??``,!0);break}case`audio_end`:this.#c?this.#c.markStreamEnd():(this.#u=!1,this.#be(`listening`));break;case`metrics`:this.#Ce({llmMs:n.llm_ms,ttsMs:n.tts_ms,firstAudioMs:n.first_audio_ms,totalMs:n.total_ms});break;case`error`:this.#xe(Error(n.error||`Voice error`)),this.#be(`error`);break;case`session_end`:this.#E={reason:String(n.reason),...typeof n.message==`string`&&{message:n.message}}}}async#se(){let e=this.bridge?.getHistory()??[],t=``;try{let e=this.config?.callContext;t=String((typeof e==`function`?await e():e)??``)}catch{}return o(e,t)}#ce(e){let t=this.#M;if(!t)return;this.#M=null;let n=!1,r=t.then(t=>{let r=this.#e;!n&&t&&e===this.#d&&r?.readyState===WebSocket.OPEN&&r.send(JSON.stringify({type:`context`,text:t}))});this.#N={done:r,drop:()=>n=!0}}async#le(){let e=this.#N;if(!e)return;let t,n=await Promise.race([e.done.then(()=>!1),new Promise(e=>{t=setTimeout(()=>e(!0),2e3)})]);clearTimeout(t),n&&e.drop()}#ue(e){this.#R=!0,this.#L=e}#de(e,t=!1){this.#w.add(e),this.#L===e&&(this.#R=!1),this.#I.delete(e),this.#H.has(e)||this.#F.delete(e),this.#V?.then(t=>t?.abort(e)),this.bridge?.dropDelegation?.(e,t),this.#C.get(e)?.abort()}#fe(e,t,n){let r=this.bridge,i=({type:t,...r})=>{let i=this.#e;return n!==this.#d||i?.readyState!==WebSocket.OPEN||this.#w.has(e)?!1:(i.send(JSON.stringify({type:t,delegationId:e,...r})),!0)},a=(e,t,n,r=0)=>i({type:e,status:t,text:n,...r>0&&{streamedChars:r}});this.#P=this.#P.then(async()=>{if(n!==this.#d||this.#w.has(e))return;let o=null,s=this.#S.has(`delegation_stream`)&&this.#S.has(`delegation_read_back`),c=t=>{o=(o??this.#le()).then(()=>{i({type:`delegation_delta`,text:t})&&this.#F.add(e)})},l=await r.runDelegatedTurn(s?{...t,stream:c}:t).catch(()=>({status:`failed`,text:``}));await this.#le(),await o;let u=s?l.streamedChars??0:0,d=!!l.followUp,f=d&&this.#S.has(`delegation_update`);if(!a(f?`delegation_update`:`delegation_result`,d&&!f?`completed`:l.status,l.text,u)||(l.status!==`failed`&&l.inChat!==!1&&this.#F.add(e),!l.followUp))return;let p=new AbortController;this.#C.set(e,p),l.followUp({signal:p.signal,approvalTimeoutMs:this.config?.approvalTimeoutMs&&Math.min(this.config.approvalTimeoutMs,54e4),readBack:f,onUpdate:e=>a(`delegation_update`,`pending_approval`,e)}).then(t=>{this.#C.delete(e),f&&t&&!p.signal.aborted&&a(`delegation_result`,t.status,t.text)})})}#pe(e,t){if(t!==this.#d||!this.#c||this.#me())return;let n=s(e);n.length!==0&&(this.#u||(this.#u=!0,this.#be(`speaking`)),this.#he(),this.#c.enqueue(n),this.#h&&this.#ge(n.length))}#me(){return Date.now()<this.#_}#he(){if(this.#b||!this.#c)return;this.#b=!0;let e=this.#d;this.#c.onFinished(()=>{e===this.#d&&(this.#b=!1,this.#_e())})}#ge(e){let t=Date.now();this.#v=Math.max(t,this.#v)+e/48,clearTimeout(this.#y),this.#y=setTimeout(()=>this.#_e(),this.#v-t+300)}#_e(){this.#u=!1,this.#v=0,this.#e&&this.#e.readyState===WebSocket.OPEN&&this.#be(this.#g?`processing`:`listening`)}#ve(){this.#c?.flush(),this.#b=!1,this.#he(),this.#u=!1,this.#v=0,clearTimeout(this.#y)}#ye(){this.#d+=1,this.#l=!1,this.#u=!1,this.#$(),this.#h=!1,this.#g=!1,this.#x=!1,this.#S=/* @__PURE__ */ new Set;for(let e of this.#C.values())e.abort();if(this.#C.clear(),this.#w.clear(),this.#T=void 0,this.#E=null,clearTimeout(this.#O),this.#j=!1,this.#M=null,this.#N=null,this.#P=Promise.resolve(),this.#F.clear(),this.#I.clear(),this.#L=null,this.#R=!1,this.#z.clear(),this.#B.clear(),this.#V?.then(e=>e?.close()),this.#V=null,this.#H.clear(),this.#W.clear(),this.#U=null,this.#b=!1,this.#_=0,this.#v=0,clearTimeout(this.#y),this.#o=[],this.#s=0,this.#a&&=(this.#a.onaudioprocess=null,this.#a.disconnect(),null),this.#i&&=(this.#i.disconnect(),null),this.#r&&=(this.#r.getTracks().forEach(e=>e.stop()),null),this.#t&&=(this.#t.close().catch(()=>{}),null),this.#c&&=(this.#c.destroy(),null),this.#e){this.#f=!0;try{this.#e.close(1e3,`client ended call`)}catch{}this.#e=null}}onResult(e){this.#G.push(e)}onError(e){this.#K.push(e)}onStatusChange(e){this.#q.push(e)}onTranscript(e){this.#J.push(e)}onMetrics(e){this.#Y.push(e)}#be(e){this.#q.forEach(t=>t(e))}#xe(e){this.#K.forEach(t=>t(e))}#Se(e,t,n,r){this.#J.forEach(i=>i(e,t,n,r))}#Ce(e){this.#Y.forEach(t=>t(e))}},f=class{#e;#t;#n;#r;#i;#a;constructor(e={}){this.config=e,this.type=`browser`,this.#e=null,this.#t=[],this.#n=[],this.#r=[],this.#i=!1,this.#a=typeof window<`u`?window:void 0}async connect(){this.#r.forEach(e=>e(`connected`))}async startListening(){try{if(this.#i)throw Error(`Already listening`);if(!this.#a)throw Error(`Window object not available`);let e=this.#a.SpeechRecognition||this.#a.webkitSpeechRecognition;if(!e)throw Error(`Browser speech recognition not supported`);this.#e=new e,this.#e.lang=this.config?.language||`en-US`,this.#e.continuous=this.config?.continuous||!1,this.#e.interimResults=!0,this.#e.onresult=e=>{let t=Array.from(e.results).map(e=>e[0]).map(e=>e.transcript).join(``),n=e.results[e.results.length-1].isFinal;this.#t.forEach(e=>e({text:t,confidence:n?.8:.5,provider:`browser`})),n&&!this.config?.continuous&&this.stopListening()},this.#e.onerror=e=>{this.#n.forEach(t=>t(Error(e.error))),this.#r.forEach(e=>e(`error`))},this.#e.onstart=()=>{this.#i=!0,this.#r.forEach(e=>e(`listening`))},this.#e.onend=()=>{this.#i=!1,this.#r.forEach(e=>e(`idle`))},this.#e.start()}catch(e){throw this.#n.forEach(t=>t(e)),this.#r.forEach(e=>e(`error`)),e}}async stopListening(){this.#e&&=(this.#e.stop(),null),this.#i=!1,this.#r.forEach(e=>e(`idle`))}onResult(e){this.#t.push(e)}onError(e){this.#n.push(e)}onStatusChange(e){this.#r.push(e)}async disconnect(){await this.stopListening(),this.#r.forEach(e=>e(`disconnected`))}static isSupported(){return`SpeechRecognition`in window||`webkitSpeechRecognition`in window}};function p(e){switch(e.type){case`runtype`:if(!e.runtype)throw Error(`Runtype voice provider requires configuration`);return new d(e.runtype);case`browser`:if(!f.isSupported())throw Error(`Browser speech recognition not supported`);return new f(e.browser||{});case`custom`:{let t=e.custom;if(!t)throw Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t==`function`?t():t;if(!n||typeof n.startListening!=`function`)throw Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw Error(`Unknown voice provider type: ${e.type}`)}}function m(e){if(e?.type===`custom`&&e.custom)return p({type:`custom`,custom:e.custom});if(e?.type===`runtype`&&e.runtype)return p({type:`runtype`,runtype:e.runtype});if(f.isSupported())return p({type:`browser`,browser:e?.browser||{language:`en-US`}});throw Error(`No supported voice providers available`)}function h(e){try{return m(e),!0}catch{return!1}}const g=e=>e.toLowerCase().replace(/[^\p{L}\p{N}]+/gu,``);var _=class{constructor(e){this.host=e,this.turns=/* @__PURE__ */ new Map,this.latestId=null,this.cancelled=/* @__PURE__ */ new Set}apply(e,t,n,r,i,a){let o=this.host;t=t.trim();let s=this.turns.get(r);if(s||(s={},this.turns.set(r,s),this.latestId=r),e===`user`){s.userFinal=n;let e=s.userId?o.find(s.userId):void 0;if(e){let r=s.userStartMs===void 0&&i!==void 0;r&&(s.userStartMs=i),o.upsert({...e,content:t,voiceProcessing:!n,...r&&this.placeBefore(this.startedAfter(i))})}else{s.userStartMs=i;let e=s.assistantId?o.find(s.assistantId):void 0;s.userId=o.inject({role:`user`,content:t,streaming:!1,voiceProcessing:!n,voiceCaption:a,...this.placeBefore(this.startedAfter(i)??e)}).id}}else if(!this.cancelled.has(r)){s.assistantFinal=n;let e=s.assistantId?o.find(s.assistantId):void 0;if(e){let r=s.assistantStartMs===void 0&&i!==void 0;r&&(s.assistantStartMs=i),o.upsert({...e,content:t,streaming:!n,voiceProcessing:!n,...r&&this.placeBefore(this.startedAfter(i))})}else t&&(s.assistantStartMs=i,s.assistantId=o.inject({role:`assistant`,content:t,streaming:!n,voiceProcessing:!n,voiceCaption:a,...this.placeBefore(this.startedAfter(i))}).id);n&&s.assistantId&&o.markSpoken(s.assistantId)}this.sync()}claimUserTurn(e,t=[]){let n=t[t.length-1];for(let e of t)e!==n&&(this.turns.has(e)||this.turns.set(e,{}),this.turns.get(e).claimed=!0);let r;if(n){if(r=this.turns.get(n),r||(r={},this.turns.set(n,r)),r.claimed)return null;r.userId&&this.host.find(r.userId)||(r.userFinal=!0,r.userId=this.host.inject({role:`user`,content:e.trim()}).id)}else{let t=g(e),n=[...this.turns.values()].reverse().flatMap(e=>{let t=e.userId&&!e.claimed?this.host.find(e.userId):void 0;return t?[{turn:e,text:g(t.content)}]:[]}).filter(({text:e})=>e&&t);r=(n.find(({text:e})=>e===t)??n.find(({text:e})=>e.startsWith(t)||t.startsWith(e)))?.turn}return r?(r.claimed=!0,r.userId):null}cancel(){let e=this.inFlight();if(e.length===0){let t=this.awaiting();if(!t)return;e=[t]}for(let t of e)this.cancelled.add(t);this.closeReplies(e),this.sync()}fail(e){let t=this.awaiting(),n=this.inFlight();if(!t&&n.length===0)return;for(let e of n)this.turns.get(e).assistantFinal=!0;this.closeReplies(n);let r=this.host.inject({role:`assistant`,content:e,streaming:!1,voiceProcessing:!1}),i=t?this.turns.get(t):void 0;i&&(i.assistantId=r.id,i.assistantFinal=!0),this.sync()}settle(){if(this.turns.size===0)return;let e=this.pending(),t=/* @__PURE__ */ new Set;for(let e of this.turns.values())e.userId&&t.add(e.userId),e.assistantId&&(t.add(e.assistantId),this.host.markSpoken(e.assistantId));this.turns.clear(),this.latestId=null,this.host.settle(t),e&&this.host.setStreaming(!1)}startedAfter(e){if(e===void 0)return;let t;for(let n of this.turns.values())for(let[r,i]of[[n.userId,n.userStartMs],[n.assistantId,n.assistantStartMs]])r&&i!==void 0&&i>e&&(!t||i<t.start)&&(t={start:i,id:r});return t&&this.host.find(t.id)}placeBefore(e){if(!e)return;let t=e.sequence??0,n=t-1;for(let r of this.turns.values())for(let i of[r.userId,r.assistantId]){let r=i?this.host.find(i):void 0,a=r?.sequence;r?.createdAt===e.createdAt&&a!==void 0&&a>n&&a<t&&(n=a)}return{createdAt:e.createdAt,sequence:(n+t)/2}}closeReplies(e){let t=/* @__PURE__ */ new Set;for(let n of e){let e=this.turns.get(n)?.assistantId;e&&(t.add(e),this.host.markSpoken(e))}t.size>0&&this.host.settle(t)}inFlight(){let e=[];for(let[t,n]of this.turns)n.assistantId&&!n.assistantFinal&&!this.cancelled.has(t)&&e.push(t);return e}awaiting(){let e=this.latestId;if(!e)return null;let t=this.turns.get(e);return t?.userFinal&&!t.assistantId&&!t.claimed&&!this.cancelled.has(e)?e:null}pending(){return this.awaiting()!==null||this.inFlight().length>0}sync(){this.host.setStreaming(this.pending())}};const v=/* @__PURE__ */ new Set(/* @__PURE__ */ `mr,mrs,ms,dr,prof,sr,jr,st,mt,vs,etc,approx,inc,ltd,co,corp,no,nos,fig,ft,dept,est,min,max,e.g,i.e,a.m,p.m,u.s,u.k`.split(`,`)),y=/([.!?]+|[,;:])(["'”’)\]*_]*)(\s+)|\n\s*/g;function b(e){let t=/(\S+)$/.exec(e)?.[1];if(!t)return!1;let n=t.replace(/^[("'“‘[*_]+/,``).toLowerCase();if(v.has(n)||/^[a-z](?:\.[a-z])*$/.test(n))return!0;if(/^\d+$/.test(t)){let n=e.length-t.length;return n===0||/\n\s*$/.test(e.slice(0,n))}return!1}function*x(e,t){let n=new RegExp(y.source,`g`);for(let r=n.exec(e);r;r=n.exec(e)){let n=r[1];if(!e.slice(0,r.index+(n?.length??0)).trim()||n!==void 0&&(/^[,;:]$/.test(n)&&!t||n===`.`&&b(e.slice(0,r.index))))continue;let i=r.index+r[0].length;i<e.length&&(yield i)}}function S(e,t){let n=e.slice(0,t),r=0;for(let e of n.matchAll(/\s+/g))n.slice(0,e.index).trim()&&(r=e.index+e[0].length);return r}function C(e){let t=0;for(let n of x(e.slice(0,220),!0))t=n;if(t)return t;let n=S(e,220);if(n)return n;let r=e.charCodeAt(219);return r>=55296&&r<=56319?219:220}var w=class{#e=``;#t=!0;push(e){return this.#e+=e,this.#n()}flush(){let e=this.#n(),t=this.#e;if(this.#e=``,t.trim()){for(let n=0;n<t.length;){let r=t.slice(n),i=r.length>220?C(r):r.length;e.push(r.slice(0,i)),n+=i}this.#t=!1}return e}idle(){let e=this.#e;if(!e.trim()||!/(?:[.!?…]["'”’)\]*_]*|\n)\s*$/.test(e))return[];this.#e=``,this.#t=!1;let t=[];for(let n=0;n<e.length;){let r=e.slice(n),i=r.length>220?C(r):r.length;t.push(r.slice(0,i)),n+=i}return t}#n(){let e=[];for(let t=this.#r();t>0;t=this.#r())e.push(this.#e.slice(0,t)),this.#e=this.#e.slice(t),this.#t=!1;return e}#r(){let e=this.#e;if(!e.trim())return 0;let t=x(e,this.#t).next().value??0;if(t&&t<=220)return t;let n=/[.!?]["'”’)\]*_]*$/.test(e);if(this.#t&&!n){let t=e.match(/\S+\s+/g)?.length??0;if(e.trim().length>=30||t>=6){let t=S(e,220);if(t)return t}}return e.length>220?C(e):0}};const T=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n+=1;return n},E=`no|nope|never ?mind|decline(?: it| that)?|cancel(?: it| that| this)?(?: (?:the|my|that|this) (?:[a-z]+ )?(?:order|request))?|don'?t (?:do|place) (?:it|that|the (?:[a-z]+ )?order)`,D=RegExp(`^(?:${E})(?: (?:${E}))?(?: thanks| thank you)?$`),O=e=>D.test(e.toLowerCase().replace(/[^a-z' ]+/g,` `).replace(/\s+/g,` `).trim()),k=()=>new Promise(e=>setTimeout(e,50)),A=(e,t)=>e.length>t?`${e.slice(0,t-1).trimEnd()}…`:e,j=e=>e.replace(/^webmcp:/,``).replace(/([a-z\d])([A-Z])/g,`$1 $2`).replace(/[_\-.]+/g,` `).trim().toLowerCase();function M(e,t=0){if(e==null||e===``)return``;if(typeof e!=`object`)return String(e);if(t>2)return``;if(Array.isArray(e))return e.map(e=>M(e,t+1)).filter(Boolean).join(`, `);let n=e,r=n.quantity??n.qty??n.count,i=n.name??n.item??n.product??n.title;return r!=null&&i!=null&&typeof i!=`object`?`${r} ${i}`:Object.entries(n).filter(([e])=>!e.startsWith(`_`)).map(([e,n])=>{let r=M(n,t+1);return r&&(t?`${j(e)} ${r}`:`${j(e)}: ${r}`)}).filter(Boolean).join(t?`, `:`; `)}function N(e){let t=e.length>1?`These actions need the user's approval in the chat before they happen:`:`This action needs the user's approval in the chat before it happens:`,n=1e3-t.length-119-2;return`${t}\n${e.map(t=>{let r=[j(t.toolName)];t.description&&r.push(`(${A(t.description.trim(),160)})`);let i=M(t.parameters);return i&&r.push(`with ${i}`),t.reason&&r.push(`because: ${A(t.reason.trim(),160)}`),A(`- ${r.join(` `)}`,Math.floor(n/e.length)-1)}).join(`
5
5
  `)}\n\nBriefly tell the user what you're about to do and ask them to approve or decline it in the chat. Don't claim it's done.`}const P=e=>e.variant===`approval`&&e.approval?.status===`pending`;function F(e){let t=null,n=null,r=()=>e.track(t??n),i=[],a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map,s=(e,t)=>{a.set(e,[...a.get(e)??[],t]),a.size>32&&a.delete(a.keys().next().value)},c=t=>e.messages().find(e=>e.id===t),l=e=>e.approvals.filter(e=>c(e)?.approval?.status===`pending`),u=e=>j(c(e)?.approval?.toolName??``),d=(t,n,r)=>{t.outcome={status:n,text:r};for(let n of l(t))e.decide(n)},f=t=>t.flatMap(t=>e.messages().find(e=>e.id===t)??[]).filter(e=>!e.variant&&e.content.trim()).map(e=>e.content.trim()).join(`
6
6
 
7
7
  `),p=async t=>{do await k();while(e.busy()&&!(t&&(e.parked()||t.failed)))};return{clientTools:e.clientTools,recordDirectTurn:e.recordDirect,getHistory:()=>{let t=e.messages().filter(e=>(e.role===`user`||e.role===`assistant`)&&!e.variant&&!e.voiceProcessing&&!e.streaming&&e.content),n=!1,r=[];for(let e=t.length-1;e>=0;--e){let i=t[e];if(i.role===`user`)n=!1;else if(!i.voiceCaption)n=!0;else if(n)continue;r.unshift({role:i.role,content:i.content})}return r},dropDelegation(t,n){o.set(t,!!n),o.size>32&&o.delete(o.keys().next().value);let r=n&&i.find(e=>e.delegationId===t);r&&!r.outcome&&d(r,`timeout`,``);for(let n of a.get(t)??[])n.stopStream?.(),n.dropped=!0,n.ids.length&&e.unspoken(n.ids)},async runDelegatedTurn({delegationId:m,userText:h,userUtteranceIds:g,stream:_,priorToolResults:v}){let y=i.filter(e=>l(e).length),b=y.flatMap(l);if(b.length===1&&O(h)){let e=u(b[0]);return d(y[0],`denied`,``),{status:`denied`,text:`Okay, I cancelled the ${e} request. Nothing was done.`,inChat:!1}}let x=e.parked()&&e.messages().every(e=>!P(e)||b.includes(e.id));e.busy()&&!x&&await p();let S=new Set(e.messages().map(e=>e.id)),C=()=>e.messages().filter(e=>!S.has(e.id)&&e.variant===`approval`),E={ids:[],failed:!1},D=_?new w:null,A=``,M=``,F=!1,I=e=>{for(let t of e)M+=t,_(t)},L;D&&(E.onUpdate=()=>{if(F)return;let e=f(E.ids);if(!e.startsWith(A)){F=!0,clearTimeout(L);return}if(e.length===A.length)return;let t=e.slice(A.length);A=e,I(D.push(t)),clearTimeout(L),L=setTimeout(()=>{F||I(D.idle())},200)},E.stopStream=()=>{clearTimeout(L),F=!0,E.onUpdate=void 0}),s(m,E),t=E,r();try{await e.send(h,{userMessageId:e.claim(h,g),priorToolResults:v}),await p(E)}catch{E.failed=!0}finally{t=null,r()}D&&(E.onUpdate?.(),clearTimeout(L),F||I(D.flush()),E.onUpdate=void 0,E.stopStream=void 0);let R=e=>{let t=T(M,e);return t>0?{streamedChars:t}:{}},z=E.ids.flatMap(t=>e.messages().find(e=>e.id===t)??[]),B=f(E.ids),V=E.failed?[]:C().filter(P),H=new Set(V.map(e=>j(e.approval.toolName)));for(let t of y){if(t.outcome)continue;for(let n of l(t).filter(e=>H.has(u(e))))t.replaced.add(n),e.decide(n);let n=u(t.approvals[0]);(t.approvals.every(e=>t.replaced.has(e))||x&&t.approvals.every(e=>c(e)?.approval?.status===`denied`))&&(t.outcome={status:`cancelled`,text:`The earlier ${n} request was replaced by the new one; it was not done.`})}if(V.length){let c=new Set(V.map(e=>e.id)),p={delegationId:m,approvals:[...c],at:Date.now(),replaced:/* @__PURE__ */ new Set};return i.push(p),o.get(m)&&d(p,`timeout`,``),B=`${B}\n\n${N(V.map(e=>e.approval))}`.trim(),{status:`pending_approval`,text:B,...R(B),followUp:async({signal:o,approvalTimeoutMs:h=3e5,readBack:g=!0,onUpdate:_})=>{let v={ids:[],failed:!1};a.delete(m),s(m,v);let y=()=>C().filter(e=>c.has(e.id)||v.ids.includes(e.id)),b=()=>C().filter(e=>P(e)&&!c.has(e.id)&&!i.some(t=>t.approvals.includes(e.id))&&(v.ids.includes(e.id)||e.approval?.toolType===`webmcp`&&n===v)),x=()=>{n=v,r()};g&&x();try{for(;!o.aborted&&!p.outcome&&(t||e.busy()||y().some(P));){g&&n!==v&&!l(p).length&&x();let t=b();if(t.length){for(let e of t)c.add(e.id),p.approvals.push(e.id);p.at=Date.now(),_?.(N(t.map(e=>e.approval)))}if(Date.now()-p.at>=h&&l(p).length&&(!e.busy()||e.parked())){d(p,`timeout`,`That ${u(p.approvals[0])} request expired, so nothing was done.`);break}await k()}}finally{n===v&&(n=null,r()),i.splice(i.indexOf(p),1)}if(o.aborted)return null;if(p.outcome)return p.outcome;if(v.failed)return{status:`failed`,text:`The ${u(p.approvals[0])} request didn't complete.`};let S=y(),w=e=>S.filter(e).map(e=>j(e.approval.toolName)).join(`, `),T=S.some(e=>e.approval?.status===`approved`),E=w(e=>e.approval?.status===`denied`&&!p.replaced.has(e.id)),D=w(e=>p.replaced.has(e.id)),O=w(e=>e.approval?.status===`timeout`),A=[T?f(v.ids):``,E&&`The user declined the ${E} request in the chat, so ${T?`that part was not done`:`nothing was done`}.`,D&&`The earlier ${D} request was replaced by the new one; it was not done.`,O&&`The ${O} request timed out, so it was not done.`].filter(Boolean).join(`
@@ -1 +1 @@
1
- import{t as e}from"./chunk-CnxIZOzx.js";import{t}from"./chunk-D5BxWOFB.js";import{c as n,l as r,r as i,s as a}from"./chunk-CVMIncEY.js";import{Check as o,ChevronDown as s,ChevronRight as c,Clipboard as l,ClipboardCopy as u,Search as d,X as ee}from"lucide";function f(e,t){t&&t.split(/\s+/).forEach(t=>t&&e.classList.add(t))}const p={flow_:{bg:`var(--persona-event-badge-flow-bg, #dcfce7)`,text:`var(--persona-event-badge-flow-fg, #15803d)`},step_:{bg:`var(--persona-event-badge-step-bg, #f5f5f5)`,text:`var(--persona-event-badge-step-fg, #0a0a0a)`},reasoning_:{bg:`var(--persona-event-badge-reasoning-bg, #fef9c3)`,text:`var(--persona-event-badge-reasoning-fg, #a16207)`},tool_:{bg:`var(--persona-event-badge-tool-bg, #f3e8ff)`,text:`var(--persona-event-badge-tool-fg, #6b21a8)`},agent_:{bg:`var(--persona-event-badge-agent-bg, #ccfbf1)`,text:`var(--persona-event-badge-agent-fg, #115e59)`},error:{bg:`var(--persona-event-badge-error-bg, #fee2e2)`,text:`var(--persona-event-badge-error-fg, #b91c1c)`}};p.execution_error=p.error,p.execution_=p.flow_,p.turn_=p.agent_,p.text_=p.agent_;const m={bg:`var(--persona-event-badge-default-bg, #f3f4f6)`,text:`var(--persona-event-badge-default-fg, #4b5563)`},h=[`flowName`,`stepName`,`reasoningText`,`text`,`name`,`tool`,`toolName`];function g(e,t){if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith(`_`)&&e.startsWith(n))return t[n]}function te(e,t){return(t&&g(e,t))??g(e,p)??m}function _(e){return/^#[0-9a-fA-F]{6}$/.test(e)?`${e}50`:`color-mix(in srgb, ${e} 31%, transparent)`}function ne(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function v(e){let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}:${String(t.getSeconds()).padStart(2,`0`)}.${String(t.getMilliseconds()).padStart(3,`0`)}`}function y(e,t){try{let n=JSON.parse(e);if(typeof n!=`object`||!n)return null;for(let e of t){let t=e.split(`.`),r=n;for(let e of t)if(r&&typeof r==`object`&&r)r=r[e];else{r=void 0;break}if(typeof r==`string`&&r.trim())return r.trim()}}catch{}return null}function b(e){return navigator.clipboard?.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement(`textarea`);n.value=e,n.style.position=`fixed`,n.style.opacity=`0`,document.body.appendChild(n),n.select(),document.execCommand(`copy`),document.body.removeChild(n),t()})}function x(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function S(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?`-- tok/s`:`${e.tokensPerSecond.toFixed(1)} tok/s`}function C(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(` · `)}function w(e,n,r){let i,a;try{a=JSON.parse(e.payload),i=JSON.stringify(a,null,2)}catch{a=e.payload,i=e.payload}let o=n.find(e=>e.renderEventStreamPayload);if(o?.renderEventStreamPayload&&r){let t=o.renderEventStreamPayload({event:e,config:r,defaultRenderer:()=>s(),parsedPayload:a});if(t)return t}return s();function s(){let e=t(`div`,`persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]`),n=t(`pre`,`persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono`);return n.textContent=i,e.appendChild(n),e}}function T(n,r,i,a,u,d,ee,p){let m=u.has(n.id),g=t(`div`,`persona-border-b persona-border-persona-divider persona-text-xs`);f(g,a.classNames?.eventRow);let S=ee.find(e=>e.renderEventStreamRow);if(S?.renderEventStreamRow&&p){let e=S.renderEventStreamRow({event:n,index:r,config:p,defaultRenderer:()=>C(),isExpanded:m,onToggleExpand:()=>d(n.id)});if(e)return g.appendChild(e),g}return g.appendChild(C()),g;function C(){let u=t(`div`,``),d=t(`div`,`persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group`);d.setAttribute(`data-event-id`,n.id);let f=t(`span`,`persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center`),g=e(m?s:c,`14px`,`currentColor`,2);g&&f.appendChild(g);let S=t(`span`,`persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]`);S.textContent=(a.timestampFormat??`relative`)===`relative`?ne(n.timestamp,i):v(n.timestamp);let C=null;a.showSequenceNumbers!==!1&&(C=t(`span`,`persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right`),C.textContent=String(r+1));let T=te(n.type,a.badgeColors),E=t(`span`,`persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border`);E.style.backgroundColor=T.bg,E.style.color=T.text,E.style.borderColor=_(T.text),E.textContent=n.type;let D=a.descriptionFields??h,O=y(n.payload,D),k=null;O&&(k=t(`span`,`persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0`),k.textContent=O);let A=t(`div`,`persona-flex-1 persona-min-w-0`),j=t(`button`,`persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0`),M=e(l,`12px`,`currentColor`,1.5);return M&&j.appendChild(M),j.addEventListener(`click`,async t=>{t.stopPropagation(),await b(x(n)),j.innerHTML=``;let r=e(o,`12px`,`currentColor`,1.5);r&&j.appendChild(r),setTimeout(()=>{j.innerHTML=``;let t=e(l,`12px`,`currentColor`,1.5);t&&j.appendChild(t)},1500)}),d.appendChild(f),d.appendChild(S),C&&d.appendChild(C),d.appendChild(E),k&&d.appendChild(k),d.appendChild(A),d.appendChild(j),u.appendChild(d),m&&u.appendChild(w(n,ee,p)),u}}function E(s){let{buffer:c,getFullHistory:l,onClose:p,config:m,plugins:h=[],getThroughput:g}=s,te=s.renderIconByName??(()=>null),_=()=>s.getConfig?.()??m??{},ne=()=>_().features?.scrollToBottom?.enabled!==!1,v=m?.features?.eventStream??{},y=h.find(e=>e.renderEventStreamView);if(y?.renderEventStreamView&&m){let e=y.renderEventStreamView({config:m,events:c.getAll(),defaultRenderer:()=>b().element,onClose:p});if(e)return{element:e,update:()=>{},destroy:()=>{}}}return b();function b(){let y=v.classNames,b=t(`div`,`persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0`);f(b,y?.panel);let x=[],w=``,E=``,D=null,O=[],k={},A=0,j=i(),M=0,re=0,N=!1,P=null,ie=!1,F=0,I=/* @__PURE__ */ new Set,L=/* @__PURE__ */ new Map,ae=``,oe=``,R=null,z,B,V,H,U=null,W=null,G=null;function se(){let n=t(`div`,`persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0`),r=t(`div`,`persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden`);if(f(r,y?.headerBar),g){W=t(`div`,`persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap`),W.style.cursor=`help`,U=t(`span`,`persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums`),U.textContent=`-- tok/s`,G=t(`div`,`persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow`),G.style.display=`none`,G.style.pointerEvents=`none`;let e=W,r=G;W.addEventListener(`mouseenter`,()=>{if(!r.textContent)return;let t=e.getBoundingClientRect(),i=n.getBoundingClientRect();r.style.left=`${t.left-i.left}px`,r.style.top=`${t.bottom-i.top+4}px`,r.style.display=`block`}),W.addEventListener(`mouseleave`,()=>{r.style.display=`none`}),W.appendChild(U)}let i=t(`div`,`persona-flex-1`);z=t(`select`,`persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer`);let a=t(`option`,``);a.value=``,a.textContent=`All events (0)`,z.appendChild(a),B=t(`button`,`persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1`),B.type=`button`,B.title=`Copy All`;let o=e(u,`12px`,`currentColor`,1.5);o&&B.appendChild(o);let s=t(`span`,`persona-event-copy-all persona-text-xs`);s.textContent=`Copy All`,B.appendChild(s),W&&r.appendChild(W),r.appendChild(i),r.appendChild(z),r.appendChild(B);let c=t(`div`,`persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface`);f(c,y?.searchBar);let l=e(d,`14px`,`var(--persona-muted, #9ca3af)`,1.5),p=t(`span`,`persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center`);l&&p.appendChild(l),V=t(`input`,`persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary`),f(V,y?.searchInput),V.type=`text`,V.placeholder=`Search event payloads...`,H=t(`button`,`persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none`),H.type=`button`,H.style.display=`none`;let m=e(ee,`12px`,`currentColor`,2);return m&&H.appendChild(m),c.appendChild(p),c.appendChild(V),c.appendChild(H),n.appendChild(r),n.appendChild(c),G&&n.appendChild(G),n}let ce,le=h.find(e=>e.renderEventStreamToolbar);ce=le?.renderEventStreamToolbar&&m?le.renderEventStreamToolbar({config:m,defaultRenderer:()=>se(),eventCount:c.getSize(),filteredCount:0,onFilterChange:e=>{w=e,Q(),$()},onSearchChange:e=>{E=e,Q(),$()}})??se():se();let K=t(`div`,`persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0`);K.style.display=`none`;function ue(){if(!g||!U||!W)return;let e=g(),t=S(e);U.textContent=t;let n=C(e);G&&(G.textContent=n,n||(G.style.display=`none`)),W.setAttribute(`aria-label`,n?`Throughput: ${t}, ${n}`:`Throughput: ${t}`)}let de=t(`div`,`persona-flex-1 persona-min-h-0 persona-relative`),q=t(`div`,`persona-event-stream-list persona-overflow-y-auto persona-min-h-0`);q.style.height=`100%`;let fe=s.scroll.createScrollToBottomControl(te,`event-stream`,q),J=fe.element;f(J,y?.scrollIndicator);let Y=s.scroll.createScrollToLatest(q,b,()=>{F=q.scrollTop},()=>{j.resume(),M=0,X()},()=>{j.pause(),X()}),pe=_().features?.scrollToBottom,me=_().future?.v5Defaults;function X(){let e=_(),t=e.features?.scrollToBottom,n=s.getViewVisible?.()===!1||t?.enabled===!1||t?.scrollBehavior!==pe?.scrollBehavior||t?.scrollDurationMs!==pe?.scrollDurationMs||e.future?.v5Defaults!==me;pe=t,me=e.future?.v5Defaults,n&&Y.cancel();let r=!Y.active&&s.getViewVisible?.()!==!1&&!j.isFollowing()&&!ye()&&x.length>0;fe.update(_(),r,s.getResponseActive?.()??!1,M)}fe.update(_(),!1);let Z=t(`div`,`persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted`);Z.style.display=`none`,de.appendChild(q),de.appendChild(Z),de.appendChild(J),b.setAttribute(`tabindex`,`0`),b.appendChild(ce),b.appendChild(K),b.appendChild(de);function he(){let e=c.getAll(),n={};for(let t of e)n[t.type]=(n[t.type]||0)+1;let r=Object.keys(n).sort(),i=r.length!==O.length||!r.every((e,t)=>e===O[t]),a=!i&&r.some(e=>n[e]!==k[e]),o=e.length!==Object.values(k).reduce((e,t)=>e+t,0);if(!i&&!a&&!o||(O=r,k=n,!z))return;let s=z.value;if(z.options[0].textContent=`All events (${e.length})`,i){for(;z.options.length>1;)z.remove(1);for(let e of r){let r=t(`option`,``);r.value=e,r.textContent=`${e} (${n[e]||0})`,z.appendChild(r)}s&&r.includes(s)?z.value=s:s&&(z.value=``,w=``)}else for(let e=1;e<z.options.length;e++){let t=z.options[e];t.textContent=`${t.value} (${n[t.value]||0})`}}function ge(){let e=c.getAll();if(w&&(e=e.filter(e=>e.type===w)),E){let t=E.toLowerCase();e=e.filter(e=>e.type.toLowerCase().includes(t)||e.payload.toLowerCase().includes(t))}return e}function _e(){return w!==``||E!==``}function Q(){Y.cancel(),A=0,M=0,j.resume(),X()}function ve(e){I.has(e)?I.delete(e):I.add(e),R=e;let t=q.scrollTop,n=j.isFollowing();ie=!0,j.pause(),$(),q.scrollTop=t,n&&j.resume(),ie=!1,X()}function ye(){return a(q,50)}function $(){re=Date.now(),N=!1,ue(),he();let e=c.getEvictedCount();e>0?(K.textContent=`${e.toLocaleString()} older events truncated`,K.style.display=``):K.style.display=`none`,x=ge();let t=x.length,n=c.getSize()>0;t===0&&n&&_e()?(Z.textContent=E?`No events matching '${E}'`:`No events matching filter`,Z.style.display=``,q.style.display=`none`):(Z.style.display=`none`,q.style.display=``),B&&(B.title=_e()?`Copy Filtered (${t})`:`Copy All`),ne()&&!j.isFollowing()&&t>A&&(M+=t-A),A=t;let r=c.getAll(),i=r.length>0?r[0].timestamp:0,a=new Set(x.map(e=>e.id));for(let e of I)a.has(e)||I.delete(e);let o=w!==ae||E!==oe,s=L.size===0&&x.length>0;if(o||s||x.length===0){q.innerHTML=``,L.clear();let e=document.createDocumentFragment();for(let t=0;t<x.length;t++){let n=T(x[t],t,i,v,I,ve,h,m);L.set(x[t].id,n),e.appendChild(n)}q.appendChild(e),ae=w,oe=E,R=null}else{if(R!==null){let e=L.get(R);if(e&&e.parentNode===q){let t=x.findIndex(e=>e.id===R);if(t>=0){let n=T(x[t],t,i,v,I,ve,h,m);q.insertBefore(n,e),e.remove(),L.set(R,n)}}R=null}let e=new Set(x.map(e=>e.id));for(let[t,n]of L)e.has(t)||(n.remove(),L.delete(t));for(let e=0;e<x.length;e++){let t=x[e];if(!L.has(t.id)){let n=T(t,e,i,v,I,ve,h,m);L.set(t.id,n),q.appendChild(n)}}}!Y.active&&j.isFollowing()&&(q.scrollTop=q.scrollHeight),X()}function be(){X(),Date.now()-re>=100?(P!==null&&(cancelAnimationFrame(P),P=null),$()):N||(N=!0,P=requestAnimationFrame(()=>{P=null,$()}))}let xe=(n,r)=>{if(!B)return;B.innerHTML=``;let i=e(n,`12px`,`currentColor`,1.5);i&&B.appendChild(i);let a=t(`span`,`persona-text-xs`);a.textContent=`Copy All`,B.appendChild(a),setTimeout(()=>{B.innerHTML=``;let n=e(u,`12px`,`currentColor`,1.5);n&&B.appendChild(n);let r=t(`span`,`persona-text-xs`);r.textContent=`Copy All`,B.appendChild(r),B.disabled=!1},r)},Se=async()=>{if(B){B.disabled=!0;try{let e;_e()?e=x:l?(e=await l(),e.length===0&&(e=c.getAll())):e=c.getAll();let t=e.map(e=>{try{return JSON.parse(e.payload)}catch{return e.payload}});await navigator.clipboard.writeText(JSON.stringify(t,null,2)),xe(o,1500)}catch{xe(ee,1500)}}},Ce=()=>{z&&(w=z.value,Q(),$())},we=()=>{V&&H&&(H.style.display=V.value?``:`none`,D&&clearTimeout(D),D=setTimeout(()=>{E=V.value,Q(),$()},150))},Te=()=>{V&&H&&(V.value=``,E=``,H.style.display=`none`,D&&clearTimeout(D),Q(),$())},Ee=()=>{if(ie)return;if(Y.active||Y.interrupted){F=q.scrollTop,X();return}let e=q.scrollTop,{action:t,nextLastScrollTop:r}=n({following:j.isFollowing(),currentScrollTop:e,lastScrollTop:F,nearBottom:ye(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});F=r,t===`resume`?(j.resume(),M=0,X()):t===`pause`&&(j.pause(),X())},De=e=>{if(Y.interruptedBy(e))return;let t=r({following:j.isFollowing(),deltaY:e.deltaY,nearBottom:ye(),resumeWhenNearBottom:!0});t===`pause`?(j.pause(),X()):t===`resume`&&(j.resume(),M=0,X())},Oe=()=>{ne()&&(j.pause(),Y.start(_()),X())},ke=e=>{let t=e.target;if(!t||t.closest(`button`))return;let n=t.closest(`[data-event-id]`);if(!n)return;let r=n.getAttribute(`data-event-id`);r&&ve(r)},Ae=e=>{(e.metaKey||e.ctrlKey)&&e.key===`f`?(e.preventDefault(),V?.focus(),V?.select()):e.key===`Escape`&&(V&&document.activeElement===V?(Te(),V.blur(),b.focus()):p&&p())};B&&B.addEventListener(`click`,Se),z&&z.addEventListener(`change`,Ce),V&&V.addEventListener(`input`,we),H&&H.addEventListener(`click`,Te),q.addEventListener(`scroll`,Ee),q.addEventListener(`wheel`,De,{passive:!0}),q.addEventListener(`click`,ke),J.addEventListener(`click`,Oe),b.addEventListener(`keydown`,Ae);function je(){Y.destroy(),fe.destroy(),D&&clearTimeout(D),P!==null&&(cancelAnimationFrame(P),P=null),N=!1,L.clear(),B&&B.removeEventListener(`click`,Se),z&&z.removeEventListener(`change`,Ce),V&&V.removeEventListener(`input`,we),H&&H.removeEventListener(`click`,Te),q.removeEventListener(`scroll`,Ee),q.removeEventListener(`wheel`,De),q.removeEventListener(`click`,ke),J.removeEventListener(`click`,Oe),b.removeEventListener(`keydown`,Ae)}return{element:b,update:be,destroy:je}}}var D=class{#e;#t=0;#n=0;#r=0;#i=/* @__PURE__ */ new Set;#a;#o;constructor(e=2e3,t=null){this.#a=e,this.#e=Array(e),this.#o=t}push(e){this.#e[this.#t]=e,this.#t=(this.#t+1)%this.#a,this.#n<this.#a&&this.#n++,this.#r++,this.#i.add(e.type),this.#o?.put(e)}getAll(){return this.#n===0?[]:this.#n<this.#a?this.#e.slice(0,this.#n):[...this.#e.slice(this.#t,this.#a),...this.#e.slice(0,this.#t)]}async restore(){if(!this.#o)return 0;let e=await this.#o.getAll();if(e.length===0)return 0;let t=e.length>this.#a?e.slice(e.length-this.#a):e;for(let e of t)this.#e[this.#t]=e,this.#t=(this.#t+1)%this.#a,this.#n<this.#a&&this.#n++,this.#i.add(e.type);return this.#r=e.length,t.length}getAllFromStore(){return this.#o?this.#o.getAll():Promise.resolve(this.getAll())}getRecent(e){let t=this.getAll();return e>=t.length?t:t.slice(t.length-e)}getSize(){return this.#n}getTotalCaptured(){return this.#r}getEvictedCount(){return this.#r-this.#n}clear(){this.#e=Array(this.#a),this.#t=0,this.#n=0,this.#r=0,this.#i.clear(),this.#o?.clear()}destroy(){this.#e=[],this.#t=0,this.#n=0,this.#r=0,this.#i.clear(),this.#o?.destroy()}getEventTypes(){return Array.from(this.#i)}},O=class{#e=null;#t=[];#n=!1;#r=!1;#i;#a;constructor(e=`persona-event-stream`,t=`events`){this.#i=e,this.#a=t}open(){return new Promise((e,t)=>{try{let n=indexedDB.open(this.#i,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(this.#a)||e.createObjectStore(this.#a,{keyPath:`id`}).createIndex(`timestamp`,`timestamp`,{unique:!1})},n.onsuccess=()=>{this.#e=n.result,e()},n.onerror=()=>{t(n.error)}}catch(e){t(e)}})}put(e){!this.#e||this.#r||(this.#t.push(e),this.#n||(this.#n=!0,queueMicrotask(()=>this.#o())))}putBatch(e){if(!(!this.#e||this.#r||e.length===0))try{let t=this.#e.transaction(this.#a,`readwrite`).objectStore(this.#a);for(let n of e)t.put(n)}catch{}}getAll(){return new Promise((e,t)=>{if(!this.#e)e([]);else try{let n=this.#e.transaction(this.#a,`readonly`).objectStore(this.#a).index(`timestamp`).getAll();n.onsuccess=()=>{e(n.result)},n.onerror=()=>{t(n.error)}}catch(e){t(e)}})}getCount(){return new Promise((e,t)=>{if(!this.#e)e(0);else try{let n=this.#e.transaction(this.#a,`readonly`).objectStore(this.#a).count();n.onsuccess=()=>{e(n.result)},n.onerror=()=>{t(n.error)}}catch(e){t(e)}})}clear(){return new Promise((e,t)=>{if(!this.#e)e();else{this.#t=[];try{let n=this.#e.transaction(this.#a,`readwrite`).objectStore(this.#a).clear();n.onsuccess=()=>{e()},n.onerror=()=>{t(n.error)}}catch(e){t(e)}}})}close(){this.#e&&=(this.#e.close(),null)}destroy(){return this.#r=!0,this.#t=[],this.close(),new Promise((e,t)=>{try{let n=indexedDB.deleteDatabase(this.#i);n.onsuccess=()=>{e()},n.onerror=()=>{t(n.error)}}catch(e){t(e)}})}#o(){if(this.#n=!1,!this.#e||this.#r||this.#t.length===0)return;let e=this.#t;this.#t=[];try{let t=this.#e.transaction(this.#a,`readwrite`).objectStore(this.#a);for(let n of e)t.put(n)}catch{}}};const k=/* @__PURE__ */ new Set([`step_start`,`turn_start`]),A=/* @__PURE__ */ new Set([`step_complete`,`turn_complete`]),j=e=>typeof e==`object`&&!!e&&!Array.isArray(e),M=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,re=(e,t)=>{let n=e[t];return j(n)?n:void 0};function N(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function P(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function ie(e,t){return typeof t.type==`string`?t.type:e}function F(e){let t=re(e,`tokens`)??re(e,`totalTokens`);return t?M(t.output):void 0}function I(e){return M(e.durationMs)}function L(){return typeof performance<`u`&&typeof performance.now==`function`?performance.now():Date.now()}var ae=class{#e={status:`idle`};#t=null;constructor(e=L){this.now=e}getMetric(){let e=this.#t;if(e&&this.#e.status===`running`&&e.firstDeltaAt!==void 0&&this.#e.outputTokens!==void 0){let t=this.now()-e.firstDeltaAt;return{...this.#e,durationMs:t,tokensPerSecond:P(this.#e.outputTokens,t)}}return this.#e}reset(){this.#t=null,this.#e={status:`idle`}}#n(e){this.#t={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.#e={status:`running`}}processEvent(e,t){if(!j(t)){e===`execution_error`&&this.#t&&(this.#t=null,this.#e={status:`error`});return}let n=ie(e,t),r=this.now();if(n===`execution_start`)this.#n(r);else if(k.has(n))this.#t||this.#n(r);else if(n===`text_delta`){let e=typeof t.delta==`string`?t.delta:``;if(!e)return;this.#t||this.#n(r);let n=this.#t;n.firstDeltaAt??=r,n.visibleCharCount+=e.length;let i=n.exactOutputTokens+N(n.visibleCharCount),a=r-n.firstDeltaAt;this.#e={status:`running`,tokensPerSecond:P(i,a),outputTokens:i,durationMs:a,source:n.exactOutputTokens>0?`usage`:`estimate`}}else if(A.has(n)){if(!this.#t)return;let e=this.#t,n=F(t);n!==void 0&&(e.exactOutputTokens+=n,e.visibleCharCount=0);let i=e.exactOutputTokens>0,a=e.exactOutputTokens+N(e.visibleCharCount),o=this.#r(e,t,r);this.#e={status:`running`,tokensPerSecond:P(a,o),outputTokens:a,durationMs:o,source:i?`usage`:`estimate`}}else if(n===`execution_complete`){if(!this.#t)return;let e=this.#t,n=F(t),i=n??e.exactOutputTokens+N(e.visibleCharCount),a=n!==void 0||e.exactOutputTokens>0?`usage`:`estimate`,o=this.#r(e,t,r);this.#e={status:`complete`,tokensPerSecond:P(i,o),outputTokens:i,durationMs:o,source:a},this.#t=null}else if(n===`execution_error`||n===`error`&&t.recoverable===!1){if(!this.#t)return;this.#t=null,this.#e={status:`error`}}}#r(e,t,n){let r=e.firstDeltaAt===void 0?void 0:n-e.firstDeltaAt;return r!==void 0&&r>=250?r:I(t)??n-e.startedAt}};export{D as EventStreamBuffer,O as EventStreamStore,ae as ThroughputTracker,E as createEventStreamView};
1
+ import{t as e}from"./chunk-CnxIZOzx.js";import{t}from"./chunk-D5BxWOFB.js";import{c as n,o as r,r as i,s as a}from"./chunk-kizhspe5.js";import{Check as o,ChevronDown as s,ChevronRight as c,Clipboard as l,ClipboardCopy as u,Search as d,X as ee}from"lucide";function f(e,t){t&&t.split(/\s+/).forEach(t=>t&&e.classList.add(t))}const p={flow_:{bg:`var(--persona-event-badge-flow-bg, #dcfce7)`,text:`var(--persona-event-badge-flow-fg, #15803d)`},step_:{bg:`var(--persona-event-badge-step-bg, #f5f5f5)`,text:`var(--persona-event-badge-step-fg, #0a0a0a)`},reasoning_:{bg:`var(--persona-event-badge-reasoning-bg, #fef9c3)`,text:`var(--persona-event-badge-reasoning-fg, #a16207)`},tool_:{bg:`var(--persona-event-badge-tool-bg, #f3e8ff)`,text:`var(--persona-event-badge-tool-fg, #6b21a8)`},agent_:{bg:`var(--persona-event-badge-agent-bg, #ccfbf1)`,text:`var(--persona-event-badge-agent-fg, #115e59)`},error:{bg:`var(--persona-event-badge-error-bg, #fee2e2)`,text:`var(--persona-event-badge-error-fg, #b91c1c)`}};p.execution_error=p.error,p.execution_=p.flow_,p.turn_=p.agent_,p.text_=p.agent_;const m={bg:`var(--persona-event-badge-default-bg, #f3f4f6)`,text:`var(--persona-event-badge-default-fg, #4b5563)`},h=[`flowName`,`stepName`,`reasoningText`,`text`,`name`,`tool`,`toolName`];function g(e,t){if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith(`_`)&&e.startsWith(n))return t[n]}function te(e,t){return(t&&g(e,t))??g(e,p)??m}function _(e){return/^#[0-9a-fA-F]{6}$/.test(e)?`${e}50`:`color-mix(in srgb, ${e} 31%, transparent)`}function ne(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function v(e){let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}:${String(t.getSeconds()).padStart(2,`0`)}.${String(t.getMilliseconds()).padStart(3,`0`)}`}function y(e,t){try{let n=JSON.parse(e);if(typeof n!=`object`||!n)return null;for(let e of t){let t=e.split(`.`),r=n;for(let e of t)if(r&&typeof r==`object`&&r)r=r[e];else{r=void 0;break}if(typeof r==`string`&&r.trim())return r.trim()}}catch{}return null}function b(e){return navigator.clipboard?.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement(`textarea`);n.value=e,n.style.position=`fixed`,n.style.opacity=`0`,document.body.appendChild(n),n.select(),document.execCommand(`copy`),document.body.removeChild(n),t()})}function x(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function S(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?`-- tok/s`:`${e.tokensPerSecond.toFixed(1)} tok/s`}function C(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(` · `)}function w(e,n,r){let i,a;try{a=JSON.parse(e.payload),i=JSON.stringify(a,null,2)}catch{a=e.payload,i=e.payload}let o=n.find(e=>e.renderEventStreamPayload);if(o?.renderEventStreamPayload&&r){let t=o.renderEventStreamPayload({event:e,config:r,defaultRenderer:()=>s(),parsedPayload:a});if(t)return t}return s();function s(){let e=t(`div`,`persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]`),n=t(`pre`,`persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono`);return n.textContent=i,e.appendChild(n),e}}function T(n,r,i,a,u,d,ee,p){let m=u.has(n.id),g=t(`div`,`persona-border-b persona-border-persona-divider persona-text-xs`);f(g,a.classNames?.eventRow);let S=ee.find(e=>e.renderEventStreamRow);if(S?.renderEventStreamRow&&p){let e=S.renderEventStreamRow({event:n,index:r,config:p,defaultRenderer:()=>C(),isExpanded:m,onToggleExpand:()=>d(n.id)});if(e)return g.appendChild(e),g}return g.appendChild(C()),g;function C(){let u=t(`div`,``),d=t(`div`,`persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group`);d.setAttribute(`data-event-id`,n.id);let f=t(`span`,`persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center`),g=e(m?s:c,`14px`,`currentColor`,2);g&&f.appendChild(g);let S=t(`span`,`persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]`);S.textContent=(a.timestampFormat??`relative`)===`relative`?ne(n.timestamp,i):v(n.timestamp);let C=null;a.showSequenceNumbers!==!1&&(C=t(`span`,`persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right`),C.textContent=String(r+1));let T=te(n.type,a.badgeColors),E=t(`span`,`persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border`);E.style.backgroundColor=T.bg,E.style.color=T.text,E.style.borderColor=_(T.text),E.textContent=n.type;let D=a.descriptionFields??h,O=y(n.payload,D),k=null;O&&(k=t(`span`,`persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0`),k.textContent=O);let A=t(`div`,`persona-flex-1 persona-min-w-0`),j=t(`button`,`persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0`),M=e(l,`12px`,`currentColor`,1.5);return M&&j.appendChild(M),j.addEventListener(`click`,async t=>{t.stopPropagation(),await b(x(n)),j.innerHTML=``;let r=e(o,`12px`,`currentColor`,1.5);r&&j.appendChild(r),setTimeout(()=>{j.innerHTML=``;let t=e(l,`12px`,`currentColor`,1.5);t&&j.appendChild(t)},1500)}),d.appendChild(f),d.appendChild(S),C&&d.appendChild(C),d.appendChild(E),k&&d.appendChild(k),d.appendChild(A),d.appendChild(j),u.appendChild(d),m&&u.appendChild(w(n,ee,p)),u}}function E(s){let{buffer:c,getFullHistory:l,onClose:p,config:m,plugins:h=[],getThroughput:g}=s,te=s.renderIconByName??(()=>null),_=()=>s.getConfig?.()??m??{},ne=()=>_().features?.scrollToBottom?.enabled!==!1,v=m?.features?.eventStream??{},y=h.find(e=>e.renderEventStreamView);if(y?.renderEventStreamView&&m){let e=y.renderEventStreamView({config:m,events:c.getAll(),defaultRenderer:()=>b().element,onClose:p});if(e)return{element:e,update:()=>{},destroy:()=>{}}}return b();function b(){let y=v.classNames,b=t(`div`,`persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0`);f(b,y?.panel);let x=[],w=``,E=``,D=null,O=[],k={},A=0,j=i(),M=0,re=0,N=!1,P=null,ie=!1,F=0,I=/* @__PURE__ */ new Set,L=/* @__PURE__ */ new Map,ae=``,oe=``,R=null,z,B,V,H,U=null,W=null,G=null;function se(){let n=t(`div`,`persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0`),r=t(`div`,`persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden`);if(f(r,y?.headerBar),g){W=t(`div`,`persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap`),W.style.cursor=`help`,U=t(`span`,`persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums`),U.textContent=`-- tok/s`,G=t(`div`,`persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow`),G.style.display=`none`,G.style.pointerEvents=`none`;let e=W,r=G;W.addEventListener(`mouseenter`,()=>{if(!r.textContent)return;let t=e.getBoundingClientRect(),i=n.getBoundingClientRect();r.style.left=`${t.left-i.left}px`,r.style.top=`${t.bottom-i.top+4}px`,r.style.display=`block`}),W.addEventListener(`mouseleave`,()=>{r.style.display=`none`}),W.appendChild(U)}let i=t(`div`,`persona-flex-1`);z=t(`select`,`persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer`);let a=t(`option`,``);a.value=``,a.textContent=`All events (0)`,z.appendChild(a),B=t(`button`,`persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1`),B.type=`button`,B.title=`Copy All`;let o=e(u,`12px`,`currentColor`,1.5);o&&B.appendChild(o);let s=t(`span`,`persona-event-copy-all persona-text-xs`);s.textContent=`Copy All`,B.appendChild(s),W&&r.appendChild(W),r.appendChild(i),r.appendChild(z),r.appendChild(B);let c=t(`div`,`persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface`);f(c,y?.searchBar);let l=e(d,`14px`,`var(--persona-muted, #9ca3af)`,1.5),p=t(`span`,`persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center`);l&&p.appendChild(l),V=t(`input`,`persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary`),f(V,y?.searchInput),V.type=`text`,V.placeholder=`Search event payloads...`,H=t(`button`,`persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none`),H.type=`button`,H.style.display=`none`;let m=e(ee,`12px`,`currentColor`,2);return m&&H.appendChild(m),c.appendChild(p),c.appendChild(V),c.appendChild(H),n.appendChild(r),n.appendChild(c),G&&n.appendChild(G),n}let ce,le=h.find(e=>e.renderEventStreamToolbar);ce=le?.renderEventStreamToolbar&&m?le.renderEventStreamToolbar({config:m,defaultRenderer:()=>se(),eventCount:c.getSize(),filteredCount:0,onFilterChange:e=>{w=e,Q(),$()},onSearchChange:e=>{E=e,Q(),$()}})??se():se();let K=t(`div`,`persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0`);K.style.display=`none`;function ue(){if(!g||!U||!W)return;let e=g(),t=S(e);U.textContent=t;let n=C(e);G&&(G.textContent=n,n||(G.style.display=`none`)),W.setAttribute(`aria-label`,n?`Throughput: ${t}, ${n}`:`Throughput: ${t}`)}let de=t(`div`,`persona-flex-1 persona-min-h-0 persona-relative`),q=t(`div`,`persona-event-stream-list persona-overflow-y-auto persona-min-h-0`);q.style.height=`100%`;let fe=s.scroll.createScrollToBottomControl(te,`event-stream`,q),J=fe.element;f(J,y?.scrollIndicator);let Y=s.scroll.createScrollToLatest(q,b,()=>{F=q.scrollTop},()=>{j.resume(),M=0,X()},()=>{j.pause(),X()}),pe=_().features?.scrollToBottom,me=_().future?.v5Defaults;function X(){let e=_(),t=e.features?.scrollToBottom,n=s.getViewVisible?.()===!1||t?.enabled===!1||t?.scrollBehavior!==pe?.scrollBehavior||t?.scrollDurationMs!==pe?.scrollDurationMs||e.future?.v5Defaults!==me;pe=t,me=e.future?.v5Defaults,n&&Y.cancel();let r=!Y.active&&s.getViewVisible?.()!==!1&&!j.isFollowing()&&!ye()&&x.length>0;fe.update(_(),r,s.getResponseActive?.()??!1,M)}fe.update(_(),!1);let Z=t(`div`,`persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted`);Z.style.display=`none`,de.appendChild(q),de.appendChild(Z),de.appendChild(J),b.setAttribute(`tabindex`,`0`),b.appendChild(ce),b.appendChild(K),b.appendChild(de);function he(){let e=c.getAll(),n={};for(let t of e)n[t.type]=(n[t.type]||0)+1;let r=Object.keys(n).sort(),i=r.length!==O.length||!r.every((e,t)=>e===O[t]),a=!i&&r.some(e=>n[e]!==k[e]),o=e.length!==Object.values(k).reduce((e,t)=>e+t,0);if(!i&&!a&&!o||(O=r,k=n,!z))return;let s=z.value;if(z.options[0].textContent=`All events (${e.length})`,i){for(;z.options.length>1;)z.remove(1);for(let e of r){let r=t(`option`,``);r.value=e,r.textContent=`${e} (${n[e]||0})`,z.appendChild(r)}s&&r.includes(s)?z.value=s:s&&(z.value=``,w=``)}else for(let e=1;e<z.options.length;e++){let t=z.options[e];t.textContent=`${t.value} (${n[t.value]||0})`}}function ge(){let e=c.getAll();if(w&&(e=e.filter(e=>e.type===w)),E){let t=E.toLowerCase();e=e.filter(e=>e.type.toLowerCase().includes(t)||e.payload.toLowerCase().includes(t))}return e}function _e(){return w!==``||E!==``}function Q(){Y.cancel(),A=0,M=0,j.resume(),X()}function ve(e){I.has(e)?I.delete(e):I.add(e),R=e;let t=q.scrollTop,n=j.isFollowing();ie=!0,j.pause(),$(),q.scrollTop=t,n&&j.resume(),ie=!1,X()}function ye(){return r(q,50)}function $(){re=Date.now(),N=!1,ue(),he();let e=c.getEvictedCount();e>0?(K.textContent=`${e.toLocaleString()} older events truncated`,K.style.display=``):K.style.display=`none`,x=ge();let t=x.length,n=c.getSize()>0;t===0&&n&&_e()?(Z.textContent=E?`No events matching '${E}'`:`No events matching filter`,Z.style.display=``,q.style.display=`none`):(Z.style.display=`none`,q.style.display=``),B&&(B.title=_e()?`Copy Filtered (${t})`:`Copy All`),ne()&&!j.isFollowing()&&t>A&&(M+=t-A),A=t;let r=c.getAll(),i=r.length>0?r[0].timestamp:0,a=new Set(x.map(e=>e.id));for(let e of I)a.has(e)||I.delete(e);let o=w!==ae||E!==oe,s=L.size===0&&x.length>0;if(o||s||x.length===0){q.innerHTML=``,L.clear();let e=document.createDocumentFragment();for(let t=0;t<x.length;t++){let n=T(x[t],t,i,v,I,ve,h,m);L.set(x[t].id,n),e.appendChild(n)}q.appendChild(e),ae=w,oe=E,R=null}else{if(R!==null){let e=L.get(R);if(e&&e.parentNode===q){let t=x.findIndex(e=>e.id===R);if(t>=0){let n=T(x[t],t,i,v,I,ve,h,m);q.insertBefore(n,e),e.remove(),L.set(R,n)}}R=null}let e=new Set(x.map(e=>e.id));for(let[t,n]of L)e.has(t)||(n.remove(),L.delete(t));for(let e=0;e<x.length;e++){let t=x[e];if(!L.has(t.id)){let n=T(t,e,i,v,I,ve,h,m);L.set(t.id,n),q.appendChild(n)}}}!Y.active&&j.isFollowing()&&(q.scrollTop=q.scrollHeight),X()}function be(){X(),Date.now()-re>=100?(P!==null&&(cancelAnimationFrame(P),P=null),$()):N||(N=!0,P=requestAnimationFrame(()=>{P=null,$()}))}let xe=(n,r)=>{if(!B)return;B.innerHTML=``;let i=e(n,`12px`,`currentColor`,1.5);i&&B.appendChild(i);let a=t(`span`,`persona-text-xs`);a.textContent=`Copy All`,B.appendChild(a),setTimeout(()=>{B.innerHTML=``;let n=e(u,`12px`,`currentColor`,1.5);n&&B.appendChild(n);let r=t(`span`,`persona-text-xs`);r.textContent=`Copy All`,B.appendChild(r),B.disabled=!1},r)},Se=async()=>{if(B){B.disabled=!0;try{let e;_e()?e=x:l?(e=await l(),e.length===0&&(e=c.getAll())):e=c.getAll();let t=e.map(e=>{try{return JSON.parse(e.payload)}catch{return e.payload}});await navigator.clipboard.writeText(JSON.stringify(t,null,2)),xe(o,1500)}catch{xe(ee,1500)}}},Ce=()=>{z&&(w=z.value,Q(),$())},we=()=>{V&&H&&(H.style.display=V.value?``:`none`,D&&clearTimeout(D),D=setTimeout(()=>{E=V.value,Q(),$()},150))},Te=()=>{V&&H&&(V.value=``,E=``,H.style.display=`none`,D&&clearTimeout(D),Q(),$())},Ee=()=>{if(ie)return;if(Y.active||Y.interrupted){F=q.scrollTop,X();return}let e=q.scrollTop,{action:t,nextLastScrollTop:n}=a({following:j.isFollowing(),currentScrollTop:e,lastScrollTop:F,nearBottom:ye(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});F=n,t===`resume`?(j.resume(),M=0,X()):t===`pause`&&(j.pause(),X())},De=e=>{if(Y.interruptedBy(e))return;let t=n({following:j.isFollowing(),deltaY:e.deltaY,nearBottom:ye(),resumeWhenNearBottom:!0});t===`pause`?(j.pause(),X()):t===`resume`&&(j.resume(),M=0,X())},Oe=()=>{ne()&&(j.pause(),Y.start(_()),X())},ke=e=>{let t=e.target;if(!t||t.closest(`button`))return;let n=t.closest(`[data-event-id]`);if(!n)return;let r=n.getAttribute(`data-event-id`);r&&ve(r)},Ae=e=>{(e.metaKey||e.ctrlKey)&&e.key===`f`?(e.preventDefault(),V?.focus(),V?.select()):e.key===`Escape`&&(V&&document.activeElement===V?(Te(),V.blur(),b.focus()):p&&p())};B&&B.addEventListener(`click`,Se),z&&z.addEventListener(`change`,Ce),V&&V.addEventListener(`input`,we),H&&H.addEventListener(`click`,Te),q.addEventListener(`scroll`,Ee),q.addEventListener(`wheel`,De,{passive:!0}),q.addEventListener(`click`,ke),J.addEventListener(`click`,Oe),b.addEventListener(`keydown`,Ae);function je(){Y.destroy(),fe.destroy(),D&&clearTimeout(D),P!==null&&(cancelAnimationFrame(P),P=null),N=!1,L.clear(),B&&B.removeEventListener(`click`,Se),z&&z.removeEventListener(`change`,Ce),V&&V.removeEventListener(`input`,we),H&&H.removeEventListener(`click`,Te),q.removeEventListener(`scroll`,Ee),q.removeEventListener(`wheel`,De),q.removeEventListener(`click`,ke),J.removeEventListener(`click`,Oe),b.removeEventListener(`keydown`,Ae)}return{element:b,update:be,destroy:je}}}var D=class{#e;#t=0;#n=0;#r=0;#i=/* @__PURE__ */ new Set;#a;#o;constructor(e=2e3,t=null){this.#a=e,this.#e=Array(e),this.#o=t}push(e){this.#e[this.#t]=e,this.#t=(this.#t+1)%this.#a,this.#n<this.#a&&this.#n++,this.#r++,this.#i.add(e.type),this.#o?.put(e)}getAll(){return this.#n===0?[]:this.#n<this.#a?this.#e.slice(0,this.#n):[...this.#e.slice(this.#t,this.#a),...this.#e.slice(0,this.#t)]}async restore(){if(!this.#o)return 0;let e=await this.#o.getAll();if(e.length===0)return 0;let t=e.length>this.#a?e.slice(e.length-this.#a):e;for(let e of t)this.#e[this.#t]=e,this.#t=(this.#t+1)%this.#a,this.#n<this.#a&&this.#n++,this.#i.add(e.type);return this.#r=e.length,t.length}getAllFromStore(){return this.#o?this.#o.getAll():Promise.resolve(this.getAll())}getRecent(e){let t=this.getAll();return e>=t.length?t:t.slice(t.length-e)}getSize(){return this.#n}getTotalCaptured(){return this.#r}getEvictedCount(){return this.#r-this.#n}clear(){this.#e=Array(this.#a),this.#t=0,this.#n=0,this.#r=0,this.#i.clear(),this.#o?.clear()}destroy(){this.#e=[],this.#t=0,this.#n=0,this.#r=0,this.#i.clear(),this.#o?.destroy()}getEventTypes(){return Array.from(this.#i)}},O=class{#e=null;#t=[];#n=!1;#r=!1;#i;#a;constructor(e=`persona-event-stream`,t=`events`){this.#i=e,this.#a=t}open(){return new Promise((e,t)=>{try{let n=indexedDB.open(this.#i,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(this.#a)||e.createObjectStore(this.#a,{keyPath:`id`}).createIndex(`timestamp`,`timestamp`,{unique:!1})},n.onsuccess=()=>{this.#e=n.result,e()},n.onerror=()=>{t(n.error)}}catch(e){t(e)}})}put(e){!this.#e||this.#r||(this.#t.push(e),this.#n||(this.#n=!0,queueMicrotask(()=>this.#o())))}putBatch(e){if(!(!this.#e||this.#r||e.length===0))try{let t=this.#e.transaction(this.#a,`readwrite`).objectStore(this.#a);for(let n of e)t.put(n)}catch{}}getAll(){return new Promise((e,t)=>{if(!this.#e)e([]);else try{let n=this.#e.transaction(this.#a,`readonly`).objectStore(this.#a).index(`timestamp`).getAll();n.onsuccess=()=>{e(n.result)},n.onerror=()=>{t(n.error)}}catch(e){t(e)}})}getCount(){return new Promise((e,t)=>{if(!this.#e)e(0);else try{let n=this.#e.transaction(this.#a,`readonly`).objectStore(this.#a).count();n.onsuccess=()=>{e(n.result)},n.onerror=()=>{t(n.error)}}catch(e){t(e)}})}clear(){return new Promise((e,t)=>{if(!this.#e)e();else{this.#t=[];try{let n=this.#e.transaction(this.#a,`readwrite`).objectStore(this.#a).clear();n.onsuccess=()=>{e()},n.onerror=()=>{t(n.error)}}catch(e){t(e)}}})}close(){this.#e&&=(this.#e.close(),null)}destroy(){return this.#r=!0,this.#t=[],this.close(),new Promise((e,t)=>{try{let n=indexedDB.deleteDatabase(this.#i);n.onsuccess=()=>{e()},n.onerror=()=>{t(n.error)}}catch(e){t(e)}})}#o(){if(this.#n=!1,!this.#e||this.#r||this.#t.length===0)return;let e=this.#t;this.#t=[];try{let t=this.#e.transaction(this.#a,`readwrite`).objectStore(this.#a);for(let n of e)t.put(n)}catch{}}};const k=/* @__PURE__ */ new Set([`step_start`,`turn_start`]),A=/* @__PURE__ */ new Set([`step_complete`,`turn_complete`]),j=e=>typeof e==`object`&&!!e&&!Array.isArray(e),M=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,re=(e,t)=>{let n=e[t];return j(n)?n:void 0};function N(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function P(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function ie(e,t){return typeof t.type==`string`?t.type:e}function F(e){let t=re(e,`tokens`)??re(e,`totalTokens`);return t?M(t.output):void 0}function I(e){return M(e.durationMs)}function L(){return typeof performance<`u`&&typeof performance.now==`function`?performance.now():Date.now()}var ae=class{#e={status:`idle`};#t=null;constructor(e=L){this.now=e}getMetric(){let e=this.#t;if(e&&this.#e.status===`running`&&e.firstDeltaAt!==void 0&&this.#e.outputTokens!==void 0){let t=this.now()-e.firstDeltaAt;return{...this.#e,durationMs:t,tokensPerSecond:P(this.#e.outputTokens,t)}}return this.#e}reset(){this.#t=null,this.#e={status:`idle`}}#n(e){this.#t={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.#e={status:`running`}}processEvent(e,t){if(!j(t)){e===`execution_error`&&this.#t&&(this.#t=null,this.#e={status:`error`});return}let n=ie(e,t),r=this.now();if(n===`execution_start`)this.#n(r);else if(k.has(n))this.#t||this.#n(r);else if(n===`text_delta`){let e=typeof t.delta==`string`?t.delta:``;if(!e)return;this.#t||this.#n(r);let n=this.#t;n.firstDeltaAt??=r,n.visibleCharCount+=e.length;let i=n.exactOutputTokens+N(n.visibleCharCount),a=r-n.firstDeltaAt;this.#e={status:`running`,tokensPerSecond:P(i,a),outputTokens:i,durationMs:a,source:n.exactOutputTokens>0?`usage`:`estimate`}}else if(A.has(n)){if(!this.#t)return;let e=this.#t,n=F(t);n!==void 0&&(e.exactOutputTokens+=n,e.visibleCharCount=0);let i=e.exactOutputTokens>0,a=e.exactOutputTokens+N(e.visibleCharCount),o=this.#r(e,t,r);this.#e={status:`running`,tokensPerSecond:P(a,o),outputTokens:a,durationMs:o,source:i?`usage`:`estimate`}}else if(n===`execution_complete`){if(!this.#t)return;let e=this.#t,n=F(t),i=n??e.exactOutputTokens+N(e.visibleCharCount),a=n!==void 0||e.exactOutputTokens>0?`usage`:`estimate`,o=this.#r(e,t,r);this.#e={status:`complete`,tokensPerSecond:P(i,o),outputTokens:i,durationMs:o,source:a},this.#t=null}else if(n===`execution_error`||n===`error`&&t.recoverable===!1){if(!this.#t)return;this.#t=null,this.#e={status:`error`}}}#r(e,t,n){let r=e.firstDeltaAt===void 0?void 0:n-e.firstDeltaAt;return r!==void 0&&r>=250?r:I(t)??n-e.startedAt}};export{D as EventStreamBuffer,O as EventStreamStore,ae as ThroughputTracker,E as createEventStreamView};
@@ -0,0 +1 @@
1
+ function e(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>!t&&(t=!0,!0)}}function t(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function n(e,n){return t(e)-e.scrollTop<=n}function r(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:i,userScrollThreshold:a,isAutoScrolling:o=!1,pauseOnUpwardScroll:s=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:l=!1}=e,u=n-r;return o||Math.abs(u)<a?{action:`none`,delta:u,nextLastScrollTop:n}:!t&&i&&(!l||u>0)?{action:`resume`,delta:u,nextLastScrollTop:n}:t&&s&&u<0||t&&c&&!i?{action:`pause`,delta:u,nextLastScrollTop:n}:{action:`none`,delta:u,nextLastScrollTop:n}}function i(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:i=!1}=e;return t&&n<0?`pause`:!t&&i&&n>0&&r?`resume`:`none`}function a(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function o(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset);return{targetScrollTop:t,spacerHeight:Math.max(0,t+e.viewportHeight-e.contentHeight+(e.slack??0))}}function s(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}export{a,i as c,t as i,s as n,n as o,e as r,r as s,o as t};
@@ -1 +1 @@
1
- var e=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}};function t(e){if(e.length===0)return`0:empty`;let t=e.map(e=>[e.name,e.description??``,e.parametersSchema?JSON.stringify(e.parametersSchema):``,e.origin??``,e.annotations?JSON.stringify(e.annotations):``].join(``)).sort();return`${e.length}:${r(t.join(``))}`}function n(e,t){let n=3735928559^t,r=1103547991^t;for(let t=0;t<e.length;t++){let i=e.charCodeAt(t);n=Math.imul(n^i,2654435761),r=Math.imul(r^i,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function r(e){return`${n(e,0).toString(36)}.${n(e,2654435761).toString(36)}`}var i=e((()=>{})),a,o,s,c,l=e((()=>{a=e=>e.replace(/[^a-zA-Z0-9_]/g,`_`).toLowerCase().replace(/_+/g,`_`).replace(/^_|_$/g,``),o=e=>typeof e==`object`&&!!e&&!Array.isArray(e),s=e=>{if(e.variant!==`tool`)return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=a(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:o(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},c=(e,t)=>{let n=[],r=[],i=[],a=``,o,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=s(l);if(e){let t=l.agentMetadata?.clientToolAnswer?.batch;r.length>0&&(t===void 0||t!==o)&&c(),r.length===0&&(a=l.createdAt,o=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}})),u,d,f=e((()=>{u=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`,`image/svg+xml`,`image/bmp`],d=[`application/pdf`,`text/plain`,`text/markdown`,`text/csv`,`application/msword`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/vnd.ms-excel`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/json`],[...u,...d]}));function p(e,t=e.contentParts??e.llmContent??e.rawContent??e.content){let n=e.content;if(typeof n!=`string`)return;let r=e.contentParts??e.llmContent??e.rawContent??n;if(n===``&&(t===r||JSON.stringify(t)===JSON.stringify(r)))return;let i=t;if(typeof i!=`string`||i!==n)return n}var m=e((()=>{f()})),h,g=e((()=>{h=e=>e.localOnly===!0||e.role===`assistant`&&typeof e.id==`string`&&e.id.startsWith(`reconnect-failed-`)})),_=`4.33.0`,v,y=e((()=>{v=_})),b,x,S,C,w,T;e((()=>{i(),l(),m(),g(),y(),b=e=>e.voiceCaption||h(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),x=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,S=e=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),C=e=>{let t=e.agentMetadata?.providerPhase??e.agentMetadata?.phase;return e.role===`assistant`&&(t===`commentary`||t===`partial_answer`||t===`final_answer`)?{phase:t}:{}},w=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt,...C(e)}),T=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(e,n,r,i){let a=!!(n&&n.length>0),o=a?t(n):void 0,s=this.host.clientToolsFingerprintSessionId===e,c=a&&s&&this.host.lastSentClientToolsFingerprint===o,l=!a&&i?.emptyMeansReplace===!0&&this.host.sentNonEmptyClientToolsSessionId===e,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=e,a?this.host.sentNonEmptyClientToolsSessionId=e:l&&(this.host.sentNonEmptyClientToolsSessionId=null)}}}async createClientSession(e){let t=this.host.isHistoryCapable()&&!e.omitVisitorFields,n=!e.omitVisitorFields,r=null;(t||n)&&(await this.host.historyInternals.historyBootstrapReady,r=await this.host.readVisitorToken());let i=this.host.routing(),a=i.agentId??i.flowId,o=t||e.durableResume?e.conversationId:void 0,s={token:this.host.config.clientToken,...a&&{flowId:a},...t&&{visitorHistory:!0},...n&&{durableRecovery:!0},...(t||n)&&r?{visitorToken:r}:{},...t&&e.identityProof?{identityProof:e.identityProof}:{},...o?{conversationId:o}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let c=await fetch(this.host.getClientApiUrl(`init`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":v},body:JSON.stringify(s),signal:e.signal});if(!c.ok){let n=await c.json().catch(()=>({error:`Session initialization failed`}));if(t&&c.status===403&&n.error===`visitor_history_disabled`){if(this.host.markHistoryUnavailable(),o)throw new this.host.HistoryClientError(`history_disabled`,`Visitor history is disabled for this surface`);return this.createClientSession({...e,omitVisitorFields:!0})}throw c.status===403&&n.error===`durable_recovery_disabled`?new this.host.HistoryClientError(`history_disabled`,`Durable recovery is disabled for this surface`):(t||e.durableResume)&&c.status===401&&n.error===`visitor_required`?new this.host.HistoryClientError(`visitor_required`,`Visitor credential no longer resolves`):o&&c.status===404?new this.host.HistoryClientError(`not_found`,`Conversation not found`):c.status===401?Error(`Invalid client token: ${n.hint||n.error}`):c.status===403?Error(`Origin not allowed: ${n.hint||n.error}`):Error(n.error||`Failed to initialize session`)}let l=await c.json();return l.visitor?.token&&await this.host.historyInternals.visitorStore?.set(l.visitor.token),{sessionId:l.sessionId,expiresAt:new Date(l.expiresAt),flow:l.flow,...l.conversationId?{conversationId:l.conversationId}:{},...l.targetId?{targetId:l.targetId}:{},...l.conversationRevision?{conversationRevision:l.conversationRevision}:{},...l.durableRecovery?{durableRecovery:l.durableRecovery}:{},...l.visitor?{visitor:l.visitor}:{},config:{welcomeMessage:l.config.welcomeMessage,placeholder:l.config.placeholder,theme:l.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 t={...e,...this.host.config.clientToken&&{token:this.host.config.clientToken}},n=await fetch(`${this.host.clientApiBase()}/v1/client/feedback`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":v},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:`Feedback submission failed`}));throw n.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,t,n){let{HistoryClientError:r}=this.host,i=()=>this.host.isCurrentTurn(n),a=e=>{i()&&t(e)};try{let t=()=>{if(e.signal?.throwIfAborted(),!i())throw new DOMException(`Turn superseded`,`AbortError`)},o=this.host.clientSession??await this.host.initSession();t();let s=async()=>{t();let n=o,r=n.durableRecovery?.enabled===!0;if(r&&(!n.conversationId||!await this.host.readVisitorToken()))throw Error(`Renewing this conversation requires its visitor credential.`);t();let i=await this.host.createClientSession({...r||this.host.isHistoryCapable()?{conversationId:n.conversationId,durableResume:r}:{storedSessionId:n.sessionId},signal:e.signal});if(t(),n.conversationId&&i.conversationId!==n.conversationId||r&&i.durableRecovery?.enabled!==!0)throw Error(`Session renewal did not preserve this conversation.`);o=this.host.finishInit(i,n.conversationId??null,!1),this.host.clientSession=o,this.host.resetSessionWarmLatch(),this.host.resetClientToolsFingerprint(),this.host.config.onSessionInit?.(o)};Date.now()>=o.expiresAt.getTime()-6e4&&await s();let c=new Map(S(e.messages).map(e=>[e,this.#s(e)])),l=await this.#l(e.messages,void 0,c),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([e])=>e!==`sessionId`&&e!==`session_id`)):void 0,d=this.host.isHistoryCapable(),f={sessionId:o.sessionId,messages:S(e.messages).flatMap(e=>{let t=c.get(e);if(!t)return[];let n=d?p(e,t.content):void 0;return[{id:e.id,role:t.role,content:t.content,...n!==void 0&&{displayContent:n}}]}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context},turnId:n,...e.interrupt&&{submitMode:`interrupt`},...e.voiceSpoken&&{voice:{spoken:!0,...e.voicePriorToolResults?.length&&{priorToolResults:e.voicePriorToolResults}}}},m=async()=>{t();let n=o.durableRecovery?.enabled===!0?await this.host.readVisitorToken():null;return t(),this.host.sendWithClientToolsDiff(o.sessionId,l.clientTools,async r=>{t();let i=await this.host.resolveChatIdentityProof(e.signal);t();let a={...f,sessionId:o.sessionId,...r,...i&&{identityProof:i}};return this.host.debug&&console.debug(`[AgentWidgetClient] client token dispatch`,{...a,...i&&{identityProof:{provider:i.provider,token:`[REDACTED]`}}}),fetch(this.host.getClientApiUrl(`chat`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":v,...n?{"X-Visitor-Token":n}:{}},body:JSON.stringify(a),signal:e.signal})})},h=await m();if(t(),h.response.status===401){let e=await h.response.clone().json().catch(()=>null);t(),e?.error===`Session not found or expired`&&(await s(),h=await m(),t())}let{response:g,commit:_}=h;if(!g.ok){let e=await g.json().catch(()=>({error:`Chat request failed`}));if(g.status===401&&e.error===`invalid_identity_proof`){let e=new r(`invalid_identity_proof`,`The identity proof was rejected`);throw a({type:`error`,error:e}),e}if(g.status===401){this.host.clearClientSession(),this.host.config.onSessionExpired?.();let e=/* @__PURE__ */ Error(`Session expired. Please refresh to continue.`);throw a({type:`error`,error:e}),e}if(g.status===429){let t=Error(e.hint||`Message limit reached for this session.`);throw a({type:`error`,error:t}),t}if(g.status===410&&e.error===`conversation_deleted`){let e=new r(`conversation_deleted`,`This conversation was deleted`);throw a({type:`error`,error:e}),e}let t=Error(e.error||`Failed to send message`);throw a({type:`error`,error:t}),t}if(!g.body){let e=/* @__PURE__ */ Error(`No response body received`);throw a({type:`error`,error:e}),e}_(),a({type:`status`,status:`connected`});try{await this.host.streamResponse(g.body,a,e.assistantMessageId,void 0,e.signal)}finally{a({type:`status`,status:`idle`})}}catch(e){let t=e instanceof Error?e:Error(String(e));throw!(t instanceof r)&&!t.message.includes(`Session expired`)&&!t.message.includes(`Message limit`)&&a({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(!b(e))return null;let t=e.contentParts??e.llmContent??e.rawContent??e.content,n=e.role===`operator`?null:w(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)||!x(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=c(S(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 s=await this.#i(e);return s&&(a.context=s),a}async#l(e,t,n){let r=c(S(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 s=await this.#i(e);s&&(a.context=s);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{T as ClientDispatch};
1
+ var e=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}};function t(e){if(e.length===0)return`0:empty`;let t=e.map(e=>[e.name,e.description??``,e.parametersSchema?JSON.stringify(e.parametersSchema):``,e.origin??``,e.annotations?JSON.stringify(e.annotations):``].join(``)).sort();return`${e.length}:${r(t.join(``))}`}function n(e,t){let n=3735928559^t,r=1103547991^t;for(let t=0;t<e.length;t++){let i=e.charCodeAt(t);n=Math.imul(n^i,2654435761),r=Math.imul(r^i,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function r(e){return`${n(e,0).toString(36)}.${n(e,2654435761).toString(36)}`}var i=e((()=>{})),a,o,s,c,l=e((()=>{a=e=>e.replace(/[^a-zA-Z0-9_]/g,`_`).toLowerCase().replace(/_+/g,`_`).replace(/^_|_$/g,``),o=e=>typeof e==`object`&&!!e&&!Array.isArray(e),s=e=>{if(e.variant!==`tool`)return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=a(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:o(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},c=(e,t)=>{let n=[],r=[],i=[],a=``,o,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=s(l);if(e){let t=l.agentMetadata?.clientToolAnswer?.batch;r.length>0&&(t===void 0||t!==o)&&c(),r.length===0&&(a=l.createdAt,o=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}})),u,d,f=e((()=>{u=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`,`image/svg+xml`,`image/bmp`],d=[`application/pdf`,`text/plain`,`text/markdown`,`text/csv`,`application/msword`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/vnd.ms-excel`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/json`],[...u,...d]}));function p(e,t=e.contentParts??e.llmContent??e.rawContent??e.content){let n=e.content;if(typeof n!=`string`)return;let r=e.contentParts??e.llmContent??e.rawContent??n;if(n===``&&(t===r||JSON.stringify(t)===JSON.stringify(r)))return;let i=t;if(typeof i!=`string`||i!==n)return n}var m=e((()=>{f()})),h,g=e((()=>{h=e=>e.localOnly===!0||e.role===`assistant`&&typeof e.id==`string`&&e.id.startsWith(`reconnect-failed-`)})),_=`4.34.0`,v,y=e((()=>{v=_})),b,x,S,C,w,T;e((()=>{i(),l(),m(),g(),y(),b=e=>e.voiceCaption||h(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),x=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,S=e=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),C=e=>{let t=e.agentMetadata?.providerPhase??e.agentMetadata?.phase;return e.role===`assistant`&&(t===`commentary`||t===`partial_answer`||t===`final_answer`)?{phase:t}:{}},w=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt,...C(e)}),T=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(e,n,r,i){let a=!!(n&&n.length>0),o=a?t(n):void 0,s=this.host.clientToolsFingerprintSessionId===e,c=a&&s&&this.host.lastSentClientToolsFingerprint===o,l=!a&&i?.emptyMeansReplace===!0&&this.host.sentNonEmptyClientToolsSessionId===e,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=e,a?this.host.sentNonEmptyClientToolsSessionId=e:l&&(this.host.sentNonEmptyClientToolsSessionId=null)}}}async createClientSession(e){let t=this.host.isHistoryCapable()&&!e.omitVisitorFields,n=!e.omitVisitorFields,r=null;(t||n)&&(await this.host.historyInternals.historyBootstrapReady,r=await this.host.readVisitorToken());let i=this.host.routing(),a=i.agentId??i.flowId,o=t||e.durableResume?e.conversationId:void 0,s={token:this.host.config.clientToken,...a&&{flowId:a},...t&&{visitorHistory:!0},...n&&{durableRecovery:!0},...(t||n)&&r?{visitorToken:r}:{},...t&&e.identityProof?{identityProof:e.identityProof}:{},...o?{conversationId:o}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let c=await fetch(this.host.getClientApiUrl(`init`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":v},body:JSON.stringify(s),signal:e.signal});if(!c.ok){let n=await c.json().catch(()=>({error:`Session initialization failed`}));if(t&&c.status===403&&n.error===`visitor_history_disabled`){if(this.host.markHistoryUnavailable(),o)throw new this.host.HistoryClientError(`history_disabled`,`Visitor history is disabled for this surface`);return this.createClientSession({...e,omitVisitorFields:!0})}throw c.status===403&&n.error===`durable_recovery_disabled`?new this.host.HistoryClientError(`history_disabled`,`Durable recovery is disabled for this surface`):(t||e.durableResume)&&c.status===401&&n.error===`visitor_required`?new this.host.HistoryClientError(`visitor_required`,`Visitor credential no longer resolves`):o&&c.status===404?new this.host.HistoryClientError(`not_found`,`Conversation not found`):c.status===401?Error(`Invalid client token: ${n.hint||n.error}`):c.status===403?Error(`Origin not allowed: ${n.hint||n.error}`):Error(n.error||`Failed to initialize session`)}let l=await c.json();return l.visitor?.token&&await this.host.historyInternals.visitorStore?.set(l.visitor.token),{sessionId:l.sessionId,expiresAt:new Date(l.expiresAt),flow:l.flow,...l.conversationId?{conversationId:l.conversationId}:{},...l.targetId?{targetId:l.targetId}:{},...l.conversationRevision?{conversationRevision:l.conversationRevision}:{},...l.durableRecovery?{durableRecovery:l.durableRecovery}:{},...l.visitor?{visitor:l.visitor}:{},config:{welcomeMessage:l.config.welcomeMessage,placeholder:l.config.placeholder,theme:l.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 t={...e,...this.host.config.clientToken&&{token:this.host.config.clientToken}},n=await fetch(`${this.host.clientApiBase()}/v1/client/feedback`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":v},body:JSON.stringify(t)});if(!n.ok){let e=await n.json().catch(()=>({error:`Feedback submission failed`}));throw n.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,t,n){let{HistoryClientError:r}=this.host,i=()=>this.host.isCurrentTurn(n),a=e=>{i()&&t(e)};try{let t=()=>{if(e.signal?.throwIfAborted(),!i())throw new DOMException(`Turn superseded`,`AbortError`)},o=this.host.clientSession??await this.host.initSession();t();let s=async()=>{t();let n=o,r=n.durableRecovery?.enabled===!0;if(r&&(!n.conversationId||!await this.host.readVisitorToken()))throw Error(`Renewing this conversation requires its visitor credential.`);t();let i=await this.host.createClientSession({...r||this.host.isHistoryCapable()?{conversationId:n.conversationId,durableResume:r}:{storedSessionId:n.sessionId},signal:e.signal});if(t(),n.conversationId&&i.conversationId!==n.conversationId||r&&i.durableRecovery?.enabled!==!0)throw Error(`Session renewal did not preserve this conversation.`);o=this.host.finishInit(i,n.conversationId??null,!1),this.host.clientSession=o,this.host.resetSessionWarmLatch(),this.host.resetClientToolsFingerprint(),this.host.config.onSessionInit?.(o)};Date.now()>=o.expiresAt.getTime()-6e4&&await s();let c=new Map(S(e.messages).map(e=>[e,this.#s(e)])),l=await this.#l(e.messages,void 0,c),u=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([e])=>e!==`sessionId`&&e!==`session_id`)):void 0,d=this.host.isHistoryCapable(),f={sessionId:o.sessionId,messages:S(e.messages).flatMap(e=>{let t=c.get(e);if(!t)return[];let n=d?p(e,t.content):void 0;return[{id:e.id,role:t.role,content:t.content,...n!==void 0&&{displayContent:n}}]}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context},turnId:n,...e.interrupt&&{submitMode:`interrupt`},...e.voiceSpoken&&{voice:{spoken:!0,...e.voicePriorToolResults?.length&&{priorToolResults:e.voicePriorToolResults}}}},m=async()=>{t();let n=o.durableRecovery?.enabled===!0?await this.host.readVisitorToken():null;return t(),this.host.sendWithClientToolsDiff(o.sessionId,l.clientTools,async r=>{t();let i=await this.host.resolveChatIdentityProof(e.signal);t();let a={...f,sessionId:o.sessionId,...r,...i&&{identityProof:i}};return this.host.debug&&console.debug(`[AgentWidgetClient] client token dispatch`,{...a,...i&&{identityProof:{provider:i.provider,token:`[REDACTED]`}}}),fetch(this.host.getClientApiUrl(`chat`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":v,...n?{"X-Visitor-Token":n}:{}},body:JSON.stringify(a),signal:e.signal})})},h=await m();if(t(),h.response.status===401){let e=await h.response.clone().json().catch(()=>null);t(),e?.error===`Session not found or expired`&&(await s(),h=await m(),t())}let{response:g,commit:_}=h;if(!g.ok){let e=await g.json().catch(()=>({error:`Chat request failed`}));if(g.status===401&&e.error===`invalid_identity_proof`){let e=new r(`invalid_identity_proof`,`The identity proof was rejected`);throw a({type:`error`,error:e}),e}if(g.status===401){this.host.clearClientSession(),this.host.config.onSessionExpired?.();let e=/* @__PURE__ */ Error(`Session expired. Please refresh to continue.`);throw a({type:`error`,error:e}),e}if(g.status===429){let t=Error(e.hint||`Message limit reached for this session.`);throw a({type:`error`,error:t}),t}if(g.status===410&&e.error===`conversation_deleted`){let e=new r(`conversation_deleted`,`This conversation was deleted`);throw a({type:`error`,error:e}),e}let t=Error(e.error||`Failed to send message`);throw a({type:`error`,error:t}),t}if(!g.body){let e=/* @__PURE__ */ Error(`No response body received`);throw a({type:`error`,error:e}),e}_(),a({type:`status`,status:`connected`});try{await this.host.streamResponse(g.body,a,e.assistantMessageId,void 0,e.signal)}finally{a({type:`status`,status:`idle`})}}catch(e){let t=e instanceof Error?e:Error(String(e));throw t instanceof r||t.message.includes(`Session expired`)||t.message.includes(`Message limit`)||a({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(!b(e))return null;let t=e.contentParts??e.llmContent??e.rawContent??e.content,n=e.role===`operator`?null:w(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)||!x(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=c(S(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 s=await this.#i(e);return s&&(a.context=s),a}async#l(e,t,n){let r=c(S(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 s=await this.#i(e);s&&(a.context=s);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{T as ClientDispatch};
@@ -1 +1 @@
1
- var e=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},t=`4.33.0`,n,r=e((()=>{n=t}));function i(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 a(e,t){return t||e.config.features?.history?.scope||(e.config.getIdentityProof?`verified-user`:`browser`)}async function o(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 s(e,t,n,r){if(t.visitor?.endUserId!=null)return t;let i=await e.reinitWithProof(n);if(i.visitor?.identityStatus!==`admitted`||i.visitor?.endUserId==null)throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,C);return i}async function c(e,t){let n=await t.json().catch(()=>({}));return typeof n.error==`string`?n.error:typeof n.message==`string`?n.message:``}async function l(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`,w);if(i.includes(`visitor token required`))throw new e.HistoryClientError(`visitor_token_missing`,T);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`,E);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 u(e,t,n){let r=await c(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`,C);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`,w)):t.includes(`visitor token required`)?new e.HistoryClientError(`visitor_token_missing`,T):t.includes(`visitor_identity_mismatch`)?new e.HistoryClientError(`visitor_identity_mismatch`,E):new e.HistoryClientError(`unauthorized`,r||`History request was not authorized`)}return new e.HistoryClientError(`request_failed`,r||`History request failed (${t.status})`)}function d(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 f(e,t,r){p(e);let f=r.trackIdentity!==!1,m=await e.initSession(),h=null;a(e,r.scope)===`verified-user`&&(h=await o(e,m,f),h&&(m=await s(e,m,h,f)));let g=e.historyInternals.visitorStore,_=!1;for(;;){let a=g?.revision()??0,o=await e.readVisitorToken();if(!o&&!r.visitorTokenOptional)throw new e.HistoryClientError(`visitor_token_missing`,`No visitor credential is stored for this browser`);let s=await fetch(i(e,t,{...r.query,sessionId:m.sessionId}),{method:r.method,headers:{"X-Persona-Version":n,...o?{"X-Visitor-Token":o}:{},...h?{"X-Identity-Proof":h}:{},...r.body===void 0?{}:{"Content-Type":`application/json`}},...r.body===void 0?{}:{body:JSON.stringify(r.body)},...r.keepalive?{keepalive:!0}:{}});if(s.status===401&&!_){_=!0,m=await l(e,await c(e,s),h,f);continue}if(!s.ok)throw await u(e,s,f);let p=s.headers.get(`X-History-Identity-Status`),v=await s.json().catch(()=>void 0);if(g&&g.revision()!==a)throw new e.HistoryClientError(`credential_changed`,`The visitor credential changed while the request was in flight`);return d(e,p,h!==null,f),v}}function p(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 m(e,t){let n=await f(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(S),nextCursor:typeof n?.nextCursor==`string`?n.nextCursor:null}}async function h(e,t,n){let r=await f(e,`conversations/${encodeURIComponent(t)}`,{method:`GET`,query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:S(r),messages:Array.isArray(r?.messages)?r.messages:[],nextMessageCursor:typeof r?.nextMessageCursor==`string`?r.nextMessageCursor:null,conversationRevision:typeof r?.conversationRevision==`string`?r.conversationRevision:null}}async function g(e,t,n){p(e);let r=0;for(let t of n){let n=t.displayContent.length;if(n>b)throw new e.HistoryClientError(`payload_too_large`,`displayContent exceeds the ${b} character limit`);r+=n}if(r>x)throw new e.HistoryClientError(`payload_too_large`,`Display projection batch exceeds the ${x} character limit`);await e.initSession();let i=e.historyInternals.visitorStore,a=i?.revision()??0,o=await f(e,`conversations/${encodeURIComponent(t)}/display-projections`,{method:`PATCH`,body:{messages:n},scope:`browser`,keepalive:r<=x,trackIdentity:!1}),s=typeof o?.conversationRevision==`string`?o.conversationRevision:null;return s&&e.clientSession?.conversationId===t&&(i?.revision()??0)===a&&e.historyInternals.setStoredConversationRevision?.(s),{conversationRevision:s}}async function _(e,t,n){let r=await f(e,`conversations/${encodeURIComponent(t)}`,{method:`DELETE`,...n?.scope?{scope:n.scope}:{}});return{deleted:typeof r?.deleted==`number`?r.deleted:0}}async function v(e,t){let n=await f(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 y(e){p(e),e.setHistoryIdentityStatus({state:`resetting`});try{await f(e,`visitor/reset`,{method:`POST`,scope:`browser`,visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}var b,x,S,C,w,T,E;e((()=>{r(),b=32768,x=49152,S=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:``}},C=`The identity proof was not admitted; account history is unavailable`,w=`The identity proof was rejected`,T=`The request carried no visitor credential`,E=`The stored visitor belongs to a different signed-in user`}))();export{v as deleteAllConversations,_ as deleteConversation,g as finalizeDisplayProjections,h as getConversation,u as historyErrorFor,m as listConversations,c as readErrorCode,l as recoverFromUnauthorized,y as resetVisitor};
1
+ var e=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},t=`4.34.0`,n,r=e((()=>{n=t}));function i(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 a(e,t){return t||e.config.features?.history?.scope||(e.config.getIdentityProof?`verified-user`:`browser`)}async function o(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 s(e,t,n,r){if(t.visitor?.endUserId!=null)return t;let i=await e.reinitWithProof(n);if(i.visitor?.identityStatus!==`admitted`||i.visitor?.endUserId==null)throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,C);return i}async function c(e,t){let n=await t.json().catch(()=>({}));return typeof n.error==`string`?n.error:typeof n.message==`string`?n.message:``}async function l(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`,w);if(i.includes(`visitor token required`))throw new e.HistoryClientError(`visitor_token_missing`,T);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`,E);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 u(e,t,n){let r=await c(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`,C);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`,w)):t.includes(`visitor token required`)?new e.HistoryClientError(`visitor_token_missing`,T):t.includes(`visitor_identity_mismatch`)?new e.HistoryClientError(`visitor_identity_mismatch`,E):new e.HistoryClientError(`unauthorized`,r||`History request was not authorized`)}return new e.HistoryClientError(`request_failed`,r||`History request failed (${t.status})`)}function d(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 f(e,t,r){p(e);let f=r.trackIdentity!==!1,m=await e.initSession(),h=null;a(e,r.scope)===`verified-user`&&(h=await o(e,m,f),h&&(m=await s(e,m,h,f)));let g=e.historyInternals.visitorStore,_=!1;for(;;){let a=g?.revision()??0,o=await e.readVisitorToken();if(!o&&!r.visitorTokenOptional)throw new e.HistoryClientError(`visitor_token_missing`,`No visitor credential is stored for this browser`);let s=await fetch(i(e,t,{...r.query,sessionId:m.sessionId}),{method:r.method,headers:{"X-Persona-Version":n,...o?{"X-Visitor-Token":o}:{},...h?{"X-Identity-Proof":h}:{},...r.body===void 0?{}:{"Content-Type":`application/json`}},...r.body===void 0?{}:{body:JSON.stringify(r.body)},...r.keepalive?{keepalive:!0}:{}});if(s.status===401&&!_){_=!0,m=await l(e,await c(e,s),h,f);continue}if(!s.ok)throw await u(e,s,f);let p=s.headers.get(`X-History-Identity-Status`),v=await s.json().catch(()=>void 0);if(g&&g.revision()!==a)throw new e.HistoryClientError(`credential_changed`,`The visitor credential changed while the request was in flight`);return d(e,p,h!==null,f),v}}function p(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 m(e,t){let n=await f(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(S),nextCursor:typeof n?.nextCursor==`string`?n.nextCursor:null}}async function h(e,t,n){let r=await f(e,`conversations/${encodeURIComponent(t)}`,{method:`GET`,query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:S(r),messages:Array.isArray(r?.messages)?r.messages:[],nextMessageCursor:typeof r?.nextMessageCursor==`string`?r.nextMessageCursor:null,conversationRevision:typeof r?.conversationRevision==`string`?r.conversationRevision:null}}async function g(e,t,n){p(e);let r=0;for(let t of n){let n=t.displayContent.length;if(n>b)throw new e.HistoryClientError(`payload_too_large`,`displayContent exceeds the ${b} character limit`);r+=n}if(r>x)throw new e.HistoryClientError(`payload_too_large`,`Display projection batch exceeds the ${x} character limit`);await e.initSession();let i=e.historyInternals.visitorStore,a=i?.revision()??0,o=await f(e,`conversations/${encodeURIComponent(t)}/display-projections`,{method:`PATCH`,body:{messages:n},scope:`browser`,keepalive:r<=x,trackIdentity:!1}),s=typeof o?.conversationRevision==`string`?o.conversationRevision:null;return s&&e.clientSession?.conversationId===t&&(i?.revision()??0)===a&&e.historyInternals.setStoredConversationRevision?.(s),{conversationRevision:s}}async function _(e,t,n){let r=await f(e,`conversations/${encodeURIComponent(t)}`,{method:`DELETE`,...n?.scope?{scope:n.scope}:{}});return{deleted:typeof r?.deleted==`number`?r.deleted:0}}async function v(e,t){let n=await f(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 y(e){p(e),e.setHistoryIdentityStatus({state:`resetting`});try{await f(e,`visitor/reset`,{method:`POST`,scope:`browser`,visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}var b,x,S,C,w,T,E;e((()=>{r(),b=32768,x=49152,S=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:``}},C=`The identity proof was not admitted; account history is unavailable`,w=`The identity proof was rejected`,T=`The request carried no visitor credential`,E=`The stored visitor belongs to a different signed-in user`}))();export{v as deleteAllConversations,_ as deleteConversation,g as finalizeDisplayProjections,h as getConversation,u as historyErrorFor,m as listConversations,c as readErrorCode,l as recoverFromUnauthorized,y as resetVisitor};
@@ -1 +1 @@
1
- var e,t=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},n=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),r=t(()=>{e=e=>e.startsWith("webmcp:")});function a(e){return"card"===e?"collapsed":e}function i(e){return e.split(";",1)[0].trim().toLowerCase()}function o(e,t){return function(e,t){let n=e?.display,r="string"==typeof n?{default:n}:n??{};if(t.file&&r.files){if("string"==typeof r.files)return{mode:a(r.files),matchedBy:{type:"files"}};let e=t.file.mimeType?i(t.file.mimeType):void 0,n=e?function(e,t){if(!e)return;let n=Object.entries(e);for(let[e,r]of n)if(i(e)===t)return{mode:a(r),selector:i(e)};let r=`${t.split("/",1)[0]}/*`;for(let[e,t]of n)if(i(e)===r)return{mode:a(t),selector:r}}(r.files.byMediaType,e):void 0;if(e&&n)return{mode:n.mode,matchedBy:{type:"mediaType",mediaType:e,selector:n.selector}};if(r.files.default)return{mode:a(r.files.default),matchedBy:{type:"files"}}}let o=r.byKind?.[t.artifactType];if(o)return{mode:a(o),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=r.byType?.[t.artifactType];if(s)return{mode:a(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let l=t.presentation?.preferredMode;return l?{mode:a(l),matchedBy:{type:"preferredMode"}}:r.default?{mode:a(r.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}(e,t).mode}function s(e,t){return JSON.stringify({component:"inline"===e?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},..."inline"===e&&t.component?{component:t.component}:{},..."inline"===e&&t.componentProps?{componentProps:t.componentProps}:{},...void 0===t.markdown?{}:{markdown:t.markdown}}})}var l,d,p,u,c,f,g,m,y,h,I=t(()=>{}),w=n(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.ALL=e.COLLECTION=e.ATOM=e.SPECIAL=e.INF=e._INFINITY=e.INFINITY=e.NAN=e.BOOL=e.NULL=e.OBJ=e.ARR=e.NUM=e.STR=void 0,e.STR=1,e.NUM=2,e.ARR=4,e.OBJ=8,e.NULL=16,e.BOOL=32,e.NAN=64,e.INFINITY=128,e._INFINITY=256,e.INF=e.INFINITY|e._INFINITY,e.SPECIAL=e.NULL|e.BOOL|e.INF|e.NAN,e.ATOM=e.STR|e.NUM|e.SPECIAL,e.COLLECTION=e.ARR|e.OBJ,e.ALL=e.ATOM|e.COLLECTION,e.Allow={STR:e.STR,NUM:e.NUM,ARR:e.ARR,OBJ:e.OBJ,NULL:e.NULL,BOOL:e.BOOL,NAN:e.NAN,INFINITY:e.INFINITY,_INFINITY:e._INFINITY,INF:e.INF,SPECIAL:e.SPECIAL,ATOM:e.ATOM,COLLECTION:e.COLLECTION,ALL:e.ALL},e.default=e.Allow}),v=n(e=>{var t=e&&e.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var a=Object.getOwnPropertyDescriptor(t,n);(!a||("get"in a?!t.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,a)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),n=e&&e.__exportStar||function(e,n){for(var r in e)"default"!==r&&!Object.prototype.hasOwnProperty.call(n,r)&&t(n,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;let r=w();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return r.Allow}}),n(w(),e);var a=class extends Error{};e.PartialJSON=a;var i=class extends Error{};function o(e,t=r.Allow.ALL){if("string"!=typeof e)throw TypeError("expecting str, got "+typeof e);if(!e.trim())throw Error(`${e} is empty`);return s(e.trim(),t)}e.MalformedJSON=i,e.parseJSON=o;let s=(e,t)=>{let n=e.length,o=0,s=e=>{throw new a(`${e} at position ${o}`)},l=e=>{throw new i(`${e} at position ${o}`)},d=()=>(g(),o>=n&&s("Unexpected end of input"),'"'===e[o]?p():"{"===e[o]?u():"["===e[o]?c():"null"===e.substring(o,o+4)||r.Allow.NULL&t&&n-o<4&&"null".startsWith(e.substring(o))?(o+=4,null):"true"===e.substring(o,o+4)||r.Allow.BOOL&t&&n-o<4&&"true".startsWith(e.substring(o))?(o+=4,!0):"false"===e.substring(o,o+5)||r.Allow.BOOL&t&&n-o<5&&"false".startsWith(e.substring(o))?(o+=5,!1):"Infinity"===e.substring(o,o+8)||r.Allow.INFINITY&t&&n-o<8&&"Infinity".startsWith(e.substring(o))?(o+=8,1/0):"-Infinity"===e.substring(o,o+9)||r.Allow._INFINITY&t&&1<n-o&&n-o<9&&"-Infinity".startsWith(e.substring(o))?(o+=9,-1/0):"NaN"===e.substring(o,o+3)||r.Allow.NAN&t&&n-o<3&&"NaN".startsWith(e.substring(o))?(o+=3,NaN):f()),p=()=>{let a=o,i=!1;for(o++;o<n&&('"'!==e[o]||i&&"\\"===e[o-1]);)i="\\"===e[o]&&!i,o++;if('"'==e.charAt(o))try{return JSON.parse(e.substring(a,++o-Number(i)))}catch(e){l(String(e))}else if(r.Allow.STR&t)try{return JSON.parse(e.substring(a,o-Number(i))+'"')}catch{return JSON.parse(e.substring(a,e.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},u=()=>{o++,g();let a={};try{for(;"}"!==e[o];){if(g(),o>=n&&r.Allow.OBJ&t)return a;let i=p();g(),o++;try{a[i]=d()}catch(e){if(r.Allow.OBJ&t)return a;throw e}g(),","===e[o]&&o++}}catch{if(r.Allow.OBJ&t)return a;s("Expected '}' at end of object")}return o++,a},c=()=>{o++;let n=[];try{for(;"]"!==e[o];)n.push(d()),g(),","===e[o]&&o++}catch{if(r.Allow.ARR&t)return n;s("Expected ']' at end of array")}return o++,n},f=()=>{if(0===o){"-"===e&&l("Not sure what '-' is");try{return JSON.parse(e)}catch(n){if(r.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}l(String(n))}}let a=o;for("-"===e[o]&&o++;e[o]&&-1===",]}".indexOf(e[o]);)o++;o==n&&!(r.Allow.NUM&t)&&s("Unterminated number literal");try{return JSON.parse(e.substring(a,o))}catch{"-"===e.substring(a,o)&&s("Not sure what '-' is");try{return JSON.parse(e.substring(a,e.lastIndexOf("e")))}catch(e){l(String(e))}}},g=()=>{for(;o<n&&" \n\r\t".includes(e[o]);)o++};return d()};e.parse=o}),x=t(()=>{v(),l=e=>{try{let t=JSON.parse(e);if(t&&"object"==typeof t&&"string"==typeof t.text)return t.text}catch{return null}return null}}),N=t(()=>{v(),d="ask_user_question"}),b=t(()=>{u={name:"suggest_replies",description:"Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the last action after your reply text is complete. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts in the user's voice (e.g. \"Tell me more about pricing\"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.",parametersSchema:p={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},origin:"sdk",annotations:{readOnlyHint:!0}},c=e=>{let t=e?.suggestions?.followUps?.maxItems,n="number"==typeof t&&Number.isFinite(t)?Math.max(1,Math.floor(t)):e?.future?.v5Defaults?5:4;return 4===n?u:{...u,parametersSchema:{...p,properties:{suggestions:{...p.properties.suggestions,maxItems:n,description:`1-${n} short, distinct follow-up replies, phrased in the user's voice.`}}}}},f=new Set,g=(e,t,n)=>{let r=`${e}:${t}:${n}`;f.has(r)||(f.add(r),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},m=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,r=e=>{let r=t?.[e],a=n?.[e];void 0!==r&&void 0!==a&&r!==a&&g(e,a,r)};e&&(r("enabled"),r("expose"));let a=t?.enabled??n?.enabled??!0;return{enabled:a,expose:a?t?.expose??n?.expose??!1:!1}}}),A=t(()=>{N(),b(),y={name:d,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:{type:"object",properties:{questions:{type:"array",minItems:1,maxItems:8,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},origin:"sdk",annotations:{readOnlyHint:!0}},h=e=>{let t=[],n=e?.features?.askUserQuestion;return!0===n?.expose&&!1!==n.enabled&&t.push(y),m(e).expose&&t.push(c(e)),t}}),T=t(()=>{});async function S(e,t,n,r){let a={"Content-Type":"application/json",...e.headers};e.getHeaders&&Object.assign(a,await e.getHeaders());let i={executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0},o=(t,n)=>fetch(`${e.clientApiBase()}${t}`,{method:"POST",headers:a,body:JSON.stringify({...n,...i})}),s=`/v1/agents/${t.agentId}/approve`;if(!e.isClientTokenMode())return o(s);let{sessionId:l}=await e.initSession(),d=await o("/v1/client/approve",{sessionId:l,...r?.assistantMessageId?{assistantMessageId:r.assistantMessageId}:{}});if(404===d.status){let e=await d.clone().json().catch(()=>null);if(!e||"Not Found"===e.error)return o(s)}return d}async function O(e,t,n,r){let a,i=e.isClientTokenMode(),o=i?e.getClientApiUrl("resume"):`${e.config.apiUrl?.replace(/\/+$/,"")||"https://api.runtype.com"}/resume`,s=null;if(i){let t=await e.initSession();a=t.sessionId,!0===t.durableRecovery?.enabled&&(s=await e.readVisitorToken())}let l={"Content-Type":"application/json",...s?{"X-Visitor-Token":s}:{},...e.headers};e.getHeaders&&Object.assign(l,await e.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:r?.streamResponse??!0,...r?.after?{after:r.after}:{}};if(a&&(d.sessionId=a,r?.assistantMessageId&&(d.assistantMessageId=r.assistantMessageId)),i&&a){let t=[...h(e.config),...await((await e.getWebMcpBridge())?.snapshotForDispatch())??[]],{response:n,commit:i}=await e.sendWithClientToolsDiff(a,t,t=>{let n={...d,...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&&i(),n}return fetch(o,{method:"POST",headers:l,body:JSON.stringify(d),signal:r?.signal})}var C,M,k=t(()=>{A(),T()});function _(e){let t=e.toLowerCase(),n="text/plain"===t?"txt":"text/markdown"===t?"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&&"octet-stream"!==e&&/^[a-z0-9.+-]+$/i.test(e))return`attachment.${e}`}return"attachment"}function L(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(!n)return t;if(!r)return e;let a=M(n);if(!M(r))return e;if(!a||r.startsWith(n))return t;let i=l(e);return null!==l(t)&&null===i?t:e}async function E(e,t,n,r,a,i,o){if(!e.parseSSEEvent)return!1;try{let s=await e.parseSSEEvent(t);if(null===s)return!1;let l=e=>{let t={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!0,variant:"assistant",sequence:i(),...void 0!==e&&{partId:e}};return r.current=t,a(t),t},d=e=>r.current?r.current:l(e);if(void 0!==s.text){void 0!==s.partId&&null!==o.current&&s.partId!==o.current&&(r.current&&(r.current.streaming=!1,a(r.current)),l(s.partId)),void 0!==s.partId&&(o.current=s.partId);let e=d(s.partId);void 0!==s.partId&&!e.partId&&(e.partId=s.partId),e.content+=s.text,a(e)}return s.done&&(r.current&&(r.current.streaming=!1,a(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 P(t,n,r,a,i,d,p,u){let c=t.streamGeneration(),f=n.getReader();t.streamReaders.add(f);let g=!!t.config().backgroundConversations,m=()=>{g&&f.cancel().catch(()=>{})};d?.addEventListener("abort",m,{once:!0});let y=new TextDecoder,h="",I=Date.now(),w=0,v=()=>I+w++,x=e=>({...e,chunks:e.chunks?[...e.chunks]:void 0}),N=e=>({...e,reasoning:e.reasoning?{...e.reasoning,chunks:[...e.reasoning.chunks]}:void 0,toolCall:e.toolCall?x(e.toolCall):void 0,tools:e.tools?.map(x)}),b=e=>{!d?.aborted&&c===t.streamGeneration()&&(e=>{if("assistant"!==e.role||e.variant)return!0;let t=Array.isArray(e.contentParts)&&e.contentParts.length>0,n="string"==typeof e.rawContent&&""!==e.rawContent.trim();return"string"==typeof e.content&&""!==e.content.trim()||t||n||!!e.stopReason})(e)&&r({type:"message",message:N(e)})},A=null,T=null,S={current:null},O={current:null},M=null,k="",P=new Map(u?.textPhases),$=new Map,R=new Map,D=new Map,B=new Map,J=new Map,F=a,j=!1,q=p?.find(e=>e.id===a);q&&(A=N(q),A.streaming=u?.openAssistant??!0,j=!0,M=q.agentMetadata?.textBlockId??null,k=q.rawContent??q.content,T=A,u&&!u.openAssistant&&(A=null)),u&&(M=u.textBlockId,k=u.rawText,u.nestedParents.forEach(([e,t])=>$.set(e,t)),u.nestedRaw.forEach(([e,t])=>D.set(e,t)));for(let e of p??[]){"tool"===e.variant&&e.toolCall?.id&&J.set(e.toolCall.id,N(e)),"reasoning"===e.variant&&e.reasoning?.id&&B.set(e.reasoning.id,N(e));let t=e.agentMetadata?.textBlockId;t&&(R.set(t,e.id===A?.id?A:N(e)),e.agentMetadata?.phase&&P.set(t,e.agentMetadata.phase));let n=e.agentMetadata?.parentToolId;t&&n&&($.set(t,n),D.set(t,e.rawContent??e.content))}let U=()=>{if(A)return A;let e,t="";return!j&&F?(e=F,j=!0,t=i??""):e=F&&M?`${F}_${M}`:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,A={id:e,role:"assistant",content:t,createdAt:(new Date).toISOString(),streaming:!0,sequence:v()},b(A),A},W=(e,t)=>{let n=B.get(e);if(n)return n;let r={id:`reason-${e}`,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!0,variant:"reasoning",agentMetadata:{executionId:t},sequence:v(),reasoning:{id:e,status:"streaming",chunks:[]}};return B.set(e,r),b(r),r},Y=new Set,G=new Map,K=new Set;for(let e of p??[])if(e.id.startsWith("artifact-ref-")){let t=e.id.slice(13);K.add(t),G.set(t,N(e))}u?.artifactTools.forEach(e=>Y.add(e));let H=new Map;u?.artifactContent.forEach(([e,t])=>H.set(e,{...t}));let Q=e=>{if(!e)return!1;let t=e.replace(/_+/g,"_").replace(/^_|_$/g,"");return"emit_artifact_markdown"===t||"emit_artifact_component"===t},V=(e,t,n)=>{let r=J.get(e),a={...r?.agentMetadata,executionId:t??r?.agentMetadata?.executionId,iteration:n??r?.agentMetadata?.iteration??(pe||void 0)};if(r)return r.agentMetadata=a,r;let i={id:`tool-${e}`,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!0,variant:"tool",agentMetadata:a,sequence:v(),toolCall:{id:e,status:"pending"}};return J.set(e,i),b(i),i},z=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e){let t=Number(e);if(Number.isFinite(t))return t;let n=Date.parse(e);if(!Number.isNaN(n))return n}return Date.now()},X=e=>{if("string"==typeof e)return e;if(null==e)return"";try{return JSON.stringify(e)}catch{return String(e)}},Z=new Map,ee=new Map,te=(e,t)=>{let n=X(t),r=L(ee.get(e.id),n);e.rawContent=r;let a=Z.get(e.id),i=t=>{let n=e.content??"";""!==t.trim()&&(!n.trim()||t.startsWith(n)||t.trimStart().startsWith(n.trim()))&&(e.content=t)},o=()=>{let t=a?.close?.();t instanceof Promise&&t.catch(()=>{}),Z.delete(e.id),ee.delete(e.id),e.streaming=!1,b(e)};if(!a)return i(n),void o();let s=l(r);if(null!==s&&""!==s.trim())return i(s),void o();let d,p=e=>{let t="string"==typeof e?e:e?.text??null;if(null!==t&&""!==t.trim())return t;let r=a.getExtractedText();return null!==r&&""!==r.trim()?r:n};try{d=a.processChunk(r)}catch{return i(n),void o()}d instanceof Promise?d.then(e=>{i(p(e)),o()}).catch(()=>{i(n),o()}):(i(p(d)),o())},ne=null,re=p?.find(e=>e.id===u?.sealedFlowMessageId);re&&(ne=N(re));let ae,ie=(e,n,r)=>{e.rawContent=n,Z.has(e.id)||Z.set(e.id,t.createStreamParser());let a=Z.get(e.id),i=/^[{[]/.test(n.trim());i&&ee.set(e.id,n);let o=()=>{e.content+=r,ee.delete(e.id),Z.delete(e.id),e.rawContent=void 0,b(e)};if(!0===a.__isPlainTextParser)return void o();let s=t=>{let r="string"==typeof t?t:t?.text??null;null!==r&&""!==r.trim()?(e.content=r,b(e)):!i&&!n.trim().startsWith("<")&&o()},l=a.processChunk(n);l instanceof Promise?l.then(s).catch(o):s(l)},oe=(e,t)=>{let n=t??e.content;if(null==n||""===n)return e.streaming=!1,void b(e);let r=ee.get(e.id)??X(n);e.rawContent=r;let a=Z.get(e.id),i=null,o=!1;if(a&&(i=a.getExtractedText(),null===i&&(i=l(r)),null===i)){let t=a.processChunk(r);t instanceof Promise?(o=!0,t.then(t=>{let n="string"==typeof t?t:t?.text??null;null!==n&&(e.content=n,e.streaming=!1,Z.delete(e.id),ee.delete(e.id),b(e))}).catch(()=>{})):i="string"==typeof t?t:t?.text??null}if(!o){null!==i&&""!==i.trim()?e.content=i:ee.has(e.id)||(e.content=X(n));let t=Z.get(e.id);if(t){let n=t.close?.();n instanceof Promise&&n.catch(()=>{}),Z.delete(e.id)}ee.delete(e.id),e.streaming=!1,b(e)}},se=(e,t,n,r)=>{let a=R.get(e);if(a)return a;let i={id:`nested-${t}-${e}`,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!0,sequence:v(),...n?{variant:n}:{},..."reasoning"===n?{reasoning:{id:e,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:t,textBlockId:e,executionId:r,phase:P.get(e)}};return R.set(e,i),b(i),i},le=[],de=new Map;u?.media.forEach(([e,t])=>de.set(e,{...t,parts:[...t.parts]}));let pe=u?.iteration??0,ue=u?.executionKind??"agent",ce=u?.executionKindResolved??!1,fe=u?.turnId??null,ge=null,me=t.config().iterationDisplay??"separate";ae=()=>{for(let n=0;n<le.length;n++){let a=le[n];if(!ce&&"flow"!==ue&&"string"==typeof a.stepType&&(ue="flow"),"reasoning_start"===a.type){let e="string"==typeof a.id?a.id:null,t="string"==typeof a.parentToolCallId&&a.parentToolCallId?a.parentToolCallId:null;if(e&&t){$.set(e,t),se(e,t,"reasoning",a.executionId);continue}let n=a.id,r=W(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,("loop"===a.scope||"turn"===a.scope)&&(r.reasoning.scope=a.scope),r.streaming=!0,r.reasoning.status="streaming",b(r)}else if("reasoning_delta"===a.type){let e="string"==typeof a.id?a.id:null;if(e&&$.has(e)&&R.has(e)){let t=R.get(e),n=a.delta;n&&t.reasoning&&(t.reasoning.chunks.push(String(n)),b(t));continue}let t=a.id,n=W(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("reasoning_complete"===a.type){let e="string"==typeof a.id?a.id:null;if(e&&$.has(e)&&R.has(e)){let t=R.get(e);if(t.reasoning){let e="string"==typeof a.text?a.text:"";e&&0===t.reasoning.chunks.length&&t.reasoning.chunks.push(e),t.reasoning.status="complete",t.streaming=!1,b(t)}$.delete(e),R.delete(e);continue}let t=a.id,n="string"==typeof a.text?a.text:"";!B.get(t)&&(n||"loop"===a.scope)&&W(t,a.executionId);let r=B.get(t);if(r?.reasoning){("loop"===a.scope||"turn"===a.scope)&&(r.reasoning.scope=a.scope),n&&0===r.reasoning.chunks.length&&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("tool_start"===a.type){A&&=(A.streaming=!1,b(A),null),"number"==typeof a.iteration&&(pe=a.iteration);let e=a.toolCallId,t=a.toolName;if(Q(t)){Y.add(e);continue}let n=V(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,void 0!==a.parameters&&(r.args=a.parameters),r.startedAt=r.startedAt??z(a.startedAt),r.completedAt=void 0,r.durationMs=void 0,n.toolCall=r,n.streaming=!0,b(n)}else if("tool_output_delta"===a.type){let e=a.toolCallId;if(Y.has(e))continue;let t=V(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("tool_complete"===a.type){let e=a.toolCallId;if(Y.has(e)){Y.delete(e);continue}let t=V(e,a.executionId,a.iteration),n=t.toolCall??{id:e,status:"running"};n.status="complete",void 0!==a.result&&(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("number"==typeof r)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("await"===a.type&&a.toolName){let t="string"==typeof a.toolCallId&&a.toolCallId.length>0?a.toolCallId:void 0,n=t??a.toolId??`local-${v()}`,r=V(n,a.executionId),i=a.toolName,o="webmcp"===a.origin&&!e(i)?`webmcp:${i}`:i,s=e(o),l=r.toolCall??{id:n,status:"pending"};l.name=o,l.args=a.parameters,l.status=s?"running":"complete",l.chunks=l.chunks??[],l.startedAt=l.startedAt??z(a.awaitedAt),s?(l.completedAt=void 0,l.duration=void 0,l.durationMs=void 0):l.completedAt=l.completedAt??l.startedAt,r.toolCall=l,r.streaming=!1,r.agentMetadata={...r.agentMetadata,executionId:a.executionId??r.agentMetadata?.executionId,awaitingLocalTool:!0,...t?{webMcpToolCallId:t}:{}},b(r)}else if("text_start"===a.type){let e="string"==typeof a.id?a.id:null;if(e){let t=C(a.phase);t?P.set(e,t):P.delete(e)}let t="string"==typeof a.parentToolCallId&&a.parentToolCallId?a.parentToolCallId:null;if(e&&t){$.set(e,t);continue}let n=A;n&&("flow"===ue?(oe(n),ne=n):(n.streaming=!1,b(n)),A=null),M=e??M,k=""}else if("text_delta"===a.type){let e="string"==typeof a.id?a.id:null,t=e?$.get(e):void 0;if(e&&t){let n="string"==typeof a.delta?a.delta:"",r=(D.get(e)??"")+n;if(D.set(e,r),""===r.trim())continue;let i=se(e,t,void 0,a.executionId);ie(i,r,n);continue}M=e??M;let n="string"==typeof a.delta?a.delta:"";if(k+=n,"flow"===ue&&""===k.trim())continue;let r=U();r.agentMetadata={textBlockId:M??void 0,phase:P.get(M??""),executionId:a.executionId,iteration:pe,..."flow"===ue?{}:{turnId:fe??void 0,agentName:ge?.agentName}},M&&R.set(M,r),ie(r,k,n),T=r}else if("text_complete"===a.type){let e="string"==typeof a.id?a.id:null;e&&P.delete(e);let t=e?R.get(e):A,n=C(a.phase);if(t&&n&&(t.agentMetadata={...t.agentMetadata,providerPhase:n}),e&&$.has(e)){let t=R.get(e);t&&oe(t),$.delete(e),D.delete(e),R.delete(e);continue}if(e&&t!==A){t&&(t.streaming=!1,b(t));continue}let r=A;r&&("flow"===ue?(oe(r),ne=r):(""===(r.content??"")&&"string"==typeof a.text&&(r.content=a.text),r.streaming=!1,b(r)),A=null),M=null,k=""}else if("step_complete"===a.type){if("tool"===a.stepType)continue;if(!1===a.success){let e=a.error||"Step failed";r({type:"error",error:Error(e)});let t=A;t&&t.streaming&&(t.streaming=!1,b(t)),r({type:"status",status:"idle"});continue}{let e=ne;ne=null;let t=a.stopReason,n=(a.result&&"object"==typeof a.result?a.result:null)?.response;if(e)t&&(e.stopReason=t),null==n?!1!==e.streaming&&(Z.delete(e.id),ee.delete(e.id),e.streaming=!1,b(e)):te(e,n);else{let e=null!=n&&""!==n;if(e||t&&"end_turn"!==t&&"unknown"!==t){let r=U();t&&(r.stopReason=t),e?oe(r,n):(r.streaming=!1,b(r))}}continue}}else if("execution_start"===a.type)ue="flow"===a.kind?"flow":"agent",ce=!0,t.config().backgroundConversations&&r({type:"status",status:"connected",executionId:a.executionId}),"agent"===ue&&(ge={executionId:a.executionId,agentId:a.agentId??"virtual",agentName:a.agentName??""});else if("turn_start"===a.type){let e="number"==typeof a.iteration?a.iteration:pe;if(e!==pe){if("separate"===me&&e>1){let e=A;e&&(e.streaming=!1,b(e),A=null)}pe=e}fe="string"==typeof a.id?a.id:null,T=null}else if("tool_input_delta"===a.type){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("tool_input_complete"===a.type){if(Y.has(a.toolCallId))continue;let e=V(a.toolCallId,a.executionId),t=e.toolCall;t.args=a.parameters,t.name=a.toolName??t.name,b(e)}else if("turn_complete"===a.type){let e=a.stopReason,t=A??T;if(e&&null!==t){let n=a.id;(!n||t.agentMetadata?.turnId===n)&&(t.stopReason=e,b(t))}fe===a.id&&(fe=null)}else if("media_start"===a.type){let e=String(a.id);de.set(e,{mediaType:"string"==typeof a.mediaType?a.mediaType:void 0,toolCallId:a.toolCallId,parts:[]})}else if("media_delta"===a.type){let e=de.get(String(a.id));e&&"string"==typeof a.delta&&e.parts.push(a.delta)}else if("media_complete"===a.type){let e=String(a.id),t=de.get(e);de.delete(e);let n=("string"==typeof a.mediaType?a.mediaType:void 0)??t?.mediaType??"application/octet-stream",r="string"==typeof a.data?a.data:void 0,i="string"==typeof a.url?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:"image"===e||e.startsWith("image/")?"image-url":"file-url",url:i,mediaType:n}}let s=a.toolCallId??t?.toolCallId,l=o?[o]:[],d=[];for(let e of l){if(!e||"object"!=typeof e)continue;let t=e,n="string"==typeof t.type?t.type:void 0,r="string"==typeof t.mediaType?t.mediaType.toLowerCase():"",a=null,i="";if("media"===n){let e="string"==typeof t.data?t.data:void 0;if(!e)continue;i=r.length>0?r:"application/octet-stream",a=`data:${i};base64,${e}`}else if("image-url"===n){let e="string"==typeof t.url?t.url:void 0;if(!e)continue;i=r,a=e}else if("file-url"===n){let e="string"==typeof t.url?t.url:void 0;if(!e)continue;i=r,a=e}else continue;if(a)if("image-url"===n||i.startsWith("image/"))d.push({type:"image",image:a,...i.includes("/")?{mimeType:i}:{}});else if(i.startsWith("audio/"))d.push({type:"audio",audio:a,mimeType:i});else if(i.startsWith("video/"))d.push({type:"video",video:a,mimeType:i});else{let e=i||"application/octet-stream";d.push({type:"file",data:a,mimeType:e,filename:_(e)})}}if(d.length>0){let e=v(),t=s,n={id:`agent-media-${"string"==typeof t&&t.length>0?`${t}-${e}`:String(e)}`,role:"assistant",content:"",contentParts:d,createdAt:(new Date).toISOString(),streaming:!1,sequence:e,agentMetadata:{executionId:a.executionId,iteration:pe}};b(n);let r=A;r&&(r.streaming=!1,b(r)),A=null,S.current=null}}else if("execution_complete"===a.type){let e=A;e&&("flow"===a.kind&&!1!==e.streaming?oe(e):(e.streaming=!1,b(e)),A=null),M=null,k="",ne=null,r({type:"status",status:!1===a.success?"error":"idle",terminal:!0})}else if("execution_error"===a.type){let e="string"==typeof a.error?a.error:a.error?.message??"Execution error";r({type:"error",error:Error(e)})}else if("ping"!==a.type)if("approval_start"===a.type){let e=a.approvalId??`approval-${v()}`,t={id:`approval-${e}`,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!1,variant:"approval",sequence:v(),approval:{id:e,status:"pending",agentId:ge?.agentId??"virtual",executionId:a.executionId??ge?.executionId??"",toolName:a.toolName??"",toolType:a.toolType,description:a.description??`Execute ${a.toolName??"tool"}`,..."string"==typeof a.reason&&a.reason?{reason:a.reason}:{},parameters:a.parameters,..."string"==typeof a.toolCallId&&a.toolCallId?{toolCallId:a.toolCallId}:{}}};b(t)}else if("approval_complete"===a.type){let e=a.approvalId;if(e){let t={id:`approval-${e}`,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!1,variant:"approval",sequence:v(),approval:{id:e,status:a.decision??"approved",agentId:ge?.agentId??"virtual",executionId:a.executionId??ge?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};b(t)}}else if("artifact_start"===a.type||"artifact_delta"===a.type||"artifact_update"===a.type||"artifact_complete"===a.type){if("artifact_start"===a.type){let e,n=a.artifactType,i=String(a.id),l="string"==typeof a.title?a.title:void 0,d=a.file;if(d&&"object"==typeof d&&!Array.isArray(d)&&"string"==typeof d.path&&"string"==typeof d.mimeType&&(e={path:d.path,mimeType:d.mimeType,..."string"==typeof d.language?{language:d.language}:{}}),r({type:"artifact_start",id:i,artifactType:n,title:l,component:"string"==typeof a.component?a.component:void 0,...e?{file:e}:{}}),H.set(i,{markdown:"",title:l,file:e}),!K.has(i)){K.add(i);let r=o(t.config().features?.artifacts,{artifactType:n,...e?{file:e}:{}}),d="string"==typeof a.component?a.component:void 0,p={id:`artifact-ref-${i}`,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!0,sequence:v(),rawContent:s(r,{artifactId:i,title:l,artifactType:n,status:"streaming",...e?{file:e}:{},...d?{component:d}:{}})};G.set(i,p),b(p)}}else if("artifact_delta"===a.type){let e=String(a.id),t="string"==typeof a.delta?a.delta:String(a.delta??"");r({type:"artifact_delta",id:e,artDelta:t});let n=H.get(e);n&&(n.markdown+=t)}else if("artifact_update"===a.type){let e=a.props&&"object"==typeof a.props&&!Array.isArray(a.props)?a.props:{};r({type:"artifact_update",id:String(a.id),props:e,component:"string"==typeof a.component?a.component:void 0});let t=H.get(String(a.id));t&&(t.props={...t.props??{},...e})}else if("artifact_complete"===a.type){let e=String(a.id);r({type:"artifact_complete",id:e});let t=G.get(e);if(t){t.streaming=!1;try{let n=JSON.parse(t.rawContent??"{}");if(n.props){n.props.status="complete";let t=H.get(e);t?.markdown&&(n.props.markdown=t.markdown),t?.file&&(n.props.file=t.file),"PersonaArtifactInline"===n.component&&t?.props&&Object.keys(t.props).length>0&&(n.props.componentProps=t.props)}t.rawContent=JSON.stringify(n)}catch{}H.delete(e),b(t),G.delete(e)}}}else if("error"===a.type&&!1===a.recoverable&&null!=a.error&&""!==a.error){let e="string"==typeof a.error?a.error:null==a.error?.message?"Execution error":String(a.error.message);r({type:"error",error:Error(e)});let t=A;t&&t.streaming&&(t.streaming=!1,b(t)),r({type:"status",status:"idle"})}}le.length=0};try{for(;;){if(c!==t.streamGeneration())return;d?.throwIfAborted();let{done:e,value:n}=await f.read();if(c!==t.streamGeneration())return;if(d?.throwIfAborted(),e)break;h+=y.decode(n,{stream:!0});let a=h.split("\n\n");h=a.pop()??"";for(let e of a){if(c!==t.streamGeneration())return;d?.throwIfAborted();let n=e.split("\n"),a="message",i="",o=null;for(let e of n)e.startsWith("event:")?a=e.replace("event:","").trim():e.startsWith("data:")?i+=e.replace("data:","").trim():e.startsWith("id:")&&(o=e.slice(3).trim());let s,l=()=>{null!==o&&""!==o&&r({type:"cursor",id:o,...t.config().backgroundConversations?{checkpoint:{textBlockId:M,openAssistant:null!==A,sealedFlowMessageId:ne?.id??null,rawText:k,executionKind:ue,executionKindResolved:ce,turnId:fe,iteration:pe,textPhases:[...P],nestedParents:[...$],nestedRaw:[...D],media:[...de].map(([e,t])=>[e,{...t,parts:[...t.parts]}]),artifactContent:[...H].map(([e,t])=>[e,{...t,props:t.props?{...t.props}:void 0}]),artifactTools:[...Y]}}:{}})};if(!i){l();continue}try{s=JSON.parse(i)}catch(t){r({type:"error",error:t instanceof Error?t:Error("Failed to parse chat stream payload")});continue}let p="object"==typeof s&&s&&!Array.isArray(s)?s:null,u="message"===a?"string"==typeof p?.type?p.type:"message":a;if(t.onSSEEvent?.(u,s),t.parseSSEEvent){S.current=A;let e=await E(t,s,r,S,b,v,O);if(c!==t.streamGeneration())return;if(d?.throwIfAborted(),S.current&&S.current!==A&&(A=S.current),e){l();continue}}p&&(le.push({...p,type:u}),ae()),l()}}ae()}finally{t.streamReaders.delete(f),d?.removeEventListener("abort",m),f.releaseLock()}}t(()=>{r(),I(),x(),k(),C=e=>"commentary"===e||"partial_answer"===e||"final_answer"===e?e:void 0,M=e=>/^[{[<]/.test(e)})();export{L as preferFinalStructuredContent,S as resolveApproval,O as resumeFlow,P as streamResponse};
1
+ var e,t=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},n=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),r=t(()=>{e=e=>e.startsWith("webmcp:")});function a(e){return"card"===e?"collapsed":e}function i(e){return e.split(";",1)[0].trim().toLowerCase()}function o(e,t){return function(e,t){let n=e?.display,r="string"==typeof n?{default:n}:n??{};if(t.file&&r.files){if("string"==typeof r.files)return{mode:a(r.files),matchedBy:{type:"files"}};let e=t.file.mimeType?i(t.file.mimeType):void 0,n=e?function(e,t){if(!e)return;let n=Object.entries(e);for(let[e,r]of n)if(i(e)===t)return{mode:a(r),selector:i(e)};let r=`${t.split("/",1)[0]}/*`;for(let[e,t]of n)if(i(e)===r)return{mode:a(t),selector:r}}(r.files.byMediaType,e):void 0;if(e&&n)return{mode:n.mode,matchedBy:{type:"mediaType",mediaType:e,selector:n.selector}};if(r.files.default)return{mode:a(r.files.default),matchedBy:{type:"files"}}}let o=r.byKind?.[t.artifactType];if(o)return{mode:a(o),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byKind"}};let s=r.byType?.[t.artifactType];if(s)return{mode:a(s),matchedBy:{type:"kind",kind:t.artifactType,configuredBy:"byType"}};let l=t.presentation?.preferredMode;return l?{mode:a(l),matchedBy:{type:"preferredMode"}}:r.default?{mode:a(r.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}(e,t).mode}function s(e,t){return JSON.stringify({component:"inline"===e?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...t.presentation?{presentation:t.presentation}:{},..."inline"===e&&t.component?{component:t.component}:{},..."inline"===e&&t.componentProps?{componentProps:t.componentProps}:{},...void 0===t.markdown?{}:{markdown:t.markdown}}})}var l,d,p,u,c,f,g,m,y,h,I=t(()=>{}),w=n(e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.ALL=e.COLLECTION=e.ATOM=e.SPECIAL=e.INF=e._INFINITY=e.INFINITY=e.NAN=e.BOOL=e.NULL=e.OBJ=e.ARR=e.NUM=e.STR=void 0,e.STR=1,e.NUM=2,e.ARR=4,e.OBJ=8,e.NULL=16,e.BOOL=32,e.NAN=64,e.INFINITY=128,e._INFINITY=256,e.INF=e.INFINITY|e._INFINITY,e.SPECIAL=e.NULL|e.BOOL|e.INF|e.NAN,e.ATOM=e.STR|e.NUM|e.SPECIAL,e.COLLECTION=e.ARR|e.OBJ,e.ALL=e.ATOM|e.COLLECTION,e.Allow={STR:e.STR,NUM:e.NUM,ARR:e.ARR,OBJ:e.OBJ,NULL:e.NULL,BOOL:e.BOOL,NAN:e.NAN,INFINITY:e.INFINITY,_INFINITY:e._INFINITY,INF:e.INF,SPECIAL:e.SPECIAL,ATOM:e.ATOM,COLLECTION:e.COLLECTION,ALL:e.ALL},e.default=e.Allow}),v=n((e,t,n)=>{var r=n&&n.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var a=Object.getOwnPropertyDescriptor(t,n);(!a||("get"in a?!t.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,a)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),a=n&&n.__exportStar||function(e,t){for(var n in e)"default"!==n&&!Object.prototype.hasOwnProperty.call(t,n)&&r(t,e,n)};Object.defineProperty(e,"__esModule",{value:!0}),e.Allow=e.MalformedJSON=e.PartialJSON=e.parseJSON=e.parse=void 0;let i=w();Object.defineProperty(e,"Allow",{enumerable:!0,get:function(){return i.Allow}}),a(w(),e);var o=class extends Error{};e.PartialJSON=o;var s=class extends Error{};function l(e,t=i.Allow.ALL){if("string"!=typeof e)throw TypeError("expecting str, got "+typeof e);if(!e.trim())throw Error(`${e} is empty`);return d(e.trim(),t)}e.MalformedJSON=s,e.parseJSON=l;let d=(e,t)=>{let n=e.length,r=0,a=e=>{throw new o(`${e} at position ${r}`)},l=e=>{throw new s(`${e} at position ${r}`)},d=()=>(g(),r>=n&&a("Unexpected end of input"),'"'===e[r]?p():"{"===e[r]?u():"["===e[r]?c():"null"===e.substring(r,r+4)||i.Allow.NULL&t&&n-r<4&&"null".startsWith(e.substring(r))?(r+=4,null):"true"===e.substring(r,r+4)||i.Allow.BOOL&t&&n-r<4&&"true".startsWith(e.substring(r))?(r+=4,!0):"false"===e.substring(r,r+5)||i.Allow.BOOL&t&&n-r<5&&"false".startsWith(e.substring(r))?(r+=5,!1):"Infinity"===e.substring(r,r+8)||i.Allow.INFINITY&t&&n-r<8&&"Infinity".startsWith(e.substring(r))?(r+=8,1/0):"-Infinity"===e.substring(r,r+9)||i.Allow._INFINITY&t&&1<n-r&&n-r<9&&"-Infinity".startsWith(e.substring(r))?(r+=9,-1/0):"NaN"===e.substring(r,r+3)||i.Allow.NAN&t&&n-r<3&&"NaN".startsWith(e.substring(r))?(r+=3,NaN):f()),p=()=>{let o=r,s=!1;for(r++;r<n&&('"'!==e[r]||s&&"\\"===e[r-1]);)s="\\"===e[r]&&!s,r++;if('"'==e.charAt(r))try{return JSON.parse(e.substring(o,++r-Number(s)))}catch(e){l(String(e))}else if(i.Allow.STR&t)try{return JSON.parse(e.substring(o,r-Number(s))+'"')}catch{return JSON.parse(e.substring(o,e.lastIndexOf("\\"))+'"')}a("Unterminated string literal")},u=()=>{r++,g();let o={};try{for(;"}"!==e[r];){if(g(),r>=n&&i.Allow.OBJ&t)return o;let a=p();g(),r++;try{o[a]=d()}catch(e){if(i.Allow.OBJ&t)return o;throw e}g(),","===e[r]&&r++}}catch{if(i.Allow.OBJ&t)return o;a("Expected '}' at end of object")}return r++,o},c=()=>{r++;let n=[];try{for(;"]"!==e[r];)n.push(d()),g(),","===e[r]&&r++}catch{if(i.Allow.ARR&t)return n;a("Expected ']' at end of array")}return r++,n},f=()=>{if(0===r){"-"===e&&l("Not sure what '-' is");try{return JSON.parse(e)}catch(n){if(i.Allow.NUM&t)try{return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}l(String(n))}}let o=r;for("-"===e[r]&&r++;e[r]&&-1===",]}".indexOf(e[r]);)r++;r==n&&!(i.Allow.NUM&t)&&a("Unterminated number literal");try{return JSON.parse(e.substring(o,r))}catch{"-"===e.substring(o,r)&&a("Not sure what '-' is");try{return JSON.parse(e.substring(o,e.lastIndexOf("e")))}catch(e){l(String(e))}}},g=()=>{for(;r<n&&" \n\r\t".includes(e[r]);)r++};return d()};e.parse=l}),x=t(()=>{v(),l=e=>{try{let t=JSON.parse(e);if(t&&"object"==typeof t&&"string"==typeof t.text)return t.text}catch{return null}return null}}),N=t(()=>{v(),d="ask_user_question"}),b=t(()=>{u={name:"suggest_replies",description:"Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the last action after your reply text is complete. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts in the user's voice (e.g. \"Tell me more about pricing\"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.",parametersSchema:p={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},origin:"sdk",annotations:{readOnlyHint:!0}},c=e=>{let t=e?.suggestions?.followUps?.maxItems,n="number"==typeof t&&Number.isFinite(t)?Math.max(1,Math.floor(t)):e?.future?.v5Defaults?5:4;return 4===n?u:{...u,parametersSchema:{...p,properties:{suggestions:{...p.properties.suggestions,maxItems:n,description:`1-${n} short, distinct follow-up replies, phrased in the user's voice.`}}}}},f=new Set,g=(e,t,n)=>{let r=`${e}:${t}:${n}`;f.has(r)||(f.add(r),console.warn(`[persona] suggestions.followUps.${e} and features.suggestReplies.${e} disagree; suggestions.followUps.${e} wins.`))},m=e=>{let t=e?.suggestions?.followUps,n=e?.features?.suggestReplies,r=e=>{let r=t?.[e],a=n?.[e];void 0!==r&&void 0!==a&&r!==a&&g(e,a,r)};e&&(r("enabled"),r("expose"));let a=t?.enabled??n?.enabled??!0;return{enabled:a,expose:a?t?.expose??n?.expose??!1:!1}}}),A=t(()=>{N(),b(),y={name:d,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:{type:"object",properties:{questions:{type:"array",minItems:1,maxItems:8,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},origin:"sdk",annotations:{readOnlyHint:!0}},h=e=>{let t=[],n=e?.features?.askUserQuestion;return!0===n?.expose&&!1!==n.enabled&&t.push(y),m(e).expose&&t.push(c(e)),t}}),T=t(()=>{});async function S(e,t,n,r){let a={"Content-Type":"application/json",...e.headers};e.getHeaders&&Object.assign(a,await e.getHeaders());let i={executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0},o=(t,n)=>fetch(`${e.clientApiBase()}${t}`,{method:"POST",headers:a,body:JSON.stringify({...n,...i})}),s=`/v1/agents/${t.agentId}/approve`;if(!e.isClientTokenMode())return o(s);let{sessionId:l}=await e.initSession(),d=await o("/v1/client/approve",{sessionId:l,...r?.assistantMessageId?{assistantMessageId:r.assistantMessageId}:{}});if(404===d.status){let e=await d.clone().json().catch(()=>null);if(!e||"Not Found"===e.error)return o(s)}return d}async function O(e,t,n,r){let a,i=e.isClientTokenMode(),o=i?e.getClientApiUrl("resume"):`${e.config.apiUrl?.replace(/\/+$/,"")||"https://api.runtype.com"}/resume`,s=null;if(i){let t=await e.initSession();a=t.sessionId,!0===t.durableRecovery?.enabled&&(s=await e.readVisitorToken())}let l={"Content-Type":"application/json",...s?{"X-Visitor-Token":s}:{},...e.headers};e.getHeaders&&Object.assign(l,await e.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:r?.streamResponse??!0,...r?.after?{after:r.after}:{}};if(a&&(d.sessionId=a,r?.assistantMessageId&&(d.assistantMessageId=r.assistantMessageId)),i&&a){let t=[...h(e.config),...await((await e.getWebMcpBridge())?.snapshotForDispatch())??[]],{response:n,commit:i}=await e.sendWithClientToolsDiff(a,t,t=>{let n={...d,...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&&i(),n}return fetch(o,{method:"POST",headers:l,body:JSON.stringify(d),signal:r?.signal})}var C,M,k=t(()=>{A(),T()});function _(e){let t=e.toLowerCase(),n="text/plain"===t?"txt":"text/markdown"===t?"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&&"octet-stream"!==e&&/^[a-z0-9.+-]+$/i.test(e))return`attachment.${e}`}return"attachment"}function L(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(!n)return t;if(!r)return e;let a=M(n);if(!M(r))return e;if(!a||r.startsWith(n))return t;let i=l(e);return null!==l(t)&&null===i?t:e}async function E(e,t,n,r,a,i,o){if(!e.parseSSEEvent)return!1;try{let s=await e.parseSSEEvent(t);if(null===s)return!1;let l=e=>{let t={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!0,variant:"assistant",sequence:i(),...void 0!==e&&{partId:e}};return r.current=t,a(t),t},d=e=>r.current?r.current:l(e);if(void 0!==s.text){void 0!==s.partId&&null!==o.current&&s.partId!==o.current&&(r.current&&(r.current.streaming=!1,a(r.current)),l(s.partId)),void 0!==s.partId&&(o.current=s.partId);let e=d(s.partId);void 0!==s.partId&&!e.partId&&(e.partId=s.partId),e.content+=s.text,a(e)}return s.done&&(r.current&&(r.current.streaming=!1,a(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 P(t,n,r,a,i,d,p,u){let c=t.streamGeneration(),f=n.getReader();t.streamReaders.add(f);let g=!!t.config().backgroundConversations,m=()=>{g&&f.cancel().catch(()=>{})};d?.addEventListener("abort",m,{once:!0});let y=new TextDecoder,h="",I=Date.now(),w=0,v=()=>I+w++,x=e=>({...e,chunks:e.chunks?[...e.chunks]:void 0}),N=e=>({...e,reasoning:e.reasoning?{...e.reasoning,chunks:[...e.reasoning.chunks]}:void 0,toolCall:e.toolCall?x(e.toolCall):void 0,tools:e.tools?.map(x)}),b=e=>{!d?.aborted&&c===t.streamGeneration()&&(e=>{if("assistant"!==e.role||e.variant)return!0;let t=Array.isArray(e.contentParts)&&e.contentParts.length>0,n="string"==typeof e.rawContent&&""!==e.rawContent.trim();return"string"==typeof e.content&&""!==e.content.trim()||t||n||!!e.stopReason})(e)&&r({type:"message",message:N(e)})},A=null,T=null,S={current:null},O={current:null},M=null,k="",P=new Map(u?.textPhases),$=new Map,R=new Map,D=new Map,B=new Map,J=new Map,F=a,j=!1,q=p?.find(e=>e.id===a);q&&(A=N(q),A.streaming=u?.openAssistant??!0,j=!0,M=q.agentMetadata?.textBlockId??null,k=q.rawContent??q.content,T=A,u&&!u.openAssistant&&(A=null)),u&&(M=u.textBlockId,k=u.rawText,u.nestedParents.forEach(([e,t])=>$.set(e,t)),u.nestedRaw.forEach(([e,t])=>D.set(e,t)));for(let e of p??[]){"tool"===e.variant&&e.toolCall?.id&&J.set(e.toolCall.id,N(e)),"reasoning"===e.variant&&e.reasoning?.id&&B.set(e.reasoning.id,N(e));let t=e.agentMetadata?.textBlockId;t&&(R.set(t,e.id===A?.id?A:N(e)),e.agentMetadata?.phase&&P.set(t,e.agentMetadata.phase));let n=e.agentMetadata?.parentToolId;t&&n&&($.set(t,n),D.set(t,e.rawContent??e.content))}let U=()=>{if(A)return A;let e,t="";return!j&&F?(e=F,j=!0,t=i??""):e=F&&M?`${F}_${M}`:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,A={id:e,role:"assistant",content:t,createdAt:(new Date).toISOString(),streaming:!0,sequence:v()},b(A),A},W=(e,t)=>{let n=B.get(e);if(n)return n;let r={id:`reason-${e}`,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!0,variant:"reasoning",agentMetadata:{executionId:t},sequence:v(),reasoning:{id:e,status:"streaming",chunks:[]}};return B.set(e,r),b(r),r},Y=new Set,G=new Map,K=new Set;for(let e of p??[])if(e.id.startsWith("artifact-ref-")){let t=e.id.slice(13);K.add(t),G.set(t,N(e))}u?.artifactTools.forEach(e=>Y.add(e));let H=new Map;u?.artifactContent.forEach(([e,t])=>H.set(e,{...t}));let Q=e=>{if(!e)return!1;let t=e.replace(/_+/g,"_").replace(/^_|_$/g,"");return"emit_artifact_markdown"===t||"emit_artifact_component"===t},V=(e,t,n)=>{let r=J.get(e),a={...r?.agentMetadata,executionId:t??r?.agentMetadata?.executionId,iteration:n??r?.agentMetadata?.iteration??(pe||void 0)};if(r)return r.agentMetadata=a,r;let i={id:`tool-${e}`,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!0,variant:"tool",agentMetadata:a,sequence:v(),toolCall:{id:e,status:"pending"}};return J.set(e,i),b(i),i},z=e=>{if("number"==typeof e&&Number.isFinite(e))return e;if("string"==typeof e){let t=Number(e);if(Number.isFinite(t))return t;let n=Date.parse(e);if(!Number.isNaN(n))return n}return Date.now()},X=e=>{if("string"==typeof e)return e;if(null==e)return"";try{return JSON.stringify(e)}catch{return String(e)}},Z=new Map,ee=new Map,te=(e,t)=>{let n=X(t),r=L(ee.get(e.id),n);e.rawContent=r;let a=Z.get(e.id),i=t=>{let n=e.content??"";""!==t.trim()&&(!n.trim()||t.startsWith(n)||t.trimStart().startsWith(n.trim()))&&(e.content=t)},o=()=>{let t=a?.close?.();t instanceof Promise&&t.catch(()=>{}),Z.delete(e.id),ee.delete(e.id),e.streaming=!1,b(e)};if(!a)return i(n),void o();let s=l(r);if(null!==s&&""!==s.trim())return i(s),void o();let d,p=e=>{let t="string"==typeof e?e:e?.text??null;if(null!==t&&""!==t.trim())return t;let r=a.getExtractedText();return null!==r&&""!==r.trim()?r:n};try{d=a.processChunk(r)}catch{return i(n),void o()}d instanceof Promise?d.then(e=>{i(p(e)),o()}).catch(()=>{i(n),o()}):(i(p(d)),o())},ne=null,re=p?.find(e=>e.id===u?.sealedFlowMessageId);re&&(ne=N(re));let ae,ie=(e,n,r)=>{e.rawContent=n,Z.has(e.id)||Z.set(e.id,t.createStreamParser());let a=Z.get(e.id),i=/^[{[]/.test(n.trim());i&&ee.set(e.id,n);let o=()=>{e.content+=r,ee.delete(e.id),Z.delete(e.id),e.rawContent=void 0,b(e)};if(!0===a.__isPlainTextParser)return void o();let s=t=>{let r="string"==typeof t?t:t?.text??null;null!==r&&""!==r.trim()?(e.content=r,b(e)):!i&&!n.trim().startsWith("<")&&o()},l=a.processChunk(n);l instanceof Promise?l.then(s).catch(o):s(l)},oe=(e,t)=>{let n=t??e.content;if(null==n||""===n)return e.streaming=!1,void b(e);let r=ee.get(e.id)??X(n);e.rawContent=r;let a=Z.get(e.id),i=null,o=!1;if(a&&(i=a.getExtractedText(),null===i&&(i=l(r)),null===i)){let t=a.processChunk(r);t instanceof Promise?(o=!0,t.then(t=>{let n="string"==typeof t?t:t?.text??null;null!==n&&(e.content=n,e.streaming=!1,Z.delete(e.id),ee.delete(e.id),b(e))}).catch(()=>{})):i="string"==typeof t?t:t?.text??null}if(!o){null!==i&&""!==i.trim()?e.content=i:ee.has(e.id)||(e.content=X(n));let t=Z.get(e.id);if(t){let n=t.close?.();n instanceof Promise&&n.catch(()=>{}),Z.delete(e.id)}ee.delete(e.id),e.streaming=!1,b(e)}},se=(e,t,n,r)=>{let a=R.get(e);if(a)return a;let i={id:`nested-${t}-${e}`,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!0,sequence:v(),...n?{variant:n}:{},..."reasoning"===n?{reasoning:{id:e,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:t,textBlockId:e,executionId:r,phase:P.get(e)}};return R.set(e,i),b(i),i},le=[],de=new Map;u?.media.forEach(([e,t])=>de.set(e,{...t,parts:[...t.parts]}));let pe=u?.iteration??0,ue=u?.executionKind??"agent",ce=u?.executionKindResolved??!1,fe=u?.turnId??null,ge=null,me=t.config().iterationDisplay??"separate";ae=()=>{for(let n=0;n<le.length;n++){let a=le[n];if(!ce&&"flow"!==ue&&"string"==typeof a.stepType&&(ue="flow"),"reasoning_start"===a.type){let e="string"==typeof a.id?a.id:null,t="string"==typeof a.parentToolCallId&&a.parentToolCallId?a.parentToolCallId:null;if(e&&t){$.set(e,t),se(e,t,"reasoning",a.executionId);continue}let n=a.id,r=W(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,("loop"===a.scope||"turn"===a.scope)&&(r.reasoning.scope=a.scope),r.streaming=!0,r.reasoning.status="streaming",b(r)}else if("reasoning_delta"===a.type){let e="string"==typeof a.id?a.id:null;if(e&&$.has(e)&&R.has(e)){let t=R.get(e),n=a.delta;n&&t.reasoning&&(t.reasoning.chunks.push(String(n)),b(t));continue}let t=a.id,n=W(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("reasoning_complete"===a.type){let e="string"==typeof a.id?a.id:null;if(e&&$.has(e)&&R.has(e)){let t=R.get(e);if(t.reasoning){let e="string"==typeof a.text?a.text:"";e&&0===t.reasoning.chunks.length&&t.reasoning.chunks.push(e),t.reasoning.status="complete",t.streaming=!1,b(t)}$.delete(e),R.delete(e);continue}let t=a.id,n="string"==typeof a.text?a.text:"";!B.get(t)&&(n||"loop"===a.scope)&&W(t,a.executionId);let r=B.get(t);if(r?.reasoning){("loop"===a.scope||"turn"===a.scope)&&(r.reasoning.scope=a.scope),n&&0===r.reasoning.chunks.length&&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("tool_start"===a.type){A&&=(A.streaming=!1,b(A),null),"number"==typeof a.iteration&&(pe=a.iteration);let e=a.toolCallId,t=a.toolName;if(Q(t)){Y.add(e);continue}let n=V(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,void 0!==a.parameters&&(r.args=a.parameters),r.startedAt=r.startedAt??z(a.startedAt),r.completedAt=void 0,r.durationMs=void 0,n.toolCall=r,n.streaming=!0,b(n)}else if("tool_output_delta"===a.type){let e=a.toolCallId;if(Y.has(e))continue;let t=V(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("tool_complete"===a.type){let e=a.toolCallId;if(Y.has(e)){Y.delete(e);continue}let t=V(e,a.executionId,a.iteration),n=t.toolCall??{id:e,status:"running"};n.status="complete",void 0!==a.result&&(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("number"==typeof r)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("await"===a.type&&a.toolName){let t="string"==typeof a.toolCallId&&a.toolCallId.length>0?a.toolCallId:void 0,n=t??a.toolId??`local-${v()}`,r=V(n,a.executionId),i=a.toolName,o="webmcp"===a.origin&&!e(i)?`webmcp:${i}`:i,s=e(o),l=r.toolCall??{id:n,status:"pending"};l.name=o,l.args=a.parameters,l.status=s?"running":"complete",l.chunks=l.chunks??[],l.startedAt=l.startedAt??z(a.awaitedAt),s?(l.completedAt=void 0,l.duration=void 0,l.durationMs=void 0):l.completedAt=l.completedAt??l.startedAt,r.toolCall=l,r.streaming=!1,r.agentMetadata={...r.agentMetadata,executionId:a.executionId??r.agentMetadata?.executionId,awaitingLocalTool:!0,...t?{webMcpToolCallId:t}:{}},b(r)}else if("text_start"===a.type){let e="string"==typeof a.id?a.id:null;if(e){let t=C(a.phase);t?P.set(e,t):P.delete(e)}let t="string"==typeof a.parentToolCallId&&a.parentToolCallId?a.parentToolCallId:null;if(e&&t){$.set(e,t);continue}let n=A;n&&("flow"===ue?(oe(n),ne=n):(n.streaming=!1,b(n)),A=null),M=e??M,k=""}else if("text_delta"===a.type){let e="string"==typeof a.id?a.id:null,t=e?$.get(e):void 0;if(e&&t){let n="string"==typeof a.delta?a.delta:"",r=(D.get(e)??"")+n;if(D.set(e,r),""===r.trim())continue;let i=se(e,t,void 0,a.executionId);ie(i,r,n);continue}M=e??M;let n="string"==typeof a.delta?a.delta:"";if(k+=n,"flow"===ue&&""===k.trim())continue;let r=U();r.agentMetadata={textBlockId:M??void 0,phase:P.get(M??""),executionId:a.executionId,iteration:pe,..."flow"===ue?{}:{turnId:fe??void 0,agentName:ge?.agentName}},M&&R.set(M,r),ie(r,k,n),T=r}else if("text_complete"===a.type){let e="string"==typeof a.id?a.id:null;e&&P.delete(e);let t=e?R.get(e):A,n=C(a.phase);if(t&&n&&(t.agentMetadata={...t.agentMetadata,providerPhase:n}),e&&$.has(e)){let t=R.get(e);t&&oe(t),$.delete(e),D.delete(e),R.delete(e);continue}if(e&&t!==A){t&&(t.streaming=!1,b(t));continue}let r=A;r&&("flow"===ue?(oe(r),ne=r):(""===(r.content??"")&&"string"==typeof a.text&&(r.content=a.text),r.streaming=!1,b(r)),A=null),M=null,k=""}else if("step_complete"===a.type){if("tool"===a.stepType)continue;if(!1===a.success){let e=a.error||"Step failed";r({type:"error",error:Error(e)});let t=A;t&&t.streaming&&(t.streaming=!1,b(t)),r({type:"status",status:"idle"});continue}{let e=ne;ne=null;let t=a.stopReason,n=(a.result&&"object"==typeof a.result?a.result:null)?.response;if(e)t&&(e.stopReason=t),null==n?!1!==e.streaming&&(Z.delete(e.id),ee.delete(e.id),e.streaming=!1,b(e)):te(e,n);else{let e=null!=n&&""!==n;if(e||t&&"end_turn"!==t&&"unknown"!==t){let r=U();t&&(r.stopReason=t),e?oe(r,n):(r.streaming=!1,b(r))}}continue}}else if("execution_start"===a.type)ue="flow"===a.kind?"flow":"agent",ce=!0,t.config().backgroundConversations&&r({type:"status",status:"connected",executionId:a.executionId}),"agent"===ue&&(ge={executionId:a.executionId,agentId:a.agentId??"virtual",agentName:a.agentName??""});else if("turn_start"===a.type){let e="number"==typeof a.iteration?a.iteration:pe;if(e!==pe){if("separate"===me&&e>1){let e=A;e&&(e.streaming=!1,b(e),A=null)}pe=e}fe="string"==typeof a.id?a.id:null,T=null}else if("tool_input_delta"===a.type){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("tool_input_complete"===a.type){if(Y.has(a.toolCallId))continue;let e=V(a.toolCallId,a.executionId),t=e.toolCall;t.args=a.parameters,t.name=a.toolName??t.name,b(e)}else if("turn_complete"===a.type){let e=a.stopReason,t=A??T;if(e&&null!==t){let n=a.id;n&&t.agentMetadata?.turnId!==n||(t.stopReason=e,b(t))}fe===a.id&&(fe=null)}else if("media_start"===a.type){let e=String(a.id);de.set(e,{mediaType:"string"==typeof a.mediaType?a.mediaType:void 0,toolCallId:a.toolCallId,parts:[]})}else if("media_delta"===a.type){let e=de.get(String(a.id));e&&"string"==typeof a.delta&&e.parts.push(a.delta)}else if("media_complete"===a.type){let e=String(a.id),t=de.get(e);de.delete(e);let n=("string"==typeof a.mediaType?a.mediaType:void 0)??t?.mediaType??"application/octet-stream",r="string"==typeof a.data?a.data:void 0,i="string"==typeof a.url?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:"image"===e||e.startsWith("image/")?"image-url":"file-url",url:i,mediaType:n}}let s=a.toolCallId??t?.toolCallId,l=o?[o]:[],d=[];for(let e of l){if(!e||"object"!=typeof e)continue;let t=e,n="string"==typeof t.type?t.type:void 0,r="string"==typeof t.mediaType?t.mediaType.toLowerCase():"",a=null,i="";if("media"===n){let e="string"==typeof t.data?t.data:void 0;if(!e)continue;i=r.length>0?r:"application/octet-stream",a=`data:${i};base64,${e}`}else if("image-url"===n){let e="string"==typeof t.url?t.url:void 0;if(!e)continue;i=r,a=e}else if("file-url"===n){let e="string"==typeof t.url?t.url:void 0;if(!e)continue;i=r,a=e}else continue;if(a)if("image-url"===n||i.startsWith("image/"))d.push({type:"image",image:a,...i.includes("/")?{mimeType:i}:{}});else if(i.startsWith("audio/"))d.push({type:"audio",audio:a,mimeType:i});else if(i.startsWith("video/"))d.push({type:"video",video:a,mimeType:i});else{let e=i||"application/octet-stream";d.push({type:"file",data:a,mimeType:e,filename:_(e)})}}if(d.length>0){let e=v(),t=s,n={id:`agent-media-${"string"==typeof t&&t.length>0?`${t}-${e}`:String(e)}`,role:"assistant",content:"",contentParts:d,createdAt:(new Date).toISOString(),streaming:!1,sequence:e,agentMetadata:{executionId:a.executionId,iteration:pe}};b(n);let r=A;r&&(r.streaming=!1,b(r)),A=null,S.current=null}}else if("execution_complete"===a.type){let e=A;e&&("flow"===a.kind&&!1!==e.streaming?oe(e):(e.streaming=!1,b(e)),A=null),M=null,k="",ne=null,r({type:"status",status:!1===a.success?"error":"idle",terminal:!0})}else if("execution_error"===a.type){let e="string"==typeof a.error?a.error:a.error?.message??"Execution error";r({type:"error",error:Error(e)})}else if("ping"!==a.type)if("approval_start"===a.type){let e=a.approvalId??`approval-${v()}`,t={id:`approval-${e}`,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!1,variant:"approval",sequence:v(),approval:{id:e,status:"pending",agentId:ge?.agentId??"virtual",executionId:a.executionId??ge?.executionId??"",toolName:a.toolName??"",toolType:a.toolType,description:a.description??`Execute ${a.toolName??"tool"}`,..."string"==typeof a.reason&&a.reason?{reason:a.reason}:{},parameters:a.parameters,..."string"==typeof a.toolCallId&&a.toolCallId?{toolCallId:a.toolCallId}:{}}};b(t)}else if("approval_complete"===a.type){let e=a.approvalId;if(e){let t={id:`approval-${e}`,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!1,variant:"approval",sequence:v(),approval:{id:e,status:a.decision??"approved",agentId:ge?.agentId??"virtual",executionId:a.executionId??ge?.executionId??"",toolName:"",description:"",resolvedAt:Date.now()}};b(t)}}else if("artifact_start"===a.type||"artifact_delta"===a.type||"artifact_update"===a.type||"artifact_complete"===a.type){if("artifact_start"===a.type){let e,n=a.artifactType,i=String(a.id),l="string"==typeof a.title?a.title:void 0,d=a.file;if(d&&"object"==typeof d&&!Array.isArray(d)&&"string"==typeof d.path&&"string"==typeof d.mimeType&&(e={path:d.path,mimeType:d.mimeType,..."string"==typeof d.language?{language:d.language}:{}}),r({type:"artifact_start",id:i,artifactType:n,title:l,component:"string"==typeof a.component?a.component:void 0,...e?{file:e}:{}}),H.set(i,{markdown:"",title:l,file:e}),!K.has(i)){K.add(i);let r=o(t.config().features?.artifacts,{artifactType:n,...e?{file:e}:{}}),d="string"==typeof a.component?a.component:void 0,p={id:`artifact-ref-${i}`,role:"assistant",content:"",createdAt:(new Date).toISOString(),streaming:!0,sequence:v(),rawContent:s(r,{artifactId:i,title:l,artifactType:n,status:"streaming",...e?{file:e}:{},...d?{component:d}:{}})};G.set(i,p),b(p)}}else if("artifact_delta"===a.type){let e=String(a.id),t="string"==typeof a.delta?a.delta:String(a.delta??"");r({type:"artifact_delta",id:e,artDelta:t});let n=H.get(e);n&&(n.markdown+=t)}else if("artifact_update"===a.type){let e=a.props&&"object"==typeof a.props&&!Array.isArray(a.props)?a.props:{};r({type:"artifact_update",id:String(a.id),props:e,component:"string"==typeof a.component?a.component:void 0});let t=H.get(String(a.id));t&&(t.props={...t.props??{},...e})}else if("artifact_complete"===a.type){let e=String(a.id);r({type:"artifact_complete",id:e});let t=G.get(e);if(t){t.streaming=!1;try{let n=JSON.parse(t.rawContent??"{}");if(n.props){n.props.status="complete";let t=H.get(e);t?.markdown&&(n.props.markdown=t.markdown),t?.file&&(n.props.file=t.file),"PersonaArtifactInline"===n.component&&t?.props&&Object.keys(t.props).length>0&&(n.props.componentProps=t.props)}t.rawContent=JSON.stringify(n)}catch{}H.delete(e),b(t),G.delete(e)}}}else if("error"===a.type&&!1===a.recoverable&&null!=a.error&&""!==a.error){let e="string"==typeof a.error?a.error:null==a.error?.message?"Execution error":String(a.error.message);r({type:"error",error:Error(e)});let t=A;t&&t.streaming&&(t.streaming=!1,b(t)),r({type:"status",status:"idle"})}}le.length=0};try{for(;;){if(c!==t.streamGeneration())return;d?.throwIfAborted();let{done:e,value:n}=await f.read();if(c!==t.streamGeneration())return;if(d?.throwIfAborted(),e)break;h+=y.decode(n,{stream:!0});let a=h.split("\n\n");h=a.pop()??"";for(let e of a){if(c!==t.streamGeneration())return;d?.throwIfAborted();let n=e.split("\n"),a="message",i="",o=null;for(let e of n)e.startsWith("event:")?a=e.replace("event:","").trim():e.startsWith("data:")?i+=e.replace("data:","").trim():e.startsWith("id:")&&(o=e.slice(3).trim());let s,l=()=>{null!==o&&""!==o&&r({type:"cursor",id:o,...t.config().backgroundConversations?{checkpoint:{textBlockId:M,openAssistant:null!==A,sealedFlowMessageId:ne?.id??null,rawText:k,executionKind:ue,executionKindResolved:ce,turnId:fe,iteration:pe,textPhases:[...P],nestedParents:[...$],nestedRaw:[...D],media:[...de].map(([e,t])=>[e,{...t,parts:[...t.parts]}]),artifactContent:[...H].map(([e,t])=>[e,{...t,props:t.props?{...t.props}:void 0}]),artifactTools:[...Y]}}:{}})};if(!i){l();continue}try{s=JSON.parse(i)}catch(t){r({type:"error",error:t instanceof Error?t:Error("Failed to parse chat stream payload")});continue}let p="object"==typeof s&&s&&!Array.isArray(s)?s:null,u="message"===a?"string"==typeof p?.type?p.type:"message":a;if(t.onSSEEvent?.(u,s),t.parseSSEEvent){S.current=A;let e=await E(t,s,r,S,b,v,O);if(c!==t.streamGeneration())return;if(d?.throwIfAborted(),S.current&&S.current!==A&&(A=S.current),e){l();continue}}p&&(le.push({...p,type:u}),ae()),l()}}ae()}finally{t.streamReaders.delete(f),d?.removeEventListener("abort",m),f.releaseLock()}}t(()=>{r(),I(),x(),k(),C=e=>"commentary"===e||"partial_answer"===e||"final_answer"===e?e:void 0,M=e=>/^[{[<]/.test(e)})();export{L as preferFinalStructuredContent,S as resolveApproval,O as resumeFlow,P as streamResponse};