@aparte/n8n-chat 1.0.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +598 -598
- package/dist/cdn/chunks/chunk-4MZPEZPE.js +209 -0
- package/dist/cdn/chunks/chunk-4MZPEZPE.js.map +7 -0
- package/dist/cdn/chunks/{chunk-UCBMONE6.js → chunk-HASLYSSG.js} +2 -2
- package/dist/cdn/chunks/{chunk-UCBMONE6.js.map → chunk-HASLYSSG.js.map} +1 -1
- package/dist/cdn/chunks/{chunk-WCZRD7U7.js → chunk-KPADIE5S.js} +1 -1
- package/dist/cdn/chunks/{chunk-WCZRD7U7.js.map → chunk-KPADIE5S.js.map} +1 -1
- package/dist/cdn/chunks/{chunk-EKOAQWDB.js → chunk-LGVX5DQP.js} +2 -2
- package/dist/cdn/chunks/{chunk-EKOAQWDB.js.map → chunk-LGVX5DQP.js.map} +1 -1
- package/dist/cdn/chunks/{chunk-FPBJCFJN.js → chunk-PPDOW5CO.js} +2 -2
- package/dist/cdn/chunks/{chunk-FPBJCFJN.js.map → chunk-PPDOW5CO.js.map} +1 -1
- package/dist/cdn/chunks/{chunk-75MBZEMR.js → chunk-XY3GEFGN.js} +2 -2
- package/dist/cdn/chunks/{chunk-75MBZEMR.js.map → chunk-XY3GEFGN.js.map} +1 -1
- package/dist/cdn/chunks/de-VHSIFTGU.js +2 -0
- package/dist/cdn/chunks/de-VHSIFTGU.js.map +7 -0
- package/dist/cdn/chunks/es-CSDZBDZK.js +2 -0
- package/dist/cdn/chunks/es-CSDZBDZK.js.map +7 -0
- package/dist/cdn/chunks/fr-A7LKKK4U.js +2 -0
- package/dist/cdn/chunks/fr-A7LKKK4U.js.map +7 -0
- package/dist/cdn/chunks/{highlight-W7QGGHNK.js → highlight-IMZBI6FV.js} +2 -2
- package/dist/cdn/chunks/{highlight-W7QGGHNK.js.map → highlight-IMZBI6FV.js.map} +1 -1
- package/dist/cdn/chunks/it-4UDH2XVX.js +2 -0
- package/dist/cdn/chunks/it-4UDH2XVX.js.map +7 -0
- package/dist/cdn/chunks/{items-X2D73Z5A.js → items-FFNVAESC.js} +2 -2
- package/dist/cdn/chunks/{items-X2D73Z5A.js.map → items-FFNVAESC.js.map} +1 -1
- package/dist/cdn/chunks/ja-5FMFPBXT.js +2 -0
- package/dist/cdn/chunks/ja-5FMFPBXT.js.map +7 -0
- package/dist/cdn/chunks/ko-KXXFK5U7.js +2 -0
- package/dist/cdn/chunks/ko-KXXFK5U7.js.map +7 -0
- package/dist/cdn/chunks/{link-LNDRLLUH.js → link-3AMG5PIK.js} +2 -2
- package/dist/cdn/chunks/{link-LNDRLLUH.js.map → link-3AMG5PIK.js.map} +1 -1
- package/dist/cdn/chunks/{media-JDTPNZHJ.js → media-F3HYZLYR.js} +2 -2
- package/dist/cdn/chunks/{media-JDTPNZHJ.js.map → media-F3HYZLYR.js.map} +1 -1
- package/dist/cdn/chunks/{order-HS6FXBIB.js → order-L6GKT5I6.js} +2 -2
- package/dist/cdn/chunks/{order-HS6FXBIB.js.map → order-L6GKT5I6.js.map} +1 -1
- package/dist/cdn/chunks/{place-N3E7T2EV.js → place-J7BDZGKL.js} +2 -2
- package/dist/cdn/chunks/{place-N3E7T2EV.js.map → place-J7BDZGKL.js.map} +1 -1
- package/dist/cdn/chunks/{plan-TCWRW3OC.js → plan-BAI6GY4A.js} +2 -2
- package/dist/cdn/chunks/{plan-TCWRW3OC.js.map → plan-BAI6GY4A.js.map} +1 -1
- package/dist/cdn/chunks/{product-JH7QUP6I.js → product-VOKQKP4K.js} +2 -2
- package/dist/cdn/chunks/{product-JH7QUP6I.js.map → product-VOKQKP4K.js.map} +1 -1
- package/dist/cdn/chunks/pt-BR-T2PIW5LH.js +2 -0
- package/dist/cdn/chunks/pt-BR-T2PIW5LH.js.map +7 -0
- package/dist/cdn/chunks/ru-CWHLBHXX.js +2 -0
- package/dist/cdn/chunks/ru-CWHLBHXX.js.map +7 -0
- package/dist/cdn/chunks/{score-GUHJWHW3.js → score-IPBHXWWN.js} +2 -2
- package/dist/cdn/chunks/{score-GUHJWHW3.js.map → score-IPBHXWWN.js.map} +1 -1
- package/dist/cdn/chunks/{stats-UIVYR2CG.js → stats-V6H3J3WL.js} +2 -2
- package/dist/cdn/chunks/{stats-UIVYR2CG.js.map → stats-V6H3J3WL.js.map} +1 -1
- package/dist/cdn/chunks/{stock-PV4GC573.js → stock-UNSEZYGA.js} +2 -2
- package/dist/cdn/chunks/{stock-PV4GC573.js.map → stock-UNSEZYGA.js.map} +1 -1
- package/dist/cdn/chunks/{weather-7L3Y3DNB.js → weather-4IMAIRYF.js} +2 -2
- package/dist/cdn/chunks/{weather-7L3Y3DNB.js.map → weather-4IMAIRYF.js.map} +1 -1
- package/dist/cdn/chunks/zh-CN-UEBLECMR.js +2 -0
- package/dist/cdn/chunks/zh-CN-UEBLECMR.js.map +7 -0
- package/dist/cdn/n8n-chat.js +2 -2
- package/dist/cdn/n8n-chat.js.map +2 -2
- package/dist/index.js.map +1 -1
- package/dist/style.css +411 -411
- package/dist/theme.css +409 -409
- package/package.json +83 -83
- package/dist/cdn/chunks/chunk-FZXRS5MT.js +0 -208
- package/dist/cdn/chunks/chunk-FZXRS5MT.js.map +0 -7
- package/dist/cdn/chunks/de-7JCOF7FR.js +0 -2
- package/dist/cdn/chunks/de-7JCOF7FR.js.map +0 -7
- package/dist/cdn/chunks/es-KUX7YCK6.js +0 -2
- package/dist/cdn/chunks/es-KUX7YCK6.js.map +0 -7
- package/dist/cdn/chunks/fr-VYD7EC55.js +0 -2
- package/dist/cdn/chunks/fr-VYD7EC55.js.map +0 -7
- package/dist/cdn/chunks/it-BXNO2THQ.js +0 -2
- package/dist/cdn/chunks/it-BXNO2THQ.js.map +0 -7
- package/dist/cdn/chunks/ja-6VGJFQ66.js +0 -2
- package/dist/cdn/chunks/ja-6VGJFQ66.js.map +0 -7
- package/dist/cdn/chunks/ko-HUU4F44X.js +0 -2
- package/dist/cdn/chunks/ko-HUU4F44X.js.map +0 -7
- package/dist/cdn/chunks/pt-BR-SNSDLB4C.js +0 -2
- package/dist/cdn/chunks/pt-BR-SNSDLB4C.js.map +0 -7
- package/dist/cdn/chunks/ru-QE2LLTEY.js +0 -2
- package/dist/cdn/chunks/ru-QE2LLTEY.js.map +0 -7
- package/dist/cdn/chunks/zh-CN-WKC5MGZY.js +0 -2
- package/dist/cdn/chunks/zh-CN-WKC5MGZY.js.map +0 -7
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
var Nn=new Set;function eo(n){let t=String(n?.type??"undefined");Nn.has(t)||(Nn.add(t),console.warn(`[runStreamAgent] Ignoring unrecognised stream event "${t}". The reply is unaffected; this usually means the provider or its SDK emits a part this version of apart\xE9 does not map yet.`))}async function ps(n){let{transportCall:t,toolLookup:e,toolConfigLookup:s,approvalResolver:i,emitter:r,signal:a,maxTurns:o=10,toolTimeoutMs:l=3e5,deferral:c}=n,d=n.baseRequest,u=0,h=n.idGen??(b=>`${b}-${u++}`),p=[...d.messages],f=b=>{p.push(b),n.onHistoryAppend?.(b)},g=!0,_=0,S,E;r({type:"run-start"});let I=c?$n(p):[];if(I.length>0){let b=[],y={turns:1,maxTurns:o,toolLookup:e,toolConfigLookup:s,approvalResolver:i,emitter:r,signal:a,toolTimeoutMs:l,declareCall:()=>{},append:f,deferral:c};for(let[m,w]of I.entries()){if(b.length>0){b.push({toolCallId:w.id,name:w.name,input:w.input,reason:Dn(w,s)});continue}let M;try{M=await Hn(w,y)}catch(v){for(let A of I.slice(m+1))r({type:"tool-aborted",toolCallId:A.id});throw v}if(typeof M=="object"){b.push({toolCallId:w.id,name:w.name,input:w.input,reason:M.defer});continue}if(M==="stop-run"){for(let v of I.slice(m+1))r({type:"tool-aborted",toolCallId:v.id});g=!1;break}}if(b.length>0&&!a.aborted){r({type:"run-suspended",pending:b});return}}for(;g&&!a.aborted;){if(_++,E=void 0,_>o){r({type:"turn-limit-exceeded",scope:"global",limit:o});break}let b=d.toolChoice;if(_===1&&b&&typeof b=="object"&&!Array.isArray(b)&&b.input!==void 0){let U=b,O=h("synthetic-tool");r({type:"tool-start",toolCallId:O,name:U.name,input:U.input});let dt=e(U.name);if(!dt){r({type:"tool-aborted",toolCallId:O,cause:"no-handler"}),g=!1;continue}let q=await Fn(dt,{id:O,name:U.name,input:U.input},a,l);if(q.status==="aborted"){r(q.cause?{type:"tool-aborted",toolCallId:O,cause:q.cause}:{type:"tool-aborted",toolCallId:O}),g=!1;continue}if(q.status==="failed")throw r({type:"tool-failed",toolCallId:O,error:Wn(q.error)}),q.error;r({type:"tool-resolved",toolCallId:O,result:q.content,structuredResult:q.structuredContent}),f({role:"assistant",content:"",toolCalls:[{id:O,name:U.name,input:U.input}]}),f({role:"tool",content:q.content,toolCallId:O,toolName:U.name}),d={...d,toolChoice:"none",tools:void 0}}let y={...d,messages:p},m=d.toolChoice;m&&typeof m=="object"&&(d={...d,toolChoice:"auto"});let w;try{w=await t(y)}catch(U){if(a.aborted||U?.name==="AbortError"){g=!1;break}throw U}if(typeof w=="string"){r({type:"turn-start"}),r({type:"text-delta",delta:w}),r({type:"text-flush"});break}r({type:"turn-start"});let M="",v=[],A=!1,R=null,C=U=>{v.push(U),!R&&(R={role:"assistant",content:M.trim(),toolCalls:v},f(R))},P=()=>{R&&(R.content=M.trim())},$=new Set,F=U=>{let O=U;for(let dt=2;$.has(O);dt++)O=`${U}#${dt}`;return $.add(O),O},V=[],Y={turns:_,maxTurns:o,toolLookup:e,toolConfigLookup:s,approvalResolver:i,emitter:r,signal:a,toolTimeoutMs:l,declareCall:C,append:f,deferral:c&&{...c,outcomes:void 0}},hs=w[Symbol.asyncIterator](),On=async()=>{if(!a.aborted)return!1;try{await hs.return?.(void 0)}catch{}return g=!1,!0};try{for(;!await On();){let U=await hs.next();if(await On()||U.done)break;let O=U.value;if(O.type==="thinking"){r({type:"thinking-delta",delta:O.delta});continue}if(O.type==="text"){M+=O.delta,r({type:"text-delta",delta:O.delta});continue}if(O.type==="sources"){r({type:"sources",sources:O.sources,...O.citations?{citations:O.citations}:{}});continue}if(O.type==="done"){O.usage&&(S=O.usage),O.finishReason&&(E=O.finishReason);continue}if(O.type==="error")throw O.code===void 0?new Error(O.message):Object.assign(new Error(O.message),{code:O.code});if(O.type!=="tool_use"){eo(O);continue}A=!0;let dt=F(O.id);r({type:"tool-start",toolCallId:dt,name:O.name,input:O.input});let q={id:dt,name:O.name,input:O.input};if(V.length>0){C(q);let Pn=Dn(q,s);Pn==="approval"&&r({type:"tool-awaiting-approval",toolCallId:q.id,name:q.name,input:q.input}),V.push({toolCallId:q.id,name:q.name,input:q.input,reason:Pn});continue}let ae=await Hn(q,Y);if(typeof ae=="object"){C(q),V.push({toolCallId:q.id,name:q.name,input:q.input,reason:ae.defer});continue}if(ae==="stop-run"){g=!1;break}if(ae==="stop-turn")break}r({type:"text-flush"}),P()}finally{try{await hs.return?.(void 0)}catch{}}if(V.length>0&&!a.aborted)return r({type:"run-suspended",pending:V,usage:S}),S;A||(g=!1)}return a.aborted&&r({type:"run-aborted"}),r({type:"run-done",usage:S,...E?{finishReason:E}:{}}),S}function $n(n){for(let t=n.length-1;t>=0;t--){let e=n[t];if(e.role==="assistant"){if(!e.toolCalls?.length)return[];let s=new Set(n.slice(t+1).filter(i=>i.role==="tool").map(i=>i.toolCallId));return e.toolCalls.filter(i=>!s.has(i.id))}if(e.role!=="tool")return[]}return[]}function Dn(n,t){let e=t?.(n.name);if(e?.external)return"external";let s=typeof e?.needsApproval=="function"?e.needsApproval({id:n.id,name:n.name,input:n.input}):e?.needsApproval;return s&&s!=="deny"?"approval":"queued"}function qn(n){let t=n.reason?.trim(),e=n.by??(t?"policy":"person"),s=t||(e==="policy"?"Tool execution was refused by the approval policy.":e==="earlier-refusal"?"Not run: an earlier call of the same step was refused.":n.instruction?`The user rejected this tool call and said: ${n.instruction}`:"Tool execution was rejected by the user.");return n.instruction?{reason:s,by:e,instruction:n.instruction}:{reason:s,by:e}}function Bn(n,t,e){let s=qn(e);return n.emitter({type:"tool-rejected",toolCallId:t.id,...s}),n.declareCall(t),n.append({role:"tool",content:s.reason,toolCallId:t.id,toolName:t.name}),"stop-turn"}async function Hn(n,t){let{signal:e}=t,s=n.input,i=t.toolConfigLookup?.(n.name),r=t.deferral?.outcomes?.[n.id];if(r?.kind==="decision"&&!r.approved)return Bn(t,n,r);let a=i?.maxTurns??t.maxTurns;if(t.turns>a)return t.emitter({type:"turn-limit-exceeded",scope:"tool",limit:a,toolCallId:n.id}),"stop-run";if(i?.external){if(!t.deferral)return t.emitter({type:"tool-aborted",toolCallId:n.id,cause:"no-handler"}),"stop-run";if(!r||r.kind==="decision")return{defer:"external"};if(r.kind==="failed")throw t.emitter({type:"tool-failed",toolCallId:n.id,error:r.error}),new Error(r.error);return t.emitter({type:"tool-resolved",toolCallId:n.id,result:r.content,structuredResult:r.structuredContent}),t.declareCall(n),t.append({role:"tool",content:r.content,toolCallId:n.id,toolName:n.name}),"continue"}let o=t.toolLookup(n.name);if(!o)return t.emitter({type:"tool-aborted",toolCallId:n.id,cause:"no-handler"}),"stop-run";let l=n.input,c=typeof i?.needsApproval=="function"?i.needsApproval({id:n.id,name:n.name,input:s}):i?.needsApproval;if(c){let u=r?.kind==="decision"&&c!=="deny"?r:void 0;if(c!=="deny"&&!u&&t.emitter({type:"tool-awaiting-approval",toolCallId:n.id,name:n.name,input:n.input}),!u&&t.deferral&&c!=="deny")return{defer:"approval"};if(!u&&!t.approvalResolver)return t.emitter({type:"tool-aborted",toolCallId:n.id,cause:"no-resolver"}),"stop-run";let h=u;if(!h&&!e.aborted&&t.approvalResolver)try{h=await t.approvalResolver({id:n.id,name:n.name,input:s},e)}catch(p){if(!e.aborted&&p?.name!=="AbortError")throw p}if(e.aborted||!h)return t.emitter({type:"tool-aborted",toolCallId:n.id,cause:"stopped"}),"stop-run";if(!h.approved)return Bn(t,n,h),"stop-turn";h.payload&&typeof h.payload=="object"&&!Array.isArray(h.payload)&&(l={...s,...h.payload}),t.emitter({type:"tool-approved",toolCallId:n.id})}let d=await Fn(o,{id:n.id,name:n.name,input:l},e,t.toolTimeoutMs);if(d.status==="aborted")return t.emitter(d.cause?{type:"tool-aborted",toolCallId:n.id,cause:d.cause}:{type:"tool-aborted",toolCallId:n.id}),"stop-run";if(d.status==="failed")throw t.emitter({type:"tool-failed",toolCallId:n.id,error:Wn(d.error)}),d.error;return t.emitter({type:"tool-resolved",toolCallId:n.id,result:d.content,structuredResult:d.structuredContent}),t.declareCall(n),t.append({role:"tool",content:d.content,toolCallId:n.id,toolName:n.name}),"continue"}async function Fn(n,t,e,s){if(e.aborted)return{status:"aborted",cause:"stopped"};let i=new AbortController,r=()=>i.abort();e.addEventListener("abort",r,{once:!0});let a,o=new Promise(u=>{a=()=>u({status:"aborted",cause:"stopped"}),e.addEventListener("abort",a,{once:!0})}),l,c=!1,d=new Promise(u=>{l=setTimeout(()=>{c=!0,i.abort(),u({status:"aborted",cause:"timeout"})},s)});try{return await Promise.race([n(t,i.signal).then(h=>({status:"resolved",content:h.content,structuredContent:h.structuredContent})),d,o])}catch(u){return u?.name==="AbortError"?e.aborted?{status:"aborted",cause:"stopped"}:c?{status:"aborted",cause:"timeout"}:{status:"aborted"}:{status:"failed",error:u}}finally{clearTimeout(l),e.removeEventListener("abort",r),a&&e.removeEventListener("abort",a)}}function Wn(n){return n instanceof Error?n.message||n.name:typeof n=="string"?n:String(n)}var so='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="8.5" y="8.5" width="12" height="12" rx="2.5"/><path d="M15.5 8.5V6a2.5 2.5 0 0 0-2.5-2.5H6A2.5 2.5 0 0 0 3.5 6v7A2.5 2.5 0 0 0 6 15.5h2.5"/></svg>',no='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 12.5 9.5 17.5 19.5 7"/></svg>',io='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 3 3.7 10.4a.9.9 0 0 0 .1 1.7l6.2 2 2 6.2a.9.9 0 0 0 1.7.1L21 3Z"/><path d="M10 14 21 3"/></svg>',ro='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="aparte-icon aparte-icon-spin"><circle cx="12" cy="12" r="10" stroke-opacity="0.25"/><path d="M12 2a10 10 0 0 1 10 10"/></svg>',ao='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9.5"/><path d="M12 7.75v5"/><path d="M12 16.25h.01"/></svg>',oo='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5.5 9.5 12 16l6.5-6.5"/></svg>',lo='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5.5 14.5 12 8l6.5 6.5"/></svg>',co='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 6.5 10.5 12 5 17.5"/><path d="M13 18h6"/></svg>',uo='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8.4 21a5.2 5.2 0 0 1-3.7-8.9l8.6-8.6a3.5 3.5 0 0 1 4.9 4.9l-8.6 8.6a1.7 1.7 0 0 1-2.5-2.5l7.4-7.4"/></svg>',ho='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3.5" y="4.5" width="17" height="15" rx="2.5"/><circle cx="8.5" cy="9" r="1.5"/><path d="M20.5 15.5l-4-4-8 8"/></svg>',po='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13.5 3H6.5A1.5 1.5 0 0 0 5 4.5v15A1.5 1.5 0 0 0 6.5 21h11a1.5 1.5 0 0 0 1.5-1.5V8.5Z"/><path d="M13.5 3v5.5H19"/></svg>',fo='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 4.5v15"/><path d="M6 13.5l6 6 6-6"/></svg>',go='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 12a8 8 0 1 0 2.35-5.65L4 8.5"/><path d="M4 3.5v5h5"/></svg>',_o='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 4.5H6a2 2 0 0 0-2 2v11.5a2 2 0 0 0 2 2h11.5a2 2 0 0 0 2-2V13"/><path d="M17.75 3.25a2.05 2.05 0 0 1 2.9 2.9l-9.15 9.15-3.9 1 1-3.9Z"/></svg>',mo='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M6.5 10.5v10"/><path d="M6.5 10.5h3l3.2-6.4a1.75 1.75 0 0 1 3.3.8V9h4a2 2 0 0 1 2 2.35l-1.3 7.3a2 2 0 0 1-2 1.6H9.5"/></svg>',bo='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.5 13.5v-10"/><path d="M17.5 13.5h-3l-3.2 6.4a1.75 1.75 0 0 1-3.3-.8V15h-4a2 2 0 0 1-2-2.35l1.3-7.3a2 2 0 0 1 2-1.6h9.1"/></svg>',vo='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14.5 6 9 12l5.5 6"/></svg>',yo='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9.5 6 15 12l-5.5 6"/></svg>',wo='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14.5 3.5a5.5 5.5 0 0 0-5.1 7.6L3.5 17l3.5 3.5 5.9-5.9a5.5 5.5 0 0 0 7.6-5.1l-3.1 3.1-2.7-.8-.8-2.7 3.1-3.1Z"/></svg>',So='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M6.5 6.5l11 11"/><path d="M17.5 6.5l-11 11"/></svg>',Ao='<svg class="aparte-icon" viewBox="0 0 24 24" fill="currentColor"><rect x="5" y="5" width="14" height="14" rx="2.5"/></svg>',Co='<svg class="aparte-icon" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="5" width="4.5" height="14" rx="1.5"/><rect x="13.5" y="5" width="4.5" height="14" rx="1.5"/></svg>',Eo='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9.5"/><path d="M12 11v5.25"/><path d="M12 7.75h.01"/></svg>',ko='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 8 21 8"/><path d="M5 8v11a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8"/><polyline points="9 14 12 11 15 14"/><line x1="12" y1="11" x2="12" y2="19"/></svg>',To='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 8 21 8"/><path d="M5 8v11a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8"/><polyline points="9 14 12 17 15 14"/><line x1="12" y1="11" x2="12" y2="17"/></svg>',Mo='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3.5v12m0 0-4.5-4.5M12 15.5l4.5-4.5M4.5 20h15"/></svg>',xo='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="5.5" cy="12" r="1.1"/><circle cx="12" cy="12" r="1.1"/><circle cx="18.5" cy="12" r="1.1"/></svg>',Io='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8.5 3.5h7"/><path d="M10 3.5v5l-3 3.5V14h10v-2l-3-3.5v-5"/><path d="M12 14v6.5"/></svg>',Lo='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 7h15M8 7V5a1.5 1.5 0 0 1 1.5-1.5h5A1.5 1.5 0 0 1 16 5v2"/><path d="m6.5 7 .8 12a1.5 1.5 0 0 0 1.5 1.5h6.4a1.5 1.5 0 0 0 1.5-1.4L17.5 7"/><path d="M10 11v5.5M14 11v5.5"/></svg>',Ro='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M6.5 4h11A2.5 2.5 0 0 1 20 6.5v8a2.5 2.5 0 0 1-2.5 2.5H9.5L4.5 21V6.5A2.5 2.5 0 0 1 6.5 4Z"/></svg>',Oo='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 7h15M4.5 12h15M4.5 17h15"/></svg>',Po='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.7 4.3 2.9 18a1.5 1.5 0 0 0 1.3 2.3h15.6a1.5 1.5 0 0 0 1.3-2.3L13.3 4.3a1.5 1.5 0 0 0-2.6 0Z"/><path d="M12 9.5V14M12 17.2v.1"/></svg>',Un={copy:so,check:no,send:io,loading:ro,error:ao,expand:oo,collapse:lo,terminal:co,paperclip:uo,image:ho,file:po,scrollDown:fo,retry:go,edit:_o,thumbUp:mo,thumbDown:bo,prevBranch:vo,nextBranch:yo,tool:wo,close:So,stop:Ao,pause:Co,info:Eo,archive:ko,unarchive:To,download:Mo,more:xo,pin:Io,trash:Lo,menu:Oo,alertTriangle:Po,messageSquare:Ro};function ji(n){return typeof n=="string"?n:n.filter(t=>t.type==="text").map(t=>t.text).join("")}var B=(n=>(n.CONFIG_NO_PROVIDER="CONFIG_NO_PROVIDER",n.CONFIG_MISSING_KEY="CONFIG_MISSING_KEY",n.CONFIG_INVALID_KEY="CONFIG_INVALID_KEY",n.CONFIG_INVALID_MODEL="CONFIG_INVALID_MODEL",n.USAGE_RATE_LIMIT="USAGE_RATE_LIMIT",n.USAGE_CONTEXT_EXCEEDED="USAGE_CONTEXT_EXCEEDED",n.USAGE_BAD_REQUEST="USAGE_BAD_REQUEST",n.NET_OFFLINE="NET_OFFLINE",n.NET_TIMEOUT="NET_TIMEOUT",n.NET_ERROR="NET_ERROR",n.PROVIDER_ERROR="PROVIDER_ERROR",n.PROVIDER_UNAVAILABLE="PROVIDER_UNAVAILABLE",n.PROVIDER_POLICY="PROVIDER_POLICY",n.PROVIDER_MISCONFIGURED="PROVIDER_MISCONFIGURED",n.MAX_TURNS_EXCEEDED="MAX_TURNS_EXCEEDED",n.UNKNOWN_ERROR="UNKNOWN_ERROR",n))(B||{}),X=class n extends Error{constructor(t,e,s,i,r){super(t),this.message=t,this.code=e,this.data=s,this.originalError=i,this.httpStatus=r,this.name="AparteError"}static codeForStatus(t){switch(t){case 400:return"USAGE_BAD_REQUEST";case 401:case 403:return"CONFIG_INVALID_KEY";case 408:return"NET_TIMEOUT";case 429:return"USAGE_RATE_LIMIT";case 503:return"PROVIDER_UNAVAILABLE";default:return t!==void 0&&t>=500?"PROVIDER_ERROR":void 0}}static from(t,e="UNKNOWN_ERROR",s){if(t instanceof n)return t;let i=t instanceof Error?t.message:String(t),r=t?.status||t?.statusCode||s,a=t?.code,o=e!=="UNKNOWN_ERROR"?e:n.carriedCode(a)??n.codeForStatus(r)??n.codeForFailure(t)??e;return new n(i,o,void 0,t,r)}static carriedCode(t){return typeof t=="string"&&Object.values(B).includes(t)?t:void 0}static codeForFailure(t){if(t instanceof Error){if(t.name==="TimeoutError")return"NET_TIMEOUT";if(t instanceof TypeError&&/fetch|network|load failed/i.test(t.message))return typeof navigator<"u"&&navigator.onLine===!1?"NET_OFFLINE":"NET_ERROR"}}},Dt=Un,Tt={inputPlaceholder:"Type a message...",sendButton:"Send",copy:"Copy",copied:"Copied!",retry:"Retry",thinking:"Thinking",elicitationOther:"Other\u2026",elicitationOtherPlaceholder:"Type your answer\u2026",elicitationOtherLabel:"Custom answer",submitButton:"Submit",stopButton:"Stop",elicitationRecommended:"Recommended",elicitationSkip:"Skip",elicitationHide:"Hide for now",elicitationWaiting:"Waiting for your answer",elicitationYes:"Yes",elicitationNo:"No",elicitationAnswerLabel:"Your answer",approvalInstructionPlaceholder:"Or tell it what to do instead\u2026",approvalAsk:"Allow {tool}?",approvalWaiting:"Waiting",scrollToBottom:"Scroll to bottom",suggestionsLabel:"Suggested prompts",contextLabel:"Context window",contextSystem:"System prompt",contextTools:"Tools",contextSummary:"Summary",contextMessages:"Messages",contextOther:"Other",contextFree:"Free",contextTotal:"Total",contextReclaim:"Compacting now would free ~{n} tokens",contextCompactNow:"Compact now",checkpointCount:"{n} messages summarised for the model",checkpointCountOne:"1 message summarised for the model",checkpointLegacy:"Earlier messages were summarised",checkpointGroup:"Context summary",checkpointShow:"Show summary",checkpointHide:"Hide summary",checkpointRestore:"Restore",checkpointRestoreConfirm:"Send the original messages to the model again?",checkpointPending:"Summarising the context\u2026",checkpointFailed:"Couldn't summarise the context",toolRunning:"Running",toolCompleted:"Done",toolRejected:"Rejected",toolStopped:"Stopped",toolFailed:"Failed",toolInput:"Input",toolOutput:"Output",toolRejectedSaid:"You said: \u201C{instruction}\u201D",toolRefusedByPolicy:"Refused by policy",toolNotRunAfterRefusal:"Not run: an earlier call was refused",toolTimedOut:"Timed out",toolUnavailable:"Not available here",toolNoApprover:"No one could approve it",toolTurnLimit:"Turn limit reached",maxTurnsReached:"Stopped after {n} turns to avoid an endless loop.",sourcesCount:"{n} sources",sourcesOne:"1 source",sourcesCard:"Sources",sourcePrevious:"Previous source",sourceNext:"Next source",sourcePosition:"Source {i} of {n}",opensInNewTab:"(opens in a new tab)",imageLoad:"Load the image from {host}",imageLoadNamed:"Load the image \u201C{alt}\u201D from {host}",questionDeclined:"You declined to answer.",artifactNotCreated:"Not created",thoughtFor:"Thought for {duration}",thought:"Thought",turnWorking:"Working\u2026",turnWorked:"Worked {duration}",turnUsed:"Used {tools}",turnTools:"one:{n} tool|other:{n} tools",feedbackReasonTitle:"What went wrong?",feedbackReasonDismiss:"Not now",triggersLoading:"Loading\u2026",triggersEmpty:"No results",triggersError:"This list could not be loaded",triggersRetry:"Try again",triggersBack:"Back",triggersCommandNew:"Start a new conversation",triggersCommandStop:"Stop the reply",triggersCommandRetry:"Answer again",triggersCommandCopy:"Copy the last reply",triggersCommandCompact:"Summarise the earlier messages",triggersCompactNothing:"There is nothing to compact yet",triggersCompactBusy:"Wait for the reply to finish",triggersCompactNoWindow:"This model does not say how much it can read",triggersCompactFailed:"The summary could not be written",triggersCommandModel:"Change the model",triggersCommandApproval:"Change the approval mode",approvalOptionsLabel:"Your decision",approvalArgsLabel:"Arguments",actionUpload:"Attach file",removeAttachment:"Remove {name}",messageFrom:"Message from {name}",selectSearchPlaceholder:"Search\u2026",selectSearchLabel:"Search options",loading:"Loading\u2026",download:"Download",openArtifact:"Open",modelContextWindow:"{n} context",previewPending:"Press Preview to run this artifact.",sandboxError:"The sandbox failed during generation.",sandboxErrorHint:"Common cause: the model produced invalid code (undefined variable, wrong argument type). Retry the request \u2014 the model may produce different code.",preview:"Preview",code:"Code",generating:"Generating\u2026",rebuildingPreview:"Rebuilding preview\u2026",typing:"Typing",responseCutOff:"Cut off at the model's length limit.",error:"Error",errorUnreachable:"The assistant can\u2019t be reached right now. Try again in a moment.",errorTimeout:"The answer took too long. Try again in a moment.",errorRefused:"The assistant isn\u2019t allowed to answer right now.",errorRateLimited:"Too many requests right now. Try again in a moment.",errorTooLong:"This conversation is too long for the model. Start a new one.",errorFailed:"The assistant couldn\u2019t answer. Try again in a moment.",errorNoAnswer:"The assistant couldn\u2019t answer this request.",running:"Running...",run:"Run",file:"File",modelSelectorPlaceholder:"Select a model...",approvalModeLabel:"Approval mode",roleNameUser:"You",roleNameAssistant:"Assistant",yourMessage:"Your message",assistantResponse:"Assistant response",messageActions:"Message actions",edit:"Edit message",editConfirm:"Send",editCancel:"Cancel",feedbackPositive:"Good response",feedbackNegative:"Bad response",previousResponse:"Previous response",nextResponse:"Next response",approveTool:"Approve",rejectTool:"Reject",messageInfo:"Details",newChat:"New Chat",loadingConversations:"Loading conversations",conversationSearchEmpty:"No conversation matches",conversationList:"Conversations",loadingConversation:"Loading the conversation",deleteConversation:"Delete",archiveConversation:"Archive",unarchiveConversation:"Unarchive",conversationActions:"Conversation actions",conversationRunning:"Answering",conversationWaiting:"Waiting for you",renameConversation:"Rename",conversationTitle:"Conversation title",pinConversation:"Pin",unpinConversation:"Unpin",deleteConversationConfirm:"Delete \u201C{title}\u201D?",cancel:"Cancel",conversationGroupPinned:"Pinned",conversationGroupToday:"Today",conversationGroupYesterday:"Yesterday",conversationGroupWeek:"Previous 7 days",conversationGroupMonth:"Previous 30 days",scrollRailLabel:"Conversation outline",sidebarLabel:"Conversations",splitHandleLabel:"Resize the panes",launcherOpen:"Open the chat",launcherClose:"Close the chat",transcript:"Transcript"};function Gi(n){return typeof n.buildRequest=="function"&&typeof n.parseStream=="function"&&typeof n.defaultEndpoint=="string"&&(typeof n.authHeaders=="function"||typeof n.authQuery=="function")}function No(n){return typeof n=="string"?{key:n}:n&&typeof n=="object"?{key:n.apiKey,endpoint:n.endpoint}:{}}function Do(n,t,e){let s=n?.error,i=typeof s=="object"?s?.message:s;return typeof i=="string"&&i?i:`${e} ${t}`}function Bo(n){return typeof n=="string"&&Object.values(B).includes(n)}async function Ho(n,t="HTTP",e){let s=await n.json().catch(()=>{}),i=Do(s,n.status,t),r=s?.error?.code,a=e?.classifyError?.(n.status,s)??(Bo(r)?r:void 0)??X.codeForStatus(n.status)??B.UNKNOWN_ERROR;return new X(i,a,void 0,void 0,n.status)}async function $o(n,t,e){let s=await t.json();if(typeof n.parseText!="function")throw new Error(`Provider "${e}" cannot resolve a non-streaming response: parseText is not implemented.`);let i=n.parseText(s),r;try{r=n.parseSources?.(s)}catch{r=void 0}return qo(i,r)}function qo(n,t){if(!t||t.sources.length===0)return n;let e=[{type:"text",delta:n},{type:"sources",...t},{type:"done"}];return new ReadableStream({pull(s){let i=e.shift();i?s.enqueue(i):s.close()}})}var ye=class{byok;warnedBrowserKey=!1;constructor(t={}){this.byok=t.byok??!1}async chat(t,e,s,i){let{key:r,endpoint:a}=No(s);if(!this.byok&&r&&this.warnBrowserKeyOnce(i.providerId),!Gi(t)){if(typeof t.chat!="function")throw new Error(`Provider "${i.providerId}" exposes neither a format-adapter surface nor chat().`);return t.chat(e,s,i)}let o=a||t.defaultEndpoint,l=t.buildRequest(e),c=`${o}${l.path}`,d={"Content-Type":"application/json",...l.headers};if(r&&t.authHeaders&&Object.assign(d,t.authHeaders(r)),r&&t.authQuery){let h=new URLSearchParams(t.authQuery(r)).toString();c+=(c.includes("?")?"&":"?")+h}let u=await fetch(c,{method:"POST",headers:d,body:JSON.stringify(l.body),signal:i.signal});if(!u.ok)throw await Ho(u,"HTTP",t);if(e.stream===!1)return $o(t,u,i.providerId);if(!u.body)throw new Error(`Provider "${i.providerId}" returned no response body for a streaming request.`);return t.parseStream(u.body)}warnBrowserKeyOnce(t){this.warnedBrowserKey||(this.warnedBrowserKey=!0,console.warn(`[Aparte] AparteDirectTransport is sending the "${t}" API key straight from the browser \u2014 it is visible to anyone who opens devtools. Fine for BYOK or local models: pass new AparteDirectTransport({ byok: true }) to silence this. For a server-held key, use AparteBackendTransport so the key never reaches the client.`))}};function G(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}var Fo=[{start:"<think>",end:"</think>"},{start:"<thinking>",end:"</thinking>"}],It=class{_options;_thinkingDelimiters;_blocks;_state;_pendingSegment=null;constructor(t={}){let e=t.thinkingDelimiters;this._thinkingDelimiters=e?Array.isArray(e)?e:[e]:Fo,this._blocks=t.blocks??[],this._options={autoGenerateIds:t.autoGenerateIds??!0,idPrefix:t.idPrefix??"seg"},this._state=this._createInitialState()}parse(t){this._state.buffer+=t;let e=[];for(;this._state.buffer.length>0||this._pendingSegment;){let s=this._parseNext();if(!s)break;s.segment&&e.push(s.segment),this._state.buffer=s.remaining}return{segments:e,remaining:this._state.buffer,state:{...this._state}}}finalize(){let t=[],e=s=>s.replace(/\n?```[ \t]*$/,"");if(this._state.activeSegment){if("content"in this._state.activeSegment){let s=this._state.activeSegment,i=s.content+this._state.buffer;(s.type==="text"||s.type==="code")&&(i=e(i)),s.content=i}t.push(this._closed(this._state.activeSegment)),this._state.activeSegment=null}else this._state.buffer.trim()&&t.push(this._closed(this._createTextSegment(e(this._state.buffer))));return this._state.mode="text",this._state.buffer="",this._state.codeLanguage=void 0,this._state.thinkingEnd=void 0,this._state.blockEnd=void 0,t}reset(){this._state=this._createInitialState(),this._pendingSegment=null}getState(){return{...this._state}}_parseNext(){if(this._pendingSegment){let e=this._pendingSegment;return this._pendingSegment=null,{segment:e,remaining:this._state.buffer}}let t=this._state.buffer;switch(this._state.mode){case"text":return this._parseTextMode(t);case"code":return this._parseCodeMode(t);case"thinking":return this._parseThinkingMode(t);case"block":return this._parseBlockMode(t);default:return null}}_parseTextMode(t){let e=t.indexOf("```"),s=-1;for(let c of this._thinkingDelimiters){let d=t.indexOf(c.start);d!==-1&&(s===-1||d<s)&&(s=d)}let i=-1,r;for(let c of this._blocks){let d=this._indexOfTag(t,c.tag);d!==-1&&(i===-1||d<i)&&(i=d,r=c)}let a=[];if(e!==-1&&a.push({type:"code",index:e}),s!==-1&&a.push({type:"thinking",index:s}),i!==-1&&a.push({type:"block",index:i}),a.sort((c,d)=>c.index-d.index),a.length===0)return t.endsWith("`")||t.endsWith("``")||this._thinkingDelimiters.some(c=>this._isPartialMatch(t,c.start))||this._blocks.some(c=>this._isPartialMatch(t,"<"+c.tag)||t.endsWith("<"+c.tag))?null:((!this._state.activeSegment||this._state.activeSegment.type!=="text")&&(this._state.activeSegment=this._createTextSegment("")),this._state.activeSegment.content+=t,{segment:null,remaining:""});let o=a[0];if(o.index>0){let c=t.slice(0,o.index);return!this._state.activeSegment||this._state.activeSegment.type!=="text"?this._state.activeSegment=this._createTextSegment(c):this._state.activeSegment.content+=c,{segment:null,remaining:t.slice(o.index)}}let l=null;if(this._state.activeSegment&&this._state.activeSegment.type==="text"&&(l=this._closed(this._state.activeSegment),this._state.activeSegment=null),o.type==="code"){let c=this._startCodeBlock(t);return c?{segment:l,remaining:c.remaining}:(l&&(this._state.activeSegment=l),null)}else if(o.type==="thinking"){let c=this._startThinkingBlock(t);return c?{segment:l,remaining:c.remaining}:(l&&(this._state.activeSegment=l),null)}else{let c=this._startBlock(t,r);return c?c.segment&&l?(this._pendingSegment=c.segment,{segment:l,remaining:c.remaining}):{segment:l??c.segment,remaining:c.remaining}:(l&&(this._state.activeSegment=l),null)}}_startCodeBlock(t){let e=t.indexOf(`
|
|
2
|
+
`);if(e===-1)return null;let i=t.slice(0,e).slice(3).trim()||"markdown";return i==="markdown"||i==="md"?{segment:null,remaining:t.slice(e+1)}:(this._state.mode="code",this._state.codeLanguage=i,this._state.activeSegment=this._createCodeSegment(i,""),this._state.activeSegment.isStreaming=!0,{segment:null,remaining:t.slice(e+1)})}_parseCodeMode(t){let e=t.indexOf("\n```");if(e===-1){if(t.length>4){let o=t.slice(0,-4);return this._state.activeSegment&&"content"in this._state.activeSegment&&(this._state.activeSegment.content+=o),{segment:null,remaining:t.slice(-4)}}return null}let s=t.slice(0,e);this._state.activeSegment&&"content"in this._state.activeSegment&&(this._state.activeSegment.content+=s);let i=this._closed(this._state.activeSegment);this._state.mode="text",this._state.activeSegment=null;let r=t.slice(e+4),a=r.startsWith(`
|
|
3
|
+
`)?r.slice(1):r;return{segment:i,remaining:a}}_startThinkingBlock(t){let e=this._thinkingDelimiters.find(s=>t.startsWith(s.start));return e?(this._state.mode="thinking",this._state.thinkingEnd=e.end,this._state.activeSegment=this._createThinkingSegment(""),{segment:null,remaining:t.slice(e.start.length)}):null}_parseThinkingMode(t){let e=this._state.thinkingEnd??this._thinkingDelimiters[0].end,s=t.indexOf(e);if(s===-1){if(this._isPartialMatch(t,e)){let a=this._getPartialMatchLength(t,e),o=t.slice(0,t.length-a);return o&&this._state.activeSegment&&"content"in this._state.activeSegment&&(this._state.activeSegment.content+=o),o?{segment:null,remaining:t.slice(-a)}:null}if(t.length>e.length){let a=t.slice(0,-e.length);return this._state.activeSegment&&"content"in this._state.activeSegment&&(this._state.activeSegment.content+=a),{segment:null,remaining:t.slice(-e.length)}}return null}let i=t.slice(0,s);this._state.activeSegment&&"content"in this._state.activeSegment&&(this._state.activeSegment.content+=i);let r=this._closed(this._state.activeSegment);return this._state.mode="text",this._state.activeSegment=null,this._state.thinkingEnd=void 0,{segment:r,remaining:t.slice(s+e.length)}}_indexOfTag(t,e){let s="<"+e,i=0;for(;;){let r=t.indexOf(s,i);if(r===-1)return-1;let a=t[r+s.length];if(a===void 0)return-1;if(a===">"||a==="/"||/\s/.test(a))return r;i=r+1}}_tagEnd(t,e){let s=null,i=!1,r=-1;for(let a=1+e.length;a<t.length;a++){let o=t[a];if(o===">"&&r===-1&&(r=a),s){if(o===s)s=null;else if(o===`
|
|
4
|
+
`)return r;continue}if(o===">")return a;if(o==="="){i=!0;continue}if(i&&(o==='"'||o==="'")){s=o,i=!1;continue}/\s/.test(o)||(i=!1)}return-1}_startBlock(t,e){let s=this._tagEnd(t,e.tag);if(s===-1)return null;let i=t.slice(1+e.tag.length,s),r=i.trimEnd().endsWith("/"),a=r?i.trimEnd().slice(0,-1):i,o=Object.create(null);for(let d of a.matchAll(/([A-Za-z_][\w:-]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/g))o[d[1]]=d[2]??d[3]??d[4]??"";let l=e.toSegment({attrs:o,id:this._options.autoGenerateIds?this._generateId():""});l.content="";let c=t.slice(s+1);return r?{segment:this._closed(l),remaining:c}:(l.isStreaming=!0,this._state.mode="block",this._state.blockEnd=`</${e.tag}>`,this._state.activeSegment=l,{segment:null,remaining:c})}_parseBlockMode(t){let e=this._state.blockEnd,s=t.indexOf(e),i=this._state.activeSegment;if(s===-1){if(this._isPartialMatch(t,e)){let a=this._getPartialMatchLength(t,e),o=t.slice(0,t.length-a);return o&&i&&(i.content+=o),o?{segment:null,remaining:t.slice(-a)}:null}if(t.length>e.length){let a=t.slice(0,-e.length);return i&&(i.content+=a),{segment:null,remaining:t.slice(-e.length)}}return null}i&&(i.content+=t.slice(0,s));let r=this._closed(this._state.activeSegment);return this._state.mode="text",this._state.activeSegment=null,this._state.blockEnd=void 0,{segment:r,remaining:t.slice(s+e.length)}}_createInitialState(){return{mode:"text",buffer:"",segments:[],activeSegment:null,segmentCounter:0}}_generateId(){return++this._state.segmentCounter,`${this._options.idPrefix}-${G()}`}_closed(t){return t&&(t.isStreaming=!1),t}_createTextSegment(t){return{id:this._options.autoGenerateIds?this._generateId():"",type:"text",content:t}}_createCodeSegment(t,e){return{id:this._options.autoGenerateIds?this._generateId():"",type:"code",language:t,content:e}}_createThinkingSegment(t){return{id:this._options.autoGenerateIds?this._generateId():"",type:"thinking",content:t}}_isPartialMatch(t,e){for(let s=1;s<e.length;s++)if(t.endsWith(e.slice(0,s)))return!0;return!1}_getPartialMatchLength(t,e){for(let s=e.length-1;s>=1;s--)if(t.endsWith(e.slice(0,s)))return s;return 0}};function zi(n,t){let e=new It(t),s=e.parse(n),i=e.finalize();return[...s.segments,...i]}var Wo=new Set(["pending","awaiting-approval"]),Uo=["content","output","result"];function jo(n){return Uo.some(t=>t in n)}function Xs(n,t,e,s){let i=Ko(t,s);return{...i,messageId:t.messageId??e,index:t.index??n.length,...we(i,{startedAt:Jt(t)?.startedAt??Date.now()})}}function Go(n,t,e,s=!1){return{...t,messageId:e,index:n.length,isStreaming:!1,...t.type==="tool_call"&&(t.status==="awaiting-approval"||t.status==="pending"&&!s)&&!t.deferred?.ticket?{status:"aborted"}:{}}}var zo=new Set(["id","type","messageId","index"]);function Jt(n){return n.meta?.aparte}function we(n,t){return{meta:{...n.meta,aparte:{...n.meta?.aparte,...t}}}}function Ko(n,t){if(!t)return n;let e={...n};for(let[s,i]of Object.entries(t))if(!(zo.has(s)||s in n)){if(s==="meta"){let{aparte:r,...a}=i??{};e.meta=a;continue}e[s]=i}return e}function ft(n){return n.type==="tool_call"?!Wo.has(n.status):n.isStreaming===!1}function Ki(n,t){if(ft(n))return t;let e={...n,...t};if(ft(e)){let s=Jt(n)?.endedAt;return{...t,...we(n,{endedAt:s??Date.now()})}}return jo(t)?{...t,...we(n,{endedAt:Date.now()})}:t}function Qs(n,t){let e={...n,...t};return"meta"in t?{...e,meta:{...n.meta,...t.meta,...n.meta?.aparte||t.meta?.aparte?{aparte:{...n.meta?.aparte,...t.meta?.aparte}}:{}}}:e}function Vi(n){let{startedAt:t,endedAt:e}=Jt(n)??{};if(!(t==null||e==null))return e-t}function Yi(n){return ft(n)?{}:we(n,{endedAt:Date.now()})}function fs(n){return{content:n.content,...n.isStreaming===!1?{isStreaming:!1}:{}}}function Zs(n){return n!=null&&n!=="streaming"&&n!=="pending"}function Ji(n){return n.filter(t=>!ft(t)).map(t=>t.id)}function Oe(n){if(!n.segments?.length)return{...n};let t=n.status==="streaming"||n.status==="pending";return{...n,segments:n.segments.reduce((e,s)=>(e.push(Go(e,s,n.id,t)),e),[])}}function Xi(n){for(let t=0;t<n.length;t++){let e=n[t];e.index!==t&&(n[t]={...e,index:t})}}var Xt="data-aparte-host",Se=Symbol.for("aparte.instanceConfig");function Vo(n,t,e){if(t===e)return;let s=i=>{let r=i.aparteConfigChanged;typeof r=="function"&&r.call(i,t,e)};s(n);for(let i of n.querySelectorAll("*"))s(i)}function Yo(n,t){let e=n[Se]??T(n.parentElement);n[Se]=t,n.setAttribute(Xt,""),Vo(n,t,e)}function T(n){let t=`[${Xt}]`,e=n?.closest?.(t);for(;e&&!e[Se];)e=e.parentElement?.closest(t);return e?.[Se]??Q}var pe=null;function j(n,t){let e=pe;pe=n;try{return t()}finally{pe=e}}function k(n){return pe??T(n)}function J(n,t,e,s){let i=s??(n.id||void 0),r=e&&typeof e=="object"?{targetId:i,...e}:e;n.dispatchEvent(new CustomEvent(t,{bubbles:!0,composed:!0,detail:r}))}function L(n){let t="";for(let e=0;e<n.length;e++){let s=n[e];s==="&"?t+="&":s==="<"?t+="<":s===">"?t+=">":s==='"'?t+=""":s==="'"?t+="'":t+=s}return t}var x=L,Ut="aparte-code-drawing",Qi="aparte-code-pending",jn="data-aparte-open",Zi="data-aparte-drawn",Jo=4*1024*1024,xs=class{entries=new Map;size=0;get(t){let e=this.entries.get(t);return e&&(this.entries.delete(t),this.entries.set(t,e)),e}set(t,e){let s=this.entries.get(t);s&&(this.size-=gs(t,s),this.entries.delete(t));let i={html:e};this.entries.set(t,i),this.size+=gs(t,i);for(let[r,a]of this.entries){if(this.size<=Jo||r===t)break;this.entries.delete(r),this.size-=gs(r,a)}return i}},gs=(n,t)=>n.length+(t.html?.length??0),nt=new WeakMap,tn=new WeakMap,Gn=new WeakMap,zn=new WeakMap,Kn=new WeakMap,tr=new WeakMap,er=new WeakMap,sr=new WeakMap,Vn=new WeakSet,Yn=new WeakSet,_s=new WeakMap,Jn=new WeakMap,oe=new WeakMap;function Xo(n){let t=Gn.get(n);return t||(t=new xs,Gn.set(n,t)),t}function Qo(n){let t=zn.get(n);return t||(t=new Map,zn.set(n,t)),t}function Xn(n,t){let e=n.get(t);return e||(e=new Map,n.set(t,e)),e}function jt(n,t){Vn.has(n)||(Vn.add(n),console.warn(`[aparte] The ${n.languages.join("/")} renderer failed; the source is shown instead.`,t))}function Zo(n){for(let t of Array.from(n.classList))if(t.startsWith("language-"))return t.slice(9).toLowerCase()||null;return null}function tl(n){return n.classList.contains("math-display")?!0:n.classList.contains("math-inline")?!1:n.parentElement?.tagName==="PRE"}function el(n){return n.hasAttribute(jn)||n.parentElement?.tagName==="PRE"&&n.parentElement.hasAttribute(jn)}function sl(n,t){let e="";try{e=n.cacheKey?.(t)??""}catch(s){jt(n,s)}return`${t.language}${t.display?"d":"i"}${e}${t.source}`}function nr(n){return typeof n?.then=="function"}function nl(n){return n.closest("pre")??nt.get(n)?.drawing??n}function il(n){return n.closest("pre")??n.parentElement??n}var ms=new Set,bs=new Map,vs=!1;function Pe(n,t){t?bs.set(n,t):ms.add(n),!vs&&(vs=!0,queueMicrotask(()=>{vs=!1;let e=[...ms],s=[...bs];ms.clear(),bs.clear();for(let i of e)al(i);for(let[i,r]of s)i.isConnected&&St(i,r)}))}var Qn=new WeakMap;function rl(n,t,e){let s=Qn.get(n);if(!s){let i=new Map;Qn.set(n,i),s=i,n.then(()=>{for(let[r,a]of i)Pe(r,a);i.clear()},()=>i.clear())}(!s.has(t)||e===void 0)&&s.set(t,e)}var vt=null;function ir(n){for(let t=n.parentElement;t;t=t.parentElement){let e=getComputedStyle(t).overflowY;if(e==="auto"||e==="scroll")return t}return null}function al(n){if(!n.isConnected)return;let t=ir(n),e=t?t.getBoundingClientRect().top+(parseFloat(getComputedStyle(t).scrollPaddingTop)||0):0;vt={scroller:t,top:e};try{St(n,sr.get(n)??{})}finally{vt=null}}function ol(n,t){let e=nl(n);if(Yn.has(e)||typeof IntersectionObserver>"u")return!1;let s=ir(e),i=Jn.get(IntersectionObserver);i||(i={byScroller:new WeakMap},Jn.set(IntersectionObserver,i));let r=s?i.byScroller.get(s):i.page;if(!r){let a=new IntersectionObserver(o=>{for(let l of o){let c=l.target;if(c.isConnected&&!l.isIntersecting)continue;a.unobserve(c);let d=(oe.get(a)??1)-1;if(oe.set(a,d),d<=0&&(a.disconnect(),s?i.byScroller.delete(s):i.page===a&&(i.page=void 0)),!c.isConnected)continue;Yn.add(c);let u=_s.get(c);u&&Pe(u)}},{root:s,rootMargin:"100% 0px"});r=a,s?i.byScroller.set(s,a):i.page=a}return _s.get(e)!==t&&(_s.set(e,t),oe.set(r,(oe.get(r)??0)+1),r.observe(e)),!0}function $t(n,t,e,s,i,r,a=!0){if(e.html===null){Lt(t,i.open);return}let o=vt?il(t):null,l=o?o.getBoundingClientRect():null,c=nt.get(t),d=c?.drawing;if(d||(d=document.createElement("span"),d.className=Ut,i.display&&d.setAttribute("data-aparte-display",""),s.bare?d.setAttribute("data-aparte-bare",""):d.setAttribute("dir","ltr"),t.after(d),tn.set(d,t),t.parentElement?.tagName==="PRE"&&t.parentElement.setAttribute(Zi,"")),c?.entry!==e||d.childNodes.length===0){let u=a?Kn.get(n):void 0;a&&!u&&(u=new WeakMap,Kn.set(n,u));let h=u?.get(e);if(h&&h.owner!==t&&!h.owner.isConnected&&t.isConnected&&!h.drawing.isConnected&&h.drawing.childNodes.length>0)d.replaceChildren(...h.drawing.childNodes),h.drawing.remove(),Lt(h.owner,!1);else{d.innerHTML=e.html;try{s.relabel?.(d,i)}catch(f){jt(s,f)}}u&&(c&&c.entry!==e&&u.get(c.entry)?.drawing===d&&u.delete(c.entry),u.set(e,{drawing:d,owner:t}))}if(t.hidden=!0,t.style.setProperty("display","none"),t.classList.remove(Qi),nt.set(t,{renderer:s,key:r,drawing:d,entry:e,ctx:i}),o&&l&&vt){let u=o.getBoundingClientRect().height-l.height;u>0&&l.bottom<=vt.top&&(vt.scroller?vt.scroller.scrollTop+=u:window.scrollBy(0,u))}}function Lt(n,t){let e=nt.get(n);e&&(e.drawing.remove(),nt.delete(n)),n.parentElement?.tagName==="PRE"&&n.parentElement.removeAttribute(Zi),n.hidden=!1,n.style.removeProperty("display"),n.classList.toggle(Qi,t)}function ll(n,t,e,s,i,r){let a=sl(e,s),o=nt.get(t);if(o&&o.renderer===e&&o.key===a&&o.drawing.childNodes.length>0)return;let l=Xo(e),c=l.get(a);if(c){$t(n,t,c,e,s,a,!r);return}if(!o&&!r){let f=tr.get(n)?.get(i);f&&s.source.startsWith(f.source)&&$t(n,t,f,e,s,null),o=nt.get(t)}if(e.lazy&&!r&&!o&&ol(t,n))return;let d=Qo(e),u=d.get(a);if(u){rl(u,n,r);return}let h;try{h=e.render(s)}catch(f){jt(e,f),h=null}if(!nr(h)){$t(n,t,l.set(a,h??null),e,s,a,!r);return}let p=h.then(f=>(d.delete(a),l.set(a,f??null),f),f=>{throw d.delete(a),jt(e,f),f});d.set(a,p),p.then(()=>Pe(n,r),()=>{})}function cl(n,t,e,s,i){let r=Xn(tr,n),a=r.get(i);a&&s.source.startsWith(a.source)?nt.get(t)?.entry!==a&&$t(n,t,a,e,s,null):(r.delete(i),Lt(t,!0));let o=Xn(er,n);if(o.get(i)===s.source)return;o.set(i,s.source);let l=()=>{o.get(i)===s.source&&o.delete(i)},c=u=>{if(u==null)return!1;let h=r.get(i);return h&&!s.source.startsWith(h.source)?!1:(r.set(i,{source:s.source,html:u}),!0)},d;try{d=e.render(s)}catch{d=null}if(!nr(d)){c(d)?$t(n,t,r.get(i),e,s,null):d==null&&l();return}d.then(u=>{c(u)?Pe(n):u==null&&l()},l)}function dl(n){for(let t of["code","kbd","samp"])for(let e of Array.from(n.getElementsByTagName(t)))e.hasAttribute("dir")||e.setAttribute("dir","ltr")}function St(n,t={}){if(typeof document>"u")return;let{streaming:e=!1,refresh:s=!1,language:i}=t;if(!s&&(dl(n),sr.set(n,{streaming:e}),e||er.delete(n),!k(n).hasCodeLanguageRenderer())){n.querySelector(`.${Ut}`)&&rr(n);return}let r=Array.from(n.querySelectorAll('code[class*="language-"]')).filter(o=>!o.closest(`.${Ut}`)),a=new Map;r.forEach((o,l)=>{let c=Zo(o);if(!c||i&&c!==i)return;let d=k(s?o:n),u=d.getCodeLanguageRenderer(c),h=nt.get(o);if(s&&(!h||h.key===null))return;if(!u){h&&Lt(o,!1);return}let p=tl(o),f=`${c}|${p?"d":"i"}`,g=a.get(f)??0;a.set(f,g+1);let _=`${f}|${g}`,S=o.textContent??"";if(!S.trim()){h&&Lt(o,!1);return}let E=e&&(el(o)||l===r.length-1),I={language:c,source:S,display:p,open:E,host:o,config:d};E?cl(n,o,u,I,_):ll(n,o,u,I,_,s?t:void 0)})}function rr(n){for(let t of Array.from(n.querySelectorAll(`.${Ut}`))){let e=tn.get(t);e?Lt(e,!1):t.remove()}}function ar(n){for(let t of Array.from(n.querySelectorAll(`.${Ut}`))){let e=tn.get(t),s=e?nt.get(e):void 0;if(s)try{s.renderer.relabel?.(t,s.ctx)}catch(i){jt(s.renderer,i)}}}function Is(n,t){return!!n&&k(t).hasCodeLanguageRenderer(n)}var or=new Set(["script","style","iframe","frame","frameset","object","embed","applet","form","button","textarea","select","option","optgroup","link","meta","base","title","head","html","body","template","noscript","svg","math","portal"]),en=new Set(["a","p","br","hr","div","span","pre","code","kbd","samp","var","strong","b","em","i","u","s","strike","del","ins","mark","small","sub","sup","blockquote","q","cite","ul","ol","li","dl","dt","dd","h1","h2","h3","h4","h5","h6","table","thead","tbody","tfoot","tr","td","th","caption","colgroup","col","img","figure","figcaption","picture","source","input","abbr","details","summary","time","wbr","address"]),ul=new Set(["class","style","title","dir","lang","role","align","aria-label","aria-hidden","aria-describedby","aria-level"]),hl={a:new Set(["href"]),img:new Set(["src","alt","width","height","loading","srcset","sizes","decoding"]),source:new Set(["src","srcset","type","media","sizes"]),input:new Set(["type","checked","disabled"]),td:new Set(["colspan","rowspan","headers"]),th:new Set(["colspan","rowspan","scope","headers"]),col:new Set(["span","width"]),colgroup:new Set(["span"]),ol:new Set(["start","type","reversed"]),time:new Set(["datetime"]),details:new Set(["open"])},pl=new Set(["href","src"]),fl=/^(?:https?:|mailto:|tel:|ftp:|sms:)/i,gl=/^(?:[#/.?]|[a-z0-9._~%+-]+(?:[/?#]|$))/i,_l=/^data:image\/(?:png|jpe?g|gif|webp|avif|bmp|x-icon|svg\+xml)[;,]/i,lr=/[\u0000-\u0020]+/g,Zn=/^(?:https?:)?[/\\]{2}|^https?:/i,ml=/^aparte-/i,bl=new Set(["data-aparte-chat","data-aparte-host","data-aparte-theme","data-aparte-split-pane","data-aparte-launcher-close","data-aparte-suggestions","data-aparte-bubble","data-aparte-empty","data-aparte-panel","data-aparte-panel-host","data-aparte-card-part","data-segment-id","data-action"]),vl=["data-aparte-dialog-","data-aparte-sidebar-","data-checkpoint-"];function yl(n){return bl.has(n)||vl.some(t=>n.startsWith(t))}var wl=new Set(["button","link","checkbox","textbox","searchbox","combobox","switch","tab","menuitem","menuitemcheckbox","menuitemradio","option","radio","slider","spinbutton","scrollbar","treeitem","gridcell","listbox","menu","menubar","radiogroup","tablist","tree","treegrid","grid","dialog","alertdialog","application","toolbar","progressbar","tabpanel"]);function Sl(n,t){let e=t==="source"?"img":t;for(let s of n.matchAll(/(?:^|[^a-z0-9+.-])([a-z][a-z0-9+.-]*:[^\s,]*)/gi))if(!Qt(s[1],e))return!1;return!0}function Qt(n,t){let e=n.replace(lr,"");return!e||fl.test(e)||t==="img"&&_l.test(e)?!0:/^[a-z][a-z0-9+.-]*:/i.test(e)?!1:gl.test(e)}var Al=new Set(["color","background-color","font-style","font-weight","font-family","font-size","font-variant","font-variant-ligatures","text-decoration","text-decoration-line","text-decoration-color","text-decoration-style","white-space"]);function Cl(n){return n.includes("\\")?!1:n.startsWith("--")&&!n.startsWith("--aparte-")}function El(n){let t=[];for(let e of n.split(";")){let s=e.trim(),i=s.indexOf(":");if(i===-1)continue;let r=s.slice(0,i).trim().toLowerCase(),a=s.slice(i+1);a.trim()&&(!Al.has(r)&&!Cl(r)||a.includes("\\")||/url\s*\(|expression\s*\(|javascript:|vbscript:|[<>]/i.test(a)||t.push(s))}return t.length?t.join("; "):null}function Ls(n,t,e){let s=hl[n];if(t.startsWith("on")||t.startsWith("formaction")||!t.startsWith("data-")&&!ul.has(t)&&!(s&&s.has(t))||yl(t)||t==="role"&&e.trim().toLowerCase().split(/\s+/).some(i=>wl.has(i))||pl.has(t)&&!Qt(e,n)||t==="srcset"&&!Sl(e,n))return null;if(t==="style")return El(e);if(t==="class"){let i=e.split(/\s+/).filter(r=>r&&!ml.test(r));return i.length?i.join(" "):null}return e}function cr(n,t){let e=n.replace(lr,""),s=t.trim().toLowerCase();return s==="_self"&&!Zn.test(e)?[["target","_self"]]:s||Zn.test(e)?[["target","_blank"],["rel","noopener noreferrer"]]:[]}function kl(n,t,e){for(let s of Array.from(n.attributes)){let i=s.name.toLowerCase(),r=Ls(e,i,s.value);r!==null&&t.setAttribute(i,r)}if(e==="a")for(let[s,i]of cr(t.getAttribute("href")??"",n.getAttribute("target")??""))t.setAttribute(s,i)}function Rs(n,t,e){for(let s of Array.from(n.childNodes)){if(s.nodeType===3){t.appendChild(e.createTextNode(s.nodeValue??""));continue}if(s.nodeType!==1)continue;let i=s,r=i.tagName.toLowerCase();if(or.has(r))continue;if(!en.has(r)){Rs(i,t,e);continue}let a=r==="input";if(a&&(i.getAttribute("type")??"").trim().toLowerCase()!=="checkbox")continue;let o=e.createElement(r);kl(i,o,r),a&&(o.setAttribute("type","checkbox"),o.setAttribute("disabled","")),Rs(i,o,e),t.appendChild(o)}}var Tl=new Set(["html","head","body"]),Ml=new Set(["link","meta","base","embed","frame"]),ti=new Map;function xl(n){let t=ti.get(n);return t||(t=new RegExp(`<\\s*\\/\\s*${n}\\s*>`,"gi"),ti.set(n,t)),t}var ei=/--!?>/g,Il=/[A-Za-z]/,le=/\s/,Ll=/[\s/>]/,Rl=/[\s/>=]/,Ol=/^[a-z][a-z0-9_.:-]*$/,Pl={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",colon:":",lpar:"(",rpar:")",sol:"/",bsol:"\\",period:".",comma:",",semi:";",num:"#",excl:"!",quest:"?",tab:" ",newline:`
|
|
5
|
+
`};function Nl(n){return n.includes("&")?n.replace(/&(?:#x([0-9a-f]+)|#([0-9]+)|([a-z]+));?/gi,(t,e,s,i)=>{if(i!==void 0)return Pl[i.toLowerCase()]??t;let r=e!==void 0?parseInt(e,16):parseInt(s??"",10);return r>0&&r<=1114111&&(r<55296||r>57343)?String.fromCodePoint(r):"\uFFFD"}):n}var Dl=n=>n.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">");function Bl(n,t){if(!en.has(n))return"";let e=n==="input",s=r=>t.find(([a])=>a===r)?.[1];if(e&&(s("type")??"").trim().toLowerCase()!=="checkbox")return"";let i=[];e&&(i.push('type="checkbox"'),s("checked")!==void 0&&i.push("checked"),i.push("disabled"));for(let[r,a]of t){if(!Ol.test(r)||e&&(r==="type"||r==="checked"||r==="disabled"))continue;let o=Ls(n,r,a);o!==null&&i.push(`${r}="${Dl(o)}"`)}if(n==="a"){let r=t.find(([o])=>o==="href"),a=r?Ls("a","href",r[1]):null;for(let[o,l]of cr(a??"",s("target")??""))i.push(`${o}="${l}"`)}return`<${n}${i.length?" "+i.join(" "):""}>`}function dr(n,t){let e=n.length,s=t;for(;s<e&&!Ll.test(n[s]);)s++;let i=n.slice(t,s).toLowerCase(),r=[],a=new Set;for(;s<e;){for(;s<e&&(le.test(n[s])||n[s]==="/");)s++;if(s>=e)break;if(n[s]===">")return{tag:i,attrs:r,end:s+1};let o=s++;for(;s<e&&!Rl.test(n[s]);)s++;let l=n.slice(o,s).toLowerCase(),c=s;for(;c<e&&le.test(n[c]);)c++;let d="";if(n[c]==="="){for(c++;c<e&&le.test(n[c]);)c++;let u=n[c];if(u==='"'||u==="'"){let h=n.indexOf(u,c+1);if(h<0)break;d=n.slice(c+1,h),s=h+1}else{let h=c;for(;c<e&&!le.test(n[c])&&n[c]!==">";)c++;d=n.slice(h,c),s=c}}a.has(l)||(a.add(l),r.push([l,Nl(d)]))}return{tag:i,attrs:r,end:-1}}function Hl(n){let t=n.length,e="",s=0;for(;s<t;){let i=n.indexOf("<",s);if(i<0){e+=n.slice(s);break}if(e+=n.slice(s,i),n.startsWith("<!--",i)){let d=i+4;if(n[d]===">")s=d+1;else if(n.startsWith("->",d))s=d+2;else{ei.lastIndex=d;let u=ei.exec(n);if(!u)break;s=u.index+u[0].length}continue}let r=n[i+1]==="/",a=i+(r?2:1);if(!Il.test(n[a]??"")){if(n[i+1]==="!"||n[i+1]==="?"||r){let d=n.indexOf(">",i+1);s=d<0?t:d+1}else e+="<",s=i+1;continue}let{tag:o,attrs:l,end:c}=dr(n,a);if(c<0)break;if(s=c,r)en.has(o)&&(e+=`</${o}>`);else if(or.has(o)&&!Tl.has(o)&&!Ml.has(o)){let d=xl(o);d.lastIndex=c;let u=d.exec(n);if(!u)break;s=u.index+u[0].length}else e+=Bl(o,l)}return e}function si(n){return Hl(n)}var Os=n=>{if(!n)return n;if(typeof DOMParser>"u")return si(n);let t;try{t=new DOMParser().parseFromString(n,"text/html")}catch{return si(n)}let e=t.createElement("div");return Rs(t.body,e,t),e.innerHTML},at="aparte-citation",ur="aparte-citation-marker",hr=/[\p{L}\p{N}]/u,$l=[24,12,6],pr=new Set(["A","ABBR","B","CITE","CODE","DEL","EM","I","INS","KBD","MARK","Q","S","SMALL","SPAN","STRONG","SUB","SUP","U"]),ni=/[.,;:!?)\]}»"'’”…。、,.!?:;」』)】》،؛؟]/,ql=/[\u00a0\u202f]/,sn=new WeakMap,fr=new WeakMap,ii=new WeakSet,fe=new WeakMap,ut=null;function nn(n){let t=n.url?.trim();return t&&/^https?:\/\//i.test(t)&&Qt(t,"a")?t:void 0}function Ae(n){let t=nn(n);if(t)try{return new URL(t).hostname.replace(/^www\./,"")}catch{}return n.title??""}function Fl(n){let t=Ae(n[0])||"?";return n.length>1?`${t} +${n.length-1}`:t}function Ps(n,t){let e=n.getLocale();return t===1?e.sourcesOne??"1 source":(e.sourcesCount??"{n} sources").replace("{n}",()=>String(t))}function Wl(n){if(typeof document>"u")return"";let t=document.createElement("textarea");return t.innerHTML=n,t.value}function ri(n){return n.replace(/^[ \t]*(?:>[ \t]*)*(?:\d{1,9}[.)]|[*+-])[ \t]+(?:\[[ xX]\][ \t]+)?/gm,"").replace(/<!--[\s\S]*?-->/g,"").replace(/!\[[^\]\n]*\]\([^)\n]*\)/g,"").replace(/<([a-z][a-z0-9+.-]*:[^>\s]+)>/gi,"$1").replace(/\]\([^)\n]*\)/g,"]").replace(/<\/?[A-Za-z][^>\n]*>/g,"").replace(/&(?:#\d+|#x[0-9a-f]+|[a-z][a-z0-9]*);/gi,Wl)}function Ul(n){let t=n.replace(/^ {0,3}(?:`{3,}|~{3,})[^\n]*$/gm,""),e="",s=0;for(let r of t.matchAll(/(`+)([^`][\s\S]*?)\1/g))e+=ri(t.slice(s,r.index))+r[2],s=(r.index??0)+r[0].length;e+=ri(t.slice(s));let i="";for(let r of e)hr.test(r)&&(i+=r);return i}function jl(n){let t="",e=[],s=n.ownerDocument.createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode:i=>i.parentElement?.closest(`.aparte-code-drawing, .${at}`)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT});for(let i=s.nextNode();i;i=s.nextNode()){let r=i.data;for(let a=0;a<r.length;){let o=(r.codePointAt(a)??0)>65535?2:1,l=r.slice(a,a+o);if(a+=o,!!hr.test(l)){t+=l;for(let c=0;c<o;c++)e.push([i,a])}}}return{text:t,ends:e}}function Gl(n,t){let e=0;for(let s=n.indexOf(t);s>=0;s=n.indexOf(t,s+1))e++;return e}function zl(n,t,e){let s=Ul(n.slice(0,Math.max(0,Math.min(n.length,t.end))));if(!s)return null;for(let i of $l){let r=s.slice(-i),a=Gl(s,r),o=-1;for(let l=0;l<a&&(l===0||o>=0);l++)o=e.text.indexOf(r,o+1);if(o>=0)return e.ends[o+r.length-1]??null;if(r.length===s.length)break}return null}function ai(n,t){let e=t;for(;e<n.length&&(ni.test(n[e])||ql.test(n[e])&&ni.test(n[e+1]??""));)e++;return e-t}function Kl(n,t,e,s){let i=e.parentElement?.closest("pre");if(i&&n.contains(i)){i.after(t);return}let r=null;for(let l=e.parentElement;l&&l!==n&&pr.has(l.tagName);l=l.parentElement)r=l;if(!r){e.splitText(s+ai(e.data,s)),e.after(t);return}let a=r;for(;a.nextSibling instanceof Element&&a.nextSibling.classList.contains("aparte-code-drawing");)a=a.nextSibling;let o=a.nextSibling;if(o instanceof Text){let l=ai(o.data,0);l>0&&(o.splitText(l),a=o)}a.parentNode.insertBefore(t,a.nextSibling)}function Vl(n,t,e,s){let i=l=>{let c=document.createElement("span");c.className=ur,c.hidden=!0,l.parentNode.insertBefore(c,l),c.append(l),c.after(n)},r=t.data.lastIndexOf(s,e);if(r>=0&&r+s.length>=e){let l=t.splitText(r);return l.splitText(s.length),i(l),!0}let a=t.parentElement,o=s.replace(/^\[|\]$/g,"");return a&&pr.has(a.tagName)&&a.textContent?.trim()===o?(i(a),!0):!1}function Yl(n,t){let e=document.createElement("button");return e.type="button",e.className="aparte-citation aparte-tag aparte-tag--sm",e.setAttribute("aria-haspopup","dialog"),e.setAttribute("aria-expanded","false"),sn.set(e,n),gr(e,t),e}function gr(n,t){let e=sn.get(n)??[],s=Fl(e);n.dataset.label=s,n.setAttribute("aria-label",`${s}, ${Ps(t,e.length)}`)}function _r(n){let t=new Set;for(let e of Array.from(n.querySelectorAll(`.${at}`)))e.parentNode&&t.add(e.parentNode),e.remove();for(let e of Array.from(n.querySelectorAll(`.${ur}`)))e.parentNode&&t.add(e.parentNode),e.replaceWith(...Array.from(e.childNodes));for(let e of t)e.normalize();fe.delete(n)}function Ns(n,t){if(typeof document>"u")return;let e=t.citations??[],s=new Map((t.sources??[]).map(g=>[g.id,g])),i=JSON.stringify([t.content,e,[...s.values()].map(g=>[g.id,g.url,g.title,g.snippet])]),r=Array.from(n.querySelectorAll(`.${at}`)),a=fe.get(n);if(a&&a.signature===i&&a.count===r.length)return;let o=document.activeElement,l=ut?.root===n&&(o===ut.chip||(!o||o===document.body)&&!ut.chip.isConnected)?ut.at:-1,c=N?.root===n?N.chip.isConnected?r.indexOf(N.chip):N.at:-1;if(_r(n),e.length===0||s.size===0){fe.set(n,{signature:i,count:0}),c>=0&&tt(!1);return}let d=k(n);ii.has(n)||(ii.add(n),n.addEventListener("click",g=>{let _=g.target?.closest?.(`.${at}`);!_||!n.contains(_)||(g.preventDefault(),Xl(_))}),n.addEventListener("focusin",g=>{let _=g.target;_.classList?.contains(at)&&(ut={root:n,chip:_,at:Array.from(n.querySelectorAll(`.${at}`)).indexOf(_)})}),n.addEventListener("focusout",g=>{ut?.root===n&&g.relatedTarget&&(ut=null)}));let u=jl(n),h=new Map;for(let g of e){let _=g.sources.map(y=>s.get(y)).filter(y=>!!y);if(_.length===0)continue;let S=zl(t.content,g,u);if(!S)continue;let E=u.ends.indexOf(S),I=g.marker&&g.start!==void 0?t.content.slice(g.start,g.end):null,b=h.get(E)??{node:S[0],offset:S[1],marker:I,sources:[]};for(let y of _)b.sources.includes(y)||b.sources.push(y);h.set(E,b)}let p=[...h.values()].sort((g,_)=>g.node===_.node?_.offset-g.offset:g.node.compareDocumentPosition(_.node)&Node.DOCUMENT_POSITION_FOLLOWING?1:-1);for(let g of p){let _=Yl(g.sources,d);fr.set(_,n),!(g.marker&&Vl(_,g.node,g.offset,g.marker))&&Kl(n,_,g.node,g.offset)}let f=Array.from(n.querySelectorAll(`.${at}`));if(fe.set(n,{signature:i,count:f.length}),l>=0&&(f[l]?f[l].focus({preventScroll:!0}):ut=null),c>=0&&N){let g=f[c];g?(N.chip=g,N.at=c,g.setAttribute("aria-expanded","true"),g.setAttribute("aria-controls",N.el.id)):tt(!1)}}function mr(n){let t=k(n);for(let e of Array.from(n.querySelectorAll(`.${at}`)))gr(e,t)}var N=null,Jl=0;function Xl(n){N?.chip===n?tt(!0):Ql(n)}function Ql(n){tt(!1);let t=sn.get(n)??[];if(t.length===0)return;let e=fr.get(n)??n.parentElement,s=Array.from(e.querySelectorAll(`.${at}`)).indexOf(n),i=k(n),r=document.createElement("div");r.className="aparte-citation-card aparte-popover",r.id=`aparte-citation-card-${++Jl}`;let a=n.closest(".aparte-viewport-container, aparte-chat-viewport")??n.ownerDocument.documentElement;r.dir=getComputedStyle(a).direction==="rtl"?"rtl":"ltr",r.setAttribute("role","dialog"),r.setAttribute("aria-label",i.getLocale().sourcesCard??"Sources");let o=document.createElement("div");o.className="aparte-citation-card__body";let l=document.createElement("p");l.className="aparte-sr-only",l.setAttribute("role","status"),r.append(o,l);let c=typeof r.showPopover=="function";c&&(r.popover="manual"),(n.closest("aparte-chat-viewport")?.parentElement??n.ownerDocument.body).append(r),c&&r.showPopover(),n.setAttribute("aria-expanded","true"),n.setAttribute("aria-controls",r.id);let d=typeof MutationObserver=="function"?new MutationObserver(tc):null;d?.observe(n.ownerDocument.body,{childList:!0,subtree:!0}),N={root:e,chip:n,at:s,el:r,body:o,status:l,sources:t,index:0,config:i,watch:d},wr(),Gt(),document.addEventListener("keydown",br,!0),document.addEventListener("pointerdown",vr,!0),window.addEventListener("scroll",yr,!0),window.addEventListener("resize",Gt),r.addEventListener("focusout",sc),r.addEventListener("keydown",ec),Zl(r)}function Zl(n){(n.querySelector("a")??n.querySelector("button:not([disabled])"))?.focus()}function tt(n){if(!N)return;let{chip:t,el:e,watch:s}=N;N=null,s?.disconnect(),e.remove(),t.setAttribute("aria-expanded","false"),t.removeAttribute("aria-controls"),document.removeEventListener("keydown",br,!0),document.removeEventListener("pointerdown",vr,!0),window.removeEventListener("scroll",yr,!0),window.removeEventListener("resize",Gt),n&&t.isConnected&&t.focus()}function tc(){N&&!N.chip.isConnected&&tt(!1)}function br(n){n.key!=="Escape"||!N||(n.preventDefault(),tt(!0))}function ec(n){if(n.key!=="Tab"||!N)return;let t=Array.from(N.el.querySelectorAll("a[href], button:not([disabled])")),e=n.shiftKey?t[0]:t[t.length-1];document.activeElement===e&&(n.preventDefault(),tt(!0))}function vr(n){if(!N)return;let t=n.target;t&&(N.el.contains(t)||N.chip.contains(t))||tt(!1)}function sc(n){if(!N)return;let t=n.relatedTarget;t&&(N.el.contains(t)||N.chip.contains(t))||t&&tt(!1)}function nc(n){for(let t=n.parentElement;t;t=t.parentElement){let e=getComputedStyle(t).overflowY;if(e==="auto"||e==="scroll")return t}return null}function yr(){if(!N)return;let n=nc(N.chip);if(n){let t=n.getBoundingClientRect(),e=N.chip.getBoundingClientRect();if(e.bottom<t.top||e.top>t.bottom){tt(!1);return}}Gt()}function Gt(){if(!N)return;let{chip:n,el:t}=N;if(!n.isConnected){tt(!1);return}let e=n.getBoundingClientRect();t.style.left="0px",t.style.top="0px";let s=t.getBoundingClientRect(),i=6,a=getComputedStyle(n).direction==="rtl"?e.right-t.offsetWidth:e.left,o=Math.max(8,Math.min(a,window.innerWidth-t.offsetWidth-8)),l=e.bottom+i;l+t.offsetHeight>window.innerHeight-8&&e.top-t.offsetHeight-i>8&&(l=e.top-t.offsetHeight-i),t.style.left=`${o-s.left}px`,t.style.top=`${l-s.top}px`}function wr(){if(!N)return;let{el:n,body:t,status:e,sources:s,index:i,config:r}=N,a=r.getLocale(),o=s[i],l=n.contains(document.activeElement)?document.activeElement.dataset.aparteCardPart:void 0;if(t.replaceChildren(),s.length>1){let h=document.createElement("div");h.className="aparte-citation-card__pager";let p=oi(a.sourcePrevious??"Previous source",r.getIcon("prevBranch"),"prev",i===0,()=>li(-1)),f=document.createElement("span");f.className="aparte-citation-card__position",f.textContent=`${i+1}/${s.length}`,f.setAttribute("aria-hidden","true");let g=oi(a.sourceNext??"Next source",r.getIcon("nextBranch"),"next",i===s.length-1,()=>li(1));h.append(p,f,g),t.append(h)}let c=nn(o),d=o.title||Ae(o)||o.url||"";if(c){let h=document.createElement("a");h.className="aparte-citation-card__title",h.href=c,h.target="_blank",h.rel="noopener noreferrer",h.dataset.aparteCardPart="link",h.textContent=d,h.dir="auto";let p=document.createElement("span");p.className="aparte-sr-only",p.textContent=` ${a.opensInNewTab??"(opens in a new tab)"}`,h.append(p),t.append(h)}else{let h=document.createElement("p");h.className="aparte-citation-card__title",h.textContent=d,h.dir="auto",t.append(h)}let u=Ae(o);if(u&&u!==d){let h=document.createElement("p");h.className="aparte-citation-card__domain",h.textContent=u,h.dir="auto",t.append(h)}if(o.snippet){let h=document.createElement("p");h.className="aparte-citation-card__snippet",h.textContent=o.snippet,h.dir="auto",t.append(h)}if(s.length>1&&(e.textContent=(a.sourcePosition??"Source {i} of {n}").replace("{i}",()=>String(i+1)).replace("{n}",()=>String(s.length))),l){let h=n.querySelector(`[data-aparte-card-part="${l}"]`);h&&!h.disabled?h.focus():(n.querySelector(".aparte-citation-card__pager button:not([disabled])")??n.querySelector("a"))?.focus()}}function oi(n,t,e,s,i){let r=document.createElement("button");return r.type="button",r.className="aparte-btn aparte-btn--icon aparte-btn--sm",r.setAttribute("aria-label",n),r.dataset.aparteCardPart=e,r.disabled=s,r.innerHTML=t,r.addEventListener("click",i),r}function li(n){N&&(N.index=Math.max(0,Math.min(N.sources.length-1,N.index+n)),wr(),Gt())}function Sr(n,t,e,s){let i=n.querySelector(":scope > .aparte-sources"),r=[],a=new Set;for(let u of e){let h=u.url??`#${u.id}${u.title??""}`;a.has(h)||(a.add(h),r.push(u))}if(r.length===0){i?.remove();return}let o=s.getLocale().opensInNewTab??"(opens in a new tab)",l=[o,...r.map(u=>`${u.url??u.id}${u.title??""}`)].join("");if(!i)i=document.createElement("details"),i.className="aparte-sources",t.after(i);else if(i.dataset.aparteKey===l){i.querySelector("summary").textContent=Ps(s,r.length);return}i.dataset.aparteKey=l;let c=document.createElement("summary");c.className="aparte-sources__summary",c.textContent=Ps(s,r.length);let d=document.createElement("ol");d.className="aparte-sources__list";for(let u of r){let h=document.createElement("li");h.className="aparte-sources__item";let p=Ae(u),f=u.title||p||u.url||"",g=nn(u);if(g){let _=document.createElement("a");_.href=g,_.target="_blank",_.rel="noopener noreferrer",_.textContent=f,_.dir="auto";let S=document.createElement("span");S.className="aparte-sr-only",S.textContent=` ${o}`,_.append(S),h.append(_)}else h.append(Object.assign(document.createElement("span"),{textContent:f,dir:"auto"}));if(p&&p!==f){let _=document.createElement("span");_.className="aparte-sources__domain",_.textContent=p,_.dir="auto",h.append(" ",_)}d.append(h)}i.replaceChildren(c,d)}var Pt=new WeakMap,ci="<i>a</i>";function di(){return k().renderMarkdown(ci)!==L(ci)}function Rt(n,t,e,s){ic(n,t,e,s),St(t,{streaming:s})}function ic(n,t,e,s){let i=k();if(s){if(Pt.delete(t),n._aparteSmd===void 0){let a=k().createStreamingMarkdownRenderer(t);a?(t.textContent="",n._aparteSmd={renderer:a,written:0}):n._aparteSmd=null}let r=n._aparteSmd;if(r){let a=e.slice(r.written);a&&(r.renderer.write(a),r.written=e.length);return}}else if(n._aparteSmd){let r=n._aparteSmd,a=e.slice(r.written);if(a&&(r.renderer.write(a),r.written=e.length),r.renderer.end(),n._aparteSmd=void 0,!di()){rr(t),_r(t),t.innerHTML=i.sanitizeHtml(t.innerHTML),Pt.set(t,{content:e,config:i,version:Z(i),writer:"parser"});return}}else{let r=Pt.get(t);if(r?.content===e&&(r.writer==="parser"&&!di()||r.writer==="markdown"&&r.config===i&&r.version===Z(i)))return}t.innerHTML=i.renderMarkdown(e),s?Pt.delete(t):Pt.set(t,{content:e,config:i,version:Z(i),writer:"markdown"})}function Ds(n){if(!k().hasHighlightProvider())return;let t=n.querySelectorAll("pre > code:not([data-aparte-highlighted])");for(let e of t){let s=e.parentElement;if(!s)continue;let i=Array.from(e.classList).find(a=>a.startsWith("language-"))?.slice(9)??"";if(Is(i,n)||e.closest(".aparte-code-drawing"))continue;let r=e.textContent??"";e.setAttribute("data-aparte-highlighted",""),k().highlightCode(r,i,{fallback:!1}).then(a=>{(s.isConnected||s.parentElement)&&rn(s,a)}).catch(()=>e.removeAttribute("data-aparte-highlighted"))}}function rn(n,t){let e=document.createElement("template");e.innerHTML=t;for(let s of Array.from(e.content.querySelectorAll("code")))s.setAttribute("data-aparte-highlighted","");n.replaceWith(e.content)}var rc={type:"text",render:n=>`<div class="aparte-segment aparte-segment-text" data-segment-id="${L(n.id)}"><div class="aparte-segment-content" dir="auto">${k().renderMarkdown(n.content)}</div></div>`,setup:(n,t)=>{let e=n.querySelector(".aparte-segment-content");e&&(t.isStreaming===!0?Rt(n,e,t.content,!0):(St(e,{streaming:!1}),Ds(e)),Ns(e,t))},update:(n,t)=>{let e=n.querySelector(".aparte-segment-content");e&&(Rt(n,e,t.content,t.isStreaming!==!1),t.isStreaming===!1&&Ds(e),Ns(e,t))},getStyles:()=>""};function an(n,t){let e=Math.max(1,Math.round(n/1e3));try{let s=(a,o)=>new Intl.NumberFormat(t,{style:"unit",unit:o,unitDisplay:"narrow"}).format(a);if(e<60)return s(e,"second");let i=Math.floor(e/60),r=e%60;return r?new Intl.ListFormat(t,{style:"narrow",type:"unit"}).format([s(i,"minute"),s(r,"second")]):s(i,"minute")}catch{return`${e}s`}}var ac=24;function Bs(n){if(n.label&&n.label!=="Thinking")return n.label;let t=k();if(!ft(n))return t.t("thinking");let s=n.showDuration??t.getSegmentDefaults("thinking")?.showDuration===!0?Vi(n):void 0;return s===void 0?t.t("thought"):t.t("thoughtFor").replace("{duration}",()=>an(s,t.getLocale().tag||void 0))}var Hs=n=>n.isStreaming===!0;function ui(n,t){let e=Bs(t),s=n.querySelector(".aparte-thinking-label");s&&s.textContent!==e&&(s.textContent=e),s?.classList.toggle("aparte-shimmer",Hs(t)),n.querySelector(".aparte-thinking-content")?.setAttribute("aria-label",e)}var oc={type:"thinking",render:n=>`<details class="aparte-segment aparte-segment-thinking aparte-accordion__item" data-segment-id="${L(n.id)}" ${n.collapsed===!1?"open":""}><summary class="aparte-accordion__header aparte-thinking-header"><span class="aparte-thinking-label${x(Hs(n)?" aparte-shimmer":"")}">${L(Bs(n))}</span><span class="aparte-accordion__icon">${k().getIcon("expand")}</span></summary><div class="aparte-accordion__panel aparte-thinking-content" dir="auto" role="region" tabindex="0" aria-label="${x(Bs(n))}">${k().renderMarkdown(n.content)}</div></details>`,relabel:(n,t)=>ui(n,t),setup:(n,t)=>{let e=n.querySelector(".aparte-thinking-content");e&&(Hs(t)?Rt(n,e,t.content,!0):St(e,{streaming:!1}))},update:(n,t)=>{ui(n,t);let e=n.querySelector(".aparte-thinking-content");if(!e)return;let s=e.scrollHeight-e.scrollTop-e.clientHeight<=ac,i=t.isStreaming!==!1;Rt(n,e,t.content,i),i||Ds(e),s&&(e.scrollTop=e.scrollHeight)},getStyles:()=>""};function on(n){return typeof navigator<"u"&&navigator.clipboard&&typeof navigator.clipboard.writeText=="function"?navigator.clipboard.writeText(n):new Promise((t,e)=>{if(typeof document>"u"||typeof document.execCommand!="function"){e(new Error("[aparte] No clipboard available in this context"));return}let s=document.createElement("textarea");s.value=n,s.setAttribute("readonly",""),s.setAttribute("aria-hidden","true"),s.style.position="fixed",s.style.top="0",s.style.left="-9999px",s.style.opacity="0";let i=document.activeElement;document.body.appendChild(s),s.focus(),s.select(),s.setSelectionRange(0,n.length);let r=!1;try{r=document.execCommand("copy")}catch{r=!1}s.remove(),i instanceof HTMLElement&&i.focus(),r?t():e(new Error("[aparte] Clipboard write failed"))})}var lc=1500;function $s(n,t){n.setAttribute("aria-label",t),n.setAttribute("title",t)}function ln(n){let t=x(k().t("copy")),e=k().getIcon("copy");return`<button type="button" class="aparte-btn aparte-btn--icon aparte-btn--sm ${x(n)}" data-action="copy" aria-label="${t}" title="${t}">${e}</button>`}function Ar(n,t){n.addEventListener("click",()=>{on(t()).catch(()=>{}),n.innerHTML=k(n).getIcon("check"),$s(n,k(n).t("copied")),n.dataset.copied="1",setTimeout(()=>{n.innerHTML=k(n).getIcon("copy"),$s(n,k(n).t("copy")),delete n.dataset.copied},lc)})}function Cr(n){n.dataset.copied||($s(n,k().t("copy")),n.innerHTML=k().getIcon("copy"))}var cc=400,dc=256,hi=new Map;function uc(n,t,e){if(n.delete(t),n.size>=dc){let s=n.keys().next().value;s!==void 0&&n.delete(s)}n.set(t,e)}function pi(n){let t=Number(n.dataset.aparteHlLen);return Number.isFinite(t)&&t>0?t:0}function hc(n,t,e,s,i){let r=n.querySelector(t);if(!r)return;delete r.dataset.aparteSettled;let a=r.querySelector("[data-aparte-tail]"),o=pi(r);if(a&&o<=e.length)a.textContent=e.slice(o);else{delete r.dataset.aparteHlLen;let d=r.querySelector("code");d?d.textContent=e:r.innerHTML=`<pre><code class="language-${L(s||"text")}">${L(e)}</code></pre>`}let l=e.lastIndexOf(`
|
|
6
|
+
`)+1;if(l<=o)return;let c=Date.now();c-(hi.get(i)??0)<cc||(uc(hi,i,c),k(n).highlightCode(e.slice(0,l),s).then(d=>{let u=n.querySelector(t);if(!u||u.dataset.aparteSettled!==void 0||l<=pi(u))return;u.innerHTML=d;let h=u.querySelector("code")??u,p=document.createElement("span");p.dataset.aparteTail="",p.textContent=e.slice(l),h.appendChild(p),u.dataset.aparteHlLen=String(l)}).catch(()=>{}))}var ys=new WeakMap,Mt=new WeakMap,ws=new WeakMap;function fi(n,t){let e=n.querySelector(".aparte-code-content-wrapper");if(!e)return;let s=`${t.language??""}${t.content}`,i=k(),r=ws.get(n);if(r?.what===s&&r.config===i)return;ws.set(n,{what:s,config:i});let a=(Mt.get(n)??0)+1;Mt.set(n,a),e.dataset.aparteSettled="",i.highlightCode(t.content,t.language||"",{fallback:!1}).then(o=>{Mt.get(n)===a&&(e.innerHTML=o)}).catch(()=>{Mt.get(n)===a&&ws.delete(n)})}var Ce=n=>(n.language||"").trim().split(/\s+/)[0]??"";function gi(n,t){let e=Ce(t),s=e?k(n).getCodeLanguageRenderer(e):void 0;n.toggleAttribute("data-aparte-bare",!!s&&s.card!==!0)}function _i(n,t){let e=n.querySelector(".aparte-code-content-wrapper");if(!e)return;Mt.set(n,(Mt.get(n)??0)+1),e.dataset.aparteSettled="";let s=Ce(t),i=Array.from(e.querySelectorAll("pre > code")).find(r=>r.classList.contains(`language-${s}`));i||(e.innerHTML=`<pre><code class="language-${L(s)}"></code></pre>`,i=e.querySelector("pre > code")),i.textContent!==t.content&&(i.textContent=t.content),St(e,{streaming:t.isStreaming===!0})}var pc={type:"code",render:n=>{let t=ln("aparte-code-copy");return`
|
|
7
|
+
<div class="aparte-segment aparte-segment-code" data-segment-id="${L(n.id)}">
|
|
8
|
+
<div class="aparte-code-header">
|
|
9
|
+
${n.filename?`<span class="aparte-code-filename">${L(n.filename)}</span>`:'<span class="aparte-code-header-filler"></span>'}
|
|
10
|
+
<span class="aparte-code-language">${L(n.language||"")}</span>
|
|
11
|
+
${t}
|
|
12
|
+
</div>
|
|
13
|
+
<div class="aparte-code-content-wrapper">
|
|
14
|
+
<pre><code class="language-${L(n.language||"text")}">${L(n.content)}</code></pre>
|
|
15
|
+
</div>
|
|
16
|
+
</div>
|
|
17
|
+
`},relabel:n=>{let t=n.querySelector(".aparte-code-copy");t&&Cr(t)},setup:(n,t)=>{ys.set(n,t.content),gi(n,t),Is(Ce(t),n)?_i(n,t):t.isStreaming!==!0&&fi(n,t);let e=n.querySelector(".aparte-code-copy");e&&Ar(e,()=>ys.get(n)??"")},update:(n,t)=>{ys.set(n,t.content),gi(n,t),Is(Ce(t),n)?_i(n,t):t.isStreaming===!0?hc(n,".aparte-code-content-wrapper",t.content,t.language||"",t.id):fi(n,t)},getStyles:()=>""};function qs(n,t){switch(n){case B.NET_OFFLINE:case B.NET_ERROR:return t("errorUnreachable");case B.NET_TIMEOUT:return t("errorTimeout");case B.CONFIG_INVALID_KEY:return t("errorRefused");case B.USAGE_RATE_LIMIT:return t("errorRateLimited");case B.USAGE_CONTEXT_EXCEEDED:return t("errorTooLong");case B.PROVIDER_ERROR:case B.PROVIDER_UNAVAILABLE:return t("errorFailed");case B.USAGE_BAD_REQUEST:case B.PROVIDER_POLICY:case B.PROVIDER_MISCONFIGURED:case B.CONFIG_INVALID_MODEL:case B.UNKNOWN_ERROR:return t("errorNoAnswer");default:return}}var fc={type:"error",render:n=>{let t=k(),e=qs(n.code,r=>t.t(r)),s=t.getErrorRenderer?.();if(s){let r=s({message:n.content,...e!==void 0?{sentence:e}:{},...n.details!==void 0?{details:n.details}:{},...n.code!==void 0?{code:n.code}:{}});return r instanceof HTMLElement&&r.setAttribute("data-segment-id",n.id),r}let i=e??n.content;return`
|
|
18
|
+
<div class="aparte-segment aparte-alert aparte-alert--danger aparte-segment-error" data-segment-id="${L(n.id)}"${n.code?` data-error-code="${x(n.code)}"`:""}>
|
|
19
|
+
<span class="aparte-alert__icon">${t.getIcon("error")||"\u26A0"}</span>
|
|
20
|
+
<div class="aparte-alert__body">
|
|
21
|
+
<div class="aparte-alert__title">${L(t.t("error"))}</div>
|
|
22
|
+
<div class="aparte-alert__message">${L(i)}</div>
|
|
23
|
+
${n.details?`<pre class="aparte-segment-error__details">${L(n.details)}</pre>`:""}
|
|
24
|
+
</div>
|
|
25
|
+
</div>
|
|
26
|
+
`},relabel:(n,t)=>{let e=k();if(e.getErrorRenderer?.())return;let s=n.querySelector(".aparte-alert__icon");s&&(s.innerHTML=e.getIcon("error")||"\u26A0");let i=n.querySelector(".aparte-alert__title");i&&(i.textContent=e.t("error"));let r=qs(t.code,o=>e.t(o)),a=n.querySelector(".aparte-alert__message");a&&r!==void 0&&(a.textContent=r)},getStyles:()=>""};function Er(n,t){if(!n||typeof n!="object"||Object.keys(n).length===0)return"";if(t)try{let e=t(n);if(typeof e=="string")return e}catch{}try{return JSON.stringify(n,null,2)}catch{return""}}function kr(n,t){let e=n.toolCall?.name??"tool",s=t.getToolDisplay(e)?.label;if(s!==void 0)try{let i=typeof s=="function"?s(n):s;if(typeof i=="string"&&i.trim())return{text:i.trim(),isLabel:!0}}catch{}return{text:e,isLabel:!1}}function Tr(n,t){let e=t.getToolSummary(n.toolCall?.name??"");if(!e)return"";try{let s=e(n);return typeof s=="string"?s.trim():""}catch{return""}}function Mr(n){return Er(n.toolCall?.input,k().getToolInputFormatter(n.toolCall?.name??""))}function Fs(n){let t=k(),e=n.status??"pending",s=i=>L(i);return e==="awaiting-approval"?`${t.getIcon("pause")}${s(t.t("approvalWaiting"))}`:e==="pending"?s(t.t("toolRunning")):e==="resolved"?`${t.getIcon("check")}${s(t.t("toolCompleted"))}`:e==="rejected"?`${t.getIcon("close")}${s(t.t("toolRejected"))}`:e==="aborted"?`${t.getIcon("stop")}${s(t.t("toolStopped"))}`:e==="failed"?`${t.getIcon("close")}${s(t.t("toolFailed"))}`:""}function xr(n){let t=k();if(n.status==="rejected"){let e=n.refusal?.by;if(e==="policy")return t.t("toolRefusedByPolicy");if(e==="earlier-refusal")return t.t("toolNotRunAfterRefusal");let s=n.refusal?.instruction?.trim();return s?t.t("toolRejectedSaid").replace("{instruction}",()=>s):""}if(n.status==="aborted")switch(n.abortCause){case"timeout":return t.t("toolTimedOut");case"no-handler":return t.t("toolUnavailable");case"no-resolver":return t.t("toolNoApprover");case"turn-limit":return t.t("toolTurnLimit");default:return""}return""}function Ws(n){let t=mc(n.result??"");return!t||n.status==="rejected"&&n.refusal?null:{key:"toolOutput",text:t}}function Ss(n){let t=k().getToolDisplay(n.toolCall?.name??"")?.details;if(t===!1)return{kind:"none"};if(typeof t!="function")return{kind:"parts"};try{let e=t(n);return e?{kind:"body",body:typeof e=="string"?k().sanitizeHtml(e):e}:{kind:"none"}}catch{return{kind:"none"}}}var mi=n=>n.querySelector(':scope > .aparte-tool-detail[data-details="app"]');function Ir(n,t){let e=n.querySelector(".aparte-tool-detail");e&&(typeof t=="string"?e.innerHTML=t:e.replaceChildren(t),ge.set(e,Lr(t)))}var ge=new WeakMap,Lr=n=>typeof n=="string"?n:n.outerHTML;function gc(n,t){if(typeof t!="string"&&n.contains(t)){ge.set(n,t.outerHTML);return}let e=ge.get(n),s=Lr(t);if(e===s)return;let i=document.createElement("div");typeof t=="string"?i.innerHTML=t:i.append(t);let r=document.createElement("div");e!==void 0&&(r.innerHTML=e),e!==void 0&&Us(r,i)&&Us(r,n)?Rr(n,r,i):n.replaceChildren(...Array.from(i.childNodes)),ge.set(n,s)}function Us(n,t){if(n.childNodes.length!==t.childNodes.length)return!1;for(let e=0;e<n.childNodes.length;e++){let s=n.childNodes[e],i=t.childNodes[e];if(s.nodeType!==i.nodeType||s.nodeName!==i.nodeName||!Us(s,i))return!1}return!0}function Rr(n,t,e){for(let s=0;s<n.childNodes.length;s++){let i=n.childNodes[s],r=t.childNodes[s],a=e.childNodes[s];if(i instanceof Element&&r instanceof Element&&a instanceof Element){for(let{name:o,value:l}of Array.from(a.attributes))r.getAttribute(o)!==l&&i.setAttribute(o,l);for(let{name:o}of Array.from(r.attributes))a.hasAttribute(o)||i.removeAttribute(o);Rr(i,r,a)}else r.nodeValue!==a.nodeValue&&(i.nodeValue=a.nodeValue)}}function bi(n,t){let e=n.querySelector(".aparte-tool-note");if(!e)return;let s=xr(t);e.textContent!==s&&(e.textContent=s),e.toggleAttribute("hidden",!s),s?e.setAttribute("title",s):e.removeAttribute("title")}function vi(n,t,e,s){let i=n.querySelector(`[data-part="${t}"]`);if(!e){i?.remove();return}if(i){let f=i.querySelector("code");f&&f.textContent!==e&&(f.textContent=e);let g=i.querySelector(".aparte-tool-part-label"),_=k().t(s);g&&g.textContent!==_&&(g.textContent=_),i.querySelector(".aparte-tool-part-body")?.setAttribute("aria-label",_);return}let r=n.querySelector(".aparte-tool-detail");if(!r)return;let a=k(),o=document.createElement("div");o.className="aparte-tool-part",o.dataset.part=t;let l=document.createElement("div");l.className="aparte-tool-part-head";let c=document.createElement("span");c.className="aparte-tool-part-label",c.textContent=a.t(s);let d=document.createElement("template");d.innerHTML=ln("aparte-tool-copy"),l.append(c,d.content);let u=document.createElement("div");u.className="aparte-tool-part-body",u.setAttribute("role","region"),u.tabIndex=0,u.setAttribute("aria-label",c.textContent);let h=document.createElement("pre"),p=document.createElement("code");p.textContent=e,h.appendChild(p),u.appendChild(h),o.append(l,u),t==="input"?r.prepend(o):r.appendChild(o),Or(o)}function Or(n){for(let t of n.querySelectorAll(".aparte-tool-copy")){if(t.dataset.wired)continue;t.dataset.wired="1";let e=t.closest(".aparte-tool-part");Ar(t,()=>e?.querySelector(".aparte-tool-part-body")?.textContent??"")}}var _c=2e5;function Pr(n){let t=n.trim();if(!(t.length>_c||!(t.startsWith("{")||t.startsWith("["))))try{let e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}}function mc(n){let t=Pr(n);return t===void 0?n:JSON.stringify(t,null,2)}function yi(n){let t=k();for(let e of n.querySelectorAll(".aparte-tool-part-body")){let s=e.querySelector("code")?.textContent??"";!s||Pr(s)===void 0||t.highlightCode(s,"json").then(i=>{(e.querySelector("code")?.textContent??"")===s&&(e.innerHTML=i)}).catch(()=>{})}}function Nr(n){return Tr(n,k())}function wi(n,t){let e=n.querySelector(".aparte-tool-target");if(!e)return;let s=Nr(t);e.textContent!==s&&(e.textContent=s),e.toggleAttribute("hidden",!s)}function Dr(n){return kr(n,k())}function Br(n){let t=k(),e=t.getToolDisplay(n.toolCall?.name??"")?.icon;return(e?t.getIcon(e):void 0)||t.getIcon("tool")}var cn=n=>k().getToolDisplay(n.toolCall?.name??"")?.quiet??!0;function Hr(n){let t=n.status??"pending",e=cn(n);return{shimmer:e&&t==="pending",spinner:!e&&t==="pending",stateHidden:e&&(t==="pending"||t==="resolved")}}function Si(n,t){let e=Hr(t);n.toggleAttribute("data-quiet",cn(t)),n.querySelector(".aparte-tool-spinner")?.toggleAttribute("hidden",!e.spinner),n.querySelector(".aparte-tool-name")?.classList.toggle("aparte-shimmer",e.shimmer),n.querySelector(".aparte-tool-state")?.classList.toggle("aparte-sr-only",e.stateHidden)}function Ai(n,t){let e=n.querySelector(".aparte-tool-name");if(!e)return;let{text:s,isLabel:i}=Dr(t);e.textContent!==s&&(e.textContent=s),e.classList.toggle("aparte-tool-name--label",i)}function bc(n){let t=Fs(n),e=Br(n),s=Nr(n),i=xr(n),r=Dr(n),a=Hr(n);return`
|
|
27
|
+
<span class="aparte-tool-label">
|
|
28
|
+
<span class="aparte-tool-icon">${e}</span>
|
|
29
|
+
<span class="aparte-tool-name${r.isLabel?" aparte-tool-name--label":""}${a.shimmer?" aparte-shimmer":""}">${L(r.text)}</span>
|
|
30
|
+
<span class="aparte-tool-target"${s?"":" hidden"}>${L(s)}</span>
|
|
31
|
+
</span>
|
|
32
|
+
<span class="aparte-spinner aparte-tool-spinner" aria-hidden="true"${a.spinner?"":" hidden"}></span>
|
|
33
|
+
<span class="aparte-tool-state${a.stateHidden?" aparte-sr-only":""}">${t}</span>
|
|
34
|
+
<span class="aparte-tool-note"${i?` title="${x(i)}"`:" hidden"}>${L(i)}</span>`}function Ci(n){return`<div class="aparte-segment aparte-segment-tool-call" data-segment-id="${L(n.id)}" data-status="${x(n.status??"pending")}" data-tool-call-id="${x(n.toolCall?.id??"")}" data-tool-name="${x(n.toolCall?.name??"tool")}" hidden></div>`}var Et=n=>n.hidden&&n.classList.contains("aparte-segment-tool-call")&&n.childElementCount===0,Bt=new WeakMap,_e=new WeakMap;function dn(n){return _e.get(n)??null}function Ei(n,t){let e=Bt.get(n);return e||(n.classList.contains("aparte-segment-tool-call")?null:t)}function ki(n,t){let e=n.toolCall?.name??"tool",s=n.status??"pending",i=n.toolCall?.id??"",r=bc(n),a=cn(n)?" data-quiet":"",o=k().getIcon("expand"),l=t.kind==="parts"?Mr(n):"",c=t.kind==="parts"?Ws(n):null;if(t.kind==="none"||t.kind==="parts"&&!l&&!c)return`
|
|
35
|
+
<div class="aparte-segment aparte-segment-tool-call" data-segment-id="${L(n.id)}" data-status="${x(s)}" data-tool-call-id="${x(i)}" data-tool-name="${x(e)}"${a}><div class="aparte-tool-line">${r}</div>
|
|
36
|
+
</div>
|
|
37
|
+
`;let d=k(),u=ln("aparte-tool-copy"),h=n.collapsed!==void 0?!n.collapsed:d.getToolDisplay(e)?.open===!0;if(t.kind==="body"){let p=document.createElement("template");p.innerHTML=`
|
|
38
|
+
<details class="aparte-segment aparte-segment-tool-call" data-segment-id="${L(n.id)}" data-status="${x(s)}" data-tool-call-id="${x(i)}" data-tool-name="${x(e)}"${a}${h?" open":""}>
|
|
39
|
+
<summary class="aparte-tool-summary"><span class="aparte-tool-toggle">${o}</span>${r}</summary>
|
|
40
|
+
<div class="aparte-tool-detail" data-details="app"></div>
|
|
41
|
+
</details>`.trim();let f=p.content.firstElementChild;return Ir(f,t.body),f}return`
|
|
42
|
+
<details class="aparte-segment aparte-segment-tool-call" data-segment-id="${L(n.id)}" data-status="${x(s)}" data-tool-call-id="${x(i)}" data-tool-name="${x(e)}"${a}${h?" open":""}>
|
|
43
|
+
<summary class="aparte-tool-summary"><span class="aparte-tool-toggle">${o}</span>${r}</summary>
|
|
44
|
+
<div class="aparte-tool-detail">
|
|
45
|
+
${l?`
|
|
46
|
+
<div class="aparte-tool-part" data-part="input">
|
|
47
|
+
<div class="aparte-tool-part-head"><span class="aparte-tool-part-label">${L(d.t("toolInput"))}</span>${u}</div>
|
|
48
|
+
<div class="aparte-tool-part-body" role="region" tabindex="0" aria-label="${x(d.t("toolInput"))}"><pre><code>${L(l)}</code></pre></div>
|
|
49
|
+
</div>`:""}
|
|
50
|
+
${c?`
|
|
51
|
+
<div class="aparte-tool-part" data-part="output">
|
|
52
|
+
<div class="aparte-tool-part-head"><span class="aparte-tool-part-label">${L(d.t(c.key))}</span>${u}</div>
|
|
53
|
+
<div class="aparte-tool-part-body" role="region" tabindex="0" aria-label="${x(d.t(c.key))}"><pre><code>${L(c.text)}</code></pre></div>
|
|
54
|
+
</div>`:""}
|
|
55
|
+
</div>
|
|
56
|
+
</details>
|
|
57
|
+
`}var xt={type:"tool_call",render:n=>{let t=n.toolCall?.name??"tool";if(k().isToolHidden(t))return Ci(n);let e=k().getToolRenderer(t);if(e){Ur(t,e);let s=e.render(n);return s instanceof HTMLElement&&(Bt.set(s,e),_e.set(s,e)),s||Ci(n)}return ki(n,Ss(n))},relabel:(n,t)=>{if(Et(n))return;let e=k(),s=Ei(n,e.getToolRenderer(t.toolCall?.name)??null);if(s){s.relabel?.(n,t);return}let i=n.querySelector(".aparte-tool-icon");i&&(i.innerHTML=Br(t)),Ai(n,t),wi(n,t),bi(n,t);let r=n.querySelector('[data-part="input"] .aparte-tool-part-label');r&&(r.textContent=e.t("toolInput")),n.querySelector('[data-part="input"] .aparte-tool-part-body')?.setAttribute("aria-label",e.t("toolInput"));let a=Ws(t),o=n.querySelector('[data-part="output"] .aparte-tool-part-label');o&&a&&(o.textContent=e.t(a.key)),a&&n.querySelector('[data-part="output"] .aparte-tool-part-body')?.setAttribute("aria-label",e.t(a.key));for(let d of n.querySelectorAll(".aparte-tool-copy"))Cr(d);let l=mi(n);if(l){let d=Ss(t);d.kind==="body"&&gc(l,d.body)}let c=n.querySelector(".aparte-tool-state");c&&(c.innerHTML=Fs(t)),Si(n,t)},update:(n,t)=>{let e=t.status??"pending",s=k().isToolHidden(t.toolCall?.name??"tool");if(s&&Et(n)){n.setAttribute("data-status",e);return}let i=s?null:k().getToolRenderer(t.toolCall?.name)??null,r=Et(n)?null:Ei(n,i);if(r&&r===i&&r.update&&!Et(n)){r.update(n,t);return}let a=p=>{let f=document.createElement("template");f.innerHTML=typeof p=="string"?p.trim():"";let g=typeof p=="string"?f.content.firstElementChild:p;g&&(g.hasAttribute("data-segment-id")||g.setAttribute("data-segment-id",t.id),xt.cleanup?.(n,t),n.replaceWith(g),xt.setup?.(g,t))};if(i||r||s||Et(n)){a(xt.render(t));return}let o=Ss(t),l=o.kind==="parts"?Mr(t):"",c=o.kind==="parts"?Ws(t):null,d=o.kind==="body"||!!l||!!c,u=!!mi(n);if(d!==(n.tagName==="DETAILS")||d&&o.kind==="body"!==u){a(ki(t,o));return}n.setAttribute("data-status",e);let h=n.querySelector(".aparte-tool-state");if(h&&(h.innerHTML=Fs(t)),Si(n,t),Ai(n,t),wi(n,t),bi(n,t),o.kind==="body"){Ir(n,o.body);return}vi(n,"input",l,"toolInput"),vi(n,"output",c?.text??"",c?.key??"toolOutput"),yi(n)},setup:(n,t)=>{let s=k().isToolHidden(t.toolCall?.name??"tool")?void 0:k().getToolRenderer(t.toolCall?.name);s&&_e.set(n,s),!Et(n)&&(Or(n),yi(n),s&&Bt.set(n,s),s?.setup?.(n,t))},cleanup:(n,t)=>{_e.delete(n);let e=Bt.get(n);if(e){Bt.delete(n);try{e.cleanup?.(n,t)}catch(s){console.error("[aparte] a tool renderer's cleanup threw",s)}}},getStyles:()=>""},Ti=new WeakMap;function ot(n){let t=Ti.get(n);return t||(t={renderers:new Map,defaultsInstalled:!1,defaultsDeclined:!1},Ti.set(n,t)),t}function $r(n){let t=ot(n);if(n===Q||t.defaultsDeclined)return t.renderers;let e=new Map(ot(Q).renderers);for(let[s,i]of t.renderers)e.set(s,i);return e}var mt=null;function qt(n,t=k()){let e=ot(t);e.renderers.get(n.type)!==n&&(e.renderers.set(n.type,n),hn(t),Ft(t))}var Mi=new WeakMap;function vc(n,t=k()){let e=n.type,s=ot(t),i=Mi.get(t);i||(i=new Map,Mi.set(t,i));let r=s.renderers.get(e),a=i.get(e);a?a[a.length-1].renderer!==r&&a.splice(0,a.length,{renderer:r}):(a=[{renderer:r}],i.set(e,a));let o={renderer:n};a.push(o),qt(n,t);let l=!1;return()=>{if(l)return;l=!0;let c=a.indexOf(o);if(c<=0)return;let d=c===a.length-1;if(a.splice(c,1),a.length===1&&i.get(e)===a&&i.delete(e),!d||s.renderers.get(e)!==n)return;let u=a[a.length-1].renderer;if(u){qt(u,t);return}if(Wr(e,t),!$r(t).has(e)&&s.defaultsInstalled&&!s.defaultsDeclined){let h=pn.find(p=>p.type===e);h&&qt(h,t)}}}function qr(n=k()){ot(n).defaultsDeclined=!0}function Fr(n=k()){let t=ot(n);if(!(t.defaultsInstalled||t.defaultsDeclined)){t.defaultsInstalled=!0;for(let e of pn)t.renderers.has(e.type)||t.renderers.set(e.type,e);hn(n)}}function Wr(n,t=k()){let e=ot(t);e.renderers.has(n)&&(e.renderers.delete(n),Ft(t))}function un(n,t=k()){return $r(t).get(n)}var ce=new Set;function hn(n=k()){if(typeof document>"u")return;(!mt||!mt.isConnected)&&(mt=document.createElement("style"),mt.id="aparte-renderer-styles",document.head.appendChild(mt),mt.textContent=Array.from(ce).join(`
|
|
58
|
+
`));let t=!1;for(let e of ot(n).renderers.values()){let s=e.getStyles?.();!s||ce.has(s)||(ce.add(s),t=!0)}t&&(mt.textContent=Array.from(ce).join(`
|
|
59
|
+
`))}var xi=new WeakMap;function Ur(n,t){if(typeof document>"u")return;let e=t.getStyles?.();if(!e)return;let s=xi.get(t);if(s||(s=`aparte-tool-renderer-${n}`,xi.set(t,s)),document.getElementById(s))return;let i=document.createElement("style");i.id=s,i.textContent=e,document.head.appendChild(i)}function jr(n=k()){let t=ot(n);t.defaultsInstalled=!0;for(let e of pn)t.renderers.has(e.type)||qt(e,n);hn(n)}var pn=[rc,oc,pc,fc,xt];function me(n){let{target:t,config:e,messageId:s,targetId:i}=n,r=new It({blocks:e.getStreamBlocks()}),a=new Set,o=null,l=new Map,c=(b,y)=>{let m=`tool-${b}`;t.updateSegment?.(m,l.has(m)?y:{...y,deferred:void 0})},d="",u=!1,h="",p=new Map,f=[],g=[],_=new Set,S=b=>{let y=b.content;typeof y=="string"&&p.set(b.id,{text:b.type==="text",content:y})},E=()=>{if(f.length===0)return;let b=0,y=[...p].map(([v,{text:A,content:R}])=>{let C=h.indexOf(R,b);return C>=0&&(b=C+R.length),{id:v,text:A,start:C,length:R.length,citations:[]}}).filter(v=>v.text);if(y.length===0)return;let m=new Set;for(let v of g){let A=y.find(P=>P.start>=0&&v.end>P.start&&v.end<=P.start+P.length);if(!A)continue;let R=v.end-A.start,C=v.start===void 0?void 0:Math.max(0,Math.min(R,v.start-A.start));A.citations.push({...v,end:R,...C===void 0?{}:{start:C}});for(let P of v.sources)m.add(P)}let w=y[y.length-1],M=new Set;for(let v of y){let A=new Set(v.citations.flatMap(C=>C.sources)),R=f.filter(C=>A.has(C.id)||v===w&&!m.has(C.id));if(R.length===0){_.has(v.id)&&t.updateSegment?.(v.id,{sources:void 0,citations:void 0});continue}M.add(v.id),t.updateSegment?.(v.id,{sources:R,citations:v.citations})}_=M},I=b=>{if(!o||u)return;let y=typeof Element<"u"&&t instanceof Element?T(t):e,m=!b||y.getSegmentDefaults("thinking")?.collapsed===!1;t.updateSegment?.(o,m?{isStreaming:!1}:{collapsed:!0,isStreaming:!1}),u=!0};return b=>{switch(b.type){case"run-start":t.updateMessage?.(s,{status:"streaming"});break;case"turn-start":I(!1),r=new It({blocks:e.getStreamBlocks()}),a=new Set,h="",p=new Map,f=_.size===0?f.map(y=>({...y,id:`${y.id}~`})):[],g=[],_=new Set,o=null,d="",u=!1;break;case"thinking-delta":{if(d+=b.delta,o)t.updateSegment?.(o,{content:d});else{let y={id:`think-${G()}`,type:"thinking",content:d,isStreaming:!0};o=y.id,a.add(y.id),t.addSegment?.(y)}break}case"text-delta":{I(!0),h+=b.delta;let y=r.parse(b.delta);for(let w of y.segments)S(w),a.has(w.id)?"content"in w&&t.updateSegment?.(w.id,fs(w)):(t.addSegment?.(w),a.add(w.id));let m=r.getState().activeSegment;m?(S(m),a.has(m.id)?t.updateSegment?.(m.id,fs(m)):(t.addSegment?.(m),a.add(m.id))):y.segments.length;break}case"text-flush":{let y=r.finalize();for(let m of y)S(m),a.has(m.id)?"content"in m&&t.updateSegment?.(m.id,fs(m)):t.addSegment?.(m);E();break}case"sources":{let y=new Map(f.map(w=>[w.id,w]));for(let w of Array.isArray(b.sources)?b.sources:[])y.set(w.id,{...y.get(w.id),...w});f=[...y.values()];let m=new Set(g.map(w=>JSON.stringify([w.start,w.end,w.marker,w.sources])));for(let w of Array.isArray(b.citations)?b.citations:[]){let M=JSON.stringify([w.start,w.end,w.marker,w.sources]);m.has(M)||(m.add(M),g.push(w))}E();break}case"tool-start":{I(!1);let y={id:`tool-${b.toolCallId}`,type:"tool_call",toolCall:{id:b.toolCallId,name:b.name,input:b.input},status:"pending"};l.set(y.id,y);let m=e.getToolRenderer(b.name);m&&Ur(b.name,m),t.addSegment?.(y);break}case"tool-awaiting-approval":t.updateSegment?.(`tool-${b.toolCallId}`,{status:"awaiting-approval"}),J(t,"aparte-tool-approval-request",{toolCallId:b.toolCallId,toolName:b.name,input:b.input},i);break;case"tool-approved":c(b.toolCallId,{status:"pending"});break;case"tool-rejected":c(b.toolCallId,{status:"rejected",result:b.reason,...b.by?{refusal:b.instruction?{by:b.by,instruction:b.instruction}:{by:b.by}}:{}});break;case"tool-resolved":c(b.toolCallId,{status:"resolved",result:b.result,...b.structuredResult!==void 0?{structuredResult:b.structuredResult}:{}});break;case"tool-aborted":c(b.toolCallId,b.cause?{status:"aborted",abortCause:b.cause}:{status:"aborted"});break;case"tool-failed":c(b.toolCallId,{status:"failed",result:b.error});break;case"turn-limit-exceeded":b.scope==="global"?t.addSegment?.({id:`max-turns-${G()}`,type:"error",content:(typeof Element<"u"&&t instanceof Element?T(t):e).t("maxTurnsReached").replace("{n}",()=>String(b.limit)),code:B.MAX_TURNS_EXCEEDED}):b.toolCallId&&c(b.toolCallId,{status:"aborted",abortCause:"turn-limit"});break;case"run-aborted":J(t,"aparte-message-aborted",{messageId:s},i);break;case"run-suspended":{let y=b.ticket;for(let m of b.pending){let w=`tool-${m.toolCallId}`,M={reason:m.reason,...typeof y=="string"?{ticket:y}:{}};t.updateSegment?.(w,{deferred:M})}if(t.updateMessage?.(s,{status:"completed"}),b.usage)try{t.setUsage?.(s,b.usage)}catch{}J(t,"aparte-message-paused",{messageId:s},i);break}case"run-done":if(t.updateMessage?.(s,{status:"completed",...b.finishReason?{finishReason:b.finishReason}:{}}),b.usage)try{t.setUsage?.(s,b.usage)}catch{}break}}}function Gr(n,t){return{[Symbol.asyncIterator](){let e=n.getReader(),s=()=>{try{e.cancel().catch(()=>{})}catch{}};return t.aborted?s():t.addEventListener("abort",s,{once:!0}),{async next(){let{done:i,value:r}=await e.read();return i?{done:!0,value:void 0}:{done:!1,value:r}},async return(){t.removeEventListener("abort",s);try{await e.cancel()}catch{}try{e.releaseLock()}catch{}return{done:!0,value:void 0}}}}}}var wu=new TextEncoder;var Su=10080*60*1e3;function fn(n){let t=typeof document>"u"?void 0:document.baseURI;try{return t?new URL(n,t):new URL(n)}catch{return null}}function yc(){let n=typeof location>"u"?null:location.origin;return n&&n!=="null"?n:null}function wc(n){try{let t=new URL(n);return t.protocol==="http:"||t.protocol==="https:"?t.origin:null}catch{return null}}function Sc(n,t){return n===t?!0:typeof n=="function"||typeof t=="function"?!1:n.length===t.length&&n.every((e,s)=>e===t[s])}var Ii=new WeakSet;function As(n){if(typeof n=="function")return(i,r)=>{try{let a=n(r?r.href:i);return a==="load"||a==="drop"?a:"hold"}catch(a){return Ii.has(n)||(Ii.add(n),console.warn("[aparte] The image policy threw, so the pictures it was asked about are held.",a)),"hold"}};let t=!1,e=!1,s=new Set;for(let i of n){let r=typeof i=="string"?i.trim():"";if(r==="*")t=!0;else if(r==="self"||r==="'self'")e=!0;else{let a=wc(r);a?s.add(a):console.warn(`[aparte] setImagePolicy: ${JSON.stringify(i)} is not 'self', '*' or an http(s) origin, so it allows nothing.`)}}return(i,r)=>t||r&&(s.has(r.origin)||e&&r.origin===yc())?"load":"hold"}var yt=/^[\u0000- ]*$/;function Ac(n,t,e){if(yt.test(t))return"load";let s=fn(t);if(s){if(s.protocol==="data:"||s.protocol==="blob:")return"load";if(s.protocol!=="http:"&&s.protocol!=="https:")return"drop"}let i=n(t,s);return i==="hold"&&s!==null&&e?.has(s.href)?"load":i}var Ee=new WeakMap;function Cc(n,t){let e=fn(t);if(!e)return;let s=Ee.get(n);s||Ee.set(n,s=new Set),s.add(e.href)}function Ec(n){return Ee.get(n)}function kc(n){Ee.delete(n)}var de=/[\t\n\f\r ]/,Tc=/^(?:|\d+w(?: \d+h)?|(?:\d+|\d*\.\d+)(?:[eE][+-]?\d+)?x)$/;function zr(n){let t=[],e=n.length,s=0;for(;s<e;){for(;s<e&&(de.test(n[s])||n[s]===",");)s++;if(s>=e)break;let i=s;for(;s<e&&!de.test(n[s]);)s++;let r=n.slice(i,s),a=[];if(r.endsWith(","))r=r.replace(/,+$/,"");else{let l="",c="in";for(;;){let d=n[s];if(c==="in"){if(d===void 0){l&&a.push(l);break}if(d===","){s++,l&&a.push(l);break}de.test(d)?(l&&a.push(l),l="",c="after"):(l+=d,d==="("&&(c="parens"))}else if(c==="parens"){if(d===void 0){a.push(l);break}l+=d,d===")"&&(c="in")}else{if(d===void 0)break;if(!de.test(d)){c="in";continue}}s++}}let o=a.join(" ");r&&Tc.test(o)&&t.push({url:r,descriptor:o})}return t}function Kr(n){return n.map(t=>t.descriptor?`${t.url} ${t.descriptor}`:t.url).join(", ")}function Vr(n){let t=fn(n);if(t?.hostname)return t.hostname;let e=n.trim();return e.length>48?`${e.slice(0,47)}\u2026`:e}function ke(n,t,e,s=!1){let i=Vr(n),r=t?e.named(i,t):e.load(i),a=e.icon;return`${s?'<span class="aparte-tag aparte-image-held" role="button" tabindex="0"':`<a class="aparte-tag aparte-image-held" href="${x(n)}" target="_blank" rel="noopener noreferrer"`} data-aparte-image="${x(n)}"${t?` data-aparte-image-alt="${x(t)}"`:""} title="${x(e.load(i))}" aria-label="${x(r)}"><span class="aparte-image-held__icon" aria-hidden="true">${a}</span>`+(t?`<span class="aparte-tag__label aparte-image-held__alt">${L(t)}</span>`:"")+`<span class="aparte-image-held__host">${L(i)}</span>${s?"</span>":"</a>"}`}function Yr(n,t){return`<img src="${x(n)}" alt="${x(t)}" referrerpolicy="no-referrer">`}var Jr=/<(?:img|source)\b|data-aparte-image/i,Mc="a[data-aparte-image], span[data-aparte-image]";function xc(n,t,e){return!n||!Jr.test(n)?n:typeof document>"u"?Dc(n,t,e):Ic(n,t,e)}function Xr(n,t,e){let s=t===void 0?[]:zr(t),i=yt.test(n)?s[0]?.url:n;if(i===void 0)return null;let r=e(i);if(r!=="load")return{decision:r,address:i,srcset:null};let a=s.filter(o=>e(o.url)==="load");return{decision:r,address:i,srcset:a.length?Kr(a):null}}function Qr(n,t,e){if(!yt.test(n)&&e(n)!=="load")return!1;if(t===void 0)return yt.test(n)?!1:null;let s=zr(t).filter(i=>e(i.url)==="load");return s.length?Kr(s):yt.test(n)?!1:null}function Ic(n,t,e){let s=document.createElement("template");s.innerHTML=n;let i=s.content,r,a=!1,o=l=>{let c=document.createElement("template");return c.innerHTML=l,c.content};for(let l of Array.from(i.querySelectorAll(Mc))){let c=l.getAttribute("data-aparte-image")??"",d=l.getAttribute("data-aparte-image-alt")??"",u=yt.test(c)?"drop":t(c);a=!0,u==="drop"?l.remove():l.replaceWith(o(u==="load"?Yr(c,d):ke(c,d,r??=e(),!!l.parentElement?.closest("a"))))}for(let l of Array.from(i.querySelectorAll("source"))){let c=Qr(l.getAttribute("src")??"",l.getAttribute("srcset")??void 0,t);if(c===!1){l.remove(),a=!0;continue}c===null?l.hasAttribute("srcset")&&(l.removeAttribute("srcset"),a=!0):c!==l.getAttribute("srcset")&&(l.setAttribute("srcset",c),a=!0)}for(let l of Array.from(i.querySelectorAll("img"))){let c=Xr(l.getAttribute("src")??"",l.getAttribute("srcset")??void 0,t);if(!c){l.hasAttribute("srcset")&&(l.removeAttribute("srcset"),a=!0),l.parentElement?.localName==="picture"&&l.getAttribute("referrerpolicy")!=="no-referrer"&&(l.setAttribute("referrerpolicy","no-referrer"),a=!0);continue}if(a=!0,c.decision==="drop"){l.remove();continue}if(c.decision==="hold"){l.replaceWith(o(ke(c.address,l.getAttribute("alt")??"",r??=e(),!!l.closest("a"))));continue}c.srcset===null?l.removeAttribute("srcset"):l.setAttribute("srcset",c.srcset),l.setAttribute("referrerpolicy","no-referrer")}return a?s.innerHTML:n}var Lc=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes","noscript","plaintext"]),Rc=new Set(["area","base","br","col","embed","hr","img","input","link","meta","source","track","wbr"]),Oc=/[A-Za-z]/,Pc=/^[a-z][a-z0-9_.:-]*$/;function Cs(n,t,e){let s=t.filter(([r])=>!(r in e)&&Pc.test(r)),i=Object.entries(e).filter(r=>r[1]!==null);return`<${n}${[...s,...i].map(([r,a])=>` ${r}="${x(a)}"`).join("")}>`}function Nc(n,t,e){let s=new RegExp(`<(/?)${t}(?=[\\s/>])`,"g");s.lastIndex=e;let i=1;for(let r=s.exec(n);r;r=s.exec(n))if(i+=r[1]?-1:1,i===0){let a=n.indexOf(">",r.index);return a<0?n.length:a+1}return-1}function Dc(n,t,e){if(!n||!Jr.test(n))return n;let s=n.toLowerCase(),i=n.length,r,a="",o=0,l=0,c=[];for(;o<i;){let d=n.indexOf("<",o);if(d<0){a+=n.slice(o);break}if(a+=n.slice(o,d),n.startsWith("<!--",d)){let E=n.indexOf("-->",d+4),I=E<0?i:E+3;a+=n.slice(d,I),o=I;continue}let u=n[d+1]==="/",h=d+(u?2:1);if(!Oc.test(n[h]??"")){a+="<",o=d+1;continue}let{tag:p,attrs:f,end:g}=dr(n,h);if(g<0){a+=n.slice(d);break}o=g;let _=n.slice(d,g);if(u){p==="a"&&(l=Math.max(0,l-1));let E=c.lastIndexOf(p);E>=0&&(c.length=E),a+=_;continue}let S=E=>f.find(([I])=>I===E)?.[1];if(Lc.has(p)){let E=s.indexOf(`</${p}`,g),I=E<0?i:E;a+=_+n.slice(g,I),o=I;continue}if((p==="a"||p==="span")&&S("data-aparte-image")!==void 0){let E=Nc(s,p,g);E>=0?o=E:p==="a"&&(l+=1);let I=S("data-aparte-image")??"",b=S("data-aparte-image-alt")??"",y=yt.test(I)?"drop":t(I);y==="load"?a+=Yr(I,b):y==="hold"&&(a+=ke(I,b,r??=e(),l>0));continue}if(p==="a"&&(l+=1),p==="source"){let E=Qr(S("src")??"",S("srcset"),t);if(E===!1)continue;a+=E===(S("srcset")??null)?_:Cs(p,f,{srcset:E});continue}if(p==="img"){let E=Xr(S("src")??"",S("srcset"),t);if(!E){let I=c[c.length-1]==="picture";S("srcset")===void 0&&(!I||S("referrerpolicy")==="no-referrer")?a+=_:a+=Cs(p,f,{srcset:null,...I?{referrerpolicy:"no-referrer"}:{}});continue}E.decision==="hold"?a+=ke(E.address,S("alt")??"",r??=e(),l>0):E.decision==="load"&&(a+=Cs(p,f,{srcset:E.srcset,referrerpolicy:"no-referrer"}));continue}!Rc.has(p)&&!_.endsWith("/>")&&c.push(p),a+=_}return a}var pt=class extends DOMException{reason;constructor(t="aborted"){super(t==="no-presenter"?"No elicitation presenter is mounted, so the request could not be shown.":"The request ended without an answer.","AbortError"),this.reason=t}};function Bc(n){return n?n.tagName?.toLowerCase()==="aparte-chat"||n.hasAttribute?.("data-aparte-chat")===!0:!1}function st(n){let t=n??null;for(;t;){if(Bc(t))return t;t=t.parentElement}return null}var Te=class{exact=new Map;patterns=new Map;any;get(t){return t instanceof RegExp?this.patterns.get(String(t))?.value:t==="*"?this.any:this.exact.get(t)}set(t,e){if(t instanceof RegExp){let s=String(t),i=this.patterns.get(s);i?i.value=e:this.patterns.set(s,{re:t,value:e})}else t==="*"?this.any=e:this.exact.set(t,e)}delete(t){t instanceof RegExp?this.patterns.delete(String(t)):t==="*"?this.any=void 0:this.exact.delete(t)}resolve(t){if(typeof t!="string")return;let e=this.exact.get(t);if(e!==void 0)return{value:e,level:"exact"};for(let{re:s,value:i}of this.patterns.values())if(t.search(s)!==-1)return{value:i,level:"pattern"};return this.any!==void 0?{value:this.any,level:"any"}:void 0}values(){let t=[...this.exact.values(),...[...this.patterns.values()].map(e=>e.value)];return this.any!==void 0&&t.push(this.any),t}clear(){this.exact.clear(),this.patterns.clear(),this.any=void 0}},Li=!1,ht={copy:!1,retry:!1,edit:!1,feedback:!1,info:!1},Ht={attachmentPreview:!1,filePreview:!1},Ri=()=>{},Zr=new WeakMap;function Z(n){return Zr.get(n)??0}function et(n){Zr.set(n,Z(n)+1)}var js=new Set,ue=new Set;function ta(n){return js.add(n),()=>{js.delete(n)}}function Ft(n){ue.size===0&&queueMicrotask(()=>{let t=[...ue];ue.clear();for(let e of t)for(let s of[...js])try{s(e)}catch(i){console.error("[aparte] a renderer-change listener threw",i)}}),ue.add(n)}var Hc=n=>n instanceof RegExp?`re:${String(n)}`:`name:${n}`,Es=["hidden","open","details","quiet"];function ks(n,t){if(!n||!(t in n)||t in Object.prototype)return;let e=n[t];return typeof e=="function"?e.bind(n):void 0}var Oi=new WeakSet;function $c(n){let t=new Set;for(let e=n;e&&e!==Object.prototype;e=Object.getPrototypeOf(e))for(let s of Object.getOwnPropertyNames(e))s!=="constructor"&&t.add(s);return[...t]}var zt=class{_markdownProvider;_streamingMarkdownProvider;_highlightProvider;_codeLanguageRenderers=new Map;_sanitizer=Os;_imagePolicy=[];_imageDecider=As([]);_imagePolicyNamed=!1;_systemPromptTemplate;_systemPromptVarsProvider;_statusRenderer;_errorRenderer;_attachmentRenderer;_siblingNavRenderer;_bubbleShellRenderer;_iconProvider;_avatarProvider;_keyProvider;_extraKeyProviders=new Set;_locale=Tt;_actions=[];_listeners=new Set;_aiProviders=new Map;_fetchedModels=new Map;_modelConfig={};_requireModelSelection=!1;_elicitationAllowOther=!0;_elicitationLayout="stepped";_elicitationAnswerOnClick=!0;_elicitationFieldRenderer;_transport=new ye;_modelPreferenceProvider;_approvalPolicy=null;_compactor=null;_conversationManager;_elicitationPresenters=[];_warnedNoPresenter=!1;_elicitationQueue=new Map;_tools=new Map;_toolRenderers=new Te;_toolRendererOverrides=new Map;_overrideGeneration=0;_toolDisplays=new Te;_streamBlocks=new Map;_segmentDefaults=new Map;_hostHandlers={...Ht};_bubbleActionsConfig={...ht};_turnSummary=null;_streamingCaret=!1;_dateSeparators=!1;registerAction(t){let e=this._actions.findIndex(s=>s.id===t.id);e!==-1?(console.warn(`[AparteConfig] Action with ID "${t.id}" already registered. Overwriting.`),this._actions[e]=t):this._actions.push(t),this._notify()}getActions(t){return this._actions.filter(e=>e.zones.includes(t)).sort((e,s)=>(e.order||0)-(s.order||0))}unregisterAction(t){let e=this._actions.length;this._actions=this._actions.filter(s=>s.id!==t),this._actions.length!==e&&this._notify()}setBubbleActions(t){this._bubbleActionsConfig={...this._bubbleActionsConfig,...t},this._notify()}setTurnSummary(t){this._turnSummary=t===!1?null:t===!0?{}:t,et(this),this._notify()}setStreamingCaret(t){this._streamingCaret=t,this._notify()}getStreamingCaret(){return this._streamingCaret}setDateSeparators(t){this._dateSeparators=t,this._notify()}getDateSeparators(){return this._dateSeparators}getTurnSummary(){return this._turnSummary}setHostHandlers(t){this._hostHandlers={...this._hostHandlers,...t},this._notify()}getHostHandlers(){return{attachmentPreview:this._hostHandlers.attachmentPreview??Ht.attachmentPreview,filePreview:this._hostHandlers.filePreview??Ht.filePreview}}getBubbleActions(){return{copy:this._bubbleActionsConfig.copy??ht.copy,retry:this._bubbleActionsConfig.retry??ht.retry,edit:this._bubbleActionsConfig.edit??ht.edit,feedback:this._bubbleActionsConfig.feedback??ht.feedback,info:this._bubbleActionsConfig.info??ht.info,feedbackReasons:this._bubbleActionsConfig.feedbackReasons,user:this._bubbleActionsConfig.user,assistant:this._bubbleActionsConfig.assistant}}setMarkdownProvider(t){this._markdownProvider=t,et(this),this._notify()}setStreamingMarkdownProvider(t){this._streamingMarkdownProvider=t,et(this),this._notify()}createStreamingMarkdownRenderer(t){return this._streamingMarkdownProvider?this._streamingMarkdownProvider(t):null}setHighlightProvider(t){this._highlightProvider=t,et(this),this._notify()}hasHighlightProvider(){return!!this._highlightProvider}registerCodeLanguageRenderer(t){let e=t.languages.map(s=>s.toLowerCase());for(let s of e)this._codeLanguageRenderers.set(s,t);return et(this),this._notify(),()=>{let s=!1;for(let i of e)this._codeLanguageRenderers.get(i)===t&&(this._codeLanguageRenderers.delete(i),s=!0);s&&(et(this),this._notify())}}getCodeLanguageRenderer(t){return this._codeLanguageRenderers.get(t.toLowerCase())}hasCodeLanguageRenderer(t){return t===void 0?this._codeLanguageRenderers.size>0:this._codeLanguageRenderers.has(t.toLowerCase())}setHtmlSanitizer(t){t!==this._sanitizer&&(t===null&&console.warn("[aparte] HTML sanitization is now DISABLED (setHtmlSanitizer(null)). Model-authored HTML will be inserted verbatim. Pass a sanitizer (defaultSanitizer, or DOMPurify chained before it) unless you sanitize upstream yourself."),this._sanitizer=t,et(this),this._notify())}sanitizeHtml(t){let e=this._sanitizer?this._sanitizer(t):t;return xc(e,s=>this.decideImage(s),()=>this._heldImageWords())}setImagePolicy(t){this._imagePolicyNamed=!0,!Sc(t,this._imagePolicy)&&(this._imagePolicy=typeof t=="function"?t:[...t],this._imageDecider=As(t),et(this),this._notify())}decideImage(t){let e=Ac(this._imageDecider,t,Ec(this));return e==="hold"&&this._noteHeldImage(t),e}_noteHeldImage(t){this._imagePolicyNamed||Li||(Li=!0,console.warn(`[aparte] A picture from ${Vr(t)} waits for the reader's click: pictures a model or a tool chose load only from the sources the app allows. To load yours, call aparteGlobalConfig.setImagePolicy(['https://cdn.example.com']); to keep holding them without this note, setImagePolicy([]). Why: https://apartejs.dev/guides/markdown/#pictures-a-reply-can-load`))}showImage(t){Cc(this,t)}_heldImageWords(){return{load:t=>this.t("imageLoad").replace("{host}",()=>t),named:(t,e)=>this.t("imageLoadNamed").replace("{host}",()=>t).replace("{alt}",()=>e),icon:this.getIcon("image")}}setSystemPrompt(t){this._systemPromptTemplate=t}getSystemPromptTemplate(){return this._systemPromptTemplate}setSystemPromptVarsProvider(t){this._systemPromptVarsProvider=t}resolveSystemPrompt(){if(!this._systemPromptTemplate?.trim())return null;let t=this._systemPromptVarsProvider?this._systemPromptVarsProvider():{};return this._systemPromptTemplate.replace(/\{\{([^}]+)\}\}/g,(s,i)=>t[i.trim()]??"").trim()||null}setIconProvider(t){this._iconProvider=t,this._notify()}registerIcons(t){let e=this._iconProvider;if(e&&Oi.has(e))Object.assign(e,t);else{let s=Object.assign(Object.create(e??null),t);Oi.add(s),this._iconProvider=s}this._notify()}getIconProvider(){let t=this._iconProvider,e={};for(let s of Object.keys(Dt))e[s]=ks(t,s)??(()=>Dt[s]);for(let s of $c(t)){let i=ks(t,s);i&&!(s in e)&&(e[s]=i)}return e}setAvatarProvider(t){this._avatarProvider=t??void 0,this._notify()}getAvatarProvider(){return this._avatarProvider??null}setStatusRenderer(t){this._statusRenderer=t??void 0,this._notify()}getStatusRenderer(){return this._statusRenderer??null}setErrorRenderer(t){this._errorRenderer=t??void 0,this._notify()}getErrorRenderer(){return this._errorRenderer??null}setAttachmentRenderer(t){this._attachmentRenderer=t??void 0,this._notify()}getAttachmentRenderer(){return this._attachmentRenderer??null}setSiblingNavRenderer(t){this._siblingNavRenderer=t??void 0,this._notify()}getSiblingNavRenderer(){return this._siblingNavRenderer??null}setBubbleShellRenderer(t){this._bubbleShellRenderer=t??void 0,this._notify()}getBubbleShellRenderer(){return this._bubbleShellRenderer??null}setLocale(t){this._locale=t,this._notify()}resetLocale(){this._locale=Tt,this._notify()}getLocale(){return this._locale}extendLocale(t){this._locale={...this._locale,...t},this._notify()}getIcon(t){let e=ks(this._iconProvider,t);return e?e():Object.prototype.hasOwnProperty.call(Dt,t)?Dt[t]:void 0}setKeyProvider(t){this._keyProvider=t}registerKeyProvider(t){let e=s=>t(s);return this._extraKeyProviders.add(e),()=>{this._extraKeyProviders.delete(e)}}async getKey(t){for(let e of[...this._extraKeyProviders].reverse()){let s=await e(t);if(s)return s}if(this._keyProvider)return await this._keyProvider(t)||void 0}async refreshProviderModels(t){let e=this._aiProviders.get(t);if(!e||!e.fetchModels)return[];try{let s=await this.getKey(t),i=await e.fetchModels(s),r=this._fetchedModels.get(t);if(i.length===0&&r?.length)return r;let a=this.getCurrentModel()?.contextWindow;return this._fetchedModels.set(t,i),this.getCurrentModel()?.contextWindow!==a&&this._notify(),i}catch(s){return console.warn(`[AparteConfig] Failed to refresh models for ${t}`,s),[]}}registerAIProvider(...t){for(let e of t)e&&(this._aiProviders.has(e.id)&&console.warn(`[AparteConfig] AI Provider "${e.id}" already registered. Overwriting.`),this._aiProviders.set(e.id,e));if(!this.hasSelectedModel()&&this._aiProviders.size===1){let e=[...this._aiProviders.values()][0],s=e.getModels();s.length===1&&(this._modelConfig={...this._modelConfig,defaultProvider:e.id,defaultModel:s[0].id})}this._notify()}unregisterAIProvider(t){this._aiProviders.delete(t),this._notify()}getAIProviders(){let t=Array.from(this._aiProviders.values()),e=this._modelConfig.enabledProviders;return e?.length?t.filter(i=>e.includes(i.id)):t}getAIProvider(t){return this._aiProviders.get(t)}setTransport(t){this._transport=t}getTransport(){return this._transport}setModelPreferenceProvider(t){this._modelPreferenceProvider=t}setApprovalPolicy(t){this._approvalPolicy=t,this._notify()}getApprovalPolicy(){return this._approvalPolicy}setCompactor(t){this._compactor=t,this._notify()}getCompactor(){return this._compactor}ruleOnToolCall(t){let e=this._tools.get(t.name)?.tool,s=this._approvalPolicy?.(t,e);return s||{verdict:e?.needsApproval?"ask":"allow"}}restoreModelPreference(){if(!this._modelPreferenceProvider)return null;let t=this._modelPreferenceProvider.load();return t?.provider&&t?.model?(this._modelConfig={...this._modelConfig,defaultProvider:t.provider,defaultModel:t.model},this._notify(),t):null}setModelConfig(t){this._modelConfig={...this._modelConfig,...t},this._modelPreferenceProvider&&this._modelConfig.defaultProvider&&this._modelConfig.defaultModel&&this._modelPreferenceProvider.save(this._modelConfig.defaultProvider,this._modelConfig.defaultModel),this._notify()}subscribe(t){return this._listeners.add(t),()=>this._listeners.delete(t)}_notify(){this._listeners.forEach(t=>{try{t()}catch(e){console.error("[AparteConfig] A config-change listener threw",e)}}),typeof window<"u"&&window.dispatchEvent(new CustomEvent("aparte-config-change",{detail:{config:this,modelConfig:this._modelConfig}}))}getModelConfig(){return{...this._modelConfig}}hasSelectedModel(){return!!(this._modelConfig.defaultProvider&&this._modelConfig.defaultModel)}setElicitationOptions(t){t.allowOther!==void 0&&(this._elicitationAllowOther=t.allowOther),t.layout!==void 0&&(this._elicitationLayout=t.layout),t.answerOnClick!==void 0&&(this._elicitationAnswerOnClick=t.answerOnClick),this._notify()}getElicitationOptions(){return{allowOther:this._elicitationAllowOther,layout:this._elicitationLayout,answerOnClick:this._elicitationAnswerOnClick}}setElicitationFieldRenderer(t){this._elicitationFieldRenderer=t??void 0,this._notify()}getElicitationFieldRenderer(){return this._elicitationFieldRenderer}setRequireModelSelection(t){this._requireModelSelection!==t&&(this._requireModelSelection=t,this._notify())}getRequireModelSelection(){return this._requireModelSelection}getCurrentModel(){let{defaultProvider:t,defaultModel:e}=this._modelConfig;if(!t||!e)return;let s=this._aiProviders.get(t);if(!s)return;let r=this._fetchedModels.get(t)?.find(o=>o.id===e);if(r)return r;let a=s.getModels();if(a instanceof Promise){console.warn(`[AparteConfig] Provider "${t}".getModels() returned a Promise \u2014 it is ignored here, so this model resolves to undefined and nothing can read its capabilities. getModels() must return the list synchronously; implement fetchModels() for async fetching.`);return}return a.find(o=>o.id===e)}t(t){let e=this._locale[t]||Tt[t];return e===void 0?"":e}renderMarkdown(t){if(this._markdownProvider)try{return this.sanitizeHtml(this._markdownProvider(t))}catch(e){console.warn("[AparteConfig] Markdown provider failed, using fallback:",e)}else if(this._streamingMarkdownProvider&&typeof document<"u")try{let e=document.createElement("div"),s=this._streamingMarkdownProvider(e);return s.write(t),s.end(),this.sanitizeHtml(e.innerHTML)}catch(e){console.warn("[AparteConfig] Streaming Markdown provider failed on a complete string, using fallback:",e)}return this._defaultMarkdownRenderer(t)}async highlightCode(t,e,s={}){if(this._highlightProvider)try{let i=this._highlightProvider(t,e),r=i instanceof Promise?await i:i;return this.sanitizeHtml(r)}catch(i){if(console.warn("[AparteConfig] Highlight provider failed, using fallback:",i),s.fallback===!1)throw i}return this._defaultHighlightRenderer(t)}registerTool(t,e){this._tools.set(t.name,{tool:t,handler:e})}unregisterTool(t){this._tools.delete(t)}getTools(){return Array.from(this._tools.values()).map(t=>t.tool)}resolveToolSystemPrompts(){let t=Array.from(this._tools.values()).map(e=>e.tool.systemPrompt?.trim()).filter(e=>!!e);return t.length?t.join(`
|
|
60
|
+
|
|
61
|
+
`):null}getToolHandler(t){return this._tools.get(t)?.handler}registerToolRenderer(t,e){this._toolRenderers.get(t)!==e&&(this._toolRenderers.set(t,e),Ft(this))}overrideToolRenderer(t,e){let s=Hc(t),i=this._toolRenderers.get(t),r=this._toolRendererOverrides.get(s);r?r[r.length-1].renderer!==i&&r.splice(0,r.length,{renderer:i}):(r=[{renderer:i}],this._toolRendererOverrides.set(s,r));let a={renderer:e};r.push(a),this.registerToolRenderer(t,e);let o=this._overrideGeneration,l=!1;return()=>{if(l||o!==this._overrideGeneration)return;l=!0;let c=r.indexOf(a);if(c<=0)return;let d=c===r.length-1;if(r.splice(c,1),r.length===1&&this._toolRendererOverrides.get(s)===r&&this._toolRendererOverrides.delete(s),!d||this._toolRenderers.get(t)!==e)return;let u=r[r.length-1].renderer;u?this.registerToolRenderer(t,u):this.unregisterToolRenderer(t)}}setSegmentDefaults(t,e){this._segmentDefaults.set(t,{...e})}getSegmentDefaults(t){return this._segmentDefaults.get(t)}clearSegmentDefaults(t){this._segmentDefaults.delete(t)}unregisterToolRenderer(t){this._toolRenderers.get(t)!==void 0&&(this._toolRenderers.delete(t),Ft(this))}getToolRenderer(t){return this._toolRenderers.resolve(t)?.value}registerToolDisplay(t,e){let s=this._toolDisplays.get(t),i={...s,...e};this._toolDisplays.set(t,i),(Es.some(a=>s?.[a]!==i[a])||s===void 0&&this._anotherShapes(i))&&et(this),this._notify()}unregisterToolDisplay(t){let e=this._toolDisplays.get(t);this._toolDisplays.delete(t),(Es.some(i=>e?.[i]!==void 0)||e!==void 0&&this._anotherShapes(e))&&et(this),this._notify()}_anotherShapes(t){return this._toolDisplays.values().some(e=>e!==t&&Es.some(s=>e[s]!==void 0))}getToolDisplay(t){return this._toolDisplays.resolve(t)?.value}isToolHidden(t){let e=this._toolDisplays.resolve(t);if(!e?.value.hidden)return!1;let s=this._toolRenderers.resolve(t),i={exact:2,pattern:1,any:0};return!s||i[s.level]<=i[e.level]}_dropToolDisplayField(t,e){let s=this._toolDisplays.get(t);if(!s||!(e in s))return;let{[e]:i,...r}=s;Object.keys(r).length?this._toolDisplays.set(t,r):this._toolDisplays.delete(t),this._notify()}registerToolSummary(t,e){this.registerToolDisplay(t,{summary:e})}unregisterToolSummary(t){this._dropToolDisplayField(t,"summary")}getToolSummary(t){return this.getToolDisplay(t)?.summary}registerToolInputFormatter(t,e){this.registerToolDisplay(t,{formatInput:e})}unregisterToolInputFormatter(t){this._dropToolDisplayField(t,"formatInput")}getToolInputFormatter(t){return this.getToolDisplay(t)?.formatInput}registerStreamBlock(t){this._streamBlocks.set(t.tag,t),this._notify()}unregisterStreamBlock(t){this._streamBlocks.delete(t)&&this._notify()}getStreamBlocks(){return Array.from(this._streamBlocks.values())}setConversationManager(t){this._conversationManager=t}getConversationManager(){return this._conversationManager}setElicitationPresenter(t,e){if(t===null){this._elicitationPresenters=[];return}this._elicitationPresenters=this._elicitationPresenters.filter(s=>s.fn!==t),this._elicitationPresenters.push(e===void 0?{fn:t}:{fn:t,owner:e})}removeElicitationPresenter(t){this._elicitationPresenters=this._elicitationPresenters.filter(e=>e.fn!==t)}getElicitationPresenter(){return this._elicitationPresenters[this._elicitationPresenters.length-1]?.fn}_presenterFor(t){let e=this._elicitationPresenters;if(e.length!==0){if(t){let s=st(t);if(s)for(let i=e.length-1;i>=0;i-=1){let r=e[i];if(r.owner&&st(r.owner)===s)return r.fn}}return e[e.length-1]?.fn}}requestUserInput(t){let e=this._elicitationQueueKey(t),s=this._elicitationQueue.get(e),i=s===void 0?this._present(t):s.then(()=>this._present(t),()=>this._present(t)),r=i.then(Ri,Ri).then(()=>{this._elicitationQueue.get(e)===r&&this._elicitationQueue.delete(e)});return this._elicitationQueue.set(e,r),i}_elicitationQueueKey(t){return st(t.target)}_present(t){let e=this._presenterFor(t.target);if(!e)return this._warnedNoPresenter||(this._warnedNoPresenter=!0,console.warn("[aparte] requestUserInput() was called with no elicitation presenter, so it rejected with an AbortError \u2014 nothing was ever shown to anybody. Add <aparte-elicitation></aparte-elicitation> inside your <aparte-chat> (the Angular wrapper's tag too) \u2014 or, under the React/Vue/Svelte wrappers, inside their [data-aparte-chat] host (every wrapper renders it by default, unless you passed `elicitation={false}`) \u2014 or register your own by calling setElicitationPresenter() on the config this chat resolves \u2014 the scoped one if you passed a `config`, aparteGlobalConfig otherwise.")),Promise.reject(new pt("no-presenter"));if(t.signal?.aborted)return Promise.reject(new pt("aborted"));let s=e(t),i=t.signal;return i?new Promise((r,a)=>{let o=()=>a(new pt("aborted"));i.addEventListener("abort",o,{once:!0}),s.then(r,a).finally(()=>i.removeEventListener("abort",o))}):s}reset(){this._markdownProvider=void 0,this._streamingMarkdownProvider=void 0,this._highlightProvider=void 0,this._codeLanguageRenderers.clear(),this._systemPromptTemplate=void 0,this._systemPromptVarsProvider=void 0,this._statusRenderer=void 0,this._errorRenderer=void 0,this._attachmentRenderer=void 0,this._siblingNavRenderer=void 0,this._bubbleShellRenderer=void 0,this._iconProvider=void 0,this._segmentDefaults.clear(),this._avatarProvider=void 0,this._keyProvider=void 0,this._conversationManager=void 0,this._elicitationPresenters=[],this._elicitationQueue.clear(),this._locale=Tt,this._actions=[],this._sanitizer=Os,this._imagePolicy=[],this._imageDecider=As([]),this._imagePolicyNamed=!1,kc(this),this._aiProviders.clear(),this._fetchedModels.clear(),this._tools.clear(),this._toolRenderers.clear(),this._toolRendererOverrides.clear(),this._overrideGeneration++,Ft(this),this._toolDisplays.clear(),this._streamBlocks.clear(),this._modelConfig={},this._requireModelSelection=!1,this._elicitationAllowOther=!0,this._elicitationLayout="stepped",this._elicitationAnswerOnClick=!0,this._elicitationFieldRenderer=void 0,this._modelPreferenceProvider=void 0,this._approvalPolicy=null,this._compactor=null,this._bubbleActionsConfig={...ht},this._turnSummary=null,this._streamingCaret=!1,this._dateSeparators=!1,this._hostHandlers={...Ht},this._notify()}_defaultMarkdownRenderer(t){return L(t).replace(/\n/g,"<br>")}_defaultHighlightRenderer(t){return`<pre><code>${L(t)}</code></pre>`}},Ts=Symbol.for("aparte.globalConfig.1");function qc(){return typeof window<"u"?(window[Ts]||(window[Ts]=new zt),window[Ts]):new zt}var Q=qc(),Gs="aparte-config-change";function gt(n,t){let e=s=>{let i=s.detail;i?.config&&i.config!==T(n)||t()};return window.addEventListener(Gs,e),()=>window.removeEventListener(Gs,e)}var ea="suggestions",Fc=/[\p{Z}\s]+/gu,Wc=/[\p{Cc}\p{Co}\p{Cn}\p{Cs}\u2800]|(?!(?:\u200C|\u200D|\uFE0E|\uFE0F))\p{Default_Ignorable_Code_Point}/u,Uc=/\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0065}\u{E006E}\u{E0067}|\u{E0073}\u{E0063}\u{E0074}|\u{E0077}\u{E006C}\u{E0073})\u{E007F}/gu,jc=/(?:^| )\p{M}|\p{Mn}{5,}/u,Gc=new Set(["\u200C","\u200D","\uFE0E","\uFE0F"]),zc=/^[0-9#*]$/,Kc=/^\p{Emoji}$/u,Pi=/^\p{Extended_Pictographic}$/u,Vc=/^\p{Emoji_Modifier}$/u,Ni=/^[\p{scx=Arab}\p{scx=Syrc}\p{scx=Thaa}\p{scx=Nkoo}\p{scx=Adlm}\p{scx=Rohg}\p{scx=Mong}\p{scx=Deva}\p{scx=Beng}\p{scx=Guru}\p{scx=Gujr}\p{scx=Orya}\p{scx=Taml}\p{scx=Telu}\p{scx=Knda}\p{scx=Mlym}\p{scx=Sinh}\p{scx=Mymr}\p{scx=Khmr}]$/u,Yc=/^[\u094D\u09CD\u0A4D\u0ACD\u0B4D\u0BCD\u0C4D\u0CCD\u0D4D\u0DCA\u1039\u17D2]$/;function Jc(n){let t=Array.from(n);for(let e=0;e<t.length;e++){let s=t[e];if(!Gc.has(s))continue;let i=t[e-1]??"",r=t[e+1]??"";if(s==="\uFE0E"||s==="\uFE0F"){if(zc.test(i)){if(s!=="\uFE0F"||r!=="\u20E3")return!1}else if(!Kc.test(i))return!1;continue}if(s==="\u200D"){let a=i==="\uFE0F"?t[e-2]??"":i;if((Pi.test(a)||Vc.test(a))&&Pi.test(r))continue}if(!(Ni.test(i)&&(Ni.test(r)||Yc.test(i)&&(r===""||r===" "))))return!1}return!0}var sa=100;function gn(n){let t=(typeof n=="string"?n:n.label).replace(Fc," ").trim();if(!t||t.length>sa)return null;let e=t.replace(Uc,"\u{1F3F4}");return Wc.test(e)||jc.test(e)||!Jc(e)?null:t}var he=new Set;function Xc(n,t){t.length===0||he.has(n)||(he.size>=50&&he.clear(),he.add(n),console.warn(`[aparte-suggestions] ${t.length} reply(ies) of a suggestions block not offered, since a chip sends exactly what it shows: ${t.map(e=>JSON.stringify(e)).join(", ")}. A reply must be 1 to ${sa} characters and hold nothing invisible (zero-width, bidi or tag characters, stray joiners).`))}function Qc(n){let t;try{t=JSON.parse(n)}catch{return null}if(!Array.isArray(t))return null;let e=t.filter(r=>typeof r=="string"||typeof r=="object"&&r!==null&&typeof r.label=="string"),s=[],i=[];for(let r of e){let a=gn(r);a!==null?s.push(a):(typeof r=="string"?r:r.label).trim()&&i.push(typeof r=="string"?r:r.label)}return Xc(n,i),s.length?s:null}function Zc(n=Q){return n.registerCodeLanguageRenderer({languages:[ea],bare:!0,render:({source:t,open:e})=>{if(e)return"";let s=Qc(t);return s?`<span class="aparte-suggestions-mark" hidden data-aparte-suggestions="${x(JSON.stringify(s))}"></span>`:`<code class="aparte-code-error">${L(t)}</code>`}})}var td=new WeakSet;function _n(n){return!!n&&td.has(n)}function ed(n){let t=n.segments,e=t[t.length-1];return n.status!=="streaming"||!e||e.isStreaming!==void 0||e.type!=="text"&&e.type!=="thinking"?t:[...t.slice(0,-1),{...e,isStreaming:!0}]}function mn(n,t,e){if(n.setTokens?.(t.tokens),t.segments&&t.segments.length>0){let s=n.getSegments?.()??[];if(s.length===t.segments.length){let i=Zs(t.status);for(let r of t.segments)if("content"in r){let a={content:r.content};i&&(a.isStreaming=!1);let o=s.find(l=>l.id===r.id);r.type==="text"&&(r.sources||r.citations||o?.sources||o?.citations)&&Object.assign(a,{sources:r.sources,citations:r.citations}),n.updateSegment?.(r.id,a)}}else n.setSegments?.(ed(t))}else t.content!==void 0&&n.setContent?.(t.content);t.attachments&&t.attachments.length>0&&n.setAttachments?.(t.attachments),e&&e.count>1&&n.setSiblings?.(e.count,e.index),t.usage!==void 0&&n.setUsage?.(t.usage),n.setFinishReason?.(t.finishReason),n.setContextSummary?.(t.contextSummary,{legacy:t.compaction===!0})}var bn=Symbol.for("aparte.derivedSegments");function K(n){return n.replace(/["\\]/g,"\\$&").replace(/[\n\r\f]/g,t=>`\\${t.charCodeAt(0).toString(16)} `)}function na(n){return n.map(t=>({id:G(),name:t.name,type:t.type||"application/octet-stream",url:URL.createObjectURL(t),size:t.size,blob:t}))}function ia(n){if(n?.length&&!(typeof URL>"u"||typeof URL.revokeObjectURL!="function"))for(let t of n)t.url?.startsWith("blob:")&&URL.revokeObjectURL(t.url)}var zs=new Map;function vn(n,t){t?zs.set(n,t):zs.delete(n)}function ra(n,t){vn(n,t);try{window.dispatchEvent(new CustomEvent("aparte-conversation-status",{detail:{id:n,status:t}}))}catch{}}function Ne(n){return zs.get(n)??null}function aa(n){if(n.hasAttribute("data-glide"))return()=>{};let t=n.ownerDocument,e=()=>{t.removeEventListener("pointerdown",s,!0),t.removeEventListener("keydown",s,!0),n.removeEventListener("aparte-send",s)},s=()=>{n.setAttribute("data-glide",""),e()};return t.addEventListener("pointerdown",s,!0),t.addEventListener("keydown",s,!0),n.addEventListener("aparte-send",s),e}function oa(n){let t=n.parentElement;for(;t;){if((t.tagName.toLowerCase()==="aparte-chat"||t.hasAttribute("data-aparte-chat"))&&t.id)return t.id;t=t.parentElement}}var Me=class{constructor(t){this._options=t}_messageId=null;_state=null;_reason="";_marked=null;start(){let t=a=>this._options.active&&!this._options.active()?!1:!a||a===this._options.ownId(),e=a=>!!a&&this._options.owns(a),s=a=>{let o=a.detail;!t(o?.targetId)||!e(o?.messageId)||(this.clear(),this._set(o.messageId,"pending",""))},i=a=>{let o=a.detail;!t(o?.targetId)||o?.skipped||o?.messageId&&o.messageId===this._messageId&&this.clear()},r=a=>{let o=a.detail;if(!(!t(o?.targetId)||!e(o?.messageId))){if(o.aborted){o.messageId===this._messageId&&this.clear();return}o.messageId!==this._messageId&&this.clear(),this._set(o.messageId,"failed",o.error??"")}};return window.addEventListener("aparte-compact-start",s),window.addEventListener("aparte-compact-done",i),window.addEventListener("aparte-compact-error",r),()=>{window.removeEventListener("aparte-compact-start",s),window.removeEventListener("aparte-compact-done",i),window.removeEventListener("aparte-compact-error",r)}}clear(){let t=this._marked??(this._messageId?this._options.bubbleOf(this._messageId):null);this._messageId=null,this._state=null,this._reason="",this._marked=null,t?.removeAttribute("data-checkpoint"),t?.removeAttribute("data-checkpoint-reason")}reapply(){!this._messageId||!this._state||this._write(this._messageId,this._state,this._reason)}_set(t,e,s){this._messageId=t,this._state=e,this._reason=s,this._write(t,e,s)}_write(t,e,s){let i=this._options.bubbleOf(t);i&&(this._marked&&this._marked!==i&&(this._marked.removeAttribute("data-checkpoint"),this._marked.removeAttribute("data-checkpoint-reason")),this._marked=i,s?i.setAttribute("data-checkpoint-reason",s):i.removeAttribute("data-checkpoint-reason"),i.getAttribute("data-checkpoint")!==e&&i.setAttribute("data-checkpoint",e))}};function xe(n){for(let t=n.length-1;t>=0;t--){let e=n[t].contextSummary?.summary;if(e!==void 0)return{summary:e,messages:n.slice(t)}}return{messages:n}}var sd="The earlier part of this conversation was compacted. This is a summary of what came before; continue from it.",yn=n=>`${sd}
|
|
62
|
+
|
|
63
|
+
${n}`;function kt(n){let t=s=>typeof s=="string"?[{type:"text",text:s}]:s,e=[];for(let s of n){let i=e[e.length-1];s.role!=="user"||i?.role!=="user"?e.push(s):typeof i.content=="string"&&typeof s.content=="string"?e[e.length-1]={...i,content:`${i.content}
|
|
64
|
+
|
|
65
|
+
${s.content}`}:e[e.length-1]={...i,content:[...t(i.content),{type:"text",text:`
|
|
66
|
+
|
|
67
|
+
`},...t(s.content)]}}return e}var Di="The tool call was stopped before it ran.",nd="The tool returned no output.";function id(n){let t=n.result?.trim();return n.status==="resolved"?t||nd:n.status==="failed"?t||"The tool failed.":n.status==="rejected"&&t||Di}var Wt=n=>n.type==="tool_call"&&!!n.deferred&&(n.status==="awaiting-approval"||n.status==="pending");function la(n,t,e={}){let s=n.segments??[];if(n.role!=="assistant"||!s.some(c=>c.type==="tool_call")){let c=t(s)||(typeof n.content=="string"?n.content:"");return c?[{role:n.role,content:c}]:[]}let i=[],r=[],a=[],o=()=>{let c=t(r);if(a.length===0)c&&i.push({role:"assistant",content:c});else{i.push({role:"assistant",content:c,toolCalls:a.map(d=>({id:d.toolCall.id,name:d.toolCall.name,input:d.toolCall.input}))});for(let d of a)e.openDeferred&&Wt(d)||i.push({role:"tool",content:id(d),toolCallId:d.toolCall.id,toolName:d.toolCall.name})}r=[],a=[]},l=!1;for(let c of s)c.type==="tool_call"?(a.push(c),e.openDeferred&&Wt(c)&&(l=!0)):(a.length>0&&!l&&o(),r.push(c));return o(),i}var ca=n=>n.status==="streaming"||n.status==="pending";function De(n){if(!n?.length)return"";let t="```",e=[];for(let s of n){let i=s.content;if(s.type==="text")i&&e.push(i);else if(s.type==="code"){let r=s.language??"";e.push(`${t}${r}
|
|
68
|
+
${i??""}
|
|
69
|
+
${t}`)}else{if(s.type==="thinking"||s.type==="tool_call"||s.type==="error")continue;if(typeof i=="string"&&i)e.push(i);else{let r=s.fallback;r&&e.push(r)}}}return e.join(`
|
|
70
|
+
`).trim()}function rd(n){let t=De(n.segments);return t||(typeof n.content=="string"&&n.content?n.content:"")}function ad(n){let t=rd(n);return n.compaction?yn(t):t}function be(n){return n.filter(t=>t.role!=="user"&&t.role!=="assistant"?!1:t.status!=="error"&&!ca(t)).flatMap(t=>{if(t.role==="assistant"&&t.segments?.some(s=>s.type==="tool_call"))return la(t,De);let e=ad(t);return e?[{role:t.role,content:e}]:[]})}function wt(n){return n?Math.ceil(n.length/3.8):0}var wn=n=>{if(!n)return 0;try{return wt(JSON.stringify(n))}catch{return 0}};function da(n){let t=0;for(let e of n)t+=wt(ji(e.content)),e.toolCalls?.length&&(t+=wn(e.toolCalls));return t}function od(n){return n.some(t=>typeof t.content!="string"&&t.content.some(e=>e.type!=="text"))}function ld(n){let t=(n.tools??[]).map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema}));return da(n.messages)+(t.length?wn(t):0)}function ua(n){return da(be(n))}var Be=n=>n.totalTokens??n.inputTokens+n.outputTokens;function ha(n){let t=n.getCurrentModel()?.capabilities;return(t?!t.includes("function_calling"):!1)?[]:n.getTools()}function cd(n,t){if(typeof t=="number"&&Number.isFinite(t)&&t>0)return t;let e=n.getCurrentModel()?.contextWindow;return e&&e>0?e:void 0}var pa=(n,t)=>n.segments?.some(e=>e.type===t)===!0;function dd(n){let t=n.usage?.inputTokens,e=n.contextEstimate;return pa(n,"tool_call")?1:t&&e&&t>0&&e>0?Math.min(3,Math.max(.5,t/e)):1}function ud(n,t){let e=n.usage;if(!pa(n,"thinking")||!(e.inputTokens>0))return Be(e);let s=n.segments??[],i=s.map(a=>a.type).lastIndexOf("tool_call"),r=Math.round(t*wt(De(s.slice(i+1))));return e.inputTokens+(e.outputTokens>0?Math.min(r,e.outputTokens):r)}function fa(n){let{messages:t,config:e}=n,s=xe(t),i=wt(e.resolveSystemPrompt())+wt(e.resolveToolSystemPrompts()),r=ha(e).map(_=>({name:_.name,description:_.description,inputSchema:_.inputSchema})),a=r.length?wn(r):0,o=s.summary===void 0?0:wt(yn(s.summary)),l={system:i,tools:a,summary:o,messages:ua(s.messages)},c=i+a+o+l.messages,d=-1;for(let _=t.length-1;_>=0;_--)if(t[_].role==="assistant"&&t[_].usage){d=_;break}let u=d>=0?t[d]:void 0,h=cd(e,n.windowOverride),p=(_,S)=>({...h!==void 0?{window:h}:{},used:_,estimated:S,parts:l,other:Math.max(0,_-c)}),f=u!==void 0&&!n.viewChanged&&d===t.length-1&&!t.some(_=>_.contextSummary!==void 0&&_.contextSummary.createdAt>u.timestamp),g=u?dd(u):1;return u&&f?p(ud(u,g),!1):p(Math.round(g*c),!0)}function _t(n){return n.composedPath?.()[0]??n.target}function At(n){return n.getRootNode()}function lt(n){return n.getRootNode().activeElement??document.activeElement}var hd=0,ve=null;function Kt(n){ve?.push(n)}function D(n,t,e){let s=document.createElement(n);return t&&(s.className=t),e!=null&&(s.textContent=e),s}function Sn(n,t,e){let s=D("span","aparte-elic-option-body"),i=D("span","aparte-elic-option-title",n);if(i.dir="auto",e){let r=D("span","aparte-tag aparte-tag--sm aparte-elic-option-badge",k().t("elicitationRecommended")||"Recommended");i.append(" ",r)}return s.appendChild(i),t&&s.appendChild(Object.assign(D("span","aparte-elic-option-desc",t),{dir:"auto"})),s}function Ks(n,t,e){let s=D("button","aparte-btn aparte-btn--block aparte-btn--surface aparte-elic-option aparte-elic-option--command"+(e?" aparte-elic-option--recommended":""));return s.type="button",s.appendChild(Sn(n,t,e)),s}function An(n,t,e){let s;if(t.title&&t.title.trim()!==e?.trim()){let i=D("p","aparte-elic-title",t.title);i.dir="auto",s=`elic-title-${G()}`,i.id=s,n.appendChild(i)}return t.description&&n.appendChild(Object.assign(D("p","aparte-elic-desc",t.description),{dir:"auto"})),s}function ga(n,t){n.setAttribute("role",t.multiple||t.commands?"group":"radiogroup"),t.titleId?n.setAttribute("aria-labelledby",t.titleId):t.fallbackLabel&&n.setAttribute("aria-label",t.fallbackLabel)}function pd(n,t,e,s){let i=D("div","aparte-elic-field aparte-elic-enum"),r=An(i,n,e),a=D("div","aparte-elic-options"),o=`elic-${G()}`,l=n.multiple?"checkbox":"radio",c=l==="checkbox"?"aparte-checkbox":"aparte-radio",d=n.allowOther??k().getElicitationOptions().allowOther,u=new Set(Array.isArray(n.default)?n.default:n.default!=null?[n.default]:[]),h=s!=null&&!n.multiple&&u.size===0;ga(a,{multiple:n.multiple,commands:h,titleId:r,fallbackLabel:e});let p=(y,m,w,M)=>{if(h){let R=Ks(m,w,M);return R.addEventListener("click",()=>s?.(y)),R}let v=D("label","aparte-field-choice aparte-elic-option"+(M?" aparte-elic-option--recommended":"")),A=D("input",c+" aparte-elic-control");return A.type=l,A.name=o,A.value=y,u.has(y)&&(A.checked=!0),v.append(A,Sn(m,w,M)),v};for(let y of n.options)a.appendChild(p(y.value,y.label??y.value,y.description,y.recommended));let f=null,g=!1;if(d){let y=k();f=D("input","aparte-field aparte-elic-other-input"),f.type="text",f.placeholder=y.t("elicitationOtherPlaceholder"),f.style.display="none",f.setAttribute("aria-label",y.t("elicitationOtherLabel"));let m=f;if(h){let w=Ks(y.t("elicitationOther"));w.classList.add("aparte-elic-option--other"),w.setAttribute("aria-expanded","false"),w.addEventListener("click",()=>{g=!0,w.setAttribute("aria-expanded","true"),m.style.display="",m.focus(),t()});let M=w.querySelector(".aparte-elic-option-title");Kt(()=>{let v=k();M.textContent=v.t("elicitationOther"),m.placeholder=v.t("elicitationOtherPlaceholder"),m.setAttribute("aria-label",v.t("elicitationOtherLabel"))}),a.append(w,m)}else{let w=D("label","aparte-field-choice aparte-elic-option aparte-elic-option--other"),M=D("input",c+" aparte-elic-control");M.type=l,M.name=o,M.value="__other__";let v=D("span","aparte-elic-option-body"),A=D("span","aparte-elic-option-title",y.t("elicitationOther"));v.appendChild(A),Kt(()=>{let R=k();A.textContent=R.t("elicitationOther"),m.placeholder=R.t("elicitationOtherPlaceholder"),m.setAttribute("aria-label",R.t("elicitationOtherLabel"))}),v.appendChild(f),w.append(M,v),a.appendChild(w)}}i.appendChild(a);let _=()=>Array.from(a.querySelectorAll(".aparte-elic-control")),S=()=>a.querySelector('input[value="__other__"]'),E=!1;a.addEventListener("keydown",y=>{E=y.key.startsWith("Arrow")}),a.addEventListener("click",()=>{E=!1}),a.addEventListener("change",()=>{let y=S();y&&f&&(f.style.display=y.checked?"":"none",y.checked&&!E&&f.focus()),E=!1,t()}),f?.addEventListener("input",t);let I=()=>f?.value.trim()??"";if(h)return{el:i,getValue:()=>I(),isComplete:()=>g&&I()!=="",focus:()=>a.querySelector(".aparte-elic-option--command")?.focus(),offersSubmit:()=>g};let b=()=>{let y=S()?.checked&&I()?I():"";if(n.multiple){let w=_().filter(M=>M.checked&&M.value!=="__other__").map(M=>M.value);return y&&w.push(y),w}let m=_().find(w=>w.checked);return m?m.value==="__other__"?y:m.value:""};return{el:i,getValue:b,isComplete:()=>{let y=b();return n.multiple?y.length>0:y!==""},focus:()=>_()[0]?.focus()}}function fd(n,t,e,s){let i=D("div","aparte-elic-field aparte-elic-boolean"),r=An(i,n,e),a=D("div","aparte-elic-options"),o=`elic-${G()}`,l=s!=null&&n.default==null;if(ga(a,{commands:l,titleId:r,fallbackLabel:e}),l){let h=k(),p=(f,g,_)=>{let S=Ks(g);if(S.addEventListener("click",()=>s?.(f)),_){let E=S.querySelector(".aparte-elic-option-title");Kt(()=>{E.textContent=k().t(_)})}a.appendChild(S)};return p(!0,n.trueLabel??h.t("elicitationYes"),n.trueLabel?void 0:"elicitationYes"),p(!1,n.falseLabel??h.t("elicitationNo"),n.falseLabel?void 0:"elicitationNo"),i.appendChild(a),{el:i,getValue:()=>!1,isComplete:()=>!1,focus:()=>a.querySelector(".aparte-elic-option--command")?.focus(),offersSubmit:()=>!1}}let c=(h,p,f)=>{let g=D("label","aparte-field-choice aparte-elic-option"),_=D("input","aparte-radio aparte-elic-control");_.type="radio",_.name=o,_.value=h,n.default!=null&&String(n.default)===h&&(_.checked=!0);let S=D("span","aparte-elic-option-body"),E=D("span","aparte-elic-option-title",p);E.dir="auto",f&&Kt(()=>{E.textContent=k().t(f)}),S.appendChild(E),g.append(_,S),a.appendChild(g)},d=k();c("true",n.trueLabel??d.t("elicitationYes"),n.trueLabel?void 0:"elicitationYes"),c("false",n.falseLabel??d.t("elicitationNo"),n.falseLabel?void 0:"elicitationNo"),i.appendChild(a),a.addEventListener("change",t);let u=()=>a.querySelector("input:checked");return{el:i,getValue:()=>u()?.value==="true",isComplete:()=>u()!=null,focus:()=>a.querySelector("input")?.focus()}}function gd(n,t,e){let s=D("div","aparte-elic-field aparte-elic-string");An(s,n,e);let i=n.multiline?D("textarea","aparte-field aparte-field--textarea aparte-elic-text"):D("input","aparte-field aparte-elic-text");n.multiline||(i.type="text"),n.placeholder&&i.setAttribute("placeholder",n.placeholder),n.default&&(i.value=n.default),n.maxLength!=null&&i.setAttribute("maxlength",String(n.maxLength));let r=n.title||n.description||e||void 0;if(i.setAttribute("aria-label",r??k().t("elicitationAnswerLabel")),r==null){let l=i;Kt(()=>{l.setAttribute("aria-label",k().t("elicitationAnswerLabel"))})}s.appendChild(i),i.addEventListener("input",t);let a=n.required??!0,o=()=>i.value;return{el:s,getValue:()=>o(),isComplete:()=>{let l=o().trim();return!a&&l===""?!0:l.length>=(n.minLength??1)},focus:()=>i.focus()}}function Bi(n,t,e,s,i){let r=k().getElicitationFieldRenderer()?.(n,{key:s,notifyChange:t});if(r)return{el:r.el,getValue:()=>r.getValue(),isComplete:()=>r.isComplete(),focus:()=>r.focus?.()};switch(n.type){case"enum":return pd(n,t,e,i);case"boolean":return fd(n,t,e,i);case"string":return gd(n,t,e)}}function _a(n,t,e){let s=[],i=ve;ve=s;try{return{..._d(n,t,e),relabel:()=>{for(let a of s)a()}}}finally{ve=i}}function _d(n,t,e){let s=D("div","aparte-elic-panel"),i=typeof n=="function"?n():n;i&&s.appendChild(Object.assign(D("p","aparte-elic-message",i),{dir:"auto"}));let r=null,a=!1,o=p=>{a||(a=!0,r?.(p))},l=p=>{r=p},c=D("div","aparte-elic-body");s.appendChild(c);let d=D("div","aparte-elic-dismiss");if(s.appendChild(d),t.type==="object"){let p=function(A){m=A,I.forEach((R,C)=>{R.field.el.hidden=C!==A}),S()},f=Object.entries(t.properties),g=new Set(t.required??f.map(([A])=>A)),_=k(),S=()=>{},E=()=>{S(),e()},I=f.map(([A,R])=>{let C=Bi(R,E,void 0,A);return!R.title&&!C.el.querySelector(".aparte-elic-title")&&C.el.insertBefore(Object.assign(D("p","aparte-elic-title",A),{dir:"auto"}),C.el.firstChild),c.appendChild(C.el),{key:A,field:C,required:g.has(A),header:R.header}}),b=()=>I.every(A=>!A.required||A.field.isComplete()),y={el:s,dismiss:d,getContent:()=>Object.fromEntries(I.map(A=>[A.key,A.field.getValue()])),isComplete:b,focus:()=>I[0]?.field.focus(),mode:()=>"submit",canProceed:b,proceed:()=>{},onSettle:l};if(I.length<2||_.getElicitationOptions().layout!=="stepped")return y;s.classList.add("aparte-elic-panel--stepped");let m=0,w=`aparte-elic-${++hd}`,M=D("div","aparte-tabs aparte-tabs--underline aparte-elic-steps");M.setAttribute("role","tablist");let v=I.map((A,R)=>{let C=D("button","aparte-tabs__tab aparte-elic-step");return C.type="button",C.setAttribute("role","tab"),C.textContent=A.header?.trim()||String(R+1),C.dir="auto",C.addEventListener("click",()=>{p(R),A.field.focus()}),C.id=`${w}-tab-${R}`,A.field.el.id=`${w}-panel-${R}`,A.field.el.setAttribute("role","tabpanel"),A.field.el.setAttribute("aria-labelledby",C.id),C.setAttribute("aria-controls",A.field.el.id),C.addEventListener("keydown",P=>{let $=getComputedStyle(M).direction==="rtl"?"ArrowLeft":"ArrowRight",F=$==="ArrowRight"?"ArrowLeft":"ArrowRight",V=P.key===$?1:P.key===F?-1:0,Y=-1;V?Y=(R+V+I.length)%I.length:P.key==="Home"?Y=0:P.key==="End"&&(Y=I.length-1),!(Y<0)&&(P.preventDefault(),p(Y),v[Y]?.focus())}),M.appendChild(C),C});return s.insertBefore(M,c),S=()=>{v.forEach((A,R)=>{A.setAttribute("aria-selected",String(R===m)),A.tabIndex=R===m?0:-1;let C=I[R].field.isComplete();A.toggleAttribute("data-answered",C);let P=A.querySelector(".aparte-elic-step__mark");if(C&&!P){let $=D("span","aparte-elic-step__mark");$.setAttribute("aria-hidden","true"),$.innerHTML=_.getIcon("check"),A.prepend($)}else!C&&P&&P.remove()})},p(0),{...y,focus:()=>I[m]?.field.focus()}}let u=k().getElicitationOptions().answerOnClick,h=Bi(t,e,i,void 0,u?o:void 0);return c.appendChild(h.el),{el:s,dismiss:d,getContent:()=>h.getValue(),isComplete:()=>h.isComplete(),focus:()=>h.focus(),mode:()=>h.offersSubmit?.()??!0?"submit":"none",canProceed:()=>h.isComplete(),proceed:()=>{},onSettle:l}}var md=0;function rt(n,t,e){let s=document.createElement(n);return t&&(s.className=t),e!=null&&(s.textContent=e),s}var bd=0;function ma(n,t,e,s,i=!0){let r=k(),a=rt("div","aparte-elic-panel aparte-approval-panel"),o=rt("div","aparte-elic-body");a.appendChild(o);let l=()=>typeof n=="function"?n():n,c=l()?Object.assign(rt("p","aparte-elic-message",l()),{dir:"auto"}):null;c&&o.appendChild(c);let d=null;if(s){d=rt("div","aparte-approval-args-label",r.t("approvalArgsLabel")),d.id="aparte-approval-args-"+ ++md;let m=rt("pre","aparte-approval-args");m.textContent=s,m.setAttribute("role","group"),m.setAttribute("aria-labelledby",d.id),m.tabIndex=0,o.append(d,m)}let u=rt("div","aparte-elic-dismiss");a.appendChild(u);let h=null,p=!1,f=m=>{p||(p=!0,h?.(m))},g=rt("div","aparte-approval-options");g.setAttribute("role","group"),g.setAttribute("aria-label",r.t("approvalOptionsLabel")),c&&(c.id||=`aparte-approval-ask-${++bd}`,g.setAttribute("aria-describedby",c.id));let _=[],S=m=>typeof m.label=="function"?m.label():m.label,E=m=>typeof m.description=="function"?m.description():m.description,I=m=>Sn(S(m),E(m));for(let m of t){let w=m.tone??"affirm",M=rt("button",`aparte-btn aparte-btn--block aparte-btn--surface aparte-approval-option aparte-approval-option--${w}`);M.type="button",M.appendChild(I(m)),M.addEventListener("click",()=>f({option:m.value})),g.appendChild(M),_.push({button:M,option:m})}o.appendChild(g);let b=i?rt("textarea","aparte-approval-instruction"):null;b&&(b.rows=1,b.placeholder=r.t("approvalInstructionPlaceholder"),b.setAttribute("aria-label",r.t("approvalInstructionPlaceholder")),b.addEventListener("input",e),o.appendChild(b));let y=()=>b?.value.trim()??"";return{el:a,dismiss:u,onSettle:m=>{h=m},getContent:()=>({instruction:y()}),isComplete:()=>y().length>0,focus:()=>{a.querySelector(".aparte-approval-option")?.focus()},relabel:()=>{let m=k(),w=m.t("approvalInstructionPlaceholder");b&&(b.placeholder=w,b.setAttribute("aria-label",w)),g.setAttribute("aria-label",m.t("approvalOptionsLabel")),c&&(c.textContent=l()),d&&(d.textContent=m.t("approvalArgsLabel"));for(let{button:M,option:v}of _)M.replaceChildren(I(v))}}}function ba(n){return T(n.target??null).requestUserInput(n)}var vd="Not run: an earlier call of the same step was refused.",Hi=n=>JSON.stringify([n.id,n.name,n.input]),$i=new Set,bt=new Map,qi="aparte-chat, aparte-chat-viewport, [data-aparte-chat]";function yd(n){return{id:n,getMetadata:()=>({id:n,name:n}),getModels:()=>[],chat:async()=>{throw new X("This turn has no provider in the page. Register one, or use a runner that calls the model elsewhere (createAgentStreamRunner, an AG-UI runner).",B.CONFIG_NO_PROVIDER)}}}function wd(n,t){let e=[],s=0;for(let i of[...t].sort((r,a)=>r.start-a.start)){let r=n.indexOf(i.text,s);r<0||(s=r+i.text.length,e.push({...i,start:r,end:s}))}return e}var Vs=class{_boundHandler=null;_listening=!1;_boundAbortHandler=null;_boundLoadedHandler=null;_boundRetryHandler=null;_boundEditHandler=null;_releaseKeyResolver=null;_isAborted=!1;_windowReadFor=new Set;async _readWindowAfterTurn(){let t=this._config,e=t.getCurrentModel(),s=t.getModelConfig().defaultProvider;if(!e||e.contextWindow||!s)return;let i=`${s}\0${e.id}`;this._windowReadFor.has(i)||(this._windowReadFor.add(i),await t.refreshProviderModels(s))}_isForThisInstance(t){if(!t)return!0;let e=t.detail,s=this.options.scopeToTargetId;if(s)return e?.targetId===s;if(this._config===Q){if(bt.size===0)return!0;let a=this._resolveTarget(e?.targetId,t),o=a?T(a):Q;return o===Q||!bt.has(o)}let i=this._resolveTarget(e?.targetId,t);if(!i)return!0;let r=T(i);return r===this._config||r===Q}_streamController=null;options;_config;_claims=!1;constructor(t={}){this.options={autoRegister:!0,...t},this._config=t.config??Q,this._registerKeyResolver(),this.options.autoRegister?jr(this._config):qr(this._config),this._setupListeners()}_beginUserTurn(){this._isAborted=!1}_registerKeyResolver(){this._releaseKeyResolver||!this.options.keyResolver||(this._releaseKeyResolver=this._config.registerKeyProvider(this.options.keyResolver))}_setupListeners(){this._boundHandler||(this._boundHandler=t=>{let e=t;e.type==="aparte-send"&&this._isForThisInstance(e)&&(this._beginUserTurn(),this._handleSend(e))})}start(){this._registerKeyResolver(),this._config!==Q&&!this._claims&&(this._claims=!0,bt.set(this._config,(bt.get(this._config)??0)+1)),this._boundHandler||this._setupListeners(),this._boundHandler&&window.addEventListener("aparte-send",this._boundHandler),this._boundAbortHandler||(this._boundAbortHandler=t=>{this._isForThisInstance(t)&&this.abort()}),window.addEventListener("aparte-abort",this._boundAbortHandler),this._boundRetryHandler||(this._boundRetryHandler=t=>{let e=t;this._isForThisInstance(e)&&this._handleRetry(e)}),window.addEventListener("aparte-retry",this._boundRetryHandler),this._boundEditHandler||(this._boundEditHandler=t=>{let e=t;this._isForThisInstance(e)&&this._handleEdit(e)}),window.addEventListener("aparte-edit",this._boundEditHandler),this._boundLoadedHandler||(this._boundLoadedHandler=t=>{if(!this._isForThisInstance(t))return;let e=t.target instanceof HTMLElement?t.target:void 0;this.resumeDeferred(e??t.detail?.targetId)}),window.addEventListener("aparte-conversation-loaded",this._boundLoadedHandler),this._listening=!0}stop(){if(this.abort(),this._claims){this._claims=!1;let t=(bt.get(this._config)??1)-1;t>0?bt.set(this._config,t):bt.delete(this._config)}this._releaseKeyResolver?.(),this._releaseKeyResolver=null,!(!this._listening||!this._boundHandler)&&(this._listening=!1,window.removeEventListener("aparte-send",this._boundHandler),this._boundHandler=null,this._boundAbortHandler&&(window.removeEventListener("aparte-abort",this._boundAbortHandler),this._boundAbortHandler=null),this._boundLoadedHandler&&(window.removeEventListener("aparte-conversation-loaded",this._boundLoadedHandler),this._boundLoadedHandler=null),this._boundRetryHandler&&(window.removeEventListener("aparte-retry",this._boundRetryHandler),this._boundRetryHandler=null),this._boundEditHandler&&(window.removeEventListener("aparte-edit",this._boundEditHandler),this._boundEditHandler=null))}abort(){this._isAborted=!0,this._streamController?.abort()}async _askForApproval(t,e,s){let i=await ba({kind:"approval",message:()=>{let o=this._config.getLocale(),l=T(s),c={id:`tool-${t.id}`,type:"tool_call",status:"awaiting-approval",toolCall:{id:t.id,name:t.name,input:t.input}},d=kr(c,l).text,u=Tr(c,l);return(o.approvalAsk??"Allow {tool}?").replace("{tool}",()=>u?`${d} ${u}`:d)},details:Er(t.input,T(s).getToolInputFormatter(t.name)),options:[{value:"allow",label:()=>this._config.getLocale().approveTool??"Approve",tone:"affirm"},{value:"deny",label:()=>this._config.getLocale().rejectTool??"Reject",tone:"deny"}],signal:e,target:s});if(i.action!=="accept")return{approved:!1,by:"person"};let r=i.content,a=r?.instruction?.trim();return a?{approved:!1,instruction:a,by:"person"}:r?.option==="allow"?{approved:!0}:{approved:!1,by:"person"}}get _modelRunsElsewhere(){let t=this.options.streamRunner;return!!t&&t!==ps}_providerFor(t){let e=t?this._config.getAIProvider(t):void 0;return e||(this._modelRunsElsewhere?yd(t??""):void 0)}async _resolveAuth(t){if(this.options.keyResolver){let s=await this.options.keyResolver(t);if(s)return s}return await this._config.getKey(t)||void 0}async _streamTurn(t,e,s,i,r,a,o){let l=this._targetIdOf(t),c=this._toolsForCurrentModel(),d=async m=>{let w={messages:m,modelId:r,stream:!0,tools:c.length?c:void 0,...o?.temperature!==void 0?{temperature:o.temperature}:{},...o?.meta?{_meta:o.meta}:{}};return this.options.requestInterceptor&&(w=await this.options.requestInterceptor(w)),w.toolChoice==="none"&&(w={...w,tools:void 0}),w},u=await d(i);if(this._isAborted){J(t,"aparte-message-aborted",{messageId:e},l),this._updateMessage(t,e,{status:"completed"});return}J(t,"aparte-message-start",{messageId:e,role:"assistant"},l),o?.resume&&J(t,"aparte-message-paused",{messageId:e},l),!o?.resume&&s.id&&this._updateMessage(t,e,{model:{providerId:s.id,modelId:u.modelId,...u.temperature!==void 0?{temperature:u.temperature}:{}}});let h=new AbortController;this._streamController!==h&&this._streamController?.abort(),this._streamController=h,this._turnsInFlight.add(e);let p=o?.rebuild?T(t).getCompactor()??this._config.getCompactor():null,f=()=>{let m=t.getMessages?.()??[],w=m.findIndex(v=>v.id===e),M=w>0?m[w-1]:void 0;return M?.role==="user"?[M.id,e]:[e]},g=()=>o?.resume?this._resumeMessages(t,e,u.messages):u.messages,_=()=>ld({messages:g(),tools:u.tools}),S=()=>od(g())?void 0:_(),E=()=>{this._closeOpenCalls(t,e),J(t,"aparte-message-aborted",{messageId:e},l),this._updateMessage(t,e,{status:"completed"})},I=()=>this._isAborted||h.signal.aborted,b=async()=>{let m=o?.resume?{usage:void 0,suspended:o.resume}:await this._streamLoop(t,e,s,u,a,h,void 0,o?.files),w=this.options.maxTurns??10,M=0,v=new Set,A=me({target:t,config:this._config,messageId:e,...l?{targetId:l}:{}});for(;m.suspended;){let P=this._isAborted||h.signal.aborted;if(!P&&++M>w){this._closeOpenCalls(t,e),me({target:t,config:this._config,messageId:e,...l?{targetId:l}:{}})({type:"turn-limit-exceeded",scope:"global",limit:w});break}let $=new Set,F=P?void 0:await this._answerDeferred(t,m.suspended.pending,h.signal,A,v,$);if(v=$,!F){this._closeOpenCalls(t,e),(this._isAborted||h.signal.aborted)&&J(t,"aparte-message-aborted",{messageId:e},l);break}let V={outcomes:F,...m.suspended.ticket?{token:m.suspended.ticket}:{}},Y=this._resumeMessages(t,e,u.messages);this._spendPause(t,e),J(t,"aparte-message-resumed",{messageId:e},l),m=await this._streamLoop(t,e,s,{...u,messages:Y},a,h,V)}let R=m.usage,C=m.finishReason;this._isAborted||h.signal.aborted?(this._closeOpenCalls(t,e),this._updateMessage(t,e,{status:"completed"})):(J(t,"aparte-message-done",{messageId:e,role:"assistant",usage:R,...C?{finishReason:C}:{}},l),this._readWindowAfterTurn())},y=async m=>{if(m.code!==B.USAGE_CONTEXT_EXCEEDED||!p||!o?.rebuild||(t.getMessage?.(e)?.segments??t.getMessages?.()?.find(M=>M.id===e)?.segments??[]).some(M=>M.type==="text"||M.type==="tool_call"))return"stands";try{let M=await p.compact({target:t,...l?{targetId:l}:{},force:!0,reason:"overflow",exclude:f(),signal:h.signal});if(I())return"stopped";if(!M.ok||M.skipped)return"stands";u=await d(await o.rebuild())}catch{return"stands"}return this._updateMessage(t,e,{status:"pending"}),"resend"};try{for(let m=0;;m++)try{if(m===0&&p?.beforeSend&&o?.rebuild){let w=!1;try{w=await p.beforeSend({target:t,...l?{targetId:l}:{},exclude:f(),requestTokens:_(),signal:h.signal})}catch(M){console.warn("[AparteClient] The compactor threw before a send; sending the request as built.",M)}if(I()){E();return}w&&(u=await d(await o.rebuild()))}this._updateMessage(t,e,{contextEstimate:S()}),await b();return}catch(w){if(this._closeOpenCalls(t,e),I()){J(t,"aparte-message-aborted",{messageId:e},l),this._updateMessage(t,e,{status:"completed"});return}let M=X.from(w,B.UNKNOWN_ERROR),v=m===0?await y(M):"stands";if(v==="resend")continue;if(v==="stopped"){E();return}this._handleLifecycleError(t,e,M);return}}finally{this._turnsInFlight.delete(e)}}_turnsInFlight=new Set;_toolsForCurrentModel(){return ha(this._config)}async _handleRetry(t){let{messageId:e,targetId:s}=t.detail??{};if(this._beginUserTurn(),!e)return;let i=this._resolveTarget(s,t);if(!i){console.warn("[AparteClient] aparte-retry \u2014 no target found");return}let r=i.getMessages?.()??[],a=r.findIndex(E=>E.id===e),l=(a>=0?r[a]:void 0)?.role==="user"?a+1:a,c=a>=0?r.slice(0,l):r,d={id:G(),role:"assistant",content:"",status:"pending",timestamp:Date.now()},u=i.addSiblingOf?.(e,d)??d.id,h=this._config.getModelConfig(),p=h.defaultProvider,f=this._providerFor(p);if(!f)return;let g=p?await this._resolveAuth(p):void 0,_=this._messagesToChatMessages(c),S=this._systemMessages();await this._streamTurn(i,u,f,[...S,...kt(_)],h.defaultModel||"",g,{...f.retryTemperature!==void 0?{temperature:f.retryTemperature}:{},...this._turnMeta([...c].reverse().find(E=>E.role==="user")),rebuild:async()=>[...this._systemMessages(),...kt(this._messagesToChatMessages(this._current(i,c)))]})}_systemMessages(){let t=[],e=this._config.resolveSystemPrompt();e&&t.push({role:"system",content:e});let s=this._config.resolveToolSystemPrompts();return s&&t.push({role:"system",content:s}),t}async _handleEdit(t){let{messageId:e,content:s,targetId:i}=t.detail??{};if(this._beginUserTurn(),!e||s===void 0)return;let r=this._resolveTarget(i,t);if(!r){console.warn("[AparteClient] aparte-edit \u2014 no target found");return}let a=r.getMessages?.().find(S=>S.id===e);r.updateMessage?.(e,{content:s,...a?.tokens?{tokens:wd(s,a.tokens)}:{}});let o=r.getMessages?.()??[],l=o.findIndex(S=>S.id===e);if(r.truncateResponsesAfter)r.truncateResponsesAfter(e);else{let S=l>=0&&l+1<o.length?o[l+1]?.id:void 0;S&&r.truncateFrom?.(S)}let c=l>=0?o.slice(0,l+1):o,d=this._messagesToChatMessages(c),u=this._systemMessages(),h=this._config.getModelConfig(),p=h.defaultProvider,f=this._providerFor(p);if(!f)return;let g=p?await this._resolveAuth(p):void 0,_=G();r.appendMessage?.({id:_,role:"assistant",content:"",status:"pending",timestamp:Date.now()}),await this._streamTurn(r,_,f,[...u,...kt(d)],h.defaultModel||"",g,{...this._turnMeta(l>=0?o[l]:void 0),rebuild:async()=>[...this._systemMessages(),...kt(this._messagesToChatMessages(this._current(r,c)))]})}_current(t,e){let s=new Map((t.getMessages?.()??[]).map(i=>[i.id,i]));return e.map(i=>t.getMessage?.(i.id)??s.get(i.id)??i)}_originChain(t){let e=t?.composedPath?.()??[];if(e.length>0)return e;let s=[],i=t?_t(t):null;for(;i;)s.push(i),i=i.parentElement;return s}_rootsFor(t){let e=[];for(let s of this._originChain(t)){if(typeof s.getRootNode!="function")continue;let i=At(s);e.includes(i)||e.push(i)}return e.includes(document)||e.push(document),e}_byId(t,e){for(let s of this._rootsFor(e)){let i=s.getElementById?.(t);if(i)return i}return null}_scanForTarget(t){for(let e of this._rootsFor(t))for(let s of e.querySelectorAll(qi)){let i=this._asRenderTarget(s);if(i)return i}return null}_resolveTarget(t,e){if(t){let i=this._byId(t,e);if(i)return this._asRenderTarget(i)??i}if(this.options.targetResolver){let i=this.options.targetResolver();if(i)return this._asRenderTarget(i)??i}let s=this._scanForTarget(e);if(s)return s;for(let i of this._rootsFor(e)){let r=i.querySelector(qi);if(r)return r}return null}_asRenderTarget(t){if(!t)return null;if(typeof t.appendMessage=="function")return t;let e=t.viewport;return e&&typeof e.appendMessage=="function"?e:null}_targetIdOf(t){let e=t??null;for(;e;){if((e.tagName?.toLowerCase()==="aparte-chat"||e.hasAttribute?.("data-aparte-chat"))&&e.id)return e.id;e=e.parentElement}return t?.id||void 0}_messagesToChatMessages(t){let{summary:e,messages:s}=xe(t);return[...this._summaryMessage(e),...be(s)]}_summaryMessage(t){return t===void 0?[]:[{role:"user",content:yn(t)}]}_turnMeta(t){let e={...t?.metadata??t?.meta,...t?.tokens?.length?{tokens:t.tokens}:{}};return Object.keys(e).length>0?{meta:e}:{}}_warnedNoModel=!1;async _handleSend(t){let{content:e,modelId:s,providerId:i}=t.detail;if(this._config.getRequireModelSelection()&&!this._config.hasSelectedModel()&&!s){console.warn("[AparteClient] Send refused: requireModelSelection is on and no model is selected yet. The composer blocks this, but this send did not come from it \u2014 disable your own send affordances while `hasSelectedModel()` is false.");return}let r=null,a=t.detail?.targetId;if(a){let g=this._byId(a,t),_=this._asRenderTarget(g);_?r=_:console.warn("[AparteClient] \u26A0\uFE0F targetId present but element not found or missing appendMessage:",a)}if(!r&&this.options.targetResolver&&(r=this._asRenderTarget(this.options.targetResolver())),!r)for(let g of this._originChain(t)){let _=g;if(typeof _?.appendMessage=="function"){r=_;break}}if(r||(r=this._scanForTarget(t)),!r){console.warn("[AparteClient] \u26A0\uFE0F No target element found with appendMessage support. Provide a targetResolver in AparteClientOptions or ensure the composer has a `target` attribute.");return}if(this._closeDeferred(r),this.options.echoUserMessage!==!1&&t.detail?.echoed!==!0){let g=Array.isArray(t.detail?.files)?t.detail.files:[];r.appendMessage?.({id:G(),role:"user",content:e,timestamp:Date.now(),...g.length>0?{attachments:na(g)}:{},...t.detail?.tokens?.length?{tokens:t.detail.tokens}:{},...t.detail?.meta?{metadata:t.detail.meta}:{}}),t.detail&&typeof t.detail=="object"&&(t.detail.echoed=!0)}let o=G(),l=this._config.getModelConfig(),c=i||l.defaultProvider;if(!c&&!this._modelRunsElsewhere){this._warnedNoModel||(this._warnedNoModel=!0,console.warn("[AparteClient] Send dropped: no model is selected. Call aparteGlobalConfig.setModelConfig({ defaultProvider, defaultModel }), mount <aparte-model-selector auto-select persist>, or register one provider with a single model \u2014 that one is selected on its own.")),this._handleLifecycleError(r,o,new X("No provider selected. Please configure a provider.",B.CONFIG_NO_PROVIDER));return}let d=this._providerFor(c);if(!d){this._handleLifecycleError(r,o,new X(`Provider '${c}' is not registered.`,B.CONFIG_MISSING_KEY,{providerId:c}));return}r.appendMessage?.({id:o,role:"assistant",content:"",status:"pending",timestamp:Date.now()});let u,h,p,f=Array.isArray(t.detail?.files)?t.detail.files:[];try{u=c?await this._resolveAuth(c):void 0;let g=this._selectFilesToInject(f),_=g.length>0?await this._filesToContentParts(g):[];p=_.length>0?_:void 0,h=this._buildMessages(e,r,p)}catch(g){this._handleLifecycleError(r,o,X.from(g,B.UNKNOWN_ERROR));return}await this._streamTurn(r,o,d,h,s||l.defaultModel||"",u,{rebuild:async()=>this._buildMessages(e,r,p),...f.length>0?{files:f}:{},...this._turnMeta(t.detail)})}_buildMessages(t,e,s){let i=this._systemMessages(),r=this.options.history??"viewport",a=e?.getMessages?.()??[];r==="viewport"?i.push(...this._toHistoryMessages(a)):typeof r=="function"&&i.push(...r(a));let o=s&&s.length>0?[{type:"text",text:t},...s]:t;return i.push({role:"user",content:o}),kt(i)}_toHistoryMessages(t){let{summary:e,messages:s}=xe(t),i=0;for(let r=0;r<s.length;r++){let a=s[r];a.role==="assistant"&&a.status!=="error"&&!ca(a)&&(i=r+1)}return[...this._summaryMessage(e),...be(s.slice(0,i))]}_selectFilesToInject(t){let e=this.options.rawFileInject==="none"?[]:this.options.rawFileInject==="images-only"?t.filter(i=>i.type.startsWith("image/")):t,s=this.options.fileInjectFilter;return s?e.filter(i=>s(i)):e}async _filesToContentParts(t){let e=/^(text\/|application\/(json|xml|javascript|typescript|x-yaml|yaml|toml|csv|markdown))/i,s=/\.(txt|md|markdown|json|jsonl|csv|tsv|xml|html|htm|css|js|mjs|cjs|ts|tsx|jsx|py|rb|java|c|cpp|h|go|rs|php|sh|bash|zsh|fish|yaml|yml|toml|ini|env|log|svg|graphql|gql)$/i;return(await Promise.all(t.map(r=>r.type.startsWith("image/")?new Promise((a,o)=>{let l=new FileReader;l.onload=()=>a({type:"image",image:l.result,mimeType:r.type}),l.onerror=()=>o(new Error(`Failed to read file: ${r.name}`)),l.readAsDataURL(r)}):e.test(r.type)||s.test(r.name)?new Promise((a,o)=>{let l=new FileReader;l.onload=()=>{let c=l.result,d=r.name.split(".").pop()??"";a({type:"text",text:`\`\`\`${d}
|
|
71
|
+
// File: ${r.name}
|
|
72
|
+
${c}
|
|
73
|
+
\`\`\``})},l.onerror=()=>o(new Error(`Failed to read file: ${r.name}`)),l.readAsText(r)}):($i.has(r.name)||($i.add(r.name),console.warn(`[aparte] ${r.name} (${r.type||"unknown type"}) is attached to the message but is not sent to the model: apart\xE9 inlines images and text files only. Handle it in your app (RAG, an upload) \u2014 the chip stays visible either way.`)),Promise.resolve(null))))).filter(r=>r!==null)}async _streamLoop(t,e,s,i,r,a=new AbortController,o,l){this._streamController!==a&&this._streamController?.abort(),this._streamController=a;let c=this.options.streamRunner??ps;return this._runViaStreamRunner(c,t,e,s,i,r,a,o,l)}async _runViaStreamRunner(t,e,s,i,r,a,o,l,c){let d=o.signal,u=this._targetIdOf(e),h=me({target:e,config:this._config,messageId:s,...u?{targetId:u}:{}}),p=r._meta?.prefixSegments,f,g,_,S=v=>{if(h(v),v.type==="tool-failed"&&(_=v.error),v.type==="run-done"&&(g=v.finishReason),v.type==="run-suspended"){let A=v.ticket;f={pending:v.pending,...typeof A=="string"?{ticket:A}:{}}}if(v.type==="run-start"&&p?.length&&!l)for(let A of p)e.addSegment?.(A)},E=async v=>{let A=await this._config.getTransport().chat(i,v,a,{providerId:i.id,signal:d});return typeof A=="string"?A:Gr(A,d)},I=v=>{let A=this._config.getToolHandler(v);if(!A)return;let R={target:e,config:this._config};return(C,P)=>A(C,P,R)},b=!!this.options.approvalResolver,y=v=>{let A=this._config.getTools().find(R=>R.name===v);if(A)return{maxTurns:A.maxTurns,needsApproval:b?A.needsApproval:R=>{let C=this._config.ruleOnToolCall(R).verdict;return C==="allow"?!1:C}}},m=this._approvalResolverFor(e),w=v=>{if(_===void 0||v instanceof X)return v;let A=v instanceof Error?v.message||v.name:typeof v=="string"?v:String(v);return A===_?new X(A,B.UNKNOWN_ERROR,void 0,v):v};return{usage:await t({messageId:s,...i.id?{providerId:i.id}:{},...l?{deferral:l}:{},...c&&c.length>0?{files:c}:{},baseRequest:r,transportCall:E,toolLookup:I,toolConfigLookup:y,approvalResolver:m,emitter:S,signal:d,maxTurns:this.options.maxTurns,toolTimeoutMs:this.options.toolTimeoutMs,idGen:v=>v==="synthetic-tool"?G():`${v}-${G()}`}).catch(v=>{throw w(v)})??void 0,...g?{finishReason:g}:{},...f?{suspended:f}:{}}}_approvalResolverFor(t,e=!1){return this.options.approvalResolver??(async(s,i)=>{let r=e?this._config.getApprovalPolicy()?.(s,this._config.getTools().find(a=>a.name===s.name))??{verdict:"ask"}:this._config.ruleOnToolCall(s);return r.verdict==="allow"?{approved:!0}:r.verdict==="deny"?{approved:!1,reason:r.reason?.trim()||"Tool execution was refused by the approval policy.",by:"policy"}:this._askForApproval(s,i,t)})}async _answerDeferred(t,e,s,i,r=new Set,a=new Set){let o={},l=this._approvalResolverFor(t,!0),c=d=>{for(let u of e.slice(d+1))o[u.toolCallId]={kind:"decision",approved:!1,reason:vd,by:"earlier-refusal"}};for(let[d,u]of e.entries()){if(s.aborted)break;let h={id:u.toolCallId,name:u.name,input:u.input??{}};if(u.reason==="approval"){let p;try{p=await l(h,s)}catch(f){if(!s.aborted&&f?.name!=="AbortError")throw f}if(!p||s.aborted)return;if(o[u.toolCallId]={kind:"decision",...p},p.approved)a.add(Hi(h));else{c(d);break}}else if(u.reason==="external"){let p=null,f=Hi(h);if(!r.has(f)&&!a.has(f))try{p=await this._gateBrowserTool(h,s,t,i)}catch(E){if(!s.aborted&&E?.name!=="AbortError")throw E;p=void 0}if(p===void 0||s.aborted)return;if(p&&!p.approved){o[u.toolCallId]={kind:"decision",...p},c(d);break}let g=p?.payload,_=g&&typeof g=="object"&&!Array.isArray(g)?{...h,input:{...h.input,...g}}:h,S=this._config.getToolHandler(u.name);try{if(!S)throw new Error(`No browser handler is registered for "${u.name}".`);let E=await S(_,s,{target:t,config:this._config});o[u.toolCallId]={kind:"result",content:E.content,...E.structuredContent!==void 0?{structuredContent:E.structuredContent}:{}}}catch(E){if(s.aborted)break;o[u.toolCallId]={kind:"failed",error:E instanceof Error?E.message:String(E)}}}}return s.aborted?void 0:o}async _gateBrowserTool(t,e,s,i){let r=this.options.approvalResolver?this._config.getTools().find(o=>o.name===t.name)?.needsApproval?"ask":"allow":this._config.ruleOnToolCall(t).verdict;if(r==="allow")return null;r==="ask"&&i?.({type:"tool-awaiting-approval",toolCallId:t.id,name:t.name,input:t.input});let a=await this._approvalResolverFor(s)(t,e)??void 0;return a?.approved&&r==="ask"&&s.updateSegment?.(`tool-${t.id}`,{status:"pending"}),a}_spendPause(t,e){let s=t.getMessage?.(e)?.segments??t.getMessages?.()?.find(r=>r.id===e)?.segments,i=r=>r.type==="tool_call"&&!!r.deferred;s?.some(i)&&t.updateMessage?.(e,{segments:s.map(r=>{if(!i(r))return r;let{deferred:a,...o}=r;return o})})}_closeOpenCalls(t,e){let s=t.getMessage?.(e)?.segments??t.getMessages?.()?.find(r=>r.id===e)?.segments,i=r=>r.type==="tool_call"&&(r.status==="pending"||r.status==="awaiting-approval");s?.some(i)&&t.updateMessage?.(e,{segments:s.map(r=>{if(!i(r))return r;let{deferred:a,...o}=r;return{...o,status:"aborted"}})})}_resumeMessages(t,e,s){let i=t.getMessages?.().find(r=>r.id===e);return[...s,...i?la(i,De,{openDeferred:!0}):[]]}_resumeBase(t,e){let s=t.slice(0,e),i=s.map(o=>o.role).lastIndexOf("user"),r=this.options.history??"viewport",a=r==="viewport"?this._toHistoryMessages(s):typeof r=="function"?r(s):[];return kt([...this._systemMessages(),...a,...i>=0?be([s[i]]):[]])}_closeDeferred(t){let s=[...t.getMessages?.()??[]].reverse().find(r=>r.role==="assistant");if(!s?.segments?.some(Wt))return;let i=s.segments.map(r=>{if(!Wt(r))return r;let{deferred:a,...o}=r;return{...o,status:"aborted"}});t.updateMessage?.(s.id,{segments:i})}async resumeDeferred(t){let e=typeof t=="string"?this._byId(t):t??this.options.targetResolver?.()??null,s=e?this._asRenderTarget(e):this._scanForTarget();if(!s)return!1;let i=s.getMessages?.()??[],r=[...i].reverse().find(h=>h.role==="assistant"),a=(r?.segments??[]).filter(Wt),o=a.find(h=>h.deferred?.ticket)?.deferred?.ticket;if(!r||a.length===0||!o||this._resuming.has(r.id)||this._turnsInFlight.has(r.id))return!1;let l=this._config.getModelConfig(),c=r.model&&this._config.getAIProvider(r.model.providerId)?r.model:void 0,d=c?.providerId??l.defaultProvider,u=this._providerFor(d);if(!u)return console.warn("[AparteClient] Cannot resume the paused turn: no provider is selected."),!1;this._beginUserTurn(),this._resuming.add(r.id);try{let h=u.id?await this._resolveAuth(u.id):void 0,p=a.map(g=>({toolCallId:g.toolCall.id,name:g.toolCall.name,input:g.toolCall.input,reason:g.deferred.reason})),f=this._resumeBase(i,i.indexOf(r));await this._streamTurn(s,r.id,u,f,c?.modelId??l.defaultModel??"",h,{resume:{pending:p,ticket:o},rebuild:async()=>{let g=s.getMessages?.()??[],_=g.findIndex(S=>S.id===r.id);return _>=0?this._resumeBase(g,_):f},...c?.temperature!==void 0?{temperature:c.temperature}:{}})}finally{this._resuming.delete(r.id)}return!0}_resuming=new Set;_updateMessage(t,e,s){t.updateMessage&&t.updateMessage(e,s)}_handleLifecycleError(t,e,s){let i={id:`error-${G()}`,type:"error",content:s.message,code:s.code};if(qs(s.code,r=>this._config.t(r))!==void 0&&console.warn(`[aparte] A turn failed (${s.code}): ${s.message}`),t.updateMessage){let r=t.getMessage?.(e)?.segments??t.getMessages?.()?.find(a=>a.id===e)?.segments??[];t.updateMessage(e,{status:"error",segments:[...r,i]})}else t.appendMessage&&t.appendMessage({id:e,role:"assistant",status:"error",timestamp:Date.now(),segments:[i]});J(t,"aparte-message-error",{messageId:e,error:s},this._targetIdOf(t))}};function va(n){return n.next?va(n.next):"current"in n?n:null}var Ie=class{_nodes=new Map;_head=null;_root={next:null,children:[]};get headId(){return this._head?.current.id??null}getMessages(){let t=this._head?.level??-1;if(t<0)return[];let e=new Array(t+1);for(let s=this._head;s;s=s.prev)e[s.level]=s.current;return e}getMessage(t){let e=this._nodes.get(t);if(e)return{parentId:e.prev?.current.id??null,message:e.current,index:e.level}}getMessageById(t){return this._nodes.get(t)?.current}getAllMessages(){let t=[];for(let e of this._nodes.values())t.push(e.current);return t}getBranches(t){let e=this._nodes.get(t);return e?[...(e.prev??this._root).children]:[]}addOrUpdateMessage(t,e){let s=this._nodes.get(e.id),i=t?this._nodes.get(t):void 0;if(t!==null&&i===void 0)throw new Error(`AparteMessageRepository: parent "${t}" not found.`);let r=i??null;if(s){s.current=e,this._relink(r,s);return}let a={prev:r,next:null,children:[],current:e,level:r?r.level+1:0};this._nodes.set(e.id,a),this._link(r,a),(this._head===r||this._head===null&&r===null)&&(this._head=a)}switchToBranch(t){let e=this._nodes.get(t);if(!e)return;let s=e.prev??this._root;s.next=e,this._head=va(e)}resetHead(t){let e=this._nodes.get(t);if(!e)return;let s=this._head;this._deleteDescendants(e);let i=e.prev??this._root;i.children=i.children.filter(a=>a!==t),i.next===e&&(i.next=null),this._nodes.delete(t),s!==null&&s!==e&&this._nodes.get(s.current.id)===s||(this._head=e.prev)}updateMessage(t,e){let s=this._nodes.get(t);s&&(s.current={...s.current,...e})}clearChildren(t){let e=this._nodes.get(t);if(e){for(let s of[...e.children]){let i=this._nodes.get(s);i&&(this._deleteDescendants(i),this._nodes.delete(s))}e.children=[],e.next=null,this._head=e}}clear(){this._nodes.clear(),this._head=null,this._root={next:null,children:[]}}import(t){this.clear();for(let{message:e,parentId:s}of t.messages){if(s!==null&&!this._nodes.has(s)){console.warn(`[AparteMessageRepository] import: message "${e.id}" names a parent "${s}" the snapshot does not hold before it \u2014 skipped.`);continue}if(this._nodes.has(e.id)){console.warn(`[AparteMessageRepository] import: message "${e.id}" repeats an id already in the snapshot \u2014 skipped.`);continue}this.addOrUpdateMessage(s,e)}t.headId&&this.switchToBranch(t.headId)}export(){let t=[],e=(s,i)=>{for(let r of s){let a=this._nodes.get(r);a&&(t.push({message:a.current,parentId:i}),e(a.children,r))}};return e(this._root.children,null),{headId:this.headId,messages:t}}_link(t,e){let s=t??this._root;s.children=[...s.children,e.current.id],s.next===null&&(s.next=e),e.prev=t}_relink(t,e){let s=e.prev??this._root;if(s!==(t??this._root)&&(s.children=s.children.filter(r=>r!==e.current.id),s.next===e)){let r=s.children[0];s.next=r?this._nodes.get(r)??null:null}e.prev=t;let i=t??this._root;i.children.includes(e.current.id)||(i.children=[...i.children,e.current.id]),i.next===null&&(i.next=e),this._updateLevels(e,t?t.level+1:0)}_updateLevels(t,e){t.level=e;for(let s of t.children){let i=this._nodes.get(s);i&&this._updateLevels(i,e+1)}}_deleteDescendants(t){for(let e of t.children){let s=this._nodes.get(e);s&&(this._deleteDescendants(s),this._nodes.delete(e))}t.children=[],t.next=null}};function Ot(n){return n.status==="streaming"||n.status==="pending"?!0:n.status===void 0&&n.role==="assistant"&&!n.content?.trim()&&!n.segments?.length}function ya(n,t,e={}){let{gap:s=4,margin:i=8,side:r="below",align:a="start",rtl:o=!1}=e,l=t.getBoundingClientRect(),c=(h,p,f)=>Math.max(i,Math.min(h,p-f-i)),d,u;if(r==="beside"){let h=n.right+s,p=n.left-l.width-s,[f,g]=o?[p,h]:[h,p],_=S=>S>=i&&S+l.width<=window.innerWidth-i;u=_(f)||!_(g)?f:g,d=n.top}else{let h=n.bottom+s,p=n.top-l.height-s,f=h+l.height<=window.innerHeight-i,g=p>=i;r==="below"?d=f||!g?h:p:d=g||!f?p:h,u=a==="start"!==o?n.left:n.right-l.width}t.style.top=`${c(d,window.innerHeight,l.height)}px`,t.style.left=`${c(u,window.innerWidth,l.width)}px`}var Sd=".aparte-message-content, .aparte-segments, .aparte-content, .aparte-checkpoint__summary";function it(n){return!!n?.closest?.(Sd)}var Fi=Symbol.for("aparte.dialogTriggers"),Ys=null,Le=null;function Ad(n){Ys=n.target,Le=null}function Cd(n){Le=n.target}function Ed(n){let t=n.target;if(!t?.closest)return;let e=t.closest("[data-aparte-dialog-open]");if(e&&!it(e)){let i=e.getAttribute("data-aparte-dialog-open"),r=i?document.getElementById(i):null;r instanceof HTMLDialogElement&&!r.open&&(n.preventDefault(),r.showModal());return}let s=t.closest("[data-aparte-dialog-close]");if(s&&!it(s)){let i=s.closest("dialog");i instanceof HTMLDialogElement&&i.open&&(n.preventDefault(),i.close(s.getAttribute("data-aparte-dialog-close")??""));return}if(t instanceof HTMLDialogElement&&t.open&&t.classList.contains("aparte-dialog")&&!t.hasAttribute("data-aparte-dialog-static")){let i=Ys===t&&Le===t;Ys=null,Le=null,i&&t.close()}}function wa(n=document){let t=n;t[Fi]||(t[Fi]=!0,n.addEventListener("pointerdown",Ad,!0),n.addEventListener("pointerup",Cd,!0),n.addEventListener("click",Ed))}var Ms="defer-hydration",Vt=new WeakMap,Yt=new WeakMap,Nt=new WeakSet,Re=new WeakSet,Js=new WeakMap,Wi=new WeakSet;function Ui(n){if(Re.has(n))return!1;if(Yt.has(n))return!0;let t=n.closest(`[${Ms}]`);if(!t)return!1;Yt.set(n,t);let e=Vt.get(t);if(!e){e=[],Vt.set(t,e);let s=new MutationObserver(()=>{t.hasAttribute(Ms)||kd(t)});s.observe(t,{attributes:!0,attributeFilter:[Ms]}),Js.set(t,s)}return e.push(n),!0}function kd(n){Js.get(n)?.disconnect(),Js.delete(n);let t=Vt.get(n)??[];Vt.delete(n);for(let e of t)Yt.delete(e),e.isConnected&&!Re.has(e)&&e.connectedCallback?.()}function H(n){if(Wi.has(n))return;Wi.add(n);let t=n.prototype,e=t.connectedCallback,s=t.attributeChangedCallback,i=t.disconnectedCallback,r=n.observedAttributes??[];t.connectedCallback=function(){if(Ui(this)){Nt.add(this);return}if(Nt.has(this)){Nt.delete(this);for(let a of r){let o=this.getAttribute(a);o!==null&&s?.call(this,a,null,o)}}Re.add(this),e?.call(this)},s&&(t.attributeChangedCallback=function(a,o,l){if(Ui(this)){Nt.add(this);return}s.call(this,a,o,l)}),t.disconnectedCallback=function(){let a=Yt.get(this);if(a){Yt.delete(this);let o=Vt.get(a);o&&o.splice(o.indexOf(this),1);return}Nt.has(this)||(Re.delete(this),i?.call(this))}}function z(n){return n===""?!0:!!n}var qe=class extends HTMLElement{static get observedAttributes(){return["value","disabled","selected","data-status"]}connectedCallback(){this.setAttribute("role","option"),this._updateAriaSelected(),this._updateStatusDot()}attributeChangedCallback(t){t==="selected"&&this._updateAriaSelected(),t==="disabled"&&this.setAttribute("aria-disabled",this.hasAttribute("disabled")?"true":"false"),t==="data-status"&&this._updateStatusDot()}get value(){return this.getAttribute("value")||this.textContent?.trim()||""}set value(t){this.setAttribute("value",t)}get label(){return Array.from(this.childNodes).find(e=>e.nodeType===Node.TEXT_NODE)?.textContent?.trim()||this.value}get disabled(){return this.hasAttribute("disabled")}set disabled(t){this.toggleAttribute("disabled",z(t))}get selected(){return this.hasAttribute("selected")}set selected(t){this.toggleAttribute("selected",z(t))}_updateAriaSelected(){this.setAttribute("aria-selected",this.selected?"true":"false")}_updateStatusDot(){let t=this.getAttribute("data-status"),e=this.querySelector(".aparte-status-dot");if(!t){e?.remove();return}e||(e=document.createElement("span"),e.className="aparte-status-dot",e.setAttribute("aria-hidden","true"),this.appendChild(e)),e.setAttribute("data-status",t)}};H(qe);customElements.get("aparte-option")||customElements.define("aparte-option",qe);var Fe=class n extends HTMLElement{static _labelIdSeq=0;static get observedAttributes(){return["label","collapsible","collapsed","loading"]}connectedCallback(){this.setAttribute("role","group"),this._render()}attributeChangedCallback(t,e,s){e!==s&&(t==="collapsed"&&this._updateCollapsedState(),this.isConnected&&this._render())}get label(){return this.getAttribute("label")||""}set label(t){this.setAttribute("label",t)}get collapsible(){return this.hasAttribute("collapsible")}set collapsible(t){this.toggleAttribute("collapsible",z(t))}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(t){this.toggleAttribute("collapsed",z(t))}get loading(){return this.hasAttribute("loading")}set loading(t){this.toggleAttribute("loading",z(t))}_render(){if(this.label&&!this.querySelector(".aparte-optgroup-header")){let e=document.createElement("div");e.className="aparte-optgroup-header";let s=document.createElement("span");if(s.className="aparte-optgroup-label",s.id=`aparte-optgroup-label-${++n._labelIdSeq}`,s.textContent=this.label,this.setAttribute("aria-labelledby",s.id),e.appendChild(s),this.collapsible){let i=document.createElement("span");i.className="aparte-optgroup-chevron",i.innerHTML=T(this).getIcon("expand"),e.appendChild(i),e.style.cursor="pointer",e.addEventListener("click",r=>{r.stopPropagation(),this._toggleCollapse()})}this.insertBefore(e,this.firstChild)}this._updateLoadingState(),this._updateCollapsedState()}_updateLoadingState(){let t=this.querySelector(".aparte-optgroup-loader");if(this.loading){if(!t){t=document.createElement("div"),t.className="aparte-optgroup-loader";let e=document.createElement("span");e.className="aparte-spinner-small",t.replaceChildren(e,` ${T(this).t("loading")||"Loading\u2026"}`),this.appendChild(t)}}else t&&t.remove()}_toggleCollapse(){this.collapsed=!this.collapsed,this.dispatchEvent(new CustomEvent("aparte-optgroup-toggle",{bubbles:!0,composed:!0,detail:{label:this.label,collapsed:this.collapsed}})),this._updateCollapsedState()}_updateCollapsedState(){this.querySelectorAll("aparte-option").forEach(e=>{e.style.display=this.collapsed?"none":""})}};H(Fe);customElements.get("aparte-optgroup")||customElements.define("aparte-optgroup",Fe);var We=class n extends HTMLElement{static _optIdSeq=0;static _listboxSeq=0;_value="";_isOpen=!1;_activeIndex=-1;_trigger=null;_dropdown=null;_searchInput=null;_observer=null;_boundHandleOptionClick=this._handleOptionClick.bind(this);_boundHandleDocumentClick=this._handleDocumentClick.bind(this);_boundHandleKeydown=this._handleKeydown.bind(this);_boundHandleTriggerClick=()=>{this._toggle()};_boundHandleTriggerKeydown=t=>{if(t.key==="Enter"||t.key===" "){if(this._isOpen)return;t.preventDefault(),this._toggle()}t.key==="ArrowDown"&&!this._isOpen&&(t.preventDefault(),this._openDropdown())};_boundHandleSearchInput=t=>{this._filterOptions(t.target.value.toLowerCase())};static get observedAttributes(){return["value","placeholder","disabled","searchable","open"]}connectedCallback(){this._value=this.getAttribute("value")||"";let t=this.hasAttribute("open")&&!this._isOpen;this._render(),this._applySearchable(),this._applyDisabled(),this._setupEventListeners(),this._setupMutationObserver(),t&&this._openDropdown()}disconnectedCallback(){this.removeEventListener("click",this._boundHandleOptionClick),document.removeEventListener("click",this._boundHandleDocumentClick),document.removeEventListener("keydown",this._boundHandleKeydown),this._observer?.disconnect()}attributeChangedCallback(t,e,s){if(this.isConnected){if(t==="value"&&e!==s&&s!==this._value&&(this._value=s||"",this._updateTriggerLabel()),t==="open"){let i=this.hasAttribute("open");i!==this._isOpen&&(i?this._openDropdown():this._closeDropdown())}t==="placeholder"&&this._updateTriggerLabel(),t==="searchable"&&this._applySearchable(),t==="disabled"&&(this._applyDisabled(),!this.hasAttribute("disabled")&&this.hasAttribute("open")&&this._openDropdown())}}get value(){return this._value}set value(t){if(t===this._value)return;let e=this._value;this._value=t,this.setAttribute("value",t),this._updateTriggerLabel(),this._emitChange(e)}get open(){return this._isOpen}set open(t){this.toggleAttribute("open",z(t))}_buildSearchInput(t){let e=document.createElement("input");return e.type="text",e.className="aparte-select-search",e.placeholder=t.t("selectSearchPlaceholder")||"Search\u2026",e.setAttribute("aria-label",t.t("selectSearchLabel")||"Search options"),e.setAttribute("role","combobox"),e.setAttribute("aria-haspopup","listbox"),e.setAttribute("aria-autocomplete","list"),e.setAttribute("aria-expanded",String(this._isOpen)),e}_applySearchable(){if(!this._dropdown||!this._trigger)return;let t=this.hasAttribute("searchable");if(t===!!this._searchInput)return;this._isOpen&&this._closeDropdown();let e=this._trigger.getAttribute("aria-controls");if(t){let s=this._buildSearchInput(T(this));e&&s.setAttribute("aria-controls",e),this._dropdown.prepend(s),this._searchInput=s,s.addEventListener("input",this._boundHandleSearchInput),this._trigger.setAttribute("role","button")}else this._searchInput.removeEventListener("input",this._boundHandleSearchInput),this._searchInput.remove(),this._searchInput=null,this._trigger.setAttribute("role","combobox");this._updateNames()}_render(){let t=this.getAttribute("placeholder")||"Select...",e=this.hasAttribute("searchable");if(this.querySelector(".aparte-select-dropdown")){this._updateTriggerLabel();return}let s=Array.from(this.children),i=T(this),r=document.createElement("div");r.className="aparte-select-trigger",r.setAttribute("tabindex","0"),r.setAttribute("role",e?"button":"combobox"),r.setAttribute("aria-haspopup","listbox"),r.setAttribute("aria-expanded","false"),r.setAttribute("aria-label",this.getAttribute("aria-label")||t);let a=document.createElement("span");a.className="aparte-select-label";let o=document.createElement("span");o.className="aparte-select-label-text",o.textContent=t;let l=document.createElement("span");l.className="aparte-select-label-sizer",l.setAttribute("aria-hidden","true"),a.append(o,l);let c=document.createElement("span");c.className="aparte-select-chevron",c.innerHTML=i.getIcon("expand"),r.append(a,c);let d=document.createElement("div");d.className="aparte-select-dropdown",d.hidden=!this._isOpen;let u=e?this._buildSearchInput(i):null;u&&d.appendChild(u);let h=document.createElement("div");h.className="aparte-select-options",h.setAttribute("role","listbox"),h.setAttribute("aria-label",r.getAttribute("aria-label")??t),h.id=this.id?`${this.id}-listbox`:`aparte-listbox-${++n._listboxSeq}`,r.setAttribute("aria-controls",h.id),u?.setAttribute("aria-controls",h.id),s.forEach(p=>{(p.tagName==="APARTE-OPTION"||p.tagName==="APARTE-OPTGROUP")&&h.appendChild(p)}),d.appendChild(h),this._observer?.disconnect(),this.innerHTML="",this.appendChild(r),this.appendChild(d),this._trigger=r,this._dropdown=d,this._searchInput=d.querySelector(".aparte-select-search"),this.isConnected&&this._setupMutationObserver(),this._updateTriggerLabel()}_setupMutationObserver(){this._observer?.disconnect(),this._observer=new MutationObserver(()=>{this._updateDropdownContent(),this._updateTriggerLabel(),this._restoreActive()}),this._observer.observe(this,{childList:!0,subtree:!0})}_restoreActive(){!this._isOpen||this._activeIndex<0||this.querySelector("aparte-option[data-active]")||this._setActive(this._activeIndex)}_updateDropdownContent(){if(!this._trigger||!this.contains(this._trigger)){this._render();return}let t=this.querySelector(".aparte-select-options");if(!t){this._render();return}let e=Array.from(this.children).filter(s=>s.className!=="aparte-select-trigger"&&s.className!=="aparte-select-dropdown");e.length!==0&&(this._observer?.disconnect(),t.innerHTML="",e.forEach(s=>{t.appendChild(s)}),this.isConnected&&this._observer?.observe(this,{childList:!0,subtree:!0}),this._updateTriggerLabel(),this._restoreActive())}_setupEventListeners(){this._trigger?.removeEventListener("click",this._boundHandleTriggerClick),this._trigger?.addEventListener("click",this._boundHandleTriggerClick),this._trigger?.removeEventListener("keydown",this._boundHandleTriggerKeydown),this._trigger?.addEventListener("keydown",this._boundHandleTriggerKeydown),this.removeEventListener("click",this._boundHandleOptionClick),this.addEventListener("click",this._boundHandleOptionClick),this._searchInput?.removeEventListener("input",this._boundHandleSearchInput),this._searchInput?.addEventListener("input",this._boundHandleSearchInput),document.addEventListener("click",this._boundHandleDocumentClick),document.addEventListener("keydown",this._boundHandleKeydown)}_handleOptionClick(t){let e=t.target.closest("aparte-option");e&&!e.hasAttribute("disabled")&&this._selectOption(e)}_handleDocumentClick(t){let e=_t(t);(!e||!this.contains(e))&&this._closeDropdown()}_handleKeydown(t){if(!this._isOpen)return;let e=lt(this)===this._searchInput;switch(t.key){case"Escape":t.preventDefault(),this._closeDropdown(),this._trigger?.focus();break;case"ArrowDown":t.preventDefault(),this._moveActive(1);break;case"ArrowUp":t.preventDefault(),this._moveActive(-1);break;case"Home":if(e)break;t.preventDefault(),this._setActive(0);break;case"End":if(e)break;t.preventDefault(),this._setActive(this._visibleOptions().length-1);break;case"Enter":{let s=this._visibleOptions()[this._activeIndex];s&&(t.preventDefault(),this._selectOption(s));break}}}_visibleOptions(){return Array.from(this.querySelectorAll("aparte-option")).filter(t=>!t.hasAttribute("disabled")&&t.style.display!=="none")}_moveActive(t){if(this._visibleOptions().length===0)return;let s=this._activeIndex<0?t>0?-1:0:this._activeIndex;this._setActive(s+t)}_activeHost(){return this._searchInput??this._trigger}_setExpanded(t){let e=String(t);this._trigger?.setAttribute("aria-expanded",e),this._searchInput?.setAttribute("aria-expanded",e)}_setActive(t){this.querySelectorAll("aparte-option").forEach(a=>a.removeAttribute("data-active"));let s=this._visibleOptions();if(s.length===0){this._activeIndex=-1,this._activeHost()?.removeAttribute("aria-activedescendant");return}let i=Math.max(0,Math.min(t,s.length-1));this._activeIndex=i;let r=s[i];r.id||(r.id=`aparte-option-${++n._optIdSeq}`),r.setAttribute("data-active",""),this._activeHost()?.setAttribute("aria-activedescendant",r.id),r.scrollIntoView?.({block:"nearest"})}_clearActive(){this._activeIndex=-1,this._activeHost()?.removeAttribute("aria-activedescendant"),this.querySelectorAll("aparte-option").forEach(t=>t.removeAttribute("data-active"))}_toggle(){this._isOpen?this._closeDropdown():this._openDropdown()}_openDropdown(){if(this._isOpen||this.hasAttribute("disabled"))return;this._isOpen=!0,this._dropdown?.removeAttribute("hidden"),this._setExpanded(!0),this.setAttribute("open",""),this._updatePosition(),this._searchInput?.focus();let e=this._visibleOptions().findIndex(s=>s.getAttribute("value")===this._value);this._setActive(e>=0?e:0),this.dispatchEvent(new CustomEvent("aparte-select-open",{bubbles:!0}))}_closeDropdown(){this._isOpen=!1,this._clearActive(),this._dropdown?.setAttribute("hidden",""),this._setExpanded(!1),this.removeAttribute("open"),this.removeAttribute("position"),this._dropdown&&(this._dropdown.style.top="",this._dropdown.style.bottom="",this._dropdown.style.left="",this._dropdown.style.width=""),this._searchInput&&(this._searchInput.value="",this._filterOptions("")),this.dispatchEvent(new CustomEvent("aparte-select-close",{bubbles:!0}))}_updatePosition(){if(!this._dropdown||!this._trigger)return;let t=this._trigger.getBoundingClientRect(),e=this._dropdown.offsetHeight||300,s=window.innerHeight,i=s-t.bottom,r=4;this._dropdown.style.left=`${t.left}px`,this._dropdown.style.width=`${t.width}px`,i<e&&t.top>e?(this._dropdown.style.top="",this._dropdown.style.bottom=`${s-t.top+r}px`,this.setAttribute("position","top")):(this._dropdown.style.top=`${t.bottom+r}px`,this._dropdown.style.bottom="",this.removeAttribute("position"))}_selectOption(t){let e=t.getAttribute("value")||t.textContent?.trim()||"",s=this._value;this._value=e,this.setAttribute("value",e),this._updateTriggerLabel(),this._closeDropdown(),this._emitChange(s),this._trigger?.focus()}_updateNames(){let t=this.getAttribute("placeholder")||"Select...",e=this.getAttribute("aria-label")||t,s=this.querySelector(".aparte-select-options");s&&s.getAttribute("aria-label")!==e&&s.setAttribute("aria-label",e);let i=this._trigger;if(!i)return;let r=this._getSelectedLabel()||t,a=i.getAttribute("role")==="button"&&r!==e?`${e}: ${r}`:e;i.getAttribute("aria-label")!==a&&i.setAttribute("aria-label",a)}_applyDisabled(){let t=this._trigger;if(!t)return;let e=this.hasAttribute("disabled");t.setAttribute("tabindex",e?"-1":"0"),e?(t.setAttribute("aria-disabled","true"),this._isOpen&&this._closeDropdown()):t.removeAttribute("aria-disabled")}_updateTriggerLabel(){let t=this.getAttribute("placeholder")||"Select...",e=this._trigger?.querySelector(".aparte-select-label-text");if(e){let r=this._getSelectedLabel()||t;e.textContent!==r&&(e.textContent=r)}let s=this._trigger?.querySelector(".aparte-select-label-sizer");if(s){let r=[t,...Array.from(this.querySelectorAll("aparte-option"),o=>Sa(o))],a=Array.from(s.children,o=>o.textContent??"");(r.length!==a.length||r.some((o,l)=>o!==a[l]))&&s.replaceChildren(...r.map(o=>{let l=document.createElement("span");return l.textContent=o,l}))}this._updateNames(),this.querySelectorAll("aparte-option").forEach(r=>{r.getAttribute("value")===this._value?r.setAttribute("selected",""):r.removeAttribute("selected")})}_getSelectedLabel(){for(let t of this.querySelectorAll("aparte-option"))if(t.getAttribute("value")===this._value)return Sa(t);return""}_filterOptions(t){this.querySelectorAll("aparte-option").forEach(s=>{let r=(s.textContent?.toLowerCase()||"").includes(t);s.style.display=r?"":"none"}),this._isOpen&&this._setActive(0)}_emitChange(t){let e={value:this._value,label:this._getSelectedLabel(),previousValue:t};this.dispatchEvent(new CustomEvent("aparte-select-change",{bubbles:!0,composed:!0,detail:e}))}};function Sa(n){let t="";for(let e of n.childNodes)e.nodeType===Node.ELEMENT_NODE&&e.matches(".aparte-option__meta, .aparte-status-dot")||(t+=e.textContent??"");return t.trim()}H(We);customElements.get("aparte-select")||customElements.define("aparte-select",We);var Ue=class extends HTMLElement{static get observedAttributes(){return["value"]}_r=9;get _circ(){return 2*Math.PI*this._r}connectedCallback(){this._render()}attributeChangedCallback(){this._render()}_render(){let t=this.getAttribute("value"),e=t!==null?Math.min(100,Math.max(0,parseFloat(t)||0)):null;this.setAttribute("role","progressbar"),this.setAttribute("aria-valuemin","0"),this.setAttribute("aria-valuemax","100"),e!==null?this.setAttribute("aria-valuenow",String(e)):this.removeAttribute("aria-valuenow");let s=e!==null?this._circ*(1-e/100):0,i=e!==null?`${this._circ.toFixed(2)}`:`${(this._circ*.72).toFixed(2)} ${(this._circ*.28).toFixed(2)}`;this.innerHTML=`<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><circle class="aparte-spinner-track" cx="12" cy="12" r="${this._r}"/><circle class="aparte-spinner-fill" cx="12" cy="12" r="${this._r}" stroke-dasharray="${i}" stroke-dashoffset="${s.toFixed(2)}"/></svg>`}};H(Ue);customElements.get("aparte-progress-spinner")||customElements.define("aparte-progress-spinner",Ue);var je=class extends HTMLElement{static get observedAttributes(){return["name"]}_unsubscribe=null;connectedCallback(){this._render(),this._unsubscribe=gt(this,()=>this._render())}disconnectedCallback(){this._unsubscribe?.(),this._unsubscribe=null}attributeChangedCallback(){this.isConnected&&this._render()}_render(){let t=this.getAttribute("name"),e=t?T(this).getIcon(t):null;this.innerHTML=e??"",this.firstElementChild?.setAttribute("aria-hidden","true")}};H(je);customElements.get("aparte-icon")||customElements.define("aparte-icon",je);function Aa(n){let t=n.activeElement;for(;t?.shadowRoot?.activeElement;)t=t.shadowRoot.activeElement;return t}function Cn(n,t){for(let e=n;e;e=e.parentNode??(e instanceof ShadowRoot?e.host:null))if(e===t)return!0;return!1}function Ca(n,t,e,s,i){let r=document.createElement("button");r.type="button",r.className="aparte-btn aparte-btn--icon aparte-btn--sm aparte-btn--ghost aparte-elic-hide",r.setAttribute("aria-expanded","true"),r.innerHTML=e.getIcon("expand");let a=document.createElement("button");a.type="button",a.className="aparte-btn aparte-btn--ghost aparte-elic-reveal",a.setAttribute("aria-expanded","false");let o=document.createElement("span");a.append(o),a.insertAdjacentHTML("beforeend",e.getIcon("collapse"));let l=c=>{let d=c.t("elicitationHide");r.setAttribute("aria-label",d),r.title=d,o.textContent=c.t("elicitationWaiting")};return l(e),r.addEventListener("click",()=>{n.setAttribute("data-collapsed",""),i(),a.focus()}),a.addEventListener("click",()=>{n.removeAttribute("data-collapsed"),i(),s()}),t.prepend(r),n.append(a),{relabel:l}}var Ge=class extends HTMLElement{_pending=null;_onTurnEnd=t=>{let e=t.detail?.targetId,s=this._pendingTargetId();e&&s&&e!==s||this._cancelPending()};_unsubscribeConfig=null;connectedCallback(){this.style.display="none",this._unsubscribeConfig=gt(this,()=>this._relabelPending()),T(this).setElicitationPresenter(this._present,this),window.addEventListener("aparte-message-aborted",this._onTurnEnd),window.addEventListener("aparte-message-error",this._onTurnEnd)}aparteConfigChanged(t,e){e.removeElicitationPresenter(this._present),t.setElicitationPresenter(this._present,this)}disconnectedCallback(){T(this).removeElicitationPresenter(this._present),window.removeEventListener("aparte-message-aborted",this._onTurnEnd),window.removeEventListener("aparte-message-error",this._onTurnEnd),this._unsubscribeConfig?.(),this._unsubscribeConfig=null,this._cancelPending()}_relabelPending(){if(!this._pending)return;let t=T(this);j(t,()=>this._pending.relabel())}_present=t=>{let e=this._getComposer();return e?new Promise((s,i)=>{let r=!1,a={},o=Aa(document),l=()=>{let C=t.message;return String(typeof C=="function"?C():C??"")},c="aparte-chat, [data-aparte-chat], [data-aparte-host]",d='input, textarea, select, [contenteditable]:not([contenteditable="false"])',u=e.closest(c)??e.parentElement??e,h=!(o instanceof HTMLElement)||o===document.body,p=h?null:o,f=p!==null&&Cn(p,u),g=p!==null&&p.matches(d),_=p!==null&&!f&&(g||p.tagName==="IFRAME"||p.closest(c)!==null),S=C=>{let P=e.querySelector(":scope > .aparte-elic-status");P||(P=document.createElement("span"),P.className="aparte-sr-only aparte-elic-status",P.setAttribute("role","status"),e.appendChild(P));let $=P;$.textContent="",C&&setTimeout(()=>{$.isConnected&&($.textContent=C)},60)},E=(C,P)=>{if(_){S(P);return}let $=window.scrollX,F=window.scrollY;g&&f?(C.el.hasAttribute("tabindex")||C.el.setAttribute("tabindex","-1"),C.el.hasAttribute("role")||C.el.setAttribute("role","group"),P&&!C.el.hasAttribute("aria-label")&&C.el.setAttribute("aria-label",P),C.el.focus()):C.focus(),h&&(window.scrollX!==$||window.scrollY!==F)&&window.scrollTo($,F)},I=()=>{if(r)return!1;r=!0,this._pending=null;let C=Aa(document),P=C instanceof Node&&Cn(C,e);return e.hidePanel(a.token),S(""),P&&((!_&&p!==null&&p.isConnected&&!Cn(p,e)?p:null)??e).focus(),!0},b=C=>{I()&&s(C)},y=(C="aborted")=>{I()&&i(new pt(C))};if(t.signal){if(t.signal.aborted){y();return}t.signal.addEventListener("abort",()=>y(),{once:!0})}let m=T(this);if(t.kind==="approval"){let C=()=>F.isComplete()&&!F.el.hasAttribute("data-collapsed"),P=()=>C()?"submit":"none",$=()=>e.setPanelSubmitEnabled(C(),P()),F=j(m,()=>ma(t.message,t.options??[],$,t.details,t.allowOther??!0));F.onSettle(Y=>b({action:"accept",content:Y}));let V=Ca(F.el,F.dismiss,m,()=>F.focus(),$);this._pending={abort:()=>y(),composer:e,relabel:()=>{F.relabel(),V.relabel(T(this))}},a.token=e.showPanel(F.el,{submitEnabled:F.isComplete(),mode:P(),onSubmit:()=>{F.isComplete()&&b({action:"accept",content:F.getContent()})},onEvict:()=>y()}),E(F,l());return}let w=t.schema??{type:"string"},M=()=>{let C=v.el.hasAttribute("data-collapsed");e.setPanelSubmitEnabled(!C&&v.canProceed(),C?"none":v.mode())},v=j(m,()=>_a(t.message,w,M)),A=document.createElement("button");A.type="button",A.className="aparte-btn aparte-elic-skip",A.textContent=m.t("elicitationSkip"),A.addEventListener("click",()=>b({action:"decline"})),v.dismiss.appendChild(A);let R=Ca(v.el,v.dismiss,m,()=>v.focus(),M);v.onSettle(C=>b({action:"accept",content:C})),this._pending={abort:()=>y(),composer:e,relabel:()=>{v.relabel();let C=T(this);A.textContent=C.t("elicitationSkip"),R.relabel(C)}},a.token=e.showPanel(v.el,{submitEnabled:v.canProceed(),mode:v.mode(),onEvict:()=>y(),onSubmit:()=>{v.isComplete()&&b({action:"accept",content:v.getContent()})}}),E(v,l())}):Promise.reject(new pt("no-presenter"))};_cancelPending(){this._pending?.abort()}_pendingTargetId(){let t=this._pending?.composer??null;for(;t;){if((t.tagName?.toLowerCase()==="aparte-chat"||t.hasAttribute?.("data-aparte-chat"))&&t.id)return t.id;t=t.parentElement}}_getComposer(){let t=this.parentElement;for(;t;){let e=t.querySelector("aparte-composer");if(e&&typeof e.showPanel=="function")return e;if(t.tagName?.toLowerCase()==="aparte-chat"||t.hasAttribute?.("data-aparte-chat"))break;t=t.parentElement}return console.warn("[aparte-elicitation] No <aparte-composer> in this element's subtree, so the request could not be shown, so it REJECTED and the turn halted. Nothing was told to the model \u2014 there is nothing true to tell it. Move <aparte-elicitation> inside the <aparte-chat> it belongs to. It is deliberately NOT borrowing another chat's composer: on a page with two chats that put the question under the wrong one."),null}};typeof customElements<"u"&&!customElements.get("aparte-elicitation")&&(H(Ge),customElements.define("aparte-elicitation",Ge));function za(n){return!n.hasAttribute("loading")&&!n.querySelector("aparte-chat-bubble")}var ze=class extends HTMLElement{static get observedAttributes(){return["placeholder","disabled","submit-on-enter","attachments"]}_observer=null;_loadingObserver=null;_offGlide=null;_childObserver=null;_gated=!1;_gateOwns=!1;_ownsShell=!1;connectedCallback(){this._render(),this._forwardAttr("placeholder"),this._forwardAttr("disabled"),this._forwardAttr("submit-on-enter"),this._syncEmptyWatch(),this._syncLoadingWatch(),this._watchForViewport(),this._offGlide?.(),this._offGlide=aa(this)}disconnectedCallback(){this._offGlide?.(),this._offGlide=null,this._observer?.disconnect(),this._observer=null,this._loadingObserver?.disconnect(),this._loadingObserver=null,this._childObserver?.disconnect(),this._childObserver=null}attributeChangedCallback(t,e,s){if(e===s)return;if(t==="attachments"){this._syncAttachments();return}if(t==="disabled"&&s===null&&this._gated){this._gateOwns=!0;return}let i=this.querySelector("aparte-composer");i&&(s!==null?i.setAttribute(t,s):i.removeAttribute(t))}get viewport(){return this.querySelector("aparte-chat-viewport")}get composer(){return this.querySelector("aparte-composer")}_render(){if(this.hasAttribute("framework-managed")||this.querySelector("aparte-chat-viewport"))return;let t=this.getAttribute("placeholder"),e=(t!==null?` placeholder="${x(t)}"`:"")+(this.hasAttribute("disabled")?" disabled":""),s=this.hasAttribute("attachments");this.innerHTML=`
|
|
74
|
+
<aparte-chat-viewport></aparte-chat-viewport>
|
|
75
|
+
<aparte-elicitation></aparte-elicitation>
|
|
76
|
+
<aparte-composer${e}>
|
|
77
|
+
<div class="aparte-composer-shell">
|
|
78
|
+
${s?"<aparte-composer-attachments></aparte-composer-attachments>":""}
|
|
79
|
+
<div class="aparte-composer-row">
|
|
80
|
+
${s?"<aparte-composer-add-attachment></aparte-composer-add-attachment>":""}
|
|
81
|
+
<aparte-composer-input></aparte-composer-input>
|
|
82
|
+
<aparte-composer-send></aparte-composer-send>
|
|
83
|
+
</div>
|
|
84
|
+
</div>
|
|
85
|
+
</aparte-composer>
|
|
86
|
+
`,this._ownsShell=!0}_syncAttachments(){if(!this._ownsShell)return;let t=this.composer,e=t?.querySelector(".aparte-composer-shell"),s=e?.querySelector(".aparte-composer-row");if(!t||!e||!s)return;let i=e.querySelector("aparte-composer-attachments"),r=s.querySelector("aparte-composer-add-attachment");if(this.hasAttribute("attachments")){i||e.insertBefore(document.createElement("aparte-composer-attachments"),s),r||s.insertBefore(document.createElement("aparte-composer-add-attachment"),s.firstChild);return}i?.remove(),r?.remove(),t.clearAttachments()}_forwardAttr(t){this.hasAttribute(t)&&this.querySelector("aparte-composer")?.setAttribute(t,this.getAttribute(t)??"")}_syncEmptyWatch(){this._observer?.disconnect(),this._observer=null;let t=this.querySelector("aparte-chat-viewport");t&&(this._updateEmpty(),this._observer=new MutationObserver(()=>this._updateEmpty()),this._observer.observe(t,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["loading"]}))}_syncLoadingWatch(){this._loadingObserver?.disconnect(),this._loadingObserver=null;let t=this.querySelector("aparte-chat-viewport");t&&(this._applyLoadingGate(),this._loadingObserver=new MutationObserver(()=>this._applyLoadingGate()),this._loadingObserver.observe(t,{attributes:!0,attributeFilter:["loading"]}))}_watchForViewport(){this._childObserver?.disconnect(),this._childObserver=null,!this.querySelector("aparte-chat-viewport")&&(this._childObserver=new MutationObserver(()=>{this.querySelector("aparte-chat-viewport")&&(this._childObserver?.disconnect(),this._childObserver=null,this._syncEmptyWatch(),this._syncLoadingWatch())}),this._childObserver.observe(this,{childList:!0,subtree:!0}))}_applyLoadingGate(){let t=this.querySelector("aparte-composer"),e=this.querySelector("aparte-chat-viewport")?.hasAttribute("loading")??!1;t&&(e&&!this._gated?(this._gated=!0,this._gateOwns=!t.hasAttribute("disabled"),t.setAttribute("disabled","")):!e&&this._gated&&(this._gated=!1,this._gateOwns&&!this.hasAttribute("disabled")&&t.removeAttribute("disabled"),this._gateOwns=!1))}_updateEmpty(){let t=this.querySelector("aparte-chat-viewport");this.toggleAttribute("data-empty",!t||za(t))}};H(ze);customElements.get("aparte-chat")||customElements.define("aparte-chat",ze);function Td(n,t,e){let s="other";try{s=new Intl.PluralRules(e).select(t)}catch{}let i=n.split("|"),r=o=>i.find(l=>l.startsWith(`${o}:`)),a=r(s)??r("other")??n;return a.slice(a.indexOf(":")+1).replace("{n}",String(t))}function Md(n,t){let e=[],s=-1,i=-1,r=0,a=()=>{r>=2&&e.push({from:s,to:i}),s=-1,i=-1,r=0};return n.forEach((o,l)=>{let c=t(o);c==="stop"?a():c==="fold"&&(s<0&&(s=l),i=l,r+=1)}),a(),e}function He(n,t){let e=`[data-segment-id="${K(t)}"]`;return n.querySelector(`:scope > ${e}, :scope > .aparte-turn > .aparte-turn__body > ${e}`)}function xd(n){let t=1/0,e=-1/0;for(let s of n){let{startedAt:i,endedAt:r}=Jt(s)??{};if(i==null||r==null)return;t=Math.min(t,i),e=Math.max(e,r)}return n.length>0?e-t:void 0}var Id=(n,t)=>t?n.split(t).length-1:0;function Ld(n,t){let e=n.createElement("span");e.className="aparte-tag aparte-inline-token",t.kind&&(e.dataset.kind=t.kind);let s=n.createElement("span");return s.className="aparte-tag__label",s.textContent=t.label,e.appendChild(s),e}function Rd(n,t,e){let s=Id(t.slice(0,e.start),e.text),i=n.ownerDocument,r=i.createTreeWalker(n,NodeFilter.SHOW_TEXT);for(;r.nextNode();){let a=r.currentNode;for(let o=a.data.indexOf(e.text);o>=0;o=a.data.indexOf(e.text,o+e.text.length)){if(s-- >0)continue;let l=i.createRange();l.setStart(a,o),l.setEnd(a,o+e.text.length),l.deleteContents(),l.insertNode(Ld(i,e));return}}}function Od(n,t,e){if(!n.querySelector(".aparte-inline-token"))for(let s of[...e].sort((i,r)=>r.start-i.start))s.text&&Rd(n,t,s)}function Ea(n,t,e){let s=document.createElement("button");return s.type="button",s.className=`aparte-btn aparte-btn--sm ${t}`,s.textContent=n,s.addEventListener("click",e),s}function Pd(n){let t=document.createElement("div");t.className="aparte-feedback-reasons",t.setAttribute("role","group"),t.setAttribute("aria-label",n.title);let e=document.createElement("span");e.textContent=n.title,t.appendChild(e);for(let s of n.reasons)t.appendChild(Ea(s,"aparte-btn--surface",()=>n.onPick(s)));return t.appendChild(Ea(n.dismiss,"aparte-btn--ghost",n.onClose)),t}var ka=n=>!!n&&typeof n.getMessages=="function"&&typeof n.updateMessage=="function";function Nd(n){let t=st(n);if(ka(t))return t;let e=n.closest("aparte-chat-viewport");return ka(e)?e:null}function Dd(n,t){let e=Nd(n);if(!e)return 0;let s=e.getMessages().filter(r=>r.contextSummary!==void 0).map(r=>r.id);for(let r of s)e.updateMessage(r,{contextSummary:void 0});let i={restored:!0};return t.messageId&&(i.messageId=t.messageId),t.targetId&&(i.targetId=t.targetId),window.dispatchEvent(new CustomEvent("aparte-compact-done",{detail:i})),s.length}function ct(n,t,e){let s=document.createElement(n);return s.className=t,e!==void 0&&(s.textContent=e),s}function Zt(n,t){let e=ct("button","aparte-btn aparte-btn--ghost aparte-btn--sm aparte-checkpoint__action",t);return e.type="button",e.setAttribute("data-checkpoint-action",n),e}function Bd(n){let{kind:t,locale:e}=n,s=ct("div","aparte-checkpoint");s.setAttribute("role","group"),s.setAttribute("aria-label",e.checkpointGroup??"Context summary"),s.setAttribute("data-state",t);let i=ct("div","aparte-checkpoint__row aparte-divider aparte-divider--label"),r=ct("div","aparte-checkpoint__label");i.appendChild(r),s.appendChild(i);let a;if(t==="done"){let l=n.count??0;a=l===1?e.checkpointCountOne??"1 message summarised for the model":(e.checkpointCount??"{n} messages summarised for the model").replace("{n}",()=>String(l))}else t==="legacy"?a=e.checkpointLegacy??"Earlier messages were summarised":t==="pending"?a=e.checkpointPending??"Summarising the context\u2026":a=e.checkpointFailed??"Couldn't summarise the context";let o=ct("span","aparte-checkpoint__text",a);if(t==="pending"?(o.classList.add("aparte-shimmer"),o.setAttribute("role","status")):t==="failed"&&(o.setAttribute("role","status"),n.reason&&(o.title=n.reason,o.appendChild(ct("span","aparte-sr-only",`: ${n.reason}`)))),r.appendChild(o),t==="done"||t==="legacy")if(n.confirming&&t==="done"){let l=ct("span","aparte-checkpoint__confirm"),c=ct("span","aparte-checkpoint__question",e.checkpointRestoreConfirm??"Send the original messages to the model again?");c.id=`${n.summaryId}-question`;let d=Zt("restore-confirm",e.checkpointRestore??"Restore");d.setAttribute("aria-describedby",c.id),l.append(c,d,Zt("restore-cancel",e.cancel??"Cancel")),r.appendChild(l)}else{let l=Zt("toggle",n.open?e.checkpointHide??"Hide summary":e.checkpointShow??"Show summary");l.setAttribute("aria-expanded",String(n.open)),l.setAttribute("aria-controls",n.summaryId),r.appendChild(l),t==="done"&&r.appendChild(Zt("restore",e.checkpointRestore??"Restore"))}else t==="failed"&&r.appendChild(Zt("retry",e.retry??"Retry"));if(t==="done"||t==="legacy"){let l=ct("div","aparte-checkpoint__summary aparte-segment-content");l.id=n.summaryId,n.open||(l.hidden=!0),s.appendChild(l)}return s}var Ta=!1;function Hd(n){Ta||(Ta=!0,console.warn(`[aparte] No renderer for segment "${n}". Register one with registerSegmentRenderer({ type: '${n}', render }) from @aparte/core \u2014 see https://apartejs.dev/guides/customization/#custom-segment-types`))}function En(n){let t=typeof n.fallback=="string"&&n.fallback.trim()?n.fallback:null;t||Hd(n.type);let e=document.createElement("div");return e.className=t?"aparte-segment aparte-segment-fallback":"aparte-segment aparte-segment-unknown",e.textContent=t??`[Unknown segment type: ${n.type}]`,e}function Ct(n,t){let e=un(n,t);return e||(Fr(t),un(n,t))}function te(n,t){let e;if(n instanceof HTMLElement)e=n;else{let s=document.createElement("div");s.innerHTML=n,e=s.firstElementChild}return e&&t&&!e.hasAttribute("data-segment-id")&&e.setAttribute("data-segment-id",t.id),e}var ne=new Map;function $d(){let n=[...ne].filter(([e])=>!e.firstChild);ne.clear();let t=n.map(([,{bubble:e,role:s}])=>{let i=getComputedStyle(e).getPropertyValue(`--aparte-avatar-image-${s}`).trim();return i!==""&&i!=="none"});n.forEach(([e],s)=>e.toggleAttribute("data-image",t[s]))}var qd=0,Ke=class extends HTMLElement{_contentEl=null;_segmentsEl=null;_attachmentsEl=null;_actionBarEl=null;_branchPickerEl=null;_footerEl=null;_content="";_tokens;_streaming=!1;_segments=[];_role="assistant";_attachments=[];_usage=null;_finishReason=null;_contextSummary=null;_legacyCompaction=null;_checkpointOpen=!1;_confirmingRestore=!1;_checkpointDrawn="";_checkpointId=`aparte-checkpoint-${++qd}`;_avatarCleanup=null;_avatarFromProvider=!1;_siblingCount=1;_wroteRootLabel=!1;_wroteBarLabel=!1;_wroteArrowLabels=!1;_drawnShell=null;_siblingIndex=0;_editing=!1;_editInput=null;_editReturnAction=null;static get observedAttributes(){return["data-role","content","timestamp","message-id","streaming","name","data-checkpoint","data-checkpoint-reason"]}constructor(){super()}_onConfigChange=t=>{let e=t.detail;e?.config&&e.config!==this._cfg||(this._updateActionBar(),this._updateName(),this._updateLocalizedLabels(),this._updateWaiting(),this._updateFinishNote(),this._checkpointDrawn="",this._updateCheckpoint(),this._renderAvatar(),this._redrawSegmentsWhoseRendererChanged(),this._relabelSegments(),j(this._cfg,()=>ar(this)),mr(this),this._syncSources(),this._updateTimestamp(this.getAttribute("timestamp")),this._redrawQueued||(this._redrawQueued=!0,queueMicrotask(()=>{this._redrawQueued=!1,this.isConnected&&this._redrawIfStale()})))};_redrawQueued=!1;_drawnWithVersion=0;_drawn=new Map;_written=new Set;_releasedWhileDetached=!1;_releaseCheckQueued=!1;_offRenderers=null;_toolRendererFor(t){if(t.type!=="tool_call")return null;let e=this._cfg;if(Ct("tool_call",e)!==xt)return null;let s=t.toolCall?.name;return!s||e.isToolHidden(s)?null:e.getToolRenderer(s)??null}_install(t,e,s,i=t){let r=this._drawn.get(t.id);r&&r.el!==e&&this._release(t.id);let a={el:e,renderer:s,tool:null,segment:t};this._drawn.set(t.id,a),this.isConnected||this._scheduleReleaseCheck(),s?.setup&&j(this._cfg,()=>s.setup(e,i)),t.type==="tool_call"&&(a.tool=dn(e))}_drawnAs(t,e=!1){return t.type!=="text"&&t.type!=="thinking"?t:t.isStreaming===!0?(this._written.add(t.id),t):!e||t.isStreaming===!1||!this._streaming?t:(this._written.add(t.id),{...t,isStreaming:!0})}_release(t){let e=this._drawn.get(t);if(!e)return;this._drawn.delete(t);let s=e.renderer?.cleanup;if(s)try{j(this._cfg,()=>s.call(e.renderer,e.el,e.segment))}catch(i){console.error("[aparte] a segment renderer's cleanup threw",i)}}_releaseAll(){for(let t of[...this._drawn.keys()])this._release(t)}_scheduleReleaseCheck(){this._releaseCheckQueued||(this._releaseCheckQueued=!0,queueMicrotask(()=>{this._releaseCheckQueued=!1,!(this.isConnected||this._drawn.size===0)&&(this._releaseAll(),this._releasedWhileDetached=!0)}))}_redrawSegment(t){let e=this._drawn.get(t.id);if(!e)return!1;let s=this._cfg,i=Ct(t.type,s),r=e.el;this._release(t.id);let a=i?this._drawnAs(t):t,o=i?te(j(s,()=>i.render(t)),t):En(t);return o?(r.replaceWith(o),this._install(t,o,i,a),!0):(r.remove(),!0)}_stillDrawnByCurrent(t,e){return Ct(t.type,this._cfg)===e.renderer&&this._toolRendererFor(t)===e.tool}_redrawSegmentsWhoseRendererChanged(){if(!(!this.isConnected||!this._segmentsEl||this._drawn.size===0)){for(let t of this._segments){let e=this._drawn.get(t.id);!e||this._stillDrawnByCurrent(t,e)||this._redrawSegment(t)}this._syncTurns()}}_onRenderersChange=t=>{t!==this._cfg&&t!==Q||this._redrawSegmentsWhoseRendererChanged()};_keepsItsDrawing(t,e){return(_n(e.renderer)||t.type==="tool_call"&&_n(e.tool))&&this._stillDrawnByCurrent(t,e)}_redrawIfStale(){if(!(this._streaming||this._editing||Z(this._cfg)===this._drawnWithVersion)){if(this._segments.length===0){this._updateContent();return}if(this._segments.some(t=>!this._drawn.has(t.id))){this._renderSegments();return}this._drawnWithVersion=Z(this._cfg);for(let t of this._segments){let e=this._drawn.get(t.id);this._keepsItsDrawing(t,e)||this._redrawSegment(t)}this._syncTurns(),this._reflectError(),this._syncCopyAction()}}_relabelSegments(){if(this._segmentsEl){for(let t of this._segments){let e=Ct(t.type,this._cfg);if(!e?.relabel)continue;let s=He(this._segmentsEl,t.id);s&&j(this._cfg,()=>e.relabel(s,t))}this._syncTurns()}}_updateLocalizedLabels(){let t=this._cfg.getLocale(),e=(s,i)=>{this.querySelector(s)?.setAttribute("aria-label",i)};this._wroteArrowLabels&&(e(".aparte-branch-prev",t.previousResponse??"Previous response"),e(".aparte-branch-next",t.nextResponse??"Next response")),this._wroteBarLabel&&e(".aparte-action-bar",t.messageActions??"Message actions")}get _cfg(){return T(this)}connectedCallback(){this._render(),this._updateContent(),this._updateTimestamp(this.getAttribute("timestamp")),this._releasedWhileDetached&&(this._releasedWhileDetached=!1,this._segments.length>0&&this._renderSegments()),window.addEventListener("aparte-config-change",this._onConfigChange),this._offRenderers??=ta(this._onRenderersChange),this.addEventListener("click",this._onBranchPickerClick),this.addEventListener("click",this._onLinkClick),this.addEventListener("click",this._onCheckpointClick),this.addEventListener("keydown",this._onCheckpointKeydown)}aparteConfigChanged(){queueMicrotask(()=>{this._redrawFrameIfChanged(),this._redrawSegmentsWhoseRendererChanged()})}_redrawFrameIfChanged(){if(!(!this.isConnected||this._editing)&&(this._cfg.getBubbleShellRenderer?.()??null)!==this._drawnShell){if(this._avatarCleanup){try{this._avatarCleanup()}catch{}this._avatarCleanup=null}this._resetMarkdownStream(),this._releaseAll(),this.replaceChildren(),this._render(),this._updateContent(),this._segments.length>0&&this._renderSegments(),this._updateAttachments(),this._updateTimestamp(this.getAttribute("timestamp")),this._updateBranchPicker(),this._updateCheckpoint()}}disconnectedCallback(){if(window.removeEventListener("aparte-config-change",this._onConfigChange),this._offRenderers?.(),this._offRenderers=null,this.removeEventListener("click",this._onBranchPickerClick),this.removeEventListener("click",this._onLinkClick),this.removeEventListener("click",this._onCheckpointClick),this.removeEventListener("keydown",this._onCheckpointKeydown),this._avatarCleanup){try{this._avatarCleanup()}catch{}this._avatarCleanup=null}this._scheduleReleaseCheck()}attributeChangedCallback(t,e,s){if(e!==s)switch(t){case"data-role":(s==="user"||s==="assistant")&&(this._role=s,this._updateRole());break;case"content":this._content=s||"",this._resetMarkdownStream(),this._updateContent();break;case"timestamp":this._updateTimestamp(s);break;case"data-checkpoint":this._updateCheckpoint();break;case"data-checkpoint-reason":this.getAttribute("data-checkpoint")==="failed"&&this._updateCheckpoint();break;case"streaming":this._updateStreaming(s!==null&&s!=="false");break;case"name":this._updateName();break}}appendToken(t){this._content+=t,this._updateContent(),this._syncCopyAction()}_askFeedbackReason(t){let e=this._cfg.getBubbleActions().feedbackReasons;if(!e?.length||this.querySelector(".aparte-feedback-reasons"))return;let s=Pd({reasons:e,title:this._cfg.t("feedbackReasonTitle"),dismiss:this._cfg.t("feedbackReasonDismiss"),onPick:i=>{s.remove(),this.dispatchEvent(new CustomEvent("aparte-feedback-reason",{bubbles:!0,composed:!0,detail:{messageId:t,reason:i}}))},onClose:()=>s.remove()});this.querySelector(".aparte-footer")?.after(s)}setTokens(t){this._tokens=t,this._drawTokens()}_drawTokens(){this._contentEl&&this._role==="user"&&this._tokens?.length&&Od(this._contentEl,this._content,this._tokens)}setContent(t){this._content=t,this.setAttribute("content",t),this._resetMarkdownStream(),this._updateContent(),this._syncCopyAction()}_resetMarkdownStream(){let t=this;t._aparteSmd&&t._aparteSmd.renderer.end(),t._aparteSmd=void 0}getContent(){return this._content}setSegments(t){this._replaceSegments(t),this._syncSources(),this._updateWaiting()}_syncSources(){let t=this._segmentsEl,e=t?.parentElement;if(!t||!e)return;let s=this._segments.flatMap(i=>i.type==="text"?i.sources??[]:[]);Sr(e,t,s,this._cfg)}_replaceSegments(t){let e=[...t];if(this._resyncKeepingCards(e)){this._syncSources();return}this._segments=e,this._renderSegments()}_resyncKeepingCards(t){if(!this._segmentsEl||t.length!==this._segments.length||t.some((s,i)=>s.id!==this._segments[i].id||!this._drawn.has(s.id)))return!1;let e=new Set(t.filter(s=>this._keepsItsDrawing(s,this._drawn.get(s.id))).map(s=>s.id));if(e.size===0)return!1;this._segments=t,this._drawnWithVersion=Z(this._cfg);for(let s of t)e.has(s.id)?this._applySegmentUpdate(s.id,s,s):this._redrawSegment(s);return this._syncTurns(),this._reflectError(),this._syncCopyAction(),!0}addSegment(t){this._segments.push(t),this._appendSegmentEl(t),this._syncTurns(),t.type==="text"&&t.sources&&this._syncSources(),this._updateWaiting()}updateSegment(t,e){let s=this._segments.findIndex(i=>i.id===t);if(s!==-1){let i=Qs(this._segments[s],e);this._segments[s]=i,i.isStreaming===!1?this._written.delete(t):"content"in e&&this._written.add(t),this._applySegmentUpdate(t,i,e),"sources"in e&&this._syncSources(),this._syncCopyAction(),("status"in e||"isStreaming"in e)&&(this._syncTurns(),this._updateWaiting())}}appendToSegment(t,e){let s=this._segments.find(i=>i.id===t);s&&"content"in s&&(s.content+=e,s.isStreaming!==!1&&this._written.add(t),this._applySegmentUpdate(t,s,{content:s.content}),this._syncCopyAction())}_settleWrittenSegments(){for(let t of this._written){let e=this._segments.findIndex(r=>r.id===t),s=this._segments[e];if(!s||s.isStreaming===!1)continue;let i={...s,isStreaming:!1};this._segments[e]=i,this._applySegmentUpdate(t,i,{isStreaming:!1})}this._written.clear()}getSegments(){return[...this._segments]}removeSegment(t){let e=this._segments.findIndex(i=>i.id===t);e!==-1&&this._segments.splice(e,1),this._release(t),(this._segmentsEl?He(this._segmentsEl,t):null)?.remove(),this._syncTurns(),this._syncSources(),this._updateWaiting(),this._syncCopyAction()}setAttachments(t){this._attachments=t,this._updateAttachments(),this._updateWaiting()}setUsage(t){this._usage=t??null,this._updateActionBar()}setFinishReason(t){this._finishReason=t??null,this._updateFinishNote()}setContextSummary(t,e){this._contextSummary=t??null,e?.legacy!==void 0&&(this._legacyCompaction=e.legacy),this._contextSummary||(this._confirmingRestore=!1,this._isLegacyCompaction()||(this._checkpointOpen=!1)),this._updateCheckpoint()}setSiblings(t,e){this._siblingCount=t,this._siblingIndex=e,this._updateBranchPicker()}updateMessage(t){if("role"in t&&(this._role=t.role,this._updateRole()),"tokens"in t&&(this._tokens=t.tokens),"content"in t&&(this._content=t.content,this._updateContent()),"segments"in t&&this._replaceSegments(t.segments),"timestamp"in t&&this._updateTimestamp(t.timestamp),"status"in t){let e=t.status==="streaming"||t.status==="pending";this._updateStreaming(e)}"attachments"in t&&(this._attachments=t.attachments??[],this._updateAttachments(),this._updateWaiting()),"finishReason"in t&&this.setFinishReason(t.finishReason),("contextSummary"in t||"compaction"in t)&&this.setContextSummary("contextSummary"in t?t.contextSummary:this._contextSummary,"compaction"in t?{legacy:t.compaction===!0}:void 0)}_updateFinishNote(){let t=this._finishReason==="length"&&!this._streaming&&this._role!=="user",e=this.querySelector(".aparte-finish-note");if(!t){e?.remove();return}if(!e){let s=this.querySelector(".aparte-message-content");if(!s)return;e=document.createElement("div"),e.className="aparte-finish-note",s.after(e)}e.textContent=this._cfg.getLocale().responseCutOff??"Cut off at the model's length limit."}_isLegacyCompaction(){return this._legacyCompaction??this.getAttribute("data-kind")==="compaction"}_checkpointKind(){let t=this.getAttribute("data-checkpoint");return t==="pending"||t==="failed"?t:this._contextSummary?"done":this._isLegacyCompaction()?"legacy":null}_checkpointSummaryText(){return this._contextSummary?this._contextSummary.summary:this._content}_updateCheckpoint(t){let e=this.querySelector(".aparte-message");if(!e)return;let s=this._checkpointKind();e.toggleAttribute("data-superseded",this._isLegacyCompaction()&&!this._contextSummary);let i=this.querySelector(":scope > .aparte-checkpoint");if(!s){let h=i&&document.activeElement&&i.contains(document.activeElement);i?.remove(),this._checkpointDrawn="",h&&(e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1"),e.focus({preventScroll:!0}));return}let r=this.getAttribute("data-checkpoint-reason")??"",a=this._checkpointSummaryText(),o=JSON.stringify([s,this._contextSummary?.count,this._contextSummary?.createdAt,r,this._checkpointOpen,this._confirmingRestore,this._checkpointOpen?a:""]);if(i&&!t&&o===this._checkpointDrawn)return;let l=document.activeElement,c=i&&l&&i.contains(l)?l.getAttribute("data-checkpoint-action"):null,d=Bd({kind:s,count:this._contextSummary?.count,reason:r,open:this._checkpointOpen,confirming:this._confirmingRestore,summaryId:this._checkpointId,locale:this._cfg.getLocale()});if(this._checkpointOpen&&(s==="done"||s==="legacy")){let h=d.querySelector(".aparte-checkpoint__summary");h&&(h.innerHTML=this._cfg.renderMarkdown(a))}i?i.replaceWith(d):this.prepend(d),this._checkpointDrawn=o;let u=t??c;u&&d.querySelector(`[data-checkpoint-action="${K(u)}"]`)?.focus()}_onCheckpointClick=t=>{let e=t.target?.closest?.("[data-checkpoint-action]"),s=e?.closest(".aparte-checkpoint");if(!(!e||!s||s.parentElement!==this)&&!e.closest(".aparte-checkpoint__summary"))switch(e.getAttribute("data-checkpoint-action")){case"toggle":this._checkpointOpen=!this._checkpointOpen,this._updateCheckpoint("toggle");break;case"restore":this._confirmingRestore=!0,this._updateCheckpoint("restore-confirm");break;case"restore-cancel":this._confirmingRestore=!1,this._updateCheckpoint("restore");break;case"restore-confirm":{this._confirmingRestore=!1;let i=this.getAttribute("message-id")??void 0;Dd(this,{messageId:i,targetId:this._resolveTargetId()}),this.setContextSummary(null);break}case"retry":{let i=this._resolveTargetId(),r=this._cfg.getCompactor();r?r.compact({target:st(this),...i?{targetId:i}:{},force:!0,reason:"retry"}):window.dispatchEvent(new CustomEvent("aparte-compact",{detail:{targetId:i}}));break}}};_onCheckpointKeydown=t=>{if(t.key!=="Escape"||!this._confirmingRestore)return;let e=t.target?.closest?.(".aparte-checkpoint");!e||e.parentElement!==this||(t.stopPropagation(),this._confirmingRestore=!1,this._updateCheckpoint("restore"))};_appendSegmentEl(t){if(!this._segmentsEl){console.warn("[AparteChatBubble] _appendSegmentEl ABORT: _segmentsEl is null");return}this._segments.length===1&&(this._drawnWithVersion=Z(this._cfg));let e=Ct(t.type,this._cfg);if(e){let s=this._drawnAs(t,!0),i=te(j(this._cfg,()=>e.render(t)),t);i&&(this._segmentsEl.appendChild(i),this._install(t,i,e,s))}else{let s=En(t);this._segmentsEl.appendChild(s),this._install(t,s,void 0)}this._contentEl&&(this._contentEl.style.display="none"),this._reflectError()}_turnRole(t){if(t.type==="thinking")return"fold";if(t.type!=="tool_call")return"stop";let e=t;return this._cfg.isToolHidden(e.toolCall?.name??"")?"skip":e.status==="awaiting-approval"||e.status==="failed"||this._toolRendererFor(t)?"stop":"fold"}_turnHolding(t){let e=t?.parentElement?.parentElement;return e?.classList.contains("aparte-turn")&&e.parentElement===this._segmentsEl?e:null}_createTurn(){let t=document.createElement("details");t.className="aparte-turn aparte-accordion__item";let e=document.createElement("summary");e.className="aparte-accordion__header aparte-turn__summary";let s=document.createElement("span");s.className="aparte-turn__label";let i=document.createElement("span");i.className="aparte-turn__current";let r=document.createElement("span");r.className="aparte-accordion__icon",r.innerHTML=this._cfg.getIcon("expand"),e.append(s,i,r),e.addEventListener("click",()=>{t.dataset.touched=""});let a=document.createElement("div");return a.className="aparte-accordion__panel aparte-turn__body",t.append(e,a),t}_syncTurns(){let t=this._segmentsEl;if(!t||this._releasedWhileDetached)return;let e=this._cfg.getTurnSummary(),s=e?Md(this._segments,c=>this._turnRole(c)):[];if(s.length===0&&!t.querySelector(":scope > .aparte-turn"))return;let i=(c,d,u)=>{let h=u?u.nextSibling:c.firstChild;return d!==h&&c.insertBefore(d,h),d},r=c=>this._drawn.get(c.id)?.el,a=new Set,o=new Map(s.map(c=>[c.from,c])),l=null;for(let c=0;c<this._segments.length;c+=1){let d=o.get(c);if(!d){let _=r(this._segments[c]);_&&(l=i(t,_,l));continue}let u=this._segments.slice(d.from,d.to+1),p=u.map(_=>this._turnHolding(r(_))).find(_=>_&&!a.has(_))??this._createTurn();a.add(p),l=i(t,p,l);let f=p.querySelector(":scope > .aparte-turn__body"),g=null;for(let _ of u){let S=r(_);S&&(g=i(f,S,g))}this._labelTurn(p,u,d.to===this._segments.length-1,e?.openWhileRunning===!0),c=d.to}for(let c of t.querySelectorAll(":scope > .aparte-turn"))a.has(c)||c.remove()}_labelTurn(t,e,s,i){let r=this._cfg,a=e.filter(u=>this._turnRole(u)==="fold"),o=a.filter(u=>u.type==="tool_call"),l=this._streaming&&s||o.some(u=>!ft(u)),c=t.querySelector(":scope > summary > .aparte-turn__label"),d=t.querySelector(":scope > summary > .aparte-turn__current");c.classList.toggle("aparte-shimmer",l),c.textContent=l?r.t("turnWorking"):this._turnOutcome(a,o.length),d.textContent=l&&o.length>0?this._stepName(o.at(-1)):"",i&&!("touched"in t.dataset)&&(t.open=l)}_turnOutcome(t,e){let s=this._cfg,i=s.getLocale().tag||void 0,r=e>0?Td(s.t("turnTools"),e,i):"",a=xd(t);if(a!==void 0){let o=s.t("turnWorked").replace("{duration}",()=>an(a,i));return r?`${o} \xB7 ${r}`:o}return r?s.t("turnUsed").replace("{tools}",()=>r):s.t("thought")}_stepName(t){let e=t.toolCall?.name??"",s=this._cfg.getToolDisplay(e)?.label;if(typeof s!="function")return s??e;try{return s(t)}catch{return e}}_applySegmentUpdate(t,e,s){let i=this._segmentsEl?He(this._segmentsEl,t):null;if(!i){this._renderSegments();return}if(this._releasedWhileDetached)return;let r=Ct(e.type,this._cfg);if(!r)return;let a=this._drawn.get(t);if(a&&a.renderer!==r){a.segment=e,this._redrawSegment(e);return}if(r.update){j(this._cfg,()=>r.update(i,e));let o=this._drawn.get(t);if(o){o.segment=e;let l=this._segmentsEl?He(this._segmentsEl,t):null;l&&l!==o.el&&(o.el=l,o.tool=e.type==="tool_call"?dn(l):null)}}else{let o=te(j(this._cfg,()=>r.render(e)),e);o&&(this._release(t),i.replaceWith(o),this._install(e,o,r))}"collapsed"in s&&(s.collapsed?i.removeAttribute("open"):i.setAttribute("open",""))}_getDisplayName(){let t=this.getAttribute("name");if(t)return t;let e=this._cfg.getLocale();return this._role==="user"?e.roleNameUser??"You":e.roleNameAssistant??"Assistant"}_getAvatarInitial(){let t=this._getDisplayName();return t.length>0?t[0]:this._role==="user"?"U":"A"}_render(){let t=this.getAttribute("data-role"),e=t==="user"||t==="assistant"?t:"assistant";if(this._role=e,this.getAttribute("role")!=="article"&&this.setAttribute("role","article"),this.hasAttribute("data-role")||this.setAttribute("data-role",e),this.querySelector(".aparte-message"))return;let s=this._getDisplayName(),i=this._getAvatarInitial(),r=this._cfg.getBubbleShellRenderer?.();if(this._drawnShell=r??null,this._avatarFromProvider=!1,this._wroteRootLabel=this._wroteBarLabel=this._wroteArrowLabels=!r,r){let o=j(this._cfg,()=>r({role:this._role,name:s,avatarInitial:i}));o instanceof HTMLElement?this.replaceChildren(o):this.innerHTML=o}else this.innerHTML=`
|
|
87
|
+
<div class="aparte-message" data-role="${x(e)}" role="article" aria-label="${x(this._getAriaLabel())}">
|
|
88
|
+
<div class="aparte-avatar" data-role="${x(e)}"></div>
|
|
89
|
+
<div class="aparte-body">
|
|
90
|
+
<div class="aparte-header">
|
|
91
|
+
<span class="aparte-name">${L(s)}</span>
|
|
92
|
+
<span class="aparte-timestamp"></span>
|
|
93
|
+
</div>
|
|
94
|
+
<div class="aparte-attachments" hidden></div>
|
|
95
|
+
<div class="aparte-message-content">
|
|
96
|
+
<div class="aparte-segments"></div>
|
|
97
|
+
<div class="aparte-content" dir="auto"></div>
|
|
98
|
+
<div class="aparte-waiting" hidden>
|
|
99
|
+
<span class="aparte-dots" aria-hidden="true"><span class="aparte-dot"></span><span class="aparte-dot"></span><span class="aparte-dot"></span></span>
|
|
100
|
+
<span class="aparte-sr-only"></span>
|
|
101
|
+
</div>
|
|
102
|
+
</div>
|
|
103
|
+
<div class="aparte-footer">
|
|
104
|
+
<div class="aparte-branch-picker" hidden>
|
|
105
|
+
<button type="button" class="aparte-btn aparte-btn--icon aparte-btn--sm aparte-branch-prev" aria-label="${x(this._cfg.getLocale().previousResponse??"Previous response")}">${this._cfg.getIcon("prevBranch")}</button>
|
|
106
|
+
<span class="aparte-branch-label">1 / 1</span>
|
|
107
|
+
<!-- The move has to be ANNOUNCED. Pressing the arrows deliberately does not
|
|
108
|
+
take focus, so without a live region a screen-reader user gets the new
|
|
109
|
+
branch and no indication anything changed. The visible label cannot be
|
|
110
|
+
the region itself: a custom sibling-nav renderer may replace it with
|
|
111
|
+
dots, which reads as nothing. No new locale key \u2014 the position is
|
|
112
|
+
digits, and the buttons beside it already carry translated labels. -->
|
|
113
|
+
<span class="aparte-sr-only aparte-branch-status" aria-live="polite"></span>
|
|
114
|
+
<button type="button" class="aparte-btn aparte-btn--icon aparte-btn--sm aparte-branch-next" aria-label="${x(this._cfg.getLocale().nextResponse??"Next response")}">${this._cfg.getIcon("nextBranch")}</button>
|
|
115
|
+
</div>
|
|
116
|
+
<div class="aparte-action-bar" role="toolbar" aria-label="${x(this._cfg.getLocale().messageActions??"Message actions")}"></div>
|
|
117
|
+
</div>
|
|
118
|
+
</div>
|
|
119
|
+
</div>
|
|
120
|
+
`;let a=this.querySelector(".aparte-message");if(a&&!a.hasAttribute("role")&&(a.setAttribute("role","article"),a.setAttribute("aria-label",this._getAriaLabel()),this._wroteRootLabel=!0),this._contentEl=this.querySelector(".aparte-content"),this._segmentsEl=this.querySelector(".aparte-segments"),this._attachmentsEl=this.querySelector(".aparte-attachments"),this._actionBarEl=this.querySelector(".aparte-action-bar"),this._actionBarEl&&!this._actionBarEl.hasAttribute("role")&&(this._actionBarEl.setAttribute("role","toolbar"),this._actionBarEl.hasAttribute("aria-label")||(this._actionBarEl.setAttribute("aria-label",this._cfg.getLocale().messageActions??"Message actions"),this._wroteBarLabel=!0)),r){let o=this.querySelector(".aparte-branch-prev"),l=this.querySelector(".aparte-branch-next"),c=u=>{let h="",p=u.ownerDocument.createTreeWalker(u,NodeFilter.SHOW_TEXT);for(let f=p.nextNode();f;f=p.nextNode()){let g=f.parentElement?.closest('[aria-hidden="true"], [hidden]');(!g||!u.contains(g))&&(h+=f.textContent??"")}return h},d=u=>!!u&&(u.hasAttribute("aria-label")||u.hasAttribute("aria-labelledby")||u.hasAttribute("title")||/\p{L}/u.test(c(u)));if((o||l)&&!d(o)&&!d(l)){let u=this._cfg.getLocale();o?.setAttribute("aria-label",u.previousResponse??"Previous response"),l?.setAttribute("aria-label",u.nextResponse??"Next response"),this._wroteArrowLabels=!0}}this._actionBarEl?.addEventListener("keydown",this._onActionBarKeydown),this._branchPickerEl=this.querySelector(".aparte-branch-picker"),this._footerEl=this.querySelector(".aparte-footer"),this._transcriptBusy=!!this.closest("aparte-chat-viewport")?.hasAttribute("data-busy"),this._updateActionBar(),this._renderAvatar(),this._streaming&&this._updateStreaming(!0),this._updateWaiting(),this._updateFinishNote(),this._updateCheckpoint()}_updateWaiting(){let e=!(this._segmentsEl?Array.from(this._segmentsEl.children).some(p=>!p.hidden):this._segments.length>0)&&!this._content.trim(),s=this._segments.at(-1),i=this._segmentsEl?.lastElementChild,r=s?.type==="tool_call"&&s.status==="awaiting-approval",a=s?.type==="tool_call"&&(ft(s)||i?.hidden===!0)&&i?.classList.contains("aparte-turn")!==!0,o=this._streaming&&this._role!=="user"&&!r&&(e||a),l=this.querySelector(".aparte-message-content");l&&(l.hidden=e&&!o);let c=this.querySelector(".aparte-message");c&&c.toggleAttribute("data-empty",e&&!this._streaming&&this._attachments.length===0);let d=this.querySelector(".aparte-waiting");if(!d||(d.hidden=!o,!o))return;let u=this._cfg.getLocale().typing,h=d.querySelector(".aparte-sr-only");h&&h.textContent!==u&&(h.textContent=u)}_renderAvatar(){let t=this.querySelector(".aparte-avatar");if(!t)return;if(this._avatarCleanup){try{this._avatarCleanup()}catch{}this._avatarCleanup=null}let e=this._cfg.getAvatarProvider();if(!e){this._avatarFromProvider&&(t.replaceChildren(),this._avatarFromProvider=!1),this._markAvatarImage(t);return}t.textContent="";let s=e.render(this._role,t);this._avatarFromProvider=!0,typeof s=="function"&&(this._avatarCleanup=s),this._markAvatarImage(t)}_markAvatarImage(t){if(t.firstChild){ne.delete(t),t.removeAttribute("data-image");return}ne.size===0&&queueMicrotask($d),ne.set(t,{bubble:this,role:this._role})}_updateRole(){let t=this.querySelector(".aparte-message"),e=this.querySelector(".aparte-avatar"),s=this.querySelector(".aparte-name");t&&(t.setAttribute("data-role",this._role),this._wroteRootLabel&&t.getAttribute("role")==="article"&&t.setAttribute("aria-label",this._getAriaLabel())),e&&(e.setAttribute("data-role",this._role),e.textContent&&!this._avatarFromProvider&&(e.textContent=this._getAvatarInitial())),s&&(s.textContent=this._getDisplayName()),this._updateActionBar(),this._renderAvatar()}_updateName(){let t=this.querySelector(".aparte-avatar"),e=this.querySelector(".aparte-name");t&&t.textContent&&!this._cfg.getAvatarProvider()&&!this._avatarFromProvider&&(t.textContent=this._getAvatarInitial()),e&&(e.textContent=this._getDisplayName());let s=this.querySelector(".aparte-message");this._wroteRootLabel&&s?.getAttribute("role")==="article"&&s.setAttribute("aria-label",this._getAriaLabel())}_updateContent(){if(this._contentEl){if(this._segments.length>0){this._contentEl.style.display="none",this._updateWaiting();return}this._drawnWithVersion=Z(this._cfg),this._contentEl.style.display="",j(this._cfg,()=>Rt(this,this._contentEl,this._content,this._streaming)),this._drawTokens(),this._updateWaiting(),this._streaming||this._highlightContentCode()}}_highlightContentCode(){!this._contentEl||!this._cfg.hasHighlightProvider()||this._contentEl.querySelectorAll("pre > code:not([data-aparte-highlighted])").forEach(t=>{let e=t.textContent??"";if(!e.trim())return;let i=t.className.match(/language-([\w+#-]+)/i)?.[1]??"";if(this._cfg.hasCodeLanguageRenderer(i)||t.closest(".aparte-code-drawing"))return;let r=t.parentElement;t.setAttribute("data-aparte-highlighted",""),Promise.resolve(this._cfg.highlightCode(e,i,{fallback:!1})).then(a=>{let o=(a??"").trim();!o||!r||!this._contentEl?.contains(r)||(/^<pre[\s>]/i.test(o)?rn(r,o):t.innerHTML=o)}).catch(()=>{t.removeAttribute("data-aparte-highlighted")})})}_renderSegments(){if(this._segmentsEl){this._drawnWithVersion=Z(this._cfg),this._releaseAll(),this._segmentsEl.innerHTML="";for(let t of this._segments){let e=Ct(t.type,this._cfg);if(e){let s=this._drawnAs(t),i=te(j(this._cfg,()=>e.render(t)),t);i&&(this._segmentsEl.appendChild(i),this._install(t,i,e,s))}else{let s=En(t);this._segmentsEl.appendChild(s),this._install(t,s,void 0)}}this._syncTurns(),this._contentEl&&(this._contentEl.style.display=this._segments.length>0?"none":""),this._reflectError(),this._syncCopyAction(),this._syncSources()}}_reflectError(){let t=this.querySelector(".aparte-message");if(!t)return;this._segments.some(s=>s.type==="error")?t.setAttribute("data-error",""):t.removeAttribute("data-error")}_updateTimestamp(t){let e=this.querySelector(".aparte-timestamp");if(!(!e||!t))try{let s=new Date(isNaN(Number(t))?t:Number(t));e.textContent=s.toLocaleTimeString(this._cfg.getLocale().tag||void 0,{hour:"2-digit",minute:"2-digit"})}catch{e.textContent=""}}_getAriaLabel(){let t=this._cfg.getLocale(),e=this.getAttribute("name");return e?(t.messageFrom||"Message from {name}").replace("{name}",()=>e):this._role==="user"?t.yourMessage??"Your message":t.assistantResponse??"Assistant response"}_updateAttachments(){if(!this._attachmentsEl)return;if(this._role!=="user"||this._attachments.length===0){this._attachmentsEl.hidden=!0,this._attachmentsEl.innerHTML="";return}this._attachmentsEl.hidden=!1;let t=this._cfg.getAttachmentRenderer?.();if(t){this._attachmentsEl.replaceChildren();for(let r of this._attachments){let a=te(j(this._cfg,()=>t(r)));a&&this._attachmentsEl.appendChild(a)}return}this._attachmentsEl.innerHTML=this._attachments.map(r=>{let a=L(r.name);if(r.type.startsWith("image/")&&this._isShowableUrl(r.url))return`<div class="aparte-thumbnail aparte-thumb aparte-thumb--image" title="${a}" data-type="${L(r.type)}"><img class="aparte-thumbnail__image" src="${L(r.url)}" alt="${a}" loading="lazy" /><span class="aparte-thumb__name">${a}</span></div>`;let o=this._isOpenableUrl(r.url)?` data-url="${L(r.url)}"`:"";return`<div class="aparte-thumbnail aparte-thumb aparte-thumb--file" title="${a}" data-type="${L(r.type)}"${o}><span class="aparte-thumbnail__label">${L(this._fileExt(r.name))}</span><span class="aparte-thumb__name">${a}</span></div>`}).join("");let{attachmentPreview:e,filePreview:s}=this._cfg.getHostHandlers(),i=[e?".aparte-thumb--image":"",s?".aparte-thumb--file[data-url]":""].filter(Boolean);i.length!==0&&this._attachmentsEl.querySelectorAll(i.join(", ")).forEach(r=>{r.setAttribute("role","button"),r.setAttribute("tabindex","0");let a=()=>{let o=r.querySelector(".aparte-thumbnail__image")?.src??r.dataset.url;o&&this.dispatchEvent(new CustomEvent("aparte-attachment-preview",{bubbles:!0,composed:!0,detail:{url:o,name:r.getAttribute("title")??"",type:r.dataset.type??""}}))};r.addEventListener("click",a),r.addEventListener("keydown",o=>{let l=o.key;l!=="Enter"&&l!==" "||(o.preventDefault(),a())})})}_isShowableUrl(t){return t?Qt(t,"img")||/^blob:/i.test(t.trim()):!1}_isOpenableUrl(t){return!!t&&/^(https?:|blob:)/i.test(t.trim())}_fileExt(t){let e=t.lastIndexOf(".");return e>0?t.slice(e+1).toUpperCase().slice(0,4):"FILE"}_onBranchPickerClick=t=>{let s=t.target?.closest?.(".aparte-branch-prev, .aparte-branch-next");if(!s||!this.contains(s))return;let i=s.classList.contains("aparte-branch-prev")?"prev":"next",r=this.getAttribute("message-id");if(!r)return;let a={messageId:r,direction:i};this.dispatchEvent(new CustomEvent("aparte-branch-navigate",{bubbles:!0,composed:!0,detail:a}))};_onLinkClick=t=>{let s=t.target?.closest?.("a[href]");if(!s||!this.contains(s))return;let i={href:s.getAttribute("href")??"",anchor:s,messageId:this.getAttribute("message-id")};this.dispatchEvent(new CustomEvent("aparte-link-click",{bubbles:!0,composed:!0,cancelable:!0,detail:i}))||t.preventDefault()};_transcriptBusy=!1;setTranscriptBusy(t){this._transcriptBusy!==t&&(this._transcriptBusy=t,this._applyTranscriptBusy(),this._updateBranchPicker())}_applyTranscriptBusy(){if(this._actionBarEl)for(let t of this._actionBarEl.querySelectorAll('[data-action="retry"], [data-action="edit"]'))t.disabled=this._transcriptBusy}_updateBranchPicker(){if(!this._branchPickerEl)return;if(this._siblingCount<=1||this._role!=="assistant"){this._branchPickerEl.hidden=!0,this._syncFooterVisibility();return}this._branchPickerEl.hidden=!1,this._syncFooterVisibility();let t=this._branchPickerEl.querySelector(".aparte-branch-label");if(t){let r=this._cfg.getSiblingNavRenderer?.();if(r){let a=j(this._cfg,()=>r({count:this._siblingCount,index:this._siblingIndex}));a instanceof HTMLElement?t.replaceChildren(a):t.innerHTML=a}else t.textContent=`${this._siblingIndex+1} / ${this._siblingCount}`}let e=this._branchPickerEl.querySelector(".aparte-branch-status");if(e){let r=`${this._siblingIndex+1} / ${this._siblingCount}`;e.textContent!==r&&(e.textContent=r)}let s=this._branchPickerEl.querySelector(".aparte-branch-prev"),i=this._branchPickerEl.querySelector(".aparte-branch-next");s&&(s.disabled=this._transcriptBusy||this._siblingIndex===0),i&&(i.disabled=this._transcriptBusy||this._siblingIndex===this._siblingCount-1)}_copyableText(){return(this._content||this._segments.filter(t=>t.type!=="thinking").map(t=>t.content??"").join(`
|
|
121
|
+
`)).trim()}_syncCopyAction(){let t=this._actionBarEl?.querySelector(".aparte-action-copy");t&&(t.hidden=this._copyableText()==="")}_updateActionBar(){if(!this._actionBarEl)return;if(this._editing){this._renderEditActions();return}let t=this._cfg.getBubbleActions(),e=this._cfg.getIconProvider(),s=this._cfg.getLocale(),i=[];if(this._role==="user")if(t.user)for(let r of t.user)i.push(this._actionButtonHtml(r,e,s));else t.copy&&i.push(this._actionButtonHtml("copy",e,s)),t.edit&&i.push(this._actionButtonHtml("edit",e,s));else if(this._role==="assistant")if(t.assistant)for(let r of t.assistant)i.push(this._actionButtonHtml(r,e,s));else t.copy&&i.push(this._actionButtonHtml("copy",e,s)),t.retry&&i.push(this._actionButtonHtml("retry",e,s)),t.feedback&&(i.push(this._actionButtonHtml("thumbUp",e,s)),i.push(this._actionButtonHtml("thumbDown",e,s))),t.info&&i.push(this._actionButtonHtml("info",e,s));this._actionBarEl.innerHTML=i.join(""),this._syncCopyAction(),this._appendCustomActions(),this._applyTranscriptBusy(),this._actionBarEl.querySelectorAll(".aparte-action-btn").forEach(r=>{r.addEventListener("click",a=>this._handleActionClick(a))}),this._syncFooterVisibility()}_rovingButtons(){return this._actionBarEl?[...this._actionBarEl.querySelectorAll("button")]:[]}_setRovingIndex(){let t=this._rovingButtons();if(!t.length)return;let e=t.filter(r=>!r.disabled),i=t.find(r=>r.tabIndex===0&&!r.disabled)??e[0]??t[0];for(let r of t)r.tabIndex=r===i?0:-1}_onActionBarKeydown=t=>{let e=t;if(!["ArrowLeft","ArrowRight","Home","End"].includes(e.key))return;let i=this._rovingButtons().filter(d=>!d.disabled);if(i.length===0)return;let r=document.activeElement,a=i.findIndex(d=>d===r);if(a===-1&&e.key!=="Home"&&e.key!=="End")return;let l=(this.closest("[dir]")?.getAttribute("dir")??document.documentElement.dir)==="rtl"?"ArrowLeft":"ArrowRight",c;e.key==="Home"?c=0:e.key==="End"?c=i.length-1:e.key===l?c=(a+1)%i.length:c=(a-1+i.length)%i.length,e.preventDefault();for(let d of this._rovingButtons())d.tabIndex=d===i[c]?0:-1;i[c]?.focus()};_syncFooterVisibility(){if(this._actionBarEl&&(this._actionBarEl.hidden=this._actionBarEl.children.length===0),this._setRovingIndex(),!this._footerEl)return;let t=!this._actionBarEl||this._actionBarEl.hidden,e=!this._branchPickerEl||this._branchPickerEl.hidden;this._footerEl.hidden=t&&e,this.querySelector(".aparte-message")?.toggleAttribute("data-branches",!e)}_appendCustomActions(){if(this._actionBarEl)for(let t of this._cfg.getActions("bubble")){if(!(t.bubble?.roles??["user","assistant"]).includes(this._role))continue;let s=document.createElement("button");s.type="button",s.className="aparte-btn aparte-btn--icon aparte-btn--sm aparte-action-btn aparte-action-custom",s.dataset.action=`custom:${t.id}`,s.setAttribute("aria-label",t.label),s.setAttribute("title",t.label),s.innerHTML=t.icon.startsWith("<")?t.icon:this._cfg.getIcon(t.icon)??t.iconFallback??"",this._actionBarEl.appendChild(s)}}_actionButtonHtml(t,e,s){switch(t){case"copy":{let i=s.copy??"Copy";return`<button type="button" class="aparte-btn aparte-btn--icon aparte-btn--sm aparte-action-btn aparte-action-copy" data-action="copy" aria-label="${x(i)}" title="${x(i)}">${e.copy()}</button>`}case"edit":{let i=s.edit??"Edit message";return`<button type="button" class="aparte-btn aparte-btn--icon aparte-btn--sm aparte-action-btn aparte-action-edit" data-action="edit" aria-label="${x(i)}" title="${x(i)}">${e.edit()}</button>`}case"retry":{let i=s.retry??"Retry";return`<button type="button" class="aparte-btn aparte-btn--icon aparte-btn--sm aparte-action-btn aparte-action-retry" data-action="retry" aria-label="${x(i)}" title="${x(i)}">${e.retry()}</button>`}case"thumbUp":{let i=s.feedbackPositive??"Good response";return`<button type="button" class="aparte-btn aparte-btn--icon aparte-btn--sm aparte-action-btn aparte-action-feedback-pos" data-action="feedback-positive" aria-label="${x(i)}" title="${x(i)}">${e.thumbUp()}</button>`}case"thumbDown":{let i=s.feedbackNegative??"Bad response";return`<button type="button" class="aparte-btn aparte-btn--icon aparte-btn--sm aparte-action-btn aparte-action-feedback-neg" data-action="feedback-negative" aria-label="${x(i)}" title="${x(i)}">${e.thumbDown()}</button>`}case"info":{if(!this._usage)return"";let i=s.messageInfo??"Details";return`<button type="button" class="aparte-btn aparte-btn--icon aparte-btn--sm aparte-action-btn aparte-action-info" data-action="info" aria-label="${x(i)}" title="${x(i)}">${this._cfg.getIcon("info")}</button>`}default:return""}}_renderEditActions(){if(!this._actionBarEl)return;let t=this._cfg.getLocale(),e=t.editConfirm??"Save",s=t.editCancel??"Cancel";this._actionBarEl.innerHTML=`<button type="button" class="aparte-btn aparte-btn--icon aparte-btn--sm aparte-btn--success aparte-action-btn aparte-action-edit-save" data-action="edit-save" aria-label="${x(e)}" title="${x(e)}">${this._cfg.getIcon("check")}</button><button type="button" class="aparte-btn aparte-btn--icon aparte-btn--sm aparte-btn--danger aparte-action-btn aparte-action-edit-cancel" data-action="edit-cancel" aria-label="${x(s)}" title="${x(s)}">${this._cfg.getIcon("close")}</button>`,this._actionBarEl.querySelectorAll(".aparte-action-btn").forEach(i=>{i.addEventListener("click",r=>this._handleActionClick(r))}),this._syncFooterVisibility()}_handleActionClick(t){let e=t.currentTarget,s=e.dataset.action,i=this.getAttribute("message-id");if(s?.startsWith("custom:")&&i){let r=s.slice(7),a={actionId:r,zone:"bubble",messageId:i,role:this._role,targetId:this._resolveTargetId()};this.dispatchEvent(new CustomEvent("aparte-action",{bubbles:!0,composed:!0,detail:a})),this._cfg.getActions("bubble").find(o=>o.id===r)?.onClick?.(t);return}switch(s){case"copy":{let r=this._copyableText(),a=this._cfg.getIconProvider(),o=this._cfg.getLocale();on(r).then(()=>{e.innerHTML=a.check(),e.setAttribute("data-copied","");let l=o.copied??o.copy??"Copied";e.setAttribute("title",l),e.setAttribute("aria-label",l),setTimeout(()=>{e.removeAttribute("data-copied"),e.innerHTML=a.copy();let c=o.copy??"Copy";e.setAttribute("title",c),e.setAttribute("aria-label",c)},2e3)}).catch(()=>{console.warn("[aparte] Clipboard write failed")});break}case"retry":{if(!i)break;let r=this._resolveTargetId(),a={messageId:i,targetId:r};this.dispatchEvent(new CustomEvent("aparte-retry",{bubbles:!0,composed:!0,detail:a}));break}case"edit":{this._enterEditMode();break}case"edit-save":{this._exitEditMode(!0);break}case"edit-cancel":{this._exitEditMode(!1);break}case"feedback-positive":case"feedback-negative":{if(!i)break;let r=s==="feedback-positive"?"positive":"negative";e.setAttribute("data-submitted","");let a={messageId:i,value:r};this.dispatchEvent(new CustomEvent("aparte-feedback",{bubbles:!0,composed:!0,detail:a})),r==="negative"?this._askFeedbackReason(i):this.querySelector(".aparte-feedback-reasons")?.remove();break}case"info":{if(!i)break;let r={messageId:i,usage:this._usage??void 0};this.dispatchEvent(new CustomEvent("aparte-message-info",{bubbles:!0,composed:!0,detail:r}));break}}}_enterEditMode(){if(this._editing||!this._contentEl)return;let t=document.activeElement;this._editReturnAction=t instanceof HTMLElement&&this.contains(t)?t.getAttribute("data-action")??"edit":null,this._editing=!0,this.querySelector(".aparte-message")?.setAttribute("data-editing","");let e=document.createElement("aparte-composer-input");e.setAttribute("placeholder",this._cfg.getLocale().edit??"Edit message"),this._editInput=e,this._contentEl.style.display="none",this._contentEl.insertAdjacentElement("afterend",e),e.setValue(this._content),e.addEventListener("aparte-composer-submit",()=>this._exitEditMode(!0)),e.addEventListener("keydown",s=>{s.key==="Escape"&&!s.isComposing&&(s.preventDefault(),this._exitEditMode(!1))}),this._updateActionBar(),e.focusEnd()}_exitEditMode(t){if(!this._editing)return;let e=this._editInput?.getValue()??"",s=this._content;this._editInput?.remove(),this._editInput=null,this._contentEl&&(this._contentEl.style.display=""),this.querySelector(".aparte-message")?.removeAttribute("data-editing"),this._editing=!1,this._redrawFrameIfChanged(),this._redrawIfStale(),this._updateActionBar();let i=this._editReturnAction;if(this._editReturnAction=null,i&&this._actionBarEl){let r=Array.from(this._actionBarEl.querySelectorAll("[data-action]")).find(o=>o.getAttribute("data-action")===i),a=r&&!r.disabled?r:this._actionBarEl.querySelector("button:not([disabled])");if(a){for(let o of this._rovingButtons())o.tabIndex=o===a?0:-1;a.focus()}}if(t&&e&&e!==s){let r=this.getAttribute("message-id");if(r){let a={messageId:r,content:e,targetId:this._resolveTargetId()};this.dispatchEvent(new CustomEvent("aparte-edit",{bubbles:!0,composed:!0,detail:a}))}}}_resolveTargetId(){let t=this.parentElement;for(;t;){if((t.tagName?.toLowerCase()==="aparte-chat"||t.hasAttribute?.("data-aparte-chat"))&&t.id)return t.id;t=t.parentElement}}_updateStreaming(t){let e=this._streaming;this._streaming=t;let s=this.querySelector(".aparte-message");s&&(s.setAttribute("data-streaming",String(t)),t?(s.setAttribute("aria-busy","true"),s.classList.add("aparte-message-streaming")):(s.removeAttribute("aria-busy"),s.classList.remove("aparte-message-streaming")),s.toggleAttribute("data-caret",t&&this._cfg.getStreamingCaret())),this._updateWaiting(),this._updateFinishNote(),e&&!t&&this._updateContent(),e&&!t&&this._settleWrittenSegments(),e&&!t&&this._segments.length>0&&this._redrawIfStale(),this._syncTurns()}};H(Ke);customElements.get("aparte-chat-bubble")||customElements.define("aparte-chat-bubble",Ke);var Ve=class extends HTMLElement{static get observedAttributes(){return["visible","text"]}get _cfg(){return T(this)}_word(){return this._cfg.t("typing")}constructor(){super()}connectedCallback(){this._render(),window.addEventListener("aparte-config-change",this._onConfigChange)}disconnectedCallback(){window.removeEventListener("aparte-config-change",this._onConfigChange)}_onConfigChange=t=>{let e=t.detail;e?.config&&e.config!==this._cfg||(this.innerHTML="",this._render())};attributeChangedCallback(t,e,s){if(e!==s)switch(t){case"visible":this._updateVisibility(s!==null);break;case"text":this._updateText(s);break}}show(){this.setAttribute("visible","")}hide(){this.removeAttribute("visible")}toggle(){this.hasAttribute("visible")?this.hide():this.show()}isVisible(){return this.hasAttribute("visible")}_render(){let t=this.getAttribute("text")||this._word(),e=this.hasAttribute("visible");if(this.querySelector(".aparte-status-container"))return;let s=this._cfg?.getStatusRenderer?.();if(s){this.innerHTML=`<div class="aparte-message aparte-status-container" data-visible="${e}" role="status" aria-live="polite"></div>`;let i=this.querySelector(".aparte-status-container");i.setAttribute("aria-label",t);let r=j(this._cfg,()=>s(t));r instanceof HTMLElement?i.appendChild(r):i.innerHTML=r;return}this.innerHTML=`
|
|
122
|
+
<div
|
|
123
|
+
class="aparte-message aparte-status-container"
|
|
124
|
+
data-visible="${e}"
|
|
125
|
+
role="status"
|
|
126
|
+
aria-live="polite"
|
|
127
|
+
>
|
|
128
|
+
<div class="aparte-avatar" data-role="assistant" style="visibility: hidden"></div>
|
|
129
|
+
<div class="aparte-body">
|
|
130
|
+
<div class="aparte-status-content">
|
|
131
|
+
<div class="aparte-dots" aria-hidden="true">
|
|
132
|
+
<span class="aparte-dot"></span>
|
|
133
|
+
</div>
|
|
134
|
+
<span class="aparte-status-text"></span>
|
|
135
|
+
<span class="aparte-sr-only aparte-status-sr"></span>
|
|
136
|
+
</div>
|
|
137
|
+
</div>
|
|
138
|
+
</div>
|
|
139
|
+
`,this.querySelector(".aparte-status-container")?.setAttribute("aria-label",t),this._writeText(this.getAttribute("text"))}_writeText(t){let e=t||null,s=this.querySelector(".aparte-status-text");s&&(s.textContent=e??""),this._syncLiveWord()}_syncLiveWord(){let t=this.querySelector(".aparte-status-sr");if(!t)return;let e=!this.getAttribute("text");t.textContent=e&&this.hasAttribute("visible")?this._word():""}_updateVisibility(t){let e=this.querySelector(".aparte-status-container");e&&e.setAttribute("data-visible",String(t)),this._syncLiveWord()}_updateText(t){let e=this.querySelector(".aparte-status-container");if(!e)return;let s=this._cfg?.getStatusRenderer?.();if(s){let i=t||this._word();e.setAttribute("aria-label",i);let r=j(this._cfg,()=>s(i));r instanceof HTMLElement?e.replaceChildren(r):e.innerHTML=r;return}this._writeText(t),e.setAttribute("aria-label",t||this._word())}};H(Ve);customElements.get("aparte-chat-status")||customElements.define("aparte-chat-status",Ve);function Ma(n,t){if(n.role!=="assistant"||n.segments?.length||typeof n.content!="string"||!n.content.trim())return n;let e=zi(n.content,{blocks:t});return e.length<=1&&e.every(i=>i.type==="text")?n:In({...n,segments:e})}function In(n){return Object.defineProperty(n,bn,{value:!0,enumerable:!1}),n}function xa(n){return n[bn]===!0}function Fd(n,t){try{return new Intl.DateTimeFormat(t||void 0,{dateStyle:"long"}).format(n)}catch{return n.toDateString()}}var Ye=class extends HTMLElement{_container=null;_scrollBtn=null;_bottomSpacer=null;_fwSpacerHeight=0;_spacerRafId=null;_spacerFrozenUntil=0;_layoutTransitionMs=0;_repo=new Ie;_isAutoScrollEnabled=!0;_lastScrollTop=0;_lastScrollHeight=0;_lastMutationAt=Number.NEGATIVE_INFINITY;_settleShadowMs=100;_settleBoundPx=100;_ownScrollAt=Number.NEGATIVE_INFINITY;_readerInputAt=Number.NEGATIVE_INFINITY;_ownScrollWindowMs=1e3;_settleWindowMs=400;_glideUntil=0;_glideWindowMs=450;_glideSettleTimer=null;_settleUntil=0;_settleRafId=null;_scrollKeys=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," "]);_scrollThreshold=50;_smoothScrollOnce=!1;_maxRenderedBubbles=1e3;_resizeObserver=null;_mutationObserver=null;_tailObserver=null;_tail=[];_tailHeights=new WeakMap;_onDisclosureToggle=()=>{this._scheduleSpacerUpdate()};_overlayRoot=null;_overlayObserver=null;_overlayAttrObserver=null;_overlayInset=-1;_transcriptInset=-1;_boundResetHandler=null;_checkpointState=null;_stopCheckpointState=null;_frameworkManagedDOM=!1;_bulkAppend=!1;static get observedAttributes(){return["scroll-threshold","max-rendered-bubbles","loading"]}get loading(){return this.hasAttribute("loading")}set loading(t){this.toggleAttribute("loading",z(t))}setLoading(t){this.loading=t}_syncLoading(){let t=this._container;if(!t)return;let e=this.hasAttribute("loading");if(t.setAttribute("aria-busy",e?"true":"false"),this._frameworkManagedDOM)return;let s=t.querySelector(":scope > .aparte-viewport-loading");if(!e){s?.remove(),t.querySelector(":scope > .aparte-viewport-loading-status")?.remove();return}if(s)return;let i=T(this),r=document.createElement("div");r.className="aparte-viewport-loading",r.setAttribute("aria-hidden","true"),r.innerHTML='<span class="aparte-skeleton aparte-skeleton--rect aparte-viewport-loading__user"></span><span class="aparte-skeleton aparte-skeleton--text"></span><span class="aparte-skeleton aparte-skeleton--text"></span><span class="aparte-skeleton aparte-skeleton--text"></span><span class="aparte-skeleton aparte-skeleton--text aparte-viewport-loading__last"></span>';let a=document.createElement("span");a.className="aparte-viewport-loading-status aparte-sr-only",a.setAttribute("role","status"),t.prepend(r,a);let o=()=>{a.isConnected&&(a.textContent=i.t("loadingConversation"))};typeof requestAnimationFrame=="function"?requestAnimationFrame(o):o()}constructor(){super(),this._handleScroll=this._handleScroll.bind(this),this._handleScrollEnd=this._handleScrollEnd.bind(this)}connectedCallback(){this.hasAttribute("framework-managed")&&(this._frameworkManagedDOM=!0),this._render(),this._setupEventListeners(),this._setupObservers(),this._updateTranscriptInset(),this._boundResetHandler=()=>this.clearAll(),window.addEventListener("aparte-reset",this._boundResetHandler),window.addEventListener("aparte-config-change",this._onConfigChange),this._checkpointState??=new Me({ownId:()=>oa(this)??(this.id||void 0),bubbleOf:t=>this.querySelector(`aparte-chat-bubble[message-id="${K(t)}"]`),owns:t=>!!this.getMessage(t),active:()=>!this._frameworkManagedDOM}),this._stopCheckpointState??=this._checkpointState.start()}_onConfigChange=t=>{let e=t.detail;if(e?.config&&e.config!==T(this))return;this._applyDirection(),this._scrollBtn?.setAttribute("aria-label",T(this).t("scrollToBottom")),(this._frameworkManagedDOM?this:this.querySelector(".aparte-viewport-container"))?.setAttribute("aria-label",T(this).t("transcript")),this._syncDateSeparators()};_nameScrollSurface(t){t.setAttribute("tabindex","0"),t.hasAttribute("role")||t.setAttribute("role","log"),t.setAttribute("aria-label",T(this).t("transcript"))}_applyDirection(){let t=this._frameworkManagedDOM?this:this.querySelector(".aparte-viewport-container");if(!t)return;let e=T(this).getLocale().direction;e?t.setAttribute("dir",e):t.removeAttribute("dir")}disconnectedCallback(){window.removeEventListener("aparte-config-change",this._onConfigChange),this._boundResetHandler&&(window.removeEventListener("aparte-reset",this._boundResetHandler),this._boundResetHandler=null),this._stopCheckpointState?.(),this._stopCheckpointState=null,this._cleanup()}attributeChangedCallback(t,e,s){if(e!==s)switch(t){case"scroll-threshold":this._scrollThreshold=parseInt(s||"50",10);break;case"max-rendered-bubbles":this._maxRenderedBubbles=parseInt(s||"1000",10),this._pruneRenderedBubbles();break;case"loading":this._syncLoading();break}}configure(t){t.scrollThreshold!==void 0&&(this._scrollThreshold=t.scrollThreshold),t.maxRenderedBubbles!==void 0&&(this._maxRenderedBubbles=t.maxRenderedBubbles,this._pruneRenderedBubbles()),t.layoutTransitionMs!==void 0&&(this._layoutTransitionMs=t.layoutTransitionMs)}appendToken(t,e){let s=this._getOrCreateMessage(t);s.content=(s.content||"")+e,this._notifyBubble(t,"appendToken",e),this._autoScroll(),this._scheduleSpacerUpdate()}appendToSegment(t,e,s){let i=this._getOrCreateMessage(t);i.segments||(i.segments=[]);let r=i.segments.findIndex(o=>o.id===e),a=r===-1?void 0:i.segments[r];a&&"content"in a&&(i.segments[r]={...a,content:a.content+s,...Yi(a)}),this.dispatchEvent(new CustomEvent("aparte-segment-update",{bubbles:!0,composed:!0,detail:{messageId:t,segmentId:e,content:s,append:!0}})),this._notifyBubble(t,"appendToSegment",s,e),this._autoScroll()}_activeMessageId(){let t=this._repo.headId,e=this._streamingMessageId();return e!==null&&e!==t?null:t}_streamingMessageId(){let t=this._repo.headId,e=null;for(let s of this._repo.getAllMessages())if(s.isStreaming){if(s.id!==t)return s.id;e=s.id}return e}_syncBusy(){this._frameworkManagedDOM||this.setTranscriptBusy(this._streamingMessageId()!==null)}_busy=!1;setTranscriptBusy(t){this._busy=t,this.toggleAttribute("data-busy",t);for(let e of this.querySelectorAll("aparte-chat-bubble"))e.setTranscriptBusy?.(t)}addSegment(t,e){let s=typeof t=="string"?t:this._activeMessageId(),i=typeof t=="string"?e:t;if(!s||!i)return;let r=this._getOrCreateMessage(s);r.segments||(r.segments=[]);let a=Xs(r.segments,i,s,T(this).getSegmentDefaults(i.type));r.segments.push(a),this._notifyBubble(s,"addSegment",a),this._autoScroll()}updateSegment(t,e,s){let i=s===void 0&&typeof e=="object",r=i?this._activeMessageId():t,a=i?t:e,o=i?e:s;if(!r)return;let l=this._repo.getMessageById(r);if(!l?.segments)return;let c=l.segments.findIndex(d=>d.id===a);if(c!==-1){let d=l.segments[c],u=Ki(d,o);l.segments[c]=Qs(d,u),this._notifyBubble(r,"updateSegment",{segmentId:a,updates:u})}}removeSegment(t,e){let s=e===void 0,i=s?this._activeMessageId():t,r=s?t:e;if(!i||!r)return;let a=this._repo.getMessageById(i);if(a?.segments){let o=a.segments.findIndex(l=>l.id===r);o!==-1&&(a.segments.splice(o,1),Xi(a.segments))}this._notifyBubble(i,"removeSegment",r)}startSegment(t,e){let s={...e,isStreaming:!0};this.addSegment(t,s)}completeSegment(t,e){this.updateSegment(t,e,{isStreaming:!1})}setUsage(t,e){let s=this._repo.getMessageById(t);s&&(s.usage=e),this._notifyBubble(t,"setUsage",e)}completeMessage(t){let e=this._repo.getMessageById(t);e&&(e.isStreaming=!1,e.status="completed",this._settleSegments(t,e),this._notifyBubble(t,"complete",{status:"completed"}),this._syncBusy(),this._recalculateSpacer())}_settleSegments(t,e){if(e.segments)for(let s of Ji(e.segments))this.updateSegment(t,s,{isStreaming:!1})}updateMessage(t,e){let s=this._repo.getMessageById(t);s&&(Object.assign(s,e),e.status&&(s.isStreaming=e.status==="streaming"||e.status==="pending",Zs(e.status)&&this._settleSegments(t,s)),this._notifyBubble(t,"update",e),e.status&&this._syncBusy(),this._autoScroll())}addMessage(t){let e=Oe({...t});Ot(t)&&(e.isStreaming=!0),this._repo.addOrUpdateMessage(this._repo.headId,e),this._pruneRenderedBubbles(),this._syncBusy(),this._autoScroll()}appendMessage(t,e){t=Ma(t,T(this).getStreamBlocks());let s=e?.historical?Oe(t):t.segments?.length?{...t,segments:t.segments.reduce((i,r)=>(i.push(Xs(i,r,t.id,T(this).getSegmentDefaults(r.type))),i),[])}:{...t};if(!e?.historical&&Ot(t)&&(s.isStreaming=!0),xa(t)&&In(s),this._repo.addOrUpdateMessage(this._repo.headId,s),!this._frameworkManagedDOM){let i=this.querySelector(".aparte-messages-wrapper");if(i){let r=document.createElement("aparte-chat-bubble");r.setAttribute("message-id",t.id),r.setAttribute("data-role",t.role),t.compaction&&r.setAttribute("data-kind","compaction"),t.timestamp&&r.setAttribute("timestamp",String(t.timestamp)),t.content&&r.setAttribute("content",t.content),Ot(t)&&r.setAttribute("streaming",""),this._bottomSpacer&&this._bottomSpacer.parentNode===i?i.insertBefore(r,this._bottomSpacer):i.appendChild(r),mn(r,s)}}this._bulkAppend||(this._pruneRenderedBubbles(),this._syncBusy(),t.role==="user"&&(this._isAutoScrollEnabled=!0,this._smoothScrollToBottom()),this._recalculateSpacer(),t.role==="user"?requestAnimationFrame(()=>{this._isAutoScrollEnabled&&this._smoothScrollToBottom()}):this._autoScroll())}updateLastMessage(t,e){let s=this._repo.headId;if(s)if(e?.append)this.appendToken(s,t);else{let i=this._repo.getMessageById(s);i&&(i.content=t),this._notifyBubble(s,"appendToken",t)}}addBranch(t){let e=this._repo.getMessage(t);if(!e)return 0;let s={id:G(),role:"assistant",content:"",status:"pending",timestamp:Date.now()};return this._repo.addOrUpdateMessage(e.parentId,s),this._repo.switchToBranch(s.id),this._reRenderActivePath(),this._repo.getBranches(s.id).indexOf(s.id)}addSiblingOf(t,e){let s=this._repo.getMessage(t);if(!s)return null;let i=s.message.role==="user"?t:s.parentId,r={...e};return Ot(e)&&(r.isStreaming=!0),this._repo.addOrUpdateMessage(i,r),this._repo.switchToBranch(e.id),this._reRenderActivePath(),e.id}navigateBranch(t,e){if(this._busy)return;let s=this._repo.getBranches(t),i=s.indexOf(t);if(i===-1)return;let r=e==="prev"?i-1:i+1;r<0||r>=s.length||(this._isAutoScrollEnabled=this._isAtBottom(),this._updateScrollButton(),this._repo.switchToBranch(s[r]),this._reRenderActivePath())}truncateResponsesAfter(t){let e=this._repo.getMessages();if(this._repo.clearChildren(t),!this._frameworkManagedDOM){let s=this.querySelector(".aparte-messages-wrapper");if(s){let i=e.findIndex(a=>a.id===t),r=i>=0?e.slice(i+1):[];for(let a of r)s.querySelector(`aparte-chat-bubble[message-id="${K(a.id)}"]`)?.remove()}}}truncateFrom(t){let e=this._repo.getMessages(),s=e.findIndex(r=>r.id===t);if(s===-1)return;let i=e.slice(s).map(r=>r.id);if(this._repo.resetHead(t),!this._frameworkManagedDOM){let r=this.querySelector(".aparte-messages-wrapper");for(let a of i)r?.querySelector(`aparte-chat-bubble[message-id="${K(a)}"]`)?.remove()}}getMessage(t){return this._repo.getMessageById(t)}getMessages(){return this._repo.getMessages()}exportTree(){return this._repo.export()}importTree(t){this.clearAll({revokeAttachments:!1});let e=T(this).getStreamBlocks();this._repo.import({...t,messages:t.messages.map(s=>{let i=Ma(s.message,e),r=Oe(i);return xa(i)&&In(r),{...s,message:r}})}),this._reRenderActivePath()}clearAll(t){if(t?.revokeAttachments!==!1)for(let e of this._repo.getAllMessages())ia(e.attachments);if(this._repo.clear(),this._syncBusy(),!this._frameworkManagedDOM){let e=this.querySelector(".aparte-messages-wrapper");e&&Array.from(e.querySelectorAll("aparte-chat-bubble")).forEach(s=>s.remove())}this._setSpacerHeight(0),this._isAutoScrollEnabled=!0,this._updateScrollButton(),this._checkpointState?.clear(),this.dispatchEvent(new CustomEvent("aparte-reset-done",{bubbles:!0,composed:!0}))}setMessages(t){this.clearAll({revokeAttachments:!1}),this._bulkAppend=!0;try{for(let e of t)this.appendMessage(e,{historical:!0})}finally{this._bulkAppend=!1}this._pruneRenderedBubbles(),this._syncBusy(),t.some(e=>e.role==="user")&&(this._isAutoScrollEnabled=!0),this._recalculateSpacer(),this._autoScroll()}scrollToBottom(){this._scrollToBottom()}resetSpacer(){this._setSpacerHeight(0),this._layoutTransitionMs>0&&(this._spacerFrozenUntil=Date.now()+this._layoutTransitionMs)}setAutoScroll(t){this._isAutoScrollEnabled=t,t||(this._readerInputAt=performance.now())}setFrameworkManagedDOM(t){this._frameworkManagedDOM=t}_getOrCreateMessage(t){let e=this._repo.getMessageById(t);if(e)return e;let s={id:t,role:"assistant",content:"",timestamp:Date.now(),isStreaming:!0,status:"streaming"};return this._repo.addOrUpdateMessage(this._repo.headId,s),s}_notifyBubble(t,e,s,i){let r=this.querySelector(`aparte-chat-bubble[message-id="${K(t)}"], [data-aparte-bubble][message-id="${K(t)}"]`);if(r)switch(e){case"appendToken":r.appendToken?.(s);break;case"appendToSegment":r.appendToSegment?.(i,s);break;case"addSegment":r.addSegment?.(s);break;case"updateSegment":{let{segmentId:a,updates:o}=s;r.updateSegment?.(a,o);break}case"removeSegment":r.removeSegment?.(s);break;case"setUsage":r.setUsage?.(s);break;case"update":{let a=s;["status","segments","content","attachments","usage","finishReason","contextSummary","compaction"].some(l=>l in a)&&r.updateMessage?.(s);break}case"complete":r.updateMessage?.(s);break}}_syncDateSeparators(){let t=T(this),e=t.getDateSeparators();if(!e&&!this.querySelector("aparte-chat-bubble[data-date]"))return;let s=new Date,i=o=>new Date(o.getFullYear(),o.getMonth(),o.getDate()).getTime(),r=i(s),a=null;this.querySelectorAll("aparte-chat-bubble").forEach(o=>{let l=Number(o.getAttribute("timestamp")),c=l?new Date(l):null,d=c?i(c):null,u=e&&c&&d!==a;if(d!==null&&(a=d),!u||!c){o.hasAttribute("data-date")&&o.removeAttribute("data-date");return}let h=Math.round((r-d)/864e5),p=h===0?t.t("conversationGroupToday"):h===1?t.t("conversationGroupYesterday"):Fd(c,t.getLocale().tag);o.getAttribute("data-date")!==p&&o.setAttribute("data-date",p)})}_reRenderActivePath(){let t=this._repo.getMessages(),e=t.map(r=>{let a=this._repo.getBranches(r.id);return{id:r.id,count:a.length,index:a.indexOf(r.id)}});if(this._frameworkManagedDOM){this._dispatchPathChanged(t,e);return}let s=this.querySelector(".aparte-messages-wrapper");if(!s)return;s.innerHTML="";let i=Math.max(0,t.length-this._maxRenderedBubbles);for(let r=i;r<t.length;r++){let a=t[r],o=e[r],l=document.createElement("aparte-chat-bubble");l.setAttribute("message-id",a.id),l.setAttribute("data-role",a.role),a.compaction&&l.setAttribute("data-kind","compaction"),a.timestamp&&l.setAttribute("timestamp",String(a.timestamp)),Ot(a)&&l.setAttribute("streaming",""),s.appendChild(l),mn(l,a,o)}this._syncDateSeparators(),this._dispatchPathChanged(t,e),this._syncBusy(),this._checkpointState?.reapply(),this._recalculateSpacer()}_dispatchPathChanged(t,e){let s={messages:t,siblings:e};this.dispatchEvent(new CustomEvent("aparte-path-changed",{bubbles:!0,composed:!0,detail:s}))}_autoScroll(){this._isAutoScrollEnabled&&requestAnimationFrame(()=>{this._isAutoScrollEnabled&&this._scrollToBottom()}),this._pruneRenderedBubbles()}requestSmoothScroll(){this._smoothScrollOnce=!0}_render(){if(this._frameworkManagedDOM){this._setupFrameworkDOM();return}if(this.querySelector(".aparte-viewport-container"))this._container=this.querySelector(".aparte-viewport-container"),this._scrollBtn=this.querySelector(".aparte-scroll-btn"),this._bottomSpacer=this.querySelector(".aparte-bottom-spacer");else{let t=document.createElement("div");t.className="aparte-viewport-container";let e=T(this).getLocale();e.direction&&t.setAttribute("dir",e.direction),t.setAttribute("role","log"),t.setAttribute("aria-live","polite"),t.setAttribute("aria-atomic","false"),t.setAttribute("aria-relevant","additions"),this._nameScrollSurface(t);let s=document.createElement("div");for(s.className="aparte-messages-wrapper";this.firstChild;)s.appendChild(this.firstChild);this._bottomSpacer=document.createElement("div"),this._bottomSpacer.className="aparte-bottom-spacer",this._bottomSpacer.setAttribute("aria-hidden","true"),s.appendChild(this._bottomSpacer),t.appendChild(s),this.appendChild(t),this._container=t,this._syncLoading(),this._scrollBtn=document.createElement("button"),this._scrollBtn.className="aparte-btn aparte-btn--surface aparte-btn--circle aparte-btn--lg aparte-scroll-btn aparte-scroll-btn--hidden",this._scrollBtn.setAttribute("type","button"),this._scrollBtn.setAttribute("aria-label",T(this).t("scrollToBottom"));let i=T(this).getIcon("scrollDown");this._scrollBtn.innerHTML=i,this.appendChild(this._scrollBtn)}}_setupFrameworkDOM(){if(this._container=this,this._bottomSpacer=null,this.classList.contains("aparte-viewport--framework")){this._scrollBtn=this.querySelector(":scope > .aparte-scroll-btn");return}this.classList.add("aparte-viewport--framework"),this._nameScrollSurface(this),this._applyDirection();let t=document.createElement("button");t.className="aparte-btn aparte-btn--surface aparte-btn--circle aparte-btn--lg aparte-scroll-btn aparte-scroll-btn--hidden",t.setAttribute("type","button"),t.setAttribute("aria-label",T(this).t("scrollToBottom"));let e=T(this).getIcon("scrollDown");t.innerHTML=e,this.appendChild(t),this._scrollBtn=t}_keepScrollButtonLast(){this._scrollBtn&&this.lastElementChild!==this._scrollBtn&&this.appendChild(this._scrollBtn)}_getSpacerHeight(){return this._frameworkManagedDOM?this._fwSpacerHeight:this._bottomSpacer?.offsetHeight??0}_setSpacerHeight(t){this._frameworkManagedDOM?(this._fwSpacerHeight=t,this.style.setProperty("--aparte-fw-spacer",`${t}px`)):this._bottomSpacer&&(this._bottomSpacer.style.height=`${t}px`)}_onScrollBtnClick=()=>{this._isAutoScrollEnabled=!0,this._smoothScrollToBottom(),this._updateScrollButton()};_pointerHeld=!1;_holdPointer=()=>{this._pointerHeld=!0};_releasePointer=()=>{this._pointerHeld=!1};_noteReaderInput=t=>{if(!(t.type==="keydown"&&!this._scrollKeys.has(t.key))){if(t.type==="pointerdown"){let e=this._container;if(!e)return;let{clientX:s}=t,i=e.getBoundingClientRect();if(!(getComputedStyle(e).direction==="rtl"?s<=i.right-e.clientWidth:s>=i.left+e.clientWidth))return}if(this._readerInputAt=performance.now(),this._gliding()&&this._container&&(this._glideUntil=0,t.type==="wheel"||t.type==="touchmove")){this._ownScrollAt=performance.now();let e=this._container.scrollTop;this._container.scrollTop=e}}};_onBranchNavigate=t=>{let e=t;e.stopPropagation(),this.navigateBranch(e.detail.messageId,e.detail.direction)};_setupEventListeners(){this._container?.addEventListener("scroll",this._handleScroll,{passive:!0}),this._container?.addEventListener("scrollend",this._handleScrollEnd,{passive:!0});for(let t of["wheel","touchmove","pointerdown","keydown"])this._container?.addEventListener(t,this._noteReaderInput,{passive:!0});this._container?.addEventListener("pointerdown",this._holdPointer,{passive:!0}),document.addEventListener("pointerup",this._releasePointer,!0),document.addEventListener("pointercancel",this._releasePointer,!0),this._scrollBtn?.addEventListener("click",this._onScrollBtnClick),this.addEventListener("aparte-branch-navigate",this._onBranchNavigate)}_setupObservers(){this._resizeObserver=new ResizeObserver(()=>{this._updateOverlayInset(),this._updateTranscriptInset(),this._isAutoScrollEnabled&&this._scrollToBottom(),this._recalculateSpacer(),this._updateScrollButton()});let t=this.querySelector(".aparte-messages-wrapper");this._container&&(this._frameworkManagedDOM?this._resizeObserver.observe(this._container,{box:"border-box"}):this._resizeObserver.observe(this._container)),this._wireOverlay(),this.parentElement&&(this._overlayAttrObserver=new MutationObserver(()=>this._wireOverlay()),this._overlayAttrObserver.observe(this.parentElement,{attributes:!0,attributeFilter:["overlay-composer"]})),this._mutationObserver=new MutationObserver(s=>{if(this._lastMutationAt=performance.now(),s.some(r=>r.type==="childList"&&(r.target===this||r.target.classList?.contains("aparte-messages-wrapper")))&&this._syncDateSeparators(),this._frameworkManagedDOM&&this._keepScrollButtonLast(),this._isAutoScrollEnabled&&!this._gliding()){let r=s.flatMap(o=>Array.from(o.addedNodes)).filter(o=>o instanceof Element&&o.tagName==="APARTE-CHAT-BUBBLE"),a=r.length===1?r[0]:void 0;if(a&&a.getAttribute("data-role")==="user"&&a.parentElement){let o=a.parentElement.querySelectorAll("aparte-chat-bubble");o[o.length-1]===a&&(this._smoothScrollOnce=!0)}}this._isAutoScrollEnabled&&requestAnimationFrame(()=>{this._isAutoScrollEnabled&&this._scrollToBottom()}),this._scheduleSpacerUpdate();let i=r=>Array.from(r).some(a=>a instanceof Element&&(a.tagName==="APARTE-CHAT-BUBBLE"||a.querySelector("aparte-chat-bubble")!==null));s.some(r=>i(r.addedNodes)||i(r.removedNodes))&&this._observeTail()}),this._tailObserver=new ResizeObserver(s=>{let i=!1;for(let r of s){let a=Math.round(r.borderBoxSize?.[0]?.blockSize??r.contentRect.height);this._tailHeights.get(r.target)!==a&&(i=!0),this._tailHeights.set(r.target,a)}i&&this._scheduleSpacerUpdate()}),this._observeTail(),this.addEventListener("toggle",this._onDisclosureToggle,!0);let e=this._frameworkManagedDOM?this:t;e&&this._mutationObserver.observe(e,{childList:!0,subtree:!0})}_wireOverlay(){let t=this.closest("[overlay-composer]");if(t!==this._overlayRoot){for(let e of this._overlayStack())this._resizeObserver?.unobserve(e);if(this._overlayObserver?.disconnect(),this._overlayObserver=null,this._overlayRoot=t,this._overlayInset=-1,this.style.removeProperty("--aparte-bottom-inset"),!(!t||!this._resizeObserver)){for(let e of this._overlayStack())this._resizeObserver.observe(e);this._overlayObserver=new MutationObserver(()=>{for(let e of this._overlayStack())this._resizeObserver?.observe(e);this._updateOverlayInset()}),this._overlayObserver.observe(t,{childList:!0}),this._updateOverlayInset()}}}_overlayStack(){return this._overlayRoot?Array.from(this._overlayRoot.children).filter(t=>t instanceof HTMLElement&&t!==this&&t.tagName.toLowerCase()!=="aparte-scroll-rail"):[]}_updateOverlayInset(){if(!this._overlayRoot)return;let t=this.getBoundingClientRect().bottom,e=1/0;for(let i of this._overlayStack()){let r=i.getBoundingClientRect();r.height>0&&(e=Math.min(e,r.top))}let s=e===1/0?0:Math.max(0,Math.round(t-e));s!==this._overlayInset&&(this._overlayInset=s,this.style.setProperty("--aparte-bottom-inset",`${s}px`))}_updateTranscriptInset(){let t=this.parentElement;if(!t)return;let e=this.querySelector(".aparte-messages-wrapper")??this._container??this,s=parseFloat(getComputedStyle(e).paddingInlineStart)||0,i=getComputedStyle(t).direction==="rtl",r=e.getBoundingClientRect(),a=t.getBoundingClientRect(),o=i?a.right-r.right:r.left-a.left,l=Math.max(0,Math.round((o+s)*10)/10);l!==this._transcriptInset&&(this._transcriptInset=l,t.style.setProperty("--aparte-transcript-inset",`${l}px`))}_isAtBottom(){if(!this._container)return!0;let{scrollTop:t,scrollHeight:e,clientHeight:s}=this._container;return e-t-s<=this._scrollThreshold}_handleScroll(){if(!this._container)return;let t=this._container.scrollTop,e=this._container.scrollHeight,s=this._lastScrollTop-t,i=Math.abs(e-this._lastScrollHeight),r=performance.now(),a=e<this._lastScrollHeight-1,o=r-this._lastMutationAt<this._settleShadowMs&&s<=this._settleBoundPx,l=r-this._ownScrollAt<this._ownScrollWindowMs&&r-this._readerInputAt>=this._ownScrollWindowMs&&!this._pointerHeld&&(s<=i+2||a||o),c=s>1&&!l,d=s>1&&r-this._readerInputAt<this._ownScrollWindowMs;this._lastScrollTop=t,this._lastScrollHeight=e,this._isAtBottom()&&!d?this._isAutoScrollEnabled=!0:c?this._isAutoScrollEnabled=!1:s>1&&l&&this._isAutoScrollEnabled&&this._settleAtBottom(),this._updateScrollButton()}_scrollToBottom(){if(this._container){if(this._smoothScrollOnce){this._smoothScrollOnce=!1,this._smoothScrollToBottom();return}if(this._gliding()){this._retargetGlide();return}this._ownScrollAt=performance.now(),this._container.scrollTop=this._container.scrollHeight,this._settleAtBottom()}}_gliding(){return performance.now()<this._glideUntil}_retargetGlide(){this._container&&(this._ownScrollAt=performance.now(),this._armGlide(),this._container.scrollTo({top:this._container.scrollHeight,behavior:"smooth"}))}_armGlide(){this._glideUntil=performance.now()+this._glideWindowMs,this._glideSettleTimer!==null&&clearTimeout(this._glideSettleTimer),this._glideSettleTimer=setTimeout(()=>{if(this._glideSettleTimer=null,!this._container||!this._isAutoScrollEnabled||this._gliding())return;let t=this._container.scrollHeight-this._container.clientHeight;this._container.scrollTop<this._lastScrollTop-1||t-this._container.scrollTop>1&&this._scrollToBottom()},this._glideWindowMs+16)}_handleScrollEnd(){if(!this._container)return;this._container.scrollHeight-this._container.clientHeight-this._container.scrollTop<=1&&(this._glideUntil=0)}_settleAtBottom(){if(this._settleUntil=performance.now()+this._settleWindowMs,this._settleRafId!==null)return;let t=()=>{if(this._settleRafId=null,!this.isConnected||!this._container||!this._isAutoScrollEnabled){this._settleUntil=0;return}let e=this._container.scrollHeight-this._container.clientHeight;e-this._container.scrollTop>1&&!this._gliding()&&(this._ownScrollAt=performance.now(),this._container.scrollTop=e),performance.now()<this._settleUntil?this._settleRafId=requestAnimationFrame(t):this._settleUntil=0};this._settleRafId=requestAnimationFrame(t)}_smoothScrollToBottom(){this._container&&(this._ownScrollAt=performance.now(),typeof this._container.scrollTo=="function"&&!this._prefersReducedMotion()?(this._armGlide(),this._container.scrollTo({top:this._container.scrollHeight,behavior:"smooth"})):this._container.scrollTop=this._container.scrollHeight)}_prefersReducedMotion(){return typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion: reduce)").matches}_updateScrollButton(){let t=this._scrollBtn;if(!t)return;let e=this._isAtBottom();t.classList.contains("aparte-scroll-btn--hidden")===e&&t.hasAttribute("tabindex")===e||(t.classList.toggle("aparte-scroll-btn--hidden",e),e?(t.setAttribute("tabindex","-1"),t.setAttribute("aria-hidden","true")):(t.removeAttribute("tabindex"),t.removeAttribute("aria-hidden")))}_recalculateSpacer(){if(!this._container||!this._frameworkManagedDOM&&!this._bottomSpacer||Date.now()<this._spacerFrozenUntil)return;let t=Array.from(this.querySelectorAll("aparte-chat-bubble"));if(t.length===0){this._setSpacerHeight(0);return}let e=[...t].reverse().find(h=>h.getAttribute("data-role")==="user");if(!e){this._setSpacerHeight(0);return}let s=this._getSpacerHeight(),i=this._container.getBoundingClientRect(),a=e.getBoundingClientRect().top-i.top+this._container.scrollTop,o=this._container.scrollHeight-s;if(o<=this._container.clientHeight){this._setSpacerHeight(0);return}let l=o-a,c=parseFloat(getComputedStyle(this._container).scrollPaddingTop)||0,d=this._container.clientHeight-c-l,u=this._container.clientHeight;this._setSpacerHeight(Math.min(Math.max(0,d),u)),this._isAutoScrollEnabled&&this._scrollToBottom()}_observeTail(){if(!this._tailObserver)return;let t=Array.from(this.querySelectorAll("aparte-chat-bubble")),e=t.length;for(;e>0&&t[e-1].getAttribute("data-role")!=="user";)e--;let s=e>0?t.slice(e-1):[];for(let i of this._tail)s.includes(i)||this._tailObserver.unobserve(i);for(let i of s)this._tail.includes(i)||(this._tailHeights.set(i,Math.round(i.offsetHeight)),this._tailObserver.observe(i,{box:"border-box"}));this._tail=s}_scheduleSpacerUpdate(){this._spacerRafId===null&&(this._spacerRafId=requestAnimationFrame(()=>{this._spacerRafId=null,this._recalculateSpacer(),this._updateScrollButton()}))}_pruneRenderedBubbles(){if(this._frameworkManagedDOM)return;let t=this.querySelector(".aparte-messages-wrapper");if(!t)return;let e=t.querySelectorAll("aparte-chat-bubble"),s=e.length-this._maxRenderedBubbles;for(let i=0;i<s;i++)e[i]?.remove()}_cleanup(){this._container?.removeEventListener("scroll",this._handleScroll),this._container?.removeEventListener("scrollend",this._handleScrollEnd),this._glideSettleTimer!==null&&(clearTimeout(this._glideSettleTimer),this._glideSettleTimer=null);for(let t of["wheel","touchmove","pointerdown","keydown"])this._container?.removeEventListener(t,this._noteReaderInput);this._container?.removeEventListener("pointerdown",this._holdPointer),document.removeEventListener("pointerup",this._releasePointer,!0),document.removeEventListener("pointercancel",this._releasePointer,!0),this._pointerHeld=!1,this._scrollBtn?.removeEventListener("click",this._onScrollBtnClick),this.removeEventListener("aparte-branch-navigate",this._onBranchNavigate),this._resizeObserver?.disconnect(),this._mutationObserver?.disconnect(),this._tailObserver?.disconnect(),this._tailObserver=null,this._tail=[],this.removeEventListener("toggle",this._onDisclosureToggle,!0),this._overlayObserver?.disconnect(),this._overlayObserver=null,this._overlayAttrObserver?.disconnect(),this._overlayAttrObserver=null,this._overlayRoot=null,this._overlayInset=-1,this._transcriptInset=-1,this._resizeObserver=null,this._mutationObserver=null,this._spacerRafId!==null&&(cancelAnimationFrame(this._spacerRafId),this._spacerRafId=null),this._settleRafId!==null&&(cancelAnimationFrame(this._settleRafId),this._settleRafId=null),this._settleUntil=0}};H(Ye);customElements.get("aparte-chat-viewport")||customElements.define("aparte-chat-viewport",Ye);var Wd=new Set(["text","search","email","url","tel","number","password"]);function Ud(n){return n instanceof HTMLTextAreaElement?n.rows===1:n instanceof HTMLInputElement&&Wd.has(n.type)}var Je=class n extends HTMLElement{_value="";_streaming=!1;_attachments=[];_listeners=new Map;_panelActive=!1;_panelMode="submit";_panelSubmitEnabled=!1;_panelOnSubmit=null;_panelToken=null;_panelOnEvict=null;static _STATE_EVENTS=new Set(["value-change","streaming-change","disabled-change","attachments-change","panel-change"]);_onMessageStart=this._handleMessageStart.bind(this);_onMessageDone=this._handleMessageDone.bind(this);get _cfg(){return T(this)}_onConfigChangeEvent=t=>{let e=t.detail;e?.config&&e.config!==this._cfg||this._onConfigChange()};_modelGated=!1;_onConfigChange=()=>{this._evaluateModelGate(),this._applyDirection()};_applyDirection(){let t=(this._cfg??T(this)).getLocale().direction;t?this.setAttribute("dir",t):this.removeAttribute("dir")}static get observedAttributes(){return["placeholder","disabled","target"]}connectedCallback(){window.addEventListener("aparte-message-start",this._onMessageStart),window.addEventListener("aparte-message-done",this._onMessageDone),window.addEventListener("aparte-message-error",this._onMessageDone),window.addEventListener("aparte-message-aborted",this._onMessageDone),window.addEventListener("aparte-config-change",this._onConfigChangeEvent),queueMicrotask(()=>this._warnIfUnattached()),this._evaluateModelGate(),this._applyDirection()}disconnectedCallback(){window.removeEventListener("aparte-message-start",this._onMessageStart),window.removeEventListener("aparte-message-done",this._onMessageDone),window.removeEventListener("aparte-message-error",this._onMessageDone),window.removeEventListener("aparte-message-aborted",this._onMessageDone),window.removeEventListener("aparte-config-change",this._onConfigChangeEvent),this._listeners.clear()}attributeChangedCallback(t,e,s){if(t==="disabled"&&this._emit("disabled-change",{disabled:s!==null}),t==="placeholder")for(let i of this.querySelectorAll("aparte-composer-input"))i.syncPlaceholder?.()}get value(){return this._value}get streaming(){return this._streaming}get disabled(){return this.hasAttribute("disabled")}set disabled(t){this.toggleAttribute("disabled",z(t))}get submitOnEnter(){return this.getAttribute("submit-on-enter")!=="false"}get attachments(){return this._attachments}get placeholder(){return this.getAttribute("placeholder")??""}set placeholder(t){t==null?this.removeAttribute("placeholder"):this.setAttribute("placeholder",String(t))}get targetId(){return this.getAttribute("target")}getState(){return{value:this._value,streaming:this._streaming,disabled:this.disabled,attachments:[...this._attachments],panelActive:this._panelActive,submitEnabled:this._panelSubmitEnabled}}setValue(t){this._value=t,this._emit("value-change",{value:t})}addAttachments(t){this._attachments=[...this._attachments,...Array.from(t)],this._emit("attachments-change",{attachments:this._attachments})}setAttachmentState(t,e){e?this._attachmentStates.set(t,e):this._attachmentStates.delete(t),this._syncUploading(),this.querySelector("aparte-composer-attachments")?.showState(t,e)}getAttachmentState(t){return this._attachmentStates.get(t)}_attachmentStates=new WeakMap;get _uploading(){return this._attachments.some(t=>this._attachmentStates.get(t)?.status==="uploading")}_syncUploading(){this.toggleAttribute("data-uploading",this._uploading)}removeAttachment(t){this._attachments=this._attachments.filter(e=>e!==t),this._syncUploading(),this._emit("attachments-change",{attachments:this._attachments})}clearAttachments(){this._attachments=[],this._syncUploading(),this._emit("attachments-change",{attachments:[]})}showPanel(t,e){this._evictPanel();let s=this.querySelector("[data-aparte-panel-host]"),i=this.querySelector("aparte-composer-input");this.setAttribute("data-panel-active",""),t.dataset.apartePanel="true",t.addEventListener("keydown",this._onPanelKeydown),s?s.appendChild(t):i?i.insertAdjacentElement("afterend",t):this.appendChild(t),this._panelActive=!0,this._panelSubmitEnabled=e?.submitEnabled??!1,this._panelMode=e?.mode??"submit",this._reflectPanelMode(),this._panelOnSubmit=e?.onSubmit??null,this._panelOnEvict=e?.onEvict??null;let r=Symbol("aparte-composer-panel");return this._panelToken=r,this._emit("panel-change",{active:!0,submitEnabled:this._panelSubmitEnabled,mode:this._panelMode}),r}hidePanel(t){if(t!==void 0){if(t!==this._panelToken)return;this._teardownPanel();return}this._evictPanel()}_onPanelKeydown=t=>{t.key!=="Enter"||t.isComposing||t.keyCode===229||t.defaultPrevented||!Ud(t.target)||!(this.submitOnEnter?!t.shiftKey:t.shiftKey)||(t.preventDefault(),this.submit())};_evictPanel(){let t=this._panelOnEvict;this._teardownPanel(),t?.()}_teardownPanel(){let t=document.activeElement,e=t instanceof Node&&this.contains(t),s=this.querySelector("[data-aparte-panel]");s&&s.remove(),this.removeAttribute("data-panel-active"),this._panelActive=!1,this._panelSubmitEnabled=!1,this._panelMode="submit",this._reflectPanelMode(),this._panelOnSubmit=null,this._panelOnEvict=null,this._panelToken=null,this._emit("panel-change",{active:!1,submitEnabled:!1,mode:"submit"}),e&&this.focus()}setPanelSubmitEnabled(t,e){this._panelActive&&(this._panelSubmitEnabled=t,e&&(this._panelMode=e),this._reflectPanelMode(),this._emit("panel-change",{active:!0,submitEnabled:t,mode:this._panelMode}))}_reflectPanelMode(){this._panelActive?this.setAttribute("data-panel-mode",this._panelMode):this.removeAttribute("data-panel-mode")}get panelActive(){return this._panelActive}_evaluateModelGate(){let t=this._cfg.getRequireModelSelection()&&!this._cfg.hasSelectedModel();t!==this._modelGated&&(this._modelGated=t,this.toggleAttribute("data-model-gated",t))}submit(){if(this._panelActive){this._panelMode!=="none"&&this._panelSubmitEnabled&&this._panelOnSubmit?.();return}if(this._streaming){this.cancel();return}let t=this._value.trim();if(!t&&this._attachments.length===0||this.disabled||this._modelGated||this._uploading)return;this._emit("submit",{value:t,attachments:this._attachments});let e=this.querySelector("aparte-composer-input")?.getTokens?.(),s={content:t,timestamp:Date.now(),targetId:this._ownTargetId(),files:this._attachments.length>0?[...this._attachments]:void 0,...e?.length?{tokens:e}:{}};this.dispatchEvent(new CustomEvent("aparte-send",{bubbles:!0,composed:!0,detail:s})),this.setValue(""),this.clearAttachments()}cancel(){this._emit("cancel",{}),this.dispatchEvent(new CustomEvent("aparte-cancel",{bubbles:!0,composed:!0}));let t={targetId:this._ownTargetId()};window.dispatchEvent(new CustomEvent("aparte-abort",{bubbles:!1,detail:t})),window.dispatchEvent(new CustomEvent("aparte-message-aborted",{bubbles:!1,detail:t}))}reset(){this.setValue(""),this.clearAttachments(),this._panelActive&&this._evictPanel()}focus(){this.querySelector("aparte-composer-input")?.focus()}_emit(t,e){this._listeners.get(t)?.forEach(s=>s(e)),n._STATE_EVENTS.has(t)&&this.dispatchEvent(new CustomEvent("aparte-composer-change",{bubbles:!0,composed:!0,detail:{state:this.getState(),composer:this}}))}_on(t,e){return this._listeners.has(t)||this._listeners.set(t,new Set),this._listeners.get(t).add(e),()=>this._listeners.get(t)?.delete(e)}_isForThisComposer(t){let e=t.detail?.targetId;return!e||!this._ownTargetId()||e===this._ownTargetId()}_warnIfUnattached(){!this.isConnected||this._ownTargetId()||document.querySelectorAll("aparte-chat, [data-aparte-chat]").length<2||console.warn(`[aparte-composer] this composer belongs to no chat while the page has several: give it target="<chat id>" or place it under a chat host with an id, or it will answer to every chat's events.`)}_ownTargetId(){let t=this.targetId;if(t)return t;let e=this.parentElement;for(;e;){if((e.tagName?.toLowerCase()==="aparte-chat"||e.hasAttribute?.("data-aparte-chat"))&&e.id)return e.id;e=e.parentElement}}_streamingMessageId=null;_isForThisTurn(t){let e=t.detail?.messageId;return!e||this._streamingMessageId===null||e===this._streamingMessageId}_handleMessageStart(t){this._isForThisComposer(t)&&(this._streamingMessageId=t.detail?.messageId??null,this._streaming=!0,this._emit("streaming-change",{streaming:!0}))}_handleMessageDone(t){!this._isForThisComposer(t)||!this._isForThisTurn(t)||(this._streamingMessageId=null,this._streaming=!1,this._emit("streaming-change",{streaming:!1}),this._panelActive&&this._evictPanel())}};H(Je);customElements.get("aparte-composer")||customElements.define("aparte-composer",Je);function Ka(n,t){let e=(n??"").split(",").map(r=>r.trim().toLowerCase()).filter(Boolean);if(e.length===0)return!0;let s=t.name.toLowerCase(),i=t.type.toLowerCase();return e.some(r=>r.startsWith(".")?s.endsWith(r):r.endsWith("/*")?i.startsWith(r.slice(0,-1)):i===r)}var Rn="data-aparte-token",Va="data-aparte-text",jd="\uFFFC",ie=n=>n.nodeType===Node.TEXT_NODE,Gd=n=>n.nodeType===Node.ELEMENT_NODE&&n.hasAttribute(Rn),Ya=n=>Array.prototype.indexOf.call(n.parentNode.childNodes,n);function re(n,t=[]){return n.childNodes.forEach(e=>{ie(e)||e.nodeName==="BR"||Gd(e)?t.push(e):re(e,t)}),t}var Ja=n=>ie(n)?n.data.length:1;function zd(n){return re(n).map(t=>ie(t)?t.data:t.nodeName==="BR"?`
|
|
140
|
+
`:jd).join("")}function Kd(n,t,e){let s=n.ownerDocument.createRange();s.setStart(t,e),s.collapse(!0);let i=0;for(let r of re(n)){if(r===t)return i+e;if(s.comparePoint(r.parentNode,Ya(r))>=0)return i;i+=Ja(r)}return i}function Ia(n,t){let e=t;for(let s of re(n)){if(ie(s)&&e<=s.data.length)return[s,e];if(e===0)return[s.parentNode,Ya(s)];e-=Ja(s)}return[n,n.childNodes.length]}function La(n,t,e){let s=n.ownerDocument.createRange();return s.setStart(...Ia(n,t)),s.setEnd(...Ia(n,e)),s}function Ra(n,t,e){let s=n.createElement("span");s.className="aparte-tag aparte-inline-token",s.setAttribute("contenteditable","false"),s.setAttribute(Rn,t),s.setAttribute(Va,e.text??e.label),e.kind&&(s.dataset.kind=e.kind);let i=n.createElement("span");return i.className="aparte-tag__label",i.textContent=e.label,s.appendChild(i),s}function Oa(n,t){let e="",s=[];for(let r of re(n))if(ie(r))e+=r.data;else if(r.nodeName==="BR")e+=`
|
|
141
|
+
`;else{let a=r,o=t.get(a.getAttribute(Rn)??""),l=a.getAttribute(Va)??a.textContent??"",c=e.length;e+=l,s.push({label:a.textContent??"",text:l,start:c,end:e.length,...a.dataset.kind?{kind:a.dataset.kind}:{},...o?.data!==void 0?{data:o.data}:{}})}let i=e.length-e.trimStart().length;return{value:e.trim(),tokens:s.map(r=>({...r,start:r.start-i,end:r.end-i}))}}var Xe=class extends HTMLElement{_editor=null;_maxHeight=200;_minHeight=44;_resizeObserver=null;_unsubscribes=[];_onInput=this._handleInput.bind(this);_onKeydown=this._handleKeydown.bind(this);_onFocus=this._handleFocus.bind(this);_onBlur=this._handleBlur.bind(this);_onPaste=this._handlePaste.bind(this);static get observedAttributes(){return["placeholder","max-height","min-height","disabled"]}connectedCallback(){this._render(),this._editor=this.querySelector(".aparte-ci-editor"),this._editor?.addEventListener("input",this._onInput),this._editor?.addEventListener("keydown",this._onKeydown),this._editor?.addEventListener("focus",this._onFocus),this._editor?.addEventListener("blur",this._onBlur),this._editor?.addEventListener("paste",this._onPaste),this._connectToRoot(),this._scheduleInitialReflow(),this._editor&&typeof ResizeObserver=="function"&&(this._resizeObserver=new ResizeObserver(()=>this._adjustHeight()),this._resizeObserver.observe(this._editor)),this._unsubscribes.push(gt(this,()=>this._updatePlaceholder()))}disconnectedCallback(){this._editor?.removeEventListener("input",this._onInput),this._editor?.removeEventListener("keydown",this._onKeydown),this._editor?.removeEventListener("focus",this._onFocus),this._editor?.removeEventListener("blur",this._onBlur),this._editor?.removeEventListener("paste",this._onPaste),this._resizeObserver?.disconnect(),this._resizeObserver=null,this._unsubscribes.forEach(t=>t()),this._unsubscribes=[]}attributeChangedCallback(t,e,s){t==="placeholder"&&this._updatePlaceholder(),t==="max-height"&&(this._maxHeight=parseInt(s||"200",10)),t==="min-height"&&(this._minHeight=parseInt(s||"44",10)),t==="disabled"&&this._updateDisabled(s!==null)}getValue(){return this._editor?Oa(this._editor,this._tokens).value:""}getTokens(){return this._editor?Oa(this._editor,this._tokens).tokens:[]}getCaret(){let t=this.ownerDocument?.getSelection();return!this._editor||!t?.rangeCount||!t.isCollapsed||!this._editor.contains(t.anchorNode)?null:{text:zd(this._editor),offset:Kd(this._editor,t.anchorNode,t.anchorOffset)}}getRangeRect(t,e=t){return this._editor?La(this._editor,t,e).getClientRects?.()[0]??null:null}replaceRange(t,e,s){this._write(t,e,()=>s?this._insertPlain(s):this._exec("delete"),()=>this.ownerDocument.createTextNode(s))}insertToken(t,e,s){let i=String(++this._lastTokenId);this._tokens.set(i,s);let r=this.ownerDocument,a=()=>{let o=r.createDocumentFragment();return o.append(Ra(r,i,s),r.createTextNode(" ")),o};this._write(t,e,()=>this._exec("insertHTML",`${Ra(r,i,s).outerHTML} `),a)}setValue(t){this._editor&&(this._editor.textContent=t,this._tokens.clear(),this._updatePlaceholderVisibility(),this._adjustHeight(),this._getRoot()?.setValue(t))}clear(){this._editor&&(this._editor.innerHTML="",this._tokens.clear(),this._updatePlaceholderVisibility(),this._adjustHeight(),this._getRoot()?.setValue(""))}syncPlaceholder(){this._updatePlaceholder()}focus(){this._editor?.focus()}blur(){this._editor?.blur()}focusEnd(){if(!this._editor)return;this._editor.focus();let t=this.ownerDocument?.getSelection();if(!t)return;let e=this.ownerDocument.createRange();e.selectNodeContents(this._editor),e.collapse(!1),t.removeAllRanges(),t.addRange(e)}_getRoot(){return this.closest("aparte-composer")}_tokens=new Map;_lastTokenId=0;_write(t,e,s,i){let r=this._editor,a=this.ownerDocument?.getSelection();if(!r||!a)return;r.focus();let o=La(r,t,e);if(a.removeAllRanges(),a.addRange(o),s())return;o.deleteContents();let l=i(),c=l.nodeType===Node.DOCUMENT_FRAGMENT_NODE?l.lastChild:l;o.insertNode(l),o.setStartAfter(c),o.collapse(!0),a.removeAllRanges(),a.addRange(o),this._handleInput()}_exec(t,e){try{return this.ownerDocument.execCommand(t,!1,e)}catch{return!1}}_insertPlain(t){return/[\r\n]/.test(t)?this._exec("insertHTML",L(t).replace(/\r\n?|\n/g,"<br>")):this._exec("insertText",t)}_getPlaceholder(){return this.getAttribute("placeholder")||this._getRoot()?.placeholder||T(this).t("inputPlaceholder")||"Type a message..."}_render(){if(this.querySelector(".aparte-ci-editor"))return;let t=this.hasAttribute("disabled")||this._getRoot()?.disabled||!1,e=x(this._getPlaceholder());this.innerHTML=`<div
|
|
142
|
+
class="aparte-ci-editor"
|
|
143
|
+
contenteditable="${!t}"
|
|
144
|
+
role="textbox"
|
|
145
|
+
aria-multiline="true"
|
|
146
|
+
aria-label="${e}"
|
|
147
|
+
tabindex="${x(String(t?-1:0))}"
|
|
148
|
+
aria-disabled="${t}"
|
|
149
|
+
data-placeholder="${e}"
|
|
150
|
+
></div>`,this._editor=this.querySelector(".aparte-ci-editor"),this._adjustHeight()}_connectToRoot(){let t=this._getRoot();t&&(this._unsubscribes.push(t._on("disabled-change",({disabled:e})=>this._updateDisabled(e))),this._unsubscribes.push(t._on("value-change",({value:e})=>{this.getValue()!==e.trim()&&(e===""?this.clear():this.setValue(e))})))}_handleInput(){this._adjustHeight(),this._editor&&!this._editor.textContent?.trim()&&this._editor.innerHTML!==""&&(this._editor.innerHTML=""),this._updatePlaceholderVisibility();let t=this.getValue();this._getRoot()?.setValue(t)}_handleKeydown(t){if(t.isComposing||t.keyCode===229||t.defaultPrevented||t.key!=="Enter")return;if(this._getRoot()?.submitOnEnter??!0?!t.shiftKey:t.shiftKey){t.preventDefault();let i=this._getRoot();if(i){if(i.streaming)return;i.submit()}else this.dispatchEvent(new CustomEvent("aparte-composer-submit",{bubbles:!0}))}else{if(t.preventDefault(),!this._editor?.textContent)return;this.ownerDocument?.execCommand("insertLineBreak")}}_handleFocus(){this.classList.add("aparte-is-focused")}_handleBlur(){this.classList.remove("aparte-is-focused")}_handlePaste(t){t.preventDefault();let e=t.clipboardData;if(!e)return;let s=this._getRoot(),i=s?.querySelector("aparte-composer-add-attachment"),r=i?Array.from(e.items).find(o=>o.type.startsWith("image/"))?.getAsFile():void 0;if(r&&Ka(i?.getAttribute("accept"),r)){s?.addAttachments([r]);return}let a=e.getData("text/plain");a&&this._insertPlain(a)}_adjustHeight(){if(!this._editor)return;this._editor.style.height="0px";let t=this.hasAttribute("min-height")?this._minHeight:0,e=this._editor.scrollHeight,s=Math.min(Math.max(e,t),this._maxHeight);this._editor.style.height=`${s}px`,this._editor.style.overflowY=e>this._maxHeight?"auto":"hidden"}_scheduleInitialReflow(){typeof requestAnimationFrame=="function"&&requestAnimationFrame(()=>this._adjustHeight()),document.fonts?.ready?.then(()=>this._adjustHeight()).catch(()=>{})}_updatePlaceholder(){if(this._editor){let t=this._getPlaceholder();this._editor.setAttribute("data-placeholder",t),this._editor.setAttribute("aria-label",t)}}_updatePlaceholderVisibility(){}_updateDisabled(t){this._editor&&(this._editor.setAttribute("contenteditable",String(!t)),this._editor.setAttribute("aria-disabled",String(t)),this._editor.setAttribute("tabindex",t?"-1":"0"),t&&this.ownerDocument?.activeElement===this._editor&&this._editor.blur())}};H(Xe);customElements.get("aparte-composer-input")||customElements.define("aparte-composer-input",Xe);var Qe=class extends HTMLElement{_button=null;_unsubscribes=[];_panel=null;_onClick=this._handleClick.bind(this);connectedCallback(){this._render(),this._button=this.querySelector(".aparte-cs-button"),this._button?.addEventListener("click",this._onClick),this._connectToRoot()}disconnectedCallback(){this._button?.removeEventListener("click",this._onClick),this._unsubscribes.forEach(t=>t()),this._unsubscribes=[]}_getRoot(){return this.closest("aparte-composer")}_render(){if(this.querySelector(".aparte-cs-button"))return;let t=T(this).t("sendButton")||"Send",e=this._getSendIcon(),s=this._getRoot(),i=!s||s.disabled||s.value.trim()==="";this.innerHTML=`<button
|
|
151
|
+
type="button"
|
|
152
|
+
class="aparte-btn aparte-btn--primary aparte-btn--solid aparte-btn--icon aparte-cs-button aparte-send-button"
|
|
153
|
+
aria-label="${x(t)}"
|
|
154
|
+
title="${x(t)}"
|
|
155
|
+
data-act="send"
|
|
156
|
+
${i?"disabled":""}
|
|
157
|
+
>${e}</button>`}_connectToRoot(){let t=this._getRoot();t&&(this._unsubscribes.push(t._on("value-change",()=>this._syncState())),this._unsubscribes.push(t._on("disabled-change",()=>this._syncState())),this._unsubscribes.push(t._on("streaming-change",({streaming:e})=>{this._getRoot()?.panelActive||this._syncStreamingState(e)})),this._unsubscribes.push(t._on("attachments-change",()=>this._syncState())),this._unsubscribes.push(t._on("panel-change",e=>{this._panel=e,this._refreshChrome()})),this._unsubscribes.push(gt(this,()=>this._refreshChrome())))}_refreshChrome(){if(this._button){if(this._panel?.active){this._syncPanelState();return}if(this._getRoot()?.streaming){this._syncStreamingState(!0);return}this._syncState()}}_syncPanelState(){let t=this._panel;if(!this._button||!t?.active)return;let e=T(this);if(t.mode==="none"){this._button.disabled=!0;return}this._button.disabled=!t.submitEnabled,this._button.innerHTML=this._getSubmitIcon(),this._button.setAttribute("data-act","submit");let s=e.t("submitButton")||"Submit";this._button.setAttribute("aria-label",s),this._button.setAttribute("title",s),this._button.classList.remove("aparte-is-streaming")}_handleClick(t){t.preventDefault(),this._getRoot()?.submit()}_syncState(){let t=this._getRoot();if(!t||!this._button||t.streaming)return;let e=t.value.trim()===""&&t.attachments.length===0;this._button.disabled=t.disabled||e,this._button.innerHTML=this._getSendIcon(),this._button.setAttribute("data-act","send");let s=T(this).t("sendButton")||"Send";this._button.setAttribute("aria-label",s),this._button.setAttribute("title",s),this._button.classList.remove("aparte-is-streaming")}_syncStreamingState(t){if(this._button)if(t){this._button.disabled=!1,this._button.innerHTML=this._getStopIcon(),this._button.setAttribute("data-act","stop");let e=T(this).t("stopButton")||"Stop";this._button.setAttribute("aria-label",e),this._button.setAttribute("title",e),this._button.classList.add("aparte-is-streaming")}else this._syncState()}_getSubmitIcon(){return T(this).getIcon("check")}_getSendIcon(){return T(this).getIcon("send")||"Send"}_getStopIcon(){return T(this).getIcon("stop")}};H(Qe);customElements.get("aparte-composer-send")||customElements.define("aparte-composer-send",Qe);var Ze=class extends HTMLElement{_button=null;_unsubscribes=[];_onClick=this._handleClick.bind(this);connectedCallback(){this._render(),this._button=this.querySelector(".aparte-cc-button"),this._button?.addEventListener("click",this._onClick),this._connectToRoot(),this._unsubscribes.push(gt(this,()=>this._refreshChrome()))}disconnectedCallback(){this._button?.removeEventListener("click",this._onClick),this._unsubscribes.forEach(t=>t()),this._unsubscribes=[]}_getRoot(){return this.closest("aparte-composer")}_render(){if(this.querySelector(".aparte-cc-button"))return;let t=T(this).t("stopButton")||"Stop",e=this._getStopIcon();this.innerHTML=`<button
|
|
158
|
+
type="button"
|
|
159
|
+
class="aparte-btn aparte-btn--icon aparte-cc-button"
|
|
160
|
+
aria-label="${x(t)}"
|
|
161
|
+
title="${x(t)}"
|
|
162
|
+
hidden
|
|
163
|
+
>${e}</button>`}_connectToRoot(){let t=this._getRoot();t&&(this._unsubscribes.push(t._on("streaming-change",({streaming:e})=>{this._button&&(this._button.hidden=!e)})),t.streaming&&this._button&&(this._button.hidden=!1))}_handleClick(t){t.preventDefault(),this._getRoot()?.cancel()}_refreshChrome(){if(!this._button)return;let t=T(this).t("stopButton")||"Stop";this._button.setAttribute("aria-label",t),this._button.setAttribute("title",t),this._button.innerHTML=this._getStopIcon()}_getStopIcon(){return T(this).getIcon("stop")}};H(Ze);customElements.get("aparte-composer-cancel")||customElements.define("aparte-composer-cancel",Ze);var ts=class extends HTMLElement{_unsubscribes=[];_objectUrls=[];connectedCallback(){this._render([]),this._connectToRoot()}disconnectedCallback(){this._unsubscribes.forEach(t=>t()),this._unsubscribes=[],this._revokeUrls()}_getRoot(){return this.closest("aparte-composer")}_connectToRoot(){let t=this._getRoot();t&&(this._unsubscribes.push(t._on("attachments-change",({attachments:e})=>this._render(e))),this._render(t.attachments))}showState(t,e){let s=this._getRoot()?.attachments.indexOf(t)??-1,i=this.querySelectorAll(".aparte-thumb")[s];if(!i)return;i.toggleAttribute("data-failed",e?.status==="error");let r=i.querySelector(".aparte-progress");if(e?.status!=="uploading"){r?.remove();return}r||(r=document.createElement("div"),r.className="aparte-progress aparte-thumb__progress",r.setAttribute("role","progressbar"),r.setAttribute("aria-label",t.name),r.innerHTML='<div class="aparte-progress__bar"></div>',i.appendChild(r));let a=e.progress!==void 0;r.classList.toggle("aparte-progress--indeterminate",!a),a?(r.setAttribute("aria-valuenow",String(e.progress)),r.setAttribute("aria-valuemin","0"),r.setAttribute("aria-valuemax","100"),r.style.setProperty("--aparte-progress-value",String(e.progress))):r.removeAttribute("aria-valuenow")}_revokeUrls(){this._objectUrls.forEach(t=>URL.revokeObjectURL(t)),this._objectUrls=[]}_render(t){this.hidden=t.length===0,this._revokeUrls();let e=T(this),s=a=>(e.t("removeAttachment")||"Remove {name}").replace("{name}",()=>a.name);this.innerHTML=t.map(a=>{let o=L(a.name),l=`<button class="aparte-btn aparte-btn--icon aparte-btn--sm aparte-thumb__remove" type="button" aria-label="${x(s(a))}">${e.getIcon("close")}</button>`;if(a.type.startsWith("image/")){let c=URL.createObjectURL(a);return this._objectUrls.push(c),`<div class="aparte-thumbnail aparte-thumb aparte-thumb--image" title="${o}"><img class="aparte-thumbnail__image" src="${x(c)}" alt="${o}" /><span class="aparte-thumb__name">${o}</span>${l}</div>`}return`<div class="aparte-thumbnail aparte-thumb aparte-thumb--file" title="${o}"><span class="aparte-thumbnail__label">${L(this._ext(a.name))}</span><span class="aparte-thumb__name">${o}</span>${l}</div>`}).join("");let i=this._getRoot();if(i)for(let a of t){let o=i.getAttachmentState(a);o&&this.showState(a,o)}if(this.querySelectorAll(".aparte-thumb__remove").forEach((a,o)=>{a.addEventListener("click",l=>{l.stopPropagation();let c=this._getRoot();c&&c.removeAttachment(c.attachments[o])})}),!T(this).getHostHandlers().attachmentPreview)return;let r=t.filter(a=>a.type.startsWith("image/"));this.querySelectorAll(".aparte-thumb--image").forEach((a,o)=>{let l=a.querySelector(".aparte-thumbnail__image");if(!l)return;l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-label",r[o]?.name??"");let c=()=>{this.dispatchEvent(new CustomEvent("aparte-attachment-preview",{bubbles:!0,composed:!0,detail:{url:l.src,name:r[o]?.name??"",type:r[o]?.type??""}}))};l.addEventListener("click",c),l.addEventListener("keydown",d=>{let u=d.key;u!=="Enter"&&u!==" "||(d.preventDefault(),c())})})}_ext(t){let e=t.lastIndexOf(".");return e>0?t.slice(e+1).toUpperCase().slice(0,4):"FILE"}};H(ts);customElements.get("aparte-composer-attachments")||customElements.define("aparte-composer-attachments",ts);var es=class extends HTMLElement{_button=null;_dragCleanup=null;_unsubscribes=[];_onClick=this._handleClick.bind(this);static get observedAttributes(){return["accept","multiple","disabled"]}connectedCallback(){this._render(),this._button=this.querySelector(".aparte-caa-button"),this._button?.addEventListener("click",this._onClick),this._connectToRoot(),this._setupDragDrop(),this._unsubscribes.push(gt(this,()=>this._refreshChrome()))}disconnectedCallback(){this._button?.removeEventListener("click",this._onClick),this._dragCleanup?.(),this._unsubscribes.forEach(t=>t()),this._unsubscribes=[]}attributeChangedCallback(t,e,s){t==="disabled"&&this._button&&(this._button.disabled=s!==null)}_getRoot(){return this.closest("aparte-composer")}_refreshChrome(){if(!this._button)return;let t=T(this),e=t.t("actionUpload")||"Attach file";this._button.setAttribute("aria-label",e),this._button.setAttribute("title",e),this._button.innerHTML=t.getIcon("paperclip")}_render(){if(this.querySelector(".aparte-caa-button"))return;let t=T(this).t("actionUpload")||"Attach file",e=T(this).getIcon("paperclip"),s=this.hasAttribute("disabled")||this._getRoot()?.disabled||!1;this.innerHTML=`<button
|
|
164
|
+
class="aparte-btn aparte-btn--icon aparte-caa-button aparte-action-button"
|
|
165
|
+
aria-label="${x(t)}"
|
|
166
|
+
title="${x(t)}"
|
|
167
|
+
type="button"
|
|
168
|
+
${s?"disabled":""}
|
|
169
|
+
>${e}</button>`}_connectToRoot(){let t=this._getRoot();t&&(this._unsubscribes.push(t._on("disabled-change",({disabled:e})=>{this._button&&(this._button.disabled=e)})),this._unsubscribes.push(t._on("streaming-change",({streaming:e})=>{this._button&&(this._button.disabled=t.disabled)})))}_handleClick(){let t=document.createElement("input");t.type="file",t.multiple=!this.hasAttribute("multiple")||this.getAttribute("multiple")!=="false";let e=this.getAttribute("accept");e&&(t.accept=e),t.style.display="none",document.body.appendChild(t),t.addEventListener("change",()=>{t.files?.length&&this._admit(t.files),document.body.removeChild(t)},{once:!0}),t.click()}_admit(t){let e=Array.from(t).filter(s=>Ka(this.getAttribute("accept"),s));e.length&&this._getRoot()?.addAttachments(e)}_setupDragDrop(){let t=this._getRoot();if(!t)return;let e=a=>{a.preventDefault(),a.stopPropagation()},s=a=>{t.disabled||(e(a),t.classList.add("aparte-is-dragover"))},i=a=>{e(a),t.classList.remove("aparte-is-dragover")},r=a=>{if(e(a),t.classList.remove("aparte-is-dragover"),t.disabled)return;let o=a.dataTransfer?.files;o?.length&&this._admit(o)};t.addEventListener("dragover",s),t.addEventListener("dragleave",i),t.addEventListener("drop",r),this._dragCleanup=()=>{t.removeEventListener("dragover",s),t.removeEventListener("dragleave",i),t.removeEventListener("drop",r)}}};H(es);customElements.get("aparte-composer-add-attachment")||customElements.define("aparte-composer-add-attachment",es);var ss=class extends HTMLElement{_button=null;_unsubscribes=[];_onClick=this._handleClick.bind(this);static get observedAttributes(){return["icon","label","disabled"]}connectedCallback(){this._render(),this._button=this.querySelector(".aparte-cact-button"),this._button?.addEventListener("click",this._onClick),this._connectToRoot(),this._unsubscribes.push(gt(this,()=>{this._button&&(this._button.innerHTML=this._resolveIcon(this.getAttribute("icon")??""))}))}disconnectedCallback(){this._button?.removeEventListener("click",this._onClick),this._unsubscribes.forEach(t=>t()),this._unsubscribes=[]}attributeChangedCallback(t,e,s){this._button&&(t==="disabled"&&(this._button.disabled=s!==null),t==="label"&&(this._button.setAttribute("aria-label",s??""),this._button.setAttribute("title",s??"")),t==="icon"&&(this._button.innerHTML=this._resolveIcon(s??"")))}_getRoot(){return this.closest("aparte-composer")}_render(){if(this.querySelector(".aparte-cact-button"))return;let t=x(this.getAttribute("label")??""),e=this._resolveIcon(this.getAttribute("icon")??""),s=this.hasAttribute("disabled")||this._getRoot()?.disabled||!1;this.innerHTML=`<button
|
|
170
|
+
class="aparte-btn aparte-btn--icon aparte-cact-button aparte-action-button"
|
|
171
|
+
aria-label="${t}"
|
|
172
|
+
title="${t}"
|
|
173
|
+
type="button"
|
|
174
|
+
${s?"disabled":""}
|
|
175
|
+
>${e}</button>`}_connectToRoot(){let t=this._getRoot();t&&(this._unsubscribes.push(t._on("disabled-change",({disabled:e})=>{this._button&&(this._button.disabled=e||this.hasAttribute("disabled"))})),this._unsubscribes.push(t._on("streaming-change",({streaming:e})=>{this._button&&(this._button.disabled=e||t.disabled||this.hasAttribute("disabled"))})))}_handleClick(t){this.dispatchEvent(new CustomEvent("aparte-action-click",{bubbles:!0,composed:!0,detail:{actionId:this.getAttribute("action-id")??"",composer:this._getRoot()}}))}_resolveIcon(t){return t?t.trimStart().startsWith("<")?t:T(this).getIcon(t)??t:""}};H(ss);customElements.get("aparte-composer-action")||customElements.define("aparte-composer-action",ss);var ns=class extends HTMLElement{_observer=null;connectedCallback(){this._syncEmpty(),this._observer??=new MutationObserver(t=>{t.some(e=>!(e.type==="attributes"&&e.target===this))&&this._syncEmpty()}),this._observer.observe(this,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["hidden","data-empty"]})}disconnectedCallback(){this._observer?.disconnect(),this._observer=null}_syncEmpty(){let t=Array.from(this.children).some(i=>!i.hasAttribute("hidden")&&!i.hasAttribute("data-empty")),e=Array.from(this.childNodes).some(i=>i.nodeType===Node.TEXT_NODE&&(i.textContent??"").trim()!==""),s=t||e;s!==!this.hasAttribute("data-empty")&&(s?this.removeAttribute("data-empty"):this.setAttribute("data-empty",""))}};H(ns);customElements.get("aparte-composer-toolbar")||customElements.define("aparte-composer-toolbar",ns);function is(n){return n.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().trim()}function Ln(n,t){let e=0;for(let s of n.querySelectorAll("[data-conv-id]")){let i=s.querySelector(".aparte-conv-item__title")?.textContent??s.textContent??"";s.hidden=t!==""&&!is(i).includes(t),s.hidden||e++}for(let s of n.querySelectorAll(".aparte-conv-group"))s.hidden=t!==""&&!Array.from(s.querySelectorAll("[data-conv-id]")).some(i=>!i.hidden);return e}var Pa=n=>n==="running"||n==="waiting"?n:null;function kn(n,t){return`[${n}="${K(t)}"]`}var Tn=864e5,Vd=4,Yd=8,rs=class extends HTMLElement{_conversations=[];_activeId=null;_open=null;_renaming=null;_warnedNoManager=!1;static get observedAttributes(){return["active-id","flat","loading","manage"]}get loading(){return this.hasAttribute("loading")}set loading(t){this.toggleAttribute("loading",z(t))}get manage(){return this.hasAttribute("manage")}set manage(t){this.toggleAttribute("manage",z(t))}connectedCallback(){this.classList.contains("aparte-conv-list")||this.classList.add("aparte-conv-list"),this.getAttribute("role")||this.setAttribute("role","navigation"),this.addEventListener("click",this._onClick),this.addEventListener("keydown",this._onKeydown),this.addEventListener("focusout",this._onFocusOut),this.addEventListener("pointerdown",this._onPress),this._render(),window.addEventListener("aparte-config-change",this._onConfigChange),window.addEventListener("aparte-conversation-status",this._onStatus)}disconnectedCallback(){this._closeMenu(),this.removeEventListener("click",this._onClick),this.removeEventListener("keydown",this._onKeydown),this.removeEventListener("focusout",this._onFocusOut),this.removeEventListener("pointerdown",this._onPress),window.removeEventListener("pointerup",this._onRelease,!0),window.removeEventListener("pointercancel",this._onRelease,!0),this._pressed=!1,this._renderAfterPress=!1,window.removeEventListener("aparte-config-change",this._onConfigChange),window.removeEventListener("aparte-conversation-status",this._onStatus)}attributeChangedCallback(t,e,s){e!==s&&(t==="active-id"?(this._activeId=s,this._updateActiveState()):(t==="flat"||t==="loading")&&this.isConnected&&this._render())}_onConfigChange=t=>{let e=t.detail;e?.config&&e.config!==T(this)||this._render()};_onStatus=t=>{let e=t.detail;if(typeof e?.id!="string")return;vn(e.id,Pa(e.status));let s=this.querySelector(kn("data-conv-id",e.id));s&&this._applyStatus(s,e.id)};setConversationStatus(t,e){ra(t,Pa(e))}getConversationStatus(t){return Ne(t)}_applyStatus(t,e){let s=Ne(e);s?t.setAttribute("data-status",s):t.removeAttribute("data-status");let i=s==="running";t.querySelector(".aparte-conv-item__title")?.classList.toggle("aparte-shimmer",i);let r=t.querySelector(".aparte-conv-item__state");r&&(r.textContent=this._statusWords(s))}_statusWords(t){return t==="running"?this._t("conversationRunning"):t==="waiting"?this._t("conversationWaiting"):""}set conversations(t){this._conversations=Array.isArray(t)?t:[],this._render()}get conversations(){return this._conversations}_pressed=!1;_renderAfterPress=!1;_onPress=()=>{this._pressed||(this._pressed=!0,window.addEventListener("pointerup",this._onRelease,!0),window.addEventListener("pointercancel",this._onRelease,!0))};_onRelease=()=>{window.removeEventListener("pointerup",this._onRelease,!0),window.removeEventListener("pointercancel",this._onRelease,!0),setTimeout(()=>{this._pressed=!1,this._renderAfterPress&&(this._renderAfterPress=!1,this.isConnected&&this._render())},0)};_ownLabel=null;_render(){let t=this.getAttribute("aria-label");if(!this.hasAttribute("aria-labelledby")&&(t===null||t===this._ownLabel)&&(this._ownLabel=this._t("conversationList"),this.setAttribute("aria-label",this._ownLabel)),this._pressed){this._renderAfterPress=!0;return}this._closeMenu(),this._renaming=null;let e=lt(this),s=e&&this.contains(e)?e.closest("[data-select-id], [data-more-id]"):null,i=s?.dataset.selectId?kn("data-select-id",s.dataset.selectId):s?.dataset.moreId?kn("data-more-id",s.dataset.moreId):null,r=s?.closest("[data-conv-id]")??null,a=f=>!f.closest("[hidden]"),o=r?Array.from(this.querySelectorAll("[data-conv-id]")).filter(a).indexOf(r):-1,l=this.hasAttribute("loading");if(this.setAttribute("aria-busy",l?"true":"false"),l){this.removeAttribute("data-no-match");let f='<span class="aparte-skeleton aparte-skeleton--text"></span>';this.innerHTML='<div class="aparte-conv-list-loading" aria-hidden="true">'+f+f+f+f+f+f+'</div><span class="aparte-conv-list-loading-status aparte-sr-only" role="status"></span>';let g=this.querySelector(".aparte-conv-list-loading-status"),_=()=>{g?.isConnected&&(g.textContent=this._t("loadingConversations"))};typeof requestAnimationFrame=="function"?requestAnimationFrame(_):_();return}let c=this.querySelector(":scope > .aparte-conv-list-no-match"),d=this._groups().map(f=>this._renderGroup(f)).join("");if(c){for(let f of Array.from(this.childNodes))f!==c&&f.remove();c.insertAdjacentHTML("beforebegin",d)}else this.innerHTML=d;if(this._applyFilter(),!i)return;let u=this.querySelector(i);if(u&&a(u)){u.focus();return}let h=Array.from(this.querySelectorAll("[data-select-id]")).filter(a),p=o>=0?h[o]??h[h.length-1]:null;if(p){p.focus();return}this.hasAttribute("tabindex")||(this.setAttribute("tabindex","-1"),this.addEventListener("blur",()=>this.removeAttribute("tabindex"),{once:!0})),this.focus()}_query="";filter(t){return this._query=is(t),this._applyFilter()}_applyFilter(){let t=this._query;if(this.hasAttribute("loading"))return 0;let e=Ln(this,t),s=t!==""&&e===0;this.toggleAttribute("data-no-match",s);let i=this.querySelector(":scope > .aparte-conv-list-no-match"),r=!i;i||(i=document.createElement("p"),i.className="aparte-conv-list-no-match",i.setAttribute("role","status"),this.appendChild(i));let a=s?this._t("conversationSearchEmpty"):"",o=()=>{i.isConnected&&i.textContent!==a&&(i.textContent=a)};return r&&a&&typeof requestAnimationFrame=="function"?requestAnimationFrame(o):o(),e}_t(t){return T(this).getLocale()[t]??Tt[t]??""}_groups(){let t=this._conversations;if(this.hasAttribute("flat")||!t.some(d=>typeof d.updatedAt=="number"))return[{key:"all",label:null,items:t}];let e=new Date,s=new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime(),i=T(this).getLocale().tag,r=new Map,a=(d,u,h)=>{let p=r.get(d);p||(p={key:d,label:u,items:[]},r.set(d,p)),p.items.push(h)};for(let d of t){if(d.pinnedAt){a("pinned",this._t("conversationGroupPinned"),d);continue}let u=d.updatedAt;if(typeof u!="number"){a("undated",null,d);continue}if(u>=s)a("today",this._t("conversationGroupToday"),d);else if(u>=s-Tn)a("yesterday",this._t("conversationGroupYesterday"),d);else if(u>=s-7*Tn)a("week",this._t("conversationGroupWeek"),d);else if(u>=s-30*Tn)a("month",this._t("conversationGroupMonth"),d);else{let h=new Date(u),p=h.getFullYear()===e.getFullYear(),f=new Intl.DateTimeFormat(i,p?{month:"long"}:{month:"long",year:"numeric"}).format(h),g=f.charAt(0).toLocaleUpperCase(i)+f.slice(1);a(`m-${h.getFullYear()}-${String(h.getMonth()).padStart(2,"0")}`,g,d)}}let o=["pinned","today","yesterday","week","month"].map(d=>r.get(d)).filter(d=>!!d),l=[...r.keys()].filter(d=>d.startsWith("m-")).sort((d,u)=>u.localeCompare(d)).map(d=>r.get(d)),c=r.get("undated");return[...o,...l,...c?[c]:[]]}_renderGroup(t){let e=t.items.map(i=>this._renderItem(i)).join("");if(t.label===null)return`<div class="aparte-conv-group">${e}</div>`;let s=L(t.label);return`
|
|
176
|
+
<div class="aparte-conv-group" role="group" aria-label="${x(t.label)}">
|
|
177
|
+
<div class="aparte-menu__label aparte-conv-group__label" aria-hidden="true">${s}</div>
|
|
178
|
+
${e}
|
|
179
|
+
</div>`}_renderItem(t){let e=t.id===this._activeId,s=["aparte-menu__item aparte-conv-item",e?"aparte-conv-item--active":"",t.archivedAt?"aparte-conv-item--archived":"",t.pinnedAt?"aparte-conv-item--pinned":""].filter(Boolean).join(" "),i=x(t.id),r=L(t.title||this._t("newChat")),a=x(this._t("conversationActions")),o=T(this).getIcon("more"),l=Ne(t.id),c=l?` data-status="${x(l)}"`:"",d=x(l==="running"?"aparte-conv-item__title aparte-shimmer":"aparte-conv-item__title"),u=L(this._statusWords(l));return`
|
|
180
|
+
<div class="${x(s)}" data-conv-id="${i}"${c}>
|
|
181
|
+
<button
|
|
182
|
+
class="aparte-conv-item__select"
|
|
183
|
+
type="button"
|
|
184
|
+
data-select-id="${i}"
|
|
185
|
+
aria-current="${e?"page":"false"}"
|
|
186
|
+
><span class="${d}" dir="auto">${r}</span><span class="aparte-conv-item__status" aria-hidden="true"></span><span class="aparte-conv-item__state aparte-sr-only">${u}</span></button>
|
|
187
|
+
<button
|
|
188
|
+
class="aparte-btn aparte-btn--icon aparte-btn--sm aparte-conv-item__more"
|
|
189
|
+
type="button"
|
|
190
|
+
data-more-id="${i}"
|
|
191
|
+
aria-label="${a}"
|
|
192
|
+
title="${a}"
|
|
193
|
+
aria-haspopup="menu"
|
|
194
|
+
aria-expanded="false"
|
|
195
|
+
>${o}</button>
|
|
196
|
+
</div>`}_menuMarkup(t){let e=T(this),s=e.getIcon("edit"),i=e.getIcon("pin"),r=e.getIcon(t.archivedAt?"unarchive":"archive"),a=e.getIcon("trash"),o=L(this._t("renameConversation")),l=L(this._t(t.pinnedAt?"unpinConversation":"pinConversation")),c=L(this._t(t.archivedAt?"unarchiveConversation":"archiveConversation")),d=L(this._t("deleteConversation"));return`
|
|
197
|
+
<button type="button" class="aparte-menu__item" role="menuitem" data-menu-action="rename">${s}<span>${o}</span></button>
|
|
198
|
+
<button type="button" class="aparte-menu__item" role="menuitem" data-menu-action="pin">${i}<span>${l}</span></button>
|
|
199
|
+
<button type="button" class="aparte-menu__item" role="menuitem" data-menu-action="archive">${r}<span>${c}</span></button>
|
|
200
|
+
<div class="aparte-menu__separator" role="separator"></div>
|
|
201
|
+
<button type="button" class="aparte-menu__item aparte-conv-menu__item--danger" role="menuitem" data-menu-action="delete">${a}<span>${d}</span></button>`}_confirmQuestion(t){return this._t("deleteConversationConfirm").replace("{title}",()=>t.title||this._t("newChat"))}_confirmMarkup(t){let e=L(this._confirmQuestion(t)),s=L(this._t("cancel")),i=L(this._t("deleteConversation"));return`
|
|
202
|
+
<div class="aparte-conv-menu__confirm">
|
|
203
|
+
<p class="aparte-conv-menu__question">${e}</p>
|
|
204
|
+
<div class="aparte-conv-menu__actions">
|
|
205
|
+
<button type="button" class="aparte-btn aparte-btn--sm aparte-btn--ghost" data-menu-action="cancel">${s}</button>
|
|
206
|
+
<button type="button" class="aparte-btn aparte-btn--sm aparte-btn--danger aparte-btn--solid" data-menu-action="confirm-delete">${i}</button>
|
|
207
|
+
</div>
|
|
208
|
+
</div>`}_openMenu(t,e){this._closeMenu();let s=t.dataset.convId,i=this._conversations.find(a=>a.id===s);if(!i)return;let r=document.createElement("div");r.className="aparte-menu aparte-conv-menu",r.setAttribute("role","menu"),r.setAttribute("aria-label",i.title||this._t("newChat")),r.innerHTML=this._menuMarkup(i),t.appendChild(r),e.setAttribute("aria-expanded","true"),this._open={id:s,row:t,button:e,menu:r},this._placeMenu(e,r),r.querySelector('[role="menuitem"]')?.focus(),document.addEventListener("pointerdown",this._onDocumentPointerDown,!0),document.addEventListener("pointerup",this._onDocumentPointerUp,!0),document.addEventListener("pointercancel",this._onDocumentPointerUp,!0),window.addEventListener("scroll",this._onWindowScroll,!0),window.addEventListener("resize",this._onWindowScroll)}_placeMenu(t,e){ya(t.getBoundingClientRect(),e,{gap:Vd,margin:Yd,align:"end",rtl:getComputedStyle(this).direction==="rtl"})}_closeMenu(t=!1){let e=this._open;e&&(this._open=null,e.menu.remove(),e.button.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",this._onDocumentPointerDown,!0),document.removeEventListener("pointerup",this._onDocumentPointerUp,!0),document.removeEventListener("pointercancel",this._onDocumentPointerUp,!0),this._pressInMenu=!1,window.removeEventListener("scroll",this._onWindowScroll,!0),window.removeEventListener("resize",this._onWindowScroll),t&&e.button.isConnected&&e.button.focus())}_pressInMenu=!1;_onDocumentPointerUp=()=>{this._pressInMenu=!1};_onDocumentPointerDown=t=>{let e=this._open;if(!e)return;let s=_t(t);this._pressInMenu=!!s&&e.menu.contains(s),!(e.menu.contains(s)||e.button.contains(s))&&this._closeMenu()};_onWindowScroll=()=>{this._closeMenu()};_onFocusOut=t=>{let e=this._open;if(!e)return;let s=t.relatedTarget;!s&&this._pressInMenu||s&&(e.menu.contains(s)||e.button.contains(s))||e.menu.contains(t.target)&&this._closeMenu()};_manage(t,e){if(!this.hasAttribute("manage")||t.defaultPrevented)return;let s=T(this).getConversationManager();if(!s){if(this._warnedNoManager)return;this._warnedNoManager=!0,console.warn("[aparte-conversation-list] `manage` is set but no conversation manager is registered, so the row menu writes nothing. Call setConversationManager(manager) on your config, or drop `manage` and handle the events yourself.");return}e(s).catch(i=>{console.warn("[aparte-conversation-list] the conversation manager refused the change:",i)})}_onMenuAction(t){let e=this._open;if(!e)return;let s=this._conversations.find(r=>r.id===e.id);if(!s){this._closeMenu();return}let i=s.id;switch(t){case"rename":this._closeMenu(),this._startRename(e.row,s);return;case"pin":if(this._closeMenu(!0),s.pinnedAt){let r=new CustomEvent("aparte-conversation-unpin",{detail:{id:i},bubbles:!0,composed:!0,cancelable:!0});this.dispatchEvent(r),this._manage(r,a=>a.unpin(i))}else{let r=new CustomEvent("aparte-conversation-pin",{detail:{id:i},bubbles:!0,composed:!0,cancelable:!0});this.dispatchEvent(r),this._manage(r,a=>a.pin(i))}return;case"archive":if(this._closeMenu(!0),s.archivedAt){let r=new CustomEvent("aparte-conversation-unarchive",{detail:{id:i},bubbles:!0,composed:!0,cancelable:!0});this.dispatchEvent(r),this._manage(r,a=>a.unarchive(i))}else{let r=new CustomEvent("aparte-conversation-archive",{detail:{id:i},bubbles:!0,composed:!0,cancelable:!0});this.dispatchEvent(r),this._manage(r,a=>a.archive(i))}return;case"delete":{let r=[...e.menu.childNodes],a=document.createElement("div");a.innerHTML=this._confirmMarkup(s),e.menu.append(...a.childNodes),e.menu.setAttribute("role","dialog"),e.menu.setAttribute("aria-label",this._confirmQuestion(s)),e.menu.querySelector('[data-menu-action="cancel"]')?.focus();for(let o of r)o.remove();this._placeMenu(e.button,e.menu);return}case"cancel":this._closeMenu(!0);return;case"confirm-delete":{this._closeMenu(!0);let r=new CustomEvent("aparte-conversation-delete",{detail:{id:i},bubbles:!0,composed:!0,cancelable:!0});this.dispatchEvent(r),this._manage(r,a=>a.delete(i));return}}}_menuFocusables(){let t=this._open;return t?Array.from(t.menu.querySelectorAll('[role="menuitem"], [data-menu-action]')):[]}_onMenuKeydown(t){let e=this._menuFocusables(),s=e.indexOf(lt(this)),i=r=>{t.preventDefault(),e[(r+e.length)%e.length]?.focus()};switch(t.key){case"Escape":t.preventDefault(),this._closeMenu(!0);return;case"Tab":t.preventDefault(),this._closeMenu(!0);return;case"ArrowDown":i(s+1);return;case"ArrowUp":i(s-1);return;case"Home":i(0);return;case"End":i(e.length-1);return}}_startRename(t,e){let s=t.querySelector(".aparte-conv-item__select");if(!s)return;let i=document.createElement("input");i.type="text",i.className="aparte-field aparte-field--sm aparte-conv-item__input",i.value=e.title,i.setAttribute("aria-label",this._t("conversationTitle")),i.dataset.renameId=e.id,s.replaceWith(i),this._renaming={id:e.id,input:i,done:!1},i.addEventListener("blur",r=>{let a=r.relatedTarget;this._finishRename(!0,!a||this.contains(a))}),i.focus(),i.select()}_finishRename(t,e){let s=this._renaming;if(!s||s.done)return;s.done=!0;let i=this._conversations.find(a=>a.id===s.id),r=s.input.value.trim();if(this._render(),t&&i&&r&&r!==i.title){let a=new CustomEvent("aparte-conversation-rename",{detail:{id:i.id,title:r},bubbles:!0,composed:!0,cancelable:!0});this.dispatchEvent(a),this._manage(a,o=>o.updateTitle(i.id,r))}e&&this.querySelector(`[data-select-id="${K(s.id)}"]`)?.focus()}_onClick=t=>{let e=t.target,s=e.closest("[data-menu-action]");if(s&&this._open?.menu.contains(s)){t.stopPropagation(),this._onMenuAction(s.dataset.menuAction);return}let i=e.closest("[data-more-id]");if(i){t.stopPropagation(),this._open?.button===i?this._closeMenu(!0):this._openMenu(i.closest("[data-conv-id]"),i);return}if(e.closest("[data-rename-id]"))return;let r=e.closest("[data-select-id]");r&&(this._closeMenu(),this.dispatchEvent(new CustomEvent("aparte-conversation-select",{detail:{id:r.dataset.selectId},bubbles:!0,composed:!0})))};_onKeydown=t=>{let e=t.target;if(this._open?.menu.contains(e)){this._onMenuKeydown(t);return}if(e.matches("[data-rename-id]")){t.key==="Enter"?(t.preventDefault(),this._finishRename(!0,!0)):t.key==="Escape"&&(t.preventDefault(),this._finishRename(!1,!0));return}};_updateActiveState(){this.querySelectorAll("[data-conv-id]").forEach(e=>{let s=e.dataset.convId===this._activeId;e.classList.toggle("aparte-conv-item--active",s),e.querySelector("[data-select-id]")?.setAttribute("aria-current",s?"page":"false")})}};H(rs);customElements.get("aparte-conversation-list")||customElements.define("aparte-conversation-list",rs);var Xa=n=>typeof n=="string"||typeof n=="object"&&n!==null&&typeof n.label=="string",Mn=n=>{try{let t=JSON.parse(n);return Array.isArray(t)?t.filter(Xa):[]}catch{return console.warn('[aparte-suggestions] `suggestions` is not a JSON array. Use ["\u2026"] or [{"label": "\u2026", "prompt": "\u2026"}].'),[]}},Na=n=>typeof n=="string"?n:n.label,Da=n=>typeof n=="string"?n:n.prompt??n.label,as=class extends HTMLElement{static get observedAttributes(){return["suggestions","target","empty-only","answers"]}_suggestions=[];_composer=null;_transcript=null;_transcriptObserver=null;_sent=!1;_wasEmpty=!0;_hidOwn=!1;_onSend=()=>{this.hasAttribute("answers")&&this._showAnswers([]),this.hasAttribute("empty-only")&&(this._transcript||this._watchTranscript(),this._sent=!0,this._applyEmptyOnly())};_applyEmptyOnly=()=>{let t=this._transcript?za(this._transcript):!0;t&&!this._wasEmpty&&(this._sent=!1),this._wasEmpty=t,this._setHidden(!t||this._sent)};_onConfigChange=()=>{let t=this.querySelector(".aparte-suggestions");t&&t.setAttribute("aria-label",this._groupLabel())};get suggestions(){return this._suggestions}set suggestions(t){this._suggestions=typeof t=="string"?Mn(t):Array.isArray(t)?t.filter(Xa):[],this.isConnected&&this._render()}connectedCallback(){this.hasAttribute("suggestions")&&this._readAttribute(),this._render(),this._watchComposer(),window.addEventListener("aparte-config-change",this._onConfigChange)}disconnectedCallback(){this._composer?.removeEventListener("aparte-send",this._onSend),this._composer=null,this._transcriptObserver?.disconnect(),this._transcriptObserver=null,this._transcript=null,this._stopHolding(),window.removeEventListener("aparte-config-change",this._onConfigChange)}attributeChangedCallback(t){this.isConnected&&(t==="suggestions"?(this._readAttribute(),this._render()):t==="target"?this._watchComposer():t==="answers"?this._watchTranscript():t==="empty-only"&&(this._watchTranscript(),this.hasAttribute("empty-only")||(this._sent=!1,this._setHidden(!1))))}_groupLabel(){return T(this).t("suggestionsLabel")||"Suggested prompts"}_parsed=null;_readAttribute(){let t=this.getAttribute("suggestions");t===null||t===this._parsed||(this._parsed=t,this._suggestions=Mn(t))}_resolveComposer(){let t=this.closest("aparte-composer");if(t)return t;let e=this.getAttribute("target");if(e){let i=document.getElementById(e)?.querySelector("aparte-composer");if(i)return i;for(let r of document.querySelectorAll("aparte-composer[target]"))if(r.getAttribute("target")===e)return r}return document.querySelector("aparte-composer")}_watchComposer(){this._composer?.removeEventListener("aparte-send",this._onSend),this._composer=this._resolveComposer(),this._composer?.addEventListener("aparte-send",this._onSend),this._watchTranscript()}_resolveTranscript(){let t=this.getAttribute("target")??this._composer?.getAttribute("target")??null,e=st(this._composer)??st(this)??(t?document.getElementById(t):null);return e?e.matches("aparte-chat-viewport")?e:e.querySelector("aparte-chat-viewport"):null}_watchTranscript(){let e=this.hasAttribute("empty-only")||this.hasAttribute("answers")?this._resolveTranscript():null;e!==this._transcript&&(this._transcriptObserver?.disconnect(),this._transcriptObserver=null,this._transcript=e,e&&(this._transcriptObserver=new MutationObserver(this._onTranscript),this._transcriptObserver.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["loading"]}))),this._onTranscript()}_onTranscript=()=>{this.hasAttribute("empty-only")&&this._applyEmptyOnly(),this.hasAttribute("answers")&&this._applyAnswers()};_applyAnswers(){let t=this._transcript?.querySelectorAll("aparte-chat-bubble"),e=t&&t.length?t[t.length-1]:null,s=e&&e.getAttribute("data-role")!=="user"?e.querySelectorAll("[data-aparte-suggestions]"):null,i=s&&s.length?s[s.length-1]:null,r=i?Mn(i.getAttribute("data-aparte-suggestions")??"[]"):[];this._showAnswers(r.map(gn).filter(a=>a!==null))}_showAnswers(t){JSON.stringify(t)!==JSON.stringify(this._suggestions)&&(this._suggestions=t,this.isConnected&&this._render())}_setHidden(t){if(t){if(this.hidden)return;this.hidden=!0,this._hidOwn=!0}else this._hidOwn&&(this.hidden=!1,this._hidOwn=!1)}_render(){if(this.replaceChildren(),this._suggestions.length===0){this.setAttribute("data-empty","");return}this.removeAttribute("data-empty");let t=document.createElement("div");t.className="aparte-suggestions",t.setAttribute("role","group"),t.setAttribute("aria-label",this._groupLabel());for(let e of this._suggestions){let s=document.createElement("button");s.type="button",s.className="aparte-btn aparte-btn--surface aparte-btn--pill aparte-suggestion",s.textContent=Na(e);let i=Da(e);i!==s.textContent&&(s.title=i),s.addEventListener("click",()=>this._activate(e)),t.appendChild(s)}this.appendChild(t)}_sending=!1;_sendingTimer;_stopHolding=()=>{this._sending=!1,clearTimeout(this._sendingTimer),window.removeEventListener("aparte-message-start",this._onTurnStart)};_onTurnStart=t=>{let e=t.detail?.targetId,s=this._ownChatId();(!e||!s||e===s)&&this._stopHolding()};_ownChatId(){let t=this._composer,e=t?.getAttribute("target");if(e)return e;for(let s=t?.parentElement??null;s;s=s.parentElement)if((s.tagName.toLowerCase()==="aparte-chat"||s.hasAttribute("data-aparte-chat"))&&s.id)return s.id}_holdUntilStreaming(){this._stopHolding(),this._sending=!0,window.addEventListener("aparte-message-start",this._onTurnStart),this._sendingTimer=setTimeout(this._stopHolding,1e3)}_activate(t){let e={label:Na(t),prompt:Da(t)};if(!this.dispatchEvent(new CustomEvent("aparte-suggestion",{detail:e,bubbles:!0,composed:!0,cancelable:!0})))return;let i=this._composer??this._resolveComposer();if(!i){console.warn("[aparte-suggestions] no <aparte-composer> to send through \u2014 put the element inside one, or point `target` at the chat it serves.");return}i!==this._composer&&this._watchComposer();let r=i;if(r.panelActive)return;let a=this.getAttribute("mode")==="fill";if(!a&&(r.streaming||this._sending))return;let o=this.contains(document.activeElement),l=typeof i.value=="string"?i.value:"",c=a?[]:(i.attachments??[]).slice();if(c.length&&i.clearAttachments(),i.setValue(e.prompt),a)i.focus();else{let d=!1,u=()=>{d=!0};i.addEventListener("aparte-send",u,{once:!0}),i.submit(),i.removeEventListener("aparte-send",u),d&&this._holdUntilStreaming(),c.length&&i.addAttachments(c),(typeof i.value=="string"?i.value:"")!==l&&i.setValue(l),o&&i.focus()}}};H(as);customElements.get("aparte-suggestions")||customElements.define("aparte-suggestions",as);var Ba=(n,t)=>{let e=Number(n);return n!==null&&Number.isFinite(e)&&e>0&&e<=1?e:t},Jd=n=>(n instanceof Element?n.closest("aparte-chat, [data-aparte-chat]"):null)?.id||void 0,W=(n,t,e)=>{let s=document.createElement(n);return s.className=t,e!==void 0&&(s.textContent=e),s},Ha="http://www.w3.org/2000/svg",Xd=()=>{let n=document.createElementNS(Ha,"svg");n.setAttribute("class","aparte-context__ring"),n.setAttribute("viewBox","0 0 36 36");for(let t of["track","value"]){let e=document.createElementNS(Ha,"circle");e.setAttribute("class",`aparte-context__${t}`),e.setAttribute("cx","18"),e.setAttribute("cy","18"),e.setAttribute("r","15.5"),t==="value"&&e.setAttribute("pathLength","100"),n.appendChild(e)}return n},$a=n=>!!n&&typeof n.getMessages=="function",Qd=n=>{if(!n)return null;if($a(n))return n;let t=n.viewport??n.querySelector("aparte-chat-viewport");return $a(t)?t:null},Zd=0,tu={system:0,tools:0,summary:0,messages:0},os=class extends HTMLElement{static get observedAttributes(){return["window","warn","danger","target","variant","used"]}_used=null;_level=null;_lastDone=null;_viewChanged=!1;_blank=!1;_overflow=!1;_compact=null;_failure="";_open=!1;_measured=null;_seen=null;_panelSignature="";_remember(t){let e=t instanceof Element?st(t):null;e&&(this._seen=e)}_onDone=t=>{let e=t.detail;!e?.usage||!this._isMine(e.targetId)||(this._remember(t.target),this._used=Be(e.usage),this._lastDone={messageId:e.messageId,usage:e.usage},this._viewChanged=!1,this._blank=!1,this._overflow=!1,this._render())};_onReset=t=>{this._isMine(Jd(t.target))&&(this._remember(t.target),this._used=null,this._lastDone=null,this._viewChanged=!1,this._overflow=!1,this._compact=null,this._blank=!0,this._render())};_onLoaded=t=>{let e=t.detail;if(!this._isMine(e?.targetId))return;this._remember(t.target),this._blank=!1,this._lastDone=null,this._viewChanged=!1,this._overflow=!1,this._compact=null;let r=[...t.target?.getMessages?.()??[]].reverse().find(a=>a.role==="assistant"&&a.usage);this._used=r?.usage?Be(r.usage):null,this._render()};_onCompactStart=t=>{let e=t.detail;this._isMine(e?.targetId)&&(this._compact="running",this._failure="",this._render())};_onCompacted=t=>{let e=t.detail;if(this._isMine(e?.targetId)){if(this._compact=null,e?.skipped){this._render();return}this._viewChanged=!0,this._overflow=!1,this._messages()||(this._used=null),this._render()}};_onCompactError=t=>{let e=t.detail;this._isMine(e?.targetId)&&(this._compact=e?.aborted?null:"failed",this._failure=e?.aborted?"":typeof e?.error=="string"?e.error:"",this._render())};_onMessageError=t=>{let e=t.detail;this._isMine(e?.targetId)&&e?.error?.code===B.USAGE_CONTEXT_EXCEEDED&&(this._remember(t.target),this._overflow=!0,this._render())};_onRerender=()=>this._render();get used(){return this._measured?.used??this._used}set used(t){t==null?this.removeAttribute("used"):this.setAttribute("used",String(t))}get window(){return this._window()}set window(t){t==null?this.removeAttribute("window"):this.setAttribute("window",String(t))}get level(){return this._level}get measure(){return this._measured}connectedCallback(){window.addEventListener("aparte-message-done",this._onDone),window.addEventListener("aparte-message-error",this._onMessageError),window.addEventListener("aparte-compact-start",this._onCompactStart),window.addEventListener("aparte-compact-done",this._onCompacted),window.addEventListener("aparte-compact-error",this._onCompactError),window.addEventListener("aparte-reset-done",this._onReset),window.addEventListener("aparte-conversation-loaded",this._onLoaded),window.addEventListener("aparte-config-change",this._onRerender),this.addEventListener("click",this._onClick),this.addEventListener("keydown",this._onKeydown),this._render()}disconnectedCallback(){window.removeEventListener("aparte-message-done",this._onDone),window.removeEventListener("aparte-message-error",this._onMessageError),window.removeEventListener("aparte-compact-start",this._onCompactStart),window.removeEventListener("aparte-compact-done",this._onCompacted),window.removeEventListener("aparte-compact-error",this._onCompactError),window.removeEventListener("aparte-reset-done",this._onReset),window.removeEventListener("aparte-conversation-loaded",this._onLoaded),window.removeEventListener("aparte-config-change",this._onRerender),this.removeEventListener("click",this._onClick),this.removeEventListener("keydown",this._onKeydown),this._stopListeningWhileOpen()}attributeChangedCallback(t){if(t==="used"){let e=Number(this.getAttribute("used"));this._used=this.hasAttribute("used")&&Number.isFinite(e)&&e>=0?e:null}this.isConnected&&this._render()}_cfg(){return T(this._chat()??this)}_window(){let t=Number(this.getAttribute("window"));if(this.hasAttribute("window")&&Number.isFinite(t)&&t>0)return t;let e=this._cfg().getCurrentModel();return e?.contextWindow&&e.contextWindow>0?e.contextWindow:null}_ownTargetId(){let t=this.getAttribute("target");if(t)return t;let e=this.parentElement;for(;e;){if((e.tagName.toLowerCase()==="aparte-chat"||e.hasAttribute("data-aparte-chat"))&&e.id)return e.id;e=e.parentElement}}_isMine(t){let e=this._ownTargetId();return!t||!e||t===e}_chat(){let t=this.getAttribute("target");if(t){let i=this.getRootNode().getElementById?.(t)??document.getElementById(t);if(i)return i}let e=st(this);return e||(this._seen?.isConnected?this._seen:null)}_messages(){let t=Qd(this._chat());if(!t)return null;try{return t.getMessages()}catch{return null}}_measure(t){let e=this._messages(),s=this._lastDone,i=e&&s?.messageId?e.map(a=>a.id===s.messageId&&!a.usage?{...a,usage:s.usage}:a):e,r=!!i?.some(a=>a.role==="assistant"&&a.usage);return i&&(r&&!this._blank||this._overflow&&i.length>0)?fa({messages:i,config:this._cfg(),windowOverride:t,viewChanged:this._viewChanged}):this._used===null?null:{window:t,used:this._used,estimated:!1,parts:{...tu},other:this._used}}_render(){let t=this._window(),e=t===null?null:this._measure(t);if(this._compact?this.setAttribute("data-compact",this._compact):this.removeAttribute("data-compact"),t===null||e===null){this._measured=null,this.setAttribute("data-empty",""),this.removeAttribute("data-level"),this._open=!1,this._stopListeningWhileOpen(),this._panelSignature="",this.replaceChildren(),this._level=null;return}this._measured=e,this.removeAttribute("data-empty");let s=e.used,i=Math.min(1,s/t),r=Ba(this.getAttribute("warn"),.75),a=Ba(this.getAttribute("danger"),.9),o=this._overflow||i>=a?"danger":i>=r?"warn":"ok";this.setAttribute("data-level",o);let l=this.getAttribute("variant")==="ring",c=this.querySelector(".aparte-context");c&&c.classList.contains("aparte-context--ring")!==l&&(this.replaceChildren(),c=null,this._panelSignature="");let d=this.querySelector('[role="meter"]'),u=this.querySelector(".aparte-context__text"),h=this.querySelector(".aparte-context__toggle"),p=this.querySelector(".aparte-context__name"),f=this.querySelector(".aparte-context__panel");(!c||!d||!u||!h||!p||!f)&&(c=W("div",l?"aparte-context aparte-context--ring":"aparte-context"),d=l?Xd():W("div","aparte-progress"),d.setAttribute("role","meter"),l||d.appendChild(W("div","aparte-progress__bar")),h=W("button","aparte-btn aparte-btn--ghost aparte-btn--sm aparte-context__toggle"),h.type="button",p=W("span","aparte-sr-only"),p.classList.add("aparte-context__name"),u=W("span","aparte-context__text"),h.append(p,u),f=W("div","aparte-context__panel aparte-popover"),f.id=`aparte-context-panel-${++Zd}`,f.setAttribute("role","group"),f.hidden=!0,h.setAttribute("aria-controls",f.id),c.append(d,h,f),this.replaceChildren(c),this._panelSignature="");let g=this._cfg(),_=g.getLocale().tag||void 0,S=new Intl.NumberFormat(_,{notation:"compact",maximumFractionDigits:1}),E=e.estimated?"~":"",I=`${E}${S.format(s)} / ${S.format(t)}`,b=Math.round(i*100),y=g.t("contextLabel")||"Context window";if(l){let m=d.querySelector(".aparte-context__value");m?.style.setProperty("--aparte-context-ratio",String(b)),m?.classList.toggle("aparte-context__value--empty",b===0),c.title=I}else d.style.setProperty("--aparte-progress-value",String(b));if(d.setAttribute("aria-valuemin","0"),d.setAttribute("aria-valuemax",String(t)),d.setAttribute("aria-valuenow",String(s)),d.setAttribute("aria-label",`${y}: ${I}`),p.textContent=`${y}: `,h.setAttribute("aria-expanded",String(this._open)),u.textContent=l?`${E}${new Intl.NumberFormat(_,{style:"percent",maximumFractionDigits:0}).format(b/100)}`:I,f.setAttribute("aria-label",y),f.hidden=!this._open,this._open?this._renderPanel(f,e,t,S):this._panelSignature="",o!==this._level){this._level=o;let m=this._ownTargetId(),w={level:o,used:s,window:t,ratio:i,targetId:m};this.dispatchEvent(new CustomEvent("aparte-context-threshold",{detail:w,bubbles:!0,composed:!0}))}}_renderPanel(t,e,s,i){let r=this._cfg(),a=r.getCompactor(),o=this._chat(),l=this._ownTargetId(),c=null;try{c=a?.preview?.({target:o,...l?{targetId:l}:{}})??null}catch{c=null}let{parts:d,used:u}=e,h=d.system+d.tools+d.summary+d.messages,p=h>u&&h>0?u/h:1,f=e.estimated?"~":"",g=[{key:"system",label:r.t("contextSystem")||"System prompt",tokens:d.system*p,approx:"~"},{key:"tools",label:r.t("contextTools")||"Tools",tokens:d.tools*p,approx:"~"},{key:"summary",label:r.t("contextSummary")||"Summary",tokens:d.summary*p,approx:"~"},{key:"messages",label:r.t("contextMessages")||"Messages",tokens:d.messages*p,approx:"~"},{key:"other",label:r.t("contextOther")||"Other",tokens:p<1?0:e.other,approx:"~"},{key:"free",label:r.t("contextFree")||"Free",tokens:Math.max(0,s-u),approx:f}],_=`${f}${i.format(u)} / ${i.format(s)}`,S=c&&c.tokens>0?(r.t("contextReclaim")||"Compacting now would free ~{n} tokens").replace("{n}",()=>i.format(Math.round(c.tokens))):"",E=!!a&&!!c&&this._compact===null,I=W("ul","aparte-context__rows");for(let v of g){let A=W("li","aparte-context__row");A.setAttribute("data-part",v.key),A.append(W("span","aparte-context__row-label",v.label)),A.append(W("span","aparte-context__row-value",`${v.approx}${i.format(Math.round(v.tokens))}`));let R=W("div","aparte-progress aparte-context__row-bar");R.setAttribute("aria-hidden","true"),R.style.setProperty("--aparte-progress-value",String(Math.round(Math.min(1,v.tokens/s)*100))),R.appendChild(W("div","aparte-progress__bar")),A.append(R),I.append(A)}let b=W("li","aparte-context__row aparte-context__row--total");b.setAttribute("data-part","total"),b.append(W("span","aparte-context__row-label",r.t("contextTotal")||"Total"),W("span","aparte-context__row-value",_)),I.append(b);let y=[I];if(this._compact==="running"){let v=W("p","aparte-context__status aparte-shimmer",r.t("checkpointPending")||"Summarising the context\u2026");v.setAttribute("role","status"),y.push(v)}else if(this._compact==="failed"){let v=W("p","aparte-context__status aparte-context__status--failed",r.t("checkpointFailed")||"Couldn't summarise the context");v.setAttribute("role","status"),this._failure&&(v.title=this._failure,v.appendChild(W("span","aparte-sr-only",`: ${this._failure}`))),y.push(v,this._action("retry",r.t("retry")||"Retry"))}S&&y.push(W("p","aparte-context__reclaim",S)),E&&y.push(this._action("compact",r.t("contextCompactNow")||"Compact now"));let m=W("div","aparte-context__content");if(m.append(...y),m.innerHTML===this._panelSignature)return;this._panelSignature=m.innerHTML;let w=document.activeElement,M=w&&t.contains(w)?w.getAttribute("data-context-action")??"":null;t.replaceChildren(...Array.from(m.childNodes)),M!==null&&((M?t.querySelector(`[data-context-action="${K(M)}"]`):null)??this.querySelector(".aparte-context__toggle"))?.focus()}_action(t,e){let s=W("button","aparte-btn aparte-btn--sm aparte-btn--surface aparte-context__action",e);return s.type="button",s.setAttribute("data-context-action",t),s}async _compactNow(t){let e=this._cfg().getCompactor(),s=this._ownTargetId();if(!e){window.dispatchEvent(new CustomEvent("aparte-compact",{detail:{targetId:s}}));return}this._compact="running",this._failure="",this._render();let i=null;try{let r=await e.compact({target:this._chat(),...s?{targetId:s}:{},force:!0,reason:t});r.ok?r.skipped||(this._viewChanged=!0):i=r.error}catch(r){i=r instanceof Error?r.message:String(r)}this._compact==="running"&&(this._compact=i===null?null:"failed",this._failure=i??""),this.isConnected&&this._render()}_onClick=t=>{let e=t.target,s=e?.closest?.("[data-context-action]");if(s){this._compactNow(s.getAttribute("data-context-action")==="retry"?"retry":"manual");return}e?.closest?.(".aparte-context__panel")||e?.closest?.(".aparte-context")&&this._setOpen(!this._open)};_setOpen(t,e=!1){t!==this._open&&(this._open=t,t?this._listenWhileOpen():this._stopListeningWhileOpen(),this._render(),t?this._place():e&&this.querySelector(".aparte-context__toggle")?.focus())}_onDocumentClick=t=>{t.composedPath().includes(this)||this._setOpen(!1)};_onKeydown=t=>{!this._open||t.key!=="Escape"||(t.preventDefault(),t.stopPropagation(),this._setOpen(!1,!0))};_onDocumentKeydown=t=>{t.key==="Escape"&&this._setOpen(!1,this.contains(document.activeElement))};_listenWhileOpen(){document.addEventListener("click",this._onDocumentClick),document.addEventListener("keydown",this._onDocumentKeydown)}_stopListeningWhileOpen(){document.removeEventListener("click",this._onDocumentClick),document.removeEventListener("keydown",this._onDocumentKeydown)}_place(){let t=this.querySelector(".aparte-context__panel");if(!t)return;t.removeAttribute("data-placement"),t.removeAttribute("data-align");let e=this.getBoundingClientRect(),s=t.getBoundingClientRect();s.height>0&&e.top<s.height&&t.setAttribute("data-placement","below");let r=getComputedStyle(t).direction==="rtl"?s.left<0:s.right>document.documentElement.clientWidth;s.width>0&&r&&t.setAttribute("data-align","end")}};H(os);customElements.get("aparte-context")||customElements.define("aparte-context",os);var $e=60,eu=6,su=150,nu=4,iu=1,qa=30,ls=class extends HTMLElement{static get observedAttributes(){return["target","every"]}_host=null;_mutations=null;_resizes=null;_sized=[];_intersections=null;_observedBubbles=[];_bandTargets=[];_observedSurface=null;_frameQueued=!1;_rebuildWanted=!1;_relabel=new Set;_excerpts=new WeakMap;_pickQueued=!1;_currentId=null;_visible=new WeakMap;_onScreen=new WeakSet;_onScreenObserver=null;_held=null;_settleTimer=null;_settleSurface=null;_alignPasses=0;_written=new Map;_onConfigChange=()=>this._rebuild();_onSurfaceScroll=()=>this._bumpSettle();get currentMessageId(){return this._currentId}connectedCallback(){this.classList.contains("aparte-scroll-rail")||this.classList.add("aparte-scroll-rail"),this.getAttribute("role")||this.setAttribute("role","navigation"),this.addEventListener("click",this._onClick),this.addEventListener("keydown",this._onKeydown),this.addEventListener("focusin",this._onFocusIn),this.addEventListener("focusout",this._onFocusOut),window.addEventListener("aparte-config-change",this._onConfigChange),this._attach()}disconnectedCallback(){this._detach(),this.removeEventListener("click",this._onClick),this.removeEventListener("keydown",this._onKeydown),this.removeEventListener("focusin",this._onFocusIn),this.removeEventListener("focusout",this._onFocusOut),window.removeEventListener("aparte-config-change",this._onConfigChange)}attributeChangedCallback(t){this.isConnected&&(t==="target"?this._attach():this._rebuild())}_findHost(){let t=this.getAttribute("target");if(t)return document.getElementById(t);let e=this.parentElement;for(;e;){if(e.tagName.toLowerCase()==="aparte-chat"||e.hasAttribute("data-aparte-chat"))return e;e=e.parentElement}return null}_attach(){if(this._detach(),this._host=this._findHost(),!this._host){this._rebuild();return}typeof MutationObserver<"u"&&(this._mutations=new MutationObserver(t=>{for(let e of t){if(this.contains(e.target))continue;if(e.type==="attributes"){if(Qa(e.target)){this._queueRebuild();return}continue}let i=(e.target instanceof Element?e.target:e.target.parentElement)?.closest("aparte-chat-bubble");if(i){this._excerpts.delete(i),this._ticked(i)&&this._queueRelabel(i);continue}if(e.type==="childList"&&(Fa(e.addedNodes)||Fa(e.removedNodes))){this._queueRebuild();return}}}),this._mutations.observe(this._host,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:["message-id","data-role"]})),typeof ResizeObserver<"u"&&(this._resizes=new ResizeObserver(()=>this._layout())),this._rebuild()}_detach(){this._mutations?.disconnect(),this._mutations=null,this._resizes?.disconnect(),this._resizes=null,this._sized=[],this._relabel.clear(),this._rebuildWanted=!1,this._unobserve(),this._release(),this._host=null}_queueRebuild(){this._rebuildWanted=!0,this._queueFrame()}_queueRelabel(t){this._relabel.add(t),this._queueFrame()}_queueFrame(){this._frameQueued||(this._frameQueued=!0,requestAnimationFrame(()=>{this._frameQueued=!1;let t=[...this._relabel];if(this._relabel.clear(),this._rebuildWanted){this._rebuildWanted=!1,this._rebuild();return}let e=T(this).getLocale();for(let s of t)this._label(s,e)}))}_ticked(t){return t.hasAttribute("message-id")?this.getAttribute("every")==="message"||t.getAttribute("data-role")==="user":!1}_label(t,e){if(!this._host?.contains(t))return;let s=t.getAttribute("message-id");if(!s)return;let i=this.querySelector(`.aparte-scroll-rail__tick[data-message-id="${K(s)}"]`);if(!i)return;let r=this._tickLabel(t,e);i.getAttribute("aria-label")!==r&&(i.setAttribute("aria-label",r),i.title=r)}_viewport(){return this._host?.querySelector("aparte-chat-viewport")??null}_scrollSurface(){let t=this._viewport();return t?t.querySelector(".aparte-viewport-container")??t:null}_messages(){let t=this._viewport();return t?Array.from(t.querySelectorAll("aparte-chat-bubble[message-id]")):[]}_bubbles(t=this._messages()){return(this.getAttribute("every")==="message"?"message":"user")==="message"?t:t.filter(s=>s.getAttribute("data-role")==="user")}_excerpt(t){let e=this._excerpts.get(t);if(e!==void 0)return e;let s=t.querySelector(".aparte-message-content")??t,i="",r=document.createTreeWalker(s,NodeFilter.SHOW_TEXT);for(let l=r.nextNode();l&&i.length<$e*16;l=r.nextNode())i+=l.nodeValue??"";let a=i.slice(0,$e*16).replace(/\s+/g," ").trim(),o=a.length>$e?`${a.slice(0,$e-1).trimEnd()}\u2026`:a;return this._excerpts.set(t,o),o}_tickLabel(t,e){let s=t.getAttribute("data-role")==="user"?e.roleNameUser??"You":e.roleNameAssistant??"Assistant",i=this._excerpt(t);return i?`${s}: ${i}`:s}_list(){return this.querySelector(":scope > .aparte-scroll-rail__list")}_rebuild(){this._watchSizes();let t=this._messages(),e=this._bubbles(t),s=T(this).getLocale(),i=s.scrollRailLabel??"Conversation outline";if(this.getAttribute("aria-label")!==i&&this.setAttribute("aria-label",i),e.length<2){this.setAttribute("data-empty",""),this.replaceChildren(),this._unobserve(),this._currentId=null,this._write("--aparte-scroll-rail-hit-size",""),this._write("--aparte-scroll-rail-gap","");return}this.removeAttribute("data-empty");let r=this._list();r||(r=document.createElement("ol"),r.className="aparte-scroll-rail__list",this.replaceChildren(r));let a=new Map;for(let d of Array.from(r.children)){let u=d.firstElementChild instanceof HTMLElement?d.firstElementChild.dataset.messageId:void 0;u&&a.set(u,d)}let o=new Set(e.map(d=>d.getAttribute("message-id")));for(let[d,u]of a)o.has(d)||(u.remove(),a.delete(d));let l=r.firstElementChild;for(let d of e){let u=d.getAttribute("message-id"),h=a.get(u);if(!h){h=document.createElement("li");let g=document.createElement("button");g.type="button",g.className="aparte-scroll-rail__tick",g.dataset.messageId=u,g.tabIndex=-1,h.appendChild(g)}let p=h.firstElementChild,f=this._tickLabel(d,s);p.getAttribute("aria-label")!==f&&(p.setAttribute("aria-label",f),p.title=f),u===this._currentId?p.getAttribute("aria-current")!=="true"&&p.setAttribute("aria-current","true"):p.removeAttribute("aria-current"),h===l?l=l.nextElementSibling:r.insertBefore(h,l)}let c=this._currentId!==null&&!o.has(this._currentId);c&&(this._currentId=null),this._syncTabStop(),(!xn(this._observedBubbles,e)||!xn(this._bandTargets,t))&&this._observe(e,t),this._layout(),c&&this._pickCurrent()}_observe(t,e){let s=typeof IntersectionObserver>"u"?null:this._scrollSurface();if(!s){this._unobserve(),this._observedBubbles=t,this._bandTargets=e;return}(!this._intersections||!this._onScreenObserver||this._observedSurface!==s)&&(this._unobserve(),this._intersections=new IntersectionObserver(l=>{for(let c of l)this._visible.set(c.target,c.isIntersecting?c.intersectionRatio:0);this._pickCurrent()},{root:s,rootMargin:`0px 0px -${100-qa}% 0px`,threshold:[0,.1,.25,.5,.75,1]}),this._onScreenObserver=new IntersectionObserver(l=>{for(let c of l)c.isIntersecting?this._onScreen.add(c.target):this._onScreen.delete(c.target);this._pickCurrent()},{root:s,threshold:[0]}),this._observedSurface=s,s.addEventListener("scroll",this._onRootScroll,{passive:!0}));let i=new Set(e);for(let l of this._bandTargets)i.has(l)||this._intersections.unobserve(l);let r=new Set(this._bandTargets);for(let l of e)r.has(l)||this._intersections.observe(l);let a=t[t.length-1],o=this._observedBubbles[this._observedBubbles.length-1];o!==a&&(o&&this._onScreenObserver.unobserve(o),this._onScreenObserver.observe(a)),this._observedBubbles=t,this._bandTargets=e}_unobserve(){this._intersections?.disconnect(),this._intersections=null,this._onScreenObserver?.disconnect(),this._onScreenObserver=null,this._observedSurface?.removeEventListener("scroll",this._onRootScroll),this._observedSurface=null,this._observedBubbles=[],this._bandTargets=[],this._visible=new WeakMap,this._onScreen=new WeakSet}_onRootScroll=()=>{this._pickQueued||(this._pickQueued=!0,requestAnimationFrame(()=>{this._pickQueued=!1,this._pickCurrent()}))};_atBottom(){let t=this._observedSurface;if(!t)return!1;let e=t.scrollHeight-t.clientHeight;return e>0&&e-t.scrollTop<=2}_pickCurrent(){if(this._held)return;let t=this._observedBubbles;if(t.length===0)return;let e=t[t.length-1],s=e.getAttribute("message-id");if(this._atBottom()||this._onScreen.has(e)){this._setCurrent(s);return}let i=null,r=null,a=!1;for(let o of this._bandTargets)this._ticked(o)&&(r=o.getAttribute("message-id")),(this._visible.get(o)??0)>0&&(a=!0,r!==null&&(i=r));i===null&&a||(i??=this._lastAbove(),i!==null&&this._setCurrent(i))}_lastAbove(){let t=this._observedSurface,e=this._observedBubbles;if(!t||e.length===0)return null;let s=t.getBoundingClientRect();if(s.height<=0)return null;let i=s.top+s.height*qa/100,r=0,a=e.length-1,o=-1;for(;r<=a;){let l=r+a>>1;e[l].getBoundingClientRect().top<i?(o=l,r=l+1):a=l-1}return o<0?null:e[o].getAttribute("message-id")}_markFor(t){let e=t.getAttribute("message-id");if(this._ticked(t))return e;let s=null;for(let i of this._messages()){if(i===t)break;this._ticked(i)&&(s=i.getAttribute("message-id"))}return s??e}_setCurrent(t){if(this._currentId!==t){this._currentId=t;for(let e of this.querySelectorAll(".aparte-scroll-rail__tick"))e.dataset.messageId===t?(e.setAttribute("aria-current","true"),this._reveal(e)):e.removeAttribute("aria-current");this._syncTabStop()}}_syncTabStop(t=!1){let e=Array.from(this.querySelectorAll(".aparte-scroll-rail__tick"));if(e.length===0)return;let s=t?null:lt(this),i=(s instanceof HTMLElement&&e.includes(s)?s:void 0)??e.find(r=>r.dataset.messageId===this._currentId)??e[e.length-1];this._setTabStop(i,e)}_onFocusIn=t=>{let e=t.target instanceof HTMLElement&&t.target.classList.contains("aparte-scroll-rail__tick")?t.target:null;e&&this.contains(e)&&this._setTabStop(e,Array.from(this.querySelectorAll(".aparte-scroll-rail__tick")))};_onFocusOut=t=>{t.relatedTarget instanceof Node&&this.contains(t.relatedTarget)||this._syncTabStop(!0)};_setTabStop(t,e){for(let s of e){let i=s===t?0:-1;s.tabIndex!==i&&(s.tabIndex=i)}}_reveal(t){let e=this.clientHeight;if(!e)return;let s=t.offsetTop,i=s+t.offsetHeight;s<this.scrollTop?this.scrollTop=s:i>this.scrollTop+e&&(this.scrollTop=i-e)}_watchSizes(){if(!this._resizes)return;let t=[];for(let e of[this._host,this._viewport(),this._scrollSurface()])e&&!t.includes(e)&&t.push(e);if(!xn(this._sized,t)){for(let e of this._sized)t.includes(e)||this._resizes.unobserve(e);for(let e of t)this._sized.includes(e)||this._resizes.observe(e);this._sized=t}}_write(t,e){this._written.get(t)!==e&&(this._written.set(t,e),e?this.style.setProperty(t,e):this.style.removeProperty(t))}_layout(){let t=this._host,e=this._viewport(),s=this._scrollSurface();if(t&&s&&this._write("--aparte-scroll-rail-bar",`${Math.max(0,s.offsetWidth-s.clientWidth)}px`),t&&e){let h=e.getBoundingClientRect(),p=t.getBoundingClientRect();h.height>0&&p.height>0&&(this._write("--aparte-scroll-rail-block-start",`${Math.max(0,Math.round(h.top-p.top))}px`),this._write("--aparte-scroll-rail-block-end",`${Math.max(0,Math.round(p.bottom-h.bottom))}px`))}let i=t??document.documentElement,r=getComputedStyle(i),a=parseFloat(r.getPropertyValue("--aparte-scroll-rail-hit-size"))||24,o=parseFloat(r.getPropertyValue("--aparte-scroll-rail-tick-thickness"))||2;(this._written.get("--aparte-scroll-rail-hit-size")??"")!==""&&this.scrollHeight<=this.clientHeight+1&&(this._write("--aparte-scroll-rail-hit-size",""),this._write("--aparte-scroll-rail-gap",""));let c=this.clientHeight,d=this._list()?.children.length??0;if(!d||!c||d*a<=c){this._write("--aparte-scroll-rail-hit-size",""),this._write("--aparte-scroll-rail-gap","");return}let u=Math.max(eu,Math.floor(c/d));this._write("--aparte-scroll-rail-hit-size",`${u}px`),this._write("--aparte-scroll-rail-gap",`${Math.max(0,u-o)}px`)}_onClick=t=>{let e=t.target.closest(".aparte-scroll-rail__tick");if(!e||!this.contains(e))return;let s=e.dataset.messageId;s&&this.jumpTo(s)};_onKeydown=t=>{if(t.key!=="ArrowDown"&&t.key!=="ArrowUp"&&t.key!=="Home"&&t.key!=="End")return;let e=Array.from(this.querySelectorAll(".aparte-scroll-rail__tick")),s=e.indexOf(lt(this));if(s===-1)return;t.preventDefault();let i=t.key==="Home"?0:t.key==="End"?e.length-1:t.key==="ArrowDown"?Math.min(e.length-1,s+1):Math.max(0,s-1),r=e[i];r&&(this._setTabStop(r,e),r.focus())};jumpTo(t){if(!this.dispatchEvent(new CustomEvent("aparte-scroll-rail-jump",{detail:{messageId:t},bubbles:!0,composed:!0,cancelable:!0})))return;let s=this._bubbleOf(t);s&&(this._viewport()?.setAutoScroll?.(!1),this._scrollTo(s),this._setCurrent(this._markFor(s)),this._hold(t))}_bubbleOf(t){return this._viewport()?.querySelector(`aparte-chat-bubble[message-id="${K(t)}"]`)??null}_scrollTo(t){let e=typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion: reduce)").matches;t.scrollIntoView({block:"start",behavior:e?"auto":"smooth"})}_hold(t){this._release(),this._held=t,this._alignPasses=0,this._settleSurface=this._scrollSurface(),this._settleSurface?.addEventListener("scroll",this._onSurfaceScroll),this._bumpSettle()}_bumpSettle(){this._settleTimer!==null&&clearTimeout(this._settleTimer),this._settleTimer=setTimeout(()=>this._settle(),su)}_settle(){let t=this._held,e=this._settleSurface,s=t?this._bubbleOf(t):null;if(t&&s&&e&&this._alignPasses<nu){let i=e.getBoundingClientRect().top+(parseFloat(getComputedStyle(e).scrollPaddingTop)||0),r=s.getBoundingClientRect().top-i;if(Math.abs(r)>iu){this._alignPasses++,this._scrollTo(s),this._bumpSettle();return}}this._release(),t&&this._setCurrent(s?this._markFor(s):t)}_release(){this._settleTimer!==null&&clearTimeout(this._settleTimer),this._settleTimer=null,this._settleSurface?.removeEventListener("scroll",this._onSurfaceScroll),this._settleSurface=null,this._held=null}};function Qa(n){return n instanceof Element&&n.localName==="aparte-chat-bubble"}function Fa(n){return Array.from(n).some(t=>t instanceof Element&&(Qa(t)||t.localName==="aparte-chat-viewport"||t.querySelector("aparte-chat-bubble")!==null))}function xn(n,t){if(n.length!==t.length)return!1;for(let e=0;e<n.length;e++)if(n[e]!==t[e])return!1;return!0}H(ls);customElements.get("aparte-scroll-rail")||customElements.define("aparte-scroll-rail",ls);var ru="(max-width: 48rem)",cs=class extends HTMLElement{static get observedAttributes(){return["collapsed","breakpoint"]}_media=null;_scrim=null;_opener=null;_lastCollapsed=null;_ready=!1;_closedByHost=!1;_hostIntentSeeded=!1;_auto=!1;_ownHidden=!1;_query="";_listWatch=null;get collapsed(){return this.hasAttribute("collapsed")}set collapsed(t){this.toggleAttribute("collapsed",z(t))}get drawer(){return this.hasAttribute("data-drawer")}connectedCallback(){this.classList.contains("aparte-sidebar")||this.classList.add("aparte-sidebar"),this.getAttribute("role")||this.setAttribute("role","complementary"),this._relabel(),this._hostIntentSeeded||(this._closedByHost=this.collapsed,this._hostIntentSeeded=!0),this.addEventListener("input",this._onInput),typeof MutationObserver=="function"&&(this._listWatch=new MutationObserver(t=>{t.some(e=>e.target!==this)&&this._syncNoMatch()}),this._listWatch.observe(this,{subtree:!0,attributes:!0,attributeFilter:["data-no-match","loading"]})),document.addEventListener("keydown",this._onKeydown),document.addEventListener("click",this._onDocumentClick),window.addEventListener("aparte-config-change",this._onConfigChange),this._watchBreakpoint(),this._syncHidden(),this._lastCollapsed=this.collapsed,this.id||(this.id=`aparte-sidebar-${++au}`),this._syncToggles(),this._ready=!0}_watchBreakpoint(){this._media?.removeEventListener("change",this._onMediaChange),this._media=null;let t=(this.getAttribute("breakpoint")??"").trim();if(t==="none"){this._applyDrawer(!1);return}if(typeof matchMedia!="function")return;let e=t?`(max-width: ${t})`:ru;this._media=matchMedia(e),this._media.addEventListener("change",this._onMediaChange),this._applyDrawer(this._media.matches)}disconnectedCallback(){this.removeEventListener("input",this._onInput),this._listWatch?.disconnect(),this._listWatch=null,document.removeEventListener("keydown",this._onKeydown),document.removeEventListener("click",this._onDocumentClick),window.removeEventListener("aparte-config-change",this._onConfigChange),this._media?.removeEventListener("change",this._onMediaChange),this._media=null,this._ready=!1}attributeChangedCallback(t){if(!this._ready)return;if(t==="breakpoint"){this._watchBreakpoint();return}if(t!=="collapsed")return;let e=this.collapsed;e!==this._lastCollapsed&&(this._lastCollapsed=e,!this._auto&&!this.drawer&&(this._closedByHost=e),this._syncScrim(),this._syncHidden(),this._syncToggles(),e&&this.drawer&&this._opener?.isConnected?(this._opener.focus(),this._opener=null):!e&&this.drawer&&this._focusFirst(),this.dispatchEvent(new CustomEvent("aparte-sidebar-toggle",{detail:{collapsed:e,drawer:this.drawer},bubbles:!0,composed:!0})))}open(t){t&&(this._opener=t),this.collapsed=!1}close(){this.collapsed=!0}toggle(t){this.collapsed?this.open(t):this.close()}_onMediaChange=t=>this._applyDrawer(t.matches);_applyDrawer(t){let e=this.drawer;this.toggleAttribute("data-drawer",t),this._auto=!0;try{t&&!e?this.collapsed=!0:!t&&e&&!this._closedByHost&&(this.collapsed=!1)}finally{this._auto=!1}this._syncScrim(),this._syncHidden(),this._syncToggles()}_syncToggles(){let t="[data-aparte-sidebar-toggle]",e=At(this),s=e===document?Array.from(document.querySelectorAll(t)):[...e.querySelectorAll(t),...document.querySelectorAll(t)];for(let i of s)it(i)||!this._drives(i)||(i.setAttribute("aria-expanded",String(!this.collapsed)),i.setAttribute("aria-controls",this.id))}_drives(t){let e=t.getAttribute("data-aparte-sidebar-toggle");return e?e===this.id:lu(t)===this}_syncHidden(){this.collapsed?(this.toggleAttribute("inert",!0),this.setAttribute("aria-hidden","true"),this._ownHidden=!0):this._ownHidden&&(this.removeAttribute("inert"),this.removeAttribute("aria-hidden"),this._ownHidden=!1)}_focusFirst(){Wa(this)[0]?.focus()}_syncScrim(){let t=this.drawer&&!this.collapsed;t&&!this._scrim?(this._scrim=document.createElement("div"),this._scrim.className="aparte-sidebar__scrim",this._scrim.setAttribute("aria-hidden","true"),this._scrim.addEventListener("click",()=>this.close()),this.appendChild(this._scrim)):!t&&this._scrim&&(this._scrim.remove(),this._scrim=null)}_onKeydown=t=>{if(!(!this.drawer||this.collapsed)){if(t.key==="Escape"){t.preventDefault(),this.close();return}if(t.key==="Tab"){let e=Wa(this);if(e.length===0)return;let s=e[0],i=e[e.length-1],r=lt(this);this.contains(r)?t.shiftKey&&r===s?(t.preventDefault(),i.focus()):!t.shiftKey&&r===i&&(t.preventDefault(),s.focus()):(t.preventDefault(),s.focus())}}};_onDocumentClick=t=>{let e=_t(t)?.closest?.("[data-aparte-sidebar-toggle]");!e||it(e)||this._drives(e)&&this.toggle(e)};_onInput=t=>{let e=t.target;e?.matches?.("[data-aparte-sidebar-search]")&&this.filter(e.value)};filter(t){this._query=t;let e=0,s=!1;for(let i of this._lists())typeof i.filter=="function"?e+=i.filter(t):(e+=Ln(i,is(t)),s=!0);return s&&typeof customElements<"u"&&customElements.whenDefined("aparte-conversation-list").then(()=>{if(this._query===t)for(let i of this._lists())i.filter?.(t);this._syncNoMatch()}),this._syncNoMatch(),e}_lists(){return Array.from(this.querySelectorAll("aparte-conversation-list"))}_syncNoMatch(){let t=is(this._query),e=t!==""&&this._lists().every(s=>typeof s.filter=="function"?s.hasAttribute("data-no-match"):!s.hasAttribute("loading")&&Ln(s,t)===0);this.toggleAttribute("data-no-match",e)}_onConfigChange=()=>this._relabel();_relabel(){if(this.hasAttribute("aria-label")&&this.dataset.ownLabel!=="locale")return;let t=T(this).getLocale();this.setAttribute("aria-label",t.sidebarLabel??"Conversations"),this.dataset.ownLabel="locale"}},au=0,ou=["a[href]","button:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(",");function Wa(n){return Array.from(n.querySelectorAll(ou)).filter(t=>!t.closest("[hidden]")&&t.checkVisibility?.()!==!1)}function lu(n){return n.closest("aparte-sidebar")??At(n).querySelector("aparte-sidebar")??document.querySelector("aparte-sidebar")}H(cs);customElements.get("aparte-sidebar")||customElements.define("aparte-sidebar",cs);function Ua(n,t,e){return Number.isFinite(n)?n<t?t:n>e?e:n:t}function cu(n){let t=Number.isFinite(n.startPercent)?n.startPercent:0;if(!Number.isFinite(n.containerPx)||n.containerPx<=0)return Ua(t,0,100);let i=((!n.vertical&&n.rtl)!==(n.primaryEnd===!0)?-1:1)*n.deltaPx*100/n.containerPx;return Ua(t+i,0,100)}function ja(n,t,e,s,i=!1){if(n==="Home")return-100;if(n==="End")return 100;let r=(t?10:1)*(i?-1:1);return s?n==="ArrowUp"?-r:n==="ArrowDown"?r:null:n==="ArrowLeft"?e?r:-r:n==="ArrowRight"?e?-r:r:null}var du="(max-width: 48rem)",ee=38,uu=300;function se(n,t){let e=Number.parseFloat(n??"");return Number.isFinite(e)?e<0?0:e>100?100:e:t}var ds=class n extends HTMLElement{static get observedAttributes(){return["position","orientation","primary","collapsed","breakpoint","pane","disabled","label","single"]}_handle=null;_scrim=null;_media=null;_observer=null;_measureRafId=null;_observedPx=0;static _paneIdSeq=0;_position=ee;_initialPosition=ee;_initialCaptured=!1;_preCollapsePosition=null;_lastPosition=null;_lastCollapsed=null;_lastPane=null;_source="api";_ready=!1;_dragging=!1;_captured=!1;_moved=!1;_pointerId=null;_dragStartPercent=ee;_dragOriginPx=0;_dragContainerPx=0;_keying=!1;get position(){return this._position}set position(t){let e=se(String(t),this._position);this.isConnected&&e===this._lastPosition||(this._position=e,this._setLive(e),this.isConnected&&this._commit("api"))}get orientation(){return this.getAttribute("orientation")==="vertical"?"vertical":"horizontal"}set orientation(t){this.setAttribute("orientation",t)}get primary(){return this.getAttribute("primary")==="end"?"end":"start"}set primary(t){this.setAttribute("primary",t)}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(t){this.toggleAttribute("collapsed",z(t))}get pane(){return this.getAttribute("pane")==="end"?"end":"start"}set pane(t){this.setAttribute("pane",t)}get disabled(){return this.hasAttribute("disabled")}set disabled(t){this.toggleAttribute("disabled",z(t))}get stacked(){return this.hasAttribute("data-stacked")||this.hasAttribute("single")||this.classList.contains("aparte-split--only-start")||this.classList.contains("aparte-split--only-end")}get single(){return this.hasAttribute("single")}set single(t){this.toggleAttribute("single",z(t))}collapse(){this.collapsed=!0}expand(){this.collapsed=!1}toggleCollapse(){this.collapsed=!this.collapsed}showPane(t){this.pane=t}reset(){this._position=this._initialPosition,this._setLive(this._position),this.isConnected&&this._commit("api")}connectedCallback(){this.classList.contains("aparte-split")||this.classList.add("aparte-split"),this._handle=this._ensureHandle();let t=this.getAttribute("position");t!==null?(this._position=se(t,ee),this._setLive(this._position)):this._position=se(getComputedStyle(this).getPropertyValue("--aparte-split-position"),ee),this._initialCaptured||(this._initialPosition=this._position,this._initialCaptured=!0),this.collapsed&&(this._lastCollapsed!==!0&&(this._preCollapsePosition=this._position),this._position=0,this._setLive(0)),this._lastPosition=this._position,this._lastCollapsed=this.collapsed,this._lastPane=this.pane,this._stampHandle(),this._relabel(),this._measureBounds(),this._handle.addEventListener("pointerdown",this._onPointerDown),this._handle.addEventListener("dblclick",this._onDoubleClick),this._handle.addEventListener("focusout",this._onFocusOut),this.addEventListener("keydown",this._onKeydown),this.addEventListener("keyup",this._onKeyup),document.addEventListener("click",this._onDocumentClick),window.addEventListener("aparte-config-change",this._onConfigChange),this._watchBreakpoint(),this._watchSize(),this._ready=!0,this._syncPaneControls()}disconnectedCallback(){this._handle?.removeEventListener("pointerdown",this._onPointerDown),this._handle?.removeEventListener("dblclick",this._onDoubleClick),this._handle?.removeEventListener("focusout",this._onFocusOut),this.removeEventListener("keydown",this._onKeydown),this.removeEventListener("keyup",this._onKeyup),document.removeEventListener("click",this._onDocumentClick),window.removeEventListener("aparte-config-change",this._onConfigChange),this._releasePointer(),this._media?.removeEventListener("change",this._onMediaChange),this._media=null,this._observer?.disconnect(),this._observer=null,this._measureRafId!==null&&(cancelAnimationFrame(this._measureRafId),this._measureRafId=null),this._removeScrim(),this._handle?.removeAttribute("data-dragging"),this._dragging=!1,this._keying=!1,this._ready=!1}attributeChangedCallback(t){if(this._ready)switch(t){case"position":{let e=se(this.getAttribute("position"),this._position);if(e===this._lastPosition)return;this._position=e,this._setLive(e),this._commit();return}case"collapsed":{let e=this.collapsed;if(e===this._lastCollapsed)return;this._lastCollapsed=e,e?(this._preCollapsePosition=this._position,this._position=0):this._position=this._preCollapsePosition??this._initialPosition,this._setLive(this._position),this._commit();return}case"pane":{let e=this.pane;if(this._syncPaneControls(),e===this._lastPane)return;this._lastPane=e,this._commit();return}case"orientation":case"primary":this._stampHandle(),this._measureBounds();return;case"disabled":this.disabled&&this._dragging&&this._endDrag("pointer",this._dragStartPercent),this._stampHandle();return;case"single":this.single&&this._dragging&&this._endDrag("pointer",this._dragStartPercent),this._stampHandle(),this._syncPaneControls();return;case"breakpoint":this._watchBreakpoint();return;case"label":this._relabel()}}_ensureHandle(){let t=Array.from(this.children).find(i=>i instanceof HTMLElement&&i.classList.contains("aparte-split__handle"));if(t){if(this.children[1]!==t){let i=Array.from(this.children).filter(r=>r!==t)[1]??null;this.insertBefore(t,i)}return t}let e=document.createElement("div");e.className="aparte-split__handle";let s=this.children[1]??null;return s?this.insertBefore(e,s):this.appendChild(e),e}_panes(){return Array.from(this.children).filter(t=>t instanceof HTMLElement&&!t.classList.contains("aparte-split__handle"))}_primaryPane(){let t=this._panes();return(this.primary==="end"?t[t.length-1]:t[0])??null}_stampHandle(){let t=this._handle;if(!t)return;t.setAttribute("role","separator"),t.setAttribute("aria-orientation",this.orientation==="vertical"?"horizontal":"vertical"),this.disabled||this.stacked?t.removeAttribute("tabindex"):t.setAttribute("tabindex","0"),t.setAttribute("aria-valuenow",String(Math.round(this._achievedPercent())));let e=this._primaryPane();e&&(e.id||(e.id=`aparte-split-pane-${++n._paneIdSeq}`),t.setAttribute("aria-controls",e.id))}_measure(t){let e=t.getBoundingClientRect();return this.orientation==="vertical"?e.height:e.width}_achievedPercent(){if(this.stacked)return this._position;let t=this._measure(this),e=this._primaryPane();return!e||!(t>0)?this._position:Math.max(0,Math.min(100,this._measure(e)/t*100))}_measureBounds(){let t=this._handle;if(!t||this._dragging||this.stacked)return;let e=this._primaryPane(),s=this._measure(this);if(!e||!(s>0)){t.setAttribute("aria-valuemin","0"),t.setAttribute("aria-valuemax","100");return}let i=this.style.getPropertyValue("--aparte-split-position");this.style.setProperty("--aparte-split-position","0%");let r=this._measure(e)/s*100;this.style.setProperty("--aparte-split-position","100%");let a=this._measure(e)/s*100;i?this.style.setProperty("--aparte-split-position",i):this.style.removeProperty("--aparte-split-position"),t.setAttribute("aria-valuemin",String(Math.round(r))),t.setAttribute("aria-valuemax",String(Math.round(a))),t.setAttribute("aria-valuenow",String(Math.round(this._achievedPercent())))}_watchSize(){typeof ResizeObserver=="function"&&(this._observer=new ResizeObserver(()=>{let t=this._measure(this);Math.abs(t-this._observedPx)<=1||(this._observedPx=t,this._measureRafId===null&&(this._measureRafId=requestAnimationFrame(()=>{this._measureRafId=null,this._measureBounds()})))}),this._observer.observe(this))}_setLive(t){this.style.setProperty("--aparte-split-position",`${Math.round(t*1e3)/1e3}%`)}_commit(t=this._source){let e=Math.round(this._achievedPercent());this._position=e,this._setLive(e),this._lastPosition=e,this.getAttribute("position")!==String(e)&&this.setAttribute("position",String(e)),this._handle?.setAttribute("aria-valuenow",String(e)),this.dispatchEvent(new CustomEvent("aparte-split-resize",{detail:{position:e,collapsed:this.collapsed,stacked:this.stacked,pane:this.pane,orientation:this.orientation,source:t},bubbles:!0,composed:!0}))}_rtl(){return getComputedStyle(this).direction==="rtl"}_onPointerDown=t=>{this.disabled||this.stacked||this._dragging||t.button>0||(t.preventDefault(),this._handle?.focus(),this._dragging=!0,this._captured=!1,this._moved=!1,this._pointerId=t.pointerId,this._dragStartPercent=this._position,this._dragOriginPx=this.orientation==="vertical"?t.clientY:t.clientX,this._dragContainerPx=this._measure(this),this._handle?.setAttribute("data-dragging",""),this._addScrim(),window.addEventListener("pointermove",this._onPointerMove),window.addEventListener("pointerup",this._onPointerUp),window.addEventListener("pointercancel",this._onPointerCancel))};_isOurPointer(t){return this._pointerId===null||t.pointerId===this._pointerId}_onPointerMove=t=>{if(!this._dragging||!this._isOurPointer(t))return;if(t.buttons===0){this._endDrag("pointer");return}if(!this._captured&&this._pointerId!==null){this._captured=!0;try{this._handle?.setPointerCapture(this._pointerId)}catch{}}let e=this.orientation==="vertical"?t.clientY:t.clientX;this._position=cu({startPercent:this._dragStartPercent,deltaPx:e-this._dragOriginPx,containerPx:this._dragContainerPx,rtl:this._rtl(),vertical:this.orientation==="vertical",primaryEnd:this.primary==="end"}),this._moved=!0,this._setLive(this._position)};_onPointerUp=t=>{this._isOurPointer(t)&&this._endDrag("pointer")};_onPointerCancel=t=>{this._isOurPointer(t)&&this._endDrag("pointer")};_endDrag(t,e){if(!this._dragging)return;let s=this._moved;this._dragging=!1,this._moved=!1,this._releasePointer(),this._handle?.removeAttribute("data-dragging"),this._removeScrim(!s),e!==void 0&&(this._position=e,this._setLive(e)),!(!s&&e===void 0)&&(this._measureBounds(),this._commit(t))}_releasePointer(){if(window.removeEventListener("pointermove",this._onPointerMove),window.removeEventListener("pointerup",this._onPointerUp),window.removeEventListener("pointercancel",this._onPointerCancel),this._captured&&this._pointerId!==null)try{this._handle?.releasePointerCapture(this._pointerId)}catch{}this._captured=!1,this._pointerId=null}_addScrim(){if(this._scrim||!this._handle)return;let t=document.createElement("div");t.className="aparte-split__scrim",t.setAttribute("aria-hidden","true"),this._handle.appendChild(t),this._scrim=t}_removeScrim(t=!1){let e=this._scrim;if(this._scrim=null,!!e){if(!t){e.remove();return}e.style.pointerEvents="none",setTimeout(()=>e.remove(),uu)}}_onDoubleClick=()=>{this.disabled||this.stacked||this.reset()};_onKeydown=t=>{if(this._dragging&&t.key==="Escape"){t.preventDefault(),this._endDrag("pointer",this._dragStartPercent);return}if(this.disabled||this.stacked||t.target!==this._handle)return;if(t.key==="Enter"){t.preventDefault(),this._source="keyboard";try{this.toggleCollapse()}finally{this._source="api"}return}let e=ja(t.key,t.shiftKey,this._rtl(),this.orientation==="vertical",this.primary==="end");e!==null&&(t.preventDefault(),this._keying=!0,this._position=se(String(this._position+e),this._position),this._setLive(this._position))};_onKeyup=t=>{!this._keying||t.target!==this._handle||ja(t.key,t.shiftKey,this._rtl(),this.orientation==="vertical")!==null&&(this._keying=!1,this._commit("keyboard"))};_onFocusOut=()=>{this._keying&&(this._keying=!1,this._commit("keyboard"))};_watchBreakpoint(){this._media?.removeEventListener("change",this._onMediaChange),this._media=null;let t=(this.getAttribute("breakpoint")??"").trim();if(t==="none"){this._applyStacked(!1);return}if(typeof matchMedia!="function")return;let e=t?`(max-width: ${t})`:du;this._media=matchMedia(e),this._media.addEventListener("change",this._onMediaChange),this._applyStacked(this._media.matches)}_onMediaChange=t=>this._applyStacked(t.matches);_applyStacked(t){let e=this.hasAttribute("data-stacked");t&&!e&&this._dragging&&this._endDrag("pointer",this._dragStartPercent),this.toggleAttribute("data-stacked",t),t!==e&&this._syncPaneControls(),t&&!e?this.hasAttribute("pane")||this.showPane("start"):!t&&e&&this.removeAttribute("pane"),this._lastPane=this.pane,this._stampHandle(),t!==e&&this._measureBounds()}_onDocumentClick=t=>{let e=_t(t)?.closest?.("[data-aparte-split-pane]");if(!e||it(e))return;let s=(e.getAttribute("data-aparte-split-pane")??"").trim(),i=s==="start"||s==="end"?s:null,r=i?"":s;if(r){if(r!==this.id)return}else if((e.closest("aparte-split")??At(e).querySelector("aparte-split")??document.querySelector("aparte-split"))!==this)return;this.showPane(i??(this.pane==="start"?"end":"start"))};_syncPaneControls(){let t=new Set([At(this),document]);for(let e of t)for(let s of e.querySelectorAll("[data-aparte-split-pane]")){let i=(s.getAttribute("data-aparte-split-pane")??"").trim();i!=="start"&&i!=="end"||s.localName!=="button"&&s.getAttribute("role")!=="button"||it(s)||(s.closest("aparte-split")??At(s).querySelector("aparte-split")??document.querySelector("aparte-split"))!==this||(this.stacked?s.setAttribute("aria-pressed",String(i===this.pane)):s.removeAttribute("aria-pressed"))}}_onConfigChange=()=>this._relabel();_relabel(){let t=this._handle;if(!t||t.hasAttribute("aria-labelledby")||t.hasAttribute("aria-label")&&t.dataset.ownLabel!=="locale")return;let e=T(this).getLocale();t.setAttribute("aria-label",this.getAttribute("label")??e.splitHandleLabel??"Resize the panes"),t.dataset.ownLabel="locale"}};H(ds);customElements.get("aparte-split")||customElements.define("aparte-split",ds);var hu="(max-width: 30rem), (max-height: 30rem)",pu=["a[href]","button:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(","),us=class extends HTMLElement{static get observedAttributes(){return["open","label","breakpoint"]}_button=null;_childWatch=null;_hostWatch=null;_media=null;_lastOpen=null;_ready=!1;get open(){return this.hasAttribute("open")}set open(t){this.toggleAttribute("open",z(t))}get sheet(){return this.hasAttribute("data-sheet")}connectedCallback(){if(this.classList.contains("aparte-launcher")||this.classList.add("aparte-launcher"),!this._button){let t=this.querySelector(":scope > button.aparte-launcher__button");this._button=t instanceof HTMLButtonElement?t:document.createElement("button"),this._button.type="button",this._button.addEventListener("click",this._onButtonClick)}for(let t of this.querySelectorAll(":scope > .aparte-launcher__button"))t!==this._button&&t.remove();this._button.parentNode!==this&&this.appendChild(this._button),typeof MutationObserver=="function"&&(this._childWatch??=new MutationObserver(()=>this._keepButton()),this._childWatch.observe(this,{childList:!0}),this._hostWatch??=new MutationObserver(()=>this._renderButton()),this._hostWatch.observe(this,{attributes:!0,attributeFilter:[Xt],subtree:!0})),this.addEventListener("click",this._onClick),this.addEventListener("keydown",this._onKeydown),window.addEventListener("aparte-config-change",this._onConfigChange),this._watchBreakpoint(),this._lastOpen=this.open,this._renderButton(),this._ready=!0}disconnectedCallback(){this.removeEventListener("click",this._onClick),this.removeEventListener("keydown",this._onKeydown),window.removeEventListener("aparte-config-change",this._onConfigChange),this._childWatch?.disconnect(),this._hostWatch?.disconnect(),this._media?.removeEventListener("change",this._onMediaChange),this._media=null,this._ready=!1}attributeChangedCallback(t){if(!this._ready)return;if(t==="breakpoint"){this._watchBreakpoint();return}if(this._renderButton(),t!=="open")return;let e=this.open;e!==this._lastOpen&&(this._lastOpen=e,!e&&this._button&&this.contains(lt(this))&&this._button.focus(),this._announce())}_announce(){this.dispatchEvent(new CustomEvent("aparte-launcher-toggle",{detail:{open:this.open,sheet:this.sheet},bubbles:!0,composed:!0}))}show(){this.open=!0}close(){this.open=!1}toggle(){this.open=!this.open}_onButtonClick=()=>{let t=!this.open;this.toggle(),t&&this._focusChat()};_onConfigChange=()=>this._renderButton();_config(){let t=Array.from(this.querySelectorAll(`[${Xt}]`)).find(e=>!it(e));return T(t??this)}_keepButton(){this._button&&this._button.parentNode!==this&&this.appendChild(this._button)}_renderButton(){let t=this._button;if(!t)return;this._keepButton();let e=this._config(),s=e.getLocale(),i=this.open,r=i?"":(this.getAttribute("label")??"").trim(),a=r?"aparte-btn--pill":"aparte-btn--circle";t.className=["aparte-btn","aparte-btn--primary","aparte-btn--solid","aparte-btn--lg",a,"aparte-launcher__button"].join(" "),t.setAttribute("aria-expanded",String(i)),r?t.removeAttribute("aria-label"):t.setAttribute("aria-label",i?s.launcherClose??"Close the chat":s.launcherOpen??"Open the chat");let o=document.createElement("span");o.className="aparte-launcher__icon",o.setAttribute("aria-hidden","true"),o.innerHTML=i?e.getIcon("launcherClose")??e.getIcon("close"):e.getIcon("launcherOpen")??e.getIcon("messageSquare");let l=[o];if(r){let c=document.createElement("span");c.className="aparte-launcher__label",c.textContent=r,l.push(c)}t.replaceChildren(...l)}_onMediaChange=t=>this._applySheet(t.matches);_watchBreakpoint(){this._media?.removeEventListener("change",this._onMediaChange),this._media=null;let t=(this.getAttribute("breakpoint")??"").trim();if(t==="none"||typeof matchMedia!="function"){this._applySheet(!1);return}this._media=matchMedia(t?`(max-width: ${t})`:hu),this._media.addEventListener("change",this._onMediaChange),this._applySheet(this._media.matches)}_applySheet(t){t!==this.sheet&&(this.toggleAttribute("data-sheet",t),this._ready&&this.open&&this._announce())}_focusables(){return Array.from(this.querySelectorAll(pu)).filter(t=>!t.closest("[hidden]")&&t.checkVisibility?.()!==!1)}_focusChat(){(Array.from(this.querySelectorAll('[role="textbox"]:not([aria-disabled="true"])')).find(s=>!it(s)&&!s.closest("[hidden]")&&s.checkVisibility?.()!==!1)??this._focusables().find(s=>s!==this._button))?.focus()}_onClick=t=>{let e=_t(t)?.closest?.("[data-aparte-launcher-close]");e&&this.contains(e)&&!it(e)&&this.close()};_inModalDialog(t){let e=_t(t)?.closest?.("dialog[open]");if(!e||!this.contains(e))return!1;try{return e.matches(":modal")}catch{return!0}}_onKeydown=t=>{if(!this.open)return;if(t.key==="Escape"){if(t.defaultPrevented||t.isComposing||t.keyCode===229||this._inModalDialog(t))return;t.preventDefault(),this.close();return}if(t.key!=="Tab"||!this.sheet)return;let e=this._focusables();if(e.length===0)return;let s=e[0],i=e[e.length-1],r=lt(this);t.shiftKey&&r===s?(t.preventDefault(),i.focus()):!t.shiftKey&&r===i&&(t.preventDefault(),s.focus())}};H(us);customElements.get("aparte-launcher")||customElements.define("aparte-launcher",us);var Ga=Symbol.for("aparte.imageHolds"),Za=".aparte-image-held[data-aparte-image]";function to(n){let t=n.getAttribute("data-aparte-image")??"";T(n).showImage(t);let e=document.createElement("img");e.setAttribute("referrerpolicy","no-referrer"),e.setAttribute("alt",n.getAttribute("data-aparte-image-alt")??""),e.setAttribute("src",t);let s=n===document.activeElement;n.replaceWith(e),s&&(e.tabIndex=-1,e.focus({preventScroll:!0}))}function fu(n){if(n.button!==0||n.ctrlKey||n.metaKey||n.shiftKey||n.altKey)return;let t=n.target?.closest?.(Za);t&&(n.preventDefault(),n.stopPropagation(),to(t))}function gu(n){if(n.key!=="Enter"&&n.key!==" ")return;let t=n.target;t?.matches?.(`span${Za}`)&&(n.preventDefault(),n.stopPropagation(),to(t))}function _u(){let n=document;n[Ga]||(n[Ga]=!0,n.addEventListener("click",fu,!0),n.addEventListener("keydown",gu,!0))}typeof document<"u"&&(wa(),_u());export{B as a,X as b,G as c,Yo as d,T as e,x as f,qt as g,vc as h,zt as i,Q as j,Zc as k,K as l,ba as m,Vs as n};
|
|
209
|
+
//# sourceMappingURL=chunk-4MZPEZPE.js.map
|