@aparte/n8n-chat 1.1.3 → 1.1.5

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 (88) hide show
  1. package/README.md +2 -2
  2. package/dist/cdn/chunks/chunk-2CZ4DUEZ.js +348 -0
  3. package/dist/cdn/chunks/chunk-2CZ4DUEZ.js.map +7 -0
  4. package/dist/cdn/chunks/{chunk-DVXCH3I6.js → chunk-55VOWNT6.js} +2 -2
  5. package/dist/cdn/chunks/{chunk-DVXCH3I6.js.map → chunk-55VOWNT6.js.map} +1 -1
  6. package/dist/cdn/chunks/{chunk-7CVHIGBT.js → chunk-AHSQRRBO.js} +1 -1
  7. package/dist/cdn/chunks/{chunk-7CVHIGBT.js.map → chunk-AHSQRRBO.js.map} +1 -1
  8. package/dist/cdn/chunks/chunk-KVLHKDQP.js +219 -0
  9. package/dist/cdn/chunks/chunk-KVLHKDQP.js.map +7 -0
  10. package/dist/cdn/chunks/chunk-KZEZHYPR.js +2 -0
  11. package/dist/cdn/chunks/chunk-KZEZHYPR.js.map +7 -0
  12. package/dist/cdn/chunks/{chunk-BANM7TF4.js → chunk-TYYJIAB7.js} +2 -2
  13. package/dist/cdn/chunks/{chunk-BANM7TF4.js.map → chunk-TYYJIAB7.js.map} +1 -1
  14. package/dist/cdn/chunks/de-X45NRNZ5.js +2 -0
  15. package/dist/cdn/chunks/de-X45NRNZ5.js.map +7 -0
  16. package/dist/cdn/chunks/es-2AVNLQ2Y.js +2 -0
  17. package/dist/cdn/chunks/es-2AVNLQ2Y.js.map +7 -0
  18. package/dist/cdn/chunks/fr-HWUWJ6FI.js +2 -0
  19. package/dist/cdn/chunks/fr-HWUWJ6FI.js.map +7 -0
  20. package/dist/cdn/chunks/{highlight-WUBGCB6T.js → highlight-2226PMH7.js} +2 -2
  21. package/dist/cdn/chunks/{highlight-WUBGCB6T.js.map → highlight-2226PMH7.js.map} +1 -1
  22. package/dist/cdn/chunks/it-DXC3TFUG.js +2 -0
  23. package/dist/cdn/chunks/it-DXC3TFUG.js.map +7 -0
  24. package/dist/cdn/chunks/{items-HIWE3HWO.js → items-KA6UG7UB.js} +2 -2
  25. package/dist/cdn/chunks/{items-HIWE3HWO.js.map → items-KA6UG7UB.js.map} +3 -3
  26. package/dist/cdn/chunks/ja-QVEXWZED.js +2 -0
  27. package/dist/cdn/chunks/ja-QVEXWZED.js.map +7 -0
  28. package/dist/cdn/chunks/ko-FJHIEJTH.js +2 -0
  29. package/dist/cdn/chunks/ko-FJHIEJTH.js.map +7 -0
  30. package/dist/cdn/chunks/{link-5HWNRD4B.js → link-LUXU47TW.js} +2 -2
  31. package/dist/cdn/chunks/{link-5HWNRD4B.js.map → link-LUXU47TW.js.map} +3 -3
  32. package/dist/cdn/chunks/{media-XHJCFMC4.js → media-GLJZTR44.js} +2 -2
  33. package/dist/cdn/chunks/{media-XHJCFMC4.js.map → media-GLJZTR44.js.map} +3 -3
  34. package/dist/cdn/chunks/{order-PIE7QNLP.js → order-WI6VVEB5.js} +2 -2
  35. package/dist/cdn/chunks/{order-PIE7QNLP.js.map → order-WI6VVEB5.js.map} +3 -3
  36. package/dist/cdn/chunks/{place-GKVCEFBR.js → place-Z75X4ZVV.js} +2 -2
  37. package/dist/cdn/chunks/{place-GKVCEFBR.js.map → place-Z75X4ZVV.js.map} +3 -3
  38. package/dist/cdn/chunks/{plan-5JXNANL7.js → plan-JJIJPX4I.js} +15 -4
  39. package/dist/cdn/chunks/plan-JJIJPX4I.js.map +7 -0
  40. package/dist/cdn/chunks/{product-WYDFOB3I.js → product-27BHLY34.js} +2 -2
  41. package/dist/cdn/chunks/{product-WYDFOB3I.js.map → product-27BHLY34.js.map} +3 -3
  42. package/dist/cdn/chunks/pt-BR-FMN3UR7Y.js +2 -0
  43. package/dist/cdn/chunks/pt-BR-FMN3UR7Y.js.map +7 -0
  44. package/dist/cdn/chunks/ru-XBZSSRMG.js +2 -0
  45. package/dist/cdn/chunks/ru-XBZSSRMG.js.map +7 -0
  46. package/dist/cdn/chunks/{score-VCBT3P7K.js → score-E6Y5C5PW.js} +2 -2
  47. package/dist/cdn/chunks/{score-VCBT3P7K.js.map → score-E6Y5C5PW.js.map} +3 -3
  48. package/dist/cdn/chunks/{stats-GDG2ICQL.js → stats-543ZWJYT.js} +2 -2
  49. package/dist/cdn/chunks/{stats-GDG2ICQL.js.map → stats-543ZWJYT.js.map} +3 -3
  50. package/dist/cdn/chunks/{stock-XSN3A64Q.js → stock-WIQ6EGG4.js} +4 -13
  51. package/dist/cdn/chunks/stock-WIQ6EGG4.js.map +7 -0
  52. package/dist/cdn/chunks/{weather-5MVHTOM3.js → weather-QMIQG7YG.js} +2 -2
  53. package/dist/cdn/chunks/{weather-5MVHTOM3.js.map → weather-QMIQG7YG.js.map} +3 -3
  54. package/dist/cdn/chunks/zh-CN-43X3LUWX.js +2 -0
  55. package/dist/cdn/chunks/zh-CN-43X3LUWX.js.map +7 -0
  56. package/dist/cdn/latest.js +4 -4
  57. package/dist/cdn/n8n-chat.js +46 -46
  58. package/dist/cdn/n8n-chat.js.map +4 -4
  59. package/dist/index.js +1 -0
  60. package/dist/index.js.map +1 -1
  61. package/dist/style.css +1 -1
  62. package/package.json +7 -7
  63. package/dist/cdn/chunks/chunk-NB75PIC5.js +0 -216
  64. package/dist/cdn/chunks/chunk-NB75PIC5.js.map +0 -7
  65. package/dist/cdn/chunks/chunk-OAAYQOXW.js +0 -2
  66. package/dist/cdn/chunks/chunk-OAAYQOXW.js.map +0 -7
  67. package/dist/cdn/chunks/chunk-RA5GYKIJ.js +0 -379
  68. package/dist/cdn/chunks/chunk-RA5GYKIJ.js.map +0 -7
  69. package/dist/cdn/chunks/de-TEGH2VNR.js +0 -2
  70. package/dist/cdn/chunks/de-TEGH2VNR.js.map +0 -7
  71. package/dist/cdn/chunks/es-UNEXO3AX.js +0 -2
  72. package/dist/cdn/chunks/es-UNEXO3AX.js.map +0 -7
  73. package/dist/cdn/chunks/fr-UZ7335OR.js +0 -2
  74. package/dist/cdn/chunks/fr-UZ7335OR.js.map +0 -7
  75. package/dist/cdn/chunks/it-PI5TOT4E.js +0 -2
  76. package/dist/cdn/chunks/it-PI5TOT4E.js.map +0 -7
  77. package/dist/cdn/chunks/ja-6Q7BHA5Q.js +0 -2
  78. package/dist/cdn/chunks/ja-6Q7BHA5Q.js.map +0 -7
  79. package/dist/cdn/chunks/ko-BMFWR3RO.js +0 -2
  80. package/dist/cdn/chunks/ko-BMFWR3RO.js.map +0 -7
  81. package/dist/cdn/chunks/plan-5JXNANL7.js.map +0 -7
  82. package/dist/cdn/chunks/pt-BR-2WMTMMJ3.js +0 -2
  83. package/dist/cdn/chunks/pt-BR-2WMTMMJ3.js.map +0 -7
  84. package/dist/cdn/chunks/ru-L4NHDBS2.js +0 -2
  85. package/dist/cdn/chunks/ru-L4NHDBS2.js.map +0 -7
  86. package/dist/cdn/chunks/stock-XSN3A64Q.js.map +0 -7
  87. package/dist/cdn/chunks/zh-CN-232EGCJD.js +0 -2
  88. package/dist/cdn/chunks/zh-CN-232EGCJD.js.map +0 -7
@@ -0,0 +1,219 @@
1
+ function Ti(){let s=[],t=!1,e=()=>{let i=s.shift();i?i():t=!1},n=()=>{let i=!1;return()=>{i||(i=!0,e())}};return()=>t?new Promise(i=>{s.push(()=>i(n()))}):(t=!0,n())}function fl(s,t){let e=n=>{let i=t(),r=a=>()=>{a(),n()};return typeof i=="function"?r(i):i.then(r)};return()=>{let n=s();return typeof n=="function"?e(n):n.then(e)}}var Ii=Symbol("aparte.approvalGate");function gl(s){return s?.[Ii]}function _l(s,t){let e=async(n,i)=>{let r=s(),a=typeof r=="function"?r:await r;try{return await t(n,i)}finally{a()}};return e[Ii]={turn:s,ask:t},e}var ml=300*1e3,bl=10,xi=new Set;function vl(s){let t=String(s?.type??"undefined");xi.has(t)||(xi.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 Gn(s){let{transportCall:t,toolLookup:e,toolConfigLookup:n,emitter:i,signal:r,maxTurns:a=bl,toolTimeoutMs:o=ml,deferral:l,parallelTools:c=!0}=s,d=s.baseRequest,h=0,u=s.idGen??(S=>`${S}-${h++}`),p=Cl(i,u,r,o),f=gl(s.approvalResolver),g=f?fl(Ti(),f.turn):Ti(),_=f?f.ask:s.approvalResolver,y={emitter:i,canAsk:!l&&_!==void 0,canBackground:!l,transportCall:t,toolLookup:e,toolConfigLookup:n,approvalResolver:c&&_?_l(g,_):_,maxTurns:a,toolTimeoutMs:o,parallelTools:c,idGen:u,background:p},b=[...d.messages],k=S=>{b.push(S),s.onHistoryAppend?.(S)},x=!0,v=0,E,A;i({type:"run-start"});try{return await w()}finally{p.close()}async function w(){let S=l?Li(b):[];if(S.length>0){let O=[],C={turns:1,maxTurns:a,toolLookup:e,toolConfigLookup:n,approvalResolver:_,approvalTurn:g,emitter:i,signal:r,toolTimeoutMs:o,declareCall:()=>{},append:k,deferral:l,runBase:y};for(let[N,D]of S.entries()){if(O.length>0){O.push({toolCallId:D.id,name:D.name,input:D.input,reason:Wn(D,n)});continue}let H;try{H=await jn(D,C)}catch(tt){for(let rt of S.slice(N+1))i({type:"tool-aborted",toolCallId:rt.id});throw tt}if(typeof H=="object"){O.push({toolCallId:D.id,name:D.name,input:D.input,reason:H.defer});continue}if(H==="stop-run"){for(let tt of S.slice(N+1))i({type:"tool-aborted",toolCallId:tt.id});x=!1;break}}if(O.length>0&&!r.aborted){p.stopAll(),i({type:"run-suspended",pending:O});return}}for(;x&&!r.aborted;){if(v++,A=void 0,v>a){i({type:"turn-limit-exceeded",scope:"global",limit:a});break}let O=d.toolChoice;if(v===1&&O&&typeof O=="object"&&!Array.isArray(O)&&O.input!==void 0){let F=O,B=u("synthetic-tool");i({type:"tool-start",toolCallId:B,name:F.name,input:F.input});let kt=e(F.name);if(!kt){i({type:"tool-aborted",toolCallId:B,cause:"no-handler"}),x=!1;continue}let K=await Oi(kt,{id:B,name:F.name,input:F.input},r,o,y);if(K.status==="aborted"){i(K.cause?{type:"tool-aborted",toolCallId:B,cause:K.cause}:{type:"tool-aborted",toolCallId:B}),x=!1;continue}if(K.status==="failed")throw i({type:"tool-failed",toolCallId:B,error:Kn(K.error)}),K.error;i({type:"tool-resolved",toolCallId:B,result:K.content,structuredResult:K.structuredContent}),k({role:"assistant",content:"",toolCalls:[{id:B,name:F.name,input:F.input}]}),k({role:"tool",content:K.content,toolCallId:B,toolName:F.name}),d={...d,toolChoice:"none",tools:void 0}}let C={...d,messages:b},N=d.toolChoice;N&&typeof N=="object"&&(d={...d,toolChoice:"auto"});let D;try{D=await t(C)}catch(F){if(r.aborted||F?.name==="AbortError"){x=!1;break}throw F}if(typeof D=="string"){if(i({type:"turn-start"}),i({type:"text-delta",delta:D}),i({type:"text-flush"}),await m(D))continue;break}i({type:"turn-start"});let H="",tt=[],rt=!1,gt=null,te=F=>{tt.push(F),!gt&&(gt={role:"assistant",content:H.trim(),toolCalls:tt},k(gt))},T=()=>{gt&&(gt.content=H.trim())},R=new Set,q=F=>{let B=F;for(let kt=2;R.has(B);kt++)B=`${F}#${kt}`;return R.add(B),B},$=[],X={turns:v,maxTurns:a,toolLookup:e,toolConfigLookup:n,approvalResolver:_,approvalTurn:g,emitter:i,signal:r,toolTimeoutMs:o,declareCall:te,append:k,deferral:l&&{...l,outcomes:void 0},runBase:y},U=c?yl(X):void 0,ut=!1,at=D[Symbol.asyncIterator](),et=async()=>{if(!r.aborted)return!1;try{await at.return?.(void 0)}catch{}return x=!1,!0};try{for(;!(await et()||U?.halted());){let F;try{let Et=at.next();if(U?.busy()){let Ei=await Promise.race([Et,U.onHalt.then(()=>Mi)]);if(Ei===Mi){ut=!0,Promise.resolve(Et).catch(()=>{});break}F=Ei}else F=await Et}catch(Et){if(await et())break;throw Et}if(await et()||U?.halted()||F.done)break;let B=F.value;if(B.type==="thinking"){i({type:"thinking-delta",delta:B.delta});continue}if(B.type==="text"){H+=B.delta,i({type:"text-delta",delta:B.delta});continue}if(B.type==="sources"){i({type:"sources",sources:B.sources,...B.citations?{citations:B.citations}:{}});continue}if(B.type==="step-start"||B.type==="step-end"){i({type:B.type,name:B.name});continue}if(B.type==="activity"){i({type:"activity",id:B.id,activityType:B.activityType,content:B.content});continue}if(B.type==="done"){B.usage&&(E=B.usage),B.finishReason&&(A=B.finishReason);continue}if(B.type==="error")throw B.code===void 0?new Error(B.message):Object.assign(new Error(B.message),{code:B.code});if(B.type!=="tool_use"){vl(B);continue}rt=!0;let kt=q(B.id),K={id:kt,name:B.name,input:B.input};if(U){U.start(K);continue}if(i({type:"tool-start",toolCallId:kt,name:B.name,input:B.input,...$.length>0?{queued:!0}:{}}),$.length>0){te(K);let Et=Wn(K,n);Et==="approval"&&i({type:"tool-awaiting-approval",toolCallId:K.id,name:K.name,input:K.input}),$.push({toolCallId:K.id,name:K.name,input:K.input,reason:Et});continue}let Te=await jn(K,X);if(typeof Te=="object"){te(K),$.push({toolCallId:K.id,name:K.name,input:K.input,reason:Te.defer});continue}if(Te==="stop-run"){x=!1;break}if(Te==="stop-turn")break}if(U){let F=await U.finish();if(F.failure)throw F.failure.error;$.push(...F.pending),F.stopRun&&(x=!1)}i({type:"text-flush"}),T()}finally{try{let F=at.return?.(void 0);ut?Promise.resolve(F).catch(()=>{}):await F}catch{}U&&await U.abandon()}if($.length>0&&!r.aborted)return p.stopAll(),i({type:"run-suspended",pending:$,usage:E}),E;!rt&&!await m(H)&&(x=!1)}return p.stopAll(),r.aborted&&i({type:"run-aborted"}),i({type:"run-done",usage:E,...A?{finishReason:A}:{}}),E}async function m(S){if(r.aborted||!p.pending())return!1;if(v>=a)return p.stopAll(),i({type:"turn-limit-exceeded",scope:"global",limit:a}),!1;if(await p.settled(),r.aborted)return!1;let O=p.report();if(!O)return!1;let C=S.trim();return C&&k({role:"assistant",content:C}),k({role:"user",content:O}),!0}}function Li(s){for(let t=s.length-1;t>=0;t--){let e=s[t];if(e.role==="assistant"){if(!e.toolCalls?.length)return[];let n=new Set(s.slice(t+1).filter(i=>i.role==="tool").map(i=>i.toolCallId));return e.toolCalls.filter(i=>!n.has(i.id))}if(e.role!=="tool")return[]}return[]}function Wn(s,t){let e=t?.(s.name);if(e?.external)return"external";let n=typeof e?.needsApproval=="function"?e.needsApproval({id:s.id,name:s.name,input:s.input}):e?.needsApproval;return n&&n!=="deny"?"approval":"queued"}function _t(s,t){return s.decided?.(t),t}function Ri(s){let t=s.reason?.trim(),e=s.by??(t?"policy":"person"),n=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.":s.instruction?`The user rejected this tool call and said: ${s.instruction}`:"Tool execution was rejected by the user.");return s.instruction?{reason:n,by:e,instruction:s.instruction}:{reason:n,by:e}}function Un(s,t,e){let n=Ri(e);return s.emitter({type:"tool-rejected",toolCallId:t.id,...n}),s.declareCall(t),s.append({role:"tool",content:n.reason,toolCallId:t.id,toolName:t.name}),_t(s,"stop-turn")}async function jn(s,t){let{signal:e}=t,n=s.input,i=t.toolConfigLookup?.(s.name),r=t.deferral?.outcomes?.[s.id];if(r?.kind==="decision"&&!r.approved)return Un(t,s,r);let a=i?.maxTurns??t.maxTurns;if(t.turns>a)return t.emitter({type:"turn-limit-exceeded",scope:"tool",limit:a,toolCallId:s.id}),_t(t,"stop-run");if(i?.external){if(!t.deferral)return t.emitter({type:"tool-aborted",toolCallId:s.id,cause:"no-handler"}),_t(t,"stop-run");if(!r||r.kind==="decision")return _t(t,{defer:"external"});if(r.kind==="failed")throw t.emitter({type:"tool-failed",toolCallId:s.id,error:r.error}),new Error(r.error);return t.emitter({type:"tool-resolved",toolCallId:s.id,result:r.content,structuredResult:r.structuredContent}),t.declareCall(s),t.append({role:"tool",content:r.content,toolCallId:s.id,toolName:s.name}),"continue"}let o=t.toolLookup(s.name);if(!o)return t.emitter({type:"tool-aborted",toolCallId:s.id,cause:"no-handler"}),_t(t,"stop-run");let l=s.input,c=typeof i?.needsApproval=="function"?i.needsApproval({id:s.id,name:s.name,input:n}):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:s.id,cause:"stopped"}),_t(t,"stop-run")}let p=h;try{if(c!=="deny"&&!h&&t.emitter({type:"tool-awaiting-approval",toolCallId:s.id,name:s.name,input:s.input}),!h&&t.deferral&&c!=="deny")return _t(t,{defer:"approval"});if(!h&&!t.approvalResolver)return t.emitter({type:"tool-aborted",toolCallId:s.id,cause:"no-resolver"}),_t(t,"stop-run");if(!p&&!e.aborted&&t.approvalResolver)try{p=await t.approvalResolver({id:s.id,name:s.name,input:n},e)}catch(f){if(!e.aborted&&f?.name!=="AbortError")throw f}}finally{u?.()}if(e.aborted||!p)return t.emitter({type:"tool-aborted",toolCallId:s.id,cause:"stopped"}),_t(t,"stop-run");if(!p.approved)return Un(t,s,p),"stop-turn";p.payload&&typeof p.payload=="object"&&!Array.isArray(p.payload)&&(l={...n,...p.payload}),t.emitter({type:"tool-approved",toolCallId:s.id}),t.asking?.(!1)}let d=await Oi(o,{id:s.id,name:s.name,input:l},e,t.toolTimeoutMs,t.runBase);if(d.status==="aborted")return t.emitter(d.cause?{type:"tool-aborted",toolCallId:s.id,cause:d.cause}:{type:"tool-aborted",toolCallId:s.id}),_t(t,"stop-run");if(d.status==="failed")throw t.emitter({type:"tool-failed",toolCallId:s.id,error:Kn(d.error)}),d.error;return t.emitter({type:"tool-resolved",toolCallId:s.id,result:d.content,structuredResult:d.structuredContent}),t.declareCall(s),t.append({role:"tool",content:d.content,toolCallId:s.id,toolName:s.name}),"continue"}var Mi=Symbol("halted");function yl(s){let t=new AbortController,e=()=>t.abort();s.signal.aborted?t.abort():s.signal.addEventListener("abort",e,{once:!0});let n=[],i=[],r=0,a=0,o=!1,l=!1,c=!1,d=!1,h,u,p=new Promise(w=>{u=w}),f=()=>{for(;r<n.length&&n[r].settled;){let w=n[r++];w.declared&&!(d&&w.pending)&&s.declareCall(w.call);for(let m of w.messages)s.append(m)}},g=()=>{d=!0,t.abort(),u()},_=async()=>{for(let w=-1;w<i.length;)w=i.length,await Promise.all(i);s.signal.removeEventListener("abort",e);for(let w of n.slice(a))w.announced&&!w.settled&&s.emitter({type:"tool-aborted",toolCallId:w.call.id,cause:"stopped"});for(let w of n)w.settled=!0;f()},y=w=>{let{parallel:m}=n[w];return n.slice(0,w).every(S=>!S.asking&&(S.settled||m&&S.parallel))},b=w=>({...s,signal:t.signal,declareCall:()=>{w.declared=!0},append:m=>{w.messages.push(m)},decided:m=>{w.asking=!1,typeof m=="object"?l=!0:m==="stop-run"?g():(c=!0,u()),A()},asking:m=>{w.asking=m,m||A()}}),k=(w,m=!1)=>{if(w.announced)return;w.announced=!0;let{call:S}=w;s.emitter({type:"tool-start",toolCallId:S.id,name:S.name,input:S.input,...m?{queued:!0}:{}})},x=w=>{let{call:m}=w;w.announced?s.emitter({type:"tool-running",toolCallId:m.id}):k(w),i.push(jn(m,b(w)).then(S=>{typeof S=="object"&&(w.declared=!0,w.pending={toolCallId:m.id,name:m.name,input:m.input,reason:S.defer})},S=>{h??={error:S},g()}).finally(()=>{w.asking=!1,w.settled=!0,f();try{A()}catch(S){h??={error:S},g()}}))},v=w=>{let{call:m}=w;k(w,!0);let S=Wn(m,s.toolConfigLookup);S==="approval"&&s.emitter({type:"tool-awaiting-approval",toolCallId:m.id,name:m.name,input:m.input}),w.declared=!0,w.pending={toolCallId:m.id,name:m.name,input:m.input,reason:S},w.settled=!0},E=w=>{k(w,!0),Un(b(w),w.call,{by:"earlier-refusal"}),w.settled=!0},A=()=>{if(!o){o=!0;try{for(;a<n.length&&!d&&!t.signal.aborted&&!(!c&&!l&&!y(a));){let w=n[a++];c?E(w):l?v(w):x(w)}}finally{o=!1}f()}};return{onHalt:p,halted:()=>c||d,busy:()=>r<n.length,start(w){let m=s.toolConfigLookup?.(w.name)?.parallel===!0,S={call:w,parallel:m,asking:!1,announced:!1,declared:!1,messages:[],settled:!1};n.push(S),A(),k(S,!0)},async finish(){if(await _(),d){for(let w of n)w.pending&&s.emitter({type:"tool-aborted",toolCallId:w.call.id,cause:"stopped"});return{...h?{failure:h}:{},stopRun:d,pending:[]}}return{...h?{failure:h}:{},stopRun:d,pending:n.flatMap(w=>w.pending?[w.pending]:[])}},async abandon(){t.abort(),await _()}}}async function Oi(s,t,e,n,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"})},n)}),{run:u,closeOpen:p}=Sl(i,t.id,r.signal),f;try{return await Promise.race([s(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:Kn(f.error)}:void 0)}}var wl=new Set(["run-start","run-done","run-aborted","run-suspended"]),Al=s=>wl.has(s.type);function Sl(s,t,e){let{emitter:n,background:i,...r}=s,a=[];return{run:{...r,startAgent:o=>{if(o.background)return i.open(o);let l=zn(n,s.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 zn(s,t,e,n,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())s({type:"agent-end",agentId:u,status:"stopped",...p?{parentAgentId:p}:{}});o.clear(),s({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&&(s({type:"agent-start",agentId:t,...n.name!==void 0?{name:n.name}:{},...n.description!==void 0?{description:n.description}:{},...e!==void 0?{toolCallId:e}:{}}),i.addEventListener("abort",c,{once:!0})),{agentId:t,signal:i,emit(d){if(!(!a||Al(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),s(h);return}s(d.agentId?d:{...d,agentId:t})}},end:l}}function Cl(s,t,e,n){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(),zn(s,t("agent"),void 0,l,c.signal);let d=()=>c.abort();e.addEventListener("abort",d,{once:!0});let h=setTimeout(()=>c.abort(),n),u={handle:void 0,name:l.name,description:l.description,stop:c,told:!1};return u.handle=zn(s,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 Kn(s){return s instanceof Error?s.message||s.name:typeof s=="string"?s:String(s)}function nt(s){return s.replace(/["\\]/g,"\\$&").replace(/[\n\r\f]/g,t=>`\\${t.charCodeAt(0).toString(16)} `)}function ct(s){return s.composedPath?.()[0]??s.target}function Tt(s){return s.getRootNode()}function ot(s){return s.getRootNode().activeElement??document.activeElement}function Vn(s,t,e={}){let{gap:n=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=s.right+n,p=s.left-l.width-n,[f,g]=o?[p,u]:[u,p],_=y=>y>=i&&y+l.width<=window.innerWidth-i;h=_(f)||!_(g)?f:g,d=s.top}else{let u=s.bottom+n,p=s.top-l.height-n,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?s.left:s.right-l.width}t.style.top=`${c(d,window.innerHeight,l.height)}px`,t.style.left=`${c(h,window.innerWidth,l.width)}px`}var xe='[role="menuitem"], [role="menuitemcheckbox"], [role="menuitemradio"]',kl=500,Ft=null;function El(s,t){for(let e=s;e&&e!==t;e=e.parentElement)if(e.hidden)return!1;return!0}function Me(s,t){return!s.disabled&&s.getAttribute("aria-disabled")!=="true"&&El(s,t)}function Ni(s,t){return s.tagName==="BUTTON"||s.tagName==="A"&&t==="Enter"}function Di(s){return getComputedStyle(s).direction==="rtl"}function Tl(s){return(s.getAttribute("aria-label")??s.textContent??"").replace(/\s+/g," ").trim().toLocaleLowerCase()}function xl(s){return!!s?.closest?.('input, textarea, select, [contenteditable]:not([contenteditable="false"])')}function Ml(s,t){for(let e=t;e;){if(e===s)return!0;let n=e.assignedSlot,i=e.nodeType===Node.DOCUMENT_FRAGMENT_NODE?e.host??null:null;e=n??e.parentNode??i}return!1}function Bi(s,t){let e=!1,n=null,i=null,r=!1,a="",o=0,l=()=>[...s.querySelectorAll(xe)].filter(v=>{let E=v.parentElement?.closest('[role="menu"]');return(!E||E===s||!s.contains(E))&&Me(v,s)}),c=v=>v?.focus({preventScroll:!0}),d=v=>{let E=ct(v);r=!!E&&(s.contains(E)||!!t.owns?.(E)),!r&&x.close(!1)},h=()=>{r=!1},u=v=>{let E=ct(v);E instanceof Node&&s.contains(E)||E instanceof Node&&i?.isConnected&&!Ml(E,i)||x.close(!1)},p=()=>x.close(!1),f=v=>{if(!e)return;let E=v.relatedTarget;!E&&r||E&&(s.contains(E)||t.owns?.(E))||x.close(!1)},g=v=>{if(!e||v.isComposing)return;let E=v.target;if(v.key==="Escape"){v.preventDefault(),x.close(!0);return}if(v.key==="Tab"){x.close(!0);return}if(v.altKey||v.ctrlKey||v.metaKey||xl(E))return;let A=l();if(!A.length)return;let w=A.indexOf(ot(s)),m=D=>{v.preventDefault(),c(A[(D+A.length)%A.length])};switch(v.key){case"ArrowDown":m(w+1);return;case"ArrowUp":m(w<0?A.length-1:w-1);return;case"Home":m(0);return;case"End":m(A.length-1);return;case"Enter":case" ":{let D=E.closest(xe);D&&s.contains(D)&&!Ni(D,v.key)&&(v.preventDefault(),D.click());return}}if([...v.key].length!==1)return;v.preventDefault();let S=Date.now();a=S-o>kl?v.key:a+v.key,o=S;let O=[...a.toLocaleLowerCase()],C=O.every(D=>D===O[0])?O[0]:O.join(""),N=[...C].length===1?w+1:Math.max(w,0);for(let D=0;D<A.length;D++){let H=A[(N+D)%A.length];if(Tl(H).startsWith(C)){c(H);return}}},_=v=>{if(!e)return;let E=v.target.closest?.(`${xe}, button`);if(!E||E===s||!s.contains(E)||!Me(E,s))return;s.dispatchEvent(new CustomEvent("aparte-menu-select",{detail:{item:E},bubbles:!0,composed:!0,cancelable:!0}))&&x.close(!0)},y=v=>{e&&v.preventDefault()};s.addEventListener("keydown",g),s.addEventListener("click",_),s.addEventListener("focusout",f),s.addEventListener("contextmenu",y);let b={position:s.style.position,top:s.style.top,left:s.style.left};s.hidden=!0;let k=!s.hasAttribute("role");k&&s.setAttribute("role","menu");let x={isOpen:()=>e,open(v,E,A,w,m){Ft&&Ft!==x&&Ft.close(!1),e=!0,Ft=x,n=w,i=m,a="",s.hidden=!1,s.style.position="fixed",Vn(v,s,E),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 S=l(),O=S.find(C=>C.getAttribute("role")==="menuitemradio"&&C.getAttribute("aria-checked")==="true");c(A==="last"?S[S.length-1]:O??S[0])},close(v){e&&(e=!1,Ft===x&&(Ft=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),v&&n?.isConnected&&n.focus(),n=null,i=null,s.hidden=!0,t.onToggle?.(!1),t.onClose?.())},release(){x.close(!1),s.removeEventListener("keydown",g),s.removeEventListener("click",_),s.removeEventListener("focusout",f),s.removeEventListener("contextmenu",y),s.style.position=b.position,s.style.top=b.top,s.style.left=b.left,s.getAttribute("style")||s.removeAttribute("style"),k&&s.removeAttribute("role")},returnTarget:()=>n};return x}function Pi(s,t,e,n=!1){let i=s.getAttribute(t);return(i===null||!n)&&s.setAttribute(t,e),()=>{i===null?s.removeAttribute(t):s.setAttribute(t,i)}}function $i(s,t,e={}){let{onOpen:n,onClose:i,...r}=e,a=[Pi(s,"aria-haspopup","menu",!0),Pi(s,"aria-expanded","false")],o=Bi(t,{owns:u=>s.contains(u),onToggle:u=>s.setAttribute("aria-expanded",String(u)),onClose:i}),l=u=>{if(o.isOpen()){let p=[...t.querySelectorAll(xe)].filter(f=>Me(f,t));(u==="last"?p[p.length-1]:p[0])?.focus({preventScroll:!0});return}n?.()!==!1&&o.open(s.getBoundingClientRect(),{...r,rtl:r.rtl??Di(s)},u,s,s)},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===" ")&&!Ni(s,u.key)&&(u.preventDefault(),c()))};return s.addEventListener("click",d),s.addEventListener("keydown",h),()=>{o.release(),s.removeEventListener("click",d),s.removeEventListener("keydown",h);for(let u of a)u()}}function Hi(s,t,e={}){let{onOpen:n,onClose:i,gap:r,margin:a,rtl:o}=e,l=Bi(t,{onClose:i}),c=(u,p,f)=>{let g=ot(s),_=g&&g!==document.body&&!t.contains(g)?g:l.returnTarget();return l.close(!1),n?.(u)===!1?!1:(l.open(p,{gap:f?0:r,margin:a,side:"below",align:"start",rtl:o??Di(s)},"first",_,u),!0)},d=u=>{let p=ct(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=ct(u);!p||t.contains(p)||c(p,p.getBoundingClientRect(),!1)&&u.preventDefault()};return s.addEventListener("contextmenu",d),s.addEventListener("keydown",h),()=>{l.release(),s.removeEventListener("contextmenu",d),s.removeEventListener("keydown",h)}}function qi(s,t={}){let e=t.activation==="manual",n=()=>[...s.querySelectorAll('[role="tab"]')].filter(u=>u.closest('[role="tablist"]')===s),i=u=>Me(u,s),r=()=>n().find(u=>u.getAttribute("aria-selected")==="true")??null,a=u=>{let p=u.getAttribute("aria-controls");return p?s.getRootNode().querySelector(`[id="${nt(p)}"]`):null},o=u=>{for(let p of n()){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=s.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||!n().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=n(),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 _=s.getAttribute("aria-orientation")==="vertical",y=!_&&getComputedStyle(s).direction==="rtl",b=_?"ArrowDown":y?"ArrowLeft":"ArrowRight",k=_?"ArrowUp":y?"ArrowRight":"ArrowLeft",x,v;if(u.key===b)x=g+1,v=1;else if(u.key===k)x=g-1,v=-1;else if(u.key==="Home")x=0,v=1;else if(u.key==="End")x=f.length-1,v=-1;else return;u.preventDefault();for(let E=0;E<f.length;E++){let A=f[((x+E*v)%f.length+f.length)%f.length];if(i(A)){(e||l(A))&&A.focus();return}}};s.addEventListener("click",c),s.addEventListener("keydown",d);let h=r()??n().find(i);return h&&o(h),()=>{s.removeEventListener("click",c),s.removeEventListener("keydown",d)}}var Il='<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>',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="M4.5 12.5 9.5 17.5 19.5 7"/></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="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>',Ol='<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>',Pl='<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>',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="M5.5 9.5 12 16l6.5-6.5"/></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="M5.5 14.5 12 8l6.5 6.5"/></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="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>',$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="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>',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="M5 6.5 10.5 12 5 17.5"/><path d="M13 18h6"/></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="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>',Fl='<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>',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="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>',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="M12 4.5v15"/><path d="M6 13.5l6 6 6-6"/></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 12a8 8 0 1 0 2.35-5.65L4 8.5"/><path d="M4 3.5v5h5"/></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="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>',Gl='<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>',Kl='<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>',Vl='<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>',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="M9.5 6 15 12l-5.5 6"/></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 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>',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="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>',tc='<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>',ec='<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>',nc='<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>',sc='<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>',ic='<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>',rc='<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>',ac='<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>',oc='<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>',lc='<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>',cc='<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>',Fi={copy:Il,check:Ll,send:Rl,loading:Ol,error:Pl,expand:Nl,collapse:Dl,maximize:Bl,minimize:$l,terminal:Hl,paperclip:ql,image:Fl,file:Wl,scrollDown:Ul,retry:jl,edit:zl,thumbUp:Gl,thumbDown:Kl,prevBranch:Vl,nextBranch:Yl,tool:Ql,close:Xl,stop:Jl,pause:Zl,info:tc,archive:ec,unarchive:nc,download:sc,more:ic,pin:rc,trash:ac,menu:lc,alertTriangle:cc,messageSquare:oc};function Qr(s){return typeof s=="string"?s:s.filter(t=>t.type==="text").map(t=>t.text).join("")}var z=(s=>(s.CONFIG_NO_PROVIDER="CONFIG_NO_PROVIDER",s.CONFIG_MISSING_KEY="CONFIG_MISSING_KEY",s.CONFIG_INVALID_KEY="CONFIG_INVALID_KEY",s.CONFIG_INVALID_MODEL="CONFIG_INVALID_MODEL",s.USAGE_RATE_LIMIT="USAGE_RATE_LIMIT",s.USAGE_CONTEXT_EXCEEDED="USAGE_CONTEXT_EXCEEDED",s.USAGE_BAD_REQUEST="USAGE_BAD_REQUEST",s.NET_OFFLINE="NET_OFFLINE",s.NET_TIMEOUT="NET_TIMEOUT",s.NET_ERROR="NET_ERROR",s.PROVIDER_ERROR="PROVIDER_ERROR",s.PROVIDER_UNAVAILABLE="PROVIDER_UNAVAILABLE",s.PROVIDER_POLICY="PROVIDER_POLICY",s.PROVIDER_MISCONFIGURED="PROVIDER_MISCONFIGURED",s.MAX_TURNS_EXCEEDED="MAX_TURNS_EXCEEDED",s.UNKNOWN_ERROR="UNKNOWN_ERROR",s))(z||{}),dt=class s extends Error{constructor(t,e,n,i,r){super(t),this.message=t,this.code=e,this.data=n,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",n){if(t instanceof s)return t;let i=t instanceof Error?t.message:String(t),r=t?.status||t?.statusCode||n,a=t?.code,o=e!=="UNKNOWN_ERROR"?e:s.carriedCode(a)??s.codeForStatus(r)??s.codeForFailure(t)??e;return new s(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"}}},se=Fi,zt={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",queueLabel:"Sent when the reply ends",queueEdit:"Edit",queueRemove:"Remove",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 Xr(s){return typeof s.buildRequest=="function"&&typeof s.parseStream=="function"&&typeof s.defaultEndpoint=="string"&&(typeof s.authHeaders=="function"||typeof s.authQuery=="function")}function dc(s){return typeof s=="string"?{key:s}:s&&typeof s=="object"?{key:s.apiKey,endpoint:s.endpoint}:{}}function uc(s,t,e){let n=s?.error,i=typeof n=="object"?n?.message:n;return typeof i=="string"&&i?i:`${e} ${t}`}function hc(s){return typeof s=="string"&&Object.values(z).includes(s)}async function pc(s,t="HTTP",e){let n=await s.json().catch(()=>{}),i=uc(n,s.status,t),r=n?.error?.code,a=e?.classifyError?.(s.status,n)??(hc(r)?r:void 0)??dt.codeForStatus(s.status)??z.UNKNOWN_ERROR;return new dt(i,a,void 0,void 0,s.status)}async function fc(s,t,e){let n=await t.json();if(typeof s.parseText!="function")throw new Error(`Provider "${e}" cannot resolve a non-streaming response: parseText is not implemented.`);let i=s.parseText(n),r;try{r=s.parseSources?.(n)}catch{r=void 0}return gc(i,r)}function gc(s,t){if(!t||t.sources.length===0)return s;let e=[{type:"text",delta:s},{type:"sources",...t},{type:"done"}];return new ReadableStream({pull(n){let i=e.shift();i?n.enqueue(i):n.close()}})}var ze=class{byok;warnedBrowserKey=!1;constructor(t={}){this.byok=t.byok??!1}async chat(t,e,n,i){let{key:r,endpoint:a}=dc(n);if(!this.byok&&r&&this.warnBrowserKeyOnce(i.providerId),!Xr(t)){if(typeof t.chat!="function")throw new Error(`Provider "${i.providerId}" exposes neither a format-adapter surface nor chat().`);return t.chat(e,n,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 pc(h,"HTTP",t);if(e.stream===!1)return fc(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 J(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}var _c=[{start:"<think>",end:"</think>"},{start:"<thinking>",end:"</thinking>"}],Yt=class{_options;_thinkingDelimiters;_blocks;_state;_pendingSegment=null;constructor(t={}){let e=t.thinkingDelimiters;this._thinkingDelimiters=e?Array.isArray(e)?e:[e]:_c,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 n=this._parseNext();if(!n)break;n.segment&&e.push(n.segment),this._state.buffer=n.remaining}return{segments:e,remaining:this._state.buffer,state:{...this._state}}}finalize(){let t=[],e=n=>n.replace(/\n?```[ \t]*$/,"");if(this._state.activeSegment){if("content"in this._state.activeSegment){let n=this._state.activeSegment,i=n.content+this._state.buffer;(n.type==="text"||n.type==="code")&&(i=e(i)),n.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("```"),n=-1;for(let c of this._thinkingDelimiters){let d=t.indexOf(c.start);d!==-1&&(n===-1||d<n)&&(n=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}),n!==-1&&a.push({type:"thinking",index:n}),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 n=t.slice(0,e);this._state.activeSegment&&"content"in this._state.activeSegment&&(this._state.activeSegment.content+=n);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(n=>t.startsWith(n.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,n=t.indexOf(e);if(n===-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,n);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(n+e.length)}}_indexOfTag(t,e){let n="<"+e,i=0;for(;;){let r=t.indexOf(n,i);if(r===-1)return-1;let a=t[r+n.length];if(a===void 0)return-1;if(a===">"||a==="/"||/\s/.test(a))return r;i=r+1}}_tagEnd(t,e){let n=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),n){if(o===n)n=null;else if(o===`
9
+ `)return r;continue}if(o===">")return a;if(o==="="){i=!0;continue}if(i&&(o==='"'||o==="'")){n=o,i=!1;continue}/\s/.test(o)||(i=!1)}return-1}_startBlock(t,e){let n=this._tagEnd(t,e.tag);if(n===-1)return null;let i=t.slice(1+e.tag.length,n),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(n+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,n=t.indexOf(e),i=this._state.activeSegment;if(n===-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,n));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(n+e.length)}}_createInitialState(){return{mode:"text",buffer:"",segments:[],activeSegment:null,segmentCounter:0}}_generateId(){return++this._state.segmentCounter,`${this._options.idPrefix}-${J()}`}_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 n=1;n<e.length;n++)if(t.endsWith(e.slice(0,n)))return!0;return!1}_getPartialMatchLength(t,e){for(let n=e.length-1;n>=1;n--)if(t.endsWith(e.slice(0,n)))return n;return 0}};function Jr(s,t){let e=new Yt(t),n=e.parse(s),i=e.finalize();return[...n.segments,...i]}var mc=new Set(["pending","awaiting-approval"]),bc=["content","output","result"];function vc(s){return bc.some(t=>t in s)}function Hs(s,t,e,n){let i=Ac(t,n);return{...i,messageId:t.messageId??e,index:t.index??s.length,...Ge(i,{startedAt:_e(t)?.startedAt??Date.now()})}}function yc(s,t,e,n=!1){let{queued:i,...r}=t;return{...r,messageId:e,index:s.length,isStreaming:!1,...t.type==="tool_call"&&(t.status==="awaiting-approval"||t.status==="pending"&&!n)&&!t.deferred?.ticket?{status:"aborted"}:{}}}var wc=new Set(["id","type","messageId","index"]);function _e(s){return s.meta?.aparte}function Ge(s,t){return{meta:{...s.meta,aparte:{...s.meta?.aparte,...t}}}}function Ac(s,t){if(!t)return s;let e={...s};for(let[n,i]of Object.entries(t))if(!(wc.has(n)||n in s)){if(n==="meta"){let{aparte:r,...a}=i??{};e.meta=a;continue}e[n]=i}return e}function It(s){return s.type==="tool_call"?!mc.has(s.status):s.isStreaming===!1}function Zr(s,t){if(It(s))return t;let e={...s,...t};if(It(e)){let n=_e(s)?.endedAt;return{...t,...Ge(s,{endedAt:n??Date.now()})}}return vc(t)?{...t,...Ge(s,{endedAt:Date.now()})}:t}function qs(s,t){let e={...s,...t};return"meta"in t?{...e,meta:{...s.meta,...t.meta,...s.meta?.aparte||t.meta?.aparte?{aparte:{...s.meta?.aparte,...t.meta?.aparte}}:{}}}:e}function ta(s){let{startedAt:t,endedAt:e}=_e(s)??{};if(!(t==null||e==null))return e-t}function ea(s){return It(s)?{}:Ge(s,{endedAt:Date.now()})}function Yn(s){return{content:s.content,...s.isStreaming===!1?{isStreaming:!1}:{}}}function Fs(s){return s!=null&&s!=="streaming"&&s!=="pending"}function na(s){return s.filter(t=>!It(t)).map(t=>t.id)}function an(s){if(!s.segments?.length)return{...s};let t=s.status==="streaming"||s.status==="pending"||(s.deferredCalls?.length??0)>0;return{...s,segments:s.segments.reduce((e,n)=>(e.push(yc(e,n,s.id,t)),e),[])}}function sa(s){for(let t=0;t<s.length;t++){let e=s[t];e.index!==t&&(s[t]={...e,index:t})}}var me="data-aparte-host",Ke=Symbol.for("aparte.instanceConfig");function Sc(s,t,e){if(t===e)return;let n=i=>{let r=i.aparteConfigChanged;typeof r=="function"&&r.call(i,t,e)};n(s);for(let i of s.querySelectorAll("*"))n(i)}function Cc(s,t){let e=s[Ke]??I(s.parentElement);s[Ke]=t,s.setAttribute(me,""),Sc(s,t,e)}function I(s){let t=`[${me}]`,e=s?.closest?.(t);for(;e&&!e[Ke];)e=e.parentElement?.closest(t);return e?.[Ke]??Q}var Be=null;function Y(s,t){let e=Be;Be=s;try{return t()}finally{Be=e}}function M(s){return Be??I(s)}function lt(s,t,e,n){let i=n??(s.id||void 0),r=e&&typeof e=="object"?{targetId:i,...e}:e;s.dispatchEvent(new CustomEvent(t,{bubbles:!0,composed:!0,detail:r}))}function P(s){let t="";for(let e=0;e<s.length;e++){let n=s[e];n==="&"?t+="&amp;":n==="<"?t+="&lt;":n===">"?t+="&gt;":n==='"'?t+="&quot;":n==="'"?t+="&#039;":t+=n}return t}var L=P,le="aparte-code-drawing",ia="aparte-code-pending",Wi="data-aparte-open",ra="data-aparte-drawn",kc=4*1024*1024,ps=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 n=this.entries.get(t);n&&(this.size-=Qn(t,n),this.entries.delete(t));let i={html:e};this.entries.set(t,i),this.size+=Qn(t,i);for(let[r,a]of this.entries){if(this.size<=kc||r===t)break;this.entries.delete(r),this.size-=Qn(r,a)}return i}},Qn=(s,t)=>s.length+(t.html?.length??0),vt=new WeakMap,Ws=new WeakMap,Ui=new WeakMap,ji=new WeakMap,zi=new WeakMap,aa=new WeakMap,oa=new WeakMap,la=new WeakMap,Gi=new WeakSet,Ki=new WeakSet,Xn=new WeakMap,Vi=new WeakMap,Ie=new WeakMap;function Ec(s){let t=Ui.get(s);return t||(t=new ps,Ui.set(s,t)),t}function Tc(s){let t=ji.get(s);return t||(t=new Map,ji.set(s,t)),t}function Yi(s,t){let e=s.get(t);return e||(e=new Map,s.set(t,e)),e}function ce(s,t){Gi.has(s)||(Gi.add(s),console.warn(`[aparte] The ${s.languages.join("/")} renderer failed; the source is shown instead.`,t))}function xc(s){for(let t of Array.from(s.classList))if(t.startsWith("language-"))return t.slice(9).toLowerCase()||null;return null}function Mc(s){return s.classList.contains("math-display")?!0:s.classList.contains("math-inline")?!1:s.parentElement?.tagName==="PRE"}function Ic(s){return s.hasAttribute(Wi)||s.parentElement?.tagName==="PRE"&&s.parentElement.hasAttribute(Wi)}function Lc(s,t){let e="";try{e=s.cacheKey?.(t)??""}catch(n){ce(s,n)}return`${t.language}${t.display?"d":"i"}${e}${t.source}`}function ca(s){return typeof s?.then=="function"}function Rc(s){return s.closest("pre")??vt.get(s)?.drawing??s}function Oc(s){return s.closest("pre")??s.parentElement??s}var Jn=new Set,Zn=new Map,ts=!1;function on(s,t){t?Zn.set(s,t):Jn.add(s),!ts&&(ts=!0,queueMicrotask(()=>{ts=!1;let e=[...Jn],n=[...Zn];Jn.clear(),Zn.clear();for(let i of e)Nc(i);for(let[i,r]of n)i.isConnected&&qt(i,r)}))}var Qi=new WeakMap;function Pc(s,t,e){let n=Qi.get(s);if(!n){let i=new Map;Qi.set(s,i),n=i,s.then(()=>{for(let[r,a]of i)on(r,a);i.clear()},()=>i.clear())}(!n.has(t)||e===void 0)&&n.set(t,e)}var Nt=null;function da(s){for(let t=s.parentElement;t;t=t.parentElement){let e=getComputedStyle(t).overflowY;if(e==="auto"||e==="scroll")return t}return null}function Nc(s){if(!s.isConnected)return;let t=da(s),e=t?t.getBoundingClientRect().top+(parseFloat(getComputedStyle(t).scrollPaddingTop)||0):0;Nt={scroller:t,top:e};try{qt(s,la.get(s)??{})}finally{Nt=null}}function Dc(s,t){let e=Rc(s);if(Ki.has(e)||typeof IntersectionObserver>"u")return!1;let n=da(e),i=Vi.get(IntersectionObserver);i||(i={byScroller:new WeakMap},Vi.set(IntersectionObserver,i));let r=n?i.byScroller.get(n):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=(Ie.get(a)??1)-1;if(Ie.set(a,d),d<=0&&(a.disconnect(),n?i.byScroller.delete(n):i.page===a&&(i.page=void 0)),!c.isConnected)continue;Ki.add(c);let h=Xn.get(c);h&&on(h)}},{root:n,rootMargin:"100% 0px"});r=a,n?i.byScroller.set(n,a):i.page=a}return Xn.get(e)!==t&&(Xn.set(e,t),Ie.set(r,(Ie.get(r)??0)+1),r.observe(e)),!0}function ae(s,t,e,n,i,r,a=!0){if(e.html===null){Qt(t,i.open);return}let o=Nt?Oc(t):null,l=o?o.getBoundingClientRect():null,c=vt.get(t),d=c?.drawing;if(d||(d=document.createElement("span"),d.className=le,i.display&&d.setAttribute("data-aparte-display",""),n.bare?d.setAttribute("data-aparte-bare",""):d.setAttribute("dir","ltr"),t.after(d),Ws.set(d,t),t.parentElement?.tagName==="PRE"&&t.parentElement.setAttribute(ra,"")),c?.entry!==e||d.childNodes.length===0){let h=a?zi.get(s):void 0;a&&!h&&(h=new WeakMap,zi.set(s,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(),Qt(u.owner,!1);else{d.innerHTML=e.html;try{n.relabel?.(d,i)}catch(f){ce(n,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(ia),vt.set(t,{renderer:n,key:r,drawing:d,entry:e,ctx:i}),o&&l&&Nt){let h=o.getBoundingClientRect().height-l.height;h>0&&l.bottom<=Nt.top&&(Nt.scroller?Nt.scroller.scrollTop+=h:window.scrollBy(0,h))}}function Qt(s,t){let e=vt.get(s);e&&(e.drawing.remove(),vt.delete(s)),s.parentElement?.tagName==="PRE"&&s.parentElement.removeAttribute(ra),s.hidden=!1,s.style.removeProperty("display"),s.classList.toggle(ia,t)}function Bc(s,t,e,n,i,r){let a=Lc(e,n),o=vt.get(t);if(o&&o.renderer===e&&o.key===a&&o.drawing.childNodes.length>0)return;let l=Ec(e),c=l.get(a);if(c){ae(s,t,c,e,n,a,!r);return}if(!o&&!r){let f=aa.get(s)?.get(i);f&&n.source.startsWith(f.source)&&ae(s,t,f,e,n,null),o=vt.get(t)}if(e.lazy&&!r&&!o&&Dc(t,s))return;let d=Tc(e),h=d.get(a);if(h){Pc(h,s,r);return}let u;try{u=e.render(n)}catch(f){ce(e,f),u=null}if(!ca(u)){ae(s,t,l.set(a,u??null),e,n,a,!r);return}let p=u.then(f=>(d.delete(a),l.set(a,f??null),f),f=>{throw d.delete(a),ce(e,f),f});d.set(a,p),p.then(()=>on(s,r),()=>{})}function $c(s,t,e,n,i){let r=Yi(aa,s),a=r.get(i);a&&n.source.startsWith(a.source)?vt.get(t)?.entry!==a&&ae(s,t,a,e,n,null):(r.delete(i),Qt(t,!0));let o=Yi(oa,s);if(o.get(i)===n.source)return;o.set(i,n.source);let l=()=>{o.get(i)===n.source&&o.delete(i)},c=h=>{if(h==null)return!1;let u=r.get(i);return u&&!n.source.startsWith(u.source)?!1:(r.set(i,{source:n.source,html:h}),!0)},d;try{d=e.render(n)}catch{d=null}if(!ca(d)){c(d)?ae(s,t,r.get(i),e,n,null):d==null&&l();return}d.then(h=>{c(h)?on(s):h==null&&l()},l)}function Hc(s){for(let t of["code","kbd","samp"])for(let e of Array.from(s.getElementsByTagName(t)))e.hasAttribute("dir")||e.setAttribute("dir","ltr")}function qt(s,t={}){if(typeof document>"u")return;let{streaming:e=!1,refresh:n=!1,language:i}=t;if(!n&&(Hc(s),la.set(s,{streaming:e}),e||oa.delete(s),!M(s).hasCodeLanguageRenderer())){s.querySelector(`.${le}`)&&ua(s);return}let r=Array.from(s.querySelectorAll('code[class*="language-"]')).filter(o=>!o.closest(`.${le}`)),a=new Map;r.forEach((o,l)=>{let c=xc(o);if(!c||i&&c!==i)return;let d=M(n?o:s),h=d.getCodeLanguageRenderer(c),u=vt.get(o);if(n&&(!u||u.key===null))return;if(!h){u&&Qt(o,!1);return}let p=Mc(o),f=`${c}|${p?"d":"i"}`,g=a.get(f)??0;a.set(f,g+1);let _=`${f}|${g}`,y=o.textContent??"";if(!y.trim()){u&&Qt(o,!1);return}let b=e&&(Ic(o)||l===r.length-1),k={language:c,source:y,display:p,open:b,host:o,config:d};b?$c(s,o,h,k,_):Bc(s,o,h,k,_,n?t:void 0)})}function ua(s){for(let t of Array.from(s.querySelectorAll(`.${le}`))){let e=Ws.get(t);e?Qt(e,!1):t.remove()}}function ha(s){for(let t of Array.from(s.querySelectorAll(`.${le}`))){let e=Ws.get(t),n=e?vt.get(e):void 0;if(n)try{n.renderer.relabel?.(t,n.ctx)}catch(i){ce(n.renderer,i)}}}function fs(s,t){return!!s&&M(t).hasCodeLanguageRenderer(s)}var pa=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"]),Us=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"]),qc=new Set(["class","style","title","dir","lang","role","align","aria-label","aria-hidden","aria-describedby","aria-level"]),Fc={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"])},Wc=new Set(["href","src"]),Uc=/^(?:https?:|mailto:|tel:|ftp:|sms:)/i,jc=/^(?:[#/.?]|[a-z0-9._~%+-]+(?:[/?#]|$))/i,zc=/^data:image\/(?:png|jpe?g|gif|webp|avif|bmp|x-icon|svg\+xml)[;,]/i,js=/[\u0000-\u0020]+/g,Xi=/^(?:https?:)?[/\\]{2}|^https?:/i,Gc=/^aparte-/i,Kc=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"]),Vc=["data-aparte-dialog-","data-aparte-sidebar-","data-checkpoint-"];function Yc(s){return Kc.has(s)||Vc.some(t=>s.startsWith(t))}var Qc=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 Xc(s,t){let e=t==="source"?"img":t;for(let n of s.matchAll(/(?:^|[^a-z0-9+.-])([a-z][a-z0-9+.-]*:[^\s,]*)/gi))if(!be(n[1],e))return!1;return!0}function be(s,t){let e=s.replace(js,"");return!e||Uc.test(e)||t==="img"&&zc.test(e)?!0:/^[a-z][a-z0-9+.-]*:/i.test(e)?!1:jc.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(s){return s.includes("\\")?!1:s.startsWith("--")&&!s.startsWith("--aparte-")}function td(s){let t=[];for(let e of s.split(";")){let n=e.trim(),i=n.indexOf(":");if(i===-1)continue;let r=n.slice(0,i).trim().toLowerCase(),a=n.slice(i+1);a.trim()&&(!Jc.has(r)&&!Zc(r)||a.includes("\\")||/url\s*\(|expression\s*\(|javascript:|vbscript:|[<>]/i.test(a)||t.push(n))}return t.length?t.join("; "):null}function gs(s,t,e){let n=Fc[s];if(t.startsWith("on")||t.startsWith("formaction")||!t.startsWith("data-")&&!qc.has(t)&&!(n&&n.has(t))||Yc(t)||t==="role"&&e.trim().toLowerCase().split(/\s+/).some(i=>Qc.has(i))||Wc.has(t)&&!be(e,s)||t==="srcset"&&!Xc(e,s))return null;if(t==="style")return td(e);if(t==="class"){let i=e.split(/\s+/).filter(r=>r&&!Gc.test(r));return i.length?i.join(" "):null}return e}function zs(s,t){let e=s.replace(js,""),n=t.trim().toLowerCase();return n==="_self"&&!Xi.test(e)?[["target","_self"]]:n||Xi.test(e)?[["target","_blank"],["rel","noopener noreferrer"]]:[]}function ed(s,t,e){for(let n of Array.from(s.attributes)){let i=n.name.toLowerCase(),r=gs(e,i,n.value);r!==null&&t.setAttribute(i,r)}if(e==="a")for(let[n,i]of zs(t.getAttribute("href")??"",s.getAttribute("target")??""))t.setAttribute(n,i)}function _s(s,t,e){for(let n of Array.from(s.childNodes)){if(n.nodeType===3){t.appendChild(e.createTextNode(n.nodeValue??""));continue}if(n.nodeType!==1)continue;let i=n,r=i.tagName.toLowerCase();if(pa.has(r))continue;if(!Us.has(r)){_s(i,t,e);continue}let a=r==="input";if(a&&(i.getAttribute("type")??"").trim().toLowerCase()!=="checkbox")continue;let o=e.createElement(r);ed(i,o,r),a&&(o.setAttribute("type","checkbox"),o.setAttribute("disabled","")),_s(i,o,e),t.appendChild(o)}}var nd=new Set(["html","head","body"]),sd=new Set(["link","meta","base","embed","frame"]),Ji=new Map;function id(s){let t=Ji.get(s);return t||(t=new RegExp(`<\\s*\\/\\s*${s}\\s*>`,"gi"),Ji.set(s,t)),t}var Zi=/--!?>/g,rd=/[A-Za-z]/,Le=/\s/,ad=/[\s/>]/,od=/[\s/>=]/,ld=/^[a-z][a-z0-9_.:-]*$/,cd={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",colon:":",lpar:"(",rpar:")",sol:"/",bsol:"\\",period:".",comma:",",semi:";",num:"#",excl:"!",quest:"?",tab:" ",newline:`
10
+ `};function dd(s){return s.includes("&")?s.replace(/&(?:#x([0-9a-f]+)|#([0-9]+)|([a-z]+));?/gi,(t,e,n,i)=>{if(i!==void 0)return cd[i.toLowerCase()]??t;let r=e!==void 0?parseInt(e,16):parseInt(n??"",10);return r>0&&r<=1114111&&(r<55296||r>57343)?String.fromCodePoint(r):"\uFFFD"}):s}var ud=s=>s.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;").replace(/</g,"&lt;").replace(/>/g,"&gt;");function hd(s,t){if(!Us.has(s))return"";let e=s==="input",n=r=>t.find(([a])=>a===r)?.[1];if(e&&(n("type")??"").trim().toLowerCase()!=="checkbox")return"";let i=[];e&&(i.push('type="checkbox"'),n("checked")!==void 0&&i.push("checked"),i.push("disabled"));for(let[r,a]of t){if(!ld.test(r)||e&&(r==="type"||r==="checked"||r==="disabled"))continue;let o=gs(s,r,a);o!==null&&i.push(`${r}="${ud(o)}"`)}if(s==="a"){let r=t.find(([o])=>o==="href"),a=r?gs("a","href",r[1]):null;for(let[o,l]of zs(a??"",n("target")??""))i.push(`${o}="${l}"`)}return`<${s}${i.length?" "+i.join(" "):""}>`}function Gs(s,t){let e=s.length,n=t;for(;n<e&&!ad.test(s[n]);)n++;let i=s.slice(t,n).toLowerCase(),r=[],a=new Set;for(;n<e;){for(;n<e&&(Le.test(s[n])||s[n]==="/");)n++;if(n>=e)break;if(s[n]===">")return{tag:i,attrs:r,end:n+1};let o=n++;for(;n<e&&!od.test(s[n]);)n++;let l=s.slice(o,n).toLowerCase(),c=n;for(;c<e&&Le.test(s[c]);)c++;let d="";if(s[c]==="="){for(c++;c<e&&Le.test(s[c]);)c++;let h=s[c];if(h==='"'||h==="'"){let u=s.indexOf(h,c+1);if(u<0)break;d=s.slice(c+1,u),n=u+1}else{let u=c;for(;c<e&&!Le.test(s[c])&&s[c]!==">";)c++;d=s.slice(u,c),n=c}}a.has(l)||(a.add(l),r.push([l,dd(d)]))}return{tag:i,attrs:r,end:-1}}function pd(s){let t=s.length,e="",n=0;for(;n<t;){let i=s.indexOf("<",n);if(i<0){e+=s.slice(n);break}if(e+=s.slice(n,i),s.startsWith("<!--",i)){let d=i+4;if(s[d]===">")n=d+1;else if(s.startsWith("->",d))n=d+2;else{Zi.lastIndex=d;let h=Zi.exec(s);if(!h)break;n=h.index+h[0].length}continue}let r=s[i+1]==="/",a=i+(r?2:1);if(!rd.test(s[a]??"")){if(s[i+1]==="!"||s[i+1]==="?"||r){let d=s.indexOf(">",i+1);n=d<0?t:d+1}else e+="&lt;",n=i+1;continue}let{tag:o,attrs:l,end:c}=Gs(s,a);if(c<0)break;if(n=c,r)Us.has(o)&&(e+=`</${o}>`);else if(pa.has(o)&&!nd.has(o)&&!sd.has(o)){let d=id(o);d.lastIndex=c;let h=d.exec(s);if(!h)break;n=h.index+h[0].length}else e+=hd(o,l)}return e}function tr(s){return pd(s)}var ms=s=>{if(!s)return s;if(typeof DOMParser>"u")return tr(s);let t;try{t=new DOMParser().parseFromString(s,"text/html")}catch{return tr(s)}let e=t.createElement("div");return _s(t.body,e,t),e.innerHTML},fd=s=>s.localName==="aparte-chat"||s.hasAttribute("data-aparte-chat");function gd(s){if(s.parentElement)return s.parentElement;let t=s.getRootNode?.();return t&&"host"in t?t.host:null}function yt(s){for(let t=s??null;t;t=gd(t)){if(t.localName.startsWith("aparte-")){let e=t.getAttribute("target");if(e)return e}if(fd(t)&&t.id)return t.id}}function st(s,t,e,n={}){let i=e.targetId??yt(s),r=i===void 0?e:{...e,targetId:i};return s.dispatchEvent(new CustomEvent(t,{bubbles:!0,composed:!0,cancelable:n.cancelable===!0,detail:r}))}var wt="aparte-citation",fa="aparte-citation-marker",ga=/[\p{L}\p{N}]/u,_d=[24,12,6],_a=new Set(["A","ABBR","B","CITE","CODE","DEL","EM","I","INS","KBD","MARK","Q","S","SMALL","SPAN","STRONG","SUB","SUP","U"]),er=/[.,;:!?)\]}»"'’”…。、,.!?:;」』)】》،؛؟]/,md=/[\u00a0\u202f]/,Ks=new WeakMap,ma=new WeakMap,nr=new WeakSet,$e=new WeakMap,xt=null;function Vs(s){let t=s.url?.trim();return t&&/^https?:\/\//i.test(t)&&be(t,"a")?t:void 0}function ba(s,t,e,n){let i=document.createElement("a");i.href=s;let r=e.decideLink(s);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=` ${n}`,i.append(a)}return i}function Ve(s){let t=Vs(s);if(t)try{return new URL(t).hostname.replace(/^www\./,"")}catch{}return s.title??""}function bd(s){let t=Ve(s[0])||"?";return s.length>1?`${t} +${s.length-1}`:t}function bs(s,t){let e=s.getLocale();return t===1?e.sourcesOne??"1 source":(e.sourcesCount??"{n} sources").replace("{n}",()=>String(t))}function vd(s){if(typeof document>"u")return"";let t=document.createElement("textarea");return t.innerHTML=s,t.value}function sr(s){return s.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,vd)}function yd(s){let t=s.replace(/^ {0,3}(?:`{3,}|~{3,})[^\n]*$/gm,""),e="",n=0;for(let r of t.matchAll(/(`+)([^`][\s\S]*?)\1/g))e+=sr(t.slice(n,r.index))+r[2],n=(r.index??0)+r[0].length;e+=sr(t.slice(n));let i="";for(let r of e)ga.test(r)&&(i+=r);return i}function wd(s){let t="",e=[],n=s.ownerDocument.createTreeWalker(s,NodeFilter.SHOW_TEXT,{acceptNode:i=>i.parentElement?.closest(`.aparte-code-drawing, .${wt}`)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT});for(let i=n.nextNode();i;i=n.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,!!ga.test(l)){t+=l;for(let c=0;c<o;c++)e.push([i,a])}}}return{text:t,ends:e}}function Ad(s,t){let e=0;for(let n=s.indexOf(t);n>=0;n=s.indexOf(t,n+1))e++;return e}function Sd(s,t,e){let n=yd(s.slice(0,Math.max(0,Math.min(s.length,t.end))));if(!n)return null;for(let i of _d){let r=n.slice(-i),a=Ad(n,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===n.length)break}return null}function ir(s,t){let e=t;for(;e<s.length&&(er.test(s[e])||md.test(s[e])&&er.test(s[e+1]??""));)e++;return e-t}function Cd(s,t,e,n){let i=e.parentElement?.closest("pre");if(i&&s.contains(i)){i.after(t);return}let r=null;for(let l=e.parentElement;l&&l!==s&&_a.has(l.tagName);l=l.parentElement)r=l;if(!r){e.splitText(n+ir(e.data,n)),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=ir(o.data,0);l>0&&(o.splitText(l),a=o)}a.parentNode.insertBefore(t,a.nextSibling)}function kd(s,t,e,n){let i=l=>{let c=document.createElement("span");c.className=fa,c.hidden=!0,l.parentNode.insertBefore(c,l),c.append(l),c.after(s)},r=t.data.lastIndexOf(n,e);if(r>=0&&r+n.length>=e){let l=t.splitText(r);return l.splitText(n.length),i(l),!0}let a=t.parentElement,o=n.replace(/^\[|\]$/g,"");return a&&_a.has(a.tagName)&&a.textContent?.trim()===o?(i(a),!0):!1}function Ed(s,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"),Ks.set(e,s),va(e,t),e}function va(s,t){let e=Ks.get(s)??[],n=bd(e);s.dataset.label=n,s.setAttribute("aria-label",`${n}, ${bs(t,e.length)}`)}function ya(s){let t=new Set;for(let e of Array.from(s.querySelectorAll(`.${wt}`)))e.parentNode&&t.add(e.parentNode),e.remove();for(let e of Array.from(s.querySelectorAll(`.${fa}`)))e.parentNode&&t.add(e.parentNode),e.replaceWith(...Array.from(e.childNodes));for(let e of t)e.normalize();$e.delete(s)}function vs(s,t){if(typeof document>"u")return;let e=t.citations??[],n=new Map((t.sources??[]).map(g=>[g.id,g])),i=JSON.stringify([t.content,e,[...n.values()].map(g=>[g.id,g.url,g.title,g.snippet])]),r=Array.from(s.querySelectorAll(`.${wt}`)),a=$e.get(s);if(a&&a.signature===i&&a.count===r.length)return;let o=document.activeElement,l=xt?.root===s&&(o===xt.chip||(!o||o===document.body)&&!xt.chip.isConnected)?xt.at:-1,c=W?.root===s?W.chip.isConnected?r.indexOf(W.chip):W.at:-1;if(ya(s),e.length===0||n.size===0){$e.set(s,{signature:i,count:0}),c>=0&&pt(!1);return}let d=M(s);nr.has(s)||(nr.add(s),s.addEventListener("click",g=>{let _=g.target?.closest?.(`.${wt}`);!_||!s.contains(_)||(g.preventDefault(),xd(_))}),s.addEventListener("focusin",g=>{let _=g.target;_.classList?.contains(wt)&&(xt={root:s,chip:_,at:Array.from(s.querySelectorAll(`.${wt}`)).indexOf(_)})}),s.addEventListener("focusout",g=>{xt?.root===s&&g.relatedTarget&&(xt=null)}));let h=wd(s),u=new Map;for(let g of e){let _=g.sources.map(v=>n.get(v)).filter(v=>!!v);if(_.length===0)continue;let y=Sd(t.content,g,h);if(!y)continue;let b=h.ends.indexOf(y),k=g.marker&&g.start!==void 0?t.content.slice(g.start,g.end):null,x=u.get(b)??{node:y[0],offset:y[1],marker:k,sources:[]};for(let v of _)x.sources.includes(v)||x.sources.push(v);u.set(b,x)}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 _=Ed(g.sources,d);ma.set(_,s),!(g.marker&&kd(_,g.node,g.offset,g.marker))&&Cd(s,_,g.node,g.offset)}let f=Array.from(s.querySelectorAll(`.${wt}`));if($e.set(s,{signature:i,count:f.length}),l>=0&&(f[l]?f[l].focus({preventScroll:!0}):xt=null),c>=0&&W){let g=f[c];g?(W.chip=g,W.at=c,g.setAttribute("aria-expanded","true"),g.setAttribute("aria-controls",W.el.id)):pt(!1)}}function wa(s){let t=M(s);for(let e of Array.from(s.querySelectorAll(`.${wt}`)))va(e,t)}var W=null,Td=0;function xd(s){W?.chip===s?pt(!0):Md(s)}function Md(s){pt(!1);let t=Ks.get(s)??[];if(t.length===0)return;let e=ma.get(s)??s.parentElement,n=Array.from(e.querySelectorAll(`.${wt}`)).indexOf(s),i=M(s),r=document.createElement("div");r.className="aparte-citation-card aparte-popover",r.id=`aparte-citation-card-${++Td}`;let a=s.closest(".aparte-viewport-container, aparte-chat-viewport")??s.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"),(s.closest("aparte-chat-viewport")?.parentElement??s.ownerDocument.body).append(r),c&&r.showPopover(),s.setAttribute("aria-expanded","true"),s.setAttribute("aria-controls",r.id);let d=typeof MutationObserver=="function"?new MutationObserver(Ld):null;d?.observe(s.ownerDocument.body,{childList:!0,subtree:!0}),W={root:e,chip:s,at:n,el:r,body:o,status:l,sources:t,index:0,config:i,watch:d},ka(),de(),document.addEventListener("keydown",Aa,!0),document.addEventListener("pointerdown",Sa,!0),window.addEventListener("scroll",Ca,!0),window.addEventListener("resize",de),r.addEventListener("focusout",Od),r.addEventListener("keydown",Rd),Id(r)}function Id(s){(s.querySelector("a")??s.querySelector("button:not([disabled])"))?.focus()}function pt(s){if(!W)return;let{chip:t,el:e,watch:n}=W;W=null,n?.disconnect(),e.remove(),t.setAttribute("aria-expanded","false"),t.removeAttribute("aria-controls"),document.removeEventListener("keydown",Aa,!0),document.removeEventListener("pointerdown",Sa,!0),window.removeEventListener("scroll",Ca,!0),window.removeEventListener("resize",de),s&&t.isConnected&&t.focus()}function Ld(){W&&!W.chip.isConnected&&pt(!1)}function Aa(s){s.key!=="Escape"||!W||(s.preventDefault(),pt(!0))}function Rd(s){if(s.key!=="Tab"||!W)return;let t=Array.from(W.el.querySelectorAll("a[href], button:not([disabled])")),e=s.shiftKey?t[0]:t[t.length-1];document.activeElement===e&&(s.preventDefault(),pt(!0))}function Sa(s){if(!W)return;let t=s.target;t&&(W.el.contains(t)||W.chip.contains(t))||pt(!1)}function Od(s){if(!W)return;let t=s.relatedTarget;t&&(W.el.contains(t)||W.chip.contains(t))||t&&pt(!1)}function Pd(s){for(let t=s.parentElement;t;t=t.parentElement){let e=getComputedStyle(t).overflowY;if(e==="auto"||e==="scroll")return t}return null}function Ca(){if(!W)return;let s=Pd(W.chip);if(s){let t=s.getBoundingClientRect(),e=W.chip.getBoundingClientRect();if(e.bottom<t.top||e.top>t.bottom){pt(!1);return}}de()}function de(){if(!W)return;let{chip:s,el:t}=W;if(!s.isConnected){pt(!1);return}let e=s.getBoundingClientRect();t.style.left="0px",t.style.top="0px";let n=t.getBoundingClientRect(),i=6,a=getComputedStyle(s).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-n.left}px`,t.style.top=`${l-n.top}px`}function ka(){if(!W)return;let{el:s,body:t,status:e,sources:n,index:i,config:r}=W,a=r.getLocale(),o=n[i],l=s.contains(document.activeElement)?document.activeElement.dataset.aparteCardPart:void 0;if(t.replaceChildren(),n.length>1){let u=document.createElement("div");u.className="aparte-citation-card__pager";let p=rr(a.sourcePrevious??"Previous source",r.getIcon("prevBranch"),"prev",i===0,()=>ar(-1)),f=document.createElement("span");f.className="aparte-citation-card__position",f.textContent=`${i+1}/${n.length}`,f.setAttribute("aria-hidden","true");let g=rr(a.sourceNext??"Next source",r.getIcon("nextBranch"),"next",i===n.length-1,()=>ar(1));u.append(p,f,g),t.append(u)}let c=Vs(o),d=o.title||Ve(o)||o.url||"";if(c){let u=ba(c,d,r,a.opensInNewTab??"(opens in a new tab)");u.className="aparte-citation-card__title",u.dataset.aparteCardPart="link",u.addEventListener("click",Nd),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=Ve(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(n.length>1&&(e.textContent=(a.sourcePosition??"Source {i} of {n}").replace("{i}",()=>String(i+1)).replace("{n}",()=>String(n.length))),l){let u=s.querySelector(`[data-aparte-card-part="${l}"]`);u&&!u.disabled?u.focus():(s.querySelector(".aparte-citation-card__pager button:not([disabled])")??s.querySelector("a"))?.focus()}}function Nd(s){let t=W?.chip,e=s.currentTarget;if(!t?.isConnected)return;let n={href:e.getAttribute("href")??"",anchor:e,messageId:t.closest("aparte-chat-bubble")?.getAttribute("message-id")??null};st(t,"aparte-link-click",n,{cancelable:!0})||s.preventDefault()}function rr(s,t,e,n,i){let r=document.createElement("button");return r.type="button",r.className="aparte-btn aparte-btn--icon aparte-btn--sm",r.setAttribute("aria-label",s),r.dataset.aparteCardPart=e,r.disabled=n,r.innerHTML=t,r.addEventListener("click",i),r}function ar(s){W&&(W.index=Math.max(0,Math.min(W.sources.length-1,W.index+s)),ka(),de())}function Ea(s,t,e,n){let i=s.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=n.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=bs(n,r.length);return}i.dataset.aparteKey=l;let c=document.createElement("summary");c.className="aparte-sources__summary",c.textContent=bs(n,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=Ve(h),f=h.title||p||h.url||"",g=Vs(h);if(g?u.append(ba(g,f,n,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 ee=new WeakMap,or="<i>a</i>";function lr(){return M().renderMarkdown(or)!==P(or)}function Xt(s,t,e,n){Dd(s,t,e,n),qt(t,{streaming:n})}function Dd(s,t,e,n){let i=M();if(n){if(ee.delete(t),s._aparteSmd===void 0){let a=M().createStreamingMarkdownRenderer(t);a?(t.textContent="",s._aparteSmd={renderer:a,written:0}):s._aparteSmd=null}let r=s._aparteSmd;if(r){let a=e.slice(r.written);a&&(r.renderer.write(a),r.written=e.length);return}}else if(s._aparteSmd){let r=s._aparteSmd,a=e.slice(r.written);if(a&&(r.renderer.write(a),r.written=e.length),r.renderer.end(),s._aparteSmd=void 0,!lr()){ua(t),ya(t),t.innerHTML=i.sanitizeHtml(t.innerHTML),ee.set(t,{content:e,config:i,version:ht(i),writer:"parser"});return}}else{let r=ee.get(t);if(r?.content===e&&(r.writer==="parser"&&!lr()||r.writer==="markdown"&&r.config===i&&r.version===ht(i)))return}t.innerHTML=i.renderMarkdown(e),n?ee.delete(t):ee.set(t,{content:e,config:i,version:ht(i),writer:"markdown"})}function ys(s){if(!M().hasHighlightProvider())return;let t=s.querySelectorAll("pre > code:not([data-aparte-highlighted])");for(let e of t){let n=e.parentElement;if(!n)continue;let i=Array.from(e.classList).find(a=>a.startsWith("language-"))?.slice(9)??"";if(fs(i,s)||e.closest(".aparte-code-drawing"))continue;let r=e.textContent??"";e.setAttribute("data-aparte-highlighted",""),M().highlightCode(r,i,{fallback:!1}).then(a=>{(n.isConnected||n.parentElement)&&Ys(n,a)}).catch(()=>e.removeAttribute("data-aparte-highlighted"))}}function Ys(s,t){let e=document.createElement("template");e.innerHTML=t;for(let n of Array.from(e.content.querySelectorAll("code")))n.setAttribute("data-aparte-highlighted","");s.replaceWith(e.content)}var Bd={type:"text",render:s=>`<div class="aparte-segment aparte-segment-text" data-segment-id="${P(s.id)}"><div class="aparte-segment-content" dir="auto">${M().renderMarkdown(s.content)}</div></div>`,setup:(s,t)=>{let e=s.querySelector(".aparte-segment-content");e&&(t.isStreaming===!0?Xt(s,e,t.content,!0):(qt(e,{streaming:!1}),ys(e)),vs(e,t))},update:(s,t)=>{let e=s.querySelector(".aparte-segment-content");e&&(Xt(s,e,t.content,t.isStreaming!==!1),t.isStreaming===!1&&ys(e),vs(e,t))},getStyles:()=>""};function Qs(s,t){let e=Math.max(1,Math.round(s/1e3));try{let n=(a,o)=>new Intl.NumberFormat(t,{style:"unit",unit:o,unitDisplay:"narrow"}).format(a);if(e<60)return n(e,"second");let i=Math.floor(e/60),r=e%60;return r?new Intl.ListFormat(t,{style:"narrow",type:"unit"}).format([n(i,"minute"),n(r,"second")]):n(i,"minute")}catch{return`${e}s`}}var $d=24;function ws(s){if(s.label&&s.label!=="Thinking")return s.label;let t=M();if(!It(s))return t.t("thinking");let n=s.showDuration??t.getSegmentDefaults("thinking")?.showDuration===!0?ta(s):void 0;return n===void 0?t.t("thought"):t.t("thoughtFor").replace("{duration}",()=>Qs(n,t.getLocale().tag||void 0))}var As=s=>s.isStreaming===!0;function cr(s,t){let e=ws(t),n=s.querySelector(".aparte-thinking-label");n&&n.textContent!==e&&(n.textContent=e),n?.classList.toggle("aparte-shimmer",As(t)),s.querySelector(".aparte-thinking-content")?.setAttribute("aria-label",e)}var Hd={type:"thinking",render:s=>`<details class="aparte-segment aparte-segment-thinking aparte-accordion__item" data-segment-id="${P(s.id)}" ${s.collapsed===!1?"open":""}><summary class="aparte-accordion__header aparte-thinking-header"><span class="aparte-thinking-label${L(As(s)?" aparte-shimmer":"")}">${P(ws(s))}</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="${L(ws(s))}">${M().renderMarkdown(s.content)}</div></details>`,relabel:(s,t)=>cr(s,t),setup:(s,t)=>{let e=s.querySelector(".aparte-thinking-content");e&&(As(t)?Xt(s,e,t.content,!0):qt(e,{streaming:!1}))},update:(s,t)=>{cr(s,t);let e=s.querySelector(".aparte-thinking-content");if(!e)return;let n=e.scrollHeight-e.scrollTop-e.clientHeight<=$d,i=t.isStreaming!==!1;Xt(s,e,t.content,i),i||ys(e),n&&(e.scrollTop=e.scrollHeight)},getStyles:()=>""};function Xs(s){return typeof navigator<"u"&&navigator.clipboard&&typeof navigator.clipboard.writeText=="function"?navigator.clipboard.writeText(s):new Promise((t,e)=>{if(typeof document>"u"||typeof document.execCommand!="function"){e(new Error("[aparte] No clipboard available in this context"));return}let n=document.createElement("textarea");n.value=s,n.setAttribute("readonly",""),n.setAttribute("aria-hidden","true"),n.style.position="fixed",n.style.top="0",n.style.left="-9999px",n.style.opacity="0";let i=document.activeElement;document.body.appendChild(n),n.focus(),n.select(),n.setSelectionRange(0,s.length);let r=!1;try{r=document.execCommand("copy")}catch{r=!1}n.remove(),i instanceof HTMLElement&&i.focus(),r?t():e(new Error("[aparte] Clipboard write failed"))})}var qd=1500;function Ss(s,t){s.setAttribute("aria-label",t),s.setAttribute("title",t)}function Js(s){let t=L(M().t("copy")),e=M().getIcon("copy");return`<button type="button" class="aparte-btn aparte-btn--icon aparte-btn--sm ${L(s)}" data-action="copy" aria-label="${t}" title="${t}">${e}</button>`}function Ta(s,t){s.addEventListener("click",()=>{Xs(t()).catch(()=>{}),s.innerHTML=M(s).getIcon("check"),Ss(s,M(s).t("copied")),s.dataset.copied="1",setTimeout(()=>{s.innerHTML=M(s).getIcon("copy"),Ss(s,M(s).t("copy")),delete s.dataset.copied},qd)})}function xa(s){s.dataset.copied||(Ss(s,M().t("copy")),s.innerHTML=M().getIcon("copy"))}var Fd=400,Wd=256,dr=new Map;function Ud(s,t,e){if(s.delete(t),s.size>=Wd){let n=s.keys().next().value;n!==void 0&&s.delete(n)}s.set(t,e)}function ur(s){let t=Number(s.dataset.aparteHlLen);return Number.isFinite(t)&&t>0?t:0}function jd(s,t,e,n,i){let r=s.querySelector(t);if(!r)return;delete r.dataset.aparteSettled;let a=r.querySelector("[data-aparte-tail]"),o=ur(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(n||"text")}">${P(e)}</code></pre>`}let l=e.lastIndexOf(`
11
+ `)+1;if(l<=o)return;let c=Date.now();c-(dr.get(i)??0)<Fd||(Ud(dr,i,c),M(s).highlightCode(e.slice(0,l),n).then(d=>{let h=s.querySelector(t);if(!h||h.dataset.aparteSettled!==void 0||l<=ur(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 es=new WeakMap,Gt=new WeakMap,ns=new WeakMap;function hr(s,t){let e=s.querySelector(".aparte-code-content-wrapper");if(!e)return;let n=`${t.language??""}${t.content}`,i=M(),r=ns.get(s);if(r?.what===n&&r.config===i)return;ns.set(s,{what:n,config:i});let a=(Gt.get(s)??0)+1;Gt.set(s,a),e.dataset.aparteSettled="",i.highlightCode(t.content,t.language||"",{fallback:!1}).then(o=>{Gt.get(s)===a&&(e.innerHTML=o)}).catch(()=>{Gt.get(s)===a&&ns.delete(s)})}var Ye=s=>(s.language||"").trim().split(/\s+/)[0]??"";function pr(s,t){let e=Ye(t),n=e?M(s).getCodeLanguageRenderer(e):void 0;s.toggleAttribute("data-aparte-bare",!!n&&n.card!==!0)}function fr(s,t){let e=s.querySelector(".aparte-code-content-wrapper");if(!e)return;Gt.set(s,(Gt.get(s)??0)+1),e.dataset.aparteSettled="";let n=Ye(t),i=Array.from(e.querySelectorAll("pre > code")).find(r=>r.classList.contains(`language-${n}`));i||(e.innerHTML=`<pre><code class="language-${P(n)}"></code></pre>`,i=e.querySelector("pre > code")),i.textContent!==t.content&&(i.textContent=t.content),qt(e,{streaming:t.isStreaming===!0})}var zd={type:"code",render:s=>{let t=Js("aparte-code-copy");return`
12
+ <div class="aparte-segment aparte-segment-code" data-segment-id="${P(s.id)}">
13
+ <div class="aparte-code-header">
14
+ ${s.filename?`<span class="aparte-code-filename">${P(s.filename)}</span>`:'<span class="aparte-code-header-filler"></span>'}
15
+ <span class="aparte-code-language">${P(s.language||"")}</span>
16
+ ${t}
17
+ </div>
18
+ <div class="aparte-code-content-wrapper">
19
+ <pre><code class="language-${P(s.language||"text")}">${P(s.content)}</code></pre>
20
+ </div>
21
+ </div>
22
+ `},relabel:s=>{let t=s.querySelector(".aparte-code-copy");t&&xa(t)},setup:(s,t)=>{es.set(s,t.content),pr(s,t),fs(Ye(t),s)?fr(s,t):t.isStreaming!==!0&&hr(s,t);let e=s.querySelector(".aparte-code-copy");e&&Ta(e,()=>es.get(s)??"")},update:(s,t)=>{es.set(s,t.content),pr(s,t),fs(Ye(t),s)?fr(s,t):t.isStreaming===!0?jd(s,".aparte-code-content-wrapper",t.content,t.language||"",t.id):hr(s,t)},getStyles:()=>""};function Cs(s,t){switch(s){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 Gd={type:"error",render:s=>{let t=M(),e=Cs(s.code,r=>t.t(r)),n=t.getErrorRenderer?.();if(n){let r=n({message:s.content,...e!==void 0?{sentence:e}:{},...s.details!==void 0?{details:s.details}:{},...s.code!==void 0?{code:s.code}:{}});return r instanceof HTMLElement&&r.setAttribute("data-segment-id",s.id),r}let i=e??s.content;return`
23
+ <div class="aparte-segment aparte-alert aparte-alert--danger aparte-segment-error" data-segment-id="${P(s.id)}"${s.code?` data-error-code="${L(s.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
+ ${s.details?`<pre class="aparte-segment-error__details">${P(s.details)}</pre>`:""}
29
+ </div>
30
+ </div>
31
+ `},relabel:(s,t)=>{let e=M();if(e.getErrorRenderer?.())return;let n=s.querySelector(".aparte-alert__icon");n&&(n.innerHTML=e.getIcon("error")||"\u26A0");let i=s.querySelector(".aparte-alert__title");i&&(i.textContent=e.t("error"));let r=Cs(t.code,o=>e.t(o)),a=s.querySelector(".aparte-alert__message");a&&r!==void 0&&(a.textContent=r)},getStyles:()=>""};function Ma(s,t){if(!s||typeof s!="object"||Object.keys(s).length===0)return"";if(t)try{let e=t(s);if(typeof e=="string")return e}catch{}try{return JSON.stringify(s,null,2)}catch{return""}}var gr=new WeakSet;function Bt(s,t){for(let e of t.getToolLineProviders())try{let n=e(s);if(n&&typeof n=="object")return n}catch(n){gr.has(e)||(gr.add(e),console.error("[aparte] A tool-line provider threw; the row keeps its default line. Further throws from it are not reported.",n))}}var Jt=s=>typeof s=="string"?s.trim():"";function ln(s,t,e=Bt(s,t)){let n=s.toolCall?.name??"tool",i=t.getToolDisplay(n)?.label;if(i!==void 0)try{let a=typeof i=="function"?i(s):i;if(typeof a=="string"&&a.trim())return{text:a.trim(),isLabel:!0}}catch{}let r=Jt(e?.label);return r?{text:r,isLabel:!0}:{text:n,isLabel:!1}}function Kd(s,t,e=Bt(s,t)){return Ia(s,t,e).text}function Ia(s,t,e=Bt(s,t)){let n=t.getToolSummary(s.toolCall?.name??"");if(n)try{let r=Jt(n(s));if(r)return{text:r,isWords:!1}}catch{}let i=Jt(e?.target);return{text:i,isWords:i!==""}}function La(s,t){if(s===void 0)return"";try{return Jt(typeof s=="function"?s(t):s)}catch{return""}}function Ra(s,t,e){return La(e.getToolDisplay(s.toolCall?.name??"")?.activity,s)||Jt(t?.activity)}function Vd(s,t,e){return La(e.getToolDisplay(s.toolCall?.name??"")?.note,s)||Jt(t?.note)}function Oa(s){return Ma(s.toolCall?.input,M().getToolInputFormatter(s.toolCall?.name??""))}function ks(s){let t=M(),e=s.status??"pending",n=i=>P(i);return e==="awaiting-approval"?`${t.getIcon("pause")}${n(t.t("approvalWaiting"))}`:cn(s)?n(t.t("toolQueued")):e==="pending"?n(t.t("toolRunning")):e==="resolved"?`${t.getIcon("check")}${n(t.t("toolCompleted"))}`:e==="rejected"?`${t.getIcon("close")}${n(t.t("toolRejected"))}`:e==="aborted"?`${t.getIcon("stop")}${n(t.t("toolStopped"))}`:e==="failed"?`${t.getIcon("close")}${n(t.t("toolFailed"))}`:""}function Yd(s){let t=M();if(s.status==="rejected"){let e=s.refusal?.by;if(e==="policy")return t.t("toolRefusedByPolicy");if(e==="earlier-refusal")return t.t("toolNotRunAfterRefusal");let n=s.refusal?.instruction?.trim();return n?t.t("toolRejectedSaid").replace("{instruction}",()=>n):""}if(s.status==="aborted")switch(s.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 Pa(s,t){return[Yd(s),Vd(s,t,M())].filter(Boolean).join(" \xB7 ")}function Es(s){let t=Zd(s.result??"");return!t||s.status==="rejected"&&s.refusal?null:{key:"toolOutput",text:t}}function ss(s,t,e){let n=M().getToolDisplay(s.toolCall?.name??""),i=n&&"details"in n?n.details:t?.details;if(i===!1)return{kind:"none"};if(typeof i!="function")return{kind:"parts"};try{let r=i(s,e?Qd(e):void 0);return r?{kind:"body",body:typeof r=="string"?M().sanitizeHtml(r):r}:{kind:"none"}}catch{return{kind:"none"}}}function Ts(s){return s.tagName==="DETAILS"?s:s.querySelector(":scope > details.aparte-tool-disclosure")}var xs=s=>s.querySelector(':scope > .aparte-tool-detail[data-details="app"], :scope > .aparte-tool-disclosure > .aparte-tool-detail[data-details="app"]');function Na(s,t){let e=s.querySelector(".aparte-tool-detail");e&&(typeof t!="string"&&t.parentNode===e||(typeof t=="string"?(e.innerHTML=t,ue.delete(e)):(e.replaceChildren(t),ue.set(e,t)),He.set(e,Da(t))))}var ue=new WeakMap;function Qd(s){let t=xs(s),e=t?ue.get(t):void 0;return e&&e.parentNode===t?e:void 0}var He=new WeakMap,Da=s=>typeof s=="string"?s:s.outerHTML;function Xd(s,t){if(typeof t!="string"&&s.contains(t)){He.set(s,t.outerHTML);return}let e=He.get(s),n=Da(t);if(e===n)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&&Ms(r,i)&&Ms(r,s)?Ba(s,r,i):(s.replaceChildren(...Array.from(i.childNodes)),typeof t=="string"?ue.delete(s):ue.set(s,t)),He.set(s,n)}function Ms(s,t){if(s.childNodes.length!==t.childNodes.length)return!1;for(let e=0;e<s.childNodes.length;e++){let n=s.childNodes[e],i=t.childNodes[e];if(n.nodeType!==i.nodeType||n.nodeName!==i.nodeName||!Ms(n,i))return!1}return!0}function Ba(s,t,e){for(let n=0;n<s.childNodes.length;n++){let i=s.childNodes[n],r=t.childNodes[n],a=e.childNodes[n];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);Ba(i,r,a)}else r.nodeValue!==a.nodeValue&&(i.nodeValue=a.nodeValue)}}function _r(s,t,e){let n=s.querySelector(".aparte-tool-note");if(!n)return;let i=Pa(t,e);n.textContent!==i&&(n.textContent=i),n.toggleAttribute("hidden",!i),i?n.setAttribute("title",i):n.removeAttribute("title")}function mr(s,t,e,n){let i=s.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(n);g&&g.textContent!==_&&(g.textContent=_),i.querySelector(".aparte-tool-part-body")?.setAttribute("aria-label",_);return}let r=s.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(n);let d=document.createElement("template");d.innerHTML=Js("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),$a(o)}function $a(s){for(let t of s.querySelectorAll(".aparte-tool-copy")){if(t.dataset.wired)continue;t.dataset.wired="1";let e=t.closest(".aparte-tool-part");Ta(t,()=>e?.querySelector(".aparte-tool-part-body")?.textContent??"")}}var Jd=2e5;function Ha(s){let t=s.trim();if(!(t.length>Jd||!(t.startsWith("{")||t.startsWith("["))))try{let e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}}function Zd(s){let t=Ha(s);return t===void 0?s:JSON.stringify(t,null,2)}function br(s){let t=M();for(let e of s.querySelectorAll(".aparte-tool-part-body")){let n=e.querySelector("code")?.textContent??"";!n||Ha(n)===void 0||t.highlightCode(n,"json").then(i=>{(e.querySelector("code")?.textContent??"")===n&&(e.innerHTML=i)}).catch(()=>{})}}function qa(s,t){return Ia(s,M(),t)}function vr(s,t,e){let n=s.querySelector(".aparte-tool-target");if(!n)return;let{text:i,isWords:r}=qa(t,e);n.textContent!==i&&(n.textContent=i),n.toggleAttribute("hidden",!i),n.classList.toggle("aparte-tool-target--words",r)}function yr(s,t,e){let n=s.querySelector(".aparte-tool-activity");if(!n)return;let i=Ra(t,e,M());n.textContent!==i&&(n.textContent=i),n.toggleAttribute("hidden",!i)}function Fa(s,t){return ln(s,M(),t)}function Wa(s){let t=M(),e=t.getToolDisplay(s.toolCall?.name??"")?.icon;return(e?t.getIcon(e):void 0)||t.getIcon("tool")}var Zs=s=>M().getToolDisplay(s.toolCall?.name??"")?.quiet??!0,cn=s=>(s.status??"pending")==="pending"&&(s.queued===!0||s.deferred?.reason==="queued");function Ua(s){let t=s.status??"pending",e=Zs(s),n=t==="pending"&&!cn(s);return{shimmer:e&&n,spinner:!e&&n,stateHidden:e&&(n||t==="resolved")}}function wr(s,t){let e=Ua(t);s.toggleAttribute("data-quiet",Zs(t)),s.toggleAttribute("data-queued",cn(t)),s.querySelector(".aparte-tool-spinner")?.toggleAttribute("hidden",!e.spinner),s.querySelector(".aparte-tool-name")?.classList.toggle("aparte-shimmer",e.shimmer),s.querySelector(".aparte-tool-state")?.classList.toggle("aparte-sr-only",e.stateHidden)}function Ar(s,t,e){let n=s.querySelector(".aparte-tool-name");if(!n)return;let{text:i,isLabel:r}=Fa(t,e);n.textContent!==i&&(n.textContent=i),n.classList.toggle("aparte-tool-name--label",r)}var Is=new WeakMap;function dn(s){let t=s?.open;return t&&typeof t.onOpen=="function"?t:void 0}function tu(s){let t=dn(s);return t?` data-opens${t.current?" data-current":""}`:""}function ti(s){let t=dn(s);if(!t)return"";let e=L(typeof t.label=="string"?t.label.trim():""),n=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"':""}>${n}</button>`}function is(s,t,e){let n=dn(t),i=s.querySelector(":scope > .aparte-tool-line"),r=s.querySelector(":scope > :is(.aparte-tool-line, .aparte-tool-open-slot) > .aparte-tool-open");if(n?Is.set(s,n):Is.delete(s),e&&i&&!!n!=!!r)if(r)r.remove(),r=null;else{let o=document.createElement("template");o.innerHTML=ti(t),r=o.content.firstElementChild,i.insertBefore(r,i.querySelector(":scope > .aparte-tool-activity"))}if(s.toggleAttribute("data-opens",!!n&&!!r),s.toggleAttribute("data-current",!!n?.current&&!!r),!n||!r)return;let a=typeof n.label=="string"?n.label.trim():"";r.getAttribute("aria-label")!==a&&(r.setAttribute("aria-label",a),r.title=a),n.current?r.setAttribute("aria-current","true"):r.removeAttribute("aria-current")}var Sr=new WeakSet;function eu(s){Sr.has(s)||(Sr.add(s),s.addEventListener("click",t=>{let e=Is.get(s),n=t.target;if(!(!e||!n?.closest||n.closest(".aparte-segment-tool-call")!==s)&&!(!n.closest(".aparte-tool-open")&&(Ts(s)||n.closest(".aparte-tool-line")?.parentElement!==s||s.ownerDocument.getSelection?.()?.isCollapsed===!1)))try{e.onOpen(s)}catch(i){console.error("[aparte] a tool line's onOpen threw",i)}}))}function Cr(s,t,e=!0){let n=ks(s),i=Wa(s),r=qa(s,t),a=Ra(s,t,M()),o=Pa(s,t),l=Fa(s,t),c=Ua(s),d=e?ti(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":""}">${n}</span>
39
+ <span class="aparte-tool-note"${o?` title="${L(o)}"`:" hidden"}>${P(o)}</span>${d}
40
+ <span class="aparte-tool-activity"${a?"":" hidden"}>${P(a)}</span>`}function kr(s){return`<div class="aparte-segment aparte-segment-tool-call" data-segment-id="${P(s.id)}" data-status="${L(s.status??"pending")}" data-tool-call-id="${L(s.toolCall?.id??"")}" data-tool-name="${L(s.toolCall?.name??"tool")}" hidden></div>`}var Wt=s=>s.hidden&&s.classList.contains("aparte-segment-tool-call")&&s.childElementCount===0,ie=new WeakMap,qe=new WeakMap;function ja(s){return qe.get(s)??null}function Er(s,t){let e=ie.get(s);return e||(s.classList.contains("aparte-segment-tool-call")?null:t)}function Tr(s,t,e){let n=s.toolCall?.name??"tool",i=s.status??"pending",r=s.toolCall?.id??"",a=Cr(s,e),o=(Zs(s)?" data-quiet":"")+(cn(s)?" data-queued":""),l=tu(e),c=M().getIcon("expand"),d=t.kind==="parts"?Oa(s):"",h=t.kind==="parts"?Es(s):null;if(t.kind==="none"||t.kind==="parts"&&!d&&!h)return`
41
+ <div class="aparte-segment aparte-segment-tool-call" data-segment-id="${P(s.id)}" data-status="${L(i)}" data-tool-call-id="${L(r)}" data-tool-name="${L(n)}"${o}${l}><div class="aparte-tool-line">${a}</div>
42
+ </div>
43
+ `;let u=M(),p=Js("aparte-tool-copy"),f=s.collapsed!==void 0?!s.collapsed:u.getToolDisplay(n)?.open===!0,g=ti(e),_=g?`<details class="aparte-tool-disclosure"${f?" open":""}>`:"",y=g?`<div class="aparte-segment aparte-segment-tool-call" data-segment-id="${P(s.id)}" data-status="${L(i)}" data-tool-call-id="${L(r)}" data-tool-name="${L(n)}"${o}${l}>${_}`:`<details class="aparte-segment aparte-segment-tool-call" data-segment-id="${P(s.id)}" data-status="${L(i)}" data-tool-call-id="${L(r)}" data-tool-name="${L(n)}"${o}${l}${f?" open":""}>`,b=g?`</details><span class="aparte-tool-open-slot">${g}</span></div>`:"</details>",k=Cr(s,e,!1);if(t.kind==="body"){let x=document.createElement("template");x.innerHTML=`
44
+ ${y}
45
+ <summary class="aparte-tool-summary"><span class="aparte-tool-toggle">${c}</span>${k}</summary>
46
+ <div class="aparte-tool-detail" data-details="app"></div>
47
+ ${b}`.trim();let v=x.content.firstElementChild;return Na(v,t.body),v}return`
48
+ ${y}
49
+ <summary class="aparte-tool-summary"><span class="aparte-tool-toggle">${c}</span>${k}</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="${L(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="${L(u.t(h.key))}"><pre><code>${P(h.text)}</code></pre></div>
60
+ </div>`:""}
61
+ </div>
62
+ ${b}
63
+ `}var Kt={type:"tool_call",render:s=>{let t=s.toolCall?.name??"tool";if(M().isToolHidden(t))return kr(s);let e=M().getToolRenderer(t);if(e){Qa(t,e);let i=e.render(s);return i instanceof HTMLElement&&(ie.set(i,e),qe.set(i,e)),i||kr(s)}let n=Bt(s,M());return Tr(s,ss(s,n),n)},relabel:(s,t)=>{if(Wt(s))return;let e=M(),n=Er(s,e.getToolRenderer(t.toolCall?.name)??null);if(n){n.relabel?.(s,t);return}let i=Bt(t,e),r=s.querySelector(".aparte-tool-icon");r&&(r.innerHTML=Wa(t)),Ar(s,t,i),vr(s,t,i),yr(s,t,i),_r(s,t,i),is(s,i,!1);let a=s.querySelector('[data-part="input"] .aparte-tool-part-label');a&&(a.textContent=e.t("toolInput")),s.querySelector('[data-part="input"] .aparte-tool-part-body')?.setAttribute("aria-label",e.t("toolInput"));let o=Es(t),l=s.querySelector('[data-part="output"] .aparte-tool-part-label');l&&o&&(l.textContent=e.t(o.key)),o&&s.querySelector('[data-part="output"] .aparte-tool-part-body')?.setAttribute("aria-label",e.t(o.key));for(let h of s.querySelectorAll(".aparte-tool-copy"))xa(h);let c=xs(s);if(c){let h=ss(t,i,s);h.kind==="body"&&Xd(c,h.body)}let d=s.querySelector(".aparte-tool-state");d&&(d.innerHTML=ks(t)),wr(s,t)},update:(s,t)=>{let e=t.status??"pending",n=M().isToolHidden(t.toolCall?.name??"tool");if(n&&Wt(s)){s.setAttribute("data-status",e);return}let i=n?null:M().getToolRenderer(t.toolCall?.name)??null,r=Wt(s)?null:Er(s,i);if(r&&r===i&&r.update&&!Wt(s)){r.update(s,t);return}let a=_=>{let y=document.createElement("template");y.innerHTML=typeof _=="string"?_.trim():"";let b=typeof _=="string"?y.content.firstElementChild:_;return b&&(b.hasAttribute("data-segment-id")||b.setAttribute("data-segment-id",t.id),Kt.cleanup?.(s,t),s.replaceWith(b),Kt.setup?.(b,t)),b};if(i||r||n||Wt(s)){a(Kt.render(t));return}let o=Bt(t,M()),l=ss(t,o,s),c=l.kind==="parts"?Oa(t):"",d=l.kind==="parts"?Es(t):null,h=l.kind==="body"||!!c||!!d,u=!!xs(s),p=Ts(s),f=!!p&&p!==s;if(h!==!!p||h&&l.kind==="body"!==u||h&&f!==!!dn(o)){let _=p?.open,y=a(Tr(t,l,o)),b=y&&_!==void 0?Ts(y):null;b&&_!==void 0&&(b.open=_);return}s.setAttribute("data-status",e);let g=s.querySelector(".aparte-tool-state");if(g&&(g.innerHTML=ks(t)),wr(s,t),Ar(s,t,o),vr(s,t,o),yr(s,t,o),_r(s,t,o),is(s,o,!0),l.kind==="body"){Na(s,l.body);return}mr(s,"input",c,"toolInput"),mr(s,"output",d?.text??"",d?.key??"toolOutput"),br(s)},setup:(s,t)=>{let n=M().isToolHidden(t.toolCall?.name??"tool")?void 0:M().getToolRenderer(t.toolCall?.name);n&&qe.set(s,n),!Wt(s)&&(n||(is(s,Bt(t,M()),!1),eu(s)),$a(s),br(s),n&&ie.set(s,n),n?.setup?.(s,t))},cleanup:(s,t)=>{qe.delete(s);let e=ie.get(s);if(e){ie.delete(s);try{e.cleanup?.(s,t)}catch(n){console.error("[aparte] a tool renderer's cleanup threw",n)}}},getStyles:()=>""};function xr(s){let t=document.createElement("div");return t.className="aparte-segment aparte-segment-activity",t.setAttribute("data-segment-id",s.id),t.setAttribute("data-activity-type",s.activityType),t.hidden=!0,t}var Mr=s=>s.hidden&&s.classList.contains("aparte-segment-activity")&&s.childElementCount===0,Ut=new WeakMap,Fe=new WeakMap;function za(s){return Fe.get(s)??null}var rs=s=>M().getActivityRenderer(s.activityType)??null,Vt={type:"activity",render:s=>{let t=rs(s);if(!t)return xr(s);let e=t.render(s);return e instanceof HTMLElement?(Ut.set(e,t),Fe.set(e,t),e):e.trim()?e:xr(s)},setup:(s,t)=>{let e=rs(t);e&&(Fe.set(s,e),!Mr(s)&&(Ut.set(s,e),e.setup?.(s,t)))},update:(s,t)=>{let e=rs(t),n=Ut.get(s)??null;if(n&&n===e&&n.update){n.update(s,t);return}if(!e&&!n&&Mr(s)){s.setAttribute("data-activity-type",t.activityType);return}let i=Vt.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),Vt.cleanup?.(s,t),s.replaceWith(r),Vt.setup?.(r,t))},relabel:(s,t)=>{Ut.get(s)?.relabel?.(s,t)},cleanup:(s,t)=>{Fe.delete(s);let e=Ut.get(s);if(e){Ut.delete(s);try{e.cleanup?.(s,t)}catch(n){console.error("[aparte] an activity renderer's cleanup threw",n)}}}},Ir=new WeakMap;function St(s){let t=Ir.get(s);return t||(t={renderers:new Map,defaultsInstalled:!1,defaultsDeclined:!1},Ir.set(s,t)),t}function Ga(s){let t=St(s);if(s===Q||t.defaultsDeclined)return t.renderers;let e=new Map(St(Q).renderers);for(let[n,i]of t.renderers)e.set(n,i);return e}var Ot=null;function oe(s,t=M()){let e=St(t);e.renderers.get(s.type)!==s&&(e.renderers.set(s.type,s),ni(t),Dt(t))}var Lr=new WeakMap;function nu(s,t=M()){let e=s.type,n=St(t),i=Lr.get(t);i||(i=new Map,Lr.set(t,i));let r=n.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:s};a.push(o),oe(s,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||n.renderers.get(e)!==s)return;let h=a[a.length-1].renderer;if(h){oe(h,t);return}if(Ya(e,t),!Ga(t).has(e)&&n.defaultsInstalled&&!n.defaultsDeclined){let u=si.find(p=>p.type===e);u&&oe(u,t)}}}function Ka(s=M()){St(s).defaultsDeclined=!0}function Va(s=M()){let t=St(s);if(!(t.defaultsInstalled||t.defaultsDeclined)){t.defaultsInstalled=!0;for(let e of si)t.renderers.has(e.type)||t.renderers.set(e.type,e);ni(s)}}function Ya(s,t=M()){let e=St(t);e.renderers.has(s)&&(e.renderers.delete(s),Dt(t))}function ei(s,t=M()){return Ga(t).get(s)}var Re=new Set;function ni(s=M()){if(typeof document>"u")return;(!Ot||!Ot.isConnected)&&(Ot=document.createElement("style"),Ot.id="aparte-renderer-styles",document.head.appendChild(Ot),Ot.textContent=Array.from(Re).join(`
64
+ `));let t=!1;for(let e of St(s).renderers.values()){let n=e.getStyles?.();!n||Re.has(n)||(Re.add(n),t=!0)}t&&(Ot.textContent=Array.from(Re).join(`
65
+ `))}var Rr=new WeakMap;function Qa(s,t){if(typeof document>"u")return;let e=t.getStyles?.();if(!e)return;let n=Rr.get(t);if(n||(n=`aparte-tool-renderer-${s}`,Rr.set(t,n)),document.getElementById(n))return;let i=document.createElement("style");i.id=n,i.textContent=e,document.head.appendChild(i)}function Xa(s=M()){let t=St(s);t.defaultsInstalled=!0;for(let e of si)t.renderers.has(e.type)||oe(e,s);ni(s)}var si=[Bd,Hd,zd,Gd,Kt,Vt];function We(s){let{target:t,config:e,messageId:n,targetId:i,conversationId:r,observe:a=!0}=s,o={messageId:n,...r?{conversationId:r}:{}},l=new Yt({blocks:e.getStreamBlocks()}),c=new Set,d=null,h=new Map,u=new Set,p=(T,R)=>u.delete(T)?{...R,queued:void 0}:R,f=(T,R)=>{let q=`tool-${T}`;t.updateSegment?.(q,p(q,h.has(q)?R:{...R,deferred:void 0}))},g="",_=!1,y="",b=new Map,k=[],x=[],v=new Set,E=T=>{let R=T.content;typeof R=="string"&&b.set(T.id,{text:T.type==="text",content:R})},A=()=>{if(k.length===0)return;let T=0,R=[...b].map(([U,{text:ut,content:at}])=>{let et=y.indexOf(at,T);return et>=0&&(T=et+at.length),{id:U,text:ut,start:et,length:at.length,citations:[]}}).filter(U=>U.text);if(R.length===0)return;let q=new Set;for(let U of x){let ut=R.find(F=>F.start>=0&&U.end>F.start&&U.end<=F.start+F.length);if(!ut)continue;let at=U.end-ut.start,et=U.start===void 0?void 0:Math.max(0,Math.min(at,U.start-ut.start));ut.citations.push({...U,end:at,...et===void 0?{}:{start:et}});for(let F of U.sources)q.add(F)}let $=R[R.length-1],X=new Set;for(let U of R){let ut=new Set(U.citations.flatMap(et=>et.sources)),at=k.filter(et=>ut.has(et.id)||U===$&&!q.has(et.id));if(at.length===0){v.has(U.id)&&t.updateSegment?.(U.id,{sources:void 0,citations:void 0});continue}X.add(U.id),t.updateSegment?.(U.id,{sources:at,citations:U.citations})}v=X},w=T=>{if(!d||_)return;let R=typeof Element<"u"&&t instanceof Element?I(t):e,q=!T||R.getSegmentDefaults("thinking")?.collapsed===!1;t.updateSegment?.(d,q?{isStreaming:!1}:{collapsed:!0,isStreaming:!1}),_=!0},m=[],S=null,O=()=>{let T=m.at(-1)??null;T!==S&&(S=T,t.setStep?.(n,T))},C=()=>{m.length=0,O()},N=()=>{let T=l.finalize();for(let R of T)E(R),c.has(R.id)?"content"in R&&t.updateSegment?.(R.id,Yn(R)):t.addSegment?.(R);A()},D=new Set,H=T=>D.has(T)?!0:(t.getMessage?t.getMessage(n)?.segments:t.segments)?.some(q=>q.id===T)?(D.add(T),!0):!1,tt=T=>{switch(T.type){case"step-start":m.push(T.name),O();break;case"step-end":{let R=m.lastIndexOf(T.name);R>=0&&m.splice(R,1),O();break}case"run-start":t.updateMessage?.(n,{status:"streaming"});break;case"turn-start":w(!1),l=new Yt({blocks:e.getStreamBlocks()}),c=new Set,y="",b=new Map,k=v.size===0?k.map(R=>({...R,id:`${R.id}~`})):[],x=[],v=new Set,d=null,g="",_=!1;break;case"thinking-delta":{if(g+=T.delta,d)t.updateSegment?.(d,{content:g});else{let R={id:`think-${J()}`,type:"thinking",content:g,isStreaming:!0};d=R.id,c.add(R.id),t.addSegment?.(R)}break}case"text-delta":{w(!0),y+=T.delta;let R=l.parse(T.delta);for(let $ of R.segments)E($),c.has($.id)?"content"in $&&t.updateSegment?.($.id,Yn($)):(t.addSegment?.($),c.add($.id));let q=l.getState().activeSegment;q?(E(q),c.has(q.id)?t.updateSegment?.(q.id,Yn(q)):(t.addSegment?.(q),c.add(q.id))):R.segments.length;break}case"text-flush":N();break;case"activity":{let R=`activity-${T.id}`;if(H(R)){t.updateSegment?.(R,{activityType:T.activityType,content:T.content});break}D.add(R),N();let q={id:R,type:"activity",activityId:T.id,activityType:T.activityType,content:T.content};t.addSegment?.(q);break}case"sources":{let R=new Map(k.map($=>[$.id,$]));for(let $ of Array.isArray(T.sources)?T.sources:[])R.set($.id,{...R.get($.id),...$});k=[...R.values()];let q=new Set(x.map($=>JSON.stringify([$.start,$.end,$.marker,$.sources])));for(let $ of Array.isArray(T.citations)?T.citations:[]){let X=JSON.stringify([$.start,$.end,$.marker,$.sources]);q.has(X)||(q.add(X),x.push($))}A();break}case"tool-start":{w(!1);let R={id:`tool-${T.toolCallId}`,type:"tool_call",toolCall:{id:T.toolCallId,name:T.name,input:T.input},status:"pending",...T.queued?{queued:!0}:{}};h.set(R.id,R),T.queued&&u.add(R.id);let q=e.getToolRenderer(T.name);q&&Qa(T.name,q),t.addSegment?.(R);break}case"tool-running":{let R=`tool-${T.toolCallId}`;u.delete(R)&&t.updateSegment?.(R,{queued:void 0});break}case"tool-awaiting-approval":t.updateSegment?.(`tool-${T.toolCallId}`,p(`tool-${T.toolCallId}`,{status:"awaiting-approval"})),lt(t,"aparte-tool-approval-request",{toolCallId:T.toolCallId,toolName:T.name,input:T.input,...o},i);break;case"tool-approved":f(T.toolCallId,{status:"pending"});break;case"tool-rejected":f(T.toolCallId,{status:"rejected",result:T.reason,...T.by?{refusal:T.instruction?{by:T.by,instruction:T.instruction}:{by:T.by}}:{}});break;case"tool-resolved":f(T.toolCallId,{status:"resolved",result:T.result,...T.structuredResult!==void 0?{structuredResult:T.structuredResult}:{}});break;case"tool-aborted":f(T.toolCallId,T.cause?{status:"aborted",abortCause:T.cause}:{status:"aborted"});break;case"tool-failed":f(T.toolCallId,{status:"failed",result:T.error});break;case"turn-limit-exceeded":T.scope==="global"?t.addSegment?.({id:`max-turns-${J()}`,type:"error",content:(typeof Element<"u"&&t instanceof Element?I(t):e).t("maxTurnsReached").replace("{n}",()=>String(T.limit)),code:z.MAX_TURNS_EXCEEDED}):T.toolCallId&&f(T.toolCallId,{status:"aborted",abortCause:"turn-limit"});break;case"run-aborted":C(),lt(t,"aparte-message-aborted",{messageId:n},i);break;case"run-suspended":{C();let R=T.ticket;for(let q of T.pending){if(q.agentId!=null)continue;let $=`tool-${q.toolCallId}`,X={reason:q.reason,...typeof R=="string"?{ticket:R}:{}};t.updateSegment?.($,p($,{deferred:X}))}if(t.updateMessage?.(n,{status:"completed"}),T.usage)try{t.setUsage?.(n,T.usage)}catch{}lt(t,"aparte-message-paused",{messageId:n},i);break}case"run-done":if(C(),t.updateMessage?.(n,{status:"completed",...T.finishReason?{finishReason:T.finishReason}:{}}),T.usage)try{t.setUsage?.(n,T.usage)}catch{}break}},rt=()=>typeof Element<"u"&&t instanceof Element?I(t):e,gt=new Set,te=(T,R)=>{let q=new Set;for(let X of new Set([R,e,Q]))for(let U of X.getRunEventObservers())q.add(U);if(q.size===0)return!1;let $={messageId:n,target:t,...i!==void 0?{targetId:i}:{},config:R};for(let X of q)try{X(T,$)}catch(U){gt.has(X)||(gt.add(X),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 T=>{let R=rt(),q=!a||te(T,R),$=T.agentId;if($==null&&T.type!=="agent-start"&&T.type!=="agent-end"){tt(T);return}!q&&!Or.has(R)&&(Or.add(R),console.warn(`[aparte] A sub-agent's events arrived (agent "${String($)}") 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().`)),T.type==="tool-awaiting-approval"&&lt(t,"aparte-tool-approval-request",{toolCallId:T.toolCallId,toolName:T.name,input:T.input,agentId:$,...o},i)}}var Or=new WeakSet;function Ja(s,t){return{[Symbol.asyncIterator](){let e=s.getReader(),n=()=>{try{e.cancel().catch(()=>{})}catch{}};return t.aborted?n():t.addEventListener("abort",n,{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",n);try{await e.cancel()}catch{}try{e.releaseLock()}catch{}return{done:!0,value:void 0}}}}}}var Rp=new TextEncoder;var Op=10080*60*1e3;function ii(s){let t=typeof document>"u"?void 0:document.baseURI;try{return t?new URL(s,t):new URL(s)}catch{return null}}function su(){let s=typeof location>"u"?null:location.origin;return s&&s!=="null"?s:null}function iu(s){try{let t=new URL(s);return t.protocol==="http:"||t.protocol==="https:"?t.origin:null}catch{return null}}function ru(s,t){return s===t?!0:typeof s=="function"||typeof t=="function"?!1:s.length===t.length&&s.every((e,n)=>e===t[n])}var Pr=new WeakSet;function as(s){if(typeof s=="function")return(i,r)=>{try{let a=s(r?r.href:i);return a==="load"||a==="drop"?a:"hold"}catch(a){return Pr.has(s)||(Pr.add(s),console.warn("[aparte] The image policy threw, so the pictures it was asked about are held.",a)),"hold"}};let t=!1,e=!1,n=new Set;for(let i of s){let r=typeof i=="string"?i.trim():"";if(r==="*")t=!0;else if(r==="self"||r==="'self'")e=!0;else{let a=iu(r);a?n.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&&(n.has(r.origin)||e&&r.origin===su())?"load":"hold"}var $t=/^[\u0000- ]*$/;function au(s,t,e){if($t.test(t))return"load";let n=ii(t);if(n){if(n.protocol==="data:"||n.protocol==="blob:")return"load";if(n.protocol!=="http:"&&n.protocol!=="https:")return"drop"}let i=s(t,n);return i==="hold"&&n!==null&&e?.has(n.href)?"load":i}var Qe=new WeakMap;function ou(s,t){let e=ii(t);if(!e)return;let n=Qe.get(s);n||Qe.set(s,n=new Set),n.add(e.href)}function lu(s){return Qe.get(s)}function cu(s){Qe.delete(s)}var Oe=/[\t\n\f\r ]/,du=/^(?:|\d+w(?: \d+h)?|(?:\d+|\d*\.\d+)(?:[eE][+-]?\d+)?x)$/;function Za(s){let t=[],e=s.length,n=0;for(;n<e;){for(;n<e&&(Oe.test(s[n])||s[n]===",");)n++;if(n>=e)break;let i=n;for(;n<e&&!Oe.test(s[n]);)n++;let r=s.slice(i,n),a=[];if(r.endsWith(","))r=r.replace(/,+$/,"");else{let l="",c="in";for(;;){let d=s[n];if(c==="in"){if(d===void 0){l&&a.push(l);break}if(d===","){n++,l&&a.push(l);break}Oe.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(!Oe.test(d)){c="in";continue}}n++}}let o=a.join(" ");r&&du.test(o)&&t.push({url:r,descriptor:o})}return t}function to(s){return s.map(t=>t.descriptor?`${t.url} ${t.descriptor}`:t.url).join(", ")}function eo(s){let t=ii(s);if(t?.hostname)return t.hostname;let e=s.trim();return e.length>48?`${e.slice(0,47)}\u2026`:e}function Xe(s,t,e,n=!1){let i=eo(s),r=t?e.named(i,t):e.load(i),a=e.icon;return`${n?'<span class="aparte-tag aparte-image-held" role="button" tabindex="0"':`<a class="aparte-tag aparte-image-held" href="${L(s)}" target="_blank" rel="noopener noreferrer"`} data-aparte-image="${L(s)}"${t?` data-aparte-image-alt="${L(t)}"`:""} title="${L(e.load(i))}" aria-label="${L(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>${n?"</span>":"</a>"}`}function no(s,t){return`<img src="${L(s)}" alt="${L(t)}" referrerpolicy="no-referrer">`}var so=/<(?:img|source)\b|data-aparte-image/i,uu="a[data-aparte-image], span[data-aparte-image]";function hu(s,t,e){return!s||!so.test(s)?s:typeof document>"u"?vu(s,t,e):pu(s,t,e)}function io(s,t,e){let n=t===void 0?[]:Za(t),i=$t.test(s)?n[0]?.url:s;if(i===void 0)return null;let r=e(i);if(r!=="load")return{decision:r,address:i,srcset:null};let a=n.filter(o=>e(o.url)==="load");return{decision:r,address:i,srcset:a.length?to(a):null}}function ro(s,t,e){if(!$t.test(s)&&e(s)!=="load")return!1;if(t===void 0)return $t.test(s)?!1:null;let n=Za(t).filter(i=>e(i.url)==="load");return n.length?to(n):$t.test(s)?!1:null}function pu(s,t,e){let n=document.createElement("template");n.innerHTML=s;let i=n.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(uu))){let c=l.getAttribute("data-aparte-image")??"",d=l.getAttribute("data-aparte-image-alt")??"",h=$t.test(c)?"drop":t(c);a=!0,h==="drop"?l.remove():l.replaceWith(o(h==="load"?no(c,d):Xe(c,d,r??=e(),!!l.parentElement?.closest("a"))))}for(let l of Array.from(i.querySelectorAll("source"))){let c=ro(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=io(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(Xe(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?n.innerHTML:s}var fu=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes","noscript","plaintext"]),gu=new Set(["area","base","br","col","embed","hr","img","input","link","meta","source","track","wbr"]),_u=/[A-Za-z]/,mu=/^[a-z][a-z0-9_.:-]*$/;function os(s,t,e){let n=t.filter(([r])=>!(r in e)&&mu.test(r)),i=Object.entries(e).filter(r=>r[1]!==null);return`<${s}${[...n,...i].map(([r,a])=>` ${r}="${L(a)}"`).join("")}>`}function bu(s,t,e){let n=new RegExp(`<(/?)${t}(?=[\\s/>])`,"g");n.lastIndex=e;let i=1;for(let r=n.exec(s);r;r=n.exec(s))if(i+=r[1]?-1:1,i===0){let a=s.indexOf(">",r.index);return a<0?s.length:a+1}return-1}function vu(s,t,e){if(!s||!so.test(s))return s;let n=s.toLowerCase(),i=s.length,r,a="",o=0,l=0,c=[];for(;o<i;){let d=s.indexOf("<",o);if(d<0){a+=s.slice(o);break}if(a+=s.slice(o,d),s.startsWith("<!--",d)){let b=s.indexOf("-->",d+4),k=b<0?i:b+3;a+=s.slice(d,k),o=k;continue}let h=s[d+1]==="/",u=d+(h?2:1);if(!_u.test(s[u]??"")){a+="<",o=d+1;continue}let{tag:p,attrs:f,end:g}=Gs(s,u);if(g<0){a+=s.slice(d);break}o=g;let _=s.slice(d,g);if(h){p==="a"&&(l=Math.max(0,l-1));let b=c.lastIndexOf(p);b>=0&&(c.length=b),a+=_;continue}let y=b=>f.find(([k])=>k===b)?.[1];if(fu.has(p)){let b=n.indexOf(`</${p}`,g),k=b<0?i:b;a+=_+s.slice(g,k),o=k;continue}if((p==="a"||p==="span")&&y("data-aparte-image")!==void 0){let b=bu(n,p,g);b>=0?o=b:p==="a"&&(l+=1);let k=y("data-aparte-image")??"",x=y("data-aparte-image-alt")??"",v=$t.test(k)?"drop":t(k);v==="load"?a+=no(k,x):v==="hold"&&(a+=Xe(k,x,r??=e(),l>0));continue}if(p==="a"&&(l+=1),p==="source"){let b=ro(y("src")??"",y("srcset"),t);if(b===!1)continue;a+=b===(y("srcset")??null)?_:os(p,f,{srcset:b});continue}if(p==="img"){let b=io(y("src")??"",y("srcset"),t);if(!b){let k=c[c.length-1]==="picture";y("srcset")===void 0&&(!k||y("referrerpolicy")==="no-referrer")?a+=_:a+=os(p,f,{srcset:null,...k?{referrerpolicy:"no-referrer"}:{}});continue}b.decision==="hold"?a+=Xe(b.address,y("alt")??"",r??=e(),l>0):b.decision==="load"&&(a+=os(p,f,{srcset:b.srcset,referrerpolicy:"no-referrer"}));continue}!gu.has(p)&&!_.endsWith("/>")&&c.push(p),a+=_}return a}var yu=/^(?:#|mailto:|tel:|sms:)/i,wu=[["target","_blank"],["rel","noopener noreferrer"]],Au=Object.freeze({target:"_blank",rel:"noopener noreferrer"}),Su=Object.freeze({});function ri(s,t,e){return s!=="external-only"&&!yu.test(t.replace(js,""))?wu:zs(t,e)}function Cu(s,t){return ri(s,t,"").length?Au:Su}var ao=/<a[\s/>]/i;function ku(s,t){return!s||!ao.test(s)?s:typeof document>"u"?Ou(s,t):Tu(s,t)}function Eu(s){let t=(s??"").split(/[ \t\n\f\r]+/).filter(e=>e&&e.toLowerCase()!=="opener");for(let e of["noopener","noreferrer"])t.some(n=>n.toLowerCase()===e)||t.push(e);return t.join(" ")}function oo(s,t,e){let n=s.find(([r])=>r==="target")?.[1];if(n!=="_blank")return(t??void 0)===n?null:{target:n,rel:void 0};let i=Eu(e);return(t??void 0)===n&&(e??void 0)===i?null:{target:n,rel:i}}function Tu(s,t){let e=document.createElement("template");e.innerHTML=s;let n=!1;for(let i of Array.from(e.content.querySelectorAll("a[href]"))){let r=ri(t,i.getAttribute("href")??"",i.getAttribute("target")??""),a=oo(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)),n=!0)}return n?e.innerHTML:s}var xu=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes","noscript","plaintext"]),Mu=/[A-Za-z]/,Iu=/^[a-z][a-z0-9_.:-]*$/,Nr=/--!?>/g;function Lu(s,t){if(s[t]===">")return t+1;if(s.startsWith("->",t))return t+2;Nr.lastIndex=t;let e=Nr.exec(s);return e?e.index+e[0].length:s.length}function Ru(s,t,e){let n=c=>t.find(([d])=>d===c)?.[1],i=n("href");if(i===void 0)return s;let r=ri(e,i,n("target")??""),a=oo(r,n("target"),n("rel"));if(!a)return s;let o=t.filter(([c])=>c!=="target"&&(a.rel===void 0||c!=="rel")&&Iu.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}="${L(d)}"`).join("")}>`}function Ou(s,t){if(!s||!ao.test(s))return s;let e=s.toLowerCase(),n=s.length,i="",r=0;for(;r<n;){let a=s.indexOf("<",r);if(a<0){i+=s.slice(r);break}if(i+=s.slice(r,a),s.startsWith("<!--",a)){let p=Lu(s,a+4);i+=s.slice(a,p),r=p;continue}let o=s[a+1]==="/",l=a+(o?2:1);if(!Mu.test(s[l]??"")){i+="<",r=a+1;continue}let{tag:c,attrs:d,end:h}=Gs(s,l);if(h<0){i+=s.slice(a);break}r=h;let u=s.slice(a,h);if(o){i+=u;continue}if(xu.has(c)){let p=e.indexOf(`</${c}`,h),f=p<0?n:p;i+=u+s.slice(h,f),r=f;continue}i+=c==="a"?Ru(u,d,t):u}return i}var At=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 Pu(s){return s?s.tagName?.toLowerCase()==="aparte-chat"||s.hasAttribute?.("data-aparte-chat")===!0:!1}function bt(s){let t=s??null;for(;t;){if(Pu(t))return t;t=t.parentElement}return null}var Je=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 n=String(t),i=this.patterns.get(n);i?i.value=e:this.patterns.set(n,{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:n,value:i}of this.patterns.values())if(t.search(n)!==-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}},Dr=!1,Mt={copy:!1,retry:!1,edit:!1,feedback:!1,info:!1},re={attachmentPreview:!1,filePreview:!1},Br=()=>{},lo=new WeakMap;function ht(s){return lo.get(s)??0}function it(s){lo.set(s,ht(s)+1)}var Ls=new Set,Pe=new Set;function co(s){return Ls.add(s),()=>{Ls.delete(s)}}function Dt(s){Pe.size===0&&queueMicrotask(()=>{let t=[...Pe];Pe.clear();for(let e of t)for(let n of[...Ls])try{n(e)}catch(i){console.error("[aparte] a renderer-change listener threw",i)}}),Pe.add(s)}var Nu=s=>s instanceof RegExp?`re:${String(s)}`:`name:${s}`,ls=["hidden","open","details","quiet"];function cs(s,t){if(!s||!(t in s)||t in Object.prototype)return;let e=s[t];return typeof e=="function"?e.bind(s):void 0}var $r=new WeakSet;function Du(s){let t=new Set;for(let e=s;e&&e!==Object.prototype;e=Object.getPrototypeOf(e))for(let n of Object.getOwnPropertyNames(e))n!=="constructor"&&t.add(n);return[...t]}var he=class{_markdownProvider;_streamingMarkdownProvider;_highlightProvider;_codeLanguageRenderers=new Map;_sanitizer=ms;_imagePolicy=[];_imageDecider=as([]);_imagePolicyNamed=!1;_linkTarget="new-tab";_systemPromptTemplate;_systemPromptVarsProvider;_statusRenderer;_errorRenderer;_attachmentRenderer;_siblingNavRenderer;_bubbleShellRenderer;_iconProvider;_avatarProvider;_keyProvider;_extraKeyProviders=new Set;_locale=zt;_actions=[];_listeners=new Set;_aiProviders=new Map;_fetchedModels=new Map;_modelConfig={};_requireModelSelection=!1;_queueWhileStreaming=!1;_elicitationAllowOther=!0;_elicitationLayout="stepped";_elicitationAnswerOnClick=!0;_elicitationFieldRenderer;_transport=new ze;_modelPreferenceProvider;_approvalPolicy=null;_compactor=null;_conversationManager;_elicitationPresenters=[];_elicitationObservers=new Set;_warnedNoPresenter=!1;_elicitationQueue=new Map;_tools=new Map;_toolRenderers=new Je;_toolRendererOverrides=new Map;_overrideGeneration=0;_toolDisplays=new Je;_activityRenderers=new Map;_toolLineProvider=null;_extraToolLineProviders=[];_stepLabels=new Map;_streamBlocks=new Map;_segmentDefaults=new Map;_runEventObservers=[];_hostHandlers={...re};_bubbleActionsConfig={...Mt};_turnSummary=null;_streamingCaret=!1;_dateSeparators=!1;registerAction(t){let e=this._actions.findIndex(n=>n.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,n)=>(e.order||0)-(n.order||0))}unregisterAction(t){let e=this._actions.length;this._actions=this._actions.filter(n=>n.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,it(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??re.attachmentPreview,filePreview:this._hostHandlers.filePreview??re.filePreview}}getBubbleActions(){return{copy:this._bubbleActionsConfig.copy??Mt.copy,retry:this._bubbleActionsConfig.retry??Mt.retry,edit:this._bubbleActionsConfig.edit??Mt.edit,feedback:this._bubbleActionsConfig.feedback??Mt.feedback,info:this._bubbleActionsConfig.info??Mt.info,feedbackReasons:this._bubbleActionsConfig.feedbackReasons,user:this._bubbleActionsConfig.user,assistant:this._bubbleActionsConfig.assistant}}setMarkdownProvider(t){this._markdownProvider=t,it(this),this._notify()}setStreamingMarkdownProvider(t){this._streamingMarkdownProvider=t,it(this),this._notify()}createStreamingMarkdownRenderer(t){return this._streamingMarkdownProvider?this._streamingMarkdownProvider(t):null}setHighlightProvider(t){this._highlightProvider=t,it(this),this._notify()}hasHighlightProvider(){return!!this._highlightProvider}registerCodeLanguageRenderer(t){let e=t.languages.map(n=>n.toLowerCase());for(let n of e)this._codeLanguageRenderers.set(n,t);return it(this),this._notify(),()=>{let n=!1;for(let i of e)this._codeLanguageRenderers.get(i)===t&&(this._codeLanguageRenderers.delete(i),n=!0);n&&(it(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,it(this),this._notify())}sanitizeHtml(t){let e=this._sanitizer?this._sanitizer(t):t,n=ku(e,this._linkTarget);return hu(n,i=>this.decideImage(i),()=>this._heldImageWords())}setImagePolicy(t){this._imagePolicyNamed=!0,!ru(t,this._imagePolicy)&&(this._imagePolicy=typeof t=="function"?t:[...t],this._imageDecider=as(t),it(this),this._notify())}decideImage(t){let e=au(this._imageDecider,t,lu(this));return e==="hold"&&this._noteHeldImage(t),e}_noteHeldImage(t){this._imagePolicyNamed||Dr||(Dr=!0,console.warn(`[aparte] A picture from ${eo(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){ou(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,it(this),this._notify())}getLinkTarget(){return this._linkTarget}decideLink(t){return Cu(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,(n,i)=>t[i.trim()]??"").trim()||null}setIconProvider(t){this._iconProvider=t,this._notify()}registerIcons(t){let e=this._iconProvider;if(e&&$r.has(e))Object.assign(e,t);else{let n=Object.assign(Object.create(e??null),t);$r.add(n),this._iconProvider=n}this._notify()}getIconProvider(){let t=this._iconProvider,e={};for(let n of Object.keys(se))e[n]=cs(t,n)??(()=>se[n]);for(let n of Du(t)){let i=cs(t,n);i&&!(n in e)&&(e[n]=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=zt,this._notify()}getLocale(){return this._locale}extendLocale(t){this._locale={...this._locale,...t},this._notify()}getIcon(t){let e=cs(this._iconProvider,t);return e?e():Object.prototype.hasOwnProperty.call(se,t)?se[t]:void 0}setKeyProvider(t){this._keyProvider=t}registerKeyProvider(t){let e=n=>t(n);return this._extraKeyProviders.add(e),()=>{this._extraKeyProviders.delete(e)}}async getKey(t){for(let e of[...this._extraKeyProviders].reverse()){let n=await e(t);if(n)return n}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 n=await this.getKey(t),i=await e.fetchModels(n),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(n){return console.warn(`[AparteConfig] Failed to refresh models for ${t}`,n),[]}}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],n=e.getModels();n.length===1&&(this._modelConfig={...this._modelConfig,defaultProvider:e.id,defaultModel:n[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,e){let n=this._tools.get(t.name)?.tool,i=this._approvalPolicy?.(t,n,e);return i||{verdict:n?.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}setQueueWhileStreaming(t){this._queueWhileStreaming!==t&&(this._queueWhileStreaming=t,this._notify())}getQueueWhileStreaming(){return this._queueWhileStreaming}getCurrentModel(){let{defaultProvider:t,defaultModel:e}=this._modelConfig;if(!t||!e)return;let n=this._aiProviders.get(t);if(!n)return;let r=this._fetchedModels.get(t)?.find(o=>o.id===e);if(r)return r;let a=n.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]||zt[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"),n=this._streamingMarkdownProvider(e);return n.write(t),n.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,n={}){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),n.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,n=Array.from(this._tools.values()).filter(i=>!e||e.has(i.tool.name)).map(i=>i.tool.systemPrompt?.trim()).filter(i=>!!i);return n.length?n.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),Dt(this))}overrideToolRenderer(t,e){let n=Nu(t),i=this._toolRenderers.get(t),r=this._toolRendererOverrides.get(n);r?r[r.length-1].renderer!==i&&r.splice(0,r.length,{renderer:i}):(r=[{renderer:i}],this._toolRendererOverrides.set(n,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(n)===r&&this._toolRendererOverrides.delete(n),!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),Dt(this))}registerActivityRenderer(t,e){return this._activityRenderers.get(t)!==e&&(this._activityRenderers.set(t,e),Dt(this)),()=>{this._activityRenderers.get(t)===e&&(this._activityRenderers.delete(t),Dt(this))}}getActivityRenderer(t){return this._activityRenderers.get(t)}getToolRenderer(t){return this._toolRenderers.resolve(t)?.value}registerToolDisplay(t,e){let n=this._toolDisplays.get(t),i={...n,...e};this._toolDisplays.set(t,i),(ls.some(a=>n?.[a]!==i[a])||n===void 0&&this._anotherShapes(i))&&it(this),this._notify()}unregisterToolDisplay(t){let e=this._toolDisplays.get(t);this._toolDisplays.delete(t),(ls.some(i=>e?.[i]!==void 0)||e!==void 0&&this._anotherShapes(e))&&it(this),this._notify()}_anotherShapes(t){return this._toolDisplays.values().some(e=>e!==t&&ls.some(n=>e[n]!==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 n=this._toolRenderers.resolve(t),i={exact:2,pattern:1,any:0};return!n||i[n.level]<=i[e.level]}setToolLineProvider(t){this._toolLineProvider!==t&&(this._toolLineProvider=t,it(this),this._notify())}registerToolLineProvider(t){let e=n=>t(n);return this._extraToolLineProviders.push(e),it(this),this._notify(),()=>{let n=this._extraToolLineProviders.indexOf(e);n!==-1&&(this._extraToolLineProviders.splice(n,1),it(this),this._notify())}}getToolLineProviders(){let t=[...this._toolLineProvider?[this._toolLineProvider]:[],...this._extraToolLineProviders];return t.length||this===Q?t:Q.getToolLineProviders()}getToolLineProvider(){return this._toolLineProvider||this===Q?this._toolLineProvider:Q._toolLineProvider}_dropToolDisplayField(t,e){let n=this._toolDisplays.get(t);if(!n||!(e in n))return;let{[e]:i,...r}=n;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 n={label:e};return this._stepLabels.set(t,n),this._notify(),()=>{this._stepLabels.get(t)===n&&(this._stepLabels.delete(t),this._notify())}}getStepLabel(t){let e=this._stepLabels.get(t);if(e)try{let n=typeof e.label=="function"?e.label({name:t,locale:this._locale}):e.label;return typeof n=="string"&&n.trim()?n.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(n=>n!==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(n=>n.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 n=bt(t);if(n)for(let i=e.length-1;i>=0;i-=1){let r=e[i];if(r.owner&&bt(r.owner)===n)return r.fn}}return e[e.length-1]?.fn}}requestUserInput(t){let e=this._elicitationQueueKey(t),n=this._elicitationQueue.get(e),i=n===void 0?this._present(t):n.then(()=>this._present(t),()=>this._present(t)),r=i.then(Br,Br).then(()=>{this._elicitationQueue.get(e)===r&&this._elicitationQueue.delete(e)});return this._elicitationQueue.set(e,r),i}_elicitationQueueKey(t){return bt(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 At("no-presenter"));if(t.signal?.aborted)return Promise.reject(new At("aborted"));if(this._elicitationObservers.size>0)return this._presentObserved(e,t);let n=e(t),i=t.signal;return i?new Promise((r,a)=>{let o=()=>a(new At("aborted"));i.addEventListener("abort",o,{once:!0}),n.then(r,a).finally(()=>i.removeEventListener("abort",o))}):n}observeElicitations(t){return this._elicitationObservers.add(t),()=>{this._elicitationObservers.delete(t)}}_presentObserved(t,e){let n=new AbortController,i,r=new Promise(a=>{i=a});return new Promise((a,o)=>{let l=!1,c=e.signal,d=p=>{l||(l=!0,c?.removeEventListener("abort",h),p(),n.signal.aborted||n.abort(),i())},h=()=>d(()=>o(new At("aborted")));c?.addEventListener("abort",h,{once:!0}),t({...e,signal:n.signal}).then(p=>d(()=>a(p)),p=>d(()=>o(p)));let u={request:e,respond:p=>d(()=>a(p)),settled:r};for(let p of[...this._elicitationObservers])try{p(u)}catch(f){console.error("[aparte] an observeElicitations listener threw; the question is still asked.",f)}})}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._elicitationObservers.clear(),this._locale=zt,this._actions=[],this._sanitizer=ms,this._imagePolicy=[],this._imageDecider=as([]),this._imagePolicyNamed=!1,cu(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++,Dt(this),this._toolDisplays.clear(),this._toolLineProvider=null,this._extraToolLineProviders=[],this._stepLabels.clear(),this._streamBlocks.clear(),this._runEventObservers=[],this._modelConfig={},this._requireModelSelection=!1,this._queueWhileStreaming=!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={...Mt},this._turnSummary=null,this._streamingCaret=!1,this._dateSeparators=!1,this._hostHandlers={...re},this._notify()}_defaultMarkdownRenderer(t){return P(t).replace(/\n/g,"<br>")}_defaultHighlightRenderer(t){return`<pre><code>${P(t)}</code></pre>`}},ds=Symbol.for("aparte.globalConfig.1");function Bu(){return typeof window<"u"?(window[ds]||(window[ds]=new he),window[ds]):new he}var Q=Bu(),Rs="aparte-config-change";function Lt(s,t){let e=n=>{let i=n.detail;i?.config&&i.config!==I(s)||t()};return window.addEventListener(Rs,e),()=>window.removeEventListener(Rs,e)}var uo="suggestions",$u=/[\p{Z}\s]+/gu,Hu=/[\p{Cc}\p{Co}\p{Cn}\p{Cs}\u2800]|(?!(?:\u200C|\u200D|\uFE0E|\uFE0F))\p{Default_Ignorable_Code_Point}/u,qu=/\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,Fu=/(?:^| )\p{M}|\p{Mn}{5,}/u,Wu=new Set(["\u200C","\u200D","\uFE0E","\uFE0F"]),Uu=/^[0-9#*]$/,ju=/^\p{Emoji}$/u,Hr=/^\p{Extended_Pictographic}$/u,zu=/^\p{Emoji_Modifier}$/u,qr=/^[\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,Gu=/^[\u094D\u09CD\u0A4D\u0ACD\u0B4D\u0BCD\u0C4D\u0CCD\u0D4D\u0DCA\u1039\u17D2]$/;function Ku(s){let t=Array.from(s);for(let e=0;e<t.length;e++){let n=t[e];if(!Wu.has(n))continue;let i=t[e-1]??"",r=t[e+1]??"";if(n==="\uFE0E"||n==="\uFE0F"){if(Uu.test(i)){if(n!=="\uFE0F"||r!=="\u20E3")return!1}else if(!ju.test(i))return!1;continue}if(n==="\u200D"){let a=i==="\uFE0F"?t[e-2]??"":i;if((Hr.test(a)||zu.test(a))&&Hr.test(r))continue}if(!(qr.test(i)&&(qr.test(r)||Gu.test(i)&&(r===""||r===" "))))return!1}return!0}var ho=100;function ai(s){let t=(typeof s=="string"?s:s.label).replace($u," ").trim();if(!t||t.length>ho)return null;let e=t.replace(qu,"\u{1F3F4}");return Hu.test(e)||Fu.test(e)||!Ku(e)?null:t}var Ne=new Set;function Vu(s,t){t.length===0||Ne.has(s)||(Ne.size>=50&&Ne.clear(),Ne.add(s),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 ${ho} characters and hold nothing invisible (zero-width, bidi or tag characters, stray joiners).`))}function Yu(s){let t;try{t=JSON.parse(s)}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"),n=[],i=[];for(let r of e){let a=ai(r);a!==null?n.push(a):(typeof r=="string"?r:r.label).trim()&&i.push(typeof r=="string"?r:r.label)}return Vu(s,i),n.length?n:null}function Qu(s=Q){return s.registerCodeLanguageRenderer({languages:[uo],bare:!0,render:({source:t,open:e})=>{if(e)return"";let n=Yu(t);return n?`<span class="aparte-suggestions-mark" hidden data-aparte-suggestions="${L(JSON.stringify(n))}"></span>`:`<code class="aparte-code-error">${P(t)}</code>`}})}var Xu=new WeakSet;function oi(s){return!!s&&Xu.has(s)}function Ju(s){let t=s.segments,e=t[t.length-1];return s.status!=="streaming"||!e||e.isStreaming!==void 0||e.type!=="text"&&e.type!=="thinking"?t:[...t.slice(0,-1),{...e,isStreaming:!0}]}function li(s,t,e){if(s.setTokens?.(t.tokens),t.segments&&t.segments.length>0){let n=s.getSegments?.()??[];if(n.length===t.segments.length){let i=Fs(t.status);for(let r of t.segments)if("content"in r){let a={content:r.content};i&&(a.isStreaming=!1);let o=n.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}),s.updateSegment?.(r.id,a)}}else s.setSegments?.(Ju(t))}else t.content!==void 0&&s.setContent?.(t.content);t.attachments&&t.attachments.length>0&&s.setAttachments?.(t.attachments),e&&e.count>1&&s.setSiblings?.(e.count,e.index),t.usage!==void 0&&s.setUsage?.(t.usage),s.setFinishReason?.(t.finishReason),s.setContextSummary?.(t.contextSummary,{legacy:t.compaction===!0})}var ci=Symbol.for("aparte.derivedSegments");function po(s){return s.map(t=>({id:J(),name:t.name,type:t.type||"application/octet-stream",url:URL.createObjectURL(t),size:t.size,blob:t}))}function fo(s){if(s?.length&&!(typeof URL>"u"||typeof URL.revokeObjectURL!="function"))for(let t of s)t.url?.startsWith("blob:")&&URL.revokeObjectURL(t.url)}var Os=new Map;function di(s,t){t?Os.set(s,t):Os.delete(s)}function go(s,t){di(s,t);try{window.dispatchEvent(new CustomEvent("aparte-conversation-status",{detail:{id:s,status:t}}))}catch{}}function un(s){return Os.get(s)??null}var Zu=Symbol.for("aparte.openConversation");function De(s){for(let t=s;t;t=t.parentElement){let e=t[Zu];if(e)return e()}return null}function _o(s){if(s.hasAttribute("data-glide"))return()=>{};let t=s.ownerDocument,e=()=>{t.removeEventListener("pointerdown",n,!0),t.removeEventListener("keydown",n,!0),s.removeEventListener("aparte-send",n)},n=()=>{s.setAttribute("data-glide",""),e()};return t.addEventListener("pointerdown",n,!0),t.addEventListener("keydown",n,!0),s.addEventListener("aparte-send",n),e}var Ze=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),n=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",n),window.addEventListener("aparte-compact-done",i),window.addEventListener("aparte-compact-error",r),()=>{window.removeEventListener("aparte-compact-start",n),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,n){this._messageId=t,this._state=e,this._reason=n,this._write(t,e,n)}_write(t,e,n){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,n?i.setAttribute("data-checkpoint-reason",n):i.removeAttribute("data-checkpoint-reason"),i.getAttribute("data-checkpoint")!==e&&i.setAttribute("data-checkpoint",e))}};function tn(s){for(let t=s.length-1;t>=0;t--){let e=s[t].contextSummary;if(e?.summary===void 0)continue;let n=t===s.length-1&&s[t].role==="user",i=e.includesSelf===!0&&!n?t+1:t;return{summary:e.summary,messages:s.slice(i)}}return{messages:s}}var th="The earlier part of this conversation was compacted. This is a summary of what came before; continue from it.",ui=s=>`${th}
68
+
69
+ ${s}`,en=new WeakMap;function eh(s){let t={role:"user",content:ui(s)};return en.set(t,t.content),t}function nh(s){for(let t of s){let e=en.get(t);if(e!==void 0)return e}}function jt(s){let t=n=>typeof n=="string"?[{type:"text",text:n}]:n,e=[];for(let n of s){let i=e[e.length-1];if(n.role!=="user"||i?.role!=="user")e.push(n);else{let r=typeof i.content=="string"&&typeof n.content=="string"?{...i,content:`${i.content}
70
+
71
+ ${n.content}`}:{...i,content:[...t(i.content),{type:"text",text:`
72
+
73
+ `},...t(n.content)]},a=en.get(i);a!==void 0&&en.set(r,a),e[e.length-1]=r}}return e}var Fr="The tool call was stopped before it ran.",sh="The tool returned no output.";function ih(s){let t=s.result?.trim();return s.status==="resolved"?t||sh:s.status==="failed"?t||"The tool failed.":s.status==="rejected"&&t||Fr}var us=s=>s.type==="tool_call"&&!!s.deferred&&(s.status==="awaiting-approval"||s.status==="pending"),Wr=s=>s.type==="tool_call"&&(s.status==="pending"||s.status==="awaiting-approval");function mo(s,t,e={}){let n=s.segments??[];if(s.role!=="assistant"||!n.some(c=>c.type==="tool_call")){let c=t(n)||(typeof s.content=="string"?s.content:"");return c?[{role:s.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&&Wr(d)||i.push({role:"tool",content:ih(d),toolCallId:d.toolCall.id,toolName:d.toolCall.name})}r=[],a=[]},l=!1;for(let c of n)c.type==="tool_call"?(a.push(c),e.openDeferred&&Wr(c)&&(l=!0)):(a.length>0&&!l&&o(),r.push(c));return o(),i}var bo=s=>s.status==="streaming"||s.status==="pending";function hn(s){if(!s?.length)return"";let t="```",e=[];for(let n of s){let i=n.content;if(n.type==="text")i&&e.push(i);else if(n.type==="code"){let r=n.language??"";e.push(`${t}${r}
74
+ ${i??""}
75
+ ${t}`)}else{if(n.type==="thinking"||n.type==="tool_call"||n.type==="error"||n.type==="activity")continue;if(typeof i=="string"&&i){let r=n.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=n.fallback;r&&e.push(r)}}}return e.join(`
76
+ `).trim()}function rh(s){let t=hn(s.segments);return t||(typeof s.content=="string"&&s.content?s.content:"")}function Ps(s){let t=rh(s);return s.compaction?ui(t):t}var ah=new Set([z.USAGE_CONTEXT_EXCEEDED,z.PROVIDER_POLICY,z.USAGE_BAD_REQUEST]);function oh(s,t){let e=s.segments??[],n;for(let i=e.length-1;i>=0;i--){let r=e[i];if(r.type==="error"){n=r.code;break}}return n!==void 0&&ah.has(n)?!0:t.some(i=>(i.attachments?.length??0)>0)}function vo(s){let t=new Set,e=[];for(let n of s)if(n.role==="user")n.compaction||e.push(n);else if(n.role==="assistant"){if(n.status!=="error")e=[];else if(oh(n,e)){for(let i of e)t.add(i);t.add(n),e=[]}}return t.size===0?[...s]:s.filter(n=>!t.has(n))}function Ue(s){return vo(s).filter(t=>t.role!=="user"&&t.role!=="assistant"?!1:t.status!=="error"&&!bo(t)).flatMap(t=>{if(t.role==="assistant"&&t.segments?.some(n=>n.type==="tool_call"))return mo(t,hn);let e=Ps(t);return e?[{role:t.role,content:e}]:[]})}function Ht(s){return s?Math.ceil(s.length/3.8):0}var hi=s=>{if(!s)return 0;try{return Ht(JSON.stringify(s))}catch{return 0}};function yo(s){let t=0;for(let e of s)t+=Ht(Qr(e.content)),e.toolCalls?.length&&(t+=hi(e.toolCalls));return t}function lh(s){return s.some(t=>typeof t.content!="string"&&t.content.some(e=>e.type!=="text"))}function ch(s){let t=(s.tools??[]).map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema}));return yo(s.messages)+(t.length?hi(t):0)}function wo(s){return yo(Ue(s))}var pn=s=>s.totalTokens??s.inputTokens+s.outputTokens;function Ao(s){let t=s.getCurrentModel()?.capabilities;return(t?!t.includes("function_calling"):!1)?[]:s.getTools()}function dh(s,t){if(typeof t=="number"&&Number.isFinite(t)&&t>0)return t;let e=s.getCurrentModel()?.contextWindow;return e&&e>0?e:void 0}var So=(s,t)=>s.segments?.some(e=>e.type===t)===!0;function uh(s){let t=s.usage?.inputTokens,e=s.contextEstimate;return So(s,"tool_call")?1:t&&e&&t>0&&e>0?Math.min(3,Math.max(.5,t/e)):1}function hh(s,t){let e=s.usage;if(!So(s,"thinking")||!(e.inputTokens>0))return pn(e);let n=s.segments??[],i=n.map(a=>a.type).lastIndexOf("tool_call"),r=Math.round(t*Ht(hn(n.slice(i+1))));return e.inputTokens+(e.outputTokens>0?Math.min(r,e.outputTokens):r)}function Co(s){let{messages:t,config:e}=s,n=tn(t),i=Ao(e),r=Ht(e.resolveSystemPrompt())+Ht(e.resolveToolSystemPrompts(i)),a=i.map(y=>({name:y.name,description:y.description,inputSchema:y.inputSchema})),o=a.length?hi(a):0,l=n.summary===void 0?0:Ht(ui(n.summary)),c={system:r,tools:o,summary:l,messages:wo(n.messages)},d=r+o+l+c.messages,h=-1;for(let y=t.length-1;y>=0;y--)if(t[y].role==="assistant"&&t[y].usage){h=y;break}let u=h>=0?t[h]:void 0,p=dh(e,s.windowOverride),f=(y,b)=>({...p!==void 0?{window:p}:{},used:y,estimated:b,parts:c,other:Math.max(0,y-d)}),g=u!==void 0&&!s.viewChanged&&h===t.length-1&&!t.some(y=>y.contextSummary!==void 0&&y.contextSummary.createdAt>u.timestamp),_=u?uh(u):1;return u&&g?f(hh(u,_),!1):f(Math.round(_*d),!0)}var ph=0,je=null;function pe(s){je?.push(s)}function j(s,t,e){let n=document.createElement(s);return t&&(n.className=t),e!=null&&(n.textContent=e),n}function pi(s,t,e){let n=j("span","aparte-elic-option-body"),i=j("span","aparte-elic-option-title",s);if(i.dir="auto",e){let r=j("span","aparte-tag aparte-tag--sm aparte-elic-option-badge",M().t("elicitationRecommended")||"Recommended");i.append(" ",r)}return n.appendChild(i),t&&n.appendChild(Object.assign(j("span","aparte-elic-option-desc",t),{dir:"auto"})),n}function Ns(s,t,e){let n=j("button","aparte-btn aparte-btn--block aparte-btn--surface aparte-elic-option aparte-elic-option--command"+(e?" aparte-elic-option--recommended":""));return n.type="button",n.appendChild(pi(s,t,e)),n}function fi(s,t,e){let n;if(t.title&&t.title.trim()!==e?.trim()){let i=j("p","aparte-elic-title",t.title);i.dir="auto",n=`elic-title-${J()}`,i.id=n,s.appendChild(i)}return t.description&&s.appendChild(Object.assign(j("p","aparte-elic-desc",t.description),{dir:"auto"})),n}function ko(s,t){s.setAttribute("role",t.multiple||t.commands?"group":"radiogroup"),t.titleId?s.setAttribute("aria-labelledby",t.titleId):t.fallbackLabel&&s.setAttribute("aria-label",t.fallbackLabel)}function fh(s,t,e,n){let i=j("div","aparte-elic-field aparte-elic-enum"),r=fi(i,s,e),a=j("div","aparte-elic-options"),o=`elic-${J()}`,l=s.multiple?"checkbox":"radio",c=l==="checkbox"?"aparte-checkbox":"aparte-radio",d=s.allowOther??M().getElicitationOptions().allowOther,h=new Set(Array.isArray(s.default)?s.default:s.default!=null?[s.default]:[]),u=n!=null&&!s.multiple&&h.size===0;ko(a,{multiple:s.multiple,commands:u,titleId:r,fallbackLabel:e});let p=(v,E,A,w)=>{if(u){let O=Ns(E,A,w);return O.addEventListener("click",()=>n?.(v)),O}let m=j("label","aparte-field-choice aparte-elic-option"+(w?" aparte-elic-option--recommended":"")),S=j("input",c+" aparte-elic-control");return S.type=l,S.name=o,S.value=v,h.has(v)&&(S.checked=!0),m.append(S,pi(E,A,w)),m};for(let v of s.options)a.appendChild(p(v.value,v.label??v.value,v.description,v.recommended));let f=null,g=!1;if(d){let v=M();f=j("input","aparte-field aparte-elic-other-input"),f.type="text",f.placeholder=v.t("elicitationOtherPlaceholder"),f.style.display="none",f.setAttribute("aria-label",v.t("elicitationOtherLabel"));let E=f;if(u){let A=Ns(v.t("elicitationOther"));A.classList.add("aparte-elic-option--other"),A.setAttribute("aria-expanded","false"),A.addEventListener("click",()=>{g=!0,A.setAttribute("aria-expanded","true"),E.style.display="",E.focus(),t()});let w=A.querySelector(".aparte-elic-option-title");pe(()=>{let m=M();w.textContent=m.t("elicitationOther"),E.placeholder=m.t("elicitationOtherPlaceholder"),E.setAttribute("aria-label",m.t("elicitationOtherLabel"))}),a.append(A,E)}else{let A=j("label","aparte-field-choice aparte-elic-option aparte-elic-option--other"),w=j("input",c+" aparte-elic-control");w.type=l,w.name=o,w.value="__other__";let m=j("span","aparte-elic-option-body"),S=j("span","aparte-elic-option-title",v.t("elicitationOther"));m.appendChild(S),pe(()=>{let O=M();S.textContent=O.t("elicitationOther"),E.placeholder=O.t("elicitationOtherPlaceholder"),E.setAttribute("aria-label",O.t("elicitationOtherLabel"))}),m.appendChild(f),A.append(w,m),a.appendChild(A)}}i.appendChild(a);let _=()=>Array.from(a.querySelectorAll(".aparte-elic-control")),y=()=>a.querySelector('input[value="__other__"]'),b=!1;a.addEventListener("keydown",v=>{b=v.key.startsWith("Arrow")}),a.addEventListener("click",()=>{b=!1}),a.addEventListener("change",()=>{let v=y();v&&f&&(f.style.display=v.checked?"":"none",v.checked&&!b&&f.focus()),b=!1,t()}),f?.addEventListener("input",t);let k=()=>f?.value.trim()??"";if(u)return{el:i,getValue:()=>k(),isComplete:()=>g&&k()!=="",focus:()=>a.querySelector(".aparte-elic-option--command")?.focus(),offersSubmit:()=>g};let x=()=>{let v=y()?.checked&&k()?k():"";if(s.multiple){let A=_().filter(w=>w.checked&&w.value!=="__other__").map(w=>w.value);return v&&A.push(v),A}let E=_().find(A=>A.checked);return E?E.value==="__other__"?v:E.value:""};return{el:i,getValue:x,isComplete:()=>{let v=x();return s.multiple?v.length>0:v!==""},focus:()=>_()[0]?.focus()}}function gh(s,t,e,n){let i=j("div","aparte-elic-field aparte-elic-boolean"),r=fi(i,s,e),a=j("div","aparte-elic-options"),o=`elic-${J()}`,l=n!=null&&s.default==null;if(ko(a,{commands:l,titleId:r,fallbackLabel:e}),l){let u=M(),p=(f,g,_)=>{let y=Ns(g);if(y.addEventListener("click",()=>n?.(f)),_){let b=y.querySelector(".aparte-elic-option-title");pe(()=>{b.textContent=M().t(_)})}a.appendChild(y)};return p(!0,s.trueLabel??u.t("elicitationYes"),s.trueLabel?void 0:"elicitationYes"),p(!1,s.falseLabel??u.t("elicitationNo"),s.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=j("label","aparte-field-choice aparte-elic-option"),_=j("input","aparte-radio aparte-elic-control");_.type="radio",_.name=o,_.value=u,s.default!=null&&String(s.default)===u&&(_.checked=!0);let y=j("span","aparte-elic-option-body"),b=j("span","aparte-elic-option-title",p);b.dir="auto",f&&pe(()=>{b.textContent=M().t(f)}),y.appendChild(b),g.append(_,y),a.appendChild(g)},d=M();c("true",s.trueLabel??d.t("elicitationYes"),s.trueLabel?void 0:"elicitationYes"),c("false",s.falseLabel??d.t("elicitationNo"),s.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 _h(s,t,e){let n=j("div","aparte-elic-field aparte-elic-string");fi(n,s,e);let i=s.multiline?j("textarea","aparte-field aparte-field--textarea aparte-elic-text"):j("input","aparte-field aparte-elic-text");s.multiline||(i.type="text"),s.placeholder&&i.setAttribute("placeholder",s.placeholder),s.default&&(i.value=s.default),s.maxLength!=null&&i.setAttribute("maxlength",String(s.maxLength));let r=s.title||s.description||e||void 0;if(i.setAttribute("aria-label",r??M().t("elicitationAnswerLabel")),r==null){let l=i;pe(()=>{l.setAttribute("aria-label",M().t("elicitationAnswerLabel"))})}n.appendChild(i),i.addEventListener("input",t);let a=s.required??!0,o=()=>i.value;return{el:n,getValue:()=>o(),isComplete:()=>{let l=o().trim();return!a&&l===""?!0:l.length>=(s.minLength??1)},focus:()=>i.focus()}}function Ur(s,t,e,n,i){let r=M().getElicitationFieldRenderer()?.(s,{key:n,notifyChange:t});if(r)return{el:r.el,getValue:()=>r.getValue(),isComplete:()=>r.isComplete(),focus:()=>r.focus?.()};switch(s.type){case"enum":return fh(s,t,e,i);case"boolean":return gh(s,t,e,i);case"string":return _h(s,t,e)}}function Eo(s,t,e){let n=[],i=je;je=n;try{return{...mh(s,t,e),relabel:()=>{for(let a of n)a()}}}finally{je=i}}function mh(s,t,e){let n=j("div","aparte-elic-panel"),i=typeof s=="function"?s():s;i&&n.appendChild(Object.assign(j("p","aparte-elic-message",i),{dir:"auto"}));let r=null,a=!1,o=p=>{a||(a=!0,r?.(p))},l=p=>{r=p},c=j("div","aparte-elic-body");n.appendChild(c);let d=j("div","aparte-elic-dismiss");if(n.appendChild(d),t.type==="object"){let p=Object.entries(t.properties),f=new Set(t.required??p.map(([m])=>m)),g=M(),_=()=>{},y=()=>{_(),e()},b=p.map(([m,S])=>{let O=Ur(S,y,void 0,m);return!S.title&&!O.el.querySelector(".aparte-elic-title")&&O.el.insertBefore(Object.assign(j("p","aparte-elic-title",m),{dir:"auto"}),O.el.firstChild),c.appendChild(O.el),{key:m,field:O,required:f.has(m),header:S.header}}),k=()=>b.every(m=>!m.required||m.field.isComplete()),x={el:n,dismiss:d,getContent:()=>Object.fromEntries(b.map(m=>[m.key,m.field.getValue()])),isComplete:k,focus:()=>b[0]?.field.focus(),mode:()=>"submit",canProceed:k,proceed:()=>{},onSettle:l};if(b.length<2||g.getElicitationOptions().layout!=="stepped")return x;n.classList.add("aparte-elic-panel--stepped");let v=0,E=`aparte-elic-${++ph}`,A=j("div","aparte-tabs aparte-tabs--underline aparte-elic-steps");A.setAttribute("role","tablist");let w=b.map((m,S)=>{let O=j("button","aparte-tabs__tab aparte-elic-step");return O.type="button",O.setAttribute("role","tab"),O.textContent=m.header?.trim()||String(S+1),O.dir="auto",O.id=`${E}-tab-${S}`,m.field.el.id=`${E}-panel-${S}`,m.field.el.setAttribute("role","tabpanel"),m.field.el.setAttribute("aria-labelledby",O.id),O.setAttribute("aria-controls",m.field.el.id),A.appendChild(O),O});return n.insertBefore(A,c),A.addEventListener("aparte-tab-change",m=>{v=w.indexOf(m.detail.tab)}),qi(A),A.addEventListener("click",m=>{let S=w.indexOf(m.target.closest(".aparte-elic-step"));S>=0&&S===v&&b[S].field.focus()}),_=()=>{w.forEach((m,S)=>{let O=b[S].field.isComplete();m.toggleAttribute("data-answered",O);let C=m.querySelector(".aparte-elic-step__mark");if(O&&!C){let N=j("span","aparte-elic-step__mark");N.setAttribute("aria-hidden","true"),N.innerHTML=g.getIcon("check"),m.prepend(N)}else!O&&C&&C.remove()})},_(),{...x,focus:()=>b[v]?.field.focus()}}let h=M().getElicitationOptions().answerOnClick,u=Ur(t,e,i,void 0,h?o:void 0);return c.appendChild(u.el),{el:n,dismiss:d,getContent:()=>u.getValue(),isComplete:()=>u.isComplete(),focus:()=>u.focus(),mode:()=>u.offersSubmit?.()??!0?"submit":"none",canProceed:()=>u.isComplete(),proceed:()=>{},onSettle:l}}var bh=0;function mt(s,t,e){let n=document.createElement(s);return t&&(n.className=t),e!=null&&(n.textContent=e),n}var vh=0;function To(s,t,e,n,i=!0,r){let a=M(),o=mt("div","aparte-elic-panel aparte-approval-panel"),l=mt("div","aparte-elic-body");o.appendChild(l);let c=()=>typeof s=="function"?s():s,d=c()?Object.assign(mt("p","aparte-elic-message",c()),{dir:"auto"}):null;d&&l.appendChild(d);let h=null;if(n){h=mt("div","aparte-approval-args-label",a.t("approvalArgsLabel")),h.id="aparte-approval-args-"+ ++bh;let A=mt("pre","aparte-approval-args");A.textContent=n,A.setAttribute("role","group"),A.setAttribute("aria-labelledby",h.id),A.tabIndex=0,l.append(h,A)}if(r!==void 0&&r!==""){let A=mt("div","aparte-approval-preview");typeof r=="string"?A.innerHTML=a.sanitizeHtml(r):A.appendChild(r),l.appendChild(A)}let u=mt("div","aparte-elic-dismiss");o.appendChild(u);let p=null,f=!1,g=A=>{f||(f=!0,p?.(A))},_=mt("div","aparte-approval-options");_.setAttribute("role","group"),_.setAttribute("aria-label",a.t("approvalOptionsLabel")),d&&(d.id||=`aparte-approval-ask-${++vh}`,_.setAttribute("aria-describedby",d.id));let y=[],b=A=>typeof A.label=="function"?A.label():A.label,k=A=>typeof A.description=="function"?A.description():A.description,x=A=>pi(b(A),k(A));for(let A of t){let w=A.tone??"affirm",m=mt("button",`aparte-btn aparte-btn--block aparte-btn--surface aparte-approval-option aparte-approval-option--${w}`);m.type="button",m.appendChild(x(A)),m.addEventListener("click",()=>g({option:A.value})),_.appendChild(m),y.push({button:m,option:A})}l.appendChild(_);let v=i?mt("textarea","aparte-approval-instruction"):null;v&&(v.rows=1,v.placeholder=a.t("approvalInstructionPlaceholder"),v.setAttribute("aria-label",a.t("approvalInstructionPlaceholder")),v.addEventListener("input",e),l.appendChild(v));let E=()=>v?.value.trim()??"";return{el:o,dismiss:u,onSettle:A=>{p=A},getContent:()=>({instruction:E()}),isComplete:()=>E().length>0,focus:()=>{o.querySelector(".aparte-approval-option")?.focus()},relabel:()=>{let A=M(),w=A.t("approvalInstructionPlaceholder");v&&(v.placeholder=w,v.setAttribute("aria-label",w)),_.setAttribute("aria-label",A.t("approvalOptionsLabel")),d&&(d.textContent=c()),h&&(h.textContent=A.t("approvalArgsLabel"));for(let{button:m,option:S}of y)m.replaceChildren(x(S))}}}function xo(s){return I(s.target??null).requestUserInput(s)}var yh="Not run: an earlier call of the same step was refused.",jr=s=>JSON.stringify([s.id,s.name,s.input]),zr=new Set,Pt=new Map,Gr="aparte-chat, aparte-chat-viewport, [data-aparte-chat]";function wh(s){return{id:s,getMetadata:()=>({id:s,name:s}),getModels:()=>[],chat:async()=>{throw new dt("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 Ah(s,t){let e=[],n=0;for(let i of[...t].sort((r,a)=>r.start-a.start)){let r=s.indexOf(i.text,n);r<0||(n=r+i.text.length,e.push({...i,start:r,end:n}))}return e}var Ds=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(),n=t.getModelConfig().defaultProvider;if(!e||e.contextWindow||!n)return;let i=`${n}\0${e.id}`;this._windowReadFor.has(i)||(this._windowReadFor.add(i),await t.refreshProviderModels(n))}_isForThisInstance(t){if(!t)return!0;let e=t.detail,n=this.options.scopeToTargetId;if(n)return e?.targetId===n;if(this._config===Q){if(Pt.size===0)return!0;let a=this._resolveTarget(e?.targetId,t),o=a?I(a):Q;return o===Q||!Pt.has(o)}let i=this._resolveTarget(e?.targetId,t);if(!i)return!0;let r=I(i);return r===this._config||r===Q}_streamController=null;options;_config;_claims=!1;constructor(t={}){this.options={autoRegister:!0,...t},this._config=t.config??Q,this._registerKeyResolver(),this.options.autoRegister?Xa(this._config):Ka(this._config),this._setupListeners()}_beginUserTurn(){this._isAborted=!1}_registerKeyResolver(){this._releaseKeyResolver||!this.options.keyResolver||(this._releaseKeyResolver=this._config.registerKeyProvider(this.options.keyResolver))}_setupListeners(){this._boundHandler||(this._boundHandler=t=>{let e=t;e.type==="aparte-send"&&this._isForThisInstance(e)&&(this._beginUserTurn(),this._handleSend(e))})}start(){this._registerKeyResolver(),this._config!==Q&&!this._claims&&(this._claims=!0,Pt.set(this._config,(Pt.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=(Pt.get(this._config)??1)-1;t>0?Pt.set(this._config,t):Pt.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()}_approvalPreviewOf(t,e){let n=I(e).getToolDisplay(t.name);try{return n?.approvalPreview?.({id:t.id,name:t.name,input:t.input})??void 0}catch(i){console.warn(`[aparte] The approval preview of "${t.name}" threw; the question shows the arguments alone.`,i);return}}async _askForApproval(t,e,n,i){let r=t.agent?.name?.trim(),a=this._approvalPreviewOf(t,n),o=await xo({kind:"approval",message:()=>{let d=this._config.getLocale(),h=I(n),u={id:`tool-${t.id}`,type:"tool_call",status:"awaiting-approval",toolCall:{id:t.id,name:t.name,input:t.input}},p=ln(u,h).text,f=Kd(u,h),g=f?`${p} ${f}`:p;return r?(d.approvalAskBy??"Allow {tool} for {agent}?").replace(/\{(agent|tool)\}/g,(_,y)=>y==="agent"?r:g):(d.approvalAsk??"Allow {tool}?").replace("{tool}",()=>g)},details:Ma(t.input,I(n).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:n,...a!==void 0?{preview:a}:{},messageId:i.messageId,...i.conversationId?{conversationId:i.conversationId}:{}});if(o.action!=="accept")return{approved:!1,by:"person"};let l=o.content,c=l?.instruction?.trim();return c?{approved:!1,instruction:c,by:"person"}:l?.option==="allow"?{approved:!0}:{approved:!1,by:"person"}}get _modelRunsElsewhere(){let t=this.options.streamRunner;return!!t&&t!==Gn}_providerFor(t){let e=t?this._config.getAIProvider(t):void 0;return e||(this._modelRunsElsewhere?wh(t??""):void 0)}async _resolveAuth(t){if(this.options.keyResolver){let n=await this.options.keyResolver(t);if(n)return n}return await this._config.getKey(t)||void 0}async _streamTurn(t,e,n,i,r,a,o){let l=this._targetIdOf(t),c={...o?.conversationId?{conversationId:o.conversationId}:{},messageId:e,...l?{targetId:l}:{}},d=this._toolsForCurrentModel(),h=async A=>{let w=nh(A),m=w===void 0?o?.meta:{...o?.meta,historySummary:w},S={messages:A,modelId:r,stream:!0,tools:d.length?d:void 0,...o?.temperature!==void 0?{temperature:o.temperature}:{},...m?{_meta:m}:{}};if(this.options.requestInterceptor&&(S=await this.options.requestInterceptor(S,c)),S.toolChoice==="none"){let O=this._config.resolveToolSystemPrompts(d);S={...S,tools:void 0,messages:O?S.messages.filter(C=>!(C.role==="system"&&C.content===O)):S.messages}}return S},u=await h(i);if(this._isAborted){lt(t,"aparte-message-aborted",{messageId:e},l),this._updateMessage(t,e,{status:"completed"});return}lt(t,"aparte-message-start",{messageId:e,role:"assistant"},l),o?.resume&&lt(t,"aparte-message-paused",{messageId:e},l),!o?.resume&&n.id&&this._updateMessage(t,e,{model:{providerId:n.id,modelId:u.modelId,...u.temperature!==void 0?{temperature:u.temperature}:{}}});let p=new AbortController;this._streamController!==p&&this._streamController?.abort(),this._streamController=p,this._turnsInFlight.add(e),this._agentNames.set(e,new Map(o?.agentNames??[]));let f=o?.rebuild?I(t).getCompactor()??this._config.getCompactor():null,g=()=>{let A=t.getMessages?.()??[],w=A.findIndex(S=>S.id===e),m=w>0?A[w-1]:void 0;return m?.role==="user"?[m.id,e]:[e]},_=()=>o?.resume?this._resumeMessages(t,e,u.messages):u.messages,y=()=>ch({messages:_(),tools:u.tools}),b=()=>lh(_())?void 0:y(),k=()=>{this._closeOpenCalls(t,e),lt(t,"aparte-message-aborted",{messageId:e},l),this._updateMessage(t,e,{status:"completed"})},x=()=>this._isAborted||p.signal.aborted,v=async()=>{let A=o?.resume?{usage:void 0,suspended:o.resume}:await this._streamLoop(t,e,n,u,a,p,void 0,o?.files,o?.conversationId,o?.userMessage),w=this.options.maxTurns??10,m=0,S=new Set,O=We({target:t,config:this._config,messageId:e,...l?{targetId:l}:{},...o?.conversationId?{conversationId:o.conversationId}:{}});for(;A.suspended;){let D=this._isAborted||p.signal.aborted;if(!D&&++m>w){this._closeOpenCalls(t,e),We({target:t,config:this._config,messageId:e,...l?{targetId:l}:{}})({type:"turn-limit-exceeded",scope:"global",limit:w});break}let H=new Set,tt=D?void 0:await this._answerDeferred(t,c,A.suspended.pending,p.signal,O,S,H);if(S=H,!tt){this._closeOpenCalls(t,e),(this._isAborted||p.signal.aborted)&&lt(t,"aparte-message-aborted",{messageId:e},l);break}let rt={outcomes:tt,...A.suspended.ticket?{token:A.suspended.ticket}:{}},gt=this._resumeMessages(t,e,u.messages);this._spendPause(t,e),lt(t,"aparte-message-resumed",{messageId:e},l),A=await this._streamLoop(t,e,n,{...u,messages:gt},a,p,rt,void 0,o?.conversationId,o?.userMessage)}let C=A.usage,N=A.finishReason;this._isAborted||p.signal.aborted?(this._closeOpenCalls(t,e),this._updateMessage(t,e,{status:"completed"})):(lt(t,"aparte-message-done",{messageId:e,role:"assistant",usage:C,...N?{finishReason:N}:{}},l),this._readWindowAfterTurn())},E=async A=>{if(A.code!==z.USAGE_CONTEXT_EXCEEDED||!f||!o?.rebuild||(t.getMessage?.(e)?.segments??t.getMessages?.()?.find(m=>m.id===e)?.segments??[]).some(m=>m.type==="text"||m.type==="tool_call"))return"stands";try{let m=await f.compact({target:t,...l?{targetId:l}:{},force:!0,reason:"overflow",exclude:g(),signal:p.signal});if(x())return"stopped";if(!m.ok||m.skipped)return"stands";u=await h(await o.rebuild())}catch{return"stands"}return this._updateMessage(t,e,{status:"pending"}),"resend"};try{for(let A=0;;A++)try{if(A===0&&f?.beforeSend&&o?.rebuild){let w=!1;try{w=await f.beforeSend({target:t,...l?{targetId:l}:{},exclude:g(),requestTokens:y(),signal:p.signal})}catch(m){console.warn("[AparteClient] The compactor threw before a send; sending the request as built.",m)}if(x()){k();return}w&&(u=await h(await o.rebuild()))}this._updateMessage(t,e,{contextEstimate:b()}),await v();return}catch(w){if(this._closeOpenCalls(t,e),x()){lt(t,"aparte-message-aborted",{messageId:e},l),this._updateMessage(t,e,{status:"completed"});return}let m=dt.from(w,z.UNKNOWN_ERROR),S=A===0?await E(m):"stands";if(S==="resend")continue;if(S==="stopped"){k();return}this._handleLifecycleError(t,e,m);return}}finally{this._turnsInFlight.delete(e),this._agentNames.delete(e)}}_turnsInFlight=new Set;_agentNames=new Map;_toolsForCurrentModel(){return Ao(this._config)}async _handleRetry(t){let{messageId:e,targetId:n}=t.detail??{};if(this._beginUserTurn(),!e)return;let i=this._resolveTarget(n,t);if(!i){console.warn("[AparteClient] aparte-retry \u2014 no target found");return}let r=De(i)??void 0,a=i.getMessages?.()??[],o=a.findIndex(x=>x.id===e),c=(o>=0?a[o]:void 0)?.role==="user"?o+1:o,d=o>=0?a.slice(0,c):a,h={id:J(),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,y=this._messagesToChatMessages(d),b=this._systemMessages(),k=[...d].reverse().find(x=>x.role==="user");await this._streamTurn(i,u,g,[...b,...jt(y)],p.defaultModel||"",_,{...g.retryTemperature!==void 0?{temperature:g.retryTemperature}:{},...this._turnMeta(k),...r?{conversationId:r}:{},...k?{userMessage:{content:Ps(k),messageId:k.id}}:{},rebuild:async()=>[...this._systemMessages(),...jt(this._messagesToChatMessages(this._current(i,d)))]})}_systemMessages(){let t=[],e=this._config.resolveSystemPrompt();e&&t.push({role:"system",content:e});let n=this._config.resolveToolSystemPrompts(this._toolsForCurrentModel());return n&&t.push({role:"system",content:n}),t}async _handleEdit(t){let{messageId:e,content:n,targetId:i}=t.detail??{};if(this._beginUserTurn(),!e||n===void 0)return;let r=this._resolveTarget(i,t);if(!r){console.warn("[AparteClient] aparte-edit \u2014 no target found");return}let a=De(r)??void 0,o=r.getMessages?.().find(b=>b.id===e);r.updateMessage?.(e,{content:n,...o?.tokens?{tokens:Ah(n,o.tokens)}:{}});let l=r.getMessages?.()??[],c=l.findIndex(b=>b.id===e);if(r.truncateResponsesAfter)r.truncateResponsesAfter(e);else{let b=c>=0&&c+1<l.length?l[c+1]?.id:void 0;b&&r.truncateFrom?.(b)}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,y=J();r.appendMessage?.({id:y,role:"assistant",content:"",status:"pending",timestamp:Date.now()}),await this._streamTurn(r,y,g,[...u,...jt(h)],p.defaultModel||"",_,{...this._turnMeta(c>=0?l[c]:void 0),...a?{conversationId:a}:{},userMessage:{content:c>=0?Ps(l[c]):String(n),messageId:e},rebuild:async()=>[...this._systemMessages(),...jt(this._messagesToChatMessages(this._current(r,d)))]})}_current(t,e){let n=new Map((t.getMessages?.()??[]).map(i=>[i.id,i]));return e.map(i=>t.getMessage?.(i.id)??n.get(i.id)??i)}_originChain(t){let e=t?.composedPath?.()??[];if(e.length>0)return e;let n=[],i=t?ct(t):null;for(;i;)n.push(i),i=i.parentElement;return n}_rootsFor(t){let e=[];for(let n of this._originChain(t)){if(typeof n.getRootNode!="function")continue;let i=Tt(n);e.includes(i)||e.push(i)}return e.includes(document)||e.push(document),e}_byId(t,e){for(let n of this._rootsFor(e)){let i=n.getElementById?.(t);if(i)return i}return null}_scanForTarget(t){for(let e of this._rootsFor(t))for(let n of e.querySelectorAll(Gr)){let i=this._asRenderTarget(n);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 n=this._scanForTarget(e);if(n)return n;for(let i of this._rootsFor(e)){let r=i.querySelector(Gr);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){return yt(t)??(t?.id||void 0)}_messagesToChatMessages(t){let{summary:e,messages:n}=tn(t);return[...this._summaryMessage(e),...Ue(n)]}_summaryMessage(t){return t===void 0?[]:[eh(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:n,providerId:i}=t.detail;if(this._config.getRequireModelSelection()&&!this._config.hasSelectedModel()&&!n){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 b=this._byId(a,t),k=this._asRenderTarget(b);k?r=k: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 b of this._originChain(t)){let k=b;if(typeof k?.appendMessage=="function"){r=k;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=De(r)??void 0;if(this._closeDeferred(r),this.options.echoUserMessage!==!1&&t.detail?.echoed!==!0){let b=Array.isArray(t.detail?.files)?t.detail.files:[];r.appendMessage?.({id:J(),role:"user",content:e,timestamp:Date.now(),...b.length>0?{attachments:po(b)}:{},...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=r.getMessages?.().at(-1),c=l?.role==="user"?l.id:void 0,d=J(),h=this._config.getModelConfig(),u=i||h.defaultProvider;if(!u&&!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,d,new dt("No provider selected. Please configure a provider.",z.CONFIG_NO_PROVIDER));return}let p=this._providerFor(u);if(!p){this._handleLifecycleError(r,d,new dt(`Provider '${u}' is not registered.`,z.CONFIG_MISSING_KEY,{providerId:u}));return}r.appendMessage?.({id:d,role:"assistant",content:"",status:"pending",timestamp:Date.now()});let f,g,_,y=Array.isArray(t.detail?.files)?t.detail.files:[];try{f=u?await this._resolveAuth(u):void 0;let b=this._selectFilesToInject(y),k=b.length>0?await this._filesToContentParts(b):[];_=k.length>0?k:void 0,g=this._buildMessages(e,r,_)}catch(b){this._handleLifecycleError(r,d,dt.from(b,z.UNKNOWN_ERROR));return}await this._streamTurn(r,d,p,g,n||h.defaultModel||"",f,{rebuild:async()=>this._buildMessages(e,r,_),...y.length>0?{files:y}:{},...this._turnMeta(t.detail),...o?{conversationId:o}:{},userMessage:{content:this._userContent(e,_),...c?{messageId:c}:{}}})}_buildMessages(t,e,n){let i=this._systemMessages(),r=this.options.history??"viewport",a=e?.getMessages?.()??[];return r==="viewport"?i.push(...this._toHistoryMessages(a)):typeof r=="function"&&i.push(...r(a)),i.push({role:"user",content:this._userContent(t,n)}),jt(i)}_userContent(t,e){return e&&e.length>0?[{type:"text",text:t},...e]:t}_toHistoryMessages(t){let{summary:e,messages:n}=tn(t),i=n.length;for(;i>0&&bo(n[i-1]);)i--;return i>0&&n[i-1].role==="user"&&i--,[...this._summaryMessage(e),...Ue(n.slice(0,i))]}_selectFilesToInject(t){let e=this.options.rawFileInject==="none"?[]:this.options.rawFileInject==="images-only"?t.filter(i=>i.type.startsWith("image/")):t,n=this.options.fileInjectFilter;return n?e.filter(i=>n(i)):e}async _filesToContentParts(t){let e=/^(text\/|application\/(json|xml|javascript|typescript|x-yaml|yaml|toml|csv|markdown))/i,n=/\.(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)||n.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)}):(zr.has(r.name)||(zr.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,n,i,r,a=new AbortController,o,l,c,d){this._streamController!==a&&this._streamController?.abort(),this._streamController=a;let h=this.options.streamRunner??Gn;return this._runViaStreamRunner(h,t,e,n,i,r,a,o,l,c,d)}async _runViaStreamRunner(t,e,n,i,r,a,o,l,c,d,h){let u=o.signal,p=this._targetIdOf(e),f={...d?{conversationId:d}:{},messageId:n,...p?{targetId:p}:{}},g=We({target:e,config:this._config,messageId:n,...p?{targetId:p}:{},...d?{conversationId:d}:{}}),_=r._meta?.prefixSegments,y,b,k,x=C=>{if(C.type==="run-suspended"&&C.agentId==null&&this._keepSubAgentCalls(e,n,C.pending,C.ticket),g(C),C.type==="agent-start"&&C.name&&this._agentNames.get(n)?.set(C.agentId,C.name),C.agentId==null){if(C.type==="tool-failed"&&(k=C.error),C.type==="run-done"&&(b=C.finishReason),C.type==="run-suspended"){let N=C.ticket;y={pending:C.pending,...typeof N=="string"?{ticket:N}:{}}}if(C.type==="run-start"&&_?.length&&!l)for(let N of _)e.addSegment?.(N)}},v=async C=>{let N=await this._config.getTransport().chat(i,C,a,{providerId:i.id,signal:u});return typeof N=="string"?N:Ja(N,u)},E=C=>{let N=this._config.getToolHandler(C);if(!N)return;let D={target:e,config:this._config,...d?{conversationId:d}:{}};return(H,tt,rt)=>N(H,tt,rt?{...D,run:rt}:D)},A=!!this.options.approvalResolver,w=C=>{let N=this._config.getTools().find(D=>D.name===C);if(N)return{maxTurns:N.maxTurns,parallel:N.parallel,needsApproval:A?N.needsApproval:D=>{let H=this._config.ruleOnToolCall(D,f).verdict;return H==="allow"?!1:H}}},m=this._approvalResolverFor(e,f),S=C=>{if(k===void 0||C instanceof dt)return C;let N=C instanceof Error?C.message||C.name:typeof C=="string"?C:String(C);return N===k?new dt(N,z.UNKNOWN_ERROR,void 0,C):C};return{usage:await t({messageId:n,...i.id?{providerId:i.id}:{},...l?{deferral:l}:{},...c&&c.length>0?{files:c}:{},...d?{conversationId:d}:{},...h?{userMessage:h}:{},baseRequest:r,transportCall:v,toolLookup:E,toolConfigLookup:w,approvalResolver:m,emitter:x,signal:u,maxTurns:this.options.maxTurns,toolTimeoutMs:this.options.toolTimeoutMs,...this.options.parallelTools!==void 0?{parallelTools:this.options.parallelTools}:{},idGen:C=>C==="synthetic-tool"?J():`${C}-${J()}`}).catch(C=>{throw S(C)})??void 0,...b?{finishReason:b}:{},...y?{suspended:y}:{}}}_approvalResolverFor(t,e,n=!1){let i=this.options.approvalResolver;return i?(r,a)=>i(r,a,e):(async(r,a)=>{let o=n?this._config.getApprovalPolicy()?.(r,this._config.getTools().find(l=>l.name===r.name),e)??{verdict:"ask"}:this._config.ruleOnToolCall(r,e);return o.verdict==="allow"?{approved:!0}:o.verdict==="deny"?{approved:!1,reason:o.reason?.trim()||"Tool execution was refused by the approval policy.",by:"policy"}:this._askForApproval(r,a,t,e)})}async _answerDeferred(t,e,n,i,r,a=new Set,o=new Set){let l={},{messageId:c}=e,d=this._approvalResolverFor(t,e,!0),h=u=>{for(let p of n.slice(u+1))l[p.toolCallId]={kind:"decision",approved:!1,reason:yh,by:"earlier-refusal"}};for(let[u,p]of n.entries()){if(i.aborted)break;let f={id:p.toolCallId,name:p.name,input:p.input??{}},g=p.agentId===void 0?void 0:this._agentNames.get(c)?.get(p.agentId),_=p.agentId===void 0?f:{...f,agent:{id:p.agentId,...g?{name:g}:{}}};if(p.reason==="approval"){let y;try{y=await d(_,i)}catch(b){if(!i.aborted&&b?.name!=="AbortError")throw b}if(!y||i.aborted)return;if(l[p.toolCallId]={kind:"decision",...y},y.approved)o.add(jr(f));else{h(u);break}}else if(p.reason==="external"){let y=null,b=jr(f);if(!a.has(b)&&!o.has(b))try{y=await this._gateBrowserTool(_,i,t,e,r)}catch(E){if(!i.aborted&&E?.name!=="AbortError")throw E;y=void 0}if(y===void 0||i.aborted)return;if(y&&!y.approved){l[p.toolCallId]={kind:"decision",...y},h(u);break}let k=y?.payload,x=k&&typeof k=="object"&&!Array.isArray(k)?{...f,input:{...f.input,...k}}:f,v=this._config.getToolHandler(p.name);try{if(!v)throw new Error(`No browser handler is registered for "${p.name}".`);let E=await v(x,i,{target:t,config:this._config,...e.conversationId?{conversationId:e.conversationId}:{}});l[p.toolCallId]={kind:"result",content:E.content,...E.structuredContent!==void 0?{structuredContent:E.structuredContent}:{}}}catch(E){if(i.aborted)break;l[p.toolCallId]={kind:"failed",error:E instanceof Error?E.message:String(E)}}}}return i.aborted?void 0:l}async _gateBrowserTool(t,e,n,i,r){let a=this.options.approvalResolver?this._config.getTools().find(l=>l.name===t.name)?.needsApproval?"ask":"allow":this._config.ruleOnToolCall(t,i).verdict;if(a==="allow")return null;a==="ask"&&r?.({type:"tool-awaiting-approval",toolCallId:t.id,name:t.name,input:t.input,...t.agent?{agentId:t.agent.id}:{}});let o=await this._approvalResolverFor(n,i)(t,e)??void 0;return o?.approved&&a==="ask"&&(t.agent?r?.({type:"tool-approved",toolCallId:t.id,agentId:t.agent.id}):n.updateSegment?.(`tool-${t.id}`,{status:"pending"})),o}_spendPause(t,e){let n=this._messageOf(t,e),i=n?.segments,r=o=>o.type==="tool_call"&&!!o.deferred,a=!!i?.some(r);!a&&!n?.deferredCalls?.length||t.updateMessage?.(e,{...a?{segments:i.map(o=>{if(!r(o))return o;let{deferred:l,...c}=o;return c})}:{},...n?.deferredCalls?.length?{deferredCalls:void 0}:{}})}_messageOf(t,e){return t.getMessage?.(e)??t.getMessages?.()?.find(n=>n.id===e)}_keepSubAgentCalls(t,e,n,i){let r=this._agentNames.get(e),a=n.filter(o=>o.agentId!=null).map(o=>{let l=r?.get(o.agentId);return{toolCallId:o.toolCallId,name:o.name,input:o.input??{},reason:o.reason,agentId:o.agentId,...l?{agentName:l}:{},...typeof i=="string"?{ticket:i}:{}}});a.length>0&&t.updateMessage?.(e,{deferredCalls:a})}_closeOpenCalls(t,e){let n=this._messageOf(t,e),i=n?.segments,r=o=>o.type==="tool_call"&&(o.status==="pending"||o.status==="awaiting-approval"),a=!!i?.some(r);!a&&!n?.deferredCalls?.length||t.updateMessage?.(e,{...a?{segments:i.map(o=>{if(!r(o))return o;let{deferred:l,...c}=o;return{...c,status:"aborted"}})}:{},...n?.deferredCalls?.length?{deferredCalls:void 0}:{}})}_resumeMessages(t,e,n){let i=t.getMessages?.().find(r=>r.id===e);return[...n,...i?mo(i,hn,{openDeferred:!0}):[]]}_resumeBase(t,e){let n=t.slice(0,e),i=n.map(o=>o.role).lastIndexOf("user"),r=this.options.history??"viewport",a=r==="viewport"?this._toHistoryMessages(n):typeof r=="function"?r(n):[];return jt([...this._systemMessages(),...a,...i>=0?Ue([n[i]]):[]])}_closeDeferred(t){let n=[...t.getMessages?.()??[]].reverse().find(r=>r.role==="assistant"),i=!!n?.segments?.some(us);!n||!i&&!n.deferredCalls?.length||t.updateMessage?.(n.id,{...i?{segments:n.segments.map(r=>{if(!us(r))return r;let{deferred:a,...o}=r;return{...o,status:"aborted"}})}:{},...n.deferredCalls?.length?{deferredCalls:void 0}:{}})}async resumeDeferred(t){let e=typeof t=="string"?this._byId(t):t??this.options.targetResolver?.()??null,n=e?this._asRenderTarget(e):this._scanForTarget();if(!n)return!1;let i=n.getMessages?.()??[],r=[...i].reverse().find(f=>f.role==="assistant"),a=(r?.segments??[]).filter(us),o=r?.deferredCalls??[],l=a.find(f=>f.deferred?.ticket)?.deferred?.ticket??o.find(f=>f.ticket)?.ticket;if(!r||a.length+o.length===0||!l||this._resuming.has(r.id)||this._turnsInFlight.has(r.id))return!1;let c=this._config.getModelConfig(),d=r.model&&this._config.getAIProvider(r.model.providerId)?r.model:void 0,h=d?.providerId??c.defaultProvider,u=this._providerFor(h);if(!u)return console.warn("[AparteClient] Cannot resume the paused turn: no provider is selected."),!1;this._beginUserTurn();let p=De(n)??void 0;this._resuming.add(r.id);try{let f=u.id?await this._resolveAuth(u.id):void 0,g=[...a.map(b=>({toolCallId:b.toolCall.id,name:b.toolCall.name,input:b.toolCall.input,reason:b.deferred.reason})),...o.map(b=>({toolCallId:b.toolCallId,name:b.name,input:b.input,reason:b.reason,...b.agentId!==void 0?{agentId:b.agentId}:{}}))],_=new Map(o.flatMap(b=>b.agentId!==void 0&&b.agentName?[[b.agentId,b.agentName]]:[])),y=this._resumeBase(i,i.indexOf(r));await this._streamTurn(n,r.id,u,y,d?.modelId??c.defaultModel??"",f,{resume:{pending:g,ticket:l},rebuild:async()=>{let b=n.getMessages?.()??[],k=b.findIndex(x=>x.id===r.id);return k>=0?this._resumeBase(b,k):y},...d?.temperature!==void 0?{temperature:d.temperature}:{},...p?{conversationId:p}:{},..._.size>0?{agentNames:_}:{}})}finally{this._resuming.delete(r.id)}return!0}_resuming=new Set;_updateMessage(t,e,n){t.updateMessage&&t.updateMessage(e,n)}_handleLifecycleError(t,e,n){let i={id:`error-${J()}`,type:"error",content:n.message,code:n.code};if(Cs(n.code,r=>this._config.t(r))!==void 0&&console.warn(`[aparte] A turn failed (${n.code}): ${n.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]});lt(t,"aparte-message-error",{messageId:e,error:n},this._targetIdOf(t))}};function Mo(s){return s.next?Mo(s.next):"current"in s?s:null}var nn=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 n=this._head;n;n=n.prev)e[n.level]=n.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 n=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(n){n.current=e,this._relink(r,n);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 n=e.prev??this._root;n.next=e,this._head=Mo(e)}resetHead(t){let e=this._nodes.get(t);if(!e)return;let n=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),n!==null&&n!==e&&this._nodes.get(n.current.id)===n||(this._head=e.prev)}updateMessage(t,e){let n=this._nodes.get(t);n&&(n.current={...n.current,...e})}clearChildren(t){let e=this._nodes.get(t);if(e){for(let n of[...e.children]){let i=this._nodes.get(n);i&&(this._deleteDescendants(i),this._nodes.delete(n))}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:n}of t.messages){if(n!==null&&!this._nodes.has(n)){console.warn(`[AparteMessageRepository] import: message "${e.id}" names a parent "${n}" 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(n,e)}t.headId&&this.switchToBranch(t.headId)}export(){let t=[],e=(n,i)=>{for(let r of n){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 n=t??this._root;n.children=[...n.children,e.current.id],n.next===null&&(n.next=e),e.prev=t}_relink(t,e){let n=e.prev??this._root;if(n!==(t??this._root)&&(n.children=n.children.filter(r=>r!==e.current.id),n.next===e)){let r=n.children[0];n.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 n of t.children){let i=this._nodes.get(n);i&&this._updateLevels(i,e+1)}}_deleteDescendants(t){for(let e of t.children){let n=this._nodes.get(e);n&&(this._deleteDescendants(n),this._nodes.delete(e))}t.children=[],t.next=null}};function Zt(s){return s.status==="streaming"||s.status==="pending"?!0:s.status===void 0&&s.role==="assistant"&&!s.content?.trim()&&!s.segments?.length}function Io(s,t,e){let n="other";try{n=new Intl.PluralRules(e).select(t)}catch{}let i=s.split("|"),r=o=>i.find(l=>l.startsWith(`${o}:`)),a=r(n)??r("other")??s;return a.slice(a.indexOf(":")+1).replace("{n}",String(t))}var Sh=".aparte-message-content, .aparte-segments, .aparte-content, .aparte-checkpoint__summary";function ft(s){return!!s?.closest?.(Sh)}var Kr=Symbol.for("aparte.dialogTriggers"),Bs=null,sn=null;function Ch(s){Bs=s.target,sn=null}function kh(s){sn=s.target}function Eh(s){let t=s.target;if(!t?.closest)return;let e=t.closest("[data-aparte-dialog-open]");if(e&&!ft(e)){let i=e.getAttribute("data-aparte-dialog-open"),r=i?document.getElementById(i):null;r instanceof HTMLDialogElement&&!r.open&&(s.preventDefault(),r.showModal());return}let n=t.closest("[data-aparte-dialog-close]");if(n&&!ft(n)){let i=n.closest("dialog");i instanceof HTMLDialogElement&&i.open&&(s.preventDefault(),i.close(n.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=Bs===t&&sn===t;Bs=null,sn=null,i&&t.close()}}function Lo(s=document){let t=s;t[Kr]||(t[Kr]=!0,s.addEventListener("pointerdown",Ch,!0),s.addEventListener("pointerup",kh,!0),s.addEventListener("click",Eh))}var hs="defer-hydration",fe=new WeakMap,ge=new WeakMap,ne=new WeakSet,rn=new WeakSet,$s=new WeakMap,Vr=new WeakSet;function Yr(s){if(rn.has(s))return!1;if(ge.has(s))return!0;let t=s.closest(`[${hs}]`);if(!t)return!1;ge.set(s,t);let e=fe.get(t);if(!e){e=[],fe.set(t,e);let n=new MutationObserver(()=>{t.hasAttribute(hs)||Th(t)});n.observe(t,{attributes:!0,attributeFilter:[hs]}),$s.set(t,n)}return e.push(s),!0}function Th(s){$s.get(s)?.disconnect(),$s.delete(s);let t=fe.get(s)??[];fe.delete(s);for(let e of t)ge.delete(e),e.isConnected&&!rn.has(e)&&e.connectedCallback?.()}function G(s){if(Vr.has(s))return;Vr.add(s);let t=s.prototype,e=t.connectedCallback,n=t.attributeChangedCallback,i=t.disconnectedCallback,r=s.observedAttributes??[];t.connectedCallback=function(){if(Yr(this)){ne.add(this);return}if(ne.has(this)){ne.delete(this);for(let a of r){let o=this.getAttribute(a);o!==null&&n?.call(this,a,null,o)}}rn.add(this),e?.call(this)},n&&(t.attributeChangedCallback=function(a,o,l){if(Yr(this)){ne.add(this);return}n.call(this,a,o,l)}),t.disconnectedCallback=function(){let a=ge.get(this);if(a){ge.delete(this);let o=fe.get(a);o&&o.splice(o.indexOf(this),1);return}ne.has(this)||(rn.delete(this),i?.call(this))}}function Z(s){return s===""?!0:!!s}var _n=class extends HTMLElement{static get observedAttributes(){return["value","disabled","selected","data-status"]}connectedCallback(){this.setAttribute("role","option"),this._updateAriaSelected(),this._updateStatusDot()}attributeChangedCallback(t,e,n){e!==n&&(t==="selected"&&this._updateAriaSelected(),t==="disabled"&&this.setAttribute("aria-disabled",this.hasAttribute("disabled")?"true":"false"),t==="data-status"&&this._updateStatusDot())}get value(){return this.getAttribute("value")||this.textContent?.trim()||""}set value(t){this.setAttribute("value",t)}get label(){return Array.from(this.childNodes).find(e=>e.nodeType===Node.TEXT_NODE)?.textContent?.trim()||this.value}get disabled(){return this.hasAttribute("disabled")}set disabled(t){this.toggleAttribute("disabled",Z(t))}get selected(){return this.hasAttribute("selected")}set selected(t){this.toggleAttribute("selected",Z(t))}_updateAriaSelected(){this.setAttribute("aria-selected",this.selected?"true":"false")}_updateStatusDot(){let t=this.getAttribute("data-status"),e=this.querySelector(".aparte-status-dot");if(!t){e?.remove();return}e||(e=document.createElement("span"),e.className="aparte-status-dot",e.setAttribute("aria-hidden","true"),this.appendChild(e)),e.setAttribute("data-status",t)}};G(_n);customElements.get("aparte-option")||customElements.define("aparte-option",_n);var mn=class s extends HTMLElement{static _labelIdSeq=0;static get observedAttributes(){return["label","collapsible","collapsed","loading"]}connectedCallback(){this.setAttribute("role","group"),this._render()}attributeChangedCallback(t,e,n){e!==n&&(t==="collapsed"&&this._updateCollapsedState(),this.isConnected&&this._render())}get label(){return this.getAttribute("label")||""}set label(t){this.setAttribute("label",t)}get collapsible(){return this.hasAttribute("collapsible")}set collapsible(t){this.toggleAttribute("collapsible",Z(t))}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(t){this.toggleAttribute("collapsed",Z(t))}get loading(){return this.hasAttribute("loading")}set loading(t){this.toggleAttribute("loading",Z(t))}_render(){if(this.label&&!this.querySelector(".aparte-optgroup-header")){let e=document.createElement("div");e.className="aparte-optgroup-header";let n=document.createElement("span");if(n.className="aparte-optgroup-label",n.id=`aparte-optgroup-label-${++s._labelIdSeq}`,n.textContent=this.label,this.setAttribute("aria-labelledby",n.id),e.appendChild(n),this.collapsible){let i=document.createElement("span");i.className="aparte-optgroup-chevron",i.innerHTML=I(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,` ${I(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(mn);customElements.get("aparte-optgroup")||customElements.define("aparte-optgroup",mn);var bn=class s 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,n){if(e!==n&&this.isConnected){if(t==="value"&&e!==n&&n!==this._value&&(this._value=n||"",this._updateTriggerLabel()),t==="open"){let i=this.hasAttribute("open");i!==this._isOpen&&(i?this._openDropdown():this._closeDropdown())}t==="placeholder"&&this._updateTriggerLabel(),t==="searchable"&&this._applySearchable(),t==="disabled"&&(this._applyDisabled(),!this.hasAttribute("disabled")&&this.hasAttribute("open")&&this._openDropdown())}}get value(){return this._value}set value(t){if(t===this._value)return;let e=this._value;this._value=t,this.setAttribute("value",t),this._updateTriggerLabel(),this._emitChange(e)}get open(){return this._isOpen}set open(t){this.toggleAttribute("open",Z(t))}_buildSearchInput(t){let e=document.createElement("input");return e.type="text",e.className="aparte-select-search",e.placeholder=t.t("selectSearchPlaceholder")||"Search\u2026",e.setAttribute("aria-label",t.t("selectSearchLabel")||"Search options"),e.setAttribute("role","combobox"),e.setAttribute("aria-haspopup","listbox"),e.setAttribute("aria-autocomplete","list"),e.setAttribute("aria-expanded",String(this._isOpen)),e}_applySearchable(){if(!this._dropdown||!this._trigger)return;let t=this.hasAttribute("searchable");if(t===!!this._searchInput)return;this._isOpen&&this._closeDropdown();let e=this._trigger.getAttribute("aria-controls");if(t){let n=this._buildSearchInput(I(this));e&&n.setAttribute("aria-controls",e),this._dropdown.prepend(n),this._searchInput=n,n.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 n=Array.from(this.children),i=I(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-${++s._listboxSeq}`,r.setAttribute("aria-controls",u.id),h?.setAttribute("aria-controls",u.id),n.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(n=>n.className!=="aparte-select-trigger"&&n.className!=="aparte-select-dropdown");e.length!==0&&(this._observer?.disconnect(),t.innerHTML="",e.forEach(n=>{t.appendChild(n)}),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=ct(t);(!e||!this.contains(e))&&this._closeDropdown()}_handleKeydown(t){if(!this._isOpen)return;let e=ot(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 n=this._visibleOptions()[this._activeIndex];n&&(t.preventDefault(),this._selectOption(n));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 n=this._activeIndex<0?t>0?-1:0:this._activeIndex;this._setActive(n+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 n=this._visibleOptions();if(n.length===0){this._activeIndex=-1,this._activeHost()?.removeAttribute("aria-activedescendant");return}let i=Math.max(0,Math.min(t,n.length-1));this._activeIndex=i;let r=n[i];r.id||(r.id=`aparte-option-${++s._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(n=>n.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,n=window.innerHeight,i=n-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=`${n-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()||"",n=this._value;this._value=e,this.setAttribute("value",e),this._updateTriggerLabel(),this._closeDropdown(),this._emitChange(n),this._trigger?.focus()}_updateNames(){let t=this.getAttribute("placeholder")||"Select...",e=this.getAttribute("aria-label")||t,n=this.querySelector(".aparte-select-options");n&&n.getAttribute("aria-label")!==e&&n.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 n=this._trigger?.querySelector(".aparte-select-label-sizer");if(n){let r=[t,...Array.from(this.querySelectorAll("aparte-option"),o=>Ro(o))],a=Array.from(n.children,o=>o.getAttribute("data-label")??"");(r.length!==a.length||r.some((o,l)=>o!==a[l]))&&n.replaceChildren(...r.map(o=>{let l=document.createElement("span");return l.setAttribute("data-label",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 Ro(t);return""}_filterOptions(t){this.querySelectorAll("aparte-option").forEach(n=>{let r=(n.textContent?.toLowerCase()||"").includes(t);n.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 Ro(s){let t="";for(let e of s.childNodes)e.nodeType===Node.ELEMENT_NODE&&e.matches(".aparte-option__meta, .aparte-status-dot")||(t+=e.textContent??"");return t.trim()}G(bn);customElements.get("aparte-select")||customElements.define("aparte-select",bn);var vn=class extends HTMLElement{static get observedAttributes(){return["value"]}_r=9;get _circ(){return 2*Math.PI*this._r}connectedCallback(){this._render()}attributeChangedCallback(t,e,n){e!==n&&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 n=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="${n.toFixed(2)}"/></svg>`}};G(vn);customElements.get("aparte-progress-spinner")||customElements.define("aparte-progress-spinner",vn);var yn=class extends HTMLElement{static get observedAttributes(){return["name"]}_unsubscribe=null;connectedCallback(){this._render(),this._unsubscribe=Lt(this,()=>this._render())}disconnectedCallback(){this._unsubscribe?.(),this._unsubscribe=null}attributeChangedCallback(){this.isConnected&&this._render()}_render(){let t=this.getAttribute("name"),e=t?I(this).getIcon(t):null;this.innerHTML=e??"",this.firstElementChild?.setAttribute("aria-hidden","true")}};G(yn);customElements.get("aparte-icon")||customElements.define("aparte-icon",yn);var Ai=".aparte-elic-option--command, .aparte-approval-option",xh='input:not([type="checkbox"]):not([type="radio"]):not([type="button"]), textarea, select, [contenteditable]:not([contenteditable="false"])';function Oo(s){[...s.querySelectorAll(Ai)].forEach((e,n)=>{n>=9||(e.setAttribute("data-shortcut",String(n+1)),e.setAttribute("aria-keyshortcuts",String(n+1)))})}function Po(s){let t=e=>{if(e.defaultPrevented||e.repeat||e.isComposing||e.keyCode===229||e.ctrlKey||e.metaKey||e.altKey||e.shiftKey||s.hasAttribute("data-collapsed"))return;let n=e.target instanceof Element?e.target:null;if(!(!n||n.closest(xh))){if(/^[1-9]$/.test(e.key)){if(!n.closest(Ai))return;let i=s.querySelectorAll(Ai)[Number(e.key)-1];if(!i)return;e.preventDefault(),i.click();return}if(e.key==="Escape"){let i=s.querySelector(".aparte-elic-skip"),r=s.querySelectorAll(".aparte-approval-option--deny"),a=i??(r.length===1?r[0]:null);if(!a)return;e.preventDefault(),a.click()}}};return s.addEventListener("keydown",t),()=>s.removeEventListener("keydown",t)}function No(s){let t=s.activeElement;for(;t?.shadowRoot?.activeElement;)t=t.shadowRoot.activeElement;return t}function gi(s,t){for(let e=s;e;e=e.parentNode??(e instanceof ShadowRoot?e.host:null))if(e===t)return!0;return!1}function Do(s,t,e,n,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",()=>{s.setAttribute("data-collapsed",""),i(),a.focus()}),a.addEventListener("click",()=>{s.removeAttribute("data-collapsed"),i(),n()}),t.prepend(r),s.append(a),{relabel:l}}var wn=class extends HTMLElement{_pending=null;_onTurnEnd=t=>{let e=t.detail?.targetId,n=this._pendingTargetId();e&&n&&e!==n||this._cancelPending()};_unsubscribeConfig=null;connectedCallback(){this.style.display="none",this._unsubscribeConfig=Lt(this,()=>this._relabelPending()),I(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(){I(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=I(this);Y(t,()=>this._pending.relabel())}_present=t=>{let e=this._getComposer();return e?new Promise((n,i)=>{let r=!1,a={},o=No(document),l=()=>{let C=t.message;return String(typeof C=="function"?C():C??"")},c="aparte-chat, [data-aparte-chat], [data-aparte-host]",d='input, textarea, select, [contenteditable]:not([contenteditable="false"])',h=e.closest(c)??e.parentElement??e,u=!(o instanceof HTMLElement)||o===document.body,p=u?null:o,f=p!==null&&gi(p,h),g=p!==null&&p.matches(d),_=p!==null&&!f&&(g||p.tagName==="IFRAME"||p.closest(c)!==null),y=C=>{let N=e.querySelector(":scope > .aparte-elic-status");N||(N=document.createElement("span"),N.className="aparte-sr-only aparte-elic-status",N.setAttribute("role","status"),e.appendChild(N));let D=N;D.textContent="",C&&setTimeout(()=>{D.isConnected&&(D.textContent=C)},60)},b=(C,N)=>{if(_){y(N);return}let D=window.scrollX,H=window.scrollY;g&&f?(C.el.hasAttribute("tabindex")||C.el.setAttribute("tabindex","-1"),C.el.hasAttribute("role")||C.el.setAttribute("role","group"),N&&!C.el.hasAttribute("aria-label")&&C.el.setAttribute("aria-label",N),C.el.focus()):C.focus(),u&&(window.scrollX!==D||window.scrollY!==H)&&window.scrollTo(D,H)},k=()=>{if(r)return!1;r=!0,this._pending=null;let C=No(document),N=C instanceof Node&&gi(C,e);return e.hidePanel(a.token),y(""),N&&((!_&&p!==null&&p.isConnected&&!gi(p,e)?p:null)??e).focus(),!0},x=C=>{k()&&n(C)},v=(C="aborted")=>{k()&&i(new At(C))};if(t.signal){if(t.signal.aborted){v();return}t.signal.addEventListener("abort",()=>v(),{once:!0})}let E=I(this);if(t.kind==="approval"){let C=()=>H.isComplete()&&!H.el.hasAttribute("data-collapsed"),N=()=>C()?"submit":"none",D=()=>e.setPanelSubmitEnabled(C(),N()),H=Y(E,()=>To(t.message,t.options??[],D,t.details,t.allowOther??!0,t.preview));Oo(H.el),Po(H.el),H.onSettle(rt=>x({action:"accept",content:rt}));let tt=Do(H.el,H.dismiss,E,()=>H.focus(),D);this._pending={abort:()=>v(),composer:e,relabel:()=>{H.relabel(),tt.relabel(I(this))}},a.token=e.showPanel(H.el,{submitEnabled:H.isComplete(),mode:N(),onSubmit:()=>{H.isComplete()&&x({action:"accept",content:H.getContent()})},onEvict:()=>v()}),b(H,l());return}let A=t.schema??{type:"string"},w=()=>{let C=m.el.hasAttribute("data-collapsed");e.setPanelSubmitEnabled(!C&&m.canProceed(),C?"none":m.mode())},m=Y(E,()=>Eo(t.message,A,w)),S=document.createElement("button");S.type="button",S.className="aparte-btn aparte-elic-skip",S.textContent=E.t("elicitationSkip"),S.addEventListener("click",()=>x({action:"decline"})),m.dismiss.appendChild(S),Oo(m.el),Po(m.el);let O=Do(m.el,m.dismiss,E,()=>m.focus(),w);m.onSettle(C=>x({action:"accept",content:C})),this._pending={abort:()=>v(),composer:e,relabel:()=>{m.relabel();let C=I(this);S.textContent=C.t("elicitationSkip"),O.relabel(C)}},a.token=e.showPanel(m.el,{submitEnabled:m.canProceed(),mode:m.mode(),onEvict:()=>v(),onSubmit:()=>{m.isComplete()&&x({action:"accept",content:m.getContent()})}}),b(m,l())}):Promise.reject(new At("no-presenter"))};_cancelPending(){this._pending?.abort()}_pendingTargetId(){return yt(this._pending?.composer??null)}_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(wn),customElements.define("aparte-elicitation",wn));function rl(s){return!s.hasAttribute("loading")&&!s.querySelector("aparte-chat-bubble")}var An=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=_o(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,n){if(e===n)return;if(t==="attachments"){this._syncAttachments();return}if(t==="type-to-focus"){let r=this.querySelector("aparte-composer");n!==null?r?.setAttribute(t,n):r?.removeAttribute(t);return}if(t==="disabled"&&n===null&&this._gated){this._gateOwns=!0;return}let i=this.querySelector("aparte-composer");i&&(n!==null?i.setAttribute(t,n):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="${L(t)}"`:"")+(this.hasAttribute("disabled")?" disabled":""),n=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
+ ${n?"<aparte-composer-attachments></aparte-composer-attachments>":""}
85
+ <div class="aparte-composer-row">
86
+ ${n?"<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"),n=e?.querySelector(".aparte-composer-row");if(!t||!e||!n)return;let i=e.querySelector("aparte-composer-attachments"),r=n.querySelector("aparte-composer-add-attachment");if(this.hasAttribute("attachments")){i||e.insertBefore(document.createElement("aparte-composer-attachments"),n),r||n.insertBefore(document.createElement("aparte-composer-add-attachment"),n.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||rl(t))}};G(An);customElements.get("aparte-chat")||customElements.define("aparte-chat",An);function Mh(s,t){let e=[],n=-1,i=-1,r=0,a=()=>{r>=2&&e.push({from:n,to:i}),n=-1,i=-1,r=0};return s.forEach((o,l)=>{let c=t(o);c==="stop"?a():c==="fold"&&(n<0&&(n=l),i=l,r+=1)}),a(),e}function fn(s,t){let e=`[data-segment-id="${nt(t)}"]`;return s.querySelector(`:scope > ${e}, :scope > .aparte-turn > .aparte-turn__body > ${e}`)}function Ih(s){let t=1/0,e=-1/0;for(let n of s){let{startedAt:i,endedAt:r}=_e(n)??{};if(i==null||r==null)return;t=Math.min(t,i),e=Math.max(e,r)}return s.length>0?e-t:void 0}var Lh=(s,t)=>t?s.split(t).length-1:0;function Rh(s,t){let e=s.createElement("span");e.className="aparte-tag aparte-inline-token",t.kind&&(e.dataset.kind=t.kind);let n=s.createElement("span");return n.className="aparte-tag__label",n.textContent=t.label,e.appendChild(n),e}function Oh(s,t,e){let n=Lh(t.slice(0,e.start),e.text),i=s.ownerDocument,r=i.createTreeWalker(s,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(n-- >0)continue;let l=i.createRange();l.setStart(a,o),l.setEnd(a,o+e.text.length),l.deleteContents(),l.insertNode(Rh(i,e));return}}}function Ph(s,t,e){if(!s.querySelector(".aparte-inline-token"))for(let n of[...e].sort((i,r)=>r.start-i.start))n.text&&Oh(s,t,n)}function Bo(s,t,e){let n=document.createElement("button");return n.type="button",n.className=`aparte-btn aparte-btn--sm ${t}`,n.textContent=s,n.addEventListener("click",e),n}function Nh(s){let t=document.createElement("div");t.className="aparte-feedback-reasons",t.setAttribute("role","group"),t.setAttribute("aria-label",s.title);let e=document.createElement("span");e.textContent=s.title,t.appendChild(e);for(let n of s.reasons)t.appendChild(Bo(n,"aparte-btn--surface",()=>s.onPick(n)));return t.appendChild(Bo(s.dismiss,"aparte-btn--ghost",s.onClose)),t}var $o=s=>!!s&&typeof s.getMessages=="function"&&typeof s.updateMessage=="function";function Dh(s){let t=bt(s);if($o(t))return t;let e=s.closest("aparte-chat-viewport");return $o(e)?e:null}function Bh(s,t){let e=Dh(s);if(!e)return 0;let n=e.getMessages().filter(r=>r.contextSummary!==void 0).map(r=>r.id);for(let r of n)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})),n.length}function Ct(s,t,e){let n=document.createElement(s);return n.className=t,e!==void 0&&(n.textContent=e),n}function ve(s,t){let e=Ct("button","aparte-btn aparte-btn--ghost aparte-btn--sm aparte-checkpoint__action",t);return e.type="button",e.setAttribute("data-checkpoint-action",s),e}function $h(s){let{kind:t,locale:e}=s,n=Ct("div","aparte-checkpoint");n.setAttribute("role","group"),n.setAttribute("aria-label",e.checkpointGroup??"Context summary"),n.setAttribute("data-state",t);let i=Ct("div","aparte-checkpoint__row aparte-divider aparte-divider--label"),r=Ct("div","aparte-checkpoint__label");i.appendChild(r),n.appendChild(i);let a;if(t==="done"){let l=s.count??0;a=l===1?e.checkpointCountOne??"1 message summarised for the model":(e.checkpointCount??"{n} messages summarised for the model").replace("{n}",()=>String(l))}else t==="legacy"?a=e.checkpointLegacy??"Earlier messages were summarised":t==="pending"?a=e.checkpointPending??"Summarising the context\u2026":a=e.checkpointFailed??"Couldn't summarise the context";let o=Ct("span","aparte-checkpoint__text",a);if(t==="pending"?(o.classList.add("aparte-shimmer"),o.setAttribute("role","status")):t==="failed"&&(o.setAttribute("role","status"),s.reason&&(o.title=s.reason,o.appendChild(Ct("span","aparte-sr-only",`: ${s.reason}`)))),r.appendChild(o),t==="done"||t==="legacy")if(s.confirming&&t==="done"){let l=Ct("span","aparte-checkpoint__confirm"),c=Ct("span","aparte-checkpoint__question",e.checkpointRestoreConfirm??"Send the original messages to the model again?");c.id=`${s.summaryId}-question`;let d=ve("restore-confirm",e.checkpointRestore??"Restore");d.setAttribute("aria-describedby",c.id),l.append(c,d,ve("restore-cancel",e.cancel??"Cancel")),r.appendChild(l)}else{let l=ve("toggle",s.open?e.checkpointHide??"Hide summary":e.checkpointShow??"Show summary");l.setAttribute("aria-expanded",String(s.open)),l.setAttribute("aria-controls",s.summaryId),r.appendChild(l),t==="done"&&r.appendChild(ve("restore",e.checkpointRestore??"Restore"))}else t==="failed"&&r.appendChild(ve("retry",e.retry??"Retry"));if(t==="done"||t==="legacy"){let l=Ct("div","aparte-checkpoint__summary aparte-segment-content");l.id=s.summaryId,s.open||(l.hidden=!0),n.appendChild(l)}return n}function Ho(s,t){return s.type==="tool_call"?ja(t):s.type==="activity"?za(t):null}var qo=!1;function Hh(s){qo||(qo=!0,console.warn(`[aparte] No renderer for segment "${s}". Register one with registerSegmentRenderer({ type: '${s}', render }) from @aparte/core \u2014 see https://apartejs.dev/guides/customization/#custom-segment-types`))}function _i(s){let t=typeof s.fallback=="string"&&s.fallback.trim()?s.fallback:null;t||Hh(s.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: ${s.type}]`,e}function Rt(s,t){let e=ei(s,t);return e||(Va(t),ei(s,t))}function ye(s,t){let e;if(s instanceof HTMLElement)e=s;else{let n=document.createElement("div");n.innerHTML=s,e=n.firstElementChild}return e&&t&&!e.hasAttribute("data-segment-id")&&e.setAttribute("data-segment-id",t.id),e}var Ce=new Map;function qh(){let s=[...Ce].filter(([e])=>!e.firstChild);Ce.clear();let t=s.map(([,{bubble:e,role:n}])=>{let i=getComputedStyle(e).getPropertyValue(`--aparte-avatar-image-${n}`).trim();return i!==""&&i!=="none"});s.forEach(([e],n)=>e.toggleAttribute("data-image",t[n]))}var Fh=0,Sn=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-${++Fh}`;_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(),Y(this._cfg,()=>ha(this)),wa(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(Rt("tool_call",e)!==Kt)return null;let n=t.toolCall?.name;return!n||e.isToolHidden(n)?null:e.getToolRenderer(n)??null}_innerRendererFor(t){return t.type!=="activity"?this._toolRendererFor(t):Rt("activity",this._cfg)!==Vt?null:this._cfg.getActivityRenderer(t.activityType)??null}_install(t,e,n,i=t){let r=this._drawn.get(t.id);r&&r.el!==e&&this._release(t.id);let a={el:e,renderer:n,tool:null,segment:t};this._drawn.set(t.id,a),this.isConnected||this._scheduleReleaseCheck(),n?.setup&&Y(this._cfg,()=>n.setup(e,i)),a.tool=Ho(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 n=e.renderer?.cleanup;if(n)try{Y(this._cfg,()=>n.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 n=this._cfg,i=Rt(t.type,n),r=e.el;this._release(t.id);let a=i?this._drawnAs(t):t,o=i?ye(Y(n,()=>i.render(t)),t):_i(t);return o?(r.replaceWith(o),this._install(t,o,i,a),!0):(r.remove(),!0)}_stillDrawnByCurrent(t,e){return Rt(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!==Q||this._redrawSegmentsWhoseRendererChanged()};_keepsItsDrawing(t,e){return(oi(e.renderer)||oi(e.tool))&&this._stillDrawnByCurrent(t,e)}_redrawIfStale(){if(!(this._streaming||this._editing||ht(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=ht(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=Rt(t.type,this._cfg);if(!e?.relabel)continue;let n=fn(this._segmentsEl,t.id);n&&Y(this._cfg,()=>e.relabel(n,t))}this._syncTurns()}}_updateLocalizedLabels(){let t=this._cfg.getLocale(),e=(n,i)=>{this.querySelector(n)?.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 I(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??=co(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,n){if(e!==n)switch(t){case"data-role":(n==="user"||n==="assistant")&&(this._role=n,this._updateRole());break;case"content":this._content=n||"",this._resetMarkdownStream(),this._updateContent();break;case"timestamp":this._updateTimestamp(n);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(n!==null&&n!=="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 n=Nh({reasons:e,title:this._cfg.t("feedbackReasonTitle"),dismiss:this._cfg.t("feedbackReasonDismiss"),onPick:i=>{n.remove(),st(this,"aparte-feedback-reason",{messageId:t,reason:i})},onClose:()=>n.remove()});this.querySelector(".aparte-footer")?.after(n)}setTokens(t){this._tokens=t,this._drawTokens()}_drawTokens(){this._contentEl&&this._role==="user"&&this._tokens?.length&&Ph(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 n=this._segments.flatMap(i=>i.type==="text"?i.sources??[]:[]);Ea(e,t,n,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((n,i)=>n.id!==this._segments[i].id||!this._drawn.has(n.id)))return!1;let e=new Set(t.filter(n=>this._keepsItsDrawing(n,this._drawn.get(n.id))).map(n=>n.id));if(e.size===0)return!1;this._segments=t,this._drawnWithVersion=ht(this._cfg);for(let n of t)e.has(n.id)?this._applySegmentUpdate(n.id,n,n):this._redrawSegment(n);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 n=this._segments.findIndex(i=>i.id===t);if(n!==-1){let i=qs(this._segments[n],e);this._segments[n]=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()):this._cfg.getTurnSummary()?.label&&this._turnHolding(this._drawn.get(t)?.el)&&this._syncTurns()}}appendToSegment(t,e){let n=this._segments.find(i=>i.id===t);n&&"content"in n&&(n.content+=e,n.isStreaming!==!1&&this._written.add(t),this._applySegmentUpdate(t,n,{content:n.content}),this._syncCopyAction())}_settleWrittenSegments(){for(let t of this._written){let e=this._segments.findIndex(r=>r.id===t),n=this._segments[e];if(!n||n.isStreaming===!1)continue;let i={...n,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?fn(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 n=this.querySelector(".aparte-message-content");if(!n)return;e=document.createElement("div"),e.className="aparte-finish-note",n.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 n=this._checkpointKind();e.toggleAttribute("data-superseded",this._isLegacyCompaction()&&!this._contextSummary);let i=this.querySelector(":scope > .aparte-checkpoint");if(!n){let p=i&&document.activeElement&&i.contains(document.activeElement);i?.remove(),this._checkpointDrawn="",p&&(e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1"),e.focus({preventScroll:!0}));return}let r=this.getAttribute("data-checkpoint-reason")??"",a=this._checkpointSummaryText(),o=n==="done"&&this._contextSummary?.includesSelf===!0,l=JSON.stringify([n,this._contextSummary?.count,this._contextSummary?.createdAt,r,this._checkpointOpen,this._confirmingRestore,this._checkpointOpen?a:"",o]);if(i&&!t&&l===this._checkpointDrawn)return;let c=document.activeElement,d=i&&c&&i.contains(c)?c.getAttribute("data-checkpoint-action"):null,h=$h({kind:n,count:this._contextSummary?.count,reason:r,open:this._checkpointOpen,confirming:this._confirmingRestore,summaryId:this._checkpointId,locale:this._cfg.getLocale()});if(this._checkpointOpen&&(n==="done"||n==="legacy")){let p=h.querySelector(".aparte-checkpoint__summary");p&&(p.innerHTML=this._cfg.renderMarkdown(a))}i&&i.hasAttribute("data-below")===o?i.replaceWith(h):(i?.remove(),o?this.append(h):this.prepend(h)),h.toggleAttribute("data-below",o),this._checkpointDrawn=l;let u=t??d;u&&h.querySelector(`[data-checkpoint-action="${nt(u)}"]`)?.focus()}_onCheckpointClick=t=>{let e=t.target?.closest?.("[data-checkpoint-action]"),n=e?.closest(".aparte-checkpoint");if(!(!e||!n||n.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;Bh(this,{messageId:i,targetId:this._resolveTargetId()}),this.setContextSummary(null);break}case"retry":{let i=this._resolveTargetId(),r=this._cfg.getCompactor();r?r.compact({target:bt(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=ht(this._cfg));let e=Rt(t.type,this._cfg);if(e){let n=this._drawnAs(t,!0),i=ye(Y(this._cfg,()=>e.render(t)),t);i&&(this._segmentsEl.appendChild(i),this._install(t,i,e,n))}else{let n=_i(t);this._segmentsEl.appendChild(n),this._install(t,n,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 n=document.createElement("span");n.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(n,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(),n=e?Mh(this._segments,c=>this._turnRole(c)):[];if(n.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(n.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 y=r(_);y&&(g=i(f,y,g))}this._labelTurn(p,h,d.to===this._segments.length-1,e??{}),c=d.to}for(let c of t.querySelectorAll(":scope > .aparte-turn"))a.has(c)||c.remove()}_labelTurn(t,e,n,i){let r=this._cfg,a=e.filter(p=>this._turnRole(p)==="fold"),o=a.filter(p=>p.type==="tool_call"),l=this._streaming&&n||o.some(p=>!It(p)),c=t.querySelector(":scope > summary > .aparte-turn__label"),d=t.querySelector(":scope > summary > .aparte-turn__current");c.classList.toggle("aparte-shimmer",l);let h;try{h=i.label?.(a,{running:l,config:r})}catch(p){console.error("[aparte] the turn summary label threw; core's line is shown instead.",p)}c.textContent=h??(l?r.t("turnWorking"):this._turnOutcome(a,o.length)),c.toggleAttribute("aria-live",!1),i.label&&c.setAttribute("aria-live","polite");let u=o.filter(p=>!p.queued&&p.deferred?.reason!=="queued").at(-1)??o.at(-1);d.textContent=h==null&&l&&u?this._stepName(u):"",i.openWhileRunning===!0&&!("touched"in t.dataset)&&(t.open=l)}_turnOutcome(t,e){let n=this._cfg,i=n.getLocale().tag||void 0,r=e>0?Io(n.t("turnTools"),e,i):"",a=Ih(t);if(a!==void 0){let o=n.t("turnWorked").replace("{duration}",()=>Qs(a,i));return r?`${o} \xB7 ${r}`:o}return r?n.t("turnUsed").replace("{tools}",()=>r):n.t("thought")}_stepName(t){return ln(t,this._cfg).text}_applySegmentUpdate(t,e,n){let i=this._segmentsEl?fn(this._segmentsEl,t):null;if(!i){this._renderSegments();return}if(this._releasedWhileDetached)return;let r=Rt(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){Y(this._cfg,()=>r.update(i,e));let o=this._drawn.get(t);if(o){o.segment=e;let l=this._segmentsEl?fn(this._segmentsEl,t):null;l&&l!==o.el&&(o.el=l,o.tool=Ho(e,l))}}else{let o=ye(Y(this._cfg,()=>r.render(e)),e);o&&(this._release(t),i.replaceWith(o),this._install(e,o,r))}"collapsed"in n&&(n.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 n=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=Y(this._cfg,()=>r({role:this._role,name:n,avatarInitial:i}));o instanceof HTMLElement?this.replaceChildren(o):this.innerHTML=o}else this.innerHTML=`
93
+ <div class="aparte-message" data-role="${L(e)}" role="article" aria-label="${L(this._getAriaLabel())}">
94
+ <div class="aparte-avatar" data-role="${L(e)}"></div>
95
+ <div class="aparte-body">
96
+ <div class="aparte-header">
97
+ <span class="aparte-name">${P(n)}</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="${L(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="${L(this._cfg.getLocale().nextResponse??"Next response")}">${this._cfg.getIcon("nextBranch")}</button>
122
+ </div>
123
+ <div class="aparte-action-bar" role="toolbar" aria-label="${L(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(),n=this._segments.at(-1),i=this._segmentsEl?.lastElementChild,r=n?.type==="tool_call"&&n.status==="awaiting-approval",a=n?.type==="tool_call"&&(It(n)||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 n=e.render(this._role,t);this._avatarFromProvider=!0,typeof n=="function"&&(this._avatarCleanup=n),this._markAvatarImage(t)}_markAvatarImage(t){if(t.firstChild){Ce.delete(t),t.removeAttribute("data-image");return}Ce.size===0&&queueMicrotask(qh),Ce.set(t,{bubble:this,role:this._role})}_updateRole(){let t=this.querySelector(".aparte-message"),e=this.querySelector(".aparte-avatar"),n=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())),n&&(n.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 n=this.querySelector(".aparte-message");this._wroteRootLabel&&n?.getAttribute("role")==="article"&&n.setAttribute("aria-label",this._getAriaLabel())}_updateContent(){if(this._contentEl){if(this._segments.length>0){this._contentEl.style.display="none",this._updateWaiting();return}this._drawnWithVersion=ht(this._cfg),this._contentEl.style.display="",Y(this._cfg,()=>Xt(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)?Ys(r,o):t.innerHTML=o)}).catch(()=>{t.removeAttribute("data-aparte-highlighted")})})}_renderSegments(){if(this._segmentsEl){this._drawnWithVersion=ht(this._cfg),this._releaseAll(),this._segmentsEl.innerHTML="";for(let t of this._segments){let e=Rt(t.type,this._cfg);if(e){let n=this._drawnAs(t),i=ye(Y(this._cfg,()=>e.render(t)),t);i&&(this._segmentsEl.appendChild(i),this._install(t,i,e,n))}else{let n=_i(t);this._segmentsEl.appendChild(n),this._install(t,n,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(n=>n.type==="error")?t.setAttribute("data-error",""):t.removeAttribute("data-error")}_updateTimestamp(t){let e=this.querySelector(".aparte-timestamp");if(!(!e||!t))try{let n=new Date(isNaN(Number(t))?t:Number(t));e.textContent=n.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=ye(Y(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:n}=this._cfg.getHostHandlers(),i=[e?".aparte-thumb--image":"",n?".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&&st(this,"aparte-attachment-preview",{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?be(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 n=t.target?.closest?.(".aparte-branch-prev, .aparte-branch-next");if(!n||!this.contains(n))return;let i=n.classList.contains("aparte-branch-prev")?"prev":"next",r=this.getAttribute("message-id");if(!r)return;st(this,"aparte-branch-navigate",{messageId:r,direction:i})};_onLinkClick=t=>{let n=t.target?.closest?.("a[href]");if(!n||!this.contains(n))return;let i={href:n.getAttribute("href")??"",anchor:n,messageId:this.getAttribute("message-id")};st(this,"aparte-link-click",i,{cancelable:!0})||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=Y(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 n=this._branchPickerEl.querySelector(".aparte-branch-prev"),i=this._branchPickerEl.querySelector(".aparte-branch-next");n&&(n.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(),n=this._cfg.getLocale(),i=[];if(this._role==="user")if(t.user)for(let r of t.user)i.push(this._actionButtonHtml(r,e,n));else t.copy&&i.push(this._actionButtonHtml("copy",e,n)),t.edit&&i.push(this._actionButtonHtml("edit",e,n));else if(this._role==="assistant")if(t.assistant)for(let r of t.assistant)i.push(this._actionButtonHtml(r,e,n));else t.copy&&i.push(this._actionButtonHtml("copy",e,n)),t.retry&&i.push(this._actionButtonHtml("retry",e,n)),t.feedback&&(i.push(this._actionButtonHtml("thumbUp",e,n)),i.push(this._actionButtonHtml("thumbDown",e,n))),t.info&&i.push(this._actionButtonHtml("info",e,n));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)return;let t=this._cfg.getLocale(),e=[];for(let n of this._cfg.getActions("bubble")){if(!(n.bubble?.roles??["user","assistant"]).includes(this._role))continue;let r=Object.hasOwn(t,n.label)?t[n.label]:void 0,a=typeof r=="string"?r:n.label,o=n.display==="label"||!n.icon?"":n.icon.startsWith("<")?n.icon:this._cfg.getIcon(n.icon)??n.iconFallback??"",l=n.display==="label"||n.display==="both"||o==="",c=document.createElement("button");c.type="button",c.className="aparte-btn aparte-btn--sm aparte-action-btn aparte-action-custom",l||c.classList.add("aparte-btn--icon"),c.dataset.action=`custom:${n.id}`,c.innerHTML=o,l?c.append(a):(c.setAttribute("aria-label",a),c.setAttribute("title",a)),n.position==="start"?e.push(c):this._actionBarEl.appendChild(c)}this._actionBarEl.prepend(...e)}_actionButtonHtml(t,e,n){switch(t){case"copy":{let i=n.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="${L(i)}" title="${L(i)}">${e.copy()}</button>`}case"edit":{let i=n.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="${L(i)}" title="${L(i)}">${e.edit()}</button>`}case"retry":{let i=n.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="${L(i)}" title="${L(i)}">${e.retry()}</button>`}case"thumbUp":{let i=n.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="${L(i)}" title="${L(i)}">${e.thumbUp()}</button>`}case"thumbDown":{let i=n.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="${L(i)}" title="${L(i)}">${e.thumbDown()}</button>`}case"info":{if(!this._usage)return"";let i=n.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="${L(i)}" title="${L(i)}">${this._cfg.getIcon("info")}</button>`}default:return""}}_renderEditActions(){if(!this._actionBarEl)return;let t=this._cfg.getLocale(),e=t.editConfirm??"Save",n=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="${L(e)}" title="${L(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="${L(n)}" title="${L(n)}">${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,n=e.dataset.action,i=this.getAttribute("message-id");if(n?.startsWith("custom:")&&i){let r=n.slice(7),a={actionId:r,zone:"bubble",messageId:i,role:this._role,targetId:this._resolveTargetId()};st(this,"aparte-action",a),this._cfg.getActions("bubble").find(o=>o.id===r)?.onClick?.(t);return}switch(n){case"copy":{let r=this._copyableText(),a=this._cfg.getIconProvider(),o=this._cfg.getLocale();Xs(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=n==="feedback-positive"?"positive":"negative";e.setAttribute("data-submitted",""),st(this,"aparte-feedback",{messageId:i,value:r}),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};st(this,"aparte-message-info",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",n=>{n.key==="Escape"&&!n.isComposing&&(n.preventDefault(),this._exitEditMode(!1))}),this._updateActionBar(),e.focusEnd()}_exitEditMode(t){if(!this._editing)return;let e=this._editInput?.getValue()??"",n=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!==n){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(){return yt(this)}_updateStreaming(t){let e=this._streaming;this._streaming=t,t||(this._step=null);let n=this.querySelector(".aparte-message");n&&(n.setAttribute("data-streaming",String(t)),t?(n.setAttribute("aria-busy","true"),n.classList.add("aparte-message-streaming")):(n.removeAttribute("aria-busy"),n.classList.remove("aparte-message-streaming")),n.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(Sn);customElements.get("aparte-chat-bubble")||customElements.define("aparte-chat-bubble",Sn);var Cn=class extends HTMLElement{static get observedAttributes(){return["visible","text"]}get _cfg(){return I(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,n){if(e!==n)switch(t){case"visible":this._updateVisibility(n!==null);break;case"text":this._updateText(n);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 n=this._cfg?.getStatusRenderer?.();if(n){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=Y(this._cfg,()=>n(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,n=this.querySelector(".aparte-status-text");n&&(n.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 n=this._cfg?.getStatusRenderer?.();if(n){let i=t||this._word();e.setAttribute("aria-label",i);let r=Y(this._cfg,()=>n(i));r instanceof HTMLElement?e.replaceChildren(r):e.innerHTML=r;return}this._writeText(t),e.setAttribute("aria-label",t||this._word())}};G(Cn);customElements.get("aparte-chat-status")||customElements.define("aparte-chat-status",Cn);function Fo(s,t){if(s.role!=="assistant"||s.segments?.length||typeof s.content!="string"||!s.content.trim())return s;let e=Jr(s.content,{blocks:t});return e.length<=1&&e.every(i=>i.type==="text")?s:Si({...s,segments:e})}function Si(s){return Object.defineProperty(s,ci,{value:!0,enumerable:!1}),s}function Wo(s){return s[ci]===!0}function Wh(s,t){try{return new Intl.DateTimeFormat(t||void 0,{dateStyle:"long"}).format(s)}catch{return s.toDateString()}}var kn=class extends HTMLElement{_container=null;_scrollBtn=null;_bottomSpacer=null;_fwSpacerHeight=0;_spacerRafId=null;_spacerFrozenUntil=0;_layoutTransitionMs=0;_repo=new nn;_isAutoScrollEnabled=!0;_lastScrollTop=0;_lastScrollHeight=0;_lastMutationAt=Number.NEGATIVE_INFINITY;_settleShadowMs=100;_settleBoundPx=100;_ownScrollAt=Number.NEGATIVE_INFINITY;_readerInputAt=Number.NEGATIVE_INFINITY;_ownScrollWindowMs=1e3;_settleWindowMs=400;_glideUntil=0;_glideWindowMs=450;_glideSettleTimer=null;_settleUntil=0;_settleRafId=null;_scrollKeys=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," "]);_scrollThreshold=50;_smoothScrollOnce=!1;_maxRenderedBubbles=1e3;_resizeObserver=null;_mutationObserver=null;_tailObserver=null;_tail=[];_tailHeights=new WeakMap;_onDisclosureToggle=()=>{this._scheduleSpacerUpdate()};_overlayRoot=null;_overlayObserver=null;_overlayAttrObserver=null;_overlayInset=-1;_transcriptInset=-1;_boundResetHandler=null;_checkpointState=null;_stopCheckpointState=null;_frameworkManagedDOM=!1;_bulkAppend=!1;static get observedAttributes(){return["scroll-threshold","max-rendered-bubbles","loading"]}get loading(){return this.hasAttribute("loading")}set loading(t){this.toggleAttribute("loading",Z(t))}setLoading(t){this.loading=t}_syncLoading(){let t=this._container;if(!t)return;let e=this.hasAttribute("loading");if(t.setAttribute("aria-busy",e?"true":"false"),this._frameworkManagedDOM)return;let n=t.querySelector(":scope > .aparte-viewport-loading");if(!e){n?.remove(),t.querySelector(":scope > .aparte-viewport-loading-status")?.remove();return}if(n)return;let i=I(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 Ze({ownId:()=>yt(this)??(this.id||void 0),bubbleOf:t=>this.querySelector(`aparte-chat-bubble[message-id="${nt(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!==I(this))return;this._applyDirection(),this._scrollBtn?.setAttribute("aria-label",I(this).t("scrollToBottom")),(this._frameworkManagedDOM?this:this.querySelector(".aparte-viewport-container"))?.setAttribute("aria-label",I(this).t("transcript")),this._syncDateSeparators()};_nameScrollSurface(t){t.setAttribute("tabindex","0"),t.hasAttribute("role")||t.setAttribute("role","log"),t.setAttribute("aria-label",I(this).t("transcript"))}_applyDirection(){let t=this._frameworkManagedDOM?this:this.querySelector(".aparte-viewport-container");if(!t)return;let e=I(this).getLocale().direction;e?t.setAttribute("dir",e):t.removeAttribute("dir")}disconnectedCallback(){this._chatId=void 0,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,n){if(e!==n)switch(t){case"scroll-threshold":this._scrollThreshold=parseInt(n||"50",10);break;case"max-rendered-bubbles":this._maxRenderedBubbles=parseInt(n||"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 n=this._getOrCreateMessage(t);n.content=(n.content||"")+e,this._notifyBubble(t,"appendToken",e),this._autoScroll(),this._scheduleSpacerUpdate()}appendToSegment(t,e,n){let i=this._getOrCreateMessage(t);i.segments||(i.segments=[]);let r=i.segments.findIndex(c=>c.id===e),a=r===-1?void 0:i.segments[r];a&&"content"in a&&(i.segments[r]={...a,content:a.content+n,...ea(a)});let o=this._chatIdOnce(),l=o===void 0?{messageId:t,segmentId:e,content:n,append:!0}:{messageId:t,segmentId:e,content:n,append:!0,targetId:o};this.dispatchEvent(new CustomEvent("aparte-segment-update",{bubbles:!0,composed:!0,detail:l})),this._notifyBubble(t,"appendToSegment",n,e),this._autoScroll()}_chatId;_chatIdOnce(){return this._chatId??=yt(this)}_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 n of this._repo.getAllMessages())if(n.isStreaming){if(n.id!==t)return n.id;e=n.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 n=typeof t=="string"?t:this._activeMessageId(),i=typeof t=="string"?e:t;if(!n||!i)return;let r=this._getOrCreateMessage(n);r.segments||(r.segments=[]);let a=Hs(r.segments,i,n,I(this).getSegmentDefaults(i.type));r.segments.push(a),this._notifyBubble(n,"addSegment",a),this._autoScroll()}updateSegment(t,e,n){let i=n===void 0&&typeof e=="object",r=i?this._activeMessageId():t,a=i?t:e,o=i?e:n;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=Zr(d,o);l.segments[c]=qs(d,h),this._notifyBubble(r,"updateSegment",{segmentId:a,updates:h})}}removeSegment(t,e){let n=e===void 0,i=n?this._activeMessageId():t,r=n?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),sa(a.segments))}this._notifyBubble(i,"removeSegment",r)}startSegment(t,e){let n={...e,isStreaming:!0};this.addSegment(t,n)}completeSegment(t,e){this.updateSegment(t,e,{isStreaming:!1})}setUsage(t,e){let n=this._repo.getMessageById(t);n&&(n.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 n of na(e.segments))this.updateSegment(t,n,{isStreaming:!1})}updateMessage(t,e){let n=this._repo.getMessageById(t);n&&(Object.assign(n,e),e.status&&(n.isStreaming=e.status==="streaming"||e.status==="pending",Fs(e.status)&&this._settleSegments(t,n)),this._notifyBubble(t,"update",e),e.status&&this._syncBusy(),this._autoScroll())}addMessage(t){let e=an({...t});Zt(t)&&(e.isStreaming=!0),this._repo.addOrUpdateMessage(this._repo.headId,e),this._pruneRenderedBubbles(),this._syncBusy(),this._autoScroll()}appendMessage(t,e){t=Fo(t,I(this).getStreamBlocks());let n=e?.historical?an(t):t.segments?.length?{...t,segments:t.segments.reduce((i,r)=>(i.push(Hs(i,r,t.id,I(this).getSegmentDefaults(r.type))),i),[])}:{...t};if(!e?.historical&&Zt(t)&&(n.isStreaming=!0),Wo(t)&&Si(n),this._repo.addOrUpdateMessage(this._repo.headId,n),!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),Zt(t)&&r.setAttribute("streaming",""),this._bottomSpacer&&this._bottomSpacer.parentNode===i?i.insertBefore(r,this._bottomSpacer):i.appendChild(r),li(r,n)}}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 n=this._repo.headId;if(n)if(e?.append)this.appendToken(n,t);else{let i=this._repo.getMessageById(n);i&&(i.content=t),this._notifyBubble(n,"appendToken",t)}}addBranch(t){let e=this._repo.getMessage(t);if(!e)return 0;let n={id:J(),role:"assistant",content:"",status:"pending",timestamp:Date.now()};return this._repo.addOrUpdateMessage(e.parentId,n),this._repo.switchToBranch(n.id),this._reRenderActivePath(),this._repo.getBranches(n.id).indexOf(n.id)}addSiblingOf(t,e){let n=this._repo.getMessage(t);if(!n)return null;let i=n.message.role==="user"?t:n.parentId,r={...e};return Zt(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 n=this._repo.getBranches(t),i=n.indexOf(t);if(i===-1)return;let r=e==="prev"?i-1:i+1;r<0||r>=n.length||(this._isAutoScrollEnabled=this._isAtBottom(),this._updateScrollButton(),this._repo.switchToBranch(n[r]),this._reRenderActivePath())}truncateResponsesAfter(t){let e=this._repo.getMessages();if(this._repo.clearChildren(t),!this._frameworkManagedDOM){let n=this.querySelector(".aparte-messages-wrapper");if(n){let i=e.findIndex(a=>a.id===t),r=i>=0?e.slice(i+1):[];for(let a of r)n.querySelector(`aparte-chat-bubble[message-id="${nt(a.id)}"]`)?.remove()}}}truncateFrom(t){let e=this._repo.getMessages(),n=e.findIndex(r=>r.id===t);if(n===-1)return;let i=e.slice(n).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="${nt(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=I(this).getStreamBlocks();this._repo.import({...t,messages:t.messages.map(n=>{let i=Fo(n.message,e),r=an(i);return Wo(i)&&Si(r),{...n,message:r}})}),this._reRenderActivePath()}clearAll(t){if(t?.revokeAttachments!==!1)for(let e of this._repo.getAllMessages())fo(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(n=>n.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 n={id:t,role:"assistant",content:"",timestamp:Date.now(),isStreaming:!0,status:"streaming"};return this._repo.addOrUpdateMessage(this._repo.headId,n),n}_notifyBubble(t,e,n,i){let r=this.querySelector(`aparte-chat-bubble[message-id="${nt(t)}"], [data-aparte-bubble][message-id="${nt(t)}"]`);if(r)switch(e){case"appendToken":r.appendToken?.(n);break;case"appendToSegment":r.appendToSegment?.(i,n);break;case"addSegment":r.addSegment?.(n);break;case"updateSegment":{let{segmentId:a,updates:o}=n;r.updateSegment?.(a,o);break}case"removeSegment":r.removeSegment?.(n);break;case"setUsage":r.setUsage?.(n);break;case"setStep":r.setStep?.(n);break;case"update":{let a=n;["status","segments","content","attachments","usage","finishReason","contextSummary","compaction"].some(l=>l in a)&&r.updateMessage?.(n);break}case"complete":r.updateMessage?.(n);break}}_syncDateSeparators(){let t=I(this),e=t.getDateSeparators();if(!e&&!this.querySelector("aparte-chat-bubble[data-date]"))return;let n=new Date,i=o=>new Date(o.getFullYear(),o.getMonth(),o.getDate()).getTime(),r=i(n),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"):Wh(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 n=this.querySelector(".aparte-messages-wrapper");if(!n)return;n.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)),Zt(a)&&l.setAttribute("streaming",""),n.appendChild(l),li(l,a,o)}this._syncDateSeparators(),this._dispatchPathChanged(t,e),this._syncBusy(),this._checkpointState?.reapply(),this._recalculateSpacer()}_dispatchPathChanged(t,e){st(this,"aparte-path-changed",{messages:t,siblings:e})}_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=I(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 n=document.createElement("div");for(n.className="aparte-messages-wrapper";this.firstChild;)n.appendChild(this.firstChild);this._bottomSpacer=document.createElement("div"),this._bottomSpacer.className="aparte-bottom-spacer",this._bottomSpacer.setAttribute("aria-hidden","true"),n.appendChild(this._bottomSpacer),t.appendChild(n),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",I(this).t("scrollToBottom"));let i=I(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",I(this).t("scrollToBottom"));let e=I(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:n}=t,i=e.getBoundingClientRect();if(!(getComputedStyle(e).direction==="rtl"?n<=i.right-e.clientWidth:n>=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(n=>{if(this._lastMutationAt=performance.now(),n.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=n.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));n.some(r=>i(r.addedNodes)||i(r.removedNodes))&&this._observeTail()}),this._tailObserver=new ResizeObserver(n=>{let i=!1;for(let r of n){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 n=e===1/0?0:Math.max(0,Math.round(t-e));n!==this._overlayInset&&(this._overlayInset=n,this.style.setProperty("--aparte-bottom-inset",`${n}px`))}_updateTranscriptInset(){let t=this.parentElement;if(!t)return;let e=this.querySelector(".aparte-messages-wrapper")??this._container??this,n=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+n)*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:n}=this._container;return e-t-n<=this._scrollThreshold}_handleScroll(){if(!this._container)return;let t=this._container.scrollTop,e=this._container.scrollHeight,n=this._lastScrollTop-t,i=Math.abs(e-this._lastScrollHeight),r=performance.now(),a=e<this._lastScrollHeight-1,o=r-this._lastMutationAt<this._settleShadowMs&&n<=this._settleBoundPx,l=r-this._ownScrollAt<this._ownScrollWindowMs&&r-this._readerInputAt>=this._ownScrollWindowMs&&!this._pointerHeld&&(n<=i+2||a||o),c=n>1&&!l,d=n>1&&r-this._readerInputAt<this._ownScrollWindowMs;this._lastScrollTop=t,this._lastScrollHeight=e,this._isAtBottom()&&!d?this._isAutoScrollEnabled=!0:c?this._isAutoScrollEnabled=!1:n>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 n=this._getSpacerHeight(),i=this._container.getBoundingClientRect(),a=e.getBoundingClientRect().top-i.top+this._container.scrollTop,o=this._container.scrollHeight-n;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 n=e>0?t.slice(e-1):[];for(let i of this._tail)n.includes(i)||this._tailObserver.unobserve(i);for(let i of n)this._tail.includes(i)||(this._tailHeights.set(i,Math.round(i.offsetHeight)),this._tailObserver.observe(i,{box:"border-box"}));this._tail=n}_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"),n=e.length-this._maxRenderedBubbles;for(let i=0;i<n;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(kn);customElements.get("aparte-chat-viewport")||customElements.define("aparte-chat-viewport",kn);var Uh=["input","textarea","select",'[contenteditable]:not([contenteditable="false"])','[role="textbox"]','[role="searchbox"]','[role="combobox"]','[role="listbox"]','[role="menu"]','[role="menubar"]','[role="tree"]','[role="grid"]'].join(", "),jh="aparte-chat, [data-aparte-chat]";function zh(s){let t=s.getAttribute("type-to-focus");return t==="page"||t==="off"?t:"chat"}function Gh(s){if(s.defaultPrevented||s.isComposing)return!1;let t=s.getModifierState?.("AltGraph")===!0;return(s.ctrlKey||s.metaKey||s.altKey)&&!t?!1:s.key==="Dead"?!0:s.key.length===1&&s.key!==" "}function Kh(s){let t=s.activeElement;for(;t?.shadowRoot?.activeElement;)t=t.shadowRoot.activeElement;return t}function Vh(s){let t=s.ownerDocument,e=!1,n=()=>{let a=s.getAttribute("target"),o=s.closest(jh)??(a?t.getElementById(a):null);return o?[o,s]:[s]},i=a=>{let o=a.composedPath();e=n().some(l=>o.includes(l))},r=a=>{let o=zh(s);if(o==="off"||!Gh(a)||s.hasAttribute("disabled"))return;let l=s.querySelector("aparte-composer-input");if(!l||l.hasAttribute("disabled"))return;let c=Kh(t);if(!c?.closest(Uh)){if(o==="chat"){let d=!c||c===t.body||c===t.documentElement;if(!(!d&&n().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 Yh=new Set(["text","search","email","url","tel","number","password"]);function Qh(s){return s instanceof HTMLTextAreaElement?s.rows===1:s instanceof HTMLInputElement&&Yh.has(s.type)}var Xh=0,En=class s 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","queue-change"]);_queue=[];_queueIdBase=`aparte-queued-${++Xh}`;_onMessageStart=this._handleMessageStart.bind(this);_onMessageDone=this._handleMessageDone.bind(this);get _cfg(){return I(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??I(this)).getLocale().direction;t?this.setAttribute("dir",t):this.removeAttribute("dir")}static get observedAttributes(){return["placeholder","disabled","target","stop-label"]}_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=Vh(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,n){if(e!==n&&(t==="disabled"&&this._emit("disabled-change",{disabled:n!==null}),t==="stop-label"&&this._emit("stop-label-change",{stopLabel:this.stopLabel}),t==="placeholder"))for(let i of this.querySelectorAll("aparte-composer-input"))i.syncPlaceholder?.()}get value(){return this._value}get streaming(){return this._streaming}get disabled(){return this.hasAttribute("disabled")}set disabled(t){this.toggleAttribute("disabled",Z(t))}get submitOnEnter(){return this.getAttribute("submit-on-enter")!=="false"}get attachments(){return this._attachments}get placeholder(){return this.getAttribute("placeholder")??""}set placeholder(t){t==null?this.removeAttribute("placeholder"):this.setAttribute("placeholder",String(t))}get targetId(){return this.getAttribute("target")}getState(){return{value:this._value,streaming:this._streaming,disabled:this.disabled,attachments:[...this._attachments],panelActive:this._panelActive,submitEnabled:this._panelSubmitEnabled,queued:this.queued}}get stopLabel(){let t=this.getAttribute("stop-label");return t?.trim()?t:null}set stopLabel(t){t?.trim()?this.setAttribute("stop-label",t):this.removeAttribute("stop-label")}get queued(){return this._queue.map(t=>({...t}))}get queueWhileStreaming(){return this._cfg.getQueueWhileStreaming()}queue(){if(this._panelActive)return;if(!this._streaming){this.submit();return}let t=this._value.trim();if(!t&&this._attachments.length===0||this.disabled)return;let e=this.querySelector("aparte-composer-input")?.getTokens?.();this._queue.push({content:t,...this._attachments.length>0?{files:[...this._attachments]}:{},...e?.length?{tokens:e}:{}}),this.setValue(""),this.clearAttachments(),this._queueChanged()}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 n=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),n?n.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||!Qh(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),n=this.querySelector("[data-aparte-panel]");n&&n.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;let e=this.querySelector("aparte-composer-input")?.getTokens?.();this._send({content:t,...this._attachments.length>0?{files:[...this._attachments]}:{},...e?.length?{tokens:e}:{}})&&(this.setValue(""),this.clearAttachments())}_send(t){let e={content:t.content,timestamp:Date.now(),targetId:this._ownTargetId(),files:t.files?.length?[...t.files]:void 0,...t.tokens?.length?{tokens:t.tokens}:{}};return st(this,"aparte-before-send",e,{cancelable:!0})?(this._emit("submit",{value:t.content,attachments:t.files??[]}),this.dispatchEvent(new CustomEvent("aparte-send",{bubbles:!0,composed:!0,detail:e})),!0):!1}_sendNextQueued(){if(this._streaming||this._queue.length===0||!this.isConnected)return;let t=this._queue.shift();this._queueChanged(),(this.disabled||this._modelGated||!this._send(t))&&this._backToField([t])}_backToField(t){if(t.length===0)return;let e=[...t.map(i=>i.content),this._value.trim()].filter(Boolean).join(`
147
+
148
+ `);this.setValue(e);let n=t.flatMap(i=>i.files??[]);n.length>0&&this.addAttachments(n)}_queueChanged(){this._emit("queue-change",{queued:this.queued}),this._drawQueue()}_drawQueue(){let t=this.querySelector(":scope .aparte-composer-queue");if(!t){if(this._queue.length===0)return;t=document.createElement("div"),t.className="aparte-composer-queue",t.setAttribute("role","group");let o=this.querySelector(".aparte-composer-row");o?.parentElement?o.parentElement.insertBefore(t,o):this.prepend(t)}let e=this._cfg,n=e.t("queueLabel")||"Sent when the reply ends";t.setAttribute("aria-label",n),t.hidden=this._queue.length===0;let i=document.createElement("div");i.className="aparte-composer-queue__label",i.textContent=n;let r=document.createElement("ul");r.className="aparte-composer-queue__list";let a=this._queueIdBase;this._queue.forEach((o,l)=>{let c=document.createElement("li");c.className="aparte-composer-queue__item";let d=document.createElement("span");d.className="aparte-composer-queue__text",d.id=`${a}-${l}`,d.textContent=o.content||(o.files??[]).map(h=>h.name).join(", "),c.append(d,this._queueButton("edit",e.t("queueEdit")||"Edit",d.id,l),this._queueButton("trash",e.t("queueRemove")||"Remove",d.id,l)),r.append(c)}),t.replaceChildren(i,r)}_queueButton(t,e,n,i){let r=document.createElement("button");r.type="button";let a=t==="trash"?"aparte-composer-queue__remove":"aparte-composer-queue__edit";return r.classList.add("aparte-btn","aparte-btn--icon","aparte-btn--sm","aparte-btn--ghost",a),r.innerHTML=this._cfg.getIcon(t),r.setAttribute("aria-label",e),r.setAttribute("title",e),r.setAttribute("aria-describedby",n),r.addEventListener("click",()=>{let[o]=this._queue.splice(i,1);this._queueChanged(),t==="edit"&&o&&(this._backToField([o]),this.focus())}),r}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(n=>n(e)),s._STATE_EVENTS.has(t)&&st(this,"aparte-composer-change",{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(){return yt(this)}_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){if(!(!this._isForThisComposer(t)||!this._isForThisTurn(t))&&(this._streamingMessageId=null,this._streaming=!1,this._emit("streaming-change",{streaming:!1}),this._panelActive&&this._evictPanel(),this._queue.length!==0))if(t.type==="aparte-message-done")setTimeout(()=>this._sendNextQueued(),0);else{let e=this._queue.splice(0);this._queueChanged(),this._backToField(e)}}};G(En);customElements.get("aparte-composer")||customElements.define("aparte-composer",En);function al(s,t){let e=(s??"").split(",").map(r=>r.trim().toLowerCase()).filter(Boolean);if(e.length===0)return!0;let n=t.name.toLowerCase(),i=t.type.toLowerCase();return e.some(r=>r.startsWith(".")?n.endsWith(r):r.endsWith("/*")?i.startsWith(r.slice(0,-1)):i===r)}var ki="data-aparte-token",ol="data-aparte-text",Jh="\uFFFC",ke=s=>s.nodeType===Node.TEXT_NODE,Zh=s=>s.nodeType===Node.ELEMENT_NODE&&s.hasAttribute(ki),ll=s=>Array.prototype.indexOf.call(s.parentNode.childNodes,s);function Ee(s,t=[]){return s.childNodes.forEach(e=>{ke(e)||e.nodeName==="BR"||Zh(e)?t.push(e):Ee(e,t)}),t}var cl=s=>ke(s)?s.data.length:1;function tp(s){return Ee(s).map(t=>ke(t)?t.data:t.nodeName==="BR"?`
149
+ `:Jh).join("")}function ep(s,t,e){let n=s.ownerDocument.createRange();n.setStart(t,e),n.collapse(!0);let i=0;for(let r of Ee(s)){if(r===t)return i+e;if(n.comparePoint(r.parentNode,ll(r))>=0)return i;i+=cl(r)}return i}function Uo(s,t){let e=t;for(let n of Ee(s)){if(ke(n)&&e<=n.data.length)return[n,e];if(e===0)return[n.parentNode,ll(n)];e-=cl(n)}return[s,s.childNodes.length]}function jo(s,t,e){let n=s.ownerDocument.createRange();return n.setStart(...Uo(s,t)),n.setEnd(...Uo(s,e)),n}function zo(s,t,e){let n=s.createElement("span");n.className="aparte-tag aparte-inline-token",n.setAttribute("contenteditable","false"),n.setAttribute(ki,t),n.setAttribute(ol,e.text??e.label),e.kind&&(n.dataset.kind=e.kind);let i=s.createElement("span");return i.className="aparte-tag__label",i.textContent=e.label,n.appendChild(i),n}function Go(s,t){let e="",n=[];for(let r of Ee(s))if(ke(r))e+=r.data;else if(r.nodeName==="BR")e+=`
150
+ `;else{let a=r,o=t.get(a.getAttribute(ki)??""),l=a.getAttribute(ol)??a.textContent??"",c=e.length;e+=l,n.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:n.map(r=>({...r,start:r.start-i,end:r.end-i}))}}var Tn=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(Lt(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,n){e!==n&&(t==="placeholder"&&this._updatePlaceholder(),t==="max-height"&&(this._maxHeight=parseInt(n||"200",10)),t==="min-height"&&(this._minHeight=parseInt(n||"44",10)),t==="disabled"&&this._updateDisabled(n!==null))}getValue(){return this._editor?Go(this._editor,this._tokens).value:""}getTokens(){return this._editor?Go(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:tp(this._editor),offset:ep(this._editor,t.anchorNode,t.anchorOffset)}}getRangeRect(t,e=t){return this._editor?jo(this._editor,t,e).getClientRects?.()[0]??null:null}replaceRange(t,e,n){this._write(t,e,()=>n?this._insertPlain(n):this._exec("delete"),()=>this.ownerDocument.createTextNode(n))}insertToken(t,e,n){let i=String(++this._lastTokenId);this._tokens.set(i,n);let r=this.ownerDocument,a=()=>{let o=r.createDocumentFragment();return o.append(zo(r,i,n),r.createTextNode(" ")),o};this._write(t,e,()=>this._exec("insertHTML",`${zo(r,i,n).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,n,i){let r=this._editor,a=this.ownerDocument?.getSelection();if(!r||!a)return;r.focus();let o=jo(r,t,e);if(a.removeAllRanges(),a.addRange(o),n())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||I(this).t("inputPlaceholder")||"Type a message..."}_render(){if(this.querySelector(".aparte-ci-editor"))return;let t=this.hasAttribute("disabled")||this._getRoot()?.disabled||!1,e=L(this._getPlaceholder());this.innerHTML=`<div
151
+ class="aparte-ci-editor"
152
+ contenteditable="${!t}"
153
+ role="textbox"
154
+ aria-multiline="true"
155
+ aria-label="${e}"
156
+ tabindex="${L(String(t?-1:0))}"
157
+ aria-disabled="${t}"
158
+ data-placeholder="${e}"
159
+ ></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){i.queueWhileStreaming&&i.queue();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 n=this._getRoot(),i=n?.querySelector("aparte-composer-add-attachment"),r=i?Array.from(e.items).find(o=>o.type.startsWith("image/"))?.getAsFile():void 0;if(r&&al(i?.getAttribute("accept"),r)){n?.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,n=Math.min(Math.max(e,t),this._maxHeight);this._editor.style.height=`${n}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(Tn);customElements.get("aparte-composer-input")||customElements.define("aparte-composer-input",Tn);var xn=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=I(this).t("sendButton")||"Send",e=this._getSendIcon(),n=this._getRoot(),i=!n||n.disabled||n.value.trim()==="";this.innerHTML=`<button
160
+ type="button"
161
+ class="aparte-btn aparte-btn--primary aparte-btn--solid aparte-btn--icon aparte-cs-button aparte-send-button"
162
+ aria-label="${L(t)}"
163
+ title="${L(t)}"
164
+ data-act="send"
165
+ ${i?"disabled":""}
166
+ >${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(t._on("stop-label-change",()=>this._refreshChrome())),this._unsubscribes.push(Lt(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=I(this);if(t.mode==="none"){this._button.disabled=!0;return}this._button.disabled=!t.submitEnabled,this._button.innerHTML=this._getSubmitIcon(),this._setAct("submit");let n=e.t("submitButton")||"Submit";this._button.setAttribute("aria-label",n),this._button.setAttribute("title",n),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 n=I(this).t("sendButton")||"Send";this._button.setAttribute("aria-label",n),this._button.setAttribute("title",n),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=this._getRoot()?.stopLabel||I(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 I(this).getIcon("check")}_getSendIcon(){return I(this).getIcon("send")||"Send"}_getStopIcon(){return I(this).getIcon("stop")}};G(xn);customElements.get("aparte-composer-send")||customElements.define("aparte-composer-send",xn);var Mn=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(Lt(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=I(this).t("stopButton")||"Stop",e=this._getStopIcon();this.innerHTML=`<button
167
+ type="button"
168
+ class="aparte-btn aparte-btn--icon aparte-cc-button"
169
+ aria-label="${L(t)}"
170
+ title="${L(t)}"
171
+ hidden
172
+ >${e}</button>`}_connectToRoot(){let t=this._getRoot();t&&(this._unsubscribes.push(t._on("streaming-change",({streaming:e})=>{this._button&&(this._button.hidden=!e)})),this._unsubscribes.push(t._on("stop-label-change",()=>this._refreshChrome())),t.streaming&&this._button&&(this._button.hidden=!1))}_handleClick(t){t.preventDefault(),this._getRoot()?.cancel()}_refreshChrome(){if(!this._button)return;let t=this._getRoot()?.stopLabel||I(this).t("stopButton")||"Stop";this._button.setAttribute("aria-label",t),this._button.setAttribute("title",t),this._button.innerHTML=this._getStopIcon()}_getStopIcon(){return I(this).getIcon("stop")}};G(Mn);customElements.get("aparte-composer-cancel")||customElements.define("aparte-composer-cancel",Mn);var In=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 n=this._getRoot()?.attachments.indexOf(t)??-1,i=this.querySelectorAll(".aparte-thumb")[n];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=I(this),n=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="${L(n(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="${L(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])})}),!I(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=()=>{st(this,"aparte-attachment-preview",{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(In);customElements.get("aparte-composer-attachments")||customElements.define("aparte-composer-attachments",In);var Ln=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(Lt(this,()=>this._refreshChrome()))}disconnectedCallback(){this._button?.removeEventListener("click",this._onClick),this._dragCleanup?.(),this._unsubscribes.forEach(t=>t()),this._unsubscribes=[]}attributeChangedCallback(t,e,n){e!==n&&t==="disabled"&&this._button&&(this._button.disabled=n!==null)}_getRoot(){return this.closest("aparte-composer")}_refreshChrome(){if(!this._button)return;let t=I(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=I(this).t("actionUpload")||"Attach file",e=I(this).getIcon("paperclip"),n=this.hasAttribute("disabled")||this._getRoot()?.disabled||!1;this.innerHTML=`<button
173
+ class="aparte-btn aparte-btn--icon aparte-caa-button aparte-action-button"
174
+ aria-label="${L(t)}"
175
+ title="${L(t)}"
176
+ type="button"
177
+ ${n?"disabled":""}
178
+ >${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(n=>al(this.getAttribute("accept"),n));e.length&&this._getRoot()?.addAttachments(e)}_setupDragDrop(){let t=this._getRoot();if(!t)return;let e=a=>{a.preventDefault(),a.stopPropagation()},n=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",n),t.addEventListener("dragleave",i),t.addEventListener("drop",r),this._dragCleanup=()=>{t.removeEventListener("dragover",n),t.removeEventListener("dragleave",i),t.removeEventListener("drop",r)}}};G(Ln);customElements.get("aparte-composer-add-attachment")||customElements.define("aparte-composer-add-attachment",Ln);var Rn=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(Lt(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,n){e!==n&&this._button&&(t==="disabled"&&(this._button.disabled=n!==null),t==="label"&&(this._button.setAttribute("aria-label",n??""),this._button.setAttribute("title",n??"")),t==="icon"&&(this._button.innerHTML=this._resolveIcon(n??"")))}_getRoot(){return this.closest("aparte-composer")}_render(){if(this.querySelector(".aparte-cact-button"))return;let t=L(this.getAttribute("label")??""),e=this._resolveIcon(this.getAttribute("icon")??""),n=this.hasAttribute("disabled")||this._getRoot()?.disabled||!1;this.innerHTML=`<button
179
+ class="aparte-btn aparte-btn--icon aparte-cact-button aparte-action-button"
180
+ aria-label="${t}"
181
+ title="${t}"
182
+ type="button"
183
+ ${n?"disabled":""}
184
+ >${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){st(this,"aparte-action-click",{actionId:this.getAttribute("action-id")??"",composer:this._getRoot()})}_resolveIcon(t){return t?t.trimStart().startsWith("<")?t:I(this).getIcon(t)??t:""}};G(Rn);customElements.get("aparte-composer-action")||customElements.define("aparte-composer-action",Rn);var On=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()!==""),n=t||e;n!==!this.hasAttribute("data-empty")&&(n?this.removeAttribute("data-empty"):this.setAttribute("data-empty",""))}};G(On);customElements.get("aparte-composer-toolbar")||customElements.define("aparte-composer-toolbar",On);function Pn(s){return s.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().trim()}function Ci(s,t){let e=0;for(let n of s.querySelectorAll("[data-conv-id]")){let i=n.querySelector(".aparte-conv-item__title")?.textContent??n.textContent??"";n.hidden=t!==""&&!Pn(i).includes(t),n.hidden||e++}for(let n of s.querySelectorAll(".aparte-conv-group"))n.hidden=t!==""&&!Array.from(n.querySelectorAll("[data-conv-id]")).some(i=>!i.hidden);return e}var Ko=s=>s==="running"||s==="waiting"?s:null;function we(s,t){return`[${s}="${nt(t)}"]`}var mi=864e5,np=["more","edit","pin","archive","unarchive","trash"],bi=4,vi=8,Nn=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",Z(t))}get manage(){return this.hasAttribute("manage")}set manage(t){this.toggleAttribute("manage",Z(t))}connectedCallback(){this.classList.contains("aparte-conv-list")||this.classList.add("aparte-conv-list"),this.getAttribute("role")||this.setAttribute("role","navigation"),this.addEventListener("click",this._onClick),this.addEventListener("keydown",this._onKeydown),this.addEventListener("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,n){e!==n&&(t==="active-id"?(this._activeId=n,this._updateActiveState()):(t==="flat"||t==="loading")&&this.isConnected&&this._render())}_onConfigChange=t=>{let e=t.detail;if(e?.config&&e.config!==I(this))return;let n=this._configDrawn(),i=this._drawnWith;i&&i.locale===n.locale&&i.glyphs===n.glyphs||this._renderUnlessHeld()};_drawnWith=null;_configDrawn(){let t=I(this);return{locale:t.getLocale(),glyphs:np.map(e=>t.getIcon(e)).join(`
185
+ `)}}_onStatus=t=>{let e=t.detail;if(typeof e?.id!="string")return;di(e.id,Ko(e.status));let n=this.querySelector(we("data-conv-id",e.id));n&&this._applyStatus(n,e.id)};setConversationStatus(t,e){go(t,Ko(e))}getConversationStatus(t){return un(t)}_applyStatus(t,e){let n=un(e);n?t.setAttribute("data-status",n):t.removeAttribute("data-status");let i=n==="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(n))}_statusWords(t){return t==="running"?this._t("conversationRunning"):t==="waiting"?this._t("conversationWaiting"):""}set conversations(t){this._conversations=Array.isArray(t)?t:[],this._renderUnlessHeld()}_renderAfterMenu=!1;_renderUnlessHeld(){if(this._renaming&&!this._renaming.done||this.querySelector("[data-menu-for]")){this._renderAfterMenu=!0;return}this._render()}_renderHeld(){!this._renderAfterMenu||!this.isConnected||(this._renderAfterMenu=!1,this._render())}get conversations(){return this._conversations}_renderMeta=null;set renderMeta(t){let e=typeof t=="function"?t:null;e!==this._renderMeta&&(this._renderMeta=e,this._renderUnlessHeld())}get renderMeta(){return this._renderMeta}_applyMeta(){let t=this._renderMeta;if(!t)return;let e=new Map(this._conversations.map(n=>[n.id,n]));for(let n of this.querySelectorAll("[data-conv-id]")){let i=e.get(n.dataset.convId??""),r=n.querySelector(".aparte-conv-item__select");if(!i||!r)continue;let a=t(i);if(a==null||a==="")continue;let o=document.createElement("span");o.className="aparte-conv-item__meta",typeof a=="string"?o.textContent=a:o.append(a),r.after(o)}}_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._renderUnlessHeld())},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._renderAfterMenu=!1,this._drawnWith=this._configDrawn(),this._releaseMenus(),this._renaming=null;let e=ot(this),n=e&&this.contains(e)?e.closest("[data-select-id], [data-more-id]"):null,i=n?.dataset.selectId?we("data-select-id",n.dataset.selectId):n?.dataset.moreId?we("data-more-id",n.dataset.moreId):null,r=n?.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._applyMeta(),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=Pn(t),this._applyFilter()}_applyFilter(){let t=this._query;if(this.hasAttribute("loading"))return 0;let e=Ci(this,t),n=t!==""&&e===0;this.toggleAttribute("data-no-match",n);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=n?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 I(this).getLocale()[t]??zt[t]??""}_groups(){let t=this._conversations;if(this.hasAttribute("flat")||!t.some(h=>typeof h.updatedAt=="number"||h.group))return[{key:"all",label:null,items:t}];let e=new Date,n=new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime(),i=I(this).getLocale().tag,r=new Map,a=(h,u,p)=>{let f=r.get(h);f||(f={key:h,label:u,items:[]},r.set(h,f)),f.items.push(p)},o=new Map;for(let h of t){if(h.group){let p=o.get(h.group.key);p||(p={key:h.group.key,label:h.group.label,items:[]},o.set(h.group.key,p)),p.items.push(h);continue}if(h.pinnedAt){a("pinned",this._t("conversationGroupPinned"),h);continue}let u=h.updatedAt;if(typeof u!="number"){a("undated",null,h);continue}if(u>=n)a("today",this._t("conversationGroupToday"),h);else if(u>=n-mi)a("yesterday",this._t("conversationGroupYesterday"),h);else if(u>=n-7*mi)a("week",this._t("conversationGroupWeek"),h);else if(u>=n-30*mi)a("month",this._t("conversationGroupMonth"),h);else{let p=new Date(u),f=p.getFullYear()===e.getFullYear(),g=new Intl.DateTimeFormat(i,f?{month:"long"}:{month:"long",year:"numeric"}).format(p),_=g.charAt(0).toLocaleUpperCase(i)+g.slice(1);a(`m-${p.getFullYear()}-${String(p.getMonth()).padStart(2,"0")}`,_,h)}}let l=["pinned","today","yesterday","week","month"].map(h=>r.get(h)).filter(h=>!!h),c=[...r.keys()].filter(h=>h.startsWith("m-")).sort((h,u)=>u.localeCompare(h)).map(h=>r.get(h)),d=r.get("undated");return[...o.values(),...l,...c,...d?[d]:[]]}_renderGroup(t){let e=t.items.map(i=>this._renderItem(i)).join("");if(t.label===null)return`<div class="aparte-conv-group">${e}</div>`;let n=P(t.label);return`
186
+ <div class="aparte-conv-group" role="group" aria-label="${L(t.label)}">
187
+ <div class="aparte-menu__label aparte-conv-group__label" aria-hidden="true">${n}</div>
188
+ ${e}
189
+ </div>`}_renderItem(t){let e=t.id===this._activeId,n=["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=L(t.id),r=P(t.title||this._t("newChat")),a=L(this._t("conversationActions")),o=I(this).getIcon("more"),l=un(t.id),c=l?` data-status="${L(l)}"`:"",d=L(l==="running"?"aparte-conv-item__title aparte-shimmer":"aparte-conv-item__title"),h=P(this._statusWords(l));return`
190
+ <div class="${L(n)}" data-conv-id="${i}"${c}>
191
+ <button
192
+ class="aparte-conv-item__select"
193
+ type="button"
194
+ data-select-id="${i}"
195
+ aria-current="${e?"page":"false"}"
196
+ ><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>
197
+ <button
198
+ class="aparte-btn aparte-btn--icon aparte-btn--sm aparte-conv-item__more"
199
+ type="button"
200
+ data-more-id="${i}"
201
+ aria-label="${a}"
202
+ title="${a}"
203
+ aria-haspopup="menu"
204
+ aria-expanded="false"
205
+ >${o}</button>
206
+ </div>`}_menuMarkup(t){let e=I(this),n=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`
207
+ <button type="button" class="aparte-menu__item" role="menuitem" data-menu-action="rename">${n}<span>${o}</span></button>
208
+ <button type="button" class="aparte-menu__item" role="menuitem" data-menu-action="pin">${i}<span>${l}</span></button>
209
+ <button type="button" class="aparte-menu__item" role="menuitem" data-menu-action="archive">${r}<span>${c}</span></button>
210
+ <div class="aparte-menu__separator" role="separator"></div>
211
+ <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)),n=P(this._t("cancel")),i=P(this._t("deleteConversation"));return`
212
+ <div class="aparte-conv-menu__confirm">
213
+ <p class="aparte-conv-menu__question">${e}</p>
214
+ <div class="aparte-conv-menu__actions">
215
+ <button type="button" class="aparte-btn aparte-btn--sm aparte-btn--ghost" data-menu-action="cancel">${n}</button>
216
+ <button type="button" class="aparte-btn aparte-btn--sm aparte-btn--danger aparte-btn--solid" data-menu-action="confirm-delete">${i}</button>
217
+ </div>
218
+ </div>`}_newMenu(){let t=document.createElement("div");return t.className="aparte-menu aparte-conv-menu",t.setAttribute("role","menu"),t}_fillMenu(t,e){let n=t.dataset.convId,i=n?this._conversations.find(r=>r.id===n):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 n=e.closest("[data-conv-id]");if(!n)continue;let i=this._newMenu();this._menus.push($i(e,i,{gap:bi,margin:vi,align:"end",onOpen:()=>this._fillMenu(n,i),onClose:()=>{i.remove(),this._renderHeld()}}))}let t=this._contextMenu??=this._newMenu();this._menus.push(Hi(this,t,{gap:bi,margin:vi,onOpen:e=>{let n=e.closest("[data-conv-id]");return!n||!this.contains(n)||e.closest("[data-rename-id], [data-menu-for]")?!1:this._fillMenu(n,t)},onClose:()=>{t.remove(),this._renderHeld()}}))}_releaseMenus(){for(let t of this._menus.splice(0))t()}_placeQuestion(t,e){let n=getComputedStyle(this).direction==="rtl",i=t===this._contextMenu?null:this.querySelector(we("data-more-id",e)),r=t.getBoundingClientRect(),a=n?r.right:r.left;Vn(i?.getBoundingClientRect()??{top:r.top,bottom:r.top,left:a,right:a},t,{gap:i?bi:0,margin:vi,align:i?"end":"start",rtl:n})}_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 n=this.getAttribute("target"),i=this.getRootNode(),r=n?i.getElementById?.(n)??this.ownerDocument.getElementById(n):null,a=I(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 n=this._conversations.find(r=>r.id===e.dataset.menuFor);if(!n)return;let i=n.id;switch(t){case"rename":{let r=this.querySelector(we("data-conv-id",i));r&&this._startRename(r,n);return}case"pin":if(n.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(n.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(n),e.append(...a.childNodes),e.setAttribute("role","dialog"),e.setAttribute("aria-label",this._confirmQuestion(n)),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 n=Array.from(e.querySelectorAll("[data-menu-action]")),i=n.indexOf(ot(this)),r=a=>{t.preventDefault(),n[(a+n.length)%n.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(n.length-1);return}}_startRename(t,e){let n=t.querySelector(".aparte-conv-item__select");if(!n)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,n.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 n=this._renaming;if(!n||n.done)return;n.done=!0;let i=this._conversations.find(a=>a.id===n.id),r=n.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="${nt(n.id)}"]`)?.focus()}_onClick=t=>{let e=t.target,n=e.closest("[data-menu-action]"),i=n?.closest("[data-menu-for]");if(n&&i){t.stopPropagation(),this._onMenuAction(n.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,n=e.closest("[data-menu-for]");if(n){n.getAttribute("role")==="dialog"&&this._onQuestionKeydown(t,n);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 n=e.dataset.convId===this._activeId;e.classList.toggle("aparte-conv-item--active",n),e.querySelector("[data-select-id]")?.setAttribute("aria-current",n?"page":"false")})}};G(Nn);customElements.get("aparte-conversation-list")||customElements.define("aparte-conversation-list",Nn);var dl=s=>typeof s=="string"||typeof s=="object"&&s!==null&&typeof s.label=="string",yi=s=>{try{let t=JSON.parse(s);return Array.isArray(t)?t.filter(dl):[]}catch{return console.warn('[aparte-suggestions] `suggestions` is not a JSON array. Use ["\u2026"] or [{"label": "\u2026", "prompt": "\u2026"}].'),[]}},Vo=s=>typeof s=="string"?s:s.label,Yo=s=>typeof s=="string"?s:s.prompt??s.label,Dn=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?rl(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"?yi(t):Array.isArray(t)?t.filter(dl):[],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,e,n){e!==n&&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 I(this).t("suggestionsLabel")||"Suggested prompts"}_parsed=null;_readAttribute(){let t=this.getAttribute("suggestions");t===null||t===this._parsed||(this._parsed=t,this._suggestions=yi(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=bt(this._composer)??bt(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,n=e&&e.getAttribute("data-role")!=="user"?e.querySelectorAll("[data-aparte-suggestions]"):null,i=n&&n.length?n[n.length-1]:null,r=i?yi(i.getAttribute("data-aparte-suggestions")??"[]"):[];this._showAnswers(r.map(ai).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(){let t=this.querySelector(".aparte-suggestions"),e=t?[...t.querySelectorAll(".aparte-suggestion")]:[],n=e.findIndex(l=>l===document.activeElement),i=n>=0?e[n].textContent:null,r=t?.scrollLeft??0;if(this.replaceChildren(),this._suggestions.length===0){this.setAttribute("data-empty","");return}this.removeAttribute("data-empty");let a=document.createElement("div");a.className="aparte-suggestions",a.setAttribute("role","group"),a.setAttribute("aria-label",this._groupLabel());for(let l of this._suggestions){let c=document.createElement("button");c.type="button",c.className="aparte-btn aparte-btn--surface aparte-btn--pill aparte-suggestion",c.textContent=Vo(l);let d=Yo(l);d!==c.textContent&&(c.title=d),c.addEventListener("click",()=>this._activate(l)),a.appendChild(c)}if(this.appendChild(a),a.scrollLeft=r,n<0)return;let o=[...a.children];(o.find(l=>l.textContent===i)??o[Math.min(n,o.length-1)])?.focus()}_sending=!1;_sendingTimer;_stopHolding=()=>{this._sending=!1,clearTimeout(this._sendingTimer),window.removeEventListener("aparte-message-start",this._onTurnStart)};_onTurnStart=t=>{let e=t.detail?.targetId,n=this._ownChatId();(!e||!n||e===n)&&this._stopHolding()};_ownChatId(){return yt(this._composer)}_holdUntilStreaming(){this._stopHolding(),this._sending=!0,window.addEventListener("aparte-message-start",this._onTurnStart),this._sendingTimer=setTimeout(this._stopHolding,1e3)}_activate(t){let e={label:Vo(t),prompt:Yo(t)};if(!st(this,"aparte-suggestion",e,{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(Dn);customElements.get("aparte-suggestions")||customElements.define("aparte-suggestions",Dn);var Qo=(s,t)=>{let e=Number(s);return s!==null&&Number.isFinite(e)&&e>0&&e<=1?e:t},sp=s=>(s instanceof Element?s.closest("aparte-chat, [data-aparte-chat]"):null)?.id||void 0,V=(s,t,e)=>{let n=document.createElement(s);return n.className=t,e!==void 0&&(n.textContent=e),n},Xo="http://www.w3.org/2000/svg",ip=()=>{let s=document.createElementNS(Xo,"svg");s.setAttribute("class","aparte-context__ring"),s.setAttribute("viewBox","0 0 36 36");for(let t of["track","value"]){let e=document.createElementNS(Xo,"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"),s.appendChild(e)}return s},Jo=s=>!!s&&typeof s.getMessages=="function",rp=s=>{if(!s)return null;if(Jo(s))return s;let t=s.viewport??s.querySelector("aparte-chat-viewport");return Jo(t)?t:null},ap=0,op={system:0,tools:0,summary:0,messages:0},Bn=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?bt(t):null;e&&(this._seen=e)}_onDone=t=>{let e=t.detail;!e?.usage||!this._isMine(e.targetId)||(this._remember(t.target),this._used=pn(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(sp(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?pn(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,e,n){if(e!==n){if(t==="used"){let i=Number(this.getAttribute("used"));this._used=this.hasAttribute("used")&&Number.isFinite(i)&&i>=0?i:null}this.isConnected&&this._render()}}_cfg(){return I(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(){return yt(this)}_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=bt(this);return e||(this._seen?.isConnected?this._seen:null)}_messages(){let t=rp(this._chat());if(!t)return null;try{return t.getMessages()}catch{return null}}_measure(t){let e=this._messages(),n=this._lastDone,i=e&&n?.messageId?e.map(a=>a.id===n.messageId&&!a.usage?{...a,usage:n.usage}:a):e,r=!!i?.some(a=>a.role==="assistant"&&a.usage);return i&&(r&&!this._blank||this._overflow&&i.length>0)?Co({messages:i,config:this._cfg(),windowOverride:t,viewChanged:this._viewChanged}):this._used===null?null:{window:t,used:this._used,estimated:!1,parts:{...op},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 n=e.used,i=Math.min(1,n/t),r=Qo(this.getAttribute("warn"),.75),a=Qo(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?ip():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-${++ap}`,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,y=new Intl.NumberFormat(_,{notation:"compact",maximumFractionDigits:1}),b=e.estimated?"~":"",k=`${b}${y.format(n)} / ${y.format(t)}`,x=Math.round(i*100),v=g.t("contextLabel")||"Context window";if(l){let E=d.querySelector(".aparte-context__value");E?.style.setProperty("--aparte-context-ratio",String(x)),E?.classList.toggle("aparte-context__value--empty",x===0),c.title=k}else d.style.setProperty("--aparte-progress-value",String(x));if(d.setAttribute("aria-valuemin","0"),d.setAttribute("aria-valuemax",String(t)),d.setAttribute("aria-valuenow",String(n)),d.setAttribute("aria-label",`${v}: ${k}`),p.textContent=`${v}: `,u.setAttribute("aria-expanded",String(this._open)),h.textContent=l?`${b}${new Intl.NumberFormat(_,{style:"percent",maximumFractionDigits:0}).format(x/100)}`:k,f.setAttribute("aria-label",v),f.hidden=!this._open,this._open?this._renderPanel(f,e,t,y):this._panelSignature="",o!==this._level){this._level=o;let E=this._ownTargetId(),A={level:o,used:n,window:t,ratio:i,targetId:E};this.dispatchEvent(new CustomEvent("aparte-context-threshold",{detail:A,bubbles:!0,composed:!0}))}}_renderPanel(t,e,n,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,n-h),approx:f}],_=`${f}${i.format(h)} / ${i.format(n)}`,y=c&&c.tokens>0?(r.t("contextReclaim")||"Compacting now would free ~{n} tokens").replace("{n}",()=>i.format(Math.round(c.tokens))):"",b=!!a&&!!c&&this._compact===null,k=V("ul","aparte-context__rows");for(let m of g){let S=V("li","aparte-context__row");S.setAttribute("data-part",m.key),S.append(V("span","aparte-context__row-label",m.label)),S.append(V("span","aparte-context__row-value",`${m.approx}${i.format(Math.round(m.tokens))}`));let O=V("div","aparte-progress aparte-context__row-bar");O.setAttribute("aria-hidden","true"),O.style.setProperty("--aparte-progress-value",String(Math.round(Math.min(1,m.tokens/n)*100))),O.appendChild(V("div","aparte-progress__bar")),S.append(O),k.append(S)}let x=V("li","aparte-context__row aparte-context__row--total");x.setAttribute("data-part","total"),x.append(V("span","aparte-context__row-label",r.t("contextTotal")||"Total"),V("span","aparte-context__row-value",_)),k.append(x);let v=[k];if(this._compact==="running"){let m=V("p","aparte-context__status aparte-shimmer",r.t("checkpointPending")||"Summarising the context\u2026");m.setAttribute("role","status"),v.push(m)}else if(this._compact==="failed"){let m=V("p","aparte-context__status aparte-context__status--failed",r.t("checkpointFailed")||"Couldn't summarise the context");m.setAttribute("role","status"),this._failure&&(m.title=this._failure,m.appendChild(V("span","aparte-sr-only",`: ${this._failure}`))),v.push(m,this._action("retry",r.t("retry")||"Retry"))}y&&v.push(V("p","aparte-context__reclaim",y)),b&&v.push(this._action("compact",r.t("contextCompactNow")||"Compact now"));let E=V("div","aparte-context__content");if(E.append(...v),E.innerHTML===this._panelSignature)return;this._panelSignature=E.innerHTML;let A=document.activeElement,w=A&&t.contains(A)?A.getAttribute("data-context-action")??"":null;t.replaceChildren(...Array.from(E.childNodes)),w!==null&&((w?t.querySelector(`[data-context-action="${nt(w)}"]`):null)??this.querySelector(".aparte-context__toggle"))?.focus()}_action(t,e){let n=V("button","aparte-btn aparte-btn--sm aparte-btn--surface aparte-context__action",e);return n.type="button",n.setAttribute("data-context-action",t),n}async _compactNow(t){let e=this._cfg().getCompactor(),n=this._ownTargetId();if(!e){window.dispatchEvent(new CustomEvent("aparte-compact",{detail:{targetId:n}}));return}this._compact="running",this._failure="",this._render();let i=null;try{let r=await e.compact({target:this._chat(),...n?{targetId:n}:{},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,n=e?.closest?.("[data-context-action]");if(n){this._compactNow(n.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(),n=t.getBoundingClientRect();n.height>0&&e.top<n.height&&t.setAttribute("data-placement","below");let r=getComputedStyle(t).direction==="rtl"?n.left<0:n.right>document.documentElement.clientWidth;n.width>0&&r&&t.setAttribute("data-align","end")}};G(Bn);customElements.get("aparte-context")||customElements.define("aparte-context",Bn);var gn=60,lp=6,cp=150,dp=4,up=1,Zo=30,$n=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,e,n){e!==n&&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(ul(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"&&(tl(e.addedNodes)||tl(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=I(this).getLocale();for(let n of t)this._label(n,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 n=t.getAttribute("message-id");if(!n)return;let i=this.querySelector(`.aparte-scroll-rail__tick[data-message-id="${nt(n)}"]`);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(n=>n.getAttribute("data-role")==="user")}_excerpt(t){let e=this._excerpts.get(t);if(e!==void 0)return e;let n=t.querySelector(".aparte-message-content")??t,i="",r=document.createTreeWalker(n,NodeFilter.SHOW_TEXT);for(let l=r.nextNode();l&&i.length<gn*16;l=r.nextNode())i+=l.nodeValue??"";let a=i.slice(0,gn*16).replace(/\s+/g," ").trim(),o=a.length>gn?`${a.slice(0,gn-1).trimEnd()}\u2026`:a;return this._excerpts.set(t,o),o}_tickLabel(t,e){let n=t.getAttribute("data-role")==="user"?e.roleNameUser??"You":e.roleNameAssistant??"Assistant",i=this._excerpt(t);return i?`${n}: ${i}`:n}_list(){return this.querySelector(":scope > .aparte-scroll-rail__list")}_rebuild(){this._watchSizes();let t=this._messages(),e=this._bubbles(t),n=I(this).getLocale(),i=n.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,n);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(),(!wi(this._observedBubbles,e)||!wi(this._bandTargets,t))&&this._observe(e,t),this._layout(),c&&this._pickCurrent()}_observe(t,e){let n=typeof IntersectionObserver>"u"?null:this._scrollSurface();if(!n){this._unobserve(),this._observedBubbles=t,this._bandTargets=e;return}(!this._intersections||!this._onScreenObserver||this._observedSurface!==n)&&(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:n,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:n,threshold:[0]}),this._observedSurface=n,n.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],n=e.getAttribute("message-id");if(this._atBottom()||this._onScreen.has(e)){this._setCurrent(n);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 n=t.getBoundingClientRect();if(n.height<=0)return null;let i=n.top+n.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 n=null;for(let i of this._messages()){if(i===t)break;this._ticked(i)&&(n=i.getAttribute("message-id"))}return n??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 n=t?null:ot(this),i=(n instanceof HTMLElement&&e.includes(n)?n: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 n of e){let i=n===t?0:-1;n.tabIndex!==i&&(n.tabIndex=i)}}_reveal(t){let e=this.clientHeight;if(!e)return;let n=t.offsetTop,i=n+t.offsetHeight;n<this.scrollTop?this.scrollTop=n: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(!wi(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(),n=this._scrollSurface();if(t&&n&&this._write("--aparte-scroll-rail-bar",`${Math.max(0,n.offsetWidth-n.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(lp,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 n=e.dataset.messageId;n&&this.jumpTo(n)};_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")),n=e.indexOf(ot(this));if(n===-1)return;t.preventDefault();let i=t.key==="Home"?0:t.key==="End"?e.length-1:t.key==="ArrowDown"?Math.min(e.length-1,n+1):Math.max(0,n-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 n=this._bubbleOf(t);n&&(this._viewport()?.setAutoScroll?.(!1),this._scrollTo(n),this._setCurrent(this._markFor(n)),this._hold(t))}_bubbleOf(t){return this._viewport()?.querySelector(`aparte-chat-bubble[message-id="${nt(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(),cp)}_settle(){let t=this._held,e=this._settleSurface,n=t?this._bubbleOf(t):null;if(t&&n&&e&&this._alignPasses<dp){let i=e.getBoundingClientRect().top+(parseFloat(getComputedStyle(e).scrollPaddingTop)||0),r=n.getBoundingClientRect().top-i;if(Math.abs(r)>up){this._alignPasses++,this._scrollTo(n),this._bumpSettle();return}}this._release(),t&&this._setCurrent(n?this._markFor(n):t)}_release(){this._settleTimer!==null&&clearTimeout(this._settleTimer),this._settleTimer=null,this._settleSurface?.removeEventListener("scroll",this._onSurfaceScroll),this._settleSurface=null,this._held=null}};function ul(s){return s instanceof Element&&s.localName==="aparte-chat-bubble"}function tl(s){return Array.from(s).some(t=>t instanceof Element&&(ul(t)||t.localName==="aparte-chat-viewport"||t.querySelector("aparte-chat-bubble")!==null))}function wi(s,t){if(s.length!==t.length)return!1;for(let e=0;e<s.length;e++)if(s[e]!==t[e])return!1;return!0}G($n);customElements.get("aparte-scroll-rail")||customElements.define("aparte-scroll-rail",$n);var hp="(max-width: 48rem)",Hn=class extends HTMLElement{static get observedAttributes(){return["collapsed","breakpoint"]}_media=null;_scrim=null;_opener=null;_lastCollapsed=null;_lastRail=!1;_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",Z(t))}_rail(){return this.getAttribute("collapsed")==="rail"&&!this.drawer}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._lastRail=this._rail(),this.id||(this.id=`aparte-sidebar-${++pp}`),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})`:hp;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,n=this._rail();if(!(e===this._lastCollapsed&&n===this._lastRail)){if(this._lastRail=n,e===this._lastCollapsed){this._syncHidden();return}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=Tt(this),n=e===document?Array.from(document.querySelectorAll(t)):[...e.querySelectorAll(t),...document.querySelectorAll(t)];for(let i of n)ft(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:gp(t)===this}_syncHidden(){this.collapsed&&!this._rail()?(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(){el(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=el(this);if(e.length===0)return;let n=e[0],i=e[e.length-1],r=ot(this);this.contains(r)?t.shiftKey&&r===n?(t.preventDefault(),i.focus()):!t.shiftKey&&r===i&&(t.preventDefault(),n.focus()):(t.preventDefault(),n.focus())}}};_onDocumentClick=t=>{let e=ct(t)?.closest?.("[data-aparte-sidebar-toggle]");!e||ft(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,n=!1;for(let i of this._lists())typeof i.filter=="function"?e+=i.filter(t):(e+=Ci(i,Pn(t)),n=!0);return n&&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=Pn(this._query),e=t!==""&&this._lists().every(n=>typeof n.filter=="function"?n.hasAttribute("data-no-match"):!n.hasAttribute("loading")&&Ci(n,t)===0);this.toggleAttribute("data-no-match",e)}_onConfigChange=()=>this._relabel();_relabel(){if(this.hasAttribute("aria-label")&&this.dataset.ownLabel!=="locale")return;let t=I(this).getLocale();this.setAttribute("aria-label",t.sidebarLabel??"Conversations"),this.dataset.ownLabel="locale"}},pp=0,fp=["a[href]","button:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(",");function el(s){return Array.from(s.querySelectorAll(fp)).filter(t=>!t.closest("[hidden]")&&t.checkVisibility?.()!==!1)}function gp(s){return s.closest("aparte-sidebar")??s.closest(".aparte-app-shell")?.querySelector("aparte-sidebar")??Tt(s).querySelector("aparte-sidebar")??document.querySelector("aparte-sidebar")}G(Hn);customElements.get("aparte-sidebar")||customElements.define("aparte-sidebar",Hn);function nl(s,t,e){return Number.isFinite(s)?s<t?t:s>e?e:s:t}function _p(s){let t=Number.isFinite(s.startPercent)?s.startPercent:0;if(!Number.isFinite(s.containerPx)||s.containerPx<=0)return nl(t,0,100);let i=((!s.vertical&&s.rtl)!==(s.primaryEnd===!0)?-1:1)*s.deltaPx*100/s.containerPx;return nl(t+i,0,100)}function sl(s,t,e,n,i=!1){if(s==="Home")return-100;if(s==="End")return 100;let r=(t?10:1)*(i?-1:1);return n?s==="ArrowUp"?-r:s==="ArrowDown"?r:null:s==="ArrowLeft"?e?r:-r:s==="ArrowRight"?e?-r:r:null}var mp="(max-width: 48rem)",Ae=38,bp=300;function Se(s,t){let e=Number.parseFloat(s??"");return Number.isFinite(e)?e<0?0:e>100?100:e:t}var qn=class s 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=Ae;_initialPosition=Ae;_initialCaptured=!1;_preCollapsePosition=null;_lastPosition=null;_lastCollapsed=null;_lastPane=null;_source="api";_ready=!1;_dragging=!1;_captured=!1;_moved=!1;_pointerId=null;_dragStartPercent=Ae;_dragOriginPx=0;_dragContainerPx=0;_keying=!1;get position(){return this._position}set position(t){let e=Se(String(t),this._position);this.isConnected&&e===this._lastPosition||(this._position=e,this._setLive(e),this.isConnected&&this._commit("api"))}get orientation(){return this.getAttribute("orientation")==="vertical"?"vertical":"horizontal"}set orientation(t){this.setAttribute("orientation",t)}get primary(){return this.getAttribute("primary")==="end"?"end":"start"}set primary(t){this.setAttribute("primary",t)}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(t){this.toggleAttribute("collapsed",Z(t))}get pane(){return this.getAttribute("pane")==="end"?"end":"start"}set pane(t){this.setAttribute("pane",t)}get disabled(){return this.hasAttribute("disabled")}set disabled(t){this.toggleAttribute("disabled",Z(t))}get stacked(){return this.hasAttribute("data-stacked")||this.hasAttribute("single")||this.classList.contains("aparte-split--only-start")||this.classList.contains("aparte-split--only-end")}get single(){return this.hasAttribute("single")}set single(t){this.toggleAttribute("single",Z(t))}collapse(){this.collapsed=!0}expand(){this.collapsed=!1}toggleCollapse(){this.collapsed=!this.collapsed}showPane(t){this.pane=t}reset(){this._position=this._initialPosition,this._setLive(this._position),this.isConnected&&this._commit("api")}connectedCallback(){this.classList.contains("aparte-split")||this.classList.add("aparte-split"),this._handle=this._ensureHandle();let t=this.getAttribute("position");t!==null?(this._position=Se(t,Ae),this._setLive(this._position)):this._position=Se(getComputedStyle(this).getPropertyValue("--aparte-split-position"),Ae),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,e,n){if(e!==n&&this._ready)switch(t){case"position":{let i=Se(this.getAttribute("position"),this._position);if(i===this._lastPosition)return;this._position=i,this._setLive(i),this._commit();return}case"collapsed":{let i=this.collapsed;if(i===this._lastCollapsed)return;this._lastCollapsed=i,i?(this._preCollapsePosition=this._position,this._position=0):this._position=this._preCollapsePosition??this._initialPosition,this._setLive(this._position),this._commit();return}case"pane":{let i=this.pane;if(this._syncPaneControls(),i===this._lastPane)return;this._lastPane=i,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",n=t?this.clientHeight:this.clientWidth;if(n<=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 ${n}px`:`${n}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=y=>{y.target===this&&y.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 n=this.children[1]??null;return n?this.insertBefore(e,n):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-${++s._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(),n=this._measure(this);if(!e||!(n>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)/n*100;this.style.setProperty("--aparte-split-position","100%");let a=this._measure(e)/n*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=_p({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 n=this._moved;this._dragging=!1,this._moved=!1,this._releasePointer(),this._handle?.removeAttribute("data-dragging"),this._removeScrim(!n),e!==void 0&&(this._position=e,this._setLive(e)),!(!n&&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(),bp)}}_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=sl(t.key,t.shiftKey,this._rtl(),this.orientation==="vertical",this.primary==="end");e!==null&&(t.preventDefault(),this._keying=!0,this._position=Se(String(this._position+e),this._position),this._setLive(this._position))};_onKeyup=t=>{!this._keying||t.target!==this._handle||sl(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})`:mp;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=ct(t)?.closest?.("[data-aparte-split-pane]");if(!e||ft(e))return;let n=(e.getAttribute("data-aparte-split-pane")??"").trim(),i=n==="start"||n==="end"?n:null,r=i?"":n;if(r){if(r!==this.id)return}else if((e.closest("aparte-split")??Tt(e).querySelector("aparte-split")??document.querySelector("aparte-split"))!==this)return;this.showPane(i??(this.pane==="start"?"end":"start"))};_syncPaneControls(){let t=new Set([Tt(this),document]);for(let e of t)for(let n of e.querySelectorAll("[data-aparte-split-pane]")){let i=(n.getAttribute("data-aparte-split-pane")??"").trim();i!=="start"&&i!=="end"||n.localName!=="button"&&n.getAttribute("role")!=="button"||ft(n)||(n.closest("aparte-split")??Tt(n).querySelector("aparte-split")??document.querySelector("aparte-split"))!==this||(this.stacked?n.setAttribute("aria-pressed",String(i===this.pane)):n.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=I(this).getLocale();t.setAttribute("aria-label",this.getAttribute("label")??e.splitHandleLabel??"Resize the panes"),t.dataset.ownLabel="locale"}};G(qn);customElements.get("aparte-split")||customElements.define("aparte-split",qn);var vp="(max-width: 30rem), (max-height: 30rem)",yp=["a[href]","button:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(","),Fn=class s 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",Z(t))}get sheet(){return this.hasAttribute("data-sheet")}get maximized(){return this.hasAttribute("maximized")}set maximized(t){this.toggleAttribute("maximized",Z(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||s._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:[me],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,n){if(e===n||!this._ready)return;if(t==="breakpoint"){this._watchBreakpoint();return}if(this._render(),t==="maximized"){e===null!=(n===null)&&this._announce();return}if(t==="maximizable"){this.open&&this.maximized&&e==="panel"!=(n==="panel")&&this._announce();return}if(t!=="open")return;let i=this.open;i!==this._lastOpen&&(this._lastOpen=i,!i&&this._button&&this.contains(ot(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(`[${me}]`)).find(e=>!ft(e));return I(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 n=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?n.launcherClose??"Close the chat":n.launcherOpen??"Open the chat");let o=[s._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(n=>n instanceof Element&&(n.matches(e)||n.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,n){t.setAttribute("aria-label",e),t.setAttribute("title",e),t.replaceChildren(s._glyph(n))}_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 n=document.createElement("div");return n.className="aparte-app-header__actions",this._maximize=s._headerButton("maximize"),this._maximize.setAttribute("data-aparte-launcher-maximize",""),this._closeControl=s._headerButton("close"),this._closeControl.setAttribute("data-aparte-launcher-close",""),n.append(this._maximize,this._closeControl),t.append(this._avatar,e,n),t}_renderHeader(t){if(!this.header||this._cardHasHeader()){let l=!!this._header?.contains(ot(this));this._clearAvatar(),this._header?.remove(),l&&(this._focusTarget()??this._button)?.focus();return}let e=this._header??=this._buildHeader(),n=t.getLocale(),i=(this.getAttribute("label")??"").trim(),r=(this.getAttribute("heading")??(i||(n.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"),s._name(o,this.maximized?n.launcherRestore??"Shrink the chat":n.launcherMaximize??"Expand the chat",t.getIcon(this.maximized?"minimize":"maximize")),s._name(this._closeControl,n.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 n=e.render("assistant",this._avatar);typeof n=="function"&&(this._avatarCleanup=n)}catch(n){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.",n)}}}_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||ft(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})`:vp),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=ot(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(yp)).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=>!ft(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=ct(t),n=i=>{let r=e?.closest?.(i);return!!r&&this.contains(r)&&!ft(r)};n("[data-aparte-launcher-close]")?this.close():n("[data-aparte-launcher-maximize]")&&(this.maximized=!this.maximized)};_inModalDialog(t){let e=ct(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 n=e[0],i=e[e.length-1],r=ot(this);t.shiftKey&&r===n?(t.preventDefault(),i.focus()):!t.shiftKey&&r===i&&(t.preventDefault(),n.focus())}};G(Fn);customElements.get("aparte-launcher")||customElements.define("aparte-launcher",Fn);var il=Symbol.for("aparte.imageHolds"),hl=".aparte-image-held[data-aparte-image]";function pl(s){let t=s.getAttribute("data-aparte-image")??"";I(s).showImage(t);let e=document.createElement("img");e.setAttribute("referrerpolicy","no-referrer"),e.setAttribute("alt",s.getAttribute("data-aparte-image-alt")??""),e.setAttribute("src",t);let n=s===document.activeElement;s.replaceWith(e),n&&(e.tabIndex=-1,e.focus({preventScroll:!0}))}function wp(s){if(s.button!==0||s.ctrlKey||s.metaKey||s.shiftKey||s.altKey)return;let t=s.target?.closest?.(hl);t&&(s.preventDefault(),s.stopPropagation(),pl(t))}function Ap(s){if(s.key!=="Enter"&&s.key!==" ")return;let t=s.target;t?.matches?.(`span${hl}`)&&(s.preventDefault(),s.stopPropagation(),pl(t))}function Sp(){let s=document;s[il]||(s[il]=!0,s.addEventListener("click",wp,!0),s.addEventListener("keydown",Ap,!0))}typeof document<"u"&&(Lo(),Sp());export{nt as a,z as b,dt as c,J as d,Cc as e,I as f,L as g,st as h,oe as i,nu as j,he as k,Q as l,Qu as m,xo as n,Ds as o};
219
+ //# sourceMappingURL=chunk-KVLHKDQP.js.map