@trillet-ai/web-sdk 1.12.0 → 1.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/widget/index.d.ts +8 -0
- package/dist/widget/index.js +18 -9
- package/dist/widget/index.js.map +1 -1
- package/dist/widget.umd.js +3 -1
- package/dist/widget.umd.js.map +1 -1
- package/package.json +1 -1
package/dist/widget.umd.js
CHANGED
|
@@ -3929,6 +3929,7 @@ svg { display: block; flex-shrink: 0; }
|
|
|
3929
3929
|
.tw-variables-form { width: 320px; }
|
|
3930
3930
|
.tw-field { display: flex; flex-direction: column; gap: 4px; }
|
|
3931
3931
|
.tw-field-label { font-size: 13px; font-weight: 500; color: var(--tw-muted); }
|
|
3932
|
+
.tw-field-required { color: var(--tw-danger); margin-left: 2px; }
|
|
3932
3933
|
.tw-field-input {
|
|
3933
3934
|
height: 38px;
|
|
3934
3935
|
padding: 0 10px;
|
|
@@ -3939,6 +3940,7 @@ svg { display: block; flex-shrink: 0; }
|
|
|
3939
3940
|
font: inherit;
|
|
3940
3941
|
font-size: 14px;
|
|
3941
3942
|
}
|
|
3943
|
+
.tw-field-input::placeholder { color: var(--tw-muted); }
|
|
3942
3944
|
.tw-field-input:focus-visible { outline: none; border-color: var(--tw-accent); }
|
|
3943
3945
|
.tw-field-error { margin: 0; font-size: 12px; color: var(--tw-danger); }
|
|
3944
3946
|
.tw-variables-form .tw-pill {
|
|
@@ -3986,5 +3988,5 @@ svg { display: block; flex-shrink: 0; }
|
|
|
3986
3988
|
.tw-hidden { display: none !important; }
|
|
3987
3989
|
`;var Ah="https://www.google.com/recaptcha/api.js?render=explicit";function W0(){return window.grecaptcha}var yB=null;function v0(){return yB||(yB=new Promise((C,A)=>{if(document.querySelector(`script[src="${Ah}"]`)){C();return}let I=document.createElement("script");I.src=Ah,I.async=!0,I.defer=!0,I.onload=()=>C(),I.onerror=()=>{yB=null,A(new Error("Failed to load Google reCAPTCHA"))},document.head.appendChild(I)}),yB)}async function V0(){await v0();let C=W0();if(!C)throw new Error("reCAPTCHA loaded but grecaptcha is undefined");return await new Promise(A=>C.ready(A)),C}async function gh(C){return(await V0()).render(C.container,{sitekey:C.siteKey,callback:()=>C.onSolved(),"expired-callback":()=>C.onExpired(),"error-callback":()=>C.onExpired()})}var X0=/(\*\*[^*\n]+\*\*|\*[^*\n]+\*|`[^`\n]+`|\[[^\]\n]+\]\((?:https?:\/\/)[^)\s]+\)|https?:\/\/[^\s<]+[^\s<.,;:!?)\]])/g;function z0(C){try{let A=new URL(C);return A.protocol==="https:"||A.protocol==="http:"?A.toString():null}catch(A){return null}}function Ih(C,A){let g=z0(A);if(!g)return document.createTextNode(C);let I=document.createElement("a");return I.href=g,I.target="_blank",I.rel="noopener noreferrer nofollow",I.textContent=C,I}function Ch(C,A){var I;let g=0;for(let B of A.matchAll(X0)){let Q=B[0],i=(I=B.index)!=null?I:0;if(i>g&&C.appendChild(document.createTextNode(A.slice(g,i))),Q.startsWith("**")){let E=document.createElement("strong");E.textContent=Q.slice(2,-2),C.appendChild(E)}else if(Q.startsWith("`")){let E=document.createElement("code");E.textContent=Q.slice(1,-1),C.appendChild(E)}else if(Q.startsWith("[")){let E=Q.slice(1,Q.indexOf("](")),o=Q.slice(Q.indexOf("](")+2,-1);C.appendChild(Ih(E,o))}else if(Q.startsWith("*")){let E=document.createElement("em");E.textContent=Q.slice(1,-1),C.appendChild(E)}else C.appendChild(Ih(Q,Q));g=i+Q.length}g<A.length&&C.appendChild(document.createTextNode(A.slice(g)))}function QE(C){let A=document.createDocumentFragment(),g=C.replace(/\r\n/g,`
|
|
3988
3990
|
`).split(/\n{2,}/);for(let I of g){let B=I.split(`
|
|
3989
|
-
`).filter(o=>o.trim()!=="");if(!B.length)continue;let Q=/^\s*[-*•]\s+/,i=/^\s*\d+[.)]\s+/;if(B.every(o=>Q.test(o))||B.every(o=>i.test(o))){let o=i.test(B[0]),D=document.createElement(o?"ol":"ul");for(let e of B){let s=document.createElement("li");Ch(s,e.replace(o?i:Q,"")),D.appendChild(s)}A.appendChild(D);continue}let E=document.createElement("p");B.forEach((o,D)=>{D>0&&E.appendChild(document.createElement("br")),Ch(E,o)}),A.appendChild(E)}return A}var qI=class extends HTMLElement{constructor(){super();this.agent=null;this.state="idle";this.open=!1;this.micEnabled=!0;this.speaking=!1;this.transcripts=[];this.display=null;this.activeMode=null;this.switching=!1;this.remote=null;this.remoteDisplay=null;this.remoteLoadedFor=null;this.pendingMessage=null;this.durationTimer=null;this.remainingSeconds=null;this.elapsedSeconds=0;this.recaptchaSolved=!1;this.recaptchaSlot=null;this.recaptchaWidgetId=null;this.pendingTimer=null;this.lastView=null;this.notice=null;this.switchingSide=!1;this.callGeneration=0;this.smoothedLevel=0;this.showTerms=!1;this.pendingStart=null;this.callId=null;this.feedbackState="hidden";this.termsAcceptedThisPage=!1;this.showVariablesForm=!1;this.dynamicVariableValues=null;this.askFocused=!1;this.errorText=null;this.draft="";this.root=this.attachShadow({mode:"open"}),this.styleEl=document.createElement("style"),this.styleEl.textContent=$c,this.container=document.createElement("div"),this.container.className="tw-root",this.root.appendChild(this.styleEl),this.root.appendChild(this.container)}static get observedAttributes(){return Pc}connectedCallback(){this.refreshConfig(),this.loadRemoteConfig()}refreshConfig(){this.config=_c(this,this.remote),this.syncActiveMode(),this.applyTheme(),this.render()}async loadRemoteConfig(){var Q,i;let{agentId:g,remoteConfig:I,apiBase:B}=this.config;if(!(!I||!g||this.remoteLoadedFor===g)){this.remoteLoadedFor=g;try{let E=`${YC("/v1/api/web-call/public/widget-config",B)}?agent_id=${encodeURIComponent(g)}`,o=await fetch(E,{headers:{Accept:"application/json"}});if(!o.ok)return;let D=await o.json();if(this.config.agentId!==g)return;this.remote=(Q=D.widget)!=null?Q:null,this.remoteDisplay=(i=D.display)!=null?i:null,this.state==="idle"&&this.refreshConfig()}catch(E){console.warn("[trillet-widget] Could not load widget design; using attributes only",E)}}}disconnectedCallback(){this.clearDurationTimer(),this.teardownAgent(),this.removeRecaptchaSlot()}attributeChangedCallback(){this.isConnected&&(this.refreshConfig(),this.loadRemoteConfig())}async sendMessage(g){var B;let I=g.trim();if(I){if(this.state==="live"&&(this.resolvedMode()==="text"||this.config.mode==="both")){await((B=this.agent)==null?void 0:B.sendTextMessage(I));return}this.config.mode!=="voice"&&((this.state==="idle"||this.state==="ended")&&(this.transcripts=[]),this.pendingMessage=I,this.state!=="connecting"&&await this.startConversation("text"))}}async startConversation(g){if(this.state==="connecting"||this.state==="live")return;if((this.config.mode==="text"||this.config.mode==="both"&&g!=="voice")&&(this.open=!0),this.needsRecaptcha()){this.render();return}await this.beginCall(g)}endConversation(){var g;(g=this.agent)==null||g.endCall()}startOver(g){if(this.callGeneration+=1,this.clearDurationTimer(),this.teardownAgent(),this.pendingTimer&&clearTimeout(this.pendingTimer),this.pendingTimer=null,this.pendingMessage=null,this.transcripts=[],this.notice=null,this.errorText=null,this.feedbackState="hidden",this.speaking=!1,this.callId=null,this.display=null,this.dynamicVariableValues=null,this.state="idle",this.config.mode==="both"&&(this.activeMode=g!=null?g:null,!g)){this.render();return}this.beginCall(g)}startCall(){return this.startConversation()}endCall(){this.endConversation()}resolvedMode(){var g;return this.config.mode==="both"?(g=this.activeMode)!=null?g:"voice":this.config.mode}syncActiveMode(){(this.config.mode==="voice"||this.config.mode==="text")&&(this.activeMode=this.config.mode)}teardownAgent(){if(this.agent){try{this.agent.removeAllListeners()}catch(g){}try{this.agent.endCall()}catch(g){}this.agent=null}}async switchModality(){if(this.config.mode!=="both"||this.state!=="live"||!this.agent)return;let g=this.resolvedMode()==="text";this.notice=null,this.switchingSide=!0,this.render();try{await this.agent.setVoiceEnabled(g)}catch(I){console.warn("[trillet-widget] Could not switch modality",I),this.notice=g?"Could not turn on your microphone. Check the browser permission and try again.":"Could not switch back to typing. Please try again."}finally{this.switchingSide=!1,this.render()}}setSpeaking(g){if(this.speaking===g)return;this.speaking=g;let I=g?this.config.speakingText:this.config.listeningText;this.root.querySelectorAll(".tw-callbar-activity").forEach(Q=>{Q.textContent=I}),this.root.querySelectorAll(".tw-wave").forEach(Q=>Q.classList.toggle("tw-wave-speaking",g)),this.root.querySelectorAll(".tw-mark").forEach(Q=>Q.classList.toggle("tw-speaking",g));let B=this.root.querySelector(".tw-header .tw-status");B&&(B.textContent=this.statusText())}flushPending(){this.pendingTimer&&clearTimeout(this.pendingTimer),this.pendingTimer=null;let g=this.pendingMessage;this.pendingMessage=null,g&&this.agent&&this.state==="live"&&this.agent.sendTextMessage(g)}async beginCall(g){if(this.config.termsText&&!this.termsAccepted()){this.pendingStart=g!=null?g:this.resolvedMode(),this.showTerms=!0,this.render();return}if(this.config.dynamicVariablePrompts.length>0&&!this.dynamicVariableValues){this.pendingStart=g!=null?g:this.resolvedMode(),this.showVariablesForm=!0,this.render();return}this.feedbackState="hidden",g&&(this.activeMode=g);let I=this.resolvedMode(),B=this.config.mode==="both"?"multimodal":I;this.notice=null,this.switching||(this.display=null);let Q=++this.callGeneration;this.setState("connecting");try{let i=new BE({agentId:this.config.agentId,workspaceId:this.config.workspaceId,apiBaseUrl:this.config.apiBase,mode:B,startWithVoice:B==="multimodal"&&I==="voice",variables:{...this.config.dynamicVariablePresets,...this.dynamicVariableValues,...this.config.variables}});if(this.agent=i,this.wireAgentEvents(i),this.config.signedUrlEndpoint||this.getRoomDetails){let E;if(this.getRoomDetails)E=await this.getRoomDetails({mode:I,session:B});else{let o=await fetch(this.config.signedUrlEndpoint,{method:"GET",headers:{Accept:"application/json"}});if(!o.ok)throw new Error(`signed-url-endpoint returned ${o.status}`);E=await o.json()}await i.joinRoom(E)}else if(this.roomDetails)await i.joinRoom(this.roomDetails);else if(this.config.workspaceId)await i.startPublicCall();else throw new Error("No credential path configured: set signed-url-endpoint, roomDetails/getRoomDetails, or workspace-id")}catch(i){if(Q!==this.callGeneration)return;this.handleError(i)}}wireAgentEvents(g){g.on("connected",I=>{var Q,i;this.display=(Q=I==null?void 0:I.display)!=null?Q:null,this.callId=(i=I==null?void 0:I.callId)!=null?i:null;let B=this.switching;this.setState("live"),this.startDurationTimer(!B),this.switching=!1,this.pendingMessage&&(this.pendingTimer=setTimeout(()=>this.flushPending(),25e3))}),g.on("disconnected",()=>{this.endLocalCall()}),g.on("error",I=>{this.handleError(I)}),g.on("modalityChanged",I=>{this.activeMode=I,this.speaking=!1,this.dispatch("modality",I),this.render()}),g.on("audioData",I=>this.setLevel(I)),g.on("assistantStartedSpeaking",()=>this.setSpeaking(!0)),g.on("assistantStoppedSpeaking",()=>this.setSpeaking(!1)),g.on("transcriptUpdate",I=>{this.transcripts=[...I],this.pendingMessage&&I.some(B=>B.role==="assistant"&&!B.toolUsed)&&this.flushPending(),this.dispatch("transcript",this.transcripts),this.updateThread()||this.render()})}endLocalCall(){this.state==="ended"||this.state==="idle"||(this.config.feedback==="end"&&this.callId&&this.elapsedSeconds>=5&&(this.feedbackState="ask"),this.clearDurationTimer(),this.speaking=!1,this.dispatch("call-end",this.elapsedSeconds),this.dispatch("conversationEnded",this.elapsedSeconds),this.setState("ended"),this.agent=null,this.pendingMessage=null,this.pendingTimer&&clearTimeout(this.pendingTimer),this.pendingTimer=null,this.config.mode==="both"&&(this.activeMode=null))}handleError(g){let I=g instanceof Error?g:new Error(String(g));this.errorText=P0(I,this.config.copy),this.clearDurationTimer(),this.speaking=!1,this.switching=!1,this.dispatch("error",I),this.agent=null,this.config.mode==="both"&&(this.activeMode=null),this.setState("idle")}startDurationTimer(g=!0){this.clearDurationTimer(),g&&(this.elapsedSeconds=0,this.remainingSeconds=typeof this.config.maxCallDuration=="number"?this.config.maxCallDuration:null),this.durationTimer=setInterval(()=>{var I;if(this.elapsedSeconds+=1,this.remainingSeconds!==null&&(this.remainingSeconds-=1,this.remainingSeconds<=0)){(I=this.agent)==null||I.endCall();return}this.renderStatus()},1e3)}clearDurationTimer(){this.durationTimer&&(clearInterval(this.durationTimer),this.durationTimer=null)}setState(g){let I=this.state;g==="connecting"&&(this.errorText=null),this.state=g,g==="live"&&I!=="live"&&!this.switching&&(this.dispatch("call-start",void 0),this.dispatch("conversationStarted",void 0)),this.render()}dispatch(g,I){this.dispatchEvent(new CustomEvent(g,{detail:I,bubbles:!0,composed:!0}))}applyTheme(){let g=this.config.brand.primaryColor||this.config.orbColor1||O0;this.style.setProperty("--tw-accent",g),this.style.setProperty("--tw-on-accent",_0(g));let I=this.config.backgroundColor||this.config.textColor,B=(Q,i)=>i?this.style.setProperty(Q,i):this.style.removeProperty(Q);B("--tw-surface",this.config.backgroundColor),B("--tw-ink",this.config.textColor),B("--tw-raised",I?"color-mix(in srgb, var(--tw-ink) 7%, var(--tw-surface))":void 0),B("--tw-line",I?"color-mix(in srgb, var(--tw-ink) 14%, var(--tw-surface))":void 0),B("--tw-muted",I?"color-mix(in srgb, var(--tw-ink) 62%, var(--tw-surface))":void 0),this.config.buttonTextColor&&this.style.setProperty("--tw-on-accent",this.config.buttonTextColor),this.style.setProperty("--tw-orb-1",this.config.orbColor1||g),this.style.setProperty("--tw-orb-2",this.config.orbColor2||"#27a3fd"),this.dataset.placement=this.config.placement,this.dataset.theme=this.config.theme}formatTime(g){let I=Math.floor(g/60),B=g%60;return`${I}:${B.toString().padStart(2,"0")}`}statusText(){return this.state==="connecting"?this.config.copy.connecting:this.state==="live"&&this.resolvedMode()==="voice"?`${this.speaking?this.config.speakingText:this.config.listeningText} ${this.timerText()}`.trim():this.state==="live"?this.config.copy.online:this.config.brand.name||this.config.copy.online}renderStatus(){let g=this.root.querySelector(".tw-status");g&&(g.textContent=this.statusText()),this.root.querySelectorAll(".tw-timer").forEach(I=>{I.textContent=I.classList.contains("tw-callbar-meta")?[this.speakerName(),this.timerText()].filter(Boolean).join(" \xB7 "):this.timerText()})}timerText(){return this.state!=="live"?"":this.remainingSeconds!==null?this.formatTime(Math.max(0,this.remainingSeconds)):this.formatTime(this.elapsedSeconds)}setLevel(g){let I=0;for(let i=0;i<g.length;i+=1)I+=g[i]*g[i];let B=Math.sqrt(I/(g.length||1)),Q=Math.min(1,B*6);this.smoothedLevel=this.smoothedLevel*.7+Q*.3,this.style.setProperty("--tw-level",this.smoothedLevel.toFixed(3))}render(){this.container.replaceChildren();let g,I;this.showTerms?(g="terms",I=this.renderTerms()):this.showVariablesForm?(g="variables",I=this.renderVariablesForm()):this.open?(g="panel",I=this.renderPanel()):(I=this.renderCard(),g=I.querySelector(".tw-callbar")?"callbar":"bar"),g!==this.lastView&&I.classList.add("tw-enter"),this.lastView=g,this.container.appendChild(I)}avatarStyle(){let g=this.config.avatarStyle;return g==="image"&&!this.config.avatar?"orb":g||(this.config.avatar?"image":"orb")}buildAvatar(g){let I=document.createElement("span"),B=this.avatarStyle();return I.className=`tw-mark tw-mark-${g} tw-mark-${B}`,I.setAttribute("aria-hidden","true"),this.state==="live"&&this.resolvedMode()==="voice"&&I.classList.add("tw-voice-live"),B==="image"?I.style.backgroundImage=`url("${this.config.avatar}")`:B==="initials"&&(I.textContent=$0(this.speakerName())),I}speakerName(){return this.config.brand.name||this.headerTitle()||""}buildWave(){let g=document.createElement("span");g.className=`tw-wave${this.speaking?" tw-wave-speaking":""}`,g.setAttribute("aria-hidden","true");for(let I=0;I<5;I+=1)g.appendChild(document.createElement("i"));return g}iconButton(g,I,B,Q=""){let i=document.createElement("button");return i.type="button",i.className=`tw-icon-btn ${Q}`.trim(),i.title=I,i.setAttribute("aria-label",I),i.innerHTML=g,i.addEventListener("click",B),i}termsKey(){let g=0;for(let I of this.config.termsText||"")g=g*31+I.charCodeAt(0)|0;return`trillet-terms:${this.config.agentId}:${g}`}termsAccepted(){if(this.termsAcceptedThisPage)return!0;try{return window.localStorage.getItem(this.termsKey())==="1"}catch(g){return!1}}renderTerms(){let g=document.createElement("div");g.className="tw-card tw-terms",g.setAttribute("role","dialog"),g.setAttribute("aria-label",this.config.copy.terms);let I=document.createElement("div");I.className="tw-card-title",I.textContent=this.config.copy.termsTitle,g.appendChild(I);let B=document.createElement("div");B.className="tw-terms-body tw-md",B.appendChild(QE(this.config.termsText||"")),g.appendChild(B);let Q=document.createElement("div");Q.className="tw-card-actions";let i=document.createElement("button");i.type="button",i.className="tw-pill",i.textContent=this.config.copy.termsAccept,i.addEventListener("click",()=>{try{window.localStorage.setItem(this.termsKey(),"1")}catch(D){}this.termsAcceptedThisPage=!0,this.showTerms=!1;let o=this.pendingStart;this.pendingStart=null,o==="text"&&(this.open=!0),this.beginCall(o!=null?o:void 0)});let E=document.createElement("button");return E.type="button",E.className="tw-secondary-btn",E.textContent=this.config.copy.termsDecline,E.addEventListener("click",()=>{this.showTerms=!1,this.pendingStart=null,this.open=!1,this.render()}),Q.appendChild(i),Q.appendChild(E),g.appendChild(Q),g}renderVariablesForm(){let g=document.createElement("div");g.className="tw-card tw-variables-form",g.setAttribute("role","dialog"),g.setAttribute("aria-label",this.config.copy.continueText);let I=document.createElement("div");I.className="tw-card-title",I.textContent=this.headerTitle()||this.config.copy.chooseModePrompt,g.appendChild(I);let B=[],Q=document.createElement("button");Q.type="button",Q.className="tw-pill",Q.textContent=this.config.copy.continueText,Q.addEventListener("click",()=>{var s;let o={},D=!0;for(let a of B){let t=a.input.value.trim(),w=a.required&&!t;if(a.err.hidden=!w,a.input.setAttribute("aria-invalid",w?"true":"false"),w){D=!1;continue}t&&(o[a.key]=t)}if(!D){(s=B.find(a=>!a.err.hidden))==null||s.input.focus();return}this.dynamicVariableValues=o,this.showVariablesForm=!1;let e=this.pendingStart;this.pendingStart=null,e==="text"&&(this.open=!0),this.beginCall(e!=null?e:void 0)}),this.config.dynamicVariablePrompts.forEach((o,D)=>{let e=document.createElement("div");e.className="tw-field";let s=`tw-var-${D}`,a=`tw-var-err-${D}`,t=document.createElement("label");t.className="tw-field-label",t.htmlFor=s,t.textContent=o.label||o.key,e.appendChild(t);let w=document.createElement("input");w.type="text",w.id=s,w.className="tw-field-input",o.placeholder&&(w.placeholder=o.placeholder),o.required&&(w.required=!0),w.setAttribute("aria-describedby",a),w.addEventListener("keydown",M=>{M.key==="Enter"&&(M.preventDefault(),Q.click())}),e.appendChild(w);let c=document.createElement("p");c.className="tw-field-error",c.id=a,c.textContent=this.config.copy.fieldRequired,c.hidden=!0,e.appendChild(c),g.appendChild(e),B.push({key:o.key,required:!!o.required,input:w,err:c})});let i=document.createElement("div");i.className="tw-card-actions",i.appendChild(Q);let E=document.createElement("button");return E.type="button",E.className="tw-secondary-btn",E.textContent=this.config.copy.termsDecline,E.addEventListener("click",()=>{this.showVariablesForm=!1,this.pendingStart=null,this.open=!1,this.render()}),i.appendChild(E),g.appendChild(i),g}renderFeedback(){if(this.feedbackState==="hidden")return null;let g=document.createElement("div");if(g.className="tw-feedback",this.feedbackState==="sent")return g.textContent=this.config.copy.feedbackThanks,g;let I=document.createElement("span");I.textContent=this.config.copy.feedbackQuestion,g.appendChild(I);let B=Q=>{this.feedbackState="sent",this.render(),fetch(YC("/v1/api/web-call/public/feedback",this.config.apiBase),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({call_id:this.callId,rating:Q})}).catch(()=>{}),this.dispatch("feedback",Q)};return g.appendChild(this.iconButton(MA.thumbUp,this.config.copy.feedbackGood,()=>B("up"))),g.appendChild(this.iconButton(MA.thumbDown,this.config.copy.feedbackBad,()=>B("down"))),g}renderCard(){let g=this.state==="idle"||this.state==="ended",I=this.state==="live",B=I&&this.resolvedMode()==="voice",Q=this.state==="connecting"&&this.resolvedMode()==="voice",i=this.needsRecaptcha()&&g,E=document.createElement("div");if(E.className="tw-bar-stack",B||Q)return E.appendChild(this.renderVoiceBar(!1)),E;if(this.errorText&&g){let t=document.createElement("div");t.className="tw-bar-note tw-error-text",t.textContent=this.errorText,E.appendChild(t)}let o=document.createElement("div");o.className="tw-ask",o.appendChild(this.buildAvatar("md"));let D=this.speakerName(),e=this.config.mode!=="voice",s=this.config.mode!=="text";if(I||this.state==="connecting"){let t=document.createElement("button");return t.type="button",t.className="tw-ask-label",t.textContent=D?xD(this.config.copy.chatWithNamed,D):this.config.copy.backToChat,t.addEventListener("click",()=>this.openPanel()),o.appendChild(t),o.appendChild(this.iconButton(MA.chat,this.config.copy.openChat,()=>this.openPanel(),"tw-sq tw-sq-accent")),E.appendChild(o),E}if(e){let t=document.createElement("form");t.className="tw-ask-form";let w=document.createElement("input");w.className="tw-ask-input",w.type="text",w.placeholder=this.config.greeting||(D?xD(this.config.copy.askNamed,D):this.config.copy.askAnything),w.setAttribute("aria-label",w.placeholder),w.value=this.draft,w.disabled=i;let c=this.iconButton(MA.send,this.config.copy.send,()=>{},"tw-sq tw-sq-accent");c.type="submit";let M=()=>{c.disabled=i||!w.value.trim()};if(w.addEventListener("input",()=>{this.draft=w.value,M()}),w.addEventListener("focus",()=>{this.askFocused=!0,this.renderAskSuggestions(E,o)}),w.addEventListener("blur",()=>{this.askFocused=!1,setTimeout(()=>{var y;this.askFocused||(y=E.querySelector(".tw-ask-suggestions"))==null||y.remove()},150)}),t.addEventListener("submit",y=>{y.preventDefault();let F=w.value.trim();!F||this.needsRecaptcha()||(this.draft="",this.sendMessage(F))}),t.appendChild(w),s){let y=this.iconButton(MA.phone,this.config.actionText||this.config.startCallText,()=>{this.needsRecaptcha()||this.beginCall("voice")},"tw-sq tw-sq-quiet");y.disabled=i,t.appendChild(y)}t.appendChild(c),M(),o.appendChild(t)}else{let t=document.createElement("button");t.type="button",t.className="tw-ask-label",t.textContent=this.config.greeting||(D?`Talk to ${D}`:this.config.startCallText),t.disabled=i,t.addEventListener("click",()=>{this.needsRecaptcha()||this.beginCall("voice")}),o.appendChild(t);let w=this.iconButton(MA.phone,this.config.actionText||this.config.startCallText,()=>{this.needsRecaptcha()||this.beginCall("voice")},"tw-sq tw-sq-accent");w.disabled=i,o.appendChild(w)}if(E.appendChild(o),i){let t=document.createElement("slot");t.setAttribute("name","recaptcha"),t.className="tw-recaptcha-slot",E.insertBefore(t,o),this.ensureRecaptchaSlot()}let a=g?this.renderFeedback():null;return a&&(a.classList.add("tw-bar-note"),E.insertBefore(a,o)),E}renderAskSuggestions(g,I){if(!this.config.suggestedPrompts.length||g.querySelector(".tw-ask-suggestions"))return;let B=document.createElement("div");B.className="tw-ask-suggestions";for(let Q of this.config.suggestedPrompts){let i=document.createElement("button");i.type="button",i.className="tw-suggestion",i.textContent=Q,i.addEventListener("mousedown",E=>{E.preventDefault(),this.askFocused=!1,this.sendMessage(Q)}),B.appendChild(i)}g.insertBefore(B,I)}openPanel(){this.open=!0;let g=this.state==="idle"&&this.transcripts.length===0;if(this.config.mode==="text"&&g&&!this.needsRecaptcha()){this.beginCall("text");return}this.render()}renderPanel(){let g=document.createElement("div");return g.className=`tw-panel${this.config.variant==="expanded"?" tw-expanded":""}`,g.setAttribute("role","dialog"),g.setAttribute("aria-label",this.headerTitle()||this.config.copy.chat),g.appendChild(this.renderHeader()),g.appendChild(this.renderBody()),g}headerTitle(){var i,E,o,D;let g=(i=this.display)!=null?i:this.remoteDisplay,I=(E=this.config.agentName)!=null?E:g==null?void 0:g.agent_name,B=(o=this.config.callFlowName)!=null?o:g==null?void 0:g.call_flow_name,Q=(D=this.config.workspaceName)!=null?D:g==null?void 0:g.workspace_name;return I||B||Q||""}renderHeader(){let g=document.createElement("div");g.className="tw-header",this.bodyShowsLargeAvatar()||g.appendChild(this.buildAvatar("sm"));let I=document.createElement("div");I.className="tw-who";let B=document.createElement("div");B.className="tw-header-title";let Q=this.config.agentName||this.speakerName();B.textContent=Q,Q&&(B.title=Q);let i=document.createElement("div");if(i.className="tw-status",this.state==="live"&&i.classList.add("tw-online"),i.textContent=this.statusText(),I.appendChild(B),I.appendChild(i),g.appendChild(I),this.config.brand.logo){let o=document.createElement("img");o.className="tw-brand-logo",o.src=this.config.brand.logo,o.alt=this.config.brand.name||"",g.appendChild(o)}let E=document.createElement("div");return E.className="tw-header-actions",E.appendChild(this.iconButton(MA.minimize,this.config.copy.minimize,()=>{this.open=!1,this.render()})),this.config.dismissible&&E.appendChild(this.iconButton(MA.close,this.config.copy.close,()=>{(this.state==="live"||this.state==="connecting")&&this.endConversation(),this.open=!1,this.render()})),g.appendChild(E),g}bodyShowsLargeAvatar(){let g=this.state==="idle"||this.state==="ended";return this.needsRecaptcha()&&g||this.isBothPreCall()||this.config.mode!=="both"&&this.resolvedMode()==="voice"?!0:this.state==="idle"&&this.transcripts.length===0}isBothPreCall(){return this.config.mode==="both"&&this.activeMode===null&&this.transcripts.length===0&&(this.state==="idle"||this.state==="ended")}needsRecaptcha(){return!!this.config.recaptchaSiteKey&&!this.recaptchaSolved}renderRecaptchaGate(g){g.classList.add("tw-center-body"),g.appendChild(this.buildAvatar("lg"));let I=document.createElement("p");I.className="tw-prompt",I.textContent=this.config.recaptchaText,g.appendChild(I);let B=document.createElement("slot");B.setAttribute("name","recaptcha"),B.className="tw-recaptcha-slot",g.appendChild(B);let Q=document.createElement("button");Q.className="tw-primary-btn",Q.type="button",Q.textContent=this.config.startCallText,Q.disabled=!0,g.appendChild(Q),this.ensureRecaptchaSlot()}ensureRecaptchaSlot(){let g=this.config.recaptchaSiteKey;if(!g||this.recaptchaSolved||this.recaptchaSlot)return;let I=document.createElement("div");I.setAttribute("slot","recaptcha"),I.className="tw-recaptcha-mount",this.appendChild(I),this.recaptchaSlot=I,this.recaptchaWidgetId=-1,gh({container:I,siteKey:g,onSolved:()=>{this.recaptchaSolved=!0,this.removeRecaptchaSlot(),this.render()},onExpired:()=>{this.recaptchaSolved=!1}}).then(B=>{this.recaptchaWidgetId=B}).catch(B=>{console.warn("[trillet-widget] reCAPTCHA failed to load; starting without it",B),this.recaptchaSolved=!0,this.removeRecaptchaSlot(),this.render()})}removeRecaptchaSlot(){var g;(g=this.recaptchaSlot)==null||g.remove(),this.recaptchaSlot=null,this.recaptchaSolved||(this.recaptchaWidgetId=null)}renderBody(){let g=document.createElement("div");return g.className="tw-body",this.needsRecaptcha()&&(this.state==="idle"||this.state==="ended")?(this.renderRecaptchaGate(g),g):this.isBothPreCall()?(this.renderBothEntry(g),g):(this.resolvedMode()==="text"||this.config.mode==="both"?this.renderTextBody(g):this.renderVoiceBody(g),g)}renderBothEntry(g){g.classList.add("tw-center-body"),g.appendChild(this.buildAvatar("lg"));let I=document.createElement("p");I.className="tw-prompt",I.textContent=this.config.greeting||this.config.copy.chooseModePrompt,g.appendChild(I);let B=document.createElement("div");B.className="tw-choices";let Q=(i,E,o,D)=>{let e=document.createElement("button");e.type="button",e.className=D?"tw-primary-btn":"tw-secondary-btn",e.innerHTML=i;let s=document.createElement("span");return s.textContent=E,e.appendChild(s),e.addEventListener("click",()=>this.startOver(o)),e};B.appendChild(Q(MA.phone,this.config.startCallText,"voice",!0)),B.appendChild(Q(MA.chat,this.config.messageText,"text",!1)),g.appendChild(B)}renderVoiceBody(g){var Q;g.classList.add("tw-center-body","tw-voice-body"),g.appendChild(this.buildAvatar("lg"));let I=document.createElement("p");I.className="tw-prompt",this.state==="connecting"?I.textContent=this.config.copy.connecting:this.state==="live"?I.textContent=this.speaking?this.config.speakingText:this.config.listeningText:this.state==="ended"?I.textContent=(Q=this.errorText)!=null?Q:this.config.copy.callEnded:I.textContent=this.config.actionText||this.config.copy.talkToUs,this.errorText&&this.state!=="live"&&I.classList.add("tw-error-text"),g.appendChild(I);let B=document.createElement("div");B.className="tw-timer",B.textContent=this.timerText(),g.appendChild(B),g.appendChild(this.renderControls())}renderTextBody(g){var o;if(g.classList.add("tw-chat-body"),this.state==="idle"&&this.transcripts.length===0){if(g.classList.add("tw-center-body"),g.appendChild(this.buildAvatar("lg")),this.errorText){let D=document.createElement("p");D.className="tw-prompt tw-error-text",D.textContent=this.errorText,g.appendChild(D)}g.appendChild(this.renderControls());return}g.appendChild(this.renderTranscript());let I=this.renderSuggestions();if(I&&g.appendChild(I),this.state==="ended"||this.state==="idle"){let D=document.createElement("div");D.className="tw-chat-ended";let e=document.createElement("span");e.textContent=(o=this.errorText)!=null?o:this.config.copy.chatEnded,this.errorText&&e.classList.add("tw-error-text"),D.appendChild(e);let s=document.createElement("button");s.type="button",s.className="tw-secondary-btn tw-small",s.textContent=this.config.copy.startNewChat,s.addEventListener("click",()=>this.startOver(this.config.mode==="both"?void 0:this.resolvedMode())),D.appendChild(s),g.appendChild(D);let a=this.renderFeedback();a&&g.appendChild(a);return}if(this.notice){let D=document.createElement("p");D.className="tw-notice",D.setAttribute("role","status"),D.textContent=this.notice,g.appendChild(D)}let B=this.config.mode==="both"&&this.resolvedMode()==="voice";g.appendChild(B?this.renderVoiceBar(!0):this.renderTextInput());let Q=document.createElement("div");Q.className="tw-chat-footer";let i=document.createElement("button");i.className="tw-link-btn tw-end-chat",i.type="button",i.textContent=this.config.mode==="text"?this.config.endCallText:this.config.copy.endConversationText,i.disabled=this.state==="connecting",i.addEventListener("click",()=>this.endConversation()),Q.appendChild(i);let E=document.createElement("button");E.className="tw-link-btn",E.type="button",E.textContent=this.config.copy.startOver,E.disabled=this.state==="connecting",E.addEventListener("click",()=>this.startOver(this.resolvedMode())),Q.appendChild(E),g.appendChild(Q)}renderSuggestions(){let g=this.config.suggestedPrompts,I=this.transcripts.some(Q=>Q.role==="user");if(!g.length||I||this.state==="ended")return null;let B=document.createElement("div");B.className="tw-suggestions";for(let Q of g){let i=document.createElement("button");i.type="button",i.className="tw-suggestion",i.textContent=Q,i.addEventListener("click",()=>{this.sendMessage(Q)}),B.appendChild(i)}return B}renderControls(){let g=document.createElement("div");if(g.className="tw-controls",this.state==="idle"||this.state==="ended"){let I=document.createElement("button");I.className="tw-primary-btn",I.type="button";let B=this.resolvedMode()==="text";I.innerHTML=B?MA.chat:MA.phone;let Q=document.createElement("span");return Q.textContent=B?this.config.copy.startChatText:this.config.startCallText,I.appendChild(Q),I.addEventListener("click",()=>this.startOver()),g.appendChild(I),g}if(this.resolvedMode()==="voice"){let I=this.iconButton(this.micEnabled?MA.mic:MA.micOff,this.micEnabled?this.config.copy.muteMic:this.config.copy.unmuteMic,()=>{var Q;this.micEnabled=!this.micEnabled,(Q=this.agent)==null||Q.toggleMicrophone(this.micEnabled),this.render()},`tw-round-btn${this.micEnabled?"":" tw-muted"}`);I.disabled=this.state!=="live",g.appendChild(I);let B=this.iconButton(MA.hangup,this.config.endCallText,()=>this.endConversation(),"tw-round-btn tw-end-btn");B.disabled=this.state==="connecting",g.appendChild(B)}return g}renderVoiceBar(g){let I=document.createElement("div");I.className=g?"tw-callbar tw-callbar-inline":"tw-callbar";let B=this.state==="connecting";I.appendChild(this.buildWave());let Q=document.createElement("div");Q.className="tw-callbar-text";let i=document.createElement("div");i.className="tw-callbar-activity",i.textContent=B?this.config.copy.connecting:this.speaking?this.config.speakingText:this.config.listeningText;let E=document.createElement("div");E.className="tw-callbar-meta tw-timer";let o=this.speakerName();E.textContent=[o,this.timerText()].filter(Boolean).join(" \xB7 "),Q.appendChild(i),Q.appendChild(E),I.appendChild(Q);let D=this.iconButton(this.micEnabled?MA.mic:MA.micOff,this.micEnabled?this.config.copy.muteMic:this.config.copy.unmuteMic,()=>{var s;this.micEnabled=!this.micEnabled,(s=this.agent)==null||s.toggleMicrophone(this.micEnabled),this.render()},`tw-sq tw-sq-quiet${this.micEnabled?"":" tw-muted"}`);if(D.disabled=B,I.appendChild(D),g){let s=this.iconButton(MA.keyboard,this.config.copy.typeInstead,()=>{this.switchModality()},"tw-sq tw-sq-quiet");s.disabled=this.switchingSide||B,I.appendChild(s)}else this.config.mode==="both"&&I.appendChild(this.iconButton(MA.chat,this.config.copy.showConversation,()=>{this.open=!0,this.render()},"tw-sq tw-sq-quiet"));let e=this.iconButton(MA.hangup,this.config.endCallText,()=>this.endConversation(),"tw-sq tw-sq-danger");return I.appendChild(e),I}renderTextInput(){let g=document.createElement("form");g.className="tw-composer";let I=document.createElement("textarea");I.className="tw-text-input",I.rows=1,I.placeholder=this.config.inputPlaceholder,I.value=this.draft,I.setAttribute("aria-label",this.config.inputPlaceholder);let B=document.createElement("button");B.className="tw-send-btn",B.type="submit",B.setAttribute("aria-label",this.config.copy.send),B.innerHTML=MA.send;let Q=()=>{B.disabled=this.state!=="live"||!I.value.trim(),I.style.height="auto",I.style.height=`${Math.min(I.scrollHeight,112)}px`},i=()=>{var o;let E=I.value.trim();!E||this.state!=="live"||(this.draft="",I.value="",Q(),(o=this.agent)==null||o.sendTextMessage(E))};if(I.addEventListener("input",()=>{this.draft=I.value,Q()}),I.addEventListener("keydown",E=>{E.key==="Enter"&&!E.shiftKey&&!E.isComposing&&(E.preventDefault(),i())}),g.addEventListener("submit",E=>{E.preventDefault(),i()}),g.appendChild(I),this.config.mode==="both"){let E=this.iconButton(MA.phone,this.config.copy.talkInstead,()=>{this.switchModality()},"tw-composer-mic");E.disabled=this.state!=="live"||this.switchingSide,g.appendChild(E)}return g.appendChild(B),requestAnimationFrame(Q),this.state==="live"&&requestAnimationFrame(()=>I.focus({preventScroll:!0})),g}streamingReply(){var I,B;let g=(B=(I=this.agent)==null?void 0:I.getCurrentTranscript())!=null?B:{};return Object.entries(g).filter(([Q])=>Q.startsWith("agent")).map(([,Q])=>Q).join(" ").trim()}fillThread(g){g.replaceChildren();let I=null;for(let Q of this.transcripts){if(Q.toolUsed)continue;let i=document.createElement("div");if(i.className=`tw-msg ${Q.role==="user"?"tw-user":"tw-assistant"}`,I===Q.role&&i.classList.add("tw-run"),I=Q.role,Q.role==="user")i.textContent=Q.text;else{if(!i.classList.contains("tw-run")&&this.speakerName()){let o=document.createElement("div");o.className="tw-msg-label",o.textContent=this.speakerName(),i.appendChild(o)}let E=document.createElement("div");E.className="tw-md",E.appendChild(QE(Q.text)),i.appendChild(E)}g.appendChild(i)}let B=this.streamingReply();if(B){let Q=document.createElement("div");if(Q.className="tw-msg tw-assistant tw-streaming",I==="assistant")Q.classList.add("tw-run");else if(this.speakerName()){let E=document.createElement("div");E.className="tw-msg-label",E.textContent=this.speakerName(),Q.appendChild(E)}let i=document.createElement("div");i.className="tw-md",i.appendChild(QE(B)),Q.appendChild(i),g.appendChild(Q)}else if(this.isAwaitingReply()){let Q=document.createElement("div");Q.className="tw-msg tw-assistant tw-typing",Q.setAttribute("aria-label",this.config.copy.typing),Q.innerHTML="<span></span><span></span><span></span>",g.appendChild(Q)}requestAnimationFrame(()=>{g.scrollTop=g.scrollHeight})}isAwaitingReply(){if(this.state==="connecting"||this.pendingMessage)return!0;if(this.state!=="live")return!1;let g=[...this.transcripts].reverse().find(I=>!I.toolUsed);return(g==null?void 0:g.role)==="user"}updateThread(){if(!this.open)return!1;let g=this.root.querySelector(".tw-chat");if(!g)return!1;this.fillThread(g);let I=this.root.querySelector(".tw-suggestions"),B=this.renderSuggestions();I&&!B&&I.remove();let Q=this.root.querySelector(".tw-status");return Q&&(Q.textContent=this.statusText()),!0}renderTranscript(){let g=document.createElement("div");return g.className="tw-chat",g.setAttribute("role","log"),g.setAttribute("aria-live","polite"),this.fillThread(g),g}};function P0(C,A){let g=C.message||"";return/Origin not allowed/i.test(g)?A.errorNotEnabled:/Public access/i.test(g)?A.errorUnavailable:/Too many/i.test(g)?A.errorTooMany:/Insufficient funds/i.test(g)?A.errorUnavailable:A.errorGeneric}var O0="#0062e9";function _0(C){let A=/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(C.trim());if(!A)return"#ffffff";let g=A[1].length===3?A[1].split("").map(E=>E+E).join(""):A[1],I=E=>{let o=parseInt(g.slice(E,E+2),16)/255;return o<=.03928?o/12.92:((o+.055)/1.055)**2.4},B=.2126*I(0)+.7152*I(2)+.0722*I(4),Q=1.05/(B+.05),i=(B+.05)/.06;return Q>=i?"#ffffff":"#16181d"}function $0(C){let A=C.trim().split(/\s+/).filter(I=>/[a-z0-9]/i.test(I));return A.length?(A.length===1?A[0].slice(0,1):A[0][0]+A[1][0]).toUpperCase():""}var og=C=>`<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${C}</svg>`,MA={chat:og('<path d="M20 12.5a7.5 7.5 0 0 1-11.2 6.5L4 20l1.1-4.3A7.5 7.5 0 1 1 20 12.5Z"/>'),phone:og('<path d="M5 4h3l1.6 4-2 1.3a11 11 0 0 0 5.1 5.1l1.3-2 4 1.6v3a2 2 0 0 1-2.2 2A16 16 0 0 1 3 6.2 2 2 0 0 1 5 4Z"/>'),hangup:og('<path d="M3.5 13.5c4.7-4 12.3-4 17 0l-1.6 2.6-3.4-1.2v-2.5a10 10 0 0 0-7 0v2.5l-3.4 1.2Z"/>'),mic:og('<rect x="9" y="3" width="6" height="11" rx="3"/><path d="M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21"/>'),micOff:og('<path d="M15 10V6a3 3 0 0 0-5.7-1.3M9 9v2a3 3 0 0 0 4.6 2.5M5.5 11a6.5 6.5 0 0 0 10.4 5.2M18.5 11a6.4 6.4 0 0 1-.6 2.6M12 17.5V21M4 4l16 16"/>'),send:og('<path d="M12 19V5M5.5 11.5 12 5l6.5 6.5"/>'),minimize:og('<path d="m6 9 6 6 6-6"/>'),thumbUp:og('<path d="M7 11v9H4v-9h3Zm0 0 4-7a2 2 0 0 1 2 2v3h5a2 2 0 0 1 2 2.3l-1.2 6A2 2 0 0 1 16.8 19H7"/>'),thumbDown:og('<path d="M17 13V4h3v9h-3Zm0 0-4 7a2 2 0 0 1-2-2v-3H6a2 2 0 0 1-2-2.3l1.2-6A2 2 0 0 1 7.2 5H17"/>'),keyboard:og('<rect x="3" y="6" width="18" height="12" rx="2"/><path d="M7 10h.01M11 10h.01M15 10h.01M7 14h10"/>'),close:og('<path d="M6 6l12 12M18 6 6 18"/>'),spinner:og('<path d="M12 3a9 9 0 1 0 9 9" class="tw-spin"/>')};var EE="trillet-widget";function iE(C=EE){typeof customElements!="undefined"&&(customElements.get(C)||customElements.define(C,qI))}iE();var AK={register:iE,TrilletWidgetElement:qI,tag:EE};typeof window!="undefined"&&(window.TrilletWidget=AK);return ah(gK);})();
|
|
3991
|
+
`).filter(o=>o.trim()!=="");if(!B.length)continue;let Q=/^\s*[-*•]\s+/,i=/^\s*\d+[.)]\s+/;if(B.every(o=>Q.test(o))||B.every(o=>i.test(o))){let o=i.test(B[0]),D=document.createElement(o?"ol":"ul");for(let e of B){let s=document.createElement("li");Ch(s,e.replace(o?i:Q,"")),D.appendChild(s)}A.appendChild(D);continue}let E=document.createElement("p");B.forEach((o,D)=>{D>0&&E.appendChild(document.createElement("br")),Ch(E,o)}),A.appendChild(E)}return A}var qI=class extends HTMLElement{constructor(){super();this.agent=null;this.state="idle";this.open=!1;this.micEnabled=!0;this.speaking=!1;this.transcripts=[];this.display=null;this.activeMode=null;this.switching=!1;this.remote=null;this.remoteDisplay=null;this.remoteLoadedFor=null;this.pendingMessage=null;this.durationTimer=null;this.remainingSeconds=null;this.elapsedSeconds=0;this.recaptchaSolved=!1;this.recaptchaSlot=null;this.recaptchaWidgetId=null;this.pendingTimer=null;this.lastView=null;this.notice=null;this.switchingSide=!1;this.callGeneration=0;this.smoothedLevel=0;this.showTerms=!1;this.pendingStart=null;this.callId=null;this.feedbackState="hidden";this.termsAcceptedThisPage=!1;this.showVariablesForm=!1;this.dynamicVariableValues=null;this.askFocused=!1;this.errorText=null;this.draft="";this.root=this.attachShadow({mode:"open"}),this.styleEl=document.createElement("style"),this.styleEl.textContent=$c,this.container=document.createElement("div"),this.container.className="tw-root",this.root.appendChild(this.styleEl),this.root.appendChild(this.container)}static get observedAttributes(){return Pc}connectedCallback(){this.refreshConfig(),this.loadRemoteConfig()}refreshConfig(){this.config=_c(this,this.remote),this.syncActiveMode(),this.applyTheme(),this.render()}async loadRemoteConfig(){var Q,i;let{agentId:g,remoteConfig:I,apiBase:B}=this.config;if(!(!I||!g||this.remoteLoadedFor===g)){this.remoteLoadedFor=g;try{let E=`${YC("/v1/api/web-call/public/widget-config",B)}?agent_id=${encodeURIComponent(g)}`,o=await fetch(E,{headers:{Accept:"application/json"}});if(!o.ok)return;let D=await o.json();if(this.config.agentId!==g)return;this.remote=(Q=D.widget)!=null?Q:null,this.remoteDisplay=(i=D.display)!=null?i:null,this.state==="idle"&&this.refreshConfig()}catch(E){console.warn("[trillet-widget] Could not load widget design; using attributes only",E)}}}disconnectedCallback(){this.clearDurationTimer(),this.teardownAgent(),this.removeRecaptchaSlot()}attributeChangedCallback(){this.isConnected&&(this.refreshConfig(),this.loadRemoteConfig())}async sendMessage(g){var B;let I=g.trim();if(I){if(this.state==="live"&&(this.resolvedMode()==="text"||this.config.mode==="both")){await((B=this.agent)==null?void 0:B.sendTextMessage(I));return}this.config.mode!=="voice"&&((this.state==="idle"||this.state==="ended")&&(this.transcripts=[]),this.pendingMessage=I,this.state!=="connecting"&&await this.startConversation("text"))}}async startConversation(g){if(this.state==="connecting"||this.state==="live")return;if((this.config.mode==="text"||this.config.mode==="both"&&g!=="voice")&&(this.open=!0),this.needsRecaptcha()){this.render();return}await this.beginCall(g)}endConversation(){var g;(g=this.agent)==null||g.endCall()}startOver(g){if(this.callGeneration+=1,this.clearDurationTimer(),this.teardownAgent(),this.pendingTimer&&clearTimeout(this.pendingTimer),this.pendingTimer=null,this.pendingMessage=null,this.transcripts=[],this.notice=null,this.errorText=null,this.feedbackState="hidden",this.speaking=!1,this.callId=null,this.display=null,this.dynamicVariableValues=null,this.state="idle",this.config.mode==="both"&&(this.activeMode=g!=null?g:null,!g)){this.render();return}this.beginCall(g)}startCall(){return this.startConversation()}endCall(){this.endConversation()}resolvedMode(){var g;return this.config.mode==="both"?(g=this.activeMode)!=null?g:"voice":this.config.mode}syncActiveMode(){(this.config.mode==="voice"||this.config.mode==="text")&&(this.activeMode=this.config.mode)}teardownAgent(){if(this.agent){try{this.agent.removeAllListeners()}catch(g){}try{this.agent.endCall()}catch(g){}this.agent=null}}async switchModality(){if(this.config.mode!=="both"||this.state!=="live"||!this.agent)return;let g=this.resolvedMode()==="text";this.notice=null,this.switchingSide=!0,this.render();try{await this.agent.setVoiceEnabled(g)}catch(I){console.warn("[trillet-widget] Could not switch modality",I),this.notice=g?"Could not turn on your microphone. Check the browser permission and try again.":"Could not switch back to typing. Please try again."}finally{this.switchingSide=!1,this.render()}}setSpeaking(g){if(this.speaking===g)return;this.speaking=g;let I=g?this.config.speakingText:this.config.listeningText;this.root.querySelectorAll(".tw-callbar-activity").forEach(Q=>{Q.textContent=I}),this.root.querySelectorAll(".tw-wave").forEach(Q=>Q.classList.toggle("tw-wave-speaking",g)),this.root.querySelectorAll(".tw-mark").forEach(Q=>Q.classList.toggle("tw-speaking",g));let B=this.root.querySelector(".tw-header .tw-status");B&&(B.textContent=this.statusText())}flushPending(){this.pendingTimer&&clearTimeout(this.pendingTimer),this.pendingTimer=null;let g=this.pendingMessage;this.pendingMessage=null,g&&this.agent&&this.state==="live"&&this.agent.sendTextMessage(g)}async beginCall(g){if(this.config.termsText&&!this.termsAccepted()){this.pendingStart=g!=null?g:this.resolvedMode(),this.showTerms=!0,this.render();return}if(this.config.dynamicVariablePrompts.length>0&&!this.dynamicVariableValues){this.pendingStart=g!=null?g:this.resolvedMode(),this.showVariablesForm=!0,this.render();return}this.feedbackState="hidden",g&&(this.activeMode=g);let I=this.resolvedMode(),B=this.config.mode==="both"?"multimodal":I;this.notice=null,this.switching||(this.display=null);let Q={...this.config.dynamicVariablePresets,...this.dynamicVariableValues,...this.config.variables},i=++this.callGeneration;this.setState("connecting");try{let E=new BE({agentId:this.config.agentId,workspaceId:this.config.workspaceId,apiBaseUrl:this.config.apiBase,mode:B,startWithVoice:B==="multimodal"&&I==="voice",variables:Q});if(this.agent=E,this.wireAgentEvents(E),this.config.signedUrlEndpoint||this.getRoomDetails){let o;if(this.getRoomDetails)o=await this.getRoomDetails({mode:I,session:B,variables:Q});else{let D=await fetch(this.config.signedUrlEndpoint,{method:"GET",headers:{Accept:"application/json"}});if(!D.ok)throw new Error(`signed-url-endpoint returned ${D.status}`);o=await D.json()}await E.joinRoom(o)}else if(this.roomDetails)await E.joinRoom(this.roomDetails);else if(this.config.workspaceId)await E.startPublicCall();else throw new Error("No credential path configured: set signed-url-endpoint, roomDetails/getRoomDetails, or workspace-id")}catch(E){if(i!==this.callGeneration)return;this.handleError(E)}}wireAgentEvents(g){g.on("connected",I=>{var Q,i;this.display=(Q=I==null?void 0:I.display)!=null?Q:null,this.callId=(i=I==null?void 0:I.callId)!=null?i:null;let B=this.switching;this.setState("live"),this.startDurationTimer(!B),this.switching=!1,this.pendingMessage&&(this.pendingTimer=setTimeout(()=>this.flushPending(),25e3))}),g.on("disconnected",()=>{this.endLocalCall()}),g.on("error",I=>{this.handleError(I)}),g.on("modalityChanged",I=>{this.activeMode=I,this.speaking=!1,this.dispatch("modality",I),this.render()}),g.on("audioData",I=>this.setLevel(I)),g.on("assistantStartedSpeaking",()=>this.setSpeaking(!0)),g.on("assistantStoppedSpeaking",()=>this.setSpeaking(!1)),g.on("transcriptUpdate",I=>{this.transcripts=[...I],this.pendingMessage&&I.some(B=>B.role==="assistant"&&!B.toolUsed)&&this.flushPending(),this.dispatch("transcript",this.transcripts),this.updateThread()||this.render()})}endLocalCall(){this.state==="ended"||this.state==="idle"||(this.config.feedback==="end"&&this.callId&&this.elapsedSeconds>=5&&(this.feedbackState="ask"),this.clearDurationTimer(),this.speaking=!1,this.dispatch("call-end",this.elapsedSeconds),this.dispatch("conversationEnded",this.elapsedSeconds),this.setState("ended"),this.agent=null,this.pendingMessage=null,this.pendingTimer&&clearTimeout(this.pendingTimer),this.pendingTimer=null,this.config.mode==="both"&&(this.activeMode=null))}handleError(g){let I=g instanceof Error?g:new Error(String(g));this.errorText=P0(I,this.config.copy),this.clearDurationTimer(),this.speaking=!1,this.switching=!1,this.dispatch("error",I),this.agent=null,this.config.mode==="both"&&(this.activeMode=null),this.setState("idle")}startDurationTimer(g=!0){this.clearDurationTimer(),g&&(this.elapsedSeconds=0,this.remainingSeconds=typeof this.config.maxCallDuration=="number"?this.config.maxCallDuration:null),this.durationTimer=setInterval(()=>{var I;if(this.elapsedSeconds+=1,this.remainingSeconds!==null&&(this.remainingSeconds-=1,this.remainingSeconds<=0)){(I=this.agent)==null||I.endCall();return}this.renderStatus()},1e3)}clearDurationTimer(){this.durationTimer&&(clearInterval(this.durationTimer),this.durationTimer=null)}setState(g){let I=this.state;g==="connecting"&&(this.errorText=null),this.state=g,g==="live"&&I!=="live"&&!this.switching&&(this.dispatch("call-start",void 0),this.dispatch("conversationStarted",void 0)),this.render()}dispatch(g,I){this.dispatchEvent(new CustomEvent(g,{detail:I,bubbles:!0,composed:!0}))}applyTheme(){let g=this.config.brand.primaryColor||this.config.orbColor1||O0;this.style.setProperty("--tw-accent",g),this.style.setProperty("--tw-on-accent",_0(g));let I=this.config.backgroundColor||this.config.textColor,B=(Q,i)=>i?this.style.setProperty(Q,i):this.style.removeProperty(Q);B("--tw-surface",this.config.backgroundColor),B("--tw-ink",this.config.textColor),B("--tw-raised",I?"color-mix(in srgb, var(--tw-ink) 7%, var(--tw-surface))":void 0),B("--tw-line",I?"color-mix(in srgb, var(--tw-ink) 14%, var(--tw-surface))":void 0),B("--tw-muted",I?"color-mix(in srgb, var(--tw-ink) 62%, var(--tw-surface))":void 0),this.config.buttonTextColor&&this.style.setProperty("--tw-on-accent",this.config.buttonTextColor),this.style.setProperty("--tw-orb-1",this.config.orbColor1||g),this.style.setProperty("--tw-orb-2",this.config.orbColor2||"#27a3fd"),this.dataset.placement=this.config.placement,this.dataset.theme=this.config.theme}formatTime(g){let I=Math.floor(g/60),B=g%60;return`${I}:${B.toString().padStart(2,"0")}`}statusText(){return this.state==="connecting"?this.config.copy.connecting:this.state==="live"&&this.resolvedMode()==="voice"?`${this.speaking?this.config.speakingText:this.config.listeningText} ${this.timerText()}`.trim():this.state==="live"?this.config.copy.online:this.config.brand.name||this.config.copy.online}renderStatus(){let g=this.root.querySelector(".tw-status");g&&(g.textContent=this.statusText()),this.root.querySelectorAll(".tw-timer").forEach(I=>{I.textContent=I.classList.contains("tw-callbar-meta")?[this.speakerName(),this.timerText()].filter(Boolean).join(" \xB7 "):this.timerText()})}timerText(){return this.state!=="live"?"":this.remainingSeconds!==null?this.formatTime(Math.max(0,this.remainingSeconds)):this.formatTime(this.elapsedSeconds)}setLevel(g){let I=0;for(let i=0;i<g.length;i+=1)I+=g[i]*g[i];let B=Math.sqrt(I/(g.length||1)),Q=Math.min(1,B*6);this.smoothedLevel=this.smoothedLevel*.7+Q*.3,this.style.setProperty("--tw-level",this.smoothedLevel.toFixed(3))}render(){this.container.replaceChildren();let g,I;this.showTerms?(g="terms",I=this.renderTerms()):this.showVariablesForm?(g="variables",I=this.renderVariablesForm()):this.open?(g="panel",I=this.renderPanel()):(I=this.renderCard(),g=I.querySelector(".tw-callbar")?"callbar":"bar"),g!==this.lastView&&I.classList.add("tw-enter"),this.lastView=g,this.container.appendChild(I)}avatarStyle(){let g=this.config.avatarStyle;return g==="image"&&!this.config.avatar?"orb":g||(this.config.avatar?"image":"orb")}buildAvatar(g){let I=document.createElement("span"),B=this.avatarStyle();return I.className=`tw-mark tw-mark-${g} tw-mark-${B}`,I.setAttribute("aria-hidden","true"),this.state==="live"&&this.resolvedMode()==="voice"&&I.classList.add("tw-voice-live"),B==="image"?I.style.backgroundImage=`url("${this.config.avatar}")`:B==="initials"&&(I.textContent=$0(this.speakerName())),I}speakerName(){return this.config.brand.name||this.headerTitle()||""}buildWave(){let g=document.createElement("span");g.className=`tw-wave${this.speaking?" tw-wave-speaking":""}`,g.setAttribute("aria-hidden","true");for(let I=0;I<5;I+=1)g.appendChild(document.createElement("i"));return g}iconButton(g,I,B,Q=""){let i=document.createElement("button");return i.type="button",i.className=`tw-icon-btn ${Q}`.trim(),i.title=I,i.setAttribute("aria-label",I),i.innerHTML=g,i.addEventListener("click",B),i}termsKey(){let g=0;for(let I of this.config.termsText||"")g=g*31+I.charCodeAt(0)|0;return`trillet-terms:${this.config.agentId}:${g}`}termsAccepted(){if(this.termsAcceptedThisPage)return!0;try{return window.localStorage.getItem(this.termsKey())==="1"}catch(g){return!1}}renderTerms(){let g=document.createElement("div");g.className="tw-card tw-terms",g.setAttribute("role","dialog"),g.setAttribute("aria-label",this.config.copy.terms);let I=document.createElement("div");I.className="tw-card-title",I.textContent=this.config.copy.termsTitle,g.appendChild(I);let B=document.createElement("div");B.className="tw-terms-body tw-md",B.appendChild(QE(this.config.termsText||"")),g.appendChild(B);let Q=document.createElement("div");Q.className="tw-card-actions";let i=document.createElement("button");i.type="button",i.className="tw-pill",i.textContent=this.config.copy.termsAccept,i.addEventListener("click",()=>{try{window.localStorage.setItem(this.termsKey(),"1")}catch(D){}this.termsAcceptedThisPage=!0,this.showTerms=!1;let o=this.pendingStart;this.pendingStart=null,o==="text"&&(this.open=!0),this.beginCall(o!=null?o:void 0)});let E=document.createElement("button");return E.type="button",E.className="tw-secondary-btn",E.textContent=this.config.copy.termsDecline,E.addEventListener("click",()=>{this.showTerms=!1,this.pendingStart=null,this.open=!1,this.render()}),Q.appendChild(i),Q.appendChild(E),g.appendChild(Q),g}renderVariablesForm(){let g=document.createElement("div");g.className="tw-card tw-variables-form",g.setAttribute("role","dialog"),g.setAttribute("aria-label",this.config.copy.continueText);let I=document.createElement("div");I.className="tw-card-title",I.textContent=this.config.copy.termsTitle,g.appendChild(I);let B=[],Q=document.createElement("button");Q.type="button",Q.className="tw-pill",Q.textContent=this.config.copy.continueText,Q.addEventListener("click",()=>{var s;let o={},D=!0;for(let a of B){let t=a.input.value.trim(),w=a.required&&!t;if(a.err.hidden=!w,a.input.setAttribute("aria-invalid",w?"true":"false"),w){D=!1;continue}t&&(o[a.key]=t)}if(!D){(s=B.find(a=>!a.err.hidden))==null||s.input.focus();return}this.dynamicVariableValues=o,this.showVariablesForm=!1;let e=this.pendingStart;this.pendingStart=null,e==="text"&&(this.open=!0),this.beginCall(e!=null?e:void 0)}),this.config.dynamicVariablePrompts.forEach((o,D)=>{let e=document.createElement("div");e.className="tw-field";let s=`tw-var-${D}`,a=`tw-var-err-${D}`,t=document.createElement("label");if(t.className="tw-field-label",t.htmlFor=s,t.textContent=o.label||o.key,o.required){let M=document.createElement("span");M.className="tw-field-required",M.textContent="*",M.setAttribute("aria-hidden","true"),t.appendChild(M)}e.appendChild(t);let w=document.createElement("input");w.type="text",w.id=s,w.className="tw-field-input",o.placeholder&&(w.placeholder=o.placeholder),o.required&&(w.required=!0),w.setAttribute("aria-required",o.required?"true":"false"),w.setAttribute("aria-describedby",a),w.addEventListener("keydown",M=>{M.key==="Enter"&&(M.preventDefault(),Q.click())}),e.appendChild(w);let c=document.createElement("p");c.className="tw-field-error",c.id=a,c.textContent=this.config.copy.fieldRequired,c.hidden=!0,e.appendChild(c),g.appendChild(e),B.push({key:o.key,required:!!o.required,input:w,err:c})});let i=document.createElement("div");i.className="tw-card-actions",i.appendChild(Q);let E=document.createElement("button");return E.type="button",E.className="tw-secondary-btn",E.textContent=this.config.copy.termsDecline,E.addEventListener("click",()=>{this.showVariablesForm=!1,this.pendingStart=null,this.open=!1,this.render()}),i.appendChild(E),g.appendChild(i),g}renderFeedback(){if(this.feedbackState==="hidden")return null;let g=document.createElement("div");if(g.className="tw-feedback",this.feedbackState==="sent")return g.textContent=this.config.copy.feedbackThanks,g;let I=document.createElement("span");I.textContent=this.config.copy.feedbackQuestion,g.appendChild(I);let B=Q=>{this.feedbackState="sent",this.render(),fetch(YC("/v1/api/web-call/public/feedback",this.config.apiBase),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({call_id:this.callId,rating:Q})}).catch(()=>{}),this.dispatch("feedback",Q)};return g.appendChild(this.iconButton(MA.thumbUp,this.config.copy.feedbackGood,()=>B("up"))),g.appendChild(this.iconButton(MA.thumbDown,this.config.copy.feedbackBad,()=>B("down"))),g}renderCard(){let g=this.state==="idle"||this.state==="ended",I=this.state==="live",B=I&&this.resolvedMode()==="voice",Q=this.state==="connecting"&&this.resolvedMode()==="voice",i=this.needsRecaptcha()&&g,E=document.createElement("div");if(E.className="tw-bar-stack",B||Q)return E.appendChild(this.renderVoiceBar(!1)),E;if(this.errorText&&g){let t=document.createElement("div");t.className="tw-bar-note tw-error-text",t.textContent=this.errorText,E.appendChild(t)}let o=document.createElement("div");o.className="tw-ask",o.appendChild(this.buildAvatar("md"));let D=this.speakerName(),e=this.config.mode!=="voice",s=this.config.mode!=="text";if(I||this.state==="connecting"){let t=document.createElement("button");return t.type="button",t.className="tw-ask-label",t.textContent=D?xD(this.config.copy.chatWithNamed,D):this.config.copy.backToChat,t.addEventListener("click",()=>this.openPanel()),o.appendChild(t),o.appendChild(this.iconButton(MA.chat,this.config.copy.openChat,()=>this.openPanel(),"tw-sq tw-sq-accent")),E.appendChild(o),E}if(e){let t=document.createElement("form");t.className="tw-ask-form";let w=document.createElement("input");w.className="tw-ask-input",w.type="text",w.placeholder=this.config.greeting||(D?xD(this.config.copy.askNamed,D):this.config.copy.askAnything),w.setAttribute("aria-label",w.placeholder),w.value=this.draft,w.disabled=i;let c=this.iconButton(MA.send,this.config.copy.send,()=>{},"tw-sq tw-sq-accent");c.type="submit";let M=()=>{c.disabled=i||!w.value.trim()};if(w.addEventListener("input",()=>{this.draft=w.value,M()}),w.addEventListener("focus",()=>{this.askFocused=!0,this.renderAskSuggestions(E,o)}),w.addEventListener("blur",()=>{this.askFocused=!1,setTimeout(()=>{var y;this.askFocused||(y=E.querySelector(".tw-ask-suggestions"))==null||y.remove()},150)}),t.addEventListener("submit",y=>{y.preventDefault();let F=w.value.trim();!F||this.needsRecaptcha()||(this.draft="",this.sendMessage(F))}),t.appendChild(w),s){let y=this.iconButton(MA.phone,this.config.actionText||this.config.startCallText,()=>{this.needsRecaptcha()||this.beginCall("voice")},"tw-sq tw-sq-quiet");y.disabled=i,t.appendChild(y)}t.appendChild(c),M(),o.appendChild(t)}else{let t=document.createElement("button");t.type="button",t.className="tw-ask-label",t.textContent=this.config.greeting||(D?`Talk to ${D}`:this.config.startCallText),t.disabled=i,t.addEventListener("click",()=>{this.needsRecaptcha()||this.beginCall("voice")}),o.appendChild(t);let w=this.iconButton(MA.phone,this.config.actionText||this.config.startCallText,()=>{this.needsRecaptcha()||this.beginCall("voice")},"tw-sq tw-sq-accent");w.disabled=i,o.appendChild(w)}if(E.appendChild(o),i){let t=document.createElement("slot");t.setAttribute("name","recaptcha"),t.className="tw-recaptcha-slot",E.insertBefore(t,o),this.ensureRecaptchaSlot()}let a=g?this.renderFeedback():null;return a&&(a.classList.add("tw-bar-note"),E.insertBefore(a,o)),E}renderAskSuggestions(g,I){if(!this.config.suggestedPrompts.length||g.querySelector(".tw-ask-suggestions"))return;let B=document.createElement("div");B.className="tw-ask-suggestions";for(let Q of this.config.suggestedPrompts){let i=document.createElement("button");i.type="button",i.className="tw-suggestion",i.textContent=Q,i.addEventListener("mousedown",E=>{E.preventDefault(),this.askFocused=!1,this.sendMessage(Q)}),B.appendChild(i)}g.insertBefore(B,I)}openPanel(){this.open=!0;let g=this.state==="idle"&&this.transcripts.length===0;if(this.config.mode==="text"&&g&&!this.needsRecaptcha()){this.beginCall("text");return}this.render()}renderPanel(){let g=document.createElement("div");return g.className=`tw-panel${this.config.variant==="expanded"?" tw-expanded":""}`,g.setAttribute("role","dialog"),g.setAttribute("aria-label",this.headerTitle()||this.config.copy.chat),g.appendChild(this.renderHeader()),g.appendChild(this.renderBody()),g}headerTitle(){var i,E,o,D;let g=(i=this.display)!=null?i:this.remoteDisplay,I=(E=this.config.agentName)!=null?E:g==null?void 0:g.agent_name,B=(o=this.config.callFlowName)!=null?o:g==null?void 0:g.call_flow_name,Q=(D=this.config.workspaceName)!=null?D:g==null?void 0:g.workspace_name;return I||B||Q||""}renderHeader(){let g=document.createElement("div");g.className="tw-header",this.bodyShowsLargeAvatar()||g.appendChild(this.buildAvatar("sm"));let I=document.createElement("div");I.className="tw-who";let B=document.createElement("div");B.className="tw-header-title";let Q=this.config.agentName||this.speakerName();B.textContent=Q,Q&&(B.title=Q);let i=document.createElement("div");if(i.className="tw-status",this.state==="live"&&i.classList.add("tw-online"),i.textContent=this.statusText(),I.appendChild(B),I.appendChild(i),g.appendChild(I),this.config.brand.logo){let o=document.createElement("img");o.className="tw-brand-logo",o.src=this.config.brand.logo,o.alt=this.config.brand.name||"",g.appendChild(o)}let E=document.createElement("div");return E.className="tw-header-actions",E.appendChild(this.iconButton(MA.minimize,this.config.copy.minimize,()=>{this.open=!1,this.render()})),this.config.dismissible&&E.appendChild(this.iconButton(MA.close,this.config.copy.close,()=>{(this.state==="live"||this.state==="connecting")&&this.endConversation(),this.open=!1,this.render()})),g.appendChild(E),g}bodyShowsLargeAvatar(){let g=this.state==="idle"||this.state==="ended";return this.needsRecaptcha()&&g||this.isBothPreCall()||this.config.mode!=="both"&&this.resolvedMode()==="voice"?!0:this.state==="idle"&&this.transcripts.length===0}isBothPreCall(){return this.config.mode==="both"&&this.activeMode===null&&this.transcripts.length===0&&(this.state==="idle"||this.state==="ended")}needsRecaptcha(){return!!this.config.recaptchaSiteKey&&!this.recaptchaSolved}renderRecaptchaGate(g){g.classList.add("tw-center-body"),g.appendChild(this.buildAvatar("lg"));let I=document.createElement("p");I.className="tw-prompt",I.textContent=this.config.recaptchaText,g.appendChild(I);let B=document.createElement("slot");B.setAttribute("name","recaptcha"),B.className="tw-recaptcha-slot",g.appendChild(B);let Q=document.createElement("button");Q.className="tw-primary-btn",Q.type="button",Q.textContent=this.config.startCallText,Q.disabled=!0,g.appendChild(Q),this.ensureRecaptchaSlot()}ensureRecaptchaSlot(){let g=this.config.recaptchaSiteKey;if(!g||this.recaptchaSolved||this.recaptchaSlot)return;let I=document.createElement("div");I.setAttribute("slot","recaptcha"),I.className="tw-recaptcha-mount",this.appendChild(I),this.recaptchaSlot=I,this.recaptchaWidgetId=-1,gh({container:I,siteKey:g,onSolved:()=>{this.recaptchaSolved=!0,this.removeRecaptchaSlot(),this.render()},onExpired:()=>{this.recaptchaSolved=!1}}).then(B=>{this.recaptchaWidgetId=B}).catch(B=>{console.warn("[trillet-widget] reCAPTCHA failed to load; starting without it",B),this.recaptchaSolved=!0,this.removeRecaptchaSlot(),this.render()})}removeRecaptchaSlot(){var g;(g=this.recaptchaSlot)==null||g.remove(),this.recaptchaSlot=null,this.recaptchaSolved||(this.recaptchaWidgetId=null)}renderBody(){let g=document.createElement("div");return g.className="tw-body",this.needsRecaptcha()&&(this.state==="idle"||this.state==="ended")?(this.renderRecaptchaGate(g),g):this.isBothPreCall()?(this.renderBothEntry(g),g):(this.resolvedMode()==="text"||this.config.mode==="both"?this.renderTextBody(g):this.renderVoiceBody(g),g)}renderBothEntry(g){g.classList.add("tw-center-body"),g.appendChild(this.buildAvatar("lg"));let I=document.createElement("p");I.className="tw-prompt",I.textContent=this.config.greeting||this.config.copy.chooseModePrompt,g.appendChild(I);let B=document.createElement("div");B.className="tw-choices";let Q=(i,E,o,D)=>{let e=document.createElement("button");e.type="button",e.className=D?"tw-primary-btn":"tw-secondary-btn",e.innerHTML=i;let s=document.createElement("span");return s.textContent=E,e.appendChild(s),e.addEventListener("click",()=>this.startOver(o)),e};B.appendChild(Q(MA.phone,this.config.startCallText,"voice",!0)),B.appendChild(Q(MA.chat,this.config.messageText,"text",!1)),g.appendChild(B)}renderVoiceBody(g){var Q;g.classList.add("tw-center-body","tw-voice-body"),g.appendChild(this.buildAvatar("lg"));let I=document.createElement("p");I.className="tw-prompt",this.state==="connecting"?I.textContent=this.config.copy.connecting:this.state==="live"?I.textContent=this.speaking?this.config.speakingText:this.config.listeningText:this.state==="ended"?I.textContent=(Q=this.errorText)!=null?Q:this.config.copy.callEnded:I.textContent=this.config.actionText||this.config.copy.talkToUs,this.errorText&&this.state!=="live"&&I.classList.add("tw-error-text"),g.appendChild(I);let B=document.createElement("div");B.className="tw-timer",B.textContent=this.timerText(),g.appendChild(B),g.appendChild(this.renderControls())}renderTextBody(g){var o;if(g.classList.add("tw-chat-body"),this.state==="idle"&&this.transcripts.length===0){if(g.classList.add("tw-center-body"),g.appendChild(this.buildAvatar("lg")),this.errorText){let D=document.createElement("p");D.className="tw-prompt tw-error-text",D.textContent=this.errorText,g.appendChild(D)}g.appendChild(this.renderControls());return}g.appendChild(this.renderTranscript());let I=this.renderSuggestions();if(I&&g.appendChild(I),this.state==="ended"||this.state==="idle"){let D=document.createElement("div");D.className="tw-chat-ended";let e=document.createElement("span");e.textContent=(o=this.errorText)!=null?o:this.config.copy.chatEnded,this.errorText&&e.classList.add("tw-error-text"),D.appendChild(e);let s=document.createElement("button");s.type="button",s.className="tw-secondary-btn tw-small",s.textContent=this.config.copy.startNewChat,s.addEventListener("click",()=>this.startOver(this.config.mode==="both"?void 0:this.resolvedMode())),D.appendChild(s),g.appendChild(D);let a=this.renderFeedback();a&&g.appendChild(a);return}if(this.notice){let D=document.createElement("p");D.className="tw-notice",D.setAttribute("role","status"),D.textContent=this.notice,g.appendChild(D)}let B=this.config.mode==="both"&&this.resolvedMode()==="voice";g.appendChild(B?this.renderVoiceBar(!0):this.renderTextInput());let Q=document.createElement("div");Q.className="tw-chat-footer";let i=document.createElement("button");i.className="tw-link-btn tw-end-chat",i.type="button",i.textContent=this.config.mode==="text"?this.config.endCallText:this.config.copy.endConversationText,i.disabled=this.state==="connecting",i.addEventListener("click",()=>this.endConversation()),Q.appendChild(i);let E=document.createElement("button");E.className="tw-link-btn",E.type="button",E.textContent=this.config.copy.startOver,E.disabled=this.state==="connecting",E.addEventListener("click",()=>this.startOver(this.resolvedMode())),Q.appendChild(E),g.appendChild(Q)}renderSuggestions(){let g=this.config.suggestedPrompts,I=this.transcripts.some(Q=>Q.role==="user");if(!g.length||I||this.state==="ended")return null;let B=document.createElement("div");B.className="tw-suggestions";for(let Q of g){let i=document.createElement("button");i.type="button",i.className="tw-suggestion",i.textContent=Q,i.addEventListener("click",()=>{this.sendMessage(Q)}),B.appendChild(i)}return B}renderControls(){let g=document.createElement("div");if(g.className="tw-controls",this.state==="idle"||this.state==="ended"){let I=document.createElement("button");I.className="tw-primary-btn",I.type="button";let B=this.resolvedMode()==="text";I.innerHTML=B?MA.chat:MA.phone;let Q=document.createElement("span");return Q.textContent=B?this.config.copy.startChatText:this.config.startCallText,I.appendChild(Q),I.addEventListener("click",()=>this.startOver()),g.appendChild(I),g}if(this.resolvedMode()==="voice"){let I=this.iconButton(this.micEnabled?MA.mic:MA.micOff,this.micEnabled?this.config.copy.muteMic:this.config.copy.unmuteMic,()=>{var Q;this.micEnabled=!this.micEnabled,(Q=this.agent)==null||Q.toggleMicrophone(this.micEnabled),this.render()},`tw-round-btn${this.micEnabled?"":" tw-muted"}`);I.disabled=this.state!=="live",g.appendChild(I);let B=this.iconButton(MA.hangup,this.config.endCallText,()=>this.endConversation(),"tw-round-btn tw-end-btn");B.disabled=this.state==="connecting",g.appendChild(B)}return g}renderVoiceBar(g){let I=document.createElement("div");I.className=g?"tw-callbar tw-callbar-inline":"tw-callbar";let B=this.state==="connecting";I.appendChild(this.buildWave());let Q=document.createElement("div");Q.className="tw-callbar-text";let i=document.createElement("div");i.className="tw-callbar-activity",i.textContent=B?this.config.copy.connecting:this.speaking?this.config.speakingText:this.config.listeningText;let E=document.createElement("div");E.className="tw-callbar-meta tw-timer";let o=this.speakerName();E.textContent=[o,this.timerText()].filter(Boolean).join(" \xB7 "),Q.appendChild(i),Q.appendChild(E),I.appendChild(Q);let D=this.iconButton(this.micEnabled?MA.mic:MA.micOff,this.micEnabled?this.config.copy.muteMic:this.config.copy.unmuteMic,()=>{var s;this.micEnabled=!this.micEnabled,(s=this.agent)==null||s.toggleMicrophone(this.micEnabled),this.render()},`tw-sq tw-sq-quiet${this.micEnabled?"":" tw-muted"}`);if(D.disabled=B,I.appendChild(D),g){let s=this.iconButton(MA.keyboard,this.config.copy.typeInstead,()=>{this.switchModality()},"tw-sq tw-sq-quiet");s.disabled=this.switchingSide||B,I.appendChild(s)}else this.config.mode==="both"&&I.appendChild(this.iconButton(MA.chat,this.config.copy.showConversation,()=>{this.open=!0,this.render()},"tw-sq tw-sq-quiet"));let e=this.iconButton(MA.hangup,this.config.endCallText,()=>this.endConversation(),"tw-sq tw-sq-danger");return I.appendChild(e),I}renderTextInput(){let g=document.createElement("form");g.className="tw-composer";let I=document.createElement("textarea");I.className="tw-text-input",I.rows=1,I.placeholder=this.config.inputPlaceholder,I.value=this.draft,I.setAttribute("aria-label",this.config.inputPlaceholder);let B=document.createElement("button");B.className="tw-send-btn",B.type="submit",B.setAttribute("aria-label",this.config.copy.send),B.innerHTML=MA.send;let Q=()=>{B.disabled=this.state!=="live"||!I.value.trim(),I.style.height="auto",I.style.height=`${Math.min(I.scrollHeight,112)}px`},i=()=>{var o;let E=I.value.trim();!E||this.state!=="live"||(this.draft="",I.value="",Q(),(o=this.agent)==null||o.sendTextMessage(E))};if(I.addEventListener("input",()=>{this.draft=I.value,Q()}),I.addEventListener("keydown",E=>{E.key==="Enter"&&!E.shiftKey&&!E.isComposing&&(E.preventDefault(),i())}),g.addEventListener("submit",E=>{E.preventDefault(),i()}),g.appendChild(I),this.config.mode==="both"){let E=this.iconButton(MA.phone,this.config.copy.talkInstead,()=>{this.switchModality()},"tw-composer-mic");E.disabled=this.state!=="live"||this.switchingSide,g.appendChild(E)}return g.appendChild(B),requestAnimationFrame(Q),this.state==="live"&&requestAnimationFrame(()=>I.focus({preventScroll:!0})),g}streamingReply(){var I,B;let g=(B=(I=this.agent)==null?void 0:I.getCurrentTranscript())!=null?B:{};return Object.entries(g).filter(([Q])=>Q.startsWith("agent")).map(([,Q])=>Q).join(" ").trim()}fillThread(g){g.replaceChildren();let I=null;for(let Q of this.transcripts){if(Q.toolUsed)continue;let i=document.createElement("div");if(i.className=`tw-msg ${Q.role==="user"?"tw-user":"tw-assistant"}`,I===Q.role&&i.classList.add("tw-run"),I=Q.role,Q.role==="user")i.textContent=Q.text;else{if(!i.classList.contains("tw-run")&&this.speakerName()){let o=document.createElement("div");o.className="tw-msg-label",o.textContent=this.speakerName(),i.appendChild(o)}let E=document.createElement("div");E.className="tw-md",E.appendChild(QE(Q.text)),i.appendChild(E)}g.appendChild(i)}let B=this.streamingReply();if(B){let Q=document.createElement("div");if(Q.className="tw-msg tw-assistant tw-streaming",I==="assistant")Q.classList.add("tw-run");else if(this.speakerName()){let E=document.createElement("div");E.className="tw-msg-label",E.textContent=this.speakerName(),Q.appendChild(E)}let i=document.createElement("div");i.className="tw-md",i.appendChild(QE(B)),Q.appendChild(i),g.appendChild(Q)}else if(this.isAwaitingReply()){let Q=document.createElement("div");Q.className="tw-msg tw-assistant tw-typing",Q.setAttribute("aria-label",this.config.copy.typing),Q.innerHTML="<span></span><span></span><span></span>",g.appendChild(Q)}requestAnimationFrame(()=>{g.scrollTop=g.scrollHeight})}isAwaitingReply(){if(this.state==="connecting"||this.pendingMessage)return!0;if(this.state!=="live")return!1;let g=[...this.transcripts].reverse().find(I=>!I.toolUsed);return(g==null?void 0:g.role)==="user"}updateThread(){if(!this.open)return!1;let g=this.root.querySelector(".tw-chat");if(!g)return!1;this.fillThread(g);let I=this.root.querySelector(".tw-suggestions"),B=this.renderSuggestions();I&&!B&&I.remove();let Q=this.root.querySelector(".tw-status");return Q&&(Q.textContent=this.statusText()),!0}renderTranscript(){let g=document.createElement("div");return g.className="tw-chat",g.setAttribute("role","log"),g.setAttribute("aria-live","polite"),this.fillThread(g),g}};function P0(C,A){let g=C.message||"";return/Origin not allowed/i.test(g)?A.errorNotEnabled:/Public access/i.test(g)?A.errorUnavailable:/Too many/i.test(g)?A.errorTooMany:/Insufficient funds/i.test(g)?A.errorUnavailable:A.errorGeneric}var O0="#0062e9";function _0(C){let A=/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(C.trim());if(!A)return"#ffffff";let g=A[1].length===3?A[1].split("").map(E=>E+E).join(""):A[1],I=E=>{let o=parseInt(g.slice(E,E+2),16)/255;return o<=.03928?o/12.92:((o+.055)/1.055)**2.4},B=.2126*I(0)+.7152*I(2)+.0722*I(4),Q=1.05/(B+.05),i=(B+.05)/.06;return Q>=i?"#ffffff":"#16181d"}function $0(C){let A=C.trim().split(/\s+/).filter(I=>/[a-z0-9]/i.test(I));return A.length?(A.length===1?A[0].slice(0,1):A[0][0]+A[1][0]).toUpperCase():""}var og=C=>`<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${C}</svg>`,MA={chat:og('<path d="M20 12.5a7.5 7.5 0 0 1-11.2 6.5L4 20l1.1-4.3A7.5 7.5 0 1 1 20 12.5Z"/>'),phone:og('<path d="M5 4h3l1.6 4-2 1.3a11 11 0 0 0 5.1 5.1l1.3-2 4 1.6v3a2 2 0 0 1-2.2 2A16 16 0 0 1 3 6.2 2 2 0 0 1 5 4Z"/>'),hangup:og('<path d="M3.5 13.5c4.7-4 12.3-4 17 0l-1.6 2.6-3.4-1.2v-2.5a10 10 0 0 0-7 0v2.5l-3.4 1.2Z"/>'),mic:og('<rect x="9" y="3" width="6" height="11" rx="3"/><path d="M5.5 11a6.5 6.5 0 0 0 13 0M12 17.5V21"/>'),micOff:og('<path d="M15 10V6a3 3 0 0 0-5.7-1.3M9 9v2a3 3 0 0 0 4.6 2.5M5.5 11a6.5 6.5 0 0 0 10.4 5.2M18.5 11a6.4 6.4 0 0 1-.6 2.6M12 17.5V21M4 4l16 16"/>'),send:og('<path d="M12 19V5M5.5 11.5 12 5l6.5 6.5"/>'),minimize:og('<path d="m6 9 6 6 6-6"/>'),thumbUp:og('<path d="M7 11v9H4v-9h3Zm0 0 4-7a2 2 0 0 1 2 2v3h5a2 2 0 0 1 2 2.3l-1.2 6A2 2 0 0 1 16.8 19H7"/>'),thumbDown:og('<path d="M17 13V4h3v9h-3Zm0 0-4 7a2 2 0 0 1-2-2v-3H6a2 2 0 0 1-2-2.3l1.2-6A2 2 0 0 1 7.2 5H17"/>'),keyboard:og('<rect x="3" y="6" width="18" height="12" rx="2"/><path d="M7 10h.01M11 10h.01M15 10h.01M7 14h10"/>'),close:og('<path d="M6 6l12 12M18 6 6 18"/>'),spinner:og('<path d="M12 3a9 9 0 1 0 9 9" class="tw-spin"/>')};var EE="trillet-widget";function iE(C=EE){typeof customElements!="undefined"&&(customElements.get(C)||customElements.define(C,qI))}iE();var AK={register:iE,TrilletWidgetElement:qI,tag:EE};typeof window!="undefined"&&(window.TrilletWidget=AK);return ah(gK);})();
|
|
3990
3992
|
//# sourceMappingURL=widget.umd.js.map
|