claudius-chat-widget 1.17.1 → 1.18.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/claudius.cjs CHANGED
@@ -1,18 +1,18 @@
1
- "use strict";var at=Object.defineProperty;var it=(e,t,n)=>t in e?at(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var le=(e,t,n)=>it(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("react/jsx-runtime"),c=require("react");class G extends Error{constructor(t,n,r,s){super(t),this.status=n,this.code=r,this.retryAfter=s,this.name="ChatApiError"}}class ve extends Error{constructor(){super("Request debounced"),this.name="DebounceError"}}const ct=3e4;function lt(e,t){const n=atob(e),r=new Uint8Array(n.length);for(let s=0;s<n.length;s++)r[s]=n.charCodeAt(s);return new Blob([r],{type:t})}class Ve{constructor(t,n){le(this,"baseUrl");le(this,"maxRetries");le(this,"debounceMs");le(this,"timeoutMs");le(this,"lastSendTime",0);this.baseUrl=t,this.maxRetries=(n==null?void 0:n.maxRetries)??2,this.debounceMs=(n==null?void 0:n.debounceMs)??300,this.timeoutMs=(n==null?void 0:n.timeoutMs)??ct}async sendMessage(t){if(this.debounceMs>0&&Date.now()-this.lastSendTime<this.debounceMs)throw new ve;this.lastSendTime=Date.now();let n;for(let r=0;r<=this.maxRetries;r++)try{const s=await this.fetchWithTimeout(t);if(s.ok)return await s.json();const o=await s.json().catch(()=>({})),i=s.headers.get("Retry-After"),l=i?Number(i):void 0;if(n=new G(o.error??`Request failed with status ${s.status}`,s.status,o.code,l),!this.isRetryable(s.status))throw n;if(r<this.maxRetries){const u=this.getRetryDelay(s,r);await this.delay(u)}}catch(s){if(s instanceof G){if(!this.isRetryable(s.status,s.code))throw s;if(n=s,r<this.maxRetries){const o=this.getRetryDelay(null,r);await this.delay(o)}}else if(n=new G("Failed to connect. Please try again.",0,"NETWORK_ERROR"),r<this.maxRetries){const o=this.getRetryDelay(null,r);await this.delay(o)}}throw n}buildRequest(t){if(!t.some(o=>{var i;return(i=o.attachments)==null?void 0:i.some(l=>!!l.data)}))return{headers:{"Content-Type":"application/json"},body:JSON.stringify({messages:t})};const r=new FormData,s=t.map(o=>o.attachments?{...o,attachments:o.attachments.map(i=>{const l={...i};return delete l.data,l})}:o);r.append("payload",JSON.stringify({messages:s}));for(const o of t)for(const i of o.attachments??[])i.data&&r.append(i.id,lt(i.data,i.mediaType),i.name);return{body:r}}async streamMessage(t,n={}){var s;if(typeof ReadableStream>"u")return this.sendMessage(t);if(this.debounceMs>0&&Date.now()-this.lastSendTime<this.debounceMs)throw new ve;this.lastSendTime=Date.now();let r;for(let o=0;o<=this.maxRetries;o++){let i;try{i=await this.fetchStream(t,n.signal)}catch(u){if((s=n.signal)!=null&&s.aborted)return{reply:"",aborted:!0};if(r=u instanceof G?u:new G("Failed to connect. Please try again.",0,"NETWORK_ERROR"),!this.isRetryable(r.status,r.code))throw r;o<this.maxRetries&&await this.delay(this.getRetryDelay(null,o));continue}if(i.status===404||i.status===405)return this.lastSendTime=0,this.sendMessage(t);if(!i.ok){const u=await i.json().catch(()=>({})),d=i.headers.get("Retry-After");if(r=new G(u.error??`Request failed with status ${i.status}`,i.status,u.code,d?Number(d):void 0),!this.isRetryable(i.status))throw r;o<this.maxRetries&&await this.delay(this.getRetryDelay(i,o));continue}if(!(i.headers.get("Content-Type")??"").includes("text/event-stream"))try{return await i.json()}catch{return this.lastSendTime=0,this.sendMessage(t)}return i.body?this.readSseStream(i.body,n):(this.lastSendTime=0,this.sendMessage(t))}throw r}async readSseStream(t,n){var f,w,S,x,h,p,j;const r=t.getReader(),s=new TextDecoder;let o="",i="";const l=[];let u;const d=()=>{r.cancel().catch(()=>{})};(f=n.signal)==null||f.addEventListener("abort",d,{once:!0});try{for(;;){let b;try{b=await r.read()}catch(y){if((w=n.signal)!=null&&w.aborted)break;throw y}if((S=n.signal)!=null&&S.aborted||b.done)break;o+=s.decode(b.value,{stream:!0});let E;for(;(E=o.indexOf(`
1
+ "use strict";var lt=Object.defineProperty;var dt=(e,t,n)=>t in e?lt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var le=(e,t,n)=>dt(e,typeof t!="symbol"?t+"":t,n);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("react/jsx-runtime"),u=require("react");class V extends Error{constructor(t,n,r,s){super(t),this.status=n,this.code=r,this.retryAfter=s,this.name="ChatApiError"}}class je extends Error{constructor(){super("Request debounced"),this.name="DebounceError"}}const ft=3e4;function ht(e,t){const n=atob(e),r=new Uint8Array(n.length);for(let s=0;s<n.length;s++)r[s]=n.charCodeAt(s);return new Blob([r],{type:t})}class Ve{constructor(t,n){le(this,"baseUrl");le(this,"maxRetries");le(this,"debounceMs");le(this,"timeoutMs");le(this,"citations");le(this,"lastSendTime",0);this.baseUrl=t,this.maxRetries=(n==null?void 0:n.maxRetries)??2,this.debounceMs=(n==null?void 0:n.debounceMs)??300,this.timeoutMs=(n==null?void 0:n.timeoutMs)??ft,this.citations=(n==null?void 0:n.citations)??!1}async sendMessage(t){if(this.debounceMs>0&&Date.now()-this.lastSendTime<this.debounceMs)throw new je;this.lastSendTime=Date.now();let n;for(let r=0;r<=this.maxRetries;r++)try{const s=await this.fetchWithTimeout(t);if(s.ok)return await s.json();const a=await s.json().catch(()=>({})),i=s.headers.get("Retry-After"),c=i?Number(i):void 0;if(n=new V(a.error??`Request failed with status ${s.status}`,s.status,a.code,c),!this.isRetryable(s.status))throw n;if(r<this.maxRetries){const l=this.getRetryDelay(s,r);await this.delay(l)}}catch(s){if(s instanceof V){if(!this.isRetryable(s.status,s.code))throw s;if(n=s,r<this.maxRetries){const a=this.getRetryDelay(null,r);await this.delay(a)}}else if(n=new V("Failed to connect. Please try again.",0,"NETWORK_ERROR"),r<this.maxRetries){const a=this.getRetryDelay(null,r);await this.delay(a)}}throw n}buildRequest(t){const n=t.some(i=>{var c;return(c=i.attachments)==null?void 0:c.some(l=>!!l.data)}),r=this.citations?{citations:!0}:{};if(!n)return{headers:{"Content-Type":"application/json"},body:JSON.stringify({messages:t,...r})};const s=new FormData,a=t.map(i=>i.attachments?{...i,attachments:i.attachments.map(c=>{const l={...c};return delete l.data,l})}:i);s.append("payload",JSON.stringify({messages:a,...r}));for(const i of t)for(const c of i.attachments??[])c.data&&s.append(c.id,ht(c.data,c.mediaType),c.name);return{body:s}}async streamMessage(t,n={}){var s;if(typeof ReadableStream>"u")return this.sendMessage(t);if(this.debounceMs>0&&Date.now()-this.lastSendTime<this.debounceMs)throw new je;this.lastSendTime=Date.now();let r;for(let a=0;a<=this.maxRetries;a++){let i;try{i=await this.fetchStream(t,n.signal)}catch(l){if((s=n.signal)!=null&&s.aborted)return{reply:"",aborted:!0};if(r=l instanceof V?l:new V("Failed to connect. Please try again.",0,"NETWORK_ERROR"),!this.isRetryable(r.status,r.code))throw r;a<this.maxRetries&&await this.delay(this.getRetryDelay(null,a));continue}if(i.status===404||i.status===405)return this.lastSendTime=0,this.sendMessage(t);if(!i.ok){const l=await i.json().catch(()=>({})),d=i.headers.get("Retry-After");if(r=new V(l.error??`Request failed with status ${i.status}`,i.status,l.code,d?Number(d):void 0),!this.isRetryable(i.status))throw r;a<this.maxRetries&&await this.delay(this.getRetryDelay(i,a));continue}if(!(i.headers.get("Content-Type")??"").includes("text/event-stream"))try{return await i.json()}catch{return this.lastSendTime=0,this.sendMessage(t)}return i.body?this.readSseStream(i.body,n):(this.lastSendTime=0,this.sendMessage(t))}throw r}async readSseStream(t,n){var j,R,g,p,f,T,x,w;const r=t.getReader(),s=new TextDecoder;let a="",i="";const c=[];let l,d;const h=()=>{r.cancel().catch(()=>{})};(j=n.signal)==null||j.addEventListener("abort",h,{once:!0});try{for(;;){let b;try{b=await r.read()}catch(N){if((R=n.signal)!=null&&R.aborted)break;throw N}if((g=n.signal)!=null&&g.aborted||b.done)break;a+=s.decode(b.value,{stream:!0});let y;for(;(y=a.indexOf(`
2
2
 
3
- `))!==-1;){const y=o.slice(0,E);o=o.slice(E+2);const v=ut(y);if(v){if(v.event==="chunk"){const k=typeof v.data.text=="string"?v.data.text:"";k&&(i+=k,(x=n.onChunk)==null||x.call(n,k,i))}else if(v.event==="tool"){if(typeof v.data.name=="string"){const k=v.data;l.push(k),(h=n.onToolUse)==null||h.call(n,k,l)}}else if(v.event==="done"){const k=Array.isArray(v.data.toolUses)?v.data.toolUses:l;u={reply:typeof v.data.reply=="string"?v.data.reply:i,sources:v.data.sources,...k.length>0?{toolUses:k}:{},...Array.isArray(v.data.attachments)?{attachments:v.data.attachments}:{}}}else if(v.event==="error")throw new G(typeof v.data.error=="string"?v.data.error:"Something went wrong. Please try again.",0,"STREAM_ERROR")}}}}finally{(p=n.signal)==null||p.removeEventListener("abort",d),r.releaseLock()}if((j=n.signal)!=null&&j.aborted)return{reply:i,aborted:!0,...l.length>0?{toolUses:l}:{}};if(u)return u;throw new G("Connection interrupted. Please try again.",0,"STREAM_ERROR")}async fetchStream(t,n){const r=new AbortController,s=()=>r.abort();n==null||n.addEventListener("abort",s,{once:!0});let o=!1;const i=this.timeoutMs>0?setTimeout(()=>{o=!0,r.abort()},this.timeoutMs):void 0,{headers:l,body:u}=this.buildRequest(t);try{return await fetch(`${this.baseUrl}/api/chat/stream`,{method:"POST",headers:l,body:u,signal:r.signal})}catch(d){throw o?new G("Request timed out. Please try again.",0,"TIMEOUT"):d}finally{i!==void 0&&clearTimeout(i),n==null||n.removeEventListener("abort",s)}}async fetchWithTimeout(t){const{headers:n,body:r}=this.buildRequest(t);if(this.timeoutMs<=0)return fetch(`${this.baseUrl}/api/chat`,{method:"POST",headers:n,body:r});const s=new AbortController,o=setTimeout(()=>s.abort(),this.timeoutMs);try{return await fetch(`${this.baseUrl}/api/chat`,{method:"POST",headers:n,body:r,signal:s.signal})}catch(i){throw s.signal.aborted?new G("Request timed out. Please try again.",0,"TIMEOUT"):i}finally{clearTimeout(o)}}isRetryable(t,n){return n==="TIMEOUT"||n==="NETWORK_ERROR"?!0:t===429||t===503}getRetryDelay(t,n){if(t&&t.status===429){const r=t.headers.get("Retry-After");if(r){const s=Number(r);return Math.min(s*1e3,6e4)}}return n===0?1e3:3e3}delay(t){return new Promise(n=>setTimeout(n,t))}}function ut(e){let t="message";const n=[];for(const r of e.split(`
3
+ `))!==-1;){const N=a.slice(0,y);a=a.slice(y+2);const S=pt(N);if(S){if(S.event==="chunk"){const E=typeof S.data.text=="string"?S.data.text:"";E&&(i+=E,(p=n.onChunk)==null||p.call(n,E,i))}else if(S.event==="tool"){if(typeof S.data.name=="string"){const E=S.data;c.push(E),(f=n.onToolUse)==null||f.call(n,E,c)}}else if(S.event==="sources")Array.isArray(S.data.sources)&&(l=S.data.sources,(T=n.onSources)==null||T.call(n,l));else if(S.event==="done"){const E=Array.isArray(S.data.toolUses)?S.data.toolUses:c;d={reply:typeof S.data.reply=="string"?S.data.reply:i,sources:Array.isArray(S.data.sources)?S.data.sources:l,...E.length>0?{toolUses:E}:{},...Array.isArray(S.data.attachments)?{attachments:S.data.attachments}:{}}}else if(S.event==="error")throw new V(typeof S.data.error=="string"?S.data.error:"Something went wrong. Please try again.",0,"STREAM_ERROR")}}}}finally{(x=n.signal)==null||x.removeEventListener("abort",h),r.releaseLock()}if((w=n.signal)!=null&&w.aborted)return{reply:i,aborted:!0,...c.length>0?{toolUses:c}:{},...l?{sources:l}:{}};if(d)return d;throw new V("Connection interrupted. Please try again.",0,"STREAM_ERROR")}async fetchStream(t,n){const r=new AbortController,s=()=>r.abort();n==null||n.addEventListener("abort",s,{once:!0});let a=!1;const i=this.timeoutMs>0?setTimeout(()=>{a=!0,r.abort()},this.timeoutMs):void 0,{headers:c,body:l}=this.buildRequest(t);try{return await fetch(`${this.baseUrl}/api/chat/stream`,{method:"POST",headers:c,body:l,signal:r.signal})}catch(d){throw a?new V("Request timed out. Please try again.",0,"TIMEOUT"):d}finally{i!==void 0&&clearTimeout(i),n==null||n.removeEventListener("abort",s)}}async fetchWithTimeout(t){const{headers:n,body:r}=this.buildRequest(t);if(this.timeoutMs<=0)return fetch(`${this.baseUrl}/api/chat`,{method:"POST",headers:n,body:r});const s=new AbortController,a=setTimeout(()=>s.abort(),this.timeoutMs);try{return await fetch(`${this.baseUrl}/api/chat`,{method:"POST",headers:n,body:r,signal:s.signal})}catch(i){throw s.signal.aborted?new V("Request timed out. Please try again.",0,"TIMEOUT"):i}finally{clearTimeout(a)}}isRetryable(t,n){return n==="TIMEOUT"||n==="NETWORK_ERROR"?!0:t===429||t===503}getRetryDelay(t,n){if(t&&t.status===429){const r=t.headers.get("Retry-After");if(r){const s=Number(r);return Math.min(s*1e3,6e4)}}return n===0?1e3:3e3}delay(t){return new Promise(n=>setTimeout(n,t))}}function pt(e){let t="message";const n=[];for(const r of e.split(`
4
4
  `))r.startsWith("event:")?t=r.slice(6).trim():r.startsWith("data:")&&n.push(r.slice(5).trimStart());if(n.length===0)return null;try{const r=JSON.parse(n.join(`
5
- `));return typeof r!="object"||r===null?null:{event:t,data:r}}catch{return null}}function Ke(e){return typeof e=="string"?{content:e}:e}function Te(e,t,n){console.error(`[claudius] plugin "${e.name}" failed in ${t}:`,n)}async function dt(e,t,n){let r=t;for(const s of e){if(!s.onBeforeSend)continue;let o=null;const i={...n,respondWith(l){o={type:"respond",message:r,reply:Ke(l)}},abort(l){o={type:"abort",reason:l}}};try{const l=await s.onBeforeSend(r,i);if(o)return o;l&&(r=l)}catch(l){Te(s,"onBeforeSend",l)}}return{type:"send",message:r}}async function ft(e,t,n){let r=t;for(const s of e)if(s.onAfterReceive)try{const o=await s.onAfterReceive(r,n);o&&(r=o)}catch(o){Te(s,"onAfterReceive",o)}return r}async function ht(e,t,n){for(const r of e){if(!r.onError)continue;let s=null;const o={...n,respondWith(i){s=Ke(i)}};try{if(await r.onError(t,o),s)return s}catch(i){Te(r,"onError",i)}}return null}const ge={maxSizeBytes:5*1024*1024,maxCount:5,allowedTypes:["image/jpeg","image/png","image/gif","image/webp","application/pdf"]};function pt(e){return e?e===!0?ge:{maxSizeBytes:e.maxSizeBytes??ge.maxSizeBytes,maxCount:e.maxCount??ge.maxCount,allowedTypes:(e.allowedTypes??ge.allowedTypes).map(t=>t.trim().toLowerCase()).filter(Boolean)}:null}function je(e){if(!Number.isFinite(e)||e<0)return"0 B";if(e<1024)return`${e} B`;const t=e/1024;if(t<1024)return`${Math.round(t)} KB`;const n=t/1024;return`${Number.isInteger(n)?n:n.toFixed(1)} MB`}const mt={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",pdf:"application/pdf"};function qe(e){var r;const t=(e.type||"").trim().toLowerCase();if(t)return t;const n=((r=e.name.split(".").pop())==null?void 0:r.toLowerCase())??"";return mt[n]??""}function gt(e){return e.startsWith("image/")}function xt(e){if(gt(e.mediaType)){if(e.url)try{const t=new URL(e.url);if(t.protocol==="http:"||t.protocol==="https:")return e.url}catch{}if(e.data)return`data:${e.mediaType};base64,${e.data}`}}function bt(e,t,n){const r=[],s=[];let o=Math.max(0,n.maxCount-t);for(const i of e){const l=qe(i);!l||!n.allowedTypes.includes(l)?s.push({file:i,reason:"type"}):i.size>n.maxSizeBytes||i.size===0?s.push({file:i,reason:"size"}):o<=0?s.push({file:i,reason:"count"}):(r.push(i),o-=1)}return{accepted:r,rejected:s}}function yt(e){return new Promise((t,n)=>{const r=new FileReader;r.onerror=()=>n(r.error??new Error("Failed to read file")),r.onload=()=>{const s=String(r.result??""),o=s.indexOf(",");t(o>=0?s.slice(o+1):s)},r.readAsDataURL(e)})}let Me=0;function wt(){return Me+=1,`att-${Date.now().toString(36)}-${Me}`}async function vt(e){const t=await yt(e);return{id:wt(),name:e.name||"attachment",mediaType:qe(e),size:e.size,data:t}}function Ye(e){return e.map(t=>{var n;return(n=t.attachments)!=null&&n.some(r=>r.data)?{...t,attachments:t.attachments.map(r=>{if(!r.data)return r;const s={...r};return delete s.data,s})}:t})}function jt(e,t){if(!t||t.length===0)return e;const n=new Map(t.map(r=>[r.id,r]));return e.map(r=>{var s;return(s=r.attachments)!=null&&s.some(o=>n.has(o.id))?{...r,attachments:r.attachments.map(o=>{const i=n.get(o.id);if(!i)return o;const l={...o,key:i.key,url:i.url,expiresAt:i.expiresAt};return delete l.data,l})}:r})}const Rt=200,Et="claudius:messages",fe=()=>new Date().toISOString();function St(e,t){let n;try{n=new URL(t).host}catch{n=t}return`${e}:${n}`}function Se(){try{return typeof sessionStorage<"u"?sessionStorage:null}catch{return null}}function Tt(e){const t=Se();if(!t)return[];try{const n=t.getItem(e);if(!n)return[];const r=JSON.parse(n);return Array.isArray(r)?r:[]}catch{return[]}}function kt({apiUrl:e,persistMessages:t=!0,storageKeyPrefix:n=Et,timeoutMs:r,translations:s,plugins:o,streaming:i=!0}){const l=c.useMemo(()=>new Ve(e,{debounceMs:0,timeoutMs:r}),[e,r]),u=St(n,e),d=t?Tt(u):[],[f,w]=c.useState(d),[S,x]=c.useState(!1),[h,p]=c.useState(!1),[j,b]=c.useState(null),[E,y]=c.useState(null),[v,k]=c.useState(!1),L=c.useRef(d.length),C=c.useRef(!1),R=c.useRef(d),P=c.useRef(null),N=c.useRef(o??[]);N.current=o??[];const $=c.useCallback(m=>{if(!t)return;const I=Se();if(I)try{const O=Ye(m.slice(-Rt));I.setItem(u,JSON.stringify(O))}catch{}},[t,u]),V=()=>(L.current+=1,`msg-${L.current}`),F=c.useCallback((m,I)=>{if(!s)return I??"Something went wrong. Please try again.";switch(m){case"TIMEOUT":return s.errorTimeout;case"NETWORK_ERROR":return s.errorConnection;case"RATE_LIMITED":return I!=null&&I.includes("minute")?s.errorRateLimitMinute:s.errorRateLimitHour;case"ATTACHMENT_QUOTA_EXCEEDED":return s.errorAttachmentQuota;case"ATTACHMENTS_DISABLED":case"ATTACHMENT_INVALID":case"ATTACHMENT_TOO_LARGE":return s.errorAttachmentRejected;case"VALIDATION_ERROR":case"CONFIG_ERROR":case"SERVICE_ERROR":case"UNKNOWN_ERROR":default:return I??s.errorGeneric}},[s]),K=c.useCallback(m=>!(m instanceof G)||m.code==="TIMEOUT"||m.code==="NETWORK_ERROR"||m.code==="RATE_LIMITED"||m.code==="SERVICE_ERROR"||m.code==="UNKNOWN_ERROR"||m.status>=500||m.status===0,[]),U=c.useCallback(async m=>{var Q,_,B;x(!0),C.current=!0,y(null),k(!1);const I=i&&typeof l.streamMessage=="function";let O=null;const Z=T=>{if(O===null){O=V(),b(O);const A=[...R.current,{id:O,role:"assistant",content:"",createdAt:fe(),...T}];R.current=A,w(A)}else{const A=O,M=R.current.map(z=>z.id===A?{...z,...T}:z);R.current=M,w(M)}},J=()=>{if(O===null)return;const T=O,A=R.current.filter(M=>M.id!==T);R.current=A,w(A)};try{let T,A,M,z,q=!1;if(I){const H=new AbortController;P.current=H,p(!0);const ee=await l.streamMessage(m,{signal:H.signal,onChunk:(ie,ae)=>Z({content:ae}),onToolUse:(ie,ae)=>Z({toolUses:[...ae]})});T=ee.reply,A=ee.sources,M=ee.toolUses,z=ee.attachments,q=ee.aborted??!1}else{const H=await l.sendMessage(m);T=H.reply,A=H.sources,M=H.toolUses,z=H.attachments}if(q&&!T){J();return}const se=((Q=R.current.find(H=>H.id===O))==null?void 0:Q.createdAt)??fe();let W={id:O??V(),role:"assistant",content:T,createdAt:se,sources:A,toolUses:M};N.current.length>0&&!q&&(W=await ft(N.current,W,{messages:m,apiUrl:e}),W.createdAt||(W={...W,createdAt:se}));const de=O!==null?R.current.map(H=>H.id===W.id?W:H):[...m,W],oe=jt(de,z);R.current=oe,w(oe),$(oe)}catch(T){if(T instanceof ve)return;if(T instanceof G&&((_=T.code)!=null&&_.startsWith("ATTACHMENT"))&&m.length>0){const A=m[m.length-1];if(A.role==="user"&&((B=A.attachments)!=null&&B.length)){const M=m.slice(0,-1);R.current=M,w(M),$(M)}}if(O!==null){$(R.current),T instanceof G?y(F(T.code,T.message)):y((s==null?void 0:s.errorConnection)??"Failed to connect. Please try again."),k(!1);return}if(N.current.length>0){const A=T instanceof Error?T:new Error(String(T)),M=await ht(N.current,A,{messages:m,apiUrl:e});if(M){const z={id:V(),role:"assistant",content:M.content,createdAt:fe(),sources:M.sources},q=[...m,z];R.current=q,w(q),$(q),y(null),k(!1);return}}T instanceof G?y(F(T.code,T.message)):y((s==null?void 0:s.errorConnection)??"Failed to connect. Please try again."),k(K(T))}finally{x(!1),C.current=!1,p(!1),b(null),P.current=null}},[e,l,F,K,$,i,s]),te=c.useCallback(()=>{var m;(m=P.current)==null||m.abort()},[]),ne=c.useCallback(async(m,I)=>{const O=m.trim(),Z=(I==null?void 0:I.filter(B=>B&&B.id))??[];if(!O&&Z.length===0||C.current)return;const J={id:V(),role:"user",content:O,createdAt:fe(),...Z.length>0?{attachments:Z}:{}};let Q=J;if(N.current.length>0){const B=await dt(N.current,J,{messages:R.current,apiUrl:e});if(B.type==="abort")return;const T=A=>A.createdAt?A:{...A,createdAt:J.createdAt};if(B.type==="respond"){const A={id:V(),role:"assistant",content:B.reply.content,createdAt:fe(),sources:B.reply.sources},M=[...R.current,T(B.message),A];R.current=M,w(M),$(M),y(null),k(!1);return}Q=T(B.message)}const _=[...R.current,Q];R.current=_,w(_),$(_),await U(_)},[e,$,U]),re=c.useCallback(async()=>{if(C.current)return;const m=R.current[R.current.length-1];!m||m.role!=="user"||await U(R.current)},[U]),X=c.useCallback(()=>{if(R.current=[],w([]),y(null),k(!1),t){const m=Se();if(!m)return;try{m.removeItem(u)}catch{}}},[t,u]);return{messages:f,isLoading:S,isStreaming:h,streamingMessageId:j,error:E,canRetry:v,sendMessage:ne,stop:te,retry:re,clearMessages:X}}function At(e){const[t,n]=c.useState(()=>typeof window>"u"?!1:window.matchMedia(e).matches);return c.useEffect(()=>{const r=window.matchMedia(e);n(r.matches);const s=o=>n(o.matches);return r.addEventListener("change",s),()=>r.removeEventListener("change",s)},[e]),t}function be(e,t){return e instanceof RegExp?e.test(t):t.toLowerCase().includes(e.toLowerCase())}function Ct(){const e=document.documentElement,t=document.body,n=e.scrollTop||t.scrollTop||0,r=Math.max(e.scrollHeight,t.scrollHeight),s=e.clientHeight||window.innerHeight,o=r-s;return o<=0?100:n/o*100}function Mt({triggers:e,enabled:t,onOpen:n,onGreeting:r}){c.useEffect(()=>{if(!t||!e||e.length===0)return;const s=new Set,o=[],i=typeof window<"u"?window.location.href:"",l=(u,d)=>{s.has(u)||(s.add(u),d==="open"?n():r(d.greeting))};return e.forEach((u,d)=>{switch(u.on){case"url":{be(u.pattern,i)&&l(d,u.action);break}case"time":{if(u.matchUrl&&!be(u.matchUrl,i))return;const f=window.setTimeout(()=>l(d,u.action),Math.max(0,u.seconds*1e3));o.push(()=>window.clearTimeout(f));break}case"scroll":{if(u.matchUrl&&!be(u.matchUrl,i))return;const f=()=>{Ct()>=u.percent&&l(d,u.action)};f(),window.addEventListener("scroll",f,{passive:!0}),o.push(()=>window.removeEventListener("scroll",f));break}case"exit-intent":{if(u.matchUrl&&!be(u.matchUrl,i))return;const f=w=>{w.clientY<=0&&l(d,u.action)};document.addEventListener("mouseleave",f),o.push(()=>document.removeEventListener("mouseleave",f));break}}}),()=>{o.forEach(u=>u())}},[e,t,n,r])}const Nt={"bottom-right":"bottom-6 right-6","bottom-left":"bottom-6 left-6","top-right":"top-6 right-6","top-left":"top-6 left-6"},Dt=c.forwardRef(function({isOpen:t,onClick:n,position:r="bottom-right",translations:s},o){const i=t?(s==null?void 0:s.closeChat)??"Close chat":(s==null?void 0:s.openChat)??"Open chat";return a.jsx("button",{ref:o,onClick:n,"aria-label":i,className:`fixed ${Nt[r]} z-50 flex h-14 w-14 items-center justify-center rounded-claudius-full bg-claudius-accent text-claudius-accent-text shadow-claudius-floating transition-transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-claudius-accent focus:ring-offset-2`,children:t?a.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}):a.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})})}),Lt=c.memo(function({count:t,isActive:n,onClick:r}){return a.jsxs("button",{onClick:r,"aria-label":"View sources",title:"View sources",className:`group relative flex h-7 w-7 items-center justify-center rounded-claudius-full transition-colors ${n?"bg-claudius-accent text-claudius-accent-text":"text-claudius-text-muted hover:bg-claudius-surface-muted hover:text-claudius-text"}`,children:[a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),a.jsx("polyline",{points:"14 2 14 8 20 8"}),a.jsx("line",{x1:"16",y1:"13",x2:"8",y2:"13"}),a.jsx("line",{x1:"16",y1:"17",x2:"8",y2:"17"})]}),a.jsx("span",{className:"absolute -right-1 -top-1 flex h-4 min-w-4 items-center justify-center rounded-claudius-full bg-claudius-accent px-1 text-[10px] font-bold text-claudius-accent-text",children:t})]})}),It=["http:","https:"];function Re(e){if(!e||typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const n=new URL(t);return It.includes(n.protocol)?t:null}catch{return null}}function Ot(){return a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),a.jsx("polyline",{points:"14 2 14 8 20 8"})]})}function Ne({label:e,onClick:t}){return a.jsx("button",{type:"button",onClick:t,"aria-label":e,className:"absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-claudius-full bg-claudius-text text-claudius-surface shadow-claudius-floating hover:opacity-90 focus:outline-none focus-visible:ring-2 focus-visible:ring-claudius-accent",children:a.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round","aria-hidden":"true",children:[a.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})}const Ze=c.memo(function({attachment:t,variant:n,onRemove:r,removeLabel:s}){const o=xt(t),i=n==="composer",l=`${t.name} (${je(t.size)})`,u=t.url?Re(t.url):null;if(o){const f=a.jsx("img",{src:o,alt:t.name,title:l,loading:"lazy",className:i?"h-12 w-12 rounded-claudius-sm border border-claudius-border object-cover":"max-h-48 max-w-full rounded-claudius-sm object-contain"});return a.jsxs("div",{className:"relative inline-block",children:[!i&&u?a.jsxs("a",{href:u,target:"_blank",rel:"noopener noreferrer",children:[f,a.jsxs("span",{className:"sr-only",children:[l," (opens in a new tab)"]})]}):f,r&&s&&a.jsx(Ne,{label:s,onClick:r})]})}const d=a.jsxs("span",{title:l,className:`inline-flex max-w-[220px] items-center gap-1.5 rounded-claudius-sm border px-2 py-1 text-xs ${i?"border-claudius-border bg-claudius-field text-claudius-text":"border-current/30 bg-transparent"}`,children:[a.jsx(Ot,{}),a.jsx("span",{className:"truncate",children:t.name}),a.jsx("span",{className:"shrink-0 opacity-70",children:je(t.size)})]});return a.jsxs("div",{className:"relative inline-block",children:[!i&&u?a.jsxs("a",{href:u,target:"_blank",rel:"noopener noreferrer",className:"underline-offset-2 hover:underline",children:[d,a.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]}):d,r&&s&&a.jsx(Ne,{label:s,onClick:r})]})}),De=c.forwardRef(function({label:t,onClick:n,children:r},s){return a.jsx("button",{ref:s,type:"button",onClick:n,"aria-label":t,title:t,className:"flex h-7 w-7 items-center justify-center rounded-claudius-full text-claudius-text-muted transition-colors hover:bg-claudius-surface-muted hover:text-claudius-text",children:a.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:r})})});function Pt({state:e,labels:t,onPlay:n,onPause:r,onResume:s,onStop:o}){var f;const i=c.useRef(null),l=c.useRef(null),u=!!((f=i.current)!=null&&f.contains(document.activeElement));c.useEffect(()=>{var w,S;e==="idle"&&u&&!((w=i.current)!=null&&w.contains(document.activeElement))&&((S=l.current)==null||S.focus())},[e,u]);const d=e==="idle"?{label:t.play,onClick:n}:e==="paused"?{label:t.resume,onClick:s}:{label:t.pause,onClick:r};return a.jsxs("div",{ref:i,className:"flex items-center gap-1",children:[a.jsx(De,{ref:l,...d,children:e==="idle"?a.jsxs(a.Fragment,{children:[a.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),a.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07",fill:"none"}),a.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14",fill:"none"})]}):e==="paused"?a.jsx("polygon",{points:"6 3 20 12 6 21 6 3"}):a.jsxs(a.Fragment,{children:[a.jsx("rect",{x:"6",y:"4",width:"4",height:"16",rx:"1"}),a.jsx("rect",{x:"14",y:"4",width:"4",height:"16",rx:"1"})]})}),e!=="idle"&&a.jsx(De,{label:t.stop,onClick:o,children:a.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5"})})]})}function $t(e){const t=e.lastIndexOf(`
6
- `),n=t===-1?"":e.slice(0,t+1);let r=t===-1?e:e.slice(t+1);return r=_t(r),r=Ft(r),n+r}function Ut(e){const t=[];for(let n=0;n<e.length-1;n++)e[n]==="*"&&e[n+1]==="*"&&(t.push(n),n++);return t}function Bt(e){const t=[];for(let n=0;n<e.length;n++)if(e[n]==="*"){if(e[n+1]==="*"){n++;continue}t.push(n)}return t}function _t(e){const t=Ut(e);if(t.length%2===0)return e;const n=t[t.length-1],r=e.slice(n+2);return r.trim()===""?e.slice(0,n)+r:e+"**"}function Ft(e){const t=Bt(e);if(t.length%2===0)return e;const n=t[t.length-1],r=e.slice(n+1);return r.trim()===""?e.slice(0,n)+r:e+"*"}function zt({toolUse:e,usedLabel:t,detailsLabel:n}){const[r,s]=c.useState(!1),o=e.input!==void 0||e.result!==void 0;return a.jsxs("div",{className:"text-xs text-claudius-text-muted",children:[a.jsxs("button",{type:"button",disabled:!o,onClick:()=>s(i=>!i),"aria-expanded":o?r:void 0,className:"flex items-center gap-1.5 rounded-claudius-full border border-claudius-border bg-claudius-surface px-2 py-0.5 hover:opacity-80 disabled:cursor-default disabled:hover:opacity-100",children:[a.jsx("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),a.jsxs("span",{children:[t," ",a.jsx("span",{className:"font-mono text-claudius-text",children:e.name}),e.isError&&a.jsx("span",{className:"text-claudius-error",children:" ✕"})]}),o&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"sr-only",children:n}),a.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:r?"rotate-180":void 0,children:a.jsx("polyline",{points:"6 9 12 15 18 9"})})]})]}),r&&o&&a.jsxs("div",{className:"mt-1 overflow-x-auto rounded-claudius-sm border border-claudius-border bg-claudius-field p-2 font-mono",children:[e.input!==void 0&&a.jsx("pre",{className:"whitespace-pre-wrap break-all",children:JSON.stringify(e.input,null,2)}),e.result!==void 0&&a.jsx("pre",{className:"mt-1 whitespace-pre-wrap break-all border-t border-claudius-border pt-1",children:e.result})]})]})}const Le=/(https?:\/\/[^\s)]+)/,Ie=/(\*\*[^*]+\*\*)/,Oe=/(\*[^*]+\*)/;function Ht(e,t){const n=e.match(/[.,;:!?'"]+$/),r=n?e.slice(0,-n[0].length):e,s=n?n[0]:"",o=Re(r);return o?a.jsxs(a.Fragment,{children:[a.jsxs("a",{href:o,target:"_blank",rel:"noopener noreferrer",className:"underline font-medium hover:opacity-80 text-claudius-link",children:[o.replace(/^https?:\/\//,""),a.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]},t),s]}):e}function Wt(e,t){const n=e.split(Ie),r=[];return n.forEach((s,o)=>{if(Ie.test(s)){const i=s.slice(2,-2);r.push(a.jsx("strong",{children:i},`${t}-b${o}`))}else s.split(Oe).forEach((l,u)=>{if(Oe.test(l)){const d=l.slice(1,-1);r.push(a.jsx("em",{children:d},`${t}-b${o}-i${u}`))}else l.split(Le).forEach((f,w)=>{Le.test(f)?r.push(Ht(f,`${t}-b${o}-i${u}-u${w}`)):f&&r.push(f)})})}),r}function Gt(e){const t=e.split(`
7
- `);return t.map((n,r)=>a.jsxs("span",{children:[Wt(n,`l${r}`),r<t.length-1&&a.jsx("br",{})]},r))}const Vt=c.memo(function({role:t,content:n,isStreaming:r=!1,sources:s,attachments:o,toolUses:i,toolUsedLabel:l="Used tool:",toolDetailsLabel:u="Tool details",onSourceClick:d,isSourceActive:f,speech:w}){const S=t==="user",x=!!o&&o.length>0,h=r?$t(n):n,p=S||n!==""||!(i!=null&&i.length);return a.jsxs("div",{className:`${S?"ml-auto":"mr-auto"} max-w-[85%]`,children:[p&&a.jsxs("div",{className:`rounded-claudius-bubble px-4 py-2.5 text-sm leading-relaxed font-body ${S?"bg-claudius-user-bubble text-claudius-user-bubble-text rounded-br-claudius-tail":"bg-claudius-assistant-bubble text-claudius-assistant-bubble-text rounded-bl-claudius-tail"}`,children:[x&&a.jsx("ul",{className:`flex flex-wrap gap-2 ${n?"mb-2":""}`,"aria-label":"Attachments",children:o.map(j=>a.jsx("li",{children:a.jsx(Ze,{attachment:j,variant:"message"})},j.id))}),(n!==""||!x)&&Gt(h)]}),!S&&i&&i.length>0&&a.jsx("div",{className:"mt-1 space-y-1",children:i.map((j,b)=>a.jsx(zt,{toolUse:j,usedLabel:l,detailsLabel:u},`${j.name}-${b}`))}),!S&&s&&s.length>0&&d&&a.jsx("div",{className:"mt-1",children:a.jsx(Lt,{count:s.length,isActive:f??!1,onClick:d})}),!S&&w&&a.jsx("div",{className:"mt-1",children:a.jsx(Pt,{...w})})]})}),Je={title:"Chat",subtitle:"Ask me anything",welcomeMessage:"Hi! How can I help you today?",closeChat:"Close chat",chatMessages:"Chat messages",typingIndicator:"Assistant is typing",placeholder:"Type your message...",sendMessage:"Send message",stopGenerating:"Stop generating",toolUsed:"Used tool:",toolDetails:"Tool details",typeYourMessage:"Type your message",openChat:"Open chat",dismissGreeting:"Dismiss greeting",attachFile:"Attach a file",removeAttachment:"Remove attachment",attachmentsLabel:"Attachments",dropFilesHint:"Drop files to attach",attachmentTooLarge:"{name} is too large. The maximum size is {max}.",attachmentTypeNotAllowed:"{name} is not a supported file type.",attachmentTooMany:"You can attach up to {max} files per message.",voiceInput:"Voice input",voiceInputHold:"Hold to talk",voiceListening:"Listening...",voicePermissionDenied:"Microphone access is blocked. Allow it in your browser settings to use voice input.",voiceNoSpeech:"No speech was detected. Please try again.",voiceNoMicrophone:"No microphone was found.",voiceUnavailable:"Voice input is not available right now.",readAloud:"Read aloud",pauseReading:"Pause reading",resumeReading:"Resume reading",stopReading:"Stop reading",moreOptions:"More options",copyAsMarkdown:"Copy as Markdown",downloadAsMarkdown:"Download as Markdown",downloadAsJson:"Download as JSON",copiedToClipboard:"Copied to clipboard",copyFailed:"Could not copy. Try downloading instead.",transcriptTitle:"Chat transcript",transcriptExported:"Exported {date}",transcriptUser:"User",transcriptAssistant:"Assistant",transcriptAttachments:"Attachments:",transcriptSources:"Sources:",errorGeneric:"Something went wrong. Please try again.",errorConnection:"Failed to connect. Please try again.",errorTimeout:"Request timed out. Please try again.",errorRateLimitMinute:"Too many requests. Please wait a minute.",errorRateLimitHour:"Hourly limit reached. Please try again later.",errorAttachmentRejected:"An attachment was rejected. Please remove it and try again.",errorAttachmentQuota:"Upload limit reached. Please try again later.",errorRetry:"Retry"},Ee=Je;function Kt(e){return{...Ee,...e}}function Pe(e){return e.key===" "||e.key==="Enter"}function qt({mode:e,isListening:t,disabled:n=!1,onStart:r,onStop:s,label:o}){const i=e==="hold",l=c.useRef(!1),u=()=>{n||l.current||(l.current=!0,r({held:!0}))},d=()=>{l.current&&(l.current=!1,s())},f=h=>{i&&h.detail!==0||(t?s():r({held:!1}))},w=h=>{var p,j;!i||h.button!==0||((j=(p=h.currentTarget).setPointerCapture)==null||j.call(p,h.pointerId),u())},S=h=>{!i||!Pe(h)||(h.preventDefault(),h.repeat||u())},x=h=>{!i||!Pe(h)||(h.preventDefault(),d())};return a.jsx("button",{type:"button",disabled:n,"aria-label":o,"aria-pressed":t,title:o,onClick:f,onPointerDown:w,onPointerUp:d,onPointerCancel:d,onLostPointerCapture:d,onKeyDown:S,onKeyUp:x,onBlur:d,onContextMenu:i?h=>h.preventDefault():void 0,style:i?{WebkitTouchCallout:"none"}:void 0,className:`flex h-11 w-11 shrink-0 items-center justify-center rounded-claudius-sm border transition-colors focus:outline-none focus:ring-1 focus:ring-claudius-accent disabled:opacity-50 ${t?"border-claudius-accent bg-claudius-accent text-claudius-accent-text focus:ring-2 focus:ring-offset-2 focus:ring-offset-claudius-surface":"border-claudius-border bg-claudius-field text-claudius-text-muted hover:text-claudius-text focus:border-claudius-accent"} ${i?"touch-none select-none":""}`,children:t&&!i?a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:a.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5"})}):a.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"}),a.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),a.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]})})}function Yt({active:e}){return a.jsxs("span",{"aria-hidden":"true","data-claudius-voice-level":e?"active":"idle",className:"claudius-voice-level pointer-events-none absolute right-3 top-1/2 flex h-4 -translate-y-1/2 items-center gap-0.5 text-claudius-accent",children:[a.jsx("span",{}),a.jsx("span",{}),a.jsx("span",{}),a.jsx("span",{})]})}function ye(e,t){return e.replace(/\{(\w+)\}/g,(n,r)=>r in t?String(t[r]):n)}const Zt={en:"en-US",es:"es-ES",fr:"fr-FR",de:"de-DE"},Jt=["toggle","hold"];function $e(e,t){if(!(!e||!e.includes("-")))return e.toLowerCase().split("-")[0]===t?e:void 0}function Qe(e,t){const n=t==null?void 0:t.trim();if(n)return n;const r=typeof document<"u"?$e(document.documentElement.lang,e):void 0;if(r)return r;const s=typeof navigator<"u"?$e(navigator.language,e):void 0;return s||Zt[e]}function Qt(e,t){const n=typeof e=="object"&&e!==null&&!Array.isArray(e);if(e!==!0&&!n)return null;const r=e===!0?{}:e,s={input:r.input??!0,output:r.output??!0,mode:Jt.includes(r.mode)?r.mode:"toggle",autoSubmit:r.autoSubmit??!1,lang:Qe(t,r.lang)};return s.input||s.output?s:null}function Xt(e,t,n){const r=t.trim();if(!r)return e;const s=e.trimEnd();return(s?`${s} ${r}`:r).slice(0,n)}function en(e){const t=[];let n=0;for(let r=0;r<e.length;r++){const s=e[r];(s===`
8
- `||s==="。"||s==="!"||s==="?"||(s==="."||s==="!"||s==="?")&&(r+1===e.length||/\s/.test(e[r+1])))&&(t.push(e.slice(n,r+1)),n=r+1)}return n<e.length&&t.push(e.slice(n)),t}function tn(e,t=150){const n=[];let r="";const s=()=>{const o=r.trim();o&&n.push(o),r=""};for(const o of en(e)){if((r+o).trim().length<=t){r+=o;continue}if(s(),o.trim().length<=t){r=o;continue}for(let i of o.trim().split(/\s+/)){for(r&&`${r} ${i}`.length>t&&s();i.length>t;)n.push(i.slice(0,t)),i=i.slice(t);r=r?`${r} ${i}`:i}}return s(),n}function Ue(){if(typeof window>"u")return;const e=window;return e.SpeechRecognition??e.webkitSpeechRecognition}function nn(e){switch(e){case"not-allowed":case"service-not-allowed":return"permission";case"no-speech":return"no-speech";case"audio-capture":return"no-microphone";default:return"unavailable"}}function rn(e){const[t]=c.useState(()=>Ue()!==void 0),[n,r]=c.useState(!1),[s,o]=c.useState(!1),i=c.useRef(null),l=c.useRef(!1),u=c.useRef(e);c.useEffect(()=>{u.current=e});const d=c.useCallback(x=>{x.onstart=null,x.onend=null,x.onerror=null,x.onresult=null,x.onspeechstart=null,x.onspeechend=null,i.current===x&&(i.current=null),r(!1),o(!1)},[]),f=c.useCallback(()=>{const x=i.current;x&&(d(x),x.abort())},[d]),w=c.useCallback(()=>{const x=i.current;return x?(l.current?x.stop():f(),!0):!1},[f]),S=c.useCallback(()=>{var b,E;const x=Ue();if(!x||i.current)return!1;const h=new x;h.lang=u.current.lang,h.interimResults=!0,h.continuous=!1;let p="";const j=()=>{l.current=!0};h.onstart=j,h.onspeechstart=()=>{j(),o(!0)},h.onspeechend=()=>o(!1),h.onresult=y=>{var L,C;let v="",k="";for(let R=0;R<y.results.length;R++){const P=y.results[R];P.isFinal?v+=P[0].transcript:k+=P[0].transcript}p=v,j(),o(!0),(C=(L=u.current).onTranscript)==null||C.call(L,v+k)},h.onerror=y=>{var v,k;y.error!=="aborted"&&((k=(v=u.current).onError)==null||k.call(v,nn(y.error))),d(h),h.abort()},h.onend=()=>{var y,v;d(h),(v=(y=u.current).onEnd)==null||v.call(y,p)},i.current=h,l.current=!1,r(!0);try{h.start()}catch{return d(h),(E=(b=u.current).onError)==null||E.call(b,"unavailable"),!1}return!0},[d]);return c.useEffect(()=>f,[f]),{isSupported:t,isListening:n,isSpeechDetected:s,start:S,stop:w,abort:f}}const he=2e3,sn=1800;function Be(e){var n;const t=(n=e.dataTransfer)==null?void 0:n.types;return!!t&&Array.from(t).includes("Files")}function on({onSend:e,isLoading:t,isStreaming:n=!1,onStop:r,placeholder:s,translations:o,attachments:i=null,voice:l=null,onVoiceStart:u,isReadingAloud:d=!1}){const f=o??Ee,[w,S]=c.useState(""),[x,h]=c.useState([]),[p,j]=c.useState(null),[b,E]=c.useState(!1),[y,v]=c.useState(null),k=c.useRef(null),L=c.useRef(null),C=c.useRef([]),R=c.useRef(0),P=c.useRef(""),N=c.useRef(""),$=c.useRef(!1),V=c.useRef(!1),F=c.useRef(!1),K=g=>{P.current=g,S(g)},U=w.length,te=U>=sn,ne=U>=he,re=s??f.placeholder,X=!!i&&x.length<i.maxCount,m=n&&!!r;c.useEffect(()=>{var g;t||(g=k.current)==null||g.focus()},[t]);const I=c.useCallback((g,D)=>{if(!i)return"";switch(D){case"size":return ye(f.attachmentTooLarge,{name:g,max:je(i.maxSizeBytes)});case"type":return ye(f.attachmentTypeNotAllowed,{name:g});case"count":return ye(f.attachmentTooMany,{max:i.maxCount})}},[i,f]),O=c.useCallback(async g=>{if(!i||g.length===0)return;const{accepted:D,rejected:ce}=bt(g,C.current.length,i);if(j(ce.length>0?I(ce[0].file.name,ce[0].reason):null),D.length===0)return;const ot=await Promise.all(D.map(vt));C.current=[...C.current,...ot],h(C.current)},[i,I]),Z=c.useCallback(g=>{C.current=C.current.filter(D=>D.id!==g),h(C.current),j(null)},[]),J=()=>{const g=P.current.trim(),D=C.current;!g&&D.length===0||P.current.length>=he||(D.length>0?e(g,D):e(g),K(""),C.current=[],h([]),j(null),v(null))},Q=g=>{switch(g){case"permission":return f.voicePermissionDenied;case"no-speech":return f.voiceNoSpeech;case"no-microphone":return f.voiceNoMicrophone;case"unavailable":return f.voiceUnavailable}},_=rn({lang:(l==null?void 0:l.lang)??"en-US",onTranscript:g=>K(Xt(N.current,g,he)),onEnd:g=>{const D=g.trim()!=="";if(D&&(V.current=!0),!$.current){A();return}D&&M()},onError:g=>{g==="no-speech"&&V.current||(F.current=!0,v(Q(g)))}}),B=!!(l!=null&&l.input)&&_.isSupported,T=_.isListening;c.useEffect(()=>{const g=k.current;T&&g&&(g.scrollLeft=g.scrollWidth)},[T,w]);const A=()=>{l!=null&&l.autoSubmit&&V.current&&!F.current&&J()},M=()=>{const g=P.current;_.start()&&(N.current=g)},z=({held:g})=>{v(null),$.current=g,V.current=!1,F.current=!1,u==null||u(),M()},q=()=>{const g=$.current;$.current=!1,!_.stop()&&g&&A()},se=()=>{$.current=!1,_.abort()},{abort:W}=_;c.useEffect(()=>{!t&&!d||($.current=!1,W())},[t,d,W]);const de=g=>{g.preventDefault(),se(),J()},oe=g=>{const D=g.target.value;D.length<=he&&(se(),v(null),K(D))},H=g=>{const D=Array.from(g.target.files??[]);g.target.value="",O(D)},ee=g=>{var ce;if(!i)return;const D=Array.from(((ce=g.clipboardData)==null?void 0:ce.files)??[]);D.length!==0&&(g.preventDefault(),O(D))},ie=g=>{!i||!Be(g)||(g.preventDefault(),R.current+=1,E(!0))},ae=g=>{!i||!Be(g)||g.preventDefault()},Y=()=>{i&&(R.current=Math.max(0,R.current-1),R.current===0&&E(!1))},xe=g=>{var D;i&&(g.preventDefault(),R.current=0,E(!1),O(Array.from(((D=g.dataTransfer)==null?void 0:D.files)??[])))};return a.jsxs("form",{onSubmit:de,onDragEnter:ie,onDragOver:ae,onDragLeave:Y,onDrop:xe,"data-drag-over":b||void 0,className:`relative border-t border-claudius-border bg-claudius-surface p-3 ${b?"ring-2 ring-inset ring-claudius-accent":""}`,children:[b&&a.jsx("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 z-10 flex items-center justify-center bg-claudius-surface text-sm font-medium text-claudius-accent",children:f.dropFilesHint}),i&&x.length>0&&a.jsx("ul",{"aria-label":f.attachmentsLabel,className:"mb-2 flex flex-wrap gap-3 pt-1",children:x.map(g=>a.jsx("li",{children:a.jsx(Ze,{attachment:g,variant:"composer",onRemove:()=>Z(g.id),removeLabel:`${f.removeAttachment}: ${g.name}`})},g.id))}),a.jsxs("div",{className:"flex gap-2",children:[i&&a.jsxs(a.Fragment,{children:[a.jsx("input",{ref:L,type:"file",multiple:!0,hidden:!0,tabIndex:-1,accept:i.allowedTypes.join(","),onChange:H,"aria-label":f.attachFile}),a.jsx("button",{type:"button",onClick:()=>{var g;return(g=L.current)==null?void 0:g.click()},disabled:t||!X,"aria-label":f.attachFile,title:f.attachFile,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-claudius-sm border border-claudius-border bg-claudius-field text-claudius-text-muted transition-colors hover:text-claudius-text focus:border-claudius-accent focus:outline-none focus:ring-1 focus:ring-claudius-accent disabled:opacity-50",children:a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"})})})]}),a.jsxs("div",{className:"relative min-w-0 flex-1",children:[a.jsx("input",{ref:k,type:"text",value:w,onChange:oe,onPaste:ee,placeholder:T?f.voiceListening:re,disabled:t,"aria-label":f.typeYourMessage,"aria-describedby":te?"char-count":void 0,className:`h-full w-full rounded-claudius-sm border border-claudius-border bg-claudius-field py-2 pl-3 text-sm font-body text-claudius-text placeholder:text-claudius-text-muted focus:border-claudius-accent focus:outline-none focus:ring-1 focus:ring-claudius-accent disabled:opacity-50 ${T?"pr-10":"pr-3"}`}),T&&a.jsx(Yt,{active:_.isSpeechDetected})]}),B&&l&&a.jsx(qt,{mode:l.mode,isListening:T,disabled:t,onStart:z,onStop:q,label:l.mode==="hold"?f.voiceInputHold:f.voiceInput}),m?a.jsx("button",{type:"button",onClick:r,"aria-label":f.stopGenerating,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-claudius-sm bg-claudius-accent text-claudius-accent-text transition-colors hover:opacity-90",children:a.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:a.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5"})})}):a.jsx("button",{type:"submit",disabled:t||ne,"aria-label":f.sendMessage,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-claudius-sm bg-claudius-accent text-claudius-accent-text transition-colors hover:opacity-90 disabled:opacity-50",children:a.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),a.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})})]}),(p??y)&&a.jsx("div",{role:"alert",className:"mt-1 text-xs text-claudius-error",children:p??y}),te&&a.jsxs("div",{id:"char-count",className:`mt-1 text-xs text-right ${ne?"text-claudius-error":"text-claudius-text-muted"}`,"aria-live":"polite",children:[U,"/",he]})]})}const an=["blog","page","external"],cn={blog:"Blog",page:"Page",external:"External"};function ln(e){try{return new URL(e).hostname}catch{return e}}const un=c.memo(function({sources:t,onClose:n}){const r=an.map(o=>({type:o,label:cn[o],items:t.filter(i=>i.type===o)})).filter(o=>o.items.length>0),s=t.length===1?"1 source found":`${t.length} sources found`;return a.jsxs("div",{className:"absolute inset-y-0 left-0 z-10 flex w-[280px] flex-col border-r-2 border-claudius-border bg-claudius-surface rounded-r-claudius-lg transition-transform duration-200 ease-out",children:[a.jsxs("div",{className:"flex items-center justify-between border-b border-claudius-border px-4 py-3",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"text-sm font-heading font-semibold text-claudius-text",children:"Sources"}),a.jsx("p",{className:"text-xs text-claudius-text-muted",children:s})]}),a.jsx("button",{onClick:n,"aria-label":"Close sources",className:"flex h-7 w-7 items-center justify-center rounded-claudius-full text-claudius-text-muted transition-colors hover:bg-claudius-surface-muted hover:text-claudius-text",children:a.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),a.jsx("div",{className:"flex-1 overflow-y-auto px-3 py-3 space-y-4",children:r.map(o=>a.jsxs("div",{children:[a.jsx("h4",{className:"mb-2 text-xs font-semibold uppercase tracking-wide text-claudius-text-muted",children:o.label}),a.jsx("div",{className:"space-y-2",children:o.items.map(i=>{const l=Re(i.url);return l?a.jsxs("a",{href:l,target:"_blank",rel:"noopener noreferrer",className:"block rounded-claudius-md border-2 border-claudius-border bg-claudius-surface-muted p-3 transition-colors hover:bg-claudius-border",children:[a.jsx("p",{className:"truncate text-sm font-medium text-claudius-text",children:i.title}),a.jsx("p",{className:"mt-0.5 text-xs text-claudius-text-muted",children:ln(l)})]},l):null})})]},o.type))})]})});function dn({title:e,subtitle:t,titleId:n,closeLabel:r,onClose:s,actions:o}){return a.jsxs("div",{className:"flex items-center gap-3 bg-claudius-accent px-5 py-4",children:[a.jsx("div",{"aria-hidden":"true",className:"flex h-8 w-8 items-center justify-center rounded-claudius-full bg-claudius-accent-soft text-sm font-bold text-claudius-accent-text",children:e.charAt(0).toUpperCase()}),a.jsxs("div",{className:"flex-1",children:[a.jsx("h2",{id:n,className:"text-sm font-heading font-semibold text-claudius-accent-text",children:e}),a.jsx("p",{className:"text-xs text-claudius-accent-text",children:t})]}),o,a.jsx("button",{onClick:s,"aria-label":r,className:"flex h-10 w-10 items-center justify-center rounded-claudius-full text-claudius-accent-text-muted transition-colors hover:bg-claudius-accent-soft hover:text-claudius-accent-text",children:a.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})}function fn({message:e,retryLabel:t,onRetry:n}){return a.jsxs("div",{role:"alert",className:"mx-auto flex max-w-[90%] flex-col items-center gap-2 rounded-claudius-sm bg-claudius-error-surface px-3 py-2 text-center text-xs text-claudius-error",children:[a.jsx("span",{children:e}),n&&a.jsx("button",{type:"button",onClick:n,className:"rounded-claudius-md bg-claudius-error px-3 py-1 text-xs font-semibold text-claudius-error-text transition-opacity hover:opacity-90 focus:outline-none focus-visible:ring-2 focus-visible:ring-claudius-error focus-visible:ring-offset-1",children:t})]})}function hn({label:e}){return a.jsx("div",{role:"status","aria-live":"polite","aria-label":e,className:"mr-auto flex max-w-[85%]",children:a.jsxs("div",{className:"flex gap-1 rounded-claudius-bubble rounded-bl-claudius-tail bg-claudius-assistant-bubble px-4 py-3",children:[a.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:0ms]"}),a.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:150ms]"}),a.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:300ms]"})]})})}function pn({label:e,items:t,onOpen:n}){const[r,s]=c.useState(!1),o=c.useId(),i=c.useId(),l=c.useRef(null),u=c.useRef(null),d=c.useRef([]),f=c.useRef(null),w=b=>{f.current=b,s(!0),n==null||n()},S=b=>{var E;s(!1),(E=u.current)==null||E.focus()};c.useEffect(()=>{var E;if(!r)return;f.current!==null&&((E=d.current[f.current])==null||E.focus(),f.current=null);const b=y=>{var v;(v=l.current)!=null&&v.contains(y.target)||s(!1)};return document.addEventListener("pointerdown",b),()=>document.removeEventListener("pointerdown",b)},[r]);const x=b=>{var y;const E=t.length;(y=d.current[(b+E)%E])==null||y.focus()},h=b=>{b.key==="ArrowDown"?(b.preventDefault(),w(0)):b.key==="ArrowUp"&&(b.preventDefault(),w(t.length-1))},p=b=>{const E=d.current.findIndex(y=>y===document.activeElement);switch(b.key){case"ArrowDown":b.preventDefault(),x(E+1);break;case"ArrowUp":b.preventDefault(),x(E===-1?t.length-1:E-1);break;case"Home":b.preventDefault(),x(0);break;case"End":b.preventDefault(),x(t.length-1);break;case"Escape":b.preventDefault(),b.stopPropagation(),S();break;case"Tab":b.shiftKey&&(b.preventDefault(),S());break}},j=b=>{var y;const E=b.relatedTarget;E&&((y=l.current)!=null&&y.contains(E)||s(!1))};return a.jsxs("div",{ref:l,className:"relative",children:[a.jsx("button",{ref:u,id:o,type:"button","aria-label":e,"aria-haspopup":"menu","aria-expanded":r,"aria-controls":r?i:void 0,onClick:()=>r?S():w(0),onKeyDown:h,className:"flex h-10 w-10 items-center justify-center rounded-claudius-full text-claudius-accent-text-muted transition-colors hover:bg-claudius-accent-soft hover:text-claudius-accent-text",children:a.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[a.jsx("circle",{cx:"12",cy:"5",r:"1.75"}),a.jsx("circle",{cx:"12",cy:"12",r:"1.75"}),a.jsx("circle",{cx:"12",cy:"19",r:"1.75"})]})}),r&&a.jsx("div",{id:i,role:"menu","aria-labelledby":o,tabIndex:-1,onKeyDown:p,onBlur:j,className:"absolute right-0 top-full z-20 mt-1 min-w-[12rem] rounded-claudius-md border border-claudius-border bg-claudius-surface py-1 shadow-claudius-elevated",children:t.map((b,E)=>a.jsx("button",{ref:y=>{d.current[E]=y},type:"button",role:"menuitem",tabIndex:-1,"aria-disabled":b.disabled||void 0,onClick:()=>{b.disabled||(S(),b.onSelect())},className:"flex min-h-[40px] w-full items-center whitespace-nowrap px-4 text-left text-sm text-claudius-text hover:bg-claudius-surface-muted focus:bg-claudius-surface-muted aria-disabled:cursor-default aria-disabled:opacity-50 aria-disabled:hover:bg-transparent",children:b.label},b.id))})]})}function mn(e,t,n){const[r,s]=c.useState(0),o=c.useRef(0),i=c.useRef(0),l=c.useRef(0),u=c.useRef(!1);return c.useEffect(()=>{const d=e.current;if(!n||!d)return;const f=x=>{if(d.scrollTop>0){u.current=!1;return}u.current=!0,i.current=x.touches[0].clientY,l.current=Date.now()},w=x=>{if(!u.current)return;let h=x.touches[0].clientY-i.current;h<0&&(h=h*.3),o.current=h,s(h)},S=()=>{if(!u.current)return;u.current=!1;const x=o.current,h=(Date.now()-l.current)/1e3,p=d.getBoundingClientRect().height,j=h>.05&&x>0&&x/h>500,b=x>p*.3;j||b?t():(o.current=0,s(0))};return d.addEventListener("touchstart",f,{passive:!0}),d.addEventListener("touchmove",w,{passive:!0}),d.addEventListener("touchend",S),()=>{d.removeEventListener("touchstart",f),d.removeEventListener("touchmove",w),d.removeEventListener("touchend",S)}},[e,t,n]),{offsetY:r}}const gn='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function xn(e,t){c.useEffect(()=>{const n=e.current;if(!n)return;const r=s=>{if(s.key!=="Tab")return;const o=Array.from(n.querySelectorAll(gn)).filter(d=>!d.hasAttribute("aria-hidden"));if(o.length===0)return;const i=o[0],l=o[o.length-1],u=document.activeElement;s.shiftKey&&u===i?(s.preventDefault(),l.focus()):!s.shiftKey&&u===l&&(s.preventDefault(),i.focus())};return n.addEventListener("keydown",r),()=>n.removeEventListener("keydown",r)},[e,t])}function pe(){if(!(typeof window>"u")&&!(typeof window.SpeechSynthesisUtterance>"u"))return window.speechSynthesis??void 0}function bn(e){const[t]=c.useState(()=>pe()!==void 0),[n,r]=c.useState(null),[s,o]=c.useState(!1),i=c.useRef(0),l=c.useRef(!1),u=c.useRef([]),d=c.useCallback(()=>{i.current+=1,l.current=!1,u.current=[],r(null),o(!1)},[]),f=c.useCallback(()=>{const h=u.current.length>0;d();const p=pe();!h||!p||(p.cancel(),p.paused&&p.resume())},[d]),w=c.useCallback((h,p)=>{const j=pe();if(!j)return;d(),(j.speaking||j.pending)&&j.cancel(),j.paused&&j.resume();const b=tn(p);if(b.length===0)return;const E=i.current,y=()=>i.current===E;u.current=b.map((v,k)=>{const L=new SpeechSynthesisUtterance(v);return L.lang=e,L.onerror=C=>{if(!y())return;(C.error==="interrupted"||C.error==="canceled")&&!l.current?d():f()},L.onpause=()=>{y()&&o(!0)},L.onresume=()=>{y()&&o(!1)},L.onend=()=>{y()&&(l.current&&!j.paused?f():k===b.length-1&&d())},L}),r(h);for(const v of u.current)j.speak(v)},[e,f,d]),S=c.useCallback(()=>{const h=pe();h&&(l.current=!0,h.pause(),h.paused&&o(!0))},[]),x=c.useCallback(()=>{const h=pe();h&&(l.current=!1,h.resume(),o(!1))},[]);return c.useEffect(()=>f,[f]),{isSupported:t,activeId:n,isPaused:s,speak:w,pause:S,resume:x,cancel:f}}const yn=/^([ \t]*)(`{3,}|~{3,})(.*)$/,wn=/^( {0,3})<(?![A-Za-z][A-Za-z0-9+.-]{1,31}:[^<>\s]*>|[A-Za-z0-9][^\s<>@]*@[^\s<>]+>)(?=[A-Za-z!?/])/,vn=/^(?: {4}|\t)/;function Xe(e){let t=0;for(const n of e)if(n===" ")t+=1;else if(n===" ")t+=4-t%4;else break;return t}function _e(e){let t=e.length;for(;t>0&&(e[t-1]===" "||e[t-1]===" ");)t-=1;return t===e.length?e:e.slice(0,t)}function jn(e){const t=yn.exec(e);if(!t)return null;const[,n,r,s]=t;return r[0]==="`"&&s.includes("`")?null:{indent:n,indentColumns:Xe(n),char:r[0],length:r.length}}function Rn(e,t){const n=e.trim();if(n.length<t.length)return!1;for(const r of n)if(r!==t.char)return!1;return Xe(e)<=t.indentColumns+3}function En(e){const t=e.replace(/\r\n?/g,`
5
+ `));return typeof r!="object"||r===null?null:{event:t,data:r}}catch{return null}}function Ke(e){return typeof e=="string"?{content:e}:e}function Ae(e,t,n){console.error(`[claudius] plugin "${e.name}" failed in ${t}:`,n)}async function mt(e,t,n){let r=t;for(const s of e){if(!s.onBeforeSend)continue;let a=null;const i={...n,respondWith(c){a={type:"respond",message:r,reply:Ke(c)}},abort(c){a={type:"abort",reason:c}}};try{const c=await s.onBeforeSend(r,i);if(a)return a;c&&(r=c)}catch(c){Ae(s,"onBeforeSend",c)}}return{type:"send",message:r}}async function gt(e,t,n){let r=t;for(const s of e)if(s.onAfterReceive)try{const a=await s.onAfterReceive(r,n);a&&(r=a)}catch(a){Ae(s,"onAfterReceive",a)}return r}async function xt(e,t,n){for(const r of e){if(!r.onError)continue;let s=null;const a={...n,respondWith(i){s=Ke(i)}};try{if(await r.onError(t,a),s)return s}catch(i){Ae(r,"onError",i)}}return null}const be={maxSizeBytes:5*1024*1024,maxCount:5,allowedTypes:["image/jpeg","image/png","image/gif","image/webp","application/pdf"]};function bt(e){return e?e===!0?be:{maxSizeBytes:e.maxSizeBytes??be.maxSizeBytes,maxCount:e.maxCount??be.maxCount,allowedTypes:(e.allowedTypes??be.allowedTypes).map(t=>t.trim().toLowerCase()).filter(Boolean)}:null}function Se(e){if(!Number.isFinite(e)||e<0)return"0 B";if(e<1024)return`${e} B`;const t=e/1024;if(t<1024)return`${Math.round(t)} KB`;const n=t/1024;return`${Number.isInteger(n)?n:n.toFixed(1)} MB`}const yt={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",pdf:"application/pdf"};function qe(e){var r;const t=(e.type||"").trim().toLowerCase();if(t)return t;const n=((r=e.name.split(".").pop())==null?void 0:r.toLowerCase())??"";return yt[n]??""}function wt(e){return e.startsWith("image/")}function vt(e){if(wt(e.mediaType)){if(e.url)try{const t=new URL(e.url);if(t.protocol==="http:"||t.protocol==="https:")return e.url}catch{}if(e.data)return`data:${e.mediaType};base64,${e.data}`}}function jt(e,t,n){const r=[],s=[];let a=Math.max(0,n.maxCount-t);for(const i of e){const c=qe(i);!c||!n.allowedTypes.includes(c)?s.push({file:i,reason:"type"}):i.size>n.maxSizeBytes||i.size===0?s.push({file:i,reason:"size"}):a<=0?s.push({file:i,reason:"count"}):(r.push(i),a-=1)}return{accepted:r,rejected:s}}function St(e){return new Promise((t,n)=>{const r=new FileReader;r.onerror=()=>n(r.error??new Error("Failed to read file")),r.onload=()=>{const s=String(r.result??""),a=s.indexOf(",");t(a>=0?s.slice(a+1):s)},r.readAsDataURL(e)})}let Me=0;function Rt(){return Me+=1,`att-${Date.now().toString(36)}-${Me}`}async function Tt(e){const t=await St(e);return{id:Rt(),name:e.name||"attachment",mediaType:qe(e),size:e.size,data:t}}function Ye(e){return e.map(t=>{var n;return(n=t.attachments)!=null&&n.some(r=>r.data)?{...t,attachments:t.attachments.map(r=>{if(!r.data)return r;const s={...r};return delete s.data,s})}:t})}function kt(e,t){if(!t||t.length===0)return e;const n=new Map(t.map(r=>[r.id,r]));return e.map(r=>{var s;return(s=r.attachments)!=null&&s.some(a=>n.has(a.id))?{...r,attachments:r.attachments.map(a=>{const i=n.get(a.id);if(!i)return a;const c={...a,key:i.key,url:i.url,expiresAt:i.expiresAt};return delete c.data,c})}:r})}const At=200,Et="claudius:messages",pe=()=>new Date().toISOString();function Ct(e,t){let n;try{n=new URL(t).host}catch{n=t}return`${e}:${n}`}function ke(){try{return typeof sessionStorage<"u"?sessionStorage:null}catch{return null}}function Nt(e){const t=ke();if(!t)return[];try{const n=t.getItem(e);if(!n)return[];const r=JSON.parse(n);return Array.isArray(r)?r:[]}catch{return[]}}function Mt({apiUrl:e,persistMessages:t=!0,storageKeyPrefix:n=Et,timeoutMs:r,translations:s,plugins:a,streaming:i=!0,citations:c=!1}){const l=u.useMemo(()=>new Ve(e,{debounceMs:0,timeoutMs:r,citations:c}),[e,r,c]),d=Ct(n,e),h=t?Nt(d):[],[j,R]=u.useState(h),[g,p]=u.useState(!1),[f,T]=u.useState(!1),[x,w]=u.useState(null),[b,y]=u.useState(null),[N,S]=u.useState(!1),E=u.useRef(h.length),M=u.useRef(!1),k=u.useRef(h),Q=u.useRef(null),L=u.useRef(a??[]);L.current=a??[];const F=u.useCallback(A=>{if(!t)return;const $=ke();if($)try{const I=Ye(A.slice(-At));$.setItem(d,JSON.stringify(I))}catch{}},[t,d]),Y=()=>(E.current+=1,`msg-${E.current}`),K=u.useCallback((A,$)=>{if(!s)return $??"Something went wrong. Please try again.";switch(A){case"TIMEOUT":return s.errorTimeout;case"NETWORK_ERROR":return s.errorConnection;case"RATE_LIMITED":return $!=null&&$.includes("minute")?s.errorRateLimitMinute:s.errorRateLimitHour;case"ATTACHMENT_QUOTA_EXCEEDED":return s.errorAttachmentQuota;case"ATTACHMENTS_DISABLED":case"ATTACHMENT_INVALID":case"ATTACHMENT_TOO_LARGE":return s.errorAttachmentRejected;case"VALIDATION_ERROR":case"CONFIG_ERROR":case"SERVICE_ERROR":case"UNKNOWN_ERROR":default:return $??s.errorGeneric}},[s]),q=u.useCallback(A=>!(A instanceof V)||A.code==="TIMEOUT"||A.code==="NETWORK_ERROR"||A.code==="RATE_LIMITED"||A.code==="SERVICE_ERROR"||A.code==="UNKNOWN_ERROR"||A.status>=500||A.status===0,[]),_=u.useCallback(async A=>{var P,Z,J;p(!0),M.current=!0,y(null),S(!1);const $=i&&typeof l.streamMessage=="function";let I=null,v;const H=()=>c?v:void 0,z=C=>{if(I===null){I=Y(),w(I);const U=[...k.current,{id:I,role:"assistant",content:"",createdAt:pe(),...H()?{sources:v}:{},...C}];k.current=U,R(U)}else{const U=I,O=k.current.map(G=>G.id===U?{...G,...C}:G);k.current=O,R(O)}},ee=()=>{if(I===null)return;const C=I,U=k.current.filter(O=>O.id!==C);k.current=U,R(U)};try{let C,U,O,G,te=!1;if($){const W=new AbortController;Q.current=W,T(!0);const ne=await l.streamMessage(A,{signal:W.signal,onChunk:(oe,m)=>z({content:m}),onToolUse:(oe,m)=>z({toolUses:[...m]}),onSources:oe=>{v=oe,c&&I!==null&&z({sources:oe})}});C=ne.reply,U=ne.sources??v,O=ne.toolUses,G=ne.attachments,te=ne.aborted??!1}else{const W=await l.sendMessage(A);C=W.reply,U=W.sources,O=W.toolUses,G=W.attachments}if(te&&!C){ee();return}const se=((P=k.current.find(W=>W.id===I))==null?void 0:P.createdAt)??pe();let X={id:I??Y(),role:"assistant",content:C,createdAt:se,sources:U,toolUses:O};L.current.length>0&&!te&&(X=await gt(L.current,X,{messages:A,apiUrl:e}),X.createdAt||(X={...X,createdAt:se}));const he=I!==null?k.current.map(W=>W.id===X.id?X:W):[...A,X],ue=kt(he,G);k.current=ue,R(ue),F(ue)}catch(C){if(C instanceof je)return;if(C instanceof V&&((Z=C.code)!=null&&Z.startsWith("ATTACHMENT"))&&A.length>0){const U=A[A.length-1];if(U.role==="user"&&((J=U.attachments)!=null&&J.length)){const O=A.slice(0,-1);k.current=O,R(O),F(O)}}if(I!==null){F(k.current),C instanceof V?y(K(C.code,C.message)):y((s==null?void 0:s.errorConnection)??"Failed to connect. Please try again."),S(!1);return}if(L.current.length>0){const U=C instanceof Error?C:new Error(String(C)),O=await xt(L.current,U,{messages:A,apiUrl:e});if(O){const G={id:Y(),role:"assistant",content:O.content,createdAt:pe(),sources:O.sources},te=[...A,G];k.current=te,R(te),F(te),y(null),S(!1);return}}C instanceof V?y(K(C.code,C.message)):y((s==null?void 0:s.errorConnection)??"Failed to connect. Please try again."),S(q(C))}finally{p(!1),M.current=!1,T(!1),w(null),Q.current=null}},[e,c,l,K,q,F,i,s]),B=u.useCallback(()=>{var A;(A=Q.current)==null||A.abort()},[]),re=u.useCallback(async(A,$)=>{const I=A.trim(),v=($==null?void 0:$.filter(P=>P&&P.id))??[];if(!I&&v.length===0||M.current)return;const H={id:Y(),role:"user",content:I,createdAt:pe(),...v.length>0?{attachments:v}:{}};let z=H;if(L.current.length>0){const P=await mt(L.current,H,{messages:k.current,apiUrl:e});if(P.type==="abort")return;const Z=J=>J.createdAt?J:{...J,createdAt:H.createdAt};if(P.type==="respond"){const J={id:Y(),role:"assistant",content:P.reply.content,createdAt:pe(),sources:P.reply.sources},C=[...k.current,Z(P.message),J];k.current=C,R(C),F(C),y(null),S(!1);return}z=Z(P.message)}const ee=[...k.current,z];k.current=ee,R(ee),F(ee),await _(ee)},[e,F,_]),ie=u.useCallback(async()=>{if(M.current)return;const A=k.current[k.current.length-1];!A||A.role!=="user"||await _(k.current)},[_]),ce=u.useCallback(()=>{if(k.current=[],R([]),y(null),S(!1),t){const A=ke();if(!A)return;try{A.removeItem(d)}catch{}}},[t,d]);return{messages:j,isLoading:g,isStreaming:f,streamingMessageId:x,error:b,canRetry:N,sendMessage:re,stop:B,retry:ie,clearMessages:ce}}function Lt(e){const[t,n]=u.useState(()=>typeof window>"u"?!1:window.matchMedia(e).matches);return u.useEffect(()=>{const r=window.matchMedia(e);n(r.matches);const s=a=>n(a.matches);return r.addEventListener("change",s),()=>r.removeEventListener("change",s)},[e]),t}function we(e,t){return e instanceof RegExp?e.test(t):t.toLowerCase().includes(e.toLowerCase())}function Dt(){const e=document.documentElement,t=document.body,n=e.scrollTop||t.scrollTop||0,r=Math.max(e.scrollHeight,t.scrollHeight),s=e.clientHeight||window.innerHeight,a=r-s;return a<=0?100:n/a*100}function It({triggers:e,enabled:t,onOpen:n,onGreeting:r}){u.useEffect(()=>{if(!t||!e||e.length===0)return;const s=new Set,a=[],i=typeof window<"u"?window.location.href:"",c=(l,d)=>{s.has(l)||(s.add(l),d==="open"?n():r(d.greeting))};return e.forEach((l,d)=>{switch(l.on){case"url":{we(l.pattern,i)&&c(d,l.action);break}case"time":{if(l.matchUrl&&!we(l.matchUrl,i))return;const h=window.setTimeout(()=>c(d,l.action),Math.max(0,l.seconds*1e3));a.push(()=>window.clearTimeout(h));break}case"scroll":{if(l.matchUrl&&!we(l.matchUrl,i))return;const h=()=>{Dt()>=l.percent&&c(d,l.action)};h(),window.addEventListener("scroll",h,{passive:!0}),a.push(()=>window.removeEventListener("scroll",h));break}case"exit-intent":{if(l.matchUrl&&!we(l.matchUrl,i))return;const h=j=>{j.clientY<=0&&c(d,l.action)};document.addEventListener("mouseleave",h),a.push(()=>document.removeEventListener("mouseleave",h));break}}}),()=>{a.forEach(l=>l())}},[e,t,n,r])}const Ot={"bottom-right":"bottom-6 right-6","bottom-left":"bottom-6 left-6","top-right":"top-6 right-6","top-left":"top-6 left-6"},$t=u.forwardRef(function({isOpen:t,onClick:n,position:r="bottom-right",translations:s},a){const i=t?(s==null?void 0:s.closeChat)??"Close chat":(s==null?void 0:s.openChat)??"Open chat";return o.jsx("button",{ref:a,onClick:n,"aria-label":i,className:`fixed ${Ot[r]} z-50 flex h-14 w-14 items-center justify-center rounded-claudius-full bg-claudius-accent text-claudius-accent-text shadow-claudius-floating transition-transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-claudius-accent focus:ring-offset-2`,children:t?o.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[o.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),o.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}):o.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:o.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})})}),Pt=u.memo(function({count:t,isActive:n,onClick:r}){return o.jsxs("button",{onClick:r,"aria-label":"View sources",title:"View sources",className:`group relative flex h-7 w-7 items-center justify-center rounded-claudius-full transition-colors ${n?"bg-claudius-accent text-claudius-accent-text":"text-claudius-text-muted hover:bg-claudius-surface-muted hover:text-claudius-text"}`,children:[o.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[o.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),o.jsx("polyline",{points:"14 2 14 8 20 8"}),o.jsx("line",{x1:"16",y1:"13",x2:"8",y2:"13"}),o.jsx("line",{x1:"16",y1:"17",x2:"8",y2:"17"})]}),o.jsx("span",{className:"absolute -right-1 -top-1 flex h-4 min-w-4 items-center justify-center rounded-claudius-full bg-claudius-accent px-1 text-[10px] font-bold text-claudius-accent-text",children:t})]})}),Ut=["http:","https:"];function ye(e){if(!e||typeof e!="string")return null;const t=e.trim();if(!t)return null;try{const n=new URL(t);return Ut.includes(n.protocol)?t:null}catch{return null}}function de(e,t){return e.replace(/\{(\w+)\}/g,(n,r)=>r in t?String(t[r]):n)}const Ze={maxSources:5,favicons:!0};function Ft(e){const t=typeof e=="object"&&e!==null&&!Array.isArray(e);if(e!==!0&&!t)return null;const n=e===!0?{}:e,r=n.maxSources;return{maxSources:typeof r=="number"&&Number.isInteger(r)&&r>=1?r:Ze.maxSources,favicons:n.favicons!==!1}}const _t=/\[([1-9]\d{0,2}(?:\s*,\s*[1-9]\d{0,2})*)\]/g;function Je(e,t){if(!e)return[];if(t<=0||!e.includes("["))return[{type:"text",value:e}];const n=[];let r=0;for(const s of e.matchAll(_t)){const a=s[1].split(",").map(c=>Number(c.trim()));if(a.some(c=>c>t))continue;const i=s.index??0;i>r&&n.push({type:"text",value:e.slice(r,i)}),n.push({type:"cite",indexes:[...new Set(a)].map(c=>c-1),raw:s[0]}),r=i+s[0].length}return r<e.length&&n.push({type:"text",value:e.slice(r)}),n}function Bt(e,t){let n="";for(const r of Je(e,t))r.type==="text"?n+=r.value:n=n.replace(/[ \t]+$/,"");return n}function Ht(e){return e.replace(/[ \t]?\[[\d,\s]*$/,"")}const zt=200;function Wt(e,t=zt){const n=e.replace(/\s+/g," ").trim();if(n.length<=t)return n;const r=n.slice(0,t),s=r.lastIndexOf(" ");return`${(s>0?r.slice(0,s):r).replace(/[\s,;:]+$/,"")}…`}function Gt(e){try{const t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?null:`${t.origin}/favicon.ico`}catch{return null}}function Vt(e){try{return new URL(e).hostname}catch{return e}}const Kt=1500;function qt(){return typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-reduced-motion: reduce)").matches:!1}const Qe="flex h-4 min-w-4 shrink-0 items-center justify-center rounded-claudius-full bg-claudius-accent px-1 text-[10px] font-bold leading-none text-claudius-accent-text",Yt=u.forwardRef(function({source:t,number:n,favicons:r,labels:s,highlighted:a},i){const c=ye(t.url),[l,d]=u.useState(!1),h=r&&c?Gt(c):null,j=t.snippet?Wt(t.snippet):"";return o.jsxs("li",{ref:i,tabIndex:-1,"data-highlight":a||void 0,className:`flex gap-2 rounded-claudius-md border bg-claudius-surface-muted p-2 focus:outline-none focus-visible:ring-2 focus-visible:ring-claudius-accent ${a?"border-claudius-accent ring-2 ring-claudius-accent":"border-claudius-border"}`,children:[o.jsx("span",{"aria-hidden":"true",className:`mt-0.5 ${Qe}`,children:n}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsxs("div",{className:"flex items-center gap-1.5",children:[h&&!l?o.jsx("img",{src:h,alt:"",width:14,height:14,loading:"lazy",decoding:"async",referrerPolicy:"no-referrer",onError:()=>d(!0),className:"h-3.5 w-3.5 shrink-0 rounded-sm"}):o.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"shrink-0",children:[o.jsx("circle",{cx:"12",cy:"12",r:"10"}),o.jsx("path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}),o.jsx("path",{d:"M2 12h20"})]}),c?o.jsxs("a",{href:c,target:"_blank",rel:"noopener noreferrer",className:"truncate font-medium text-claudius-text hover:underline",children:[t.title,o.jsxs("span",{className:"sr-only",children:[" ",s.opensInNewTab]})]}):o.jsx("span",{className:"truncate font-medium text-claudius-text",children:t.title}),c&&o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:"shrink-0",children:[o.jsx("path",{d:"M15 3h6v6"}),o.jsx("path",{d:"M10 14 21 3"}),o.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"})]})]}),j&&o.jsx("p",{className:"mt-0.5 break-words",children:j}),c&&o.jsx("p",{className:"mt-0.5 truncate",children:Vt(c)})]})]})}),Zt=u.memo(function({sources:t,maxSources:n,favicons:r,labels:s,reveal:a=null}){const i=u.useId(),[c,l]=u.useState(!1),[d,h]=u.useState(!1),[j,R]=u.useState(null),[g,p]=u.useState(null),f=u.useRef(new Map),T=u.useRef(n);T.current=n,u.useEffect(()=>{a&&(R(a),l(!0),a.index>=T.current&&h(!0))},[a]),u.useEffect(()=>{if(!j)return;const b=f.current.get(j.index);b&&(typeof b.scrollIntoView=="function"&&b.scrollIntoView({block:"nearest",behavior:qt()?"auto":"smooth"}),b.focus({preventScroll:!0}),p(j),R(null))},[j]),u.useEffect(()=>{if(!g)return;const b=setTimeout(()=>p(null),Kt);return()=>clearTimeout(b)},[g]);const x=t.length,w=d?t:t.slice(0,n);return o.jsxs("div",{className:"mt-1 text-xs text-claudius-text-muted",children:[o.jsxs("button",{type:"button",onClick:()=>l(b=>!b),"aria-expanded":c,"aria-controls":c?i:void 0,className:"flex items-center gap-1.5 rounded-claudius-full border border-claudius-border bg-claudius-surface px-2 py-0.5 hover:opacity-80 focus:outline-none focus-visible:ring-2 focus-visible:ring-claudius-accent",children:[o.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[o.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),o.jsx("polyline",{points:"14 2 14 8 20 8"}),o.jsx("line",{x1:"16",y1:"13",x2:"8",y2:"13"}),o.jsx("line",{x1:"16",y1:"17",x2:"8",y2:"17"})]}),o.jsx("span",{children:s.sources}),o.jsx("span",{className:Qe,children:x}),o.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:c?"rotate-180":void 0,children:o.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),c&&o.jsxs(o.Fragment,{children:[o.jsx("ol",{id:i,"aria-label":s.sources,className:"mt-1 space-y-1.5",children:w.map((b,y)=>o.jsx(Yt,{ref:N=>{N?f.current.set(y,N):f.current.delete(y)},source:b,number:y+1,favicons:r,labels:s,highlighted:(g==null?void 0:g.index)===y},`${y}-${b.url}`))}),x>n&&o.jsx("button",{type:"button",onClick:()=>h(b=>!b),"aria-expanded":d,className:"mt-1 font-medium text-claudius-link underline hover:opacity-80 focus:outline-none focus-visible:ring-2 focus-visible:ring-claudius-accent",children:d?s.showFewerSources:de(s.showAllSources,{count:x})})]})]})});function Jt(){return o.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[o.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),o.jsx("polyline",{points:"14 2 14 8 20 8"})]})}function Le({label:e,onClick:t}){return o.jsx("button",{type:"button",onClick:t,"aria-label":e,className:"absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-claudius-full bg-claudius-text text-claudius-surface shadow-claudius-floating hover:opacity-90 focus:outline-none focus-visible:ring-2 focus-visible:ring-claudius-accent",children:o.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round","aria-hidden":"true",children:[o.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),o.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})}const Xe=u.memo(function({attachment:t,variant:n,onRemove:r,removeLabel:s}){const a=vt(t),i=n==="composer",c=`${t.name} (${Se(t.size)})`,l=t.url?ye(t.url):null;if(a){const h=o.jsx("img",{src:a,alt:t.name,title:c,loading:"lazy",className:i?"h-12 w-12 rounded-claudius-sm border border-claudius-border object-cover":"max-h-48 max-w-full rounded-claudius-sm object-contain"});return o.jsxs("div",{className:"relative inline-block",children:[!i&&l?o.jsxs("a",{href:l,target:"_blank",rel:"noopener noreferrer",children:[h,o.jsxs("span",{className:"sr-only",children:[c," (opens in a new tab)"]})]}):h,r&&s&&o.jsx(Le,{label:s,onClick:r})]})}const d=o.jsxs("span",{title:c,className:`inline-flex max-w-[220px] items-center gap-1.5 rounded-claudius-sm border px-2 py-1 text-xs ${i?"border-claudius-border bg-claudius-field text-claudius-text":"border-current/30 bg-transparent"}`,children:[o.jsx(Jt,{}),o.jsx("span",{className:"truncate",children:t.name}),o.jsx("span",{className:"shrink-0 opacity-70",children:Se(t.size)})]});return o.jsxs("div",{className:"relative inline-block",children:[!i&&l?o.jsxs("a",{href:l,target:"_blank",rel:"noopener noreferrer",className:"underline-offset-2 hover:underline",children:[d,o.jsx("span",{className:"sr-only",children:" (opens in a new tab)"})]}):d,r&&s&&o.jsx(Le,{label:s,onClick:r})]})}),De=u.forwardRef(function({label:t,onClick:n,children:r},s){return o.jsx("button",{ref:s,type:"button",onClick:n,"aria-label":t,title:t,className:"flex h-7 w-7 items-center justify-center rounded-claudius-full text-claudius-text-muted transition-colors hover:bg-claudius-surface-muted hover:text-claudius-text",children:o.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:r})})});function Qt({state:e,labels:t,onPlay:n,onPause:r,onResume:s,onStop:a}){var h;const i=u.useRef(null),c=u.useRef(null),l=!!((h=i.current)!=null&&h.contains(document.activeElement));u.useEffect(()=>{var j,R;e==="idle"&&l&&!((j=i.current)!=null&&j.contains(document.activeElement))&&((R=c.current)==null||R.focus())},[e,l]);const d=e==="idle"?{label:t.play,onClick:n}:e==="paused"?{label:t.resume,onClick:s}:{label:t.pause,onClick:r};return o.jsxs("div",{ref:i,className:"flex items-center gap-1",children:[o.jsx(De,{ref:c,...d,children:e==="idle"?o.jsxs(o.Fragment,{children:[o.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),o.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07",fill:"none"}),o.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14",fill:"none"})]}):e==="paused"?o.jsx("polygon",{points:"6 3 20 12 6 21 6 3"}):o.jsxs(o.Fragment,{children:[o.jsx("rect",{x:"6",y:"4",width:"4",height:"16",rx:"1"}),o.jsx("rect",{x:"14",y:"4",width:"4",height:"16",rx:"1"})]})}),e!=="idle"&&o.jsx(De,{label:t.stop,onClick:a,children:o.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5"})})]})}function Xt(e){const t=e.lastIndexOf(`
6
+ `),n=t===-1?"":e.slice(0,t+1);let r=t===-1?e:e.slice(t+1);return r=nn(r),r=rn(r),n+r}function en(e){const t=[];for(let n=0;n<e.length-1;n++)e[n]==="*"&&e[n+1]==="*"&&(t.push(n),n++);return t}function tn(e){const t=[];for(let n=0;n<e.length;n++)if(e[n]==="*"){if(e[n+1]==="*"){n++;continue}t.push(n)}return t}function nn(e){const t=en(e);if(t.length%2===0)return e;const n=t[t.length-1],r=e.slice(n+2);return r.trim()===""?e.slice(0,n)+r:e+"**"}function rn(e){const t=tn(e);if(t.length%2===0)return e;const n=t[t.length-1],r=e.slice(n+1);return r.trim()===""?e.slice(0,n)+r:e+"*"}function sn({toolUse:e,usedLabel:t,detailsLabel:n}){const[r,s]=u.useState(!1),a=e.input!==void 0||e.result!==void 0;return o.jsxs("div",{className:"text-xs text-claudius-text-muted",children:[o.jsxs("button",{type:"button",disabled:!a,onClick:()=>s(i=>!i),"aria-expanded":a?r:void 0,className:"flex items-center gap-1.5 rounded-claudius-full border border-claudius-border bg-claudius-surface px-2 py-0.5 hover:opacity-80 disabled:cursor-default disabled:hover:opacity-100",children:[o.jsx("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:o.jsx("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),o.jsxs("span",{children:[t," ",o.jsx("span",{className:"font-mono text-claudius-text",children:e.name}),e.isError&&o.jsx("span",{className:"text-claudius-error",children:" ✕"})]}),a&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"sr-only",children:n}),o.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:r?"rotate-180":void 0,children:o.jsx("polyline",{points:"6 9 12 15 18 9"})})]})]}),r&&a&&o.jsxs("div",{className:"mt-1 overflow-x-auto rounded-claudius-sm border border-claudius-border bg-claudius-field p-2 font-mono",children:[e.input!==void 0&&o.jsx("pre",{className:"whitespace-pre-wrap break-all",children:JSON.stringify(e.input,null,2)}),e.result!==void 0&&o.jsx("pre",{className:"mt-1 whitespace-pre-wrap break-all border-t border-claudius-border pt-1",children:e.result})]})]})}const Ie=/(https?:\/\/[^\s)]+)/,Oe=/(\*\*[^*]+\*\*)/,$e=/(\*[^*]+\*)/,on=/(?:\[[1-9]\d{0,2}(?:\s*,\s*[1-9]\d{0,2})*\])+$/;function an(e,t,n){const r=e.match(/[.,;:!?'"]+$/),s=r?e.slice(0,-r[0].length):e,a=r?r[0]:"",i=n.citations?s.match(on):null,c=i?s.slice(0,-i[0].length):s,l=ye(c);return l?o.jsxs(u.Fragment,{children:[o.jsxs("a",{href:l,target:"_blank",rel:"noopener noreferrer",className:"underline font-medium hover:opacity-80 text-claudius-link",children:[l.replace(/^https?:\/\//,""),o.jsxs("span",{className:"sr-only",children:[" ",n.newTabLabel]})]}),i&&et(i[0],`${t}-m`,n),a]},t):e}function et(e,t,n){const r=n.citations;return r?Je(e,r.sources.length).map((s,a)=>s.type==="text"?s.value:o.jsx("span",{className:"inline-flex gap-0.5 align-super",children:s.indexes.map(i=>o.jsx("button",{type:"button",onClick:()=>r.onCite(i),"aria-label":de(r.label,{n:i+1,title:r.sources[i].title}),title:r.sources[i].title,className:"inline-flex h-4 min-w-4 items-center justify-center rounded-claudius-full bg-claudius-accent px-1 text-[10px] font-semibold leading-none text-claudius-accent-text hover:opacity-80 focus:outline-none focus-visible:ring-2 focus-visible:ring-claudius-accent focus-visible:ring-offset-1",children:i+1},i))},`${t}-c${a}`)):e?[e]:[]}function Te(e,t,n){const r=[];return e.split(Ie).forEach((s,a)=>{Ie.test(s)?r.push(an(s,`${t}-u${a}`,n)):s&&r.push(...et(s,`${t}-u${a}`,n))}),r}function cn(e,t,n){const r=[];return e.split(Oe).forEach((s,a)=>{if(Oe.test(s)){r.push(o.jsx("strong",{children:Te(s.slice(2,-2),`${t}-b${a}`,n)},`${t}-b${a}`));return}s.split($e).forEach((i,c)=>{const l=`${t}-b${a}-i${c}`;$e.test(i)?r.push(o.jsx("em",{children:Te(i.slice(1,-1),l,n)},l)):r.push(...Te(i,l,n))})}),r}function un(e,t){const n=e.split(`
7
+ `);return n.map((r,s)=>o.jsxs("span",{children:[cn(r,`l${s}`,t),s<n.length-1&&o.jsx("br",{})]},s))}const ln=u.memo(function({role:t,content:n,isStreaming:r=!1,sources:s,attachments:a,toolUses:i,toolUsedLabel:c="Used tool:",toolDetailsLabel:l="Tool details",onSourceClick:d,isSourceActive:h,speech:j,citations:R,linkNewTabLabel:g="(opens in a new tab)"}){const p=t==="user",[f,T]=u.useState(null),x=u.useRef(0),w=!p&&R&&s&&s.length>0?{config:R,sources:s}:null,b=!!a&&a.length>0,y=r&&w?Ht(n):n,N=r?Xt(y):y,S={newTabLabel:g,citations:w?{sources:w.sources,label:w.config.labels.citation,onCite:M=>{x.current+=1,T({index:M,key:x.current})}}:void 0},E=p||n!==""||!(i!=null&&i.length);return o.jsxs("div",{className:`${p?"ml-auto":"mr-auto"} max-w-[85%]`,children:[E&&o.jsxs("div",{className:`rounded-claudius-bubble px-4 py-2.5 text-sm leading-relaxed font-body ${p?"bg-claudius-user-bubble text-claudius-user-bubble-text rounded-br-claudius-tail":"bg-claudius-assistant-bubble text-claudius-assistant-bubble-text rounded-bl-claudius-tail"}`,children:[b&&o.jsx("ul",{className:`flex flex-wrap gap-2 ${n?"mb-2":""}`,"aria-label":"Attachments",children:a.map(M=>o.jsx("li",{children:o.jsx(Xe,{attachment:M,variant:"message"})},M.id))}),(n!==""||!b)&&un(N,S)]}),!p&&i&&i.length>0&&o.jsx("div",{className:"mt-1 space-y-1",children:i.map((M,k)=>o.jsx(sn,{toolUse:M,usedLabel:c,detailsLabel:l},`${M.name}-${k}`))}),w?o.jsx(Zt,{sources:w.sources,maxSources:w.config.maxSources,favicons:w.config.favicons,labels:w.config.labels,reveal:f}):!p&&s&&s.length>0&&d&&o.jsx("div",{className:"mt-1",children:o.jsx(Pt,{count:s.length,isActive:h??!1,onClick:d})}),!p&&j&&o.jsx("div",{className:"mt-1",children:o.jsx(Qt,{...j})})]})}),tt={title:"Chat",subtitle:"Ask me anything",welcomeMessage:"Hi! How can I help you today?",closeChat:"Close chat",chatMessages:"Chat messages",typingIndicator:"Assistant is typing",placeholder:"Type your message...",sendMessage:"Send message",stopGenerating:"Stop generating",toolUsed:"Used tool:",toolDetails:"Tool details",typeYourMessage:"Type your message",openChat:"Open chat",dismissGreeting:"Dismiss greeting",attachFile:"Attach a file",removeAttachment:"Remove attachment",attachmentsLabel:"Attachments",dropFilesHint:"Drop files to attach",attachmentTooLarge:"{name} is too large. The maximum size is {max}.",attachmentTypeNotAllowed:"{name} is not a supported file type.",attachmentTooMany:"You can attach up to {max} files per message.",voiceInput:"Voice input",voiceInputHold:"Hold to talk",voiceListening:"Listening...",voicePermissionDenied:"Microphone access is blocked. Allow it in your browser settings to use voice input.",voiceNoSpeech:"No speech was detected. Please try again.",voiceNoMicrophone:"No microphone was found.",voiceUnavailable:"Voice input is not available right now.",readAloud:"Read aloud",pauseReading:"Pause reading",resumeReading:"Resume reading",stopReading:"Stop reading",moreOptions:"More options",copyAsMarkdown:"Copy as Markdown",downloadAsMarkdown:"Download as Markdown",downloadAsJson:"Download as JSON",copiedToClipboard:"Copied to clipboard",copyFailed:"Could not copy. Try downloading instead.",transcriptTitle:"Chat transcript",transcriptExported:"Exported {date}",transcriptUser:"User",transcriptAssistant:"Assistant",transcriptAttachments:"Attachments:",transcriptSources:"Sources:",sources:"Sources",showAllSources:"Show all ({count})",showFewerSources:"Show fewer",citation:"Source {n}: {title}",opensInNewTab:"(opens in a new tab)",errorGeneric:"Something went wrong. Please try again.",errorConnection:"Failed to connect. Please try again.",errorTimeout:"Request timed out. Please try again.",errorRateLimitMinute:"Too many requests. Please wait a minute.",errorRateLimitHour:"Hourly limit reached. Please try again later.",errorAttachmentRejected:"An attachment was rejected. Please remove it and try again.",errorAttachmentQuota:"Upload limit reached. Please try again later.",errorRetry:"Retry"},Re=tt;function dn(e){return{...Re,...e}}function Pe(e){return e.key===" "||e.key==="Enter"}function fn({mode:e,isListening:t,disabled:n=!1,onStart:r,onStop:s,label:a}){const i=e==="hold",c=u.useRef(!1),l=()=>{n||c.current||(c.current=!0,r({held:!0}))},d=()=>{c.current&&(c.current=!1,s())},h=p=>{i&&p.detail!==0||(t?s():r({held:!1}))},j=p=>{var f,T;!i||p.button!==0||((T=(f=p.currentTarget).setPointerCapture)==null||T.call(f,p.pointerId),l())},R=p=>{!i||!Pe(p)||(p.preventDefault(),p.repeat||l())},g=p=>{!i||!Pe(p)||(p.preventDefault(),d())};return o.jsx("button",{type:"button",disabled:n,"aria-label":a,"aria-pressed":t,title:a,onClick:h,onPointerDown:j,onPointerUp:d,onPointerCancel:d,onLostPointerCapture:d,onKeyDown:R,onKeyUp:g,onBlur:d,onContextMenu:i?p=>p.preventDefault():void 0,style:i?{WebkitTouchCallout:"none"}:void 0,className:`flex h-11 w-11 shrink-0 items-center justify-center rounded-claudius-sm border transition-colors focus:outline-none focus:ring-1 focus:ring-claudius-accent disabled:opacity-50 ${t?"border-claudius-accent bg-claudius-accent text-claudius-accent-text focus:ring-2 focus:ring-offset-2 focus:ring-offset-claudius-surface":"border-claudius-border bg-claudius-field text-claudius-text-muted hover:text-claudius-text focus:border-claudius-accent"} ${i?"touch-none select-none":""}`,children:t&&!i?o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:o.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5"})}):o.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[o.jsx("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"}),o.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),o.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]})})}function hn({active:e}){return o.jsxs("span",{"aria-hidden":"true","data-claudius-voice-level":e?"active":"idle",className:"claudius-voice-level pointer-events-none absolute right-3 top-1/2 flex h-4 -translate-y-1/2 items-center gap-0.5 text-claudius-accent",children:[o.jsx("span",{}),o.jsx("span",{}),o.jsx("span",{}),o.jsx("span",{})]})}const pn={en:"en-US",es:"es-ES",fr:"fr-FR",de:"de-DE"},mn=["toggle","hold"];function Ue(e,t){if(!(!e||!e.includes("-")))return e.toLowerCase().split("-")[0]===t?e:void 0}function nt(e,t){const n=t==null?void 0:t.trim();if(n)return n;const r=typeof document<"u"?Ue(document.documentElement.lang,e):void 0;if(r)return r;const s=typeof navigator<"u"?Ue(navigator.language,e):void 0;return s||pn[e]}function gn(e,t){const n=typeof e=="object"&&e!==null&&!Array.isArray(e);if(e!==!0&&!n)return null;const r=e===!0?{}:e,s={input:r.input??!0,output:r.output??!0,mode:mn.includes(r.mode)?r.mode:"toggle",autoSubmit:r.autoSubmit??!1,lang:nt(t,r.lang)};return s.input||s.output?s:null}function xn(e,t,n){const r=t.trim();if(!r)return e;const s=e.trimEnd();return(s?`${s} ${r}`:r).slice(0,n)}function bn(e){const t=[];let n=0;for(let r=0;r<e.length;r++){const s=e[r];(s===`
8
+ `||s==="。"||s==="!"||s==="?"||(s==="."||s==="!"||s==="?")&&(r+1===e.length||/\s/.test(e[r+1])))&&(t.push(e.slice(n,r+1)),n=r+1)}return n<e.length&&t.push(e.slice(n)),t}function yn(e,t=150){const n=[];let r="";const s=()=>{const a=r.trim();a&&n.push(a),r=""};for(const a of bn(e)){if((r+a).trim().length<=t){r+=a;continue}if(s(),a.trim().length<=t){r=a;continue}for(let i of a.trim().split(/\s+/)){for(r&&`${r} ${i}`.length>t&&s();i.length>t;)n.push(i.slice(0,t)),i=i.slice(t);r=r?`${r} ${i}`:i}}return s(),n}function Fe(){if(typeof window>"u")return;const e=window;return e.SpeechRecognition??e.webkitSpeechRecognition}function wn(e){switch(e){case"not-allowed":case"service-not-allowed":return"permission";case"no-speech":return"no-speech";case"audio-capture":return"no-microphone";default:return"unavailable"}}function vn(e){const[t]=u.useState(()=>Fe()!==void 0),[n,r]=u.useState(!1),[s,a]=u.useState(!1),i=u.useRef(null),c=u.useRef(!1),l=u.useRef(e);u.useEffect(()=>{l.current=e});const d=u.useCallback(g=>{g.onstart=null,g.onend=null,g.onerror=null,g.onresult=null,g.onspeechstart=null,g.onspeechend=null,i.current===g&&(i.current=null),r(!1),a(!1)},[]),h=u.useCallback(()=>{const g=i.current;g&&(d(g),g.abort())},[d]),j=u.useCallback(()=>{const g=i.current;return g?(c.current?g.stop():h(),!0):!1},[h]),R=u.useCallback(()=>{var x,w;const g=Fe();if(!g||i.current)return!1;const p=new g;p.lang=l.current.lang,p.interimResults=!0,p.continuous=!1;let f="";const T=()=>{c.current=!0};p.onstart=T,p.onspeechstart=()=>{T(),a(!0)},p.onspeechend=()=>a(!1),p.onresult=b=>{var S,E;let y="",N="";for(let M=0;M<b.results.length;M++){const k=b.results[M];k.isFinal?y+=k[0].transcript:N+=k[0].transcript}f=y,T(),a(!0),(E=(S=l.current).onTranscript)==null||E.call(S,y+N)},p.onerror=b=>{var y,N;b.error!=="aborted"&&((N=(y=l.current).onError)==null||N.call(y,wn(b.error))),d(p),p.abort()},p.onend=()=>{var b,y;d(p),(y=(b=l.current).onEnd)==null||y.call(b,f)},i.current=p,c.current=!1,r(!0);try{p.start()}catch{return d(p),(w=(x=l.current).onError)==null||w.call(x,"unavailable"),!1}return!0},[d]);return u.useEffect(()=>h,[h]),{isSupported:t,isListening:n,isSpeechDetected:s,start:R,stop:j,abort:h}}const me=2e3,jn=1800;function _e(e){var n;const t=(n=e.dataTransfer)==null?void 0:n.types;return!!t&&Array.from(t).includes("Files")}function Sn({onSend:e,isLoading:t,isStreaming:n=!1,onStop:r,placeholder:s,translations:a,attachments:i=null,voice:c=null,onVoiceStart:l,isReadingAloud:d=!1}){const h=a??Re,[j,R]=u.useState(""),[g,p]=u.useState([]),[f,T]=u.useState(null),[x,w]=u.useState(!1),[b,y]=u.useState(null),N=u.useRef(null),S=u.useRef(null),E=u.useRef([]),M=u.useRef(0),k=u.useRef(""),Q=u.useRef(""),L=u.useRef(!1),F=u.useRef(!1),Y=u.useRef(!1),K=m=>{k.current=m,R(m)},q=j.length,_=q>=jn,B=q>=me,re=s??h.placeholder,ie=!!i&&g.length<i.maxCount,ce=n&&!!r;u.useEffect(()=>{var m;t||(m=N.current)==null||m.focus()},[t]);const A=u.useCallback((m,D)=>{if(!i)return"";switch(D){case"size":return de(h.attachmentTooLarge,{name:m,max:Se(i.maxSizeBytes)});case"type":return de(h.attachmentTypeNotAllowed,{name:m});case"count":return de(h.attachmentTooMany,{max:i.maxCount})}},[i,h]),$=u.useCallback(async m=>{if(!i||m.length===0)return;const{accepted:D,rejected:ae}=jt(m,E.current.length,i);if(T(ae.length>0?A(ae[0].file.name,ae[0].reason):null),D.length===0)return;const ut=await Promise.all(D.map(Tt));E.current=[...E.current,...ut],p(E.current)},[i,A]),I=u.useCallback(m=>{E.current=E.current.filter(D=>D.id!==m),p(E.current),T(null)},[]),v=()=>{const m=k.current.trim(),D=E.current;!m&&D.length===0||k.current.length>=me||(D.length>0?e(m,D):e(m),K(""),E.current=[],p([]),T(null),y(null))},H=m=>{switch(m){case"permission":return h.voicePermissionDenied;case"no-speech":return h.voiceNoSpeech;case"no-microphone":return h.voiceNoMicrophone;case"unavailable":return h.voiceUnavailable}},z=vn({lang:(c==null?void 0:c.lang)??"en-US",onTranscript:m=>K(xn(Q.current,m,me)),onEnd:m=>{const D=m.trim()!=="";if(D&&(F.current=!0),!L.current){Z();return}D&&J()},onError:m=>{m==="no-speech"&&F.current||(Y.current=!0,y(H(m)))}}),ee=!!(c!=null&&c.input)&&z.isSupported,P=z.isListening;u.useEffect(()=>{const m=N.current;P&&m&&(m.scrollLeft=m.scrollWidth)},[P,j]);const Z=()=>{c!=null&&c.autoSubmit&&F.current&&!Y.current&&v()},J=()=>{const m=k.current;z.start()&&(Q.current=m)},C=({held:m})=>{y(null),L.current=m,F.current=!1,Y.current=!1,l==null||l(),J()},U=()=>{const m=L.current;L.current=!1,!z.stop()&&m&&Z()},O=()=>{L.current=!1,z.abort()},{abort:G}=z;u.useEffect(()=>{!t&&!d||(L.current=!1,G())},[t,d,G]);const te=m=>{m.preventDefault(),O(),v()},se=m=>{const D=m.target.value;D.length<=me&&(O(),y(null),K(D))},X=m=>{const D=Array.from(m.target.files??[]);m.target.value="",$(D)},he=m=>{var ae;if(!i)return;const D=Array.from(((ae=m.clipboardData)==null?void 0:ae.files)??[]);D.length!==0&&(m.preventDefault(),$(D))},ue=m=>{!i||!_e(m)||(m.preventDefault(),M.current+=1,w(!0))},W=m=>{!i||!_e(m)||m.preventDefault()},ne=()=>{i&&(M.current=Math.max(0,M.current-1),M.current===0&&w(!1))},oe=m=>{var D;i&&(m.preventDefault(),M.current=0,w(!1),$(Array.from(((D=m.dataTransfer)==null?void 0:D.files)??[])))};return o.jsxs("form",{onSubmit:te,onDragEnter:ue,onDragOver:W,onDragLeave:ne,onDrop:oe,"data-drag-over":x||void 0,className:`relative border-t border-claudius-border bg-claudius-surface p-3 ${x?"ring-2 ring-inset ring-claudius-accent":""}`,children:[x&&o.jsx("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 z-10 flex items-center justify-center bg-claudius-surface text-sm font-medium text-claudius-accent",children:h.dropFilesHint}),i&&g.length>0&&o.jsx("ul",{"aria-label":h.attachmentsLabel,className:"mb-2 flex flex-wrap gap-3 pt-1",children:g.map(m=>o.jsx("li",{children:o.jsx(Xe,{attachment:m,variant:"composer",onRemove:()=>I(m.id),removeLabel:`${h.removeAttachment}: ${m.name}`})},m.id))}),o.jsxs("div",{className:"flex gap-2",children:[i&&o.jsxs(o.Fragment,{children:[o.jsx("input",{ref:S,type:"file",multiple:!0,hidden:!0,tabIndex:-1,accept:i.allowedTypes.join(","),onChange:X,"aria-label":h.attachFile}),o.jsx("button",{type:"button",onClick:()=>{var m;return(m=S.current)==null?void 0:m.click()},disabled:t||!ie,"aria-label":h.attachFile,title:h.attachFile,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-claudius-sm border border-claudius-border bg-claudius-field text-claudius-text-muted transition-colors hover:text-claudius-text focus:border-claudius-accent focus:outline-none focus:ring-1 focus:ring-claudius-accent disabled:opacity-50",children:o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:o.jsx("path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"})})})]}),o.jsxs("div",{className:"relative min-w-0 flex-1",children:[o.jsx("input",{ref:N,type:"text",value:j,onChange:se,onPaste:he,placeholder:P?h.voiceListening:re,disabled:t,"aria-label":h.typeYourMessage,"aria-describedby":_?"char-count":void 0,className:`h-full w-full rounded-claudius-sm border border-claudius-border bg-claudius-field py-2 pl-3 text-sm font-body text-claudius-text placeholder:text-claudius-text-muted focus:border-claudius-accent focus:outline-none focus:ring-1 focus:ring-claudius-accent disabled:opacity-50 ${P?"pr-10":"pr-3"}`}),P&&o.jsx(hn,{active:z.isSpeechDetected})]}),ee&&c&&o.jsx(fn,{mode:c.mode,isListening:P,disabled:t,onStart:C,onStop:U,label:c.mode==="hold"?h.voiceInputHold:h.voiceInput}),ce?o.jsx("button",{type:"button",onClick:r,"aria-label":h.stopGenerating,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-claudius-sm bg-claudius-accent text-claudius-accent-text transition-colors hover:opacity-90",children:o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:o.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5"})})}):o.jsx("button",{type:"submit",disabled:t||B,"aria-label":h.sendMessage,className:"flex h-11 w-11 shrink-0 items-center justify-center rounded-claudius-sm bg-claudius-accent text-claudius-accent-text transition-colors hover:opacity-90 disabled:opacity-50",children:o.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[o.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),o.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})})]}),(f??b)&&o.jsx("div",{role:"alert",className:"mt-1 text-xs text-claudius-error",children:f??b}),_&&o.jsxs("div",{id:"char-count",className:`mt-1 text-xs text-right ${B?"text-claudius-error":"text-claudius-text-muted"}`,"aria-live":"polite",children:[q,"/",me]})]})}const Rn=["blog","page","external"],Tn={blog:"Blog",page:"Page",external:"External"};function kn(e){try{return new URL(e).hostname}catch{return e}}const An=u.memo(function({sources:t,onClose:n}){const r=Rn.map(a=>({type:a,label:Tn[a],items:t.filter(i=>i.type===a)})).filter(a=>a.items.length>0),s=t.length===1?"1 source found":`${t.length} sources found`;return o.jsxs("div",{className:"absolute inset-y-0 left-0 z-10 flex w-[280px] flex-col border-r-2 border-claudius-border bg-claudius-surface rounded-r-claudius-lg transition-transform duration-200 ease-out",children:[o.jsxs("div",{className:"flex items-center justify-between border-b border-claudius-border px-4 py-3",children:[o.jsxs("div",{children:[o.jsx("h3",{className:"text-sm font-heading font-semibold text-claudius-text",children:"Sources"}),o.jsx("p",{className:"text-xs text-claudius-text-muted",children:s})]}),o.jsx("button",{onClick:n,"aria-label":"Close sources",className:"flex h-7 w-7 items-center justify-center rounded-claudius-full text-claudius-text-muted transition-colors hover:bg-claudius-surface-muted hover:text-claudius-text",children:o.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[o.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),o.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),o.jsx("div",{className:"flex-1 overflow-y-auto px-3 py-3 space-y-4",children:r.map(a=>o.jsxs("div",{children:[o.jsx("h4",{className:"mb-2 text-xs font-semibold uppercase tracking-wide text-claudius-text-muted",children:a.label}),o.jsx("div",{className:"space-y-2",children:a.items.map(i=>{const c=ye(i.url);return c?o.jsxs("a",{href:c,target:"_blank",rel:"noopener noreferrer",className:"block rounded-claudius-md border-2 border-claudius-border bg-claudius-surface-muted p-3 transition-colors hover:bg-claudius-border",children:[o.jsx("p",{className:"truncate text-sm font-medium text-claudius-text",children:i.title}),o.jsx("p",{className:"mt-0.5 text-xs text-claudius-text-muted",children:kn(c)})]},c):null})})]},a.type))})]})});function En({title:e,subtitle:t,titleId:n,closeLabel:r,onClose:s,actions:a}){return o.jsxs("div",{className:"flex items-center gap-3 bg-claudius-accent px-5 py-4",children:[o.jsx("div",{"aria-hidden":"true",className:"flex h-8 w-8 items-center justify-center rounded-claudius-full bg-claudius-accent-soft text-sm font-bold text-claudius-accent-text",children:e.charAt(0).toUpperCase()}),o.jsxs("div",{className:"flex-1",children:[o.jsx("h2",{id:n,className:"text-sm font-heading font-semibold text-claudius-accent-text",children:e}),o.jsx("p",{className:"text-xs text-claudius-accent-text",children:t})]}),a,o.jsx("button",{onClick:s,"aria-label":r,className:"flex h-10 w-10 items-center justify-center rounded-claudius-full text-claudius-accent-text-muted transition-colors hover:bg-claudius-accent-soft hover:text-claudius-accent-text",children:o.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[o.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),o.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})}function Cn({message:e,retryLabel:t,onRetry:n}){return o.jsxs("div",{role:"alert",className:"mx-auto flex max-w-[90%] flex-col items-center gap-2 rounded-claudius-sm bg-claudius-error-surface px-3 py-2 text-center text-xs text-claudius-error",children:[o.jsx("span",{children:e}),n&&o.jsx("button",{type:"button",onClick:n,className:"rounded-claudius-md bg-claudius-error px-3 py-1 text-xs font-semibold text-claudius-error-text transition-opacity hover:opacity-90 focus:outline-none focus-visible:ring-2 focus-visible:ring-claudius-error focus-visible:ring-offset-1",children:t})]})}function Nn({label:e}){return o.jsx("div",{role:"status","aria-live":"polite","aria-label":e,className:"mr-auto flex max-w-[85%]",children:o.jsxs("div",{className:"flex gap-1 rounded-claudius-bubble rounded-bl-claudius-tail bg-claudius-assistant-bubble px-4 py-3",children:[o.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:0ms]"}),o.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:150ms]"}),o.jsx("span",{className:"h-2 w-2 motion-safe:animate-bounce rounded-claudius-full bg-claudius-text-muted [animation-delay:300ms]"})]})})}function Mn({label:e,items:t,onOpen:n}){const[r,s]=u.useState(!1),a=u.useId(),i=u.useId(),c=u.useRef(null),l=u.useRef(null),d=u.useRef([]),h=u.useRef(null),j=x=>{h.current=x,s(!0),n==null||n()},R=x=>{var w;s(!1),(w=l.current)==null||w.focus()};u.useEffect(()=>{var w;if(!r)return;h.current!==null&&((w=d.current[h.current])==null||w.focus(),h.current=null);const x=b=>{var y;(y=c.current)!=null&&y.contains(b.target)||s(!1)};return document.addEventListener("pointerdown",x),()=>document.removeEventListener("pointerdown",x)},[r]);const g=x=>{var b;const w=t.length;(b=d.current[(x+w)%w])==null||b.focus()},p=x=>{x.key==="ArrowDown"?(x.preventDefault(),j(0)):x.key==="ArrowUp"&&(x.preventDefault(),j(t.length-1))},f=x=>{const w=d.current.findIndex(b=>b===document.activeElement);switch(x.key){case"ArrowDown":x.preventDefault(),g(w+1);break;case"ArrowUp":x.preventDefault(),g(w===-1?t.length-1:w-1);break;case"Home":x.preventDefault(),g(0);break;case"End":x.preventDefault(),g(t.length-1);break;case"Escape":x.preventDefault(),x.stopPropagation(),R();break;case"Tab":x.shiftKey&&(x.preventDefault(),R());break}},T=x=>{var b;const w=x.relatedTarget;w&&((b=c.current)!=null&&b.contains(w)||s(!1))};return o.jsxs("div",{ref:c,className:"relative",children:[o.jsx("button",{ref:l,id:a,type:"button","aria-label":e,"aria-haspopup":"menu","aria-expanded":r,"aria-controls":r?i:void 0,onClick:()=>r?R():j(0),onKeyDown:p,className:"flex h-10 w-10 items-center justify-center rounded-claudius-full text-claudius-accent-text-muted transition-colors hover:bg-claudius-accent-soft hover:text-claudius-accent-text",children:o.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:[o.jsx("circle",{cx:"12",cy:"5",r:"1.75"}),o.jsx("circle",{cx:"12",cy:"12",r:"1.75"}),o.jsx("circle",{cx:"12",cy:"19",r:"1.75"})]})}),r&&o.jsx("div",{id:i,role:"menu","aria-labelledby":a,tabIndex:-1,onKeyDown:f,onBlur:T,className:"absolute right-0 top-full z-20 mt-1 min-w-[12rem] rounded-claudius-md border border-claudius-border bg-claudius-surface py-1 shadow-claudius-elevated",children:t.map((x,w)=>o.jsx("button",{ref:b=>{d.current[w]=b},type:"button",role:"menuitem",tabIndex:-1,"aria-disabled":x.disabled||void 0,onClick:()=>{x.disabled||(R(),x.onSelect())},className:"flex min-h-[40px] w-full items-center whitespace-nowrap px-4 text-left text-sm text-claudius-text hover:bg-claudius-surface-muted focus:bg-claudius-surface-muted aria-disabled:cursor-default aria-disabled:opacity-50 aria-disabled:hover:bg-transparent",children:x.label},x.id))})]})}function Ln(e,t,n){const[r,s]=u.useState(0),a=u.useRef(0),i=u.useRef(0),c=u.useRef(0),l=u.useRef(!1);return u.useEffect(()=>{const d=e.current;if(!n||!d)return;const h=g=>{if(d.scrollTop>0){l.current=!1;return}l.current=!0,i.current=g.touches[0].clientY,c.current=Date.now()},j=g=>{if(!l.current)return;let p=g.touches[0].clientY-i.current;p<0&&(p=p*.3),a.current=p,s(p)},R=()=>{if(!l.current)return;l.current=!1;const g=a.current,p=(Date.now()-c.current)/1e3,f=d.getBoundingClientRect().height,T=p>.05&&g>0&&g/p>500,x=g>f*.3;T||x?t():(a.current=0,s(0))};return d.addEventListener("touchstart",h,{passive:!0}),d.addEventListener("touchmove",j,{passive:!0}),d.addEventListener("touchend",R),()=>{d.removeEventListener("touchstart",h),d.removeEventListener("touchmove",j),d.removeEventListener("touchend",R)}},[e,t,n]),{offsetY:r}}const Dn='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function In(e,t){u.useEffect(()=>{const n=e.current;if(!n)return;const r=s=>{if(s.key!=="Tab")return;const a=Array.from(n.querySelectorAll(Dn)).filter(d=>!d.hasAttribute("aria-hidden"));if(a.length===0)return;const i=a[0],c=a[a.length-1],l=document.activeElement;s.shiftKey&&l===i?(s.preventDefault(),c.focus()):!s.shiftKey&&l===c&&(s.preventDefault(),i.focus())};return n.addEventListener("keydown",r),()=>n.removeEventListener("keydown",r)},[e,t])}function ge(){if(!(typeof window>"u")&&!(typeof window.SpeechSynthesisUtterance>"u"))return window.speechSynthesis??void 0}function On(e){const[t]=u.useState(()=>ge()!==void 0),[n,r]=u.useState(null),[s,a]=u.useState(!1),i=u.useRef(0),c=u.useRef(!1),l=u.useRef([]),d=u.useCallback(()=>{i.current+=1,c.current=!1,l.current=[],r(null),a(!1)},[]),h=u.useCallback(()=>{const p=l.current.length>0;d();const f=ge();!p||!f||(f.cancel(),f.paused&&f.resume())},[d]),j=u.useCallback((p,f)=>{const T=ge();if(!T)return;d(),(T.speaking||T.pending)&&T.cancel(),T.paused&&T.resume();const x=yn(f);if(x.length===0)return;const w=i.current,b=()=>i.current===w;l.current=x.map((y,N)=>{const S=new SpeechSynthesisUtterance(y);return S.lang=e,S.onerror=E=>{if(!b())return;(E.error==="interrupted"||E.error==="canceled")&&!c.current?d():h()},S.onpause=()=>{b()&&a(!0)},S.onresume=()=>{b()&&a(!1)},S.onend=()=>{b()&&(c.current&&!T.paused?h():N===x.length-1&&d())},S}),r(p);for(const y of l.current)T.speak(y)},[e,h,d]),R=u.useCallback(()=>{const p=ge();p&&(c.current=!0,p.pause(),p.paused&&a(!0))},[]),g=u.useCallback(()=>{const p=ge();p&&(c.current=!1,p.resume(),a(!1))},[]);return u.useEffect(()=>h,[h]),{isSupported:t,activeId:n,isPaused:s,speak:j,pause:R,resume:g,cancel:h}}const $n=/^([ \t]*)(`{3,}|~{3,})(.*)$/,Pn=/^( {0,3})<(?![A-Za-z][A-Za-z0-9+.-]{1,31}:[^<>\s]*>|[A-Za-z0-9][^\s<>@]*@[^\s<>]+>)(?=[A-Za-z!?/])/,Un=/^(?: {4}|\t)/;function rt(e){let t=0;for(const n of e)if(n===" ")t+=1;else if(n===" ")t+=4-t%4;else break;return t}function Be(e){let t=e.length;for(;t>0&&(e[t-1]===" "||e[t-1]===" ");)t-=1;return t===e.length?e:e.slice(0,t)}function Fn(e){const t=$n.exec(e);if(!t)return null;const[,n,r,s]=t;return r[0]==="`"&&s.includes("`")?null:{indent:n,indentColumns:rt(n),char:r[0],length:r.length}}function _n(e,t){const n=e.trim();if(n.length<t.length)return!1;for(const r of n)if(r!==t.char)return!1;return rt(e)<=t.indentColumns+3}function Bn(e){const t=e.replace(/\r\n?/g,`
9
9
  `).split(`
10
- `),n=[];let r=null;for(let s=0;s<t.length;s++){const o=t[s];if(r){n.push(o),Rn(o,r)&&(r=null);continue}const i=jn(o);if(i){r=i,n.push(o);continue}let l=o.replace(wn,"$1\\<");const u=t[s+1];o.trim()!==""&&u!==void 0&&u.trim()!==""&&!vn.test(o)&&!o.endsWith("\\")&&(l=_e(l)+" "),n.push(l)}if(r)n[n.length-1]===""&&n.pop(),n.push(r.indent+r.char.repeat(r.length));else{for(;n.length>0&&n[n.length-1].trim()==="";)n.pop();n.length>0&&(n[n.length-1]=_e(n[n.length-1]))}return n.join(`
11
- `)}const Sn=/[\u00a0\u202f]/g;function Tn(e){if(e.formatDate)return e.formatDate;const t=s=>new Intl.DateTimeFormat(s,{dateStyle:"medium",timeStyle:"short",timeZone:e.timeZone});let n=null;try{n=t(e.locale)}catch{try{n=t(void 0)}catch{n=null}}const r=n;return r?s=>r.format(s):s=>s.toISOString()}function kn(e){const t=Tn(e);return n=>t(n).replace(Sn," ")}function An(e,t){var n;try{return((n=new Intl.DateTimeFormat("en",{timeZone:t,timeZoneName:"longOffset"}).formatToParts(e).find(s=>s.type==="timeZoneName"))==null?void 0:n.value)??""}catch{return""}}function et(e){const t=e.replace(/\s+/g," ").trim();if(t==="")return"";const n=Math.max(0,...(t.match(/`+/g)??[]).map(o=>o.length)),r="`".repeat(n+1),s=t.startsWith("`")||t.endsWith("`")?" ":"";return`${r}${s}${t}${s}${r}`}const Cn={"(":"%28",")":"%29","<":"%3C",">":"%3E","\\":"%5C"};function Mn(e,t){const n=ue(e.title||e.url).replace(/\s+/g," ").trim().replace(/[\\[\]<]/g,"\\$&"),r=Re(ue(e.url));if(!r)return`${t+1}. ${n}`;const s=r.replace(/[()<>\\]/g,o=>Cn[o]).replace(/\s/g,"%20");return`${t+1}. [${n}](${s})`}function Nn(e){const t=et(ue(e.name)),n=je(Number(e.size));return`- ${t} (${ue(e.mediaType)}, ${n})`}function ue(e){return typeof e=="string"?e:String(e??"")}function we(e){return Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"):[]}function Dn(e,t){const{labels:n}=t,r=kn(t),s=t.now??new Date,o=An(s,t.timeZone),i=r(s)+(o?` (${o})`:""),l=[`# ${n.title}`,ye(n.exported,{date:i})];for(const u of e){if(u===null||typeof u!="object")continue;const d=u.role==="user"?n.user:n.assistant,f=u.createdAt?new Date(u.createdAt):null,w=f&&!Number.isNaN(f.getTime())?` · ${r(f)}`:"";l.push(`## ${d}${w}`);const S=En(ue(u.content));S&&l.push(S);const x=we(u.attachments);x.length&&l.push(n.attachments,x.map(Nn).join(`
12
- `));const h=we(u.toolUses);h.length&&l.push(h.map(j=>`${n.toolUsed} ${et(ue(j.name))}`).join(`
13
- `));const p=we(u.sources);p.length&&l.push(n.sources,p.map(Mn).join(`
14
- `))}return l.join(`
10
+ `),n=[];let r=null;for(let s=0;s<t.length;s++){const a=t[s];if(r){n.push(a),_n(a,r)&&(r=null);continue}const i=Fn(a);if(i){r=i,n.push(a);continue}let c=a.replace(Pn,"$1\\<");const l=t[s+1];a.trim()!==""&&l!==void 0&&l.trim()!==""&&!Un.test(a)&&!a.endsWith("\\")&&(c=Be(c)+" "),n.push(c)}if(r)n[n.length-1]===""&&n.pop(),n.push(r.indent+r.char.repeat(r.length));else{for(;n.length>0&&n[n.length-1].trim()==="";)n.pop();n.length>0&&(n[n.length-1]=Be(n[n.length-1]))}return n.join(`
11
+ `)}const Hn=/[\u00a0\u202f]/g;function zn(e){if(e.formatDate)return e.formatDate;const t=s=>new Intl.DateTimeFormat(s,{dateStyle:"medium",timeStyle:"short",timeZone:e.timeZone});let n=null;try{n=t(e.locale)}catch{try{n=t(void 0)}catch{n=null}}const r=n;return r?s=>r.format(s):s=>s.toISOString()}function Wn(e){const t=zn(e);return n=>t(n).replace(Hn," ")}function Gn(e,t){var n;try{return((n=new Intl.DateTimeFormat("en",{timeZone:t,timeZoneName:"longOffset"}).formatToParts(e).find(s=>s.type==="timeZoneName"))==null?void 0:n.value)??""}catch{return""}}function st(e){const t=e.replace(/\s+/g," ").trim();if(t==="")return"";const n=Math.max(0,...(t.match(/`+/g)??[]).map(a=>a.length)),r="`".repeat(n+1),s=t.startsWith("`")||t.endsWith("`")?" ":"";return`${r}${s}${t}${s}${r}`}const Vn={"(":"%28",")":"%29","<":"%3C",">":"%3E","\\":"%5C"};function Kn(e,t){const n=fe(e.title||e.url).replace(/\s+/g," ").trim().replace(/[\\[\]<]/g,"\\$&"),r=ye(fe(e.url));if(!r)return`${t+1}. ${n}`;const s=r.replace(/[()<>\\]/g,a=>Vn[a]).replace(/\s/g,"%20");return`${t+1}. [${n}](${s})`}function qn(e){const t=st(fe(e.name)),n=Se(Number(e.size));return`- ${t} (${fe(e.mediaType)}, ${n})`}function fe(e){return typeof e=="string"?e:String(e??"")}function ve(e){return Array.isArray(e)?e.filter(t=>t!==null&&typeof t=="object"):[]}function Yn(e,t){const{labels:n}=t,r=Wn(t),s=t.now??new Date,a=Gn(s,t.timeZone),i=r(s)+(a?` (${a})`:""),c=[`# ${n.title}`,de(n.exported,{date:i})];for(const l of e){if(l===null||typeof l!="object")continue;const d=l.role==="user"?n.user:n.assistant,h=l.createdAt?new Date(l.createdAt):null,j=h&&!Number.isNaN(h.getTime())?` · ${r(h)}`:"";c.push(`## ${d}${j}`);const R=Bn(fe(l.content));R&&c.push(R);const g=ve(l.attachments);g.length&&c.push(n.attachments,g.map(qn).join(`
12
+ `));const p=ve(l.toolUses);p.length&&c.push(p.map(T=>`${n.toolUsed} ${st(fe(T.name))}`).join(`
13
+ `));const f=ve(l.sources);f.length&&c.push(n.sources,f.map(Kn).join(`
14
+ `))}return c.join(`
15
15
 
16
16
  `)+`
17
- `}function Ln(e){const t=e.filter(n=>n!==null&&typeof n=="object").map(n=>n.attachments===void 0?n:{...n,attachments:we(n.attachments)});return JSON.stringify(Ye(t),null,2)+`
18
- `}function Fe(e,t={}){const n=t.now??new Date;let r;try{const s=new Intl.DateTimeFormat("en",{timeZone:t.timeZone,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(n),o=i=>{var l;return((l=s.find(u=>u.type===i))==null?void 0:l.value)??""};r=`${o("year")}-${o("month")}-${o("day")}`}catch{r=n.toISOString().slice(0,10)}return`chat-transcript-${r}.${e}`}function In(e){const t=document.activeElement;let n=null;try{return n=document.createElement("textarea"),n.value=e,n.setAttribute("readonly",""),n.setAttribute("aria-hidden","true"),n.tabIndex=-1,n.style.position="fixed",n.style.top="0",n.style.left="0",n.style.opacity="0",document.body.appendChild(n),n.focus({preventScroll:!0}),n.select(),document.execCommand("copy")}catch{return!1}finally{try{n==null||n.remove()}catch{}try{t==null||t.focus()}catch{}}}async function On(e){var t;try{if((t=navigator.clipboard)!=null&&t.writeText)return await navigator.clipboard.writeText(e),!0}catch{}try{return In(e)}catch{return!1}}const Pn=4e4;function ze(e,t,n){const r=URL.createObjectURL(new Blob([t],{type:n})),s=document.createElement("a");s.href=r,s.download=e,s.style.display="none",document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(r),Pn)}const $n=4e3;function Un({enabled:e,messages:t,busy:n,locale:r,translations:s}){const o=s??Ee,[i,l]=c.useState(null),u=c.useRef(null),d=c.useRef(!0);c.useEffect(()=>(d.current=!0,()=>{d.current=!1,u.current&&clearTimeout(u.current)}),[]);const f=c.useCallback(()=>{u.current&&clearTimeout(u.current),u.current=null,l(null)},[]),w=c.useCallback(x=>{d.current&&(u.current&&clearTimeout(u.current),l(x),u.current=setTimeout(()=>{u.current=null,l(null)},$n))},[]);return{items:c.useMemo(()=>{if(!e)return[];const x=n||t.length===0,h=()=>Dn(t,{locale:r,labels:{title:o.transcriptTitle,exported:o.transcriptExported,user:o.transcriptUser,assistant:o.transcriptAssistant,attachments:o.transcriptAttachments,sources:o.transcriptSources,toolUsed:o.toolUsed}});return[{id:"copy-markdown",label:o.copyAsMarkdown,disabled:x,onSelect:()=>{On(h()).then(p=>w(p?o.copiedToClipboard:o.copyFailed))}},{id:"download-markdown",label:o.downloadAsMarkdown,disabled:x,onSelect:()=>ze(Fe("md"),h(),"text/markdown;charset=utf-8")},{id:"download-json",label:o.downloadAsJson,disabled:x,onSelect:()=>ze(Fe("json"),Ln(t),"application/json")}]},[e,n,t,r,o,w]),status:i,clearStatus:f}}const Bn=/\*\*([^*]+)\*\*/g,_n=/\*([^*]+)\*/g,Fn=/https?:\/\/[^\s)]+/g;function He(e){return e.replace(Bn,"$1").replace(_n,"$1").replace(Fn,t=>{var s;const n=((s=t.match(/[.,;:!?'"]+$/))==null?void 0:s[0])??"",r=n?t.slice(0,-n.length):t;try{return new URL(r).hostname+n}catch{return t}})}const zn={"bottom-right":"bottom-24 right-3 sm:right-6","bottom-left":"bottom-24 left-3 sm:left-6","top-right":"top-24 right-3 sm:right-6","top-left":"top-24 left-3 sm:left-6"};function Hn({messages:e,isLoading:t,isStreaming:n=!1,streamingMessageId:r=null,error:s,canRetry:o=!1,onSend:i,onStop:l,onRetry:u,onClose:d,title:f="Chat",subtitle:w="Ask me anything",welcomeMessage:S="Hi! How can I help you today?",placeholder:x,position:h="bottom-right",translations:p,isMobile:j=!1,attachments:b=null,voice:E=null,conversationExport:y=!1,locale:v="en-US"}){const k=c.useId(),L=c.useRef(null),C=c.useRef(null),[R,P]=c.useState(null);xn(L,!0);const N=bn((E==null?void 0:E.lang)??"en-US"),$=!!(E!=null&&E.output)&&N.isSupported,V={play:(p==null?void 0:p.readAloud)??"Read aloud",pause:(p==null?void 0:p.pauseReading)??"Pause reading",resume:(p==null?void 0:p.resumeReading)??"Resume reading",stop:(p==null?void 0:p.stopReading)??"Stop reading"},F=Un({enabled:y,messages:e,busy:t,locale:v,translations:p}),{offsetY:K}=mn(C,d,j),U=K!==0,te=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-reduced-motion: reduce)").matches:!1;c.useEffect(()=>{const m=C.current;m&&(m.scrollTop=m.scrollHeight)},[e,t]),c.useEffect(()=>{const m=I=>{I.key==="Escape"&&!I.isComposing&&!I.defaultPrevented&&d()};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[d]);const ne=(p==null?void 0:p.closeChat)??"Close chat",re=(p==null?void 0:p.chatMessages)??"Chat messages",X=[...e].reverse().find(m=>m.role==="assistant");return a.jsxs("div",{ref:L,role:"dialog","aria-modal":j?"true":void 0,"aria-labelledby":k,className:j?"claudius-bottom-sheet fixed inset-x-0 bottom-0 z-50 flex h-[90vh] w-full flex-col overflow-hidden rounded-t-claudius-lg bg-claudius-surface shadow-claudius-elevated font-body":`fixed ${zn[h]} z-50 flex h-[min(500px,calc(100vh-7rem))] w-[calc(100vw-1.5rem)] max-w-[380px] sm:max-w-[400px] md:max-w-[440px] flex-col overflow-hidden rounded-claudius-lg bg-claudius-surface shadow-claudius-elevated font-body`,style:j&&!te?{transform:`translateY(${Math.max(0,K)}px)`}:void 0,"data-dragging":U||void 0,children:[j&&a.jsx("div",{className:"flex justify-center py-2","aria-hidden":"true",children:a.jsx("div",{className:"h-1 w-8 rounded-claudius-full bg-claudius-border"})}),a.jsx(dn,{title:f,subtitle:w,titleId:k,closeLabel:ne,onClose:d,actions:y?a.jsx(pn,{label:(p==null?void 0:p.moreOptions)??"More options",items:F.items,onOpen:F.clearStatus}):void 0}),a.jsxs("div",{className:"relative flex-1 overflow-hidden",children:[R&&a.jsx(un,{sources:R.sources,onClose:()=>P(null)}),y&&a.jsx("div",{role:"status",className:"pointer-events-none absolute inset-x-0 top-2 z-10 flex justify-center px-4",children:F.status&&a.jsx("span",{className:"rounded-claudius-full bg-claudius-text px-3 py-1 text-xs text-claudius-surface shadow-claudius-elevated",children:F.status})}),a.jsxs("div",{ref:C,role:"log","aria-label":re,className:"h-full space-y-3 overflow-y-auto px-4 py-4",children:[e.length===0&&!s&&a.jsx("div",{className:"mr-auto flex max-w-[85%]",children:a.jsx("div",{className:"rounded-claudius-bubble rounded-bl-claudius-tail bg-claudius-assistant-bubble px-4 py-2.5 text-sm leading-relaxed text-claudius-assistant-bubble-text",children:S})}),e.map(m=>a.jsx(Vt,{role:m.role,content:m.content,isStreaming:m.id===r,sources:m.sources,attachments:m.attachments,toolUses:m.toolUses,toolUsedLabel:p==null?void 0:p.toolUsed,toolDetailsLabel:p==null?void 0:p.toolDetails,isSourceActive:(R==null?void 0:R.messageId)===m.id,onSourceClick:()=>{(R==null?void 0:R.messageId)===m.id?P(null):m.sources&&m.sources.length>0&&P({messageId:m.id,sources:m.sources})},speech:$&&m.role==="assistant"&&m.id!==r&&m.content.trim()!==""?{state:N.activeId!==m.id?"idle":N.isPaused?"paused":"speaking",labels:V,onPlay:()=>N.speak(m.id,He(m.content)),onPause:N.pause,onResume:N.resume,onStop:N.cancel}:void 0},m.id)),t&&!(r!==null&&e.some(m=>m.id===r&&m.content.length>0))&&a.jsx(hn,{label:(p==null?void 0:p.typingIndicator)??"Assistant is typing"}),s&&a.jsx(fn,{message:s,retryLabel:(p==null?void 0:p.errorRetry)??"Retry",onRetry:o&&u&&!t?u:void 0})]})]}),a.jsx("div",{"data-claudius-live":"assistant","aria-live":"polite","aria-atomic":"true",className:"sr-only",children:X&&X.id!==r?He(X.content):""}),a.jsx(on,{onSend:i,isLoading:t,isStreaming:n,onStop:l,placeholder:x,translations:p,attachments:b,voice:E,onVoiceStart:N.cancel,isReadingAloud:N.activeId!==null})]})}function Wn({message:e,position:t,onOpen:n,onDismiss:r,dismissLabel:s}){const o=t.startsWith("bottom"),i=t.endsWith("right"),l=["claudius-greeting-bubble","fixed z-40 max-w-xs",o?"bottom-20":"top-20",i?"right-4":"left-4"].join(" ");return a.jsxs("div",{className:l,role:"status","aria-live":"polite",children:[a.jsx("button",{type:"button",onClick:n,className:"block w-full rounded-claudius-lg bg-claudius-surface p-4 pr-8 text-left text-sm font-body text-claudius-text shadow-claudius-floating ring-1 ring-claudius-border transition hover:shadow-claudius-floating-hover focus:outline-none focus:ring-2 focus:ring-claudius-accent",children:e}),a.jsx("button",{type:"button",onClick:u=>{u.stopPropagation(),r()},"aria-label":s,className:"absolute right-1 top-1 flex h-6 w-6 items-center justify-center rounded-claudius-full text-claudius-text-muted hover:bg-claudius-surface-muted focus:outline-none focus:ring-2 focus:ring-claudius-accent",children:a.jsx("span",{"aria-hidden":"true",children:"×"})})]})}const Gn={title:"Chat",subtitle:"Pregúntame lo que quieras",welcomeMessage:"¡Hola! ¿En qué puedo ayudarte hoy?",closeChat:"Cerrar chat",chatMessages:"Mensajes del chat",typingIndicator:"El asistente está escribiendo",placeholder:"Escribe tu mensaje...",sendMessage:"Enviar mensaje",stopGenerating:"Detener la respuesta",toolUsed:"Herramienta usada:",toolDetails:"Detalles de la herramienta",typeYourMessage:"Escribe tu mensaje",openChat:"Abrir chat",dismissGreeting:"Descartar saludo",attachFile:"Adjuntar un archivo",removeAttachment:"Quitar adjunto",attachmentsLabel:"Adjuntos",dropFilesHint:"Suelta los archivos para adjuntarlos",attachmentTooLarge:"{name} es demasiado grande. El tamaño máximo es {max}.",attachmentTypeNotAllowed:"{name} no es un tipo de archivo compatible.",attachmentTooMany:"Puedes adjuntar hasta {max} archivos por mensaje.",voiceInput:"Entrada de voz",voiceInputHold:"Mantén pulsado para hablar",voiceListening:"Escuchando...",voicePermissionDenied:"El acceso al micrófono está bloqueado. Permítelo en la configuración de tu navegador para usar la entrada de voz.",voiceNoSpeech:"No se detectó ninguna voz. Inténtalo de nuevo.",voiceNoMicrophone:"No se encontró ningún micrófono.",voiceUnavailable:"La entrada de voz no está disponible en este momento.",readAloud:"Leer en voz alta",pauseReading:"Pausar la lectura",resumeReading:"Reanudar la lectura",stopReading:"Detener la lectura",moreOptions:"Más opciones",copyAsMarkdown:"Copiar como Markdown",downloadAsMarkdown:"Descargar como Markdown",downloadAsJson:"Descargar como JSON",copiedToClipboard:"Copiado al portapapeles",copyFailed:"No se pudo copiar. Prueba a descargarlo.",transcriptTitle:"Transcripción del chat",transcriptExported:"Exportado el {date}",transcriptUser:"Usuario",transcriptAssistant:"Asistente",transcriptAttachments:"Adjuntos:",transcriptSources:"Fuentes:",errorGeneric:"Algo salió mal. Inténtalo de nuevo.",errorConnection:"No se pudo conectar. Inténtalo de nuevo.",errorTimeout:"La solicitud tardó demasiado. Inténtalo de nuevo.",errorRateLimitMinute:"Demasiadas solicitudes. Espera un minuto.",errorRateLimitHour:"Has alcanzado el límite por hora. Inténtalo más tarde.",errorAttachmentRejected:"Se rechazó un adjunto. Quítalo e inténtalo de nuevo.",errorAttachmentQuota:"Límite de subida alcanzado. Inténtalo más tarde.",errorRetry:"Reintentar"},Vn={title:"Chat",subtitle:"Posez-moi vos questions",welcomeMessage:"Bonjour ! Comment puis-je vous aider aujourd'hui ?",closeChat:"Fermer le chat",chatMessages:"Messages du chat",typingIndicator:"L'assistant écrit",placeholder:"Saisissez votre message...",sendMessage:"Envoyer le message",stopGenerating:"Arrêter la génération",toolUsed:"Outil utilisé :",toolDetails:"Détails de l'outil",typeYourMessage:"Saisissez votre message",openChat:"Ouvrir le chat",dismissGreeting:"Ignorer le message d'accueil",attachFile:"Joindre un fichier",removeAttachment:"Retirer la pièce jointe",attachmentsLabel:"Pièces jointes",dropFilesHint:"Déposez les fichiers pour les joindre",attachmentTooLarge:"{name} est trop volumineux. La taille maximale est de {max}.",attachmentTypeNotAllowed:"{name} n'est pas un type de fichier pris en charge.",attachmentTooMany:"Vous pouvez joindre jusqu'à {max} fichiers par message.",voiceInput:"Saisie vocale",voiceInputHold:"Maintenez pour parler",voiceListening:"Écoute en cours...",voicePermissionDenied:"L'accès au microphone est bloqué. Autorisez-le dans les paramètres de votre navigateur pour utiliser la saisie vocale.",voiceNoSpeech:"Aucune voix n'a été détectée. Veuillez réessayer.",voiceNoMicrophone:"Aucun microphone n'a été trouvé.",voiceUnavailable:"La saisie vocale n'est pas disponible pour le moment.",readAloud:"Lire à voix haute",pauseReading:"Mettre la lecture en pause",resumeReading:"Reprendre la lecture",stopReading:"Arrêter la lecture",moreOptions:"Plus d'options",copyAsMarkdown:"Copier en Markdown",downloadAsMarkdown:"Télécharger en Markdown",downloadAsJson:"Télécharger en JSON",copiedToClipboard:"Copié dans le presse-papiers",copyFailed:"Impossible de copier. Essayez plutôt de télécharger.",transcriptTitle:"Transcription du chat",transcriptExported:"Exporté le {date}",transcriptUser:"Utilisateur",transcriptAssistant:"Assistant",transcriptAttachments:"Pièces jointes :",transcriptSources:"Sources :",errorGeneric:"Une erreur s'est produite. Veuillez réessayer.",errorConnection:"Échec de la connexion. Veuillez réessayer.",errorTimeout:"La requête a expiré. Veuillez réessayer.",errorRateLimitMinute:"Trop de requêtes. Veuillez patienter une minute.",errorRateLimitHour:"Limite horaire atteinte. Veuillez réessayer plus tard.",errorAttachmentRejected:"Une pièce jointe a été refusée. Retirez-la et réessayez.",errorAttachmentQuota:"Limite d'envoi atteinte. Veuillez réessayer plus tard.",errorRetry:"Réessayer"},Kn={title:"Chat",subtitle:"Fragen Sie mich alles",welcomeMessage:"Hallo! Wie kann ich Ihnen heute helfen?",closeChat:"Chat schließen",chatMessages:"Chat-Nachrichten",typingIndicator:"Der Assistent schreibt",placeholder:"Geben Sie Ihre Nachricht ein...",sendMessage:"Nachricht senden",stopGenerating:"Generierung stoppen",toolUsed:"Verwendetes Tool:",toolDetails:"Tool-Details",typeYourMessage:"Geben Sie Ihre Nachricht ein",openChat:"Chat öffnen",dismissGreeting:"Begrüßung schließen",attachFile:"Datei anhängen",removeAttachment:"Anhang entfernen",attachmentsLabel:"Anhänge",dropFilesHint:"Dateien hier ablegen, um sie anzuhängen",attachmentTooLarge:"{name} ist zu groß. Die maximale Größe beträgt {max}.",attachmentTypeNotAllowed:"{name} ist kein unterstützter Dateityp.",attachmentTooMany:"Sie können bis zu {max} Dateien pro Nachricht anhängen.",voiceInput:"Spracheingabe",voiceInputHold:"Zum Sprechen gedrückt halten",voiceListening:"Ich höre zu...",voicePermissionDenied:"Der Zugriff auf das Mikrofon ist blockiert. Erlauben Sie ihn in den Einstellungen Ihres Browsers, um die Spracheingabe zu nutzen.",voiceNoSpeech:"Es wurde keine Sprache erkannt. Bitte versuchen Sie es erneut.",voiceNoMicrophone:"Es wurde kein Mikrofon gefunden.",voiceUnavailable:"Die Spracheingabe ist momentan nicht verfügbar.",readAloud:"Vorlesen",pauseReading:"Vorlesen pausieren",resumeReading:"Vorlesen fortsetzen",stopReading:"Vorlesen beenden",moreOptions:"Weitere Optionen",copyAsMarkdown:"Als Markdown kopieren",downloadAsMarkdown:"Als Markdown herunterladen",downloadAsJson:"Als JSON herunterladen",copiedToClipboard:"In die Zwischenablage kopiert",copyFailed:"Kopieren nicht möglich. Bitte stattdessen herunterladen.",transcriptTitle:"Chat-Protokoll",transcriptExported:"Exportiert am {date}",transcriptUser:"Nutzer",transcriptAssistant:"Assistent",transcriptAttachments:"Anhänge:",transcriptSources:"Quellen:",errorGeneric:"Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut.",errorConnection:"Verbindung fehlgeschlagen. Bitte versuchen Sie es erneut.",errorTimeout:"Zeitüberschreitung der Anfrage. Bitte versuchen Sie es erneut.",errorRateLimitMinute:"Zu viele Anfragen. Bitte warten Sie eine Minute.",errorRateLimitHour:"Stündliches Limit erreicht. Bitte versuchen Sie es später erneut.",errorAttachmentRejected:"Ein Anhang wurde abgelehnt. Bitte entfernen Sie ihn und versuchen Sie es erneut.",errorAttachmentQuota:"Upload-Limit erreicht. Bitte versuchen Sie es später erneut.",errorRetry:"Erneut versuchen"},ke={en:Je,es:Gn,fr:Vn,de:Kn};function We(e){if(!e)return;const t=e.toLowerCase().split("-")[0];return Object.prototype.hasOwnProperty.call(ke,t)?t:void 0}function Ae(){const e=typeof document<"u"?We(document.documentElement.lang):void 0;if(e)return e;const t=typeof navigator<"u"?We(navigator.language):void 0;return t||"en"}function tt(e={}){const{locale:t,translations:n}=e,r=ke[t??Ae()];return n?{...r,...n}:{...r}}const Ge=["accent","accentText","accentSoft","accentTextMuted","surface","surfaceMuted","text","textMuted","border","userBubble","userBubbleText","assistantBubble","assistantBubbleText","field","error","errorSurface","errorText","link","scrim"],qn=["sm","md","lg","full","tail"],Yn=["elevated","floating","floatingHover"],Zn=["heading","body"],Ce={default:{name:"default"},minimal:{name:"minimal",colors:{accent:"#171717",accentText:"#ffffff",surface:"#ffffff",surfaceMuted:"#f5f5f5",text:"#171717",textMuted:"#737373",border:"#e5e5e5",link:"#171717"},colorsDark:{accent:"#fafafa",accentText:"#171717",surface:"#0a0a0a",surfaceMuted:"#1c1c1c",text:"#fafafa",textMuted:"#a3a3a3",border:"#2e2e2e",field:"#1c1c1c",link:"#fafafa"},radii:{sm:"4px",md:"6px",lg:"10px"},shadows:{elevated:"0 4px 16px rgb(0 0 0 / 0.12)",floating:"0 2px 8px rgb(0 0 0 / 0.12)",floatingHover:"0 4px 12px rgb(0 0 0 / 0.16)"}},playful:{name:"playful",colors:{accent:"#8b5cf6",surfaceMuted:"#f5f3ff",assistantBubbleText:"#4c1d95",link:"#7c3aed"},colorsDark:{accent:"#a78bfa",surfaceMuted:"#2e1065",assistantBubbleText:"#ede9fe",link:"#c4b5fd"},radii:{sm:"12px",md:"16px",lg:"24px",tail:"8px"},shadows:{elevated:"0 24px 48px -12px rgb(139 92 246 / 0.35)",floating:"0 10px 20px -5px rgb(139 92 246 / 0.4)",floatingHover:"0 16px 28px -6px rgb(139 92 246 / 0.5)"},fonts:{heading:"ui-rounded, 'Hiragino Maru Gothic ProN', system-ui",body:"ui-rounded, 'Hiragino Maru Gothic ProN', system-ui"}},corporate:{name:"corporate",colors:{accent:"#1e3a5f",surfaceMuted:"#f3f4f6",text:"#1f2937",textMuted:"#6b7280",border:"#d1d5db",link:"#1d4ed8"},colorsDark:{accent:"#2c5282",link:"#93c5fd"},radii:{sm:"4px",md:"6px",lg:"8px",tail:"2px"},shadows:{elevated:"0 8px 24px rgb(15 23 42 / 0.16)",floating:"0 4px 12px rgb(15 23 42 / 0.18)",floatingHover:"0 6px 16px rgb(15 23 42 / 0.24)"},fonts:{heading:"'Segoe UI', 'Helvetica Neue', Arial, system-ui",body:"'Segoe UI', 'Helvetica Neue', Arial, system-ui"}}};function Jn(e){return Object.prototype.hasOwnProperty.call(Ce,e)}const Qn=new Set(["light","dark","auto"]);function Xn(e){if(e===void 0)return{mode:"light"};if(typeof e=="string"){if(Qn.has(e))return{mode:e};if(Jn(e)){const t=Ce[e];return{mode:t.colorScheme??"light",theme:t}}return{mode:"light",url:e}}return{mode:e.colorScheme??"light",theme:e}}function er(e){return e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}function tr(e,t){console.warn(`[Claudius] Ignoring unknown theme token "${t}" in "${e}"`)}function me(e,t,n,r,s,o=""){if(s)for(const[i,l]of Object.entries(s)){if(!r.includes(i)){tr(t,i);continue}typeof l=="string"&&(e[`${n}${er(i)}${o}`]=l)}}function nr(e){const t={};me(t,"colors","--cl-color-",Ge,e.colors);for(const[n,r]of Object.entries({...t}))t[`${n}-dark`]=r;return me(t,"colorsDark","--cl-color-",Ge,e.colorsDark,"-dark"),me(t,"radii","--cl-radius-",qn,e.radii),me(t,"shadows","--cl-shadow-",Yn,e.shadows),me(t,"fonts","--cl-font-",Zn,e.fonts),t}function rr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function sr(e){const t=c.useMemo(()=>Xn(e),[e]),[n,r]=c.useState(null),s=t.url;c.useEffect(()=>{if(r(null),!s)return;const u=new AbortController;return fetch(s,{signal:u.signal}).then(d=>{if(!d.ok)throw new Error(`HTTP ${d.status}`);return d.json()}).then(d=>{if(!rr(d))throw new Error("theme JSON must be an object");r(d)}).catch(d=>{u.signal.aborted||console.error(`[Claudius] Failed to load theme from ${s}:`,d)}),()=>u.abort()},[s]);const o=t.theme??n??null,i=(n==null?void 0:n.colorScheme)??t.mode,l=c.useMemo(()=>o?nr(o):{},[o]);return{mode:i,cssVars:l}}const nt="claudius:triggers:dismissed";function or(){if(typeof window>"u")return!1;try{return window.sessionStorage.getItem(nt)==="1"}catch{return!1}}function ar(){if(!(typeof window>"u"))try{window.sessionStorage.setItem(nt,"1")}catch{}}function ir({apiUrl:e,title:t,subtitle:n,welcomeMessage:r,placeholder:s,persistMessages:o,storageKeyPrefix:i,requestTimeoutMs:l,theme:u="light",accentColor:d,position:f="bottom-right",locale:w,translations:S,triggers:x,plugins:h,streaming:p=!0,attachments:j=!1,voice:b=!1,conversationExport:E=!1}){const[y,v]=c.useState(!1),k=c.useMemo(()=>pt(j),[j]),L=c.useMemo(()=>w??Ae(),[w]),C=c.useMemo(()=>Qt(b,L),[b,L]),R=c.useMemo(()=>Qe(L),[L]),[P,N]=c.useState(null),[$,V]=c.useState(or),F=c.useRef(!1),K=At("(max-width: 639px)"),U=c.useMemo(()=>tt({locale:w,translations:S}),[w,S]),{messages:te,isLoading:ne,isStreaming:re,streamingMessageId:X,error:m,canRetry:I,sendMessage:O,stop:Z,retry:J}=kt({apiUrl:e,persistMessages:o,storageKeyPrefix:i,timeoutMs:l,translations:U,plugins:h,streaming:p}),Q=c.useRef(null),_=c.useRef(y),{mode:B,cssVars:T}=sr(u),[A,M]=c.useState(!1);c.useEffect(()=>{if(B!=="auto")return;const Y=window.matchMedia("(prefers-color-scheme: dark)");M(Y.matches);const xe=g=>M(g.matches);return Y.addEventListener("change",xe),()=>Y.removeEventListener("change",xe)},[B]),c.useEffect(()=>{var Y;_.current&&!y&&((Y=Q.current)==null||Y.focus()),_.current=y},[y]);const z=c.useCallback(()=>{V(!0),ar()},[]),q=c.useCallback(()=>{v(!1),F.current&&(F.current=!1,z())},[z]),se=c.useCallback(()=>{v(Y=>!Y)},[]),W=c.useCallback(()=>{F.current=!0,N(null),v(!0)},[]),de=c.useCallback(Y=>{N(Y)},[]),oe=c.useCallback(()=>{N(null),W()},[W]),H=c.useCallback(()=>{N(null),z()},[z]);Mt({triggers:x,enabled:!$&&!y,onOpen:W,onGreeting:de});const ee=B==="dark"||B==="auto"&&A,ie={...T,...d?{"--cl-color-accent":d,"--cl-color-accent-dark":d}:{}},ae=Object.keys(ie).length>0?ie:void 0;return a.jsx("div",{className:"claudius-root",style:ae,children:a.jsxs("div",{"data-claudius-dark":ee?"true":"false",children:[y&&K&&a.jsx("div",{className:"claudius-scrim fixed inset-0 z-40 bg-claudius-scrim",onClick:q,"aria-hidden":"true"}),y&&a.jsx(Hn,{messages:te,isLoading:ne,isStreaming:re,streamingMessageId:X,error:m,canRetry:I,onSend:O,onStop:Z,onRetry:J,onClose:q,title:t??U.title,subtitle:n??U.subtitle,welcomeMessage:r??U.welcomeMessage,placeholder:s??U.placeholder,position:f,translations:U,isMobile:K,attachments:k,voice:C,conversationExport:E===!0,locale:R}),!(y&&K)&&a.jsx(Dt,{ref:Q,isOpen:y,onClick:se,position:f,translations:U}),!y&&P&&a.jsx(Wn,{message:P,position:f,onOpen:oe,onDismiss:H,dismissLabel:U.dismissGreeting})]})})}function cr(e){const{onEvent:t,includeContent:n=!0}=e,r=s=>n?s:"";return{name:"analytics",onBeforeSend(s){t({type:"message_sent",role:"user",content:r(s.content),chars:s.content.length})},onAfterReceive(s){t({type:"message_received",role:"assistant",content:r(s.content),chars:s.content.length})},onError(s){t({type:"chat_error",message:s.message,code:s.code})}}}const rt=[/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,/\b\d{3}-\d{2}-\d{4}\b/g,/\b(?:\d[ -]?){13,16}\b/g,/\b(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b/g];function st(e,t,n){return t.reduce((r,s)=>(s.lastIndex=0,r.replace(s,n)),e)}function lr(e={}){const{patterns:t=rt,replacement:n="[redacted]",redactReplies:r=!1}=e,s=o=>{const i=st(o.content,t,n);if(i!==o.content)return{...o,content:i}};return{name:"redact-pii",onBeforeSend:s,onAfterReceive:r?s:void 0}}function ur(e,t,n){return typeof e=="function"?e(t):e instanceof RegExp?e.test(t):n?t.includes(e):t.toLowerCase().includes(e.toLowerCase())}function dr(e){const{rules:t,caseSensitive:n=!1}=e;return{name:"canned-responses",onBeforeSend(r,s){for(const o of t)if(ur(o.match,r.content,n)){s.respondWith(o.reply);return}}}}exports.ChatApiClient=Ve;exports.ChatApiError=G;exports.ChatWidget=ir;exports.DEFAULT_ATTACHMENT_OPTIONS=ge;exports.DEFAULT_PII_PATTERNS=rt;exports.DebounceError=ve;exports.builtinThemes=Ce;exports.createTranslations=Kt;exports.defaultTranslations=Ee;exports.detectLocale=Ae;exports.locales=ke;exports.pluginAnalytics=cr;exports.pluginCannedResponses=dr;exports.pluginRedactPII=lr;exports.redactText=st;exports.resolveTranslations=tt;
17
+ `}function Zn(e){const t=e.filter(n=>n!==null&&typeof n=="object").map(n=>n.attachments===void 0?n:{...n,attachments:ve(n.attachments)});return JSON.stringify(Ye(t),null,2)+`
18
+ `}function He(e,t={}){const n=t.now??new Date;let r;try{const s=new Intl.DateTimeFormat("en",{timeZone:t.timeZone,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(n),a=i=>{var c;return((c=s.find(l=>l.type===i))==null?void 0:c.value)??""};r=`${a("year")}-${a("month")}-${a("day")}`}catch{r=n.toISOString().slice(0,10)}return`chat-transcript-${r}.${e}`}function Jn(e){const t=document.activeElement;let n=null;try{return n=document.createElement("textarea"),n.value=e,n.setAttribute("readonly",""),n.setAttribute("aria-hidden","true"),n.tabIndex=-1,n.style.position="fixed",n.style.top="0",n.style.left="0",n.style.opacity="0",document.body.appendChild(n),n.focus({preventScroll:!0}),n.select(),document.execCommand("copy")}catch{return!1}finally{try{n==null||n.remove()}catch{}try{t==null||t.focus()}catch{}}}async function Qn(e){var t;try{if((t=navigator.clipboard)!=null&&t.writeText)return await navigator.clipboard.writeText(e),!0}catch{}try{return Jn(e)}catch{return!1}}const Xn=4e4;function ze(e,t,n){const r=URL.createObjectURL(new Blob([t],{type:n})),s=document.createElement("a");s.href=r,s.download=e,s.style.display="none",document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(r),Xn)}const er=4e3;function tr({enabled:e,messages:t,busy:n,locale:r,translations:s}){const a=s??Re,[i,c]=u.useState(null),l=u.useRef(null),d=u.useRef(!0);u.useEffect(()=>(d.current=!0,()=>{d.current=!1,l.current&&clearTimeout(l.current)}),[]);const h=u.useCallback(()=>{l.current&&clearTimeout(l.current),l.current=null,c(null)},[]),j=u.useCallback(g=>{d.current&&(l.current&&clearTimeout(l.current),c(g),l.current=setTimeout(()=>{l.current=null,c(null)},er))},[]);return{items:u.useMemo(()=>{if(!e)return[];const g=n||t.length===0,p=()=>Yn(t,{locale:r,labels:{title:a.transcriptTitle,exported:a.transcriptExported,user:a.transcriptUser,assistant:a.transcriptAssistant,attachments:a.transcriptAttachments,sources:a.transcriptSources,toolUsed:a.toolUsed}});return[{id:"copy-markdown",label:a.copyAsMarkdown,disabled:g,onSelect:()=>{Qn(p()).then(f=>j(f?a.copiedToClipboard:a.copyFailed))}},{id:"download-markdown",label:a.downloadAsMarkdown,disabled:g,onSelect:()=>ze(He("md"),p(),"text/markdown;charset=utf-8")},{id:"download-json",label:a.downloadAsJson,disabled:g,onSelect:()=>ze(He("json"),Zn(t),"application/json")}]},[e,n,t,r,a,j]),status:i,clearStatus:h}}const nr=/\*\*([^*]+)\*\*/g,rr=/\*([^*]+)\*/g,sr=/https?:\/\/[^\s)]+/g;function or(e){return e.replace(nr,"$1").replace(rr,"$1").replace(sr,t=>{var s;const n=((s=t.match(/[.,;:!?'"]+$/))==null?void 0:s[0])??"",r=n?t.slice(0,-n.length):t;try{return new URL(r).hostname+n}catch{return t}})}const ar={"bottom-right":"bottom-24 right-3 sm:right-6","bottom-left":"bottom-24 left-3 sm:left-6","top-right":"top-24 right-3 sm:right-6","top-left":"top-24 left-3 sm:left-6"};function ir({messages:e,isLoading:t,isStreaming:n=!1,streamingMessageId:r=null,error:s,canRetry:a=!1,onSend:i,onStop:c,onRetry:l,onClose:d,title:h="Chat",subtitle:j="Ask me anything",welcomeMessage:R="Hi! How can I help you today?",placeholder:g,position:p="bottom-right",translations:f,isMobile:T=!1,attachments:x=null,voice:w=null,conversationExport:b=!1,locale:y="en-US",citations:N=null}){const S=u.useId(),E=u.useRef(null),M=u.useRef(null),[k,Q]=u.useState(null);In(E,!0);const L=On((w==null?void 0:w.lang)??"en-US"),F=!!(w!=null&&w.output)&&L.isSupported,Y={play:(f==null?void 0:f.readAloud)??"Read aloud",pause:(f==null?void 0:f.pauseReading)??"Pause reading",resume:(f==null?void 0:f.resumeReading)??"Resume reading",stop:(f==null?void 0:f.stopReading)??"Stop reading"},K=tr({enabled:b,messages:e,busy:t,locale:y,translations:f}),q=(f==null?void 0:f.opensInNewTab)??"(opens in a new tab)",_=u.useMemo(()=>N?{...N,labels:{sources:(f==null?void 0:f.sources)??"Sources",showAllSources:(f==null?void 0:f.showAllSources)??"Show all ({count})",showFewerSources:(f==null?void 0:f.showFewerSources)??"Show fewer",citation:(f==null?void 0:f.citation)??"Source {n}: {title}",opensInNewTab:q}}:void 0,[N,f,q]),B=v=>{var H;return or(_&&((H=v.sources)!=null&&H.length)?Bt(v.content,v.sources.length):v.content)},{offsetY:re}=Ln(M,d,T),ie=re!==0,ce=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-reduced-motion: reduce)").matches:!1;u.useEffect(()=>{const v=M.current;v&&(v.scrollTop=v.scrollHeight)},[e,t]),u.useEffect(()=>{const v=H=>{H.key==="Escape"&&!H.isComposing&&!H.defaultPrevented&&d()};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[d]);const A=(f==null?void 0:f.closeChat)??"Close chat",$=(f==null?void 0:f.chatMessages)??"Chat messages",I=[...e].reverse().find(v=>v.role==="assistant");return o.jsxs("div",{ref:E,role:"dialog","aria-modal":T?"true":void 0,"aria-labelledby":S,className:T?"claudius-bottom-sheet fixed inset-x-0 bottom-0 z-50 flex h-[90vh] w-full flex-col overflow-hidden rounded-t-claudius-lg bg-claudius-surface shadow-claudius-elevated font-body":`fixed ${ar[p]} z-50 flex h-[min(500px,calc(100vh-7rem))] w-[calc(100vw-1.5rem)] max-w-[380px] sm:max-w-[400px] md:max-w-[440px] flex-col overflow-hidden rounded-claudius-lg bg-claudius-surface shadow-claudius-elevated font-body`,style:T&&!ce?{transform:`translateY(${Math.max(0,re)}px)`}:void 0,"data-dragging":ie||void 0,children:[T&&o.jsx("div",{className:"flex justify-center py-2","aria-hidden":"true",children:o.jsx("div",{className:"h-1 w-8 rounded-claudius-full bg-claudius-border"})}),o.jsx(En,{title:h,subtitle:j,titleId:S,closeLabel:A,onClose:d,actions:b?o.jsx(Mn,{label:(f==null?void 0:f.moreOptions)??"More options",items:K.items,onOpen:K.clearStatus}):void 0}),o.jsxs("div",{className:"relative flex-1 overflow-hidden",children:[k&&o.jsx(An,{sources:k.sources,onClose:()=>Q(null)}),b&&o.jsx("div",{role:"status",className:"pointer-events-none absolute inset-x-0 top-2 z-10 flex justify-center px-4",children:K.status&&o.jsx("span",{className:"rounded-claudius-full bg-claudius-text px-3 py-1 text-xs text-claudius-surface shadow-claudius-elevated",children:K.status})}),o.jsxs("div",{ref:M,role:"log","aria-label":$,className:"h-full space-y-3 overflow-y-auto px-4 py-4",children:[e.length===0&&!s&&o.jsx("div",{className:"mr-auto flex max-w-[85%]",children:o.jsx("div",{className:"rounded-claudius-bubble rounded-bl-claudius-tail bg-claudius-assistant-bubble px-4 py-2.5 text-sm leading-relaxed text-claudius-assistant-bubble-text",children:R})}),e.map(v=>o.jsx(ln,{role:v.role,content:v.content,isStreaming:v.id===r,sources:v.sources,attachments:v.attachments,toolUses:v.toolUses,toolUsedLabel:f==null?void 0:f.toolUsed,toolDetailsLabel:f==null?void 0:f.toolDetails,citations:_,linkNewTabLabel:q,isSourceActive:_?void 0:(k==null?void 0:k.messageId)===v.id,onSourceClick:_?void 0:()=>{(k==null?void 0:k.messageId)===v.id?Q(null):v.sources&&v.sources.length>0&&Q({messageId:v.id,sources:v.sources})},speech:F&&v.role==="assistant"&&v.id!==r&&v.content.trim()!==""?{state:L.activeId!==v.id?"idle":L.isPaused?"paused":"speaking",labels:Y,onPlay:()=>L.speak(v.id,B(v)),onPause:L.pause,onResume:L.resume,onStop:L.cancel}:void 0},v.id)),t&&!(r!==null&&e.some(v=>v.id===r&&v.content.length>0))&&o.jsx(Nn,{label:(f==null?void 0:f.typingIndicator)??"Assistant is typing"}),s&&o.jsx(Cn,{message:s,retryLabel:(f==null?void 0:f.errorRetry)??"Retry",onRetry:a&&l&&!t?l:void 0})]})]}),o.jsx("div",{"data-claudius-live":"assistant","aria-live":"polite","aria-atomic":"true",className:"sr-only",children:I&&I.id!==r?B(I):""}),o.jsx(Sn,{onSend:i,isLoading:t,isStreaming:n,onStop:c,placeholder:g,translations:f,attachments:x,voice:w,onVoiceStart:L.cancel,isReadingAloud:L.activeId!==null})]})}function cr({message:e,position:t,onOpen:n,onDismiss:r,dismissLabel:s}){const a=t.startsWith("bottom"),i=t.endsWith("right"),c=["claudius-greeting-bubble","fixed z-40 max-w-xs",a?"bottom-20":"top-20",i?"right-4":"left-4"].join(" ");return o.jsxs("div",{className:c,role:"status","aria-live":"polite",children:[o.jsx("button",{type:"button",onClick:n,className:"block w-full rounded-claudius-lg bg-claudius-surface p-4 pr-8 text-left text-sm font-body text-claudius-text shadow-claudius-floating ring-1 ring-claudius-border transition hover:shadow-claudius-floating-hover focus:outline-none focus:ring-2 focus:ring-claudius-accent",children:e}),o.jsx("button",{type:"button",onClick:l=>{l.stopPropagation(),r()},"aria-label":s,className:"absolute right-1 top-1 flex h-6 w-6 items-center justify-center rounded-claudius-full text-claudius-text-muted hover:bg-claudius-surface-muted focus:outline-none focus:ring-2 focus:ring-claudius-accent",children:o.jsx("span",{"aria-hidden":"true",children:"×"})})]})}const ur={title:"Chat",subtitle:"Pregúntame lo que quieras",welcomeMessage:"¡Hola! ¿En qué puedo ayudarte hoy?",closeChat:"Cerrar chat",chatMessages:"Mensajes del chat",typingIndicator:"El asistente está escribiendo",placeholder:"Escribe tu mensaje...",sendMessage:"Enviar mensaje",stopGenerating:"Detener la respuesta",toolUsed:"Herramienta usada:",toolDetails:"Detalles de la herramienta",typeYourMessage:"Escribe tu mensaje",openChat:"Abrir chat",dismissGreeting:"Descartar saludo",attachFile:"Adjuntar un archivo",removeAttachment:"Quitar adjunto",attachmentsLabel:"Adjuntos",dropFilesHint:"Suelta los archivos para adjuntarlos",attachmentTooLarge:"{name} es demasiado grande. El tamaño máximo es {max}.",attachmentTypeNotAllowed:"{name} no es un tipo de archivo compatible.",attachmentTooMany:"Puedes adjuntar hasta {max} archivos por mensaje.",voiceInput:"Entrada de voz",voiceInputHold:"Mantén pulsado para hablar",voiceListening:"Escuchando...",voicePermissionDenied:"El acceso al micrófono está bloqueado. Permítelo en la configuración de tu navegador para usar la entrada de voz.",voiceNoSpeech:"No se detectó ninguna voz. Inténtalo de nuevo.",voiceNoMicrophone:"No se encontró ningún micrófono.",voiceUnavailable:"La entrada de voz no está disponible en este momento.",readAloud:"Leer en voz alta",pauseReading:"Pausar la lectura",resumeReading:"Reanudar la lectura",stopReading:"Detener la lectura",moreOptions:"Más opciones",copyAsMarkdown:"Copiar como Markdown",downloadAsMarkdown:"Descargar como Markdown",downloadAsJson:"Descargar como JSON",copiedToClipboard:"Copiado al portapapeles",copyFailed:"No se pudo copiar. Prueba a descargarlo.",transcriptTitle:"Transcripción del chat",transcriptExported:"Exportado el {date}",transcriptUser:"Usuario",transcriptAssistant:"Asistente",transcriptAttachments:"Adjuntos:",transcriptSources:"Fuentes:",sources:"Fuentes",showAllSources:"Mostrar todas ({count})",showFewerSources:"Mostrar menos",citation:"Fuente {n}: {title}",opensInNewTab:"(se abre en una pestaña nueva)",errorGeneric:"Algo salió mal. Inténtalo de nuevo.",errorConnection:"No se pudo conectar. Inténtalo de nuevo.",errorTimeout:"La solicitud tardó demasiado. Inténtalo de nuevo.",errorRateLimitMinute:"Demasiadas solicitudes. Espera un minuto.",errorRateLimitHour:"Has alcanzado el límite por hora. Inténtalo más tarde.",errorAttachmentRejected:"Se rechazó un adjunto. Quítalo e inténtalo de nuevo.",errorAttachmentQuota:"Límite de subida alcanzado. Inténtalo más tarde.",errorRetry:"Reintentar"},lr={title:"Chat",subtitle:"Posez-moi vos questions",welcomeMessage:"Bonjour ! Comment puis-je vous aider aujourd'hui ?",closeChat:"Fermer le chat",chatMessages:"Messages du chat",typingIndicator:"L'assistant écrit",placeholder:"Saisissez votre message...",sendMessage:"Envoyer le message",stopGenerating:"Arrêter la génération",toolUsed:"Outil utilisé :",toolDetails:"Détails de l'outil",typeYourMessage:"Saisissez votre message",openChat:"Ouvrir le chat",dismissGreeting:"Ignorer le message d'accueil",attachFile:"Joindre un fichier",removeAttachment:"Retirer la pièce jointe",attachmentsLabel:"Pièces jointes",dropFilesHint:"Déposez les fichiers pour les joindre",attachmentTooLarge:"{name} est trop volumineux. La taille maximale est de {max}.",attachmentTypeNotAllowed:"{name} n'est pas un type de fichier pris en charge.",attachmentTooMany:"Vous pouvez joindre jusqu'à {max} fichiers par message.",voiceInput:"Saisie vocale",voiceInputHold:"Maintenez pour parler",voiceListening:"Écoute en cours...",voicePermissionDenied:"L'accès au microphone est bloqué. Autorisez-le dans les paramètres de votre navigateur pour utiliser la saisie vocale.",voiceNoSpeech:"Aucune voix n'a été détectée. Veuillez réessayer.",voiceNoMicrophone:"Aucun microphone n'a été trouvé.",voiceUnavailable:"La saisie vocale n'est pas disponible pour le moment.",readAloud:"Lire à voix haute",pauseReading:"Mettre la lecture en pause",resumeReading:"Reprendre la lecture",stopReading:"Arrêter la lecture",moreOptions:"Plus d'options",copyAsMarkdown:"Copier en Markdown",downloadAsMarkdown:"Télécharger en Markdown",downloadAsJson:"Télécharger en JSON",copiedToClipboard:"Copié dans le presse-papiers",copyFailed:"Impossible de copier. Essayez plutôt de télécharger.",transcriptTitle:"Transcription du chat",transcriptExported:"Exporté le {date}",transcriptUser:"Utilisateur",transcriptAssistant:"Assistant",transcriptAttachments:"Pièces jointes :",transcriptSources:"Sources :",sources:"Sources",showAllSources:"Tout afficher ({count})",showFewerSources:"Afficher moins",citation:"Source {n} : {title}",opensInNewTab:"(s'ouvre dans un nouvel onglet)",errorGeneric:"Une erreur s'est produite. Veuillez réessayer.",errorConnection:"Échec de la connexion. Veuillez réessayer.",errorTimeout:"La requête a expiré. Veuillez réessayer.",errorRateLimitMinute:"Trop de requêtes. Veuillez patienter une minute.",errorRateLimitHour:"Limite horaire atteinte. Veuillez réessayer plus tard.",errorAttachmentRejected:"Une pièce jointe a été refusée. Retirez-la et réessayez.",errorAttachmentQuota:"Limite d'envoi atteinte. Veuillez réessayer plus tard.",errorRetry:"Réessayer"},dr={title:"Chat",subtitle:"Fragen Sie mich alles",welcomeMessage:"Hallo! Wie kann ich Ihnen heute helfen?",closeChat:"Chat schließen",chatMessages:"Chat-Nachrichten",typingIndicator:"Der Assistent schreibt",placeholder:"Geben Sie Ihre Nachricht ein...",sendMessage:"Nachricht senden",stopGenerating:"Generierung stoppen",toolUsed:"Verwendetes Tool:",toolDetails:"Tool-Details",typeYourMessage:"Geben Sie Ihre Nachricht ein",openChat:"Chat öffnen",dismissGreeting:"Begrüßung schließen",attachFile:"Datei anhängen",removeAttachment:"Anhang entfernen",attachmentsLabel:"Anhänge",dropFilesHint:"Dateien hier ablegen, um sie anzuhängen",attachmentTooLarge:"{name} ist zu groß. Die maximale Größe beträgt {max}.",attachmentTypeNotAllowed:"{name} ist kein unterstützter Dateityp.",attachmentTooMany:"Sie können bis zu {max} Dateien pro Nachricht anhängen.",voiceInput:"Spracheingabe",voiceInputHold:"Zum Sprechen gedrückt halten",voiceListening:"Ich höre zu...",voicePermissionDenied:"Der Zugriff auf das Mikrofon ist blockiert. Erlauben Sie ihn in den Einstellungen Ihres Browsers, um die Spracheingabe zu nutzen.",voiceNoSpeech:"Es wurde keine Sprache erkannt. Bitte versuchen Sie es erneut.",voiceNoMicrophone:"Es wurde kein Mikrofon gefunden.",voiceUnavailable:"Die Spracheingabe ist momentan nicht verfügbar.",readAloud:"Vorlesen",pauseReading:"Vorlesen pausieren",resumeReading:"Vorlesen fortsetzen",stopReading:"Vorlesen beenden",moreOptions:"Weitere Optionen",copyAsMarkdown:"Als Markdown kopieren",downloadAsMarkdown:"Als Markdown herunterladen",downloadAsJson:"Als JSON herunterladen",copiedToClipboard:"In die Zwischenablage kopiert",copyFailed:"Kopieren nicht möglich. Bitte stattdessen herunterladen.",transcriptTitle:"Chat-Protokoll",transcriptExported:"Exportiert am {date}",transcriptUser:"Nutzer",transcriptAssistant:"Assistent",transcriptAttachments:"Anhänge:",transcriptSources:"Quellen:",sources:"Quellen",showAllSources:"Alle anzeigen ({count})",showFewerSources:"Weniger anzeigen",citation:"Quelle {n}: {title}",opensInNewTab:"(öffnet in einem neuen Tab)",errorGeneric:"Etwas ist schiefgelaufen. Bitte versuchen Sie es erneut.",errorConnection:"Verbindung fehlgeschlagen. Bitte versuchen Sie es erneut.",errorTimeout:"Zeitüberschreitung der Anfrage. Bitte versuchen Sie es erneut.",errorRateLimitMinute:"Zu viele Anfragen. Bitte warten Sie eine Minute.",errorRateLimitHour:"Stündliches Limit erreicht. Bitte versuchen Sie es später erneut.",errorAttachmentRejected:"Ein Anhang wurde abgelehnt. Bitte entfernen Sie ihn und versuchen Sie es erneut.",errorAttachmentQuota:"Upload-Limit erreicht. Bitte versuchen Sie es später erneut.",errorRetry:"Erneut versuchen"},Ee={en:tt,es:ur,fr:lr,de:dr};function We(e){if(!e)return;const t=e.toLowerCase().split("-")[0];return Object.prototype.hasOwnProperty.call(Ee,t)?t:void 0}function Ce(){const e=typeof document<"u"?We(document.documentElement.lang):void 0;if(e)return e;const t=typeof navigator<"u"?We(navigator.language):void 0;return t||"en"}function ot(e={}){const{locale:t,translations:n}=e,r=Ee[t??Ce()];return n?{...r,...n}:{...r}}const Ge=["accent","accentText","accentSoft","accentTextMuted","surface","surfaceMuted","text","textMuted","border","userBubble","userBubbleText","assistantBubble","assistantBubbleText","field","error","errorSurface","errorText","link","scrim"],fr=["sm","md","lg","full","tail"],hr=["elevated","floating","floatingHover"],pr=["heading","body"],Ne={default:{name:"default"},minimal:{name:"minimal",colors:{accent:"#171717",accentText:"#ffffff",surface:"#ffffff",surfaceMuted:"#f5f5f5",text:"#171717",textMuted:"#737373",border:"#e5e5e5",link:"#171717"},colorsDark:{accent:"#fafafa",accentText:"#171717",surface:"#0a0a0a",surfaceMuted:"#1c1c1c",text:"#fafafa",textMuted:"#a3a3a3",border:"#2e2e2e",field:"#1c1c1c",link:"#fafafa"},radii:{sm:"4px",md:"6px",lg:"10px"},shadows:{elevated:"0 4px 16px rgb(0 0 0 / 0.12)",floating:"0 2px 8px rgb(0 0 0 / 0.12)",floatingHover:"0 4px 12px rgb(0 0 0 / 0.16)"}},playful:{name:"playful",colors:{accent:"#8b5cf6",surfaceMuted:"#f5f3ff",assistantBubbleText:"#4c1d95",link:"#7c3aed"},colorsDark:{accent:"#a78bfa",surfaceMuted:"#2e1065",assistantBubbleText:"#ede9fe",link:"#c4b5fd"},radii:{sm:"12px",md:"16px",lg:"24px",tail:"8px"},shadows:{elevated:"0 24px 48px -12px rgb(139 92 246 / 0.35)",floating:"0 10px 20px -5px rgb(139 92 246 / 0.4)",floatingHover:"0 16px 28px -6px rgb(139 92 246 / 0.5)"},fonts:{heading:"ui-rounded, 'Hiragino Maru Gothic ProN', system-ui",body:"ui-rounded, 'Hiragino Maru Gothic ProN', system-ui"}},corporate:{name:"corporate",colors:{accent:"#1e3a5f",surfaceMuted:"#f3f4f6",text:"#1f2937",textMuted:"#6b7280",border:"#d1d5db",link:"#1d4ed8"},colorsDark:{accent:"#2c5282",link:"#93c5fd"},radii:{sm:"4px",md:"6px",lg:"8px",tail:"2px"},shadows:{elevated:"0 8px 24px rgb(15 23 42 / 0.16)",floating:"0 4px 12px rgb(15 23 42 / 0.18)",floatingHover:"0 6px 16px rgb(15 23 42 / 0.24)"},fonts:{heading:"'Segoe UI', 'Helvetica Neue', Arial, system-ui",body:"'Segoe UI', 'Helvetica Neue', Arial, system-ui"}}};function mr(e){return Object.prototype.hasOwnProperty.call(Ne,e)}const gr=new Set(["light","dark","auto"]);function xr(e){if(e===void 0)return{mode:"light"};if(typeof e=="string"){if(gr.has(e))return{mode:e};if(mr(e)){const t=Ne[e];return{mode:t.colorScheme??"light",theme:t}}return{mode:"light",url:e}}return{mode:e.colorScheme??"light",theme:e}}function br(e){return e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}function yr(e,t){console.warn(`[Claudius] Ignoring unknown theme token "${t}" in "${e}"`)}function xe(e,t,n,r,s,a=""){if(s)for(const[i,c]of Object.entries(s)){if(!r.includes(i)){yr(t,i);continue}typeof c=="string"&&(e[`${n}${br(i)}${a}`]=c)}}function wr(e){const t={};xe(t,"colors","--cl-color-",Ge,e.colors);for(const[n,r]of Object.entries({...t}))t[`${n}-dark`]=r;return xe(t,"colorsDark","--cl-color-",Ge,e.colorsDark,"-dark"),xe(t,"radii","--cl-radius-",fr,e.radii),xe(t,"shadows","--cl-shadow-",hr,e.shadows),xe(t,"fonts","--cl-font-",pr,e.fonts),t}function vr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function jr(e){const t=u.useMemo(()=>xr(e),[e]),[n,r]=u.useState(null),s=t.url;u.useEffect(()=>{if(r(null),!s)return;const l=new AbortController;return fetch(s,{signal:l.signal}).then(d=>{if(!d.ok)throw new Error(`HTTP ${d.status}`);return d.json()}).then(d=>{if(!vr(d))throw new Error("theme JSON must be an object");r(d)}).catch(d=>{l.signal.aborted||console.error(`[Claudius] Failed to load theme from ${s}:`,d)}),()=>l.abort()},[s]);const a=t.theme??n??null,i=(n==null?void 0:n.colorScheme)??t.mode,c=u.useMemo(()=>a?wr(a):{},[a]);return{mode:i,cssVars:c}}const at="claudius:triggers:dismissed";function Sr(){if(typeof window>"u")return!1;try{return window.sessionStorage.getItem(at)==="1"}catch{return!1}}function Rr(){if(!(typeof window>"u"))try{window.sessionStorage.setItem(at,"1")}catch{}}function Tr({apiUrl:e,title:t,subtitle:n,welcomeMessage:r,placeholder:s,persistMessages:a,storageKeyPrefix:i,requestTimeoutMs:c,theme:l="light",accentColor:d,position:h="bottom-right",locale:j,translations:R,triggers:g,plugins:p,streaming:f=!0,attachments:T=!1,voice:x=!1,conversationExport:w=!1,citations:b=!1}){const[y,N]=u.useState(!1),S=u.useMemo(()=>bt(T),[T]),E=u.useMemo(()=>j??Ce(),[j]),M=u.useMemo(()=>gn(x,E),[x,E]),k=u.useMemo(()=>Ft(b),[b]),Q=u.useMemo(()=>nt(E),[E]),[L,F]=u.useState(null),[Y,K]=u.useState(Sr),q=u.useRef(!1),_=Lt("(max-width: 639px)"),B=u.useMemo(()=>ot({locale:j,translations:R}),[j,R]),{messages:re,isLoading:ie,isStreaming:ce,streamingMessageId:A,error:$,canRetry:I,sendMessage:v,stop:H,retry:z}=Mt({apiUrl:e,persistMessages:a,storageKeyPrefix:i,timeoutMs:c,translations:B,plugins:p,streaming:f,citations:k!==null}),ee=u.useRef(null),P=u.useRef(y),{mode:Z,cssVars:J}=jr(l),[C,U]=u.useState(!1);u.useEffect(()=>{if(Z!=="auto")return;const m=window.matchMedia("(prefers-color-scheme: dark)");U(m.matches);const D=ae=>U(ae.matches);return m.addEventListener("change",D),()=>m.removeEventListener("change",D)},[Z]),u.useEffect(()=>{var m;P.current&&!y&&((m=ee.current)==null||m.focus()),P.current=y},[y]);const O=u.useCallback(()=>{K(!0),Rr()},[]),G=u.useCallback(()=>{N(!1),q.current&&(q.current=!1,O())},[O]),te=u.useCallback(()=>{N(m=>!m)},[]),se=u.useCallback(()=>{q.current=!0,F(null),N(!0)},[]),X=u.useCallback(m=>{F(m)},[]),he=u.useCallback(()=>{F(null),se()},[se]),ue=u.useCallback(()=>{F(null),O()},[O]);It({triggers:g,enabled:!Y&&!y,onOpen:se,onGreeting:X});const W=Z==="dark"||Z==="auto"&&C,ne={...J,...d?{"--cl-color-accent":d,"--cl-color-accent-dark":d}:{}},oe=Object.keys(ne).length>0?ne:void 0;return o.jsx("div",{className:"claudius-root",style:oe,children:o.jsxs("div",{"data-claudius-dark":W?"true":"false",children:[y&&_&&o.jsx("div",{className:"claudius-scrim fixed inset-0 z-40 bg-claudius-scrim",onClick:G,"aria-hidden":"true"}),y&&o.jsx(ir,{messages:re,isLoading:ie,isStreaming:ce,streamingMessageId:A,error:$,canRetry:I,onSend:v,onStop:H,onRetry:z,onClose:G,title:t??B.title,subtitle:n??B.subtitle,welcomeMessage:r??B.welcomeMessage,placeholder:s??B.placeholder,position:h,translations:B,isMobile:_,attachments:S,voice:M,conversationExport:w===!0,locale:Q,citations:k}),!(y&&_)&&o.jsx($t,{ref:ee,isOpen:y,onClick:te,position:h,translations:B}),!y&&L&&o.jsx(cr,{message:L,position:h,onOpen:he,onDismiss:ue,dismissLabel:B.dismissGreeting})]})})}function kr(e){const{onEvent:t,includeContent:n=!0}=e,r=s=>n?s:"";return{name:"analytics",onBeforeSend(s){t({type:"message_sent",role:"user",content:r(s.content),chars:s.content.length})},onAfterReceive(s){t({type:"message_received",role:"assistant",content:r(s.content),chars:s.content.length})},onError(s){t({type:"chat_error",message:s.message,code:s.code})}}}const it=[/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,/\b\d{3}-\d{2}-\d{4}\b/g,/\b(?:\d[ -]?){13,16}\b/g,/\b(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b/g];function ct(e,t,n){return t.reduce((r,s)=>(s.lastIndex=0,r.replace(s,n)),e)}function Ar(e={}){const{patterns:t=it,replacement:n="[redacted]",redactReplies:r=!1}=e,s=a=>{const i=ct(a.content,t,n);if(i!==a.content)return{...a,content:i}};return{name:"redact-pii",onBeforeSend:s,onAfterReceive:r?s:void 0}}function Er(e,t,n){return typeof e=="function"?e(t):e instanceof RegExp?e.test(t):n?t.includes(e):t.toLowerCase().includes(e.toLowerCase())}function Cr(e){const{rules:t,caseSensitive:n=!1}=e;return{name:"canned-responses",onBeforeSend(r,s){for(const a of t)if(Er(a.match,r.content,n)){s.respondWith(a.reply);return}}}}exports.ChatApiClient=Ve;exports.ChatApiError=V;exports.ChatWidget=Tr;exports.DEFAULT_ATTACHMENT_OPTIONS=be;exports.DEFAULT_CITATIONS_OPTIONS=Ze;exports.DEFAULT_PII_PATTERNS=it;exports.DebounceError=je;exports.builtinThemes=Ne;exports.createTranslations=dn;exports.defaultTranslations=Re;exports.detectLocale=Ce;exports.locales=Ee;exports.pluginAnalytics=kr;exports.pluginCannedResponses=Cr;exports.pluginRedactPII=Ar;exports.redactText=ct;exports.resolveTranslations=ot;