@runtypelabs/persona 4.30.0 → 4.32.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.
- package/README.md +22 -1
- package/dist/activity-ui.cjs +2 -2
- package/dist/activity-ui.d.cts +11 -3
- package/dist/activity-ui.d.ts +11 -3
- package/dist/activity-ui.js +1 -1
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/approval-ui.d.cts +2 -2
- package/dist/approval-ui.d.ts +2 -2
- package/dist/artifacts-ui.d.cts +3 -3
- package/dist/artifacts-ui.d.ts +3 -3
- package/dist/background-runtime.d.cts +1 -1
- package/dist/background-runtime.d.ts +1 -1
- package/dist/chunk-C2IbR39s.js +1 -0
- package/dist/chunk-CkE90FtA.js +2 -0
- package/dist/{chunk-n96BB0YH.js → chunk-CzZBmTLd.js} +1 -1
- package/dist/chunk-DABqu7C3.js +2 -0
- package/dist/chunk-DDAwu89-.js +1 -0
- package/dist/{chunk-CqEWCkJt.js → chunk-DZg9bFK6.js} +1 -1
- package/dist/chunk-DbD5qyBw.js +3 -0
- package/dist/{chunk-gayfbmEU.js → chunk-FEzOcZof.js} +1 -1
- package/dist/{chunk-UyZbbbz3.js → chunk-MdlQetfC.js} +2 -2
- package/dist/client-dispatch.js +1 -1
- package/dist/client-history.js +1 -1
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/composer-actions-runtime.d.cts +2 -2
- package/dist/composer-actions-runtime.d.ts +2 -2
- package/dist/{composer-input-C76gfIoK.d.cts → composer-input-dwg_o9Z-.d.cts} +1 -1
- package/dist/{composer-input-C76gfIoK.d.ts → composer-input-dwg_o9Z-.d.ts} +1 -1
- package/dist/{composer-store-C7tvaz90.d.cts → composer-store-Dw7Zbqxr.d.cts} +1 -1
- package/dist/{composer-store-C7tvaz90.d.ts → composer-store-Dw7Zbqxr.d.ts} +1 -1
- package/dist/{context-mention-manager-IfT4JHma.d.cts → context-mention-manager-D2p0-JH-.d.cts} +2 -2
- package/dist/{context-mention-manager-IfT4JHma.d.ts → context-mention-manager-D2p0-JH-.d.ts} +2 -2
- package/dist/context-mentions-inline.d.cts +2 -2
- package/dist/context-mentions-inline.d.ts +2 -2
- package/dist/context-mentions.d.cts +3 -3
- package/dist/context-mentions.d.ts +3 -3
- package/dist/{defaults-Cc_p0PGM.d.cts → defaults-CjX0kKzb.d.cts} +1 -1
- package/dist/{defaults-Cc_p0PGM.d.ts → defaults-CjX0kKzb.d.ts} +1 -1
- package/dist/dictation-runtime.d.cts +2 -2
- package/dist/dictation-runtime.d.ts +2 -2
- package/dist/event-stream-view.d.cts +1 -1
- package/dist/event-stream-view.d.ts +1 -1
- package/dist/{fallback-speech-engine-CSxWpG0A.d.cts → fallback-speech-engine-DmF7MczI.d.cts} +1 -1
- package/dist/{fallback-speech-engine-CSxWpG0A.d.ts → fallback-speech-engine-DmF7MczI.d.ts} +1 -1
- package/dist/{feature-preferences-eeSOmDxg.d.cts → feature-preferences-CVFDt9Xf.d.cts} +1 -1
- package/dist/{feature-preferences-eeSOmDxg.d.ts → feature-preferences-CVFDt9Xf.d.ts} +1 -1
- package/dist/forms-ui.d.cts +2 -2
- package/dist/forms-ui.d.ts +2 -2
- package/dist/{history-confirm-dialog-DXkuAgh-.d.cts → history-confirm-dialog-DJEXsTyE.d.cts} +1 -1
- package/dist/{history-confirm-dialog-DXkuAgh-.d.ts → history-confirm-dialog-DJEXsTyE.d.ts} +1 -1
- package/dist/history-shell.d.cts +6 -6
- package/dist/history-shell.d.ts +6 -6
- package/dist/history-view.d.cts +1 -1
- package/dist/history-view.d.ts +1 -1
- package/dist/index.cjs +49 -47
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -9
- package/dist/index.d.ts +9 -9
- package/dist/index.global.js +1 -1
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +43 -41
- package/dist/index.js.map +1 -1
- package/dist/{loading-label-runtime-loader-C53YyPJ-.d.cts → loading-label-runtime-loader-CPxnoaoi.d.cts} +1 -1
- package/dist/{loading-label-runtime-loader-C53YyPJ-.d.ts → loading-label-runtime-loader-CPxnoaoi.d.ts} +1 -1
- package/dist/loading-label-runtime.d.cts +1 -1
- package/dist/loading-label-runtime.d.ts +1 -1
- package/dist/markdown-parsers.js +18 -15
- package/dist/{message-bubble-Cg_sTXUN.d.cts → message-bubble-CkZGlCLC.d.cts} +1 -1
- package/dist/{message-bubble-Cg_sTXUN.d.ts → message-bubble-CkZGlCLC.d.ts} +1 -1
- package/dist/preferences-runtime.d.cts +1 -1
- package/dist/preferences-runtime.d.ts +1 -1
- package/dist/{preview-BeMKALry.d.cts → preview-DdUvoLb4.d.cts} +2 -2
- package/dist/{preview-BeMKALry.d.ts → preview-DdUvoLb4.d.ts} +2 -2
- package/dist/{registry-BBe-Lesw.d.ts → registry-Dz4iHNST.d.cts} +3 -1
- package/dist/{registry-BBe-Lesw.d.cts → registry-Dz4iHNST.d.ts} +3 -1
- package/dist/{session-C0fSteA4.d.cts → session-Baxp9iRK.d.cts} +24 -9
- package/dist/{session-C0fSteA4.d.ts → session-Baxp9iRK.d.ts} +24 -9
- package/dist/session-reconnect.d.cts +2 -2
- package/dist/session-reconnect.d.ts +2 -2
- package/dist/smart-dom-reader.d.cts +1 -1
- package/dist/smart-dom-reader.d.ts +1 -1
- package/dist/theme-editor-preview.cjs +47 -45
- package/dist/theme-editor-preview.d.cts +1 -1
- package/dist/theme-editor-preview.d.ts +1 -1
- package/dist/theme-editor-preview.js +23 -24
- package/dist/theme-editor.d.cts +2 -2
- package/dist/theme-editor.d.ts +2 -2
- package/dist/theme-reference.d.cts +2 -2
- package/dist/theme-reference.d.ts +2 -2
- package/dist/{tool-loading-animation-BvdaZfwh.d.cts → tool-loading-animation-un3kA5Ur.d.cts} +1 -1
- package/dist/{tool-loading-animation-BvdaZfwh.d.ts → tool-loading-animation-un3kA5Ur.d.ts} +1 -1
- package/dist/{turn-activity-ui-BYBlInZQ.d.cts → turn-activity-ui-BGNhtMcH.d.cts} +2 -2
- package/dist/{turn-activity-ui-BYBlInZQ.d.ts → turn-activity-ui-BGNhtMcH.d.ts} +2 -2
- package/dist/turn-activity-ui.d.cts +1 -1
- package/dist/turn-activity-ui.d.ts +1 -1
- package/dist/{types-CiXi4ICM.d.cts → types-BOZHQIk0.d.cts} +13 -1
- package/dist/{types-CiXi4ICM.d.ts → types-BOZHQIk0.d.ts} +13 -1
- package/dist/voice-client-tools.d.cts +1 -1
- package/dist/voice-client-tools.d.ts +1 -1
- package/dist/voice-runtime.cjs +1 -1
- package/dist/voice-runtime.d.cts +2 -2
- package/dist/voice-runtime.d.ts +2 -2
- package/dist/voice-runtime.js +1 -1
- package/dist/voice-worklet-player.d.cts +2 -2
- package/dist/voice-worklet-player.d.ts +2 -2
- package/dist/{webmcp-runtime-entry-BTbOg3Au.d.cts → webmcp-runtime-entry-DuAG1_yF.d.cts} +1 -1
- package/dist/{webmcp-runtime-entry-BTbOg3Au.d.ts → webmcp-runtime-entry-DuAG1_yF.d.ts} +1 -1
- package/dist/webmcp-runtime.d.cts +1 -1
- package/dist/webmcp-runtime.d.ts +1 -1
- package/dist/widget.css +1 -1
- package/package.json +2 -2
- package/src/activity-ui.ts +23 -0
- package/src/components/disclosure-animation.ts +5 -0
- package/src/components/tool-bubble.ts +1 -0
- package/src/index-core.ts +2 -0
- package/src/markdown-parsers-eager.ts +2 -1
- package/src/markdown-parsers-entry.ts +1 -0
- package/src/markdown-parsers-loader.ts +2 -0
- package/src/postprocessors.ts +14 -0
- package/src/session.ts +3 -0
- package/src/styles/widget.css +6 -0
- package/src/types.ts +13 -0
- package/src/ui.background-conversations.test.ts +6 -0
- package/src/ui.footer-visibility.test.ts +54 -0
- package/src/ui.page-cache.test.ts +268 -0
- package/src/ui.postprocess.test.ts +80 -1
- package/src/ui.reveal-tool-call.test.ts +258 -0
- package/src/ui.ts +222 -32
- package/src/utils/actions.ts +3 -0
- package/src/utils/streaming-markdown.test.ts +103 -0
- package/src/utils/streaming-markdown.ts +186 -0
- package/dist/chunk-18tPmsiJ.js +0 -1
- package/dist/chunk-B3OrH9Ng.js +0 -2
- package/dist/chunk-Dp2vWE9V.js +0 -1
- package/dist/chunk-VloQ2dnh.js +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{r as e,t}from"./chunk-D5BxWOFB.js";import{t as n}from"./chunk-Bb3MaswO.js";import{a as r,c as i,d as a,f as o,g as s,h as c,i as l,l as u,o as d,p as f,r as p,s as m,t as h,u as g}from"./chunk-mEFmAbxE.js";import{i as _,n as v,r as y,t as b}from"./chunk-BGPPJ_ui.js";import{n as x}from"./chunk-Cve3IfG4.js";const S=`[data-persona-disclosure]`,C=/* @__PURE__ */ new WeakMap;function w(e,t){C.get(e)?.effect.finished?.then(t,t)??t()}function T(e){let t=e?.expansion;return{animation:t?.animation??(e?.future?.v5Defaults?`height`:`instant`),duration:Number.isFinite(t?.duration)?Math.max(0,t.duration):160,easing:t?.easing??`ease-out`}}const E=e=>{let t=Array.from(e.children);return{header:t.find(e=>e.matches(`button[data-expand-header]`)),content:t.find(e=>e.classList.contains(`persona-border-t`)),preview:t.find(e=>e.hasAttribute(`data-persona-collapsed-preview`))}},D=e=>E(e).header?.getAttribute(`aria-expanded`)===`true`,O=()=>typeof matchMedia==`function`&&matchMedia(`(prefers-reduced-motion: reduce)`).matches;function k(e){let{header:t,content:n}=E(e),r=e.getRootNode();n?.contains(r.activeElement)&&t?.focus({preventScroll:!0})}function A(e,t){let{content:n,preview:r}=E(e);n&&(t||k(e),n.inert=!t,n.style.display=t?``:`none`,r&&(r.style.display=t||!(r.textContent||r.childNodes.length)?`none`:``))}function j(e){C.get(e)?.finish()}function M(e){for(let t=e.parentElement?.closest(S);t;t=t.parentElement?.closest(S))j(t);e.querySelectorAll(S).forEach(j)}function N(e,t,n,r){let i=T(n),a=i.animation===`height`&&i.duration>0&&!O()&&e.isConnected&&typeof e.animate==`function`,o=a?r??e.getBoundingClientRect().height:0,s=a&&C.has(e)?E(e).content:void 0,c=s?getComputedStyle(s):void 0,l=c?{transform:c.transform,opacity:c.opacity}:void 0;if(M(e),j(e),A(e,t),!a)return;let{header:u,content:d,preview:f}=E(e);if(!u||!d)return;let p=e.getBoundingClientRect().height;if(o===p)return;t||(d.style.display=``,f&&(f.style.display=`none`));let m,h;try{m=e.animate([{height:`${o}px`,boxSizing:`border-box`,overflow:`hidden`},{height:`${p}px`,boxSizing:`border-box`,overflow:`hidden`}],{duration:i.duration,easing:i.easing,fill:`both`});let n=getComputedStyle(d),r={transform:n.transform||`none`,opacity:n.opacity||`1`},a={transform:`${r.transform===`none`?``:r.transform} translateY(-8px)`,opacity:`0`};h=d.animate([l??(t?a:r),t?r:a],{duration:i.duration,easing:i.easing,fill:`both`})}catch{m?.cancel(),A(e,t);return}let g,_=p,v=()=>{C.get(e)?.effect===m&&(C.delete(e),g?.disconnect(),m.onfinish=m.oncancel=null,m.cancel(),h.cancel(),A(e,t))};C.set(e,{effect:m,expanded:t,settings:JSON.stringify(i),finish:v}),m.onfinish=m.oncancel=v,t&&typeof ResizeObserver==`function`&&(g=new ResizeObserver(()=>{if(C.get(e)?.effect!==m||!e.isConnected)return;let t=m.effect,n=t?.getComputedTiming().progress;if(n==null||n<0||n>=1)return;let r=e.getBoundingClientRect().height,i=e.style.getPropertyValue(`height`),a=e.style.getPropertyPriority(`height`);e.style.setProperty(`height`,`auto`,`important`);let o=e.getBoundingClientRect().height;i?e.style.setProperty(`height`,i,a):e.style.removeProperty(`height`),o!==_&&(_=o,t.setKeyframes([{height:`${r}px`,offset:n,boxSizing:`border-box`,overflow:`hidden`},{height:`${o}px`,offset:1,boxSizing:`border-box`,overflow:`hidden`}]))}),g.observe(d),g.observe(u))}function P(e,t){let n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Map,i=typeof matchMedia==`function`?matchMedia(`(prefers-reduced-motion: reduce)`):void 0,a=()=>n.forEach(j),o=()=>{i?.matches&&a()};i?.addEventListener?.(`change`,o);let s=()=>{let e=T(t());return e.animation===`height`&&e.duration>0&&!O()};return{prepare(i){if(r.clear(),!s()){a(),n.clear();return}let o=new Map(Array.from(e.querySelectorAll(S),e=>[e.id,e]));for(let e of i.querySelectorAll(S)){let i=o.get(e.id);if(!i)continue;n.add(i);let a=D(e),s=C.get(i);if(a!==D(i))r.set(i.id,i.getBoundingClientRect().height),a||k(i),j(i);else if(s){if(s.settings!==JSON.stringify(T(t()))||O())j(i);else if(!s.expanded){let{content:t,preview:n}=E(e);t&&(t.style.display=``,t.inert=!0),n&&(n.style.display=`none`)}}}},sync(){if(!s())a(),n.clear(),r.clear();else{for(let t of n)e.contains(t)||(j(t),n.delete(t));for(let i of e.querySelectorAll(S)){n.add(i);let e=r.get(i.id);e!==void 0&&N(i,D(i),t(),e);let a=C.get(i);a&&(a.settings!==JSON.stringify(T(t()))||O())&&j(i)}r.clear()}},clear(){e.querySelectorAll(S).forEach(j),a(),n.clear(),r.clear()},destroy(){this.clear(),i?.removeEventListener?.(`change`,o)}}}const F=new Map([[`web_search|web_search_preview|WebSearch`,`Searching the web`,`Searched the web`,`globe`],[`web_fetch|WebFetch`,`Reading web pages`,`Read web pages`,`globe`,`single`],[`file_search|search_files|Glob`,`Searching files`,`Searched files`,`search`],[`read_text_file|read_multiple_files|Read`,`Reading files`,`Read files`,`file-text`,`single`],[`write_file|edit_file|apply_patch|Write|Edit|NotebookEdit`,`Editing files`,`Edited files`,`pencil`,`single`],[`list_directory|list_directory_with_sizes|directory_tree`,`Browsing files`,`Browsed files`,`folder`],[`Grep`,`Searching code`,`Searched code`,`search`],[`shell|local_shell|bash|Bash|PowerShell|bash_code_execution`,`Running commands`,`Ran commands`,`terminal`,`single`],[`code_interpreter|code_execution`,`Running code`,`Ran code`,`code-xml`],[`browser_navigate|browser_click|browser_snapshot|browser_fill_form`,`Using the browser`,`Used the browser`,`globe`],[`computer`,`Using the computer`,`Used the computer`,`monitor`],[`image_generation`,`Generating images`,`Generated images`,`image`],[`git_status|git_diff|git_diff_staged|git_diff_unstaged|git_log|git_show`,`Checking repository changes`,`Checked repository changes`,`file-code`],[`tool_search|ToolSearch`,`Finding tools`,`Looked up tools`,`search`],[`Agent`,`Delegating work`,`Delegated work`,`bot`],[`TodoWrite|TaskCreate|TaskUpdate`,`Updating the plan`,`Updated the plan`,`clipboard`],[`sql_db_query`,`Querying the database`,`Queried the database`,`database`],[`search_gmail`,`Searching email`,`Searched email`,`mail`]].flatMap(([e,...t])=>e.split(`|`).map(e=>[e,t]))),I=e=>{let t=e.replace(/([a-z\d])([A-Z])/g,`$1 $2`).replace(/[_-]+/g,` `).replace(/\s+/g,` `).toLowerCase();return t[0].toUpperCase()+t.slice(1)},L=e=>{let t=e.name?.trim()||`tool`,n=I(t);return F.get(t)??[`Using ${n}`,`Used ${n}`]},ee=e=>L(e)[2]??`wrench`,te=(e,t)=>{let n=t.toolCall?.iconName;return(typeof n==`function`?n(e):n)??ee(e)};function ne(e,t){if(typeof t.toolCall?.iconName==`string`)return t.toolCall.iconName;let n=e.map(e=>te(e,t));return e.every((t,r)=>L(t)[0]===L(e[0])[0]&&n[r]===n[0])?n[0]:`toolbox`}const re=[[`approvalStatus`,`pending`,`Waiting for approval`],[`approvalStatus`,`denied`,`Approval denied`],[`approvalStatus`,`timeout`,`Approval expired`],[`success`,!1,`Failed`],[`interrupted`,!0,`Interrupted`],[`superseded`,!0,`Approved, ran again below`]],ie=e=>e.error||re.some(([t,n])=>e[t]===n),ae=e=>ie(e)?I(e.name?.trim()||`tool`):L(e)[+(e.status===`complete`)],oe=e=>{let t=ae(e);return L(e)[3]&&!/^(read_multiple_files|apply_patch)$/.test(e.name?.trim()??``)?t.replace(/(web pages|files|commands)$/,e=>`a ${e.slice(0,-1)}`):t};function se(e,t=3){let n=e.length;if(n===0)return``;(!Number.isInteger(t)||t<0)&&(t=3);let r=/* @__PURE__ */ new Map;for(let t of e){let e=L(t)[0],n=r.get(e);(!n||n.status===`complete`&&!ie(n))&&r.set(e,t)}let i=t?[...r.values()].slice(0,t).map((e,t)=>{let n=ae(e);return t?n[0].toLowerCase()+n.slice(1):n}).join(`, `):n===1?`1 activity`:`${n} activities`,a=r.size-t;a>0&&t&&(i+=`, and ${a} more`);for(let[t,n,r]of re)e.some(e=>e[t]===n||n===!1&&e.error)&&(i+=` · ${r}`);return i}function ce(e){let{executionId:t,phase:n}=e.agentMetadata??{};if(e.role!==`assistant`||typeof t!=`string`||!t)return;let r=e.variant===`tool`||e.variant===`reasoning`||n===`commentary`?`progress`:n===`partial_answer`||n===`final_answer`?`final`:void 0;if(r)return{id:t,kind:r,startedAt:Date.parse(e.createdAt)}}const le={toolCallDisplay:{variant:`row`,grouped:!0,groupedMode:`collapsible`,autoExpand:!1,iconVisibility:`always`},reasoningDisplay:{appearance:`inset`,variant:`row`,autoExpand:!1,iconVisibility:`always`}},ue=Object.entries(le).flatMap(([e,t])=>Object.keys(t).map(t=>`features.${e}.${t}`)),de=/* @__PURE__ */ new WeakMap;function R(e,t){return e.turnActivity??t.turnActivity?.resolveMessage?.(e)??ce(e)}const z=e=>{let t=e.toolCall,n=e.approval?.status??t.approvalStatus;return t.error||t.interrupted||t.success===!1||t.superseded||n&&n!==`approved`},B=(e,t)=>e.toolCall?.actionTitle?.trim()||t?.toolCall?.resolveActionTitle?.(e.toolCall,e)?.trim()||void 0,V=(e,t)=>B(e,t)||oe(e.toolCall);function fe(e,t,n){let r=e.filter(e=>e.toolCall?.status!==`complete`);return t.features?.toolCallDisplay?.groupSummary===`current-action`&&r.length===1&&!e.some(z)?V(r[0],t):n}function H(e,t){if(!e.turnActivity?.enabled||t.role!==`assistant`||R(t,e)?.kind!==`progress`)return e;let n=de.get(e);if(n)return n;let{defaultProvenance:r,suppliedPath:i}=l(),a=r(e,ue),o={...e.features};for(let t of[`toolCallDisplay`,`reasoningDisplay`]){let n={...o[t]};for(let[r,o]of Object.entries(le[t]))!a.includes(`features.${t}.${r}`)&&i(e.preferences,`${t}.${r}`)!==`explicit`&&Object.assign(n,{[r]:o});o[t]=n}o.toolCallDisplay={...o.toolCallDisplay,groupSummary:o.toolCallDisplay?.groupSummary??(o.toolCallDisplay?.groupedMode===`stack`?`aggregate`:`current-action`)};let s={...e,features:o};return de.set(e,s),s}const pe=[`persona-w-full`,`persona-rounded-2xl`,`persona-bg-persona-surface`,`persona-border`,`persona-border-persona-message-border`,`persona-text-persona-primary`,`persona-shadow-sm`,`persona-overflow-hidden`,`persona-px-0`,`persona-py-0`],U=(e,t)=>t==null?!1:typeof t==`string`?(e.textContent=t,!0):(e.appendChild(t),!0),W=(e,n)=>{let r=t(`div`,[`persona-message-bubble`,e,...pe].join(` `));return r.id=`bubble-${n}`,r.setAttribute(`data-message-id`,n),r.setAttribute(`data-persona-disclosure`,``),r},G=e=>{let n=t(`button`,e.expandable?`persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none`:`persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none`);return n.type=`button`,e.expandable&&(n.setAttribute(`aria-expanded`,e.expanded?`true`:`false`),n.setAttribute(`data-expand-header`,`true`)),n.setAttribute(`data-bubble-type`,e.bubbleType),n},K=(e,t,n,r)=>{let i=r?.expansion?.chevron?.[t?`expanded`:`collapsed`]??(r?.future?.v5Defaults?t?`down`:`right`:t?`up`:`down`),a=T(r),o=e.querySelector(`svg`);if(!o){if(o=d(`chevron-right`,16,n,1.5),!o)return;e.replaceChildren(o)}o.setAttribute(`stroke`,n),e.classList.add(`persona-disclosure-chevron`),e.style.transform=`rotate(${{right:0,down:90,left:180,up:-90}[i]}deg)`,e.style.transitionDuration=`${a.animation===`height`?a.duration:0}ms`,e.style.transitionTimingFunction=a.easing},q=(e,n,r)=>{if(!r.expandable)return e.append(n),null;let i=t(`div`,`persona-flex persona-items-center`);K(i,r.expanded,r.iconColor,r.config);let a=t(`div`,r.metaGap?`persona-flex persona-items-center persona-gap-2 persona-ml-auto`:`persona-flex persona-items-center persona-ml-auto`);return a.append(i),e.append(n,a),i},me=e=>{let n=t(`div`,`persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted`);if(n.setAttribute(`data-persona-collapsed-preview`,e.previewKind),n.style.display=`none`,n.style.whiteSpace=`pre-wrap`,!e.expanded&&e.isActive&&e.activePreview&&e.previewText){let t=e.renderPreview?.();U(n,t)||(n.textContent=e.previewText),n.style.display=``}return!e.expanded&&e.isActive&&e.activeMinHeight&&(e.bubble.style.minHeight=e.activeMinHeight),n},he=e=>{e.header.setAttribute(`aria-expanded`,e.expanded?`true`:`false`),e.toggleIcon&&K(e.toggleIcon,e.expanded,e.iconColor,e.config),e.content.style.display=e.expanded?``:`none`,e.content.inert=!e.expanded,e.collapsedPreview.style.display=e.expanded?`none`:e.collapsedPreview.textContent||e.collapsedPreview.childNodes.length?``:`none`},ge=(e,t,n)=>{let r=n.stateSet.has(e),i=t.querySelector(`button[data-expand-header="true"]`),a=t.querySelector(`.persona-border-t`);if(!i||!a)return;i.setAttribute(`aria-expanded`,r?`true`:`false`);let o=i.querySelector(`.persona-ml-auto`)?.querySelector(`:scope > .persona-flex.persona-items-center`);o&&K(o,r,n.iconColor,n.config),N(t,r,n.config)},_e=(e,n,r,i,a,o)=>{e.textContent=``;for(let s of c(n,r))(s.styles.length?e.appendChild(t(`span`,s.styles.map(e=>`persona-tool-text-${e}`).join(` `))):e).append(s.isDuration?i?o():a:s.text)},ve=(e,t,n,r)=>{let i=n instanceof HTMLElement;return t.textContent=typeof n==`string`&&n.trim()?n:r,e.appendChild(i?n:t),i},J=(e,t,n)=>e.split(/\r?\n/).map(e=>e.trim()).filter(Boolean).slice(t,n).join(`
|
|
2
|
+
`);function Y(e,t,n){e&&n&&(e=H(e,n));let r=t===`tool`,i=r?`toolCallDisplay`:`reasoningDisplay`;return{...e,features:{...e?.features,[i]:{...r?y:b,...e?.future?.v5Defaults===!0?r?_:v:{},...e?.features?.[i],layout:X(e,t)}}}}function X(e,t,n){e&&n&&(e=H(e,n));let r=t===`tool`?`toolCallDisplay`:`reasoningDisplay`;return e?.features?.[r]?.layout??e?.features?.[r]?.variant??(e?.future?.v5Defaults?`row`:`card`)}function Z(e){let t=Math.max(0,Math.floor((e??0)/1e3));return t<1?`a moment`:t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}function ye(e,t){let n=Number(e.getAttribute(`data-tool-elapsed`));if(!n)return;let r=t-n;e.textContent=e.classList.contains(`persona-activity-duration`)?be(r,e.dataset.prefix):e.closest(`.persona-activity-row`)?Z(r):f(r)}const be=(e,t=``)=>Number.isFinite(e)&&e>=1e3?t+Z(e):``;function Q(e,n,r,i,a=!1,o){let s=a||X(r,i)===`row`,c=e.querySelector(`:scope > button`),u=i===`tool`?n.toolCall:n.reasoning,f=u?.status!==`complete`,p=r.features?.toolCallDisplay?.durationDisplay;if(c&&(s||r.future?.v5Defaults)&&i===`tool`&&u&&(p===`all`||p===(a?`group`:`tools`))){let e=t(`span`,`persona-activity-duration`),{startedAt:r,completedAt:i,durationMs:a}=u;f&&r>0&&r<=Date.now()&&e.setAttribute(`data-tool-elapsed`,String(r));let o=n.toolCall?.duration??a??i-r;e.textContent=be(f&&r!==void 0?r>0?Date.now()-r:void 0:o),c.appendChild(e)}if(!s)return e;if(e.className=`persona-message-bubble persona-${i}-bubble persona-activity-row`,e.dataset.activityKind=i,i===`tool`){let t=l().getExplicitLegacyStyle(r,`toolCall.shadow`);e.style.boxShadow=typeof t==`string`?t.trim()||`none`:`var(--persona-consumer-toolBubble-shadow, none)`}if(!c)return e;c.className=c.classList.contains(`persona-theme-padding`)?`persona-activity-header persona-theme-padding`:`persona-activity-header`;let m=n.approval?.status??n.toolCall?.approvalStatus,h=n.toolCall?.interrupted?`interrupted`:m===`denied`||m===`timeout`?`denied`:m===`pending`?`awaiting-approval`:n.toolCall?.success===!1?`error`:f?u?.status===`pending`?`pending`:`running`:`done`;e.dataset.activityState=h;let g=t(`span`,`persona-activity-icon`);g.dataset.activityIcon=h;let _=i===`reasoning`?r.features?.reasoningDisplay?.iconName:void 0,v=h===`done`?i===`reasoning`?_||`brain`:o??(a?`toolbox`:te(n.toolCall,r)):void 0;v&&v!==`check`&&(g.style.color=`inherit`);let y=d(_||(h===`pending`?`circle`:h===`awaiting-approval`?`clock`:h===`running`?`loader-circle`:h===`done`?v||`check`:`x`),16,`currentColor`,2);!y&&v&&(y=d(`square-text`,16,`currentColor`,2)),y&&g.appendChild(y),c.querySelector(`.persona-reasoning-header-icon`)?.remove();let b=i===`tool`?`toolCallDisplay`:`reasoningDisplay`,x=(a?r.features?.toolCallDisplay?.groupIconVisibility:void 0)??r.features?.[b]?.iconVisibility??(r.future?.v5Defaults?`active`:`always`);(x===`always`||x===`active`&&h!==`done`)&&c.prepend(g),c.querySelector(`:scope > div:not(.persona-ml-auto)`)?.classList.add(`persona-activity-label`),c.querySelector(`.persona-ml-auto`)?.classList.add(`persona-activity-chevron`);let S=e.querySelector(`:scope > .persona-border-t`);return S?.classList.add(`persona-activity-body`),S&&(S.id=`activity-details-${n.id}`,c.setAttribute(`aria-controls`,S.id)),e}function xe(e,t,n=()=>({})){let r=t?P(t,n):void 0,i=/* @__PURE__ */ new Map,a=e=>{let t=i.get(e)??{};return i.set(e,t),t},o=e=>{clearTimeout(e.timer),e.timer=void 0};return{observe(t,r,s,c={},l){let u=r===`tool`?t.toolCall:t.reasoning;if(!u)return;let d=Y(n(),r,t).features;c={...r===`tool`?d?.toolCallDisplay:d?.reasoningDisplay,...c},!i.has(t.id)&&l!==void 0&&(s[l?`add`:`delete`](t.id),a(t.id).manual=i.get(l)?.manual);let f=a(t.id);if(!f.manual&&(u.status!==`complete`&&(o(f),f.finished=!1),!f.seen&&u.status!==`complete`&&u.chunks?.some(Boolean)&&(f.seen=!0,c.autoExpand!==!1&&s.add(t.id)),f.seen&&u.status===`complete`&&!f.finished)){if(f.finished=!0,c.autoCollapseDelay===!1)return;f.timer=setTimeout(()=>{f.timer=void 0,s.delete(t.id),e(t.id,r)},c.autoCollapseDelay??1e3)}},manual(e){let t=a(e);t.manual=!0,o(t)},prune(e){for(let[t,n]of i)e.has(t)||(o(n),i.delete(t))},prepare(e){r?.prepare(e)},sync(){r?.sync()},clear(){i.forEach(o),i.clear(),r?.clear()},destroy(){this.clear(),r?.destroy()}}}function Se(e,n,r,i,a=typeof i==`string`,o){let s=W(`persona-tool-bubble`,e.id),c=G({expandable:!0,expanded:r,bubbleType:`tool`}),l=t(`div`,``);typeof i==`string`?l.textContent=i:l.appendChild(i);let u=m(n);q(c,l,{config:n,expandable:!0,expanded:r,iconColor:u.toggleTextColor||u.headerTextColor||`currentColor`,metaGap:!0});let d=t(`div`,`persona-border-t`);return d.style.display=r?``:`none`,d.inert=!r,s.append(c,d),Q(s,e,n,`tool`,!0,o),s.dataset.personaToolGroup=`true`,T(n).animation===`height`&&(s.dataset.personaDisclosureMotion=`height`),a&&(s.dataset.activityState===`running`||s.dataset.activityState===`pending`)&&x(l,n,`tool-group`),{bubble:s,body:d}}const Ce=(e,t=!1)=>e.toggleTextColor||e.headerTextColor||(t?`currentColor`:`var(--persona-primary, #171717)`),we=(e,t)=>{let r=(e.chunks??[]).join(``).trim();return r?J(r,-t):J(n(e.args),0,t)},Te=(e,t,n)=>{let r=n?.features?.toolCallDisplay,i=X(n,`tool`)===`row`,a=r?.collapsedMode??y.collapsedMode,c=t.success===!1?t.error||`Tool failed`:we(t,r?.previewMaxLines??y.previewMaxLines),l=i&&a===`tool-call`?oe({...t,approvalStatus:e.approval?.status??t.approvalStatus}):t.interrupted?`${t.name?.trim()||`Tool`} · Interrupted`:n?.future?.v5Defaults||i?`${t.status===`complete`?`Used`:`Using`} ${t.name?.trim()||`tool`}`:o(t),u=t.status!==`complete`,d=n?.toolCall??{},f=u&&i&&a===`tool-call`&&!z(e)?V(e,n):l;a===`tool-name`?f=t.name?.trim()||l:a===`tool-preview`&&c&&(f=c),u&&d.activeTextTemplate?f=s(t,d.activeTextTemplate,f):!u&&!t.interrupted&&d.completeTextTemplate&&(f=s(t,d.completeTextTemplate,f)),t.interrupted?f.includes(` · Interrupted`)||(f+=` · Interrupted`):t.success===!1?f+=` · Failed`:t.superseded&&(f+=` · Approved, ran again below`);let p=e.approval?.status??t.approvalStatus;return p===`pending`?f+=` · Waiting for approval`:p===`denied`?f+=` · Approval denied`:p===`timeout`&&(f+=` · Approval expired`),{summary:f,previewText:c,isActive:u}},Ee=(e,t,n,r)=>{ge(e,t,{stateSet:n,config:r,iconColor:Ce(m(r),t.classList.contains(`persona-activity-row`))})},De=(r,i,a=/* @__PURE__ */ new Set)=>{i=Y(i,`tool`,r);let o=r.toolCall,s=m(i),c=W(`persona-tool-bubble`,r.id);if(s.backgroundColor&&(c.style.backgroundColor=s.backgroundColor),s.borderColor&&(c.style.borderColor=s.borderColor),s.borderWidth&&(c.style.borderWidth=s.borderWidth),s.borderRadius&&(c.style.borderRadius=s.borderRadius),c.style.boxShadow=s.shadow===void 0?`var(--persona-tool-bubble-shadow)`:s.shadow.trim()===``?`none`:s.shadow,!o)return Q(c,r,i,`tool`);o.id&&(c.dataset.toolCallId=o.id);let l=i.features.toolCallDisplay,u=l.expandable??y.expandable,d=u&&a.has(r.id),{summary:f,previewText:_,isActive:v}=Te(r,o,i),b=G({expandable:u,expanded:d,bubbleType:`tool`});s.headerBackgroundColor&&(b.style.backgroundColor=s.headerBackgroundColor),p(b,i,`header`);let S=t(`div`,`persona-flex persona-flex-col persona-text-left`),C=t(`span`,`persona-text-xs persona-text-persona-primary`);s.headerTextColor&&(C.style.color=s.headerTextColor);let w=String(o.startedAt??Date.now()),T=()=>{let e=t(`span`,``);return v&&e.setAttribute(`data-tool-elapsed`,w),e.textContent=g(o),e},E=s.renderCollapsedSummary?.({message:r,toolCall:o,defaultSummary:f,actionTitle:B(r,i),previewText:_,collapsedMode:l.collapsedMode??y.collapsedMode,isActive:v,config:i,elapsed:g(o),createElapsedElement:T}),D=ve(S,C,E,f),O=s.activeTextTemplate,k=o.interrupted?void 0:s.completeTextTemplate,A=v?O:k;D||(A&&_e(C,A,o.name?.trim()||`tool`,v,g(o),T),v&&x(C,i,`tool`));let j=Ce(s,X(i,`tool`)===`row`),M=q(b,S,{config:i,expandable:u,expanded:d,iconColor:j,metaGap:!0}),N=me({bubble:c,previewKind:`tool`,expanded:d,isActive:v,previewText:_,activePreview:l.activePreview,activeMinHeight:l.activeMinHeight,renderPreview:()=>s.renderCollapsedPreview?.({message:r,toolCall:o,defaultPreview:_,isActive:v,config:i})});if(!u)return c.append(b,N),Q(c,r,i,`tool`);let P=t(`div`,`persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3`);P.style.display=d?``:`none`,s.contentBackgroundColor&&(P.style.backgroundColor=s.contentBackgroundColor),s.contentTextColor&&(P.style.color=s.contentTextColor),p(P,i,`content`);let F=i.future?.v5Defaults===!0;if(l.showToolName&&o.name&&P.appendChild(e(`div`,{className:`persona-text-xs persona-text-persona-muted${F?``:` persona-italic`}`,attrs:{"data-persona-tool-name":``},text:o.name,style:{color:F?void 0:s.contentTextColor||s.headerTextColor}})),F)h(P,r,i);else{let r=(r,i)=>{let a=t(`div`,`persona-space-y-1`),o=e(`div`,{className:`persona-text-xs persona-text-persona-muted`,text:r,style:{color:s.labelTextColor}}),c=e(`pre`,{className:`persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs`,style:{fontSize:`0.75rem`,lineHeight:`1rem`,backgroundColor:s.codeBlockBackgroundColor??`var(--persona-container, #f3f4f6)`,borderColor:s.codeBlockBorderColor??`var(--persona-border, #e5e7eb)`,color:s.codeBlockTextColor??`var(--persona-text, #171717)`}},e(`span`,{className:`persona-activity-scroll`,text:n(i),attrs:{role:`region`,"aria-label":r}}));a.append(o,c),P.appendChild(a)};o.args!==void 0&&r(`Arguments`,o.args),o.chunks?.length&&r(`Activity`,o.chunks.join(``)),o.success===!1&&P.appendChild(e(`div`,{className:`persona-text-sm persona-whitespace-pre-wrap`,text:o.error||`Tool failed`,attrs:{"data-persona-tool-error":``}})),o.status===`complete`&&o.result!==void 0&&r(`Result`,o.result)}return he({expanded:d,header:b,toggleIcon:M,content:P,collapsedPreview:N,iconColor:j,config:i}),c.append(b,N,P),Q(c,r,i,`tool`)},$=(e,t,n,r)=>{ge(e,t,{stateSet:n,config:r,iconColor:`currentColor`})},Oe=(n,r,i=/* @__PURE__ */ new Set)=>{r=Y(r,`reasoning`,n);let o=n.reasoning,s=W(`persona-reasoning-bubble`,n.id);if(!o)return Q(s,n,r,`reasoning`);let c=r.features.reasoningDisplay,l=c.expandable??b.expandable,f=l&&i.has(n.id),p=o.status!==`complete`,m=J(n.reasoning?.chunks.join(``)??``,0,c.previewMaxLines??b.previewMaxLines),h=G({expandable:l,expanded:f,bubbleType:`reasoning`}),g=t(`div`,`persona-flex persona-flex-col persona-text-left`),_=t(`span`,`persona-text-xs persona-text-persona-primary`),v=X(r,`reasoning`)===`row`;s.dataset.appearance=c.appearance??(r.future?.v5Defaults?`inset`:v?`plain`:`panel`);let y=v&&!p?`Thought for ${Z(o.durationMs??(o.completedAt-o.startedAt||void 0))}`:`Thinking...`,S=r.reasoning??{},C=String(o.startedAt??Date.now()),w=()=>{let e=t(`span`,``);return e.setAttribute(`data-tool-elapsed`,C),e.textContent=u(o),e},T=S.renderCollapsedSummary?.({message:n,reasoning:o,defaultSummary:y,previewText:m,isActive:p,config:r,elapsed:u(o),createElapsedElement:w}),E=ve(g,_,T,y),D=t(`span`,`persona-text-xs persona-text-persona-primary`);D.textContent=a(o),v||g.appendChild(D);let O=S.activeTextTemplate,k=S.completeTextTemplate,A=p?O:k;if(E||(A&&(D.style.display=`none`,_e(_,A,``,p,u(o),w)),_.style.display=!A&&!p&&!v?`none`:``,p&&x(_,r,`reasoning`)),c.iconName&&!E){let e=t(`span`,`persona-reasoning-header-icon`),n=d(c.iconName,16,`currentColor`,2);n&&(e.appendChild(n),h.appendChild(e))}let j=`currentColor`,M=q(h,g,{config:r,expandable:l,expanded:f,iconColor:j,metaGap:!1}),N=me({bubble:s,previewKind:`reasoning`,expanded:f,isActive:p,previewText:m,activePreview:c.activePreview,activeMinHeight:c.activeMinHeight,renderPreview:()=>r.reasoning?.renderCollapsedPreview?.({message:n,reasoning:o,defaultPreview:m,isActive:p,config:r})});if(!l)return s.append(h,N),Q(s,n,r,`reasoning`);let P=t(`div`,`persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3`),F=c.maxHeight,I=e(`div`,{className:`persona-whitespace-pre-wrap`},e(`div`,{className:`persona-activity-scroll`,text:o.chunks.join(``)||(p?`Waiting for details…`:`No additional context was shared.`),style:{maxHeight:F},attrs:{tabindex:`0`,role:`region`,"aria-label":`Reasoning`}}));return P.appendChild(I),he({expanded:f,header:h,toggleIcon:M,content:P,collapsedPreview:N,iconColor:j,config:r}),s.append(h,N,P),Q(s,n,r,`reasoning`)};function ke(e){let{config:n,messages:r,tempContainer:a,streaming:o,runActivity:s,showToolCalls:c,showReasoning:u,dropCompletedToolCalls:d,dropReasoningRow:f,createMessageRow:p,activityIds:m,activityLifecycle:h,toolExpansionState:g}=e,_=i.render;if(n.turnActivity?.enabled&&_)return _(e,{group:Se,tools:ke,classify:R,presentation:H,hasExplicitThemeStyle:l().hasExplicitThemeStyle});let v=n.features?.toolCallDisplay;if(v?.grouped){let e=[],i=[],l=v.groupBoundary===`iteration`,_=v.groupedMode===`summary`,y=()=>{i.length&&e.push(i),i=[]};r.forEach(e=>{if(e.variant===`tool`&&e.toolCall&&c){if(d&&e.toolCall.status===`complete`&&!e.toolCall.interrupted)return;let t=i[i.length-1]?.agentMetadata,n=e.agentMetadata;l&&t&&n&&(t.executionId&&n.executionId&&t.executionId!==n.executionId||t.iteration!==void 0&&n.iteration!==void 0&&t.iteration!==n.iteration)&&y(),i.push(e)}else(e.variant!==`reasoning`||u&&(e.reasoning?.status!==`complete`||!f(e.reasoning)))&&y()}),y();let b=/* @__PURE__ */ new Map;for(let e of a.children)e instanceof HTMLElement&&b.set(e.dataset.wrapperId,e);e.forEach((r,i)=>{let a=r.map(e=>b.get(e.id)).filter(e=>!!e);if(a.length<(_?1:2))return;let c=`tool-group-${r[0].id}`,u=p(c,`assistant`);u.dataset.personaToolGroupRow=`true`,(v.groupAppearance||n.future?.v5Defaults)&&(u.dataset.groupAppearance=v.groupAppearance??`inset`);let d=r.map(e=>e.toolCall),f=d.some(e=>e.interrupted),y=i===e.length-1,S=r.some(e=>s?.messageIds.has(e.id)),C={messages:r,toolCalls:d,config:n,streaming:o,isLatestGroup:y,isCurrentRunGroup:S},w=r.map(e=>e.approval?.status??e.toolCall?.approvalStatus),T=[`pending`,`denied`,`timeout`].find(e=>w.includes(e)),E=!d.some(e=>e.success===!1||e.error),D=f||!E||T,O=d.some(e=>e.status!==`complete`),k=O||!l&&o&&y&&S&&!D,A=`${r.length} tool${r.length===1?``:`s`}`,j=v.groupedMode===`collapsible`||X(n,`tool`)===`row`?se(d.map((e,t)=>({...e,approvalStatus:w[t]})),v.groupSummaryMaxItems):f?`${A} · Interrupted`:`Called ${A}`,M=fe(r,n,j),N=n.toolCall?.renderGroupedSummary?.({...C,defaultSummary:M})??M;if(a[0].before(u),v.groupedMode===`collapsible`){let e={...r[0],id:c,approval:void 0,toolCall:{id:c,status:k?`running`:`complete`,chunks:d.flatMap(e=>e.chunks??[]),success:E,interrupted:f,approvalStatus:T}};if(d.every(e=>Ae(e.startedAt)&&(e.status!==`complete`||Ae(e.completedAt)&&e.completedAt>=e.startedAt))){let t=Math.min(...d.map(e=>e.startedAt)),n=Math.max(...d.map(e=>e.completedAt??e.startedAt));O?e.toolCall.startedAt=t:e.toolCall.durationMs=n-t}m.add(c),h.observe(e,`tool`,g,v,r.find(e=>g.has(e.id))?.id??``);let t=Se(e,n,g.has(c),N,void 0,!k&&!D?ne(d,n):void 0);t.bubble.classList.add(`persona-tool-group`),t.body.dataset.personaToolGroupStack=`true`,u.appendChild(t.bubble),a.forEach((e,n)=>{je(e),e.style.setProperty(`--persona-activity-stagger`,`${n*40}ms`),e.classList.add(`persona-activity-group-child`),t.body.appendChild(e)});return}let P=t(`div`,`persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2`);P.dataset.personaToolGroup=`true`;let F=t(`div`,`persona-tool-group-summary persona-text-xs persona-text-persona-muted`);if(F.id=`tool-group-summary-${r[0].id}`,U(F,N),!(N instanceof HTMLElement)&&k&&!D&&x(F,n,`tool-group`),P.appendChild(F),u.appendChild(P),_){for(let e of a)e.remove();return}let I=t(`div`,`persona-tool-group-stack persona-flex persona-flex-col`);I.id=`tool-group-stack-${r[0].id}`,I.dataset.personaToolGroupStack=`true`,P.appendChild(I),a.forEach((e,n)=>{je(e);let r=t(`div`,`persona-tool-group-item persona-relative`);r.dataset.personaToolGroupItem=`true`,n<a.length-1&&(r.dataset.personaToolGroupConnector=`true`),r.appendChild(e),I.appendChild(r)})})}return!1}const Ae=e=>e>0&&e<=Date.now(),je=e=>e.style.setProperty(`--persona-message-row-max-width`,`100%`);function Me(e){let t=`.persona-activity-scroll`,n=e=>{let t=e.scrollHeight-e.clientHeight,n=e.clientHeight>0&&t>1;e.toggleAttribute(`data-persona-scroll-top`,n&&e.scrollTop>1),e.toggleAttribute(`data-persona-scroll-bottom`,n&&t-e.scrollTop>1),e.tabIndex=n?0:-1},r=typeof ResizeObserver>`u`?void 0:new ResizeObserver(e=>{for(let{target:t}of e)n(t)}),i=()=>{r?.disconnect(),e.querySelectorAll(t).forEach(e=>{r?.observe(e),n(e)})},a=e=>{let r=e.target;r.matches(t)&&n(r)};return e.addEventListener(`scroll`,a,!0),{sync:i,destroy(){r?.disconnect(),e.removeEventListener(`scroll`,a,!0)}}}function Ne(e,t,n,r,i,a,o){return i(n.spacerHeight+e.offsetHeight),n.pending++,()=>w(e,()=>{--n.pending||!o()||(i(t.scrollTop+t.clientHeight+a-r(n.spacerHeight)),n.initialSpacerHeight=n.spacerHeight,n.contentHeightAtAnchor=t.scrollHeight-n.spacerHeight)})}function Pe(e,t,n,r,i,a){let o=Me(e),s=xe((e,o)=>{i.delete(e);let s=a(e);s&&(o===`tool`?Ee(e,s,n,t()):$(e,s,r,t()))},e,t);return{...s,sync(){s.sync(),o.sync()},destroy(){s.destroy(),o.destroy()},observeMessages(e,i){let a=t();for(let t of e){let e=t.variant===`tool`?`tool`:t.variant===`reasoning`?`reasoning`:null;if(!e||X(a,e,t)!==`row`)continue;let o=Y(a,e,t).features,c=e===`tool`?o?.toolCallDisplay:o?.reasoningDisplay;c?.expandable!==!1&&(i.add(t.id),s.observe(t,e,e===`tool`?n:r,c))}}}}export{Pe as createActivityLifecycle,Oe as createReasoningBubble,De as createToolBubble,ke as groupToolRows,Ne as holdScroll,r as initActivityUi,i as turnUi,ye as updateActivityElapsed,$ as updateReasoningBubbleUI,Ee as updateToolBubbleUI};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./chunk-
|
|
1
|
+
import{t as e}from"./chunk-DDAwu89-.js";const t=32768,n=49152,r=e=>{let t=e??{},n=typeof t.targetId==`string`?t.targetId:null;return{id:typeof t.id==`string`?t.id:``,title:typeof t.title==`string`?t.title:``,targetId:n,preview:typeof t.preview==`string`?t.preview:null,messageCount:typeof t.messageCount==`number`?t.messageCount:0,createdAt:typeof t.createdAt==`string`?t.createdAt:``,updatedAt:typeof t.updatedAt==`string`?t.updatedAt:``}},i=`The identity proof was not admitted; account history is unavailable`,a=`The identity proof was rejected`,o=`The request carried no visitor credential`,s=`The stored visitor belongs to a different signed-in user`;function c(e,t,n){let r=new URLSearchParams;for(let[e,t]of Object.entries(n))t!==void 0&&t!==``&&r.set(e,String(t));let i=r.toString();return`${e.clientApiBase()}/v1/client/${t}${i?`?${i}`:``}`}function l(e,t){return t||e.config.features?.history?.scope||(e.config.getIdentityProof?`verified-user`:`browser`)}async function u(e,t,n){let r=e.config.getIdentityProof;if(!r)return n&&e.setHistoryIdentityStatus(e.browserOnlyStatus()),null;n&&e.setHistoryIdentityStatus({state:`verifying`});let i;try{i=await r()??null}catch{throw n&&e.setHistoryIdentityStatus({state:`identity_provider_failed`}),new e.HistoryClientError(`identity_provider_failed`,`The identity proof provider failed`)}if(i)return i;if(t.visitor?.endUserId!=null)throw n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`authentication_required`,`This browser is bound to a signed-in user and needs a fresh identity proof`);return n&&e.setHistoryIdentityStatus({state:`browser_only`,reason:`proof_unavailable_before_binding`}),null}async function d(e,t,n,r){if(t.visitor?.endUserId!=null)return t;let a=await e.reinitWithProof(n);if(a.visitor?.identityStatus!==`admitted`||a.visitor?.endUserId==null)throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,i);return a}async function f(e,t){let n=await t.json().catch(()=>({}));return typeof n.error==`string`?n.error:typeof n.message==`string`?n.message:``}async function p(e,t,n,r){let i=t.toLowerCase();if(i.includes(`invalid_identity_proof`))throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,a);if(i.includes(`visitor token required`))throw new e.HistoryClientError(`visitor_token_missing`,o);if(i.includes(`visitor_identity_mismatch`)){if(!n)throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`visitor_identity_mismatch`,s);return e.reinitWithProof(n)}if(i.includes(`expired`)||i.includes(`not found`))return e.clearClientSession(),e.initSession();throw new e.HistoryClientError(`unauthorized`,t||`History request was not authorized`)}async function m(e,t,n){let r=await f(e,t);if(t.status===404)return new e.HistoryClientError(`not_found`,`Conversation not found`);if(t.status===429){let n=Number.parseInt(t.headers.get(`Retry-After`)??``,10);return new e.HistoryClientError(`rate_limited`,`Too many history requests`,{...Number.isFinite(n)?{retryAfterSeconds:n}:{}})}if(t.status===503&&r.includes(`identity_proof_not_admitted`))return n&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,i);if(t.status===401){let t=r.toLowerCase();return t.includes(`invalid_identity_proof`)?(n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,a)):t.includes(`visitor token required`)?new e.HistoryClientError(`visitor_token_missing`,o):t.includes(`visitor_identity_mismatch`)?new e.HistoryClientError(`visitor_identity_mismatch`,s):new e.HistoryClientError(`unauthorized`,r||`History request was not authorized`)}return new e.HistoryClientError(`request_failed`,r||`History request failed (${t.status})`)}function h(e,t,n,r){let i=t?.toLowerCase()??null;if(n){if(i===`admitted`){r&&e.setHistoryIdentityStatus({state:`verified`});return}throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),i===`ignored`?new e.HistoryClientError(`identity_contract_violation`,`Server reported an ignored identity proof on a success response`):new e.HistoryClientError(`proof_not_admitted`,`The response did not acknowledge the identity proof this request sent`)}if(i===`admitted`)throw new e.HistoryClientError(`identity_contract_violation`,`Server admitted an identity proof that was never sent`);r&&e.setHistoryIdentityStatus(e.browserOnlyStatus())}async function g(t,n,r){_(t);let i=r.trackIdentity!==!1,a=await t.initSession(),o=null;l(t,r.scope)===`verified-user`&&(o=await u(t,a,i),o&&(a=await d(t,a,o,i)));let s=t.historyInternals.visitorStore,g=!1;for(;;){let l=s?.revision()??0,u=await t.readVisitorToken();if(!u&&!r.visitorTokenOptional)throw new t.HistoryClientError(`visitor_token_missing`,`No visitor credential is stored for this browser`);let d=await fetch(c(t,n,{...r.query,sessionId:a.sessionId}),{method:r.method,headers:{"X-Persona-Version":e,...u?{"X-Visitor-Token":u}:{},...o?{"X-Identity-Proof":o}:{},...r.body===void 0?{}:{"Content-Type":`application/json`}},...r.body===void 0?{}:{body:JSON.stringify(r.body)},...r.keepalive?{keepalive:!0}:{}});if(d.status===401&&!g){g=!0,a=await p(t,await f(t,d),o,i);continue}if(!d.ok)throw await m(t,d,i);let _=d.headers.get(`X-History-Identity-Status`),v=await d.json().catch(()=>void 0);if(s&&s.revision()!==l)throw new t.HistoryClientError(`credential_changed`,`The visitor credential changed while the request was in flight`);return h(t,_,o!==null,i),v}}function _(e){if(!e.isClientTokenMode())throw Error(`Conversation history is only available in client token mode`);if(!e.isHistoryCapable())throw new e.HistoryClientError(`history_disabled`,`Visitor history is disabled for this surface`)}async function v(e,t){let n=await g(e,`conversations`,{method:`GET`,query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit===void 0?{}:{limit:t.limit},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(r),nextCursor:typeof n?.nextCursor==`string`?n.nextCursor:null}}async function y(e,t,n){let i=await g(e,`conversations/${encodeURIComponent(t)}`,{method:`GET`,query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:r(i),messages:Array.isArray(i?.messages)?i.messages:[],nextMessageCursor:typeof i?.nextMessageCursor==`string`?i.nextMessageCursor:null,conversationRevision:typeof i?.conversationRevision==`string`?i.conversationRevision:null}}async function b(e,r,i){_(e);let a=0;for(let n of i){let r=n.displayContent.length;if(r>t)throw new e.HistoryClientError(`payload_too_large`,`displayContent exceeds the ${t} character limit`);a+=r}if(a>n)throw new e.HistoryClientError(`payload_too_large`,`Display projection batch exceeds the ${n} character limit`);await e.initSession();let o=e.historyInternals.visitorStore,s=o?.revision()??0,c=await g(e,`conversations/${encodeURIComponent(r)}/display-projections`,{method:`PATCH`,body:{messages:i},scope:`browser`,keepalive:a<=n,trackIdentity:!1}),l=typeof c?.conversationRevision==`string`?c.conversationRevision:null;return l&&e.clientSession?.conversationId===r&&(o?.revision()??0)===s&&e.historyInternals.setStoredConversationRevision?.(l),{conversationRevision:l}}async function x(e,t,n){let r=await g(e,`conversations/${encodeURIComponent(t)}`,{method:`DELETE`,...n?.scope?{scope:n.scope}:{}});return{deleted:typeof r?.deleted==`number`?r.deleted:0}}async function S(e,t){let n=await g(e,`conversations`,{method:`DELETE`,query:{...t?.targetId===void 0?{}:{targetId:t.targetId}},...t?.scope?{scope:t.scope}:{}});return{deleted:typeof n?.deleted==`number`?n.deleted:0}}async function C(e){_(e),e.setHistoryIdentityStatus({state:`resetting`});try{await g(e,`visitor/reset`,{method:`POST`,scope:`browser`,visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}export{S as deleteAllConversations,x as deleteConversation,b as finalizeDisplayProjections,y as getConversation,m as historyErrorFor,v as listConversations,f as readErrorCode,p as recoverFromUnauthorized,C as resetVisitor};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./chunk-DbD5qyBw.js";import{Marked as t}from"marked";import n from"dompurify";const r=e=>!e||/\s/.test(e),i=e=>!!e&&/[\p{P}\p{S}]/u.test(e),a=(e,t,n)=>{let r=e.slice(t,n),i=n;for(;(i=e.indexOf(r,i))!==-1;){if(e[i-1]!=="`"&&e[i+r.length]!=="`")return i+r.length;i+=r.length}return-1},o=(e,t=!0)=>{let n=[],s=/* @__PURE__ */ new Set,c=``;for(let l=0;l<e.length;){let u=e[l];if(u===`\\`)c+=e.slice(l,l+2),l+=2;else if(u==="`"){let t=l+1;for(;e[t]==="`";)t++;let n=e.slice(l,t),r=a(e,l,t);if(r!==-1)c+=e.slice(l,r),l=r;else{let r=e.slice(t);c+=r?`${n}${r}${r.endsWith("`")?` `:``}${n}`:``,l=e.length}}else if(u===`<`){let t=e.indexOf(`>`,l+1);c+=e.slice(l,t<0?e.length:t+1),l=t<0?e.length:t+1}else if(t&&(u===`[`||u===`!`&&e[l+1]===`[`)){let t=u===`!`,n=l+(t?2:1),i=1,s=n;for(;s<e.length;s++)if(e[s]===`\\`)s++;else if(e[s]==="`"){let t=s+1;for(;e[t]==="`";)t++;let n=a(e,s,t);s=(n<0?t:n)-1}else if(e[s]===`[`&&i++,e[s]===`]`&&--i===0)break;if(s>=e.length){c+=t?``:o(e.slice(n),!1);break}if(e[s+1]===`(`){let i=1,a=``,u=!1,d=s+2;for(;d<e.length;d++){let t=e[d];if(t===`\\`)d++;else if(a)t===a&&(a=``);else if((t===`"`||t===`'`)&&r(e[d-1]))a=t;else if(t===`<`&&(u=!0),t===`>`&&(u=!1),!u&&t===`(`&&i++,!u&&t===`)`&&--i===0)break}if(d>=e.length){c+=t?``:o(e.slice(n,s),!1);break}c+=e.slice(l,d+1),l=d+1;continue}if(s===e.length-1){c+=t?``:o(e.slice(n,s),!1);break}c+=e.slice(l,s+1),l=s+1}else if(u===`*`||u===`_`){let t=l+1;for(;e[t]===u;)t++;let a=e.slice(l,t),o=e[l-1]??``,d=e[t]??``,f=!r(d)&&(!i(d)||r(o)||i(o)),p=!r(o)&&(!i(o)||r(d)||i(d)),m=a.length;if(p&&(u!==`_`||!f||i(d)))for(;m&&n[n.length-1]?.marker[0]===u;){let e=n[n.length-1],t=Math.min(m,e.marker.length);m-=t,e.marker=e.marker.slice(t),e.marker||n.pop()}if(m&&a.length<=3&&f&&!p)n.push({marker:u.repeat(m)});else if(m===a.length&&t===e.length&&r(o)&&e.slice(e.lastIndexOf(`
|
|
2
|
+
`,l)+1,l).trim()&&(n.length>0||!s.has(u))){l=t;continue}r(o)&&r(d)&&t<e.length&&s.add(u),c+=a,l=t}else c+=u,l++}let l=c.match(/\s*$/)?.[0]??``;c=c.slice(0,c.length-l.length),n.length&&(c.match(/\\+$/)?.[0].length??0)%2&&(c+=`\\`);for(let e=n.length-1;e>=0;e--)c+=n[e].marker;return c+l},s=t=>{let n=``,r=``,i=``,a=()=>{n+=e(r).split(/(\n\s*\n)/).map(e=>/^\n\s*\n$/.test(e)?e:o(e)).join(``),r=``};for(let e of t.match(/[^\n]*\n|[^\n]+$/g)??[]){let t=/^(?: {0,3}> ?)* {0,3}(?:[-+*] )?(`{3,}|~{3,})(.*)/.exec(e);i?(n+=e,t&&t[1][0]===i[0]&&t[1].length>=i.length&&!t[2].trim()&&(i=``)):t?(a(),i=t[1],n+=e):/^(?: {4}|\t)/.test(e)?(a(),n+=e):r+=e}return a(),n};export{n as DOMPurify,t as Marked,s as stabilizeStreamingMarkdown};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=`4.32.0`;export{e as t};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{t as e}from"./chunk-
|
|
1
|
+
import{t as e}from"./chunk-DDAwu89-.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
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(`
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
const e=/^\s*\|?[\s:|-]*-[\s:|-]*$/,t=e=>e.includes(`|`),n=e=>{let t=e.trim();return t.startsWith(`|`)&&(t=t.slice(1)),t.endsWith(`|`)&&(t=t.slice(0,-1)),t.split(`|`).map(e=>e.trim())},r=e=>`| ${e.join(` | `)} |`,i=e=>`| ${Array.from({length:e},()=>`---`).join(` | `)} |`,a=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>``)),o=o=>{if(!o||!o.includes(`|`))return o;let s=o.split(`
|
|
2
|
+
`),c=!1;for(let o=0;o<s.length-1;o++){let l=s[o],u=s[o+1];if(!t(l)||e.test(l)||!e.test(u))continue;let d=n(l).length;if(d<1)continue;let f=i(d);s[o+1]!==f&&(s[o+1]=f,c=!0);let p=o+2;for(;p<s.length;p++){let e=s[p];if(e.trim()===``||!t(e))break;let i=r(a(n(e),d));s[p]!==i&&(s[p]=i,c=!0)}o=p-1}return c?s.join(`
|
|
3
|
+
`):o};export{o as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e}from"./chunk-BAdIgC5d.js";import{t}from"./chunk-18tPmsiJ.js";import{t as n}from"./chunk-Bz9jAgba.js";import{n as r}from"./chunk-DTDHeUsG.js";const i=e=>e.replace(/[^a-zA-Z0-9_]/g,`_`).toLowerCase().replace(/_+/g,`_`).replace(/^_|_$/g,``),a=e=>typeof e==`object`&&!!e&&!Array.isArray(e),o=e=>{if(e.variant!==`tool`)return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=i(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:a(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},s=(e,t)=>{let n=[],r=[],i=[],a=``,s,c=()=>{r.length!==0&&(n.push({role:`assistant`,content:``,createdAt:a,toolCalls:r},{role:`tool`,content:``,createdAt:a,toolResults:i}),r=[],i=[])};for(let l of e){let e=o(l);if(e){let t=l.agentMetadata?.clientToolAnswer?.batch;r.length>0&&(t===void 0||t!==s)&&c(),r.length===0&&(a=l.createdAt,s=t),r.some(t=>t.toolCallId===e.call.toolCallId)||(r.push(e.call),i.push(e.result));continue}let u=t(l);u&&(c(),n.push(u))}return c(),n},c=e=>e.voiceCaption||r(e)?!1:!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0),l=e=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),u=e=>{let t=e.agentMetadata?.providerPhase??e.agentMetadata?.phase;return e.role===`assistant`&&(t===`commentary`||t===`partial_answer`||t===`final_answer`)?{phase:t}:{}},d=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt,...u(e)});var f=class{constructor(e){this.host=e}async initializeSession(){await this.host.historyInternals.historyBootstrapReady;let e=this.host.config.getStoredConversationId?.()||null,t=this.host.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.host.isHistoryCapable()&&!t)return this.#e(e,!1);let n=await this.host.readVisitorToken();if(e&&n)try{let n=await this.createClientSession({conversationId:e,durableResume:t});return t&&n.durableRecovery?.enabled!==!0&&this.host.historyInternals.setStoredResumableHandle?.(null),this.host.finishInit(n,e,!1)}catch(n){if(!(n instanceof this.host.HistoryClientError&&n.code===`not_found`)&&!(n instanceof this.host.HistoryClientError&&n.code===`visitor_required`)&&!(n instanceof this.host.HistoryClientError&&n.code===`history_disabled`))throw n;return t&&this.host.historyInternals.setStoredResumableHandle?.(null),this.#e(e,!0)}return this.#e(e,!1)}async#e(e,t){let n=this.host.historyInternals.visitorStore;return n&&!await this.host.readVisitorToken()?n.withFirstInitLock(()=>this.#t(e,t)):this.#t(e,t)}async#t(e,t){let n=this.host.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:n}),i=await this.#n(r);return this.host.finishInit(i,e,t)}async#n(e){if(!e.visitor?.token||this.host.claimInFlight||!this.host.isHistoryCapable()&&e.durableRecovery?.enabled!==!0)return e;this.host.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:e.sessionId})}catch{return e}finally{this.host.claimInFlight=!1}}async sendWithClientToolsDiff(t,n,r,i){let a=!!(n&&n.length>0),o=a?e(n):void 0,s=this.host.clientToolsFingerprintSessionId===t,c=a&&s&&this.host.lastSentClientToolsFingerprint===o,l=!a&&i?.emptyMeansReplace===!0&&this.host.sentNonEmptyClientToolsSessionId===t,u=!1,d;for(let e=0;d=await r({...a&&(u||!c)&&n?{clientTools:n}:{},...l?{clientTools:[]}:{},...o?{clientToolsFingerprint:o}:{}}),d.status===409&&e===0&&a&&(await d.clone().json().catch(()=>null))?.error===`client_tools_resend_required`;e++)u=!0,this.host.lastSentClientToolsFingerprint=null;return{response:d,commit:()=>{this.host.lastSentClientToolsFingerprint=o??null,this.host.clientToolsFingerprintSessionId=t,a?this.host.sentNonEmptyClientToolsSessionId=t:l&&(this.host.sentNonEmptyClientToolsSessionId=null)}}}async createClientSession(e){let n=this.host.isHistoryCapable()&&!e.omitVisitorFields,r=!e.omitVisitorFields,i=null;(n||r)&&(await this.host.historyInternals.historyBootstrapReady,i=await this.host.readVisitorToken());let a=this.host.routing(),o=a.agentId??a.flowId,s=n||e.durableResume?e.conversationId:void 0,c={token:this.host.config.clientToken,...o&&{flowId:o},...n&&{visitorHistory:!0},...r&&{durableRecovery:!0},...(n||r)&&i?{visitorToken:i}:{},...n&&e.identityProof?{identityProof:e.identityProof}:{},...s?{conversationId:s}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let l=await fetch(this.host.getClientApiUrl(`init`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":t},body:JSON.stringify(c),signal:e.signal});if(!l.ok){let t=await l.json().catch(()=>({error:`Session initialization failed`}));if(n&&l.status===403&&t.error===`visitor_history_disabled`){if(this.host.markHistoryUnavailable(),s)throw new this.host.HistoryClientError(`history_disabled`,`Visitor history is disabled for this surface`);return this.createClientSession({...e,omitVisitorFields:!0})}throw l.status===403&&t.error===`durable_recovery_disabled`?new this.host.HistoryClientError(`history_disabled`,`Durable recovery is disabled for this surface`):(n||e.durableResume)&&l.status===401&&t.error===`visitor_required`?new this.host.HistoryClientError(`visitor_required`,`Visitor credential no longer resolves`):s&&l.status===404?new this.host.HistoryClientError(`not_found`,`Conversation not found`):l.status===401?Error(`Invalid client token: ${t.hint||t.error}`):l.status===403?Error(`Origin not allowed: ${t.hint||t.error}`):Error(t.error||`Failed to initialize session`)}let u=await l.json();return u.visitor?.token&&await this.host.historyInternals.visitorStore?.set(u.visitor.token),{sessionId:u.sessionId,expiresAt:new Date(u.expiresAt),flow:u.flow,...u.conversationId?{conversationId:u.conversationId}:{},...u.targetId?{targetId:u.targetId}:{},...u.conversationRevision?{conversationRevision:u.conversationRevision}:{},...u.durableRecovery?{durableRecovery:u.durableRecovery}:{},...u.visitor?{visitor:u.visitor}:{},config:{welcomeMessage:u.config.welcomeMessage,placeholder:u.config.placeholder,theme:u.config.theme}}}async sendFeedback(e){if([`upvote`,`downvote`,`copy`].includes(e.type)&&!e.messageId)throw Error(`messageId is required for ${e.type} feedback type`);if(e.type===`csat`&&(e.rating===void 0||e.rating<1||e.rating>5))throw Error(`CSAT rating must be between 1 and 5`);if(e.type===`nps`&&(e.rating===void 0||e.rating<0||e.rating>10))throw Error(`NPS rating must be between 0 and 10`);this.host.debug&&console.debug(`[AgentWidgetClient] sending feedback`,e);let n={...e,...this.host.config.clientToken&&{token:this.host.config.clientToken}},r=await fetch(`${this.host.clientApiBase()}/v1/client/feedback`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":t},body:JSON.stringify(n)});if(!r.ok){let e=await r.json().catch(()=>({error:`Feedback submission failed`}));throw r.status===401?(this.host.clientSession=null,this.host.resetSessionWarmLatch(),this.host.config.onSessionExpired?.(),Error(`Session expired. Please refresh to continue.`)):Error(e.error||`Failed to submit feedback`)}}async dispatchClientToken(e,r,i){let{HistoryClientError:a}=this.host,o=()=>this.host.isCurrentTurn(i),s=e=>{o()&&r(e)};try{let r=()=>{if(e.signal?.throwIfAborted(),!o())throw new DOMException(`Turn superseded`,`AbortError`)},l=this.host.clientSession??await this.host.initSession();r();let u=async()=>{r();let t=l,n=t.durableRecovery?.enabled===!0;if(n&&(!t.conversationId||!await this.host.readVisitorToken()))throw Error(`Renewing this conversation requires its visitor credential.`);r();let i=await this.host.createClientSession({...n||this.host.isHistoryCapable()?{conversationId:t.conversationId,durableResume:n}:{storedSessionId:t.sessionId},signal:e.signal});if(r(),t.conversationId&&i.conversationId!==t.conversationId||n&&i.durableRecovery?.enabled!==!0)throw Error(`Session renewal did not preserve this conversation.`);l=this.host.finishInit(i,t.conversationId??null,!1),this.host.clientSession=l,this.host.resetSessionWarmLatch(),this.host.resetClientToolsFingerprint(),this.host.config.onSessionInit?.(l)};Date.now()>=l.expiresAt.getTime()-6e4&&await u();let d=await this.#c(e.messages),f=d.metadata?Object.fromEntries(Object.entries(d.metadata).filter(([e])=>e!==`sessionId`&&e!==`session_id`)):void 0,p=this.host.isHistoryCapable(),m={sessionId:l.sessionId,messages:e.messages.filter(c).map(e=>{let t=p?n(e):void 0;return{id:e.id,role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,...t!==void 0&&{displayContent:t}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...f&&Object.keys(f).length>0&&{metadata:f},...d.inputs&&Object.keys(d.inputs).length>0&&{inputs:d.inputs},...d.context&&{context:d.context},turnId:i,...e.interrupt&&{submitMode:`interrupt`},...e.voiceSpoken&&{voice:{spoken:!0,...e.voicePriorToolResults?.length&&{priorToolResults:e.voicePriorToolResults}}}},h=async()=>{r();let n=l.durableRecovery?.enabled===!0?await this.host.readVisitorToken():null;return r(),this.host.sendWithClientToolsDiff(l.sessionId,d.clientTools,async i=>{r();let a=await this.host.resolveChatIdentityProof(e.signal);r();let o={...m,sessionId:l.sessionId,...i,...a&&{identityProof:a}};return this.host.debug&&console.debug(`[AgentWidgetClient] client token dispatch`,{...o,...a&&{identityProof:{provider:a.provider,token:`[REDACTED]`}}}),fetch(this.host.getClientApiUrl(`chat`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":t,...n?{"X-Visitor-Token":n}:{}},body:JSON.stringify(o),signal:e.signal})})},g=await h();if(r(),g.response.status===401){let e=await g.response.clone().json().catch(()=>null);r(),e?.error===`Session not found or expired`&&(await u(),g=await h(),r())}let{response:_,commit:v}=g;if(!_.ok){let e=await _.json().catch(()=>({error:`Chat request failed`}));if(_.status===401&&e.error===`invalid_identity_proof`){let e=new a(`invalid_identity_proof`,`The identity proof was rejected`);throw s({type:`error`,error:e}),e}if(_.status===401){this.host.clearClientSession(),this.host.config.onSessionExpired?.();let e=/* @__PURE__ */ Error(`Session expired. Please refresh to continue.`);throw s({type:`error`,error:e}),e}if(_.status===429){let t=Error(e.hint||`Message limit reached for this session.`);throw s({type:`error`,error:t}),t}if(_.status===410&&e.error===`conversation_deleted`){let e=new a(`conversation_deleted`,`This conversation was deleted`);throw s({type:`error`,error:e}),e}let t=Error(e.error||`Failed to send message`);throw s({type:`error`,error:t}),t}if(!_.body){let e=/* @__PURE__ */ Error(`No response body received`);throw s({type:`error`,error:e}),e}v(),s({type:`status`,status:`connected`});try{await this.host.streamResponse(_.body,s,e.assistantMessageId,void 0,e.signal)}finally{s({type:`status`,status:`idle`})}}catch(e){let t=e instanceof Error?e:Error(String(e));throw!(t instanceof a)&&!t.message.includes(`Session expired`)&&!t.message.includes(`Message limit`)&&s({type:`error`,error:t}),t}}async dispatchProxy(e,t){let n=await this.#c(e.messages,e.composerOptions);this.host.debug&&console.debug(`[AgentWidgetClient] dispatch payload`,n);let r={...this.host.headers};if(this.host.getHeaders)try{let e=await this.host.getHeaders();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.host.customFetch)try{i=await this.host.customFetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.host.streamResponse(i.body,t,void 0,void 0,e.signal)}finally{t({type:`status`,status:`idle`})}}async dispatchAgent(e,t){let n=await this.#s(e.messages,e.composerOptions);this.host.debug&&console.debug(`[AgentWidgetClient] agent dispatch payload`,n);let r={...this.host.headers};if(this.host.getHeaders)try{let e=await this.host.getHeaders();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.host.customFetch)try{i=await this.host.customFetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.host.streamResponse(i.body,t,e.assistantMessageId,void 0,e.signal)}finally{t({type:`status`,status:`idle`})}}#r(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`user`)return n.mentionContext&&Object.keys(n.mentionContext).length>0?{mentions:n.mentionContext}:null}return null}async#i(e){let t={};this.host.contextProviders.length&&await Promise.all(this.host.contextProviders.map(async n=>{try{let r=await n({messages:e,config:this.host.config});r&&typeof r==`object`&&Object.assign(t,r)}catch(e){typeof console<`u`&&console.warn(`[AgentWidget] Context provider failed:`,e)}}));let n=this.#r(e);return n&&Object.assign(t,n),Object.keys(t).length?t:null}#a(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}#o(e,t){let n=t?.selectedModelId;return!n||!(`model`in e)?e:this.host.config.composer?.models?.some(e=>e.id===n)?{...e,model:n}:e}async#s(e,t){let n=this.host.routing().agentId;if(!this.host.config.agent&&!n)throw Error(`Agent configuration required for agent mode`);let r=s(l(e),e=>c(e)&&(e.role===`user`||e.role===`assistant`||e.role===`system`)&&(!e.variant||e.variant===`assistant`)?d(e):null),i=this.#a(t),a={agent:this.#o(this.host.config.agent??{agentId:n},i),messages:r,options:{streamResponse:!0,recordMode:`virtual`,...this.host.config.agentOptions}};i&&(a.composerOptions=i);let o=[...this.host.builtInClientTools(this.host.config),...await(await this.host.getWebMcpBridge())?.snapshotForDispatch()??[]];o.length>0&&(a.clientTools=o);let u=await this.#i(e);return u&&(a.context=u),a}async#c(e,t){let n=s(l(e),e=>c(e)?d(e):null),r=this.host.routing(),i={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[e,t]of Object.entries(r.targetPayload))e!==`messages`&&(i[e]=t);let a=[...this.host.builtInClientTools(this.host.config),...await(await this.host.getWebMcpBridge())?.snapshotForDispatch()??[]];a.length>0&&(i.clientTools=a);let o=await this.#i(e);o&&(i.context=o);let u=this.#a(t);if(u&&(i.composerOptions=u),this.host.requestMiddleware)try{let e=await this.host.requestMiddleware({payload:{...i},config:this.host.config});if(e&&typeof e==`object`){let t=e;return i.clientTools!==void 0&&!(`clientTools`in t)&&(t.clientTools=i.clientTools),t}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Request middleware error:`,e)}return i}};export{f as ClientDispatch};
|
|
1
|
+
import{n as e}from"./chunk-BAdIgC5d.js";import{t}from"./chunk-DDAwu89-.js";import{t as n}from"./chunk-Bz9jAgba.js";import{n as r}from"./chunk-DTDHeUsG.js";const i=e=>e.replace(/[^a-zA-Z0-9_]/g,`_`).toLowerCase().replace(/_+/g,`_`).replace(/^_|_$/g,``),a=e=>typeof e==`object`&&!!e&&!Array.isArray(e),o=e=>{if(e.variant!==`tool`)return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=i(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:a(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},s=(e,t)=>{let n=[],r=[],i=[],a=``,s,c=()=>{r.length!==0&&(n.push({role:`assistant`,content:``,createdAt:a,toolCalls:r},{role:`tool`,content:``,createdAt:a,toolResults:i}),r=[],i=[])};for(let l of e){let e=o(l);if(e){let t=l.agentMetadata?.clientToolAnswer?.batch;r.length>0&&(t===void 0||t!==s)&&c(),r.length===0&&(a=l.createdAt,s=t),r.some(t=>t.toolCallId===e.call.toolCallId)||(r.push(e.call),i.push(e.result));continue}let u=t(l);u&&(c(),n.push(u))}return c(),n},c=e=>e.voiceCaption||r(e)?!1:!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0),l=e=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),u=e=>{let t=e.agentMetadata?.providerPhase??e.agentMetadata?.phase;return e.role===`assistant`&&(t===`commentary`||t===`partial_answer`||t===`final_answer`)?{phase:t}:{}},d=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt,...u(e)});var f=class{constructor(e){this.host=e}async initializeSession(){await this.host.historyInternals.historyBootstrapReady;let e=this.host.config.getStoredConversationId?.()||null,t=this.host.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.host.isHistoryCapable()&&!t)return this.#e(e,!1);let n=await this.host.readVisitorToken();if(e&&n)try{let n=await this.createClientSession({conversationId:e,durableResume:t});return t&&n.durableRecovery?.enabled!==!0&&this.host.historyInternals.setStoredResumableHandle?.(null),this.host.finishInit(n,e,!1)}catch(n){if(!(n instanceof this.host.HistoryClientError&&n.code===`not_found`)&&!(n instanceof this.host.HistoryClientError&&n.code===`visitor_required`)&&!(n instanceof this.host.HistoryClientError&&n.code===`history_disabled`))throw n;return t&&this.host.historyInternals.setStoredResumableHandle?.(null),this.#e(e,!0)}return this.#e(e,!1)}async#e(e,t){let n=this.host.historyInternals.visitorStore;return n&&!await this.host.readVisitorToken()?n.withFirstInitLock(()=>this.#t(e,t)):this.#t(e,t)}async#t(e,t){let n=this.host.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:n}),i=await this.#n(r);return this.host.finishInit(i,e,t)}async#n(e){if(!e.visitor?.token||this.host.claimInFlight||!this.host.isHistoryCapable()&&e.durableRecovery?.enabled!==!0)return e;this.host.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:e.sessionId})}catch{return e}finally{this.host.claimInFlight=!1}}async sendWithClientToolsDiff(t,n,r,i){let a=!!(n&&n.length>0),o=a?e(n):void 0,s=this.host.clientToolsFingerprintSessionId===t,c=a&&s&&this.host.lastSentClientToolsFingerprint===o,l=!a&&i?.emptyMeansReplace===!0&&this.host.sentNonEmptyClientToolsSessionId===t,u=!1,d;for(let e=0;d=await r({...a&&(u||!c)&&n?{clientTools:n}:{},...l?{clientTools:[]}:{},...o?{clientToolsFingerprint:o}:{}}),d.status===409&&e===0&&a&&(await d.clone().json().catch(()=>null))?.error===`client_tools_resend_required`;e++)u=!0,this.host.lastSentClientToolsFingerprint=null;return{response:d,commit:()=>{this.host.lastSentClientToolsFingerprint=o??null,this.host.clientToolsFingerprintSessionId=t,a?this.host.sentNonEmptyClientToolsSessionId=t:l&&(this.host.sentNonEmptyClientToolsSessionId=null)}}}async createClientSession(e){let n=this.host.isHistoryCapable()&&!e.omitVisitorFields,r=!e.omitVisitorFields,i=null;(n||r)&&(await this.host.historyInternals.historyBootstrapReady,i=await this.host.readVisitorToken());let a=this.host.routing(),o=a.agentId??a.flowId,s=n||e.durableResume?e.conversationId:void 0,c={token:this.host.config.clientToken,...o&&{flowId:o},...n&&{visitorHistory:!0},...r&&{durableRecovery:!0},...(n||r)&&i?{visitorToken:i}:{},...n&&e.identityProof?{identityProof:e.identityProof}:{},...s?{conversationId:s}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let l=await fetch(this.host.getClientApiUrl(`init`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":t},body:JSON.stringify(c),signal:e.signal});if(!l.ok){let t=await l.json().catch(()=>({error:`Session initialization failed`}));if(n&&l.status===403&&t.error===`visitor_history_disabled`){if(this.host.markHistoryUnavailable(),s)throw new this.host.HistoryClientError(`history_disabled`,`Visitor history is disabled for this surface`);return this.createClientSession({...e,omitVisitorFields:!0})}throw l.status===403&&t.error===`durable_recovery_disabled`?new this.host.HistoryClientError(`history_disabled`,`Durable recovery is disabled for this surface`):(n||e.durableResume)&&l.status===401&&t.error===`visitor_required`?new this.host.HistoryClientError(`visitor_required`,`Visitor credential no longer resolves`):s&&l.status===404?new this.host.HistoryClientError(`not_found`,`Conversation not found`):l.status===401?Error(`Invalid client token: ${t.hint||t.error}`):l.status===403?Error(`Origin not allowed: ${t.hint||t.error}`):Error(t.error||`Failed to initialize session`)}let u=await l.json();return u.visitor?.token&&await this.host.historyInternals.visitorStore?.set(u.visitor.token),{sessionId:u.sessionId,expiresAt:new Date(u.expiresAt),flow:u.flow,...u.conversationId?{conversationId:u.conversationId}:{},...u.targetId?{targetId:u.targetId}:{},...u.conversationRevision?{conversationRevision:u.conversationRevision}:{},...u.durableRecovery?{durableRecovery:u.durableRecovery}:{},...u.visitor?{visitor:u.visitor}:{},config:{welcomeMessage:u.config.welcomeMessage,placeholder:u.config.placeholder,theme:u.config.theme}}}async sendFeedback(e){if([`upvote`,`downvote`,`copy`].includes(e.type)&&!e.messageId)throw Error(`messageId is required for ${e.type} feedback type`);if(e.type===`csat`&&(e.rating===void 0||e.rating<1||e.rating>5))throw Error(`CSAT rating must be between 1 and 5`);if(e.type===`nps`&&(e.rating===void 0||e.rating<0||e.rating>10))throw Error(`NPS rating must be between 0 and 10`);this.host.debug&&console.debug(`[AgentWidgetClient] sending feedback`,e);let n={...e,...this.host.config.clientToken&&{token:this.host.config.clientToken}},r=await fetch(`${this.host.clientApiBase()}/v1/client/feedback`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":t},body:JSON.stringify(n)});if(!r.ok){let e=await r.json().catch(()=>({error:`Feedback submission failed`}));throw r.status===401?(this.host.clientSession=null,this.host.resetSessionWarmLatch(),this.host.config.onSessionExpired?.(),Error(`Session expired. Please refresh to continue.`)):Error(e.error||`Failed to submit feedback`)}}async dispatchClientToken(e,r,i){let{HistoryClientError:a}=this.host,o=()=>this.host.isCurrentTurn(i),s=e=>{o()&&r(e)};try{let r=()=>{if(e.signal?.throwIfAborted(),!o())throw new DOMException(`Turn superseded`,`AbortError`)},l=this.host.clientSession??await this.host.initSession();r();let u=async()=>{r();let t=l,n=t.durableRecovery?.enabled===!0;if(n&&(!t.conversationId||!await this.host.readVisitorToken()))throw Error(`Renewing this conversation requires its visitor credential.`);r();let i=await this.host.createClientSession({...n||this.host.isHistoryCapable()?{conversationId:t.conversationId,durableResume:n}:{storedSessionId:t.sessionId},signal:e.signal});if(r(),t.conversationId&&i.conversationId!==t.conversationId||n&&i.durableRecovery?.enabled!==!0)throw Error(`Session renewal did not preserve this conversation.`);l=this.host.finishInit(i,t.conversationId??null,!1),this.host.clientSession=l,this.host.resetSessionWarmLatch(),this.host.resetClientToolsFingerprint(),this.host.config.onSessionInit?.(l)};Date.now()>=l.expiresAt.getTime()-6e4&&await u();let d=await this.#c(e.messages),f=d.metadata?Object.fromEntries(Object.entries(d.metadata).filter(([e])=>e!==`sessionId`&&e!==`session_id`)):void 0,p=this.host.isHistoryCapable(),m={sessionId:l.sessionId,messages:e.messages.filter(c).map(e=>{let t=p?n(e):void 0;return{id:e.id,role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,...t!==void 0&&{displayContent:t}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...f&&Object.keys(f).length>0&&{metadata:f},...d.inputs&&Object.keys(d.inputs).length>0&&{inputs:d.inputs},...d.context&&{context:d.context},turnId:i,...e.interrupt&&{submitMode:`interrupt`},...e.voiceSpoken&&{voice:{spoken:!0,...e.voicePriorToolResults?.length&&{priorToolResults:e.voicePriorToolResults}}}},h=async()=>{r();let n=l.durableRecovery?.enabled===!0?await this.host.readVisitorToken():null;return r(),this.host.sendWithClientToolsDiff(l.sessionId,d.clientTools,async i=>{r();let a=await this.host.resolveChatIdentityProof(e.signal);r();let o={...m,sessionId:l.sessionId,...i,...a&&{identityProof:a}};return this.host.debug&&console.debug(`[AgentWidgetClient] client token dispatch`,{...o,...a&&{identityProof:{provider:a.provider,token:`[REDACTED]`}}}),fetch(this.host.getClientApiUrl(`chat`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":t,...n?{"X-Visitor-Token":n}:{}},body:JSON.stringify(o),signal:e.signal})})},g=await h();if(r(),g.response.status===401){let e=await g.response.clone().json().catch(()=>null);r(),e?.error===`Session not found or expired`&&(await u(),g=await h(),r())}let{response:_,commit:v}=g;if(!_.ok){let e=await _.json().catch(()=>({error:`Chat request failed`}));if(_.status===401&&e.error===`invalid_identity_proof`){let e=new a(`invalid_identity_proof`,`The identity proof was rejected`);throw s({type:`error`,error:e}),e}if(_.status===401){this.host.clearClientSession(),this.host.config.onSessionExpired?.();let e=/* @__PURE__ */ Error(`Session expired. Please refresh to continue.`);throw s({type:`error`,error:e}),e}if(_.status===429){let t=Error(e.hint||`Message limit reached for this session.`);throw s({type:`error`,error:t}),t}if(_.status===410&&e.error===`conversation_deleted`){let e=new a(`conversation_deleted`,`This conversation was deleted`);throw s({type:`error`,error:e}),e}let t=Error(e.error||`Failed to send message`);throw s({type:`error`,error:t}),t}if(!_.body){let e=/* @__PURE__ */ Error(`No response body received`);throw s({type:`error`,error:e}),e}v(),s({type:`status`,status:`connected`});try{await this.host.streamResponse(_.body,s,e.assistantMessageId,void 0,e.signal)}finally{s({type:`status`,status:`idle`})}}catch(e){let t=e instanceof Error?e:Error(String(e));throw!(t instanceof a)&&!t.message.includes(`Session expired`)&&!t.message.includes(`Message limit`)&&s({type:`error`,error:t}),t}}async dispatchProxy(e,t){let n=await this.#c(e.messages,e.composerOptions);this.host.debug&&console.debug(`[AgentWidgetClient] dispatch payload`,n);let r={...this.host.headers};if(this.host.getHeaders)try{let e=await this.host.getHeaders();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.host.customFetch)try{i=await this.host.customFetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.host.streamResponse(i.body,t,void 0,void 0,e.signal)}finally{t({type:`status`,status:`idle`})}}async dispatchAgent(e,t){let n=await this.#s(e.messages,e.composerOptions);this.host.debug&&console.debug(`[AgentWidgetClient] agent dispatch payload`,n);let r={...this.host.headers};if(this.host.getHeaders)try{let e=await this.host.getHeaders();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.host.customFetch)try{i=await this.host.customFetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.host.streamResponse(i.body,t,e.assistantMessageId,void 0,e.signal)}finally{t({type:`status`,status:`idle`})}}#r(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`user`)return n.mentionContext&&Object.keys(n.mentionContext).length>0?{mentions:n.mentionContext}:null}return null}async#i(e){let t={};this.host.contextProviders.length&&await Promise.all(this.host.contextProviders.map(async n=>{try{let r=await n({messages:e,config:this.host.config});r&&typeof r==`object`&&Object.assign(t,r)}catch(e){typeof console<`u`&&console.warn(`[AgentWidget] Context provider failed:`,e)}}));let n=this.#r(e);return n&&Object.assign(t,n),Object.keys(t).length?t:null}#a(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}#o(e,t){let n=t?.selectedModelId;return!n||!(`model`in e)?e:this.host.config.composer?.models?.some(e=>e.id===n)?{...e,model:n}:e}async#s(e,t){let n=this.host.routing().agentId;if(!this.host.config.agent&&!n)throw Error(`Agent configuration required for agent mode`);let r=s(l(e),e=>c(e)&&(e.role===`user`||e.role===`assistant`||e.role===`system`)&&(!e.variant||e.variant===`assistant`)?d(e):null),i=this.#a(t),a={agent:this.#o(this.host.config.agent??{agentId:n},i),messages:r,options:{streamResponse:!0,recordMode:`virtual`,...this.host.config.agentOptions}};i&&(a.composerOptions=i);let o=[...this.host.builtInClientTools(this.host.config),...await(await this.host.getWebMcpBridge())?.snapshotForDispatch()??[]];o.length>0&&(a.clientTools=o);let u=await this.#i(e);return u&&(a.context=u),a}async#c(e,t){let n=s(l(e),e=>c(e)?d(e):null),r=this.host.routing(),i={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[e,t]of Object.entries(r.targetPayload))e!==`messages`&&(i[e]=t);let a=[...this.host.builtInClientTools(this.host.config),...await(await this.host.getWebMcpBridge())?.snapshotForDispatch()??[]];a.length>0&&(i.clientTools=a);let o=await this.#i(e);o&&(i.context=o);let u=this.#a(t);if(u&&(i.composerOptions=u),this.host.requestMiddleware)try{let e=await this.host.requestMiddleware({payload:{...i},config:this.host.config});if(e&&typeof e==`object`){let t=e;return i.clientTools!==void 0&&!(`clientTools`in t)&&(t.clientTools=i.clientTools),t}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Request middleware error:`,e)}return i}};export{f as ClientDispatch};
|