@aparte/n8n-chat 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +207 -2
  3. package/dist/cdn/chunks/chunk-MU6PIUJC.js +206 -0
  4. package/dist/cdn/chunks/chunk-MU6PIUJC.js.map +7 -0
  5. package/dist/cdn/chunks/chunk-XAWE4EAK.js +2 -0
  6. package/dist/cdn/chunks/chunk-XAWE4EAK.js.map +7 -0
  7. package/dist/cdn/chunks/de-WJNL5YNK.js +2 -0
  8. package/dist/cdn/chunks/de-WJNL5YNK.js.map +7 -0
  9. package/dist/cdn/chunks/es-DV5N3CXP.js +2 -0
  10. package/dist/cdn/chunks/es-DV5N3CXP.js.map +7 -0
  11. package/dist/cdn/chunks/fr-YU75PBOR.js +2 -0
  12. package/dist/cdn/chunks/fr-YU75PBOR.js.map +7 -0
  13. package/dist/cdn/chunks/highlight-HDJ3ROJ4.js +153 -0
  14. package/dist/cdn/chunks/highlight-HDJ3ROJ4.js.map +7 -0
  15. package/dist/cdn/chunks/it-DZTHWNO3.js +2 -0
  16. package/dist/cdn/chunks/it-DZTHWNO3.js.map +7 -0
  17. package/dist/cdn/chunks/ja-QO442LBN.js +2 -0
  18. package/dist/cdn/chunks/ja-QO442LBN.js.map +7 -0
  19. package/dist/cdn/chunks/ko-EGFZJCXQ.js +2 -0
  20. package/dist/cdn/chunks/ko-EGFZJCXQ.js.map +7 -0
  21. package/dist/cdn/chunks/pt-BR-526LHI67.js +2 -0
  22. package/dist/cdn/chunks/pt-BR-526LHI67.js.map +7 -0
  23. package/dist/cdn/chunks/ru-5WNEMKNP.js +2 -0
  24. package/dist/cdn/chunks/ru-5WNEMKNP.js.map +7 -0
  25. package/dist/cdn/chunks/zh-CN-ABSHNLG6.js +2 -0
  26. package/dist/cdn/chunks/zh-CN-ABSHNLG6.js.map +7 -0
  27. package/dist/cdn/n8n-chat.js +97 -0
  28. package/dist/cdn/n8n-chat.js.map +7 -0
  29. package/dist/create-chat.d.ts +187 -0
  30. package/dist/highlight-DDyMJYBk.js +29 -0
  31. package/dist/highlight-DDyMJYBk.js.map +1 -0
  32. package/dist/highlight.d.ts +2 -0
  33. package/dist/icons.d.ts +7 -0
  34. package/dist/index.d.ts +11 -0
  35. package/dist/index.js +593 -0
  36. package/dist/index.js.map +1 -0
  37. package/dist/strings.d.ts +40 -0
  38. package/dist/style.css +370 -0
  39. package/dist/theme.css +368 -0
  40. package/package.json +81 -5
@@ -0,0 +1,206 @@
1
+ var Ps=new Set;function $i(n){let t=String(n?.type??"undefined");Ps.has(t)||(Ps.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 He(n){let{transportCall:t,toolLookup:e,toolConfigLookup:s,approvalResolver:i,emitter:r,signal:a,maxTurns:o=10,toolTimeoutMs:l=3e5,deferral:d}=n,c=n.baseRequest,h=0,p=n.idGen??(M=>`${M}-${h++}`),u=[...c.messages],_=M=>{u.push(M),n.onHistoryAppend?.(M)},f=!0,m=0,I,x;r({type:"run-start"});let R=d?Ns(u):[];if(R.length>0){let M=[],k={turns:1,maxTurns:o,toolLookup:e,toolConfigLookup:s,approvalResolver:i,emitter:r,signal:a,toolTimeoutMs:l,declareCall:()=>{},append:_,deferral:d};for(let[b,w]of R.entries()){if(M.length>0){M.push({toolCallId:w.id,name:w.name,input:w.input,reason:Ds(w,s)});continue}let C;try{C=await Hs(w,k)}catch(g){for(let v of R.slice(b+1))r({type:"tool-aborted",toolCallId:v.id});throw g}if(typeof C=="object"){M.push({toolCallId:w.id,name:w.name,input:w.input,reason:C.defer});continue}if(C==="stop-run"){for(let g of R.slice(b+1))r({type:"tool-aborted",toolCallId:g.id});f=!1;break}}if(M.length>0&&!a.aborted){r({type:"run-suspended",pending:M});return}}for(;f&&!a.aborted;){if(m++,x=void 0,m>o){r({type:"turn-limit-exceeded",scope:"global",limit:o});break}let M=c.toolChoice;if(m===1&&M&&typeof M=="object"&&!Array.isArray(M)&&M.input!==void 0){let U=M,O=p("synthetic-tool");r({type:"tool-start",toolCallId:O,name:U.name,input:U.input});let tt=e(U.name);if(!tt){r({type:"tool-aborted",toolCallId:O,cause:"no-handler"}),f=!1;continue}let $=await $s(tt,{id:O,name:U.name,input:U.input},a,l);if($.status==="aborted"){r($.cause?{type:"tool-aborted",toolCallId:O,cause:$.cause}:{type:"tool-aborted",toolCallId:O}),f=!1;continue}if($.status==="failed")throw r({type:"tool-failed",toolCallId:O,error:Fs($.error)}),$.error;r({type:"tool-resolved",toolCallId:O,result:$.content,structuredResult:$.structuredContent}),_({role:"assistant",content:"",toolCalls:[{id:O,name:U.name,input:U.input}]}),_({role:"tool",content:$.content,toolCallId:O,toolName:U.name}),c={...c,toolChoice:"none",tools:void 0}}let k={...c,messages:u},b=c.toolChoice;b&&typeof b=="object"&&(c={...c,toolChoice:"auto"});let w;try{w=await t(k)}catch(U){if(a.aborted||U?.name==="AbortError"){f=!1;break}throw U}if(typeof w=="string"){r({type:"text-delta",delta:w}),r({type:"text-flush"});break}r({type:"turn-start"});let C="",g=[],v=!1,L=null,S=U=>{g.push(U),!L&&(L={role:"assistant",content:C.trim(),toolCalls:g},_(L))},D=()=>{L&&(L.content=C.trim())},q=new Set,B=U=>{let O=U;for(let tt=2;q.has(O);tt++)O=`${U}#${tt}`;return q.add(O),O},X=[],yt={turns:m,maxTurns:o,toolLookup:e,toolConfigLookup:s,approvalResolver:i,emitter:r,signal:a,toolTimeoutMs:l,declareCall:S,append:_,deferral:d&&{...d,outcomes:void 0}},Be=w[Symbol.asyncIterator](),Rs=async()=>{if(!a.aborted)return!1;try{await Be.return?.(void 0)}catch{}return f=!1,!0};try{for(;!await Rs();){let U=await Be.next();if(await Rs()||U.done)break;let O=U.value;if(O.type==="thinking"){r({type:"thinking-delta",delta:O.delta});continue}if(O.type==="text"){C+=O.delta,r({type:"text-delta",delta:O.delta});continue}if(O.type==="done"){O.usage&&(I=O.usage),O.finishReason&&(x=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"){$i(O);continue}v=!0;let tt=B(O.id);r({type:"tool-start",toolCallId:tt,name:O.name,input:O.input});let $={id:tt,name:O.name,input:O.input};if(X.length>0){S($);let Os=Ds($,s);Os==="approval"&&r({type:"tool-awaiting-approval",toolCallId:$.id,name:$.name,input:$.input}),X.push({toolCallId:$.id,name:$.name,input:$.input,reason:Os});continue}let Ht=await Hs($,yt);if(typeof Ht=="object"){S($),X.push({toolCallId:$.id,name:$.name,input:$.input,reason:Ht.defer});continue}if(Ht==="stop-run"){f=!1;break}if(Ht==="stop-turn")break}r({type:"text-flush"}),D()}finally{try{await Be.return?.(void 0)}catch{}}if(X.length>0&&!a.aborted)return r({type:"run-suspended",pending:X,usage:I}),I;v||(f=!1)}return a.aborted&&r({type:"run-aborted"}),r({type:"run-done",usage:I,...x?{finishReason:x}:{}}),I}function Ns(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 Ds(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 qs(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 Bs(n,t,e){let s=qs(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 Hs(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 Bs(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,d=typeof i?.needsApproval=="function"?i.needsApproval({id:n.id,name:n.name,input:s}):i?.needsApproval;if(d){let h=r?.kind==="decision"&&d!=="deny"?r:void 0;if(d!=="deny"&&!h&&t.emitter({type:"tool-awaiting-approval",toolCallId:n.id,name:n.name,input:n.input}),!h&&t.deferral&&d!=="deny")return{defer:"approval"};if(!h&&!t.approvalResolver)return t.emitter({type:"tool-aborted",toolCallId:n.id,cause:"no-resolver"}),"stop-run";let p=h;if(!p&&!e.aborted&&t.approvalResolver)try{p=await t.approvalResolver({id:n.id,name:n.name,input:s},e)}catch(u){if(!e.aborted&&u?.name!=="AbortError")throw u}if(e.aborted||!p)return t.emitter({type:"tool-aborted",toolCallId:n.id,cause:"stopped"}),"stop-run";if(!p.approved)return Bs(t,n,p),"stop-turn";p.payload&&typeof p.payload=="object"&&!Array.isArray(p.payload)&&(l={...s,...p.payload}),t.emitter({type:"tool-approved",toolCallId:n.id})}let c=await $s(o,{id:n.id,name:n.name,input:l},e,t.toolTimeoutMs);if(c.status==="aborted")return t.emitter(c.cause?{type:"tool-aborted",toolCallId:n.id,cause:c.cause}:{type:"tool-aborted",toolCallId:n.id}),"stop-run";if(c.status==="failed")throw t.emitter({type:"tool-failed",toolCallId:n.id,error:Fs(c.error)}),c.error;return t.emitter({type:"tool-resolved",toolCallId:n.id,result:c.content,structuredResult:c.structuredContent}),t.declareCall(n),t.append({role:"tool",content:c.content,toolCallId:n.id,toolName:n.name}),"continue"}async function $s(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(h=>{a=()=>h({status:"aborted",cause:"stopped"}),e.addEventListener("abort",a,{once:!0})}),l,d=!1,c=new Promise(h=>{l=setTimeout(()=>{d=!0,i.abort(),h({status:"aborted",cause:"timeout"})},s)});try{return await Promise.race([n(t,i.signal).then(p=>({status:"resolved",content:p.content,structuredContent:p.structuredContent})),c,o])}catch(h){return h?.name==="AbortError"?e.aborted?{status:"aborted",cause:"stopped"}:d?{status:"aborted",cause:"timeout"}:{status:"aborted"}:{status:"failed",error:h}}finally{clearTimeout(l),e.removeEventListener("abort",r),a&&e.removeEventListener("abort",a)}}function Fs(n){return n instanceof Error?n.message||n.name:typeof n=="string"?n:String(n)}var Fi='<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>',Ui='<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>',ji='<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>',Wi='<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>',Gi='<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>',Vi='<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>',zi='<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>',Ki='<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>',Yi='<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>',Qi='<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>',Xi='<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>',Ji='<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>',Zi='<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>',tr='<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>',er='<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>',sr='<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>',nr='<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>',ir='<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>',rr='<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>',ar='<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>',or='<svg class="aparte-icon" viewBox="0 0 24 24" fill="currentColor"><rect x="5" y="5" width="14" height="14" rx="2.5"/></svg>',lr='<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>',cr='<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>',dr='<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>',hr='<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>',ur='<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>',pr='<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>',_r='<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>',fr='<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>',gr='<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>',mr='<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>',br='<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>',Us={copy:Fi,check:Ui,send:ji,loading:Wi,error:Gi,expand:Vi,collapse:zi,terminal:Ki,paperclip:Yi,image:Qi,file:Xi,scrollDown:Ji,retry:Zi,edit:tr,thumbUp:er,thumbDown:sr,prevBranch:nr,nextBranch:ir,tool:rr,close:ar,stop:or,pause:lr,info:cr,archive:dr,unarchive:hr,download:ur,more:pr,pin:_r,trash:fr,menu:mr,alertTriangle:br,messageSquare:gr};function yn(n){return typeof n=="string"?n:n.filter(t=>t.type==="text").map(t=>t.text).join("")}var H=(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))(H||{}),K=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(H).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"}}},At=Us,gt={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",compactionSummaryTitle:"Conversation summary",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.",questionDeclined:"You declined to answer.",artifactNotCreated:"Not created",thoughtFor:"Thought for {duration}",thought:"Thought",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 wn(n){return typeof n.buildRequest=="function"&&typeof n.parseStream=="function"&&typeof n.defaultEndpoint=="string"&&(typeof n.authHeaders=="function"||typeof n.authQuery=="function")}function vr(n){return typeof n=="string"?{key:n}:n&&typeof n=="object"?{key:n.apiKey,endpoint:n.endpoint}:{}}function yr(n,t,e){let s=n?.error,i=typeof s=="object"?s?.message:s;return typeof i=="string"&&i?i:`${e} ${t}`}function wr(n){return typeof n=="string"&&Object.values(H).includes(n)}async function Sr(n,t="HTTP",e){let s=await n.json().catch(()=>{}),i=yr(s,n.status,t),r=s?.error?.code,a=e?.classifyError?.(n.status,s)??(wr(r)?r:void 0)??K.codeForStatus(n.status)??H.UNKNOWN_ERROR;return new K(i,a,void 0,void 0,n.status)}async function Ar(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.`);return n.parseText(s)}var Kt=class{byok;warnedBrowserKey=!1;constructor(t={}){this.byok=t.byok??!1}async chat(t,e,s,i){let{key:r,endpoint:a}=vr(s);if(!this.byok&&r&&this.warnBrowserKeyOnce(i.providerId),!wn(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),d=`${o}${l.path}`,c={"Content-Type":"application/json",...l.headers};if(r&&t.authHeaders&&Object.assign(c,t.authHeaders(r)),r&&t.authQuery){let p=new URLSearchParams(t.authQuery(r)).toString();d+=(d.includes("?")?"&":"?")+p}let h=await fetch(d,{method:"POST",headers:c,body:JSON.stringify(l.body),signal:i.signal});if(!h.ok)throw await Sr(h,"HTTP",t);if(e.stream===!1)return Ar(t,h,i.providerId);if(!h.body)throw new Error(`Provider "${i.providerId}" returned no response body for a streaming request.`);return t.parseStream(h.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 W(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}var Cr=[{start:"<think>",end:"</think>"},{start:"<thinking>",end:"</thinking>"}],bt=class{_options;_thinkingDelimiters;_blocks;_state;_pendingSegment=null;constructor(t={}){let e=t.thinkingDelimiters;this._thinkingDelimiters=e?Array.isArray(e)?e:[e]:Cr,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 d of this._thinkingDelimiters){let c=t.indexOf(d.start);c!==-1&&(s===-1||c<s)&&(s=c)}let i=-1,r;for(let d of this._blocks){let c=this._indexOfTag(t,d.tag);c!==-1&&(i===-1||c<i)&&(i=c,r=d)}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((d,c)=>d.index-c.index),a.length===0)return t.endsWith("`")||t.endsWith("``")||this._thinkingDelimiters.some(d=>this._isPartialMatch(t,d.start))||this._blocks.some(d=>this._isPartialMatch(t,"<"+d.tag)||t.endsWith("<"+d.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 d=t.slice(0,o.index);return!this._state.activeSegment||this._state.activeSegment.type!=="text"?this._state.activeSegment=this._createTextSegment(d):this._state.activeSegment.content+=d,{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 d=this._startCodeBlock(t);return d?{segment:l,remaining:d.remaining}:(l&&(this._state.activeSegment=l),null)}else if(o.type==="thinking"){let d=this._startThinkingBlock(t);return d?{segment:l,remaining:d.remaining}:(l&&(this._state.activeSegment=l),null)}else{let d=this._startBlock(t,r);return d?d.segment&&l?(this._pendingSegment=d.segment,{segment:l,remaining:d.remaining}):{segment:l??d.segment,remaining:d.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,""),{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 c of a.matchAll(/([A-Za-z_][\w:-]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/g))o[c[1]]=c[2]??c[3]??c[4]??"";let l=e.toSegment({attrs:o,id:this._options.autoGenerateIds?this._generateId():""});l.content="";let d=t.slice(s+1);return r?{segment:this._closed(l),remaining:d}:(l.isStreaming=!0,this._state.mode="block",this._state.blockEnd=`</${e.tag}>`,this._state.activeSegment=l,{segment:null,remaining:d})}_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}-${W()}`}_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 Sn(n,t){let e=new bt(t),s=e.parse(n),i=e.finalize();return[...s.segments,...i]}var Er=new Set(["pending","awaiting-approval"]),kr=["content","output","result"];function Mr(n){return kr.some(t=>t in n)}function os(n,t,e,s){let i=xr(t,s);return{...i,messageId:t.messageId??e,index:t.index??n.length,...Yt(i,{startedAt:se(t)?.startedAt??Date.now()})}}function Tr(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 Ir=new Set(["id","type","messageId","index"]);function se(n){return n.meta?.aparte}function Yt(n,t){return{meta:{...n.meta,aparte:{...n.meta?.aparte,...t}}}}function xr(n,t){if(!t)return n;let e={...n};for(let[s,i]of Object.entries(t))if(!(Ir.has(s)||s in n)){if(s==="meta"){let{aparte:r,...a}=i??{};e.meta=a;continue}e[s]=i}return e}function dt(n){return n.type==="tool_call"?!Er.has(n.status):n.isStreaming===!1}function An(n,t){if(dt(n))return t;let e={...n,...t};if(dt(e)){let s=se(n)?.endedAt;return{...t,...Yt(n,{endedAt:s??Date.now()})}}return Mr(t)?{...t,...Yt(n,{endedAt:Date.now()})}:t}function ls(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 Cn(n){let{startedAt:t,endedAt:e}=se(n)??{};if(!(t==null||e==null))return e-t}function En(n){return dt(n)?{}:Yt(n,{endedAt:Date.now()})}function Ne(n){return{content:n.content,...n.isStreaming===!1?{isStreaming:!1}:{}}}function cs(n){return n!=null&&n!=="streaming"&&n!=="pending"}function kn(n){return n.filter(t=>!dt(t)).map(t=>t.id)}function ne(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(Tr(e,s,n.id,t)),e),[])}}function Mn(n){for(let t=0;t<n.length;t++){let e=n[t];e.index!==t&&(n[t]={...e,index:t})}}var Lt="data-aparte-host",We=Symbol.for("aparte.instanceConfig");function Lr(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 Rr(n,t){let e=n[We]??y(n.parentElement);n[We]=t,n.setAttribute(Lt,""),Lr(n,t,e)}function y(n){return n?.closest?.(`[${Lt}]`)?.[We]??Y}var Ft=null;function j(n,t){let e=Ft;Ft=n;try{return t()}finally{Ft=e}}function A(n){return Ft??y(n)}function z(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 Ut(n){let{target:t,config:e,messageId:s,targetId:i}=n,r=new bt({blocks:e.getStreamBlocks()}),a=new Set,o=null,l=new Map,d=(u,_)=>{let f=`tool-${u}`;t.updateSegment?.(f,l.has(f)?_:{..._,deferred:void 0})},c="",h=!1,p=u=>{if(!o||h)return;let _=typeof Element<"u"&&t instanceof Element?y(t):e,f=!u||_.getSegmentDefaults("thinking")?.collapsed===!1;t.updateSegment?.(o,f?{isStreaming:!1}:{collapsed:!0,isStreaming:!1}),h=!0};return u=>{switch(u.type){case"run-start":t.updateMessage?.(s,{status:"streaming"});break;case"turn-start":p(!1),r=new bt({blocks:e.getStreamBlocks()}),a=new Set,o=null,c="",h=!1;break;case"thinking-delta":{if(c+=u.delta,o)t.updateSegment?.(o,{content:c});else{let _={id:`think-${W()}`,type:"thinking",content:c,isStreaming:!0};o=_.id,a.add(_.id),t.addSegment?.(_)}break}case"text-delta":{p(!0);let _=r.parse(u.delta);for(let m of _.segments)a.has(m.id)?"content"in m&&t.updateSegment?.(m.id,Ne(m)):(t.addSegment?.(m),a.add(m.id));let f=r.getState().activeSegment;f?a.has(f.id)?t.updateSegment?.(f.id,Ne(f)):(t.addSegment?.(f),a.add(f.id)):_.segments.length;break}case"text-flush":{let _=r.finalize();for(let f of _)a.has(f.id)?"content"in f&&t.updateSegment?.(f.id,Ne(f)):t.addSegment?.(f);break}case"tool-start":{p(!1);let _={id:`tool-${u.toolCallId}`,type:"tool_call",toolCall:{id:u.toolCallId,name:u.name,input:u.input},status:"pending"};l.set(_.id,_);let f=e.getToolRenderer(u.name);f&&Jn(u.name,f),t.addSegment?.(_);break}case"tool-awaiting-approval":t.updateSegment?.(`tool-${u.toolCallId}`,{status:"awaiting-approval"}),z(t,"aparte-tool-approval-request",{toolCallId:u.toolCallId,toolName:u.name,input:u.input},i);break;case"tool-approved":d(u.toolCallId,{status:"pending"});break;case"tool-rejected":d(u.toolCallId,{status:"rejected",result:u.reason,...u.by?{refusal:u.instruction?{by:u.by,instruction:u.instruction}:{by:u.by}}:{}});break;case"tool-resolved":d(u.toolCallId,{status:"resolved",result:u.result,...u.structuredResult!==void 0?{structuredResult:u.structuredResult}:{}});break;case"tool-aborted":d(u.toolCallId,u.cause?{status:"aborted",abortCause:u.cause}:{status:"aborted"});break;case"tool-failed":d(u.toolCallId,{status:"failed",result:u.error});break;case"turn-limit-exceeded":u.scope==="global"?t.addSegment?.({id:`max-turns-${W()}`,type:"error",content:(typeof Element<"u"&&t instanceof Element?y(t):e).t("maxTurnsReached").replace("{n}",()=>String(u.limit)),code:H.MAX_TURNS_EXCEEDED}):u.toolCallId&&d(u.toolCallId,{status:"aborted",abortCause:"turn-limit"});break;case"run-aborted":z(t,"aparte-message-aborted",{messageId:s},i);break;case"run-suspended":{let _=u.ticket;for(let f of u.pending){let m=`tool-${f.toolCallId}`,I={reason:f.reason,...typeof _=="string"?{ticket:_}:{}};t.updateSegment?.(m,{deferred:I})}if(t.updateMessage?.(s,{status:"completed"}),u.usage)try{t.setUsage?.(s,u.usage)}catch{}z(t,"aparte-message-paused",{messageId:s},i);break}case"run-done":if(t.updateMessage?.(s,{status:"completed",...u.finishReason?{finishReason:u.finishReason}:{}}),u.usage)try{t.setUsage?.(s,u.usage)}catch{}break}}}function Tn(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 bo=new TextEncoder;var vo=10080*60*1e3;var ds=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"]),Or=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"]),Pr=new Set(["class","style","title","dir","lang","role","align","aria-label","aria-hidden","aria-describedby","aria-level"]),Dr={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"])},Br=new Set(["href","src"]),Hr=/^(?:https?:|mailto:|tel:|ftp:|sms:)/i,Nr=/^(?:[#/.?]|[a-z0-9._~%+-]+(?:[/?#]|$))/i,qr=/^data:image\/(?:png|jpe?g|gif|webp|avif|bmp|x-icon|svg\+xml)[;,]/i,In=/[\u0000-\u0020]+/g,js=/^(?:https?:)?[/\\]{2}|^https?:[/\\]/i,$r=/^aparte-/i;function Fr(n,t){let e=t==="source"?"img":t;for(let s of n.matchAll(/[a-z][a-z0-9+.-]*:[^\s,]*/gi))if(!ie(s[0],e))return!1;return!0}function ie(n,t){let e=n.replace(In,"");return!e||Hr.test(e)||t==="img"&&qr.test(e)?!0:/^[a-z][a-z0-9+.-]*:/i.test(e)?!1:Nr.test(e)}var Ur=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 jr(n){return n.includes("\\")?!1:n.startsWith("--")&&!n.startsWith("--aparte-")}function Wr(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()&&(!Ur.has(r)&&!jr(r)||a.includes("\\")||/url\s*\(|expression\s*\(|javascript:|vbscript:|[<>]/i.test(a)||t.push(s))}return t.length?t.join("; "):null}function Gr(n,t,e){let s=Dr[e];for(let i of Array.from(n.attributes)){let r=i.name.toLowerCase(),a=i.value;if(!(r.startsWith("on")||r.startsWith("formaction"))&&!(!r.startsWith("data-")&&!Pr.has(r)&&!(s&&s.has(r)))&&!(Br.has(r)&&!ie(a,e))&&!(e==="input"&&r==="type"&&a.toLowerCase()!=="checkbox")&&!(r==="srcset"&&!Fr(a,e))){if(r==="style"){let o=Wr(a);if(o===null)continue;t.setAttribute("style",o);continue}if(r==="class"){let o=a.split(/\s+/).filter(l=>l&&!$r.test(l));if(!o.length)continue;t.setAttribute("class",o.join(" "));continue}t.setAttribute(r,a)}}if(e==="a"){let i=(t.getAttribute("href")??"").replace(In,""),r=(n.getAttribute("target")??"").trim().toLowerCase();r==="_self"&&!js.test(i)?t.setAttribute("target","_self"):(r||js.test(i))&&(t.setAttribute("target","_blank"),t.setAttribute("rel","noopener noreferrer"))}}function Ge(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(ds.has(r))continue;if(!Or.has(r)){Ge(i,t,e);continue}let a=e.createElement(r);Gr(i,a,r),Ge(i,a,e),t.appendChild(a)}}var Vr=new Set(["html","head","body"]),zr=Array.from(ds).join("|"),Kr=Array.from(ds).filter(n=>!Vr.has(n)).join("|"),Yr=new RegExp(`<\\s*(${Kr})\\b[\\s\\S]*?<\\s*\\/\\s*\\1\\s*>`,"gi"),Qr=new RegExp(`<\\s*\\/?\\s*(?:${zr})\\b[^>]*>`,"gi"),Ws=/["'/\s]on[a-z]+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi,Xr=/(?:href|src|xlink:href)\s*=\s*(?:"\s*(?:javascript|vbscript|data):[^"]*"|'\s*(?:javascript|vbscript|data):[^']*'|(?:javascript|vbscript|data):[^\s>]*)/gi;function Gs(n){let t=n.replace(Yr,"").replace(Qr,"");for(let e=t.replace(Ws," ");e!==t;e=t.replace(Ws," "))t=e;return t.replace(Xr," ")}var Ve=n=>{if(!n)return n;if(typeof DOMParser>"u")return Gs(n);let t;try{t=new DOMParser().parseFromString(n,"text/html")}catch{return Gs(n)}let e=t.createElement("div");return Ge(t.body,e,t),e.innerHTML},st=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 T(n){let t="";for(let e=0;e<n.length;e++){let s=n[e];s==="&"?t+="&amp;":s==="<"?t+="&lt;":s===">"?t+="&gt;":s==='"'?t+="&quot;":s==="'"?t+="&#039;":t+=s}return t}var E=T;function Jr(n){return n?n.tagName?.toLowerCase()==="aparte-chat"||n.hasAttribute?.("data-aparte-chat")===!0:!1}function Q(n){let t=n??null;for(;t;){if(Jr(t))return t;t=t.parentElement}return null}var Qt=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}},et={copy:!1,retry:!1,edit:!1,feedback:!1,info:!1},Ct={attachmentPreview:!1,filePreview:!1},Vs=()=>{},xn=new WeakMap;function nt(n){return xn.get(n)??0}function wt(n){xn.set(n,nt(n)+1)}var ze=new Set,Nt=new Set;function Ln(n){return ze.add(n),()=>{ze.delete(n)}}function jt(n){Nt.size===0&&queueMicrotask(()=>{let t=[...Nt];Nt.clear();for(let e of t)for(let s of[...ze])try{s(e)}catch(i){console.error("[aparte] a renderer-change listener threw",i)}}),Nt.add(n)}var Zr=n=>n instanceof RegExp?`re:${String(n)}`:`name:${n}`,qe=["hidden","open","details","quiet"];function $e(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 zs=new WeakSet;function ta(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 Mt=class{_markdownProvider;_streamingMarkdownProvider;_highlightProvider;_sanitizer=Ve;_systemPromptTemplate;_systemPromptVarsProvider;_statusRenderer;_errorRenderer;_attachmentRenderer;_siblingNavRenderer;_bubbleShellRenderer;_iconProvider;_avatarProvider;_keyProvider;_extraKeyProviders=new Set;_locale=gt;_actions=[];_listeners=new Set;_aiProviders=new Map;_fetchedModels=new Map;_modelConfig={};_requireModelSelection=!1;_elicitationAllowOther=!0;_elicitationLayout="stepped";_elicitationAnswerOnClick=!0;_elicitationFieldRenderer;_transport=new Kt;_modelPreferenceProvider;_approvalPolicy=null;_compactor=null;_conversationManager;_elicitationPresenters=[];_warnedNoPresenter=!1;_elicitationQueue=new Map;_tools=new Map;_toolRenderers=new Qt;_toolRendererOverrides=new Map;_overrideGeneration=0;_toolDisplays=new Qt;_streamBlocks=new Map;_segmentDefaults=new Map;_hostHandlers={...Ct};_bubbleActionsConfig={...et};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()}setHostHandlers(t){this._hostHandlers={...this._hostHandlers,...t},this._notify()}getHostHandlers(){return{attachmentPreview:this._hostHandlers.attachmentPreview??Ct.attachmentPreview,filePreview:this._hostHandlers.filePreview??Ct.filePreview}}getBubbleActions(){return{copy:this._bubbleActionsConfig.copy??et.copy,retry:this._bubbleActionsConfig.retry??et.retry,edit:this._bubbleActionsConfig.edit??et.edit,feedback:this._bubbleActionsConfig.feedback??et.feedback,info:this._bubbleActionsConfig.info??et.info,user:this._bubbleActionsConfig.user,assistant:this._bubbleActionsConfig.assistant}}setMarkdownProvider(t){this._markdownProvider=t,wt(this),this._notify()}setStreamingMarkdownProvider(t){this._streamingMarkdownProvider=t,wt(this),this._notify()}createStreamingMarkdownRenderer(t){return this._streamingMarkdownProvider?this._streamingMarkdownProvider(t):null}setHighlightProvider(t){this._highlightProvider=t,wt(this),this._notify()}hasHighlightProvider(){return!!this._highlightProvider}setHtmlSanitizer(t){t===null&&console.warn("[aparte] HTML sanitization is now DISABLED (setHtmlSanitizer(null)). Model-authored HTML will be inserted verbatim. Pass a sanitizer (e.g. DOMPurify.sanitize) unless you sanitize upstream yourself."),this._sanitizer=t}sanitizeHtml(t){return this._sanitizer?this._sanitizer(t):t}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&&zs.has(e))Object.assign(e,t);else{let s=Object.assign(Object.create(e??null),t);zs.add(s),this._iconProvider=s}this._notify()}getIconProvider(){let t=this._iconProvider,e={};for(let s of Object.keys(At))e[s]=$e(t,s)??(()=>At[s]);for(let s of ta(t)){let i=$e(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=gt,this._notify()}getLocale(){return this._locale}extendLocale(t){this._locale={...this._locale,...t},this._notify()}getIcon(t){let e=$e(this._iconProvider,t);return e?e():Object.prototype.hasOwnProperty.call(At,t)?At[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]||gt[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){if(this._highlightProvider)try{let s=this._highlightProvider(t,e),i=s instanceof Promise?await s:s;return this.sanitizeHtml(i)}catch(s){console.warn("[AparteConfig] Highlight provider failed, using fallback:",s)}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(`
5
+
6
+ `):null}getToolHandler(t){return this._tools.get(t)?.handler}registerToolRenderer(t,e){this._toolRenderers.get(t)!==e&&(this._toolRenderers.set(t,e),jt(this))}overrideToolRenderer(t,e){let s=Zr(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 d=r.indexOf(a);if(d<=0)return;let c=d===r.length-1;if(r.splice(d,1),r.length===1&&this._toolRendererOverrides.get(s)===r&&this._toolRendererOverrides.delete(s),!c||this._toolRenderers.get(t)!==e)return;let h=r[r.length-1].renderer;h?this.registerToolRenderer(t,h):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),jt(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),(qe.some(a=>s?.[a]!==i[a])||s===void 0&&this._anotherShapes(i))&&wt(this),this._notify()}unregisterToolDisplay(t){let e=this._toolDisplays.get(t);this._toolDisplays.delete(t),(qe.some(i=>e?.[i]!==void 0)||e!==void 0&&this._anotherShapes(e))&&wt(this),this._notify()}_anotherShapes(t){return this._toolDisplays.values().some(e=>e!==t&&qe.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=Q(t);if(s)for(let i=e.length-1;i>=0;i-=1){let r=e[i];if(r.owner&&Q(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(Vs,Vs).then(()=>{this._elicitationQueue.get(e)===r&&this._elicitationQueue.delete(e)});return this._elicitationQueue.set(e,r),i}_elicitationQueueKey(t){return Q(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 st("no-presenter"));if(t.signal?.aborted)return Promise.reject(new st("aborted"));let s=e(t),i=t.signal;return i?new Promise((r,a)=>{let o=()=>a(new st("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._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=gt,this._actions=[],this._sanitizer=Ve,this._aiProviders.clear(),this._fetchedModels.clear(),this._tools.clear(),this._toolRenderers.clear(),this._toolRendererOverrides.clear(),this._overrideGeneration++,jt(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={...et},this._hostHandlers={...Ct},this._notify()}_defaultMarkdownRenderer(t){return T(t).replace(/\n/g,"<br>")}_defaultHighlightRenderer(t){return`<pre><code>${T(t)}</code></pre>`}},Fe=Symbol.for("aparte.globalConfig.1");function ea(){return typeof window<"u"?(window[Fe]||(window[Fe]=new Mt),window[Fe]):new Mt}var Y=ea(),Ke="aparte-config-change";function it(n,t){let e=s=>{let i=s.detail;i?.config&&i.config!==y(n)||t()};return window.addEventListener(Ke,e),()=>window.removeEventListener(Ke,e)}var qt=new WeakMap,Ks="<i>a</i>";function Ys(){return A().renderMarkdown(Ks)!==T(Ks)}function re(n,t,e,s){if(s){if(n._aparteSmd===void 0){qt.delete(t);let r=A().createStreamingMarkdownRenderer(t);r?(t.textContent="",n._aparteSmd={renderer:r,written:0}):n._aparteSmd=null}let i=n._aparteSmd;if(i){let r=e.slice(i.written);r&&(i.renderer.write(r),i.written=e.length);return}}else if(n._aparteSmd){let i=n._aparteSmd,r=e.slice(i.written);if(r&&(i.renderer.write(r),i.written=e.length),i.renderer.end(),n._aparteSmd=void 0,!Ys()){t.innerHTML=A().sanitizeHtml(t.innerHTML),qt.set(t,e);return}}else if(qt.get(t)===e&&!Ys())return;qt.delete(t),t.innerHTML=A().renderMarkdown(e)}function Ye(n){if(!A().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)??"",r=e.textContent??"";e.setAttribute("data-aparte-highlighted",""),A().highlightCode(r,i).then(a=>{(s.isConnected||s.parentElement)&&(s.outerHTML=a)}).catch(()=>{})}}var sa={type:"text",render:n=>`<div class="aparte-segment aparte-segment-text" data-segment-id="${T(n.id)}"><div class="aparte-segment-content">${A().renderMarkdown(n.content)}</div></div>`,setup:(n,t)=>{let e=n.querySelector(".aparte-segment-content");e&&t.isStreaming!==!0&&Ye(e)},update:(n,t)=>{let e=n.querySelector(".aparte-segment-content");e&&(re(n,e,t.content,t.isStreaming!==!1),t.isStreaming===!1&&Ye(e))},getStyles:()=>""};function na(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 ia=24;function Qe(n){if(n.label&&n.label!=="Thinking")return n.label;let t=A();if(!dt(n))return t.t("thinking");let s=n.showDuration??t.getSegmentDefaults("thinking")?.showDuration===!0?Cn(n):void 0;return s===void 0?t.t("thought"):t.t("thoughtFor").replace("{duration}",()=>na(s,t.getLocale().tag||void 0))}var Rn=n=>n.isStreaming===!0;function Qs(n,t){let e=Qe(t),s=n.querySelector(".aparte-thinking-label");s&&s.textContent!==e&&(s.textContent=e),s?.classList.toggle("aparte-shimmer",Rn(t)),n.querySelector(".aparte-thinking-content")?.setAttribute("aria-label",e)}var ra={type:"thinking",render:n=>`<details class="aparte-segment aparte-segment-thinking aparte-accordion__item" data-segment-id="${T(n.id)}" ${n.collapsed===!1?"open":""}><summary class="aparte-accordion__header aparte-thinking-header"><span class="aparte-thinking-label${E(Rn(n)?" aparte-shimmer":"")}">${T(Qe(n))}</span><span class="aparte-accordion__icon">${A().getIcon("expand")}</span></summary><div class="aparte-accordion__panel aparte-thinking-content" role="region" tabindex="0" aria-label="${E(Qe(n))}">${A().renderMarkdown(n.content)}</div></details>`,relabel:(n,t)=>Qs(n,t),update:(n,t)=>{Qs(n,t);let e=n.querySelector(".aparte-thinking-content");if(!e)return;let s=e.scrollHeight-e.scrollTop-e.clientHeight<=ia,i=t.isStreaming!==!1;re(n,e,t.content,i),i||Ye(e),s&&(e.scrollTop=e.scrollHeight)},getStyles:()=>""};function hs(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 aa=1500;function Xe(n,t){n.setAttribute("aria-label",t),n.setAttribute("title",t)}function us(n){let t=E(A().t("copy")),e=A().getIcon("copy");return`<button type="button" class="aparte-btn aparte-btn--icon aparte-btn--sm ${E(n)}" data-action="copy" aria-label="${t}" title="${t}">${e}</button>`}function On(n,t){n.addEventListener("click",()=>{hs(t()).catch(()=>{}),n.innerHTML=A(n).getIcon("check"),Xe(n,A(n).t("copied")),n.dataset.copied="1",setTimeout(()=>{n.innerHTML=A(n).getIcon("copy"),Xe(n,A(n).t("copy")),delete n.dataset.copied},aa)})}function Pn(n){n.dataset.copied||(Xe(n,A().t("copy")),n.innerHTML=A().getIcon("copy"))}var oa=400,la=256,Xs=new Map;function ca(n,t,e){if(n.delete(t),n.size>=la){let s=n.keys().next().value;s!==void 0&&n.delete(s)}n.set(t,e)}function Js(n){let t=Number(n.dataset.aparteHlLen);return Number.isFinite(t)&&t>0?t:0}function da(n,t,e,s,i){let r=n.querySelector(t);if(!r)return;let a=r.querySelector("[data-aparte-tail]"),o=Js(r);if(a&&o<=e.length)a.textContent=e.slice(o);else{delete r.dataset.aparteHlLen;let c=r.querySelector("code");c?c.textContent=e:r.innerHTML=`<pre><code class="language-${T(s||"text")}">${T(e)}</code></pre>`}let l=e.lastIndexOf(`
7
+ `)+1;if(l<=o)return;let d=Date.now();d-(Xs.get(i)??0)<oa||(ca(Xs,i,d),A(n).highlightCode(e.slice(0,l),s).then(c=>{let h=n.querySelector(t);if(!h||l<=Js(h))return;h.innerHTML=c;let p=h.querySelector("code")??h,u=document.createElement("span");u.dataset.aparteTail="",u.textContent=e.slice(l),p.appendChild(u),h.dataset.aparteHlLen=String(l)}).catch(()=>{}))}var ha={type:"code",render:n=>{let t=us("aparte-code-copy");return`
8
+ <div class="aparte-segment aparte-segment-code" data-segment-id="${T(n.id)}">
9
+ <div class="aparte-code-header">
10
+ ${n.filename?`<span class="aparte-code-filename">${T(n.filename)}</span>`:'<span class="aparte-code-header-filler"></span>'}
11
+ <span class="aparte-code-language">${T(n.language||"")}</span>
12
+ ${t}
13
+ </div>
14
+ <div class="aparte-code-content-wrapper">
15
+ <pre><code class="language-${T(n.language||"text")}">${T(n.content)}</code></pre>
16
+ </div>
17
+ </div>
18
+ `},relabel:n=>{let t=n.querySelector(".aparte-code-copy");t&&Pn(t)},setup:(n,t)=>{let e=n.querySelector(".aparte-code-content-wrapper");e&&A().highlightCode(t.content,t.language||"").then(i=>{e.innerHTML=i}).catch(()=>{});let s=n.querySelector(".aparte-code-copy");s&&On(s,()=>n.querySelector(".aparte-code-content-wrapper")?.textContent??"")},update:(n,t)=>{if(t.isStreaming)da(n,".aparte-code-content-wrapper",t.content,t.language||"",t.id);else{let e=n.querySelector(".aparte-code-content-wrapper");e&&A().highlightCode(t.content,t.language||"").then(s=>{e.innerHTML=s}).catch(()=>{})}},getStyles:()=>""};function Je(n,t){switch(n){case H.NET_OFFLINE:case H.NET_ERROR:return t("errorUnreachable");case H.NET_TIMEOUT:return t("errorTimeout");case H.CONFIG_INVALID_KEY:return t("errorRefused");case H.USAGE_RATE_LIMIT:return t("errorRateLimited");case H.USAGE_CONTEXT_EXCEEDED:return t("errorTooLong");case H.PROVIDER_ERROR:case H.PROVIDER_UNAVAILABLE:return t("errorFailed");case H.USAGE_BAD_REQUEST:case H.PROVIDER_POLICY:case H.PROVIDER_MISCONFIGURED:case H.CONFIG_INVALID_MODEL:case H.UNKNOWN_ERROR:return t("errorNoAnswer");default:return}}var ua={type:"error",render:n=>{let t=A(),e=Je(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`
19
+ <div class="aparte-segment aparte-alert aparte-alert--danger aparte-segment-error" data-segment-id="${T(n.id)}"${n.code?` data-error-code="${E(n.code)}"`:""}>
20
+ <span class="aparte-alert__icon">${t.getIcon("error")||"\u26A0"}</span>
21
+ <div class="aparte-alert__body">
22
+ <div class="aparte-alert__title">${T(t.t("error"))}</div>
23
+ <div class="aparte-alert__message">${T(i)}</div>
24
+ ${n.details?`<pre class="aparte-segment-error__details">${T(n.details)}</pre>`:""}
25
+ </div>
26
+ </div>
27
+ `},relabel:(n,t)=>{let e=A();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=Je(t.code,o=>e.t(o)),a=n.querySelector(".aparte-alert__message");a&&r!==void 0&&(a.textContent=r)},getStyles:()=>""};function Dn(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 Bn(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 Hn(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 Nn(n){return Dn(n.toolCall?.input,A().getToolInputFormatter(n.toolCall?.name??""))}function Ze(n){let t=A(),e=n.status??"pending",s=i=>T(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 qn(n){let t=A();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 ts(n){let t=fa(n.result??"");return!t||n.status==="rejected"&&n.refusal?null:{key:"toolOutput",text:t}}function Ue(n){let t=A().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"?A().sanitizeHtml(e):e}:{kind:"none"}}catch{return{kind:"none"}}}var Zs=n=>n.querySelector(':scope > .aparte-tool-detail[data-details="app"]');function $n(n,t){let e=n.querySelector(".aparte-tool-detail");e&&(typeof t=="string"?e.innerHTML=t:e.replaceChildren(t),Wt.set(e,Fn(t)))}var Wt=new WeakMap,Fn=n=>typeof n=="string"?n:n.outerHTML;function pa(n,t){if(typeof t!="string"&&n.contains(t)){Wt.set(n,t.outerHTML);return}let e=Wt.get(n),s=Fn(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&&es(r,i)&&es(r,n)?Un(n,r,i):n.replaceChildren(...Array.from(i.childNodes)),Wt.set(n,s)}function es(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||!es(s,i))return!1}return!0}function Un(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);Un(i,r,a)}else r.nodeValue!==a.nodeValue&&(i.nodeValue=a.nodeValue)}}function tn(n,t){let e=n.querySelector(".aparte-tool-note");if(!e)return;let s=qn(t);e.textContent!==s&&(e.textContent=s),e.toggleAttribute("hidden",!s),s?e.setAttribute("title",s):e.removeAttribute("title")}function en(n,t,e,s){let i=n.querySelector(`[data-part="${t}"]`);if(!e){i?.remove();return}if(i){let _=i.querySelector("code");_&&_.textContent!==e&&(_.textContent=e);let f=i.querySelector(".aparte-tool-part-label"),m=A().t(s);f&&f.textContent!==m&&(f.textContent=m),i.querySelector(".aparte-tool-part-body")?.setAttribute("aria-label",m);return}let r=n.querySelector(".aparte-tool-detail");if(!r)return;let a=A(),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 d=document.createElement("span");d.className="aparte-tool-part-label",d.textContent=a.t(s);let c=document.createElement("template");c.innerHTML=us("aparte-tool-copy"),l.append(d,c.content);let h=document.createElement("div");h.className="aparte-tool-part-body",h.setAttribute("role","region"),h.tabIndex=0,h.setAttribute("aria-label",d.textContent);let p=document.createElement("pre"),u=document.createElement("code");u.textContent=e,p.appendChild(u),h.appendChild(p),o.append(l,h),t==="input"?r.prepend(o):r.appendChild(o),jn(o)}function jn(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");On(t,()=>e?.querySelector(".aparte-tool-part-body")?.textContent??"")}}var _a=2e5;function Wn(n){let t=n.trim();if(!(t.length>_a||!(t.startsWith("{")||t.startsWith("["))))try{let e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}}function fa(n){let t=Wn(n);return t===void 0?n:JSON.stringify(t,null,2)}function sn(n){let t=A();for(let e of n.querySelectorAll(".aparte-tool-part-body")){let s=e.querySelector("code")?.textContent??"";!s||Wn(s)===void 0||t.highlightCode(s,"json").then(i=>{(e.querySelector("code")?.textContent??"")===s&&(e.innerHTML=i)}).catch(()=>{})}}function Gn(n){return Hn(n,A())}function nn(n,t){let e=n.querySelector(".aparte-tool-target");if(!e)return;let s=Gn(t);e.textContent!==s&&(e.textContent=s),e.toggleAttribute("hidden",!s)}function Vn(n){return Bn(n,A())}function zn(n){let t=A(),e=t.getToolDisplay(n.toolCall?.name??"")?.icon;return(e?t.getIcon(e):void 0)||t.getIcon("tool")}var ps=n=>A().getToolDisplay(n.toolCall?.name??"")?.quiet??!0;function Kn(n){let t=n.status??"pending",e=ps(n);return{shimmer:e&&t==="pending",spinner:!e&&t==="pending",stateHidden:e&&(t==="pending"||t==="resolved")}}function rn(n,t){let e=Kn(t);n.toggleAttribute("data-quiet",ps(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 an(n,t){let e=n.querySelector(".aparte-tool-name");if(!e)return;let{text:s,isLabel:i}=Vn(t);e.textContent!==s&&(e.textContent=s),e.classList.toggle("aparte-tool-name--label",i)}function ga(n){let t=Ze(n),e=zn(n),s=Gn(n),i=qn(n),r=Vn(n),a=Kn(n);return`
28
+ <span class="aparte-tool-label">
29
+ <span class="aparte-tool-icon">${e}</span>
30
+ <span class="aparte-tool-name${r.isLabel?" aparte-tool-name--label":""}${a.shimmer?" aparte-shimmer":""}">${T(r.text)}</span>
31
+ <span class="aparte-tool-target"${s?"":" hidden"}>${T(s)}</span>
32
+ </span>
33
+ <span class="aparte-spinner aparte-tool-spinner" aria-hidden="true"${a.spinner?"":" hidden"}></span>
34
+ <span class="aparte-tool-state${a.stateHidden?" aparte-sr-only":""}">${t}</span>
35
+ <span class="aparte-tool-note"${i?` title="${E(i)}"`:" hidden"}>${T(i)}</span>`}function on(n){return`<div class="aparte-segment aparte-segment-tool-call" data-segment-id="${T(n.id)}" data-status="${E(n.status??"pending")}" data-tool-call-id="${E(n.toolCall?.id??"")}" data-tool-name="${E(n.toolCall?.name??"tool")}" hidden></div>`}var _t=n=>n.hidden&&n.classList.contains("aparte-segment-tool-call")&&n.childElementCount===0,Et=new WeakMap,Gt=new WeakMap;function _s(n){return Gt.get(n)??null}function ln(n,t){let e=Et.get(n);return e||(n.classList.contains("aparte-segment-tool-call")?null:t)}function cn(n,t){let e=n.toolCall?.name??"tool",s=n.status??"pending",i=n.toolCall?.id??"",r=ga(n),a=ps(n)?" data-quiet":"",o=A().getIcon("expand"),l=t.kind==="parts"?Nn(n):"",d=t.kind==="parts"?ts(n):null;if(t.kind==="none"||t.kind==="parts"&&!l&&!d)return`
36
+ <div class="aparte-segment aparte-segment-tool-call" data-segment-id="${T(n.id)}" data-status="${E(s)}" data-tool-call-id="${E(i)}" data-tool-name="${E(e)}"${a}><div class="aparte-tool-line">${r}</div>
37
+ </div>
38
+ `;let c=A(),h=us("aparte-tool-copy"),p=n.collapsed!==void 0?!n.collapsed:c.getToolDisplay(e)?.open===!0;if(t.kind==="body"){let u=document.createElement("template");u.innerHTML=`
39
+ <details class="aparte-segment aparte-segment-tool-call" data-segment-id="${T(n.id)}" data-status="${E(s)}" data-tool-call-id="${E(i)}" data-tool-name="${E(e)}"${a}${p?" open":""}>
40
+ <summary class="aparte-tool-summary"><span class="aparte-tool-toggle">${o}</span>${r}</summary>
41
+ <div class="aparte-tool-detail" data-details="app"></div>
42
+ </details>`.trim();let _=u.content.firstElementChild;return $n(_,t.body),_}return`
43
+ <details class="aparte-segment aparte-segment-tool-call" data-segment-id="${T(n.id)}" data-status="${E(s)}" data-tool-call-id="${E(i)}" data-tool-name="${E(e)}"${a}${p?" open":""}>
44
+ <summary class="aparte-tool-summary"><span class="aparte-tool-toggle">${o}</span>${r}</summary>
45
+ <div class="aparte-tool-detail">
46
+ ${l?`
47
+ <div class="aparte-tool-part" data-part="input">
48
+ <div class="aparte-tool-part-head"><span class="aparte-tool-part-label">${T(c.t("toolInput"))}</span>${h}</div>
49
+ <div class="aparte-tool-part-body" role="region" tabindex="0" aria-label="${E(c.t("toolInput"))}"><pre><code>${T(l)}</code></pre></div>
50
+ </div>`:""}
51
+ ${d?`
52
+ <div class="aparte-tool-part" data-part="output">
53
+ <div class="aparte-tool-part-head"><span class="aparte-tool-part-label">${T(c.t(d.key))}</span>${h}</div>
54
+ <div class="aparte-tool-part-body" role="region" tabindex="0" aria-label="${E(c.t(d.key))}"><pre><code>${T(d.text)}</code></pre></div>
55
+ </div>`:""}
56
+ </div>
57
+ </details>
58
+ `}var mt={type:"tool_call",render:n=>{let t=n.toolCall?.name??"tool";if(A().isToolHidden(t))return on(n);let e=A().getToolRenderer(t);if(e){Jn(t,e);let s=e.render(n);return s instanceof HTMLElement&&(Et.set(s,e),Gt.set(s,e)),s||on(n)}return cn(n,Ue(n))},relabel:(n,t)=>{if(_t(n))return;let e=A(),s=ln(n,e.getToolRenderer(t.toolCall?.name)??null);if(s){s.relabel?.(n,t);return}let i=n.querySelector(".aparte-tool-icon");i&&(i.innerHTML=zn(t)),an(n,t),nn(n,t),tn(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=ts(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 c of n.querySelectorAll(".aparte-tool-copy"))Pn(c);let l=Zs(n);if(l){let c=Ue(t);c.kind==="body"&&pa(l,c.body)}let d=n.querySelector(".aparte-tool-state");d&&(d.innerHTML=Ze(t)),rn(n,t)},update:(n,t)=>{let e=t.status??"pending",s=A().isToolHidden(t.toolCall?.name??"tool");if(s&&_t(n)){n.setAttribute("data-status",e);return}let i=s?null:A().getToolRenderer(t.toolCall?.name)??null,r=_t(n)?null:ln(n,i);if(r&&r===i&&r.update&&!_t(n)){r.update(n,t);return}let a=u=>{let _=document.createElement("template");_.innerHTML=typeof u=="string"?u.trim():"";let f=typeof u=="string"?_.content.firstElementChild:u;f&&(f.hasAttribute("data-segment-id")||f.setAttribute("data-segment-id",t.id),mt.cleanup?.(n,t),n.replaceWith(f),mt.setup?.(f,t))};if(i||r||s||_t(n)){a(mt.render(t));return}let o=Ue(t),l=o.kind==="parts"?Nn(t):"",d=o.kind==="parts"?ts(t):null,c=o.kind==="body"||!!l||!!d,h=!!Zs(n);if(c!==(n.tagName==="DETAILS")||c&&o.kind==="body"!==h){a(cn(t,o));return}n.setAttribute("data-status",e);let p=n.querySelector(".aparte-tool-state");if(p&&(p.innerHTML=Ze(t)),rn(n,t),an(n,t),nn(n,t),tn(n,t),o.kind==="body"){$n(n,o.body);return}en(n,"input",l,"toolInput"),en(n,"output",d?.text??"",d?.key??"toolOutput"),sn(n)},setup:(n,t)=>{let s=A().isToolHidden(t.toolCall?.name??"tool")?void 0:A().getToolRenderer(t.toolCall?.name);s&&Gt.set(n,s),!_t(n)&&(jn(n),sn(n),s&&Et.set(n,s),s?.setup?.(n,t))},cleanup:(n,t)=>{Gt.delete(n);let e=Et.get(n);if(e){Et.delete(n);try{e.cleanup?.(n,t)}catch(s){console.error("[aparte] a tool renderer's cleanup threw",s)}}},getStyles:()=>""},dn=new WeakMap;function ht(n){let t=dn.get(n);return t||(t={renderers:new Map,defaultsInstalled:!1,defaultsDeclined:!1},dn.set(n,t)),t}function ma(n){let t=ht(n);if(n===Y||t.defaultsDeclined)return t.renderers;let e=new Map(ht(Y).renderers);for(let[s,i]of t.renderers)e.set(s,i);return e}var ot=null;function Yn(n,t=A()){let e=ht(t);e.renderers.get(n.type)!==n&&(e.renderers.set(n.type,n),gs(t),jt(t))}function Qn(n=A()){ht(n).defaultsDeclined=!0}function Xn(n=A()){let t=ht(n);if(!(t.defaultsInstalled||t.defaultsDeclined)){t.defaultsInstalled=!0;for(let e of ti)t.renderers.has(e.type)||t.renderers.set(e.type,e);gs(n)}}function fs(n,t=A()){return ma(t).get(n)}var $t=new Set;function gs(n=A()){if(typeof document>"u")return;(!ot||!ot.isConnected)&&(ot=document.createElement("style"),ot.id="aparte-renderer-styles",document.head.appendChild(ot),ot.textContent=Array.from($t).join(`
59
+ `));let t=!1;for(let e of ht(n).renderers.values()){let s=e.getStyles?.();!s||$t.has(s)||($t.add(s),t=!0)}t&&(ot.textContent=Array.from($t).join(`
60
+ `))}var hn=new WeakMap;function Jn(n,t){if(typeof document>"u")return;let e=t.getStyles?.();if(!e)return;let s=hn.get(t);if(s||(s=`aparte-tool-renderer-${n}`,hn.set(t,s)),document.getElementById(s))return;let i=document.createElement("style");i.id=s,i.textContent=e,document.head.appendChild(i)}function Zn(n=A()){let t=ht(n);t.defaultsInstalled=!0;for(let e of ti)t.renderers.has(e.type)||Yn(e,n);gs(n)}var ti=[sa,ra,ha,ua,mt],ba=new WeakSet;function ms(n){return!!n&&ba.has(n)}function bs(n,t,e){if(t.segments&&t.segments.length>0)if((n.getSegments?.()??[]).length===t.segments.length){let i=cs(t.status);for(let r of t.segments)if("content"in r){let a={content:r.content};i&&(a.isStreaming=!1),n.updateSegment?.(r.id,a)}}else n.setSegments?.(t.segments);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 vs=Symbol.for("aparte.derivedSegments");function ei(n){return n.map(t=>({id:W(),name:t.name,type:t.type||"application/octet-stream",url:URL.createObjectURL(t),size:t.size,blob:t}))}function si(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 ss=new Map;function ys(n,t){t?ss.set(n,t):ss.delete(n)}function ni(n,t){ys(n,t);try{window.dispatchEvent(new CustomEvent("aparte-conversation-status",{detail:{id:n,status:t}}))}catch{}}function ae(n){return ss.get(n)??null}function G(n){return n.replace(/["\\]/g,"\\$&").replace(/[\n\r\f]/g,t=>`\\${t.charCodeAt(0).toString(16)} `)}function ii(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 ri(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 Xt=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 Jt(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 va="The earlier part of this conversation was compacted. This is a summary of what came before; continue from it.",ws=n=>`${va}
61
+
62
+ ${n}`;function ft(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}
63
+
64
+ ${s.content}`}:e[e.length-1]={...i,content:[...t(i.content),{type:"text",text:`
65
+
66
+ `},...t(s.content)]}}return e}var un="The tool call was stopped before it ran.",ya="The tool returned no output.";function wa(n){let t=n.result?.trim();return n.status==="resolved"?t||ya:n.status==="failed"?t||"The tool failed.":n.status==="rejected"&&t||un}var kt=n=>n.type==="tool_call"&&!!n.deferred&&(n.status==="awaiting-approval"||n.status==="pending");function ai(n,t,e={}){let s=n.segments??[];if(n.role!=="assistant"||!s.some(d=>d.type==="tool_call")){let d=t(s)||(typeof n.content=="string"?n.content:"");return d?[{role:n.role,content:d}]:[]}let i=[],r=[],a=[],o=()=>{let d=t(r);if(a.length===0)d&&i.push({role:"assistant",content:d});else{i.push({role:"assistant",content:d,toolCalls:a.map(c=>({id:c.toolCall.id,name:c.toolCall.name,input:c.toolCall.input}))});for(let c of a)e.openDeferred&&kt(c)||i.push({role:"tool",content:wa(c),toolCallId:c.toolCall.id,toolName:c.toolCall.name})}r=[],a=[]},l=!1;for(let d of s)d.type==="tool_call"?(a.push(d),e.openDeferred&&kt(d)&&(l=!0)):(a.length>0&&!l&&o(),r.push(d));return o(),i}var oi=n=>n.status==="streaming"||n.status==="pending";function oe(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}
67
+ ${i??""}
68
+ ${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(`
69
+ `).trim()}function Sa(n){let t=oe(n.segments);return t||(typeof n.content=="string"&&n.content?n.content:"")}function Aa(n){let t=Sa(n);return n.compaction?ws(t):t}function Vt(n){return n.filter(t=>t.role!=="user"&&t.role!=="assistant"?!1:t.status!=="error"&&!oi(t)).flatMap(t=>{if(t.role==="assistant"&&t.segments?.some(s=>s.type==="tool_call"))return ai(t,oe);let e=Aa(t);return e?[{role:t.role,content:e}]:[]})}function ct(n){return n?Math.ceil(n.length/3.8):0}var Ss=n=>{if(!n)return 0;try{return ct(JSON.stringify(n))}catch{return 0}};function li(n){let t=0;for(let e of n)t+=ct(yn(e.content)),e.toolCalls?.length&&(t+=Ss(e.toolCalls));return t}function Ca(n){return n.some(t=>typeof t.content!="string"&&t.content.some(e=>e.type!=="text"))}function Ea(n){let t=(n.tools??[]).map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema}));return li(n.messages)+(t.length?Ss(t):0)}function ci(n){return li(Vt(n))}var le=n=>n.totalTokens??n.inputTokens+n.outputTokens;function di(n){let t=n.getCurrentModel()?.capabilities;return(t?!t.includes("function_calling"):!1)?[]:n.getTools()}function ka(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 hi=(n,t)=>n.segments?.some(e=>e.type===t)===!0;function Ma(n){let t=n.usage?.inputTokens,e=n.contextEstimate;return hi(n,"tool_call")?1:t&&e&&t>0&&e>0?Math.min(3,Math.max(.5,t/e)):1}function Ta(n,t){let e=n.usage;if(!hi(n,"thinking")||!(e.inputTokens>0))return le(e);let s=n.segments??[],i=s.map(a=>a.type).lastIndexOf("tool_call"),r=Math.round(t*ct(oe(s.slice(i+1))));return e.inputTokens+(e.outputTokens>0?Math.min(r,e.outputTokens):r)}function ui(n){let{messages:t,config:e}=n,s=Jt(t),i=ct(e.resolveSystemPrompt())+ct(e.resolveToolSystemPrompts()),r=di(e).map(m=>({name:m.name,description:m.description,inputSchema:m.inputSchema})),a=r.length?Ss(r):0,o=s.summary===void 0?0:ct(ws(s.summary)),l={system:i,tools:a,summary:o,messages:ci(s.messages)},d=i+a+o+l.messages,c=-1;for(let m=t.length-1;m>=0;m--)if(t[m].role==="assistant"&&t[m].usage){c=m;break}let h=c>=0?t[c]:void 0,p=ka(e,n.windowOverride),u=(m,I)=>({...p!==void 0?{window:p}:{},used:m,estimated:I,parts:l,other:Math.max(0,m-d)}),_=h!==void 0&&!n.viewChanged&&c===t.length-1&&!t.some(m=>m.contextSummary!==void 0&&m.contextSummary.createdAt>h.timestamp),f=h?Ma(h):1;return h&&_?u(Ta(h,f),!1):u(Math.round(f*d),!0)}function rt(n){return n.composedPath?.()[0]??n.target}function ut(n){return n.getRootNode()}function at(n){return n.getRootNode().activeElement??document.activeElement}var Ia=0,zt=null;function Tt(n){zt?.push(n)}function P(n,t,e){let s=document.createElement(n);return t&&(s.className=t),e!=null&&(s.textContent=e),s}function As(n,t,e){let s=P("span","aparte-elic-option-body"),i=P("span","aparte-elic-option-title",n);if(e){let r=P("span","aparte-tag aparte-tag--sm aparte-elic-option-badge",A().t("elicitationRecommended")||"Recommended");i.append(" ",r)}return s.appendChild(i),t&&s.appendChild(P("span","aparte-elic-option-desc",t)),s}function ns(n,t,e){let s=P("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(As(n,t,e)),s}function Cs(n,t,e){let s;if(t.title&&t.title.trim()!==e?.trim()){let i=P("p","aparte-elic-title",t.title);s=`elic-title-${W()}`,i.id=s,n.appendChild(i)}return t.description&&n.appendChild(P("p","aparte-elic-desc",t.description)),s}function pi(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 xa(n,t,e,s){let i=P("div","aparte-elic-field aparte-elic-enum"),r=Cs(i,n,e),a=P("div","aparte-elic-options"),o=`elic-${W()}`,l=n.multiple?"checkbox":"radio",d=l==="checkbox"?"aparte-checkbox":"aparte-radio",c=n.allowOther??A().getElicitationOptions().allowOther,h=new Set(Array.isArray(n.default)?n.default:n.default!=null?[n.default]:[]),p=s!=null&&!n.multiple&&h.size===0;pi(a,{multiple:n.multiple,commands:p,titleId:r,fallbackLabel:e});let u=(k,b,w,C)=>{if(p){let L=ns(b,w,C);return L.addEventListener("click",()=>s?.(k)),L}let g=P("label","aparte-field-choice aparte-elic-option"+(C?" aparte-elic-option--recommended":"")),v=P("input",d+" aparte-elic-control");return v.type=l,v.name=o,v.value=k,h.has(k)&&(v.checked=!0),g.append(v,As(b,w,C)),g};for(let k of n.options)a.appendChild(u(k.value,k.label??k.value,k.description,k.recommended));let _=null,f=!1;if(c){let k=A();_=P("input","aparte-field aparte-elic-other-input"),_.type="text",_.placeholder=k.t("elicitationOtherPlaceholder"),_.style.display="none",_.setAttribute("aria-label",k.t("elicitationOtherLabel"));let b=_;if(p){let w=ns(k.t("elicitationOther"));w.classList.add("aparte-elic-option--other"),w.setAttribute("aria-expanded","false"),w.addEventListener("click",()=>{f=!0,w.setAttribute("aria-expanded","true"),b.style.display="",b.focus(),t()});let C=w.querySelector(".aparte-elic-option-title");Tt(()=>{let g=A();C.textContent=g.t("elicitationOther"),b.placeholder=g.t("elicitationOtherPlaceholder"),b.setAttribute("aria-label",g.t("elicitationOtherLabel"))}),a.append(w,b)}else{let w=P("label","aparte-field-choice aparte-elic-option aparte-elic-option--other"),C=P("input",d+" aparte-elic-control");C.type=l,C.name=o,C.value="__other__";let g=P("span","aparte-elic-option-body"),v=P("span","aparte-elic-option-title",k.t("elicitationOther"));g.appendChild(v),Tt(()=>{let L=A();v.textContent=L.t("elicitationOther"),b.placeholder=L.t("elicitationOtherPlaceholder"),b.setAttribute("aria-label",L.t("elicitationOtherLabel"))}),g.appendChild(_),w.append(C,g),a.appendChild(w)}}i.appendChild(a);let m=()=>Array.from(a.querySelectorAll(".aparte-elic-control")),I=()=>a.querySelector('input[value="__other__"]'),x=!1;a.addEventListener("keydown",k=>{x=k.key.startsWith("Arrow")}),a.addEventListener("click",()=>{x=!1}),a.addEventListener("change",()=>{let k=I();k&&_&&(_.style.display=k.checked?"":"none",k.checked&&!x&&_.focus()),x=!1,t()}),_?.addEventListener("input",t);let R=()=>_?.value.trim()??"";if(p)return{el:i,getValue:()=>R(),isComplete:()=>f&&R()!=="",focus:()=>a.querySelector(".aparte-elic-option--command")?.focus(),offersSubmit:()=>f};let M=()=>{let k=I()?.checked&&R()?R():"";if(n.multiple){let w=m().filter(C=>C.checked&&C.value!=="__other__").map(C=>C.value);return k&&w.push(k),w}let b=m().find(w=>w.checked);return b?b.value==="__other__"?k:b.value:""};return{el:i,getValue:M,isComplete:()=>{let k=M();return n.multiple?k.length>0:k!==""},focus:()=>m()[0]?.focus()}}function La(n,t,e,s){let i=P("div","aparte-elic-field aparte-elic-boolean"),r=Cs(i,n,e),a=P("div","aparte-elic-options"),o=`elic-${W()}`,l=s!=null&&n.default==null;if(pi(a,{commands:l,titleId:r,fallbackLabel:e}),l){let p=A(),u=(_,f,m)=>{let I=ns(f);if(I.addEventListener("click",()=>s?.(_)),m){let x=I.querySelector(".aparte-elic-option-title");Tt(()=>{x.textContent=A().t(m)})}a.appendChild(I)};return u(!0,n.trueLabel??p.t("elicitationYes"),n.trueLabel?void 0:"elicitationYes"),u(!1,n.falseLabel??p.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 d=(p,u,_)=>{let f=P("label","aparte-field-choice aparte-elic-option"),m=P("input","aparte-radio aparte-elic-control");m.type="radio",m.name=o,m.value=p,n.default!=null&&String(n.default)===p&&(m.checked=!0);let I=P("span","aparte-elic-option-body"),x=P("span","aparte-elic-option-title",u);_&&Tt(()=>{x.textContent=A().t(_)}),I.appendChild(x),f.append(m,I),a.appendChild(f)},c=A();d("true",n.trueLabel??c.t("elicitationYes"),n.trueLabel?void 0:"elicitationYes"),d("false",n.falseLabel??c.t("elicitationNo"),n.falseLabel?void 0:"elicitationNo"),i.appendChild(a),a.addEventListener("change",t);let h=()=>a.querySelector("input:checked");return{el:i,getValue:()=>h()?.value==="true",isComplete:()=>h()!=null,focus:()=>a.querySelector("input")?.focus()}}function Ra(n,t,e){let s=P("div","aparte-elic-field aparte-elic-string");Cs(s,n,e);let i=n.multiline?P("textarea","aparte-field aparte-field--textarea aparte-elic-text"):P("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??A().t("elicitationAnswerLabel")),r==null){let l=i;Tt(()=>{l.setAttribute("aria-label",A().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 pn(n,t,e,s,i){let r=A().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 xa(n,t,e,i);case"boolean":return La(n,t,e,i);case"string":return Ra(n,t,e)}}function _i(n,t,e){let s=[],i=zt;zt=s;try{return{...Oa(n,t,e),relabel:()=>{for(let a of s)a()}}}finally{zt=i}}function Oa(n,t,e){let s=P("div","aparte-elic-panel"),i=typeof n=="function"?n():n;i&&s.appendChild(P("p","aparte-elic-message",i));let r=null,a=!1,o=u=>{a||(a=!0,r?.(u))},l=u=>{r=u},d=P("div","aparte-elic-body");s.appendChild(d);let c=P("div","aparte-elic-dismiss");if(s.appendChild(c),t.type==="object"){let u=function(v){b=v,R.forEach((L,S)=>{L.field.el.hidden=S!==v}),I()},_=Object.entries(t.properties),f=new Set(t.required??_.map(([v])=>v)),m=A(),I=()=>{},x=()=>{I(),e()},R=_.map(([v,L])=>{let S=pn(L,x,void 0,v);return!L.title&&!S.el.querySelector(".aparte-elic-title")&&S.el.insertBefore(P("p","aparte-elic-title",v),S.el.firstChild),d.appendChild(S.el),{key:v,field:S,required:f.has(v),header:L.header}}),M=()=>R.every(v=>!v.required||v.field.isComplete()),k={el:s,dismiss:c,getContent:()=>Object.fromEntries(R.map(v=>[v.key,v.field.getValue()])),isComplete:M,focus:()=>R[0]?.field.focus(),mode:()=>"submit",canProceed:M,proceed:()=>{},onSettle:l};if(R.length<2||m.getElicitationOptions().layout!=="stepped")return k;s.classList.add("aparte-elic-panel--stepped");let b=0,w=`aparte-elic-${++Ia}`,C=P("div","aparte-tabs aparte-tabs--underline aparte-elic-steps");C.setAttribute("role","tablist");let g=R.map((v,L)=>{let S=P("button","aparte-tabs__tab aparte-elic-step");return S.type="button",S.setAttribute("role","tab"),S.textContent=v.header?.trim()||String(L+1),S.addEventListener("click",()=>{u(L),v.field.focus()}),S.id=`${w}-tab-${L}`,v.field.el.id=`${w}-panel-${L}`,v.field.el.setAttribute("role","tabpanel"),v.field.el.setAttribute("aria-labelledby",S.id),S.setAttribute("aria-controls",v.field.el.id),S.addEventListener("keydown",D=>{let q=D.key==="ArrowRight"?1:D.key==="ArrowLeft"?-1:0,B=-1;q?B=(L+q+R.length)%R.length:D.key==="Home"?B=0:D.key==="End"&&(B=R.length-1),!(B<0)&&(D.preventDefault(),u(B),g[B]?.focus())}),C.appendChild(S),S});return s.insertBefore(C,d),I=()=>{g.forEach((v,L)=>{v.setAttribute("aria-selected",String(L===b)),v.tabIndex=L===b?0:-1;let S=R[L].field.isComplete();v.toggleAttribute("data-answered",S);let D=v.querySelector(".aparte-elic-step__mark");if(S&&!D){let q=P("span","aparte-elic-step__mark");q.setAttribute("aria-hidden","true"),q.innerHTML=m.getIcon("check"),v.prepend(q)}else!S&&D&&D.remove()})},u(0),{...k,focus:()=>R[b]?.field.focus()}}let h=A().getElicitationOptions().answerOnClick,p=pn(t,e,i,void 0,h?o:void 0);return d.appendChild(p.el),{el:s,dismiss:c,getContent:()=>p.getValue(),isComplete:()=>p.isComplete(),focus:()=>p.focus(),mode:()=>p.offersSubmit?.()??!0?"submit":"none",canProceed:()=>p.isComplete(),proceed:()=>{},onSettle:l}}var Pa=0;function J(n,t,e){let s=document.createElement(n);return t&&(s.className=t),e!=null&&(s.textContent=e),s}var Da=0;function fi(n,t,e,s,i=!0){let r=A(),a=J("div","aparte-elic-panel aparte-approval-panel"),o=J("div","aparte-elic-body");a.appendChild(o);let l=()=>typeof n=="function"?n():n,d=l()?J("p","aparte-elic-message",l()):null;d&&o.appendChild(d);let c=null;if(s){c=J("div","aparte-approval-args-label",r.t("approvalArgsLabel")),c.id="aparte-approval-args-"+ ++Pa;let b=J("pre","aparte-approval-args");b.textContent=s,b.setAttribute("role","group"),b.setAttribute("aria-labelledby",c.id),b.tabIndex=0,o.append(c,b)}let h=J("div","aparte-elic-dismiss");a.appendChild(h);let p=null,u=!1,_=b=>{u||(u=!0,p?.(b))},f=J("div","aparte-approval-options");f.setAttribute("role","group"),f.setAttribute("aria-label",r.t("approvalOptionsLabel")),d&&(d.id||=`aparte-approval-ask-${++Da}`,f.setAttribute("aria-describedby",d.id));let m=[],I=b=>typeof b.label=="function"?b.label():b.label,x=b=>typeof b.description=="function"?b.description():b.description,R=b=>As(I(b),x(b));for(let b of t){let w=b.tone??"affirm",C=J("button",`aparte-btn aparte-btn--block aparte-btn--surface aparte-approval-option aparte-approval-option--${w}`);C.type="button",C.appendChild(R(b)),C.addEventListener("click",()=>_({option:b.value})),f.appendChild(C),m.push({button:C,option:b})}o.appendChild(f);let M=i?J("textarea","aparte-approval-instruction"):null;M&&(M.rows=1,M.placeholder=r.t("approvalInstructionPlaceholder"),M.setAttribute("aria-label",r.t("approvalInstructionPlaceholder")),M.addEventListener("input",e),o.appendChild(M));let k=()=>M?.value.trim()??"";return{el:a,dismiss:h,onSettle:b=>{p=b},getContent:()=>({instruction:k()}),isComplete:()=>k().length>0,focus:()=>{a.querySelector(".aparte-approval-option")?.focus()},relabel:()=>{let b=A(),w=b.t("approvalInstructionPlaceholder");M&&(M.placeholder=w,M.setAttribute("aria-label",w)),f.setAttribute("aria-label",b.t("approvalOptionsLabel")),d&&(d.textContent=l()),c&&(c.textContent=b.t("approvalArgsLabel"));for(let{button:C,option:g}of m)C.replaceChildren(R(g))}}}function gi(n){return y(n.target??null).requestUserInput(n)}var Ba="Not run: an earlier call of the same step was refused.",_n=n=>JSON.stringify([n.id,n.name,n.input]),fn=new Set,lt=new Map,gn="aparte-chat, aparte-chat-viewport, [data-aparte-chat]";function Ha(n){return{id:n,getMetadata:()=>({id:n,name:n}),getModels:()=>[],chat:async()=>{throw new K("This turn has no provider in the page. Register one, or use a runner that calls the model elsewhere (createAgentStreamRunner, an AG-UI runner).",H.CONFIG_NO_PROVIDER)}}}var is=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===Y){if(lt.size===0)return!0;let a=this._resolveTarget(e?.targetId,t),o=a?y(a):Y;return o===Y||!lt.has(o)}let i=this._resolveTarget(e?.targetId,t);if(!i)return!0;let r=y(i);return r===this._config||r===Y}_streamController=null;options;_config;_claims=!1;constructor(t={}){this.options={autoRegister:!0,...t},this._config=t.config??Y,this._registerKeyResolver(),this.options.autoRegister?Zn(this._config):Qn(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!==Y&&!this._claims&&(this._claims=!0,lt.set(this._config,(lt.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=(lt.get(this._config)??1)-1;t>0?lt.set(this._config,t):lt.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 gi({kind:"approval",message:()=>{let o=this._config.getLocale(),l=y(s),d={id:`tool-${t.id}`,type:"tool_call",status:"awaiting-approval",toolCall:{id:t.id,name:t.name,input:t.input}},c=Bn(d,l).text,h=Hn(d,l);return(o.approvalAsk??"Allow {tool}?").replace("{tool}",()=>h?`${c} ${h}`:c)},details:Dn(t.input,y(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!==He}_providerFor(t){let e=t?this._config.getAIProvider(t):void 0;return e||(this._modelRunsElsewhere?Ha(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),d=this._toolsForCurrentModel(),c=async b=>{let w={messages:b,modelId:r,stream:!0,tools:d.length?d:void 0,...o?.temperature!==void 0?{temperature:o.temperature}:{}};return this.options.requestInterceptor&&(w=await this.options.requestInterceptor(w)),w.toolChoice==="none"&&(w={...w,tools:void 0}),w},h=await c(i);if(this._isAborted){z(t,"aparte-message-aborted",{messageId:e},l),this._updateMessage(t,e,{status:"completed"});return}z(t,"aparte-message-start",{messageId:e,role:"assistant"},l),o?.resume&&z(t,"aparte-message-paused",{messageId:e},l),!o?.resume&&s.id&&this._updateMessage(t,e,{model:{providerId:s.id,modelId:h.modelId,...h.temperature!==void 0?{temperature:h.temperature}:{}}});let p=new AbortController;this._streamController!==p&&this._streamController?.abort(),this._streamController=p,this._turnsInFlight.add(e);let u=o?.rebuild?y(t).getCompactor()??this._config.getCompactor():null,_=()=>{let b=t.getMessages?.()??[],w=b.findIndex(g=>g.id===e),C=w>0?b[w-1]:void 0;return C?.role==="user"?[C.id,e]:[e]},f=()=>o?.resume?this._resumeMessages(t,e,h.messages):h.messages,m=()=>Ea({messages:f(),tools:h.tools}),I=()=>Ca(f())?void 0:m(),x=()=>{this._closeOpenCalls(t,e),z(t,"aparte-message-aborted",{messageId:e},l),this._updateMessage(t,e,{status:"completed"})},R=()=>this._isAborted||p.signal.aborted,M=async()=>{let b=o?.resume?{usage:void 0,suspended:o.resume}:await this._streamLoop(t,e,s,h,a,p,void 0,o?.files),w=this.options.maxTurns??10,C=0,g=new Set,v=Ut({target:t,config:this._config,messageId:e,...l?{targetId:l}:{}});for(;b.suspended;){let D=this._isAborted||p.signal.aborted;if(!D&&++C>w){this._closeOpenCalls(t,e),Ut({target:t,config:this._config,messageId:e,...l?{targetId:l}:{}})({type:"turn-limit-exceeded",scope:"global",limit:w});break}let q=new Set,B=D?void 0:await this._answerDeferred(t,b.suspended.pending,p.signal,v,g,q);if(g=q,!B){this._closeOpenCalls(t,e),(this._isAborted||p.signal.aborted)&&z(t,"aparte-message-aborted",{messageId:e},l);break}let X={outcomes:B,...b.suspended.ticket?{token:b.suspended.ticket}:{}},yt=this._resumeMessages(t,e,h.messages);this._spendPause(t,e),z(t,"aparte-message-resumed",{messageId:e},l),b=await this._streamLoop(t,e,s,{...h,messages:yt},a,p,X)}let L=b.usage,S=b.finishReason;this._isAborted||p.signal.aborted?(this._closeOpenCalls(t,e),this._updateMessage(t,e,{status:"completed"})):(z(t,"aparte-message-done",{messageId:e,role:"assistant",usage:L,...S?{finishReason:S}:{}},l),this._readWindowAfterTurn())},k=async b=>{if(b.code!==H.USAGE_CONTEXT_EXCEEDED||!u||!o?.rebuild||(t.getMessage?.(e)?.segments??t.getMessages?.()?.find(C=>C.id===e)?.segments??[]).some(C=>C.type==="text"||C.type==="tool_call"))return"stands";try{let C=await u.compact({target:t,...l?{targetId:l}:{},force:!0,reason:"overflow",exclude:_(),signal:p.signal});if(R())return"stopped";if(!C.ok||C.skipped)return"stands";h=await c(await o.rebuild())}catch{return"stands"}return this._updateMessage(t,e,{status:"pending"}),"resend"};try{for(let b=0;;b++)try{if(b===0&&u?.beforeSend&&o?.rebuild){let w=!1;try{w=await u.beforeSend({target:t,...l?{targetId:l}:{},exclude:_(),requestTokens:m(),signal:p.signal})}catch(C){console.warn("[AparteClient] The compactor threw before a send; sending the request as built.",C)}if(R()){x();return}w&&(h=await c(await o.rebuild()))}this._updateMessage(t,e,{contextEstimate:I()}),await M();return}catch(w){if(this._closeOpenCalls(t,e),R()){z(t,"aparte-message-aborted",{messageId:e},l),this._updateMessage(t,e,{status:"completed"});return}let C=K.from(w,H.UNKNOWN_ERROR),g=b===0?await k(C):"stands";if(g==="resend")continue;if(g==="stopped"){x();return}this._handleLifecycleError(t,e,C);return}}finally{this._turnsInFlight.delete(e)}}_turnsInFlight=new Set;_toolsForCurrentModel(){return di(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(x=>x.id===e),l=(a>=0?r[a]:void 0)?.role==="user"?a+1:a,d=a>=0?r.slice(0,l):r,c={id:W(),role:"assistant",content:"",status:"pending",timestamp:Date.now()},h=i.addSiblingOf?.(e,c)??c.id,p=this._config.getModelConfig(),u=p.defaultProvider,_=this._providerFor(u);if(!_)return;let f=u?await this._resolveAuth(u):void 0,m=this._messagesToChatMessages(d),I=this._systemMessages();await this._streamTurn(i,h,_,[...I,...ft(m)],p.defaultModel||"",f,{temperature:.4,rebuild:async()=>[...this._systemMessages(),...ft(this._messagesToChatMessages(this._current(i,d)))]})}_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}r.updateMessage?.(e,{content:s});let a=r.getMessages?.()??[],o=a.findIndex(m=>m.id===e);if(r.truncateResponsesAfter)r.truncateResponsesAfter(e);else{let m=o>=0&&o+1<a.length?a[o+1]?.id:void 0;m&&r.truncateFrom?.(m)}let l=o>=0?a.slice(0,o+1):a,d=this._messagesToChatMessages(l),c=this._systemMessages(),h=this._config.getModelConfig(),p=h.defaultProvider,u=this._providerFor(p);if(!u)return;let _=p?await this._resolveAuth(p):void 0,f=W();r.appendMessage?.({id:f,role:"assistant",content:"",status:"pending",timestamp:Date.now()}),await this._streamTurn(r,f,u,[...c,...ft(d)],h.defaultModel||"",_,{rebuild:async()=>[...this._systemMessages(),...ft(this._messagesToChatMessages(this._current(r,l)))]})}_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?rt(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=ut(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(gn)){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(gn);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}=Jt(t);return[...this._summaryMessage(e),...Vt(s)]}_summaryMessage(t){return t===void 0?[]:[{role:"user",content:ws(t)}]}_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 f=this._byId(a,t),m=this._asRenderTarget(f);m?r=m: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 f of this._originChain(t)){let m=f;if(typeof m?.appendMessage=="function"){r=m;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 f=Array.isArray(t.detail?.files)?t.detail.files:[];r.appendMessage?.({id:W(),role:"user",content:e,timestamp:Date.now(),...f.length>0?{attachments:ei(f)}:{}}),t.detail&&typeof t.detail=="object"&&(t.detail.echoed=!0)}let o=W(),l=this._config.getModelConfig(),d=i||l.defaultProvider;if(!d&&!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 K("No provider selected. Please configure a provider.",H.CONFIG_NO_PROVIDER));return}let c=this._providerFor(d);if(!c){this._handleLifecycleError(r,o,new K(`Provider '${d}' is not registered.`,H.CONFIG_MISSING_KEY,{providerId:d}));return}r.appendMessage?.({id:o,role:"assistant",content:"",status:"pending",timestamp:Date.now()});let h,p,u,_=Array.isArray(t.detail?.files)?t.detail.files:[];try{h=d?await this._resolveAuth(d):void 0;let f=this._selectFilesToInject(_),m=f.length>0?await this._filesToContentParts(f):[];u=m.length>0?m:void 0,p=this._buildMessages(e,r,u)}catch(f){this._handleLifecycleError(r,o,K.from(f,H.UNKNOWN_ERROR));return}await this._streamTurn(r,o,c,p,s||l.defaultModel||"",h,{rebuild:async()=>this._buildMessages(e,r,u),..._.length>0?{files:_}:{}})}_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}),ft(i)}_toHistoryMessages(t){let{summary:e,messages:s}=Jt(t),i=0;for(let r=0;r<s.length;r++){let a=s[r];a.role==="assistant"&&a.status!=="error"&&!oi(a)&&(i=r+1)}return[...this._summaryMessage(e),...Vt(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 d=l.result,c=r.name.split(".").pop()??"";a({type:"text",text:`\`\`\`${c}
70
+ // File: ${r.name}
71
+ ${d}
72
+ \`\`\``})},l.onerror=()=>o(new Error(`Failed to read file: ${r.name}`)),l.readAsText(r)}):(fn.has(r.name)||(fn.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 d=this.options.streamRunner??He;return this._runViaStreamRunner(d,t,e,s,i,r,a,o,l)}async _runViaStreamRunner(t,e,s,i,r,a,o,l,d){let c=o.signal,h=this._targetIdOf(e),p=Ut({target:e,config:this._config,messageId:s,...h?{targetId:h}:{}}),u=r._meta?.prefixSegments,_,f,m,I=g=>{if(p(g),g.type==="tool-failed"&&(m=g.error),g.type==="run-done"&&(f=g.finishReason),g.type==="run-suspended"){let v=g.ticket;_={pending:g.pending,...typeof v=="string"?{ticket:v}:{}}}if(g.type==="run-start"&&u?.length&&!l)for(let v of u)e.addSegment?.(v)},x=async g=>{let v=await this._config.getTransport().chat(i,g,a,{providerId:i.id,signal:c});return typeof v=="string"?v:Tn(v,c)},R=g=>{let v=this._config.getToolHandler(g);if(!v)return;let L={target:e,config:this._config};return(S,D)=>v(S,D,L)},M=!!this.options.approvalResolver,k=g=>{let v=this._config.getTools().find(L=>L.name===g);if(v)return{maxTurns:v.maxTurns,needsApproval:M?v.needsApproval:L=>{let S=this._config.ruleOnToolCall(L).verdict;return S==="allow"?!1:S}}},b=this._approvalResolverFor(e),w=g=>{if(m===void 0||g instanceof K)return g;let v=g instanceof Error?g.message||g.name:typeof g=="string"?g:String(g);return v===m?new K(v,H.UNKNOWN_ERROR,void 0,g):g};return{usage:await t({messageId:s,...i.id?{providerId:i.id}:{},...l?{deferral:l}:{},...d&&d.length>0?{files:d}:{},baseRequest:r,transportCall:x,toolLookup:R,toolConfigLookup:k,approvalResolver:b,emitter:I,signal:c,maxTurns:this.options.maxTurns,toolTimeoutMs:this.options.toolTimeoutMs,idGen:g=>g==="synthetic-tool"?W():`${g}-${W()}`}).catch(g=>{throw w(g)})??void 0,...f?{finishReason:f}:{},..._?{suspended:_}:{}}}_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),d=c=>{for(let h of e.slice(c+1))o[h.toolCallId]={kind:"decision",approved:!1,reason:Ba,by:"earlier-refusal"}};for(let[c,h]of e.entries()){if(s.aborted)break;let p={id:h.toolCallId,name:h.name,input:h.input??{}};if(h.reason==="approval"){let u;try{u=await l(p,s)}catch(_){if(!s.aborted&&_?.name!=="AbortError")throw _}if(!u||s.aborted)return;if(o[h.toolCallId]={kind:"decision",...u},u.approved)a.add(_n(p));else{d(c);break}}else if(h.reason==="external"){let u=null,_=_n(p);if(!r.has(_)&&!a.has(_))try{u=await this._gateBrowserTool(p,s,t,i)}catch(x){if(!s.aborted&&x?.name!=="AbortError")throw x;u=void 0}if(u===void 0||s.aborted)return;if(u&&!u.approved){o[h.toolCallId]={kind:"decision",...u},d(c);break}let f=u?.payload,m=f&&typeof f=="object"&&!Array.isArray(f)?{...p,input:{...p.input,...f}}:p,I=this._config.getToolHandler(h.name);try{if(!I)throw new Error(`No browser handler is registered for "${h.name}".`);let x=await I(m,s,{target:t,config:this._config});o[h.toolCallId]={kind:"result",content:x.content,...x.structuredContent!==void 0?{structuredContent:x.structuredContent}:{}}}catch(x){if(s.aborted)break;o[h.toolCallId]={kind:"failed",error:x instanceof Error?x.message:String(x)}}}}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?ai(i,oe,{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 ft([...this._systemMessages(),...a,...i>=0?Vt([s[i]]):[]])}_closeDeferred(t){let s=[...t.getMessages?.()??[]].reverse().find(r=>r.role==="assistant");if(!s?.segments?.some(kt))return;let i=s.segments.map(r=>{if(!kt(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(p=>p.role==="assistant"),a=(r?.segments??[]).filter(kt),o=a.find(p=>p.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(),d=r.model&&this._config.getAIProvider(r.model.providerId)?r.model:void 0,c=d?.providerId??l.defaultProvider,h=this._providerFor(c);if(!h)return console.warn("[AparteClient] Cannot resume the paused turn: no provider is selected."),!1;this._beginUserTurn(),this._resuming.add(r.id);try{let p=h.id?await this._resolveAuth(h.id):void 0,u=a.map(f=>({toolCallId:f.toolCall.id,name:f.toolCall.name,input:f.toolCall.input,reason:f.deferred.reason})),_=this._resumeBase(i,i.indexOf(r));await this._streamTurn(s,r.id,h,_,d?.modelId??l.defaultModel??"",p,{resume:{pending:u,ticket:o},rebuild:async()=>{let f=s.getMessages?.()??[],m=f.findIndex(I=>I.id===r.id);return m>=0?this._resumeBase(f,m):_},...d?.temperature!==void 0?{temperature:d.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-${W()}`,type:"error",content:s.message,code:s.code};if(Je(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]});z(t,"aparte-message-error",{messageId:e,error:s},this._targetIdOf(t))}};function mi(n){return n.next?mi(n.next):"current"in n?n:null}var Zt=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=mi(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 vt(n){return n.status==="streaming"||n.status==="pending"?!0:n.status===void 0&&n.role==="assistant"&&!n.content?.trim()&&!n.segments?.length}var mn=Symbol.for("aparte.dialogTriggers"),rs=null,te=null;function Na(n){rs=n.target,te=null}function qa(n){te=n.target}function $a(n){let t=n.target;if(!t?.closest)return;let e=t.closest("[data-aparte-dialog-open]");if(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){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=rs===t&&te===t;rs=null,te=null,i&&t.close()}}function bi(n=document){let t=n;t[mn]||(t[mn]=!0,n.addEventListener("pointerdown",Na,!0),n.addEventListener("pointerup",qa,!0),n.addEventListener("click",$a))}var je="defer-hydration",It=new WeakMap,xt=new WeakMap,St=new WeakSet,ee=new WeakSet,as=new WeakMap,bn=new WeakSet;function vn(n){if(ee.has(n))return!1;if(xt.has(n))return!0;let t=n.closest(`[${je}]`);if(!t)return!1;xt.set(n,t);let e=It.get(t);if(!e){e=[],It.set(t,e);let s=new MutationObserver(()=>{t.hasAttribute(je)||Fa(t)});s.observe(t,{attributes:!0,attributeFilter:[je]}),as.set(t,s)}return e.push(n),!0}function Fa(n){as.get(n)?.disconnect(),as.delete(n);let t=It.get(n)??[];It.delete(n);for(let e of t)xt.delete(e),e.isConnected&&!ee.has(e)&&e.connectedCallback?.()}function N(n){if(bn.has(n))return;bn.add(n);let t=n.prototype,e=t.connectedCallback,s=t.attributeChangedCallback,i=t.disconnectedCallback,r=n.observedAttributes??[];t.connectedCallback=function(){if(vn(this)){St.add(this);return}if(St.has(this)){St.delete(this);for(let a of r){let o=this.getAttribute(a);o!==null&&s?.call(this,a,null,o)}}ee.add(this),e?.call(this)},s&&(t.attributeChangedCallback=function(a,o,l){if(vn(this)){St.add(this);return}s.call(this,a,o,l)}),t.disconnectedCallback=function(){let a=xt.get(this);if(a){xt.delete(this);let o=It.get(a);o&&o.splice(o.indexOf(this),1);return}St.has(this)||(ee.delete(this),i?.call(this))}}function V(n){return n===""?!0:!!n}var de=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",V(t))}get selected(){return this.hasAttribute("selected")}set selected(t){this.toggleAttribute("selected",V(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)}};N(de);customElements.get("aparte-option")||customElements.define("aparte-option",de);var he=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",V(t))}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(t){this.toggleAttribute("collapsed",V(t))}get loading(){return this.hasAttribute("loading")}set loading(t){this.toggleAttribute("loading",V(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=y(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,` ${y(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":""})}};N(he);customElements.get("aparte-optgroup")||customElements.define("aparte-optgroup",he);var ue=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",V(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(y(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=y(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 d=document.createElement("span");d.className="aparte-select-chevron",d.innerHTML=i.getIcon("expand"),r.append(a,d);let c=document.createElement("div");c.className="aparte-select-dropdown",c.hidden=!this._isOpen;let h=e?this._buildSearchInput(i):null;h&&c.appendChild(h);let p=document.createElement("div");p.className="aparte-select-options",p.setAttribute("role","listbox"),p.setAttribute("aria-label",r.getAttribute("aria-label")??t),p.id=this.id?`${this.id}-listbox`:`aparte-listbox-${++n._listboxSeq}`,r.setAttribute("aria-controls",p.id),h?.setAttribute("aria-controls",p.id),s.forEach(u=>{(u.tagName==="APARTE-OPTION"||u.tagName==="APARTE-OPTGROUP")&&p.appendChild(u)}),c.appendChild(p),this._observer?.disconnect(),this.innerHTML="",this.appendChild(r),this.appendChild(c),this._trigger=r,this._dropdown=c,this._searchInput=c.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=rt(t);(!e||!this.contains(e))&&this._closeDropdown()}_handleKeydown(t){if(!this._isOpen)return;let e=at(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=>vi(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 vi(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 vi(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()}N(ue);customElements.get("aparte-select")||customElements.define("aparte-select",ue);var pe=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>`}};N(pe);customElements.get("aparte-progress-spinner")||customElements.define("aparte-progress-spinner",pe);var _e=class extends HTMLElement{static get observedAttributes(){return["name"]}_unsubscribe=null;connectedCallback(){this._render(),this._unsubscribe=it(this,()=>this._render())}disconnectedCallback(){this._unsubscribe?.(),this._unsubscribe=null}attributeChangedCallback(){this.isConnected&&this._render()}_render(){let t=this.getAttribute("name"),e=t?y(this).getIcon(t):null;this.innerHTML=e??"",this.firstElementChild?.setAttribute("aria-hidden","true")}};N(_e);customElements.get("aparte-icon")||customElements.define("aparte-icon",_e);function yi(n){let t=n.activeElement;for(;t?.shadowRoot?.activeElement;)t=t.shadowRoot.activeElement;return t}function Es(n,t){for(let e=n;e;e=e.parentNode??(e instanceof ShadowRoot?e.host:null))if(e===t)return!0;return!1}function wi(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=d=>{let c=d.t("elicitationHide");r.setAttribute("aria-label",c),r.title=c,o.textContent=d.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 fe=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=it(this,()=>this._relabelPending()),y(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(){y(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=y(this);j(t,()=>this._pending.relabel())}_present=t=>{let e=this._getComposer();return e?new Promise((s,i)=>{let r=!1,a={},o=yi(document),l=()=>{let S=t.message;return String(typeof S=="function"?S():S??"")},d="aparte-chat, [data-aparte-chat], [data-aparte-host]",c='input, textarea, select, [contenteditable]:not([contenteditable="false"])',h=e.closest(d)??e.parentElement??e,p=!(o instanceof HTMLElement)||o===document.body,u=p?null:o,_=u!==null&&Es(u,h),f=u!==null&&u.matches(c),m=u!==null&&!_&&(f||u.tagName==="IFRAME"||u.closest(d)!==null),I=S=>{let D=e.querySelector(":scope > .aparte-elic-status");D||(D=document.createElement("span"),D.className="aparte-sr-only aparte-elic-status",D.setAttribute("role","status"),e.appendChild(D));let q=D;q.textContent="",S&&setTimeout(()=>{q.isConnected&&(q.textContent=S)},60)},x=(S,D)=>{if(m){I(D);return}let q=window.scrollX,B=window.scrollY;f&&_?(S.el.hasAttribute("tabindex")||S.el.setAttribute("tabindex","-1"),S.el.hasAttribute("role")||S.el.setAttribute("role","group"),D&&!S.el.hasAttribute("aria-label")&&S.el.setAttribute("aria-label",D),S.el.focus()):S.focus(),p&&(window.scrollX!==q||window.scrollY!==B)&&window.scrollTo(q,B)},R=()=>{if(r)return!1;r=!0,this._pending=null;let S=yi(document),D=S instanceof Node&&Es(S,e);return e.hidePanel(a.token),I(""),D&&((!m&&u!==null&&u.isConnected&&!Es(u,e)?u:null)??e).focus(),!0},M=S=>{R()&&s(S)},k=(S="aborted")=>{R()&&i(new st(S))};if(t.signal){if(t.signal.aborted){k();return}t.signal.addEventListener("abort",()=>k(),{once:!0})}let b=y(this);if(t.kind==="approval"){let S=()=>B.isComplete()&&!B.el.hasAttribute("data-collapsed"),D=()=>S()?"submit":"none",q=()=>e.setPanelSubmitEnabled(S(),D()),B=j(b,()=>fi(t.message,t.options??[],q,t.details,t.allowOther??!0));B.onSettle(yt=>M({action:"accept",content:yt}));let X=wi(B.el,B.dismiss,b,()=>B.focus(),q);this._pending={abort:()=>k(),composer:e,relabel:()=>{B.relabel(),X.relabel(y(this))}},a.token=e.showPanel(B.el,{submitEnabled:B.isComplete(),mode:D(),onSubmit:()=>{B.isComplete()&&M({action:"accept",content:B.getContent()})},onEvict:()=>k()}),x(B,l());return}let w=t.schema??{type:"string"},C=()=>{let S=g.el.hasAttribute("data-collapsed");e.setPanelSubmitEnabled(!S&&g.canProceed(),S?"none":g.mode())},g=j(b,()=>_i(t.message,w,C)),v=document.createElement("button");v.type="button",v.className="aparte-btn aparte-elic-skip",v.textContent=b.t("elicitationSkip"),v.addEventListener("click",()=>M({action:"decline"})),g.dismiss.appendChild(v);let L=wi(g.el,g.dismiss,b,()=>g.focus(),C);g.onSettle(S=>M({action:"accept",content:S})),this._pending={abort:()=>k(),composer:e,relabel:()=>{g.relabel();let S=y(this);v.textContent=S.t("elicitationSkip"),L.relabel(S)}},a.token=e.showPanel(g.el,{submitEnabled:g.canProceed(),mode:g.mode(),onEvict:()=>k(),onSubmit:()=>{g.isComplete()&&M({action:"accept",content:g.getContent()})}}),x(g,l())}):Promise.reject(new st("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")&&(N(fe),customElements.define("aparte-elicitation",fe));function Hi(n){return!n.hasAttribute("loading")&&!n.querySelector("aparte-chat-bubble")}var ge=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=ii(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="${E(t)}"`:"")+(this.hasAttribute("disabled")?" disabled":""),s=this.hasAttribute("attachments");this.innerHTML=`
73
+ <aparte-chat-viewport></aparte-chat-viewport>
74
+ <aparte-elicitation></aparte-elicitation>
75
+ <aparte-composer${e}>
76
+ <div class="aparte-composer-shell">
77
+ ${s?"<aparte-composer-attachments></aparte-composer-attachments>":""}
78
+ <div class="aparte-composer-row">
79
+ ${s?"<aparte-composer-add-attachment></aparte-composer-add-attachment>":""}
80
+ <aparte-composer-input></aparte-composer-input>
81
+ <aparte-composer-send></aparte-composer-send>
82
+ </div>
83
+ </div>
84
+ </aparte-composer>
85
+ `,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||Hi(t))}};N(ge);customElements.get("aparte-chat")||customElements.define("aparte-chat",ge);var Si=n=>!!n&&typeof n.getMessages=="function"&&typeof n.updateMessage=="function";function Ua(n){let t=Q(n);if(Si(t))return t;let e=n.closest("aparte-chat-viewport");return Si(e)?e:null}function ja(n,t){let e=Ua(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 Z(n,t,e){let s=document.createElement(n);return s.className=t,e!==void 0&&(s.textContent=e),s}function Rt(n,t){let e=Z("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 Wa(n){let{kind:t,locale:e}=n,s=Z("div","aparte-checkpoint");s.setAttribute("role","group"),s.setAttribute("aria-label",e.checkpointGroup??"Context summary"),s.setAttribute("data-state",t);let i=Z("div","aparte-checkpoint__row aparte-divider aparte-divider--label"),r=Z("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=Z("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(Z("span","aparte-sr-only",`: ${n.reason}`)))),r.appendChild(o),t==="done"||t==="legacy")if(n.confirming&&t==="done"){let l=Z("span","aparte-checkpoint__confirm"),d=Z("span","aparte-checkpoint__question",e.checkpointRestoreConfirm??"Send the original messages to the model again?");d.id=`${n.summaryId}-question`;let c=Rt("restore-confirm",e.checkpointRestore??"Restore");c.setAttribute("aria-describedby",d.id),l.append(d,c,Rt("restore-cancel",e.cancel??"Cancel")),r.appendChild(l)}else{let l=Rt("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(Rt("restore",e.checkpointRestore??"Restore"))}else t==="failed"&&r.appendChild(Rt("retry",e.retry??"Retry"));if(t==="done"||t==="legacy"){let l=Z("div","aparte-checkpoint__summary aparte-segment-content");l.id=n.summaryId,n.open||(l.hidden=!0),s.appendChild(l)}return s}var Ai=!1;function Ga(n){Ai||(Ai=!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 ks(n){let t=typeof n.fallback=="string"&&n.fallback.trim()?n.fallback:null;t||Ga(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 pt(n,t){let e=fs(n,t);return e||(Xn(t),fs(n,t))}function Ot(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 Bt=new Map;function Va(){let n=[...Bt].filter(([e])=>!e.firstChild);Bt.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 za=0,me=class extends HTMLElement{_contentEl=null;_segmentsEl=null;_attachmentsEl=null;_actionBarEl=null;_branchPickerEl=null;_footerEl=null;_content="";_streaming=!1;_segments=[];_role="assistant";_attachments=[];_usage=null;_finishReason=null;_contextSummary=null;_legacyCompaction=null;_checkpointOpen=!1;_confirmingRestore=!1;_checkpointDrawn="";_checkpointId=`aparte-checkpoint-${++za}`;_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(),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;_releasedWhileDetached=!1;_releaseCheckQueued=!1;_offRenderers=null;_toolRendererFor(t){if(t.type!=="tool_call")return null;let e=this._cfg;if(pt("tool_call",e)!==mt)return null;let s=t.toolCall?.name;return!s||e.isToolHidden(s)?null:e.getToolRenderer(s)??null}_install(t,e,s){let i=this._drawn.get(t.id);i&&i.el!==e&&this._release(t.id);let r={el:e,renderer:s,tool:null,segment:t};this._drawn.set(t.id,r),this.isConnected||this._scheduleReleaseCheck(),s?.setup&&j(this._cfg,()=>s.setup(e,t)),t.type==="tool_call"&&(r.tool=_s(e))}_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=pt(t.type,s),r=e.el;this._release(t.id);let a=i?Ot(j(s,()=>i.render(t)),t):ks(t);return a?(r.replaceWith(a),this._install(t,a,i),!0):(r.remove(),!0)}_stillDrawnByCurrent(t,e){return pt(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)}}_onRenderersChange=t=>{t!==this._cfg&&t!==Y||this._redrawSegmentsWhoseRendererChanged()};_keepsItsDrawing(t,e){return(ms(e.renderer)||t.type==="tool_call"&&ms(e.tool))&&this._stillDrawnByCurrent(t,e)}_redrawIfStale(){if(!(this._streaming||this._editing||nt(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=nt(this._cfg);for(let t of this._segments){let e=this._drawn.get(t.id);this._keepsItsDrawing(t,e)||this._redrawSegment(t)}this._reflectError(),this._syncCopyAction()}}_relabelSegments(){if(this._segmentsEl)for(let t of this._segments){let e=pt(t.type,this._cfg);if(!e?.relabel)continue;let s=this._segmentsEl.querySelector(`:scope > [data-segment-id="${G(t.id)}"]`);s&&j(this._cfg,()=>e.relabel(s,t))}}_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 y(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??=Ln(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()}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._updateWaiting()}_replaceSegments(t){let e=[...t];this._resyncKeepingCards(e)||(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=nt(this._cfg);for(let s of t)e.has(s.id)?this._applySegmentUpdate(s.id,s,s):this._redrawSegment(s);return this._reflectError(),this._syncCopyAction(),!0}addSegment(t){this._segments.push(t),this._appendSegmentEl(t),this._updateWaiting()}updateSegment(t,e){let s=this._segments.findIndex(i=>i.id===t);if(s!==-1){let i=ls(this._segments[s],e);this._segments[s]=i,this._applySegmentUpdate(t,i,e),this._syncCopyAction(),("status"in e||"isStreaming"in e)&&this._updateWaiting()}}appendToSegment(t,e){let s=this._segments.find(i=>i.id===t);s&&"content"in s&&(s.content+=e,this._applySegmentUpdate(t,s,{content:s.content}),this._syncCopyAction())}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?.querySelector(`:scope > [data-segment-id="${G(t)}"]`)?.remove(),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()),"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 p=i&&document.activeElement&&i.contains(document.activeElement);i?.remove(),this._checkpointDrawn="",p&&(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,d=i&&l&&i.contains(l)?l.getAttribute("data-checkpoint-action"):null,c=Wa({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 p=c.querySelector(".aparte-checkpoint__summary");p&&(p.innerHTML=this._cfg.renderMarkdown(a))}i?i.replaceWith(c):this.prepend(c),this._checkpointDrawn=o;let h=t??d;h&&c.querySelector(`[data-checkpoint-action="${G(h)}"]`)?.focus()}_onCheckpointClick=t=>{let e=t.target?.closest?.("[data-checkpoint-action]"),s=e?.closest(".aparte-checkpoint");if(!(!e||!s||s.parentElement!==this))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;ja(this,{messageId:i,targetId:this._resolveTargetId()}),this.setContextSummary(null);break}case"retry":{let i=this._resolveTargetId(),r=this._cfg.getCompactor();r?r.compact({target:Q(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=nt(this._cfg));let e=pt(t.type,this._cfg);if(e){let s=Ot(j(this._cfg,()=>e.render(t)),t);s&&(this._segmentsEl.appendChild(s),this._install(t,s,e))}else{let s=ks(t);this._segmentsEl.appendChild(s),this._install(t,s,void 0)}this._contentEl&&(this._contentEl.style.display="none"),this._reflectError()}_applySegmentUpdate(t,e,s){let i=this._segmentsEl?.querySelector(`:scope > [data-segment-id="${G(t)}"]`);if(!i){this._renderSegments();return}if(this._releasedWhileDetached)return;let r=pt(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?.querySelector(`:scope > [data-segment-id="${G(t)}"]`);l&&l!==o.el&&(o.el=l,o.tool=e.type==="tool_call"?_s(l):null)}}else{let o=Ot(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=`
86
+ <div class="aparte-message" data-role="${E(e)}" role="article" aria-label="${E(this._getAriaLabel())}">
87
+ <div class="aparte-avatar" data-role="${E(e)}"></div>
88
+ <div class="aparte-body">
89
+ <div class="aparte-header">
90
+ <span class="aparte-name">${T(s)}</span>
91
+ <span class="aparte-timestamp"></span>
92
+ </div>
93
+ <div class="aparte-attachments" hidden></div>
94
+ <div class="aparte-message-content">
95
+ <div class="aparte-segments"></div>
96
+ <div class="aparte-content"></div>
97
+ <div class="aparte-waiting" hidden>
98
+ <span class="aparte-dots" aria-hidden="true"><span class="aparte-dot"></span><span class="aparte-dot"></span><span class="aparte-dot"></span></span>
99
+ <span class="aparte-sr-only"></span>
100
+ </div>
101
+ </div>
102
+ <div class="aparte-footer">
103
+ <div class="aparte-branch-picker" hidden>
104
+ <button type="button" class="aparte-btn aparte-btn--icon aparte-btn--sm aparte-branch-prev" aria-label="${E(this._cfg.getLocale().previousResponse??"Previous response")}">${this._cfg.getIcon("prevBranch")}</button>
105
+ <span class="aparte-branch-label">1 / 1</span>
106
+ <!-- The move has to be ANNOUNCED. Pressing the arrows deliberately does not
107
+ take focus, so without a live region a screen-reader user gets the new
108
+ branch and no indication anything changed. The visible label cannot be
109
+ the region itself: a custom sibling-nav renderer may replace it with
110
+ dots, which reads as nothing. No new locale key \u2014 the position is
111
+ digits, and the buttons beside it already carry translated labels. -->
112
+ <span class="aparte-sr-only aparte-branch-status" aria-live="polite"></span>
113
+ <button type="button" class="aparte-btn aparte-btn--icon aparte-btn--sm aparte-branch-next" aria-label="${E(this._cfg.getLocale().nextResponse??"Next response")}">${this._cfg.getIcon("nextBranch")}</button>
114
+ </div>
115
+ <div class="aparte-action-bar" role="toolbar" aria-label="${E(this._cfg.getLocale().messageActions??"Message actions")}"></div>
116
+ </div>
117
+ </div>
118
+ </div>
119
+ `;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"),d=h=>{let p="",u=h.ownerDocument.createTreeWalker(h,NodeFilter.SHOW_TEXT);for(let _=u.nextNode();_;_=u.nextNode()){let f=_.parentElement?.closest('[aria-hidden="true"], [hidden]');(!f||!h.contains(f))&&(p+=_.textContent??"")}return p},c=h=>!!h&&(h.hasAttribute("aria-label")||h.hasAttribute("aria-labelledby")||h.hasAttribute("title")||/\p{L}/u.test(d(h)));if((o||l)&&!c(o)&&!c(l)){let h=this._cfg.getLocale();o?.setAttribute("aria-label",h.previousResponse??"Previous response"),l?.setAttribute("aria-label",h.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(u=>!u.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"&&(dt(s)||i?.hidden===!0),o=this._streaming&&this._role!=="user"&&!r&&(e||a),l=this.querySelector(".aparte-message-content");l&&(l.hidden=e&&!o);let d=this.querySelector(".aparte-message");d&&d.toggleAttribute("data-empty",e&&!this._streaming&&this._attachments.length===0);let c=this.querySelector(".aparte-waiting");if(!c||(c.hidden=!o,!o))return;let h=this._cfg.getLocale().typing,p=c.querySelector(".aparte-sr-only");p&&p.textContent!==h&&(p.textContent=h)}_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){Bt.delete(t),t.removeAttribute("data-image");return}Bt.size===0&&queueMicrotask(Va),Bt.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=nt(this._cfg),this._contentEl.style.display="",j(this._cfg,()=>re(this,this._contentEl,this._content,this._streaming)),this._updateWaiting(),this._streaming||this._highlightContentCode()}}_highlightContentCode(){!this._contentEl||!this._cfg.hasHighlightProvider()||this._contentEl.querySelectorAll("pre > code").forEach(t=>{let e=t.textContent??"";if(!e.trim())return;let i=t.className.match(/language-([\w+#-]+)/i)?.[1]??"",r=t.parentElement;Promise.resolve(this._cfg.highlightCode(e,i)).then(a=>{let o=(a??"").trim();!o||!r||!r.isConnected||(/^<pre[\s>]/i.test(o)?r.outerHTML=o:t.innerHTML=o)}).catch(()=>{})})}_renderSegments(){if(this._segmentsEl){this._drawnWithVersion=nt(this._cfg),this._releaseAll(),this._segmentsEl.innerHTML="";for(let t of this._segments){let e=pt(t.type,this._cfg);if(e){let s=Ot(j(this._cfg,()=>e.render(t)),t);s&&(this._segmentsEl.appendChild(s),this._install(t,s,e))}else{let s=ks(t);this._segmentsEl.appendChild(s),this._install(t,s,void 0)}}this._contentEl&&(this._contentEl.style.display=this._segments.length>0?"none":""),this._reflectError(),this._syncCopyAction()}}_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=Ot(j(this._cfg,()=>t(r)));a&&this._attachmentsEl.appendChild(a)}return}this._attachmentsEl.innerHTML=this._attachments.map(r=>{let a=T(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="${T(r.type)}"><img class="aparte-thumbnail__image" src="${T(r.url)}" alt="${a}" loading="lazy" /><span class="aparte-thumb__name">${a}</span></div>`;let o=this._isOpenableUrl(r.url)?` data-url="${T(r.url)}"`:"";return`<div class="aparte-thumbnail aparte-thumb aparte-thumb--file" title="${a}" data-type="${T(r.type)}"${o}><span class="aparte-thumbnail__label">${T(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?ie(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(`
120
+ `)).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(c=>!c.disabled);if(i.length===0)return;let r=document.activeElement,a=i.findIndex(c=>c===r);if(a===-1&&e.key!=="Home"&&e.key!=="End")return;let l=(this.closest("[dir]")?.getAttribute("dir")??document.documentElement.dir)==="rtl"?"ArrowLeft":"ArrowRight",d;e.key==="Home"?d=0:e.key==="End"?d=i.length-1:e.key===l?d=(a+1)%i.length:d=(a-1+i.length)%i.length,e.preventDefault();for(let c of this._rovingButtons())c.tabIndex=c===i[d]?0:-1;i[d]?.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="${E(i)}" title="${E(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="${E(i)}" title="${E(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="${E(i)}" title="${E(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="${E(i)}" title="${E(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="${E(i)}" title="${E(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="${E(i)}" title="${E(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="${E(e)}" title="${E(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="${E(s)}" title="${E(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();hs(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 d=o.copy??"Copy";e.setAttribute("title",d),e.setAttribute("aria-label",d)},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}));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"))),this._updateWaiting(),this._updateFinishNote(),e&&!t&&this._updateContent(),e&&!t&&this._segments.length>0&&this._redrawIfStale()}};N(me);customElements.get("aparte-chat-bubble")||customElements.define("aparte-chat-bubble",me);var be=class extends HTMLElement{static get observedAttributes(){return["visible","text"]}get _cfg(){return y(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=`
121
+ <div
122
+ class="aparte-message aparte-status-container"
123
+ data-visible="${e}"
124
+ role="status"
125
+ aria-live="polite"
126
+ >
127
+ <div class="aparte-avatar" data-role="assistant" style="visibility: hidden"></div>
128
+ <div class="aparte-body">
129
+ <div class="aparte-status-content">
130
+ <div class="aparte-dots" aria-hidden="true">
131
+ <span class="aparte-dot"></span>
132
+ </div>
133
+ <span class="aparte-status-text"></span>
134
+ <span class="aparte-sr-only aparte-status-sr"></span>
135
+ </div>
136
+ </div>
137
+ </div>
138
+ `,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())}};N(be);customElements.get("aparte-chat-status")||customElements.define("aparte-chat-status",be);function Ci(n,t){if(n.role!=="assistant"||n.segments?.length||typeof n.content!="string"||!n.content.trim())return n;let e=Sn(n.content,{blocks:t});return e.length<=1&&e.every(i=>i.type==="text")?n:xs({...n,segments:e})}function xs(n){return Object.defineProperty(n,vs,{value:!0,enumerable:!1}),n}function Ei(n){return n[vs]===!0}var ve=class extends HTMLElement{_container=null;_scrollBtn=null;_bottomSpacer=null;_fwSpacerHeight=0;_spacerRafId=null;_spacerFrozenUntil=0;_layoutTransitionMs=0;_repo=new Zt;_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;_overlayInset=-1;_transcriptInset=-1;_boundResetHandler=null;_checkpointState=null;_stopCheckpointState=null;_frameworkManagedDOM=!1;static get observedAttributes(){return["scroll-threshold","max-rendered-bubbles","loading"]}get loading(){return this.hasAttribute("loading")}set loading(t){this.toggleAttribute("loading",V(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=y(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 Xt({ownId:()=>ri(this)??(this.id||void 0),bubbleOf:t=>this.querySelector(`aparte-chat-bubble[message-id="${G(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!==y(this))return;this._applyDirection(),this._scrollBtn?.setAttribute("aria-label",y(this).t("scrollToBottom")),(this._frameworkManagedDOM?this:this.querySelector(".aparte-viewport-container"))?.setAttribute("aria-label",y(this).t("transcript"))};_nameScrollSurface(t){t.setAttribute("tabindex","0"),t.hasAttribute("role")||t.setAttribute("role","log"),t.setAttribute("aria-label",y(this).t("transcript"))}_applyDirection(){let t=this.querySelector(".aparte-viewport-container");if(!t)return;let e=y(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,...En(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=os(r.segments,i,s,y(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 d=l.segments.findIndex(c=>c.id===a);if(d!==-1){let c=l.segments[d],h=An(c,o);l.segments[d]=ls(c,h),this._notifyBubble(r,"updateSegment",{segmentId:a,updates:h})}}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),Mn(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 kn(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",cs(e.status)&&this._settleSegments(t,s)),this._notifyBubble(t,"update",e),e.status&&this._syncBusy(),this._autoScroll())}addMessage(t){let e=ne({...t});vt(t)&&(e.isStreaming=!0),this._repo.addOrUpdateMessage(this._repo.headId,e),this._pruneRenderedBubbles(),this._syncBusy(),this._autoScroll()}appendMessage(t,e){t=Ci(t,y(this).getStreamBlocks());let s=e?.historical?ne(t):t.segments?.length?{...t,segments:t.segments.reduce((i,r)=>(i.push(os(i,r,t.id,y(this).getSegmentDefaults(r.type))),i),[])}:{...t};if(!e?.historical&&vt(t)&&(s.isStreaming=!0),Ei(t)&&xs(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),vt(t)&&r.setAttribute("streaming",""),this._bottomSpacer&&this._bottomSpacer.parentNode===i?i.insertBefore(r,this._bottomSpacer):i.appendChild(r),bs(r,s)}}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:W(),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 vt(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="${G(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="${G(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=y(this).getStreamBlocks();this._repo.import({...t,messages:t.messages.map(s=>{let i=Ci(s.message,e),r=ne(i);return Ei(i)&&xs(r),{...s,message:r}})}),this._reRenderActivePath()}clearAll(t){if(t?.revokeAttachments!==!1)for(let e of this._repo.getAllMessages())si(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}))}clearMessages(){this._repo.clear()}setMessages(t){this.clearAll({revokeAttachments:!1});for(let e of t)this.appendMessage(e,{historical:!0})}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="${G(t)}"], [data-aparte-bubble][message-id="${G(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}}_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)),vt(a)&&l.setAttribute("streaming",""),s.appendChild(l),bs(l,a,o)}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=y(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",y(this).t("scrollToBottom"));let i=y(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);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",y(this).t("scrollToBottom"));let e=y(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");if(this._container&&(this._frameworkManagedDOM?this._resizeObserver.observe(this._container,{box:"border-box"}):this._resizeObserver.observe(this._container)),this._overlayRoot=this.closest("[overlay-composer]"),this._overlayRoot&&this._resizeObserver){for(let s of this._overlayStack())this._resizeObserver.observe(s);this._overlayObserver=new MutationObserver(()=>{for(let s of this._overlayStack())this._resizeObserver?.observe(s);this._updateOverlayInset()}),this._overlayObserver.observe(this._overlayRoot,{childList:!0}),this._updateOverlayInset()}this._mutationObserver=new MutationObserver(s=>{if(this._lastMutationAt=performance.now(),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})}_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||a),l=r-this._ownScrollAt<this._ownScrollWindowMs&&r-this._readerInputAt>=this._ownScrollWindowMs&&!this._pointerHeld&&(s<=i+2||o),d=s>1&&!l,c=s>1&&r-this._readerInputAt<this._ownScrollWindowMs;this._lastScrollTop=t,this._lastScrollHeight=e,this._isAtBottom()&&!c?this._isAutoScrollEnabled=!0:d?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(p=>p.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,d=parseFloat(getComputedStyle(this._container).scrollPaddingTop)||0,c=this._container.clientHeight-d-l,h=this._container.clientHeight;this._setSpacerHeight(Math.min(Math.max(0,c),h)),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._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}};N(ve);customElements.get("aparte-chat-viewport")||customElements.define("aparte-chat-viewport",ve);var ye=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 y(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??y(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",V(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})}removeAttachment(t){this._attachments=this._attachments.filter(e=>e!==t),this._emit("attachments-change",{attachments:this._attachments})}clearAttachments(){this._attachments=[],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",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()}_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)return;this._emit("submit",{value:t,attachments:this._attachments});let e={content:t,timestamp:Date.now(),targetId:this._ownTargetId(),files:this._attachments.length>0?[...this._attachments]:void 0};this.dispatchEvent(new CustomEvent("aparte-send",{bubbles:!0,composed:!0,detail:e})),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())}};N(ye);customElements.get("aparte-composer")||customElements.define("aparte-composer",ye);function Ni(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 we=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(it(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(){if(!this._editor)return"";let t="",e=s=>{s.childNodes.forEach(i=>{i.nodeType===Node.TEXT_NODE?t+=i.textContent??"":i.nodeName==="BR"?t+=`
139
+ `:e(i)})};return e(this._editor),t.trim()}setValue(t){this._editor&&(this._editor.textContent=t,this._updatePlaceholderVisibility(),this._adjustHeight(),this._getRoot()?.setValue(t))}clear(){this._editor&&(this._editor.innerHTML="",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")}_getPlaceholder(){return this.getAttribute("placeholder")||this._getRoot()?.placeholder||y(this).t("inputPlaceholder")||"Type a message..."}_render(){if(this.querySelector(".aparte-ci-editor"))return;let t=this.hasAttribute("disabled")||this._getRoot()?.disabled||!1,e=E(this._getPlaceholder());this.innerHTML=`<div
140
+ class="aparte-ci-editor"
141
+ contenteditable="${!t}"
142
+ role="textbox"
143
+ aria-multiline="true"
144
+ aria-label="${e}"
145
+ tabindex="${E(String(t?-1:0))}"
146
+ aria-disabled="${t}"
147
+ data-placeholder="${e}"
148
+ ></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.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&&Ni(i?.getAttribute("accept"),r)){s?.addAttachments([r]);return}let a=e.getData("text/plain");a&&document.execCommand("insertText",!1,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())}};N(we);customElements.get("aparte-composer-input")||customElements.define("aparte-composer-input",we);var Se=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=y(this).t("sendButton")||"Send",e=this._getSendIcon(),s=this._getRoot(),i=!s||s.disabled||s.value.trim()==="";this.innerHTML=`<button
149
+ type="button"
150
+ class="aparte-btn aparte-btn--primary aparte-btn--solid aparte-btn--icon aparte-cs-button aparte-send-button"
151
+ aria-label="${E(t)}"
152
+ title="${E(t)}"
153
+ ${i?"disabled":""}
154
+ >${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(it(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=y(this);if(t.mode==="none"){this._button.disabled=!0;return}this._button.disabled=!t.submitEnabled,this._button.innerHTML=this._getSubmitIcon();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();let s=y(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();let e=y(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 y(this).getIcon("check")}_getSendIcon(){return y(this).getIcon("send")||"Send"}_getStopIcon(){return y(this).getIcon("stop")}};N(Se);customElements.get("aparte-composer-send")||customElements.define("aparte-composer-send",Se);var Ae=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(it(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=y(this).t("stopButton")||"Stop",e=this._getStopIcon();this.innerHTML=`<button
155
+ type="button"
156
+ class="aparte-btn aparte-btn--icon aparte-cc-button"
157
+ aria-label="${E(t)}"
158
+ title="${E(t)}"
159
+ hidden
160
+ >${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=y(this).t("stopButton")||"Stop";this._button.setAttribute("aria-label",t),this._button.setAttribute("title",t),this._button.innerHTML=this._getStopIcon()}_getStopIcon(){return y(this).getIcon("stop")}};N(Ae);customElements.get("aparte-composer-cancel")||customElements.define("aparte-composer-cancel",Ae);var Ce=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))}_revokeUrls(){this._objectUrls.forEach(t=>URL.revokeObjectURL(t)),this._objectUrls=[]}_render(t){this.hidden=t.length===0,this._revokeUrls();let e=y(this),s=r=>(e.t("removeAttachment")||"Remove {name}").replace("{name}",()=>r.name);if(this.innerHTML=t.map(r=>{let a=T(r.name),o=`<button class="aparte-btn aparte-btn--icon aparte-btn--sm aparte-thumb__remove" type="button" aria-label="${E(s(r))}">${e.getIcon("close")}</button>`;if(r.type.startsWith("image/")){let l=URL.createObjectURL(r);return this._objectUrls.push(l),`<div class="aparte-thumbnail aparte-thumb aparte-thumb--image" title="${a}"><img class="aparte-thumbnail__image" src="${E(l)}" alt="${a}" /><span class="aparte-thumb__name">${a}</span>${o}</div>`}return`<div class="aparte-thumbnail aparte-thumb aparte-thumb--file" title="${a}"><span class="aparte-thumbnail__label">${T(this._ext(r.name))}</span><span class="aparte-thumb__name">${a}</span>${o}</div>`}).join(""),this.querySelectorAll(".aparte-thumb__remove").forEach((r,a)=>{r.addEventListener("click",o=>{o.stopPropagation();let l=this._getRoot();l&&l.removeAttachment(l.attachments[a])})}),!y(this).getHostHandlers().attachmentPreview)return;let i=t.filter(r=>r.type.startsWith("image/"));this.querySelectorAll(".aparte-thumb--image").forEach((r,a)=>{let o=r.querySelector(".aparte-thumbnail__image");if(!o)return;o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.setAttribute("aria-label",i[a]?.name??"");let l=()=>{this.dispatchEvent(new CustomEvent("aparte-attachment-preview",{bubbles:!0,composed:!0,detail:{url:o.src,name:i[a]?.name??"",type:i[a]?.type??""}}))};o.addEventListener("click",l),o.addEventListener("keydown",d=>{let c=d.key;c!=="Enter"&&c!==" "||(d.preventDefault(),l())})})}_ext(t){let e=t.lastIndexOf(".");return e>0?t.slice(e+1).toUpperCase().slice(0,4):"FILE"}};N(Ce);customElements.get("aparte-composer-attachments")||customElements.define("aparte-composer-attachments",Ce);var Ee=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(it(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=y(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=y(this).t("actionUpload")||"Attach file",e=y(this).getIcon("paperclip"),s=this.hasAttribute("disabled")||this._getRoot()?.disabled||!1;this.innerHTML=`<button
161
+ class="aparte-btn aparte-btn--icon aparte-caa-button aparte-action-button"
162
+ aria-label="${E(t)}"
163
+ title="${E(t)}"
164
+ type="button"
165
+ ${s?"disabled":""}
166
+ >${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=>Ni(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)}}};N(Ee);customElements.get("aparte-composer-add-attachment")||customElements.define("aparte-composer-add-attachment",Ee);var ke=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(it(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=E(this.getAttribute("label")??""),e=this._resolveIcon(this.getAttribute("icon")??""),s=this.hasAttribute("disabled")||this._getRoot()?.disabled||!1;this.innerHTML=`<button
167
+ class="aparte-btn aparte-btn--icon aparte-cact-button aparte-action-button"
168
+ aria-label="${t}"
169
+ title="${t}"
170
+ type="button"
171
+ ${s?"disabled":""}
172
+ >${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:y(this).getIcon(t)??t:""}};N(ke);customElements.get("aparte-composer-action")||customElements.define("aparte-composer-action",ke);var Me=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",""))}};N(Me);customElements.get("aparte-composer-toolbar")||customElements.define("aparte-composer-toolbar",Me);function Te(n){return n.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().trim()}function Ls(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!==""&&!Te(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 ki=n=>n==="running"||n==="waiting"?n:null;function Ms(n,t){return`[${n}="${G(t)}"]`}var Ts=864e5,Is=4,ce=8,Ie=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",V(t))}get manage(){return this.hasAttribute("manage")}set manage(t){this.toggleAttribute("manage",V(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!==y(this)||this._render()};_onStatus=t=>{let e=t.detail;if(typeof e?.id!="string")return;ys(e.id,ki(e.status));let s=this.querySelector(Ms("data-conv-id",e.id));s&&this._applyStatus(s,e.id)};setConversationStatus(t,e){ni(t,ki(e))}getConversationStatus(t){return ae(t)}_applyStatus(t,e){let s=ae(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=at(this),s=e&&this.contains(e)?e.closest("[data-select-id], [data-more-id]"):null,i=s?.dataset.selectId?Ms("data-select-id",s.dataset.selectId):s?.dataset.moreId?Ms("data-more-id",s.dataset.moreId):null,r=s?.closest("[data-conv-id]")??null,a=_=>!_.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 _='<span class="aparte-skeleton aparte-skeleton--text"></span>';this.innerHTML='<div class="aparte-conv-list-loading" aria-hidden="true">'+_+_+_+_+_+_+'</div><span class="aparte-conv-list-loading-status aparte-sr-only" role="status"></span>';let f=this.querySelector(".aparte-conv-list-loading-status"),m=()=>{f?.isConnected&&(f.textContent=this._t("loadingConversations"))};typeof requestAnimationFrame=="function"?requestAnimationFrame(m):m();return}let d=this.querySelector(":scope > .aparte-conv-list-no-match"),c=this._groups().map(_=>this._renderGroup(_)).join("");if(d){for(let _ of Array.from(this.childNodes))_!==d&&_.remove();d.insertAdjacentHTML("beforebegin",c)}else this.innerHTML=c;if(this._applyFilter(),!i)return;let h=this.querySelector(i);if(h&&a(h)){h.focus();return}let p=Array.from(this.querySelectorAll("[data-select-id]")).filter(a),u=o>=0?p[o]??p[p.length-1]:null;if(u){u.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=Te(t),this._applyFilter()}_applyFilter(){let t=this._query;if(this.hasAttribute("loading"))return 0;let e=Ls(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 y(this).getLocale()[t]??gt[t]??""}_groups(){let t=this._conversations;if(this.hasAttribute("flat")||!t.some(c=>typeof c.updatedAt=="number"))return[{key:"all",label:null,items:t}];let e=new Date,s=new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime(),i=y(this).getLocale().tag,r=new Map,a=(c,h,p)=>{let u=r.get(c);u||(u={key:c,label:h,items:[]},r.set(c,u)),u.items.push(p)};for(let c of t){if(c.pinnedAt){a("pinned",this._t("conversationGroupPinned"),c);continue}let h=c.updatedAt;if(typeof h!="number"){a("undated",null,c);continue}if(h>=s)a("today",this._t("conversationGroupToday"),c);else if(h>=s-Ts)a("yesterday",this._t("conversationGroupYesterday"),c);else if(h>=s-7*Ts)a("week",this._t("conversationGroupWeek"),c);else if(h>=s-30*Ts)a("month",this._t("conversationGroupMonth"),c);else{let p=new Date(h),u=p.getFullYear()===e.getFullYear(),_=new Intl.DateTimeFormat(i,u?{month:"long"}:{month:"long",year:"numeric"}).format(p),f=_.charAt(0).toLocaleUpperCase(i)+_.slice(1);a(`m-${p.getFullYear()}-${String(p.getMonth()).padStart(2,"0")}`,f,c)}}let o=["pinned","today","yesterday","week","month"].map(c=>r.get(c)).filter(c=>!!c),l=[...r.keys()].filter(c=>c.startsWith("m-")).sort((c,h)=>h.localeCompare(c)).map(c=>r.get(c)),d=r.get("undated");return[...o,...l,...d?[d]:[]]}_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=T(t.label);return`
173
+ <div class="aparte-conv-group" role="group" aria-label="${E(t.label)}">
174
+ <div class="aparte-menu__label aparte-conv-group__label" aria-hidden="true">${s}</div>
175
+ ${e}
176
+ </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=E(t.id),r=T(t.title||this._t("newChat")),a=E(this._t("conversationActions")),o=y(this).getIcon("more"),l=ae(t.id),d=l?` data-status="${E(l)}"`:"",c=E(l==="running"?"aparte-conv-item__title aparte-shimmer":"aparte-conv-item__title"),h=T(this._statusWords(l));return`
177
+ <div class="${E(s)}" data-conv-id="${i}"${d}>
178
+ <button
179
+ class="aparte-conv-item__select"
180
+ type="button"
181
+ data-select-id="${i}"
182
+ aria-current="${e?"page":"false"}"
183
+ ><span class="${c}">${r}</span><span class="aparte-conv-item__status" aria-hidden="true"></span><span class="aparte-conv-item__state aparte-sr-only">${h}</span></button>
184
+ <button
185
+ class="aparte-btn aparte-btn--icon aparte-btn--sm aparte-conv-item__more"
186
+ type="button"
187
+ data-more-id="${i}"
188
+ aria-label="${a}"
189
+ title="${a}"
190
+ aria-haspopup="menu"
191
+ aria-expanded="false"
192
+ >${o}</button>
193
+ </div>`}_menuMarkup(t){let e=y(this),s=e.getIcon("edit"),i=e.getIcon("pin"),r=e.getIcon(t.archivedAt?"unarchive":"archive"),a=e.getIcon("trash"),o=T(this._t("renameConversation")),l=T(this._t(t.pinnedAt?"unpinConversation":"pinConversation")),d=T(this._t(t.archivedAt?"unarchiveConversation":"archiveConversation")),c=T(this._t("deleteConversation"));return`
194
+ <button type="button" class="aparte-menu__item" role="menuitem" data-menu-action="rename">${s}<span>${o}</span></button>
195
+ <button type="button" class="aparte-menu__item" role="menuitem" data-menu-action="pin">${i}<span>${l}</span></button>
196
+ <button type="button" class="aparte-menu__item" role="menuitem" data-menu-action="archive">${r}<span>${d}</span></button>
197
+ <div class="aparte-menu__separator" role="separator"></div>
198
+ <button type="button" class="aparte-menu__item aparte-conv-menu__item--danger" role="menuitem" data-menu-action="delete">${a}<span>${c}</span></button>`}_confirmQuestion(t){return this._t("deleteConversationConfirm").replace("{title}",()=>t.title||this._t("newChat"))}_confirmMarkup(t){let e=T(this._confirmQuestion(t)),s=T(this._t("cancel")),i=T(this._t("deleteConversation"));return`
199
+ <div class="aparte-conv-menu__confirm">
200
+ <p class="aparte-conv-menu__question">${e}</p>
201
+ <div class="aparte-conv-menu__actions">
202
+ <button type="button" class="aparte-btn aparte-btn--sm aparte-btn--ghost" data-menu-action="cancel">${s}</button>
203
+ <button type="button" class="aparte-btn aparte-btn--sm aparte-btn--danger aparte-btn--solid" data-menu-action="confirm-delete">${i}</button>
204
+ </div>
205
+ </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){let s=t.getBoundingClientRect(),i=e.getBoundingClientRect(),r=s.bottom+Is;r+i.height>window.innerHeight-ce&&s.top-i.height-Is>=ce&&(r=s.top-i.height-Is);let o=getComputedStyle(this).direction==="rtl"?s.left:s.right-i.width;o=Math.max(ce,Math.min(o,window.innerWidth-i.width-ce)),e.style.top=`${r}px`,e.style.left=`${o}px`}_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=rt(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=y(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(at(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="${G(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")})}};N(Ie);customElements.get("aparte-conversation-list")||customElements.define("aparte-conversation-list",Ie);var qi=n=>typeof n=="string"||typeof n=="object"&&n!==null&&typeof n.label=="string",Mi=n=>{try{let t=JSON.parse(n);return Array.isArray(t)?t.filter(qi):[]}catch{return console.warn('[aparte-suggestions] `suggestions` is not a JSON array. Use ["\u2026"] or [{"label": "\u2026", "prompt": "\u2026"}].'),[]}},Ti=n=>typeof n=="string"?n:n.label,Ii=n=>typeof n=="string"?n:n.prompt??n.label,xe=class extends HTMLElement{static get observedAttributes(){return["suggestions","target","empty-only"]}_suggestions=[];_composer=null;_transcript=null;_transcriptObserver=null;_sent=!1;_wasEmpty=!0;_hidOwn=!1;_onSend=()=>{this.hasAttribute("empty-only")&&(this._transcript||this._watchTranscript(),this._sent=!0,this._applyEmptyOnly())};_applyEmptyOnly=()=>{let t=this._transcript?Hi(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"?Mi(t):Array.isArray(t)?t.filter(qi):[],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,window.removeEventListener("aparte-config-change",this._onConfigChange)}attributeChangedCallback(t){this.isConnected&&(t==="suggestions"?(this._readAttribute(),this._render()):t==="target"?this._watchComposer():t==="empty-only"&&(this._watchTranscript(),this.hasAttribute("empty-only")||(this._sent=!1,this._setHidden(!1))))}_groupLabel(){return y(this).t("suggestionsLabel")||"Suggested prompts"}_parsed=null;_readAttribute(){let t=this.getAttribute("suggestions");t===null||t===this._parsed||(this._parsed=t,this._suggestions=Mi(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=Q(this._composer)??Q(this)??(t?document.getElementById(t):null);return e?e.matches("aparte-chat-viewport")?e:e.querySelector("aparte-chat-viewport"):null}_watchTranscript(){let t=this.hasAttribute("empty-only")?this._resolveTranscript():null;t!==this._transcript&&(this._transcriptObserver?.disconnect(),this._transcriptObserver=null,this._transcript=t,t&&(this._transcriptObserver=new MutationObserver(this._applyEmptyOnly),this._transcriptObserver.observe(t,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["loading"]}))),this.hasAttribute("empty-only")&&this._applyEmptyOnly()}_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=Ti(e);let i=Ii(e);i!==s.textContent&&(s.title=i),s.addEventListener("click",()=>this._activate(e)),t.appendChild(s)}this.appendChild(t)}_activate(t){let e={label:Ti(t),prompt:Ii(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=this.contains(document.activeElement);i.setValue(e.prompt),this.getAttribute("mode")==="fill"?i.focus():(i.submit(),r&&i.focus())}};N(xe);customElements.get("aparte-suggestions")||customElements.define("aparte-suggestions",xe);var xi=(n,t)=>{let e=Number(n);return n!==null&&Number.isFinite(e)&&e>0&&e<=1?e:t},Ka=n=>(n instanceof Element?n.closest("aparte-chat, [data-aparte-chat]"):null)?.id||void 0,F=(n,t,e)=>{let s=document.createElement(n);return s.className=t,e!==void 0&&(s.textContent=e),s},Li="http://www.w3.org/2000/svg",Ya=()=>{let n=document.createElementNS(Li,"svg");n.setAttribute("class","aparte-context__ring"),n.setAttribute("viewBox","0 0 36 36");for(let t of["track","value"]){let e=document.createElementNS(Li,"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},Ri=n=>!!n&&typeof n.getMessages=="function",Qa=n=>{if(!n)return null;if(Ri(n))return n;let t=n.viewport??n.querySelector("aparte-chat-viewport");return Ri(t)?t:null},Xa=0,Ja={system:0,tools:0,summary:0,messages:0},Le=class extends HTMLElement{static get observedAttributes(){return["window","warn","danger","target","variant","used"]}_used=null;_level=null;_compactRequested=!1;_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?Q(t):null;e&&(this._seen=e)}_onDone=t=>{let e=t.detail;!e?.usage||!this._isMine(e.targetId)||(this._remember(t.target),this._used=le(e.usage),this._lastDone={messageId:e.messageId,usage:e.usage},this._viewChanged=!1,this._blank=!1,this._overflow=!1,this._render(!0))};_onReset=t=>{this._isMine(Ka(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?le(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._compactRequested=!1,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._compactRequested=!1,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===H.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 y(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=Q(this);return e||(this._seen?.isConnected?this._seen:null)}_messages(){let t=Qa(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)?ui({messages:i,config:this._cfg(),windowOverride:t,viewChanged:this._viewChanged}):this._used===null?null:{window:t,used:this._used,estimated:!1,parts:{...Ja},other:this._used}}_render(t=!1){let e=this._window(),s=e===null?null:this._measure(e);if(this._compact?this.setAttribute("data-compact",this._compact):this.removeAttribute("data-compact"),e===null||s===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=s,this.removeAttribute("data-empty");let i=s.used,r=Math.min(1,i/e),a=xi(this.getAttribute("warn"),.75),o=xi(this.getAttribute("danger"),.9),l=this._overflow||r>=o?"danger":r>=a?"warn":"ok";this.setAttribute("data-level",l);let d=this.getAttribute("variant")==="ring",c=this.querySelector(".aparte-context");c&&c.classList.contains("aparte-context--ring")!==d&&(this.replaceChildren(),c=null,this._panelSignature="");let h=this.querySelector('[role="meter"]'),p=this.querySelector(".aparte-context__text"),u=this.querySelector(".aparte-context__toggle"),_=this.querySelector(".aparte-context__name"),f=this.querySelector(".aparte-context__panel");(!c||!h||!p||!u||!_||!f)&&(c=F("div",d?"aparte-context aparte-context--ring":"aparte-context"),h=d?Ya():F("div","aparte-progress"),h.setAttribute("role","meter"),d||h.appendChild(F("div","aparte-progress__bar")),u=F("button","aparte-btn aparte-btn--ghost aparte-btn--sm aparte-context__toggle"),u.type="button",_=F("span","aparte-sr-only"),_.classList.add("aparte-context__name"),p=F("span","aparte-context__text"),u.append(_,p),f=F("div","aparte-context__panel aparte-popover"),f.id=`aparte-context-panel-${++Xa}`,f.setAttribute("role","group"),f.hidden=!0,u.setAttribute("aria-controls",f.id),c.append(h,u,f),this.replaceChildren(c),this._panelSignature="");let m=this._cfg(),I=m.getLocale().tag||void 0,x=new Intl.NumberFormat(I,{notation:"compact",maximumFractionDigits:1}),R=s.estimated?"~":"",M=`${R}${x.format(i)} / ${x.format(e)}`,k=Math.round(r*100),b=m.t("contextLabel")||"Context window";if(d){let w=h.querySelector(".aparte-context__value");w?.style.setProperty("--aparte-context-ratio",String(k)),w?.classList.toggle("aparte-context__value--empty",k===0),c.title=M}else h.style.setProperty("--aparte-progress-value",String(k));if(h.setAttribute("aria-valuemin","0"),h.setAttribute("aria-valuemax",String(e)),h.setAttribute("aria-valuenow",String(i)),h.setAttribute("aria-label",`${b}: ${M}`),_.textContent=`${b}: `,u.setAttribute("aria-expanded",String(this._open)),p.textContent=d?`${R}${new Intl.NumberFormat(I,{style:"percent",maximumFractionDigits:0}).format(k/100)}`:M,f.setAttribute("aria-label",b),f.hidden=!this._open,this._open?this._renderPanel(f,s,e,x):this._panelSignature="",l!==this._level){this._level=l;let w=this._ownTargetId(),C={level:l,used:i,window:e,ratio:r,targetId:w};this.dispatchEvent(new CustomEvent("aparte-context-threshold",{detail:C,bubbles:!0,composed:!0})),l!=="danger"&&(this._compactRequested=!1)}t&&l==="danger"&&this.hasAttribute("auto-compact")&&!this._compactRequested&&(this._compactRequested=!0,window.dispatchEvent(new CustomEvent("aparte-compact",{detail:{targetId:this._ownTargetId(),auto:!0,window:e}})))}_renderPanel(t,e,s,i){let r=this._cfg(),a=r.getCompactor(),o=this._chat(),l=this._ownTargetId(),d=null;try{d=a?.preview?.({target:o,...l?{targetId:l}:{}})??null}catch{d=null}let{parts:c,used:h}=e,p=c.system+c.tools+c.summary+c.messages,u=p>h&&p>0?h/p:1,_=e.estimated?"~":"",f=[{key:"system",label:r.t("contextSystem")||"System prompt",tokens:c.system*u,approx:"~"},{key:"tools",label:r.t("contextTools")||"Tools",tokens:c.tools*u,approx:"~"},{key:"summary",label:r.t("contextSummary")||"Summary",tokens:c.summary*u,approx:"~"},{key:"messages",label:r.t("contextMessages")||"Messages",tokens:c.messages*u,approx:"~"},{key:"other",label:r.t("contextOther")||"Other",tokens:u<1?0:e.other,approx:"~"},{key:"free",label:r.t("contextFree")||"Free",tokens:Math.max(0,s-h),approx:_}],m=`${_}${i.format(h)} / ${i.format(s)}`,I=d&&d.tokens>0?(r.t("contextReclaim")||"Compacting now would free ~{n} tokens").replace("{n}",()=>i.format(Math.round(d.tokens))):"",x=!!a&&!!d&&this._compact===null,R=F("ul","aparte-context__rows");for(let g of f){let v=F("li","aparte-context__row");v.setAttribute("data-part",g.key),v.append(F("span","aparte-context__row-label",g.label)),v.append(F("span","aparte-context__row-value",`${g.approx}${i.format(Math.round(g.tokens))}`));let L=F("div","aparte-progress aparte-context__row-bar");L.setAttribute("aria-hidden","true"),L.style.setProperty("--aparte-progress-value",String(Math.round(Math.min(1,g.tokens/s)*100))),L.appendChild(F("div","aparte-progress__bar")),v.append(L),R.append(v)}let M=F("li","aparte-context__row aparte-context__row--total");M.setAttribute("data-part","total"),M.append(F("span","aparte-context__row-label",r.t("contextTotal")||"Total"),F("span","aparte-context__row-value",m)),R.append(M);let k=[R];if(this._compact==="running"){let g=F("p","aparte-context__status aparte-shimmer",r.t("checkpointPending")||"Summarising the context\u2026");g.setAttribute("role","status"),k.push(g)}else if(this._compact==="failed"){let g=F("p","aparte-context__status aparte-context__status--failed",r.t("checkpointFailed")||"Couldn't summarise the context");g.setAttribute("role","status"),this._failure&&(g.title=this._failure,g.appendChild(F("span","aparte-sr-only",`: ${this._failure}`))),k.push(g,this._action("retry",r.t("retry")||"Retry"))}I&&k.push(F("p","aparte-context__reclaim",I)),x&&k.push(this._action("compact",r.t("contextCompactNow")||"Compact now"));let b=F("div","aparte-context__content");if(b.append(...k),b.innerHTML===this._panelSignature)return;this._panelSignature=b.innerHTML;let w=document.activeElement,C=w&&t.contains(w)?w.getAttribute("data-context-action")??"":null;t.replaceChildren(...Array.from(b.childNodes)),C!==null&&((C?t.querySelector(`[data-context-action="${G(C)}"]`):null)??this.querySelector(".aparte-context__toggle"))?.focus()}_action(t,e){let s=F("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"),s.width>0&&s.right>document.documentElement.clientWidth&&t.setAttribute("data-align","end")}};N(Le);customElements.get("aparte-context")||customElements.define("aparte-context",Le);var Oi=60,Za=6,to=150,eo=4,so=1,Re=class extends HTMLElement{static get observedAttributes(){return["target","every"]}_host=null;_mutations=null;_resizes=null;_intersections=null;_observedBubbles=[];_observedSurface=null;_rebuildQueued=!1;_pickQueued=!1;_currentId=null;_visible=new Map;_onScreen=new Set;_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),window.addEventListener("aparte-config-change",this._onConfigChange),this._attach()}disconnectedCallback(){this._detach(),this.removeEventListener("click",this._onClick),this.removeEventListener("keydown",this._onKeydown),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}if(typeof MutationObserver<"u"&&(this._mutations=new MutationObserver(t=>{t.some(e=>!this.contains(e.target))&&this._queueRebuild()}),this._mutations.observe(this._host,{childList:!0,subtree:!0,characterData:!0})),typeof ResizeObserver<"u"){this._resizes=new ResizeObserver(()=>this._layout()),this._resizes.observe(this._host);let t=this._viewport();t&&this._resizes.observe(t)}this._rebuild()}_detach(){this._mutations?.disconnect(),this._mutations=null,this._resizes?.disconnect(),this._resizes=null,this._unobserve(),this._release(),this._host=null}_queueRebuild(){this._rebuildQueued||(this._rebuildQueued=!0,requestAnimationFrame(()=>{this._rebuildQueued=!1,this._rebuild()}))}_viewport(){return this._host?.querySelector("aparte-chat-viewport")??null}_scrollSurface(){let t=this._viewport();return t?t.querySelector(".aparte-viewport-container")??t:null}_bubbles(){let t=this._viewport();if(!t)return[];let e=this.getAttribute("every")==="message"?"message":"user",s=Array.from(t.querySelectorAll("aparte-chat-bubble[message-id]"));return e==="message"?s:s.filter(i=>i.getAttribute("data-role")==="user")}_excerpt(t){let s=((t.querySelector(".aparte-message-content")??t).textContent??"").replace(/\s+/g," ").trim();return s.length>Oi?`${s.slice(0,Oi-1).trimEnd()}\u2026`:s}_tickLabel(t){let e=y(this).getLocale(),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(){let t=this._bubbles(),s=y(this).getLocale().scrollRailLabel??"Conversation outline";if(this.getAttribute("aria-label")!==s&&this.setAttribute("aria-label",s),t.length<2){this.setAttribute("data-empty",""),this.replaceChildren(),this._unobserve(),this._currentId=null,this._write("--aparte-scroll-rail-hit-size","");return}this.removeAttribute("data-empty");let i=this._list();i||(i=document.createElement("ol"),i.className="aparte-scroll-rail__list",this.replaceChildren(i));let r=new Map;for(let l of Array.from(i.children)){let d=l.firstElementChild instanceof HTMLElement?l.firstElementChild.dataset.messageId:void 0;d&&r.set(d,l)}let a=new Set,o=0;for(let l of t){let d=l.getAttribute("message-id");a.add(d);let c=r.get(d);if(c)r.delete(d);else{c=document.createElement("li");let _=document.createElement("button");_.type="button",_.className="aparte-scroll-rail__tick",_.dataset.messageId=d,c.appendChild(_)}let h=c.firstElementChild,p=this._tickLabel(l);h.getAttribute("aria-label")!==p&&(h.setAttribute("aria-label",p),h.title=p),d===this._currentId?h.getAttribute("aria-current")!=="true"&&h.setAttribute("aria-current","true"):h.removeAttribute("aria-current");let u=i.children[o]??null;u!==c&&i.insertBefore(c,u),o++}for(let l of r.values())l.remove();this._currentId&&!a.has(this._currentId)&&(this._currentId=null),no(this._observedBubbles,t)||this._observe(t),this._layout()}_observe(t){if(this._unobserve(),this._observedBubbles=t,typeof IntersectionObserver>"u")return;let e=this._scrollSurface();if(e){this._intersections=new IntersectionObserver(s=>{for(let i of s){let r=i.target.getAttribute("message-id");r&&this._visible.set(r,i.isIntersecting?i.intersectionRatio:0)}this._pickCurrent()},{root:e,rootMargin:"0px 0px -70% 0px",threshold:[0,.1,.25,.5,.75,1]}),this._onScreenObserver=new IntersectionObserver(s=>{for(let i of s){let r=i.target.getAttribute("message-id");r&&(i.isIntersecting?this._onScreen.add(r):this._onScreen.delete(r))}this._pickCurrent()},{root:e,threshold:[0]});for(let s of t)this._intersections.observe(s),this._onScreenObserver.observe(s);this._observedSurface=e,e.addEventListener("scroll",this._onRootScroll,{passive:!0})}}_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._visible.clear(),this._onScreen.clear()}_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].getAttribute("message-id");if(this._atBottom()||this._onScreen.has(e)){this._setCurrent(e);return}let s=null;for(let i of t){let r=i.getAttribute("message-id");(this._visible.get(r)??0)>0&&(s=r)}s!==null&&this._setCurrent(s)}_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")}}_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)}_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=this._list()?.children.length??0,r=this.clientHeight;if(!i||!r){this._write("--aparte-scroll-rail-hit-size",""),this._write("--aparte-scroll-rail-gap","");return}let a=t??document.documentElement,o=getComputedStyle(a),l=parseFloat(o.getPropertyValue("--aparte-scroll-rail-hit-size"))||24,d=parseFloat(o.getPropertyValue("--aparte-scroll-rail-tick-thickness"))||2;if(i*l<=r){this._write("--aparte-scroll-rail-hit-size",""),this._write("--aparte-scroll-rail-gap","");return}let c=Math.max(Za,Math.floor(r/i));this._write("--aparte-scroll-rail-hit-size",`${c}px`),this._write("--aparte-scroll-rail-gap",`${Math.max(0,c-d)}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(at(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);e[i]?.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(t),this._hold(t))}_bubbleOf(t){return this._viewport()?.querySelector(`aparte-chat-bubble[message-id="${G(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(),to)}_settle(){let t=this._held,e=this._settleSurface,s=t?this._bubbleOf(t):null;if(t&&s&&e&&this._alignPasses<eo){let i=e.getBoundingClientRect().top+(parseFloat(getComputedStyle(e).scrollPaddingTop)||0),r=s.getBoundingClientRect().top-i;if(Math.abs(r)>so){this._alignPasses++,this._scrollTo(s),this._bumpSettle();return}}this._release(),t&&this._setCurrent(t)}_release(){this._settleTimer!==null&&clearTimeout(this._settleTimer),this._settleTimer=null,this._settleSurface?.removeEventListener("scroll",this._onSurfaceScroll),this._settleSurface=null,this._held=null}};function no(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}N(Re);customElements.get("aparte-scroll-rail")||customElements.define("aparte-scroll-rail",Re);var io="(max-width: 48rem)",Oe=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",V(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-${++ro}`),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})`:io;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=ut(this),s=e===document?Array.from(document.querySelectorAll(t)):[...e.querySelectorAll(t),...document.querySelectorAll(t)];for(let i of s)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:oo(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(){Pi(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=Pi(this);if(e.length===0)return;let s=e[0],i=e[e.length-1],r=at(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=rt(t)?.closest?.("[data-aparte-sidebar-toggle]");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+=Ls(i,Te(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=Te(this._query),e=t!==""&&this._lists().every(s=>typeof s.filter=="function"?s.hasAttribute("data-no-match"):!s.hasAttribute("loading")&&Ls(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=y(this).getLocale();this.setAttribute("aria-label",t.sidebarLabel??"Conversations"),this.dataset.ownLabel="locale"}},ro=0,ao=["a[href]","button:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(",");function Pi(n){return Array.from(n.querySelectorAll(ao)).filter(t=>!t.closest("[hidden]")&&t.checkVisibility?.()!==!1)}function oo(n){return n.closest("aparte-sidebar")??ut(n).querySelector("aparte-sidebar")??document.querySelector("aparte-sidebar")}N(Oe);customElements.get("aparte-sidebar")||customElements.define("aparte-sidebar",Oe);function Di(n,t,e){return Number.isFinite(n)?n<t?t:n>e?e:n:t}function lo(n){let t=Number.isFinite(n.startPercent)?n.startPercent:0;if(!Number.isFinite(n.containerPx)||n.containerPx<=0)return Di(t,0,100);let i=((!n.vertical&&n.rtl)!==(n.primaryEnd===!0)?-1:1)*n.deltaPx*100/n.containerPx;return Di(t+i,0,100)}function Bi(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 co="(max-width: 48rem)",Pt=38,ho=300;function Dt(n,t){let e=Number.parseFloat(n??"");return Number.isFinite(e)?e<0?0:e>100?100:e:t}var Pe=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=Pt;_initialPosition=Pt;_initialCaptured=!1;_preCollapsePosition=null;_lastPosition=null;_lastCollapsed=null;_lastPane=null;_source="api";_ready=!1;_dragging=!1;_captured=!1;_moved=!1;_pointerId=null;_dragStartPercent=Pt;_dragOriginPx=0;_dragContainerPx=0;_keying=!1;get position(){return this._position}set position(t){let e=Dt(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",V(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",V(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",V(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=Dt(t,Pt),this._setLive(this._position)):this._position=Dt(getComputedStyle(this).getPropertyValue("--aparte-split-position"),Pt),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=Dt(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=lo({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(),ho)}}_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=Bi(t.key,t.shiftKey,this._rtl(),this.orientation==="vertical",this.primary==="end");e!==null&&(t.preventDefault(),this._keying=!0,this._position=Dt(String(this._position+e),this._position),this._setLive(this._position))};_onKeyup=t=>{!this._keying||t.target!==this._handle||Bi(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})`:co;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=rt(t)?.closest?.("[data-aparte-split-pane]");if(!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")??ut(e).querySelector("aparte-split")??document.querySelector("aparte-split"))!==this)return;this.showPane(i??(this.pane==="start"?"end":"start"))};_syncPaneControls(){let t=new Set([ut(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"||(s.closest("aparte-split")??ut(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=y(this).getLocale();t.setAttribute("aria-label",this.getAttribute("label")??e.splitHandleLabel??"Resize the panes"),t.dataset.ownLabel="locale"}};N(Pe);customElements.get("aparte-split")||customElements.define("aparte-split",Pe);var uo="(max-width: 30rem), (max-height: 30rem)",po=["a[href]","button:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(","),De=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",V(t))}get sheet(){return this.hasAttribute("data-sheet")}connectedCallback(){this.classList.contains("aparte-launcher")||this.classList.add("aparte-launcher"),this._button||(this._button=document.createElement("button"),this._button.type="button",this._button.addEventListener("click",this._onButtonClick)),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:[Lt],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(at(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(){return y(this.querySelector(`[${Lt}]`)??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 d=document.createElement("span");d.className="aparte-launcher__label",d.textContent=r,l.push(d)}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})`:uo),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(po)).filter(t=>!t.closest("[hidden]")&&t.checkVisibility?.()!==!1)}_focusChat(){(Array.from(this.querySelectorAll('[role="textbox"]:not([aria-disabled="true"])')).find(s=>!s.closest("[hidden]")&&s.checkVisibility?.()!==!1)??this._focusables().find(s=>s!==this._button))?.focus()}_onClick=t=>{let e=rt(t)?.closest?.("[data-aparte-launcher-close]");e&&this.contains(e)&&this.close()};_inModalDialog(t){let e=rt(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=at(this);t.shiftKey&&r===s?(t.preventDefault(),i.focus()):!t.shiftKey&&r===i&&(t.preventDefault(),s.focus())}};N(De);customElements.get("aparte-launcher")||customElements.define("aparte-launcher",De);typeof document<"u"&&bi();export{H as a,K as b,W as c,Rr as d,Mt as e,Y as f,Yn as g,gi as h,is as i};
206
+ //# sourceMappingURL=chunk-MU6PIUJC.js.map