@aparte/n8n-chat 1.1.1 → 1.1.3

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 (82) hide show
  1. package/README.md +2 -2
  2. package/dist/cdn/chunks/{chunk-KB6DEEIQ.js → chunk-7CVHIGBT.js} +1 -1
  3. package/dist/cdn/chunks/{chunk-KB6DEEIQ.js.map → chunk-7CVHIGBT.js.map} +1 -1
  4. package/dist/cdn/chunks/{chunk-Y44OMGIJ.js → chunk-BANM7TF4.js} +2 -2
  5. package/dist/cdn/chunks/{chunk-Y44OMGIJ.js.map → chunk-BANM7TF4.js.map} +1 -1
  6. package/dist/cdn/chunks/{chunk-7K4YMHQR.js → chunk-DVXCH3I6.js} +2 -2
  7. package/dist/cdn/chunks/{chunk-7K4YMHQR.js.map → chunk-DVXCH3I6.js.map} +1 -1
  8. package/dist/cdn/chunks/chunk-NB75PIC5.js +216 -0
  9. package/dist/cdn/chunks/chunk-NB75PIC5.js.map +7 -0
  10. package/dist/cdn/chunks/{chunk-6ZVO7OTR.js → chunk-OAAYQOXW.js} +2 -2
  11. package/dist/cdn/chunks/{chunk-6ZVO7OTR.js.map → chunk-OAAYQOXW.js.map} +1 -1
  12. package/dist/cdn/chunks/chunk-RA5GYKIJ.js +379 -0
  13. package/dist/cdn/chunks/chunk-RA5GYKIJ.js.map +7 -0
  14. package/dist/cdn/chunks/de-TEGH2VNR.js +2 -0
  15. package/dist/cdn/chunks/de-TEGH2VNR.js.map +7 -0
  16. package/dist/cdn/chunks/es-UNEXO3AX.js +2 -0
  17. package/dist/cdn/chunks/es-UNEXO3AX.js.map +7 -0
  18. package/dist/cdn/chunks/fr-UZ7335OR.js +2 -0
  19. package/dist/cdn/chunks/fr-UZ7335OR.js.map +7 -0
  20. package/dist/cdn/chunks/{highlight-UOFUMZVB.js → highlight-WUBGCB6T.js} +2 -2
  21. package/dist/cdn/chunks/{highlight-UOFUMZVB.js.map → highlight-WUBGCB6T.js.map} +1 -1
  22. package/dist/cdn/chunks/it-PI5TOT4E.js +2 -0
  23. package/dist/cdn/chunks/it-PI5TOT4E.js.map +7 -0
  24. package/dist/cdn/chunks/{items-ZVVHDZQS.js → items-HIWE3HWO.js} +3 -3
  25. package/dist/cdn/chunks/{items-ZVVHDZQS.js.map → items-HIWE3HWO.js.map} +4 -4
  26. package/dist/cdn/chunks/ja-6Q7BHA5Q.js +2 -0
  27. package/dist/cdn/chunks/ja-6Q7BHA5Q.js.map +7 -0
  28. package/dist/cdn/chunks/ko-BMFWR3RO.js +2 -0
  29. package/dist/cdn/chunks/ko-BMFWR3RO.js.map +7 -0
  30. package/dist/cdn/chunks/{link-7HOSE2HR.js → link-5HWNRD4B.js} +2 -2
  31. package/dist/cdn/chunks/{link-7HOSE2HR.js.map → link-5HWNRD4B.js.map} +1 -1
  32. package/dist/cdn/chunks/{media-TKQMGWJL.js → media-XHJCFMC4.js} +2 -2
  33. package/dist/cdn/chunks/{media-TKQMGWJL.js.map → media-XHJCFMC4.js.map} +1 -1
  34. package/dist/cdn/chunks/{order-JHIBAOAM.js → order-PIE7QNLP.js} +2 -2
  35. package/dist/cdn/chunks/{order-JHIBAOAM.js.map → order-PIE7QNLP.js.map} +1 -1
  36. package/dist/cdn/chunks/{place-U5X4TNLJ.js → place-GKVCEFBR.js} +2 -2
  37. package/dist/cdn/chunks/{place-U5X4TNLJ.js.map → place-GKVCEFBR.js.map} +1 -1
  38. package/dist/cdn/chunks/{plan-SLX26KB6.js → plan-5JXNANL7.js} +2 -2
  39. package/dist/cdn/chunks/{plan-SLX26KB6.js.map → plan-5JXNANL7.js.map} +3 -3
  40. package/dist/cdn/chunks/{product-QD2UM2YC.js → product-WYDFOB3I.js} +2 -2
  41. package/dist/cdn/chunks/{product-QD2UM2YC.js.map → product-WYDFOB3I.js.map} +1 -1
  42. package/dist/cdn/chunks/pt-BR-2WMTMMJ3.js +2 -0
  43. package/dist/cdn/chunks/pt-BR-2WMTMMJ3.js.map +7 -0
  44. package/dist/cdn/chunks/ru-L4NHDBS2.js +2 -0
  45. package/dist/cdn/chunks/ru-L4NHDBS2.js.map +7 -0
  46. package/dist/cdn/chunks/{score-SIWLGKFB.js → score-VCBT3P7K.js} +2 -2
  47. package/dist/cdn/chunks/{score-SIWLGKFB.js.map → score-VCBT3P7K.js.map} +1 -1
  48. package/dist/cdn/chunks/{stats-I7FWD22A.js → stats-GDG2ICQL.js} +2 -2
  49. package/dist/cdn/chunks/{stats-I7FWD22A.js.map → stats-GDG2ICQL.js.map} +1 -1
  50. package/dist/cdn/chunks/{stock-SU4RHFTL.js → stock-XSN3A64Q.js} +2 -2
  51. package/dist/cdn/chunks/{stock-SU4RHFTL.js.map → stock-XSN3A64Q.js.map} +1 -1
  52. package/dist/cdn/chunks/{weather-OLNMWGUD.js → weather-5MVHTOM3.js} +2 -2
  53. package/dist/cdn/chunks/{weather-OLNMWGUD.js.map → weather-5MVHTOM3.js.map} +1 -1
  54. package/dist/cdn/chunks/zh-CN-232EGCJD.js +2 -0
  55. package/dist/cdn/chunks/zh-CN-232EGCJD.js.map +7 -0
  56. package/dist/cdn/latest.js +4 -4
  57. package/dist/cdn/n8n-chat.js +58 -58
  58. package/dist/cdn/n8n-chat.js.map +4 -4
  59. package/dist/style.css +1 -1
  60. package/package.json +7 -7
  61. package/dist/cdn/chunks/chunk-L72XRVUT.js +0 -209
  62. package/dist/cdn/chunks/chunk-L72XRVUT.js.map +0 -7
  63. package/dist/cdn/chunks/chunk-S6J6TTL4.js +0 -379
  64. package/dist/cdn/chunks/chunk-S6J6TTL4.js.map +0 -7
  65. package/dist/cdn/chunks/de-7VJXZS3Y.js +0 -2
  66. package/dist/cdn/chunks/de-7VJXZS3Y.js.map +0 -7
  67. package/dist/cdn/chunks/es-DJOVPGNH.js +0 -2
  68. package/dist/cdn/chunks/es-DJOVPGNH.js.map +0 -7
  69. package/dist/cdn/chunks/fr-MX37SEJL.js +0 -2
  70. package/dist/cdn/chunks/fr-MX37SEJL.js.map +0 -7
  71. package/dist/cdn/chunks/it-ACF2ENLA.js +0 -2
  72. package/dist/cdn/chunks/it-ACF2ENLA.js.map +0 -7
  73. package/dist/cdn/chunks/ja-RUBXQ3AK.js +0 -2
  74. package/dist/cdn/chunks/ja-RUBXQ3AK.js.map +0 -7
  75. package/dist/cdn/chunks/ko-SZPL4AIC.js +0 -2
  76. package/dist/cdn/chunks/ko-SZPL4AIC.js.map +0 -7
  77. package/dist/cdn/chunks/pt-BR-O6V4ZHQV.js +0 -2
  78. package/dist/cdn/chunks/pt-BR-O6V4ZHQV.js.map +0 -7
  79. package/dist/cdn/chunks/ru-GHVKB5QT.js +0 -2
  80. package/dist/cdn/chunks/ru-GHVKB5QT.js.map +0 -7
  81. package/dist/cdn/chunks/zh-CN-EHJ3XH3O.js +0 -2
  82. package/dist/cdn/chunks/zh-CN-EHJ3XH3O.js.map +0 -7
@@ -0,0 +1,216 @@
1
+ function Ai(){let n=[],t=!1,e=()=>{let i=n.shift();i?i():t=!1},s=()=>{let i=!1;return()=>{i||(i=!0,e())}};return()=>t?new Promise(i=>{n.push(()=>i(s()))}):(t=!0,s())}function al(n,t){let e=s=>{let i=t(),r=a=>()=>{a(),s()};return typeof i=="function"?r(i):i.then(r)};return()=>{let s=n();return typeof s=="function"?e(s):s.then(e)}}var Ei=Symbol("aparte.approvalGate");function ol(n){return n?.[Ei]}function ll(n,t){let e=async(s,i)=>{let r=n(),a=typeof r=="function"?r:await r;try{return await t(s,i)}finally{a()}};return e[Ei]={turn:n,ask:t},e}var cl=300*1e3,dl=10,Si=new Set;function ul(n){let t=String(n?.type??"undefined");Si.has(t)||(Si.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 Un(n){let{transportCall:t,toolLookup:e,toolConfigLookup:s,emitter:i,signal:r,maxTurns:a=dl,toolTimeoutMs:o=cl,deferral:l,parallelTools:c=!0}=n,d=n.baseRequest,h=0,u=n.idGen??(A=>`${A}-${h++}`),p=_l(i,u,r,o),f=ol(n.approvalResolver),g=f?al(Ai(),f.turn):Ai(),_=f?f.ask:n.approvalResolver,w={emitter:i,canAsk:!l&&_!==void 0,canBackground:!l,transportCall:t,toolLookup:e,toolConfigLookup:s,approvalResolver:c&&_?ll(g,_):_,maxTurns:a,toolTimeoutMs:o,parallelTools:c,idGen:u,background:p},S=[...d.messages],T=A=>{S.push(A),n.onHistoryAppend?.(A)},k=!0,m=0,v,E;i({type:"run-start"});try{return await b()}finally{p.close()}async function b(){let A=l?ki(S):[];if(A.length>0){let x=[],O={turns:1,maxTurns:a,toolLookup:e,toolConfigLookup:s,approvalResolver:_,approvalTurn:g,emitter:i,signal:r,toolTimeoutMs:o,declareCall:()=>{},append:T,deferral:l,runBase:w};for(let[$,D]of A.entries()){if(x.length>0){x.push({toolCallId:D.id,name:D.name,input:D.input,reason:$n(D,s)});continue}let q;try{q=await Fn(D,O)}catch(st){for(let pt of A.slice($+1))i({type:"tool-aborted",toolCallId:pt.id});throw st}if(typeof q=="object"){x.push({toolCallId:D.id,name:D.name,input:D.input,reason:q.defer});continue}if(q==="stop-run"){for(let st of A.slice($+1))i({type:"tool-aborted",toolCallId:st.id});k=!1;break}}if(x.length>0&&!r.aborted){p.stopAll(),i({type:"run-suspended",pending:x});return}}for(;k&&!r.aborted;){if(m++,E=void 0,m>a){i({type:"turn-limit-exceeded",scope:"global",limit:a});break}let x=d.toolChoice;if(m===1&&x&&typeof x=="object"&&!Array.isArray(x)&&x.input!==void 0){let j=x,N=u("synthetic-tool");i({type:"tool-start",toolCallId:N,name:j.name,input:j.input});let At=e(j.name);if(!At){i({type:"tool-aborted",toolCallId:N,cause:"no-handler"}),k=!1;continue}let K=await xi(At,{id:N,name:j.name,input:j.input},r,o,w);if(K.status==="aborted"){i(K.cause?{type:"tool-aborted",toolCallId:N,cause:K.cause}:{type:"tool-aborted",toolCallId:N}),k=!1;continue}if(K.status==="failed")throw i({type:"tool-failed",toolCallId:N,error:jn(K.error)}),K.error;i({type:"tool-resolved",toolCallId:N,result:K.content,structuredResult:K.structuredContent}),T({role:"assistant",content:"",toolCalls:[{id:N,name:j.name,input:j.input}]}),T({role:"tool",content:K.content,toolCallId:N,toolName:j.name}),d={...d,toolChoice:"none",tools:void 0}}let O={...d,messages:S},$=d.toolChoice;$&&typeof $=="object"&&(d={...d,toolChoice:"auto"});let D;try{D=await t(O)}catch(j){if(r.aborted||j?.name==="AbortError"){k=!1;break}throw j}if(typeof D=="string"){if(i({type:"turn-start"}),i({type:"text-delta",delta:D}),i({type:"text-flush"}),await y(D))continue;break}i({type:"turn-start"});let q="",st=[],pt=!1,C=null,R=j=>{st.push(j),!C&&(C={role:"assistant",content:q.trim(),toolCalls:st},T(C))},H=()=>{C&&(C.content=q.trim())},B=new Set,Z=j=>{let N=j;for(let At=2;B.has(N);At++)N=`${j}#${At}`;return B.add(N),N},U=[],ct={turns:m,maxTurns:a,toolLookup:e,toolConfigLookup:s,approvalResolver:_,approvalTurn:g,emitter:i,signal:r,toolTimeoutMs:o,declareCall:R,append:T,deferral:l&&{...l,outcomes:void 0},runBase:w},Y=c?hl(ct):void 0,nt=!1,ft=D[Symbol.asyncIterator](),Hn=async()=>{if(!r.aborted)return!1;try{await ft.return?.(void 0)}catch{}return k=!1,!0};try{for(;!(await Hn()||Y?.halted());){let j;try{let St=ft.next();if(Y?.busy()){let wi=await Promise.race([St,Y.onHalt.then(()=>Ci)]);if(wi===Ci){nt=!0,Promise.resolve(St).catch(()=>{});break}j=wi}else j=await St}catch(St){if(await Hn())break;throw St}if(await Hn()||Y?.halted()||j.done)break;let N=j.value;if(N.type==="thinking"){i({type:"thinking-delta",delta:N.delta});continue}if(N.type==="text"){q+=N.delta,i({type:"text-delta",delta:N.delta});continue}if(N.type==="sources"){i({type:"sources",sources:N.sources,...N.citations?{citations:N.citations}:{}});continue}if(N.type==="step-start"||N.type==="step-end"){i({type:N.type,name:N.name});continue}if(N.type==="activity"){i({type:"activity",id:N.id,activityType:N.activityType,content:N.content});continue}if(N.type==="done"){N.usage&&(v=N.usage),N.finishReason&&(E=N.finishReason);continue}if(N.type==="error")throw N.code===void 0?new Error(N.message):Object.assign(new Error(N.message),{code:N.code});if(N.type!=="tool_use"){ul(N);continue}pt=!0;let At=Z(N.id),K={id:At,name:N.name,input:N.input};if(Y){Y.start(K);continue}if(i({type:"tool-start",toolCallId:At,name:N.name,input:N.input,...U.length>0?{queued:!0}:{}}),U.length>0){R(K);let St=$n(K,s);St==="approval"&&i({type:"tool-awaiting-approval",toolCallId:K.id,name:K.name,input:K.input}),U.push({toolCallId:K.id,name:K.name,input:K.input,reason:St});continue}let Ce=await Fn(K,ct);if(typeof Ce=="object"){R(K),U.push({toolCallId:K.id,name:K.name,input:K.input,reason:Ce.defer});continue}if(Ce==="stop-run"){k=!1;break}if(Ce==="stop-turn")break}if(Y){let j=await Y.finish();if(j.failure)throw j.failure.error;U.push(...j.pending),j.stopRun&&(k=!1)}i({type:"text-flush"}),H()}finally{try{let j=ft.return?.(void 0);nt?Promise.resolve(j).catch(()=>{}):await j}catch{}Y&&await Y.abandon()}if(U.length>0&&!r.aborted)return p.stopAll(),i({type:"run-suspended",pending:U,usage:v}),v;!pt&&!await y(q)&&(k=!1)}return p.stopAll(),r.aborted&&i({type:"run-aborted"}),i({type:"run-done",usage:v,...E?{finishReason:E}:{}}),v}async function y(A){if(r.aborted||!p.pending())return!1;if(m>=a)return p.stopAll(),i({type:"turn-limit-exceeded",scope:"global",limit:a}),!1;if(await p.settled(),r.aborted)return!1;let x=p.report();if(!x)return!1;let O=A.trim();return O&&T({role:"assistant",content:O}),T({role:"user",content:x}),!0}}function ki(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 $n(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 gt(n,t){return n.decided?.(t),t}function Ti(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 qn(n,t,e){let s=Ti(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}),gt(n,"stop-turn")}async function Fn(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 qn(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}),gt(t,"stop-run");if(i?.external){if(!t.deferral)return t.emitter({type:"tool-aborted",toolCallId:n.id,cause:"no-handler"}),gt(t,"stop-run");if(!r||r.kind==="decision")return gt(t,{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"}),gt(t,"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 h=r?.kind==="decision"&&c!=="deny"?r:void 0,u;if(!h&&t.approvalResolver&&!(t.deferral&&c!=="deny")){t.asking?.(!0);let f=t.approvalTurn();if(typeof f=="function")u=f;else if(u=await f,e.aborted)return u(),t.emitter({type:"tool-aborted",toolCallId:n.id,cause:"stopped"}),gt(t,"stop-run")}let p=h;try{if(c!=="deny"&&!h&&t.emitter({type:"tool-awaiting-approval",toolCallId:n.id,name:n.name,input:n.input}),!h&&t.deferral&&c!=="deny")return gt(t,{defer:"approval"});if(!h&&!t.approvalResolver)return t.emitter({type:"tool-aborted",toolCallId:n.id,cause:"no-resolver"}),gt(t,"stop-run");if(!p&&!e.aborted&&t.approvalResolver)try{p=await t.approvalResolver({id:n.id,name:n.name,input:s},e)}catch(f){if(!e.aborted&&f?.name!=="AbortError")throw f}}finally{u?.()}if(e.aborted||!p)return t.emitter({type:"tool-aborted",toolCallId:n.id,cause:"stopped"}),gt(t,"stop-run");if(!p.approved)return qn(t,n,p),"stop-turn";p.payload&&typeof p.payload=="object"&&!Array.isArray(p.payload)&&(l={...s,...p.payload}),t.emitter({type:"tool-approved",toolCallId:n.id}),t.asking?.(!1)}let d=await xi(o,{id:n.id,name:n.name,input:l},e,t.toolTimeoutMs,t.runBase);if(d.status==="aborted")return t.emitter(d.cause?{type:"tool-aborted",toolCallId:n.id,cause:d.cause}:{type:"tool-aborted",toolCallId:n.id}),gt(t,"stop-run");if(d.status==="failed")throw t.emitter({type:"tool-failed",toolCallId:n.id,error:jn(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"}var Ci=Symbol("halted");function hl(n){let t=new AbortController,e=()=>t.abort();n.signal.aborted?t.abort():n.signal.addEventListener("abort",e,{once:!0});let s=[],i=[],r=0,a=0,o=!1,l=!1,c=!1,d=!1,h,u,p=new Promise(b=>{u=b}),f=()=>{for(;r<s.length&&s[r].settled;){let b=s[r++];b.declared&&!(d&&b.pending)&&n.declareCall(b.call);for(let y of b.messages)n.append(y)}},g=()=>{d=!0,t.abort(),u()},_=async()=>{for(let b=-1;b<i.length;)b=i.length,await Promise.all(i);n.signal.removeEventListener("abort",e);for(let b of s.slice(a))b.announced&&!b.settled&&n.emitter({type:"tool-aborted",toolCallId:b.call.id,cause:"stopped"});for(let b of s)b.settled=!0;f()},w=b=>{let{parallel:y}=s[b];return s.slice(0,b).every(A=>!A.asking&&(A.settled||y&&A.parallel))},S=b=>({...n,signal:t.signal,declareCall:()=>{b.declared=!0},append:y=>{b.messages.push(y)},decided:y=>{b.asking=!1,typeof y=="object"?l=!0:y==="stop-run"?g():(c=!0,u()),E()},asking:y=>{b.asking=y,y||E()}}),T=(b,y=!1)=>{if(b.announced)return;b.announced=!0;let{call:A}=b;n.emitter({type:"tool-start",toolCallId:A.id,name:A.name,input:A.input,...y?{queued:!0}:{}})},k=b=>{let{call:y}=b;b.announced?n.emitter({type:"tool-running",toolCallId:y.id}):T(b),i.push(Fn(y,S(b)).then(A=>{typeof A=="object"&&(b.declared=!0,b.pending={toolCallId:y.id,name:y.name,input:y.input,reason:A.defer})},A=>{h??={error:A},g()}).finally(()=>{b.asking=!1,b.settled=!0,f();try{E()}catch(A){h??={error:A},g()}}))},m=b=>{let{call:y}=b;T(b,!0);let A=$n(y,n.toolConfigLookup);A==="approval"&&n.emitter({type:"tool-awaiting-approval",toolCallId:y.id,name:y.name,input:y.input}),b.declared=!0,b.pending={toolCallId:y.id,name:y.name,input:y.input,reason:A},b.settled=!0},v=b=>{T(b,!0),qn(S(b),b.call,{by:"earlier-refusal"}),b.settled=!0},E=()=>{if(!o){o=!0;try{for(;a<s.length&&!d&&!t.signal.aborted&&!(!c&&!l&&!w(a));){let b=s[a++];c?v(b):l?m(b):k(b)}}finally{o=!1}f()}};return{onHalt:p,halted:()=>c||d,busy:()=>r<s.length,start(b){let y=n.toolConfigLookup?.(b.name)?.parallel===!0,A={call:b,parallel:y,asking:!1,announced:!1,declared:!1,messages:[],settled:!1};s.push(A),E(),T(A,!0)},async finish(){if(await _(),d){for(let b of s)b.pending&&n.emitter({type:"tool-aborted",toolCallId:b.call.id,cause:"stopped"});return{...h?{failure:h}:{},stopRun:d,pending:[]}}return{...h?{failure:h}:{},stopRun:d,pending:s.flatMap(b=>b.pending?[b.pending]:[])}},async abandon(){t.abort(),await _()}}}async function xi(n,t,e,s,i){if(e.aborted)return{status:"aborted",cause:"stopped"};let r=new AbortController,a=()=>r.abort();e.addEventListener("abort",a,{once:!0});let o,l=new Promise(g=>{o=()=>g({status:"aborted",cause:"stopped"}),e.addEventListener("abort",o,{once:!0})}),c,d=!1,h=new Promise(g=>{c=setTimeout(()=>{d=!0,r.abort(),g({status:"aborted",cause:"timeout"})},s)}),{run:u,closeOpen:p}=gl(i,t.id,r.signal),f;try{return await Promise.race([n(t,r.signal,u).then(_=>({status:"resolved",content:_.content,structuredContent:_.structuredContent})),h,l])}catch(g){return g?.name==="AbortError"?e.aborted?{status:"aborted",cause:"stopped"}:d?{status:"aborted",cause:"timeout"}:{status:"aborted"}:(f={error:g},{status:"failed",error:g})}finally{clearTimeout(c),e.removeEventListener("abort",a),o&&e.removeEventListener("abort",o),p(f?"failed":"stopped",f?{error:jn(f.error)}:void 0)}}var pl=new Set(["run-start","run-done","run-aborted","run-suspended"]),fl=n=>pl.has(n.type);function gl(n,t,e){let{emitter:s,background:i,...r}=n,a=[];return{run:{...r,startAgent:o=>{if(o.background)return i.open(o);let l=Wn(s,n.idGen("agent"),o.detached?void 0:t,o,e);return a.push(l),l}},closeOpen:(o,l)=>{for(let c of a.reverse())c.end(o,l);a.length=0}}}function Wn(n,t,e,s,i,r){let a=!i.aborted,o=new Map,l=(d,h)=>{if(a){a=!1,i.removeEventListener("abort",c);for(let[u,p]of[...o].reverse())n({type:"agent-end",agentId:u,status:"stopped",...p?{parentAgentId:p}:{}});o.clear(),n({type:"agent-end",agentId:t,status:d,...h?.result!==void 0?{result:h.result}:{},...h?.error!==void 0?{error:h.error}:{}}),r?.(d,h)}},c=()=>l("stopped");return a&&(n({type:"agent-start",agentId:t,...s.name!==void 0?{name:s.name}:{},...s.description!==void 0?{description:s.description}:{},...e!==void 0?{toolCallId:e}:{}}),i.addEventListener("abort",c,{once:!0})),{agentId:t,signal:i,emit(d){if(!(!a||fl(d))){if(d.type==="agent-start"||d.type==="agent-end"){let h=d.parentAgentId?d:{...d,parentAgentId:t};h.type==="agent-start"?o.set(h.agentId,h.parentAgentId):o.delete(h.agentId),n(h);return}n(d.agentId?d:{...d,agentId:t})}},end:l}}function _l(n,t,e,s){let i=[],r=null,a=!1,o=()=>i.some(l=>!l.ended);return{open(l){let c=new AbortController;if(a||e.aborted)return c.abort(),Wn(n,t("agent"),void 0,l,c.signal);let d=()=>c.abort();e.addEventListener("abort",d,{once:!0});let h=setTimeout(()=>c.abort(),s),u={handle:void 0,name:l.name,description:l.description,stop:c,told:!1};return u.handle=Wn(n,t("agent"),void 0,l,c.signal,(p,f)=>{clearTimeout(h),e.removeEventListener("abort",d),u.ended={status:p,...f},o()||r?.()}),i.push(u),u.handle},close(){a=!0;for(let l of i)l.ended||l.stop.abort()},pending:()=>i.some(l=>!l.ended||!l.told),settled:()=>o()?new Promise(l=>{r=()=>{r=null,l()}}):Promise.resolve(),report(){let l=i.filter(d=>d.ended&&!d.told);for(let d of l)d.told=!0;if(l.length===0)return"";let c=l.map(d=>{let h=`Sub-agent "${d.name??d.handle.agentId}"${d.description?` (${d.description})`:""}`,u=d.ended;return u.status==="done"?`${h} is done:
2
+ ${u.result?.trim()||"(it wrote nothing)"}`:u.status==="failed"?`${h} failed: ${u.error??"no reason given"}`:`${h} was stopped before it answered.`});return`${l.length===1?"A sub-agent you started is back.":"The sub-agents you started are back."}
3
+
4
+ ${c.join(`
5
+
6
+ `)}`},stopAll(){for(let l of i)l.ended||l.stop.abort()}}}function jn(n){return n instanceof Error?n.message||n.name:typeof n=="string"?n:String(n)}function tt(n){return n.replace(/["\\]/g,"\\$&").replace(/[\n\r\f]/g,t=>`\\${t.charCodeAt(0).toString(16)} `)}function at(n){return n.composedPath?.()[0]??n.target}function Ct(n){return n.getRootNode()}function it(n){return n.getRootNode().activeElement??document.activeElement}function zn(n,t,e={}){let{gap:s=4,margin:i=8,side:r="below",align:a="start",rtl:o=!1}=e,l=t.getBoundingClientRect(),c=(u,p,f)=>Math.max(i,Math.min(u,p-f-i)),d,h;if(r==="beside"){let u=n.right+s,p=n.left-l.width-s,[f,g]=o?[p,u]:[u,p],_=w=>w>=i&&w+l.width<=window.innerWidth-i;h=_(f)||!_(g)?f:g,d=n.top}else{let u=n.bottom+s,p=n.top-l.height-s,f=u+l.height<=window.innerHeight-i,g=p>=i;r==="below"?d=f||!g?u:p:d=g||!f?p:u,h=a==="start"!==o?n.left:n.right-l.width}t.style.top=`${c(d,window.innerHeight,l.height)}px`,t.style.left=`${c(h,window.innerWidth,l.width)}px`}var Ee='[role="menuitem"], [role="menuitemcheckbox"], [role="menuitemradio"]',ml=500,$t=null;function bl(n,t){for(let e=n;e&&e!==t;e=e.parentElement)if(e.hidden)return!1;return!0}function ke(n,t){return!n.disabled&&n.getAttribute("aria-disabled")!=="true"&&bl(n,t)}function Li(n,t){return n.tagName==="BUTTON"||n.tagName==="A"&&t==="Enter"}function Ii(n){return getComputedStyle(n).direction==="rtl"}function vl(n){return(n.getAttribute("aria-label")??n.textContent??"").replace(/\s+/g," ").trim().toLocaleLowerCase()}function yl(n){return!!n?.closest?.('input, textarea, select, [contenteditable]:not([contenteditable="false"])')}function wl(n,t){for(let e=t;e;){if(e===n)return!0;let s=e.assignedSlot,i=e.nodeType===Node.DOCUMENT_FRAGMENT_NODE?e.host??null:null;e=s??e.parentNode??i}return!1}function Ri(n,t){let e=!1,s=null,i=null,r=!1,a="",o=0,l=()=>[...n.querySelectorAll(Ee)].filter(m=>{let v=m.parentElement?.closest('[role="menu"]');return(!v||v===n||!n.contains(v))&&ke(m,n)}),c=m=>m?.focus({preventScroll:!0}),d=m=>{let v=at(m);r=!!v&&(n.contains(v)||!!t.owns?.(v)),!r&&k.close(!1)},h=()=>{r=!1},u=m=>{let v=at(m);v instanceof Node&&n.contains(v)||v instanceof Node&&i?.isConnected&&!wl(v,i)||k.close(!1)},p=()=>k.close(!1),f=m=>{if(!e)return;let v=m.relatedTarget;!v&&r||v&&(n.contains(v)||t.owns?.(v))||k.close(!1)},g=m=>{if(!e||m.isComposing)return;let v=m.target;if(m.key==="Escape"){m.preventDefault(),k.close(!0);return}if(m.key==="Tab"){k.close(!0);return}if(m.altKey||m.ctrlKey||m.metaKey||yl(v))return;let E=l();if(!E.length)return;let b=E.indexOf(it(n)),y=D=>{m.preventDefault(),c(E[(D+E.length)%E.length])};switch(m.key){case"ArrowDown":y(b+1);return;case"ArrowUp":y(b<0?E.length-1:b-1);return;case"Home":y(0);return;case"End":y(E.length-1);return;case"Enter":case" ":{let D=v.closest(Ee);D&&n.contains(D)&&!Li(D,m.key)&&(m.preventDefault(),D.click());return}}if([...m.key].length!==1)return;m.preventDefault();let A=Date.now();a=A-o>ml?m.key:a+m.key,o=A;let x=[...a.toLocaleLowerCase()],O=x.every(D=>D===x[0])?x[0]:x.join(""),$=[...O].length===1?b+1:Math.max(b,0);for(let D=0;D<E.length;D++){let q=E[($+D)%E.length];if(vl(q).startsWith(O)){c(q);return}}},_=m=>{if(!e)return;let v=m.target.closest?.(`${Ee}, button`);if(!v||v===n||!n.contains(v)||!ke(v,n))return;n.dispatchEvent(new CustomEvent("aparte-menu-select",{detail:{item:v},bubbles:!0,composed:!0,cancelable:!0}))&&k.close(!0)},w=m=>{e&&m.preventDefault()};n.addEventListener("keydown",g),n.addEventListener("click",_),n.addEventListener("focusout",f),n.addEventListener("contextmenu",w);let S={position:n.style.position,top:n.style.top,left:n.style.left};n.hidden=!0;let T=!n.hasAttribute("role");T&&n.setAttribute("role","menu");let k={isOpen:()=>e,open(m,v,E,b,y){$t&&$t!==k&&$t.close(!1),e=!0,$t=k,s=b,i=y,a="",n.hidden=!1,n.style.position="fixed",zn(m,n,v),document.addEventListener("pointerdown",d,!0),document.addEventListener("pointerup",h,!0),document.addEventListener("pointercancel",h,!0),window.addEventListener("scroll",u,!0),window.addEventListener("resize",p),t.onToggle?.(!0);let A=l(),x=A.find(O=>O.getAttribute("role")==="menuitemradio"&&O.getAttribute("aria-checked")==="true");c(E==="last"?A[A.length-1]:x??A[0])},close(m){e&&(e=!1,$t===k&&($t=null),r=!1,document.removeEventListener("pointerdown",d,!0),document.removeEventListener("pointerup",h,!0),document.removeEventListener("pointercancel",h,!0),window.removeEventListener("scroll",u,!0),window.removeEventListener("resize",p),m&&s?.isConnected&&s.focus(),s=null,i=null,n.hidden=!0,t.onToggle?.(!1),t.onClose?.())},release(){k.close(!1),n.removeEventListener("keydown",g),n.removeEventListener("click",_),n.removeEventListener("focusout",f),n.removeEventListener("contextmenu",w),n.style.position=S.position,n.style.top=S.top,n.style.left=S.left,n.getAttribute("style")||n.removeAttribute("style"),T&&n.removeAttribute("role")},returnTarget:()=>s};return k}function Mi(n,t,e,s=!1){let i=n.getAttribute(t);return(i===null||!s)&&n.setAttribute(t,e),()=>{i===null?n.removeAttribute(t):n.setAttribute(t,i)}}function Oi(n,t,e={}){let{onOpen:s,onClose:i,...r}=e,a=[Mi(n,"aria-haspopup","menu",!0),Mi(n,"aria-expanded","false")],o=Ri(t,{owns:u=>n.contains(u),onToggle:u=>n.setAttribute("aria-expanded",String(u)),onClose:i}),l=u=>{if(o.isOpen()){let p=[...t.querySelectorAll(Ee)].filter(f=>ke(f,t));(u==="last"?p[p.length-1]:p[0])?.focus({preventScroll:!0});return}s?.()!==!1&&o.open(n.getBoundingClientRect(),{...r,rtl:r.rtl??Ii(n)},u,n,n)},c=()=>{o.isOpen()?o.close(!0):l("first")},d=()=>c(),h=u=>{u.altKey||u.ctrlKey||u.metaKey||u.isComposing||(u.key==="ArrowDown"||u.key==="ArrowUp"?(u.preventDefault(),l(u.key==="ArrowUp"?"last":"first")):(u.key==="Enter"||u.key===" ")&&!Li(n,u.key)&&(u.preventDefault(),c()))};return n.addEventListener("click",d),n.addEventListener("keydown",h),()=>{o.release(),n.removeEventListener("click",d),n.removeEventListener("keydown",h);for(let u of a)u()}}function Pi(n,t,e={}){let{onOpen:s,onClose:i,gap:r,margin:a,rtl:o}=e,l=Ri(t,{onClose:i}),c=(u,p,f)=>{let g=it(n),_=g&&g!==document.body&&!t.contains(g)?g:l.returnTarget();return l.close(!1),s?.(u)===!1?!1:(l.open(p,{gap:f?0:r,margin:a,side:"below",align:"start",rtl:o??Ii(n)},"first",_,u),!0)},d=u=>{let p=at(u);if(!p)return;if(p instanceof Node&&t.contains(p)){u.preventDefault();return}let f={top:u.clientY,bottom:u.clientY,left:u.clientX,right:u.clientX};c(p,f,!0)&&u.preventDefault()},h=u=>{if(!(u.key==="F10"&&u.shiftKey||u.key==="ContextMenu"))return;let p=at(u);!p||t.contains(p)||c(p,p.getBoundingClientRect(),!1)&&u.preventDefault()};return n.addEventListener("contextmenu",d),n.addEventListener("keydown",h),()=>{l.release(),n.removeEventListener("contextmenu",d),n.removeEventListener("keydown",h)}}function Ni(n,t={}){let e=t.activation==="manual",s=()=>[...n.querySelectorAll('[role="tab"]')].filter(u=>u.closest('[role="tablist"]')===n),i=u=>ke(u,n),r=()=>s().find(u=>u.getAttribute("aria-selected")==="true")??null,a=u=>{let p=u.getAttribute("aria-controls");return p?n.getRootNode().querySelector(`[id="${tt(p)}"]`):null},o=u=>{for(let p of s()){let f=p===u;p.setAttribute("aria-selected",String(f)),p.tabIndex=f?0:-1;let g=a(p);g&&(g.hidden=!f)}},l=u=>{let p=r();if(u===p)return!0;let f=n.dispatchEvent(new CustomEvent("aparte-tab-change",{detail:{tab:u,panel:a(u),previous:p},bubbles:!0,composed:!0,cancelable:!0}));return f&&o(u),f},c=u=>{let p=u.target.closest?.('[role="tab"]');!p||!s().includes(p)||!i(p)||l(p)},d=u=>{if(u.altKey||u.ctrlKey||u.metaKey||u.isComposing)return;let p=u.target.closest?.('[role="tab"]'),f=s(),g=p?f.indexOf(p):-1;if(!p||g<0)return;if(u.key==="Enter"||u.key===" "){e&&p.tagName!=="BUTTON"&&i(p)&&(u.preventDefault(),l(p));return}let _=n.getAttribute("aria-orientation")==="vertical",w=!_&&getComputedStyle(n).direction==="rtl",S=_?"ArrowDown":w?"ArrowLeft":"ArrowRight",T=_?"ArrowUp":w?"ArrowRight":"ArrowLeft",k,m;if(u.key===S)k=g+1,m=1;else if(u.key===T)k=g-1,m=-1;else if(u.key==="Home")k=0,m=1;else if(u.key==="End")k=f.length-1,m=-1;else return;u.preventDefault();for(let v=0;v<f.length;v++){let E=f[((k+v*m)%f.length+f.length)%f.length];if(i(E)){(e||l(E))&&E.focus();return}}};n.addEventListener("click",c),n.addEventListener("keydown",d);let h=r()??s().find(i);return h&&o(h),()=>{n.removeEventListener("click",c),n.removeEventListener("keydown",d)}}var Al='<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>',Sl='<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>',Cl='<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>',El='<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>',kl='<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>',Tl='<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>',xl='<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>',Ml='<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 4.5h5.5V10"/><path d="M10 19.5H4.5V14"/><path d="m19.5 4.5-6 6"/><path d="m4.5 19.5 6-6"/></svg>',Ll='<svg class="aparte-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19.5 10H14V4.5"/><path d="M4.5 14H10v5.5"/><path d="m14 10 5.5-5.5"/><path d="m10 14-5.5 5.5"/></svg>',Il='<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>',Rl='<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>',Ol='<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>',Pl='<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>',Nl='<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>',Dl='<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>',Bl='<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>',Hl='<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>',$l='<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>',ql='<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>',Fl='<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>',Wl='<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>',Ul='<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>',jl='<svg class="aparte-icon" viewBox="0 0 24 24" fill="currentColor"><rect x="5" y="5" width="14" height="14" rx="2.5"/></svg>',zl='<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>',Gl='<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>',Kl='<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>',Vl='<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>',Yl='<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>',Ql='<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>',Xl='<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>',Jl='<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>',Zl='<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>',tc='<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>',ec='<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>',Di={copy:Al,check:Sl,send:Cl,loading:El,error:kl,expand:Tl,collapse:xl,maximize:Ml,minimize:Ll,terminal:Il,paperclip:Rl,image:Ol,file:Pl,scrollDown:Nl,retry:Dl,edit:Bl,thumbUp:Hl,thumbDown:$l,prevBranch:ql,nextBranch:Fl,tool:Wl,close:Ul,stop:jl,pause:zl,info:Gl,archive:Kl,unarchive:Vl,download:Yl,more:Ql,pin:Xl,trash:Jl,menu:tc,alertTriangle:ec,messageSquare:Zl};function zr(n){return typeof n=="string"?n:n.filter(t=>t.type==="text").map(t=>t.text).join("")}var z=(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))(z||{}),lt=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(z).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"}}},Zt=Di,Ut={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}?",approvalAskBy:"Allow {tool} for {agent}?",approvalWaiting:"Waiting",scrollToBottom:"Scroll to bottom",suggestionsLabel:"Suggested prompts",contextLabel:"Context window",contextSystem:"System prompt",contextTools:"Tools",contextSummary:"Summary",contextMessages:"Messages",contextOther:"Other",contextFree:"Free",contextTotal:"Total",contextReclaim:"Compacting now would free ~{n} tokens",contextCompactNow:"Compact now",checkpointCount:"{n} messages summarised for the model",checkpointCountOne:"1 message summarised for the model",checkpointLegacy:"Earlier messages were summarised",checkpointGroup:"Context summary",checkpointShow:"Show summary",checkpointHide:"Hide summary",checkpointRestore:"Restore",checkpointRestoreConfirm:"Send the original messages to the model again?",checkpointPending:"Summarising the context\u2026",checkpointFailed:"Couldn't summarise the context",toolRunning:"Running",toolQueued:"Queued",toolCompleted:"Done",toolRejected:"Rejected",toolStopped:"Stopped",toolFailed:"Failed",toolInput:"Input",toolOutput:"Output",toolRejectedSaid:"You said: \u201C{instruction}\u201D",toolRefusedByPolicy:"Refused by policy",toolNotRunAfterRefusal:"Not run: an earlier call was refused",toolTimedOut:"Timed out",toolUnavailable:"Not available here",toolNoApprover:"No one could approve it",toolTurnLimit:"Turn limit reached",maxTurnsReached:"Stopped after {n} turns to avoid an endless loop.",sourcesCount:"{n} sources",sourcesOne:"1 source",sourcesCard:"Sources",sourcePrevious:"Previous source",sourceNext:"Next source",sourcePosition:"Source {i} of {n}",opensInNewTab:"(opens in a new tab)",imageLoad:"Load the image from {host}",imageLoadNamed:"Load the image \u201C{alt}\u201D from {host}",questionDeclined:"You declined to answer.",artifactNotCreated:"Not created",thoughtFor:"Thought for {duration}",thought:"Thought",turnWorking:"Working\u2026",turnWorked:"Worked {duration}",turnUsed:"Used {tools}",turnTools:"one:{n} tool|other:{n} tools",feedbackReasonTitle:"What went wrong?",feedbackReasonDismiss:"Not now",triggersLoading:"Loading\u2026",triggersEmpty:"No results",triggersError:"This list could not be loaded",triggersRetry:"Try again",triggersBack:"Back",triggersCommandNew:"Start a new conversation",triggersCommandStop:"Stop the reply",triggersCommandRetry:"Answer again",triggersCommandCopy:"Copy the last reply",triggersCommandCompact:"Summarise the earlier messages",triggersCompactNothing:"There is nothing to compact yet",triggersCompactBusy:"Wait for the reply to finish",triggersCompactNoWindow:"This model does not say how much it can read",triggersCompactFailed:"The summary could not be written",triggersCommandModel:"Change the model",triggersCommandApproval:"Change the approval mode",approvalOptionsLabel:"Your decision",approvalArgsLabel:"Arguments",actionUpload:"Attach file",removeAttachment:"Remove {name}",messageFrom:"Message from {name}",selectSearchPlaceholder:"Search\u2026",selectSearchLabel:"Search options",loading:"Loading\u2026",download:"Download",openArtifact:"Open",closeArtifact:"Close",artifactVersion:"Version {n} of {total}",previousVersion:"Previous version",nextVersion:"Next version",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",launcherHeading:"Chat",launcherMaximize:"Expand the chat",launcherRestore:"Shrink the chat",transcript:"Transcript"};function Gr(n){return typeof n.buildRequest=="function"&&typeof n.parseStream=="function"&&typeof n.defaultEndpoint=="string"&&(typeof n.authHeaders=="function"||typeof n.authQuery=="function")}function nc(n){return typeof n=="string"?{key:n}:n&&typeof n=="object"?{key:n.apiKey,endpoint:n.endpoint}:{}}function sc(n,t,e){let s=n?.error,i=typeof s=="object"?s?.message:s;return typeof i=="string"&&i?i:`${e} ${t}`}function ic(n){return typeof n=="string"&&Object.values(z).includes(n)}async function rc(n,t="HTTP",e){let s=await n.json().catch(()=>{}),i=sc(s,n.status,t),r=s?.error?.code,a=e?.classifyError?.(n.status,s)??(ic(r)?r:void 0)??lt.codeForStatus(n.status)??z.UNKNOWN_ERROR;return new lt(i,a,void 0,void 0,n.status)}async function ac(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 oc(i,r)}function oc(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 We=class{byok;warnedBrowserKey=!1;constructor(t={}){this.byok=t.byok??!1}async chat(t,e,s,i){let{key:r,endpoint:a}=nc(s);if(!this.byok&&r&&this.warnBrowserKeyOnce(i.providerId),!Gr(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 u=new URLSearchParams(t.authQuery(r)).toString();c+=(c.includes("?")?"&":"?")+u}let h=await fetch(c,{method:"POST",headers:d,body:JSON.stringify(l.body),signal:i.signal});if(!h.ok)throw await rc(h,"HTTP",t);if(e.stream===!1)return ac(t,h,i.providerId);if(!h.body)throw new Error(`Provider "${i.providerId}" returned no response body for a streaming request.`);return t.parseStream(h.body)}warnBrowserKeyOnce(t){this.warnedBrowserKey||(this.warnedBrowserKey=!0,console.warn(`[Aparte] AparteDirectTransport is sending the "${t}" API key straight from the browser \u2014 it is visible to anyone who opens devtools. Fine for BYOK or local models: pass new AparteDirectTransport({ byok: true }) to silence this. For a server-held key, use AparteBackendTransport so the key never reaches the client.`))}};function X(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}var lc=[{start:"<think>",end:"</think>"},{start:"<thinking>",end:"</thinking>"}],Kt=class{_options;_thinkingDelimiters;_blocks;_state;_pendingSegment=null;constructor(t={}){let e=t.thinkingDelimiters;this._thinkingDelimiters=e?Array.isArray(e)?e:[e]:lc,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(`
7
+ `);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(`
8
+ `)?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===`
9
+ `)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}-${X()}`}_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 Kr(n,t){let e=new Kt(t),s=e.parse(n),i=e.finalize();return[...s.segments,...i]}var cc=new Set(["pending","awaiting-approval"]),dc=["content","output","result"];function uc(n){return dc.some(t=>t in n)}function Ns(n,t,e,s){let i=fc(t,s);return{...i,messageId:t.messageId??e,index:t.index??n.length,...Ue(i,{startedAt:pe(t)?.startedAt??Date.now()})}}function hc(n,t,e,s=!1){let{queued:i,...r}=t;return{...r,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 pc=new Set(["id","type","messageId","index"]);function pe(n){return n.meta?.aparte}function Ue(n,t){return{meta:{...n.meta,aparte:{...n.meta?.aparte,...t}}}}function fc(n,t){if(!t)return n;let e={...n};for(let[s,i]of Object.entries(t))if(!(pc.has(s)||s in n)){if(s==="meta"){let{aparte:r,...a}=i??{};e.meta=a;continue}e[s]=i}return e}function xt(n){return n.type==="tool_call"?!cc.has(n.status):n.isStreaming===!1}function Vr(n,t){if(xt(n))return t;let e={...n,...t};if(xt(e)){let s=pe(n)?.endedAt;return{...t,...Ue(n,{endedAt:s??Date.now()})}}return uc(t)?{...t,...Ue(n,{endedAt:Date.now()})}:t}function Ds(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 Yr(n){let{startedAt:t,endedAt:e}=pe(n)??{};if(!(t==null||e==null))return e-t}function Qr(n){return xt(n)?{}:Ue(n,{endedAt:Date.now()})}function Gn(n){return{content:n.content,...n.isStreaming===!1?{isStreaming:!1}:{}}}function Bs(n){return n!=null&&n!=="streaming"&&n!=="pending"}function Xr(n){return n.filter(t=>!xt(t)).map(t=>t.id)}function en(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(hc(e,s,n.id,t)),e),[])}}function Jr(n){for(let t=0;t<n.length;t++){let e=n[t];e.index!==t&&(n[t]={...e,index:t})}}var fe="data-aparte-host",je=Symbol.for("aparte.instanceConfig");function gc(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 _c(n,t){let e=n[je]??L(n.parentElement);n[je]=t,n.setAttribute(fe,""),gc(n,t,e)}function L(n){let t=`[${fe}]`,e=n?.closest?.(t);for(;e&&!e[je];)e=e.parentElement?.closest(t);return e?.[je]??et}var Pe=null;function Q(n,t){let e=Pe;Pe=n;try{return t()}finally{Pe=e}}function M(n){return Pe??L(n)}function rt(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 P(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 I=P,ie="aparte-code-drawing",Zr="aparte-code-pending",Bi="data-aparte-open",ta="data-aparte-drawn",mc=4*1024*1024,ds=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-=Kn(t,s),this.entries.delete(t));let i={html:e};this.entries.set(t,i),this.size+=Kn(t,i);for(let[r,a]of this.entries){if(this.size<=mc||r===t)break;this.entries.delete(r),this.size-=Kn(r,a)}return i}},Kn=(n,t)=>n.length+(t.html?.length??0),mt=new WeakMap,Hs=new WeakMap,Hi=new WeakMap,$i=new WeakMap,qi=new WeakMap,ea=new WeakMap,na=new WeakMap,sa=new WeakMap,Fi=new WeakSet,Wi=new WeakSet,Vn=new WeakMap,Ui=new WeakMap,Te=new WeakMap;function bc(n){let t=Hi.get(n);return t||(t=new ds,Hi.set(n,t)),t}function vc(n){let t=$i.get(n);return t||(t=new Map,$i.set(n,t)),t}function ji(n,t){let e=n.get(t);return e||(e=new Map,n.set(t,e)),e}function re(n,t){Fi.has(n)||(Fi.add(n),console.warn(`[aparte] The ${n.languages.join("/")} renderer failed; the source is shown instead.`,t))}function yc(n){for(let t of Array.from(n.classList))if(t.startsWith("language-"))return t.slice(9).toLowerCase()||null;return null}function wc(n){return n.classList.contains("math-display")?!0:n.classList.contains("math-inline")?!1:n.parentElement?.tagName==="PRE"}function Ac(n){return n.hasAttribute(Bi)||n.parentElement?.tagName==="PRE"&&n.parentElement.hasAttribute(Bi)}function Sc(n,t){let e="";try{e=n.cacheKey?.(t)??""}catch(s){re(n,s)}return`${t.language}${t.display?"d":"i"}${e}${t.source}`}function ia(n){return typeof n?.then=="function"}function Cc(n){return n.closest("pre")??mt.get(n)?.drawing??n}function Ec(n){return n.closest("pre")??n.parentElement??n}var Yn=new Set,Qn=new Map,Xn=!1;function nn(n,t){t?Qn.set(n,t):Yn.add(n),!Xn&&(Xn=!0,queueMicrotask(()=>{Xn=!1;let e=[...Yn],s=[...Qn];Yn.clear(),Qn.clear();for(let i of e)Tc(i);for(let[i,r]of s)i.isConnected&&Ht(i,r)}))}var zi=new WeakMap;function kc(n,t,e){let s=zi.get(n);if(!s){let i=new Map;zi.set(n,i),s=i,n.then(()=>{for(let[r,a]of i)nn(r,a);i.clear()},()=>i.clear())}(!s.has(t)||e===void 0)&&s.set(t,e)}var Ot=null;function ra(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 Tc(n){if(!n.isConnected)return;let t=ra(n),e=t?t.getBoundingClientRect().top+(parseFloat(getComputedStyle(t).scrollPaddingTop)||0):0;Ot={scroller:t,top:e};try{Ht(n,sa.get(n)??{})}finally{Ot=null}}function xc(n,t){let e=Cc(n);if(Wi.has(e)||typeof IntersectionObserver>"u")return!1;let s=ra(e),i=Ui.get(IntersectionObserver);i||(i={byScroller:new WeakMap},Ui.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=(Te.get(a)??1)-1;if(Te.set(a,d),d<=0&&(a.disconnect(),s?i.byScroller.delete(s):i.page===a&&(i.page=void 0)),!c.isConnected)continue;Wi.add(c);let h=Vn.get(c);h&&nn(h)}},{root:s,rootMargin:"100% 0px"});r=a,s?i.byScroller.set(s,a):i.page=a}return Vn.get(e)!==t&&(Vn.set(e,t),Te.set(r,(Te.get(r)??0)+1),r.observe(e)),!0}function ne(n,t,e,s,i,r,a=!0){if(e.html===null){Vt(t,i.open);return}let o=Ot?Ec(t):null,l=o?o.getBoundingClientRect():null,c=mt.get(t),d=c?.drawing;if(d||(d=document.createElement("span"),d.className=ie,i.display&&d.setAttribute("data-aparte-display",""),s.bare?d.setAttribute("data-aparte-bare",""):d.setAttribute("dir","ltr"),t.after(d),Hs.set(d,t),t.parentElement?.tagName==="PRE"&&t.parentElement.setAttribute(ta,"")),c?.entry!==e||d.childNodes.length===0){let h=a?qi.get(n):void 0;a&&!h&&(h=new WeakMap,qi.set(n,h));let u=h?.get(e);if(u&&u.owner!==t&&!u.owner.isConnected&&t.isConnected&&!u.drawing.isConnected&&u.drawing.childNodes.length>0)d.replaceChildren(...u.drawing.childNodes),u.drawing.remove(),Vt(u.owner,!1);else{d.innerHTML=e.html;try{s.relabel?.(d,i)}catch(f){re(s,f)}}h&&(c&&c.entry!==e&&h.get(c.entry)?.drawing===d&&h.delete(c.entry),h.set(e,{drawing:d,owner:t}))}if(t.hidden=!0,t.style.setProperty("display","none"),t.classList.remove(Zr),mt.set(t,{renderer:s,key:r,drawing:d,entry:e,ctx:i}),o&&l&&Ot){let h=o.getBoundingClientRect().height-l.height;h>0&&l.bottom<=Ot.top&&(Ot.scroller?Ot.scroller.scrollTop+=h:window.scrollBy(0,h))}}function Vt(n,t){let e=mt.get(n);e&&(e.drawing.remove(),mt.delete(n)),n.parentElement?.tagName==="PRE"&&n.parentElement.removeAttribute(ta),n.hidden=!1,n.style.removeProperty("display"),n.classList.toggle(Zr,t)}function Mc(n,t,e,s,i,r){let a=Sc(e,s),o=mt.get(t);if(o&&o.renderer===e&&o.key===a&&o.drawing.childNodes.length>0)return;let l=bc(e),c=l.get(a);if(c){ne(n,t,c,e,s,a,!r);return}if(!o&&!r){let f=ea.get(n)?.get(i);f&&s.source.startsWith(f.source)&&ne(n,t,f,e,s,null),o=mt.get(t)}if(e.lazy&&!r&&!o&&xc(t,n))return;let d=vc(e),h=d.get(a);if(h){kc(h,n,r);return}let u;try{u=e.render(s)}catch(f){re(e,f),u=null}if(!ia(u)){ne(n,t,l.set(a,u??null),e,s,a,!r);return}let p=u.then(f=>(d.delete(a),l.set(a,f??null),f),f=>{throw d.delete(a),re(e,f),f});d.set(a,p),p.then(()=>nn(n,r),()=>{})}function Lc(n,t,e,s,i){let r=ji(ea,n),a=r.get(i);a&&s.source.startsWith(a.source)?mt.get(t)?.entry!==a&&ne(n,t,a,e,s,null):(r.delete(i),Vt(t,!0));let o=ji(na,n);if(o.get(i)===s.source)return;o.set(i,s.source);let l=()=>{o.get(i)===s.source&&o.delete(i)},c=h=>{if(h==null)return!1;let u=r.get(i);return u&&!s.source.startsWith(u.source)?!1:(r.set(i,{source:s.source,html:h}),!0)},d;try{d=e.render(s)}catch{d=null}if(!ia(d)){c(d)?ne(n,t,r.get(i),e,s,null):d==null&&l();return}d.then(h=>{c(h)?nn(n):h==null&&l()},l)}function Ic(n){for(let t of["code","kbd","samp"])for(let e of Array.from(n.getElementsByTagName(t)))e.hasAttribute("dir")||e.setAttribute("dir","ltr")}function Ht(n,t={}){if(typeof document>"u")return;let{streaming:e=!1,refresh:s=!1,language:i}=t;if(!s&&(Ic(n),sa.set(n,{streaming:e}),e||na.delete(n),!M(n).hasCodeLanguageRenderer())){n.querySelector(`.${ie}`)&&aa(n);return}let r=Array.from(n.querySelectorAll('code[class*="language-"]')).filter(o=>!o.closest(`.${ie}`)),a=new Map;r.forEach((o,l)=>{let c=yc(o);if(!c||i&&c!==i)return;let d=M(s?o:n),h=d.getCodeLanguageRenderer(c),u=mt.get(o);if(s&&(!u||u.key===null))return;if(!h){u&&Vt(o,!1);return}let p=wc(o),f=`${c}|${p?"d":"i"}`,g=a.get(f)??0;a.set(f,g+1);let _=`${f}|${g}`,w=o.textContent??"";if(!w.trim()){u&&Vt(o,!1);return}let S=e&&(Ac(o)||l===r.length-1),T={language:c,source:w,display:p,open:S,host:o,config:d};S?Lc(n,o,h,T,_):Mc(n,o,h,T,_,s?t:void 0)})}function aa(n){for(let t of Array.from(n.querySelectorAll(`.${ie}`))){let e=Hs.get(t);e?Vt(e,!1):t.remove()}}function oa(n){for(let t of Array.from(n.querySelectorAll(`.${ie}`))){let e=Hs.get(t),s=e?mt.get(e):void 0;if(s)try{s.renderer.relabel?.(t,s.ctx)}catch(i){re(s.renderer,i)}}}function us(n,t){return!!n&&M(t).hasCodeLanguageRenderer(n)}var la=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"]),$s=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"]),Rc=new Set(["class","style","title","dir","lang","role","align","aria-label","aria-hidden","aria-describedby","aria-level"]),Oc={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"])},Pc=new Set(["href","src"]),Nc=/^(?:https?:|mailto:|tel:|ftp:|sms:)/i,Dc=/^(?:[#/.?]|[a-z0-9._~%+-]+(?:[/?#]|$))/i,Bc=/^data:image\/(?:png|jpe?g|gif|webp|avif|bmp|x-icon|svg\+xml)[;,]/i,qs=/[\u0000-\u0020]+/g,Gi=/^(?:https?:)?[/\\]{2}|^https?:/i,Hc=/^aparte-/i,$c=new Set(["data-aparte-chat","data-aparte-host","data-aparte-theme","data-aparte-split-pane","data-aparte-launcher-close","data-aparte-launcher-maximize","data-aparte-suggestions","data-aparte-bubble","data-aparte-empty","data-aparte-panel","data-aparte-panel-host","data-aparte-card-part","data-segment-id","data-action"]),qc=["data-aparte-dialog-","data-aparte-sidebar-","data-checkpoint-"];function Fc(n){return $c.has(n)||qc.some(t=>n.startsWith(t))}var Wc=new Set(["button","link","checkbox","textbox","searchbox","combobox","switch","tab","menuitem","menuitemcheckbox","menuitemradio","option","radio","slider","spinbutton","scrollbar","treeitem","gridcell","listbox","menu","menubar","radiogroup","tablist","tree","treegrid","grid","dialog","alertdialog","application","toolbar","progressbar","tabpanel"]);function Uc(n,t){let e=t==="source"?"img":t;for(let s of n.matchAll(/(?:^|[^a-z0-9+.-])([a-z][a-z0-9+.-]*:[^\s,]*)/gi))if(!ge(s[1],e))return!1;return!0}function ge(n,t){let e=n.replace(qs,"");return!e||Nc.test(e)||t==="img"&&Bc.test(e)?!0:/^[a-z][a-z0-9+.-]*:/i.test(e)?!1:Dc.test(e)}var jc=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 zc(n){return n.includes("\\")?!1:n.startsWith("--")&&!n.startsWith("--aparte-")}function Gc(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()&&(!jc.has(r)&&!zc(r)||a.includes("\\")||/url\s*\(|expression\s*\(|javascript:|vbscript:|[<>]/i.test(a)||t.push(s))}return t.length?t.join("; "):null}function hs(n,t,e){let s=Oc[n];if(t.startsWith("on")||t.startsWith("formaction")||!t.startsWith("data-")&&!Rc.has(t)&&!(s&&s.has(t))||Fc(t)||t==="role"&&e.trim().toLowerCase().split(/\s+/).some(i=>Wc.has(i))||Pc.has(t)&&!ge(e,n)||t==="srcset"&&!Uc(e,n))return null;if(t==="style")return Gc(e);if(t==="class"){let i=e.split(/\s+/).filter(r=>r&&!Hc.test(r));return i.length?i.join(" "):null}return e}function Fs(n,t){let e=n.replace(qs,""),s=t.trim().toLowerCase();return s==="_self"&&!Gi.test(e)?[["target","_self"]]:s||Gi.test(e)?[["target","_blank"],["rel","noopener noreferrer"]]:[]}function Kc(n,t,e){for(let s of Array.from(n.attributes)){let i=s.name.toLowerCase(),r=hs(e,i,s.value);r!==null&&t.setAttribute(i,r)}if(e==="a")for(let[s,i]of Fs(t.getAttribute("href")??"",n.getAttribute("target")??""))t.setAttribute(s,i)}function ps(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(la.has(r))continue;if(!$s.has(r)){ps(i,t,e);continue}let a=r==="input";if(a&&(i.getAttribute("type")??"").trim().toLowerCase()!=="checkbox")continue;let o=e.createElement(r);Kc(i,o,r),a&&(o.setAttribute("type","checkbox"),o.setAttribute("disabled","")),ps(i,o,e),t.appendChild(o)}}var Vc=new Set(["html","head","body"]),Yc=new Set(["link","meta","base","embed","frame"]),Ki=new Map;function Qc(n){let t=Ki.get(n);return t||(t=new RegExp(`<\\s*\\/\\s*${n}\\s*>`,"gi"),Ki.set(n,t)),t}var Vi=/--!?>/g,Xc=/[A-Za-z]/,xe=/\s/,Jc=/[\s/>]/,Zc=/[\s/>=]/,td=/^[a-z][a-z0-9_.:-]*$/,ed={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",colon:":",lpar:"(",rpar:")",sol:"/",bsol:"\\",period:".",comma:",",semi:";",num:"#",excl:"!",quest:"?",tab:" ",newline:`
10
+ `};function nd(n){return n.includes("&")?n.replace(/&(?:#x([0-9a-f]+)|#([0-9]+)|([a-z]+));?/gi,(t,e,s,i)=>{if(i!==void 0)return ed[i.toLowerCase()]??t;let r=e!==void 0?parseInt(e,16):parseInt(s??"",10);return r>0&&r<=1114111&&(r<55296||r>57343)?String.fromCodePoint(r):"\uFFFD"}):n}var sd=n=>n.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;");function id(n,t){if(!$s.has(n))return"";let e=n==="input",s=r=>t.find(([a])=>a===r)?.[1];if(e&&(s("type")??"").trim().toLowerCase()!=="checkbox")return"";let i=[];e&&(i.push('type="checkbox"'),s("checked")!==void 0&&i.push("checked"),i.push("disabled"));for(let[r,a]of t){if(!td.test(r)||e&&(r==="type"||r==="checked"||r==="disabled"))continue;let o=hs(n,r,a);o!==null&&i.push(`${r}="${sd(o)}"`)}if(n==="a"){let r=t.find(([o])=>o==="href"),a=r?hs("a","href",r[1]):null;for(let[o,l]of Fs(a??"",s("target")??""))i.push(`${o}="${l}"`)}return`<${n}${i.length?" "+i.join(" "):""}>`}function Ws(n,t){let e=n.length,s=t;for(;s<e&&!Jc.test(n[s]);)s++;let i=n.slice(t,s).toLowerCase(),r=[],a=new Set;for(;s<e;){for(;s<e&&(xe.test(n[s])||n[s]==="/");)s++;if(s>=e)break;if(n[s]===">")return{tag:i,attrs:r,end:s+1};let o=s++;for(;s<e&&!Zc.test(n[s]);)s++;let l=n.slice(o,s).toLowerCase(),c=s;for(;c<e&&xe.test(n[c]);)c++;let d="";if(n[c]==="="){for(c++;c<e&&xe.test(n[c]);)c++;let h=n[c];if(h==='"'||h==="'"){let u=n.indexOf(h,c+1);if(u<0)break;d=n.slice(c+1,u),s=u+1}else{let u=c;for(;c<e&&!xe.test(n[c])&&n[c]!==">";)c++;d=n.slice(u,c),s=c}}a.has(l)||(a.add(l),r.push([l,nd(d)]))}return{tag:i,attrs:r,end:-1}}function rd(n){let t=n.length,e="",s=0;for(;s<t;){let i=n.indexOf("<",s);if(i<0){e+=n.slice(s);break}if(e+=n.slice(s,i),n.startsWith("<!--",i)){let d=i+4;if(n[d]===">")s=d+1;else if(n.startsWith("->",d))s=d+2;else{Vi.lastIndex=d;let h=Vi.exec(n);if(!h)break;s=h.index+h[0].length}continue}let r=n[i+1]==="/",a=i+(r?2:1);if(!Xc.test(n[a]??"")){if(n[i+1]==="!"||n[i+1]==="?"||r){let d=n.indexOf(">",i+1);s=d<0?t:d+1}else e+="&lt;",s=i+1;continue}let{tag:o,attrs:l,end:c}=Ws(n,a);if(c<0)break;if(s=c,r)$s.has(o)&&(e+=`</${o}>`);else if(la.has(o)&&!Vc.has(o)&&!Yc.has(o)){let d=Qc(o);d.lastIndex=c;let h=d.exec(n);if(!h)break;s=h.index+h[0].length}else e+=id(o,l)}return e}function Yi(n){return rd(n)}var fs=n=>{if(!n)return n;if(typeof DOMParser>"u")return Yi(n);let t;try{t=new DOMParser().parseFromString(n,"text/html")}catch{return Yi(n)}let e=t.createElement("div");return ps(t.body,e,t),e.innerHTML},vt="aparte-citation",ca="aparte-citation-marker",da=/[\p{L}\p{N}]/u,ad=[24,12,6],ua=new Set(["A","ABBR","B","CITE","CODE","DEL","EM","I","INS","KBD","MARK","Q","S","SMALL","SPAN","STRONG","SUB","SUP","U"]),Qi=/[.,;:!?)\]}»"'’”…。、,.!?:;」』)】》،؛؟]/,od=/[\u00a0\u202f]/,Us=new WeakMap,ha=new WeakMap,Xi=new WeakSet,Ne=new WeakMap,Et=null;function js(n){let t=n.url?.trim();return t&&/^https?:\/\//i.test(t)&&ge(t,"a")?t:void 0}function pa(n,t,e,s){let i=document.createElement("a");i.href=n;let r=e.decideLink(n);if(r.target&&(i.target=r.target),r.rel&&(i.rel=r.rel),i.textContent=t,i.dir="auto",r.target==="_blank"){let a=document.createElement("span");a.className="aparte-sr-only",a.textContent=` ${s}`,i.append(a)}return i}function ze(n){let t=js(n);if(t)try{return new URL(t).hostname.replace(/^www\./,"")}catch{}return n.title??""}function ld(n){let t=ze(n[0])||"?";return n.length>1?`${t} +${n.length-1}`:t}function gs(n,t){let e=n.getLocale();return t===1?e.sourcesOne??"1 source":(e.sourcesCount??"{n} sources").replace("{n}",()=>String(t))}function cd(n){if(typeof document>"u")return"";let t=document.createElement("textarea");return t.innerHTML=n,t.value}function Ji(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,cd)}function dd(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+=Ji(t.slice(s,r.index))+r[2],s=(r.index??0)+r[0].length;e+=Ji(t.slice(s));let i="";for(let r of e)da.test(r)&&(i+=r);return i}function ud(n){let t="",e=[],s=n.ownerDocument.createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode:i=>i.parentElement?.closest(`.aparte-code-drawing, .${vt}`)?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,!!da.test(l)){t+=l;for(let c=0;c<o;c++)e.push([i,a])}}}return{text:t,ends:e}}function hd(n,t){let e=0;for(let s=n.indexOf(t);s>=0;s=n.indexOf(t,s+1))e++;return e}function pd(n,t,e){let s=dd(n.slice(0,Math.max(0,Math.min(n.length,t.end))));if(!s)return null;for(let i of ad){let r=s.slice(-i),a=hd(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 Zi(n,t){let e=t;for(;e<n.length&&(Qi.test(n[e])||od.test(n[e])&&Qi.test(n[e+1]??""));)e++;return e-t}function fd(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&&ua.has(l.tagName);l=l.parentElement)r=l;if(!r){e.splitText(s+Zi(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=Zi(o.data,0);l>0&&(o.splitText(l),a=o)}a.parentNode.insertBefore(t,a.nextSibling)}function gd(n,t,e,s){let i=l=>{let c=document.createElement("span");c.className=ca,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&&ua.has(a.tagName)&&a.textContent?.trim()===o?(i(a),!0):!1}function _d(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"),Us.set(e,n),fa(e,t),e}function fa(n,t){let e=Us.get(n)??[],s=ld(e);n.dataset.label=s,n.setAttribute("aria-label",`${s}, ${gs(t,e.length)}`)}function ga(n){let t=new Set;for(let e of Array.from(n.querySelectorAll(`.${vt}`)))e.parentNode&&t.add(e.parentNode),e.remove();for(let e of Array.from(n.querySelectorAll(`.${ca}`)))e.parentNode&&t.add(e.parentNode),e.replaceWith(...Array.from(e.childNodes));for(let e of t)e.normalize();Ne.delete(n)}function _s(n,t){if(typeof document>"u")return;let e=t.citations??[],s=new Map((t.sources??[]).map(g=>[g.id,g])),i=JSON.stringify([t.content,e,[...s.values()].map(g=>[g.id,g.url,g.title,g.snippet])]),r=Array.from(n.querySelectorAll(`.${vt}`)),a=Ne.get(n);if(a&&a.signature===i&&a.count===r.length)return;let o=document.activeElement,l=Et?.root===n&&(o===Et.chip||(!o||o===document.body)&&!Et.chip.isConnected)?Et.at:-1,c=F?.root===n?F.chip.isConnected?r.indexOf(F.chip):F.at:-1;if(ga(n),e.length===0||s.size===0){Ne.set(n,{signature:i,count:0}),c>=0&&ut(!1);return}let d=M(n);Xi.has(n)||(Xi.add(n),n.addEventListener("click",g=>{let _=g.target?.closest?.(`.${vt}`);!_||!n.contains(_)||(g.preventDefault(),bd(_))}),n.addEventListener("focusin",g=>{let _=g.target;_.classList?.contains(vt)&&(Et={root:n,chip:_,at:Array.from(n.querySelectorAll(`.${vt}`)).indexOf(_)})}),n.addEventListener("focusout",g=>{Et?.root===n&&g.relatedTarget&&(Et=null)}));let h=ud(n),u=new Map;for(let g of e){let _=g.sources.map(m=>s.get(m)).filter(m=>!!m);if(_.length===0)continue;let w=pd(t.content,g,h);if(!w)continue;let S=h.ends.indexOf(w),T=g.marker&&g.start!==void 0?t.content.slice(g.start,g.end):null,k=u.get(S)??{node:w[0],offset:w[1],marker:T,sources:[]};for(let m of _)k.sources.includes(m)||k.sources.push(m);u.set(S,k)}let p=[...u.values()].sort((g,_)=>g.node===_.node?_.offset-g.offset:g.node.compareDocumentPosition(_.node)&Node.DOCUMENT_POSITION_FOLLOWING?1:-1);for(let g of p){let _=_d(g.sources,d);ha.set(_,n),!(g.marker&&gd(_,g.node,g.offset,g.marker))&&fd(n,_,g.node,g.offset)}let f=Array.from(n.querySelectorAll(`.${vt}`));if(Ne.set(n,{signature:i,count:f.length}),l>=0&&(f[l]?f[l].focus({preventScroll:!0}):Et=null),c>=0&&F){let g=f[c];g?(F.chip=g,F.at=c,g.setAttribute("aria-expanded","true"),g.setAttribute("aria-controls",F.el.id)):ut(!1)}}function _a(n){let t=M(n);for(let e of Array.from(n.querySelectorAll(`.${vt}`)))fa(e,t)}var F=null,md=0;function bd(n){F?.chip===n?ut(!0):vd(n)}function vd(n){ut(!1);let t=Us.get(n)??[];if(t.length===0)return;let e=ha.get(n)??n.parentElement,s=Array.from(e.querySelectorAll(`.${vt}`)).indexOf(n),i=M(n),r=document.createElement("div");r.className="aparte-citation-card aparte-popover",r.id=`aparte-citation-card-${++md}`;let a=n.closest(".aparte-viewport-container, aparte-chat-viewport")??n.ownerDocument.documentElement;r.dir=getComputedStyle(a).direction==="rtl"?"rtl":"ltr",r.setAttribute("role","dialog"),r.setAttribute("aria-label",i.getLocale().sourcesCard??"Sources");let o=document.createElement("div");o.className="aparte-citation-card__body";let l=document.createElement("p");l.className="aparte-sr-only",l.setAttribute("role","status"),r.append(o,l);let c=typeof r.showPopover=="function";c&&(r.popover="manual"),(n.closest("aparte-chat-viewport")?.parentElement??n.ownerDocument.body).append(r),c&&r.showPopover(),n.setAttribute("aria-expanded","true"),n.setAttribute("aria-controls",r.id);let d=typeof MutationObserver=="function"?new MutationObserver(wd):null;d?.observe(n.ownerDocument.body,{childList:!0,subtree:!0}),F={root:e,chip:n,at:s,el:r,body:o,status:l,sources:t,index:0,config:i,watch:d},ya(),ae(),document.addEventListener("keydown",ma,!0),document.addEventListener("pointerdown",ba,!0),window.addEventListener("scroll",va,!0),window.addEventListener("resize",ae),r.addEventListener("focusout",Sd),r.addEventListener("keydown",Ad),yd(r)}function yd(n){(n.querySelector("a")??n.querySelector("button:not([disabled])"))?.focus()}function ut(n){if(!F)return;let{chip:t,el:e,watch:s}=F;F=null,s?.disconnect(),e.remove(),t.setAttribute("aria-expanded","false"),t.removeAttribute("aria-controls"),document.removeEventListener("keydown",ma,!0),document.removeEventListener("pointerdown",ba,!0),window.removeEventListener("scroll",va,!0),window.removeEventListener("resize",ae),n&&t.isConnected&&t.focus()}function wd(){F&&!F.chip.isConnected&&ut(!1)}function ma(n){n.key!=="Escape"||!F||(n.preventDefault(),ut(!0))}function Ad(n){if(n.key!=="Tab"||!F)return;let t=Array.from(F.el.querySelectorAll("a[href], button:not([disabled])")),e=n.shiftKey?t[0]:t[t.length-1];document.activeElement===e&&(n.preventDefault(),ut(!0))}function ba(n){if(!F)return;let t=n.target;t&&(F.el.contains(t)||F.chip.contains(t))||ut(!1)}function Sd(n){if(!F)return;let t=n.relatedTarget;t&&(F.el.contains(t)||F.chip.contains(t))||t&&ut(!1)}function Cd(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 va(){if(!F)return;let n=Cd(F.chip);if(n){let t=n.getBoundingClientRect(),e=F.chip.getBoundingClientRect();if(e.bottom<t.top||e.top>t.bottom){ut(!1);return}}ae()}function ae(){if(!F)return;let{chip:n,el:t}=F;if(!n.isConnected){ut(!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 ya(){if(!F)return;let{el:n,body:t,status:e,sources:s,index:i,config:r}=F,a=r.getLocale(),o=s[i],l=n.contains(document.activeElement)?document.activeElement.dataset.aparteCardPart:void 0;if(t.replaceChildren(),s.length>1){let u=document.createElement("div");u.className="aparte-citation-card__pager";let p=tr(a.sourcePrevious??"Previous source",r.getIcon("prevBranch"),"prev",i===0,()=>er(-1)),f=document.createElement("span");f.className="aparte-citation-card__position",f.textContent=`${i+1}/${s.length}`,f.setAttribute("aria-hidden","true");let g=tr(a.sourceNext??"Next source",r.getIcon("nextBranch"),"next",i===s.length-1,()=>er(1));u.append(p,f,g),t.append(u)}let c=js(o),d=o.title||ze(o)||o.url||"";if(c){let u=pa(c,d,r,a.opensInNewTab??"(opens in a new tab)");u.className="aparte-citation-card__title",u.dataset.aparteCardPart="link",u.addEventListener("click",Ed),t.append(u)}else{let u=document.createElement("p");u.className="aparte-citation-card__title",u.textContent=d,u.dir="auto",t.append(u)}let h=ze(o);if(h&&h!==d){let u=document.createElement("p");u.className="aparte-citation-card__domain",u.textContent=h,u.dir="auto",t.append(u)}if(o.snippet){let u=document.createElement("p");u.className="aparte-citation-card__snippet",u.textContent=o.snippet,u.dir="auto",t.append(u)}if(s.length>1&&(e.textContent=(a.sourcePosition??"Source {i} of {n}").replace("{i}",()=>String(i+1)).replace("{n}",()=>String(s.length))),l){let u=n.querySelector(`[data-aparte-card-part="${l}"]`);u&&!u.disabled?u.focus():(n.querySelector(".aparte-citation-card__pager button:not([disabled])")??n.querySelector("a"))?.focus()}}function Ed(n){let t=F?.chip,e=n.currentTarget;if(!t?.isConnected)return;let s={href:e.getAttribute("href")??"",anchor:e,messageId:t.closest("aparte-chat-bubble")?.getAttribute("message-id")??null};t.dispatchEvent(new CustomEvent("aparte-link-click",{bubbles:!0,composed:!0,cancelable:!0,detail:s}))||n.preventDefault()}function tr(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 er(n){F&&(F.index=Math.max(0,Math.min(F.sources.length-1,F.index+n)),ya(),ae())}function wa(n,t,e,s){let i=n.querySelector(":scope > .aparte-sources"),r=[],a=new Set;for(let h of e){let u=h.url??`#${h.id}${h.title??""}`;a.has(u)||(a.add(u),r.push(h))}if(r.length===0){i?.remove();return}let o=s.getLocale().opensInNewTab??"(opens in a new tab)",l=[o,...r.map(h=>`${h.url??h.id}${h.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=gs(s,r.length);return}i.dataset.aparteKey=l;let c=document.createElement("summary");c.className="aparte-sources__summary",c.textContent=gs(s,r.length);let d=document.createElement("ol");d.className="aparte-sources__list";for(let h of r){let u=document.createElement("li");u.className="aparte-sources__item";let p=ze(h),f=h.title||p||h.url||"",g=js(h);if(g?u.append(pa(g,f,s,o)):u.append(Object.assign(document.createElement("span"),{textContent:f,dir:"auto"})),p&&p!==f){let _=document.createElement("span");_.className="aparte-sources__domain",_.textContent=p,_.dir="auto",u.append(" ",_)}d.append(u)}i.replaceChildren(c,d)}var Xt=new WeakMap,nr="<i>a</i>";function sr(){return M().renderMarkdown(nr)!==P(nr)}function Yt(n,t,e,s){kd(n,t,e,s),Ht(t,{streaming:s})}function kd(n,t,e,s){let i=M();if(s){if(Xt.delete(t),n._aparteSmd===void 0){let a=M().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,!sr()){aa(t),ga(t),t.innerHTML=i.sanitizeHtml(t.innerHTML),Xt.set(t,{content:e,config:i,version:dt(i),writer:"parser"});return}}else{let r=Xt.get(t);if(r?.content===e&&(r.writer==="parser"&&!sr()||r.writer==="markdown"&&r.config===i&&r.version===dt(i)))return}t.innerHTML=i.renderMarkdown(e),s?Xt.delete(t):Xt.set(t,{content:e,config:i,version:dt(i),writer:"markdown"})}function ms(n){if(!M().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(us(i,n)||e.closest(".aparte-code-drawing"))continue;let r=e.textContent??"";e.setAttribute("data-aparte-highlighted",""),M().highlightCode(r,i,{fallback:!1}).then(a=>{(s.isConnected||s.parentElement)&&zs(s,a)}).catch(()=>e.removeAttribute("data-aparte-highlighted"))}}function zs(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 Td={type:"text",render:n=>`<div class="aparte-segment aparte-segment-text" data-segment-id="${P(n.id)}"><div class="aparte-segment-content" dir="auto">${M().renderMarkdown(n.content)}</div></div>`,setup:(n,t)=>{let e=n.querySelector(".aparte-segment-content");e&&(t.isStreaming===!0?Yt(n,e,t.content,!0):(Ht(e,{streaming:!1}),ms(e)),_s(e,t))},update:(n,t)=>{let e=n.querySelector(".aparte-segment-content");e&&(Yt(n,e,t.content,t.isStreaming!==!1),t.isStreaming===!1&&ms(e),_s(e,t))},getStyles:()=>""};function Gs(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 xd=24;function bs(n){if(n.label&&n.label!=="Thinking")return n.label;let t=M();if(!xt(n))return t.t("thinking");let s=n.showDuration??t.getSegmentDefaults("thinking")?.showDuration===!0?Yr(n):void 0;return s===void 0?t.t("thought"):t.t("thoughtFor").replace("{duration}",()=>Gs(s,t.getLocale().tag||void 0))}var vs=n=>n.isStreaming===!0;function ir(n,t){let e=bs(t),s=n.querySelector(".aparte-thinking-label");s&&s.textContent!==e&&(s.textContent=e),s?.classList.toggle("aparte-shimmer",vs(t)),n.querySelector(".aparte-thinking-content")?.setAttribute("aria-label",e)}var Md={type:"thinking",render:n=>`<details class="aparte-segment aparte-segment-thinking aparte-accordion__item" data-segment-id="${P(n.id)}" ${n.collapsed===!1?"open":""}><summary class="aparte-accordion__header aparte-thinking-header"><span class="aparte-thinking-label${I(vs(n)?" aparte-shimmer":"")}">${P(bs(n))}</span><span class="aparte-accordion__icon">${M().getIcon("expand")}</span></summary><div class="aparte-accordion__panel aparte-thinking-content" dir="auto" role="region" tabindex="0" aria-label="${I(bs(n))}">${M().renderMarkdown(n.content)}</div></details>`,relabel:(n,t)=>ir(n,t),setup:(n,t)=>{let e=n.querySelector(".aparte-thinking-content");e&&(vs(t)?Yt(n,e,t.content,!0):Ht(e,{streaming:!1}))},update:(n,t)=>{ir(n,t);let e=n.querySelector(".aparte-thinking-content");if(!e)return;let s=e.scrollHeight-e.scrollTop-e.clientHeight<=xd,i=t.isStreaming!==!1;Yt(n,e,t.content,i),i||ms(e),s&&(e.scrollTop=e.scrollHeight)},getStyles:()=>""};function Ks(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 Ld=1500;function ys(n,t){n.setAttribute("aria-label",t),n.setAttribute("title",t)}function Vs(n){let t=I(M().t("copy")),e=M().getIcon("copy");return`<button type="button" class="aparte-btn aparte-btn--icon aparte-btn--sm ${I(n)}" data-action="copy" aria-label="${t}" title="${t}">${e}</button>`}function Aa(n,t){n.addEventListener("click",()=>{Ks(t()).catch(()=>{}),n.innerHTML=M(n).getIcon("check"),ys(n,M(n).t("copied")),n.dataset.copied="1",setTimeout(()=>{n.innerHTML=M(n).getIcon("copy"),ys(n,M(n).t("copy")),delete n.dataset.copied},Ld)})}function Sa(n){n.dataset.copied||(ys(n,M().t("copy")),n.innerHTML=M().getIcon("copy"))}var Id=400,Rd=256,rr=new Map;function Od(n,t,e){if(n.delete(t),n.size>=Rd){let s=n.keys().next().value;s!==void 0&&n.delete(s)}n.set(t,e)}function ar(n){let t=Number(n.dataset.aparteHlLen);return Number.isFinite(t)&&t>0?t:0}function Pd(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=ar(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-${P(s||"text")}">${P(e)}</code></pre>`}let l=e.lastIndexOf(`
11
+ `)+1;if(l<=o)return;let c=Date.now();c-(rr.get(i)??0)<Id||(Od(rr,i,c),M(n).highlightCode(e.slice(0,l),s).then(d=>{let h=n.querySelector(t);if(!h||h.dataset.aparteSettled!==void 0||l<=ar(h))return;h.innerHTML=d;let u=h.querySelector("code")??h,p=document.createElement("span");p.dataset.aparteTail="",p.textContent=e.slice(l),u.appendChild(p),h.dataset.aparteHlLen=String(l)}).catch(()=>{}))}var Jn=new WeakMap,jt=new WeakMap,Zn=new WeakMap;function or(n,t){let e=n.querySelector(".aparte-code-content-wrapper");if(!e)return;let s=`${t.language??""}${t.content}`,i=M(),r=Zn.get(n);if(r?.what===s&&r.config===i)return;Zn.set(n,{what:s,config:i});let a=(jt.get(n)??0)+1;jt.set(n,a),e.dataset.aparteSettled="",i.highlightCode(t.content,t.language||"",{fallback:!1}).then(o=>{jt.get(n)===a&&(e.innerHTML=o)}).catch(()=>{jt.get(n)===a&&Zn.delete(n)})}var Ge=n=>(n.language||"").trim().split(/\s+/)[0]??"";function lr(n,t){let e=Ge(t),s=e?M(n).getCodeLanguageRenderer(e):void 0;n.toggleAttribute("data-aparte-bare",!!s&&s.card!==!0)}function cr(n,t){let e=n.querySelector(".aparte-code-content-wrapper");if(!e)return;jt.set(n,(jt.get(n)??0)+1),e.dataset.aparteSettled="";let s=Ge(t),i=Array.from(e.querySelectorAll("pre > code")).find(r=>r.classList.contains(`language-${s}`));i||(e.innerHTML=`<pre><code class="language-${P(s)}"></code></pre>`,i=e.querySelector("pre > code")),i.textContent!==t.content&&(i.textContent=t.content),Ht(e,{streaming:t.isStreaming===!0})}var Nd={type:"code",render:n=>{let t=Vs("aparte-code-copy");return`
12
+ <div class="aparte-segment aparte-segment-code" data-segment-id="${P(n.id)}">
13
+ <div class="aparte-code-header">
14
+ ${n.filename?`<span class="aparte-code-filename">${P(n.filename)}</span>`:'<span class="aparte-code-header-filler"></span>'}
15
+ <span class="aparte-code-language">${P(n.language||"")}</span>
16
+ ${t}
17
+ </div>
18
+ <div class="aparte-code-content-wrapper">
19
+ <pre><code class="language-${P(n.language||"text")}">${P(n.content)}</code></pre>
20
+ </div>
21
+ </div>
22
+ `},relabel:n=>{let t=n.querySelector(".aparte-code-copy");t&&Sa(t)},setup:(n,t)=>{Jn.set(n,t.content),lr(n,t),us(Ge(t),n)?cr(n,t):t.isStreaming!==!0&&or(n,t);let e=n.querySelector(".aparte-code-copy");e&&Aa(e,()=>Jn.get(n)??"")},update:(n,t)=>{Jn.set(n,t.content),lr(n,t),us(Ge(t),n)?cr(n,t):t.isStreaming===!0?Pd(n,".aparte-code-content-wrapper",t.content,t.language||"",t.id):or(n,t)},getStyles:()=>""};function ws(n,t){switch(n){case z.NET_OFFLINE:case z.NET_ERROR:return t("errorUnreachable");case z.NET_TIMEOUT:return t("errorTimeout");case z.CONFIG_INVALID_KEY:return t("errorRefused");case z.USAGE_RATE_LIMIT:return t("errorRateLimited");case z.USAGE_CONTEXT_EXCEEDED:return t("errorTooLong");case z.PROVIDER_ERROR:case z.PROVIDER_UNAVAILABLE:return t("errorFailed");case z.USAGE_BAD_REQUEST:case z.PROVIDER_POLICY:case z.PROVIDER_MISCONFIGURED:case z.CONFIG_INVALID_MODEL:case z.UNKNOWN_ERROR:return t("errorNoAnswer");default:return}}var Dd={type:"error",render:n=>{let t=M(),e=ws(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`
23
+ <div class="aparte-segment aparte-alert aparte-alert--danger aparte-segment-error" data-segment-id="${P(n.id)}"${n.code?` data-error-code="${I(n.code)}"`:""}>
24
+ <span class="aparte-alert__icon">${t.getIcon("error")||"\u26A0"}</span>
25
+ <div class="aparte-alert__body">
26
+ <div class="aparte-alert__title">${P(t.t("error"))}</div>
27
+ <div class="aparte-alert__message">${P(i)}</div>
28
+ ${n.details?`<pre class="aparte-segment-error__details">${P(n.details)}</pre>`:""}
29
+ </div>
30
+ </div>
31
+ `},relabel:(n,t)=>{let e=M();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=ws(t.code,o=>e.t(o)),a=n.querySelector(".aparte-alert__message");a&&r!==void 0&&(a.textContent=r)},getStyles:()=>""};function Ca(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""}}var dr=new WeakSet;function Nt(n,t){let e=t.getToolLineProvider();if(e)try{let s=e(n);return s&&typeof s=="object"?s:void 0}catch(s){dr.has(e)||(dr.add(e),console.error("[aparte] The tool-line provider threw; the row keeps its default line. Further throws from it are not reported.",s));return}}var oe=n=>typeof n=="string"?n.trim():"";function sn(n,t,e=Nt(n,t)){let s=n.toolCall?.name??"tool",i=t.getToolDisplay(s)?.label;if(i!==void 0)try{let a=typeof i=="function"?i(n):i;if(typeof a=="string"&&a.trim())return{text:a.trim(),isLabel:!0}}catch{}let r=oe(e?.label);return r?{text:r,isLabel:!0}:{text:s,isLabel:!1}}function Bd(n,t,e=Nt(n,t)){return Ea(n,t,e).text}function Ea(n,t,e=Nt(n,t)){let s=t.getToolSummary(n.toolCall?.name??"");if(s)try{let r=oe(s(n));if(r)return{text:r,isWords:!1}}catch{}let i=oe(e?.target);return{text:i,isWords:i!==""}}function ka(n,t){return oe(t?.activity)}function Hd(n){return oe(n?.note)}function Ta(n){return Ca(n.toolCall?.input,M().getToolInputFormatter(n.toolCall?.name??""))}function As(n){let t=M(),e=n.status??"pending",s=i=>P(i);return e==="awaiting-approval"?`${t.getIcon("pause")}${s(t.t("approvalWaiting"))}`:rn(n)?s(t.t("toolQueued")):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 $d(n){let t=M();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 xa(n,t){return[$d(n),Hd(t)].filter(Boolean).join(" \xB7 ")}function Ss(n){let t=Ud(n.result??"");return!t||n.status==="rejected"&&n.refusal?null:{key:"toolOutput",text:t}}function ts(n,t,e){let s=M().getToolDisplay(n.toolCall?.name??""),i=s&&"details"in s?s.details:t?.details;if(i===!1)return{kind:"none"};if(typeof i!="function")return{kind:"parts"};try{let r=i(n,e?qd(e):void 0);return r?{kind:"body",body:typeof r=="string"?M().sanitizeHtml(r):r}:{kind:"none"}}catch{return{kind:"none"}}}function Cs(n){return n.tagName==="DETAILS"?n:n.querySelector(":scope > details.aparte-tool-disclosure")}var Es=n=>n.querySelector(':scope > .aparte-tool-detail[data-details="app"], :scope > .aparte-tool-disclosure > .aparte-tool-detail[data-details="app"]');function Ma(n,t){let e=n.querySelector(".aparte-tool-detail");e&&(typeof t!="string"&&t.parentNode===e||(typeof t=="string"?(e.innerHTML=t,le.delete(e)):(e.replaceChildren(t),le.set(e,t)),De.set(e,La(t))))}var le=new WeakMap;function qd(n){let t=Es(n),e=t?le.get(t):void 0;return e&&e.parentNode===t?e:void 0}var De=new WeakMap,La=n=>typeof n=="string"?n:n.outerHTML;function Fd(n,t){if(typeof t!="string"&&n.contains(t)){De.set(n,t.outerHTML);return}let e=De.get(n),s=La(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&&ks(r,i)&&ks(r,n)?Ia(n,r,i):(n.replaceChildren(...Array.from(i.childNodes)),typeof t=="string"?le.delete(n):le.set(n,t)),De.set(n,s)}function ks(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||!ks(s,i))return!1}return!0}function Ia(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);Ia(i,r,a)}else r.nodeValue!==a.nodeValue&&(i.nodeValue=a.nodeValue)}}function ur(n,t,e){let s=n.querySelector(".aparte-tool-note");if(!s)return;let i=xa(t,e);s.textContent!==i&&(s.textContent=i),s.toggleAttribute("hidden",!i),i?s.setAttribute("title",i):s.removeAttribute("title")}function hr(n,t,e,s){let i=n.querySelector(`[data-part="${t}"]`);if(!e){i?.remove();return}if(i){let f=i.querySelector("code");f&&f.textContent!==e&&(f.textContent=e);let g=i.querySelector(".aparte-tool-part-label"),_=M().t(s);g&&g.textContent!==_&&(g.textContent=_),i.querySelector(".aparte-tool-part-body")?.setAttribute("aria-label",_);return}let r=n.querySelector(".aparte-tool-detail");if(!r)return;let a=M(),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=Vs("aparte-tool-copy"),l.append(c,d.content);let h=document.createElement("div");h.className="aparte-tool-part-body",h.setAttribute("role","region"),h.tabIndex=0,h.setAttribute("aria-label",c.textContent);let u=document.createElement("pre"),p=document.createElement("code");p.textContent=e,u.appendChild(p),h.appendChild(u),o.append(l,h),t==="input"?r.prepend(o):r.appendChild(o),Ra(o)}function Ra(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");Aa(t,()=>e?.querySelector(".aparte-tool-part-body")?.textContent??"")}}var Wd=2e5;function Oa(n){let t=n.trim();if(!(t.length>Wd||!(t.startsWith("{")||t.startsWith("["))))try{let e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}}function Ud(n){let t=Oa(n);return t===void 0?n:JSON.stringify(t,null,2)}function pr(n){let t=M();for(let e of n.querySelectorAll(".aparte-tool-part-body")){let s=e.querySelector("code")?.textContent??"";!s||Oa(s)===void 0||t.highlightCode(s,"json").then(i=>{(e.querySelector("code")?.textContent??"")===s&&(e.innerHTML=i)}).catch(()=>{})}}function Pa(n,t){return Ea(n,M(),t)}function fr(n,t,e){let s=n.querySelector(".aparte-tool-target");if(!s)return;let{text:i,isWords:r}=Pa(t,e);s.textContent!==i&&(s.textContent=i),s.toggleAttribute("hidden",!i),s.classList.toggle("aparte-tool-target--words",r)}function gr(n,t,e){let s=n.querySelector(".aparte-tool-activity");if(!s)return;let i=ka(t,e);s.textContent!==i&&(s.textContent=i),s.toggleAttribute("hidden",!i)}function Na(n,t){return sn(n,M(),t)}function Da(n){let t=M(),e=t.getToolDisplay(n.toolCall?.name??"")?.icon;return(e?t.getIcon(e):void 0)||t.getIcon("tool")}var Ys=n=>M().getToolDisplay(n.toolCall?.name??"")?.quiet??!0,rn=n=>(n.status??"pending")==="pending"&&(n.queued===!0||n.deferred?.reason==="queued");function Ba(n){let t=n.status??"pending",e=Ys(n),s=t==="pending"&&!rn(n);return{shimmer:e&&s,spinner:!e&&s,stateHidden:e&&(s||t==="resolved")}}function _r(n,t){let e=Ba(t);n.toggleAttribute("data-quiet",Ys(t)),n.toggleAttribute("data-queued",rn(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 mr(n,t,e){let s=n.querySelector(".aparte-tool-name");if(!s)return;let{text:i,isLabel:r}=Na(t,e);s.textContent!==i&&(s.textContent=i),s.classList.toggle("aparte-tool-name--label",r)}var Ts=new WeakMap;function an(n){let t=n?.open;return t&&typeof t.onOpen=="function"?t:void 0}function jd(n){let t=an(n);return t?` data-opens${t.current?" data-current":""}`:""}function Qs(n){let t=an(n);if(!t)return"";let e=I(typeof t.label=="string"?t.label.trim():""),s=M().getIcon("maximize");return`<button type="button" class="aparte-btn aparte-btn--icon aparte-btn--sm aparte-tool-open" aria-label="${e}" title="${e}"${t.current?' aria-current="true"':""}>${s}</button>`}function es(n,t,e){let s=an(t),i=n.querySelector(":scope > .aparte-tool-line"),r=n.querySelector(":scope > :is(.aparte-tool-line, .aparte-tool-open-slot) > .aparte-tool-open");if(s?Ts.set(n,s):Ts.delete(n),e&&i&&!!s!=!!r)if(r)r.remove(),r=null;else{let o=document.createElement("template");o.innerHTML=Qs(t),r=o.content.firstElementChild,i.insertBefore(r,i.querySelector(":scope > .aparte-tool-activity"))}if(n.toggleAttribute("data-opens",!!s&&!!r),n.toggleAttribute("data-current",!!s?.current&&!!r),!s||!r)return;let a=typeof s.label=="string"?s.label.trim():"";r.getAttribute("aria-label")!==a&&(r.setAttribute("aria-label",a),r.title=a),s.current?r.setAttribute("aria-current","true"):r.removeAttribute("aria-current")}var br=new WeakSet;function zd(n){br.has(n)||(br.add(n),n.addEventListener("click",t=>{let e=Ts.get(n),s=t.target;if(!(!e||!s?.closest||s.closest(".aparte-segment-tool-call")!==n)&&!(!s.closest(".aparte-tool-open")&&(Cs(n)||s.closest(".aparte-tool-line")?.parentElement!==n||n.ownerDocument.getSelection?.()?.isCollapsed===!1)))try{e.onOpen(n)}catch(i){console.error("[aparte] a tool line's onOpen threw",i)}}))}function vr(n,t,e=!0){let s=As(n),i=Da(n),r=Pa(n,t),a=ka(n,t),o=xa(n,t),l=Na(n,t),c=Ba(n),d=e?Qs(t):"";return`
32
+ <span class="aparte-tool-label">
33
+ <span class="aparte-tool-icon">${i}</span>
34
+ <span class="aparte-tool-name${l.isLabel?" aparte-tool-name--label":""}${c.shimmer?" aparte-shimmer":""}">${P(l.text)}</span>
35
+ <span class="aparte-tool-target${r.isWords?" aparte-tool-target--words":""}"${r.text?"":" hidden"}>${P(r.text)}</span>
36
+ </span>
37
+ <span class="aparte-spinner aparte-tool-spinner" aria-hidden="true"${c.spinner?"":" hidden"}></span>
38
+ <span class="aparte-tool-state${c.stateHidden?" aparte-sr-only":""}">${s}</span>
39
+ <span class="aparte-tool-note"${o?` title="${I(o)}"`:" hidden"}>${P(o)}</span>${d}
40
+ <span class="aparte-tool-activity"${a?"":" hidden"}>${P(a)}</span>`}function yr(n){return`<div class="aparte-segment aparte-segment-tool-call" data-segment-id="${P(n.id)}" data-status="${I(n.status??"pending")}" data-tool-call-id="${I(n.toolCall?.id??"")}" data-tool-name="${I(n.toolCall?.name??"tool")}" hidden></div>`}var qt=n=>n.hidden&&n.classList.contains("aparte-segment-tool-call")&&n.childElementCount===0,te=new WeakMap,Be=new WeakMap;function Ha(n){return Be.get(n)??null}function wr(n,t){let e=te.get(n);return e||(n.classList.contains("aparte-segment-tool-call")?null:t)}function Ar(n,t,e){let s=n.toolCall?.name??"tool",i=n.status??"pending",r=n.toolCall?.id??"",a=vr(n,e),o=(Ys(n)?" data-quiet":"")+(rn(n)?" data-queued":""),l=jd(e),c=M().getIcon("expand"),d=t.kind==="parts"?Ta(n):"",h=t.kind==="parts"?Ss(n):null;if(t.kind==="none"||t.kind==="parts"&&!d&&!h)return`
41
+ <div class="aparte-segment aparte-segment-tool-call" data-segment-id="${P(n.id)}" data-status="${I(i)}" data-tool-call-id="${I(r)}" data-tool-name="${I(s)}"${o}${l}><div class="aparte-tool-line">${a}</div>
42
+ </div>
43
+ `;let u=M(),p=Vs("aparte-tool-copy"),f=n.collapsed!==void 0?!n.collapsed:u.getToolDisplay(s)?.open===!0,g=Qs(e),_=g?`<details class="aparte-tool-disclosure"${f?" open":""}>`:"",w=g?`<div class="aparte-segment aparte-segment-tool-call" data-segment-id="${P(n.id)}" data-status="${I(i)}" data-tool-call-id="${I(r)}" data-tool-name="${I(s)}"${o}${l}>${_}`:`<details class="aparte-segment aparte-segment-tool-call" data-segment-id="${P(n.id)}" data-status="${I(i)}" data-tool-call-id="${I(r)}" data-tool-name="${I(s)}"${o}${l}${f?" open":""}>`,S=g?`</details><span class="aparte-tool-open-slot">${g}</span></div>`:"</details>",T=vr(n,e,!1);if(t.kind==="body"){let k=document.createElement("template");k.innerHTML=`
44
+ ${w}
45
+ <summary class="aparte-tool-summary"><span class="aparte-tool-toggle">${c}</span>${T}</summary>
46
+ <div class="aparte-tool-detail" data-details="app"></div>
47
+ ${S}`.trim();let m=k.content.firstElementChild;return Ma(m,t.body),m}return`
48
+ ${w}
49
+ <summary class="aparte-tool-summary"><span class="aparte-tool-toggle">${c}</span>${T}</summary>
50
+ <div class="aparte-tool-detail">
51
+ ${d?`
52
+ <div class="aparte-tool-part" data-part="input">
53
+ <div class="aparte-tool-part-head"><span class="aparte-tool-part-label">${P(u.t("toolInput"))}</span>${p}</div>
54
+ <div class="aparte-tool-part-body" role="region" tabindex="0" aria-label="${I(u.t("toolInput"))}"><pre><code>${P(d)}</code></pre></div>
55
+ </div>`:""}
56
+ ${h?`
57
+ <div class="aparte-tool-part" data-part="output">
58
+ <div class="aparte-tool-part-head"><span class="aparte-tool-part-label">${P(u.t(h.key))}</span>${p}</div>
59
+ <div class="aparte-tool-part-body" role="region" tabindex="0" aria-label="${I(u.t(h.key))}"><pre><code>${P(h.text)}</code></pre></div>
60
+ </div>`:""}
61
+ </div>
62
+ ${S}
63
+ `}var zt={type:"tool_call",render:n=>{let t=n.toolCall?.name??"tool";if(M().isToolHidden(t))return yr(n);let e=M().getToolRenderer(t);if(e){ja(t,e);let i=e.render(n);return i instanceof HTMLElement&&(te.set(i,e),Be.set(i,e)),i||yr(n)}let s=Nt(n,M());return Ar(n,ts(n,s),s)},relabel:(n,t)=>{if(qt(n))return;let e=M(),s=wr(n,e.getToolRenderer(t.toolCall?.name)??null);if(s){s.relabel?.(n,t);return}let i=Nt(t,e),r=n.querySelector(".aparte-tool-icon");r&&(r.innerHTML=Da(t)),mr(n,t,i),fr(n,t,i),gr(n,t,i),ur(n,t,i),es(n,i,!1);let a=n.querySelector('[data-part="input"] .aparte-tool-part-label');a&&(a.textContent=e.t("toolInput")),n.querySelector('[data-part="input"] .aparte-tool-part-body')?.setAttribute("aria-label",e.t("toolInput"));let o=Ss(t),l=n.querySelector('[data-part="output"] .aparte-tool-part-label');l&&o&&(l.textContent=e.t(o.key)),o&&n.querySelector('[data-part="output"] .aparte-tool-part-body')?.setAttribute("aria-label",e.t(o.key));for(let h of n.querySelectorAll(".aparte-tool-copy"))Sa(h);let c=Es(n);if(c){let h=ts(t,i,n);h.kind==="body"&&Fd(c,h.body)}let d=n.querySelector(".aparte-tool-state");d&&(d.innerHTML=As(t)),_r(n,t)},update:(n,t)=>{let e=t.status??"pending",s=M().isToolHidden(t.toolCall?.name??"tool");if(s&&qt(n)){n.setAttribute("data-status",e);return}let i=s?null:M().getToolRenderer(t.toolCall?.name)??null,r=qt(n)?null:wr(n,i);if(r&&r===i&&r.update&&!qt(n)){r.update(n,t);return}let a=_=>{let w=document.createElement("template");w.innerHTML=typeof _=="string"?_.trim():"";let S=typeof _=="string"?w.content.firstElementChild:_;return S&&(S.hasAttribute("data-segment-id")||S.setAttribute("data-segment-id",t.id),zt.cleanup?.(n,t),n.replaceWith(S),zt.setup?.(S,t)),S};if(i||r||s||qt(n)){a(zt.render(t));return}let o=Nt(t,M()),l=ts(t,o,n),c=l.kind==="parts"?Ta(t):"",d=l.kind==="parts"?Ss(t):null,h=l.kind==="body"||!!c||!!d,u=!!Es(n),p=Cs(n),f=!!p&&p!==n;if(h!==!!p||h&&l.kind==="body"!==u||h&&f!==!!an(o)){let _=p?.open,w=a(Ar(t,l,o)),S=w&&_!==void 0?Cs(w):null;S&&_!==void 0&&(S.open=_);return}n.setAttribute("data-status",e);let g=n.querySelector(".aparte-tool-state");if(g&&(g.innerHTML=As(t)),_r(n,t),mr(n,t,o),fr(n,t,o),gr(n,t,o),ur(n,t,o),es(n,o,!0),l.kind==="body"){Ma(n,l.body);return}hr(n,"input",c,"toolInput"),hr(n,"output",d?.text??"",d?.key??"toolOutput"),pr(n)},setup:(n,t)=>{let s=M().isToolHidden(t.toolCall?.name??"tool")?void 0:M().getToolRenderer(t.toolCall?.name);s&&Be.set(n,s),!qt(n)&&(s||(es(n,Nt(t,M()),!1),zd(n)),Ra(n),pr(n),s&&te.set(n,s),s?.setup?.(n,t))},cleanup:(n,t)=>{Be.delete(n);let e=te.get(n);if(e){te.delete(n);try{e.cleanup?.(n,t)}catch(s){console.error("[aparte] a tool renderer's cleanup threw",s)}}},getStyles:()=>""};function Sr(n){let t=document.createElement("div");return t.className="aparte-segment aparte-segment-activity",t.setAttribute("data-segment-id",n.id),t.setAttribute("data-activity-type",n.activityType),t.hidden=!0,t}var Cr=n=>n.hidden&&n.classList.contains("aparte-segment-activity")&&n.childElementCount===0,Ft=new WeakMap,He=new WeakMap;function $a(n){return He.get(n)??null}var ns=n=>M().getActivityRenderer(n.activityType)??null,Gt={type:"activity",render:n=>{let t=ns(n);if(!t)return Sr(n);let e=t.render(n);return e instanceof HTMLElement?(Ft.set(e,t),He.set(e,t),e):e.trim()?e:Sr(n)},setup:(n,t)=>{let e=ns(t);e&&(He.set(n,e),!Cr(n)&&(Ft.set(n,e),e.setup?.(n,t)))},update:(n,t)=>{let e=ns(t),s=Ft.get(n)??null;if(s&&s===e&&s.update){s.update(n,t);return}if(!e&&!s&&Cr(n)){n.setAttribute("data-activity-type",t.activityType);return}let i=Gt.render(t),r;if(typeof i=="string"){let a=document.createElement("template");a.innerHTML=i.trim(),r=a.content.firstElementChild}else r=i;r&&(r.hasAttribute("data-segment-id")||r.setAttribute("data-segment-id",t.id),Gt.cleanup?.(n,t),n.replaceWith(r),Gt.setup?.(r,t))},relabel:(n,t)=>{Ft.get(n)?.relabel?.(n,t)},cleanup:(n,t)=>{He.delete(n);let e=Ft.get(n);if(e){Ft.delete(n);try{e.cleanup?.(n,t)}catch(s){console.error("[aparte] an activity renderer's cleanup threw",s)}}}},Er=new WeakMap;function yt(n){let t=Er.get(n);return t||(t={renderers:new Map,defaultsInstalled:!1,defaultsDeclined:!1},Er.set(n,t)),t}function qa(n){let t=yt(n);if(n===et||t.defaultsDeclined)return t.renderers;let e=new Map(yt(et).renderers);for(let[s,i]of t.renderers)e.set(s,i);return e}var It=null;function se(n,t=M()){let e=yt(t);e.renderers.get(n.type)!==n&&(e.renderers.set(n.type,n),Js(t),Pt(t))}var kr=new WeakMap;function Gd(n,t=M()){let e=n.type,s=yt(t),i=kr.get(t);i||(i=new Map,kr.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),se(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 h=a[a.length-1].renderer;if(h){se(h,t);return}if(Ua(e,t),!qa(t).has(e)&&s.defaultsInstalled&&!s.defaultsDeclined){let u=Zs.find(p=>p.type===e);u&&se(u,t)}}}function Fa(n=M()){yt(n).defaultsDeclined=!0}function Wa(n=M()){let t=yt(n);if(!(t.defaultsInstalled||t.defaultsDeclined)){t.defaultsInstalled=!0;for(let e of Zs)t.renderers.has(e.type)||t.renderers.set(e.type,e);Js(n)}}function Ua(n,t=M()){let e=yt(t);e.renderers.has(n)&&(e.renderers.delete(n),Pt(t))}function Xs(n,t=M()){return qa(t).get(n)}var Me=new Set;function Js(n=M()){if(typeof document>"u")return;(!It||!It.isConnected)&&(It=document.createElement("style"),It.id="aparte-renderer-styles",document.head.appendChild(It),It.textContent=Array.from(Me).join(`
64
+ `));let t=!1;for(let e of yt(n).renderers.values()){let s=e.getStyles?.();!s||Me.has(s)||(Me.add(s),t=!0)}t&&(It.textContent=Array.from(Me).join(`
65
+ `))}var Tr=new WeakMap;function ja(n,t){if(typeof document>"u")return;let e=t.getStyles?.();if(!e)return;let s=Tr.get(t);if(s||(s=`aparte-tool-renderer-${n}`,Tr.set(t,s)),document.getElementById(s))return;let i=document.createElement("style");i.id=s,i.textContent=e,document.head.appendChild(i)}function za(n=M()){let t=yt(n);t.defaultsInstalled=!0;for(let e of Zs)t.renderers.has(e.type)||se(e,n);Js(n)}var Zs=[Td,Md,Nd,Dd,zt,Gt];function $e(n){let{target:t,config:e,messageId:s,targetId:i,observe:r=!0}=n,a=new Kt({blocks:e.getStreamBlocks()}),o=new Set,l=null,c=new Map,d=new Set,h=(C,R)=>d.delete(C)?{...R,queued:void 0}:R,u=(C,R)=>{let H=`tool-${C}`;t.updateSegment?.(H,h(H,c.has(H)?R:{...R,deferred:void 0}))},p="",f=!1,g="",_=new Map,w=[],S=[],T=new Set,k=C=>{let R=C.content;typeof R=="string"&&_.set(C.id,{text:C.type==="text",content:R})},m=()=>{if(w.length===0)return;let C=0,R=[..._].map(([U,{text:ct,content:Y}])=>{let nt=g.indexOf(Y,C);return nt>=0&&(C=nt+Y.length),{id:U,text:ct,start:nt,length:Y.length,citations:[]}}).filter(U=>U.text);if(R.length===0)return;let H=new Set;for(let U of S){let ct=R.find(ft=>ft.start>=0&&U.end>ft.start&&U.end<=ft.start+ft.length);if(!ct)continue;let Y=U.end-ct.start,nt=U.start===void 0?void 0:Math.max(0,Math.min(Y,U.start-ct.start));ct.citations.push({...U,end:Y,...nt===void 0?{}:{start:nt}});for(let ft of U.sources)H.add(ft)}let B=R[R.length-1],Z=new Set;for(let U of R){let ct=new Set(U.citations.flatMap(nt=>nt.sources)),Y=w.filter(nt=>ct.has(nt.id)||U===B&&!H.has(nt.id));if(Y.length===0){T.has(U.id)&&t.updateSegment?.(U.id,{sources:void 0,citations:void 0});continue}Z.add(U.id),t.updateSegment?.(U.id,{sources:Y,citations:U.citations})}T=Z},v=C=>{if(!l||f)return;let R=typeof Element<"u"&&t instanceof Element?L(t):e,H=!C||R.getSegmentDefaults("thinking")?.collapsed===!1;t.updateSegment?.(l,H?{isStreaming:!1}:{collapsed:!0,isStreaming:!1}),f=!0},E=[],b=null,y=()=>{let C=E.at(-1)??null;C!==b&&(b=C,t.setStep?.(s,C))},A=()=>{E.length=0,y()},x=()=>{let C=a.finalize();for(let R of C)k(R),o.has(R.id)?"content"in R&&t.updateSegment?.(R.id,Gn(R)):t.addSegment?.(R);m()},O=new Set,$=C=>O.has(C)?!0:(t.getMessage?t.getMessage(s)?.segments:t.segments)?.some(H=>H.id===C)?(O.add(C),!0):!1,D=C=>{switch(C.type){case"step-start":E.push(C.name),y();break;case"step-end":{let R=E.lastIndexOf(C.name);R>=0&&E.splice(R,1),y();break}case"run-start":t.updateMessage?.(s,{status:"streaming"});break;case"turn-start":v(!1),a=new Kt({blocks:e.getStreamBlocks()}),o=new Set,g="",_=new Map,w=T.size===0?w.map(R=>({...R,id:`${R.id}~`})):[],S=[],T=new Set,l=null,p="",f=!1;break;case"thinking-delta":{if(p+=C.delta,l)t.updateSegment?.(l,{content:p});else{let R={id:`think-${X()}`,type:"thinking",content:p,isStreaming:!0};l=R.id,o.add(R.id),t.addSegment?.(R)}break}case"text-delta":{v(!0),g+=C.delta;let R=a.parse(C.delta);for(let B of R.segments)k(B),o.has(B.id)?"content"in B&&t.updateSegment?.(B.id,Gn(B)):(t.addSegment?.(B),o.add(B.id));let H=a.getState().activeSegment;H?(k(H),o.has(H.id)?t.updateSegment?.(H.id,Gn(H)):(t.addSegment?.(H),o.add(H.id))):R.segments.length;break}case"text-flush":x();break;case"activity":{let R=`activity-${C.id}`;if($(R)){t.updateSegment?.(R,{activityType:C.activityType,content:C.content});break}O.add(R),x();let H={id:R,type:"activity",activityId:C.id,activityType:C.activityType,content:C.content};t.addSegment?.(H);break}case"sources":{let R=new Map(w.map(B=>[B.id,B]));for(let B of Array.isArray(C.sources)?C.sources:[])R.set(B.id,{...R.get(B.id),...B});w=[...R.values()];let H=new Set(S.map(B=>JSON.stringify([B.start,B.end,B.marker,B.sources])));for(let B of Array.isArray(C.citations)?C.citations:[]){let Z=JSON.stringify([B.start,B.end,B.marker,B.sources]);H.has(Z)||(H.add(Z),S.push(B))}m();break}case"tool-start":{v(!1);let R={id:`tool-${C.toolCallId}`,type:"tool_call",toolCall:{id:C.toolCallId,name:C.name,input:C.input},status:"pending",...C.queued?{queued:!0}:{}};c.set(R.id,R),C.queued&&d.add(R.id);let H=e.getToolRenderer(C.name);H&&ja(C.name,H),t.addSegment?.(R);break}case"tool-running":{let R=`tool-${C.toolCallId}`;d.delete(R)&&t.updateSegment?.(R,{queued:void 0});break}case"tool-awaiting-approval":t.updateSegment?.(`tool-${C.toolCallId}`,h(`tool-${C.toolCallId}`,{status:"awaiting-approval"})),rt(t,"aparte-tool-approval-request",{toolCallId:C.toolCallId,toolName:C.name,input:C.input},i);break;case"tool-approved":u(C.toolCallId,{status:"pending"});break;case"tool-rejected":u(C.toolCallId,{status:"rejected",result:C.reason,...C.by?{refusal:C.instruction?{by:C.by,instruction:C.instruction}:{by:C.by}}:{}});break;case"tool-resolved":u(C.toolCallId,{status:"resolved",result:C.result,...C.structuredResult!==void 0?{structuredResult:C.structuredResult}:{}});break;case"tool-aborted":u(C.toolCallId,C.cause?{status:"aborted",abortCause:C.cause}:{status:"aborted"});break;case"tool-failed":u(C.toolCallId,{status:"failed",result:C.error});break;case"turn-limit-exceeded":C.scope==="global"?t.addSegment?.({id:`max-turns-${X()}`,type:"error",content:(typeof Element<"u"&&t instanceof Element?L(t):e).t("maxTurnsReached").replace("{n}",()=>String(C.limit)),code:z.MAX_TURNS_EXCEEDED}):C.toolCallId&&u(C.toolCallId,{status:"aborted",abortCause:"turn-limit"});break;case"run-aborted":A(),rt(t,"aparte-message-aborted",{messageId:s},i);break;case"run-suspended":{A();let R=C.ticket;for(let H of C.pending){if(H.agentId!=null)continue;let B=`tool-${H.toolCallId}`,Z={reason:H.reason,...typeof R=="string"?{ticket:R}:{}};t.updateSegment?.(B,h(B,{deferred:Z}))}if(t.updateMessage?.(s,{status:"completed"}),C.usage)try{t.setUsage?.(s,C.usage)}catch{}rt(t,"aparte-message-paused",{messageId:s},i);break}case"run-done":if(A(),t.updateMessage?.(s,{status:"completed",...C.finishReason?{finishReason:C.finishReason}:{}}),C.usage)try{t.setUsage?.(s,C.usage)}catch{}break}},q=()=>typeof Element<"u"&&t instanceof Element?L(t):e,st=new Set,pt=(C,R)=>{let H=new Set;for(let Z of new Set([R,e,et]))for(let U of Z.getRunEventObservers())H.add(U);if(H.size===0)return!1;let B={messageId:s,target:t,...i!==void 0?{targetId:i}:{},config:R};for(let Z of H)try{Z(C,B)}catch(U){st.has(Z)||(st.add(Z),console.error("[aparte] A run-event observer threw; the reply goes on without it. Further throws from it in this reply are not reported.",U))}return!0};return C=>{let R=q(),H=!r||pt(C,R),B=C.agentId;if(B==null&&C.type!=="agent-start"&&C.type!=="agent-end"){D(C);return}!H&&!xr.has(R)&&(xr.add(R),console.warn(`[aparte] A sub-agent's events arrived (agent "${String(B)}") and nothing draws them: they are kept out of the reply and not shown. Add @aparte/plugin-subagents (setupSubagents()) to show one line per sub-agent, or hear them with config.observeRunEvents().`)),C.type==="tool-awaiting-approval"&&rt(t,"aparte-tool-approval-request",{toolCallId:C.toolCallId,toolName:C.name,input:C.input,agentId:B},i)}}var xr=new WeakSet;function Ga(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 _p=new TextEncoder;var mp=10080*60*1e3;function ti(n){let t=typeof document>"u"?void 0:document.baseURI;try{return t?new URL(n,t):new URL(n)}catch{return null}}function Kd(){let n=typeof location>"u"?null:location.origin;return n&&n!=="null"?n:null}function Vd(n){try{let t=new URL(n);return t.protocol==="http:"||t.protocol==="https:"?t.origin:null}catch{return null}}function Yd(n,t){return n===t?!0:typeof n=="function"||typeof t=="function"?!1:n.length===t.length&&n.every((e,s)=>e===t[s])}var Mr=new WeakSet;function ss(n){if(typeof n=="function")return(i,r)=>{try{let a=n(r?r.href:i);return a==="load"||a==="drop"?a:"hold"}catch(a){return Mr.has(n)||(Mr.add(n),console.warn("[aparte] The image policy threw, so the pictures it was asked about are held.",a)),"hold"}};let t=!1,e=!1,s=new Set;for(let i of n){let r=typeof i=="string"?i.trim():"";if(r==="*")t=!0;else if(r==="self"||r==="'self'")e=!0;else{let a=Vd(r);a?s.add(a):console.warn(`[aparte] setImagePolicy: ${JSON.stringify(i)} is not 'self', '*' or an http(s) origin, so it allows nothing.`)}}return(i,r)=>t||r&&(s.has(r.origin)||e&&r.origin===Kd())?"load":"hold"}var Dt=/^[\u0000- ]*$/;function Qd(n,t,e){if(Dt.test(t))return"load";let s=ti(t);if(s){if(s.protocol==="data:"||s.protocol==="blob:")return"load";if(s.protocol!=="http:"&&s.protocol!=="https:")return"drop"}let i=n(t,s);return i==="hold"&&s!==null&&e?.has(s.href)?"load":i}var Ke=new WeakMap;function Xd(n,t){let e=ti(t);if(!e)return;let s=Ke.get(n);s||Ke.set(n,s=new Set),s.add(e.href)}function Jd(n){return Ke.get(n)}function Zd(n){Ke.delete(n)}var Le=/[\t\n\f\r ]/,tu=/^(?:|\d+w(?: \d+h)?|(?:\d+|\d*\.\d+)(?:[eE][+-]?\d+)?x)$/;function Ka(n){let t=[],e=n.length,s=0;for(;s<e;){for(;s<e&&(Le.test(n[s])||n[s]===",");)s++;if(s>=e)break;let i=s;for(;s<e&&!Le.test(n[s]);)s++;let r=n.slice(i,s),a=[];if(r.endsWith(","))r=r.replace(/,+$/,"");else{let l="",c="in";for(;;){let d=n[s];if(c==="in"){if(d===void 0){l&&a.push(l);break}if(d===","){s++,l&&a.push(l);break}Le.test(d)?(l&&a.push(l),l="",c="after"):(l+=d,d==="("&&(c="parens"))}else if(c==="parens"){if(d===void 0){a.push(l);break}l+=d,d===")"&&(c="in")}else{if(d===void 0)break;if(!Le.test(d)){c="in";continue}}s++}}let o=a.join(" ");r&&tu.test(o)&&t.push({url:r,descriptor:o})}return t}function Va(n){return n.map(t=>t.descriptor?`${t.url} ${t.descriptor}`:t.url).join(", ")}function Ya(n){let t=ti(n);if(t?.hostname)return t.hostname;let e=n.trim();return e.length>48?`${e.slice(0,47)}\u2026`:e}function Ve(n,t,e,s=!1){let i=Ya(n),r=t?e.named(i,t):e.load(i),a=e.icon;return`${s?'<span class="aparte-tag aparte-image-held" role="button" tabindex="0"':`<a class="aparte-tag aparte-image-held" href="${I(n)}" target="_blank" rel="noopener noreferrer"`} data-aparte-image="${I(n)}"${t?` data-aparte-image-alt="${I(t)}"`:""} title="${I(e.load(i))}" aria-label="${I(r)}"><span class="aparte-image-held__icon" aria-hidden="true">${a}</span>`+(t?`<span class="aparte-tag__label aparte-image-held__alt">${P(t)}</span>`:"")+`<span class="aparte-image-held__host">${P(i)}</span>${s?"</span>":"</a>"}`}function Qa(n,t){return`<img src="${I(n)}" alt="${I(t)}" referrerpolicy="no-referrer">`}var Xa=/<(?:img|source)\b|data-aparte-image/i,eu="a[data-aparte-image], span[data-aparte-image]";function nu(n,t,e){return!n||!Xa.test(n)?n:typeof document>"u"?cu(n,t,e):su(n,t,e)}function Ja(n,t,e){let s=t===void 0?[]:Ka(t),i=Dt.test(n)?s[0]?.url:n;if(i===void 0)return null;let r=e(i);if(r!=="load")return{decision:r,address:i,srcset:null};let a=s.filter(o=>e(o.url)==="load");return{decision:r,address:i,srcset:a.length?Va(a):null}}function Za(n,t,e){if(!Dt.test(n)&&e(n)!=="load")return!1;if(t===void 0)return Dt.test(n)?!1:null;let s=Ka(t).filter(i=>e(i.url)==="load");return s.length?Va(s):Dt.test(n)?!1:null}function su(n,t,e){let s=document.createElement("template");s.innerHTML=n;let i=s.content,r,a=!1,o=l=>{let c=document.createElement("template");return c.innerHTML=l,c.content};for(let l of Array.from(i.querySelectorAll(eu))){let c=l.getAttribute("data-aparte-image")??"",d=l.getAttribute("data-aparte-image-alt")??"",h=Dt.test(c)?"drop":t(c);a=!0,h==="drop"?l.remove():l.replaceWith(o(h==="load"?Qa(c,d):Ve(c,d,r??=e(),!!l.parentElement?.closest("a"))))}for(let l of Array.from(i.querySelectorAll("source"))){let c=Za(l.getAttribute("src")??"",l.getAttribute("srcset")??void 0,t);if(c===!1){l.remove(),a=!0;continue}c===null?l.hasAttribute("srcset")&&(l.removeAttribute("srcset"),a=!0):c!==l.getAttribute("srcset")&&(l.setAttribute("srcset",c),a=!0)}for(let l of Array.from(i.querySelectorAll("img"))){let c=Ja(l.getAttribute("src")??"",l.getAttribute("srcset")??void 0,t);if(!c){l.hasAttribute("srcset")&&(l.removeAttribute("srcset"),a=!0),l.parentElement?.localName==="picture"&&l.getAttribute("referrerpolicy")!=="no-referrer"&&(l.setAttribute("referrerpolicy","no-referrer"),a=!0);continue}if(a=!0,c.decision==="drop"){l.remove();continue}if(c.decision==="hold"){l.replaceWith(o(Ve(c.address,l.getAttribute("alt")??"",r??=e(),!!l.closest("a"))));continue}c.srcset===null?l.removeAttribute("srcset"):l.setAttribute("srcset",c.srcset),l.setAttribute("referrerpolicy","no-referrer")}return a?s.innerHTML:n}var iu=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes","noscript","plaintext"]),ru=new Set(["area","base","br","col","embed","hr","img","input","link","meta","source","track","wbr"]),au=/[A-Za-z]/,ou=/^[a-z][a-z0-9_.:-]*$/;function is(n,t,e){let s=t.filter(([r])=>!(r in e)&&ou.test(r)),i=Object.entries(e).filter(r=>r[1]!==null);return`<${n}${[...s,...i].map(([r,a])=>` ${r}="${I(a)}"`).join("")}>`}function lu(n,t,e){let s=new RegExp(`<(/?)${t}(?=[\\s/>])`,"g");s.lastIndex=e;let i=1;for(let r=s.exec(n);r;r=s.exec(n))if(i+=r[1]?-1:1,i===0){let a=n.indexOf(">",r.index);return a<0?n.length:a+1}return-1}function cu(n,t,e){if(!n||!Xa.test(n))return n;let s=n.toLowerCase(),i=n.length,r,a="",o=0,l=0,c=[];for(;o<i;){let d=n.indexOf("<",o);if(d<0){a+=n.slice(o);break}if(a+=n.slice(o,d),n.startsWith("<!--",d)){let S=n.indexOf("-->",d+4),T=S<0?i:S+3;a+=n.slice(d,T),o=T;continue}let h=n[d+1]==="/",u=d+(h?2:1);if(!au.test(n[u]??"")){a+="<",o=d+1;continue}let{tag:p,attrs:f,end:g}=Ws(n,u);if(g<0){a+=n.slice(d);break}o=g;let _=n.slice(d,g);if(h){p==="a"&&(l=Math.max(0,l-1));let S=c.lastIndexOf(p);S>=0&&(c.length=S),a+=_;continue}let w=S=>f.find(([T])=>T===S)?.[1];if(iu.has(p)){let S=s.indexOf(`</${p}`,g),T=S<0?i:S;a+=_+n.slice(g,T),o=T;continue}if((p==="a"||p==="span")&&w("data-aparte-image")!==void 0){let S=lu(s,p,g);S>=0?o=S:p==="a"&&(l+=1);let T=w("data-aparte-image")??"",k=w("data-aparte-image-alt")??"",m=Dt.test(T)?"drop":t(T);m==="load"?a+=Qa(T,k):m==="hold"&&(a+=Ve(T,k,r??=e(),l>0));continue}if(p==="a"&&(l+=1),p==="source"){let S=Za(w("src")??"",w("srcset"),t);if(S===!1)continue;a+=S===(w("srcset")??null)?_:is(p,f,{srcset:S});continue}if(p==="img"){let S=Ja(w("src")??"",w("srcset"),t);if(!S){let T=c[c.length-1]==="picture";w("srcset")===void 0&&(!T||w("referrerpolicy")==="no-referrer")?a+=_:a+=is(p,f,{srcset:null,...T?{referrerpolicy:"no-referrer"}:{}});continue}S.decision==="hold"?a+=Ve(S.address,w("alt")??"",r??=e(),l>0):S.decision==="load"&&(a+=is(p,f,{srcset:S.srcset,referrerpolicy:"no-referrer"}));continue}!ru.has(p)&&!_.endsWith("/>")&&c.push(p),a+=_}return a}var du=/^(?:#|mailto:|tel:|sms:)/i,uu=[["target","_blank"],["rel","noopener noreferrer"]],hu=Object.freeze({target:"_blank",rel:"noopener noreferrer"}),pu=Object.freeze({});function ei(n,t,e){return n!=="external-only"&&!du.test(t.replace(qs,""))?uu:Fs(t,e)}function fu(n,t){return ei(n,t,"").length?hu:pu}var to=/<a[\s/>]/i;function gu(n,t){return!n||!to.test(n)?n:typeof document>"u"?Su(n,t):mu(n,t)}function _u(n){let t=(n??"").split(/[ \t\n\f\r]+/).filter(e=>e&&e.toLowerCase()!=="opener");for(let e of["noopener","noreferrer"])t.some(s=>s.toLowerCase()===e)||t.push(e);return t.join(" ")}function eo(n,t,e){let s=n.find(([r])=>r==="target")?.[1];if(s!=="_blank")return(t??void 0)===s?null:{target:s,rel:void 0};let i=_u(e);return(t??void 0)===s&&(e??void 0)===i?null:{target:s,rel:i}}function mu(n,t){let e=document.createElement("template");e.innerHTML=n;let s=!1;for(let i of Array.from(e.content.querySelectorAll("a[href]"))){let r=ei(t,i.getAttribute("href")??"",i.getAttribute("target")??""),a=eo(r,i.getAttribute("target"),i.getAttribute("rel"));a&&(i.removeAttribute("target"),a.target!==void 0&&i.setAttribute("target",a.target),a.rel!==void 0&&(i.removeAttribute("rel"),i.setAttribute("rel",a.rel)),s=!0)}return s?e.innerHTML:n}var bu=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes","noscript","plaintext"]),vu=/[A-Za-z]/,yu=/^[a-z][a-z0-9_.:-]*$/,Lr=/--!?>/g;function wu(n,t){if(n[t]===">")return t+1;if(n.startsWith("->",t))return t+2;Lr.lastIndex=t;let e=Lr.exec(n);return e?e.index+e[0].length:n.length}function Au(n,t,e){let s=c=>t.find(([d])=>d===c)?.[1],i=s("href");if(i===void 0)return n;let r=ei(e,i,s("target")??""),a=eo(r,s("target"),s("rel"));if(!a)return n;let o=t.filter(([c])=>c!=="target"&&(a.rel===void 0||c!=="rel")&&yu.test(c)),l=[];return a.target!==void 0&&l.push(["target",a.target]),a.rel!==void 0&&l.push(["rel",a.rel]),`<a${[...o,...l].map(([c,d])=>` ${c}="${I(d)}"`).join("")}>`}function Su(n,t){if(!n||!to.test(n))return n;let e=n.toLowerCase(),s=n.length,i="",r=0;for(;r<s;){let a=n.indexOf("<",r);if(a<0){i+=n.slice(r);break}if(i+=n.slice(r,a),n.startsWith("<!--",a)){let p=wu(n,a+4);i+=n.slice(a,p),r=p;continue}let o=n[a+1]==="/",l=a+(o?2:1);if(!vu.test(n[l]??"")){i+="<",r=a+1;continue}let{tag:c,attrs:d,end:h}=Ws(n,l);if(h<0){i+=n.slice(a);break}r=h;let u=n.slice(a,h);if(o){i+=u;continue}if(bu.has(c)){let p=e.indexOf(`</${c}`,h),f=p<0?s:p;i+=u+n.slice(h,f),r=f;continue}i+=c==="a"?Au(u,d,t):u}return i}var Tt=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 Cu(n){return n?n.tagName?.toLowerCase()==="aparte-chat"||n.hasAttribute?.("data-aparte-chat")===!0:!1}function _t(n){let t=n??null;for(;t;){if(Cu(t))return t;t=t.parentElement}return null}var Ye=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}},Ir=!1,kt={copy:!1,retry:!1,edit:!1,feedback:!1,info:!1},ee={attachmentPreview:!1,filePreview:!1},Rr=()=>{},no=new WeakMap;function dt(n){return no.get(n)??0}function ot(n){no.set(n,dt(n)+1)}var xs=new Set,Ie=new Set;function so(n){return xs.add(n),()=>{xs.delete(n)}}function Pt(n){Ie.size===0&&queueMicrotask(()=>{let t=[...Ie];Ie.clear();for(let e of t)for(let s of[...xs])try{s(e)}catch(i){console.error("[aparte] a renderer-change listener threw",i)}}),Ie.add(n)}var Eu=n=>n instanceof RegExp?`re:${String(n)}`:`name:${n}`,rs=["hidden","open","details","quiet"];function as(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 Or=new WeakSet;function ku(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 ce=class{_markdownProvider;_streamingMarkdownProvider;_highlightProvider;_codeLanguageRenderers=new Map;_sanitizer=fs;_imagePolicy=[];_imageDecider=ss([]);_imagePolicyNamed=!1;_linkTarget="new-tab";_systemPromptTemplate;_systemPromptVarsProvider;_statusRenderer;_errorRenderer;_attachmentRenderer;_siblingNavRenderer;_bubbleShellRenderer;_iconProvider;_avatarProvider;_keyProvider;_extraKeyProviders=new Set;_locale=Ut;_actions=[];_listeners=new Set;_aiProviders=new Map;_fetchedModels=new Map;_modelConfig={};_requireModelSelection=!1;_elicitationAllowOther=!0;_elicitationLayout="stepped";_elicitationAnswerOnClick=!0;_elicitationFieldRenderer;_transport=new We;_modelPreferenceProvider;_approvalPolicy=null;_compactor=null;_conversationManager;_elicitationPresenters=[];_warnedNoPresenter=!1;_elicitationQueue=new Map;_tools=new Map;_toolRenderers=new Ye;_toolRendererOverrides=new Map;_overrideGeneration=0;_toolDisplays=new Ye;_activityRenderers=new Map;_toolLineProvider=null;_stepLabels=new Map;_streamBlocks=new Map;_segmentDefaults=new Map;_runEventObservers=[];_hostHandlers={...ee};_bubbleActionsConfig={...kt};_turnSummary=null;_streamingCaret=!1;_dateSeparators=!1;registerAction(t){let e=this._actions.findIndex(s=>s.id===t.id);e!==-1?(console.warn(`[AparteConfig] Action with ID "${t.id}" already registered. Overwriting.`),this._actions[e]=t):this._actions.push(t),this._notify()}getActions(t){return this._actions.filter(e=>e.zones.includes(t)).sort((e,s)=>(e.order||0)-(s.order||0))}unregisterAction(t){let e=this._actions.length;this._actions=this._actions.filter(s=>s.id!==t),this._actions.length!==e&&this._notify()}setBubbleActions(t){this._bubbleActionsConfig={...this._bubbleActionsConfig,...t},this._notify()}setTurnSummary(t){this._turnSummary=t===!1?null:t===!0?{}:t,ot(this),this._notify()}setStreamingCaret(t){this._streamingCaret=t,this._notify()}getStreamingCaret(){return this._streamingCaret}setDateSeparators(t){this._dateSeparators=t,this._notify()}getDateSeparators(){return this._dateSeparators}getTurnSummary(){return this._turnSummary}setHostHandlers(t){this._hostHandlers={...this._hostHandlers,...t},this._notify()}getHostHandlers(){return{attachmentPreview:this._hostHandlers.attachmentPreview??ee.attachmentPreview,filePreview:this._hostHandlers.filePreview??ee.filePreview}}getBubbleActions(){return{copy:this._bubbleActionsConfig.copy??kt.copy,retry:this._bubbleActionsConfig.retry??kt.retry,edit:this._bubbleActionsConfig.edit??kt.edit,feedback:this._bubbleActionsConfig.feedback??kt.feedback,info:this._bubbleActionsConfig.info??kt.info,feedbackReasons:this._bubbleActionsConfig.feedbackReasons,user:this._bubbleActionsConfig.user,assistant:this._bubbleActionsConfig.assistant}}setMarkdownProvider(t){this._markdownProvider=t,ot(this),this._notify()}setStreamingMarkdownProvider(t){this._streamingMarkdownProvider=t,ot(this),this._notify()}createStreamingMarkdownRenderer(t){return this._streamingMarkdownProvider?this._streamingMarkdownProvider(t):null}setHighlightProvider(t){this._highlightProvider=t,ot(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 ot(this),this._notify(),()=>{let s=!1;for(let i of e)this._codeLanguageRenderers.get(i)===t&&(this._codeLanguageRenderers.delete(i),s=!0);s&&(ot(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,ot(this),this._notify())}sanitizeHtml(t){let e=this._sanitizer?this._sanitizer(t):t,s=gu(e,this._linkTarget);return nu(s,i=>this.decideImage(i),()=>this._heldImageWords())}setImagePolicy(t){this._imagePolicyNamed=!0,!Yd(t,this._imagePolicy)&&(this._imagePolicy=typeof t=="function"?t:[...t],this._imageDecider=ss(t),ot(this),this._notify())}decideImage(t){let e=Qd(this._imageDecider,t,Jd(this));return e==="hold"&&this._noteHeldImage(t),e}_noteHeldImage(t){this._imagePolicyNamed||Ir||(Ir=!0,console.warn(`[aparte] A picture from ${Ya(t)} waits for the reader's click: pictures a model or a tool chose load only from the sources the app allows. To load yours, call aparteGlobalConfig.setImagePolicy(['https://cdn.example.com']); to keep holding them without this note, setImagePolicy([]). Why: https://apartejs.dev/guides/markdown/#pictures-a-reply-can-load`))}showImage(t){Xd(this,t)}_heldImageWords(){return{load:t=>this.t("imageLoad").replace("{host}",()=>t),named:(t,e)=>this.t("imageLoadNamed").replace("{host}",()=>t).replace("{alt}",()=>e),icon:this.getIcon("image")}}setLinkTarget(t){t!==this._linkTarget&&(this._linkTarget=t,ot(this),this._notify())}getLinkTarget(){return this._linkTarget}decideLink(t){return fu(this._linkTarget,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&&Or.has(e))Object.assign(e,t);else{let s=Object.assign(Object.create(e??null),t);Or.add(s),this._iconProvider=s}this._notify()}getIconProvider(){let t=this._iconProvider,e={};for(let s of Object.keys(Zt))e[s]=as(t,s)??(()=>Zt[s]);for(let s of ku(t)){let i=as(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=Ut,this._notify()}getLocale(){return this._locale}extendLocale(t){this._locale={...this._locale,...t},this._notify()}getIcon(t){let e=as(this._iconProvider,t);return e?e():Object.prototype.hasOwnProperty.call(Zt,t)?Zt[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]||Ut[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(t){let e=t?new Set(t.map(i=>i.name)):null,s=Array.from(this._tools.values()).filter(i=>!e||e.has(i.tool.name)).map(i=>i.tool.systemPrompt?.trim()).filter(i=>!!i);return s.length?s.join(`
66
+
67
+ `):null}getToolHandler(t){return this._tools.get(t)?.handler}registerToolRenderer(t,e){this._toolRenderers.get(t)!==e&&(this._toolRenderers.set(t,e),Pt(this))}overrideToolRenderer(t,e){let s=Eu(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 h=r[r.length-1].renderer;h?this.registerToolRenderer(t,h):this.unregisterToolRenderer(t)}}setSegmentDefaults(t,e){this._segmentDefaults.set(t,{...e})}getSegmentDefaults(t){return this._segmentDefaults.get(t)}clearSegmentDefaults(t){this._segmentDefaults.delete(t)}unregisterToolRenderer(t){this._toolRenderers.get(t)!==void 0&&(this._toolRenderers.delete(t),Pt(this))}registerActivityRenderer(t,e){return this._activityRenderers.get(t)!==e&&(this._activityRenderers.set(t,e),Pt(this)),()=>{this._activityRenderers.get(t)===e&&(this._activityRenderers.delete(t),Pt(this))}}getActivityRenderer(t){return this._activityRenderers.get(t)}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),(rs.some(a=>s?.[a]!==i[a])||s===void 0&&this._anotherShapes(i))&&ot(this),this._notify()}unregisterToolDisplay(t){let e=this._toolDisplays.get(t);this._toolDisplays.delete(t),(rs.some(i=>e?.[i]!==void 0)||e!==void 0&&this._anotherShapes(e))&&ot(this),this._notify()}_anotherShapes(t){return this._toolDisplays.values().some(e=>e!==t&&rs.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]}setToolLineProvider(t){this._toolLineProvider!==t&&(this._toolLineProvider=t,ot(this),this._notify())}getToolLineProvider(){return this._toolLineProvider||this===et?this._toolLineProvider:et._toolLineProvider}_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}registerStepLabel(t,e){let s={label:e};return this._stepLabels.set(t,s),this._notify(),()=>{this._stepLabels.get(t)===s&&(this._stepLabels.delete(t),this._notify())}}getStepLabel(t){let e=this._stepLabels.get(t);if(e)try{let s=typeof e.label=="function"?e.label({name:t,locale:this._locale}):e.label;return typeof s=="string"&&s.trim()?s.trim():void 0}catch{return}}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())}observeRunEvents(t){let e={fn:t};return this._runEventObservers.push(e),()=>{this._runEventObservers=this._runEventObservers.filter(s=>s!==e)}}getRunEventObservers(){return this._runEventObservers.map(t=>t.fn)}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=_t(t);if(s)for(let i=e.length-1;i>=0;i-=1){let r=e[i];if(r.owner&&_t(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(Rr,Rr).then(()=>{this._elicitationQueue.get(e)===r&&this._elicitationQueue.delete(e)});return this._elicitationQueue.set(e,r),i}_elicitationQueueKey(t){return _t(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 Tt("no-presenter"));if(t.signal?.aborted)return Promise.reject(new Tt("aborted"));let s=e(t),i=t.signal;return i?new Promise((r,a)=>{let o=()=>a(new Tt("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=Ut,this._actions=[],this._sanitizer=fs,this._imagePolicy=[],this._imageDecider=ss([]),this._imagePolicyNamed=!1,Zd(this),this._linkTarget="new-tab",this._aiProviders.clear(),this._fetchedModels.clear(),this._tools.clear(),this._toolRenderers.clear(),this._toolRendererOverrides.clear(),this._activityRenderers.clear(),this._overrideGeneration++,Pt(this),this._toolDisplays.clear(),this._toolLineProvider=null,this._stepLabels.clear(),this._streamBlocks.clear(),this._runEventObservers=[],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={...kt},this._turnSummary=null,this._streamingCaret=!1,this._dateSeparators=!1,this._hostHandlers={...ee},this._notify()}_defaultMarkdownRenderer(t){return P(t).replace(/\n/g,"<br>")}_defaultHighlightRenderer(t){return`<pre><code>${P(t)}</code></pre>`}},os=Symbol.for("aparte.globalConfig.1");function Tu(){return typeof window<"u"?(window[os]||(window[os]=new ce),window[os]):new ce}var et=Tu(),Ms="aparte-config-change";function Mt(n,t){let e=s=>{let i=s.detail;i?.config&&i.config!==L(n)||t()};return window.addEventListener(Ms,e),()=>window.removeEventListener(Ms,e)}var io="suggestions",xu=/[\p{Z}\s]+/gu,Mu=/[\p{Cc}\p{Co}\p{Cn}\p{Cs}\u2800]|(?!(?:\u200C|\u200D|\uFE0E|\uFE0F))\p{Default_Ignorable_Code_Point}/u,Lu=/\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0065}\u{E006E}\u{E0067}|\u{E0073}\u{E0063}\u{E0074}|\u{E0077}\u{E006C}\u{E0073})\u{E007F}/gu,Iu=/(?:^| )\p{M}|\p{Mn}{5,}/u,Ru=new Set(["\u200C","\u200D","\uFE0E","\uFE0F"]),Ou=/^[0-9#*]$/,Pu=/^\p{Emoji}$/u,Pr=/^\p{Extended_Pictographic}$/u,Nu=/^\p{Emoji_Modifier}$/u,Nr=/^[\p{scx=Arab}\p{scx=Syrc}\p{scx=Thaa}\p{scx=Nkoo}\p{scx=Adlm}\p{scx=Rohg}\p{scx=Mong}\p{scx=Deva}\p{scx=Beng}\p{scx=Guru}\p{scx=Gujr}\p{scx=Orya}\p{scx=Taml}\p{scx=Telu}\p{scx=Knda}\p{scx=Mlym}\p{scx=Sinh}\p{scx=Mymr}\p{scx=Khmr}]$/u,Du=/^[\u094D\u09CD\u0A4D\u0ACD\u0B4D\u0BCD\u0C4D\u0CCD\u0D4D\u0DCA\u1039\u17D2]$/;function Bu(n){let t=Array.from(n);for(let e=0;e<t.length;e++){let s=t[e];if(!Ru.has(s))continue;let i=t[e-1]??"",r=t[e+1]??"";if(s==="\uFE0E"||s==="\uFE0F"){if(Ou.test(i)){if(s!=="\uFE0F"||r!=="\u20E3")return!1}else if(!Pu.test(i))return!1;continue}if(s==="\u200D"){let a=i==="\uFE0F"?t[e-2]??"":i;if((Pr.test(a)||Nu.test(a))&&Pr.test(r))continue}if(!(Nr.test(i)&&(Nr.test(r)||Du.test(i)&&(r===""||r===" "))))return!1}return!0}var ro=100;function ni(n){let t=(typeof n=="string"?n:n.label).replace(xu," ").trim();if(!t||t.length>ro)return null;let e=t.replace(Lu,"\u{1F3F4}");return Mu.test(e)||Iu.test(e)||!Bu(e)?null:t}var Re=new Set;function Hu(n,t){t.length===0||Re.has(n)||(Re.size>=50&&Re.clear(),Re.add(n),console.warn(`[aparte-suggestions] ${t.length} reply(ies) of a suggestions block not offered, since a chip sends exactly what it shows: ${t.map(e=>JSON.stringify(e)).join(", ")}. A reply must be 1 to ${ro} characters and hold nothing invisible (zero-width, bidi or tag characters, stray joiners).`))}function $u(n){let t;try{t=JSON.parse(n)}catch{return null}if(!Array.isArray(t))return null;let e=t.filter(r=>typeof r=="string"||typeof r=="object"&&r!==null&&typeof r.label=="string"),s=[],i=[];for(let r of e){let a=ni(r);a!==null?s.push(a):(typeof r=="string"?r:r.label).trim()&&i.push(typeof r=="string"?r:r.label)}return Hu(n,i),s.length?s:null}function qu(n=et){return n.registerCodeLanguageRenderer({languages:[io],bare:!0,render:({source:t,open:e})=>{if(e)return"";let s=$u(t);return s?`<span class="aparte-suggestions-mark" hidden data-aparte-suggestions="${I(JSON.stringify(s))}"></span>`:`<code class="aparte-code-error">${P(t)}</code>`}})}var Fu=new WeakSet;function si(n){return!!n&&Fu.has(n)}function Wu(n){let t=n.segments,e=t[t.length-1];return n.status!=="streaming"||!e||e.isStreaming!==void 0||e.type!=="text"&&e.type!=="thinking"?t:[...t.slice(0,-1),{...e,isStreaming:!0}]}function ii(n,t,e){if(n.setTokens?.(t.tokens),t.segments&&t.segments.length>0){let s=n.getSegments?.()??[];if(s.length===t.segments.length){let i=Bs(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?.(Wu(t))}else t.content!==void 0&&n.setContent?.(t.content);t.attachments&&t.attachments.length>0&&n.setAttachments?.(t.attachments),e&&e.count>1&&n.setSiblings?.(e.count,e.index),t.usage!==void 0&&n.setUsage?.(t.usage),n.setFinishReason?.(t.finishReason),n.setContextSummary?.(t.contextSummary,{legacy:t.compaction===!0})}var ri=Symbol.for("aparte.derivedSegments");function ao(n){return n.map(t=>({id:X(),name:t.name,type:t.type||"application/octet-stream",url:URL.createObjectURL(t),size:t.size,blob:t}))}function oo(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 Ls=new Map;function ai(n,t){t?Ls.set(n,t):Ls.delete(n)}function lo(n,t){ai(n,t);try{window.dispatchEvent(new CustomEvent("aparte-conversation-status",{detail:{id:n,status:t}}))}catch{}}function on(n){return Ls.get(n)??null}var Uu=Symbol.for("aparte.openConversation");function Oe(n){for(let t=n;t;t=t.parentElement){let e=t[Uu];if(e)return e()}return null}function co(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 uo(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 Qe=class{constructor(t){this._options=t}_messageId=null;_state=null;_reason="";_marked=null;start(){let t=a=>this._options.active&&!this._options.active()?!1:!a||a===this._options.ownId(),e=a=>!!a&&this._options.owns(a),s=a=>{let o=a.detail;!t(o?.targetId)||!e(o?.messageId)||(this.clear(),this._set(o.messageId,"pending",""))},i=a=>{let o=a.detail;!t(o?.targetId)||o?.skipped||o?.messageId&&o.messageId===this._messageId&&this.clear()},r=a=>{let o=a.detail;if(!(!t(o?.targetId)||!e(o?.messageId))){if(o.aborted){o.messageId===this._messageId&&this.clear();return}o.messageId!==this._messageId&&this.clear(),this._set(o.messageId,"failed",o.error??"")}};return window.addEventListener("aparte-compact-start",s),window.addEventListener("aparte-compact-done",i),window.addEventListener("aparte-compact-error",r),()=>{window.removeEventListener("aparte-compact-start",s),window.removeEventListener("aparte-compact-done",i),window.removeEventListener("aparte-compact-error",r)}}clear(){let t=this._marked??(this._messageId?this._options.bubbleOf(this._messageId):null);this._messageId=null,this._state=null,this._reason="",this._marked=null,t?.removeAttribute("data-checkpoint"),t?.removeAttribute("data-checkpoint-reason")}reapply(){!this._messageId||!this._state||this._write(this._messageId,this._state,this._reason)}_set(t,e,s){this._messageId=t,this._state=e,this._reason=s,this._write(t,e,s)}_write(t,e,s){let i=this._options.bubbleOf(t);i&&(this._marked&&this._marked!==i&&(this._marked.removeAttribute("data-checkpoint"),this._marked.removeAttribute("data-checkpoint-reason")),this._marked=i,s?i.setAttribute("data-checkpoint-reason",s):i.removeAttribute("data-checkpoint-reason"),i.getAttribute("data-checkpoint")!==e&&i.setAttribute("data-checkpoint",e))}};function Xe(n){for(let t=n.length-1;t>=0;t--){let e=n[t].contextSummary?.summary;if(e!==void 0)return{summary:e,messages:n.slice(t)}}return{messages:n}}var ju="The earlier part of this conversation was compacted. This is a summary of what came before; continue from it.",oi=n=>`${ju}
68
+
69
+ ${n}`;function Wt(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}
70
+
71
+ ${s.content}`}:e[e.length-1]={...i,content:[...t(i.content),{type:"text",text:`
72
+
73
+ `},...t(s.content)]}}return e}var Dr="The tool call was stopped before it ran.",zu="The tool returned no output.";function Gu(n){let t=n.result?.trim();return n.status==="resolved"?t||zu:n.status==="failed"?t||"The tool failed.":n.status==="rejected"&&t||Dr}var ls=n=>n.type==="tool_call"&&!!n.deferred&&(n.status==="awaiting-approval"||n.status==="pending"),Br=n=>n.type==="tool_call"&&(n.status==="pending"||n.status==="awaiting-approval");function ho(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&&Br(d)||i.push({role:"tool",content:Gu(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&&Br(c)&&(l=!0)):(a.length>0&&!l&&o(),r.push(c));return o(),i}var po=n=>n.status==="streaming"||n.status==="pending";function ln(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}
74
+ ${i??""}
75
+ ${t}`)}else{if(s.type==="thinking"||s.type==="tool_call"||s.type==="error"||s.type==="activity")continue;if(typeof i=="string"&&i){let r=s.wire,a=r&&typeof r.before=="string"?r.before:"",o=r&&typeof r.after=="string"?r.after:"";e.push(`${a}${i}${o}`)}else{let r=s.fallback;r&&e.push(r)}}}return e.join(`
76
+ `).trim()}function Ku(n){let t=ln(n.segments);return t||(typeof n.content=="string"&&n.content?n.content:"")}function Vu(n){let t=Ku(n);return n.compaction?oi(t):t}function qe(n){return n.filter(t=>t.role!=="user"&&t.role!=="assistant"?!1:t.status!=="error"&&!po(t)).flatMap(t=>{if(t.role==="assistant"&&t.segments?.some(s=>s.type==="tool_call"))return ho(t,ln);let e=Vu(t);return e?[{role:t.role,content:e}]:[]})}function Bt(n){return n?Math.ceil(n.length/3.8):0}var li=n=>{if(!n)return 0;try{return Bt(JSON.stringify(n))}catch{return 0}};function fo(n){let t=0;for(let e of n)t+=Bt(zr(e.content)),e.toolCalls?.length&&(t+=li(e.toolCalls));return t}function Yu(n){return n.some(t=>typeof t.content!="string"&&t.content.some(e=>e.type!=="text"))}function Qu(n){let t=(n.tools??[]).map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema}));return fo(n.messages)+(t.length?li(t):0)}function go(n){return fo(qe(n))}var cn=n=>n.totalTokens??n.inputTokens+n.outputTokens;function _o(n){let t=n.getCurrentModel()?.capabilities;return(t?!t.includes("function_calling"):!1)?[]:n.getTools()}function Xu(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 mo=(n,t)=>n.segments?.some(e=>e.type===t)===!0;function Ju(n){let t=n.usage?.inputTokens,e=n.contextEstimate;return mo(n,"tool_call")?1:t&&e&&t>0&&e>0?Math.min(3,Math.max(.5,t/e)):1}function Zu(n,t){let e=n.usage;if(!mo(n,"thinking")||!(e.inputTokens>0))return cn(e);let s=n.segments??[],i=s.map(a=>a.type).lastIndexOf("tool_call"),r=Math.round(t*Bt(ln(s.slice(i+1))));return e.inputTokens+(e.outputTokens>0?Math.min(r,e.outputTokens):r)}function bo(n){let{messages:t,config:e}=n,s=Xe(t),i=_o(e),r=Bt(e.resolveSystemPrompt())+Bt(e.resolveToolSystemPrompts(i)),a=i.map(w=>({name:w.name,description:w.description,inputSchema:w.inputSchema})),o=a.length?li(a):0,l=s.summary===void 0?0:Bt(oi(s.summary)),c={system:r,tools:o,summary:l,messages:go(s.messages)},d=r+o+l+c.messages,h=-1;for(let w=t.length-1;w>=0;w--)if(t[w].role==="assistant"&&t[w].usage){h=w;break}let u=h>=0?t[h]:void 0,p=Xu(e,n.windowOverride),f=(w,S)=>({...p!==void 0?{window:p}:{},used:w,estimated:S,parts:c,other:Math.max(0,w-d)}),g=u!==void 0&&!n.viewChanged&&h===t.length-1&&!t.some(w=>w.contextSummary!==void 0&&w.contextSummary.createdAt>u.timestamp),_=u?Ju(u):1;return u&&g?f(Zu(u,_),!1):f(Math.round(_*d),!0)}var th=0,Fe=null;function de(n){Fe?.push(n)}function W(n,t,e){let s=document.createElement(n);return t&&(s.className=t),e!=null&&(s.textContent=e),s}function ci(n,t,e){let s=W("span","aparte-elic-option-body"),i=W("span","aparte-elic-option-title",n);if(i.dir="auto",e){let r=W("span","aparte-tag aparte-tag--sm aparte-elic-option-badge",M().t("elicitationRecommended")||"Recommended");i.append(" ",r)}return s.appendChild(i),t&&s.appendChild(Object.assign(W("span","aparte-elic-option-desc",t),{dir:"auto"})),s}function Is(n,t,e){let s=W("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(ci(n,t,e)),s}function di(n,t,e){let s;if(t.title&&t.title.trim()!==e?.trim()){let i=W("p","aparte-elic-title",t.title);i.dir="auto",s=`elic-title-${X()}`,i.id=s,n.appendChild(i)}return t.description&&n.appendChild(Object.assign(W("p","aparte-elic-desc",t.description),{dir:"auto"})),s}function vo(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 eh(n,t,e,s){let i=W("div","aparte-elic-field aparte-elic-enum"),r=di(i,n,e),a=W("div","aparte-elic-options"),o=`elic-${X()}`,l=n.multiple?"checkbox":"radio",c=l==="checkbox"?"aparte-checkbox":"aparte-radio",d=n.allowOther??M().getElicitationOptions().allowOther,h=new Set(Array.isArray(n.default)?n.default:n.default!=null?[n.default]:[]),u=s!=null&&!n.multiple&&h.size===0;vo(a,{multiple:n.multiple,commands:u,titleId:r,fallbackLabel:e});let p=(m,v,E,b)=>{if(u){let x=Is(v,E,b);return x.addEventListener("click",()=>s?.(m)),x}let y=W("label","aparte-field-choice aparte-elic-option"+(b?" aparte-elic-option--recommended":"")),A=W("input",c+" aparte-elic-control");return A.type=l,A.name=o,A.value=m,h.has(m)&&(A.checked=!0),y.append(A,ci(v,E,b)),y};for(let m of n.options)a.appendChild(p(m.value,m.label??m.value,m.description,m.recommended));let f=null,g=!1;if(d){let m=M();f=W("input","aparte-field aparte-elic-other-input"),f.type="text",f.placeholder=m.t("elicitationOtherPlaceholder"),f.style.display="none",f.setAttribute("aria-label",m.t("elicitationOtherLabel"));let v=f;if(u){let E=Is(m.t("elicitationOther"));E.classList.add("aparte-elic-option--other"),E.setAttribute("aria-expanded","false"),E.addEventListener("click",()=>{g=!0,E.setAttribute("aria-expanded","true"),v.style.display="",v.focus(),t()});let b=E.querySelector(".aparte-elic-option-title");de(()=>{let y=M();b.textContent=y.t("elicitationOther"),v.placeholder=y.t("elicitationOtherPlaceholder"),v.setAttribute("aria-label",y.t("elicitationOtherLabel"))}),a.append(E,v)}else{let E=W("label","aparte-field-choice aparte-elic-option aparte-elic-option--other"),b=W("input",c+" aparte-elic-control");b.type=l,b.name=o,b.value="__other__";let y=W("span","aparte-elic-option-body"),A=W("span","aparte-elic-option-title",m.t("elicitationOther"));y.appendChild(A),de(()=>{let x=M();A.textContent=x.t("elicitationOther"),v.placeholder=x.t("elicitationOtherPlaceholder"),v.setAttribute("aria-label",x.t("elicitationOtherLabel"))}),y.appendChild(f),E.append(b,y),a.appendChild(E)}}i.appendChild(a);let _=()=>Array.from(a.querySelectorAll(".aparte-elic-control")),w=()=>a.querySelector('input[value="__other__"]'),S=!1;a.addEventListener("keydown",m=>{S=m.key.startsWith("Arrow")}),a.addEventListener("click",()=>{S=!1}),a.addEventListener("change",()=>{let m=w();m&&f&&(f.style.display=m.checked?"":"none",m.checked&&!S&&f.focus()),S=!1,t()}),f?.addEventListener("input",t);let T=()=>f?.value.trim()??"";if(u)return{el:i,getValue:()=>T(),isComplete:()=>g&&T()!=="",focus:()=>a.querySelector(".aparte-elic-option--command")?.focus(),offersSubmit:()=>g};let k=()=>{let m=w()?.checked&&T()?T():"";if(n.multiple){let E=_().filter(b=>b.checked&&b.value!=="__other__").map(b=>b.value);return m&&E.push(m),E}let v=_().find(E=>E.checked);return v?v.value==="__other__"?m:v.value:""};return{el:i,getValue:k,isComplete:()=>{let m=k();return n.multiple?m.length>0:m!==""},focus:()=>_()[0]?.focus()}}function nh(n,t,e,s){let i=W("div","aparte-elic-field aparte-elic-boolean"),r=di(i,n,e),a=W("div","aparte-elic-options"),o=`elic-${X()}`,l=s!=null&&n.default==null;if(vo(a,{commands:l,titleId:r,fallbackLabel:e}),l){let u=M(),p=(f,g,_)=>{let w=Is(g);if(w.addEventListener("click",()=>s?.(f)),_){let S=w.querySelector(".aparte-elic-option-title");de(()=>{S.textContent=M().t(_)})}a.appendChild(w)};return p(!0,n.trueLabel??u.t("elicitationYes"),n.trueLabel?void 0:"elicitationYes"),p(!1,n.falseLabel??u.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=(u,p,f)=>{let g=W("label","aparte-field-choice aparte-elic-option"),_=W("input","aparte-radio aparte-elic-control");_.type="radio",_.name=o,_.value=u,n.default!=null&&String(n.default)===u&&(_.checked=!0);let w=W("span","aparte-elic-option-body"),S=W("span","aparte-elic-option-title",p);S.dir="auto",f&&de(()=>{S.textContent=M().t(f)}),w.appendChild(S),g.append(_,w),a.appendChild(g)},d=M();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 h=()=>a.querySelector("input:checked");return{el:i,getValue:()=>h()?.value==="true",isComplete:()=>h()!=null,focus:()=>a.querySelector("input")?.focus()}}function sh(n,t,e){let s=W("div","aparte-elic-field aparte-elic-string");di(s,n,e);let i=n.multiline?W("textarea","aparte-field aparte-field--textarea aparte-elic-text"):W("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??M().t("elicitationAnswerLabel")),r==null){let l=i;de(()=>{l.setAttribute("aria-label",M().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 Hr(n,t,e,s,i){let r=M().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 eh(n,t,e,i);case"boolean":return nh(n,t,e,i);case"string":return sh(n,t,e)}}function yo(n,t,e){let s=[],i=Fe;Fe=s;try{return{...ih(n,t,e),relabel:()=>{for(let a of s)a()}}}finally{Fe=i}}function ih(n,t,e){let s=W("div","aparte-elic-panel"),i=typeof n=="function"?n():n;i&&s.appendChild(Object.assign(W("p","aparte-elic-message",i),{dir:"auto"}));let r=null,a=!1,o=p=>{a||(a=!0,r?.(p))},l=p=>{r=p},c=W("div","aparte-elic-body");s.appendChild(c);let d=W("div","aparte-elic-dismiss");if(s.appendChild(d),t.type==="object"){let p=Object.entries(t.properties),f=new Set(t.required??p.map(([y])=>y)),g=M(),_=()=>{},w=()=>{_(),e()},S=p.map(([y,A])=>{let x=Hr(A,w,void 0,y);return!A.title&&!x.el.querySelector(".aparte-elic-title")&&x.el.insertBefore(Object.assign(W("p","aparte-elic-title",y),{dir:"auto"}),x.el.firstChild),c.appendChild(x.el),{key:y,field:x,required:f.has(y),header:A.header}}),T=()=>S.every(y=>!y.required||y.field.isComplete()),k={el:s,dismiss:d,getContent:()=>Object.fromEntries(S.map(y=>[y.key,y.field.getValue()])),isComplete:T,focus:()=>S[0]?.field.focus(),mode:()=>"submit",canProceed:T,proceed:()=>{},onSettle:l};if(S.length<2||g.getElicitationOptions().layout!=="stepped")return k;s.classList.add("aparte-elic-panel--stepped");let m=0,v=`aparte-elic-${++th}`,E=W("div","aparte-tabs aparte-tabs--underline aparte-elic-steps");E.setAttribute("role","tablist");let b=S.map((y,A)=>{let x=W("button","aparte-tabs__tab aparte-elic-step");return x.type="button",x.setAttribute("role","tab"),x.textContent=y.header?.trim()||String(A+1),x.dir="auto",x.id=`${v}-tab-${A}`,y.field.el.id=`${v}-panel-${A}`,y.field.el.setAttribute("role","tabpanel"),y.field.el.setAttribute("aria-labelledby",x.id),x.setAttribute("aria-controls",y.field.el.id),E.appendChild(x),x});return s.insertBefore(E,c),E.addEventListener("aparte-tab-change",y=>{m=b.indexOf(y.detail.tab)}),Ni(E),E.addEventListener("click",y=>{let A=b.indexOf(y.target.closest(".aparte-elic-step"));A>=0&&A===m&&S[A].field.focus()}),_=()=>{b.forEach((y,A)=>{let x=S[A].field.isComplete();y.toggleAttribute("data-answered",x);let O=y.querySelector(".aparte-elic-step__mark");if(x&&!O){let $=W("span","aparte-elic-step__mark");$.setAttribute("aria-hidden","true"),$.innerHTML=g.getIcon("check"),y.prepend($)}else!x&&O&&O.remove()})},_(),{...k,focus:()=>S[m]?.field.focus()}}let h=M().getElicitationOptions().answerOnClick,u=Hr(t,e,i,void 0,h?o:void 0);return c.appendChild(u.el),{el:s,dismiss:d,getContent:()=>u.getValue(),isComplete:()=>u.isComplete(),focus:()=>u.focus(),mode:()=>u.offersSubmit?.()??!0?"submit":"none",canProceed:()=>u.isComplete(),proceed:()=>{},onSettle:l}}var rh=0;function bt(n,t,e){let s=document.createElement(n);return t&&(s.className=t),e!=null&&(s.textContent=e),s}var ah=0;function wo(n,t,e,s,i=!0){let r=M(),a=bt("div","aparte-elic-panel aparte-approval-panel"),o=bt("div","aparte-elic-body");a.appendChild(o);let l=()=>typeof n=="function"?n():n,c=l()?Object.assign(bt("p","aparte-elic-message",l()),{dir:"auto"}):null;c&&o.appendChild(c);let d=null;if(s){d=bt("div","aparte-approval-args-label",r.t("approvalArgsLabel")),d.id="aparte-approval-args-"+ ++rh;let v=bt("pre","aparte-approval-args");v.textContent=s,v.setAttribute("role","group"),v.setAttribute("aria-labelledby",d.id),v.tabIndex=0,o.append(d,v)}let h=bt("div","aparte-elic-dismiss");a.appendChild(h);let u=null,p=!1,f=v=>{p||(p=!0,u?.(v))},g=bt("div","aparte-approval-options");g.setAttribute("role","group"),g.setAttribute("aria-label",r.t("approvalOptionsLabel")),c&&(c.id||=`aparte-approval-ask-${++ah}`,g.setAttribute("aria-describedby",c.id));let _=[],w=v=>typeof v.label=="function"?v.label():v.label,S=v=>typeof v.description=="function"?v.description():v.description,T=v=>ci(w(v),S(v));for(let v of t){let E=v.tone??"affirm",b=bt("button",`aparte-btn aparte-btn--block aparte-btn--surface aparte-approval-option aparte-approval-option--${E}`);b.type="button",b.appendChild(T(v)),b.addEventListener("click",()=>f({option:v.value})),g.appendChild(b),_.push({button:b,option:v})}o.appendChild(g);let k=i?bt("textarea","aparte-approval-instruction"):null;k&&(k.rows=1,k.placeholder=r.t("approvalInstructionPlaceholder"),k.setAttribute("aria-label",r.t("approvalInstructionPlaceholder")),k.addEventListener("input",e),o.appendChild(k));let m=()=>k?.value.trim()??"";return{el:a,dismiss:h,onSettle:v=>{u=v},getContent:()=>({instruction:m()}),isComplete:()=>m().length>0,focus:()=>{a.querySelector(".aparte-approval-option")?.focus()},relabel:()=>{let v=M(),E=v.t("approvalInstructionPlaceholder");k&&(k.placeholder=E,k.setAttribute("aria-label",E)),g.setAttribute("aria-label",v.t("approvalOptionsLabel")),c&&(c.textContent=l()),d&&(d.textContent=v.t("approvalArgsLabel"));for(let{button:b,option:y}of _)b.replaceChildren(T(y))}}}function Ao(n){return L(n.target??null).requestUserInput(n)}var oh="Not run: an earlier call of the same step was refused.",$r=n=>JSON.stringify([n.id,n.name,n.input]),qr=new Set,Rt=new Map,Fr="aparte-chat, aparte-chat-viewport, [data-aparte-chat]";function lh(n){return{id:n,getMetadata:()=>({id:n,name:n}),getModels:()=>[],chat:async()=>{throw new lt("This turn has no provider in the page. Register one, or use a runner that calls the model elsewhere (createAgentStreamRunner, an AG-UI runner).",z.CONFIG_NO_PROVIDER)}}}function ch(n,t){let e=[],s=0;for(let i of[...t].sort((r,a)=>r.start-a.start)){let r=n.indexOf(i.text,s);r<0||(s=r+i.text.length,e.push({...i,start:r,end:s}))}return e}var Rs=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===et){if(Rt.size===0)return!0;let a=this._resolveTarget(e?.targetId,t),o=a?L(a):et;return o===et||!Rt.has(o)}let i=this._resolveTarget(e?.targetId,t);if(!i)return!0;let r=L(i);return r===this._config||r===et}_streamController=null;options;_config;_claims=!1;constructor(t={}){this.options={autoRegister:!0,...t},this._config=t.config??et,this._registerKeyResolver(),this.options.autoRegister?za(this._config):Fa(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!==et&&!this._claims&&(this._claims=!0,Rt.set(this._config,(Rt.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=(Rt.get(this._config)??1)-1;t>0?Rt.set(this._config,t):Rt.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=t.agent?.name?.trim(),r=await Ao({kind:"approval",message:()=>{let l=this._config.getLocale(),c=L(s),d={id:`tool-${t.id}`,type:"tool_call",status:"awaiting-approval",toolCall:{id:t.id,name:t.name,input:t.input}},h=sn(d,c).text,u=Bd(d,c),p=u?`${h} ${u}`:h;return i?(l.approvalAskBy??"Allow {tool} for {agent}?").replace(/\{(agent|tool)\}/g,(f,g)=>g==="agent"?i:p):(l.approvalAsk??"Allow {tool}?").replace("{tool}",()=>p)},details:Ca(t.input,L(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(r.action!=="accept")return{approved:!1,by:"person"};let a=r.content,o=a?.instruction?.trim();return o?{approved:!1,instruction:o,by:"person"}:a?.option==="allow"?{approved:!0}:{approved:!1,by:"person"}}get _modelRunsElsewhere(){let t=this.options.streamRunner;return!!t&&t!==Un}_providerFor(t){let e=t?this._config.getAIProvider(t):void 0;return e||(this._modelRunsElsewhere?lh(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 v=>{let E={messages:v,modelId:r,stream:!0,tools:c.length?c:void 0,...o?.temperature!==void 0?{temperature:o.temperature}:{},...o?.meta?{_meta:o.meta}:{}};if(this.options.requestInterceptor&&(E=await this.options.requestInterceptor(E)),E.toolChoice==="none"){let b=this._config.resolveToolSystemPrompts(c);E={...E,tools:void 0,messages:b?E.messages.filter(y=>!(y.role==="system"&&y.content===b)):E.messages}}return E},h=await d(i);if(this._isAborted){rt(t,"aparte-message-aborted",{messageId:e},l),this._updateMessage(t,e,{status:"completed"});return}rt(t,"aparte-message-start",{messageId:e,role:"assistant"},l),o?.resume&&rt(t,"aparte-message-paused",{messageId:e},l),!o?.resume&&s.id&&this._updateMessage(t,e,{model:{providerId:s.id,modelId:h.modelId,...h.temperature!==void 0?{temperature:h.temperature}:{}}});let u=new AbortController;this._streamController!==u&&this._streamController?.abort(),this._streamController=u,this._turnsInFlight.add(e),this._agentNames.set(e,new Map);let p=o?.rebuild?L(t).getCompactor()??this._config.getCompactor():null,f=()=>{let v=t.getMessages?.()??[],E=v.findIndex(y=>y.id===e),b=E>0?v[E-1]:void 0;return b?.role==="user"?[b.id,e]:[e]},g=()=>o?.resume?this._resumeMessages(t,e,h.messages):h.messages,_=()=>Qu({messages:g(),tools:h.tools}),w=()=>Yu(g())?void 0:_(),S=()=>{this._closeOpenCalls(t,e),rt(t,"aparte-message-aborted",{messageId:e},l),this._updateMessage(t,e,{status:"completed"})},T=()=>this._isAborted||u.signal.aborted,k=async()=>{let v=o?.resume?{usage:void 0,suspended:o.resume}:await this._streamLoop(t,e,s,h,a,u,void 0,o?.files,o?.conversationId),E=this.options.maxTurns??10,b=0,y=new Set,A=$e({target:t,config:this._config,messageId:e,...l?{targetId:l}:{}});for(;v.suspended;){let $=this._isAborted||u.signal.aborted;if(!$&&++b>E){this._closeOpenCalls(t,e),$e({target:t,config:this._config,messageId:e,...l?{targetId:l}:{}})({type:"turn-limit-exceeded",scope:"global",limit:E});break}let D=new Set,q=$?void 0:await this._answerDeferred(t,e,v.suspended.pending,u.signal,A,y,D);if(y=D,!q){this._closeOpenCalls(t,e),(this._isAborted||u.signal.aborted)&&rt(t,"aparte-message-aborted",{messageId:e},l);break}let st={outcomes:q,...v.suspended.ticket?{token:v.suspended.ticket}:{}},pt=this._resumeMessages(t,e,h.messages);this._spendPause(t,e),rt(t,"aparte-message-resumed",{messageId:e},l),v=await this._streamLoop(t,e,s,{...h,messages:pt},a,u,st,void 0,o?.conversationId)}let x=v.usage,O=v.finishReason;this._isAborted||u.signal.aborted?(this._closeOpenCalls(t,e),this._updateMessage(t,e,{status:"completed"})):(rt(t,"aparte-message-done",{messageId:e,role:"assistant",usage:x,...O?{finishReason:O}:{}},l),this._readWindowAfterTurn())},m=async v=>{if(v.code!==z.USAGE_CONTEXT_EXCEEDED||!p||!o?.rebuild||(t.getMessage?.(e)?.segments??t.getMessages?.()?.find(b=>b.id===e)?.segments??[]).some(b=>b.type==="text"||b.type==="tool_call"))return"stands";try{let b=await p.compact({target:t,...l?{targetId:l}:{},force:!0,reason:"overflow",exclude:f(),signal:u.signal});if(T())return"stopped";if(!b.ok||b.skipped)return"stands";h=await d(await o.rebuild())}catch{return"stands"}return this._updateMessage(t,e,{status:"pending"}),"resend"};try{for(let v=0;;v++)try{if(v===0&&p?.beforeSend&&o?.rebuild){let E=!1;try{E=await p.beforeSend({target:t,...l?{targetId:l}:{},exclude:f(),requestTokens:_(),signal:u.signal})}catch(b){console.warn("[AparteClient] The compactor threw before a send; sending the request as built.",b)}if(T()){S();return}E&&(h=await d(await o.rebuild()))}this._updateMessage(t,e,{contextEstimate:w()}),await k();return}catch(E){if(this._closeOpenCalls(t,e),T()){rt(t,"aparte-message-aborted",{messageId:e},l),this._updateMessage(t,e,{status:"completed"});return}let b=lt.from(E,z.UNKNOWN_ERROR),y=v===0?await m(b):"stands";if(y==="resend")continue;if(y==="stopped"){S();return}this._handleLifecycleError(t,e,b);return}}finally{this._turnsInFlight.delete(e),this._agentNames.delete(e)}}_turnsInFlight=new Set;_agentNames=new Map;_toolsForCurrentModel(){return _o(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=Oe(i)??void 0,a=i.getMessages?.()??[],o=a.findIndex(T=>T.id===e),c=(o>=0?a[o]:void 0)?.role==="user"?o+1:o,d=o>=0?a.slice(0,c):a,h={id:X(),role:"assistant",content:"",status:"pending",timestamp:Date.now()},u=i.addSiblingOf?.(e,h)??h.id,p=this._config.getModelConfig(),f=p.defaultProvider,g=this._providerFor(f);if(!g)return;let _=f?await this._resolveAuth(f):void 0,w=this._messagesToChatMessages(d),S=this._systemMessages();await this._streamTurn(i,u,g,[...S,...Wt(w)],p.defaultModel||"",_,{...g.retryTemperature!==void 0?{temperature:g.retryTemperature}:{},...this._turnMeta([...d].reverse().find(T=>T.role==="user")),...r?{conversationId:r}:{},rebuild:async()=>[...this._systemMessages(),...Wt(this._messagesToChatMessages(this._current(i,d)))]})}_systemMessages(){let t=[],e=this._config.resolveSystemPrompt();e&&t.push({role:"system",content:e});let s=this._config.resolveToolSystemPrompts(this._toolsForCurrentModel());return s&&t.push({role:"system",content:s}),t}async _handleEdit(t){let{messageId:e,content:s,targetId:i}=t.detail??{};if(this._beginUserTurn(),!e||s===void 0)return;let r=this._resolveTarget(i,t);if(!r){console.warn("[AparteClient] aparte-edit \u2014 no target found");return}let a=Oe(r)??void 0,o=r.getMessages?.().find(S=>S.id===e);r.updateMessage?.(e,{content:s,...o?.tokens?{tokens:ch(s,o.tokens)}:{}});let l=r.getMessages?.()??[],c=l.findIndex(S=>S.id===e);if(r.truncateResponsesAfter)r.truncateResponsesAfter(e);else{let S=c>=0&&c+1<l.length?l[c+1]?.id:void 0;S&&r.truncateFrom?.(S)}let d=c>=0?l.slice(0,c+1):l,h=this._messagesToChatMessages(d),u=this._systemMessages(),p=this._config.getModelConfig(),f=p.defaultProvider,g=this._providerFor(f);if(!g)return;let _=f?await this._resolveAuth(f):void 0,w=X();r.appendMessage?.({id:w,role:"assistant",content:"",status:"pending",timestamp:Date.now()}),await this._streamTurn(r,w,g,[...u,...Wt(h)],p.defaultModel||"",_,{...this._turnMeta(c>=0?l[c]:void 0),...a?{conversationId:a}:{},rebuild:async()=>[...this._systemMessages(),...Wt(this._messagesToChatMessages(this._current(r,d)))]})}_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?at(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=Ct(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(Fr)){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(Fr);if(r)return r}return null}_asRenderTarget(t){if(!t)return null;if(typeof t.appendMessage=="function")return t;let e=t.viewport;return e&&typeof e.appendMessage=="function"?e:null}_targetIdOf(t){let e=t??null;for(;e;){if((e.tagName?.toLowerCase()==="aparte-chat"||e.hasAttribute?.("data-aparte-chat"))&&e.id)return e.id;e=e.parentElement}return t?.id||void 0}_messagesToChatMessages(t){let{summary:e,messages:s}=Xe(t);return[...this._summaryMessage(e),...qe(s)]}_summaryMessage(t){return t===void 0?[]:[{role:"user",content:oi(t)}]}_turnMeta(t){let e={...t?.metadata??t?.meta,...t?.tokens?.length?{tokens:t.tokens}:{}};return Object.keys(e).length>0?{meta:e}:{}}_warnedNoModel=!1;async _handleSend(t){let{content:e,modelId:s,providerId:i}=t.detail;if(this._config.getRequireModelSelection()&&!this._config.hasSelectedModel()&&!s){console.warn("[AparteClient] Send refused: requireModelSelection is on and no model is selected yet. The composer blocks this, but this send did not come from it \u2014 disable your own send affordances while `hasSelectedModel()` is false.");return}let r=null,a=t.detail?.targetId;if(a){let _=this._byId(a,t),w=this._asRenderTarget(_);w?r=w: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 _ of this._originChain(t)){let w=_;if(typeof w?.appendMessage=="function"){r=w;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}let o=Oe(r)??void 0;if(this._closeDeferred(r),this.options.echoUserMessage!==!1&&t.detail?.echoed!==!0){let _=Array.isArray(t.detail?.files)?t.detail.files:[];r.appendMessage?.({id:X(),role:"user",content:e,timestamp:Date.now(),..._.length>0?{attachments:ao(_)}:{},...t.detail?.tokens?.length?{tokens:t.detail.tokens}:{},...t.detail?.meta?{metadata:t.detail.meta}:{}}),t.detail&&typeof t.detail=="object"&&(t.detail.echoed=!0)}let l=X(),c=this._config.getModelConfig(),d=i||c.defaultProvider;if(!d&&!this._modelRunsElsewhere){this._warnedNoModel||(this._warnedNoModel=!0,console.warn("[AparteClient] Send dropped: no model is selected. Call aparteGlobalConfig.setModelConfig({ defaultProvider, defaultModel }), mount <aparte-model-selector auto-select persist>, or register one provider with a single model \u2014 that one is selected on its own.")),this._handleLifecycleError(r,l,new lt("No provider selected. Please configure a provider.",z.CONFIG_NO_PROVIDER));return}let h=this._providerFor(d);if(!h){this._handleLifecycleError(r,l,new lt(`Provider '${d}' is not registered.`,z.CONFIG_MISSING_KEY,{providerId:d}));return}r.appendMessage?.({id:l,role:"assistant",content:"",status:"pending",timestamp:Date.now()});let u,p,f,g=Array.isArray(t.detail?.files)?t.detail.files:[];try{u=d?await this._resolveAuth(d):void 0;let _=this._selectFilesToInject(g),w=_.length>0?await this._filesToContentParts(_):[];f=w.length>0?w:void 0,p=this._buildMessages(e,r,f)}catch(_){this._handleLifecycleError(r,l,lt.from(_,z.UNKNOWN_ERROR));return}await this._streamTurn(r,l,h,p,s||c.defaultModel||"",u,{rebuild:async()=>this._buildMessages(e,r,f),...g.length>0?{files:g}:{},...this._turnMeta(t.detail),...o?{conversationId:o}:{}})}_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}),Wt(i)}_toHistoryMessages(t){let{summary:e,messages:s}=Xe(t),i=0;for(let r=0;r<s.length;r++){let a=s[r];a.role==="assistant"&&a.status!=="error"&&!po(a)&&(i=r+1)}return[...this._summaryMessage(e),...qe(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}
77
+ // File: ${r.name}
78
+ ${c}
79
+ \`\`\``})},l.onerror=()=>o(new Error(`Failed to read file: ${r.name}`)),l.readAsText(r)}):(qr.has(r.name)||(qr.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,c){this._streamController!==a&&this._streamController?.abort(),this._streamController=a;let d=this.options.streamRunner??Un;return this._runViaStreamRunner(d,t,e,s,i,r,a,o,l,c)}async _runViaStreamRunner(t,e,s,i,r,a,o,l,c,d){let h=o.signal,u=this._targetIdOf(e),p=$e({target:e,config:this._config,messageId:s,...u?{targetId:u}:{}}),f=r._meta?.prefixSegments,g,_,w,S=A=>{if(p(A),A.type==="agent-start"&&A.name&&this._agentNames.get(s)?.set(A.agentId,A.name),A.agentId==null){if(A.type==="tool-failed"&&(w=A.error),A.type==="run-done"&&(_=A.finishReason),A.type==="run-suspended"){let x=A.ticket;g={pending:A.pending,...typeof x=="string"?{ticket:x}:{}}}if(A.type==="run-start"&&f?.length&&!l)for(let x of f)e.addSegment?.(x)}},T=async A=>{let x=await this._config.getTransport().chat(i,A,a,{providerId:i.id,signal:h});return typeof x=="string"?x:Ga(x,h)},k=A=>{let x=this._config.getToolHandler(A);if(!x)return;let O={target:e,config:this._config,...d?{conversationId:d}:{}};return($,D,q)=>x($,D,q?{...O,run:q}:O)},m=!!this.options.approvalResolver,v=A=>{let x=this._config.getTools().find(O=>O.name===A);if(x)return{maxTurns:x.maxTurns,parallel:x.parallel,needsApproval:m?x.needsApproval:O=>{let $=this._config.ruleOnToolCall(O).verdict;return $==="allow"?!1:$}}},E=this._approvalResolverFor(e),b=A=>{if(w===void 0||A instanceof lt)return A;let x=A instanceof Error?A.message||A.name:typeof A=="string"?A:String(A);return x===w?new lt(x,z.UNKNOWN_ERROR,void 0,A):A};return{usage:await t({messageId:s,...i.id?{providerId:i.id}:{},...l?{deferral:l}:{},...c&&c.length>0?{files:c}:{},...d?{conversationId:d}:{},baseRequest:r,transportCall:T,toolLookup:k,toolConfigLookup:v,approvalResolver:E,emitter:S,signal:h,maxTurns:this.options.maxTurns,toolTimeoutMs:this.options.toolTimeoutMs,...this.options.parallelTools!==void 0?{parallelTools:this.options.parallelTools}:{},idGen:A=>A==="synthetic-tool"?X():`${A}-${X()}`}).catch(A=>{throw b(A)})??void 0,..._?{finishReason:_}:{},...g?{suspended:g}:{}}}_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,a=new Set,o=new Set){let l={},c=this._approvalResolverFor(t,!0),d=h=>{for(let u of s.slice(h+1))l[u.toolCallId]={kind:"decision",approved:!1,reason:oh,by:"earlier-refusal"}};for(let[h,u]of s.entries()){if(i.aborted)break;let p={id:u.toolCallId,name:u.name,input:u.input??{}},f=u.agentId===void 0?void 0:this._agentNames.get(e)?.get(u.agentId),g=u.agentId===void 0?p:{...p,agent:{id:u.agentId,...f?{name:f}:{}}};if(u.reason==="approval"){let _;try{_=await c(g,i)}catch(w){if(!i.aborted&&w?.name!=="AbortError")throw w}if(!_||i.aborted)return;if(l[u.toolCallId]={kind:"decision",..._},_.approved)o.add($r(p));else{d(h);break}}else if(u.reason==="external"){let _=null,w=$r(p);if(!a.has(w)&&!o.has(w))try{_=await this._gateBrowserTool(g,i,t,r)}catch(m){if(!i.aborted&&m?.name!=="AbortError")throw m;_=void 0}if(_===void 0||i.aborted)return;if(_&&!_.approved){l[u.toolCallId]={kind:"decision",..._},d(h);break}let S=_?.payload,T=S&&typeof S=="object"&&!Array.isArray(S)?{...p,input:{...p.input,...S}}:p,k=this._config.getToolHandler(u.name);try{if(!k)throw new Error(`No browser handler is registered for "${u.name}".`);let m=await k(T,i,{target:t,config:this._config});l[u.toolCallId]={kind:"result",content:m.content,...m.structuredContent!==void 0?{structuredContent:m.structuredContent}:{}}}catch(m){if(i.aborted)break;l[u.toolCallId]={kind:"failed",error:m instanceof Error?m.message:String(m)}}}}return i.aborted?void 0:l}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,...t.agent?{agentId:t.agent.id}:{}});let a=await this._approvalResolverFor(s)(t,e)??void 0;return a?.approved&&r==="ask"&&(t.agent?i?.({type:"tool-approved",toolCallId:t.id,agentId:t.agent.id}):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?ho(i,ln,{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 Wt([...this._systemMessages(),...a,...i>=0?qe([s[i]]):[]])}_closeDeferred(t){let s=[...t.getMessages?.()??[]].reverse().find(r=>r.role==="assistant");if(!s?.segments?.some(ls))return;let i=s.segments.map(r=>{if(!ls(r))return r;let{deferred:a,...o}=r;return{...o,status:"aborted"}});t.updateMessage?.(s.id,{segments:i})}async resumeDeferred(t){let e=typeof t=="string"?this._byId(t):t??this.options.targetResolver?.()??null,s=e?this._asRenderTarget(e):this._scanForTarget();if(!s)return!1;let i=s.getMessages?.()??[],r=[...i].reverse().find(p=>p.role==="assistant"),a=(r?.segments??[]).filter(ls),o=a.find(p=>p.deferred?.ticket)?.deferred?.ticket;if(!r||a.length===0||!o||this._resuming.has(r.id)||this._turnsInFlight.has(r.id))return!1;let l=this._config.getModelConfig(),c=r.model&&this._config.getAIProvider(r.model.providerId)?r.model:void 0,d=c?.providerId??l.defaultProvider,h=this._providerFor(d);if(!h)return console.warn("[AparteClient] Cannot resume the paused turn: no provider is selected."),!1;this._beginUserTurn();let u=Oe(s)??void 0;this._resuming.add(r.id);try{let p=h.id?await this._resolveAuth(h.id):void 0,f=a.map(_=>({toolCallId:_.toolCall.id,name:_.toolCall.name,input:_.toolCall.input,reason:_.deferred.reason})),g=this._resumeBase(i,i.indexOf(r));await this._streamTurn(s,r.id,h,g,c?.modelId??l.defaultModel??"",p,{resume:{pending:f,ticket:o},rebuild:async()=>{let _=s.getMessages?.()??[],w=_.findIndex(S=>S.id===r.id);return w>=0?this._resumeBase(_,w):g},...c?.temperature!==void 0?{temperature:c.temperature}:{},...u?{conversationId:u}:{}})}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-${X()}`,type:"error",content:s.message,code:s.code};if(ws(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]});rt(t,"aparte-message-error",{messageId:e,error:s},this._targetIdOf(t))}};function So(n){return n.next?So(n.next):"current"in n?n:null}var Je=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=So(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 Qt(n){return n.status==="streaming"||n.status==="pending"?!0:n.status===void 0&&n.role==="assistant"&&!n.content?.trim()&&!n.segments?.length}function Co(n,t,e){let s="other";try{s=new Intl.PluralRules(e).select(t)}catch{}let i=n.split("|"),r=o=>i.find(l=>l.startsWith(`${o}:`)),a=r(s)??r("other")??n;return a.slice(a.indexOf(":")+1).replace("{n}",String(t))}var dh=".aparte-message-content, .aparte-segments, .aparte-content, .aparte-checkpoint__summary";function ht(n){return!!n?.closest?.(dh)}var Wr=Symbol.for("aparte.dialogTriggers"),Os=null,Ze=null;function uh(n){Os=n.target,Ze=null}function hh(n){Ze=n.target}function ph(n){let t=n.target;if(!t?.closest)return;let e=t.closest("[data-aparte-dialog-open]");if(e&&!ht(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&&!ht(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=Os===t&&Ze===t;Os=null,Ze=null,i&&t.close()}}function Eo(n=document){let t=n;t[Wr]||(t[Wr]=!0,n.addEventListener("pointerdown",uh,!0),n.addEventListener("pointerup",hh,!0),n.addEventListener("click",ph))}var cs="defer-hydration",ue=new WeakMap,he=new WeakMap,Jt=new WeakSet,tn=new WeakSet,Ps=new WeakMap,Ur=new WeakSet;function jr(n){if(tn.has(n))return!1;if(he.has(n))return!0;let t=n.closest(`[${cs}]`);if(!t)return!1;he.set(n,t);let e=ue.get(t);if(!e){e=[],ue.set(t,e);let s=new MutationObserver(()=>{t.hasAttribute(cs)||fh(t)});s.observe(t,{attributes:!0,attributeFilter:[cs]}),Ps.set(t,s)}return e.push(n),!0}function fh(n){Ps.get(n)?.disconnect(),Ps.delete(n);let t=ue.get(n)??[];ue.delete(n);for(let e of t)he.delete(e),e.isConnected&&!tn.has(e)&&e.connectedCallback?.()}function G(n){if(Ur.has(n))return;Ur.add(n);let t=n.prototype,e=t.connectedCallback,s=t.attributeChangedCallback,i=t.disconnectedCallback,r=n.observedAttributes??[];t.connectedCallback=function(){if(jr(this)){Jt.add(this);return}if(Jt.has(this)){Jt.delete(this);for(let a of r){let o=this.getAttribute(a);o!==null&&s?.call(this,a,null,o)}}tn.add(this),e?.call(this)},s&&(t.attributeChangedCallback=function(a,o,l){if(jr(this)){Jt.add(this);return}s.call(this,a,o,l)}),t.disconnectedCallback=function(){let a=he.get(this);if(a){he.delete(this);let o=ue.get(a);o&&o.splice(o.indexOf(this),1);return}Jt.has(this)||(tn.delete(this),i?.call(this))}}function J(n){return n===""?!0:!!n}var hn=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",J(t))}get selected(){return this.hasAttribute("selected")}set selected(t){this.toggleAttribute("selected",J(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)}};G(hn);customElements.get("aparte-option")||customElements.define("aparte-option",hn);var pn=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",J(t))}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(t){this.toggleAttribute("collapsed",J(t))}get loading(){return this.hasAttribute("loading")}set loading(t){this.toggleAttribute("loading",J(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=L(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,` ${L(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":""})}};G(pn);customElements.get("aparte-optgroup")||customElements.define("aparte-optgroup",pn);var fn=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",J(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(L(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=L(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 h=e?this._buildSearchInput(i):null;h&&d.appendChild(h);let u=document.createElement("div");u.className="aparte-select-options",u.setAttribute("role","listbox"),u.setAttribute("aria-label",r.getAttribute("aria-label")??t),u.id=this.id?`${this.id}-listbox`:`aparte-listbox-${++n._listboxSeq}`,r.setAttribute("aria-controls",u.id),h?.setAttribute("aria-controls",u.id),s.forEach(p=>{(p.tagName==="APARTE-OPTION"||p.tagName==="APARTE-OPTGROUP")&&u.appendChild(p)}),d.appendChild(u),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=at(t);(!e||!this.contains(e))&&this._closeDropdown()}_handleKeydown(t){if(!this._isOpen)return;let e=it(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=>ko(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 ko(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 ko(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()}G(fn);customElements.get("aparte-select")||customElements.define("aparte-select",fn);var gn=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>`}};G(gn);customElements.get("aparte-progress-spinner")||customElements.define("aparte-progress-spinner",gn);var _n=class extends HTMLElement{static get observedAttributes(){return["name"]}_unsubscribe=null;connectedCallback(){this._render(),this._unsubscribe=Mt(this,()=>this._render())}disconnectedCallback(){this._unsubscribe?.(),this._unsubscribe=null}attributeChangedCallback(){this.isConnected&&this._render()}_render(){let t=this.getAttribute("name"),e=t?L(this).getIcon(t):null;this.innerHTML=e??"",this.firstElementChild?.setAttribute("aria-hidden","true")}};G(_n);customElements.get("aparte-icon")||customElements.define("aparte-icon",_n);function To(n){let t=n.activeElement;for(;t?.shadowRoot?.activeElement;)t=t.shadowRoot.activeElement;return t}function ui(n,t){for(let e=n;e;e=e.parentNode??(e instanceof ShadowRoot?e.host:null))if(e===t)return!0;return!1}function xo(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 mn=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=Mt(this,()=>this._relabelPending()),L(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(){L(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=L(this);Q(t,()=>this._pending.relabel())}_present=t=>{let e=this._getComposer();return e?new Promise((s,i)=>{let r=!1,a={},o=To(document),l=()=>{let O=t.message;return String(typeof O=="function"?O():O??"")},c="aparte-chat, [data-aparte-chat], [data-aparte-host]",d='input, textarea, select, [contenteditable]:not([contenteditable="false"])',h=e.closest(c)??e.parentElement??e,u=!(o instanceof HTMLElement)||o===document.body,p=u?null:o,f=p!==null&&ui(p,h),g=p!==null&&p.matches(d),_=p!==null&&!f&&(g||p.tagName==="IFRAME"||p.closest(c)!==null),w=O=>{let $=e.querySelector(":scope > .aparte-elic-status");$||($=document.createElement("span"),$.className="aparte-sr-only aparte-elic-status",$.setAttribute("role","status"),e.appendChild($));let D=$;D.textContent="",O&&setTimeout(()=>{D.isConnected&&(D.textContent=O)},60)},S=(O,$)=>{if(_){w($);return}let D=window.scrollX,q=window.scrollY;g&&f?(O.el.hasAttribute("tabindex")||O.el.setAttribute("tabindex","-1"),O.el.hasAttribute("role")||O.el.setAttribute("role","group"),$&&!O.el.hasAttribute("aria-label")&&O.el.setAttribute("aria-label",$),O.el.focus()):O.focus(),u&&(window.scrollX!==D||window.scrollY!==q)&&window.scrollTo(D,q)},T=()=>{if(r)return!1;r=!0,this._pending=null;let O=To(document),$=O instanceof Node&&ui(O,e);return e.hidePanel(a.token),w(""),$&&((!_&&p!==null&&p.isConnected&&!ui(p,e)?p:null)??e).focus(),!0},k=O=>{T()&&s(O)},m=(O="aborted")=>{T()&&i(new Tt(O))};if(t.signal){if(t.signal.aborted){m();return}t.signal.addEventListener("abort",()=>m(),{once:!0})}let v=L(this);if(t.kind==="approval"){let O=()=>q.isComplete()&&!q.el.hasAttribute("data-collapsed"),$=()=>O()?"submit":"none",D=()=>e.setPanelSubmitEnabled(O(),$()),q=Q(v,()=>wo(t.message,t.options??[],D,t.details,t.allowOther??!0));q.onSettle(pt=>k({action:"accept",content:pt}));let st=xo(q.el,q.dismiss,v,()=>q.focus(),D);this._pending={abort:()=>m(),composer:e,relabel:()=>{q.relabel(),st.relabel(L(this))}},a.token=e.showPanel(q.el,{submitEnabled:q.isComplete(),mode:$(),onSubmit:()=>{q.isComplete()&&k({action:"accept",content:q.getContent()})},onEvict:()=>m()}),S(q,l());return}let E=t.schema??{type:"string"},b=()=>{let O=y.el.hasAttribute("data-collapsed");e.setPanelSubmitEnabled(!O&&y.canProceed(),O?"none":y.mode())},y=Q(v,()=>yo(t.message,E,b)),A=document.createElement("button");A.type="button",A.className="aparte-btn aparte-elic-skip",A.textContent=v.t("elicitationSkip"),A.addEventListener("click",()=>k({action:"decline"})),y.dismiss.appendChild(A);let x=xo(y.el,y.dismiss,v,()=>y.focus(),b);y.onSettle(O=>k({action:"accept",content:O})),this._pending={abort:()=>m(),composer:e,relabel:()=>{y.relabel();let O=L(this);A.textContent=O.t("elicitationSkip"),x.relabel(O)}},a.token=e.showPanel(y.el,{submitEnabled:y.canProceed(),mode:y.mode(),onEvict:()=>m(),onSubmit:()=>{y.isComplete()&&k({action:"accept",content:y.getContent()})}}),S(y,l())}):Promise.reject(new Tt("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")&&(G(mn),customElements.define("aparte-elicitation",mn));function Xo(n){return!n.hasAttribute("loading")&&!n.querySelector("aparte-chat-bubble")}var bn=class extends HTMLElement{static get observedAttributes(){return["placeholder","disabled","submit-on-enter","attachments","type-to-focus"]}_observer=null;_loadingObserver=null;_offGlide=null;_childObserver=null;_gated=!1;_gateOwns=!1;_ownsShell=!1;connectedCallback(){this.setAttribute("data-aparte-chat",""),this._render(),this._forwardAttr("placeholder"),this._forwardAttr("disabled"),this._forwardAttr("submit-on-enter"),this._forwardAttr("type-to-focus"),this._syncEmptyWatch(),this._syncLoadingWatch(),this._watchForViewport(),this._offGlide?.(),this._offGlide=co(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==="type-to-focus"){let r=this.querySelector("aparte-composer");s!==null?r?.setAttribute(t,s):r?.removeAttribute(t);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="${I(t)}"`:"")+(this.hasAttribute("disabled")?" disabled":""),s=this.hasAttribute("attachments");this.innerHTML=`
80
+ <aparte-chat-viewport></aparte-chat-viewport>
81
+ <aparte-elicitation></aparte-elicitation>
82
+ <aparte-composer${e}>
83
+ <div class="aparte-composer-shell">
84
+ ${s?"<aparte-composer-attachments></aparte-composer-attachments>":""}
85
+ <div class="aparte-composer-row">
86
+ ${s?"<aparte-composer-add-attachment></aparte-composer-add-attachment>":""}
87
+ <aparte-composer-input></aparte-composer-input>
88
+ <aparte-composer-send></aparte-composer-send>
89
+ </div>
90
+ </div>
91
+ </aparte-composer>
92
+ `,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||Xo(t))}};G(bn);customElements.get("aparte-chat")||customElements.define("aparte-chat",bn);function gh(n,t){let e=[],s=-1,i=-1,r=0,a=()=>{r>=2&&e.push({from:s,to:i}),s=-1,i=-1,r=0};return n.forEach((o,l)=>{let c=t(o);c==="stop"?a():c==="fold"&&(s<0&&(s=l),i=l,r+=1)}),a(),e}function dn(n,t){let e=`[data-segment-id="${tt(t)}"]`;return n.querySelector(`:scope > ${e}, :scope > .aparte-turn > .aparte-turn__body > ${e}`)}function _h(n){let t=1/0,e=-1/0;for(let s of n){let{startedAt:i,endedAt:r}=pe(s)??{};if(i==null||r==null)return;t=Math.min(t,i),e=Math.max(e,r)}return n.length>0?e-t:void 0}var mh=(n,t)=>t?n.split(t).length-1:0;function bh(n,t){let e=n.createElement("span");e.className="aparte-tag aparte-inline-token",t.kind&&(e.dataset.kind=t.kind);let s=n.createElement("span");return s.className="aparte-tag__label",s.textContent=t.label,e.appendChild(s),e}function vh(n,t,e){let s=mh(t.slice(0,e.start),e.text),i=n.ownerDocument,r=i.createTreeWalker(n,NodeFilter.SHOW_TEXT);for(;r.nextNode();){let a=r.currentNode;for(let o=a.data.indexOf(e.text);o>=0;o=a.data.indexOf(e.text,o+e.text.length)){if(s-- >0)continue;let l=i.createRange();l.setStart(a,o),l.setEnd(a,o+e.text.length),l.deleteContents(),l.insertNode(bh(i,e));return}}}function yh(n,t,e){if(!n.querySelector(".aparte-inline-token"))for(let s of[...e].sort((i,r)=>r.start-i.start))s.text&&vh(n,t,s)}function Mo(n,t,e){let s=document.createElement("button");return s.type="button",s.className=`aparte-btn aparte-btn--sm ${t}`,s.textContent=n,s.addEventListener("click",e),s}function wh(n){let t=document.createElement("div");t.className="aparte-feedback-reasons",t.setAttribute("role","group"),t.setAttribute("aria-label",n.title);let e=document.createElement("span");e.textContent=n.title,t.appendChild(e);for(let s of n.reasons)t.appendChild(Mo(s,"aparte-btn--surface",()=>n.onPick(s)));return t.appendChild(Mo(n.dismiss,"aparte-btn--ghost",n.onClose)),t}var Lo=n=>!!n&&typeof n.getMessages=="function"&&typeof n.updateMessage=="function";function Ah(n){let t=_t(n);if(Lo(t))return t;let e=n.closest("aparte-chat-viewport");return Lo(e)?e:null}function Sh(n,t){let e=Ah(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 wt(n,t,e){let s=document.createElement(n);return s.className=t,e!==void 0&&(s.textContent=e),s}function _e(n,t){let e=wt("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 Ch(n){let{kind:t,locale:e}=n,s=wt("div","aparte-checkpoint");s.setAttribute("role","group"),s.setAttribute("aria-label",e.checkpointGroup??"Context summary"),s.setAttribute("data-state",t);let i=wt("div","aparte-checkpoint__row aparte-divider aparte-divider--label"),r=wt("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=wt("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(wt("span","aparte-sr-only",`: ${n.reason}`)))),r.appendChild(o),t==="done"||t==="legacy")if(n.confirming&&t==="done"){let l=wt("span","aparte-checkpoint__confirm"),c=wt("span","aparte-checkpoint__question",e.checkpointRestoreConfirm??"Send the original messages to the model again?");c.id=`${n.summaryId}-question`;let d=_e("restore-confirm",e.checkpointRestore??"Restore");d.setAttribute("aria-describedby",c.id),l.append(c,d,_e("restore-cancel",e.cancel??"Cancel")),r.appendChild(l)}else{let l=_e("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(_e("restore",e.checkpointRestore??"Restore"))}else t==="failed"&&r.appendChild(_e("retry",e.retry??"Retry"));if(t==="done"||t==="legacy"){let l=wt("div","aparte-checkpoint__summary aparte-segment-content");l.id=n.summaryId,n.open||(l.hidden=!0),s.appendChild(l)}return s}function Io(n,t){return n.type==="tool_call"?Ha(t):n.type==="activity"?$a(t):null}var Ro=!1;function Eh(n){Ro||(Ro=!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 hi(n){let t=typeof n.fallback=="string"&&n.fallback.trim()?n.fallback:null;t||Eh(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 Lt(n,t){let e=Xs(n,t);return e||(Wa(t),Xs(n,t))}function me(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 we=new Map;function kh(){let n=[...we].filter(([e])=>!e.firstChild);we.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 Th=0,vn=class extends HTMLElement{_contentEl=null;_segmentsEl=null;_attachmentsEl=null;_actionBarEl=null;_branchPickerEl=null;_footerEl=null;_content="";_tokens;_streaming=!1;_clearingStreamingAttr=!1;_segments=[];_role="assistant";_attachments=[];_usage=null;_step=null;_finishReason=null;_contextSummary=null;_legacyCompaction=null;_checkpointOpen=!1;_confirmingRestore=!1;_checkpointDrawn="";_checkpointId=`aparte-checkpoint-${++Th}`;_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(),Q(this._cfg,()=>oa(this)),_a(this),this._syncSources(),this._updateTimestamp(this.getAttribute("timestamp")),this._redrawQueued||(this._redrawQueued=!0,queueMicrotask(()=>{this._redrawQueued=!1,this.isConnected&&this._redrawIfStale()})))};_redrawQueued=!1;_drawnWithVersion=0;_drawn=new Map;_written=new Set;_releasedWhileDetached=!1;_releaseCheckQueued=!1;_offRenderers=null;_toolRendererFor(t){if(t.type!=="tool_call")return null;let e=this._cfg;if(Lt("tool_call",e)!==zt)return null;let s=t.toolCall?.name;return!s||e.isToolHidden(s)?null:e.getToolRenderer(s)??null}_innerRendererFor(t){return t.type!=="activity"?this._toolRendererFor(t):Lt("activity",this._cfg)!==Gt?null:this._cfg.getActivityRenderer(t.activityType)??null}_install(t,e,s,i=t){let r=this._drawn.get(t.id);r&&r.el!==e&&this._release(t.id);let a={el:e,renderer:s,tool:null,segment:t};this._drawn.set(t.id,a),this.isConnected||this._scheduleReleaseCheck(),s?.setup&&Q(this._cfg,()=>s.setup(e,i)),a.tool=Io(t,e)}_drawnAs(t,e=!1){return t.type!=="text"&&t.type!=="thinking"?t:t.isStreaming===!0?(this._written.add(t.id),t):!e||t.isStreaming===!1||!this._streaming?t:(this._written.add(t.id),{...t,isStreaming:!0})}_release(t){let e=this._drawn.get(t);if(!e)return;this._drawn.delete(t);let s=e.renderer?.cleanup;if(s)try{Q(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=Lt(t.type,s),r=e.el;this._release(t.id);let a=i?this._drawnAs(t):t,o=i?me(Q(s,()=>i.render(t)),t):hi(t);return o?(r.replaceWith(o),this._install(t,o,i,a),!0):(r.remove(),!0)}_stillDrawnByCurrent(t,e){return Lt(t.type,this._cfg)===e.renderer&&this._innerRendererFor(t)===e.tool}_redrawSegmentsWhoseRendererChanged(){if(!(!this.isConnected||!this._segmentsEl||this._drawn.size===0)){for(let t of this._segments){let e=this._drawn.get(t.id);!e||this._stillDrawnByCurrent(t,e)||this._redrawSegment(t)}this._syncTurns()}}_onRenderersChange=t=>{t!==this._cfg&&t!==et||this._redrawSegmentsWhoseRendererChanged()};_keepsItsDrawing(t,e){return(si(e.renderer)||si(e.tool))&&this._stillDrawnByCurrent(t,e)}_redrawIfStale(){if(!(this._streaming||this._editing||dt(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=dt(this._cfg);for(let t of this._segments){let e=this._drawn.get(t.id);this._keepsItsDrawing(t,e)||this._redrawSegment(t)}this._syncTurns(),this._reflectError(),this._syncCopyAction()}}_relabelSegments(){if(this._segmentsEl){for(let t of this._segments){let e=Lt(t.type,this._cfg);if(!e?.relabel)continue;let s=dn(this._segmentsEl,t.id);s&&Q(this._cfg,()=>e.relabel(s,t))}this._syncTurns()}}_updateLocalizedLabels(){let t=this._cfg.getLocale(),e=(s,i)=>{this.querySelector(s)?.setAttribute("aria-label",i)};this._wroteArrowLabels&&(e(".aparte-branch-prev",t.previousResponse??"Previous response"),e(".aparte-branch-next",t.nextResponse??"Next response")),this._wroteBarLabel&&e(".aparte-action-bar",t.messageActions??"Message actions")}get _cfg(){return L(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??=so(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(),this.isConnected&&this._updateWaiting()})}_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._clearingStreamingAttr||this._updateStreaming(s!==null&&s!=="false");break;case"name":this._updateName();break}}appendToken(t){this._content+=t,this._updateContent(),this._syncCopyAction()}_askFeedbackReason(t){let e=this._cfg.getBubbleActions().feedbackReasons;if(!e?.length||this.querySelector(".aparte-feedback-reasons"))return;let s=wh({reasons:e,title:this._cfg.t("feedbackReasonTitle"),dismiss:this._cfg.t("feedbackReasonDismiss"),onPick:i=>{s.remove(),this.dispatchEvent(new CustomEvent("aparte-feedback-reason",{bubbles:!0,composed:!0,detail:{messageId:t,reason:i}}))},onClose:()=>s.remove()});this.querySelector(".aparte-footer")?.after(s)}setTokens(t){this._tokens=t,this._drawTokens()}_drawTokens(){this._contentEl&&this._role==="user"&&this._tokens?.length&&yh(this._contentEl,this._content,this._tokens)}setContent(t){this._content=t,this.setAttribute("content",t),this._resetMarkdownStream(),this._updateContent(),this._syncCopyAction()}_resetMarkdownStream(){let t=this;t._aparteSmd&&t._aparteSmd.renderer.end(),t._aparteSmd=void 0}getContent(){return this._content}setSegments(t){this._replaceSegments(t),this._syncSources(),this._updateWaiting()}_syncSources(){let t=this._segmentsEl,e=t?.parentElement;if(!t||!e)return;let s=this._segments.flatMap(i=>i.type==="text"?i.sources??[]:[]);wa(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=dt(this._cfg);for(let s of t)e.has(s.id)?this._applySegmentUpdate(s.id,s,s):this._redrawSegment(s);return this._syncTurns(),this._reflectError(),this._syncCopyAction(),!0}addSegment(t){this._segments.push(t),this._appendSegmentEl(t),this._syncTurns(),t.type==="text"&&t.sources&&this._syncSources(),this._updateWaiting()}updateSegment(t,e){let s=this._segments.findIndex(i=>i.id===t);if(s!==-1){let i=Ds(this._segments[s],e);this._segments[s]=i,i.isStreaming===!1?this._written.delete(t):"content"in e&&this._written.add(t),this._applySegmentUpdate(t,i,e),"sources"in e&&this._syncSources(),this._syncCopyAction(),("status"in e||"isStreaming"in e||"queued"in e||"deferred"in e)&&(this._syncTurns(),this._updateWaiting())}}appendToSegment(t,e){let s=this._segments.find(i=>i.id===t);s&&"content"in s&&(s.content+=e,s.isStreaming!==!1&&this._written.add(t),this._applySegmentUpdate(t,s,{content:s.content}),this._syncCopyAction())}_settleWrittenSegments(){for(let t of this._written){let e=this._segments.findIndex(r=>r.id===t),s=this._segments[e];if(!s||s.isStreaming===!1)continue;let i={...s,isStreaming:!1};this._segments[e]=i,this._applySegmentUpdate(t,i,{isStreaming:!1})}this._written.clear()}getSegments(){return[...this._segments]}removeSegment(t){let e=this._segments.findIndex(i=>i.id===t);e!==-1&&this._segments.splice(e,1),this._release(t),(this._segmentsEl?dn(this._segmentsEl,t):null)?.remove(),this._syncTurns(),this._syncSources(),this._updateWaiting(),this._syncCopyAction()}setAttachments(t){this._attachments=t,this._updateAttachments(),this._updateWaiting()}setUsage(t){this._usage=t??null,this._updateActionBar()}setStep(t){let e=typeof t=="string"&&t.trim()?t.trim():null;e!==this._step&&(this._step=e,this._updateWaiting())}setFinishReason(t){this._finishReason=t??null,this._updateFinishNote()}setContextSummary(t,e){this._contextSummary=t??null,e?.legacy!==void 0&&(this._legacyCompaction=e.legacy),this._contextSummary||(this._confirmingRestore=!1,this._isLegacyCompaction()||(this._checkpointOpen=!1)),this._updateCheckpoint()}setSiblings(t,e){this._siblingCount=t,this._siblingIndex=e,this._updateBranchPicker()}updateMessage(t){if("role"in t&&(this._role=t.role,this._updateRole()),"tokens"in t&&(this._tokens=t.tokens),"content"in t&&(this._content=t.content,this._updateContent()),"segments"in t&&this._replaceSegments(t.segments),"timestamp"in t&&this._updateTimestamp(t.timestamp),"status"in t){let e=t.status==="streaming"||t.status==="pending";this._updateStreaming(e)}"attachments"in t&&(this._attachments=t.attachments??[],this._updateAttachments(),this._updateWaiting()),"finishReason"in t&&this.setFinishReason(t.finishReason),("contextSummary"in t||"compaction"in t)&&this.setContextSummary("contextSummary"in t?t.contextSummary:this._contextSummary,"compaction"in t?{legacy:t.compaction===!0}:void 0)}_updateFinishNote(){let t=this._finishReason==="length"&&!this._streaming&&this._role!=="user",e=this.querySelector(".aparte-finish-note");if(!t){e?.remove();return}if(!e){let s=this.querySelector(".aparte-message-content");if(!s)return;e=document.createElement("div"),e.className="aparte-finish-note",s.after(e)}e.textContent=this._cfg.getLocale().responseCutOff??"Cut off at the model's length limit."}_isLegacyCompaction(){return this._legacyCompaction??this.getAttribute("data-kind")==="compaction"}_checkpointKind(){let t=this.getAttribute("data-checkpoint");return t==="pending"||t==="failed"?t:this._contextSummary?"done":this._isLegacyCompaction()?"legacy":null}_checkpointSummaryText(){return this._contextSummary?this._contextSummary.summary:this._content}_updateCheckpoint(t){let e=this.querySelector(".aparte-message");if(!e)return;let s=this._checkpointKind();e.toggleAttribute("data-superseded",this._isLegacyCompaction()&&!this._contextSummary);let i=this.querySelector(":scope > .aparte-checkpoint");if(!s){let u=i&&document.activeElement&&i.contains(document.activeElement);i?.remove(),this._checkpointDrawn="",u&&(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=Ch({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 u=d.querySelector(".aparte-checkpoint__summary");u&&(u.innerHTML=this._cfg.renderMarkdown(a))}i?i.replaceWith(d):this.prepend(d),this._checkpointDrawn=o;let h=t??c;h&&d.querySelector(`[data-checkpoint-action="${tt(h)}"]`)?.focus()}_onCheckpointClick=t=>{let e=t.target?.closest?.("[data-checkpoint-action]"),s=e?.closest(".aparte-checkpoint");if(!(!e||!s||s.parentElement!==this)&&!e.closest(".aparte-checkpoint__summary"))switch(e.getAttribute("data-checkpoint-action")){case"toggle":this._checkpointOpen=!this._checkpointOpen,this._updateCheckpoint("toggle");break;case"restore":this._confirmingRestore=!0,this._updateCheckpoint("restore-confirm");break;case"restore-cancel":this._confirmingRestore=!1,this._updateCheckpoint("restore");break;case"restore-confirm":{this._confirmingRestore=!1;let i=this.getAttribute("message-id")??void 0;Sh(this,{messageId:i,targetId:this._resolveTargetId()}),this.setContextSummary(null);break}case"retry":{let i=this._resolveTargetId(),r=this._cfg.getCompactor();r?r.compact({target:_t(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=dt(this._cfg));let e=Lt(t.type,this._cfg);if(e){let s=this._drawnAs(t,!0),i=me(Q(this._cfg,()=>e.render(t)),t);i&&(this._segmentsEl.appendChild(i),this._install(t,i,e,s))}else{let s=hi(t);this._segmentsEl.appendChild(s),this._install(t,s,void 0)}this._contentEl&&(this._contentEl.style.display="none"),this._reflectError()}_turnRole(t){if(t.type==="thinking")return"fold";if(t.type!=="tool_call")return"stop";let e=t;return this._cfg.isToolHidden(e.toolCall?.name??"")?"skip":e.status==="awaiting-approval"||e.status==="failed"||this._toolRendererFor(t)?"stop":"fold"}_turnHolding(t){let e=t?.parentElement?.parentElement;return e?.classList.contains("aparte-turn")&&e.parentElement===this._segmentsEl?e:null}_createTurn(){let t=document.createElement("details");t.className="aparte-turn aparte-accordion__item";let e=document.createElement("summary");e.className="aparte-accordion__header aparte-turn__summary";let s=document.createElement("span");s.className="aparte-turn__label";let i=document.createElement("span");i.className="aparte-turn__current";let r=document.createElement("span");r.className="aparte-accordion__icon",r.innerHTML=this._cfg.getIcon("expand"),e.append(s,i,r),e.addEventListener("click",()=>{t.dataset.touched=""});let a=document.createElement("div");return a.className="aparte-accordion__panel aparte-turn__body",t.append(e,a),t}_syncTurns(){let t=this._segmentsEl;if(!t||this._releasedWhileDetached)return;let e=this._cfg.getTurnSummary(),s=e?gh(this._segments,c=>this._turnRole(c)):[];if(s.length===0&&!t.querySelector(":scope > .aparte-turn"))return;let i=(c,d,h)=>{let u=h?h.nextSibling:c.firstChild;return d!==u&&c.insertBefore(d,u),d},r=c=>this._drawn.get(c.id)?.el,a=new Set,o=new Map(s.map(c=>[c.from,c])),l=null;for(let c=0;c<this._segments.length;c+=1){let d=o.get(c);if(!d){let _=r(this._segments[c]);_&&(l=i(t,_,l));continue}let h=this._segments.slice(d.from,d.to+1),p=h.map(_=>this._turnHolding(r(_))).find(_=>_&&!a.has(_))??this._createTurn();a.add(p),l=i(t,p,l);let f=p.querySelector(":scope > .aparte-turn__body"),g=null;for(let _ of h){let w=r(_);w&&(g=i(f,w,g))}this._labelTurn(p,h,d.to===this._segments.length-1,e?.openWhileRunning===!0),c=d.to}for(let c of t.querySelectorAll(":scope > .aparte-turn"))a.has(c)||c.remove()}_labelTurn(t,e,s,i){let r=this._cfg,a=e.filter(u=>this._turnRole(u)==="fold"),o=a.filter(u=>u.type==="tool_call"),l=this._streaming&&s||o.some(u=>!xt(u)),c=t.querySelector(":scope > summary > .aparte-turn__label"),d=t.querySelector(":scope > summary > .aparte-turn__current");c.classList.toggle("aparte-shimmer",l),c.textContent=l?r.t("turnWorking"):this._turnOutcome(a,o.length);let h=o.filter(u=>!u.queued&&u.deferred?.reason!=="queued").at(-1)??o.at(-1);d.textContent=l&&h?this._stepName(h):"",i&&!("touched"in t.dataset)&&(t.open=l)}_turnOutcome(t,e){let s=this._cfg,i=s.getLocale().tag||void 0,r=e>0?Co(s.t("turnTools"),e,i):"",a=_h(t);if(a!==void 0){let o=s.t("turnWorked").replace("{duration}",()=>Gs(a,i));return r?`${o} \xB7 ${r}`:o}return r?s.t("turnUsed").replace("{tools}",()=>r):s.t("thought")}_stepName(t){return sn(t,this._cfg).text}_applySegmentUpdate(t,e,s){let i=this._segmentsEl?dn(this._segmentsEl,t):null;if(!i){this._renderSegments();return}if(this._releasedWhileDetached)return;let r=Lt(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){Q(this._cfg,()=>r.update(i,e));let o=this._drawn.get(t);if(o){o.segment=e;let l=this._segmentsEl?dn(this._segmentsEl,t):null;l&&l!==o.el&&(o.el=l,o.tool=Io(e,l))}}else{let o=me(Q(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=Q(this._cfg,()=>r({role:this._role,name:s,avatarInitial:i}));o instanceof HTMLElement?this.replaceChildren(o):this.innerHTML=o}else this.innerHTML=`
93
+ <div class="aparte-message" data-role="${I(e)}" role="article" aria-label="${I(this._getAriaLabel())}">
94
+ <div class="aparte-avatar" data-role="${I(e)}"></div>
95
+ <div class="aparte-body">
96
+ <div class="aparte-header">
97
+ <span class="aparte-name">${P(s)}</span>
98
+ <span class="aparte-timestamp"></span>
99
+ </div>
100
+ <div class="aparte-attachments" hidden></div>
101
+ <div class="aparte-message-content">
102
+ <div class="aparte-segments"></div>
103
+ <div class="aparte-content" dir="auto"></div>
104
+ <div class="aparte-waiting" hidden>
105
+ <span class="aparte-dots" aria-hidden="true"><span class="aparte-dot"></span><span class="aparte-dot"></span><span class="aparte-dot"></span></span>
106
+ <span class="aparte-waiting-step aparte-shimmer" aria-hidden="true" dir="auto" hidden></span>
107
+ <span class="aparte-sr-only" aria-live="polite">${P(this._cfg.getLocale().typing??"")}</span>
108
+ </div>
109
+ </div>
110
+ <div class="aparte-footer">
111
+ <div class="aparte-branch-picker" hidden>
112
+ <button type="button" class="aparte-btn aparte-btn--icon aparte-btn--sm aparte-branch-prev" aria-label="${I(this._cfg.getLocale().previousResponse??"Previous response")}">${this._cfg.getIcon("prevBranch")}</button>
113
+ <span class="aparte-branch-label">1 / 1</span>
114
+ <!-- The move has to be ANNOUNCED. Pressing the arrows deliberately does not
115
+ take focus, so without a live region a screen-reader user gets the new
116
+ branch and no indication anything changed. The visible label cannot be
117
+ the region itself: a custom sibling-nav renderer may replace it with
118
+ dots, which reads as nothing. No new locale key \u2014 the position is
119
+ digits, and the buttons beside it already carry translated labels. -->
120
+ <span class="aparte-sr-only aparte-branch-status" aria-live="polite"></span>
121
+ <button type="button" class="aparte-btn aparte-btn--icon aparte-btn--sm aparte-branch-next" aria-label="${I(this._cfg.getLocale().nextResponse??"Next response")}">${this._cfg.getIcon("nextBranch")}</button>
122
+ </div>
123
+ <div class="aparte-action-bar" role="toolbar" aria-label="${I(this._cfg.getLocale().messageActions??"Message actions")}"></div>
124
+ </div>
125
+ </div>
126
+ </div>
127
+ `;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=h=>{let u="",p=h.ownerDocument.createTreeWalker(h,NodeFilter.SHOW_TEXT);for(let f=p.nextNode();f;f=p.nextNode()){let g=f.parentElement?.closest('[aria-hidden="true"], [hidden]');(!g||!h.contains(g))&&(u+=f.textContent??"")}return u},d=h=>!!h&&(h.hasAttribute("aria-label")||h.hasAttribute("aria-labelledby")||h.hasAttribute("title")||/\p{L}/u.test(c(h)));if((o||l)&&!d(o)&&!d(l)){let h=this._cfg.getLocale();o?.setAttribute("aria-label",h.previousResponse??"Previous response"),l?.setAttribute("aria-label",h.nextResponse??"Next response"),this._wroteArrowLabels=!0}}this._actionBarEl?.addEventListener("keydown",this._onActionBarKeydown),this._branchPickerEl=this.querySelector(".aparte-branch-picker"),this._footerEl=this.querySelector(".aparte-footer"),this._transcriptBusy=!!this.closest("aparte-chat-viewport")?.hasAttribute("data-busy"),this._updateActionBar(),this._renderAvatar(),this._streaming&&this._updateStreaming(!0),this._updateWaiting(),this._updateFinishNote(),this._updateCheckpoint()}_updateWaiting(){let e=!(this._segmentsEl?Array.from(this._segmentsEl.children).some(g=>!g.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"&&(xt(s)||i?.hidden===!0)&&i?.classList.contains("aparte-turn")!==!0,o=this._streaming&&this._role!=="user"&&!r&&(e||a),l=this.querySelector(".aparte-message-content");l&&(l.hidden=e&&!o);let c=this.querySelector(".aparte-message");c&&c.toggleAttribute("data-empty",e&&!this._streaming&&this._attachments.length===0);let d=this.querySelector(".aparte-waiting");if(!d)return;d.hidden=!o;let h=o&&this._step?this._cfg.getStepLabel(this._step)??this._step:null,u=d.querySelector(".aparte-waiting-step");if(!u&&h){u=document.createElement("span"),u.className="aparte-waiting-step aparte-shimmer",u.setAttribute("aria-hidden","true"),u.dir="auto";let g=d.querySelector(".aparte-dots");g?g.after(u):d.prepend(u)}if(u&&(u.hidden=!h,h&&u.textContent!==h&&(u.textContent=h)),!o)return;let p=h??this._cfg.getLocale().typing,f=d.querySelector(".aparte-sr-only");f&&f.textContent!==p&&(f.textContent=p)}_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){we.delete(t),t.removeAttribute("data-image");return}we.size===0&&queueMicrotask(kh),we.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=dt(this._cfg),this._contentEl.style.display="",Q(this._cfg,()=>Yt(this,this._contentEl,this._content,this._streaming)),this._drawTokens(),this._updateWaiting(),this._streaming||this._highlightContentCode()}}_highlightContentCode(){!this._contentEl||!this._cfg.hasHighlightProvider()||this._contentEl.querySelectorAll("pre > code:not([data-aparte-highlighted])").forEach(t=>{let e=t.textContent??"";if(!e.trim())return;let i=t.className.match(/language-([\w+#-]+)/i)?.[1]??"";if(this._cfg.hasCodeLanguageRenderer(i)||t.closest(".aparte-code-drawing"))return;let r=t.parentElement;t.setAttribute("data-aparte-highlighted",""),Promise.resolve(this._cfg.highlightCode(e,i,{fallback:!1})).then(a=>{let o=(a??"").trim();!o||!r||!this._contentEl?.contains(r)||(/^<pre[\s>]/i.test(o)?zs(r,o):t.innerHTML=o)}).catch(()=>{t.removeAttribute("data-aparte-highlighted")})})}_renderSegments(){if(this._segmentsEl){this._drawnWithVersion=dt(this._cfg),this._releaseAll(),this._segmentsEl.innerHTML="";for(let t of this._segments){let e=Lt(t.type,this._cfg);if(e){let s=this._drawnAs(t),i=me(Q(this._cfg,()=>e.render(t)),t);i&&(this._segmentsEl.appendChild(i),this._install(t,i,e,s))}else{let s=hi(t);this._segmentsEl.appendChild(s),this._install(t,s,void 0)}}this._syncTurns(),this._contentEl&&(this._contentEl.style.display=this._segments.length>0?"none":""),this._reflectError(),this._syncCopyAction(),this._syncSources()}}_reflectError(){let t=this.querySelector(".aparte-message");if(!t)return;this._segments.some(s=>s.type==="error")?t.setAttribute("data-error",""):t.removeAttribute("data-error")}_updateTimestamp(t){let e=this.querySelector(".aparte-timestamp");if(!(!e||!t))try{let s=new Date(isNaN(Number(t))?t:Number(t));e.textContent=s.toLocaleTimeString(this._cfg.getLocale().tag||void 0,{hour:"2-digit",minute:"2-digit"})}catch{e.textContent=""}}_getAriaLabel(){let t=this._cfg.getLocale(),e=this.getAttribute("name");return e?(t.messageFrom||"Message from {name}").replace("{name}",()=>e):this._role==="user"?t.yourMessage??"Your message":t.assistantResponse??"Assistant response"}_updateAttachments(){if(!this._attachmentsEl)return;if(this._role!=="user"||this._attachments.length===0){this._attachmentsEl.hidden=!0,this._attachmentsEl.innerHTML="";return}this._attachmentsEl.hidden=!1;let t=this._cfg.getAttachmentRenderer?.();if(t){this._attachmentsEl.replaceChildren();for(let r of this._attachments){let a=me(Q(this._cfg,()=>t(r)));a&&this._attachmentsEl.appendChild(a)}return}this._attachmentsEl.innerHTML=this._attachments.map(r=>{let a=P(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="${P(r.type)}"><img class="aparte-thumbnail__image" src="${P(r.url)}" alt="${a}" loading="lazy" /><span class="aparte-thumb__name">${a}</span></div>`;let o=this._isOpenableUrl(r.url)?` data-url="${P(r.url)}"`:"";return`<div class="aparte-thumbnail aparte-thumb aparte-thumb--file" title="${a}" data-type="${P(r.type)}"${o}><span class="aparte-thumbnail__label">${P(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?ge(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=Q(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"&&t.type!=="activity").map(t=>t.content??"").join(`
128
+ `)).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="${I(i)}" title="${I(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="${I(i)}" title="${I(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="${I(i)}" title="${I(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="${I(i)}" title="${I(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="${I(i)}" title="${I(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="${I(i)}" title="${I(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="${I(e)}" title="${I(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="${I(s)}" title="${I(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();Ks(r).then(()=>{e.innerHTML=a.check(),e.setAttribute("data-copied","");let l=o.copied??o.copy??"Copied";e.setAttribute("title",l),e.setAttribute("aria-label",l),setTimeout(()=>{e.removeAttribute("data-copied"),e.innerHTML=a.copy();let c=o.copy??"Copy";e.setAttribute("title",c),e.setAttribute("aria-label",c)},2e3)}).catch(()=>{console.warn("[aparte] Clipboard write failed")});break}case"retry":{if(!i)break;let r=this._resolveTargetId(),a={messageId:i,targetId:r};this.dispatchEvent(new CustomEvent("aparte-retry",{bubbles:!0,composed:!0,detail:a}));break}case"edit":{this._enterEditMode();break}case"edit-save":{this._exitEditMode(!0);break}case"edit-cancel":{this._exitEditMode(!1);break}case"feedback-positive":case"feedback-negative":{if(!i)break;let r=s==="feedback-positive"?"positive":"negative";e.setAttribute("data-submitted","");let a={messageId:i,value:r};this.dispatchEvent(new CustomEvent("aparte-feedback",{bubbles:!0,composed:!0,detail:a})),r==="negative"?this._askFeedbackReason(i):this.querySelector(".aparte-feedback-reasons")?.remove();break}case"info":{if(!i)break;let r={messageId:i,usage:this._usage??void 0};this.dispatchEvent(new CustomEvent("aparte-message-info",{bubbles:!0,composed:!0,detail:r}));break}}}_enterEditMode(){if(this._editing||!this._contentEl)return;let t=document.activeElement;this._editReturnAction=t instanceof HTMLElement&&this.contains(t)?t.getAttribute("data-action")??"edit":null,this._editing=!0,this.querySelector(".aparte-message")?.setAttribute("data-editing","");let e=document.createElement("aparte-composer-input");e.setAttribute("placeholder",this._cfg.getLocale().edit??"Edit message"),this._editInput=e,this._contentEl.style.display="none",this._contentEl.insertAdjacentElement("afterend",e),e.setValue(this._content),e.addEventListener("aparte-composer-submit",()=>this._exitEditMode(!0)),e.addEventListener("keydown",s=>{s.key==="Escape"&&!s.isComposing&&(s.preventDefault(),this._exitEditMode(!1))}),this._updateActionBar(),e.focusEnd()}_exitEditMode(t){if(!this._editing)return;let e=this._editInput?.getValue()??"",s=this._content;this._editInput?.remove(),this._editInput=null,this._contentEl&&(this._contentEl.style.display=""),this.querySelector(".aparte-message")?.removeAttribute("data-editing"),this._editing=!1,this._redrawFrameIfChanged(),this._redrawIfStale(),this._updateActionBar();let i=this._editReturnAction;if(this._editReturnAction=null,i&&this._actionBarEl){let r=Array.from(this._actionBarEl.querySelectorAll("[data-action]")).find(o=>o.getAttribute("data-action")===i),a=r&&!r.disabled?r:this._actionBarEl.querySelector("button:not([disabled])");if(a){for(let o of this._rovingButtons())o.tabIndex=o===a?0:-1;a.focus()}}if(t&&e&&e!==s){let r=this.getAttribute("message-id");if(r){let a={messageId:r,content:e,targetId:this._resolveTargetId()};this.dispatchEvent(new CustomEvent("aparte-edit",{bubbles:!0,composed:!0,detail:a}))}}}_resolveTargetId(){let t=this.parentElement;for(;t;){if((t.tagName?.toLowerCase()==="aparte-chat"||t.hasAttribute?.("data-aparte-chat"))&&t.id)return t.id;t=t.parentElement}}_updateStreaming(t){let e=this._streaming;this._streaming=t,t||(this._step=null);let s=this.querySelector(".aparte-message");s&&(s.setAttribute("data-streaming",String(t)),t?(s.setAttribute("aria-busy","true"),s.classList.add("aparte-message-streaming")):(s.removeAttribute("aria-busy"),s.classList.remove("aparte-message-streaming")),s.toggleAttribute("data-caret",t&&this._cfg.getStreamingCaret())),this._updateWaiting(),this._updateFinishNote(),e&&!t&&this._updateContent(),e&&!t&&this._settleWrittenSegments(),e&&!t&&this._segments.length>0&&this._redrawIfStale(),this._syncTurns(),t||this._dropStreamingAttribute()}_dropStreamingAttribute(){let t=this.getAttribute("streaming");if(!(t===null||t==="false")){this._clearingStreamingAttr=!0;try{this.removeAttribute("streaming")}finally{this._clearingStreamingAttr=!1}}}};G(vn);customElements.get("aparte-chat-bubble")||customElements.define("aparte-chat-bubble",vn);var yn=class extends HTMLElement{static get observedAttributes(){return["visible","text"]}get _cfg(){return L(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=Q(this._cfg,()=>s(t));r instanceof HTMLElement?i.appendChild(r):i.innerHTML=r;return}this.innerHTML=`
129
+ <div
130
+ class="aparte-message aparte-status-container"
131
+ data-visible="${e}"
132
+ role="status"
133
+ aria-live="polite"
134
+ >
135
+ <div class="aparte-avatar" data-role="assistant" style="visibility: hidden"></div>
136
+ <div class="aparte-body">
137
+ <div class="aparte-status-content">
138
+ <div class="aparte-dots" aria-hidden="true">
139
+ <span class="aparte-dot"></span>
140
+ </div>
141
+ <span class="aparte-status-text"></span>
142
+ <span class="aparte-sr-only aparte-status-sr"></span>
143
+ </div>
144
+ </div>
145
+ </div>
146
+ `,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=Q(this._cfg,()=>s(i));r instanceof HTMLElement?e.replaceChildren(r):e.innerHTML=r;return}this._writeText(t),e.setAttribute("aria-label",t||this._word())}};G(yn);customElements.get("aparte-chat-status")||customElements.define("aparte-chat-status",yn);function Oo(n,t){if(n.role!=="assistant"||n.segments?.length||typeof n.content!="string"||!n.content.trim())return n;let e=Kr(n.content,{blocks:t});return e.length<=1&&e.every(i=>i.type==="text")?n:bi({...n,segments:e})}function bi(n){return Object.defineProperty(n,ri,{value:!0,enumerable:!1}),n}function Po(n){return n[ri]===!0}function xh(n,t){try{return new Intl.DateTimeFormat(t||void 0,{dateStyle:"long"}).format(n)}catch{return n.toDateString()}}var wn=class extends HTMLElement{_container=null;_scrollBtn=null;_bottomSpacer=null;_fwSpacerHeight=0;_spacerRafId=null;_spacerFrozenUntil=0;_layoutTransitionMs=0;_repo=new Je;_isAutoScrollEnabled=!0;_lastScrollTop=0;_lastScrollHeight=0;_lastMutationAt=Number.NEGATIVE_INFINITY;_settleShadowMs=100;_settleBoundPx=100;_ownScrollAt=Number.NEGATIVE_INFINITY;_readerInputAt=Number.NEGATIVE_INFINITY;_ownScrollWindowMs=1e3;_settleWindowMs=400;_glideUntil=0;_glideWindowMs=450;_glideSettleTimer=null;_settleUntil=0;_settleRafId=null;_scrollKeys=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," "]);_scrollThreshold=50;_smoothScrollOnce=!1;_maxRenderedBubbles=1e3;_resizeObserver=null;_mutationObserver=null;_tailObserver=null;_tail=[];_tailHeights=new WeakMap;_onDisclosureToggle=()=>{this._scheduleSpacerUpdate()};_overlayRoot=null;_overlayObserver=null;_overlayAttrObserver=null;_overlayInset=-1;_transcriptInset=-1;_boundResetHandler=null;_checkpointState=null;_stopCheckpointState=null;_frameworkManagedDOM=!1;_bulkAppend=!1;static get observedAttributes(){return["scroll-threshold","max-rendered-bubbles","loading"]}get loading(){return this.hasAttribute("loading")}set loading(t){this.toggleAttribute("loading",J(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=L(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 Qe({ownId:()=>uo(this)??(this.id||void 0),bubbleOf:t=>this.querySelector(`aparte-chat-bubble[message-id="${tt(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!==L(this))return;this._applyDirection(),this._scrollBtn?.setAttribute("aria-label",L(this).t("scrollToBottom")),(this._frameworkManagedDOM?this:this.querySelector(".aparte-viewport-container"))?.setAttribute("aria-label",L(this).t("transcript")),this._syncDateSeparators()};_nameScrollSurface(t){t.setAttribute("tabindex","0"),t.hasAttribute("role")||t.setAttribute("role","log"),t.setAttribute("aria-label",L(this).t("transcript"))}_applyDirection(){let t=this._frameworkManagedDOM?this:this.querySelector(".aparte-viewport-container");if(!t)return;let e=L(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,...Qr(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=Ns(r.segments,i,s,L(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],h=Vr(d,o);l.segments[c]=Ds(d,h),this._notifyBubble(r,"updateSegment",{segmentId:a,updates:h})}}removeSegment(t,e){let s=e===void 0,i=s?this._activeMessageId():t,r=s?t:e;if(!i||!r)return;let a=this._repo.getMessageById(i);if(a?.segments){let o=a.segments.findIndex(l=>l.id===r);o!==-1&&(a.segments.splice(o,1),Jr(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)}setStep(t,e){this._notifyBubble(t,"setStep",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 Xr(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",Bs(e.status)&&this._settleSegments(t,s)),this._notifyBubble(t,"update",e),e.status&&this._syncBusy(),this._autoScroll())}addMessage(t){let e=en({...t});Qt(t)&&(e.isStreaming=!0),this._repo.addOrUpdateMessage(this._repo.headId,e),this._pruneRenderedBubbles(),this._syncBusy(),this._autoScroll()}appendMessage(t,e){t=Oo(t,L(this).getStreamBlocks());let s=e?.historical?en(t):t.segments?.length?{...t,segments:t.segments.reduce((i,r)=>(i.push(Ns(i,r,t.id,L(this).getSegmentDefaults(r.type))),i),[])}:{...t};if(!e?.historical&&Qt(t)&&(s.isStreaming=!0),Po(t)&&bi(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),Qt(t)&&r.setAttribute("streaming",""),this._bottomSpacer&&this._bottomSpacer.parentNode===i?i.insertBefore(r,this._bottomSpacer):i.appendChild(r),ii(r,s)}}this._bulkAppend||(this._pruneRenderedBubbles(),this._syncBusy(),t.role==="user"&&(this._isAutoScrollEnabled=!0,this._smoothScrollToBottom()),this._recalculateSpacer(),t.role==="user"?requestAnimationFrame(()=>{this._isAutoScrollEnabled&&this._smoothScrollToBottom()}):this._autoScroll())}updateLastMessage(t,e){let s=this._repo.headId;if(s)if(e?.append)this.appendToken(s,t);else{let i=this._repo.getMessageById(s);i&&(i.content=t),this._notifyBubble(s,"appendToken",t)}}addBranch(t){let e=this._repo.getMessage(t);if(!e)return 0;let s={id:X(),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 Qt(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="${tt(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="${tt(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=L(this).getStreamBlocks();this._repo.import({...t,messages:t.messages.map(s=>{let i=Oo(s.message,e),r=en(i);return Po(i)&&bi(r),{...s,message:r}})}),this._reRenderActivePath()}clearAll(t){if(t?.revokeAttachments!==!1)for(let e of this._repo.getAllMessages())oo(e.attachments);if(this._repo.clear(),this._syncBusy(),!this._frameworkManagedDOM){let e=this.querySelector(".aparte-messages-wrapper");e&&Array.from(e.querySelectorAll("aparte-chat-bubble")).forEach(s=>s.remove())}this._setSpacerHeight(0),this._isAutoScrollEnabled=!0,this._updateScrollButton(),this._checkpointState?.clear(),this.dispatchEvent(new CustomEvent("aparte-reset-done",{bubbles:!0,composed:!0}))}setMessages(t){this.clearAll({revokeAttachments:!1}),this._bulkAppend=!0;try{for(let e of t)this.appendMessage(e,{historical:!0})}finally{this._bulkAppend=!1}this._pruneRenderedBubbles(),this._syncBusy(),t.some(e=>e.role==="user")&&(this._isAutoScrollEnabled=!0),this._recalculateSpacer(),this._autoScroll()}scrollToBottom(){this._scrollToBottom()}resetSpacer(){this._setSpacerHeight(0),this._layoutTransitionMs>0&&(this._spacerFrozenUntil=Date.now()+this._layoutTransitionMs)}setAutoScroll(t){this._isAutoScrollEnabled=t,t||(this._readerInputAt=performance.now())}setFrameworkManagedDOM(t){this._frameworkManagedDOM=t}_getOrCreateMessage(t){let e=this._repo.getMessageById(t);if(e)return e;let s={id:t,role:"assistant",content:"",timestamp:Date.now(),isStreaming:!0,status:"streaming"};return this._repo.addOrUpdateMessage(this._repo.headId,s),s}_notifyBubble(t,e,s,i){let r=this.querySelector(`aparte-chat-bubble[message-id="${tt(t)}"], [data-aparte-bubble][message-id="${tt(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"setStep":r.setStep?.(s);break;case"update":{let a=s;["status","segments","content","attachments","usage","finishReason","contextSummary","compaction"].some(l=>l in a)&&r.updateMessage?.(s);break}case"complete":r.updateMessage?.(s);break}}_syncDateSeparators(){let t=L(this),e=t.getDateSeparators();if(!e&&!this.querySelector("aparte-chat-bubble[data-date]"))return;let s=new Date,i=o=>new Date(o.getFullYear(),o.getMonth(),o.getDate()).getTime(),r=i(s),a=null;this.querySelectorAll("aparte-chat-bubble").forEach(o=>{let l=Number(o.getAttribute("timestamp")),c=l?new Date(l):null,d=c?i(c):null,h=e&&c&&d!==a;if(d!==null&&(a=d),!h||!c){o.hasAttribute("data-date")&&o.removeAttribute("data-date");return}let u=Math.round((r-d)/864e5),p=u===0?t.t("conversationGroupToday"):u===1?t.t("conversationGroupYesterday"):xh(c,t.getLocale().tag);o.getAttribute("data-date")!==p&&o.setAttribute("data-date",p)})}_reRenderActivePath(){let t=this._repo.getMessages(),e=t.map(r=>{let a=this._repo.getBranches(r.id);return{id:r.id,count:a.length,index:a.indexOf(r.id)}});if(this._frameworkManagedDOM){this._dispatchPathChanged(t,e);return}let s=this.querySelector(".aparte-messages-wrapper");if(!s)return;s.innerHTML="";let i=Math.max(0,t.length-this._maxRenderedBubbles);for(let r=i;r<t.length;r++){let a=t[r],o=e[r],l=document.createElement("aparte-chat-bubble");l.setAttribute("message-id",a.id),l.setAttribute("data-role",a.role),a.compaction&&l.setAttribute("data-kind","compaction"),a.timestamp&&l.setAttribute("timestamp",String(a.timestamp)),Qt(a)&&l.setAttribute("streaming",""),s.appendChild(l),ii(l,a,o)}this._syncDateSeparators(),this._dispatchPathChanged(t,e),this._syncBusy(),this._checkpointState?.reapply(),this._recalculateSpacer()}_dispatchPathChanged(t,e){let s={messages:t,siblings:e};this.dispatchEvent(new CustomEvent("aparte-path-changed",{bubbles:!0,composed:!0,detail:s}))}_autoScroll(){this._isAutoScrollEnabled&&requestAnimationFrame(()=>{this._isAutoScrollEnabled&&this._scrollToBottom()}),this._pruneRenderedBubbles()}requestSmoothScroll(){this._smoothScrollOnce=!0}_render(){if(this._frameworkManagedDOM){this._setupFrameworkDOM();return}if(this.querySelector(".aparte-viewport-container"))this._container=this.querySelector(".aparte-viewport-container"),this._scrollBtn=this.querySelector(".aparte-scroll-btn"),this._bottomSpacer=this.querySelector(".aparte-bottom-spacer");else{let t=document.createElement("div");t.className="aparte-viewport-container";let e=L(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",L(this).t("scrollToBottom"));let i=L(this).getIcon("scrollDown");this._scrollBtn.innerHTML=i,this.appendChild(this._scrollBtn)}}_setupFrameworkDOM(){if(this._container=this,this._bottomSpacer=null,this.classList.contains("aparte-viewport--framework")){this._scrollBtn=this.querySelector(":scope > .aparte-scroll-btn");return}this.classList.add("aparte-viewport--framework"),this._nameScrollSurface(this),this._applyDirection();let t=document.createElement("button");t.className="aparte-btn aparte-btn--surface aparte-btn--circle aparte-btn--lg aparte-scroll-btn aparte-scroll-btn--hidden",t.setAttribute("type","button"),t.setAttribute("aria-label",L(this).t("scrollToBottom"));let e=L(this).getIcon("scrollDown");t.innerHTML=e,this.appendChild(t),this._scrollBtn=t}_keepScrollButtonLast(){this._scrollBtn&&this.lastElementChild!==this._scrollBtn&&this.appendChild(this._scrollBtn)}_getSpacerHeight(){return this._frameworkManagedDOM?this._fwSpacerHeight:this._bottomSpacer?.offsetHeight??0}_setSpacerHeight(t){this._frameworkManagedDOM?(this._fwSpacerHeight=t,this.style.setProperty("--aparte-fw-spacer",`${t}px`)):this._bottomSpacer&&(this._bottomSpacer.style.height=`${t}px`)}_onScrollBtnClick=()=>{this._isAutoScrollEnabled=!0,this._smoothScrollToBottom(),this._updateScrollButton()};_pointerHeld=!1;_holdPointer=()=>{this._pointerHeld=!0};_releasePointer=()=>{this._pointerHeld=!1};_noteReaderInput=t=>{if(!(t.type==="keydown"&&!this._scrollKeys.has(t.key))){if(t.type==="pointerdown"){let e=this._container;if(!e)return;let{clientX:s}=t,i=e.getBoundingClientRect();if(!(getComputedStyle(e).direction==="rtl"?s<=i.right-e.clientWidth:s>=i.left+e.clientWidth))return}if(this._readerInputAt=performance.now(),this._gliding()&&this._container&&(this._glideUntil=0,t.type==="wheel"||t.type==="touchmove")){this._ownScrollAt=performance.now();let e=this._container.scrollTop;this._container.scrollTop=e}}};_onBranchNavigate=t=>{let e=t;e.stopPropagation(),this.navigateBranch(e.detail.messageId,e.detail.direction)};_setupEventListeners(){this._container?.addEventListener("scroll",this._handleScroll,{passive:!0}),this._container?.addEventListener("scrollend",this._handleScrollEnd,{passive:!0});for(let t of["wheel","touchmove","pointerdown","keydown"])this._container?.addEventListener(t,this._noteReaderInput,{passive:!0});this._container?.addEventListener("pointerdown",this._holdPointer,{passive:!0}),document.addEventListener("pointerup",this._releasePointer,!0),document.addEventListener("pointercancel",this._releasePointer,!0),this._scrollBtn?.addEventListener("click",this._onScrollBtnClick),this.addEventListener("aparte-branch-navigate",this._onBranchNavigate)}_setupObservers(){this._resizeObserver=new ResizeObserver(()=>{this._updateOverlayInset(),this._updateTranscriptInset(),this._isAutoScrollEnabled&&this._scrollToBottom(),this._recalculateSpacer(),this._updateScrollButton()});let t=this.querySelector(".aparte-messages-wrapper");this._container&&(this._frameworkManagedDOM?this._resizeObserver.observe(this._container,{box:"border-box"}):this._resizeObserver.observe(this._container)),this._wireOverlay(),this.parentElement&&(this._overlayAttrObserver=new MutationObserver(()=>this._wireOverlay()),this._overlayAttrObserver.observe(this.parentElement,{attributes:!0,attributeFilter:["overlay-composer"]})),this._mutationObserver=new MutationObserver(s=>{if(this._lastMutationAt=performance.now(),s.some(r=>r.type==="childList"&&(r.target===this||r.target.classList?.contains("aparte-messages-wrapper")))&&this._syncDateSeparators(),this._frameworkManagedDOM&&this._keepScrollButtonLast(),this._isAutoScrollEnabled&&!this._gliding()){let r=s.flatMap(o=>Array.from(o.addedNodes)).filter(o=>o instanceof Element&&o.tagName==="APARTE-CHAT-BUBBLE"),a=r.length===1?r[0]:void 0;if(a&&a.getAttribute("data-role")==="user"&&a.parentElement){let o=a.parentElement.querySelectorAll("aparte-chat-bubble");o[o.length-1]===a&&(this._smoothScrollOnce=!0)}}this._isAutoScrollEnabled&&requestAnimationFrame(()=>{this._isAutoScrollEnabled&&this._scrollToBottom()}),this._scheduleSpacerUpdate();let i=r=>Array.from(r).some(a=>a instanceof Element&&(a.tagName==="APARTE-CHAT-BUBBLE"||a.querySelector("aparte-chat-bubble")!==null));s.some(r=>i(r.addedNodes)||i(r.removedNodes))&&this._observeTail()}),this._tailObserver=new ResizeObserver(s=>{let i=!1;for(let r of s){let a=Math.round(r.borderBoxSize?.[0]?.blockSize??r.contentRect.height);this._tailHeights.get(r.target)!==a&&(i=!0),this._tailHeights.set(r.target,a)}i&&this._scheduleSpacerUpdate()}),this._observeTail(),this.addEventListener("toggle",this._onDisclosureToggle,!0);let e=this._frameworkManagedDOM?this:t;e&&this._mutationObserver.observe(e,{childList:!0,subtree:!0})}_wireOverlay(){let t=this.closest("[overlay-composer]");if(t!==this._overlayRoot){for(let e of this._overlayStack())this._resizeObserver?.unobserve(e);if(this._overlayObserver?.disconnect(),this._overlayObserver=null,this._overlayRoot=t,this._overlayInset=-1,this.style.removeProperty("--aparte-bottom-inset"),!(!t||!this._resizeObserver)){for(let e of this._overlayStack())this._resizeObserver.observe(e);this._overlayObserver=new MutationObserver(()=>{for(let e of this._overlayStack())this._resizeObserver?.observe(e);this._updateOverlayInset()}),this._overlayObserver.observe(t,{childList:!0}),this._updateOverlayInset()}}}_overlayStack(){return this._overlayRoot?Array.from(this._overlayRoot.children).filter(t=>t instanceof HTMLElement&&t!==this&&t.tagName.toLowerCase()!=="aparte-scroll-rail"):[]}_updateOverlayInset(){if(!this._overlayRoot)return;let t=this.getBoundingClientRect().bottom,e=1/0;for(let i of this._overlayStack()){let r=i.getBoundingClientRect();r.height>0&&(e=Math.min(e,r.top))}let s=e===1/0?0:Math.max(0,Math.round(t-e));s!==this._overlayInset&&(this._overlayInset=s,this.style.setProperty("--aparte-bottom-inset",`${s}px`))}_updateTranscriptInset(){let t=this.parentElement;if(!t)return;let e=this.querySelector(".aparte-messages-wrapper")??this._container??this,s=parseFloat(getComputedStyle(e).paddingInlineStart)||0,i=getComputedStyle(t).direction==="rtl",r=e.getBoundingClientRect(),a=t.getBoundingClientRect(),o=i?a.right-r.right:r.left-a.left,l=Math.max(0,Math.round((o+s)*10)/10);l!==this._transcriptInset&&(this._transcriptInset=l,t.style.setProperty("--aparte-transcript-inset",`${l}px`))}_isAtBottom(){if(!this._container)return!0;let{scrollTop:t,scrollHeight:e,clientHeight:s}=this._container;return e-t-s<=this._scrollThreshold}_handleScroll(){if(!this._container)return;let t=this._container.scrollTop,e=this._container.scrollHeight,s=this._lastScrollTop-t,i=Math.abs(e-this._lastScrollHeight),r=performance.now(),a=e<this._lastScrollHeight-1,o=r-this._lastMutationAt<this._settleShadowMs&&s<=this._settleBoundPx,l=r-this._ownScrollAt<this._ownScrollWindowMs&&r-this._readerInputAt>=this._ownScrollWindowMs&&!this._pointerHeld&&(s<=i+2||a||o),c=s>1&&!l,d=s>1&&r-this._readerInputAt<this._ownScrollWindowMs;this._lastScrollTop=t,this._lastScrollHeight=e,this._isAtBottom()&&!d?this._isAutoScrollEnabled=!0:c?this._isAutoScrollEnabled=!1:s>1&&l&&this._isAutoScrollEnabled&&this._settleAtBottom(),this._updateScrollButton()}_scrollToBottom(){if(this._container){if(this._fitsOnceCentred()){this._smoothScrollOnce=!1,this._gliding()&&(this._glideUntil=0,this._ownScrollAt=performance.now(),this._container.scrollTop=0);return}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()}}_fitsOnceCentred(){if(!this._container)return!1;let t=this._centringRoom();return t>0&&this._container.scrollHeight-this._getSpacerHeight()<=this._container.clientHeight+t}_centringRoom(){let t=this.closest("aparte-chat[center-empty], .aparte-chat-container--auto-center");return t&&parseFloat(getComputedStyle(t,"::after").height)||0}_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(u=>u.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._centringRoom()){this._setSpacerHeight(0);return}let l=o-a,c=parseFloat(getComputedStyle(this._container).scrollPaddingTop)||0,d=this._container.clientHeight-c-l,h=this._container.clientHeight;this._setSpacerHeight(Math.min(Math.max(0,d),h)),this._isAutoScrollEnabled&&this._scrollToBottom()}_observeTail(){if(!this._tailObserver)return;let t=Array.from(this.querySelectorAll("aparte-chat-bubble")),e=t.length;for(;e>0&&t[e-1].getAttribute("data-role")!=="user";)e--;let s=e>0?t.slice(e-1):[];for(let i of this._tail)s.includes(i)||this._tailObserver.unobserve(i);for(let i of s)this._tail.includes(i)||(this._tailHeights.set(i,Math.round(i.offsetHeight)),this._tailObserver.observe(i,{box:"border-box"}));this._tail=s}_scheduleSpacerUpdate(){this._spacerRafId===null&&(this._spacerRafId=requestAnimationFrame(()=>{this._spacerRafId=null,this._recalculateSpacer(),this._updateScrollButton()}))}_pruneRenderedBubbles(){if(this._frameworkManagedDOM)return;let t=this.querySelector(".aparte-messages-wrapper");if(!t)return;let e=t.querySelectorAll("aparte-chat-bubble"),s=e.length-this._maxRenderedBubbles;for(let i=0;i<s;i++)e[i]?.remove()}_cleanup(){this._container?.removeEventListener("scroll",this._handleScroll),this._container?.removeEventListener("scrollend",this._handleScrollEnd),this._glideSettleTimer!==null&&(clearTimeout(this._glideSettleTimer),this._glideSettleTimer=null);for(let t of["wheel","touchmove","pointerdown","keydown"])this._container?.removeEventListener(t,this._noteReaderInput);this._container?.removeEventListener("pointerdown",this._holdPointer),document.removeEventListener("pointerup",this._releasePointer,!0),document.removeEventListener("pointercancel",this._releasePointer,!0),this._pointerHeld=!1,this._scrollBtn?.removeEventListener("click",this._onScrollBtnClick),this.removeEventListener("aparte-branch-navigate",this._onBranchNavigate),this._resizeObserver?.disconnect(),this._mutationObserver?.disconnect(),this._tailObserver?.disconnect(),this._tailObserver=null,this._tail=[],this.removeEventListener("toggle",this._onDisclosureToggle,!0),this._overlayObserver?.disconnect(),this._overlayObserver=null,this._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}};G(wn);customElements.get("aparte-chat-viewport")||customElements.define("aparte-chat-viewport",wn);var Mh=["input","textarea","select",'[contenteditable]:not([contenteditable="false"])','[role="textbox"]','[role="searchbox"]','[role="combobox"]','[role="listbox"]','[role="menu"]','[role="menubar"]','[role="tree"]','[role="grid"]'].join(", "),Lh="aparte-chat, [data-aparte-chat]";function Ih(n){let t=n.getAttribute("type-to-focus");return t==="page"||t==="off"?t:"chat"}function Rh(n){if(n.defaultPrevented||n.isComposing)return!1;let t=n.getModifierState?.("AltGraph")===!0;return(n.ctrlKey||n.metaKey||n.altKey)&&!t?!1:n.key==="Dead"?!0:n.key.length===1&&n.key!==" "}function Oh(n){let t=n.activeElement;for(;t?.shadowRoot?.activeElement;)t=t.shadowRoot.activeElement;return t}function Ph(n){let t=n.ownerDocument,e=!1,s=()=>{let a=n.getAttribute("target"),o=n.closest(Lh)??(a?t.getElementById(a):null);return o?[o,n]:[n]},i=a=>{let o=a.composedPath();e=s().some(l=>o.includes(l))},r=a=>{let o=Ih(n);if(o==="off"||!Rh(a)||n.hasAttribute("disabled"))return;let l=n.querySelector("aparte-composer-input");if(!l||l.hasAttribute("disabled"))return;let c=Oh(t);if(!c?.closest(Mh)){if(o==="chat"){let d=!c||c===t.body||c===t.documentElement;if(!(!d&&s().some(u=>u.contains(c)))&&!(d&&e))return}l.focusEnd?.()}};return t.addEventListener("pointerdown",i,!0),t.addEventListener("keydown",r),()=>{t.removeEventListener("pointerdown",i,!0),t.removeEventListener("keydown",r)}}var Nh=new Set(["text","search","email","url","tel","number","password"]);function Dh(n){return n instanceof HTMLTextAreaElement?n.rows===1:n instanceof HTMLInputElement&&Nh.has(n.type)}var An=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 L(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??L(this)).getLocale().direction;t?this.setAttribute("dir",t):this.removeAttribute("dir")}static get observedAttributes(){return["placeholder","disabled","target"]}_offTypeToFocus=null;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(),this._offTypeToFocus?.(),this._offTypeToFocus=Ph(this)}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(),this._offTypeToFocus?.(),this._offTypeToFocus=null}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",J(t))}get submitOnEnter(){return this.getAttribute("submit-on-enter")!=="false"}get attachments(){return this._attachments}get placeholder(){return this.getAttribute("placeholder")??""}set placeholder(t){t==null?this.removeAttribute("placeholder"):this.setAttribute("placeholder",String(t))}get targetId(){return this.getAttribute("target")}getState(){return{value:this._value,streaming:this._streaming,disabled:this.disabled,attachments:[...this._attachments],panelActive:this._panelActive,submitEnabled:this._panelSubmitEnabled}}setValue(t){this._value=t,this._emit("value-change",{value:t})}addAttachments(t){this._attachments=[...this._attachments,...Array.from(t)],this._emit("attachments-change",{attachments:this._attachments})}setAttachmentState(t,e){e?this._attachmentStates.set(t,e):this._attachmentStates.delete(t),this._syncUploading(),this.querySelector("aparte-composer-attachments")?.showState(t,e)}getAttachmentState(t){return this._attachmentStates.get(t)}_attachmentStates=new WeakMap;get _uploading(){return this._attachments.some(t=>this._attachmentStates.get(t)?.status==="uploading")}_syncUploading(){this.toggleAttribute("data-uploading",this._uploading)}removeAttachment(t){this._attachments=this._attachments.filter(e=>e!==t),this._syncUploading(),this._emit("attachments-change",{attachments:this._attachments})}clearAttachments(){this._attachments=[],this._syncUploading(),this._emit("attachments-change",{attachments:[]})}showPanel(t,e){this._evictPanel();let s=this.querySelector("[data-aparte-panel-host]"),i=this.querySelector("aparte-composer-input");this.setAttribute("data-panel-active",""),t.dataset.apartePanel="true",t.addEventListener("keydown",this._onPanelKeydown),s?s.appendChild(t):i?i.insertAdjacentElement("afterend",t):this.appendChild(t),this._panelActive=!0,this._panelSubmitEnabled=e?.submitEnabled??!1,this._panelMode=e?.mode??"submit",this._reflectPanelMode(),this._panelOnSubmit=e?.onSubmit??null,this._panelOnEvict=e?.onEvict??null;let r=Symbol("aparte-composer-panel");return this._panelToken=r,this._emit("panel-change",{active:!0,submitEnabled:this._panelSubmitEnabled,mode:this._panelMode}),r}hidePanel(t){if(t!==void 0){if(t!==this._panelToken)return;this._teardownPanel();return}this._evictPanel()}_onPanelKeydown=t=>{t.key!=="Enter"||t.isComposing||t.keyCode===229||t.defaultPrevented||!Dh(t.target)||!(this.submitOnEnter?!t.shiftKey:t.shiftKey)||(t.preventDefault(),this.submit())};_evictPanel(){let t=this._panelOnEvict;this._teardownPanel(),t?.()}_teardownPanel(){let t=document.activeElement,e=t instanceof Node&&this.contains(t),s=this.querySelector("[data-aparte-panel]");s&&s.remove(),this.removeAttribute("data-panel-active"),this._panelActive=!1,this._panelSubmitEnabled=!1,this._panelMode="submit",this._reflectPanelMode(),this._panelOnSubmit=null,this._panelOnEvict=null,this._panelToken=null,this._emit("panel-change",{active:!1,submitEnabled:!1,mode:"submit"}),e&&this.focus()}setPanelSubmitEnabled(t,e){this._panelActive&&(this._panelSubmitEnabled=t,e&&(this._panelMode=e),this._reflectPanelMode(),this._emit("panel-change",{active:!0,submitEnabled:t,mode:this._panelMode}))}_reflectPanelMode(){this._panelActive?this.setAttribute("data-panel-mode",this._panelMode):this.removeAttribute("data-panel-mode")}get panelActive(){return this._panelActive}_evaluateModelGate(){let t=this._cfg.getRequireModelSelection()&&!this._cfg.hasSelectedModel();t!==this._modelGated&&(this._modelGated=t,this.toggleAttribute("data-model-gated",t))}submit(){if(this._panelActive){this._panelMode!=="none"&&this._panelSubmitEnabled&&this._panelOnSubmit?.();return}if(this._streaming){this.cancel();return}let t=this._value.trim();if(!t&&this._attachments.length===0||this.disabled||this._modelGated||this._uploading)return;this._emit("submit",{value:t,attachments:this._attachments});let e=this.querySelector("aparte-composer-input")?.getTokens?.(),s={content:t,timestamp:Date.now(),targetId:this._ownTargetId(),files:this._attachments.length>0?[...this._attachments]:void 0,...e?.length?{tokens:e}:{}};this.dispatchEvent(new CustomEvent("aparte-send",{bubbles:!0,composed:!0,detail:s})),this.setValue(""),this.clearAttachments()}cancel(){this._emit("cancel",{}),this.dispatchEvent(new CustomEvent("aparte-cancel",{bubbles:!0,composed:!0}));let t={targetId:this._ownTargetId()};window.dispatchEvent(new CustomEvent("aparte-abort",{bubbles:!1,detail:t})),window.dispatchEvent(new CustomEvent("aparte-message-aborted",{bubbles:!1,detail:t}))}reset(){this.setValue(""),this.clearAttachments(),this._panelActive&&this._evictPanel()}focus(){this.querySelector("aparte-composer-input")?.focus()}_emit(t,e){this._listeners.get(t)?.forEach(s=>s(e)),n._STATE_EVENTS.has(t)&&this.dispatchEvent(new CustomEvent("aparte-composer-change",{bubbles:!0,composed:!0,detail:{state:this.getState(),composer:this}}))}_on(t,e){return this._listeners.has(t)||this._listeners.set(t,new Set),this._listeners.get(t).add(e),()=>this._listeners.get(t)?.delete(e)}_isForThisComposer(t){let e=t.detail?.targetId;return!e||!this._ownTargetId()||e===this._ownTargetId()}_warnIfUnattached(){!this.isConnected||this._ownTargetId()||document.querySelectorAll("aparte-chat, [data-aparte-chat]").length<2||console.warn(`[aparte-composer] this composer belongs to no chat while the page has several: give it target="<chat id>" or place it under a chat host with an id, or it will answer to every chat's events.`)}_ownTargetId(){let t=this.targetId;if(t)return t;let e=this.parentElement;for(;e;){if((e.tagName?.toLowerCase()==="aparte-chat"||e.hasAttribute?.("data-aparte-chat"))&&e.id)return e.id;e=e.parentElement}}_streamingMessageId=null;_isForThisTurn(t){let e=t.detail?.messageId;return!e||this._streamingMessageId===null||e===this._streamingMessageId}_handleMessageStart(t){this._isForThisComposer(t)&&(this._streamingMessageId=t.detail?.messageId??null,this._streaming=!0,this._emit("streaming-change",{streaming:!0}))}_handleMessageDone(t){!this._isForThisComposer(t)||!this._isForThisTurn(t)||(this._streamingMessageId=null,this._streaming=!1,this._emit("streaming-change",{streaming:!1}),this._panelActive&&this._evictPanel())}};G(An);customElements.get("aparte-composer")||customElements.define("aparte-composer",An);function Jo(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 yi="data-aparte-token",Zo="data-aparte-text",Bh="\uFFFC",Ae=n=>n.nodeType===Node.TEXT_NODE,Hh=n=>n.nodeType===Node.ELEMENT_NODE&&n.hasAttribute(yi),tl=n=>Array.prototype.indexOf.call(n.parentNode.childNodes,n);function Se(n,t=[]){return n.childNodes.forEach(e=>{Ae(e)||e.nodeName==="BR"||Hh(e)?t.push(e):Se(e,t)}),t}var el=n=>Ae(n)?n.data.length:1;function $h(n){return Se(n).map(t=>Ae(t)?t.data:t.nodeName==="BR"?`
147
+ `:Bh).join("")}function qh(n,t,e){let s=n.ownerDocument.createRange();s.setStart(t,e),s.collapse(!0);let i=0;for(let r of Se(n)){if(r===t)return i+e;if(s.comparePoint(r.parentNode,tl(r))>=0)return i;i+=el(r)}return i}function No(n,t){let e=t;for(let s of Se(n)){if(Ae(s)&&e<=s.data.length)return[s,e];if(e===0)return[s.parentNode,tl(s)];e-=el(s)}return[n,n.childNodes.length]}function Do(n,t,e){let s=n.ownerDocument.createRange();return s.setStart(...No(n,t)),s.setEnd(...No(n,e)),s}function Bo(n,t,e){let s=n.createElement("span");s.className="aparte-tag aparte-inline-token",s.setAttribute("contenteditable","false"),s.setAttribute(yi,t),s.setAttribute(Zo,e.text??e.label),e.kind&&(s.dataset.kind=e.kind);let i=n.createElement("span");return i.className="aparte-tag__label",i.textContent=e.label,s.appendChild(i),s}function Ho(n,t){let e="",s=[];for(let r of Se(n))if(Ae(r))e+=r.data;else if(r.nodeName==="BR")e+=`
148
+ `;else{let a=r,o=t.get(a.getAttribute(yi)??""),l=a.getAttribute(Zo)??a.textContent??"",c=e.length;e+=l,s.push({label:a.textContent??"",text:l,start:c,end:e.length,...a.dataset.kind?{kind:a.dataset.kind}:{},...o?.data!==void 0?{data:o.data}:{}})}let i=e.length-e.trimStart().length;return{value:e.trim(),tokens:s.map(r=>({...r,start:r.start-i,end:r.end-i}))}}var Sn=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(Mt(this,()=>this._updatePlaceholder()))}disconnectedCallback(){this._editor?.removeEventListener("input",this._onInput),this._editor?.removeEventListener("keydown",this._onKeydown),this._editor?.removeEventListener("focus",this._onFocus),this._editor?.removeEventListener("blur",this._onBlur),this._editor?.removeEventListener("paste",this._onPaste),this._resizeObserver?.disconnect(),this._resizeObserver=null,this._unsubscribes.forEach(t=>t()),this._unsubscribes=[]}attributeChangedCallback(t,e,s){t==="placeholder"&&this._updatePlaceholder(),t==="max-height"&&(this._maxHeight=parseInt(s||"200",10)),t==="min-height"&&(this._minHeight=parseInt(s||"44",10)),t==="disabled"&&this._updateDisabled(s!==null)}getValue(){return this._editor?Ho(this._editor,this._tokens).value:""}getTokens(){return this._editor?Ho(this._editor,this._tokens).tokens:[]}getCaret(){let t=this.ownerDocument?.getSelection();return!this._editor||!t?.rangeCount||!t.isCollapsed||!this._editor.contains(t.anchorNode)?null:{text:$h(this._editor),offset:qh(this._editor,t.anchorNode,t.anchorOffset)}}getRangeRect(t,e=t){return this._editor?Do(this._editor,t,e).getClientRects?.()[0]??null:null}replaceRange(t,e,s){this._write(t,e,()=>s?this._insertPlain(s):this._exec("delete"),()=>this.ownerDocument.createTextNode(s))}insertToken(t,e,s){let i=String(++this._lastTokenId);this._tokens.set(i,s);let r=this.ownerDocument,a=()=>{let o=r.createDocumentFragment();return o.append(Bo(r,i,s),r.createTextNode(" ")),o};this._write(t,e,()=>this._exec("insertHTML",`${Bo(r,i,s).outerHTML} `),a)}setValue(t){this._editor&&(this._editor.textContent=t,this._tokens.clear(),this._updatePlaceholderVisibility(),this._adjustHeight(),this._getRoot()?.setValue(t))}clear(){this._editor&&(this._editor.innerHTML="",this._tokens.clear(),this._updatePlaceholderVisibility(),this._adjustHeight(),this._getRoot()?.setValue(""))}syncPlaceholder(){this._updatePlaceholder()}focus(){this._editor?.focus()}blur(){this._editor?.blur()}focusEnd(){if(!this._editor)return;this._editor.focus();let t=this.ownerDocument?.getSelection();if(!t)return;let e=this.ownerDocument.createRange();e.selectNodeContents(this._editor),e.collapse(!1),t.removeAllRanges(),t.addRange(e)}_getRoot(){return this.closest("aparte-composer")}_tokens=new Map;_lastTokenId=0;_write(t,e,s,i){let r=this._editor,a=this.ownerDocument?.getSelection();if(!r||!a)return;r.focus();let o=Do(r,t,e);if(a.removeAllRanges(),a.addRange(o),s())return;o.deleteContents();let l=i(),c=l.nodeType===Node.DOCUMENT_FRAGMENT_NODE?l.lastChild:l;o.insertNode(l),o.setStartAfter(c),o.collapse(!0),a.removeAllRanges(),a.addRange(o),this._handleInput()}_exec(t,e){try{return this.ownerDocument.execCommand(t,!1,e)}catch{return!1}}_insertPlain(t){return/[\r\n]/.test(t)?this._exec("insertHTML",P(t).replace(/\r\n?|\n/g,"<br>")):this._exec("insertText",t)}_getPlaceholder(){return this.getAttribute("placeholder")||this._getRoot()?.placeholder||L(this).t("inputPlaceholder")||"Type a message..."}_render(){if(this.querySelector(".aparte-ci-editor"))return;let t=this.hasAttribute("disabled")||this._getRoot()?.disabled||!1,e=I(this._getPlaceholder());this.innerHTML=`<div
149
+ class="aparte-ci-editor"
150
+ contenteditable="${!t}"
151
+ role="textbox"
152
+ aria-multiline="true"
153
+ aria-label="${e}"
154
+ tabindex="${I(String(t?-1:0))}"
155
+ aria-disabled="${t}"
156
+ data-placeholder="${e}"
157
+ ></div>`,this._editor=this.querySelector(".aparte-ci-editor"),this._adjustHeight()}_connectToRoot(){let t=this._getRoot();t&&(this._unsubscribes.push(t._on("disabled-change",({disabled:e})=>this._updateDisabled(e))),this._unsubscribes.push(t._on("value-change",({value:e})=>{this.getValue()!==e.trim()&&(e===""?this.clear():this.setValue(e))})))}_handleInput(){this._adjustHeight(),this._editor&&!this._editor.textContent?.trim()&&this._editor.innerHTML!==""&&(this._editor.innerHTML=""),this._updatePlaceholderVisibility();let t=this.getValue();this._getRoot()?.setValue(t)}_handleKeydown(t){if(t.isComposing||t.keyCode===229||t.defaultPrevented||t.key!=="Enter")return;if(this._getRoot()?.submitOnEnter??!0?!t.shiftKey:t.shiftKey){t.preventDefault();let i=this._getRoot();if(i){if(i.streaming)return;i.submit()}else this.dispatchEvent(new CustomEvent("aparte-composer-submit",{bubbles:!0}))}else{if(t.preventDefault(),!this._editor?.textContent)return;this.ownerDocument?.execCommand("insertLineBreak")}}_handleFocus(){this.classList.add("aparte-is-focused")}_handleBlur(){this.classList.remove("aparte-is-focused")}_handlePaste(t){t.preventDefault();let e=t.clipboardData;if(!e)return;let s=this._getRoot(),i=s?.querySelector("aparte-composer-add-attachment"),r=i?Array.from(e.items).find(o=>o.type.startsWith("image/"))?.getAsFile():void 0;if(r&&Jo(i?.getAttribute("accept"),r)){s?.addAttachments([r]);return}let a=e.getData("text/plain");a&&this._insertPlain(a)}_adjustHeight(){if(!this._editor)return;this._editor.style.height="0px";let t=this.hasAttribute("min-height")?this._minHeight:0,e=this._editor.scrollHeight,s=Math.min(Math.max(e,t),this._maxHeight);this._editor.style.height=`${s}px`,this._editor.style.overflowY=e>this._maxHeight?"auto":"hidden"}_scheduleInitialReflow(){typeof requestAnimationFrame=="function"&&requestAnimationFrame(()=>this._adjustHeight()),document.fonts?.ready?.then(()=>this._adjustHeight()).catch(()=>{})}_updatePlaceholder(){if(this._editor){let t=this._getPlaceholder();this._editor.setAttribute("data-placeholder",t),this._editor.setAttribute("aria-label",t)}}_updatePlaceholderVisibility(){}_updateDisabled(t){this._editor&&(this._editor.setAttribute("contenteditable",String(!t)),this._editor.setAttribute("aria-disabled",String(t)),this._editor.setAttribute("tabindex",t?"-1":"0"),t&&this.ownerDocument?.activeElement===this._editor&&this._editor.blur())}};G(Sn);customElements.get("aparte-composer-input")||customElements.define("aparte-composer-input",Sn);var Cn=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=L(this).t("sendButton")||"Send",e=this._getSendIcon(),s=this._getRoot(),i=!s||s.disabled||s.value.trim()==="";this.innerHTML=`<button
158
+ type="button"
159
+ class="aparte-btn aparte-btn--primary aparte-btn--solid aparte-btn--icon aparte-cs-button aparte-send-button"
160
+ aria-label="${I(t)}"
161
+ title="${I(t)}"
162
+ data-act="send"
163
+ ${i?"disabled":""}
164
+ >${e}</button>`,this.setAttribute("data-act","send")}_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(Mt(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=L(this);if(t.mode==="none"){this._button.disabled=!0;return}this._button.disabled=!t.submitEnabled,this._button.innerHTML=this._getSubmitIcon(),this._setAct("submit");let s=e.t("submitButton")||"Submit";this._button.setAttribute("aria-label",s),this._button.setAttribute("title",s),this._button.classList.remove("aparte-is-streaming")}_handleClick(t){t.preventDefault(),this._getRoot()?.submit()}_setAct(t){this._button?.setAttribute("data-act",t),this.setAttribute("data-act",t)}_syncState(){let t=this._getRoot();if(!t||!this._button||t.streaming)return;let e=t.value.trim()===""&&t.attachments.length===0;this._button.disabled=t.disabled||e,this._button.innerHTML=this._getSendIcon(),this._setAct("send");let s=L(this).t("sendButton")||"Send";this._button.setAttribute("aria-label",s),this._button.setAttribute("title",s),this._button.classList.remove("aparte-is-streaming")}_syncStreamingState(t){if(this._button)if(t){this._button.disabled=!1,this._button.innerHTML=this._getStopIcon(),this._setAct("stop");let e=L(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 L(this).getIcon("check")}_getSendIcon(){return L(this).getIcon("send")||"Send"}_getStopIcon(){return L(this).getIcon("stop")}};G(Cn);customElements.get("aparte-composer-send")||customElements.define("aparte-composer-send",Cn);var En=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(Mt(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=L(this).t("stopButton")||"Stop",e=this._getStopIcon();this.innerHTML=`<button
165
+ type="button"
166
+ class="aparte-btn aparte-btn--icon aparte-cc-button"
167
+ aria-label="${I(t)}"
168
+ title="${I(t)}"
169
+ hidden
170
+ >${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=L(this).t("stopButton")||"Stop";this._button.setAttribute("aria-label",t),this._button.setAttribute("title",t),this._button.innerHTML=this._getStopIcon()}_getStopIcon(){return L(this).getIcon("stop")}};G(En);customElements.get("aparte-composer-cancel")||customElements.define("aparte-composer-cancel",En);var kn=class extends HTMLElement{_unsubscribes=[];_objectUrls=[];connectedCallback(){this._render([]),this._connectToRoot()}disconnectedCallback(){this._unsubscribes.forEach(t=>t()),this._unsubscribes=[],this._revokeUrls()}_getRoot(){return this.closest("aparte-composer")}_connectToRoot(){let t=this._getRoot();t&&(this._unsubscribes.push(t._on("attachments-change",({attachments:e})=>this._render(e))),this._render(t.attachments))}showState(t,e){let s=this._getRoot()?.attachments.indexOf(t)??-1,i=this.querySelectorAll(".aparte-thumb")[s];if(!i)return;i.toggleAttribute("data-failed",e?.status==="error");let r=i.querySelector(".aparte-progress");if(e?.status!=="uploading"){r?.remove();return}r||(r=document.createElement("div"),r.className="aparte-progress aparte-thumb__progress",r.setAttribute("role","progressbar"),r.setAttribute("aria-label",t.name),r.innerHTML='<div class="aparte-progress__bar"></div>',i.appendChild(r));let a=e.progress!==void 0;r.classList.toggle("aparte-progress--indeterminate",!a),a?(r.setAttribute("aria-valuenow",String(e.progress)),r.setAttribute("aria-valuemin","0"),r.setAttribute("aria-valuemax","100"),r.style.setProperty("--aparte-progress-value",String(e.progress))):r.removeAttribute("aria-valuenow")}_revokeUrls(){this._objectUrls.forEach(t=>URL.revokeObjectURL(t)),this._objectUrls=[]}_render(t){this.hidden=t.length===0,this._revokeUrls();let e=L(this),s=a=>(e.t("removeAttachment")||"Remove {name}").replace("{name}",()=>a.name);this.innerHTML=t.map(a=>{let o=P(a.name),l=`<button class="aparte-btn aparte-btn--icon aparte-btn--sm aparte-thumb__remove" type="button" aria-label="${I(s(a))}">${e.getIcon("close")}</button>`;if(a.type.startsWith("image/")){let c=URL.createObjectURL(a);return this._objectUrls.push(c),`<div class="aparte-thumbnail aparte-thumb aparte-thumb--image" title="${o}"><img class="aparte-thumbnail__image" src="${I(c)}" alt="${o}" /><span class="aparte-thumb__name">${o}</span>${l}</div>`}return`<div class="aparte-thumbnail aparte-thumb aparte-thumb--file" title="${o}"><span class="aparte-thumbnail__label">${P(this._ext(a.name))}</span><span class="aparte-thumb__name">${o}</span>${l}</div>`}).join("");let i=this._getRoot();if(i)for(let a of t){let o=i.getAttachmentState(a);o&&this.showState(a,o)}if(this.querySelectorAll(".aparte-thumb__remove").forEach((a,o)=>{a.addEventListener("click",l=>{l.stopPropagation();let c=this._getRoot();c&&c.removeAttachment(c.attachments[o])})}),!L(this).getHostHandlers().attachmentPreview)return;let r=t.filter(a=>a.type.startsWith("image/"));this.querySelectorAll(".aparte-thumb--image").forEach((a,o)=>{let l=a.querySelector(".aparte-thumbnail__image");if(!l)return;l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-label",r[o]?.name??"");let c=()=>{this.dispatchEvent(new CustomEvent("aparte-attachment-preview",{bubbles:!0,composed:!0,detail:{url:l.src,name:r[o]?.name??"",type:r[o]?.type??""}}))};l.addEventListener("click",c),l.addEventListener("keydown",d=>{let h=d.key;h!=="Enter"&&h!==" "||(d.preventDefault(),c())})})}_ext(t){let e=t.lastIndexOf(".");return e>0?t.slice(e+1).toUpperCase().slice(0,4):"FILE"}};G(kn);customElements.get("aparte-composer-attachments")||customElements.define("aparte-composer-attachments",kn);var Tn=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(Mt(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=L(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=L(this).t("actionUpload")||"Attach file",e=L(this).getIcon("paperclip"),s=this.hasAttribute("disabled")||this._getRoot()?.disabled||!1;this.innerHTML=`<button
171
+ class="aparte-btn aparte-btn--icon aparte-caa-button aparte-action-button"
172
+ aria-label="${I(t)}"
173
+ title="${I(t)}"
174
+ type="button"
175
+ ${s?"disabled":""}
176
+ >${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=>Jo(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)}}};G(Tn);customElements.get("aparte-composer-add-attachment")||customElements.define("aparte-composer-add-attachment",Tn);var xn=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(Mt(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=I(this.getAttribute("label")??""),e=this._resolveIcon(this.getAttribute("icon")??""),s=this.hasAttribute("disabled")||this._getRoot()?.disabled||!1;this.innerHTML=`<button
177
+ class="aparte-btn aparte-btn--icon aparte-cact-button aparte-action-button"
178
+ aria-label="${t}"
179
+ title="${t}"
180
+ type="button"
181
+ ${s?"disabled":""}
182
+ >${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:L(this).getIcon(t)??t:""}};G(xn);customElements.get("aparte-composer-action")||customElements.define("aparte-composer-action",xn);var Mn=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",""))}};G(Mn);customElements.get("aparte-composer-toolbar")||customElements.define("aparte-composer-toolbar",Mn);function Ln(n){return n.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().trim()}function vi(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!==""&&!Ln(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 $o=n=>n==="running"||n==="waiting"?n:null;function be(n,t){return`[${n}="${tt(t)}"]`}var pi=864e5,fi=4,gi=8,In=class extends HTMLElement{_conversations=[];_activeId=null;_menus=[];_contextMenu=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",J(t))}get manage(){return this.hasAttribute("manage")}set manage(t){this.toggleAttribute("manage",J(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("aparte-menu-select",this._onMenuSelect),this.addEventListener("pointerdown",this._onPress),this._render(),window.addEventListener("aparte-config-change",this._onConfigChange),window.addEventListener("aparte-conversation-status",this._onStatus)}disconnectedCallback(){this._releaseMenus(),this.removeEventListener("click",this._onClick),this.removeEventListener("keydown",this._onKeydown),this.removeEventListener("aparte-menu-select",this._onMenuSelect),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!==L(this)||this._render()};_onStatus=t=>{let e=t.detail;if(typeof e?.id!="string")return;ai(e.id,$o(e.status));let s=this.querySelector(be("data-conv-id",e.id));s&&this._applyStatus(s,e.id)};setConversationStatus(t,e){lo(t,$o(e))}getConversationStatus(t){return on(t)}_applyStatus(t,e){let s=on(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._releaseMenus(),this._renaming=null;let e=it(this),s=e&&this.contains(e)?e.closest("[data-select-id], [data-more-id]"):null,i=s?.dataset.selectId?be("data-select-id",s.dataset.selectId):s?.dataset.moreId?be("data-more-id",s.dataset.moreId):null,r=s?.closest("[data-conv-id]")??null,a=f=>!f.closest("[hidden]"),o=r?Array.from(this.querySelectorAll("[data-conv-id]")).filter(a).indexOf(r):-1,l=this.hasAttribute("loading");if(this.setAttribute("aria-busy",l?"true":"false"),l){this.removeAttribute("data-no-match");let f='<span class="aparte-skeleton aparte-skeleton--text"></span>';this.innerHTML='<div class="aparte-conv-list-loading" aria-hidden="true">'+f+f+f+f+f+f+'</div><span class="aparte-conv-list-loading-status aparte-sr-only" role="status"></span>';let g=this.querySelector(".aparte-conv-list-loading-status"),_=()=>{g?.isConnected&&(g.textContent=this._t("loadingConversations"))};typeof requestAnimationFrame=="function"?requestAnimationFrame(_):_();return}let c=this.querySelector(":scope > .aparte-conv-list-no-match"),d=this._groups().map(f=>this._renderGroup(f)).join("");if(c){for(let f of Array.from(this.childNodes))f!==c&&f.remove();c.insertAdjacentHTML("beforebegin",d)}else this.innerHTML=d;if(this._applyFilter(),this._wireMenus(),!i)return;let h=this.querySelector(i);if(h&&a(h)){h.focus();return}let u=Array.from(this.querySelectorAll("[data-select-id]")).filter(a),p=o>=0?u[o]??u[u.length-1]:null;if(p){p.focus();return}this.hasAttribute("tabindex")||(this.setAttribute("tabindex","-1"),this.addEventListener("blur",()=>this.removeAttribute("tabindex"),{once:!0})),this.focus()}_query="";filter(t){return this._query=Ln(t),this._applyFilter()}_applyFilter(){let t=this._query;if(this.hasAttribute("loading"))return 0;let e=vi(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 L(this).getLocale()[t]??Ut[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=L(this).getLocale().tag,r=new Map,a=(d,h,u)=>{let p=r.get(d);p||(p={key:d,label:h,items:[]},r.set(d,p)),p.items.push(u)};for(let d of t){if(d.pinnedAt){a("pinned",this._t("conversationGroupPinned"),d);continue}let h=d.updatedAt;if(typeof h!="number"){a("undated",null,d);continue}if(h>=s)a("today",this._t("conversationGroupToday"),d);else if(h>=s-pi)a("yesterday",this._t("conversationGroupYesterday"),d);else if(h>=s-7*pi)a("week",this._t("conversationGroupWeek"),d);else if(h>=s-30*pi)a("month",this._t("conversationGroupMonth"),d);else{let u=new Date(h),p=u.getFullYear()===e.getFullYear(),f=new Intl.DateTimeFormat(i,p?{month:"long"}:{month:"long",year:"numeric"}).format(u),g=f.charAt(0).toLocaleUpperCase(i)+f.slice(1);a(`m-${u.getFullYear()}-${String(u.getMonth()).padStart(2,"0")}`,g,d)}}let o=["pinned","today","yesterday","week","month"].map(d=>r.get(d)).filter(d=>!!d),l=[...r.keys()].filter(d=>d.startsWith("m-")).sort((d,h)=>h.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=P(t.label);return`
183
+ <div class="aparte-conv-group" role="group" aria-label="${I(t.label)}">
184
+ <div class="aparte-menu__label aparte-conv-group__label" aria-hidden="true">${s}</div>
185
+ ${e}
186
+ </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=I(t.id),r=P(t.title||this._t("newChat")),a=I(this._t("conversationActions")),o=L(this).getIcon("more"),l=on(t.id),c=l?` data-status="${I(l)}"`:"",d=I(l==="running"?"aparte-conv-item__title aparte-shimmer":"aparte-conv-item__title"),h=P(this._statusWords(l));return`
187
+ <div class="${I(s)}" data-conv-id="${i}"${c}>
188
+ <button
189
+ class="aparte-conv-item__select"
190
+ type="button"
191
+ data-select-id="${i}"
192
+ aria-current="${e?"page":"false"}"
193
+ ><span class="${d}" dir="auto">${r}</span><span class="aparte-conv-item__status" aria-hidden="true"></span><span class="aparte-conv-item__state aparte-sr-only">${h}</span></button>
194
+ <button
195
+ class="aparte-btn aparte-btn--icon aparte-btn--sm aparte-conv-item__more"
196
+ type="button"
197
+ data-more-id="${i}"
198
+ aria-label="${a}"
199
+ title="${a}"
200
+ aria-haspopup="menu"
201
+ aria-expanded="false"
202
+ >${o}</button>
203
+ </div>`}_menuMarkup(t){let e=L(this),s=e.getIcon("edit"),i=e.getIcon("pin"),r=e.getIcon(t.archivedAt?"unarchive":"archive"),a=e.getIcon("trash"),o=P(this._t("renameConversation")),l=P(this._t(t.pinnedAt?"unpinConversation":"pinConversation")),c=P(this._t(t.archivedAt?"unarchiveConversation":"archiveConversation")),d=P(this._t("deleteConversation"));return`
204
+ <button type="button" class="aparte-menu__item" role="menuitem" data-menu-action="rename">${s}<span>${o}</span></button>
205
+ <button type="button" class="aparte-menu__item" role="menuitem" data-menu-action="pin">${i}<span>${l}</span></button>
206
+ <button type="button" class="aparte-menu__item" role="menuitem" data-menu-action="archive">${r}<span>${c}</span></button>
207
+ <div class="aparte-menu__separator" role="separator"></div>
208
+ <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=P(this._confirmQuestion(t)),s=P(this._t("cancel")),i=P(this._t("deleteConversation"));return`
209
+ <div class="aparte-conv-menu__confirm">
210
+ <p class="aparte-conv-menu__question">${e}</p>
211
+ <div class="aparte-conv-menu__actions">
212
+ <button type="button" class="aparte-btn aparte-btn--sm aparte-btn--ghost" data-menu-action="cancel">${s}</button>
213
+ <button type="button" class="aparte-btn aparte-btn--sm aparte-btn--danger aparte-btn--solid" data-menu-action="confirm-delete">${i}</button>
214
+ </div>
215
+ </div>`}_newMenu(){let t=document.createElement("div");return t.className="aparte-menu aparte-conv-menu",t.setAttribute("role","menu"),t}_fillMenu(t,e){let s=t.dataset.convId,i=s?this._conversations.find(r=>r.id===s):void 0;return i?(e.dataset.menuFor=i.id,e.setAttribute("role","menu"),e.setAttribute("aria-label",i.title||this._t("newChat")),e.innerHTML=this._menuMarkup(i),t.appendChild(e),!0):!1}_wireMenus(){for(let e of this.querySelectorAll("[data-more-id]")){let s=e.closest("[data-conv-id]");if(!s)continue;let i=this._newMenu();this._menus.push(Oi(e,i,{gap:fi,margin:gi,align:"end",onOpen:()=>this._fillMenu(s,i),onClose:()=>i.remove()}))}let t=this._contextMenu??=this._newMenu();this._menus.push(Pi(this,t,{gap:fi,margin:gi,onOpen:e=>{let s=e.closest("[data-conv-id]");return!s||!this.contains(s)||e.closest("[data-rename-id], [data-menu-for]")?!1:this._fillMenu(s,t)},onClose:()=>t.remove()}))}_releaseMenus(){for(let t of this._menus.splice(0))t()}_placeQuestion(t,e){let s=getComputedStyle(this).direction==="rtl",i=t===this._contextMenu?null:this.querySelector(be("data-more-id",e)),r=t.getBoundingClientRect(),a=s?r.right:r.left;zn(i?.getBoundingClientRect()??{top:r.top,bottom:r.top,left:a,right:a},t,{gap:i?fi:0,margin:gi,align:i?"end":"start",rtl:s})}_onMenuSelect=t=>{t.target.dataset.menuFor!==void 0&&(t.stopPropagation(),t.detail.item.dataset.menuAction==="delete"&&t.preventDefault())};_manage(t,e){if(!this.hasAttribute("manage")||t.defaultPrevented)return;let s=this.getAttribute("target"),i=this.getRootNode(),r=s?i.getElementById?.(s)??this.ownerDocument.getElementById(s):null,a=L(r??this).getConversationManager();if(!a){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(a).catch(o=>{console.warn("[aparte-conversation-list] the conversation manager refused the change:",o)})}_onMenuAction(t,e){let s=this._conversations.find(r=>r.id===e.dataset.menuFor);if(!s)return;let i=s.id;switch(t){case"rename":{let r=this.querySelector(be("data-conv-id",i));r&&this._startRename(r,s);return}case"pin":if(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(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.childNodes],a=document.createElement("div");a.innerHTML=this._confirmMarkup(s),e.append(...a.childNodes),e.setAttribute("role","dialog"),e.setAttribute("aria-label",this._confirmQuestion(s)),e.querySelector('[data-menu-action="cancel"]')?.focus();for(let o of r)o.remove();this._placeQuestion(e,i);return}case"cancel":return;case"confirm-delete":{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}}}_onQuestionKeydown(t,e){if(t.defaultPrevented)return;let s=Array.from(e.querySelectorAll("[data-menu-action]")),i=s.indexOf(it(this)),r=a=>{t.preventDefault(),s[(a+s.length)%s.length]?.focus()};switch(t.key){case"ArrowDown":r(i+1);return;case"ArrowUp":r(i-1);return;case"Home":r(0);return;case"End":r(s.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="${tt(s.id)}"]`)?.focus()}_onClick=t=>{let e=t.target,s=e.closest("[data-menu-action]"),i=s?.closest("[data-menu-for]");if(s&&i){t.stopPropagation(),this._onMenuAction(s.dataset.menuAction,i);return}if(e.closest("[data-more-id]")){t.stopPropagation();return}if(e.closest("[data-rename-id]"))return;let r=e.closest("[data-select-id]");if(r){let a=this.getAttribute("target");this.dispatchEvent(new CustomEvent("aparte-conversation-select",{detail:{id:r.dataset.selectId,...a?{targetId:a}:{}},bubbles:!0,composed:!0}))}};_onKeydown=t=>{let e=t.target,s=e.closest("[data-menu-for]");if(s){s.getAttribute("role")==="dialog"&&this._onQuestionKeydown(t,s);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")})}};G(In);customElements.get("aparte-conversation-list")||customElements.define("aparte-conversation-list",In);var nl=n=>typeof n=="string"||typeof n=="object"&&n!==null&&typeof n.label=="string",_i=n=>{try{let t=JSON.parse(n);return Array.isArray(t)?t.filter(nl):[]}catch{return console.warn('[aparte-suggestions] `suggestions` is not a JSON array. Use ["\u2026"] or [{"label": "\u2026", "prompt": "\u2026"}].'),[]}},qo=n=>typeof n=="string"?n:n.label,Fo=n=>typeof n=="string"?n:n.prompt??n.label,Rn=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?Xo(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"?_i(t):Array.isArray(t)?t.filter(nl):[],this.isConnected&&this._render()}connectedCallback(){this.hasAttribute("suggestions")&&this._readAttribute(),this._render(),this._watchComposer(),window.addEventListener("aparte-config-change",this._onConfigChange)}disconnectedCallback(){this._composer?.removeEventListener("aparte-send",this._onSend),this._composer=null,this._transcriptObserver?.disconnect(),this._transcriptObserver=null,this._transcript=null,this._stopHolding(),window.removeEventListener("aparte-config-change",this._onConfigChange)}attributeChangedCallback(t){this.isConnected&&(t==="suggestions"?(this._readAttribute(),this._render()):t==="target"?this._watchComposer():t==="answers"?this._watchTranscript():t==="empty-only"&&(this._watchTranscript(),this.hasAttribute("empty-only")||(this._sent=!1,this._setHidden(!1))))}_groupLabel(){return L(this).t("suggestionsLabel")||"Suggested prompts"}_parsed=null;_readAttribute(){let t=this.getAttribute("suggestions");t===null||t===this._parsed||(this._parsed=t,this._suggestions=_i(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=_t(this._composer)??_t(this)??(t?document.getElementById(t):null);return e?e.matches("aparte-chat-viewport")?e:e.querySelector("aparte-chat-viewport"):null}_watchTranscript(){let e=this.hasAttribute("empty-only")||this.hasAttribute("answers")?this._resolveTranscript():null;e!==this._transcript&&(this._transcriptObserver?.disconnect(),this._transcriptObserver=null,this._transcript=e,e&&(this._transcriptObserver=new MutationObserver(this._onTranscript),this._transcriptObserver.observe(e,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["loading"]}))),this._onTranscript()}_onTranscript=()=>{this.hasAttribute("empty-only")&&this._applyEmptyOnly(),this.hasAttribute("answers")&&this._applyAnswers()};_applyAnswers(){let t=this._transcript?.querySelectorAll("aparte-chat-bubble"),e=t&&t.length?t[t.length-1]:null,s=e&&e.getAttribute("data-role")!=="user"?e.querySelectorAll("[data-aparte-suggestions]"):null,i=s&&s.length?s[s.length-1]:null,r=i?_i(i.getAttribute("data-aparte-suggestions")??"[]"):[];this._showAnswers(r.map(ni).filter(a=>a!==null))}_showAnswers(t){JSON.stringify(t)!==JSON.stringify(this._suggestions)&&(this._suggestions=t,this.isConnected&&this._render())}_setHidden(t){if(t){if(this.hidden)return;this.hidden=!0,this._hidOwn=!0}else this._hidOwn&&(this.hidden=!1,this._hidOwn=!1)}_render(){if(this.replaceChildren(),this._suggestions.length===0){this.setAttribute("data-empty","");return}this.removeAttribute("data-empty");let t=document.createElement("div");t.className="aparte-suggestions",t.setAttribute("role","group"),t.setAttribute("aria-label",this._groupLabel());for(let e of this._suggestions){let s=document.createElement("button");s.type="button",s.className="aparte-btn aparte-btn--surface aparte-btn--pill aparte-suggestion",s.textContent=qo(e);let i=Fo(e);i!==s.textContent&&(s.title=i),s.addEventListener("click",()=>this._activate(e)),t.appendChild(s)}this.appendChild(t)}_sending=!1;_sendingTimer;_stopHolding=()=>{this._sending=!1,clearTimeout(this._sendingTimer),window.removeEventListener("aparte-message-start",this._onTurnStart)};_onTurnStart=t=>{let e=t.detail?.targetId,s=this._ownChatId();(!e||!s||e===s)&&this._stopHolding()};_ownChatId(){let t=this._composer,e=t?.getAttribute("target");if(e)return e;for(let s=t?.parentElement??null;s;s=s.parentElement)if((s.tagName.toLowerCase()==="aparte-chat"||s.hasAttribute("data-aparte-chat"))&&s.id)return s.id}_holdUntilStreaming(){this._stopHolding(),this._sending=!0,window.addEventListener("aparte-message-start",this._onTurnStart),this._sendingTimer=setTimeout(this._stopHolding,1e3)}_activate(t){let e={label:qo(t),prompt:Fo(t)};if(!this.dispatchEvent(new CustomEvent("aparte-suggestion",{detail:e,bubbles:!0,composed:!0,cancelable:!0})))return;let i=this._composer??this._resolveComposer();if(!i){console.warn("[aparte-suggestions] no <aparte-composer> to send through \u2014 put the element inside one, or point `target` at the chat it serves.");return}i!==this._composer&&this._watchComposer();let r=i;if(r.panelActive)return;let a=this.getAttribute("mode")==="fill";if(!a&&(r.streaming||this._sending))return;let o=this.contains(document.activeElement),l=typeof i.value=="string"?i.value:"",c=a?[]:(i.attachments??[]).slice();if(c.length&&i.clearAttachments(),i.setValue(e.prompt),a)i.focus();else{let d=!1,h=()=>{d=!0};i.addEventListener("aparte-send",h,{once:!0}),i.submit(),i.removeEventListener("aparte-send",h),d&&this._holdUntilStreaming(),c.length&&i.addAttachments(c),(typeof i.value=="string"?i.value:"")!==l&&i.setValue(l),o&&i.focus()}}};G(Rn);customElements.get("aparte-suggestions")||customElements.define("aparte-suggestions",Rn);var Wo=(n,t)=>{let e=Number(n);return n!==null&&Number.isFinite(e)&&e>0&&e<=1?e:t},Fh=n=>(n instanceof Element?n.closest("aparte-chat, [data-aparte-chat]"):null)?.id||void 0,V=(n,t,e)=>{let s=document.createElement(n);return s.className=t,e!==void 0&&(s.textContent=e),s},Uo="http://www.w3.org/2000/svg",Wh=()=>{let n=document.createElementNS(Uo,"svg");n.setAttribute("class","aparte-context__ring"),n.setAttribute("viewBox","0 0 36 36");for(let t of["track","value"]){let e=document.createElementNS(Uo,"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},jo=n=>!!n&&typeof n.getMessages=="function",Uh=n=>{if(!n)return null;if(jo(n))return n;let t=n.viewport??n.querySelector("aparte-chat-viewport");return jo(t)?t:null},jh=0,zh={system:0,tools:0,summary:0,messages:0},On=class extends HTMLElement{static get observedAttributes(){return["window","warn","danger","target","variant","used"]}_used=null;_level=null;_lastDone=null;_viewChanged=!1;_blank=!1;_overflow=!1;_compact=null;_failure="";_open=!1;_measured=null;_seen=null;_panelSignature="";_remember(t){let e=t instanceof Element?_t(t):null;e&&(this._seen=e)}_onDone=t=>{let e=t.detail;!e?.usage||!this._isMine(e.targetId)||(this._remember(t.target),this._used=cn(e.usage),this._lastDone={messageId:e.messageId,usage:e.usage},this._viewChanged=!1,this._blank=!1,this._overflow=!1,this._render())};_onReset=t=>{this._isMine(Fh(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?cn(r.usage):null,this._render()};_onCompactStart=t=>{let e=t.detail;this._isMine(e?.targetId)&&(this._compact="running",this._failure="",this._render())};_onCompacted=t=>{let e=t.detail;if(this._isMine(e?.targetId)){if(this._compact=null,e?.skipped){this._render();return}this._viewChanged=!0,this._overflow=!1,this._messages()||(this._used=null),this._render()}};_onCompactError=t=>{let e=t.detail;this._isMine(e?.targetId)&&(this._compact=e?.aborted?null:"failed",this._failure=e?.aborted?"":typeof e?.error=="string"?e.error:"",this._render())};_onMessageError=t=>{let e=t.detail;this._isMine(e?.targetId)&&e?.error?.code===z.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 L(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=_t(this);return e||(this._seen?.isConnected?this._seen:null)}_messages(){let t=Uh(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)?bo({messages:i,config:this._cfg(),windowOverride:t,viewChanged:this._viewChanged}):this._used===null?null:{window:t,used:this._used,estimated:!1,parts:{...zh},other:this._used}}_render(){let t=this._window(),e=t===null?null:this._measure(t);if(this._compact?this.setAttribute("data-compact",this._compact):this.removeAttribute("data-compact"),t===null||e===null){this._measured=null,this.setAttribute("data-empty",""),this.removeAttribute("data-level"),this._open=!1,this._stopListeningWhileOpen(),this._panelSignature="",this.replaceChildren(),this._level=null;return}this._measured=e,this.removeAttribute("data-empty");let s=e.used,i=Math.min(1,s/t),r=Wo(this.getAttribute("warn"),.75),a=Wo(this.getAttribute("danger"),.9),o=this._overflow||i>=a?"danger":i>=r?"warn":"ok";this.setAttribute("data-level",o);let l=this.getAttribute("variant")==="ring",c=this.querySelector(".aparte-context");c&&c.classList.contains("aparte-context--ring")!==l&&(this.replaceChildren(),c=null,this._panelSignature="");let d=this.querySelector('[role="meter"]'),h=this.querySelector(".aparte-context__text"),u=this.querySelector(".aparte-context__toggle"),p=this.querySelector(".aparte-context__name"),f=this.querySelector(".aparte-context__panel");(!c||!d||!h||!u||!p||!f)&&(c=V("div",l?"aparte-context aparte-context--ring":"aparte-context"),d=l?Wh():V("div","aparte-progress"),d.setAttribute("role","meter"),l||d.appendChild(V("div","aparte-progress__bar")),u=V("button","aparte-btn aparte-btn--ghost aparte-btn--sm aparte-context__toggle"),u.type="button",p=V("span","aparte-sr-only"),p.classList.add("aparte-context__name"),h=V("span","aparte-context__text"),u.append(p,h),f=V("div","aparte-context__panel aparte-popover"),f.id=`aparte-context-panel-${++jh}`,f.setAttribute("role","group"),f.hidden=!0,u.setAttribute("aria-controls",f.id),c.append(d,u,f),this.replaceChildren(c),this._panelSignature="");let g=this._cfg(),_=g.getLocale().tag||void 0,w=new Intl.NumberFormat(_,{notation:"compact",maximumFractionDigits:1}),S=e.estimated?"~":"",T=`${S}${w.format(s)} / ${w.format(t)}`,k=Math.round(i*100),m=g.t("contextLabel")||"Context window";if(l){let v=d.querySelector(".aparte-context__value");v?.style.setProperty("--aparte-context-ratio",String(k)),v?.classList.toggle("aparte-context__value--empty",k===0),c.title=T}else d.style.setProperty("--aparte-progress-value",String(k));if(d.setAttribute("aria-valuemin","0"),d.setAttribute("aria-valuemax",String(t)),d.setAttribute("aria-valuenow",String(s)),d.setAttribute("aria-label",`${m}: ${T}`),p.textContent=`${m}: `,u.setAttribute("aria-expanded",String(this._open)),h.textContent=l?`${S}${new Intl.NumberFormat(_,{style:"percent",maximumFractionDigits:0}).format(k/100)}`:T,f.setAttribute("aria-label",m),f.hidden=!this._open,this._open?this._renderPanel(f,e,t,w):this._panelSignature="",o!==this._level){this._level=o;let v=this._ownTargetId(),E={level:o,used:s,window:t,ratio:i,targetId:v};this.dispatchEvent(new CustomEvent("aparte-context-threshold",{detail:E,bubbles:!0,composed:!0}))}}_renderPanel(t,e,s,i){let r=this._cfg(),a=r.getCompactor(),o=this._chat(),l=this._ownTargetId(),c=null;try{c=a?.preview?.({target:o,...l?{targetId:l}:{}})??null}catch{c=null}let{parts:d,used:h}=e,u=d.system+d.tools+d.summary+d.messages,p=u>h&&u>0?h/u:1,f=e.estimated?"~":"",g=[{key:"system",label:r.t("contextSystem")||"System prompt",tokens:d.system*p,approx:"~"},{key:"tools",label:r.t("contextTools")||"Tools",tokens:d.tools*p,approx:"~"},{key:"summary",label:r.t("contextSummary")||"Summary",tokens:d.summary*p,approx:"~"},{key:"messages",label:r.t("contextMessages")||"Messages",tokens:d.messages*p,approx:"~"},{key:"other",label:r.t("contextOther")||"Other",tokens:p<1?0:e.other,approx:"~"},{key:"free",label:r.t("contextFree")||"Free",tokens:Math.max(0,s-h),approx:f}],_=`${f}${i.format(h)} / ${i.format(s)}`,w=c&&c.tokens>0?(r.t("contextReclaim")||"Compacting now would free ~{n} tokens").replace("{n}",()=>i.format(Math.round(c.tokens))):"",S=!!a&&!!c&&this._compact===null,T=V("ul","aparte-context__rows");for(let y of g){let A=V("li","aparte-context__row");A.setAttribute("data-part",y.key),A.append(V("span","aparte-context__row-label",y.label)),A.append(V("span","aparte-context__row-value",`${y.approx}${i.format(Math.round(y.tokens))}`));let x=V("div","aparte-progress aparte-context__row-bar");x.setAttribute("aria-hidden","true"),x.style.setProperty("--aparte-progress-value",String(Math.round(Math.min(1,y.tokens/s)*100))),x.appendChild(V("div","aparte-progress__bar")),A.append(x),T.append(A)}let k=V("li","aparte-context__row aparte-context__row--total");k.setAttribute("data-part","total"),k.append(V("span","aparte-context__row-label",r.t("contextTotal")||"Total"),V("span","aparte-context__row-value",_)),T.append(k);let m=[T];if(this._compact==="running"){let y=V("p","aparte-context__status aparte-shimmer",r.t("checkpointPending")||"Summarising the context\u2026");y.setAttribute("role","status"),m.push(y)}else if(this._compact==="failed"){let y=V("p","aparte-context__status aparte-context__status--failed",r.t("checkpointFailed")||"Couldn't summarise the context");y.setAttribute("role","status"),this._failure&&(y.title=this._failure,y.appendChild(V("span","aparte-sr-only",`: ${this._failure}`))),m.push(y,this._action("retry",r.t("retry")||"Retry"))}w&&m.push(V("p","aparte-context__reclaim",w)),S&&m.push(this._action("compact",r.t("contextCompactNow")||"Compact now"));let v=V("div","aparte-context__content");if(v.append(...m),v.innerHTML===this._panelSignature)return;this._panelSignature=v.innerHTML;let E=document.activeElement,b=E&&t.contains(E)?E.getAttribute("data-context-action")??"":null;t.replaceChildren(...Array.from(v.childNodes)),b!==null&&((b?t.querySelector(`[data-context-action="${tt(b)}"]`):null)??this.querySelector(".aparte-context__toggle"))?.focus()}_action(t,e){let s=V("button","aparte-btn aparte-btn--sm aparte-btn--surface aparte-context__action",e);return s.type="button",s.setAttribute("data-context-action",t),s}async _compactNow(t){let e=this._cfg().getCompactor(),s=this._ownTargetId();if(!e){window.dispatchEvent(new CustomEvent("aparte-compact",{detail:{targetId:s}}));return}this._compact="running",this._failure="",this._render();let i=null;try{let r=await e.compact({target:this._chat(),...s?{targetId:s}:{},force:!0,reason:t});r.ok?r.skipped||(this._viewChanged=!0):i=r.error}catch(r){i=r instanceof Error?r.message:String(r)}this._compact==="running"&&(this._compact=i===null?null:"failed",this._failure=i??""),this.isConnected&&this._render()}_onClick=t=>{let e=t.target,s=e?.closest?.("[data-context-action]");if(s){this._compactNow(s.getAttribute("data-context-action")==="retry"?"retry":"manual");return}e?.closest?.(".aparte-context__panel")||e?.closest?.(".aparte-context")&&this._setOpen(!this._open)};_setOpen(t,e=!1){t!==this._open&&(this._open=t,t?this._listenWhileOpen():this._stopListeningWhileOpen(),this._render(),t?this._place():e&&this.querySelector(".aparte-context__toggle")?.focus())}_onDocumentClick=t=>{t.composedPath().includes(this)||this._setOpen(!1)};_onKeydown=t=>{!this._open||t.key!=="Escape"||(t.preventDefault(),t.stopPropagation(),this._setOpen(!1,!0))};_onDocumentKeydown=t=>{t.key==="Escape"&&this._setOpen(!1,this.contains(document.activeElement))};_listenWhileOpen(){document.addEventListener("click",this._onDocumentClick),document.addEventListener("keydown",this._onDocumentKeydown)}_stopListeningWhileOpen(){document.removeEventListener("click",this._onDocumentClick),document.removeEventListener("keydown",this._onDocumentKeydown)}_place(){let t=this.querySelector(".aparte-context__panel");if(!t)return;t.removeAttribute("data-placement"),t.removeAttribute("data-align");let e=this.getBoundingClientRect(),s=t.getBoundingClientRect();s.height>0&&e.top<s.height&&t.setAttribute("data-placement","below");let r=getComputedStyle(t).direction==="rtl"?s.left<0:s.right>document.documentElement.clientWidth;s.width>0&&r&&t.setAttribute("data-align","end")}};G(On);customElements.get("aparte-context")||customElements.define("aparte-context",On);var un=60,Gh=6,Kh=150,Vh=4,Yh=1,zo=30,Pn=class extends HTMLElement{static get observedAttributes(){return["target","every"]}_host=null;_mutations=null;_resizes=null;_sized=[];_intersections=null;_observedBubbles=[];_bandTargets=[];_observedSurface=null;_frameQueued=!1;_rebuildWanted=!1;_relabel=new Set;_excerpts=new WeakMap;_pickQueued=!1;_currentId=null;_visible=new WeakMap;_onScreen=new WeakSet;_onScreenObserver=null;_held=null;_settleTimer=null;_settleSurface=null;_alignPasses=0;_written=new Map;_onConfigChange=()=>this._rebuild();_onSurfaceScroll=()=>this._bumpSettle();get currentMessageId(){return this._currentId}connectedCallback(){this.classList.contains("aparte-scroll-rail")||this.classList.add("aparte-scroll-rail"),this.getAttribute("role")||this.setAttribute("role","navigation"),this.addEventListener("click",this._onClick),this.addEventListener("keydown",this._onKeydown),this.addEventListener("focusin",this._onFocusIn),this.addEventListener("focusout",this._onFocusOut),window.addEventListener("aparte-config-change",this._onConfigChange),this._attach()}disconnectedCallback(){this._detach(),this.removeEventListener("click",this._onClick),this.removeEventListener("keydown",this._onKeydown),this.removeEventListener("focusin",this._onFocusIn),this.removeEventListener("focusout",this._onFocusOut),window.removeEventListener("aparte-config-change",this._onConfigChange)}attributeChangedCallback(t){this.isConnected&&(t==="target"?this._attach():this._rebuild())}_findHost(){let t=this.getAttribute("target");if(t)return document.getElementById(t);let e=this.parentElement;for(;e;){if(e.tagName.toLowerCase()==="aparte-chat"||e.hasAttribute("data-aparte-chat"))return e;e=e.parentElement}return null}_attach(){if(this._detach(),this._host=this._findHost(),!this._host){this._rebuild();return}typeof MutationObserver<"u"&&(this._mutations=new MutationObserver(t=>{for(let e of t){if(this.contains(e.target))continue;if(e.type==="attributes"){if(sl(e.target)){this._queueRebuild();return}continue}let i=(e.target instanceof Element?e.target:e.target.parentElement)?.closest("aparte-chat-bubble");if(i){this._excerpts.delete(i),this._ticked(i)&&this._queueRelabel(i);continue}if(e.type==="childList"&&(Go(e.addedNodes)||Go(e.removedNodes))){this._queueRebuild();return}}}),this._mutations.observe(this._host,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:["message-id","data-role"]})),typeof ResizeObserver<"u"&&(this._resizes=new ResizeObserver(()=>this._layout())),this._rebuild()}_detach(){this._mutations?.disconnect(),this._mutations=null,this._resizes?.disconnect(),this._resizes=null,this._sized=[],this._relabel.clear(),this._rebuildWanted=!1,this._unobserve(),this._release(),this._host=null}_queueRebuild(){this._rebuildWanted=!0,this._queueFrame()}_queueRelabel(t){this._relabel.add(t),this._queueFrame()}_queueFrame(){this._frameQueued||(this._frameQueued=!0,requestAnimationFrame(()=>{this._frameQueued=!1;let t=[...this._relabel];if(this._relabel.clear(),this._rebuildWanted){this._rebuildWanted=!1,this._rebuild();return}let e=L(this).getLocale();for(let s of t)this._label(s,e)}))}_ticked(t){return t.hasAttribute("message-id")?this.getAttribute("every")==="message"||t.getAttribute("data-role")==="user":!1}_label(t,e){if(!this._host?.contains(t))return;let s=t.getAttribute("message-id");if(!s)return;let i=this.querySelector(`.aparte-scroll-rail__tick[data-message-id="${tt(s)}"]`);if(!i)return;let r=this._tickLabel(t,e);i.getAttribute("aria-label")!==r&&(i.setAttribute("aria-label",r),i.title=r)}_viewport(){return this._host?.querySelector("aparte-chat-viewport")??null}_scrollSurface(){let t=this._viewport();return t?t.querySelector(".aparte-viewport-container")??t:null}_messages(){let t=this._viewport();return t?Array.from(t.querySelectorAll("aparte-chat-bubble[message-id]")):[]}_bubbles(t=this._messages()){return(this.getAttribute("every")==="message"?"message":"user")==="message"?t:t.filter(s=>s.getAttribute("data-role")==="user")}_excerpt(t){let e=this._excerpts.get(t);if(e!==void 0)return e;let s=t.querySelector(".aparte-message-content")??t,i="",r=document.createTreeWalker(s,NodeFilter.SHOW_TEXT);for(let l=r.nextNode();l&&i.length<un*16;l=r.nextNode())i+=l.nodeValue??"";let a=i.slice(0,un*16).replace(/\s+/g," ").trim(),o=a.length>un?`${a.slice(0,un-1).trimEnd()}\u2026`:a;return this._excerpts.set(t,o),o}_tickLabel(t,e){let s=t.getAttribute("data-role")==="user"?e.roleNameUser??"You":e.roleNameAssistant??"Assistant",i=this._excerpt(t);return i?`${s}: ${i}`:s}_list(){return this.querySelector(":scope > .aparte-scroll-rail__list")}_rebuild(){this._watchSizes();let t=this._messages(),e=this._bubbles(t),s=L(this).getLocale(),i=s.scrollRailLabel??"Conversation outline";if(this.getAttribute("aria-label")!==i&&this.setAttribute("aria-label",i),e.length<2){this.setAttribute("data-empty",""),this.replaceChildren(),this._unobserve(),this._currentId=null,this._write("--aparte-scroll-rail-hit-size",""),this._write("--aparte-scroll-rail-gap","");return}this.removeAttribute("data-empty");let r=this._list();r||(r=document.createElement("ol"),r.className="aparte-scroll-rail__list",this.replaceChildren(r));let a=new Map;for(let d of Array.from(r.children)){let h=d.firstElementChild instanceof HTMLElement?d.firstElementChild.dataset.messageId:void 0;h&&a.set(h,d)}let o=new Set(e.map(d=>d.getAttribute("message-id")));for(let[d,h]of a)o.has(d)||(h.remove(),a.delete(d));let l=r.firstElementChild;for(let d of e){let h=d.getAttribute("message-id"),u=a.get(h);if(!u){u=document.createElement("li");let g=document.createElement("button");g.type="button",g.className="aparte-scroll-rail__tick",g.dataset.messageId=h,g.tabIndex=-1,u.appendChild(g)}let p=u.firstElementChild,f=this._tickLabel(d,s);p.getAttribute("aria-label")!==f&&(p.setAttribute("aria-label",f),p.title=f),h===this._currentId?p.getAttribute("aria-current")!=="true"&&p.setAttribute("aria-current","true"):p.removeAttribute("aria-current"),u===l?l=l.nextElementSibling:r.insertBefore(u,l)}let c=this._currentId!==null&&!o.has(this._currentId);c&&(this._currentId=null),this._syncTabStop(),(!mi(this._observedBubbles,e)||!mi(this._bandTargets,t))&&this._observe(e,t),this._layout(),c&&this._pickCurrent()}_observe(t,e){let s=typeof IntersectionObserver>"u"?null:this._scrollSurface();if(!s){this._unobserve(),this._observedBubbles=t,this._bandTargets=e;return}(!this._intersections||!this._onScreenObserver||this._observedSurface!==s)&&(this._unobserve(),this._intersections=new IntersectionObserver(l=>{for(let c of l)this._visible.set(c.target,c.isIntersecting?c.intersectionRatio:0);this._pickCurrent()},{root:s,rootMargin:`0px 0px -${100-zo}% 0px`,threshold:[0,.1,.25,.5,.75,1]}),this._onScreenObserver=new IntersectionObserver(l=>{for(let c of l)c.isIntersecting?this._onScreen.add(c.target):this._onScreen.delete(c.target);this._pickCurrent()},{root:s,threshold:[0]}),this._observedSurface=s,s.addEventListener("scroll",this._onRootScroll,{passive:!0}));let i=new Set(e);for(let l of this._bandTargets)i.has(l)||this._intersections.unobserve(l);let r=new Set(this._bandTargets);for(let l of e)r.has(l)||this._intersections.observe(l);let a=t[t.length-1],o=this._observedBubbles[this._observedBubbles.length-1];o!==a&&(o&&this._onScreenObserver.unobserve(o),this._onScreenObserver.observe(a)),this._observedBubbles=t,this._bandTargets=e}_unobserve(){this._intersections?.disconnect(),this._intersections=null,this._onScreenObserver?.disconnect(),this._onScreenObserver=null,this._observedSurface?.removeEventListener("scroll",this._onRootScroll),this._observedSurface=null,this._observedBubbles=[],this._bandTargets=[],this._visible=new WeakMap,this._onScreen=new WeakSet}_onRootScroll=()=>{this._pickQueued||(this._pickQueued=!0,requestAnimationFrame(()=>{this._pickQueued=!1,this._pickCurrent()}))};_atBottom(){let t=this._observedSurface;if(!t)return!1;let e=t.scrollHeight-t.clientHeight;return e>0&&e-t.scrollTop<=2}_pickCurrent(){if(this._held)return;let t=this._observedBubbles;if(t.length===0)return;let e=t[t.length-1],s=e.getAttribute("message-id");if(this._atBottom()||this._onScreen.has(e)){this._setCurrent(s);return}let i=null,r=null,a=!1;for(let o of this._bandTargets)this._ticked(o)&&(r=o.getAttribute("message-id")),(this._visible.get(o)??0)>0&&(a=!0,r!==null&&(i=r));i===null&&a||(i??=this._lastAbove(),i!==null&&this._setCurrent(i))}_lastAbove(){let t=this._observedSurface,e=this._observedBubbles;if(!t||e.length===0)return null;let s=t.getBoundingClientRect();if(s.height<=0)return null;let i=s.top+s.height*zo/100,r=0,a=e.length-1,o=-1;for(;r<=a;){let l=r+a>>1;e[l].getBoundingClientRect().top<i?(o=l,r=l+1):a=l-1}return o<0?null:e[o].getAttribute("message-id")}_markFor(t){let e=t.getAttribute("message-id");if(this._ticked(t))return e;let s=null;for(let i of this._messages()){if(i===t)break;this._ticked(i)&&(s=i.getAttribute("message-id"))}return s??e}_setCurrent(t){if(this._currentId!==t){this._currentId=t;for(let e of this.querySelectorAll(".aparte-scroll-rail__tick"))e.dataset.messageId===t?(e.setAttribute("aria-current","true"),this._reveal(e)):e.removeAttribute("aria-current");this._syncTabStop()}}_syncTabStop(t=!1){let e=Array.from(this.querySelectorAll(".aparte-scroll-rail__tick"));if(e.length===0)return;let s=t?null:it(this),i=(s instanceof HTMLElement&&e.includes(s)?s:void 0)??e.find(r=>r.dataset.messageId===this._currentId)??e[e.length-1];this._setTabStop(i,e)}_onFocusIn=t=>{let e=t.target instanceof HTMLElement&&t.target.classList.contains("aparte-scroll-rail__tick")?t.target:null;e&&this.contains(e)&&this._setTabStop(e,Array.from(this.querySelectorAll(".aparte-scroll-rail__tick")))};_onFocusOut=t=>{t.relatedTarget instanceof Node&&this.contains(t.relatedTarget)||this._syncTabStop(!0)};_setTabStop(t,e){for(let s of e){let i=s===t?0:-1;s.tabIndex!==i&&(s.tabIndex=i)}}_reveal(t){let e=this.clientHeight;if(!e)return;let s=t.offsetTop,i=s+t.offsetHeight;s<this.scrollTop?this.scrollTop=s:i>this.scrollTop+e&&(this.scrollTop=i-e)}_watchSizes(){if(!this._resizes)return;let t=[];for(let e of[this._host,this._viewport(),this._scrollSurface()])e&&!t.includes(e)&&t.push(e);if(!mi(this._sized,t)){for(let e of this._sized)t.includes(e)||this._resizes.unobserve(e);for(let e of t)this._sized.includes(e)||this._resizes.observe(e);this._sized=t}}_write(t,e){this._written.get(t)!==e&&(this._written.set(t,e),e?this.style.setProperty(t,e):this.style.removeProperty(t))}_layout(){let t=this._host,e=this._viewport(),s=this._scrollSurface();if(t&&s&&this._write("--aparte-scroll-rail-bar",`${Math.max(0,s.offsetWidth-s.clientWidth)}px`),t&&e){let u=e.getBoundingClientRect(),p=t.getBoundingClientRect();u.height>0&&p.height>0&&(this._write("--aparte-scroll-rail-block-start",`${Math.max(0,Math.round(u.top-p.top))}px`),this._write("--aparte-scroll-rail-block-end",`${Math.max(0,Math.round(p.bottom-u.bottom))}px`))}let i=t??document.documentElement,r=getComputedStyle(i),a=parseFloat(r.getPropertyValue("--aparte-scroll-rail-hit-size"))||24,o=parseFloat(r.getPropertyValue("--aparte-scroll-rail-tick-thickness"))||2;(this._written.get("--aparte-scroll-rail-hit-size")??"")!==""&&this.scrollHeight<=this.clientHeight+1&&(this._write("--aparte-scroll-rail-hit-size",""),this._write("--aparte-scroll-rail-gap",""));let c=this.clientHeight,d=this._list()?.children.length??0;if(!d||!c||d*a<=c){this._write("--aparte-scroll-rail-hit-size",""),this._write("--aparte-scroll-rail-gap","");return}let h=Math.max(Gh,Math.floor(c/d));this._write("--aparte-scroll-rail-hit-size",`${h}px`),this._write("--aparte-scroll-rail-gap",`${Math.max(0,h-o)}px`)}_onClick=t=>{let e=t.target.closest(".aparte-scroll-rail__tick");if(!e||!this.contains(e))return;let s=e.dataset.messageId;s&&this.jumpTo(s)};_onKeydown=t=>{if(t.key!=="ArrowDown"&&t.key!=="ArrowUp"&&t.key!=="Home"&&t.key!=="End")return;let e=Array.from(this.querySelectorAll(".aparte-scroll-rail__tick")),s=e.indexOf(it(this));if(s===-1)return;t.preventDefault();let i=t.key==="Home"?0:t.key==="End"?e.length-1:t.key==="ArrowDown"?Math.min(e.length-1,s+1):Math.max(0,s-1),r=e[i];r&&(this._setTabStop(r,e),r.focus())};jumpTo(t){if(!this.dispatchEvent(new CustomEvent("aparte-scroll-rail-jump",{detail:{messageId:t},bubbles:!0,composed:!0,cancelable:!0})))return;let s=this._bubbleOf(t);s&&(this._viewport()?.setAutoScroll?.(!1),this._scrollTo(s),this._setCurrent(this._markFor(s)),this._hold(t))}_bubbleOf(t){return this._viewport()?.querySelector(`aparte-chat-bubble[message-id="${tt(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(),Kh)}_settle(){let t=this._held,e=this._settleSurface,s=t?this._bubbleOf(t):null;if(t&&s&&e&&this._alignPasses<Vh){let i=e.getBoundingClientRect().top+(parseFloat(getComputedStyle(e).scrollPaddingTop)||0),r=s.getBoundingClientRect().top-i;if(Math.abs(r)>Yh){this._alignPasses++,this._scrollTo(s),this._bumpSettle();return}}this._release(),t&&this._setCurrent(s?this._markFor(s):t)}_release(){this._settleTimer!==null&&clearTimeout(this._settleTimer),this._settleTimer=null,this._settleSurface?.removeEventListener("scroll",this._onSurfaceScroll),this._settleSurface=null,this._held=null}};function sl(n){return n instanceof Element&&n.localName==="aparte-chat-bubble"}function Go(n){return Array.from(n).some(t=>t instanceof Element&&(sl(t)||t.localName==="aparte-chat-viewport"||t.querySelector("aparte-chat-bubble")!==null))}function mi(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}G(Pn);customElements.get("aparte-scroll-rail")||customElements.define("aparte-scroll-rail",Pn);var Qh="(max-width: 48rem)",Nn=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;_launcher=null;_launcherWatch=null;_ownHidden=!1;_query="";_listWatch=null;get collapsed(){return this.hasAttribute("collapsed")}set collapsed(t){this.toggleAttribute("collapsed",J(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._launcher=this.closest("aparte-launcher"),this._launcher&&typeof MutationObserver=="function"&&(this._launcherWatch=new MutationObserver(()=>this._followLauncher()),this._launcherWatch.observe(this._launcher,{attributes:!0,attributeFilter:["open","maximized","maximizable"]})),this._watchBreakpoint(),this._syncHidden(),this._lastCollapsed=this.collapsed,this.id||(this.id=`aparte-sidebar-${++Xh}`),this._syncToggles(),this._ready=!0}_watchBreakpoint(){this._media?.removeEventListener("change",this._onMediaChange),this._media=null;let t=(this.getAttribute("breakpoint")??"").trim();if(t!=="none"&&typeof matchMedia=="function"){let e=t?`(max-width: ${t})`:Qh;this._media=matchMedia(e),this._media.addEventListener("change",this._onMediaChange)}else if(t!=="none"&&!this._launcher)return;this._applyDrawer(this._wantsDrawer())}_wantsDrawer(){return(this.getAttribute("breakpoint")??"").trim()==="none"?!1:(this._media?.matches??!1)||this._inCard()}_inCard(){let t=this._launcher;return!t||!this._cardShell()?!1:!(t.hasAttribute("maximized")&&t.getAttribute("maximizable")!=="panel")}_followLauncher(){this._applyDrawer(this._wantsDrawer()),this.drawer&&!this.collapsed&&!this._launcher?.hasAttribute("open")&&(this._opener=null,this.close())}_cardShell(){let t=this._launcher?this.parentElement:null;return t?.classList.contains("aparte-app-shell")?t:null}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._launcherWatch?.disconnect(),this._launcherWatch=null,this._launcher=null,this._scrim?.remove(),this._scrim=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=()=>this._applyDrawer(this._wantsDrawer());_applyDrawer(t){let e=this.drawer;t!==e&&(this._opener=null),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=Ct(this),s=e===document?Array.from(document.querySelectorAll(t)):[...e.querySelectorAll(t),...document.querySelectorAll(t)];for(let i of s)ht(i)||!this._drives(i)||(i.setAttribute("aria-expanded",String(!this.collapsed)),i.setAttribute("aria-controls",this.id))}_drives(t){let e=t.getAttribute("data-aparte-sidebar-toggle");return e?e===this.id:Zh(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(){Ko(this)[0]?.focus()}_syncScrim(){let t=this.drawer&&!this.collapsed;if(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());let e=this._cardShell();e?(this._scrim.classList.add("aparte-sidebar__scrim--contained"),e.appendChild(this._scrim)):this.appendChild(this._scrim)}else!t&&this._scrim&&(this._scrim.remove(),this._scrim=null)}_onKeydown=t=>{if(!(!this.drawer||this.collapsed)){if(t.key==="Escape"){if(t.defaultPrevented)return;t.preventDefault(),this.close();return}if(t.key==="Tab"){let e=Ko(this);if(e.length===0)return;let s=e[0],i=e[e.length-1],r=it(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=at(t)?.closest?.("[data-aparte-sidebar-toggle]");!e||ht(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+=vi(i,Ln(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=Ln(this._query),e=t!==""&&this._lists().every(s=>typeof s.filter=="function"?s.hasAttribute("data-no-match"):!s.hasAttribute("loading")&&vi(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=L(this).getLocale();this.setAttribute("aria-label",t.sidebarLabel??"Conversations"),this.dataset.ownLabel="locale"}},Xh=0,Jh=["a[href]","button:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(",");function Ko(n){return Array.from(n.querySelectorAll(Jh)).filter(t=>!t.closest("[hidden]")&&t.checkVisibility?.()!==!1)}function Zh(n){return n.closest("aparte-sidebar")??n.closest(".aparte-app-shell")?.querySelector("aparte-sidebar")??Ct(n).querySelector("aparte-sidebar")??document.querySelector("aparte-sidebar")}G(Nn);customElements.get("aparte-sidebar")||customElements.define("aparte-sidebar",Nn);function Vo(n,t,e){return Number.isFinite(n)?n<t?t:n>e?e:n:t}function tp(n){let t=Number.isFinite(n.startPercent)?n.startPercent:0;if(!Number.isFinite(n.containerPx)||n.containerPx<=0)return Vo(t,0,100);let i=((!n.vertical&&n.rtl)!==(n.primaryEnd===!0)?-1:1)*n.deltaPx*100/n.containerPx;return Vo(t+i,0,100)}function Yo(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 ep="(max-width: 48rem)",ve=38,np=300;function ye(n,t){let e=Number.parseFloat(n??"");return Number.isFinite(e)?e<0?0:e>100?100:e:t}var Dn=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=ve;_initialPosition=ve;_initialCaptured=!1;_preCollapsePosition=null;_lastPosition=null;_lastCollapsed=null;_lastPane=null;_source="api";_ready=!1;_dragging=!1;_captured=!1;_moved=!1;_pointerId=null;_dragStartPercent=ve;_dragOriginPx=0;_dragContainerPx=0;_keying=!1;get position(){return this._position}set position(t){let e=ye(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",J(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",J(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",J(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=ye(t,ve),this._setLive(this._position)):this._position=ye(getComputedStyle(this).getPropertyValue("--aparte-split-position"),ve),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._endMove?.(),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=ye(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(),this._moveBetweenOneAndTwo();return;case"breakpoint":this._watchBreakpoint();return;case"label":this._relabel()}}get _unmeasurable(){return this.stacked||this.hasAttribute("data-moving")}_endMove=null;_moveBetweenOneAndTwo(){if(this._endMove?.(),!this.isConnected||this.hasAttribute("data-stacked")||this.classList.contains("aparte-split--only-start")||this.classList.contains("aparte-split--only-end")||typeof matchMedia!="function"||matchMedia("(prefers-reduced-motion: reduce)").matches)return;let t=this.orientation==="vertical",e=t?"gridTemplateRows":"gridTemplateColumns",s=t?this.clientHeight:this.clientWidth;if(s<=0)return;this.setAttribute("data-moving","");let i=getComputedStyle(this)[e];if(i.trim().split(/\s+/).length!==3){this.removeAttribute("data-moving");return}let r=this.pane==="end"?"end":"start",a=r==="end"?`0px 0px ${s}px`:`${s}px 0px 0px`,o=this.single,l=i.trim().split(/\s+/),c=this.children[r==="end"?0:2],d=t?"blockSize":"inlineSize",h=t?"alignSelf":"justifySelf",u=c?{size:c.style[d],align:c.style[h]}:null;c&&(c.style[d]=l[r==="end"?0:2],c.style[h]=r==="end"?"end":"start"),this.style[e]=o?i:a,this.offsetWidth,this.setAttribute("data-moving","run"),this.style[e]=o?a:i;let p=null,f=w=>{w.target===this&&w.propertyName.startsWith("grid-template")&&g()},g=()=>{p!==null&&clearTimeout(p),this.removeEventListener("transitionend",f),this.style.removeProperty(t?"grid-template-rows":"grid-template-columns"),c&&u&&(c.style[d]=u.size,c.style[h]=u.align),this.removeAttribute("data-moving"),this._endMove=null,this._measureBounds()};this._endMove=g,this.addEventListener("transitionend",f);let _=Number.parseFloat(getComputedStyle(this).transitionDuration)||0;p=setTimeout(g,_*1e3+120)}_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._unmeasurable)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._unmeasurable)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._unmeasurable||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=tp({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(),np)}}_onDoubleClick=()=>{this.disabled||this._unmeasurable||this.reset()};_onKeydown=t=>{if(this._dragging&&t.key==="Escape"){t.preventDefault(),this._endDrag("pointer",this._dragStartPercent);return}if(this.disabled||this._unmeasurable||t.target!==this._handle)return;if(t.key==="Enter"){t.preventDefault(),this._source="keyboard";try{this.toggleCollapse()}finally{this._source="api"}return}let e=Yo(t.key,t.shiftKey,this._rtl(),this.orientation==="vertical",this.primary==="end");e!==null&&(t.preventDefault(),this._keying=!0,this._position=ye(String(this._position+e),this._position),this._setLive(this._position))};_onKeyup=t=>{!this._keying||t.target!==this._handle||Yo(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})`:ep;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=at(t)?.closest?.("[data-aparte-split-pane]");if(!e||ht(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")??Ct(e).querySelector("aparte-split")??document.querySelector("aparte-split"))!==this)return;this.showPane(i??(this.pane==="start"?"end":"start"))};_syncPaneControls(){let t=new Set([Ct(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"||ht(s)||(s.closest("aparte-split")??Ct(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=L(this).getLocale();t.setAttribute("aria-label",this.getAttribute("label")??e.splitHandleLabel??"Resize the panes"),t.dataset.ownLabel="locale"}};G(Dn);customElements.get("aparte-split")||customElements.define("aparte-split",Dn);var sp="(max-width: 30rem), (max-height: 30rem)",ip=["a[href]","button:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(","),Bn=class n extends HTMLElement{static get observedAttributes(){return["open","label","breakpoint","header","heading","subheading","maximizable","maximized"]}_button=null;_header=null;_avatar=null;_avatarDrawnBy=null;_avatarCleanup=null;_title=null;_subtitle=null;_maximize=null;_closeControl=null;_childWatch=null;_hostWatch=null;_media=null;_lastOpen=null;_ready=!1;get open(){return this.hasAttribute("open")}set open(t){this.toggleAttribute("open",J(t))}get sheet(){return this.hasAttribute("data-sheet")}get maximized(){return this.hasAttribute("maximized")}set maximized(t){this.toggleAttribute("maximized",J(t))}get covers(){if(!this.open)return!1;if(this.sheet)return!0;if(!this.maximized)return!1;if(!this._panel)return!0;let t=this.getBoundingClientRect().width;return t>0&&t>=document.documentElement.clientWidth-1}get _panel(){return this.getAttribute("maximizable")==="panel"}get header(){return this.getAttribute("header")!=="false"}set header(t){t===!1||t==="false"?this.setAttribute("header","false"):this.removeAttribute("header")}connectedCallback(){if(this.classList.contains("aparte-launcher")||this.classList.add("aparte-launcher"),!this._button){let t=this.querySelector(":scope > button.aparte-launcher__button");this._button=t instanceof HTMLButtonElement?t:document.createElement("button"),this._button.type="button",this._button.addEventListener("click",this._onButtonClick)}for(let t of this.querySelectorAll(":scope > .aparte-launcher__button, :scope > .aparte-launcher__header"))t!==this._button&&t!==this._header&&t.remove();this._button.parentNode!==this&&this.appendChild(this._button),typeof MutationObserver=="function"&&(this._childWatch??=new MutationObserver(t=>{t.some(e=>e.target===this||n._touchesParts(e))&&this._onChildren()}),this._childWatch.observe(this,{childList:!0,subtree:!0}),this._hostWatch??=new MutationObserver(()=>this._render()),this._hostWatch.observe(this,{attributes:!0,attributeFilter:[fe],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._render(),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._clearAvatar(),this._ready=!1}attributeChangedCallback(t,e,s){if(!this._ready)return;if(t==="breakpoint"){this._watchBreakpoint();return}if(this._render(),t==="maximized"){e===null!=(s===null)&&this._announce();return}if(t==="maximizable"){this.open&&this.maximized&&e==="panel"!=(s==="panel")&&this._announce();return}if(t!=="open")return;let i=this.open;i!==this._lastOpen&&(this._lastOpen=i,!i&&this._button&&this.contains(it(this))&&this._button.focus(),this._announce())}_announce(){this.dispatchEvent(new CustomEvent("aparte-launcher-toggle",{detail:{open:this.open,sheet:this.sheet,maximized:this.maximized,covers:this.covers},bubbles:!0,composed:!0}))}show(){this.open=!0}close(){this.open=!1}toggle(){this.open=!this.open}maximize(){this.maximized=!0}restore(){this.maximized=!1}_onButtonClick=()=>{let t=!this.open;this.toggle(),t&&this._focusChat()};_onConfigChange=()=>this._render();_render(){let t=this._config();this._renderButton(t),this._renderHeader(t),this._syncMaximizeControls()}_onChildren(){this._keepButton(),this._renderHeader(this._config()),this._syncMaximizeControls()}_config(){let t=Array.from(this.querySelectorAll(`[${fe}]`)).find(e=>!ht(e));return L(t??this)}_keepButton(){this._button&&this._button.parentNode!==this&&this.appendChild(this._button)}_renderButton(t){let e=this._button;if(!e)return;this._keepButton();let s=t.getLocale(),i=this.open,r=i?"":(this.getAttribute("label")??"").trim(),a=r?"aparte-btn--pill":"aparte-btn--circle";e.className=["aparte-btn","aparte-btn--primary","aparte-btn--solid","aparte-btn--lg",a,"aparte-launcher__button"].join(" "),e.setAttribute("aria-expanded",String(i)),r?e.removeAttribute("aria-label"):e.setAttribute("aria-label",i?s.launcherClose??"Close the chat":s.launcherOpen??"Open the chat");let o=[n._glyph(i?t.getIcon("launcherClose")??t.getIcon("close"):t.getIcon("launcherOpen")??t.getIcon("messageSquare"))];if(r){let l=document.createElement("span");l.className="aparte-launcher__label",l.textContent=r,o.push(l)}e.replaceChildren(...o)}static _glyph(t){let e=document.createElement("span");return e.className="aparte-launcher__icon",e.setAttribute("aria-hidden","true"),e.innerHTML=t,e}_cardHasHeader(){return Array.from(this.children).some(t=>t!==this._button&&t!==this._header&&t.querySelector(":scope > header")!==null)}static _touchesParts(t){let e="header, [data-aparte-launcher-maximize]";return[...t.addedNodes,...t.removedNodes].some(s=>s instanceof Element&&(s.matches(e)||s.querySelector(e)!==null))}static _headerButton(t){let e=document.createElement("button");return e.type="button",e.className=`aparte-btn aparte-btn--icon aparte-btn--ghost aparte-launcher__${t}`,e}static _name(t,e,s){t.setAttribute("aria-label",e),t.setAttribute("title",e),t.replaceChildren(n._glyph(s))}_buildHeader(){let t=document.createElement("div");t.className="aparte-app-header aparte-launcher__header",this._avatar=document.createElement("span"),this._avatar.className="aparte-avatar aparte-launcher__avatar",this._avatar.setAttribute("data-role","assistant"),this._avatar.setAttribute("aria-hidden","true");let e=document.createElement("div");e.className="aparte-launcher__heading",this._title=document.createElement("span"),this._title.className="aparte-app-header__title aparte-launcher__title",this._title.setAttribute("role","heading"),this._title.setAttribute("aria-level","2"),this._subtitle=document.createElement("span"),this._subtitle.className="aparte-launcher__subheading",e.append(this._title,this._subtitle);let s=document.createElement("div");return s.className="aparte-app-header__actions",this._maximize=n._headerButton("maximize"),this._maximize.setAttribute("data-aparte-launcher-maximize",""),this._closeControl=n._headerButton("close"),this._closeControl.setAttribute("data-aparte-launcher-close",""),s.append(this._maximize,this._closeControl),t.append(this._avatar,e,s),t}_renderHeader(t){if(!this.header||this._cardHasHeader()){let l=!!this._header?.contains(it(this));this._clearAvatar(),this._header?.remove(),l&&(this._focusTarget()??this._button)?.focus();return}let e=this._header??=this._buildHeader(),s=t.getLocale(),i=(this.getAttribute("label")??"").trim(),r=(this.getAttribute("heading")??(i||(s.launcherHeading??"Chat"))).trim();this._title.textContent=r,this._title.hidden=!r,this._drawAvatar(t);let a=(this.getAttribute("subheading")??"").trim();this._subtitle.textContent=a,this._subtitle.hidden=!a;let o=this._maximize;o.hidden=!this.hasAttribute("maximizable"),n._name(o,this.maximized?s.launcherRestore??"Shrink the chat":s.launcherMaximize??"Expand the chat",t.getIcon(this.maximized?"minimize":"maximize")),n._name(this._closeControl,s.launcherClose??"Close the chat",t.getIcon("close")),this.firstElementChild!==e&&this.prepend(e),this._markAvatarImage()}_drawAvatar(t){let e=t.getAvatarProvider();if(e!==this._avatarDrawnBy&&(this._clearAvatar(),!(!e||!this._avatar))){this._avatarDrawnBy=e;try{let s=e.render("assistant",this._avatar);typeof s=="function"&&(this._avatarCleanup=s)}catch(s){this._avatar.replaceChildren(),console.error("[aparte] The avatar provider failed for the launcher's header, which shows no avatar. It is called with a host outside any message there.",s)}}}_markAvatarImage(){let t=this._avatar;if(!t)return;let e=typeof getComputedStyle=="function"?getComputedStyle(t).backgroundImage:"";t.toggleAttribute("data-image",!t.firstChild&&!!e&&e!=="none")}_clearAvatar(){try{this._avatarCleanup?.()}catch{}this._avatarCleanup=null,this._avatarDrawnBy=null,this._avatar?.replaceChildren()}_syncMaximizeControls(){let t=String(this.maximized);for(let e of this.querySelectorAll("[data-aparte-launcher-maximize]"))e===this._maximize||ht(e)||e.setAttribute("aria-pressed",t)}_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})`:sp),this._media.addEventListener("change",this._onMediaChange),this._applySheet(this._media.matches)}_applySheet(t){if(t===this.sheet)return;this.toggleAttribute("data-sheet",t);let e=it(this);t&&e?.matches("[data-aparte-launcher-maximize]")&&this.contains(e)&&(this._closeControl?.isConnected?this._closeControl:this._focusTarget())?.focus(),this._ready&&this.open&&this._announce()}_focusables(){return Array.from(this.querySelectorAll(ip)).filter(t=>!t.closest("[hidden]")&&t.checkVisibility?.()!==!1)}_focusChat(){this._focusTarget()?.focus()}_focusTarget(){return Array.from(this.querySelectorAll('[role="textbox"]:not([aria-disabled="true"])')).find(e=>!ht(e)&&!e.closest("[hidden]")&&e.checkVisibility?.()!==!1)??this._focusables().find(e=>e!==this._button&&!this._header?.contains(e))??(this.covers&&this._closeControl?.isConnected?this._closeControl:void 0)}_onClick=t=>{let e=at(t),s=i=>{let r=e?.closest?.(i);return!!r&&this.contains(r)&&!ht(r)};s("[data-aparte-launcher-close]")?this.close():s("[data-aparte-launcher-maximize]")&&(this.maximized=!this.maximized)};_inModalDialog(t){let e=at(t)?.closest?.("dialog[open]");if(!e||!this.contains(e))return!1;try{return e.matches(":modal")}catch{return!0}}_drawerOpen(){return this.querySelector("aparte-sidebar[data-drawer]:not([collapsed])")!==null}_onKeydown=t=>{if(!this.open)return;if(t.key==="Escape"){if(t.defaultPrevented||t.isComposing||t.keyCode===229||this._inModalDialog(t)||this._drawerOpen())return;t.preventDefault(),this.maximized&&!this.sheet?this.maximized=!1:this.close();return}if(t.key!=="Tab"||!this.covers)return;let e=this._focusables();if(e.length===0)return;let s=e[0],i=e[e.length-1],r=it(this);t.shiftKey&&r===s?(t.preventDefault(),i.focus()):!t.shiftKey&&r===i&&(t.preventDefault(),s.focus())}};G(Bn);customElements.get("aparte-launcher")||customElements.define("aparte-launcher",Bn);var Qo=Symbol.for("aparte.imageHolds"),il=".aparte-image-held[data-aparte-image]";function rl(n){let t=n.getAttribute("data-aparte-image")??"";L(n).showImage(t);let e=document.createElement("img");e.setAttribute("referrerpolicy","no-referrer"),e.setAttribute("alt",n.getAttribute("data-aparte-image-alt")??""),e.setAttribute("src",t);let s=n===document.activeElement;n.replaceWith(e),s&&(e.tabIndex=-1,e.focus({preventScroll:!0}))}function rp(n){if(n.button!==0||n.ctrlKey||n.metaKey||n.shiftKey||n.altKey)return;let t=n.target?.closest?.(il);t&&(n.preventDefault(),n.stopPropagation(),rl(t))}function ap(n){if(n.key!=="Enter"&&n.key!==" ")return;let t=n.target;t?.matches?.(`span${il}`)&&(n.preventDefault(),n.stopPropagation(),rl(t))}function op(){let n=document;n[Qo]||(n[Qo]=!0,n.addEventListener("click",rp,!0),n.addEventListener("keydown",ap,!0))}typeof document<"u"&&(Eo(),op());export{tt as a,z as b,lt as c,X as d,_c as e,L as f,I as g,se as h,Gd as i,ce as j,et as k,qu as l,Ao as m,Rs as n};
216
+ //# sourceMappingURL=chunk-NB75PIC5.js.map