@runtypelabs/persona 4.32.1 → 4.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/activity-ui.d.cts +3 -3
- package/dist/activity-ui.d.ts +3 -3
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/approval-ui.d.cts +2 -2
- package/dist/approval-ui.d.ts +2 -2
- package/dist/artifacts-ui.d.cts +3 -3
- package/dist/artifacts-ui.d.ts +3 -3
- package/dist/background-runtime.d.cts +1 -1
- package/dist/background-runtime.d.ts +1 -1
- package/dist/{chunk-BbXc58OA.js → chunk-6CUrH_jm.js} +1 -1
- package/dist/{chunk-B_H0l3u2.js → chunk-BRM3bHcJ.js} +1 -1
- package/dist/chunk-CEPM3FOp.js +1 -0
- package/dist/{chunk-CumoXK3u.js → chunk-CXQJG7pb.js} +1 -1
- package/dist/{chunk-UWMfWW2a.js → chunk-D1G8tgYc.js} +1 -1
- package/dist/{chunk-BpjtKnGI.js → chunk-D6U0E82p.js} +1 -1
- package/dist/{chunk-2FnmZ9AA.js → chunk-DOZmcve8.js} +1 -1
- package/dist/chunk-DVgzoVCB.js +1 -0
- package/dist/{chunk-C9uOhfk5.js → chunk-DW7Vg_l2.js} +1 -1
- package/dist/{chunk-B3l7TOOv.js → chunk-DbGLjU2P.js} +1 -1
- package/dist/{chunk-DTGvDx8o.js → chunk-Dj2a9f9w.js} +1 -1
- package/dist/{chunk-DgZZqy14.js → chunk-d54BJdKd.js} +1 -1
- package/dist/chunk-dLJWKfOb.js +1 -0
- package/dist/{chunk-DNdeIFJ6.js → chunk-gu34lr-P.js} +1 -1
- package/dist/chunk-i4qGOJAL.js +1 -0
- package/dist/{chunk-DVZ8ri1z.js → chunk-ql5N2I_t.js} +1 -1
- package/dist/client-dispatch.js +1 -1
- package/dist/client-history.js +1 -1
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/composer-actions-runtime.d.cts +2 -2
- package/dist/composer-actions-runtime.d.ts +2 -2
- package/dist/{composer-input-dwg_o9Z-.d.cts → composer-input-DnqGCXZz.d.cts} +1 -1
- package/dist/{composer-input-dwg_o9Z-.d.ts → composer-input-DnqGCXZz.d.ts} +1 -1
- package/dist/{composer-store-Dw7Zbqxr.d.cts → composer-store-6Iwy6WLI.d.cts} +1 -1
- package/dist/{composer-store-Dw7Zbqxr.d.ts → composer-store-6Iwy6WLI.d.ts} +1 -1
- package/dist/{context-mention-manager-D2p0-JH-.d.cts → context-mention-manager-B-rHF98n.d.cts} +2 -2
- package/dist/{context-mention-manager-D2p0-JH-.d.ts → context-mention-manager-B-rHF98n.d.ts} +2 -2
- package/dist/context-mentions-inline.d.cts +2 -2
- package/dist/context-mentions-inline.d.ts +2 -2
- package/dist/context-mentions.d.cts +3 -3
- package/dist/context-mentions.d.ts +3 -3
- package/dist/{defaults-CjX0kKzb.d.ts → defaults-BuOjqUAG.d.cts} +2 -1
- package/dist/{defaults-CjX0kKzb.d.cts → defaults-BuOjqUAG.d.ts} +2 -1
- package/dist/dictation-runtime.d.cts +2 -2
- package/dist/dictation-runtime.d.ts +2 -2
- package/dist/event-stream-view.d.cts +1 -1
- package/dist/event-stream-view.d.ts +1 -1
- package/dist/{fallback-speech-engine-DmF7MczI.d.cts → fallback-speech-engine-SqEfkGda.d.cts} +1 -1
- package/dist/{fallback-speech-engine-DmF7MczI.d.ts → fallback-speech-engine-SqEfkGda.d.ts} +1 -1
- package/dist/{feature-preferences-CVFDt9Xf.d.cts → feature-preferences-DqAmje-2.d.cts} +1 -1
- package/dist/{feature-preferences-CVFDt9Xf.d.ts → feature-preferences-DqAmje-2.d.ts} +1 -1
- package/dist/forms-ui.d.cts +2 -2
- package/dist/forms-ui.d.ts +2 -2
- package/dist/{history-confirm-dialog-DJEXsTyE.d.cts → history-confirm-dialog-B3L7QNcO.d.cts} +1 -1
- package/dist/{history-confirm-dialog-DJEXsTyE.d.ts → history-confirm-dialog-B3L7QNcO.d.ts} +1 -1
- package/dist/history-shell.cjs +1 -1
- package/dist/history-shell.d.cts +6 -6
- package/dist/history-shell.d.ts +6 -6
- package/dist/history-shell.js +1 -1
- package/dist/history-view.d.cts +1 -1
- package/dist/history-view.d.ts +1 -1
- package/dist/index.cjs +38 -38
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -9
- package/dist/index.d.ts +9 -9
- package/dist/index.global.js +1 -1
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +52 -52
- package/dist/index.js.map +1 -1
- package/dist/install.global.js +1 -1
- package/dist/install.global.js.map +1 -1
- package/dist/launcher.global.js +2 -2
- package/dist/launcher.global.js.map +1 -1
- package/dist/{loading-label-runtime-loader-CPxnoaoi.d.cts → loading-label-runtime-loader-JecjOfJS.d.cts} +1 -1
- package/dist/{loading-label-runtime-loader-CPxnoaoi.d.ts → loading-label-runtime-loader-JecjOfJS.d.ts} +1 -1
- package/dist/loading-label-runtime.d.cts +1 -1
- package/dist/loading-label-runtime.d.ts +1 -1
- package/dist/{message-bubble-CkZGlCLC.d.ts → message-bubble-CBYtpDsT.d.cts} +2 -2
- package/dist/{message-bubble-CkZGlCLC.d.cts → message-bubble-CBYtpDsT.d.ts} +2 -2
- package/dist/preferences-runtime.d.cts +1 -1
- package/dist/preferences-runtime.d.ts +1 -1
- package/dist/{preview-DdUvoLb4.d.cts → preview-_UJwwt2L.d.cts} +2 -2
- package/dist/{preview-DdUvoLb4.d.ts → preview-_UJwwt2L.d.ts} +2 -2
- package/dist/{registry-Dz4iHNST.d.cts → registry-B5ZV3K-h.d.cts} +1 -1
- package/dist/{registry-Dz4iHNST.d.ts → registry-B5ZV3K-h.d.ts} +1 -1
- package/dist/{session-Baxp9iRK.d.cts → session-Bys8_XuB.d.cts} +10 -9
- package/dist/{session-Baxp9iRK.d.ts → session-Bys8_XuB.d.ts} +10 -9
- package/dist/session-reconnect.d.cts +2 -2
- package/dist/session-reconnect.d.ts +2 -2
- package/dist/smart-dom-reader.d.cts +1 -1
- package/dist/smart-dom-reader.d.ts +1 -1
- package/dist/theme-editor-preview.cjs +31 -31
- package/dist/theme-editor-preview.d.cts +1 -1
- package/dist/theme-editor-preview.d.ts +1 -1
- package/dist/theme-editor-preview.js +19 -19
- package/dist/theme-editor.cjs +1 -1
- package/dist/theme-editor.d.cts +2 -2
- package/dist/theme-editor.d.ts +2 -2
- package/dist/theme-editor.js +1 -1
- package/dist/theme-reference.cjs +1 -1
- package/dist/theme-reference.d.cts +4 -2
- package/dist/theme-reference.d.ts +4 -2
- package/dist/theme-reference.js +1 -1
- package/dist/{tool-loading-animation-un3kA5Ur.d.cts → tool-loading-animation-d5qAQcwv.d.cts} +1 -1
- package/dist/{tool-loading-animation-un3kA5Ur.d.ts → tool-loading-animation-d5qAQcwv.d.ts} +1 -1
- package/dist/{turn-activity-ui-BGNhtMcH.d.cts → turn-activity-ui-q6fHVnx-.d.cts} +2 -2
- package/dist/{turn-activity-ui-BGNhtMcH.d.ts → turn-activity-ui-q6fHVnx-.d.ts} +2 -2
- package/dist/turn-activity-ui.d.cts +1 -1
- package/dist/turn-activity-ui.d.ts +1 -1
- package/dist/{types-BOZHQIk0.d.cts → types-B_mj21jg.d.cts} +91 -7
- package/dist/{types-BOZHQIk0.d.ts → types-B_mj21jg.d.ts} +91 -7
- package/dist/voice-client-tools.d.cts +1 -1
- package/dist/voice-client-tools.d.ts +1 -1
- package/dist/voice-runtime.cjs +1 -1
- package/dist/voice-runtime.d.cts +2 -2
- package/dist/voice-runtime.d.ts +2 -2
- package/dist/voice-runtime.js +1 -1
- package/dist/voice-worklet-player.d.cts +2 -2
- package/dist/voice-worklet-player.d.ts +2 -2
- package/dist/{webmcp-runtime-entry-DuAG1_yF.d.cts → webmcp-runtime-entry-ClEO3qdI.d.cts} +1 -1
- package/dist/{webmcp-runtime-entry-DuAG1_yF.d.ts → webmcp-runtime-entry-ClEO3qdI.d.ts} +1 -1
- package/dist/webmcp-runtime.d.cts +1 -1
- package/dist/webmcp-runtime.d.ts +1 -1
- package/dist/widget.css +1 -1
- package/package.json +1 -1
- package/src/client-dispatch.ts +69 -16
- package/src/client.operator-role.test.ts +217 -0
- package/src/components/message-bubble.test.ts +169 -0
- package/src/components/message-bubble.ts +97 -28
- package/src/defaults-parity.test.ts +14 -0
- package/src/index-core.ts +7 -0
- package/src/index-global.ts +2 -1
- package/src/install.test.ts +6 -5
- package/src/install.ts +2 -2
- package/src/launcher-global.ts +2 -1
- package/src/session.resubmit-from.test.ts +27 -0
- package/src/session.test.ts +51 -0
- package/src/session.ts +22 -12
- package/src/styles/widget.css +23 -1
- package/src/theme-reference.ts +3 -1
- package/src/types/theme.ts +21 -0
- package/src/types.ts +71 -6
- package/src/ui.ask-user-question-plugin.test.ts +154 -0
- package/src/ui.operator-role.test.ts +336 -0
- package/src/ui.ts +37 -12
- package/src/utils/__snapshots__/tokens-parity.test.ts.snap +236 -0
- package/src/utils/brand.test.ts +14 -0
- package/src/utils/brand.ts +8 -4
- package/src/utils/cdn-release.test.ts +20 -0
- package/src/utils/cdn-release.ts +14 -0
- package/src/utils/history-messages.test.ts +30 -0
- package/src/utils/history-messages.ts +26 -8
- package/src/utils/message-fingerprint.ts +4 -0
- package/src/utils/resubmit-turn.test.ts +13 -0
- package/src/utils/resubmit-turn.ts +12 -1
- package/src/utils/tokens.ts +31 -0
- package/src/welcome.test.ts +16 -0
- package/src/welcome.ts +10 -2
- package/dist/chunk-BkOYJ11B.js +0 -1
- package/dist/chunk-Bz9jAgba.js +0 -1
- package/dist/chunk-CdpVP6LZ.js +0 -1
- package/dist/chunk-DM-OJt5q.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as e,r as t,t as n}from"./chunk-D5BxWOFB.js";import{r}from"./chunk-Bb41bKyp.js";import{n as i,r as a}from"./chunk-Bz9jAgba.js";import{a as o}from"./chunk-Cy1A8vbF.js";import{n as s}from"./chunk-CLMIHW4_.js";const c=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},l=e=>Object.freeze({...e}),u=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),d=e=>e?l(e):null;function ee(e){let{plugins:t,config:n}=e,r=!1,i=!1,a=!1,o=!1,s=null,ee=[],f=()=>{for(let e of ee.splice(0))try{e()}catch(e){c(`renderHistoryView cleanup`,e)}},p=(e,n)=>{for(let r of t){let t=r[e];if(t)try{let e=t(n);if(e)return e}catch(t){c(e,t)}}return null},m=()=>({presentation:e.getPresentation(),config:n}),h={header:t=>o?p(`renderHistoryHeader`,Object.freeze({...m(),returnSurface:e.getReturnSurface(),identityStatus:l(t.identityStatus),pendingAction:d(t.pendingAction),copy:l(t.copy),actions:Object.freeze({close:_.close,startNewConversation:_.startNewConversation}),defaultRenderer:t.defaultRenderer})):null,conversation:e=>o?p(`renderHistoryConversation`,Object.freeze({...m(),conversation:u(e.conversation),active:e.active,pending:e.pending,open:e.open,requestDelete:e.requestDelete,defaultRenderer:e.defaultRenderer})):null,state:e=>o?p(`renderHistoryState`,Object.freeze({...m(),state:l(e.state),identityStatus:l(e.identityStatus),copy:l(e.copy),...e.retry?{retry:e.retry}:{},...e.startNewConversation?{startNewConversation:e.startNewConversation}:{},defaultRenderer:e.defaultRenderer})):null},te=t.flatMap(t=>(t.railSections??[]).map(t=>({...t,placement:t.placement??`above-conversations`,items:[],render:n=>t.render(Object.freeze({collapsed:n,presentation:e.getPresentation(),actions:_}))}))),g=e.createView({slots:h,renderDom:!1,onModelChange:()=>b(),railSections:te}),_=Object.freeze({...g.operations,close:e.close}),v=()=>(o=!0,g.setDomRenderEnabled(!0),g.element),ne=t=>Object.freeze({conversations:Object.freeze(t.conversations.map(u)),activeConversationId:t.activeConversationId,state:l(t.state),pendingAction:d(t.pendingAction),identityStatus:l(t.identityStatus),nextCursor:t.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:l(g.copy),actions:_,defaultRenderer:v,requestRender:()=>b(),onCleanup:e=>{ee.push(e)}}),y=()=>{o=!1;let e=null;for(let n of t)if(n.renderHistoryView){try{e=n.renderHistoryView(ne(g.getModel()))}catch(t){c(`renderHistoryView`,t),e=null}if(e)break}let n=!e||e.contains(g.element);return o=n,g.setDomRenderEnabled(n),e??g.element};function b(){if(!(!a||r||i)){i=!0;try{f();let t=y();if(t===s)return;let n=s;s=t,e.onElementChanged(t,n)}finally{i=!1}}}return a=!0,b(),{view:g,get element(){return s??g.element},requestRender:b,dispose:()=>{r=!0,f()}}}const f=/* @__PURE__ */ new Map([[`not_found`,`not_found`],[`conversation_deleted`,`not_found`],[`rate_limited`,`rate_limited`],[`authentication_required`,`authentication_required`],[`invalid_identity_proof`,`authentication_required`],[`visitor_identity_mismatch`,`authentication_required`],[`visitor_required`,`authentication_required`],[`identity_provider_failed`,`identity_provider_failed`],[`proof_not_admitted`,`proof_not_admitted`],[`identity_contract_violation`,`proof_not_admitted`],[`unauthorized`,`authentication_failed`],[`visitor_token_missing`,`authentication_failed`],[`conversation_credential_missing`,`authentication_failed`]]),p=/* @__PURE__ */ new Map([[`not_found`,`That conversation is no longer available.`],[`rate_limited`,`Too many history requests.`],[`authentication_failed`,`History access was not authorized.`],[`authentication_required`,`Sign in again to view account history.`],[`identity_provider_failed`,`The identity provider did not respond.`],[`proof_not_admitted`,`Account history is not available for this configuration.`],[`unsupported_scope`,`This history scope is not supported.`],[`unavailable`,`Conversation history is unavailable right now.`]]),m=e=>p.get(e)??`Conversation history is unavailable right now.`;function h(e,{HistoryClientError:t,HistoryProviderError:n}){if(e instanceof n)return e;if(e instanceof t){let t=f.get(e.code)??`unavailable`;return new n(t,m(t),{...e.retryAfterSeconds===void 0?{}:{retryAfterSeconds:e.retryAfterSeconds}})}return new n(`unavailable`,m(`unavailable`))}function te(e){let{HistoryProviderError:t}=e.errors,n=()=>e.getClient?.()??e.client,r=e.getIdentityProofConfigured()?[`browser`,`verified-user`]:[`browser`],o={scopes:r},s=e=>{if(!r.includes(e))throw new t(`unsupported_scope`,m(`unsupported_scope`))},c=async(t,n)=>{s(t);try{return await n()}catch(t){throw h(t,e.errors)}},l=t=>{let n=!1;return{conversationId:t.session.conversationId??``,conversationRevision:t.session.conversationRevision??``,async commit(){n||(n=!0,t.commit(),await e.onActivationCommitted(t.session))},discard(){n||(n=!0,t.discard())}}};return{capabilities:o,getIdentityStatus(){return n().getHistoryIdentityStatus()},subscribeIdentityStatus(e){return n().subscribeHistoryIdentityStatus(e)},subscribeAvailability(e){return n().subscribeHistoryAvailability(e)},async list(e){return c(e.context.scope,async()=>{let t=await n().listConversations({...e.cursor?{cursor:e.cursor}:{},...e.limit===void 0?{}:{limit:e.limit},...e.targetId?{targetId:e.targetId}:{},scope:e.context.scope});return{items:t.data,nextCursor:t.nextCursor}})},async getPage(e,t){return c(t.context.scope,async()=>{let r=await n().getConversation(e,{...t.cursor?{messageCursor:t.cursor}:{},scope:t.context.scope}),o=i(r.messages,{...t.beforeCreatedAt?{beforeCreatedAt:t.beforeCreatedAt}:{}});return{summary:r.summary,messages:a([],o),conversationRevision:r.conversationRevision??``,nextCursor:r.nextMessageCursor}})},async prepareOpen(e,t){return c(t.context.scope,async()=>l(await n().prepareConversationSession(e)))},async prepareStartNew(e){return c(e.context.scope,async()=>l(await n().prepareNewConversationSession()))},async delete(e,t){await c(t.context.scope,()=>n().deleteConversation(e,{scope:t.context.scope}))},async deleteAll(e){return c(e.context.scope,()=>n().deleteAllConversations({...e.targetId===void 0?{}:{targetId:e.targetId},scope:e.context.scope}))},async resetDevice(){try{return await n().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}const g=i=>{let a=s(i.config.features?.history?.copy),c=null,l=!1,u=null,d=null,f=`conversation`,p=null,m=null,h=null,g=null,_=0,v=null,ne=null,y=null,b=`persona-history-${Math.random().toString(36).slice(2,8)}`,x=()=>i.historyFeatureEnabled()&&!!c&&!l,re=()=>{let e=i.session.getStatus();return i.isStreaming||e===`paused`||e===`resuming`},ie=()=>{let e=i.config.features?.history?.scope;if(e)return e;let t=i.config.getIdentityProof?`verified-user`:`browser`,n=c?.capabilities.scopes;return!n||n.includes(t)?t:n[0]??t},S=()=>d?.scope??ie(),ae=()=>i.session.getClientSession()?.targetId??null,oe=e=>`${e.state}:${`reason`in e?e.reason:``}`,se=e=>{let t=oe(e);t!==g&&(g=t,i.eventBus.emit(`history:identityStatusChanged`,{status:e,timestamp:Date.now()}))},ce=null,le=null,ue=()=>{if(!i.historyFeatureEnabled())return null;let e=i.getHistoryProviderFactory();if(e)return e();let t=i.config.features?.history?.provider;return t?typeof t==`function`?(ce!==t&&(ce=t,le=t()),le):t:i.session.isClientTokenMode()?te({errors:i.historyErrors,client:i.session.getClient(),getIdentityProofConfigured:()=>typeof i.config.getIdentityProof==`function`,onActivationCommitted:e=>i.session.bindActivatedSession(e),getClient:()=>i.session.getClient()}):null},de=()=>{ne?.(),ne=null,y?.(),y=null,l=!1;let e=c;c=ue(),e&&e!==c&&i.discardConversationContinuity();let t={...i.historyInternals};c?t.historyProvider=c:delete t.historyProvider,i.historyInternals=t,i.session.setHistoryInternals(i.historyInternals),c&&(ne=c.subscribeAvailability?.(e=>{l=!e,e||q({restoreFocus:!1}),$()})??null,y=c.subscribeIdentityStatus(e=>se(e)),g=oe(c.getIdentityStatus()))},fe=()=>{let e=i.config.features?.history?.presentation??`panel`;if(e===`panel`||e===`auto`&&i.launcherEnabled&&!i.isDockedMountMode(i.config))return`panel`;let t=i.artifactSplitRoot??i.container;return(t.getBoundingClientRect().width||t.clientWidth)>=720?`rail`:`panel`},C=(e,t)=>{t?(e.setAttribute(`aria-hidden`,`true`),e.setAttribute(`inert`,``)):(e.removeAttribute(`aria-hidden`),e.removeAttribute(`inert`))},pe=`data-persona-history-suppressed`,w=null,T=null,E=null,D=null,me=null,he=``,ge=()=>i.header===me?he:o(i.config)?``:`none`,_e=()=>i.historyPresentation===`panel`&&!!E&&D===E.element&&o(i.config)&&ge()!==`none`,ve=()=>{for(let e of Array.from(i.header.children))e!==w&&e.setAttribute(pe,``)},ye=()=>{for(let e of Array.from(i.container.querySelectorAll(`[${pe}]`)))e.removeAttribute(pe)},be=()=>{let e=E;if(!e)return;if(Array.from(i.header.children).some(e=>e!==w&&!e.hasAttribute(pe))){T&&T!==i.header&&(T.style.removeProperty(`min-height`),T=null);let e=i.header.offsetHeight;e>0&&(i.header.style.minHeight=`${e}px`,T=i.header)}w||=n(`div`,`persona-history-header-host`),e.setHeaderPlacement(`external`);let t=e.getHeaderElement();t.parentNode!==w&&w.replaceChildren(t),w.parentNode!==i.header&&i.header.appendChild(w),ve()},xe=()=>{T&&=(T.style.removeProperty(`min-height`),null),w&&(E?.setHeaderPlacement(`inline`),w.remove(),w=null,ye())},Se=null,Ce=()=>{Se&&(i.body.style.display=`none`,C(i.body,!0),i.footer.hidden=!0,C(i.footer,!0),i.panelSuggestions.style.display=`none`,C(i.panelSuggestions,!0),i.panelSuggestionsFade.style.display=`none`,_e()?(be(),i.header.style.display=ge(),C(i.header,!1)):(xe(),i.header.style.display=`none`,C(i.header,!0)))};i.reapplyHistoryHostChrome=Ce;let we=e=>{let t=i.body.style.display,n=i.footer.hidden,r=i.panelSuggestions.style.display,a=i.panelSuggestionsFade.style.display,s=i.footer,c=i.header,l=i.header.style.display;me=c,he=l,Se=()=>{Se=null,xe(),me=null,i.body.style.display=t,C(i.body,!1),i.panelSuggestions.style.display=r,C(i.panelSuggestions,!1),i.panelSuggestionsFade.style.display=a,s.hidden=n,C(s,!1),i.footer!==s&&(i.footer.hidden=!1,C(i.footer,!1)),c.style.display=l,C(c,!1),i.header!==c&&(i.header.style.display=o(i.config)?``:`none`,C(i.header,!1))},i.container.insertBefore(e,i.footer.parentNode===i.container?i.footer:i.panelSuggestions),Ce()},O=null,k=null,Te=null,A=null,Ee=()=>[i.header,i.panelElements.closeButtonWrapper,i.panelElements.clearChatButtonWrapper,i.body,i.footer,i.scrollToBottomButton],De=()=>i.config.features?.history?.rail?.collapsible!==!1,j=()=>i.config.features?.history?.rail?.side===`right`?`right`:`left`,Oe=e=>Math.min(400,Math.max(200,Math.round(e))),ke=()=>i.config.features?.history?.rail?.resizable===!0,M,Ae=()=>{if(M===void 0&&(M=null,i.config.persistState!==!1))try{let e=Number(window.localStorage.getItem(`${i.currentKeyPrefix()}rail-width`));e&&(M=e)}catch{}return M},N=()=>Oe(Ae()??i.config.features?.history?.rail?.width??260),je=e=>{if(M=e,i.config.persistState!==!1)try{window.localStorage.setItem(`${i.currentKeyPrefix()}rail-width`,String(e))}catch{}},Me=()=>De()&&i.config.features?.history?.rail?.collapsedBehavior===`overlay`,P=!1,Ne=e=>{let t=n(`img`);return t.src=e,t.alt=``,t.setAttribute(`aria-hidden`,`true`),t},Pe=()=>{let e=i.config.features?.history?.rail?.brand;if(!e)return;let t=!1,n;return r=>{if(e.render)try{return e.render({collapsed:r})??null}catch(e){return t||(t=!0,console.warn(`[persona] history rail brand threw`,e)),null}return n===void 0&&(n=e.iconUrl?Ne(e.iconUrl):e.icon?i.renderLucideIcon(e.icon,20):null),n?n.cloneNode(!0):null}},Fe=()=>i.config.features?.history?.rail?.sections?.map(e=>{let t=!1,n=n=>{t||(t=!0,console.warn(`[persona] history rail section threw`,e.id,n))};return{id:e.id,title:e.title,placement:e.placement??`above-conversations`,items:e.items.map(e=>{let t;return{id:e.id,label:e.label,badge:e.badge,iconNode:()=>{if(t!==void 0)return t;try{t=e.renderIcon?e.renderIcon()??null:e.iconUrl?Ne(e.iconUrl):e.icon?i.renderLucideIcon(e.icon,20):null}catch(e){n(e),t=null}return t},onSelect:()=>{try{e.onSelect()}catch(e){n(e)}}}})}})??[],Ie=e=>{let t=Fe();for(let n of e)t.some(e=>e.id===n.id)?console.warn(`[persona] duplicate history rail section id`,n.id):t.push(n);return t.length?t:void 0},F=null,Le=()=>`${i.currentKeyPrefix()}rail-collapsed`,Re=()=>{if(F===null&&(F=i.config.features?.history?.rail?.defaultCollapsed===!0,i.config.persistState!==!1))try{let e=window.localStorage.getItem(Le());e&&(F=e===`1`)}catch{}return F},ze=e=>{if(F=e,i.config.persistState!==!1)try{window.localStorage.setItem(Le(),e?`1`:`0`)}catch{}},I=()=>i.historyPresentation===`rail`&&De()&&!Me()&&Re(),Be=()=>{},Ve=()=>{Me()?Be():(ze(!Re()),u?.view.setCollapsed(I()),i.applyRailChrome(),i.repinAnchoredMessage())},He=()=>{let e=i.config.features?.history?.rail?.collapseShortcut;return!e||!i.parseCombo(e)?null:{combo:e,hint:i.formatCombo(e),aria:i.ariaCombo(e)}},Ue=`var(--persona-history-overlay-margin,8px)`,L=null,R=null,We=0,z=null,B=null,V=!1,Ge=0,Ke=()=>window.matchMedia?.(`(pointer: coarse)`).matches===!0,H=()=>x()&&Me()&&(i.historyPresentation??fe())===`rail`,qe=()=>i.historyVisible&&!P,U=()=>{B!==null&&clearTimeout(B),B=null},Je=()=>{i.loadHistoryView().catch(()=>{})},Ye=()=>{U(),P&&(B=setTimeout(()=>{B=null,!V&&P&&(z?.contains(document.activeElement)||q({restoreFocus:!1}))},300))},Xe=(e,t)=>{let n=z?.getBoundingClientRect();if(!n)return!1;let r=L?.getBoundingClientRect(),i=r?Math.min(r.top,n.top):n.top;return e>=n.left&&e<=n.right&&t>=i&&t<=n.bottom||!!r&&e>=r.left&&e<=r.right&&t>=r.top&&t<=r.bottom},Ze=e=>{P&&(V=Xe(e.clientX,e.clientY),V?U():B===null&&Ye())},Qe=e=>{!i.historyVisible&&H()&&(P=!0,K({invoker:L,keyboard:e?.keyboard===!0}).then(()=>{i.historyVisible?!V&&document.activeElement!==L&&q():P=!1}))},$e=()=>{let e=D?.querySelector(`[data-persona-history-focus="collapse"]`);e&&(e.setAttribute(`aria-label`,P?a.expandLabel:a.collapseLabel),e.setAttribute(`aria-expanded`,P?`false`:`true`))},et=()=>{ze(!1);let e=u;if(!P||!e){K({invoker:L});return}let t=document.activeElement===L;P=!1,ft(),e.element.remove(),mt(e.element),$e(),t&&_t(),i.repinAnchoredMessage(),$()},tt=()=>{ze(!0),q()};Be=()=>{!i.historyVisible||P?et():tt()};let nt=()=>{let e=He(),t=i.createHeaderIconButton({ariaLabel:a.expandLabel,iconName:`panel-left`,wrapperClassName:`persona-relative persona-inline-flex persona-items-center persona-justify-center`,extraClassName:`persona-rail-trigger`,tooltip:!1,attrs:{"data-persona-rail-trigger":``,"aria-controls":b,...e?{"aria-keyshortcuts":e.aria}:{}}}),n=t.button;n.addEventListener(`mouseenter`,()=>{V=!0,U(),!(Ke()||Date.now()<Ge)&&Qe()}),n.addEventListener(`mouseleave`,()=>{V=!1,Ge=0,Ye()}),n.addEventListener(`focus`,()=>{i.historyVisible||Je()}),n.addEventListener(`click`,e=>{x()&&(e.detail!==0&&Ke()&&!i.historyVisible?Qe():et())}),L=n,R=t.wrapper},W=()=>{if(R&&!R.isConnected&&(R=null,L=null),!H()){R?.remove(),R=null,L=null;return}L||nt();let e=R,t=L;if(!e||!t)return;let n=j()===`right`?null:i.header.firstChild;(n??i.header.lastChild)!==e&&i.header.insertBefore(e,n),e.style.display=qe()||We>0?`none`:``,t.setAttribute(`aria-label`,a.expandLabel),t.setAttribute(`aria-expanded`,i.historyVisible?`true`:`false`),z&&i.applyRailChrome()},rt=e=>{if(!P)return;let t=e.target;t instanceof Node&&(z?.contains(t)||R?.contains(t)||t instanceof Element&&t.closest(`.persona-dropdown-menu,[role="alertdialog"]`)||q({restoreFocus:!1}))};document.addEventListener(`pointerdown`,rt,!0),i.destroyCallbacks.push(()=>{document.removeEventListener(`pointerdown`,rt,!0),document.removeEventListener(`pointermove`,Ze),G?.(),U()});let it=null,G=null,at=e=>{je(Oe(e)),i.applyRailChrome(),i.repinAnchoredMessage()},ot=()=>{let e=n(`div`,`persona-rail-resizer`);return e.tabIndex=0,e.setAttribute(`role`,`separator`),e.setAttribute(`aria-orientation`,`vertical`),e.setAttribute(`aria-valuemin`,`200`),e.setAttribute(`aria-valuemax`,`400`),e.addEventListener(`pointerdown`,t=>{let n=k;if(!n||t.button!==0)return;t.preventDefault(),G?.();let r=t.clientX,a=n.getBoundingClientRect().width||N(),o=j()===`right`?-1:1,s=a,c=i.mount.ownerDocument;n.style.transition=`none`;let l=t=>{s=Oe(a+o*(t.clientX-r)),n.style.flex=`0 0 ${s}px`,e.setAttribute(`aria-valuenow`,String(s))},u=()=>{G=null,c.removeEventListener(`pointermove`,l),c.removeEventListener(`pointerup`,u),c.removeEventListener(`pointercancel`,u),n.style.removeProperty(`transition`);try{e.releasePointerCapture(t.pointerId)}catch{}at(s)};G=u,c.addEventListener(`pointermove`,l),c.addEventListener(`pointerup`,u),c.addEventListener(`pointercancel`,u);try{e.setPointerCapture(t.pointerId)}catch{}}),e.addEventListener(`keydown`,e=>{let t=j()===`right`?-16:16,n=N(),r=e.key===`ArrowRight`?n+t:e.key===`ArrowLeft`?n-t:e.key===`Home`?200:e.key===`End`?400:null;r!==null&&(e.preventDefault(),at(r))}),e},st=(e,t)=>{if(!ke()||I()){G?.(),it?.remove();return}let n=it??ot();it=n,n.setAttribute(`aria-label`,a.resizeLabel),n.setAttribute(`aria-valuenow`,String(N())),n.nextElementSibling!==t&&e.insertBefore(n,t)};i.applyRailChrome=()=>{u?.view.setRailSide(j());let e=j()===`right`,t=z;if(t){let n=L?L.getBoundingClientRect().bottom-i.container.getBoundingClientRect().top:0;t.style.top=`calc(${Math.max(0,Math.round(n))}px + ${Ue})`,t.style.width=`${N()}px`,t.style.left=e?``:Ue,t.style.right=e?Ue:``}let n=k,r=O,a=Te;if(!n||!r||!a)return;n.style.flex=`0 0 ${I()?52:N()}px`;let o=`1px solid var(--persona-divider,#e5e7eb)`;n.style.borderRight=e?``:o,n.style.borderLeft=e?o:``;let s=e?a:n;r.firstElementChild!==s&&r.append(s,e?n:a),st(r,e?n:a)};let ct=e=>{if(A&&k){A.replaceWith(e),A=null,i.applyRailChrome();return}let t=n(`div`,`persona-history-rail-shell`);t.style.cssText=`display:flex;flex-direction:row;flex:1 1 auto;min-height:0`;let r=n(`div`,`persona-history-rail-conversation`);r.style.cssText=`display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative`;let a=n(`div`,`persona-history-rail-host`);a.style.cssText=`display:flex;min-height:0;overflow:hidden`,i.container.insertBefore(t,i.header.parentNode===i.container?i.header:i.body);for(let e of Ee())e?.parentNode===i.container&&r.appendChild(e);t.append(a,r),a.appendChild(e),O=t,k=a,Te=r,i.applyRailChrome()},lt=()=>{if(O)return;let e=n(`div`,`persona-history-rail-placeholder`);e.style.cssText=`flex:1 1 auto;min-height:0`,A=e,ct(e),i.repinAnchoredMessage()},ut=()=>{A&&(ft(),i.repinAnchoredMessage())},dt=e=>{let t=n(`div`,`persona-history-rail-overlay`);t.style.cssText=`position:absolute;bottom:${Ue};display:flex;overflow:hidden;z-index:${r-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,i.container.style.position=`relative`,i.container.appendChild(t),t.appendChild(e),document.addEventListener(`pointermove`,Ze),z=t,i.applyRailChrome(),$e()},ft=()=>{Se?.(),z&&=(V&&(Ge=Date.now()+150),document.removeEventListener(`pointermove`,Ze),z.remove(),null);let e=O;if(e){G?.();for(let t of Ee())if(t&&e.contains(t)){let n=t===i.scrollToBottomButton?i.panelSuggestions:e;i.container.insertBefore(t,n)}e.remove(),O=null,k=null,Te=null,A=null}},pt=e=>{D=e,e.id=b,e.style.flex=`1 1 auto`,e.style.minHeight=`0`},mt=e=>{pt(e),(i.historyPresentation!==`rail`||P)&&ut(),i.historyPresentation===`rail`?P?dt(e):ct(e):we(e)},ht=()=>{if(W(),Ht(),!i.historyVisible||!u)return;let e=fe();if(e===i.historyPresentation)return;let t=document.activeElement,n=t instanceof HTMLElement&&(u.element.contains(t)||w?.contains(t)===!0)?t:null;ft(),u.element.remove(),u.view.setHeaderPlacement(`inline`),i.historyPresentation=e,u.view.setPresentation(e),u.view.setCollapsed(I()),u.requestRender(),u.element.isConnected||mt(u.element),n?.isConnected?n.focus():_t(),i.syncScrollToBottomButton(),i.repinAnchoredMessage(),$()},gt=(e,t)=>w?.querySelector(t)??e.querySelector(t),_t=()=>{let e=u?.element??D;if(!e)return;let t=gt(e,`[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]`);if(t){t.focus();return}let n=gt(e,`.persona-history-title`)??e;n.tabIndex=-1,n.focus()},K=async e=>{if(!x()||i.historyVisible)return;let t=c;if(!t)return;if(!P&&H()&&Re()){W();return}vt();let n=++_;f=e?.returnSurface??`conversation`,p=e?.invoker??m;let r=H()&&!P;r&&(We+=1,W(),lt());let s;try{s=await i.loadHistoryView()}catch{i.announceHistory(a.openHistoryLabel),r&&(--We,n===_&&(ut(),W()));return}if(r&&--We,n!==_||i.historyVisible)return;d={scope:ie()},i.historyPresentation=fe(),i.historyVisible=!0;let l=i.historyPresentation===`panel`&&o(i.config)&&i.header.style.display!==`none`?`external`:`inline`,h=i.config.features?.history?.rowAvatar,te=He(),g=te?{hint:te.hint,aria:te.aria}:null,v={provider:t,context:d,targetId:ae(),presentation:i.historyPresentation,collapsible:De(),collapsed:I(),railSide:j(),renderRailHeader:i.config.features?.history?.rail?.renderHeader,railBrand:Pe(),onToggleCollapse:Ve,...g?{collapseShortcut:g}:{},headerPlacement:l,showScopeStatus:i.config.features?.history?.showScopeStatus!==!1,showDelete:i.config.features?.history?.showDelete!==!1,showDeleteAll:i.config.features?.history?.showDeleteAll!==!1,...i.config.features?.history?.listActions?.length?{listActions:i.config.features.history.listActions}:{},rowAvatar:h===!1?!1:typeof h==`string`?h:i.config.launcher?.iconUrl,activeConversationId:i.session.getActiveConversationId(),...i.config.features?.history?.grouping?{grouping:i.config.features.history.grouping}:{},...i.config.features?.history?.copy?{copy:i.config.features.history.copy}:{},...i.config.features?.history?.pageSize===void 0?{}:{pageSize:i.config.features.history.pageSize},onSelect:e=>At(e,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:e=>i.setActiveConversationSummary(e),attachTooltip:i.attachTooltip,onStartNew:()=>jt({focusComposer:!0}),onClose:()=>q(),onRequestDeleteConversation:e=>Rt(e),onRequestClearHistory:()=>zt(),...t.resetDevice?{onRequestResetIdentity:()=>Bt()}:{}};u=ee({plugins:i.plugins,config:i.config,getPresentation:()=>i.historyPresentation??`panel`,getReturnSurface:()=>f,close:()=>q(),createView:({slots:e,renderDom:t,onModelChange:n,railSections:r})=>(E=s.createHistoryView({...v,railSections:Ie(r),slots:e,renderDom:t,onModelChange:n,onAnnounce:i.announceHistory}),E),onElementChanged:(e,t)=>{if(!t?.isConnected)return mt(e);pt(e),t.replaceWith(e),Ce()}}),u.view.setNewConversationRequired(i.historySessionState.recovery===`new_conversation_required`),e?.focus!==!1&&(i.historyPresentation!==`rail`||e?.keyboard===!0)&&_t(),i.syncScrollToBottomButton(),i.repinAnchoredMessage(),$(),i.eventBus.emit(`history:opened`,{presentation:i.historyPresentation,returnSurface:f,timestamp:Date.now()})},vt=()=>{},q=e=>{if(!i.historyVisible)return;_+=1;let t=f,n=p,r=u,a=e?.restoreFocus!==!1;i.historyVisible=!1;let o=!1,s=null,c=()=>{if(!o){if(o=!0,vt=()=>{},s!==null&&clearTimeout(s),P=!1,U(),ft(),r?.dispose(),r?.view.destroy(),r?.element.remove(),u===r&&(u=null,E=null,D=null,i.historyPresentation=null,d=null,p=null),i.syncScrollToBottomButton(),i.repinAnchoredMessage(),$(),a){let e=n??m;e?.isConnected?e.focus():i.maybeFocusInput()}i.eventBus.emit(`history:closed`,{returnSurface:t,timestamp:Date.now()})}},l=r&&r.element===r.view.element?r.view.playExit():null;l?(vt=c,s=setTimeout(c,250),l.then(c)):c()},yt=e=>{if(e.key===`Escape`&&i.historyVisible&&u){if(i.historyPresentation===`rail`){let t=e.target;if(!(t instanceof Node)||!(u.element.contains(t)||P&&R?.contains(t)===!0))return}e.preventDefault(),e.stopPropagation(),q()}};i.container.addEventListener(`keydown`,yt),i.destroyCallbacks.push(()=>i.container.removeEventListener(`keydown`,yt));let J=0,Y=null,bt=null,xt=()=>{bt&&clearTimeout(bt),bt=null};i.destroyCallbacks.push(xt);let St=()=>{xt();let e=i.conversationOpenPendingEl;e&&(i.conversationOpenTakeover=!0,e.hidden=!1,i.messagesWrapper.style.display=`none`,i.updateWelcome())},X=()=>{J+=1,xt(),Y?.remove(),Y=null,i.conversationOpenPendingEl&&(i.conversationOpenPendingEl.remove(),i.conversationOpenPendingEl=null,i.conversationOpenTakeover=!1,i.messagesWrapper.style.removeProperty(`display`),C(i.footer,!1),i.updateWelcome())},Ct=()=>{try{if(window.matchMedia?.(`(prefers-reduced-motion: reduce)`)?.matches)return;i.messagesWrapper.animate([{opacity:0},{opacity:1}],{duration:150,easing:`ease-out`})}catch{}},wt=n=>{let r=i.config.layout?.messages?.layout??`bubble`,a=t(`div`,{className:`persona-flex`,attrs:{"aria-hidden":`true`}});i.applyMessageRowLayout(a,n);let o=t(`div`,{className:e(i.getBubbleClasses(n,r).join(` `),`persona-conversation-loading-bubble`),attrs:{"data-persona-theme-zone":`${n}-message`},style:{width:n===`user`?`64%`:`100%`,backgroundColor:r===`flat`?`transparent`:`var(--persona-message-${n}-bg, var(--persona-${n===`user`?`accent`:`container`}))`,color:`var(--persona-message-${n}-text, ${n===`user`&&r!==`flat`?`white`:`var(--persona-text)`})`}},...[`94%`,...n===`assistant`?[`86%`]:[],`62%`].map(e=>t(`div`,{className:`persona-conversation-loading-line`,style:{width:e}})));return i.applyBubbleGeometry(o,n,r,{...i.resolveThemeDefaults(i.config.future).components.message[n],...i.config.theme?.components?.message?.[n],...i.config.darkTheme?.components?.message?.[n]}),a.appendChild(o),a},Tt=()=>t(`div`,{className:`persona-conversation-loading-body`,style:{gap:i.messagesWrapper.style.gap}},wt(`user`),wt(`assistant`),wt(`user`),wt(`assistant`)),Et=()=>i.config.loadingIndicator?.conversationOpenVariant===`skeleton`?Tt():t(`div`,{className:`persona-conversation-loading-spinner`,attrs:{"aria-hidden":`true`}},t(`span`,{className:`persona-conversation-loading-ring`})),Dt=e=>{i.conversationOpenPendingEl?.remove(),i.conversationOpenPendingEl=e,e.hidden=!i.conversationOpenTakeover,i.body.insertBefore(e,i.messagesWrapper),xt(),i.conversationOpenTakeover||(bt=setTimeout(St,250)),C(i.footer,!0)},Ot=()=>{let n={config:i.config,streaming:!1,location:`conversation-open`,defaultRenderer:Et},r=null,o=i.plugins.find(e=>e.renderLoadingIndicator);o?.renderLoadingIndicator&&(r=o.renderLoadingIndicator(n)),r===null&&i.config.loadingIndicator?.render&&(r=i.config.loadingIndicator.render(n));let s=r??Et();Dt(t(`div`,{className:e(`persona-conversation-loading`,s.classList.contains(`persona-conversation-loading-spinner`)&&`persona-conversation-loading--centered`),attrs:{role:`status`,"aria-label":a.openConversationLoadingLabel},style:{maxWidth:i.messagesWrapper.style.maxWidth||`none`}},s))},kt=e=>{let n=()=>{At(e,{focusComposer:!0}).catch(()=>{})},r=x()?()=>{X(),K()}:void 0,o=(e,n)=>{let r=t(`button`,{className:`persona-conversation-loading-error-action`,attrs:{type:`button`},text:e});return r.addEventListener(`click`,n),r},s=()=>t(`div`,{className:`persona-conversation-loading-error-body`},t(`p`,{className:`persona-conversation-loading-error-title`,text:a.openConversationErrorTitle}),t(`div`,{className:`persona-conversation-loading-error-actions`},o(a.openConversationRetryLabel,n),r?o(a.openConversationBackLabel,r):null)),c=Object.freeze({conversationId:e,config:i.config,copy:Object.freeze({title:a.openConversationErrorTitle,retryLabel:a.openConversationRetryLabel,backLabel:a.openConversationBackLabel}),retry:n,...r?{back:r}:{},defaultRenderer:s}),l=null;for(let e of i.plugins)if(e.renderHistoryOpenError){try{l=e.renderHistoryOpenError(c)}catch(e){console.warn(`[persona] renderHistoryOpenError threw`,e),l=null}if(l)break}if(Y?.remove(),Y=t(`div`,{className:`persona-conversation-loading-error`,attrs:{role:`alert`}},l??s()),!i.session.getActiveConversationId()&&i.session.getMessages().length===0&&!i.composerStore.getState().text&&!i.attachmentManager?.hasAttachments()){let e=Y;Y=null,Dt(e),St()}else i.body.insertBefore(Y,i.messagesWrapper);i.announceHistory(a.openConversationErrorTitle)};i.eventBus.on(`history:closed`,()=>{i.conversationOpenPendingEl&&C(i.footer,!0)});let At=async(e,{focusComposer:t=!1,busy:n=`reject`}={})=>{let r=S();if(n===`background`&&(i.session.assertBackgroundSwitchable(),i.composerStore.getState().phase===`preparing`))throw new i.SessionHistoryError(`conversation_busy`,`Finish preparing this turn before switching conversations`);if(n===`reject`&&(i.session.isStreaming()||[`paused`,`resuming`].includes(i.session.getStatus())||i.composerStore.getState().phase===`preparing`))throw new i.SessionHistoryError(`conversation_busy`,`Finish or stop the current turn before switching conversations`);n===`stop`&&(++i.composerConversationGeneration,i.submissionAbort?.abort(),i.submissionAbort=null,i.composerStore.setPreparing(!1),i.session.cancel());let a=i.conversationStateKey();(!i.conversationOpenPendingEl||i.pendingConversationReading?.key!==a)&&(i.pendingConversationReading={key:a,reading:i.captureConversationReading()});let o=null,s=!!u;u?.view.setActiveConversationId(e),X();let c=J;Ot(),i.historyVisible&&(i.historyPresentation===`panel`||P)&&q({restoreFocus:!1}),i.suppressScrollSend=!0;try{await i.session.openConversation(e,{scope:r,busy:n,onBeforeCommit:()=>{i.saveConversationContinuity(),o=i.composerConversationGeneration,i.conversationPersistenceOwner=o},onCommitted:()=>{i.restoreConversationContinuity(),i.conversationPersistenceOwner===o&&(i.conversationPersistenceOwner=null),i.usesSessionVoiceForConfig(i.config)&&i.session.setupVoice(),i.persistState()}})}catch(t){if(i.conversationPersistenceOwner===o&&(i.conversationPersistenceOwner=null),o===i.composerConversationGeneration&&i.usesSessionVoiceForConfig(i.config)&&i.session.setupVoice(),c===J){let t=i.pendingConversationReading?.reading;X(),t&&i.restoreConversationReading(t),i.pendingConversationReading=null,u?.view.setActiveConversationId(i.session.getActiveConversationId()),kt(e),i.suppressScrollSend=!1}throw t}finally{(c===J||!i.conversationOpenPendingEl)&&(i.suppressScrollSend=!1)}c===J&&(X(),i.pendingConversationReading=null,i.messageCache.clear(),Ct(),Q(),s||i.setActiveConversationSummary(null),i.eventBus.emit(`history:conversationOpened`,{conversationId:e,title:i.activeConversationTitle,scope:r,timestamp:Date.now()}),t&&i.maybeFocusInput())},jt=async({focusComposer:e=!1}={})=>{X();let t=null;try{await i.session.startNewConversation({scope:S(),onBeforeCommit:()=>{i.saveConversationContinuity(),t=i.composerConversationGeneration,i.conversationPersistenceOwner=t},onCommitted:()=>{i.restoreConversationContinuity(!0),i.conversationPersistenceOwner===t&&(i.conversationPersistenceOwner=null),i.usesSessionVoiceForConfig(i.config)&&i.session.setupVoice(),i.persistState(),i.pendingConversationReading=null}})}catch(e){throw i.conversationPersistenceOwner===t&&(i.conversationPersistenceOwner=null),t===i.composerConversationGeneration&&i.usesSessionVoiceForConfig(i.config)&&i.session.setupVoice(),e}i.setActiveConversationSummary(null),i.messageCache.clear(),i.resetAnchorState(),i.resumeAutoScroll(),i.jumpToBottomInstant(),Q();let n=i.session.getActiveConversationId();u?.view.setActiveConversationId(n),i.eventBus.emit(`history:conversationStarted`,{conversationId:n,timestamp:Date.now()}),i.historyVisible&&(i.historyPresentation===`panel`||P)&&q({restoreFocus:!1}),e&&i.maybeFocusInput()},Mt=async(e,t)=>{let n=await i.session.updateConversation(e,{...t,...t.title===void 0?{}:{title:t.title.trim()}});return u?.view.applyConversationSummary(n),!u&&e===i.session.getActiveConversationId()&&i.setActiveConversationSummary(n),n},Nt=async e=>{let t=S(),n=i.session.getActiveConversationId()===e;await i.session.deleteConversation(e,{scope:t}),i.discardConversationContinuity(e),n&&(i.attachmentManager?.destroy({release:!0}),i.attachmentManager=null,i.restoreConversationContinuity(!0)),u?.view.removeConversationSummary(e),n&&(i.setActiveConversationSummary(null),i.messageCache.clear(),i.resetAnchorState(),i.resumeAutoScroll(),Q()),i.eventBus.emit(`history:conversationDeleted`,{conversationId:e,scope:t,wasActive:n,timestamp:Date.now()})},Pt=async e=>{let t=e?.scope??S(),n=e?.allTargets?null:e?.targetId??ae(),r=await i.session.clearConversationHistory({...n?{targetId:n}:{},scope:t});return i.discardConversationContinuity(),i.setActiveConversationSummary(null),i.messageCache.clear(),i.resetAnchorState(),i.resumeAutoScroll(),Q(),i.eventBus.emit(`history:cleared`,{deleted:r.deleted,scope:t,targetId:n,timestamp:Date.now()}),r},Ft=async()=>{if(!c?.resetDevice)throw Error(`[Persona] resetHistoryIdentity() requires a history provider that can reset this device`);let e=!1;try{e=(await i.session.resetHistoryDevice()).remoteRevocationConfirmed}finally{i.discardConversationContinuity(),X(),i.setActiveConversationSummary(null),i.session.clearArtifacts(),i.messageCache.clear(),i.lastAppliedMessages=null,i.config.clearStoredSessionId?.(),i.config.clearStoredConversationId?.(),i.persistentMetadata={},i.actionManager.syncFromMetadata(),i.clearPersistedDraft();let e=i.storageAdapter;e?.clear&&i.runStorageMutation(()=>e.clear(),`[AgentWidget] Failed to clear storage adapter:`),i.resetAnchorState(),i.resumeAutoScroll(),Q(),q({restoreFocus:!1}),i.maybeFocusInput(),i.open||i.launcherSurfaceInstance?.launcher.element.focus()}return i.announceHistory(e?a.identityResetNotice:a.identityResetUnconfirmedNotice),i.eventBus.emit(`history:identityReset`,{remoteRevocationConfirmed:e,timestamp:Date.now()}),{remoteRevocationConfirmed:e}},It=()=>i.artifactSplitRoot?i.panel:i.container,Lt=async e=>{let t=await i.loadHistoryView().catch(()=>null);return typeof t?.showHistoryConfirm==`function`?t.showHistoryConfirm(e):window.confirm(`${e.title}\n\n${e.description}`)},Rt=async e=>await Lt({host:It(),title:a.deleteConversationConfirmTitle,description:a.deleteConversationConfirm,confirmLabel:a.deleteConversationConfirmLabel,cancelLabel:a.confirmCancelLabel})?(await Nt(e),`deleted`):`cancelled`,zt=async()=>{let e=S()===`verified-user`;return await Lt({host:It(),title:a.clearHistoryConfirmTitle,description:e?a.clearHistoryVerifiedConfirm:a.clearHistoryConfirm,confirmLabel:a.clearHistoryConfirmLabel,cancelLabel:a.confirmCancelLabel})?(await Pt(),`cleared`):`cancelled`},Bt=async()=>{if(!await Lt({host:It(),title:a.resetIdentityConfirmTitle,description:a.resetIdentityConfirm,confirmLabel:a.resetIdentityConfirmLabel,cancelLabel:a.confirmCancelLabel}))return{outcome:`cancelled`};let{remoteRevocationConfirmed:e}=await Ft();return{outcome:`reset`,remoteRevocationConfirmed:e}},Z=n(`button`,`persona-history-earlier`);Z.type=`button`,Z.textContent=a.showEarlierMessagesLabel,Z.setAttribute(`data-persona-history-earlier`,``),Object.assign(Z.style,{alignSelf:`center`,minHeight:`44px`,padding:`0 16px`,borderRadius:`999px`,border:`1px solid var(--persona-border, rgba(0,0,0,0.12))`,background:`transparent`,color:`inherit`,font:`inherit`,cursor:`pointer`,flexShrink:`0`});let Q=()=>{x()&&i.historySessionState.nextMessageCursor&&i.session.getActiveConversationId()?(Z.textContent=a.showEarlierMessagesLabel,Z.parentNode!==i.body&&i.body.insertBefore(Z,i.body.firstChild)):Z.remove()};Z.addEventListener(`click`,()=>{let e=i.session.getActiveConversationId(),t=i.historySessionState.nextMessageCursor;if(!e||!t||Z.disabled)return;Z.disabled=!0;let n=i.body.scrollHeight,r=i.body.scrollTop;i.session.loadOlderMessages(e,t,{scope:S()}).then(()=>{i.body.scrollTop=r+(i.body.scrollHeight-n),i.repinAnchoredMessage()}).catch(()=>{}).finally(()=>{Z.disabled=!1,Q()})});let Vt=()=>{let e=i.createHeaderIconButton({ariaLabel:a.openHistoryLabel,iconName:`history`,wrapperClassName:`persona-relative persona-inline-flex persona-items-center persona-justify-center`,extraClassName:`persona-history-toggle`,attrs:{"data-persona-history-toggle":``}});return e.button.addEventListener(`click`,t=>{x()&&!re()&&(i.historyVisible?q():K({invoker:e.button,keyboard:t.detail===0}))}),e},Ht=()=>{if(!x()){h?.remove(),m=null,h=null;return}if(h&&!h.isConnected&&(m=null,h=null),!m&&i.header){let e=Vt();m=e.button,h=e.wrapper;let t=i.panelElements.clearChatButtonWrapper||i.panelElements.closeButtonWrapper;t?.parentNode&&i.header.contains(t)?t.parentNode.insertBefore(h,t):i.header.appendChild(h)}if(!m||!h)return;let e=H()||i.historyVisible&&i.historyPresentation===`rail`;if(h.style.display=e?`none`:``,e){document.activeElement===m&&_t();return}let t=re();m.disabled=t,m.setAttribute(`aria-disabled`,t?`true`:`false`);let n=t?a.openHistoryBusyLabel:a.openHistoryLabel;m.setAttribute(`aria-label`,n),(i.config.features?.history?.presentation??`panel`)===`panel`?(m.removeAttribute(`aria-expanded`),m.removeAttribute(`aria-controls`)):(m.setAttribute(`aria-expanded`,i.historyVisible?`true`:`false`),m.setAttribute(`aria-controls`,b))},Ut=!1,Wt=()=>{let e=i.panelElements.clearChatButton;e&&(x()?(Ut||=(v=e.getAttribute(`aria-label`)??``,!0),e.setAttribute(`aria-label`,a.newConversationLabel),e.removeAttribute(`title`)):Ut&&(Ut=!1,v&&e.setAttribute(`aria-label`,v)))},$=()=>{a=s(i.config.features?.history?.copy),Ht(),W(),Wt(),Q()};return i.historyChromeSync=$,de(),$(),i.destroyCallbacks.push(()=>{ne?.(),y?.(),_+=1,vt(),u?.dispose(),u?.view.destroy(),u=null}),{clearConversationOpenPending:X,cancelConversationOpenTakeover:xt,historyOperationScope:S,discardConversationContinuity:i.discardConversationContinuity,historyAvailable:x,historyScope:ie,installHistoryProvider:de,syncHistoryChromeImpl:$,syncHistoryPresentation:ht,syncEarlierMessagesPill:Q,openHistory:K,closeHistory:q,openHistoryConversation:At,startNewConversation:jt,updateHistoryConversation:Mt,deleteHistoryConversation:Nt,requestDeleteConversation:Rt,clearConversationHistory:Pt,resetHistoryIdentity:Ft,railCollapseShortcut:He,railCollapsible:De,railTriggerApplies:H,railOverlayMode:Me,toggleRailCollapsed:Ve,toggleRailPinned:()=>Be(),get historyProvider(){return c},get historySurface(){return u},get railShell(){return O},get railHost(){return k},get railColumn(){return Te}}};export{g as createHistoryShell};
|
|
1
|
+
import{i as e,r as t,t as n}from"./chunk-D5BxWOFB.js";import{r}from"./chunk-Bb41bKyp.js";import{n as i,r as a}from"./chunk-i4qGOJAL.js";import{a as o}from"./chunk-Cy1A8vbF.js";import{n as s}from"./chunk-CLMIHW4_.js";const c=(e,t)=>{console.warn(`[persona] ${e} threw`,t)},l=e=>Object.freeze({...e}),u=e=>Object.freeze({id:e.id,title:e.title,targetId:e.targetId,preview:e.preview,messageCount:e.messageCount,createdAt:e.createdAt,updatedAt:e.updatedAt}),d=e=>e?l(e):null;function ee(e){let{plugins:t,config:n}=e,r=!1,i=!1,a=!1,o=!1,s=null,ee=[],f=()=>{for(let e of ee.splice(0))try{e()}catch(e){c(`renderHistoryView cleanup`,e)}},p=(e,n)=>{for(let r of t){let t=r[e];if(t)try{let e=t(n);if(e)return e}catch(t){c(e,t)}}return null},m=()=>({presentation:e.getPresentation(),config:n}),h={header:t=>o?p(`renderHistoryHeader`,Object.freeze({...m(),returnSurface:e.getReturnSurface(),identityStatus:l(t.identityStatus),pendingAction:d(t.pendingAction),copy:l(t.copy),actions:Object.freeze({close:_.close,startNewConversation:_.startNewConversation}),defaultRenderer:t.defaultRenderer})):null,conversation:e=>o?p(`renderHistoryConversation`,Object.freeze({...m(),conversation:u(e.conversation),active:e.active,pending:e.pending,open:e.open,requestDelete:e.requestDelete,defaultRenderer:e.defaultRenderer})):null,state:e=>o?p(`renderHistoryState`,Object.freeze({...m(),state:l(e.state),identityStatus:l(e.identityStatus),copy:l(e.copy),...e.retry?{retry:e.retry}:{},...e.startNewConversation?{startNewConversation:e.startNewConversation}:{},defaultRenderer:e.defaultRenderer})):null},te=t.flatMap(t=>(t.railSections??[]).map(t=>({...t,placement:t.placement??`above-conversations`,items:[],render:n=>t.render(Object.freeze({collapsed:n,presentation:e.getPresentation(),actions:_}))}))),g=e.createView({slots:h,renderDom:!1,onModelChange:()=>b(),railSections:te}),_=Object.freeze({...g.operations,close:e.close}),v=()=>(o=!0,g.setDomRenderEnabled(!0),g.element),ne=t=>Object.freeze({conversations:Object.freeze(t.conversations.map(u)),activeConversationId:t.activeConversationId,state:l(t.state),pendingAction:d(t.pendingAction),identityStatus:l(t.identityStatus),nextCursor:t.nextCursor,presentation:e.getPresentation(),returnSurface:e.getReturnSurface(),config:n,copy:l(g.copy),actions:_,defaultRenderer:v,requestRender:()=>b(),onCleanup:e=>{ee.push(e)}}),y=()=>{o=!1;let e=null;for(let n of t)if(n.renderHistoryView){try{e=n.renderHistoryView(ne(g.getModel()))}catch(t){c(`renderHistoryView`,t),e=null}if(e)break}let n=!e||e.contains(g.element);return o=n,g.setDomRenderEnabled(n),e??g.element};function b(){if(!(!a||r||i)){i=!0;try{f();let t=y();if(t===s)return;let n=s;s=t,e.onElementChanged(t,n)}finally{i=!1}}}return a=!0,b(),{view:g,get element(){return s??g.element},requestRender:b,dispose:()=>{r=!0,f()}}}const f=/* @__PURE__ */ new Map([[`not_found`,`not_found`],[`conversation_deleted`,`not_found`],[`rate_limited`,`rate_limited`],[`authentication_required`,`authentication_required`],[`invalid_identity_proof`,`authentication_required`],[`visitor_identity_mismatch`,`authentication_required`],[`visitor_required`,`authentication_required`],[`identity_provider_failed`,`identity_provider_failed`],[`proof_not_admitted`,`proof_not_admitted`],[`identity_contract_violation`,`proof_not_admitted`],[`unauthorized`,`authentication_failed`],[`visitor_token_missing`,`authentication_failed`],[`conversation_credential_missing`,`authentication_failed`]]),p=/* @__PURE__ */ new Map([[`not_found`,`That conversation is no longer available.`],[`rate_limited`,`Too many history requests.`],[`authentication_failed`,`History access was not authorized.`],[`authentication_required`,`Sign in again to view account history.`],[`identity_provider_failed`,`The identity provider did not respond.`],[`proof_not_admitted`,`Account history is not available for this configuration.`],[`unsupported_scope`,`This history scope is not supported.`],[`unavailable`,`Conversation history is unavailable right now.`]]),m=e=>p.get(e)??`Conversation history is unavailable right now.`;function h(e,{HistoryClientError:t,HistoryProviderError:n}){if(e instanceof n)return e;if(e instanceof t){let t=f.get(e.code)??`unavailable`;return new n(t,m(t),{...e.retryAfterSeconds===void 0?{}:{retryAfterSeconds:e.retryAfterSeconds}})}return new n(`unavailable`,m(`unavailable`))}function te(e){let{HistoryProviderError:t}=e.errors,n=()=>e.getClient?.()??e.client,r=e.getIdentityProofConfigured()?[`browser`,`verified-user`]:[`browser`],o={scopes:r},s=e=>{if(!r.includes(e))throw new t(`unsupported_scope`,m(`unsupported_scope`))},c=async(t,n)=>{s(t);try{return await n()}catch(t){throw h(t,e.errors)}},l=t=>{let n=!1;return{conversationId:t.session.conversationId??``,conversationRevision:t.session.conversationRevision??``,async commit(){n||(n=!0,t.commit(),await e.onActivationCommitted(t.session))},discard(){n||(n=!0,t.discard())}}};return{capabilities:o,getIdentityStatus(){return n().getHistoryIdentityStatus()},subscribeIdentityStatus(e){return n().subscribeHistoryIdentityStatus(e)},subscribeAvailability(e){return n().subscribeHistoryAvailability(e)},async list(e){return c(e.context.scope,async()=>{let t=await n().listConversations({...e.cursor?{cursor:e.cursor}:{},...e.limit===void 0?{}:{limit:e.limit},...e.targetId?{targetId:e.targetId}:{},scope:e.context.scope});return{items:t.data,nextCursor:t.nextCursor}})},async getPage(e,t){return c(t.context.scope,async()=>{let r=await n().getConversation(e,{...t.cursor?{messageCursor:t.cursor}:{},scope:t.context.scope}),o=i(r.messages,{...t.beforeCreatedAt?{beforeCreatedAt:t.beforeCreatedAt}:{}});return{summary:r.summary,messages:a([],o),conversationRevision:r.conversationRevision??``,nextCursor:r.nextMessageCursor}})},async prepareOpen(e,t){return c(t.context.scope,async()=>l(await n().prepareConversationSession(e)))},async prepareStartNew(e){return c(e.context.scope,async()=>l(await n().prepareNewConversationSession()))},async delete(e,t){await c(t.context.scope,()=>n().deleteConversation(e,{scope:t.context.scope}))},async deleteAll(e){return c(e.context.scope,()=>n().deleteAllConversations({...e.targetId===void 0?{}:{targetId:e.targetId},scope:e.context.scope}))},async resetDevice(){try{return await n().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}const g=i=>{let a=s(i.config.features?.history?.copy),c=null,l=!1,u=null,d=null,f=`conversation`,p=null,m=null,h=null,g=null,_=0,v=null,ne=null,y=null,b=`persona-history-${Math.random().toString(36).slice(2,8)}`,x=()=>i.historyFeatureEnabled()&&!!c&&!l,re=()=>{let e=i.session.getStatus();return i.isStreaming||e===`paused`||e===`resuming`},ie=()=>{let e=i.config.features?.history?.scope;if(e)return e;let t=i.config.getIdentityProof?`verified-user`:`browser`,n=c?.capabilities.scopes;return!n||n.includes(t)?t:n[0]??t},S=()=>d?.scope??ie(),ae=()=>i.session.getClientSession()?.targetId??null,oe=e=>`${e.state}:${`reason`in e?e.reason:``}`,se=e=>{let t=oe(e);t!==g&&(g=t,i.eventBus.emit(`history:identityStatusChanged`,{status:e,timestamp:Date.now()}))},ce=null,le=null,ue=()=>{if(!i.historyFeatureEnabled())return null;let e=i.getHistoryProviderFactory();if(e)return e();let t=i.config.features?.history?.provider;return t?typeof t==`function`?(ce!==t&&(ce=t,le=t()),le):t:i.session.isClientTokenMode()?te({errors:i.historyErrors,client:i.session.getClient(),getIdentityProofConfigured:()=>typeof i.config.getIdentityProof==`function`,onActivationCommitted:e=>i.session.bindActivatedSession(e),getClient:()=>i.session.getClient()}):null},de=()=>{ne?.(),ne=null,y?.(),y=null,l=!1;let e=c;c=ue(),e&&e!==c&&i.discardConversationContinuity();let t={...i.historyInternals};c?t.historyProvider=c:delete t.historyProvider,i.historyInternals=t,i.session.setHistoryInternals(i.historyInternals),c&&(ne=c.subscribeAvailability?.(e=>{l=!e,e||q({restoreFocus:!1}),$()})??null,y=c.subscribeIdentityStatus(e=>se(e)),g=oe(c.getIdentityStatus()))},fe=()=>{let e=i.config.features?.history?.presentation??`panel`;if(e===`panel`||e===`auto`&&i.launcherEnabled&&!i.isDockedMountMode(i.config))return`panel`;let t=i.artifactSplitRoot??i.container;return(t.getBoundingClientRect().width||t.clientWidth)>=720?`rail`:`panel`},C=(e,t)=>{t?(e.setAttribute(`aria-hidden`,`true`),e.setAttribute(`inert`,``)):(e.removeAttribute(`aria-hidden`),e.removeAttribute(`inert`))},pe=`data-persona-history-suppressed`,w=null,T=null,E=null,D=null,me=null,he=``,ge=()=>i.header===me?he:o(i.config)?``:`none`,_e=()=>i.historyPresentation===`panel`&&!!E&&D===E.element&&o(i.config)&&ge()!==`none`,ve=()=>{for(let e of Array.from(i.header.children))e!==w&&e.setAttribute(pe,``)},ye=()=>{for(let e of Array.from(i.container.querySelectorAll(`[${pe}]`)))e.removeAttribute(pe)},be=()=>{let e=E;if(!e)return;if(Array.from(i.header.children).some(e=>e!==w&&!e.hasAttribute(pe))){T&&T!==i.header&&(T.style.removeProperty(`min-height`),T=null);let e=i.header.offsetHeight;e>0&&(i.header.style.minHeight=`${e}px`,T=i.header)}w||=n(`div`,`persona-history-header-host`),e.setHeaderPlacement(`external`);let t=e.getHeaderElement();t.parentNode!==w&&w.replaceChildren(t),w.parentNode!==i.header&&i.header.appendChild(w),ve()},xe=()=>{T&&=(T.style.removeProperty(`min-height`),null),w&&(E?.setHeaderPlacement(`inline`),w.remove(),w=null,ye())},Se=null,Ce=()=>{Se&&(i.body.style.display=`none`,C(i.body,!0),i.footer.hidden=!0,C(i.footer,!0),i.panelSuggestions.style.display=`none`,C(i.panelSuggestions,!0),i.panelSuggestionsFade.style.display=`none`,_e()?(be(),i.header.style.display=ge(),C(i.header,!1)):(xe(),i.header.style.display=`none`,C(i.header,!0)))};i.reapplyHistoryHostChrome=Ce;let we=e=>{let t=i.body.style.display,n=i.footer.hidden,r=i.panelSuggestions.style.display,a=i.panelSuggestionsFade.style.display,s=i.footer,c=i.header,l=i.header.style.display;me=c,he=l,Se=()=>{Se=null,xe(),me=null,i.body.style.display=t,C(i.body,!1),i.panelSuggestions.style.display=r,C(i.panelSuggestions,!1),i.panelSuggestionsFade.style.display=a,s.hidden=n,C(s,!1),i.footer!==s&&(i.footer.hidden=!1,C(i.footer,!1)),c.style.display=l,C(c,!1),i.header!==c&&(i.header.style.display=o(i.config)?``:`none`,C(i.header,!1))},i.container.insertBefore(e,i.footer.parentNode===i.container?i.footer:i.panelSuggestions),Ce()},O=null,k=null,Te=null,A=null,Ee=()=>[i.header,i.panelElements.closeButtonWrapper,i.panelElements.clearChatButtonWrapper,i.body,i.footer,i.scrollToBottomButton],De=()=>i.config.features?.history?.rail?.collapsible!==!1,j=()=>i.config.features?.history?.rail?.side===`right`?`right`:`left`,Oe=e=>Math.min(400,Math.max(200,Math.round(e))),ke=()=>i.config.features?.history?.rail?.resizable===!0,M,Ae=()=>{if(M===void 0&&(M=null,i.config.persistState!==!1))try{let e=Number(window.localStorage.getItem(`${i.currentKeyPrefix()}rail-width`));e&&(M=e)}catch{}return M},N=()=>Oe(Ae()??i.config.features?.history?.rail?.width??260),je=e=>{if(M=e,i.config.persistState!==!1)try{window.localStorage.setItem(`${i.currentKeyPrefix()}rail-width`,String(e))}catch{}},Me=()=>De()&&i.config.features?.history?.rail?.collapsedBehavior===`overlay`,P=!1,Ne=e=>{let t=n(`img`);return t.src=e,t.alt=``,t.setAttribute(`aria-hidden`,`true`),t},Pe=()=>{let e=i.config.features?.history?.rail?.brand;if(!e)return;let t=!1,n;return r=>{if(e.render)try{return e.render({collapsed:r})??null}catch(e){return t||(t=!0,console.warn(`[persona] history rail brand threw`,e)),null}return n===void 0&&(n=e.iconUrl?Ne(e.iconUrl):e.icon?i.renderLucideIcon(e.icon,20):null),n?n.cloneNode(!0):null}},Fe=()=>i.config.features?.history?.rail?.sections?.map(e=>{let t=!1,n=n=>{t||(t=!0,console.warn(`[persona] history rail section threw`,e.id,n))};return{id:e.id,title:e.title,placement:e.placement??`above-conversations`,items:e.items.map(e=>{let t;return{id:e.id,label:e.label,badge:e.badge,iconNode:()=>{if(t!==void 0)return t;try{t=e.renderIcon?e.renderIcon()??null:e.iconUrl?Ne(e.iconUrl):e.icon?i.renderLucideIcon(e.icon,20):null}catch(e){n(e),t=null}return t},onSelect:()=>{try{e.onSelect()}catch(e){n(e)}}}})}})??[],Ie=e=>{let t=Fe();for(let n of e)t.some(e=>e.id===n.id)?console.warn(`[persona] duplicate history rail section id`,n.id):t.push(n);return t.length?t:void 0},F=null,Le=()=>`${i.currentKeyPrefix()}rail-collapsed`,Re=()=>{if(F===null&&(F=i.config.features?.history?.rail?.defaultCollapsed===!0,i.config.persistState!==!1))try{let e=window.localStorage.getItem(Le());e&&(F=e===`1`)}catch{}return F},ze=e=>{if(F=e,i.config.persistState!==!1)try{window.localStorage.setItem(Le(),e?`1`:`0`)}catch{}},I=()=>i.historyPresentation===`rail`&&De()&&!Me()&&Re(),Be=()=>{},Ve=()=>{Me()?Be():(ze(!Re()),u?.view.setCollapsed(I()),i.applyRailChrome(),i.repinAnchoredMessage())},He=()=>{let e=i.config.features?.history?.rail?.collapseShortcut;return!e||!i.parseCombo(e)?null:{combo:e,hint:i.formatCombo(e),aria:i.ariaCombo(e)}},Ue=`var(--persona-history-overlay-margin,8px)`,L=null,R=null,We=0,z=null,B=null,V=!1,Ge=0,Ke=()=>window.matchMedia?.(`(pointer: coarse)`).matches===!0,H=()=>x()&&Me()&&(i.historyPresentation??fe())===`rail`,qe=()=>i.historyVisible&&!P,U=()=>{B!==null&&clearTimeout(B),B=null},Je=()=>{i.loadHistoryView().catch(()=>{})},Ye=()=>{U(),P&&(B=setTimeout(()=>{B=null,!V&&P&&(z?.contains(document.activeElement)||q({restoreFocus:!1}))},300))},Xe=(e,t)=>{let n=z?.getBoundingClientRect();if(!n)return!1;let r=L?.getBoundingClientRect(),i=r?Math.min(r.top,n.top):n.top;return e>=n.left&&e<=n.right&&t>=i&&t<=n.bottom||!!r&&e>=r.left&&e<=r.right&&t>=r.top&&t<=r.bottom},Ze=e=>{P&&(V=Xe(e.clientX,e.clientY),V?U():B===null&&Ye())},Qe=e=>{!i.historyVisible&&H()&&(P=!0,K({invoker:L,keyboard:e?.keyboard===!0}).then(()=>{i.historyVisible?!V&&document.activeElement!==L&&q():P=!1}))},$e=()=>{let e=D?.querySelector(`[data-persona-history-focus="collapse"]`);e&&(e.setAttribute(`aria-label`,P?a.expandLabel:a.collapseLabel),e.setAttribute(`aria-expanded`,P?`false`:`true`))},et=()=>{ze(!1);let e=u;if(!P||!e){K({invoker:L});return}let t=document.activeElement===L;P=!1,ft(),e.element.remove(),mt(e.element),$e(),t&&_t(),i.repinAnchoredMessage(),$()},tt=()=>{ze(!0),q()};Be=()=>{!i.historyVisible||P?et():tt()};let nt=()=>{let e=He(),t=i.createHeaderIconButton({ariaLabel:a.expandLabel,iconName:`panel-left`,wrapperClassName:`persona-relative persona-inline-flex persona-items-center persona-justify-center`,extraClassName:`persona-rail-trigger`,tooltip:!1,attrs:{"data-persona-rail-trigger":``,"aria-controls":b,...e?{"aria-keyshortcuts":e.aria}:{}}}),n=t.button;n.addEventListener(`mouseenter`,()=>{V=!0,U(),!(Ke()||Date.now()<Ge)&&Qe()}),n.addEventListener(`mouseleave`,()=>{V=!1,Ge=0,Ye()}),n.addEventListener(`focus`,()=>{i.historyVisible||Je()}),n.addEventListener(`click`,e=>{x()&&(e.detail!==0&&Ke()&&!i.historyVisible?Qe():et())}),L=n,R=t.wrapper},W=()=>{if(R&&!R.isConnected&&(R=null,L=null),!H()){R?.remove(),R=null,L=null;return}L||nt();let e=R,t=L;if(!e||!t)return;let n=j()===`right`?null:i.header.firstChild;(n??i.header.lastChild)!==e&&i.header.insertBefore(e,n),e.style.display=qe()||We>0?`none`:``,t.setAttribute(`aria-label`,a.expandLabel),t.setAttribute(`aria-expanded`,i.historyVisible?`true`:`false`),z&&i.applyRailChrome()},rt=e=>{if(!P)return;let t=e.target;t instanceof Node&&(z?.contains(t)||R?.contains(t)||t instanceof Element&&t.closest(`.persona-dropdown-menu,[role="alertdialog"]`)||q({restoreFocus:!1}))};document.addEventListener(`pointerdown`,rt,!0),i.destroyCallbacks.push(()=>{document.removeEventListener(`pointerdown`,rt,!0),document.removeEventListener(`pointermove`,Ze),G?.(),U()});let it=null,G=null,at=e=>{je(Oe(e)),i.applyRailChrome(),i.repinAnchoredMessage()},ot=()=>{let e=n(`div`,`persona-rail-resizer`);return e.tabIndex=0,e.setAttribute(`role`,`separator`),e.setAttribute(`aria-orientation`,`vertical`),e.setAttribute(`aria-valuemin`,`200`),e.setAttribute(`aria-valuemax`,`400`),e.addEventListener(`pointerdown`,t=>{let n=k;if(!n||t.button!==0)return;t.preventDefault(),G?.();let r=t.clientX,a=n.getBoundingClientRect().width||N(),o=j()===`right`?-1:1,s=a,c=i.mount.ownerDocument;n.style.transition=`none`;let l=t=>{s=Oe(a+o*(t.clientX-r)),n.style.flex=`0 0 ${s}px`,e.setAttribute(`aria-valuenow`,String(s))},u=()=>{G=null,c.removeEventListener(`pointermove`,l),c.removeEventListener(`pointerup`,u),c.removeEventListener(`pointercancel`,u),n.style.removeProperty(`transition`);try{e.releasePointerCapture(t.pointerId)}catch{}at(s)};G=u,c.addEventListener(`pointermove`,l),c.addEventListener(`pointerup`,u),c.addEventListener(`pointercancel`,u);try{e.setPointerCapture(t.pointerId)}catch{}}),e.addEventListener(`keydown`,e=>{let t=j()===`right`?-16:16,n=N(),r=e.key===`ArrowRight`?n+t:e.key===`ArrowLeft`?n-t:e.key===`Home`?200:e.key===`End`?400:null;r!==null&&(e.preventDefault(),at(r))}),e},st=(e,t)=>{if(!ke()||I()){G?.(),it?.remove();return}let n=it??ot();it=n,n.setAttribute(`aria-label`,a.resizeLabel),n.setAttribute(`aria-valuenow`,String(N())),n.nextElementSibling!==t&&e.insertBefore(n,t)};i.applyRailChrome=()=>{u?.view.setRailSide(j());let e=j()===`right`,t=z;if(t){let n=L?L.getBoundingClientRect().bottom-i.container.getBoundingClientRect().top:0;t.style.top=`calc(${Math.max(0,Math.round(n))}px + ${Ue})`,t.style.width=`${N()}px`,t.style.left=e?``:Ue,t.style.right=e?Ue:``}let n=k,r=O,a=Te;if(!n||!r||!a)return;n.style.flex=`0 0 ${I()?52:N()}px`;let o=`1px solid var(--persona-divider,#e5e7eb)`;n.style.borderRight=e?``:o,n.style.borderLeft=e?o:``;let s=e?a:n;r.firstElementChild!==s&&r.append(s,e?n:a),st(r,e?n:a)};let ct=e=>{if(A&&k){A.replaceWith(e),A=null,i.applyRailChrome();return}let t=n(`div`,`persona-history-rail-shell`);t.style.cssText=`display:flex;flex-direction:row;flex:1 1 auto;min-height:0`;let r=n(`div`,`persona-history-rail-conversation`);r.style.cssText=`display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative`;let a=n(`div`,`persona-history-rail-host`);a.style.cssText=`display:flex;min-height:0;overflow:hidden`,i.container.insertBefore(t,i.header.parentNode===i.container?i.header:i.body);for(let e of Ee())e?.parentNode===i.container&&r.appendChild(e);t.append(a,r),a.appendChild(e),O=t,k=a,Te=r,i.applyRailChrome()},lt=()=>{if(O)return;let e=n(`div`,`persona-history-rail-placeholder`);e.style.cssText=`flex:1 1 auto;min-height:0`,A=e,ct(e),i.repinAnchoredMessage()},ut=()=>{A&&(ft(),i.repinAnchoredMessage())},dt=e=>{let t=n(`div`,`persona-history-rail-overlay`);t.style.cssText=`position:absolute;bottom:${Ue};display:flex;overflow:hidden;z-index:${r-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,i.container.style.position=`relative`,i.container.appendChild(t),t.appendChild(e),document.addEventListener(`pointermove`,Ze),z=t,i.applyRailChrome(),$e()},ft=()=>{Se?.(),z&&=(V&&(Ge=Date.now()+150),document.removeEventListener(`pointermove`,Ze),z.remove(),null);let e=O;if(e){G?.();for(let t of Ee())if(t&&e.contains(t)){let n=t===i.scrollToBottomButton?i.panelSuggestions:e;i.container.insertBefore(t,n)}e.remove(),O=null,k=null,Te=null,A=null}},pt=e=>{D=e,e.id=b,e.style.flex=`1 1 auto`,e.style.minHeight=`0`},mt=e=>{pt(e),(i.historyPresentation!==`rail`||P)&&ut(),i.historyPresentation===`rail`?P?dt(e):ct(e):we(e)},ht=()=>{if(W(),Ht(),!i.historyVisible||!u)return;let e=fe();if(e===i.historyPresentation)return;let t=document.activeElement,n=t instanceof HTMLElement&&(u.element.contains(t)||w?.contains(t)===!0)?t:null;ft(),u.element.remove(),u.view.setHeaderPlacement(`inline`),i.historyPresentation=e,u.view.setPresentation(e),u.view.setCollapsed(I()),u.requestRender(),u.element.isConnected||mt(u.element),n?.isConnected?n.focus():_t(),i.syncScrollToBottomButton(),i.repinAnchoredMessage(),$()},gt=(e,t)=>w?.querySelector(t)??e.querySelector(t),_t=()=>{let e=u?.element??D;if(!e)return;let t=gt(e,`[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]`);if(t){t.focus();return}let n=gt(e,`.persona-history-title`)??e;n.tabIndex=-1,n.focus()},K=async e=>{if(!x()||i.historyVisible)return;let t=c;if(!t)return;if(!P&&H()&&Re()){W();return}vt();let n=++_;f=e?.returnSurface??`conversation`,p=e?.invoker??m;let r=H()&&!P;r&&(We+=1,W(),lt());let s;try{s=await i.loadHistoryView()}catch{i.announceHistory(a.openHistoryLabel),r&&(--We,n===_&&(ut(),W()));return}if(r&&--We,n!==_||i.historyVisible)return;d={scope:ie()},i.historyPresentation=fe(),i.historyVisible=!0;let l=i.historyPresentation===`panel`&&o(i.config)&&i.header.style.display!==`none`?`external`:`inline`,h=i.config.features?.history?.rowAvatar,te=He(),g=te?{hint:te.hint,aria:te.aria}:null,v={provider:t,context:d,targetId:ae(),presentation:i.historyPresentation,collapsible:De(),collapsed:I(),railSide:j(),renderRailHeader:i.config.features?.history?.rail?.renderHeader,railBrand:Pe(),onToggleCollapse:Ve,...g?{collapseShortcut:g}:{},headerPlacement:l,showScopeStatus:i.config.features?.history?.showScopeStatus!==!1,showDelete:i.config.features?.history?.showDelete!==!1,showDeleteAll:i.config.features?.history?.showDeleteAll!==!1,...i.config.features?.history?.listActions?.length?{listActions:i.config.features.history.listActions}:{},rowAvatar:h===!1?!1:typeof h==`string`?h:i.config.launcher?.iconUrl,activeConversationId:i.session.getActiveConversationId(),...i.config.features?.history?.grouping?{grouping:i.config.features.history.grouping}:{},...i.config.features?.history?.copy?{copy:i.config.features.history.copy}:{},...i.config.features?.history?.pageSize===void 0?{}:{pageSize:i.config.features.history.pageSize},onSelect:e=>At(e,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:e=>i.setActiveConversationSummary(e),attachTooltip:i.attachTooltip,onStartNew:()=>jt({focusComposer:!0}),onClose:()=>q(),onRequestDeleteConversation:e=>Rt(e),onRequestClearHistory:()=>zt(),...t.resetDevice?{onRequestResetIdentity:()=>Bt()}:{}};u=ee({plugins:i.plugins,config:i.config,getPresentation:()=>i.historyPresentation??`panel`,getReturnSurface:()=>f,close:()=>q(),createView:({slots:e,renderDom:t,onModelChange:n,railSections:r})=>(E=s.createHistoryView({...v,railSections:Ie(r),slots:e,renderDom:t,onModelChange:n,onAnnounce:i.announceHistory}),E),onElementChanged:(e,t)=>{if(!t?.isConnected)return mt(e);pt(e),t.replaceWith(e),Ce()}}),u.view.setNewConversationRequired(i.historySessionState.recovery===`new_conversation_required`),e?.focus!==!1&&(i.historyPresentation!==`rail`||e?.keyboard===!0)&&_t(),i.syncScrollToBottomButton(),i.repinAnchoredMessage(),$(),i.eventBus.emit(`history:opened`,{presentation:i.historyPresentation,returnSurface:f,timestamp:Date.now()})},vt=()=>{},q=e=>{if(!i.historyVisible)return;_+=1;let t=f,n=p,r=u,a=e?.restoreFocus!==!1;i.historyVisible=!1;let o=!1,s=null,c=()=>{if(!o){if(o=!0,vt=()=>{},s!==null&&clearTimeout(s),P=!1,U(),ft(),r?.dispose(),r?.view.destroy(),r?.element.remove(),u===r&&(u=null,E=null,D=null,i.historyPresentation=null,d=null,p=null),i.syncScrollToBottomButton(),i.repinAnchoredMessage(),$(),a){let e=n??m;e?.isConnected?e.focus():i.maybeFocusInput()}i.eventBus.emit(`history:closed`,{returnSurface:t,timestamp:Date.now()})}},l=r&&r.element===r.view.element?r.view.playExit():null;l?(vt=c,s=setTimeout(c,250),l.then(c)):c()},yt=e=>{if(e.key===`Escape`&&i.historyVisible&&u){if(i.historyPresentation===`rail`){let t=e.target;if(!(t instanceof Node)||!(u.element.contains(t)||P&&R?.contains(t)===!0))return}e.preventDefault(),e.stopPropagation(),q()}};i.container.addEventListener(`keydown`,yt),i.destroyCallbacks.push(()=>i.container.removeEventListener(`keydown`,yt));let J=0,Y=null,bt=null,xt=()=>{bt&&clearTimeout(bt),bt=null};i.destroyCallbacks.push(xt);let St=()=>{xt();let e=i.conversationOpenPendingEl;e&&(i.conversationOpenTakeover=!0,e.hidden=!1,i.messagesWrapper.style.display=`none`,i.updateWelcome())},X=()=>{J+=1,xt(),Y?.remove(),Y=null,i.conversationOpenPendingEl&&(i.conversationOpenPendingEl.remove(),i.conversationOpenPendingEl=null,i.conversationOpenTakeover=!1,i.messagesWrapper.style.removeProperty(`display`),C(i.footer,!1),i.updateWelcome())},Ct=()=>{try{if(window.matchMedia?.(`(prefers-reduced-motion: reduce)`)?.matches)return;i.messagesWrapper.animate([{opacity:0},{opacity:1}],{duration:150,easing:`ease-out`})}catch{}},wt=n=>{let r=i.config.layout?.messages?.layout??`bubble`,a=t(`div`,{className:`persona-flex`,attrs:{"aria-hidden":`true`}});i.applyMessageRowLayout(a,n);let o=t(`div`,{className:e(i.getBubbleClasses(n,r).join(` `),`persona-conversation-loading-bubble`),attrs:{"data-persona-theme-zone":`${n}-message`},style:{width:n===`user`?`64%`:`100%`,backgroundColor:r===`flat`?`transparent`:`var(--persona-message-${n}-bg, var(--persona-${n===`user`?`accent`:`container`}))`,color:`var(--persona-message-${n}-text, ${n===`user`&&r!==`flat`?`white`:`var(--persona-text)`})`}},...[`94%`,...n===`assistant`?[`86%`]:[],`62%`].map(e=>t(`div`,{className:`persona-conversation-loading-line`,style:{width:e}})));return i.applyBubbleGeometry(o,n,r,{...i.resolveThemeDefaults(i.config.future).components.message[n],...i.config.theme?.components?.message?.[n],...i.config.darkTheme?.components?.message?.[n]}),a.appendChild(o),a},Tt=()=>t(`div`,{className:`persona-conversation-loading-body`,style:{gap:i.messagesWrapper.style.gap}},wt(`user`),wt(`assistant`),wt(`user`),wt(`assistant`)),Et=()=>i.config.loadingIndicator?.conversationOpenVariant===`skeleton`?Tt():t(`div`,{className:`persona-conversation-loading-spinner`,attrs:{"aria-hidden":`true`}},t(`span`,{className:`persona-conversation-loading-ring`})),Dt=e=>{i.conversationOpenPendingEl?.remove(),i.conversationOpenPendingEl=e,e.hidden=!i.conversationOpenTakeover,i.body.insertBefore(e,i.messagesWrapper),xt(),i.conversationOpenTakeover||(bt=setTimeout(St,250)),C(i.footer,!0)},Ot=()=>{let n={config:i.config,streaming:!1,location:`conversation-open`,defaultRenderer:Et},r=null,o=i.plugins.find(e=>e.renderLoadingIndicator);o?.renderLoadingIndicator&&(r=o.renderLoadingIndicator(n)),r===null&&i.config.loadingIndicator?.render&&(r=i.config.loadingIndicator.render(n));let s=r??Et();Dt(t(`div`,{className:e(`persona-conversation-loading`,s.classList.contains(`persona-conversation-loading-spinner`)&&`persona-conversation-loading--centered`),attrs:{role:`status`,"aria-label":a.openConversationLoadingLabel},style:{maxWidth:i.messagesWrapper.style.maxWidth||`none`}},s))},kt=e=>{let n=()=>{At(e,{focusComposer:!0}).catch(()=>{})},r=x()?()=>{X(),K()}:void 0,o=(e,n)=>{let r=t(`button`,{className:`persona-conversation-loading-error-action`,attrs:{type:`button`},text:e});return r.addEventListener(`click`,n),r},s=()=>t(`div`,{className:`persona-conversation-loading-error-body`},t(`p`,{className:`persona-conversation-loading-error-title`,text:a.openConversationErrorTitle}),t(`div`,{className:`persona-conversation-loading-error-actions`},o(a.openConversationRetryLabel,n),r?o(a.openConversationBackLabel,r):null)),c=Object.freeze({conversationId:e,config:i.config,copy:Object.freeze({title:a.openConversationErrorTitle,retryLabel:a.openConversationRetryLabel,backLabel:a.openConversationBackLabel}),retry:n,...r?{back:r}:{},defaultRenderer:s}),l=null;for(let e of i.plugins)if(e.renderHistoryOpenError){try{l=e.renderHistoryOpenError(c)}catch(e){console.warn(`[persona] renderHistoryOpenError threw`,e),l=null}if(l)break}if(Y?.remove(),Y=t(`div`,{className:`persona-conversation-loading-error`,attrs:{role:`alert`}},l??s()),!i.session.getActiveConversationId()&&i.session.getMessages().length===0&&!i.composerStore.getState().text&&!i.attachmentManager?.hasAttachments()){let e=Y;Y=null,Dt(e),St()}else i.body.insertBefore(Y,i.messagesWrapper);i.announceHistory(a.openConversationErrorTitle)};i.eventBus.on(`history:closed`,()=>{i.conversationOpenPendingEl&&C(i.footer,!0)});let At=async(e,{focusComposer:t=!1,busy:n=`reject`}={})=>{let r=S();if(n===`background`&&(i.session.assertBackgroundSwitchable(),i.composerStore.getState().phase===`preparing`))throw new i.SessionHistoryError(`conversation_busy`,`Finish preparing this turn before switching conversations`);if(n===`reject`&&(i.session.isStreaming()||[`paused`,`resuming`].includes(i.session.getStatus())||i.composerStore.getState().phase===`preparing`))throw new i.SessionHistoryError(`conversation_busy`,`Finish or stop the current turn before switching conversations`);n===`stop`&&(++i.composerConversationGeneration,i.submissionAbort?.abort(),i.submissionAbort=null,i.composerStore.setPreparing(!1),i.session.cancel());let a=i.conversationStateKey();(!i.conversationOpenPendingEl||i.pendingConversationReading?.key!==a)&&(i.pendingConversationReading={key:a,reading:i.captureConversationReading()});let o=null,s=!!u;u?.view.setActiveConversationId(e),X();let c=J;Ot(),i.historyVisible&&(i.historyPresentation===`panel`||P)&&q({restoreFocus:!1}),i.suppressScrollSend=!0;try{await i.session.openConversation(e,{scope:r,busy:n,onBeforeCommit:()=>{i.saveConversationContinuity(),o=i.composerConversationGeneration,i.conversationPersistenceOwner=o},onCommitted:()=>{i.restoreConversationContinuity(),i.conversationPersistenceOwner===o&&(i.conversationPersistenceOwner=null),i.usesSessionVoiceForConfig(i.config)&&i.session.setupVoice(),i.persistState()}})}catch(t){if(i.conversationPersistenceOwner===o&&(i.conversationPersistenceOwner=null),o===i.composerConversationGeneration&&i.usesSessionVoiceForConfig(i.config)&&i.session.setupVoice(),c===J){let t=i.pendingConversationReading?.reading;X(),t&&i.restoreConversationReading(t),i.pendingConversationReading=null,u?.view.setActiveConversationId(i.session.getActiveConversationId()),kt(e),i.suppressScrollSend=!1}throw t}finally{(c===J||!i.conversationOpenPendingEl)&&(i.suppressScrollSend=!1)}c===J&&(X(),i.pendingConversationReading=null,i.messageCache.clear(),Ct(),Q(),s||i.setActiveConversationSummary(null),i.eventBus.emit(`history:conversationOpened`,{conversationId:e,title:i.activeConversationTitle,scope:r,timestamp:Date.now()}),t&&i.maybeFocusInput())},jt=async({focusComposer:e=!1}={})=>{X();let t=null;try{await i.session.startNewConversation({scope:S(),onBeforeCommit:()=>{i.saveConversationContinuity(),t=i.composerConversationGeneration,i.conversationPersistenceOwner=t},onCommitted:()=>{i.restoreConversationContinuity(!0),i.conversationPersistenceOwner===t&&(i.conversationPersistenceOwner=null),i.usesSessionVoiceForConfig(i.config)&&i.session.setupVoice(),i.persistState(),i.pendingConversationReading=null}})}catch(e){throw i.conversationPersistenceOwner===t&&(i.conversationPersistenceOwner=null),t===i.composerConversationGeneration&&i.usesSessionVoiceForConfig(i.config)&&i.session.setupVoice(),e}i.setActiveConversationSummary(null),i.messageCache.clear(),i.resetAnchorState(),i.resumeAutoScroll(),i.jumpToBottomInstant(),Q();let n=i.session.getActiveConversationId();u?.view.setActiveConversationId(n),i.eventBus.emit(`history:conversationStarted`,{conversationId:n,timestamp:Date.now()}),i.historyVisible&&(i.historyPresentation===`panel`||P)&&q({restoreFocus:!1}),e&&i.maybeFocusInput()},Mt=async(e,t)=>{let n=await i.session.updateConversation(e,{...t,...t.title===void 0?{}:{title:t.title.trim()}});return u?.view.applyConversationSummary(n),!u&&e===i.session.getActiveConversationId()&&i.setActiveConversationSummary(n),n},Nt=async e=>{let t=S(),n=i.session.getActiveConversationId()===e;await i.session.deleteConversation(e,{scope:t}),i.discardConversationContinuity(e),n&&(i.attachmentManager?.destroy({release:!0}),i.attachmentManager=null,i.restoreConversationContinuity(!0)),u?.view.removeConversationSummary(e),n&&(i.setActiveConversationSummary(null),i.messageCache.clear(),i.resetAnchorState(),i.resumeAutoScroll(),Q()),i.eventBus.emit(`history:conversationDeleted`,{conversationId:e,scope:t,wasActive:n,timestamp:Date.now()})},Pt=async e=>{let t=e?.scope??S(),n=e?.allTargets?null:e?.targetId??ae(),r=await i.session.clearConversationHistory({...n?{targetId:n}:{},scope:t});return i.discardConversationContinuity(),i.setActiveConversationSummary(null),i.messageCache.clear(),i.resetAnchorState(),i.resumeAutoScroll(),Q(),i.eventBus.emit(`history:cleared`,{deleted:r.deleted,scope:t,targetId:n,timestamp:Date.now()}),r},Ft=async()=>{if(!c?.resetDevice)throw Error(`[Persona] resetHistoryIdentity() requires a history provider that can reset this device`);let e=!1;try{e=(await i.session.resetHistoryDevice()).remoteRevocationConfirmed}finally{i.discardConversationContinuity(),X(),i.setActiveConversationSummary(null),i.session.clearArtifacts(),i.messageCache.clear(),i.lastAppliedMessages=null,i.config.clearStoredSessionId?.(),i.config.clearStoredConversationId?.(),i.persistentMetadata={},i.actionManager.syncFromMetadata(),i.clearPersistedDraft();let e=i.storageAdapter;e?.clear&&i.runStorageMutation(()=>e.clear(),`[AgentWidget] Failed to clear storage adapter:`),i.resetAnchorState(),i.resumeAutoScroll(),Q(),q({restoreFocus:!1}),i.maybeFocusInput(),i.open||i.launcherSurfaceInstance?.launcher.element.focus()}return i.announceHistory(e?a.identityResetNotice:a.identityResetUnconfirmedNotice),i.eventBus.emit(`history:identityReset`,{remoteRevocationConfirmed:e,timestamp:Date.now()}),{remoteRevocationConfirmed:e}},It=()=>i.artifactSplitRoot?i.panel:i.container,Lt=async e=>{let t=await i.loadHistoryView().catch(()=>null);return typeof t?.showHistoryConfirm==`function`?t.showHistoryConfirm(e):window.confirm(`${e.title}\n\n${e.description}`)},Rt=async e=>await Lt({host:It(),title:a.deleteConversationConfirmTitle,description:a.deleteConversationConfirm,confirmLabel:a.deleteConversationConfirmLabel,cancelLabel:a.confirmCancelLabel})?(await Nt(e),`deleted`):`cancelled`,zt=async()=>{let e=S()===`verified-user`;return await Lt({host:It(),title:a.clearHistoryConfirmTitle,description:e?a.clearHistoryVerifiedConfirm:a.clearHistoryConfirm,confirmLabel:a.clearHistoryConfirmLabel,cancelLabel:a.confirmCancelLabel})?(await Pt(),`cleared`):`cancelled`},Bt=async()=>{if(!await Lt({host:It(),title:a.resetIdentityConfirmTitle,description:a.resetIdentityConfirm,confirmLabel:a.resetIdentityConfirmLabel,cancelLabel:a.confirmCancelLabel}))return{outcome:`cancelled`};let{remoteRevocationConfirmed:e}=await Ft();return{outcome:`reset`,remoteRevocationConfirmed:e}},Z=n(`button`,`persona-history-earlier`);Z.type=`button`,Z.textContent=a.showEarlierMessagesLabel,Z.setAttribute(`data-persona-history-earlier`,``),Object.assign(Z.style,{alignSelf:`center`,minHeight:`44px`,padding:`0 16px`,borderRadius:`999px`,border:`1px solid var(--persona-border, rgba(0,0,0,0.12))`,background:`transparent`,color:`inherit`,font:`inherit`,cursor:`pointer`,flexShrink:`0`});let Q=()=>{x()&&i.historySessionState.nextMessageCursor&&i.session.getActiveConversationId()?(Z.textContent=a.showEarlierMessagesLabel,Z.parentNode!==i.body&&i.body.insertBefore(Z,i.body.firstChild)):Z.remove()};Z.addEventListener(`click`,()=>{let e=i.session.getActiveConversationId(),t=i.historySessionState.nextMessageCursor;if(!e||!t||Z.disabled)return;Z.disabled=!0;let n=i.body.scrollHeight,r=i.body.scrollTop;i.session.loadOlderMessages(e,t,{scope:S()}).then(()=>{i.body.scrollTop=r+(i.body.scrollHeight-n),i.repinAnchoredMessage()}).catch(()=>{}).finally(()=>{Z.disabled=!1,Q()})});let Vt=()=>{let e=i.createHeaderIconButton({ariaLabel:a.openHistoryLabel,iconName:`history`,wrapperClassName:`persona-relative persona-inline-flex persona-items-center persona-justify-center`,extraClassName:`persona-history-toggle`,attrs:{"data-persona-history-toggle":``}});return e.button.addEventListener(`click`,t=>{x()&&!re()&&(i.historyVisible?q():K({invoker:e.button,keyboard:t.detail===0}))}),e},Ht=()=>{if(!x()){h?.remove(),m=null,h=null;return}if(h&&!h.isConnected&&(m=null,h=null),!m&&i.header){let e=Vt();m=e.button,h=e.wrapper;let t=i.panelElements.clearChatButtonWrapper||i.panelElements.closeButtonWrapper;t?.parentNode&&i.header.contains(t)?t.parentNode.insertBefore(h,t):i.header.appendChild(h)}if(!m||!h)return;let e=H()||i.historyVisible&&i.historyPresentation===`rail`;if(h.style.display=e?`none`:``,e){document.activeElement===m&&_t();return}let t=re();m.disabled=t,m.setAttribute(`aria-disabled`,t?`true`:`false`);let n=t?a.openHistoryBusyLabel:a.openHistoryLabel;m.setAttribute(`aria-label`,n),(i.config.features?.history?.presentation??`panel`)===`panel`?(m.removeAttribute(`aria-expanded`),m.removeAttribute(`aria-controls`)):(m.setAttribute(`aria-expanded`,i.historyVisible?`true`:`false`),m.setAttribute(`aria-controls`,b))},Ut=!1,Wt=()=>{let e=i.panelElements.clearChatButton;e&&(x()?(Ut||=(v=e.getAttribute(`aria-label`)??``,!0),e.setAttribute(`aria-label`,a.newConversationLabel),e.removeAttribute(`title`)):Ut&&(Ut=!1,v&&e.setAttribute(`aria-label`,v)))},$=()=>{a=s(i.config.features?.history?.copy),Ht(),W(),Wt(),Q()};return i.historyChromeSync=$,de(),$(),i.destroyCallbacks.push(()=>{ne?.(),y?.(),_+=1,vt(),u?.dispose(),u?.view.destroy(),u=null}),{clearConversationOpenPending:X,cancelConversationOpenTakeover:xt,historyOperationScope:S,discardConversationContinuity:i.discardConversationContinuity,historyAvailable:x,historyScope:ie,installHistoryProvider:de,syncHistoryChromeImpl:$,syncHistoryPresentation:ht,syncEarlierMessagesPill:Q,openHistory:K,closeHistory:q,openHistoryConversation:At,startNewConversation:jt,updateHistoryConversation:Mt,deleteHistoryConversation:Nt,requestDeleteConversation:Rt,clearConversationHistory:Pt,resetHistoryIdentity:Ft,railCollapseShortcut:He,railCollapsible:De,railTriggerApplies:H,railOverlayMode:Me,toggleRailCollapsed:Ve,toggleRailPinned:()=>Be(),get historyProvider(){return c},get historySurface(){return u},get railShell(){return O},get railHost(){return k},get railColumn(){return Te}}};export{g as createHistoryShell};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=`4.33.0`;export{e as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./chunk-
|
|
1
|
+
import{t as e}from"./chunk-DVgzoVCB.js";const t=32768,n=49152,r=e=>{let t=e??{},n=typeof t.targetId==`string`?t.targetId:null;return{id:typeof t.id==`string`?t.id:``,title:typeof t.title==`string`?t.title:``,targetId:n,preview:typeof t.preview==`string`?t.preview:null,messageCount:typeof t.messageCount==`number`?t.messageCount:0,createdAt:typeof t.createdAt==`string`?t.createdAt:``,updatedAt:typeof t.updatedAt==`string`?t.updatedAt:``}},i=`The identity proof was not admitted; account history is unavailable`,a=`The identity proof was rejected`,o=`The request carried no visitor credential`,s=`The stored visitor belongs to a different signed-in user`;function c(e,t,n){let r=new URLSearchParams;for(let[e,t]of Object.entries(n))t!==void 0&&t!==``&&r.set(e,String(t));let i=r.toString();return`${e.clientApiBase()}/v1/client/${t}${i?`?${i}`:``}`}function l(e,t){return t||e.config.features?.history?.scope||(e.config.getIdentityProof?`verified-user`:`browser`)}async function u(e,t,n){let r=e.config.getIdentityProof;if(!r)return n&&e.setHistoryIdentityStatus(e.browserOnlyStatus()),null;n&&e.setHistoryIdentityStatus({state:`verifying`});let i;try{i=await r()??null}catch{throw n&&e.setHistoryIdentityStatus({state:`identity_provider_failed`}),new e.HistoryClientError(`identity_provider_failed`,`The identity proof provider failed`)}if(i)return i;if(t.visitor?.endUserId!=null)throw n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`authentication_required`,`This browser is bound to a signed-in user and needs a fresh identity proof`);return n&&e.setHistoryIdentityStatus({state:`browser_only`,reason:`proof_unavailable_before_binding`}),null}async function d(e,t,n,r){if(t.visitor?.endUserId!=null)return t;let a=await e.reinitWithProof(n);if(a.visitor?.identityStatus!==`admitted`||a.visitor?.endUserId==null)throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,i);return a}async function f(e,t){let n=await t.json().catch(()=>({}));return typeof n.error==`string`?n.error:typeof n.message==`string`?n.message:``}async function p(e,t,n,r){let i=t.toLowerCase();if(i.includes(`invalid_identity_proof`))throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,a);if(i.includes(`visitor token required`))throw new e.HistoryClientError(`visitor_token_missing`,o);if(i.includes(`visitor_identity_mismatch`)){if(!n)throw r&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`proof_unavailable_after_binding`}),new e.HistoryClientError(`visitor_identity_mismatch`,s);return e.reinitWithProof(n)}if(i.includes(`expired`)||i.includes(`not found`))return e.clearClientSession(),e.initSession();throw new e.HistoryClientError(`unauthorized`,t||`History request was not authorized`)}async function m(e,t,n){let r=await f(e,t);if(t.status===404)return new e.HistoryClientError(`not_found`,`Conversation not found`);if(t.status===429){let n=Number.parseInt(t.headers.get(`Retry-After`)??``,10);return new e.HistoryClientError(`rate_limited`,`Too many history requests`,{...Number.isFinite(n)?{retryAfterSeconds:n}:{}})}if(t.status===503&&r.includes(`identity_proof_not_admitted`))return n&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),new e.HistoryClientError(`proof_not_admitted`,i);if(t.status===401){let t=r.toLowerCase();return t.includes(`invalid_identity_proof`)?(n&&e.setHistoryIdentityStatus({state:`authentication_required`,reason:`invalid_identity_proof`}),new e.HistoryClientError(`invalid_identity_proof`,a)):t.includes(`visitor token required`)?new e.HistoryClientError(`visitor_token_missing`,o):t.includes(`visitor_identity_mismatch`)?new e.HistoryClientError(`visitor_identity_mismatch`,s):new e.HistoryClientError(`unauthorized`,r||`History request was not authorized`)}return new e.HistoryClientError(`request_failed`,r||`History request failed (${t.status})`)}function h(e,t,n,r){let i=t?.toLowerCase()??null;if(n){if(i===`admitted`){r&&e.setHistoryIdentityStatus({state:`verified`});return}throw r&&e.setHistoryIdentityStatus({state:`configuration_error`,reason:`proof_not_admitted`}),i===`ignored`?new e.HistoryClientError(`identity_contract_violation`,`Server reported an ignored identity proof on a success response`):new e.HistoryClientError(`proof_not_admitted`,`The response did not acknowledge the identity proof this request sent`)}if(i===`admitted`)throw new e.HistoryClientError(`identity_contract_violation`,`Server admitted an identity proof that was never sent`);r&&e.setHistoryIdentityStatus(e.browserOnlyStatus())}async function g(t,n,r){_(t);let i=r.trackIdentity!==!1,a=await t.initSession(),o=null;l(t,r.scope)===`verified-user`&&(o=await u(t,a,i),o&&(a=await d(t,a,o,i)));let s=t.historyInternals.visitorStore,g=!1;for(;;){let l=s?.revision()??0,u=await t.readVisitorToken();if(!u&&!r.visitorTokenOptional)throw new t.HistoryClientError(`visitor_token_missing`,`No visitor credential is stored for this browser`);let d=await fetch(c(t,n,{...r.query,sessionId:a.sessionId}),{method:r.method,headers:{"X-Persona-Version":e,...u?{"X-Visitor-Token":u}:{},...o?{"X-Identity-Proof":o}:{},...r.body===void 0?{}:{"Content-Type":`application/json`}},...r.body===void 0?{}:{body:JSON.stringify(r.body)},...r.keepalive?{keepalive:!0}:{}});if(d.status===401&&!g){g=!0,a=await p(t,await f(t,d),o,i);continue}if(!d.ok)throw await m(t,d,i);let _=d.headers.get(`X-History-Identity-Status`),v=await d.json().catch(()=>void 0);if(s&&s.revision()!==l)throw new t.HistoryClientError(`credential_changed`,`The visitor credential changed while the request was in flight`);return h(t,_,o!==null,i),v}}function _(e){if(!e.isClientTokenMode())throw Error(`Conversation history is only available in client token mode`);if(!e.isHistoryCapable())throw new e.HistoryClientError(`history_disabled`,`Visitor history is disabled for this surface`)}async function v(e,t){let n=await g(e,`conversations`,{method:`GET`,query:{...t?.cursor?{cursor:t.cursor}:{},...t?.limit===void 0?{}:{limit:t.limit},...t?.targetId?{targetId:t.targetId}:{}},...t?.scope?{scope:t.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(r),nextCursor:typeof n?.nextCursor==`string`?n.nextCursor:null}}async function y(e,t,n){let i=await g(e,`conversations/${encodeURIComponent(t)}`,{method:`GET`,query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}});return{summary:r(i),messages:Array.isArray(i?.messages)?i.messages:[],nextMessageCursor:typeof i?.nextMessageCursor==`string`?i.nextMessageCursor:null,conversationRevision:typeof i?.conversationRevision==`string`?i.conversationRevision:null}}async function b(e,r,i){_(e);let a=0;for(let n of i){let r=n.displayContent.length;if(r>t)throw new e.HistoryClientError(`payload_too_large`,`displayContent exceeds the ${t} character limit`);a+=r}if(a>n)throw new e.HistoryClientError(`payload_too_large`,`Display projection batch exceeds the ${n} character limit`);await e.initSession();let o=e.historyInternals.visitorStore,s=o?.revision()??0,c=await g(e,`conversations/${encodeURIComponent(r)}/display-projections`,{method:`PATCH`,body:{messages:i},scope:`browser`,keepalive:a<=n,trackIdentity:!1}),l=typeof c?.conversationRevision==`string`?c.conversationRevision:null;return l&&e.clientSession?.conversationId===r&&(o?.revision()??0)===s&&e.historyInternals.setStoredConversationRevision?.(l),{conversationRevision:l}}async function x(e,t,n){let r=await g(e,`conversations/${encodeURIComponent(t)}`,{method:`DELETE`,...n?.scope?{scope:n.scope}:{}});return{deleted:typeof r?.deleted==`number`?r.deleted:0}}async function S(e,t){let n=await g(e,`conversations`,{method:`DELETE`,query:{...t?.targetId===void 0?{}:{targetId:t.targetId}},...t?.scope?{scope:t.scope}:{}});return{deleted:typeof n?.deleted==`number`?n.deleted:0}}async function C(e){_(e),e.setHistoryIdentityStatus({state:`resetting`});try{await g(e,`visitor/reset`,{method:`POST`,scope:`browser`,visitorTokenOptional:!0})}finally{await e.historyInternals.visitorStore?.clear(),e.setHistoryIdentityStatus(e.derivedBrowserOnly())}return{reset:!0}}export{S as deleteAllConversations,x as deleteConversation,b as finalizeDisplayProjections,y as getConversation,m as historyErrorFor,v as listConversations,f as readErrorCode,p as recoverFromUnauthorized,C as resetVisitor};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e,r as t}from"./chunk-
|
|
1
|
+
import{a as e,r as t}from"./chunk-CEPM3FOp.js";import{t as n}from"./chunk-D5BxWOFB.js";import{t as r}from"./chunk-DehTFE4q.js";const i=(e,t,r)=>{let i=r;for(let r of t){let t=n(`span`,`persona-tool-char`);t.style.setProperty(`--char-index`,String(i)),t.textContent=r===` `?`\xA0`:r,e.appendChild(t),i++}return i};function a(e,t){let{animation:n,duration:r,color:a,secondaryColor:o}=t;if(n===`none`||(e.setAttribute(`data-preserve-animation`,`true`),e.classList.add(`persona-tool-loading-${n}`),r&&e.style.setProperty(`--persona-tool-anim-duration`,r),a&&e.style.setProperty(`--persona-tool-anim-color`,a),o&&e.style.setProperty(`--persona-tool-anim-secondary-color`,o),n===`pulse`))return;let s=0,c=e=>{for(let t of Array.from(e.childNodes))if(t.nodeType===3){let e=document.createElement(`span`);s=i(e,t.textContent??``,s),t.replaceWith(...Array.from(e.childNodes))}else t instanceof HTMLElement&&!t.hasAttribute(`data-tool-elapsed`)&&c(t)};c(e)}const{resolveToolStyles:o,applyToolPadding:s,toolLoadingDuration:c}=r({getExplicitLegacyStyle:t,hasExplicitThemeStyle:e});function l(e,t,n){let r=t?.loadingLabel,i=n===`reasoning`,s=i?t?.reasoning:o(t),l=n===`waiting`?void 0:i?t?.features?.reasoningDisplay:t?.features?.toolCallDisplay,u=r?.animation??l?.loadingAnimation??(n===`waiting`||t?.future?.v5Defaults?`shimmer`:`none`);if(u===`none`)return;let d={animation:u,duration:r?.duration===void 0?i?`${s?.loadingAnimationDuration??2e3}ms`:c(t):`${r.duration}ms`,color:r?.color??s?.loadingAnimationColor,secondaryColor:r?.secondaryColor??s?.loadingAnimationSecondaryColor};e.dataset.personaLoadingLabel=n,e.dataset.personaLoadingText=e.textContent??``,e.dataset.personaLoadingAnimation=JSON.stringify([n,e.textContent,d,!!r?.animate,e.className,e.getAttribute(`style`)]),r?.animate?e.setAttribute(`data-preserve-animation`,`true`):a(e,d)}function u(e,t){let n=!1,r=/* @__PURE__ */ new Map,i=e.ownerDocument.defaultView?.matchMedia?.(`(prefers-reduced-motion: reduce)`),a=e=>{try{e()}catch(e){console.warn(`[persona] Loading label animation failed`,e)}},o=e=>{let t=r.get(e);r.delete(e),t?.handle&&a(()=>t.handle?.destroy())},s=e=>`${e.closest(`[data-wrapper-id]`)?.dataset.wrapperId??``}:${e.dataset.personaLoadingLabel}`,c=e=>{if(n)return;let a=i?.matches?void 0:t().loadingLabel?.animate;if(!a&&!r.size)return;let c=new Set(Array.from(e.querySelectorAll(`[data-persona-loading-label]`),s)),l=new Set(Array.from(e.querySelectorAll(`[data-persona-reuse]`),e=>e.dataset.wrapperId));for(let[e,t]of r){let n=l.has(e.closest(`[data-wrapper-id]`)?.dataset.wrapperId);(t.start!==a||!n&&!c.has(s(e)))&&o(e)}},l=()=>{if(n)return;let s=t(),c=i?.matches?void 0:s.loadingLabel?.animate;if(!c&&!r.size)return;let l=new Set(e.querySelectorAll(`[data-persona-loading-label]`));for(let[e,t]of r)(!c||t.start!==c||!l.has(e)||e.dataset.personaLoadingLabel!==t.kind)&&o(e);if(c)for(let e of l){if(n||t().loadingLabel?.animate!==c)break;let i={element:e,config:s,text:e.dataset.personaLoadingText??``,kind:e.dataset.personaLoadingLabel,reducedMotion:!1},o=r.get(e);if(o)a(()=>o.handle?.update?.(i));else{let t={start:c,kind:i.kind,handle:void 0};r.set(e,t),a(()=>{let n=c(i);r.get(e)===t?t.handle=n:n?.destroy()})}}};return i?.addEventListener?.(`change`,l),{prepare:c,sync:l,destroy(){n=!0,i?.removeEventListener?.(`change`,l);for(let e of r.keys())o(e)}}}export{a as applyLoadingAnimation,l as applyLoadingLabel,u as createLoadingLabelLifecycle};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as e}from"./chunk-CdpVP6LZ.js";import{t}from"./chunk-D5BxWOFB.js";import{ARR as n,OBJ as r,STR as i,parse as a}from"partial-json";const o=`ask_user_question`,s=`data-persona-ask-sheet-for`,c=`Type your own answer here`,l=`Send`,u=`data-ask-current-index`,d=`data-ask-question-count`,f=`data-ask-answers`,p=`data-ask-grouped`,m=e=>e.layout===`pills`?`pills`:`rows`,h=e=>e.getAttribute(`data-ask-layout`)===`pills`?`pills`:`rows`;let g=!1;const _=e=>e.replace(/["\\]/g,`\\$&`),v=e=>e.variant===`tool`&&!!e.toolCall&&e.toolCall.name===`ask_user_question`,y=e=>e?.features?.askUserQuestion??{},b=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let o=t.status===`complete`;if(t.args&&typeof t.args==`object`)return{payload:t.args,complete:o};let s=t.chunks;if(!s||s.length===0)return{payload:null,complete:o};try{let e=s.join(``),t=a(e,i|r|n);if(t&&typeof t==`object`)return{payload:t,complete:o}}catch{}return{payload:null,complete:o}},x=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>8&&!g&&(g=!0,typeof console<`u`&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to 8.`)),t.slice(0,8)},S=e=>x(e)[0]??null,C=(e,t)=>x(e)[t]??null,w={sheetBackground:`--persona-ask-sheet-bg`,sheetBorder:`--persona-ask-sheet-border`,sheetShadow:`--persona-ask-sheet-shadow`,pillBackground:`--persona-ask-pill-bg`,pillBackgroundSelected:`--persona-ask-pill-bg-selected`,pillTextColor:`--persona-ask-pill-fg`,pillTextColorSelected:`--persona-ask-pill-fg-selected`,pillBorderRadius:`--persona-ask-pill-radius`,customInputBackground:`--persona-ask-input-bg`},T=(t,n)=>{Object.entries(w).forEach(([r,i])=>{let a=e(n,`features.askUserQuestion.styles.${r}`);typeof a==`string`&&a?t.style.setProperty(i,a):t.style.removeProperty(i)})},E=(e,n,r)=>{if(e!==`rows`)return null;let i=t(`span`,`persona-ask-row-affordance`);if(i.setAttribute(`aria-hidden`,`true`),n){let e=t(`span`,`persona-ask-row-check`);i.appendChild(e)}else{let e=t(`span`,`persona-ask-row-badge`);e.textContent=String(r+1),i.appendChild(e)}return i},D=(e,n,r,i)=>{let a=t(`button`,r===`rows`?`persona-ask-pill persona-ask-row persona-pointer-events-auto`:`persona-ask-pill persona-pointer-events-auto`);if(a.type=`button`,a.setAttribute(`role`,i?`checkbox`:`button`),a.setAttribute(`aria-pressed`,`false`),a.setAttribute(`data-ask-user-action`,`pick`),a.setAttribute(`data-option-index`,String(n)),a.setAttribute(`data-option-label`,e.label),r===`rows`){let o=t(`span`,`persona-ask-row-content`),s=t(`span`,`persona-ask-row-label`);if(s.textContent=e.label,o.appendChild(s),e.description){let n=t(`span`,`persona-ask-row-description`);n.textContent=e.description,o.appendChild(n)}a.appendChild(o);let c=E(r,i,n);c&&a.appendChild(c)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},O=e=>{let n=t(`span`,e===`rows`?`persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none`:`persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none`);return n.setAttribute(`aria-hidden`,`true`),n},k=(e,n,r,i)=>{let a=t(`div`,i===`rows`?`persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2`:`persona-ask-pills persona-flex persona-flex-wrap persona-gap-2`);a.setAttribute(`role`,`group`),a.setAttribute(`data-ask-pill-list`,`true`);let o=!!e?.multiSelect,s=(Array.isArray(e?.options)?e.options:[]).filter(e=>e&&typeof e.label==`string`&&e.label.length>0);if(s.length===0&&!r){for(let e=0;e<3;e++)a.appendChild(O(i));return a}if(s.forEach((e,t)=>{a.appendChild(D(e,t,i,o))}),e?.allowFreeText!==!1){let e=i===`rows`?`Other`:`Other…`;if(i===`rows`){let r=t(`div`,`persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto`);r.setAttribute(`data-ask-user-action`,`focus-free-text`),r.setAttribute(`data-option-index`,String(s.length)),r.setAttribute(`data-ask-other-row`,`true`);let l=t(`span`,`persona-ask-row-content`),u=document.createElement(`input`);u.type=`text`,u.className=`persona-ask-row-input persona-flex-1 persona-pointer-events-auto`,u.placeholder=n.freeTextPlaceholder??c,u.setAttribute(`data-ask-free-text-input`,`true`),u.setAttribute(`aria-label`,n.freeTextLabel??e),l.appendChild(u),r.appendChild(l);let d=E(i,o,s.length);d&&r.appendChild(d),a.appendChild(r)}else{let r=t(`button`,`persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto`);r.type=`button`,r.setAttribute(`data-ask-user-action`,`open-free-text`),r.textContent=n.freeTextLabel??e,a.appendChild(r)}}return a},A=(e,n)=>{let r=t(`div`,n===`rows`?`persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2`:`persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2`);r.setAttribute(`data-ask-free-text-row`,`true`);let i=document.createElement(`input`);if(i.type=`text`,i.className=`persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto`,i.placeholder=e.freeTextPlaceholder??c,i.setAttribute(`data-ask-free-text-input`,`true`),r.appendChild(i),n!==`rows`){let n=t(`button`,`persona-ask-free-text-submit persona-pointer-events-auto`);n.type=`button`,n.textContent=e.submitLabel??l,n.setAttribute(`data-ask-user-action`,`submit-free-text`),r.appendChild(n)}return r},j=e=>{let n=t(`div`,`persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2`);n.setAttribute(`data-ask-multi-actions`,`true`);let r=t(`button`,`persona-ask-multi-submit persona-pointer-events-auto`);return r.type=`button`,r.textContent=e.submitLabel??l,r.setAttribute(`data-ask-user-action`,`submit-multi`),r.disabled=!0,n.appendChild(r),n},M=(e,n,r)=>{let i=t(`div`,`persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2`);i.setAttribute(`data-ask-nav-row`,`true`);let a=t(`button`,`persona-ask-nav-back persona-pointer-events-auto`);a.type=`button`,a.textContent=r.backLabel??`Back`,a.setAttribute(`data-ask-user-action`,`back`),a.disabled=e===0,i.appendChild(a);let o=t(`div`,`persona-ask-nav-right persona-flex persona-items-center persona-gap-2`),s=t(`button`,`persona-ask-nav-skip persona-pointer-events-auto`);s.type=`button`,s.textContent=r.skipLabel??`Skip`,s.setAttribute(`data-ask-user-action`,`skip`),o.appendChild(s);let c=t(`button`,`persona-ask-nav-next persona-pointer-events-auto`);c.type=`button`;let l=e===n-1;return c.textContent=l?r.submitAllLabel??`Submit all`:r.nextLabel??`Next`,c.setAttribute(`data-ask-user-action`,l?`submit-all`:`next`),c.disabled=!0,o.appendChild(c),i.appendChild(o),i},N=e=>{let t=e.getAttribute(f);if(!t)return{};try{let e=JSON.parse(t);return e&&typeof e==`object`?e:{}}catch{return{}}},P=(e,t)=>{e.setAttribute(f,JSON.stringify(t))},F=e=>{let t=Number(e.getAttribute(`data-ask-current-index`)??`0`);return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},I=(e,t)=>{e.setAttribute(u,String(Math.max(0,Math.floor(t))))},L=e=>{let t=Number(e.getAttribute(`data-ask-question-count`)??`1`);return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},R=e=>e.getAttribute(p)===`true`,z=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!=`object`)return{};let r={};return t.forEach((e,t)=>{let i=typeof e?.question==`string`?e.question:``;if(i&&Object.prototype.hasOwnProperty.call(n,i)){let e=n[i];(typeof e==`string`||Array.isArray(e))&&(r[t]=e)}}),r},B=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!=`number`||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},V=(e,t)=>{let{payload:n}=b(t),r=x(n),i=N(e),a={},o=/* @__PURE__ */ new Set;return r.forEach((e,t)=>{let n=typeof e?.question==`string`?e.question:``;n&&(o.has(n)&&typeof console<`u`&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${n}"; later answer wins.`),o.add(n),Object.prototype.hasOwnProperty.call(i,t)&&(a[n]=i[t]))}),a},H=e=>{let t=N(e)[F(e)],n=/* @__PURE__ */ new Set;typeof t==`string`?n.add(t):Array.isArray(t)&&t.forEach(e=>n.add(e));let r=e.querySelectorAll(`[data-ask-user-action="pick"][data-option-label]`);r.forEach(e=>{let t=e.getAttribute(`data-option-label`)??``,r=n.has(t);e.setAttribute(`aria-pressed`,r?`true`:`false`),e.classList.toggle(`persona-ask-pill-selected`,r)});let i=new Set(Array.from(r).map(e=>e.getAttribute(`data-option-label`)??``)),a=e.querySelector(`[data-ask-free-text-input="true"]`);a&&(typeof t==`string`&&t.length>0&&!i.has(t)?(a.value=t,a.closest(`[data-ask-free-text-row="true"]`)?.classList.remove(`persona-hidden`)):a.value=``)},U=e=>{if(!R(e))return;let t=N(e)[F(e)],n=typeof t==`string`&&t.length>0||Array.isArray(t)&&t.length>0,r=e.querySelector(`[data-ask-user-action="next"], [data-ask-user-action="submit-all"]`);r&&(r.disabled=!n);let i=e.querySelector(`[data-ask-user-action="submit-multi"]`);i&&(i.disabled=Array.from(e.querySelectorAll(`[aria-pressed="true"][data-option-label]`)).length===0)},W=(e,t,n)=>{let r=y(n),i=h(e),{payload:a,complete:o}=b(t),s=R(e),c=F(e),l=L(e),u=s?C(a,c):S(a),d=!!u?.multiSelect,f=e.querySelector(`[data-ask-step-inline="true"]`);f&&(f.textContent=s?`${c+1}/${l}`:``);let p=e.querySelector(`[data-ask-stepper="true"]`);p&&p.remove();let m=e.querySelector(`[data-ask-question="true"]`);if(m){let e=typeof u?.question==`string`?u.question:``;m.textContent=e,m.classList.toggle(`persona-ask-question-skeleton`,!e&&!o)}let g=e.querySelector(`[data-ask-pill-list="true"]`);if(g){let e=k(u,r,o,i);g.replaceWith(e)}if(i!==`rows`){let t=e.querySelector(`[data-ask-free-text-row="true"]`);t&&t.replaceWith(A(r,i))}let _=e.querySelector(`[data-ask-multi-actions="true"]`);!s&&d&&!_?e.appendChild(j(r)):(!d||s)&&_&&_.remove(),e.setAttribute(`data-multi-select`,d?`true`:`false`);let v=e.querySelector(`[data-ask-nav-row="true"]`);if(s){let t=M(c,l,r);v?v.replaceWith(t):e.appendChild(t)}else v&&v.remove();H(e),U(e)},G=(e,n,r)=>{let i=y(n),a=m(i),o=e.toolCall.id,c=x(r),l=Math.max(1,c.length),f=l>1,h=z(e,c),g=f?B(e,l):0,_=t(`div`,[`persona-ask-sheet`,`persona-ask-sheet--${a}`,`persona-pointer-events-auto`,`persona-ask-sheet-enter`].join(` `));_.setAttribute(s,o),_.setAttribute(`data-tool-call-id`,o),_.setAttribute(`data-message-id`,e.id),_.setAttribute(d,String(l)),_.setAttribute(u,String(g)),_.setAttribute(p,f?`true`:`false`),_.setAttribute(`data-ask-layout`,a),P(_,h),_.setAttribute(`role`,`group`),_.setAttribute(`aria-label`,`Suggested answers`),i.slideInMs!==void 0&&_.style.setProperty(`--persona-ask-sheet-duration`,`${i.slideInMs}ms`),T(_,n);let v=t(`div`,`persona-ask-sheet-header persona-flex persona-items-center persona-gap-3`),b=t(`div`,`persona-ask-sheet-question persona-flex-1`);b.setAttribute(`data-ask-question`,`true`),b.textContent=``,v.appendChild(b);let S=t(`span`,`persona-ask-sheet-step-inline`);S.setAttribute(`data-ask-step-inline`,`true`),S.textContent=``,v.appendChild(S),_.appendChild(v);let C=t(`div`,a===`rows`?`persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2`:`persona-ask-pills persona-flex persona-flex-wrap persona-gap-2`);return C.setAttribute(`data-ask-pill-list`,`true`),C.setAttribute(`role`,`group`),_.appendChild(C),a!==`rows`&&_.appendChild(A(i,a)),W(_,e,n),requestAnimationFrame(()=>{requestAnimationFrame(()=>_.classList.remove(`persona-ask-sheet-enter`))}),_},K=(e,t,n)=>{T(e,n);let{payload:r}=b(t),i=Math.max(1,x(r).length);i>L(e)&&(e.setAttribute(d,String(i)),i>1&&!R(e)&&e.setAttribute(p,`true`)),W(e,t,n)},q=(e,t,n)=>{if(!n||!v(e)||y(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${s}]`).forEach(e=>{e.getAttribute(s)!==r&&e.remove()});let i=n.querySelector(`[${s}="${_(r)}"]`);if(i){K(i,e,t);return}let{payload:a}=b(e),o=G(e,t,a);n.appendChild(o)},J=(e,t)=>{if(!e)return;let n=t?`[${s}="${_(t)}"]`:`[${s}]`;e.querySelectorAll(n).forEach(e=>{e.classList.add(`persona-ask-sheet-leave`);let t=Number.parseInt(getComputedStyle(e).getPropertyValue(`--persona-ask-sheet-duration`)||`180`,10);setTimeout(()=>e.remove(),Number.isFinite(t)?t:180)})},Y=e=>Array.from(e.querySelectorAll(`[aria-pressed="true"][data-option-label]`)).map(e=>e.getAttribute(`data-option-label`)).filter(e=>typeof e==`string`&&e.length>0),X=(e,t)=>{let n=N(e),r=F(e);typeof t==`string`&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,P(e,n),H(e),U(e)},Z=(e,t,n,r)=>{let i=L(e),a=Math.max(0,Math.min(i-1,r));I(e,a),W(e,t,n)};export{L as a,R as c,N as d,J as f,F as i,Z as l,V as n,Y as o,X as p,q as r,v as s,o as t,b as u};
|
|
1
|
+
import{r as e}from"./chunk-CEPM3FOp.js";import{t}from"./chunk-D5BxWOFB.js";import{ARR as n,OBJ as r,STR as i,parse as a}from"partial-json";const o=`ask_user_question`,s=`data-persona-ask-sheet-for`,c=`Type your own answer here`,l=`Send`,u=`data-ask-current-index`,d=`data-ask-question-count`,f=`data-ask-answers`,p=`data-ask-grouped`,m=e=>e.layout===`pills`?`pills`:`rows`,h=e=>e.getAttribute(`data-ask-layout`)===`pills`?`pills`:`rows`;let g=!1;const _=e=>e.replace(/["\\]/g,`\\$&`),v=e=>e.variant===`tool`&&!!e.toolCall&&e.toolCall.name===`ask_user_question`,y=e=>e?.features?.askUserQuestion??{},b=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let o=t.status===`complete`;if(t.args&&typeof t.args==`object`)return{payload:t.args,complete:o};let s=t.chunks;if(!s||s.length===0)return{payload:null,complete:o};try{let e=s.join(``),t=a(e,i|r|n);if(t&&typeof t==`object`)return{payload:t,complete:o}}catch{}return{payload:null,complete:o}},x=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>8&&!g&&(g=!0,typeof console<`u`&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to 8.`)),t.slice(0,8)},S=e=>x(e)[0]??null,C=(e,t)=>x(e)[t]??null,w={sheetBackground:`--persona-ask-sheet-bg`,sheetBorder:`--persona-ask-sheet-border`,sheetShadow:`--persona-ask-sheet-shadow`,pillBackground:`--persona-ask-pill-bg`,pillBackgroundSelected:`--persona-ask-pill-bg-selected`,pillTextColor:`--persona-ask-pill-fg`,pillTextColorSelected:`--persona-ask-pill-fg-selected`,pillBorderRadius:`--persona-ask-pill-radius`,customInputBackground:`--persona-ask-input-bg`},T=(t,n)=>{Object.entries(w).forEach(([r,i])=>{let a=e(n,`features.askUserQuestion.styles.${r}`);typeof a==`string`&&a?t.style.setProperty(i,a):t.style.removeProperty(i)})},E=(e,n,r)=>{if(e!==`rows`)return null;let i=t(`span`,`persona-ask-row-affordance`);if(i.setAttribute(`aria-hidden`,`true`),n){let e=t(`span`,`persona-ask-row-check`);i.appendChild(e)}else{let e=t(`span`,`persona-ask-row-badge`);e.textContent=String(r+1),i.appendChild(e)}return i},D=(e,n,r,i)=>{let a=t(`button`,r===`rows`?`persona-ask-pill persona-ask-row persona-pointer-events-auto`:`persona-ask-pill persona-pointer-events-auto`);if(a.type=`button`,a.setAttribute(`role`,i?`checkbox`:`button`),a.setAttribute(`aria-pressed`,`false`),a.setAttribute(`data-ask-user-action`,`pick`),a.setAttribute(`data-option-index`,String(n)),a.setAttribute(`data-option-label`,e.label),r===`rows`){let o=t(`span`,`persona-ask-row-content`),s=t(`span`,`persona-ask-row-label`);if(s.textContent=e.label,o.appendChild(s),e.description){let n=t(`span`,`persona-ask-row-description`);n.textContent=e.description,o.appendChild(n)}a.appendChild(o);let c=E(r,i,n);c&&a.appendChild(c)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},O=e=>{let n=t(`span`,e===`rows`?`persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none`:`persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none`);return n.setAttribute(`aria-hidden`,`true`),n},k=(e,n,r,i)=>{let a=t(`div`,i===`rows`?`persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2`:`persona-ask-pills persona-flex persona-flex-wrap persona-gap-2`);a.setAttribute(`role`,`group`),a.setAttribute(`data-ask-pill-list`,`true`);let o=!!e?.multiSelect,s=(Array.isArray(e?.options)?e.options:[]).filter(e=>e&&typeof e.label==`string`&&e.label.length>0);if(s.length===0&&!r){for(let e=0;e<3;e++)a.appendChild(O(i));return a}if(s.forEach((e,t)=>{a.appendChild(D(e,t,i,o))}),e?.allowFreeText!==!1){let e=i===`rows`?`Other`:`Other…`;if(i===`rows`){let r=t(`div`,`persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto`);r.setAttribute(`data-ask-user-action`,`focus-free-text`),r.setAttribute(`data-option-index`,String(s.length)),r.setAttribute(`data-ask-other-row`,`true`);let l=t(`span`,`persona-ask-row-content`),u=document.createElement(`input`);u.type=`text`,u.className=`persona-ask-row-input persona-flex-1 persona-pointer-events-auto`,u.placeholder=n.freeTextPlaceholder??c,u.setAttribute(`data-ask-free-text-input`,`true`),u.setAttribute(`aria-label`,n.freeTextLabel??e),l.appendChild(u),r.appendChild(l);let d=E(i,o,s.length);d&&r.appendChild(d),a.appendChild(r)}else{let r=t(`button`,`persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto`);r.type=`button`,r.setAttribute(`data-ask-user-action`,`open-free-text`),r.textContent=n.freeTextLabel??e,a.appendChild(r)}}return a},A=(e,n)=>{let r=t(`div`,n===`rows`?`persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2`:`persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2`);r.setAttribute(`data-ask-free-text-row`,`true`);let i=document.createElement(`input`);if(i.type=`text`,i.className=`persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto`,i.placeholder=e.freeTextPlaceholder??c,i.setAttribute(`data-ask-free-text-input`,`true`),r.appendChild(i),n!==`rows`){let n=t(`button`,`persona-ask-free-text-submit persona-pointer-events-auto`);n.type=`button`,n.textContent=e.submitLabel??l,n.setAttribute(`data-ask-user-action`,`submit-free-text`),r.appendChild(n)}return r},j=e=>{let n=t(`div`,`persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2`);n.setAttribute(`data-ask-multi-actions`,`true`);let r=t(`button`,`persona-ask-multi-submit persona-pointer-events-auto`);return r.type=`button`,r.textContent=e.submitLabel??l,r.setAttribute(`data-ask-user-action`,`submit-multi`),r.disabled=!0,n.appendChild(r),n},M=(e,n,r)=>{let i=t(`div`,`persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2`);i.setAttribute(`data-ask-nav-row`,`true`);let a=t(`button`,`persona-ask-nav-back persona-pointer-events-auto`);a.type=`button`,a.textContent=r.backLabel??`Back`,a.setAttribute(`data-ask-user-action`,`back`),a.disabled=e===0,i.appendChild(a);let o=t(`div`,`persona-ask-nav-right persona-flex persona-items-center persona-gap-2`),s=t(`button`,`persona-ask-nav-skip persona-pointer-events-auto`);s.type=`button`,s.textContent=r.skipLabel??`Skip`,s.setAttribute(`data-ask-user-action`,`skip`),o.appendChild(s);let c=t(`button`,`persona-ask-nav-next persona-pointer-events-auto`);c.type=`button`;let l=e===n-1;return c.textContent=l?r.submitAllLabel??`Submit all`:r.nextLabel??`Next`,c.setAttribute(`data-ask-user-action`,l?`submit-all`:`next`),c.disabled=!0,o.appendChild(c),i.appendChild(o),i},N=e=>{let t=e.getAttribute(f);if(!t)return{};try{let e=JSON.parse(t);return e&&typeof e==`object`?e:{}}catch{return{}}},P=(e,t)=>{e.setAttribute(f,JSON.stringify(t))},F=e=>{let t=Number(e.getAttribute(`data-ask-current-index`)??`0`);return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},I=(e,t)=>{e.setAttribute(u,String(Math.max(0,Math.floor(t))))},L=e=>{let t=Number(e.getAttribute(`data-ask-question-count`)??`1`);return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},R=e=>e.getAttribute(p)===`true`,z=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!=`object`)return{};let r={};return t.forEach((e,t)=>{let i=typeof e?.question==`string`?e.question:``;if(i&&Object.prototype.hasOwnProperty.call(n,i)){let e=n[i];(typeof e==`string`||Array.isArray(e))&&(r[t]=e)}}),r},B=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!=`number`||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},V=(e,t)=>{let{payload:n}=b(t),r=x(n),i=N(e),a={},o=/* @__PURE__ */ new Set;return r.forEach((e,t)=>{let n=typeof e?.question==`string`?e.question:``;n&&(o.has(n)&&typeof console<`u`&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${n}"; later answer wins.`),o.add(n),Object.prototype.hasOwnProperty.call(i,t)&&(a[n]=i[t]))}),a},H=e=>{let t=N(e)[F(e)],n=/* @__PURE__ */ new Set;typeof t==`string`?n.add(t):Array.isArray(t)&&t.forEach(e=>n.add(e));let r=e.querySelectorAll(`[data-ask-user-action="pick"][data-option-label]`);r.forEach(e=>{let t=e.getAttribute(`data-option-label`)??``,r=n.has(t);e.setAttribute(`aria-pressed`,r?`true`:`false`),e.classList.toggle(`persona-ask-pill-selected`,r)});let i=new Set(Array.from(r).map(e=>e.getAttribute(`data-option-label`)??``)),a=e.querySelector(`[data-ask-free-text-input="true"]`);a&&(typeof t==`string`&&t.length>0&&!i.has(t)?(a.value=t,a.closest(`[data-ask-free-text-row="true"]`)?.classList.remove(`persona-hidden`)):a.value=``)},U=e=>{if(!R(e))return;let t=N(e)[F(e)],n=typeof t==`string`&&t.length>0||Array.isArray(t)&&t.length>0,r=e.querySelector(`[data-ask-user-action="next"], [data-ask-user-action="submit-all"]`);r&&(r.disabled=!n);let i=e.querySelector(`[data-ask-user-action="submit-multi"]`);i&&(i.disabled=Array.from(e.querySelectorAll(`[aria-pressed="true"][data-option-label]`)).length===0)},W=(e,t,n)=>{let r=y(n),i=h(e),{payload:a,complete:o}=b(t),s=R(e),c=F(e),l=L(e),u=s?C(a,c):S(a),d=!!u?.multiSelect,f=e.querySelector(`[data-ask-step-inline="true"]`);f&&(f.textContent=s?`${c+1}/${l}`:``);let p=e.querySelector(`[data-ask-stepper="true"]`);p&&p.remove();let m=e.querySelector(`[data-ask-question="true"]`);if(m){let e=typeof u?.question==`string`?u.question:``;m.textContent=e,m.classList.toggle(`persona-ask-question-skeleton`,!e&&!o)}let g=e.querySelector(`[data-ask-pill-list="true"]`);if(g){let e=k(u,r,o,i);g.replaceWith(e)}if(i!==`rows`){let t=e.querySelector(`[data-ask-free-text-row="true"]`);t&&t.replaceWith(A(r,i))}let _=e.querySelector(`[data-ask-multi-actions="true"]`);!s&&d&&!_?e.appendChild(j(r)):(!d||s)&&_&&_.remove(),e.setAttribute(`data-multi-select`,d?`true`:`false`);let v=e.querySelector(`[data-ask-nav-row="true"]`);if(s){let t=M(c,l,r);v?v.replaceWith(t):e.appendChild(t)}else v&&v.remove();H(e),U(e)},G=(e,n,r)=>{let i=y(n),a=m(i),o=e.toolCall.id,c=x(r),l=Math.max(1,c.length),f=l>1,h=z(e,c),g=f?B(e,l):0,_=t(`div`,[`persona-ask-sheet`,`persona-ask-sheet--${a}`,`persona-pointer-events-auto`,`persona-ask-sheet-enter`].join(` `));_.setAttribute(s,o),_.setAttribute(`data-tool-call-id`,o),_.setAttribute(`data-message-id`,e.id),_.setAttribute(d,String(l)),_.setAttribute(u,String(g)),_.setAttribute(p,f?`true`:`false`),_.setAttribute(`data-ask-layout`,a),P(_,h),_.setAttribute(`role`,`group`),_.setAttribute(`aria-label`,`Suggested answers`),i.slideInMs!==void 0&&_.style.setProperty(`--persona-ask-sheet-duration`,`${i.slideInMs}ms`),T(_,n);let v=t(`div`,`persona-ask-sheet-header persona-flex persona-items-center persona-gap-3`),b=t(`div`,`persona-ask-sheet-question persona-flex-1`);b.setAttribute(`data-ask-question`,`true`),b.textContent=``,v.appendChild(b);let S=t(`span`,`persona-ask-sheet-step-inline`);S.setAttribute(`data-ask-step-inline`,`true`),S.textContent=``,v.appendChild(S),_.appendChild(v);let C=t(`div`,a===`rows`?`persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2`:`persona-ask-pills persona-flex persona-flex-wrap persona-gap-2`);return C.setAttribute(`data-ask-pill-list`,`true`),C.setAttribute(`role`,`group`),_.appendChild(C),a!==`rows`&&_.appendChild(A(i,a)),W(_,e,n),requestAnimationFrame(()=>{requestAnimationFrame(()=>_.classList.remove(`persona-ask-sheet-enter`))}),_},K=(e,t,n)=>{T(e,n);let{payload:r}=b(t),i=Math.max(1,x(r).length);i>L(e)&&(e.setAttribute(d,String(i)),i>1&&!R(e)&&e.setAttribute(p,`true`)),W(e,t,n)},q=(e,t,n)=>{if(!n||!v(e)||y(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${s}]`).forEach(e=>{e.getAttribute(s)!==r&&e.remove()});let i=n.querySelector(`[${s}="${_(r)}"]`);if(i){K(i,e,t);return}let{payload:a}=b(e),o=G(e,t,a);n.appendChild(o)},J=(e,t)=>{if(!e)return;let n=t?`[${s}="${_(t)}"]`:`[${s}]`;e.querySelectorAll(n).forEach(e=>{e.classList.add(`persona-ask-sheet-leave`);let t=Number.parseInt(getComputedStyle(e).getPropertyValue(`--persona-ask-sheet-duration`)||`180`,10);setTimeout(()=>e.remove(),Number.isFinite(t)?t:180)})},Y=e=>Array.from(e.querySelectorAll(`[aria-pressed="true"][data-option-label]`)).map(e=>e.getAttribute(`data-option-label`)).filter(e=>typeof e==`string`&&e.length>0),X=(e,t)=>{let n=N(e),r=F(e);typeof t==`string`&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,P(e,n),H(e),U(e)},Z=(e,t,n,r)=>{let i=L(e),a=Math.max(0,Math.min(i-1,r));I(e,a),W(e,t,n)};export{L as a,R as c,N as d,J as f,F as i,Z as l,V as n,Y as o,X as p,q as r,v as s,o as t,b as u};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as e,m as t,p as n,r,s as i}from"./chunk-CdpVP6LZ.js";import{r as a,t as o}from"./chunk-BnfM7-qg.js";import{t as s}from"./chunk-CnxIZOzx.js";import{i as c,r as l,t as u}from"./chunk-D5BxWOFB.js";import{r as d}from"./chunk-Bb41bKyp.js";import{t as f}from"./chunk-BlTD-Wgn.js";import{n as p,t as m}from"./chunk-BAkaTZpd.js";import{i as h,n as g,r as _,t as v}from"./chunk-BGPPJ_ui.js";import{t as y}from"./chunk-Bj8Hnh10.js";import{r as b}from"./chunk-Cy1A8vbF.js";import{Activity as x,ArrowDown as S,ArrowLeft as C,ArrowRight as w,ArrowUp as T,ArrowUpRight as E,AtSign as ee,Bot as D,Check as O,ChevronDown as k,ChevronLeft as A,ChevronRight as j,ChevronUp as M,Clipboard as N,ClipboardCopy as P,CodeXml as te,Copy as ne,Download as re,Ellipsis as ie,ExternalLink as ae,Eye as oe,File as se,FileCode as ce,FileSpreadsheet as le,FileText as ue,History as de,ImagePlus as fe,Loader as pe,LoaderCircle as me,Maximize as he,Menu as ge,MessageSquare as _e,Mic as ve,Minimize as ye,Minus as be,PanelLeft as xe,Paperclip as Se,Pencil as Ce,Plus as we,Quote as Te,RefreshCw as Ee,Search as De,Send as Oe,ShieldAlert as ke,ShieldCheck as Ae,ShieldX as je,Square as Me,Star as Ne,ThumbsDown as Pe,ThumbsUp as Fe,Trash as Ie,Trash2 as Le,Upload as Re,Volume2 as ze,X as Be}from"lucide";const Ve={activity:x,"arrow-down":S,"arrow-up":T,"arrow-up-right":E,bot:D,"chevron-down":k,"chevron-up":M,"chevron-right":j,"chevron-left":A,check:O,clipboard:N,"clipboard-copy":P,"code-xml":te,copy:ne,file:se,"file-code":ce,"file-spreadsheet":le,"file-text":ue,"image-plus":fe,loader:pe,"loader-circle":me,mic:ve,paperclip:Se,quote:Te,"refresh-cw":Ee,search:De,send:Oe,"shield-alert":ke,"shield-check":Ae,"shield-x":je,square:Me,"square-text":[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`}],[`path`,{d:`M7 8h10M7 12h10M7 16h6`}]],"thumbs-down":Pe,"thumbs-up":Fe,upload:Re,"volume-2":ze,"voice-bars":[[`path`,{d:`M4 10v4`}],[`path`,{d:`M8 6v12`}],[`path`,{d:`M12 3v18`}],[`path`,{d:`M16 7v10`}],[`path`,{d:`M20 10v4`}]],x:Be,"at-sign":ee,"arrow-left":C,"arrow-right":w,"external-link":ae,ellipsis:ie,menu:ge,"panel-left":xe,plus:we,minus:be,pencil:Ce,trash:Ie,"trash-2":Le,download:re,maximize:he,minimize:ye,"message-square":_e,star:Ne,eye:oe,history:de},He=/* @__PURE__ */ `brain.toolbox.wrench.circle.database.terminal.user.mail.phone.calendar.clock.building.map-pin.lock.key.credit-card.hash.globe.link.circle-check.circle-x.triangle-alert.info.ban.shield.ellipsis-vertical.house.pen-line.save.share.funnel.settings.rotate-cw.shopping-cart.shopping-bag.package.truck.tag.gift.receipt.wallet.store.dollar-sign.percent.play.pause.volume-x.camera.image.film.headphones.message-circle.bell.heart.eye-off.bookmark.calendar-days.timer.folder.folder-open.files.chart-column.sparkles.zap.sun.moon.flag.lightbulb.monitor.smartphone`.split(`.`),F=new Map(Object.entries(Ve)),I=/* @__PURE__ */ new Map;let L=!1;const Ue=/* @__PURE__ */ new Set,We=e=>{let t=[...Ue];e&&Ue.clear();for(let e of t)try{e()}catch{}},Ge=()=>{let e=0;for(let[t,n]of I){let r=F.get(n);if(!r)continue;I.delete(t),e++;let i=s(r);if(i)for(t.removeAttribute(`data-persona-icon-pending`);i.firstChild;)t.appendChild(i.firstChild)}return e},Ke=e=>{if(!L){for(let[t,n]of Object.entries(e))F.has(t)||F.set(t,n);L=!0,Ge(),We(!0)}},qe=()=>L?null:o().then(e=>Ke(e.EXTRA_LUCIDE_ICONS)),Je=()=>{qe()?.catch(e=>{console.warn(`[Persona] Failed to load the icons-extra chunk`,e)})},Ye=(e,t,n)=>{let r=s([],e,t,n);return r.setAttribute(`data-persona-icon-pending`,`true`),r},R=(e,t=24,n=`currentColor`,r=2)=>{let i=F.get(e);if(i)return s(i,t,n,r);if(He.includes(e)){let i=Ye(t,n,r);return I.size>=500&&I.delete(I.keys().next().value),I.set(i,e),Je(),i}return console.warn(`Unknown Persona icon "${e}". Use registerIcons().`),null},Xe=(e,t)=>e.visible!==!1&&(e.mode!==`transient`||t===`connecting`||t===`paused`||t===`resuming`||t===`error`),Ze=(e,t,n)=>{let r=t.mode===`transient`,i=e.hasAttribute(`data-persona-composer-reason`)||e.hasAttribute(`data-persona-composer-notice`);e.style.display=Xe(t,n)||r&&i&&t.visible!==!1?``:`none`,e.classList.toggle(`persona-mt-2`,!r),e.classList.toggle(`persona-mb-2`,r)},Qe=(e,t,n)=>{t.parentElement&&e.parentElement===t.parentElement&&(n.mode===`transient`?e.nextElementSibling!==t&&t.before(e):t.nextElementSibling!==e&&t.after(e))};function $e(e){let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return 20;let n=t.getComputedStyle(e).lineHeight;if(!n||!n.trim().endsWith(`px`))return 20;let r=parseFloat(n);return Number.isFinite(r)&&r>0?r:20}function et(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:e>0?e:t}function tt(e,t){e.style.maxHeight=`${t*$e(e)}px`,e.style.overflowY=`auto`}function nt(e){let t=e?.ownerDocument?.defaultView??(typeof window<`u`?window:null);if(!t||typeof t.matchMedia!=`function`)return!1;try{return t.matchMedia(`(pointer: coarse)`).matches===!0}catch{return!1}}function rt(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function it(e,t){if(e.key!==`Enter`||e.shiftKey||e.isComposing)return!1;let n=e.metaKey===!0||e.ctrlKey===!0,r=t.submitKey??`enter`;return r===`none`?!1:r===`mod-enter`?n:n||!rt(t)}function at(e){return(e.submitKey??`enter`)===`enter`?rt(e)?`enter`:`send`:`enter`}function ot(e,t){e.setAttribute(`enterkeyhint`,at(t))}function z(e,t){let n=t?.autocomplete;e.setAttribute(`autocomplete`,typeof n==`string`&&n?n:`off`);let r=(t,n)=>{n===void 0?e.removeAttribute(t):e.setAttribute(t,n)};r(`autocapitalize`,typeof t?.autocapitalize==`string`?t.autocapitalize:void 0),r(`spellcheck`,typeof t?.spellcheck==`boolean`?String(t.spellcheck):void 0),r(`inputmode`,typeof t?.inputmode==`string`&&t.inputmode?t.inputmode:void 0),r(`aria-label`,typeof t?.ariaLabel==`string`&&t.ariaLabel?t.ariaLabel:void 0)}function st(e){return e===!0?{disabled:!0}:!e||typeof e!=`object`?{disabled:!1}:{disabled:!0,reason:typeof e.reason==`string`&&e.reason?e.reason:void 0}}const{setLoader:ct,load:lt}=a({fallbackImport:()=>import(`./chunk-Co3VVwGe.js`)}),ut=lt,{setLoader:dt,load:ft}=a({fallbackImport:()=>import(`./chunk-Bkma5hIU.js`),resetOnSetLoader:!0}),pt=ft;let B=400,V=300,H=0;const U=e=>Math.max(0,e);function mt(e){e.delayMs!==void 0&&(B=U(e.delayMs)),e.skipDelayMs!==void 0&&(V=U(e.skipDelayMs))}const ht=()=>Date.now()<H,gt=e=>{H=e>0?Date.now()+e:0},W=/* @__PURE__ */ new WeakMap,_t=e=>typeof e.closest==`function`&&e.closest(`[data-persona-tooltip-suppressed]`)!==null;function vt(e){W.get(e)?.hide()}const yt=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&`host`in e,bt=e=>{let t=e.getRootNode?.();return yt(t)?t:e.closest(`dialog[open]`)??e.ownerDocument.body},G=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),xt=[...[`background`,`foreground`,`hint-fg`,`radius`,`font-size`,`padding`,`max-width`,`shadow`,`arrow-display`].map(e=>`--persona-tooltip-${e}`),`--persona-font-family`,`--persona-radius-sm`];function K(e){W.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:r,hint:i,enabled:a=!0,gap:o=8,viewportPadding:s=8}=e,c=()=>t.ownerDocument,l=()=>c().defaultView??window,u=null,f=null,p=null,m=null,h,g=!1,_=!1,v=!1,y=()=>(typeof r==`function`?r():r).trim(),b=()=>(typeof i==`function`?i():i??``).trim(),x=()=>U(e.delayMs??B),S=()=>U(e.skipDelayMs??V),C=()=>{h!==void 0&&(l().clearTimeout(h),h=void 0)},w=()=>{C();let e=u!==null;m?.(),m=null,u?.remove(),u=null,f=null,p=null,e&>(S())},T=()=>{if(!u)return;let e=c(),n=l(),r=t.getBoundingClientRect(),i=u.getBoundingClientRect(),a=e.documentElement.clientWidth||n.innerWidth,d=e.documentElement.clientHeight||n.innerHeight,f=a-s-i.width,p=r.left+r.width/2-i.width/2,m=G(p,s,f),h=r.top-s,g=d-s-r.bottom,_=h>=i.height+o||h>=g?`top`:`bottom`,v=_===`top`?r.top-o-i.height:r.bottom+o,y=d-s-i.height,b=G(v,s,y),x=r.left+r.width/2,S=Math.max(10,i.width-10),C=G(x-m,10,S);u.dataset.placement=_,u.style.left=`${m}px`,u.style.top=`${b}px`,u.style.setProperty(`--persona-tooltip-arrow-x`,`${C}px`)},E=()=>{if(v||!a||u||!t.isConnected||_t(t))return;let e=y(),n=bt(t);if(!e||!n)return;let r=c(),i=l();u=r.createElement(`div`),u.className=`persona-control-tooltip`,u.setAttribute(`role`,`tooltip`),u.dataset.state=`measuring`,u.style.zIndex=String(d);let o=i.getComputedStyle?.(t);if(o){for(let e of xt){let t=o.getPropertyValue(e).trim();t&&u.style.setProperty(e,t)}o.fontFamily&&(u.style.fontFamily=o.fontFamily)}f=r.createElement(`span`),f.className=`persona-control-tooltip__label`,f.textContent=e,u.appendChild(f);let s=b();s&&(p=r.createElement(`span`),p.className=`persona-control-tooltip__hint`,p.textContent=s,u.appendChild(p));let h=r.createElement(`span`);h.className=`persona-control-tooltip__arrow`,u.appendChild(h),n.appendChild(u),T(),u.dataset.state=`open`;let g=()=>{if(!t.isConnected){w();return}f&&(f.textContent=y()),p&&(p.textContent=b());let e=bt(t);u&&e&&u.parentNode!==e&&e.appendChild(u),T()};i.addEventListener(`scroll`,g,!0),i.addEventListener(`resize`,g);let _=t.closest(`[data-persona-root]`);_?.addEventListener(`persona:internal:host-moved`,g);let x=t.getRootNode(),S=yt(x)?x:r.documentElement,C=typeof MutationObserver>`u`?null:new MutationObserver(()=>{t.isConnected||w()});C?.observe(S,{childList:!0,subtree:!0}),m=()=>{i.removeEventListener(`scroll`,g,!0),i.removeEventListener(`resize`,g),_?.removeEventListener(`persona:internal:host-moved`,g),C?.disconnect()}},ee=e=>{v||u||(C(),e||x()<=0||ht()?E():h=l().setTimeout(()=>{h=void 0,E()},x()))},D=()=>{g||_?ee(_):w()},O=()=>{let e=l();e.matchMedia&&e.matchMedia(`(hover: none)`).matches||(g=!0,D())},k=()=>{g=!1,D()},A=()=>{try{_=t.matches(`:focus-visible`)}catch{_=!0}D()},j=()=>{_=!1,D()},M=()=>{g=!1,_=!1,w()},N=e=>{e.key===`Escape`&&M()};n.addEventListener(`mouseenter`,O),n.addEventListener(`mouseleave`,k),t.addEventListener(`focus`,A),t.addEventListener(`blur`,j),t.addEventListener(`keydown`,N),t.addEventListener(`click`,M);let P={get isOpen(){return u!==null},show:E,hide:w,reposition:T,destroy:()=>{v||(v=!0,w(),n.removeEventListener(`mouseenter`,O),n.removeEventListener(`mouseleave`,k),t.removeEventListener(`focus`,A),t.removeEventListener(`blur`,j),t.removeEventListener(`keydown`,N),t.removeEventListener(`click`,M),W.delete(t))}};return W.set(t,P),P}const q=(e,t,n,r)=>{let[i,a]=t.split(`.`);return[e?.theme,e?.darkTheme].some(e=>e?.components?.[i]?.[a]?.[n]!==void 0)?`var(--persona-components-${t.replace(`.`,`-`)}-${n}, ${r})`:r},J=(e,t)=>{let n=e&&r(e,t);return typeof n==`string`&&n?n:void 0},Y=(e,t,n,r)=>{let i=t.startsWith(`var(`);e.classList.toggle(`persona-theme-padding`,i),e.style.padding=i?``:t,i?e.style.setProperty(`--persona-theme-padding`,t):e.style.removeProperty(`--persona-theme-padding`),n&&(e.style.paddingLeft=e.style.paddingRight=n),r&&(e.style.paddingTop=e.style.paddingBottom=r)},X=(e,t,n)=>{let r=t.startsWith(`var(`)&&t.includes(`--persona-components-`);e.classList.toggle(`persona-control-size`,r),r?e.style.setProperty(`--persona-control-size`,t):e.style.removeProperty(`--persona-control-size`),e.style.width=e.style.height=t,e.style.minWidth=e.style.minHeight=n??``},St=`min(440px, calc(100vw - 24px))`,Ct=`40px`,wt={apiUrl:`https://api.runtype.com/api/chat/dispatch`,clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:`light`,tooltip:{delayMs:400,skipDelayMs:300},launcher:{enabled:!0,mountMode:`floating`,dock:{side:`right`,width:`420px`},title:`Chat Assistant`,subtitle:`Here to help you get answers fast`,agentIconText:`💬`,agentIconName:`bot`,headerIconName:`bot`,position:`bottom-right`,width:St,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:`40px`,headerIconSize:Ct,closeButtonPaddingX:`0px`,closeButtonPaddingY:`0px`,callToActionIconName:`arrow-up-right`,callToActionIconText:``,callToActionIconSize:`32px`,callToActionIconPadding:`5px`,callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:`transparent`,clearChat:{backgroundColor:`transparent`,borderColor:`transparent`,enabled:!0,placement:`inline`,iconName:`refresh-cw`,showTooltip:!0,tooltipText:`Clear chat`,paddingX:`0px`,paddingY:`0px`},headerIconHidden:!1,border:void 0,shadow:`0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)`},copy:{inputPlaceholder:`How can I help...`,sendButtonLabel:`Send`},sendButton:{borderWidth:`0px`,paddingX:`12px`,paddingY:`10px`,borderColor:void 0,useIcon:!0,iconText:`↑`,showTooltip:!0,tooltipText:`Send message`,iconName:`send`},statusIndicator:{visible:!0,idleText:`Online`,connectingText:`Connecting…`,connectedText:`Streaming…`,errorText:`Offline`},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:`mic`,borderWidth:`0px`,iconColor:void 0,backgroundColor:`transparent`,borderColor:`transparent`,recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:`transparent`,showTooltip:!0,tooltipText:`Start voice recognition`},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:`arrow-down`,label:``,streamingIndicator:`arrow`,scrollBehavior:`instant`,scrollDurationMs:220,transition:`none`},scrollBehavior:{mode:`anchor-top`,anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:_,reasoningDisplay:v,streamAnimation:{type:`none`,placeholder:`none`,speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:`Other…`,freeTextPlaceholder:`Type your answer…`,submitLabel:`Send`},history:{enabled:!1,presentation:`panel`,showScopeStatus:!0,showDelete:!0,showDeleteAll:!0}},suggestionChips:[`Show me what you can help with`,`Walk me through getting started`,`Answer a question about this page`],suggestionChipsConfig:{fontFamily:`sans-serif`,fontWeight:`500`,paddingX:`12px`,paddingY:`6px`},layout:{header:{layout:`default`,showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:`bubble`,avatar:{show:!1,position:`left`},timestamp:{show:!1,position:`below`},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:`hover`,align:`right`,layout:`pill-inside`},debug:!1},Tt={},Z={colorScheme:`light`,errorDisplay:`block`,messageActions:{visibility:void 0},suggestionChipsConfig:{fontWeight:void 0},approval:y,loadingIndicator:{variant:`label`},launcher:{variant:`circle`,width:`min(400px, calc(100vw - 24px))`,headerIconSize:`20px`},features:{artifacts:{enabled:!0},scrollToBottom:{streamingIndicator:`dots`,transition:`fade`,scrollBehavior:`smooth`},toolCallDisplay:h,reasoningDisplay:g},composer:{layout:`single-row`,placement:`overlay`},sendButton:{iconName:`arrow-up`},statusIndicator:{mode:`transient`},layout:{contentMaxWidth:`768px`,topFade:!0,header:{showSubtitle:!1},messages:{assistant:{width:`full`}}}};function Et(e){return e?.future?.v5Defaults===!0?`v5`:`v4`}function Q(t){let n=Et(t)===`v5`?Z:Tt;return e(wt,n)}Q();function Dt(t,n){if(t||n)return t?n?e(t,n):t:n}function Ot(e){let r=Q(e);return e?i(t(b({...r,...e,colorScheme:n(e,[`colorScheme`]).includes(`colorScheme`)?e.colorScheme:e.brand?void 0:r.colorScheme,...r.approval||e.approval!==void 0?{approval:e.approval!==!1&&{...r.approval||{},...e.approval}}:{},theme:Dt(r.theme,e.theme),darkTheme:Dt(r.darkTheme,e.darkTheme),launcher:{...r.launcher,...e.launcher,dock:{...r.launcher?.dock,...e.launcher?.dock},clearChat:{...r.launcher?.clearChat,...e.launcher?.clearChat}},...r.composer||e.composer?{composer:{...r.composer,...e.composer}}:{},tooltip:{...r.tooltip,...e.tooltip},copy:{...r.copy,...e.copy},sendButton:{...r.sendButton,...e.sendButton},statusIndicator:{...r.statusIndicator,...e.statusIndicator},voiceRecognition:{...r.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=r.features?.artifacts,n=e.features?.artifacts,i=r.features?.scrollToBottom,a=e.features?.scrollToBottom,o=r.features?.scrollBehavior,s=e.features?.scrollBehavior,c=r.features?.streamAnimation,l=e.features?.streamAnimation,u=r.features?.askUserQuestion,d=e.features?.askUserQuestion,f=r.features?.history,p=e.features?.history,m=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},h=i===void 0&&a===void 0?void 0:{...i,...a},g=o===void 0&&s===void 0?void 0:{...o,...s},_=c===void 0&&l===void 0?void 0:{...c,...l},v=u===void 0&&d===void 0?void 0:{...u,...d,styles:{...u?.styles,...d?.styles}},y=f===void 0&&p===void 0?void 0:{...f,...p,copy:{...f?.copy,...p?.copy}};return{...r.features,...e.features,toolCallDisplay:{...r.features?.toolCallDisplay,...e.features?.toolCallDisplay,...e.features?.toolCallDisplay?.layout===void 0&&e.features?.toolCallDisplay?.variant!==void 0?{layout:e.features.toolCallDisplay.variant}:{}},reasoningDisplay:{...r.features?.reasoningDisplay,...e.features?.reasoningDisplay,...e.features?.reasoningDisplay?.layout===void 0&&e.features?.reasoningDisplay?.variant!==void 0?{layout:e.features.reasoningDisplay.variant}:{}},...h===void 0?{}:{scrollToBottom:h},...g===void 0?{}:{scrollBehavior:g},...m===void 0?{}:{artifacts:m},..._===void 0?{}:{streamAnimation:_},...v===void 0?{}:{askUserQuestion:v},...y===void 0?{}:{history:y}}})(),suggestionChips:e.suggestionChips??r.suggestionChips,suggestionChipsConfig:{...r.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...r.layout,...e.layout,header:{...r.layout?.header,...e.layout?.header},messages:{...r.layout?.messages,...e.layout?.messages,...r.layout?.messages?.user||e.layout?.messages?.user?{user:{...r.layout?.messages?.user,...e.layout?.messages?.user}}:{},...r.layout?.messages?.assistant||e.layout?.messages?.assistant?{assistant:{...r.layout?.messages?.assistant,...e.layout?.messages?.assistant}}:{},avatar:{...r.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...r.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...r.layout?.slots,...e.layout?.slots}},markdown:{...r.markdown,...e.markdown,options:{...r.markdown?.options,...e.markdown?.options}},messageActions:{...r.messageActions,...e.messageActions}},e),e,Z),e):i(t(b(r),void 0,Z))}const kt=(e,t)=>{let n=u(`textarea`);n.setAttribute(`data-persona-composer-input`,``),n.placeholder=e?.copy?.inputPlaceholder??`How can I help...`,n.dir=`auto`,ot(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:nt(n)}),z(n,e?.composer?.inputAttributes),n.className=`persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea`,n.rows=1,n.style.fontFamily=`var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))`,n.style.fontWeight=`var(--persona-input-font-weight, var(--persona-font-weight, 400))`;let r=et(e?.composer?.maxLines,t?.defaultMaxLines??3),i=`${r*20}px`;n.style.maxHeight=i,n.style.overflowY=`auto`;let a=()=>{let e=n.style.maxHeight;if(e!==i){let t=parseFloat(e);if(Number.isFinite(t)&&t>0)return t}let t=r*$e(n);return i=`${t}px`,n.style.maxHeight=i,t},o=()=>{n.addEventListener(`input`,()=>{n.style.height=`auto`;let e=Math.min(n.scrollHeight,a());n.style.height=`${e}px`})};return n.style.border=`none`,n.style.outline=`none`,n.style.borderWidth=`0`,n.style.borderStyle=`none`,n.style.borderColor=`transparent`,n.addEventListener(`focus`,()=>{n.style.border=`none`,n.style.outline=`none`,n.style.borderWidth=`0`,n.style.borderStyle=`none`,n.style.borderColor=`transparent`,n.style.boxShadow=`none`}),n.addEventListener(`blur`,()=>{n.style.border=`none`,n.style.outline=`none`}),{textarea:n,attachAutoResize:o}},At=`[data-persona-glyph-stack]`,jt=(e,t,n=`send`)=>{let r=l(`span`,{className:`persona-composer-glyph-stack`,attrs:{"data-mode":n,"data-persona-glyph-stack":``}});return e.setAttribute(`data-glyph`,`send`),t.setAttribute(`data-glyph`,`stop`),r.append(e,t),r},Mt=/* @__PURE__ */ new WeakMap,$=(e,t,n=!0)=>{Mt.set(e,t);let r=t?.sendButton??{},i=r.useIcon??!1,a=e.getAttribute(`data-persona-send-mode`)===`stop`?`stop`:`send`,o=e=>J(t,`sendButton.${e}`),s=(e,n)=>q(t,`composer.send`,e,n),l=o(`size`)||r.size;e.style.fontSize=i?`18px`:``,e.style.lineHeight=i?`1`:``,e.className=c(`persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer`,i?`persona-flex persona-items-center persona-justify-center ${m}`:`persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold`,i&&!o(`backgroundColor`)&&`persona-bg-persona-primary`,!i&&!o(`textColor`)&&`persona-text-white`),X(e,i?l||(s(`size`,``)?s(`size`,`var(--persona-composer-control-size, 40px)`):``):``,i?l:void 0);let u=s(`foreground`,i?`var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))`:`#ffffff`),d=s(`background`,i?`var(--persona-button-primary-bg, var(--persona-primary, #111827))`:`var(--persona-accent, #0f0f0f)`);e.style.color=o(`textColor`)||(a===`stop`&&s(`foreground`,``)?`var(--persona-button-stop-fg, ${u})`:s(`foreground`,``)||(i?u:``)),e.style.backgroundColor=(i?o(`backgroundColor`):void 0)||(s(`background`,``)?a===`stop`?`var(--persona-button-stop-bg, ${d})`:d:``);let f=o(`borderWidth`)||(s(`borderWidth`,``)?s(`borderWidth`,r.borderWidth||`0px`):r.borderWidth||``);e.style.borderWidth=f,e.style.borderStyle=f?`solid`:``,e.style.borderColor=o(`borderColor`)||(s(`borderColor`,``)?s(`borderColor`,r.borderColor||`transparent`):r.borderColor||``),e.style.borderRadius=s(`borderRadius`,``)?s(`borderRadius`,`var(--persona-components-composer-sendButtonRadius, var(--persona-button-radius))`):``,Y(e,s(`padding`,i?`0`:`8px 16px`),i?void 0:o(`paddingX`)||(s(`padding`,``)?void 0:r.paddingX),i?void 0:o(`paddingY`)||(s(`padding`,``)?void 0:r.paddingY));let p=parseFloat(r.iconSize??``)||Math.round((parseFloat(r.size??``)||40)*.5);if(n){if(e.replaceChildren(),i){let t=r.iconStrokeWidth??2,n=r.iconName?R(r.iconName,p,`currentColor`,t):null,i=R(r.stopIconName??`square`,p,`currentColor`,t);n&&i?e.appendChild(jt(n,i,a)):n?e.appendChild(n):e.textContent=r.iconText??`↑`}else e.textContent=a===`stop`?t?.copy?.stopButtonLabel??`Stop`:t?.copy?.sendButtonLabel??`Send`}for(let n of Array.from(e.querySelectorAll(`svg`))){n.style.width=n.style.height=o(`iconSize`)?``:s(`iconSize`,`var(--persona-components-composer-sendIconSize, ${p}px)`);let e=t?.sendButton?.iconStrokeWidth;n.style.strokeWidth=e===void 0?s(`iconStrokeWidth`,``):String(e)}},Nt=e=>{let t=e?.sendButton,n=u(`div`,`persona-send-button-wrapper`),r=l(`button`,{attrs:{type:`submit`,"data-persona-composer-submit":``,"data-persona-send-mode":`send`}});return $(r,e),r.setAttribute(`aria-label`,t?.tooltipText??`Send message`),n.appendChild(r),K({anchor:r,trigger:n,text:()=>r.getAttribute(`aria-label`)??``,enabled:t?.showTooltip??!1}),{button:r,wrapper:n,setMode:e=>{if(r.getAttribute(`data-persona-send-mode`)===e)return;r.setAttribute(`data-persona-send-mode`,e),r.setAttribute(`aria-label`,e===`stop`?t?.stopTooltipText??`Stop generating`:t?.tooltipText??`Send message`);let n=Mt.get(r);$(r,n,!1),r.querySelector(At)?.setAttribute(`data-mode`,e),(n?.sendButton?.useIcon??!1)||(r.textContent=e===`stop`?n?.copy?.stopButtonLabel??`Stop`:n?.copy?.sendButtonLabel??`Send`)},glyphStack:r.querySelector(At)}},Pt=(e,t,n=`idle`,r=`none`)=>{let i=t?.voiceRecognition??{},a=e=>J(t,`voiceRecognition.${e}`),o=(e,n)=>q(t,`voice.control`,e,n),s=a(`iconSize`)||i.iconSize;X(e,s||(o(`size`,``)?o(`size`,`var(--persona-composer-control-size, 40px)`):``),s),e.classList.add(m),e.classList.toggle(p,!s&&!o(`size`,``)),e.style.fontSize=`18px`,e.style.lineHeight=`1`;let c=a(`iconColor`)||J(t,`sendButton.textColor`)||o(`foreground`,`var(--persona-text, #111827)`),l=a(`backgroundColor`)||J(t,`sendButton.backgroundColor`)||o(`background`,i.backgroundColor||`transparent`),u=a(`borderColor`)||o(`borderColor`,i.borderColor||`transparent`),d=a(`borderWidth`)||o(`borderWidth`,i.borderWidth||``);e.style.borderWidth=d,e.style.borderStyle=d?`solid`:``,e.style.borderRadius=o(`borderRadius`,``)?o(`borderRadius`,`var(--persona-button-radius)`):``,Y(e,o(`padding`,``)?o(`padding`,`0px`):``,a(`paddingX`)||(o(`padding`,``)?void 0:i.paddingX),a(`paddingY`)||(o(`padding`,``)?void 0:i.paddingY));let f=a(`recordingBackgroundColor`)||`var(--persona-voice-recording-bg, #ef4444)`,h=a(`recordingIconColor`)||`var(--persona-voice-recording-indicator, #ffffff)`,g=a(`recordingBorderColor`)||`var(--persona-consumer-voice-recording-border, ${i.recordingBorderColor||u})`,_=c,v=l,y=u,b=i.iconName??`mic`;if(n===`recording`)_=h,v=f,y=g;else if(n===`processing`)_=a(`processingIconColor`)||`var(--persona-consumer-voice-processing-icon, ${c})`,v=a(`processingBackgroundColor`)||`var(--persona-consumer-voice-processing-background, ${l})`,y=a(`processingBorderColor`)||`var(--persona-components-voice-processing-border, ${u})`,b=i.processingIconName??`loader`;else if(n===`speaking`){let e=r===`barge-in`;_=a(`speakingIconColor`)||`var(--persona-consumer-voice-speaking-icon, ${e&&a(`recordingIconColor`)||c})`,v=a(`speakingBackgroundColor`)||`var(--persona-components-voice-speaking-background, ${e?f:l})`,y=a(`speakingBorderColor`)||`var(--persona-components-voice-speaking-border, ${e?g:u})`,b=i.speakingIconName??(r===`cancel`?`square`:e?`mic`:`volume-2`)}e.style.color=_,e.style.backgroundColor=v,e.style.borderColor=y,e.setAttribute(`data-state`,n);let x=parseFloat(i.iconSize??``)||24,S=R(b,x,`currentColor`,1.5);if(e.replaceChildren(),S){let t=s||(o(`iconSize`,``)?o(`iconSize`,`var(--persona-composer-control-icon-size, 24px)`):``);S.style.width=S.style.height=t,!s&&o(`iconSize`,``)&&(S.style.flexBasis=t),S.style.strokeWidth=o(`iconStrokeWidth`,`1.5`),e.appendChild(S)}else e.textContent=`🎤`},Ft=e=>{let t=e?.voiceRecognition??{};if(t.enabled!==!0||t.showButton===!1)return null;let n=typeof window<`u`&&(window.webkitSpeechRecognition!==void 0||window.SpeechRecognition!==void 0),r=t.provider?.type===`runtype`,i=t.provider?.type===`custom`||t.dictation?.provider?.type===`custom`;if(!(n||r||i))return null;let a=u(`div`,`persona-send-button-wrapper`),o=l(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-control`,attrs:{type:`button`,"data-persona-composer-mic":``,"data-state":`idle`,"aria-label":t.tooltipText??`Start voice recognition`}});Pt(o,e),a.appendChild(o);let s=t.tooltipText??`Start voice recognition`;return K({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??s,enabled:t.showTooltip??!1}),{button:o,wrapper:a}},It=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=u(`div`,`persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2`);n.setAttribute(`data-persona-composer-attachment-previews`,``),n.style.display=`none`;let r=u(`input`);r.type=`file`,r.setAttribute(`data-persona-composer-attachment-input`,``),r.accept=(t.allowedTypes??f).join(`,`),r.multiple=(t.maxFiles??4)>1,r.style.display=`none`,r.setAttribute(`aria-label`,`Attach files`);let i=t.buttonIconName??`paperclip`,a=u(`div`,`persona-send-button-wrapper`),o=l(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${m} ${p}`,attrs:{type:`button`,"data-persona-composer-attachment-button":``,"aria-label":t.buttonTooltipText??`Attach file`},style:{fontSize:`18px`,lineHeight:`1`}}),s=R(i,24,`currentColor`,1.5);s?o.appendChild(s):o.textContent=`📎`,o.addEventListener(`click`,e=>{e.preventDefault(),r.click()}),a.appendChild(o);let c=t.buttonTooltipText??`Attach file`;return K({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??c}),{button:o,wrapper:a,input:r,previewsContainer:n}},Lt=e=>{let t=e?.statusIndicator??{},n=t.align===`left`?`persona-text-left`:t.align===`center`?`persona-text-center`:`persona-text-right`,r=u(`div`,`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute(`data-persona-composer-status`,``),Ze(r,t,`idle`);let i=t.idleText??`Online`;if(t.idleLink){let e=u(`a`);e.href=t.idleLink,e.target=`_blank`,e.rel=`noopener noreferrer`,e.textContent=i,e.style.color=`inherit`,e.style.textDecoration=`none`,r.appendChild(e)}else r.textContent=i;return r},Rt=()=>l(`div`,{className:`persona-mb-3 persona-flex persona-flex-wrap persona-gap-2`,attrs:{"data-persona-composer-suggestions":``}});function zt(e){let{config:t,onOpen:n}=e,r=t.buttonIconName??`plus`,i=t.buttonTooltipText??`Add context`,a=u(`div`,`persona-send-button-wrapper`),o=l(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${m} ${p}`,attrs:{type:`button`,"data-persona-composer-mention-button":``,"aria-label":i,"aria-haspopup":`listbox`,"aria-expanded":`false`},style:{fontSize:`18px`,lineHeight:`1`}}),s=R(r,24,`currentColor`,1.5);return s?o.appendChild(s):o.textContent=`+`,o.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),n()}),a.appendChild(o),K({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??i}),{button:o,wrapper:a}}function Bt(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=l(`span`,{className:c(`persona-mention-token`,t.readonly&&`persona-mention-token-readonly`),attrs:{"data-mention-source":e.sourceId,title:e.label,role:`img`,"aria-label":`${e.label} mention`}});e.color&&n.style.setProperty(`--persona-mention-token-accent`,e.color);let r=R(e.iconName??`at-sign`,13,`currentColor`,2);if(r){let e=u(`span`,`persona-mention-token-icon`);e.appendChild(r),n.appendChild(e)}return n.appendChild(l(`span`,{className:`persona-mention-token-label`,text:`@${e.label}`})),n}export{it as A,vt as C,z as D,ot as E,qe as F,R as I,et as M,Ze as N,tt as O,Qe as P,mt as S,ut as T,Y as _,It as a,J as b,Nt as c,Z as d,St as f,Et as g,Q as h,$ as i,st as j,nt as k,Lt as l,Ot as m,zt as n,kt as o,Ct as p,Pt as r,Ft as s,Bt as t,Rt as u,X as v,pt as w,K as x,q as y};
|
|
1
|
+
import{f as e,m as t,p as n,r,s as i}from"./chunk-CEPM3FOp.js";import{r as a,t as o}from"./chunk-BnfM7-qg.js";import{t as s}from"./chunk-CnxIZOzx.js";import{i as c,r as l,t as u}from"./chunk-D5BxWOFB.js";import{r as d}from"./chunk-Bb41bKyp.js";import{t as f}from"./chunk-BlTD-Wgn.js";import{n as p,t as m}from"./chunk-BAkaTZpd.js";import{i as h,n as g,r as _,t as v}from"./chunk-BGPPJ_ui.js";import{t as y}from"./chunk-Bj8Hnh10.js";import{r as b}from"./chunk-Cy1A8vbF.js";import{Activity as x,ArrowDown as S,ArrowLeft as C,ArrowRight as w,ArrowUp as T,ArrowUpRight as E,AtSign as ee,Bot as D,Check as O,ChevronDown as k,ChevronLeft as A,ChevronRight as j,ChevronUp as M,Clipboard as N,ClipboardCopy as P,CodeXml as te,Copy as ne,Download as re,Ellipsis as ie,ExternalLink as ae,Eye as oe,File as se,FileCode as ce,FileSpreadsheet as le,FileText as ue,History as de,ImagePlus as fe,Loader as pe,LoaderCircle as me,Maximize as he,Menu as ge,MessageSquare as _e,Mic as ve,Minimize as ye,Minus as be,PanelLeft as xe,Paperclip as Se,Pencil as Ce,Plus as we,Quote as Te,RefreshCw as Ee,Search as De,Send as Oe,ShieldAlert as ke,ShieldCheck as Ae,ShieldX as je,Square as Me,Star as Ne,ThumbsDown as Pe,ThumbsUp as Fe,Trash as Ie,Trash2 as Le,Upload as Re,Volume2 as ze,X as Be}from"lucide";const Ve={activity:x,"arrow-down":S,"arrow-up":T,"arrow-up-right":E,bot:D,"chevron-down":k,"chevron-up":M,"chevron-right":j,"chevron-left":A,check:O,clipboard:N,"clipboard-copy":P,"code-xml":te,copy:ne,file:se,"file-code":ce,"file-spreadsheet":le,"file-text":ue,"image-plus":fe,loader:pe,"loader-circle":me,mic:ve,paperclip:Se,quote:Te,"refresh-cw":Ee,search:De,send:Oe,"shield-alert":ke,"shield-check":Ae,"shield-x":je,square:Me,"square-text":[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`}],[`path`,{d:`M7 8h10M7 12h10M7 16h6`}]],"thumbs-down":Pe,"thumbs-up":Fe,upload:Re,"volume-2":ze,"voice-bars":[[`path`,{d:`M4 10v4`}],[`path`,{d:`M8 6v12`}],[`path`,{d:`M12 3v18`}],[`path`,{d:`M16 7v10`}],[`path`,{d:`M20 10v4`}]],x:Be,"at-sign":ee,"arrow-left":C,"arrow-right":w,"external-link":ae,ellipsis:ie,menu:ge,"panel-left":xe,plus:we,minus:be,pencil:Ce,trash:Ie,"trash-2":Le,download:re,maximize:he,minimize:ye,"message-square":_e,star:Ne,eye:oe,history:de},He=/* @__PURE__ */ `brain.toolbox.wrench.circle.database.terminal.user.mail.phone.calendar.clock.building.map-pin.lock.key.credit-card.hash.globe.link.circle-check.circle-x.triangle-alert.info.ban.shield.ellipsis-vertical.house.pen-line.save.share.funnel.settings.rotate-cw.shopping-cart.shopping-bag.package.truck.tag.gift.receipt.wallet.store.dollar-sign.percent.play.pause.volume-x.camera.image.film.headphones.message-circle.bell.heart.eye-off.bookmark.calendar-days.timer.folder.folder-open.files.chart-column.sparkles.zap.sun.moon.flag.lightbulb.monitor.smartphone`.split(`.`),F=new Map(Object.entries(Ve)),I=/* @__PURE__ */ new Map;let L=!1;const Ue=/* @__PURE__ */ new Set,We=e=>{let t=[...Ue];e&&Ue.clear();for(let e of t)try{e()}catch{}},Ge=()=>{let e=0;for(let[t,n]of I){let r=F.get(n);if(!r)continue;I.delete(t),e++;let i=s(r);if(i)for(t.removeAttribute(`data-persona-icon-pending`);i.firstChild;)t.appendChild(i.firstChild)}return e},Ke=e=>{if(!L){for(let[t,n]of Object.entries(e))F.has(t)||F.set(t,n);L=!0,Ge(),We(!0)}},qe=()=>L?null:o().then(e=>Ke(e.EXTRA_LUCIDE_ICONS)),Je=()=>{qe()?.catch(e=>{console.warn(`[Persona] Failed to load the icons-extra chunk`,e)})},Ye=(e,t,n)=>{let r=s([],e,t,n);return r.setAttribute(`data-persona-icon-pending`,`true`),r},R=(e,t=24,n=`currentColor`,r=2)=>{let i=F.get(e);if(i)return s(i,t,n,r);if(He.includes(e)){let i=Ye(t,n,r);return I.size>=500&&I.delete(I.keys().next().value),I.set(i,e),Je(),i}return console.warn(`Unknown Persona icon "${e}". Use registerIcons().`),null},Xe=(e,t)=>e.visible!==!1&&(e.mode!==`transient`||t===`connecting`||t===`paused`||t===`resuming`||t===`error`),Ze=(e,t,n)=>{let r=t.mode===`transient`,i=e.hasAttribute(`data-persona-composer-reason`)||e.hasAttribute(`data-persona-composer-notice`);e.style.display=Xe(t,n)||r&&i&&t.visible!==!1?``:`none`,e.classList.toggle(`persona-mt-2`,!r),e.classList.toggle(`persona-mb-2`,r)},Qe=(e,t,n)=>{t.parentElement&&e.parentElement===t.parentElement&&(n.mode===`transient`?e.nextElementSibling!==t&&t.before(e):t.nextElementSibling!==e&&t.after(e))};function $e(e){let t=e.ownerDocument?.defaultView;if(!t?.getComputedStyle)return 20;let n=t.getComputedStyle(e).lineHeight;if(!n||!n.trim().endsWith(`px`))return 20;let r=parseFloat(n);return Number.isFinite(r)&&r>0?r:20}function et(e,t){return typeof e!=`number`||!Number.isFinite(e)?t:e>0?e:t}function tt(e,t){e.style.maxHeight=`${t*$e(e)}px`,e.style.overflowY=`auto`}function nt(e){let t=e?.ownerDocument?.defaultView??(typeof window<`u`?window:null);if(!t||typeof t.matchMedia!=`function`)return!1;try{return t.matchMedia(`(pointer: coarse)`).matches===!0}catch{return!1}}function rt(e){return e.insertNewlineOnTouchEnter===!0&&e.coarsePointer===!0}function it(e,t){if(e.key!==`Enter`||e.shiftKey||e.isComposing)return!1;let n=e.metaKey===!0||e.ctrlKey===!0,r=t.submitKey??`enter`;return r===`none`?!1:r===`mod-enter`?n:n||!rt(t)}function at(e){return(e.submitKey??`enter`)===`enter`?rt(e)?`enter`:`send`:`enter`}function ot(e,t){e.setAttribute(`enterkeyhint`,at(t))}function z(e,t){let n=t?.autocomplete;e.setAttribute(`autocomplete`,typeof n==`string`&&n?n:`off`);let r=(t,n)=>{n===void 0?e.removeAttribute(t):e.setAttribute(t,n)};r(`autocapitalize`,typeof t?.autocapitalize==`string`?t.autocapitalize:void 0),r(`spellcheck`,typeof t?.spellcheck==`boolean`?String(t.spellcheck):void 0),r(`inputmode`,typeof t?.inputmode==`string`&&t.inputmode?t.inputmode:void 0),r(`aria-label`,typeof t?.ariaLabel==`string`&&t.ariaLabel?t.ariaLabel:void 0)}function st(e){return e===!0?{disabled:!0}:!e||typeof e!=`object`?{disabled:!1}:{disabled:!0,reason:typeof e.reason==`string`&&e.reason?e.reason:void 0}}const{setLoader:ct,load:lt}=a({fallbackImport:()=>import(`./chunk-Co3VVwGe.js`)}),ut=lt,{setLoader:dt,load:ft}=a({fallbackImport:()=>import(`./chunk-Bkma5hIU.js`),resetOnSetLoader:!0}),pt=ft;let B=400,V=300,H=0;const U=e=>Math.max(0,e);function mt(e){e.delayMs!==void 0&&(B=U(e.delayMs)),e.skipDelayMs!==void 0&&(V=U(e.skipDelayMs))}const ht=()=>Date.now()<H,gt=e=>{H=e>0?Date.now()+e:0},W=/* @__PURE__ */ new WeakMap,_t=e=>typeof e.closest==`function`&&e.closest(`[data-persona-tooltip-suppressed]`)!==null;function vt(e){W.get(e)?.hide()}const yt=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&`host`in e,bt=e=>{let t=e.getRootNode?.();return yt(t)?t:e.closest(`dialog[open]`)??e.ownerDocument.body},G=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n)),xt=[...[`background`,`foreground`,`hint-fg`,`radius`,`font-size`,`padding`,`max-width`,`shadow`,`arrow-display`].map(e=>`--persona-tooltip-${e}`),`--persona-font-family`,`--persona-radius-sm`];function K(e){W.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:r,hint:i,enabled:a=!0,gap:o=8,viewportPadding:s=8}=e,c=()=>t.ownerDocument,l=()=>c().defaultView??window,u=null,f=null,p=null,m=null,h,g=!1,_=!1,v=!1,y=()=>(typeof r==`function`?r():r).trim(),b=()=>(typeof i==`function`?i():i??``).trim(),x=()=>U(e.delayMs??B),S=()=>U(e.skipDelayMs??V),C=()=>{h!==void 0&&(l().clearTimeout(h),h=void 0)},w=()=>{C();let e=u!==null;m?.(),m=null,u?.remove(),u=null,f=null,p=null,e&>(S())},T=()=>{if(!u)return;let e=c(),n=l(),r=t.getBoundingClientRect(),i=u.getBoundingClientRect(),a=e.documentElement.clientWidth||n.innerWidth,d=e.documentElement.clientHeight||n.innerHeight,f=a-s-i.width,p=r.left+r.width/2-i.width/2,m=G(p,s,f),h=r.top-s,g=d-s-r.bottom,_=h>=i.height+o||h>=g?`top`:`bottom`,v=_===`top`?r.top-o-i.height:r.bottom+o,y=d-s-i.height,b=G(v,s,y),x=r.left+r.width/2,S=Math.max(10,i.width-10),C=G(x-m,10,S);u.dataset.placement=_,u.style.left=`${m}px`,u.style.top=`${b}px`,u.style.setProperty(`--persona-tooltip-arrow-x`,`${C}px`)},E=()=>{if(v||!a||u||!t.isConnected||_t(t))return;let e=y(),n=bt(t);if(!e||!n)return;let r=c(),i=l();u=r.createElement(`div`),u.className=`persona-control-tooltip`,u.setAttribute(`role`,`tooltip`),u.dataset.state=`measuring`,u.style.zIndex=String(d);let o=i.getComputedStyle?.(t);if(o){for(let e of xt){let t=o.getPropertyValue(e).trim();t&&u.style.setProperty(e,t)}o.fontFamily&&(u.style.fontFamily=o.fontFamily)}f=r.createElement(`span`),f.className=`persona-control-tooltip__label`,f.textContent=e,u.appendChild(f);let s=b();s&&(p=r.createElement(`span`),p.className=`persona-control-tooltip__hint`,p.textContent=s,u.appendChild(p));let h=r.createElement(`span`);h.className=`persona-control-tooltip__arrow`,u.appendChild(h),n.appendChild(u),T(),u.dataset.state=`open`;let g=()=>{if(!t.isConnected){w();return}f&&(f.textContent=y()),p&&(p.textContent=b());let e=bt(t);u&&e&&u.parentNode!==e&&e.appendChild(u),T()};i.addEventListener(`scroll`,g,!0),i.addEventListener(`resize`,g);let _=t.closest(`[data-persona-root]`);_?.addEventListener(`persona:internal:host-moved`,g);let x=t.getRootNode(),S=yt(x)?x:r.documentElement,C=typeof MutationObserver>`u`?null:new MutationObserver(()=>{t.isConnected||w()});C?.observe(S,{childList:!0,subtree:!0}),m=()=>{i.removeEventListener(`scroll`,g,!0),i.removeEventListener(`resize`,g),_?.removeEventListener(`persona:internal:host-moved`,g),C?.disconnect()}},ee=e=>{v||u||(C(),e||x()<=0||ht()?E():h=l().setTimeout(()=>{h=void 0,E()},x()))},D=()=>{g||_?ee(_):w()},O=()=>{let e=l();e.matchMedia&&e.matchMedia(`(hover: none)`).matches||(g=!0,D())},k=()=>{g=!1,D()},A=()=>{try{_=t.matches(`:focus-visible`)}catch{_=!0}D()},j=()=>{_=!1,D()},M=()=>{g=!1,_=!1,w()},N=e=>{e.key===`Escape`&&M()};n.addEventListener(`mouseenter`,O),n.addEventListener(`mouseleave`,k),t.addEventListener(`focus`,A),t.addEventListener(`blur`,j),t.addEventListener(`keydown`,N),t.addEventListener(`click`,M);let P={get isOpen(){return u!==null},show:E,hide:w,reposition:T,destroy:()=>{v||(v=!0,w(),n.removeEventListener(`mouseenter`,O),n.removeEventListener(`mouseleave`,k),t.removeEventListener(`focus`,A),t.removeEventListener(`blur`,j),t.removeEventListener(`keydown`,N),t.removeEventListener(`click`,M),W.delete(t))}};return W.set(t,P),P}const q=(e,t,n,r)=>{let[i,a]=t.split(`.`);return[e?.theme,e?.darkTheme].some(e=>e?.components?.[i]?.[a]?.[n]!==void 0)?`var(--persona-components-${t.replace(`.`,`-`)}-${n}, ${r})`:r},J=(e,t)=>{let n=e&&r(e,t);return typeof n==`string`&&n?n:void 0},Y=(e,t,n,r)=>{let i=t.startsWith(`var(`);e.classList.toggle(`persona-theme-padding`,i),e.style.padding=i?``:t,i?e.style.setProperty(`--persona-theme-padding`,t):e.style.removeProperty(`--persona-theme-padding`),n&&(e.style.paddingLeft=e.style.paddingRight=n),r&&(e.style.paddingTop=e.style.paddingBottom=r)},X=(e,t,n)=>{let r=t.startsWith(`var(`)&&t.includes(`--persona-components-`);e.classList.toggle(`persona-control-size`,r),r?e.style.setProperty(`--persona-control-size`,t):e.style.removeProperty(`--persona-control-size`),e.style.width=e.style.height=t,e.style.minWidth=e.style.minHeight=n??``},St=`min(440px, calc(100vw - 24px))`,Ct=`40px`,wt={apiUrl:`https://api.runtype.com/api/chat/dispatch`,clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:`light`,tooltip:{delayMs:400,skipDelayMs:300},launcher:{enabled:!0,mountMode:`floating`,dock:{side:`right`,width:`420px`},title:`Chat Assistant`,subtitle:`Here to help you get answers fast`,agentIconText:`💬`,agentIconName:`bot`,headerIconName:`bot`,position:`bottom-right`,width:St,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:`40px`,headerIconSize:Ct,closeButtonPaddingX:`0px`,closeButtonPaddingY:`0px`,callToActionIconName:`arrow-up-right`,callToActionIconText:``,callToActionIconSize:`32px`,callToActionIconPadding:`5px`,callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:`transparent`,clearChat:{backgroundColor:`transparent`,borderColor:`transparent`,enabled:!0,placement:`inline`,iconName:`refresh-cw`,showTooltip:!0,tooltipText:`Clear chat`,paddingX:`0px`,paddingY:`0px`},headerIconHidden:!1,border:void 0,shadow:`0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)`},copy:{inputPlaceholder:`How can I help...`,sendButtonLabel:`Send`},sendButton:{borderWidth:`0px`,paddingX:`12px`,paddingY:`10px`,borderColor:void 0,useIcon:!0,iconText:`↑`,showTooltip:!0,tooltipText:`Send message`,iconName:`send`},statusIndicator:{visible:!0,idleText:`Online`,connectingText:`Connecting…`,connectedText:`Streaming…`,errorText:`Offline`},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:`mic`,borderWidth:`0px`,iconColor:void 0,backgroundColor:`transparent`,borderColor:`transparent`,recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:`transparent`,showTooltip:!0,tooltipText:`Start voice recognition`},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:`arrow-down`,label:``,streamingIndicator:`arrow`,scrollBehavior:`instant`,scrollDurationMs:220,transition:`none`},scrollBehavior:{mode:`anchor-top`,anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:_,reasoningDisplay:v,streamAnimation:{type:`none`,placeholder:`none`,speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:`Other…`,freeTextPlaceholder:`Type your answer…`,submitLabel:`Send`},history:{enabled:!1,presentation:`panel`,showScopeStatus:!0,showDelete:!0,showDeleteAll:!0}},suggestionChips:[`Show me what you can help with`,`Walk me through getting started`,`Answer a question about this page`],suggestionChipsConfig:{fontFamily:`sans-serif`,fontWeight:`500`,paddingX:`12px`,paddingY:`6px`},layout:{header:{layout:`default`,showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:`bubble`,avatar:{show:!1,position:`left`},timestamp:{show:!1,position:`below`},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:`hover`,align:`right`,layout:`pill-inside`},debug:!1},Tt={},Z={colorScheme:`light`,errorDisplay:`block`,messageActions:{visibility:void 0},suggestionChipsConfig:{fontWeight:void 0},approval:y,loadingIndicator:{variant:`label`},launcher:{variant:`circle`,width:`min(400px, calc(100vw - 24px))`,headerIconSize:`20px`},features:{artifacts:{enabled:!0},scrollToBottom:{streamingIndicator:`dots`,transition:`fade`,scrollBehavior:`smooth`},toolCallDisplay:h,reasoningDisplay:g},composer:{layout:`single-row`,placement:`overlay`},sendButton:{iconName:`arrow-up`},statusIndicator:{mode:`transient`},layout:{contentMaxWidth:`768px`,topFade:!0,header:{showSubtitle:!1},messages:{assistant:{width:`full`}}}};function Et(e){return e?.future?.v5Defaults===!0?`v5`:`v4`}function Q(t){let n=Et(t)===`v5`?Z:Tt;return e(wt,n)}Q();function Dt(t,n){if(t||n)return t?n?e(t,n):t:n}function Ot(e){let r=Q(e);return e?i(t(b({...r,...e,colorScheme:n(e,[`colorScheme`]).includes(`colorScheme`)?e.colorScheme:e.brand?void 0:r.colorScheme,...r.approval||e.approval!==void 0?{approval:e.approval!==!1&&{...r.approval||{},...e.approval}}:{},theme:Dt(r.theme,e.theme),darkTheme:Dt(r.darkTheme,e.darkTheme),launcher:{...r.launcher,...e.launcher,dock:{...r.launcher?.dock,...e.launcher?.dock},clearChat:{...r.launcher?.clearChat,...e.launcher?.clearChat}},...r.composer||e.composer?{composer:{...r.composer,...e.composer}}:{},tooltip:{...r.tooltip,...e.tooltip},copy:{...r.copy,...e.copy},sendButton:{...r.sendButton,...e.sendButton},statusIndicator:{...r.statusIndicator,...e.statusIndicator},voiceRecognition:{...r.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=r.features?.artifacts,n=e.features?.artifacts,i=r.features?.scrollToBottom,a=e.features?.scrollToBottom,o=r.features?.scrollBehavior,s=e.features?.scrollBehavior,c=r.features?.streamAnimation,l=e.features?.streamAnimation,u=r.features?.askUserQuestion,d=e.features?.askUserQuestion,f=r.features?.history,p=e.features?.history,m=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},h=i===void 0&&a===void 0?void 0:{...i,...a},g=o===void 0&&s===void 0?void 0:{...o,...s},_=c===void 0&&l===void 0?void 0:{...c,...l},v=u===void 0&&d===void 0?void 0:{...u,...d,styles:{...u?.styles,...d?.styles}},y=f===void 0&&p===void 0?void 0:{...f,...p,copy:{...f?.copy,...p?.copy}};return{...r.features,...e.features,toolCallDisplay:{...r.features?.toolCallDisplay,...e.features?.toolCallDisplay,...e.features?.toolCallDisplay?.layout===void 0&&e.features?.toolCallDisplay?.variant!==void 0?{layout:e.features.toolCallDisplay.variant}:{}},reasoningDisplay:{...r.features?.reasoningDisplay,...e.features?.reasoningDisplay,...e.features?.reasoningDisplay?.layout===void 0&&e.features?.reasoningDisplay?.variant!==void 0?{layout:e.features.reasoningDisplay.variant}:{}},...h===void 0?{}:{scrollToBottom:h},...g===void 0?{}:{scrollBehavior:g},...m===void 0?{}:{artifacts:m},..._===void 0?{}:{streamAnimation:_},...v===void 0?{}:{askUserQuestion:v},...y===void 0?{}:{history:y}}})(),suggestionChips:e.suggestionChips??r.suggestionChips,suggestionChipsConfig:{...r.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...r.layout,...e.layout,header:{...r.layout?.header,...e.layout?.header},messages:{...r.layout?.messages,...e.layout?.messages,...r.layout?.messages?.user||e.layout?.messages?.user?{user:{...r.layout?.messages?.user,...e.layout?.messages?.user}}:{},...r.layout?.messages?.assistant||e.layout?.messages?.assistant?{assistant:{...r.layout?.messages?.assistant,...e.layout?.messages?.assistant}}:{},avatar:{...r.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...r.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...r.layout?.slots,...e.layout?.slots}},markdown:{...r.markdown,...e.markdown,options:{...r.markdown?.options,...e.markdown?.options}},messageActions:{...r.messageActions,...e.messageActions}},e),e,Z),e):i(t(b(r),void 0,Z))}const kt=(e,t)=>{let n=u(`textarea`);n.setAttribute(`data-persona-composer-input`,``),n.placeholder=e?.copy?.inputPlaceholder??`How can I help...`,n.dir=`auto`,ot(n,{submitKey:e?.composer?.submitKey,insertNewlineOnTouchEnter:e?.composer?.insertNewlineOnTouchEnter,coarsePointer:nt(n)}),z(n,e?.composer?.inputAttributes),n.className=`persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-text focus:persona-outline-none focus:persona-border-none persona-composer-textarea`,n.rows=1,n.style.fontFamily=`var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))`,n.style.fontWeight=`var(--persona-input-font-weight, var(--persona-font-weight, 400))`;let r=et(e?.composer?.maxLines,t?.defaultMaxLines??3),i=`${r*20}px`;n.style.maxHeight=i,n.style.overflowY=`auto`;let a=()=>{let e=n.style.maxHeight;if(e!==i){let t=parseFloat(e);if(Number.isFinite(t)&&t>0)return t}let t=r*$e(n);return i=`${t}px`,n.style.maxHeight=i,t},o=()=>{n.addEventListener(`input`,()=>{n.style.height=`auto`;let e=Math.min(n.scrollHeight,a());n.style.height=`${e}px`})};return n.style.border=`none`,n.style.outline=`none`,n.style.borderWidth=`0`,n.style.borderStyle=`none`,n.style.borderColor=`transparent`,n.addEventListener(`focus`,()=>{n.style.border=`none`,n.style.outline=`none`,n.style.borderWidth=`0`,n.style.borderStyle=`none`,n.style.borderColor=`transparent`,n.style.boxShadow=`none`}),n.addEventListener(`blur`,()=>{n.style.border=`none`,n.style.outline=`none`}),{textarea:n,attachAutoResize:o}},At=`[data-persona-glyph-stack]`,jt=(e,t,n=`send`)=>{let r=l(`span`,{className:`persona-composer-glyph-stack`,attrs:{"data-mode":n,"data-persona-glyph-stack":``}});return e.setAttribute(`data-glyph`,`send`),t.setAttribute(`data-glyph`,`stop`),r.append(e,t),r},Mt=/* @__PURE__ */ new WeakMap,$=(e,t,n=!0)=>{Mt.set(e,t);let r=t?.sendButton??{},i=r.useIcon??!1,a=e.getAttribute(`data-persona-send-mode`)===`stop`?`stop`:`send`,o=e=>J(t,`sendButton.${e}`),s=(e,n)=>q(t,`composer.send`,e,n),l=o(`size`)||r.size;e.style.fontSize=i?`18px`:``,e.style.lineHeight=i?`1`:``,e.className=c(`persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer`,i?`persona-flex persona-items-center persona-justify-center ${m}`:`persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold`,i&&!o(`backgroundColor`)&&`persona-bg-persona-primary`,!i&&!o(`textColor`)&&`persona-text-white`),X(e,i?l||(s(`size`,``)?s(`size`,`var(--persona-composer-control-size, 40px)`):``):``,i?l:void 0);let u=s(`foreground`,i?`var(--persona-send-button-fg, var(--persona-button-primary-fg, #ffffff))`:`#ffffff`),d=s(`background`,i?`var(--persona-button-primary-bg, var(--persona-primary, #111827))`:`var(--persona-accent, #0f0f0f)`);e.style.color=o(`textColor`)||(a===`stop`&&s(`foreground`,``)?`var(--persona-button-stop-fg, ${u})`:s(`foreground`,``)||(i?u:``)),e.style.backgroundColor=(i?o(`backgroundColor`):void 0)||(s(`background`,``)?a===`stop`?`var(--persona-button-stop-bg, ${d})`:d:``);let f=o(`borderWidth`)||(s(`borderWidth`,``)?s(`borderWidth`,r.borderWidth||`0px`):r.borderWidth||``);e.style.borderWidth=f,e.style.borderStyle=f?`solid`:``,e.style.borderColor=o(`borderColor`)||(s(`borderColor`,``)?s(`borderColor`,r.borderColor||`transparent`):r.borderColor||``),e.style.borderRadius=s(`borderRadius`,``)?s(`borderRadius`,`var(--persona-components-composer-sendButtonRadius, var(--persona-button-radius))`):``,Y(e,s(`padding`,i?`0`:`8px 16px`),i?void 0:o(`paddingX`)||(s(`padding`,``)?void 0:r.paddingX),i?void 0:o(`paddingY`)||(s(`padding`,``)?void 0:r.paddingY));let p=parseFloat(r.iconSize??``)||Math.round((parseFloat(r.size??``)||40)*.5);if(n){if(e.replaceChildren(),i){let t=r.iconStrokeWidth??2,n=r.iconName?R(r.iconName,p,`currentColor`,t):null,i=R(r.stopIconName??`square`,p,`currentColor`,t);n&&i?e.appendChild(jt(n,i,a)):n?e.appendChild(n):e.textContent=r.iconText??`↑`}else e.textContent=a===`stop`?t?.copy?.stopButtonLabel??`Stop`:t?.copy?.sendButtonLabel??`Send`}for(let n of Array.from(e.querySelectorAll(`svg`))){n.style.width=n.style.height=o(`iconSize`)?``:s(`iconSize`,`var(--persona-components-composer-sendIconSize, ${p}px)`);let e=t?.sendButton?.iconStrokeWidth;n.style.strokeWidth=e===void 0?s(`iconStrokeWidth`,``):String(e)}},Nt=e=>{let t=e?.sendButton,n=u(`div`,`persona-send-button-wrapper`),r=l(`button`,{attrs:{type:`submit`,"data-persona-composer-submit":``,"data-persona-send-mode":`send`}});return $(r,e),r.setAttribute(`aria-label`,t?.tooltipText??`Send message`),n.appendChild(r),K({anchor:r,trigger:n,text:()=>r.getAttribute(`aria-label`)??``,enabled:t?.showTooltip??!1}),{button:r,wrapper:n,setMode:e=>{if(r.getAttribute(`data-persona-send-mode`)===e)return;r.setAttribute(`data-persona-send-mode`,e),r.setAttribute(`aria-label`,e===`stop`?t?.stopTooltipText??`Stop generating`:t?.tooltipText??`Send message`);let n=Mt.get(r);$(r,n,!1),r.querySelector(At)?.setAttribute(`data-mode`,e),(n?.sendButton?.useIcon??!1)||(r.textContent=e===`stop`?n?.copy?.stopButtonLabel??`Stop`:n?.copy?.sendButtonLabel??`Send`)},glyphStack:r.querySelector(At)}},Pt=(e,t,n=`idle`,r=`none`)=>{let i=t?.voiceRecognition??{},a=e=>J(t,`voiceRecognition.${e}`),o=(e,n)=>q(t,`voice.control`,e,n),s=a(`iconSize`)||i.iconSize;X(e,s||(o(`size`,``)?o(`size`,`var(--persona-composer-control-size, 40px)`):``),s),e.classList.add(m),e.classList.toggle(p,!s&&!o(`size`,``)),e.style.fontSize=`18px`,e.style.lineHeight=`1`;let c=a(`iconColor`)||J(t,`sendButton.textColor`)||o(`foreground`,`var(--persona-text, #111827)`),l=a(`backgroundColor`)||J(t,`sendButton.backgroundColor`)||o(`background`,i.backgroundColor||`transparent`),u=a(`borderColor`)||o(`borderColor`,i.borderColor||`transparent`),d=a(`borderWidth`)||o(`borderWidth`,i.borderWidth||``);e.style.borderWidth=d,e.style.borderStyle=d?`solid`:``,e.style.borderRadius=o(`borderRadius`,``)?o(`borderRadius`,`var(--persona-button-radius)`):``,Y(e,o(`padding`,``)?o(`padding`,`0px`):``,a(`paddingX`)||(o(`padding`,``)?void 0:i.paddingX),a(`paddingY`)||(o(`padding`,``)?void 0:i.paddingY));let f=a(`recordingBackgroundColor`)||`var(--persona-voice-recording-bg, #ef4444)`,h=a(`recordingIconColor`)||`var(--persona-voice-recording-indicator, #ffffff)`,g=a(`recordingBorderColor`)||`var(--persona-consumer-voice-recording-border, ${i.recordingBorderColor||u})`,_=c,v=l,y=u,b=i.iconName??`mic`;if(n===`recording`)_=h,v=f,y=g;else if(n===`processing`)_=a(`processingIconColor`)||`var(--persona-consumer-voice-processing-icon, ${c})`,v=a(`processingBackgroundColor`)||`var(--persona-consumer-voice-processing-background, ${l})`,y=a(`processingBorderColor`)||`var(--persona-components-voice-processing-border, ${u})`,b=i.processingIconName??`loader`;else if(n===`speaking`){let e=r===`barge-in`;_=a(`speakingIconColor`)||`var(--persona-consumer-voice-speaking-icon, ${e&&a(`recordingIconColor`)||c})`,v=a(`speakingBackgroundColor`)||`var(--persona-components-voice-speaking-background, ${e?f:l})`,y=a(`speakingBorderColor`)||`var(--persona-components-voice-speaking-border, ${e?g:u})`,b=i.speakingIconName??(r===`cancel`?`square`:e?`mic`:`volume-2`)}e.style.color=_,e.style.backgroundColor=v,e.style.borderColor=y,e.setAttribute(`data-state`,n);let x=parseFloat(i.iconSize??``)||24,S=R(b,x,`currentColor`,1.5);if(e.replaceChildren(),S){let t=s||(o(`iconSize`,``)?o(`iconSize`,`var(--persona-composer-control-icon-size, 24px)`):``);S.style.width=S.style.height=t,!s&&o(`iconSize`,``)&&(S.style.flexBasis=t),S.style.strokeWidth=o(`iconStrokeWidth`,`1.5`),e.appendChild(S)}else e.textContent=`🎤`},Ft=e=>{let t=e?.voiceRecognition??{};if(t.enabled!==!0||t.showButton===!1)return null;let n=typeof window<`u`&&(window.webkitSpeechRecognition!==void 0||window.SpeechRecognition!==void 0),r=t.provider?.type===`runtype`,i=t.provider?.type===`custom`||t.dictation?.provider?.type===`custom`;if(!(n||r||i))return null;let a=u(`div`,`persona-send-button-wrapper`),o=l(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-composer-control`,attrs:{type:`button`,"data-persona-composer-mic":``,"data-state":`idle`,"aria-label":t.tooltipText??`Start voice recognition`}});Pt(o,e),a.appendChild(o);let s=t.tooltipText??`Start voice recognition`;return K({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??s,enabled:t.showTooltip??!1}),{button:o,wrapper:a}},It=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=u(`div`,`persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2`);n.setAttribute(`data-persona-composer-attachment-previews`,``),n.style.display=`none`;let r=u(`input`);r.type=`file`,r.setAttribute(`data-persona-composer-attachment-input`,``),r.accept=(t.allowedTypes??f).join(`,`),r.multiple=(t.maxFiles??4)>1,r.style.display=`none`,r.setAttribute(`aria-label`,`Attach files`);let i=t.buttonIconName??`paperclip`,a=u(`div`,`persona-send-button-wrapper`),o=l(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button ${m} ${p}`,attrs:{type:`button`,"data-persona-composer-attachment-button":``,"aria-label":t.buttonTooltipText??`Attach file`},style:{fontSize:`18px`,lineHeight:`1`}}),s=R(i,24,`currentColor`,1.5);s?o.appendChild(s):o.textContent=`📎`,o.addEventListener(`click`,e=>{e.preventDefault(),r.click()}),a.appendChild(o);let c=t.buttonTooltipText??`Attach file`;return K({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??c}),{button:o,wrapper:a,input:r,previewsContainer:n}},Lt=e=>{let t=e?.statusIndicator??{},n=t.align===`left`?`persona-text-left`:t.align===`center`?`persona-text-center`:`persona-text-right`,r=u(`div`,`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute(`data-persona-composer-status`,``),Ze(r,t,`idle`);let i=t.idleText??`Online`;if(t.idleLink){let e=u(`a`);e.href=t.idleLink,e.target=`_blank`,e.rel=`noopener noreferrer`,e.textContent=i,e.style.color=`inherit`,e.style.textDecoration=`none`,r.appendChild(e)}else r.textContent=i;return r},Rt=()=>l(`div`,{className:`persona-mb-3 persona-flex persona-flex-wrap persona-gap-2`,attrs:{"data-persona-composer-suggestions":``}});function zt(e){let{config:t,onOpen:n}=e,r=t.buttonIconName??`plus`,i=t.buttonTooltipText??`Add context`,a=u(`div`,`persona-send-button-wrapper`),o=l(`button`,{className:`persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button ${m} ${p}`,attrs:{type:`button`,"data-persona-composer-mention-button":``,"aria-label":i,"aria-haspopup":`listbox`,"aria-expanded":`false`},style:{fontSize:`18px`,lineHeight:`1`}}),s=R(r,24,`currentColor`,1.5);return s?o.appendChild(s):o.textContent=`+`,o.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation(),n()}),a.appendChild(o),K({anchor:o,trigger:a,text:()=>o.getAttribute(`aria-label`)??i}),{button:o,wrapper:a}}function Bt(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=l(`span`,{className:c(`persona-mention-token`,t.readonly&&`persona-mention-token-readonly`),attrs:{"data-mention-source":e.sourceId,title:e.label,role:`img`,"aria-label":`${e.label} mention`}});e.color&&n.style.setProperty(`--persona-mention-token-accent`,e.color);let r=R(e.iconName??`at-sign`,13,`currentColor`,2);if(r){let e=u(`span`,`persona-mention-token-icon`);e.appendChild(r),n.appendChild(e)}return n.appendChild(l(`span`,{className:`persona-mention-token-label`,text:`@${e.label}`})),n}export{it as A,vt as C,z as D,ot as E,qe as F,R as I,et as M,Ze as N,tt as O,Qe as P,mt as S,ut as T,Y as _,It as a,J as b,Nt as c,Z as d,St as f,Et as g,Q as h,$ as i,st as j,nt as k,Lt as l,Ot as m,zt as n,kt as o,Ct as p,Pt as r,Ft as s,Bt as t,Rt as u,X as v,pt as w,K as x,q as y};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e}from"./chunk-BAdIgC5d.js";import{t}from"./chunk-DVgzoVCB.js";import{t as n}from"./chunk-i4qGOJAL.js";import{n as r}from"./chunk-DTDHeUsG.js";const i=e=>e.replace(/[^a-zA-Z0-9_]/g,`_`).toLowerCase().replace(/_+/g,`_`).replace(/^_|_$/g,``),a=e=>typeof e==`object`&&!!e&&!Array.isArray(e),o=e=>{if(e.variant!==`tool`)return null;let t=e.agentMetadata?.clientToolAnswer;if(!t||!t.toolCallId||t.result===void 0)return null;let n=i(t.toolName);return n?{call:{toolCallId:t.toolCallId,toolName:n,args:a(t.args)?t.args:{}},result:{toolCallId:t.toolCallId,toolName:n,result:t.result}}:null},s=(e,t)=>{let n=[],r=[],i=[],a=``,s,c=()=>{r.length!==0&&(n.push({role:`assistant`,content:``,createdAt:a,toolCalls:r},{role:`tool`,content:``,createdAt:a,toolResults:i}),r=[],i=[])};for(let l of e){let e=o(l);if(e){let t=l.agentMetadata?.clientToolAnswer?.batch;r.length>0&&(t===void 0||t!==s)&&c(),r.length===0&&(a=l.createdAt,s=t),r.some(t=>t.toolCallId===e.call.toolCallId)||(r.push(e.call),i.push(e.result));continue}let u=t(l);u&&(c(),n.push(u))}return c(),n},c=e=>e.voiceCaption||r(e)?!1:!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0),l=e=>typeof e==`string`?!0:Array.isArray(e)?e.every(e=>{if(!e||typeof e!=`object`)return!1;switch(e.type){case`text`:return typeof e.text==`string`;case`image`:return typeof e.image==`string`;case`audio`:return typeof e.audio==`string`;case`video`:return typeof e.video==`string`;case`file`:return typeof e.data==`string`&&typeof e.mimeType==`string`&&typeof e.filename==`string`;default:return!1}}):!1,u=e=>e.slice().sort((e,t)=>new Date(e.createdAt).getTime()-new Date(t.createdAt).getTime()),d=e=>{let t=e.agentMetadata?.providerPhase??e.agentMetadata?.phase;return e.role===`assistant`&&(t===`commentary`||t===`partial_answer`||t===`final_answer`)?{phase:t}:{}},f=e=>({role:e.role,content:e.contentParts??e.llmContent??e.rawContent??e.content,createdAt:e.createdAt,...d(e)});var p=class{constructor(e){this.host=e}async initializeSession(){await this.host.historyInternals.historyBootstrapReady;let e=this.host.config.getStoredConversationId?.()||null,t=this.host.historyInternals.shouldResumeDurableConversation?.()===!0;if(!this.host.isHistoryCapable()&&!t)return this.#e(e,!1);let n=await this.host.readVisitorToken();if(e&&n)try{let n=await this.createClientSession({conversationId:e,durableResume:t});return t&&n.durableRecovery?.enabled!==!0&&this.host.historyInternals.setStoredResumableHandle?.(null),this.host.finishInit(n,e,!1)}catch(n){if(!(n instanceof this.host.HistoryClientError&&n.code===`not_found`)&&!(n instanceof this.host.HistoryClientError&&n.code===`visitor_required`)&&!(n instanceof this.host.HistoryClientError&&n.code===`history_disabled`))throw n;return t&&this.host.historyInternals.setStoredResumableHandle?.(null),this.#e(e,!0)}return this.#e(e,!1)}async#e(e,t){let n=this.host.historyInternals.visitorStore;return n&&!await this.host.readVisitorToken()?n.withFirstInitLock(()=>this.#t(e,t)):this.#t(e,t)}async#t(e,t){let n=this.host.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:n}),i=await this.#n(r);return this.host.finishInit(i,e,t)}async#n(e){if(!e.visitor?.token||this.host.claimInFlight||!this.host.isHistoryCapable()&&e.durableRecovery?.enabled!==!0)return e;this.host.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:e.sessionId})}catch{return e}finally{this.host.claimInFlight=!1}}async sendWithClientToolsDiff(t,n,r,i){let a=!!(n&&n.length>0),o=a?e(n):void 0,s=this.host.clientToolsFingerprintSessionId===t,c=a&&s&&this.host.lastSentClientToolsFingerprint===o,l=!a&&i?.emptyMeansReplace===!0&&this.host.sentNonEmptyClientToolsSessionId===t,u=!1,d;for(let e=0;d=await r({...a&&(u||!c)&&n?{clientTools:n}:{},...l?{clientTools:[]}:{},...o?{clientToolsFingerprint:o}:{}}),d.status===409&&e===0&&a&&(await d.clone().json().catch(()=>null))?.error===`client_tools_resend_required`;e++)u=!0,this.host.lastSentClientToolsFingerprint=null;return{response:d,commit:()=>{this.host.lastSentClientToolsFingerprint=o??null,this.host.clientToolsFingerprintSessionId=t,a?this.host.sentNonEmptyClientToolsSessionId=t:l&&(this.host.sentNonEmptyClientToolsSessionId=null)}}}async createClientSession(e){let n=this.host.isHistoryCapable()&&!e.omitVisitorFields,r=!e.omitVisitorFields,i=null;(n||r)&&(await this.host.historyInternals.historyBootstrapReady,i=await this.host.readVisitorToken());let a=this.host.routing(),o=a.agentId??a.flowId,s=n||e.durableResume?e.conversationId:void 0,c={token:this.host.config.clientToken,...o&&{flowId:o},...n&&{visitorHistory:!0},...r&&{durableRecovery:!0},...(n||r)&&i?{visitorToken:i}:{},...n&&e.identityProof?{identityProof:e.identityProof}:{},...s?{conversationId:s}:e.storedSessionId?{sessionId:e.storedSessionId}:{}};e.signal?.throwIfAborted();let l=await fetch(this.host.getClientApiUrl(`init`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":t},body:JSON.stringify(c),signal:e.signal});if(!l.ok){let t=await l.json().catch(()=>({error:`Session initialization failed`}));if(n&&l.status===403&&t.error===`visitor_history_disabled`){if(this.host.markHistoryUnavailable(),s)throw new this.host.HistoryClientError(`history_disabled`,`Visitor history is disabled for this surface`);return this.createClientSession({...e,omitVisitorFields:!0})}throw l.status===403&&t.error===`durable_recovery_disabled`?new this.host.HistoryClientError(`history_disabled`,`Durable recovery is disabled for this surface`):(n||e.durableResume)&&l.status===401&&t.error===`visitor_required`?new this.host.HistoryClientError(`visitor_required`,`Visitor credential no longer resolves`):s&&l.status===404?new this.host.HistoryClientError(`not_found`,`Conversation not found`):l.status===401?Error(`Invalid client token: ${t.hint||t.error}`):l.status===403?Error(`Origin not allowed: ${t.hint||t.error}`):Error(t.error||`Failed to initialize session`)}let u=await l.json();return u.visitor?.token&&await this.host.historyInternals.visitorStore?.set(u.visitor.token),{sessionId:u.sessionId,expiresAt:new Date(u.expiresAt),flow:u.flow,...u.conversationId?{conversationId:u.conversationId}:{},...u.targetId?{targetId:u.targetId}:{},...u.conversationRevision?{conversationRevision:u.conversationRevision}:{},...u.durableRecovery?{durableRecovery:u.durableRecovery}:{},...u.visitor?{visitor:u.visitor}:{},config:{welcomeMessage:u.config.welcomeMessage,placeholder:u.config.placeholder,theme:u.config.theme}}}async sendFeedback(e){if([`upvote`,`downvote`,`copy`].includes(e.type)&&!e.messageId)throw Error(`messageId is required for ${e.type} feedback type`);if(e.type===`csat`&&(e.rating===void 0||e.rating<1||e.rating>5))throw Error(`CSAT rating must be between 1 and 5`);if(e.type===`nps`&&(e.rating===void 0||e.rating<0||e.rating>10))throw Error(`NPS rating must be between 0 and 10`);this.host.debug&&console.debug(`[AgentWidgetClient] sending feedback`,e);let n={...e,...this.host.config.clientToken&&{token:this.host.config.clientToken}},r=await fetch(`${this.host.clientApiBase()}/v1/client/feedback`,{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":t},body:JSON.stringify(n)});if(!r.ok){let e=await r.json().catch(()=>({error:`Feedback submission failed`}));throw r.status===401?(this.host.clientSession=null,this.host.resetSessionWarmLatch(),this.host.config.onSessionExpired?.(),Error(`Session expired. Please refresh to continue.`)):Error(e.error||`Failed to submit feedback`)}}async dispatchClientToken(e,r,i){let{HistoryClientError:a}=this.host,o=()=>this.host.isCurrentTurn(i),s=e=>{o()&&r(e)};try{let r=()=>{if(e.signal?.throwIfAborted(),!o())throw new DOMException(`Turn superseded`,`AbortError`)},c=this.host.clientSession??await this.host.initSession();r();let l=async()=>{r();let t=c,n=t.durableRecovery?.enabled===!0;if(n&&(!t.conversationId||!await this.host.readVisitorToken()))throw Error(`Renewing this conversation requires its visitor credential.`);r();let i=await this.host.createClientSession({...n||this.host.isHistoryCapable()?{conversationId:t.conversationId,durableResume:n}:{storedSessionId:t.sessionId},signal:e.signal});if(r(),t.conversationId&&i.conversationId!==t.conversationId||n&&i.durableRecovery?.enabled!==!0)throw Error(`Session renewal did not preserve this conversation.`);c=this.host.finishInit(i,t.conversationId??null,!1),this.host.clientSession=c,this.host.resetSessionWarmLatch(),this.host.resetClientToolsFingerprint(),this.host.config.onSessionInit?.(c)};Date.now()>=c.expiresAt.getTime()-6e4&&await l();let d=new Map(u(e.messages).map(e=>[e,this.#s(e)])),f=await this.#l(e.messages,void 0,d),p=f.metadata?Object.fromEntries(Object.entries(f.metadata).filter(([e])=>e!==`sessionId`&&e!==`session_id`)):void 0,m=this.host.isHistoryCapable(),h={sessionId:c.sessionId,messages:u(e.messages).flatMap(e=>{let t=d.get(e);if(!t)return[];let r=m?n(e,t.content):void 0;return[{id:e.id,role:t.role,content:t.content,...r!==void 0&&{displayContent:r}}]}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...f.inputs&&Object.keys(f.inputs).length>0&&{inputs:f.inputs},...f.context&&{context:f.context},turnId:i,...e.interrupt&&{submitMode:`interrupt`},...e.voiceSpoken&&{voice:{spoken:!0,...e.voicePriorToolResults?.length&&{priorToolResults:e.voicePriorToolResults}}}},g=async()=>{r();let n=c.durableRecovery?.enabled===!0?await this.host.readVisitorToken():null;return r(),this.host.sendWithClientToolsDiff(c.sessionId,f.clientTools,async i=>{r();let a=await this.host.resolveChatIdentityProof(e.signal);r();let o={...h,sessionId:c.sessionId,...i,...a&&{identityProof:a}};return this.host.debug&&console.debug(`[AgentWidgetClient] client token dispatch`,{...o,...a&&{identityProof:{provider:a.provider,token:`[REDACTED]`}}}),fetch(this.host.getClientApiUrl(`chat`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-Persona-Version":t,...n?{"X-Visitor-Token":n}:{}},body:JSON.stringify(o),signal:e.signal})})},_=await g();if(r(),_.response.status===401){let e=await _.response.clone().json().catch(()=>null);r(),e?.error===`Session not found or expired`&&(await l(),_=await g(),r())}let{response:v,commit:y}=_;if(!v.ok){let e=await v.json().catch(()=>({error:`Chat request failed`}));if(v.status===401&&e.error===`invalid_identity_proof`){let e=new a(`invalid_identity_proof`,`The identity proof was rejected`);throw s({type:`error`,error:e}),e}if(v.status===401){this.host.clearClientSession(),this.host.config.onSessionExpired?.();let e=/* @__PURE__ */ Error(`Session expired. Please refresh to continue.`);throw s({type:`error`,error:e}),e}if(v.status===429){let t=Error(e.hint||`Message limit reached for this session.`);throw s({type:`error`,error:t}),t}if(v.status===410&&e.error===`conversation_deleted`){let e=new a(`conversation_deleted`,`This conversation was deleted`);throw s({type:`error`,error:e}),e}let t=Error(e.error||`Failed to send message`);throw s({type:`error`,error:t}),t}if(!v.body){let e=/* @__PURE__ */ Error(`No response body received`);throw s({type:`error`,error:e}),e}y(),s({type:`status`,status:`connected`});try{await this.host.streamResponse(v.body,s,e.assistantMessageId,void 0,e.signal)}finally{s({type:`status`,status:`idle`})}}catch(e){let t=e instanceof Error?e:Error(String(e));throw!(t instanceof a)&&!t.message.includes(`Session expired`)&&!t.message.includes(`Message limit`)&&s({type:`error`,error:t}),t}}async dispatchProxy(e,t){let n=await this.#l(e.messages,e.composerOptions);this.host.debug&&console.debug(`[AgentWidgetClient] dispatch payload`,n);let r={...this.host.headers};if(this.host.getHeaders)try{let e=await this.host.getHeaders();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.host.customFetch)try{i=await this.host.customFetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.host.streamResponse(i.body,t,void 0,void 0,e.signal)}finally{t({type:`status`,status:`idle`})}}async dispatchAgent(e,t){let n=await this.#c(e.messages,e.composerOptions);this.host.debug&&console.debug(`[AgentWidgetClient] agent dispatch payload`,n);let r={...this.host.headers};if(this.host.getHeaders)try{let e=await this.host.getHeaders();r={...r,...e}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] getHeaders error:`,e)}let i;if(this.host.customFetch)try{i=await this.host.customFetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal},n)}catch(e){let n=e instanceof Error?e:Error(String(e));throw t({type:`error`,error:n}),n}else i=await fetch(this.host.apiUrl,{method:`POST`,headers:r,body:JSON.stringify(n),signal:e.signal});if(!i.ok||!i.body){let e=/* @__PURE__ */ Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw t({type:`error`,error:e}),e}t({type:`status`,status:`connected`});try{await this.host.streamResponse(i.body,t,e.assistantMessageId,void 0,e.signal)}finally{t({type:`status`,status:`idle`})}}#r(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`user`)return n.mentionContext&&Object.keys(n.mentionContext).length>0?{mentions:n.mentionContext}:null}return null}async#i(e){let t={};this.host.contextProviders.length&&await Promise.all(this.host.contextProviders.map(async n=>{try{let r=await n({messages:e,config:this.host.config});r&&typeof r==`object`&&Object.assign(t,r)}catch(e){typeof console<`u`&&console.warn(`[AgentWidget] Context provider failed:`,e)}}));let n=this.#r(e);return n&&Object.assign(t,n),Object.keys(t).length?t:null}#a(e){if(!e)return;let t={};return e.selectedModelId&&(t.selectedModelId=e.selectedModelId),e.activeModeIds?.length&&(t.activeModeIds=[...e.activeModeIds]),Object.keys(t).length>0?t:void 0}#o(e,t){let n=t?.selectedModelId;return!n||!(`model`in e)?e:this.host.config.composer?.models?.some(e=>e.id===n)?{...e,model:n}:e}#s(e){if(!c(e))return null;let t=e.contentParts??e.llmContent??e.rawContent??e.content,n=e.role===`operator`?null:f(e),r=this.host.config.modelMessageTransform;if(!r)return n;let i=r({message:e,content:t,modelMessage:n});if(i===null)return null;if(!i||typeof i!=`object`||![`user`,`assistant`,`system`].includes(i.role)||!l(i.content)||typeof i.createdAt!=`string`)throw TypeError(`modelMessageTransform must return a supported model message or null`);return{role:i.role,content:i.content,createdAt:i.createdAt,...i.role===`assistant`&&i.phase&&{phase:i.phase}}}async#c(e,t){let n=this.host.routing().agentId;if(!this.host.config.agent&&!n)throw Error(`Agent configuration required for agent mode`);let r=s(u(e),e=>!e.variant||e.variant===`assistant`?this.#s(e):null),i=this.#a(t),a={agent:this.#o(this.host.config.agent??{agentId:n},i),messages:r,options:{streamResponse:!0,recordMode:`virtual`,...this.host.config.agentOptions}};i&&(a.composerOptions=i);let o=[...this.host.builtInClientTools(this.host.config),...await(await this.host.getWebMcpBridge())?.snapshotForDispatch()??[]];o.length>0&&(a.clientTools=o);let c=await this.#i(e);return c&&(a.context=c),a}async#l(e,t,n){let r=s(u(e),e=>n?n.get(e)??null:this.#s(e)),i=this.host.routing(),a={messages:r,...i.agentId?{agent:{agentId:i.agentId}}:i.flowId?{flowId:i.flowId}:{}};if(i.targetPayload)for(let[e,t]of Object.entries(i.targetPayload))e!==`messages`&&(a[e]=t);let o=[...this.host.builtInClientTools(this.host.config),...await(await this.host.getWebMcpBridge())?.snapshotForDispatch()??[]];o.length>0&&(a.clientTools=o);let c=await this.#i(e);c&&(a.context=c);let l=this.#a(t);if(l&&(a.composerOptions=l),this.host.requestMiddleware)try{let e=await this.host.requestMiddleware({payload:{...a},config:this.host.config});if(e&&typeof e==`object`){let t=e;return a.clientTools!==void 0&&!(`clientTools`in t)&&(t.clientTools=a.clientTools),t}}catch(e){typeof console<`u`&&console.error(`[AgentWidget] Request middleware error:`,e)}return a}};export{p as ClientDispatch};
|