@runtypelabs/persona 4.28.0 → 4.28.1
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 +25 -0
- package/dist/{approval-ui-QAKWNFNM.js → approval-ui-OBBI62ES.js} +1 -1
- package/dist/approval-ui.cjs +2 -2
- package/dist/approval-ui.d.cts +7 -5
- package/dist/approval-ui.d.ts +7 -5
- package/dist/approval-ui.js +2 -2
- package/dist/artifacts-ui.d.cts +7 -5
- package/dist/artifacts-ui.d.ts +7 -5
- package/dist/{chunk-NQLDCJAP.js → chunk-D4TDKCT5.js} +2 -2
- package/dist/chunk-FNXK3VTC.js +1 -0
- package/dist/{client-history-LV3KHEFA.js → client-history-QGAFMCBE.js} +1 -1
- package/dist/client-history.js +1 -1
- package/dist/{client-stream-N22JHTLE.js → client-stream-WXD2FL23.js} +1 -1
- package/dist/client-stream.js +3 -3
- package/dist/codegen.cjs +4 -4
- package/dist/codegen.js +5 -5
- package/dist/context-mentions.d.cts +7 -5
- package/dist/context-mentions.d.ts +7 -5
- package/dist/event-stream-view.d.cts +7 -5
- package/dist/event-stream-view.d.ts +7 -5
- package/dist/forms-ui.d.cts +7 -5
- package/dist/forms-ui.d.ts +7 -5
- package/dist/index.cjs +40 -40
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +32 -30
- package/dist/index.d.ts +32 -30
- package/dist/index.global.js +1 -1
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +41 -41
- package/dist/index.js.map +1 -1
- package/dist/session-reconnect.d.cts +7 -5
- package/dist/session-reconnect.d.ts +7 -5
- package/dist/smart-dom-reader.d.cts +7 -5
- package/dist/smart-dom-reader.d.ts +7 -5
- package/dist/theme-editor-preview.cjs +51 -51
- package/dist/theme-editor-preview.d.cts +7 -5
- package/dist/theme-editor-preview.d.ts +7 -5
- package/dist/theme-editor-preview.js +4 -4
- package/dist/theme-editor.d.cts +8 -6
- package/dist/theme-editor.d.ts +8 -6
- package/dist/{voice-runtime-LVUMPUDS.js → voice-runtime-TWFJ4UUS.js} +1 -1
- package/dist/voice-runtime.cjs +1 -1
- package/dist/voice-runtime.d.cts +7 -5
- package/dist/voice-runtime.d.ts +7 -5
- package/dist/voice-runtime.js +1 -1
- package/dist/webmcp-runtime-5Q3IHAHP.js +6 -0
- package/dist/webmcp-runtime.cjs +2 -2
- package/dist/webmcp-runtime.d.cts +22 -26
- package/dist/webmcp-runtime.d.ts +22 -26
- package/dist/webmcp-runtime.js +2 -2
- package/package.json +5 -2
- package/src/generated/runtype-openapi-contract.ts +3 -0
- package/src/theme-editor/webmcp/types.ts +1 -1
- package/src/types.ts +7 -5
- package/src/webmcp-bridge.test.ts +87 -21
- package/src/webmcp-bridge.ts +21 -26
- package/src/webmcp-polyfill.integration.test.ts +339 -0
- package/src/webmcp-polyfill.ts +7 -4
- package/src/webmcp-runtime-bundle.test.ts +1 -1
- package/src/webmcp-runtime-entry.ts +34 -19
- package/dist/chunk-AALCT54S.js +0 -1
- package/dist/webmcp-runtime-V6ZWW3PI.js +0 -6
|
@@ -3214,9 +3214,8 @@ type WebMcpConfirmInfo = {
|
|
|
3214
3214
|
};
|
|
3215
3215
|
/**
|
|
3216
3216
|
* Why the confirm was requested. Currently always `'gate'`: the default
|
|
3217
|
-
* confirm-by-default gate that fires before every `webmcp:*` call.
|
|
3218
|
-
*
|
|
3219
|
-
* internally, so Persona no longer surfaces a nested in-tool confirm.)
|
|
3217
|
+
* confirm-by-default gate that fires before every `webmcp:*` call. Tool
|
|
3218
|
+
* callbacks on v6 receive an AbortSignal, not a nested confirmation API.
|
|
3220
3219
|
*/
|
|
3221
3220
|
reason: 'gate';
|
|
3222
3221
|
};
|
|
@@ -9439,8 +9438,11 @@ type AgentWidgetConfig = {
|
|
|
9439
9438
|
/**
|
|
9440
9439
|
* WebMCP: consume page-registered tools (`document.modelContext.registerTool`).
|
|
9441
9440
|
* When `enabled`, the widget installs `@mcp-b/webmcp-polyfill`, snapshots the
|
|
9442
|
-
* registry on every dispatch, ships it as `clientTools[]`,
|
|
9443
|
-
* returned `webmcp:*`
|
|
9441
|
+
* current document's registry on every dispatch, ships it as `clientTools[]`,
|
|
9442
|
+
* and executes returned `webmcp:*` calls with confirm-by-default gating.
|
|
9443
|
+
* Supports host-installed v5 JSON-string and v6 object-input contracts.
|
|
9444
|
+
* The automatic fallback stays on v5 to preserve existing browser support
|
|
9445
|
+
* and callback-result behavior.
|
|
9444
9446
|
*
|
|
9445
9447
|
* Server-side policy on the chat surface is the source of truth: these
|
|
9446
9448
|
* fields layer on top.
|
|
@@ -3214,9 +3214,8 @@ type WebMcpConfirmInfo = {
|
|
|
3214
3214
|
};
|
|
3215
3215
|
/**
|
|
3216
3216
|
* Why the confirm was requested. Currently always `'gate'`: the default
|
|
3217
|
-
* confirm-by-default gate that fires before every `webmcp:*` call.
|
|
3218
|
-
*
|
|
3219
|
-
* internally, so Persona no longer surfaces a nested in-tool confirm.)
|
|
3217
|
+
* confirm-by-default gate that fires before every `webmcp:*` call. Tool
|
|
3218
|
+
* callbacks on v6 receive an AbortSignal, not a nested confirmation API.
|
|
3220
3219
|
*/
|
|
3221
3220
|
reason: 'gate';
|
|
3222
3221
|
};
|
|
@@ -9439,8 +9438,11 @@ type AgentWidgetConfig = {
|
|
|
9439
9438
|
/**
|
|
9440
9439
|
* WebMCP: consume page-registered tools (`document.modelContext.registerTool`).
|
|
9441
9440
|
* When `enabled`, the widget installs `@mcp-b/webmcp-polyfill`, snapshots the
|
|
9442
|
-
* registry on every dispatch, ships it as `clientTools[]`,
|
|
9443
|
-
* returned `webmcp:*`
|
|
9441
|
+
* current document's registry on every dispatch, ships it as `clientTools[]`,
|
|
9442
|
+
* and executes returned `webmcp:*` calls with confirm-by-default gating.
|
|
9443
|
+
* Supports host-installed v5 JSON-string and v6 object-input contracts.
|
|
9444
|
+
* The automatic fallback stays on v5 to preserve existing browser support
|
|
9445
|
+
* and callback-result behavior.
|
|
9444
9446
|
*
|
|
9445
9447
|
* Server-side policy on the chat surface is the source of truth: these
|
|
9446
9448
|
* fields layer on top.
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{a as Nm,b as Ka,d as is,e as Vm,f as Ga,g as $m,h as Of,i as _f,m as Ff,n as ms,o as go}from"./chunk-QRKGQPU7.js";import{a as nl}from"./chunk-4HPTPUC6.js";import{b as gi,c as Pd,e as Ef,f as Tf,g as kf}from"./chunk-J4J3Y2P2.js";import{A as ff,B as hf,C as yf,D as Id,E as Uo,F as Mr,G as bf,H as qn,I as ol,J as rl,K as vf,L as sl,M as gs,N as il,O as al,P as ll,Q as Cf,R as Af,S as Mf,T as Rd,a as Sr,b as Pm,c as Lm,d as Im,e as Hm,f as Rm,g as xr,h as Wm,i as Bm,j as Dm,k as Ua,l as $o,m as rs,n as qa,o as Ar,p as Om,q as ja,r as ui,s as wd,t as df,u as pf,v as uf,w as Cn,x as gf,y as mf,z as Ld}from"./chunk-T7QM7YMF.js";import{a as je,c as _m,d as Fm,e as se}from"./chunk-ZC66NAIR.js";import{a as tl,c as sf,d as zo,f as us,g as kd,i as af,j as lf,k as cf}from"./chunk-S6PBWE75.js";import{a as pl,b as Bf,c as Bd,d as mi,e as ul,f as fi,g as gl,h as hi,i as Df,j as yi}from"./chunk-CPVD5P5B.js";import{a as Pf,b as Lf,c as uo,d as Er,e as If,f as Hf,g as Rf,h as Wd,i as Wf}from"./chunk-VK6JOIYJ.js";import{a as Qa,b as jm,c as as,d as xd,e as Td}from"./chunk-K6HKIP5K.js";import{c as cs,d as tf,j as nf,k as Md}from"./chunk-K7NA7G7J.js";import{a as gt,b as Dt,d as rf}from"./chunk-2ANTRKTV.js";import{a as Ed,d as el,e as of,f as ds}from"./chunk-TR2H475E.js";import{b as zm,c as Ya,d as Um,e as Sd,f as qm,g as ls,h as Km,i as Gm,j as Ym,k as Qm,l as Xa,m as Ja,n as Ad,o as Za,q as Xm,r as Jm,s as Zm,t as ef}from"./chunk-
|
|
1
|
+
import{a as Nm,b as Ka,d as is,e as Vm,f as Ga,g as $m,h as Of,i as _f,m as Ff,n as ms,o as go}from"./chunk-QRKGQPU7.js";import{a as nl}from"./chunk-4HPTPUC6.js";import{b as gi,c as Pd,e as Ef,f as Tf,g as kf}from"./chunk-J4J3Y2P2.js";import{A as ff,B as hf,C as yf,D as Id,E as Uo,F as Mr,G as bf,H as qn,I as ol,J as rl,K as vf,L as sl,M as gs,N as il,O as al,P as ll,Q as Cf,R as Af,S as Mf,T as Rd,a as Sr,b as Pm,c as Lm,d as Im,e as Hm,f as Rm,g as xr,h as Wm,i as Bm,j as Dm,k as Ua,l as $o,m as rs,n as qa,o as Ar,p as Om,q as ja,r as ui,s as wd,t as df,u as pf,v as uf,w as Cn,x as gf,y as mf,z as Ld}from"./chunk-T7QM7YMF.js";import{a as je,c as _m,d as Fm,e as se}from"./chunk-ZC66NAIR.js";import{a as tl,c as sf,d as zo,f as us,g as kd,i as af,j as lf,k as cf}from"./chunk-S6PBWE75.js";import{a as pl,b as Bf,c as Bd,d as mi,e as ul,f as fi,g as gl,h as hi,i as Df,j as yi}from"./chunk-CPVD5P5B.js";import{a as Pf,b as Lf,c as uo,d as Er,e as If,f as Hf,g as Rf,h as Wd,i as Wf}from"./chunk-VK6JOIYJ.js";import{a as Qa,b as jm,c as as,d as xd,e as Td}from"./chunk-K6HKIP5K.js";import{c as cs,d as tf,j as nf,k as Md}from"./chunk-K7NA7G7J.js";import{a as gt,b as Dt,d as rf}from"./chunk-2ANTRKTV.js";import{a as Ed,d as el,e as of,f as ds}from"./chunk-TR2H475E.js";import{b as zm,c as Ya,d as Um,e as Sd,f as qm,g as ls,h as Km,i as Gm,j as Ym,k as Qm,l as Xa,m as Ja,n as Ad,o as Za,q as Xm,r as Jm,s as Zm,t as ef}from"./chunk-D4TDKCT5.js";import{a as ps}from"./chunk-FNXK3VTC.js";import{a as wf,b as cl,c as Hd,d as Sf}from"./chunk-HGUCGM3K.js";import{b as dl}from"./chunk-Q735PSZL.js";import{a as yt}from"./chunk-7NQ4ZTHF.js";import{a as P,c as Y,d as ss}from"./chunk-76IELU7F.js";import{a as xf}from"./chunk-UPO4GUFC.js";import{Circle as PC,Clock as LC}from"lucide";import{ChevronDown as xC,ChevronUp as AC}from"lucide";var MC=["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"],EC="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",TC="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",kC=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),ml=(t,e)=>{let n=P("div",["persona-message-bubble",t,...MC].join(" "));return n.id=`bubble-${e}`,n.setAttribute("data-message-id",e),n},fl=t=>{let e=P("button",t.expandable?EC:TC);return e.type="button",t.expandable&&(e.setAttribute("aria-expanded",t.expanded?"true":"false"),e.setAttribute("data-expand-header","true")),e.setAttribute("data-bubble-type",t.bubbleType),e},Dd=(t,e,n)=>{t.innerHTML="";let o=yt(e?AC:xC,16,n,2);o?t.appendChild(o):t.textContent=e?"Hide":"Show"},fs=(t,e,n)=>{if(!n.expandable)return t.append(e),null;let o=P("div","persona-flex persona-items-center");Dd(o,n.expanded,n.iconColor);let s=P("div",n.metaGap?"persona-flex persona-items-center persona-gap-2 persona-ml-auto":"persona-flex persona-items-center persona-ml-auto");return s.append(o),t.append(e,s),o},hl=t=>{let e=P("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(e.setAttribute("data-persona-collapsed-preview",t.previewKind),e.style.display="none",e.style.whiteSpace="pre-wrap",!t.expanded&&t.isActive&&t.activePreview&&t.previewText){let n=t.renderPreview?.();kC(e,n)||(e.textContent=t.previewText),e.style.display=""}return!t.expanded&&t.isActive&&t.activeMinHeight&&(t.bubble.style.minHeight=t.activeMinHeight),e},yl=t=>{t.header.setAttribute("aria-expanded",t.expanded?"true":"false"),t.toggleIcon&&Dd(t.toggleIcon,t.expanded,t.iconColor),t.content.style.display=t.expanded?"":"none",t.collapsedPreview.style.display=t.expanded?"none":t.collapsedPreview.textContent||t.collapsedPreview.childNodes.length?"":"none"},bl=(t,e,n)=>{let o=n.stateSet.has(t),s=e.querySelector('button[data-expand-header="true"]'),i=e.querySelector(".persona-border-t"),l=e.querySelector(`[data-persona-collapsed-preview="${n.previewKind}"]`);if(!s||!i)return;s.setAttribute("aria-expanded",o?"true":"false");let u=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");u&&Dd(u,o,n.iconColor),i.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")};function vl(t,e){let n=e==="tool"?"toolCallDisplay":"reasoningDisplay";return{...t,features:{...t?.features,[n]:{...e==="tool"?$o:rs,...t?.future?.v5Defaults===!0?qa.features?.[n]:{},...t?.features?.[n]}}}}function qo(t,e){let n=e==="tool"?"toolCallDisplay":"reasoningDisplay";return t?.features?.[n]?.variant??(t?.future?.v5Defaults?"row":"card")}function bi(t){let e=Math.max(0,Math.floor((t??0)/1e3));return e<1?"a moment":e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}function mo(t,e,n,o){if(qo(n,o)!=="row")return t;t.className=`persona-message-bubble persona-${o}-bubble persona-activity-row`,t.dataset.activityKind=o,o==="tool"&&n.toolCall?.shadow===void 0&&(t.style.boxShadow="var(--persona-tool-bubble-shadow, none)");let s=t.querySelector(":scope > button");if(!s)return t;s.className="persona-activity-header";let i=o==="tool"?e.toolCall:e.reasoning,l=i?.status!=="complete",c=e.approval?.status??e.toolCall?.approvalStatus,u=c==="denied"?"denied":c==="pending"?"awaiting-approval":e.toolCall?.success===!1?"error":l?i?.status==="pending"?"pending":"running":"done";t.dataset.activityState=u;let p=P("span","persona-activity-icon");p.dataset.activityIcon=u;let g={pending:"circle",running:"loader-circle",done:"check",error:"x",denied:"x","awaiting-approval":"clock"},y=o==="reasoning"?n.features?.reasoningDisplay?.iconName:void 0,h=y?se(y,16,"currentColor",2):u==="pending"?yt(PC,16,"currentColor",2):u==="awaiting-approval"?yt(LC,16,"currentColor",2):se(g[u],16,"currentColor",2);h&&p.appendChild(h),s.querySelector(".persona-reasoning-header-icon")?.remove();let C=o==="tool"?"toolCallDisplay":"reasoningDisplay",E=n.features?.[C]?.iconVisibility??(n.future?.v5Defaults?"active":"always");if((E==="always"||E==="active"&&u!=="done")&&s.prepend(p),o==="tool"&&i){let k=P("span","persona-activity-duration");l&&i.startedAt&&k.setAttribute("data-tool-elapsed",String(i.startedAt));let R=(o==="tool"?e.toolCall?.duration:void 0)??i.durationMs??(i.completedAt!==void 0&&i.startedAt!==void 0?i.completedAt-i.startedAt:void 0);k.textContent=R===void 0?"":bi(R),s.appendChild(k)}s.querySelector(":scope > div:not(.persona-ml-auto)")?.classList.add("persona-activity-label"),s.querySelector(".persona-ml-auto")?.classList.add("persona-activity-chevron");let L=t.querySelector(":scope > .persona-border-t");return L?.classList.add("persona-activity-body"),L&&(L.id=`activity-details-${e.id}`,s.setAttribute("aria-controls",L.id)),t}function Nf(t){let e=new Set,n=new Set,o=new Set,s=new Map,i=l=>{clearTimeout(s.get(l)),s.delete(l)};return{observe(l,c,u,p={}){let g=c==="tool"?l.toolCall:l.reasoning;if(!(!g||n.has(l.id))&&(!e.has(l.id)&&g.status!=="complete"&&g.chunks?.some(Boolean)&&(e.add(l.id),p.autoExpand!==!1&&u.add(l.id)),e.has(l.id)&&g.status==="complete"&&!o.has(l.id))){if(o.add(l.id),p.autoCollapseDelay===!1)return;s.set(l.id,setTimeout(()=>{s.delete(l.id),u.delete(l.id),t(l.id,c)},p.autoCollapseDelay??1e3))}},manual(l){n.add(l),i(l)},prune(l){for(let c of new Set([...e,...n,...o]))l.has(c)||(i(c),e.delete(c),n.delete(c),o.delete(c))},clear(){for(let l of s.keys())i(l);e.clear(),n.clear(),o.clear()}}}function Vf(t,e,n,o){let s=P("div","");s.id=`bubble-${t.id}`,s.dataset.messageId=t.id;let i=P("button","");i.type="button",i.dataset.expandHeader="true",i.dataset.bubbleType="tool",i.setAttribute("aria-expanded",String(n));let l=P("div","");typeof o=="string"?l.textContent=o:l.appendChild(o),fs(i,l,{expandable:!0,expanded:n,iconColor:e.toolCall?.toggleTextColor||e.toolCall?.headerTextColor||"currentColor",metaGap:!0});let c=P("div","persona-border-t");return c.id=`activity-details-${t.id}`,c.style.display=n?"":"none",i.setAttribute("aria-controls",c.id),s.append(i,c),mo(s,t,{...e,features:{...e.features,toolCallDisplay:{...e.features?.toolCallDisplay,variant:"row"}}},"tool"),s.dataset.personaToolGroup="true",e.features?.toolCallDisplay?.loadingAnimation==="shimmer"&&(s.dataset.activityGroupShimmer="true"),{bubble:s,body:c}}function $f(t,e){let n=t.voiceRecognition,o=e.voiceRecognition;return n?.enabled===!0!=(o?.enabled===!0)||n?.provider?.type!==o?.provider?.type||n?.provider?.custom!==o?.provider?.custom||n?.provider?.runtype?.createPlaybackEngine!==o?.provider?.runtype?.createPlaybackEngine||JSON.stringify(n?.provider?.runtype)!==JSON.stringify(o?.provider?.runtype)||t.agentId!==e.agentId||t.clientToken!==e.clientToken||t.apiUrl!==e.apiUrl}function Ot(t){return t?.type==="runtype"||t?.type==="custom"}var IC=()=>typeof window<"u"&&("SpeechRecognition"in window||"webkitSpeechRecognition"in window);function zf(t){try{if(t?.type==="custom"&&t.custom){let e=t.custom,n=typeof e=="function"?e():e;return!!n&&typeof n.startListening=="function"}return t?.type==="runtype"&&t.runtype?!0:IC()}catch{return!1}}var Uf=/^\s*\|?[\s:|-]*-[\s:|-]*$/,qf=t=>t.includes("|"),jf=t=>{let e=t.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(n=>n.trim())},HC=t=>`| ${t.join(" | ")} |`,RC=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,WC=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),Kf=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
|
|
2
2
|
`),n=!1;for(let o=0;o<e.length-1;o++){let s=e[o],i=e[o+1];if(!qf(s)||Uf.test(s)||!Uf.test(i))continue;let l=jf(s).length;if(l<1)continue;let c=RC(l);e[o+1]!==c&&(e[o+1]=c,n=!0);let u=o+2;for(;u<e.length;u++){let p=e[u];if(p.trim()===""||!qf(p))break;let g=HC(WC(jf(p),l));e[u]!==g&&(e[u]=g,n=!0)}o=u-1}return n?e.join(`
|
|
3
|
-
`):t};var Gf="var(--persona-md-table-scroll-fade, 24px)",Yf=new WeakSet;function Xf(t){t.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let s=document.createElement("div");s.className="persona-table-scroll",n.replaceWith(s),s.appendChild(n)})}function Qf(t){let e=t.scrollWidth-t.clientWidth;if(e<=1){t.removeAttribute("data-persona-scroll-x");return}t.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(t).direction==="rtl"?e+t.scrollLeft:t.scrollLeft,s=e-o;t.style.setProperty("--persona-fade-l",o<=1?"0px":Gf),t.style.setProperty("--persona-fade-r",s<=1?"0px":Gf)}function Od(t){Yf.has(t)||(Yf.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&Qf(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(Qf)}var{setLoader:GA,load:BC,provide:YA,getSync:DC}=je({fallbackImport:()=>import("./client-stream-N22JHTLE.js")});var Tr=BC;var Jf=DC;var{setLoader:JA,load:OC}=je({fallbackImport:()=>import("./webmcp-runtime-V6ZWW3PI.js")});var Zf=OC;var _C="agent_",FC="flow_";function eh(t){return t.startsWith(_C)?{kind:"agentId",agentId:t}:t.startsWith(FC)?{kind:"flowId",flowId:t}:null}function th(t,e){let n=t.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let l=n.slice(0,o),c=n.slice(o+1);if(l==="runtype"){let p=eh(c);if(p)return p;throw new Error(`[Persona] target "runtype:${c}" is not a valid Runtype agent_/flow_ id.`)}let u=e?.[l];if(!u)throw new Error(`[Persona] No target provider registered for "${l}". Add a \`targetProviders.${l}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:u(c).payload}}let s=eh(n);if(s)return s;let i=e?.default;if(i)return{kind:"payload",payload:i(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}function Cl(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function hs(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}function nh(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`turn_${t}_${e}`}var NC=t=>t.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),VC=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),$C=t=>{if(t.variant!=="tool")return null;let e=t.agentMetadata?.clientToolAnswer;if(!e||!e.toolCallId||e.result===void 0)return null;let n=NC(e.toolName);return n?{call:{toolCallId:e.toolCallId,toolName:n,args:VC(e.args)?e.args:{}},result:{toolCallId:e.toolCallId,toolName:n,result:e.result}}:null},_d=(t,e)=>{let n=[],o=[],s=[],i="",l,c=()=>{o.length!==0&&(n.push({role:"assistant",content:"",createdAt:i,toolCalls:o},{role:"tool",content:"",createdAt:i,toolResults:s}),o=[],s=[])};for(let u of t){let p=$C(u);if(p){let y=u.agentMetadata?.clientToolAnswer?.batch;o.length>0&&(y===void 0||y!==l)&&c(),o.length===0&&(i=u.createdAt,l=y),o.some(h=>h.toolCallId===p.call.toolCallId)||(o.push(p.call),s.push(p.result));continue}let g=e(u);g&&(c(),n.push(g))}return c(),n};var{setLoader:rM,load:zC,provide:sM}=je({fallbackImport:()=>import("./client-history-LV3KHEFA.js")});var fo=zC;var UC="https://api.runtype.com/v1/dispatch",bt=class extends Error{constructor(e,n,o){super(n),this.name="HistoryClientError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},oh=t=>"reason"in t?t.reason:void 0,qC="The identity proof was rejected",Fd=(t,e)=>t instanceof bt&&t.code===e,Nd=t=>t.voiceCaption?!1:!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0),rh=t=>t.slice().sort((e,n)=>new Date(e.createdAt).getTime()-new Date(n.createdAt).getTime()),sh=t=>({role:t.role,content:t.contentParts??t.llmContent??t.rawContent??t.content,createdAt:t.createdAt});function jC(t){switch(t){case"json":return Zm;case"regex-json":return Jm;case"xml":return ef;default:return Xm}}var vi=class{constructor(e={},n={}){this.config=e;this.historyInternals=n;this.#h=null;this.clientSession=null;this.#p=null;this.#S=!1;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.#t=null;this.#x=!1;this.#R=!1;this.#G=!1;this.#D=null;this.#$=new Set;this.#r=new Set;this.webMcpBridge=null;this.#l=null;this.#q=null;this.#me=null;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.#e=e.apiUrl??UC,this.#o={"Content-Type":"application/json","X-Persona-Version":ps,...e.headers},this.debug=!!e.debug,this.#m=e.streamParser??jC(e.parserType),this.#n=e.contextProviders??[],this.#i=e.requestMiddleware,this.#s=e.customFetch,this.#a=e.parseSSEEvent,this.#v=e.getHeaders,e.webmcp?.enabled===!0&&(this.#l=this.#A(e.webmcp))}#e;#o;#m;#n;#i;#s;#a;#v;#c;#h;#p;#S;#t;#x;#R;#G;#D;#$;#r;#l;#f;#A(e){return Zf().then(n=>{let o=new n.WebMcpBridge(e,{recordToolDisplayTitles:zm,getToolDisplayTitle:Ya,loadPolyfill:qm});return this.#f!==void 0&&o.setConfirmHandler(this.#f),this.webMcpBridge=o,o}).catch(n=>(this.#l=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",n),null))}#P(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.#l||(this.#l=this.#A(this.config.webmcp)),this.#l)}updateConfig(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.#c=e}setWebMcpConfirmHandler(e){this.#f=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(e,n,o){return this.config.webmcp?.enabled!==!0?null:this.#P().then(s=>s?s.executeToolCall(e,n,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.#c}isClientTokenMode(){return!!this.config.clientToken}#u(){let{agentId:e,flowId:n,target:o,targetProviders:s}=this.config;if(!o)return{agentId:e,flowId:n};let i=th(o,s);return i.kind==="agentId"?{agentId:i.agentId}:i.kind==="flowId"?{flowId:i.flowId}:{targetPayload:i.payload}}isAgentMode(){return!!(this.config.agent||this.#u().agentId)}#d(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||rf}#M(e){return`${this.#d()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let n=await this.initSession(),o=!1;for(;;){let s=n.conversationId,i=await this.readVisitorToken();if(n.durableRecovery?.enabled!==!0||!s||!i)throw new bt("visitor_token_missing","Durable recovery is not enabled for this client session");let l=`${this.#d()}/v1/client/conversations/${encodeURIComponent(s)}/executions/${encodeURIComponent(e.executionId)}/events`,c=new URLSearchParams({sessionId:n.sessionId,after:e.after}),u=await fetch(`${l}?${c}`,{method:"GET",headers:{"X-Persona-Version":ps,"X-Visitor-Token":i},signal:e.signal});if(u.status===401&&!o){o=!0;let p=await fo();n=await p.recoverFromUnauthorized(this.#I(),await p.readErrorCode(this.#I(),u),null,!0);continue}if(!u.ok)throw await(await fo()).historyErrorFor(this.#I(),u,!0);return u}}async warmSession(){let e=this.clientSession;return!this.isClientTokenMode()||this.#p||e&&new Date<e.expiresAt||this.#S===e?null:(this.#S=e,this.initSession().catch(()=>null))}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.#p)return this.#p;let e=this.#p=this.#re().then(n=>this.#p!==e?this.initSession():(this.clientSession=n,this.#S=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(n),n)).finally(()=>{this.#p===e&&(this.#p=null)});return e}#C(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.#x}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.get()??null):null}#y(){if(!this.#x){this.#z({state:"unavailable",reason:"history_disabled"}),this.#x=!0,!this.#R&&typeof console<"u"&&(this.#R=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let e of[...this.#r])e(!1)}}getHistoryIdentityStatus(){return this.#D??this.#L()}subscribeHistoryIdentityStatus(e){return this.#$.add(e),()=>{this.#$.delete(e)}}subscribeHistoryAvailability(e){return this.#r.add(e),this.#x&&e(!1),()=>{this.#r.delete(e)}}#L(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.#x?{state:"unavailable",reason:"history_disabled"}:this.#oe():{state:"unavailable",reason:"ineligible_mode"}}#oe(){let e=this.#D;return e?.state==="browser_only"?e:this.#Y()}#Y(){return this.config.features?.history?.scope==="browser"?{state:"browser_only",reason:"configured_browser_scope"}:this.config.getIdentityProof?{state:"browser_only",reason:"proof_unavailable_before_binding"}:{state:"browser_only",reason:"no_identity_provider"}}#z(e){let n=this.getHistoryIdentityStatus(),o=n.state===e.state&&oh(n)===oh(e);if(this.#D=e,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let s of[...this.#$])s(e)}}async#w(e){let n=this.#C()&&!e.omitVisitorFields,o=!e.omitVisitorFields,s=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,s=await this.readVisitorToken());let i=this.#u(),l=i.agentId??i.flowId,c=n||e.durableResume?e.conversationId:void 0,u={token:this.config.clientToken,...l&&{flowId:l},...n&&{visitorHistory:!0},...o&&{durableRecovery:!0},...(n||o)&&s?{visitorToken:s}:{},...n&&e.identityProof?{identityProof:e.identityProof}:{},...c?{conversationId:c}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let p=await fetch(this.#M("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ps},body:JSON.stringify(u),signal:e.signal});if(!p.ok){let y=await p.json().catch(()=>({error:"Session initialization failed"}));if(n&&p.status===403&&y.error==="visitor_history_disabled"){if(this.#y(),c)throw new bt("history_disabled","Visitor history is disabled for this surface");return this.#w({...e,omitVisitorFields:!0})}throw p.status===403&&y.error==="durable_recovery_disabled"?new bt("history_disabled","Durable recovery is disabled for this surface"):(n||e.durableResume)&&p.status===401&&y.error==="visitor_required"?new bt("visitor_required","Visitor credential no longer resolves"):c&&p.status===404?new bt("not_found","Conversation not found"):p.status===401?new Error(`Invalid client token: ${y.hint||y.error}`):p.status===403?new Error(`Origin not allowed: ${y.hint||y.error}`):new Error(y.error||"Failed to initialize session")}let g=await p.json();return g.visitor?.token&&await this.historyInternals.visitorStore?.set(g.visitor.token),{sessionId:g.sessionId,expiresAt:new Date(g.expiresAt),flow:g.flow,...g.conversationId?{conversationId:g.conversationId}:{},...g.targetId?{targetId:g.targetId}:{},...g.conversationRevision?{conversationRevision:g.conversationRevision}:{},...g.durableRecovery?{durableRecovery:g.durableRecovery}:{},...g.visitor?{visitor:g.visitor}:{},config:{welcomeMessage:g.config.welcomeMessage,placeholder:g.config.placeholder,theme:g.config.theme}}}async#re(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.#C()&&!n)return this.#W(e,!1);let o=await this.readVisitorToken();if(e&&o)try{let s=await this.#w({conversationId:e,durableResume:n});return n&&s.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.#O(s,e,!1)}catch(s){if(!Fd(s,"not_found")&&!Fd(s,"visitor_required")&&!Fd(s,"history_disabled"))throw s;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.#W(e,!0)}return this.#W(e,!1)}async#W(e,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.#V(e,n)):this.#V(e,n)}async#V(e,n){let o=this.config.getStoredSessionId?.()||null,s=await this.#w({storedSessionId:o}),i=await this.#ge(s);return this.#O(i,e,n)}async#ue(e){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,s=await this.#w({storedSessionId:n,identityProof:e}),i=this.#O(s,o,!1);return this.clientSession=i,this.#p=null,this.#S=!1,this.resetClientToolsFingerprint(),i}async#ge(e){if(!e.visitor?.token||this.#G||!this.#C()&&e.durableRecovery?.enabled!==!0)return e;this.#G=!0;try{return await this.#w({storedSessionId:e.sessionId})}catch{return e}finally{this.#G=!1}}#O(e,n,o){let s=e.conversationId;return s&&n&&(o||s!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:s}),this.config.setStoredSessionId?.(e.sessionId),s&&(this.config.setStoredConversationId?.(s),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}#U(e){let n=!1;return{session:e,commit:()=>{n||(n=!0,this.clientSession=e,this.#S=!1,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(e,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.#C())throw new bt("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let o=n?.proof??null;if(!await this.readVisitorToken()&&!o)throw new bt("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let i=await this.#w({conversationId:e,identityProof:o});return this.#U(i)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let e=await this.#w({});return this.#U(e)}handleExternalCredentialChange(){this.clearClientSession(),this.#C()&&this.#z(this.#Y())}clearClientSession(){this.clientSession=null,this.#p=null,this.#S=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#t=null}#Q(){return`${this.#d()}/v1/client/feedback`}async sendFeedback(e){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let s={...e,...this.config.clientToken&&{token:this.config.clientToken}},i=await fetch(this.#Q(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ps},body:JSON.stringify(s)});if(!i.ok){let l=await i.json().catch(()=>({error:"Feedback submission failed"}));throw i.status===401?(this.clientSession=null,this.#S=!1,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(l.error||"Failed to submit feedback")}}async submitMessageFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:e,comment:n})}async submitNPSFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:e,comment:n})}async#ae(e){e?.throwIfAborted();let n=this.config.identityProvider;if(n===void 0)return;let o=this.config.getIdentityProof;if(!n.trim()||!o)throw new Error("Chat identity requires identityProvider and getIdentityProof.");let s,i;try{let l=Promise.resolve().then(()=>o());s=e?await Promise.race([l,new Promise((c,u)=>{i=()=>u(e.reason),e.addEventListener("abort",i,{once:!0}),e.aborted&&i()})]):await l}catch{throw e?.throwIfAborted(),new Error("The identity proof provider failed.")}finally{i&&e?.removeEventListener("abort",i)}if(typeof s!="string"||!s.trim())throw new Error("A fresh identity proof is required to send this message.");return{provider:n,token:s}}#q;#B(){let e=this;return this.#q??={get config(){return e.config},headers:this.#o,getHeaders:this.#v,debug:this.debug,clientApiBase:()=>e.#d(),getClientApiUrl:n=>e.#M(n),getWebMcpBridge:()=>e.#P(),sendWithClientToolsDiff:(n,o,s,i)=>e.#se(n,o,s,i),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}#me;#I(){let e=this;return this.#me??={HistoryClientError:bt,get config(){return e.config},get historyInternals(){return e.historyInternals},get clientSession(){return e.clientSession},clientApiBase:()=>e.#d(),setHistoryIdentityStatus:n=>e.#z(n),browserOnlyStatus:()=>e.#oe(),derivedBrowserOnly:()=>e.#Y(),reinitWithProof:n=>e.#ue(n),isHistoryCapable:()=>e.#C(),clearClientSession:()=>e.clearClientSession(),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}async listConversations(e){return(await fo()).listConversations(this.#I(),e)}async getConversation(e,n){return(await fo()).getConversation(this.#I(),e,n)}async finalizeDisplayProjections(e,n){return(await fo()).finalizeDisplayProjections(this.#I(),e,n)}async deleteConversation(e,n){return(await fo()).deleteConversation(this.#I(),e,n)}async deleteAllConversations(e){return(await fo()).deleteAllConversations(this.#I(),e)}async resetVisitor(){return(await fo()).resetVisitor(this.#I())}async dispatch(e,n){return e.signal?.throwIfAborted(),Tr().catch(()=>{}),this.isClientTokenMode()?this.#fe(e,n):this.isAgentMode()?this.#le(e,n):this.#he(e,n)}async#fe(e,n){let o=nh();this.#h=o;let s=()=>this.#h===o,i=l=>{s()&&n(l)};n({type:"status",status:"connecting"});try{let l=()=>{if(e.signal?.throwIfAborted(),!s())throw new DOMException("Turn superseded","AbortError")},c=this.clientSession??await this.initSession();l();let u=async()=>{l();let L=c,k=L.durableRecovery?.enabled===!0;if(k&&(!L.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");l();let R=await this.#w({...k||this.#C()?{conversationId:L.conversationId,durableResume:k}:{storedSessionId:L.sessionId},signal:e.signal});if(l(),L.conversationId&&R.conversationId!==L.conversationId||k&&R.durableRecovery?.enabled!==!0)throw new Error("Session renewal did not preserve this conversation.");c=this.#O(R,L.conversationId??null,!1),this.clientSession=c,this.#S=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(c)};Date.now()>=c.expiresAt.getTime()-6e4&&await u();let p=await this.#F(e.messages),g=p.metadata?Object.fromEntries(Object.entries(p.metadata).filter(([L])=>L!=="sessionId"&&L!=="session_id")):void 0,y=this.#C(),h={sessionId:c.sessionId,messages:e.messages.filter(Nd).map(L=>{let k=y?gi(L):void 0;return{id:L.id,role:L.role,content:L.contentParts??L.llmContent??L.rawContent??L.content,...k!==void 0&&{displayContent:k}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...g&&Object.keys(g).length>0&&{metadata:g},...p.inputs&&Object.keys(p.inputs).length>0&&{inputs:p.inputs},...p.context&&{context:p.context},turnId:o,...e.interrupt&&{submitMode:"interrupt"},...e.voiceSpoken&&{voice:{spoken:!0}}},C=async()=>{l();let L=c.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return l(),this.#se(c.sessionId,p.clientTools,async k=>{l();let R=await this.#ae(e.signal);l();let B={...h,sessionId:c.sessionId,...k,...R&&{identityProof:R}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...B,...R&&{identityProof:{provider:R.provider,token:"[REDACTED]"}}}),fetch(this.#M("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ps,...L?{"X-Visitor-Token":L}:{}},body:JSON.stringify(B),signal:e.signal})})},E=await C();if(l(),E.response.status===401){let L=await E.response.clone().json().catch(()=>null);l(),L?.error==="Session not found or expired"&&(await u(),E=await C(),l())}let{response:A,commit:I}=E;if(!A.ok){let L=await A.json().catch(()=>({error:"Chat request failed"}));if(A.status===401&&L.error==="invalid_identity_proof"){let R=new bt("invalid_identity_proof",qC);throw i({type:"error",error:R}),R}if(A.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let R=new Error("Session expired. Please refresh to continue.");throw i({type:"error",error:R}),R}if(A.status===429){let R=new Error(L.hint||"Message limit reached for this session.");throw i({type:"error",error:R}),R}if(A.status===410&&L.error==="conversation_deleted"){let R=new bt("conversation_deleted","This conversation was deleted");throw i({type:"error",error:R}),R}let k=new Error(L.error||"Failed to send message");throw i({type:"error",error:k}),k}if(!A.body){let L=new Error("No response body received");throw i({type:"error",error:L}),L}I(),i({type:"status",status:"connected"});try{await this.#X(A.body,i,e.assistantMessageId)}finally{i({type:"status",status:"idle"})}}catch(l){let c=l instanceof Error?l:new Error(String(l));throw!(c instanceof bt)&&!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&i({type:"error",error:c}),c}}async#he(e,n){n({type:"status",status:"connecting"});let o=await this.#F(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.#o};if(this.#v)try{let l=await this.#v();s={...s,...l}}catch(l){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.#s)try{i=await this.#s(this.#e,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal},o)}catch(l){let c=l instanceof Error?l:new Error(String(l));throw n({type:"error",error:c}),c}else i=await fetch(this.#e,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let l=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw n({type:"error",error:l}),l}n({type:"status",status:"connected"});try{await this.#X(i.body,n)}finally{n({type:"status",status:"idle"})}}async#le(e,n){n({type:"status",status:"connecting"});let o=await this.#b(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.#o};if(this.#v)try{let l=await this.#v();s={...s,...l}}catch(l){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.#s)try{i=await this.#s(this.#e,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal},o)}catch(l){let c=l instanceof Error?l:new Error(String(l));throw n({type:"error",error:c}),c}else i=await fetch(this.#e,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let l=new Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw n({type:"error",error:l}),l}n({type:"status",status:"connected"});try{await this.#X(i.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(e,n,o,s){n({type:"status",status:"connected"});try{await this.#X(e,n,o,s)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){return(await Tr()).resolveApproval(this.#B(),e,n)}async#se(e,n,o,s){let i=!!(n&&n.length>0),l=i?Um(n):void 0,c=this.clientToolsFingerprintSessionId===e,u=i&&c&&this.lastSentClientToolsFingerprint===l,p=!i&&s?.emptyMeansReplace===!0&&this.#t===e,g=!1,y;for(let h=0;;h++){if(y=await o({...i&&(g||!u)&&n?{clientTools:n}:{},...p?{clientTools:[]}:{},...l?{clientToolsFingerprint:l}:{}}),y.status===409&&h===0&&i&&(await y.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){g=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:y,commit:()=>{this.lastSentClientToolsFingerprint=l??null,this.clientToolsFingerprintSessionId=e,i?this.#t=e:p&&(this.#t=null)}}}async resumeFlow(e,n,o){return(await Tr()).resumeFlow(this.#B(),e,n,o)}#ce(e){for(let n=e.length-1;n>=0;n--){let o=e[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async#_(e){let n={};this.#n.length&&await Promise.all(this.#n.map(async s=>{try{let i=await s({messages:e,config:this.config});i&&typeof i=="object"&&Object.assign(n,i)}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",i)}}));let o=this.#ce(e);return o&&Object.assign(n,o),Object.keys(n).length?n:null}#E(e){if(!e)return;let n={};return e.selectedModelId&&(n.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(n.activeModeIds=[...e.activeModeIds]),Object.keys(n).length>0?n:void 0}#T(e,n){let o=n?.selectedModelId;return!o||!("model"in e)?e:this.config.composer?.models?.some(i=>i.id===o)?{...e,model:o}:e}async#b(e,n){let o=this.#u().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let s=_d(rh(e),p=>Nd(p)&&(p.role==="user"||p.role==="assistant"||p.role==="system")&&(!p.variant||p.variant==="assistant")?sh(p):null),i=this.#E(n),l={agent:this.#T(this.config.agent??{agentId:o},i),messages:s,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};i&&(l.composerOptions=i);let c=[...Td(this.config),...await(await this.#P())?.snapshotForDispatch()??[]];c.length>0&&(l.clientTools=c);let u=await this.#_(e);return u&&(l.context=u),l}async#F(e,n){let o=_d(rh(e),p=>Nd(p)?sh(p):null),s=this.#u(),i={messages:o,...s.agentId?{agent:{agentId:s.agentId}}:s.flowId?{flowId:s.flowId}:{}};if(s.targetPayload)for(let[p,g]of Object.entries(s.targetPayload))p!=="messages"&&(i[p]=g);let l=[...Td(this.config),...await(await this.#P())?.snapshotForDispatch()??[]];l.length>0&&(i.clientTools=l);let c=await this.#_(e);c&&(i.context=c);let u=this.#E(n);if(u&&(i.composerOptions=u),this.#i)try{let p=await this.#i({payload:{...i},config:this.config});if(p&&typeof p=="object"){let g=p;return i.clientTools!==void 0&&!("clientTools"in g)&&(g.clientTools=i.clientTools),g}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",p)}return i}async#X(e,n,o,s){let{streamResponse:i}=Jf()??await Tr();return i({config:()=>this.config,createStreamParser:this.#m,parseSSEEvent:this.#a,onSSEEvent:(l,c)=>this.#c?.(l,c)},e,n,o,s)}};var{setLoader:wM,load:KC,provide:SM,getSync:GC}=je({fallbackImport:()=>import("./ui-extras-entry-WAYFKVNW.js")});var wl=KC;var Vd=GC;var{setLoader:MM,load:YC,provide:EM,getSync:QC}=je({fallbackImport:()=>import("./session-actions-ISSKSI66.js")});var $d=YC;var ih=QC;var XC=t=>t.sourceLabel?`quoted-text source=${t.sourceLabel}`:"quoted-text";function JC(t){let e=t?.text?.trim()??"";return e?Sf(XC(t),e):""}function ah(t){let e=JC(t.quote);return e?t.contentParts&&t.contentParts.length>0?{contentParts:[zo(e),...t.contentParts]}:{llmContent:[e,t.text].filter(Boolean).join(`
|
|
3
|
+
`):t};var Gf="var(--persona-md-table-scroll-fade, 24px)",Yf=new WeakSet;function Xf(t){t.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let s=document.createElement("div");s.className="persona-table-scroll",n.replaceWith(s),s.appendChild(n)})}function Qf(t){let e=t.scrollWidth-t.clientWidth;if(e<=1){t.removeAttribute("data-persona-scroll-x");return}t.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(t).direction==="rtl"?e+t.scrollLeft:t.scrollLeft,s=e-o;t.style.setProperty("--persona-fade-l",o<=1?"0px":Gf),t.style.setProperty("--persona-fade-r",s<=1?"0px":Gf)}function Od(t){Yf.has(t)||(Yf.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&Qf(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(Qf)}var{setLoader:GA,load:BC,provide:YA,getSync:DC}=je({fallbackImport:()=>import("./client-stream-WXD2FL23.js")});var Tr=BC;var Jf=DC;var{setLoader:JA,load:OC}=je({fallbackImport:()=>import("./webmcp-runtime-5Q3IHAHP.js")});var Zf=OC;var _C="agent_",FC="flow_";function eh(t){return t.startsWith(_C)?{kind:"agentId",agentId:t}:t.startsWith(FC)?{kind:"flowId",flowId:t}:null}function th(t,e){let n=t.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let l=n.slice(0,o),c=n.slice(o+1);if(l==="runtype"){let p=eh(c);if(p)return p;throw new Error(`[Persona] target "runtype:${c}" is not a valid Runtype agent_/flow_ id.`)}let u=e?.[l];if(!u)throw new Error(`[Persona] No target provider registered for "${l}". Add a \`targetProviders.${l}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:u(c).payload}}let s=eh(n);if(s)return s;let i=e?.default;if(i)return{kind:"payload",payload:i(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}function Cl(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function hs(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}function nh(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`turn_${t}_${e}`}var NC=t=>t.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase().replace(/_+/g,"_").replace(/^_|_$/g,""),VC=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),$C=t=>{if(t.variant!=="tool")return null;let e=t.agentMetadata?.clientToolAnswer;if(!e||!e.toolCallId||e.result===void 0)return null;let n=NC(e.toolName);return n?{call:{toolCallId:e.toolCallId,toolName:n,args:VC(e.args)?e.args:{}},result:{toolCallId:e.toolCallId,toolName:n,result:e.result}}:null},_d=(t,e)=>{let n=[],o=[],s=[],i="",l,c=()=>{o.length!==0&&(n.push({role:"assistant",content:"",createdAt:i,toolCalls:o},{role:"tool",content:"",createdAt:i,toolResults:s}),o=[],s=[])};for(let u of t){let p=$C(u);if(p){let y=u.agentMetadata?.clientToolAnswer?.batch;o.length>0&&(y===void 0||y!==l)&&c(),o.length===0&&(i=u.createdAt,l=y),o.some(h=>h.toolCallId===p.call.toolCallId)||(o.push(p.call),s.push(p.result));continue}let g=e(u);g&&(c(),n.push(g))}return c(),n};var{setLoader:rM,load:zC,provide:sM}=je({fallbackImport:()=>import("./client-history-QGAFMCBE.js")});var fo=zC;var UC="https://api.runtype.com/v1/dispatch",bt=class extends Error{constructor(e,n,o){super(n),this.name="HistoryClientError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},oh=t=>"reason"in t?t.reason:void 0,qC="The identity proof was rejected",Fd=(t,e)=>t instanceof bt&&t.code===e,Nd=t=>t.voiceCaption?!1:!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0),rh=t=>t.slice().sort((e,n)=>new Date(e.createdAt).getTime()-new Date(n.createdAt).getTime()),sh=t=>({role:t.role,content:t.contentParts??t.llmContent??t.rawContent??t.content,createdAt:t.createdAt});function jC(t){switch(t){case"json":return Zm;case"regex-json":return Jm;case"xml":return ef;default:return Xm}}var vi=class{constructor(e={},n={}){this.config=e;this.historyInternals=n;this.#h=null;this.clientSession=null;this.#p=null;this.#S=!1;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.#t=null;this.#x=!1;this.#R=!1;this.#G=!1;this.#D=null;this.#$=new Set;this.#r=new Set;this.webMcpBridge=null;this.#l=null;this.#q=null;this.#me=null;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.#e=e.apiUrl??UC,this.#o={"Content-Type":"application/json","X-Persona-Version":ps,...e.headers},this.debug=!!e.debug,this.#m=e.streamParser??jC(e.parserType),this.#n=e.contextProviders??[],this.#i=e.requestMiddleware,this.#s=e.customFetch,this.#a=e.parseSSEEvent,this.#v=e.getHeaders,e.webmcp?.enabled===!0&&(this.#l=this.#A(e.webmcp))}#e;#o;#m;#n;#i;#s;#a;#v;#c;#h;#p;#S;#t;#x;#R;#G;#D;#$;#r;#l;#f;#A(e){return Zf().then(n=>{let o=new n.WebMcpBridge(e,{recordToolDisplayTitles:zm,getToolDisplayTitle:Ya,loadPolyfill:qm});return this.#f!==void 0&&o.setConfirmHandler(this.#f),this.webMcpBridge=o,o}).catch(n=>(this.#l=null,console.warn("[Persona] Failed to load the WebMCP runtime chunk",n),null))}#P(){return this.webMcpBridge?Promise.resolve(this.webMcpBridge):this.config.webmcp?.enabled!==!0?Promise.resolve(null):(this.#l||(this.#l=this.#A(this.config.webmcp)),this.#l)}updateConfig(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.#c=e}setWebMcpConfirmHandler(e){this.#f=e,this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(e,n,o){return this.config.webmcp?.enabled!==!0?null:this.#P().then(s=>s?s.executeToolCall(e,n,o):{isError:!0,content:[{type:"text",text:"WebMCP runtime failed to load."}]})}getSSEEventCallback(){return this.#c}isClientTokenMode(){return!!this.config.clientToken}#u(){let{agentId:e,flowId:n,target:o,targetProviders:s}=this.config;if(!o)return{agentId:e,flowId:n};let i=th(o,s);return i.kind==="agentId"?{agentId:i.agentId}:i.kind==="flowId"?{flowId:i.flowId}:{targetPayload:i.payload}}isAgentMode(){return!!(this.config.agent||this.#u().agentId)}#d(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||rf}#M(e){return`${this.#d()}/v1/client/${e}`}getClientSession(){return this.clientSession}async reconnectClientTokenStream(e){let n=await this.initSession(),o=!1;for(;;){let s=n.conversationId,i=await this.readVisitorToken();if(n.durableRecovery?.enabled!==!0||!s||!i)throw new bt("visitor_token_missing","Durable recovery is not enabled for this client session");let l=`${this.#d()}/v1/client/conversations/${encodeURIComponent(s)}/executions/${encodeURIComponent(e.executionId)}/events`,c=new URLSearchParams({sessionId:n.sessionId,after:e.after}),u=await fetch(`${l}?${c}`,{method:"GET",headers:{"X-Persona-Version":ps,"X-Visitor-Token":i},signal:e.signal});if(u.status===401&&!o){o=!0;let p=await fo();n=await p.recoverFromUnauthorized(this.#I(),await p.readErrorCode(this.#I(),u),null,!0);continue}if(!u.ok)throw await(await fo()).historyErrorFor(this.#I(),u,!0);return u}}async warmSession(){let e=this.clientSession;return!this.isClientTokenMode()||this.#p||e&&new Date<e.expiresAt||this.#S===e?null:(this.#S=e,this.initSession().catch(()=>null))}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.#p)return this.#p;let e=this.#p=this.#re().then(n=>this.#p!==e?this.initSession():(this.clientSession=n,this.#S=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(n),n)).finally(()=>{this.#p===e&&(this.#p=null)});return e}#C(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.#x}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.get()??null):null}#y(){if(!this.#x){this.#z({state:"unavailable",reason:"history_disabled"}),this.#x=!0,!this.#R&&typeof console<"u"&&(this.#R=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let e of[...this.#r])e(!1)}}getHistoryIdentityStatus(){return this.#D??this.#L()}subscribeHistoryIdentityStatus(e){return this.#$.add(e),()=>{this.#$.delete(e)}}subscribeHistoryAvailability(e){return this.#r.add(e),this.#x&&e(!1),()=>{this.#r.delete(e)}}#L(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.#x?{state:"unavailable",reason:"history_disabled"}:this.#oe():{state:"unavailable",reason:"ineligible_mode"}}#oe(){let e=this.#D;return e?.state==="browser_only"?e:this.#Y()}#Y(){return this.config.features?.history?.scope==="browser"?{state:"browser_only",reason:"configured_browser_scope"}:this.config.getIdentityProof?{state:"browser_only",reason:"proof_unavailable_before_binding"}:{state:"browser_only",reason:"no_identity_provider"}}#z(e){let n=this.getHistoryIdentityStatus(),o=n.state===e.state&&oh(n)===oh(e);if(this.#D=e,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let s of[...this.#$])s(e)}}async#w(e){let n=this.#C()&&!e.omitVisitorFields,o=!e.omitVisitorFields,s=null;(n||o)&&(await this.historyInternals.historyBootstrapReady,s=await this.readVisitorToken());let i=this.#u(),l=i.agentId??i.flowId,c=n||e.durableResume?e.conversationId:void 0,u={token:this.config.clientToken,...l&&{flowId:l},...n&&{visitorHistory:!0},...o&&{durableRecovery:!0},...(n||o)&&s?{visitorToken:s}:{},...n&&e.identityProof?{identityProof:e.identityProof}:{},...c?{conversationId:c}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let p=await fetch(this.#M("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ps},body:JSON.stringify(u),signal:e.signal});if(!p.ok){let y=await p.json().catch(()=>({error:"Session initialization failed"}));if(n&&p.status===403&&y.error==="visitor_history_disabled"){if(this.#y(),c)throw new bt("history_disabled","Visitor history is disabled for this surface");return this.#w({...e,omitVisitorFields:!0})}throw p.status===403&&y.error==="durable_recovery_disabled"?new bt("history_disabled","Durable recovery is disabled for this surface"):(n||e.durableResume)&&p.status===401&&y.error==="visitor_required"?new bt("visitor_required","Visitor credential no longer resolves"):c&&p.status===404?new bt("not_found","Conversation not found"):p.status===401?new Error(`Invalid client token: ${y.hint||y.error}`):p.status===403?new Error(`Origin not allowed: ${y.hint||y.error}`):new Error(y.error||"Failed to initialize session")}let g=await p.json();return g.visitor?.token&&await this.historyInternals.visitorStore?.set(g.visitor.token),{sessionId:g.sessionId,expiresAt:new Date(g.expiresAt),flow:g.flow,...g.conversationId?{conversationId:g.conversationId}:{},...g.targetId?{targetId:g.targetId}:{},...g.conversationRevision?{conversationRevision:g.conversationRevision}:{},...g.durableRecovery?{durableRecovery:g.durableRecovery}:{},...g.visitor?{visitor:g.visitor}:{},config:{welcomeMessage:g.config.welcomeMessage,placeholder:g.config.placeholder,theme:g.config.theme}}}async#re(){await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,n=this.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.#C()&&!n)return this.#W(e,!1);let o=await this.readVisitorToken();if(e&&o)try{let s=await this.#w({conversationId:e,durableResume:n});return n&&s.durableRecovery?.enabled!==!0&&this.historyInternals.setStoredResumableHandle?.(null),this.#O(s,e,!1)}catch(s){if(!Fd(s,"not_found")&&!Fd(s,"visitor_required")&&!Fd(s,"history_disabled"))throw s;return n&&this.historyInternals.setStoredResumableHandle?.(null),this.#W(e,!0)}return this.#W(e,!1)}async#W(e,n){let o=this.historyInternals.visitorStore;return o&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.#V(e,n)):this.#V(e,n)}async#V(e,n){let o=this.config.getStoredSessionId?.()||null,s=await this.#w({storedSessionId:o}),i=await this.#ge(s);return this.#O(i,e,n)}async#ue(e){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,s=await this.#w({storedSessionId:n,identityProof:e}),i=this.#O(s,o,!1);return this.clientSession=i,this.#p=null,this.#S=!1,this.resetClientToolsFingerprint(),i}async#ge(e){if(!e.visitor?.token||this.#G||!this.#C()&&e.durableRecovery?.enabled!==!0)return e;this.#G=!0;try{return await this.#w({storedSessionId:e.sessionId})}catch{return e}finally{this.#G=!1}}#O(e,n,o){let s=e.conversationId;return s&&n&&(o||s!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:s}),this.config.setStoredSessionId?.(e.sessionId),s&&(this.config.setStoredConversationId?.(s),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}#U(e){let n=!1;return{session:e,commit:()=>{n||(n=!0,this.clientSession=e,this.#S=!1,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(e,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.#C())throw new bt("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let o=n?.proof??null;if(!await this.readVisitorToken()&&!o)throw new bt("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let i=await this.#w({conversationId:e,identityProof:o});return this.#U(i)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let e=await this.#w({});return this.#U(e)}handleExternalCredentialChange(){this.clearClientSession(),this.#C()&&this.#z(this.#Y())}clearClientSession(){this.clientSession=null,this.#p=null,this.#S=!1,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.#t=null}#Q(){return`${this.#d()}/v1/client/feedback`}async sendFeedback(e){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let s={...e,...this.config.clientToken&&{token:this.config.clientToken}},i=await fetch(this.#Q(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ps},body:JSON.stringify(s)});if(!i.ok){let l=await i.json().catch(()=>({error:"Feedback submission failed"}));throw i.status===401?(this.clientSession=null,this.#S=!1,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(l.error||"Failed to submit feedback")}}async submitMessageFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:e,comment:n})}async submitNPSFeedback(e,n){let o=this.getClientSession()??await this.initSession();return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:e,comment:n})}async#ae(e){e?.throwIfAborted();let n=this.config.identityProvider;if(n===void 0)return;let o=this.config.getIdentityProof;if(!n.trim()||!o)throw new Error("Chat identity requires identityProvider and getIdentityProof.");let s,i;try{let l=Promise.resolve().then(()=>o());s=e?await Promise.race([l,new Promise((c,u)=>{i=()=>u(e.reason),e.addEventListener("abort",i,{once:!0}),e.aborted&&i()})]):await l}catch{throw e?.throwIfAborted(),new Error("The identity proof provider failed.")}finally{i&&e?.removeEventListener("abort",i)}if(typeof s!="string"||!s.trim())throw new Error("A fresh identity proof is required to send this message.");return{provider:n,token:s}}#q;#B(){let e=this;return this.#q??={get config(){return e.config},headers:this.#o,getHeaders:this.#v,debug:this.debug,clientApiBase:()=>e.#d(),getClientApiUrl:n=>e.#M(n),getWebMcpBridge:()=>e.#P(),sendWithClientToolsDiff:(n,o,s,i)=>e.#se(n,o,s,i),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}#me;#I(){let e=this;return this.#me??={HistoryClientError:bt,get config(){return e.config},get historyInternals(){return e.historyInternals},get clientSession(){return e.clientSession},clientApiBase:()=>e.#d(),setHistoryIdentityStatus:n=>e.#z(n),browserOnlyStatus:()=>e.#oe(),derivedBrowserOnly:()=>e.#Y(),reinitWithProof:n=>e.#ue(n),isHistoryCapable:()=>e.#C(),clearClientSession:()=>e.clearClientSession(),initSession:()=>e.initSession(),readVisitorToken:()=>e.readVisitorToken(),isClientTokenMode:()=>e.isClientTokenMode()}}async listConversations(e){return(await fo()).listConversations(this.#I(),e)}async getConversation(e,n){return(await fo()).getConversation(this.#I(),e,n)}async finalizeDisplayProjections(e,n){return(await fo()).finalizeDisplayProjections(this.#I(),e,n)}async deleteConversation(e,n){return(await fo()).deleteConversation(this.#I(),e,n)}async deleteAllConversations(e){return(await fo()).deleteAllConversations(this.#I(),e)}async resetVisitor(){return(await fo()).resetVisitor(this.#I())}async dispatch(e,n){return e.signal?.throwIfAborted(),Tr().catch(()=>{}),this.isClientTokenMode()?this.#fe(e,n):this.isAgentMode()?this.#le(e,n):this.#he(e,n)}async#fe(e,n){let o=nh();this.#h=o;let s=()=>this.#h===o,i=l=>{s()&&n(l)};n({type:"status",status:"connecting"});try{let l=()=>{if(e.signal?.throwIfAborted(),!s())throw new DOMException("Turn superseded","AbortError")},c=this.clientSession??await this.initSession();l();let u=async()=>{l();let L=c,k=L.durableRecovery?.enabled===!0;if(k&&(!L.conversationId||!await this.readVisitorToken()))throw new Error("Renewing this conversation requires its visitor credential.");l();let R=await this.#w({...k||this.#C()?{conversationId:L.conversationId,durableResume:k}:{storedSessionId:L.sessionId},signal:e.signal});if(l(),L.conversationId&&R.conversationId!==L.conversationId||k&&R.durableRecovery?.enabled!==!0)throw new Error("Session renewal did not preserve this conversation.");c=this.#O(R,L.conversationId??null,!1),this.clientSession=c,this.#S=!1,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(c)};Date.now()>=c.expiresAt.getTime()-6e4&&await u();let p=await this.#F(e.messages),g=p.metadata?Object.fromEntries(Object.entries(p.metadata).filter(([L])=>L!=="sessionId"&&L!=="session_id")):void 0,y=this.#C(),h={sessionId:c.sessionId,messages:e.messages.filter(Nd).map(L=>{let k=y?gi(L):void 0;return{id:L.id,role:L.role,content:L.contentParts??L.llmContent??L.rawContent??L.content,...k!==void 0&&{displayContent:k}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...g&&Object.keys(g).length>0&&{metadata:g},...p.inputs&&Object.keys(p.inputs).length>0&&{inputs:p.inputs},...p.context&&{context:p.context},turnId:o,...e.interrupt&&{submitMode:"interrupt"},...e.voiceSpoken&&{voice:{spoken:!0}}},C=async()=>{l();let L=c.durableRecovery?.enabled===!0?await this.readVisitorToken():null;return l(),this.#se(c.sessionId,p.clientTools,async k=>{l();let R=await this.#ae(e.signal);l();let B={...h,sessionId:c.sessionId,...k,...R&&{identityProof:R}};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",{...B,...R&&{identityProof:{provider:R.provider,token:"[REDACTED]"}}}),fetch(this.#M("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":ps,...L?{"X-Visitor-Token":L}:{}},body:JSON.stringify(B),signal:e.signal})})},E=await C();if(l(),E.response.status===401){let L=await E.response.clone().json().catch(()=>null);l(),L?.error==="Session not found or expired"&&(await u(),E=await C(),l())}let{response:A,commit:I}=E;if(!A.ok){let L=await A.json().catch(()=>({error:"Chat request failed"}));if(A.status===401&&L.error==="invalid_identity_proof"){let R=new bt("invalid_identity_proof",qC);throw i({type:"error",error:R}),R}if(A.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let R=new Error("Session expired. Please refresh to continue.");throw i({type:"error",error:R}),R}if(A.status===429){let R=new Error(L.hint||"Message limit reached for this session.");throw i({type:"error",error:R}),R}if(A.status===410&&L.error==="conversation_deleted"){let R=new bt("conversation_deleted","This conversation was deleted");throw i({type:"error",error:R}),R}let k=new Error(L.error||"Failed to send message");throw i({type:"error",error:k}),k}if(!A.body){let L=new Error("No response body received");throw i({type:"error",error:L}),L}I(),i({type:"status",status:"connected"});try{await this.#X(A.body,i,e.assistantMessageId)}finally{i({type:"status",status:"idle"})}}catch(l){let c=l instanceof Error?l:new Error(String(l));throw!(c instanceof bt)&&!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&i({type:"error",error:c}),c}}async#he(e,n){n({type:"status",status:"connecting"});let o=await this.#F(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.#o};if(this.#v)try{let l=await this.#v();s={...s,...l}}catch(l){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.#s)try{i=await this.#s(this.#e,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal},o)}catch(l){let c=l instanceof Error?l:new Error(String(l));throw n({type:"error",error:c}),c}else i=await fetch(this.#e,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let l=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw n({type:"error",error:l}),l}n({type:"status",status:"connected"});try{await this.#X(i.body,n)}finally{n({type:"status",status:"idle"})}}async#le(e,n){n({type:"status",status:"connecting"});let o=await this.#b(e.messages,e.composerOptions);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.#o};if(this.#v)try{let l=await this.#v();s={...s,...l}}catch(l){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",l)}let i;if(this.#s)try{i=await this.#s(this.#e,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal},o)}catch(l){let c=l instanceof Error?l:new Error(String(l));throw n({type:"error",error:c}),c}else i=await fetch(this.#e,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let l=new Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw n({type:"error",error:l}),l}n({type:"status",status:"connected"});try{await this.#X(i.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(e,n,o,s){n({type:"status",status:"connected"});try{await this.#X(e,n,o,s)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){return(await Tr()).resolveApproval(this.#B(),e,n)}async#se(e,n,o,s){let i=!!(n&&n.length>0),l=i?Um(n):void 0,c=this.clientToolsFingerprintSessionId===e,u=i&&c&&this.lastSentClientToolsFingerprint===l,p=!i&&s?.emptyMeansReplace===!0&&this.#t===e,g=!1,y;for(let h=0;;h++){if(y=await o({...i&&(g||!u)&&n?{clientTools:n}:{},...p?{clientTools:[]}:{},...l?{clientToolsFingerprint:l}:{}}),y.status===409&&h===0&&i&&(await y.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){g=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:y,commit:()=>{this.lastSentClientToolsFingerprint=l??null,this.clientToolsFingerprintSessionId=e,i?this.#t=e:p&&(this.#t=null)}}}async resumeFlow(e,n,o){return(await Tr()).resumeFlow(this.#B(),e,n,o)}#ce(e){for(let n=e.length-1;n>=0;n--){let o=e[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async#_(e){let n={};this.#n.length&&await Promise.all(this.#n.map(async s=>{try{let i=await s({messages:e,config:this.config});i&&typeof i=="object"&&Object.assign(n,i)}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",i)}}));let o=this.#ce(e);return o&&Object.assign(n,o),Object.keys(n).length?n:null}#E(e){if(!e)return;let n={};return e.selectedModelId&&(n.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(n.activeModeIds=[...e.activeModeIds]),Object.keys(n).length>0?n:void 0}#T(e,n){let o=n?.selectedModelId;return!o||!("model"in e)?e:this.config.composer?.models?.some(i=>i.id===o)?{...e,model:o}:e}async#b(e,n){let o=this.#u().agentId;if(!this.config.agent&&!o)throw new Error("Agent configuration required for agent mode");let s=_d(rh(e),p=>Nd(p)&&(p.role==="user"||p.role==="assistant"||p.role==="system")&&(!p.variant||p.variant==="assistant")?sh(p):null),i=this.#E(n),l={agent:this.#T(this.config.agent??{agentId:o},i),messages:s,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};i&&(l.composerOptions=i);let c=[...Td(this.config),...await(await this.#P())?.snapshotForDispatch()??[]];c.length>0&&(l.clientTools=c);let u=await this.#_(e);return u&&(l.context=u),l}async#F(e,n){let o=_d(rh(e),p=>Nd(p)?sh(p):null),s=this.#u(),i={messages:o,...s.agentId?{agent:{agentId:s.agentId}}:s.flowId?{flowId:s.flowId}:{}};if(s.targetPayload)for(let[p,g]of Object.entries(s.targetPayload))p!=="messages"&&(i[p]=g);let l=[...Td(this.config),...await(await this.#P())?.snapshotForDispatch()??[]];l.length>0&&(i.clientTools=l);let c=await this.#_(e);c&&(i.context=c);let u=this.#E(n);if(u&&(i.composerOptions=u),this.#i)try{let p=await this.#i({payload:{...i},config:this.config});if(p&&typeof p=="object"){let g=p;return i.clientTools!==void 0&&!("clientTools"in g)&&(g.clientTools=i.clientTools),g}}catch(p){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",p)}return i}async#X(e,n,o,s){let{streamResponse:i}=Jf()??await Tr();return i({config:()=>this.config,createStreamParser:this.#m,parseSSEEvent:this.#a,onSSEEvent:(l,c)=>this.#c?.(l,c)},e,n,o,s)}};var{setLoader:wM,load:KC,provide:SM,getSync:GC}=je({fallbackImport:()=>import("./ui-extras-entry-WAYFKVNW.js")});var wl=KC;var Vd=GC;var{setLoader:MM,load:YC,provide:EM,getSync:QC}=je({fallbackImport:()=>import("./session-actions-ISSKSI66.js")});var $d=YC;var ih=QC;var XC=t=>t.sourceLabel?`quoted-text source=${t.sourceLabel}`:"quoted-text";function JC(t){let e=t?.text?.trim()??"";return e?Sf(XC(t),e):""}function ah(t){let e=JC(t.quote);return e?t.contentParts&&t.contentParts.length>0?{contentParts:[zo(e),...t.contentParts]}:{llmContent:[e,t.text].filter(Boolean).join(`
|
|
4
4
|
|
|
5
|
-
`)}:{}}function Sl(t,e=140){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}function lh(t,e){let n=t.findIndex(s=>s.id===e);if(n===-1||t[n].role!=="user")return null;let o=n+1;for(;o<t.length&&t[o].role!=="user";)o+=1;return{start:n,end:o}}function zd(t,e){let n=t.findIndex(o=>o.id===e);if(n<=0)return null;for(let o=n-1;o>=0;o-=1)if(t[o].role==="user")return t[o].id;return null}function ch(t){for(let e=t.length-1;e>=0;e-=1){let n=t[e];if(n.role==="user"||n.streaming)return null;if(!(n.role!=="assistant"||n.variant))return zd(t,n.id)?n.id:null}return null}function Ud(t){return t.role!=="user"||t.variant||t.streaming||t.contentParts?.length||t.contextMentions?.length||t.contentSegments?.length||t.mentionContext&&Object.keys(t.mentionContext).length>0||t.rawContent!==void 0||t.llmContent!==void 0&&t.llmContent!==t.content||t.quote?!1:typeof t.content=="string"&&t.content.length>0}function qd(t){let e=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of e){let o=t.find(s=>s.name===n);if(o)return o}return t.find(n=>n.lang.startsWith("en"))??t[0]}var Ci=class t{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(e,n){if(!t.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let s=new SpeechSynthesisUtterance(e.text),i=o.getVoices();if(e.voice){let l=i.find(c=>c.name===e.voice);l&&(s.voice=l)}else i.length>0&&(s.voice=this.options.pickVoice?this.options.pickVoice(i):qd(i));e.rate!==void 0&&(s.rate=e.rate),e.pitch!==void 0&&(s.pitch=e.pitch),s.onend=()=>n.onEnd?.(),s.onerror=l=>{let c=l.error;c==="canceled"||c==="interrupted"?n.onEnd?.():n.onError?.(new Error(c||"Speech synthesis failed"))},setTimeout(()=>{o.speak(s),n.onStart?.()},50)}pause(){t.isSupported()&&window.speechSynthesis.pause()}resume(){t.isSupported()&&window.speechSynthesis.resume()}stop(){t.isSupported()&&window.speechSynthesis.cancel()}};var xl=class{#e=null;#o=null;#m="idle";#n=new Set;#i=0;#s;constructor(e){this.#s=e}get supportsPause(){return this.#e?.supportsPause??!0}stateFor(e){return this.#o===e?this.#m:"idle"}activeMessageId(){return this.#o}onChange(e){return this.#n.add(e),()=>this.#n.delete(e)}toggle(e,n){if(this.#o===e){if(this.#m==="playing"){this.#e?.supportsPause?(this.#e.pause(),this.#a(e,"paused")):this.stop();return}if(this.#m==="paused"){this.#e?.resume(),this.#a(e,"playing");return}if(this.#m==="loading"){this.stop();return}}this.play(e,n)}async play(e,n){let o=++this.#i;this.#e?.stop(),this.#a(e,"loading");try{if(!this.#e){let s=await this.#s();if(o!==this.#i)return;if(!s){this.#a(null,"idle");return}this.#e=s}this.#e.speak(n,{onStart:()=>{o===this.#i&&this.#a(e,"playing")},onEnd:()=>{o===this.#i&&this.#a(null,"idle")},onError:()=>{o===this.#i&&this.#a(null,"idle")}})}catch{o===this.#i&&this.#a(null,"idle")}}stop(){this.#i++,this.#e?.stop(),this.#a(null,"idle")}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#n.clear()}#a(e,n){this.#o=n==="idle"?null:e,this.#m=n;for(let o of this.#n)o(this.#o,this.#m)}};var wi=class{#e;#o=!1;start(e){this.#e=e,this.#o=!1}cancel(){this.#o=!0}accepts(e){return!this.#o&&(!e||!this.#e||e===this.#e)}};var{setLoader:DM,load:ZC,getSync:ew}=je({fallbackImport:()=>import("./voice-runtime-
|
|
5
|
+
`)}:{}}function Sl(t,e=140){let n=t.replace(/\s+/g," ").trim();return n.length<=e?n:`${n.slice(0,e-1)}\u2026`}function lh(t,e){let n=t.findIndex(s=>s.id===e);if(n===-1||t[n].role!=="user")return null;let o=n+1;for(;o<t.length&&t[o].role!=="user";)o+=1;return{start:n,end:o}}function zd(t,e){let n=t.findIndex(o=>o.id===e);if(n<=0)return null;for(let o=n-1;o>=0;o-=1)if(t[o].role==="user")return t[o].id;return null}function ch(t){for(let e=t.length-1;e>=0;e-=1){let n=t[e];if(n.role==="user"||n.streaming)return null;if(!(n.role!=="assistant"||n.variant))return zd(t,n.id)?n.id:null}return null}function Ud(t){return t.role!=="user"||t.variant||t.streaming||t.contentParts?.length||t.contextMentions?.length||t.contentSegments?.length||t.mentionContext&&Object.keys(t.mentionContext).length>0||t.rawContent!==void 0||t.llmContent!==void 0&&t.llmContent!==t.content||t.quote?!1:typeof t.content=="string"&&t.content.length>0}function qd(t){let e=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of e){let o=t.find(s=>s.name===n);if(o)return o}return t.find(n=>n.lang.startsWith("en"))??t[0]}var Ci=class t{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(e,n){if(!t.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let s=new SpeechSynthesisUtterance(e.text),i=o.getVoices();if(e.voice){let l=i.find(c=>c.name===e.voice);l&&(s.voice=l)}else i.length>0&&(s.voice=this.options.pickVoice?this.options.pickVoice(i):qd(i));e.rate!==void 0&&(s.rate=e.rate),e.pitch!==void 0&&(s.pitch=e.pitch),s.onend=()=>n.onEnd?.(),s.onerror=l=>{let c=l.error;c==="canceled"||c==="interrupted"?n.onEnd?.():n.onError?.(new Error(c||"Speech synthesis failed"))},setTimeout(()=>{o.speak(s),n.onStart?.()},50)}pause(){t.isSupported()&&window.speechSynthesis.pause()}resume(){t.isSupported()&&window.speechSynthesis.resume()}stop(){t.isSupported()&&window.speechSynthesis.cancel()}};var xl=class{#e=null;#o=null;#m="idle";#n=new Set;#i=0;#s;constructor(e){this.#s=e}get supportsPause(){return this.#e?.supportsPause??!0}stateFor(e){return this.#o===e?this.#m:"idle"}activeMessageId(){return this.#o}onChange(e){return this.#n.add(e),()=>this.#n.delete(e)}toggle(e,n){if(this.#o===e){if(this.#m==="playing"){this.#e?.supportsPause?(this.#e.pause(),this.#a(e,"paused")):this.stop();return}if(this.#m==="paused"){this.#e?.resume(),this.#a(e,"playing");return}if(this.#m==="loading"){this.stop();return}}this.play(e,n)}async play(e,n){let o=++this.#i;this.#e?.stop(),this.#a(e,"loading");try{if(!this.#e){let s=await this.#s();if(o!==this.#i)return;if(!s){this.#a(null,"idle");return}this.#e=s}this.#e.speak(n,{onStart:()=>{o===this.#i&&this.#a(e,"playing")},onEnd:()=>{o===this.#i&&this.#a(null,"idle")},onError:()=>{o===this.#i&&this.#a(null,"idle")}})}catch{o===this.#i&&this.#a(null,"idle")}}stop(){this.#i++,this.#e?.stop(),this.#a(null,"idle")}destroy(){this.stop(),this.#e?.destroy?.(),this.#e=null,this.#n.clear()}#a(e,n){this.#o=n==="idle"?null:e,this.#m=n;for(let o of this.#n)o(this.#o,this.#m)}};var wi=class{#e;#o=!1;start(e){this.#e=e,this.#o=!1}cancel(){this.#o=!0}accepts(e){return!this.#o&&(!e||!this.#e||e===this.#e)}};var{setLoader:DM,load:ZC,getSync:ew}=je({fallbackImport:()=>import("./voice-runtime-TWFJ4UUS.js")});var Si=ZC,dh=ew;function jd(t){if(!t)return"";let e=tw(t);return ph(e!==null?e:t)}function tw(t){let e=t.trim(),n=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(e=n[1].trim()),!e.startsWith("{"))return null;try{let o=JSON.parse(e);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function ph(t){if(!t)return"";let e=t;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
|
|
6
6
|
`),e=e.replace(/\n{2,}/g,`
|
|
7
7
|
`),e.trim()}var uh=null;var Kd=()=>uh?uh():import("./runtype-tts-entry-NFBVWR7N.js");var{setLoader:VM,load:nw}=je({fallbackImport:()=>import("./session-reconnect-JKIJBHS5.js")});var gh=nw;var ow=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId","getIdentityProof","identityProvider","getStoredConversationId","setStoredConversationId","clearStoredConversationId","clearStoredSessionId"];function rw(t,e){return ow.some(n=>t[n]!==e[n])}var jn=class extends Error{constructor(e,n){super(n),this.name="SessionHistoryError",this.code=e}};function Gd(t,e){let n=t instanceof Error?t:new Error(String(t));if(typeof e=="string")return e;if(typeof e=="function")return e(n);let o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
|
|
8
8
|
|
|
@@ -23,7 +23,7 @@ _Details: ${n.message}_`:o}var mh=t=>Sd(t)||t===Ed,Al=class t{constructor(e={},n
|
|
|
23
23
|
`):""},kp=(t,e,n)=>{bl(t,e,{stateSet:n,previewKind:"reasoning",iconColor:"currentColor"})},Pp=(t,e,n=new Set)=>{e=vl(e,"reasoning");let o=t.reasoning,s=ml("persona-reasoning-bubble",t.id);if(!o)return mo(s,t,e,"reasoning");let i=e?.features?.reasoningDisplay??{},l=i.expandable??rs.expandable,c=l&&n.has(t.id),u=o.status!=="complete",p=ix(t,i.previewMaxLines??rs.previewMaxLines),g=fl({expandable:l,expanded:c,bubbleType:"reasoning"}),y=P("div","persona-flex persona-flex-col persona-text-left"),h=P("span","persona-text-xs persona-text-persona-primary"),C=qo(e,"reasoning")==="row",E=C&&!u?`Thought for ${bi(o.durationMs??(o.completedAt!==void 0&&o.startedAt!==void 0?o.completedAt-o.startedAt:void 0))}`:"Thinking...",A=e?.reasoning??{},I=String(o.startedAt??Date.now()),L=()=>{let W=P("span","");return W.setAttribute("data-tool-elapsed",I),W.textContent=Ja(o),W},k=A.renderCollapsedSummary?.({message:t,reasoning:o,defaultSummary:E,previewText:p,isActive:u,config:e??{},elapsed:Ja(o),createElapsedElement:L});typeof k=="string"&&k.trim()?(h.textContent=k,y.appendChild(h)):k instanceof HTMLElement?y.appendChild(k):(h.textContent=E,y.appendChild(h));let R=P("span","persona-text-xs persona-text-persona-primary");R.textContent=Km(o),C||y.appendChild(R);let B=i.loadingAnimation??rs.loadingAnimation,O=A.activeTextTemplate,V=A.completeTextTemplate,J=u?O:V,_=k instanceof HTMLElement,Q=(W,ee)=>{h.textContent="";let ne=Za(W,""),he=0;for(let ve of ne){let Xe=ve.styles.length>0?(()=>{let Je=P("span",ve.styles.map(Wt=>`persona-tool-text-${Wt}`).join(" "));return h.appendChild(Je),Je})():h;if(ve.isDuration&&u)Xe.appendChild(L());else{let Je=ve.isDuration?Ja(o):ve.text;ee?he=ms(Xe,Je,he):Xe.appendChild(document.createTextNode(Je))}}};if(!_&&J)if(R.style.display="none",h.style.display="",u&&B!=="none"){let W=A.loadingAnimationDuration??2e3;h.setAttribute("data-preserve-animation","true"),B==="pulse"?(h.classList.add("persona-tool-loading-pulse"),h.style.setProperty("--persona-tool-anim-duration",`${W}ms`),Q(J,!1)):(h.classList.add(`persona-tool-loading-${B}`),h.style.setProperty("--persona-tool-anim-duration",`${W}ms`),B==="shimmer-color"&&(A.loadingAnimationColor&&h.style.setProperty("--persona-tool-anim-color",A.loadingAnimationColor),A.loadingAnimationSecondaryColor&&h.style.setProperty("--persona-tool-anim-secondary-color",A.loadingAnimationSecondaryColor)),Q(J,!0))}else Q(J,!1);else if(!_&&u&&B!=="none"){h.style.display="";let W=A.loadingAnimationDuration??2e3;if(h.setAttribute("data-preserve-animation","true"),B==="pulse")h.classList.add("persona-tool-loading-pulse"),h.style.setProperty("--persona-tool-anim-duration",`${W}ms`);else{h.classList.add(`persona-tool-loading-${B}`),h.style.setProperty("--persona-tool-anim-duration",`${W}ms`),B==="shimmer-color"&&(A.loadingAnimationColor&&h.style.setProperty("--persona-tool-anim-color",A.loadingAnimationColor),A.loadingAnimationSecondaryColor&&h.style.setProperty("--persona-tool-anim-secondary-color",A.loadingAnimationSecondaryColor));let ee=h.textContent||E;h.textContent="",ms(h,ee,0)}o.status==="complete"&&!C&&(h.style.display="none")}else _||(o.status==="complete"&&!C?h.style.display="none":h.style.display="");if(i.iconName&&!_){let W=P("span","persona-reasoning-header-icon"),ee=se(i.iconName,16,"currentColor",2);ee&&(W.appendChild(ee),g.appendChild(W))}let G="currentColor",w=fs(g,y,{expandable:l,expanded:c,iconColor:G,metaGap:!1}),v=hl({bubble:s,previewKind:"reasoning",expanded:c,isActive:u,previewText:p,activePreview:i.activePreview,activeMinHeight:i.activeMinHeight,renderPreview:()=>e?.reasoning?.renderCollapsedPreview?.({message:t,reasoning:o,defaultPreview:p,isActive:u,config:e??{}})});if(!l)return s.append(g,v),mo(s,t,e,"reasoning");let T=P("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");T.style.display=c?"":"none";let S=o.chunks.join(""),z=P("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return z.textContent=S||(o.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),T.appendChild(z),yl({expanded:c,header:g,toggleIcon:w,content:T,collapsedPreview:v,iconColor:G}),s.append(g,v,T),mo(s,t,e,"reasoning")};var _y=t=>{if(t==null)return!0;if(typeof t=="string"){if(!t.trim())return!0;try{return _y(JSON.parse(t))}catch{return!1}}return typeof t=="object"&&Object.keys(t).length===0},ax=t=>{if(t!==null&&typeof t=="object")return!0;if(typeof t!="string")return!1;try{let e=JSON.parse(t);return e!==null&&typeof e=="object"}catch{return!1}};function Fy(t,e,n){let o=e.toolCall;if(!o)return;let s=n.toolCall??{},i=(c,u)=>{let p=Y("section",{className:"persona-tool-detail",attrs:{"data-persona-tool-detail":c.toLowerCase()},style:{backgroundColor:s.codeBlockBackgroundColor,borderColor:s.codeBlockBorderColor,borderWidth:s.codeBlockBorderColor?"1px":void 0}}),g=Y("div",{className:"persona-tool-detail-label",text:c,style:{color:s.labelTextColor}}),y=ls(u),h=Y("pre",{className:`persona-tool-detail-value${ax(u)?" persona-tool-detail-code":""}`,text:y,attrs:y.length>420||y.split(`
|
|
24
24
|
`).length>7?{tabindex:"0","aria-label":`${c} content`}:{},style:{color:s.codeBlockTextColor??s.contentTextColor}}),C=Y("button",{className:"persona-tool-detail-copy",attrs:{type:"button","data-persona-copy-tool-detail":"","aria-label":`Copy ${c.toLowerCase()}`,title:`Copy ${c.toLowerCase()}`}}),E=se("copy",14,"currentColor",1.7);E&&C.appendChild(E),p.append(g,h,C),t.appendChild(p)};_y(o.args)||i("Request",o.args);let l=o.status==="complete"&&o.result!==void 0?o.result:o.chunks?.join("");l!==void 0&&(typeof l!="string"||l.trim())&&i("Response",l),o.success===!1&&t.appendChild(Y("div",{className:"persona-text-sm persona-whitespace-pre-wrap",text:o.error||"Tool failed",attrs:{"data-persona-tool-error":"",role:"status"}}))}var Lp=new WeakMap;async function Ny(t){let e=t.closest("[data-persona-tool-detail]"),n=e?.querySelector("pre");if(!n)return;let o=`Copy ${e?.getAttribute("data-persona-tool-detail")}`;clearTimeout(Lp.get(t));try{await navigator.clipboard.writeText(n.textContent??""),t.dataset.copied="true",t.setAttribute("aria-label","Copied"),t.title="Copied";let s=se("check",14,"currentColor",2);s&&t.replaceChildren(s)}catch{t.setAttribute("aria-label","Copy failed \u2014 try again"),t.title="Copy failed \u2014 try again"}Lp.set(t,setTimeout(()=>{delete t.dataset.copied,t.setAttribute("aria-label",o),t.title=o;let s=se("copy",14,"currentColor",1.7);s&&t.replaceChildren(s),Lp.delete(t)},1800))}var Vy=(t,e=!1)=>t.toggleTextColor||t.headerTextColor||(e?"currentColor":"var(--persona-primary, #171717)"),lx=(t,e)=>{let n=t.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(l=>l.trim()).filter(Boolean).slice(-e).join(`
|
|
25
25
|
`);let s=ls(n.args).trim();return s?s.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(0,e).join(`
|
|
26
|
-
`):""},Ip=(t,e)=>{t.style.backgroundColor=e.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",t.style.borderColor=e.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",t.style.color=e.codeBlockTextColor??"var(--persona-text, #171717)"},cx=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,s=o?.collapsedMode??$o.collapsedMode,i=n?.success===!1?n.error||"Tool failed":lx(t,o?.previewMaxLines??$o.previewMaxLines),l=n?qo(e,"tool")==="row"?`${n.status==="complete"?"Used":"Using"} ${n.name?.trim()||"tool"}`:Ym(n):"";if(!n)return{summary:l,previewText:i,isActive:!1};let c=n.status!=="complete",u=e?.toolCall??{},p=l;return s==="tool-name"?p=n.name?.trim()||l:s==="tool-preview"&&i&&(p=i),c&&u.activeTextTemplate?p=Ad(n,u.activeTextTemplate,p):!c&&u.completeTextTemplate&&(p=Ad(n,u.completeTextTemplate,p)),n.success===!1?p+=" \xB7 Failed":n.superseded&&(p+=" \xB7 Approved, ran again below"),{summary:p,previewText:i,isActive:c}},Hp=(t,e,n,o)=>{bl(t,e,{stateSet:n,previewKind:"tool",iconColor:Vy(o?.toolCall??{},e.classList.contains("persona-activity-row"))})},Rp=(t,e,n=new Set)=>{e=vl(e,"tool");let o=t.toolCall,s=e?.toolCall??{},i=ml("persona-tool-bubble",t.id);if(s.backgroundColor&&(i.style.backgroundColor=s.backgroundColor),s.borderColor&&(i.style.borderColor=s.borderColor),s.borderWidth&&(i.style.borderWidth=s.borderWidth),s.borderRadius&&(i.style.borderRadius=s.borderRadius),i.style.boxShadow=s.shadow!==void 0?s.shadow.trim()===""?"none":s.shadow:"var(--persona-tool-bubble-shadow)",!o)return mo(i,t,e,"tool");let l=e?.features?.toolCallDisplay??{},c=l.expandable??$o.expandable,u=c&&n.has(t.id),{summary:p,previewText:g,isActive:y}=cx(t,e),h=fl({expandable:c,expanded:u,bubbleType:"tool"});s.headerBackgroundColor&&(h.style.backgroundColor=s.headerBackgroundColor),s.headerPaddingX&&(h.style.paddingLeft=s.headerPaddingX,h.style.paddingRight=s.headerPaddingX),s.headerPaddingY&&(h.style.paddingTop=s.headerPaddingY,h.style.paddingBottom=s.headerPaddingY);let C=P("div","persona-flex persona-flex-col persona-text-left"),E=P("span","persona-text-xs persona-text-persona-primary");s.headerTextColor&&(E.style.color=s.headerTextColor);let A=String(o.startedAt??Date.now()),I=()=>{let v=P("span","");return v.setAttribute("data-tool-elapsed",A),v.textContent=Xa(o),v},L=s.renderCollapsedSummary?.({message:t,toolCall:o,defaultSummary:p,previewText:g,collapsedMode:l.collapsedMode??$o.collapsedMode,isActive:y,config:e??{},elapsed:Xa(o),createElapsedElement:I});typeof L=="string"&&L.trim()?(E.textContent=L,C.appendChild(E)):L instanceof HTMLElement?C.appendChild(L):(E.textContent=p,C.appendChild(E));let k=l.loadingAnimation??$o.loadingAnimation,R=s.activeTextTemplate,B=s.completeTextTemplate,O=y?R:B,V=L instanceof HTMLElement,J=(v,T)=>{E.textContent="";let S=o.name?.trim()||"tool",z=Za(v,S),W=0;for(let ee of z){let ne=ee.styles.length>0?(()=>{let he=P("span",ee.styles.map(ve=>`persona-tool-text-${ve}`).join(" "));return E.appendChild(he),he})():E;if(ee.isDuration&&y)ne.appendChild(I());else{let he=ee.isDuration?Xa(o):ee.text;T?W=ms(ne,he,W):ne.appendChild(document.createTextNode(he))}}};if(!V)if(y&&k!=="none"){let v=s.loadingAnimationDuration??2e3;if(E.setAttribute("data-preserve-animation","true"),k==="pulse")E.classList.add("persona-tool-loading-pulse"),E.style.setProperty("--persona-tool-anim-duration",`${v}ms`),O&&J(O,!1);else if(E.classList.add(`persona-tool-loading-${k}`),E.style.setProperty("--persona-tool-anim-duration",`${v}ms`),k==="shimmer-color"&&(s.loadingAnimationColor&&E.style.setProperty("--persona-tool-anim-color",s.loadingAnimationColor),s.loadingAnimationSecondaryColor&&E.style.setProperty("--persona-tool-anim-secondary-color",s.loadingAnimationSecondaryColor)),O)J(O,!0);else{let T=E.textContent||p;E.textContent="",ms(E,T,0)}}else O&&J(O,!1);let _=Vy(s,qo(e,"tool")==="row"),Q=fs(h,C,{expandable:c,expanded:u,iconColor:_,metaGap:!0}),G=hl({bubble:i,previewKind:"tool",expanded:u,isActive:y,previewText:g,activePreview:l.activePreview,activeMinHeight:l.activeMinHeight,renderPreview:()=>s.renderCollapsedPreview?.({message:t,toolCall:o,defaultPreview:g,isActive:y,config:e??{}})});if(!c)return i.append(h,G),mo(i,t,e,"tool");let w=P("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(w.style.display=u?"":"none",s.contentBackgroundColor&&(w.style.backgroundColor=s.contentBackgroundColor),s.contentTextColor&&(w.style.color=s.contentTextColor),s.contentPaddingX&&(w.style.paddingLeft=s.contentPaddingX,w.style.paddingRight=s.contentPaddingX),s.contentPaddingY&&(w.style.paddingTop=s.contentPaddingY,w.style.paddingBottom=s.contentPaddingY),e.future?.v5Defaults===!0)Fy(w,t,e);else{if(o.name){let v=P("div","persona-text-xs persona-text-persona-muted persona-italic");s.contentTextColor?v.style.color=s.contentTextColor:s.headerTextColor&&(v.style.color=s.headerTextColor),v.textContent=o.name,w.appendChild(v)}if(o.args!==void 0){let v=P("div","persona-space-y-1"),T=P("div","persona-text-xs persona-text-persona-muted");s.labelTextColor&&(T.style.color=s.labelTextColor),T.textContent="Arguments";let S=P("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",Ip(S,s),S.textContent=ls(o.args),v.append(T,S),w.appendChild(v)}if(o.chunks&&o.chunks.length){let v=P("div","persona-space-y-1"),T=P("div","persona-text-xs persona-text-persona-muted");s.labelTextColor&&(T.style.color=s.labelTextColor),T.textContent="Activity";let S=P("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",Ip(S,s),S.textContent=o.chunks.join(""),v.append(T,S),w.appendChild(v)}if(o.success===!1&&w.appendChild(Y("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){let v=P("div","persona-space-y-1"),T=P("div","persona-text-xs persona-text-persona-muted");s.labelTextColor&&(T.style.color=s.labelTextColor),T.textContent="Result";let S=P("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",Ip(S,s),S.textContent=ls(o.result),v.append(T,S),w.appendChild(v)}if(o.status==="complete"&&typeof o.duration=="number"){let v=P("div","persona-text-xs persona-text-persona-muted");s.contentTextColor&&(v.style.color=s.contentTextColor),v.textContent=`Duration: ${o.duration}ms`,w.appendChild(v)}}return yl({expanded:u,header:h,toggleIcon:Q,content:w,collapsedPreview:G,iconColor:_}),i.append(h,G,w),mo(i,t,e,"tool")};var{setLoader:Ck,load:dx,provide:wk,getSync:px}=je({fallbackImport:()=>import("./approval-ui-QAKWNFNM.js")});var $y=dx;var zy=px;var{setLoader:Ak,load:ux}=je({fallbackImport:()=>import("./event-stream-view-FOIJHFQO.js")});var Wp=ux;var Bp=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:Lk,load:gx,provide:Ik,getSync:mx}=je({fallbackImport:()=>import("./artifacts-ui-NJGMM27I.js")}),xs=null,Ul=new Set,Uy=t=>{if(xs)return xs;xs=t,t.initArtifactsUi({componentRegistry:go});for(let o of Bp)go.has(o)||go.register(o,o==="PersonaArtifactCard"?t.PersonaArtifactCard:t.PersonaArtifactInline,{bubbleChrome:!1});let e=is();e?t.__provideMarkdownParsers(e):Ka(()=>{let o=is();o&&t.__provideMarkdownParsers(o)}),t.__setIconsExtraLoader(()=>_m());let n=[...Ul];Ul.clear();for(let o of n)try{o()}catch{}return t};var ql=()=>gx().then(Uy);var yo=()=>{if(xs)return xs;let t=mx();return t?Uy(t):null},Dp=t=>xs?()=>{}:(Ul.add(t),()=>{Ul.delete(t)});function zt(t){return t?.features?.artifacts?.enabled===!0}function qy(t,e){if(t.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),t.style.removeProperty("--persona-artifact-pane-border"),t.style.removeProperty("--persona-artifact-pane-border-left"),!zt(e))return;let n=e.features?.artifacts?.layout,o=n?.paneBorder?.trim(),s=n?.paneBorderLeft?.trim();o?(t.classList.add("persona-artifact-border-full"),t.style.setProperty("--persona-artifact-pane-border",o)):s&&(t.classList.add("persona-artifact-border-left"),t.style.setProperty("--persona-artifact-pane-border-left",s))}function fx(t){t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),t.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),t.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var jy=["panel","seamless","detached"];function Op(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&jy.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function _p(t){return!t||!zt(t)?!1:Op(t)==="detached"}function Oi(t,e){if(!zt(e)){t.style.removeProperty("--persona-artifact-split-gap"),t.style.removeProperty("--persona-artifact-pane-width"),t.style.removeProperty("--persona-artifact-pane-max-width"),t.style.removeProperty("--persona-artifact-pane-min-width"),t.style.removeProperty("--persona-artifact-drawer-width"),t.style.removeProperty("--persona-artifact-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),fx(t),qy(t,e);return}let n=e.features?.artifacts?.layout,o=Op(e)==="detached"?"var(--persona-panel-inset)":"0";t.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),t.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),t.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.drawerWidth?t.style.setProperty("--persona-artifact-drawer-width",n.drawerWidth):t.style.removeProperty("--persona-artifact-drawer-width"),n?.paneMinWidth?t.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):t.style.removeProperty("--persona-artifact-pane-min-width");let s=n?.paneBackground?.trim();s?t.style.setProperty("--persona-artifact-pane-bg",s):t.style.removeProperty("--persona-artifact-pane-bg");let i=n?.panePadding?.trim();i?t.style.setProperty("--persona-artifact-pane-padding",i):t.style.removeProperty("--persona-artifact-pane-padding");let l=[[n?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[n?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[n?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[n?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[c,u]of l){let p=c?.trim();p?t.style.setProperty(u,p):t.style.removeProperty(u)}qy(t,e)}function _i(t,e){for(let c of jy)t.classList.remove(`persona-artifact-appearance-${c}`);if(t.style.removeProperty("--persona-artifact-pane-radius"),t.style.removeProperty("--persona-artifact-pane-shadow"),t.style.removeProperty("--persona-artifact-chat-shadow"),!zt(e))return;let n=e.features?.artifacts?.layout,o=Op(e);t.classList.add(`persona-artifact-appearance-${o}`);let s=n?.paneBorderRadius?.trim();s&&t.style.setProperty("--persona-artifact-pane-radius",s);let i=n?.paneShadow?.trim();i&&t.style.setProperty("--persona-artifact-pane-shadow",i);let l=n?.chatShadow?.trim();l&&t.style.setProperty("--persona-artifact-chat-shadow",l)}function Ky(t,e){return!e||!zt(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var hx=new Set(["__proto__","prototype","constructor"]),yx=new Set(["collapsed","card","panel","inline"]),Gy=new Set(["markdown","component"]),bx=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Lr=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Kl=t=>!hx.has(t),Fp=t=>typeof t=="string"&&yx.has(t),Ir=t=>Object.keys(t).length>0;function Gn(t,e,n,o){t.push({path:e,code:n,message:o})}var vx="Ignored because this key is not part of the persisted preference schema.",jl="Ignored an unsupported value.",Cx="Expected collapsed, panel, or inline.",wx='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',Yy={kind:"mode",message:jl},As={kind:"string",message:"Expected a CSS length string."},bo={kind:"boolean"},Sx={paneWidth:As,paneMaxWidth:As,paneMinWidth:As,expandedPanelWidth:As,resizableMinWidth:As,resizableMaxWidth:As,expandLauncherPanelWhenOpen:bo,resizable:bo},xx={kind:"object",message:"Expected a preference object.",children:{showToolCalls:bo,showReasoning:bo,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:jl},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:jl},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:jl},expandable:bo,grouped:bo}},reasoningDisplay:{kind:"object",children:{expandable:bo,activePreview:bo}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:Yy,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:Yy,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Gy,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Gy}}},filePreview:{kind:"object",children:{enabled:bo}},layout:{kind:"object",children:Sx}}}}};function Qy(t,e,n,o){if(t!==void 0)switch(e.kind){case"boolean":return typeof t=="boolean"?t:Gn(o,n,"invalid_type","Expected a boolean.");case"string":return typeof t=="string"?t:Gn(o,n,"invalid_type",e.message);case"enum":return typeof t=="string"&&e.values.has(t)?t:Gn(o,n,"invalid_value",e.message);case"mode":return Fp(t)?Qa(t):Gn(o,n,"invalid_value",e.message);case"modeMap":{if(!Lr(t))return Gn(o,n,"invalid_type","Expected an object.");let s=e.keys==="mediaType"?void 0:e.keys,i={};for(let[l,c]of Object.entries(t)){let u=s?l:jm(l);Kl(l)&&(s?s.has(l):bx.test(u))?Fp(c)?i[u]=Qa(c):Gn(o,`${n}.${l}`,"invalid_value",Cx):Gn(o,`${n}.${l}`,s?"unknown_key":"invalid_value",s?"Ignored an unsupported selector.":wx)}return Ir(i)?i:void 0}case"object":{if(e.bareMode&&Fp(t))return Qa(t);if(!Lr(t))return Gn(o,n,"invalid_type",e.message??"Expected an object.");let s=Object.keys(e.children),i=c=>n?`${n}.${c}`:c;for(let c of Object.keys(t))(!Kl(c)||!s.includes(c))&&Gn(o,i(c),"unknown_key",vx);let l={};for(let c of s){let u=e.children[c],p=Qy(t[c],u,i(c),o);if(u.deprecated&&t[c]!==void 0&&Gn(o,i(c),"deprecated_key",u.deprecated),p===void 0)continue;let g=u.alias??c,y=l[g];l[g]=Lr(y)&&Lr(p)?{...y,...p}:p}return Ir(l)?l:void 0}}}function Ax(t){let e=[];return{preferences:(t===null?void 0:Qy(t,xx,"",e))??{},issues:e}}function Ms(t){if(Array.isArray(t))return t.map(Ms);if(!Lr(t))return t;let e={};for(let[n,o]of Object.entries(t))Kl(n)&&o!==void 0&&(e[n]=Ms(o));return e}function Xy(t,e){let n=Ms(t);for(let[o,s]of Object.entries(e)){if(!Kl(o)||s===void 0)continue;let i=n[o];n[o]=Lr(i)&&Lr(s)?Xy(i,s):Ms(s)}return n}function Mx(t){let e={},n;for(let s of t){let i=Ax(s).preferences;n=Jy(n,i.artifacts?.display),e=Xy(e,i)}let o=e;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function Ex(t,e){if(e===void 0)return t===void 0?void 0:Ms(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,s={...n.byMediaType,...e.byMediaType},i={...o?{default:o}:{},...Ir(s)?{byMediaType:s}:{}};return Ir(i)?i:void 0}function Jy(t,e){if(e===void 0)return t===void 0?void 0:Ms(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,s={...n.byType,...n.byKind,...e.byType,...e.byKind},i=Ex(n.files,e.files),l={...o?{default:o}:{},...Ir(s)?{byKind:s}:{},...i!==void 0?{files:i}:{}};return Ir(l)?l:void 0}function Tx(t={},e){let n=Mx(e),o={...t};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...t.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...t.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let s=t.artifacts??{},i={...s};if(n.artifacts.display!==void 0){let l=Jy(s.display,n.artifacts.display);l!==void 0&&(i.display=l)}n.artifacts.filePreview&&(i.filePreview={...s.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(i.layout={...s.layout,...n.artifacts.layout}),o.artifacts=i}return o}function Np(t){let e=t.preferences;return!e||!Ir(e)?t:{...t,features:Tx(t.features??{},[e])}}function kx(t,e){if(!t?.trim())return e;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return n?Math.max(0,Number(n[1])):e}function Px(t){if(!t?.trim())return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return e?Math.max(0,Number(e[1])):null}function Lx(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function Ix(t,e,n,o){let s=t-o-2*e-n;return Math.max(0,s)}function Vp(t,e){let o=(e.getComputedStyle(t).gap||"0px").trim().split(/\s+/)[0]??"0px",s=/^([\d.]+)px$/i.exec(o);if(s)return Number(s[1]);let i=/^([\d.]+)/.exec(o);return i?Number(i[1]):8}function Zy(t,e,n,o,s,i,l=200){let c=kx(s,200),u=Ix(e,n,o,l);u=Math.max(c,u);let p=Px(i);return p!==null&&(u=Math.min(u,p)),Lx(t,c,u)}var{setLoader:_k,load:Hx,provide:Fk,getSync:Rx}=je({fallbackImport:()=>import("./forms-ui-PJMI3HQR.js")});var eb=Hx;var tb=Rx;var $p=class{#e=new Map;register(e){this.#e.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.#e.set(e.id,e),e.onRegister?.()}unregister(e){let n=this.#e.get(e);n&&(n.onUnregister?.(),this.#e.delete(e))}getAll(){return Array.from(this.#e.values()).sort((e,n)=>(n.priority??0)-(e.priority??0))}getForInstance(e){let n=this.getAll();if(!e||e.length===0)return n;let o=new Set(e.map(i=>i.id));return[...n.filter(i=>!o.has(i.id)),...e].sort((i,l)=>(l.priority??0)-(i.priority??0))}clear(){this.#e.forEach(e=>e.onUnregister?.()),this.#e.clear()}},zp=new $p;var nb=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Wx=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),ob=(t,e,n)=>{if(!nb(t)||!nb(e)||Wx.has(n))return e;let o={...t};for(let s of Object.keys(e)){if(e[s]===void 0){delete o[s];continue}let i=n?`${n}.${s}`:s;o[s]=ob(t[s],e[s],i)}return o};function rb(t,e){let n=Pm(qa),o=Im(t,e,n),s=Lm(Hm(ob(t,e,""),n,o),o);return Wm(ja(s),Bm(t,e))}var sb=()=>{let t=new Map,e=(s,i)=>(t.has(s)||t.set(s,new Set),t.get(s).add(i),()=>n(s,i)),n=(s,i)=>{t.get(s)?.delete(i)};return{on:e,off:n,emit:(s,i)=>{t.get(s)?.forEach(l=>{try{l(i)}catch(c){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",c)}})}}};var Bx=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},Dx=t=>{let e=t.trim(),n=e.indexOf("{");if(n===-1)return null;let o=0;for(let s=n;s<e.length;s+=1){let i=e[s];if(i==="{"&&(o+=1),i==="}"&&(o-=1,o===0))return e.slice(n,s+1)}return null},qp=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=Bx(t),n=Dx(e);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:s,...i}=o;return{type:String(s),payload:i,raw:o}}catch{return null}},Up=t=>typeof t=="string"?t:t==null?"":String(t),Fi={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:Up(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=Up(n.element);if(o&&e.document?.querySelector){let s=e.document.querySelector(o);s?setTimeout(()=>{s.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Up(n.text)}}},ib=t=>Array.isArray(t)?t.map(e=>String(e)):[],jp=t=>{let e=new Set(ib(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(ib(t.getSessionMetadata().processedActionMessageIds))},o=()=>{let i=Array.from(e);t.updateSessionMetadata(l=>({...l,processedActionMessageIds:i}))};return{process:i=>{if(i.streaming||i.message.role!=="assistant"||!i.text||e.has(i.message.id))return null;let l=typeof i.raw=="string"&&i.raw||typeof i.message.rawContent=="string"&&i.message.rawContent||typeof i.text=="string"&&i.text||null;!l&&typeof i.text=="string"&&i.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let c=l?t.parsers.reduce((p,g)=>p||g?.({text:l,message:i.message})||null,null):null;if(!c)return null;e.add(i.message.id),o();let u={action:c,message:i.message};t.emit("action:detected",u);for(let p of t.handlers)if(p)try{let g=()=>{t.emit("action:resubmit",u)},y=p(c,{message:i.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:g});if(!y)continue;if(y.handled){let h=y.persistMessage!==!1;return{text:y.displayText!==void 0?y.displayText:"",persist:h,resubmit:y.resubmit}}}catch(g){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",g)}return{text:"",persist:!0}},syncFromMetadata:n}};var Ox=t=>{if(!t)return null;try{return JSON.parse(t)}catch(e){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},_x=t=>t.map(e=>({...e,streaming:!1})),Fx=t=>t.map(e=>({...e,status:"complete"})),ab=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?Ox(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let s={...n,messages:n.messages?_x(n.messages):void 0,artifacts:n.artifacts?Fx(n.artifacts):void 0};o.setItem(t,JSON.stringify(s))}catch(s){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let n=e();if(n)try{n.removeItem(t)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var Nx=t=>{let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e.toString(16).padStart(8,"0")},lb=async t=>{let e=globalThis.crypto?.subtle;if(e)try{let n=await e.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}catch{}return Nx(t)},Vx=async(t,e)=>{let n=await lb(t);return{storageKey:`${e}visitor:${n}`,leaseKey:`${e}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await lb(`${t}\0${e}`)}`}};var cb=(t,e,n)=>{let o="",s="",i="",l=!1,c=!1,u=0,p=null,g=null,y=new Set,h=()=>{if(n||l)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return l=!0,null}},C=()=>{let _=h();if(!_)return p;try{return _.getItem(o)}catch{return l=!0,p}},E=(_,Q)=>{if(c||_===p)return;let G=p;p=_,u+=1;let w={previousToken:G,token:_,source:Q,revision:u};for(let v of y)v(w)},A=_=>{c||_.key!==null&&_.key!==o||E(_.key===null?null:_.newValue??null,"external")},I=(async()=>{let _=await Vx(t,e);o=_.storageKey,s=_.leaseKey,i=_.lockName,p=C(),!n&&typeof window<"u"&&window.addEventListener("storage",A)})(),L=_=>new Promise(Q=>setTimeout(Q,_)),k=()=>{let _=h();if(!_)return null;try{let Q=_.getItem(s);if(!Q)return null;let G=JSON.parse(Q);return typeof G?.expiresAt=="number"&&typeof G?.ownerNonce=="string"?G:null}catch{return null}},R=_=>{let Q=h();if(Q)try{k()?.ownerNonce===_&&Q.removeItem(s)}catch{}},B=new Set,O=_=>c?Promise.reject(new Error("Visitor store destroyed before its first init could start")):_(),V=_=>new Promise(Q=>{let G=setTimeout(w,_);function w(){clearTimeout(G),B.delete(w),window.removeEventListener("storage",v),Q()}function v(T){(T.key===null||T.key===s)&&w()}B.add(w),window.addEventListener("storage",v)}),J=async _=>{let Q=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,G=Date.now()+15e3;for(;!c&&Date.now()<G;){let w=h();if(!w)break;let v=Date.now(),T=k();if(T&&T.expiresAt>v&&T.ownerNonce!==Q){await V(Math.min(T.expiresAt-v,500));continue}try{w.setItem(s,JSON.stringify({ownerNonce:Q,expiresAt:v+1e4}))}catch{l=!0;break}if(await L(20+Math.random()*40),k()?.ownerNonce!==Q){await V(500);continue}g=Q;try{return await O(_)}finally{g=null,R(Q)}}return O(_)};return{ready:I,async get(){return await I,E(C(),"external"),p},async set(_){await I;let Q=h();if(Q)try{Q.setItem(o,_)}catch{l=!0}E(_,"local")},async clear(){await I;let _=h();if(_)try{_.removeItem(o)}catch{l=!0}E(null,"local")},revision(){return u},subscribe(_){return y.add(_),()=>{y.delete(_)}},async withFirstInitLock(_){await I;let Q=globalThis.navigator?.locks;return Q?.request?Q.request(i,()=>O(_)):h()?J(_):O(_)},matches(_,Q,G){return _===t&&Q===e&&G===n},destroy(){c=!0,y.clear(),typeof window<"u"&&window.removeEventListener("storage",A),g&&R(g);for(let _ of[...B])_()}}};var{setLoader:Xk,load:$x}=je({fallbackImport:()=>import("./history-view-NCFBI5GR.js")});var db=$x;var{setLoader:eP,load:zx,provide:tP,getSync:Ux}=je({fallbackImport:()=>import("./history-shell-QDQ44PSE.js")});var pb=zx;var Gl=Ux;var qx=null;function ub(){return qx}import{parse as sP,STR as iP,OBJ as aP}from"partial-json";function gb(t,e){let{config:n,message:o,onPropsUpdate:s}=e,i=go.get(t.component);if(!i){if(Bp.includes(t.component)){ql().catch(()=>{});let c=P("div","persona-w-full");return c.setAttribute("data-persona-artifact-pending","true"),c}return console.warn(`[ComponentMiddleware] Component "${t.component}" not found in registry. Falling back to default rendering.`),null}let l={message:o,config:n,updateProps:c=>{s&&s(c)}};try{return i(t.props,l)}catch(c){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,c),null}}function mb(t){if(typeof t.rawContent=="string"&&t.rawContent.length>0)return t.rawContent;if(typeof t.content=="string"){let e=t.content.trim();if(e.startsWith("{")||e.startsWith("["))return t.content}return null}function Kp(t){let e=mb(t);if(!e)return!1;try{let n=JSON.parse(e);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function fb(t){let e=mb(t);if(!e)return null;try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:e}}}catch{}return null}var jx=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function hb(t){let{onSubmit:e,onDismiss:n,title:o="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:i="Share your thoughts (optional)...",submitText:l="Submit",skipText:c="Skip",showComment:u=!0,ratingLabels:p=jx}=t,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-csat",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Customer satisfaction feedback");let y=null,h=document.createElement("div");h.className="persona-feedback-content";let C=document.createElement("div");C.className="persona-feedback-header";let E=document.createElement("h3");E.className="persona-feedback-title",E.textContent=o,C.appendChild(E);let A=document.createElement("p");A.className="persona-feedback-subtitle",A.textContent=s,C.appendChild(A),h.appendChild(C);let I=document.createElement("div");I.className="persona-feedback-rating persona-feedback-rating-csat",I.setAttribute("role","radiogroup"),I.setAttribute("aria-label","Satisfaction rating from 1 to 5");let L=[];for(let V=1;V<=5;V++){let J=document.createElement("button");J.type="button",J.className="persona-feedback-rating-btn persona-feedback-star-btn",J.setAttribute("role","radio"),J.setAttribute("aria-checked","false"),J.setAttribute("aria-label",`${V} star${V>1?"s":""}: ${p[V-1]}`),J.title=p[V-1],J.dataset.rating=String(V),J.innerHTML=`
|
|
26
|
+
`):""},Ip=(t,e)=>{t.style.backgroundColor=e.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",t.style.borderColor=e.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",t.style.color=e.codeBlockTextColor??"var(--persona-text, #171717)"},cx=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,s=o?.collapsedMode??$o.collapsedMode,i=n?.success===!1?n.error||"Tool failed":lx(t,o?.previewMaxLines??$o.previewMaxLines),l=n?qo(e,"tool")==="row"?`${n.status==="complete"?"Used":"Using"} ${n.name?.trim()||"tool"}`:Ym(n):"";if(!n)return{summary:l,previewText:i,isActive:!1};let c=n.status!=="complete",u=e?.toolCall??{},p=l;return s==="tool-name"?p=n.name?.trim()||l:s==="tool-preview"&&i&&(p=i),c&&u.activeTextTemplate?p=Ad(n,u.activeTextTemplate,p):!c&&u.completeTextTemplate&&(p=Ad(n,u.completeTextTemplate,p)),n.success===!1?p+=" \xB7 Failed":n.superseded&&(p+=" \xB7 Approved, ran again below"),{summary:p,previewText:i,isActive:c}},Hp=(t,e,n,o)=>{bl(t,e,{stateSet:n,previewKind:"tool",iconColor:Vy(o?.toolCall??{},e.classList.contains("persona-activity-row"))})},Rp=(t,e,n=new Set)=>{e=vl(e,"tool");let o=t.toolCall,s=e?.toolCall??{},i=ml("persona-tool-bubble",t.id);if(s.backgroundColor&&(i.style.backgroundColor=s.backgroundColor),s.borderColor&&(i.style.borderColor=s.borderColor),s.borderWidth&&(i.style.borderWidth=s.borderWidth),s.borderRadius&&(i.style.borderRadius=s.borderRadius),i.style.boxShadow=s.shadow!==void 0?s.shadow.trim()===""?"none":s.shadow:"var(--persona-tool-bubble-shadow)",!o)return mo(i,t,e,"tool");let l=e?.features?.toolCallDisplay??{},c=l.expandable??$o.expandable,u=c&&n.has(t.id),{summary:p,previewText:g,isActive:y}=cx(t,e),h=fl({expandable:c,expanded:u,bubbleType:"tool"});s.headerBackgroundColor&&(h.style.backgroundColor=s.headerBackgroundColor),s.headerPaddingX&&(h.style.paddingLeft=s.headerPaddingX,h.style.paddingRight=s.headerPaddingX),s.headerPaddingY&&(h.style.paddingTop=s.headerPaddingY,h.style.paddingBottom=s.headerPaddingY);let C=P("div","persona-flex persona-flex-col persona-text-left"),E=P("span","persona-text-xs persona-text-persona-primary");s.headerTextColor&&(E.style.color=s.headerTextColor);let A=String(o.startedAt??Date.now()),I=()=>{let v=P("span","");return v.setAttribute("data-tool-elapsed",A),v.textContent=Xa(o),v},L=s.renderCollapsedSummary?.({message:t,toolCall:o,defaultSummary:p,previewText:g,collapsedMode:l.collapsedMode??$o.collapsedMode,isActive:y,config:e??{},elapsed:Xa(o),createElapsedElement:I});typeof L=="string"&&L.trim()?(E.textContent=L,C.appendChild(E)):L instanceof HTMLElement?C.appendChild(L):(E.textContent=p,C.appendChild(E));let k=l.loadingAnimation??$o.loadingAnimation,R=s.activeTextTemplate,B=s.completeTextTemplate,O=y?R:B,V=L instanceof HTMLElement,J=(v,T)=>{E.textContent="";let S=o.name?.trim()||"tool",z=Za(v,S),W=0;for(let ee of z){let ne=ee.styles.length>0?(()=>{let he=P("span",ee.styles.map(ve=>`persona-tool-text-${ve}`).join(" "));return E.appendChild(he),he})():E;if(ee.isDuration&&y)ne.appendChild(I());else{let he=ee.isDuration?Xa(o):ee.text;T?W=ms(ne,he,W):ne.appendChild(document.createTextNode(he))}}};if(!V)if(y&&k!=="none"){let v=s.loadingAnimationDuration??2e3;if(E.setAttribute("data-preserve-animation","true"),k==="pulse")E.classList.add("persona-tool-loading-pulse"),E.style.setProperty("--persona-tool-anim-duration",`${v}ms`),O&&J(O,!1);else if(E.classList.add(`persona-tool-loading-${k}`),E.style.setProperty("--persona-tool-anim-duration",`${v}ms`),k==="shimmer-color"&&(s.loadingAnimationColor&&E.style.setProperty("--persona-tool-anim-color",s.loadingAnimationColor),s.loadingAnimationSecondaryColor&&E.style.setProperty("--persona-tool-anim-secondary-color",s.loadingAnimationSecondaryColor)),O)J(O,!0);else{let T=E.textContent||p;E.textContent="",ms(E,T,0)}}else O&&J(O,!1);let _=Vy(s,qo(e,"tool")==="row"),Q=fs(h,C,{expandable:c,expanded:u,iconColor:_,metaGap:!0}),G=hl({bubble:i,previewKind:"tool",expanded:u,isActive:y,previewText:g,activePreview:l.activePreview,activeMinHeight:l.activeMinHeight,renderPreview:()=>s.renderCollapsedPreview?.({message:t,toolCall:o,defaultPreview:g,isActive:y,config:e??{}})});if(!c)return i.append(h,G),mo(i,t,e,"tool");let w=P("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(w.style.display=u?"":"none",s.contentBackgroundColor&&(w.style.backgroundColor=s.contentBackgroundColor),s.contentTextColor&&(w.style.color=s.contentTextColor),s.contentPaddingX&&(w.style.paddingLeft=s.contentPaddingX,w.style.paddingRight=s.contentPaddingX),s.contentPaddingY&&(w.style.paddingTop=s.contentPaddingY,w.style.paddingBottom=s.contentPaddingY),e.future?.v5Defaults===!0)Fy(w,t,e);else{if(o.name){let v=P("div","persona-text-xs persona-text-persona-muted persona-italic");s.contentTextColor?v.style.color=s.contentTextColor:s.headerTextColor&&(v.style.color=s.headerTextColor),v.textContent=o.name,w.appendChild(v)}if(o.args!==void 0){let v=P("div","persona-space-y-1"),T=P("div","persona-text-xs persona-text-persona-muted");s.labelTextColor&&(T.style.color=s.labelTextColor),T.textContent="Arguments";let S=P("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",Ip(S,s),S.textContent=ls(o.args),v.append(T,S),w.appendChild(v)}if(o.chunks&&o.chunks.length){let v=P("div","persona-space-y-1"),T=P("div","persona-text-xs persona-text-persona-muted");s.labelTextColor&&(T.style.color=s.labelTextColor),T.textContent="Activity";let S=P("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",Ip(S,s),S.textContent=o.chunks.join(""),v.append(T,S),w.appendChild(v)}if(o.success===!1&&w.appendChild(Y("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){let v=P("div","persona-space-y-1"),T=P("div","persona-text-xs persona-text-persona-muted");s.labelTextColor&&(T.style.color=s.labelTextColor),T.textContent="Result";let S=P("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",Ip(S,s),S.textContent=ls(o.result),v.append(T,S),w.appendChild(v)}if(o.status==="complete"&&typeof o.duration=="number"){let v=P("div","persona-text-xs persona-text-persona-muted");s.contentTextColor&&(v.style.color=s.contentTextColor),v.textContent=`Duration: ${o.duration}ms`,w.appendChild(v)}}return yl({expanded:u,header:h,toggleIcon:Q,content:w,collapsedPreview:G,iconColor:_}),i.append(h,G,w),mo(i,t,e,"tool")};var{setLoader:Ck,load:dx,provide:wk,getSync:px}=je({fallbackImport:()=>import("./approval-ui-OBBI62ES.js")});var $y=dx;var zy=px;var{setLoader:Ak,load:ux}=je({fallbackImport:()=>import("./event-stream-view-FOIJHFQO.js")});var Wp=ux;var Bp=["PersonaArtifactCard","PersonaArtifactInline"],{setLoader:Lk,load:gx,provide:Ik,getSync:mx}=je({fallbackImport:()=>import("./artifacts-ui-NJGMM27I.js")}),xs=null,Ul=new Set,Uy=t=>{if(xs)return xs;xs=t,t.initArtifactsUi({componentRegistry:go});for(let o of Bp)go.has(o)||go.register(o,o==="PersonaArtifactCard"?t.PersonaArtifactCard:t.PersonaArtifactInline,{bubbleChrome:!1});let e=is();e?t.__provideMarkdownParsers(e):Ka(()=>{let o=is();o&&t.__provideMarkdownParsers(o)}),t.__setIconsExtraLoader(()=>_m());let n=[...Ul];Ul.clear();for(let o of n)try{o()}catch{}return t};var ql=()=>gx().then(Uy);var yo=()=>{if(xs)return xs;let t=mx();return t?Uy(t):null},Dp=t=>xs?()=>{}:(Ul.add(t),()=>{Ul.delete(t)});function zt(t){return t?.features?.artifacts?.enabled===!0}function qy(t,e){if(t.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),t.style.removeProperty("--persona-artifact-pane-border"),t.style.removeProperty("--persona-artifact-pane-border-left"),!zt(e))return;let n=e.features?.artifacts?.layout,o=n?.paneBorder?.trim(),s=n?.paneBorderLeft?.trim();o?(t.classList.add("persona-artifact-border-full"),t.style.setProperty("--persona-artifact-pane-border",o)):s&&(t.classList.add("persona-artifact-border-left"),t.style.setProperty("--persona-artifact-pane-border-left",s))}function fx(t){t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),t.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),t.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var jy=["panel","seamless","detached"];function Op(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&jy.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function _p(t){return!t||!zt(t)?!1:Op(t)==="detached"}function Oi(t,e){if(!zt(e)){t.style.removeProperty("--persona-artifact-split-gap"),t.style.removeProperty("--persona-artifact-pane-width"),t.style.removeProperty("--persona-artifact-pane-max-width"),t.style.removeProperty("--persona-artifact-pane-min-width"),t.style.removeProperty("--persona-artifact-drawer-width"),t.style.removeProperty("--persona-artifact-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),fx(t),qy(t,e);return}let n=e.features?.artifacts?.layout,o=Op(e)==="detached"?"var(--persona-panel-inset)":"0";t.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),t.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),t.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.drawerWidth?t.style.setProperty("--persona-artifact-drawer-width",n.drawerWidth):t.style.removeProperty("--persona-artifact-drawer-width"),n?.paneMinWidth?t.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):t.style.removeProperty("--persona-artifact-pane-min-width");let s=n?.paneBackground?.trim();s?t.style.setProperty("--persona-artifact-pane-bg",s):t.style.removeProperty("--persona-artifact-pane-bg");let i=n?.panePadding?.trim();i?t.style.setProperty("--persona-artifact-pane-padding",i):t.style.removeProperty("--persona-artifact-pane-padding");let l=[[n?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[n?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[n?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[n?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[c,u]of l){let p=c?.trim();p?t.style.setProperty(u,p):t.style.removeProperty(u)}qy(t,e)}function _i(t,e){for(let c of jy)t.classList.remove(`persona-artifact-appearance-${c}`);if(t.style.removeProperty("--persona-artifact-pane-radius"),t.style.removeProperty("--persona-artifact-pane-shadow"),t.style.removeProperty("--persona-artifact-chat-shadow"),!zt(e))return;let n=e.features?.artifacts?.layout,o=Op(e);t.classList.add(`persona-artifact-appearance-${o}`);let s=n?.paneBorderRadius?.trim();s&&t.style.setProperty("--persona-artifact-pane-radius",s);let i=n?.paneShadow?.trim();i&&t.style.setProperty("--persona-artifact-pane-shadow",i);let l=n?.chatShadow?.trim();l&&t.style.setProperty("--persona-artifact-chat-shadow",l)}function Ky(t,e){return!e||!zt(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var hx=new Set(["__proto__","prototype","constructor"]),yx=new Set(["collapsed","card","panel","inline"]),Gy=new Set(["markdown","component"]),bx=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,Lr=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Kl=t=>!hx.has(t),Fp=t=>typeof t=="string"&&yx.has(t),Ir=t=>Object.keys(t).length>0;function Gn(t,e,n,o){t.push({path:e,code:n,message:o})}var vx="Ignored because this key is not part of the persisted preference schema.",jl="Ignored an unsupported value.",Cx="Expected collapsed, panel, or inline.",wx='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',Yy={kind:"mode",message:jl},As={kind:"string",message:"Expected a CSS length string."},bo={kind:"boolean"},Sx={paneWidth:As,paneMaxWidth:As,paneMinWidth:As,expandedPanelWidth:As,resizableMinWidth:As,resizableMaxWidth:As,expandLauncherPanelWhenOpen:bo,resizable:bo},xx={kind:"object",message:"Expected a preference object.",children:{showToolCalls:bo,showReasoning:bo,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:jl},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:jl},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:jl},expandable:bo,grouped:bo}},reasoningDisplay:{kind:"object",children:{expandable:bo,activePreview:bo}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:Yy,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:Yy,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Gy,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Gy}}},filePreview:{kind:"object",children:{enabled:bo}},layout:{kind:"object",children:Sx}}}}};function Qy(t,e,n,o){if(t!==void 0)switch(e.kind){case"boolean":return typeof t=="boolean"?t:Gn(o,n,"invalid_type","Expected a boolean.");case"string":return typeof t=="string"?t:Gn(o,n,"invalid_type",e.message);case"enum":return typeof t=="string"&&e.values.has(t)?t:Gn(o,n,"invalid_value",e.message);case"mode":return Fp(t)?Qa(t):Gn(o,n,"invalid_value",e.message);case"modeMap":{if(!Lr(t))return Gn(o,n,"invalid_type","Expected an object.");let s=e.keys==="mediaType"?void 0:e.keys,i={};for(let[l,c]of Object.entries(t)){let u=s?l:jm(l);Kl(l)&&(s?s.has(l):bx.test(u))?Fp(c)?i[u]=Qa(c):Gn(o,`${n}.${l}`,"invalid_value",Cx):Gn(o,`${n}.${l}`,s?"unknown_key":"invalid_value",s?"Ignored an unsupported selector.":wx)}return Ir(i)?i:void 0}case"object":{if(e.bareMode&&Fp(t))return Qa(t);if(!Lr(t))return Gn(o,n,"invalid_type",e.message??"Expected an object.");let s=Object.keys(e.children),i=c=>n?`${n}.${c}`:c;for(let c of Object.keys(t))(!Kl(c)||!s.includes(c))&&Gn(o,i(c),"unknown_key",vx);let l={};for(let c of s){let u=e.children[c],p=Qy(t[c],u,i(c),o);if(u.deprecated&&t[c]!==void 0&&Gn(o,i(c),"deprecated_key",u.deprecated),p===void 0)continue;let g=u.alias??c,y=l[g];l[g]=Lr(y)&&Lr(p)?{...y,...p}:p}return Ir(l)?l:void 0}}}function Ax(t){let e=[];return{preferences:(t===null?void 0:Qy(t,xx,"",e))??{},issues:e}}function Ms(t){if(Array.isArray(t))return t.map(Ms);if(!Lr(t))return t;let e={};for(let[n,o]of Object.entries(t))Kl(n)&&o!==void 0&&(e[n]=Ms(o));return e}function Xy(t,e){let n=Ms(t);for(let[o,s]of Object.entries(e)){if(!Kl(o)||s===void 0)continue;let i=n[o];n[o]=Lr(i)&&Lr(s)?Xy(i,s):Ms(s)}return n}function Mx(t){let e={},n;for(let s of t){let i=Ax(s).preferences;n=Jy(n,i.artifacts?.display),e=Xy(e,i)}let o=e;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function Ex(t,e){if(e===void 0)return t===void 0?void 0:Ms(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,s={...n.byMediaType,...e.byMediaType},i={...o?{default:o}:{},...Ir(s)?{byMediaType:s}:{}};return Ir(i)?i:void 0}function Jy(t,e){if(e===void 0)return t===void 0?void 0:Ms(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,s={...n.byType,...n.byKind,...e.byType,...e.byKind},i=Ex(n.files,e.files),l={...o?{default:o}:{},...Ir(s)?{byKind:s}:{},...i!==void 0?{files:i}:{}};return Ir(l)?l:void 0}function Tx(t={},e){let n=Mx(e),o={...t};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...t.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...t.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let s=t.artifacts??{},i={...s};if(n.artifacts.display!==void 0){let l=Jy(s.display,n.artifacts.display);l!==void 0&&(i.display=l)}n.artifacts.filePreview&&(i.filePreview={...s.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(i.layout={...s.layout,...n.artifacts.layout}),o.artifacts=i}return o}function Np(t){let e=t.preferences;return!e||!Ir(e)?t:{...t,features:Tx(t.features??{},[e])}}function kx(t,e){if(!t?.trim())return e;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return n?Math.max(0,Number(n[1])):e}function Px(t){if(!t?.trim())return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return e?Math.max(0,Number(e[1])):null}function Lx(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function Ix(t,e,n,o){let s=t-o-2*e-n;return Math.max(0,s)}function Vp(t,e){let o=(e.getComputedStyle(t).gap||"0px").trim().split(/\s+/)[0]??"0px",s=/^([\d.]+)px$/i.exec(o);if(s)return Number(s[1]);let i=/^([\d.]+)/.exec(o);return i?Number(i[1]):8}function Zy(t,e,n,o,s,i,l=200){let c=kx(s,200),u=Ix(e,n,o,l);u=Math.max(c,u);let p=Px(i);return p!==null&&(u=Math.min(u,p)),Lx(t,c,u)}var{setLoader:_k,load:Hx,provide:Fk,getSync:Rx}=je({fallbackImport:()=>import("./forms-ui-PJMI3HQR.js")});var eb=Hx;var tb=Rx;var $p=class{#e=new Map;register(e){this.#e.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.#e.set(e.id,e),e.onRegister?.()}unregister(e){let n=this.#e.get(e);n&&(n.onUnregister?.(),this.#e.delete(e))}getAll(){return Array.from(this.#e.values()).sort((e,n)=>(n.priority??0)-(e.priority??0))}getForInstance(e){let n=this.getAll();if(!e||e.length===0)return n;let o=new Set(e.map(i=>i.id));return[...n.filter(i=>!o.has(i.id)),...e].sort((i,l)=>(l.priority??0)-(i.priority??0))}clear(){this.#e.forEach(e=>e.onUnregister?.()),this.#e.clear()}},zp=new $p;var nb=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Wx=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),ob=(t,e,n)=>{if(!nb(t)||!nb(e)||Wx.has(n))return e;let o={...t};for(let s of Object.keys(e)){if(e[s]===void 0){delete o[s];continue}let i=n?`${n}.${s}`:s;o[s]=ob(t[s],e[s],i)}return o};function rb(t,e){let n=Pm(qa),o=Im(t,e,n),s=Lm(Hm(ob(t,e,""),n,o),o);return Wm(ja(s),Bm(t,e))}var sb=()=>{let t=new Map,e=(s,i)=>(t.has(s)||t.set(s,new Set),t.get(s).add(i),()=>n(s,i)),n=(s,i)=>{t.get(s)?.delete(i)};return{on:e,off:n,emit:(s,i)=>{t.get(s)?.forEach(l=>{try{l(i)}catch(c){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",c)}})}}};var Bx=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},Dx=t=>{let e=t.trim(),n=e.indexOf("{");if(n===-1)return null;let o=0;for(let s=n;s<e.length;s+=1){let i=e[s];if(i==="{"&&(o+=1),i==="}"&&(o-=1,o===0))return e.slice(n,s+1)}return null},qp=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=Bx(t),n=Dx(e);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:s,...i}=o;return{type:String(s),payload:i,raw:o}}catch{return null}},Up=t=>typeof t=="string"?t:t==null?"":String(t),Fi={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:Up(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=Up(n.element);if(o&&e.document?.querySelector){let s=e.document.querySelector(o);s?setTimeout(()=>{s.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Up(n.text)}}},ib=t=>Array.isArray(t)?t.map(e=>String(e)):[],jp=t=>{let e=new Set(ib(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(ib(t.getSessionMetadata().processedActionMessageIds))},o=()=>{let i=Array.from(e);t.updateSessionMetadata(l=>({...l,processedActionMessageIds:i}))};return{process:i=>{if(i.streaming||i.message.role!=="assistant"||!i.text||e.has(i.message.id))return null;let l=typeof i.raw=="string"&&i.raw||typeof i.message.rawContent=="string"&&i.message.rawContent||typeof i.text=="string"&&i.text||null;!l&&typeof i.text=="string"&&i.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let c=l?t.parsers.reduce((p,g)=>p||g?.({text:l,message:i.message})||null,null):null;if(!c)return null;e.add(i.message.id),o();let u={action:c,message:i.message};t.emit("action:detected",u);for(let p of t.handlers)if(p)try{let g=()=>{t.emit("action:resubmit",u)},y=p(c,{message:i.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:g});if(!y)continue;if(y.handled){let h=y.persistMessage!==!1;return{text:y.displayText!==void 0?y.displayText:"",persist:h,resubmit:y.resubmit}}}catch(g){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",g)}return{text:"",persist:!0}},syncFromMetadata:n}};var Ox=t=>{if(!t)return null;try{return JSON.parse(t)}catch(e){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},_x=t=>t.map(e=>({...e,streaming:!1})),Fx=t=>t.map(e=>({...e,status:"complete"})),ab=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?Ox(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let s={...n,messages:n.messages?_x(n.messages):void 0,artifacts:n.artifacts?Fx(n.artifacts):void 0};o.setItem(t,JSON.stringify(s))}catch(s){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let n=e();if(n)try{n.removeItem(t)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var Nx=t=>{let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e.toString(16).padStart(8,"0")},lb=async t=>{let e=globalThis.crypto?.subtle;if(e)try{let n=await e.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}catch{}return Nx(t)},Vx=async(t,e)=>{let n=await lb(t);return{storageKey:`${e}visitor:${n}`,leaseKey:`${e}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await lb(`${t}\0${e}`)}`}};var cb=(t,e,n)=>{let o="",s="",i="",l=!1,c=!1,u=0,p=null,g=null,y=new Set,h=()=>{if(n||l)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return l=!0,null}},C=()=>{let _=h();if(!_)return p;try{return _.getItem(o)}catch{return l=!0,p}},E=(_,Q)=>{if(c||_===p)return;let G=p;p=_,u+=1;let w={previousToken:G,token:_,source:Q,revision:u};for(let v of y)v(w)},A=_=>{c||_.key!==null&&_.key!==o||E(_.key===null?null:_.newValue??null,"external")},I=(async()=>{let _=await Vx(t,e);o=_.storageKey,s=_.leaseKey,i=_.lockName,p=C(),!n&&typeof window<"u"&&window.addEventListener("storage",A)})(),L=_=>new Promise(Q=>setTimeout(Q,_)),k=()=>{let _=h();if(!_)return null;try{let Q=_.getItem(s);if(!Q)return null;let G=JSON.parse(Q);return typeof G?.expiresAt=="number"&&typeof G?.ownerNonce=="string"?G:null}catch{return null}},R=_=>{let Q=h();if(Q)try{k()?.ownerNonce===_&&Q.removeItem(s)}catch{}},B=new Set,O=_=>c?Promise.reject(new Error("Visitor store destroyed before its first init could start")):_(),V=_=>new Promise(Q=>{let G=setTimeout(w,_);function w(){clearTimeout(G),B.delete(w),window.removeEventListener("storage",v),Q()}function v(T){(T.key===null||T.key===s)&&w()}B.add(w),window.addEventListener("storage",v)}),J=async _=>{let Q=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,G=Date.now()+15e3;for(;!c&&Date.now()<G;){let w=h();if(!w)break;let v=Date.now(),T=k();if(T&&T.expiresAt>v&&T.ownerNonce!==Q){await V(Math.min(T.expiresAt-v,500));continue}try{w.setItem(s,JSON.stringify({ownerNonce:Q,expiresAt:v+1e4}))}catch{l=!0;break}if(await L(20+Math.random()*40),k()?.ownerNonce!==Q){await V(500);continue}g=Q;try{return await O(_)}finally{g=null,R(Q)}}return O(_)};return{ready:I,async get(){return await I,E(C(),"external"),p},async set(_){await I;let Q=h();if(Q)try{Q.setItem(o,_)}catch{l=!0}E(_,"local")},async clear(){await I;let _=h();if(_)try{_.removeItem(o)}catch{l=!0}E(null,"local")},revision(){return u},subscribe(_){return y.add(_),()=>{y.delete(_)}},async withFirstInitLock(_){await I;let Q=globalThis.navigator?.locks;return Q?.request?Q.request(i,()=>O(_)):h()?J(_):O(_)},matches(_,Q,G){return _===t&&Q===e&&G===n},destroy(){c=!0,y.clear(),typeof window<"u"&&window.removeEventListener("storage",A),g&&R(g);for(let _ of[...B])_()}}};var{setLoader:Xk,load:$x}=je({fallbackImport:()=>import("./history-view-NCFBI5GR.js")});var db=$x;var{setLoader:eP,load:zx,provide:tP,getSync:Ux}=je({fallbackImport:()=>import("./history-shell-QDQ44PSE.js")});var pb=zx;var Gl=Ux;var qx=null;function ub(){return qx}import{parse as sP,STR as iP,OBJ as aP}from"partial-json";function gb(t,e){let{config:n,message:o,onPropsUpdate:s}=e,i=go.get(t.component);if(!i){if(Bp.includes(t.component)){ql().catch(()=>{});let c=P("div","persona-w-full");return c.setAttribute("data-persona-artifact-pending","true"),c}return console.warn(`[ComponentMiddleware] Component "${t.component}" not found in registry. Falling back to default rendering.`),null}let l={message:o,config:n,updateProps:c=>{s&&s(c)}};try{return i(t.props,l)}catch(c){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,c),null}}function mb(t){if(typeof t.rawContent=="string"&&t.rawContent.length>0)return t.rawContent;if(typeof t.content=="string"){let e=t.content.trim();if(e.startsWith("{")||e.startsWith("["))return t.content}return null}function Kp(t){let e=mb(t);if(!e)return!1;try{let n=JSON.parse(e);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function fb(t){let e=mb(t);if(!e)return null;try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:e}}}catch{}return null}var jx=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function hb(t){let{onSubmit:e,onDismiss:n,title:o="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:i="Share your thoughts (optional)...",submitText:l="Submit",skipText:c="Skip",showComment:u=!0,ratingLabels:p=jx}=t,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-csat",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Customer satisfaction feedback");let y=null,h=document.createElement("div");h.className="persona-feedback-content";let C=document.createElement("div");C.className="persona-feedback-header";let E=document.createElement("h3");E.className="persona-feedback-title",E.textContent=o,C.appendChild(E);let A=document.createElement("p");A.className="persona-feedback-subtitle",A.textContent=s,C.appendChild(A),h.appendChild(C);let I=document.createElement("div");I.className="persona-feedback-rating persona-feedback-rating-csat",I.setAttribute("role","radiogroup"),I.setAttribute("aria-label","Satisfaction rating from 1 to 5");let L=[];for(let V=1;V<=5;V++){let J=document.createElement("button");J.type="button",J.className="persona-feedback-rating-btn persona-feedback-star-btn",J.setAttribute("role","radio"),J.setAttribute("aria-checked","false"),J.setAttribute("aria-label",`${V} star${V>1?"s":""}: ${p[V-1]}`),J.title=p[V-1],J.dataset.rating=String(V),J.innerHTML=`
|
|
27
27
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
28
28
|
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
|
|
29
29
|
</svg>
|
package/dist/theme-editor.d.cts
CHANGED
|
@@ -3214,9 +3214,8 @@ type WebMcpConfirmInfo = {
|
|
|
3214
3214
|
};
|
|
3215
3215
|
/**
|
|
3216
3216
|
* Why the confirm was requested. Currently always `'gate'`: the default
|
|
3217
|
-
* confirm-by-default gate that fires before every `webmcp:*` call.
|
|
3218
|
-
*
|
|
3219
|
-
* internally, so Persona no longer surfaces a nested in-tool confirm.)
|
|
3217
|
+
* confirm-by-default gate that fires before every `webmcp:*` call. Tool
|
|
3218
|
+
* callbacks on v6 receive an AbortSignal, not a nested confirmation API.
|
|
3220
3219
|
*/
|
|
3221
3220
|
reason: 'gate';
|
|
3222
3221
|
};
|
|
@@ -9292,8 +9291,11 @@ type AgentWidgetConfig = {
|
|
|
9292
9291
|
/**
|
|
9293
9292
|
* WebMCP: consume page-registered tools (`document.modelContext.registerTool`).
|
|
9294
9293
|
* When `enabled`, the widget installs `@mcp-b/webmcp-polyfill`, snapshots the
|
|
9295
|
-
* registry on every dispatch, ships it as `clientTools[]`,
|
|
9296
|
-
* returned `webmcp:*`
|
|
9294
|
+
* current document's registry on every dispatch, ships it as `clientTools[]`,
|
|
9295
|
+
* and executes returned `webmcp:*` calls with confirm-by-default gating.
|
|
9296
|
+
* Supports host-installed v5 JSON-string and v6 object-input contracts.
|
|
9297
|
+
* The automatic fallback stays on v5 to preserve existing browser support
|
|
9298
|
+
* and callback-result behavior.
|
|
9297
9299
|
*
|
|
9298
9300
|
* Server-side policy on the chat surface is the source of truth: these
|
|
9299
9301
|
* fields layer on top.
|
|
@@ -10476,7 +10478,7 @@ declare function tokenRefDisplayName(path: string): string;
|
|
|
10476
10478
|
*
|
|
10477
10479
|
* We deliberately keep our own small WebMCP types rather than depending on
|
|
10478
10480
|
* `@mcp-b/webmcp-types`, so the tool definitions are transport-agnostic and the
|
|
10479
|
-
*
|
|
10481
|
+
* tool definitions do not depend on the polyfill's types. These mirror the WebMCP draft
|
|
10480
10482
|
* (`registerTool(tool, { signal })`) and the MCP tool-result envelope that
|
|
10481
10483
|
* `@mcp-b/webmcp-polyfill` expects `execute` to return.
|
|
10482
10484
|
*/
|
package/dist/theme-editor.d.ts
CHANGED
|
@@ -3214,9 +3214,8 @@ type WebMcpConfirmInfo = {
|
|
|
3214
3214
|
};
|
|
3215
3215
|
/**
|
|
3216
3216
|
* Why the confirm was requested. Currently always `'gate'`: the default
|
|
3217
|
-
* confirm-by-default gate that fires before every `webmcp:*` call.
|
|
3218
|
-
*
|
|
3219
|
-
* internally, so Persona no longer surfaces a nested in-tool confirm.)
|
|
3217
|
+
* confirm-by-default gate that fires before every `webmcp:*` call. Tool
|
|
3218
|
+
* callbacks on v6 receive an AbortSignal, not a nested confirmation API.
|
|
3220
3219
|
*/
|
|
3221
3220
|
reason: 'gate';
|
|
3222
3221
|
};
|
|
@@ -9292,8 +9291,11 @@ type AgentWidgetConfig = {
|
|
|
9292
9291
|
/**
|
|
9293
9292
|
* WebMCP: consume page-registered tools (`document.modelContext.registerTool`).
|
|
9294
9293
|
* When `enabled`, the widget installs `@mcp-b/webmcp-polyfill`, snapshots the
|
|
9295
|
-
* registry on every dispatch, ships it as `clientTools[]`,
|
|
9296
|
-
* returned `webmcp:*`
|
|
9294
|
+
* current document's registry on every dispatch, ships it as `clientTools[]`,
|
|
9295
|
+
* and executes returned `webmcp:*` calls with confirm-by-default gating.
|
|
9296
|
+
* Supports host-installed v5 JSON-string and v6 object-input contracts.
|
|
9297
|
+
* The automatic fallback stays on v5 to preserve existing browser support
|
|
9298
|
+
* and callback-result behavior.
|
|
9297
9299
|
*
|
|
9298
9300
|
* Server-side policy on the chat surface is the source of truth: these
|
|
9299
9301
|
* fields layer on top.
|
|
@@ -10476,7 +10478,7 @@ declare function tokenRefDisplayName(path: string): string;
|
|
|
10476
10478
|
*
|
|
10477
10479
|
* We deliberately keep our own small WebMCP types rather than depending on
|
|
10478
10480
|
* `@mcp-b/webmcp-types`, so the tool definitions are transport-agnostic and the
|
|
10479
|
-
*
|
|
10481
|
+
* tool definitions do not depend on the polyfill's types. These mirror the WebMCP draft
|
|
10480
10482
|
* (`registerTool(tool, { signal })`) and the MCP tool-result envelope that
|
|
10481
10483
|
* `@mcp-b/webmcp-polyfill` expects `execute` to return.
|
|
10482
10484
|
*/
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as ae}from"./chunk-6V3MNEKB.js";import{a as oe}from"./chunk-
|
|
1
|
+
import{a as ae}from"./chunk-6V3MNEKB.js";import{a as oe}from"./chunk-FNXK3VTC.js";var K=16e3,Me=24e3,Te=4096,_e=K*2*8,Ee=4,Ie=1380533830,Ve=3e4,Pe=1e3,Re=5e3,Le=3e4,Ne=3e4,Oe=6e5,De="full-duplex-v1",Ue=300,xe=2e3,$e=2e3,Be="runtype-browser-v1",We=54e4,He="You're talking to an AI assistant. Voice is processed by OpenAI.",qe=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."]]),ce=["provider_error","server_restart"],O="Voice connection lost.",je=8e3,Fe=4e3,Xe=12,le=2e3;function ze(i,e){let t="Conversation so far:",s=e.slice(0,Fe).trim(),n=je-(s?s.length+2:0)-t.length,r=[];for(let l of i.slice(-Xe).reverse()){let a=l.content.replace(/\s+/g," ").trim();if(!a)continue;a.length>le&&(a=`${a.slice(0,le-1)}\u2026`);let o=`${l.role==="user"?"User":"Assistant"}: ${a}`;if(o.length+1>n)break;n-=o.length+1,r.unshift(o)}let d=r.length>0?[`${t}
|
|
2
2
|
${r.join(`
|
|
3
3
|
`)}`]:[];return s&&d.push(s),d.join(`
|
|
4
4
|
|
package/dist/voice-runtime.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var J=Object.defineProperty;var Pe=Object.getOwnPropertyDescriptor;var Ve=Object.getOwnPropertyNames;var Re=Object.prototype.hasOwnProperty;var je=(n,e)=>{for(var t in e)J(n,t,{get:e[t],enumerable:!0})},Le=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ve(e))!Re.call(n,i)&&i!==t&&J(n,i,{get:()=>e[i],enumerable:!(s=Pe(e,i))||s.enumerable});return n};var Ne=n=>Le(J({},"__esModule",{value:!0}),n);var St={};je(St,{BrowserVoiceProvider:()=>_,KeyedVoiceTranscript:()=>U,RuntypeVoiceProvider:()=>E,createBestAvailableVoiceProvider:()=>Q,createMicStateStyles:()=>Ce,createVoiceProvider:()=>R,createVoiceSessionBridge:()=>Ae,isVoiceSupported:()=>ge,wireSessionVoice:()=>ke});module.exports=Ne(St);var N=class{#e=null;#i=0;#r=[];#n=[];#c=[];#l=!1;#m=!1;#y=0;#o=!1;#p=!1;#d;#t=[];#b=0;#_=!1;#a;#u;#g;#h=null;constructor(e=24e3,t={}){this.#u=e;let s=Math.max(0,t.prebufferMs??0);this.#g=Math.round(e*s/1e3),this.#d=this.#g>0}#w(){if(!this.#e){let t=typeof window<"u"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let s=t.AudioContext||t.webkitAudioContext;this.#e=new s({sampleRate:this.#u})}let e=this.#e;return e.state==="suspended"&&!this.#p&&e.resume(),e}enqueue(e){if(e.length===0)return;let t=e;if(this.#h){let i=new Uint8Array(this.#h.length+e.length);i.set(this.#h),i.set(e,this.#h.length),t=i,this.#h=null}if(t.length%2!==0&&(this.#h=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let s=this.#f(t);s.length!==0&&(this.#d?(this.#t.push(s),this.#b+=s.length,clearTimeout(this.#a),this.#b>=this.#g?this.#S():this.#_&&(this.#a=setTimeout(()=>this.#S(),this.#g/this.#u*1e3))):this.#A(s))}markStreamEnd(){this.#t.length>0&&this.#S(),this.#m=!0,this.#k()}flush(){for(let e of this.#r){e.onended=null;try{e.stop(),e.disconnect()}catch{}}this.#r=[],this.#y=0,this.#i=0,this.#l=!1,this.#m=!1,this.#n=[],this.#c=[],this.#h=null,this.#t=[],this.#b=0,this.#d=this.#g>0,this.#o=!1,clearTimeout(this.#a)}setContinuousMode(e){this.#_=e}isPlaying(){return this.#l}onFinished(e){this.#n.push(e)}onStarted(e){this.#c.push(e)}pause(){this.#p=!0,this.#e&&this.#e.state==="running"&&this.#e.suspend()}resume(){this.#p=!1,this.#e&&this.#e.state==="suspended"&&this.#e.resume()}async destroy(){this.flush(),this.#e&&(await this.#e.close(),this.#e=null)}#S(){this.#d=!1;let e=this.#t;this.#t=[],this.#b=0;for(let t of e)this.#A(t)}#A(e){if(e.length===0)return;let t=this.#w(),s=t.createBuffer(1,e.length,this.#u);s.getChannelData(0).set(e);let i=t.createBufferSource();i.buffer=s,i.connect(t.destination);let r=t.currentTime;if(this.#i===0?this.#i=r:this.#i<r&&(this.#i=r,this.#g>0&&(this.#d=!0)),i.start(this.#i),this.#i+=s.duration,this.#r.push(i),this.#y++,this.#l=!0,!this.#o){this.#o=!0;let l=this.#c.slice();this.#c=[];for(let d of l)d()}i.onended=()=>{let l=this.#r.indexOf(i);l!==-1&&(this.#r.splice(l,1),this.#y--,this.#k())}}#k(){if(this.#m&&this.#y<=0&&this.#t.length===0){this.#l=!1,this.#m=!1;let e=this.#n.slice();this.#n=[];for(let t of e)t()}}#f(e){let t=Math.floor(e.length/2),s=new Float32Array(t),i=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let r=0;r<t;r++){let l=i.getInt16(r*2,!0);s[r]=l/32768}return s}};var le="4.28.
|
|
1
|
+
"use strict";var J=Object.defineProperty;var Pe=Object.getOwnPropertyDescriptor;var Ve=Object.getOwnPropertyNames;var Re=Object.prototype.hasOwnProperty;var je=(n,e)=>{for(var t in e)J(n,t,{get:e[t],enumerable:!0})},Le=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Ve(e))!Re.call(n,i)&&i!==t&&J(n,i,{get:()=>e[i],enumerable:!(s=Pe(e,i))||s.enumerable});return n};var Ne=n=>Le(J({},"__esModule",{value:!0}),n);var St={};je(St,{BrowserVoiceProvider:()=>_,KeyedVoiceTranscript:()=>U,RuntypeVoiceProvider:()=>E,createBestAvailableVoiceProvider:()=>Q,createMicStateStyles:()=>Ce,createVoiceProvider:()=>R,createVoiceSessionBridge:()=>Ae,isVoiceSupported:()=>ge,wireSessionVoice:()=>ke});module.exports=Ne(St);var N=class{#e=null;#i=0;#r=[];#n=[];#c=[];#l=!1;#m=!1;#y=0;#o=!1;#p=!1;#d;#t=[];#b=0;#_=!1;#a;#u;#g;#h=null;constructor(e=24e3,t={}){this.#u=e;let s=Math.max(0,t.prebufferMs??0);this.#g=Math.round(e*s/1e3),this.#d=this.#g>0}#w(){if(!this.#e){let t=typeof window<"u"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let s=t.AudioContext||t.webkitAudioContext;this.#e=new s({sampleRate:this.#u})}let e=this.#e;return e.state==="suspended"&&!this.#p&&e.resume(),e}enqueue(e){if(e.length===0)return;let t=e;if(this.#h){let i=new Uint8Array(this.#h.length+e.length);i.set(this.#h),i.set(e,this.#h.length),t=i,this.#h=null}if(t.length%2!==0&&(this.#h=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let s=this.#f(t);s.length!==0&&(this.#d?(this.#t.push(s),this.#b+=s.length,clearTimeout(this.#a),this.#b>=this.#g?this.#S():this.#_&&(this.#a=setTimeout(()=>this.#S(),this.#g/this.#u*1e3))):this.#A(s))}markStreamEnd(){this.#t.length>0&&this.#S(),this.#m=!0,this.#k()}flush(){for(let e of this.#r){e.onended=null;try{e.stop(),e.disconnect()}catch{}}this.#r=[],this.#y=0,this.#i=0,this.#l=!1,this.#m=!1,this.#n=[],this.#c=[],this.#h=null,this.#t=[],this.#b=0,this.#d=this.#g>0,this.#o=!1,clearTimeout(this.#a)}setContinuousMode(e){this.#_=e}isPlaying(){return this.#l}onFinished(e){this.#n.push(e)}onStarted(e){this.#c.push(e)}pause(){this.#p=!0,this.#e&&this.#e.state==="running"&&this.#e.suspend()}resume(){this.#p=!1,this.#e&&this.#e.state==="suspended"&&this.#e.resume()}async destroy(){this.flush(),this.#e&&(await this.#e.close(),this.#e=null)}#S(){this.#d=!1;let e=this.#t;this.#t=[],this.#b=0;for(let t of e)this.#A(t)}#A(e){if(e.length===0)return;let t=this.#w(),s=t.createBuffer(1,e.length,this.#u);s.getChannelData(0).set(e);let i=t.createBufferSource();i.buffer=s,i.connect(t.destination);let r=t.currentTime;if(this.#i===0?this.#i=r:this.#i<r&&(this.#i=r,this.#g>0&&(this.#d=!0)),i.start(this.#i),this.#i+=s.duration,this.#r.push(i),this.#y++,this.#l=!0,!this.#o){this.#o=!0;let l=this.#c.slice();this.#c=[];for(let d of l)d()}i.onended=()=>{let l=this.#r.indexOf(i);l!==-1&&(this.#r.splice(l,1),this.#y--,this.#k())}}#k(){if(this.#m&&this.#y<=0&&this.#t.length===0){this.#l=!1,this.#m=!1;let e=this.#n.slice();this.#n=[];for(let t of e)t()}}#f(e){let t=Math.floor(e.length/2),s=new Float32Array(t),i=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let r=0;r<t;r++){let l=i.getInt16(r*2,!0);s[r]=l/32768}return s}};var le="4.28.1";var de=le;var Z=16e3,Ue=24e3,De=4096,Be=Z*2*8,qe=4,$e=1380533830,We=3e4,He=1e3,Fe=5e3,ze=3e4,Xe=3e4,Ge=6e5,Ke="full-duplex-v1",Ye=300,Je=2e3,Ze=2e3,Qe="runtype-browser-v1",et=54e4,tt="You're talking to an AI assistant. Voice is processed by OpenAI.",st=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."]]),ue=["provider_error","server_restart"],O="Voice connection lost.",it=8e3,nt=4e3,rt=12,pe=2e3;function ot(n,e){let t="Conversation so far:",s=e.slice(0,nt).trim(),i=it-(s?s.length+2:0)-t.length,r=[];for(let d of n.slice(-rt).reverse()){let a=d.content.replace(/\s+/g," ").trim();if(!a)continue;a.length>pe&&(a=`${a.slice(0,pe-1)}\u2026`);let o=`${d.role==="user"?"User":"Assistant"}: ${a}`;if(o.length+1>i)break;i-=o.length+1,r.unshift(o)}let l=r.length>0?[`${t}
|
|
2
2
|
${r.join(`
|
|
3
3
|
`)}`]:[];return s&&l.push(s),l.join(`
|
|
4
4
|
|