@aparte/n8n-chat 0.4.0 → 1.0.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 (87) hide show
  1. package/README.md +110 -19
  2. package/dist/cdn/chunks/{chunk-27HPUSEO.js → chunk-75MBZEMR.js} +2 -2
  3. package/dist/cdn/chunks/{chunk-27HPUSEO.js.map → chunk-75MBZEMR.js.map} +1 -1
  4. package/dist/cdn/chunks/{chunk-J2RB5NH4.js → chunk-EKOAQWDB.js} +2 -2
  5. package/dist/cdn/chunks/{chunk-J2RB5NH4.js.map → chunk-EKOAQWDB.js.map} +1 -1
  6. package/dist/cdn/chunks/chunk-FPBJCFJN.js +379 -0
  7. package/dist/cdn/chunks/chunk-FPBJCFJN.js.map +7 -0
  8. package/dist/cdn/chunks/chunk-FZXRS5MT.js +208 -0
  9. package/dist/cdn/chunks/chunk-FZXRS5MT.js.map +7 -0
  10. package/dist/cdn/chunks/{chunk-A2H2YABP.js → chunk-UCBMONE6.js} +2 -2
  11. package/dist/cdn/chunks/{chunk-A2H2YABP.js.map → chunk-UCBMONE6.js.map} +1 -1
  12. package/dist/cdn/chunks/{chunk-GJ4YMVTA.js → chunk-WCZRD7U7.js} +1 -1
  13. package/dist/cdn/chunks/{chunk-GJ4YMVTA.js.map → chunk-WCZRD7U7.js.map} +1 -1
  14. package/dist/cdn/chunks/de-7JCOF7FR.js +2 -0
  15. package/dist/cdn/chunks/de-7JCOF7FR.js.map +7 -0
  16. package/dist/cdn/chunks/es-KUX7YCK6.js +2 -0
  17. package/dist/cdn/chunks/es-KUX7YCK6.js.map +7 -0
  18. package/dist/cdn/chunks/fr-VYD7EC55.js +2 -0
  19. package/dist/cdn/chunks/fr-VYD7EC55.js.map +7 -0
  20. package/dist/cdn/chunks/{highlight-SCSTGNZJ.js → highlight-W7QGGHNK.js} +2 -2
  21. package/dist/cdn/chunks/{highlight-SCSTGNZJ.js.map → highlight-W7QGGHNK.js.map} +1 -1
  22. package/dist/cdn/chunks/it-BXNO2THQ.js +2 -0
  23. package/dist/cdn/chunks/it-BXNO2THQ.js.map +7 -0
  24. package/dist/cdn/chunks/{items-TBASSOQ3.js → items-X2D73Z5A.js} +3 -3
  25. package/dist/cdn/chunks/{items-TBASSOQ3.js.map → items-X2D73Z5A.js.map} +4 -4
  26. package/dist/cdn/chunks/ja-6VGJFQ66.js +2 -0
  27. package/dist/cdn/chunks/ja-6VGJFQ66.js.map +7 -0
  28. package/dist/cdn/chunks/ko-HUU4F44X.js +2 -0
  29. package/dist/cdn/chunks/ko-HUU4F44X.js.map +7 -0
  30. package/dist/cdn/chunks/{link-VR62DJAD.js → link-LNDRLLUH.js} +3 -3
  31. package/dist/cdn/chunks/link-LNDRLLUH.js.map +7 -0
  32. package/dist/cdn/chunks/{media-O7WQHRGC.js → media-JDTPNZHJ.js} +4 -4
  33. package/dist/cdn/chunks/{media-O7WQHRGC.js.map → media-JDTPNZHJ.js.map} +4 -4
  34. package/dist/cdn/chunks/{order-H7FHTQ2J.js → order-HS6FXBIB.js} +3 -3
  35. package/dist/cdn/chunks/{order-H7FHTQ2J.js.map → order-HS6FXBIB.js.map} +3 -3
  36. package/dist/cdn/chunks/{place-TGHDGFFI.js → place-N3E7T2EV.js} +3 -3
  37. package/dist/cdn/chunks/{place-TGHDGFFI.js.map → place-N3E7T2EV.js.map} +4 -4
  38. package/dist/cdn/chunks/{plan-JA7466PF.js → plan-TCWRW3OC.js} +3 -3
  39. package/dist/cdn/chunks/{plan-JA7466PF.js.map → plan-TCWRW3OC.js.map} +4 -4
  40. package/dist/cdn/chunks/{product-VEI5FUDZ.js → product-JH7QUP6I.js} +3 -3
  41. package/dist/cdn/chunks/{product-VEI5FUDZ.js.map → product-JH7QUP6I.js.map} +4 -4
  42. package/dist/cdn/chunks/pt-BR-SNSDLB4C.js +2 -0
  43. package/dist/cdn/chunks/pt-BR-SNSDLB4C.js.map +7 -0
  44. package/dist/cdn/chunks/ru-QE2LLTEY.js +2 -0
  45. package/dist/cdn/chunks/ru-QE2LLTEY.js.map +7 -0
  46. package/dist/cdn/chunks/{score-QTZEGTBP.js → score-GUHJWHW3.js} +6 -6
  47. package/dist/cdn/chunks/{score-QTZEGTBP.js.map → score-GUHJWHW3.js.map} +4 -4
  48. package/dist/cdn/chunks/{stats-CNVSRBY6.js → stats-UIVYR2CG.js} +2 -2
  49. package/dist/cdn/chunks/{stats-CNVSRBY6.js.map → stats-UIVYR2CG.js.map} +1 -1
  50. package/dist/cdn/chunks/{stock-2KHFILSB.js → stock-PV4GC573.js} +2 -2
  51. package/dist/cdn/chunks/{stock-2KHFILSB.js.map → stock-PV4GC573.js.map} +1 -1
  52. package/dist/cdn/chunks/{weather-FAK6EHSV.js → weather-7L3Y3DNB.js} +2 -2
  53. package/dist/cdn/chunks/{weather-FAK6EHSV.js.map → weather-7L3Y3DNB.js.map} +1 -1
  54. package/dist/cdn/chunks/zh-CN-WKC5MGZY.js +2 -0
  55. package/dist/cdn/chunks/zh-CN-WKC5MGZY.js.map +7 -0
  56. package/dist/cdn/n8n-chat.js +61 -61
  57. package/dist/cdn/n8n-chat.js.map +4 -4
  58. package/dist/create-chat.d.ts +27 -2
  59. package/dist/index.js +39 -5
  60. package/dist/index.js.map +1 -1
  61. package/dist/strings.d.ts +7 -0
  62. package/dist/style.css +29 -9
  63. package/dist/theme.css +28 -8
  64. package/package.json +7 -7
  65. package/dist/cdn/chunks/chunk-7CJVMXIB.js +0 -356
  66. package/dist/cdn/chunks/chunk-7CJVMXIB.js.map +0 -7
  67. package/dist/cdn/chunks/chunk-N7SVHDCW.js +0 -206
  68. package/dist/cdn/chunks/chunk-N7SVHDCW.js.map +0 -7
  69. package/dist/cdn/chunks/de-NQDMZC5V.js +0 -2
  70. package/dist/cdn/chunks/de-NQDMZC5V.js.map +0 -7
  71. package/dist/cdn/chunks/es-IBJAOBGB.js +0 -2
  72. package/dist/cdn/chunks/es-IBJAOBGB.js.map +0 -7
  73. package/dist/cdn/chunks/fr-32HJELG3.js +0 -2
  74. package/dist/cdn/chunks/fr-32HJELG3.js.map +0 -7
  75. package/dist/cdn/chunks/it-HHSL2KBW.js +0 -2
  76. package/dist/cdn/chunks/it-HHSL2KBW.js.map +0 -7
  77. package/dist/cdn/chunks/ja-2EHR4WNO.js +0 -2
  78. package/dist/cdn/chunks/ja-2EHR4WNO.js.map +0 -7
  79. package/dist/cdn/chunks/ko-XONDEFR4.js +0 -2
  80. package/dist/cdn/chunks/ko-XONDEFR4.js.map +0 -7
  81. package/dist/cdn/chunks/link-VR62DJAD.js.map +0 -7
  82. package/dist/cdn/chunks/pt-BR-367NLYVE.js +0 -2
  83. package/dist/cdn/chunks/pt-BR-367NLYVE.js.map +0 -7
  84. package/dist/cdn/chunks/ru-ETHLBBSY.js +0 -2
  85. package/dist/cdn/chunks/ru-ETHLBBSY.js.map +0 -7
  86. package/dist/cdn/chunks/zh-CN-OGEW5BS2.js +0 -2
  87. package/dist/cdn/chunks/zh-CN-OGEW5BS2.js.map +0 -7
@@ -1,206 +0,0 @@
1
- var bn=new Set;function la(n){let t=String(n?.type??"undefined");bn.has(t)||(bn.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 ss(n){let{transportCall:t,toolLookup:e,toolConfigLookup:s,approvalResolver:i,emitter:r,signal:a,maxTurns:o=10,toolTimeoutMs:l=3e5,deferral:c}=n,d=n.baseRequest,u=0,h=n.idGen??(b=>`${b}-${u++}`),f=[...d.messages],_=b=>{f.push(b),n.onHistoryAppend?.(b)},p=!0,m=0,T,L;r({type:"run-start"});let R=c?Sn(f):[];if(R.length>0){let b=[],y={turns:1,maxTurns:o,toolLookup:e,toolConfigLookup:s,approvalResolver:i,emitter:r,signal:a,toolTimeoutMs:l,declareCall:()=>{},append:_,deferral:c};for(let[g,w]of R.entries()){if(b.length>0){b.push({toolCallId:w.id,name:w.name,input:w.input,reason:vn(w,s)});continue}let E;try{E=await wn(w,y)}catch(v){for(let S of R.slice(g+1))r({type:"tool-aborted",toolCallId:S.id});throw v}if(typeof E=="object"){b.push({toolCallId:w.id,name:w.name,input:w.input,reason:E.defer});continue}if(E==="stop-run"){for(let v of R.slice(g+1))r({type:"tool-aborted",toolCallId:v.id});p=!1;break}}if(b.length>0&&!a.aborted){r({type:"run-suspended",pending:b});return}}for(;p&&!a.aborted;){if(m++,L=void 0,m>o){r({type:"turn-limit-exceeded",scope:"global",limit:o});break}let b=d.toolChoice;if(m===1&&b&&typeof b=="object"&&!Array.isArray(b)&&b.input!==void 0){let W=b,O=h("synthetic-tool");r({type:"tool-start",toolCallId:O,name:W.name,input:W.input});let at=e(W.name);if(!at){r({type:"tool-aborted",toolCallId:O,cause:"no-handler"}),p=!1;continue}let F=await Cn(at,{id:O,name:W.name,input:W.input},a,l);if(F.status==="aborted"){r(F.cause?{type:"tool-aborted",toolCallId:O,cause:F.cause}:{type:"tool-aborted",toolCallId:O}),p=!1;continue}if(F.status==="failed")throw r({type:"tool-failed",toolCallId:O,error:En(F.error)}),F.error;r({type:"tool-resolved",toolCallId:O,result:F.content,structuredResult:F.structuredContent}),_({role:"assistant",content:"",toolCalls:[{id:O,name:W.name,input:W.input}]}),_({role:"tool",content:F.content,toolCallId:O,toolName:W.name}),d={...d,toolChoice:"none",tools:void 0}}let y={...d,messages:f},g=d.toolChoice;g&&typeof g=="object"&&(d={...d,toolChoice:"auto"});let w;try{w=await t(y)}catch(W){if(a.aborted||W?.name==="AbortError"){p=!1;break}throw W}if(typeof w=="string"){r({type:"turn-start"}),r({type:"text-delta",delta:w}),r({type:"text-flush"});break}r({type:"turn-start"});let E="",v=[],S=!1,x=null,A=W=>{v.push(W),!x&&(x={role:"assistant",content:E.trim(),toolCalls:v},_(x))},P=()=>{x&&(x.content=E.trim())},q=new Set,B=W=>{let O=W;for(let at=2;q.has(O);at++)O=`${W}#${at}`;return q.add(O),O},et=[],xt={turns:m,maxTurns:o,toolLookup:e,toolConfigLookup:s,approvalResolver:i,emitter:r,signal:a,toolTimeoutMs:l,declareCall:A,append:_,deferral:c&&{...c,outcomes:void 0}},es=w[Symbol.asyncIterator](),gn=async()=>{if(!a.aborted)return!1;try{await es.return?.(void 0)}catch{}return p=!1,!0};try{for(;!await gn();){let W=await es.next();if(await gn()||W.done)break;let O=W.value;if(O.type==="thinking"){r({type:"thinking-delta",delta:O.delta});continue}if(O.type==="text"){E+=O.delta,r({type:"text-delta",delta:O.delta});continue}if(O.type==="sources"){r({type:"sources",sources:O.sources,...O.citations?{citations:O.citations}:{}});continue}if(O.type==="done"){O.usage&&(T=O.usage),O.finishReason&&(L=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"){la(O);continue}S=!0;let at=B(O.id);r({type:"tool-start",toolCallId:at,name:O.name,input:O.input});let F={id:at,name:O.name,input:O.input};if(et.length>0){A(F);let mn=vn(F,s);mn==="approval"&&r({type:"tool-awaiting-approval",toolCallId:F.id,name:F.name,input:F.input}),et.push({toolCallId:F.id,name:F.name,input:F.input,reason:mn});continue}let te=await wn(F,xt);if(typeof te=="object"){A(F),et.push({toolCallId:F.id,name:F.name,input:F.input,reason:te.defer});continue}if(te==="stop-run"){p=!1;break}if(te==="stop-turn")break}r({type:"text-flush"}),P()}finally{try{await es.return?.(void 0)}catch{}}if(et.length>0&&!a.aborted)return r({type:"run-suspended",pending:et,usage:T}),T;S||(p=!1)}return a.aborted&&r({type:"run-aborted"}),r({type:"run-done",usage:T,...L?{finishReason:L}:{}}),T}function Sn(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 vn(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 An(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 yn(n,t,e){let s=An(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 wn(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 yn(t,n,r);let a=i?.maxTurns??t.maxTurns;if(t.turns>a)return t.emitter({type:"turn-limit-exceeded",scope:"tool",limit:a,toolCallId:n.id}),"stop-run";if(i?.external){if(!t.deferral)return t.emitter({type:"tool-aborted",toolCallId:n.id,cause:"no-handler"}),"stop-run";if(!r||r.kind==="decision")return{defer:"external"};if(r.kind==="failed")throw t.emitter({type:"tool-failed",toolCallId:n.id,error:r.error}),new Error(r.error);return t.emitter({type:"tool-resolved",toolCallId:n.id,result:r.content,structuredResult:r.structuredContent}),t.declareCall(n),t.append({role:"tool",content:r.content,toolCallId:n.id,toolName:n.name}),"continue"}let o=t.toolLookup(n.name);if(!o)return t.emitter({type:"tool-aborted",toolCallId:n.id,cause:"no-handler"}),"stop-run";let l=n.input,c=typeof i?.needsApproval=="function"?i.needsApproval({id:n.id,name:n.name,input:s}):i?.needsApproval;if(c){let u=r?.kind==="decision"&&c!=="deny"?r:void 0;if(c!=="deny"&&!u&&t.emitter({type:"tool-awaiting-approval",toolCallId:n.id,name:n.name,input:n.input}),!u&&t.deferral&&c!=="deny")return{defer:"approval"};if(!u&&!t.approvalResolver)return t.emitter({type:"tool-aborted",toolCallId:n.id,cause:"no-resolver"}),"stop-run";let h=u;if(!h&&!e.aborted&&t.approvalResolver)try{h=await t.approvalResolver({id:n.id,name:n.name,input:s},e)}catch(f){if(!e.aborted&&f?.name!=="AbortError")throw f}if(e.aborted||!h)return t.emitter({type:"tool-aborted",toolCallId:n.id,cause:"stopped"}),"stop-run";if(!h.approved)return yn(t,n,h),"stop-turn";h.payload&&typeof h.payload=="object"&&!Array.isArray(h.payload)&&(l={...s,...h.payload}),t.emitter({type:"tool-approved",toolCallId:n.id})}let d=await Cn(o,{id:n.id,name:n.name,input:l},e,t.toolTimeoutMs);if(d.status==="aborted")return t.emitter(d.cause?{type:"tool-aborted",toolCallId:n.id,cause:d.cause}:{type:"tool-aborted",toolCallId:n.id}),"stop-run";if(d.status==="failed")throw t.emitter({type:"tool-failed",toolCallId:n.id,error:En(d.error)}),d.error;return t.emitter({type:"tool-resolved",toolCallId:n.id,result:d.content,structuredResult:d.structuredContent}),t.declareCall(n),t.append({role:"tool",content:d.content,toolCallId:n.id,toolName:n.name}),"continue"}async function Cn(n,t,e,s){if(e.aborted)return{status:"aborted",cause:"stopped"};let i=new AbortController,r=()=>i.abort();e.addEventListener("abort",r,{once:!0});let a,o=new Promise(u=>{a=()=>u({status:"aborted",cause:"stopped"}),e.addEventListener("abort",a,{once:!0})}),l,c=!1,d=new Promise(u=>{l=setTimeout(()=>{c=!0,i.abort(),u({status:"aborted",cause:"timeout"})},s)});try{return await Promise.race([n(t,i.signal).then(h=>({status:"resolved",content:h.content,structuredContent:h.structuredContent})),d,o])}catch(u){return u?.name==="AbortError"?e.aborted?{status:"aborted",cause:"stopped"}:c?{status:"aborted",cause:"timeout"}:{status:"aborted"}:{status:"failed",error:u}}finally{clearTimeout(l),e.removeEventListener("abort",r),a&&e.removeEventListener("abort",a)}}function En(n){return n instanceof Error?n.message||n.name:typeof n=="string"?n:String(n)}var ca='<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>',da='<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>',ua='<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>',ha='<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>',pa='<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>',fa='<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>',_a='<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>',ga='<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>',ma='<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>',ba='<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>',va='<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>',ya='<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>',wa='<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>',Sa='<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>',Aa='<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>',Ca='<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>',Ea='<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>',ka='<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>',Ma='<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>',Ta='<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>',La='<svg class="aparte-icon" viewBox="0 0 24 24" fill="currentColor"><rect x="5" y="5" width="14" height="14" rx="2.5"/></svg>',xa='<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>',Ia='<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>',Ra='<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>',Oa='<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>',Pa='<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>',Na='<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>',Da='<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>',Ba='<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>',Ha='<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>',$a='<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>',qa='<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>',kn={copy:ca,check:da,send:ua,loading:ha,error:pa,expand:fa,collapse:_a,terminal:ga,paperclip:ma,image:ba,file:va,scrollDown:ya,retry:wa,edit:Sa,thumbUp:Aa,thumbDown:Ca,prevBranch:Ea,nextBranch:ka,tool:Ma,close:Ta,stop:La,pause:xa,info:Ia,archive:Ra,unarchive:Oa,download:Pa,more:Na,pin:Da,trash:Ba,menu:$a,alertTriangle:qa,messageSquare:Ha};function Si(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||{}),Y=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"}}},Ot=kn,Ct={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.",sourcesCount:"{n} sources",sourcesOne:"1 source",sourcesCard:"Sources",sourcePrevious:"Previous source",sourceNext:"Next source",sourcePosition:"Source {i} of {n}",opensInNewTab:"(opens in a new tab)",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 Ai(n){return typeof n.buildRequest=="function"&&typeof n.parseStream=="function"&&typeof n.defaultEndpoint=="string"&&(typeof n.authHeaders=="function"||typeof n.authQuery=="function")}function Fa(n){return typeof n=="string"?{key:n}:n&&typeof n=="object"?{key:n.apiKey,endpoint:n.endpoint}:{}}function Ua(n,t,e){let s=n?.error,i=typeof s=="object"?s?.message:s;return typeof i=="string"&&i?i:`${e} ${t}`}function Wa(n){return typeof n=="string"&&Object.values(H).includes(n)}async function ja(n,t="HTTP",e){let s=await n.json().catch(()=>{}),i=Ua(s,n.status,t),r=s?.error?.code,a=e?.classifyError?.(n.status,s)??(Wa(r)?r:void 0)??Y.codeForStatus(n.status)??H.UNKNOWN_ERROR;return new Y(i,a,void 0,void 0,n.status)}async function Ga(n,t,e){let s=await t.json();if(typeof n.parseText!="function")throw new Error(`Provider "${e}" cannot resolve a non-streaming response: parseText is not implemented.`);let i=n.parseText(s),r;try{r=n.parseSources?.(s)}catch{r=void 0}return za(i,r)}function za(n,t){if(!t||t.sources.length===0)return n;let e=[{type:"text",delta:n},{type:"sources",...t},{type:"done"}];return new ReadableStream({pull(s){let i=e.shift();i?s.enqueue(i):s.close()}})}var ue=class{byok;warnedBrowserKey=!1;constructor(t={}){this.byok=t.byok??!1}async chat(t,e,s,i){let{key:r,endpoint:a}=Fa(s);if(!this.byok&&r&&this.warnBrowserKeyOnce(i.providerId),!Ai(t)){if(typeof t.chat!="function")throw new Error(`Provider "${i.providerId}" exposes neither a format-adapter surface nor chat().`);return t.chat(e,s,i)}let o=a||t.defaultEndpoint,l=t.buildRequest(e),c=`${o}${l.path}`,d={"Content-Type":"application/json",...l.headers};if(r&&t.authHeaders&&Object.assign(d,t.authHeaders(r)),r&&t.authQuery){let h=new URLSearchParams(t.authQuery(r)).toString();c+=(c.includes("?")?"&":"?")+h}let u=await fetch(c,{method:"POST",headers:d,body:JSON.stringify(l.body),signal:i.signal});if(!u.ok)throw await ja(u,"HTTP",t);if(e.stream===!1)return Ga(t,u,i.providerId);if(!u.body)throw new Error(`Provider "${i.providerId}" returned no response body for a streaming request.`);return t.parseStream(u.body)}warnBrowserKeyOnce(t){this.warnedBrowserKey||(this.warnedBrowserKey=!0,console.warn(`[Aparte] AparteDirectTransport is sending the "${t}" API key straight from the browser \u2014 it is visible to anyone who opens devtools. Fine for BYOK or local models: pass new AparteDirectTransport({ byok: true }) to silence this. For a server-held key, use AparteBackendTransport so the key never reaches the client.`))}};function G(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}var Ka=[{start:"<think>",end:"</think>"},{start:"<thinking>",end:"</thinking>"}],Mt=class{_options;_thinkingDelimiters;_blocks;_state;_pendingSegment=null;constructor(t={}){let e=t.thinkingDelimiters;this._thinkingDelimiters=e?Array.isArray(e)?e:[e]:Ka,this._blocks=t.blocks??[],this._options={autoGenerateIds:t.autoGenerateIds??!0,idPrefix:t.idPrefix??"seg"},this._state=this._createInitialState()}parse(t){this._state.buffer+=t;let e=[];for(;this._state.buffer.length>0||this._pendingSegment;){let s=this._parseNext();if(!s)break;s.segment&&e.push(s.segment),this._state.buffer=s.remaining}return{segments:e,remaining:this._state.buffer,state:{...this._state}}}finalize(){let t=[],e=s=>s.replace(/\n?```[ \t]*$/,"");if(this._state.activeSegment){if("content"in this._state.activeSegment){let s=this._state.activeSegment,i=s.content+this._state.buffer;(s.type==="text"||s.type==="code")&&(i=e(i)),s.content=i}t.push(this._closed(this._state.activeSegment)),this._state.activeSegment=null}else this._state.buffer.trim()&&t.push(this._closed(this._createTextSegment(e(this._state.buffer))));return this._state.mode="text",this._state.buffer="",this._state.codeLanguage=void 0,this._state.thinkingEnd=void 0,this._state.blockEnd=void 0,t}reset(){this._state=this._createInitialState(),this._pendingSegment=null}getState(){return{...this._state}}_parseNext(){if(this._pendingSegment){let e=this._pendingSegment;return this._pendingSegment=null,{segment:e,remaining:this._state.buffer}}let t=this._state.buffer;switch(this._state.mode){case"text":return this._parseTextMode(t);case"code":return this._parseCodeMode(t);case"thinking":return this._parseThinkingMode(t);case"block":return this._parseBlockMode(t);default:return null}}_parseTextMode(t){let e=t.indexOf("```"),s=-1;for(let c of this._thinkingDelimiters){let d=t.indexOf(c.start);d!==-1&&(s===-1||d<s)&&(s=d)}let i=-1,r;for(let c of this._blocks){let d=this._indexOfTag(t,c.tag);d!==-1&&(i===-1||d<i)&&(i=d,r=c)}let a=[];if(e!==-1&&a.push({type:"code",index:e}),s!==-1&&a.push({type:"thinking",index:s}),i!==-1&&a.push({type:"block",index:i}),a.sort((c,d)=>c.index-d.index),a.length===0)return t.endsWith("`")||t.endsWith("``")||this._thinkingDelimiters.some(c=>this._isPartialMatch(t,c.start))||this._blocks.some(c=>this._isPartialMatch(t,"<"+c.tag)||t.endsWith("<"+c.tag))?null:((!this._state.activeSegment||this._state.activeSegment.type!=="text")&&(this._state.activeSegment=this._createTextSegment("")),this._state.activeSegment.content+=t,{segment:null,remaining:""});let o=a[0];if(o.index>0){let c=t.slice(0,o.index);return!this._state.activeSegment||this._state.activeSegment.type!=="text"?this._state.activeSegment=this._createTextSegment(c):this._state.activeSegment.content+=c,{segment:null,remaining:t.slice(o.index)}}let l=null;if(this._state.activeSegment&&this._state.activeSegment.type==="text"&&(l=this._closed(this._state.activeSegment),this._state.activeSegment=null),o.type==="code"){let c=this._startCodeBlock(t);return c?{segment:l,remaining:c.remaining}:(l&&(this._state.activeSegment=l),null)}else if(o.type==="thinking"){let c=this._startThinkingBlock(t);return c?{segment:l,remaining:c.remaining}:(l&&(this._state.activeSegment=l),null)}else{let c=this._startBlock(t,r);return c?c.segment&&l?(this._pendingSegment=c.segment,{segment:l,remaining:c.remaining}):{segment:l??c.segment,remaining:c.remaining}:(l&&(this._state.activeSegment=l),null)}}_startCodeBlock(t){let e=t.indexOf(`
2
- `);if(e===-1)return null;let i=t.slice(0,e).slice(3).trim()||"markdown";return i==="markdown"||i==="md"?{segment:null,remaining:t.slice(e+1)}:(this._state.mode="code",this._state.codeLanguage=i,this._state.activeSegment=this._createCodeSegment(i,""),this._state.activeSegment.isStreaming=!0,{segment:null,remaining:t.slice(e+1)})}_parseCodeMode(t){let e=t.indexOf("\n```");if(e===-1){if(t.length>4){let o=t.slice(0,-4);return this._state.activeSegment&&"content"in this._state.activeSegment&&(this._state.activeSegment.content+=o),{segment:null,remaining:t.slice(-4)}}return null}let s=t.slice(0,e);this._state.activeSegment&&"content"in this._state.activeSegment&&(this._state.activeSegment.content+=s);let i=this._closed(this._state.activeSegment);this._state.mode="text",this._state.activeSegment=null;let r=t.slice(e+4),a=r.startsWith(`
3
- `)?r.slice(1):r;return{segment:i,remaining:a}}_startThinkingBlock(t){let e=this._thinkingDelimiters.find(s=>t.startsWith(s.start));return e?(this._state.mode="thinking",this._state.thinkingEnd=e.end,this._state.activeSegment=this._createThinkingSegment(""),{segment:null,remaining:t.slice(e.start.length)}):null}_parseThinkingMode(t){let e=this._state.thinkingEnd??this._thinkingDelimiters[0].end,s=t.indexOf(e);if(s===-1){if(this._isPartialMatch(t,e)){let a=this._getPartialMatchLength(t,e),o=t.slice(0,t.length-a);return o&&this._state.activeSegment&&"content"in this._state.activeSegment&&(this._state.activeSegment.content+=o),o?{segment:null,remaining:t.slice(-a)}:null}if(t.length>e.length){let a=t.slice(0,-e.length);return this._state.activeSegment&&"content"in this._state.activeSegment&&(this._state.activeSegment.content+=a),{segment:null,remaining:t.slice(-e.length)}}return null}let i=t.slice(0,s);this._state.activeSegment&&"content"in this._state.activeSegment&&(this._state.activeSegment.content+=i);let r=this._closed(this._state.activeSegment);return this._state.mode="text",this._state.activeSegment=null,this._state.thinkingEnd=void 0,{segment:r,remaining:t.slice(s+e.length)}}_indexOfTag(t,e){let s="<"+e,i=0;for(;;){let r=t.indexOf(s,i);if(r===-1)return-1;let a=t[r+s.length];if(a===void 0)return-1;if(a===">"||a==="/"||/\s/.test(a))return r;i=r+1}}_tagEnd(t,e){let s=null,i=!1,r=-1;for(let a=1+e.length;a<t.length;a++){let o=t[a];if(o===">"&&r===-1&&(r=a),s){if(o===s)s=null;else if(o===`
4
- `)return r;continue}if(o===">")return a;if(o==="="){i=!0;continue}if(i&&(o==='"'||o==="'")){s=o,i=!1;continue}/\s/.test(o)||(i=!1)}return-1}_startBlock(t,e){let s=this._tagEnd(t,e.tag);if(s===-1)return null;let i=t.slice(1+e.tag.length,s),r=i.trimEnd().endsWith("/"),a=r?i.trimEnd().slice(0,-1):i,o=Object.create(null);for(let d of a.matchAll(/([A-Za-z_][\w:-]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/g))o[d[1]]=d[2]??d[3]??d[4]??"";let l=e.toSegment({attrs:o,id:this._options.autoGenerateIds?this._generateId():""});l.content="";let c=t.slice(s+1);return r?{segment:this._closed(l),remaining:c}:(l.isStreaming=!0,this._state.mode="block",this._state.blockEnd=`</${e.tag}>`,this._state.activeSegment=l,{segment:null,remaining:c})}_parseBlockMode(t){let e=this._state.blockEnd,s=t.indexOf(e),i=this._state.activeSegment;if(s===-1){if(this._isPartialMatch(t,e)){let a=this._getPartialMatchLength(t,e),o=t.slice(0,t.length-a);return o&&i&&(i.content+=o),o?{segment:null,remaining:t.slice(-a)}:null}if(t.length>e.length){let a=t.slice(0,-e.length);return i&&(i.content+=a),{segment:null,remaining:t.slice(-e.length)}}return null}i&&(i.content+=t.slice(0,s));let r=this._closed(this._state.activeSegment);return this._state.mode="text",this._state.activeSegment=null,this._state.blockEnd=void 0,{segment:r,remaining:t.slice(s+e.length)}}_createInitialState(){return{mode:"text",buffer:"",segments:[],activeSegment:null,segmentCounter:0}}_generateId(){return++this._state.segmentCounter,`${this._options.idPrefix}-${G()}`}_closed(t){return t&&(t.isStreaming=!1),t}_createTextSegment(t){return{id:this._options.autoGenerateIds?this._generateId():"",type:"text",content:t}}_createCodeSegment(t,e){return{id:this._options.autoGenerateIds?this._generateId():"",type:"code",language:t,content:e}}_createThinkingSegment(t){return{id:this._options.autoGenerateIds?this._generateId():"",type:"thinking",content:t}}_isPartialMatch(t,e){for(let s=1;s<e.length;s++)if(t.endsWith(e.slice(0,s)))return!0;return!1}_getPartialMatchLength(t,e){for(let s=e.length-1;s>=1;s--)if(t.endsWith(e.slice(0,s)))return s;return 0}};function Ci(n,t){let e=new Mt(t),s=e.parse(n),i=e.finalize();return[...s.segments,...i]}var Va=new Set(["pending","awaiting-approval"]),Ya=["content","output","result"];function Qa(n){return Ya.some(t=>t in n)}function Hs(n,t,e,s){let i=Za(t,s);return{...i,messageId:t.messageId??e,index:t.index??n.length,...he(i,{startedAt:we(t)?.startedAt??Date.now()})}}function Ja(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 Xa=new Set(["id","type","messageId","index"]);function we(n){return n.meta?.aparte}function he(n,t){return{meta:{...n.meta,aparte:{...n.meta?.aparte,...t}}}}function Za(n,t){if(!t)return n;let e={...n};for(let[s,i]of Object.entries(t))if(!(Xa.has(s)||s in n)){if(s==="meta"){let{aparte:r,...a}=i??{};e.meta=a;continue}e[s]=i}return e}function bt(n){return n.type==="tool_call"?!Va.has(n.status):n.isStreaming===!1}function Ei(n,t){if(bt(n))return t;let e={...n,...t};if(bt(e)){let s=we(n)?.endedAt;return{...t,...he(n,{endedAt:s??Date.now()})}}return Qa(t)?{...t,...he(n,{endedAt:Date.now()})}:t}function $s(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 ki(n){let{startedAt:t,endedAt:e}=we(n)??{};if(!(t==null||e==null))return e-t}function Mi(n){return bt(n)?{}:he(n,{endedAt:Date.now()})}function ns(n){return{content:n.content,...n.isStreaming===!1?{isStreaming:!1}:{}}}function qs(n){return n!=null&&n!=="streaming"&&n!=="pending"}function Ti(n){return n.filter(t=>!bt(t)).map(t=>t.id)}function Se(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(Ja(e,s,n.id,t)),e),[])}}function Li(n){for(let t=0;t<n.length;t++){let e=n[t];e.index!==t&&(n[t]={...e,index:t})}}var Kt="data-aparte-host",gs=Symbol.for("aparte.instanceConfig");function to(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 eo(n,t){let e=n[gs]??k(n.parentElement);n[gs]=t,n.setAttribute(Kt,""),to(n,t,e)}function k(n){return n?.closest?.(`[${Kt}]`)?.[gs]??Q}var ie=null;function j(n,t){let e=ie;ie=n;try{return t()}finally{ie=e}}function C(n){return ie??k(n)}function V(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 I(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 M=I,qt="aparte-code-drawing",xi="aparte-code-pending",Mn="data-aparte-open",Ii="data-aparte-drawn",so=4*1024*1024,ms=class{entries=new Map;size=0;get(t){let e=this.entries.get(t);return e&&(this.entries.delete(t),this.entries.set(t,e)),e}set(t,e){let s=this.entries.get(t);s&&(this.size-=is(t,s),this.entries.delete(t));let i={html:e};this.entries.set(t,i),this.size+=is(t,i);for(let[r,a]of this.entries){if(this.size<=so||r===t)break;this.entries.delete(r),this.size-=is(r,a)}return i}},is=(n,t)=>n.length+(t.html?.length??0),tt=new WeakMap,Fs=new WeakMap,Tn=new WeakMap,Ln=new WeakMap,xn=new WeakMap,Ri=new WeakMap,Oi=new WeakMap,Pi=new WeakMap,In=new WeakSet,Rn=new WeakSet,rs=new WeakMap,On=new WeakMap,ee=new WeakMap;function no(n){let t=Tn.get(n);return t||(t=new ms,Tn.set(n,t)),t}function io(n){let t=Ln.get(n);return t||(t=new Map,Ln.set(n,t)),t}function Pn(n,t){let e=n.get(t);return e||(e=new Map,n.set(t,e)),e}function Ft(n,t){In.has(n)||(In.add(n),console.warn(`[aparte] The ${n.languages.join("/")} renderer failed; the source is shown instead.`,t))}function ro(n){for(let t of Array.from(n.classList))if(t.startsWith("language-"))return t.slice(9).toLowerCase()||null;return null}function ao(n){return n.classList.contains("math-display")?!0:n.classList.contains("math-inline")?!1:n.parentElement?.tagName==="PRE"}function oo(n){return n.hasAttribute(Mn)||n.parentElement?.tagName==="PRE"&&n.parentElement.hasAttribute(Mn)}function lo(n,t){let e="";try{e=n.cacheKey?.(t)??""}catch(s){Ft(n,s)}return`${t.language}${t.display?"d":"i"}${e}${t.source}`}function Ni(n){return typeof n?.then=="function"}function co(n){return n.closest("pre")??tt.get(n)?.drawing??n}function uo(n){return n.closest("pre")??n.parentElement??n}var as=new Set,os=new Map,ls=!1;function Ae(n,t){t?os.set(n,t):as.add(n),!ls&&(ls=!0,queueMicrotask(()=>{ls=!1;let e=[...as],s=[...os];as.clear(),os.clear();for(let i of e)po(i);for(let[i,r]of s)i.isConnected&&vt(i,r)}))}var Nn=new WeakMap;function ho(n,t,e){let s=Nn.get(n);if(!s){let i=new Map;Nn.set(n,i),s=i,n.then(()=>{for(let[r,a]of i)Ae(r,a);i.clear()},()=>i.clear())}(!s.has(t)||e===void 0)&&s.set(t,e)}var gt=null;function Di(n){for(let t=n.parentElement;t;t=t.parentElement){let e=getComputedStyle(t).overflowY;if(e==="auto"||e==="scroll")return t}return null}function po(n){if(!n.isConnected)return;let t=Di(n),e=t?t.getBoundingClientRect().top+(parseFloat(getComputedStyle(t).scrollPaddingTop)||0):0;gt={scroller:t,top:e};try{vt(n,Pi.get(n)??{})}finally{gt=null}}function fo(n,t){let e=co(n);if(Rn.has(e)||typeof IntersectionObserver>"u")return!1;let s=Di(e),i=On.get(IntersectionObserver);i||(i={byScroller:new WeakMap},On.set(IntersectionObserver,i));let r=s?i.byScroller.get(s):i.page;if(!r){let a=new IntersectionObserver(o=>{for(let l of o){let c=l.target;if(c.isConnected&&!l.isIntersecting)continue;a.unobserve(c);let d=(ee.get(a)??1)-1;if(ee.set(a,d),d<=0&&(a.disconnect(),s?i.byScroller.delete(s):i.page===a&&(i.page=void 0)),!c.isConnected)continue;Rn.add(c);let u=rs.get(c);u&&Ae(u)}},{root:s,rootMargin:"100% 0px"});r=a,s?i.byScroller.set(s,a):i.page=a}return rs.get(e)!==t&&(rs.set(e,t),ee.set(r,(ee.get(r)??0)+1),r.observe(e)),!0}function Dt(n,t,e,s,i,r,a=!0){if(e.html===null){Tt(t,i.open);return}let o=gt?uo(t):null,l=o?o.getBoundingClientRect():null,c=tt.get(t),d=c?.drawing;if(d||(d=document.createElement("span"),d.className=qt,i.display&&d.setAttribute("data-aparte-display",""),s.bare&&d.setAttribute("data-aparte-bare",""),t.after(d),Fs.set(d,t),t.parentElement?.tagName==="PRE"&&t.parentElement.setAttribute(Ii,"")),c?.entry!==e||d.childNodes.length===0){let u=a?xn.get(n):void 0;a&&!u&&(u=new WeakMap,xn.set(n,u));let h=u?.get(e);if(h&&h.owner!==t&&!h.owner.isConnected&&t.isConnected&&!h.drawing.isConnected&&h.drawing.childNodes.length>0)d.replaceChildren(...h.drawing.childNodes),h.drawing.remove(),Tt(h.owner,!1);else{d.innerHTML=e.html;try{s.relabel?.(d,i)}catch(_){Ft(s,_)}}u&&(c&&c.entry!==e&&u.get(c.entry)?.drawing===d&&u.delete(c.entry),u.set(e,{drawing:d,owner:t}))}if(t.hidden=!0,t.style.setProperty("display","none"),t.classList.remove(xi),tt.set(t,{renderer:s,key:r,drawing:d,entry:e,ctx:i}),o&&l&&gt){let u=o.getBoundingClientRect().height-l.height;u>0&&l.bottom<=gt.top&&(gt.scroller?gt.scroller.scrollTop+=u:window.scrollBy(0,u))}}function Tt(n,t){let e=tt.get(n);e&&(e.drawing.remove(),tt.delete(n)),n.parentElement?.tagName==="PRE"&&n.parentElement.removeAttribute(Ii),n.hidden=!1,n.style.removeProperty("display"),n.classList.toggle(xi,t)}function _o(n,t,e,s,i,r){let a=lo(e,s),o=tt.get(t);if(o&&o.renderer===e&&o.key===a&&o.drawing.childNodes.length>0)return;let l=no(e),c=l.get(a);if(c){Dt(n,t,c,e,s,a,!r);return}if(!o&&!r){let _=Ri.get(n)?.get(i);_&&s.source.startsWith(_.source)&&Dt(n,t,_,e,s,null),o=tt.get(t)}if(e.lazy&&!r&&!o&&fo(t,n))return;let d=io(e),u=d.get(a);if(u){ho(u,n,r);return}let h;try{h=e.render(s)}catch(_){Ft(e,_),h=null}if(!Ni(h)){Dt(n,t,l.set(a,h??null),e,s,a,!r);return}let f=h.then(_=>(d.delete(a),l.set(a,_??null),_),_=>{throw d.delete(a),Ft(e,_),_});d.set(a,f),f.then(()=>Ae(n,r),()=>{})}function go(n,t,e,s,i){let r=Pn(Ri,n),a=r.get(i);a&&s.source.startsWith(a.source)?tt.get(t)?.entry!==a&&Dt(n,t,a,e,s,null):(r.delete(i),Tt(t,!0));let o=Pn(Oi,n);if(o.get(i)===s.source)return;o.set(i,s.source);let l=()=>{o.get(i)===s.source&&o.delete(i)},c=u=>{if(u==null)return!1;let h=r.get(i);return h&&!s.source.startsWith(h.source)?!1:(r.set(i,{source:s.source,html:u}),!0)},d;try{d=e.render(s)}catch{d=null}if(!Ni(d)){c(d)?Dt(n,t,r.get(i),e,s,null):d==null&&l();return}d.then(u=>{c(u)?Ae(n):u==null&&l()},l)}function vt(n,t={}){if(typeof document>"u")return;let{streaming:e=!1,refresh:s=!1,language:i}=t;if(!s&&(Pi.set(n,{streaming:e}),e||Oi.delete(n),!C(n).hasCodeLanguageRenderer())){n.querySelector(`.${qt}`)&&Bi(n);return}let r=Array.from(n.querySelectorAll('code[class*="language-"]')).filter(o=>!o.closest(`.${qt}`)),a=new Map;r.forEach((o,l)=>{let c=ro(o);if(!c||i&&c!==i)return;let d=C(s?o:n),u=d.getCodeLanguageRenderer(c),h=tt.get(o);if(s&&(!h||h.key===null))return;if(!u){h&&Tt(o,!1);return}let f=ao(o),_=`${c}|${f?"d":"i"}`,p=a.get(_)??0;a.set(_,p+1);let m=`${_}|${p}`,T=o.textContent??"";if(!T.trim()){h&&Tt(o,!1);return}let L=e&&(oo(o)||l===r.length-1),R={language:c,source:T,display:f,open:L,host:o,config:d};L?go(n,o,u,R,m):_o(n,o,u,R,m,s?t:void 0)})}function Bi(n){for(let t of Array.from(n.querySelectorAll(`.${qt}`))){let e=Fs.get(t);e?Tt(e,!1):t.remove()}}function Hi(n){for(let t of Array.from(n.querySelectorAll(`.${qt}`))){let e=Fs.get(t),s=e?tt.get(e):void 0;if(s)try{s.renderer.relabel?.(t,s.ctx)}catch(i){Ft(s.renderer,i)}}}function bs(n,t){return!!n&&C(t).hasCodeLanguageRenderer(n)}var Us=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"]),mo=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"]),bo=new Set(["class","style","title","dir","lang","role","align","aria-label","aria-hidden","aria-describedby","aria-level"]),vo={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"])},yo=new Set(["href","src"]),wo=/^(?:https?:|mailto:|tel:|ftp:|sms:)/i,So=/^(?:[#/.?]|[a-z0-9._~%+-]+(?:[/?#]|$))/i,Ao=/^data:image\/(?:png|jpe?g|gif|webp|avif|bmp|x-icon|svg\+xml)[;,]/i,$i=/[\u0000-\u0020]+/g,Dn=/^(?:https?:)?[/\\]{2}|^https?:[/\\]/i,Co=/^aparte-/i;function Eo(n,t){let e=t==="source"?"img":t;for(let s of n.matchAll(/[a-z][a-z0-9+.-]*:[^\s,]*/gi))if(!Vt(s[0],e))return!1;return!0}function Vt(n,t){let e=n.replace($i,"");return!e||wo.test(e)||t==="img"&&Ao.test(e)?!0:/^[a-z][a-z0-9+.-]*:/i.test(e)?!1:So.test(e)}var ko=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 Mo(n){return n.includes("\\")?!1:n.startsWith("--")&&!n.startsWith("--aparte-")}function To(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()&&(!ko.has(r)&&!Mo(r)||a.includes("\\")||/url\s*\(|expression\s*\(|javascript:|vbscript:|[<>]/i.test(a)||t.push(s))}return t.length?t.join("; "):null}function Lo(n,t,e){let s=vo[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-")&&!bo.has(r)&&!(s&&s.has(r)))&&!(yo.has(r)&&!Vt(a,e))&&!(e==="input"&&r==="type"&&a.toLowerCase()!=="checkbox")&&!(r==="srcset"&&!Eo(a,e))){if(r==="style"){let o=To(a);if(o===null)continue;t.setAttribute("style",o);continue}if(r==="class"){let o=a.split(/\s+/).filter(l=>l&&!Co.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($i,""),r=(n.getAttribute("target")??"").trim().toLowerCase();r==="_self"&&!Dn.test(i)?t.setAttribute("target","_self"):(r||Dn.test(i))&&(t.setAttribute("target","_blank"),t.setAttribute("rel","noopener noreferrer"))}}function vs(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(Us.has(r))continue;if(!mo.has(r)){vs(i,t,e);continue}let a=e.createElement(r);Lo(i,a,r),vs(i,a,e),t.appendChild(a)}}var xo=new Set(["html","head","body"]),Io=Array.from(Us).join("|"),Ro=Array.from(Us).filter(n=>!xo.has(n)).join("|"),Oo=new RegExp(`<\\s*(${Ro})\\b[\\s\\S]*?<\\s*\\/\\s*\\1\\s*>`,"gi"),Po=new RegExp(`<\\s*\\/?\\s*(?:${Io})\\b[^>]*>`,"gi"),Bn=/["'/\s]on[a-z]+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi,No=/(?:href|src|xlink:href)\s*=\s*(?:"\s*(?:javascript|vbscript|data):[^"]*"|'\s*(?:javascript|vbscript|data):[^']*'|(?:javascript|vbscript|data):[^\s>]*)/gi;function Hn(n){let t=n.replace(Oo,"").replace(Po,"");for(let e=t.replace(Bn," ");e!==t;e=t.replace(Bn," "))t=e;return t.replace(No," ")}var ys=n=>{if(!n)return n;if(typeof DOMParser>"u")return Hn(n);let t;try{t=new DOMParser().parseFromString(n,"text/html")}catch{return Hn(n)}let e=t.createElement("div");return vs(t.body,e,t),e.innerHTML},nt="aparte-citation",qi="aparte-citation-marker",Fi=/[\p{L}\p{N}]/u,Do=[24,12,6],Ui=new Set(["A","ABBR","B","CITE","CODE","DEL","EM","I","INS","KBD","MARK","Q","S","SMALL","SPAN","STRONG","SUB","SUP","U"]),$n=/[.,;:!?)\]}»"'’”…。、,.!?:;」』)】》،؛؟]/,Bo=/[\u00a0\u202f]/,Ws=new WeakMap,Wi=new WeakMap,qn=new WeakSet,re=new WeakMap,ot=null;function js(n){let t=n.url?.trim();return t&&/^https?:\/\//i.test(t)&&Vt(t,"a")?t:void 0}function pe(n){let t=js(n);if(t)try{return new URL(t).hostname.replace(/^www\./,"")}catch{}return n.title??""}function Ho(n){let t=pe(n[0])||"?";return n.length>1?`${t} +${n.length-1}`:t}function ws(n,t){let e=n.getLocale();return t===1?e.sourcesOne??"1 source":(e.sourcesCount??"{n} sources").replace("{n}",()=>String(t))}function $o(n){if(typeof document>"u")return"";let t=document.createElement("textarea");return t.innerHTML=n,t.value}function Fn(n){return n.replace(/^[ \t]*(?:>[ \t]*)*(?:\d{1,9}[.)]|[*+-])[ \t]+(?:\[[ xX]\][ \t]+)?/gm,"").replace(/<!--[\s\S]*?-->/g,"").replace(/!\[[^\]\n]*\]\([^)\n]*\)/g,"").replace(/<([a-z][a-z0-9+.-]*:[^>\s]+)>/gi,"$1").replace(/\]\([^)\n]*\)/g,"]").replace(/<\/?[A-Za-z][^>\n]*>/g,"").replace(/&(?:#\d+|#x[0-9a-f]+|[a-z][a-z0-9]*);/gi,$o)}function qo(n){let t=n.replace(/^ {0,3}(?:`{3,}|~{3,})[^\n]*$/gm,""),e="",s=0;for(let r of t.matchAll(/(`+)([^`][\s\S]*?)\1/g))e+=Fn(t.slice(s,r.index))+r[2],s=(r.index??0)+r[0].length;e+=Fn(t.slice(s));let i="";for(let r of e)Fi.test(r)&&(i+=r);return i}function Fo(n){let t="",e=[],s=n.ownerDocument.createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode:i=>i.parentElement?.closest(`.aparte-code-drawing, .${nt}`)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT});for(let i=s.nextNode();i;i=s.nextNode()){let r=i.data;for(let a=0;a<r.length;){let o=(r.codePointAt(a)??0)>65535?2:1,l=r.slice(a,a+o);if(a+=o,!!Fi.test(l)){t+=l;for(let c=0;c<o;c++)e.push([i,a])}}}return{text:t,ends:e}}function Uo(n,t){let e=0;for(let s=n.indexOf(t);s>=0;s=n.indexOf(t,s+1))e++;return e}function Wo(n,t,e){let s=qo(n.slice(0,Math.max(0,Math.min(n.length,t.end))));if(!s)return null;for(let i of Do){let r=s.slice(-i),a=Uo(s,r),o=-1;for(let l=0;l<a&&(l===0||o>=0);l++)o=e.text.indexOf(r,o+1);if(o>=0)return e.ends[o+r.length-1]??null;if(r.length===s.length)break}return null}function Un(n,t){let e=t;for(;e<n.length&&($n.test(n[e])||Bo.test(n[e])&&$n.test(n[e+1]??""));)e++;return e-t}function jo(n,t,e,s){let i=e.parentElement?.closest("pre");if(i&&n.contains(i)){i.after(t);return}let r=null;for(let l=e.parentElement;l&&l!==n&&Ui.has(l.tagName);l=l.parentElement)r=l;if(!r){e.splitText(s+Un(e.data,s)),e.after(t);return}let a=r;for(;a.nextSibling instanceof Element&&a.nextSibling.classList.contains("aparte-code-drawing");)a=a.nextSibling;let o=a.nextSibling;if(o instanceof Text){let l=Un(o.data,0);l>0&&(o.splitText(l),a=o)}a.parentNode.insertBefore(t,a.nextSibling)}function Go(n,t,e,s){let i=l=>{let c=document.createElement("span");c.className=qi,c.hidden=!0,l.parentNode.insertBefore(c,l),c.append(l),c.after(n)},r=t.data.lastIndexOf(s,e);if(r>=0&&r+s.length>=e){let l=t.splitText(r);return l.splitText(s.length),i(l),!0}let a=t.parentElement,o=s.replace(/^\[|\]$/g,"");return a&&Ui.has(a.tagName)&&a.textContent?.trim()===o?(i(a),!0):!1}function zo(n,t){let e=document.createElement("button");return e.type="button",e.className="aparte-citation aparte-tag aparte-tag--sm",e.setAttribute("aria-haspopup","dialog"),e.setAttribute("aria-expanded","false"),Ws.set(e,n),ji(e,t),e}function ji(n,t){let e=Ws.get(n)??[],s=Ho(e);n.dataset.label=s,n.setAttribute("aria-label",`${s}, ${ws(t,e.length)}`)}function Gi(n){let t=new Set;for(let e of Array.from(n.querySelectorAll(`.${nt}`)))e.parentNode&&t.add(e.parentNode),e.remove();for(let e of Array.from(n.querySelectorAll(`.${qi}`)))e.parentNode&&t.add(e.parentNode),e.replaceWith(...Array.from(e.childNodes));for(let e of t)e.normalize();re.delete(n)}function Ss(n,t){if(typeof document>"u")return;let e=t.citations??[],s=new Map((t.sources??[]).map(p=>[p.id,p])),i=JSON.stringify([t.content,e,[...s.values()].map(p=>[p.id,p.url,p.title,p.snippet])]),r=Array.from(n.querySelectorAll(`.${nt}`)),a=re.get(n);if(a&&a.signature===i&&a.count===r.length)return;let o=document.activeElement,l=ot?.root===n&&(o===ot.chip||(!o||o===document.body)&&!ot.chip.isConnected)?ot.at:-1,c=N?.root===n?N.chip.isConnected?r.indexOf(N.chip):N.at:-1;if(Gi(n),e.length===0||s.size===0){re.set(n,{signature:i,count:0}),c>=0&&X(!1);return}let d=C(n);qn.has(n)||(qn.add(n),n.addEventListener("click",p=>{let m=p.target?.closest?.(`.${nt}`);!m||!n.contains(m)||(p.preventDefault(),Vo(m))}),n.addEventListener("focusin",p=>{let m=p.target;m.classList?.contains(nt)&&(ot={root:n,chip:m,at:Array.from(n.querySelectorAll(`.${nt}`)).indexOf(m)})}),n.addEventListener("focusout",p=>{ot?.root===n&&p.relatedTarget&&(ot=null)}));let u=Fo(n),h=new Map;for(let p of e){let m=p.sources.map(y=>s.get(y)).filter(y=>!!y);if(m.length===0)continue;let T=Wo(t.content,p,u);if(!T)continue;let L=u.ends.indexOf(T),R=p.marker&&p.start!==void 0?t.content.slice(p.start,p.end):null,b=h.get(L)??{node:T[0],offset:T[1],marker:R,sources:[]};for(let y of m)b.sources.includes(y)||b.sources.push(y);h.set(L,b)}let f=[...h.values()].sort((p,m)=>p.node===m.node?m.offset-p.offset:p.node.compareDocumentPosition(m.node)&Node.DOCUMENT_POSITION_FOLLOWING?1:-1);for(let p of f){let m=zo(p.sources,d);Wi.set(m,n),!(p.marker&&Go(m,p.node,p.offset,p.marker))&&jo(n,m,p.node,p.offset)}let _=Array.from(n.querySelectorAll(`.${nt}`));if(re.set(n,{signature:i,count:_.length}),l>=0&&(_[l]?_[l].focus({preventScroll:!0}):ot=null),c>=0&&N){let p=_[c];p?(N.chip=p,N.at=c,p.setAttribute("aria-expanded","true"),p.setAttribute("aria-controls",N.el.id)):X(!1)}}function zi(n){let t=C(n);for(let e of Array.from(n.querySelectorAll(`.${nt}`)))ji(e,t)}var N=null,Ko=0;function Vo(n){N?.chip===n?X(!0):Yo(n)}function Yo(n){X(!1);let t=Ws.get(n)??[];if(t.length===0)return;let e=Wi.get(n)??n.parentElement,s=Array.from(e.querySelectorAll(`.${nt}`)).indexOf(n),i=C(n),r=document.createElement("div");r.className="aparte-citation-card aparte-popover",r.id=`aparte-citation-card-${++Ko}`,r.setAttribute("role","dialog"),r.setAttribute("aria-label",i.getLocale().sourcesCard??"Sources");let a=document.createElement("div");a.className="aparte-citation-card__body";let o=document.createElement("p");o.className="aparte-sr-only",o.setAttribute("role","status"),r.append(a,o);let l=typeof r.showPopover=="function";l&&(r.popover="manual"),(n.closest("aparte-chat-viewport")?.parentElement??n.ownerDocument.body).append(r),l&&r.showPopover(),n.setAttribute("aria-expanded","true"),n.setAttribute("aria-controls",r.id);let c=typeof MutationObserver=="function"?new MutationObserver(Jo):null;c?.observe(n.ownerDocument.body,{childList:!0,subtree:!0}),N={root:e,chip:n,at:s,el:r,body:a,status:o,sources:t,index:0,config:i,watch:c},Qi(),Ut(),document.addEventListener("keydown",Ki,!0),document.addEventListener("pointerdown",Vi,!0),window.addEventListener("scroll",Yi,!0),window.addEventListener("resize",Ut),r.addEventListener("focusout",Zo),r.addEventListener("keydown",Xo),Qo(r)}function Qo(n){(n.querySelector("a")??n.querySelector("button:not([disabled])"))?.focus()}function X(n){if(!N)return;let{chip:t,el:e,watch:s}=N;N=null,s?.disconnect(),e.remove(),t.setAttribute("aria-expanded","false"),t.removeAttribute("aria-controls"),document.removeEventListener("keydown",Ki,!0),document.removeEventListener("pointerdown",Vi,!0),window.removeEventListener("scroll",Yi,!0),window.removeEventListener("resize",Ut),n&&t.isConnected&&t.focus()}function Jo(){N&&!N.chip.isConnected&&X(!1)}function Ki(n){n.key!=="Escape"||!N||(n.preventDefault(),X(!0))}function Xo(n){if(n.key!=="Tab"||!N)return;let t=Array.from(N.el.querySelectorAll("a[href], button:not([disabled])")),e=n.shiftKey?t[0]:t[t.length-1];document.activeElement===e&&(n.preventDefault(),X(!0))}function Vi(n){if(!N)return;let t=n.target;t&&(N.el.contains(t)||N.chip.contains(t))||X(!1)}function Zo(n){if(!N)return;let t=n.relatedTarget;t&&(N.el.contains(t)||N.chip.contains(t))||t&&X(!1)}function tl(n){for(let t=n.parentElement;t;t=t.parentElement){let e=getComputedStyle(t).overflowY;if(e==="auto"||e==="scroll")return t}return null}function Yi(){if(!N)return;let n=tl(N.chip);if(n){let t=n.getBoundingClientRect(),e=N.chip.getBoundingClientRect();if(e.bottom<t.top||e.top>t.bottom){X(!1);return}}Ut()}function Ut(){if(!N)return;let{chip:n,el:t}=N;if(!n.isConnected){X(!1);return}let e=n.getBoundingClientRect();t.style.left="0px",t.style.top="0px";let s=t.getBoundingClientRect(),i=6,a=getComputedStyle(n).direction==="rtl"?e.right-t.offsetWidth:e.left,o=Math.max(8,Math.min(a,window.innerWidth-t.offsetWidth-8)),l=e.bottom+i;l+t.offsetHeight>window.innerHeight-8&&e.top-t.offsetHeight-i>8&&(l=e.top-t.offsetHeight-i),t.style.left=`${o-s.left}px`,t.style.top=`${l-s.top}px`}function Qi(){if(!N)return;let{el:n,body:t,status:e,sources:s,index:i,config:r}=N,a=r.getLocale(),o=s[i],l=n.contains(document.activeElement)?document.activeElement.dataset.aparteCardPart:void 0;if(t.replaceChildren(),s.length>1){let h=document.createElement("div");h.className="aparte-citation-card__pager";let f=Wn(a.sourcePrevious??"Previous source",r.getIcon("prevBranch"),"prev",i===0,()=>jn(-1)),_=document.createElement("span");_.className="aparte-citation-card__position",_.textContent=`${i+1}/${s.length}`,_.setAttribute("aria-hidden","true");let p=Wn(a.sourceNext??"Next source",r.getIcon("nextBranch"),"next",i===s.length-1,()=>jn(1));h.append(f,_,p),t.append(h)}let c=js(o),d=o.title||pe(o)||o.url||"";if(c){let h=document.createElement("a");h.className="aparte-citation-card__title",h.href=c,h.target="_blank",h.rel="noopener noreferrer",h.dataset.aparteCardPart="link",h.textContent=d;let f=document.createElement("span");f.className="aparte-sr-only",f.textContent=` ${a.opensInNewTab??"(opens in a new tab)"}`,h.append(f),t.append(h)}else{let h=document.createElement("p");h.className="aparte-citation-card__title",h.textContent=d,t.append(h)}let u=pe(o);if(u&&u!==d){let h=document.createElement("p");h.className="aparte-citation-card__domain",h.textContent=u,t.append(h)}if(o.snippet){let h=document.createElement("p");h.className="aparte-citation-card__snippet",h.textContent=o.snippet,t.append(h)}if(s.length>1&&(e.textContent=(a.sourcePosition??"Source {i} of {n}").replace("{i}",()=>String(i+1)).replace("{n}",()=>String(s.length))),l){let h=n.querySelector(`[data-aparte-card-part="${l}"]`);h&&!h.disabled?h.focus():(n.querySelector(".aparte-citation-card__pager button:not([disabled])")??n.querySelector("a"))?.focus()}}function Wn(n,t,e,s,i){let r=document.createElement("button");return r.type="button",r.className="aparte-btn aparte-btn--icon aparte-btn--sm",r.setAttribute("aria-label",n),r.dataset.aparteCardPart=e,r.disabled=s,r.innerHTML=t,r.addEventListener("click",i),r}function jn(n){N&&(N.index=Math.max(0,Math.min(N.sources.length-1,N.index+n)),Qi(),Ut())}function Ji(n,t,e,s){let i=n.querySelector(":scope > .aparte-sources"),r=[],a=new Set;for(let u of e){let h=u.url??`#${u.id}${u.title??""}`;a.has(h)||(a.add(h),r.push(u))}if(r.length===0){i?.remove();return}let o=s.getLocale().opensInNewTab??"(opens in a new tab)",l=[o,...r.map(u=>`${u.url??u.id}${u.title??""}`)].join("");if(!i)i=document.createElement("details"),i.className="aparte-sources",t.after(i);else if(i.dataset.aparteKey===l){i.querySelector("summary").textContent=ws(s,r.length);return}i.dataset.aparteKey=l;let c=document.createElement("summary");c.className="aparte-sources__summary",c.textContent=ws(s,r.length);let d=document.createElement("ol");d.className="aparte-sources__list";for(let u of r){let h=document.createElement("li");h.className="aparte-sources__item";let f=pe(u),_=u.title||f||u.url||"",p=js(u);if(p){let m=document.createElement("a");m.href=p,m.target="_blank",m.rel="noopener noreferrer",m.textContent=_;let T=document.createElement("span");T.className="aparte-sr-only",T.textContent=` ${o}`,m.append(T),h.append(m)}else h.append(_);if(f&&f!==_){let m=document.createElement("span");m.className="aparte-sources__domain",m.textContent=f,h.append(" ",m)}d.append(h)}i.replaceChildren(c,d)}var It=new WeakMap,Gn="<i>a</i>";function zn(){return C().renderMarkdown(Gn)!==I(Gn)}function Ce(n,t,e,s){el(n,t,e,s),vt(t,{streaming:s})}function el(n,t,e,s){let i=C();if(s){if(It.delete(t),n._aparteSmd===void 0){let a=C().createStreamingMarkdownRenderer(t);a?(t.textContent="",n._aparteSmd={renderer:a,written:0}):n._aparteSmd=null}let r=n._aparteSmd;if(r){let a=e.slice(r.written);a&&(r.renderer.write(a),r.written=e.length);return}}else if(n._aparteSmd){let r=n._aparteSmd,a=e.slice(r.written);if(a&&(r.renderer.write(a),r.written=e.length),r.renderer.end(),n._aparteSmd=void 0,!zn()){Bi(t),Gi(t),t.innerHTML=i.sanitizeHtml(t.innerHTML),It.set(t,{content:e,config:i,version:J(i),writer:"parser"});return}}else{let r=It.get(t);if(r?.content===e&&(r.writer==="parser"&&!zn()||r.writer==="markdown"&&r.config===i&&r.version===J(i)))return}t.innerHTML=i.renderMarkdown(e),s?It.delete(t):It.set(t,{content:e,config:i,version:J(i),writer:"markdown"})}function As(n){if(!C().hasHighlightProvider())return;let t=n.querySelectorAll("pre > code:not([data-aparte-highlighted])");for(let e of t){let s=e.parentElement;if(!s)continue;let i=Array.from(e.classList).find(a=>a.startsWith("language-"))?.slice(9)??"";if(bs(i,n)||e.closest(".aparte-code-drawing"))continue;let r=e.textContent??"";e.setAttribute("data-aparte-highlighted",""),C().highlightCode(r,i,{fallback:!1}).then(a=>{(s.isConnected||s.parentElement)&&Gs(s,a)}).catch(()=>e.removeAttribute("data-aparte-highlighted"))}}function Gs(n,t){let e=document.createElement("template");e.innerHTML=t;for(let s of Array.from(e.content.querySelectorAll("code")))s.setAttribute("data-aparte-highlighted","");n.replaceWith(e.content)}var sl={type:"text",render:n=>`<div class="aparte-segment aparte-segment-text" data-segment-id="${I(n.id)}"><div class="aparte-segment-content">${C().renderMarkdown(n.content)}</div></div>`,setup:(n,t)=>{let e=n.querySelector(".aparte-segment-content");e&&(vt(e,{streaming:t.isStreaming===!0}),t.isStreaming!==!0&&As(e),Ss(e,t))},update:(n,t)=>{let e=n.querySelector(".aparte-segment-content");e&&(Ce(n,e,t.content,t.isStreaming!==!1),t.isStreaming===!1&&As(e),Ss(e,t))},getStyles:()=>""};function nl(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 il=24;function Cs(n){if(n.label&&n.label!=="Thinking")return n.label;let t=C();if(!bt(n))return t.t("thinking");let s=n.showDuration??t.getSegmentDefaults("thinking")?.showDuration===!0?ki(n):void 0;return s===void 0?t.t("thought"):t.t("thoughtFor").replace("{duration}",()=>nl(s,t.getLocale().tag||void 0))}var Es=n=>n.isStreaming===!0;function Kn(n,t){let e=Cs(t),s=n.querySelector(".aparte-thinking-label");s&&s.textContent!==e&&(s.textContent=e),s?.classList.toggle("aparte-shimmer",Es(t)),n.querySelector(".aparte-thinking-content")?.setAttribute("aria-label",e)}var rl={type:"thinking",render:n=>`<details class="aparte-segment aparte-segment-thinking aparte-accordion__item" data-segment-id="${I(n.id)}" ${n.collapsed===!1?"open":""}><summary class="aparte-accordion__header aparte-thinking-header"><span class="aparte-thinking-label${M(Es(n)?" aparte-shimmer":"")}">${I(Cs(n))}</span><span class="aparte-accordion__icon">${C().getIcon("expand")}</span></summary><div class="aparte-accordion__panel aparte-thinking-content" role="region" tabindex="0" aria-label="${M(Cs(n))}">${C().renderMarkdown(n.content)}</div></details>`,relabel:(n,t)=>Kn(n,t),setup:(n,t)=>{let e=n.querySelector(".aparte-thinking-content");e&&vt(e,{streaming:Es(t)})},update:(n,t)=>{Kn(n,t);let e=n.querySelector(".aparte-thinking-content");if(!e)return;let s=e.scrollHeight-e.scrollTop-e.clientHeight<=il,i=t.isStreaming!==!1;Ce(n,e,t.content,i),i||As(e),s&&(e.scrollTop=e.scrollHeight)},getStyles:()=>""};function zs(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 al=1500;function ks(n,t){n.setAttribute("aria-label",t),n.setAttribute("title",t)}function Ks(n){let t=M(C().t("copy")),e=C().getIcon("copy");return`<button type="button" class="aparte-btn aparte-btn--icon aparte-btn--sm ${M(n)}" data-action="copy" aria-label="${t}" title="${t}">${e}</button>`}function Xi(n,t){n.addEventListener("click",()=>{zs(t()).catch(()=>{}),n.innerHTML=C(n).getIcon("check"),ks(n,C(n).t("copied")),n.dataset.copied="1",setTimeout(()=>{n.innerHTML=C(n).getIcon("copy"),ks(n,C(n).t("copy")),delete n.dataset.copied},al)})}function Zi(n){n.dataset.copied||(ks(n,C().t("copy")),n.innerHTML=C().getIcon("copy"))}var ol=400,ll=256,Vn=new Map;function cl(n,t,e){if(n.delete(t),n.size>=ll){let s=n.keys().next().value;s!==void 0&&n.delete(s)}n.set(t,e)}function Yn(n){let t=Number(n.dataset.aparteHlLen);return Number.isFinite(t)&&t>0?t:0}function dl(n,t,e,s,i){let r=n.querySelector(t);if(!r)return;delete r.dataset.aparteSettled;let a=r.querySelector("[data-aparte-tail]"),o=Yn(r);if(a&&o<=e.length)a.textContent=e.slice(o);else{delete r.dataset.aparteHlLen;let d=r.querySelector("code");d?d.textContent=e:r.innerHTML=`<pre><code class="language-${I(s||"text")}">${I(e)}</code></pre>`}let l=e.lastIndexOf(`
5
- `)+1;if(l<=o)return;let c=Date.now();c-(Vn.get(i)??0)<ol||(cl(Vn,i,c),C(n).highlightCode(e.slice(0,l),s).then(d=>{let u=n.querySelector(t);if(!u||u.dataset.aparteSettled!==void 0||l<=Yn(u))return;u.innerHTML=d;let h=u.querySelector("code")??u,f=document.createElement("span");f.dataset.aparteTail="",f.textContent=e.slice(l),h.appendChild(f),u.dataset.aparteHlLen=String(l)}).catch(()=>{}))}var cs=new WeakMap,Et=new WeakMap,ds=new WeakMap;function Qn(n,t){let e=n.querySelector(".aparte-code-content-wrapper");if(!e)return;let s=`${t.language??""}${t.content}`,i=C(),r=ds.get(n);if(r?.what===s&&r.config===i)return;ds.set(n,{what:s,config:i});let a=(Et.get(n)??0)+1;Et.set(n,a),e.dataset.aparteSettled="",i.highlightCode(t.content,t.language||"",{fallback:!1}).then(o=>{Et.get(n)===a&&(e.innerHTML=o)}).catch(()=>{Et.get(n)===a&&ds.delete(n)})}var fe=n=>(n.language||"").trim().split(/\s+/)[0]??"";function Jn(n,t){let e=fe(t);n.toggleAttribute("data-aparte-bare",!!e&&C(n).getCodeLanguageRenderer(e)?.bare===!0)}function Xn(n,t){let e=n.querySelector(".aparte-code-content-wrapper");if(!e)return;Et.set(n,(Et.get(n)??0)+1),e.dataset.aparteSettled="";let s=fe(t),i=Array.from(e.querySelectorAll("pre > code")).find(r=>r.classList.contains(`language-${s}`));i||(e.innerHTML=`<pre><code class="language-${I(s)}"></code></pre>`,i=e.querySelector("pre > code")),i.textContent!==t.content&&(i.textContent=t.content),vt(e,{streaming:t.isStreaming===!0})}var ul={type:"code",render:n=>{let t=Ks("aparte-code-copy");return`
6
- <div class="aparte-segment aparte-segment-code" data-segment-id="${I(n.id)}">
7
- <div class="aparte-code-header">
8
- ${n.filename?`<span class="aparte-code-filename">${I(n.filename)}</span>`:'<span class="aparte-code-header-filler"></span>'}
9
- <span class="aparte-code-language">${I(n.language||"")}</span>
10
- ${t}
11
- </div>
12
- <div class="aparte-code-content-wrapper">
13
- <pre><code class="language-${I(n.language||"text")}">${I(n.content)}</code></pre>
14
- </div>
15
- </div>
16
- `},relabel:n=>{let t=n.querySelector(".aparte-code-copy");t&&Zi(t)},setup:(n,t)=>{cs.set(n,t.content),Jn(n,t),bs(fe(t),n)?Xn(n,t):t.isStreaming!==!0&&Qn(n,t);let e=n.querySelector(".aparte-code-copy");e&&Xi(e,()=>cs.get(n)??"")},update:(n,t)=>{cs.set(n,t.content),Jn(n,t),bs(fe(t),n)?Xn(n,t):t.isStreaming===!0?dl(n,".aparte-code-content-wrapper",t.content,t.language||"",t.id):Qn(n,t)},getStyles:()=>""};function Ms(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 hl={type:"error",render:n=>{let t=C(),e=Ms(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`
17
- <div class="aparte-segment aparte-alert aparte-alert--danger aparte-segment-error" data-segment-id="${I(n.id)}"${n.code?` data-error-code="${M(n.code)}"`:""}>
18
- <span class="aparte-alert__icon">${t.getIcon("error")||"\u26A0"}</span>
19
- <div class="aparte-alert__body">
20
- <div class="aparte-alert__title">${I(t.t("error"))}</div>
21
- <div class="aparte-alert__message">${I(i)}</div>
22
- ${n.details?`<pre class="aparte-segment-error__details">${I(n.details)}</pre>`:""}
23
- </div>
24
- </div>
25
- `},relabel:(n,t)=>{let e=C();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=Ms(t.code,o=>e.t(o)),a=n.querySelector(".aparte-alert__message");a&&r!==void 0&&(a.textContent=r)},getStyles:()=>""};function tr(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 er(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 sr(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 nr(n){return tr(n.toolCall?.input,C().getToolInputFormatter(n.toolCall?.name??""))}function Ts(n){let t=C(),e=n.status??"pending",s=i=>I(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 ir(n){let t=C();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 Ls(n){let t=_l(n.result??"");return!t||n.status==="rejected"&&n.refusal?null:{key:"toolOutput",text:t}}function us(n){let t=C().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"?C().sanitizeHtml(e):e}:{kind:"none"}}catch{return{kind:"none"}}}var Zn=n=>n.querySelector(':scope > .aparte-tool-detail[data-details="app"]');function rr(n,t){let e=n.querySelector(".aparte-tool-detail");e&&(typeof t=="string"?e.innerHTML=t:e.replaceChildren(t),ae.set(e,ar(t)))}var ae=new WeakMap,ar=n=>typeof n=="string"?n:n.outerHTML;function pl(n,t){if(typeof t!="string"&&n.contains(t)){ae.set(n,t.outerHTML);return}let e=ae.get(n),s=ar(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&&xs(r,i)&&xs(r,n)?or(n,r,i):n.replaceChildren(...Array.from(i.childNodes)),ae.set(n,s)}function xs(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||!xs(s,i))return!1}return!0}function or(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);or(i,r,a)}else r.nodeValue!==a.nodeValue&&(i.nodeValue=a.nodeValue)}}function ti(n,t){let e=n.querySelector(".aparte-tool-note");if(!e)return;let s=ir(t);e.textContent!==s&&(e.textContent=s),e.toggleAttribute("hidden",!s),s?e.setAttribute("title",s):e.removeAttribute("title")}function ei(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 p=i.querySelector(".aparte-tool-part-label"),m=C().t(s);p&&p.textContent!==m&&(p.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=C(),o=document.createElement("div");o.className="aparte-tool-part",o.dataset.part=t;let l=document.createElement("div");l.className="aparte-tool-part-head";let c=document.createElement("span");c.className="aparte-tool-part-label",c.textContent=a.t(s);let d=document.createElement("template");d.innerHTML=Ks("aparte-tool-copy"),l.append(c,d.content);let u=document.createElement("div");u.className="aparte-tool-part-body",u.setAttribute("role","region"),u.tabIndex=0,u.setAttribute("aria-label",c.textContent);let h=document.createElement("pre"),f=document.createElement("code");f.textContent=e,h.appendChild(f),u.appendChild(h),o.append(l,u),t==="input"?r.prepend(o):r.appendChild(o),lr(o)}function lr(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");Xi(t,()=>e?.querySelector(".aparte-tool-part-body")?.textContent??"")}}var fl=2e5;function cr(n){let t=n.trim();if(!(t.length>fl||!(t.startsWith("{")||t.startsWith("["))))try{let e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}}function _l(n){let t=cr(n);return t===void 0?n:JSON.stringify(t,null,2)}function si(n){let t=C();for(let e of n.querySelectorAll(".aparte-tool-part-body")){let s=e.querySelector("code")?.textContent??"";!s||cr(s)===void 0||t.highlightCode(s,"json").then(i=>{(e.querySelector("code")?.textContent??"")===s&&(e.innerHTML=i)}).catch(()=>{})}}function dr(n){return sr(n,C())}function ni(n,t){let e=n.querySelector(".aparte-tool-target");if(!e)return;let s=dr(t);e.textContent!==s&&(e.textContent=s),e.toggleAttribute("hidden",!s)}function ur(n){return er(n,C())}function hr(n){let t=C(),e=t.getToolDisplay(n.toolCall?.name??"")?.icon;return(e?t.getIcon(e):void 0)||t.getIcon("tool")}var Vs=n=>C().getToolDisplay(n.toolCall?.name??"")?.quiet??!0;function pr(n){let t=n.status??"pending",e=Vs(n);return{shimmer:e&&t==="pending",spinner:!e&&t==="pending",stateHidden:e&&(t==="pending"||t==="resolved")}}function ii(n,t){let e=pr(t);n.toggleAttribute("data-quiet",Vs(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 ri(n,t){let e=n.querySelector(".aparte-tool-name");if(!e)return;let{text:s,isLabel:i}=ur(t);e.textContent!==s&&(e.textContent=s),e.classList.toggle("aparte-tool-name--label",i)}function gl(n){let t=Ts(n),e=hr(n),s=dr(n),i=ir(n),r=ur(n),a=pr(n);return`
26
- <span class="aparte-tool-label">
27
- <span class="aparte-tool-icon">${e}</span>
28
- <span class="aparte-tool-name${r.isLabel?" aparte-tool-name--label":""}${a.shimmer?" aparte-shimmer":""}">${I(r.text)}</span>
29
- <span class="aparte-tool-target"${s?"":" hidden"}>${I(s)}</span>
30
- </span>
31
- <span class="aparte-spinner aparte-tool-spinner" aria-hidden="true"${a.spinner?"":" hidden"}></span>
32
- <span class="aparte-tool-state${a.stateHidden?" aparte-sr-only":""}">${t}</span>
33
- <span class="aparte-tool-note"${i?` title="${M(i)}"`:" hidden"}>${I(i)}</span>`}function ai(n){return`<div class="aparte-segment aparte-segment-tool-call" data-segment-id="${I(n.id)}" data-status="${M(n.status??"pending")}" data-tool-call-id="${M(n.toolCall?.id??"")}" data-tool-name="${M(n.toolCall?.name??"tool")}" hidden></div>`}var St=n=>n.hidden&&n.classList.contains("aparte-segment-tool-call")&&n.childElementCount===0,Pt=new WeakMap,oe=new WeakMap;function Ys(n){return oe.get(n)??null}function oi(n,t){let e=Pt.get(n);return e||(n.classList.contains("aparte-segment-tool-call")?null:t)}function li(n,t){let e=n.toolCall?.name??"tool",s=n.status??"pending",i=n.toolCall?.id??"",r=gl(n),a=Vs(n)?" data-quiet":"",o=C().getIcon("expand"),l=t.kind==="parts"?nr(n):"",c=t.kind==="parts"?Ls(n):null;if(t.kind==="none"||t.kind==="parts"&&!l&&!c)return`
34
- <div class="aparte-segment aparte-segment-tool-call" data-segment-id="${I(n.id)}" data-status="${M(s)}" data-tool-call-id="${M(i)}" data-tool-name="${M(e)}"${a}><div class="aparte-tool-line">${r}</div>
35
- </div>
36
- `;let d=C(),u=Ks("aparte-tool-copy"),h=n.collapsed!==void 0?!n.collapsed:d.getToolDisplay(e)?.open===!0;if(t.kind==="body"){let f=document.createElement("template");f.innerHTML=`
37
- <details class="aparte-segment aparte-segment-tool-call" data-segment-id="${I(n.id)}" data-status="${M(s)}" data-tool-call-id="${M(i)}" data-tool-name="${M(e)}"${a}${h?" open":""}>
38
- <summary class="aparte-tool-summary"><span class="aparte-tool-toggle">${o}</span>${r}</summary>
39
- <div class="aparte-tool-detail" data-details="app"></div>
40
- </details>`.trim();let _=f.content.firstElementChild;return rr(_,t.body),_}return`
41
- <details class="aparte-segment aparte-segment-tool-call" data-segment-id="${I(n.id)}" data-status="${M(s)}" data-tool-call-id="${M(i)}" data-tool-name="${M(e)}"${a}${h?" open":""}>
42
- <summary class="aparte-tool-summary"><span class="aparte-tool-toggle">${o}</span>${r}</summary>
43
- <div class="aparte-tool-detail">
44
- ${l?`
45
- <div class="aparte-tool-part" data-part="input">
46
- <div class="aparte-tool-part-head"><span class="aparte-tool-part-label">${I(d.t("toolInput"))}</span>${u}</div>
47
- <div class="aparte-tool-part-body" role="region" tabindex="0" aria-label="${M(d.t("toolInput"))}"><pre><code>${I(l)}</code></pre></div>
48
- </div>`:""}
49
- ${c?`
50
- <div class="aparte-tool-part" data-part="output">
51
- <div class="aparte-tool-part-head"><span class="aparte-tool-part-label">${I(d.t(c.key))}</span>${u}</div>
52
- <div class="aparte-tool-part-body" role="region" tabindex="0" aria-label="${M(d.t(c.key))}"><pre><code>${I(c.text)}</code></pre></div>
53
- </div>`:""}
54
- </div>
55
- </details>
56
- `}var kt={type:"tool_call",render:n=>{let t=n.toolCall?.name??"tool";if(C().isToolHidden(t))return ai(n);let e=C().getToolRenderer(t);if(e){br(t,e);let s=e.render(n);return s instanceof HTMLElement&&(Pt.set(s,e),oe.set(s,e)),s||ai(n)}return li(n,us(n))},relabel:(n,t)=>{if(St(n))return;let e=C(),s=oi(n,e.getToolRenderer(t.toolCall?.name)??null);if(s){s.relabel?.(n,t);return}let i=n.querySelector(".aparte-tool-icon");i&&(i.innerHTML=hr(t)),ri(n,t),ni(n,t),ti(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=Ls(t),o=n.querySelector('[data-part="output"] .aparte-tool-part-label');o&&a&&(o.textContent=e.t(a.key)),a&&n.querySelector('[data-part="output"] .aparte-tool-part-body')?.setAttribute("aria-label",e.t(a.key));for(let d of n.querySelectorAll(".aparte-tool-copy"))Zi(d);let l=Zn(n);if(l){let d=us(t);d.kind==="body"&&pl(l,d.body)}let c=n.querySelector(".aparte-tool-state");c&&(c.innerHTML=Ts(t)),ii(n,t)},update:(n,t)=>{let e=t.status??"pending",s=C().isToolHidden(t.toolCall?.name??"tool");if(s&&St(n)){n.setAttribute("data-status",e);return}let i=s?null:C().getToolRenderer(t.toolCall?.name)??null,r=St(n)?null:oi(n,i);if(r&&r===i&&r.update&&!St(n)){r.update(n,t);return}let a=f=>{let _=document.createElement("template");_.innerHTML=typeof f=="string"?f.trim():"";let p=typeof f=="string"?_.content.firstElementChild:f;p&&(p.hasAttribute("data-segment-id")||p.setAttribute("data-segment-id",t.id),kt.cleanup?.(n,t),n.replaceWith(p),kt.setup?.(p,t))};if(i||r||s||St(n)){a(kt.render(t));return}let o=us(t),l=o.kind==="parts"?nr(t):"",c=o.kind==="parts"?Ls(t):null,d=o.kind==="body"||!!l||!!c,u=!!Zn(n);if(d!==(n.tagName==="DETAILS")||d&&o.kind==="body"!==u){a(li(t,o));return}n.setAttribute("data-status",e);let h=n.querySelector(".aparte-tool-state");if(h&&(h.innerHTML=Ts(t)),ii(n,t),ri(n,t),ni(n,t),ti(n,t),o.kind==="body"){rr(n,o.body);return}ei(n,"input",l,"toolInput"),ei(n,"output",c?.text??"",c?.key??"toolOutput"),si(n)},setup:(n,t)=>{let s=C().isToolHidden(t.toolCall?.name??"tool")?void 0:C().getToolRenderer(t.toolCall?.name);s&&oe.set(n,s),!St(n)&&(lr(n),si(n),s&&Pt.set(n,s),s?.setup?.(n,t))},cleanup:(n,t)=>{oe.delete(n);let e=Pt.get(n);if(e){Pt.delete(n);try{e.cleanup?.(n,t)}catch(s){console.error("[aparte] a tool renderer's cleanup threw",s)}}},getStyles:()=>""},ci=new WeakMap;function it(n){let t=ci.get(n);return t||(t={renderers:new Map,defaultsInstalled:!1,defaultsDeclined:!1},ci.set(n,t)),t}function fr(n){let t=it(n);if(n===Q||t.defaultsDeclined)return t.renderers;let e=new Map(it(Q).renderers);for(let[s,i]of t.renderers)e.set(s,i);return e}var ft=null;function Bt(n,t=C()){let e=it(t);e.renderers.get(n.type)!==n&&(e.renderers.set(n.type,n),Js(t),Ht(t))}var di=new WeakMap;function ml(n,t=C()){let e=n.type,s=it(t),i=di.get(t);i||(i=new Map,di.set(t,i));let r=s.renderers.get(e),a=i.get(e);a?a[a.length-1].renderer!==r&&a.splice(0,a.length,{renderer:r}):(a=[{renderer:r}],i.set(e,a));let o={renderer:n};a.push(o),Bt(n,t);let l=!1;return()=>{if(l)return;l=!0;let c=a.indexOf(o);if(c<=0)return;let d=c===a.length-1;if(a.splice(c,1),a.length===1&&i.get(e)===a&&i.delete(e),!d||s.renderers.get(e)!==n)return;let u=a[a.length-1].renderer;if(u){Bt(u,t);return}if(mr(e,t),!fr(t).has(e)&&s.defaultsInstalled&&!s.defaultsDeclined){let h=Xs.find(f=>f.type===e);h&&Bt(h,t)}}}function _r(n=C()){it(n).defaultsDeclined=!0}function gr(n=C()){let t=it(n);if(!(t.defaultsInstalled||t.defaultsDeclined)){t.defaultsInstalled=!0;for(let e of Xs)t.renderers.has(e.type)||t.renderers.set(e.type,e);Js(n)}}function mr(n,t=C()){let e=it(t);e.renderers.has(n)&&(e.renderers.delete(n),Ht(t))}function Qs(n,t=C()){return fr(t).get(n)}var se=new Set;function Js(n=C()){if(typeof document>"u")return;(!ft||!ft.isConnected)&&(ft=document.createElement("style"),ft.id="aparte-renderer-styles",document.head.appendChild(ft),ft.textContent=Array.from(se).join(`
57
- `));let t=!1;for(let e of it(n).renderers.values()){let s=e.getStyles?.();!s||se.has(s)||(se.add(s),t=!0)}t&&(ft.textContent=Array.from(se).join(`
58
- `))}var ui=new WeakMap;function br(n,t){if(typeof document>"u")return;let e=t.getStyles?.();if(!e)return;let s=ui.get(t);if(s||(s=`aparte-tool-renderer-${n}`,ui.set(t,s)),document.getElementById(s))return;let i=document.createElement("style");i.id=s,i.textContent=e,document.head.appendChild(i)}function vr(n=C()){let t=it(n);t.defaultsInstalled=!0;for(let e of Xs)t.renderers.has(e.type)||Bt(e,n);Js(n)}var Xs=[sl,rl,ul,hl,kt];function le(n){let{target:t,config:e,messageId:s,targetId:i}=n,r=new Mt({blocks:e.getStreamBlocks()}),a=new Set,o=null,l=new Map,c=(b,y)=>{let g=`tool-${b}`;t.updateSegment?.(g,l.has(g)?y:{...y,deferred:void 0})},d="",u=!1,h="",f=new Map,_=[],p=[],m=new Set,T=b=>{let y=b.content;typeof y=="string"&&f.set(b.id,{text:b.type==="text",content:y})},L=()=>{if(_.length===0)return;let b=0,y=[...f].map(([v,{text:S,content:x}])=>{let A=h.indexOf(x,b);return A>=0&&(b=A+x.length),{id:v,text:S,start:A,length:x.length,citations:[]}}).filter(v=>v.text);if(y.length===0)return;let g=new Set;for(let v of p){let S=y.find(P=>P.start>=0&&v.end>P.start&&v.end<=P.start+P.length);if(!S)continue;let x=v.end-S.start,A=v.start===void 0?void 0:Math.max(0,Math.min(x,v.start-S.start));S.citations.push({...v,end:x,...A===void 0?{}:{start:A}});for(let P of v.sources)g.add(P)}let w=y[y.length-1],E=new Set;for(let v of y){let S=new Set(v.citations.flatMap(A=>A.sources)),x=_.filter(A=>S.has(A.id)||v===w&&!g.has(A.id));if(x.length===0){m.has(v.id)&&t.updateSegment?.(v.id,{sources:void 0,citations:void 0});continue}E.add(v.id),t.updateSegment?.(v.id,{sources:x,citations:v.citations})}m=E},R=b=>{if(!o||u)return;let y=typeof Element<"u"&&t instanceof Element?k(t):e,g=!b||y.getSegmentDefaults("thinking")?.collapsed===!1;t.updateSegment?.(o,g?{isStreaming:!1}:{collapsed:!0,isStreaming:!1}),u=!0};return b=>{switch(b.type){case"run-start":t.updateMessage?.(s,{status:"streaming"});break;case"turn-start":R(!1),r=new Mt({blocks:e.getStreamBlocks()}),a=new Set,h="",f=new Map,_=m.size===0?_.map(y=>({...y,id:`${y.id}~`})):[],p=[],m=new Set,o=null,d="",u=!1;break;case"thinking-delta":{if(d+=b.delta,o)t.updateSegment?.(o,{content:d});else{let y={id:`think-${G()}`,type:"thinking",content:d,isStreaming:!0};o=y.id,a.add(y.id),t.addSegment?.(y)}break}case"text-delta":{R(!0),h+=b.delta;let y=r.parse(b.delta);for(let w of y.segments)T(w),a.has(w.id)?"content"in w&&t.updateSegment?.(w.id,ns(w)):(t.addSegment?.(w),a.add(w.id));let g=r.getState().activeSegment;g?(T(g),a.has(g.id)?t.updateSegment?.(g.id,ns(g)):(t.addSegment?.(g),a.add(g.id))):y.segments.length;break}case"text-flush":{let y=r.finalize();for(let g of y)T(g),a.has(g.id)?"content"in g&&t.updateSegment?.(g.id,ns(g)):t.addSegment?.(g);L();break}case"sources":{let y=new Map(_.map(w=>[w.id,w]));for(let w of Array.isArray(b.sources)?b.sources:[])y.set(w.id,{...y.get(w.id),...w});_=[...y.values()];let g=new Set(p.map(w=>JSON.stringify([w.start,w.end,w.marker,w.sources])));for(let w of Array.isArray(b.citations)?b.citations:[]){let E=JSON.stringify([w.start,w.end,w.marker,w.sources]);g.has(E)||(g.add(E),p.push(w))}L();break}case"tool-start":{R(!1);let y={id:`tool-${b.toolCallId}`,type:"tool_call",toolCall:{id:b.toolCallId,name:b.name,input:b.input},status:"pending"};l.set(y.id,y);let g=e.getToolRenderer(b.name);g&&br(b.name,g),t.addSegment?.(y);break}case"tool-awaiting-approval":t.updateSegment?.(`tool-${b.toolCallId}`,{status:"awaiting-approval"}),V(t,"aparte-tool-approval-request",{toolCallId:b.toolCallId,toolName:b.name,input:b.input},i);break;case"tool-approved":c(b.toolCallId,{status:"pending"});break;case"tool-rejected":c(b.toolCallId,{status:"rejected",result:b.reason,...b.by?{refusal:b.instruction?{by:b.by,instruction:b.instruction}:{by:b.by}}:{}});break;case"tool-resolved":c(b.toolCallId,{status:"resolved",result:b.result,...b.structuredResult!==void 0?{structuredResult:b.structuredResult}:{}});break;case"tool-aborted":c(b.toolCallId,b.cause?{status:"aborted",abortCause:b.cause}:{status:"aborted"});break;case"tool-failed":c(b.toolCallId,{status:"failed",result:b.error});break;case"turn-limit-exceeded":b.scope==="global"?t.addSegment?.({id:`max-turns-${G()}`,type:"error",content:(typeof Element<"u"&&t instanceof Element?k(t):e).t("maxTurnsReached").replace("{n}",()=>String(b.limit)),code:H.MAX_TURNS_EXCEEDED}):b.toolCallId&&c(b.toolCallId,{status:"aborted",abortCause:"turn-limit"});break;case"run-aborted":V(t,"aparte-message-aborted",{messageId:s},i);break;case"run-suspended":{let y=b.ticket;for(let g of b.pending){let w=`tool-${g.toolCallId}`,E={reason:g.reason,...typeof y=="string"?{ticket:y}:{}};t.updateSegment?.(w,{deferred:E})}if(t.updateMessage?.(s,{status:"completed"}),b.usage)try{t.setUsage?.(s,b.usage)}catch{}V(t,"aparte-message-paused",{messageId:s},i);break}case"run-done":if(t.updateMessage?.(s,{status:"completed",...b.finishReason?{finishReason:b.finishReason}:{}}),b.usage)try{t.setUsage?.(s,b.usage)}catch{}break}}}function yr(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 Ac=new TextEncoder;var Cc=10080*60*1e3;var dt=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 bl(n){return n?n.tagName?.toLowerCase()==="aparte-chat"||n.hasAttribute?.("data-aparte-chat")===!0:!1}function Z(n){let t=n??null;for(;t;){if(bl(t))return t;t=t.parentElement}return null}var _e=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}},ct={copy:!1,retry:!1,edit:!1,feedback:!1,info:!1},Nt={attachmentPreview:!1,filePreview:!1},hi=()=>{},wr=new WeakMap;function J(n){return wr.get(n)??0}function lt(n){wr.set(n,J(n)+1)}var Is=new Set,ne=new Set;function Sr(n){return Is.add(n),()=>{Is.delete(n)}}function Ht(n){ne.size===0&&queueMicrotask(()=>{let t=[...ne];ne.clear();for(let e of t)for(let s of[...Is])try{s(e)}catch(i){console.error("[aparte] a renderer-change listener threw",i)}}),ne.add(n)}var vl=n=>n instanceof RegExp?`re:${String(n)}`:`name:${n}`,hs=["hidden","open","details","quiet"];function ps(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 pi=new WeakSet;function yl(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 Wt=class{_markdownProvider;_streamingMarkdownProvider;_highlightProvider;_codeLanguageRenderers=new Map;_sanitizer=ys;_systemPromptTemplate;_systemPromptVarsProvider;_statusRenderer;_errorRenderer;_attachmentRenderer;_siblingNavRenderer;_bubbleShellRenderer;_iconProvider;_avatarProvider;_keyProvider;_extraKeyProviders=new Set;_locale=Ct;_actions=[];_listeners=new Set;_aiProviders=new Map;_fetchedModels=new Map;_modelConfig={};_requireModelSelection=!1;_elicitationAllowOther=!0;_elicitationLayout="stepped";_elicitationAnswerOnClick=!0;_elicitationFieldRenderer;_transport=new ue;_modelPreferenceProvider;_approvalPolicy=null;_compactor=null;_conversationManager;_elicitationPresenters=[];_warnedNoPresenter=!1;_elicitationQueue=new Map;_tools=new Map;_toolRenderers=new _e;_toolRendererOverrides=new Map;_overrideGeneration=0;_toolDisplays=new _e;_streamBlocks=new Map;_segmentDefaults=new Map;_hostHandlers={...Nt};_bubbleActionsConfig={...ct};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??Nt.attachmentPreview,filePreview:this._hostHandlers.filePreview??Nt.filePreview}}getBubbleActions(){return{copy:this._bubbleActionsConfig.copy??ct.copy,retry:this._bubbleActionsConfig.retry??ct.retry,edit:this._bubbleActionsConfig.edit??ct.edit,feedback:this._bubbleActionsConfig.feedback??ct.feedback,info:this._bubbleActionsConfig.info??ct.info,user:this._bubbleActionsConfig.user,assistant:this._bubbleActionsConfig.assistant}}setMarkdownProvider(t){this._markdownProvider=t,lt(this),this._notify()}setStreamingMarkdownProvider(t){this._streamingMarkdownProvider=t,lt(this),this._notify()}createStreamingMarkdownRenderer(t){return this._streamingMarkdownProvider?this._streamingMarkdownProvider(t):null}setHighlightProvider(t){this._highlightProvider=t,lt(this),this._notify()}hasHighlightProvider(){return!!this._highlightProvider}registerCodeLanguageRenderer(t){let e=t.languages.map(s=>s.toLowerCase());for(let s of e)this._codeLanguageRenderers.set(s,t);return lt(this),this._notify(),()=>{let s=!1;for(let i of e)this._codeLanguageRenderers.get(i)===t&&(this._codeLanguageRenderers.delete(i),s=!0);s&&(lt(this),this._notify())}}getCodeLanguageRenderer(t){return this._codeLanguageRenderers.get(t.toLowerCase())}hasCodeLanguageRenderer(t){return t===void 0?this._codeLanguageRenderers.size>0:this._codeLanguageRenderers.has(t.toLowerCase())}setHtmlSanitizer(t){t!==this._sanitizer&&(t===null&&console.warn("[aparte] HTML sanitization is now DISABLED (setHtmlSanitizer(null)). Model-authored HTML will be inserted verbatim. Pass a sanitizer (defaultSanitizer, or DOMPurify chained before it) unless you sanitize upstream yourself."),this._sanitizer=t,lt(this),this._notify())}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&&pi.has(e))Object.assign(e,t);else{let s=Object.assign(Object.create(e??null),t);pi.add(s),this._iconProvider=s}this._notify()}getIconProvider(){let t=this._iconProvider,e={};for(let s of Object.keys(Ot))e[s]=ps(t,s)??(()=>Ot[s]);for(let s of yl(t)){let i=ps(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=Ct,this._notify()}getLocale(){return this._locale}extendLocale(t){this._locale={...this._locale,...t},this._notify()}getIcon(t){let e=ps(this._iconProvider,t);return e?e():Object.prototype.hasOwnProperty.call(Ot,t)?Ot[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]||Ct[t];return e===void 0?"":e}renderMarkdown(t){if(this._markdownProvider)try{return this.sanitizeHtml(this._markdownProvider(t))}catch(e){console.warn("[AparteConfig] Markdown provider failed, using fallback:",e)}else if(this._streamingMarkdownProvider&&typeof document<"u")try{let e=document.createElement("div"),s=this._streamingMarkdownProvider(e);return s.write(t),s.end(),this.sanitizeHtml(e.innerHTML)}catch(e){console.warn("[AparteConfig] Streaming Markdown provider failed on a complete string, using fallback:",e)}return this._defaultMarkdownRenderer(t)}async highlightCode(t,e,s={}){if(this._highlightProvider)try{let i=this._highlightProvider(t,e),r=i instanceof Promise?await i:i;return this.sanitizeHtml(r)}catch(i){if(console.warn("[AparteConfig] Highlight provider failed, using fallback:",i),s.fallback===!1)throw i}return this._defaultHighlightRenderer(t)}registerTool(t,e){this._tools.set(t.name,{tool:t,handler:e})}unregisterTool(t){this._tools.delete(t)}getTools(){return Array.from(this._tools.values()).map(t=>t.tool)}resolveToolSystemPrompts(){let t=Array.from(this._tools.values()).map(e=>e.tool.systemPrompt?.trim()).filter(e=>!!e);return t.length?t.join(`
59
-
60
- `):null}getToolHandler(t){return this._tools.get(t)?.handler}registerToolRenderer(t,e){this._toolRenderers.get(t)!==e&&(this._toolRenderers.set(t,e),Ht(this))}overrideToolRenderer(t,e){let s=vl(t),i=this._toolRenderers.get(t),r=this._toolRendererOverrides.get(s);r?r[r.length-1].renderer!==i&&r.splice(0,r.length,{renderer:i}):(r=[{renderer:i}],this._toolRendererOverrides.set(s,r));let a={renderer:e};r.push(a),this.registerToolRenderer(t,e);let o=this._overrideGeneration,l=!1;return()=>{if(l||o!==this._overrideGeneration)return;l=!0;let c=r.indexOf(a);if(c<=0)return;let d=c===r.length-1;if(r.splice(c,1),r.length===1&&this._toolRendererOverrides.get(s)===r&&this._toolRendererOverrides.delete(s),!d||this._toolRenderers.get(t)!==e)return;let u=r[r.length-1].renderer;u?this.registerToolRenderer(t,u):this.unregisterToolRenderer(t)}}setSegmentDefaults(t,e){this._segmentDefaults.set(t,{...e})}getSegmentDefaults(t){return this._segmentDefaults.get(t)}clearSegmentDefaults(t){this._segmentDefaults.delete(t)}unregisterToolRenderer(t){this._toolRenderers.get(t)!==void 0&&(this._toolRenderers.delete(t),Ht(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),(hs.some(a=>s?.[a]!==i[a])||s===void 0&&this._anotherShapes(i))&&lt(this),this._notify()}unregisterToolDisplay(t){let e=this._toolDisplays.get(t);this._toolDisplays.delete(t),(hs.some(i=>e?.[i]!==void 0)||e!==void 0&&this._anotherShapes(e))&&lt(this),this._notify()}_anotherShapes(t){return this._toolDisplays.values().some(e=>e!==t&&hs.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=Z(t);if(s)for(let i=e.length-1;i>=0;i-=1){let r=e[i];if(r.owner&&Z(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(hi,hi).then(()=>{this._elicitationQueue.get(e)===r&&this._elicitationQueue.delete(e)});return this._elicitationQueue.set(e,r),i}_elicitationQueueKey(t){return Z(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 dt("no-presenter"));if(t.signal?.aborted)return Promise.reject(new dt("aborted"));let s=e(t),i=t.signal;return i?new Promise((r,a)=>{let o=()=>a(new dt("aborted"));i.addEventListener("abort",o,{once:!0}),s.then(r,a).finally(()=>i.removeEventListener("abort",o))}):s}reset(){this._markdownProvider=void 0,this._streamingMarkdownProvider=void 0,this._highlightProvider=void 0,this._codeLanguageRenderers.clear(),this._systemPromptTemplate=void 0,this._systemPromptVarsProvider=void 0,this._statusRenderer=void 0,this._errorRenderer=void 0,this._attachmentRenderer=void 0,this._siblingNavRenderer=void 0,this._bubbleShellRenderer=void 0,this._iconProvider=void 0,this._segmentDefaults.clear(),this._avatarProvider=void 0,this._keyProvider=void 0,this._conversationManager=void 0,this._elicitationPresenters=[],this._elicitationQueue.clear(),this._locale=Ct,this._actions=[],this._sanitizer=ys,this._aiProviders.clear(),this._fetchedModels.clear(),this._tools.clear(),this._toolRenderers.clear(),this._toolRendererOverrides.clear(),this._overrideGeneration++,Ht(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={...ct},this._hostHandlers={...Nt},this._notify()}_defaultMarkdownRenderer(t){return I(t).replace(/\n/g,"<br>")}_defaultHighlightRenderer(t){return`<pre><code>${I(t)}</code></pre>`}},fs=Symbol.for("aparte.globalConfig.1");function wl(){return typeof window<"u"?(window[fs]||(window[fs]=new Wt),window[fs]):new Wt}var Q=wl(),Rs="aparte-config-change";function ut(n,t){let e=s=>{let i=s.detail;i?.config&&i.config!==k(n)||t()};return window.addEventListener(Rs,e),()=>window.removeEventListener(Rs,e)}var Ar="suggestions";function Sl(n){let t;try{t=JSON.parse(n)}catch{return null}if(!Array.isArray(t))return null;let e=t.filter(s=>typeof s=="string"&&s.trim()!==""||typeof s=="object"&&s!==null&&typeof s.label=="string");return e.length?e:null}function Al(n=Q){return n.registerCodeLanguageRenderer({languages:[Ar],bare:!0,render:({source:t,open:e})=>{if(e)return"";let s=Sl(t);return s?`<span class="aparte-suggestions-mark" hidden data-aparte-suggestions="${M(JSON.stringify(s))}"></span>`:`<code class="aparte-code-error">${I(t)}</code>`}})}var Cl=new WeakSet;function Zs(n){return!!n&&Cl.has(n)}function tn(n,t,e){if(t.segments&&t.segments.length>0){let s=n.getSegments?.()??[];if(s.length===t.segments.length){let i=qs(t.status);for(let r of t.segments)if("content"in r){let a={content:r.content};i&&(a.isStreaming=!1);let o=s.find(l=>l.id===r.id);r.type==="text"&&(r.sources||r.citations||o?.sources||o?.citations)&&Object.assign(a,{sources:r.sources,citations:r.citations}),n.updateSegment?.(r.id,a)}}else n.setSegments?.(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 en=Symbol.for("aparte.derivedSegments");function Cr(n){return n.map(t=>({id:G(),name:t.name,type:t.type||"application/octet-stream",url:URL.createObjectURL(t),size:t.size,blob:t}))}function Er(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 Os=new Map;function sn(n,t){t?Os.set(n,t):Os.delete(n)}function kr(n,t){sn(n,t);try{window.dispatchEvent(new CustomEvent("aparte-conversation-status",{detail:{id:n,status:t}}))}catch{}}function Ee(n){return Os.get(n)??null}function z(n){return n.replace(/["\\]/g,"\\$&").replace(/[\n\r\f]/g,t=>`\\${t.charCodeAt(0).toString(16)} `)}function Mr(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 Tr(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 ge=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 me(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 El="The earlier part of this conversation was compacted. This is a summary of what came before; continue from it.",nn=n=>`${El}
61
-
62
- ${n}`;function At(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 fi="The tool call was stopped before it ran.",kl="The tool returned no output.";function Ml(n){let t=n.result?.trim();return n.status==="resolved"?t||kl:n.status==="failed"?t||"The tool failed.":n.status==="rejected"&&t||fi}var $t=n=>n.type==="tool_call"&&!!n.deferred&&(n.status==="awaiting-approval"||n.status==="pending");function Lr(n,t,e={}){let s=n.segments??[];if(n.role!=="assistant"||!s.some(c=>c.type==="tool_call")){let c=t(s)||(typeof n.content=="string"?n.content:"");return c?[{role:n.role,content:c}]:[]}let i=[],r=[],a=[],o=()=>{let c=t(r);if(a.length===0)c&&i.push({role:"assistant",content:c});else{i.push({role:"assistant",content:c,toolCalls:a.map(d=>({id:d.toolCall.id,name:d.toolCall.name,input:d.toolCall.input}))});for(let d of a)e.openDeferred&&$t(d)||i.push({role:"tool",content:Ml(d),toolCallId:d.toolCall.id,toolName:d.toolCall.name})}r=[],a=[]},l=!1;for(let c of s)c.type==="tool_call"?(a.push(c),e.openDeferred&&$t(c)&&(l=!0)):(a.length>0&&!l&&o(),r.push(c));return o(),i}var xr=n=>n.status==="streaming"||n.status==="pending";function ke(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 Tl(n){let t=ke(n.segments);return t||(typeof n.content=="string"&&n.content?n.content:"")}function Ll(n){let t=Tl(n);return n.compaction?nn(t):t}function ce(n){return n.filter(t=>t.role!=="user"&&t.role!=="assistant"?!1:t.status!=="error"&&!xr(t)).flatMap(t=>{if(t.role==="assistant"&&t.segments?.some(s=>s.type==="tool_call"))return Lr(t,ke);let e=Ll(t);return e?[{role:t.role,content:e}]:[]})}function mt(n){return n?Math.ceil(n.length/3.8):0}var rn=n=>{if(!n)return 0;try{return mt(JSON.stringify(n))}catch{return 0}};function Ir(n){let t=0;for(let e of n)t+=mt(Si(e.content)),e.toolCalls?.length&&(t+=rn(e.toolCalls));return t}function xl(n){return n.some(t=>typeof t.content!="string"&&t.content.some(e=>e.type!=="text"))}function Il(n){let t=(n.tools??[]).map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema}));return Ir(n.messages)+(t.length?rn(t):0)}function Rr(n){return Ir(ce(n))}var Me=n=>n.totalTokens??n.inputTokens+n.outputTokens;function Or(n){let t=n.getCurrentModel()?.capabilities;return(t?!t.includes("function_calling"):!1)?[]:n.getTools()}function Rl(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 Pr=(n,t)=>n.segments?.some(e=>e.type===t)===!0;function Ol(n){let t=n.usage?.inputTokens,e=n.contextEstimate;return Pr(n,"tool_call")?1:t&&e&&t>0&&e>0?Math.min(3,Math.max(.5,t/e)):1}function Pl(n,t){let e=n.usage;if(!Pr(n,"thinking")||!(e.inputTokens>0))return Me(e);let s=n.segments??[],i=s.map(a=>a.type).lastIndexOf("tool_call"),r=Math.round(t*mt(ke(s.slice(i+1))));return e.inputTokens+(e.outputTokens>0?Math.min(r,e.outputTokens):r)}function Nr(n){let{messages:t,config:e}=n,s=me(t),i=mt(e.resolveSystemPrompt())+mt(e.resolveToolSystemPrompts()),r=Or(e).map(m=>({name:m.name,description:m.description,inputSchema:m.inputSchema})),a=r.length?rn(r):0,o=s.summary===void 0?0:mt(nn(s.summary)),l={system:i,tools:a,summary:o,messages:Rr(s.messages)},c=i+a+o+l.messages,d=-1;for(let m=t.length-1;m>=0;m--)if(t[m].role==="assistant"&&t[m].usage){d=m;break}let u=d>=0?t[d]:void 0,h=Rl(e,n.windowOverride),f=(m,T)=>({...h!==void 0?{window:h}:{},used:m,estimated:T,parts:l,other:Math.max(0,m-c)}),_=u!==void 0&&!n.viewChanged&&d===t.length-1&&!t.some(m=>m.contextSummary!==void 0&&m.contextSummary.createdAt>u.timestamp),p=u?Ol(u):1;return u&&_?f(Pl(u,p),!1):f(Math.round(p*c),!0)}function ht(n){return n.composedPath?.()[0]??n.target}function yt(n){return n.getRootNode()}function pt(n){return n.getRootNode().activeElement??document.activeElement}var Nl=0,de=null;function jt(n){de?.push(n)}function D(n,t,e){let s=document.createElement(n);return t&&(s.className=t),e!=null&&(s.textContent=e),s}function an(n,t,e){let s=D("span","aparte-elic-option-body"),i=D("span","aparte-elic-option-title",n);if(e){let r=D("span","aparte-tag aparte-tag--sm aparte-elic-option-badge",C().t("elicitationRecommended")||"Recommended");i.append(" ",r)}return s.appendChild(i),t&&s.appendChild(D("span","aparte-elic-option-desc",t)),s}function Ps(n,t,e){let s=D("button","aparte-btn aparte-btn--block aparte-btn--surface aparte-elic-option aparte-elic-option--command"+(e?" aparte-elic-option--recommended":""));return s.type="button",s.appendChild(an(n,t,e)),s}function on(n,t,e){let s;if(t.title&&t.title.trim()!==e?.trim()){let i=D("p","aparte-elic-title",t.title);s=`elic-title-${G()}`,i.id=s,n.appendChild(i)}return t.description&&n.appendChild(D("p","aparte-elic-desc",t.description)),s}function Dr(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 Dl(n,t,e,s){let i=D("div","aparte-elic-field aparte-elic-enum"),r=on(i,n,e),a=D("div","aparte-elic-options"),o=`elic-${G()}`,l=n.multiple?"checkbox":"radio",c=l==="checkbox"?"aparte-checkbox":"aparte-radio",d=n.allowOther??C().getElicitationOptions().allowOther,u=new Set(Array.isArray(n.default)?n.default:n.default!=null?[n.default]:[]),h=s!=null&&!n.multiple&&u.size===0;Dr(a,{multiple:n.multiple,commands:h,titleId:r,fallbackLabel:e});let f=(y,g,w,E)=>{if(h){let x=Ps(g,w,E);return x.addEventListener("click",()=>s?.(y)),x}let v=D("label","aparte-field-choice aparte-elic-option"+(E?" aparte-elic-option--recommended":"")),S=D("input",c+" aparte-elic-control");return S.type=l,S.name=o,S.value=y,u.has(y)&&(S.checked=!0),v.append(S,an(g,w,E)),v};for(let y of n.options)a.appendChild(f(y.value,y.label??y.value,y.description,y.recommended));let _=null,p=!1;if(d){let y=C();_=D("input","aparte-field aparte-elic-other-input"),_.type="text",_.placeholder=y.t("elicitationOtherPlaceholder"),_.style.display="none",_.setAttribute("aria-label",y.t("elicitationOtherLabel"));let g=_;if(h){let w=Ps(y.t("elicitationOther"));w.classList.add("aparte-elic-option--other"),w.setAttribute("aria-expanded","false"),w.addEventListener("click",()=>{p=!0,w.setAttribute("aria-expanded","true"),g.style.display="",g.focus(),t()});let E=w.querySelector(".aparte-elic-option-title");jt(()=>{let v=C();E.textContent=v.t("elicitationOther"),g.placeholder=v.t("elicitationOtherPlaceholder"),g.setAttribute("aria-label",v.t("elicitationOtherLabel"))}),a.append(w,g)}else{let w=D("label","aparte-field-choice aparte-elic-option aparte-elic-option--other"),E=D("input",c+" aparte-elic-control");E.type=l,E.name=o,E.value="__other__";let v=D("span","aparte-elic-option-body"),S=D("span","aparte-elic-option-title",y.t("elicitationOther"));v.appendChild(S),jt(()=>{let x=C();S.textContent=x.t("elicitationOther"),g.placeholder=x.t("elicitationOtherPlaceholder"),g.setAttribute("aria-label",x.t("elicitationOtherLabel"))}),v.appendChild(_),w.append(E,v),a.appendChild(w)}}i.appendChild(a);let m=()=>Array.from(a.querySelectorAll(".aparte-elic-control")),T=()=>a.querySelector('input[value="__other__"]'),L=!1;a.addEventListener("keydown",y=>{L=y.key.startsWith("Arrow")}),a.addEventListener("click",()=>{L=!1}),a.addEventListener("change",()=>{let y=T();y&&_&&(_.style.display=y.checked?"":"none",y.checked&&!L&&_.focus()),L=!1,t()}),_?.addEventListener("input",t);let R=()=>_?.value.trim()??"";if(h)return{el:i,getValue:()=>R(),isComplete:()=>p&&R()!=="",focus:()=>a.querySelector(".aparte-elic-option--command")?.focus(),offersSubmit:()=>p};let b=()=>{let y=T()?.checked&&R()?R():"";if(n.multiple){let w=m().filter(E=>E.checked&&E.value!=="__other__").map(E=>E.value);return y&&w.push(y),w}let g=m().find(w=>w.checked);return g?g.value==="__other__"?y:g.value:""};return{el:i,getValue:b,isComplete:()=>{let y=b();return n.multiple?y.length>0:y!==""},focus:()=>m()[0]?.focus()}}function Bl(n,t,e,s){let i=D("div","aparte-elic-field aparte-elic-boolean"),r=on(i,n,e),a=D("div","aparte-elic-options"),o=`elic-${G()}`,l=s!=null&&n.default==null;if(Dr(a,{commands:l,titleId:r,fallbackLabel:e}),l){let h=C(),f=(_,p,m)=>{let T=Ps(p);if(T.addEventListener("click",()=>s?.(_)),m){let L=T.querySelector(".aparte-elic-option-title");jt(()=>{L.textContent=C().t(m)})}a.appendChild(T)};return f(!0,n.trueLabel??h.t("elicitationYes"),n.trueLabel?void 0:"elicitationYes"),f(!1,n.falseLabel??h.t("elicitationNo"),n.falseLabel?void 0:"elicitationNo"),i.appendChild(a),{el:i,getValue:()=>!1,isComplete:()=>!1,focus:()=>a.querySelector(".aparte-elic-option--command")?.focus(),offersSubmit:()=>!1}}let c=(h,f,_)=>{let p=D("label","aparte-field-choice aparte-elic-option"),m=D("input","aparte-radio aparte-elic-control");m.type="radio",m.name=o,m.value=h,n.default!=null&&String(n.default)===h&&(m.checked=!0);let T=D("span","aparte-elic-option-body"),L=D("span","aparte-elic-option-title",f);_&&jt(()=>{L.textContent=C().t(_)}),T.appendChild(L),p.append(m,T),a.appendChild(p)},d=C();c("true",n.trueLabel??d.t("elicitationYes"),n.trueLabel?void 0:"elicitationYes"),c("false",n.falseLabel??d.t("elicitationNo"),n.falseLabel?void 0:"elicitationNo"),i.appendChild(a),a.addEventListener("change",t);let u=()=>a.querySelector("input:checked");return{el:i,getValue:()=>u()?.value==="true",isComplete:()=>u()!=null,focus:()=>a.querySelector("input")?.focus()}}function Hl(n,t,e){let s=D("div","aparte-elic-field aparte-elic-string");on(s,n,e);let i=n.multiline?D("textarea","aparte-field aparte-field--textarea aparte-elic-text"):D("input","aparte-field aparte-elic-text");n.multiline||(i.type="text"),n.placeholder&&i.setAttribute("placeholder",n.placeholder),n.default&&(i.value=n.default),n.maxLength!=null&&i.setAttribute("maxlength",String(n.maxLength));let r=n.title||n.description||e||void 0;if(i.setAttribute("aria-label",r??C().t("elicitationAnswerLabel")),r==null){let l=i;jt(()=>{l.setAttribute("aria-label",C().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 _i(n,t,e,s,i){let r=C().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 Dl(n,t,e,i);case"boolean":return Bl(n,t,e,i);case"string":return Hl(n,t,e)}}function Br(n,t,e){let s=[],i=de;de=s;try{return{...$l(n,t,e),relabel:()=>{for(let a of s)a()}}}finally{de=i}}function $l(n,t,e){let s=D("div","aparte-elic-panel"),i=typeof n=="function"?n():n;i&&s.appendChild(D("p","aparte-elic-message",i));let r=null,a=!1,o=f=>{a||(a=!0,r?.(f))},l=f=>{r=f},c=D("div","aparte-elic-body");s.appendChild(c);let d=D("div","aparte-elic-dismiss");if(s.appendChild(d),t.type==="object"){let f=function(S){g=S,R.forEach((x,A)=>{x.field.el.hidden=A!==S}),T()},_=Object.entries(t.properties),p=new Set(t.required??_.map(([S])=>S)),m=C(),T=()=>{},L=()=>{T(),e()},R=_.map(([S,x])=>{let A=_i(x,L,void 0,S);return!x.title&&!A.el.querySelector(".aparte-elic-title")&&A.el.insertBefore(D("p","aparte-elic-title",S),A.el.firstChild),c.appendChild(A.el),{key:S,field:A,required:p.has(S),header:x.header}}),b=()=>R.every(S=>!S.required||S.field.isComplete()),y={el:s,dismiss:d,getContent:()=>Object.fromEntries(R.map(S=>[S.key,S.field.getValue()])),isComplete:b,focus:()=>R[0]?.field.focus(),mode:()=>"submit",canProceed:b,proceed:()=>{},onSettle:l};if(R.length<2||m.getElicitationOptions().layout!=="stepped")return y;s.classList.add("aparte-elic-panel--stepped");let g=0,w=`aparte-elic-${++Nl}`,E=D("div","aparte-tabs aparte-tabs--underline aparte-elic-steps");E.setAttribute("role","tablist");let v=R.map((S,x)=>{let A=D("button","aparte-tabs__tab aparte-elic-step");return A.type="button",A.setAttribute("role","tab"),A.textContent=S.header?.trim()||String(x+1),A.addEventListener("click",()=>{f(x),S.field.focus()}),A.id=`${w}-tab-${x}`,S.field.el.id=`${w}-panel-${x}`,S.field.el.setAttribute("role","tabpanel"),S.field.el.setAttribute("aria-labelledby",A.id),A.setAttribute("aria-controls",S.field.el.id),A.addEventListener("keydown",P=>{let q=P.key==="ArrowRight"?1:P.key==="ArrowLeft"?-1:0,B=-1;q?B=(x+q+R.length)%R.length:P.key==="Home"?B=0:P.key==="End"&&(B=R.length-1),!(B<0)&&(P.preventDefault(),f(B),v[B]?.focus())}),E.appendChild(A),A});return s.insertBefore(E,c),T=()=>{v.forEach((S,x)=>{S.setAttribute("aria-selected",String(x===g)),S.tabIndex=x===g?0:-1;let A=R[x].field.isComplete();S.toggleAttribute("data-answered",A);let P=S.querySelector(".aparte-elic-step__mark");if(A&&!P){let q=D("span","aparte-elic-step__mark");q.setAttribute("aria-hidden","true"),q.innerHTML=m.getIcon("check"),S.prepend(q)}else!A&&P&&P.remove()})},f(0),{...y,focus:()=>R[g]?.field.focus()}}let u=C().getElicitationOptions().answerOnClick,h=_i(t,e,i,void 0,u?o:void 0);return c.appendChild(h.el),{el:s,dismiss:d,getContent:()=>h.getValue(),isComplete:()=>h.isComplete(),focus:()=>h.focus(),mode:()=>h.offersSubmit?.()??!0?"submit":"none",canProceed:()=>h.isComplete(),proceed:()=>{},onSettle:l}}var ql=0;function st(n,t,e){let s=document.createElement(n);return t&&(s.className=t),e!=null&&(s.textContent=e),s}var Fl=0;function Hr(n,t,e,s,i=!0){let r=C(),a=st("div","aparte-elic-panel aparte-approval-panel"),o=st("div","aparte-elic-body");a.appendChild(o);let l=()=>typeof n=="function"?n():n,c=l()?st("p","aparte-elic-message",l()):null;c&&o.appendChild(c);let d=null;if(s){d=st("div","aparte-approval-args-label",r.t("approvalArgsLabel")),d.id="aparte-approval-args-"+ ++ql;let g=st("pre","aparte-approval-args");g.textContent=s,g.setAttribute("role","group"),g.setAttribute("aria-labelledby",d.id),g.tabIndex=0,o.append(d,g)}let u=st("div","aparte-elic-dismiss");a.appendChild(u);let h=null,f=!1,_=g=>{f||(f=!0,h?.(g))},p=st("div","aparte-approval-options");p.setAttribute("role","group"),p.setAttribute("aria-label",r.t("approvalOptionsLabel")),c&&(c.id||=`aparte-approval-ask-${++Fl}`,p.setAttribute("aria-describedby",c.id));let m=[],T=g=>typeof g.label=="function"?g.label():g.label,L=g=>typeof g.description=="function"?g.description():g.description,R=g=>an(T(g),L(g));for(let g of t){let w=g.tone??"affirm",E=st("button",`aparte-btn aparte-btn--block aparte-btn--surface aparte-approval-option aparte-approval-option--${w}`);E.type="button",E.appendChild(R(g)),E.addEventListener("click",()=>_({option:g.value})),p.appendChild(E),m.push({button:E,option:g})}o.appendChild(p);let b=i?st("textarea","aparte-approval-instruction"):null;b&&(b.rows=1,b.placeholder=r.t("approvalInstructionPlaceholder"),b.setAttribute("aria-label",r.t("approvalInstructionPlaceholder")),b.addEventListener("input",e),o.appendChild(b));let y=()=>b?.value.trim()??"";return{el:a,dismiss:u,onSettle:g=>{h=g},getContent:()=>({instruction:y()}),isComplete:()=>y().length>0,focus:()=>{a.querySelector(".aparte-approval-option")?.focus()},relabel:()=>{let g=C(),w=g.t("approvalInstructionPlaceholder");b&&(b.placeholder=w,b.setAttribute("aria-label",w)),p.setAttribute("aria-label",g.t("approvalOptionsLabel")),c&&(c.textContent=l()),d&&(d.textContent=g.t("approvalArgsLabel"));for(let{button:E,option:v}of m)E.replaceChildren(R(v))}}}function $r(n){return k(n.target??null).requestUserInput(n)}var Ul="Not run: an earlier call of the same step was refused.",gi=n=>JSON.stringify([n.id,n.name,n.input]),mi=new Set,_t=new Map,bi="aparte-chat, aparte-chat-viewport, [data-aparte-chat]";function Wl(n){return{id:n,getMetadata:()=>({id:n,name:n}),getModels:()=>[],chat:async()=>{throw new Y("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 Ns=class{_boundHandler=null;_listening=!1;_boundAbortHandler=null;_boundLoadedHandler=null;_boundRetryHandler=null;_boundEditHandler=null;_releaseKeyResolver=null;_isAborted=!1;_windowReadFor=new Set;async _readWindowAfterTurn(){let t=this._config,e=t.getCurrentModel(),s=t.getModelConfig().defaultProvider;if(!e||e.contextWindow||!s)return;let i=`${s}\0${e.id}`;this._windowReadFor.has(i)||(this._windowReadFor.add(i),await t.refreshProviderModels(s))}_isForThisInstance(t){if(!t)return!0;let e=t.detail,s=this.options.scopeToTargetId;if(s)return e?.targetId===s;if(this._config===Q){if(_t.size===0)return!0;let a=this._resolveTarget(e?.targetId,t),o=a?k(a):Q;return o===Q||!_t.has(o)}let i=this._resolveTarget(e?.targetId,t);if(!i)return!0;let r=k(i);return r===this._config||r===Q}_streamController=null;options;_config;_claims=!1;constructor(t={}){this.options={autoRegister:!0,...t},this._config=t.config??Q,this._registerKeyResolver(),this.options.autoRegister?vr(this._config):_r(this._config),this._setupListeners()}_beginUserTurn(){this._isAborted=!1}_registerKeyResolver(){this._releaseKeyResolver||!this.options.keyResolver||(this._releaseKeyResolver=this._config.registerKeyProvider(this.options.keyResolver))}_setupListeners(){this._boundHandler||(this._boundHandler=t=>{let e=t;e.type==="aparte-send"&&this._isForThisInstance(e)&&(this._beginUserTurn(),this._handleSend(e))})}start(){this._registerKeyResolver(),this._config!==Q&&!this._claims&&(this._claims=!0,_t.set(this._config,(_t.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=(_t.get(this._config)??1)-1;t>0?_t.set(this._config,t):_t.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 $r({kind:"approval",message:()=>{let o=this._config.getLocale(),l=k(s),c={id:`tool-${t.id}`,type:"tool_call",status:"awaiting-approval",toolCall:{id:t.id,name:t.name,input:t.input}},d=er(c,l).text,u=sr(c,l);return(o.approvalAsk??"Allow {tool}?").replace("{tool}",()=>u?`${d} ${u}`:d)},details:tr(t.input,k(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!==ss}_providerFor(t){let e=t?this._config.getAIProvider(t):void 0;return e||(this._modelRunsElsewhere?Wl(t??""):void 0)}async _resolveAuth(t){if(this.options.keyResolver){let s=await this.options.keyResolver(t);if(s)return s}return await this._config.getKey(t)||void 0}async _streamTurn(t,e,s,i,r,a,o){let l=this._targetIdOf(t),c=this._toolsForCurrentModel(),d=async g=>{let w={messages:g,modelId:r,stream:!0,tools:c.length?c: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},u=await d(i);if(this._isAborted){V(t,"aparte-message-aborted",{messageId:e},l),this._updateMessage(t,e,{status:"completed"});return}V(t,"aparte-message-start",{messageId:e,role:"assistant"},l),o?.resume&&V(t,"aparte-message-paused",{messageId:e},l),!o?.resume&&s.id&&this._updateMessage(t,e,{model:{providerId:s.id,modelId:u.modelId,...u.temperature!==void 0?{temperature:u.temperature}:{}}});let h=new AbortController;this._streamController!==h&&this._streamController?.abort(),this._streamController=h,this._turnsInFlight.add(e);let f=o?.rebuild?k(t).getCompactor()??this._config.getCompactor():null,_=()=>{let g=t.getMessages?.()??[],w=g.findIndex(v=>v.id===e),E=w>0?g[w-1]:void 0;return E?.role==="user"?[E.id,e]:[e]},p=()=>o?.resume?this._resumeMessages(t,e,u.messages):u.messages,m=()=>Il({messages:p(),tools:u.tools}),T=()=>xl(p())?void 0:m(),L=()=>{this._closeOpenCalls(t,e),V(t,"aparte-message-aborted",{messageId:e},l),this._updateMessage(t,e,{status:"completed"})},R=()=>this._isAborted||h.signal.aborted,b=async()=>{let g=o?.resume?{usage:void 0,suspended:o.resume}:await this._streamLoop(t,e,s,u,a,h,void 0,o?.files),w=this.options.maxTurns??10,E=0,v=new Set,S=le({target:t,config:this._config,messageId:e,...l?{targetId:l}:{}});for(;g.suspended;){let P=this._isAborted||h.signal.aborted;if(!P&&++E>w){this._closeOpenCalls(t,e),le({target:t,config:this._config,messageId:e,...l?{targetId:l}:{}})({type:"turn-limit-exceeded",scope:"global",limit:w});break}let q=new Set,B=P?void 0:await this._answerDeferred(t,g.suspended.pending,h.signal,S,v,q);if(v=q,!B){this._closeOpenCalls(t,e),(this._isAborted||h.signal.aborted)&&V(t,"aparte-message-aborted",{messageId:e},l);break}let et={outcomes:B,...g.suspended.ticket?{token:g.suspended.ticket}:{}},xt=this._resumeMessages(t,e,u.messages);this._spendPause(t,e),V(t,"aparte-message-resumed",{messageId:e},l),g=await this._streamLoop(t,e,s,{...u,messages:xt},a,h,et)}let x=g.usage,A=g.finishReason;this._isAborted||h.signal.aborted?(this._closeOpenCalls(t,e),this._updateMessage(t,e,{status:"completed"})):(V(t,"aparte-message-done",{messageId:e,role:"assistant",usage:x,...A?{finishReason:A}:{}},l),this._readWindowAfterTurn())},y=async g=>{if(g.code!==H.USAGE_CONTEXT_EXCEEDED||!f||!o?.rebuild||(t.getMessage?.(e)?.segments??t.getMessages?.()?.find(E=>E.id===e)?.segments??[]).some(E=>E.type==="text"||E.type==="tool_call"))return"stands";try{let E=await f.compact({target:t,...l?{targetId:l}:{},force:!0,reason:"overflow",exclude:_(),signal:h.signal});if(R())return"stopped";if(!E.ok||E.skipped)return"stands";u=await d(await o.rebuild())}catch{return"stands"}return this._updateMessage(t,e,{status:"pending"}),"resend"};try{for(let g=0;;g++)try{if(g===0&&f?.beforeSend&&o?.rebuild){let w=!1;try{w=await f.beforeSend({target:t,...l?{targetId:l}:{},exclude:_(),requestTokens:m(),signal:h.signal})}catch(E){console.warn("[AparteClient] The compactor threw before a send; sending the request as built.",E)}if(R()){L();return}w&&(u=await d(await o.rebuild()))}this._updateMessage(t,e,{contextEstimate:T()}),await b();return}catch(w){if(this._closeOpenCalls(t,e),R()){V(t,"aparte-message-aborted",{messageId:e},l),this._updateMessage(t,e,{status:"completed"});return}let E=Y.from(w,H.UNKNOWN_ERROR),v=g===0?await y(E):"stands";if(v==="resend")continue;if(v==="stopped"){L();return}this._handleLifecycleError(t,e,E);return}}finally{this._turnsInFlight.delete(e)}}_turnsInFlight=new Set;_toolsForCurrentModel(){return Or(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(L=>L.id===e),l=(a>=0?r[a]:void 0)?.role==="user"?a+1:a,c=a>=0?r.slice(0,l):r,d={id:G(),role:"assistant",content:"",status:"pending",timestamp:Date.now()},u=i.addSiblingOf?.(e,d)??d.id,h=this._config.getModelConfig(),f=h.defaultProvider,_=this._providerFor(f);if(!_)return;let p=f?await this._resolveAuth(f):void 0,m=this._messagesToChatMessages(c),T=this._systemMessages();await this._streamTurn(i,u,_,[...T,...At(m)],h.defaultModel||"",p,{temperature:.4,rebuild:async()=>[...this._systemMessages(),...At(this._messagesToChatMessages(this._current(i,c)))]})}_systemMessages(){let t=[],e=this._config.resolveSystemPrompt();e&&t.push({role:"system",content:e});let s=this._config.resolveToolSystemPrompts();return s&&t.push({role:"system",content:s}),t}async _handleEdit(t){let{messageId:e,content:s,targetId:i}=t.detail??{};if(this._beginUserTurn(),!e||s===void 0)return;let r=this._resolveTarget(i,t);if(!r){console.warn("[AparteClient] aparte-edit \u2014 no target found");return}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,c=this._messagesToChatMessages(l),d=this._systemMessages(),u=this._config.getModelConfig(),h=u.defaultProvider,f=this._providerFor(h);if(!f)return;let _=h?await this._resolveAuth(h):void 0,p=G();r.appendMessage?.({id:p,role:"assistant",content:"",status:"pending",timestamp:Date.now()}),await this._streamTurn(r,p,f,[...d,...At(c)],u.defaultModel||"",_,{rebuild:async()=>[...this._systemMessages(),...At(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?ht(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=yt(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(bi)){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(bi);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}=me(t);return[...this._summaryMessage(e),...ce(s)]}_summaryMessage(t){return t===void 0?[]:[{role:"user",content:nn(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 p=this._byId(a,t),m=this._asRenderTarget(p);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 p of this._originChain(t)){let m=p;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 p=Array.isArray(t.detail?.files)?t.detail.files:[];r.appendMessage?.({id:G(),role:"user",content:e,timestamp:Date.now(),...p.length>0?{attachments:Cr(p)}:{}}),t.detail&&typeof t.detail=="object"&&(t.detail.echoed=!0)}let o=G(),l=this._config.getModelConfig(),c=i||l.defaultProvider;if(!c&&!this._modelRunsElsewhere){this._warnedNoModel||(this._warnedNoModel=!0,console.warn("[AparteClient] Send dropped: no model is selected. Call aparteGlobalConfig.setModelConfig({ defaultProvider, defaultModel }), mount <aparte-model-selector auto-select persist>, or register one provider with a single model \u2014 that one is selected on its own.")),this._handleLifecycleError(r,o,new Y("No provider selected. Please configure a provider.",H.CONFIG_NO_PROVIDER));return}let d=this._providerFor(c);if(!d){this._handleLifecycleError(r,o,new Y(`Provider '${c}' is not registered.`,H.CONFIG_MISSING_KEY,{providerId:c}));return}r.appendMessage?.({id:o,role:"assistant",content:"",status:"pending",timestamp:Date.now()});let u,h,f,_=Array.isArray(t.detail?.files)?t.detail.files:[];try{u=c?await this._resolveAuth(c):void 0;let p=this._selectFilesToInject(_),m=p.length>0?await this._filesToContentParts(p):[];f=m.length>0?m:void 0,h=this._buildMessages(e,r,f)}catch(p){this._handleLifecycleError(r,o,Y.from(p,H.UNKNOWN_ERROR));return}await this._streamTurn(r,o,d,h,s||l.defaultModel||"",u,{rebuild:async()=>this._buildMessages(e,r,f),..._.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}),At(i)}_toHistoryMessages(t){let{summary:e,messages:s}=me(t),i=0;for(let r=0;r<s.length;r++){let a=s[r];a.role==="assistant"&&a.status!=="error"&&!xr(a)&&(i=r+1)}return[...this._summaryMessage(e),...ce(s.slice(0,i))]}_selectFilesToInject(t){let e=this.options.rawFileInject==="none"?[]:this.options.rawFileInject==="images-only"?t.filter(i=>i.type.startsWith("image/")):t,s=this.options.fileInjectFilter;return s?e.filter(i=>s(i)):e}async _filesToContentParts(t){let e=/^(text\/|application\/(json|xml|javascript|typescript|x-yaml|yaml|toml|csv|markdown))/i,s=/\.(txt|md|markdown|json|jsonl|csv|tsv|xml|html|htm|css|js|mjs|cjs|ts|tsx|jsx|py|rb|java|c|cpp|h|go|rs|php|sh|bash|zsh|fish|yaml|yml|toml|ini|env|log|svg|graphql|gql)$/i;return(await Promise.all(t.map(r=>r.type.startsWith("image/")?new Promise((a,o)=>{let l=new FileReader;l.onload=()=>a({type:"image",image:l.result,mimeType:r.type}),l.onerror=()=>o(new Error(`Failed to read file: ${r.name}`)),l.readAsDataURL(r)}):e.test(r.type)||s.test(r.name)?new Promise((a,o)=>{let l=new FileReader;l.onload=()=>{let c=l.result,d=r.name.split(".").pop()??"";a({type:"text",text:`\`\`\`${d}
70
- // File: ${r.name}
71
- ${c}
72
- \`\`\``})},l.onerror=()=>o(new Error(`Failed to read file: ${r.name}`)),l.readAsText(r)}):(mi.has(r.name)||(mi.add(r.name),console.warn(`[aparte] ${r.name} (${r.type||"unknown type"}) is attached to the message but is not sent to the model: apart\xE9 inlines images and text files only. Handle it in your app (RAG, an upload) \u2014 the chip stays visible either way.`)),Promise.resolve(null))))).filter(r=>r!==null)}async _streamLoop(t,e,s,i,r,a=new AbortController,o,l){this._streamController!==a&&this._streamController?.abort(),this._streamController=a;let c=this.options.streamRunner??ss;return this._runViaStreamRunner(c,t,e,s,i,r,a,o,l)}async _runViaStreamRunner(t,e,s,i,r,a,o,l,c){let d=o.signal,u=this._targetIdOf(e),h=le({target:e,config:this._config,messageId:s,...u?{targetId:u}:{}}),f=r._meta?.prefixSegments,_,p,m,T=v=>{if(h(v),v.type==="tool-failed"&&(m=v.error),v.type==="run-done"&&(p=v.finishReason),v.type==="run-suspended"){let S=v.ticket;_={pending:v.pending,...typeof S=="string"?{ticket:S}:{}}}if(v.type==="run-start"&&f?.length&&!l)for(let S of f)e.addSegment?.(S)},L=async v=>{let S=await this._config.getTransport().chat(i,v,a,{providerId:i.id,signal:d});return typeof S=="string"?S:yr(S,d)},R=v=>{let S=this._config.getToolHandler(v);if(!S)return;let x={target:e,config:this._config};return(A,P)=>S(A,P,x)},b=!!this.options.approvalResolver,y=v=>{let S=this._config.getTools().find(x=>x.name===v);if(S)return{maxTurns:S.maxTurns,needsApproval:b?S.needsApproval:x=>{let A=this._config.ruleOnToolCall(x).verdict;return A==="allow"?!1:A}}},g=this._approvalResolverFor(e),w=v=>{if(m===void 0||v instanceof Y)return v;let S=v instanceof Error?v.message||v.name:typeof v=="string"?v:String(v);return S===m?new Y(S,H.UNKNOWN_ERROR,void 0,v):v};return{usage:await t({messageId:s,...i.id?{providerId:i.id}:{},...l?{deferral:l}:{},...c&&c.length>0?{files:c}:{},baseRequest:r,transportCall:L,toolLookup:R,toolConfigLookup:y,approvalResolver:g,emitter:T,signal:d,maxTurns:this.options.maxTurns,toolTimeoutMs:this.options.toolTimeoutMs,idGen:v=>v==="synthetic-tool"?G():`${v}-${G()}`}).catch(v=>{throw w(v)})??void 0,...p?{finishReason:p}:{},..._?{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),c=d=>{for(let u of e.slice(d+1))o[u.toolCallId]={kind:"decision",approved:!1,reason:Ul,by:"earlier-refusal"}};for(let[d,u]of e.entries()){if(s.aborted)break;let h={id:u.toolCallId,name:u.name,input:u.input??{}};if(u.reason==="approval"){let f;try{f=await l(h,s)}catch(_){if(!s.aborted&&_?.name!=="AbortError")throw _}if(!f||s.aborted)return;if(o[u.toolCallId]={kind:"decision",...f},f.approved)a.add(gi(h));else{c(d);break}}else if(u.reason==="external"){let f=null,_=gi(h);if(!r.has(_)&&!a.has(_))try{f=await this._gateBrowserTool(h,s,t,i)}catch(L){if(!s.aborted&&L?.name!=="AbortError")throw L;f=void 0}if(f===void 0||s.aborted)return;if(f&&!f.approved){o[u.toolCallId]={kind:"decision",...f},c(d);break}let p=f?.payload,m=p&&typeof p=="object"&&!Array.isArray(p)?{...h,input:{...h.input,...p}}:h,T=this._config.getToolHandler(u.name);try{if(!T)throw new Error(`No browser handler is registered for "${u.name}".`);let L=await T(m,s,{target:t,config:this._config});o[u.toolCallId]={kind:"result",content:L.content,...L.structuredContent!==void 0?{structuredContent:L.structuredContent}:{}}}catch(L){if(s.aborted)break;o[u.toolCallId]={kind:"failed",error:L instanceof Error?L.message:String(L)}}}}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?Lr(i,ke,{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 At([...this._systemMessages(),...a,...i>=0?ce([s[i]]):[]])}_closeDeferred(t){let s=[...t.getMessages?.()??[]].reverse().find(r=>r.role==="assistant");if(!s?.segments?.some($t))return;let i=s.segments.map(r=>{if(!$t(r))return r;let{deferred:a,...o}=r;return{...o,status:"aborted"}});t.updateMessage?.(s.id,{segments:i})}async resumeDeferred(t){let e=typeof t=="string"?this._byId(t):t??this.options.targetResolver?.()??null,s=e?this._asRenderTarget(e):this._scanForTarget();if(!s)return!1;let i=s.getMessages?.()??[],r=[...i].reverse().find(h=>h.role==="assistant"),a=(r?.segments??[]).filter($t),o=a.find(h=>h.deferred?.ticket)?.deferred?.ticket;if(!r||a.length===0||!o||this._resuming.has(r.id)||this._turnsInFlight.has(r.id))return!1;let l=this._config.getModelConfig(),c=r.model&&this._config.getAIProvider(r.model.providerId)?r.model:void 0,d=c?.providerId??l.defaultProvider,u=this._providerFor(d);if(!u)return console.warn("[AparteClient] Cannot resume the paused turn: no provider is selected."),!1;this._beginUserTurn(),this._resuming.add(r.id);try{let h=u.id?await this._resolveAuth(u.id):void 0,f=a.map(p=>({toolCallId:p.toolCall.id,name:p.toolCall.name,input:p.toolCall.input,reason:p.deferred.reason})),_=this._resumeBase(i,i.indexOf(r));await this._streamTurn(s,r.id,u,_,c?.modelId??l.defaultModel??"",h,{resume:{pending:f,ticket:o},rebuild:async()=>{let p=s.getMessages?.()??[],m=p.findIndex(T=>T.id===r.id);return m>=0?this._resumeBase(p,m):_},...c?.temperature!==void 0?{temperature:c.temperature}:{}})}finally{this._resuming.delete(r.id)}return!0}_resuming=new Set;_updateMessage(t,e,s){t.updateMessage&&t.updateMessage(e,s)}_handleLifecycleError(t,e,s){let i={id:`error-${G()}`,type:"error",content:s.message,code:s.code};if(Ms(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]});V(t,"aparte-message-error",{messageId:e,error:s},this._targetIdOf(t))}};function qr(n){return n.next?qr(n.next):"current"in n?n:null}var be=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=qr(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 Lt(n){return n.status==="streaming"||n.status==="pending"?!0:n.status===void 0&&n.role==="assistant"&&!n.content?.trim()&&!n.segments?.length}var vi=Symbol.for("aparte.dialogTriggers"),Ds=null,ve=null;function jl(n){Ds=n.target,ve=null}function Gl(n){ve=n.target}function zl(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=Ds===t&&ve===t;Ds=null,ve=null,i&&t.close()}}function Fr(n=document){let t=n;t[vi]||(t[vi]=!0,n.addEventListener("pointerdown",jl,!0),n.addEventListener("pointerup",Gl,!0),n.addEventListener("click",zl))}var _s="defer-hydration",Gt=new WeakMap,zt=new WeakMap,Rt=new WeakSet,ye=new WeakSet,Bs=new WeakMap,yi=new WeakSet;function wi(n){if(ye.has(n))return!1;if(zt.has(n))return!0;let t=n.closest(`[${_s}]`);if(!t)return!1;zt.set(n,t);let e=Gt.get(t);if(!e){e=[],Gt.set(t,e);let s=new MutationObserver(()=>{t.hasAttribute(_s)||Kl(t)});s.observe(t,{attributes:!0,attributeFilter:[_s]}),Bs.set(t,s)}return e.push(n),!0}function Kl(n){Bs.get(n)?.disconnect(),Bs.delete(n);let t=Gt.get(n)??[];Gt.delete(n);for(let e of t)zt.delete(e),e.isConnected&&!ye.has(e)&&e.connectedCallback?.()}function $(n){if(yi.has(n))return;yi.add(n);let t=n.prototype,e=t.connectedCallback,s=t.attributeChangedCallback,i=t.disconnectedCallback,r=n.observedAttributes??[];t.connectedCallback=function(){if(wi(this)){Rt.add(this);return}if(Rt.has(this)){Rt.delete(this);for(let a of r){let o=this.getAttribute(a);o!==null&&s?.call(this,a,null,o)}}ye.add(this),e?.call(this)},s&&(t.attributeChangedCallback=function(a,o,l){if(wi(this)){Rt.add(this);return}s.call(this,a,o,l)}),t.disconnectedCallback=function(){let a=zt.get(this);if(a){zt.delete(this);let o=Gt.get(a);o&&o.splice(o.indexOf(this),1);return}Rt.has(this)||(ye.delete(this),i?.call(this))}}function K(n){return n===""?!0:!!n}var Le=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",K(t))}get selected(){return this.hasAttribute("selected")}set selected(t){this.toggleAttribute("selected",K(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)}};$(Le);customElements.get("aparte-option")||customElements.define("aparte-option",Le);var xe=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",K(t))}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(t){this.toggleAttribute("collapsed",K(t))}get loading(){return this.hasAttribute("loading")}set loading(t){this.toggleAttribute("loading",K(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=k(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,` ${k(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":""})}};$(xe);customElements.get("aparte-optgroup")||customElements.define("aparte-optgroup",xe);var Ie=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",K(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(k(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=k(this),r=document.createElement("div");r.className="aparte-select-trigger",r.setAttribute("tabindex","0"),r.setAttribute("role",e?"button":"combobox"),r.setAttribute("aria-haspopup","listbox"),r.setAttribute("aria-expanded","false"),r.setAttribute("aria-label",this.getAttribute("aria-label")||t);let a=document.createElement("span");a.className="aparte-select-label";let o=document.createElement("span");o.className="aparte-select-label-text",o.textContent=t;let l=document.createElement("span");l.className="aparte-select-label-sizer",l.setAttribute("aria-hidden","true"),a.append(o,l);let c=document.createElement("span");c.className="aparte-select-chevron",c.innerHTML=i.getIcon("expand"),r.append(a,c);let d=document.createElement("div");d.className="aparte-select-dropdown",d.hidden=!this._isOpen;let u=e?this._buildSearchInput(i):null;u&&d.appendChild(u);let h=document.createElement("div");h.className="aparte-select-options",h.setAttribute("role","listbox"),h.setAttribute("aria-label",r.getAttribute("aria-label")??t),h.id=this.id?`${this.id}-listbox`:`aparte-listbox-${++n._listboxSeq}`,r.setAttribute("aria-controls",h.id),u?.setAttribute("aria-controls",h.id),s.forEach(f=>{(f.tagName==="APARTE-OPTION"||f.tagName==="APARTE-OPTGROUP")&&h.appendChild(f)}),d.appendChild(h),this._observer?.disconnect(),this.innerHTML="",this.appendChild(r),this.appendChild(d),this._trigger=r,this._dropdown=d,this._searchInput=d.querySelector(".aparte-select-search"),this.isConnected&&this._setupMutationObserver(),this._updateTriggerLabel()}_setupMutationObserver(){this._observer?.disconnect(),this._observer=new MutationObserver(()=>{this._updateDropdownContent(),this._updateTriggerLabel(),this._restoreActive()}),this._observer.observe(this,{childList:!0,subtree:!0})}_restoreActive(){!this._isOpen||this._activeIndex<0||this.querySelector("aparte-option[data-active]")||this._setActive(this._activeIndex)}_updateDropdownContent(){if(!this._trigger||!this.contains(this._trigger)){this._render();return}let t=this.querySelector(".aparte-select-options");if(!t){this._render();return}let e=Array.from(this.children).filter(s=>s.className!=="aparte-select-trigger"&&s.className!=="aparte-select-dropdown");e.length!==0&&(this._observer?.disconnect(),t.innerHTML="",e.forEach(s=>{t.appendChild(s)}),this.isConnected&&this._observer?.observe(this,{childList:!0,subtree:!0}),this._updateTriggerLabel(),this._restoreActive())}_setupEventListeners(){this._trigger?.removeEventListener("click",this._boundHandleTriggerClick),this._trigger?.addEventListener("click",this._boundHandleTriggerClick),this._trigger?.removeEventListener("keydown",this._boundHandleTriggerKeydown),this._trigger?.addEventListener("keydown",this._boundHandleTriggerKeydown),this.removeEventListener("click",this._boundHandleOptionClick),this.addEventListener("click",this._boundHandleOptionClick),this._searchInput?.removeEventListener("input",this._boundHandleSearchInput),this._searchInput?.addEventListener("input",this._boundHandleSearchInput),document.addEventListener("click",this._boundHandleDocumentClick),document.addEventListener("keydown",this._boundHandleKeydown)}_handleOptionClick(t){let e=t.target.closest("aparte-option");e&&!e.hasAttribute("disabled")&&this._selectOption(e)}_handleDocumentClick(t){let e=ht(t);(!e||!this.contains(e))&&this._closeDropdown()}_handleKeydown(t){if(!this._isOpen)return;let e=pt(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=>Ur(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 Ur(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 Ur(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()}$(Ie);customElements.get("aparte-select")||customElements.define("aparte-select",Ie);var Re=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>`}};$(Re);customElements.get("aparte-progress-spinner")||customElements.define("aparte-progress-spinner",Re);var Oe=class extends HTMLElement{static get observedAttributes(){return["name"]}_unsubscribe=null;connectedCallback(){this._render(),this._unsubscribe=ut(this,()=>this._render())}disconnectedCallback(){this._unsubscribe?.(),this._unsubscribe=null}attributeChangedCallback(){this.isConnected&&this._render()}_render(){let t=this.getAttribute("name"),e=t?k(this).getIcon(t):null;this.innerHTML=e??"",this.firstElementChild?.setAttribute("aria-hidden","true")}};$(Oe);customElements.get("aparte-icon")||customElements.define("aparte-icon",Oe);function Wr(n){let t=n.activeElement;for(;t?.shadowRoot?.activeElement;)t=t.shadowRoot.activeElement;return t}function ln(n,t){for(let e=n;e;e=e.parentNode??(e instanceof ShadowRoot?e.host:null))if(e===t)return!0;return!1}function jr(n,t,e,s,i){let r=document.createElement("button");r.type="button",r.className="aparte-btn aparte-btn--icon aparte-btn--sm aparte-btn--ghost aparte-elic-hide",r.setAttribute("aria-expanded","true"),r.innerHTML=e.getIcon("expand");let a=document.createElement("button");a.type="button",a.className="aparte-btn aparte-btn--ghost aparte-elic-reveal",a.setAttribute("aria-expanded","false");let o=document.createElement("span");a.append(o),a.insertAdjacentHTML("beforeend",e.getIcon("collapse"));let l=c=>{let d=c.t("elicitationHide");r.setAttribute("aria-label",d),r.title=d,o.textContent=c.t("elicitationWaiting")};return l(e),r.addEventListener("click",()=>{n.setAttribute("data-collapsed",""),i(),a.focus()}),a.addEventListener("click",()=>{n.removeAttribute("data-collapsed"),i(),s()}),t.prepend(r),n.append(a),{relabel:l}}var Pe=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=ut(this,()=>this._relabelPending()),k(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(){k(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=k(this);j(t,()=>this._pending.relabel())}_present=t=>{let e=this._getComposer();return e?new Promise((s,i)=>{let r=!1,a={},o=Wr(document),l=()=>{let A=t.message;return String(typeof A=="function"?A():A??"")},c="aparte-chat, [data-aparte-chat], [data-aparte-host]",d='input, textarea, select, [contenteditable]:not([contenteditable="false"])',u=e.closest(c)??e.parentElement??e,h=!(o instanceof HTMLElement)||o===document.body,f=h?null:o,_=f!==null&&ln(f,u),p=f!==null&&f.matches(d),m=f!==null&&!_&&(p||f.tagName==="IFRAME"||f.closest(c)!==null),T=A=>{let P=e.querySelector(":scope > .aparte-elic-status");P||(P=document.createElement("span"),P.className="aparte-sr-only aparte-elic-status",P.setAttribute("role","status"),e.appendChild(P));let q=P;q.textContent="",A&&setTimeout(()=>{q.isConnected&&(q.textContent=A)},60)},L=(A,P)=>{if(m){T(P);return}let q=window.scrollX,B=window.scrollY;p&&_?(A.el.hasAttribute("tabindex")||A.el.setAttribute("tabindex","-1"),A.el.hasAttribute("role")||A.el.setAttribute("role","group"),P&&!A.el.hasAttribute("aria-label")&&A.el.setAttribute("aria-label",P),A.el.focus()):A.focus(),h&&(window.scrollX!==q||window.scrollY!==B)&&window.scrollTo(q,B)},R=()=>{if(r)return!1;r=!0,this._pending=null;let A=Wr(document),P=A instanceof Node&&ln(A,e);return e.hidePanel(a.token),T(""),P&&((!m&&f!==null&&f.isConnected&&!ln(f,e)?f:null)??e).focus(),!0},b=A=>{R()&&s(A)},y=(A="aborted")=>{R()&&i(new dt(A))};if(t.signal){if(t.signal.aborted){y();return}t.signal.addEventListener("abort",()=>y(),{once:!0})}let g=k(this);if(t.kind==="approval"){let A=()=>B.isComplete()&&!B.el.hasAttribute("data-collapsed"),P=()=>A()?"submit":"none",q=()=>e.setPanelSubmitEnabled(A(),P()),B=j(g,()=>Hr(t.message,t.options??[],q,t.details,t.allowOther??!0));B.onSettle(xt=>b({action:"accept",content:xt}));let et=jr(B.el,B.dismiss,g,()=>B.focus(),q);this._pending={abort:()=>y(),composer:e,relabel:()=>{B.relabel(),et.relabel(k(this))}},a.token=e.showPanel(B.el,{submitEnabled:B.isComplete(),mode:P(),onSubmit:()=>{B.isComplete()&&b({action:"accept",content:B.getContent()})},onEvict:()=>y()}),L(B,l());return}let w=t.schema??{type:"string"},E=()=>{let A=v.el.hasAttribute("data-collapsed");e.setPanelSubmitEnabled(!A&&v.canProceed(),A?"none":v.mode())},v=j(g,()=>Br(t.message,w,E)),S=document.createElement("button");S.type="button",S.className="aparte-btn aparte-elic-skip",S.textContent=g.t("elicitationSkip"),S.addEventListener("click",()=>b({action:"decline"})),v.dismiss.appendChild(S);let x=jr(v.el,v.dismiss,g,()=>v.focus(),E);v.onSettle(A=>b({action:"accept",content:A})),this._pending={abort:()=>y(),composer:e,relabel:()=>{v.relabel();let A=k(this);S.textContent=A.t("elicitationSkip"),x.relabel(A)}},a.token=e.showPanel(v.el,{submitEnabled:v.canProceed(),mode:v.mode(),onEvict:()=>y(),onSubmit:()=>{v.isComplete()&&b({action:"accept",content:v.getContent()})}}),L(v,l())}):Promise.reject(new dt("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")&&($(Pe),customElements.define("aparte-elicitation",Pe));function ra(n){return!n.hasAttribute("loading")&&!n.querySelector("aparte-chat-bubble")}var Ne=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=Mr(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="${M(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||ra(t))}};$(Ne);customElements.get("aparte-chat")||customElements.define("aparte-chat",Ne);var Gr=n=>!!n&&typeof n.getMessages=="function"&&typeof n.updateMessage=="function";function Vl(n){let t=Z(n);if(Gr(t))return t;let e=n.closest("aparte-chat-viewport");return Gr(e)?e:null}function Yl(n,t){let e=Vl(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 rt(n,t,e){let s=document.createElement(n);return s.className=t,e!==void 0&&(s.textContent=e),s}function Yt(n,t){let e=rt("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 Ql(n){let{kind:t,locale:e}=n,s=rt("div","aparte-checkpoint");s.setAttribute("role","group"),s.setAttribute("aria-label",e.checkpointGroup??"Context summary"),s.setAttribute("data-state",t);let i=rt("div","aparte-checkpoint__row aparte-divider aparte-divider--label"),r=rt("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=rt("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(rt("span","aparte-sr-only",`: ${n.reason}`)))),r.appendChild(o),t==="done"||t==="legacy")if(n.confirming&&t==="done"){let l=rt("span","aparte-checkpoint__confirm"),c=rt("span","aparte-checkpoint__question",e.checkpointRestoreConfirm??"Send the original messages to the model again?");c.id=`${n.summaryId}-question`;let d=Yt("restore-confirm",e.checkpointRestore??"Restore");d.setAttribute("aria-describedby",c.id),l.append(c,d,Yt("restore-cancel",e.cancel??"Cancel")),r.appendChild(l)}else{let l=Yt("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(Yt("restore",e.checkpointRestore??"Restore"))}else t==="failed"&&r.appendChild(Yt("retry",e.retry??"Retry"));if(t==="done"||t==="legacy"){let l=rt("div","aparte-checkpoint__summary aparte-segment-content");l.id=n.summaryId,n.open||(l.hidden=!0),s.appendChild(l)}return s}var zr=!1;function Jl(n){zr||(zr=!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 cn(n){let t=typeof n.fallback=="string"&&n.fallback.trim()?n.fallback:null;t||Jl(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 wt(n,t){let e=Qs(n,t);return e||(gr(t),Qs(n,t))}function Qt(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 Zt=new Map;function Xl(){let n=[...Zt].filter(([e])=>!e.firstChild);Zt.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 Zl=0,De=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-${++Zl}`;_avatarCleanup=null;_avatarFromProvider=!1;_siblingCount=1;_wroteRootLabel=!1;_wroteBarLabel=!1;_wroteArrowLabels=!1;_drawnShell=null;_siblingIndex=0;_editing=!1;_editInput=null;_editReturnAction=null;static get observedAttributes(){return["data-role","content","timestamp","message-id","streaming","name","data-checkpoint","data-checkpoint-reason"]}constructor(){super()}_onConfigChange=t=>{let e=t.detail;e?.config&&e.config!==this._cfg||(this._updateActionBar(),this._updateName(),this._updateLocalizedLabels(),this._updateWaiting(),this._updateFinishNote(),this._checkpointDrawn="",this._updateCheckpoint(),this._renderAvatar(),this._redrawSegmentsWhoseRendererChanged(),this._relabelSegments(),j(this._cfg,()=>Hi(this)),zi(this),this._syncSources(),this._updateTimestamp(this.getAttribute("timestamp")),this._redrawQueued||(this._redrawQueued=!0,queueMicrotask(()=>{this._redrawQueued=!1,this.isConnected&&this._redrawIfStale()})))};_redrawQueued=!1;_drawnWithVersion=0;_drawn=new Map;_releasedWhileDetached=!1;_releaseCheckQueued=!1;_offRenderers=null;_toolRendererFor(t){if(t.type!=="tool_call")return null;let e=this._cfg;if(wt("tool_call",e)!==kt)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=Ys(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=wt(t.type,s),r=e.el;this._release(t.id);let a=i?Qt(j(s,()=>i.render(t)),t):cn(t);return a?(r.replaceWith(a),this._install(t,a,i),!0):(r.remove(),!0)}_stillDrawnByCurrent(t,e){return wt(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!==Q||this._redrawSegmentsWhoseRendererChanged()};_keepsItsDrawing(t,e){return(Zs(e.renderer)||t.type==="tool_call"&&Zs(e.tool))&&this._stillDrawnByCurrent(t,e)}_redrawIfStale(){if(!(this._streaming||this._editing||J(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=J(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=wt(t.type,this._cfg);if(!e?.relabel)continue;let s=this._segmentsEl.querySelector(`:scope > [data-segment-id="${z(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 k(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??=Sr(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._syncSources(),this._updateWaiting()}_syncSources(){let t=this._segmentsEl,e=t?.parentElement;if(!t||!e)return;let s=this._segments.flatMap(i=>i.type==="text"?i.sources??[]:[]);Ji(e,t,s,this._cfg)}_replaceSegments(t){let e=[...t];if(this._resyncKeepingCards(e)){this._syncSources();return}this._segments=e,this._renderSegments()}_resyncKeepingCards(t){if(!this._segmentsEl||t.length!==this._segments.length||t.some((s,i)=>s.id!==this._segments[i].id||!this._drawn.has(s.id)))return!1;let e=new Set(t.filter(s=>this._keepsItsDrawing(s,this._drawn.get(s.id))).map(s=>s.id));if(e.size===0)return!1;this._segments=t,this._drawnWithVersion=J(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),t.type==="text"&&t.sources&&this._syncSources(),this._updateWaiting()}updateSegment(t,e){let s=this._segments.findIndex(i=>i.id===t);if(s!==-1){let i=$s(this._segments[s],e);this._segments[s]=i,this._applySegmentUpdate(t,i,e),"sources"in e&&this._syncSources(),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="${z(t)}"]`)?.remove(),this._syncSources(),this._updateWaiting(),this._syncCopyAction()}setAttachments(t){this._attachments=t,this._updateAttachments(),this._updateWaiting()}setUsage(t){this._usage=t??null,this._updateActionBar()}setFinishReason(t){this._finishReason=t??null,this._updateFinishNote()}setContextSummary(t,e){this._contextSummary=t??null,e?.legacy!==void 0&&(this._legacyCompaction=e.legacy),this._contextSummary||(this._confirmingRestore=!1,this._isLegacyCompaction()||(this._checkpointOpen=!1)),this._updateCheckpoint()}setSiblings(t,e){this._siblingCount=t,this._siblingIndex=e,this._updateBranchPicker()}updateMessage(t){if("role"in t&&(this._role=t.role,this._updateRole()),"content"in t&&(this._content=t.content,this._updateContent()),"segments"in t&&this._replaceSegments(t.segments),"timestamp"in t&&this._updateTimestamp(t.timestamp),"status"in t){let e=t.status==="streaming"||t.status==="pending";this._updateStreaming(e)}"attachments"in t&&(this._attachments=t.attachments??[],this._updateAttachments(),this._updateWaiting()),"finishReason"in t&&this.setFinishReason(t.finishReason),("contextSummary"in t||"compaction"in t)&&this.setContextSummary("contextSummary"in t?t.contextSummary:this._contextSummary,"compaction"in t?{legacy:t.compaction===!0}:void 0)}_updateFinishNote(){let t=this._finishReason==="length"&&!this._streaming&&this._role!=="user",e=this.querySelector(".aparte-finish-note");if(!t){e?.remove();return}if(!e){let s=this.querySelector(".aparte-message-content");if(!s)return;e=document.createElement("div"),e.className="aparte-finish-note",s.after(e)}e.textContent=this._cfg.getLocale().responseCutOff??"Cut off at the model's length limit."}_isLegacyCompaction(){return this._legacyCompaction??this.getAttribute("data-kind")==="compaction"}_checkpointKind(){let t=this.getAttribute("data-checkpoint");return t==="pending"||t==="failed"?t:this._contextSummary?"done":this._isLegacyCompaction()?"legacy":null}_checkpointSummaryText(){return this._contextSummary?this._contextSummary.summary:this._content}_updateCheckpoint(t){let e=this.querySelector(".aparte-message");if(!e)return;let s=this._checkpointKind();e.toggleAttribute("data-superseded",this._isLegacyCompaction()&&!this._contextSummary);let i=this.querySelector(":scope > .aparte-checkpoint");if(!s){let h=i&&document.activeElement&&i.contains(document.activeElement);i?.remove(),this._checkpointDrawn="",h&&(e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1"),e.focus({preventScroll:!0}));return}let r=this.getAttribute("data-checkpoint-reason")??"",a=this._checkpointSummaryText(),o=JSON.stringify([s,this._contextSummary?.count,this._contextSummary?.createdAt,r,this._checkpointOpen,this._confirmingRestore,this._checkpointOpen?a:""]);if(i&&!t&&o===this._checkpointDrawn)return;let l=document.activeElement,c=i&&l&&i.contains(l)?l.getAttribute("data-checkpoint-action"):null,d=Ql({kind:s,count:this._contextSummary?.count,reason:r,open:this._checkpointOpen,confirming:this._confirmingRestore,summaryId:this._checkpointId,locale:this._cfg.getLocale()});if(this._checkpointOpen&&(s==="done"||s==="legacy")){let h=d.querySelector(".aparte-checkpoint__summary");h&&(h.innerHTML=this._cfg.renderMarkdown(a))}i?i.replaceWith(d):this.prepend(d),this._checkpointDrawn=o;let u=t??c;u&&d.querySelector(`[data-checkpoint-action="${z(u)}"]`)?.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;Yl(this,{messageId:i,targetId:this._resolveTargetId()}),this.setContextSummary(null);break}case"retry":{let i=this._resolveTargetId(),r=this._cfg.getCompactor();r?r.compact({target:Z(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=J(this._cfg));let e=wt(t.type,this._cfg);if(e){let s=Qt(j(this._cfg,()=>e.render(t)),t);s&&(this._segmentsEl.appendChild(s),this._install(t,s,e))}else{let s=cn(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="${z(t)}"]`);if(!i){this._renderSegments();return}if(this._releasedWhileDetached)return;let r=wt(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="${z(t)}"]`);l&&l!==o.el&&(o.el=l,o.tool=e.type==="tool_call"?Ys(l):null)}}else{let o=Qt(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="${M(e)}" role="article" aria-label="${M(this._getAriaLabel())}">
87
- <div class="aparte-avatar" data-role="${M(e)}"></div>
88
- <div class="aparte-body">
89
- <div class="aparte-header">
90
- <span class="aparte-name">${I(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="${M(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="${M(this._cfg.getLocale().nextResponse??"Next response")}">${this._cfg.getIcon("nextBranch")}</button>
114
- </div>
115
- <div class="aparte-action-bar" role="toolbar" aria-label="${M(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"),c=u=>{let h="",f=u.ownerDocument.createTreeWalker(u,NodeFilter.SHOW_TEXT);for(let _=f.nextNode();_;_=f.nextNode()){let p=_.parentElement?.closest('[aria-hidden="true"], [hidden]');(!p||!u.contains(p))&&(h+=_.textContent??"")}return h},d=u=>!!u&&(u.hasAttribute("aria-label")||u.hasAttribute("aria-labelledby")||u.hasAttribute("title")||/\p{L}/u.test(c(u)));if((o||l)&&!d(o)&&!d(l)){let u=this._cfg.getLocale();o?.setAttribute("aria-label",u.previousResponse??"Previous response"),l?.setAttribute("aria-label",u.nextResponse??"Next response"),this._wroteArrowLabels=!0}}this._actionBarEl?.addEventListener("keydown",this._onActionBarKeydown),this._branchPickerEl=this.querySelector(".aparte-branch-picker"),this._footerEl=this.querySelector(".aparte-footer"),this._transcriptBusy=!!this.closest("aparte-chat-viewport")?.hasAttribute("data-busy"),this._updateActionBar(),this._renderAvatar(),this._streaming&&this._updateStreaming(!0),this._updateWaiting(),this._updateFinishNote(),this._updateCheckpoint()}_updateWaiting(){let e=!(this._segmentsEl?Array.from(this._segmentsEl.children).some(f=>!f.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"&&(bt(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 c=this.querySelector(".aparte-message");c&&c.toggleAttribute("data-empty",e&&!this._streaming&&this._attachments.length===0);let d=this.querySelector(".aparte-waiting");if(!d||(d.hidden=!o,!o))return;let u=this._cfg.getLocale().typing,h=d.querySelector(".aparte-sr-only");h&&h.textContent!==u&&(h.textContent=u)}_renderAvatar(){let t=this.querySelector(".aparte-avatar");if(!t)return;if(this._avatarCleanup){try{this._avatarCleanup()}catch{}this._avatarCleanup=null}let e=this._cfg.getAvatarProvider();if(!e){this._avatarFromProvider&&(t.replaceChildren(),this._avatarFromProvider=!1),this._markAvatarImage(t);return}t.textContent="";let s=e.render(this._role,t);this._avatarFromProvider=!0,typeof s=="function"&&(this._avatarCleanup=s),this._markAvatarImage(t)}_markAvatarImage(t){if(t.firstChild){Zt.delete(t),t.removeAttribute("data-image");return}Zt.size===0&&queueMicrotask(Xl),Zt.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=J(this._cfg),this._contentEl.style.display="",j(this._cfg,()=>Ce(this,this._contentEl,this._content,this._streaming)),this._updateWaiting(),this._streaming||this._highlightContentCode()}}_highlightContentCode(){!this._contentEl||!this._cfg.hasHighlightProvider()||this._contentEl.querySelectorAll("pre > code:not([data-aparte-highlighted])").forEach(t=>{let e=t.textContent??"";if(!e.trim())return;let i=t.className.match(/language-([\w+#-]+)/i)?.[1]??"";if(this._cfg.hasCodeLanguageRenderer(i)||t.closest(".aparte-code-drawing"))return;let r=t.parentElement;t.setAttribute("data-aparte-highlighted",""),Promise.resolve(this._cfg.highlightCode(e,i,{fallback:!1})).then(a=>{let o=(a??"").trim();!o||!r||!this._contentEl?.contains(r)||(/^<pre[\s>]/i.test(o)?Gs(r,o):t.innerHTML=o)}).catch(()=>{t.removeAttribute("data-aparte-highlighted")})})}_renderSegments(){if(this._segmentsEl){this._drawnWithVersion=J(this._cfg),this._releaseAll(),this._segmentsEl.innerHTML="";for(let t of this._segments){let e=wt(t.type,this._cfg);if(e){let s=Qt(j(this._cfg,()=>e.render(t)),t);s&&(this._segmentsEl.appendChild(s),this._install(t,s,e))}else{let s=cn(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(),this._syncSources()}}_reflectError(){let t=this.querySelector(".aparte-message");if(!t)return;this._segments.some(s=>s.type==="error")?t.setAttribute("data-error",""):t.removeAttribute("data-error")}_updateTimestamp(t){let e=this.querySelector(".aparte-timestamp");if(!(!e||!t))try{let s=new Date(isNaN(Number(t))?t:Number(t));e.textContent=s.toLocaleTimeString(this._cfg.getLocale().tag||void 0,{hour:"2-digit",minute:"2-digit"})}catch{e.textContent=""}}_getAriaLabel(){let t=this._cfg.getLocale(),e=this.getAttribute("name");return e?(t.messageFrom||"Message from {name}").replace("{name}",()=>e):this._role==="user"?t.yourMessage??"Your message":t.assistantResponse??"Assistant response"}_updateAttachments(){if(!this._attachmentsEl)return;if(this._role!=="user"||this._attachments.length===0){this._attachmentsEl.hidden=!0,this._attachmentsEl.innerHTML="";return}this._attachmentsEl.hidden=!1;let t=this._cfg.getAttachmentRenderer?.();if(t){this._attachmentsEl.replaceChildren();for(let r of this._attachments){let a=Qt(j(this._cfg,()=>t(r)));a&&this._attachmentsEl.appendChild(a)}return}this._attachmentsEl.innerHTML=this._attachments.map(r=>{let a=I(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="${I(r.type)}"><img class="aparte-thumbnail__image" src="${I(r.url)}" alt="${a}" loading="lazy" /><span class="aparte-thumb__name">${a}</span></div>`;let o=this._isOpenableUrl(r.url)?` data-url="${I(r.url)}"`:"";return`<div class="aparte-thumbnail aparte-thumb aparte-thumb--file" title="${a}" data-type="${I(r.type)}"${o}><span class="aparte-thumbnail__label">${I(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?Vt(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(d=>!d.disabled);if(i.length===0)return;let r=document.activeElement,a=i.findIndex(d=>d===r);if(a===-1&&e.key!=="Home"&&e.key!=="End")return;let l=(this.closest("[dir]")?.getAttribute("dir")??document.documentElement.dir)==="rtl"?"ArrowLeft":"ArrowRight",c;e.key==="Home"?c=0:e.key==="End"?c=i.length-1:e.key===l?c=(a+1)%i.length:c=(a-1+i.length)%i.length,e.preventDefault();for(let d of this._rovingButtons())d.tabIndex=d===i[c]?0:-1;i[c]?.focus()};_syncFooterVisibility(){if(this._actionBarEl&&(this._actionBarEl.hidden=this._actionBarEl.children.length===0),this._setRovingIndex(),!this._footerEl)return;let t=!this._actionBarEl||this._actionBarEl.hidden,e=!this._branchPickerEl||this._branchPickerEl.hidden;this._footerEl.hidden=t&&e,this.querySelector(".aparte-message")?.toggleAttribute("data-branches",!e)}_appendCustomActions(){if(this._actionBarEl)for(let t of this._cfg.getActions("bubble")){if(!(t.bubble?.roles??["user","assistant"]).includes(this._role))continue;let s=document.createElement("button");s.type="button",s.className="aparte-btn aparte-btn--icon aparte-btn--sm aparte-action-btn aparte-action-custom",s.dataset.action=`custom:${t.id}`,s.setAttribute("aria-label",t.label),s.setAttribute("title",t.label),s.innerHTML=t.icon.startsWith("<")?t.icon:this._cfg.getIcon(t.icon)??t.iconFallback??"",this._actionBarEl.appendChild(s)}}_actionButtonHtml(t,e,s){switch(t){case"copy":{let i=s.copy??"Copy";return`<button type="button" class="aparte-btn aparte-btn--icon aparte-btn--sm aparte-action-btn aparte-action-copy" data-action="copy" aria-label="${M(i)}" title="${M(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="${M(i)}" title="${M(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="${M(i)}" title="${M(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="${M(i)}" title="${M(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="${M(i)}" title="${M(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="${M(i)}" title="${M(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="${M(e)}" title="${M(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="${M(s)}" title="${M(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();zs(r).then(()=>{e.innerHTML=a.check(),e.setAttribute("data-copied","");let l=o.copied??o.copy??"Copied";e.setAttribute("title",l),e.setAttribute("aria-label",l),setTimeout(()=>{e.removeAttribute("data-copied"),e.innerHTML=a.copy();let c=o.copy??"Copy";e.setAttribute("title",c),e.setAttribute("aria-label",c)},2e3)}).catch(()=>{console.warn("[aparte] Clipboard write failed")});break}case"retry":{if(!i)break;let r=this._resolveTargetId(),a={messageId:i,targetId:r};this.dispatchEvent(new CustomEvent("aparte-retry",{bubbles:!0,composed:!0,detail:a}));break}case"edit":{this._enterEditMode();break}case"edit-save":{this._exitEditMode(!0);break}case"edit-cancel":{this._exitEditMode(!1);break}case"feedback-positive":case"feedback-negative":{if(!i)break;let r=s==="feedback-positive"?"positive":"negative";e.setAttribute("data-submitted","");let a={messageId:i,value:r};this.dispatchEvent(new CustomEvent("aparte-feedback",{bubbles:!0,composed:!0,detail:a}));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()}};$(De);customElements.get("aparte-chat-bubble")||customElements.define("aparte-chat-bubble",De);var Be=class extends HTMLElement{static get observedAttributes(){return["visible","text"]}get _cfg(){return k(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())}};$(Be);customElements.get("aparte-chat-status")||customElements.define("aparte-chat-status",Be);function Kr(n,t){if(n.role!=="assistant"||n.segments?.length||typeof n.content!="string"||!n.content.trim())return n;let e=Ci(n.content,{blocks:t});return e.length<=1&&e.every(i=>i.type==="text")?n:fn({...n,segments:e})}function fn(n){return Object.defineProperty(n,en,{value:!0,enumerable:!1}),n}function Vr(n){return n[en]===!0}var He=class extends HTMLElement{_container=null;_scrollBtn=null;_bottomSpacer=null;_fwSpacerHeight=0;_spacerRafId=null;_spacerFrozenUntil=0;_layoutTransitionMs=0;_repo=new be;_isAutoScrollEnabled=!0;_lastScrollTop=0;_lastScrollHeight=0;_lastMutationAt=Number.NEGATIVE_INFINITY;_settleShadowMs=100;_settleBoundPx=100;_ownScrollAt=Number.NEGATIVE_INFINITY;_readerInputAt=Number.NEGATIVE_INFINITY;_ownScrollWindowMs=1e3;_settleWindowMs=400;_glideUntil=0;_glideWindowMs=450;_glideSettleTimer=null;_settleUntil=0;_settleRafId=null;_scrollKeys=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," "]);_scrollThreshold=50;_smoothScrollOnce=!1;_maxRenderedBubbles=1e3;_resizeObserver=null;_mutationObserver=null;_tailObserver=null;_tail=[];_tailHeights=new WeakMap;_onDisclosureToggle=()=>{this._scheduleSpacerUpdate()};_overlayRoot=null;_overlayObserver=null;_overlayAttrObserver=null;_overlayInset=-1;_transcriptInset=-1;_boundResetHandler=null;_checkpointState=null;_stopCheckpointState=null;_frameworkManagedDOM=!1;static get observedAttributes(){return["scroll-threshold","max-rendered-bubbles","loading"]}get loading(){return this.hasAttribute("loading")}set loading(t){this.toggleAttribute("loading",K(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=k(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 ge({ownId:()=>Tr(this)??(this.id||void 0),bubbleOf:t=>this.querySelector(`aparte-chat-bubble[message-id="${z(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!==k(this))return;this._applyDirection(),this._scrollBtn?.setAttribute("aria-label",k(this).t("scrollToBottom")),(this._frameworkManagedDOM?this:this.querySelector(".aparte-viewport-container"))?.setAttribute("aria-label",k(this).t("transcript"))};_nameScrollSurface(t){t.setAttribute("tabindex","0"),t.hasAttribute("role")||t.setAttribute("role","log"),t.setAttribute("aria-label",k(this).t("transcript"))}_applyDirection(){let t=this.querySelector(".aparte-viewport-container");if(!t)return;let e=k(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,...Mi(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=Hs(r.segments,i,s,k(this).getSegmentDefaults(i.type));r.segments.push(a),this._notifyBubble(s,"addSegment",a),this._autoScroll()}updateSegment(t,e,s){let i=s===void 0&&typeof e=="object",r=i?this._activeMessageId():t,a=i?t:e,o=i?e:s;if(!r)return;let l=this._repo.getMessageById(r);if(!l?.segments)return;let c=l.segments.findIndex(d=>d.id===a);if(c!==-1){let d=l.segments[c],u=Ei(d,o);l.segments[c]=$s(d,u),this._notifyBubble(r,"updateSegment",{segmentId:a,updates:u})}}removeSegment(t,e){let s=e===void 0,i=s?this._activeMessageId():t,r=s?t:e;if(!i||!r)return;let a=this._repo.getMessageById(i);if(a?.segments){let o=a.segments.findIndex(l=>l.id===r);o!==-1&&(a.segments.splice(o,1),Li(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 Ti(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",qs(e.status)&&this._settleSegments(t,s)),this._notifyBubble(t,"update",e),e.status&&this._syncBusy(),this._autoScroll())}addMessage(t){let e=Se({...t});Lt(t)&&(e.isStreaming=!0),this._repo.addOrUpdateMessage(this._repo.headId,e),this._pruneRenderedBubbles(),this._syncBusy(),this._autoScroll()}appendMessage(t,e){t=Kr(t,k(this).getStreamBlocks());let s=e?.historical?Se(t):t.segments?.length?{...t,segments:t.segments.reduce((i,r)=>(i.push(Hs(i,r,t.id,k(this).getSegmentDefaults(r.type))),i),[])}:{...t};if(!e?.historical&&Lt(t)&&(s.isStreaming=!0),Vr(t)&&fn(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),Lt(t)&&r.setAttribute("streaming",""),this._bottomSpacer&&this._bottomSpacer.parentNode===i?i.insertBefore(r,this._bottomSpacer):i.appendChild(r),tn(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:G(),role:"assistant",content:"",status:"pending",timestamp:Date.now()};return this._repo.addOrUpdateMessage(e.parentId,s),this._repo.switchToBranch(s.id),this._reRenderActivePath(),this._repo.getBranches(s.id).indexOf(s.id)}addSiblingOf(t,e){let s=this._repo.getMessage(t);if(!s)return null;let i=s.message.role==="user"?t:s.parentId,r={...e};return Lt(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="${z(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="${z(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=k(this).getStreamBlocks();this._repo.import({...t,messages:t.messages.map(s=>{let i=Kr(s.message,e),r=Se(i);return Vr(i)&&fn(r),{...s,message:r}})}),this._reRenderActivePath()}clearAll(t){if(t?.revokeAttachments!==!1)for(let e of this._repo.getAllMessages())Er(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="${z(t)}"], [data-aparte-bubble][message-id="${z(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)),Lt(a)&&l.setAttribute("streaming",""),s.appendChild(l),tn(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=k(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",k(this).t("scrollToBottom"));let i=k(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",k(this).t("scrollToBottom"));let e=k(this).getIcon("scrollDown");t.innerHTML=e,this.appendChild(t),this._scrollBtn=t}_keepScrollButtonLast(){this._scrollBtn&&this.lastElementChild!==this._scrollBtn&&this.appendChild(this._scrollBtn)}_getSpacerHeight(){return this._frameworkManagedDOM?this._fwSpacerHeight:this._bottomSpacer?.offsetHeight??0}_setSpacerHeight(t){this._frameworkManagedDOM?(this._fwSpacerHeight=t,this.style.setProperty("--aparte-fw-spacer",`${t}px`)):this._bottomSpacer&&(this._bottomSpacer.style.height=`${t}px`)}_onScrollBtnClick=()=>{this._isAutoScrollEnabled=!0,this._smoothScrollToBottom(),this._updateScrollButton()};_pointerHeld=!1;_holdPointer=()=>{this._pointerHeld=!0};_releasePointer=()=>{this._pointerHeld=!1};_noteReaderInput=t=>{if(!(t.type==="keydown"&&!this._scrollKeys.has(t.key))){if(t.type==="pointerdown"){let e=this._container;if(!e)return;let{clientX:s}=t,i=e.getBoundingClientRect();if(!(getComputedStyle(e).direction==="rtl"?s<=i.right-e.clientWidth:s>=i.left+e.clientWidth))return}if(this._readerInputAt=performance.now(),this._gliding()&&this._container&&(this._glideUntil=0,t.type==="wheel"||t.type==="touchmove")){this._ownScrollAt=performance.now();let e=this._container.scrollTop;this._container.scrollTop=e}}};_onBranchNavigate=t=>{let e=t;e.stopPropagation(),this.navigateBranch(e.detail.messageId,e.detail.direction)};_setupEventListeners(){this._container?.addEventListener("scroll",this._handleScroll,{passive:!0}),this._container?.addEventListener("scrollend",this._handleScrollEnd,{passive:!0});for(let t of["wheel","touchmove","pointerdown","keydown"])this._container?.addEventListener(t,this._noteReaderInput,{passive:!0});this._container?.addEventListener("pointerdown",this._holdPointer,{passive:!0}),document.addEventListener("pointerup",this._releasePointer,!0),document.addEventListener("pointercancel",this._releasePointer,!0),this._scrollBtn?.addEventListener("click",this._onScrollBtnClick),this.addEventListener("aparte-branch-navigate",this._onBranchNavigate)}_setupObservers(){this._resizeObserver=new ResizeObserver(()=>{this._updateOverlayInset(),this._updateTranscriptInset(),this._isAutoScrollEnabled&&this._scrollToBottom(),this._recalculateSpacer(),this._updateScrollButton()});let t=this.querySelector(".aparte-messages-wrapper");this._container&&(this._frameworkManagedDOM?this._resizeObserver.observe(this._container,{box:"border-box"}):this._resizeObserver.observe(this._container)),this._wireOverlay(),this.parentElement&&(this._overlayAttrObserver=new MutationObserver(()=>this._wireOverlay()),this._overlayAttrObserver.observe(this.parentElement,{attributes:!0,attributeFilter:["overlay-composer"]})),this._mutationObserver=new MutationObserver(s=>{if(this._lastMutationAt=performance.now(),this._frameworkManagedDOM&&this._keepScrollButtonLast(),this._isAutoScrollEnabled&&!this._gliding()){let r=s.flatMap(o=>Array.from(o.addedNodes)).filter(o=>o instanceof Element&&o.tagName==="APARTE-CHAT-BUBBLE"),a=r.length===1?r[0]:void 0;if(a&&a.getAttribute("data-role")==="user"&&a.parentElement){let o=a.parentElement.querySelectorAll("aparte-chat-bubble");o[o.length-1]===a&&(this._smoothScrollOnce=!0)}}this._isAutoScrollEnabled&&requestAnimationFrame(()=>{this._isAutoScrollEnabled&&this._scrollToBottom()}),this._scheduleSpacerUpdate();let i=r=>Array.from(r).some(a=>a instanceof Element&&(a.tagName==="APARTE-CHAT-BUBBLE"||a.querySelector("aparte-chat-bubble")!==null));s.some(r=>i(r.addedNodes)||i(r.removedNodes))&&this._observeTail()}),this._tailObserver=new ResizeObserver(s=>{let i=!1;for(let r of s){let a=Math.round(r.borderBoxSize?.[0]?.blockSize??r.contentRect.height);this._tailHeights.get(r.target)!==a&&(i=!0),this._tailHeights.set(r.target,a)}i&&this._scheduleSpacerUpdate()}),this._observeTail(),this.addEventListener("toggle",this._onDisclosureToggle,!0);let e=this._frameworkManagedDOM?this:t;e&&this._mutationObserver.observe(e,{childList:!0,subtree:!0})}_wireOverlay(){let t=this.closest("[overlay-composer]");if(t!==this._overlayRoot){for(let e of this._overlayStack())this._resizeObserver?.unobserve(e);if(this._overlayObserver?.disconnect(),this._overlayObserver=null,this._overlayRoot=t,this._overlayInset=-1,this.style.removeProperty("--aparte-bottom-inset"),!(!t||!this._resizeObserver)){for(let e of this._overlayStack())this._resizeObserver.observe(e);this._overlayObserver=new MutationObserver(()=>{for(let e of this._overlayStack())this._resizeObserver?.observe(e);this._updateOverlayInset()}),this._overlayObserver.observe(t,{childList:!0}),this._updateOverlayInset()}}}_overlayStack(){return this._overlayRoot?Array.from(this._overlayRoot.children).filter(t=>t instanceof HTMLElement&&t!==this&&t.tagName.toLowerCase()!=="aparte-scroll-rail"):[]}_updateOverlayInset(){if(!this._overlayRoot)return;let t=this.getBoundingClientRect().bottom,e=1/0;for(let i of this._overlayStack()){let r=i.getBoundingClientRect();r.height>0&&(e=Math.min(e,r.top))}let s=e===1/0?0:Math.max(0,Math.round(t-e));s!==this._overlayInset&&(this._overlayInset=s,this.style.setProperty("--aparte-bottom-inset",`${s}px`))}_updateTranscriptInset(){let t=this.parentElement;if(!t)return;let e=this.querySelector(".aparte-messages-wrapper")??this._container??this,s=parseFloat(getComputedStyle(e).paddingInlineStart)||0,i=getComputedStyle(t).direction==="rtl",r=e.getBoundingClientRect(),a=t.getBoundingClientRect(),o=i?a.right-r.right:r.left-a.left,l=Math.max(0,Math.round((o+s)*10)/10);l!==this._transcriptInset&&(this._transcriptInset=l,t.style.setProperty("--aparte-transcript-inset",`${l}px`))}_isAtBottom(){if(!this._container)return!0;let{scrollTop:t,scrollHeight:e,clientHeight:s}=this._container;return e-t-s<=this._scrollThreshold}_handleScroll(){if(!this._container)return;let t=this._container.scrollTop,e=this._container.scrollHeight,s=this._lastScrollTop-t,i=Math.abs(e-this._lastScrollHeight),r=performance.now(),a=e<this._lastScrollHeight-1,o=r-this._lastMutationAt<this._settleShadowMs&&s<=this._settleBoundPx,l=r-this._ownScrollAt<this._ownScrollWindowMs&&r-this._readerInputAt>=this._ownScrollWindowMs&&!this._pointerHeld&&(s<=i+2||a||o),c=s>1&&!l,d=s>1&&r-this._readerInputAt<this._ownScrollWindowMs;this._lastScrollTop=t,this._lastScrollHeight=e,this._isAtBottom()&&!d?this._isAutoScrollEnabled=!0:c?this._isAutoScrollEnabled=!1:s>1&&l&&this._isAutoScrollEnabled&&this._settleAtBottom(),this._updateScrollButton()}_scrollToBottom(){if(this._container){if(this._smoothScrollOnce){this._smoothScrollOnce=!1,this._smoothScrollToBottom();return}if(this._gliding()){this._retargetGlide();return}this._ownScrollAt=performance.now(),this._container.scrollTop=this._container.scrollHeight,this._settleAtBottom()}}_gliding(){return performance.now()<this._glideUntil}_retargetGlide(){this._container&&(this._ownScrollAt=performance.now(),this._armGlide(),this._container.scrollTo({top:this._container.scrollHeight,behavior:"smooth"}))}_armGlide(){this._glideUntil=performance.now()+this._glideWindowMs,this._glideSettleTimer!==null&&clearTimeout(this._glideSettleTimer),this._glideSettleTimer=setTimeout(()=>{if(this._glideSettleTimer=null,!this._container||!this._isAutoScrollEnabled||this._gliding())return;let t=this._container.scrollHeight-this._container.clientHeight;this._container.scrollTop<this._lastScrollTop-1||t-this._container.scrollTop>1&&this._scrollToBottom()},this._glideWindowMs+16)}_handleScrollEnd(){if(!this._container)return;this._container.scrollHeight-this._container.clientHeight-this._container.scrollTop<=1&&(this._glideUntil=0)}_settleAtBottom(){if(this._settleUntil=performance.now()+this._settleWindowMs,this._settleRafId!==null)return;let t=()=>{if(this._settleRafId=null,!this.isConnected||!this._container||!this._isAutoScrollEnabled){this._settleUntil=0;return}let e=this._container.scrollHeight-this._container.clientHeight;e-this._container.scrollTop>1&&!this._gliding()&&(this._ownScrollAt=performance.now(),this._container.scrollTop=e),performance.now()<this._settleUntil?this._settleRafId=requestAnimationFrame(t):this._settleUntil=0};this._settleRafId=requestAnimationFrame(t)}_smoothScrollToBottom(){this._container&&(this._ownScrollAt=performance.now(),typeof this._container.scrollTo=="function"&&!this._prefersReducedMotion()?(this._armGlide(),this._container.scrollTo({top:this._container.scrollHeight,behavior:"smooth"})):this._container.scrollTop=this._container.scrollHeight)}_prefersReducedMotion(){return typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion: reduce)").matches}_updateScrollButton(){let t=this._scrollBtn;if(!t)return;let e=this._isAtBottom();t.classList.contains("aparte-scroll-btn--hidden")===e&&t.hasAttribute("tabindex")===e||(t.classList.toggle("aparte-scroll-btn--hidden",e),e?(t.setAttribute("tabindex","-1"),t.setAttribute("aria-hidden","true")):(t.removeAttribute("tabindex"),t.removeAttribute("aria-hidden")))}_recalculateSpacer(){if(!this._container||!this._frameworkManagedDOM&&!this._bottomSpacer||Date.now()<this._spacerFrozenUntil)return;let t=Array.from(this.querySelectorAll("aparte-chat-bubble"));if(t.length===0){this._setSpacerHeight(0);return}let e=[...t].reverse().find(h=>h.getAttribute("data-role")==="user");if(!e){this._setSpacerHeight(0);return}let s=this._getSpacerHeight(),i=this._container.getBoundingClientRect(),a=e.getBoundingClientRect().top-i.top+this._container.scrollTop,o=this._container.scrollHeight-s;if(o<=this._container.clientHeight){this._setSpacerHeight(0);return}let l=o-a,c=parseFloat(getComputedStyle(this._container).scrollPaddingTop)||0,d=this._container.clientHeight-c-l,u=this._container.clientHeight;this._setSpacerHeight(Math.min(Math.max(0,d),u)),this._isAutoScrollEnabled&&this._scrollToBottom()}_observeTail(){if(!this._tailObserver)return;let t=Array.from(this.querySelectorAll("aparte-chat-bubble")),e=t.length;for(;e>0&&t[e-1].getAttribute("data-role")!=="user";)e--;let s=e>0?t.slice(e-1):[];for(let i of this._tail)s.includes(i)||this._tailObserver.unobserve(i);for(let i of s)this._tail.includes(i)||(this._tailHeights.set(i,Math.round(i.offsetHeight)),this._tailObserver.observe(i,{box:"border-box"}));this._tail=s}_scheduleSpacerUpdate(){this._spacerRafId===null&&(this._spacerRafId=requestAnimationFrame(()=>{this._spacerRafId=null,this._recalculateSpacer(),this._updateScrollButton()}))}_pruneRenderedBubbles(){if(this._frameworkManagedDOM)return;let t=this.querySelector(".aparte-messages-wrapper");if(!t)return;let e=t.querySelectorAll("aparte-chat-bubble"),s=e.length-this._maxRenderedBubbles;for(let i=0;i<s;i++)e[i]?.remove()}_cleanup(){this._container?.removeEventListener("scroll",this._handleScroll),this._container?.removeEventListener("scrollend",this._handleScrollEnd),this._glideSettleTimer!==null&&(clearTimeout(this._glideSettleTimer),this._glideSettleTimer=null);for(let t of["wheel","touchmove","pointerdown","keydown"])this._container?.removeEventListener(t,this._noteReaderInput);this._container?.removeEventListener("pointerdown",this._holdPointer),document.removeEventListener("pointerup",this._releasePointer,!0),document.removeEventListener("pointercancel",this._releasePointer,!0),this._pointerHeld=!1,this._scrollBtn?.removeEventListener("click",this._onScrollBtnClick),this.removeEventListener("aparte-branch-navigate",this._onBranchNavigate),this._resizeObserver?.disconnect(),this._mutationObserver?.disconnect(),this._tailObserver?.disconnect(),this._tailObserver=null,this._tail=[],this.removeEventListener("toggle",this._onDisclosureToggle,!0),this._overlayObserver?.disconnect(),this._overlayObserver=null,this._overlayAttrObserver?.disconnect(),this._overlayAttrObserver=null,this._overlayRoot=null,this._overlayInset=-1,this._transcriptInset=-1,this._resizeObserver=null,this._mutationObserver=null,this._spacerRafId!==null&&(cancelAnimationFrame(this._spacerRafId),this._spacerRafId=null),this._settleRafId!==null&&(cancelAnimationFrame(this._settleRafId),this._settleRafId=null),this._settleUntil=0}};$(He);customElements.get("aparte-chat-viewport")||customElements.define("aparte-chat-viewport",He);var $e=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 k(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??k(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",K(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())}};$($e);customElements.get("aparte-composer")||customElements.define("aparte-composer",$e);function aa(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 qe=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(ut(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||k(this).t("inputPlaceholder")||"Type a message..."}_render(){if(this.querySelector(".aparte-ci-editor"))return;let t=this.hasAttribute("disabled")||this._getRoot()?.disabled||!1,e=M(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="${M(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&&aa(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())}};$(qe);customElements.get("aparte-composer-input")||customElements.define("aparte-composer-input",qe);var Fe=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=k(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="${M(t)}"
152
- title="${M(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(ut(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=k(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=k(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=k(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 k(this).getIcon("check")}_getSendIcon(){return k(this).getIcon("send")||"Send"}_getStopIcon(){return k(this).getIcon("stop")}};$(Fe);customElements.get("aparte-composer-send")||customElements.define("aparte-composer-send",Fe);var Ue=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(ut(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=k(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="${M(t)}"
158
- title="${M(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=k(this).t("stopButton")||"Stop";this._button.setAttribute("aria-label",t),this._button.setAttribute("title",t),this._button.innerHTML=this._getStopIcon()}_getStopIcon(){return k(this).getIcon("stop")}};$(Ue);customElements.get("aparte-composer-cancel")||customElements.define("aparte-composer-cancel",Ue);var We=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=k(this),s=r=>(e.t("removeAttachment")||"Remove {name}").replace("{name}",()=>r.name);if(this.innerHTML=t.map(r=>{let a=I(r.name),o=`<button class="aparte-btn aparte-btn--icon aparte-btn--sm aparte-thumb__remove" type="button" aria-label="${M(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="${M(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">${I(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])})}),!k(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",c=>{let d=c.key;d!=="Enter"&&d!==" "||(c.preventDefault(),l())})})}_ext(t){let e=t.lastIndexOf(".");return e>0?t.slice(e+1).toUpperCase().slice(0,4):"FILE"}};$(We);customElements.get("aparte-composer-attachments")||customElements.define("aparte-composer-attachments",We);var je=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(ut(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=k(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=k(this).t("actionUpload")||"Attach file",e=k(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="${M(t)}"
163
- title="${M(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=>aa(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)}}};$(je);customElements.get("aparte-composer-add-attachment")||customElements.define("aparte-composer-add-attachment",je);var Ge=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(ut(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=M(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:k(this).getIcon(t)??t:""}};$(Ge);customElements.get("aparte-composer-action")||customElements.define("aparte-composer-action",Ge);var ze=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",""))}};$(ze);customElements.get("aparte-composer-toolbar")||customElements.define("aparte-composer-toolbar",ze);function Ke(n){return n.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().trim()}function _n(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!==""&&!Ke(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 Yr=n=>n==="running"||n==="waiting"?n:null;function dn(n,t){return`[${n}="${z(t)}"]`}var un=864e5,hn=4,Te=8,Ve=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",K(t))}get manage(){return this.hasAttribute("manage")}set manage(t){this.toggleAttribute("manage",K(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!==k(this)||this._render()};_onStatus=t=>{let e=t.detail;if(typeof e?.id!="string")return;sn(e.id,Yr(e.status));let s=this.querySelector(dn("data-conv-id",e.id));s&&this._applyStatus(s,e.id)};setConversationStatus(t,e){kr(t,Yr(e))}getConversationStatus(t){return Ee(t)}_applyStatus(t,e){let s=Ee(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=pt(this),s=e&&this.contains(e)?e.closest("[data-select-id], [data-more-id]"):null,i=s?.dataset.selectId?dn("data-select-id",s.dataset.selectId):s?.dataset.moreId?dn("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 p=this.querySelector(".aparte-conv-list-loading-status"),m=()=>{p?.isConnected&&(p.textContent=this._t("loadingConversations"))};typeof requestAnimationFrame=="function"?requestAnimationFrame(m):m();return}let c=this.querySelector(":scope > .aparte-conv-list-no-match"),d=this._groups().map(_=>this._renderGroup(_)).join("");if(c){for(let _ of Array.from(this.childNodes))_!==c&&_.remove();c.insertAdjacentHTML("beforebegin",d)}else this.innerHTML=d;if(this._applyFilter(),!i)return;let u=this.querySelector(i);if(u&&a(u)){u.focus();return}let h=Array.from(this.querySelectorAll("[data-select-id]")).filter(a),f=o>=0?h[o]??h[h.length-1]:null;if(f){f.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=Ke(t),this._applyFilter()}_applyFilter(){let t=this._query;if(this.hasAttribute("loading"))return 0;let e=_n(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 k(this).getLocale()[t]??Ct[t]??""}_groups(){let t=this._conversations;if(this.hasAttribute("flat")||!t.some(d=>typeof d.updatedAt=="number"))return[{key:"all",label:null,items:t}];let e=new Date,s=new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime(),i=k(this).getLocale().tag,r=new Map,a=(d,u,h)=>{let f=r.get(d);f||(f={key:d,label:u,items:[]},r.set(d,f)),f.items.push(h)};for(let d of t){if(d.pinnedAt){a("pinned",this._t("conversationGroupPinned"),d);continue}let u=d.updatedAt;if(typeof u!="number"){a("undated",null,d);continue}if(u>=s)a("today",this._t("conversationGroupToday"),d);else if(u>=s-un)a("yesterday",this._t("conversationGroupYesterday"),d);else if(u>=s-7*un)a("week",this._t("conversationGroupWeek"),d);else if(u>=s-30*un)a("month",this._t("conversationGroupMonth"),d);else{let h=new Date(u),f=h.getFullYear()===e.getFullYear(),_=new Intl.DateTimeFormat(i,f?{month:"long"}:{month:"long",year:"numeric"}).format(h),p=_.charAt(0).toLocaleUpperCase(i)+_.slice(1);a(`m-${h.getFullYear()}-${String(h.getMonth()).padStart(2,"0")}`,p,d)}}let o=["pinned","today","yesterday","week","month"].map(d=>r.get(d)).filter(d=>!!d),l=[...r.keys()].filter(d=>d.startsWith("m-")).sort((d,u)=>u.localeCompare(d)).map(d=>r.get(d)),c=r.get("undated");return[...o,...l,...c?[c]:[]]}_renderGroup(t){let e=t.items.map(i=>this._renderItem(i)).join("");if(t.label===null)return`<div class="aparte-conv-group">${e}</div>`;let s=I(t.label);return`
173
- <div class="aparte-conv-group" role="group" aria-label="${M(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=M(t.id),r=I(t.title||this._t("newChat")),a=M(this._t("conversationActions")),o=k(this).getIcon("more"),l=Ee(t.id),c=l?` data-status="${M(l)}"`:"",d=M(l==="running"?"aparte-conv-item__title aparte-shimmer":"aparte-conv-item__title"),u=I(this._statusWords(l));return`
177
- <div class="${M(s)}" data-conv-id="${i}"${c}>
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="${d}">${r}</span><span class="aparte-conv-item__status" aria-hidden="true"></span><span class="aparte-conv-item__state aparte-sr-only">${u}</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=k(this),s=e.getIcon("edit"),i=e.getIcon("pin"),r=e.getIcon(t.archivedAt?"unarchive":"archive"),a=e.getIcon("trash"),o=I(this._t("renameConversation")),l=I(this._t(t.pinnedAt?"unpinConversation":"pinConversation")),c=I(this._t(t.archivedAt?"unarchiveConversation":"archiveConversation")),d=I(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>${c}</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>${d}</span></button>`}_confirmQuestion(t){return this._t("deleteConversationConfirm").replace("{title}",()=>t.title||this._t("newChat"))}_confirmMarkup(t){let e=I(this._confirmQuestion(t)),s=I(this._t("cancel")),i=I(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+hn;r+i.height>window.innerHeight-Te&&s.top-i.height-hn>=Te&&(r=s.top-i.height-hn);let o=getComputedStyle(this).direction==="rtl"?s.left:s.right-i.width;o=Math.max(Te,Math.min(o,window.innerWidth-i.width-Te)),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=ht(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=k(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(pt(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="${z(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")})}};$(Ve);customElements.get("aparte-conversation-list")||customElements.define("aparte-conversation-list",Ve);var oa=n=>typeof n=="string"||typeof n=="object"&&n!==null&&typeof n.label=="string",pn=n=>{try{let t=JSON.parse(n);return Array.isArray(t)?t.filter(oa):[]}catch{return console.warn('[aparte-suggestions] `suggestions` is not a JSON array. Use ["\u2026"] or [{"label": "\u2026", "prompt": "\u2026"}].'),[]}},Qr=n=>typeof n=="string"?n:n.label,Jr=n=>typeof n=="string"?n:n.prompt??n.label,Ye=class extends HTMLElement{static get observedAttributes(){return["suggestions","target","empty-only","answers"]}_suggestions=[];_composer=null;_transcript=null;_transcriptObserver=null;_sent=!1;_wasEmpty=!0;_hidOwn=!1;_onSend=()=>{this.hasAttribute("answers")&&this._showAnswers([]),this.hasAttribute("empty-only")&&(this._transcript||this._watchTranscript(),this._sent=!0,this._applyEmptyOnly())};_applyEmptyOnly=()=>{let t=this._transcript?ra(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"?pn(t):Array.isArray(t)?t.filter(oa):[],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==="answers"?this._watchTranscript():t==="empty-only"&&(this._watchTranscript(),this.hasAttribute("empty-only")||(this._sent=!1,this._setHidden(!1))))}_groupLabel(){return k(this).t("suggestionsLabel")||"Suggested prompts"}_parsed=null;_readAttribute(){let t=this.getAttribute("suggestions");t===null||t===this._parsed||(this._parsed=t,this._suggestions=pn(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=Z(this._composer)??Z(this)??(t?document.getElementById(t):null);return e?e.matches("aparte-chat-viewport")?e:e.querySelector("aparte-chat-viewport"):null}_watchTranscript(){let e=this.hasAttribute("empty-only")||this.hasAttribute("answers")?this._resolveTranscript():null;e!==this._transcript&&(this._transcriptObserver?.disconnect(),this._transcriptObserver=null,this._transcript=e,e&&(this._transcriptObserver=new MutationObserver(this._onTranscript),this._transcriptObserver.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["loading"]}))),this._onTranscript()}_onTranscript=()=>{this.hasAttribute("empty-only")&&this._applyEmptyOnly(),this.hasAttribute("answers")&&this._applyAnswers()};_applyAnswers(){let t=this._transcript?.querySelectorAll("aparte-chat-bubble"),e=t&&t.length?t[t.length-1]:null,s=e&&e.getAttribute("data-role")!=="user"?e.querySelectorAll("[data-aparte-suggestions]"):null,i=s&&s.length?s[s.length-1]:null;this._showAnswers(i?pn(i.getAttribute("data-aparte-suggestions")??"[]"):[])}_showAnswers(t){JSON.stringify(t)!==JSON.stringify(this._suggestions)&&(this._suggestions=t,this.isConnected&&this._render())}_setHidden(t){if(t){if(this.hidden)return;this.hidden=!0,this._hidOwn=!0}else this._hidOwn&&(this.hidden=!1,this._hidOwn=!1)}_render(){if(this.replaceChildren(),this._suggestions.length===0){this.setAttribute("data-empty","");return}this.removeAttribute("data-empty");let t=document.createElement("div");t.className="aparte-suggestions",t.setAttribute("role","group"),t.setAttribute("aria-label",this._groupLabel());for(let e of this._suggestions){let s=document.createElement("button");s.type="button",s.className="aparte-btn aparte-btn--surface aparte-btn--pill aparte-suggestion",s.textContent=Qr(e);let i=Jr(e);i!==s.textContent&&(s.title=i),s.addEventListener("click",()=>this._activate(e)),t.appendChild(s)}this.appendChild(t)}_activate(t){let e={label:Qr(t),prompt:Jr(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())}};$(Ye);customElements.get("aparte-suggestions")||customElements.define("aparte-suggestions",Ye);var Xr=(n,t)=>{let e=Number(n);return n!==null&&Number.isFinite(e)&&e>0&&e<=1?e:t},tc=n=>(n instanceof Element?n.closest("aparte-chat, [data-aparte-chat]"):null)?.id||void 0,U=(n,t,e)=>{let s=document.createElement(n);return s.className=t,e!==void 0&&(s.textContent=e),s},Zr="http://www.w3.org/2000/svg",ec=()=>{let n=document.createElementNS(Zr,"svg");n.setAttribute("class","aparte-context__ring"),n.setAttribute("viewBox","0 0 36 36");for(let t of["track","value"]){let e=document.createElementNS(Zr,"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},ta=n=>!!n&&typeof n.getMessages=="function",sc=n=>{if(!n)return null;if(ta(n))return n;let t=n.viewport??n.querySelector("aparte-chat-viewport");return ta(t)?t:null},nc=0,ic={system:0,tools:0,summary:0,messages:0},Qe=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?Z(t):null;e&&(this._seen=e)}_onDone=t=>{let e=t.detail;!e?.usage||!this._isMine(e.targetId)||(this._remember(t.target),this._used=Me(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(tc(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?Me(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 k(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=Z(this);return e||(this._seen?.isConnected?this._seen:null)}_messages(){let t=sc(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)?Nr({messages:i,config:this._cfg(),windowOverride:t,viewChanged:this._viewChanged}):this._used===null?null:{window:t,used:this._used,estimated:!1,parts:{...ic},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=Xr(this.getAttribute("warn"),.75),o=Xr(this.getAttribute("danger"),.9),l=this._overflow||r>=o?"danger":r>=a?"warn":"ok";this.setAttribute("data-level",l);let c=this.getAttribute("variant")==="ring",d=this.querySelector(".aparte-context");d&&d.classList.contains("aparte-context--ring")!==c&&(this.replaceChildren(),d=null,this._panelSignature="");let u=this.querySelector('[role="meter"]'),h=this.querySelector(".aparte-context__text"),f=this.querySelector(".aparte-context__toggle"),_=this.querySelector(".aparte-context__name"),p=this.querySelector(".aparte-context__panel");(!d||!u||!h||!f||!_||!p)&&(d=U("div",c?"aparte-context aparte-context--ring":"aparte-context"),u=c?ec():U("div","aparte-progress"),u.setAttribute("role","meter"),c||u.appendChild(U("div","aparte-progress__bar")),f=U("button","aparte-btn aparte-btn--ghost aparte-btn--sm aparte-context__toggle"),f.type="button",_=U("span","aparte-sr-only"),_.classList.add("aparte-context__name"),h=U("span","aparte-context__text"),f.append(_,h),p=U("div","aparte-context__panel aparte-popover"),p.id=`aparte-context-panel-${++nc}`,p.setAttribute("role","group"),p.hidden=!0,f.setAttribute("aria-controls",p.id),d.append(u,f,p),this.replaceChildren(d),this._panelSignature="");let m=this._cfg(),T=m.getLocale().tag||void 0,L=new Intl.NumberFormat(T,{notation:"compact",maximumFractionDigits:1}),R=s.estimated?"~":"",b=`${R}${L.format(i)} / ${L.format(e)}`,y=Math.round(r*100),g=m.t("contextLabel")||"Context window";if(c){let w=u.querySelector(".aparte-context__value");w?.style.setProperty("--aparte-context-ratio",String(y)),w?.classList.toggle("aparte-context__value--empty",y===0),d.title=b}else u.style.setProperty("--aparte-progress-value",String(y));if(u.setAttribute("aria-valuemin","0"),u.setAttribute("aria-valuemax",String(e)),u.setAttribute("aria-valuenow",String(i)),u.setAttribute("aria-label",`${g}: ${b}`),_.textContent=`${g}: `,f.setAttribute("aria-expanded",String(this._open)),h.textContent=c?`${R}${new Intl.NumberFormat(T,{style:"percent",maximumFractionDigits:0}).format(y/100)}`:b,p.setAttribute("aria-label",g),p.hidden=!this._open,this._open?this._renderPanel(p,s,e,L):this._panelSignature="",l!==this._level){this._level=l;let w=this._ownTargetId(),E={level:l,used:i,window:e,ratio:r,targetId:w};this.dispatchEvent(new CustomEvent("aparte-context-threshold",{detail:E,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(),c=null;try{c=a?.preview?.({target:o,...l?{targetId:l}:{}})??null}catch{c=null}let{parts:d,used:u}=e,h=d.system+d.tools+d.summary+d.messages,f=h>u&&h>0?u/h:1,_=e.estimated?"~":"",p=[{key:"system",label:r.t("contextSystem")||"System prompt",tokens:d.system*f,approx:"~"},{key:"tools",label:r.t("contextTools")||"Tools",tokens:d.tools*f,approx:"~"},{key:"summary",label:r.t("contextSummary")||"Summary",tokens:d.summary*f,approx:"~"},{key:"messages",label:r.t("contextMessages")||"Messages",tokens:d.messages*f,approx:"~"},{key:"other",label:r.t("contextOther")||"Other",tokens:f<1?0:e.other,approx:"~"},{key:"free",label:r.t("contextFree")||"Free",tokens:Math.max(0,s-u),approx:_}],m=`${_}${i.format(u)} / ${i.format(s)}`,T=c&&c.tokens>0?(r.t("contextReclaim")||"Compacting now would free ~{n} tokens").replace("{n}",()=>i.format(Math.round(c.tokens))):"",L=!!a&&!!c&&this._compact===null,R=U("ul","aparte-context__rows");for(let v of p){let S=U("li","aparte-context__row");S.setAttribute("data-part",v.key),S.append(U("span","aparte-context__row-label",v.label)),S.append(U("span","aparte-context__row-value",`${v.approx}${i.format(Math.round(v.tokens))}`));let x=U("div","aparte-progress aparte-context__row-bar");x.setAttribute("aria-hidden","true"),x.style.setProperty("--aparte-progress-value",String(Math.round(Math.min(1,v.tokens/s)*100))),x.appendChild(U("div","aparte-progress__bar")),S.append(x),R.append(S)}let b=U("li","aparte-context__row aparte-context__row--total");b.setAttribute("data-part","total"),b.append(U("span","aparte-context__row-label",r.t("contextTotal")||"Total"),U("span","aparte-context__row-value",m)),R.append(b);let y=[R];if(this._compact==="running"){let v=U("p","aparte-context__status aparte-shimmer",r.t("checkpointPending")||"Summarising the context\u2026");v.setAttribute("role","status"),y.push(v)}else if(this._compact==="failed"){let v=U("p","aparte-context__status aparte-context__status--failed",r.t("checkpointFailed")||"Couldn't summarise the context");v.setAttribute("role","status"),this._failure&&(v.title=this._failure,v.appendChild(U("span","aparte-sr-only",`: ${this._failure}`))),y.push(v,this._action("retry",r.t("retry")||"Retry"))}T&&y.push(U("p","aparte-context__reclaim",T)),L&&y.push(this._action("compact",r.t("contextCompactNow")||"Compact now"));let g=U("div","aparte-context__content");if(g.append(...y),g.innerHTML===this._panelSignature)return;this._panelSignature=g.innerHTML;let w=document.activeElement,E=w&&t.contains(w)?w.getAttribute("data-context-action")??"":null;t.replaceChildren(...Array.from(g.childNodes)),E!==null&&((E?t.querySelector(`[data-context-action="${z(E)}"]`):null)??this.querySelector(".aparte-context__toggle"))?.focus()}_action(t,e){let s=U("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")}};$(Qe);customElements.get("aparte-context")||customElements.define("aparte-context",Qe);var ea=60,rc=6,ac=150,oc=4,lc=1,Je=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>ea?`${s.slice(0,ea-1).trimEnd()}\u2026`:s}_tickLabel(t){let e=k(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=k(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 c=l.firstElementChild instanceof HTMLElement?l.firstElementChild.dataset.messageId:void 0;c&&r.set(c,l)}let a=new Set,o=0;for(let l of t){let c=l.getAttribute("message-id");a.add(c);let d=r.get(c);if(d)r.delete(c);else{d=document.createElement("li");let _=document.createElement("button");_.type="button",_.className="aparte-scroll-rail__tick",_.dataset.messageId=c,d.appendChild(_)}let u=d.firstElementChild,h=this._tickLabel(l);u.getAttribute("aria-label")!==h&&(u.setAttribute("aria-label",h),u.title=h),c===this._currentId?u.getAttribute("aria-current")!=="true"&&u.setAttribute("aria-current","true"):u.removeAttribute("aria-current");let f=i.children[o]??null;f!==d&&i.insertBefore(d,f),o++}for(let l of r.values())l.remove();this._currentId&&!a.has(this._currentId)&&(this._currentId=null),cc(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 u=e.getBoundingClientRect(),h=t.getBoundingClientRect();u.height>0&&h.height>0&&(this._write("--aparte-scroll-rail-block-start",`${Math.max(0,Math.round(u.top-h.top))}px`),this._write("--aparte-scroll-rail-block-end",`${Math.max(0,Math.round(h.bottom-u.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,c=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 d=Math.max(rc,Math.floor(r/i));this._write("--aparte-scroll-rail-hit-size",`${d}px`),this._write("--aparte-scroll-rail-gap",`${Math.max(0,d-c)}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(pt(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="${z(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(),ac)}_settle(){let t=this._held,e=this._settleSurface,s=t?this._bubbleOf(t):null;if(t&&s&&e&&this._alignPasses<oc){let i=e.getBoundingClientRect().top+(parseFloat(getComputedStyle(e).scrollPaddingTop)||0),r=s.getBoundingClientRect().top-i;if(Math.abs(r)>lc){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 cc(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}$(Je);customElements.get("aparte-scroll-rail")||customElements.define("aparte-scroll-rail",Je);var dc="(max-width: 48rem)",Xe=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",K(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-${++uc}`),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})`:dc;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=yt(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:pc(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(){sa(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=sa(this);if(e.length===0)return;let s=e[0],i=e[e.length-1],r=pt(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=ht(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+=_n(i,Ke(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=Ke(this._query),e=t!==""&&this._lists().every(s=>typeof s.filter=="function"?s.hasAttribute("data-no-match"):!s.hasAttribute("loading")&&_n(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=k(this).getLocale();this.setAttribute("aria-label",t.sidebarLabel??"Conversations"),this.dataset.ownLabel="locale"}},uc=0,hc=["a[href]","button:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(",");function sa(n){return Array.from(n.querySelectorAll(hc)).filter(t=>!t.closest("[hidden]")&&t.checkVisibility?.()!==!1)}function pc(n){return n.closest("aparte-sidebar")??yt(n).querySelector("aparte-sidebar")??document.querySelector("aparte-sidebar")}$(Xe);customElements.get("aparte-sidebar")||customElements.define("aparte-sidebar",Xe);function na(n,t,e){return Number.isFinite(n)?n<t?t:n>e?e:n:t}function fc(n){let t=Number.isFinite(n.startPercent)?n.startPercent:0;if(!Number.isFinite(n.containerPx)||n.containerPx<=0)return na(t,0,100);let i=((!n.vertical&&n.rtl)!==(n.primaryEnd===!0)?-1:1)*n.deltaPx*100/n.containerPx;return na(t+i,0,100)}function ia(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 _c="(max-width: 48rem)",Jt=38,gc=300;function Xt(n,t){let e=Number.parseFloat(n??"");return Number.isFinite(e)?e<0?0:e>100?100:e:t}var Ze=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=Jt;_initialPosition=Jt;_initialCaptured=!1;_preCollapsePosition=null;_lastPosition=null;_lastCollapsed=null;_lastPane=null;_source="api";_ready=!1;_dragging=!1;_captured=!1;_moved=!1;_pointerId=null;_dragStartPercent=Jt;_dragOriginPx=0;_dragContainerPx=0;_keying=!1;get position(){return this._position}set position(t){let e=Xt(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",K(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",K(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",K(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=Xt(t,Jt),this._setLive(this._position)):this._position=Xt(getComputedStyle(this).getPropertyValue("--aparte-split-position"),Jt),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=Xt(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=fc({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(),gc)}}_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=ia(t.key,t.shiftKey,this._rtl(),this.orientation==="vertical",this.primary==="end");e!==null&&(t.preventDefault(),this._keying=!0,this._position=Xt(String(this._position+e),this._position),this._setLive(this._position))};_onKeyup=t=>{!this._keying||t.target!==this._handle||ia(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})`:_c;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=ht(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")??yt(e).querySelector("aparte-split")??document.querySelector("aparte-split"))!==this)return;this.showPane(i??(this.pane==="start"?"end":"start"))};_syncPaneControls(){let t=new Set([yt(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")??yt(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=k(this).getLocale();t.setAttribute("aria-label",this.getAttribute("label")??e.splitHandleLabel??"Resize the panes"),t.dataset.ownLabel="locale"}};$(Ze);customElements.get("aparte-split")||customElements.define("aparte-split",Ze);var mc="(max-width: 30rem), (max-height: 30rem)",bc=["a[href]","button:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(","),ts=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",K(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:[Kt],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(pt(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 k(this.querySelector(`[${Kt}]`)??this)}_keepButton(){this._button&&this._button.parentNode!==this&&this.appendChild(this._button)}_renderButton(){let t=this._button;if(!t)return;this._keepButton();let e=this._config(),s=e.getLocale(),i=this.open,r=i?"":(this.getAttribute("label")??"").trim(),a=r?"aparte-btn--pill":"aparte-btn--circle";t.className=["aparte-btn","aparte-btn--primary","aparte-btn--solid","aparte-btn--lg",a,"aparte-launcher__button"].join(" "),t.setAttribute("aria-expanded",String(i)),r?t.removeAttribute("aria-label"):t.setAttribute("aria-label",i?s.launcherClose??"Close the chat":s.launcherOpen??"Open the chat");let o=document.createElement("span");o.className="aparte-launcher__icon",o.setAttribute("aria-hidden","true"),o.innerHTML=i?e.getIcon("launcherClose")??e.getIcon("close"):e.getIcon("launcherOpen")??e.getIcon("messageSquare");let l=[o];if(r){let c=document.createElement("span");c.className="aparte-launcher__label",c.textContent=r,l.push(c)}t.replaceChildren(...l)}_onMediaChange=t=>this._applySheet(t.matches);_watchBreakpoint(){this._media?.removeEventListener("change",this._onMediaChange),this._media=null;let t=(this.getAttribute("breakpoint")??"").trim();if(t==="none"||typeof matchMedia!="function"){this._applySheet(!1);return}this._media=matchMedia(t?`(max-width: ${t})`:mc),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(bc)).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=ht(t)?.closest?.("[data-aparte-launcher-close]");e&&this.contains(e)&&this.close()};_inModalDialog(t){let e=ht(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=pt(this);t.shiftKey&&r===s?(t.preventDefault(),i.focus()):!t.shiftKey&&r===i&&(t.preventDefault(),s.focus())}};$(ts);customElements.get("aparte-launcher")||customElements.define("aparte-launcher",ts);typeof document<"u"&&Fr();export{H as a,Y as b,G as c,eo as d,k as e,M as f,Bt as g,ml as h,Wt as i,Q as j,Al as k,z as l,$r as m,Ns as n};
206
- //# sourceMappingURL=chunk-N7SVHDCW.js.map