@cuadra-ai/uikit 0.4.4 → 0.4.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.
@@ -1,40 +1,40 @@
1
- (function($,p){typeof exports=="object"&&typeof module!="undefined"?p(exports,require("react/jsx-runtime"),require("react"),require("react-dom/client"),require("react-dom")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react","react-dom/client","react-dom"],p):($=typeof globalThis!="undefined"?globalThis:$||self,p($.CuadraUIKit={},$.React,$.React,$.ReactDOM,$.ReactDOM))})(this,(function($,p,y,me,He){"use strict";var vv=Object.defineProperty,kv=Object.defineProperties;var Sv=Object.getOwnPropertyDescriptors;var kn=Object.getOwnPropertySymbols;var Mu=Object.prototype.hasOwnProperty,Pu=Object.prototype.propertyIsEnumerable;var ii=($,p)=>(p=Symbol[$])?p:Symbol.for("Symbol."+$),Nu=$=>{throw TypeError($)},Lu=Math.pow,si=($,p,y)=>p in $?vv($,p,{enumerable:!0,configurable:!0,writable:!0,value:y}):$[p]=y,m=($,p)=>{for(var y in p||(p={}))Mu.call(p,y)&&si($,y,p[y]);if(kn)for(var y of kn(p))Pu.call(p,y)&&si($,y,p[y]);return $},E=($,p)=>kv($,Sv(p));var V=($,p)=>{var y={};for(var me in $)Mu.call($,me)&&p.indexOf(me)<0&&(y[me]=$[me]);if($!=null&&kn)for(var me of kn($))p.indexOf(me)<0&&Pu.call($,me)&&(y[me]=$[me]);return y};var C=($,p,y)=>si($,typeof p!="symbol"?p+"":p,y),Du=($,p,y)=>p.has($)||Nu("Cannot "+y);var Ke=($,p,y)=>(Du($,p,"read from private field"),y?y.call($):p.get($)),er=($,p,y)=>p.has($)?Nu("Cannot add the same private member more than once"):p instanceof WeakSet?p.add($):p.set($,y),tr=($,p,y,me)=>(Du($,p,"write to private field"),me?me.call($,y):p.set($,y),y);var P=($,p,y)=>new Promise((me,He)=>{var Le=Ce=>{try{K(y.next(Ce))}catch(qe){He(qe)}},Ge=Ce=>{try{K(y.throw(Ce))}catch(qe){He(qe)}},K=Ce=>Ce.done?me(Ce.value):Promise.resolve(Ce.value).then(Le,Ge);K((y=y.apply($,p)).next())}),Ne=function($,p){this[0]=$,this[1]=p},Pr=($,p,y)=>{var me=(Ge,K,Ce,qe)=>{try{var rr=y[Ge](K),nr=(K=rr.value)instanceof Ne,Tn=rr.done;Promise.resolve(nr?K[0]:K).then(ot=>nr?me(Ge==="return"?Ge:"next",K[1]?{done:ot.done,value:ot.value}:ot,Ce,qe):Ce({value:ot,done:Tn})).catch(ot=>me("throw",ot,Ce,qe))}catch(ot){qe(ot)}},He=Ge=>Le[Ge]=K=>new Promise((Ce,qe)=>me(Ge,K,Ce,qe)),Le={};return y=y.apply($,p),Le[ii("asyncIterator")]=()=>Le,He("next"),He("throw"),He("return"),Le};var Ft=($,p,y)=>(p=$[ii("asyncIterator")])?p.call($):($=$[ii("iterator")](),p={},y=(me,He)=>(He=$[me])&&(p[me]=Le=>new Promise((Ge,K,Ce)=>(Le=He.call($,Le),Ce=Le.done,Promise.resolve(Le.value).then(qe=>Ge({value:qe,done:Ce}),K)))),y("next"),y("return"),p);var it,Lt,Qe,_u,Ir,Tu,Er,Ar,Mr,Cu,Iu;var Le=typeof document!="undefined"?document.currentScript:null;function Ge(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const K=Ge(y);const Ce=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),qe=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,r,n)=>n?n.toUpperCase():r.toLowerCase()),rr=e=>{const t=qe(e);return t.charAt(0).toUpperCase()+t.slice(1)},nr=(...e)=>e.filter((t,r,n)=>!!t&&t.trim()!==""&&n.indexOf(t)===r).join(" ").trim(),Tn=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var ot={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const Fu=y.forwardRef((u,l)=>{var d=u,{color:e="currentColor",size:t=24,strokeWidth:r=2,absoluteStrokeWidth:n,className:a="",children:i,iconNode:s}=d,o=V(d,["color","size","strokeWidth","absoluteStrokeWidth","className","children","iconNode"]);return y.createElement("svg",m(m(E(m({ref:l},ot),{width:t,height:t,stroke:e,strokeWidth:n?Number(r)*24/Number(t):r,className:nr("lucide",a)}),!i&&!Tn(o)&&{"aria-hidden":"true"}),o),[...s.map(([c,h])=>y.createElement(c,h)),...Array.isArray(i)?i:[i]])});const De=(e,t)=>{const r=y.forwardRef((s,i)=>{var o=s,{className:n}=o,a=V(o,["className"]);return y.createElement(Fu,m({ref:i,iconNode:t,className:nr(`lucide-${Ce(rr(e))}`,`lucide-${e}`,n)},a))});return r.displayName=rr(e),r};const Bu=De("arrow-up",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);const zu=De("check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);const Cn=De("chevron-down",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);const Ru=De("contrast",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 18a6 6 0 0 0 0-12v12z",key:"j4l70d"}]]);const ju=De("copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);const $u=De("ellipsis-vertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]);const Uu=De("file-spreadsheet",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M8 13h2",key:"yr2amv"}],["path",{d:"M14 13h2",key:"un5t4a"}],["path",{d:"M8 17h2",key:"2yhykz"}],["path",{d:"M14 17h2",key:"10kma7"}]]);const li=De("file-text",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]);const Hu=De("file-type",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M11 18h2",key:"12mj7e"}],["path",{d:"M12 12v6",key:"3ahymv"}],["path",{d:"M9 13v-.5a.5.5 0 0 1 .5-.5h5a.5.5 0 0 1 .5.5v.5",key:"qbrxap"}]]);const ui=De("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);const qu=De("log-out",[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]]);const Vu=De("menu",[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]]);const ci=De("paperclip",[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]]);const Wu=De("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);const In=De("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);var Ju=e=>Array.from(e).map(r=>r.getModelContext()).sort((r,n)=>{var a,i;return((a=n.priority)!=null?a:0)-((i=r.priority)!=null?i:0)}).reduce((r,n)=>{var a;if(n.system&&(r.system?r.system+=`
1
+ (function(U,p){typeof exports=="object"&&typeof module!="undefined"?p(exports,require("react/jsx-runtime"),require("react"),require("react-dom/client"),require("react-dom")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react","react-dom/client","react-dom"],p):(U=typeof globalThis!="undefined"?globalThis:U||self,p(U.CuadraUIKit={},U.React,U.React,U.ReactDOM,U.ReactDOM))})(this,(function(U,p,y,me,He){"use strict";var kv=Object.defineProperty,Sv=Object.defineProperties;var _v=Object.getOwnPropertyDescriptors;var kn=Object.getOwnPropertySymbols;var Pu=Object.prototype.hasOwnProperty,Nu=Object.prototype.propertyIsEnumerable;var si=(U,p)=>(p=Symbol[U])?p:Symbol.for("Symbol."+U),Lu=U=>{throw TypeError(U)},Du=Math.pow,oi=(U,p,y)=>p in U?kv(U,p,{enumerable:!0,configurable:!0,writable:!0,value:y}):U[p]=y,m=(U,p)=>{for(var y in p||(p={}))Pu.call(p,y)&&oi(U,y,p[y]);if(kn)for(var y of kn(p))Nu.call(p,y)&&oi(U,y,p[y]);return U},E=(U,p)=>Sv(U,_v(p));var V=(U,p)=>{var y={};for(var me in U)Pu.call(U,me)&&p.indexOf(me)<0&&(y[me]=U[me]);if(U!=null&&kn)for(var me of kn(U))p.indexOf(me)<0&&Nu.call(U,me)&&(y[me]=U[me]);return y};var C=(U,p,y)=>oi(U,typeof p!="symbol"?p+"":p,y),Ou=(U,p,y)=>p.has(U)||Lu("Cannot "+y);var Ge=(U,p,y)=>(Ou(U,p,"read from private field"),y?y.call(U):p.get(U)),er=(U,p,y)=>p.has(U)?Lu("Cannot add the same private member more than once"):p instanceof WeakSet?p.add(U):p.set(U,y),tr=(U,p,y,me)=>(Ou(U,p,"write to private field"),me?me.call(U,y):p.set(U,y),y);var P=(U,p,y)=>new Promise((me,He)=>{var Le=Ie=>{try{K(y.next(Ie))}catch(qe){He(qe)}},Xe=Ie=>{try{K(y.throw(Ie))}catch(qe){He(qe)}},K=Ie=>Ie.done?me(Ie.value):Promise.resolve(Ie.value).then(Le,Xe);K((y=y.apply(U,p)).next())}),Ee=function(U,p){this[0]=U,this[1]=p},Nr=(U,p,y)=>{var me=(Xe,K,Ie,qe)=>{try{var rr=y[Xe](K),nr=(K=rr.value)instanceof Ee,Tn=rr.done;Promise.resolve(nr?K[0]:K).then(ot=>nr?me(Xe==="return"?Xe:"next",K[1]?{done:ot.done,value:ot.value}:ot,Ie,qe):Ie({value:ot,done:Tn})).catch(ot=>me("throw",ot,Ie,qe))}catch(ot){qe(ot)}},He=Xe=>Le[Xe]=K=>new Promise((Ie,qe)=>me(Xe,K,Ie,qe)),Le={};return y=y.apply(U,p),Le[si("asyncIterator")]=()=>Le,He("next"),He("throw"),He("return"),Le};var Ft=(U,p,y)=>(p=U[si("asyncIterator")])?p.call(U):(U=U[si("iterator")](),p={},y=(me,He)=>(He=U[me])&&(p[me]=Le=>new Promise((Xe,K,Ie)=>(Le=He.call(U,Le),Ie=Le.done,Promise.resolve(Le.value).then(qe=>Xe({value:qe,done:Ie}),K)))),y("next"),y("return"),p);var st,Lt,Ze,Tu,Er,Cu,Ar,Mr,Pr,Iu,Eu;var Le=typeof document!="undefined"?document.currentScript:null;function Xe(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const K=Xe(y);const Ie=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),qe=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,r,n)=>n?n.toUpperCase():r.toLowerCase()),rr=e=>{const t=qe(e);return t.charAt(0).toUpperCase()+t.slice(1)},nr=(...e)=>e.filter((t,r,n)=>!!t&&t.trim()!==""&&n.indexOf(t)===r).join(" ").trim(),Tn=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0};var ot={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const Bu=y.forwardRef((u,l)=>{var d=u,{color:e="currentColor",size:t=24,strokeWidth:r=2,absoluteStrokeWidth:n,className:a="",children:i,iconNode:s}=d,o=V(d,["color","size","strokeWidth","absoluteStrokeWidth","className","children","iconNode"]);return y.createElement("svg",m(m(E(m({ref:l},ot),{width:t,height:t,stroke:e,strokeWidth:n?Number(r)*24/Number(t):r,className:nr("lucide",a)}),!i&&!Tn(o)&&{"aria-hidden":"true"}),o),[...s.map(([c,h])=>y.createElement(c,h)),...Array.isArray(i)?i:[i]])});const De=(e,t)=>{const r=y.forwardRef((s,i)=>{var o=s,{className:n}=o,a=V(o,["className"]);return y.createElement(Bu,m({ref:i,iconNode:t,className:nr(`lucide-${Ie(rr(e))}`,`lucide-${e}`,n)},a))});return r.displayName=rr(e),r};const zu=De("arrow-up",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);const Ru=De("check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);const Cn=De("chevron-down",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);const ju=De("contrast",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 18a6 6 0 0 0 0-12v12z",key:"j4l70d"}]]);const $u=De("copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);const Uu=De("ellipsis-vertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]);const Hu=De("file-spreadsheet",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M8 13h2",key:"yr2amv"}],["path",{d:"M14 13h2",key:"un5t4a"}],["path",{d:"M8 17h2",key:"2yhykz"}],["path",{d:"M14 17h2",key:"10kma7"}]]);const ui=De("file-text",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]);const qu=De("file-type",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M11 18h2",key:"12mj7e"}],["path",{d:"M12 12v6",key:"3ahymv"}],["path",{d:"M9 13v-.5a.5.5 0 0 1 .5-.5h5a.5.5 0 0 1 .5.5v.5",key:"qbrxap"}]]);const ci=De("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);const Vu=De("log-out",[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]]);const Wu=De("menu",[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]]);const di=De("paperclip",[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]]);const Ju=De("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);const In=De("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);var Yu=e=>Array.from(e).map(r=>r.getModelContext()).sort((r,n)=>{var a,i;return((a=n.priority)!=null?a:0)-((i=r.priority)!=null?i:0)}).reduce((r,n)=>{var a;if(n.system&&(r.system?r.system+=`
2
2
 
3
- ${n.system}`:r.system=n.system),n.tools)for(const[i,s]of Object.entries(n.tools)){const o=(a=r.tools)==null?void 0:a[i];if(o&&o!==s)throw new Error(`You tried to define a tool with the name ${i}, but it already exists.`);r.tools||(r.tools={}),r.tools[i]=s}return n.config&&(r.config=m(m({},r.config),n.config)),n.callSettings&&(r.callSettings=m(m({},r.callSettings),n.callSettings)),r},{}),En=class{constructor(){C(this,"_providers",new Set);C(this,"_subscribers",new Set)}getModelContext(){return Ju(this._providers)}registerModelContextProvider(e){var r;this._providers.add(e);const t=(r=e.subscribe)==null?void 0:r.call(e,()=>{this.notifySubscribers()});return this.notifySubscribers(),()=>{this._providers.delete(e),t==null||t(),this.notifySubscribers()}}notifySubscribers(){for(const e of this._subscribers)e()}subscribe(e){return this._subscribers.add(e),()=>this._subscribers.delete(e)}},An=class{constructor(){C(this,"_contextProvider",new En)}registerModelContextProvider(e){return this._contextProvider.registerModelContextProvider(e)}getModelContextProvider(){return this._contextProvider}},ar=class{constructor(){C(this,"_subscribers",new Set)}subscribe(e){return this._subscribers.add(e),()=>this._subscribers.delete(e)}waitForUpdate(){return new Promise(e=>{const t=this.subscribe(()=>{t(),e()})})}_notifySubscribers(){const e=[];for(const t of this._subscribers)try{t()}catch(r){e.push(r)}if(e.length>0)throw e.length===1?e[0]:new AggregateError(e)}},Yu=e=>e.status.type==="complete",di=class extends ar{constructor(){super(...arguments);C(this,"isEditing",!0);C(this,"_attachments",[]);C(this,"_text","");C(this,"_role","user");C(this,"_runConfig",{});C(this,"_eventSubscribers",new Map)}get attachmentAccept(){var t,r;return(r=(t=this.getAttachmentAdapter())==null?void 0:t.accept)!=null?r:"*"}get attachments(){return this._attachments}setAttachments(t){this._attachments=t,this._notifySubscribers()}get isEmpty(){return!this.text.trim()&&!this.attachments.length}get text(){return this._text}get role(){return this._role}get runConfig(){return this._runConfig}setText(t){this._text!==t&&(this._text=t,this._notifySubscribers())}setRole(t){this._role!==t&&(this._role=t,this._notifySubscribers())}setRunConfig(t){this._runConfig!==t&&(this._runConfig=t,this._notifySubscribers())}_emptyTextAndAttachments(){this._attachments=[],this._text="",this._notifySubscribers()}_onClearAttachments(){return P(this,null,function*(){const t=this.getAttachmentAdapter();t&&(yield Promise.all(this._attachments.map(r=>t.remove(r))))})}reset(){return P(this,null,function*(){if(this._attachments.length===0&&this._text===""&&this._role==="user"&&Object.keys(this._runConfig).length===0)return;this._role="user",this._runConfig={};const t=this._onClearAttachments();this._emptyTextAndAttachments(),yield t})}clearAttachments(){return P(this,null,function*(){const t=this._onClearAttachments();this.setAttachments([]),yield t})}send(){return P(this,null,function*(){const t=this.getAttachmentAdapter(),r=t&&this.attachments.length>0?Promise.all(this.attachments.map(i=>P(this,null,function*(){return Yu(i)?i:yield t.send(i)}))):[],n=this.text;this._emptyTextAndAttachments();const a={createdAt:new Date,role:this.role,content:n?[{type:"text",text:n}]:[],attachments:yield r,runConfig:this.runConfig,metadata:{custom:{}}};this.handleSend(a),this._notifyEventSubscribers("send")})}cancel(){this.handleCancel()}addAttachment(t){return P(this,null,function*(){const r=this.getAttachmentAdapter();if(!r)throw new Error("Attachments are not supported");const n=u=>{const d=this._attachments.findIndex(c=>c.id===u.id);d!==-1?this._attachments=[...this._attachments.slice(0,d),u,...this._attachments.slice(d+1)]:this._attachments=[...this._attachments,u],this._notifySubscribers()},a=r.add({file:t});if(Symbol.asyncIterator in a)try{for(var i=Ft(a),s,o,l;s=!(o=yield i.next()).done;s=!1){const u=o.value;n(u)}}catch(o){l=[o]}finally{try{s&&(o=i.return)&&(yield o.call(i))}finally{if(l)throw l[0]}}else n(yield a);this._notifyEventSubscribers("attachment-add"),this._notifySubscribers()})}removeAttachment(t){return P(this,null,function*(){const r=this.getAttachmentAdapter();if(!r)throw new Error("Attachments are not supported");const n=this._attachments.findIndex(i=>i.id===t);if(n===-1)throw new Error("Attachment not found");const a=this._attachments[n];yield r.remove(a),this._attachments=[...this._attachments.slice(0,n),...this._attachments.slice(n+1)],this._notifySubscribers()})}_notifyEventSubscribers(t){const r=this._eventSubscribers.get(t);if(r)for(const n of r)n()}unstable_on(t,r){const n=this._eventSubscribers.get(t);return n?n.add(r):this._eventSubscribers.set(t,new Set([r])),()=>{const a=this._eventSubscribers.get(t);a&&a.delete(r)}}},hi=class extends di{constructor(t){super();C(this,"_canCancel",!1);this.runtime=t,this.connect()}get canCancel(){return this._canCancel}get attachments(){return super.attachments}getAttachmentAdapter(){var t;return(t=this.runtime.adapters)==null?void 0:t.attachments}connect(){return this.runtime.subscribe(()=>{this.canCancel!==this.runtime.capabilities.cancel&&(this._canCancel=this.runtime.capabilities.cancel,this._notifySubscribers())})}handleSend(t){return P(this,null,function*(){var r,n;this.runtime.append(E(m({},t),{parentId:(n=(r=this.runtime.messages.at(-1))==null?void 0:r.id)!=null?n:null,sourceId:null}))})}handleCancel(){return P(this,null,function*(){this.runtime.cancelRun()})}};let fi=(e,t=21)=>(r=t)=>{let n="",a=r|0;for(;a--;)n+=e[Math.random()*e.length|0];return n};var _t=fi("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),Ku="__optimistic__",Gu=()=>`${Ku}${_t()}`,ir=Symbol("autoStatus"),Xu=Object.freeze(Object.assign({type:"running"},{[ir]:!0})),Qu=Object.freeze(Object.assign({type:"complete",reason:"unknown"},{[ir]:!0})),Zu=Object.freeze(Object.assign({type:"requires-action",reason:"tool-calls"},{[ir]:!0})),ec=Object.freeze(Object.assign({type:"requires-action",reason:"interrupt"},{[ir]:!0})),pi=(e,t,r,n,a)=>e&&a?Object.assign({type:"incomplete",reason:"error",error:a},{[ir]:!0}):e&&t?Xu:r?ec:n?Zu:Qu;function Nr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Tt={exports:{}},mi;function tc(){if(mi)return Tt.exports;mi=1;const e=typeof Buffer!="undefined",t=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,r=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function n(o,l,u){u==null&&l!==null&&typeof l=="object"&&(u=l,l=void 0),e&&Buffer.isBuffer(o)&&(o=o.toString()),o&&o.charCodeAt(0)===65279&&(o=o.slice(1));const d=JSON.parse(o,l);if(d===null||typeof d!="object")return d;const c=u&&u.protoAction||"error",h=u&&u.constructorAction||"error";if(c==="ignore"&&h==="ignore")return d;if(c!=="ignore"&&h!=="ignore"){if(t.test(o)===!1&&r.test(o)===!1)return d}else if(c!=="ignore"&&h==="ignore"){if(t.test(o)===!1)return d}else if(r.test(o)===!1)return d;return a(d,{protoAction:c,constructorAction:h,safe:u&&u.safe})}function a(o,{protoAction:l="error",constructorAction:u="error",safe:d}={}){let c=[o];for(;c.length;){const h=c;c=[];for(const f of h){if(l!=="ignore"&&Object.prototype.hasOwnProperty.call(f,"__proto__")){if(d===!0)return null;if(l==="error")throw new SyntaxError("Object contains forbidden prototype property");delete f.__proto__}if(u!=="ignore"&&Object.prototype.hasOwnProperty.call(f,"constructor")&&f.constructor!==null&&typeof f.constructor=="object"&&Object.prototype.hasOwnProperty.call(f.constructor,"prototype")){if(d===!0)return null;if(u==="error")throw new SyntaxError("Object contains forbidden prototype property");delete f.constructor}for(const g in f){const v=f[g];v&&typeof v=="object"&&c.push(v)}}}return o}function i(o,l,u){const{stackTraceLimit:d}=Error;Error.stackTraceLimit=0;try{return n(o,l,u)}finally{Error.stackTraceLimit=d}}function s(o,l){const{stackTraceLimit:u}=Error;Error.stackTraceLimit=0;try{return n(o,l,{safe:!0})}catch(d){return}finally{Error.stackTraceLimit=u}}return Tt.exports=i,Tt.exports.default=i,Tt.exports.parse=i,Tt.exports.safeParse=s,Tt.exports.scan=a,Tt.exports}var rc=tc();const Mn=Nr(rc);function nc(e){const t=["ROOT"];let r=-1,n=null;const a=[];let i;function s(){i!==void 0&&(a.push(JSON.parse(`"${i}"`)),i=void 0)}function o(c,h,f){switch(c){case'"':{r=h,t.pop(),t.push(f),t.push("INSIDE_STRING"),s();break}case"f":case"t":case"n":{r=h,n=h,t.pop(),t.push(f),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(f),t.push("INSIDE_NUMBER"),s();break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=h,t.pop(),t.push(f),t.push("INSIDE_NUMBER"),s();break}case"{":{r=h,t.pop(),t.push(f),t.push("INSIDE_OBJECT_START"),s();break}case"[":{r=h,t.pop(),t.push(f),t.push("INSIDE_ARRAY_START"),s();break}}}function l(c,h){switch(c){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=h,t.pop(),i=a.pop();break}}}function u(c,h){switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA"),i=(Number(i)+1).toString();break}case"]":{r=h,t.pop(),i=a.pop();break}}}for(let c=0;c<e.length;c++){const h=e[c];switch(t[t.length-1]){case"ROOT":o(h,c,"FINISH");break;case"INSIDE_OBJECT_START":{switch(h){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY"),i="";break}case"}":{r=c,t.pop(),i=a.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(h){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY"),i="";break}}break}case"INSIDE_OBJECT_KEY":{switch(h){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}case"\\":{t.push("INSIDE_STRING_ESCAPE"),i+=h;break}default:{i+=h;break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(h){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(h,c,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{l(h,c);break}case"INSIDE_STRING":{switch(h){case'"':{t.pop(),r=c,i=a.pop();break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:r=c}break}case"INSIDE_ARRAY_START":{switch(h){case"]":{r=c,t.pop(),i=a.pop();break}default:{r=c,i="0",o(h,c,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(h){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA"),i=(Number(i)+1).toString();break}case"]":{r=c,t.pop(),i=a.pop();break}default:{r=c;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(h,c,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),t[t.length-1]==="INSIDE_STRING"?r=c:t[t.length-1]==="INSIDE_OBJECT_KEY"&&(i+=h);break}case"INSIDE_NUMBER":{switch(h){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=c;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),i=a.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(h,c),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&l(h,c);break}case"}":{t.pop(),i=a.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&l(h,c);break}case"]":{t.pop(),i=a.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(h,c);break}default:{t.pop(),i=a.pop();break}}break}case"INSIDE_LITERAL":{const g=e.substring(n,c+1);!"false".startsWith(g)&&!"true".startsWith(g)&&!"null".startsWith(g)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?l(h,c):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(h,c)):r=c;break}}}let d=e.slice(0,r+1);for(let c=t.length-1;c>=0;c--)switch(t[c]){case"INSIDE_STRING":{d+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{d+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{d+="]";break}case"INSIDE_LITERAL":{const f=e.substring(n,e.length);"true".startsWith(f)?d+="true".slice(f.length):"false".startsWith(f)?d+="false".slice(f.length):"null".startsWith(f)&&(d+="null".slice(f.length))}}return[d,a]}var Lr=Symbol("aui.parse-partial-json-object.meta"),ac=e=>e==null?void 0:e[Lr],Dr=e=>{if(e.length===0)return{[Lr]:{state:"partial",partialPath:[]}};try{const t=Mn.parse(e);if(typeof t!="object"||t===null)throw new Error("argsText is expected to be an object");return t[Lr]={state:"complete",partialPath:[]},t}catch(t){try{const[r,n]=nc(e),a=Mn.parse(r);if(typeof a!="object"||a===null)throw new Error("argsText is expected to be an object");return a[Lr]={state:"partial",partialPath:n},a}catch(r){return}}},gi=(e,t,r)=>{if(typeof e!="object"||e===null)return t.state;if(t.state==="complete")return"complete";if(r.length===0)return t.state;const[n,...a]=r;if(!Object.prototype.hasOwnProperty.call(e,n))return"partial";const[i,...s]=t.partialPath;if(n!==i)return"complete";const o=e[n];return gi(o,{state:"partial",partialPath:s},a)},Bt=(e,t)=>{const r=ac(e);if(!r)throw new Error("unable to determine object state");return gi(e,r,t.map(String))};function ic(){return Pr(this,null,function*(){const e=this.getReader();try{for(;;){const{done:t,value:r}=yield new Ne(e.read());if(t)break;yield r}}finally{e.releaseLock()}})}function Pn(e){var t,r;return(r=e[t=Symbol.asyncIterator])!=null||(e[t]=ic),e}var Nn={toResponse(e,t){var r;return new Response(Nn.toByteStream(e,t),{headers:(r=t.headers)!=null?r:{}})},fromResponse(e,t){return Nn.fromByteStream(e.body,t)},toByteStream(e,t){return e.pipeThrough(t)},fromByteStream(e,t){return e.pipeThrough(t)}},Ln=function(){let e,t;const r=new Promise((n,a)=>{e=n,t=a});if(!e||!t)throw new Error("Failed to create promise");return{promise:r,resolve:e,reject:t}},sc=()=>{const e=[];let t=!1,r,n;const a=s=>{s.promise||(s.promise=s.reader.read().then(({done:o,value:l})=>{s.promise=void 0,o?(e.splice(e.indexOf(s),1),t&&e.length===0&&r.close()):r.enqueue(l),n==null||n.resolve(),n=void 0}).catch(o=>{console.error(o),e.forEach(l=>{l.reader.cancel()}),e.length=0,r.error(o),n==null||n.reject(o),n=void 0}))};return{readable:new ReadableStream({start(s){r=s},pull(){return n=Ln(),e.forEach(s=>{a(s)}),n.promise},cancel(){e.forEach(s=>{s.reader.cancel()}),e.length=0}}),isSealed(){return t},seal(){t=!0,e.length===0&&r.close()},addStream(s){if(t)throw new Error("Cannot add streams after the run callback has settled.");const o={reader:s.getReader()};e.push(o),a(o)},enqueue(s){this.addStream(new ReadableStream({start(o){o.enqueue(s),o.close()}}))}}},yi=class{constructor(e){C(this,"_controller");C(this,"_isClosed",!1);this._controller=e}append(e){return this._controller.enqueue({type:"text-delta",path:[],textDelta:e}),this}close(){this._isClosed||(this._isClosed=!0,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())}},bi=e=>new ReadableStream({start(t){var r;return(r=e.start)==null?void 0:r.call(e,new yi(t))},pull(t){var r;return(r=e.pull)==null?void 0:r.call(e,new yi(t))},cancel(t){var r;return(r=e.cancel)==null?void 0:r.call(e,t)}}),wi=()=>{let e;return[bi({start(r){e=r}}),e]},xi=class{constructor(e){C(this,"_isClosed",!1);C(this,"_mergeTask");C(this,"_argsTextController");this._controller=e;const t=bi({start:n=>{this._argsTextController=n}});let r=!1;this._mergeTask=t.pipeTo(new WritableStream({write:n=>{switch(n.type){case"text-delta":r=!0,this._controller.enqueue(n);break;case"part-finish":r||this._controller.enqueue({type:"text-delta",textDelta:"{}",path:[]}),this._controller.enqueue({type:"tool-call-args-text-finish",path:[]});break;default:throw new Error(`Unexpected chunk type: ${n.type}`)}}}))}get argsText(){return this._argsTextController}setResponse(e){return P(this,null,function*(){var t;this._argsTextController.close(),yield Promise.resolve(),this._controller.enqueue(E(m({type:"result",path:[]},e.artifact!==void 0?{artifact:e.artifact}:{}),{result:e.result,isError:(t=e.isError)!=null?t:!1}))})}close(){return P(this,null,function*(){this._isClosed||(this._isClosed=!0,this._argsTextController.close(),yield this._mergeTask,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())})}},oc=e=>new ReadableStream({start(t){var r;return(r=e.start)==null?void 0:r.call(e,new xi(t))},pull(t){var r;return(r=e.pull)==null?void 0:r.call(e,new xi(t))},cancel(t){var r;return(r=e.cancel)==null?void 0:r.call(e,t)}}),lc=()=>{let e;return[oc({start(r){e=r}}),e]},vi=class{constructor(){C(this,"value",-1)}up(){return++this.value}},uc=class extends TransformStream{constructor(e){super({transform(t,r){r.enqueue(E(m({},t),{path:[e,...t.path]}))}})}};(class extends TransformStream{constructor(e){super({transform(t,r){const{path:[n,...a]}=t;if(e!==n)throw new Error(`Path mismatch: expected ${e}, got ${n}`);r.enqueue(E(m({},t),{path:a}))}})}});var cc=class extends TransformStream{constructor(e){const t=new vi,r=new Map;super({transform(n,a){n.type==="part-start"&&n.path.length===0&&r.set(t.up(),e.up());const[i,...s]=n.path;if(i===void 0){a.enqueue(n);return}const o=r.get(i);if(o===void 0)throw new Error("Path not found");a.enqueue(E(m({},n),{path:[o,...s]}))}})}},ki=class extends TransformStream{constructor(e){super();const t=e(super.readable);Object.defineProperty(this,"readable",{value:t,writable:!1})}},Si=class extends TransformStream{constructor(){const e=[];super({transform(t,r){if(t.type==="part-start"){if(t.path.length!==0){r.error(new Error("Nested parts are not supported"));return}e.push(t.part),r.enqueue(t);return}if(t.type==="text-delta"||t.type==="result"||t.type==="part-finish"||t.type==="tool-call-args-text-finish"){if(t.path.length!==1){r.error(new Error(`${t.type} chunks must have a path of length 1`));return}const n=t.path[0];if(n<0||n>=e.length){r.error(new Error(`Invalid path index: ${n}`));return}const a=e[n];r.enqueue(E(m({},t),{meta:a}));return}r.enqueue(t)}})}},_i=fi("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),dc=class Ou{constructor(t){C(this,"_state");C(this,"_parentId");this._state=t||{merger:sc(),contentCounter:new vi}}get __internal_isClosed(){return this._state.merger.isSealed()}__internal_getReadable(){return this._state.merger.readable}__internal_subscribeToClose(t){this._state.closeSubscriber=t}_addPart(t,r){this._state.append&&(this._state.append.controller.close(),this._state.append=void 0),this.enqueue({type:"part-start",part:t,path:[]}),this._state.merger.addStream(r.pipeThrough(new uc(this._state.contentCounter.value)))}merge(t){this._state.merger.addStream(t.pipeThrough(new cc(this._state.contentCounter)))}appendText(t){var r;((r=this._state.append)==null?void 0:r.kind)!=="text"&&(this._state.append={kind:"text",controller:this.addTextPart()}),this._state.append.controller.append(t)}appendReasoning(t){var r;((r=this._state.append)==null?void 0:r.kind)!=="reasoning"&&(this._state.append={kind:"reasoning",controller:this.addReasoningPart()}),this._state.append.controller.append(t)}addTextPart(){const[t,r]=wi();return this._addPart({type:"text"},t),r}addReasoningPart(){const[t,r]=wi();return this._addPart({type:"reasoning"},t),r}addToolCallPart(t){var o;const r=typeof t=="string"?{toolName:t}:t,n=r.toolName,a=(o=r.toolCallId)!=null?o:_i(),[i,s]=lc();return this._addPart(m({type:"tool-call",toolName:n,toolCallId:a},this._parentId&&{parentId:this._parentId}),i),r.argsText!==void 0&&(s.argsText.append(r.argsText),s.argsText.close()),r.args!==void 0&&(s.argsText.append(JSON.stringify(r.args)),s.argsText.close()),r.response!==void 0&&s.setResponse(r.response),s}appendSource(t){this._addPart(m(m({},t),this._parentId&&{parentId:this._parentId}),new ReadableStream({start(r){r.enqueue({type:"part-finish",path:[]}),r.close()}}))}appendFile(t){this._addPart(t,new ReadableStream({start(r){r.enqueue({type:"part-finish",path:[]}),r.close()}}))}enqueue(t){this._state.merger.enqueue(t),t.type==="part-start"&&t.path.length===0&&this._state.contentCounter.up()}withParentId(t){const r=new Ou(this._state);return r._parentId=t,r}close(){var t,r,n,a;(r=(t=this._state.append)==null?void 0:t.controller)==null||r.close(),this._state.merger.seal(),(a=(n=this._state).closeSubscriber)==null||a.call(n)}};function hc(e){const t=new dc;return P(null,null,function*(){try{yield e(t)}catch(n){throw t.__internal_isClosed||t.enqueue({type:"error",path:[],error:String(n)}),n}finally{t.__internal_isClosed||t.close()}}),t.__internal_getReadable()}function Ti(){const{resolve:e,promise:t}=Ln();let r;return[hc(a=>(r=a,r.__internal_subscribeToClose(e),t)),r]}var fc=class extends TransformStream{constructor(e,t,r){const[n,a]=Ti();let i;super({start(o){var l;return i=n.pipeTo(new WritableStream({write(u){o.enqueue(u)},abort(u){o.error(u)},close(){o.terminate()}})).catch(u=>{o.error(u)}),(l=e.start)==null?void 0:l.call(e,a)},transform(o){var l;return(l=e.transform)==null?void 0:l.call(e,o,a)},flush(){return P(this,null,function*(){var o;yield(o=e.flush)==null?void 0:o.call(e,a),a.close(),yield i})}},t,r)}},sr=(e,t,r)=>{var h,f,g,v,b,w,T;const{role:n,id:a,createdAt:i,attachments:s,status:o,metadata:l}=e,u={id:a!=null?a:t,createdAt:i!=null?i:new Date},d=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content,c=z=>{var I=z,{image:_}=I,D=V(I,["image"]);return _.match(/^data:image\/(png|jpeg|jpg|gif|webp);base64,(.*)$/)?E(m({},D),{image:_}):(console.warn("Invalid image data format detected"),null)};if(n!=="user"&&(s!=null&&s.length))throw new Error("attachments are only supported for user messages");if(n!=="assistant"&&o)throw new Error("status is only supported for assistant messages");if(n!=="assistant"&&(l!=null&&l.steps))throw new Error("metadata.steps is only supported for assistant messages");switch(n){case"assistant":return E(m({},u),{role:n,content:d.map(_=>{var I,B,H,j,S;const D=_.type;switch(D){case"text":case"reasoning":return _.text.trim().length===0?null:_;case"file":case"source":return _;case"image":return c(_);case"data":return _;case"tool-call":{const z=_,{parentId:N,messages:M}=z,U=V(z,["parentId","messages"]),R=m(m(E(m({},U),{toolCallId:(I=_.toolCallId)!=null?I:`tool-${_t()}`}),N!==void 0&&{parentId:N}),M!==void 0&&{messages:M});return _.args?E(m({},R),{args:_.args,argsText:(B=_.argsText)!=null?B:JSON.stringify(_.args)}):E(m({},R),{args:(j=Dr((H=_.argsText)!=null?H:""))!=null?j:{},argsText:(S=_.argsText)!=null?S:""})}default:{const N=D;throw new Error(`Unsupported assistant message part type: ${N}`)}}}).filter(_=>!!_),status:o!=null?o:r,metadata:m({unstable_state:(h=l==null?void 0:l.unstable_state)!=null?h:null,unstable_annotations:(f=l==null?void 0:l.unstable_annotations)!=null?f:[],unstable_data:(g=l==null?void 0:l.unstable_data)!=null?g:[],custom:(v=l==null?void 0:l.custom)!=null?v:{},steps:(b=l==null?void 0:l.steps)!=null?b:[]},(l==null?void 0:l.submittedFeedback)&&{submittedFeedback:l.submittedFeedback})});case"user":return E(m({},u),{role:n,content:d.map(_=>{const D=_.type;switch(D){case"text":case"image":case"audio":case"file":return _;default:{const z=D;throw new Error(`Unsupported user message part type: ${z}`)}}}),attachments:s!=null?s:[],metadata:{custom:(w=l==null?void 0:l.custom)!=null?w:{}}});case"system":if(d.length!==1||d[0].type!=="text")throw new Error("System messages must have exactly one text message part.");return E(m({},u),{role:n,content:d,metadata:{custom:(T=l==null?void 0:l.custom)!=null?T:{}}});default:{const _=n;throw new Error(`Unknown message role: ${_}`)}}},Dn={fromArray:e=>{const t=e.map(r=>sr(r,_t(),pi(!1,!1,!1,!1,void 0)));return{messages:t.map((r,n)=>({parentId:n>0?t[n-1].id:null,message:r}))}}},Or=e=>e.next?Or(e.next):"current"in e?e:null,pc=class{constructor(e){C(this,"_value",null);this.func=e}get value(){return this._value===null&&(this._value=this.func()),this._value}dirty(){this._value=null}},Ci=class{constructor(){C(this,"messages",new Map);C(this,"head",null);C(this,"root",{children:[],next:null});C(this,"_messages",new pc(()=>{var t,r;const e=new Array(((r=(t=this.head)==null?void 0:t.level)!=null?r:-1)+1);for(let n=this.head;n;n=n.prev)e[n.level]=n.current;return e}))}updateLevels(e,t){e.level=t;for(const r of e.children){const n=this.messages.get(r);n&&this.updateLevels(n,t+1)}}performOp(e,t,r){var i;const n=(i=t.prev)!=null?i:this.root,a=e!=null?e:this.root;if(!(r==="relink"&&n===a)){if(r!=="link"&&(n.children=n.children.filter(s=>s!==t.current.id),n.next===t)){const s=n.children.at(-1),o=s?this.messages.get(s):null;if(o===void 0)throw new Error("MessageRepository(performOp/cut): Fallback sibling message not found. This is likely an internal bug in assistant-ui.");n.next=o}if(r!=="cut"){for(let o=e;o;o=o.prev)if(o.current.id===t.current.id)throw new Error("MessageRepository(performOp/link): A message with the same id already exists in the parent tree. This error occurs if the same message id is found multiple times. This is likely an internal bug in assistant-ui.");a.children=[...a.children,t.current.id],(Or(t)===this.head||a.next===null)&&(a.next=t),t.prev=e;const s=e?e.level+1:0;this.updateLevels(t,s)}}}get headId(){var e,t;return(t=(e=this.head)==null?void 0:e.current.id)!=null?t:null}getMessages(e){var n;if(e===void 0||e===((n=this.head)==null?void 0:n.current.id))return this._messages.value;const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(getMessages): Head message not found. This is likely an internal bug in assistant-ui.");const r=new Array(t.level+1);for(let a=t;a;a=a.prev)r[a.level]=a.current;return r}addOrUpdateMessage(e,t){const r=this.messages.get(t.id),n=e?this.messages.get(e):null;if(n===void 0)throw new Error("MessageRepository(addOrUpdateMessage): Parent message not found. This is likely an internal bug in assistant-ui.");if(r){r.current=t,this.performOp(n,r,"relink"),this._messages.dirty();return}const a={prev:n,current:t,next:null,children:[],level:n?n.level+1:0};this.messages.set(t.id,a),this.performOp(n,a,"link"),this.head===n&&(this.head=a),this._messages.dirty()}getMessage(e){var r,n;const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(updateMessage): Message not found. This is likely an internal bug in assistant-ui.");return{parentId:(n=(r=t.prev)==null?void 0:r.current.id)!=null?n:null,message:t.current,index:t.level}}appendOptimisticMessage(e,t){let r;do r=Gu();while(this.messages.has(r));return this.addOrUpdateMessage(e,sr(t,r,{type:"running"})),r}deleteMessage(e,t){const r=this.messages.get(e);if(!r)throw new Error("MessageRepository(deleteMessage): Message not found. This is likely an internal bug in assistant-ui.");const n=t===void 0?r.prev:t===null?null:this.messages.get(t);if(n===void 0)throw new Error("MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui.");for(const a of r.children){const i=this.messages.get(a);if(!i)throw new Error("MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui.");this.performOp(n,i,"relink")}this.performOp(null,r,"cut"),this.messages.delete(e),this.head===r&&(this.head=Or(n!=null?n:this.root)),this._messages.dirty()}getBranches(e){var n;const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(getBranches): Message not found. This is likely an internal bug in assistant-ui.");const{children:r}=(n=t.prev)!=null?n:this.root;return r}switchToBranch(e){var n;const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(switchToBranch): Branch not found. This is likely an internal bug in assistant-ui.");const r=(n=t.prev)!=null?n:this.root;r.next=t,this.head=Or(t),this._messages.dirty()}resetHead(e){if(e===null){this.clear();return}const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(resetHead): Branch not found. This is likely an internal bug in assistant-ui.");if(t.children.length>0){const r=n=>{for(const a of n.children){const i=this.messages.get(a);i&&(r(i),this.messages.delete(a))}};r(t),t.children=[],t.next=null}this.head=t;for(let r=t;r;r=r.prev)r.prev&&(r.prev.next=r);this._messages.dirty()}clear(){this.messages.clear(),this.head=null,this.root={children:[],next:null},this._messages.dirty()}export(){var t,r,n,a;const e=[];for(const[,i]of this.messages)e.push({message:i.current,parentId:(r=(t=i.prev)==null?void 0:t.current.id)!=null?r:null});return{headId:(a=(n=this.head)==null?void 0:n.current.id)!=null?a:null,messages:e}}import({headId:e,messages:t}){var r,n;for(const{message:a,parentId:i}of t)this.addOrUpdateMessage(i,a);this.resetHead((n=e!=null?e:(r=t.at(-1))==null?void 0:r.message.id)!=null?n:null)}},Fr=class{constructor(){C(this,"_subscriptions",new Set);C(this,"_connection")}get isConnected(){return!!this._connection}notifySubscribers(){for(const e of this._subscriptions)e()}_updateConnection(){var e;if(this._subscriptions.size>0){if(this._connection)return;this._connection=this._connect()}else(e=this._connection)==null||e.call(this),this._connection=void 0}subscribe(e){return this._subscriptions.add(e),this._updateConnection(),()=>{this._subscriptions.delete(e),this._updateConnection()}}},et=Symbol("skip-update"),On=class extends Fr{constructor(t){super();C(this,"_previousStateDirty",!0);C(this,"_previousState");C(this,"getState",()=>{if(!this.isConnected||this._previousStateDirty){const t=this.binding.getState();t!==et&&(this._previousState=t),this._previousStateDirty=!1}if(this._previousState===void 0)throw new Error("Entry not available in the store");return this._previousState});this.binding=t}get path(){return this.binding.path}_connect(){const t=()=>{this._previousStateDirty=!0,this.notifySubscribers()};return this.binding.subscribe(t)}},Br=class{constructor(e,t){this._core=e,this._threadListBinding=t,this.__internal_bindMethods()}get path(){return this._core.path}__internal_bindMethods(){this.switchTo=this.switchTo.bind(this),this.rename=this.rename.bind(this),this.archive=this.archive.bind(this),this.unarchive=this.unarchive.bind(this),this.delete=this.delete.bind(this),this.initialize=this.initialize.bind(this),this.generateTitle=this.generateTitle.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getState=this.getState.bind(this),this.detach=this.detach.bind(this)}getState(){return this._core.getState()}switchTo(){const e=this._core.getState();return this._threadListBinding.switchToThread(e.id)}rename(e){const t=this._core.getState();return this._threadListBinding.rename(t.id,e)}archive(){const e=this._core.getState();return this._threadListBinding.archive(e.id)}unarchive(){const e=this._core.getState();return this._threadListBinding.unarchive(e.id)}delete(){const e=this._core.getState();return this._threadListBinding.delete(e.id)}initialize(){const e=this._core.getState();return this._threadListBinding.initialize(e.id)}generateTitle(){const e=this._core.getState();return this._threadListBinding.generateTitle(e.id)}unstable_on(e,t){let r=this._core.getState().isMain,n=this._core.getState().id;return this.subscribe(()=>{const a=this._core.getState(),i=a.isMain,s=a.id;r===i&&n===s||(r=i,n=s,!(e==="switched-to"&&!i)&&(e==="switched-away"&&i||t()))})}subscribe(e){return this._core.subscribe(e)}detach(){const e=this._core.getState();this._threadListBinding.detach(e.id)}__internal_getRuntime(){return this}};function mc(e,t){if(e===void 0&&t===void 0)return!0;if(e===void 0||t===void 0)return!1;for(const r of Object.keys(e)){const n=e[r],a=t[r];if(!Object.is(n,a))return!1}return!0}var tt=class extends Fr{constructor(t){super();C(this,"_previousState");C(this,"getState",()=>(this.isConnected||this._syncState(),this._previousState));this.binding=t;const r=t.getState();if(r===et)throw new Error("Entry not available in the store");this._previousState=r}get path(){return this.binding.path}_syncState(){const t=this.binding.getState();return t===et||mc(t,this._previousState)?!1:(this._previousState=t,!0)}_connect(){const t=()=>{this._syncState()&&this.notifySubscribers()};return this.binding.subscribe(t)}},zr=Symbol("innerMessage"),Rr=e=>e.content.filter(r=>r.type==="text").map(r=>r.text).join(`
3
+ ${n.system}`:r.system=n.system),n.tools)for(const[i,s]of Object.entries(n.tools)){const o=(a=r.tools)==null?void 0:a[i];if(o&&o!==s)throw new Error(`You tried to define a tool with the name ${i}, but it already exists.`);r.tools||(r.tools={}),r.tools[i]=s}return n.config&&(r.config=m(m({},r.config),n.config)),n.callSettings&&(r.callSettings=m(m({},r.callSettings),n.callSettings)),r},{}),En=class{constructor(){C(this,"_providers",new Set);C(this,"_subscribers",new Set)}getModelContext(){return Yu(this._providers)}registerModelContextProvider(e){var r;this._providers.add(e);const t=(r=e.subscribe)==null?void 0:r.call(e,()=>{this.notifySubscribers()});return this.notifySubscribers(),()=>{this._providers.delete(e),t==null||t(),this.notifySubscribers()}}notifySubscribers(){for(const e of this._subscribers)e()}subscribe(e){return this._subscribers.add(e),()=>this._subscribers.delete(e)}},An=class{constructor(){C(this,"_contextProvider",new En)}registerModelContextProvider(e){return this._contextProvider.registerModelContextProvider(e)}getModelContextProvider(){return this._contextProvider}},ar=class{constructor(){C(this,"_subscribers",new Set)}subscribe(e){return this._subscribers.add(e),()=>this._subscribers.delete(e)}waitForUpdate(){return new Promise(e=>{const t=this.subscribe(()=>{t(),e()})})}_notifySubscribers(){const e=[];for(const t of this._subscribers)try{t()}catch(r){e.push(r)}if(e.length>0)throw e.length===1?e[0]:new AggregateError(e)}},Ku=e=>e.status.type==="complete",hi=class extends ar{constructor(){super(...arguments);C(this,"isEditing",!0);C(this,"_attachments",[]);C(this,"_text","");C(this,"_role","user");C(this,"_runConfig",{});C(this,"_eventSubscribers",new Map)}get attachmentAccept(){var t,r;return(r=(t=this.getAttachmentAdapter())==null?void 0:t.accept)!=null?r:"*"}get attachments(){return this._attachments}setAttachments(t){this._attachments=t,this._notifySubscribers()}get isEmpty(){return!this.text.trim()&&!this.attachments.length}get text(){return this._text}get role(){return this._role}get runConfig(){return this._runConfig}setText(t){this._text!==t&&(this._text=t,this._notifySubscribers())}setRole(t){this._role!==t&&(this._role=t,this._notifySubscribers())}setRunConfig(t){this._runConfig!==t&&(this._runConfig=t,this._notifySubscribers())}_emptyTextAndAttachments(){this._attachments=[],this._text="",this._notifySubscribers()}_onClearAttachments(){return P(this,null,function*(){const t=this.getAttachmentAdapter();t&&(yield Promise.all(this._attachments.map(r=>t.remove(r))))})}reset(){return P(this,null,function*(){if(this._attachments.length===0&&this._text===""&&this._role==="user"&&Object.keys(this._runConfig).length===0)return;this._role="user",this._runConfig={};const t=this._onClearAttachments();this._emptyTextAndAttachments(),yield t})}clearAttachments(){return P(this,null,function*(){const t=this._onClearAttachments();this.setAttachments([]),yield t})}send(){return P(this,null,function*(){const t=this.getAttachmentAdapter(),r=t&&this.attachments.length>0?Promise.all(this.attachments.map(i=>P(this,null,function*(){return Ku(i)?i:yield t.send(i)}))):[],n=this.text;this._emptyTextAndAttachments();const a={createdAt:new Date,role:this.role,content:n?[{type:"text",text:n}]:[],attachments:yield r,runConfig:this.runConfig,metadata:{custom:{}}};this.handleSend(a),this._notifyEventSubscribers("send")})}cancel(){this.handleCancel()}addAttachment(t){return P(this,null,function*(){const r=this.getAttachmentAdapter();if(!r)throw new Error("Attachments are not supported");const n=u=>{const d=this._attachments.findIndex(c=>c.id===u.id);d!==-1?this._attachments=[...this._attachments.slice(0,d),u,...this._attachments.slice(d+1)]:this._attachments=[...this._attachments,u],this._notifySubscribers()},a=r.add({file:t});if(Symbol.asyncIterator in a)try{for(var i=Ft(a),s,o,l;s=!(o=yield i.next()).done;s=!1){const u=o.value;n(u)}}catch(o){l=[o]}finally{try{s&&(o=i.return)&&(yield o.call(i))}finally{if(l)throw l[0]}}else n(yield a);this._notifyEventSubscribers("attachment-add"),this._notifySubscribers()})}removeAttachment(t){return P(this,null,function*(){const r=this.getAttachmentAdapter();if(!r)throw new Error("Attachments are not supported");const n=this._attachments.findIndex(i=>i.id===t);if(n===-1)throw new Error("Attachment not found");const a=this._attachments[n];yield r.remove(a),this._attachments=[...this._attachments.slice(0,n),...this._attachments.slice(n+1)],this._notifySubscribers()})}_notifyEventSubscribers(t){const r=this._eventSubscribers.get(t);if(r)for(const n of r)n()}unstable_on(t,r){const n=this._eventSubscribers.get(t);return n?n.add(r):this._eventSubscribers.set(t,new Set([r])),()=>{const a=this._eventSubscribers.get(t);a&&a.delete(r)}}},fi=class extends hi{constructor(t){super();C(this,"_canCancel",!1);this.runtime=t,this.connect()}get canCancel(){return this._canCancel}get attachments(){return super.attachments}getAttachmentAdapter(){var t;return(t=this.runtime.adapters)==null?void 0:t.attachments}connect(){return this.runtime.subscribe(()=>{this.canCancel!==this.runtime.capabilities.cancel&&(this._canCancel=this.runtime.capabilities.cancel,this._notifySubscribers())})}handleSend(t){return P(this,null,function*(){var r,n;this.runtime.append(E(m({},t),{parentId:(n=(r=this.runtime.messages.at(-1))==null?void 0:r.id)!=null?n:null,sourceId:null}))})}handleCancel(){return P(this,null,function*(){this.runtime.cancelRun()})}};let pi=(e,t=21)=>(r=t)=>{let n="",a=r|0;for(;a--;)n+=e[Math.random()*e.length|0];return n};var _t=pi("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),Gu="__optimistic__",Xu=()=>`${Gu}${_t()}`,ir=Symbol("autoStatus"),Qu=Object.freeze(Object.assign({type:"running"},{[ir]:!0})),Zu=Object.freeze(Object.assign({type:"complete",reason:"unknown"},{[ir]:!0})),ec=Object.freeze(Object.assign({type:"requires-action",reason:"tool-calls"},{[ir]:!0})),tc=Object.freeze(Object.assign({type:"requires-action",reason:"interrupt"},{[ir]:!0})),mi=(e,t,r,n,a)=>e&&a?Object.assign({type:"incomplete",reason:"error",error:a},{[ir]:!0}):e&&t?Qu:r?tc:n?ec:Zu;function Lr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Tt={exports:{}},gi;function rc(){if(gi)return Tt.exports;gi=1;const e=typeof Buffer!="undefined",t=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,r=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function n(o,l,u){u==null&&l!==null&&typeof l=="object"&&(u=l,l=void 0),e&&Buffer.isBuffer(o)&&(o=o.toString()),o&&o.charCodeAt(0)===65279&&(o=o.slice(1));const d=JSON.parse(o,l);if(d===null||typeof d!="object")return d;const c=u&&u.protoAction||"error",h=u&&u.constructorAction||"error";if(c==="ignore"&&h==="ignore")return d;if(c!=="ignore"&&h!=="ignore"){if(t.test(o)===!1&&r.test(o)===!1)return d}else if(c!=="ignore"&&h==="ignore"){if(t.test(o)===!1)return d}else if(r.test(o)===!1)return d;return a(d,{protoAction:c,constructorAction:h,safe:u&&u.safe})}function a(o,{protoAction:l="error",constructorAction:u="error",safe:d}={}){let c=[o];for(;c.length;){const h=c;c=[];for(const f of h){if(l!=="ignore"&&Object.prototype.hasOwnProperty.call(f,"__proto__")){if(d===!0)return null;if(l==="error")throw new SyntaxError("Object contains forbidden prototype property");delete f.__proto__}if(u!=="ignore"&&Object.prototype.hasOwnProperty.call(f,"constructor")&&f.constructor!==null&&typeof f.constructor=="object"&&Object.prototype.hasOwnProperty.call(f.constructor,"prototype")){if(d===!0)return null;if(u==="error")throw new SyntaxError("Object contains forbidden prototype property");delete f.constructor}for(const g in f){const v=f[g];v&&typeof v=="object"&&c.push(v)}}}return o}function i(o,l,u){const{stackTraceLimit:d}=Error;Error.stackTraceLimit=0;try{return n(o,l,u)}finally{Error.stackTraceLimit=d}}function s(o,l){const{stackTraceLimit:u}=Error;Error.stackTraceLimit=0;try{return n(o,l,{safe:!0})}catch(d){return}finally{Error.stackTraceLimit=u}}return Tt.exports=i,Tt.exports.default=i,Tt.exports.parse=i,Tt.exports.safeParse=s,Tt.exports.scan=a,Tt.exports}var nc=rc();const Mn=Lr(nc);function ac(e){const t=["ROOT"];let r=-1,n=null;const a=[];let i;function s(){i!==void 0&&(a.push(JSON.parse(`"${i}"`)),i=void 0)}function o(c,h,f){switch(c){case'"':{r=h,t.pop(),t.push(f),t.push("INSIDE_STRING"),s();break}case"f":case"t":case"n":{r=h,n=h,t.pop(),t.push(f),t.push("INSIDE_LITERAL");break}case"-":{t.pop(),t.push(f),t.push("INSIDE_NUMBER"),s();break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=h,t.pop(),t.push(f),t.push("INSIDE_NUMBER"),s();break}case"{":{r=h,t.pop(),t.push(f),t.push("INSIDE_OBJECT_START"),s();break}case"[":{r=h,t.pop(),t.push(f),t.push("INSIDE_ARRAY_START"),s();break}}}function l(c,h){switch(c){case",":{t.pop(),t.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{r=h,t.pop(),i=a.pop();break}}}function u(c,h){switch(c){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA"),i=(Number(i)+1).toString();break}case"]":{r=h,t.pop(),i=a.pop();break}}}for(let c=0;c<e.length;c++){const h=e[c];switch(t[t.length-1]){case"ROOT":o(h,c,"FINISH");break;case"INSIDE_OBJECT_START":{switch(h){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY"),i="";break}case"}":{r=c,t.pop(),i=a.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(h){case'"':{t.pop(),t.push("INSIDE_OBJECT_KEY"),i="";break}}break}case"INSIDE_OBJECT_KEY":{switch(h){case'"':{t.pop(),t.push("INSIDE_OBJECT_AFTER_KEY");break}case"\\":{t.push("INSIDE_STRING_ESCAPE"),i+=h;break}default:{i+=h;break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(h){case":":{t.pop(),t.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{o(h,c,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{l(h,c);break}case"INSIDE_STRING":{switch(h){case'"':{t.pop(),r=c,i=a.pop();break}case"\\":{t.push("INSIDE_STRING_ESCAPE");break}default:r=c}break}case"INSIDE_ARRAY_START":{switch(h){case"]":{r=c,t.pop(),i=a.pop();break}default:{r=c,i="0",o(h,c,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(h){case",":{t.pop(),t.push("INSIDE_ARRAY_AFTER_COMMA"),i=(Number(i)+1).toString();break}case"]":{r=c,t.pop(),i=a.pop();break}default:{r=c;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{o(h,c,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{t.pop(),t[t.length-1]==="INSIDE_STRING"?r=c:t[t.length-1]==="INSIDE_OBJECT_KEY"&&(i+=h);break}case"INSIDE_NUMBER":{switch(h){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{r=c;break}case"e":case"E":case"-":case".":break;case",":{t.pop(),i=a.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(h,c),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&l(h,c);break}case"}":{t.pop(),i=a.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&l(h,c);break}case"]":{t.pop(),i=a.pop(),t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(h,c);break}default:{t.pop(),i=a.pop();break}}break}case"INSIDE_LITERAL":{const g=e.substring(n,c+1);!"false".startsWith(g)&&!"true".startsWith(g)&&!"null".startsWith(g)?(t.pop(),t[t.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?l(h,c):t[t.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&u(h,c)):r=c;break}}}let d=e.slice(0,r+1);for(let c=t.length-1;c>=0;c--)switch(t[c]){case"INSIDE_STRING":{d+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{d+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{d+="]";break}case"INSIDE_LITERAL":{const f=e.substring(n,e.length);"true".startsWith(f)?d+="true".slice(f.length):"false".startsWith(f)?d+="false".slice(f.length):"null".startsWith(f)&&(d+="null".slice(f.length))}}return[d,a]}var Dr=Symbol("aui.parse-partial-json-object.meta"),ic=e=>e==null?void 0:e[Dr],Or=e=>{if(e.length===0)return{[Dr]:{state:"partial",partialPath:[]}};try{const t=Mn.parse(e);if(typeof t!="object"||t===null)throw new Error("argsText is expected to be an object");return t[Dr]={state:"complete",partialPath:[]},t}catch(t){try{const[r,n]=ac(e),a=Mn.parse(r);if(typeof a!="object"||a===null)throw new Error("argsText is expected to be an object");return a[Dr]={state:"partial",partialPath:n},a}catch(r){return}}},yi=(e,t,r)=>{if(typeof e!="object"||e===null)return t.state;if(t.state==="complete")return"complete";if(r.length===0)return t.state;const[n,...a]=r;if(!Object.prototype.hasOwnProperty.call(e,n))return"partial";const[i,...s]=t.partialPath;if(n!==i)return"complete";const o=e[n];return yi(o,{state:"partial",partialPath:s},a)},Bt=(e,t)=>{const r=ic(e);if(!r)throw new Error("unable to determine object state");return yi(e,r,t.map(String))};function sc(){return Nr(this,null,function*(){const e=this.getReader();try{for(;;){const{done:t,value:r}=yield new Ee(e.read());if(t)break;yield r}}finally{e.releaseLock()}})}function Pn(e){var t,r;return(r=e[t=Symbol.asyncIterator])!=null||(e[t]=sc),e}var Nn={toResponse(e,t){var r;return new Response(Nn.toByteStream(e,t),{headers:(r=t.headers)!=null?r:{}})},fromResponse(e,t){return Nn.fromByteStream(e.body,t)},toByteStream(e,t){return e.pipeThrough(t)},fromByteStream(e,t){return e.pipeThrough(t)}},Ln=function(){let e,t;const r=new Promise((n,a)=>{e=n,t=a});if(!e||!t)throw new Error("Failed to create promise");return{promise:r,resolve:e,reject:t}},oc=()=>{const e=[];let t=!1,r,n;const a=s=>{s.promise||(s.promise=s.reader.read().then(({done:o,value:l})=>{s.promise=void 0,o?(e.splice(e.indexOf(s),1),t&&e.length===0&&r.close()):r.enqueue(l),n==null||n.resolve(),n=void 0}).catch(o=>{console.error(o),e.forEach(l=>{l.reader.cancel()}),e.length=0,r.error(o),n==null||n.reject(o),n=void 0}))};return{readable:new ReadableStream({start(s){r=s},pull(){return n=Ln(),e.forEach(s=>{a(s)}),n.promise},cancel(){e.forEach(s=>{s.reader.cancel()}),e.length=0}}),isSealed(){return t},seal(){t=!0,e.length===0&&r.close()},addStream(s){if(t)throw new Error("Cannot add streams after the run callback has settled.");const o={reader:s.getReader()};e.push(o),a(o)},enqueue(s){this.addStream(new ReadableStream({start(o){o.enqueue(s),o.close()}}))}}},bi=class{constructor(e){C(this,"_controller");C(this,"_isClosed",!1);this._controller=e}append(e){return this._controller.enqueue({type:"text-delta",path:[],textDelta:e}),this}close(){this._isClosed||(this._isClosed=!0,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())}},wi=e=>new ReadableStream({start(t){var r;return(r=e.start)==null?void 0:r.call(e,new bi(t))},pull(t){var r;return(r=e.pull)==null?void 0:r.call(e,new bi(t))},cancel(t){var r;return(r=e.cancel)==null?void 0:r.call(e,t)}}),xi=()=>{let e;return[wi({start(r){e=r}}),e]},vi=class{constructor(e){C(this,"_isClosed",!1);C(this,"_mergeTask");C(this,"_argsTextController");this._controller=e;const t=wi({start:n=>{this._argsTextController=n}});let r=!1;this._mergeTask=t.pipeTo(new WritableStream({write:n=>{switch(n.type){case"text-delta":r=!0,this._controller.enqueue(n);break;case"part-finish":r||this._controller.enqueue({type:"text-delta",textDelta:"{}",path:[]}),this._controller.enqueue({type:"tool-call-args-text-finish",path:[]});break;default:throw new Error(`Unexpected chunk type: ${n.type}`)}}}))}get argsText(){return this._argsTextController}setResponse(e){return P(this,null,function*(){var t;this._argsTextController.close(),yield Promise.resolve(),this._controller.enqueue(E(m({type:"result",path:[]},e.artifact!==void 0?{artifact:e.artifact}:{}),{result:e.result,isError:(t=e.isError)!=null?t:!1}))})}close(){return P(this,null,function*(){this._isClosed||(this._isClosed=!0,this._argsTextController.close(),yield this._mergeTask,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())})}},lc=e=>new ReadableStream({start(t){var r;return(r=e.start)==null?void 0:r.call(e,new vi(t))},pull(t){var r;return(r=e.pull)==null?void 0:r.call(e,new vi(t))},cancel(t){var r;return(r=e.cancel)==null?void 0:r.call(e,t)}}),uc=()=>{let e;return[lc({start(r){e=r}}),e]},ki=class{constructor(){C(this,"value",-1)}up(){return++this.value}},cc=class extends TransformStream{constructor(e){super({transform(t,r){r.enqueue(E(m({},t),{path:[e,...t.path]}))}})}};(class extends TransformStream{constructor(e){super({transform(t,r){const{path:[n,...a]}=t;if(e!==n)throw new Error(`Path mismatch: expected ${e}, got ${n}`);r.enqueue(E(m({},t),{path:a}))}})}});var dc=class extends TransformStream{constructor(e){const t=new ki,r=new Map;super({transform(n,a){n.type==="part-start"&&n.path.length===0&&r.set(t.up(),e.up());const[i,...s]=n.path;if(i===void 0){a.enqueue(n);return}const o=r.get(i);if(o===void 0)throw new Error("Path not found");a.enqueue(E(m({},n),{path:[o,...s]}))}})}},Si=class extends TransformStream{constructor(e){super();const t=e(super.readable);Object.defineProperty(this,"readable",{value:t,writable:!1})}},_i=class extends TransformStream{constructor(){const e=[];super({transform(t,r){if(t.type==="part-start"){if(t.path.length!==0){r.error(new Error("Nested parts are not supported"));return}e.push(t.part),r.enqueue(t);return}if(t.type==="text-delta"||t.type==="result"||t.type==="part-finish"||t.type==="tool-call-args-text-finish"){if(t.path.length!==1){r.error(new Error(`${t.type} chunks must have a path of length 1`));return}const n=t.path[0];if(n<0||n>=e.length){r.error(new Error(`Invalid path index: ${n}`));return}const a=e[n];r.enqueue(E(m({},t),{meta:a}));return}r.enqueue(t)}})}},Ti=pi("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),hc=class Fu{constructor(t){C(this,"_state");C(this,"_parentId");this._state=t||{merger:oc(),contentCounter:new ki}}get __internal_isClosed(){return this._state.merger.isSealed()}__internal_getReadable(){return this._state.merger.readable}__internal_subscribeToClose(t){this._state.closeSubscriber=t}_addPart(t,r){this._state.append&&(this._state.append.controller.close(),this._state.append=void 0),this.enqueue({type:"part-start",part:t,path:[]}),this._state.merger.addStream(r.pipeThrough(new cc(this._state.contentCounter.value)))}merge(t){this._state.merger.addStream(t.pipeThrough(new dc(this._state.contentCounter)))}appendText(t){var r;((r=this._state.append)==null?void 0:r.kind)!=="text"&&(this._state.append={kind:"text",controller:this.addTextPart()}),this._state.append.controller.append(t)}appendReasoning(t){var r;((r=this._state.append)==null?void 0:r.kind)!=="reasoning"&&(this._state.append={kind:"reasoning",controller:this.addReasoningPart()}),this._state.append.controller.append(t)}addTextPart(){const[t,r]=xi();return this._addPart({type:"text"},t),r}addReasoningPart(){const[t,r]=xi();return this._addPart({type:"reasoning"},t),r}addToolCallPart(t){var o;const r=typeof t=="string"?{toolName:t}:t,n=r.toolName,a=(o=r.toolCallId)!=null?o:Ti(),[i,s]=uc();return this._addPart(m({type:"tool-call",toolName:n,toolCallId:a},this._parentId&&{parentId:this._parentId}),i),r.argsText!==void 0&&(s.argsText.append(r.argsText),s.argsText.close()),r.args!==void 0&&(s.argsText.append(JSON.stringify(r.args)),s.argsText.close()),r.response!==void 0&&s.setResponse(r.response),s}appendSource(t){this._addPart(m(m({},t),this._parentId&&{parentId:this._parentId}),new ReadableStream({start(r){r.enqueue({type:"part-finish",path:[]}),r.close()}}))}appendFile(t){this._addPart(t,new ReadableStream({start(r){r.enqueue({type:"part-finish",path:[]}),r.close()}}))}enqueue(t){this._state.merger.enqueue(t),t.type==="part-start"&&t.path.length===0&&this._state.contentCounter.up()}withParentId(t){const r=new Fu(this._state);return r._parentId=t,r}close(){var t,r,n,a;(r=(t=this._state.append)==null?void 0:t.controller)==null||r.close(),this._state.merger.seal(),(a=(n=this._state).closeSubscriber)==null||a.call(n)}};function fc(e){const t=new hc;return P(null,null,function*(){try{yield e(t)}catch(n){throw t.__internal_isClosed||t.enqueue({type:"error",path:[],error:String(n)}),n}finally{t.__internal_isClosed||t.close()}}),t.__internal_getReadable()}function Ci(){const{resolve:e,promise:t}=Ln();let r;return[fc(a=>(r=a,r.__internal_subscribeToClose(e),t)),r]}var pc=class extends TransformStream{constructor(e,t,r){const[n,a]=Ci();let i;super({start(o){var l;return i=n.pipeTo(new WritableStream({write(u){o.enqueue(u)},abort(u){o.error(u)},close(){o.terminate()}})).catch(u=>{o.error(u)}),(l=e.start)==null?void 0:l.call(e,a)},transform(o){var l;return(l=e.transform)==null?void 0:l.call(e,o,a)},flush(){return P(this,null,function*(){var o;yield(o=e.flush)==null?void 0:o.call(e,a),a.close(),yield i})}},t,r)}},sr=(e,t,r)=>{var h,f,g,v,b,w,_;const{role:n,id:a,createdAt:i,attachments:s,status:o,metadata:l}=e,u={id:a!=null?a:t,createdAt:i!=null?i:new Date},d=typeof e.content=="string"?[{type:"text",text:e.content}]:e.content,c=j=>{var I=j,{image:T}=I,B=V(I,["image"]);return T.match(/^data:image\/(png|jpeg|jpg|gif|webp);base64,(.*)$/)?E(m({},B),{image:T}):(console.warn("Invalid image data format detected"),null)};if(n!=="user"&&(s!=null&&s.length))throw new Error("attachments are only supported for user messages");if(n!=="assistant"&&o)throw new Error("status is only supported for assistant messages");if(n!=="assistant"&&(l!=null&&l.steps))throw new Error("metadata.steps is only supported for assistant messages");switch(n){case"assistant":return E(m({},u),{role:n,content:d.map(T=>{var I,z,H,O,S;const B=T.type;switch(B){case"text":case"reasoning":return T.text.trim().length===0?null:T;case"file":case"source":return T;case"image":return c(T);case"data":return T;case"tool-call":{const j=T,{parentId:N,messages:M}=j,W=V(j,["parentId","messages"]),R=m(m(E(m({},W),{toolCallId:(I=T.toolCallId)!=null?I:`tool-${_t()}`}),N!==void 0&&{parentId:N}),M!==void 0&&{messages:M});return T.args?E(m({},R),{args:T.args,argsText:(z=T.argsText)!=null?z:JSON.stringify(T.args)}):E(m({},R),{args:(O=Or((H=T.argsText)!=null?H:""))!=null?O:{},argsText:(S=T.argsText)!=null?S:""})}default:{const N=B;throw new Error(`Unsupported assistant message part type: ${N}`)}}}).filter(T=>!!T),status:o!=null?o:r,metadata:m({unstable_state:(h=l==null?void 0:l.unstable_state)!=null?h:null,unstable_annotations:(f=l==null?void 0:l.unstable_annotations)!=null?f:[],unstable_data:(g=l==null?void 0:l.unstable_data)!=null?g:[],custom:(v=l==null?void 0:l.custom)!=null?v:{},steps:(b=l==null?void 0:l.steps)!=null?b:[]},(l==null?void 0:l.submittedFeedback)&&{submittedFeedback:l.submittedFeedback})});case"user":return E(m({},u),{role:n,content:d.map(T=>{const B=T.type;switch(B){case"text":case"image":case"audio":case"file":return T;default:{const j=B;throw new Error(`Unsupported user message part type: ${j}`)}}}),attachments:s!=null?s:[],metadata:{custom:(w=l==null?void 0:l.custom)!=null?w:{}}});case"system":if(d.length!==1||d[0].type!=="text")throw new Error("System messages must have exactly one text message part.");return E(m({},u),{role:n,content:d,metadata:{custom:(_=l==null?void 0:l.custom)!=null?_:{}}});default:{const T=n;throw new Error(`Unknown message role: ${T}`)}}},Dn={fromArray:e=>{const t=e.map(r=>sr(r,_t(),mi(!1,!1,!1,!1,void 0)));return{messages:t.map((r,n)=>({parentId:n>0?t[n-1].id:null,message:r}))}}},Fr=e=>e.next?Fr(e.next):"current"in e?e:null,mc=class{constructor(e){C(this,"_value",null);this.func=e}get value(){return this._value===null&&(this._value=this.func()),this._value}dirty(){this._value=null}},Ii=class{constructor(){C(this,"messages",new Map);C(this,"head",null);C(this,"root",{children:[],next:null});C(this,"_messages",new mc(()=>{var t,r;const e=new Array(((r=(t=this.head)==null?void 0:t.level)!=null?r:-1)+1);for(let n=this.head;n;n=n.prev)e[n.level]=n.current;return e}))}updateLevels(e,t){e.level=t;for(const r of e.children){const n=this.messages.get(r);n&&this.updateLevels(n,t+1)}}performOp(e,t,r){var i;const n=(i=t.prev)!=null?i:this.root,a=e!=null?e:this.root;if(!(r==="relink"&&n===a)){if(r!=="link"&&(n.children=n.children.filter(s=>s!==t.current.id),n.next===t)){const s=n.children.at(-1),o=s?this.messages.get(s):null;if(o===void 0)throw new Error("MessageRepository(performOp/cut): Fallback sibling message not found. This is likely an internal bug in assistant-ui.");n.next=o}if(r!=="cut"){for(let o=e;o;o=o.prev)if(o.current.id===t.current.id)throw new Error("MessageRepository(performOp/link): A message with the same id already exists in the parent tree. This error occurs if the same message id is found multiple times. This is likely an internal bug in assistant-ui.");a.children=[...a.children,t.current.id],(Fr(t)===this.head||a.next===null)&&(a.next=t),t.prev=e;const s=e?e.level+1:0;this.updateLevels(t,s)}}}get headId(){var e,t;return(t=(e=this.head)==null?void 0:e.current.id)!=null?t:null}getMessages(e){var n;if(e===void 0||e===((n=this.head)==null?void 0:n.current.id))return this._messages.value;const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(getMessages): Head message not found. This is likely an internal bug in assistant-ui.");const r=new Array(t.level+1);for(let a=t;a;a=a.prev)r[a.level]=a.current;return r}addOrUpdateMessage(e,t){const r=this.messages.get(t.id),n=e?this.messages.get(e):null;if(n===void 0)throw new Error("MessageRepository(addOrUpdateMessage): Parent message not found. This is likely an internal bug in assistant-ui.");if(r){r.current=t,this.performOp(n,r,"relink"),this._messages.dirty();return}const a={prev:n,current:t,next:null,children:[],level:n?n.level+1:0};this.messages.set(t.id,a),this.performOp(n,a,"link"),this.head===n&&(this.head=a),this._messages.dirty()}getMessage(e){var r,n;const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(updateMessage): Message not found. This is likely an internal bug in assistant-ui.");return{parentId:(n=(r=t.prev)==null?void 0:r.current.id)!=null?n:null,message:t.current,index:t.level}}appendOptimisticMessage(e,t){let r;do r=Xu();while(this.messages.has(r));return this.addOrUpdateMessage(e,sr(t,r,{type:"running"})),r}deleteMessage(e,t){const r=this.messages.get(e);if(!r)throw new Error("MessageRepository(deleteMessage): Message not found. This is likely an internal bug in assistant-ui.");const n=t===void 0?r.prev:t===null?null:this.messages.get(t);if(n===void 0)throw new Error("MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui.");for(const a of r.children){const i=this.messages.get(a);if(!i)throw new Error("MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui.");this.performOp(n,i,"relink")}this.performOp(null,r,"cut"),this.messages.delete(e),this.head===r&&(this.head=Fr(n!=null?n:this.root)),this._messages.dirty()}getBranches(e){var n;const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(getBranches): Message not found. This is likely an internal bug in assistant-ui.");const{children:r}=(n=t.prev)!=null?n:this.root;return r}switchToBranch(e){var n;const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(switchToBranch): Branch not found. This is likely an internal bug in assistant-ui.");const r=(n=t.prev)!=null?n:this.root;r.next=t,this.head=Fr(t),this._messages.dirty()}resetHead(e){if(e===null){this.clear();return}const t=this.messages.get(e);if(!t)throw new Error("MessageRepository(resetHead): Branch not found. This is likely an internal bug in assistant-ui.");if(t.children.length>0){const r=n=>{for(const a of n.children){const i=this.messages.get(a);i&&(r(i),this.messages.delete(a))}};r(t),t.children=[],t.next=null}this.head=t;for(let r=t;r;r=r.prev)r.prev&&(r.prev.next=r);this._messages.dirty()}clear(){this.messages.clear(),this.head=null,this.root={children:[],next:null},this._messages.dirty()}export(){var t,r,n,a;const e=[];for(const[,i]of this.messages)e.push({message:i.current,parentId:(r=(t=i.prev)==null?void 0:t.current.id)!=null?r:null});return{headId:(a=(n=this.head)==null?void 0:n.current.id)!=null?a:null,messages:e}}import({headId:e,messages:t}){var r,n;for(const{message:a,parentId:i}of t)this.addOrUpdateMessage(i,a);this.resetHead((n=e!=null?e:(r=t.at(-1))==null?void 0:r.message.id)!=null?n:null)}},Br=class{constructor(){C(this,"_subscriptions",new Set);C(this,"_connection")}get isConnected(){return!!this._connection}notifySubscribers(){for(const e of this._subscriptions)e()}_updateConnection(){var e;if(this._subscriptions.size>0){if(this._connection)return;this._connection=this._connect()}else(e=this._connection)==null||e.call(this),this._connection=void 0}subscribe(e){return this._subscriptions.add(e),this._updateConnection(),()=>{this._subscriptions.delete(e),this._updateConnection()}}},tt=Symbol("skip-update"),On=class extends Br{constructor(t){super();C(this,"_previousStateDirty",!0);C(this,"_previousState");C(this,"getState",()=>{if(!this.isConnected||this._previousStateDirty){const t=this.binding.getState();t!==tt&&(this._previousState=t),this._previousStateDirty=!1}if(this._previousState===void 0)throw new Error("Entry not available in the store");return this._previousState});this.binding=t}get path(){return this.binding.path}_connect(){const t=()=>{this._previousStateDirty=!0,this.notifySubscribers()};return this.binding.subscribe(t)}},zr=class{constructor(e,t){this._core=e,this._threadListBinding=t,this.__internal_bindMethods()}get path(){return this._core.path}__internal_bindMethods(){this.switchTo=this.switchTo.bind(this),this.rename=this.rename.bind(this),this.archive=this.archive.bind(this),this.unarchive=this.unarchive.bind(this),this.delete=this.delete.bind(this),this.initialize=this.initialize.bind(this),this.generateTitle=this.generateTitle.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getState=this.getState.bind(this),this.detach=this.detach.bind(this)}getState(){return this._core.getState()}switchTo(){const e=this._core.getState();return this._threadListBinding.switchToThread(e.id)}rename(e){const t=this._core.getState();return this._threadListBinding.rename(t.id,e)}archive(){const e=this._core.getState();return this._threadListBinding.archive(e.id)}unarchive(){const e=this._core.getState();return this._threadListBinding.unarchive(e.id)}delete(){const e=this._core.getState();return this._threadListBinding.delete(e.id)}initialize(){const e=this._core.getState();return this._threadListBinding.initialize(e.id)}generateTitle(){const e=this._core.getState();return this._threadListBinding.generateTitle(e.id)}unstable_on(e,t){let r=this._core.getState().isMain,n=this._core.getState().id;return this.subscribe(()=>{const a=this._core.getState(),i=a.isMain,s=a.id;r===i&&n===s||(r=i,n=s,!(e==="switched-to"&&!i)&&(e==="switched-away"&&i||t()))})}subscribe(e){return this._core.subscribe(e)}detach(){const e=this._core.getState();this._threadListBinding.detach(e.id)}__internal_getRuntime(){return this}};function gc(e,t){if(e===void 0&&t===void 0)return!0;if(e===void 0||t===void 0)return!1;for(const r of Object.keys(e)){const n=e[r],a=t[r];if(!Object.is(n,a))return!1}return!0}var rt=class extends Br{constructor(t){super();C(this,"_previousState");C(this,"getState",()=>(this.isConnected||this._syncState(),this._previousState));this.binding=t;const r=t.getState();if(r===tt)throw new Error("Entry not available in the store");this._previousState=r}get path(){return this.binding.path}_syncState(){const t=this.binding.getState();return t===tt||gc(t,this._previousState)?!1:(this._previousState=t,!0)}_connect(){const t=()=>{this._syncState()&&this.notifySubscribers()};return this.binding.subscribe(t)}},Rr=Symbol("innerMessage"),jr=e=>e.content.filter(r=>r.type==="text").map(r=>r.text).join(`
4
4
 
5
- `),Ii=class{constructor(e){this._core=e,this.__internal_bindMethods()}get path(){return this._core.path}__internal_bindMethods(){this.getState=this.getState.bind(this),this.remove=this.remove.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this._core.getState()}subscribe(e){return this._core.subscribe(e)}},Ei=class extends Ii{constructor(e,t){super(e),this._composerApi=t}remove(){const e=this._composerApi.getState();if(!e)throw new Error("Composer is not available");return e.removeAttachment(this.getState().id)}},gc=class extends Ei{get source(){return"thread-composer"}},yc=class extends Ei{get source(){return"edit-composer"}},bc=class extends Ii{get source(){return"message"}constructor(e){super(e)}remove(){throw new Error("Message attachments cannot be removed")}},Ai=class extends Fr{constructor(e){super(),this.config=e}getState(){return this.config.binding.getState()}outerSubscribe(e){return this.config.binding.subscribe(e)}_connect(){const e=()=>{this.notifySubscribers()};let t=this.config.binding.getState(),r=t==null?void 0:t.unstable_on(this.config.event,e);const n=()=>{var s;const i=this.config.binding.getState();i!==t&&(t=i,r==null||r(),r=(s=this.config.binding.getState())==null?void 0:s.unstable_on(this.config.event,e))},a=this.outerSubscribe(n);return()=>{a==null||a(),r==null||r()}}},Mi=Object.freeze([]),Pi=Object.freeze({}),wc=e=>{var t,r,n,a,i,s,o,l,u;return Object.freeze({type:"thread",isEditing:(t=e==null?void 0:e.isEditing)!=null?t:!1,canCancel:(r=e==null?void 0:e.canCancel)!=null?r:!1,isEmpty:(n=e==null?void 0:e.isEmpty)!=null?n:!0,attachments:(a=e==null?void 0:e.attachments)!=null?a:Mi,text:(i=e==null?void 0:e.text)!=null?i:"",role:(s=e==null?void 0:e.role)!=null?s:"user",runConfig:(o=e==null?void 0:e.runConfig)!=null?o:Pi,attachmentAccept:(l=e==null?void 0:e.attachmentAccept)!=null?l:"",value:(u=e==null?void 0:e.text)!=null?u:""})},xc=e=>{var t,r,n,a,i,s,o,l,u;return Object.freeze({type:"edit",isEditing:(t=e==null?void 0:e.isEditing)!=null?t:!1,canCancel:(r=e==null?void 0:e.canCancel)!=null?r:!1,isEmpty:(n=e==null?void 0:e.isEmpty)!=null?n:!0,text:(a=e==null?void 0:e.text)!=null?a:"",role:(i=e==null?void 0:e.role)!=null?i:"user",attachments:(s=e==null?void 0:e.attachments)!=null?s:Mi,runConfig:(o=e==null?void 0:e.runConfig)!=null?o:Pi,attachmentAccept:(l=e==null?void 0:e.attachmentAccept)!=null?l:"",value:(u=e==null?void 0:e.text)!=null?u:""})},Ni=class{constructor(e){C(this,"_eventSubscriptionSubjects",new Map);this._core=e}get path(){return this._core.path}__internal_bindMethods(){this.setText=this.setText.bind(this),this.setRunConfig=this.setRunConfig.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.addAttachment=this.addAttachment.bind(this),this.reset=this.reset.bind(this),this.clearAttachments=this.clearAttachments.bind(this),this.send=this.send.bind(this),this.cancel=this.cancel.bind(this),this.setRole=this.setRole.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_on=this.unstable_on.bind(this)}setText(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.setText(e)}setRunConfig(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.setRunConfig(e)}addAttachment(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");return t.addAttachment(e)}reset(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");return e.reset()}clearAttachments(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");return e.clearAttachments()}send(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.send()}cancel(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.cancel()}setRole(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.setRole(e)}subscribe(e){return this._core.subscribe(e)}unstable_on(e,t){let r=this._eventSubscriptionSubjects.get(e);return r||(r=new Ai({event:e,binding:this._core}),this._eventSubscriptionSubjects.set(e,r)),r.subscribe(t)}},vc=class extends Ni{constructor(t){const r=new On({path:t.path,getState:()=>wc(t.getState()),subscribe:n=>t.subscribe(n)});super({path:t.path,getState:()=>t.getState(),subscribe:n=>r.subscribe(n)});C(this,"_getState");this._getState=r.getState.bind(r),this.__internal_bindMethods()}get path(){return this._core.path}get type(){return"thread"}getState(){return this._getState()}getAttachmentByIndex(t){return new gc(new tt({path:E(m({},this.path),{attachmentSource:"thread-composer",attachmentSelector:{type:"index",index:t},ref:`${this.path.ref}${this.path.ref}.attachments[${t}]`}),getState:()=>{const n=this.getState().attachments[t];return n?E(m({},n),{source:"thread-composer"}):et},subscribe:r=>this._core.subscribe(r)}),this._core)}},kc=class extends Ni{constructor(t,r){const n=new On({path:t.path,getState:()=>xc(t.getState()),subscribe:a=>t.subscribe(a)});super({path:t.path,getState:()=>t.getState(),subscribe:a=>n.subscribe(a)});C(this,"_getState");this._beginEdit=r,this._getState=n.getState.bind(n),this.__internal_bindMethods()}get path(){return this._core.path}get type(){return"edit"}__internal_bindMethods(){super.__internal_bindMethods(),this.beginEdit=this.beginEdit.bind(this)}getState(){return this._getState()}beginEdit(){this._beginEdit()}getAttachmentByIndex(t){return new yc(new tt({path:E(m({},this.path),{attachmentSource:"edit-composer",attachmentSelector:{type:"index",index:t},ref:`${this.path.ref}${this.path.ref}.attachments[${t}]`}),getState:()=>{const n=this.getState().attachments[t];return n?E(m({},n),{source:"edit-composer"}):et},subscribe:r=>this._core.subscribe(r)}),this._core)}},Sc=class Sn{constructor(t=null){C(this,"_state");this._state=t}get state(){return this._state}append(t){this._state=t.reduce((r,n)=>Sn.apply(r,n),this._state)}static apply(t,r){const n=r.type;switch(n){case"set":return Sn.updatePath(t,r.path,()=>r.value);case"append-text":return Sn.updatePath(t,r.path,a=>{if(typeof a!="string")throw new Error(`Expected string at path [${r.path.join(", ")}]`);return a+r.value});default:{const a=n;throw new Error(`Invalid operation type: ${a}`)}}}static updatePath(t,r,n){if(r.length===0)return n(t);if(t!=null||(t={}),typeof t!="object")throw new Error(`Invalid path: [${r.join(", ")}]`);const[a,...i]=r;if(Array.isArray(t)){const o=Number(a);if(Number.isNaN(o))throw new Error(`Expected array index at [${r.join(", ")}]`);if(o>t.length||o<0)throw new Error("Insert array index out of bounds");const l=[...t];return l[o]=this.updatePath(l[o],i,n),l}const s=m({},t);return s[a]=this.updatePath(s[a],i,n),s}},_c=({unstable_state:e=null}={})=>({role:"assistant",status:{type:"running"},parts:[],get content(){return this.parts},metadata:{unstable_state:e,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}),jr=(e,t,r)=>{if(e.parts.length===0)throw new Error("No parts available to update.");if(t.path.length!==1)throw new Error("Nested paths are not supported yet.");const n=t.path[0],a=r(e.parts[n]);return E(m({},e),{parts:[...e.parts.slice(0,n),a,...e.parts.slice(n+1)],get content(){return this.parts}})},Tc=(e,t)=>{const r=t.part;if(r.type==="text"||r.type==="reasoning"){const n=m({type:r.type,text:"",status:{type:"running"}},r.parentId&&{parentId:r.parentId});return E(m({},e),{parts:[...e.parts,n],get content(){return this.parts}})}else if(r.type==="tool-call"){const n=m({type:"tool-call",state:"partial-call",status:{type:"running",isArgsComplete:!1},toolCallId:r.toolCallId,toolName:r.toolName,argsText:"",args:{}},r.parentId&&{parentId:r.parentId});return E(m({},e),{parts:[...e.parts,n],get content(){return this.parts}})}else if(r.type==="source"){const n=m(m({type:"source",sourceType:r.sourceType,id:r.id,url:r.url},r.title?{title:r.title}:void 0),r.parentId&&{parentId:r.parentId});return E(m({},e),{parts:[...e.parts,n],get content(){return this.parts}})}else if(r.type==="file"){const n={type:"file",mimeType:r.mimeType,data:r.data};return E(m({},e),{parts:[...e.parts,n],get content(){return this.parts}})}else throw new Error(`Unsupported part type: ${r.type}`)},Cc=(e,t)=>jr(e,t,r=>{if(r.type!=="tool-call")throw new Error("Last is not a tool call");return r.state!=="partial-call"?r:E(m({},r),{state:"call"})}),Ic=(e,t)=>jr(e,t,r=>E(m({},r),{status:{type:"complete",reason:"unknown"}})),Ec=(e,t)=>jr(e,t,r=>{var n;if(r.type==="text"||r.type==="reasoning")return E(m({},r),{text:r.text+t.textDelta});if(r.type==="tool-call"){const a=r.argsText+t.textDelta,i=(n=Dr(a))!=null?n:r.args;return E(m({},r),{argsText:a,args:i})}else throw new Error("text-delta received but part is neither text nor tool-call")}),Ac=(e,t)=>jr(e,t,r=>{var n;if(r.type==="tool-call")return E(m(E(m({},r),{state:"result"}),t.artifact!==void 0?{artifact:t.artifact}:{}),{result:t.result,isError:(n=t.isError)!=null?n:!1,status:{type:"complete",reason:"stop"}});throw new Error("Result chunk received but part is not a tool-call")}),Li=(e,t)=>{var n,a;if(((n=e.status)==null?void 0:n.type)==="incomplete"&&((a=e.status)==null?void 0:a.reason)==="error")return e;const r=Mc(t);return E(m({},e),{status:r})},Mc=e=>e.finishReason==="tool-calls"?{type:"requires-action",reason:"tool-calls"}:e.finishReason==="stop"||e.finishReason==="unknown"?{type:"complete",reason:e.finishReason}:{type:"incomplete",reason:e.finishReason},Pc=(e,t)=>E(m({},e),{metadata:E(m({},e.metadata),{unstable_annotations:[...e.metadata.unstable_annotations,...t.annotations]})}),Nc=(e,t)=>E(m({},e),{metadata:E(m({},e.metadata),{unstable_data:[...e.metadata.unstable_data,...t.data]})}),Lc=(e,t)=>E(m({},e),{metadata:E(m({},e.metadata),{steps:[...e.metadata.steps,{state:"started",messageId:t.messageId}]})}),Dc=(e,t)=>{var a;const r=e.metadata.steps.slice(),n=r.length-1;return r.length>0&&((a=r[n])==null?void 0:a.state)==="started"?r[n]=E(m({},r[n]),{state:"finished",finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}):r.push({state:"finished",messageId:_i(),finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}),E(m({},e),{metadata:E(m({},e.metadata),{steps:r})})},Oc=(e,t)=>E(m({},e),{status:{type:"incomplete",reason:"error",error:t.error}}),Fc=(e,t)=>{const r=new Sc(e.metadata.unstable_state);return r.append(t.operations),E(m({},e),{metadata:E(m({},e.metadata),{unstable_state:r.state})})},Bc=e=>{let t=!1;return()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}},zc=class extends TransformStream{constructor({initialMessage:e,throttle:t,onError:r}={}){let n=e!=null?e:_c(),a;const i=t?Bc(()=>{a==null||a.enqueue(n)}):()=>{a==null||a.enqueue(n)};super({start(s){a=s},transform(s){const o=s.type;switch(o){case"part-start":n=Tc(n,s);break;case"tool-call-args-text-finish":n=Cc(n,s);break;case"part-finish":n=Ic(n,s);break;case"text-delta":n=Ec(n,s);break;case"result":n=Ac(n,s);break;case"message-finish":n=Li(n,s);break;case"annotations":n=Pc(n,s);break;case"data":n=Nc(n,s);break;case"step-start":n=Lc(n,s);break;case"step-finish":n=Dc(n,s);break;case"error":n=Oc(n,s),r==null||r(s.error);break;case"update-state":n=Fc(n,s);break;default:{const l=o;throw new Error(`Unsupported chunk type: ${l}`)}}i()},flush(s){var o,l,u;if(((o=n.status)==null?void 0:o.type)==="running"){const d=(u=(l=n.parts)==null?void 0:l.some(c=>c.type==="tool-call"&&(c.state==="call"||c.state==="partial-call")&&c.result===void 0))!=null?u:!1;n=Li(n,{finishReason:d?"tool-calls":"unknown"}),s.enqueue(n)}}})}},Rc=class extends ki{constructor(){super(e=>{const t=new fc({transform(r,n){n.appendText(r)}});return e.pipeThrough(new TextDecoderStream).pipeThrough(t)})}},jc=class _n{constructor(t){this.readable=t,this.readable=t}static fromAssistantStream(t){return new _n(t.pipeThrough(new zc))}unstable_result(){return P(this,null,function*(){let t;try{for(var r=Ft(this),n,a,i;n=!(a=yield r.next()).done;n=!1){const s=a.value;t=s}}catch(a){i=[a]}finally{try{n&&(a=r.return)&&(yield a.call(r))}finally{if(i)throw i[0]}}return t||{role:"assistant",status:{type:"complete",reason:"unknown"},parts:[],content:[],metadata:{unstable_state:null,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}})}[Symbol.asyncIterator](){const t=this.readable.getReader();return{next(){return P(this,null,function*(){const{done:n,value:a}=yield t.read();return n?{done:!0,value:void 0}:{done:!1,value:a}})}}}tee(){const[t,r]=this.readable.tee();return[new _n(t),new _n(r)]}},Di=Symbol.for("aui.tool-response"),mt=class oi{constructor(t){C(this,"artifact");C(this,"result");C(this,"isError");var r;t.artifact!==void 0&&(this.artifact=t.artifact),this.result=t.result,this.isError=(r=t.isError)!=null?r:!1}get[Di](){return!0}static[Symbol.hasInstance](t){return typeof t=="object"&&t!==null&&Di in t}static toResponse(t){return t instanceof oi?t:new oi({result:t===void 0?"<no result>":t})}};function $c(e,t,r){try{const n=e();if(typeof n=="object"&&n!==null&&"then"in n)return n.then(t,r);t(n)}catch(n){r(n)}}function or(e,t){let r=e;for(const n of t){if(r==null)return;r=r[n]}return r}var Uc=class{constructor(e,t,r){C(this,"resolve");C(this,"reject");C(this,"disposed",!1);C(this,"fieldPath");this.resolve=e,this.reject=t,this.fieldPath=r}update(e){if(!this.disposed)try{if(Bt(e,this.fieldPath)==="complete"){const t=or(e,this.fieldPath);t!==void 0&&(this.resolve(t),this.dispose())}}catch(t){this.reject(t),this.dispose()}}dispose(){this.disposed=!0}},Oi=class{constructor(e,t){C(this,"controller");C(this,"disposed",!1);C(this,"fieldPath");this.controller=e,this.fieldPath=t}update(e){if(!this.disposed)try{const t=or(e,this.fieldPath);t!==void 0&&this.controller.enqueue(t),Bt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(t){this.controller.error(t),this.dispose()}}dispose(){this.disposed=!0}},Fi=class{constructor(e,t){C(this,"controller");C(this,"disposed",!1);C(this,"fieldPath");C(this,"lastValue");this.controller=e,this.fieldPath=t}update(e){var t;if(!this.disposed)try{const r=or(e,this.fieldPath);if(r!==void 0&&typeof r=="string"){const n=r.substring(((t=this.lastValue)==null?void 0:t.length)||0);this.lastValue=r,this.controller.enqueue(n)}Bt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(r){this.controller.error(r),this.dispose()}}dispose(){this.disposed=!0}},Bi=class{constructor(e,t){C(this,"controller");C(this,"disposed",!1);C(this,"fieldPath");C(this,"processedIndexes",new Set);this.controller=e,this.fieldPath=t}update(e){if(!this.disposed)try{const t=or(e,this.fieldPath);if(!Array.isArray(t))return;for(let r=0;r<t.length;r++)if(!this.processedIndexes.has(r)){const n=[...this.fieldPath,r];Bt(e,n)==="complete"&&(this.controller.enqueue(t[r]),this.processedIndexes.add(r))}Bt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(t){this.controller.error(t),this.dispose()}}dispose(){this.disposed=!0}},Hc=class{constructor(e){C(this,"argTextDeltas");C(this,"handles",new Set);C(this,"args",Dr(""));this.argTextDeltas=e,this.processStream()}processStream(){return P(this,null,function*(){try{let e="";const t=this.argTextDeltas.getReader();for(;;){const{value:r,done:n}=yield t.read();if(n)break;e+=r;const a=Dr(e);if(a!==void 0){this.args=a;for(const i of this.handles)i.update(a)}}}catch(e){console.error("Error processing argument stream:",e);for(const t of this.handles)t.dispose()}})}get(...e){return new Promise((t,r)=>{const n=new Uc(t,r,e);if(this.args&&Bt(this.args,e)==="complete"){const a=or(this.args,e);if(a!==void 0){t(a);return}}this.handles.add(n),n.update(this.args)})}streamValues(...e){const t=e,r=new ReadableStream({start:n=>{const a=new Oi(n,t);this.handles.add(a),a.update(this.args)},cancel:()=>{for(const n of this.handles)if(n instanceof Oi){n.dispose(),this.handles.delete(n);break}}});return Pn(r)}streamText(...e){const t=e,r=new ReadableStream({start:n=>{const a=new Fi(n,t);this.handles.add(a),a.update(this.args)},cancel:()=>{for(const n of this.handles)if(n instanceof Fi){n.dispose(),this.handles.delete(n);break}}});return Pn(r)}forEach(...e){const t=e,r=new ReadableStream({start:n=>{const a=new Bi(n,t);this.handles.add(a),a.update(this.args)},cancel:()=>{for(const n of this.handles)if(n instanceof Bi){n.dispose(),this.handles.delete(n);break}}});return Pn(r)}},qc=class{constructor(e){this.promise=e}get(){return this.promise}},Vc=class{constructor(){C(this,"args");C(this,"response");C(this,"writable");C(this,"resolve");C(this,"argsText","");C(this,"result",{get:()=>P(this,null,function*(){return(yield this.response.get()).result})});const e=new TransformStream;this.writable=e.writable,this.args=new Hc(e.readable);const{promise:t,resolve:r}=Ln();this.resolve=r,this.response=new qc(t)}appendArgsTextDelta(e){return P(this,null,function*(){const t=this.writable.getWriter();try{yield t.write(e)}catch(r){console.warn(r)}finally{t.releaseLock()}this.argsText+=e})}setResponse(e){this.resolve(e)}},Wc=class extends ki{constructor(e){const t=new Map,r=new Map;super(n=>{const a=new TransformStream({transform(s,o){switch((s.type!=="part-finish"||s.meta.type!=="tool-call")&&o.enqueue(s),s.type){case"part-start":if(s.part.type==="tool-call"){const u=new Vc;r.set(s.part.toolCallId,u),e.streamCall({reader:u,toolCallId:s.part.toolCallId,toolName:s.part.toolName})}break;case"text-delta":{if(s.meta.type==="tool-call"){const u=s.meta.toolCallId,d=r.get(u);if(!d)throw new Error("No controller found for tool call");d.appendArgsTextDelta(s.textDelta)}break}case"result":{if(s.meta.type!=="tool-call")break;const{toolCallId:u}=s.meta,d=r.get(u);if(!d)throw new Error("No controller found for tool call");d.setResponse(new mt({result:s.result,artifact:s.artifact,isError:s.isError}));break}case"tool-call-args-text-finish":{if(s.meta.type!=="tool-call")break;const{toolCallId:u,toolName:d}=s.meta,c=r.get(u);if(!c)throw new Error("No controller found for tool call");let h=!1;const f=$c(()=>{var b;let g;try{g=Mn.parse(c.argsText)}catch(w){throw new Error(`Function parameter parsing failed. ${JSON.stringify(w.message)}`)}const v=e.execute({toolCallId:u,toolName:d,args:g});return v!==void 0&&(h=!0,(b=e.onExecutionStart)==null||b.call(e,u,d)),v},g=>{var b;if(h&&((b=e.onExecutionEnd)==null||b.call(e,u,d)),g===void 0)return;const v=new mt({artifact:g.artifact,result:g.result,isError:g.isError});c.setResponse(v),o.enqueue(m({type:"result",path:s.path},v))},g=>{var b;h&&((b=e.onExecutionEnd)==null||b.call(e,u,d));const v=new mt({result:String(g),isError:!0});c.setResponse(v),o.enqueue(m({type:"result",path:s.path},v))});f&&t.set(u,f);break}case"part-finish":{if(s.meta.type!=="tool-call")break;const{toolCallId:u}=s.meta,d=t.get(u);d?d.then(()=>{t.delete(u),r.delete(u),o.enqueue(s)}):o.enqueue(s)}}},flush(){return P(this,null,function*(){yield Promise.all(t.values())})}});return n.pipeThrough(new Si).pipeThrough(a)})}},Jc=e=>typeof e=="object"&&e!==null&&"~standard"in e&&e["~standard"].version===1;function Yc(e,t,r,n){const a=e==null?void 0:e[r.toolName];return!a||!a.execute?void 0:(s=>P(null,null,function*(){var d;if(t.aborted)return new mt({result:"Tool execution was cancelled.",isError:!0});let o=s;if(Jc(a.parameters)){let c=a.parameters["~standard"].validate(r.args);c instanceof Promise&&(c=yield c),c.issues&&(o=(d=a.experimental_onSchemaValidationError)!=null?d:(()=>{throw new Error(`Function parameter validation failed. ${JSON.stringify(c.issues)}`)}))}const l=new Promise(c=>{const h=()=>{queueMicrotask(()=>{queueMicrotask(()=>{c(new mt({result:"Tool execution was cancelled.",isError:!0}))})})};t.aborted?h():t.addEventListener("abort",h,{once:!0})}),u=P(null,null,function*(){const c=yield o(r.args,{toolCallId:r.toolCallId,abortSignal:t,human:h=>n(r.toolCallId,h)});return mt.toResponse(c)});return Promise.race([u,l])}))(a.execute)}function Kc(e,t,r,n,a){var i,s;(s=(i=e==null?void 0:e[n.toolName])==null?void 0:i.streamCall)==null||s.call(i,r,{toolCallId:n.toolCallId,abortSignal:t,human:o=>a(n.toolCallId,o)})}function Gc(e,t,r,n){const a=typeof e=="function"?e:()=>e,i=typeof t=="function"?t:()=>t;return new Wc({execute:s=>Yc(a(),i(),s,r),streamCall:l=>{var u=l,{reader:s}=u,o=V(u,["reader"]);return Kc(a(),i(),s,o,r)},onExecutionStart:n==null?void 0:n.onExecutionStart,onExecutionEnd:n==null?void 0:n.onExecutionEnd})}var zi=class{constructor(e,t,r){this.contentBinding=e,this.messageApi=t,this.threadApi=r,this.__internal_bindMethods()}get path(){return this.contentBinding.path}__internal_bindMethods(){this.addToolResult=this.addToolResult.bind(this),this.resumeToolCall=this.resumeToolCall.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this.contentBinding.getState()}addToolResult(e){const t=this.contentBinding.getState();if(!t)throw new Error("Message part is not available");if(t.type!=="tool-call")throw new Error("Tried to add tool result to non-tool message part");if(!this.messageApi)throw new Error("Message API is not available. This is likely a bug in assistant-ui.");if(!this.threadApi)throw new Error("Thread API is not available");const r=this.messageApi.getState();if(!r)throw new Error("Message is not available");const n=t.toolName,a=t.toolCallId,i=mt.toResponse(e);this.threadApi.getState().addToolResult({messageId:r.id,toolName:n,toolCallId:a,result:i.result,artifact:i.artifact,isError:i.isError})}resumeToolCall(e){const t=this.contentBinding.getState();if(!t)throw new Error("Message part is not available");if(t.type!=="tool-call")throw new Error("Tried to resume tool call on non-tool message part");if(!this.threadApi)throw new Error("Thread API is not available");const r=t.toolCallId;this.threadApi.getState().resumeToolCall({toolCallId:r,payload:e})}subscribe(e){return this.contentBinding.subscribe(e)}},$r=class extends Fr{constructor(e){super(),this.binding=e}get path(){return this.binding.path}getState(){return this.binding.getState()}outerSubscribe(e){return this.binding.subscribe(e)}_connect(){const e=()=>{this.notifySubscribers()};let t=this.binding.getState(),r=t==null?void 0:t.subscribe(e);const n=()=>{var s;const i=this.binding.getState();i!==t&&(t=i,r==null||r(),r=(s=this.binding.getState())==null?void 0:s.subscribe(e),e())},a=this.outerSubscribe(n);return()=>{a==null||a(),r==null||r()}}},Ur=Object.freeze({type:"complete"}),Xc=(e,t,r)=>{if(e.role!=="assistant")return Ur;if(r.type==="tool-call")return r.result?Ur:e.status;const n=t===Math.max(0,e.content.length-1);return e.status.type==="requires-action"?Ur:n?e.status:Ur},Ri=(e,t)=>{const r=e.content[t];if(!r)return et;const n=Xc(e,t,r);return Object.freeze(E(m({},r),{[zr]:r[zr],status:n}))},Qc=class{constructor(e,t){C(this,"composer");C(this,"_getEditComposerRuntimeCore",()=>this._threadBinding.getState().getEditComposer(this._core.getState().id));this._core=e,this._threadBinding=t,this.composer=new kc(new $r({path:E(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:"edit"}),getState:this._getEditComposerRuntimeCore,subscribe:r=>this._threadBinding.subscribe(r)}),()=>this._threadBinding.getState().beginEdit(this._core.getState().id)),this.__internal_bindMethods()}get path(){return this._core.path}__internal_bindMethods(){this.reload=this.reload.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getMessagePartByIndex=this.getMessagePartByIndex.bind(this),this.getMessagePartByToolCallId=this.getMessagePartByToolCallId.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_getCopyText=this.unstable_getCopyText.bind(this),this.speak=this.speak.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.submitFeedback=this.submitFeedback.bind(this),this.switchToBranch=this.switchToBranch.bind(this)}getState(){return this._core.getState()}reload(e={}){const t=this._getEditComposerRuntimeCore(),r=t!=null?t:this._threadBinding.getState().composer,n=t!=null?t:r,{runConfig:a=n.runConfig}=e,i=this._core.getState();if(i.role!=="assistant")throw new Error("Can only reload assistant messages");this._threadBinding.getState().startRun({parentId:i.parentId,sourceId:i.id,runConfig:a})}speak(){const e=this._core.getState();return this._threadBinding.getState().speak(e.id)}stopSpeaking(){var r;const e=this._core.getState();if(((r=this._threadBinding.getState().speech)==null?void 0:r.messageId)===e.id)this._threadBinding.getState().stopSpeaking();else throw new Error("Message is not being spoken")}submitFeedback({type:e}){const t=this._core.getState();this._threadBinding.getState().submitFeedback({messageId:t.id,type:e})}switchToBranch({position:e,branchId:t}){const r=this._core.getState();if(t&&e)throw new Error("May not specify both branchId and position");if(!t&&!e)throw new Error("Must specify either branchId or position");const a=this._threadBinding.getState().getBranches(r.id);let i=t;if(e==="previous"?i=a[r.branchNumber-2]:e==="next"&&(i=a[r.branchNumber]),!i)throw new Error("Branch not found");this._threadBinding.getState().switchToBranch(i)}unstable_getCopyText(){return Rr(this.getState())}subscribe(e){return this._core.subscribe(e)}getMessagePartByIndex(e){if(e<0)throw new Error("Message part index must be >= 0");return new zi(new tt({path:E(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.content[${e}]`,messagePartSelector:{type:"index",index:e}}),getState:()=>Ri(this.getState(),e),subscribe:t=>this._core.subscribe(t)}),this._core,this._threadBinding)}getMessagePartByToolCallId(e){return new zi(new tt({path:E(m({},this.path),{ref:this.path.ref+`${this.path.ref}.content[toolCallId=${JSON.stringify(e)}]`,messagePartSelector:{type:"toolCallId",toolCallId:e}}),getState:()=>{const t=this._core.getState(),r=t.content.findIndex(n=>n.type==="tool-call"&&n.toolCallId===e);return r===-1?et:Ri(t,r)},subscribe:t=>this._core.subscribe(t)}),this._core,this._threadBinding)}getAttachmentByIndex(e){return new bc(new tt({path:E(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.attachments[${e}]`,attachmentSource:"message",attachmentSelector:{type:"index",index:e}}),getState:()=>{const t=this.getState().attachments,r=t==null?void 0:t[e];return r?E(m({},r),{source:"message"}):et},subscribe:t=>this._core.subscribe(t)}))}},Zc=e=>{var t,r,n;return m({parentId:(t=e.parentId)!=null?t:null,sourceId:(r=e.sourceId)!=null?r:null,runConfig:(n=e.runConfig)!=null?n:{}},e.stream?{stream:e.stream}:{})},ed=e=>{var t,r,n;return{parentId:(t=e.parentId)!=null?t:null,sourceId:(r=e.sourceId)!=null?r:null,runConfig:(n=e.runConfig)!=null?n:{}}},td=(e,t)=>{var r,n,a,i,s,o,l,u,d,c,h;return typeof t=="string"?{createdAt:new Date,parentId:(n=(r=e.at(-1))==null?void 0:r.id)!=null?n:null,sourceId:null,runConfig:{},role:"user",content:[{type:"text",text:t}],attachments:[],metadata:{custom:{}}}:{createdAt:(a=t.createdAt)!=null?a:new Date,parentId:(o=(s=t.parentId)!=null?s:(i=e.at(-1))==null?void 0:i.id)!=null?o:null,sourceId:(l=t.sourceId)!=null?l:null,role:(u=t.role)!=null?u:"user",content:t.content,attachments:(d=t.attachments)!=null?d:[],metadata:(c=t.metadata)!=null?c:{custom:{}},runConfig:(h=t.runConfig)!=null?h:{},startRun:t.startRun}},rd=(e,t)=>{const r=e.messages.at(-1);return Object.freeze({threadId:t.id,metadata:t,capabilities:e.capabilities,isDisabled:e.isDisabled,isLoading:e.isLoading,isRunning:(r==null?void 0:r.role)!=="assistant"?!1:r.status.type==="running",messages:e.messages,state:e.state,suggestions:e.suggestions,extras:e.extras,speech:e.speech})},ji=class{constructor(e,t){C(this,"_threadBinding");C(this,"composer");C(this,"_eventSubscriptionSubjects",new Map);const r=new tt({path:e.path,getState:()=>rd(e.getState(),t.getState()),subscribe:n=>{const a=e.subscribe(n),i=t.subscribe(n);return()=>{a(),i()}}});this._threadBinding={path:e.path,getState:()=>e.getState(),getStateState:()=>r.getState(),outerSubscribe:n=>e.outerSubscribe(n),subscribe:n=>e.subscribe(n)},this.composer=new vc(new $r({path:E(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:"thread"}),getState:()=>this._threadBinding.getState().composer,subscribe:n=>this._threadBinding.subscribe(n)})),this.__internal_bindMethods()}get path(){return this._threadBinding.path}get __internal_threadBinding(){return this._threadBinding}__internal_bindMethods(){this.append=this.append.bind(this),this.unstable_resumeRun=this.unstable_resumeRun.bind(this),this.unstable_loadExternalState=this.unstable_loadExternalState.bind(this),this.startRun=this.startRun.bind(this),this.cancelRun=this.cancelRun.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.export=this.export.bind(this),this.import=this.import.bind(this),this.reset=this.reset.bind(this),this.getMessageByIndex=this.getMessageByIndex.bind(this),this.getMessageById=this.getMessageById.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getModelContext=this.getModelContext.bind(this),this.getModelConfig=this.getModelConfig.bind(this),this.getState=this.getState.bind(this)}getState(){return this._threadBinding.getStateState()}append(e){this._threadBinding.getState().append(td(this._threadBinding.getState().messages,e))}subscribe(e){return this._threadBinding.subscribe(e)}getModelContext(){return this._threadBinding.getState().getModelContext()}getModelConfig(){return this.getModelContext()}startRun(e){const t=e===null||typeof e=="string"?{parentId:e}:e;return this._threadBinding.getState().startRun(ed(t))}unstable_resumeRun(e){return this._threadBinding.getState().resumeRun(Zc(e))}unstable_loadExternalState(e){this._threadBinding.getState().unstable_loadExternalState(e)}cancelRun(){this._threadBinding.getState().cancelRun()}stopSpeaking(){return this._threadBinding.getState().stopSpeaking()}export(){return this._threadBinding.getState().export()}import(e){this._threadBinding.getState().import(e)}reset(e){this._threadBinding.getState().reset(e)}getMessageByIndex(e){if(e<0)throw new Error("Message index must be >= 0");return this._getMessageRuntime(E(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.messages[${e}]`,messageSelector:{type:"index",index:e}}),()=>{var n,a;const t=this._threadBinding.getState().messages,r=t[e];if(r)return{message:r,parentId:(a=(n=t[e-1])==null?void 0:n.id)!=null?a:null,index:e}})}getMessageById(e){return this._getMessageRuntime(E(m({},this.path),{ref:this.path.ref+`${this.path.ref}.messages[messageId=${JSON.stringify(e)}]`,messageSelector:{type:"messageId",messageId:e}}),()=>this._threadBinding.getState().getMessageById(e))}_getMessageRuntime(e,t){return new Qc(new tt({path:e,getState:()=>{var d,c;const{message:r,parentId:n,index:a}=(d=t())!=null?d:{},{messages:i,speech:s}=this._threadBinding.getState();if(!r||n===void 0||a===void 0)return et;const l=this._threadBinding.getState().getBranches(r.id),u=r.metadata.submittedFeedback;return E(m({},r),{[zr]:r[zr],index:a,isLast:((c=i.at(-1))==null?void 0:c.id)===r.id,parentId:n,branchNumber:l.indexOf(r.id)+1,branchCount:l.length,speech:(s==null?void 0:s.messageId)===r.id?s:void 0,submittedFeedback:u})},subscribe:r=>this._threadBinding.subscribe(r)}),this._threadBinding)}unstable_on(e,t){let r=this._eventSubscriptionSubjects.get(e);return r||(r=new Ai({event:e,binding:this._threadBinding}),this._eventSubscriptionSubjects.set(e,r)),r.subscribe(t)}},nd=e=>({mainThreadId:e.mainThreadId,newThread:e.newThreadId,threads:e.threadIds,archivedThreads:e.archivedThreadIds,isLoading:e.isLoading,threadItems:e.threadData}),Hr=(e,t)=>{if(t===void 0)return et;const r=e.getItemById(t);return r?{id:r.id,threadId:r.id,remoteId:r.remoteId,externalId:r.externalId,title:r.title,status:r.status,isMain:r.id===e.mainThreadId}:et},ad=class{constructor(e,t=ji){C(this,"_getState");C(this,"_mainThreadListItemRuntime");C(this,"main");this._core=e,this._runtimeFactory=t;const r=new On({path:{},getState:()=>nd(e),subscribe:n=>e.subscribe(n)});this._getState=r.getState.bind(r),this._mainThreadListItemRuntime=new Br(new tt({path:{ref:"threadItems[main]",threadSelector:{type:"main"}},getState:()=>Hr(this._core,this._core.mainThreadId),subscribe:n=>this._core.subscribe(n)}),this._core),this.main=new t(new $r({path:{ref:"threads.main",threadSelector:{type:"main"}},getState:()=>e.getMainThreadRuntimeCore(),subscribe:n=>e.subscribe(n)}),this._mainThreadListItemRuntime),this.__internal_bindMethods()}__internal_bindMethods(){this.switchToThread=this.switchToThread.bind(this),this.switchToNewThread=this.switchToNewThread.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getById=this.getById.bind(this),this.getItemById=this.getItemById.bind(this),this.getItemByIndex=this.getItemByIndex.bind(this),this.getArchivedItemByIndex=this.getArchivedItemByIndex.bind(this)}switchToThread(e){return this._core.switchToThread(e)}switchToNewThread(){return this._core.switchToNewThread()}getState(){return this._getState()}subscribe(e){return this._core.subscribe(e)}get mainItem(){return this._mainThreadListItemRuntime}getById(e){return new this._runtimeFactory(new $r({path:{ref:`threads[threadId=${JSON.stringify(e)}]`,threadSelector:{type:"threadId",threadId:e}},getState:()=>this._core.getThreadRuntimeCore(e),subscribe:t=>this._core.subscribe(t)}),this.mainItem)}getItemByIndex(e){return new Br(new tt({path:{ref:`threadItems[${e}]`,threadSelector:{type:"index",index:e}},getState:()=>Hr(this._core,this._core.threadIds[e]),subscribe:t=>this._core.subscribe(t)}),this._core)}getArchivedItemByIndex(e){return new Br(new tt({path:{ref:`archivedThreadItems[${e}]`,threadSelector:{type:"archiveIndex",index:e}},getState:()=>Hr(this._core,this._core.archivedThreadIds[e]),subscribe:t=>this._core.subscribe(t)}),this._core)}getItemById(e){return new Br(new tt({path:{ref:`threadItems[threadId=${e}]`,threadSelector:{type:"threadId",threadId:e}},getState:()=>Hr(this._core,e),subscribe:t=>this._core.subscribe(t)}),this._core)}},id=e=>e.startsWith("image/")?"image":e.startsWith("text/")?"document":"file",sd=class{constructor(e){C(this,"accept","*");C(this,"uploadedUrls",new Map);this.cloud=e}add(t){return Pr(this,arguments,function*({file:e}){const r=crypto.randomUUID(),n=id(e.type);let a={id:r,type:n,name:e.name,contentType:e.type,file:e,status:{type:"running",reason:"uploading",progress:0}};yield a;try{const{signedUrl:i,publicUrl:s}=yield new Ne(this.cloud.files.generatePresignedUploadUrl({filename:e.name}));yield new Ne(fetch(i,{method:"PUT",body:e,headers:{"Content-Type":e.type},mode:"cors"})),this.uploadedUrls.set(r,s),a=E(m({},a),{status:{type:"requires-action",reason:"composer-send"}}),yield a}catch(i){a=E(m({},a),{status:{type:"incomplete",reason:"error"}}),yield a}})}remove(e){return P(this,null,function*(){this.uploadedUrls.delete(e.id)})}send(e){return P(this,null,function*(){const t=this.uploadedUrls.get(e.id);if(!t)throw new Error("Attachment not uploaded");this.uploadedUrls.delete(e.id);let r;return e.type==="image"?r=[{type:"image",image:t,filename:e.name}]:r=[{type:"file",data:t,mimeType:e.contentType,filename:e.name}],E(m({},e),{status:{type:"complete"},content:r})})}},Fn=y.createContext(null),Bn=({adapters:e,children:t})=>{const r=y.useContext(Fn);return p.jsx(Fn.Provider,{value:m(m({},r),e),children:t})},od=()=>y.useContext(Fn),ld=class extends di{constructor(t,r,{parentId:n,message:a}){var i;super();C(this,"_nonTextParts");C(this,"_previousText");C(this,"_parentId");C(this,"_sourceId");this.runtime=t,this.endEditCallback=r,this._parentId=n,this._sourceId=a.id,this._previousText=Rr(a),this.setText(this._previousText),this.setRole(a.role),this.setAttachments((i=a.attachments)!=null?i:[]),this._nonTextParts=a.content.filter(s=>s.type!=="text"),this.setRunConfig(m({},t.composer.runConfig))}get canCancel(){return!0}getAttachmentAdapter(){var t;return(t=this.runtime.adapters)==null?void 0:t.attachments}handleSend(t){return P(this,null,function*(){Rr(t)!==this._previousText&&this.runtime.append(E(m({},t),{content:[...t.content,...this._nonTextParts],parentId:this._parentId,sourceId:this._sourceId})),this.handleCancel()})}handleCancel(){this.endEditCallback(),this._notifySubscribers()}},ud=class{constructor(e){C(this,"_subscriptions",new Set);C(this,"_isInitialized",!1);C(this,"repository",new Ci);C(this,"composer",new hi(this));C(this,"_editComposers",new Map);C(this,"_stopSpeaking");C(this,"speech");C(this,"_eventSubscribers",new Map);this._contextProvider=e}get messages(){return this.repository.getMessages()}get state(){var t;let e;for(const r of this.messages)if(r.role==="assistant"){e=r;break}return(t=e==null?void 0:e.metadata.unstable_state)!=null?t:null}getModelContext(){return this._contextProvider.getModelContext()}getEditComposer(e){return this._editComposers.get(e)}beginEdit(e){if(this._editComposers.has(e))throw new Error("Edit already in progress");this._editComposers.set(e,new ld(this,()=>this._editComposers.delete(e),this.repository.getMessage(e))),this._notifySubscribers()}getMessageById(e){try{return this.repository.getMessage(e)}catch(t){return}}getBranches(e){return this.repository.getBranches(e)}switchToBranch(e){this.repository.switchToBranch(e),this._notifySubscribers()}_notifySubscribers(){for(const e of this._subscriptions)e()}_notifyEventSubscribers(e){const t=this._eventSubscribers.get(e);if(t)for(const r of t)r()}subscribe(e){return this._subscriptions.add(e),()=>this._subscriptions.delete(e)}submitFeedback({messageId:e,type:t}){var i;const r=(i=this.adapters)==null?void 0:i.feedback;if(!r)throw new Error("Feedback adapter not configured");const{message:n,parentId:a}=this.repository.getMessage(e);if(r.submit({message:n,type:t}),n.role==="assistant"){const s=E(m({},n),{metadata:E(m({},n.metadata),{submittedFeedback:{type:t}})});this.repository.addOrUpdateMessage(a,s)}this._notifySubscribers()}speak(e){var i,s;const t=(i=this.adapters)==null?void 0:i.speech;if(!t)throw new Error("Speech adapter not configured");const{message:r}=this.repository.getMessage(e);(s=this._stopSpeaking)==null||s.call(this);const n=t.speak(Rr(r)),a=n.subscribe(()=>{n.status.type==="ended"?(this._stopSpeaking=void 0,this.speech=void 0):this.speech={messageId:e,status:n.status},this._notifySubscribers()});this.speech={messageId:e,status:n.status},this._notifySubscribers(),this._stopSpeaking=()=>{n.cancel(),a(),this.speech=void 0,this._stopSpeaking=void 0}}stopSpeaking(){if(!this._stopSpeaking)throw new Error("No message is being spoken");this._stopSpeaking(),this._notifySubscribers()}ensureInitialized(){this._isInitialized||(this._isInitialized=!0,this._notifyEventSubscribers("initialize"))}export(){return this.repository.export()}import(e){this.ensureInitialized(),this.repository.clear(),this.repository.import(e),this._notifySubscribers()}reset(e){this.import(Dn.fromArray(e!=null?e:[]))}unstable_on(e,t){var n,a,i;if(e==="model-context-update")return(i=(a=(n=this._contextProvider).subscribe)==null?void 0:a.call(n,t))!=null?i:(()=>{});const r=this._eventSubscribers.get(e);return r?r.add(t):this._eventSubscribers.set(e,new Set([t])),()=>{this._eventSubscribers.get(e).delete(t)}}},cd=e=>{try{return JSON.parse(e),!0}catch(t){return!1}};function dd({state:e,getTools:t,onResult:r,setToolStatuses:n}){const a=y.useRef({}),i=y.useRef(new Map),s=y.useRef(new AbortController),o=y.useRef(0),l=y.useRef([]),[u]=y.useState(()=>{const[f,g]=Ti(),v=Gc(t,()=>{var b,w;return(w=(b=s.current)==null?void 0:b.signal)!=null?w:new AbortController().signal},(b,w)=>new Promise((T,_)=>{const D=i.current.get(b);D&&D.reject(new Error("Human input request was superseded by a new request")),i.current.set(b,{resolve:T,reject:_}),n(z=>E(m({},z),{[b]:{type:"interrupt",payload:{type:"human",payload:w}}}))}),{onExecutionStart:b=>{o.current++,n(w=>E(m({},w),{[b]:{type:"executing"}}))},onExecutionEnd:b=>{o.current--,n(w=>{const T=m({},w);return delete T[b],T}),o.current===0&&(l.current.forEach(w=>w()),l.current=[])}});return f.pipeThrough(v).pipeThrough(new Si).pipeTo(new WritableStream({write(b){var w;if(b.type==="result"){if((w=a.current[b.meta.toolCallId])!=null&&w.hasResult)return;r(m({type:"add-tool-result",toolCallId:b.meta.toolCallId,toolName:b.meta.toolName,result:b.result,isError:b.isError},b.artifact&&{artifact:b.artifact}))}}})),g}),d=y.useRef(new Set),c=y.useRef(!0);y.useEffect(()=>{const f=g=>{g.forEach(v=>{v.content.forEach(b=>{if(b.type==="tool-call"){if(c.current)d.current.add(b.toolCallId);else{if(d.current.has(b.toolCallId))return;let w=a.current[b.toolCallId];if(w||(w={argsText:"",hasResult:!1,argsComplete:!1,controller:u.addToolCallPart({toolName:b.toolName,toolCallId:b.toolCallId})},a.current[b.toolCallId]=w),b.argsText!==w.argsText)if(w.argsComplete)process.env.NODE_ENV!=="production"&&console.warn("argsText updated after controller was closed:",{previous:w.argsText,next:b.argsText});else{if(!b.argsText.startsWith(w.argsText))throw new Error(`Tool call argsText can only be appended, not updated: ${b.argsText} does not start with ${w.argsText}`);const T=b.argsText.slice(w.argsText.length);w.controller.argsText.append(T);const _=cd(b.argsText);_&&w.controller.argsText.close(),a.current[b.toolCallId]={argsText:b.argsText,hasResult:w.hasResult,argsComplete:_,controller:w.controller}}b.result!==void 0&&!w.hasResult&&(w.controller.setResponse(new mt({result:b.result,artifact:b.artifact,isError:b.isError})),w.controller.close(),a.current[b.toolCallId]={hasResult:!0,argsComplete:!0,argsText:w.argsText,controller:w.controller})}b.messages&&f(b.messages)}})})};f(e.messages),c.current&&(c.current=!1)},[e,u,r]);const h=()=>(i.current.forEach(({reject:f})=>{f(new Error("Tool execution aborted"))}),i.current.clear(),s.current.abort(),s.current=new AbortController,o.current===0?Promise.resolve():new Promise(f=>{l.current.push(f)}));return{reset:()=>{h(),c.current=!0},abort:h,resume:(f,g)=>{const v=i.current.get(f);if(v)i.current.delete(f),n(b=>E(m({},b),{[f]:{type:"executing"}})),v.resolve(g);else throw new Error(`Tool call ${f} is not waiting for human input`)}}}var hd=class{list(){return Promise.resolve({threads:[]})}rename(){return Promise.resolve()}archive(){return Promise.resolve()}unarchive(){return Promise.resolve()}delete(){return Promise.resolve()}initialize(e){return Promise.resolve({remoteId:e,externalId:void 0})}generateTitle(){return Promise.resolve(new ReadableStream)}fetch(e){return Promise.reject(new Error("Thread not found"))}};function fd(e,t){e.commitTasks.forEach(r=>{const n=r.cellIndex,a=t.cells[n];if(a.type!=="effect")throw new Error("Cannot find effect cell");let i=!0;if(a.deps!==void 0&&r.deps!==void 0&&(i=a.deps.length!==r.deps.length||a.deps.some((s,o)=>!Object.is(s,r.deps[o]))),i){if(a.mounted){if(typeof a.deps!=typeof r.deps)throw new Error("tapEffect called with and without dependencies across re-renders");try{a.mounted&&a.cleanup&&a.cleanup()}finally{a.mounted=!1}}try{const s=r.effect();if(s!==void 0&&typeof s!="function")throw new Error(`An effect function must either return a cleanup function or nothing. Received: ${typeof s}`);a.mounted=!0,a.cleanup=typeof s=="function"?s:void 0,a.deps=r.deps}catch(s){throw s}}})}function pd(e){let t=null;for(let r=e.cells.length-1;r>=0;r--){const n=e.cells[r];if((n==null?void 0:n.type)==="effect"&&n.mounted&&n.cleanup)try{n.cleanup()}catch(a){t==null&&(t=a)}finally{n.mounted=!1}}if(t!=null)throw t}var lr=null;function md(e,t){e.currentIndex=0;const r=lr;lr=e;try{if(t(),e.isFirstRender=!1,e.cells.length!==e.currentIndex)throw new Error(`Rendered ${e.currentIndex} hooks but expected ${e.cells.length}. Hooks must be called in the exact same order in every render.`)}finally{lr=r}}function zn(){if(!lr)throw new Error("No resource fiber available");return lr}function $i(e,t){const r=e[Ui];if(!r)throw new Error("ResourceElement.type is not a valid Resource");return r(t)}var Ui=Symbol("fnSymbol");function qr(e,t){return{resource:e,scheduleRerender:t,cells:[],currentIndex:0,renderContext:void 0,isFirstRender:!0,isMounted:!1,isNeverMounted:!0}}function zt(e){e.isMounted=!1,pd(e)}function ur(e,t){const r={commitTasks:[],props:t,state:void 0};return md(e,()=>{e.renderContext=r;try{r.state=$i(e.resource,t)}finally{e.renderContext=void 0}}),r}function Rt(e,t){e.isMounted=!0,e.isNeverMounted=!1,fd(t,e)}var gd=globalThis.__ASSISTANT_UI_DISABLE_LAYOUT_EFFECT__===!0,Hi=gd?y.useEffect:y.useLayoutEffect;function Rn(e){const[,t]=y.useState({}),r=y.useMemo(()=>qr(e.type,()=>t({})),[e.type,t]),n=ur(r,e.props);return Hi(()=>()=>zt(r),[]),Hi(()=>{Rt(r,n)}),n.state}var jt=e=>typeof e=="string"?{scope:e.split(".")[0],event:e}:{scope:e.scope,event:e.event},Ct=(e,t,r)=>t===e,$t,jn=()=>{if($t)return $t;const e=()=>({apis:new Map,nextId:0,listeners:new Set});if(typeof window=="undefined")return $t=e(),$t;const t=window.__ASSISTANT_UI_DEVTOOLS_HOOK__;if(t)return $t=t,t;const r=e();return window.__ASSISTANT_UI_DEVTOOLS_HOOK__=r,$t=r,r},yd=(it=class{static register(t){var o,l;const r=jn();for(const u of r.apis.values())if(u.api===t)return()=>{};const n=r.nextId++,a={api:t,logs:[]},i=(o=t.on)==null?void 0:o.call(t,"*",u=>{const d=r.apis.get(n);d&&(d.logs.push({time:new Date,event:u.event,data:u.payload}),d.logs.length>it.MAX_EVENT_LOGS_PER_API&&(d.logs=d.logs.slice(-200)),it.notifyListeners(n))}),s=(l=t.subscribe)==null?void 0:l.call(t,()=>{it.notifyListeners(n)});return r.apis.set(n,a),it.notifyListeners(n),()=>{const u=jn();u.apis.get(n)&&(i==null||i(),s==null||s(),u.apis.delete(n),it.notifyListeners(n))}}static notifyListeners(t){jn().listeners.forEach(n=>n(t))}},C(it,"MAX_EVENT_LOGS_PER_API",200),it);function ge(e){const t=(r,n)=>m({type:t,props:r},(n==null?void 0:n.key)!==void 0&&{key:n.key});return t[Ui]=e,t}var bd=e=>{if(e.renderContext)throw new Error("Resource updated during render");if(e.isNeverMounted)throw new Error("Resource updated before mount");e.isMounted&&e.scheduleRerender()};function wd(e){const t=zn(),r=t.currentIndex++;if(!t.isFirstRender&&r>=t.cells.length)throw new Error("Rendered more hooks than during the previous render. Hooks must be called in the exact same order in every render.");if(!t.cells[r]){const i={type:"state",value:typeof e=="function"?e():e,set:s=>{const o=i.value,l=typeof s=="function"?s(o):s;Object.is(o,l)||(i.value=l,bd(t))}};t.cells[r]=i}const n=t.cells[r];if(n.type!=="state")throw new Error("Hook order changed between renders");return n}function lt(e){const t=wd(e);return[t.value,t.set]}function xd(){const e=zn(),t=e.currentIndex++;if(!e.isFirstRender&&t>=e.cells.length)throw new Error("Rendered more hooks than during the previous render. Hooks must be called in the exact same order in every render.");if(!e.cells[t]){const n={type:"effect",mounted:!1};e.cells[t]=n}if(e.cells[t].type!=="effect")throw new Error("Hook order changed between renders");return t}function Oe(e,t){const r=zn(),n=xd();r.renderContext.commitTasks.push({effect:e,deps:t,cellIndex:n})}function Ut(e){const[t]=lt(()=>({current:e}));return t}var vd=(e,t)=>{if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Object.is(e[r],t[r]))return!1;return!0},oe=(e,t)=>{const r=Ut();return r.current||(r.current={value:e(),deps:t}),vd(r.current.deps,t)||(r.current.value=e(),r.current.deps=t),r.current.value};function Vr(e,t){const[r,n]=lt({}),a=oe(()=>qr(e.type,()=>n({})),[e.type]),i=t?oe(()=>e.props,t):e.props,s=oe(()=>ur(a,i),[a,i,r]);return Oe(()=>()=>zt(a),[a]),Oe(()=>{Rt(a,s)},[a,s]),s.state}function rt(e){return $i(e.type,e.props)}function qi(e){const t=new Set;e.forEach((o,l)=>{if(o.key===void 0)throw new Error(`tapResources: All resource elements must have a key. Element at index ${l} is missing a key.`);if(t.has(o.key))throw new Error(`tapResources: Duplicate key "${o.key}" found. All keys must be unique.`);t.add(o.key)});const[r,n]=lt({}),a=oe(()=>new Map(e.map(o=>[o.key,o])),[e]),[i]=lt(()=>new Map),s=oe(()=>{const o=new Map,l=new Set;return a.forEach((u,d)=>{l.add(d);let c=i.get(d);(!c||c.resource!==u.type)&&(c&&zt(c),c=qr(u.type,()=>n({})),i.set(d,c));const h=ur(c,u.props);o.set(d,h)}),i.forEach((u,d)=>{l.has(d)||(zt(u),i.delete(d))}),o},[a,r]);return Oe(()=>{s.forEach((o,l)=>{const u=i.get(l);u&&Rt(u,o)})},[s,i]),Oe(()=>()=>{i.forEach(o=>{zt(o)}),i.clear()},[i]),oe(()=>e.map(o=>{var l;return(l=s.get(o.key))==null?void 0:l.state}),[e,s])}var $n=[],Un=!1;function kd(){Un=!1;const e=$n;$n=[];for(const t of e)try{t()}catch(r){console.error("Error in scheduled task:",r)}}function Sd(e){$n.push(e),Un||(Un=!0,queueMicrotask(kd))}var _d=(Lt=class{constructor(t){C(this,"_isDirty",!1);C(this,"_hasScheduledTask",!1);C(this,"_isFlushing",!1);this._task=t}get isDirty(){return this._isDirty}markDirty(){this._isDirty=!0,!(this._hasScheduledTask||this._isFlushing)&&(this._hasScheduledTask=!0,Sd(()=>{this._hasScheduledTask=!1,this.flushSync()}))}flushSync(){if(this._isFlushing)return;this._isFlushing=!0;let t=0;try{for(;this._isDirty;){if(t++,t>Lt.MAX_FLUSH_DEPTH)throw new Error("Maximum update depth exceeded. This can happen when a resource repeatedly calls setState inside tapEffect.");this._isDirty=!1,this._task()}}finally{this._isFlushing=!1}}},C(Lt,"MAX_FLUSH_DEPTH",50),Lt),Td=ge(({element:e,onUpdateInput:t,onFlushSync:r,onDispose:n})=>{const[a,i]=lt(e.props),s=rt({type:e.type,props:a}),o=Ut(new Set).current,l=Ut(s);return Oe(()=>{s!==l.current&&(l.current=s,o.forEach(d=>d()))}),oe(()=>({getState:()=>l.current,subscribe:d=>(o.add(d),()=>o.delete(d)),updateInput:d=>{t(),i(()=>d)},flushSync:r,dispose:n}),[])}),Cd=(e,t=!1)=>{let r=!t;const n={element:e,onUpdateInput:()=>{r||(r=!0,Rt(i,s))},onFlushSync:()=>{a.flushSync()},onDispose:()=>zt(i)},a=new _d(()=>{s=ur(i,n),r&&Rt(i,s)}),i=qr(Td,()=>a.markDirty());let s=ur(i,n);return r&&Rt(i,s),s.state},cr=Symbol("tap.Context"),Vi=e=>({[cr]:e}),Wi=(e,t,r)=>{const n=e[cr];e[cr]=t;try{return r()}finally{e[cr]=n}},Ji=e=>e[cr];const Yi=e=>{let t;const r=new Set,n=(u,d)=>{const c=typeof u=="function"?u(t):u;if(!Object.is(c,t)){const h=t;t=(d!=null?d:typeof c!="object"||c===null)?c:Object.assign({},t,c),r.forEach(f=>f(t,h))}},a=()=>t,o={setState:n,getState:a,getInitialState:()=>l,subscribe:u=>(r.add(u),()=>r.delete(u))},l=t=e(n,a,o);return o},Id=(e=>e?Yi(e):Yi),Ed=e=>e;function Ad(e,t=Ed){const r=y.useSyncExternalStore(e.subscribe,y.useCallback(()=>t(e.getState()),[e,t]),y.useCallback(()=>t(e.getInitialState()),[e,t]));return y.useDebugValue(r),r}const Ki=e=>{const t=Id(e),r=n=>Ad(t,n);return Object.assign(r,t),r},Ht=(e=>e?Ki(e):Ki);function Gi(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Xi(...e){return t=>{let r=!1;const n=e.map(a=>{const i=Gi(a,t);return!r&&typeof i=="function"&&(r=!0),i});if(r)return()=>{for(let a=0;a<n.length;a++){const i=n[a];typeof i=="function"?i():Gi(e[a],null)}}}}function Wr(...e){return K.useCallback(Xi(...e),e)}var Qi=ge(e=>{const t=oe(()=>Cd(e,!0),[e.type]);return Oe(()=>{t.updateInput(e.props)}),t}),Md=class{constructor(e){this.getApi=e}get(e,t){return this.getApi()[t]}ownKeys(){return Object.keys(this.getApi())}has(e,t){return t in this.getApi()}getOwnPropertyDescriptor(e,t){return Object.getOwnPropertyDescriptor(this.getApi(),t)}set(){return!1}defineProperty(){return!1}deleteProperty(){return!1}},nt=(e,t)=>{const r=Ut(e);Oe(()=>{r.current=e});const n=oe(()=>new Proxy({},new Md(()=>r.current)),[]),a=t==null?void 0:t.key,i=e.getState();return oe(()=>({key:a,state:i,api:n}),[i,a])},gt=ge(e=>{const t=Ut(e.get);return Oe(()=>{t.current=e.get}),oe(()=>Ie({source:e.source,query:e.query,get:()=>t.current()}),[e.source,JSON.stringify(e.query)])}),Pd=ge(e=>{const t=Vr(e.scopeElement);return oe(()=>[e.fieldName,t],[e.fieldName,t])}),Nd=ge(e=>{const o=e,{on:t,subscribe:r,flushSync:n}=o,a=V(o,["on","subscribe","flushSync"]),i=Ut({on:t,subscribe:r,flushSync:n});Oe(()=>{i.current={on:t,subscribe:r,flushSync:n}});const s=qi(Object.entries(a).map(([l,u])=>Pd({fieldName:l,scopeElement:u},{key:l})));return oe(()=>{const l=Object.fromEntries(s),{on:u,subscribe:d,flushSync:c}=i.current;return u&&(l.on=(h,f)=>u(h,f)),d&&(l.subscribe=h=>d(h)),c&&(l.flushSync=()=>c()),l},[...s])}),Zi=Vi(null),Ld=(e,t)=>Wi(Zi,e,t),es=()=>{const e=Ji(Zi);if(!e)throw new Error("Model context is not available in this context");return e},Dd=ge(({toolkit:e})=>{const[t,r]=lt(()=>({tools:{}})),n=es();Oe(()=>{if(!e)return;const i=[];for(const[l,u]of Object.entries(e))u.render&&i.push(a(l,u.render));const s=Object.entries(e).reduce((l,[u,d])=>{const f=d,{render:c}=f,h=V(f,["render"]);return l[u]=h,l},{}),o={getModelContext:()=>({tools:s})};return i.push(n.register(o)),()=>{i.forEach(l=>l())}},[e,n]);const a=(i,s)=>(r(o=>{var l;return E(m({},o),{tools:E(m({},o.tools),{[i]:[...(l=o.tools[i])!=null?l:[],s]})})}),()=>{r(o=>{var l,u;return E(m({},o),{tools:E(m({},o.tools),{[i]:(u=(l=o.tools[i])==null?void 0:l.filter(d=>d!==s))!=null?u:[]})})})});return nt({getState:()=>t,setToolUI:a})}),Od=ge(()=>oe(()=>{const t=new Map;return{on:(r,n)=>{t.has(r)||t.set(r,new Set);const a=t.get(r);return a.add(n),()=>{a.delete(n),a.size===0&&t.delete(r)}},emit:(r,n)=>{const a=t.get(r),i=t.get("*");!a&&!i||queueMicrotask(()=>{if(a)for(const s of a)s(n);if(i)for(const s of i)s({event:r,payload:n})})}}},[])),ts=Vi(null),Fd=(e,t)=>Wi(ts,e,t),Hn=()=>{const e=Ji(ts);if(!e)throw new Error("Events context is not available");return e},Bd=ge(()=>{const[e]=lt(()=>({})),t=new En;return nt({getState:()=>e,getModelContext:()=>t.getModelContext(),subscribe:r=>t.subscribe(r),register:r=>t.registerModelContextProvider(r)})}),zd=ge(({threads:e,modelContext:t,tools:r})=>{const n=rt(Od()),{threads:a,tools:i,modelContext:s}=Fd(n,()=>{const l=Vr(t!=null?t:Bd(),[t]);return Ld(l.api,()=>({modelContext:l,tools:Vr(r!=null?r:Dd({}),[r]),threads:Vr(e,[e])}))}),o=oe(()=>({threads:a.state,tools:i.state,modelContext:s.state}),[a.state,i.state,s.state]);return nt({getState:()=>o,threads:a.api,tools:i.api,modelContext:s.api,on:n.on})}),Rd=e=>{const t=()=>e.getState().api.threads.item("main");return{threads:Ie({source:"root",query:{},get:()=>e.getState().api.threads}),tools:Ie({source:"root",query:{},get:()=>e.getState().api.tools}),modelContext:Ie({source:"root",query:{},get:()=>e.getState().api.modelContext}),thread:Ie({source:"threads",query:{type:"main"},get:()=>e.getState().api.threads.thread("main")}),threadListItem:Ie({source:"threads",query:{type:"main"},get:()=>t()}),composer:Ie({source:"thread",query:{},get:()=>e.getState().api.threads.thread("main").composer}),on(r,n){const{event:a,scope:i}=jt(r);if(i==="*")return e.getState().api.on(a,n);if(Ct("thread",i)||Ct("thread-list-item",i)||Ct("composer",i))return e.getState().api.on(a,s=>{s.threadId===t().getState().id&&n(s)});throw new Error(`Event scope is not available in this component: ${i}`)},subscribe:e.subscribe,flushSync:e.flushSync}},jd=e=>{const t=Jr(),r=Rn(Qi(zd(e))),n=y.useMemo(()=>Rd(r),[r]);return y.useMemo(()=>ns(t,n),[t,n])},Ie=e=>{const t=e.get;return t.source=e.source,t.query=e.query,t},yt=()=>()=>{},rs=y.createContext({threads:Ie({source:null,query:{},get:()=>{throw new Error("Threads is only available inside <AssistantProvider />")}}),tools:Ie({source:null,query:{},get:()=>{throw new Error("Tools is only available inside <AssistantProvider />")}}),modelContext:Ie({source:null,query:{},get:()=>{throw new Error("ModelContext is only available inside <AssistantProvider />")}}),threadListItem:Ie({source:null,query:{},get:()=>{throw new Error("ThreadListItem is only available inside <AssistantProvider />")}}),thread:Ie({source:null,query:{},get:()=>{throw new Error("Thread is only available inside <AssistantProvider />")}}),composer:Ie({source:null,query:{},get:()=>{throw new Error("Composer is only available inside <AssistantProvider />")}}),message:Ie({source:null,query:{},get:()=>{throw new Error("Message is only available inside <ThreadPrimitive.Messages />")}}),part:Ie({source:null,query:{},get:()=>{throw new Error("Part is only available inside <MessagePrimitive.Parts />")}}),attachment:Ie({source:null,query:{},get:()=>{throw new Error("Attachment is only available inside <MessagePrimitive.Attachments /> or <ComposerPrimitive.Attachments />")}}),subscribe:yt,flushSync:yt,on:e=>{const{scope:t}=jt(e);throw new Error(`Event scope is not available in this component: ${t}`)}}),Jr=()=>y.useContext(rs),It=e=>{const t=Jr(),r=Rn(Nd(e));return y.useMemo(()=>ns(t,r),[t,r])},$d=e=>jd(e);function fe(e){return e?$d(e):Jr()}var Ud=(e,t)=>e===yt?t:t===yt?e:(...r)=>{e(...r),t(...r)},Hd=(e,t)=>e===yt?t:t===yt?e:(...r)=>{const n=e(...r),a=t(...r);return()=>{n(),a()}},ns=(e,t)=>{const r=t.subscribe,n=t.flushSync;return E(m(m({},e),t),{subscribe:Hd(e.subscribe,r!=null?r:yt),flushSync:Ud(e.flushSync,n!=null?n:yt)})},bt=({api:e,children:t,devToolsVisible:r=!0})=>(y.useEffect(()=>{if(!(!r||!e.subscribe))return yd.register(e)},[e,r]),p.jsx(rs.Provider,{value:e,children:t})),as=(_u=class{constructor(e){er(this,Qe);tr(this,Qe,e)}get threads(){return Ke(this,Qe).threads().getState()}get tools(){return Ke(this,Qe).tools().getState()}get threadListItem(){return Ke(this,Qe).threadListItem().getState()}get thread(){return Ke(this,Qe).thread().getState()}get composer(){return Ke(this,Qe).composer().getState()}get message(){return Ke(this,Qe).message().getState()}get part(){return Ke(this,Qe).part().getState()}get attachment(){return Ke(this,Qe).attachment().getState()}},Qe=new WeakMap,_u),re=e=>{const t=fe(),r=y.useMemo(()=>new as(t),[t]),n=y.useSyncExternalStore(t.subscribe,()=>e(r),()=>e(r));if(y.useDebugValue(n),n instanceof as)throw new Error("You tried to return the entire AssistantState. This is not supported due to technical limitations.");return n},qn=(e,t)=>{const r=fe(),n=y.useRef(t);y.useEffect(()=>{n.current=t});const{scope:a,event:i}=jt(e);y.useEffect(()=>r.on({scope:a,event:i},s=>n.current(s)),[r,a,i])};function qd(e,t){function r(n){const a=y.useContext(e);if(!(n!=null&&n.optional)&&!a)throw new Error(`This component must be used within ${t}.`);return a}return r}function is(e,t){function r(a){const i=e(a);return i?i[t]:null}function n(a){let i=!1,s;typeof a=="function"?s=a:a&&typeof a=="object"&&(i=!!a.optional,s=a.selector);const o=r({optional:i});return o?s?o(s):o():null}return{[t]:n,[`${t}Store`]:r}}var ss=y.createContext(null),Vd=qd(ss,"ThreadPrimitive.Viewport"),{useThreadViewport:Yr,useThreadViewportStore:Vn}=is(Vd,"useThreadViewport"),Wd=e=>{var r;const t=e;t.__isBound||((r=t.__internal_bindMethods)==null||r.call(t),t.__isBound=!0)};function Jd(e,t=Yd){Wd(e);const r=y.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getState()));return y.useDebugValue(r),r}var Yd=e=>e;function os(e){function t(r){let n=!1,a;typeof r=="function"?a=r:r&&(n=!!r.optional,a=r.selector);const i=e({optional:n});return i?Jd(i,a):null}return t}function ls(e){const t=fe(),r=re(()=>{var n,a,i;return t.thread.source&&(i=(a=(n=t.thread()).__internal_getRuntime)==null?void 0:a.call(n))!=null?i:null});if(!r&&!(e!=null&&e.optional))throw new Error("ThreadRuntime is not available");return r}var Kd=os(ls);function Gd(e){const t=fe(),r=re(()=>{var n,a,i;return t.threadListItem.source&&(i=(a=(n=t.threadListItem()).__internal_getRuntime)==null?void 0:a.call(n))!=null?i:null});if(!r&&!(e!=null&&e.optional))throw new Error("ThreadListItemRuntime is not available");return r}var us=os(Gd),Et=e=>{const[,t]=lt(e.getState);return Oe(()=>(t(e.getState()),e.subscribe(()=>{t(e.getState())})),[e]),e.getState()},Xd=ge(({runtime:e})=>{const t=Et(e),r=Hn();return Oe(()=>{const n=[],a=["switched-to","switched-away"];for(const i of a){const s=e.unstable_on(i,()=>{r.emit(`thread-list-item.${i}`,{threadId:e.getState().id})});n.push(s)}return()=>{for(const i of n)i()}},[e,r]),nt({getState:()=>t,switchTo:e.switchTo,rename:e.rename,archive:e.archive,unarchive:e.unarchive,delete:e.delete,generateTitle:e.generateTitle,initialize:e.initialize,detach:e.detach,__internal_getRuntime:()=>e},{key:t.id})}),dr=e=>{const t=qi(e);return{state:t.map(r=>r.state),api:r=>{var a,i;const n="index"in r?(a=t[r.index])==null?void 0:a.api:(i=t.find(s=>s.key===r.key))==null?void 0:i.api;if(!n)throw new Error(`tapLookupResources: Resource not found for lookup: ${JSON.stringify(r)}`);return n}}},cs=ge(({runtime:e})=>{const t=Et(e);return nt({getState:()=>t,remove:e.remove,__internal_getRuntime:()=>e},{key:t.id})}),Qd=ge(({runtime:e,index:t})=>{const r=oe(()=>e.getAttachmentByIndex(t),[e,t]);return rt(cs({runtime:r}))}),ds=ge(({threadIdRef:e,messageIdRef:t,runtime:r})=>{var o;const n=Et(r),a=Hn();Oe(()=>{const l=[],u=["send","attachment-add"];for(const d of u){const c=r.unstable_on(d,()=>{a.emit(`composer.${d}`,m({threadId:e.current},t&&{messageId:t.current}))});l.push(c)}return()=>{for(const d of l)d()}},[r,a,e,t]);const i=dr(n.attachments.map((l,u)=>Qd({runtime:r,index:u},{key:u}))),s=oe(()=>{var l;return{text:n.text,role:n.role,attachments:i.state,runConfig:n.runConfig,isEditing:n.isEditing,canCancel:n.canCancel,attachmentAccept:n.attachmentAccept,isEmpty:n.isEmpty,type:(l=n.type)!=null?l:"thread"}},[n,i.state]);return nt({getState:()=>s,setText:r.setText,setRole:r.setRole,setRunConfig:r.setRunConfig,addAttachment:r.addAttachment,reset:r.reset,clearAttachments:r.clearAttachments,send:r.send,cancel:r.cancel,beginEdit:(o=r.beginEdit)!=null?o:(()=>{throw new Error("beginEdit is not supported in this runtime")}),attachment:l=>"id"in l?i.api({key:l.id}):i.api(l),__internal_getRuntime:()=>r})}),Zd=ge(({runtime:e})=>{const t=Et(e);return nt({getState:()=>t,addToolResult:n=>e.addToolResult(n),resumeToolCall:n=>e.resumeToolCall(n),__internal_getRuntime:()=>e},{key:t.type==="tool-call"?`toolCallId-${t.toolCallId}`:void 0})}),eh=ge(({runtime:e,index:t})=>{const r=oe(()=>e.getAttachmentByIndex(t),[e,t]);return rt(cs({runtime:r}))}),th=ge(({runtime:e,index:t})=>{const r=oe(()=>e.getMessagePartByIndex(t),[e,t]);return rt(Zd({runtime:r}))}),rh=ge(({runtime:e,threadIdRef:t})=>{var h,f;const r=Et(e),[n,a]=lt(!1),[i,s]=lt(!1),o=oe(()=>({get current(){return e.getState().id}}),[e]),l=rt(ds({runtime:e.composer,threadIdRef:t,messageIdRef:o})),u=dr(r.content.map((g,v)=>th({runtime:e,index:v},{key:v}))),d=dr((f=(h=r.attachments)==null?void 0:h.map((g,v)=>eh({runtime:e,index:v},{key:v})))!=null?f:[]),c=oe(()=>E(m({},r),{parts:u.state,composer:l.state,isCopied:n,isHovering:i}),[r,u.state,l.state,n,i]);return nt({getState:()=>c,composer:l.api,reload:g=>e.reload(g),speak:()=>e.speak(),stopSpeaking:()=>e.stopSpeaking(),submitFeedback:g=>e.submitFeedback(g),switchToBranch:g=>e.switchToBranch(g),getCopyText:()=>e.unstable_getCopyText(),part:g=>"index"in g?u.api({index:g.index}):u.api({key:`toolCallId-${g.toolCallId}`}),attachment:g=>"id"in g?d.api({key:g.id}):d.api(g),setIsCopied:a,setIsHovering:s,__internal_getRuntime:()=>e},{key:r.id})}),nh=ge(({runtime:e,id:t,threadIdRef:r})=>{const n=oe(()=>e.getMessageById(t),[e,t]);return rt(rh({runtime:n,threadIdRef:r}))}),ah=ge(({runtime:e})=>{const t=Et(e),r=Hn();Oe(()=>{const o=[],l=["run-start","run-end","initialize","model-context-update"];for(const u of l){const d=e.unstable_on(u,()=>{var h;const c=((h=e.getState())==null?void 0:h.threadId)||"unknown";r.emit(`thread.${u}`,{threadId:c})});o.push(d)}return()=>{for(const u of o)u()}},[e]);const n=oe(()=>({get current(){return e.getState().threadId}}),[e]),a=rt(ds({runtime:e.composer,threadIdRef:n})),i=dr(t.messages.map(o=>nh({runtime:e,id:o.id,threadIdRef:n},{key:o.id}))),s=oe(()=>({isEmpty:i.state.length===0&&!t.isLoading,isDisabled:t.isDisabled,isLoading:t.isLoading,isRunning:t.isRunning,capabilities:t.capabilities,state:t.state,suggestions:t.suggestions,extras:t.extras,speech:t.speech,composer:a.state,messages:i.state}),[t,i,a.state]);return nt({getState:()=>s,composer:a.api,append:e.append,startRun:e.startRun,unstable_resumeRun:e.unstable_resumeRun,cancelRun:e.cancelRun,getModelContext:e.getModelContext,export:e.export,import:e.import,reset:e.reset,stopSpeaking:e.stopSpeaking,startVoice:()=>P(null,null,function*(){throw new Error("startVoice is not supported in this runtime")}),stopVoice:()=>P(null,null,function*(){throw new Error("stopVoice is not supported in this runtime")}),message:o=>"id"in o?i.api({key:o.id}):i.api(o),__internal_getRuntime:()=>e})}),ih=ge(({runtime:e,id:t})=>{const r=oe(()=>e.getItemById(t),[e,t]);return rt(Xd({runtime:r}))}),sh=ge(({runtime:e,__internal_assistantRuntime:t})=>{const r=Et(e),n=rt(ah({runtime:e.main})),a=dr(Object.keys(r.threadItems).map(s=>ih({runtime:e,id:s},{key:s}))),i=oe(()=>{var s;return{mainThreadId:r.mainThreadId,newThreadId:(s=r.newThread)!=null?s:null,isLoading:r.isLoading,threadIds:r.threads,archivedThreadIds:r.archivedThreads,threadItems:a.state,main:n.state}},[r,a.state,n.state]);return nt({getState:()=>i,thread:()=>n.api,item:s=>{if(s==="main")return a.api({key:i.mainThreadId});if("id"in s)return a.api({key:s.id});const{index:o,archived:l=!1}=s,u=l?i.archivedThreadIds[o]:i.threadIds[o];return a.api({key:u})},switchToThread:s=>{e.switchToThread(s)},switchToNewThread:()=>{e.switchToNewThread()},__internal_getAssistantRuntime:()=>t})}),oh=ge(e=>{const t=es();return Oe(()=>e.registerModelContextProvider(t),[e,t]),rt(sh({runtime:e.threads,__internal_assistantRuntime:e}))}),Wn=e=>{const t=new Map,r=()=>{let n=0;for(const a of t.values())n+=a;e(n)};return{register:()=>{const n=Symbol();return t.set(n,0),{setHeight:a=>{t.get(n)!==a&&(t.set(n,a),r())},unregister:()=>{t.delete(n),r()}}}}},lh=(e={})=>{const t=new Set,r=Wn(s=>{i.setState({height:E(m({},i.getState().height),{viewport:s})})}),n=Wn(s=>{i.setState({height:E(m({},i.getState().height),{inset:s})})}),a=Wn(s=>{i.setState({height:E(m({},i.getState().height),{userMessage:s})})}),i=Ht(()=>{var s;return{isAtBottom:!0,scrollToBottom:({behavior:o="auto"}={})=>{for(const l of t)l({behavior:o})},onScrollToBottom:o=>(t.add(o),()=>{t.delete(o)}),turnAnchor:(s=e.turnAnchor)!=null?s:"bottom",height:{viewport:0,inset:0,userMessage:0},registerViewport:r.register,registerContentInset:n.register,registerUserMessageHeight:a.register}});return i},hr=e=>e,uh=e=>{const t=Vn({optional:!0}),[r]=y.useState(()=>lh(e));return y.useEffect(()=>t==null?void 0:t.getState().onScrollToBottom(()=>{r.getState().scrollToBottom()}),[t,r]),y.useEffect(()=>{if(t)return r.subscribe(n=>{t.getState().isAtBottom!==n.isAtBottom&&hr(t).setState({isAtBottom:n.isAtBottom})})},[r,t]),y.useEffect(()=>{var i;const n={turnAnchor:(i=e.turnAnchor)!=null?i:"bottom"};r.getState().turnAnchor!==n.turnAnchor&&hr(r).setState(n)},[r,e.turnAnchor]),r},hs=({children:e,options:t={}})=>{const r=uh(t),[n]=y.useState(()=>({useThreadViewport:r}));return p.jsx(ss.Provider,{value:n,children:e})},ch=e=>{var t;return(t=e._core)==null?void 0:t.RenderComponent},dh=({children:e,runtime:t})=>{const r=fe({threads:oh(t)}),n=ch(t);return p.jsxs(bt,{api:r,children:[n&&p.jsx(n,{}),p.jsx(hs,{children:e})]})},fs=y.memo(dh),hh=({index:e,archived:t,children:r})=>{const n=fe(),a=It({threadListItem:gt({source:"threads",query:{type:"index",index:e,archived:t},get:()=>n.threads().item({index:e,archived:t})}),on(i,s){const o=()=>n.threads().item({index:e,archived:t}),{event:l,scope:u}=jt(i);return Ct("thread-list-item",u)?n.on({scope:"*",event:l},d=>{d.threadId===o().getState().id&&s(d)}):n.on(i,s)}});return p.jsx(bt,{api:a,children:r})},fh=({id:e,children:t})=>{const r=fe(),n=It({threadListItem:gt({source:"threads",query:{type:"id",id:e},get:()=>r.threads().item({id:e})}),on(a,i){const s=()=>r.threads().item({id:e}),{event:o,scope:l}=jt(a);return Ct("thread-list-item",l)?r.on({scope:"*",event:o},u=>{u.threadId===s().getState().id&&i(u)}):r.on(a,i)}});return p.jsx(bt,{api:n,children:t})},ph=({index:e,children:t})=>{const r=fe(),n=It({message:gt({source:"thread",query:{type:"index",index:e},get:()=>r.thread().message({index:e})}),composer:gt({source:"message",query:{},get:()=>r.thread().message({index:e}).composer}),on(a,i){const s=()=>r.thread().message({index:e}),{event:o,scope:l}=jt(a);return!Ct("composer",l)&&!Ct("message",l)?r.on(a,i):r.on({scope:"thread",event:o},u=>{u.messageId===s().getState().id&&i(u)})}});return p.jsx(bt,{api:n,children:t})},mh=({index:e,children:t})=>{const r=fe(),n=It({part:gt({source:"message",query:{type:"index",index:e},get:()=>r.message().part({index:e})})});return p.jsx(bt,{api:n,children:t})},gh=({index:e,children:t})=>{const r=fe(),n=It({attachment:gt({source:"message",query:{type:"index",index:e},get:()=>r.message().attachment({index:e})})});return p.jsx(bt,{api:n,children:t})},yh=({index:e,children:t})=>{const r=fe(),n=It({attachment:gt({source:"composer",query:{type:"index",index:e},get:()=>r.composer().attachment({index:e})})});return p.jsx(bt,{api:n,children:t})},bh=ge(({text:e,isRunning:t})=>{const r=oe(()=>({type:"text",text:e,status:t?{type:"running"}:{type:"complete"}}),[e,t]);return nt({getState:()=>r,addToolResult:()=>{throw new Error("Not supported")},resumeToolCall:()=>{throw new Error("Not supported")}})}),wh=({text:e,isRunning:t=!1,children:r})=>{const n=Rn(Qi(bh({text:e,isRunning:t}))),a=It({part:gt({source:"root",query:{},get:()=>n.getState().api}),subscribe:n.subscribe,flushSync:n.flushSync});return p.jsx(bt,{api:a,children:r})},ps=(e,t)=>{var r,n;return t===void 0?((r=e.status)==null?void 0:r.type)==="requires-action"&&e.status.reason==="tool-calls"&&e.content.every(a=>a.type!=="tool-call"||!!a.result):((n=e.status)==null?void 0:n.type)==="requires-action"&&e.status.reason==="tool-calls"&&e.content.every(a=>a.type!=="tool-call"||!!a.result||!t.includes(a.toolName))},Jn=class extends Error{constructor(t,r){super(r);C(this,"name","AbortError");C(this,"detach");this.detach=t}},xh=class extends ud{constructor(t,r){super(t);C(this,"capabilities",{switchToBranch:!0,switchBranchDuringRun:!0,edit:!0,reload:!0,cancel:!0,unstable_copy:!0,speech:!1,attachments:!1,feedback:!1});C(this,"abortController",null);C(this,"isDisabled",!1);C(this,"_isLoading",!1);C(this,"_suggestions",[]);C(this,"_suggestionsController",null);C(this,"_options");C(this,"_lastRunConfig",{});C(this,"_loadPromise");this.__internal_setOptions(r)}get isLoading(){return this._isLoading}get suggestions(){return this._suggestions}get adapters(){return this._options.adapters}get extras(){}__internal_setOptions(t){var s,o,l;if(this._options===t)return;this._options=t;let r=!1;const n=((s=t.adapters)==null?void 0:s.speech)!==void 0;this.capabilities.speech!==n&&(this.capabilities.speech=n,r=!0);const a=((o=t.adapters)==null?void 0:o.attachments)!==void 0;this.capabilities.attachments!==a&&(this.capabilities.attachments=a,r=!0);const i=((l=t.adapters)==null?void 0:l.feedback)!==void 0;this.capabilities.feedback!==i&&(this.capabilities.feedback=i,r=!0),r&&this._notifySubscribers()}__internal_load(){var r,n;if(this._loadPromise)return this._loadPromise;const t=(n=(r=this.adapters.history)==null?void 0:r.load())!=null?n:Promise.resolve(null);return this._isLoading=!0,this._notifySubscribers(),this._loadPromise=t.then(a=>{var s,o;if(!a)return;this.repository.import(a),this._notifySubscribers();const i=(o=(s=this.adapters.history)==null?void 0:s.resume)==null?void 0:o.bind(this.adapters.history);a.unstable_resume&&i&&this.startRun({parentId:this.repository.headId,sourceId:this.repository.headId,runConfig:this._lastRunConfig},i)}).finally(()=>{this._isLoading=!1,this._notifySubscribers()}),this._loadPromise}append(t){return P(this,null,function*(){var a,i,s;this.ensureInitialized();const r=sr(t,_t(),{type:"complete",reason:"unknown"});this.repository.addOrUpdateMessage(t.parentId,r),(a=this._options.adapters.history)==null||a.append(m({parentId:t.parentId,message:r},t.runConfig!==void 0&&{runConfig:t.runConfig})),((i=t.startRun)!=null?i:t.role==="user")?yield this.startRun({parentId:r.id,sourceId:t.sourceId,runConfig:(s=t.runConfig)!=null?s:{}}):(this.repository.resetHead(r.id),this._notifySubscribers())})}resumeRun(n){var a=n,{stream:t}=a,r=V(a,["stream"]);if(!t)throw new Error("You must pass a stream parameter to resume runs.");return this.startRun(r,t)}unstable_loadExternalState(){throw new Error("Runtime does not support importing external states.")}startRun(a,i){return P(this,arguments,function*({parentId:t,runConfig:r},n){var u,d,c;this.ensureInitialized();let o={id:_t(),role:"assistant",status:{type:"running"},content:[],metadata:{unstable_state:this.state,unstable_annotations:[],unstable_data:[],steps:[],custom:{}},createdAt:new Date};this._notifyEventSubscribers("run-start");try{this._suggestions=[],(u=this._suggestionsController)==null||u.abort(),this._suggestionsController=null,this._notifySubscribers();do o=yield this.performRoundtrip(t,o,r,n),n=void 0;while(ps(o,this._options.unstable_humanToolNames))}finally{this._notifyEventSubscribers("run-end")}this._suggestionsController=new AbortController;const l=this._suggestionsController.signal;if(this.adapters.suggestion&&((d=o.status)==null?void 0:d.type)!=="requires-action"){const b=(c=this.adapters.suggestion)==null?void 0:c.generate({messages:this.messages});if(Symbol.asyncIterator in b)try{for(var h=Ft(b),f,g,v;f=!(g=yield h.next()).done;f=!1){const w=g.value;if(l.aborted)break;this._suggestions=w,this._notifySubscribers()}}catch(g){v=[g]}finally{try{f&&(g=h.return)&&(yield g.call(h))}finally{if(v)throw v[0]}}else{const w=yield b;if(l.aborted)return;this._suggestions=w,this._notifySubscribers()}}})}performRoundtrip(t,r,n,a){return P(this,null,function*(){var g,v,b,w,T,_,D,z,I,N;const i=t?this.repository.getMessages(t):[];(g=this.abortController)==null||g.abort(),this.abortController=new AbortController;const s=r.content,o=(v=r.metadata)==null?void 0:v.unstable_annotations,l=(b=r.metadata)==null?void 0:b.unstable_data,u=(w=r.metadata)==null?void 0:w.steps,d=(T=r.metadata)==null?void 0:T.custom,c=M=>{var de,x,se,we,k,xe;const U=(de=M.metadata)==null?void 0:de.steps,R=U?[...u!=null?u:[],...U]:void 0,F=(x=M.metadata)==null?void 0:x.unstable_annotations,Q=(se=M.metadata)==null?void 0:se.unstable_data,ue=F?[...o!=null?o:[],...F]:void 0,pe=Q?[...l!=null?l:[],...Q]:void 0;r=m(E(m(m({},r),M.content?{content:[...s,...(we=M.content)!=null?we:[]]}:void 0),{status:(k=M.status)!=null?k:r.status}),M.metadata?{metadata:m(m(m(m(m(m({},r.metadata),M.metadata.unstable_state?{unstable_state:M.metadata.unstable_state}:void 0),ue?{unstable_annotations:ue}:void 0),pe?{unstable_data:pe}:void 0),R?{steps:R}:void 0),(xe=M.metadata)!=null&&xe.custom?{custom:m(m({},d!=null?d:{}),M.metadata.custom)}:void 0)}:void 0),this.repository.addOrUpdateMessage(t,r),this._notifySubscribers()},h=(_=this._options.maxSteps)!=null?_:2;if(((I=(z=(D=r.metadata)==null?void 0:D.steps)==null?void 0:z.length)!=null?I:0)>=h)return c({status:{type:"incomplete",reason:"tool-calls"}}),r;c({status:{type:"running"}}),this.repository.resetHead(r.id),this._notifySubscribers();try{this._lastRunConfig=n!=null?n:{};const M=this.getModelContext();a=a!=null?a:this.adapters.chatModel.run.bind(this.adapters.chatModel);const U=this.abortController.signal,R=a({messages:i,runConfig:this._lastRunConfig,abortSignal:U,context:M,config:M,unstable_assistantMessageId:r.id,unstable_getMessage(){return r}});if(Symbol.asyncIterator in R)try{for(var B=Ft(R),H,j,S;H=!(j=yield B.next()).done;H=!1){const F=j.value;if(U.aborted){c({status:{type:"incomplete",reason:"cancelled"}});break}c(F)}}catch(j){S=[j]}finally{try{H&&(j=B.return)&&(yield j.call(B))}finally{if(S)throw S[0]}}else c(yield R);r.status.type==="running"&&c({status:{type:"complete",reason:"unknown"}})}catch(M){if(M instanceof Jn)c({status:{type:"incomplete",reason:"cancelled"}});else throw c({status:{type:"incomplete",reason:"error",error:M instanceof Error?M.message:`[${typeof M}] ${new String(M).toString()}`}}),M}finally{this.abortController=null,(r.status.type==="complete"||r.status.type==="incomplete")&&(yield(N=this._options.adapters.history)==null?void 0:N.append({parentId:t,message:r,runConfig:this._lastRunConfig}))}return r})}detach(){var r;const t=new Jn(!0);(r=this.abortController)==null||r.abort(t),this.abortController=null}cancelRun(){var r;const t=new Jn(!1);(r=this.abortController)==null||r.abort(t),this.abortController=null}addToolResult({messageId:t,toolCallId:r,result:n,isError:a,artifact:i}){const s=this.repository.getMessage(t),{parentId:o}=s;let{message:l}=s;if(l.role!=="assistant")throw new Error("Tried to add tool result to non-assistant message");let u=!1,d=!1;const c=l.content.map(h=>h.type!=="tool-call"||h.toolCallId!==r?h:(d=!0,h.result||(u=!0),E(m({},h),{result:n,artifact:i,isError:a})));if(!d)throw new Error("Tried to add tool result to non-existing tool call");l=E(m({},l),{content:c}),this.repository.addOrUpdateMessage(o,l),u&&ps(l,this._options.unstable_humanToolNames)&&this.performRoundtrip(o,l,this._lastRunConfig)}resumeToolCall(t){throw new Error("Local runtime does not support resuming tool calls.")}},ms=Object.freeze([]),Yn="__DEFAULT_ID__",vh=Object.freeze({[Yn]:{id:Yn,remoteId:void 0,externalId:void 0,status:"regular",title:void 0}}),kh=class extends ar{constructor(t){super();C(this,"_mainThread");this._mainThread=t()}get isLoading(){return!1}getMainThreadRuntimeCore(){return this._mainThread}get newThreadId(){throw new Error("Method not implemented.")}get threadIds(){throw ms}get archivedThreadIds(){throw ms}get mainThreadId(){return Yn}get threadData(){return vh}getThreadRuntimeCore(){throw new Error("Method not implemented.")}getLoadThreadsPromise(){throw new Error("Method not implemented.")}getItemById(t){if(t===this.mainThreadId)return{status:"regular",id:this.mainThreadId,remoteId:this.mainThreadId,externalId:void 0,title:void 0,isMain:!0};throw new Error("Method not implemented")}switchToThread(){return P(this,null,function*(){throw new Error("Method not implemented.")})}switchToNewThread(){throw new Error("Method not implemented.")}rename(){throw new Error("Method not implemented.")}archive(){throw new Error("Method not implemented.")}detach(){throw new Error("Method not implemented.")}unarchive(){throw new Error("Method not implemented.")}delete(){throw new Error("Method not implemented.")}initialize(t){return Promise.resolve({remoteId:t,externalId:void 0})}generateTitle(){throw new Error("Method not implemented.")}},Sh=class extends An{constructor(t,r){super();C(this,"threads");C(this,"Provider");C(this,"_options");this._options=t,this.threads=new kh(()=>new xh(this._contextProvider,this._options)),r&&this.threads.getMainThreadRuntimeCore().import(Dn.fromArray(r))}},gs=e=>{try{const r=e.split(".")[1];if(!r)throw new Error("Invalid JWT format");let n=r.replace(/-/g,"+").replace(/_/g,"/");for(;n.length%4!==0;)n+="=";const a=atob(n),s=JSON.parse(a).exp;if(!s||typeof s!="number")throw new Error('JWT does not contain a valid "exp" field');return s*1e3}catch(t){throw new Error(`Unable to determine the token expiry: ${t}`)}},ys=(Tu=class{constructor(e){C(this,"strategy","jwt");C(this,"cachedToken",null);C(this,"tokenExpiry",null);er(this,Ir);tr(this,Ir,e)}getAuthHeaders(){return P(this,null,function*(){const e=Date.now();if(this.cachedToken&&this.tokenExpiry&&this.tokenExpiry-e>30*1e3)return{Authorization:`Bearer ${this.cachedToken}`};const t=yield Ke(this,Ir).call(this);return t?(this.cachedToken=t,this.tokenExpiry=gs(t),{Authorization:`Bearer ${t}`}):!1})}readAuthHeaders(e){const t=e.get("Authorization");if(!t)return;const[r,n]=t.split(" ");if(r!=="Bearer"||!n)throw new Error("Invalid auth header received");this.cachedToken=n,this.tokenExpiry=gs(n)}},Ir=new WeakMap,Tu),_h=(Cu=class{constructor(e,t,r){C(this,"strategy","api-key");er(this,Er);er(this,Ar);er(this,Mr);tr(this,Er,e),tr(this,Ar,t),tr(this,Mr,r)}getAuthHeaders(){return P(this,null,function*(){return{Authorization:`Bearer ${Ke(this,Er)}`,"Aui-User-Id":Ke(this,Ar),"Aui-Workspace-Id":Ke(this,Mr)}})}readAuthHeaders(){}},Er=new WeakMap,Ar=new WeakMap,Mr=new WeakMap,Cu),Kr="aui:refresh_token",Th=class{constructor(e){C(this,"strategy","anon");C(this,"baseUrl");C(this,"jwtStrategy");this.baseUrl=e,this.jwtStrategy=new ys(()=>P(this,null,function*(){const t=Date.now(),r=localStorage.getItem(Kr),n=r?JSON.parse(r):void 0;if(n)if(new Date(n.expires_at).getTime()-t>30*1e3){const u=yield fetch(`${this.baseUrl}/v1/auth/tokens/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:n.token})});if(u.ok){const d=yield u.json(),{access_token:c,refresh_token:h}=d;return h&&localStorage.setItem(Kr,JSON.stringify(h)),c}}else localStorage.removeItem(Kr);const a=yield fetch(`${this.baseUrl}/v1/auth/tokens/anonymous`,{method:"POST"});if(!a.ok)return null;const i=yield a.json(),{access_token:s,refresh_token:o}=i;return!s||!o?null:(localStorage.setItem(Kr,JSON.stringify(o)),s)}))}getAuthHeaders(){return P(this,null,function*(){return this.jwtStrategy.getAuthHeaders()})}readAuthHeaders(e){this.jwtStrategy.readAuthHeaders(e)}},Ch=class extends Error{constructor(e){super(e),this.name="APIError"}},Ih=class{constructor(e){C(this,"_auth");C(this,"_baseUrl");if("authToken"in e)this._baseUrl=e.baseUrl,this._auth=new ys(e.authToken);else if("apiKey"in e)this._baseUrl="https://backend.assistant-api.com",this._auth=new _h(e.apiKey,e.userId,e.workspaceId);else if("anonymous"in e)this._baseUrl=e.baseUrl,this._auth=new Th(e.baseUrl);else throw new Error("Invalid configuration: Must provide authToken, apiKey, or anonymous configuration")}initializeAuth(){return P(this,null,function*(){return!!this._auth.getAuthHeaders()})}makeRawRequest(r){return P(this,arguments,function*(e,t={}){var l;const n=yield this._auth.getAuthHeaders();if(!n)throw new Error("Authorization failed");const a=E(m(m({},n),t.headers),{"Content-Type":"application/json"}),i=new URLSearchParams;if(t.query)for(const[u,d]of Object.entries(t.query))d!==!1&&(d===!0?i.set(u,"true"):i.set(u,d.toString()));const s=new URL(`${this._baseUrl}/v1${e}`);s.search=i.toString();const o=yield fetch(s,{method:(l=t.method)!=null?l:"GET",headers:a,body:t.body?JSON.stringify(t.body):null});if(this._auth.readAuthHeaders(o.headers),!o.ok){const u=yield o.text();try{const d=JSON.parse(u);throw new Ch(d.message)}catch(d){throw new Error(`Request failed with status ${o.status}, ${u}`)}}return o})}makeRequest(r){return P(this,arguments,function*(e,t={}){return(yield this.makeRawRequest(e,t)).json()})}},Eh=class{constructor(e){this.cloud=e}create(){return P(this,null,function*(){return this.cloud.makeRequest("/auth/tokens",{method:"POST"})})}},Ah=class{constructor(e){this.cloud=e}__internal_getAssistantOptions(e){return{api:`${this.cloud._baseUrl}/v1/runs/stream`,headers:()=>P(this,null,function*(){const t=yield this.cloud._auth.getAuthHeaders();if(!t)throw new Error("Authorization failed");return E(m({},t),{Accept:"text/plain"})}),body:{assistant_id:e,response_format:"vercel-ai-data-stream/v1",thread_id:"unstable_todo"}}}stream(e){return P(this,null,function*(){const t=yield this.cloud.makeRawRequest("/runs/stream",{method:"POST",headers:{Accept:"text/plain"},body:e});return Nn.fromResponse(t,new Rc)})}},Mh=class{constructor(e){this.cloud=e}list(e,t){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{query:t})})}create(e,t){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{method:"POST",body:t})})}},Ph=class{constructor(e){C(this,"messages");this.cloud=e,this.messages=new Mh(e)}list(e){return P(this,null,function*(){return this.cloud.makeRequest("/threads",{query:e})})}get(e){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`)})}create(e){return P(this,null,function*(){return this.cloud.makeRequest("/threads",{method:"POST",body:e})})}update(e,t){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:"PUT",body:t})})}delete(e){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:"DELETE"})})}},Nh=class{constructor(e){this.cloud=e}pdfToImages(e){return P(this,null,function*(){return this.cloud.makeRequest("/files/pdf-to-images",{method:"POST",body:e})})}generatePresignedUploadUrl(e){return P(this,null,function*(){return this.cloud.makeRequest("/files/attachments/generate-presigned-upload-url",{method:"POST",body:e})})}},Lh=class{constructor(e){C(this,"threads");C(this,"auth");C(this,"runs");C(this,"files");const t=new Ih(e);this.threads=new Ph(t),this.auth={tokens:new Eh(t)},this.runs=new Ah(t),this.files=new Nh(t)}};function Kn(e,t=0){return t>100?!1:e===null||typeof e=="string"||typeof e=="boolean"?!0:typeof e=="number"?!Number.isNaN(e)&&Number.isFinite(e):Array.isArray(e)?e.every(r=>Kn(r,t+1)):typeof e=="object"?Object.entries(e).every(([r,n])=>typeof r=="string"&&Kn(n,t+1)):!1}var Dh=e=>{var t;return m({role:e.role,content:e.content.map(r=>{const n=r.type;switch(n){case"text":return{type:"text",text:r.text};case"reasoning":return{type:"reasoning",text:r.text};case"source":return m({type:"source",sourceType:r.sourceType,id:r.id,url:r.url},r.title?{title:r.title}:void 0);case"tool-call":return Kn(r.result)||console.warn(`tool-call result is not JSON! ${JSON.stringify(r)}`),m(m(m({type:"tool-call",toolCallId:r.toolCallId,toolName:r.toolName},JSON.stringify(r.args)===r.argsText?{args:r.args}:{argsText:r.argsText}),r.result?{result:r.result}:{}),r.isError?{isError:!0}:{});default:{const a=n;throw new Error(`Message part type not supported by aui/v0: ${a}`)}}}),metadata:e.metadata},e.status?{status:((t=e.status)==null?void 0:t.type)==="running"?{type:"incomplete",reason:"cancelled"}:e.status}:void 0)},Oh=e=>{const t=e.content,r=sr(m({id:e.id,createdAt:e.created_at},t),e.id,{type:"complete",reason:"unknown"});return{parentId:e.parent_id,message:r}},Gn=new WeakMap,Fh=class{constructor(e,t){this.parent=e,this.formatAdapter=t}append(e){return P(this,null,function*(){const t=this.formatAdapter.encode(e),r=this.formatAdapter.getId(e.message);return this.parent._appendWithFormat(e.parentId,r,this.formatAdapter.format,t)})}load(){return P(this,null,function*(){return this.parent._loadWithFormat(this.formatAdapter.format,e=>this.formatAdapter.decode(e))})}},Bh=class{constructor(e,t){this.cloudRef=e,this.store=t}get _getIdForLocalId(){return Gn.has(this.store.threadListItem())||Gn.set(this.store.threadListItem(),{}),Gn.get(this.store.threadListItem())}withFormat(e){return new Fh(this,e)}append(r){return P(this,arguments,function*({parentId:e,message:t}){var i;const{remoteId:n}=yield this.store.threadListItem().initialize(),a=this.cloudRef.current.threads.messages.create(n,{parent_id:e?(i=yield this._getIdForLocalId[e])!=null?i:e:null,format:"aui/v0",content:Dh(t)}).then(({message_id:s})=>(this._getIdForLocalId[t.id]=s,s));return this._getIdForLocalId[t.id]=a,a.then(()=>{})})}load(){return P(this,null,function*(){const e=this.store.threadListItem().getState().remoteId;if(!e)return{messages:[]};const{messages:t}=yield this.cloudRef.current.threads.messages.list(e,{format:"aui/v0"});return{messages:t.filter(n=>n.format==="aui/v0").map(Oh).reverse()}})}_appendWithFormat(e,t,r,n){return P(this,null,function*(){var s;const{remoteId:a}=yield this.store.threadListItem().initialize(),i=this.cloudRef.current.threads.messages.create(a,{parent_id:e?(s=yield this._getIdForLocalId[e])!=null?s:e:null,format:r,content:n}).then(({message_id:o})=>(this._getIdForLocalId[t]=o,o));return this._getIdForLocalId[t]=i,i.then(()=>{})})}_loadWithFormat(e,t){return P(this,null,function*(){const r=this.store.threadListItem().getState().remoteId;if(!r)return{messages:[]};const{messages:n}=yield this.cloudRef.current.threads.messages.list(r,{format:e});return{messages:n.filter(a=>a.format===e).map(a=>t({id:a.id,parent_id:a.parent_id,format:a.format,content:a.content})).reverse()}})}},zh=e=>{const t=fe(),[r]=y.useState(()=>new Bh(e,t));return r},bs=typeof process!="undefined"&&((Iu=process==null?void 0:process.env)==null?void 0:Iu.NEXT_PUBLIC_ASSISTANT_BASE_URL),Xn=bs?new Lh({baseUrl:bs,anonymous:!0}):void 0,Rh=e=>{var a;const t=y.useRef(e);y.useEffect(()=>{t.current=e},[e]);const r=y.useCallback(function({children:s}){var c;const o=zh({get current(){var h;return(h=t.current.cloud)!=null?h:Xn}}),l=(c=t.current.cloud)!=null?c:Xn,u=y.useMemo(()=>new sd(l),[l]),d=y.useMemo(()=>({history:o,attachments:u}),[o,u]);return p.jsx(Bn,{adapters:d,children:s})},[]),n=(a=e.cloud)!=null?a:Xn;return n?{list:()=>P(null,null,function*(){const{threads:i}=yield n.threads.list();return{threads:i.map(s=>{var o;return{status:s.is_archived?"archived":"regular",remoteId:s.id,title:s.title,externalId:(o=s.external_id)!=null?o:void 0}})}}),initialize:()=>P(null,null,function*(){var u,d;const s=yield(d=(u=e.create)==null?void 0:u.call(e))!=null?d:Promise.resolve(),o=s?s.externalId:void 0,{thread_id:l}=yield n.threads.create({last_message_at:new Date,external_id:o});return{externalId:o,remoteId:l}}),rename:(i,s)=>P(null,null,function*(){return n.threads.update(i,{title:s})}),archive:i=>P(null,null,function*(){return n.threads.update(i,{is_archived:!0})}),unarchive:i=>P(null,null,function*(){return n.threads.update(i,{is_archived:!1})}),delete:i=>P(null,null,function*(){var s;return yield(s=e.delete)==null?void 0:s.call(e,i),n.threads.delete(i)}),generateTitle:(i,s)=>P(null,null,function*(){return n.runs.stream({thread_id:i,assistant_id:"system/thread_title",messages:s})}),fetch:i=>P(null,null,function*(){var o;const s=yield n.threads.get(i);return{status:s.is_archived?"archived":"regular",remoteId:s.id,title:s.title,externalId:(o=s.external_id)!=null?o:void 0}}),unstable_Provider:r}:new hd},jh=(e,n)=>{var a=n,{initialMessages:t}=a,r=V(a,["initialMessages"]);var u;const d=(u=od())!=null?u:{},{modelContext:i}=d,s=V(d,["modelContext"]),o=y.useMemo(()=>E(m({},r),{adapters:E(m(m({},s),r.adapters),{chatModel:e})}),[e,r,s]),[l]=y.useState(()=>new Sh(o,t));return y.useEffect(()=>()=>{l.threads.getMainThreadRuntimeCore().detach()},[l]),y.useEffect(()=>{l.threads.getMainThreadRuntimeCore().__internal_setOptions(o),l.threads.getMainThreadRuntimeCore().__internal_load()},[l,o]),y.useEffect(()=>{if(i)return l.registerModelContextProvider(i)},[i,l]),y.useMemo(()=>new Qn(l),[l])},ws=(e,n={})=>{var a=n,{cloud:t}=a,r=V(a,["cloud"]);const i=Rh({cloud:t});return _s({runtimeHook:function(){return jh(e,r)},adapter:i,allowNesting:!0})},Qn=class{constructor(e){C(this,"threads");C(this,"_thread");this._core=e,this.threads=new ad(e.threads),this._thread=this.threads.main,this.__internal_bindMethods()}get threadList(){return this.threads}__internal_bindMethods(){this.switchToNewThread=this.switchToNewThread.bind(this),this.switchToThread=this.switchToThread.bind(this),this.registerModelContextProvider=this.registerModelContextProvider.bind(this),this.registerModelConfigProvider=this.registerModelConfigProvider.bind(this),this.reset=this.reset.bind(this)}get thread(){return this._thread}switchToNewThread(){return this._core.threads.switchToNewThread()}switchToThread(e){return this._core.threads.switchToThread(e)}registerModelContextProvider(e){return this._core.registerModelContextProvider(e)}registerModelConfigProvider(e){return this.registerModelContextProvider(e)}reset({initialMessages:e}={}){return this._core.threads.getMainThreadRuntimeCore().import(Dn.fromArray(e!=null?e:[]))}},$h=e=>{const o=e,{cloud:t,initialMessages:r,maxSteps:n,adapters:a,unstable_humanToolNames:i}=o,s=V(o,["cloud","initialMessages","maxSteps","adapters","unstable_humanToolNames"]);return{localRuntimeOptions:{cloud:t,initialMessages:r,maxSteps:n,adapters:a,unstable_humanToolNames:i},otherOptions:s}};function At(e){const t=K.useRef(e);return K.useEffect(()=>{t.current=e}),K.useMemo(()=>(...r)=>{var n;return(n=t.current)==null?void 0:n.call(t,...r)},[])}var xs=y.createContext(null),Uh=e=>({useSmoothStatus:Ht(()=>e)}),Hh=({children:e})=>{const t=vs({optional:!0}),r=fe(),[n]=y.useState(()=>Uh(r.part().getState().status));return t?e:p.jsx(xs.Provider,{value:n,children:e})},qh=e=>{const t=y.forwardRef((r,n)=>p.jsx(Hh,{children:p.jsx(e,E(m({},r),{ref:n}))}));return t.displayName=e.displayName,t};function vs(e){const t=y.useContext(xs);if(!(e!=null&&e.optional)&&!t)throw new Error("This component must be used within a SmoothContextProvider.");return t}var{useSmoothStatus:Vh,useSmoothStatusStore:Wh}=is(vs,"useSmoothStatus"),Jh=class{constructor(e,t){C(this,"animationFrameId",null);C(this,"lastUpdateTime",Date.now());C(this,"targetText","");C(this,"animate",()=>{const e=Date.now();let r=e-this.lastUpdateTime;const n=this.targetText.length-this.currentText.length,a=Math.min(5,250/n);let i=0;for(;r>=a&&i<n;)i++,r-=a;i!==n?this.animationFrameId=requestAnimationFrame(this.animate):this.animationFrameId=null,i!==0&&(this.currentText=this.targetText.slice(0,this.currentText.length+i),this.lastUpdateTime=e-r,this.setText(this.currentText))});this.currentText=e,this.setText=t}start(){this.animationFrameId===null&&(this.lastUpdateTime=Date.now(),this.animate())}stop(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}},Zn=Object.freeze({type:"running"}),ks=(e,t=!1)=>{const{text:r}=e,n=re(({message:d})=>d.id),a=y.useRef(n),[i,s]=y.useState(r),o=Wh({optional:!0}),l=At(d=>{if(s(d),o){const c=i!==d||e.status.type==="running"?Zn:e.status;hr(o).setState(c,!0)}});y.useEffect(()=>{if(o){const d=t&&(i!==r||e.status.type==="running")?Zn:e.status;hr(o).setState(d,!0)}},[o,t,r,i,e.status]);const[u]=y.useState(new Jh(r,l));return y.useEffect(()=>{if(!t){u.stop();return}if(a.current!==n||!r.startsWith(u.targetText)){a.current=n,l(r),u.currentText=r,u.targetText=r,u.stop();return}u.targetText=r,u.start()},[l,u,n,t,r]),y.useEffect(()=>()=>{u.stop()},[u]),y.useMemo(()=>t?{type:"text",text:i,status:r===i?e.status:Zn}:e,[t,i,e,r])};const Yh=Object.freeze(Object.defineProperty({__proto__:null,AssistantRuntimeImpl:Qn,BaseAssistantRuntimeCore:An,CompositeContextProvider:En,DefaultThreadComposerRuntimeCore:hi,MessageRepository:Ci,ThreadRuntimeImpl:ji,fromThreadMessageLike:sr,generateId:_t,getAutoStatus:pi,splitLocalRuntimeOptions:$h,useSmooth:ks,useSmoothStatus:Vh,useToolInvocations:dd,withSmoothContextProvider:qh},Symbol.toStringTag,{value:"Module"}));var Kh=class extends ar{constructor(t){super();C(this,"useRuntimeHook");C(this,"instances",new Map);C(this,"useAliveThreadsKeysChanged",Ht(()=>({})));C(this,"_InnerActiveThreadProvider",({threadId:t})=>{const{useRuntime:r}=this.useRuntimeHook(),n=r(),a=n.thread.__internal_threadBinding,i=y.useCallback(()=>{const l=this.instances.get(t);if(!l)throw new Error("Thread not found. This is a bug in assistant-ui.");l.runtime=a.getState(),this._notifySubscribers()},[t,a]),s=y.useRef(!1);s.current||i(),y.useEffect(()=>(s.current=!0,i(),a.outerSubscribe(i)),[a,i]);const o=fe();return y.useEffect(()=>n.threads.main.unstable_on("initialize",()=>{if(o.threadListItem().getState().status==="new"){o.threadListItem().initialize();const u=n.thread.unstable_on("run-end",()=>{u(),o.threadListItem().generateTitle()})}}),[n,o]),null});C(this,"_OuterActiveThreadProvider",y.memo(({threadId:t,provider:r})=>p.jsx(fh,{id:t,children:p.jsx(r,{children:p.jsx(this._InnerActiveThreadProvider,{threadId:t})})})));C(this,"__internal_RenderThreadRuntimes",({provider:t})=>(this.useAliveThreadsKeysChanged(),Array.from(this.instances.keys()).map(r=>p.jsx(this._OuterActiveThreadProvider,{threadId:r,provider:t},r))));this.useRuntimeHook=Ht(()=>({useRuntime:t}))}startThreadRuntime(t){return this.instances.has(t)||(this.instances.set(t,{}),this.useAliveThreadsKeysChanged.setState({},!0)),new Promise((r,n)=>{const a=()=>{const s=this.instances.get(t);if(!s)i(),n(new Error("Thread was deleted before runtime was started"));else if(s.runtime)i(),r(s.runtime);else return},i=this.subscribe(a);a()})}getThreadRuntimeCore(t){const r=this.instances.get(t);if(r)return r.runtime}stopThreadRuntime(t){this.instances.delete(t),this.useAliveThreadsKeysChanged.setState({},!0)}setRuntimeHook(t){this.useRuntimeHook.getState().useRuntime!==t&&this.useRuntimeHook.setState({useRuntime:t},!0)}},Se=new Error("This is the empty thread, a placeholder for the main thread. You cannot perform any actions on this thread instance. This error is probably because you tried to call a thread method in your render function. Call the method inside a `useEffect` hook instead."),Gh={getMessageById(){},getBranches(){return[]},switchToBranch(){throw Se},append(){throw Se},startRun(){throw Se},resumeRun(){throw Se},cancelRun(){throw Se},addToolResult(){throw Se},resumeToolCall(){throw Se},speak(){throw Se},stopSpeaking(){throw Se},submitFeedback(){throw Se},getModelContext(){return{}},unstable_loadExternalState(){throw Se},composer:{attachments:[],attachmentAccept:"*",addAttachment(){return P(this,null,function*(){throw Se})},removeAttachment(){return P(this,null,function*(){throw Se})},isEditing:!0,canCancel:!1,isEmpty:!0,text:"",setText(){throw Se},role:"user",setRole(){throw Se},runConfig:{},setRunConfig(){throw Se},reset(){return P(this,null,function*(){})},clearAttachments(){return P(this,null,function*(){})},send(){throw Se},cancel(){},subscribe(){return()=>{}},unstable_on(){return()=>{}}},getEditComposer(){},beginEdit(){throw Se},speech:void 0,capabilities:{switchToBranch:!1,switchBranchDuringRun:!1,edit:!1,reload:!1,cancel:!1,unstable_copy:!1,speech:!1,attachments:!1,feedback:!1},isDisabled:!1,isLoading:!1,messages:[],state:null,suggestions:[],extras:void 0,subscribe(){return()=>{}},import(){throw Se},export(){return{messages:[]}},reset(){throw Se},unstable_on(){return()=>{}}},Ss=(e,t,r)=>r.reduce((n,a)=>{var i;return(i=a==null?void 0:a(n,t))!=null?i:n},e),Xh=class extends ar{constructor(t){super();C(this,"_pendingTransforms",[]);C(this,"_baseValue");C(this,"_cachedValue");this._baseValue=t,this._cachedValue=t}_updateState(){this._cachedValue=this._pendingTransforms.reduce((t,r)=>Ss(t,r.task,[r.loading,r.optimistic]),this._baseValue),this._notifySubscribers()}get baseValue(){return this._baseValue}get value(){return this._cachedValue}update(t){this._baseValue=t,this._updateState()}optimisticUpdate(t){return P(this,null,function*(){const r=t.execute(),n=E(m({},t),{task:r});try{this._pendingTransforms.push(n),this._updateState();const a=yield r;return this._baseValue=Ss(this._baseValue,a,[t.optimistic,t.then]),a}finally{const a=this._pendingTransforms.indexOf(n);a>-1&&this._pendingTransforms.splice(a,1),this._updateState()}})}};function Rv(e){return e}var Gr=(e,t)=>{const r=e.threadIdMap[t];if(r!==void 0)return e.threadData[r]},Xr=(e,t,r)=>{const n=Gr(e,t);if(!n)return e;const{id:a,remoteId:i,status:s}=n;if(s===r)return e;const o=m({},e);switch(s){case"new":o.newThreadId=void 0;break;case"regular":o.threadIds=o.threadIds.filter(l=>l!==a);break;case"archived":o.archivedThreadIds=o.archivedThreadIds.filter(l=>l!==a);break;default:{const l=s;throw new Error(`Unsupported state: ${l}`)}}switch(r){case"regular":o.threadIds=[a,...o.threadIds];break;case"archived":o.archivedThreadIds=[a,...o.archivedThreadIds];break;case"deleted":o.threadData=Object.fromEntries(Object.entries(o.threadData).filter(([l])=>l!==a)),o.threadIdMap=Object.fromEntries(Object.entries(o.threadIdMap).filter(([l])=>l!==a&&l!==i));break;default:{const l=r;throw new Error(`Unsupported state: ${l}`)}}return r!=="deleted"&&(o.threadData=E(m({},o.threadData),{[a]:E(m({},n),{status:r})})),o},Qh=class extends ar{constructor(t,r){super();C(this,"_options");C(this,"_hookManager");C(this,"_loadThreadsPromise");C(this,"_mainThreadId");C(this,"_state",new Xh({isLoading:!1,newThreadId:void 0,threadIds:[],archivedThreadIds:[],threadIdMap:{},threadData:{}}));C(this,"useProvider");C(this,"initialize",t=>P(this,null,function*(){if(this._state.value.newThreadId!==t){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status==="new")throw new Error("Unexpected new state");return r.initializeTask}return this._state.optimisticUpdate({execute:()=>this._options.adapter.initialize(t),optimistic:r=>Xr(r,t,"regular"),loading:(r,n)=>{const a=t;return E(m({},r),{threadData:E(m({},r.threadData),{[a]:E(m({},r.threadData[a]),{initializeTask:n})})})},then:(r,{remoteId:n,externalId:a})=>{const i=Gr(r,t);if(!i)return r;const s=t;return E(m({},r),{threadIdMap:E(m({},r.threadIdMap),{[n]:s}),threadData:E(m({},r.threadData),{[s]:E(m({},i),{initializeTask:Promise.resolve({remoteId:n,externalId:a}),remoteId:n,externalId:a})})})}})}));C(this,"generateTitle",t=>P(this,null,function*(){var l;const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status==="new")throw new Error("Thread is not yet initialized");const{remoteId:n}=yield r.initializeTask,a=this._hookManager.getThreadRuntimeCore(r.id);if(!a)return;const i=a.messages,s=yield this._options.adapter.generateTitle(n,i),o=jc.fromAssistantStream(s);try{for(var u=Ft(o),d,c,h;d=!(c=yield u.next()).done;d=!1){const f=c.value;const g=(l=f.parts.filter(b=>b.type==="text")[0])==null?void 0:l.text,v=this._state.baseValue;this._state.update(E(m({},v),{threadData:E(m({},v.threadData),{[r.id]:E(m({},r),{title:g})})}))}}catch(c){h=[c]}finally{try{d&&(c=u.return)&&(yield c.call(u))}finally{if(h)throw h[0]}}}));C(this,"useBoundIds",Ht(()=>[]));C(this,"__internal_RenderComponent",()=>{const t=y.useId();y.useEffect(()=>(this.useBoundIds.setState(i=>[...i,t],!0),()=>{this.useBoundIds.setState(i=>i.filter(s=>s!==t),!0)}),[t]);const r=this.useBoundIds(),{Provider:n}=this.useProvider(),a={modelContext:this.contextProvider};return(r.length===0||r[0]===t)&&p.jsx(Bn,{adapters:a,children:p.jsx(this._hookManager.__internal_RenderThreadRuntimes,{provider:n})})});this.contextProvider=r,this._state.subscribe(()=>this._notifySubscribers()),this._hookManager=new Kh(t.runtimeHook),this.useProvider=Ht(()=>{var n;return{Provider:(n=t.adapter.unstable_Provider)!=null?n:y.Fragment}}),this.__internal_setOptions(t),this.switchToNewThread()}get threadData(){return this._state.value.threadData}getLoadThreadsPromise(){return this._loadThreadsPromise||(this._loadThreadsPromise=this._state.optimisticUpdate({execute:()=>this._options.adapter.list(),loading:t=>E(m({},t),{isLoading:!0}),then:(t,r)=>{const n=[],a=[],i={},s={};for(const o of r.threads){switch(o.status){case"regular":n.push(o.remoteId);break;case"archived":a.push(o.remoteId);break;default:{const u=o.status;throw new Error(`Unsupported state: ${u}`)}}const l=o.remoteId;i[o.remoteId]=l,s[l]={id:o.remoteId,remoteId:o.remoteId,externalId:o.externalId,status:o.status,title:o.title,initializeTask:Promise.resolve({remoteId:o.remoteId,externalId:o.externalId})}}return E(m({},t),{threadIds:n,archivedThreadIds:a,threadIdMap:m(m({},t.threadIdMap),i),threadData:m(m({},t.threadData),s)})}}).then(()=>{})),this._loadThreadsPromise}__internal_setOptions(t){var n;if(this._options===t)return;this._options=t;const r=(n=t.adapter.unstable_Provider)!=null?n:y.Fragment;r!==this.useProvider.getState().Provider&&this.useProvider.setState({Provider:r},!0),this._hookManager.setRuntimeHook(t.runtimeHook)}__internal_load(){this.getLoadThreadsPromise()}get isLoading(){return this._state.value.isLoading}get threadIds(){return this._state.value.threadIds}get archivedThreadIds(){return this._state.value.archivedThreadIds}get newThreadId(){return this._state.value.newThreadId}get mainThreadId(){return this._mainThreadId}getMainThreadRuntimeCore(){const t=this._hookManager.getThreadRuntimeCore(this._mainThreadId);return t||Gh}getThreadRuntimeCore(t){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");const n=this._hookManager.getThreadRuntimeCore(r.id);if(!n)throw new Error("Thread not found");return n}getItemById(t){return Gr(this._state.value,t)}switchToThread(t){return P(this,null,function*(){let r=this.getItemById(t);if(!r){const a=yield this._options.adapter.fetch(t),i=this._state.value,s=a.remoteId,o=E(m({},i.threadData),{[s]:{id:s,initializeTask:Promise.resolve({remoteId:a.remoteId,externalId:a.externalId}),remoteId:a.remoteId,externalId:a.externalId,status:a.status,title:a.title}}),l=E(m({},i.threadIdMap),{[a.remoteId]:s}),u=a.status==="regular"?[...i.threadIds,a.remoteId]:i.threadIds,d=a.status==="archived"?[...i.archivedThreadIds,a.remoteId]:i.archivedThreadIds;this._state.update(E(m({},i),{threadIds:u,archivedThreadIds:d,threadIdMap:l,threadData:o})),r=this.getItemById(t)}if(!r)throw new Error("Thread not found");if(this._mainThreadId===r.id)return;const n=this._hookManager.startThreadRuntime(r.id);this.mainThreadId!==void 0?yield n:n.then(()=>this._notifySubscribers()),r.status==="archived"&&(yield this.unarchive(r.id)),this._mainThreadId=r.id,this._notifySubscribers()})}switchToNewThread(){return P(this,null,function*(){for(;this._state.baseValue.newThreadId!==void 0&&this._state.value.newThreadId===void 0;)yield this._state.waitForUpdate();const t=this._state.value;let r=this._state.value.newThreadId;if(r===void 0){do r=`__LOCALID_${_t()}`;while(t.threadIdMap[r]);const n=r;this._state.update(E(m({},t),{newThreadId:r,threadIdMap:E(m({},t.threadIdMap),{[r]:n}),threadData:E(m({},t.threadData),{[n]:{status:"new",id:r,remoteId:void 0,externalId:void 0,title:void 0}})}))}return this.switchToThread(r)})}rename(t,r){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status==="new")throw new Error("Thread is not yet initialized");return this._state.optimisticUpdate({execute:()=>P(this,null,function*(){const{remoteId:a}=yield n.initializeTask;return this._options.adapter.rename(a,r)}),optimistic:a=>{const i=Gr(a,t);return i?E(m({},a),{threadData:E(m({},a.threadData),{[i.id]:E(m({},i),{title:r})})}):a}})}_ensureThreadIsNotMain(t){return P(this,null,function*(){if(t===this.newThreadId)throw new Error("Cannot ensure new thread is not main");t===this._mainThreadId&&(yield this.switchToNewThread())})}archive(t){return P(this,null,function*(){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status!=="regular")throw new Error("Thread is not yet initialized or already archived");return this._state.optimisticUpdate({execute:()=>P(this,null,function*(){yield this._ensureThreadIsNotMain(r.id);const{remoteId:n}=yield r.initializeTask;return this._options.adapter.archive(n)}),optimistic:n=>Xr(n,r.id,"archived")})})}unarchive(t){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status!=="archived")throw new Error("Thread is not archived");return this._state.optimisticUpdate({execute:()=>P(this,null,function*(){try{const{remoteId:n}=yield r.initializeTask;return yield this._options.adapter.unarchive(n)}catch(n){throw yield this._ensureThreadIsNotMain(r.id),n}}),optimistic:n=>Xr(n,r.id,"regular")})}delete(t){return P(this,null,function*(){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status!=="regular"&&r.status!=="archived")throw new Error("Thread is not yet initialized");return this._state.optimisticUpdate({execute:()=>P(this,null,function*(){yield this._ensureThreadIsNotMain(r.id);const{remoteId:n}=yield r.initializeTask;return yield this._options.adapter.delete(n)}),optimistic:n=>Xr(n,r.id,"deleted")})})}detach(t){return P(this,null,function*(){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status!=="regular"&&r.status!=="archived")throw new Error("Thread is not yet initialized");yield this._ensureThreadIsNotMain(r.id),this._hookManager.stopThreadRuntime(r.id)})}},Zh=class extends An{constructor(t){super();C(this,"threads");this.threads=new Qh(t,this._contextProvider)}get RenderComponent(){return this.threads.__internal_RenderComponent}},ef=e=>{const[t]=y.useState(()=>new Zh(e));return y.useEffect(()=>{t.threads.__internal_setOptions(e),t.threads.__internal_load()},[t,e]),y.useMemo(()=>new Qn(t),[t])},_s=e=>{if(Jr().threadListItem.source!==null){if(!e.allowNesting)throw new Error("useRemoteThreadListRuntime cannot be nested inside another RemoteThreadListRuntime. Set allowNesting: true to allow nesting (the inner runtime will become a no-op).");return e.runtimeHook()}return ef(e)},tf=Symbol.for("react.lazy"),Qr=K[" use ".trim().toString()];function rf(e){return typeof e=="object"&&e!==null&&"then"in e}function Ts(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===tf&&"_payload"in e&&rf(e._payload)}function Cs(e){const t=nf(e),r=K.forwardRef((n,a)=>{let u=n,{children:i}=u,s=V(u,["children"]);Ts(i)&&typeof Qr=="function"&&(i=Qr(i._payload));const o=K.Children.toArray(i),l=o.find(sf);if(l){const d=l.props.children,c=o.map(h=>h===l?K.Children.count(d)>1?K.Children.only(null):K.isValidElement(d)?d.props.children:null:h);return p.jsx(t,E(m({},s),{ref:a,children:K.isValidElement(d)?K.cloneElement(d,void 0,c):null}))}return p.jsx(t,E(m({},s),{ref:a,children:i}))});return r.displayName=`${e}.Slot`,r}var Is=Cs("Slot");function nf(e){const t=K.forwardRef((r,n)=>{let s=r,{children:a}=s,i=V(s,["children"]);if(Ts(a)&&typeof Qr=="function"&&(a=Qr(a._payload)),K.isValidElement(a)){const o=lf(a),l=of(i,a.props);return a.type!==K.Fragment&&(l.ref=n?Xi(n,o):o),K.cloneElement(a,l)}return K.Children.count(a)>1?K.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var af=Symbol("radix.slottable");function sf(e){return K.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===af}function of(e,t){const r=m({},t);for(const n in t){const a=e[n],i=t[n];/^on[A-Z]/.test(n)?a&&i?r[n]=(...o)=>{const l=i(...o);return a(...o),l}:a&&(r[n]=a):n==="style"?r[n]=m(m({},a),i):n==="className"&&(r[n]=[a,i].filter(Boolean).join(" "))}return m(m({},e),r)}function lf(e){var n,a;let t=(n=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:n.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=(a=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:a.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}var uf=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ht=uf.reduce((e,t)=>{const r=Cs(`Primitive.${t}`),n=K.forwardRef((a,i)=>{const u=a,{asChild:s}=u,o=V(u,["asChild"]),l=s?r:t;return typeof window!="undefined"&&(window[Symbol.for("radix-ui")]=!0),p.jsx(l,E(m({},o),{ref:i}))});return n.displayName=`Primitive.${t}`,E(m({},e),{[t]:n})},{});function qt(e,t,{checkForDefaultPrevented:r=!0}={}){return function(a){if(e==null||e(a),r===!1||!a.defaultPrevented)return t==null?void 0:t(a)}}var fr=(e,t,r=[])=>{const n=y.forwardRef((a,i)=>{var u;const s={},o={};Object.keys(a).forEach(d=>{r.includes(d)?s[d]=a[d]:o[d]=a[d]});const l=(u=t(s))!=null?u:void 0;return p.jsx(ht.button,E(m({type:"button"},o),{ref:i,disabled:o.disabled||!l,onClick:qt(o.onClick,l)}))});return n.displayName=e,n};function cf(e,t=globalThis==null?void 0:globalThis.document){const r=At(e);K.useEffect(()=>{const n=a=>{a.key==="Escape"&&r(a)};return t.addEventListener("keydown",n,{capture:!0}),()=>t.removeEventListener("keydown",n,{capture:!0})},[r,t])}var df=()=>{const e=fe();return y.useCallback(()=>{e.attachment().remove()},[e])},hf=fr("AttachmentPrimitive.Remove",df),pr=e=>{const t=y.useRef(void 0);return y.useCallback(n=>{t.current&&t.current(),n&&(t.current=e(n))},[e])},Es=(e,t)=>{const r=y.useCallback(n=>{if(!e)return;const a=e(),i=()=>{const o=t?t(n):n.offsetHeight;a.setHeight(o)},s=new ResizeObserver(i);return s.observe(n),i(),()=>{s.disconnect(),a.unregister()}},[e,t]);return pr(r)},As=y.createContext(!1),Ms=(e,t)=>{const r=e.match(/^([\d.]+)(em|px|rem)$/);if(!r)return 0;const n=parseFloat(r[1]),a=r[2];if(a==="px")return n;if(a==="em"){const i=parseFloat(getComputedStyle(t).fontSize)||16;return n*i}if(a==="rem"){const i=parseFloat(getComputedStyle(document.documentElement).fontSize)||16;return n*i}return 0},Ps=({children:e,fillClampThreshold:t="10em",fillClampOffset:r="6em"})=>{const n=re(({message:l})=>l.isLast&&l.index>=2),a=Vn({optional:!0}),i=y.useContext(As),s=y.useCallback(l=>{if(!a||i)return;const u=()=>{const d=a.getState();if(d.turnAnchor==="top"&&n){const{viewport:c,inset:h,userMessage:f}=d.height,g=Ms(t,l),v=Ms(r,l),b=f<=g?f:v,w=Math.max(0,c-h-b);l.style.minHeight=`${w}px`,l.style.flexShrink="0",l.style.transition="min-height 0s"}else l.style.minHeight="",l.style.flexShrink="",l.style.transition=""};return u(),a.subscribe(u)},[a,n,i,t,r]),o=pr(s);return p.jsx(As.Provider,{value:!0,children:p.jsx(Is,{ref:o,children:e})})};Ps.displayName="ThreadPrimitive.ViewportSlack";var ff=()=>{const e=fe(),t=re(()=>e.message()),r=y.useCallback(n=>{const a=()=>{t.setIsHovering(!0)},i=()=>{t.setIsHovering(!1)};return n.addEventListener("mouseenter",a),n.addEventListener("mouseleave",i),n.matches(":hover")&&t.setIsHovering(!0),()=>{n.removeEventListener("mouseenter",a),n.removeEventListener("mouseleave",i),t.setIsHovering(!1)}},[t]);return pr(r)},pf=()=>{const e=Yr(a=>a.turnAnchor),t=Yr(a=>a.registerUserMessageHeight),r=re(({thread:a,message:i})=>{var s;return e==="top"&&i.role==="user"&&i.index===a.messages.length-2&&((s=a.messages.at(-1))==null?void 0:s.role)==="assistant"}),n=y.useCallback(a=>a.offsetHeight,[]);return Es(r?t:null,n)},ea=y.forwardRef((e,t)=>{const r=ff(),n=pf(),a=Wr(t,r,n);return p.jsx(Ps,{children:p.jsx(ht.div,E(m({},e),{ref:a}))})});ea.displayName="MessagePrimitive.Root";var Ns=()=>re(({part:t})=>{if(t.type!=="text"&&t.type!=="reasoning")throw new Error("MessagePartText can only be used inside text or reasoning message parts.");return t}),Ls=y.forwardRef((a,n)=>{var i=a,{smooth:e=!0,component:t="span"}=i,r=V(i,["smooth","component"]);const{text:s,status:o}=ks(Ns(),e);return p.jsx(t,E(m({"data-status":o.type},r),{ref:n,children:s}))});Ls.displayName="MessagePartPrimitive.Text";var mf=()=>re(({part:t})=>{if(t.type!=="image")throw new Error("MessagePartImage can only be used inside image message parts.");return t}),Ds=y.forwardRef((e,t)=>{const{image:r}=mf();return p.jsx(ht.img,E(m({src:r},e),{ref:t}))});Ds.displayName="MessagePartPrimitive.Image";var Os=({children:e})=>re(({part:r})=>r.status.type==="running")?e:null;Os.displayName="MessagePartPrimitive.InProgress";const Fs=e=>Symbol.iterator in e,Bs=e=>"entries"in e,zs=(e,t)=>{const r=e instanceof Map?e:new Map(e.entries()),n=t instanceof Map?t:new Map(t.entries());if(r.size!==n.size)return!1;for(const[a,i]of r)if(!n.has(a)||!Object.is(i,n.get(a)))return!1;return!0},gf=(e,t)=>{const r=e[Symbol.iterator](),n=t[Symbol.iterator]();let a=r.next(),i=n.next();for(;!a.done&&!i.done;){if(!Object.is(a.value,i.value))return!1;a=r.next(),i=n.next()}return!!a.done&&!!i.done};function yf(e,t){return Object.is(e,t)?!0:typeof e!="object"||e===null||typeof t!="object"||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:Fs(e)&&Fs(t)?Bs(e)&&Bs(t)?zs(e,t):gf(e,t):zs({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function bf(e){const t=y.useRef(void 0);return r=>{const n=e(r);return yf(t.current,n)?t.current:t.current=n}}var Rs=e=>{let t=-1;return{startGroup:r=>{t===-1&&(t=r)},endGroup:(r,n)=>{t!==-1&&(n.push({type:e,startIndex:t,endIndex:r}),t=-1)},finalize:(r,n)=>{t!==-1&&n.push({type:e,startIndex:t,endIndex:r})}}},wf=e=>{const t=[],r=Rs("toolGroup"),n=Rs("reasoningGroup");for(let a=0;a<e.length;a++){const i=e[a];i==="tool-call"?(n.endGroup(a-1,t),r.startGroup(a)):i==="reasoning"?(r.endGroup(a-1,t),n.startGroup(a)):(r.endGroup(a-1,t),n.endGroup(a-1,t),t.push({type:"single",index:a}))}return r.finalize(e.length-1,t),n.finalize(e.length-1,t),t},xf=()=>{const e=re(bf(t=>t.message.parts.map(r=>r.type)));return y.useMemo(()=>e.length===0?[]:wf(e),[e])},vf=r=>{var n=r,{Fallback:e}=n,t=V(n,["Fallback"]);const a=re(({tools:i})=>{var o,l;const s=(o=i.tools[t.toolName])!=null?o:e;return Array.isArray(s)?(l=s[0])!=null?l:e:s});return a?p.jsx(a,m({},t)):null},ft={Text:()=>p.jsxs("p",{style:{whiteSpace:"pre-line"},children:[p.jsx(Ls,{}),p.jsx(Os,{children:p.jsx("span",{style:{fontFamily:"revert"},children:" ●"})})]}),Reasoning:()=>null,Source:()=>null,Image:()=>p.jsx(Ds,{}),File:()=>null,Unstable_Audio:()=>null,ToolGroup:({children:e})=>e,ReasoningGroup:({children:e})=>e},kf=({components:{Text:e=ft.Text,Reasoning:t=ft.Reasoning,Image:r=ft.Image,Source:n=ft.Source,File:a=ft.File,Unstable_Audio:i=ft.Unstable_Audio,tools:s={}}={}})=>{var d,c,h;const o=fe(),l=re(({part:f})=>f),u=l.type;if(u==="tool-call"){const f=o.part().addToolResult,g=o.part().resumeToolCall;if("Override"in s)return p.jsx(s.Override,E(m({},l),{addResult:f,resume:g}));const v=(c=(d=s.by_name)==null?void 0:d[l.toolName])!=null?c:s.Fallback;return p.jsx(vf,E(m({},l),{Fallback:v,addResult:f,resume:g}))}if(((h=l.status)==null?void 0:h.type)==="requires-action")throw new Error("Encountered unexpected requires-action status");switch(u){case"text":return p.jsx(e,m({},l));case"reasoning":return p.jsx(t,m({},l));case"source":return p.jsx(n,m({},l));case"image":return p.jsx(r,m({},l));case"file":return p.jsx(a,m({},l));case"audio":return p.jsx(i,m({},l));case"data":return null;default:const f=u;throw new Error(`Unknown message part type: ${f}`)}},Zr=y.memo(({index:e,components:t})=>p.jsx(mh,{index:e,children:p.jsx(kf,{components:t})}),(e,t)=>{var r,n,a,i,s,o,l,u,d,c,h,f,g,v,b,w,T,_;return e.index===t.index&&((r=e.components)==null?void 0:r.Text)===((n=t.components)==null?void 0:n.Text)&&((a=e.components)==null?void 0:a.Reasoning)===((i=t.components)==null?void 0:i.Reasoning)&&((s=e.components)==null?void 0:s.Source)===((o=t.components)==null?void 0:o.Source)&&((l=e.components)==null?void 0:l.Image)===((u=t.components)==null?void 0:u.Image)&&((d=e.components)==null?void 0:d.File)===((c=t.components)==null?void 0:c.File)&&((h=e.components)==null?void 0:h.Unstable_Audio)===((f=t.components)==null?void 0:f.Unstable_Audio)&&((g=e.components)==null?void 0:g.tools)===((v=t.components)==null?void 0:v.tools)&&((b=e.components)==null?void 0:b.ToolGroup)===((w=t.components)==null?void 0:w.ToolGroup)&&((T=e.components)==null?void 0:T.ReasoningGroup)===((_=t.components)==null?void 0:_.ReasoningGroup)});Zr.displayName="MessagePrimitive.PartByIndex";var Sf=({status:e,component:t})=>p.jsx(wh,{text:"",isRunning:e.type==="running",children:p.jsx(t,{type:"text",text:"",status:e})}),_f=Object.freeze({type:"complete"}),Tf=({components:e})=>{var r;const t=re(n=>{var a;return(a=n.message.status)!=null?a:_f});return e!=null&&e.Empty?p.jsx(e.Empty,{status:t}):p.jsx(Sf,{status:t,component:(r=e==null?void 0:e.Text)!=null?r:ft.Text})},Cf=y.memo(Tf,(e,t)=>{var r,n,a,i;return((r=e.components)==null?void 0:r.Empty)===((n=t.components)==null?void 0:n.Empty)&&((a=e.components)==null?void 0:a.Text)===((i=t.components)==null?void 0:i.Text)}),ta=({components:e})=>{const t=re(({message:a})=>a.parts.length),r=xf(),n=y.useMemo(()=>t===0?p.jsx(Cf,{components:e}):r.map(a=>{var i,s;if(a.type==="single")return p.jsx(Zr,{index:a.index,components:e},a.index);if(a.type==="toolGroup"){const o=(i=e==null?void 0:e.ToolGroup)!=null?i:ft.ToolGroup;return p.jsx(o,{startIndex:a.startIndex,endIndex:a.endIndex,children:Array.from({length:a.endIndex-a.startIndex+1},(l,u)=>p.jsx(Zr,{index:a.startIndex+u,components:e},u))},`tool-${a.startIndex}`)}else{const o=(s=e==null?void 0:e.ReasoningGroup)!=null?s:ft.ReasoningGroup;return p.jsx(o,{startIndex:a.startIndex,endIndex:a.endIndex,children:Array.from({length:a.endIndex-a.startIndex+1},(l,u)=>p.jsx(Zr,{index:a.startIndex+u,components:e},u))},`reasoning-${a.startIndex}`)}}),[r,e,t]);return p.jsx(p.Fragment,{children:n})};ta.displayName="MessagePrimitive.Parts";var If=(e,t)=>{var n,a,i;const r=t.type;switch(r){case"image":return(n=e==null?void 0:e.Image)!=null?n:e==null?void 0:e.Attachment;case"document":return(a=e==null?void 0:e.Document)!=null?a:e==null?void 0:e.Attachment;case"file":return(i=e==null?void 0:e.File)!=null?i:e==null?void 0:e.Attachment;default:const s=r;throw new Error(`Unknown attachment type: ${s}`)}},Ef=({components:e})=>{const t=re(({attachment:n})=>n);if(!t)return null;const r=If(e,t);return r?p.jsx(r,{}):null},js=y.memo(({index:e,components:t})=>p.jsx(gh,{index:e,children:p.jsx(Ef,{components:t})}),(e,t)=>{var r,n,a,i,s,o,l,u;return e.index===t.index&&((r=e.components)==null?void 0:r.Image)===((n=t.components)==null?void 0:n.Image)&&((a=e.components)==null?void 0:a.Document)===((i=t.components)==null?void 0:i.Document)&&((s=e.components)==null?void 0:s.File)===((o=t.components)==null?void 0:o.File)&&((l=e.components)==null?void 0:l.Attachment)===((u=t.components)==null?void 0:u.Attachment)});js.displayName="MessagePrimitive.AttachmentByIndex";var $s=({components:e})=>{const t=re(({message:n})=>n.role!=="user"?0:n.attachments.length);return y.useMemo(()=>Array.from({length:t},(n,a)=>p.jsx(js,{index:a,components:e},a)),[t,e])};$s.displayName="MessagePrimitive.Attachments";var Us=()=>{const e=fe(),t=re(n=>n.thread.isRunning||!n.composer.isEditing||n.composer.isEmpty),r=y.useCallback(()=>{e.composer().send()},[e]);return t?null:r},Af=fr("ComposerPrimitive.Send",Us),Hs=y.forwardRef((n,r)=>{var a=n,{onSubmit:e}=a,t=V(a,["onSubmit"]);const i=Us(),s=o=>{o.preventDefault(),i&&i()};return p.jsx(ht.form,E(m({},t),{ref:r,onSubmit:qt(e,s)}))});Hs.displayName="ComposerPrimitive.Root";function ra(){return ra=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},ra.apply(null,arguments)}function Mf(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)!==-1)continue;r[n]=e[n]}return r}var Pf=y.useLayoutEffect,Nf=function(t){var r=y.useRef(t);return Pf(function(){r.current=t}),r},qs=function(t,r){if(typeof t=="function"){t(r);return}t.current=r},Lf=function(t,r){var n=y.useRef();return y.useCallback(function(a){t.current=a,n.current&&qs(n.current,null),n.current=r,r&&qs(r,a)},[r])},Vs={"min-height":"0","max-height":"none",height:"0",visibility:"hidden",overflow:"hidden",position:"absolute","z-index":"-1000",top:"0",right:"0",display:"block"},Df=function(t){Object.keys(Vs).forEach(function(r){t.style.setProperty(r,Vs[r],"important")})},Ws=Df,Fe=null,Js=function(t,r){var n=t.scrollHeight;return r.sizingStyle.boxSizing==="border-box"?n+r.borderSize:n-r.paddingSize};function Of(e,t,r,n){r===void 0&&(r=1),n===void 0&&(n=1/0),Fe||(Fe=document.createElement("textarea"),Fe.setAttribute("tabindex","-1"),Fe.setAttribute("aria-hidden","true"),Ws(Fe)),Fe.parentNode===null&&document.body.appendChild(Fe);var a=e.paddingSize,i=e.borderSize,s=e.sizingStyle,o=s.boxSizing;Object.keys(s).forEach(function(h){var f=h;Fe.style[f]=s[f]}),Ws(Fe),Fe.value=t;var l=Js(Fe,e);Fe.value=t,l=Js(Fe,e),Fe.value="x";var u=Fe.scrollHeight-a,d=u*r;o==="border-box"&&(d=d+a+i),l=Math.max(d,l);var c=u*n;return o==="border-box"&&(c=c+a+i),l=Math.min(c,l),[l,u]}var Ys=function(){},Ff=function(t,r){return t.reduce(function(n,a){return n[a]=r[a],n},{})},Bf=["borderBottomWidth","borderLeftWidth","borderRightWidth","borderTopWidth","boxSizing","fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","lineHeight","paddingBottom","paddingLeft","paddingRight","paddingTop","tabSize","textIndent","textRendering","textTransform","width","wordBreak","wordSpacing","scrollbarGutter"],zf=!!document.documentElement.currentStyle,Rf=function(t){var r=window.getComputedStyle(t);if(r===null)return null;var n=Ff(Bf,r),a=n.boxSizing;if(a==="")return null;zf&&a==="border-box"&&(n.width=parseFloat(n.width)+parseFloat(n.borderRightWidth)+parseFloat(n.borderLeftWidth)+parseFloat(n.paddingRight)+parseFloat(n.paddingLeft)+"px");var i=parseFloat(n.paddingBottom)+parseFloat(n.paddingTop),s=parseFloat(n.borderBottomWidth)+parseFloat(n.borderTopWidth);return{sizingStyle:n,paddingSize:i,borderSize:s}},jf=Rf;function na(e,t,r){var n=Nf(r);K.useLayoutEffect(function(){var a=function(s){return n.current(s)};if(e)return e.addEventListener(t,a),function(){return e.removeEventListener(t,a)}},[])}var $f=function(t,r){na(document.body,"reset",function(n){t.current.form===n.target&&r(n)})},Uf=function(t){na(window,"resize",t)},Hf=function(t){na(document.fonts,"loadingdone",t)},qf=["cacheMeasurements","maxRows","minRows","onChange","onHeightChange"],Vf=function(t,r){var n=t.cacheMeasurements,a=t.maxRows,i=t.minRows,s=t.onChange,o=s===void 0?Ys:s,l=t.onHeightChange,u=l===void 0?Ys:l,d=Mf(t,qf),c=d.value!==void 0,h=K.useRef(null),f=Lf(h,r),g=K.useRef(0),v=K.useRef(),b=function(){var _=h.current,D=n&&v.current?v.current:jf(_);if(D){v.current=D;var z=Of(D,_.value||_.placeholder||"x",i,a),I=z[0],B=z[1];g.current!==I&&(g.current=I,_.style.setProperty("height",I+"px","important"),u(I,{rowHeight:B}))}},w=function(_){c||b(),o(_)};return K.useLayoutEffect(b),$f(h,function(){if(!c){var T=h.current.value;requestAnimationFrame(function(){var _=h.current;_&&T!==_.value&&b()})}}),Uf(b),Hf(b),K.createElement("textarea",ra({},d,{onChange:w,ref:f}))},Wf=K.forwardRef(Vf),Ks=e=>{const t=At(e),r=Yr(n=>n.onScrollToBottom);y.useEffect(()=>r(t),[r,t])},Gs=y.forwardRef((g,f)=>{var v=g,{autoFocus:e=!1,asChild:t,disabled:r,onChange:n,onKeyDown:a,onPaste:i,submitOnEnter:s=!0,cancelOnEscape:o=!0,unstable_focusOnRunStart:l=!0,unstable_focusOnScrollToBottom:u=!0,unstable_focusOnThreadSwitched:d=!0,addAttachmentOnPaste:c=!0}=v,h=V(v,["autoFocus","asChild","disabled","onChange","onKeyDown","onPaste","submitOnEnter","cancelOnEscape","unstable_focusOnRunStart","unstable_focusOnScrollToBottom","unstable_focusOnThreadSwitched","addAttachmentOnPaste"]);const b=fe(),w=re(({composer:S})=>S.isEditing?S.text:""),T=t?Is:Wf,_=re(({thread:S})=>S.isDisabled)||r,D=y.useRef(null),z=Wr(f,D);cf(S=>{var M;if(!o||!((M=D.current)!=null&&M.contains(S.target)))return;const N=b.composer();N.getState().canCancel&&(N.cancel(),S.preventDefault())});const I=S=>{var N,M;_||!s||S.nativeEvent.isComposing||S.key==="Enter"&&S.shiftKey===!1&&(b.thread().getState().isRunning||(S.preventDefault(),(M=(N=D.current)==null?void 0:N.closest("form"))==null||M.requestSubmit()))},B=S=>P(null,null,function*(){var U;if(!c)return;const N=b.thread().getState().capabilities,M=Array.from(((U=S.clipboardData)==null?void 0:U.files)||[]);if(N.attachments&&M.length>0)try{S.preventDefault(),yield Promise.all(M.map(R=>b.composer().addAttachment(R)))}catch(R){console.error("Error adding attachment:",R)}}),H=e&&!_,j=y.useCallback(()=>{const S=D.current;!S||!H||(S.focus({preventScroll:!0}),S.setSelectionRange(S.value.length,S.value.length))},[H]);return y.useEffect(()=>j(),[j]),Ks(()=>{b.composer().getState().type==="thread"&&u&&j()}),y.useEffect(()=>{if(!(b.composer().getState().type!=="thread"||!l))return b.on("thread.run-start",j)},[l,j,b]),y.useEffect(()=>{if(!(b.composer().getState().type!=="thread"||!d))return b.on("thread-list-item.switched-to",j)},[d,j,b]),p.jsx(T,E(m({name:"input",value:w},h),{ref:z,disabled:_,onChange:qt(n,S=>{b.composer().getState().isEditing&&(b.composer().setText(S.target.value),b.flushSync())}),onKeyDown:qt(a,I),onPaste:qt(i,B)}))});Gs.displayName="ComposerPrimitive.Input";var Jf=({multiple:e=!0}={})=>{const t=re(({composer:a})=>!a.isEditing),r=fe(),n=y.useCallback(()=>{const a=document.createElement("input");a.type="file",a.multiple=e,a.hidden=!0;const i=r.composer().getState().attachmentAccept;i!=="*"&&(a.accept=i),document.body.appendChild(a),a.onchange=s=>{const o=s.target.files;if(o){for(const l of o)r.composer().addAttachment(l);document.body.removeChild(a)}},a.oncancel=()=>{(!a.files||a.files.length===0)&&document.body.removeChild(a)},a.click()},[r,e]);return t?null:n},Yf=fr("ComposerPrimitive.AddAttachment",Jf,["multiple"]),Kf=(e,t)=>{var n,a,i;const r=t.type;switch(r){case"image":return(n=e==null?void 0:e.Image)!=null?n:e==null?void 0:e.Attachment;case"document":return(a=e==null?void 0:e.Document)!=null?a:e==null?void 0:e.Attachment;case"file":return(i=e==null?void 0:e.File)!=null?i:e==null?void 0:e.Attachment;default:const s=r;throw new Error(`Unknown attachment type: ${s}`)}},Gf=({components:e})=>{const t=re(({attachment:n})=>n);if(!t)return null;const r=Kf(e,t);return r?p.jsx(r,{}):null},Xs=y.memo(({index:e,components:t})=>p.jsx(yh,{index:e,children:p.jsx(Gf,{components:t})}),(e,t)=>{var r,n,a,i,s,o,l,u;return e.index===t.index&&((r=e.components)==null?void 0:r.Image)===((n=t.components)==null?void 0:n.Image)&&((a=e.components)==null?void 0:a.Document)===((i=t.components)==null?void 0:i.Document)&&((s=e.components)==null?void 0:s.File)===((o=t.components)==null?void 0:o.File)&&((l=e.components)==null?void 0:l.Attachment)===((u=t.components)==null?void 0:u.Attachment)});Xs.displayName="ComposerPrimitive.AttachmentByIndex";var Qs=({components:e})=>{const t=re(n=>n.composer.attachments.length);return y.useMemo(()=>Array.from({length:t},(n,a)=>p.jsx(Xs,{index:a,components:e},a)),[t,e])};Qs.displayName="ComposerPrimitive.Attachments";var Zs=y.forwardRef((e,t)=>p.jsx(ht.div,E(m({},e),{ref:t})));Zs.displayName="ThreadPrimitive.Root";var eo=({children:e})=>re(({thread:r})=>r.messages.length===0&&!r.isLoading)?e:null;eo.displayName="ThreadPrimitive.Empty";var Xf=e=>{const t=At(e),r=y.useCallback(n=>{const a=new ResizeObserver(()=>{t()}),i=new MutationObserver(()=>{t()});return a.observe(n),i.observe(n,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),()=>{a.disconnect(),i.disconnect()}},[t]);return pr(r)},Qf=({autoScroll:e,scrollToBottomOnRunStart:t=!0,scrollToBottomOnInitialize:r=!0,scrollToBottomOnThreadSwitch:n=!0})=>{const a=y.useRef(null),i=Vn();e===void 0&&(e=i.getState().turnAnchor!=="top");const s=y.useRef(0),o=y.useRef(null),l=y.useCallback(f=>{const g=a.current;g&&(o.current=f,g.scrollTo({top:g.scrollHeight,behavior:f}))},[]),u=()=>{const f=a.current;if(!f)return;const g=i.getState().isAtBottom,v=Math.abs(f.scrollHeight-f.scrollTop-f.clientHeight)<1||f.scrollHeight<=f.clientHeight;!v&&s.current<f.scrollTop||(v&&(o.current=null),(v||o.current===null)&&v!==g&&hr(i).setState({isAtBottom:v})),s.current=f.scrollTop},d=Xf(()=>{const f=o.current;f?l(f):e&&i.getState().isAtBottom&&l("instant"),u()}),c=pr(f=>(f.addEventListener("scroll",u),()=>{f.removeEventListener("scroll",u)}));return Ks(({behavior:f})=>{l(f)}),qn("thread.run-start",()=>{t&&(o.current="auto",requestAnimationFrame(()=>{l("auto")}))}),qn("thread.initialize",()=>{r&&(o.current="instant",requestAnimationFrame(()=>{l("instant")}))}),qn("thread-list-item.switched-to",()=>{n&&(o.current="instant",requestAnimationFrame(()=>{l("instant")}))}),Wr(d,c,a)},Zf=()=>{const e=Yr(r=>r.registerViewport),t=y.useCallback(r=>r.clientHeight,[]);return Es(e,t)},to=y.forwardRef((o,s)=>{var l=o,{autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:r,scrollToBottomOnThreadSwitch:n,children:a}=l,i=V(l,["autoScroll","scrollToBottomOnRunStart","scrollToBottomOnInitialize","scrollToBottomOnThreadSwitch","children"]);const u=Qf({autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:r,scrollToBottomOnThreadSwitch:n}),d=Zf(),c=Wr(s,u,d);return p.jsx(ht.div,E(m({},i),{ref:c,children:a}))});to.displayName="ThreadPrimitive.ViewportScrollable";var ro=y.forwardRef((n,r)=>{var a=n,{turnAnchor:e}=a,t=V(a,["turnAnchor"]);return p.jsx(hs,{options:{turnAnchor:e},children:p.jsx(to,E(m({},t),{ref:r}))})});ro.displayName="ThreadPrimitive.Viewport";var no=(e,t)=>e.Message===t.Message&&e.EditComposer===t.EditComposer&&e.UserEditComposer===t.UserEditComposer&&e.AssistantEditComposer===t.AssistantEditComposer&&e.SystemEditComposer===t.SystemEditComposer&&e.UserMessage===t.UserMessage&&e.AssistantMessage===t.AssistantMessage&&e.SystemMessage===t.SystemMessage,ep=()=>null,tp=(e,t,r)=>{var n,a,i,s,o,l,u,d,c,h,f,g;switch(t){case"user":return r?(i=(a=(n=e.UserEditComposer)!=null?n:e.EditComposer)!=null?a:e.UserMessage)!=null?i:e.Message:(s=e.UserMessage)!=null?s:e.Message;case"assistant":return r?(u=(l=(o=e.AssistantEditComposer)!=null?o:e.EditComposer)!=null?l:e.AssistantMessage)!=null?u:e.Message:(d=e.AssistantMessage)!=null?d:e.Message;case"system":return r?(f=(h=(c=e.SystemEditComposer)!=null?c:e.EditComposer)!=null?h:e.SystemMessage)!=null?f:e.Message:(g=e.SystemMessage)!=null?g:ep;default:const v=t;throw new Error(`Unknown message role: ${v}`)}},rp=({components:e})=>{const t=re(({message:a})=>a.role),r=re(({message:a})=>a.composer.isEditing),n=tp(e,t,r);return p.jsx(n,{})},ao=y.memo(({index:e,components:t})=>p.jsx(ph,{index:e,children:p.jsx(rp,{components:t})}),(e,t)=>e.index===t.index&&no(e.components,t.components));ao.displayName="ThreadPrimitive.MessageByIndex";var io=({components:e})=>{const t=re(({thread:n})=>n.messages.length);return y.useMemo(()=>t===0?null:Array.from({length:t},(n,a)=>p.jsx(ao,{index:a,components:e},a)),[t,e])};io.displayName="ThreadPrimitive.Messages";var np=y.memo(io,(e,t)=>no(e.components,t.components)),so=y.forwardRef((a,n)=>{var i=a,{onClick:e,disabled:t}=i,r=V(i,["onClick","disabled"]);const s=re(({threads:l})=>l.newThreadId===l.mainThreadId),o=fe();return p.jsx(ht.button,E(m(m({type:"button"},s?{"data-active":"true","aria-current":"true"}:null),r),{ref:n,disabled:t,onClick:qt(e,()=>{o.threads().switchToNewThread()})}))});so.displayName="ThreadListPrimitive.New";var oo=y.memo(({index:e,archived:t=!1,components:r})=>{const n=r.ThreadListItem;return p.jsx(hh,{index:e,archived:t,children:p.jsx(n,{})})},(e,t)=>e.index===t.index&&e.archived===t.archived&&e.components.ThreadListItem===t.components.ThreadListItem);oo.displayName="ThreadListPrimitive.ItemByIndex";var lo=({archived:e=!1,components:t})=>{const r=re(({threads:a})=>e?a.archivedThreadIds.length:a.threadIds.length);return y.useMemo(()=>Array.from({length:r},(a,i)=>p.jsx(oo,{index:i,archived:e,components:t},i)),[r,e,t])};lo.displayName="ThreadListPrimitive.Items";var uo=y.forwardRef((e,t)=>p.jsx(ht.div,E(m({},e),{ref:t})));uo.displayName="ThreadListPrimitive.Root";var co=y.forwardRef((e,t)=>{const r=re(({threads:n,threadListItem:a})=>n.mainThreadId===a.id);return p.jsx(ht.div,E(m(m({},r?{"data-active":"true","aria-current":"true"}:null),e),{ref:t}))});co.displayName="ThreadListItemPrimitive.Root";var ap=()=>{const e=fe();return y.useCallback(()=>{e.threadListItem().delete()},[e])},ip=fr("ThreadListItemPrimitive.Delete",ap),sp=()=>{const e=fe();return y.useCallback(()=>{e.threadListItem().switchTo()},[e])},op=fr("ThreadListItemPrimitive.Trigger",sp);function lp(){if(typeof crypto!="undefined"&&crypto.randomUUID)return crypto.randomUUID();if(typeof crypto!="undefined"&&crypto.getRandomValues){const e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=Array.from(e,r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`}class ho{constructor(t,r,n=!1){C(this,"baseUrl");C(this,"sessionToken",null);C(this,"isProxyMode",!1);this.baseUrl=t.replace(/\/$/,""),this.isProxyMode=n,r&&(this.sessionToken=r)}setSessionToken(t){this.sessionToken=t}getUrl(t){if(this.isProxyMode){const r=`${this.baseUrl}${t.replace("/v1","")}`;return r.startsWith("/")||r.startsWith("./"),r}return`${this.baseUrl}${t}`}createOrContinueChat(t,r){return P(this,null,function*(){const n=this.getUrl("/v1/chats"),i={"Content-Type":"application/json",Accept:"text/event-stream","Accept-Encoding":"identity","Cache-Control":"no-cache","X-Accel-Buffering":"no","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(i.Authorization=`Bearer ${this.sessionToken}`);const s=E(m({},t),{stream:!0}),o=yield fetch(n,{method:"POST",headers:i,body:JSON.stringify(s),signal:r,cache:"no-store"});if(!o.ok){const l=yield o.json().catch(()=>({}));throw new Error(l.detail||l.message||`API error: ${o.status} ${o.statusText}`)}if(!o.body)throw new Error("Response body is null");return o.body})}getChat(t){return P(this,null,function*(){const r=this.getUrl(`/v1/chats/${t}`),n={"Content-Type":"application/json"};this.sessionToken&&(n.Authorization=`Bearer ${this.sessionToken}`);const a=yield fetch(r,{method:"GET",headers:n});if(!a.ok){const i=yield a.json().catch(()=>({}));throw new Error(i.detail||i.message||`API error: ${a.status} ${a.statusText}`)}return a.json()})}listChats(t){return P(this,null,function*(){const r=this.getUrl("/v1/chats"),n=r.startsWith("/")||r.startsWith("./")?new URL(r,window.location.origin):new URL(r);t!=null&&t.limit&&n.searchParams.set("limit",t.limit.toString()),t!=null&&t.cursor&&n.searchParams.set("cursor",t.cursor),t!=null&&t["expand[]"]&&t["expand[]"].forEach(s=>{n.searchParams.append("expand[]",s)});const a={"Content-Type":"application/json"};this.sessionToken&&(a.Authorization=`Bearer ${this.sessionToken}`);const i=yield fetch(n.toString(),{method:"GET",headers:a});if(!i.ok){const s=yield i.json().catch(()=>({}));throw new Error(s.detail||s.message||`API error: ${i.status} ${i.statusText}`)}return i.json()})}generateIdempotencyKey(){return lp()}updateChat(t,r){return P(this,null,function*(){const n=`/v1/chats/${t}`,a=this.getUrl(n),i=a.startsWith("/")||a.startsWith("./")?new URL(a,window.location.origin):new URL(a),o={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(o.Authorization=`Bearer ${this.sessionToken}`);const l=yield fetch(i.toString(),{method:"PATCH",headers:o,body:JSON.stringify(r)});if(!l.ok){const d=yield l.text();let c={};try{c=JSON.parse(d)}catch(h){c={detail:d}}throw new Error(c.detail||c.message||`API error: ${l.status} ${l.statusText}`)}if(l.status===204)return{};const u=yield l.text();if(!u)return{};try{return JSON.parse(u)}catch(d){return{}}})}deleteChat(t){return P(this,null,function*(){const r=`/v1/chats/${t}`,n=this.getUrl(r),a=n.startsWith("/")||n.startsWith("./")?new URL(n,window.location.origin):new URL(n),s={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(s.Authorization=`Bearer ${this.sessionToken}`);const o=yield fetch(a.toString(),{method:"DELETE",headers:s});if(!o.ok){const l=yield o.json().catch(()=>({}));throw new Error(l.detail||l.message||`API error: ${o.status} ${o.statusText}`)}})}listModels(t){return P(this,null,function*(){const r=this.getUrl("/v1/models"),n=r.startsWith("/")||r.startsWith("./")?new URL(r,window.location.origin):new URL(r);t!=null&&t.limit&&n.searchParams.set("limit",t.limit.toString()),t!=null&&t.cursor&&n.searchParams.set("cursor",t.cursor),t!=null&&t["expand[]"]&&t["expand[]"].forEach(s=>{n.searchParams.append("expand[]",s)});const a={"Content-Type":"application/json"};this.sessionToken&&(a.Authorization=`Bearer ${this.sessionToken}`);const i=yield fetch(n.toString(),{method:"GET",headers:a});if(!i.ok){const s=yield i.json().catch(()=>({}));throw new Error(s.detail||s.message||`API error: ${i.status} ${i.statusText}`)}return i.json()})}getModel(t){return P(this,null,function*(){const r=this.getUrl(`/v1/models/${t}`),n={"Content-Type":"application/json"};this.sessionToken&&(n.Authorization=`Bearer ${this.sessionToken}`);const a=yield fetch(r,{method:"GET",headers:n});if(!a.ok){const i=yield a.json().catch(()=>({}));throw new Error(i.detail||i.message||`API error: ${a.status} ${a.statusText}`)}return a.json()})}uploadFile(t,r,n){return P(this,null,function*(){const a=this.getUrl("/v1/files"),i=this.generateIdempotencyKey(),s=new FormData;s.append("file",t),r&&s.append("resource_type",r),n&&s.append("resource_id",n);const o={"Idempotency-Key":i};this.sessionToken&&(o.Authorization=`Bearer ${this.sessionToken}`);const l=yield fetch(a,{method:"POST",headers:o,body:s});if(!l.ok){const u=yield l.json().catch(()=>({}));throw new Error(u.detail||u.message||`API error: ${l.status} ${l.statusText}`)}return l.json()})}}function up(e,t){return Pr(this,null,function*(){const r=e.getReader(),n=new TextDecoder;let a="";try{for(;;){if(t!=null&&t.aborted){r.cancel();break}const{done:i,value:s}=yield new Ne(r.read());if(i)break;a+=n.decode(s,{stream:!0});const o=a.split(`
5
+ `),Ei=class{constructor(e){this._core=e,this.__internal_bindMethods()}get path(){return this._core.path}__internal_bindMethods(){this.getState=this.getState.bind(this),this.remove=this.remove.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this._core.getState()}subscribe(e){return this._core.subscribe(e)}},Ai=class extends Ei{constructor(e,t){super(e),this._composerApi=t}remove(){const e=this._composerApi.getState();if(!e)throw new Error("Composer is not available");return e.removeAttachment(this.getState().id)}},yc=class extends Ai{get source(){return"thread-composer"}},bc=class extends Ai{get source(){return"edit-composer"}},wc=class extends Ei{get source(){return"message"}constructor(e){super(e)}remove(){throw new Error("Message attachments cannot be removed")}},Mi=class extends Br{constructor(e){super(),this.config=e}getState(){return this.config.binding.getState()}outerSubscribe(e){return this.config.binding.subscribe(e)}_connect(){const e=()=>{this.notifySubscribers()};let t=this.config.binding.getState(),r=t==null?void 0:t.unstable_on(this.config.event,e);const n=()=>{var s;const i=this.config.binding.getState();i!==t&&(t=i,r==null||r(),r=(s=this.config.binding.getState())==null?void 0:s.unstable_on(this.config.event,e))},a=this.outerSubscribe(n);return()=>{a==null||a(),r==null||r()}}},Pi=Object.freeze([]),Ni=Object.freeze({}),xc=e=>{var t,r,n,a,i,s,o,l,u;return Object.freeze({type:"thread",isEditing:(t=e==null?void 0:e.isEditing)!=null?t:!1,canCancel:(r=e==null?void 0:e.canCancel)!=null?r:!1,isEmpty:(n=e==null?void 0:e.isEmpty)!=null?n:!0,attachments:(a=e==null?void 0:e.attachments)!=null?a:Pi,text:(i=e==null?void 0:e.text)!=null?i:"",role:(s=e==null?void 0:e.role)!=null?s:"user",runConfig:(o=e==null?void 0:e.runConfig)!=null?o:Ni,attachmentAccept:(l=e==null?void 0:e.attachmentAccept)!=null?l:"",value:(u=e==null?void 0:e.text)!=null?u:""})},vc=e=>{var t,r,n,a,i,s,o,l,u;return Object.freeze({type:"edit",isEditing:(t=e==null?void 0:e.isEditing)!=null?t:!1,canCancel:(r=e==null?void 0:e.canCancel)!=null?r:!1,isEmpty:(n=e==null?void 0:e.isEmpty)!=null?n:!0,text:(a=e==null?void 0:e.text)!=null?a:"",role:(i=e==null?void 0:e.role)!=null?i:"user",attachments:(s=e==null?void 0:e.attachments)!=null?s:Pi,runConfig:(o=e==null?void 0:e.runConfig)!=null?o:Ni,attachmentAccept:(l=e==null?void 0:e.attachmentAccept)!=null?l:"",value:(u=e==null?void 0:e.text)!=null?u:""})},Li=class{constructor(e){C(this,"_eventSubscriptionSubjects",new Map);this._core=e}get path(){return this._core.path}__internal_bindMethods(){this.setText=this.setText.bind(this),this.setRunConfig=this.setRunConfig.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.addAttachment=this.addAttachment.bind(this),this.reset=this.reset.bind(this),this.clearAttachments=this.clearAttachments.bind(this),this.send=this.send.bind(this),this.cancel=this.cancel.bind(this),this.setRole=this.setRole.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_on=this.unstable_on.bind(this)}setText(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.setText(e)}setRunConfig(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.setRunConfig(e)}addAttachment(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");return t.addAttachment(e)}reset(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");return e.reset()}clearAttachments(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");return e.clearAttachments()}send(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.send()}cancel(){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.cancel()}setRole(e){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.setRole(e)}subscribe(e){return this._core.subscribe(e)}unstable_on(e,t){let r=this._eventSubscriptionSubjects.get(e);return r||(r=new Mi({event:e,binding:this._core}),this._eventSubscriptionSubjects.set(e,r)),r.subscribe(t)}},kc=class extends Li{constructor(t){const r=new On({path:t.path,getState:()=>xc(t.getState()),subscribe:n=>t.subscribe(n)});super({path:t.path,getState:()=>t.getState(),subscribe:n=>r.subscribe(n)});C(this,"_getState");this._getState=r.getState.bind(r),this.__internal_bindMethods()}get path(){return this._core.path}get type(){return"thread"}getState(){return this._getState()}getAttachmentByIndex(t){return new yc(new rt({path:E(m({},this.path),{attachmentSource:"thread-composer",attachmentSelector:{type:"index",index:t},ref:`${this.path.ref}${this.path.ref}.attachments[${t}]`}),getState:()=>{const n=this.getState().attachments[t];return n?E(m({},n),{source:"thread-composer"}):tt},subscribe:r=>this._core.subscribe(r)}),this._core)}},Sc=class extends Li{constructor(t,r){const n=new On({path:t.path,getState:()=>vc(t.getState()),subscribe:a=>t.subscribe(a)});super({path:t.path,getState:()=>t.getState(),subscribe:a=>n.subscribe(a)});C(this,"_getState");this._beginEdit=r,this._getState=n.getState.bind(n),this.__internal_bindMethods()}get path(){return this._core.path}get type(){return"edit"}__internal_bindMethods(){super.__internal_bindMethods(),this.beginEdit=this.beginEdit.bind(this)}getState(){return this._getState()}beginEdit(){this._beginEdit()}getAttachmentByIndex(t){return new bc(new rt({path:E(m({},this.path),{attachmentSource:"edit-composer",attachmentSelector:{type:"index",index:t},ref:`${this.path.ref}${this.path.ref}.attachments[${t}]`}),getState:()=>{const n=this.getState().attachments[t];return n?E(m({},n),{source:"edit-composer"}):tt},subscribe:r=>this._core.subscribe(r)}),this._core)}},_c=class Sn{constructor(t=null){C(this,"_state");this._state=t}get state(){return this._state}append(t){this._state=t.reduce((r,n)=>Sn.apply(r,n),this._state)}static apply(t,r){const n=r.type;switch(n){case"set":return Sn.updatePath(t,r.path,()=>r.value);case"append-text":return Sn.updatePath(t,r.path,a=>{if(typeof a!="string")throw new Error(`Expected string at path [${r.path.join(", ")}]`);return a+r.value});default:{const a=n;throw new Error(`Invalid operation type: ${a}`)}}}static updatePath(t,r,n){if(r.length===0)return n(t);if(t!=null||(t={}),typeof t!="object")throw new Error(`Invalid path: [${r.join(", ")}]`);const[a,...i]=r;if(Array.isArray(t)){const o=Number(a);if(Number.isNaN(o))throw new Error(`Expected array index at [${r.join(", ")}]`);if(o>t.length||o<0)throw new Error("Insert array index out of bounds");const l=[...t];return l[o]=this.updatePath(l[o],i,n),l}const s=m({},t);return s[a]=this.updatePath(s[a],i,n),s}},Tc=({unstable_state:e=null}={})=>({role:"assistant",status:{type:"running"},parts:[],get content(){return this.parts},metadata:{unstable_state:e,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}),$r=(e,t,r)=>{if(e.parts.length===0)throw new Error("No parts available to update.");if(t.path.length!==1)throw new Error("Nested paths are not supported yet.");const n=t.path[0],a=r(e.parts[n]);return E(m({},e),{parts:[...e.parts.slice(0,n),a,...e.parts.slice(n+1)],get content(){return this.parts}})},Cc=(e,t)=>{const r=t.part;if(r.type==="text"||r.type==="reasoning"){const n=m({type:r.type,text:"",status:{type:"running"}},r.parentId&&{parentId:r.parentId});return E(m({},e),{parts:[...e.parts,n],get content(){return this.parts}})}else if(r.type==="tool-call"){const n=m({type:"tool-call",state:"partial-call",status:{type:"running",isArgsComplete:!1},toolCallId:r.toolCallId,toolName:r.toolName,argsText:"",args:{}},r.parentId&&{parentId:r.parentId});return E(m({},e),{parts:[...e.parts,n],get content(){return this.parts}})}else if(r.type==="source"){const n=m(m({type:"source",sourceType:r.sourceType,id:r.id,url:r.url},r.title?{title:r.title}:void 0),r.parentId&&{parentId:r.parentId});return E(m({},e),{parts:[...e.parts,n],get content(){return this.parts}})}else if(r.type==="file"){const n={type:"file",mimeType:r.mimeType,data:r.data};return E(m({},e),{parts:[...e.parts,n],get content(){return this.parts}})}else throw new Error(`Unsupported part type: ${r.type}`)},Ic=(e,t)=>$r(e,t,r=>{if(r.type!=="tool-call")throw new Error("Last is not a tool call");return r.state!=="partial-call"?r:E(m({},r),{state:"call"})}),Ec=(e,t)=>$r(e,t,r=>E(m({},r),{status:{type:"complete",reason:"unknown"}})),Ac=(e,t)=>$r(e,t,r=>{var n;if(r.type==="text"||r.type==="reasoning")return E(m({},r),{text:r.text+t.textDelta});if(r.type==="tool-call"){const a=r.argsText+t.textDelta,i=(n=Or(a))!=null?n:r.args;return E(m({},r),{argsText:a,args:i})}else throw new Error("text-delta received but part is neither text nor tool-call")}),Mc=(e,t)=>$r(e,t,r=>{var n;if(r.type==="tool-call")return E(m(E(m({},r),{state:"result"}),t.artifact!==void 0?{artifact:t.artifact}:{}),{result:t.result,isError:(n=t.isError)!=null?n:!1,status:{type:"complete",reason:"stop"}});throw new Error("Result chunk received but part is not a tool-call")}),Di=(e,t)=>{var n,a;if(((n=e.status)==null?void 0:n.type)==="incomplete"&&((a=e.status)==null?void 0:a.reason)==="error")return e;const r=Pc(t);return E(m({},e),{status:r})},Pc=e=>e.finishReason==="tool-calls"?{type:"requires-action",reason:"tool-calls"}:e.finishReason==="stop"||e.finishReason==="unknown"?{type:"complete",reason:e.finishReason}:{type:"incomplete",reason:e.finishReason},Nc=(e,t)=>E(m({},e),{metadata:E(m({},e.metadata),{unstable_annotations:[...e.metadata.unstable_annotations,...t.annotations]})}),Lc=(e,t)=>E(m({},e),{metadata:E(m({},e.metadata),{unstable_data:[...e.metadata.unstable_data,...t.data]})}),Dc=(e,t)=>E(m({},e),{metadata:E(m({},e.metadata),{steps:[...e.metadata.steps,{state:"started",messageId:t.messageId}]})}),Oc=(e,t)=>{var a;const r=e.metadata.steps.slice(),n=r.length-1;return r.length>0&&((a=r[n])==null?void 0:a.state)==="started"?r[n]=E(m({},r[n]),{state:"finished",finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}):r.push({state:"finished",messageId:Ti(),finishReason:t.finishReason,usage:t.usage,isContinued:t.isContinued}),E(m({},e),{metadata:E(m({},e.metadata),{steps:r})})},Fc=(e,t)=>E(m({},e),{status:{type:"incomplete",reason:"error",error:t.error}}),Bc=(e,t)=>{const r=new _c(e.metadata.unstable_state);return r.append(t.operations),E(m({},e),{metadata:E(m({},e.metadata),{unstable_state:r.state})})},zc=e=>{let t=!1;return()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}},Rc=class extends TransformStream{constructor({initialMessage:e,throttle:t,onError:r}={}){let n=e!=null?e:Tc(),a;const i=t?zc(()=>{a==null||a.enqueue(n)}):()=>{a==null||a.enqueue(n)};super({start(s){a=s},transform(s){const o=s.type;switch(o){case"part-start":n=Cc(n,s);break;case"tool-call-args-text-finish":n=Ic(n,s);break;case"part-finish":n=Ec(n,s);break;case"text-delta":n=Ac(n,s);break;case"result":n=Mc(n,s);break;case"message-finish":n=Di(n,s);break;case"annotations":n=Nc(n,s);break;case"data":n=Lc(n,s);break;case"step-start":n=Dc(n,s);break;case"step-finish":n=Oc(n,s);break;case"error":n=Fc(n,s),r==null||r(s.error);break;case"update-state":n=Bc(n,s);break;default:{const l=o;throw new Error(`Unsupported chunk type: ${l}`)}}i()},flush(s){var o,l,u;if(((o=n.status)==null?void 0:o.type)==="running"){const d=(u=(l=n.parts)==null?void 0:l.some(c=>c.type==="tool-call"&&(c.state==="call"||c.state==="partial-call")&&c.result===void 0))!=null?u:!1;n=Di(n,{finishReason:d?"tool-calls":"unknown"}),s.enqueue(n)}}})}},jc=class extends Si{constructor(){super(e=>{const t=new pc({transform(r,n){n.appendText(r)}});return e.pipeThrough(new TextDecoderStream).pipeThrough(t)})}},$c=class _n{constructor(t){this.readable=t,this.readable=t}static fromAssistantStream(t){return new _n(t.pipeThrough(new Rc))}unstable_result(){return P(this,null,function*(){let t;try{for(var r=Ft(this),n,a,i;n=!(a=yield r.next()).done;n=!1){const s=a.value;t=s}}catch(a){i=[a]}finally{try{n&&(a=r.return)&&(yield a.call(r))}finally{if(i)throw i[0]}}return t||{role:"assistant",status:{type:"complete",reason:"unknown"},parts:[],content:[],metadata:{unstable_state:null,unstable_data:[],unstable_annotations:[],steps:[],custom:{}}}})}[Symbol.asyncIterator](){const t=this.readable.getReader();return{next(){return P(this,null,function*(){const{done:n,value:a}=yield t.read();return n?{done:!0,value:void 0}:{done:!1,value:a}})}}}tee(){const[t,r]=this.readable.tee();return[new _n(t),new _n(r)]}},Oi=Symbol.for("aui.tool-response"),gt=class li{constructor(t){C(this,"artifact");C(this,"result");C(this,"isError");var r;t.artifact!==void 0&&(this.artifact=t.artifact),this.result=t.result,this.isError=(r=t.isError)!=null?r:!1}get[Oi](){return!0}static[Symbol.hasInstance](t){return typeof t=="object"&&t!==null&&Oi in t}static toResponse(t){return t instanceof li?t:new li({result:t===void 0?"<no result>":t})}};function Uc(e,t,r){try{const n=e();if(typeof n=="object"&&n!==null&&"then"in n)return n.then(t,r);t(n)}catch(n){r(n)}}function or(e,t){let r=e;for(const n of t){if(r==null)return;r=r[n]}return r}var Hc=class{constructor(e,t,r){C(this,"resolve");C(this,"reject");C(this,"disposed",!1);C(this,"fieldPath");this.resolve=e,this.reject=t,this.fieldPath=r}update(e){if(!this.disposed)try{if(Bt(e,this.fieldPath)==="complete"){const t=or(e,this.fieldPath);t!==void 0&&(this.resolve(t),this.dispose())}}catch(t){this.reject(t),this.dispose()}}dispose(){this.disposed=!0}},Fi=class{constructor(e,t){C(this,"controller");C(this,"disposed",!1);C(this,"fieldPath");this.controller=e,this.fieldPath=t}update(e){if(!this.disposed)try{const t=or(e,this.fieldPath);t!==void 0&&this.controller.enqueue(t),Bt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(t){this.controller.error(t),this.dispose()}}dispose(){this.disposed=!0}},Bi=class{constructor(e,t){C(this,"controller");C(this,"disposed",!1);C(this,"fieldPath");C(this,"lastValue");this.controller=e,this.fieldPath=t}update(e){var t;if(!this.disposed)try{const r=or(e,this.fieldPath);if(r!==void 0&&typeof r=="string"){const n=r.substring(((t=this.lastValue)==null?void 0:t.length)||0);this.lastValue=r,this.controller.enqueue(n)}Bt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(r){this.controller.error(r),this.dispose()}}dispose(){this.disposed=!0}},zi=class{constructor(e,t){C(this,"controller");C(this,"disposed",!1);C(this,"fieldPath");C(this,"processedIndexes",new Set);this.controller=e,this.fieldPath=t}update(e){if(!this.disposed)try{const t=or(e,this.fieldPath);if(!Array.isArray(t))return;for(let r=0;r<t.length;r++)if(!this.processedIndexes.has(r)){const n=[...this.fieldPath,r];Bt(e,n)==="complete"&&(this.controller.enqueue(t[r]),this.processedIndexes.add(r))}Bt(e,this.fieldPath)==="complete"&&(this.controller.close(),this.dispose())}catch(t){this.controller.error(t),this.dispose()}}dispose(){this.disposed=!0}},qc=class{constructor(e){C(this,"argTextDeltas");C(this,"handles",new Set);C(this,"args",Or(""));this.argTextDeltas=e,this.processStream()}processStream(){return P(this,null,function*(){try{let e="";const t=this.argTextDeltas.getReader();for(;;){const{value:r,done:n}=yield t.read();if(n)break;e+=r;const a=Or(e);if(a!==void 0){this.args=a;for(const i of this.handles)i.update(a)}}}catch(e){console.error("Error processing argument stream:",e);for(const t of this.handles)t.dispose()}})}get(...e){return new Promise((t,r)=>{const n=new Hc(t,r,e);if(this.args&&Bt(this.args,e)==="complete"){const a=or(this.args,e);if(a!==void 0){t(a);return}}this.handles.add(n),n.update(this.args)})}streamValues(...e){const t=e,r=new ReadableStream({start:n=>{const a=new Fi(n,t);this.handles.add(a),a.update(this.args)},cancel:()=>{for(const n of this.handles)if(n instanceof Fi){n.dispose(),this.handles.delete(n);break}}});return Pn(r)}streamText(...e){const t=e,r=new ReadableStream({start:n=>{const a=new Bi(n,t);this.handles.add(a),a.update(this.args)},cancel:()=>{for(const n of this.handles)if(n instanceof Bi){n.dispose(),this.handles.delete(n);break}}});return Pn(r)}forEach(...e){const t=e,r=new ReadableStream({start:n=>{const a=new zi(n,t);this.handles.add(a),a.update(this.args)},cancel:()=>{for(const n of this.handles)if(n instanceof zi){n.dispose(),this.handles.delete(n);break}}});return Pn(r)}},Vc=class{constructor(e){this.promise=e}get(){return this.promise}},Wc=class{constructor(){C(this,"args");C(this,"response");C(this,"writable");C(this,"resolve");C(this,"argsText","");C(this,"result",{get:()=>P(this,null,function*(){return(yield this.response.get()).result})});const e=new TransformStream;this.writable=e.writable,this.args=new qc(e.readable);const{promise:t,resolve:r}=Ln();this.resolve=r,this.response=new Vc(t)}appendArgsTextDelta(e){return P(this,null,function*(){const t=this.writable.getWriter();try{yield t.write(e)}catch(r){console.warn(r)}finally{t.releaseLock()}this.argsText+=e})}setResponse(e){this.resolve(e)}},Jc=class extends Si{constructor(e){const t=new Map,r=new Map;super(n=>{const a=new TransformStream({transform(s,o){switch((s.type!=="part-finish"||s.meta.type!=="tool-call")&&o.enqueue(s),s.type){case"part-start":if(s.part.type==="tool-call"){const u=new Wc;r.set(s.part.toolCallId,u),e.streamCall({reader:u,toolCallId:s.part.toolCallId,toolName:s.part.toolName})}break;case"text-delta":{if(s.meta.type==="tool-call"){const u=s.meta.toolCallId,d=r.get(u);if(!d)throw new Error("No controller found for tool call");d.appendArgsTextDelta(s.textDelta)}break}case"result":{if(s.meta.type!=="tool-call")break;const{toolCallId:u}=s.meta,d=r.get(u);if(!d)throw new Error("No controller found for tool call");d.setResponse(new gt({result:s.result,artifact:s.artifact,isError:s.isError}));break}case"tool-call-args-text-finish":{if(s.meta.type!=="tool-call")break;const{toolCallId:u,toolName:d}=s.meta,c=r.get(u);if(!c)throw new Error("No controller found for tool call");let h=!1;const f=Uc(()=>{var b;let g;try{g=Mn.parse(c.argsText)}catch(w){throw new Error(`Function parameter parsing failed. ${JSON.stringify(w.message)}`)}const v=e.execute({toolCallId:u,toolName:d,args:g});return v!==void 0&&(h=!0,(b=e.onExecutionStart)==null||b.call(e,u,d)),v},g=>{var b;if(h&&((b=e.onExecutionEnd)==null||b.call(e,u,d)),g===void 0)return;const v=new gt({artifact:g.artifact,result:g.result,isError:g.isError});c.setResponse(v),o.enqueue(m({type:"result",path:s.path},v))},g=>{var b;h&&((b=e.onExecutionEnd)==null||b.call(e,u,d));const v=new gt({result:String(g),isError:!0});c.setResponse(v),o.enqueue(m({type:"result",path:s.path},v))});f&&t.set(u,f);break}case"part-finish":{if(s.meta.type!=="tool-call")break;const{toolCallId:u}=s.meta,d=t.get(u);d?d.then(()=>{t.delete(u),r.delete(u),o.enqueue(s)}):o.enqueue(s)}}},flush(){return P(this,null,function*(){yield Promise.all(t.values())})}});return n.pipeThrough(new _i).pipeThrough(a)})}},Yc=e=>typeof e=="object"&&e!==null&&"~standard"in e&&e["~standard"].version===1;function Kc(e,t,r,n){const a=e==null?void 0:e[r.toolName];return!a||!a.execute?void 0:(s=>P(null,null,function*(){var d;if(t.aborted)return new gt({result:"Tool execution was cancelled.",isError:!0});let o=s;if(Yc(a.parameters)){let c=a.parameters["~standard"].validate(r.args);c instanceof Promise&&(c=yield c),c.issues&&(o=(d=a.experimental_onSchemaValidationError)!=null?d:(()=>{throw new Error(`Function parameter validation failed. ${JSON.stringify(c.issues)}`)}))}const l=new Promise(c=>{const h=()=>{queueMicrotask(()=>{queueMicrotask(()=>{c(new gt({result:"Tool execution was cancelled.",isError:!0}))})})};t.aborted?h():t.addEventListener("abort",h,{once:!0})}),u=P(null,null,function*(){const c=yield o(r.args,{toolCallId:r.toolCallId,abortSignal:t,human:h=>n(r.toolCallId,h)});return gt.toResponse(c)});return Promise.race([u,l])}))(a.execute)}function Gc(e,t,r,n,a){var i,s;(s=(i=e==null?void 0:e[n.toolName])==null?void 0:i.streamCall)==null||s.call(i,r,{toolCallId:n.toolCallId,abortSignal:t,human:o=>a(n.toolCallId,o)})}function Xc(e,t,r,n){const a=typeof e=="function"?e:()=>e,i=typeof t=="function"?t:()=>t;return new Jc({execute:s=>Kc(a(),i(),s,r),streamCall:l=>{var u=l,{reader:s}=u,o=V(u,["reader"]);return Gc(a(),i(),s,o,r)},onExecutionStart:n==null?void 0:n.onExecutionStart,onExecutionEnd:n==null?void 0:n.onExecutionEnd})}var Ri=class{constructor(e,t,r){this.contentBinding=e,this.messageApi=t,this.threadApi=r,this.__internal_bindMethods()}get path(){return this.contentBinding.path}__internal_bindMethods(){this.addToolResult=this.addToolResult.bind(this),this.resumeToolCall=this.resumeToolCall.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this.contentBinding.getState()}addToolResult(e){const t=this.contentBinding.getState();if(!t)throw new Error("Message part is not available");if(t.type!=="tool-call")throw new Error("Tried to add tool result to non-tool message part");if(!this.messageApi)throw new Error("Message API is not available. This is likely a bug in assistant-ui.");if(!this.threadApi)throw new Error("Thread API is not available");const r=this.messageApi.getState();if(!r)throw new Error("Message is not available");const n=t.toolName,a=t.toolCallId,i=gt.toResponse(e);this.threadApi.getState().addToolResult({messageId:r.id,toolName:n,toolCallId:a,result:i.result,artifact:i.artifact,isError:i.isError})}resumeToolCall(e){const t=this.contentBinding.getState();if(!t)throw new Error("Message part is not available");if(t.type!=="tool-call")throw new Error("Tried to resume tool call on non-tool message part");if(!this.threadApi)throw new Error("Thread API is not available");const r=t.toolCallId;this.threadApi.getState().resumeToolCall({toolCallId:r,payload:e})}subscribe(e){return this.contentBinding.subscribe(e)}},Ur=class extends Br{constructor(e){super(),this.binding=e}get path(){return this.binding.path}getState(){return this.binding.getState()}outerSubscribe(e){return this.binding.subscribe(e)}_connect(){const e=()=>{this.notifySubscribers()};let t=this.binding.getState(),r=t==null?void 0:t.subscribe(e);const n=()=>{var s;const i=this.binding.getState();i!==t&&(t=i,r==null||r(),r=(s=this.binding.getState())==null?void 0:s.subscribe(e),e())},a=this.outerSubscribe(n);return()=>{a==null||a(),r==null||r()}}},Hr=Object.freeze({type:"complete"}),Qc=(e,t,r)=>{if(e.role!=="assistant")return Hr;if(r.type==="tool-call")return r.result?Hr:e.status;const n=t===Math.max(0,e.content.length-1);return e.status.type==="requires-action"?Hr:n?e.status:Hr},ji=(e,t)=>{const r=e.content[t];if(!r)return tt;const n=Qc(e,t,r);return Object.freeze(E(m({},r),{[Rr]:r[Rr],status:n}))},Zc=class{constructor(e,t){C(this,"composer");C(this,"_getEditComposerRuntimeCore",()=>this._threadBinding.getState().getEditComposer(this._core.getState().id));this._core=e,this._threadBinding=t,this.composer=new Sc(new Ur({path:E(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:"edit"}),getState:this._getEditComposerRuntimeCore,subscribe:r=>this._threadBinding.subscribe(r)}),()=>this._threadBinding.getState().beginEdit(this._core.getState().id)),this.__internal_bindMethods()}get path(){return this._core.path}__internal_bindMethods(){this.reload=this.reload.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getMessagePartByIndex=this.getMessagePartByIndex.bind(this),this.getMessagePartByToolCallId=this.getMessagePartByToolCallId.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_getCopyText=this.unstable_getCopyText.bind(this),this.speak=this.speak.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.submitFeedback=this.submitFeedback.bind(this),this.switchToBranch=this.switchToBranch.bind(this)}getState(){return this._core.getState()}reload(e={}){const t=this._getEditComposerRuntimeCore(),r=t!=null?t:this._threadBinding.getState().composer,n=t!=null?t:r,{runConfig:a=n.runConfig}=e,i=this._core.getState();if(i.role!=="assistant")throw new Error("Can only reload assistant messages");this._threadBinding.getState().startRun({parentId:i.parentId,sourceId:i.id,runConfig:a})}speak(){const e=this._core.getState();return this._threadBinding.getState().speak(e.id)}stopSpeaking(){var r;const e=this._core.getState();if(((r=this._threadBinding.getState().speech)==null?void 0:r.messageId)===e.id)this._threadBinding.getState().stopSpeaking();else throw new Error("Message is not being spoken")}submitFeedback({type:e}){const t=this._core.getState();this._threadBinding.getState().submitFeedback({messageId:t.id,type:e})}switchToBranch({position:e,branchId:t}){const r=this._core.getState();if(t&&e)throw new Error("May not specify both branchId and position");if(!t&&!e)throw new Error("Must specify either branchId or position");const a=this._threadBinding.getState().getBranches(r.id);let i=t;if(e==="previous"?i=a[r.branchNumber-2]:e==="next"&&(i=a[r.branchNumber]),!i)throw new Error("Branch not found");this._threadBinding.getState().switchToBranch(i)}unstable_getCopyText(){return jr(this.getState())}subscribe(e){return this._core.subscribe(e)}getMessagePartByIndex(e){if(e<0)throw new Error("Message part index must be >= 0");return new Ri(new rt({path:E(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.content[${e}]`,messagePartSelector:{type:"index",index:e}}),getState:()=>ji(this.getState(),e),subscribe:t=>this._core.subscribe(t)}),this._core,this._threadBinding)}getMessagePartByToolCallId(e){return new Ri(new rt({path:E(m({},this.path),{ref:this.path.ref+`${this.path.ref}.content[toolCallId=${JSON.stringify(e)}]`,messagePartSelector:{type:"toolCallId",toolCallId:e}}),getState:()=>{const t=this._core.getState(),r=t.content.findIndex(n=>n.type==="tool-call"&&n.toolCallId===e);return r===-1?tt:ji(t,r)},subscribe:t=>this._core.subscribe(t)}),this._core,this._threadBinding)}getAttachmentByIndex(e){return new wc(new rt({path:E(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.attachments[${e}]`,attachmentSource:"message",attachmentSelector:{type:"index",index:e}}),getState:()=>{const t=this.getState().attachments,r=t==null?void 0:t[e];return r?E(m({},r),{source:"message"}):tt},subscribe:t=>this._core.subscribe(t)}))}},ed=e=>{var t,r,n;return m({parentId:(t=e.parentId)!=null?t:null,sourceId:(r=e.sourceId)!=null?r:null,runConfig:(n=e.runConfig)!=null?n:{}},e.stream?{stream:e.stream}:{})},td=e=>{var t,r,n;return{parentId:(t=e.parentId)!=null?t:null,sourceId:(r=e.sourceId)!=null?r:null,runConfig:(n=e.runConfig)!=null?n:{}}},rd=(e,t)=>{var r,n,a,i,s,o,l,u,d,c,h;return typeof t=="string"?{createdAt:new Date,parentId:(n=(r=e.at(-1))==null?void 0:r.id)!=null?n:null,sourceId:null,runConfig:{},role:"user",content:[{type:"text",text:t}],attachments:[],metadata:{custom:{}}}:{createdAt:(a=t.createdAt)!=null?a:new Date,parentId:(o=(s=t.parentId)!=null?s:(i=e.at(-1))==null?void 0:i.id)!=null?o:null,sourceId:(l=t.sourceId)!=null?l:null,role:(u=t.role)!=null?u:"user",content:t.content,attachments:(d=t.attachments)!=null?d:[],metadata:(c=t.metadata)!=null?c:{custom:{}},runConfig:(h=t.runConfig)!=null?h:{},startRun:t.startRun}},nd=(e,t)=>{const r=e.messages.at(-1);return Object.freeze({threadId:t.id,metadata:t,capabilities:e.capabilities,isDisabled:e.isDisabled,isLoading:e.isLoading,isRunning:(r==null?void 0:r.role)!=="assistant"?!1:r.status.type==="running",messages:e.messages,state:e.state,suggestions:e.suggestions,extras:e.extras,speech:e.speech})},$i=class{constructor(e,t){C(this,"_threadBinding");C(this,"composer");C(this,"_eventSubscriptionSubjects",new Map);const r=new rt({path:e.path,getState:()=>nd(e.getState(),t.getState()),subscribe:n=>{const a=e.subscribe(n),i=t.subscribe(n);return()=>{a(),i()}}});this._threadBinding={path:e.path,getState:()=>e.getState(),getStateState:()=>r.getState(),outerSubscribe:n=>e.outerSubscribe(n),subscribe:n=>e.subscribe(n)},this.composer=new kc(new Ur({path:E(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.composer`,composerSource:"thread"}),getState:()=>this._threadBinding.getState().composer,subscribe:n=>this._threadBinding.subscribe(n)})),this.__internal_bindMethods()}get path(){return this._threadBinding.path}get __internal_threadBinding(){return this._threadBinding}__internal_bindMethods(){this.append=this.append.bind(this),this.unstable_resumeRun=this.unstable_resumeRun.bind(this),this.unstable_loadExternalState=this.unstable_loadExternalState.bind(this),this.startRun=this.startRun.bind(this),this.cancelRun=this.cancelRun.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.export=this.export.bind(this),this.import=this.import.bind(this),this.reset=this.reset.bind(this),this.getMessageByIndex=this.getMessageByIndex.bind(this),this.getMessageById=this.getMessageById.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getModelContext=this.getModelContext.bind(this),this.getModelConfig=this.getModelConfig.bind(this),this.getState=this.getState.bind(this)}getState(){return this._threadBinding.getStateState()}append(e){this._threadBinding.getState().append(rd(this._threadBinding.getState().messages,e))}subscribe(e){return this._threadBinding.subscribe(e)}getModelContext(){return this._threadBinding.getState().getModelContext()}getModelConfig(){return this.getModelContext()}startRun(e){const t=e===null||typeof e=="string"?{parentId:e}:e;return this._threadBinding.getState().startRun(td(t))}unstable_resumeRun(e){return this._threadBinding.getState().resumeRun(ed(e))}unstable_loadExternalState(e){this._threadBinding.getState().unstable_loadExternalState(e)}cancelRun(){this._threadBinding.getState().cancelRun()}stopSpeaking(){return this._threadBinding.getState().stopSpeaking()}export(){return this._threadBinding.getState().export()}import(e){this._threadBinding.getState().import(e)}reset(e){this._threadBinding.getState().reset(e)}getMessageByIndex(e){if(e<0)throw new Error("Message index must be >= 0");return this._getMessageRuntime(E(m({},this.path),{ref:`${this.path.ref}${this.path.ref}.messages[${e}]`,messageSelector:{type:"index",index:e}}),()=>{var n,a;const t=this._threadBinding.getState().messages,r=t[e];if(r)return{message:r,parentId:(a=(n=t[e-1])==null?void 0:n.id)!=null?a:null,index:e}})}getMessageById(e){return this._getMessageRuntime(E(m({},this.path),{ref:this.path.ref+`${this.path.ref}.messages[messageId=${JSON.stringify(e)}]`,messageSelector:{type:"messageId",messageId:e}}),()=>this._threadBinding.getState().getMessageById(e))}_getMessageRuntime(e,t){return new Zc(new rt({path:e,getState:()=>{var d,c;const{message:r,parentId:n,index:a}=(d=t())!=null?d:{},{messages:i,speech:s}=this._threadBinding.getState();if(!r||n===void 0||a===void 0)return tt;const l=this._threadBinding.getState().getBranches(r.id),u=r.metadata.submittedFeedback;return E(m({},r),{[Rr]:r[Rr],index:a,isLast:((c=i.at(-1))==null?void 0:c.id)===r.id,parentId:n,branchNumber:l.indexOf(r.id)+1,branchCount:l.length,speech:(s==null?void 0:s.messageId)===r.id?s:void 0,submittedFeedback:u})},subscribe:r=>this._threadBinding.subscribe(r)}),this._threadBinding)}unstable_on(e,t){let r=this._eventSubscriptionSubjects.get(e);return r||(r=new Mi({event:e,binding:this._threadBinding}),this._eventSubscriptionSubjects.set(e,r)),r.subscribe(t)}},ad=e=>({mainThreadId:e.mainThreadId,newThread:e.newThreadId,threads:e.threadIds,archivedThreads:e.archivedThreadIds,isLoading:e.isLoading,threadItems:e.threadData}),qr=(e,t)=>{if(t===void 0)return tt;const r=e.getItemById(t);return r?{id:r.id,threadId:r.id,remoteId:r.remoteId,externalId:r.externalId,title:r.title,status:r.status,isMain:r.id===e.mainThreadId}:tt},id=class{constructor(e,t=$i){C(this,"_getState");C(this,"_mainThreadListItemRuntime");C(this,"main");this._core=e,this._runtimeFactory=t;const r=new On({path:{},getState:()=>ad(e),subscribe:n=>e.subscribe(n)});this._getState=r.getState.bind(r),this._mainThreadListItemRuntime=new zr(new rt({path:{ref:"threadItems[main]",threadSelector:{type:"main"}},getState:()=>qr(this._core,this._core.mainThreadId),subscribe:n=>this._core.subscribe(n)}),this._core),this.main=new t(new Ur({path:{ref:"threads.main",threadSelector:{type:"main"}},getState:()=>e.getMainThreadRuntimeCore(),subscribe:n=>e.subscribe(n)}),this._mainThreadListItemRuntime),this.__internal_bindMethods()}__internal_bindMethods(){this.switchToThread=this.switchToThread.bind(this),this.switchToNewThread=this.switchToNewThread.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getById=this.getById.bind(this),this.getItemById=this.getItemById.bind(this),this.getItemByIndex=this.getItemByIndex.bind(this),this.getArchivedItemByIndex=this.getArchivedItemByIndex.bind(this)}switchToThread(e){return this._core.switchToThread(e)}switchToNewThread(){return this._core.switchToNewThread()}getState(){return this._getState()}subscribe(e){return this._core.subscribe(e)}get mainItem(){return this._mainThreadListItemRuntime}getById(e){return new this._runtimeFactory(new Ur({path:{ref:`threads[threadId=${JSON.stringify(e)}]`,threadSelector:{type:"threadId",threadId:e}},getState:()=>this._core.getThreadRuntimeCore(e),subscribe:t=>this._core.subscribe(t)}),this.mainItem)}getItemByIndex(e){return new zr(new rt({path:{ref:`threadItems[${e}]`,threadSelector:{type:"index",index:e}},getState:()=>qr(this._core,this._core.threadIds[e]),subscribe:t=>this._core.subscribe(t)}),this._core)}getArchivedItemByIndex(e){return new zr(new rt({path:{ref:`archivedThreadItems[${e}]`,threadSelector:{type:"archiveIndex",index:e}},getState:()=>qr(this._core,this._core.archivedThreadIds[e]),subscribe:t=>this._core.subscribe(t)}),this._core)}getItemById(e){return new zr(new rt({path:{ref:`threadItems[threadId=${e}]`,threadSelector:{type:"threadId",threadId:e}},getState:()=>qr(this._core,e),subscribe:t=>this._core.subscribe(t)}),this._core)}},sd=e=>e.startsWith("image/")?"image":e.startsWith("text/")?"document":"file",od=class{constructor(e){C(this,"accept","*");C(this,"uploadedUrls",new Map);this.cloud=e}add(t){return Nr(this,arguments,function*({file:e}){const r=crypto.randomUUID(),n=sd(e.type);let a={id:r,type:n,name:e.name,contentType:e.type,file:e,status:{type:"running",reason:"uploading",progress:0}};yield a;try{const{signedUrl:i,publicUrl:s}=yield new Ee(this.cloud.files.generatePresignedUploadUrl({filename:e.name}));yield new Ee(fetch(i,{method:"PUT",body:e,headers:{"Content-Type":e.type},mode:"cors"})),this.uploadedUrls.set(r,s),a=E(m({},a),{status:{type:"requires-action",reason:"composer-send"}}),yield a}catch(i){a=E(m({},a),{status:{type:"incomplete",reason:"error"}}),yield a}})}remove(e){return P(this,null,function*(){this.uploadedUrls.delete(e.id)})}send(e){return P(this,null,function*(){const t=this.uploadedUrls.get(e.id);if(!t)throw new Error("Attachment not uploaded");this.uploadedUrls.delete(e.id);let r;return e.type==="image"?r=[{type:"image",image:t,filename:e.name}]:r=[{type:"file",data:t,mimeType:e.contentType,filename:e.name}],E(m({},e),{status:{type:"complete"},content:r})})}},Fn=y.createContext(null),Bn=({adapters:e,children:t})=>{const r=y.useContext(Fn);return p.jsx(Fn.Provider,{value:m(m({},r),e),children:t})},ld=()=>y.useContext(Fn),ud=class extends hi{constructor(t,r,{parentId:n,message:a}){var i;super();C(this,"_nonTextParts");C(this,"_previousText");C(this,"_parentId");C(this,"_sourceId");this.runtime=t,this.endEditCallback=r,this._parentId=n,this._sourceId=a.id,this._previousText=jr(a),this.setText(this._previousText),this.setRole(a.role),this.setAttachments((i=a.attachments)!=null?i:[]),this._nonTextParts=a.content.filter(s=>s.type!=="text"),this.setRunConfig(m({},t.composer.runConfig))}get canCancel(){return!0}getAttachmentAdapter(){var t;return(t=this.runtime.adapters)==null?void 0:t.attachments}handleSend(t){return P(this,null,function*(){jr(t)!==this._previousText&&this.runtime.append(E(m({},t),{content:[...t.content,...this._nonTextParts],parentId:this._parentId,sourceId:this._sourceId})),this.handleCancel()})}handleCancel(){this.endEditCallback(),this._notifySubscribers()}},cd=class{constructor(e){C(this,"_subscriptions",new Set);C(this,"_isInitialized",!1);C(this,"repository",new Ii);C(this,"composer",new fi(this));C(this,"_editComposers",new Map);C(this,"_stopSpeaking");C(this,"speech");C(this,"_eventSubscribers",new Map);this._contextProvider=e}get messages(){return this.repository.getMessages()}get state(){var t;let e;for(const r of this.messages)if(r.role==="assistant"){e=r;break}return(t=e==null?void 0:e.metadata.unstable_state)!=null?t:null}getModelContext(){return this._contextProvider.getModelContext()}getEditComposer(e){return this._editComposers.get(e)}beginEdit(e){if(this._editComposers.has(e))throw new Error("Edit already in progress");this._editComposers.set(e,new ud(this,()=>this._editComposers.delete(e),this.repository.getMessage(e))),this._notifySubscribers()}getMessageById(e){try{return this.repository.getMessage(e)}catch(t){return}}getBranches(e){return this.repository.getBranches(e)}switchToBranch(e){this.repository.switchToBranch(e),this._notifySubscribers()}_notifySubscribers(){for(const e of this._subscriptions)e()}_notifyEventSubscribers(e){const t=this._eventSubscribers.get(e);if(t)for(const r of t)r()}subscribe(e){return this._subscriptions.add(e),()=>this._subscriptions.delete(e)}submitFeedback({messageId:e,type:t}){var i;const r=(i=this.adapters)==null?void 0:i.feedback;if(!r)throw new Error("Feedback adapter not configured");const{message:n,parentId:a}=this.repository.getMessage(e);if(r.submit({message:n,type:t}),n.role==="assistant"){const s=E(m({},n),{metadata:E(m({},n.metadata),{submittedFeedback:{type:t}})});this.repository.addOrUpdateMessage(a,s)}this._notifySubscribers()}speak(e){var i,s;const t=(i=this.adapters)==null?void 0:i.speech;if(!t)throw new Error("Speech adapter not configured");const{message:r}=this.repository.getMessage(e);(s=this._stopSpeaking)==null||s.call(this);const n=t.speak(jr(r)),a=n.subscribe(()=>{n.status.type==="ended"?(this._stopSpeaking=void 0,this.speech=void 0):this.speech={messageId:e,status:n.status},this._notifySubscribers()});this.speech={messageId:e,status:n.status},this._notifySubscribers(),this._stopSpeaking=()=>{n.cancel(),a(),this.speech=void 0,this._stopSpeaking=void 0}}stopSpeaking(){if(!this._stopSpeaking)throw new Error("No message is being spoken");this._stopSpeaking(),this._notifySubscribers()}ensureInitialized(){this._isInitialized||(this._isInitialized=!0,this._notifyEventSubscribers("initialize"))}export(){return this.repository.export()}import(e){this.ensureInitialized(),this.repository.clear(),this.repository.import(e),this._notifySubscribers()}reset(e){this.import(Dn.fromArray(e!=null?e:[]))}unstable_on(e,t){var n,a,i;if(e==="model-context-update")return(i=(a=(n=this._contextProvider).subscribe)==null?void 0:a.call(n,t))!=null?i:(()=>{});const r=this._eventSubscribers.get(e);return r?r.add(t):this._eventSubscribers.set(e,new Set([t])),()=>{this._eventSubscribers.get(e).delete(t)}}},dd=e=>{try{return JSON.parse(e),!0}catch(t){return!1}};function hd({state:e,getTools:t,onResult:r,setToolStatuses:n}){const a=y.useRef({}),i=y.useRef(new Map),s=y.useRef(new AbortController),o=y.useRef(0),l=y.useRef([]),[u]=y.useState(()=>{const[f,g]=Ci(),v=Xc(t,()=>{var b,w;return(w=(b=s.current)==null?void 0:b.signal)!=null?w:new AbortController().signal},(b,w)=>new Promise((_,T)=>{const B=i.current.get(b);B&&B.reject(new Error("Human input request was superseded by a new request")),i.current.set(b,{resolve:_,reject:T}),n(j=>E(m({},j),{[b]:{type:"interrupt",payload:{type:"human",payload:w}}}))}),{onExecutionStart:b=>{o.current++,n(w=>E(m({},w),{[b]:{type:"executing"}}))},onExecutionEnd:b=>{o.current--,n(w=>{const _=m({},w);return delete _[b],_}),o.current===0&&(l.current.forEach(w=>w()),l.current=[])}});return f.pipeThrough(v).pipeThrough(new _i).pipeTo(new WritableStream({write(b){var w;if(b.type==="result"){if((w=a.current[b.meta.toolCallId])!=null&&w.hasResult)return;r(m({type:"add-tool-result",toolCallId:b.meta.toolCallId,toolName:b.meta.toolName,result:b.result,isError:b.isError},b.artifact&&{artifact:b.artifact}))}}})),g}),d=y.useRef(new Set),c=y.useRef(!0);y.useEffect(()=>{const f=g=>{g.forEach(v=>{v.content.forEach(b=>{if(b.type==="tool-call"){if(c.current)d.current.add(b.toolCallId);else{if(d.current.has(b.toolCallId))return;let w=a.current[b.toolCallId];if(w||(w={argsText:"",hasResult:!1,argsComplete:!1,controller:u.addToolCallPart({toolName:b.toolName,toolCallId:b.toolCallId})},a.current[b.toolCallId]=w),b.argsText!==w.argsText)if(w.argsComplete)process.env.NODE_ENV!=="production"&&console.warn("argsText updated after controller was closed:",{previous:w.argsText,next:b.argsText});else{if(!b.argsText.startsWith(w.argsText))throw new Error(`Tool call argsText can only be appended, not updated: ${b.argsText} does not start with ${w.argsText}`);const _=b.argsText.slice(w.argsText.length);w.controller.argsText.append(_);const T=dd(b.argsText);T&&w.controller.argsText.close(),a.current[b.toolCallId]={argsText:b.argsText,hasResult:w.hasResult,argsComplete:T,controller:w.controller}}b.result!==void 0&&!w.hasResult&&(w.controller.setResponse(new gt({result:b.result,artifact:b.artifact,isError:b.isError})),w.controller.close(),a.current[b.toolCallId]={hasResult:!0,argsComplete:!0,argsText:w.argsText,controller:w.controller})}b.messages&&f(b.messages)}})})};f(e.messages),c.current&&(c.current=!1)},[e,u,r]);const h=()=>(i.current.forEach(({reject:f})=>{f(new Error("Tool execution aborted"))}),i.current.clear(),s.current.abort(),s.current=new AbortController,o.current===0?Promise.resolve():new Promise(f=>{l.current.push(f)}));return{reset:()=>{h(),c.current=!0},abort:h,resume:(f,g)=>{const v=i.current.get(f);if(v)i.current.delete(f),n(b=>E(m({},b),{[f]:{type:"executing"}})),v.resolve(g);else throw new Error(`Tool call ${f} is not waiting for human input`)}}}var fd=class{list(){return Promise.resolve({threads:[]})}rename(){return Promise.resolve()}archive(){return Promise.resolve()}unarchive(){return Promise.resolve()}delete(){return Promise.resolve()}initialize(e){return Promise.resolve({remoteId:e,externalId:void 0})}generateTitle(){return Promise.resolve(new ReadableStream)}fetch(e){return Promise.reject(new Error("Thread not found"))}};function pd(e,t){e.commitTasks.forEach(r=>{const n=r.cellIndex,a=t.cells[n];if(a.type!=="effect")throw new Error("Cannot find effect cell");let i=!0;if(a.deps!==void 0&&r.deps!==void 0&&(i=a.deps.length!==r.deps.length||a.deps.some((s,o)=>!Object.is(s,r.deps[o]))),i){if(a.mounted){if(typeof a.deps!=typeof r.deps)throw new Error("tapEffect called with and without dependencies across re-renders");try{a.mounted&&a.cleanup&&a.cleanup()}finally{a.mounted=!1}}try{const s=r.effect();if(s!==void 0&&typeof s!="function")throw new Error(`An effect function must either return a cleanup function or nothing. Received: ${typeof s}`);a.mounted=!0,a.cleanup=typeof s=="function"?s:void 0,a.deps=r.deps}catch(s){throw s}}})}function md(e){let t=null;for(let r=e.cells.length-1;r>=0;r--){const n=e.cells[r];if((n==null?void 0:n.type)==="effect"&&n.mounted&&n.cleanup)try{n.cleanup()}catch(a){t==null&&(t=a)}finally{n.mounted=!1}}if(t!=null)throw t}var lr=null;function gd(e,t){e.currentIndex=0;const r=lr;lr=e;try{if(t(),e.isFirstRender=!1,e.cells.length!==e.currentIndex)throw new Error(`Rendered ${e.currentIndex} hooks but expected ${e.cells.length}. Hooks must be called in the exact same order in every render.`)}finally{lr=r}}function zn(){if(!lr)throw new Error("No resource fiber available");return lr}function Ui(e,t){const r=e[Hi];if(!r)throw new Error("ResourceElement.type is not a valid Resource");return r(t)}var Hi=Symbol("fnSymbol");function Vr(e,t){return{resource:e,scheduleRerender:t,cells:[],currentIndex:0,renderContext:void 0,isFirstRender:!0,isMounted:!1,isNeverMounted:!0}}function zt(e){e.isMounted=!1,md(e)}function ur(e,t){const r={commitTasks:[],props:t,state:void 0};return gd(e,()=>{e.renderContext=r;try{r.state=Ui(e.resource,t)}finally{e.renderContext=void 0}}),r}function Rt(e,t){e.isMounted=!0,e.isNeverMounted=!1,pd(t,e)}var yd=globalThis.__ASSISTANT_UI_DISABLE_LAYOUT_EFFECT__===!0,qi=yd?y.useEffect:y.useLayoutEffect;function Rn(e){const[,t]=y.useState({}),r=y.useMemo(()=>Vr(e.type,()=>t({})),[e.type,t]),n=ur(r,e.props);return qi(()=>()=>zt(r),[]),qi(()=>{Rt(r,n)}),n.state}var jt=e=>typeof e=="string"?{scope:e.split(".")[0],event:e}:{scope:e.scope,event:e.event},Ct=(e,t,r)=>t===e,$t,jn=()=>{if($t)return $t;const e=()=>({apis:new Map,nextId:0,listeners:new Set});if(typeof window=="undefined")return $t=e(),$t;const t=window.__ASSISTANT_UI_DEVTOOLS_HOOK__;if(t)return $t=t,t;const r=e();return window.__ASSISTANT_UI_DEVTOOLS_HOOK__=r,$t=r,r},bd=(st=class{static register(t){var o,l;const r=jn();for(const u of r.apis.values())if(u.api===t)return()=>{};const n=r.nextId++,a={api:t,logs:[]},i=(o=t.on)==null?void 0:o.call(t,"*",u=>{const d=r.apis.get(n);d&&(d.logs.push({time:new Date,event:u.event,data:u.payload}),d.logs.length>st.MAX_EVENT_LOGS_PER_API&&(d.logs=d.logs.slice(-200)),st.notifyListeners(n))}),s=(l=t.subscribe)==null?void 0:l.call(t,()=>{st.notifyListeners(n)});return r.apis.set(n,a),st.notifyListeners(n),()=>{const u=jn();u.apis.get(n)&&(i==null||i(),s==null||s(),u.apis.delete(n),st.notifyListeners(n))}}static notifyListeners(t){jn().listeners.forEach(n=>n(t))}},C(st,"MAX_EVENT_LOGS_PER_API",200),st);function ge(e){const t=(r,n)=>m({type:t,props:r},(n==null?void 0:n.key)!==void 0&&{key:n.key});return t[Hi]=e,t}var wd=e=>{if(e.renderContext)throw new Error("Resource updated during render");if(e.isNeverMounted)throw new Error("Resource updated before mount");e.isMounted&&e.scheduleRerender()};function xd(e){const t=zn(),r=t.currentIndex++;if(!t.isFirstRender&&r>=t.cells.length)throw new Error("Rendered more hooks than during the previous render. Hooks must be called in the exact same order in every render.");if(!t.cells[r]){const i={type:"state",value:typeof e=="function"?e():e,set:s=>{const o=i.value,l=typeof s=="function"?s(o):s;Object.is(o,l)||(i.value=l,wd(t))}};t.cells[r]=i}const n=t.cells[r];if(n.type!=="state")throw new Error("Hook order changed between renders");return n}function lt(e){const t=xd(e);return[t.value,t.set]}function vd(){const e=zn(),t=e.currentIndex++;if(!e.isFirstRender&&t>=e.cells.length)throw new Error("Rendered more hooks than during the previous render. Hooks must be called in the exact same order in every render.");if(!e.cells[t]){const n={type:"effect",mounted:!1};e.cells[t]=n}if(e.cells[t].type!=="effect")throw new Error("Hook order changed between renders");return t}function Oe(e,t){const r=zn(),n=vd();r.renderContext.commitTasks.push({effect:e,deps:t,cellIndex:n})}function Ut(e){const[t]=lt(()=>({current:e}));return t}var kd=(e,t)=>{if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Object.is(e[r],t[r]))return!1;return!0},ue=(e,t)=>{const r=Ut();return r.current||(r.current={value:e(),deps:t}),kd(r.current.deps,t)||(r.current.value=e(),r.current.deps=t),r.current.value};function Wr(e,t){const[r,n]=lt({}),a=ue(()=>Vr(e.type,()=>n({})),[e.type]),i=t?ue(()=>e.props,t):e.props,s=ue(()=>ur(a,i),[a,i,r]);return Oe(()=>()=>zt(a),[a]),Oe(()=>{Rt(a,s)},[a,s]),s.state}function nt(e){return Ui(e.type,e.props)}function Vi(e){const t=new Set;e.forEach((o,l)=>{if(o.key===void 0)throw new Error(`tapResources: All resource elements must have a key. Element at index ${l} is missing a key.`);if(t.has(o.key))throw new Error(`tapResources: Duplicate key "${o.key}" found. All keys must be unique.`);t.add(o.key)});const[r,n]=lt({}),a=ue(()=>new Map(e.map(o=>[o.key,o])),[e]),[i]=lt(()=>new Map),s=ue(()=>{const o=new Map,l=new Set;return a.forEach((u,d)=>{l.add(d);let c=i.get(d);(!c||c.resource!==u.type)&&(c&&zt(c),c=Vr(u.type,()=>n({})),i.set(d,c));const h=ur(c,u.props);o.set(d,h)}),i.forEach((u,d)=>{l.has(d)||(zt(u),i.delete(d))}),o},[a,r]);return Oe(()=>{s.forEach((o,l)=>{const u=i.get(l);u&&Rt(u,o)})},[s,i]),Oe(()=>()=>{i.forEach(o=>{zt(o)}),i.clear()},[i]),ue(()=>e.map(o=>{var l;return(l=s.get(o.key))==null?void 0:l.state}),[e,s])}var $n=[],Un=!1;function Sd(){Un=!1;const e=$n;$n=[];for(const t of e)try{t()}catch(r){console.error("Error in scheduled task:",r)}}function _d(e){$n.push(e),Un||(Un=!0,queueMicrotask(Sd))}var Td=(Lt=class{constructor(t){C(this,"_isDirty",!1);C(this,"_hasScheduledTask",!1);C(this,"_isFlushing",!1);this._task=t}get isDirty(){return this._isDirty}markDirty(){this._isDirty=!0,!(this._hasScheduledTask||this._isFlushing)&&(this._hasScheduledTask=!0,_d(()=>{this._hasScheduledTask=!1,this.flushSync()}))}flushSync(){if(this._isFlushing)return;this._isFlushing=!0;let t=0;try{for(;this._isDirty;){if(t++,t>Lt.MAX_FLUSH_DEPTH)throw new Error("Maximum update depth exceeded. This can happen when a resource repeatedly calls setState inside tapEffect.");this._isDirty=!1,this._task()}}finally{this._isFlushing=!1}}},C(Lt,"MAX_FLUSH_DEPTH",50),Lt),Cd=ge(({element:e,onUpdateInput:t,onFlushSync:r,onDispose:n})=>{const[a,i]=lt(e.props),s=nt({type:e.type,props:a}),o=Ut(new Set).current,l=Ut(s);return Oe(()=>{s!==l.current&&(l.current=s,o.forEach(d=>d()))}),ue(()=>({getState:()=>l.current,subscribe:d=>(o.add(d),()=>o.delete(d)),updateInput:d=>{t(),i(()=>d)},flushSync:r,dispose:n}),[])}),Id=(e,t=!1)=>{let r=!t;const n={element:e,onUpdateInput:()=>{r||(r=!0,Rt(i,s))},onFlushSync:()=>{a.flushSync()},onDispose:()=>zt(i)},a=new Td(()=>{s=ur(i,n),r&&Rt(i,s)}),i=Vr(Cd,()=>a.markDirty());let s=ur(i,n);return r&&Rt(i,s),s.state},cr=Symbol("tap.Context"),Wi=e=>({[cr]:e}),Ji=(e,t,r)=>{const n=e[cr];e[cr]=t;try{return r()}finally{e[cr]=n}},Yi=e=>e[cr];const Ki=e=>{let t;const r=new Set,n=(u,d)=>{const c=typeof u=="function"?u(t):u;if(!Object.is(c,t)){const h=t;t=(d!=null?d:typeof c!="object"||c===null)?c:Object.assign({},t,c),r.forEach(f=>f(t,h))}},a=()=>t,o={setState:n,getState:a,getInitialState:()=>l,subscribe:u=>(r.add(u),()=>r.delete(u))},l=t=e(n,a,o);return o},Ed=(e=>e?Ki(e):Ki),Ad=e=>e;function Md(e,t=Ad){const r=y.useSyncExternalStore(e.subscribe,y.useCallback(()=>t(e.getState()),[e,t]),y.useCallback(()=>t(e.getInitialState()),[e,t]));return y.useDebugValue(r),r}const Gi=e=>{const t=Ed(e),r=n=>Md(t,n);return Object.assign(r,t),r},Ht=(e=>e?Gi(e):Gi);function Xi(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function Qi(...e){return t=>{let r=!1;const n=e.map(a=>{const i=Xi(a,t);return!r&&typeof i=="function"&&(r=!0),i});if(r)return()=>{for(let a=0;a<n.length;a++){const i=n[a];typeof i=="function"?i():Xi(e[a],null)}}}}function Jr(...e){return K.useCallback(Qi(...e),e)}var Zi=ge(e=>{const t=ue(()=>Id(e,!0),[e.type]);return Oe(()=>{t.updateInput(e.props)}),t}),Pd=class{constructor(e){this.getApi=e}get(e,t){return this.getApi()[t]}ownKeys(){return Object.keys(this.getApi())}has(e,t){return t in this.getApi()}getOwnPropertyDescriptor(e,t){return Object.getOwnPropertyDescriptor(this.getApi(),t)}set(){return!1}defineProperty(){return!1}deleteProperty(){return!1}},at=(e,t)=>{const r=Ut(e);Oe(()=>{r.current=e});const n=ue(()=>new Proxy({},new Pd(()=>r.current)),[]),a=t==null?void 0:t.key,i=e.getState();return ue(()=>({key:a,state:i,api:n}),[i,a])},yt=ge(e=>{const t=Ut(e.get);return Oe(()=>{t.current=e.get}),ue(()=>Ae({source:e.source,query:e.query,get:()=>t.current()}),[e.source,JSON.stringify(e.query)])}),Nd=ge(e=>{const t=Wr(e.scopeElement);return ue(()=>[e.fieldName,t],[e.fieldName,t])}),Ld=ge(e=>{const o=e,{on:t,subscribe:r,flushSync:n}=o,a=V(o,["on","subscribe","flushSync"]),i=Ut({on:t,subscribe:r,flushSync:n});Oe(()=>{i.current={on:t,subscribe:r,flushSync:n}});const s=Vi(Object.entries(a).map(([l,u])=>Nd({fieldName:l,scopeElement:u},{key:l})));return ue(()=>{const l=Object.fromEntries(s),{on:u,subscribe:d,flushSync:c}=i.current;return u&&(l.on=(h,f)=>u(h,f)),d&&(l.subscribe=h=>d(h)),c&&(l.flushSync=()=>c()),l},[...s])}),es=Wi(null),Dd=(e,t)=>Ji(es,e,t),ts=()=>{const e=Yi(es);if(!e)throw new Error("Model context is not available in this context");return e},Od=ge(({toolkit:e})=>{const[t,r]=lt(()=>({tools:{}})),n=ts();Oe(()=>{if(!e)return;const i=[];for(const[l,u]of Object.entries(e))u.render&&i.push(a(l,u.render));const s=Object.entries(e).reduce((l,[u,d])=>{const f=d,{render:c}=f,h=V(f,["render"]);return l[u]=h,l},{}),o={getModelContext:()=>({tools:s})};return i.push(n.register(o)),()=>{i.forEach(l=>l())}},[e,n]);const a=(i,s)=>(r(o=>{var l;return E(m({},o),{tools:E(m({},o.tools),{[i]:[...(l=o.tools[i])!=null?l:[],s]})})}),()=>{r(o=>{var l,u;return E(m({},o),{tools:E(m({},o.tools),{[i]:(u=(l=o.tools[i])==null?void 0:l.filter(d=>d!==s))!=null?u:[]})})})});return at({getState:()=>t,setToolUI:a})}),Fd=ge(()=>ue(()=>{const t=new Map;return{on:(r,n)=>{t.has(r)||t.set(r,new Set);const a=t.get(r);return a.add(n),()=>{a.delete(n),a.size===0&&t.delete(r)}},emit:(r,n)=>{const a=t.get(r),i=t.get("*");!a&&!i||queueMicrotask(()=>{if(a)for(const s of a)s(n);if(i)for(const s of i)s({event:r,payload:n})})}}},[])),rs=Wi(null),Bd=(e,t)=>Ji(rs,e,t),Hn=()=>{const e=Yi(rs);if(!e)throw new Error("Events context is not available");return e},zd=ge(()=>{const[e]=lt(()=>({})),t=new En;return at({getState:()=>e,getModelContext:()=>t.getModelContext(),subscribe:r=>t.subscribe(r),register:r=>t.registerModelContextProvider(r)})}),Rd=ge(({threads:e,modelContext:t,tools:r})=>{const n=nt(Fd()),{threads:a,tools:i,modelContext:s}=Bd(n,()=>{const l=Wr(t!=null?t:zd(),[t]);return Dd(l.api,()=>({modelContext:l,tools:Wr(r!=null?r:Od({}),[r]),threads:Wr(e,[e])}))}),o=ue(()=>({threads:a.state,tools:i.state,modelContext:s.state}),[a.state,i.state,s.state]);return at({getState:()=>o,threads:a.api,tools:i.api,modelContext:s.api,on:n.on})}),jd=e=>{const t=()=>e.getState().api.threads.item("main");return{threads:Ae({source:"root",query:{},get:()=>e.getState().api.threads}),tools:Ae({source:"root",query:{},get:()=>e.getState().api.tools}),modelContext:Ae({source:"root",query:{},get:()=>e.getState().api.modelContext}),thread:Ae({source:"threads",query:{type:"main"},get:()=>e.getState().api.threads.thread("main")}),threadListItem:Ae({source:"threads",query:{type:"main"},get:()=>t()}),composer:Ae({source:"thread",query:{},get:()=>e.getState().api.threads.thread("main").composer}),on(r,n){const{event:a,scope:i}=jt(r);if(i==="*")return e.getState().api.on(a,n);if(Ct("thread",i)||Ct("thread-list-item",i)||Ct("composer",i))return e.getState().api.on(a,s=>{s.threadId===t().getState().id&&n(s)});throw new Error(`Event scope is not available in this component: ${i}`)},subscribe:e.subscribe,flushSync:e.flushSync}},$d=e=>{const t=Yr(),r=Rn(Zi(Rd(e))),n=y.useMemo(()=>jd(r),[r]);return y.useMemo(()=>as(t,n),[t,n])},Ae=e=>{const t=e.get;return t.source=e.source,t.query=e.query,t},bt=()=>()=>{},ns=y.createContext({threads:Ae({source:null,query:{},get:()=>{throw new Error("Threads is only available inside <AssistantProvider />")}}),tools:Ae({source:null,query:{},get:()=>{throw new Error("Tools is only available inside <AssistantProvider />")}}),modelContext:Ae({source:null,query:{},get:()=>{throw new Error("ModelContext is only available inside <AssistantProvider />")}}),threadListItem:Ae({source:null,query:{},get:()=>{throw new Error("ThreadListItem is only available inside <AssistantProvider />")}}),thread:Ae({source:null,query:{},get:()=>{throw new Error("Thread is only available inside <AssistantProvider />")}}),composer:Ae({source:null,query:{},get:()=>{throw new Error("Composer is only available inside <AssistantProvider />")}}),message:Ae({source:null,query:{},get:()=>{throw new Error("Message is only available inside <ThreadPrimitive.Messages />")}}),part:Ae({source:null,query:{},get:()=>{throw new Error("Part is only available inside <MessagePrimitive.Parts />")}}),attachment:Ae({source:null,query:{},get:()=>{throw new Error("Attachment is only available inside <MessagePrimitive.Attachments /> or <ComposerPrimitive.Attachments />")}}),subscribe:bt,flushSync:bt,on:e=>{const{scope:t}=jt(e);throw new Error(`Event scope is not available in this component: ${t}`)}}),Yr=()=>y.useContext(ns),It=e=>{const t=Yr(),r=Rn(Ld(e));return y.useMemo(()=>as(t,r),[t,r])},Ud=e=>$d(e);function pe(e){return e?Ud(e):Yr()}var Hd=(e,t)=>e===bt?t:t===bt?e:(...r)=>{e(...r),t(...r)},qd=(e,t)=>e===bt?t:t===bt?e:(...r)=>{const n=e(...r),a=t(...r);return()=>{n(),a()}},as=(e,t)=>{const r=t.subscribe,n=t.flushSync;return E(m(m({},e),t),{subscribe:qd(e.subscribe,r!=null?r:bt),flushSync:Hd(e.flushSync,n!=null?n:bt)})},wt=({api:e,children:t,devToolsVisible:r=!0})=>(y.useEffect(()=>{if(!(!r||!e.subscribe))return bd.register(e)},[e,r]),p.jsx(ns.Provider,{value:e,children:t})),is=(Tu=class{constructor(e){er(this,Ze);tr(this,Ze,e)}get threads(){return Ge(this,Ze).threads().getState()}get tools(){return Ge(this,Ze).tools().getState()}get threadListItem(){return Ge(this,Ze).threadListItem().getState()}get thread(){return Ge(this,Ze).thread().getState()}get composer(){return Ge(this,Ze).composer().getState()}get message(){return Ge(this,Ze).message().getState()}get part(){return Ge(this,Ze).part().getState()}get attachment(){return Ge(this,Ze).attachment().getState()}},Ze=new WeakMap,Tu),ae=e=>{const t=pe(),r=y.useMemo(()=>new is(t),[t]),n=y.useSyncExternalStore(t.subscribe,()=>e(r),()=>e(r));if(y.useDebugValue(n),n instanceof is)throw new Error("You tried to return the entire AssistantState. This is not supported due to technical limitations.");return n},qn=(e,t)=>{const r=pe(),n=y.useRef(t);y.useEffect(()=>{n.current=t});const{scope:a,event:i}=jt(e);y.useEffect(()=>r.on({scope:a,event:i},s=>n.current(s)),[r,a,i])};function Vd(e,t){function r(n){const a=y.useContext(e);if(!(n!=null&&n.optional)&&!a)throw new Error(`This component must be used within ${t}.`);return a}return r}function ss(e,t){function r(a){const i=e(a);return i?i[t]:null}function n(a){let i=!1,s;typeof a=="function"?s=a:a&&typeof a=="object"&&(i=!!a.optional,s=a.selector);const o=r({optional:i});return o?s?o(s):o():null}return{[t]:n,[`${t}Store`]:r}}var os=y.createContext(null),Wd=Vd(os,"ThreadPrimitive.Viewport"),{useThreadViewport:Kr,useThreadViewportStore:Vn}=ss(Wd,"useThreadViewport"),Jd=e=>{var r;const t=e;t.__isBound||((r=t.__internal_bindMethods)==null||r.call(t),t.__isBound=!0)};function Yd(e,t=Kd){Jd(e);const r=y.useSyncExternalStore(e.subscribe,()=>t(e.getState()),()=>t(e.getState()));return y.useDebugValue(r),r}var Kd=e=>e;function ls(e){function t(r){let n=!1,a;typeof r=="function"?a=r:r&&(n=!!r.optional,a=r.selector);const i=e({optional:n});return i?Yd(i,a):null}return t}function us(e){const t=pe(),r=ae(()=>{var n,a,i;return t.thread.source&&(i=(a=(n=t.thread()).__internal_getRuntime)==null?void 0:a.call(n))!=null?i:null});if(!r&&!(e!=null&&e.optional))throw new Error("ThreadRuntime is not available");return r}var Gd=ls(us);function Xd(e){const t=pe(),r=ae(()=>{var n,a,i;return t.threadListItem.source&&(i=(a=(n=t.threadListItem()).__internal_getRuntime)==null?void 0:a.call(n))!=null?i:null});if(!r&&!(e!=null&&e.optional))throw new Error("ThreadListItemRuntime is not available");return r}var cs=ls(Xd),Et=e=>{const[,t]=lt(e.getState);return Oe(()=>(t(e.getState()),e.subscribe(()=>{t(e.getState())})),[e]),e.getState()},Qd=ge(({runtime:e})=>{const t=Et(e),r=Hn();return Oe(()=>{const n=[],a=["switched-to","switched-away"];for(const i of a){const s=e.unstable_on(i,()=>{r.emit(`thread-list-item.${i}`,{threadId:e.getState().id})});n.push(s)}return()=>{for(const i of n)i()}},[e,r]),at({getState:()=>t,switchTo:e.switchTo,rename:e.rename,archive:e.archive,unarchive:e.unarchive,delete:e.delete,generateTitle:e.generateTitle,initialize:e.initialize,detach:e.detach,__internal_getRuntime:()=>e},{key:t.id})}),dr=e=>{const t=Vi(e);return{state:t.map(r=>r.state),api:r=>{var a,i;const n="index"in r?(a=t[r.index])==null?void 0:a.api:(i=t.find(s=>s.key===r.key))==null?void 0:i.api;if(!n)throw new Error(`tapLookupResources: Resource not found for lookup: ${JSON.stringify(r)}`);return n}}},ds=ge(({runtime:e})=>{const t=Et(e);return at({getState:()=>t,remove:e.remove,__internal_getRuntime:()=>e},{key:t.id})}),Zd=ge(({runtime:e,index:t})=>{const r=ue(()=>e.getAttachmentByIndex(t),[e,t]);return nt(ds({runtime:r}))}),hs=ge(({threadIdRef:e,messageIdRef:t,runtime:r})=>{var o;const n=Et(r),a=Hn();Oe(()=>{const l=[],u=["send","attachment-add"];for(const d of u){const c=r.unstable_on(d,()=>{a.emit(`composer.${d}`,m({threadId:e.current},t&&{messageId:t.current}))});l.push(c)}return()=>{for(const d of l)d()}},[r,a,e,t]);const i=dr(n.attachments.map((l,u)=>Zd({runtime:r,index:u},{key:u}))),s=ue(()=>{var l;return{text:n.text,role:n.role,attachments:i.state,runConfig:n.runConfig,isEditing:n.isEditing,canCancel:n.canCancel,attachmentAccept:n.attachmentAccept,isEmpty:n.isEmpty,type:(l=n.type)!=null?l:"thread"}},[n,i.state]);return at({getState:()=>s,setText:r.setText,setRole:r.setRole,setRunConfig:r.setRunConfig,addAttachment:r.addAttachment,reset:r.reset,clearAttachments:r.clearAttachments,send:r.send,cancel:r.cancel,beginEdit:(o=r.beginEdit)!=null?o:(()=>{throw new Error("beginEdit is not supported in this runtime")}),attachment:l=>"id"in l?i.api({key:l.id}):i.api(l),__internal_getRuntime:()=>r})}),eh=ge(({runtime:e})=>{const t=Et(e);return at({getState:()=>t,addToolResult:n=>e.addToolResult(n),resumeToolCall:n=>e.resumeToolCall(n),__internal_getRuntime:()=>e},{key:t.type==="tool-call"?`toolCallId-${t.toolCallId}`:void 0})}),th=ge(({runtime:e,index:t})=>{const r=ue(()=>e.getAttachmentByIndex(t),[e,t]);return nt(ds({runtime:r}))}),rh=ge(({runtime:e,index:t})=>{const r=ue(()=>e.getMessagePartByIndex(t),[e,t]);return nt(eh({runtime:r}))}),nh=ge(({runtime:e,threadIdRef:t})=>{var h,f;const r=Et(e),[n,a]=lt(!1),[i,s]=lt(!1),o=ue(()=>({get current(){return e.getState().id}}),[e]),l=nt(hs({runtime:e.composer,threadIdRef:t,messageIdRef:o})),u=dr(r.content.map((g,v)=>rh({runtime:e,index:v},{key:v}))),d=dr((f=(h=r.attachments)==null?void 0:h.map((g,v)=>th({runtime:e,index:v},{key:v})))!=null?f:[]),c=ue(()=>E(m({},r),{parts:u.state,composer:l.state,isCopied:n,isHovering:i}),[r,u.state,l.state,n,i]);return at({getState:()=>c,composer:l.api,reload:g=>e.reload(g),speak:()=>e.speak(),stopSpeaking:()=>e.stopSpeaking(),submitFeedback:g=>e.submitFeedback(g),switchToBranch:g=>e.switchToBranch(g),getCopyText:()=>e.unstable_getCopyText(),part:g=>"index"in g?u.api({index:g.index}):u.api({key:`toolCallId-${g.toolCallId}`}),attachment:g=>"id"in g?d.api({key:g.id}):d.api(g),setIsCopied:a,setIsHovering:s,__internal_getRuntime:()=>e},{key:r.id})}),ah=ge(({runtime:e,id:t,threadIdRef:r})=>{const n=ue(()=>e.getMessageById(t),[e,t]);return nt(nh({runtime:n,threadIdRef:r}))}),ih=ge(({runtime:e})=>{const t=Et(e),r=Hn();Oe(()=>{const o=[],l=["run-start","run-end","initialize","model-context-update"];for(const u of l){const d=e.unstable_on(u,()=>{var h;const c=((h=e.getState())==null?void 0:h.threadId)||"unknown";r.emit(`thread.${u}`,{threadId:c})});o.push(d)}return()=>{for(const u of o)u()}},[e]);const n=ue(()=>({get current(){return e.getState().threadId}}),[e]),a=nt(hs({runtime:e.composer,threadIdRef:n})),i=dr(t.messages.map(o=>ah({runtime:e,id:o.id,threadIdRef:n},{key:o.id}))),s=ue(()=>({isEmpty:i.state.length===0&&!t.isLoading,isDisabled:t.isDisabled,isLoading:t.isLoading,isRunning:t.isRunning,capabilities:t.capabilities,state:t.state,suggestions:t.suggestions,extras:t.extras,speech:t.speech,composer:a.state,messages:i.state}),[t,i,a.state]);return at({getState:()=>s,composer:a.api,append:e.append,startRun:e.startRun,unstable_resumeRun:e.unstable_resumeRun,cancelRun:e.cancelRun,getModelContext:e.getModelContext,export:e.export,import:e.import,reset:e.reset,stopSpeaking:e.stopSpeaking,startVoice:()=>P(null,null,function*(){throw new Error("startVoice is not supported in this runtime")}),stopVoice:()=>P(null,null,function*(){throw new Error("stopVoice is not supported in this runtime")}),message:o=>"id"in o?i.api({key:o.id}):i.api(o),__internal_getRuntime:()=>e})}),sh=ge(({runtime:e,id:t})=>{const r=ue(()=>e.getItemById(t),[e,t]);return nt(Qd({runtime:r}))}),oh=ge(({runtime:e,__internal_assistantRuntime:t})=>{const r=Et(e),n=nt(ih({runtime:e.main})),a=dr(Object.keys(r.threadItems).map(s=>sh({runtime:e,id:s},{key:s}))),i=ue(()=>{var s;return{mainThreadId:r.mainThreadId,newThreadId:(s=r.newThread)!=null?s:null,isLoading:r.isLoading,threadIds:r.threads,archivedThreadIds:r.archivedThreads,threadItems:a.state,main:n.state}},[r,a.state,n.state]);return at({getState:()=>i,thread:()=>n.api,item:s=>{if(s==="main")return a.api({key:i.mainThreadId});if("id"in s)return a.api({key:s.id});const{index:o,archived:l=!1}=s,u=l?i.archivedThreadIds[o]:i.threadIds[o];return a.api({key:u})},switchToThread:s=>{e.switchToThread(s)},switchToNewThread:()=>{e.switchToNewThread()},__internal_getAssistantRuntime:()=>t})}),lh=ge(e=>{const t=ts();return Oe(()=>e.registerModelContextProvider(t),[e,t]),nt(oh({runtime:e.threads,__internal_assistantRuntime:e}))}),Wn=e=>{const t=new Map,r=()=>{let n=0;for(const a of t.values())n+=a;e(n)};return{register:()=>{const n=Symbol();return t.set(n,0),{setHeight:a=>{t.get(n)!==a&&(t.set(n,a),r())},unregister:()=>{t.delete(n),r()}}}}},uh=(e={})=>{const t=new Set,r=Wn(s=>{i.setState({height:E(m({},i.getState().height),{viewport:s})})}),n=Wn(s=>{i.setState({height:E(m({},i.getState().height),{inset:s})})}),a=Wn(s=>{i.setState({height:E(m({},i.getState().height),{userMessage:s})})}),i=Ht(()=>{var s;return{isAtBottom:!0,scrollToBottom:({behavior:o="auto"}={})=>{for(const l of t)l({behavior:o})},onScrollToBottom:o=>(t.add(o),()=>{t.delete(o)}),turnAnchor:(s=e.turnAnchor)!=null?s:"bottom",height:{viewport:0,inset:0,userMessage:0},registerViewport:r.register,registerContentInset:n.register,registerUserMessageHeight:a.register}});return i},hr=e=>e,ch=e=>{const t=Vn({optional:!0}),[r]=y.useState(()=>uh(e));return y.useEffect(()=>t==null?void 0:t.getState().onScrollToBottom(()=>{r.getState().scrollToBottom()}),[t,r]),y.useEffect(()=>{if(t)return r.subscribe(n=>{t.getState().isAtBottom!==n.isAtBottom&&hr(t).setState({isAtBottom:n.isAtBottom})})},[r,t]),y.useEffect(()=>{var i;const n={turnAnchor:(i=e.turnAnchor)!=null?i:"bottom"};r.getState().turnAnchor!==n.turnAnchor&&hr(r).setState(n)},[r,e.turnAnchor]),r},fs=({children:e,options:t={}})=>{const r=ch(t),[n]=y.useState(()=>({useThreadViewport:r}));return p.jsx(os.Provider,{value:n,children:e})},dh=e=>{var t;return(t=e._core)==null?void 0:t.RenderComponent},hh=({children:e,runtime:t})=>{const r=pe({threads:lh(t)}),n=dh(t);return p.jsxs(wt,{api:r,children:[n&&p.jsx(n,{}),p.jsx(fs,{children:e})]})},ps=y.memo(hh),fh=({index:e,archived:t,children:r})=>{const n=pe(),a=It({threadListItem:yt({source:"threads",query:{type:"index",index:e,archived:t},get:()=>n.threads().item({index:e,archived:t})}),on(i,s){const o=()=>n.threads().item({index:e,archived:t}),{event:l,scope:u}=jt(i);return Ct("thread-list-item",u)?n.on({scope:"*",event:l},d=>{d.threadId===o().getState().id&&s(d)}):n.on(i,s)}});return p.jsx(wt,{api:a,children:r})},ph=({id:e,children:t})=>{const r=pe(),n=It({threadListItem:yt({source:"threads",query:{type:"id",id:e},get:()=>r.threads().item({id:e})}),on(a,i){const s=()=>r.threads().item({id:e}),{event:o,scope:l}=jt(a);return Ct("thread-list-item",l)?r.on({scope:"*",event:o},u=>{u.threadId===s().getState().id&&i(u)}):r.on(a,i)}});return p.jsx(wt,{api:n,children:t})},mh=({index:e,children:t})=>{const r=pe(),n=It({message:yt({source:"thread",query:{type:"index",index:e},get:()=>r.thread().message({index:e})}),composer:yt({source:"message",query:{},get:()=>r.thread().message({index:e}).composer}),on(a,i){const s=()=>r.thread().message({index:e}),{event:o,scope:l}=jt(a);return!Ct("composer",l)&&!Ct("message",l)?r.on(a,i):r.on({scope:"thread",event:o},u=>{u.messageId===s().getState().id&&i(u)})}});return p.jsx(wt,{api:n,children:t})},gh=({index:e,children:t})=>{const r=pe(),n=It({part:yt({source:"message",query:{type:"index",index:e},get:()=>r.message().part({index:e})})});return p.jsx(wt,{api:n,children:t})},yh=({index:e,children:t})=>{const r=pe(),n=It({attachment:yt({source:"message",query:{type:"index",index:e},get:()=>r.message().attachment({index:e})})});return p.jsx(wt,{api:n,children:t})},bh=({index:e,children:t})=>{const r=pe(),n=It({attachment:yt({source:"composer",query:{type:"index",index:e},get:()=>r.composer().attachment({index:e})})});return p.jsx(wt,{api:n,children:t})},wh=ge(({text:e,isRunning:t})=>{const r=ue(()=>({type:"text",text:e,status:t?{type:"running"}:{type:"complete"}}),[e,t]);return at({getState:()=>r,addToolResult:()=>{throw new Error("Not supported")},resumeToolCall:()=>{throw new Error("Not supported")}})}),xh=({text:e,isRunning:t=!1,children:r})=>{const n=Rn(Zi(wh({text:e,isRunning:t}))),a=It({part:yt({source:"root",query:{},get:()=>n.getState().api}),subscribe:n.subscribe,flushSync:n.flushSync});return p.jsx(wt,{api:a,children:r})},ms=(e,t)=>{var r,n;return t===void 0?((r=e.status)==null?void 0:r.type)==="requires-action"&&e.status.reason==="tool-calls"&&e.content.every(a=>a.type!=="tool-call"||!!a.result):((n=e.status)==null?void 0:n.type)==="requires-action"&&e.status.reason==="tool-calls"&&e.content.every(a=>a.type!=="tool-call"||!!a.result||!t.includes(a.toolName))},Jn=class extends Error{constructor(t,r){super(r);C(this,"name","AbortError");C(this,"detach");this.detach=t}},vh=class extends cd{constructor(t,r){super(t);C(this,"capabilities",{switchToBranch:!0,switchBranchDuringRun:!0,edit:!0,reload:!0,cancel:!0,unstable_copy:!0,speech:!1,attachments:!1,feedback:!1});C(this,"abortController",null);C(this,"isDisabled",!1);C(this,"_isLoading",!1);C(this,"_suggestions",[]);C(this,"_suggestionsController",null);C(this,"_options");C(this,"_lastRunConfig",{});C(this,"_loadPromise");this.__internal_setOptions(r)}get isLoading(){return this._isLoading}get suggestions(){return this._suggestions}get adapters(){return this._options.adapters}get extras(){}__internal_setOptions(t){var s,o,l;if(this._options===t)return;this._options=t;let r=!1;const n=((s=t.adapters)==null?void 0:s.speech)!==void 0;this.capabilities.speech!==n&&(this.capabilities.speech=n,r=!0);const a=((o=t.adapters)==null?void 0:o.attachments)!==void 0;this.capabilities.attachments!==a&&(this.capabilities.attachments=a,r=!0);const i=((l=t.adapters)==null?void 0:l.feedback)!==void 0;this.capabilities.feedback!==i&&(this.capabilities.feedback=i,r=!0),r&&this._notifySubscribers()}__internal_load(){var r,n;if(this._loadPromise)return this._loadPromise;const t=(n=(r=this.adapters.history)==null?void 0:r.load())!=null?n:Promise.resolve(null);return this._isLoading=!0,this._notifySubscribers(),this._loadPromise=t.then(a=>{var s,o;if(!a)return;this.repository.import(a),this._notifySubscribers();const i=(o=(s=this.adapters.history)==null?void 0:s.resume)==null?void 0:o.bind(this.adapters.history);a.unstable_resume&&i&&this.startRun({parentId:this.repository.headId,sourceId:this.repository.headId,runConfig:this._lastRunConfig},i)}).finally(()=>{this._isLoading=!1,this._notifySubscribers()}),this._loadPromise}append(t){return P(this,null,function*(){var a,i,s;this.ensureInitialized();const r=sr(t,_t(),{type:"complete",reason:"unknown"});this.repository.addOrUpdateMessage(t.parentId,r),(a=this._options.adapters.history)==null||a.append(m({parentId:t.parentId,message:r},t.runConfig!==void 0&&{runConfig:t.runConfig})),((i=t.startRun)!=null?i:t.role==="user")?yield this.startRun({parentId:r.id,sourceId:t.sourceId,runConfig:(s=t.runConfig)!=null?s:{}}):(this.repository.resetHead(r.id),this._notifySubscribers())})}resumeRun(n){var a=n,{stream:t}=a,r=V(a,["stream"]);if(!t)throw new Error("You must pass a stream parameter to resume runs.");return this.startRun(r,t)}unstable_loadExternalState(){throw new Error("Runtime does not support importing external states.")}startRun(a,i){return P(this,arguments,function*({parentId:t,runConfig:r},n){var u,d,c;this.ensureInitialized();let o={id:_t(),role:"assistant",status:{type:"running"},content:[],metadata:{unstable_state:this.state,unstable_annotations:[],unstable_data:[],steps:[],custom:{}},createdAt:new Date};this._notifyEventSubscribers("run-start");try{this._suggestions=[],(u=this._suggestionsController)==null||u.abort(),this._suggestionsController=null,this._notifySubscribers();do o=yield this.performRoundtrip(t,o,r,n),n=void 0;while(ms(o,this._options.unstable_humanToolNames))}finally{this._notifyEventSubscribers("run-end")}this._suggestionsController=new AbortController;const l=this._suggestionsController.signal;if(this.adapters.suggestion&&((d=o.status)==null?void 0:d.type)!=="requires-action"){const b=(c=this.adapters.suggestion)==null?void 0:c.generate({messages:this.messages});if(Symbol.asyncIterator in b)try{for(var h=Ft(b),f,g,v;f=!(g=yield h.next()).done;f=!1){const w=g.value;if(l.aborted)break;this._suggestions=w,this._notifySubscribers()}}catch(g){v=[g]}finally{try{f&&(g=h.return)&&(yield g.call(h))}finally{if(v)throw v[0]}}else{const w=yield b;if(l.aborted)return;this._suggestions=w,this._notifySubscribers()}}})}performRoundtrip(t,r,n,a){return P(this,null,function*(){var g,v,b,w,_,T,B,j,I,N;const i=t?this.repository.getMessages(t):[];(g=this.abortController)==null||g.abort(),this.abortController=new AbortController;const s=r.content,o=(v=r.metadata)==null?void 0:v.unstable_annotations,l=(b=r.metadata)==null?void 0:b.unstable_data,u=(w=r.metadata)==null?void 0:w.steps,d=(_=r.metadata)==null?void 0:_.custom,c=M=>{var he,x,le,we,k,xe;const W=(he=M.metadata)==null?void 0:he.steps,R=W?[...u!=null?u:[],...W]:void 0,F=(x=M.metadata)==null?void 0:x.unstable_annotations,Q=(le=M.metadata)==null?void 0:le.unstable_data,se=F?[...o!=null?o:[],...F]:void 0,Ce=Q?[...l!=null?l:[],...Q]:void 0;r=m(E(m(m({},r),M.content?{content:[...s,...(we=M.content)!=null?we:[]]}:void 0),{status:(k=M.status)!=null?k:r.status}),M.metadata?{metadata:m(m(m(m(m(m({},r.metadata),M.metadata.unstable_state?{unstable_state:M.metadata.unstable_state}:void 0),se?{unstable_annotations:se}:void 0),Ce?{unstable_data:Ce}:void 0),R?{steps:R}:void 0),(xe=M.metadata)!=null&&xe.custom?{custom:m(m({},d!=null?d:{}),M.metadata.custom)}:void 0)}:void 0),this.repository.addOrUpdateMessage(t,r),this._notifySubscribers()},h=(T=this._options.maxSteps)!=null?T:2;if(((I=(j=(B=r.metadata)==null?void 0:B.steps)==null?void 0:j.length)!=null?I:0)>=h)return c({status:{type:"incomplete",reason:"tool-calls"}}),r;c({status:{type:"running"}}),this.repository.resetHead(r.id),this._notifySubscribers();try{this._lastRunConfig=n!=null?n:{};const M=this.getModelContext();a=a!=null?a:this.adapters.chatModel.run.bind(this.adapters.chatModel);const W=this.abortController.signal,R=a({messages:i,runConfig:this._lastRunConfig,abortSignal:W,context:M,config:M,unstable_assistantMessageId:r.id,unstable_getMessage(){return r}});if(Symbol.asyncIterator in R)try{for(var z=Ft(R),H,O,S;H=!(O=yield z.next()).done;H=!1){const F=O.value;if(W.aborted){c({status:{type:"incomplete",reason:"cancelled"}});break}c(F)}}catch(O){S=[O]}finally{try{H&&(O=z.return)&&(yield O.call(z))}finally{if(S)throw S[0]}}else c(yield R);r.status.type==="running"&&c({status:{type:"complete",reason:"unknown"}})}catch(M){if(M instanceof Jn)c({status:{type:"incomplete",reason:"cancelled"}});else throw c({status:{type:"incomplete",reason:"error",error:M instanceof Error?M.message:`[${typeof M}] ${new String(M).toString()}`}}),M}finally{this.abortController=null,(r.status.type==="complete"||r.status.type==="incomplete")&&(yield(N=this._options.adapters.history)==null?void 0:N.append({parentId:t,message:r,runConfig:this._lastRunConfig}))}return r})}detach(){var r;const t=new Jn(!0);(r=this.abortController)==null||r.abort(t),this.abortController=null}cancelRun(){var r;const t=new Jn(!1);(r=this.abortController)==null||r.abort(t),this.abortController=null}addToolResult({messageId:t,toolCallId:r,result:n,isError:a,artifact:i}){const s=this.repository.getMessage(t),{parentId:o}=s;let{message:l}=s;if(l.role!=="assistant")throw new Error("Tried to add tool result to non-assistant message");let u=!1,d=!1;const c=l.content.map(h=>h.type!=="tool-call"||h.toolCallId!==r?h:(d=!0,h.result||(u=!0),E(m({},h),{result:n,artifact:i,isError:a})));if(!d)throw new Error("Tried to add tool result to non-existing tool call");l=E(m({},l),{content:c}),this.repository.addOrUpdateMessage(o,l),u&&ms(l,this._options.unstable_humanToolNames)&&this.performRoundtrip(o,l,this._lastRunConfig)}resumeToolCall(t){throw new Error("Local runtime does not support resuming tool calls.")}},gs=Object.freeze([]),Yn="__DEFAULT_ID__",kh=Object.freeze({[Yn]:{id:Yn,remoteId:void 0,externalId:void 0,status:"regular",title:void 0}}),Sh=class extends ar{constructor(t){super();C(this,"_mainThread");this._mainThread=t()}get isLoading(){return!1}getMainThreadRuntimeCore(){return this._mainThread}get newThreadId(){throw new Error("Method not implemented.")}get threadIds(){throw gs}get archivedThreadIds(){throw gs}get mainThreadId(){return Yn}get threadData(){return kh}getThreadRuntimeCore(){throw new Error("Method not implemented.")}getLoadThreadsPromise(){throw new Error("Method not implemented.")}getItemById(t){if(t===this.mainThreadId)return{status:"regular",id:this.mainThreadId,remoteId:this.mainThreadId,externalId:void 0,title:void 0,isMain:!0};throw new Error("Method not implemented")}switchToThread(){return P(this,null,function*(){throw new Error("Method not implemented.")})}switchToNewThread(){throw new Error("Method not implemented.")}rename(){throw new Error("Method not implemented.")}archive(){throw new Error("Method not implemented.")}detach(){throw new Error("Method not implemented.")}unarchive(){throw new Error("Method not implemented.")}delete(){throw new Error("Method not implemented.")}initialize(t){return Promise.resolve({remoteId:t,externalId:void 0})}generateTitle(){throw new Error("Method not implemented.")}},_h=class extends An{constructor(t,r){super();C(this,"threads");C(this,"Provider");C(this,"_options");this._options=t,this.threads=new Sh(()=>new vh(this._contextProvider,this._options)),r&&this.threads.getMainThreadRuntimeCore().import(Dn.fromArray(r))}},ys=e=>{try{const r=e.split(".")[1];if(!r)throw new Error("Invalid JWT format");let n=r.replace(/-/g,"+").replace(/_/g,"/");for(;n.length%4!==0;)n+="=";const a=atob(n),s=JSON.parse(a).exp;if(!s||typeof s!="number")throw new Error('JWT does not contain a valid "exp" field');return s*1e3}catch(t){throw new Error(`Unable to determine the token expiry: ${t}`)}},bs=(Cu=class{constructor(e){C(this,"strategy","jwt");C(this,"cachedToken",null);C(this,"tokenExpiry",null);er(this,Er);tr(this,Er,e)}getAuthHeaders(){return P(this,null,function*(){const e=Date.now();if(this.cachedToken&&this.tokenExpiry&&this.tokenExpiry-e>30*1e3)return{Authorization:`Bearer ${this.cachedToken}`};const t=yield Ge(this,Er).call(this);return t?(this.cachedToken=t,this.tokenExpiry=ys(t),{Authorization:`Bearer ${t}`}):!1})}readAuthHeaders(e){const t=e.get("Authorization");if(!t)return;const[r,n]=t.split(" ");if(r!=="Bearer"||!n)throw new Error("Invalid auth header received");this.cachedToken=n,this.tokenExpiry=ys(n)}},Er=new WeakMap,Cu),Th=(Iu=class{constructor(e,t,r){C(this,"strategy","api-key");er(this,Ar);er(this,Mr);er(this,Pr);tr(this,Ar,e),tr(this,Mr,t),tr(this,Pr,r)}getAuthHeaders(){return P(this,null,function*(){return{Authorization:`Bearer ${Ge(this,Ar)}`,"Aui-User-Id":Ge(this,Mr),"Aui-Workspace-Id":Ge(this,Pr)}})}readAuthHeaders(){}},Ar=new WeakMap,Mr=new WeakMap,Pr=new WeakMap,Iu),Gr="aui:refresh_token",Ch=class{constructor(e){C(this,"strategy","anon");C(this,"baseUrl");C(this,"jwtStrategy");this.baseUrl=e,this.jwtStrategy=new bs(()=>P(this,null,function*(){const t=Date.now(),r=localStorage.getItem(Gr),n=r?JSON.parse(r):void 0;if(n)if(new Date(n.expires_at).getTime()-t>30*1e3){const u=yield fetch(`${this.baseUrl}/v1/auth/tokens/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:n.token})});if(u.ok){const d=yield u.json(),{access_token:c,refresh_token:h}=d;return h&&localStorage.setItem(Gr,JSON.stringify(h)),c}}else localStorage.removeItem(Gr);const a=yield fetch(`${this.baseUrl}/v1/auth/tokens/anonymous`,{method:"POST"});if(!a.ok)return null;const i=yield a.json(),{access_token:s,refresh_token:o}=i;return!s||!o?null:(localStorage.setItem(Gr,JSON.stringify(o)),s)}))}getAuthHeaders(){return P(this,null,function*(){return this.jwtStrategy.getAuthHeaders()})}readAuthHeaders(e){this.jwtStrategy.readAuthHeaders(e)}},Ih=class extends Error{constructor(e){super(e),this.name="APIError"}},Eh=class{constructor(e){C(this,"_auth");C(this,"_baseUrl");if("authToken"in e)this._baseUrl=e.baseUrl,this._auth=new bs(e.authToken);else if("apiKey"in e)this._baseUrl="https://backend.assistant-api.com",this._auth=new Th(e.apiKey,e.userId,e.workspaceId);else if("anonymous"in e)this._baseUrl=e.baseUrl,this._auth=new Ch(e.baseUrl);else throw new Error("Invalid configuration: Must provide authToken, apiKey, or anonymous configuration")}initializeAuth(){return P(this,null,function*(){return!!this._auth.getAuthHeaders()})}makeRawRequest(r){return P(this,arguments,function*(e,t={}){var l;const n=yield this._auth.getAuthHeaders();if(!n)throw new Error("Authorization failed");const a=E(m(m({},n),t.headers),{"Content-Type":"application/json"}),i=new URLSearchParams;if(t.query)for(const[u,d]of Object.entries(t.query))d!==!1&&(d===!0?i.set(u,"true"):i.set(u,d.toString()));const s=new URL(`${this._baseUrl}/v1${e}`);s.search=i.toString();const o=yield fetch(s,{method:(l=t.method)!=null?l:"GET",headers:a,body:t.body?JSON.stringify(t.body):null});if(this._auth.readAuthHeaders(o.headers),!o.ok){const u=yield o.text();try{const d=JSON.parse(u);throw new Ih(d.message)}catch(d){throw new Error(`Request failed with status ${o.status}, ${u}`)}}return o})}makeRequest(r){return P(this,arguments,function*(e,t={}){return(yield this.makeRawRequest(e,t)).json()})}},Ah=class{constructor(e){this.cloud=e}create(){return P(this,null,function*(){return this.cloud.makeRequest("/auth/tokens",{method:"POST"})})}},Mh=class{constructor(e){this.cloud=e}__internal_getAssistantOptions(e){return{api:`${this.cloud._baseUrl}/v1/runs/stream`,headers:()=>P(this,null,function*(){const t=yield this.cloud._auth.getAuthHeaders();if(!t)throw new Error("Authorization failed");return E(m({},t),{Accept:"text/plain"})}),body:{assistant_id:e,response_format:"vercel-ai-data-stream/v1",thread_id:"unstable_todo"}}}stream(e){return P(this,null,function*(){const t=yield this.cloud.makeRawRequest("/runs/stream",{method:"POST",headers:{Accept:"text/plain"},body:e});return Nn.fromResponse(t,new jc)})}},Ph=class{constructor(e){this.cloud=e}list(e,t){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{query:t})})}create(e,t){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{method:"POST",body:t})})}},Nh=class{constructor(e){C(this,"messages");this.cloud=e,this.messages=new Ph(e)}list(e){return P(this,null,function*(){return this.cloud.makeRequest("/threads",{query:e})})}get(e){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`)})}create(e){return P(this,null,function*(){return this.cloud.makeRequest("/threads",{method:"POST",body:e})})}update(e,t){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:"PUT",body:t})})}delete(e){return P(this,null,function*(){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:"DELETE"})})}},Lh=class{constructor(e){this.cloud=e}pdfToImages(e){return P(this,null,function*(){return this.cloud.makeRequest("/files/pdf-to-images",{method:"POST",body:e})})}generatePresignedUploadUrl(e){return P(this,null,function*(){return this.cloud.makeRequest("/files/attachments/generate-presigned-upload-url",{method:"POST",body:e})})}},Dh=class{constructor(e){C(this,"threads");C(this,"auth");C(this,"runs");C(this,"files");const t=new Eh(e);this.threads=new Nh(t),this.auth={tokens:new Ah(t)},this.runs=new Mh(t),this.files=new Lh(t)}};function Kn(e,t=0){return t>100?!1:e===null||typeof e=="string"||typeof e=="boolean"?!0:typeof e=="number"?!Number.isNaN(e)&&Number.isFinite(e):Array.isArray(e)?e.every(r=>Kn(r,t+1)):typeof e=="object"?Object.entries(e).every(([r,n])=>typeof r=="string"&&Kn(n,t+1)):!1}var Oh=e=>{var t;return m({role:e.role,content:e.content.map(r=>{const n=r.type;switch(n){case"text":return{type:"text",text:r.text};case"reasoning":return{type:"reasoning",text:r.text};case"source":return m({type:"source",sourceType:r.sourceType,id:r.id,url:r.url},r.title?{title:r.title}:void 0);case"tool-call":return Kn(r.result)||console.warn(`tool-call result is not JSON! ${JSON.stringify(r)}`),m(m(m({type:"tool-call",toolCallId:r.toolCallId,toolName:r.toolName},JSON.stringify(r.args)===r.argsText?{args:r.args}:{argsText:r.argsText}),r.result?{result:r.result}:{}),r.isError?{isError:!0}:{});default:{const a=n;throw new Error(`Message part type not supported by aui/v0: ${a}`)}}}),metadata:e.metadata},e.status?{status:((t=e.status)==null?void 0:t.type)==="running"?{type:"incomplete",reason:"cancelled"}:e.status}:void 0)},Fh=e=>{const t=e.content,r=sr(m({id:e.id,createdAt:e.created_at},t),e.id,{type:"complete",reason:"unknown"});return{parentId:e.parent_id,message:r}},Gn=new WeakMap,Bh=class{constructor(e,t){this.parent=e,this.formatAdapter=t}append(e){return P(this,null,function*(){const t=this.formatAdapter.encode(e),r=this.formatAdapter.getId(e.message);return this.parent._appendWithFormat(e.parentId,r,this.formatAdapter.format,t)})}load(){return P(this,null,function*(){return this.parent._loadWithFormat(this.formatAdapter.format,e=>this.formatAdapter.decode(e))})}},zh=class{constructor(e,t){this.cloudRef=e,this.store=t}get _getIdForLocalId(){return Gn.has(this.store.threadListItem())||Gn.set(this.store.threadListItem(),{}),Gn.get(this.store.threadListItem())}withFormat(e){return new Bh(this,e)}append(r){return P(this,arguments,function*({parentId:e,message:t}){var i;const{remoteId:n}=yield this.store.threadListItem().initialize(),a=this.cloudRef.current.threads.messages.create(n,{parent_id:e?(i=yield this._getIdForLocalId[e])!=null?i:e:null,format:"aui/v0",content:Oh(t)}).then(({message_id:s})=>(this._getIdForLocalId[t.id]=s,s));return this._getIdForLocalId[t.id]=a,a.then(()=>{})})}load(){return P(this,null,function*(){const e=this.store.threadListItem().getState().remoteId;if(!e)return{messages:[]};const{messages:t}=yield this.cloudRef.current.threads.messages.list(e,{format:"aui/v0"});return{messages:t.filter(n=>n.format==="aui/v0").map(Fh).reverse()}})}_appendWithFormat(e,t,r,n){return P(this,null,function*(){var s;const{remoteId:a}=yield this.store.threadListItem().initialize(),i=this.cloudRef.current.threads.messages.create(a,{parent_id:e?(s=yield this._getIdForLocalId[e])!=null?s:e:null,format:r,content:n}).then(({message_id:o})=>(this._getIdForLocalId[t]=o,o));return this._getIdForLocalId[t]=i,i.then(()=>{})})}_loadWithFormat(e,t){return P(this,null,function*(){const r=this.store.threadListItem().getState().remoteId;if(!r)return{messages:[]};const{messages:n}=yield this.cloudRef.current.threads.messages.list(r,{format:e});return{messages:n.filter(a=>a.format===e).map(a=>t({id:a.id,parent_id:a.parent_id,format:a.format,content:a.content})).reverse()}})}},Rh=e=>{const t=pe(),[r]=y.useState(()=>new zh(e,t));return r},ws=typeof process!="undefined"&&((Eu=process==null?void 0:process.env)==null?void 0:Eu.NEXT_PUBLIC_ASSISTANT_BASE_URL),Xn=ws?new Dh({baseUrl:ws,anonymous:!0}):void 0,jh=e=>{var a;const t=y.useRef(e);y.useEffect(()=>{t.current=e},[e]);const r=y.useCallback(function({children:s}){var c;const o=Rh({get current(){var h;return(h=t.current.cloud)!=null?h:Xn}}),l=(c=t.current.cloud)!=null?c:Xn,u=y.useMemo(()=>new od(l),[l]),d=y.useMemo(()=>({history:o,attachments:u}),[o,u]);return p.jsx(Bn,{adapters:d,children:s})},[]),n=(a=e.cloud)!=null?a:Xn;return n?{list:()=>P(null,null,function*(){const{threads:i}=yield n.threads.list();return{threads:i.map(s=>{var o;return{status:s.is_archived?"archived":"regular",remoteId:s.id,title:s.title,externalId:(o=s.external_id)!=null?o:void 0}})}}),initialize:()=>P(null,null,function*(){var u,d;const s=yield(d=(u=e.create)==null?void 0:u.call(e))!=null?d:Promise.resolve(),o=s?s.externalId:void 0,{thread_id:l}=yield n.threads.create({last_message_at:new Date,external_id:o});return{externalId:o,remoteId:l}}),rename:(i,s)=>P(null,null,function*(){return n.threads.update(i,{title:s})}),archive:i=>P(null,null,function*(){return n.threads.update(i,{is_archived:!0})}),unarchive:i=>P(null,null,function*(){return n.threads.update(i,{is_archived:!1})}),delete:i=>P(null,null,function*(){var s;return yield(s=e.delete)==null?void 0:s.call(e,i),n.threads.delete(i)}),generateTitle:(i,s)=>P(null,null,function*(){return n.runs.stream({thread_id:i,assistant_id:"system/thread_title",messages:s})}),fetch:i=>P(null,null,function*(){var o;const s=yield n.threads.get(i);return{status:s.is_archived?"archived":"regular",remoteId:s.id,title:s.title,externalId:(o=s.external_id)!=null?o:void 0}}),unstable_Provider:r}:new fd},$h=(e,n)=>{var a=n,{initialMessages:t}=a,r=V(a,["initialMessages"]);var u;const d=(u=ld())!=null?u:{},{modelContext:i}=d,s=V(d,["modelContext"]),o=y.useMemo(()=>E(m({},r),{adapters:E(m(m({},s),r.adapters),{chatModel:e})}),[e,r,s]),[l]=y.useState(()=>new _h(o,t));return y.useEffect(()=>()=>{l.threads.getMainThreadRuntimeCore().detach()},[l]),y.useEffect(()=>{l.threads.getMainThreadRuntimeCore().__internal_setOptions(o),l.threads.getMainThreadRuntimeCore().__internal_load()},[l,o]),y.useEffect(()=>{if(i)return l.registerModelContextProvider(i)},[i,l]),y.useMemo(()=>new Qn(l),[l])},xs=(e,n={})=>{var a=n,{cloud:t}=a,r=V(a,["cloud"]);const i=jh({cloud:t});return Ts({runtimeHook:function(){return $h(e,r)},adapter:i,allowNesting:!0})},Qn=class{constructor(e){C(this,"threads");C(this,"_thread");this._core=e,this.threads=new id(e.threads),this._thread=this.threads.main,this.__internal_bindMethods()}get threadList(){return this.threads}__internal_bindMethods(){this.switchToNewThread=this.switchToNewThread.bind(this),this.switchToThread=this.switchToThread.bind(this),this.registerModelContextProvider=this.registerModelContextProvider.bind(this),this.registerModelConfigProvider=this.registerModelConfigProvider.bind(this),this.reset=this.reset.bind(this)}get thread(){return this._thread}switchToNewThread(){return this._core.threads.switchToNewThread()}switchToThread(e){return this._core.threads.switchToThread(e)}registerModelContextProvider(e){return this._core.registerModelContextProvider(e)}registerModelConfigProvider(e){return this.registerModelContextProvider(e)}reset({initialMessages:e}={}){return this._core.threads.getMainThreadRuntimeCore().import(Dn.fromArray(e!=null?e:[]))}},Uh=e=>{const o=e,{cloud:t,initialMessages:r,maxSteps:n,adapters:a,unstable_humanToolNames:i}=o,s=V(o,["cloud","initialMessages","maxSteps","adapters","unstable_humanToolNames"]);return{localRuntimeOptions:{cloud:t,initialMessages:r,maxSteps:n,adapters:a,unstable_humanToolNames:i},otherOptions:s}};function At(e){const t=K.useRef(e);return K.useEffect(()=>{t.current=e}),K.useMemo(()=>(...r)=>{var n;return(n=t.current)==null?void 0:n.call(t,...r)},[])}var vs=y.createContext(null),Hh=e=>({useSmoothStatus:Ht(()=>e)}),qh=({children:e})=>{const t=ks({optional:!0}),r=pe(),[n]=y.useState(()=>Hh(r.part().getState().status));return t?e:p.jsx(vs.Provider,{value:n,children:e})},Vh=e=>{const t=y.forwardRef((r,n)=>p.jsx(qh,{children:p.jsx(e,E(m({},r),{ref:n}))}));return t.displayName=e.displayName,t};function ks(e){const t=y.useContext(vs);if(!(e!=null&&e.optional)&&!t)throw new Error("This component must be used within a SmoothContextProvider.");return t}var{useSmoothStatus:Wh,useSmoothStatusStore:Jh}=ss(ks,"useSmoothStatus"),Yh=class{constructor(e,t){C(this,"animationFrameId",null);C(this,"lastUpdateTime",Date.now());C(this,"targetText","");C(this,"animate",()=>{const e=Date.now();let r=e-this.lastUpdateTime;const n=this.targetText.length-this.currentText.length,a=Math.min(5,250/n);let i=0;for(;r>=a&&i<n;)i++,r-=a;i!==n?this.animationFrameId=requestAnimationFrame(this.animate):this.animationFrameId=null,i!==0&&(this.currentText=this.targetText.slice(0,this.currentText.length+i),this.lastUpdateTime=e-r,this.setText(this.currentText))});this.currentText=e,this.setText=t}start(){this.animationFrameId===null&&(this.lastUpdateTime=Date.now(),this.animate())}stop(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}},Zn=Object.freeze({type:"running"}),Ss=(e,t=!1)=>{const{text:r}=e,n=ae(({message:d})=>d.id),a=y.useRef(n),[i,s]=y.useState(r),o=Jh({optional:!0}),l=At(d=>{if(s(d),o){const c=i!==d||e.status.type==="running"?Zn:e.status;hr(o).setState(c,!0)}});y.useEffect(()=>{if(o){const d=t&&(i!==r||e.status.type==="running")?Zn:e.status;hr(o).setState(d,!0)}},[o,t,r,i,e.status]);const[u]=y.useState(new Yh(r,l));return y.useEffect(()=>{if(!t){u.stop();return}if(a.current!==n||!r.startsWith(u.targetText)){a.current=n,l(r),u.currentText=r,u.targetText=r,u.stop();return}u.targetText=r,u.start()},[l,u,n,t,r]),y.useEffect(()=>()=>{u.stop()},[u]),y.useMemo(()=>t?{type:"text",text:i,status:r===i?e.status:Zn}:e,[t,i,e,r])};const Kh=Object.freeze(Object.defineProperty({__proto__:null,AssistantRuntimeImpl:Qn,BaseAssistantRuntimeCore:An,CompositeContextProvider:En,DefaultThreadComposerRuntimeCore:fi,MessageRepository:Ii,ThreadRuntimeImpl:$i,fromThreadMessageLike:sr,generateId:_t,getAutoStatus:mi,splitLocalRuntimeOptions:Uh,useSmooth:Ss,useSmoothStatus:Wh,useToolInvocations:hd,withSmoothContextProvider:Vh},Symbol.toStringTag,{value:"Module"}));var Gh=class extends ar{constructor(t){super();C(this,"useRuntimeHook");C(this,"instances",new Map);C(this,"useAliveThreadsKeysChanged",Ht(()=>({})));C(this,"_InnerActiveThreadProvider",({threadId:t})=>{const{useRuntime:r}=this.useRuntimeHook(),n=r(),a=n.thread.__internal_threadBinding,i=y.useCallback(()=>{const l=this.instances.get(t);if(!l)throw new Error("Thread not found. This is a bug in assistant-ui.");l.runtime=a.getState(),this._notifySubscribers()},[t,a]),s=y.useRef(!1);s.current||i(),y.useEffect(()=>(s.current=!0,i(),a.outerSubscribe(i)),[a,i]);const o=pe();return y.useEffect(()=>n.threads.main.unstable_on("initialize",()=>{if(o.threadListItem().getState().status==="new"){o.threadListItem().initialize();const u=n.thread.unstable_on("run-end",()=>{u(),o.threadListItem().generateTitle()})}}),[n,o]),null});C(this,"_OuterActiveThreadProvider",y.memo(({threadId:t,provider:r})=>p.jsx(ph,{id:t,children:p.jsx(r,{children:p.jsx(this._InnerActiveThreadProvider,{threadId:t})})})));C(this,"__internal_RenderThreadRuntimes",({provider:t})=>(this.useAliveThreadsKeysChanged(),Array.from(this.instances.keys()).map(r=>p.jsx(this._OuterActiveThreadProvider,{threadId:r,provider:t},r))));this.useRuntimeHook=Ht(()=>({useRuntime:t}))}startThreadRuntime(t){return this.instances.has(t)||(this.instances.set(t,{}),this.useAliveThreadsKeysChanged.setState({},!0)),new Promise((r,n)=>{const a=()=>{const s=this.instances.get(t);if(!s)i(),n(new Error("Thread was deleted before runtime was started"));else if(s.runtime)i(),r(s.runtime);else return},i=this.subscribe(a);a()})}getThreadRuntimeCore(t){const r=this.instances.get(t);if(r)return r.runtime}stopThreadRuntime(t){this.instances.delete(t),this.useAliveThreadsKeysChanged.setState({},!0)}setRuntimeHook(t){this.useRuntimeHook.getState().useRuntime!==t&&this.useRuntimeHook.setState({useRuntime:t},!0)}},Se=new Error("This is the empty thread, a placeholder for the main thread. You cannot perform any actions on this thread instance. This error is probably because you tried to call a thread method in your render function. Call the method inside a `useEffect` hook instead."),Xh={getMessageById(){},getBranches(){return[]},switchToBranch(){throw Se},append(){throw Se},startRun(){throw Se},resumeRun(){throw Se},cancelRun(){throw Se},addToolResult(){throw Se},resumeToolCall(){throw Se},speak(){throw Se},stopSpeaking(){throw Se},submitFeedback(){throw Se},getModelContext(){return{}},unstable_loadExternalState(){throw Se},composer:{attachments:[],attachmentAccept:"*",addAttachment(){return P(this,null,function*(){throw Se})},removeAttachment(){return P(this,null,function*(){throw Se})},isEditing:!0,canCancel:!1,isEmpty:!0,text:"",setText(){throw Se},role:"user",setRole(){throw Se},runConfig:{},setRunConfig(){throw Se},reset(){return P(this,null,function*(){})},clearAttachments(){return P(this,null,function*(){})},send(){throw Se},cancel(){},subscribe(){return()=>{}},unstable_on(){return()=>{}}},getEditComposer(){},beginEdit(){throw Se},speech:void 0,capabilities:{switchToBranch:!1,switchBranchDuringRun:!1,edit:!1,reload:!1,cancel:!1,unstable_copy:!1,speech:!1,attachments:!1,feedback:!1},isDisabled:!1,isLoading:!1,messages:[],state:null,suggestions:[],extras:void 0,subscribe(){return()=>{}},import(){throw Se},export(){return{messages:[]}},reset(){throw Se},unstable_on(){return()=>{}}},_s=(e,t,r)=>r.reduce((n,a)=>{var i;return(i=a==null?void 0:a(n,t))!=null?i:n},e),Qh=class extends ar{constructor(t){super();C(this,"_pendingTransforms",[]);C(this,"_baseValue");C(this,"_cachedValue");this._baseValue=t,this._cachedValue=t}_updateState(){this._cachedValue=this._pendingTransforms.reduce((t,r)=>_s(t,r.task,[r.loading,r.optimistic]),this._baseValue),this._notifySubscribers()}get baseValue(){return this._baseValue}get value(){return this._cachedValue}update(t){this._baseValue=t,this._updateState()}optimisticUpdate(t){return P(this,null,function*(){const r=t.execute(),n=E(m({},t),{task:r});try{this._pendingTransforms.push(n),this._updateState();const a=yield r;return this._baseValue=_s(this._baseValue,a,[t.optimistic,t.then]),a}finally{const a=this._pendingTransforms.indexOf(n);a>-1&&this._pendingTransforms.splice(a,1),this._updateState()}})}};function jv(e){return e}var Xr=(e,t)=>{const r=e.threadIdMap[t];if(r!==void 0)return e.threadData[r]},Qr=(e,t,r)=>{const n=Xr(e,t);if(!n)return e;const{id:a,remoteId:i,status:s}=n;if(s===r)return e;const o=m({},e);switch(s){case"new":o.newThreadId=void 0;break;case"regular":o.threadIds=o.threadIds.filter(l=>l!==a);break;case"archived":o.archivedThreadIds=o.archivedThreadIds.filter(l=>l!==a);break;default:{const l=s;throw new Error(`Unsupported state: ${l}`)}}switch(r){case"regular":o.threadIds=[a,...o.threadIds];break;case"archived":o.archivedThreadIds=[a,...o.archivedThreadIds];break;case"deleted":o.threadData=Object.fromEntries(Object.entries(o.threadData).filter(([l])=>l!==a)),o.threadIdMap=Object.fromEntries(Object.entries(o.threadIdMap).filter(([l])=>l!==a&&l!==i));break;default:{const l=r;throw new Error(`Unsupported state: ${l}`)}}return r!=="deleted"&&(o.threadData=E(m({},o.threadData),{[a]:E(m({},n),{status:r})})),o},Zh=class extends ar{constructor(t,r){super();C(this,"_options");C(this,"_hookManager");C(this,"_loadThreadsPromise");C(this,"_mainThreadId");C(this,"_state",new Qh({isLoading:!1,newThreadId:void 0,threadIds:[],archivedThreadIds:[],threadIdMap:{},threadData:{}}));C(this,"useProvider");C(this,"initialize",t=>P(this,null,function*(){if(this._state.value.newThreadId!==t){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status==="new")throw new Error("Unexpected new state");return r.initializeTask}return this._state.optimisticUpdate({execute:()=>this._options.adapter.initialize(t),optimistic:r=>Qr(r,t,"regular"),loading:(r,n)=>{const a=t;return E(m({},r),{threadData:E(m({},r.threadData),{[a]:E(m({},r.threadData[a]),{initializeTask:n})})})},then:(r,{remoteId:n,externalId:a})=>{const i=Xr(r,t);if(!i)return r;const s=t;return E(m({},r),{threadIdMap:E(m({},r.threadIdMap),{[n]:s}),threadData:E(m({},r.threadData),{[s]:E(m({},i),{initializeTask:Promise.resolve({remoteId:n,externalId:a}),remoteId:n,externalId:a})})})}})}));C(this,"generateTitle",t=>P(this,null,function*(){var l;const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status==="new")throw new Error("Thread is not yet initialized");const{remoteId:n}=yield r.initializeTask,a=this._hookManager.getThreadRuntimeCore(r.id);if(!a)return;const i=a.messages,s=yield this._options.adapter.generateTitle(n,i),o=$c.fromAssistantStream(s);try{for(var u=Ft(o),d,c,h;d=!(c=yield u.next()).done;d=!1){const f=c.value;const g=(l=f.parts.filter(b=>b.type==="text")[0])==null?void 0:l.text,v=this._state.baseValue;this._state.update(E(m({},v),{threadData:E(m({},v.threadData),{[r.id]:E(m({},r),{title:g})})}))}}catch(c){h=[c]}finally{try{d&&(c=u.return)&&(yield c.call(u))}finally{if(h)throw h[0]}}}));C(this,"useBoundIds",Ht(()=>[]));C(this,"__internal_RenderComponent",()=>{const t=y.useId();y.useEffect(()=>(this.useBoundIds.setState(i=>[...i,t],!0),()=>{this.useBoundIds.setState(i=>i.filter(s=>s!==t),!0)}),[t]);const r=this.useBoundIds(),{Provider:n}=this.useProvider(),a={modelContext:this.contextProvider};return(r.length===0||r[0]===t)&&p.jsx(Bn,{adapters:a,children:p.jsx(this._hookManager.__internal_RenderThreadRuntimes,{provider:n})})});this.contextProvider=r,this._state.subscribe(()=>this._notifySubscribers()),this._hookManager=new Gh(t.runtimeHook),this.useProvider=Ht(()=>{var n;return{Provider:(n=t.adapter.unstable_Provider)!=null?n:y.Fragment}}),this.__internal_setOptions(t),this.switchToNewThread()}get threadData(){return this._state.value.threadData}getLoadThreadsPromise(){return this._loadThreadsPromise||(this._loadThreadsPromise=this._state.optimisticUpdate({execute:()=>this._options.adapter.list(),loading:t=>E(m({},t),{isLoading:!0}),then:(t,r)=>{const n=[],a=[],i={},s={};for(const o of r.threads){switch(o.status){case"regular":n.push(o.remoteId);break;case"archived":a.push(o.remoteId);break;default:{const u=o.status;throw new Error(`Unsupported state: ${u}`)}}const l=o.remoteId;i[o.remoteId]=l,s[l]={id:o.remoteId,remoteId:o.remoteId,externalId:o.externalId,status:o.status,title:o.title,initializeTask:Promise.resolve({remoteId:o.remoteId,externalId:o.externalId})}}return E(m({},t),{threadIds:n,archivedThreadIds:a,threadIdMap:m(m({},t.threadIdMap),i),threadData:m(m({},t.threadData),s)})}}).then(()=>{})),this._loadThreadsPromise}__internal_setOptions(t){var n;if(this._options===t)return;this._options=t;const r=(n=t.adapter.unstable_Provider)!=null?n:y.Fragment;r!==this.useProvider.getState().Provider&&this.useProvider.setState({Provider:r},!0),this._hookManager.setRuntimeHook(t.runtimeHook)}__internal_load(){this.getLoadThreadsPromise()}get isLoading(){return this._state.value.isLoading}get threadIds(){return this._state.value.threadIds}get archivedThreadIds(){return this._state.value.archivedThreadIds}get newThreadId(){return this._state.value.newThreadId}get mainThreadId(){return this._mainThreadId}getMainThreadRuntimeCore(){const t=this._hookManager.getThreadRuntimeCore(this._mainThreadId);return t||Xh}getThreadRuntimeCore(t){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");const n=this._hookManager.getThreadRuntimeCore(r.id);if(!n)throw new Error("Thread not found");return n}getItemById(t){return Xr(this._state.value,t)}switchToThread(t){return P(this,null,function*(){let r=this.getItemById(t);if(!r){const a=yield this._options.adapter.fetch(t),i=this._state.value,s=a.remoteId,o=E(m({},i.threadData),{[s]:{id:s,initializeTask:Promise.resolve({remoteId:a.remoteId,externalId:a.externalId}),remoteId:a.remoteId,externalId:a.externalId,status:a.status,title:a.title}}),l=E(m({},i.threadIdMap),{[a.remoteId]:s}),u=a.status==="regular"?[...i.threadIds,a.remoteId]:i.threadIds,d=a.status==="archived"?[...i.archivedThreadIds,a.remoteId]:i.archivedThreadIds;this._state.update(E(m({},i),{threadIds:u,archivedThreadIds:d,threadIdMap:l,threadData:o})),r=this.getItemById(t)}if(!r)throw new Error("Thread not found");if(this._mainThreadId===r.id)return;const n=this._hookManager.startThreadRuntime(r.id);this.mainThreadId!==void 0?yield n:n.then(()=>this._notifySubscribers()),r.status==="archived"&&(yield this.unarchive(r.id)),this._mainThreadId=r.id,this._notifySubscribers()})}switchToNewThread(){return P(this,null,function*(){for(;this._state.baseValue.newThreadId!==void 0&&this._state.value.newThreadId===void 0;)yield this._state.waitForUpdate();const t=this._state.value;let r=this._state.value.newThreadId;if(r===void 0){do r=`__LOCALID_${_t()}`;while(t.threadIdMap[r]);const n=r;this._state.update(E(m({},t),{newThreadId:r,threadIdMap:E(m({},t.threadIdMap),{[r]:n}),threadData:E(m({},t.threadData),{[n]:{status:"new",id:r,remoteId:void 0,externalId:void 0,title:void 0}})}))}return this.switchToThread(r)})}rename(t,r){const n=this.getItemById(t);if(!n)throw new Error("Thread not found");if(n.status==="new")throw new Error("Thread is not yet initialized");return this._state.optimisticUpdate({execute:()=>P(this,null,function*(){const{remoteId:a}=yield n.initializeTask;return this._options.adapter.rename(a,r)}),optimistic:a=>{const i=Xr(a,t);return i?E(m({},a),{threadData:E(m({},a.threadData),{[i.id]:E(m({},i),{title:r})})}):a}})}_ensureThreadIsNotMain(t){return P(this,null,function*(){if(t===this.newThreadId)throw new Error("Cannot ensure new thread is not main");t===this._mainThreadId&&(yield this.switchToNewThread())})}archive(t){return P(this,null,function*(){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status!=="regular")throw new Error("Thread is not yet initialized or already archived");return this._state.optimisticUpdate({execute:()=>P(this,null,function*(){yield this._ensureThreadIsNotMain(r.id);const{remoteId:n}=yield r.initializeTask;return this._options.adapter.archive(n)}),optimistic:n=>Qr(n,r.id,"archived")})})}unarchive(t){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status!=="archived")throw new Error("Thread is not archived");return this._state.optimisticUpdate({execute:()=>P(this,null,function*(){try{const{remoteId:n}=yield r.initializeTask;return yield this._options.adapter.unarchive(n)}catch(n){throw yield this._ensureThreadIsNotMain(r.id),n}}),optimistic:n=>Qr(n,r.id,"regular")})}delete(t){return P(this,null,function*(){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status!=="regular"&&r.status!=="archived")throw new Error("Thread is not yet initialized");return this._state.optimisticUpdate({execute:()=>P(this,null,function*(){yield this._ensureThreadIsNotMain(r.id);const{remoteId:n}=yield r.initializeTask;return yield this._options.adapter.delete(n)}),optimistic:n=>Qr(n,r.id,"deleted")})})}detach(t){return P(this,null,function*(){const r=this.getItemById(t);if(!r)throw new Error("Thread not found");if(r.status!=="regular"&&r.status!=="archived")throw new Error("Thread is not yet initialized");yield this._ensureThreadIsNotMain(r.id),this._hookManager.stopThreadRuntime(r.id)})}},ef=class extends An{constructor(t){super();C(this,"threads");this.threads=new Zh(t,this._contextProvider)}get RenderComponent(){return this.threads.__internal_RenderComponent}},tf=e=>{const[t]=y.useState(()=>new ef(e));return y.useEffect(()=>{t.threads.__internal_setOptions(e),t.threads.__internal_load()},[t,e]),y.useMemo(()=>new Qn(t),[t])},Ts=e=>{if(Yr().threadListItem.source!==null){if(!e.allowNesting)throw new Error("useRemoteThreadListRuntime cannot be nested inside another RemoteThreadListRuntime. Set allowNesting: true to allow nesting (the inner runtime will become a no-op).");return e.runtimeHook()}return tf(e)},rf=Symbol.for("react.lazy"),Zr=K[" use ".trim().toString()];function nf(e){return typeof e=="object"&&e!==null&&"then"in e}function Cs(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===rf&&"_payload"in e&&nf(e._payload)}function Is(e){const t=af(e),r=K.forwardRef((n,a)=>{let u=n,{children:i}=u,s=V(u,["children"]);Cs(i)&&typeof Zr=="function"&&(i=Zr(i._payload));const o=K.Children.toArray(i),l=o.find(of);if(l){const d=l.props.children,c=o.map(h=>h===l?K.Children.count(d)>1?K.Children.only(null):K.isValidElement(d)?d.props.children:null:h);return p.jsx(t,E(m({},s),{ref:a,children:K.isValidElement(d)?K.cloneElement(d,void 0,c):null}))}return p.jsx(t,E(m({},s),{ref:a,children:i}))});return r.displayName=`${e}.Slot`,r}var Es=Is("Slot");function af(e){const t=K.forwardRef((r,n)=>{let s=r,{children:a}=s,i=V(s,["children"]);if(Cs(a)&&typeof Zr=="function"&&(a=Zr(a._payload)),K.isValidElement(a)){const o=uf(a),l=lf(i,a.props);return a.type!==K.Fragment&&(l.ref=n?Qi(n,o):o),K.cloneElement(a,l)}return K.Children.count(a)>1?K.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var sf=Symbol("radix.slottable");function of(e){return K.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===sf}function lf(e,t){const r=m({},t);for(const n in t){const a=e[n],i=t[n];/^on[A-Z]/.test(n)?a&&i?r[n]=(...o)=>{const l=i(...o);return a(...o),l}:a&&(r[n]=a):n==="style"?r[n]=m(m({},a),i):n==="className"&&(r[n]=[a,i].filter(Boolean).join(" "))}return m(m({},e),r)}function uf(e){var n,a;let t=(n=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:n.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=(a=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:a.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}var cf=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ft=cf.reduce((e,t)=>{const r=Is(`Primitive.${t}`),n=K.forwardRef((a,i)=>{const u=a,{asChild:s}=u,o=V(u,["asChild"]),l=s?r:t;return typeof window!="undefined"&&(window[Symbol.for("radix-ui")]=!0),p.jsx(l,E(m({},o),{ref:i}))});return n.displayName=`Primitive.${t}`,E(m({},e),{[t]:n})},{});function qt(e,t,{checkForDefaultPrevented:r=!0}={}){return function(a){if(e==null||e(a),r===!1||!a.defaultPrevented)return t==null?void 0:t(a)}}var fr=(e,t,r=[])=>{const n=y.forwardRef((a,i)=>{var u;const s={},o={};Object.keys(a).forEach(d=>{r.includes(d)?s[d]=a[d]:o[d]=a[d]});const l=(u=t(s))!=null?u:void 0;return p.jsx(ft.button,E(m({type:"button"},o),{ref:i,disabled:o.disabled||!l,onClick:qt(o.onClick,l)}))});return n.displayName=e,n};function df(e,t=globalThis==null?void 0:globalThis.document){const r=At(e);K.useEffect(()=>{const n=a=>{a.key==="Escape"&&r(a)};return t.addEventListener("keydown",n,{capture:!0}),()=>t.removeEventListener("keydown",n,{capture:!0})},[r,t])}var hf=()=>{const e=pe();return y.useCallback(()=>{e.attachment().remove()},[e])},ff=fr("AttachmentPrimitive.Remove",hf),pr=e=>{const t=y.useRef(void 0);return y.useCallback(n=>{t.current&&t.current(),n&&(t.current=e(n))},[e])},As=(e,t)=>{const r=y.useCallback(n=>{if(!e)return;const a=e(),i=()=>{const o=t?t(n):n.offsetHeight;a.setHeight(o)},s=new ResizeObserver(i);return s.observe(n),i(),()=>{s.disconnect(),a.unregister()}},[e,t]);return pr(r)},Ms=y.createContext(!1),Ps=(e,t)=>{const r=e.match(/^([\d.]+)(em|px|rem)$/);if(!r)return 0;const n=parseFloat(r[1]),a=r[2];if(a==="px")return n;if(a==="em"){const i=parseFloat(getComputedStyle(t).fontSize)||16;return n*i}if(a==="rem"){const i=parseFloat(getComputedStyle(document.documentElement).fontSize)||16;return n*i}return 0},Ns=({children:e,fillClampThreshold:t="10em",fillClampOffset:r="6em"})=>{const n=ae(({message:l})=>l.isLast&&l.index>=2),a=Vn({optional:!0}),i=y.useContext(Ms),s=y.useCallback(l=>{if(!a||i)return;const u=()=>{const d=a.getState();if(d.turnAnchor==="top"&&n){const{viewport:c,inset:h,userMessage:f}=d.height,g=Ps(t,l),v=Ps(r,l),b=f<=g?f:v,w=Math.max(0,c-h-b);l.style.minHeight=`${w}px`,l.style.flexShrink="0",l.style.transition="min-height 0s"}else l.style.minHeight="",l.style.flexShrink="",l.style.transition=""};return u(),a.subscribe(u)},[a,n,i,t,r]),o=pr(s);return p.jsx(Ms.Provider,{value:!0,children:p.jsx(Es,{ref:o,children:e})})};Ns.displayName="ThreadPrimitive.ViewportSlack";var pf=()=>{const e=pe(),t=ae(()=>e.message()),r=y.useCallback(n=>{const a=()=>{t.setIsHovering(!0)},i=()=>{t.setIsHovering(!1)};return n.addEventListener("mouseenter",a),n.addEventListener("mouseleave",i),n.matches(":hover")&&t.setIsHovering(!0),()=>{n.removeEventListener("mouseenter",a),n.removeEventListener("mouseleave",i),t.setIsHovering(!1)}},[t]);return pr(r)},mf=()=>{const e=Kr(a=>a.turnAnchor),t=Kr(a=>a.registerUserMessageHeight),r=ae(({thread:a,message:i})=>{var s;return e==="top"&&i.role==="user"&&i.index===a.messages.length-2&&((s=a.messages.at(-1))==null?void 0:s.role)==="assistant"}),n=y.useCallback(a=>a.offsetHeight,[]);return As(r?t:null,n)},ea=y.forwardRef((e,t)=>{const r=pf(),n=mf(),a=Jr(t,r,n);return p.jsx(Ns,{children:p.jsx(ft.div,E(m({},e),{ref:a}))})});ea.displayName="MessagePrimitive.Root";var Ls=()=>ae(({part:t})=>{if(t.type!=="text"&&t.type!=="reasoning")throw new Error("MessagePartText can only be used inside text or reasoning message parts.");return t}),Ds=y.forwardRef((a,n)=>{var i=a,{smooth:e=!0,component:t="span"}=i,r=V(i,["smooth","component"]);const{text:s,status:o}=Ss(Ls(),e);return p.jsx(t,E(m({"data-status":o.type},r),{ref:n,children:s}))});Ds.displayName="MessagePartPrimitive.Text";var gf=()=>ae(({part:t})=>{if(t.type!=="image")throw new Error("MessagePartImage can only be used inside image message parts.");return t}),Os=y.forwardRef((e,t)=>{const{image:r}=gf();return p.jsx(ft.img,E(m({src:r},e),{ref:t}))});Os.displayName="MessagePartPrimitive.Image";var Fs=({children:e})=>ae(({part:r})=>r.status.type==="running")?e:null;Fs.displayName="MessagePartPrimitive.InProgress";const Bs=e=>Symbol.iterator in e,zs=e=>"entries"in e,Rs=(e,t)=>{const r=e instanceof Map?e:new Map(e.entries()),n=t instanceof Map?t:new Map(t.entries());if(r.size!==n.size)return!1;for(const[a,i]of r)if(!n.has(a)||!Object.is(i,n.get(a)))return!1;return!0},yf=(e,t)=>{const r=e[Symbol.iterator](),n=t[Symbol.iterator]();let a=r.next(),i=n.next();for(;!a.done&&!i.done;){if(!Object.is(a.value,i.value))return!1;a=r.next(),i=n.next()}return!!a.done&&!!i.done};function bf(e,t){return Object.is(e,t)?!0:typeof e!="object"||e===null||typeof t!="object"||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:Bs(e)&&Bs(t)?zs(e)&&zs(t)?Rs(e,t):yf(e,t):Rs({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function wf(e){const t=y.useRef(void 0);return r=>{const n=e(r);return bf(t.current,n)?t.current:t.current=n}}var js=e=>{let t=-1;return{startGroup:r=>{t===-1&&(t=r)},endGroup:(r,n)=>{t!==-1&&(n.push({type:e,startIndex:t,endIndex:r}),t=-1)},finalize:(r,n)=>{t!==-1&&n.push({type:e,startIndex:t,endIndex:r})}}},xf=e=>{const t=[],r=js("toolGroup"),n=js("reasoningGroup");for(let a=0;a<e.length;a++){const i=e[a];i==="tool-call"?(n.endGroup(a-1,t),r.startGroup(a)):i==="reasoning"?(r.endGroup(a-1,t),n.startGroup(a)):(r.endGroup(a-1,t),n.endGroup(a-1,t),t.push({type:"single",index:a}))}return r.finalize(e.length-1,t),n.finalize(e.length-1,t),t},vf=()=>{const e=ae(wf(t=>t.message.parts.map(r=>r.type)));return y.useMemo(()=>e.length===0?[]:xf(e),[e])},kf=r=>{var n=r,{Fallback:e}=n,t=V(n,["Fallback"]);const a=ae(({tools:i})=>{var o,l;const s=(o=i.tools[t.toolName])!=null?o:e;return Array.isArray(s)?(l=s[0])!=null?l:e:s});return a?p.jsx(a,m({},t)):null},pt={Text:()=>p.jsxs("p",{style:{whiteSpace:"pre-line"},children:[p.jsx(Ds,{}),p.jsx(Fs,{children:p.jsx("span",{style:{fontFamily:"revert"},children:" ●"})})]}),Reasoning:()=>null,Source:()=>null,Image:()=>p.jsx(Os,{}),File:()=>null,Unstable_Audio:()=>null,ToolGroup:({children:e})=>e,ReasoningGroup:({children:e})=>e},Sf=({components:{Text:e=pt.Text,Reasoning:t=pt.Reasoning,Image:r=pt.Image,Source:n=pt.Source,File:a=pt.File,Unstable_Audio:i=pt.Unstable_Audio,tools:s={}}={}})=>{var d,c,h;const o=pe(),l=ae(({part:f})=>f),u=l.type;if(u==="tool-call"){const f=o.part().addToolResult,g=o.part().resumeToolCall;if("Override"in s)return p.jsx(s.Override,E(m({},l),{addResult:f,resume:g}));const v=(c=(d=s.by_name)==null?void 0:d[l.toolName])!=null?c:s.Fallback;return p.jsx(kf,E(m({},l),{Fallback:v,addResult:f,resume:g}))}if(((h=l.status)==null?void 0:h.type)==="requires-action")throw new Error("Encountered unexpected requires-action status");switch(u){case"text":return p.jsx(e,m({},l));case"reasoning":return p.jsx(t,m({},l));case"source":return p.jsx(n,m({},l));case"image":return p.jsx(r,m({},l));case"file":return p.jsx(a,m({},l));case"audio":return p.jsx(i,m({},l));case"data":return null;default:const f=u;throw new Error(`Unknown message part type: ${f}`)}},en=y.memo(({index:e,components:t})=>p.jsx(gh,{index:e,children:p.jsx(Sf,{components:t})}),(e,t)=>{var r,n,a,i,s,o,l,u,d,c,h,f,g,v,b,w,_,T;return e.index===t.index&&((r=e.components)==null?void 0:r.Text)===((n=t.components)==null?void 0:n.Text)&&((a=e.components)==null?void 0:a.Reasoning)===((i=t.components)==null?void 0:i.Reasoning)&&((s=e.components)==null?void 0:s.Source)===((o=t.components)==null?void 0:o.Source)&&((l=e.components)==null?void 0:l.Image)===((u=t.components)==null?void 0:u.Image)&&((d=e.components)==null?void 0:d.File)===((c=t.components)==null?void 0:c.File)&&((h=e.components)==null?void 0:h.Unstable_Audio)===((f=t.components)==null?void 0:f.Unstable_Audio)&&((g=e.components)==null?void 0:g.tools)===((v=t.components)==null?void 0:v.tools)&&((b=e.components)==null?void 0:b.ToolGroup)===((w=t.components)==null?void 0:w.ToolGroup)&&((_=e.components)==null?void 0:_.ReasoningGroup)===((T=t.components)==null?void 0:T.ReasoningGroup)});en.displayName="MessagePrimitive.PartByIndex";var _f=({status:e,component:t})=>p.jsx(xh,{text:"",isRunning:e.type==="running",children:p.jsx(t,{type:"text",text:"",status:e})}),Tf=Object.freeze({type:"complete"}),Cf=({components:e})=>{var r;const t=ae(n=>{var a;return(a=n.message.status)!=null?a:Tf});return e!=null&&e.Empty?p.jsx(e.Empty,{status:t}):p.jsx(_f,{status:t,component:(r=e==null?void 0:e.Text)!=null?r:pt.Text})},If=y.memo(Cf,(e,t)=>{var r,n,a,i;return((r=e.components)==null?void 0:r.Empty)===((n=t.components)==null?void 0:n.Empty)&&((a=e.components)==null?void 0:a.Text)===((i=t.components)==null?void 0:i.Text)}),ta=({components:e})=>{const t=ae(({message:a})=>a.parts.length),r=vf(),n=y.useMemo(()=>t===0?p.jsx(If,{components:e}):r.map(a=>{var i,s;if(a.type==="single")return p.jsx(en,{index:a.index,components:e},a.index);if(a.type==="toolGroup"){const o=(i=e==null?void 0:e.ToolGroup)!=null?i:pt.ToolGroup;return p.jsx(o,{startIndex:a.startIndex,endIndex:a.endIndex,children:Array.from({length:a.endIndex-a.startIndex+1},(l,u)=>p.jsx(en,{index:a.startIndex+u,components:e},u))},`tool-${a.startIndex}`)}else{const o=(s=e==null?void 0:e.ReasoningGroup)!=null?s:pt.ReasoningGroup;return p.jsx(o,{startIndex:a.startIndex,endIndex:a.endIndex,children:Array.from({length:a.endIndex-a.startIndex+1},(l,u)=>p.jsx(en,{index:a.startIndex+u,components:e},u))},`reasoning-${a.startIndex}`)}}),[r,e,t]);return p.jsx(p.Fragment,{children:n})};ta.displayName="MessagePrimitive.Parts";var Ef=(e,t)=>{var n,a,i;const r=t.type;switch(r){case"image":return(n=e==null?void 0:e.Image)!=null?n:e==null?void 0:e.Attachment;case"document":return(a=e==null?void 0:e.Document)!=null?a:e==null?void 0:e.Attachment;case"file":return(i=e==null?void 0:e.File)!=null?i:e==null?void 0:e.Attachment;default:const s=r;throw new Error(`Unknown attachment type: ${s}`)}},Af=({components:e})=>{const t=ae(({attachment:n})=>n);if(!t)return null;const r=Ef(e,t);return r?p.jsx(r,{}):null},$s=y.memo(({index:e,components:t})=>p.jsx(yh,{index:e,children:p.jsx(Af,{components:t})}),(e,t)=>{var r,n,a,i,s,o,l,u;return e.index===t.index&&((r=e.components)==null?void 0:r.Image)===((n=t.components)==null?void 0:n.Image)&&((a=e.components)==null?void 0:a.Document)===((i=t.components)==null?void 0:i.Document)&&((s=e.components)==null?void 0:s.File)===((o=t.components)==null?void 0:o.File)&&((l=e.components)==null?void 0:l.Attachment)===((u=t.components)==null?void 0:u.Attachment)});$s.displayName="MessagePrimitive.AttachmentByIndex";var Us=({components:e})=>{const t=ae(({message:n})=>n.role!=="user"?0:n.attachments.length);return y.useMemo(()=>Array.from({length:t},(n,a)=>p.jsx($s,{index:a,components:e},a)),[t,e])};Us.displayName="MessagePrimitive.Attachments";var Hs=()=>{const e=pe(),t=ae(n=>n.thread.isRunning||!n.composer.isEditing||n.composer.isEmpty),r=y.useCallback(()=>{e.composer().send()},[e]);return t?null:r},Mf=fr("ComposerPrimitive.Send",Hs),qs=y.forwardRef((n,r)=>{var a=n,{onSubmit:e}=a,t=V(a,["onSubmit"]);const i=Hs(),s=o=>{o.preventDefault(),i&&i()};return p.jsx(ft.form,E(m({},t),{ref:r,onSubmit:qt(e,s)}))});qs.displayName="ComposerPrimitive.Root";function ra(){return ra=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},ra.apply(null,arguments)}function Pf(e,t){if(e==null)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.indexOf(n)!==-1)continue;r[n]=e[n]}return r}var Nf=y.useLayoutEffect,Lf=function(t){var r=y.useRef(t);return Nf(function(){r.current=t}),r},Vs=function(t,r){if(typeof t=="function"){t(r);return}t.current=r},Df=function(t,r){var n=y.useRef();return y.useCallback(function(a){t.current=a,n.current&&Vs(n.current,null),n.current=r,r&&Vs(r,a)},[r])},Ws={"min-height":"0","max-height":"none",height:"0",visibility:"hidden",overflow:"hidden",position:"absolute","z-index":"-1000",top:"0",right:"0",display:"block"},Of=function(t){Object.keys(Ws).forEach(function(r){t.style.setProperty(r,Ws[r],"important")})},Js=Of,Fe=null,Ys=function(t,r){var n=t.scrollHeight;return r.sizingStyle.boxSizing==="border-box"?n+r.borderSize:n-r.paddingSize};function Ff(e,t,r,n){r===void 0&&(r=1),n===void 0&&(n=1/0),Fe||(Fe=document.createElement("textarea"),Fe.setAttribute("tabindex","-1"),Fe.setAttribute("aria-hidden","true"),Js(Fe)),Fe.parentNode===null&&document.body.appendChild(Fe);var a=e.paddingSize,i=e.borderSize,s=e.sizingStyle,o=s.boxSizing;Object.keys(s).forEach(function(h){var f=h;Fe.style[f]=s[f]}),Js(Fe),Fe.value=t;var l=Ys(Fe,e);Fe.value=t,l=Ys(Fe,e),Fe.value="x";var u=Fe.scrollHeight-a,d=u*r;o==="border-box"&&(d=d+a+i),l=Math.max(d,l);var c=u*n;return o==="border-box"&&(c=c+a+i),l=Math.min(c,l),[l,u]}var Ks=function(){},Bf=function(t,r){return t.reduce(function(n,a){return n[a]=r[a],n},{})},zf=["borderBottomWidth","borderLeftWidth","borderRightWidth","borderTopWidth","boxSizing","fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","lineHeight","paddingBottom","paddingLeft","paddingRight","paddingTop","tabSize","textIndent","textRendering","textTransform","width","wordBreak","wordSpacing","scrollbarGutter"],Rf=!!document.documentElement.currentStyle,jf=function(t){var r=window.getComputedStyle(t);if(r===null)return null;var n=Bf(zf,r),a=n.boxSizing;if(a==="")return null;Rf&&a==="border-box"&&(n.width=parseFloat(n.width)+parseFloat(n.borderRightWidth)+parseFloat(n.borderLeftWidth)+parseFloat(n.paddingRight)+parseFloat(n.paddingLeft)+"px");var i=parseFloat(n.paddingBottom)+parseFloat(n.paddingTop),s=parseFloat(n.borderBottomWidth)+parseFloat(n.borderTopWidth);return{sizingStyle:n,paddingSize:i,borderSize:s}},$f=jf;function na(e,t,r){var n=Lf(r);K.useLayoutEffect(function(){var a=function(s){return n.current(s)};if(e)return e.addEventListener(t,a),function(){return e.removeEventListener(t,a)}},[])}var Uf=function(t,r){na(document.body,"reset",function(n){t.current.form===n.target&&r(n)})},Hf=function(t){na(window,"resize",t)},qf=function(t){na(document.fonts,"loadingdone",t)},Vf=["cacheMeasurements","maxRows","minRows","onChange","onHeightChange"],Wf=function(t,r){var n=t.cacheMeasurements,a=t.maxRows,i=t.minRows,s=t.onChange,o=s===void 0?Ks:s,l=t.onHeightChange,u=l===void 0?Ks:l,d=Pf(t,Vf),c=d.value!==void 0,h=K.useRef(null),f=Df(h,r),g=K.useRef(0),v=K.useRef(),b=function(){var T=h.current,B=n&&v.current?v.current:$f(T);if(B){v.current=B;var j=Ff(B,T.value||T.placeholder||"x",i,a),I=j[0],z=j[1];g.current!==I&&(g.current=I,T.style.setProperty("height",I+"px","important"),u(I,{rowHeight:z}))}},w=function(T){c||b(),o(T)};return K.useLayoutEffect(b),Uf(h,function(){if(!c){var _=h.current.value;requestAnimationFrame(function(){var T=h.current;T&&_!==T.value&&b()})}}),Hf(b),qf(b),K.createElement("textarea",ra({},d,{onChange:w,ref:f}))},Jf=K.forwardRef(Wf),Gs=e=>{const t=At(e),r=Kr(n=>n.onScrollToBottom);y.useEffect(()=>r(t),[r,t])},Xs=y.forwardRef((g,f)=>{var v=g,{autoFocus:e=!1,asChild:t,disabled:r,onChange:n,onKeyDown:a,onPaste:i,submitOnEnter:s=!0,cancelOnEscape:o=!0,unstable_focusOnRunStart:l=!0,unstable_focusOnScrollToBottom:u=!0,unstable_focusOnThreadSwitched:d=!0,addAttachmentOnPaste:c=!0}=v,h=V(v,["autoFocus","asChild","disabled","onChange","onKeyDown","onPaste","submitOnEnter","cancelOnEscape","unstable_focusOnRunStart","unstable_focusOnScrollToBottom","unstable_focusOnThreadSwitched","addAttachmentOnPaste"]);const b=pe(),w=ae(({composer:S})=>S.isEditing?S.text:""),_=t?Es:Jf,T=ae(({thread:S})=>S.isDisabled)||r,B=y.useRef(null),j=Jr(f,B);df(S=>{var M;if(!o||!((M=B.current)!=null&&M.contains(S.target)))return;const N=b.composer();N.getState().canCancel&&(N.cancel(),S.preventDefault())});const I=S=>{var N,M;T||!s||S.nativeEvent.isComposing||S.key==="Enter"&&S.shiftKey===!1&&(b.thread().getState().isRunning||(S.preventDefault(),(M=(N=B.current)==null?void 0:N.closest("form"))==null||M.requestSubmit()))},z=S=>P(null,null,function*(){var W;if(!c)return;const N=b.thread().getState().capabilities,M=Array.from(((W=S.clipboardData)==null?void 0:W.files)||[]);if(N.attachments&&M.length>0)try{S.preventDefault(),yield Promise.all(M.map(R=>b.composer().addAttachment(R)))}catch(R){console.error("Error adding attachment:",R)}}),H=e&&!T,O=y.useCallback(()=>{const S=B.current;!S||!H||(S.focus({preventScroll:!0}),S.setSelectionRange(S.value.length,S.value.length))},[H]);return y.useEffect(()=>O(),[O]),Gs(()=>{b.composer().getState().type==="thread"&&u&&O()}),y.useEffect(()=>{if(!(b.composer().getState().type!=="thread"||!l))return b.on("thread.run-start",O)},[l,O,b]),y.useEffect(()=>{if(!(b.composer().getState().type!=="thread"||!d))return b.on("thread-list-item.switched-to",O)},[d,O,b]),p.jsx(_,E(m({name:"input",value:w},h),{ref:j,disabled:T,onChange:qt(n,S=>{b.composer().getState().isEditing&&(b.composer().setText(S.target.value),b.flushSync())}),onKeyDown:qt(a,I),onPaste:qt(i,z)}))});Xs.displayName="ComposerPrimitive.Input";var Yf=({multiple:e=!0}={})=>{const t=ae(({composer:a})=>!a.isEditing),r=pe(),n=y.useCallback(()=>{const a=document.createElement("input");a.type="file",a.multiple=e,a.hidden=!0;const i=r.composer().getState().attachmentAccept;i!=="*"&&(a.accept=i),document.body.appendChild(a),a.onchange=s=>{const o=s.target.files;if(o){for(const l of o)r.composer().addAttachment(l);document.body.removeChild(a)}},a.oncancel=()=>{(!a.files||a.files.length===0)&&document.body.removeChild(a)},a.click()},[r,e]);return t?null:n},Kf=fr("ComposerPrimitive.AddAttachment",Yf,["multiple"]),Gf=(e,t)=>{var n,a,i;const r=t.type;switch(r){case"image":return(n=e==null?void 0:e.Image)!=null?n:e==null?void 0:e.Attachment;case"document":return(a=e==null?void 0:e.Document)!=null?a:e==null?void 0:e.Attachment;case"file":return(i=e==null?void 0:e.File)!=null?i:e==null?void 0:e.Attachment;default:const s=r;throw new Error(`Unknown attachment type: ${s}`)}},Xf=({components:e})=>{const t=ae(({attachment:n})=>n);if(!t)return null;const r=Gf(e,t);return r?p.jsx(r,{}):null},Qs=y.memo(({index:e,components:t})=>p.jsx(bh,{index:e,children:p.jsx(Xf,{components:t})}),(e,t)=>{var r,n,a,i,s,o,l,u;return e.index===t.index&&((r=e.components)==null?void 0:r.Image)===((n=t.components)==null?void 0:n.Image)&&((a=e.components)==null?void 0:a.Document)===((i=t.components)==null?void 0:i.Document)&&((s=e.components)==null?void 0:s.File)===((o=t.components)==null?void 0:o.File)&&((l=e.components)==null?void 0:l.Attachment)===((u=t.components)==null?void 0:u.Attachment)});Qs.displayName="ComposerPrimitive.AttachmentByIndex";var Zs=({components:e})=>{const t=ae(n=>n.composer.attachments.length);return y.useMemo(()=>Array.from({length:t},(n,a)=>p.jsx(Qs,{index:a,components:e},a)),[t,e])};Zs.displayName="ComposerPrimitive.Attachments";var eo=y.forwardRef((e,t)=>p.jsx(ft.div,E(m({},e),{ref:t})));eo.displayName="ThreadPrimitive.Root";var to=({children:e})=>ae(({thread:r})=>r.messages.length===0&&!r.isLoading)?e:null;to.displayName="ThreadPrimitive.Empty";var Qf=e=>{const t=At(e),r=y.useCallback(n=>{const a=new ResizeObserver(()=>{t()}),i=new MutationObserver(()=>{t()});return a.observe(n),i.observe(n,{childList:!0,subtree:!0,attributes:!0,characterData:!0}),()=>{a.disconnect(),i.disconnect()}},[t]);return pr(r)},Zf=({autoScroll:e,scrollToBottomOnRunStart:t=!0,scrollToBottomOnInitialize:r=!0,scrollToBottomOnThreadSwitch:n=!0})=>{const a=y.useRef(null),i=Vn();e===void 0&&(e=i.getState().turnAnchor!=="top");const s=y.useRef(0),o=y.useRef(null),l=y.useCallback(f=>{const g=a.current;g&&(o.current=f,g.scrollTo({top:g.scrollHeight,behavior:f}))},[]),u=()=>{const f=a.current;if(!f)return;const g=i.getState().isAtBottom,v=Math.abs(f.scrollHeight-f.scrollTop-f.clientHeight)<1||f.scrollHeight<=f.clientHeight;!v&&s.current<f.scrollTop||(v&&(o.current=null),(v||o.current===null)&&v!==g&&hr(i).setState({isAtBottom:v})),s.current=f.scrollTop},d=Qf(()=>{const f=o.current;f?l(f):e&&i.getState().isAtBottom&&l("instant"),u()}),c=pr(f=>(f.addEventListener("scroll",u),()=>{f.removeEventListener("scroll",u)}));return Gs(({behavior:f})=>{l(f)}),qn("thread.run-start",()=>{t&&(o.current="auto",requestAnimationFrame(()=>{l("auto")}))}),qn("thread.initialize",()=>{r&&(o.current="instant",requestAnimationFrame(()=>{l("instant")}))}),qn("thread-list-item.switched-to",()=>{n&&(o.current="instant",requestAnimationFrame(()=>{l("instant")}))}),Jr(d,c,a)},ep=()=>{const e=Kr(r=>r.registerViewport),t=y.useCallback(r=>r.clientHeight,[]);return As(e,t)},ro=y.forwardRef((o,s)=>{var l=o,{autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:r,scrollToBottomOnThreadSwitch:n,children:a}=l,i=V(l,["autoScroll","scrollToBottomOnRunStart","scrollToBottomOnInitialize","scrollToBottomOnThreadSwitch","children"]);const u=Zf({autoScroll:e,scrollToBottomOnRunStart:t,scrollToBottomOnInitialize:r,scrollToBottomOnThreadSwitch:n}),d=ep(),c=Jr(s,u,d);return p.jsx(ft.div,E(m({},i),{ref:c,children:a}))});ro.displayName="ThreadPrimitive.ViewportScrollable";var no=y.forwardRef((n,r)=>{var a=n,{turnAnchor:e}=a,t=V(a,["turnAnchor"]);return p.jsx(fs,{options:{turnAnchor:e},children:p.jsx(ro,E(m({},t),{ref:r}))})});no.displayName="ThreadPrimitive.Viewport";var ao=(e,t)=>e.Message===t.Message&&e.EditComposer===t.EditComposer&&e.UserEditComposer===t.UserEditComposer&&e.AssistantEditComposer===t.AssistantEditComposer&&e.SystemEditComposer===t.SystemEditComposer&&e.UserMessage===t.UserMessage&&e.AssistantMessage===t.AssistantMessage&&e.SystemMessage===t.SystemMessage,tp=()=>null,rp=(e,t,r)=>{var n,a,i,s,o,l,u,d,c,h,f,g;switch(t){case"user":return r?(i=(a=(n=e.UserEditComposer)!=null?n:e.EditComposer)!=null?a:e.UserMessage)!=null?i:e.Message:(s=e.UserMessage)!=null?s:e.Message;case"assistant":return r?(u=(l=(o=e.AssistantEditComposer)!=null?o:e.EditComposer)!=null?l:e.AssistantMessage)!=null?u:e.Message:(d=e.AssistantMessage)!=null?d:e.Message;case"system":return r?(f=(h=(c=e.SystemEditComposer)!=null?c:e.EditComposer)!=null?h:e.SystemMessage)!=null?f:e.Message:(g=e.SystemMessage)!=null?g:tp;default:const v=t;throw new Error(`Unknown message role: ${v}`)}},np=({components:e})=>{const t=ae(({message:a})=>a.role),r=ae(({message:a})=>a.composer.isEditing),n=rp(e,t,r);return p.jsx(n,{})},io=y.memo(({index:e,components:t})=>p.jsx(mh,{index:e,children:p.jsx(np,{components:t})}),(e,t)=>e.index===t.index&&ao(e.components,t.components));io.displayName="ThreadPrimitive.MessageByIndex";var so=({components:e})=>{const t=ae(({thread:n})=>n.messages.length);return y.useMemo(()=>t===0?null:Array.from({length:t},(n,a)=>p.jsx(io,{index:a,components:e},a)),[t,e])};so.displayName="ThreadPrimitive.Messages";var ap=y.memo(so,(e,t)=>ao(e.components,t.components)),oo=y.forwardRef((a,n)=>{var i=a,{onClick:e,disabled:t}=i,r=V(i,["onClick","disabled"]);const s=ae(({threads:l})=>l.newThreadId===l.mainThreadId),o=pe();return p.jsx(ft.button,E(m(m({type:"button"},s?{"data-active":"true","aria-current":"true"}:null),r),{ref:n,disabled:t,onClick:qt(e,()=>{o.threads().switchToNewThread()})}))});oo.displayName="ThreadListPrimitive.New";var lo=y.memo(({index:e,archived:t=!1,components:r})=>{const n=r.ThreadListItem;return p.jsx(fh,{index:e,archived:t,children:p.jsx(n,{})})},(e,t)=>e.index===t.index&&e.archived===t.archived&&e.components.ThreadListItem===t.components.ThreadListItem);lo.displayName="ThreadListPrimitive.ItemByIndex";var uo=({archived:e=!1,components:t})=>{const r=ae(({threads:a})=>e?a.archivedThreadIds.length:a.threadIds.length);return y.useMemo(()=>Array.from({length:r},(a,i)=>p.jsx(lo,{index:i,archived:e,components:t},i)),[r,e,t])};uo.displayName="ThreadListPrimitive.Items";var co=y.forwardRef((e,t)=>p.jsx(ft.div,E(m({},e),{ref:t})));co.displayName="ThreadListPrimitive.Root";var ho=y.forwardRef((e,t)=>{const r=ae(({threads:n,threadListItem:a})=>n.mainThreadId===a.id);return p.jsx(ft.div,E(m(m({},r?{"data-active":"true","aria-current":"true"}:null),e),{ref:t}))});ho.displayName="ThreadListItemPrimitive.Root";var ip=()=>{const e=pe();return y.useCallback(()=>{e.threadListItem().delete()},[e])},sp=fr("ThreadListItemPrimitive.Delete",ip),op=()=>{const e=pe();return y.useCallback(()=>{e.threadListItem().switchTo()},[e])},lp=fr("ThreadListItemPrimitive.Trigger",op);function up(){if(typeof crypto!="undefined"&&crypto.randomUUID)return crypto.randomUUID();if(typeof crypto!="undefined"&&crypto.getRandomValues){const e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=Array.from(e,r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`}class fo{constructor(t,r,n=!1){C(this,"baseUrl");C(this,"sessionToken",null);C(this,"isProxyMode",!1);this.baseUrl=t.replace(/\/$/,""),this.isProxyMode=n,r&&(this.sessionToken=r)}setSessionToken(t){this.sessionToken=t}getUrl(t){if(this.isProxyMode){const r=`${this.baseUrl}${t.replace("/v1","")}`;return r.startsWith("/")||r.startsWith("./"),r}return`${this.baseUrl}${t}`}createOrContinueChat(t,r){return P(this,null,function*(){const n=this.getUrl("/v1/chats"),i={"Content-Type":"application/json",Accept:"text/event-stream","Accept-Encoding":"identity","Cache-Control":"no-cache","X-Accel-Buffering":"no","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(i.Authorization=`Bearer ${this.sessionToken}`);const s=E(m({},t),{stream:!0}),o=yield fetch(n,{method:"POST",headers:i,body:JSON.stringify(s),signal:r,cache:"no-store"});if(!o.ok){const l=yield o.json().catch(()=>({}));throw new Error(l.detail||l.message||`API error: ${o.status} ${o.statusText}`)}if(!o.body)throw new Error("Response body is null");return o.body})}getChat(t){return P(this,null,function*(){const r=this.getUrl(`/v1/chats/${t}`),n={"Content-Type":"application/json"};this.sessionToken&&(n.Authorization=`Bearer ${this.sessionToken}`);const a=yield fetch(r,{method:"GET",headers:n});if(!a.ok){const i=yield a.json().catch(()=>({}));throw new Error(i.detail||i.message||`API error: ${a.status} ${a.statusText}`)}return a.json()})}listChats(t){return P(this,null,function*(){const r=this.getUrl("/v1/chats"),n=r.startsWith("/")||r.startsWith("./")?new URL(r,window.location.origin):new URL(r);t!=null&&t.limit&&n.searchParams.set("limit",t.limit.toString()),t!=null&&t.cursor&&n.searchParams.set("cursor",t.cursor),t!=null&&t["expand[]"]&&t["expand[]"].forEach(s=>{n.searchParams.append("expand[]",s)});const a={"Content-Type":"application/json"};this.sessionToken&&(a.Authorization=`Bearer ${this.sessionToken}`);const i=yield fetch(n.toString(),{method:"GET",headers:a});if(!i.ok){const s=yield i.json().catch(()=>({}));throw new Error(s.detail||s.message||`API error: ${i.status} ${i.statusText}`)}return i.json()})}generateIdempotencyKey(){return up()}updateChat(t,r){return P(this,null,function*(){const n=`/v1/chats/${t}`,a=this.getUrl(n),i=a.startsWith("/")||a.startsWith("./")?new URL(a,window.location.origin):new URL(a),o={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(o.Authorization=`Bearer ${this.sessionToken}`);const l=yield fetch(i.toString(),{method:"PATCH",headers:o,body:JSON.stringify(r)});if(!l.ok){const d=yield l.text();let c={};try{c=JSON.parse(d)}catch(h){c={detail:d}}throw new Error(c.detail||c.message||`API error: ${l.status} ${l.statusText}`)}if(l.status===204)return{};const u=yield l.text();if(!u)return{};try{return JSON.parse(u)}catch(d){return{}}})}deleteChat(t){return P(this,null,function*(){const r=`/v1/chats/${t}`,n=this.getUrl(r),a=n.startsWith("/")||n.startsWith("./")?new URL(n,window.location.origin):new URL(n),s={"Content-Type":"application/json","Idempotency-Key":this.generateIdempotencyKey()};this.sessionToken&&(s.Authorization=`Bearer ${this.sessionToken}`);const o=yield fetch(a.toString(),{method:"DELETE",headers:s});if(!o.ok){const l=yield o.json().catch(()=>({}));throw new Error(l.detail||l.message||`API error: ${o.status} ${o.statusText}`)}})}listModels(t){return P(this,null,function*(){const r=this.getUrl("/v1/models"),n=r.startsWith("/")||r.startsWith("./")?new URL(r,window.location.origin):new URL(r);t!=null&&t.limit&&n.searchParams.set("limit",t.limit.toString()),t!=null&&t.cursor&&n.searchParams.set("cursor",t.cursor),t!=null&&t["expand[]"]&&t["expand[]"].forEach(s=>{n.searchParams.append("expand[]",s)});const a={"Content-Type":"application/json"};this.sessionToken&&(a.Authorization=`Bearer ${this.sessionToken}`);const i=yield fetch(n.toString(),{method:"GET",headers:a});if(!i.ok){const s=yield i.json().catch(()=>({}));throw new Error(s.detail||s.message||`API error: ${i.status} ${i.statusText}`)}return i.json()})}getModel(t){return P(this,null,function*(){const r=this.getUrl(`/v1/models/${t}`),n={"Content-Type":"application/json"};this.sessionToken&&(n.Authorization=`Bearer ${this.sessionToken}`);const a=yield fetch(r,{method:"GET",headers:n});if(!a.ok){const i=yield a.json().catch(()=>({}));throw new Error(i.detail||i.message||`API error: ${a.status} ${a.statusText}`)}return a.json()})}uploadFile(t,r,n){return P(this,null,function*(){const a=this.getUrl("/v1/files"),i=this.generateIdempotencyKey(),s=new FormData;s.append("file",t),r&&s.append("resource_type",r),n&&s.append("resource_id",n);const o={"Idempotency-Key":i};this.sessionToken&&(o.Authorization=`Bearer ${this.sessionToken}`);const l=yield fetch(a,{method:"POST",headers:o,body:s});if(!l.ok){const u=yield l.json().catch(()=>({}));throw new Error(u.detail||u.message||`API error: ${l.status} ${l.statusText}`)}return l.json()})}}function cp(e,t){return Nr(this,null,function*(){const r=e.getReader(),n=new TextDecoder;let a="";try{for(;;){if(t!=null&&t.aborted){r.cancel();break}const{done:i,value:s}=yield new Ee(r.read());if(i)break;a+=n.decode(s,{stream:!0});const o=a.split(`
6
6
 
7
- `);a=o.pop()||"";for(const l of o)if(l.startsWith("data: ")){const u=l.slice(6);if(u.trim()==="[DONE]"){yield{done:!0};continue}try{yield JSON.parse(u)}catch(d){}}}}finally{r.releaseLock()}})}function cp(e){return e.map(t=>{let r="";if(typeof t.content=="string")r=t.content;else if(Array.isArray(t.content)){const n=t.content.find(a=>a.type==="text");n&&typeof n=="object"&&"text"in n&&(r=n.text)}return{role:t.role,content:r}})}function dp(e){return m(m({id:e.id,role:e.role,content:[{type:"text",text:e.content}],createdAt:new Date(e.createdAt),metadata:{custom:{}}},e.role==="assistant"&&{status:{type:"complete",reason:"stop"},metadata:{unstable_state:null,unstable_annotations:[],unstable_data:[],steps:[],custom:{}}}),e.role==="user"&&{attachments:[]})}const en=new Map;function hp(e,t){return{list(){return P(this,null,function*(){const n=[];let i,s=0;do{const l=yield e.listChats({limit:50,cursor:i}),u=l.items||[];Array.isArray(u)&&u.length>0&&n.push(...u),i=l.nextCursor||void 0,s++}while(i&&s<50);return{threads:n.map(l=>{const u=l.id;return!u||l.deletedAt?null:{status:"regular",remoteId:u,title:l.title||"New Chat",createdAt:l.createdAt?new Date(l.createdAt):new Date,updatedAt:l.updatedAt?new Date(l.updatedAt):new Date}}).filter(l=>l!==null)}})},initialize(n){return P(this,null,function*(){return{remoteId:en.get(n)||n,externalId:void 0}})},rename(n,a){return P(this,null,function*(){yield e.updateChat(n,{title:a})})},archive(n){return P(this,null,function*(){})},unarchive(n){return P(this,null,function*(){})},delete(n){return P(this,null,function*(){yield e.deleteChat(n)})},generateTitle(n,a){return P(this,null,function*(){return new ReadableStream})},fetch(n){return P(this,null,function*(){try{const a=yield e.getChat(n);return{status:"regular",remoteId:a.id||n,title:a.title||"Chat",createdAt:a.createdAt?new Date(a.createdAt):new Date,updatedAt:a.updatedAt?new Date(a.updatedAt):new Date}}catch(a){return{status:"regular",remoteId:n,createdAt:new Date,updatedAt:new Date}}})},updateRemoteId(n,a){en.set(n,a),t==null||t(n,a)},unstable_Provider:({children:n})=>{const a=us(),i=a==null?void 0:a.remoteId,s=y.useMemo(()=>({load(){return P(this,null,function*(){if(!i)return{messages:[]};try{const u=yield e.getChat(i);return!u.messages||u.messages.length===0?{messages:[]}:{messages:u.messages.map(c=>dp(c))}}catch(u){return{messages:[]}}})},append(u){return P(this,null,function*(){})}}),[i,e]),o=y.useMemo(()=>({history:s}),[s]);return p.jsx(Bn,{adapters:o,children:n})}}}class fp{constructor(){C(this,"messageMetadata",new Map);C(this,"currentMessageId",null);C(this,"listeners",new Set)}setCurrentMessage(t){this.currentMessageId=t}update(t){if(!this.currentMessageId)return;const r=this.messageMetadata.get(this.currentMessageId)||{},n=t.sources;n&&n.length>0&&(this.messageMetadata.set(this.currentMessageId,E(m({},r),{sources:n})),this.notify())}get(){return this.currentMessageId?this.messageMetadata.get(this.currentMessageId)||{}:{}}getForMessage(t){return this.messageMetadata.get(t)||{}}getCurrentMessageId(){return this.currentMessageId}clear(){this.currentMessageId=null}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}notify(){this.listeners.forEach(t=>t())}}const wt=new fp,fo=new Map,aa=[];let tn=[];function po(e,t,r=50,n=800){aa.push({question:e,response:t,streamingSpeed:r,initialDelay:n})}function mo(e,t){const{modelId:r,systemPrompt:n,ephemeral:a,enableReasoning:i,onChatCreated:s,onUserMessage:o,onThreadIdUpdate:l,onBeforeRequest:u,mockResponseOnBlocked:d}=t;let c;return{run(f){return Pr(this,null,function*(){var de,x,se,we;const{messages:g,abortSignal:v,context:b}=f,w=aa.shift();if(w){o==null||o();const W=(de=w.initialDelay)!=null?de:800;if(W>0&&(yield new Ne(new Promise(he=>setTimeout(he,W)))),v!=null&&v.aborted)throw new Error("Request aborted");const ie=w.response.split(" ");let be="";const ve=w.streamingSpeed||50,Me=`premade-${Date.now()}`;a&&(s==null||s(Me));for(let he=0;he<ie.length;he++){if(v!=null&&v.aborted)throw new Error("Request aborted");be+=(he===0?"":" ")+ie[he],yield{content:[{type:"text",text:be}]},yield new Ne(new Promise(Pe=>setTimeout(Pe,ve+Math.random()*(ve*.5))))}yield{content:[{type:"text",text:be}]},tn.push({role:"user",content:w.question},{role:"assistant",content:w.response});return}const T=b==null?void 0:b.threadId;let _=T;if(!_&&g.length>0){const W=g.find(ie=>ie.role==="user");W&&(_=(typeof W.content=="string"?W.content:Array.isArray(W.content)&&((x=W.content.find(be=>be.type==="text"))==null?void 0:x.text)||"").substring(0,50))}let D;T&&(D=en.get(T)),!D&&_&&(D=fo.get(_)),!D&&c&&(D=c),o==null||o();let z=g,I=-1;for(let W=g.length-1;W>=0;W--)if(g[W].role==="assistant"){I=W;break}(D||I>=0)&&I>=0&&(z=g.slice(I+1));const B=cp(z);if(tn.length>0&&!D){const W=tn.map(ie=>({role:ie.role,content:ie.content}));B.unshift(...W),tn=[]}const H={messages:B,chatId:D||null,systemPrompt:n,ephemeral:a,enableReasoning:i,stream:!0};if(r&&r.trim()!==""&&(H.modelId=r),u&&!(yield new Ne(u()))){if(d){const ie=typeof d=="function"?d():d,be=g.filter(Pe=>Pe.role==="user"),ve=be.length>0?be[be.length-1]:void 0;let Me="Message";if(ve){if(typeof ve.content=="string")Me=ve.content;else if(Array.isArray(ve.content)){const Pe=ve.content.find(kt=>kt.type==="text");Me=(Pe==null?void 0:Pe.text)||"Message"}}po(Me,ie,40,400);const he=aa.shift();if(he){o==null||o();const Pe=(se=he.initialDelay)!=null?se:400;if(Pe>0&&(yield new Ne(new Promise(ke=>setTimeout(ke,Pe)))),v!=null&&v.aborted)throw new Error("Request aborted");const kt=he.response.split(" ");let st="";const dt=he.streamingSpeed||40,Dt=`mock-${Date.now()}`;a&&(s==null||s(Dt));for(let ke=0;ke<kt.length;ke++){if(v!=null&&v.aborted)throw new Error("Request aborted");st+=(ke===0?"":" ")+kt[ke],yield{content:[{type:"text",text:st}]},yield new Ne(new Promise(Qt=>setTimeout(Qt,dt+Math.random()*(dt*.3))))}yield{content:[{type:"text",text:st}]};return}}throw new Error("Request blocked")}const j=yield new Ne(e.createOrContinueChat(H,v));let S="",N="",M;const U=[];let R=0,F=!1;const Q=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;wt.clear(),wt.setCurrentMessage(Q);const ue=()=>{U.length!==R&&(R=U.length,wt.update({sources:U.length>0?[...U]:void 0}))},pe=()=>{ue();const W=[];return N&&W.push({type:"reasoning",text:N}),S&&W.push({type:"text",text:S}),W.length===0&&W.push({type:"text",text:""}),{content:W}};try{for(var k=Ft(up(j,v)),xe,Ue,ye;xe=!(Ue=yield new Ne(k.next())).done;xe=!1){const W=Ue.value;if(v!=null&&v.aborted)throw new Error("Request aborted");const ie=W.id||W.chatId||W.messageId;ie&&!M&&(M=ie,c=ie,s==null||s(ie),T&&l&&(l(T,ie),en.set(T,ie)),_&&fo.set(_,ie));const be=W.sources;if(be&&Array.isArray(be)&&be.length>0)for(const he of be)U.some(Pe=>Pe.sourceId===he.sourceId)||U.push({sourceId:he.sourceId,filename:he.filename||"Unknown",score:(we=he.score)!=null?we:1,chunkId:he.chunkId,datasetId:he.datasetId});const ve=W.reasoning;if(ve&&ve.length>0&&(N+=ve,yield pe()),W.type)switch(W.type){case"source-document":W.sourceId&&U.push({sourceId:W.sourceId,filename:W.title||"Unknown",score:1});continue;case"reasoning-start":continue;case"reasoning-delta":W.delta&&(N+=W.delta),(S||N)&&(yield pe());continue;case"reasoning-end":(S||N)&&(yield pe());continue;case"text-delta":W.delta&&(N&&!F&&!S&&(F=!0,yield new Ne(new Promise(he=>setTimeout(he,400)))),S+=W.delta),S&&(yield pe());continue;case"error":throw new Error(W.errorText||"Stream error");case"text-start":case"text-end":case"start":case"start-step":case"finish-step":case"finish":continue}const Me=W.delta;if(Me!=null&&(N&&!F&&!S&&(F=!0,yield new Ne(new Promise(he=>setTimeout(he,400)))),S+=Me),W.content&&(S+=W.content),W.message&&(S+=W.message.content||""),W.finished){(S||N||U.length>0)&&(yield pe());break}(S||N||U.length>0)&&(yield pe())}}catch(Ue){ye=[Ue]}finally{try{xe&&(Ue=k.return)&&(yield new Ne(Ue.call(k)))}finally{if(ye)throw ye[0]}}(S||N||U.length>0)&&(yield pe())})}}}class rn extends Error{constructor(t,r,n){super(t),this.code=r,this.file=n,this.name="AttachmentValidationError"}}const pp=["image/jpeg","image/png","image/gif","image/webp","image/svg+xml","application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","text/plain","text/markdown","text/csv","application/json"],mp=[".pdf",".doc",".docx",".xls",".xlsx",".txt",".md",".csv",".json",".jpg",".jpeg",".png",".gif",".webp",".svg"],gp=10*1024*1024;function go(e){if(e===0)return"0 Bytes";const t=1024,r=["Bytes","KB","MB","GB"],n=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,n)).toFixed(2))+" "+r[n]}function yp(e){return e.lastIndexOf(".")>=0?e.slice(e.lastIndexOf(".")).toLowerCase():""}function bp(e,t){const n={"image/jpeg":[".jpg",".jpeg"],"image/png":[".png"],"image/gif":[".gif"],"image/webp":[".webp"],"image/svg+xml":[".svg"],"application/pdf":[".pdf"],"text/plain":[".txt"],"text/markdown":[".md"],"text/csv":[".csv"],"application/json":[".json"]}[e];return n?n.includes(t.toLowerCase()):!0}function wp(){return typeof crypto!="undefined"&&crypto.randomUUID?"attachment-"+crypto.randomUUID():"attachment-"+Date.now()+"-"+Math.random().toString(36).slice(2,11)}function yo(e={}){const{validation:t={},onValidationError:r,onAttachmentAdded:n,onAttachmentRemoved:a}=e,{maxFileSizeBytes:i=gp,allowedMimeTypes:s=pp,allowedExtensions:o=mp,validateContentType:l=!0}=t,u=o.join(",");function d(h){if(h.size>i){const g=new rn('File "'+h.name+'" is too large ('+go(h.size)+"). Maximum size is "+go(i)+".","FILE_TOO_LARGE",h);throw r==null||r(g),g}const f=yp(h.name);if(f&&!o.some(g=>g.toLowerCase()===f)){const g=new rn('File type "'+f+'" is not allowed. Allowed types: '+o.join(", "),"INVALID_TYPE",h);throw r==null||r(g),g}if(h.type&&!s.some(g=>{if(g.endsWith("/*")){const v=g.slice(0,-1);return h.type.startsWith(v)}return h.type===g})){const g=new rn('File type "'+h.type+'" is not allowed.',"INVALID_TYPE",h);throw r==null||r(g),g}if(l&&h.type&&f&&!bp(h.type,f)){const g=new rn('File extension "'+f+'" does not match content type "'+h.type+'".',"VALIDATION_FAILED",h);throw r==null||r(g),g}}return{accept:u,add(f){return P(this,arguments,function*({file:h}){d(h);let g="file";h.type.startsWith("image/")?g="image":(h.type.includes("pdf")||h.type.includes("document")||h.type.includes("text")||h.name.endsWith(".pdf")||h.name.endsWith(".docx")||h.name.endsWith(".txt")||h.name.endsWith(".md")||h.name.endsWith(".csv")||h.name.endsWith(".json"))&&(g="document");const v={id:wp(),type:g,name:h.name,contentType:h.type,file:h,status:{type:"requires-action",reason:"composer-send"}};return n==null||n(v),v})},remove(h){return P(this,null,function*(){a==null||a(h.id)})},send(h){return P(this,null,function*(){if(h.type==="image"&&h.file){const f=yield new Promise((g,v)=>{const b=new FileReader;b.onload=()=>g(b.result),b.onerror=()=>v(new Error("Failed to read file")),b.readAsDataURL(h.file)});return E(m({},h),{status:{type:"complete"},content:[{type:"image",image:f}]})}return E(m({},h),{status:{type:"complete"},content:[]})})}}}function xp({children:e,baseUrl:t,sessionToken:r,isProxyMode:n=!1,mode:a="multiChat",modelId:i,onModelChange:s,ephemeral:o=!1,systemPrompt:l,enableReasoning:u=!1,initialThreadId:d,onError:c,onChatCreated:h,onUserMessage:f,onThreadIdUpdate:g,onChatsLoaded:v,enableAttachments:b=!1,onBeforeRequest:w,mockResponseOnBlocked:T}){const _=y.useMemo(()=>new ho(t,r||void 0,n),[t,r,n]),[D,z]=y.useState(i||null);y.useEffect(()=>{i&&z(i)},[i]);const I=y.useCallback(j=>{h==null||h(j)},[h]),B=y.useCallback((j,S)=>{g==null||g(j,S)},[g]),H=y.useMemo(()=>mo(_,{modelId:D||void 0,systemPrompt:l,ephemeral:o,enableReasoning:u,onChatCreated:I,onUserMessage:f,onBeforeRequest:w,mockResponseOnBlocked:T}),[_,D,l,o,u,I,f,w,T]);return a==="singleChat"?p.jsx(vp,{modelAdapter:H,enableAttachments:b,children:e}):p.jsx(kp,{client:_,modelAdapterOptions:{modelId:D||void 0,systemPrompt:l,ephemeral:o,enableReasoning:u,onChatCreated:I,onUserMessage:f,onBeforeRequest:w,mockResponseOnBlocked:T},initialThreadId:d,onChatsLoaded:v,onThreadIdUpdate:B,onError:c,enableAttachments:b,children:e})}function vp({modelAdapter:e,enableAttachments:t,children:r}){const n=y.useMemo(()=>t?yo():void 0,[t]),a=ws(e,{adapters:m({},n&&{attachments:n})});return p.jsx(fs,{runtime:a,children:r})}function kp({client:e,modelAdapterOptions:t,initialThreadId:r,onChatsLoaded:n,onThreadIdUpdate:a,onError:i,enableAttachments:s,children:o}){const l=y.useMemo(()=>hp(e,(v,b)=>{a==null||a(v,b)}),[e,a]),u=y.useCallback((v,b)=>{l.updateRemoteId&&l.updateRemoteId(v,b),a==null||a(v,b)},[l,a]),d=y.useMemo(()=>E(m({},l),{list(){return P(this,null,function*(){const b=yield l.list();return n==null||n(),b})}}),[l,n]);y.useEffect(()=>{window.__cuadraThreadListAdapter=d,window.__cuadraThreadListRuntime=null},[d]);const c=y.useMemo(()=>mo(e,E(m({},t),{onThreadIdUpdate:u})),[e,t,u]),h=y.useMemo(()=>s?yo():void 0,[s]),f=y.useCallback(()=>ws(c,{adapters:m({},h&&{attachments:h})}),[c,h]),g=_s({adapter:d,runtimeHook:f});return y.useEffect(()=>{window.__cuadraThreadListRuntime=g},[g]),p.jsx(fs,{runtime:g,children:o})}function jv(){}function $v(){}function Sp(e,t){const r={};return(e[e.length-1]===""?[...e,""]:e).join((r.padRight?" ":"")+","+(r.padLeft===!1?"":" ")).trim()}const _p=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Tp=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Cp={};function bo(e,t){return(Cp.jsx?Tp:_p).test(e)}const Ip=/[ \t\n\f\r]/g;function Ep(e){return typeof e=="object"?e.type==="text"?wo(e.value):!1:wo(e)}function wo(e){return e.replace(Ip,"")===""}class mr{constructor(t,r,n){this.normal=r,this.property=t,n&&(this.space=n)}}mr.prototype.normal={},mr.prototype.property={},mr.prototype.space=void 0;function xo(e,t){const r={},n={};for(const a of e)Object.assign(r,a.property),Object.assign(n,a.normal);return new mr(r,n,t)}function ia(e){return e.toLowerCase()}class je{constructor(t,r){this.attribute=r,this.property=t}}je.prototype.attribute="",je.prototype.booleanish=!1,je.prototype.boolean=!1,je.prototype.commaOrSpaceSeparated=!1,je.prototype.commaSeparated=!1,je.prototype.defined=!1,je.prototype.mustUseProperty=!1,je.prototype.number=!1,je.prototype.overloadedBoolean=!1,je.prototype.property="",je.prototype.spaceSeparated=!1,je.prototype.space=void 0;let Ap=0;const G=Mt(),_e=Mt(),sa=Mt(),L=Mt(),ce=Mt(),Vt=Mt(),Ve=Mt();function Mt(){return Lu(2,++Ap)}const oa=Object.freeze(Object.defineProperty({__proto__:null,boolean:G,booleanish:_e,commaOrSpaceSeparated:Ve,commaSeparated:Vt,number:L,overloadedBoolean:sa,spaceSeparated:ce},Symbol.toStringTag,{value:"Module"})),la=Object.keys(oa);class ua extends je{constructor(t,r,n,a){let i=-1;if(super(t,r),vo(this,"space",a),typeof n=="number")for(;++i<la.length;){const s=la[i];vo(this,la[i],(n&oa[s])===oa[s])}}}ua.prototype.defined=!0;function vo(e,t,r){r&&(e[t]=r)}function Wt(e){const t={},r={};for(const[n,a]of Object.entries(e.properties)){const i=new ua(n,e.transform(e.attributes||{},n),a,e.space);e.mustUseProperty&&e.mustUseProperty.includes(n)&&(i.mustUseProperty=!0),t[n]=i,r[ia(n)]=n,r[ia(i.attribute)]=n}return new mr(t,r,e.space)}const ko=Wt({properties:{ariaActiveDescendant:null,ariaAtomic:_e,ariaAutoComplete:null,ariaBusy:_e,ariaChecked:_e,ariaColCount:L,ariaColIndex:L,ariaColSpan:L,ariaControls:ce,ariaCurrent:null,ariaDescribedBy:ce,ariaDetails:null,ariaDisabled:_e,ariaDropEffect:ce,ariaErrorMessage:null,ariaExpanded:_e,ariaFlowTo:ce,ariaGrabbed:_e,ariaHasPopup:null,ariaHidden:_e,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:ce,ariaLevel:L,ariaLive:null,ariaModal:_e,ariaMultiLine:_e,ariaMultiSelectable:_e,ariaOrientation:null,ariaOwns:ce,ariaPlaceholder:null,ariaPosInSet:L,ariaPressed:_e,ariaReadOnly:_e,ariaRelevant:null,ariaRequired:_e,ariaRoleDescription:ce,ariaRowCount:L,ariaRowIndex:L,ariaRowSpan:L,ariaSelected:_e,ariaSetSize:L,ariaSort:null,ariaValueMax:L,ariaValueMin:L,ariaValueNow:L,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function So(e,t){return t in e?e[t]:t}function _o(e,t){return So(e,t.toLowerCase())}const Mp=Wt({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Vt,acceptCharset:ce,accessKey:ce,action:null,allow:null,allowFullScreen:G,allowPaymentRequest:G,allowUserMedia:G,alt:null,as:null,async:G,autoCapitalize:null,autoComplete:ce,autoFocus:G,autoPlay:G,blocking:ce,capture:null,charSet:null,checked:G,cite:null,className:ce,cols:L,colSpan:null,content:null,contentEditable:_e,controls:G,controlsList:ce,coords:L|Vt,crossOrigin:null,data:null,dateTime:null,decoding:null,default:G,defer:G,dir:null,dirName:null,disabled:G,download:sa,draggable:_e,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:G,formTarget:null,headers:ce,height:L,hidden:sa,high:L,href:null,hrefLang:null,htmlFor:ce,httpEquiv:ce,id:null,imageSizes:null,imageSrcSet:null,inert:G,inputMode:null,integrity:null,is:null,isMap:G,itemId:null,itemProp:ce,itemRef:ce,itemScope:G,itemType:ce,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:G,low:L,manifest:null,max:null,maxLength:L,media:null,method:null,min:null,minLength:L,multiple:G,muted:G,name:null,nonce:null,noModule:G,noValidate:G,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:G,optimum:L,pattern:null,ping:ce,placeholder:null,playsInline:G,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:G,referrerPolicy:null,rel:ce,required:G,reversed:G,rows:L,rowSpan:L,sandbox:ce,scope:null,scoped:G,seamless:G,selected:G,shadowRootClonable:G,shadowRootDelegatesFocus:G,shadowRootMode:null,shape:null,size:L,sizes:null,slot:null,span:L,spellCheck:_e,src:null,srcDoc:null,srcLang:null,srcSet:null,start:L,step:null,style:null,tabIndex:L,target:null,title:null,translate:null,type:null,typeMustMatch:G,useMap:null,value:_e,width:L,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:ce,axis:null,background:null,bgColor:null,border:L,borderColor:null,bottomMargin:L,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:G,declare:G,event:null,face:null,frame:null,frameBorder:null,hSpace:L,leftMargin:L,link:null,longDesc:null,lowSrc:null,marginHeight:L,marginWidth:L,noResize:G,noHref:G,noShade:G,noWrap:G,object:null,profile:null,prompt:null,rev:null,rightMargin:L,rules:null,scheme:null,scrolling:_e,standby:null,summary:null,text:null,topMargin:L,valueType:null,version:null,vAlign:null,vLink:null,vSpace:L,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:G,disableRemotePlayback:G,prefix:null,property:null,results:L,security:null,unselectable:null},space:"html",transform:_o}),Pp=Wt({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:Ve,accentHeight:L,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:L,amplitude:L,arabicForm:null,ascent:L,attributeName:null,attributeType:null,azimuth:L,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:L,by:null,calcMode:null,capHeight:L,className:ce,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:L,diffuseConstant:L,direction:null,display:null,dur:null,divisor:L,dominantBaseline:null,download:G,dx:null,dy:null,edgeMode:null,editable:null,elevation:L,enableBackground:null,end:null,event:null,exponent:L,externalResourcesRequired:null,fill:null,fillOpacity:L,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:Vt,g2:Vt,glyphName:Vt,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:L,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:L,horizOriginX:L,horizOriginY:L,id:null,ideographic:L,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:L,k:L,k1:L,k2:L,k3:L,k4:L,kernelMatrix:Ve,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:L,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:L,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:L,overlineThickness:L,paintOrder:null,panose1:null,path:null,pathLength:L,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:ce,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:L,pointsAtY:L,pointsAtZ:L,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Ve,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Ve,rev:Ve,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Ve,requiredFeatures:Ve,requiredFonts:Ve,requiredFormats:Ve,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:L,specularExponent:L,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:L,strikethroughThickness:L,string:null,stroke:null,strokeDashArray:Ve,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:L,strokeOpacity:L,strokeWidth:null,style:null,surfaceScale:L,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Ve,tabIndex:L,tableValues:null,target:null,targetX:L,targetY:L,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Ve,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:L,underlineThickness:L,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:L,values:null,vAlphabetic:L,vMathematical:L,vectorEffect:null,vHanging:L,vIdeographic:L,version:null,vertAdvY:L,vertOriginX:L,vertOriginY:L,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:L,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:So}),To=Wt({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}}),Co=Wt({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:_o}),Io=Wt({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),Np={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},Lp=/[A-Z]/g,Eo=/-[a-z]/g,Dp=/^data[-\w.:]+$/i;function Op(e,t){const r=ia(t);let n=t,a=je;if(r in e.normal)return e.property[e.normal[r]];if(r.length>4&&r.slice(0,4)==="data"&&Dp.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(Eo,Bp);n="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!Eo.test(i)){let s=i.replace(Lp,Fp);s.charAt(0)!=="-"&&(s="-"+s),t="data"+s}}a=ua}return new a(n,t)}function Fp(e){return"-"+e.toLowerCase()}function Bp(e){return e.charAt(1).toUpperCase()}const zp=xo([ko,Mp,To,Co,Io],"html"),ca=xo([ko,Pp,To,Co,Io],"svg");function Rp(e){return e.join(" ").trim()}var Jt={},da,Ao;function jp(){if(Ao)return da;Ao=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,r=/^\s*/,n=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,a=/^:\s*/,i=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,s=/^[;\s]*/,o=/^\s+|\s+$/g,l=`
8
- `,u="/",d="*",c="",h="comment",f="declaration";function g(b,w){if(typeof b!="string")throw new TypeError("First argument must be a string");if(!b)return[];w=w||{};var T=1,_=1;function D(R){var F=R.match(t);F&&(T+=F.length);var Q=R.lastIndexOf(l);_=~Q?R.length-Q:_+R.length}function z(){var R={line:T,column:_};return function(F){return F.position=new I(R),j(),F}}function I(R){this.start=R,this.end={line:T,column:_},this.source=w.source}I.prototype.content=b;function B(R){var F=new Error(w.source+":"+T+":"+_+": "+R);if(F.reason=R,F.filename=w.source,F.line=T,F.column=_,F.source=b,!w.silent)throw F}function H(R){var F=R.exec(b);if(F){var Q=F[0];return D(Q),b=b.slice(Q.length),F}}function j(){H(r)}function S(R){var F;for(R=R||[];F=N();)F!==!1&&R.push(F);return R}function N(){var R=z();if(!(u!=b.charAt(0)||d!=b.charAt(1))){for(var F=2;c!=b.charAt(F)&&(d!=b.charAt(F)||u!=b.charAt(F+1));)++F;if(F+=2,c===b.charAt(F-1))return B("End of comment missing");var Q=b.slice(2,F-2);return _+=2,D(Q),b=b.slice(F),_+=2,R({type:h,comment:Q})}}function M(){var R=z(),F=H(n);if(F){if(N(),!H(a))return B("property missing ':'");var Q=H(i),ue=R({type:f,property:v(F[0].replace(e,c)),value:Q?v(Q[0].replace(e,c)):c});return H(s),ue}}function U(){var R=[];S(R);for(var F;F=M();)F!==!1&&(R.push(F),S(R));return R}return j(),U()}function v(b){return b?b.replace(o,c):c}return da=g,da}var Mo;function $p(){if(Mo)return Jt;Mo=1;var e=Jt&&Jt.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Jt,"__esModule",{value:!0}),Jt.default=r;const t=e(jp());function r(n,a){let i=null;if(!n||typeof n!="string")return i;const s=(0,t.default)(n),o=typeof a=="function";return s.forEach(l=>{if(l.type!=="declaration")return;const{property:u,value:d}=l;o?a(u,d,l):d&&(i=i||{},i[u]=d)}),i}return Jt}var gr={},Po;function Up(){if(Po)return gr;Po=1,Object.defineProperty(gr,"__esModule",{value:!0}),gr.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,r=/^[^-]+$/,n=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,i=function(u){return!u||r.test(u)||e.test(u)},s=function(u,d){return d.toUpperCase()},o=function(u,d){return"".concat(d,"-")},l=function(u,d){return d===void 0&&(d={}),i(u)?u:(u=u.toLowerCase(),d.reactCompat?u=u.replace(a,o):u=u.replace(n,o),u.replace(t,s))};return gr.camelCase=l,gr}var yr,No;function Hp(){if(No)return yr;No=1;var e=yr&&yr.__importDefault||function(a){return a&&a.__esModule?a:{default:a}},t=e($p()),r=Up();function n(a,i){var s={};return!a||typeof a!="string"||(0,t.default)(a,function(o,l){o&&l&&(s[(0,r.camelCase)(o,i)]=l)}),s}return n.default=n,yr=n,yr}var qp=Hp();const Vp=Nr(qp),Lo=Do("end"),ha=Do("start");function Do(e){return t;function t(r){const n=r&&r.position&&r.position[e]||{};if(typeof n.line=="number"&&n.line>0&&typeof n.column=="number"&&n.column>0)return{line:n.line,column:n.column,offset:typeof n.offset=="number"&&n.offset>-1?n.offset:void 0}}}function Wp(e){const t=ha(e),r=Lo(e);if(t&&r)return{start:t,end:r}}function br(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Oo(e.position):"start"in e||"end"in e?Oo(e):"line"in e||"column"in e?fa(e):""}function fa(e){return Fo(e&&e.line)+":"+Fo(e&&e.column)}function Oo(e){return fa(e&&e.start)+"-"+fa(e&&e.end)}function Fo(e){return e&&typeof e=="number"?e:1}class Ee extends Error{constructor(t,r,n){super(),typeof r=="string"&&(n=r,r=void 0);let a="",i={},s=!1;if(r&&("line"in r&&"column"in r?i={place:r}:"start"in r&&"end"in r?i={place:r}:"type"in r?i={ancestors:[r],place:r.position}:i=m({},r)),typeof t=="string"?a=t:!i.cause&&t&&(s=!0,a=t.message,i.cause=t),!i.ruleId&&!i.source&&typeof n=="string"){const l=n.indexOf(":");l===-1?i.ruleId=n:(i.source=n.slice(0,l),i.ruleId=n.slice(l+1))}if(!i.place&&i.ancestors&&i.ancestors){const l=i.ancestors[i.ancestors.length-1];l&&(i.place=l.position)}const o=i.place&&"start"in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=o?o.column:void 0,this.fatal=void 0,this.file="",this.message=a,this.line=o?o.line:void 0,this.name=br(i.place)||"1:1",this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=s&&i.cause&&typeof i.cause.stack=="string"?i.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}Ee.prototype.file="",Ee.prototype.name="",Ee.prototype.reason="",Ee.prototype.message="",Ee.prototype.stack="",Ee.prototype.column=void 0,Ee.prototype.line=void 0,Ee.prototype.ancestors=void 0,Ee.prototype.cause=void 0,Ee.prototype.fatal=void 0,Ee.prototype.place=void 0,Ee.prototype.ruleId=void 0,Ee.prototype.source=void 0;const pa={}.hasOwnProperty,Jp=new Map,Yp=/[A-Z]/g,Kp=new Set(["table","tbody","thead","tfoot","tr"]),Gp=new Set(["td","th"]),Bo="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function Xp(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const r=t.filePath||void 0;let n;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");n=im(r,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");n=am(r,t.jsx,t.jsxs)}const a={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:n,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:r,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?ca:zp,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},i=zo(a,e,void 0);return i&&typeof i!="string"?i:a.create(e,a.Fragment,{children:i||void 0},void 0)}function zo(e,t,r){if(t.type==="element")return Qp(e,t,r);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return Zp(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return tm(e,t,r);if(t.type==="mdxjsEsm")return em(e,t);if(t.type==="root")return rm(e,t,r);if(t.type==="text")return nm(e,t)}function Qp(e,t,r){const n=e.schema;let a=n;t.tagName.toLowerCase()==="svg"&&n.space==="html"&&(a=ca,e.schema=a),e.ancestors.push(t);const i=jo(e,t.tagName,!1),s=sm(e,t);let o=ga(e,t);return Kp.has(t.tagName)&&(o=o.filter(function(l){return typeof l=="string"?!Ep(l):!0})),Ro(e,s,i,t),ma(s,o),e.ancestors.pop(),e.schema=n,e.create(t,i,s,r)}function Zp(e,t){if(t.data&&t.data.estree&&e.evaluater){const n=t.data.estree.body[0];return n.type,e.evaluater.evaluateExpression(n.expression)}wr(e,t.position)}function em(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);wr(e,t.position)}function tm(e,t,r){const n=e.schema;let a=n;t.name==="svg"&&n.space==="html"&&(a=ca,e.schema=a),e.ancestors.push(t);const i=t.name===null?e.Fragment:jo(e,t.name,!0),s=om(e,t),o=ga(e,t);return Ro(e,s,i,t),ma(s,o),e.ancestors.pop(),e.schema=n,e.create(t,i,s,r)}function rm(e,t,r){const n={};return ma(n,ga(e,t)),e.create(t,e.Fragment,n,r)}function nm(e,t){return t.value}function Ro(e,t,r,n){typeof r!="string"&&r!==e.Fragment&&e.passNode&&(t.node=n)}function ma(e,t){if(t.length>0){const r=t.length>1?t:t[0];r&&(e.children=r)}}function am(e,t,r){return n;function n(a,i,s,o){const u=Array.isArray(s.children)?r:t;return o?u(i,s,o):u(i,s)}}function im(e,t){return r;function r(n,a,i,s){const o=Array.isArray(i.children),l=ha(n);return t(a,i,s,o,{columnNumber:l?l.column-1:void 0,fileName:e,lineNumber:l?l.line:void 0},void 0)}}function sm(e,t){const r={};let n,a;for(a in t.properties)if(a!=="children"&&pa.call(t.properties,a)){const i=lm(e,a,t.properties[a]);if(i){const[s,o]=i;e.tableCellAlignToStyle&&s==="align"&&typeof o=="string"&&Gp.has(t.tagName)?n=o:r[s]=o}}if(n){const i=r.style||(r.style={});i[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=n}return r}function om(e,t){const r={};for(const n of t.attributes)if(n.type==="mdxJsxExpressionAttribute")if(n.data&&n.data.estree&&e.evaluater){const i=n.data.estree.body[0];i.type;const s=i.expression;s.type;const o=s.properties[0];o.type,Object.assign(r,e.evaluater.evaluateExpression(o.argument))}else wr(e,t.position);else{const a=n.name;let i;if(n.value&&typeof n.value=="object")if(n.value.data&&n.value.data.estree&&e.evaluater){const o=n.value.data.estree.body[0];o.type,i=e.evaluater.evaluateExpression(o.expression)}else wr(e,t.position);else i=n.value===null?!0:n.value;r[a]=i}return r}function ga(e,t){const r=[];let n=-1;const a=e.passKeys?new Map:Jp;for(;++n<t.children.length;){const i=t.children[n];let s;if(e.passKeys){const l=i.type==="element"?i.tagName:i.type==="mdxJsxFlowElement"||i.type==="mdxJsxTextElement"?i.name:void 0;if(l){const u=a.get(l)||0;s=l+"-"+u,a.set(l,u+1)}}const o=zo(e,i,s);o!==void 0&&r.push(o)}return r}function lm(e,t,r){const n=Op(e.schema,t);if(!(r==null||typeof r=="number"&&Number.isNaN(r))){if(Array.isArray(r)&&(r=n.commaSeparated?Sp(r):Rp(r)),n.property==="style"){let a=typeof r=="object"?r:um(e,String(r));return e.stylePropertyNameCase==="css"&&(a=cm(a)),["style",a]}return[e.elementAttributeNameCase==="react"&&n.space?Np[n.property]||n.property:n.attribute,r]}}function um(e,t){try{return Vp(t,{reactCompat:!0})}catch(r){if(e.ignoreInvalidStyle)return{};const n=r,a=new Ee("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:n,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw a.file=e.filePath||void 0,a.url=Bo+"#cannot-parse-style-attribute",a}}function jo(e,t,r){let n;if(!r)n={type:"Literal",value:t};else if(t.includes(".")){const a=t.split(".");let i=-1,s;for(;++i<a.length;){const o=bo(a[i])?{type:"Identifier",name:a[i]}:{type:"Literal",value:a[i]};s=s?{type:"MemberExpression",object:s,property:o,computed:!!(i&&o.type==="Literal"),optional:!1}:o}n=s}else n=bo(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(n.type==="Literal"){const a=n.value;return pa.call(e.components,a)?e.components[a]:a}if(e.evaluater)return e.evaluater.evaluateExpression(n);wr(e)}function wr(e,t){const r=new Ee("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw r.file=e.filePath||void 0,r.url=Bo+"#cannot-handle-mdx-estrees-without-createevaluater",r}function cm(e){const t={};let r;for(r in e)pa.call(e,r)&&(t[dm(r)]=e[r]);return t}function dm(e){let t=e.replace(Yp,hm);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function hm(e){return"-"+e.toLowerCase()}const ya={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},fm={};function ba(e,t){const r=fm,n=typeof r.includeImageAlt=="boolean"?r.includeImageAlt:!0,a=typeof r.includeHtml=="boolean"?r.includeHtml:!0;return $o(e,n,a)}function $o(e,t,r){if(pm(e)){if("value"in e)return e.type==="html"&&!r?"":e.value;if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return Uo(e.children,t,r)}return Array.isArray(e)?Uo(e,t,r):""}function Uo(e,t,r){const n=[];let a=-1;for(;++a<e.length;)n[a]=$o(e[a],t,r);return n.join("")}function pm(e){return!!(e&&typeof e=="object")}const Ho=document.createElement("i");function wa(e){const t="&"+e+";";Ho.innerHTML=t;const r=Ho.textContent;return r.charCodeAt(r.length-1)===59&&e!=="semi"||r===t?!1:r}function We(e,t,r,n){const a=e.length;let i=0,s;if(t<0?t=-t>a?0:a+t:t=t>a?a:t,r=r>0?r:0,n.length<1e4)s=Array.from(n),s.unshift(t,r),e.splice(...s);else for(r&&e.splice(t,r);i<n.length;)s=n.slice(i,i+1e4),s.unshift(t,0),e.splice(...s),i+=1e4,t+=1e4}function Xe(e,t){return e.length>0?(We(e,e.length,0,t),e):t}const qo={}.hasOwnProperty;function Vo(e){const t={};let r=-1;for(;++r<e.length;)mm(t,e[r]);return t}function mm(e,t){let r;for(r in t){const a=(qo.call(e,r)?e[r]:void 0)||(e[r]={}),i=t[r];let s;if(i)for(s in i){qo.call(a,s)||(a[s]=[]);const o=i[s];gm(a[s],Array.isArray(o)?o:o?[o]:[])}}}function gm(e,t){let r=-1;const n=[];for(;++r<t.length;)(t[r].add==="after"?e:n).push(t[r]);We(e,0,0,n)}function Wo(e,t){const r=Number.parseInt(e,t);return r<9||r===11||r>13&&r<32||r>126&&r<160||r>55295&&r<57344||r>64975&&r<65008||(r&65535)===65535||(r&65535)===65534||r>1114111?"�":String.fromCodePoint(r)}function at(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Be=xt(/[A-Za-z]/),Ae=xt(/[\dA-Za-z]/),ym=xt(/[#-'*+\--9=?A-Z^-~]/);function nn(e){return e!==null&&(e<32||e===127)}const xa=xt(/\d/),bm=xt(/[\dA-Fa-f]/),wm=xt(/[!-/:-@[-`{-~]/);function J(e){return e!==null&&e<-2}function le(e){return e!==null&&(e<0||e===32)}function te(e){return e===-2||e===-1||e===32}const an=xt(new RegExp("\\p{P}|\\p{S}","u")),Pt=xt(/\s/);function xt(e){return t;function t(r){return r!==null&&r>-1&&e.test(String.fromCharCode(r))}}function Yt(e){const t=[];let r=-1,n=0,a=0;for(;++r<e.length;){const i=e.charCodeAt(r);let s="";if(i===37&&Ae(e.charCodeAt(r+1))&&Ae(e.charCodeAt(r+2)))a=2;else if(i<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(i))||(s=String.fromCharCode(i));else if(i>55295&&i<57344){const o=e.charCodeAt(r+1);i<56320&&o>56319&&o<57344?(s=String.fromCharCode(i,o),a=1):s="�"}else s=String.fromCharCode(i);s&&(t.push(e.slice(n,r),encodeURIComponent(s)),n=r+a+1,s=""),a&&(r+=a,a=0)}return t.join("")+e.slice(n)}function ne(e,t,r,n){const a=n?n-1:Number.POSITIVE_INFINITY;let i=0;return s;function s(l){return te(l)?(e.enter(r),o(l)):t(l)}function o(l){return te(l)&&i++<a?(e.consume(l),o):(e.exit(r),t(l))}}const xm={tokenize:vm};function vm(e){const t=e.attempt(this.parser.constructs.contentInitial,n,a);let r;return t;function n(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),ne(e,t,"linePrefix")}function a(o){return e.enter("paragraph"),i(o)}function i(o){const l=e.enter("chunkText",{contentType:"text",previous:r});return r&&(r.next=l),r=l,s(o)}function s(o){if(o===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(o);return}return J(o)?(e.consume(o),e.exit("chunkText"),i):(e.consume(o),s)}}const km={tokenize:Sm},Jo={tokenize:_m};function Sm(e){const t=this,r=[];let n=0,a,i,s;return o;function o(_){if(n<r.length){const D=r[n];return t.containerState=D[1],e.attempt(D[0].continuation,l,u)(_)}return u(_)}function l(_){if(n++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,a&&T();const D=t.events.length;let z=D,I;for(;z--;)if(t.events[z][0]==="exit"&&t.events[z][1].type==="chunkFlow"){I=t.events[z][1].end;break}w(n);let B=D;for(;B<t.events.length;)t.events[B][1].end=m({},I),B++;return We(t.events,z+1,0,t.events.slice(D)),t.events.length=B,u(_)}return o(_)}function u(_){if(n===r.length){if(!a)return h(_);if(a.currentConstruct&&a.currentConstruct.concrete)return g(_);t.interrupt=!!(a.currentConstruct&&!a._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(Jo,d,c)(_)}function d(_){return a&&T(),w(n),h(_)}function c(_){return t.parser.lazy[t.now().line]=n!==r.length,s=t.now().offset,g(_)}function h(_){return t.containerState={},e.attempt(Jo,f,g)(_)}function f(_){return n++,r.push([t.currentConstruct,t.containerState]),h(_)}function g(_){if(_===null){a&&T(),w(0),e.consume(_);return}return a=a||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:a,contentType:"flow",previous:i}),v(_)}function v(_){if(_===null){b(e.exit("chunkFlow"),!0),w(0),e.consume(_);return}return J(_)?(e.consume(_),b(e.exit("chunkFlow")),n=0,t.interrupt=void 0,o):(e.consume(_),v)}function b(_,D){const z=t.sliceStream(_);if(D&&z.push(null),_.previous=i,i&&(i.next=_),i=_,a.defineSkip(_.start),a.write(z),t.parser.lazy[_.start.line]){let I=a.events.length;for(;I--;)if(a.events[I][1].start.offset<s&&(!a.events[I][1].end||a.events[I][1].end.offset>s))return;const B=t.events.length;let H=B,j,S;for(;H--;)if(t.events[H][0]==="exit"&&t.events[H][1].type==="chunkFlow"){if(j){S=t.events[H][1].end;break}j=!0}for(w(n),I=B;I<t.events.length;)t.events[I][1].end=m({},S),I++;We(t.events,H+1,0,t.events.slice(B)),t.events.length=I}}function w(_){let D=r.length;for(;D-- >_;){const z=r[D];t.containerState=z[1],z[0].exit.call(t,e)}r.length=_}function T(){a.write([null]),i=void 0,a=void 0,t.containerState._closeFlow=void 0}}function _m(e,t,r){return ne(e,e.attempt(this.parser.constructs.document,t,r),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Kt(e){if(e===null||le(e)||Pt(e))return 1;if(an(e))return 2}function sn(e,t,r){const n=[];let a=-1;for(;++a<e.length;){const i=e[a].resolveAll;i&&!n.includes(i)&&(t=i(t,r),n.push(i))}return t}const va={name:"attention",resolveAll:Tm,tokenize:Cm};function Tm(e,t){let r=-1,n,a,i,s,o,l,u,d;for(;++r<e.length;)if(e[r][0]==="enter"&&e[r][1].type==="attentionSequence"&&e[r][1]._close){for(n=r;n--;)if(e[n][0]==="exit"&&e[n][1].type==="attentionSequence"&&e[n][1]._open&&t.sliceSerialize(e[n][1]).charCodeAt(0)===t.sliceSerialize(e[r][1]).charCodeAt(0)){if((e[n][1]._close||e[r][1]._open)&&(e[r][1].end.offset-e[r][1].start.offset)%3&&!((e[n][1].end.offset-e[n][1].start.offset+e[r][1].end.offset-e[r][1].start.offset)%3))continue;l=e[n][1].end.offset-e[n][1].start.offset>1&&e[r][1].end.offset-e[r][1].start.offset>1?2:1;const c=m({},e[n][1].end),h=m({},e[r][1].start);Yo(c,-l),Yo(h,l),s={type:l>1?"strongSequence":"emphasisSequence",start:c,end:m({},e[n][1].end)},o={type:l>1?"strongSequence":"emphasisSequence",start:m({},e[r][1].start),end:h},i={type:l>1?"strongText":"emphasisText",start:m({},e[n][1].end),end:m({},e[r][1].start)},a={type:l>1?"strong":"emphasis",start:m({},s.start),end:m({},o.end)},e[n][1].end=m({},s.start),e[r][1].start=m({},o.end),u=[],e[n][1].end.offset-e[n][1].start.offset&&(u=Xe(u,[["enter",e[n][1],t],["exit",e[n][1],t]])),u=Xe(u,[["enter",a,t],["enter",s,t],["exit",s,t],["enter",i,t]]),u=Xe(u,sn(t.parser.constructs.insideSpan.null,e.slice(n+1,r),t)),u=Xe(u,[["exit",i,t],["enter",o,t],["exit",o,t],["exit",a,t]]),e[r][1].end.offset-e[r][1].start.offset?(d=2,u=Xe(u,[["enter",e[r][1],t],["exit",e[r][1],t]])):d=0,We(e,n-1,r-n+3,u),r=n+u.length-d-2;break}}for(r=-1;++r<e.length;)e[r][1].type==="attentionSequence"&&(e[r][1].type="data");return e}function Cm(e,t){const r=this.parser.constructs.attentionMarkers.null,n=this.previous,a=Kt(n);let i;return s;function s(l){return i=l,e.enter("attentionSequence"),o(l)}function o(l){if(l===i)return e.consume(l),o;const u=e.exit("attentionSequence"),d=Kt(l),c=!d||d===2&&a||r.includes(l),h=!a||a===2&&d||r.includes(n);return u._open=!!(i===42?c:c&&(a||!h)),u._close=!!(i===42?h:h&&(d||!c)),t(l)}}function Yo(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const Im={name:"autolink",tokenize:Em};function Em(e,t,r){let n=0;return a;function a(f){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(f),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),i}function i(f){return Be(f)?(e.consume(f),s):f===64?r(f):u(f)}function s(f){return f===43||f===45||f===46||Ae(f)?(n=1,o(f)):u(f)}function o(f){return f===58?(e.consume(f),n=0,l):(f===43||f===45||f===46||Ae(f))&&n++<32?(e.consume(f),o):(n=0,u(f))}function l(f){return f===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(f),e.exit("autolinkMarker"),e.exit("autolink"),t):f===null||f===32||f===60||nn(f)?r(f):(e.consume(f),l)}function u(f){return f===64?(e.consume(f),d):ym(f)?(e.consume(f),u):r(f)}function d(f){return Ae(f)?c(f):r(f)}function c(f){return f===46?(e.consume(f),n=0,d):f===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(f),e.exit("autolinkMarker"),e.exit("autolink"),t):h(f)}function h(f){if((f===45||Ae(f))&&n++<63){const g=f===45?h:c;return e.consume(f),g}return r(f)}}const xr={partial:!0,tokenize:Am};function Am(e,t,r){return n;function n(i){return te(i)?ne(e,a,"linePrefix")(i):a(i)}function a(i){return i===null||J(i)?t(i):r(i)}}const Ko={continuation:{tokenize:Pm},exit:Nm,name:"blockQuote",tokenize:Mm};function Mm(e,t,r){const n=this;return a;function a(s){if(s===62){const o=n.containerState;return o.open||(e.enter("blockQuote",{_container:!0}),o.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(s),e.exit("blockQuoteMarker"),i}return r(s)}function i(s){return te(s)?(e.enter("blockQuotePrefixWhitespace"),e.consume(s),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(s))}}function Pm(e,t,r){const n=this;return a;function a(s){return te(s)?ne(e,i,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(s):i(s)}function i(s){return e.attempt(Ko,t,r)(s)}}function Nm(e){e.exit("blockQuote")}const Go={name:"characterEscape",tokenize:Lm};function Lm(e,t,r){return n;function n(i){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(i),e.exit("escapeMarker"),a}function a(i){return wm(i)?(e.enter("characterEscapeValue"),e.consume(i),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):r(i)}}const Xo={name:"characterReference",tokenize:Dm};function Dm(e,t,r){const n=this;let a=0,i,s;return o;function o(c){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(c),e.exit("characterReferenceMarker"),l}function l(c){return c===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(c),e.exit("characterReferenceMarkerNumeric"),u):(e.enter("characterReferenceValue"),i=31,s=Ae,d(c))}function u(c){return c===88||c===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(c),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),i=6,s=bm,d):(e.enter("characterReferenceValue"),i=7,s=xa,d(c))}function d(c){if(c===59&&a){const h=e.exit("characterReferenceValue");return s===Ae&&!wa(n.sliceSerialize(h))?r(c):(e.enter("characterReferenceMarker"),e.consume(c),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return s(c)&&a++<i?(e.consume(c),d):r(c)}}const Qo={partial:!0,tokenize:Fm},Zo={concrete:!0,name:"codeFenced",tokenize:Om};function Om(e,t,r){const n=this,a={partial:!0,tokenize:z};let i=0,s=0,o;return l;function l(I){return u(I)}function u(I){const B=n.events[n.events.length-1];return i=B&&B[1].type==="linePrefix"?B[2].sliceSerialize(B[1],!0).length:0,o=I,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),d(I)}function d(I){return I===o?(s++,e.consume(I),d):s<3?r(I):(e.exit("codeFencedFenceSequence"),te(I)?ne(e,c,"whitespace")(I):c(I))}function c(I){return I===null||J(I)?(e.exit("codeFencedFence"),n.interrupt?t(I):e.check(Qo,v,D)(I)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),h(I))}function h(I){return I===null||J(I)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),c(I)):te(I)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),ne(e,f,"whitespace")(I)):I===96&&I===o?r(I):(e.consume(I),h)}function f(I){return I===null||J(I)?c(I):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(I))}function g(I){return I===null||J(I)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),c(I)):I===96&&I===o?r(I):(e.consume(I),g)}function v(I){return e.attempt(a,D,b)(I)}function b(I){return e.enter("lineEnding"),e.consume(I),e.exit("lineEnding"),w}function w(I){return i>0&&te(I)?ne(e,T,"linePrefix",i+1)(I):T(I)}function T(I){return I===null||J(I)?e.check(Qo,v,D)(I):(e.enter("codeFlowValue"),_(I))}function _(I){return I===null||J(I)?(e.exit("codeFlowValue"),T(I)):(e.consume(I),_)}function D(I){return e.exit("codeFenced"),t(I)}function z(I,B,H){let j=0;return S;function S(F){return I.enter("lineEnding"),I.consume(F),I.exit("lineEnding"),N}function N(F){return I.enter("codeFencedFence"),te(F)?ne(I,M,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(F):M(F)}function M(F){return F===o?(I.enter("codeFencedFenceSequence"),U(F)):H(F)}function U(F){return F===o?(j++,I.consume(F),U):j>=s?(I.exit("codeFencedFenceSequence"),te(F)?ne(I,R,"whitespace")(F):R(F)):H(F)}function R(F){return F===null||J(F)?(I.exit("codeFencedFence"),B(F)):H(F)}}}function Fm(e,t,r){const n=this;return a;function a(s){return s===null?r(s):(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),i)}function i(s){return n.parser.lazy[n.now().line]?r(s):t(s)}}const ka={name:"codeIndented",tokenize:zm},Bm={partial:!0,tokenize:Rm};function zm(e,t,r){const n=this;return a;function a(u){return e.enter("codeIndented"),ne(e,i,"linePrefix",5)(u)}function i(u){const d=n.events[n.events.length-1];return d&&d[1].type==="linePrefix"&&d[2].sliceSerialize(d[1],!0).length>=4?s(u):r(u)}function s(u){return u===null?l(u):J(u)?e.attempt(Bm,s,l)(u):(e.enter("codeFlowValue"),o(u))}function o(u){return u===null||J(u)?(e.exit("codeFlowValue"),s(u)):(e.consume(u),o)}function l(u){return e.exit("codeIndented"),t(u)}}function Rm(e,t,r){const n=this;return a;function a(s){return n.parser.lazy[n.now().line]?r(s):J(s)?(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),a):ne(e,i,"linePrefix",5)(s)}function i(s){const o=n.events[n.events.length-1];return o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?t(s):J(s)?a(s):r(s)}}const jm={name:"codeText",previous:Um,resolve:$m,tokenize:Hm};function $m(e){let t=e.length-4,r=3,n,a;if((e[r][1].type==="lineEnding"||e[r][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(n=r;++n<t;)if(e[n][1].type==="codeTextData"){e[r][1].type="codeTextPadding",e[t][1].type="codeTextPadding",r+=2,t-=2;break}}for(n=r-1,t++;++n<=t;)a===void 0?n!==t&&e[n][1].type!=="lineEnding"&&(a=n):(n===t||e[n][1].type==="lineEnding")&&(e[a][1].type="codeTextData",n!==a+2&&(e[a][1].end=e[n-1][1].end,e.splice(a+2,n-a-2),t-=n-a-2,n=a+2),a=void 0);return e}function Um(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function Hm(e,t,r){let n=0,a,i;return s;function s(c){return e.enter("codeText"),e.enter("codeTextSequence"),o(c)}function o(c){return c===96?(e.consume(c),n++,o):(e.exit("codeTextSequence"),l(c))}function l(c){return c===null?r(c):c===32?(e.enter("space"),e.consume(c),e.exit("space"),l):c===96?(i=e.enter("codeTextSequence"),a=0,d(c)):J(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),l):(e.enter("codeTextData"),u(c))}function u(c){return c===null||c===32||c===96||J(c)?(e.exit("codeTextData"),l(c)):(e.consume(c),u)}function d(c){return c===96?(e.consume(c),a++,d):a===n?(e.exit("codeTextSequence"),e.exit("codeText"),t(c)):(i.type="codeTextData",u(c))}}class qm{constructor(t){this.left=t?[...t]:[],this.right=[]}get(t){if(t<0||t>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return t<this.left.length?this.left[t]:this.right[this.right.length-t+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(t,r){const n=r==null?Number.POSITIVE_INFINITY:r;return n<this.left.length?this.left.slice(t,n):t>this.left.length?this.right.slice(this.right.length-n+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-n+this.left.length).reverse())}splice(t,r,n){const a=r||0;this.setCursor(Math.trunc(t));const i=this.right.splice(this.right.length-a,Number.POSITIVE_INFINITY);return n&&vr(this.left,n),i.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),vr(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),vr(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t<this.left.length){const r=this.left.splice(t,Number.POSITIVE_INFINITY);vr(this.right,r.reverse())}else{const r=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);vr(this.left,r.reverse())}}}function vr(e,t){let r=0;if(t.length<1e4)e.push(...t);else for(;r<t.length;)e.push(...t.slice(r,r+1e4)),r+=1e4}function el(e){const t={};let r=-1,n,a,i,s,o,l,u;const d=new qm(e);for(;++r<d.length;){for(;r in t;)r=t[r];if(n=d.get(r),r&&n[1].type==="chunkFlow"&&d.get(r-1)[1].type==="listItemPrefix"&&(l=n[1]._tokenizer.events,i=0,i<l.length&&l[i][1].type==="lineEndingBlank"&&(i+=2),i<l.length&&l[i][1].type==="content"))for(;++i<l.length&&l[i][1].type!=="content";)l[i][1].type==="chunkText"&&(l[i][1]._isInFirstContentOfListItem=!0,i++);if(n[0]==="enter")n[1].contentType&&(Object.assign(t,Vm(d,r)),r=t[r],u=!0);else if(n[1]._container){for(i=r,a=void 0;i--;)if(s=d.get(i),s[1].type==="lineEnding"||s[1].type==="lineEndingBlank")s[0]==="enter"&&(a&&(d.get(a)[1].type="lineEndingBlank"),s[1].type="lineEnding",a=i);else if(!(s[1].type==="linePrefix"||s[1].type==="listItemIndent"))break;a&&(n[1].end=m({},d.get(a)[1].start),o=d.slice(a,r),o.unshift(n),d.splice(a,r-a+1,o))}}return We(e,0,Number.POSITIVE_INFINITY,d.slice(0)),!u}function Vm(e,t){const r=e.get(t)[1],n=e.get(t)[2];let a=t-1;const i=[];let s=r._tokenizer;s||(s=n.parser[r.contentType](r.start),r._contentTypeTextTrailing&&(s._contentTypeTextTrailing=!0));const o=s.events,l=[],u={};let d,c,h=-1,f=r,g=0,v=0;const b=[v];for(;f;){for(;e.get(++a)[1]!==f;);i.push(a),f._tokenizer||(d=n.sliceStream(f),f.next||d.push(null),c&&s.defineSkip(f.start),f._isInFirstContentOfListItem&&(s._gfmTasklistFirstContentOfListItem=!0),s.write(d),f._isInFirstContentOfListItem&&(s._gfmTasklistFirstContentOfListItem=void 0)),c=f,f=f.next}for(f=r;++h<o.length;)o[h][0]==="exit"&&o[h-1][0]==="enter"&&o[h][1].type===o[h-1][1].type&&o[h][1].start.line!==o[h][1].end.line&&(v=h+1,b.push(v),f._tokenizer=void 0,f.previous=void 0,f=f.next);for(s.events=[],f?(f._tokenizer=void 0,f.previous=void 0):b.pop(),h=b.length;h--;){const w=o.slice(b[h],b[h+1]),T=i.pop();l.push([T,T+w.length-1]),e.splice(T,2,w)}for(l.reverse(),h=-1;++h<l.length;)u[g+l[h][0]]=g+l[h][1],g+=l[h][1]-l[h][0]-1;return u}const Wm={resolve:Ym,tokenize:Km},Jm={partial:!0,tokenize:Gm};function Ym(e){return el(e),e}function Km(e,t){let r;return n;function n(o){return e.enter("content"),r=e.enter("chunkContent",{contentType:"content"}),a(o)}function a(o){return o===null?i(o):J(o)?e.check(Jm,s,i)(o):(e.consume(o),a)}function i(o){return e.exit("chunkContent"),e.exit("content"),t(o)}function s(o){return e.consume(o),e.exit("chunkContent"),r.next=e.enter("chunkContent",{contentType:"content",previous:r}),r=r.next,a}}function Gm(e,t,r){const n=this;return a;function a(s){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),ne(e,i,"linePrefix")}function i(s){if(s===null||J(s))return r(s);const o=n.events[n.events.length-1];return!n.parser.constructs.disable.null.includes("codeIndented")&&o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?t(s):e.interrupt(n.parser.constructs.flow,r,t)(s)}}function tl(e,t,r,n,a,i,s,o,l){const u=l||Number.POSITIVE_INFINITY;let d=0;return c;function c(w){return w===60?(e.enter(n),e.enter(a),e.enter(i),e.consume(w),e.exit(i),h):w===null||w===32||w===41||nn(w)?r(w):(e.enter(n),e.enter(s),e.enter(o),e.enter("chunkString",{contentType:"string"}),v(w))}function h(w){return w===62?(e.enter(i),e.consume(w),e.exit(i),e.exit(a),e.exit(n),t):(e.enter(o),e.enter("chunkString",{contentType:"string"}),f(w))}function f(w){return w===62?(e.exit("chunkString"),e.exit(o),h(w)):w===null||w===60||J(w)?r(w):(e.consume(w),w===92?g:f)}function g(w){return w===60||w===62||w===92?(e.consume(w),f):f(w)}function v(w){return!d&&(w===null||w===41||le(w))?(e.exit("chunkString"),e.exit(o),e.exit(s),e.exit(n),t(w)):d<u&&w===40?(e.consume(w),d++,v):w===41?(e.consume(w),d--,v):w===null||w===32||w===40||nn(w)?r(w):(e.consume(w),w===92?b:v)}function b(w){return w===40||w===41||w===92?(e.consume(w),v):v(w)}}function rl(e,t,r,n,a,i){const s=this;let o=0,l;return u;function u(f){return e.enter(n),e.enter(a),e.consume(f),e.exit(a),e.enter(i),d}function d(f){return o>999||f===null||f===91||f===93&&!l||f===94&&!o&&"_hiddenFootnoteSupport"in s.parser.constructs?r(f):f===93?(e.exit(i),e.enter(a),e.consume(f),e.exit(a),e.exit(n),t):J(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),d):(e.enter("chunkString",{contentType:"string"}),c(f))}function c(f){return f===null||f===91||f===93||J(f)||o++>999?(e.exit("chunkString"),d(f)):(e.consume(f),l||(l=!te(f)),f===92?h:c)}function h(f){return f===91||f===92||f===93?(e.consume(f),o++,c):c(f)}}function nl(e,t,r,n,a,i){let s;return o;function o(h){return h===34||h===39||h===40?(e.enter(n),e.enter(a),e.consume(h),e.exit(a),s=h===40?41:h,l):r(h)}function l(h){return h===s?(e.enter(a),e.consume(h),e.exit(a),e.exit(n),t):(e.enter(i),u(h))}function u(h){return h===s?(e.exit(i),l(s)):h===null?r(h):J(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),ne(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),d(h))}function d(h){return h===s||h===null||J(h)?(e.exit("chunkString"),u(h)):(e.consume(h),h===92?c:d)}function c(h){return h===s||h===92?(e.consume(h),d):d(h)}}function kr(e,t){let r;return n;function n(a){return J(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),r=!0,n):te(a)?ne(e,n,r?"linePrefix":"lineSuffix")(a):t(a)}}const Xm={name:"definition",tokenize:Zm},Qm={partial:!0,tokenize:eg};function Zm(e,t,r){const n=this;let a;return i;function i(f){return e.enter("definition"),s(f)}function s(f){return rl.call(n,e,o,r,"definitionLabel","definitionLabelMarker","definitionLabelString")(f)}function o(f){return a=at(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)),f===58?(e.enter("definitionMarker"),e.consume(f),e.exit("definitionMarker"),l):r(f)}function l(f){return le(f)?kr(e,u)(f):u(f)}function u(f){return tl(e,d,r,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(f)}function d(f){return e.attempt(Qm,c,c)(f)}function c(f){return te(f)?ne(e,h,"whitespace")(f):h(f)}function h(f){return f===null||J(f)?(e.exit("definition"),n.parser.defined.push(a),t(f)):r(f)}}function eg(e,t,r){return n;function n(o){return le(o)?kr(e,a)(o):r(o)}function a(o){return nl(e,i,r,"definitionTitle","definitionTitleMarker","definitionTitleString")(o)}function i(o){return te(o)?ne(e,s,"whitespace")(o):s(o)}function s(o){return o===null||J(o)?t(o):r(o)}}const tg={name:"hardBreakEscape",tokenize:rg};function rg(e,t,r){return n;function n(i){return e.enter("hardBreakEscape"),e.consume(i),a}function a(i){return J(i)?(e.exit("hardBreakEscape"),t(i)):r(i)}}const ng={name:"headingAtx",resolve:ag,tokenize:ig};function ag(e,t){let r=e.length-2,n=3,a,i;return e[n][1].type==="whitespace"&&(n+=2),r-2>n&&e[r][1].type==="whitespace"&&(r-=2),e[r][1].type==="atxHeadingSequence"&&(n===r-1||r-4>n&&e[r-2][1].type==="whitespace")&&(r-=n+1===r?2:4),r>n&&(a={type:"atxHeadingText",start:e[n][1].start,end:e[r][1].end},i={type:"chunkText",start:e[n][1].start,end:e[r][1].end,contentType:"text"},We(e,n,r-n+1,[["enter",a,t],["enter",i,t],["exit",i,t],["exit",a,t]])),e}function ig(e,t,r){let n=0;return a;function a(d){return e.enter("atxHeading"),i(d)}function i(d){return e.enter("atxHeadingSequence"),s(d)}function s(d){return d===35&&n++<6?(e.consume(d),s):d===null||le(d)?(e.exit("atxHeadingSequence"),o(d)):r(d)}function o(d){return d===35?(e.enter("atxHeadingSequence"),l(d)):d===null||J(d)?(e.exit("atxHeading"),t(d)):te(d)?ne(e,o,"whitespace")(d):(e.enter("atxHeadingText"),u(d))}function l(d){return d===35?(e.consume(d),l):(e.exit("atxHeadingSequence"),o(d))}function u(d){return d===null||d===35||le(d)?(e.exit("atxHeadingText"),o(d)):(e.consume(d),u)}}const sg=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],al=["pre","script","style","textarea"],og={concrete:!0,name:"htmlFlow",resolveTo:cg,tokenize:dg},lg={partial:!0,tokenize:fg},ug={partial:!0,tokenize:hg};function cg(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function dg(e,t,r){const n=this;let a,i,s,o,l;return u;function u(k){return d(k)}function d(k){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(k),c}function c(k){return k===33?(e.consume(k),h):k===47?(e.consume(k),i=!0,v):k===63?(e.consume(k),a=3,n.interrupt?t:x):Be(k)?(e.consume(k),s=String.fromCharCode(k),b):r(k)}function h(k){return k===45?(e.consume(k),a=2,f):k===91?(e.consume(k),a=5,o=0,g):Be(k)?(e.consume(k),a=4,n.interrupt?t:x):r(k)}function f(k){return k===45?(e.consume(k),n.interrupt?t:x):r(k)}function g(k){const xe="CDATA[";return k===xe.charCodeAt(o++)?(e.consume(k),o===xe.length?n.interrupt?t:M:g):r(k)}function v(k){return Be(k)?(e.consume(k),s=String.fromCharCode(k),b):r(k)}function b(k){if(k===null||k===47||k===62||le(k)){const xe=k===47,Ue=s.toLowerCase();return!xe&&!i&&al.includes(Ue)?(a=1,n.interrupt?t(k):M(k)):sg.includes(s.toLowerCase())?(a=6,xe?(e.consume(k),w):n.interrupt?t(k):M(k)):(a=7,n.interrupt&&!n.parser.lazy[n.now().line]?r(k):i?T(k):_(k))}return k===45||Ae(k)?(e.consume(k),s+=String.fromCharCode(k),b):r(k)}function w(k){return k===62?(e.consume(k),n.interrupt?t:M):r(k)}function T(k){return te(k)?(e.consume(k),T):S(k)}function _(k){return k===47?(e.consume(k),S):k===58||k===95||Be(k)?(e.consume(k),D):te(k)?(e.consume(k),_):S(k)}function D(k){return k===45||k===46||k===58||k===95||Ae(k)?(e.consume(k),D):z(k)}function z(k){return k===61?(e.consume(k),I):te(k)?(e.consume(k),z):_(k)}function I(k){return k===null||k===60||k===61||k===62||k===96?r(k):k===34||k===39?(e.consume(k),l=k,B):te(k)?(e.consume(k),I):H(k)}function B(k){return k===l?(e.consume(k),l=null,j):k===null||J(k)?r(k):(e.consume(k),B)}function H(k){return k===null||k===34||k===39||k===47||k===60||k===61||k===62||k===96||le(k)?z(k):(e.consume(k),H)}function j(k){return k===47||k===62||te(k)?_(k):r(k)}function S(k){return k===62?(e.consume(k),N):r(k)}function N(k){return k===null||J(k)?M(k):te(k)?(e.consume(k),N):r(k)}function M(k){return k===45&&a===2?(e.consume(k),Q):k===60&&a===1?(e.consume(k),ue):k===62&&a===4?(e.consume(k),se):k===63&&a===3?(e.consume(k),x):k===93&&a===5?(e.consume(k),de):J(k)&&(a===6||a===7)?(e.exit("htmlFlowData"),e.check(lg,we,U)(k)):k===null||J(k)?(e.exit("htmlFlowData"),U(k)):(e.consume(k),M)}function U(k){return e.check(ug,R,we)(k)}function R(k){return e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),F}function F(k){return k===null||J(k)?U(k):(e.enter("htmlFlowData"),M(k))}function Q(k){return k===45?(e.consume(k),x):M(k)}function ue(k){return k===47?(e.consume(k),s="",pe):M(k)}function pe(k){if(k===62){const xe=s.toLowerCase();return al.includes(xe)?(e.consume(k),se):M(k)}return Be(k)&&s.length<8?(e.consume(k),s+=String.fromCharCode(k),pe):M(k)}function de(k){return k===93?(e.consume(k),x):M(k)}function x(k){return k===62?(e.consume(k),se):k===45&&a===2?(e.consume(k),x):M(k)}function se(k){return k===null||J(k)?(e.exit("htmlFlowData"),we(k)):(e.consume(k),se)}function we(k){return e.exit("htmlFlow"),t(k)}}function hg(e,t,r){const n=this;return a;function a(s){return J(s)?(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),i):r(s)}function i(s){return n.parser.lazy[n.now().line]?r(s):t(s)}}function fg(e,t,r){return n;function n(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),e.attempt(xr,t,r)}}const pg={name:"htmlText",tokenize:mg};function mg(e,t,r){const n=this;let a,i,s;return o;function o(x){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(x),l}function l(x){return x===33?(e.consume(x),u):x===47?(e.consume(x),z):x===63?(e.consume(x),_):Be(x)?(e.consume(x),H):r(x)}function u(x){return x===45?(e.consume(x),d):x===91?(e.consume(x),i=0,g):Be(x)?(e.consume(x),T):r(x)}function d(x){return x===45?(e.consume(x),f):r(x)}function c(x){return x===null?r(x):x===45?(e.consume(x),h):J(x)?(s=c,ue(x)):(e.consume(x),c)}function h(x){return x===45?(e.consume(x),f):c(x)}function f(x){return x===62?Q(x):x===45?h(x):c(x)}function g(x){const se="CDATA[";return x===se.charCodeAt(i++)?(e.consume(x),i===se.length?v:g):r(x)}function v(x){return x===null?r(x):x===93?(e.consume(x),b):J(x)?(s=v,ue(x)):(e.consume(x),v)}function b(x){return x===93?(e.consume(x),w):v(x)}function w(x){return x===62?Q(x):x===93?(e.consume(x),w):v(x)}function T(x){return x===null||x===62?Q(x):J(x)?(s=T,ue(x)):(e.consume(x),T)}function _(x){return x===null?r(x):x===63?(e.consume(x),D):J(x)?(s=_,ue(x)):(e.consume(x),_)}function D(x){return x===62?Q(x):_(x)}function z(x){return Be(x)?(e.consume(x),I):r(x)}function I(x){return x===45||Ae(x)?(e.consume(x),I):B(x)}function B(x){return J(x)?(s=B,ue(x)):te(x)?(e.consume(x),B):Q(x)}function H(x){return x===45||Ae(x)?(e.consume(x),H):x===47||x===62||le(x)?j(x):r(x)}function j(x){return x===47?(e.consume(x),Q):x===58||x===95||Be(x)?(e.consume(x),S):J(x)?(s=j,ue(x)):te(x)?(e.consume(x),j):Q(x)}function S(x){return x===45||x===46||x===58||x===95||Ae(x)?(e.consume(x),S):N(x)}function N(x){return x===61?(e.consume(x),M):J(x)?(s=N,ue(x)):te(x)?(e.consume(x),N):j(x)}function M(x){return x===null||x===60||x===61||x===62||x===96?r(x):x===34||x===39?(e.consume(x),a=x,U):J(x)?(s=M,ue(x)):te(x)?(e.consume(x),M):(e.consume(x),R)}function U(x){return x===a?(e.consume(x),a=void 0,F):x===null?r(x):J(x)?(s=U,ue(x)):(e.consume(x),U)}function R(x){return x===null||x===34||x===39||x===60||x===61||x===96?r(x):x===47||x===62||le(x)?j(x):(e.consume(x),R)}function F(x){return x===47||x===62||le(x)?j(x):r(x)}function Q(x){return x===62?(e.consume(x),e.exit("htmlTextData"),e.exit("htmlText"),t):r(x)}function ue(x){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(x),e.exit("lineEnding"),pe}function pe(x){return te(x)?ne(e,de,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(x):de(x)}function de(x){return e.enter("htmlTextData"),s(x)}}const Sa={name:"labelEnd",resolveAll:wg,resolveTo:xg,tokenize:vg},gg={tokenize:kg},yg={tokenize:Sg},bg={tokenize:_g};function wg(e){let t=-1;const r=[];for(;++t<e.length;){const n=e[t][1];if(r.push(e[t]),n.type==="labelImage"||n.type==="labelLink"||n.type==="labelEnd"){const a=n.type==="labelImage"?4:2;n.type="data",t+=a}}return e.length!==r.length&&We(e,0,e.length,r),e}function xg(e,t){let r=e.length,n=0,a,i,s,o;for(;r--;)if(a=e[r][1],i){if(a.type==="link"||a.type==="labelLink"&&a._inactive)break;e[r][0]==="enter"&&a.type==="labelLink"&&(a._inactive=!0)}else if(s){if(e[r][0]==="enter"&&(a.type==="labelImage"||a.type==="labelLink")&&!a._balanced&&(i=r,a.type!=="labelLink")){n=2;break}}else a.type==="labelEnd"&&(s=r);const l={type:e[i][1].type==="labelLink"?"link":"image",start:m({},e[i][1].start),end:m({},e[e.length-1][1].end)},u={type:"label",start:m({},e[i][1].start),end:m({},e[s][1].end)},d={type:"labelText",start:m({},e[i+n+2][1].end),end:m({},e[s-2][1].start)};return o=[["enter",l,t],["enter",u,t]],o=Xe(o,e.slice(i+1,i+n+3)),o=Xe(o,[["enter",d,t]]),o=Xe(o,sn(t.parser.constructs.insideSpan.null,e.slice(i+n+4,s-3),t)),o=Xe(o,[["exit",d,t],e[s-2],e[s-1],["exit",u,t]]),o=Xe(o,e.slice(s+1)),o=Xe(o,[["exit",l,t]]),We(e,i,e.length,o),e}function vg(e,t,r){const n=this;let a=n.events.length,i,s;for(;a--;)if((n.events[a][1].type==="labelImage"||n.events[a][1].type==="labelLink")&&!n.events[a][1]._balanced){i=n.events[a][1];break}return o;function o(h){return i?i._inactive?c(h):(s=n.parser.defined.includes(at(n.sliceSerialize({start:i.end,end:n.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(h),e.exit("labelMarker"),e.exit("labelEnd"),l):r(h)}function l(h){return h===40?e.attempt(gg,d,s?d:c)(h):h===91?e.attempt(yg,d,s?u:c)(h):s?d(h):c(h)}function u(h){return e.attempt(bg,d,c)(h)}function d(h){return t(h)}function c(h){return i._balanced=!0,r(h)}}function kg(e,t,r){return n;function n(c){return e.enter("resource"),e.enter("resourceMarker"),e.consume(c),e.exit("resourceMarker"),a}function a(c){return le(c)?kr(e,i)(c):i(c)}function i(c){return c===41?d(c):tl(e,s,o,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(c)}function s(c){return le(c)?kr(e,l)(c):d(c)}function o(c){return r(c)}function l(c){return c===34||c===39||c===40?nl(e,u,r,"resourceTitle","resourceTitleMarker","resourceTitleString")(c):d(c)}function u(c){return le(c)?kr(e,d)(c):d(c)}function d(c){return c===41?(e.enter("resourceMarker"),e.consume(c),e.exit("resourceMarker"),e.exit("resource"),t):r(c)}}function Sg(e,t,r){const n=this;return a;function a(o){return rl.call(n,e,i,s,"reference","referenceMarker","referenceString")(o)}function i(o){return n.parser.defined.includes(at(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)))?t(o):r(o)}function s(o){return r(o)}}function _g(e,t,r){return n;function n(i){return e.enter("reference"),e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),a}function a(i){return i===93?(e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),e.exit("reference"),t):r(i)}}const Tg={name:"labelStartImage",resolveAll:Sa.resolveAll,tokenize:Cg};function Cg(e,t,r){const n=this;return a;function a(o){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(o),e.exit("labelImageMarker"),i}function i(o){return o===91?(e.enter("labelMarker"),e.consume(o),e.exit("labelMarker"),e.exit("labelImage"),s):r(o)}function s(o){return o===94&&"_hiddenFootnoteSupport"in n.parser.constructs?r(o):t(o)}}const Ig={name:"labelStartLink",resolveAll:Sa.resolveAll,tokenize:Eg};function Eg(e,t,r){const n=this;return a;function a(s){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(s),e.exit("labelMarker"),e.exit("labelLink"),i}function i(s){return s===94&&"_hiddenFootnoteSupport"in n.parser.constructs?r(s):t(s)}}const _a={name:"lineEnding",tokenize:Ag};function Ag(e,t){return r;function r(n){return e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),ne(e,t,"linePrefix")}}const on={name:"thematicBreak",tokenize:Mg};function Mg(e,t,r){let n=0,a;return i;function i(u){return e.enter("thematicBreak"),s(u)}function s(u){return a=u,o(u)}function o(u){return u===a?(e.enter("thematicBreakSequence"),l(u)):n>=3&&(u===null||J(u))?(e.exit("thematicBreak"),t(u)):r(u)}function l(u){return u===a?(e.consume(u),n++,l):(e.exit("thematicBreakSequence"),te(u)?ne(e,o,"whitespace")(u):o(u))}}const $e={continuation:{tokenize:Dg},exit:Fg,name:"list",tokenize:Lg},Pg={partial:!0,tokenize:Bg},Ng={partial:!0,tokenize:Og};function Lg(e,t,r){const n=this,a=n.events[n.events.length-1];let i=a&&a[1].type==="linePrefix"?a[2].sliceSerialize(a[1],!0).length:0,s=0;return o;function o(f){const g=n.containerState.type||(f===42||f===43||f===45?"listUnordered":"listOrdered");if(g==="listUnordered"?!n.containerState.marker||f===n.containerState.marker:xa(f)){if(n.containerState.type||(n.containerState.type=g,e.enter(g,{_container:!0})),g==="listUnordered")return e.enter("listItemPrefix"),f===42||f===45?e.check(on,r,u)(f):u(f);if(!n.interrupt||f===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),l(f)}return r(f)}function l(f){return xa(f)&&++s<10?(e.consume(f),l):(!n.interrupt||s<2)&&(n.containerState.marker?f===n.containerState.marker:f===41||f===46)?(e.exit("listItemValue"),u(f)):r(f)}function u(f){return e.enter("listItemMarker"),e.consume(f),e.exit("listItemMarker"),n.containerState.marker=n.containerState.marker||f,e.check(xr,n.interrupt?r:d,e.attempt(Pg,h,c))}function d(f){return n.containerState.initialBlankLine=!0,i++,h(f)}function c(f){return te(f)?(e.enter("listItemPrefixWhitespace"),e.consume(f),e.exit("listItemPrefixWhitespace"),h):r(f)}function h(f){return n.containerState.size=i+n.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(f)}}function Dg(e,t,r){const n=this;return n.containerState._closeFlow=void 0,e.check(xr,a,i);function a(o){return n.containerState.furtherBlankLines=n.containerState.furtherBlankLines||n.containerState.initialBlankLine,ne(e,t,"listItemIndent",n.containerState.size+1)(o)}function i(o){return n.containerState.furtherBlankLines||!te(o)?(n.containerState.furtherBlankLines=void 0,n.containerState.initialBlankLine=void 0,s(o)):(n.containerState.furtherBlankLines=void 0,n.containerState.initialBlankLine=void 0,e.attempt(Ng,t,s)(o))}function s(o){return n.containerState._closeFlow=!0,n.interrupt=void 0,ne(e,e.attempt($e,t,r),"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function Og(e,t,r){const n=this;return ne(e,a,"listItemIndent",n.containerState.size+1);function a(i){const s=n.events[n.events.length-1];return s&&s[1].type==="listItemIndent"&&s[2].sliceSerialize(s[1],!0).length===n.containerState.size?t(i):r(i)}}function Fg(e){e.exit(this.containerState.type)}function Bg(e,t,r){const n=this;return ne(e,a,"listItemPrefixWhitespace",n.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function a(i){const s=n.events[n.events.length-1];return!te(i)&&s&&s[1].type==="listItemPrefixWhitespace"?t(i):r(i)}}const il={name:"setextUnderline",resolveTo:zg,tokenize:Rg};function zg(e,t){let r=e.length,n,a,i;for(;r--;)if(e[r][0]==="enter"){if(e[r][1].type==="content"){n=r;break}e[r][1].type==="paragraph"&&(a=r)}else e[r][1].type==="content"&&e.splice(r,1),!i&&e[r][1].type==="definition"&&(i=r);const s={type:"setextHeading",start:m({},e[n][1].start),end:m({},e[e.length-1][1].end)};return e[a][1].type="setextHeadingText",i?(e.splice(a,0,["enter",s,t]),e.splice(i+1,0,["exit",e[n][1],t]),e[n][1].end=m({},e[i][1].end)):e[n][1]=s,e.push(["exit",s,t]),e}function Rg(e,t,r){const n=this;let a;return i;function i(u){let d=n.events.length,c;for(;d--;)if(n.events[d][1].type!=="lineEnding"&&n.events[d][1].type!=="linePrefix"&&n.events[d][1].type!=="content"){c=n.events[d][1].type==="paragraph";break}return!n.parser.lazy[n.now().line]&&(n.interrupt||c)?(e.enter("setextHeadingLine"),a=u,s(u)):r(u)}function s(u){return e.enter("setextHeadingLineSequence"),o(u)}function o(u){return u===a?(e.consume(u),o):(e.exit("setextHeadingLineSequence"),te(u)?ne(e,l,"lineSuffix")(u):l(u))}function l(u){return u===null||J(u)?(e.exit("setextHeadingLine"),t(u)):r(u)}}const jg={tokenize:$g};function $g(e){const t=this,r=e.attempt(xr,n,e.attempt(this.parser.constructs.flowInitial,a,ne(e,e.attempt(this.parser.constructs.flow,a,e.attempt(Wm,a)),"linePrefix")));return r;function n(i){if(i===null){e.consume(i);return}return e.enter("lineEndingBlank"),e.consume(i),e.exit("lineEndingBlank"),t.currentConstruct=void 0,r}function a(i){if(i===null){e.consume(i);return}return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),t.currentConstruct=void 0,r}}const Ug={resolveAll:ol()},Hg=sl("string"),qg=sl("text");function sl(e){return{resolveAll:ol(e==="text"?Vg:void 0),tokenize:t};function t(r){const n=this,a=this.parser.constructs[e],i=r.attempt(a,s,o);return s;function s(d){return u(d)?i(d):o(d)}function o(d){if(d===null){r.consume(d);return}return r.enter("data"),r.consume(d),l}function l(d){return u(d)?(r.exit("data"),i(d)):(r.consume(d),l)}function u(d){if(d===null)return!0;const c=a[d];let h=-1;if(c)for(;++h<c.length;){const f=c[h];if(!f.previous||f.previous.call(n,n.previous))return!0}return!1}}}function ol(e){return t;function t(r,n){let a=-1,i;for(;++a<=r.length;)i===void 0?r[a]&&r[a][1].type==="data"&&(i=a,a++):(!r[a]||r[a][1].type!=="data")&&(a!==i+2&&(r[i][1].end=r[a-1][1].end,r.splice(i+2,a-i-2),a=i+2),i=void 0);return e?e(r,n):r}}function Vg(e,t){let r=0;for(;++r<=e.length;)if((r===e.length||e[r][1].type==="lineEnding")&&e[r-1][1].type==="data"){const n=e[r-1][1],a=t.sliceStream(n);let i=a.length,s=-1,o=0,l;for(;i--;){const u=a[i];if(typeof u=="string"){for(s=u.length;u.charCodeAt(s-1)===32;)o++,s--;if(s)break;s=-1}else if(u===-2)l=!0,o++;else if(u!==-1){i++;break}}if(t._contentTypeTextTrailing&&r===e.length&&(o=0),o){const u={type:r===e.length||l||o<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:i?s:n.start._bufferIndex+s,_index:n.start._index+i,line:n.end.line,column:n.end.column-o,offset:n.end.offset-o},end:m({},n.end)};n.end=m({},u.start),n.start.offset===n.end.offset?Object.assign(n,u):(e.splice(r,0,["enter",u,t],["exit",u,t]),r+=2)}r++}return e}const Wg=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:{null:[42,95]},contentInitial:{91:Xm},disable:{null:[]},document:{42:$e,43:$e,45:$e,48:$e,49:$e,50:$e,51:$e,52:$e,53:$e,54:$e,55:$e,56:$e,57:$e,62:Ko},flow:{35:ng,42:on,45:[il,on],60:og,61:il,95:on,96:Zo,126:Zo},flowInitial:{[-2]:ka,[-1]:ka,32:ka},insideSpan:{null:[va,Ug]},string:{38:Xo,92:Go},text:{[-5]:_a,[-4]:_a,[-3]:_a,33:Tg,38:Xo,42:va,60:[Im,pg],91:Ig,92:[tg,Go],93:Sa,95:va,96:jm}},Symbol.toStringTag,{value:"Module"}));function Jg(e,t,r){let n={_bufferIndex:-1,_index:0,line:r&&r.line||1,column:r&&r.column||1,offset:r&&r.offset||0};const a={},i=[];let s=[],o=[];const l={attempt:B(z),check:B(I),consume:T,enter:_,exit:D,interrupt:B(I,{interrupt:!0})},u={code:null,containerState:{},defineSkip:v,events:[],now:g,parser:e,previous:null,sliceSerialize:h,sliceStream:f,write:c};let d=t.tokenize.call(u,l);return t.resolveAll&&i.push(t),u;function c(N){return s=Xe(s,N),b(),s[s.length-1]!==null?[]:(H(t,0),u.events=sn(i,u.events,u),u.events)}function h(N,M){return Kg(f(N),M)}function f(N){return Yg(s,N)}function g(){const{_bufferIndex:N,_index:M,line:U,column:R,offset:F}=n;return{_bufferIndex:N,_index:M,line:U,column:R,offset:F}}function v(N){a[N.line]=N.column,S()}function b(){let N;for(;n._index<s.length;){const M=s[n._index];if(typeof M=="string")for(N=n._index,n._bufferIndex<0&&(n._bufferIndex=0);n._index===N&&n._bufferIndex<M.length;)w(M.charCodeAt(n._bufferIndex));else w(M)}}function w(N){d=d(N)}function T(N){J(N)?(n.line++,n.column=1,n.offset+=N===-3?2:1,S()):N!==-1&&(n.column++,n.offset++),n._bufferIndex<0?n._index++:(n._bufferIndex++,n._bufferIndex===s[n._index].length&&(n._bufferIndex=-1,n._index++)),u.previous=N}function _(N,M){const U=M||{};return U.type=N,U.start=g(),u.events.push(["enter",U,u]),o.push(U),U}function D(N){const M=o.pop();return M.end=g(),u.events.push(["exit",M,u]),M}function z(N,M){H(N,M.from)}function I(N,M){M.restore()}function B(N,M){return U;function U(R,F,Q){let ue,pe,de,x;return Array.isArray(R)?we(R):"tokenize"in R?we([R]):se(R);function se(ye){return W;function W(ie){const be=ie!==null&&ye[ie],ve=ie!==null&&ye.null,Me=[...Array.isArray(be)?be:be?[be]:[],...Array.isArray(ve)?ve:ve?[ve]:[]];return we(Me)(ie)}}function we(ye){return ue=ye,pe=0,ye.length===0?Q:k(ye[pe])}function k(ye){return W;function W(ie){return x=j(),de=ye,ye.partial||(u.currentConstruct=ye),ye.name&&u.parser.constructs.disable.null.includes(ye.name)?Ue():ye.tokenize.call(M?Object.assign(Object.create(u),M):u,l,xe,Ue)(ie)}}function xe(ye){return N(de,x),F}function Ue(ye){return x.restore(),++pe<ue.length?k(ue[pe]):Q}}}function H(N,M){N.resolveAll&&!i.includes(N)&&i.push(N),N.resolve&&We(u.events,M,u.events.length-M,N.resolve(u.events.slice(M),u)),N.resolveTo&&(u.events=N.resolveTo(u.events,u))}function j(){const N=g(),M=u.previous,U=u.currentConstruct,R=u.events.length,F=Array.from(o);return{from:R,restore:Q};function Q(){n=N,u.previous=M,u.currentConstruct=U,u.events.length=R,o=F,S()}}function S(){n.line in a&&n.column<2&&(n.column=a[n.line],n.offset+=a[n.line]-1)}}function Yg(e,t){const r=t.start._index,n=t.start._bufferIndex,a=t.end._index,i=t.end._bufferIndex;let s;if(r===a)s=[e[r].slice(n,i)];else{if(s=e.slice(r,a),n>-1){const o=s[0];typeof o=="string"?s[0]=o.slice(n):s.shift()}i>0&&s.push(e[a].slice(0,i))}return s}function Kg(e,t){let r=-1;const n=[];let a;for(;++r<e.length;){const i=e[r];let s;if(typeof i=="string")s=i;else switch(i){case-5:{s="\r";break}case-4:{s=`
7
+ `);a=o.pop()||"";for(const l of o)if(l.startsWith("data: ")){const u=l.slice(6);if(u.trim()==="[DONE]"){yield{done:!0};continue}try{yield JSON.parse(u)}catch(d){}}}}finally{r.releaseLock()}})}function dp(e){return e.map(t=>{let r="";if(typeof t.content=="string")r=t.content;else if(Array.isArray(t.content)){const n=t.content.find(a=>a.type==="text");n&&typeof n=="object"&&"text"in n&&(r=n.text)}return{role:t.role,content:r}})}function hp(e){return m(m({id:e.id,role:e.role,content:[{type:"text",text:e.content}],createdAt:new Date(e.createdAt),metadata:{custom:{}}},e.role==="assistant"&&{status:{type:"complete",reason:"stop"},metadata:{unstable_state:null,unstable_annotations:[],unstable_data:[],steps:[],custom:{}}}),e.role==="user"&&{attachments:[]})}const mr=new Map,aa=new Map;function fp(e,t){return{list(){return P(this,null,function*(){const n=[];let i,s=0;do{const l=yield e.listChats({limit:50,cursor:i}),u=l.items||[];Array.isArray(u)&&u.length>0&&n.push(...u),i=l.nextCursor||void 0,s++}while(i&&s<50);return{threads:n.map(l=>{const u=l.id;return!u||l.deletedAt?null:{status:"regular",remoteId:u,title:l.title||"New Chat",createdAt:l.createdAt?new Date(l.createdAt):new Date,updatedAt:l.updatedAt?new Date(l.updatedAt):new Date}}).filter(l=>l!==null)}})},initialize(n){return P(this,null,function*(){return{remoteId:mr.get(n)||n,externalId:void 0}})},rename(n,a){return P(this,null,function*(){const i=mr.get(n)||n;yield e.updateChat(i,{title:a})})},archive(n){return P(this,null,function*(){})},unarchive(n){return P(this,null,function*(){})},delete(n){return P(this,null,function*(){const a=mr.get(n)||n;yield e.deleteChat(a)})},generateTitle(n,a){return P(this,null,function*(){return new ReadableStream})},fetch(n){return P(this,null,function*(){try{const a=yield e.getChat(n);return{status:"regular",remoteId:a.id||n,title:a.title||"Chat",createdAt:a.createdAt?new Date(a.createdAt):new Date,updatedAt:a.updatedAt?new Date(a.updatedAt):new Date}}catch(a){return{status:"regular",remoteId:n,createdAt:new Date,updatedAt:new Date}}})},updateRemoteId(n,a){mr.set(n,a),t==null||t(n,a)},unstable_Provider:({children:n})=>{const a=cs(),i=a==null?void 0:a.remoteId,s=y.useMemo(()=>({load(){return P(this,null,function*(){if(!i)return{messages:[]};try{const u=yield e.getChat(i);if(!u.messages||u.messages.length===0)return{messages:[]};const d=u.messages.map(h=>hp(h)),c=d.map((h,f)=>({message:h,parentId:f>0?d[f-1].id:null}));for(const h of d)aa.set(h.id,i);return{messages:c}}catch(u){return{messages:[]}}})},append(u){return P(this,null,function*(){})}}),[i,e]),o=y.useMemo(()=>({history:s}),[s]);return p.jsx(Bn,{adapters:o,children:n})}}}class pp{constructor(){C(this,"messageMetadata",new Map);C(this,"currentMessageId",null);C(this,"listeners",new Set)}setCurrentMessage(t){this.currentMessageId=t}update(t){if(!this.currentMessageId)return;const r=this.messageMetadata.get(this.currentMessageId)||{},n=t.sources;n&&n.length>0&&(this.messageMetadata.set(this.currentMessageId,E(m({},r),{sources:n})),this.notify())}get(){return this.currentMessageId?this.messageMetadata.get(this.currentMessageId)||{}:{}}getForMessage(t){return this.messageMetadata.get(t)||{}}getCurrentMessageId(){return this.currentMessageId}clear(){this.currentMessageId=null}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}notify(){this.listeners.forEach(t=>t())}}const xt=new pp,po=new Map,ia=[];let tn=[];function mo(e,t,r=50,n=800){ia.push({question:e,response:t,streamingSpeed:r,initialDelay:n})}function go(e,t){const{modelId:r,systemPrompt:n,ephemeral:a,enableReasoning:i,onChatCreated:s,onUserMessage:o,onThreadIdUpdate:l,onBeforeRequest:u,mockResponseOnBlocked:d}=t;let c;return{run(f){return Nr(this,null,function*(){var Ce,he,x,le,we;const{messages:g,abortSignal:v}=f,b=ia.shift();if(b){o==null||o();const $=(Ce=b.initialDelay)!=null?Ce:800;if($>0&&(yield new Ee(new Promise(ne=>setTimeout(ne,$)))),v!=null&&v.aborted)throw new Error("Request aborted");const Z=b.response.split(" ");let fe="";const be=b.streamingSpeed||50,Ne=`premade-${Date.now()}`;a&&(s==null||s(Ne));for(let ne=0;ne<Z.length;ne++){if(v!=null&&v.aborted)throw new Error("Request aborted");fe+=(ne===0?"":" ")+Z[ne],yield{content:[{type:"text",text:fe}]},yield new Ee(new Promise(ve=>setTimeout(ve,be+Math.random()*(be*.5))))}yield{content:[{type:"text",text:fe}]},tn.push({role:"user",content:b.question},{role:"assistant",content:b.response});return}let w;for(const $ of g){const Z=aa.get($.id);if(Z){w=Z;break}}if(!w&&g.length>0){const $=g.find(Z=>Z.role==="user");if($){const fe=(typeof $.content=="string"?$.content:Array.isArray($.content)&&((he=$.content.find(be=>be.type==="text"))==null?void 0:he.text)||"").substring(0,50);w=po.get(fe)}}!w&&c&&(w=c),o==null||o();let _=g,T=-1;for(let $=g.length-1;$>=0;$--)if(g[$].role==="assistant"){T=$;break}(w||T>=0)&&T>=0&&(_=g.slice(T+1));const B=dp(_);if(tn.length>0&&!w){const $=tn.map(Z=>({role:Z.role,content:Z.content}));B.unshift(...$),tn=[]}const j=[];let I;for(let $=_.length-1;$>=0;$--)if(_[$].role==="user"){I=_[$];break}if(I&&"attachments"in I){const $=I.attachments;if($&&$.length>0){for(const Z of $)if(Z.file)try{const fe=yield new Ee(e.uploadFile(Z.file));j.push(fe.id)}catch(fe){}}}const z={messages:B,chatId:w||null,systemPrompt:n,ephemeral:a,enableReasoning:i,stream:!0};if(r&&r.trim()!==""&&(z.modelId=r),j.length>0&&(z.fileIds=j),u&&!(yield new Ee(u()))){if(d){const Z=typeof d=="function"?d():d,fe=g.filter(ve=>ve.role==="user"),be=fe.length>0?fe[fe.length-1]:void 0;let Ne="Message";if(be){if(typeof be.content=="string")Ne=be.content;else if(Array.isArray(be.content)){const ve=be.content.find(dt=>dt.type==="text");Ne=(ve==null?void 0:ve.text)||"Message"}}mo(Ne,Z,40,400);const ne=ia.shift();if(ne){o==null||o();const ve=(x=ne.initialDelay)!=null?x:400;if(ve>0&&(yield new Ee(new Promise(ke=>setTimeout(ke,ve)))),v!=null&&v.aborted)throw new Error("Request aborted");const dt=ne.response.split(" ");let Je="";const ht=ne.streamingSpeed||40,Dt=`mock-${Date.now()}`;a&&(s==null||s(Dt));for(let ke=0;ke<dt.length;ke++){if(v!=null&&v.aborted)throw new Error("Request aborted");Je+=(ke===0?"":" ")+dt[ke],yield{content:[{type:"text",text:Je}]},yield new Ee(new Promise(Qt=>setTimeout(Qt,ht+Math.random()*(ht*.3))))}yield{content:[{type:"text",text:Je}]};return}}throw new Error("Request blocked")}const H=yield new Ee(e.createOrContinueChat(z,v));let O="",S="",N;const M=[];let W=0,R=!1;const F=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;xt.clear(),xt.setCurrentMessage(F);const Q=()=>{M.length!==W&&(W=M.length,xt.update({sources:M.length>0?[...M]:void 0}))},se=()=>{Q();const $=[];return S&&$.push({type:"reasoning",text:S}),O&&$.push({type:"text",text:O}),$.length===0&&$.push({type:"text",text:""}),{content:$}};try{for(var k=Ft(cp(H,v)),xe,Ue,ye;xe=!(Ue=yield new Ee(k.next())).done;xe=!1){const $=Ue.value;if(v!=null&&v.aborted)throw new Error("Request aborted");const Z=$.id||$.chatId||$.messageId;if(Z&&!N){N=Z,c=Z,s==null||s(Z);for(const ne of g)aa.set(ne.id,Z);if(g.length>0){const ne=g.find(ve=>ve.role==="user");if(ne){const dt=(typeof ne.content=="string"?ne.content:Array.isArray(ne.content)&&((le=ne.content.find(Je=>Je.type==="text"))==null?void 0:le.text)||"").substring(0,50);po.set(dt,Z)}}if(l){for(const[ne,ve]of mr.entries())if(ve===Z){l(ne,Z);break}}}const fe=$.sources;if(fe&&Array.isArray(fe)&&fe.length>0)for(const ne of fe)M.some(ve=>ve.sourceId===ne.sourceId)||M.push({sourceId:ne.sourceId,filename:ne.filename||"Unknown",score:(we=ne.score)!=null?we:1,chunkId:ne.chunkId,datasetId:ne.datasetId});const be=$.reasoning;if(be&&be.length>0&&(S+=be,yield se()),$.type)switch($.type){case"source-document":$.sourceId&&M.push({sourceId:$.sourceId,filename:$.title||"Unknown",score:1});continue;case"reasoning-start":continue;case"reasoning-delta":$.delta&&(S+=$.delta),(O||S)&&(yield se());continue;case"reasoning-end":(O||S)&&(yield se());continue;case"text-delta":$.delta&&(S&&!R&&!O&&(R=!0,yield new Ee(new Promise(ne=>setTimeout(ne,400)))),O+=$.delta),O&&(yield se());continue;case"error":throw new Error($.errorText||"Stream error");case"text-start":case"text-end":case"start":case"start-step":case"finish-step":case"finish":continue}const Ne=$.delta;if(Ne!=null&&(S&&!R&&!O&&(R=!0,yield new Ee(new Promise(ne=>setTimeout(ne,400)))),O+=Ne),$.content&&(O+=$.content),$.message&&(O+=$.message.content||""),$.finished){(O||S||M.length>0)&&(yield se());break}(O||S||M.length>0)&&(yield se())}}catch(Ue){ye=[Ue]}finally{try{xe&&(Ue=k.return)&&(yield new Ee(Ue.call(k)))}finally{if(ye)throw ye[0]}}(O||S||M.length>0)&&(yield se())})}}}class rn extends Error{constructor(t,r,n){super(t),this.code=r,this.file=n,this.name="AttachmentValidationError"}}const mp=["image/jpeg","image/png","image/gif","image/webp","image/svg+xml","application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","text/plain","text/markdown","text/csv","application/json"],gp=[".pdf",".doc",".docx",".xls",".xlsx",".txt",".md",".csv",".json",".jpg",".jpeg",".png",".gif",".webp",".svg"],yp=10*1024*1024;function yo(e){if(e===0)return"0 Bytes";const t=1024,r=["Bytes","KB","MB","GB"],n=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,n)).toFixed(2))+" "+r[n]}function bp(e){return e.lastIndexOf(".")>=0?e.slice(e.lastIndexOf(".")).toLowerCase():""}function wp(e,t){const n={"image/jpeg":[".jpg",".jpeg"],"image/png":[".png"],"image/gif":[".gif"],"image/webp":[".webp"],"image/svg+xml":[".svg"],"application/pdf":[".pdf"],"text/plain":[".txt"],"text/markdown":[".md"],"text/csv":[".csv"],"application/json":[".json"]}[e];return n?n.includes(t.toLowerCase()):!0}function xp(){return typeof crypto!="undefined"&&crypto.randomUUID?"attachment-"+crypto.randomUUID():"attachment-"+Date.now()+"-"+Math.random().toString(36).slice(2,11)}function bo(e={}){const{validation:t={},onValidationError:r,onAttachmentAdded:n,onAttachmentRemoved:a}=e,{maxFileSizeBytes:i=yp,allowedMimeTypes:s=mp,allowedExtensions:o=gp,validateContentType:l=!0}=t,u=o.join(",");function d(h){if(h.size>i){const g=new rn('File "'+h.name+'" is too large ('+yo(h.size)+"). Maximum size is "+yo(i)+".","FILE_TOO_LARGE",h);throw r==null||r(g),g}const f=bp(h.name);if(f&&!o.some(g=>g.toLowerCase()===f)){const g=new rn('File type "'+f+'" is not allowed. Allowed types: '+o.join(", "),"INVALID_TYPE",h);throw r==null||r(g),g}if(h.type&&!s.some(g=>{if(g.endsWith("/*")){const v=g.slice(0,-1);return h.type.startsWith(v)}return h.type===g})){const g=new rn('File type "'+h.type+'" is not allowed.',"INVALID_TYPE",h);throw r==null||r(g),g}if(l&&h.type&&f&&!wp(h.type,f)){const g=new rn('File extension "'+f+'" does not match content type "'+h.type+'".',"VALIDATION_FAILED",h);throw r==null||r(g),g}}return{accept:u,add(f){return P(this,arguments,function*({file:h}){d(h);let g="file";h.type.startsWith("image/")?g="image":(h.type.includes("pdf")||h.type.includes("document")||h.type.includes("text")||h.name.endsWith(".pdf")||h.name.endsWith(".docx")||h.name.endsWith(".txt")||h.name.endsWith(".md")||h.name.endsWith(".csv")||h.name.endsWith(".json"))&&(g="document");const v={id:xp(),type:g,name:h.name,contentType:h.type,file:h,status:{type:"requires-action",reason:"composer-send"}};return n==null||n(v),v})},remove(h){return P(this,null,function*(){a==null||a(h.id)})},send(h){return P(this,null,function*(){if(h.type==="image"&&h.file){const f=yield new Promise((g,v)=>{const b=new FileReader;b.onload=()=>g(b.result),b.onerror=()=>v(new Error("Failed to read file")),b.readAsDataURL(h.file)});return E(m({},h),{status:{type:"complete"},content:[{type:"image",image:f}]})}return E(m({},h),{status:{type:"complete"},content:[]})})}}}function vp({children:e,baseUrl:t,sessionToken:r,isProxyMode:n=!1,mode:a="multiChat",modelId:i,onModelChange:s,ephemeral:o=!1,systemPrompt:l,enableReasoning:u=!1,initialThreadId:d,onError:c,onChatCreated:h,onUserMessage:f,onThreadIdUpdate:g,onChatsLoaded:v,enableAttachments:b=!1,onBeforeRequest:w,mockResponseOnBlocked:_}){const T=y.useMemo(()=>new fo(t,r||void 0,n),[t,r,n]),[B,j]=y.useState(i||null);y.useEffect(()=>{i&&j(i)},[i]);const I=y.useCallback(O=>{h==null||h(O)},[h]),z=y.useCallback((O,S)=>{g==null||g(O,S)},[g]),H=y.useMemo(()=>go(T,{modelId:B||void 0,systemPrompt:l,ephemeral:o,enableReasoning:u,onChatCreated:I,onUserMessage:f,onBeforeRequest:w,mockResponseOnBlocked:_}),[T,B,l,o,u,I,f,w,_]);return a==="singleChat"?p.jsx(kp,{modelAdapter:H,enableAttachments:b,children:e}):p.jsx(Sp,{client:T,modelAdapterOptions:{modelId:B||void 0,systemPrompt:l,ephemeral:o,enableReasoning:u,onChatCreated:I,onUserMessage:f,onBeforeRequest:w,mockResponseOnBlocked:_},initialThreadId:d,onChatsLoaded:v,onThreadIdUpdate:z,onError:c,enableAttachments:b,children:e})}function kp({modelAdapter:e,enableAttachments:t,children:r}){const n=y.useMemo(()=>t?bo():void 0,[t]),a=xs(e,{adapters:m({},n&&{attachments:n})});return p.jsx(ps,{runtime:a,children:r})}function Sp({client:e,modelAdapterOptions:t,initialThreadId:r,onChatsLoaded:n,onThreadIdUpdate:a,onError:i,enableAttachments:s,children:o}){const l=y.useMemo(()=>fp(e,(v,b)=>{a==null||a(v,b)}),[e,a]),u=y.useCallback((v,b)=>{l.updateRemoteId&&l.updateRemoteId(v,b),a==null||a(v,b)},[l,a]),d=y.useMemo(()=>E(m({},l),{list(){return P(this,null,function*(){const b=yield l.list();return n==null||n(),b})}}),[l,n]);y.useEffect(()=>{window.__cuadraThreadListAdapter=d,window.__cuadraThreadListRuntime=null},[d]);const c=y.useMemo(()=>go(e,E(m({},t),{onThreadIdUpdate:u})),[e,t,u]),h=y.useMemo(()=>s?bo():void 0,[s]),f=y.useCallback(()=>xs(c,{adapters:m({},h&&{attachments:h})}),[c,h]),g=Ts({adapter:d,runtimeHook:f});return y.useEffect(()=>{window.__cuadraThreadListRuntime=g},[g]),p.jsx(ps,{runtime:g,children:o})}function $v(){}function Uv(){}function _p(e,t){const r={};return(e[e.length-1]===""?[...e,""]:e).join((r.padRight?" ":"")+","+(r.padLeft===!1?"":" ")).trim()}const Tp=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Cp=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Ip={};function wo(e,t){return(Ip.jsx?Cp:Tp).test(e)}const Ep=/[ \t\n\f\r]/g;function Ap(e){return typeof e=="object"?e.type==="text"?xo(e.value):!1:xo(e)}function xo(e){return e.replace(Ep,"")===""}class gr{constructor(t,r,n){this.normal=r,this.property=t,n&&(this.space=n)}}gr.prototype.normal={},gr.prototype.property={},gr.prototype.space=void 0;function vo(e,t){const r={},n={};for(const a of e)Object.assign(r,a.property),Object.assign(n,a.normal);return new gr(r,n,t)}function sa(e){return e.toLowerCase()}class je{constructor(t,r){this.attribute=r,this.property=t}}je.prototype.attribute="",je.prototype.booleanish=!1,je.prototype.boolean=!1,je.prototype.commaOrSpaceSeparated=!1,je.prototype.commaSeparated=!1,je.prototype.defined=!1,je.prototype.mustUseProperty=!1,je.prototype.number=!1,je.prototype.overloadedBoolean=!1,je.prototype.property="",je.prototype.spaceSeparated=!1,je.prototype.space=void 0;let Mp=0;const G=Mt(),_e=Mt(),oa=Mt(),L=Mt(),de=Mt(),Vt=Mt(),Ve=Mt();function Mt(){return Du(2,++Mp)}const la=Object.freeze(Object.defineProperty({__proto__:null,boolean:G,booleanish:_e,commaOrSpaceSeparated:Ve,commaSeparated:Vt,number:L,overloadedBoolean:oa,spaceSeparated:de},Symbol.toStringTag,{value:"Module"})),ua=Object.keys(la);class ca extends je{constructor(t,r,n,a){let i=-1;if(super(t,r),ko(this,"space",a),typeof n=="number")for(;++i<ua.length;){const s=ua[i];ko(this,ua[i],(n&la[s])===la[s])}}}ca.prototype.defined=!0;function ko(e,t,r){r&&(e[t]=r)}function Wt(e){const t={},r={};for(const[n,a]of Object.entries(e.properties)){const i=new ca(n,e.transform(e.attributes||{},n),a,e.space);e.mustUseProperty&&e.mustUseProperty.includes(n)&&(i.mustUseProperty=!0),t[n]=i,r[sa(n)]=n,r[sa(i.attribute)]=n}return new gr(t,r,e.space)}const So=Wt({properties:{ariaActiveDescendant:null,ariaAtomic:_e,ariaAutoComplete:null,ariaBusy:_e,ariaChecked:_e,ariaColCount:L,ariaColIndex:L,ariaColSpan:L,ariaControls:de,ariaCurrent:null,ariaDescribedBy:de,ariaDetails:null,ariaDisabled:_e,ariaDropEffect:de,ariaErrorMessage:null,ariaExpanded:_e,ariaFlowTo:de,ariaGrabbed:_e,ariaHasPopup:null,ariaHidden:_e,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:de,ariaLevel:L,ariaLive:null,ariaModal:_e,ariaMultiLine:_e,ariaMultiSelectable:_e,ariaOrientation:null,ariaOwns:de,ariaPlaceholder:null,ariaPosInSet:L,ariaPressed:_e,ariaReadOnly:_e,ariaRelevant:null,ariaRequired:_e,ariaRoleDescription:de,ariaRowCount:L,ariaRowIndex:L,ariaRowSpan:L,ariaSelected:_e,ariaSetSize:L,ariaSort:null,ariaValueMax:L,ariaValueMin:L,ariaValueNow:L,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function _o(e,t){return t in e?e[t]:t}function To(e,t){return _o(e,t.toLowerCase())}const Pp=Wt({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Vt,acceptCharset:de,accessKey:de,action:null,allow:null,allowFullScreen:G,allowPaymentRequest:G,allowUserMedia:G,alt:null,as:null,async:G,autoCapitalize:null,autoComplete:de,autoFocus:G,autoPlay:G,blocking:de,capture:null,charSet:null,checked:G,cite:null,className:de,cols:L,colSpan:null,content:null,contentEditable:_e,controls:G,controlsList:de,coords:L|Vt,crossOrigin:null,data:null,dateTime:null,decoding:null,default:G,defer:G,dir:null,dirName:null,disabled:G,download:oa,draggable:_e,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:G,formTarget:null,headers:de,height:L,hidden:oa,high:L,href:null,hrefLang:null,htmlFor:de,httpEquiv:de,id:null,imageSizes:null,imageSrcSet:null,inert:G,inputMode:null,integrity:null,is:null,isMap:G,itemId:null,itemProp:de,itemRef:de,itemScope:G,itemType:de,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:G,low:L,manifest:null,max:null,maxLength:L,media:null,method:null,min:null,minLength:L,multiple:G,muted:G,name:null,nonce:null,noModule:G,noValidate:G,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:G,optimum:L,pattern:null,ping:de,placeholder:null,playsInline:G,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:G,referrerPolicy:null,rel:de,required:G,reversed:G,rows:L,rowSpan:L,sandbox:de,scope:null,scoped:G,seamless:G,selected:G,shadowRootClonable:G,shadowRootDelegatesFocus:G,shadowRootMode:null,shape:null,size:L,sizes:null,slot:null,span:L,spellCheck:_e,src:null,srcDoc:null,srcLang:null,srcSet:null,start:L,step:null,style:null,tabIndex:L,target:null,title:null,translate:null,type:null,typeMustMatch:G,useMap:null,value:_e,width:L,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:de,axis:null,background:null,bgColor:null,border:L,borderColor:null,bottomMargin:L,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:G,declare:G,event:null,face:null,frame:null,frameBorder:null,hSpace:L,leftMargin:L,link:null,longDesc:null,lowSrc:null,marginHeight:L,marginWidth:L,noResize:G,noHref:G,noShade:G,noWrap:G,object:null,profile:null,prompt:null,rev:null,rightMargin:L,rules:null,scheme:null,scrolling:_e,standby:null,summary:null,text:null,topMargin:L,valueType:null,version:null,vAlign:null,vLink:null,vSpace:L,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:G,disableRemotePlayback:G,prefix:null,property:null,results:L,security:null,unselectable:null},space:"html",transform:To}),Np=Wt({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:Ve,accentHeight:L,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:L,amplitude:L,arabicForm:null,ascent:L,attributeName:null,attributeType:null,azimuth:L,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:L,by:null,calcMode:null,capHeight:L,className:de,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:L,diffuseConstant:L,direction:null,display:null,dur:null,divisor:L,dominantBaseline:null,download:G,dx:null,dy:null,edgeMode:null,editable:null,elevation:L,enableBackground:null,end:null,event:null,exponent:L,externalResourcesRequired:null,fill:null,fillOpacity:L,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:Vt,g2:Vt,glyphName:Vt,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:L,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:L,horizOriginX:L,horizOriginY:L,id:null,ideographic:L,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:L,k:L,k1:L,k2:L,k3:L,k4:L,kernelMatrix:Ve,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:L,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:L,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:L,overlineThickness:L,paintOrder:null,panose1:null,path:null,pathLength:L,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:de,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:L,pointsAtY:L,pointsAtZ:L,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Ve,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Ve,rev:Ve,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Ve,requiredFeatures:Ve,requiredFonts:Ve,requiredFormats:Ve,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:L,specularExponent:L,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:L,strikethroughThickness:L,string:null,stroke:null,strokeDashArray:Ve,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:L,strokeOpacity:L,strokeWidth:null,style:null,surfaceScale:L,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Ve,tabIndex:L,tableValues:null,target:null,targetX:L,targetY:L,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Ve,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:L,underlineThickness:L,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:L,values:null,vAlphabetic:L,vMathematical:L,vectorEffect:null,vHanging:L,vIdeographic:L,version:null,vertAdvY:L,vertOriginX:L,vertOriginY:L,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:L,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:_o}),Co=Wt({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}}),Io=Wt({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:To}),Eo=Wt({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),Lp={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},Dp=/[A-Z]/g,Ao=/-[a-z]/g,Op=/^data[-\w.:]+$/i;function Fp(e,t){const r=sa(t);let n=t,a=je;if(r in e.normal)return e.property[e.normal[r]];if(r.length>4&&r.slice(0,4)==="data"&&Op.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(Ao,zp);n="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!Ao.test(i)){let s=i.replace(Dp,Bp);s.charAt(0)!=="-"&&(s="-"+s),t="data"+s}}a=ca}return new a(n,t)}function Bp(e){return"-"+e.toLowerCase()}function zp(e){return e.charAt(1).toUpperCase()}const Rp=vo([So,Pp,Co,Io,Eo],"html"),da=vo([So,Np,Co,Io,Eo],"svg");function jp(e){return e.join(" ").trim()}var Jt={},ha,Mo;function $p(){if(Mo)return ha;Mo=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,r=/^\s*/,n=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,a=/^:\s*/,i=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,s=/^[;\s]*/,o=/^\s+|\s+$/g,l=`
8
+ `,u="/",d="*",c="",h="comment",f="declaration";function g(b,w){if(typeof b!="string")throw new TypeError("First argument must be a string");if(!b)return[];w=w||{};var _=1,T=1;function B(R){var F=R.match(t);F&&(_+=F.length);var Q=R.lastIndexOf(l);T=~Q?R.length-Q:T+R.length}function j(){var R={line:_,column:T};return function(F){return F.position=new I(R),O(),F}}function I(R){this.start=R,this.end={line:_,column:T},this.source=w.source}I.prototype.content=b;function z(R){var F=new Error(w.source+":"+_+":"+T+": "+R);if(F.reason=R,F.filename=w.source,F.line=_,F.column=T,F.source=b,!w.silent)throw F}function H(R){var F=R.exec(b);if(F){var Q=F[0];return B(Q),b=b.slice(Q.length),F}}function O(){H(r)}function S(R){var F;for(R=R||[];F=N();)F!==!1&&R.push(F);return R}function N(){var R=j();if(!(u!=b.charAt(0)||d!=b.charAt(1))){for(var F=2;c!=b.charAt(F)&&(d!=b.charAt(F)||u!=b.charAt(F+1));)++F;if(F+=2,c===b.charAt(F-1))return z("End of comment missing");var Q=b.slice(2,F-2);return T+=2,B(Q),b=b.slice(F),T+=2,R({type:h,comment:Q})}}function M(){var R=j(),F=H(n);if(F){if(N(),!H(a))return z("property missing ':'");var Q=H(i),se=R({type:f,property:v(F[0].replace(e,c)),value:Q?v(Q[0].replace(e,c)):c});return H(s),se}}function W(){var R=[];S(R);for(var F;F=M();)F!==!1&&(R.push(F),S(R));return R}return O(),W()}function v(b){return b?b.replace(o,c):c}return ha=g,ha}var Po;function Up(){if(Po)return Jt;Po=1;var e=Jt&&Jt.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Jt,"__esModule",{value:!0}),Jt.default=r;const t=e($p());function r(n,a){let i=null;if(!n||typeof n!="string")return i;const s=(0,t.default)(n),o=typeof a=="function";return s.forEach(l=>{if(l.type!=="declaration")return;const{property:u,value:d}=l;o?a(u,d,l):d&&(i=i||{},i[u]=d)}),i}return Jt}var yr={},No;function Hp(){if(No)return yr;No=1,Object.defineProperty(yr,"__esModule",{value:!0}),yr.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,r=/^[^-]+$/,n=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,i=function(u){return!u||r.test(u)||e.test(u)},s=function(u,d){return d.toUpperCase()},o=function(u,d){return"".concat(d,"-")},l=function(u,d){return d===void 0&&(d={}),i(u)?u:(u=u.toLowerCase(),d.reactCompat?u=u.replace(a,o):u=u.replace(n,o),u.replace(t,s))};return yr.camelCase=l,yr}var br,Lo;function qp(){if(Lo)return br;Lo=1;var e=br&&br.__importDefault||function(a){return a&&a.__esModule?a:{default:a}},t=e(Up()),r=Hp();function n(a,i){var s={};return!a||typeof a!="string"||(0,t.default)(a,function(o,l){o&&l&&(s[(0,r.camelCase)(o,i)]=l)}),s}return n.default=n,br=n,br}var Vp=qp();const Wp=Lr(Vp),Do=Oo("end"),fa=Oo("start");function Oo(e){return t;function t(r){const n=r&&r.position&&r.position[e]||{};if(typeof n.line=="number"&&n.line>0&&typeof n.column=="number"&&n.column>0)return{line:n.line,column:n.column,offset:typeof n.offset=="number"&&n.offset>-1?n.offset:void 0}}}function Jp(e){const t=fa(e),r=Do(e);if(t&&r)return{start:t,end:r}}function wr(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Fo(e.position):"start"in e||"end"in e?Fo(e):"line"in e||"column"in e?pa(e):""}function pa(e){return Bo(e&&e.line)+":"+Bo(e&&e.column)}function Fo(e){return pa(e&&e.start)+"-"+pa(e&&e.end)}function Bo(e){return e&&typeof e=="number"?e:1}class Me extends Error{constructor(t,r,n){super(),typeof r=="string"&&(n=r,r=void 0);let a="",i={},s=!1;if(r&&("line"in r&&"column"in r?i={place:r}:"start"in r&&"end"in r?i={place:r}:"type"in r?i={ancestors:[r],place:r.position}:i=m({},r)),typeof t=="string"?a=t:!i.cause&&t&&(s=!0,a=t.message,i.cause=t),!i.ruleId&&!i.source&&typeof n=="string"){const l=n.indexOf(":");l===-1?i.ruleId=n:(i.source=n.slice(0,l),i.ruleId=n.slice(l+1))}if(!i.place&&i.ancestors&&i.ancestors){const l=i.ancestors[i.ancestors.length-1];l&&(i.place=l.position)}const o=i.place&&"start"in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=o?o.column:void 0,this.fatal=void 0,this.file="",this.message=a,this.line=o?o.line:void 0,this.name=wr(i.place)||"1:1",this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=s&&i.cause&&typeof i.cause.stack=="string"?i.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}Me.prototype.file="",Me.prototype.name="",Me.prototype.reason="",Me.prototype.message="",Me.prototype.stack="",Me.prototype.column=void 0,Me.prototype.line=void 0,Me.prototype.ancestors=void 0,Me.prototype.cause=void 0,Me.prototype.fatal=void 0,Me.prototype.place=void 0,Me.prototype.ruleId=void 0,Me.prototype.source=void 0;const ma={}.hasOwnProperty,Yp=new Map,Kp=/[A-Z]/g,Gp=new Set(["table","tbody","thead","tfoot","tr"]),Xp=new Set(["td","th"]),zo="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function Qp(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const r=t.filePath||void 0;let n;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");n=sm(r,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");n=im(r,t.jsx,t.jsxs)}const a={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:n,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:r,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?da:Rp,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},i=Ro(a,e,void 0);return i&&typeof i!="string"?i:a.create(e,a.Fragment,{children:i||void 0},void 0)}function Ro(e,t,r){if(t.type==="element")return Zp(e,t,r);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return em(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return rm(e,t,r);if(t.type==="mdxjsEsm")return tm(e,t);if(t.type==="root")return nm(e,t,r);if(t.type==="text")return am(e,t)}function Zp(e,t,r){const n=e.schema;let a=n;t.tagName.toLowerCase()==="svg"&&n.space==="html"&&(a=da,e.schema=a),e.ancestors.push(t);const i=$o(e,t.tagName,!1),s=om(e,t);let o=ya(e,t);return Gp.has(t.tagName)&&(o=o.filter(function(l){return typeof l=="string"?!Ap(l):!0})),jo(e,s,i,t),ga(s,o),e.ancestors.pop(),e.schema=n,e.create(t,i,s,r)}function em(e,t){if(t.data&&t.data.estree&&e.evaluater){const n=t.data.estree.body[0];return n.type,e.evaluater.evaluateExpression(n.expression)}xr(e,t.position)}function tm(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);xr(e,t.position)}function rm(e,t,r){const n=e.schema;let a=n;t.name==="svg"&&n.space==="html"&&(a=da,e.schema=a),e.ancestors.push(t);const i=t.name===null?e.Fragment:$o(e,t.name,!0),s=lm(e,t),o=ya(e,t);return jo(e,s,i,t),ga(s,o),e.ancestors.pop(),e.schema=n,e.create(t,i,s,r)}function nm(e,t,r){const n={};return ga(n,ya(e,t)),e.create(t,e.Fragment,n,r)}function am(e,t){return t.value}function jo(e,t,r,n){typeof r!="string"&&r!==e.Fragment&&e.passNode&&(t.node=n)}function ga(e,t){if(t.length>0){const r=t.length>1?t:t[0];r&&(e.children=r)}}function im(e,t,r){return n;function n(a,i,s,o){const u=Array.isArray(s.children)?r:t;return o?u(i,s,o):u(i,s)}}function sm(e,t){return r;function r(n,a,i,s){const o=Array.isArray(i.children),l=fa(n);return t(a,i,s,o,{columnNumber:l?l.column-1:void 0,fileName:e,lineNumber:l?l.line:void 0},void 0)}}function om(e,t){const r={};let n,a;for(a in t.properties)if(a!=="children"&&ma.call(t.properties,a)){const i=um(e,a,t.properties[a]);if(i){const[s,o]=i;e.tableCellAlignToStyle&&s==="align"&&typeof o=="string"&&Xp.has(t.tagName)?n=o:r[s]=o}}if(n){const i=r.style||(r.style={});i[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=n}return r}function lm(e,t){const r={};for(const n of t.attributes)if(n.type==="mdxJsxExpressionAttribute")if(n.data&&n.data.estree&&e.evaluater){const i=n.data.estree.body[0];i.type;const s=i.expression;s.type;const o=s.properties[0];o.type,Object.assign(r,e.evaluater.evaluateExpression(o.argument))}else xr(e,t.position);else{const a=n.name;let i;if(n.value&&typeof n.value=="object")if(n.value.data&&n.value.data.estree&&e.evaluater){const o=n.value.data.estree.body[0];o.type,i=e.evaluater.evaluateExpression(o.expression)}else xr(e,t.position);else i=n.value===null?!0:n.value;r[a]=i}return r}function ya(e,t){const r=[];let n=-1;const a=e.passKeys?new Map:Yp;for(;++n<t.children.length;){const i=t.children[n];let s;if(e.passKeys){const l=i.type==="element"?i.tagName:i.type==="mdxJsxFlowElement"||i.type==="mdxJsxTextElement"?i.name:void 0;if(l){const u=a.get(l)||0;s=l+"-"+u,a.set(l,u+1)}}const o=Ro(e,i,s);o!==void 0&&r.push(o)}return r}function um(e,t,r){const n=Fp(e.schema,t);if(!(r==null||typeof r=="number"&&Number.isNaN(r))){if(Array.isArray(r)&&(r=n.commaSeparated?_p(r):jp(r)),n.property==="style"){let a=typeof r=="object"?r:cm(e,String(r));return e.stylePropertyNameCase==="css"&&(a=dm(a)),["style",a]}return[e.elementAttributeNameCase==="react"&&n.space?Lp[n.property]||n.property:n.attribute,r]}}function cm(e,t){try{return Wp(t,{reactCompat:!0})}catch(r){if(e.ignoreInvalidStyle)return{};const n=r,a=new Me("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:n,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw a.file=e.filePath||void 0,a.url=zo+"#cannot-parse-style-attribute",a}}function $o(e,t,r){let n;if(!r)n={type:"Literal",value:t};else if(t.includes(".")){const a=t.split(".");let i=-1,s;for(;++i<a.length;){const o=wo(a[i])?{type:"Identifier",name:a[i]}:{type:"Literal",value:a[i]};s=s?{type:"MemberExpression",object:s,property:o,computed:!!(i&&o.type==="Literal"),optional:!1}:o}n=s}else n=wo(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(n.type==="Literal"){const a=n.value;return ma.call(e.components,a)?e.components[a]:a}if(e.evaluater)return e.evaluater.evaluateExpression(n);xr(e)}function xr(e,t){const r=new Me("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw r.file=e.filePath||void 0,r.url=zo+"#cannot-handle-mdx-estrees-without-createevaluater",r}function dm(e){const t={};let r;for(r in e)ma.call(e,r)&&(t[hm(r)]=e[r]);return t}function hm(e){let t=e.replace(Kp,fm);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function fm(e){return"-"+e.toLowerCase()}const ba={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},pm={};function wa(e,t){const r=pm,n=typeof r.includeImageAlt=="boolean"?r.includeImageAlt:!0,a=typeof r.includeHtml=="boolean"?r.includeHtml:!0;return Uo(e,n,a)}function Uo(e,t,r){if(mm(e)){if("value"in e)return e.type==="html"&&!r?"":e.value;if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return Ho(e.children,t,r)}return Array.isArray(e)?Ho(e,t,r):""}function Ho(e,t,r){const n=[];let a=-1;for(;++a<e.length;)n[a]=Uo(e[a],t,r);return n.join("")}function mm(e){return!!(e&&typeof e=="object")}const qo=document.createElement("i");function xa(e){const t="&"+e+";";qo.innerHTML=t;const r=qo.textContent;return r.charCodeAt(r.length-1)===59&&e!=="semi"||r===t?!1:r}function We(e,t,r,n){const a=e.length;let i=0,s;if(t<0?t=-t>a?0:a+t:t=t>a?a:t,r=r>0?r:0,n.length<1e4)s=Array.from(n),s.unshift(t,r),e.splice(...s);else for(r&&e.splice(t,r);i<n.length;)s=n.slice(i,i+1e4),s.unshift(t,0),e.splice(...s),i+=1e4,t+=1e4}function Qe(e,t){return e.length>0?(We(e,e.length,0,t),e):t}const Vo={}.hasOwnProperty;function Wo(e){const t={};let r=-1;for(;++r<e.length;)gm(t,e[r]);return t}function gm(e,t){let r;for(r in t){const a=(Vo.call(e,r)?e[r]:void 0)||(e[r]={}),i=t[r];let s;if(i)for(s in i){Vo.call(a,s)||(a[s]=[]);const o=i[s];ym(a[s],Array.isArray(o)?o:o?[o]:[])}}}function ym(e,t){let r=-1;const n=[];for(;++r<t.length;)(t[r].add==="after"?e:n).push(t[r]);We(e,0,0,n)}function Jo(e,t){const r=Number.parseInt(e,t);return r<9||r===11||r>13&&r<32||r>126&&r<160||r>55295&&r<57344||r>64975&&r<65008||(r&65535)===65535||(r&65535)===65534||r>1114111?"�":String.fromCodePoint(r)}function it(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Be=vt(/[A-Za-z]/),Pe=vt(/[\dA-Za-z]/),bm=vt(/[#-'*+\--9=?A-Z^-~]/);function nn(e){return e!==null&&(e<32||e===127)}const va=vt(/\d/),wm=vt(/[\dA-Fa-f]/),xm=vt(/[!-/:-@[-`{-~]/);function J(e){return e!==null&&e<-2}function ce(e){return e!==null&&(e<0||e===32)}function re(e){return e===-2||e===-1||e===32}const an=vt(new RegExp("\\p{P}|\\p{S}","u")),Pt=vt(/\s/);function vt(e){return t;function t(r){return r!==null&&r>-1&&e.test(String.fromCharCode(r))}}function Yt(e){const t=[];let r=-1,n=0,a=0;for(;++r<e.length;){const i=e.charCodeAt(r);let s="";if(i===37&&Pe(e.charCodeAt(r+1))&&Pe(e.charCodeAt(r+2)))a=2;else if(i<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(i))||(s=String.fromCharCode(i));else if(i>55295&&i<57344){const o=e.charCodeAt(r+1);i<56320&&o>56319&&o<57344?(s=String.fromCharCode(i,o),a=1):s="�"}else s=String.fromCharCode(i);s&&(t.push(e.slice(n,r),encodeURIComponent(s)),n=r+a+1,s=""),a&&(r+=a,a=0)}return t.join("")+e.slice(n)}function ie(e,t,r,n){const a=n?n-1:Number.POSITIVE_INFINITY;let i=0;return s;function s(l){return re(l)?(e.enter(r),o(l)):t(l)}function o(l){return re(l)&&i++<a?(e.consume(l),o):(e.exit(r),t(l))}}const vm={tokenize:km};function km(e){const t=e.attempt(this.parser.constructs.contentInitial,n,a);let r;return t;function n(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),ie(e,t,"linePrefix")}function a(o){return e.enter("paragraph"),i(o)}function i(o){const l=e.enter("chunkText",{contentType:"text",previous:r});return r&&(r.next=l),r=l,s(o)}function s(o){if(o===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(o);return}return J(o)?(e.consume(o),e.exit("chunkText"),i):(e.consume(o),s)}}const Sm={tokenize:_m},Yo={tokenize:Tm};function _m(e){const t=this,r=[];let n=0,a,i,s;return o;function o(T){if(n<r.length){const B=r[n];return t.containerState=B[1],e.attempt(B[0].continuation,l,u)(T)}return u(T)}function l(T){if(n++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,a&&_();const B=t.events.length;let j=B,I;for(;j--;)if(t.events[j][0]==="exit"&&t.events[j][1].type==="chunkFlow"){I=t.events[j][1].end;break}w(n);let z=B;for(;z<t.events.length;)t.events[z][1].end=m({},I),z++;return We(t.events,j+1,0,t.events.slice(B)),t.events.length=z,u(T)}return o(T)}function u(T){if(n===r.length){if(!a)return h(T);if(a.currentConstruct&&a.currentConstruct.concrete)return g(T);t.interrupt=!!(a.currentConstruct&&!a._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(Yo,d,c)(T)}function d(T){return a&&_(),w(n),h(T)}function c(T){return t.parser.lazy[t.now().line]=n!==r.length,s=t.now().offset,g(T)}function h(T){return t.containerState={},e.attempt(Yo,f,g)(T)}function f(T){return n++,r.push([t.currentConstruct,t.containerState]),h(T)}function g(T){if(T===null){a&&_(),w(0),e.consume(T);return}return a=a||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:a,contentType:"flow",previous:i}),v(T)}function v(T){if(T===null){b(e.exit("chunkFlow"),!0),w(0),e.consume(T);return}return J(T)?(e.consume(T),b(e.exit("chunkFlow")),n=0,t.interrupt=void 0,o):(e.consume(T),v)}function b(T,B){const j=t.sliceStream(T);if(B&&j.push(null),T.previous=i,i&&(i.next=T),i=T,a.defineSkip(T.start),a.write(j),t.parser.lazy[T.start.line]){let I=a.events.length;for(;I--;)if(a.events[I][1].start.offset<s&&(!a.events[I][1].end||a.events[I][1].end.offset>s))return;const z=t.events.length;let H=z,O,S;for(;H--;)if(t.events[H][0]==="exit"&&t.events[H][1].type==="chunkFlow"){if(O){S=t.events[H][1].end;break}O=!0}for(w(n),I=z;I<t.events.length;)t.events[I][1].end=m({},S),I++;We(t.events,H+1,0,t.events.slice(z)),t.events.length=I}}function w(T){let B=r.length;for(;B-- >T;){const j=r[B];t.containerState=j[1],j[0].exit.call(t,e)}r.length=T}function _(){a.write([null]),i=void 0,a=void 0,t.containerState._closeFlow=void 0}}function Tm(e,t,r){return ie(e,e.attempt(this.parser.constructs.document,t,r),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Kt(e){if(e===null||ce(e)||Pt(e))return 1;if(an(e))return 2}function sn(e,t,r){const n=[];let a=-1;for(;++a<e.length;){const i=e[a].resolveAll;i&&!n.includes(i)&&(t=i(t,r),n.push(i))}return t}const ka={name:"attention",resolveAll:Cm,tokenize:Im};function Cm(e,t){let r=-1,n,a,i,s,o,l,u,d;for(;++r<e.length;)if(e[r][0]==="enter"&&e[r][1].type==="attentionSequence"&&e[r][1]._close){for(n=r;n--;)if(e[n][0]==="exit"&&e[n][1].type==="attentionSequence"&&e[n][1]._open&&t.sliceSerialize(e[n][1]).charCodeAt(0)===t.sliceSerialize(e[r][1]).charCodeAt(0)){if((e[n][1]._close||e[r][1]._open)&&(e[r][1].end.offset-e[r][1].start.offset)%3&&!((e[n][1].end.offset-e[n][1].start.offset+e[r][1].end.offset-e[r][1].start.offset)%3))continue;l=e[n][1].end.offset-e[n][1].start.offset>1&&e[r][1].end.offset-e[r][1].start.offset>1?2:1;const c=m({},e[n][1].end),h=m({},e[r][1].start);Ko(c,-l),Ko(h,l),s={type:l>1?"strongSequence":"emphasisSequence",start:c,end:m({},e[n][1].end)},o={type:l>1?"strongSequence":"emphasisSequence",start:m({},e[r][1].start),end:h},i={type:l>1?"strongText":"emphasisText",start:m({},e[n][1].end),end:m({},e[r][1].start)},a={type:l>1?"strong":"emphasis",start:m({},s.start),end:m({},o.end)},e[n][1].end=m({},s.start),e[r][1].start=m({},o.end),u=[],e[n][1].end.offset-e[n][1].start.offset&&(u=Qe(u,[["enter",e[n][1],t],["exit",e[n][1],t]])),u=Qe(u,[["enter",a,t],["enter",s,t],["exit",s,t],["enter",i,t]]),u=Qe(u,sn(t.parser.constructs.insideSpan.null,e.slice(n+1,r),t)),u=Qe(u,[["exit",i,t],["enter",o,t],["exit",o,t],["exit",a,t]]),e[r][1].end.offset-e[r][1].start.offset?(d=2,u=Qe(u,[["enter",e[r][1],t],["exit",e[r][1],t]])):d=0,We(e,n-1,r-n+3,u),r=n+u.length-d-2;break}}for(r=-1;++r<e.length;)e[r][1].type==="attentionSequence"&&(e[r][1].type="data");return e}function Im(e,t){const r=this.parser.constructs.attentionMarkers.null,n=this.previous,a=Kt(n);let i;return s;function s(l){return i=l,e.enter("attentionSequence"),o(l)}function o(l){if(l===i)return e.consume(l),o;const u=e.exit("attentionSequence"),d=Kt(l),c=!d||d===2&&a||r.includes(l),h=!a||a===2&&d||r.includes(n);return u._open=!!(i===42?c:c&&(a||!h)),u._close=!!(i===42?h:h&&(d||!c)),t(l)}}function Ko(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const Em={name:"autolink",tokenize:Am};function Am(e,t,r){let n=0;return a;function a(f){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(f),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),i}function i(f){return Be(f)?(e.consume(f),s):f===64?r(f):u(f)}function s(f){return f===43||f===45||f===46||Pe(f)?(n=1,o(f)):u(f)}function o(f){return f===58?(e.consume(f),n=0,l):(f===43||f===45||f===46||Pe(f))&&n++<32?(e.consume(f),o):(n=0,u(f))}function l(f){return f===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(f),e.exit("autolinkMarker"),e.exit("autolink"),t):f===null||f===32||f===60||nn(f)?r(f):(e.consume(f),l)}function u(f){return f===64?(e.consume(f),d):bm(f)?(e.consume(f),u):r(f)}function d(f){return Pe(f)?c(f):r(f)}function c(f){return f===46?(e.consume(f),n=0,d):f===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(f),e.exit("autolinkMarker"),e.exit("autolink"),t):h(f)}function h(f){if((f===45||Pe(f))&&n++<63){const g=f===45?h:c;return e.consume(f),g}return r(f)}}const vr={partial:!0,tokenize:Mm};function Mm(e,t,r){return n;function n(i){return re(i)?ie(e,a,"linePrefix")(i):a(i)}function a(i){return i===null||J(i)?t(i):r(i)}}const Go={continuation:{tokenize:Nm},exit:Lm,name:"blockQuote",tokenize:Pm};function Pm(e,t,r){const n=this;return a;function a(s){if(s===62){const o=n.containerState;return o.open||(e.enter("blockQuote",{_container:!0}),o.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(s),e.exit("blockQuoteMarker"),i}return r(s)}function i(s){return re(s)?(e.enter("blockQuotePrefixWhitespace"),e.consume(s),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(s))}}function Nm(e,t,r){const n=this;return a;function a(s){return re(s)?ie(e,i,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(s):i(s)}function i(s){return e.attempt(Go,t,r)(s)}}function Lm(e){e.exit("blockQuote")}const Xo={name:"characterEscape",tokenize:Dm};function Dm(e,t,r){return n;function n(i){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(i),e.exit("escapeMarker"),a}function a(i){return xm(i)?(e.enter("characterEscapeValue"),e.consume(i),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):r(i)}}const Qo={name:"characterReference",tokenize:Om};function Om(e,t,r){const n=this;let a=0,i,s;return o;function o(c){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(c),e.exit("characterReferenceMarker"),l}function l(c){return c===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(c),e.exit("characterReferenceMarkerNumeric"),u):(e.enter("characterReferenceValue"),i=31,s=Pe,d(c))}function u(c){return c===88||c===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(c),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),i=6,s=wm,d):(e.enter("characterReferenceValue"),i=7,s=va,d(c))}function d(c){if(c===59&&a){const h=e.exit("characterReferenceValue");return s===Pe&&!xa(n.sliceSerialize(h))?r(c):(e.enter("characterReferenceMarker"),e.consume(c),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return s(c)&&a++<i?(e.consume(c),d):r(c)}}const Zo={partial:!0,tokenize:Bm},el={concrete:!0,name:"codeFenced",tokenize:Fm};function Fm(e,t,r){const n=this,a={partial:!0,tokenize:j};let i=0,s=0,o;return l;function l(I){return u(I)}function u(I){const z=n.events[n.events.length-1];return i=z&&z[1].type==="linePrefix"?z[2].sliceSerialize(z[1],!0).length:0,o=I,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),d(I)}function d(I){return I===o?(s++,e.consume(I),d):s<3?r(I):(e.exit("codeFencedFenceSequence"),re(I)?ie(e,c,"whitespace")(I):c(I))}function c(I){return I===null||J(I)?(e.exit("codeFencedFence"),n.interrupt?t(I):e.check(Zo,v,B)(I)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),h(I))}function h(I){return I===null||J(I)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),c(I)):re(I)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),ie(e,f,"whitespace")(I)):I===96&&I===o?r(I):(e.consume(I),h)}function f(I){return I===null||J(I)?c(I):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(I))}function g(I){return I===null||J(I)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),c(I)):I===96&&I===o?r(I):(e.consume(I),g)}function v(I){return e.attempt(a,B,b)(I)}function b(I){return e.enter("lineEnding"),e.consume(I),e.exit("lineEnding"),w}function w(I){return i>0&&re(I)?ie(e,_,"linePrefix",i+1)(I):_(I)}function _(I){return I===null||J(I)?e.check(Zo,v,B)(I):(e.enter("codeFlowValue"),T(I))}function T(I){return I===null||J(I)?(e.exit("codeFlowValue"),_(I)):(e.consume(I),T)}function B(I){return e.exit("codeFenced"),t(I)}function j(I,z,H){let O=0;return S;function S(F){return I.enter("lineEnding"),I.consume(F),I.exit("lineEnding"),N}function N(F){return I.enter("codeFencedFence"),re(F)?ie(I,M,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(F):M(F)}function M(F){return F===o?(I.enter("codeFencedFenceSequence"),W(F)):H(F)}function W(F){return F===o?(O++,I.consume(F),W):O>=s?(I.exit("codeFencedFenceSequence"),re(F)?ie(I,R,"whitespace")(F):R(F)):H(F)}function R(F){return F===null||J(F)?(I.exit("codeFencedFence"),z(F)):H(F)}}}function Bm(e,t,r){const n=this;return a;function a(s){return s===null?r(s):(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),i)}function i(s){return n.parser.lazy[n.now().line]?r(s):t(s)}}const Sa={name:"codeIndented",tokenize:Rm},zm={partial:!0,tokenize:jm};function Rm(e,t,r){const n=this;return a;function a(u){return e.enter("codeIndented"),ie(e,i,"linePrefix",5)(u)}function i(u){const d=n.events[n.events.length-1];return d&&d[1].type==="linePrefix"&&d[2].sliceSerialize(d[1],!0).length>=4?s(u):r(u)}function s(u){return u===null?l(u):J(u)?e.attempt(zm,s,l)(u):(e.enter("codeFlowValue"),o(u))}function o(u){return u===null||J(u)?(e.exit("codeFlowValue"),s(u)):(e.consume(u),o)}function l(u){return e.exit("codeIndented"),t(u)}}function jm(e,t,r){const n=this;return a;function a(s){return n.parser.lazy[n.now().line]?r(s):J(s)?(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),a):ie(e,i,"linePrefix",5)(s)}function i(s){const o=n.events[n.events.length-1];return o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?t(s):J(s)?a(s):r(s)}}const $m={name:"codeText",previous:Hm,resolve:Um,tokenize:qm};function Um(e){let t=e.length-4,r=3,n,a;if((e[r][1].type==="lineEnding"||e[r][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(n=r;++n<t;)if(e[n][1].type==="codeTextData"){e[r][1].type="codeTextPadding",e[t][1].type="codeTextPadding",r+=2,t-=2;break}}for(n=r-1,t++;++n<=t;)a===void 0?n!==t&&e[n][1].type!=="lineEnding"&&(a=n):(n===t||e[n][1].type==="lineEnding")&&(e[a][1].type="codeTextData",n!==a+2&&(e[a][1].end=e[n-1][1].end,e.splice(a+2,n-a-2),t-=n-a-2,n=a+2),a=void 0);return e}function Hm(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function qm(e,t,r){let n=0,a,i;return s;function s(c){return e.enter("codeText"),e.enter("codeTextSequence"),o(c)}function o(c){return c===96?(e.consume(c),n++,o):(e.exit("codeTextSequence"),l(c))}function l(c){return c===null?r(c):c===32?(e.enter("space"),e.consume(c),e.exit("space"),l):c===96?(i=e.enter("codeTextSequence"),a=0,d(c)):J(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),l):(e.enter("codeTextData"),u(c))}function u(c){return c===null||c===32||c===96||J(c)?(e.exit("codeTextData"),l(c)):(e.consume(c),u)}function d(c){return c===96?(e.consume(c),a++,d):a===n?(e.exit("codeTextSequence"),e.exit("codeText"),t(c)):(i.type="codeTextData",u(c))}}class Vm{constructor(t){this.left=t?[...t]:[],this.right=[]}get(t){if(t<0||t>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return t<this.left.length?this.left[t]:this.right[this.right.length-t+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(t,r){const n=r==null?Number.POSITIVE_INFINITY:r;return n<this.left.length?this.left.slice(t,n):t>this.left.length?this.right.slice(this.right.length-n+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-n+this.left.length).reverse())}splice(t,r,n){const a=r||0;this.setCursor(Math.trunc(t));const i=this.right.splice(this.right.length-a,Number.POSITIVE_INFINITY);return n&&kr(this.left,n),i.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),kr(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),kr(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t<this.left.length){const r=this.left.splice(t,Number.POSITIVE_INFINITY);kr(this.right,r.reverse())}else{const r=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);kr(this.left,r.reverse())}}}function kr(e,t){let r=0;if(t.length<1e4)e.push(...t);else for(;r<t.length;)e.push(...t.slice(r,r+1e4)),r+=1e4}function tl(e){const t={};let r=-1,n,a,i,s,o,l,u;const d=new Vm(e);for(;++r<d.length;){for(;r in t;)r=t[r];if(n=d.get(r),r&&n[1].type==="chunkFlow"&&d.get(r-1)[1].type==="listItemPrefix"&&(l=n[1]._tokenizer.events,i=0,i<l.length&&l[i][1].type==="lineEndingBlank"&&(i+=2),i<l.length&&l[i][1].type==="content"))for(;++i<l.length&&l[i][1].type!=="content";)l[i][1].type==="chunkText"&&(l[i][1]._isInFirstContentOfListItem=!0,i++);if(n[0]==="enter")n[1].contentType&&(Object.assign(t,Wm(d,r)),r=t[r],u=!0);else if(n[1]._container){for(i=r,a=void 0;i--;)if(s=d.get(i),s[1].type==="lineEnding"||s[1].type==="lineEndingBlank")s[0]==="enter"&&(a&&(d.get(a)[1].type="lineEndingBlank"),s[1].type="lineEnding",a=i);else if(!(s[1].type==="linePrefix"||s[1].type==="listItemIndent"))break;a&&(n[1].end=m({},d.get(a)[1].start),o=d.slice(a,r),o.unshift(n),d.splice(a,r-a+1,o))}}return We(e,0,Number.POSITIVE_INFINITY,d.slice(0)),!u}function Wm(e,t){const r=e.get(t)[1],n=e.get(t)[2];let a=t-1;const i=[];let s=r._tokenizer;s||(s=n.parser[r.contentType](r.start),r._contentTypeTextTrailing&&(s._contentTypeTextTrailing=!0));const o=s.events,l=[],u={};let d,c,h=-1,f=r,g=0,v=0;const b=[v];for(;f;){for(;e.get(++a)[1]!==f;);i.push(a),f._tokenizer||(d=n.sliceStream(f),f.next||d.push(null),c&&s.defineSkip(f.start),f._isInFirstContentOfListItem&&(s._gfmTasklistFirstContentOfListItem=!0),s.write(d),f._isInFirstContentOfListItem&&(s._gfmTasklistFirstContentOfListItem=void 0)),c=f,f=f.next}for(f=r;++h<o.length;)o[h][0]==="exit"&&o[h-1][0]==="enter"&&o[h][1].type===o[h-1][1].type&&o[h][1].start.line!==o[h][1].end.line&&(v=h+1,b.push(v),f._tokenizer=void 0,f.previous=void 0,f=f.next);for(s.events=[],f?(f._tokenizer=void 0,f.previous=void 0):b.pop(),h=b.length;h--;){const w=o.slice(b[h],b[h+1]),_=i.pop();l.push([_,_+w.length-1]),e.splice(_,2,w)}for(l.reverse(),h=-1;++h<l.length;)u[g+l[h][0]]=g+l[h][1],g+=l[h][1]-l[h][0]-1;return u}const Jm={resolve:Km,tokenize:Gm},Ym={partial:!0,tokenize:Xm};function Km(e){return tl(e),e}function Gm(e,t){let r;return n;function n(o){return e.enter("content"),r=e.enter("chunkContent",{contentType:"content"}),a(o)}function a(o){return o===null?i(o):J(o)?e.check(Ym,s,i)(o):(e.consume(o),a)}function i(o){return e.exit("chunkContent"),e.exit("content"),t(o)}function s(o){return e.consume(o),e.exit("chunkContent"),r.next=e.enter("chunkContent",{contentType:"content",previous:r}),r=r.next,a}}function Xm(e,t,r){const n=this;return a;function a(s){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),ie(e,i,"linePrefix")}function i(s){if(s===null||J(s))return r(s);const o=n.events[n.events.length-1];return!n.parser.constructs.disable.null.includes("codeIndented")&&o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?t(s):e.interrupt(n.parser.constructs.flow,r,t)(s)}}function rl(e,t,r,n,a,i,s,o,l){const u=l||Number.POSITIVE_INFINITY;let d=0;return c;function c(w){return w===60?(e.enter(n),e.enter(a),e.enter(i),e.consume(w),e.exit(i),h):w===null||w===32||w===41||nn(w)?r(w):(e.enter(n),e.enter(s),e.enter(o),e.enter("chunkString",{contentType:"string"}),v(w))}function h(w){return w===62?(e.enter(i),e.consume(w),e.exit(i),e.exit(a),e.exit(n),t):(e.enter(o),e.enter("chunkString",{contentType:"string"}),f(w))}function f(w){return w===62?(e.exit("chunkString"),e.exit(o),h(w)):w===null||w===60||J(w)?r(w):(e.consume(w),w===92?g:f)}function g(w){return w===60||w===62||w===92?(e.consume(w),f):f(w)}function v(w){return!d&&(w===null||w===41||ce(w))?(e.exit("chunkString"),e.exit(o),e.exit(s),e.exit(n),t(w)):d<u&&w===40?(e.consume(w),d++,v):w===41?(e.consume(w),d--,v):w===null||w===32||w===40||nn(w)?r(w):(e.consume(w),w===92?b:v)}function b(w){return w===40||w===41||w===92?(e.consume(w),v):v(w)}}function nl(e,t,r,n,a,i){const s=this;let o=0,l;return u;function u(f){return e.enter(n),e.enter(a),e.consume(f),e.exit(a),e.enter(i),d}function d(f){return o>999||f===null||f===91||f===93&&!l||f===94&&!o&&"_hiddenFootnoteSupport"in s.parser.constructs?r(f):f===93?(e.exit(i),e.enter(a),e.consume(f),e.exit(a),e.exit(n),t):J(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),d):(e.enter("chunkString",{contentType:"string"}),c(f))}function c(f){return f===null||f===91||f===93||J(f)||o++>999?(e.exit("chunkString"),d(f)):(e.consume(f),l||(l=!re(f)),f===92?h:c)}function h(f){return f===91||f===92||f===93?(e.consume(f),o++,c):c(f)}}function al(e,t,r,n,a,i){let s;return o;function o(h){return h===34||h===39||h===40?(e.enter(n),e.enter(a),e.consume(h),e.exit(a),s=h===40?41:h,l):r(h)}function l(h){return h===s?(e.enter(a),e.consume(h),e.exit(a),e.exit(n),t):(e.enter(i),u(h))}function u(h){return h===s?(e.exit(i),l(s)):h===null?r(h):J(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),ie(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),d(h))}function d(h){return h===s||h===null||J(h)?(e.exit("chunkString"),u(h)):(e.consume(h),h===92?c:d)}function c(h){return h===s||h===92?(e.consume(h),d):d(h)}}function Sr(e,t){let r;return n;function n(a){return J(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),r=!0,n):re(a)?ie(e,n,r?"linePrefix":"lineSuffix")(a):t(a)}}const Qm={name:"definition",tokenize:eg},Zm={partial:!0,tokenize:tg};function eg(e,t,r){const n=this;let a;return i;function i(f){return e.enter("definition"),s(f)}function s(f){return nl.call(n,e,o,r,"definitionLabel","definitionLabelMarker","definitionLabelString")(f)}function o(f){return a=it(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)),f===58?(e.enter("definitionMarker"),e.consume(f),e.exit("definitionMarker"),l):r(f)}function l(f){return ce(f)?Sr(e,u)(f):u(f)}function u(f){return rl(e,d,r,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(f)}function d(f){return e.attempt(Zm,c,c)(f)}function c(f){return re(f)?ie(e,h,"whitespace")(f):h(f)}function h(f){return f===null||J(f)?(e.exit("definition"),n.parser.defined.push(a),t(f)):r(f)}}function tg(e,t,r){return n;function n(o){return ce(o)?Sr(e,a)(o):r(o)}function a(o){return al(e,i,r,"definitionTitle","definitionTitleMarker","definitionTitleString")(o)}function i(o){return re(o)?ie(e,s,"whitespace")(o):s(o)}function s(o){return o===null||J(o)?t(o):r(o)}}const rg={name:"hardBreakEscape",tokenize:ng};function ng(e,t,r){return n;function n(i){return e.enter("hardBreakEscape"),e.consume(i),a}function a(i){return J(i)?(e.exit("hardBreakEscape"),t(i)):r(i)}}const ag={name:"headingAtx",resolve:ig,tokenize:sg};function ig(e,t){let r=e.length-2,n=3,a,i;return e[n][1].type==="whitespace"&&(n+=2),r-2>n&&e[r][1].type==="whitespace"&&(r-=2),e[r][1].type==="atxHeadingSequence"&&(n===r-1||r-4>n&&e[r-2][1].type==="whitespace")&&(r-=n+1===r?2:4),r>n&&(a={type:"atxHeadingText",start:e[n][1].start,end:e[r][1].end},i={type:"chunkText",start:e[n][1].start,end:e[r][1].end,contentType:"text"},We(e,n,r-n+1,[["enter",a,t],["enter",i,t],["exit",i,t],["exit",a,t]])),e}function sg(e,t,r){let n=0;return a;function a(d){return e.enter("atxHeading"),i(d)}function i(d){return e.enter("atxHeadingSequence"),s(d)}function s(d){return d===35&&n++<6?(e.consume(d),s):d===null||ce(d)?(e.exit("atxHeadingSequence"),o(d)):r(d)}function o(d){return d===35?(e.enter("atxHeadingSequence"),l(d)):d===null||J(d)?(e.exit("atxHeading"),t(d)):re(d)?ie(e,o,"whitespace")(d):(e.enter("atxHeadingText"),u(d))}function l(d){return d===35?(e.consume(d),l):(e.exit("atxHeadingSequence"),o(d))}function u(d){return d===null||d===35||ce(d)?(e.exit("atxHeadingText"),o(d)):(e.consume(d),u)}}const og=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],il=["pre","script","style","textarea"],lg={concrete:!0,name:"htmlFlow",resolveTo:dg,tokenize:hg},ug={partial:!0,tokenize:pg},cg={partial:!0,tokenize:fg};function dg(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function hg(e,t,r){const n=this;let a,i,s,o,l;return u;function u(k){return d(k)}function d(k){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(k),c}function c(k){return k===33?(e.consume(k),h):k===47?(e.consume(k),i=!0,v):k===63?(e.consume(k),a=3,n.interrupt?t:x):Be(k)?(e.consume(k),s=String.fromCharCode(k),b):r(k)}function h(k){return k===45?(e.consume(k),a=2,f):k===91?(e.consume(k),a=5,o=0,g):Be(k)?(e.consume(k),a=4,n.interrupt?t:x):r(k)}function f(k){return k===45?(e.consume(k),n.interrupt?t:x):r(k)}function g(k){const xe="CDATA[";return k===xe.charCodeAt(o++)?(e.consume(k),o===xe.length?n.interrupt?t:M:g):r(k)}function v(k){return Be(k)?(e.consume(k),s=String.fromCharCode(k),b):r(k)}function b(k){if(k===null||k===47||k===62||ce(k)){const xe=k===47,Ue=s.toLowerCase();return!xe&&!i&&il.includes(Ue)?(a=1,n.interrupt?t(k):M(k)):og.includes(s.toLowerCase())?(a=6,xe?(e.consume(k),w):n.interrupt?t(k):M(k)):(a=7,n.interrupt&&!n.parser.lazy[n.now().line]?r(k):i?_(k):T(k))}return k===45||Pe(k)?(e.consume(k),s+=String.fromCharCode(k),b):r(k)}function w(k){return k===62?(e.consume(k),n.interrupt?t:M):r(k)}function _(k){return re(k)?(e.consume(k),_):S(k)}function T(k){return k===47?(e.consume(k),S):k===58||k===95||Be(k)?(e.consume(k),B):re(k)?(e.consume(k),T):S(k)}function B(k){return k===45||k===46||k===58||k===95||Pe(k)?(e.consume(k),B):j(k)}function j(k){return k===61?(e.consume(k),I):re(k)?(e.consume(k),j):T(k)}function I(k){return k===null||k===60||k===61||k===62||k===96?r(k):k===34||k===39?(e.consume(k),l=k,z):re(k)?(e.consume(k),I):H(k)}function z(k){return k===l?(e.consume(k),l=null,O):k===null||J(k)?r(k):(e.consume(k),z)}function H(k){return k===null||k===34||k===39||k===47||k===60||k===61||k===62||k===96||ce(k)?j(k):(e.consume(k),H)}function O(k){return k===47||k===62||re(k)?T(k):r(k)}function S(k){return k===62?(e.consume(k),N):r(k)}function N(k){return k===null||J(k)?M(k):re(k)?(e.consume(k),N):r(k)}function M(k){return k===45&&a===2?(e.consume(k),Q):k===60&&a===1?(e.consume(k),se):k===62&&a===4?(e.consume(k),le):k===63&&a===3?(e.consume(k),x):k===93&&a===5?(e.consume(k),he):J(k)&&(a===6||a===7)?(e.exit("htmlFlowData"),e.check(ug,we,W)(k)):k===null||J(k)?(e.exit("htmlFlowData"),W(k)):(e.consume(k),M)}function W(k){return e.check(cg,R,we)(k)}function R(k){return e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),F}function F(k){return k===null||J(k)?W(k):(e.enter("htmlFlowData"),M(k))}function Q(k){return k===45?(e.consume(k),x):M(k)}function se(k){return k===47?(e.consume(k),s="",Ce):M(k)}function Ce(k){if(k===62){const xe=s.toLowerCase();return il.includes(xe)?(e.consume(k),le):M(k)}return Be(k)&&s.length<8?(e.consume(k),s+=String.fromCharCode(k),Ce):M(k)}function he(k){return k===93?(e.consume(k),x):M(k)}function x(k){return k===62?(e.consume(k),le):k===45&&a===2?(e.consume(k),x):M(k)}function le(k){return k===null||J(k)?(e.exit("htmlFlowData"),we(k)):(e.consume(k),le)}function we(k){return e.exit("htmlFlow"),t(k)}}function fg(e,t,r){const n=this;return a;function a(s){return J(s)?(e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),i):r(s)}function i(s){return n.parser.lazy[n.now().line]?r(s):t(s)}}function pg(e,t,r){return n;function n(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),e.attempt(vr,t,r)}}const mg={name:"htmlText",tokenize:gg};function gg(e,t,r){const n=this;let a,i,s;return o;function o(x){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(x),l}function l(x){return x===33?(e.consume(x),u):x===47?(e.consume(x),j):x===63?(e.consume(x),T):Be(x)?(e.consume(x),H):r(x)}function u(x){return x===45?(e.consume(x),d):x===91?(e.consume(x),i=0,g):Be(x)?(e.consume(x),_):r(x)}function d(x){return x===45?(e.consume(x),f):r(x)}function c(x){return x===null?r(x):x===45?(e.consume(x),h):J(x)?(s=c,se(x)):(e.consume(x),c)}function h(x){return x===45?(e.consume(x),f):c(x)}function f(x){return x===62?Q(x):x===45?h(x):c(x)}function g(x){const le="CDATA[";return x===le.charCodeAt(i++)?(e.consume(x),i===le.length?v:g):r(x)}function v(x){return x===null?r(x):x===93?(e.consume(x),b):J(x)?(s=v,se(x)):(e.consume(x),v)}function b(x){return x===93?(e.consume(x),w):v(x)}function w(x){return x===62?Q(x):x===93?(e.consume(x),w):v(x)}function _(x){return x===null||x===62?Q(x):J(x)?(s=_,se(x)):(e.consume(x),_)}function T(x){return x===null?r(x):x===63?(e.consume(x),B):J(x)?(s=T,se(x)):(e.consume(x),T)}function B(x){return x===62?Q(x):T(x)}function j(x){return Be(x)?(e.consume(x),I):r(x)}function I(x){return x===45||Pe(x)?(e.consume(x),I):z(x)}function z(x){return J(x)?(s=z,se(x)):re(x)?(e.consume(x),z):Q(x)}function H(x){return x===45||Pe(x)?(e.consume(x),H):x===47||x===62||ce(x)?O(x):r(x)}function O(x){return x===47?(e.consume(x),Q):x===58||x===95||Be(x)?(e.consume(x),S):J(x)?(s=O,se(x)):re(x)?(e.consume(x),O):Q(x)}function S(x){return x===45||x===46||x===58||x===95||Pe(x)?(e.consume(x),S):N(x)}function N(x){return x===61?(e.consume(x),M):J(x)?(s=N,se(x)):re(x)?(e.consume(x),N):O(x)}function M(x){return x===null||x===60||x===61||x===62||x===96?r(x):x===34||x===39?(e.consume(x),a=x,W):J(x)?(s=M,se(x)):re(x)?(e.consume(x),M):(e.consume(x),R)}function W(x){return x===a?(e.consume(x),a=void 0,F):x===null?r(x):J(x)?(s=W,se(x)):(e.consume(x),W)}function R(x){return x===null||x===34||x===39||x===60||x===61||x===96?r(x):x===47||x===62||ce(x)?O(x):(e.consume(x),R)}function F(x){return x===47||x===62||ce(x)?O(x):r(x)}function Q(x){return x===62?(e.consume(x),e.exit("htmlTextData"),e.exit("htmlText"),t):r(x)}function se(x){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(x),e.exit("lineEnding"),Ce}function Ce(x){return re(x)?ie(e,he,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(x):he(x)}function he(x){return e.enter("htmlTextData"),s(x)}}const _a={name:"labelEnd",resolveAll:xg,resolveTo:vg,tokenize:kg},yg={tokenize:Sg},bg={tokenize:_g},wg={tokenize:Tg};function xg(e){let t=-1;const r=[];for(;++t<e.length;){const n=e[t][1];if(r.push(e[t]),n.type==="labelImage"||n.type==="labelLink"||n.type==="labelEnd"){const a=n.type==="labelImage"?4:2;n.type="data",t+=a}}return e.length!==r.length&&We(e,0,e.length,r),e}function vg(e,t){let r=e.length,n=0,a,i,s,o;for(;r--;)if(a=e[r][1],i){if(a.type==="link"||a.type==="labelLink"&&a._inactive)break;e[r][0]==="enter"&&a.type==="labelLink"&&(a._inactive=!0)}else if(s){if(e[r][0]==="enter"&&(a.type==="labelImage"||a.type==="labelLink")&&!a._balanced&&(i=r,a.type!=="labelLink")){n=2;break}}else a.type==="labelEnd"&&(s=r);const l={type:e[i][1].type==="labelLink"?"link":"image",start:m({},e[i][1].start),end:m({},e[e.length-1][1].end)},u={type:"label",start:m({},e[i][1].start),end:m({},e[s][1].end)},d={type:"labelText",start:m({},e[i+n+2][1].end),end:m({},e[s-2][1].start)};return o=[["enter",l,t],["enter",u,t]],o=Qe(o,e.slice(i+1,i+n+3)),o=Qe(o,[["enter",d,t]]),o=Qe(o,sn(t.parser.constructs.insideSpan.null,e.slice(i+n+4,s-3),t)),o=Qe(o,[["exit",d,t],e[s-2],e[s-1],["exit",u,t]]),o=Qe(o,e.slice(s+1)),o=Qe(o,[["exit",l,t]]),We(e,i,e.length,o),e}function kg(e,t,r){const n=this;let a=n.events.length,i,s;for(;a--;)if((n.events[a][1].type==="labelImage"||n.events[a][1].type==="labelLink")&&!n.events[a][1]._balanced){i=n.events[a][1];break}return o;function o(h){return i?i._inactive?c(h):(s=n.parser.defined.includes(it(n.sliceSerialize({start:i.end,end:n.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(h),e.exit("labelMarker"),e.exit("labelEnd"),l):r(h)}function l(h){return h===40?e.attempt(yg,d,s?d:c)(h):h===91?e.attempt(bg,d,s?u:c)(h):s?d(h):c(h)}function u(h){return e.attempt(wg,d,c)(h)}function d(h){return t(h)}function c(h){return i._balanced=!0,r(h)}}function Sg(e,t,r){return n;function n(c){return e.enter("resource"),e.enter("resourceMarker"),e.consume(c),e.exit("resourceMarker"),a}function a(c){return ce(c)?Sr(e,i)(c):i(c)}function i(c){return c===41?d(c):rl(e,s,o,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(c)}function s(c){return ce(c)?Sr(e,l)(c):d(c)}function o(c){return r(c)}function l(c){return c===34||c===39||c===40?al(e,u,r,"resourceTitle","resourceTitleMarker","resourceTitleString")(c):d(c)}function u(c){return ce(c)?Sr(e,d)(c):d(c)}function d(c){return c===41?(e.enter("resourceMarker"),e.consume(c),e.exit("resourceMarker"),e.exit("resource"),t):r(c)}}function _g(e,t,r){const n=this;return a;function a(o){return nl.call(n,e,i,s,"reference","referenceMarker","referenceString")(o)}function i(o){return n.parser.defined.includes(it(n.sliceSerialize(n.events[n.events.length-1][1]).slice(1,-1)))?t(o):r(o)}function s(o){return r(o)}}function Tg(e,t,r){return n;function n(i){return e.enter("reference"),e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),a}function a(i){return i===93?(e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),e.exit("reference"),t):r(i)}}const Cg={name:"labelStartImage",resolveAll:_a.resolveAll,tokenize:Ig};function Ig(e,t,r){const n=this;return a;function a(o){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(o),e.exit("labelImageMarker"),i}function i(o){return o===91?(e.enter("labelMarker"),e.consume(o),e.exit("labelMarker"),e.exit("labelImage"),s):r(o)}function s(o){return o===94&&"_hiddenFootnoteSupport"in n.parser.constructs?r(o):t(o)}}const Eg={name:"labelStartLink",resolveAll:_a.resolveAll,tokenize:Ag};function Ag(e,t,r){const n=this;return a;function a(s){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(s),e.exit("labelMarker"),e.exit("labelLink"),i}function i(s){return s===94&&"_hiddenFootnoteSupport"in n.parser.constructs?r(s):t(s)}}const Ta={name:"lineEnding",tokenize:Mg};function Mg(e,t){return r;function r(n){return e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),ie(e,t,"linePrefix")}}const on={name:"thematicBreak",tokenize:Pg};function Pg(e,t,r){let n=0,a;return i;function i(u){return e.enter("thematicBreak"),s(u)}function s(u){return a=u,o(u)}function o(u){return u===a?(e.enter("thematicBreakSequence"),l(u)):n>=3&&(u===null||J(u))?(e.exit("thematicBreak"),t(u)):r(u)}function l(u){return u===a?(e.consume(u),n++,l):(e.exit("thematicBreakSequence"),re(u)?ie(e,o,"whitespace")(u):o(u))}}const $e={continuation:{tokenize:Og},exit:Bg,name:"list",tokenize:Dg},Ng={partial:!0,tokenize:zg},Lg={partial:!0,tokenize:Fg};function Dg(e,t,r){const n=this,a=n.events[n.events.length-1];let i=a&&a[1].type==="linePrefix"?a[2].sliceSerialize(a[1],!0).length:0,s=0;return o;function o(f){const g=n.containerState.type||(f===42||f===43||f===45?"listUnordered":"listOrdered");if(g==="listUnordered"?!n.containerState.marker||f===n.containerState.marker:va(f)){if(n.containerState.type||(n.containerState.type=g,e.enter(g,{_container:!0})),g==="listUnordered")return e.enter("listItemPrefix"),f===42||f===45?e.check(on,r,u)(f):u(f);if(!n.interrupt||f===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),l(f)}return r(f)}function l(f){return va(f)&&++s<10?(e.consume(f),l):(!n.interrupt||s<2)&&(n.containerState.marker?f===n.containerState.marker:f===41||f===46)?(e.exit("listItemValue"),u(f)):r(f)}function u(f){return e.enter("listItemMarker"),e.consume(f),e.exit("listItemMarker"),n.containerState.marker=n.containerState.marker||f,e.check(vr,n.interrupt?r:d,e.attempt(Ng,h,c))}function d(f){return n.containerState.initialBlankLine=!0,i++,h(f)}function c(f){return re(f)?(e.enter("listItemPrefixWhitespace"),e.consume(f),e.exit("listItemPrefixWhitespace"),h):r(f)}function h(f){return n.containerState.size=i+n.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(f)}}function Og(e,t,r){const n=this;return n.containerState._closeFlow=void 0,e.check(vr,a,i);function a(o){return n.containerState.furtherBlankLines=n.containerState.furtherBlankLines||n.containerState.initialBlankLine,ie(e,t,"listItemIndent",n.containerState.size+1)(o)}function i(o){return n.containerState.furtherBlankLines||!re(o)?(n.containerState.furtherBlankLines=void 0,n.containerState.initialBlankLine=void 0,s(o)):(n.containerState.furtherBlankLines=void 0,n.containerState.initialBlankLine=void 0,e.attempt(Lg,t,s)(o))}function s(o){return n.containerState._closeFlow=!0,n.interrupt=void 0,ie(e,e.attempt($e,t,r),"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function Fg(e,t,r){const n=this;return ie(e,a,"listItemIndent",n.containerState.size+1);function a(i){const s=n.events[n.events.length-1];return s&&s[1].type==="listItemIndent"&&s[2].sliceSerialize(s[1],!0).length===n.containerState.size?t(i):r(i)}}function Bg(e){e.exit(this.containerState.type)}function zg(e,t,r){const n=this;return ie(e,a,"listItemPrefixWhitespace",n.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function a(i){const s=n.events[n.events.length-1];return!re(i)&&s&&s[1].type==="listItemPrefixWhitespace"?t(i):r(i)}}const sl={name:"setextUnderline",resolveTo:Rg,tokenize:jg};function Rg(e,t){let r=e.length,n,a,i;for(;r--;)if(e[r][0]==="enter"){if(e[r][1].type==="content"){n=r;break}e[r][1].type==="paragraph"&&(a=r)}else e[r][1].type==="content"&&e.splice(r,1),!i&&e[r][1].type==="definition"&&(i=r);const s={type:"setextHeading",start:m({},e[n][1].start),end:m({},e[e.length-1][1].end)};return e[a][1].type="setextHeadingText",i?(e.splice(a,0,["enter",s,t]),e.splice(i+1,0,["exit",e[n][1],t]),e[n][1].end=m({},e[i][1].end)):e[n][1]=s,e.push(["exit",s,t]),e}function jg(e,t,r){const n=this;let a;return i;function i(u){let d=n.events.length,c;for(;d--;)if(n.events[d][1].type!=="lineEnding"&&n.events[d][1].type!=="linePrefix"&&n.events[d][1].type!=="content"){c=n.events[d][1].type==="paragraph";break}return!n.parser.lazy[n.now().line]&&(n.interrupt||c)?(e.enter("setextHeadingLine"),a=u,s(u)):r(u)}function s(u){return e.enter("setextHeadingLineSequence"),o(u)}function o(u){return u===a?(e.consume(u),o):(e.exit("setextHeadingLineSequence"),re(u)?ie(e,l,"lineSuffix")(u):l(u))}function l(u){return u===null||J(u)?(e.exit("setextHeadingLine"),t(u)):r(u)}}const $g={tokenize:Ug};function Ug(e){const t=this,r=e.attempt(vr,n,e.attempt(this.parser.constructs.flowInitial,a,ie(e,e.attempt(this.parser.constructs.flow,a,e.attempt(Jm,a)),"linePrefix")));return r;function n(i){if(i===null){e.consume(i);return}return e.enter("lineEndingBlank"),e.consume(i),e.exit("lineEndingBlank"),t.currentConstruct=void 0,r}function a(i){if(i===null){e.consume(i);return}return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),t.currentConstruct=void 0,r}}const Hg={resolveAll:ll()},qg=ol("string"),Vg=ol("text");function ol(e){return{resolveAll:ll(e==="text"?Wg:void 0),tokenize:t};function t(r){const n=this,a=this.parser.constructs[e],i=r.attempt(a,s,o);return s;function s(d){return u(d)?i(d):o(d)}function o(d){if(d===null){r.consume(d);return}return r.enter("data"),r.consume(d),l}function l(d){return u(d)?(r.exit("data"),i(d)):(r.consume(d),l)}function u(d){if(d===null)return!0;const c=a[d];let h=-1;if(c)for(;++h<c.length;){const f=c[h];if(!f.previous||f.previous.call(n,n.previous))return!0}return!1}}}function ll(e){return t;function t(r,n){let a=-1,i;for(;++a<=r.length;)i===void 0?r[a]&&r[a][1].type==="data"&&(i=a,a++):(!r[a]||r[a][1].type!=="data")&&(a!==i+2&&(r[i][1].end=r[a-1][1].end,r.splice(i+2,a-i-2),a=i+2),i=void 0);return e?e(r,n):r}}function Wg(e,t){let r=0;for(;++r<=e.length;)if((r===e.length||e[r][1].type==="lineEnding")&&e[r-1][1].type==="data"){const n=e[r-1][1],a=t.sliceStream(n);let i=a.length,s=-1,o=0,l;for(;i--;){const u=a[i];if(typeof u=="string"){for(s=u.length;u.charCodeAt(s-1)===32;)o++,s--;if(s)break;s=-1}else if(u===-2)l=!0,o++;else if(u!==-1){i++;break}}if(t._contentTypeTextTrailing&&r===e.length&&(o=0),o){const u={type:r===e.length||l||o<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:i?s:n.start._bufferIndex+s,_index:n.start._index+i,line:n.end.line,column:n.end.column-o,offset:n.end.offset-o},end:m({},n.end)};n.end=m({},u.start),n.start.offset===n.end.offset?Object.assign(n,u):(e.splice(r,0,["enter",u,t],["exit",u,t]),r+=2)}r++}return e}const Jg=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:{null:[42,95]},contentInitial:{91:Qm},disable:{null:[]},document:{42:$e,43:$e,45:$e,48:$e,49:$e,50:$e,51:$e,52:$e,53:$e,54:$e,55:$e,56:$e,57:$e,62:Go},flow:{35:ag,42:on,45:[sl,on],60:lg,61:sl,95:on,96:el,126:el},flowInitial:{[-2]:Sa,[-1]:Sa,32:Sa},insideSpan:{null:[ka,Hg]},string:{38:Qo,92:Xo},text:{[-5]:Ta,[-4]:Ta,[-3]:Ta,33:Cg,38:Qo,42:ka,60:[Em,mg],91:Eg,92:[rg,Xo],93:_a,95:ka,96:$m}},Symbol.toStringTag,{value:"Module"}));function Yg(e,t,r){let n={_bufferIndex:-1,_index:0,line:r&&r.line||1,column:r&&r.column||1,offset:r&&r.offset||0};const a={},i=[];let s=[],o=[];const l={attempt:z(j),check:z(I),consume:_,enter:T,exit:B,interrupt:z(I,{interrupt:!0})},u={code:null,containerState:{},defineSkip:v,events:[],now:g,parser:e,previous:null,sliceSerialize:h,sliceStream:f,write:c};let d=t.tokenize.call(u,l);return t.resolveAll&&i.push(t),u;function c(N){return s=Qe(s,N),b(),s[s.length-1]!==null?[]:(H(t,0),u.events=sn(i,u.events,u),u.events)}function h(N,M){return Gg(f(N),M)}function f(N){return Kg(s,N)}function g(){const{_bufferIndex:N,_index:M,line:W,column:R,offset:F}=n;return{_bufferIndex:N,_index:M,line:W,column:R,offset:F}}function v(N){a[N.line]=N.column,S()}function b(){let N;for(;n._index<s.length;){const M=s[n._index];if(typeof M=="string")for(N=n._index,n._bufferIndex<0&&(n._bufferIndex=0);n._index===N&&n._bufferIndex<M.length;)w(M.charCodeAt(n._bufferIndex));else w(M)}}function w(N){d=d(N)}function _(N){J(N)?(n.line++,n.column=1,n.offset+=N===-3?2:1,S()):N!==-1&&(n.column++,n.offset++),n._bufferIndex<0?n._index++:(n._bufferIndex++,n._bufferIndex===s[n._index].length&&(n._bufferIndex=-1,n._index++)),u.previous=N}function T(N,M){const W=M||{};return W.type=N,W.start=g(),u.events.push(["enter",W,u]),o.push(W),W}function B(N){const M=o.pop();return M.end=g(),u.events.push(["exit",M,u]),M}function j(N,M){H(N,M.from)}function I(N,M){M.restore()}function z(N,M){return W;function W(R,F,Q){let se,Ce,he,x;return Array.isArray(R)?we(R):"tokenize"in R?we([R]):le(R);function le(ye){return $;function $(Z){const fe=Z!==null&&ye[Z],be=Z!==null&&ye.null,Ne=[...Array.isArray(fe)?fe:fe?[fe]:[],...Array.isArray(be)?be:be?[be]:[]];return we(Ne)(Z)}}function we(ye){return se=ye,Ce=0,ye.length===0?Q:k(ye[Ce])}function k(ye){return $;function $(Z){return x=O(),he=ye,ye.partial||(u.currentConstruct=ye),ye.name&&u.parser.constructs.disable.null.includes(ye.name)?Ue():ye.tokenize.call(M?Object.assign(Object.create(u),M):u,l,xe,Ue)(Z)}}function xe(ye){return N(he,x),F}function Ue(ye){return x.restore(),++Ce<se.length?k(se[Ce]):Q}}}function H(N,M){N.resolveAll&&!i.includes(N)&&i.push(N),N.resolve&&We(u.events,M,u.events.length-M,N.resolve(u.events.slice(M),u)),N.resolveTo&&(u.events=N.resolveTo(u.events,u))}function O(){const N=g(),M=u.previous,W=u.currentConstruct,R=u.events.length,F=Array.from(o);return{from:R,restore:Q};function Q(){n=N,u.previous=M,u.currentConstruct=W,u.events.length=R,o=F,S()}}function S(){n.line in a&&n.column<2&&(n.column=a[n.line],n.offset+=a[n.line]-1)}}function Kg(e,t){const r=t.start._index,n=t.start._bufferIndex,a=t.end._index,i=t.end._bufferIndex;let s;if(r===a)s=[e[r].slice(n,i)];else{if(s=e.slice(r,a),n>-1){const o=s[0];typeof o=="string"?s[0]=o.slice(n):s.shift()}i>0&&s.push(e[a].slice(0,i))}return s}function Gg(e,t){let r=-1;const n=[];let a;for(;++r<e.length;){const i=e[r];let s;if(typeof i=="string")s=i;else switch(i){case-5:{s="\r";break}case-4:{s=`
9
9
  `;break}case-3:{s=`\r
10
- `;break}case-2:{s=t?" ":" ";break}case-1:{if(!t&&a)continue;s=" ";break}default:s=String.fromCharCode(i)}a=i===-2,n.push(s)}return n.join("")}function Gg(e){const n={constructs:Vo([Wg,...(e||{}).extensions||[]]),content:a(xm),defined:[],document:a(km),flow:a(jg),lazy:{},string:a(Hg),text:a(qg)};return n;function a(i){return s;function s(o){return Jg(n,i,o)}}}function Xg(e){for(;!el(e););return e}const ll=/[\0\t\n\r]/g;function Qg(){let e=1,t="",r=!0,n;return a;function a(i,s,o){const l=[];let u,d,c,h,f;for(i=t+(typeof i=="string"?i.toString():new TextDecoder(s||void 0).decode(i)),c=0,t="",r&&(i.charCodeAt(0)===65279&&c++,r=void 0);c<i.length;){if(ll.lastIndex=c,u=ll.exec(i),h=u&&u.index!==void 0?u.index:i.length,f=i.charCodeAt(h),!u){t=i.slice(c);break}if(f===10&&c===h&&n)l.push(-3),n=void 0;else switch(n&&(l.push(-5),n=void 0),c<h&&(l.push(i.slice(c,h)),e+=h-c),f){case 0:{l.push(65533),e++;break}case 9:{for(d=Math.ceil(e/4)*4,l.push(-2);e++<d;)l.push(-1);break}case 10:{l.push(-4),e=1;break}default:n=!0,e=1}c=h+1}return o&&(n&&l.push(-5),t&&l.push(t),l.push(null)),l}}const Zg=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function ey(e){return e.replace(Zg,ty)}function ty(e,t,r){if(t)return t;if(r.charCodeAt(0)===35){const a=r.charCodeAt(1),i=a===120||a===88;return Wo(r.slice(i?2:1),i?16:10)}return wa(r)||e}const ul={}.hasOwnProperty;function ry(e,t,r){return typeof t!="string"&&(r=t,t=void 0),ny(r)(Xg(Gg(r).document().write(Qg()(e,t,!0))))}function ny(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:i(Qt),autolinkProtocol:j,autolinkEmail:j,atxHeading:i(st),blockQuote:i(ve),characterEscape:j,characterReference:j,codeFenced:i(Me),codeFencedFenceInfo:s,codeFencedFenceMeta:s,codeIndented:i(Me,s),codeText:i(he,s),codeTextData:j,data:j,codeFlowValue:j,definition:i(Pe),definitionDestinationString:s,definitionLabelString:s,definitionTitleString:s,emphasis:i(kt),hardBreakEscape:i(dt),hardBreakTrailing:i(dt),htmlFlow:i(Dt,s),htmlFlowData:j,htmlText:i(Dt,s),htmlTextData:j,image:i(ke),label:s,link:i(Qt),listItem:i(wn),listItemValue:h,listOrdered:i(St,c),listUnordered:i(St),paragraph:i(Ot),reference:k,referenceString:s,resourceDestinationString:s,resourceTitleString:s,setextHeading:i(st),strong:i(xn),thematicBreak:i(vn)},exit:{atxHeading:l(),atxHeadingSequence:z,autolink:l(),autolinkEmail:be,autolinkProtocol:ie,blockQuote:l(),characterEscapeValue:S,characterReferenceMarkerHexadecimal:Ue,characterReferenceMarkerNumeric:Ue,characterReferenceValue:ye,characterReference:W,codeFenced:l(b),codeFencedFence:v,codeFencedFenceInfo:f,codeFencedFenceMeta:g,codeFlowValue:S,codeIndented:l(w),codeText:l(F),codeTextData:S,data:S,definition:l(),definitionDestinationString:D,definitionLabelString:T,definitionTitleString:_,emphasis:l(),hardBreakEscape:l(M),hardBreakTrailing:l(M),htmlFlow:l(U),htmlFlowData:S,htmlText:l(R),htmlTextData:S,image:l(ue),label:de,labelText:pe,lineEnding:N,link:l(Q),listItem:l(),listOrdered:l(),listUnordered:l(),paragraph:l(),referenceString:xe,resourceDestinationString:x,resourceTitleString:se,resource:we,setextHeading:l(H),setextHeadingLineSequence:B,setextHeadingText:I,strong:l(),thematicBreak:l()}};cl(t,(e||{}).mdastExtensions||[]);const r={};return n;function n(A){let O={type:"root",children:[]};const Y={stack:[O],tokenStack:[],config:t,enter:o,exit:u,buffer:s,resume:d,data:r},Z=[];let ae=-1;for(;++ae<A.length;)if(A[ae][1].type==="listOrdered"||A[ae][1].type==="listUnordered")if(A[ae][0]==="enter")Z.push(ae);else{const Je=Z.pop();ae=a(A,Je,ae)}for(ae=-1;++ae<A.length;){const Je=t[A[ae][0]];ul.call(Je,A[ae][1].type)&&Je[A[ae][1].type].call(Object.assign({sliceSerialize:A[ae][2].sliceSerialize},Y),A[ae][1])}if(Y.tokenStack.length>0){const Je=Y.tokenStack[Y.tokenStack.length-1];(Je[1]||dl).call(Y,void 0,Je[0])}for(O.position={start:vt(A.length>0?A[0][1].start:{line:1,column:1,offset:0}),end:vt(A.length>0?A[A.length-2][1].end:{line:1,column:1,offset:0})},ae=-1;++ae<t.transforms.length;)O=t.transforms[ae](O)||O;return O}function a(A,O,Y){let Z=O-1,ae=-1,Je=!1,Ze,Ye,Zt,q;for(;++Z<=Y;){const X=A[Z];switch(X[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{X[0]==="enter"?ae++:ae--,q=void 0;break}case"lineEndingBlank":{X[0]==="enter"&&(Ze&&!q&&!ae&&!Zt&&(Zt=Z),q=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:q=void 0}if(!ae&&X[0]==="enter"&&X[1].type==="listItemPrefix"||ae===-1&&X[0]==="exit"&&(X[1].type==="listUnordered"||X[1].type==="listOrdered")){if(Ze){let ee=Z;for(Ye=void 0;ee--;){const Re=A[ee];if(Re[1].type==="lineEnding"||Re[1].type==="lineEndingBlank"){if(Re[0]==="exit")continue;Ye&&(A[Ye][1].type="lineEndingBlank",Je=!0),Re[1].type="lineEnding",Ye=ee}else if(!(Re[1].type==="linePrefix"||Re[1].type==="blockQuotePrefix"||Re[1].type==="blockQuotePrefixWhitespace"||Re[1].type==="blockQuoteMarker"||Re[1].type==="listItemIndent"))break}Zt&&(!Ye||Zt<Ye)&&(Ze._spread=!0),Ze.end=Object.assign({},Ye?A[Ye][1].start:X[1].end),A.splice(Ye||Z,0,["exit",Ze,X[2]]),Z++,Y++}if(X[1].type==="listItemPrefix"){const ee={type:"listItem",_spread:!1,start:Object.assign({},X[1].start),end:void 0};Ze=ee,A.splice(Z,0,["enter",ee,X[2]]),Z++,Y++,Zt=void 0,q=!0}}}return A[O][1]._spread=Je,Y}function i(A,O){return Y;function Y(Z){o.call(this,A(Z),Z),O&&O.call(this,Z)}}function s(){this.stack.push({type:"fragment",children:[]})}function o(A,O,Y){this.stack[this.stack.length-1].children.push(A),this.stack.push(A),this.tokenStack.push([O,Y||void 0]),A.position={start:vt(O.start),end:void 0}}function l(A){return O;function O(Y){A&&A.call(this,Y),u.call(this,Y)}}function u(A,O){const Y=this.stack.pop(),Z=this.tokenStack.pop();if(Z)Z[0].type!==A.type&&(O?O.call(this,A,Z[0]):(Z[1]||dl).call(this,A,Z[0]));else throw new Error("Cannot close `"+A.type+"` ("+br({start:A.start,end:A.end})+"): it’s not open");Y.position.end=vt(A.end)}function d(){return ba(this.stack.pop())}function c(){this.data.expectingFirstListItemValue=!0}function h(A){if(this.data.expectingFirstListItemValue){const O=this.stack[this.stack.length-2];O.start=Number.parseInt(this.sliceSerialize(A),10),this.data.expectingFirstListItemValue=void 0}}function f(){const A=this.resume(),O=this.stack[this.stack.length-1];O.lang=A}function g(){const A=this.resume(),O=this.stack[this.stack.length-1];O.meta=A}function v(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function b(){const A=this.resume(),O=this.stack[this.stack.length-1];O.value=A.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function w(){const A=this.resume(),O=this.stack[this.stack.length-1];O.value=A.replace(/(\r?\n|\r)$/g,"")}function T(A){const O=this.resume(),Y=this.stack[this.stack.length-1];Y.label=O,Y.identifier=at(this.sliceSerialize(A)).toLowerCase()}function _(){const A=this.resume(),O=this.stack[this.stack.length-1];O.title=A}function D(){const A=this.resume(),O=this.stack[this.stack.length-1];O.url=A}function z(A){const O=this.stack[this.stack.length-1];if(!O.depth){const Y=this.sliceSerialize(A).length;O.depth=Y}}function I(){this.data.setextHeadingSlurpLineEnding=!0}function B(A){const O=this.stack[this.stack.length-1];O.depth=this.sliceSerialize(A).codePointAt(0)===61?1:2}function H(){this.data.setextHeadingSlurpLineEnding=void 0}function j(A){const Y=this.stack[this.stack.length-1].children;let Z=Y[Y.length-1];(!Z||Z.type!=="text")&&(Z=ai(),Z.position={start:vt(A.start),end:void 0},Y.push(Z)),this.stack.push(Z)}function S(A){const O=this.stack.pop();O.value+=this.sliceSerialize(A),O.position.end=vt(A.end)}function N(A){const O=this.stack[this.stack.length-1];if(this.data.atHardBreak){const Y=O.children[O.children.length-1];Y.position.end=vt(A.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(O.type)&&(j.call(this,A),S.call(this,A))}function M(){this.data.atHardBreak=!0}function U(){const A=this.resume(),O=this.stack[this.stack.length-1];O.value=A}function R(){const A=this.resume(),O=this.stack[this.stack.length-1];O.value=A}function F(){const A=this.resume(),O=this.stack[this.stack.length-1];O.value=A}function Q(){const A=this.stack[this.stack.length-1];if(this.data.inReference){const O=this.data.referenceType||"shortcut";A.type+="Reference",A.referenceType=O,delete A.url,delete A.title}else delete A.identifier,delete A.label;this.data.referenceType=void 0}function ue(){const A=this.stack[this.stack.length-1];if(this.data.inReference){const O=this.data.referenceType||"shortcut";A.type+="Reference",A.referenceType=O,delete A.url,delete A.title}else delete A.identifier,delete A.label;this.data.referenceType=void 0}function pe(A){const O=this.sliceSerialize(A),Y=this.stack[this.stack.length-2];Y.label=ey(O),Y.identifier=at(O).toLowerCase()}function de(){const A=this.stack[this.stack.length-1],O=this.resume(),Y=this.stack[this.stack.length-1];if(this.data.inReference=!0,Y.type==="link"){const Z=A.children;Y.children=Z}else Y.alt=O}function x(){const A=this.resume(),O=this.stack[this.stack.length-1];O.url=A}function se(){const A=this.resume(),O=this.stack[this.stack.length-1];O.title=A}function we(){this.data.inReference=void 0}function k(){this.data.referenceType="collapsed"}function xe(A){const O=this.resume(),Y=this.stack[this.stack.length-1];Y.label=O,Y.identifier=at(this.sliceSerialize(A)).toLowerCase(),this.data.referenceType="full"}function Ue(A){this.data.characterReferenceType=A.type}function ye(A){const O=this.sliceSerialize(A),Y=this.data.characterReferenceType;let Z;Y?(Z=Wo(O,Y==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Z=wa(O);const ae=this.stack[this.stack.length-1];ae.value+=Z}function W(A){const O=this.stack.pop();O.position.end=vt(A.end)}function ie(A){S.call(this,A);const O=this.stack[this.stack.length-1];O.url=this.sliceSerialize(A)}function be(A){S.call(this,A);const O=this.stack[this.stack.length-1];O.url="mailto:"+this.sliceSerialize(A)}function ve(){return{type:"blockquote",children:[]}}function Me(){return{type:"code",lang:null,meta:null,value:""}}function he(){return{type:"inlineCode",value:""}}function Pe(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function kt(){return{type:"emphasis",children:[]}}function st(){return{type:"heading",depth:0,children:[]}}function dt(){return{type:"break"}}function Dt(){return{type:"html",value:""}}function ke(){return{type:"image",title:null,url:"",alt:null}}function Qt(){return{type:"link",title:null,url:"",children:[]}}function St(A){return{type:"list",ordered:A.type==="listOrdered",start:null,spread:A._spread,children:[]}}function wn(A){return{type:"listItem",spread:A._spread,checked:null,children:[]}}function Ot(){return{type:"paragraph",children:[]}}function xn(){return{type:"strong",children:[]}}function ai(){return{type:"text",value:""}}function vn(){return{type:"thematicBreak"}}}function vt(e){return{line:e.line,column:e.column,offset:e.offset}}function cl(e,t){let r=-1;for(;++r<t.length;){const n=t[r];Array.isArray(n)?cl(e,n):ay(e,n)}}function ay(e,t){let r;for(r in t)if(ul.call(t,r))switch(r){case"canContainEols":{const n=t[r];n&&e[r].push(...n);break}case"transforms":{const n=t[r];n&&e[r].push(...n);break}case"enter":case"exit":{const n=t[r];n&&Object.assign(e[r],n);break}}}function dl(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+br({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+br({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+br({start:t.start,end:t.end})+") is still open")}function iy(e){const t=this;t.parser=r;function r(n){return ry(n,E(m(m({},t.data("settings")),e),{extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]}))}}function sy(e,t){const r={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,r),e.applyData(t,r)}function oy(e,t){const r={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,r),[e.applyData(t,r),{type:"text",value:`
11
- `}]}function ly(e,t){const r=t.value?t.value+`
12
- `:"",n={},a=t.lang?t.lang.split(/\s+/):[];a.length>0&&(n.className=["language-"+a[0]]);let i={type:"element",tagName:"code",properties:n,children:[{type:"text",value:r}]};return t.meta&&(i.data={meta:t.meta}),e.patch(t,i),i=e.applyData(t,i),i={type:"element",tagName:"pre",properties:{},children:[i]},e.patch(t,i),i}function uy(e,t){const r={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function cy(e,t){const r={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function dy(e,t){const r=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=String(t.identifier).toUpperCase(),a=Yt(n.toLowerCase()),i=e.footnoteOrder.indexOf(n);let s,o=e.footnoteCounts.get(n);o===void 0?(o=0,e.footnoteOrder.push(n),s=e.footnoteOrder.length):s=i+1,o+=1,e.footnoteCounts.set(n,o);const l={type:"element",tagName:"a",properties:{href:"#"+r+"fn-"+a,id:r+"fnref-"+a+(o>1?"-"+o:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(s)}]};e.patch(t,l);const u={type:"element",tagName:"sup",properties:{},children:[l]};return e.patch(t,u),e.applyData(t,u)}function hy(e,t){const r={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function fy(e,t){if(e.options.allowDangerousHtml){const r={type:"raw",value:t.value};return e.patch(t,r),e.applyData(t,r)}}function hl(e,t){const r=t.referenceType;let n="]";if(r==="collapsed"?n+="[]":r==="full"&&(n+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+n}];const a=e.all(t),i=a[0];i&&i.type==="text"?i.value="["+i.value:a.unshift({type:"text",value:"["});const s=a[a.length-1];return s&&s.type==="text"?s.value+=n:a.push({type:"text",value:n}),a}function py(e,t){const r=String(t.identifier).toUpperCase(),n=e.definitionById.get(r);if(!n)return hl(e,t);const a={src:Yt(n.url||""),alt:t.alt};n.title!==null&&n.title!==void 0&&(a.title=n.title);const i={type:"element",tagName:"img",properties:a,children:[]};return e.patch(t,i),e.applyData(t,i)}function my(e,t){const r={src:Yt(t.url)};t.alt!==null&&t.alt!==void 0&&(r.alt=t.alt),t.title!==null&&t.title!==void 0&&(r.title=t.title);const n={type:"element",tagName:"img",properties:r,children:[]};return e.patch(t,n),e.applyData(t,n)}function gy(e,t){const r={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,r);const n={type:"element",tagName:"code",properties:{},children:[r]};return e.patch(t,n),e.applyData(t,n)}function yy(e,t){const r=String(t.identifier).toUpperCase(),n=e.definitionById.get(r);if(!n)return hl(e,t);const a={href:Yt(n.url||"")};n.title!==null&&n.title!==void 0&&(a.title=n.title);const i={type:"element",tagName:"a",properties:a,children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function by(e,t){const r={href:Yt(t.url)};t.title!==null&&t.title!==void 0&&(r.title=t.title);const n={type:"element",tagName:"a",properties:r,children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function wy(e,t,r){const n=e.all(t),a=r?xy(r):fl(t),i={},s=[];if(typeof t.checked=="boolean"){const d=n[0];let c;d&&d.type==="element"&&d.tagName==="p"?c=d:(c={type:"element",tagName:"p",properties:{},children:[]},n.unshift(c)),c.children.length>0&&c.children.unshift({type:"text",value:" "}),c.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),i.className=["task-list-item"]}let o=-1;for(;++o<n.length;){const d=n[o];(a||o!==0||d.type!=="element"||d.tagName!=="p")&&s.push({type:"text",value:`
10
+ `;break}case-2:{s=t?" ":" ";break}case-1:{if(!t&&a)continue;s=" ";break}default:s=String.fromCharCode(i)}a=i===-2,n.push(s)}return n.join("")}function Xg(e){const n={constructs:Wo([Jg,...(e||{}).extensions||[]]),content:a(vm),defined:[],document:a(Sm),flow:a($g),lazy:{},string:a(qg),text:a(Vg)};return n;function a(i){return s;function s(o){return Yg(n,i,o)}}}function Qg(e){for(;!tl(e););return e}const ul=/[\0\t\n\r]/g;function Zg(){let e=1,t="",r=!0,n;return a;function a(i,s,o){const l=[];let u,d,c,h,f;for(i=t+(typeof i=="string"?i.toString():new TextDecoder(s||void 0).decode(i)),c=0,t="",r&&(i.charCodeAt(0)===65279&&c++,r=void 0);c<i.length;){if(ul.lastIndex=c,u=ul.exec(i),h=u&&u.index!==void 0?u.index:i.length,f=i.charCodeAt(h),!u){t=i.slice(c);break}if(f===10&&c===h&&n)l.push(-3),n=void 0;else switch(n&&(l.push(-5),n=void 0),c<h&&(l.push(i.slice(c,h)),e+=h-c),f){case 0:{l.push(65533),e++;break}case 9:{for(d=Math.ceil(e/4)*4,l.push(-2);e++<d;)l.push(-1);break}case 10:{l.push(-4),e=1;break}default:n=!0,e=1}c=h+1}return o&&(n&&l.push(-5),t&&l.push(t),l.push(null)),l}}const ey=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function ty(e){return e.replace(ey,ry)}function ry(e,t,r){if(t)return t;if(r.charCodeAt(0)===35){const a=r.charCodeAt(1),i=a===120||a===88;return Jo(r.slice(i?2:1),i?16:10)}return xa(r)||e}const cl={}.hasOwnProperty;function ny(e,t,r){return typeof t!="string"&&(r=t,t=void 0),ay(r)(Qg(Xg(r).document().write(Zg()(e,t,!0))))}function ay(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:i(Qt),autolinkProtocol:O,autolinkEmail:O,atxHeading:i(Je),blockQuote:i(be),characterEscape:O,characterReference:O,codeFenced:i(Ne),codeFencedFenceInfo:s,codeFencedFenceMeta:s,codeIndented:i(Ne,s),codeText:i(ne,s),codeTextData:O,data:O,codeFlowValue:O,definition:i(ve),definitionDestinationString:s,definitionLabelString:s,definitionTitleString:s,emphasis:i(dt),hardBreakEscape:i(ht),hardBreakTrailing:i(ht),htmlFlow:i(Dt,s),htmlFlowData:O,htmlText:i(Dt,s),htmlTextData:O,image:i(ke),label:s,link:i(Qt),listItem:i(wn),listItemValue:h,listOrdered:i(St,c),listUnordered:i(St),paragraph:i(Ot),reference:k,referenceString:s,resourceDestinationString:s,resourceTitleString:s,setextHeading:i(Je),strong:i(xn),thematicBreak:i(vn)},exit:{atxHeading:l(),atxHeadingSequence:j,autolink:l(),autolinkEmail:fe,autolinkProtocol:Z,blockQuote:l(),characterEscapeValue:S,characterReferenceMarkerHexadecimal:Ue,characterReferenceMarkerNumeric:Ue,characterReferenceValue:ye,characterReference:$,codeFenced:l(b),codeFencedFence:v,codeFencedFenceInfo:f,codeFencedFenceMeta:g,codeFlowValue:S,codeIndented:l(w),codeText:l(F),codeTextData:S,data:S,definition:l(),definitionDestinationString:B,definitionLabelString:_,definitionTitleString:T,emphasis:l(),hardBreakEscape:l(M),hardBreakTrailing:l(M),htmlFlow:l(W),htmlFlowData:S,htmlText:l(R),htmlTextData:S,image:l(se),label:he,labelText:Ce,lineEnding:N,link:l(Q),listItem:l(),listOrdered:l(),listUnordered:l(),paragraph:l(),referenceString:xe,resourceDestinationString:x,resourceTitleString:le,resource:we,setextHeading:l(H),setextHeadingLineSequence:z,setextHeadingText:I,strong:l(),thematicBreak:l()}};dl(t,(e||{}).mdastExtensions||[]);const r={};return n;function n(A){let D={type:"root",children:[]};const Y={stack:[D],tokenStack:[],config:t,enter:o,exit:u,buffer:s,resume:d,data:r},ee=[];let oe=-1;for(;++oe<A.length;)if(A[oe][1].type==="listOrdered"||A[oe][1].type==="listUnordered")if(A[oe][0]==="enter")ee.push(oe);else{const Ye=ee.pop();oe=a(A,Ye,oe)}for(oe=-1;++oe<A.length;){const Ye=t[A[oe][0]];cl.call(Ye,A[oe][1].type)&&Ye[A[oe][1].type].call(Object.assign({sliceSerialize:A[oe][2].sliceSerialize},Y),A[oe][1])}if(Y.tokenStack.length>0){const Ye=Y.tokenStack[Y.tokenStack.length-1];(Ye[1]||hl).call(Y,void 0,Ye[0])}for(D.position={start:kt(A.length>0?A[0][1].start:{line:1,column:1,offset:0}),end:kt(A.length>0?A[A.length-2][1].end:{line:1,column:1,offset:0})},oe=-1;++oe<t.transforms.length;)D=t.transforms[oe](D)||D;return D}function a(A,D,Y){let ee=D-1,oe=-1,Ye=!1,et,Ke,Zt,q;for(;++ee<=Y;){const X=A[ee];switch(X[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{X[0]==="enter"?oe++:oe--,q=void 0;break}case"lineEndingBlank":{X[0]==="enter"&&(et&&!q&&!oe&&!Zt&&(Zt=ee),q=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:q=void 0}if(!oe&&X[0]==="enter"&&X[1].type==="listItemPrefix"||oe===-1&&X[0]==="exit"&&(X[1].type==="listUnordered"||X[1].type==="listOrdered")){if(et){let te=ee;for(Ke=void 0;te--;){const Re=A[te];if(Re[1].type==="lineEnding"||Re[1].type==="lineEndingBlank"){if(Re[0]==="exit")continue;Ke&&(A[Ke][1].type="lineEndingBlank",Ye=!0),Re[1].type="lineEnding",Ke=te}else if(!(Re[1].type==="linePrefix"||Re[1].type==="blockQuotePrefix"||Re[1].type==="blockQuotePrefixWhitespace"||Re[1].type==="blockQuoteMarker"||Re[1].type==="listItemIndent"))break}Zt&&(!Ke||Zt<Ke)&&(et._spread=!0),et.end=Object.assign({},Ke?A[Ke][1].start:X[1].end),A.splice(Ke||ee,0,["exit",et,X[2]]),ee++,Y++}if(X[1].type==="listItemPrefix"){const te={type:"listItem",_spread:!1,start:Object.assign({},X[1].start),end:void 0};et=te,A.splice(ee,0,["enter",te,X[2]]),ee++,Y++,Zt=void 0,q=!0}}}return A[D][1]._spread=Ye,Y}function i(A,D){return Y;function Y(ee){o.call(this,A(ee),ee),D&&D.call(this,ee)}}function s(){this.stack.push({type:"fragment",children:[]})}function o(A,D,Y){this.stack[this.stack.length-1].children.push(A),this.stack.push(A),this.tokenStack.push([D,Y||void 0]),A.position={start:kt(D.start),end:void 0}}function l(A){return D;function D(Y){A&&A.call(this,Y),u.call(this,Y)}}function u(A,D){const Y=this.stack.pop(),ee=this.tokenStack.pop();if(ee)ee[0].type!==A.type&&(D?D.call(this,A,ee[0]):(ee[1]||hl).call(this,A,ee[0]));else throw new Error("Cannot close `"+A.type+"` ("+wr({start:A.start,end:A.end})+"): it’s not open");Y.position.end=kt(A.end)}function d(){return wa(this.stack.pop())}function c(){this.data.expectingFirstListItemValue=!0}function h(A){if(this.data.expectingFirstListItemValue){const D=this.stack[this.stack.length-2];D.start=Number.parseInt(this.sliceSerialize(A),10),this.data.expectingFirstListItemValue=void 0}}function f(){const A=this.resume(),D=this.stack[this.stack.length-1];D.lang=A}function g(){const A=this.resume(),D=this.stack[this.stack.length-1];D.meta=A}function v(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function b(){const A=this.resume(),D=this.stack[this.stack.length-1];D.value=A.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function w(){const A=this.resume(),D=this.stack[this.stack.length-1];D.value=A.replace(/(\r?\n|\r)$/g,"")}function _(A){const D=this.resume(),Y=this.stack[this.stack.length-1];Y.label=D,Y.identifier=it(this.sliceSerialize(A)).toLowerCase()}function T(){const A=this.resume(),D=this.stack[this.stack.length-1];D.title=A}function B(){const A=this.resume(),D=this.stack[this.stack.length-1];D.url=A}function j(A){const D=this.stack[this.stack.length-1];if(!D.depth){const Y=this.sliceSerialize(A).length;D.depth=Y}}function I(){this.data.setextHeadingSlurpLineEnding=!0}function z(A){const D=this.stack[this.stack.length-1];D.depth=this.sliceSerialize(A).codePointAt(0)===61?1:2}function H(){this.data.setextHeadingSlurpLineEnding=void 0}function O(A){const Y=this.stack[this.stack.length-1].children;let ee=Y[Y.length-1];(!ee||ee.type!=="text")&&(ee=ii(),ee.position={start:kt(A.start),end:void 0},Y.push(ee)),this.stack.push(ee)}function S(A){const D=this.stack.pop();D.value+=this.sliceSerialize(A),D.position.end=kt(A.end)}function N(A){const D=this.stack[this.stack.length-1];if(this.data.atHardBreak){const Y=D.children[D.children.length-1];Y.position.end=kt(A.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(D.type)&&(O.call(this,A),S.call(this,A))}function M(){this.data.atHardBreak=!0}function W(){const A=this.resume(),D=this.stack[this.stack.length-1];D.value=A}function R(){const A=this.resume(),D=this.stack[this.stack.length-1];D.value=A}function F(){const A=this.resume(),D=this.stack[this.stack.length-1];D.value=A}function Q(){const A=this.stack[this.stack.length-1];if(this.data.inReference){const D=this.data.referenceType||"shortcut";A.type+="Reference",A.referenceType=D,delete A.url,delete A.title}else delete A.identifier,delete A.label;this.data.referenceType=void 0}function se(){const A=this.stack[this.stack.length-1];if(this.data.inReference){const D=this.data.referenceType||"shortcut";A.type+="Reference",A.referenceType=D,delete A.url,delete A.title}else delete A.identifier,delete A.label;this.data.referenceType=void 0}function Ce(A){const D=this.sliceSerialize(A),Y=this.stack[this.stack.length-2];Y.label=ty(D),Y.identifier=it(D).toLowerCase()}function he(){const A=this.stack[this.stack.length-1],D=this.resume(),Y=this.stack[this.stack.length-1];if(this.data.inReference=!0,Y.type==="link"){const ee=A.children;Y.children=ee}else Y.alt=D}function x(){const A=this.resume(),D=this.stack[this.stack.length-1];D.url=A}function le(){const A=this.resume(),D=this.stack[this.stack.length-1];D.title=A}function we(){this.data.inReference=void 0}function k(){this.data.referenceType="collapsed"}function xe(A){const D=this.resume(),Y=this.stack[this.stack.length-1];Y.label=D,Y.identifier=it(this.sliceSerialize(A)).toLowerCase(),this.data.referenceType="full"}function Ue(A){this.data.characterReferenceType=A.type}function ye(A){const D=this.sliceSerialize(A),Y=this.data.characterReferenceType;let ee;Y?(ee=Jo(D,Y==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):ee=xa(D);const oe=this.stack[this.stack.length-1];oe.value+=ee}function $(A){const D=this.stack.pop();D.position.end=kt(A.end)}function Z(A){S.call(this,A);const D=this.stack[this.stack.length-1];D.url=this.sliceSerialize(A)}function fe(A){S.call(this,A);const D=this.stack[this.stack.length-1];D.url="mailto:"+this.sliceSerialize(A)}function be(){return{type:"blockquote",children:[]}}function Ne(){return{type:"code",lang:null,meta:null,value:""}}function ne(){return{type:"inlineCode",value:""}}function ve(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function dt(){return{type:"emphasis",children:[]}}function Je(){return{type:"heading",depth:0,children:[]}}function ht(){return{type:"break"}}function Dt(){return{type:"html",value:""}}function ke(){return{type:"image",title:null,url:"",alt:null}}function Qt(){return{type:"link",title:null,url:"",children:[]}}function St(A){return{type:"list",ordered:A.type==="listOrdered",start:null,spread:A._spread,children:[]}}function wn(A){return{type:"listItem",spread:A._spread,checked:null,children:[]}}function Ot(){return{type:"paragraph",children:[]}}function xn(){return{type:"strong",children:[]}}function ii(){return{type:"text",value:""}}function vn(){return{type:"thematicBreak"}}}function kt(e){return{line:e.line,column:e.column,offset:e.offset}}function dl(e,t){let r=-1;for(;++r<t.length;){const n=t[r];Array.isArray(n)?dl(e,n):iy(e,n)}}function iy(e,t){let r;for(r in t)if(cl.call(t,r))switch(r){case"canContainEols":{const n=t[r];n&&e[r].push(...n);break}case"transforms":{const n=t[r];n&&e[r].push(...n);break}case"enter":case"exit":{const n=t[r];n&&Object.assign(e[r],n);break}}}function hl(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+wr({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+wr({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+wr({start:t.start,end:t.end})+") is still open")}function sy(e){const t=this;t.parser=r;function r(n){return ny(n,E(m(m({},t.data("settings")),e),{extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]}))}}function oy(e,t){const r={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,r),e.applyData(t,r)}function ly(e,t){const r={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,r),[e.applyData(t,r),{type:"text",value:`
11
+ `}]}function uy(e,t){const r=t.value?t.value+`
12
+ `:"",n={},a=t.lang?t.lang.split(/\s+/):[];a.length>0&&(n.className=["language-"+a[0]]);let i={type:"element",tagName:"code",properties:n,children:[{type:"text",value:r}]};return t.meta&&(i.data={meta:t.meta}),e.patch(t,i),i=e.applyData(t,i),i={type:"element",tagName:"pre",properties:{},children:[i]},e.patch(t,i),i}function cy(e,t){const r={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function dy(e,t){const r={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function hy(e,t){const r=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=String(t.identifier).toUpperCase(),a=Yt(n.toLowerCase()),i=e.footnoteOrder.indexOf(n);let s,o=e.footnoteCounts.get(n);o===void 0?(o=0,e.footnoteOrder.push(n),s=e.footnoteOrder.length):s=i+1,o+=1,e.footnoteCounts.set(n,o);const l={type:"element",tagName:"a",properties:{href:"#"+r+"fn-"+a,id:r+"fnref-"+a+(o>1?"-"+o:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(s)}]};e.patch(t,l);const u={type:"element",tagName:"sup",properties:{},children:[l]};return e.patch(t,u),e.applyData(t,u)}function fy(e,t){const r={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function py(e,t){if(e.options.allowDangerousHtml){const r={type:"raw",value:t.value};return e.patch(t,r),e.applyData(t,r)}}function fl(e,t){const r=t.referenceType;let n="]";if(r==="collapsed"?n+="[]":r==="full"&&(n+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+n}];const a=e.all(t),i=a[0];i&&i.type==="text"?i.value="["+i.value:a.unshift({type:"text",value:"["});const s=a[a.length-1];return s&&s.type==="text"?s.value+=n:a.push({type:"text",value:n}),a}function my(e,t){const r=String(t.identifier).toUpperCase(),n=e.definitionById.get(r);if(!n)return fl(e,t);const a={src:Yt(n.url||""),alt:t.alt};n.title!==null&&n.title!==void 0&&(a.title=n.title);const i={type:"element",tagName:"img",properties:a,children:[]};return e.patch(t,i),e.applyData(t,i)}function gy(e,t){const r={src:Yt(t.url)};t.alt!==null&&t.alt!==void 0&&(r.alt=t.alt),t.title!==null&&t.title!==void 0&&(r.title=t.title);const n={type:"element",tagName:"img",properties:r,children:[]};return e.patch(t,n),e.applyData(t,n)}function yy(e,t){const r={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,r);const n={type:"element",tagName:"code",properties:{},children:[r]};return e.patch(t,n),e.applyData(t,n)}function by(e,t){const r=String(t.identifier).toUpperCase(),n=e.definitionById.get(r);if(!n)return fl(e,t);const a={href:Yt(n.url||"")};n.title!==null&&n.title!==void 0&&(a.title=n.title);const i={type:"element",tagName:"a",properties:a,children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function wy(e,t){const r={href:Yt(t.url)};t.title!==null&&t.title!==void 0&&(r.title=t.title);const n={type:"element",tagName:"a",properties:r,children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function xy(e,t,r){const n=e.all(t),a=r?vy(r):pl(t),i={},s=[];if(typeof t.checked=="boolean"){const d=n[0];let c;d&&d.type==="element"&&d.tagName==="p"?c=d:(c={type:"element",tagName:"p",properties:{},children:[]},n.unshift(c)),c.children.length>0&&c.children.unshift({type:"text",value:" "}),c.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),i.className=["task-list-item"]}let o=-1;for(;++o<n.length;){const d=n[o];(a||o!==0||d.type!=="element"||d.tagName!=="p")&&s.push({type:"text",value:`
13
13
  `}),d.type==="element"&&d.tagName==="p"&&!a?s.push(...d.children):s.push(d)}const l=n[n.length-1];l&&(a||l.type!=="element"||l.tagName!=="p")&&s.push({type:"text",value:`
14
- `});const u={type:"element",tagName:"li",properties:i,children:s};return e.patch(t,u),e.applyData(t,u)}function xy(e){let t=!1;if(e.type==="list"){t=e.spread||!1;const r=e.children;let n=-1;for(;!t&&++n<r.length;)t=fl(r[n])}return t}function fl(e){const t=e.spread;return t==null?e.children.length>1:t}function vy(e,t){const r={},n=e.all(t);let a=-1;for(typeof t.start=="number"&&t.start!==1&&(r.start=t.start);++a<n.length;){const s=n[a];if(s.type==="element"&&s.tagName==="li"&&s.properties&&Array.isArray(s.properties.className)&&s.properties.className.includes("task-list-item")){r.className=["contains-task-list"];break}}const i={type:"element",tagName:t.ordered?"ol":"ul",properties:r,children:e.wrap(n,!0)};return e.patch(t,i),e.applyData(t,i)}function ky(e,t){const r={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function Sy(e,t){const r={type:"root",children:e.wrap(e.all(t))};return e.patch(t,r),e.applyData(t,r)}function _y(e,t){const r={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function Ty(e,t){const r=e.all(t),n=r.shift(),a=[];if(n){const s={type:"element",tagName:"thead",properties:{},children:e.wrap([n],!0)};e.patch(t.children[0],s),a.push(s)}if(r.length>0){const s={type:"element",tagName:"tbody",properties:{},children:e.wrap(r,!0)},o=ha(t.children[1]),l=Lo(t.children[t.children.length-1]);o&&l&&(s.position={start:o,end:l}),a.push(s)}const i={type:"element",tagName:"table",properties:{},children:e.wrap(a,!0)};return e.patch(t,i),e.applyData(t,i)}function Cy(e,t,r){const n=r?r.children:void 0,i=(n?n.indexOf(t):1)===0?"th":"td",s=r&&r.type==="table"?r.align:void 0,o=s?s.length:t.children.length;let l=-1;const u=[];for(;++l<o;){const c=t.children[l],h={},f=s?s[l]:void 0;f&&(h.align=f);let g={type:"element",tagName:i,properties:h,children:[]};c&&(g.children=e.all(c),e.patch(c,g),g=e.applyData(c,g)),u.push(g)}const d={type:"element",tagName:"tr",properties:{},children:e.wrap(u,!0)};return e.patch(t,d),e.applyData(t,d)}function Iy(e,t){const r={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}const pl=9,ml=32;function Ey(e){const t=String(e),r=/\r?\n|\r/g;let n=r.exec(t),a=0;const i=[];for(;n;)i.push(gl(t.slice(a,n.index),a>0,!0),n[0]),a=n.index+n[0].length,n=r.exec(t);return i.push(gl(t.slice(a),a>0,!1)),i.join("")}function gl(e,t,r){let n=0,a=e.length;if(t){let i=e.codePointAt(n);for(;i===pl||i===ml;)n++,i=e.codePointAt(n)}if(r){let i=e.codePointAt(a-1);for(;i===pl||i===ml;)a--,i=e.codePointAt(a-1)}return a>n?e.slice(n,a):""}function Ay(e,t){const r={type:"text",value:Ey(String(t.value))};return e.patch(t,r),e.applyData(t,r)}function My(e,t){const r={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,r),e.applyData(t,r)}const Py={blockquote:sy,break:oy,code:ly,delete:uy,emphasis:cy,footnoteReference:dy,heading:hy,html:fy,imageReference:py,image:my,inlineCode:gy,linkReference:yy,link:by,listItem:wy,list:vy,paragraph:ky,root:Sy,strong:_y,table:Ty,tableCell:Iy,tableRow:Cy,text:Ay,thematicBreak:My,toml:ln,yaml:ln,definition:ln,footnoteDefinition:ln};function ln(){}const yl=-1,un=0,Sr=1,cn=2,Ta=3,Ca=4,Ia=5,Ea=6,bl=7,wl=8,xl=typeof self=="object"?self:globalThis,Ny=(e,t)=>{const r=(a,i)=>(e.set(i,a),a),n=a=>{if(e.has(a))return e.get(a);const[i,s]=t[a];switch(i){case un:case yl:return r(s,a);case Sr:{const o=r([],a);for(const l of s)o.push(n(l));return o}case cn:{const o=r({},a);for(const[l,u]of s)o[n(l)]=n(u);return o}case Ta:return r(new Date(s),a);case Ca:{const{source:o,flags:l}=s;return r(new RegExp(o,l),a)}case Ia:{const o=r(new Map,a);for(const[l,u]of s)o.set(n(l),n(u));return o}case Ea:{const o=r(new Set,a);for(const l of s)o.add(n(l));return o}case bl:{const{name:o,message:l}=s;return r(new xl[o](l),a)}case wl:return r(BigInt(s),a);case"BigInt":return r(Object(BigInt(s)),a);case"ArrayBuffer":return r(new Uint8Array(s).buffer,s);case"DataView":{const{buffer:o}=new Uint8Array(s);return r(new DataView(o),s)}}return r(new xl[i](s),a)};return n},vl=e=>Ny(new Map,e)(0),Gt="",{toString:Ly}={},{keys:Dy}=Object,_r=e=>{const t=typeof e;if(t!=="object"||!e)return[un,t];const r=Ly.call(e).slice(8,-1);switch(r){case"Array":return[Sr,Gt];case"Object":return[cn,Gt];case"Date":return[Ta,Gt];case"RegExp":return[Ca,Gt];case"Map":return[Ia,Gt];case"Set":return[Ea,Gt];case"DataView":return[Sr,r]}return r.includes("Array")?[Sr,r]:r.includes("Error")?[bl,r]:[cn,r]},dn=([e,t])=>e===un&&(t==="function"||t==="symbol"),Oy=(e,t,r,n)=>{const a=(s,o)=>{const l=n.push(s)-1;return r.set(o,l),l},i=s=>{if(r.has(s))return r.get(s);let[o,l]=_r(s);switch(o){case un:{let d=s;switch(l){case"bigint":o=wl,d=s.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+l);d=null;break;case"undefined":return a([yl],s)}return a([o,d],s)}case Sr:{if(l){let h=s;return l==="DataView"?h=new Uint8Array(s.buffer):l==="ArrayBuffer"&&(h=new Uint8Array(s)),a([l,[...h]],s)}const d=[],c=a([o,d],s);for(const h of s)d.push(i(h));return c}case cn:{if(l)switch(l){case"BigInt":return a([l,s.toString()],s);case"Boolean":case"Number":case"String":return a([l,s.valueOf()],s)}if(t&&"toJSON"in s)return i(s.toJSON());const d=[],c=a([o,d],s);for(const h of Dy(s))(e||!dn(_r(s[h])))&&d.push([i(h),i(s[h])]);return c}case Ta:return a([o,s.toISOString()],s);case Ca:{const{source:d,flags:c}=s;return a([o,{source:d,flags:c}],s)}case Ia:{const d=[],c=a([o,d],s);for(const[h,f]of s)(e||!(dn(_r(h))||dn(_r(f))))&&d.push([i(h),i(f)]);return c}case Ea:{const d=[],c=a([o,d],s);for(const h of s)(e||!dn(_r(h)))&&d.push(i(h));return c}}const{message:u}=s;return a([o,{name:l,message:u}],s)};return i},kl=(e,{json:t,lossy:r}={})=>{const n=[];return Oy(!(t||r),!!t,new Map,n)(e),n},hn=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?vl(kl(e,t)):structuredClone(e):(e,t)=>vl(kl(e,t));function Fy(e,t){const r=[{type:"text",value:"↩"}];return t>1&&r.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),r}function By(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function zy(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",r=e.options.footnoteBackContent||Fy,n=e.options.footnoteBackLabel||By,a=e.options.footnoteLabel||"Footnotes",i=e.options.footnoteLabelTagName||"h2",s=e.options.footnoteLabelProperties||{className:["sr-only"]},o=[];let l=-1;for(;++l<e.footnoteOrder.length;){const u=e.footnoteById.get(e.footnoteOrder[l]);if(!u)continue;const d=e.all(u),c=String(u.identifier).toUpperCase(),h=Yt(c.toLowerCase());let f=0;const g=[],v=e.footnoteCounts.get(c);for(;v!==void 0&&++f<=v;){g.length>0&&g.push({type:"text",value:" "});let T=typeof r=="string"?r:r(l,f);typeof T=="string"&&(T={type:"text",value:T}),g.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+h+(f>1?"-"+f:""),dataFootnoteBackref:"",ariaLabel:typeof n=="string"?n:n(l,f),className:["data-footnote-backref"]},children:Array.isArray(T)?T:[T]})}const b=d[d.length-1];if(b&&b.type==="element"&&b.tagName==="p"){const T=b.children[b.children.length-1];T&&T.type==="text"?T.value+=" ":b.children.push({type:"text",value:" "}),b.children.push(...g)}else d.push(...g);const w={type:"element",tagName:"li",properties:{id:t+"fn-"+h},children:e.wrap(d,!0)};e.patch(u,w),o.push(w)}if(o.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:i,properties:E(m({},hn(s)),{id:"footnote-label"}),children:[{type:"text",value:a}]},{type:"text",value:`
14
+ `});const u={type:"element",tagName:"li",properties:i,children:s};return e.patch(t,u),e.applyData(t,u)}function vy(e){let t=!1;if(e.type==="list"){t=e.spread||!1;const r=e.children;let n=-1;for(;!t&&++n<r.length;)t=pl(r[n])}return t}function pl(e){const t=e.spread;return t==null?e.children.length>1:t}function ky(e,t){const r={},n=e.all(t);let a=-1;for(typeof t.start=="number"&&t.start!==1&&(r.start=t.start);++a<n.length;){const s=n[a];if(s.type==="element"&&s.tagName==="li"&&s.properties&&Array.isArray(s.properties.className)&&s.properties.className.includes("task-list-item")){r.className=["contains-task-list"];break}}const i={type:"element",tagName:t.ordered?"ol":"ul",properties:r,children:e.wrap(n,!0)};return e.patch(t,i),e.applyData(t,i)}function Sy(e,t){const r={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function _y(e,t){const r={type:"root",children:e.wrap(e.all(t))};return e.patch(t,r),e.applyData(t,r)}function Ty(e,t){const r={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function Cy(e,t){const r=e.all(t),n=r.shift(),a=[];if(n){const s={type:"element",tagName:"thead",properties:{},children:e.wrap([n],!0)};e.patch(t.children[0],s),a.push(s)}if(r.length>0){const s={type:"element",tagName:"tbody",properties:{},children:e.wrap(r,!0)},o=fa(t.children[1]),l=Do(t.children[t.children.length-1]);o&&l&&(s.position={start:o,end:l}),a.push(s)}const i={type:"element",tagName:"table",properties:{},children:e.wrap(a,!0)};return e.patch(t,i),e.applyData(t,i)}function Iy(e,t,r){const n=r?r.children:void 0,i=(n?n.indexOf(t):1)===0?"th":"td",s=r&&r.type==="table"?r.align:void 0,o=s?s.length:t.children.length;let l=-1;const u=[];for(;++l<o;){const c=t.children[l],h={},f=s?s[l]:void 0;f&&(h.align=f);let g={type:"element",tagName:i,properties:h,children:[]};c&&(g.children=e.all(c),e.patch(c,g),g=e.applyData(c,g)),u.push(g)}const d={type:"element",tagName:"tr",properties:{},children:e.wrap(u,!0)};return e.patch(t,d),e.applyData(t,d)}function Ey(e,t){const r={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}const ml=9,gl=32;function Ay(e){const t=String(e),r=/\r?\n|\r/g;let n=r.exec(t),a=0;const i=[];for(;n;)i.push(yl(t.slice(a,n.index),a>0,!0),n[0]),a=n.index+n[0].length,n=r.exec(t);return i.push(yl(t.slice(a),a>0,!1)),i.join("")}function yl(e,t,r){let n=0,a=e.length;if(t){let i=e.codePointAt(n);for(;i===ml||i===gl;)n++,i=e.codePointAt(n)}if(r){let i=e.codePointAt(a-1);for(;i===ml||i===gl;)a--,i=e.codePointAt(a-1)}return a>n?e.slice(n,a):""}function My(e,t){const r={type:"text",value:Ay(String(t.value))};return e.patch(t,r),e.applyData(t,r)}function Py(e,t){const r={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,r),e.applyData(t,r)}const Ny={blockquote:oy,break:ly,code:uy,delete:cy,emphasis:dy,footnoteReference:hy,heading:fy,html:py,imageReference:my,image:gy,inlineCode:yy,linkReference:by,link:wy,listItem:xy,list:ky,paragraph:Sy,root:_y,strong:Ty,table:Cy,tableCell:Ey,tableRow:Iy,text:My,thematicBreak:Py,toml:ln,yaml:ln,definition:ln,footnoteDefinition:ln};function ln(){}const bl=-1,un=0,_r=1,cn=2,Ca=3,Ia=4,Ea=5,Aa=6,wl=7,xl=8,vl=typeof self=="object"?self:globalThis,Ly=(e,t)=>{const r=(a,i)=>(e.set(i,a),a),n=a=>{if(e.has(a))return e.get(a);const[i,s]=t[a];switch(i){case un:case bl:return r(s,a);case _r:{const o=r([],a);for(const l of s)o.push(n(l));return o}case cn:{const o=r({},a);for(const[l,u]of s)o[n(l)]=n(u);return o}case Ca:return r(new Date(s),a);case Ia:{const{source:o,flags:l}=s;return r(new RegExp(o,l),a)}case Ea:{const o=r(new Map,a);for(const[l,u]of s)o.set(n(l),n(u));return o}case Aa:{const o=r(new Set,a);for(const l of s)o.add(n(l));return o}case wl:{const{name:o,message:l}=s;return r(new vl[o](l),a)}case xl:return r(BigInt(s),a);case"BigInt":return r(Object(BigInt(s)),a);case"ArrayBuffer":return r(new Uint8Array(s).buffer,s);case"DataView":{const{buffer:o}=new Uint8Array(s);return r(new DataView(o),s)}}return r(new vl[i](s),a)};return n},kl=e=>Ly(new Map,e)(0),Gt="",{toString:Dy}={},{keys:Oy}=Object,Tr=e=>{const t=typeof e;if(t!=="object"||!e)return[un,t];const r=Dy.call(e).slice(8,-1);switch(r){case"Array":return[_r,Gt];case"Object":return[cn,Gt];case"Date":return[Ca,Gt];case"RegExp":return[Ia,Gt];case"Map":return[Ea,Gt];case"Set":return[Aa,Gt];case"DataView":return[_r,r]}return r.includes("Array")?[_r,r]:r.includes("Error")?[wl,r]:[cn,r]},dn=([e,t])=>e===un&&(t==="function"||t==="symbol"),Fy=(e,t,r,n)=>{const a=(s,o)=>{const l=n.push(s)-1;return r.set(o,l),l},i=s=>{if(r.has(s))return r.get(s);let[o,l]=Tr(s);switch(o){case un:{let d=s;switch(l){case"bigint":o=xl,d=s.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+l);d=null;break;case"undefined":return a([bl],s)}return a([o,d],s)}case _r:{if(l){let h=s;return l==="DataView"?h=new Uint8Array(s.buffer):l==="ArrayBuffer"&&(h=new Uint8Array(s)),a([l,[...h]],s)}const d=[],c=a([o,d],s);for(const h of s)d.push(i(h));return c}case cn:{if(l)switch(l){case"BigInt":return a([l,s.toString()],s);case"Boolean":case"Number":case"String":return a([l,s.valueOf()],s)}if(t&&"toJSON"in s)return i(s.toJSON());const d=[],c=a([o,d],s);for(const h of Oy(s))(e||!dn(Tr(s[h])))&&d.push([i(h),i(s[h])]);return c}case Ca:return a([o,s.toISOString()],s);case Ia:{const{source:d,flags:c}=s;return a([o,{source:d,flags:c}],s)}case Ea:{const d=[],c=a([o,d],s);for(const[h,f]of s)(e||!(dn(Tr(h))||dn(Tr(f))))&&d.push([i(h),i(f)]);return c}case Aa:{const d=[],c=a([o,d],s);for(const h of s)(e||!dn(Tr(h)))&&d.push(i(h));return c}}const{message:u}=s;return a([o,{name:l,message:u}],s)};return i},Sl=(e,{json:t,lossy:r}={})=>{const n=[];return Fy(!(t||r),!!t,new Map,n)(e),n},hn=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?kl(Sl(e,t)):structuredClone(e):(e,t)=>kl(Sl(e,t));function By(e,t){const r=[{type:"text",value:"↩"}];return t>1&&r.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),r}function zy(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function Ry(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",r=e.options.footnoteBackContent||By,n=e.options.footnoteBackLabel||zy,a=e.options.footnoteLabel||"Footnotes",i=e.options.footnoteLabelTagName||"h2",s=e.options.footnoteLabelProperties||{className:["sr-only"]},o=[];let l=-1;for(;++l<e.footnoteOrder.length;){const u=e.footnoteById.get(e.footnoteOrder[l]);if(!u)continue;const d=e.all(u),c=String(u.identifier).toUpperCase(),h=Yt(c.toLowerCase());let f=0;const g=[],v=e.footnoteCounts.get(c);for(;v!==void 0&&++f<=v;){g.length>0&&g.push({type:"text",value:" "});let _=typeof r=="string"?r:r(l,f);typeof _=="string"&&(_={type:"text",value:_}),g.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+h+(f>1?"-"+f:""),dataFootnoteBackref:"",ariaLabel:typeof n=="string"?n:n(l,f),className:["data-footnote-backref"]},children:Array.isArray(_)?_:[_]})}const b=d[d.length-1];if(b&&b.type==="element"&&b.tagName==="p"){const _=b.children[b.children.length-1];_&&_.type==="text"?_.value+=" ":b.children.push({type:"text",value:" "}),b.children.push(...g)}else d.push(...g);const w={type:"element",tagName:"li",properties:{id:t+"fn-"+h},children:e.wrap(d,!0)};e.patch(u,w),o.push(w)}if(o.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:i,properties:E(m({},hn(s)),{id:"footnote-label"}),children:[{type:"text",value:a}]},{type:"text",value:`
15
15
  `},{type:"element",tagName:"ol",properties:{},children:e.wrap(o,!0)},{type:"text",value:`
16
- `}]}}const fn=(function(e){if(e==null)return Uy;if(typeof e=="function")return pn(e);if(typeof e=="object")return Array.isArray(e)?Ry(e):jy(e);if(typeof e=="string")return $y(e);throw new Error("Expected function, string, or object as test")});function Ry(e){const t=[];let r=-1;for(;++r<e.length;)t[r]=fn(e[r]);return pn(n);function n(...a){let i=-1;for(;++i<t.length;)if(t[i].apply(this,a))return!0;return!1}}function jy(e){const t=e;return pn(r);function r(n){const a=n;let i;for(i in e)if(a[i]!==t[i])return!1;return!0}}function $y(e){return pn(t);function t(r){return r&&r.type===e}}function pn(e){return t;function t(r,n,a){return!!(Hy(r)&&e.call(this,r,typeof n=="number"?n:void 0,a||void 0))}}function Uy(){return!0}function Hy(e){return e!==null&&typeof e=="object"&&"type"in e}function Xv(e){return e}const Sl=[],qy=!0,Aa=!1,Vy="skip";function _l(e,t,r,n){let a;typeof t=="function"&&typeof r!="function"?(n=r,r=t):a=t;const i=fn(a),s=n?-1:1;o(e,void 0,[])();function o(l,u,d){const c=l&&typeof l=="object"?l:{};if(typeof c.type=="string"){const f=typeof c.tagName=="string"?c.tagName:typeof c.name=="string"?c.name:void 0;Object.defineProperty(h,"name",{value:"node ("+(l.type+(f?"<"+f+">":""))+")"})}return h;function h(){let f=Sl,g,v,b;if((!t||i(l,u,d[d.length-1]||void 0))&&(f=Wy(r(l,d)),f[0]===Aa))return f;if("children"in l&&l.children){const w=l;if(w.children&&f[0]!==Vy)for(v=(n?w.children.length:-1)+s,b=d.concat(w);v>-1&&v<w.children.length;){const T=w.children[v];if(g=o(T,v,b)(),g[0]===Aa)return g;v=typeof g[1]=="number"?g[1]:v+s}}return f}}}function Wy(e){return Array.isArray(e)?e:typeof e=="number"?[qy,e]:e==null?Sl:[e]}function Ma(e,t,r,n){let a,i,s;typeof t=="function"&&typeof r!="function"?(i=void 0,s=t,a=r):(i=t,s=r,a=n),_l(e,i,o,a);function o(l,u){const d=u[u.length-1],c=d?d.children.indexOf(l):void 0;return s(l,c,d)}}const Pa={}.hasOwnProperty,Jy={};function Yy(e,t){const r=t||Jy,n=new Map,a=new Map,i=new Map,s=m(m({},Py),r.handlers),o={all:u,applyData:Gy,definitionById:n,footnoteById:a,footnoteCounts:i,footnoteOrder:[],handlers:s,one:l,options:r,patch:Ky,wrap:Qy};return Ma(e,function(d){if(d.type==="definition"||d.type==="footnoteDefinition"){const c=d.type==="definition"?n:a,h=String(d.identifier).toUpperCase();c.has(h)||c.set(h,d)}}),o;function l(d,c){const h=d.type,f=o.handlers[h];if(Pa.call(o.handlers,h)&&f)return f(o,d,c);if(o.options.passThrough&&o.options.passThrough.includes(h)){if("children"in d){const v=d,{children:b}=v,w=V(v,["children"]),T=hn(w);return T.children=o.all(d),T}return hn(d)}return(o.options.unknownHandler||Xy)(o,d,c)}function u(d){const c=[];if("children"in d){const h=d.children;let f=-1;for(;++f<h.length;){const g=o.one(h[f],d);if(g){if(f&&h[f-1].type==="break"&&(!Array.isArray(g)&&g.type==="text"&&(g.value=Tl(g.value)),!Array.isArray(g)&&g.type==="element")){const v=g.children[0];v&&v.type==="text"&&(v.value=Tl(v.value))}Array.isArray(g)?c.push(...g):c.push(g)}}}return c}}function Ky(e,t){e.position&&(t.position=Wp(e))}function Gy(e,t){let r=t;if(e&&e.data){const n=e.data.hName,a=e.data.hChildren,i=e.data.hProperties;if(typeof n=="string")if(r.type==="element")r.tagName=n;else{const s="children"in r?r.children:[r];r={type:"element",tagName:n,properties:{},children:s}}r.type==="element"&&i&&Object.assign(r.properties,hn(i)),"children"in r&&r.children&&a!==null&&a!==void 0&&(r.children=a)}return r}function Xy(e,t){const r=t.data||{},n="value"in t&&!(Pa.call(r,"hProperties")||Pa.call(r,"hChildren"))?{type:"text",value:t.value}:{type:"element",tagName:"div",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function Qy(e,t){const r=[];let n=-1;for(t&&r.push({type:"text",value:`
16
+ `}]}}const fn=(function(e){if(e==null)return Hy;if(typeof e=="function")return pn(e);if(typeof e=="object")return Array.isArray(e)?jy(e):$y(e);if(typeof e=="string")return Uy(e);throw new Error("Expected function, string, or object as test")});function jy(e){const t=[];let r=-1;for(;++r<e.length;)t[r]=fn(e[r]);return pn(n);function n(...a){let i=-1;for(;++i<t.length;)if(t[i].apply(this,a))return!0;return!1}}function $y(e){const t=e;return pn(r);function r(n){const a=n;let i;for(i in e)if(a[i]!==t[i])return!1;return!0}}function Uy(e){return pn(t);function t(r){return r&&r.type===e}}function pn(e){return t;function t(r,n,a){return!!(qy(r)&&e.call(this,r,typeof n=="number"?n:void 0,a||void 0))}}function Hy(){return!0}function qy(e){return e!==null&&typeof e=="object"&&"type"in e}function Qv(e){return e}const _l=[],Vy=!0,Ma=!1,Wy="skip";function Tl(e,t,r,n){let a;typeof t=="function"&&typeof r!="function"?(n=r,r=t):a=t;const i=fn(a),s=n?-1:1;o(e,void 0,[])();function o(l,u,d){const c=l&&typeof l=="object"?l:{};if(typeof c.type=="string"){const f=typeof c.tagName=="string"?c.tagName:typeof c.name=="string"?c.name:void 0;Object.defineProperty(h,"name",{value:"node ("+(l.type+(f?"<"+f+">":""))+")"})}return h;function h(){let f=_l,g,v,b;if((!t||i(l,u,d[d.length-1]||void 0))&&(f=Jy(r(l,d)),f[0]===Ma))return f;if("children"in l&&l.children){const w=l;if(w.children&&f[0]!==Wy)for(v=(n?w.children.length:-1)+s,b=d.concat(w);v>-1&&v<w.children.length;){const _=w.children[v];if(g=o(_,v,b)(),g[0]===Ma)return g;v=typeof g[1]=="number"?g[1]:v+s}}return f}}}function Jy(e){return Array.isArray(e)?e:typeof e=="number"?[Vy,e]:e==null?_l:[e]}function Pa(e,t,r,n){let a,i,s;typeof t=="function"&&typeof r!="function"?(i=void 0,s=t,a=r):(i=t,s=r,a=n),Tl(e,i,o,a);function o(l,u){const d=u[u.length-1],c=d?d.children.indexOf(l):void 0;return s(l,c,d)}}const Na={}.hasOwnProperty,Yy={};function Ky(e,t){const r=t||Yy,n=new Map,a=new Map,i=new Map,s=m(m({},Ny),r.handlers),o={all:u,applyData:Xy,definitionById:n,footnoteById:a,footnoteCounts:i,footnoteOrder:[],handlers:s,one:l,options:r,patch:Gy,wrap:Zy};return Pa(e,function(d){if(d.type==="definition"||d.type==="footnoteDefinition"){const c=d.type==="definition"?n:a,h=String(d.identifier).toUpperCase();c.has(h)||c.set(h,d)}}),o;function l(d,c){const h=d.type,f=o.handlers[h];if(Na.call(o.handlers,h)&&f)return f(o,d,c);if(o.options.passThrough&&o.options.passThrough.includes(h)){if("children"in d){const v=d,{children:b}=v,w=V(v,["children"]),_=hn(w);return _.children=o.all(d),_}return hn(d)}return(o.options.unknownHandler||Qy)(o,d,c)}function u(d){const c=[];if("children"in d){const h=d.children;let f=-1;for(;++f<h.length;){const g=o.one(h[f],d);if(g){if(f&&h[f-1].type==="break"&&(!Array.isArray(g)&&g.type==="text"&&(g.value=Cl(g.value)),!Array.isArray(g)&&g.type==="element")){const v=g.children[0];v&&v.type==="text"&&(v.value=Cl(v.value))}Array.isArray(g)?c.push(...g):c.push(g)}}}return c}}function Gy(e,t){e.position&&(t.position=Jp(e))}function Xy(e,t){let r=t;if(e&&e.data){const n=e.data.hName,a=e.data.hChildren,i=e.data.hProperties;if(typeof n=="string")if(r.type==="element")r.tagName=n;else{const s="children"in r?r.children:[r];r={type:"element",tagName:n,properties:{},children:s}}r.type==="element"&&i&&Object.assign(r.properties,hn(i)),"children"in r&&r.children&&a!==null&&a!==void 0&&(r.children=a)}return r}function Qy(e,t){const r=t.data||{},n="value"in t&&!(Na.call(r,"hProperties")||Na.call(r,"hChildren"))?{type:"text",value:t.value}:{type:"element",tagName:"div",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function Zy(e,t){const r=[];let n=-1;for(t&&r.push({type:"text",value:`
17
17
  `});++n<e.length;)n&&r.push({type:"text",value:`
18
18
  `}),r.push(e[n]);return t&&e.length>0&&r.push({type:"text",value:`
19
- `}),r}function Tl(e){let t=0,r=e.charCodeAt(t);for(;r===9||r===32;)t++,r=e.charCodeAt(t);return e.slice(t)}function Cl(e,t){const r=Yy(e,t),n=r.one(e,void 0),a=zy(r),i=Array.isArray(n)?{type:"root",children:n}:n||{type:"root",children:[]};return a&&i.children.push({type:"text",value:`
20
- `},a),i}function Zy(e,t){return e&&"run"in e?function(r,n){return P(this,null,function*(){const a=Cl(r,m({file:n},t));yield e.run(a,n)})}:function(r,n){return Cl(r,m({file:n},e||t))}}function Il(e){if(e)throw e}var Na,El;function eb(){if(El)return Na;El=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,r=Object.defineProperty,n=Object.getOwnPropertyDescriptor,a=function(u){return typeof Array.isArray=="function"?Array.isArray(u):t.call(u)==="[object Array]"},i=function(u){if(!u||t.call(u)!=="[object Object]")return!1;var d=e.call(u,"constructor"),c=u.constructor&&u.constructor.prototype&&e.call(u.constructor.prototype,"isPrototypeOf");if(u.constructor&&!d&&!c)return!1;var h;for(h in u);return typeof h=="undefined"||e.call(u,h)},s=function(u,d){r&&d.name==="__proto__"?r(u,d.name,{enumerable:!0,configurable:!0,value:d.newValue,writable:!0}):u[d.name]=d.newValue},o=function(u,d){if(d==="__proto__")if(e.call(u,d)){if(n)return n(u,d).value}else return;return u[d]};return Na=function l(){var u,d,c,h,f,g,v=arguments[0],b=1,w=arguments.length,T=!1;for(typeof v=="boolean"&&(T=v,v=arguments[1]||{},b=2),(v==null||typeof v!="object"&&typeof v!="function")&&(v={});b<w;++b)if(u=arguments[b],u!=null)for(d in u)c=o(v,d),h=o(u,d),v!==h&&(T&&h&&(i(h)||(f=a(h)))?(f?(f=!1,g=c&&a(c)?c:[]):g=c&&i(c)?c:{},s(v,{name:d,newValue:l(T,g,h)})):typeof h!="undefined"&&s(v,{name:d,newValue:h}));return v},Na}var tb=eb();const La=Nr(tb);function Da(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function rb(){const e=[],t={run:r,use:n};return t;function r(...a){let i=-1;const s=a.pop();if(typeof s!="function")throw new TypeError("Expected function as last argument, not "+s);o(null,...a);function o(l,...u){const d=e[++i];let c=-1;if(l){s(l);return}for(;++c<a.length;)(u[c]===null||u[c]===void 0)&&(u[c]=a[c]);a=u,d?nb(d,o)(...u):s(null,...u)}}function n(a){if(typeof a!="function")throw new TypeError("Expected `middelware` to be a function, not "+a);return e.push(a),t}}function nb(e,t){let r;return n;function n(...s){const o=e.length>s.length;let l;o&&s.push(a);try{l=e.apply(this,s)}catch(u){const d=u;if(o&&r)throw d;return a(d)}o||(l&&l.then&&typeof l.then=="function"?l.then(i,a):l instanceof Error?a(l):i(l))}function a(s,...o){r||(r=!0,t(s,...o))}function i(s){a(null,s)}}const ut={basename:ab,dirname:ib,extname:sb,join:ob,sep:"/"};function ab(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Tr(e);let r=0,n=-1,a=e.length,i;if(t===void 0||t.length===0||t.length>e.length){for(;a--;)if(e.codePointAt(a)===47){if(i){r=a+1;break}}else n<0&&(i=!0,n=a+1);return n<0?"":e.slice(r,n)}if(t===e)return"";let s=-1,o=t.length-1;for(;a--;)if(e.codePointAt(a)===47){if(i){r=a+1;break}}else s<0&&(i=!0,s=a+1),o>-1&&(e.codePointAt(a)===t.codePointAt(o--)?o<0&&(n=a):(o=-1,n=s));return r===n?n=s:n<0&&(n=e.length),e.slice(r,n)}function ib(e){if(Tr(e),e.length===0)return".";let t=-1,r=e.length,n;for(;--r;)if(e.codePointAt(r)===47){if(n){t=r;break}}else n||(n=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function sb(e){Tr(e);let t=e.length,r=-1,n=0,a=-1,i=0,s;for(;t--;){const o=e.codePointAt(t);if(o===47){if(s){n=t+1;break}continue}r<0&&(s=!0,r=t+1),o===46?a<0?a=t:i!==1&&(i=1):a>-1&&(i=-1)}return a<0||r<0||i===0||i===1&&a===r-1&&a===n+1?"":e.slice(a,r)}function ob(...e){let t=-1,r;for(;++t<e.length;)Tr(e[t]),e[t]&&(r=r===void 0?e[t]:r+"/"+e[t]);return r===void 0?".":lb(r)}function lb(e){Tr(e);const t=e.codePointAt(0)===47;let r=ub(e,!t);return r.length===0&&!t&&(r="."),r.length>0&&e.codePointAt(e.length-1)===47&&(r+="/"),t?"/"+r:r}function ub(e,t){let r="",n=0,a=-1,i=0,s=-1,o,l;for(;++s<=e.length;){if(s<e.length)o=e.codePointAt(s);else{if(o===47)break;o=47}if(o===47){if(!(a===s-1||i===1))if(a!==s-1&&i===2){if(r.length<2||n!==2||r.codePointAt(r.length-1)!==46||r.codePointAt(r.length-2)!==46){if(r.length>2){if(l=r.lastIndexOf("/"),l!==r.length-1){l<0?(r="",n=0):(r=r.slice(0,l),n=r.length-1-r.lastIndexOf("/")),a=s,i=0;continue}}else if(r.length>0){r="",n=0,a=s,i=0;continue}}t&&(r=r.length>0?r+"/..":"..",n=2)}else r.length>0?r+="/"+e.slice(a+1,s):r=e.slice(a+1,s),n=s-a-1;a=s,i=0}else o===46&&i>-1?i++:i=-1}return r}function Tr(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const cb={cwd:db};function db(){return"/"}function Oa(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function hb(e){if(typeof e=="string")e=new URL(e);else if(!Oa(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return fb(e)}function fb(e){if(e.hostname!==""){const n=new TypeError('File URL host must be "localhost" or empty on darwin');throw n.code="ERR_INVALID_FILE_URL_HOST",n}const t=e.pathname;let r=-1;for(;++r<t.length;)if(t.codePointAt(r)===37&&t.codePointAt(r+1)===50){const n=t.codePointAt(r+2);if(n===70||n===102){const a=new TypeError("File URL path must not include encoded / characters");throw a.code="ERR_INVALID_FILE_URL_PATH",a}}return decodeURIComponent(t)}const Fa=["history","path","basename","stem","extname","dirname"];class Al{constructor(t){let r;t?Oa(t)?r={path:t}:typeof t=="string"||pb(t)?r={value:t}:r=t:r={},this.cwd="cwd"in r?"":cb.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let n=-1;for(;++n<Fa.length;){const i=Fa[n];i in r&&r[i]!==void 0&&r[i]!==null&&(this[i]=i==="history"?[...r[i]]:r[i])}let a;for(a in r)Fa.includes(a)||(this[a]=r[a])}get basename(){return typeof this.path=="string"?ut.basename(this.path):void 0}set basename(t){za(t,"basename"),Ba(t,"basename"),this.path=ut.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?ut.dirname(this.path):void 0}set dirname(t){Ml(this.basename,"dirname"),this.path=ut.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?ut.extname(this.path):void 0}set extname(t){if(Ba(t,"extname"),Ml(this.dirname,"extname"),t){if(t.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(t.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=ut.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){Oa(t)&&(t=hb(t)),za(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?ut.basename(this.path,this.extname):void 0}set stem(t){za(t,"stem"),Ba(t,"stem"),this.path=ut.join(this.dirname||"",t+(this.extname||""))}fail(t,r,n){const a=this.message(t,r,n);throw a.fatal=!0,a}info(t,r,n){const a=this.message(t,r,n);return a.fatal=void 0,a}message(t,r,n){const a=new Ee(t,r,n);return this.path&&(a.name=this.path+":"+a.name,a.file=this.path),a.fatal=!1,this.messages.push(a),a}toString(t){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(t||void 0).decode(this.value)}}function Ba(e,t){if(e&&e.includes(ut.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+ut.sep+"`")}function za(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function Ml(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function pb(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const mb=(function(e){const n=this.constructor.prototype,a=n[e],i=function(){return a.apply(i,arguments)};return Object.setPrototypeOf(i,n),i}),gb={}.hasOwnProperty;class Ra extends mb{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=rb()}copy(){const t=new Ra;let r=-1;for(;++r<this.attachers.length;){const n=this.attachers[r];t.use(...n)}return t.data(La(!0,{},this.namespace)),t}data(t,r){return typeof t=="string"?arguments.length===2?(Ua("data",this.frozen),this.namespace[t]=r,this):gb.call(this.namespace,t)&&this.namespace[t]||void 0:t?(Ua("data",this.frozen),this.namespace=t,this):this.namespace}freeze(){if(this.frozen)return this;const t=this;for(;++this.freezeIndex<this.attachers.length;){const[r,...n]=this.attachers[this.freezeIndex];if(n[0]===!1)continue;n[0]===!0&&(n[0]=void 0);const a=r.call(t,...n);typeof a=="function"&&this.transformers.use(a)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(t){this.freeze();const r=mn(t),n=this.parser||this.Parser;return ja("parse",n),n(String(r),r)}process(t,r){const n=this;return this.freeze(),ja("process",this.parser||this.Parser),$a("process",this.compiler||this.Compiler),r?a(void 0,r):new Promise(a);function a(i,s){const o=mn(t),l=n.parse(o);n.run(l,o,function(d,c,h){if(d||!c||!h)return u(d);const f=c,g=n.stringify(f,h);wb(g)?h.value=g:h.result=g,u(d,h)});function u(d,c){d||!c?s(d):i?i(c):r(void 0,c)}}}processSync(t){let r=!1,n;return this.freeze(),ja("processSync",this.parser||this.Parser),$a("processSync",this.compiler||this.Compiler),this.process(t,a),Nl("processSync","process",r),n;function a(i,s){r=!0,Il(i),n=s}}run(t,r,n){Pl(t),this.freeze();const a=this.transformers;return!n&&typeof r=="function"&&(n=r,r=void 0),n?i(void 0,n):new Promise(i);function i(s,o){const l=mn(r);a.run(t,l,u);function u(d,c,h){const f=c||t;d?o(d):s?s(f):n(void 0,f,h)}}}runSync(t,r){let n=!1,a;return this.run(t,r,i),Nl("runSync","run",n),a;function i(s,o){Il(s),a=o,n=!0}}stringify(t,r){this.freeze();const n=mn(r),a=this.compiler||this.Compiler;return $a("stringify",a),Pl(t),a(t,n)}use(t,...r){const n=this.attachers,a=this.namespace;if(Ua("use",this.frozen),t!=null)if(typeof t=="function")l(t,r);else if(typeof t=="object")Array.isArray(t)?o(t):s(t);else throw new TypeError("Expected usable value, not `"+t+"`");return this;function i(u){if(typeof u=="function")l(u,[]);else if(typeof u=="object")if(Array.isArray(u)){const[d,...c]=u;l(d,c)}else s(u);else throw new TypeError("Expected usable value, not `"+u+"`")}function s(u){if(!("plugins"in u)&&!("settings"in u))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");o(u.plugins),u.settings&&(a.settings=La(!0,a.settings,u.settings))}function o(u){let d=-1;if(u!=null)if(Array.isArray(u))for(;++d<u.length;){const c=u[d];i(c)}else throw new TypeError("Expected a list of plugins, not `"+u+"`")}function l(u,d){let c=-1,h=-1;for(;++c<n.length;)if(n[c][0]===u){h=c;break}if(h===-1)n.push([u,...d]);else if(d.length>0){let[f,...g]=d;const v=n[h][1];Da(v)&&Da(f)&&(f=La(!0,v,f)),n[h]=[u,f,...g]}}}}const yb=new Ra().freeze();function ja(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function $a(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Ua(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Pl(e){if(!Da(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Nl(e,t,r){if(!r)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function mn(e){return bb(e)?e:new Al(e)}function bb(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function wb(e){return typeof e=="string"||xb(e)}function xb(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const vb="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Ll=[],Dl={allowDangerousHtml:!0},kb=/^(https?|ircs?|mailto|xmpp)$/i,Sb=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function _b(e){const t=Tb(e),r=Cb(e);return Ib(t.runSync(t.parse(r),r),e)}function Tb(e){const t=e.rehypePlugins||Ll,r=e.remarkPlugins||Ll,n=e.remarkRehypeOptions?m(m({},e.remarkRehypeOptions),Dl):Dl;return yb().use(iy).use(r).use(Zy,n).use(t)}function Cb(e){const t=e.children||"",r=new Al;return typeof t=="string"&&(r.value=t),r}function Ib(e,t){const r=t.allowedElements,n=t.allowElement,a=t.components,i=t.disallowedElements,s=t.skipHtml,o=t.unwrapDisallowed,l=t.urlTransform||Eb;for(const d of Sb)Object.hasOwn(t,d.from)&&(""+d.from+(d.to?"use `"+d.to+"` instead":"remove it")+vb+d.id,void 0);return Ma(e,u),Xp(e,{Fragment:p.Fragment,components:a,ignoreInvalidStyle:!0,jsx:p.jsx,jsxs:p.jsxs,passKeys:!0,passNode:!0});function u(d,c,h){if(d.type==="raw"&&h&&typeof c=="number")return s?h.children.splice(c,1):h.children[c]={type:"text",value:d.value},c;if(d.type==="element"){let f;for(f in ya)if(Object.hasOwn(ya,f)&&Object.hasOwn(d.properties,f)){const g=d.properties[f],v=ya[f];(v===null||v.includes(d.tagName))&&(d.properties[f]=l(String(g||""),f,d))}}if(d.type==="element"){let f=r?!r.includes(d.tagName):i?i.includes(d.tagName):!1;if(!f&&n&&typeof c=="number"&&(f=!n(d,c,h)),f&&h&&typeof c=="number")return o&&d.children?h.children.splice(c,1,...d.children):h.children.splice(c,1),c}}}function Eb(e){const t=e.indexOf(":"),r=e.indexOf("?"),n=e.indexOf("#"),a=e.indexOf("/");return t===-1||a!==-1&&t>a||r!==-1&&t>r||n!==-1&&t>n||kb.test(e.slice(0,t))?e:""}var Ab=(e,t)=>typeof e=="string"?e===t:JSON.stringify(e)===JSON.stringify(t),Mb=(e,t)=>{if(!e||!t)return!1;const r=n=>{const o=n||{},{position:a,data:i}=o;return V(o,["position","data"])};return JSON.stringify(r(e.properties))===JSON.stringify(r(t.properties))&&Ab(e.children,t.children)},Ha=(e,t)=>Mb(e.node,t.node),Pb=(e={})=>Object.fromEntries(Object.entries(e!=null?e:{}).map(([t,r])=>{if(!r)return[t,r];const n=r,a=o=>{var l=o,{node:i}=l,s=V(l,["node"]);return p.jsx(n,m({},s))};return[t,y.memo(a,Ha)]})),qa=y.createContext(null),Ol=()=>y.useContext(qa)!==null,Nb=r=>{var n=r,{children:e}=n,t=V(n,["children"]);return p.jsx(qa.Provider,{value:t,children:e})},Lb=y.memo(Nb,Ha),Db=r=>{var n=r,{node:e}=n,t=V(n,["node"]);return p.jsx("pre",m({},t))},Ob=r=>{var n=r,{node:e}=n,t=V(n,["node"]);return p.jsx("code",m({},t))},Va=({node:e,components:{Pre:t,Code:r},code:n})=>p.jsx(t,{children:p.jsx(r,{node:e,children:n})}),Fb=()=>null,Bb=({node:e,components:{Pre:t,Code:r,SyntaxHighlighter:n,CodeHeader:a},language:i,code:s})=>{const o=y.useMemo(()=>({Pre:t,Code:r}),[t,r]),l=i?n:Va;return p.jsxs(p.Fragment,{children:[p.jsx(a,{node:e,language:i,code:s}),p.jsx(l,{node:e,components:o,language:i!=null?i:"unknown",code:s})]})},Wa={exports:{}};var Fl;function zb(){return Fl||(Fl=1,(function(e){(function(){var t={}.hasOwnProperty;function r(){for(var i="",s=0;s<arguments.length;s++){var o=arguments[s];o&&(i=a(i,n(o)))}return i}function n(i){if(typeof i=="string"||typeof i=="number")return i;if(typeof i!="object")return"";if(Array.isArray(i))return r.apply(null,i);if(i.toString!==Object.prototype.toString&&!i.toString.toString().includes("[native code]"))return i.toString();var s="";for(var o in i)t.call(i,o)&&i[o]&&(s=a(s,o));return s}function a(i,s){return s?i?i+" "+s:i+s:i}e.exports?(r.default=r,e.exports=r):window.classNames=r})()})(Wa)),Wa.exports}var Rb=zb();const Bl=Nr(Rb);var zl=r=>{var n=r,{className:e}=n,t=V(n,["className"]);return s=>{var o=s,{className:a}=o,i=V(o,["className"]);return m(m({className:Bl(e,a)},t),i)}},jb=l=>{var u=l,{node:e,components:{Pre:t,Code:r,SyntaxHighlighter:n,CodeHeader:a},componentsByLanguage:i={},children:s}=u,o=V(u,["node","components","componentsByLanguage","children"]);var T,_,D,z,I,B;const d=y.useContext(qa),c=zl(d),h=At(H=>p.jsx(t,m({},c(H)))),f=zl(o),g=At(H=>p.jsx(r,m({},f(H)))),v=(_=(T=/language-(\w+)/.exec(o.className||""))==null?void 0:T[1])!=null?_:"";if(typeof s!="string")return p.jsx(Va,{node:e,components:{Pre:h,Code:g},code:s});const b=(z=(D=i[v])==null?void 0:D.SyntaxHighlighter)!=null?z:n,w=(B=(I=i[v])==null?void 0:I.CodeHeader)!=null?B:a;return p.jsx(Bb,{node:e,components:{Pre:h,Code:g,SyntaxHighlighter:b,CodeHeader:w},language:v||"unknown",code:s})},$b=a=>{var i=a,{node:e,components:t,componentsByLanguage:r}=i,n=V(i,["node","components","componentsByLanguage"]);return Ol()?p.jsx(jb,m({node:e,components:t,componentsByLanguage:r},n)):p.jsx(t.Code,m({},n))},Ub=y.memo($b,(e,t)=>e.components===t.components&&e.componentsByLanguage===t.componentsByLanguage&&Ha(e,t)),{useSmooth:Hb,useSmoothStatus:qb,withSmoothContextProvider:Vb}=Yh,Wb=i=>{var s=i,{components:e,componentsByLanguage:t,smooth:r=!0,preprocess:n}=s,a=V(s,["components","componentsByLanguage","smooth","preprocess"]);const o=Ns(),l=y.useMemo(()=>n?E(m({},o),{text:n(o.text)}):o,[o,n]),{text:u}=Hb(l,r),{pre:d=Db,code:c=Ob,SyntaxHighlighter:h=Va,CodeHeader:f=Fb}=e!=null?e:{},g=y.useMemo(()=>({Pre:d,Code:c,SyntaxHighlighter:h,CodeHeader:f}),[d,c,h,f]),v=At(w=>p.jsx(Ub,m({components:g,componentsByLanguage:t},w))),b=y.useMemo(()=>{const I=e!=null?e:{},{pre:w,code:T,SyntaxHighlighter:_,CodeHeader:D}=I,z=V(I,["pre","code","SyntaxHighlighter","CodeHeader"]);return E(m({},z),{pre:Lb,code:v})},[v,e]);return p.jsx(_b,E(m({components:b},a),{children:u}))},Rl=y.forwardRef((i,a)=>{var s=i,{className:e,containerProps:t,containerComponent:r="div"}=s,n=V(s,["className","containerProps","containerComponent"]);const o=qb();return p.jsx(r,E(m({"data-status":o.type},t),{className:Bl(e,t==null?void 0:t.className),ref:a,children:p.jsx(Wb,m({},n))}))});Rl.displayName="MarkdownTextPrimitive";var Jb=Vb(Rl);function jl(e,t){const r=String(e);if(typeof t!="string")throw new TypeError("Expected character");let n=0,a=r.indexOf(t);for(;a!==-1;)n++,a=r.indexOf(t,a+t.length);return n}function Yb(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function Kb(e,t,r){const a=fn((r||{}).ignore||[]),i=Gb(t);let s=-1;for(;++s<i.length;)_l(e,"text",o);function o(u,d){let c=-1,h;for(;++c<d.length;){const f=d[c],g=h?h.children:void 0;if(a(f,g?g.indexOf(f):void 0,h))return;h=f}if(h)return l(u,d)}function l(u,d){const c=d[d.length-1],h=i[s][0],f=i[s][1];let g=0;const b=c.children.indexOf(u);let w=!1,T=[];h.lastIndex=0;let _=h.exec(u.value);for(;_;){const D=_.index,z={index:_.index,input:_.input,stack:[...d,u]};let I=f(..._,z);if(typeof I=="string"&&(I=I.length>0?{type:"text",value:I}:void 0),I===!1?h.lastIndex=D+1:(g!==D&&T.push({type:"text",value:u.value.slice(g,D)}),Array.isArray(I)?T.push(...I):I&&T.push(I),g=D+_[0].length,w=!0),!h.global)break;_=h.exec(u.value)}return w?(g<u.value.length&&T.push({type:"text",value:u.value.slice(g)}),c.children.splice(b,1,...T)):T=[u],b+T.length}}function Gb(e){const t=[];if(!Array.isArray(e))throw new TypeError("Expected find and replace tuple or list of tuples");const r=!e[0]||Array.isArray(e[0])?e:[e];let n=-1;for(;++n<r.length;){const a=r[n];t.push([Xb(a[0]),Qb(a[1])])}return t}function Xb(e){return typeof e=="string"?new RegExp(Yb(e),"g"):e}function Qb(e){return typeof e=="function"?e:function(){return e}}const Ja="phrasing",Ya=["autolink","link","image","label"];function Zb(){return{transforms:[sw],enter:{literalAutolink:tw,literalAutolinkEmail:Ka,literalAutolinkHttp:Ka,literalAutolinkWww:Ka},exit:{literalAutolink:iw,literalAutolinkEmail:aw,literalAutolinkHttp:rw,literalAutolinkWww:nw}}}function ew(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Ja,notInConstruct:Ya},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Ja,notInConstruct:Ya},{character:":",before:"[ps]",after:"\\/",inConstruct:Ja,notInConstruct:Ya}]}}function tw(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function Ka(e){this.config.enter.autolinkProtocol.call(this,e)}function rw(e){this.config.exit.autolinkProtocol.call(this,e)}function nw(e){this.config.exit.data.call(this,e);const t=this.stack[this.stack.length-1];t.type,t.url="http://"+this.sliceSerialize(e)}function aw(e){this.config.exit.autolinkEmail.call(this,e)}function iw(e){this.exit(e)}function sw(e){Kb(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,ow],[new RegExp("(?<=^|\\s|\\p{P}|\\p{S})([-.\\w+]+)@([-\\w]+(?:\\.[-\\w]+)+)","gu"),lw]],{ignore:["link","linkReference"]})}function ow(e,t,r,n,a){let i="";if(!$l(a)||(/^w/i.test(t)&&(r=t+r,t="",i="http://"),!uw(r)))return!1;const s=cw(r+n);if(!s[0])return!1;const o={type:"link",title:null,url:i+t+s[0],children:[{type:"text",value:t+s[0]}]};return s[1]?[o,{type:"text",value:s[1]}]:o}function lw(e,t,r,n){return!$l(n,!0)||/[-\d_]$/.test(r)?!1:{type:"link",title:null,url:"mailto:"+t+"@"+r,children:[{type:"text",value:t+"@"+r}]}}function uw(e){const t=e.split(".");return!(t.length<2||t[t.length-1]&&(/_/.test(t[t.length-1])||!/[a-zA-Z\d]/.test(t[t.length-1]))||t[t.length-2]&&(/_/.test(t[t.length-2])||!/[a-zA-Z\d]/.test(t[t.length-2])))}function cw(e){const t=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let r=t[0],n=r.indexOf(")");const a=jl(e,"(");let i=jl(e,")");for(;n!==-1&&a>i;)e+=r.slice(0,n+1),r=r.slice(n+1),n=r.indexOf(")"),i++;return[e,r]}function $l(e,t){const r=e.input.charCodeAt(e.index-1);return(e.index===0||Pt(r)||an(r))&&(!t||r!==47)}Ul.peek=ww;function dw(){this.buffer()}function hw(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function fw(){this.buffer()}function pw(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function mw(e){const t=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=at(this.sliceSerialize(e)).toLowerCase(),r.label=t}function gw(e){this.exit(e)}function yw(e){const t=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=at(this.sliceSerialize(e)).toLowerCase(),r.label=t}function bw(e){this.exit(e)}function ww(){return"["}function Ul(e,t,r,n){const a=r.createTracker(n);let i=a.move("[^");const s=r.enter("footnoteReference"),o=r.enter("reference");return i+=a.move(r.safe(r.associationId(e),{after:"]",before:i})),o(),s(),i+=a.move("]"),i}function xw(){return{enter:{gfmFootnoteCallString:dw,gfmFootnoteCall:hw,gfmFootnoteDefinitionLabelString:fw,gfmFootnoteDefinition:pw},exit:{gfmFootnoteCallString:mw,gfmFootnoteCall:gw,gfmFootnoteDefinitionLabelString:yw,gfmFootnoteDefinition:bw}}}function vw(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:r,footnoteReference:Ul},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function r(n,a,i,s){const o=i.createTracker(s);let l=o.move("[^");const u=i.enter("footnoteDefinition"),d=i.enter("label");return l+=o.move(i.safe(i.associationId(n),{before:l,after:"]"})),d(),l+=o.move("]:"),n.children&&n.children.length>0&&(o.shift(4),l+=o.move((t?`
21
- `:" ")+i.indentLines(i.containerFlow(n,o.current()),t?Hl:kw))),u(),l}}function kw(e,t,r){return t===0?e:Hl(e,t,r)}function Hl(e,t,r){return(r?"":" ")+e}const Sw=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];ql.peek=Ew;function _w(){return{canContainEols:["delete"],enter:{strikethrough:Cw},exit:{strikethrough:Iw}}}function Tw(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:Sw}],handlers:{delete:ql}}}function Cw(e){this.enter({type:"delete",children:[]},e)}function Iw(e){this.exit(e)}function ql(e,t,r,n){const a=r.createTracker(n),i=r.enter("strikethrough");let s=a.move("~~");return s+=r.containerPhrasing(e,E(m({},a.current()),{before:s,after:"~"})),s+=a.move("~~"),i(),s}function Ew(){return"~"}function Aw(e){return e.length}function Mw(e,t){const r=t||{},n=(r.align||[]).concat(),a=r.stringLength||Aw,i=[],s=[],o=[],l=[];let u=0,d=-1;for(;++d<e.length;){const v=[],b=[];let w=-1;for(e[d].length>u&&(u=e[d].length);++w<e[d].length;){const T=Pw(e[d][w]);if(r.alignDelimiters!==!1){const _=a(T);b[w]=_,(l[w]===void 0||_>l[w])&&(l[w]=_)}v.push(T)}s[d]=v,o[d]=b}let c=-1;if(typeof n=="object"&&"length"in n)for(;++c<u;)i[c]=Vl(n[c]);else{const v=Vl(n);for(;++c<u;)i[c]=v}c=-1;const h=[],f=[];for(;++c<u;){const v=i[c];let b="",w="";v===99?(b=":",w=":"):v===108?b=":":v===114&&(w=":");let T=r.alignDelimiters===!1?1:Math.max(1,l[c]-b.length-w.length);const _=b+"-".repeat(T)+w;r.alignDelimiters!==!1&&(T=b.length+T+w.length,T>l[c]&&(l[c]=T),f[c]=T),h[c]=_}s.splice(1,0,h),o.splice(1,0,f),d=-1;const g=[];for(;++d<s.length;){const v=s[d],b=o[d];c=-1;const w=[];for(;++c<u;){const T=v[c]||"";let _="",D="";if(r.alignDelimiters!==!1){const z=l[c]-(b[c]||0),I=i[c];I===114?_=" ".repeat(z):I===99?z%2?(_=" ".repeat(z/2+.5),D=" ".repeat(z/2-.5)):(_=" ".repeat(z/2),D=_):D=" ".repeat(z)}r.delimiterStart!==!1&&!c&&w.push("|"),r.padding!==!1&&!(r.alignDelimiters===!1&&T==="")&&(r.delimiterStart!==!1||c)&&w.push(" "),r.alignDelimiters!==!1&&w.push(_),w.push(T),r.alignDelimiters!==!1&&w.push(D),r.padding!==!1&&w.push(" "),(r.delimiterEnd!==!1||c!==u-1)&&w.push("|")}g.push(r.delimiterEnd===!1?w.join("").replace(/ +$/,""):w.join(""))}return g.join(`
22
- `)}function Pw(e){return e==null?"":String(e)}function Vl(e){const t=typeof e=="string"?e.codePointAt(0):0;return t===67||t===99?99:t===76||t===108?108:t===82||t===114?114:0}function Nw(e,t,r,n){const a=r.enter("blockquote"),i=r.createTracker(n);i.move("> "),i.shift(2);const s=r.indentLines(r.containerFlow(e,i.current()),Lw);return a(),s}function Lw(e,t,r){return">"+(r?"":" ")+e}function Dw(e,t){return Wl(e,t.inConstruct,!0)&&!Wl(e,t.notInConstruct,!1)}function Wl(e,t,r){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return r;let n=-1;for(;++n<t.length;)if(e.includes(t[n]))return!0;return!1}function Jl(e,t,r,n){let a=-1;for(;++a<r.unsafe.length;)if(r.unsafe[a].character===`
23
- `&&Dw(r.stack,r.unsafe[a]))return/[ \t]/.test(n.before)?"":" ";return`\\
24
- `}function Ow(e,t){const r=String(e);let n=r.indexOf(t),a=n,i=0,s=0;if(typeof t!="string")throw new TypeError("Expected substring");for(;n!==-1;)n===a?++i>s&&(s=i):i=1,a=n+t.length,n=r.indexOf(t,a);return s}function Fw(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function Bw(e){const t=e.options.fence||"`";if(t!=="`"&&t!=="~")throw new Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function zw(e,t,r,n){const a=Bw(r),i=e.value||"",s=a==="`"?"GraveAccent":"Tilde";if(Fw(e,r)){const c=r.enter("codeIndented"),h=r.indentLines(i,Rw);return c(),h}const o=r.createTracker(n),l=a.repeat(Math.max(Ow(i,a)+1,3)),u=r.enter("codeFenced");let d=o.move(l);if(e.lang){const c=r.enter(`codeFencedLang${s}`);d+=o.move(r.safe(e.lang,m({before:d,after:" ",encode:["`"]},o.current()))),c()}if(e.lang&&e.meta){const c=r.enter(`codeFencedMeta${s}`);d+=o.move(" "),d+=o.move(r.safe(e.meta,m({before:d,after:`
19
+ `}),r}function Cl(e){let t=0,r=e.charCodeAt(t);for(;r===9||r===32;)t++,r=e.charCodeAt(t);return e.slice(t)}function Il(e,t){const r=Ky(e,t),n=r.one(e,void 0),a=Ry(r),i=Array.isArray(n)?{type:"root",children:n}:n||{type:"root",children:[]};return a&&i.children.push({type:"text",value:`
20
+ `},a),i}function eb(e,t){return e&&"run"in e?function(r,n){return P(this,null,function*(){const a=Il(r,m({file:n},t));yield e.run(a,n)})}:function(r,n){return Il(r,m({file:n},e||t))}}function El(e){if(e)throw e}var La,Al;function tb(){if(Al)return La;Al=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,r=Object.defineProperty,n=Object.getOwnPropertyDescriptor,a=function(u){return typeof Array.isArray=="function"?Array.isArray(u):t.call(u)==="[object Array]"},i=function(u){if(!u||t.call(u)!=="[object Object]")return!1;var d=e.call(u,"constructor"),c=u.constructor&&u.constructor.prototype&&e.call(u.constructor.prototype,"isPrototypeOf");if(u.constructor&&!d&&!c)return!1;var h;for(h in u);return typeof h=="undefined"||e.call(u,h)},s=function(u,d){r&&d.name==="__proto__"?r(u,d.name,{enumerable:!0,configurable:!0,value:d.newValue,writable:!0}):u[d.name]=d.newValue},o=function(u,d){if(d==="__proto__")if(e.call(u,d)){if(n)return n(u,d).value}else return;return u[d]};return La=function l(){var u,d,c,h,f,g,v=arguments[0],b=1,w=arguments.length,_=!1;for(typeof v=="boolean"&&(_=v,v=arguments[1]||{},b=2),(v==null||typeof v!="object"&&typeof v!="function")&&(v={});b<w;++b)if(u=arguments[b],u!=null)for(d in u)c=o(v,d),h=o(u,d),v!==h&&(_&&h&&(i(h)||(f=a(h)))?(f?(f=!1,g=c&&a(c)?c:[]):g=c&&i(c)?c:{},s(v,{name:d,newValue:l(_,g,h)})):typeof h!="undefined"&&s(v,{name:d,newValue:h}));return v},La}var rb=tb();const Da=Lr(rb);function Oa(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function nb(){const e=[],t={run:r,use:n};return t;function r(...a){let i=-1;const s=a.pop();if(typeof s!="function")throw new TypeError("Expected function as last argument, not "+s);o(null,...a);function o(l,...u){const d=e[++i];let c=-1;if(l){s(l);return}for(;++c<a.length;)(u[c]===null||u[c]===void 0)&&(u[c]=a[c]);a=u,d?ab(d,o)(...u):s(null,...u)}}function n(a){if(typeof a!="function")throw new TypeError("Expected `middelware` to be a function, not "+a);return e.push(a),t}}function ab(e,t){let r;return n;function n(...s){const o=e.length>s.length;let l;o&&s.push(a);try{l=e.apply(this,s)}catch(u){const d=u;if(o&&r)throw d;return a(d)}o||(l&&l.then&&typeof l.then=="function"?l.then(i,a):l instanceof Error?a(l):i(l))}function a(s,...o){r||(r=!0,t(s,...o))}function i(s){a(null,s)}}const ut={basename:ib,dirname:sb,extname:ob,join:lb,sep:"/"};function ib(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Cr(e);let r=0,n=-1,a=e.length,i;if(t===void 0||t.length===0||t.length>e.length){for(;a--;)if(e.codePointAt(a)===47){if(i){r=a+1;break}}else n<0&&(i=!0,n=a+1);return n<0?"":e.slice(r,n)}if(t===e)return"";let s=-1,o=t.length-1;for(;a--;)if(e.codePointAt(a)===47){if(i){r=a+1;break}}else s<0&&(i=!0,s=a+1),o>-1&&(e.codePointAt(a)===t.codePointAt(o--)?o<0&&(n=a):(o=-1,n=s));return r===n?n=s:n<0&&(n=e.length),e.slice(r,n)}function sb(e){if(Cr(e),e.length===0)return".";let t=-1,r=e.length,n;for(;--r;)if(e.codePointAt(r)===47){if(n){t=r;break}}else n||(n=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function ob(e){Cr(e);let t=e.length,r=-1,n=0,a=-1,i=0,s;for(;t--;){const o=e.codePointAt(t);if(o===47){if(s){n=t+1;break}continue}r<0&&(s=!0,r=t+1),o===46?a<0?a=t:i!==1&&(i=1):a>-1&&(i=-1)}return a<0||r<0||i===0||i===1&&a===r-1&&a===n+1?"":e.slice(a,r)}function lb(...e){let t=-1,r;for(;++t<e.length;)Cr(e[t]),e[t]&&(r=r===void 0?e[t]:r+"/"+e[t]);return r===void 0?".":ub(r)}function ub(e){Cr(e);const t=e.codePointAt(0)===47;let r=cb(e,!t);return r.length===0&&!t&&(r="."),r.length>0&&e.codePointAt(e.length-1)===47&&(r+="/"),t?"/"+r:r}function cb(e,t){let r="",n=0,a=-1,i=0,s=-1,o,l;for(;++s<=e.length;){if(s<e.length)o=e.codePointAt(s);else{if(o===47)break;o=47}if(o===47){if(!(a===s-1||i===1))if(a!==s-1&&i===2){if(r.length<2||n!==2||r.codePointAt(r.length-1)!==46||r.codePointAt(r.length-2)!==46){if(r.length>2){if(l=r.lastIndexOf("/"),l!==r.length-1){l<0?(r="",n=0):(r=r.slice(0,l),n=r.length-1-r.lastIndexOf("/")),a=s,i=0;continue}}else if(r.length>0){r="",n=0,a=s,i=0;continue}}t&&(r=r.length>0?r+"/..":"..",n=2)}else r.length>0?r+="/"+e.slice(a+1,s):r=e.slice(a+1,s),n=s-a-1;a=s,i=0}else o===46&&i>-1?i++:i=-1}return r}function Cr(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const db={cwd:hb};function hb(){return"/"}function Fa(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function fb(e){if(typeof e=="string")e=new URL(e);else if(!Fa(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return pb(e)}function pb(e){if(e.hostname!==""){const n=new TypeError('File URL host must be "localhost" or empty on darwin');throw n.code="ERR_INVALID_FILE_URL_HOST",n}const t=e.pathname;let r=-1;for(;++r<t.length;)if(t.codePointAt(r)===37&&t.codePointAt(r+1)===50){const n=t.codePointAt(r+2);if(n===70||n===102){const a=new TypeError("File URL path must not include encoded / characters");throw a.code="ERR_INVALID_FILE_URL_PATH",a}}return decodeURIComponent(t)}const Ba=["history","path","basename","stem","extname","dirname"];class Ml{constructor(t){let r;t?Fa(t)?r={path:t}:typeof t=="string"||mb(t)?r={value:t}:r=t:r={},this.cwd="cwd"in r?"":db.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let n=-1;for(;++n<Ba.length;){const i=Ba[n];i in r&&r[i]!==void 0&&r[i]!==null&&(this[i]=i==="history"?[...r[i]]:r[i])}let a;for(a in r)Ba.includes(a)||(this[a]=r[a])}get basename(){return typeof this.path=="string"?ut.basename(this.path):void 0}set basename(t){Ra(t,"basename"),za(t,"basename"),this.path=ut.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?ut.dirname(this.path):void 0}set dirname(t){Pl(this.basename,"dirname"),this.path=ut.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?ut.extname(this.path):void 0}set extname(t){if(za(t,"extname"),Pl(this.dirname,"extname"),t){if(t.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(t.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=ut.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){Fa(t)&&(t=fb(t)),Ra(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?ut.basename(this.path,this.extname):void 0}set stem(t){Ra(t,"stem"),za(t,"stem"),this.path=ut.join(this.dirname||"",t+(this.extname||""))}fail(t,r,n){const a=this.message(t,r,n);throw a.fatal=!0,a}info(t,r,n){const a=this.message(t,r,n);return a.fatal=void 0,a}message(t,r,n){const a=new Me(t,r,n);return this.path&&(a.name=this.path+":"+a.name,a.file=this.path),a.fatal=!1,this.messages.push(a),a}toString(t){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(t||void 0).decode(this.value)}}function za(e,t){if(e&&e.includes(ut.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+ut.sep+"`")}function Ra(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function Pl(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function mb(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const gb=(function(e){const n=this.constructor.prototype,a=n[e],i=function(){return a.apply(i,arguments)};return Object.setPrototypeOf(i,n),i}),yb={}.hasOwnProperty;class ja extends gb{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=nb()}copy(){const t=new ja;let r=-1;for(;++r<this.attachers.length;){const n=this.attachers[r];t.use(...n)}return t.data(Da(!0,{},this.namespace)),t}data(t,r){return typeof t=="string"?arguments.length===2?(Ha("data",this.frozen),this.namespace[t]=r,this):yb.call(this.namespace,t)&&this.namespace[t]||void 0:t?(Ha("data",this.frozen),this.namespace=t,this):this.namespace}freeze(){if(this.frozen)return this;const t=this;for(;++this.freezeIndex<this.attachers.length;){const[r,...n]=this.attachers[this.freezeIndex];if(n[0]===!1)continue;n[0]===!0&&(n[0]=void 0);const a=r.call(t,...n);typeof a=="function"&&this.transformers.use(a)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(t){this.freeze();const r=mn(t),n=this.parser||this.Parser;return $a("parse",n),n(String(r),r)}process(t,r){const n=this;return this.freeze(),$a("process",this.parser||this.Parser),Ua("process",this.compiler||this.Compiler),r?a(void 0,r):new Promise(a);function a(i,s){const o=mn(t),l=n.parse(o);n.run(l,o,function(d,c,h){if(d||!c||!h)return u(d);const f=c,g=n.stringify(f,h);xb(g)?h.value=g:h.result=g,u(d,h)});function u(d,c){d||!c?s(d):i?i(c):r(void 0,c)}}}processSync(t){let r=!1,n;return this.freeze(),$a("processSync",this.parser||this.Parser),Ua("processSync",this.compiler||this.Compiler),this.process(t,a),Ll("processSync","process",r),n;function a(i,s){r=!0,El(i),n=s}}run(t,r,n){Nl(t),this.freeze();const a=this.transformers;return!n&&typeof r=="function"&&(n=r,r=void 0),n?i(void 0,n):new Promise(i);function i(s,o){const l=mn(r);a.run(t,l,u);function u(d,c,h){const f=c||t;d?o(d):s?s(f):n(void 0,f,h)}}}runSync(t,r){let n=!1,a;return this.run(t,r,i),Ll("runSync","run",n),a;function i(s,o){El(s),a=o,n=!0}}stringify(t,r){this.freeze();const n=mn(r),a=this.compiler||this.Compiler;return Ua("stringify",a),Nl(t),a(t,n)}use(t,...r){const n=this.attachers,a=this.namespace;if(Ha("use",this.frozen),t!=null)if(typeof t=="function")l(t,r);else if(typeof t=="object")Array.isArray(t)?o(t):s(t);else throw new TypeError("Expected usable value, not `"+t+"`");return this;function i(u){if(typeof u=="function")l(u,[]);else if(typeof u=="object")if(Array.isArray(u)){const[d,...c]=u;l(d,c)}else s(u);else throw new TypeError("Expected usable value, not `"+u+"`")}function s(u){if(!("plugins"in u)&&!("settings"in u))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");o(u.plugins),u.settings&&(a.settings=Da(!0,a.settings,u.settings))}function o(u){let d=-1;if(u!=null)if(Array.isArray(u))for(;++d<u.length;){const c=u[d];i(c)}else throw new TypeError("Expected a list of plugins, not `"+u+"`")}function l(u,d){let c=-1,h=-1;for(;++c<n.length;)if(n[c][0]===u){h=c;break}if(h===-1)n.push([u,...d]);else if(d.length>0){let[f,...g]=d;const v=n[h][1];Oa(v)&&Oa(f)&&(f=Da(!0,v,f)),n[h]=[u,f,...g]}}}}const bb=new ja().freeze();function $a(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Ua(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Ha(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Nl(e){if(!Oa(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Ll(e,t,r){if(!r)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function mn(e){return wb(e)?e:new Ml(e)}function wb(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function xb(e){return typeof e=="string"||vb(e)}function vb(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const kb="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Dl=[],Ol={allowDangerousHtml:!0},Sb=/^(https?|ircs?|mailto|xmpp)$/i,_b=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function Tb(e){const t=Cb(e),r=Ib(e);return Eb(t.runSync(t.parse(r),r),e)}function Cb(e){const t=e.rehypePlugins||Dl,r=e.remarkPlugins||Dl,n=e.remarkRehypeOptions?m(m({},e.remarkRehypeOptions),Ol):Ol;return bb().use(sy).use(r).use(eb,n).use(t)}function Ib(e){const t=e.children||"",r=new Ml;return typeof t=="string"&&(r.value=t),r}function Eb(e,t){const r=t.allowedElements,n=t.allowElement,a=t.components,i=t.disallowedElements,s=t.skipHtml,o=t.unwrapDisallowed,l=t.urlTransform||Ab;for(const d of _b)Object.hasOwn(t,d.from)&&(""+d.from+(d.to?"use `"+d.to+"` instead":"remove it")+kb+d.id,void 0);return Pa(e,u),Qp(e,{Fragment:p.Fragment,components:a,ignoreInvalidStyle:!0,jsx:p.jsx,jsxs:p.jsxs,passKeys:!0,passNode:!0});function u(d,c,h){if(d.type==="raw"&&h&&typeof c=="number")return s?h.children.splice(c,1):h.children[c]={type:"text",value:d.value},c;if(d.type==="element"){let f;for(f in ba)if(Object.hasOwn(ba,f)&&Object.hasOwn(d.properties,f)){const g=d.properties[f],v=ba[f];(v===null||v.includes(d.tagName))&&(d.properties[f]=l(String(g||""),f,d))}}if(d.type==="element"){let f=r?!r.includes(d.tagName):i?i.includes(d.tagName):!1;if(!f&&n&&typeof c=="number"&&(f=!n(d,c,h)),f&&h&&typeof c=="number")return o&&d.children?h.children.splice(c,1,...d.children):h.children.splice(c,1),c}}}function Ab(e){const t=e.indexOf(":"),r=e.indexOf("?"),n=e.indexOf("#"),a=e.indexOf("/");return t===-1||a!==-1&&t>a||r!==-1&&t>r||n!==-1&&t>n||Sb.test(e.slice(0,t))?e:""}var Mb=(e,t)=>typeof e=="string"?e===t:JSON.stringify(e)===JSON.stringify(t),Pb=(e,t)=>{if(!e||!t)return!1;const r=n=>{const o=n||{},{position:a,data:i}=o;return V(o,["position","data"])};return JSON.stringify(r(e.properties))===JSON.stringify(r(t.properties))&&Mb(e.children,t.children)},qa=(e,t)=>Pb(e.node,t.node),Nb=(e={})=>Object.fromEntries(Object.entries(e!=null?e:{}).map(([t,r])=>{if(!r)return[t,r];const n=r,a=o=>{var l=o,{node:i}=l,s=V(l,["node"]);return p.jsx(n,m({},s))};return[t,y.memo(a,qa)]})),Va=y.createContext(null),Fl=()=>y.useContext(Va)!==null,Lb=r=>{var n=r,{children:e}=n,t=V(n,["children"]);return p.jsx(Va.Provider,{value:t,children:e})},Db=y.memo(Lb,qa),Ob=r=>{var n=r,{node:e}=n,t=V(n,["node"]);return p.jsx("pre",m({},t))},Fb=r=>{var n=r,{node:e}=n,t=V(n,["node"]);return p.jsx("code",m({},t))},Wa=({node:e,components:{Pre:t,Code:r},code:n})=>p.jsx(t,{children:p.jsx(r,{node:e,children:n})}),Bb=()=>null,zb=({node:e,components:{Pre:t,Code:r,SyntaxHighlighter:n,CodeHeader:a},language:i,code:s})=>{const o=y.useMemo(()=>({Pre:t,Code:r}),[t,r]),l=i?n:Wa;return p.jsxs(p.Fragment,{children:[p.jsx(a,{node:e,language:i,code:s}),p.jsx(l,{node:e,components:o,language:i!=null?i:"unknown",code:s})]})},Ja={exports:{}};var Bl;function Rb(){return Bl||(Bl=1,(function(e){(function(){var t={}.hasOwnProperty;function r(){for(var i="",s=0;s<arguments.length;s++){var o=arguments[s];o&&(i=a(i,n(o)))}return i}function n(i){if(typeof i=="string"||typeof i=="number")return i;if(typeof i!="object")return"";if(Array.isArray(i))return r.apply(null,i);if(i.toString!==Object.prototype.toString&&!i.toString.toString().includes("[native code]"))return i.toString();var s="";for(var o in i)t.call(i,o)&&i[o]&&(s=a(s,o));return s}function a(i,s){return s?i?i+" "+s:i+s:i}e.exports?(r.default=r,e.exports=r):window.classNames=r})()})(Ja)),Ja.exports}var jb=Rb();const zl=Lr(jb);var Rl=r=>{var n=r,{className:e}=n,t=V(n,["className"]);return s=>{var o=s,{className:a}=o,i=V(o,["className"]);return m(m({className:zl(e,a)},t),i)}},$b=l=>{var u=l,{node:e,components:{Pre:t,Code:r,SyntaxHighlighter:n,CodeHeader:a},componentsByLanguage:i={},children:s}=u,o=V(u,["node","components","componentsByLanguage","children"]);var _,T,B,j,I,z;const d=y.useContext(Va),c=Rl(d),h=At(H=>p.jsx(t,m({},c(H)))),f=Rl(o),g=At(H=>p.jsx(r,m({},f(H)))),v=(T=(_=/language-(\w+)/.exec(o.className||""))==null?void 0:_[1])!=null?T:"";if(typeof s!="string")return p.jsx(Wa,{node:e,components:{Pre:h,Code:g},code:s});const b=(j=(B=i[v])==null?void 0:B.SyntaxHighlighter)!=null?j:n,w=(z=(I=i[v])==null?void 0:I.CodeHeader)!=null?z:a;return p.jsx(zb,{node:e,components:{Pre:h,Code:g,SyntaxHighlighter:b,CodeHeader:w},language:v||"unknown",code:s})},Ub=a=>{var i=a,{node:e,components:t,componentsByLanguage:r}=i,n=V(i,["node","components","componentsByLanguage"]);return Fl()?p.jsx($b,m({node:e,components:t,componentsByLanguage:r},n)):p.jsx(t.Code,m({},n))},Hb=y.memo(Ub,(e,t)=>e.components===t.components&&e.componentsByLanguage===t.componentsByLanguage&&qa(e,t)),{useSmooth:qb,useSmoothStatus:Vb,withSmoothContextProvider:Wb}=Kh,Jb=i=>{var s=i,{components:e,componentsByLanguage:t,smooth:r=!0,preprocess:n}=s,a=V(s,["components","componentsByLanguage","smooth","preprocess"]);const o=Ls(),l=y.useMemo(()=>n?E(m({},o),{text:n(o.text)}):o,[o,n]),{text:u}=qb(l,r),{pre:d=Ob,code:c=Fb,SyntaxHighlighter:h=Wa,CodeHeader:f=Bb}=e!=null?e:{},g=y.useMemo(()=>({Pre:d,Code:c,SyntaxHighlighter:h,CodeHeader:f}),[d,c,h,f]),v=At(w=>p.jsx(Hb,m({components:g,componentsByLanguage:t},w))),b=y.useMemo(()=>{const I=e!=null?e:{},{pre:w,code:_,SyntaxHighlighter:T,CodeHeader:B}=I,j=V(I,["pre","code","SyntaxHighlighter","CodeHeader"]);return E(m({},j),{pre:Db,code:v})},[v,e]);return p.jsx(Tb,E(m({components:b},a),{children:u}))},jl=y.forwardRef((i,a)=>{var s=i,{className:e,containerProps:t,containerComponent:r="div"}=s,n=V(s,["className","containerProps","containerComponent"]);const o=Vb();return p.jsx(r,E(m({"data-status":o.type},t),{className:zl(e,t==null?void 0:t.className),ref:a,children:p.jsx(Jb,m({},n))}))});jl.displayName="MarkdownTextPrimitive";var Yb=Wb(jl);function $l(e,t){const r=String(e);if(typeof t!="string")throw new TypeError("Expected character");let n=0,a=r.indexOf(t);for(;a!==-1;)n++,a=r.indexOf(t,a+t.length);return n}function Kb(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function Gb(e,t,r){const a=fn((r||{}).ignore||[]),i=Xb(t);let s=-1;for(;++s<i.length;)Tl(e,"text",o);function o(u,d){let c=-1,h;for(;++c<d.length;){const f=d[c],g=h?h.children:void 0;if(a(f,g?g.indexOf(f):void 0,h))return;h=f}if(h)return l(u,d)}function l(u,d){const c=d[d.length-1],h=i[s][0],f=i[s][1];let g=0;const b=c.children.indexOf(u);let w=!1,_=[];h.lastIndex=0;let T=h.exec(u.value);for(;T;){const B=T.index,j={index:T.index,input:T.input,stack:[...d,u]};let I=f(...T,j);if(typeof I=="string"&&(I=I.length>0?{type:"text",value:I}:void 0),I===!1?h.lastIndex=B+1:(g!==B&&_.push({type:"text",value:u.value.slice(g,B)}),Array.isArray(I)?_.push(...I):I&&_.push(I),g=B+T[0].length,w=!0),!h.global)break;T=h.exec(u.value)}return w?(g<u.value.length&&_.push({type:"text",value:u.value.slice(g)}),c.children.splice(b,1,..._)):_=[u],b+_.length}}function Xb(e){const t=[];if(!Array.isArray(e))throw new TypeError("Expected find and replace tuple or list of tuples");const r=!e[0]||Array.isArray(e[0])?e:[e];let n=-1;for(;++n<r.length;){const a=r[n];t.push([Qb(a[0]),Zb(a[1])])}return t}function Qb(e){return typeof e=="string"?new RegExp(Kb(e),"g"):e}function Zb(e){return typeof e=="function"?e:function(){return e}}const Ya="phrasing",Ka=["autolink","link","image","label"];function ew(){return{transforms:[ow],enter:{literalAutolink:rw,literalAutolinkEmail:Ga,literalAutolinkHttp:Ga,literalAutolinkWww:Ga},exit:{literalAutolink:sw,literalAutolinkEmail:iw,literalAutolinkHttp:nw,literalAutolinkWww:aw}}}function tw(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Ya,notInConstruct:Ka},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Ya,notInConstruct:Ka},{character:":",before:"[ps]",after:"\\/",inConstruct:Ya,notInConstruct:Ka}]}}function rw(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function Ga(e){this.config.enter.autolinkProtocol.call(this,e)}function nw(e){this.config.exit.autolinkProtocol.call(this,e)}function aw(e){this.config.exit.data.call(this,e);const t=this.stack[this.stack.length-1];t.type,t.url="http://"+this.sliceSerialize(e)}function iw(e){this.config.exit.autolinkEmail.call(this,e)}function sw(e){this.exit(e)}function ow(e){Gb(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,lw],[new RegExp("(?<=^|\\s|\\p{P}|\\p{S})([-.\\w+]+)@([-\\w]+(?:\\.[-\\w]+)+)","gu"),uw]],{ignore:["link","linkReference"]})}function lw(e,t,r,n,a){let i="";if(!Ul(a)||(/^w/i.test(t)&&(r=t+r,t="",i="http://"),!cw(r)))return!1;const s=dw(r+n);if(!s[0])return!1;const o={type:"link",title:null,url:i+t+s[0],children:[{type:"text",value:t+s[0]}]};return s[1]?[o,{type:"text",value:s[1]}]:o}function uw(e,t,r,n){return!Ul(n,!0)||/[-\d_]$/.test(r)?!1:{type:"link",title:null,url:"mailto:"+t+"@"+r,children:[{type:"text",value:t+"@"+r}]}}function cw(e){const t=e.split(".");return!(t.length<2||t[t.length-1]&&(/_/.test(t[t.length-1])||!/[a-zA-Z\d]/.test(t[t.length-1]))||t[t.length-2]&&(/_/.test(t[t.length-2])||!/[a-zA-Z\d]/.test(t[t.length-2])))}function dw(e){const t=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let r=t[0],n=r.indexOf(")");const a=$l(e,"(");let i=$l(e,")");for(;n!==-1&&a>i;)e+=r.slice(0,n+1),r=r.slice(n+1),n=r.indexOf(")"),i++;return[e,r]}function Ul(e,t){const r=e.input.charCodeAt(e.index-1);return(e.index===0||Pt(r)||an(r))&&(!t||r!==47)}Hl.peek=xw;function hw(){this.buffer()}function fw(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function pw(){this.buffer()}function mw(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function gw(e){const t=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=it(this.sliceSerialize(e)).toLowerCase(),r.label=t}function yw(e){this.exit(e)}function bw(e){const t=this.resume(),r=this.stack[this.stack.length-1];r.type,r.identifier=it(this.sliceSerialize(e)).toLowerCase(),r.label=t}function ww(e){this.exit(e)}function xw(){return"["}function Hl(e,t,r,n){const a=r.createTracker(n);let i=a.move("[^");const s=r.enter("footnoteReference"),o=r.enter("reference");return i+=a.move(r.safe(r.associationId(e),{after:"]",before:i})),o(),s(),i+=a.move("]"),i}function vw(){return{enter:{gfmFootnoteCallString:hw,gfmFootnoteCall:fw,gfmFootnoteDefinitionLabelString:pw,gfmFootnoteDefinition:mw},exit:{gfmFootnoteCallString:gw,gfmFootnoteCall:yw,gfmFootnoteDefinitionLabelString:bw,gfmFootnoteDefinition:ww}}}function kw(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:r,footnoteReference:Hl},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function r(n,a,i,s){const o=i.createTracker(s);let l=o.move("[^");const u=i.enter("footnoteDefinition"),d=i.enter("label");return l+=o.move(i.safe(i.associationId(n),{before:l,after:"]"})),d(),l+=o.move("]:"),n.children&&n.children.length>0&&(o.shift(4),l+=o.move((t?`
21
+ `:" ")+i.indentLines(i.containerFlow(n,o.current()),t?ql:Sw))),u(),l}}function Sw(e,t,r){return t===0?e:ql(e,t,r)}function ql(e,t,r){return(r?"":" ")+e}const _w=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Vl.peek=Aw;function Tw(){return{canContainEols:["delete"],enter:{strikethrough:Iw},exit:{strikethrough:Ew}}}function Cw(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:_w}],handlers:{delete:Vl}}}function Iw(e){this.enter({type:"delete",children:[]},e)}function Ew(e){this.exit(e)}function Vl(e,t,r,n){const a=r.createTracker(n),i=r.enter("strikethrough");let s=a.move("~~");return s+=r.containerPhrasing(e,E(m({},a.current()),{before:s,after:"~"})),s+=a.move("~~"),i(),s}function Aw(){return"~"}function Mw(e){return e.length}function Pw(e,t){const r=t||{},n=(r.align||[]).concat(),a=r.stringLength||Mw,i=[],s=[],o=[],l=[];let u=0,d=-1;for(;++d<e.length;){const v=[],b=[];let w=-1;for(e[d].length>u&&(u=e[d].length);++w<e[d].length;){const _=Nw(e[d][w]);if(r.alignDelimiters!==!1){const T=a(_);b[w]=T,(l[w]===void 0||T>l[w])&&(l[w]=T)}v.push(_)}s[d]=v,o[d]=b}let c=-1;if(typeof n=="object"&&"length"in n)for(;++c<u;)i[c]=Wl(n[c]);else{const v=Wl(n);for(;++c<u;)i[c]=v}c=-1;const h=[],f=[];for(;++c<u;){const v=i[c];let b="",w="";v===99?(b=":",w=":"):v===108?b=":":v===114&&(w=":");let _=r.alignDelimiters===!1?1:Math.max(1,l[c]-b.length-w.length);const T=b+"-".repeat(_)+w;r.alignDelimiters!==!1&&(_=b.length+_+w.length,_>l[c]&&(l[c]=_),f[c]=_),h[c]=T}s.splice(1,0,h),o.splice(1,0,f),d=-1;const g=[];for(;++d<s.length;){const v=s[d],b=o[d];c=-1;const w=[];for(;++c<u;){const _=v[c]||"";let T="",B="";if(r.alignDelimiters!==!1){const j=l[c]-(b[c]||0),I=i[c];I===114?T=" ".repeat(j):I===99?j%2?(T=" ".repeat(j/2+.5),B=" ".repeat(j/2-.5)):(T=" ".repeat(j/2),B=T):B=" ".repeat(j)}r.delimiterStart!==!1&&!c&&w.push("|"),r.padding!==!1&&!(r.alignDelimiters===!1&&_==="")&&(r.delimiterStart!==!1||c)&&w.push(" "),r.alignDelimiters!==!1&&w.push(T),w.push(_),r.alignDelimiters!==!1&&w.push(B),r.padding!==!1&&w.push(" "),(r.delimiterEnd!==!1||c!==u-1)&&w.push("|")}g.push(r.delimiterEnd===!1?w.join("").replace(/ +$/,""):w.join(""))}return g.join(`
22
+ `)}function Nw(e){return e==null?"":String(e)}function Wl(e){const t=typeof e=="string"?e.codePointAt(0):0;return t===67||t===99?99:t===76||t===108?108:t===82||t===114?114:0}function Lw(e,t,r,n){const a=r.enter("blockquote"),i=r.createTracker(n);i.move("> "),i.shift(2);const s=r.indentLines(r.containerFlow(e,i.current()),Dw);return a(),s}function Dw(e,t,r){return">"+(r?"":" ")+e}function Ow(e,t){return Jl(e,t.inConstruct,!0)&&!Jl(e,t.notInConstruct,!1)}function Jl(e,t,r){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return r;let n=-1;for(;++n<t.length;)if(e.includes(t[n]))return!0;return!1}function Yl(e,t,r,n){let a=-1;for(;++a<r.unsafe.length;)if(r.unsafe[a].character===`
23
+ `&&Ow(r.stack,r.unsafe[a]))return/[ \t]/.test(n.before)?"":" ";return`\\
24
+ `}function Fw(e,t){const r=String(e);let n=r.indexOf(t),a=n,i=0,s=0;if(typeof t!="string")throw new TypeError("Expected substring");for(;n!==-1;)n===a?++i>s&&(s=i):i=1,a=n+t.length,n=r.indexOf(t,a);return s}function Bw(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function zw(e){const t=e.options.fence||"`";if(t!=="`"&&t!=="~")throw new Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function Rw(e,t,r,n){const a=zw(r),i=e.value||"",s=a==="`"?"GraveAccent":"Tilde";if(Bw(e,r)){const c=r.enter("codeIndented"),h=r.indentLines(i,jw);return c(),h}const o=r.createTracker(n),l=a.repeat(Math.max(Fw(i,a)+1,3)),u=r.enter("codeFenced");let d=o.move(l);if(e.lang){const c=r.enter(`codeFencedLang${s}`);d+=o.move(r.safe(e.lang,m({before:d,after:" ",encode:["`"]},o.current()))),c()}if(e.lang&&e.meta){const c=r.enter(`codeFencedMeta${s}`);d+=o.move(" "),d+=o.move(r.safe(e.meta,m({before:d,after:`
25
25
  `,encode:["`"]},o.current()))),c()}return d+=o.move(`
26
26
  `),i&&(d+=o.move(i+`
27
- `)),d+=o.move(l),u(),d}function Rw(e,t,r){return(r?"":" ")+e}function Ga(e){const t=e.options.quote||'"';if(t!=='"'&&t!=="'")throw new Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function jw(e,t,r,n){const a=Ga(r),i=a==='"'?"Quote":"Apostrophe",s=r.enter("definition");let o=r.enter("label");const l=r.createTracker(n);let u=l.move("[");return u+=l.move(r.safe(r.associationId(e),m({before:u,after:"]"},l.current()))),u+=l.move("]: "),o(),!e.url||/[\0- \u007F]/.test(e.url)?(o=r.enter("destinationLiteral"),u+=l.move("<"),u+=l.move(r.safe(e.url,m({before:u,after:">"},l.current()))),u+=l.move(">")):(o=r.enter("destinationRaw"),u+=l.move(r.safe(e.url,m({before:u,after:e.title?" ":`
28
- `},l.current())))),o(),e.title&&(o=r.enter(`title${i}`),u+=l.move(" "+a),u+=l.move(r.safe(e.title,m({before:u,after:a},l.current()))),u+=l.move(a),o()),s(),u}function $w(e){const t=e.options.emphasis||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function Cr(e){return"&#x"+e.toString(16).toUpperCase()+";"}function gn(e,t,r){const n=Kt(e),a=Kt(t);return n===void 0?a===void 0?r==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:n===1?a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}Yl.peek=Uw;function Yl(e,t,r,n){const a=$w(r),i=r.enter("emphasis"),s=r.createTracker(n),o=s.move(a);let l=s.move(r.containerPhrasing(e,m({after:a,before:o},s.current())));const u=l.charCodeAt(0),d=gn(n.before.charCodeAt(n.before.length-1),u,a);d.inside&&(l=Cr(u)+l.slice(1));const c=l.charCodeAt(l.length-1),h=gn(n.after.charCodeAt(0),c,a);h.inside&&(l=l.slice(0,-1)+Cr(c));const f=s.move(a);return i(),r.attentionEncodeSurroundingInfo={after:h.outside,before:d.outside},o+l+f}function Uw(e,t,r){return r.options.emphasis||"*"}function Hw(e,t){let r=!1;return Ma(e,function(n){if("value"in n&&/\r?\n|\r/.test(n.value)||n.type==="break")return r=!0,Aa}),!!((!e.depth||e.depth<3)&&ba(e)&&(t.options.setext||r))}function qw(e,t,r,n){const a=Math.max(Math.min(6,e.depth||1),1),i=r.createTracker(n);if(Hw(e,r)){const d=r.enter("headingSetext"),c=r.enter("phrasing"),h=r.containerPhrasing(e,E(m({},i.current()),{before:`
27
+ `)),d+=o.move(l),u(),d}function jw(e,t,r){return(r?"":" ")+e}function Xa(e){const t=e.options.quote||'"';if(t!=='"'&&t!=="'")throw new Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function $w(e,t,r,n){const a=Xa(r),i=a==='"'?"Quote":"Apostrophe",s=r.enter("definition");let o=r.enter("label");const l=r.createTracker(n);let u=l.move("[");return u+=l.move(r.safe(r.associationId(e),m({before:u,after:"]"},l.current()))),u+=l.move("]: "),o(),!e.url||/[\0- \u007F]/.test(e.url)?(o=r.enter("destinationLiteral"),u+=l.move("<"),u+=l.move(r.safe(e.url,m({before:u,after:">"},l.current()))),u+=l.move(">")):(o=r.enter("destinationRaw"),u+=l.move(r.safe(e.url,m({before:u,after:e.title?" ":`
28
+ `},l.current())))),o(),e.title&&(o=r.enter(`title${i}`),u+=l.move(" "+a),u+=l.move(r.safe(e.title,m({before:u,after:a},l.current()))),u+=l.move(a),o()),s(),u}function Uw(e){const t=e.options.emphasis||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function Ir(e){return"&#x"+e.toString(16).toUpperCase()+";"}function gn(e,t,r){const n=Kt(e),a=Kt(t);return n===void 0?a===void 0?r==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:n===1?a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}Kl.peek=Hw;function Kl(e,t,r,n){const a=Uw(r),i=r.enter("emphasis"),s=r.createTracker(n),o=s.move(a);let l=s.move(r.containerPhrasing(e,m({after:a,before:o},s.current())));const u=l.charCodeAt(0),d=gn(n.before.charCodeAt(n.before.length-1),u,a);d.inside&&(l=Ir(u)+l.slice(1));const c=l.charCodeAt(l.length-1),h=gn(n.after.charCodeAt(0),c,a);h.inside&&(l=l.slice(0,-1)+Ir(c));const f=s.move(a);return i(),r.attentionEncodeSurroundingInfo={after:h.outside,before:d.outside},o+l+f}function Hw(e,t,r){return r.options.emphasis||"*"}function qw(e,t){let r=!1;return Pa(e,function(n){if("value"in n&&/\r?\n|\r/.test(n.value)||n.type==="break")return r=!0,Ma}),!!((!e.depth||e.depth<3)&&wa(e)&&(t.options.setext||r))}function Vw(e,t,r,n){const a=Math.max(Math.min(6,e.depth||1),1),i=r.createTracker(n);if(qw(e,r)){const d=r.enter("headingSetext"),c=r.enter("phrasing"),h=r.containerPhrasing(e,E(m({},i.current()),{before:`
29
29
  `,after:`
30
30
  `}));return c(),d(),h+`
31
31
  `+(a===1?"=":"-").repeat(h.length-(Math.max(h.lastIndexOf("\r"),h.lastIndexOf(`
32
32
  `))+1))}const s="#".repeat(a),o=r.enter("headingAtx"),l=r.enter("phrasing");i.move(s+" ");let u=r.containerPhrasing(e,m({before:"# ",after:`
33
- `},i.current()));return/^[\t ]/.test(u)&&(u=Cr(u.charCodeAt(0))+u.slice(1)),u=u?s+" "+u:s,r.options.closeAtx&&(u+=" "+s),l(),o(),u}Kl.peek=Vw;function Kl(e){return e.value||""}function Vw(){return"<"}Gl.peek=Ww;function Gl(e,t,r,n){const a=Ga(r),i=a==='"'?"Quote":"Apostrophe",s=r.enter("image");let o=r.enter("label");const l=r.createTracker(n);let u=l.move("![");return u+=l.move(r.safe(e.alt,m({before:u,after:"]"},l.current()))),u+=l.move("]("),o(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(o=r.enter("destinationLiteral"),u+=l.move("<"),u+=l.move(r.safe(e.url,m({before:u,after:">"},l.current()))),u+=l.move(">")):(o=r.enter("destinationRaw"),u+=l.move(r.safe(e.url,m({before:u,after:e.title?" ":")"},l.current())))),o(),e.title&&(o=r.enter(`title${i}`),u+=l.move(" "+a),u+=l.move(r.safe(e.title,m({before:u,after:a},l.current()))),u+=l.move(a),o()),u+=l.move(")"),s(),u}function Ww(){return"!"}Xl.peek=Jw;function Xl(e,t,r,n){const a=e.referenceType,i=r.enter("imageReference");let s=r.enter("label");const o=r.createTracker(n);let l=o.move("![");const u=r.safe(e.alt,m({before:l,after:"]"},o.current()));l+=o.move(u+"]["),s();const d=r.stack;r.stack=[],s=r.enter("reference");const c=r.safe(r.associationId(e),m({before:l,after:"]"},o.current()));return s(),r.stack=d,i(),a==="full"||!u||u!==c?l+=o.move(c+"]"):a==="shortcut"?l=l.slice(0,-1):l+=o.move("]"),l}function Jw(){return"!"}Ql.peek=Yw;function Ql(e,t,r){let n=e.value||"",a="`",i=-1;for(;new RegExp("(^|[^`])"+a+"([^`]|$)").test(n);)a+="`";for(/[^ \r\n]/.test(n)&&(/^[ \r\n]/.test(n)&&/[ \r\n]$/.test(n)||/^`|`$/.test(n))&&(n=" "+n+" ");++i<r.unsafe.length;){const s=r.unsafe[i],o=r.compilePattern(s);let l;if(s.atBreak)for(;l=o.exec(n);){let u=l.index;n.charCodeAt(u)===10&&n.charCodeAt(u-1)===13&&u--,n=n.slice(0,u)+" "+n.slice(l.index+1)}}return a+n+a}function Yw(){return"`"}function Zl(e,t){const r=ba(e);return!!(!t.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type==="text"&&(r===e.url||"mailto:"+r===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}eu.peek=Kw;function eu(e,t,r,n){const a=Ga(r),i=a==='"'?"Quote":"Apostrophe",s=r.createTracker(n);let o,l;if(Zl(e,r)){const d=r.stack;r.stack=[],o=r.enter("autolink");let c=s.move("<");return c+=s.move(r.containerPhrasing(e,m({before:c,after:">"},s.current()))),c+=s.move(">"),o(),r.stack=d,c}o=r.enter("link"),l=r.enter("label");let u=s.move("[");return u+=s.move(r.containerPhrasing(e,m({before:u,after:"]("},s.current()))),u+=s.move("]("),l(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(l=r.enter("destinationLiteral"),u+=s.move("<"),u+=s.move(r.safe(e.url,m({before:u,after:">"},s.current()))),u+=s.move(">")):(l=r.enter("destinationRaw"),u+=s.move(r.safe(e.url,m({before:u,after:e.title?" ":")"},s.current())))),l(),e.title&&(l=r.enter(`title${i}`),u+=s.move(" "+a),u+=s.move(r.safe(e.title,m({before:u,after:a},s.current()))),u+=s.move(a),l()),u+=s.move(")"),o(),u}function Kw(e,t,r){return Zl(e,r)?"<":"["}tu.peek=Gw;function tu(e,t,r,n){const a=e.referenceType,i=r.enter("linkReference");let s=r.enter("label");const o=r.createTracker(n);let l=o.move("[");const u=r.containerPhrasing(e,m({before:l,after:"]"},o.current()));l+=o.move(u+"]["),s();const d=r.stack;r.stack=[],s=r.enter("reference");const c=r.safe(r.associationId(e),m({before:l,after:"]"},o.current()));return s(),r.stack=d,i(),a==="full"||!u||u!==c?l+=o.move(c+"]"):a==="shortcut"?l=l.slice(0,-1):l+=o.move("]"),l}function Gw(){return"["}function Xa(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function Xw(e){const t=Xa(e),r=e.options.bulletOther;if(!r)return t==="*"?"-":"*";if(r!=="*"&&r!=="+"&&r!=="-")throw new Error("Cannot serialize items with `"+r+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(r===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+r+"`) to be different");return r}function Qw(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function ru(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function Zw(e,t,r,n){const a=r.enter("list"),i=r.bulletCurrent;let s=e.ordered?Qw(r):Xa(r);const o=e.ordered?s==="."?")":".":Xw(r);let l=t&&r.bulletLastUsed?s===r.bulletLastUsed:!1;if(!e.ordered){const d=e.children?e.children[0]:void 0;if((s==="*"||s==="-")&&d&&(!d.children||!d.children[0])&&r.stack[r.stack.length-1]==="list"&&r.stack[r.stack.length-2]==="listItem"&&r.stack[r.stack.length-3]==="list"&&r.stack[r.stack.length-4]==="listItem"&&r.indexStack[r.indexStack.length-1]===0&&r.indexStack[r.indexStack.length-2]===0&&r.indexStack[r.indexStack.length-3]===0&&(l=!0),ru(r)===s&&d){let c=-1;for(;++c<e.children.length;){const h=e.children[c];if(h&&h.type==="listItem"&&h.children&&h.children[0]&&h.children[0].type==="thematicBreak"){l=!0;break}}}}l&&(s=o),r.bulletCurrent=s;const u=r.containerFlow(e,n);return r.bulletLastUsed=s,r.bulletCurrent=i,a(),u}function ex(e){const t=e.options.listItemIndent||"one";if(t!=="tab"&&t!=="one"&&t!=="mixed")throw new Error("Cannot serialize items with `"+t+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return t}function tx(e,t,r,n){const a=ex(r);let i=r.bulletCurrent||Xa(r);t&&t.type==="list"&&t.ordered&&(i=(typeof t.start=="number"&&t.start>-1?t.start:1)+(r.options.incrementListMarker===!1?0:t.children.indexOf(e))+i);let s=i.length+1;(a==="tab"||a==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(s=Math.ceil(s/4)*4);const o=r.createTracker(n);o.move(i+" ".repeat(s-i.length)),o.shift(s);const l=r.enter("listItem"),u=r.indentLines(r.containerFlow(e,o.current()),d);return l(),u;function d(c,h,f){return h?(f?"":" ".repeat(s))+c:(f?i:i+" ".repeat(s-i.length))+c}}function rx(e,t,r,n){const a=r.enter("paragraph"),i=r.enter("phrasing"),s=r.containerPhrasing(e,n);return i(),a(),s}const nx=fn(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function ax(e,t,r,n){return(e.children.some(function(s){return nx(s)})?r.containerPhrasing:r.containerFlow).call(r,e,n)}function ix(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}nu.peek=sx;function nu(e,t,r,n){const a=ix(r),i=r.enter("strong"),s=r.createTracker(n),o=s.move(a+a);let l=s.move(r.containerPhrasing(e,m({after:a,before:o},s.current())));const u=l.charCodeAt(0),d=gn(n.before.charCodeAt(n.before.length-1),u,a);d.inside&&(l=Cr(u)+l.slice(1));const c=l.charCodeAt(l.length-1),h=gn(n.after.charCodeAt(0),c,a);h.inside&&(l=l.slice(0,-1)+Cr(c));const f=s.move(a+a);return i(),r.attentionEncodeSurroundingInfo={after:h.outside,before:d.outside},o+l+f}function sx(e,t,r){return r.options.strong||"*"}function ox(e,t,r,n){return r.safe(e.value,n)}function lx(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function ux(e,t,r){const n=(ru(r)+(r.options.ruleSpaces?" ":"")).repeat(lx(r));return r.options.ruleSpaces?n.slice(0,-1):n}const au={blockquote:Nw,break:Jl,code:zw,definition:jw,emphasis:Yl,hardBreak:Jl,heading:qw,html:Kl,image:Gl,imageReference:Xl,inlineCode:Ql,link:eu,linkReference:tu,list:Zw,listItem:tx,paragraph:rx,root:ax,strong:nu,text:ox,thematicBreak:ux};function cx(){return{enter:{table:dx,tableData:iu,tableHeader:iu,tableRow:fx},exit:{codeText:px,table:hx,tableData:Qa,tableHeader:Qa,tableRow:Qa}}}function dx(e){const t=e._align;this.enter({type:"table",align:t.map(function(r){return r==="none"?null:r}),children:[]},e),this.data.inTable=!0}function hx(e){this.exit(e),this.data.inTable=void 0}function fx(e){this.enter({type:"tableRow",children:[]},e)}function Qa(e){this.exit(e)}function iu(e){this.enter({type:"tableCell",children:[]},e)}function px(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,mx));const r=this.stack[this.stack.length-1];r.type,r.value=t,this.exit(e)}function mx(e,t){return t==="|"?t:e}function gx(e){const t=e||{},r=t.tableCellPadding,n=t.tablePipeAlign,a=t.stringLength,i=r?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
34
- `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:h,table:s,tableCell:l,tableRow:o}};function s(f,g,v,b){return u(d(f,v,b),f.align)}function o(f,g,v,b){const w=c(f,v,b),T=u([w]);return T.slice(0,T.indexOf(`
35
- `))}function l(f,g,v,b){const w=v.enter("tableCell"),T=v.enter("phrasing"),_=v.containerPhrasing(f,E(m({},b),{before:i,after:i}));return T(),w(),_}function u(f,g){return Mw(f,{align:g,alignDelimiters:n,padding:r,stringLength:a})}function d(f,g,v){const b=f.children;let w=-1;const T=[],_=g.enter("table");for(;++w<b.length;)T[w]=c(b[w],g,v);return _(),T}function c(f,g,v){const b=f.children;let w=-1;const T=[],_=g.enter("tableRow");for(;++w<b.length;)T[w]=l(b[w],f,g,v);return _(),T}function h(f,g,v){let b=au.inlineCode(f,g,v);return v.stack.includes("tableCell")&&(b=b.replace(/\|/g,"\\$&")),b}}function yx(){return{exit:{taskListCheckValueChecked:su,taskListCheckValueUnchecked:su,paragraph:wx}}}function bx(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:xx}}}function su(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function wx(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const r=this.stack[this.stack.length-1];r.type;const n=r.children[0];if(n&&n.type==="text"){const a=t.children;let i=-1,s;for(;++i<a.length;){const o=a[i];if(o.type==="paragraph"){s=o;break}}s===r&&(n.value=n.value.slice(1),n.value.length===0?r.children.shift():r.position&&n.position&&typeof n.position.start.offset=="number"&&(n.position.start.column++,n.position.start.offset++,r.position.start=Object.assign({},n.position.start)))}}this.exit(e)}function xx(e,t,r,n){const a=e.children[0],i=typeof e.checked=="boolean"&&a&&a.type==="paragraph",s="["+(e.checked?"x":" ")+"] ",o=r.createTracker(n);i&&o.move(s);let l=au.listItem(e,t,r,m(m({},n),o.current()));return i&&(l=l.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,u)),l;function u(d){return d+s}}function vx(){return[Zb(),xw(),_w(),cx(),yx()]}function kx(e){return{extensions:[ew(),vw(e),Tw(),gx(e),bx()]}}const Sx={tokenize:Ax,partial:!0},ou={tokenize:Mx,partial:!0},lu={tokenize:Px,partial:!0},uu={tokenize:Nx,partial:!0},_x={tokenize:Lx,partial:!0},cu={name:"wwwAutolink",tokenize:Ix,previous:hu},du={name:"protocolAutolink",tokenize:Ex,previous:fu},pt={name:"emailAutolink",tokenize:Cx,previous:pu},ct={};function Tx(){return{text:ct}}let Nt=48;for(;Nt<123;)ct[Nt]=pt,Nt++,Nt===58?Nt=65:Nt===91&&(Nt=97);ct[43]=pt,ct[45]=pt,ct[46]=pt,ct[95]=pt,ct[72]=[pt,du],ct[104]=[pt,du],ct[87]=[pt,cu],ct[119]=[pt,cu];function Cx(e,t,r){const n=this;let a,i;return s;function s(c){return!Za(c)||!pu.call(n,n.previous)||ei(n.events)?r(c):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),o(c))}function o(c){return Za(c)?(e.consume(c),o):c===64?(e.consume(c),l):r(c)}function l(c){return c===46?e.check(_x,d,u)(c):c===45||c===95||Ae(c)?(i=!0,e.consume(c),l):d(c)}function u(c){return e.consume(c),a=!0,l}function d(c){return i&&a&&Be(n.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(c)):r(c)}}function Ix(e,t,r){const n=this;return a;function a(s){return s!==87&&s!==119||!hu.call(n,n.previous)||ei(n.events)?r(s):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(Sx,e.attempt(ou,e.attempt(lu,i),r),r)(s))}function i(s){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(s)}}function Ex(e,t,r){const n=this;let a="",i=!1;return s;function s(c){return(c===72||c===104)&&fu.call(n,n.previous)&&!ei(n.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),a+=String.fromCodePoint(c),e.consume(c),o):r(c)}function o(c){if(Be(c)&&a.length<5)return a+=String.fromCodePoint(c),e.consume(c),o;if(c===58){const h=a.toLowerCase();if(h==="http"||h==="https")return e.consume(c),l}return r(c)}function l(c){return c===47?(e.consume(c),i?u:(i=!0,l)):r(c)}function u(c){return c===null||nn(c)||le(c)||Pt(c)||an(c)?r(c):e.attempt(ou,e.attempt(lu,d),r)(c)}function d(c){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(c)}}function Ax(e,t,r){let n=0;return a;function a(s){return(s===87||s===119)&&n<3?(n++,e.consume(s),a):s===46&&n===3?(e.consume(s),i):r(s)}function i(s){return s===null?r(s):t(s)}}function Mx(e,t,r){let n,a,i;return s;function s(u){return u===46||u===95?e.check(uu,l,o)(u):u===null||le(u)||Pt(u)||u!==45&&an(u)?l(u):(i=!0,e.consume(u),s)}function o(u){return u===95?n=!0:(a=n,n=void 0),e.consume(u),s}function l(u){return a||n||!i?r(u):t(u)}}function Px(e,t){let r=0,n=0;return a;function a(s){return s===40?(r++,e.consume(s),a):s===41&&n<r?i(s):s===33||s===34||s===38||s===39||s===41||s===42||s===44||s===46||s===58||s===59||s===60||s===63||s===93||s===95||s===126?e.check(uu,t,i)(s):s===null||le(s)||Pt(s)?t(s):(e.consume(s),a)}function i(s){return s===41&&n++,e.consume(s),a}}function Nx(e,t,r){return n;function n(o){return o===33||o===34||o===39||o===41||o===42||o===44||o===46||o===58||o===59||o===63||o===95||o===126?(e.consume(o),n):o===38?(e.consume(o),i):o===93?(e.consume(o),a):o===60||o===null||le(o)||Pt(o)?t(o):r(o)}function a(o){return o===null||o===40||o===91||le(o)||Pt(o)?t(o):n(o)}function i(o){return Be(o)?s(o):r(o)}function s(o){return o===59?(e.consume(o),n):Be(o)?(e.consume(o),s):r(o)}}function Lx(e,t,r){return n;function n(i){return e.consume(i),a}function a(i){return Ae(i)?r(i):t(i)}}function hu(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||le(e)}function fu(e){return!Be(e)}function pu(e){return!(e===47||Za(e))}function Za(e){return e===43||e===45||e===46||e===95||Ae(e)}function ei(e){let t=e.length,r=!1;for(;t--;){const n=e[t][1];if((n.type==="labelLink"||n.type==="labelImage")&&!n._balanced){r=!0;break}if(n._gfmAutolinkLiteralWalkedInto){r=!1;break}}return e.length>0&&!r&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),r}const Dx={tokenize:Ux,partial:!0};function Ox(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:Rx,continuation:{tokenize:jx},exit:$x}},text:{91:{name:"gfmFootnoteCall",tokenize:zx},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:Fx,resolveTo:Bx}}}}function Fx(e,t,r){const n=this;let a=n.events.length;const i=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let s;for(;a--;){const l=n.events[a][1];if(l.type==="labelImage"){s=l;break}if(l.type==="gfmFootnoteCall"||l.type==="labelLink"||l.type==="label"||l.type==="image"||l.type==="link")break}return o;function o(l){if(!s||!s._balanced)return r(l);const u=at(n.sliceSerialize({start:s.end,end:n.now()}));return u.codePointAt(0)!==94||!i.includes(u.slice(1))?r(l):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(l),e.exit("gfmFootnoteCallLabelMarker"),t(l))}}function Bx(e,t){let r=e.length;for(;r--;)if(e[r][1].type==="labelImage"&&e[r][0]==="enter"){e[r][1];break}e[r+1][1].type="data",e[r+3][1].type="gfmFootnoteCallLabelMarker";const n={type:"gfmFootnoteCall",start:Object.assign({},e[r+3][1].start),end:Object.assign({},e[e.length-1][1].end)},a={type:"gfmFootnoteCallMarker",start:Object.assign({},e[r+3][1].end),end:Object.assign({},e[r+3][1].end)};a.end.column++,a.end.offset++,a.end._bufferIndex++;const i={type:"gfmFootnoteCallString",start:Object.assign({},a.end),end:Object.assign({},e[e.length-1][1].start)},s={type:"chunkString",contentType:"string",start:Object.assign({},i.start),end:Object.assign({},i.end)},o=[e[r+1],e[r+2],["enter",n,t],e[r+3],e[r+4],["enter",a,t],["exit",a,t],["enter",i,t],["enter",s,t],["exit",s,t],["exit",i,t],e[e.length-2],e[e.length-1],["exit",n,t]];return e.splice(r,e.length-r+1,...o),e}function zx(e,t,r){const n=this,a=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let i=0,s;return o;function o(c){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(c),e.exit("gfmFootnoteCallLabelMarker"),l}function l(c){return c!==94?r(c):(e.enter("gfmFootnoteCallMarker"),e.consume(c),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",u)}function u(c){if(i>999||c===93&&!s||c===null||c===91||le(c))return r(c);if(c===93){e.exit("chunkString");const h=e.exit("gfmFootnoteCallString");return a.includes(at(n.sliceSerialize(h)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(c),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):r(c)}return le(c)||(s=!0),i++,e.consume(c),c===92?d:u}function d(c){return c===91||c===92||c===93?(e.consume(c),i++,u):u(c)}}function Rx(e,t,r){const n=this,a=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let i,s=0,o;return l;function l(g){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),u}function u(g){return g===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",d):r(g)}function d(g){if(s>999||g===93&&!o||g===null||g===91||le(g))return r(g);if(g===93){e.exit("chunkString");const v=e.exit("gfmFootnoteDefinitionLabelString");return i=at(n.sliceSerialize(v)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),h}return le(g)||(o=!0),s++,e.consume(g),g===92?c:d}function c(g){return g===91||g===92||g===93?(e.consume(g),s++,d):d(g)}function h(g){return g===58?(e.enter("definitionMarker"),e.consume(g),e.exit("definitionMarker"),a.includes(i)||a.push(i),ne(e,f,"gfmFootnoteDefinitionWhitespace")):r(g)}function f(g){return t(g)}}function jx(e,t,r){return e.check(xr,t,e.attempt(Dx,t,r))}function $x(e){e.exit("gfmFootnoteDefinition")}function Ux(e,t,r){const n=this;return ne(e,a,"gfmFootnoteDefinitionIndent",5);function a(i){const s=n.events[n.events.length-1];return s&&s[1].type==="gfmFootnoteDefinitionIndent"&&s[2].sliceSerialize(s[1],!0).length===4?t(i):r(i)}}function Hx(e){let r=(e||{}).singleTilde;const n={name:"strikethrough",tokenize:i,resolveAll:a};return r==null&&(r=!0),{text:{126:n},insideSpan:{null:[n]},attentionMarkers:{null:[126]}};function a(s,o){let l=-1;for(;++l<s.length;)if(s[l][0]==="enter"&&s[l][1].type==="strikethroughSequenceTemporary"&&s[l][1]._close){let u=l;for(;u--;)if(s[u][0]==="exit"&&s[u][1].type==="strikethroughSequenceTemporary"&&s[u][1]._open&&s[l][1].end.offset-s[l][1].start.offset===s[u][1].end.offset-s[u][1].start.offset){s[l][1].type="strikethroughSequence",s[u][1].type="strikethroughSequence";const d={type:"strikethrough",start:Object.assign({},s[u][1].start),end:Object.assign({},s[l][1].end)},c={type:"strikethroughText",start:Object.assign({},s[u][1].end),end:Object.assign({},s[l][1].start)},h=[["enter",d,o],["enter",s[u][1],o],["exit",s[u][1],o],["enter",c,o]],f=o.parser.constructs.insideSpan.null;f&&We(h,h.length,0,sn(f,s.slice(u+1,l),o)),We(h,h.length,0,[["exit",c,o],["enter",s[l][1],o],["exit",s[l][1],o],["exit",d,o]]),We(s,u-1,l-u+3,h),l=u+h.length-2;break}}for(l=-1;++l<s.length;)s[l][1].type==="strikethroughSequenceTemporary"&&(s[l][1].type="data");return s}function i(s,o,l){const u=this.previous,d=this.events;let c=0;return h;function h(g){return u===126&&d[d.length-1][1].type!=="characterEscape"?l(g):(s.enter("strikethroughSequenceTemporary"),f(g))}function f(g){const v=Kt(u);if(g===126)return c>1?l(g):(s.consume(g),c++,f);if(c<2&&!r)return l(g);const b=s.exit("strikethroughSequenceTemporary"),w=Kt(g);return b._open=!w||w===2&&!!v,b._close=!v||v===2&&!!w,o(g)}}}class qx{constructor(){this.map=[]}add(t,r,n){Vx(this,t,r,n)}consume(t){if(this.map.sort(function(i,s){return i[0]-s[0]}),this.map.length===0)return;let r=this.map.length;const n=[];for(;r>0;)r-=1,n.push(t.slice(this.map[r][0]+this.map[r][1]),this.map[r][2]),t.length=this.map[r][0];n.push(t.slice()),t.length=0;let a=n.pop();for(;a;){for(const i of a)t.push(i);a=n.pop()}this.map.length=0}}function Vx(e,t,r,n){let a=0;if(!(r===0&&n.length===0)){for(;a<e.map.length;){if(e.map[a][0]===t){e.map[a][1]+=r,e.map[a][2].push(...n);return}a+=1}e.map.push([t,r,n])}}function Wx(e,t){let r=!1;const n=[];for(;t<e.length;){const a=e[t];if(r){if(a[0]==="enter")a[1].type==="tableContent"&&n.push(e[t+1][1].type==="tableDelimiterMarker"?"left":"none");else if(a[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){const i=n.length-1;n[i]=n[i]==="left"?"center":"right"}}else if(a[1].type==="tableDelimiterRow")break}else a[0]==="enter"&&a[1].type==="tableDelimiterRow"&&(r=!0);t+=1}return n}function Jx(){return{flow:{null:{name:"table",tokenize:Yx,resolveAll:Kx}}}}function Yx(e,t,r){const n=this;let a=0,i=0,s;return o;function o(S){let N=n.events.length-1;for(;N>-1;){const R=n.events[N][1].type;if(R==="lineEnding"||R==="linePrefix")N--;else break}const M=N>-1?n.events[N][1].type:null,U=M==="tableHead"||M==="tableRow"?I:l;return U===I&&n.parser.lazy[n.now().line]?r(S):U(S)}function l(S){return e.enter("tableHead"),e.enter("tableRow"),u(S)}function u(S){return S===124||(s=!0,i+=1),d(S)}function d(S){return S===null?r(S):J(S)?i>1?(i=0,n.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(S),e.exit("lineEnding"),f):r(S):te(S)?ne(e,d,"whitespace")(S):(i+=1,s&&(s=!1,a+=1),S===124?(e.enter("tableCellDivider"),e.consume(S),e.exit("tableCellDivider"),s=!0,d):(e.enter("data"),c(S)))}function c(S){return S===null||S===124||le(S)?(e.exit("data"),d(S)):(e.consume(S),S===92?h:c)}function h(S){return S===92||S===124?(e.consume(S),c):c(S)}function f(S){return n.interrupt=!1,n.parser.lazy[n.now().line]?r(S):(e.enter("tableDelimiterRow"),s=!1,te(S)?ne(e,g,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(S):g(S))}function g(S){return S===45||S===58?b(S):S===124?(s=!0,e.enter("tableCellDivider"),e.consume(S),e.exit("tableCellDivider"),v):z(S)}function v(S){return te(S)?ne(e,b,"whitespace")(S):b(S)}function b(S){return S===58?(i+=1,s=!0,e.enter("tableDelimiterMarker"),e.consume(S),e.exit("tableDelimiterMarker"),w):S===45?(i+=1,w(S)):S===null||J(S)?D(S):z(S)}function w(S){return S===45?(e.enter("tableDelimiterFiller"),T(S)):z(S)}function T(S){return S===45?(e.consume(S),T):S===58?(s=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(S),e.exit("tableDelimiterMarker"),_):(e.exit("tableDelimiterFiller"),_(S))}function _(S){return te(S)?ne(e,D,"whitespace")(S):D(S)}function D(S){return S===124?g(S):S===null||J(S)?!s||a!==i?z(S):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(S)):z(S)}function z(S){return r(S)}function I(S){return e.enter("tableRow"),B(S)}function B(S){return S===124?(e.enter("tableCellDivider"),e.consume(S),e.exit("tableCellDivider"),B):S===null||J(S)?(e.exit("tableRow"),t(S)):te(S)?ne(e,B,"whitespace")(S):(e.enter("data"),H(S))}function H(S){return S===null||S===124||le(S)?(e.exit("data"),B(S)):(e.consume(S),S===92?j:H)}function j(S){return S===92||S===124?(e.consume(S),H):H(S)}}function Kx(e,t){let r=-1,n=!0,a=0,i=[0,0,0,0],s=[0,0,0,0],o=!1,l=0,u,d,c;const h=new qx;for(;++r<e.length;){const f=e[r],g=f[1];f[0]==="enter"?g.type==="tableHead"?(o=!1,l!==0&&(mu(h,t,l,u,d),d=void 0,l=0),u={type:"table",start:Object.assign({},g.start),end:Object.assign({},g.end)},h.add(r,0,[["enter",u,t]])):g.type==="tableRow"||g.type==="tableDelimiterRow"?(n=!0,c=void 0,i=[0,0,0,0],s=[0,r+1,0,0],o&&(o=!1,d={type:"tableBody",start:Object.assign({},g.start),end:Object.assign({},g.end)},h.add(r,0,[["enter",d,t]])),a=g.type==="tableDelimiterRow"?2:d?3:1):a&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")?(n=!1,s[2]===0&&(i[1]!==0&&(s[0]=s[1],c=yn(h,t,i,a,void 0,c),i=[0,0,0,0]),s[2]=r)):g.type==="tableCellDivider"&&(n?n=!1:(i[1]!==0&&(s[0]=s[1],c=yn(h,t,i,a,void 0,c)),i=s,s=[i[1],r,0,0])):g.type==="tableHead"?(o=!0,l=r):g.type==="tableRow"||g.type==="tableDelimiterRow"?(l=r,i[1]!==0?(s[0]=s[1],c=yn(h,t,i,a,r,c)):s[1]!==0&&(c=yn(h,t,s,a,r,c)),a=0):a&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")&&(s[3]=r)}for(l!==0&&mu(h,t,l,u,d),h.consume(t.events),r=-1;++r<t.events.length;){const f=t.events[r];f[0]==="enter"&&f[1].type==="table"&&(f[1]._align=Wx(t.events,r))}return e}function yn(e,t,r,n,a,i){const s=n===1?"tableHeader":n===2?"tableDelimiter":"tableData",o="tableContent";r[0]!==0&&(i.end=Object.assign({},Xt(t.events,r[0])),e.add(r[0],0,[["exit",i,t]]));const l=Xt(t.events,r[1]);if(i={type:s,start:Object.assign({},l),end:Object.assign({},l)},e.add(r[1],0,[["enter",i,t]]),r[2]!==0){const u=Xt(t.events,r[2]),d=Xt(t.events,r[3]),c={type:o,start:Object.assign({},u),end:Object.assign({},d)};if(e.add(r[2],0,[["enter",c,t]]),n!==2){const h=t.events[r[2]],f=t.events[r[3]];if(h[1].end=Object.assign({},f[1].end),h[1].type="chunkText",h[1].contentType="text",r[3]>r[2]+1){const g=r[2]+1,v=r[3]-r[2]-1;e.add(g,v,[])}}e.add(r[3]+1,0,[["exit",c,t]])}return a!==void 0&&(i.end=Object.assign({},Xt(t.events,a)),e.add(a,0,[["exit",i,t]]),i=void 0),i}function mu(e,t,r,n,a){const i=[],s=Xt(t.events,r);a&&(a.end=Object.assign({},s),i.push(["exit",a,t])),n.end=Object.assign({},s),i.push(["exit",n,t]),e.add(r+1,0,i)}function Xt(e,t){const r=e[t],n=r[0]==="enter"?"start":"end";return r[1][n]}const Gx={name:"tasklistCheck",tokenize:Qx};function Xx(){return{text:{91:Gx}}}function Qx(e,t,r){const n=this;return a;function a(l){return n.previous!==null||!n._gfmTasklistFirstContentOfListItem?r(l):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(l),e.exit("taskListCheckMarker"),i)}function i(l){return le(l)?(e.enter("taskListCheckValueUnchecked"),e.consume(l),e.exit("taskListCheckValueUnchecked"),s):l===88||l===120?(e.enter("taskListCheckValueChecked"),e.consume(l),e.exit("taskListCheckValueChecked"),s):r(l)}function s(l){return l===93?(e.enter("taskListCheckMarker"),e.consume(l),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),o):r(l)}function o(l){return J(l)?t(l):te(l)?e.check({tokenize:Zx},t,r)(l):r(l)}}function Zx(e,t,r){return ne(e,n,"whitespace");function n(a){return a===null?r(a):t(a)}}function ev(e){return Vo([Tx(),Ox(),Hx(e),Jx(),Xx()])}const tv={};function rv(e){const t=this,r=e||tv,n=t.data(),a=n.micromarkExtensions||(n.micromarkExtensions=[]),i=n.fromMarkdownExtensions||(n.fromMarkdownExtensions=[]),s=n.toMarkdownExtensions||(n.toMarkdownExtensions=[]);a.push(ev(r)),i.push(vx()),s.push(kx(r))}function Te(...e){return e.filter(Boolean).join(" ")}const nv=({content:e})=>p.jsx(Jb,{remarkPlugins:[rv],className:"cuadra-aui-md",components:sv,children:e}),ti=y.memo(nv),av=({language:e,code:t})=>{const{isCopied:r,copyToClipboard:n}=iv(),a=()=>{!t||r||n(t)};return p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-between cuadra-gap-4 cuadra-mt-4 cuadra-rounded-t-lg cuadra-bg-muted/50 cuadra-border-b cuadra-border-border cuadra-px-4 cuadra-py-2 cuadra-text-sm cuadra-font-normal cuadra-text-foreground cuadra-font-brand",children:[p.jsx("span",{className:"cuadra-lowercase [&>span]:cuadra-text-xs cuadra-font-brand",children:e}),p.jsxs("button",{onClick:a,className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-muted cuadra-transition-colors","aria-label":"Copy code",children:[!r&&p.jsx(ju,{className:"cuadra-h-4 cuadra-w-4"}),r&&p.jsx(zu,{className:"cuadra-h-4 cuadra-w-4"})]})]})},iv=({copiedDuration:e=3e3}={})=>{const[t,r]=y.useState(!1);return{isCopied:t,copyToClipboard:a=>{a&&navigator.clipboard.writeText(a).then(()=>{r(!0),setTimeout(()=>r(!1),e)})}}},sv=Pb({h1:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("h1",m({className:Te("cuadra-mb-6 cuadra-scroll-m-20 cuadra-text-2xl cuadra-font-normal cuadra-tracking-tight last:cuadra-mb-0 font-brand",e)},t))},h2:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("h2",m({className:Te("cuadra-mb-4 cuadra-mt-6 cuadra-scroll-m-20 cuadra-text-xl cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},h3:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("h3",m({className:Te("cuadra-mb-3 cuadra-mt-5 cuadra-scroll-m-20 cuadra-text-lg cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},h4:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("h4",m({className:Te("cuadra-mb-4 cuadra-mt-6 cuadra-scroll-m-20 cuadra-text-xl cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},h5:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("h5",m({className:Te("cuadra-my-4 cuadra-text-lg cuadra-font-normal first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},h6:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("h6",m({className:Te("cuadra-my-4 cuadra-font-normal first:cuadra-mb-0 font-brand",e)},t))},p:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("p",m({className:Te("cuadra-mb-5 cuadra-mt-5 cuadra-leading-7 first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},a:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("a",m({className:Te("cuadra-text-primary cuadra-font-medium cuadra-underline cuadra-underline-offset-4 font-brand",e)},t))},blockquote:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("blockquote",m({className:Te("cuadra-border-l-2 cuadra-pl-6 cuadra-italic font-brand",e)},t))},ul:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("ul",m({className:Te("cuadra-my-5 cuadra-ml-6 cuadra-list-disc [&>li]:cuadra-mt-2 font-brand",e)},t))},ol:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("ol",m({className:Te("cuadra-my-5 cuadra-ml-6 cuadra-list-decimal [&>li]:cuadra-mt-2 font-brand",e)},t))},hr:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("hr",m({className:Te("cuadra-my-5 cuadra-border-b",e)},t))},table:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("table",m({className:Te("cuadra-my-5 cuadra-w-full cuadra-border-separate cuadra-border-spacing-0 cuadra-overflow-y-auto font-brand",e)},t))},th:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("th",m({className:Te("cuadra-bg-muted cuadra-px-4 cuadra-py-2 cuadra-text-left cuadra-font-normal first:cuadra-rounded-tl-lg last:cuadra-rounded-tr-lg [&[align=center]]:cuadra-text-center [&[align=right]]:cuadra-text-right font-brand",e)},t))},td:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("td",m({className:Te("cuadra-border-b cuadra-border-l cuadra-px-4 cuadra-py-2 cuadra-text-left last:cuadra-border-r [&[align=center]]:cuadra-text-center [&[align=right]]:cuadra-text-right font-brand",e)},t))},tr:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("tr",m({className:Te("cuadra-m-0 cuadra-border-b cuadra-p-0 first:cuadra-border-t [&:last-child>td:first-child]:cuadra-rounded-bl-lg [&:last-child>td:last-child]:cuadra-rounded-br-lg",e)},t))},sup:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("sup",m({className:Te("[&>a]:cuadra-text-xs [&>a]:cuadra-no-underline font-brand",e)},t))},pre:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("pre",m({className:Te("cuadra-overflow-x-auto cuadra-whitespace-pre-wrap cuadra-break-words cuadra-rounded-b-lg !cuadra-rounded-t-none cuadra-bg-muted cuadra-p-4 cuadra-text-foreground font-brand",e)},t))},code:function(n){var a=n,{className:t}=a,r=V(a,["className"]);const i=Ol();return p.jsx("code",m({className:Te(!i&&"cuadra-bg-muted cuadra-rounded cuadra-border cuadra-font-normal font-brand",t)},r))},CodeHeader:av});function gu(n){var a=n,{className:e="",variant:t="default"}=a,r=V(a,["className","variant"]);const i="cuadra-inline-flex cuadra-items-center cuadra-rounded-md cuadra-px-3 cuadra-py-1.5 cuadra-text-xs cuadra-font-medium font-brand",s={default:"cuadra-border cuadra-border-border cuadra-bg-muted cuadra-text-muted-foreground",subtle:"cuadra-border cuadra-border-border/50 cuadra-bg-muted/50 cuadra-text-muted-foreground",outline:"cuadra-border cuadra-border-border cuadra-bg-background cuadra-text-foreground",ghost:"cuadra-text-muted-foreground"};return p.jsx("div",m({className:`${i} ${s[t]||s.default} ${e}`},r))}function ov(e){const t=new Map;for(const r of e){const n=t.get(r.filename);(!n||r.score>n.score)&&t.set(r.filename,r)}return Array.from(t.values()).sort((r,n)=>n.score-r.score)}function lv({sources:e,maxVisible:t=3}){if(!e||e.length===0)return null;const r=ov(e),n=r.slice(0,t),a=r.length-t;return p.jsxs("div",{className:"cuadra-mt-4 cuadra-pt-3 cuadra-border-t cuadra-border-border",children:[p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1.5 cuadra-mb-2.5",children:[p.jsx(li,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground"}),p.jsx("span",{className:"cuadra-text-xs cuadra-font-medium cuadra-text-muted-foreground font-brand",children:"Sources"})]}),p.jsxs("div",{className:"cuadra-flex cuadra-flex-wrap cuadra-gap-2",children:[n.map((i,s)=>p.jsx(cv,{source:i},i.sourceId||s)),a>0&&p.jsxs(gu,{variant:"subtle",children:["+",a," more"]})]})]})}function uv(e){var r;switch((r=e.split(".").pop())==null?void 0:r.toLowerCase()){case"csv":case"xlsx":case"xls":return Uu;case"md":case"txt":return Hu;default:return li}}function cv({source:e}){const{filename:t,score:r}=e,n=uv(t);return p.jsxs(gu,{className:"cuadra-gap-2 cuadra-cursor-default",title:r<1?`${Math.round(r*100)}% relevant`:void 0,children:[p.jsx(n,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-shrink-0 cuadra-opacity-60"}),p.jsx("span",{className:"cuadra-truncate cuadra-max-w-[180px]",children:t}),r<1&&r>0&&p.jsxs("span",{className:"cuadra-opacity-50 cuadra-text-[10px] cuadra-tabular-nums",children:[Math.round(r*100),"%"]})]})}const yu=y.forwardRef(function({welcomeTitle:t="Hi, how can I help you today?",welcomeSubtitle:r="Start exploring our platform and discover what you can build.",extraTopPadding:n,suggestions:a,inputPlaceholder:i="Type your message...",enableAttachments:s=!1,preMadeResponseDelay:o=1e3,streamingSpeed:l=50,safeArea:u=!1},d){const c=ls(),h=fe(),[f,g]=y.useState(!1),[v,b]=y.useState(null),[w,T]=y.useState(!1),_=y.useCallback((B,H,j)=>{var S,N;if(!w)try{const M=(S=j==null?void 0:j.streamingSpeed)!=null?S:l,U=(N=j==null?void 0:j.delay)!=null?N:o;po(B,H,M,U),h.composer().setText(B),setTimeout(()=>{h.composer().send()},10)}catch(M){}},[w,l,o,h]),D=y.useCallback(B=>{try{h.composer().setText(B),setTimeout(()=>{h.composer().send()},10)}catch(H){}},[h]),z=y.useCallback(B=>P(null,null,function*(){var H;if(!(w||!c))try{if(B.response){const j=(H=B.responseDelay)!=null?H:o;yield _(B.prompt,B.response,{delay:j,streamingSpeed:l})}else D(B.prompt)}catch(j){}}),[c,w,o,l,_,D]),I=y.useCallback(()=>{try{const B=window.__cuadraThreadListRuntime;B!=null&&B.switchToNewThread&&B.switchToNewThread()}catch(B){}},[]);return y.useImperativeHandle(d,()=>({sendMessage:D,sendPreMadeQA:_,clearChat:I}),[D,_,I]),y.useEffect(()=>{var B,H;if(!c){g(!1);return}try{const j=c==null?void 0:c.store;if(!j){g(!1);return}const S=(B=j.subscribe)==null?void 0:B.call(j,M=>{const U=M==null?void 0:M.threadId,R=(M==null?void 0:M.messages)||[],F=(M==null?void 0:M.isLoadingHistory)||!1,Q=R.length;U&&U!==v&&b(U),g(F&&Q===0)}),N=(H=j.getState)==null?void 0:H.call(j);if(N){const M=N==null?void 0:N.threadId,U=(N==null?void 0:N.messages)||[],R=(N==null?void 0:N.isLoadingHistory)||!1,F=U.length;M&&M!==v&&b(M),g(R&&F===0)}return()=>{S&&S()}}catch(j){g(!1)}},[c,v]),p.jsxs(Zs,{className:"cuadra-bg-inherit cuadra-flex cuadra-flex-col cuadra-w-full cuadra-h-full",children:[p.jsx(ro,{className:"cuadra-w-full cuadra-bg-inherit cuadra-px-4 cuadra-flex-1 cuadra-min-h-0 cuadra-overflow-y-auto cuadra-relative scrollbar-thin cuadra-pt-4",style:n?{paddingTop:n}:void 0,children:f?p.jsx("div",{className:"cuadra-absolute cuadra-inset-0 cuadra-flex cuadra-items-center cuadra-justify-center",children:p.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-2",children:[p.jsx(ui,{className:"cuadra-h-6 cuadra-w-6 cuadra-animate-spin cuadra-text-muted-foreground"}),p.jsx("p",{className:"cuadra-text-sm cuadra-text-muted-foreground font-brand",children:"Loading messages..."})]})}):p.jsxs(p.Fragment,{children:[p.jsx(eo,{children:p.jsx(dv,{title:t,subtitle:r,suggestions:a,onSuggestionClick:z,isProcessing:w})}),p.jsx(np,{components:{UserMessage:hv,AssistantMessage:mv}})]})}),p.jsxs("div",{className:"cuadra-w-full cuadra-mt-3 cuadra-border-t cuadra-border-border cuadra-pt-4",style:u?{paddingBottom:"env(safe-area-inset-bottom)"}:void 0,children:[s&&p.jsx(Qs,{components:{Attachment:()=>{const B=re(({attachment:H})=>H);return B?p.jsxs("div",{className:"cuadra-relative cuadra-inline-flex cuadra-items-center cuadra-gap-2 cuadra-mb-2 cuadra-px-2 cuadra-py-1 cuadra-rounded-md cuadra-bg-muted cuadra-border cuadra-border-border",children:[p.jsx("span",{className:"cuadra-text-xs cuadra-text-muted-foreground font-brand",children:B.name||"Attachment"}),p.jsx(hf,{asChild:!0,children:p.jsx("button",{type:"button",className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-size-4 cuadra-rounded hover:cuadra-bg-background cuadra-transition-colors","aria-label":"Remove attachment",children:p.jsx(In,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})})})]}):null}}}),p.jsxs(Hs,{className:"cuadra-relative !cuadra-relative cuadra-flex-1 cuadra-w-full",children:[p.jsx(Gs,{asChild:!0,children:p.jsx("textarea",{rows:3,placeholder:i,className:"cuadra-flex cuadra-min-h-[80px] cuadra-w-full cuadra-rounded-md cuadra-border cuadra-border-border cuadra-bg-background cuadra-px-3 cuadra-py-2 cuadra-text-base cuadra-text-foreground placeholder:cuadra-text-muted-foreground focus-visible:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 cuadra-resize-none font-brand",style:{paddingRight:s?"5rem":"3rem",fontSize:"1rem",borderWidth:"1px"}})}),s&&p.jsx(Yf,{multiple:!0,asChild:!0,children:p.jsx("button",{type:"button",className:"!cuadra-absolute !cuadra-bottom-2 !cuadra-right-12 cuadra-size-8 cuadra-rounded-md hover:cuadra-bg-muted cuadra-transition-colors cuadra-flex cuadra-items-center cuadra-justify-center cuadra-border cuadra-border-border",style:{position:"absolute",bottom:"0.5rem",right:"3rem"},"aria-label":"Attach file",children:p.jsx(ci,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground",strokeWidth:1.5})})}),p.jsx(Af,{asChild:!0,children:p.jsx("button",{className:"!cuadra-absolute !cuadra-bottom-2 !cuadra-right-2 cuadra-size-8 cuadra-rounded-md cuadra-shadow-sm hover:cuadra-opacity-90 disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed cuadra-flex cuadra-items-center cuadra-justify-center",style:{position:"absolute",bottom:"0.5rem",right:"0.5rem",backgroundColor:"var(--cuadra-primary)",color:"hsl(var(--cuadra-primary-foreground))"},"aria-label":"Send message",type:"button",children:p.jsx(Bu,{className:"cuadra-h-4 cuadra-w-4"})})})]})]})]})});function dv({title:e,subtitle:t,suggestions:r,onSuggestionClick:n,isProcessing:a}){return p.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-h-full cuadra-py-12 cuadra-px-4 cuadra-overflow-y-auto scrollbar-hide",children:p.jsxs("div",{className:"cuadra-text-center cuadra-max-w-3xl cuadra-w-full cuadra-flex cuadra-flex-col cuadra-items-center cuadra-justify-center cuadra-min-h-full",children:[p.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-justify-center cuadra-mb-8",children:[p.jsx("h2",{className:"cuadra-text-xl cuadra-font-normal cuadra-text-foreground cuadra-mb-2 font-brand",children:e}),p.jsx("p",{className:"cuadra-text-muted-foreground font-brand",children:t})]}),r&&r.length>0&&p.jsx("div",{className:"cuadra-grid cuadra-grid-cols-2 cuadra-gap-2 cuadra-pb-4 cuadra-w-full cuadra-max-w-2xl",children:r.map((i,s)=>p.jsx("button",{type:"button",onClick:()=>n(i),disabled:a,className:"cuadra-w-full cuadra-text-center cuadra-px-4 cuadra-py-3 cuadra-rounded-lg cuadra-border cuadra-border-border cuadra-bg-background cuadra-text-base cuadra-text-foreground font-brand cuadra-cursor-pointer focus:cuadra-outline-none focus:cuadra-ring-0 disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed",style:{borderWidth:"1px"},children:i.prompt},`suggestion-${s}`))})]})})}function hv(){return p.jsxs(ea,{className:"cuadra-grid cuadra-w-full cuadra-auto-rows-auto cuadra-grid-cols-[minmax(72px,1fr)_auto] cuadra-gap-y-2 cuadra-py-3 [&:where(>*)]:cuadra-col-start-2",children:[p.jsx($s,{components:{Attachment:()=>{var i;const e=re(({attachment:s})=>s);if(!e)return null;const t=e.type==="image",r=e.file,n=(i=e.content)==null?void 0:i.find(s=>s.type==="image"),a=r?URL.createObjectURL(r):n==null?void 0:n.image;return p.jsx("div",{className:"cuadra-col-start-2 cuadra-row-start-1 cuadra-mb-2 cuadra-max-w-[calc(42rem*0.8)]",children:t&&a?p.jsx("img",{src:a,alt:e.name||"Attachment",className:"cuadra-rounded-lg cuadra-border cuadra-border-border cuadra-max-h-64 cuadra-max-w-full cuadra-object-contain",style:{borderWidth:"1px"}}):p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2 cuadra-rounded-lg cuadra-border cuadra-border-border cuadra-bg-muted cuadra-px-3 cuadra-py-2",children:[p.jsx(ci,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"}),p.jsx("span",{className:"cuadra-text-sm cuadra-text-foreground font-brand",children:e.name||"Attachment"})]})})}}}),p.jsx("div",{className:"cuadra-bg-muted cuadra-text-foreground cuadra-col-start-2 cuadra-row-start-2 cuadra-max-w-[calc(42rem*0.8)] cuadra-break-words cuadra-rounded-3xl cuadra-border cuadra-border-border cuadra-px-5 cuadra-py-2.5 font-brand",style:{maxWidth:"calc(42rem * 0.8)",borderRadius:"1.5rem",backgroundColor:"var(--cuadra-muted)",color:"hsl(var(--cuadra-foreground))",paddingLeft:"1.25rem",paddingRight:"1.25rem",paddingTop:"0.625rem",paddingBottom:"0.625rem",wordBreak:"break-word",borderWidth:"1px"},children:p.jsx(ta,{components:{Text:({text:e})=>p.jsx(ti,{content:e||""})}})})]})}function fv({text:e}){const[t,r]=y.useState(!1),n=re(({message:a})=>{var i;return((i=a==null?void 0:a.status)==null?void 0:i.type)==="running"});return e?n?p.jsx("div",{className:"cuadra-mb-3 cuadra-py-1",children:p.jsx("div",{className:"cuadra-text-sm cuadra-text-muted-foreground cuadra-leading-relaxed font-brand cuadra-animate-text-shimmer",children:e})}):p.jsxs("div",{className:"cuadra-mb-3",children:[p.jsxs("button",{type:"button",onClick:()=>r(!t),className:"cuadra-flex cuadra-items-center cuadra-gap-1.5 cuadra-py-1 cuadra-text-sm cuadra-text-muted-foreground hover:cuadra-text-foreground cuadra-transition-colors font-brand",children:[p.jsx(Cn,{className:`cuadra-h-3.5 cuadra-w-3.5 cuadra-shrink-0 cuadra-transition-transform cuadra-duration-200 ${t?"":"cuadra--rotate-90"}`}),p.jsx("span",{children:"Reasoning"})]}),p.jsx("div",{className:`cuadra-overflow-hidden cuadra-transition-all cuadra-duration-200 cuadra-ease-out ${t?"cuadra-max-h-[2000px] cuadra-opacity-100":"cuadra-max-h-0 cuadra-opacity-0"}`,children:p.jsx("div",{className:"cuadra-pl-5 cuadra-pt-2 cuadra-text-sm cuadra-text-muted-foreground cuadra-leading-relaxed font-brand",children:p.jsx(ti,{content:e})})})]}):null}function pv(){return p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2 cuadra-text-muted-foreground cuadra-text-sm font-brand cuadra-py-2",children:[p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1",children:[p.jsx("span",{className:"cuadra-inline-block cuadra-w-1.5 cuadra-h-1.5 cuadra-bg-current cuadra-rounded-full cuadra-animate-bounce",style:{animationDelay:"0ms"}}),p.jsx("span",{className:"cuadra-inline-block cuadra-w-1.5 cuadra-h-1.5 cuadra-bg-current cuadra-rounded-full cuadra-animate-bounce",style:{animationDelay:"150ms"}}),p.jsx("span",{className:"cuadra-inline-block cuadra-w-1.5 cuadra-h-1.5 cuadra-bg-current cuadra-rounded-full cuadra-animate-bounce",style:{animationDelay:"300ms"}})]}),p.jsx("span",{children:"Thinking..."})]})}function mv(){const e=re(({message:s})=>{var o;return((o=s==null?void 0:s.status)==null?void 0:o.type)==="running"}),t=re(({message:s})=>{const o=s==null?void 0:s.content;return!o||!Array.isArray(o)?!1:o.some(l=>!!(l.type==="text"&&l.text&&l.text.length>0||l.type==="reasoning"&&l.text&&l.text.length>0))}),r=y.useRef(!1),[n,a]=y.useState(null);y.useEffect(()=>{if(e&&t&&!r.current){const s=wt.getCurrentMessageId();s&&(r.current=!0,a(s))}},[e,t]);const i=y.useSyncExternalStore(s=>wt.subscribe(s),()=>{var s,o;if(n){const l=wt.getForMessage(n);return(s=l.sources)!=null&&s.length?l.sources:null}if(e&&t){const l=wt.getCurrentMessageId();if(l){const u=wt.getForMessage(l);return(o=u.sources)!=null&&o.length?u.sources:null}}return null},()=>null);return p.jsx(ea,{className:"cuadra-relative cuadra-grid cuadra-w-full cuadra-grid-cols-[auto_auto_1fr] cuadra-grid-rows-[auto_1fr] cuadra-py-3",children:p.jsxs("div",{className:"cuadra-text-foreground cuadra-col-span-2 cuadra-col-start-2 cuadra-row-start-1 cuadra-my-1.5 cuadra-max-w-[90%] cuadra-break-words cuadra-leading-7 font-brand",style:{maxWidth:"90%",marginTop:"0.375rem",marginBottom:"0.375rem"},children:[p.jsx(ta,{components:{Text:({text:s})=>p.jsx(ti,{content:s||""}),Reasoning:({text:s})=>p.jsx(fv,{text:s||""})}}),e&&!t&&p.jsx(pv,{}),i&&i.length>0&&p.jsx(lv,{sources:i})]})})}const bu=({className:e="",theme:t="system"})=>{const r=()=>{if(typeof window=="undefined")return"light";if(t==="system"){const s=localStorage.getItem("theme");return s||(window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light")}return t},[n,a]=y.useState(r);y.useEffect(()=>{t!=="system"&&a(t)},[t]),y.useEffect(()=>{const s=document.documentElement;s.classList.remove("light","dark"),s.classList.add(n),t==="system"&&localStorage.setItem("theme",n)},[n,t]);const i=()=>{t==="system"&&a(s=>s==="light"?"dark":"light")};return p.jsx("button",{type:"button","aria-label":"Toggle theme",onClick:i,disabled:t!=="system",className:`cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-8 cuadra-w-8 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed ${e}`,children:p.jsx(Ru,{className:`cuadra-h-4 cuadra-w-4 cuadra-transition-colors ${n==="dark"?"cuadra-text-primary":"cuadra-text-gray-400"}`})})};function gv({onThreadSelect:e}){var b,w;const t=us(),r=Kd(T=>T.threadId),[n,a]=y.useState(null),i=(t==null?void 0:t.id)===r,s=n===(t==null?void 0:t.id),[o,l]=y.useState(!1),[u,d]=y.useState((t==null?void 0:t.title)||""),[c,h]=y.useState(!1),[f,g]=y.useState(!1),v=()=>P(null,null,function*(){if(!(t!=null&&t.remoteId)||!u||u===t.title){l(!1);return}try{g(!0);const T=window.__cuadraThreadListAdapter;T&&typeof T.rename=="function"&&(yield T.rename(t.remoteId,u)),l(!1),h(!1)}catch(T){l(!1),h(!1)}finally{g(!1)}});return y.useEffect(()=>{t!=null&&t.title&&!o&&d(t.title)},[t==null?void 0:t.title,o]),t?p.jsxs(co,{className:`group cuadra-relative cuadra-flex cuadra-items-center cuadra-rounded-lg cuadra-transition-colors cuadra-cursor-pointer cuadra-border cuadra-mb-2 ${i?"cuadra-bg-muted cuadra-border-border":"cuadra-border-transparent hover:cuadra-bg-muted hover:cuadra-border-border"}`,style:{marginBottom:"0.5rem"},onMouseEnter:()=>a(t.id),onMouseLeave:()=>a(null),children:[p.jsx(op,{className:"cuadra-p-3 cuadra-flex-1 cuadra-flex cuadra-items-center cuadra-min-w-0 cuadra-cursor-pointer",onClick:()=>e==null?void 0:e(),children:p.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-min-w-0 cuadra-flex-1 cuadra-items-start cuadra-text-left",children:o?p.jsx("input",{className:"cuadra-flex cuadra-w-full cuadra-rounded-md cuadra-border cuadra-border-input cuadra-bg-background cuadra-px-3 cuadra-py-2 cuadra-text-sm placeholder:cuadra-text-muted-foreground focus-visible:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 font-brand",value:u,onChange:T=>d(T.target.value),onKeyDown:T=>{T.key==="Enter"&&v(),T.key==="Escape"&&(l(!1),d(t.title||""))},disabled:f,autoFocus:!0,onClick:T=>T.stopPropagation()}):p.jsxs(p.Fragment,{children:[p.jsx("span",{className:"cuadra-text-sm cuadra-font-normal cuadra-text-foreground cuadra-truncate font-brand",children:(((b=t.title)==null?void 0:b.length)||0)>60?`${(w=t.title)==null?void 0:w.slice(0,60)}…`:t.title||"Chat"}),t.updatedAt&&p.jsx("span",{className:"cuadra-text-xs cuadra-text-muted-foreground cuadra-mt-1 font-brand",children:new Date(t.updatedAt).toLocaleDateString()})]})})}),p.jsx("div",{className:"cuadra-mr-2 cuadra-flex-shrink-0 cuadra-w-6 cuadra-h-6 cuadra-flex cuadra-items-center cuadra-justify-center",children:(s||i||c)&&p.jsxs("div",{className:"cuadra-relative",children:[p.jsx("button",{type:"button",className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-background/50 cuadra-transition-colors",onClick:T=>{T.stopPropagation(),h(!c)},"aria-label":"Thread options",children:p.jsx($u,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"})}),c&&p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:()=>h(!1)}),p.jsx("div",{className:"cuadra-absolute cuadra-right-0 cuadra-top-8 cuadra-z-50 cuadra-bg-background cuadra-border cuadra-border-border cuadra-rounded-lg cuadra-shadow-lg cuadra-min-w-[120px] cuadra-overflow-hidden",children:o?p.jsx("button",{type:"button",className:"cuadra-w-full cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left hover:cuadra-bg-muted cuadra-transition-colors font-brand",onClick:T=>{T.stopPropagation(),v()},disabled:f,children:"Save"}):p.jsxs(p.Fragment,{children:[p.jsx("button",{type:"button",className:"cuadra-w-full cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left hover:cuadra-bg-muted cuadra-transition-colors font-brand",onClick:T=>{T.stopPropagation(),l(!0),d(t.title||""),h(!1)},children:"Rename"}),p.jsx("div",{className:"cuadra-border-t cuadra-border-border"}),p.jsx(ip,{asChild:!0,children:p.jsx("button",{type:"button",className:"cuadra-w-full cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left cuadra-text-destructive hover:cuadra-bg-muted cuadra-transition-colors font-brand",onClick:T=>{T.stopPropagation(),h(!1)},children:"Delete"})})]})})]})]})})]}):null}function wu({onThreadSelect:e,showThemeToggle:t,theme:r,onLogout:n,safeArea:a=!1,orgName:i,primaryColor:s}){return p.jsxs(uo,{className:"!cuadra-border-r cuadra-border-border cuadra-flex cuadra-flex-col cuadra-bg-background cuadra-transition-all cuadra-duration-300 cuadra-ease-in-out cuadra-h-full cuadra-w-80",style:{borderRightWidth:"1px"},children:[p.jsxs("div",{className:"cuadra-border-b cuadra-border-border cuadra-flex cuadra-items-center cuadra-justify-between cuadra-transition-all cuadra-duration-300 cuadra-min-h-16 cuadra-px-4 cuadra-py-4",style:a?{paddingTop:"calc(env(safe-area-inset-top) + 1rem)",paddingLeft:"calc(env(safe-area-inset-left) + 0.5rem)"}:void 0,children:[i?p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2 cuadra-flex-1 cuadra-min-w-0",children:[p.jsx("div",{className:"cuadra-w-8 cuadra-h-8 cuadra-rounded-full cuadra-flex cuadra-items-center cuadra-justify-center cuadra-text-white cuadra-font-bold cuadra-text-sm cuadra-flex-shrink-0",style:{backgroundColor:s||"hsl(var(--primary))"},children:i.charAt(0).toUpperCase()}),p.jsx("span",{className:"cuadra-font-medium cuadra-text-sm cuadra-text-foreground cuadra-truncate font-brand",children:i})]}):p.jsx("div",{className:"cuadra-flex-1"}),p.jsx("button",{type:"button",onClick:e,className:"cuadra-flex md:cuadra-hidden cuadra-items-center cuadra-justify-center cuadra-h-8 cuadra-w-8 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors cuadra-flex-shrink-0","aria-label":"Close",children:p.jsx(In,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-foreground"})})]}),p.jsxs("div",{className:"cuadra-flex-1 cuadra-overflow-y-auto cuadra-p-2 cuadra-pl-4 scrollbar-thin",style:a?{paddingLeft:"calc(env(safe-area-inset-left) + 1rem)"}:void 0,children:[p.jsx(so,{className:"group cuadra-relative cuadra-flex cuadra-items-center cuadra-gap-3 cuadra-p-3 cuadra-rounded-lg cuadra-cursor-pointer cuadra-transition-colors cuadra-border cuadra-border-transparent hover:cuadra-bg-muted hover:cuadra-border-border",onClick:()=>e==null?void 0:e(),children:p.jsx("div",{className:"cuadra-flex-1 cuadra-min-w-0",children:p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2",children:[p.jsx(Wu,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"}),p.jsx("h4",{className:"cuadra-text-sm cuadra-font-normal cuadra-text-foreground font-brand",children:"New Chat"})]})})}),p.jsx("div",{className:"cuadra-my-2 cuadra-border-t cuadra-border-border"}),p.jsx(lo,{components:{ThreadListItem:o=>p.jsx(gv,E(m({},o),{onThreadSelect:e}))}})]}),(t||n)&&p.jsxs("div",{className:"cuadra-border-t cuadra-border-border cuadra-flex md:cuadra-hidden cuadra-items-center cuadra-justify-between cuadra-px-4 cuadra-py-4",style:a?{paddingBottom:"calc(env(safe-area-inset-bottom) + 0.5rem)",paddingLeft:"calc(env(safe-area-inset-left) + 0.5rem)"}:void 0,children:[n&&p.jsx("button",{type:"button",onClick:n,className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-8 cuadra-w-8 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors","aria-label":"Logout",children:p.jsx(qu,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-foreground"})}),t&&p.jsx(bu,{theme:r})]})]})}const yv=`
33
+ `},i.current()));return/^[\t ]/.test(u)&&(u=Ir(u.charCodeAt(0))+u.slice(1)),u=u?s+" "+u:s,r.options.closeAtx&&(u+=" "+s),l(),o(),u}Gl.peek=Ww;function Gl(e){return e.value||""}function Ww(){return"<"}Xl.peek=Jw;function Xl(e,t,r,n){const a=Xa(r),i=a==='"'?"Quote":"Apostrophe",s=r.enter("image");let o=r.enter("label");const l=r.createTracker(n);let u=l.move("![");return u+=l.move(r.safe(e.alt,m({before:u,after:"]"},l.current()))),u+=l.move("]("),o(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(o=r.enter("destinationLiteral"),u+=l.move("<"),u+=l.move(r.safe(e.url,m({before:u,after:">"},l.current()))),u+=l.move(">")):(o=r.enter("destinationRaw"),u+=l.move(r.safe(e.url,m({before:u,after:e.title?" ":")"},l.current())))),o(),e.title&&(o=r.enter(`title${i}`),u+=l.move(" "+a),u+=l.move(r.safe(e.title,m({before:u,after:a},l.current()))),u+=l.move(a),o()),u+=l.move(")"),s(),u}function Jw(){return"!"}Ql.peek=Yw;function Ql(e,t,r,n){const a=e.referenceType,i=r.enter("imageReference");let s=r.enter("label");const o=r.createTracker(n);let l=o.move("![");const u=r.safe(e.alt,m({before:l,after:"]"},o.current()));l+=o.move(u+"]["),s();const d=r.stack;r.stack=[],s=r.enter("reference");const c=r.safe(r.associationId(e),m({before:l,after:"]"},o.current()));return s(),r.stack=d,i(),a==="full"||!u||u!==c?l+=o.move(c+"]"):a==="shortcut"?l=l.slice(0,-1):l+=o.move("]"),l}function Yw(){return"!"}Zl.peek=Kw;function Zl(e,t,r){let n=e.value||"",a="`",i=-1;for(;new RegExp("(^|[^`])"+a+"([^`]|$)").test(n);)a+="`";for(/[^ \r\n]/.test(n)&&(/^[ \r\n]/.test(n)&&/[ \r\n]$/.test(n)||/^`|`$/.test(n))&&(n=" "+n+" ");++i<r.unsafe.length;){const s=r.unsafe[i],o=r.compilePattern(s);let l;if(s.atBreak)for(;l=o.exec(n);){let u=l.index;n.charCodeAt(u)===10&&n.charCodeAt(u-1)===13&&u--,n=n.slice(0,u)+" "+n.slice(l.index+1)}}return a+n+a}function Kw(){return"`"}function eu(e,t){const r=wa(e);return!!(!t.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type==="text"&&(r===e.url||"mailto:"+r===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}tu.peek=Gw;function tu(e,t,r,n){const a=Xa(r),i=a==='"'?"Quote":"Apostrophe",s=r.createTracker(n);let o,l;if(eu(e,r)){const d=r.stack;r.stack=[],o=r.enter("autolink");let c=s.move("<");return c+=s.move(r.containerPhrasing(e,m({before:c,after:">"},s.current()))),c+=s.move(">"),o(),r.stack=d,c}o=r.enter("link"),l=r.enter("label");let u=s.move("[");return u+=s.move(r.containerPhrasing(e,m({before:u,after:"]("},s.current()))),u+=s.move("]("),l(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(l=r.enter("destinationLiteral"),u+=s.move("<"),u+=s.move(r.safe(e.url,m({before:u,after:">"},s.current()))),u+=s.move(">")):(l=r.enter("destinationRaw"),u+=s.move(r.safe(e.url,m({before:u,after:e.title?" ":")"},s.current())))),l(),e.title&&(l=r.enter(`title${i}`),u+=s.move(" "+a),u+=s.move(r.safe(e.title,m({before:u,after:a},s.current()))),u+=s.move(a),l()),u+=s.move(")"),o(),u}function Gw(e,t,r){return eu(e,r)?"<":"["}ru.peek=Xw;function ru(e,t,r,n){const a=e.referenceType,i=r.enter("linkReference");let s=r.enter("label");const o=r.createTracker(n);let l=o.move("[");const u=r.containerPhrasing(e,m({before:l,after:"]"},o.current()));l+=o.move(u+"]["),s();const d=r.stack;r.stack=[],s=r.enter("reference");const c=r.safe(r.associationId(e),m({before:l,after:"]"},o.current()));return s(),r.stack=d,i(),a==="full"||!u||u!==c?l+=o.move(c+"]"):a==="shortcut"?l=l.slice(0,-1):l+=o.move("]"),l}function Xw(){return"["}function Qa(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function Qw(e){const t=Qa(e),r=e.options.bulletOther;if(!r)return t==="*"?"-":"*";if(r!=="*"&&r!=="+"&&r!=="-")throw new Error("Cannot serialize items with `"+r+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(r===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+r+"`) to be different");return r}function Zw(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function nu(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function ex(e,t,r,n){const a=r.enter("list"),i=r.bulletCurrent;let s=e.ordered?Zw(r):Qa(r);const o=e.ordered?s==="."?")":".":Qw(r);let l=t&&r.bulletLastUsed?s===r.bulletLastUsed:!1;if(!e.ordered){const d=e.children?e.children[0]:void 0;if((s==="*"||s==="-")&&d&&(!d.children||!d.children[0])&&r.stack[r.stack.length-1]==="list"&&r.stack[r.stack.length-2]==="listItem"&&r.stack[r.stack.length-3]==="list"&&r.stack[r.stack.length-4]==="listItem"&&r.indexStack[r.indexStack.length-1]===0&&r.indexStack[r.indexStack.length-2]===0&&r.indexStack[r.indexStack.length-3]===0&&(l=!0),nu(r)===s&&d){let c=-1;for(;++c<e.children.length;){const h=e.children[c];if(h&&h.type==="listItem"&&h.children&&h.children[0]&&h.children[0].type==="thematicBreak"){l=!0;break}}}}l&&(s=o),r.bulletCurrent=s;const u=r.containerFlow(e,n);return r.bulletLastUsed=s,r.bulletCurrent=i,a(),u}function tx(e){const t=e.options.listItemIndent||"one";if(t!=="tab"&&t!=="one"&&t!=="mixed")throw new Error("Cannot serialize items with `"+t+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return t}function rx(e,t,r,n){const a=tx(r);let i=r.bulletCurrent||Qa(r);t&&t.type==="list"&&t.ordered&&(i=(typeof t.start=="number"&&t.start>-1?t.start:1)+(r.options.incrementListMarker===!1?0:t.children.indexOf(e))+i);let s=i.length+1;(a==="tab"||a==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(s=Math.ceil(s/4)*4);const o=r.createTracker(n);o.move(i+" ".repeat(s-i.length)),o.shift(s);const l=r.enter("listItem"),u=r.indentLines(r.containerFlow(e,o.current()),d);return l(),u;function d(c,h,f){return h?(f?"":" ".repeat(s))+c:(f?i:i+" ".repeat(s-i.length))+c}}function nx(e,t,r,n){const a=r.enter("paragraph"),i=r.enter("phrasing"),s=r.containerPhrasing(e,n);return i(),a(),s}const ax=fn(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function ix(e,t,r,n){return(e.children.some(function(s){return ax(s)})?r.containerPhrasing:r.containerFlow).call(r,e,n)}function sx(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}au.peek=ox;function au(e,t,r,n){const a=sx(r),i=r.enter("strong"),s=r.createTracker(n),o=s.move(a+a);let l=s.move(r.containerPhrasing(e,m({after:a,before:o},s.current())));const u=l.charCodeAt(0),d=gn(n.before.charCodeAt(n.before.length-1),u,a);d.inside&&(l=Ir(u)+l.slice(1));const c=l.charCodeAt(l.length-1),h=gn(n.after.charCodeAt(0),c,a);h.inside&&(l=l.slice(0,-1)+Ir(c));const f=s.move(a+a);return i(),r.attentionEncodeSurroundingInfo={after:h.outside,before:d.outside},o+l+f}function ox(e,t,r){return r.options.strong||"*"}function lx(e,t,r,n){return r.safe(e.value,n)}function ux(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function cx(e,t,r){const n=(nu(r)+(r.options.ruleSpaces?" ":"")).repeat(ux(r));return r.options.ruleSpaces?n.slice(0,-1):n}const iu={blockquote:Lw,break:Yl,code:Rw,definition:$w,emphasis:Kl,hardBreak:Yl,heading:Vw,html:Gl,image:Xl,imageReference:Ql,inlineCode:Zl,link:tu,linkReference:ru,list:ex,listItem:rx,paragraph:nx,root:ix,strong:au,text:lx,thematicBreak:cx};function dx(){return{enter:{table:hx,tableData:su,tableHeader:su,tableRow:px},exit:{codeText:mx,table:fx,tableData:Za,tableHeader:Za,tableRow:Za}}}function hx(e){const t=e._align;this.enter({type:"table",align:t.map(function(r){return r==="none"?null:r}),children:[]},e),this.data.inTable=!0}function fx(e){this.exit(e),this.data.inTable=void 0}function px(e){this.enter({type:"tableRow",children:[]},e)}function Za(e){this.exit(e)}function su(e){this.enter({type:"tableCell",children:[]},e)}function mx(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,gx));const r=this.stack[this.stack.length-1];r.type,r.value=t,this.exit(e)}function gx(e,t){return t==="|"?t:e}function yx(e){const t=e||{},r=t.tableCellPadding,n=t.tablePipeAlign,a=t.stringLength,i=r?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
34
+ `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:h,table:s,tableCell:l,tableRow:o}};function s(f,g,v,b){return u(d(f,v,b),f.align)}function o(f,g,v,b){const w=c(f,v,b),_=u([w]);return _.slice(0,_.indexOf(`
35
+ `))}function l(f,g,v,b){const w=v.enter("tableCell"),_=v.enter("phrasing"),T=v.containerPhrasing(f,E(m({},b),{before:i,after:i}));return _(),w(),T}function u(f,g){return Pw(f,{align:g,alignDelimiters:n,padding:r,stringLength:a})}function d(f,g,v){const b=f.children;let w=-1;const _=[],T=g.enter("table");for(;++w<b.length;)_[w]=c(b[w],g,v);return T(),_}function c(f,g,v){const b=f.children;let w=-1;const _=[],T=g.enter("tableRow");for(;++w<b.length;)_[w]=l(b[w],f,g,v);return T(),_}function h(f,g,v){let b=iu.inlineCode(f,g,v);return v.stack.includes("tableCell")&&(b=b.replace(/\|/g,"\\$&")),b}}function bx(){return{exit:{taskListCheckValueChecked:ou,taskListCheckValueUnchecked:ou,paragraph:xx}}}function wx(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:vx}}}function ou(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function xx(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const r=this.stack[this.stack.length-1];r.type;const n=r.children[0];if(n&&n.type==="text"){const a=t.children;let i=-1,s;for(;++i<a.length;){const o=a[i];if(o.type==="paragraph"){s=o;break}}s===r&&(n.value=n.value.slice(1),n.value.length===0?r.children.shift():r.position&&n.position&&typeof n.position.start.offset=="number"&&(n.position.start.column++,n.position.start.offset++,r.position.start=Object.assign({},n.position.start)))}}this.exit(e)}function vx(e,t,r,n){const a=e.children[0],i=typeof e.checked=="boolean"&&a&&a.type==="paragraph",s="["+(e.checked?"x":" ")+"] ",o=r.createTracker(n);i&&o.move(s);let l=iu.listItem(e,t,r,m(m({},n),o.current()));return i&&(l=l.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,u)),l;function u(d){return d+s}}function kx(){return[ew(),vw(),Tw(),dx(),bx()]}function Sx(e){return{extensions:[tw(),kw(e),Cw(),yx(e),wx()]}}const _x={tokenize:Mx,partial:!0},lu={tokenize:Px,partial:!0},uu={tokenize:Nx,partial:!0},cu={tokenize:Lx,partial:!0},Tx={tokenize:Dx,partial:!0},du={name:"wwwAutolink",tokenize:Ex,previous:fu},hu={name:"protocolAutolink",tokenize:Ax,previous:pu},mt={name:"emailAutolink",tokenize:Ix,previous:mu},ct={};function Cx(){return{text:ct}}let Nt=48;for(;Nt<123;)ct[Nt]=mt,Nt++,Nt===58?Nt=65:Nt===91&&(Nt=97);ct[43]=mt,ct[45]=mt,ct[46]=mt,ct[95]=mt,ct[72]=[mt,hu],ct[104]=[mt,hu],ct[87]=[mt,du],ct[119]=[mt,du];function Ix(e,t,r){const n=this;let a,i;return s;function s(c){return!ei(c)||!mu.call(n,n.previous)||ti(n.events)?r(c):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),o(c))}function o(c){return ei(c)?(e.consume(c),o):c===64?(e.consume(c),l):r(c)}function l(c){return c===46?e.check(Tx,d,u)(c):c===45||c===95||Pe(c)?(i=!0,e.consume(c),l):d(c)}function u(c){return e.consume(c),a=!0,l}function d(c){return i&&a&&Be(n.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(c)):r(c)}}function Ex(e,t,r){const n=this;return a;function a(s){return s!==87&&s!==119||!fu.call(n,n.previous)||ti(n.events)?r(s):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(_x,e.attempt(lu,e.attempt(uu,i),r),r)(s))}function i(s){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(s)}}function Ax(e,t,r){const n=this;let a="",i=!1;return s;function s(c){return(c===72||c===104)&&pu.call(n,n.previous)&&!ti(n.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),a+=String.fromCodePoint(c),e.consume(c),o):r(c)}function o(c){if(Be(c)&&a.length<5)return a+=String.fromCodePoint(c),e.consume(c),o;if(c===58){const h=a.toLowerCase();if(h==="http"||h==="https")return e.consume(c),l}return r(c)}function l(c){return c===47?(e.consume(c),i?u:(i=!0,l)):r(c)}function u(c){return c===null||nn(c)||ce(c)||Pt(c)||an(c)?r(c):e.attempt(lu,e.attempt(uu,d),r)(c)}function d(c){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(c)}}function Mx(e,t,r){let n=0;return a;function a(s){return(s===87||s===119)&&n<3?(n++,e.consume(s),a):s===46&&n===3?(e.consume(s),i):r(s)}function i(s){return s===null?r(s):t(s)}}function Px(e,t,r){let n,a,i;return s;function s(u){return u===46||u===95?e.check(cu,l,o)(u):u===null||ce(u)||Pt(u)||u!==45&&an(u)?l(u):(i=!0,e.consume(u),s)}function o(u){return u===95?n=!0:(a=n,n=void 0),e.consume(u),s}function l(u){return a||n||!i?r(u):t(u)}}function Nx(e,t){let r=0,n=0;return a;function a(s){return s===40?(r++,e.consume(s),a):s===41&&n<r?i(s):s===33||s===34||s===38||s===39||s===41||s===42||s===44||s===46||s===58||s===59||s===60||s===63||s===93||s===95||s===126?e.check(cu,t,i)(s):s===null||ce(s)||Pt(s)?t(s):(e.consume(s),a)}function i(s){return s===41&&n++,e.consume(s),a}}function Lx(e,t,r){return n;function n(o){return o===33||o===34||o===39||o===41||o===42||o===44||o===46||o===58||o===59||o===63||o===95||o===126?(e.consume(o),n):o===38?(e.consume(o),i):o===93?(e.consume(o),a):o===60||o===null||ce(o)||Pt(o)?t(o):r(o)}function a(o){return o===null||o===40||o===91||ce(o)||Pt(o)?t(o):n(o)}function i(o){return Be(o)?s(o):r(o)}function s(o){return o===59?(e.consume(o),n):Be(o)?(e.consume(o),s):r(o)}}function Dx(e,t,r){return n;function n(i){return e.consume(i),a}function a(i){return Pe(i)?r(i):t(i)}}function fu(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||ce(e)}function pu(e){return!Be(e)}function mu(e){return!(e===47||ei(e))}function ei(e){return e===43||e===45||e===46||e===95||Pe(e)}function ti(e){let t=e.length,r=!1;for(;t--;){const n=e[t][1];if((n.type==="labelLink"||n.type==="labelImage")&&!n._balanced){r=!0;break}if(n._gfmAutolinkLiteralWalkedInto){r=!1;break}}return e.length>0&&!r&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),r}const Ox={tokenize:Hx,partial:!0};function Fx(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:jx,continuation:{tokenize:$x},exit:Ux}},text:{91:{name:"gfmFootnoteCall",tokenize:Rx},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:Bx,resolveTo:zx}}}}function Bx(e,t,r){const n=this;let a=n.events.length;const i=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let s;for(;a--;){const l=n.events[a][1];if(l.type==="labelImage"){s=l;break}if(l.type==="gfmFootnoteCall"||l.type==="labelLink"||l.type==="label"||l.type==="image"||l.type==="link")break}return o;function o(l){if(!s||!s._balanced)return r(l);const u=it(n.sliceSerialize({start:s.end,end:n.now()}));return u.codePointAt(0)!==94||!i.includes(u.slice(1))?r(l):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(l),e.exit("gfmFootnoteCallLabelMarker"),t(l))}}function zx(e,t){let r=e.length;for(;r--;)if(e[r][1].type==="labelImage"&&e[r][0]==="enter"){e[r][1];break}e[r+1][1].type="data",e[r+3][1].type="gfmFootnoteCallLabelMarker";const n={type:"gfmFootnoteCall",start:Object.assign({},e[r+3][1].start),end:Object.assign({},e[e.length-1][1].end)},a={type:"gfmFootnoteCallMarker",start:Object.assign({},e[r+3][1].end),end:Object.assign({},e[r+3][1].end)};a.end.column++,a.end.offset++,a.end._bufferIndex++;const i={type:"gfmFootnoteCallString",start:Object.assign({},a.end),end:Object.assign({},e[e.length-1][1].start)},s={type:"chunkString",contentType:"string",start:Object.assign({},i.start),end:Object.assign({},i.end)},o=[e[r+1],e[r+2],["enter",n,t],e[r+3],e[r+4],["enter",a,t],["exit",a,t],["enter",i,t],["enter",s,t],["exit",s,t],["exit",i,t],e[e.length-2],e[e.length-1],["exit",n,t]];return e.splice(r,e.length-r+1,...o),e}function Rx(e,t,r){const n=this,a=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let i=0,s;return o;function o(c){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(c),e.exit("gfmFootnoteCallLabelMarker"),l}function l(c){return c!==94?r(c):(e.enter("gfmFootnoteCallMarker"),e.consume(c),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",u)}function u(c){if(i>999||c===93&&!s||c===null||c===91||ce(c))return r(c);if(c===93){e.exit("chunkString");const h=e.exit("gfmFootnoteCallString");return a.includes(it(n.sliceSerialize(h)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(c),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):r(c)}return ce(c)||(s=!0),i++,e.consume(c),c===92?d:u}function d(c){return c===91||c===92||c===93?(e.consume(c),i++,u):u(c)}}function jx(e,t,r){const n=this,a=n.parser.gfmFootnotes||(n.parser.gfmFootnotes=[]);let i,s=0,o;return l;function l(g){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),u}function u(g){return g===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",d):r(g)}function d(g){if(s>999||g===93&&!o||g===null||g===91||ce(g))return r(g);if(g===93){e.exit("chunkString");const v=e.exit("gfmFootnoteDefinitionLabelString");return i=it(n.sliceSerialize(v)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),h}return ce(g)||(o=!0),s++,e.consume(g),g===92?c:d}function c(g){return g===91||g===92||g===93?(e.consume(g),s++,d):d(g)}function h(g){return g===58?(e.enter("definitionMarker"),e.consume(g),e.exit("definitionMarker"),a.includes(i)||a.push(i),ie(e,f,"gfmFootnoteDefinitionWhitespace")):r(g)}function f(g){return t(g)}}function $x(e,t,r){return e.check(vr,t,e.attempt(Ox,t,r))}function Ux(e){e.exit("gfmFootnoteDefinition")}function Hx(e,t,r){const n=this;return ie(e,a,"gfmFootnoteDefinitionIndent",5);function a(i){const s=n.events[n.events.length-1];return s&&s[1].type==="gfmFootnoteDefinitionIndent"&&s[2].sliceSerialize(s[1],!0).length===4?t(i):r(i)}}function qx(e){let r=(e||{}).singleTilde;const n={name:"strikethrough",tokenize:i,resolveAll:a};return r==null&&(r=!0),{text:{126:n},insideSpan:{null:[n]},attentionMarkers:{null:[126]}};function a(s,o){let l=-1;for(;++l<s.length;)if(s[l][0]==="enter"&&s[l][1].type==="strikethroughSequenceTemporary"&&s[l][1]._close){let u=l;for(;u--;)if(s[u][0]==="exit"&&s[u][1].type==="strikethroughSequenceTemporary"&&s[u][1]._open&&s[l][1].end.offset-s[l][1].start.offset===s[u][1].end.offset-s[u][1].start.offset){s[l][1].type="strikethroughSequence",s[u][1].type="strikethroughSequence";const d={type:"strikethrough",start:Object.assign({},s[u][1].start),end:Object.assign({},s[l][1].end)},c={type:"strikethroughText",start:Object.assign({},s[u][1].end),end:Object.assign({},s[l][1].start)},h=[["enter",d,o],["enter",s[u][1],o],["exit",s[u][1],o],["enter",c,o]],f=o.parser.constructs.insideSpan.null;f&&We(h,h.length,0,sn(f,s.slice(u+1,l),o)),We(h,h.length,0,[["exit",c,o],["enter",s[l][1],o],["exit",s[l][1],o],["exit",d,o]]),We(s,u-1,l-u+3,h),l=u+h.length-2;break}}for(l=-1;++l<s.length;)s[l][1].type==="strikethroughSequenceTemporary"&&(s[l][1].type="data");return s}function i(s,o,l){const u=this.previous,d=this.events;let c=0;return h;function h(g){return u===126&&d[d.length-1][1].type!=="characterEscape"?l(g):(s.enter("strikethroughSequenceTemporary"),f(g))}function f(g){const v=Kt(u);if(g===126)return c>1?l(g):(s.consume(g),c++,f);if(c<2&&!r)return l(g);const b=s.exit("strikethroughSequenceTemporary"),w=Kt(g);return b._open=!w||w===2&&!!v,b._close=!v||v===2&&!!w,o(g)}}}class Vx{constructor(){this.map=[]}add(t,r,n){Wx(this,t,r,n)}consume(t){if(this.map.sort(function(i,s){return i[0]-s[0]}),this.map.length===0)return;let r=this.map.length;const n=[];for(;r>0;)r-=1,n.push(t.slice(this.map[r][0]+this.map[r][1]),this.map[r][2]),t.length=this.map[r][0];n.push(t.slice()),t.length=0;let a=n.pop();for(;a;){for(const i of a)t.push(i);a=n.pop()}this.map.length=0}}function Wx(e,t,r,n){let a=0;if(!(r===0&&n.length===0)){for(;a<e.map.length;){if(e.map[a][0]===t){e.map[a][1]+=r,e.map[a][2].push(...n);return}a+=1}e.map.push([t,r,n])}}function Jx(e,t){let r=!1;const n=[];for(;t<e.length;){const a=e[t];if(r){if(a[0]==="enter")a[1].type==="tableContent"&&n.push(e[t+1][1].type==="tableDelimiterMarker"?"left":"none");else if(a[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){const i=n.length-1;n[i]=n[i]==="left"?"center":"right"}}else if(a[1].type==="tableDelimiterRow")break}else a[0]==="enter"&&a[1].type==="tableDelimiterRow"&&(r=!0);t+=1}return n}function Yx(){return{flow:{null:{name:"table",tokenize:Kx,resolveAll:Gx}}}}function Kx(e,t,r){const n=this;let a=0,i=0,s;return o;function o(S){let N=n.events.length-1;for(;N>-1;){const R=n.events[N][1].type;if(R==="lineEnding"||R==="linePrefix")N--;else break}const M=N>-1?n.events[N][1].type:null,W=M==="tableHead"||M==="tableRow"?I:l;return W===I&&n.parser.lazy[n.now().line]?r(S):W(S)}function l(S){return e.enter("tableHead"),e.enter("tableRow"),u(S)}function u(S){return S===124||(s=!0,i+=1),d(S)}function d(S){return S===null?r(S):J(S)?i>1?(i=0,n.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(S),e.exit("lineEnding"),f):r(S):re(S)?ie(e,d,"whitespace")(S):(i+=1,s&&(s=!1,a+=1),S===124?(e.enter("tableCellDivider"),e.consume(S),e.exit("tableCellDivider"),s=!0,d):(e.enter("data"),c(S)))}function c(S){return S===null||S===124||ce(S)?(e.exit("data"),d(S)):(e.consume(S),S===92?h:c)}function h(S){return S===92||S===124?(e.consume(S),c):c(S)}function f(S){return n.interrupt=!1,n.parser.lazy[n.now().line]?r(S):(e.enter("tableDelimiterRow"),s=!1,re(S)?ie(e,g,"linePrefix",n.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(S):g(S))}function g(S){return S===45||S===58?b(S):S===124?(s=!0,e.enter("tableCellDivider"),e.consume(S),e.exit("tableCellDivider"),v):j(S)}function v(S){return re(S)?ie(e,b,"whitespace")(S):b(S)}function b(S){return S===58?(i+=1,s=!0,e.enter("tableDelimiterMarker"),e.consume(S),e.exit("tableDelimiterMarker"),w):S===45?(i+=1,w(S)):S===null||J(S)?B(S):j(S)}function w(S){return S===45?(e.enter("tableDelimiterFiller"),_(S)):j(S)}function _(S){return S===45?(e.consume(S),_):S===58?(s=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(S),e.exit("tableDelimiterMarker"),T):(e.exit("tableDelimiterFiller"),T(S))}function T(S){return re(S)?ie(e,B,"whitespace")(S):B(S)}function B(S){return S===124?g(S):S===null||J(S)?!s||a!==i?j(S):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(S)):j(S)}function j(S){return r(S)}function I(S){return e.enter("tableRow"),z(S)}function z(S){return S===124?(e.enter("tableCellDivider"),e.consume(S),e.exit("tableCellDivider"),z):S===null||J(S)?(e.exit("tableRow"),t(S)):re(S)?ie(e,z,"whitespace")(S):(e.enter("data"),H(S))}function H(S){return S===null||S===124||ce(S)?(e.exit("data"),z(S)):(e.consume(S),S===92?O:H)}function O(S){return S===92||S===124?(e.consume(S),H):H(S)}}function Gx(e,t){let r=-1,n=!0,a=0,i=[0,0,0,0],s=[0,0,0,0],o=!1,l=0,u,d,c;const h=new Vx;for(;++r<e.length;){const f=e[r],g=f[1];f[0]==="enter"?g.type==="tableHead"?(o=!1,l!==0&&(gu(h,t,l,u,d),d=void 0,l=0),u={type:"table",start:Object.assign({},g.start),end:Object.assign({},g.end)},h.add(r,0,[["enter",u,t]])):g.type==="tableRow"||g.type==="tableDelimiterRow"?(n=!0,c=void 0,i=[0,0,0,0],s=[0,r+1,0,0],o&&(o=!1,d={type:"tableBody",start:Object.assign({},g.start),end:Object.assign({},g.end)},h.add(r,0,[["enter",d,t]])),a=g.type==="tableDelimiterRow"?2:d?3:1):a&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")?(n=!1,s[2]===0&&(i[1]!==0&&(s[0]=s[1],c=yn(h,t,i,a,void 0,c),i=[0,0,0,0]),s[2]=r)):g.type==="tableCellDivider"&&(n?n=!1:(i[1]!==0&&(s[0]=s[1],c=yn(h,t,i,a,void 0,c)),i=s,s=[i[1],r,0,0])):g.type==="tableHead"?(o=!0,l=r):g.type==="tableRow"||g.type==="tableDelimiterRow"?(l=r,i[1]!==0?(s[0]=s[1],c=yn(h,t,i,a,r,c)):s[1]!==0&&(c=yn(h,t,s,a,r,c)),a=0):a&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")&&(s[3]=r)}for(l!==0&&gu(h,t,l,u,d),h.consume(t.events),r=-1;++r<t.events.length;){const f=t.events[r];f[0]==="enter"&&f[1].type==="table"&&(f[1]._align=Jx(t.events,r))}return e}function yn(e,t,r,n,a,i){const s=n===1?"tableHeader":n===2?"tableDelimiter":"tableData",o="tableContent";r[0]!==0&&(i.end=Object.assign({},Xt(t.events,r[0])),e.add(r[0],0,[["exit",i,t]]));const l=Xt(t.events,r[1]);if(i={type:s,start:Object.assign({},l),end:Object.assign({},l)},e.add(r[1],0,[["enter",i,t]]),r[2]!==0){const u=Xt(t.events,r[2]),d=Xt(t.events,r[3]),c={type:o,start:Object.assign({},u),end:Object.assign({},d)};if(e.add(r[2],0,[["enter",c,t]]),n!==2){const h=t.events[r[2]],f=t.events[r[3]];if(h[1].end=Object.assign({},f[1].end),h[1].type="chunkText",h[1].contentType="text",r[3]>r[2]+1){const g=r[2]+1,v=r[3]-r[2]-1;e.add(g,v,[])}}e.add(r[3]+1,0,[["exit",c,t]])}return a!==void 0&&(i.end=Object.assign({},Xt(t.events,a)),e.add(a,0,[["exit",i,t]]),i=void 0),i}function gu(e,t,r,n,a){const i=[],s=Xt(t.events,r);a&&(a.end=Object.assign({},s),i.push(["exit",a,t])),n.end=Object.assign({},s),i.push(["exit",n,t]),e.add(r+1,0,i)}function Xt(e,t){const r=e[t],n=r[0]==="enter"?"start":"end";return r[1][n]}const Xx={name:"tasklistCheck",tokenize:Zx};function Qx(){return{text:{91:Xx}}}function Zx(e,t,r){const n=this;return a;function a(l){return n.previous!==null||!n._gfmTasklistFirstContentOfListItem?r(l):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(l),e.exit("taskListCheckMarker"),i)}function i(l){return ce(l)?(e.enter("taskListCheckValueUnchecked"),e.consume(l),e.exit("taskListCheckValueUnchecked"),s):l===88||l===120?(e.enter("taskListCheckValueChecked"),e.consume(l),e.exit("taskListCheckValueChecked"),s):r(l)}function s(l){return l===93?(e.enter("taskListCheckMarker"),e.consume(l),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),o):r(l)}function o(l){return J(l)?t(l):re(l)?e.check({tokenize:ev},t,r)(l):r(l)}}function ev(e,t,r){return ie(e,n,"whitespace");function n(a){return a===null?r(a):t(a)}}function tv(e){return Wo([Cx(),Fx(),qx(e),Yx(),Qx()])}const rv={};function nv(e){const t=this,r=e||rv,n=t.data(),a=n.micromarkExtensions||(n.micromarkExtensions=[]),i=n.fromMarkdownExtensions||(n.fromMarkdownExtensions=[]),s=n.toMarkdownExtensions||(n.toMarkdownExtensions=[]);a.push(tv(r)),i.push(kx()),s.push(Sx(r))}function Te(...e){return e.filter(Boolean).join(" ")}const av=({content:e})=>p.jsx(Yb,{remarkPlugins:[nv],className:"cuadra-aui-md",components:ov,children:e}),ri=y.memo(av),iv=({language:e,code:t})=>{const{isCopied:r,copyToClipboard:n}=sv(),a=()=>{!t||r||n(t)};return p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-between cuadra-gap-4 cuadra-mt-4 cuadra-rounded-t-lg cuadra-bg-muted/50 cuadra-border-b cuadra-border-border cuadra-px-4 cuadra-py-2 cuadra-text-sm cuadra-font-normal cuadra-text-foreground cuadra-font-brand",children:[p.jsx("span",{className:"cuadra-lowercase [&>span]:cuadra-text-xs cuadra-font-brand",children:e}),p.jsxs("button",{onClick:a,className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-muted cuadra-transition-colors","aria-label":"Copy code",children:[!r&&p.jsx($u,{className:"cuadra-h-4 cuadra-w-4"}),r&&p.jsx(Ru,{className:"cuadra-h-4 cuadra-w-4"})]})]})},sv=({copiedDuration:e=3e3}={})=>{const[t,r]=y.useState(!1);return{isCopied:t,copyToClipboard:a=>{a&&navigator.clipboard.writeText(a).then(()=>{r(!0),setTimeout(()=>r(!1),e)})}}},ov=Nb({h1:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("h1",m({className:Te("cuadra-mb-6 cuadra-scroll-m-20 cuadra-text-2xl cuadra-font-normal cuadra-tracking-tight last:cuadra-mb-0 font-brand",e)},t))},h2:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("h2",m({className:Te("cuadra-mb-4 cuadra-mt-6 cuadra-scroll-m-20 cuadra-text-xl cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},h3:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("h3",m({className:Te("cuadra-mb-3 cuadra-mt-5 cuadra-scroll-m-20 cuadra-text-lg cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},h4:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("h4",m({className:Te("cuadra-mb-4 cuadra-mt-6 cuadra-scroll-m-20 cuadra-text-xl cuadra-font-normal cuadra-tracking-tight first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},h5:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("h5",m({className:Te("cuadra-my-4 cuadra-text-lg cuadra-font-normal first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},h6:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("h6",m({className:Te("cuadra-my-4 cuadra-font-normal first:cuadra-mb-0 font-brand",e)},t))},p:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("p",m({className:Te("cuadra-mb-5 cuadra-mt-5 cuadra-leading-7 first:cuadra-mt-0 last:cuadra-mb-0 font-brand",e)},t))},a:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("a",m({className:Te("cuadra-text-primary cuadra-font-medium cuadra-underline cuadra-underline-offset-4 font-brand",e)},t))},blockquote:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("blockquote",m({className:Te("cuadra-border-l-2 cuadra-pl-6 cuadra-italic font-brand",e)},t))},ul:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("ul",m({className:Te("cuadra-my-5 cuadra-ml-6 cuadra-list-disc [&>li]:cuadra-mt-2 font-brand",e)},t))},ol:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("ol",m({className:Te("cuadra-my-5 cuadra-ml-6 cuadra-list-decimal [&>li]:cuadra-mt-2 font-brand",e)},t))},hr:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("hr",m({className:Te("cuadra-my-5 cuadra-border-b",e)},t))},table:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("table",m({className:Te("cuadra-my-5 cuadra-w-full cuadra-border-separate cuadra-border-spacing-0 cuadra-overflow-y-auto font-brand",e)},t))},th:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("th",m({className:Te("cuadra-bg-muted cuadra-px-4 cuadra-py-2 cuadra-text-left cuadra-font-normal first:cuadra-rounded-tl-lg last:cuadra-rounded-tr-lg [&[align=center]]:cuadra-text-center [&[align=right]]:cuadra-text-right font-brand",e)},t))},td:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("td",m({className:Te("cuadra-border-b cuadra-border-l cuadra-px-4 cuadra-py-2 cuadra-text-left last:cuadra-border-r [&[align=center]]:cuadra-text-center [&[align=right]]:cuadra-text-right font-brand",e)},t))},tr:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("tr",m({className:Te("cuadra-m-0 cuadra-border-b cuadra-p-0 first:cuadra-border-t [&:last-child>td:first-child]:cuadra-rounded-bl-lg [&:last-child>td:last-child]:cuadra-rounded-br-lg",e)},t))},sup:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("sup",m({className:Te("[&>a]:cuadra-text-xs [&>a]:cuadra-no-underline font-brand",e)},t))},pre:r=>{var n=r,{className:e}=n,t=V(n,["className"]);return p.jsx("pre",m({className:Te("cuadra-overflow-x-auto cuadra-whitespace-pre-wrap cuadra-break-words cuadra-rounded-b-lg !cuadra-rounded-t-none cuadra-bg-muted cuadra-p-4 cuadra-text-foreground font-brand",e)},t))},code:function(n){var a=n,{className:t}=a,r=V(a,["className"]);const i=Fl();return p.jsx("code",m({className:Te(!i&&"cuadra-bg-muted cuadra-rounded cuadra-border cuadra-font-normal font-brand",t)},r))},CodeHeader:iv});function yu(n){var a=n,{className:e="",variant:t="default"}=a,r=V(a,["className","variant"]);const i="cuadra-inline-flex cuadra-items-center cuadra-rounded-md cuadra-px-3 cuadra-py-1.5 cuadra-text-xs cuadra-font-medium font-brand",s={default:"cuadra-border cuadra-border-border cuadra-bg-muted cuadra-text-muted-foreground",subtle:"cuadra-border cuadra-border-border/50 cuadra-bg-muted/50 cuadra-text-muted-foreground",outline:"cuadra-border cuadra-border-border cuadra-bg-background cuadra-text-foreground",ghost:"cuadra-text-muted-foreground"};return p.jsx("div",m({className:`${i} ${s[t]||s.default} ${e}`},r))}function lv(e){const t=new Map;for(const r of e){const n=t.get(r.filename);(!n||r.score>n.score)&&t.set(r.filename,r)}return Array.from(t.values()).sort((r,n)=>n.score-r.score)}function uv({sources:e,maxVisible:t=3}){if(!e||e.length===0)return null;const r=lv(e),n=r.slice(0,t),a=r.length-t;return p.jsxs("div",{className:"cuadra-mt-4 cuadra-pt-3 cuadra-border-t cuadra-border-border",children:[p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1.5 cuadra-mb-2.5",children:[p.jsx(ui,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-text-muted-foreground"}),p.jsx("span",{className:"cuadra-text-xs cuadra-font-medium cuadra-text-muted-foreground font-brand",children:"Sources"})]}),p.jsxs("div",{className:"cuadra-flex cuadra-flex-wrap cuadra-gap-2",children:[n.map((i,s)=>p.jsx(dv,{source:i},i.sourceId||s)),a>0&&p.jsxs(yu,{variant:"subtle",children:["+",a," more"]})]})]})}function cv(e){var r;switch((r=e.split(".").pop())==null?void 0:r.toLowerCase()){case"csv":case"xlsx":case"xls":return Hu;case"md":case"txt":return qu;default:return ui}}function dv({source:e}){const{filename:t,score:r}=e,n=cv(t);return p.jsxs(yu,{className:"cuadra-gap-2 cuadra-cursor-default",title:r<1?`${Math.round(r*100)}% relevant`:void 0,children:[p.jsx(n,{className:"cuadra-h-3.5 cuadra-w-3.5 cuadra-shrink-0 cuadra-opacity-60"}),p.jsx("span",{className:"cuadra-truncate cuadra-max-w-[180px]",children:t}),r<1&&r>0&&p.jsxs("span",{className:"cuadra-opacity-50 cuadra-text-[10px] cuadra-tabular-nums",children:[Math.round(r*100),"%"]})]})}const bu=y.forwardRef(function({welcomeTitle:t="Hi, how can I help you today?",welcomeSubtitle:r="Start exploring our platform and discover what you can build.",extraTopPadding:n,suggestions:a,inputPlaceholder:i="Type your message...",enableAttachments:s=!1,preMadeResponseDelay:o=1e3,streamingSpeed:l=50,safeArea:u=!1},d){const c=us(),h=pe(),[f,g]=y.useState(!1),[v,b]=y.useState(null),[w,_]=y.useState(!1),T=y.useCallback((z,H,O)=>{var S,N;if(!w)try{const M=(S=O==null?void 0:O.streamingSpeed)!=null?S:l,W=(N=O==null?void 0:O.delay)!=null?N:o;mo(z,H,M,W),h.composer().setText(z),setTimeout(()=>{h.composer().send()},10)}catch(M){}},[w,l,o,h]),B=y.useCallback(z=>{try{h.composer().setText(z),setTimeout(()=>{h.composer().send()},10)}catch(H){}},[h]),j=y.useCallback(z=>P(null,null,function*(){var H;if(!(w||!c))try{if(z.response){const O=(H=z.responseDelay)!=null?H:o;yield T(z.prompt,z.response,{delay:O,streamingSpeed:l})}else B(z.prompt)}catch(O){}}),[c,w,o,l,T,B]),I=y.useCallback(()=>{try{const z=window.__cuadraThreadListRuntime;z!=null&&z.switchToNewThread&&z.switchToNewThread()}catch(z){}},[]);return y.useImperativeHandle(d,()=>({sendMessage:B,sendPreMadeQA:T,clearChat:I}),[B,T,I]),y.useEffect(()=>{var z,H;if(!c){g(!1);return}try{const O=c==null?void 0:c.store;if(!O){g(!1);return}const S=(z=O.subscribe)==null?void 0:z.call(O,M=>{const W=M==null?void 0:M.threadId,R=(M==null?void 0:M.messages)||[],F=(M==null?void 0:M.isLoadingHistory)||!1,Q=R.length;W&&W!==v&&b(W),g(F&&Q===0)}),N=(H=O.getState)==null?void 0:H.call(O);if(N){const M=N==null?void 0:N.threadId,W=(N==null?void 0:N.messages)||[],R=(N==null?void 0:N.isLoadingHistory)||!1,F=W.length;M&&M!==v&&b(M),g(R&&F===0)}return()=>{S&&S()}}catch(O){g(!1)}},[c,v]),p.jsxs(eo,{className:"cuadra-bg-inherit cuadra-flex cuadra-flex-col cuadra-w-full cuadra-h-full",children:[p.jsx(no,{className:"cuadra-w-full cuadra-bg-inherit cuadra-px-4 cuadra-flex-1 cuadra-min-h-0 cuadra-overflow-y-auto cuadra-relative scrollbar-thin cuadra-pt-4",style:n?{paddingTop:n}:void 0,children:f?p.jsx("div",{className:"cuadra-absolute cuadra-inset-0 cuadra-flex cuadra-items-center cuadra-justify-center",children:p.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-2",children:[p.jsx(ci,{className:"cuadra-h-6 cuadra-w-6 cuadra-animate-spin cuadra-text-muted-foreground"}),p.jsx("p",{className:"cuadra-text-sm cuadra-text-muted-foreground font-brand",children:"Loading messages..."})]})}):p.jsxs(p.Fragment,{children:[p.jsx(to,{children:p.jsx(hv,{title:t,subtitle:r,suggestions:a,onSuggestionClick:j,isProcessing:w})}),p.jsx(ap,{components:{UserMessage:fv,AssistantMessage:gv}})]})}),p.jsxs("div",{className:"cuadra-w-full cuadra-mt-3 cuadra-border-t cuadra-border-border cuadra-pt-4",style:u?{paddingBottom:"env(safe-area-inset-bottom)"}:void 0,children:[s&&p.jsx(Zs,{components:{Attachment:()=>{const z=ae(({attachment:H})=>H);return z?p.jsxs("div",{className:"cuadra-relative cuadra-inline-flex cuadra-items-center cuadra-gap-2 cuadra-mb-2 cuadra-px-2 cuadra-py-1 cuadra-rounded-md cuadra-bg-muted cuadra-border cuadra-border-border",children:[p.jsx("span",{className:"cuadra-text-xs cuadra-text-muted-foreground font-brand",children:z.name||"Attachment"}),p.jsx(ff,{asChild:!0,children:p.jsx("button",{type:"button",className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-size-4 cuadra-rounded hover:cuadra-bg-background cuadra-transition-colors","aria-label":"Remove attachment",children:p.jsx(In,{className:"cuadra-h-3 cuadra-w-3 cuadra-text-muted-foreground"})})})]}):null}}}),p.jsxs(qs,{className:"cuadra-relative !cuadra-relative cuadra-flex-1 cuadra-w-full",children:[p.jsx(Xs,{asChild:!0,children:p.jsx("textarea",{rows:3,placeholder:i,className:"cuadra-flex cuadra-min-h-[80px] cuadra-w-full cuadra-rounded-md cuadra-border cuadra-border-border cuadra-bg-background cuadra-px-3 cuadra-py-2 cuadra-text-base cuadra-text-foreground placeholder:cuadra-text-muted-foreground focus-visible:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 cuadra-resize-none font-brand",style:{paddingRight:s?"5rem":"3rem",fontSize:"1rem",borderWidth:"1px"}})}),s&&p.jsx(Kf,{multiple:!0,asChild:!0,children:p.jsx("button",{type:"button",className:"!cuadra-absolute !cuadra-bottom-2 !cuadra-right-12 cuadra-size-8 cuadra-rounded-md hover:cuadra-bg-muted cuadra-transition-colors cuadra-flex cuadra-items-center cuadra-justify-center cuadra-border cuadra-border-border",style:{position:"absolute",bottom:"0.5rem",right:"3rem"},"aria-label":"Attach file",children:p.jsx(di,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground",strokeWidth:1.5})})}),p.jsx(Mf,{asChild:!0,children:p.jsx("button",{className:"!cuadra-absolute !cuadra-bottom-2 !cuadra-right-2 cuadra-size-8 cuadra-rounded-md cuadra-shadow-sm hover:cuadra-opacity-90 disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed cuadra-flex cuadra-items-center cuadra-justify-center",style:{position:"absolute",bottom:"0.5rem",right:"0.5rem",backgroundColor:"var(--cuadra-primary)",color:"hsl(var(--cuadra-primary-foreground))"},"aria-label":"Send message",type:"button",children:p.jsx(zu,{className:"cuadra-h-4 cuadra-w-4"})})})]})]})]})});function hv({title:e,subtitle:t,suggestions:r,onSuggestionClick:n,isProcessing:a}){return p.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-h-full cuadra-py-12 cuadra-px-4 cuadra-overflow-y-auto scrollbar-hide",children:p.jsxs("div",{className:"cuadra-text-center cuadra-max-w-3xl cuadra-w-full cuadra-flex cuadra-flex-col cuadra-items-center cuadra-justify-center cuadra-min-h-full",children:[p.jsxs("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-justify-center cuadra-mb-8",children:[p.jsx("h2",{className:"cuadra-text-xl cuadra-font-normal cuadra-text-foreground cuadra-mb-2 font-brand",children:e}),p.jsx("p",{className:"cuadra-text-muted-foreground font-brand",children:t})]}),r&&r.length>0&&p.jsx("div",{className:"cuadra-grid cuadra-grid-cols-2 cuadra-gap-2 cuadra-pb-4 cuadra-w-full cuadra-max-w-2xl",children:r.map((i,s)=>p.jsx("button",{type:"button",onClick:()=>n(i),disabled:a,className:"cuadra-w-full cuadra-text-center cuadra-px-4 cuadra-py-3 cuadra-rounded-lg cuadra-border cuadra-border-border cuadra-bg-background cuadra-text-base cuadra-text-foreground font-brand cuadra-cursor-pointer focus:cuadra-outline-none focus:cuadra-ring-0 disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed",style:{borderWidth:"1px"},children:i.prompt},`suggestion-${s}`))})]})})}function fv(){return p.jsxs(ea,{className:"cuadra-grid cuadra-w-full cuadra-auto-rows-auto cuadra-grid-cols-[minmax(72px,1fr)_auto] cuadra-gap-y-2 cuadra-py-3 [&:where(>*)]:cuadra-col-start-2",children:[p.jsx(Us,{components:{Attachment:()=>{var i;const e=ae(({attachment:s})=>s);if(!e)return null;const t=e.type==="image",r=e.file,n=(i=e.content)==null?void 0:i.find(s=>s.type==="image"),a=r?URL.createObjectURL(r):n==null?void 0:n.image;return p.jsx("div",{className:"cuadra-col-start-2 cuadra-row-start-1 cuadra-mb-2 cuadra-max-w-[calc(42rem*0.8)]",children:t&&a?p.jsx("img",{src:a,alt:e.name||"Attachment",className:"cuadra-rounded-lg cuadra-border cuadra-border-border cuadra-max-h-64 cuadra-max-w-full cuadra-object-contain",style:{borderWidth:"1px"}}):p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2 cuadra-rounded-lg cuadra-border cuadra-border-border cuadra-bg-muted cuadra-px-3 cuadra-py-2",children:[p.jsx(di,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"}),p.jsx("span",{className:"cuadra-text-sm cuadra-text-foreground font-brand",children:e.name||"Attachment"})]})})}}}),p.jsx("div",{className:"cuadra-bg-muted cuadra-text-foreground cuadra-col-start-2 cuadra-row-start-2 cuadra-max-w-[calc(42rem*0.8)] cuadra-break-words cuadra-rounded-3xl cuadra-border cuadra-border-border cuadra-px-5 cuadra-py-2.5 font-brand",style:{maxWidth:"calc(42rem * 0.8)",borderRadius:"1.5rem",backgroundColor:"var(--cuadra-muted)",color:"hsl(var(--cuadra-foreground))",paddingLeft:"1.25rem",paddingRight:"1.25rem",paddingTop:"0.625rem",paddingBottom:"0.625rem",wordBreak:"break-word",borderWidth:"1px"},children:p.jsx(ta,{components:{Text:({text:e})=>p.jsx(ri,{content:e||""})}})})]})}function pv({text:e}){const[t,r]=y.useState(!1),n=ae(({message:a})=>{var i;return((i=a==null?void 0:a.status)==null?void 0:i.type)==="running"});return e?n?p.jsx("div",{className:"cuadra-mb-3 cuadra-py-1",children:p.jsx("div",{className:"cuadra-text-sm cuadra-text-muted-foreground cuadra-leading-relaxed font-brand cuadra-animate-text-shimmer",children:e})}):p.jsxs("div",{className:"cuadra-mb-3",children:[p.jsxs("button",{type:"button",onClick:()=>r(!t),className:"cuadra-flex cuadra-items-center cuadra-gap-1.5 cuadra-py-1 cuadra-text-sm cuadra-text-muted-foreground hover:cuadra-text-foreground cuadra-transition-colors font-brand",children:[p.jsx(Cn,{className:`cuadra-h-3.5 cuadra-w-3.5 cuadra-shrink-0 cuadra-transition-transform cuadra-duration-200 ${t?"":"cuadra--rotate-90"}`}),p.jsx("span",{children:"Reasoning"})]}),p.jsx("div",{className:`cuadra-overflow-hidden cuadra-transition-all cuadra-duration-200 cuadra-ease-out ${t?"cuadra-max-h-[2000px] cuadra-opacity-100":"cuadra-max-h-0 cuadra-opacity-0"}`,children:p.jsx("div",{className:"cuadra-pl-5 cuadra-pt-2 cuadra-text-sm cuadra-text-muted-foreground cuadra-leading-relaxed font-brand",children:p.jsx(ri,{content:e})})})]}):null}function mv(){return p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2 cuadra-text-muted-foreground cuadra-text-sm font-brand cuadra-py-2",children:[p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-1",children:[p.jsx("span",{className:"cuadra-inline-block cuadra-w-1.5 cuadra-h-1.5 cuadra-bg-current cuadra-rounded-full cuadra-animate-bounce",style:{animationDelay:"0ms"}}),p.jsx("span",{className:"cuadra-inline-block cuadra-w-1.5 cuadra-h-1.5 cuadra-bg-current cuadra-rounded-full cuadra-animate-bounce",style:{animationDelay:"150ms"}}),p.jsx("span",{className:"cuadra-inline-block cuadra-w-1.5 cuadra-h-1.5 cuadra-bg-current cuadra-rounded-full cuadra-animate-bounce",style:{animationDelay:"300ms"}})]}),p.jsx("span",{children:"Thinking..."})]})}function gv(){const e=ae(({message:s})=>{var o;return((o=s==null?void 0:s.status)==null?void 0:o.type)==="running"}),t=ae(({message:s})=>{const o=s==null?void 0:s.content;return!o||!Array.isArray(o)?!1:o.some(l=>!!(l.type==="text"&&l.text&&l.text.length>0||l.type==="reasoning"&&l.text&&l.text.length>0))}),r=y.useRef(!1),[n,a]=y.useState(null);y.useEffect(()=>{if(e&&t&&!r.current){const s=xt.getCurrentMessageId();s&&(r.current=!0,a(s))}},[e,t]);const i=y.useSyncExternalStore(s=>xt.subscribe(s),()=>{var s,o;if(n){const l=xt.getForMessage(n);return(s=l.sources)!=null&&s.length?l.sources:null}if(e&&t){const l=xt.getCurrentMessageId();if(l){const u=xt.getForMessage(l);return(o=u.sources)!=null&&o.length?u.sources:null}}return null},()=>null);return p.jsx(ea,{className:"cuadra-relative cuadra-grid cuadra-w-full cuadra-grid-cols-[auto_auto_1fr] cuadra-grid-rows-[auto_1fr] cuadra-py-3",children:p.jsxs("div",{className:"cuadra-text-foreground cuadra-col-span-2 cuadra-col-start-2 cuadra-row-start-1 cuadra-my-1.5 cuadra-max-w-[90%] cuadra-break-words cuadra-leading-7 font-brand",style:{maxWidth:"90%",marginTop:"0.375rem",marginBottom:"0.375rem"},children:[p.jsx(ta,{components:{Text:({text:s})=>p.jsx(ri,{content:s||""}),Reasoning:({text:s})=>p.jsx(pv,{text:s||""})}}),e&&!t&&p.jsx(mv,{}),i&&i.length>0&&p.jsx(uv,{sources:i})]})})}const wu=({className:e="",theme:t="system"})=>{const r=()=>{if(typeof window=="undefined")return"light";if(t==="system"){const s=localStorage.getItem("theme");return s||(window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light")}return t},[n,a]=y.useState(r);y.useEffect(()=>{t!=="system"&&a(t)},[t]),y.useEffect(()=>{const s=document.documentElement;s.classList.remove("light","dark"),s.classList.add(n),t==="system"&&localStorage.setItem("theme",n)},[n,t]);const i=()=>{t==="system"&&a(s=>s==="light"?"dark":"light")};return p.jsx("button",{type:"button","aria-label":"Toggle theme",onClick:i,disabled:t!=="system",className:`cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-8 cuadra-w-8 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed ${e}`,children:p.jsx(ju,{className:`cuadra-h-4 cuadra-w-4 cuadra-transition-colors ${n==="dark"?"cuadra-text-primary":"cuadra-text-gray-400"}`})})};function yv({onThreadSelect:e}){var b,w;const t=cs(),r=Gd(_=>_.threadId),[n,a]=y.useState(null),i=(t==null?void 0:t.id)===r,s=n===(t==null?void 0:t.id),[o,l]=y.useState(!1),[u,d]=y.useState((t==null?void 0:t.title)||""),[c,h]=y.useState(!1),[f,g]=y.useState(!1),v=()=>P(null,null,function*(){if(!(t!=null&&t.remoteId)||!u||u===t.title){l(!1);return}try{g(!0);const _=window.__cuadraThreadListAdapter;_&&typeof _.rename=="function"&&(yield _.rename(t.remoteId,u)),l(!1),h(!1)}catch(_){l(!1),h(!1)}finally{g(!1)}});return y.useEffect(()=>{t!=null&&t.title&&!o&&d(t.title)},[t==null?void 0:t.title,o]),t?p.jsxs(ho,{className:`group cuadra-relative cuadra-flex cuadra-items-center cuadra-rounded-lg cuadra-transition-colors cuadra-cursor-pointer cuadra-border cuadra-mb-2 ${i?"cuadra-bg-muted cuadra-border-border":"cuadra-border-transparent hover:cuadra-bg-muted hover:cuadra-border-border"}`,style:{marginBottom:"0.5rem"},onMouseEnter:()=>a(t.id),onMouseLeave:()=>a(null),children:[p.jsx(lp,{className:"cuadra-p-3 cuadra-flex-1 cuadra-flex cuadra-items-center cuadra-min-w-0 cuadra-cursor-pointer",onClick:()=>e==null?void 0:e(),children:p.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-min-w-0 cuadra-flex-1 cuadra-items-start cuadra-text-left",children:o?p.jsx("input",{className:"cuadra-flex cuadra-w-full cuadra-rounded-md cuadra-border cuadra-border-input cuadra-bg-background cuadra-text-foreground cuadra-px-3 cuadra-py-2 cuadra-text-sm placeholder:cuadra-text-muted-foreground focus-visible:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 font-brand",value:u,onChange:_=>d(_.target.value),onKeyDown:_=>{_.key==="Enter"&&v(),_.key==="Escape"&&(l(!1),d(t.title||""))},onBlur:()=>{l(!1),d(t.title||"Chat")},disabled:f,autoFocus:!0,onClick:_=>_.stopPropagation()}):p.jsxs(p.Fragment,{children:[p.jsx("span",{className:"cuadra-text-sm cuadra-font-normal cuadra-text-foreground cuadra-truncate font-brand",children:(((b=t.title)==null?void 0:b.length)||0)>60?`${(w=t.title)==null?void 0:w.slice(0,60)}…`:t.title||"Chat"}),t.updatedAt&&p.jsx("span",{className:"cuadra-text-xs cuadra-text-muted-foreground cuadra-mt-1 font-brand",children:new Date(t.updatedAt).toLocaleDateString()})]})})}),p.jsx("div",{className:"cuadra-mr-2 cuadra-flex-shrink-0 cuadra-w-6 cuadra-h-6 cuadra-flex cuadra-items-center cuadra-justify-center",children:(s||i||c)&&p.jsxs("div",{className:"cuadra-relative",children:[p.jsx("button",{type:"button",className:"cuadra-p-1 cuadra-rounded hover:cuadra-bg-background/50 cuadra-transition-colors",onClick:_=>{_.stopPropagation(),h(!c)},"aria-label":"Thread options",children:p.jsx(Uu,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"})}),c&&p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-40",onClick:()=>h(!1)}),p.jsx("div",{className:"cuadra-absolute cuadra-right-0 cuadra-top-8 cuadra-z-50 cuadra-bg-background cuadra-border cuadra-border-border cuadra-rounded-lg cuadra-shadow-lg cuadra-min-w-[120px] cuadra-overflow-hidden",children:o?p.jsx("button",{type:"button",className:"cuadra-w-full cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left cuadra-text-foreground hover:cuadra-bg-muted cuadra-transition-colors font-brand",onClick:_=>{_.stopPropagation(),v()},disabled:f,children:"Save"}):p.jsxs(p.Fragment,{children:[p.jsx("button",{type:"button",className:"cuadra-w-full cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left cuadra-text-foreground hover:cuadra-bg-muted cuadra-transition-colors font-brand",onClick:_=>{_.stopPropagation(),l(!0),d(t.title||"Chat"),h(!1)},children:"Rename"}),p.jsx("div",{className:"cuadra-border-t cuadra-border-border"}),p.jsx(sp,{asChild:!0,children:p.jsx("button",{type:"button",className:"cuadra-w-full cuadra-px-3 cuadra-py-2 cuadra-text-sm cuadra-text-left cuadra-text-destructive hover:cuadra-bg-muted cuadra-transition-colors font-brand",onClick:_=>{_.stopPropagation(),h(!1)},children:"Delete"})})]})})]})]})})]}):null}function xu({onThreadSelect:e,showThemeToggle:t,theme:r,onLogout:n,safeArea:a=!1,orgName:i,primaryColor:s}){return p.jsxs(co,{className:"!cuadra-border-r cuadra-border-border cuadra-flex cuadra-flex-col cuadra-bg-background cuadra-transition-all cuadra-duration-300 cuadra-ease-in-out cuadra-h-full cuadra-w-80",style:{borderRightWidth:"1px"},children:[p.jsxs("div",{className:"cuadra-border-b cuadra-border-border cuadra-flex cuadra-items-center cuadra-justify-between cuadra-transition-all cuadra-duration-300 cuadra-min-h-16 cuadra-px-4 cuadra-py-4",style:a?{paddingTop:"calc(env(safe-area-inset-top) + 1rem)",paddingLeft:"calc(env(safe-area-inset-left) + 0.5rem)"}:void 0,children:[i?p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2 cuadra-flex-1 cuadra-min-w-0",children:[p.jsx("div",{className:"cuadra-w-8 cuadra-h-8 cuadra-rounded-full cuadra-flex cuadra-items-center cuadra-justify-center cuadra-text-white cuadra-font-bold cuadra-text-sm cuadra-flex-shrink-0",style:{backgroundColor:s||"hsl(var(--primary))"},children:i.charAt(0).toUpperCase()}),p.jsx("span",{className:"cuadra-font-medium cuadra-text-sm cuadra-text-foreground cuadra-truncate font-brand",children:i})]}):p.jsx("div",{className:"cuadra-flex-1"}),p.jsx("button",{type:"button",onClick:e,className:"cuadra-flex md:cuadra-hidden cuadra-items-center cuadra-justify-center cuadra-h-8 cuadra-w-8 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors cuadra-flex-shrink-0","aria-label":"Close",children:p.jsx(In,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-foreground"})})]}),p.jsxs("div",{className:"cuadra-flex-1 cuadra-overflow-y-auto cuadra-p-2 cuadra-pl-4 scrollbar-thin",style:a?{paddingLeft:"calc(env(safe-area-inset-left) + 1rem)"}:void 0,children:[p.jsx(oo,{className:"group cuadra-relative cuadra-flex cuadra-items-center cuadra-gap-3 cuadra-p-3 cuadra-rounded-lg cuadra-cursor-pointer cuadra-transition-colors cuadra-border cuadra-border-transparent hover:cuadra-bg-muted hover:cuadra-border-border",onClick:()=>e==null?void 0:e(),children:p.jsx("div",{className:"cuadra-flex-1 cuadra-min-w-0",children:p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2",children:[p.jsx(Ju,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"}),p.jsx("h4",{className:"cuadra-text-sm cuadra-font-normal cuadra-text-foreground font-brand",children:"New Chat"})]})})}),p.jsx("div",{className:"cuadra-my-2 cuadra-border-t cuadra-border-border"}),p.jsx(uo,{components:{ThreadListItem:o=>p.jsx(yv,E(m({},o),{onThreadSelect:e}))}})]}),(t||n)&&p.jsxs("div",{className:"cuadra-border-t cuadra-border-border cuadra-flex md:cuadra-hidden cuadra-items-center cuadra-justify-between cuadra-px-4 cuadra-py-4",style:a?{paddingBottom:"calc(env(safe-area-inset-bottom) + 0.5rem)",paddingLeft:"calc(env(safe-area-inset-left) + 0.5rem)"}:void 0,children:[n&&p.jsx("button",{type:"button",onClick:n,className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-8 cuadra-w-8 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors","aria-label":"Logout",children:p.jsx(Vu,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-foreground"})}),t&&p.jsx(wu,{theme:r})]})]})}const bv=`
36
36
  @keyframes rotate {
37
37
  100% { transform: rotate(1turn); }
38
38
  }
39
- `,ri=({children:e,className:t="",paddingX:r="px-0",paddingY:n="py-0",borderSizePx:a=4,style:i,contentStyle:s,rotating:o=!1})=>p.jsxs(p.Fragment,{children:[p.jsx("style",{children:yv}),p.jsxs("div",{className:`cuadra-relative cuadra-bg-background md:cuadra-rounded-xl cuadra-overflow-hidden ${t}`,style:m({padding:a},i),children:[p.jsx("div",{className:`cuadra-absolute md:cuadra-rounded-xl cuadra-textured-card-border ${o?"cuadra-textured-card-border-rotating":""}`,style:o?{left:"-100%",top:"-100%",width:"300%",height:"300%",backgroundRepeat:"no-repeat",backgroundSize:"cover",backgroundPosition:"center",animation:"rotate 4s linear infinite"}:{backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",top:"0",left:"0",width:"100%",height:"100%"}}),p.jsx("div",{className:`cuadra-relative cuadra-bg-background cuadra-h-full cuadra-z-10 cuadra-flex cuadra-flex-col cuadra-overflow-hidden ${r} ${n}`,style:m({borderRadius:"calc(0.75rem - 4px)"},s),children:e})]})]}),xu=({currentModel:e,models:t,modelsLoading:r,modelsError:n,onModelChange:a,hideModelSelector:i=!1,showThemeToggle:s=!0,theme:o="system",onMobileMenuClick:l,showMobileMenuButton:u=!1,safeArea:d=!1})=>{const[c,h]=y.useState(!1),[f,g]=y.useState(!1),v=y.useRef(null);y.useEffect(()=>{const T=_=>{v.current&&!v.current.contains(_.target)&&h(!1)};return c&&document.addEventListener("mousedown",T),()=>{document.removeEventListener("mousedown",T)}},[c]);const b=t.find(T=>T.id===e),w=T=>{a(T),h(!1),g(!1)};return p.jsxs("div",{className:`cuadra-min-h-16 cuadra-px-4 cuadra-py-3 cuadra-flex cuadra-items-center cuadra-justify-between cuadra-bg-background ${d?"":"cuadra-border-b cuadra-border-border"}`,style:d?{paddingTop:"calc(env(safe-area-inset-top) + 0.75rem)"}:void 0,children:[p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2",children:[u&&p.jsx("button",{type:"button",onClick:l,className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-10 cuadra-w-10 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed md:cuadra-hidden",style:{backgroundColor:"hsl(var(--muted))"},"aria-label":"Toggle thread list",children:p.jsx(Vu,{className:"cuadra-h-5 cuadra-w-5 cuadra-text-foreground",strokeWidth:1.5})}),s&&p.jsx("div",{className:"cuadra-hidden md:cuadra-flex cuadra-items-center cuadra-gap-2",children:p.jsx(bu,{theme:o})})]}),p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2 md:cuadra-ml-0 cuadra-ml-auto",children:[!i&&p.jsx("label",{className:"cuadra-hidden md:cuadra-inline cuadra-text-sm cuadra-text-muted-foreground cuadra-font-brand",children:"Model"}),i?null:r?p.jsx("div",{className:"cuadra-w-48 cuadra-rounded-md cuadra-border cuadra-border-border cuadra-px-3 cuadra-py-2 cuadra-bg-muted",children:p.jsx("span",{className:"cuadra-text-muted-foreground cuadra-text-sm cuadra-font-brand",children:"Loading..."})}):n?p.jsx("div",{className:"cuadra-w-48 cuadra-rounded-md cuadra-border cuadra-border-destructive cuadra-px-3 cuadra-py-2 cuadra-bg-destructive/10",children:p.jsx("span",{className:"cuadra-text-destructive cuadra-text-sm cuadra-font-brand",children:"Failed to load models"})}):p.jsxs(p.Fragment,{children:[p.jsxs("div",{ref:v,className:"cuadra-hidden md:cuadra-block cuadra-relative cuadra-w-48",children:[p.jsxs("button",{type:"button",onClick:()=>h(!c),disabled:r||t.length===0||!!n,className:"cuadra-flex cuadra-h-10 cuadra-w-full cuadra-items-center cuadra-justify-between cuadra-rounded-md cuadra-border cuadra-border-input cuadra-bg-background cuadra-px-3 cuadra-py-2 cuadra-text-sm placeholder:cuadra-text-muted-foreground focus:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 cuadra-font-brand",children:[p.jsx("span",{className:b?"cuadra-text-foreground":"cuadra-text-muted-foreground",children:(b==null?void 0:b.name)||"Select model"}),p.jsx(Cn,{className:"cuadra-ml-2 cuadra-h-4 cuadra-w-4 cuadra-opacity-50"})]}),c&&t.length>0&&p.jsx("div",{className:"cuadra-absolute cuadra-z-50 cuadra-mt-1 cuadra-w-full cuadra-min-w-[8rem] cuadra-overflow-hidden cuadra-rounded-md glass-popover cuadra-text-popover-foreground cuadra-animate-in fade-in-80 cuadra-border cuadra-border-border cuadra-bg-popover cuadra-shadow-md",children:p.jsx("div",{className:"cuadra-p-1",children:t.map(T=>p.jsxs("button",{type:"button",onClick:()=>w(T.id),className:`cuadra-relative cuadra-flex cuadra-w-full cuadra-cursor-pointer cuadra-select-none cuadra-items-center cuadra-rounded-sm cuadra-py-1.5 cuadra-pl-8 cuadra-pr-2 cuadra-text-sm cuadra-outline-none focus:cuadra-bg-secondary focus:cuadra-text-secondary-foreground font-brand cuadra-transition-colors ${e===T.id?"cuadra-bg-secondary cuadra-text-secondary-foreground":"hover:cuadra-bg-secondary/50"}`,children:[e===T.id&&p.jsx("span",{className:"cuadra-absolute cuadra-left-2 cuadra-flex cuadra-h-3.5 cuadra-w-3.5 cuadra-items-center cuadra-justify-center",children:p.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",fill:"none",viewBox:"0 0 16 16",children:p.jsx("path",{fill:"currentColor",fillRule:"evenodd",d:"M6.47 10.03a.75.75 0 0 1-1.06-1.06l2-2a.75.75 0 0 1 1.06 0l2 2a.75.75 0 1 1-1.06 1.06L8 9.06l-1.53 1.53Z",clipRule:"evenodd"})})}),p.jsx("span",{children:T.name})]},T.id))})})]}),p.jsxs("button",{type:"button",onClick:()=>g(!0),disabled:r||t.length===0||!!n,className:"cuadra-flex md:cuadra-hidden cuadra-h-10 cuadra-items-center cuadra-gap-1 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-px-4 cuadra-py-2 cuadra-text-base cuadra-font-medium focus:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 cuadra-font-brand cuadra-transition-colors",style:{backgroundColor:"hsl(var(--muted))"},children:[p.jsx("span",{className:"cuadra-text-foreground",children:(b==null?void 0:b.name)||"Select model"}),p.jsx(Cn,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"})]}),f&&typeof document!="undefined"&&He.createPortal(p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-bg-black/50 cuadra-z-50 md:cuadra-hidden",onClick:()=>g(!1)}),p.jsxs("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-50 cuadra-flex cuadra-flex-col cuadra-bg-background md:cuadra-hidden",children:[p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-between cuadra-border-b cuadra-border-border cuadra-px-4 cuadra-py-4",style:d?{paddingTop:"calc(env(safe-area-inset-top) + 1rem)"}:void 0,children:[p.jsx("h2",{className:"cuadra-text-lg cuadra-font-normal cuadra-text-foreground font-brand",children:"Select Model"}),p.jsx("button",{type:"button",onClick:()=>g(!1),className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-8 cuadra-w-8 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors","aria-label":"Close",children:p.jsx(In,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-foreground"})})]}),p.jsx("div",{className:"cuadra-flex-1 cuadra-overflow-y-auto cuadra-p-4",children:r?p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-py-8",children:p.jsx("span",{className:"cuadra-text-muted-foreground cuadra-text-sm cuadra-font-brand",children:"Loading models..."})}):n?p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-py-8",children:p.jsx("span",{className:"cuadra-text-destructive cuadra-text-sm cuadra-font-brand",children:"Failed to load models"})}):t.length===0?p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-py-8",children:p.jsx("span",{className:"cuadra-text-muted-foreground cuadra-text-sm cuadra-font-brand",children:"No models available"})}):p.jsx("div",{className:"cuadra-space-y-2",children:t.map(T=>p.jsxs("button",{type:"button",onClick:()=>w(T.id),className:`cuadra-w-full cuadra-flex cuadra-items-center cuadra-justify-between cuadra-rounded-lg cuadra-border cuadra-px-4 cuadra-py-4 cuadra-text-left cuadra-transition-colors font-brand cuadra-bg-background cuadra-text-foreground cuadra-border-border hover:cuadra-bg-muted ${e===T.id?"cuadra-border-primary":""}`,children:[p.jsx("span",{className:"cuadra-text-base cuadra-font-normal",children:T.name}),e===T.id&&p.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",fill:"none",viewBox:"0 0 20 20",className:"cuadra-text-primary",children:p.jsx("path",{fill:"currentColor",fillRule:"evenodd",d:"M16.707 5.293a1 1 0 0 1 0 1.414l-8 8a1 1 0 0 1-1.414 0l-4-4a1 1 0 0 1 1.414-1.414L8 12.586l7.293-7.293a1 1 0 0 1 1.414 0Z",clipRule:"evenodd"})})]},T.id))})})]})]}),document.body)]})]})]})},bv=y.createContext(void 0),ni=({children:e,value:t})=>p.jsx(bv.Provider,{value:t,children:e});function wv(){y.useEffect(()=>{if(document.querySelector("style[data-cuadra-uikit]"))return;const t=document.createElement("div");t.className="cuadra-flex",document.body.appendChild(t);const r=window.getComputedStyle(t).display==="flex";if(document.body.removeChild(t),r)return;const n=document.createElement("link");n.setAttribute("data-cuadra-uikit","true"),n.rel="stylesheet",n.type="text/css";const a=["/node_modules/@cuadra-ai/uikit/dist/uikit.css",new URL("../dist/uikit.css",typeof document=="undefined"&&typeof location=="undefined"?require("url").pathToFileURL(__filename).href:typeof document=="undefined"?location.href:Le&&Le.tagName.toUpperCase()==="SCRIPT"&&Le.src||new URL("cuadra-uikit.umd.js",document.baseURI).href).href];let i=!1;for(const s of a)if(n.href=s,n.onload=()=>{i=!0},n.onerror=()=>{},document.head.appendChild(n),i)break},[])}const vu=y.forwardRef(function({config:t},r){wv();const n=y.useRef(null),a=y.useRef(!1),{baseUrl:i,proxyUrl:s,sessionToken:o,mode:l="multiChat",modelMode:u="fixed",modelId:d,onModelChange:c,ephemeral:h=!1,systemPrompt:f,enableReasoning:g=!1,initialThreadId:v,welcomeTitle:b,welcomeSubtitle:w,extraTopPadding:T,suggestions:_,inputPlaceholder:D,preMadeResponseDelay:z=1e3,streamingSpeed:I=50,showThemeToggle:B=!0,initialMessage:H,initialPreMadeQA:j,theme:S="system",onError:N,onChatCreated:M,onUserMessage:U,onThreadIdUpdate:R,onLogout:F,enableAttachments:Q=!1,onBeforeRequest:ue,mockResponseOnBlocked:pe}=t;y.useImperativeHandle(r,()=>({sendMessage:q=>{var X;(X=n.current)==null||X.sendMessage(q)},sendPreMadeQA:(q,X,ee)=>{var Re;(Re=n.current)==null||Re.sendPreMadeQA(q,X,ee)},clearChat:()=>{var q;(q=n.current)==null||q.clearChat()}}),[]),y.useEffect(()=>{if(a.current)return;const q=setTimeout(()=>{var X,ee;j?(a.current=!0,(X=n.current)==null||X.sendPreMadeQA(j.question,j.answer,{delay:z,streamingSpeed:I})):H&&(a.current=!0,(ee=n.current)==null||ee.sendMessage(H))},500);return()=>clearTimeout(q)},[H,j,z,I]);const[de,x]=y.useState(!1),[se,we]=y.useState(null),[k,xe]=y.useState(null),[Ue,ye]=y.useState(!1),W=y.useRef(null),ie=q=>{if(q<30)return!0;if(W.current){const X=W.current.getBoundingClientRect();if(q-X.left<30)return!0}return!1},be=q=>{const X=window.innerWidth;return q>X-80},ve=q=>{const ee=q.touches[0].clientX;if(de){be(ee)&&(we(ee),xe(ee),ye(!0));return}ie(ee)&&(we(ee),xe(ee),ye(!0))},Me=q=>{if(se===null||!Ue)return;const X=q.touches[0];xe(X.clientX)},he=()=>{if(se===null||k===null){ye(!1),we(null),xe(null);return}const q=k-se,X=Math.abs(q),ee=50;if(X<10){we(null),xe(null),ye(!1);return}q>ee&&!de&&se!==null?ie(se)&&x(!0):q<-ee&&de&&x(!1),we(null),xe(null),ye(!1)},Pe=()=>{if(Ue&&se!==null&&k!==null){const q=k-se;if(de)return`translateX(${Math.min(0,q)}px)`;if(se!==null&&ie(se))return`translateX(${Math.min(0,-320+q)}px)`}return de?"translateX(0)":"translateX(-100%)"},kt=()=>{if(!Ue||se===null||k===null)return de?.5:0;const X=k-se;return de?Math.max(0,Math.min(1,(320+X)/320))*.5:se!==null&&ie(se)?Math.max(0,Math.min(1,(X+320)/320))*.5:0},st=s||i||"",dt=!!s,Dt=y.useMemo(()=>new ho(st,o||void 0,dt),[st,o,dt]),[ke,Qt]=y.useState(null),[St,wn]=y.useState(!1),[Ot,xn]=y.useState(null),[ai,vn]=y.useState(!1);y.useEffect(()=>{l==="multiChat"&&vn(!0)},[l]);const A=y.useCallback(()=>P(null,null,function*(){if(u==="selector"){wn(!0),xn(null);try{const q=yield Dt.listModels();Qt(q)}catch(q){xn(q instanceof Error?q:new Error("Failed to load models"))}finally{wn(!1)}}}),[Dt,u]);y.useEffect(()=>{u==="selector"&&A()},[u,A]),y.useEffect(()=>(typeof window!="undefined"&&(window.__cuadraUIKitRefetchModels=A),()=>{typeof window!="undefined"&&delete window.__cuadraUIKitRefetchModels}),[A]);const[O,Y]=y.useState(u==="fixed"&&d||null),Z=y.useRef(O),ae=y.useCallback(q=>{const X=Z.current;Y(q),Z.current=q,c==null||c(q),X!==null&&X!==q&&l==="multiChat"&&setTimeout(()=>{var Re,Eu;const ee=window.__cuadraThreadListRuntime;if((Re=ee==null?void 0:ee.threads)!=null&&Re.switchToNewThread)try{ee.threads.switchToNewThread()}catch(Au){}else if((Eu=ee==null?void 0:ee.threads)!=null&&Eu.createThread)try{ee.threads.createThread()}catch(Au){}else if(ee!=null&&ee.switchToNewThread)try{ee.switchToNewThread()}catch(Au){}},100)},[c,l]);y.useEffect(()=>{if(u==="selector"&&(ke!=null&&ke.items)&&ke.items.length>0&&!O){const q=ke.items[0];if(q!=null&&q.id){const X=q.id;Y(X),c==null||c(X)}}},[u,ke==null?void 0:ke.items,O,c]);const Je=u==="fixed"?!!d:!!O,Ze=y.useMemo(()=>((ke==null?void 0:ke.items)||[]).filter(q=>(q==null?void 0:q.id)&&(q==null?void 0:q.displayName)).map(q=>({id:q.id,name:q.displayName})),[ke]),Ye=y.useMemo(()=>({currentModelId:O||"",models:Ze,modelsLoading:St,modelsError:Ot,onModelChange:ae,refetchModels:A}),[O,Ze,St,Ot,ae,A]);return u==="selector"&&St||l==="multiChat"&&ai?p.jsx(ni,{value:Ye,children:p.jsx(ri,{className:"cuadra-h-full",paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",borderSizePx:t.borderless?0:4,children:p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full",children:p.jsx(ui,{className:"cuadra-h-6 cuadra-w-6 cuadra-animate-spin cuadra-text-muted-foreground"})})})}):u==="selector"&&!Je&&Ot?p.jsx(ni,{value:Ye,children:p.jsx(ri,{className:"cuadra-h-full",paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",children:p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full",children:p.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-2",children:p.jsx("p",{className:"cuadra-text-sm cuadra-text-destructive font-brand",children:"Failed to load models"})})})})}):p.jsx("div",{className:"cuadra-uikit cuadra-h-full cuadra-w-full",style:{height:"100%",width:"100%"},children:p.jsx(ni,{value:Ye,children:p.jsx(xp,{baseUrl:dt?st:i||st,sessionToken:o,isProxyMode:dt,mode:l,modelMode:u,modelId:O||d||void 0,onModelChange:ae,ephemeral:h,systemPrompt:f,enableReasoning:g,initialThreadId:v,enableAttachments:Q,onError:N,onChatCreated:M,onUserMessage:U,onThreadIdUpdate:R,onBeforeRequest:ue,mockResponseOnBlocked:pe,onChatsLoaded:()=>{l==="multiChat"&&vn(!1)},children:p.jsx(ri,{paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",className:`cuadra-h-full ${t.containerClass||""}`,borderSizePx:t.borderless?0:4,style:{height:"100%"},children:p.jsx("div",{className:"cuadra-h-full cuadra-flex cuadra-relative",style:{height:"100%"},onTouchStart:ve,onTouchMove:Me,onTouchEnd:he,children:l==="multiChat"?p.jsxs(p.Fragment,{children:[typeof document!="undefined"&&He.createPortal(p.jsx("div",{className:`cuadra-fixed cuadra-inset-0 cuadra-bg-black cuadra-z-40 md:cuadra-hidden cuadra-transition-opacity cuadra-duration-300 ${de||Ue?"":"cuadra-pointer-events-none"}`,style:{opacity:kt()},onClick:()=>x(!1)}),document.body),typeof document!="undefined"&&p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-hidden md:cuadra-block !cuadra-border-r cuadra-border-border cuadra-flex cuadra-flex-col cuadra-bg-background cuadra-transition-all cuadra-duration-300 cuadra-ease-in-out cuadra-h-full cuadra-w-80 cuadra-relative",style:{borderRightWidth:"1px",height:"100%"},children:p.jsx(wu,{onThreadSelect:()=>x(!1),showThemeToggle:B,theme:S,onLogout:F,safeArea:t.safeArea,orgName:t.orgName,primaryColor:t.primaryColor})}),typeof document!="undefined"&&He.createPortal(p.jsx("div",{className:`cuadra-block md:cuadra-hidden !cuadra-border-r cuadra-border-border cuadra-flex cuadra-flex-col cuadra-bg-background cuadra-h-screen cuadra-w-80 cuadra-fixed cuadra-z-50 cuadra-top-0 cuadra-left-0 ${de||Ue?"":"cuadra-pointer-events-none"}`,style:{borderRightWidth:"1px",transform:Pe(),transition:Ue?"none":"transform 0.3s ease-in-out"},children:p.jsx(wu,{onThreadSelect:()=>x(!1),showThemeToggle:B,theme:S,onLogout:F,safeArea:t.safeArea,orgName:t.orgName,primaryColor:t.primaryColor})}),document.body)]}),p.jsxs("div",{ref:W,className:"cuadra-flex-1 cuadra-flex cuadra-flex-col",children:[u==="selector"&&p.jsx(xu,{currentModel:O||"",models:Ze,modelsLoading:St,modelsError:Ot,onModelChange:ae,showThemeToggle:B,theme:S,onMobileMenuClick:()=>x(!de),showMobileMenuButton:l==="multiChat",safeArea:t.safeArea}),p.jsx("div",{className:"cuadra-flex-1 cuadra-relative cuadra-min-h-0 cuadra-space-y-4 cuadra-p-4",children:p.jsx(yu,{ref:n,welcomeTitle:b,welcomeSubtitle:w,extraTopPadding:T,suggestions:_,inputPlaceholder:D,enableAttachments:Q,preMadeResponseDelay:z,streamingSpeed:I,safeArea:t.safeArea})})]})]}):p.jsxs("div",{className:"cuadra-flex-1 cuadra-flex cuadra-flex-col",children:[u==="selector"&&p.jsx(xu,{currentModel:O||"",models:Ze,modelsLoading:St,modelsError:Ot,onModelChange:ae,showThemeToggle:B,theme:S,safeArea:t.safeArea}),p.jsx("div",{className:"cuadra-flex-1 cuadra-relative cuadra-min-h-0 cuadra-space-y-4 cuadra-p-4",children:p.jsx(yu,{ref:n,welcomeTitle:b,welcomeSubtitle:w,extraTopPadding:T,suggestions:_,inputPlaceholder:D,preMadeResponseDelay:z,streamingSpeed:I,safeArea:t.safeArea})})]})})})})})})});class bn{constructor(){C(this,"config",null);C(this,"root",null);C(this,"container",null);C(this,"instances",new Map)}init(t){if(!t.baseUrl&&!t.proxyUrl)throw new Error("Either baseUrl or proxyUrl is required");if(t.modelMode==="fixed"&&t.modelId!==void 0&&(!t.modelId||t.modelId.trim()===""))throw new Error("modelId cannot be empty when explicitly provided. Omit modelId to let backend resolve it.");const r=t.containerId||"cuadra-chat";let n=document.getElementById(r);n||(n=document.createElement("div"),n.id=r,document.body.appendChild(n)),t.containerClass&&n.classList.add(...t.containerClass.split(" ")),this.config=E(m({},t),{containerId:r}),this.container=n,this.root=me.createRoot(n),this.root.render(y.createElement(ku,{config:this.config})),this.instances.set(r,this)}destroy(t){var a;const r=t||((a=this.config)==null?void 0:a.containerId);if(!r)return;const n=this.instances.get(r);n!=null&&n.root&&(n.root.unmount(),n.root=null),n!=null&&n.container&&n.container.parentNode&&n.container.parentNode.removeChild(n.container),this.instances.delete(r)}updateConfig(t,r){var s;const n=r||((s=this.config)==null?void 0:s.containerId);if(!n)return;const a=this.instances.get(n);if(!(a!=null&&a.config))return;const i=m(m({},a.config),t);a.config=i,a.root&&a.container&&a.root.render(y.createElement(ku,{config:i}))}getInstance(t){var n;const r=t||((n=this.config)==null?void 0:n.containerId);return r&&this.instances.get(r)||null}static parseConfigFromAttributes(t,r){const n={};return t.dataset.baseUrl&&(n.baseUrl=t.dataset.baseUrl),t.dataset.proxyUrl&&(n.proxyUrl=t.dataset.proxyUrl),t.dataset.sessionToken&&(n.sessionToken=t.dataset.sessionToken),t.dataset.containerId&&(n.containerId=t.dataset.containerId),t.dataset.containerClass&&(n.containerClass=t.dataset.containerClass),t.dataset.mode&&(n.mode=t.dataset.mode),t.dataset.modelMode&&(n.modelMode=t.dataset.modelMode),t.dataset.modelId&&(n.modelId=t.dataset.modelId),t.dataset.ephemeral&&(n.ephemeral=t.dataset.ephemeral==="true"),t.dataset.systemPrompt&&(n.systemPrompt=t.dataset.systemPrompt),r&&(r.dataset.baseUrl&&(n.baseUrl=r.dataset.baseUrl),r.dataset.proxyUrl&&(n.proxyUrl=r.dataset.proxyUrl),r.dataset.sessionToken&&(n.sessionToken=r.dataset.sessionToken),r.dataset.mode&&(n.mode=r.dataset.mode),r.dataset.modelMode&&(n.modelMode=r.dataset.modelMode),r.dataset.modelId&&(n.modelId=r.dataset.modelId)),n}}const ku=({config:e})=>p.jsx(vu,{config:e});let ze=null;typeof window!="undefined"&&(ze=new bn);const Su={init:e=>(ze||(ze=new bn),ze.init(e)),destroy:e=>ze==null?void 0:ze.destroy(e),updateConfig:(e,t)=>ze==null?void 0:ze.updateConfig(e,t),getInstance:e=>ze==null?void 0:ze.getInstance(e),refetchModels:()=>{if(typeof window!="undefined"){const e=window.__cuadraUIKitRefetchModels;e&&e()}},version:"0.1.0"};if(typeof window!="undefined"){window.CuadraUIKit=Su;const e=()=>{const t=document.querySelectorAll('script[src*="cuadra-uikit"]'),r=Array.from(t).find(n=>(n.getAttribute("src")||"").includes("cuadra-uikit.umd.js"));r&&r.dataset.autoInit!=="false"&&xv(r)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e):setTimeout(e,0)}function xv(e){if(!e||!ze)return;const t=bn.parseConfigFromAttributes(e),r=t.containerId||"cuadra-chat",n=document.getElementById(r);if(n){const a=bn.parseConfigFromAttributes(e,n);Object.assign(t,a)}(t.baseUrl||t.proxyUrl)&&ze.init(t)}$.WidgetContent=vu,$.default=Su,Object.defineProperties($,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
39
+ `,ni=({children:e,className:t="",paddingX:r="px-0",paddingY:n="py-0",borderSizePx:a=4,style:i,contentStyle:s,rotating:o=!1})=>p.jsxs(p.Fragment,{children:[p.jsx("style",{children:bv}),p.jsxs("div",{className:`cuadra-relative cuadra-bg-background md:cuadra-rounded-xl cuadra-overflow-hidden ${t}`,style:m({padding:a},i),children:[p.jsx("div",{className:`cuadra-absolute md:cuadra-rounded-xl cuadra-textured-card-border ${o?"cuadra-textured-card-border-rotating":""}`,style:o?{left:"-100%",top:"-100%",width:"300%",height:"300%",backgroundRepeat:"no-repeat",backgroundSize:"cover",backgroundPosition:"center",animation:"rotate 4s linear infinite"}:{backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",top:"0",left:"0",width:"100%",height:"100%"}}),p.jsx("div",{className:`cuadra-relative cuadra-bg-background cuadra-h-full cuadra-z-10 cuadra-flex cuadra-flex-col cuadra-overflow-hidden ${r} ${n}`,style:m({borderRadius:"calc(0.75rem - 4px)"},s),children:e})]})]}),vu=({currentModel:e,models:t,modelsLoading:r,modelsError:n,onModelChange:a,hideModelSelector:i=!1,showThemeToggle:s=!0,theme:o="system",onMobileMenuClick:l,showMobileMenuButton:u=!1,safeArea:d=!1})=>{const[c,h]=y.useState(!1),[f,g]=y.useState(!1),v=y.useRef(null);y.useEffect(()=>{const _=T=>{v.current&&!v.current.contains(T.target)&&h(!1)};return c&&document.addEventListener("mousedown",_),()=>{document.removeEventListener("mousedown",_)}},[c]);const b=t.find(_=>_.id===e),w=_=>{a(_),h(!1),g(!1)};return p.jsxs("div",{className:`cuadra-min-h-16 cuadra-px-4 cuadra-py-3 cuadra-flex cuadra-items-center cuadra-justify-between cuadra-bg-background ${d?"":"cuadra-border-b cuadra-border-border"}`,style:d?{paddingTop:"calc(env(safe-area-inset-top) + 0.75rem)"}:void 0,children:[p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2",children:[u&&p.jsx("button",{type:"button",onClick:l,className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-10 cuadra-w-10 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors disabled:cuadra-opacity-50 disabled:cuadra-cursor-not-allowed md:cuadra-hidden",style:{backgroundColor:"hsl(var(--muted))"},"aria-label":"Toggle thread list",children:p.jsx(Wu,{className:"cuadra-h-5 cuadra-w-5 cuadra-text-foreground",strokeWidth:1.5})}),s&&p.jsx("div",{className:"cuadra-hidden md:cuadra-flex cuadra-items-center cuadra-gap-2",children:p.jsx(wu,{theme:o})})]}),p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-gap-2 md:cuadra-ml-0 cuadra-ml-auto",children:[!i&&p.jsx("label",{className:"cuadra-hidden md:cuadra-inline cuadra-text-sm cuadra-text-muted-foreground cuadra-font-brand",children:"Model"}),i?null:r?p.jsx("div",{className:"cuadra-w-48 cuadra-rounded-md cuadra-border cuadra-border-border cuadra-px-3 cuadra-py-2 cuadra-bg-muted",children:p.jsx("span",{className:"cuadra-text-muted-foreground cuadra-text-sm cuadra-font-brand",children:"Loading..."})}):n?p.jsx("div",{className:"cuadra-w-48 cuadra-rounded-md cuadra-border cuadra-border-destructive cuadra-px-3 cuadra-py-2 cuadra-bg-destructive/10",children:p.jsx("span",{className:"cuadra-text-destructive cuadra-text-sm cuadra-font-brand",children:"Failed to load models"})}):p.jsxs(p.Fragment,{children:[p.jsxs("div",{ref:v,className:"cuadra-hidden md:cuadra-block cuadra-relative cuadra-w-48",children:[p.jsxs("button",{type:"button",onClick:()=>h(!c),disabled:r||t.length===0||!!n,className:"cuadra-flex cuadra-h-10 cuadra-w-full cuadra-items-center cuadra-justify-between cuadra-rounded-md cuadra-border cuadra-border-input cuadra-bg-background cuadra-px-3 cuadra-py-2 cuadra-text-sm placeholder:cuadra-text-muted-foreground focus:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 cuadra-font-brand",children:[p.jsx("span",{className:b?"cuadra-text-foreground":"cuadra-text-muted-foreground",children:(b==null?void 0:b.name)||"Select model"}),p.jsx(Cn,{className:"cuadra-ml-2 cuadra-h-4 cuadra-w-4 cuadra-opacity-50"})]}),c&&t.length>0&&p.jsx("div",{className:"cuadra-absolute cuadra-z-50 cuadra-mt-1 cuadra-w-full cuadra-min-w-[8rem] cuadra-overflow-hidden cuadra-rounded-md glass-popover cuadra-text-popover-foreground cuadra-animate-in fade-in-80 cuadra-border cuadra-border-border cuadra-bg-popover cuadra-shadow-md",children:p.jsx("div",{className:"cuadra-p-1",children:t.map(_=>p.jsxs("button",{type:"button",onClick:()=>w(_.id),className:`cuadra-relative cuadra-flex cuadra-w-full cuadra-cursor-pointer cuadra-select-none cuadra-items-center cuadra-rounded-sm cuadra-py-1.5 cuadra-pl-8 cuadra-pr-2 cuadra-text-sm cuadra-outline-none focus:cuadra-bg-secondary focus:cuadra-text-secondary-foreground font-brand cuadra-transition-colors ${e===_.id?"cuadra-bg-secondary cuadra-text-secondary-foreground":"hover:cuadra-bg-secondary/50"}`,children:[e===_.id&&p.jsx("span",{className:"cuadra-absolute cuadra-left-2 cuadra-flex cuadra-h-3.5 cuadra-w-3.5 cuadra-items-center cuadra-justify-center",children:p.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",fill:"none",viewBox:"0 0 16 16",children:p.jsx("path",{fill:"currentColor",fillRule:"evenodd",d:"M6.47 10.03a.75.75 0 0 1-1.06-1.06l2-2a.75.75 0 0 1 1.06 0l2 2a.75.75 0 1 1-1.06 1.06L8 9.06l-1.53 1.53Z",clipRule:"evenodd"})})}),p.jsx("span",{children:_.name})]},_.id))})})]}),p.jsxs("button",{type:"button",onClick:()=>g(!0),disabled:r||t.length===0||!!n,className:"cuadra-flex md:cuadra-hidden cuadra-h-10 cuadra-items-center cuadra-gap-1 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-px-4 cuadra-py-2 cuadra-text-base cuadra-font-medium focus:cuadra-outline-none disabled:cuadra-cursor-not-allowed disabled:cuadra-opacity-50 cuadra-font-brand cuadra-transition-colors",style:{backgroundColor:"hsl(var(--muted))"},children:[p.jsx("span",{className:"cuadra-text-foreground",children:(b==null?void 0:b.name)||"Select model"}),p.jsx(Cn,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-muted-foreground"})]}),f&&typeof document!="undefined"&&He.createPortal(p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-bg-black/50 cuadra-z-50 md:cuadra-hidden",onClick:()=>g(!1)}),p.jsxs("div",{className:"cuadra-fixed cuadra-inset-0 cuadra-z-50 cuadra-flex cuadra-flex-col cuadra-bg-background md:cuadra-hidden",children:[p.jsxs("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-between cuadra-border-b cuadra-border-border cuadra-px-4 cuadra-py-4",style:d?{paddingTop:"calc(env(safe-area-inset-top) + 1rem)"}:void 0,children:[p.jsx("h2",{className:"cuadra-text-lg cuadra-font-normal cuadra-text-foreground font-brand",children:"Select Model"}),p.jsx("button",{type:"button",onClick:()=>g(!1),className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-8 cuadra-w-8 cuadra-rounded-full cuadra-bg-muted hover:cuadra-bg-muted/80 cuadra-transition-colors","aria-label":"Close",children:p.jsx(In,{className:"cuadra-h-4 cuadra-w-4 cuadra-text-foreground"})})]}),p.jsx("div",{className:"cuadra-flex-1 cuadra-overflow-y-auto cuadra-p-4",children:r?p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-py-8",children:p.jsx("span",{className:"cuadra-text-muted-foreground cuadra-text-sm cuadra-font-brand",children:"Loading models..."})}):n?p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-py-8",children:p.jsx("span",{className:"cuadra-text-destructive cuadra-text-sm cuadra-font-brand",children:"Failed to load models"})}):t.length===0?p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-py-8",children:p.jsx("span",{className:"cuadra-text-muted-foreground cuadra-text-sm cuadra-font-brand",children:"No models available"})}):p.jsx("div",{className:"cuadra-space-y-2",children:t.map(_=>p.jsxs("button",{type:"button",onClick:()=>w(_.id),className:`cuadra-w-full cuadra-flex cuadra-items-center cuadra-justify-between cuadra-rounded-lg cuadra-border cuadra-px-4 cuadra-py-4 cuadra-text-left cuadra-transition-colors font-brand cuadra-bg-background cuadra-text-foreground cuadra-border-border hover:cuadra-bg-muted ${e===_.id?"cuadra-border-primary":""}`,children:[p.jsx("span",{className:"cuadra-text-base cuadra-font-normal",children:_.name}),e===_.id&&p.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",fill:"none",viewBox:"0 0 20 20",className:"cuadra-text-primary",children:p.jsx("path",{fill:"currentColor",fillRule:"evenodd",d:"M16.707 5.293a1 1 0 0 1 0 1.414l-8 8a1 1 0 0 1-1.414 0l-4-4a1 1 0 0 1 1.414-1.414L8 12.586l7.293-7.293a1 1 0 0 1 1.414 0Z",clipRule:"evenodd"})})]},_.id))})})]})]}),document.body)]})]})]})},wv=y.createContext(void 0),ai=({children:e,value:t})=>p.jsx(wv.Provider,{value:t,children:e});function xv(){y.useEffect(()=>{if(document.querySelector("style[data-cuadra-uikit]"))return;const t=document.createElement("div");t.className="cuadra-flex",document.body.appendChild(t);const r=window.getComputedStyle(t).display==="flex";if(document.body.removeChild(t),r)return;const n=document.createElement("link");n.setAttribute("data-cuadra-uikit","true"),n.rel="stylesheet",n.type="text/css";const a=["/node_modules/@cuadra-ai/uikit/dist/uikit.css",new URL("../dist/uikit.css",typeof document=="undefined"&&typeof location=="undefined"?require("url").pathToFileURL(__filename).href:typeof document=="undefined"?location.href:Le&&Le.tagName.toUpperCase()==="SCRIPT"&&Le.src||new URL("cuadra-uikit.umd.js",document.baseURI).href).href];let i=!1;for(const s of a)if(n.href=s,n.onload=()=>{i=!0},n.onerror=()=>{},document.head.appendChild(n),i)break},[])}const ku=y.forwardRef(function({config:t},r){xv();const n=y.useRef(null),a=y.useRef(!1),{baseUrl:i,proxyUrl:s,sessionToken:o,mode:l="multiChat",modelMode:u="fixed",modelId:d,onModelChange:c,ephemeral:h=!1,systemPrompt:f,enableReasoning:g=!1,initialThreadId:v,welcomeTitle:b,welcomeSubtitle:w,extraTopPadding:_,suggestions:T,inputPlaceholder:B,preMadeResponseDelay:j=1e3,streamingSpeed:I=50,showThemeToggle:z=!0,initialMessage:H,initialPreMadeQA:O,theme:S="system",onError:N,onChatCreated:M,onUserMessage:W,onThreadIdUpdate:R,onLogout:F,enableAttachments:Q=!1,onBeforeRequest:se,mockResponseOnBlocked:Ce}=t;y.useImperativeHandle(r,()=>({sendMessage:q=>{var X;(X=n.current)==null||X.sendMessage(q)},sendPreMadeQA:(q,X,te)=>{var Re;(Re=n.current)==null||Re.sendPreMadeQA(q,X,te)},clearChat:()=>{var q;(q=n.current)==null||q.clearChat()}}),[]),y.useEffect(()=>{if(a.current)return;const q=setTimeout(()=>{var X,te;O?(a.current=!0,(X=n.current)==null||X.sendPreMadeQA(O.question,O.answer,{delay:j,streamingSpeed:I})):H&&(a.current=!0,(te=n.current)==null||te.sendMessage(H))},500);return()=>clearTimeout(q)},[H,O,j,I]);const[he,x]=y.useState(!1),[le,we]=y.useState(null),[k,xe]=y.useState(null),[Ue,ye]=y.useState(!1),$=y.useRef(null),Z=q=>{if(q<30)return!0;if($.current){const X=$.current.getBoundingClientRect();if(q-X.left<30)return!0}return!1},fe=q=>{const X=window.innerWidth;return q>X-80},be=q=>{const te=q.touches[0].clientX;if(he){fe(te)&&(we(te),xe(te),ye(!0));return}Z(te)&&(we(te),xe(te),ye(!0))},Ne=q=>{if(le===null||!Ue)return;const X=q.touches[0];xe(X.clientX)},ne=()=>{if(le===null||k===null){ye(!1),we(null),xe(null);return}const q=k-le,X=Math.abs(q),te=50;if(X<10){we(null),xe(null),ye(!1);return}q>te&&!he&&le!==null?Z(le)&&x(!0):q<-te&&he&&x(!1),we(null),xe(null),ye(!1)},ve=()=>{if(Ue&&le!==null&&k!==null){const q=k-le;if(he)return`translateX(${Math.min(0,q)}px)`;if(le!==null&&Z(le))return`translateX(${Math.min(0,-320+q)}px)`}return he?"translateX(0)":"translateX(-100%)"},dt=()=>{if(!Ue||le===null||k===null)return he?.5:0;const X=k-le;return he?Math.max(0,Math.min(1,(320+X)/320))*.5:le!==null&&Z(le)?Math.max(0,Math.min(1,(X+320)/320))*.5:0},Je=s||i||"",ht=!!s,Dt=y.useMemo(()=>new fo(Je,o||void 0,ht),[Je,o,ht]),[ke,Qt]=y.useState(null),[St,wn]=y.useState(!1),[Ot,xn]=y.useState(null),[ii,vn]=y.useState(!1);y.useEffect(()=>{l==="multiChat"&&vn(!0)},[l]);const A=y.useCallback(()=>P(null,null,function*(){if(u==="selector"){wn(!0),xn(null);try{const q=yield Dt.listModels();Qt(q)}catch(q){xn(q instanceof Error?q:new Error("Failed to load models"))}finally{wn(!1)}}}),[Dt,u]);y.useEffect(()=>{u==="selector"&&A()},[u,A]),y.useEffect(()=>(typeof window!="undefined"&&(window.__cuadraUIKitRefetchModels=A),()=>{typeof window!="undefined"&&delete window.__cuadraUIKitRefetchModels}),[A]);const[D,Y]=y.useState(u==="fixed"&&d||null),ee=y.useRef(D),oe=y.useCallback(q=>{const X=ee.current;Y(q),ee.current=q,c==null||c(q),X!==null&&X!==q&&l==="multiChat"&&setTimeout(()=>{var Re,Au;const te=window.__cuadraThreadListRuntime;if((Re=te==null?void 0:te.threads)!=null&&Re.switchToNewThread)try{te.threads.switchToNewThread()}catch(Mu){}else if((Au=te==null?void 0:te.threads)!=null&&Au.createThread)try{te.threads.createThread()}catch(Mu){}else if(te!=null&&te.switchToNewThread)try{te.switchToNewThread()}catch(Mu){}},100)},[c,l]);y.useEffect(()=>{if(u==="selector"&&(ke!=null&&ke.items)&&ke.items.length>0&&!D){const q=ke.items[0];if(q!=null&&q.id){const X=q.id;Y(X),c==null||c(X)}}},[u,ke==null?void 0:ke.items,D,c]);const Ye=u==="fixed"?!!d:!!D,et=y.useMemo(()=>((ke==null?void 0:ke.items)||[]).filter(q=>(q==null?void 0:q.id)&&(q==null?void 0:q.displayName)).map(q=>({id:q.id,name:q.displayName})),[ke]),Ke=y.useMemo(()=>({currentModelId:D||"",models:et,modelsLoading:St,modelsError:Ot,onModelChange:oe,refetchModels:A}),[D,et,St,Ot,oe,A]);return u==="selector"&&St||l==="multiChat"&&ii?p.jsx(ai,{value:Ke,children:p.jsx(ni,{className:"cuadra-h-full",paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",borderSizePx:t.borderless?0:4,children:p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full",children:p.jsx(ci,{className:"cuadra-h-6 cuadra-w-6 cuadra-animate-spin cuadra-text-muted-foreground"})})})}):u==="selector"&&!Ye&&Ot?p.jsx(ai,{value:Ke,children:p.jsx(ni,{className:"cuadra-h-full",paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",children:p.jsx("div",{className:"cuadra-flex cuadra-items-center cuadra-justify-center cuadra-h-full",children:p.jsx("div",{className:"cuadra-flex cuadra-flex-col cuadra-items-center cuadra-gap-2",children:p.jsx("p",{className:"cuadra-text-sm cuadra-text-destructive font-brand",children:"Failed to load models"})})})})}):p.jsx("div",{className:"cuadra-uikit cuadra-h-full cuadra-w-full",style:{height:"100%",width:"100%"},children:p.jsx(ai,{value:Ke,children:p.jsx(vp,{baseUrl:ht?Je:i||Je,sessionToken:o,isProxyMode:ht,mode:l,modelMode:u,modelId:D||d||void 0,onModelChange:oe,ephemeral:h,systemPrompt:f,enableReasoning:g,initialThreadId:v,enableAttachments:Q,onError:N,onChatCreated:M,onUserMessage:W,onThreadIdUpdate:R,onBeforeRequest:se,mockResponseOnBlocked:Ce,onChatsLoaded:()=>{l==="multiChat"&&vn(!1)},children:p.jsx(ni,{paddingX:"cuadra-px-0",paddingY:"cuadra-py-0",className:`cuadra-h-full ${t.containerClass||""}`,borderSizePx:t.borderless?0:4,style:{height:"100%"},children:p.jsx("div",{className:"cuadra-h-full cuadra-flex cuadra-relative",style:{height:"100%"},onTouchStart:be,onTouchMove:Ne,onTouchEnd:ne,children:l==="multiChat"?p.jsxs(p.Fragment,{children:[typeof document!="undefined"&&He.createPortal(p.jsx("div",{className:`cuadra-fixed cuadra-inset-0 cuadra-bg-black cuadra-z-40 md:cuadra-hidden cuadra-transition-opacity cuadra-duration-300 ${he||Ue?"":"cuadra-pointer-events-none"}`,style:{opacity:dt()},onClick:()=>x(!1)}),document.body),typeof document!="undefined"&&p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"cuadra-hidden md:cuadra-block !cuadra-border-r cuadra-border-border cuadra-flex cuadra-flex-col cuadra-bg-background cuadra-transition-all cuadra-duration-300 cuadra-ease-in-out cuadra-h-full cuadra-w-80 cuadra-relative",style:{borderRightWidth:"1px",height:"100%"},children:p.jsx(xu,{onThreadSelect:()=>x(!1),showThemeToggle:z,theme:S,onLogout:F,safeArea:t.safeArea,orgName:t.orgName,primaryColor:t.primaryColor})}),typeof document!="undefined"&&He.createPortal(p.jsx("div",{className:`cuadra-block md:cuadra-hidden !cuadra-border-r cuadra-border-border cuadra-flex cuadra-flex-col cuadra-bg-background cuadra-h-screen cuadra-w-80 cuadra-fixed cuadra-z-50 cuadra-top-0 cuadra-left-0 ${he||Ue?"":"cuadra-pointer-events-none"}`,style:{borderRightWidth:"1px",transform:ve(),transition:Ue?"none":"transform 0.3s ease-in-out"},children:p.jsx(xu,{onThreadSelect:()=>x(!1),showThemeToggle:z,theme:S,onLogout:F,safeArea:t.safeArea,orgName:t.orgName,primaryColor:t.primaryColor})}),document.body)]}),p.jsxs("div",{ref:$,className:"cuadra-flex-1 cuadra-flex cuadra-flex-col",children:[u==="selector"&&p.jsx(vu,{currentModel:D||"",models:et,modelsLoading:St,modelsError:Ot,onModelChange:oe,showThemeToggle:z,theme:S,onMobileMenuClick:()=>x(!he),showMobileMenuButton:l==="multiChat",safeArea:t.safeArea}),p.jsx("div",{className:"cuadra-flex-1 cuadra-relative cuadra-min-h-0 cuadra-space-y-4 cuadra-p-4",children:p.jsx(bu,{ref:n,welcomeTitle:b,welcomeSubtitle:w,extraTopPadding:_,suggestions:T,inputPlaceholder:B,enableAttachments:Q,preMadeResponseDelay:j,streamingSpeed:I,safeArea:t.safeArea})})]})]}):p.jsxs("div",{className:"cuadra-flex-1 cuadra-flex cuadra-flex-col",children:[u==="selector"&&p.jsx(vu,{currentModel:D||"",models:et,modelsLoading:St,modelsError:Ot,onModelChange:oe,showThemeToggle:z,theme:S,safeArea:t.safeArea}),p.jsx("div",{className:"cuadra-flex-1 cuadra-relative cuadra-min-h-0 cuadra-space-y-4 cuadra-p-4",children:p.jsx(bu,{ref:n,welcomeTitle:b,welcomeSubtitle:w,extraTopPadding:_,suggestions:T,inputPlaceholder:B,preMadeResponseDelay:j,streamingSpeed:I,safeArea:t.safeArea})})]})})})})})})});class bn{constructor(){C(this,"config",null);C(this,"root",null);C(this,"container",null);C(this,"instances",new Map)}init(t){if(!t.baseUrl&&!t.proxyUrl)throw new Error("Either baseUrl or proxyUrl is required");if(t.modelMode==="fixed"&&t.modelId!==void 0&&(!t.modelId||t.modelId.trim()===""))throw new Error("modelId cannot be empty when explicitly provided. Omit modelId to let backend resolve it.");const r=t.containerId||"cuadra-chat";let n=document.getElementById(r);n||(n=document.createElement("div"),n.id=r,document.body.appendChild(n)),t.containerClass&&n.classList.add(...t.containerClass.split(" ")),this.config=E(m({},t),{containerId:r}),this.container=n,this.root=me.createRoot(n),this.root.render(y.createElement(Su,{config:this.config})),this.instances.set(r,this)}destroy(t){var a;const r=t||((a=this.config)==null?void 0:a.containerId);if(!r)return;const n=this.instances.get(r);n!=null&&n.root&&(n.root.unmount(),n.root=null),n!=null&&n.container&&n.container.parentNode&&n.container.parentNode.removeChild(n.container),this.instances.delete(r)}updateConfig(t,r){var s;const n=r||((s=this.config)==null?void 0:s.containerId);if(!n)return;const a=this.instances.get(n);if(!(a!=null&&a.config))return;const i=m(m({},a.config),t);a.config=i,a.root&&a.container&&a.root.render(y.createElement(Su,{config:i}))}getInstance(t){var n;const r=t||((n=this.config)==null?void 0:n.containerId);return r&&this.instances.get(r)||null}static parseConfigFromAttributes(t,r){const n={};return t.dataset.baseUrl&&(n.baseUrl=t.dataset.baseUrl),t.dataset.proxyUrl&&(n.proxyUrl=t.dataset.proxyUrl),t.dataset.sessionToken&&(n.sessionToken=t.dataset.sessionToken),t.dataset.containerId&&(n.containerId=t.dataset.containerId),t.dataset.containerClass&&(n.containerClass=t.dataset.containerClass),t.dataset.mode&&(n.mode=t.dataset.mode),t.dataset.modelMode&&(n.modelMode=t.dataset.modelMode),t.dataset.modelId&&(n.modelId=t.dataset.modelId),t.dataset.ephemeral&&(n.ephemeral=t.dataset.ephemeral==="true"),t.dataset.systemPrompt&&(n.systemPrompt=t.dataset.systemPrompt),r&&(r.dataset.baseUrl&&(n.baseUrl=r.dataset.baseUrl),r.dataset.proxyUrl&&(n.proxyUrl=r.dataset.proxyUrl),r.dataset.sessionToken&&(n.sessionToken=r.dataset.sessionToken),r.dataset.mode&&(n.mode=r.dataset.mode),r.dataset.modelMode&&(n.modelMode=r.dataset.modelMode),r.dataset.modelId&&(n.modelId=r.dataset.modelId)),n}}const Su=({config:e})=>p.jsx(ku,{config:e});let ze=null;typeof window!="undefined"&&(ze=new bn);const _u={init:e=>(ze||(ze=new bn),ze.init(e)),destroy:e=>ze==null?void 0:ze.destroy(e),updateConfig:(e,t)=>ze==null?void 0:ze.updateConfig(e,t),getInstance:e=>ze==null?void 0:ze.getInstance(e),refetchModels:()=>{if(typeof window!="undefined"){const e=window.__cuadraUIKitRefetchModels;e&&e()}},version:"0.1.0"};if(typeof window!="undefined"){window.CuadraUIKit=_u;const e=()=>{const t=document.querySelectorAll('script[src*="cuadra-uikit"]'),r=Array.from(t).find(n=>(n.getAttribute("src")||"").includes("cuadra-uikit.umd.js"));r&&r.dataset.autoInit!=="false"&&vv(r)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e):setTimeout(e,0)}function vv(e){if(!e||!ze)return;const t=bn.parseConfigFromAttributes(e),r=t.containerId||"cuadra-chat",n=document.getElementById(r);if(n){const a=bn.parseConfigFromAttributes(e,n);Object.assign(t,a)}(t.baseUrl||t.proxyUrl)&&ze.init(t)}U.WidgetContent=ku,U.default=_u,Object.defineProperties(U,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
40
40
  //# sourceMappingURL=cuadra-uikit.umd.js.map